FinceptTerminal is a modern finance application offering advanced market analytics, investment research, and economic data tools, designed for interactive exploration and data-driven decision-making in a user-friendly environment.
C++ ai-agentsalgorithmic-tradingbloomberg-terminalcppfinancefinancial-marketsfintechgood-first-issueinvestmentinvestment-researchmachine-learningopensourcepythonqtquantitative-financestock-markettrading
research tab update:
tilakpatel22c1a2338c4c45
diff --git a/.github/workflows/release-production.yml b/.github/workflows/release-production.ymlindex fa1800dab..e89035b7e 100644--- a/.github/workflows/release-production.yml+++ b/.github/workflows/release-production.yml@@ -139,8 +139,10 @@ jobs:fifi- # Copy macOS updater signature files- TAR_GZ_SIG=$(find fincept-terminal-desktop/src-tauri/target/${{ matrix.target }}/release/bundle/macos -name "*.tar.gz.sig" -type f 2>/dev/null | head -1)+ # Copy macOS updater .tar.gz and signature files (required for auto-update)+ TAR_GZ=$(find fincept-terminal-desktop/src-tauri/target/${{ matrix.target }}/release/bundle/macos -name "*.app.tar.gz" -type f 2>/dev/null | head -1)+ TAR_GZ_SIG=$(find fincept-terminal-desktop/src-tauri/target/${{ matrix.target }}/release/bundle/macos -name "*.app.tar.gz.sig" -type f 2>/dev/null | head -1)+ [ -f "$TAR_GZ" ] && cp "$TAR_GZ" "release-artifacts/" && echo "Found macOS tar.gz: $TAR_GZ" || echo "Warning: macOS tar.gz not found"[ -f "$TAR_GZ_SIG" ] && cp "$TAR_GZ_SIG" "release-artifacts/" && echo "Found macOS signature: $TAR_GZ_SIG" || echo "Warning: macOS signature not found"elif [[ "${{ matrix.platform }}" == "ubuntu-22.04" ]]; then@@ -150,8 +152,10 @@ jobs:[ -f "$APPIMAGE" ] && cp "$APPIMAGE" "release-artifacts/FinceptTerminal-v${VERSION}-${SUFFIX}.AppImage" || { echo "Error: AppImage not found"; exit 1; }[ -f "$DEB" ] && cp "$DEB" "release-artifacts/FinceptTerminal-v${VERSION}-${SUFFIX}.deb" || echo "Warning: DEB not found"- # Copy Linux updater signature files- APPIMAGE_TAR_GZ_SIG=$(find fincept-terminal-desktop/src-tauri/target/${{ matrix.target }}/release/bundle/appimage -name "*.tar.gz.sig" -type f 2>/dev/null | head -1)+ # Copy Linux updater .tar.gz and signature files (required for auto-update)+ APPIMAGE_TAR_GZ=$(find fincept-terminal-desktop/src-tauri/target/${{ matrix.target }}/release/bundle/appimage -name "*.AppImage.tar.gz" -type f 2>/dev/null | head -1)+ APPIMAGE_TAR_GZ_SIG=$(find fincept-terminal-desktop/src-tauri/target/${{ matrix.target }}/release/bundle/appimage -name "*.AppImage.tar.gz.sig" -type f 2>/dev/null | head -1)+ [ -f "$APPIMAGE_TAR_GZ" ] && cp "$APPIMAGE_TAR_GZ" "release-artifacts/" && echo "Found Linux tar.gz: $APPIMAGE_TAR_GZ" || echo "Warning: Linux tar.gz not found"[ -f "$APPIMAGE_TAR_GZ_SIG" ] && cp "$APPIMAGE_TAR_GZ_SIG" "release-artifacts/" && echo "Found Linux signature: $APPIMAGE_TAR_GZ_SIG" || echo "Warning: Linux signature not found"elif [[ "${{ matrix.platform }}" == "windows-2022" ]]; then@@ -159,17 +163,18 @@ jobs:MSI=$(find fincept-terminal-desktop/src-tauri/target/${{ matrix.target }}/release/bundle -name "*.msi" -type f 2>/dev/null | head -1)[ -f "$MSI" ] && cp "$MSI" "release-artifacts/FinceptTerminal-v${VERSION}-${SUFFIX}.msi" || { echo "Error: MSI not found"; exit 1; }- # Copy Windows updater signature files+ # Copy Windows updater NSIS files and signatures (required for auto-update)NSIS_ZIP=$(find fincept-terminal-desktop/src-tauri/target/${{ matrix.target }}/release/bundle/nsis -name "*.nsis.zip" -type f 2>/dev/null | head -1)NSIS_ZIP_SIG=$(find fincept-terminal-desktop/src-tauri/target/${{ matrix.target }}/release/bundle/nsis -name "*.nsis.zip.sig" -type f 2>/dev/null | head -1)[ -f "$NSIS_ZIP" ] && cp "$NSIS_ZIP" "release-artifacts/" && echo "Found NSIS zip: $NSIS_ZIP" || echo "Warning: NSIS zip not found"[ -f "$NSIS_ZIP_SIG" ] && cp "$NSIS_ZIP_SIG" "release-artifacts/" && echo "Found Windows signature: $NSIS_ZIP_SIG" || echo "Warning: Windows signature not found"fi- # Copy latest.json (updater manifest) - only one platform needs to generate this+ # Copy platform-specific latest.json (will be merged in create-release job)LATEST_JSON=$(find fincept-terminal-desktop/src-tauri/target/${{ matrix.target }}/release/bundle -name "latest.json" -type f 2>/dev/null | head -1)if [ -f "$LATEST_JSON" ]; then- cp "$LATEST_JSON" "release-artifacts/latest.json"+ # Save with platform suffix to merge later+ cp "$LATEST_JSON" "release-artifacts/latest-${{ matrix.platform }}.json"echo "Found latest.json: $LATEST_JSON"echo "latest.json content:"cat "$LATEST_JSON"@@ -216,28 +221,170 @@ jobs:with:path: all-artifacts+ - name: Setup Python for JSON processing+ uses: actions/setup-python@v5+ with:+ python-version: '3.12'+- name: Organize release filesid: organizerun: |mkdir -p release-files- # Copy installer files- find all-artifacts -type f \( -name "*.dmg" -o -name "*.msi" -o -name "*.AppImage" -o -name "*.deb" -o -name "*.app.tar.gz" \) -exec cp {} release-files/ \;+ VERSION="${{ steps.get_version.outputs.version }}"+ TAG_NAME="${{ github.ref_name }}"+ REPO_URL="https://github.com/${{ github.repository }}"++ echo "=== All downloaded artifacts ==="+ find all-artifacts -type f | sort++ # Copy installer files (user-facing downloads)+ find all-artifacts -type f -name "*.dmg" -exec cp {} release-files/ \;+ find all-artifacts -type f -name "*.msi" -exec cp {} release-files/ \;+ find all-artifacts -type f -name "*.AppImage" -exec cp {} release-files/ \;+ find all-artifacts -type f -name "*.deb" -exec cp {} release-files/ \;- # Copy updater files (signatures and manifest)- find all-artifacts -type f \( -name "latest.json" -o -name "*.tar.gz.sig" -o -name "*.nsis.zip" -o -name "*.nsis.zip.sig" \) -exec cp {} release-files/ \; 2>/dev/null || echo "No updater files found"+ # Copy updater archives (required for auto-update)+ find all-artifacts -type f -name "*.app.tar.gz" -exec cp {} release-files/ \;+ find all-artifacts -type f -name "*.app.tar.gz.sig" -exec cp {} release-files/ \;+ find all-artifacts -type f -name "*.AppImage.tar.gz" -exec cp {} release-files/ \;+ find all-artifacts -type f -name "*.AppImage.tar.gz.sig" -exec cp {} release-files/ \;+ find all-artifacts -type f -name "*.nsis.zip" -exec cp {} release-files/ \;+ find all-artifacts -type f -name "*.nsis.zip.sig" -exec cp {} release-files/ \;- echo "=== Release Files ==="+ echo "=== Release files after copying ==="ls -lh release-files/- # Validate latest.json exists- if [ -f "release-files/latest.json" ]; then- echo "SUCCESS: latest.json found"- echo "latest.json content:"- cat release-files/latest.json- else- echo "WARNING: latest.json not found - auto-updater will not work!"- fi+ # Find all platform-specific latest.json files+ echo "=== Looking for platform-specific latest.json files ==="+ find all-artifacts -type f -name "latest-*.json" -exec echo "Found: {}" \; -exec cat {} \;++ # Create Python script to generate unified latest.json+ cat > generate_latest_json.py << 'PYTHON_SCRIPT'+import json+import os+import glob+import sys+from datetime import datetime, timezone++def main():+ version = os.environ.get('VERSION', '0.0.0')+ tag_name = os.environ.get('TAG_NAME', 'v0.0.0')+ repo_url = os.environ.get('REPO_URL', '')++ # Initialize the merged JSON structure+ merged = {+ "version": version,+ "notes": f"FinceptTerminal {tag_name} - See release notes at {repo_url}/releases/tag/{tag_name}",+ "pub_date": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),+ "platforms": {}+ }++ # Try to merge from platform-specific latest.json files first+ platform_files = glob.glob("all-artifacts/**/latest-*.json", recursive=True)+ print(f"Found {len(platform_files)} platform-specific latest.json files")++ for pf in platform_files:+ print(f"Processing: {pf}")+ try:+ with open(pf, 'r') as f:+ data = json.load(f)+ if 'platforms' in data:+ # Update URLs to point to GitHub releases+ for platform_key, platform_data in data['platforms'].items():+ if 'url' in platform_data:+ # Extract just the filename and create proper GitHub release URL+ filename = os.path.basename(platform_data['url'])+ platform_data['url'] = f"{repo_url}/releases/download/{tag_name}/{filename}"+ merged['platforms'].update(data['platforms'])+ print(f" Added platforms: {list(data['platforms'].keys())}")+ except Exception as e:+ print(f" Error processing {pf}: {e}")++ # If no platforms found from JSON files, generate from artifacts+ if not merged['platforms']:+ print("No platforms found from JSON files, generating from artifacts...")++ # Check for Windows NSIS+ nsis_zips = glob.glob("release-files/*.nsis.zip")+ nsis_sigs = glob.glob("release-files/*.nsis.zip.sig")+ if nsis_zips and nsis_sigs:+ nsis_filename = os.path.basename(nsis_zips[0])+ with open(nsis_sigs[0], 'r') as f:+ signature = f.read().strip()+ merged['platforms']['windows-x86_64'] = {+ "signature": signature,+ "url": f"{repo_url}/releases/download/{tag_name}/{nsis_filename}"+ }+ print(f"Added windows-x86_64 from artifacts")++ # Check for macOS ARM (aarch64)+ macos_arm_tars = [f for f in glob.glob("release-files/*.app.tar.gz") if 'aarch64' in f]+ macos_arm_sigs = [f for f in glob.glob("release-files/*.app.tar.gz.sig") if 'aarch64' in f]+ if macos_arm_tars and macos_arm_sigs:+ tar_filename = os.path.basename(macos_arm_tars[0])+ with open(macos_arm_sigs[0], 'r') as f:+ signature = f.read().strip()+ merged['platforms']['darwin-aarch64'] = {+ "signature": signature,+ "url": f"{repo_url}/releases/download/{tag_name}/{tar_filename}"+ }+ print(f"Added darwin-aarch64 from artifacts")++ # Check for macOS Intel (x86_64)+ macos_x64_tars = [f for f in glob.glob("release-files/*.app.tar.gz") if 'x86_64' in f and 'aarch64' not in f]+ macos_x64_sigs = [f for f in glob.glob("release-files/*.app.tar.gz.sig") if 'x86_64' in f and 'aarch64' not in f]+ if macos_x64_tars and macos_x64_sigs:+ tar_filename = os.path.basename(macos_x64_tars[0])+ with open(macos_x64_sigs[0], 'r') as f:+ signature = f.read().strip()+ merged['platforms']['darwin-x86_64'] = {+ "signature": signature,+ "url": f"{repo_url}/releases/download/{tag_name}/{tar_filename}"+ }+ print(f"Added darwin-x86_64 from artifacts")++ # Check for Linux+ linux_tars = glob.glob("release-files/*.AppImage.tar.gz")+ linux_sigs = glob.glob("release-files/*.AppImage.tar.gz.sig")+ if linux_tars and linux_sigs:+ tar_filename = os.path.basename(linux_tars[0])+ with open(linux_sigs[0], 'r') as f:+ signature = f.read().strip()+ merged['platforms']['linux-x86_64'] = {+ "signature": signature,+ "url": f"{repo_url}/releases/download/{tag_name}/{tar_filename}"+ }+ print(f"Added linux-x86_64 from artifacts")++ # Write the merged JSON+ with open('release-files/latest.json', 'w') as f:+ json.dump(merged, f, indent=2)++ print(f"\n=== Generated latest.json ===")+ print(json.dumps(merged, indent=2))++ # Validate we have at least one platform+ if not merged['platforms']:+ print("ERROR: No platforms found for latest.json!")+ sys.exit(1)++ print(f"\nSuccessfully generated latest.json with {len(merged['platforms'])} platform(s)")+ return 0++if __name__ == "__main__":+ sys.exit(main())+PYTHON_SCRIPT++ # Run the Python script to generate latest.json+ VERSION="${VERSION}" TAG_NAME="${TAG_NAME}" REPO_URL="${REPO_URL}" python3 generate_latest_json.py++ # Validate the generated JSON+ echo "=== Validating generated latest.json ==="+ python3 -c "import json; data = json.load(open('release-files/latest.json')); print(f'Valid JSON with {len(data.get(\"platforms\", {}))} platforms')" || { echo "ERROR: Invalid JSON generated"; exit 1; }++ echo "=== Final Release Files ==="+ ls -lh release-files/file_count=$(find release-files -type f | wc -l)[ "$file_count" -eq 0 ] && { echo "Error: No release files found"; exit 1; }@@ -247,6 +394,9 @@ jobs:ls -1 release-files/ >> $GITHUB_OUTPUTecho "EOF" >> $GITHUB_OUTPUT+ # Cleanup+ rm -f generate_latest_json.py+- name: Check if release existsid: check_releaserun: |diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/financial_analysis_cli.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/financial_analysis_cli.pyindex 89881114c..fa2b80dac 100644--- a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/financial_analysis_cli.py+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/financial_analysis_cli.py@@ -3,7 +3,7 @@Financial Analysis CLI Wrapper==============================Command-line interface for the financial analysis module.-Called by Tauri/Rust via PyO3.+Called by Tauri/Rust via worker pool or subprocess.Usage:python financial_analysis_cli.py <command> [args...]diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/finanicalanalysis/core/data_processor.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/finanicalanalysis/core/data_processor.pyindex 60bb6f445..96ebd977b 100644--- a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/finanicalanalysis/core/data_processor.py+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/finanicalanalysis/core/data_processor.py@@ -435,14 +435,34 @@ class DataProcessor:warnings = []# Balance Sheet Equation: Assets = Liabilities + Equity+ # Only validate if we have complete balance sheet data (all three components present and non-zero)if statements.balance_sheet:assets = statements.balance_sheet.get('total_assets', 0)liabilities = statements.balance_sheet.get('total_liabilities', 0)equity = statements.balance_sheet.get('total_equity', 0)- if abs(assets - (liabilities + equity)) > 0.01: # Allow for rounding- errors.append(- f"Balance sheet doesn't balance: Assets({assets}) != Liabilities({liabilities}) + Equity({equity})")+ # Only enforce balance sheet equation if we have all three values+ has_assets = assets != 0 or 'total_assets' in statements.balance_sheet+ has_liabilities = liabilities != 0 or 'total_liabilities' in statements.balance_sheet+ has_equity = equity != 0 or 'total_equity' in statements.balance_sheet++ if has_assets and has_liabilities and has_equity:+ if abs(assets - (liabilities + equity)) > 0.01: # Allow for rounding+ errors.append(+ f"Balance sheet doesn't balance: Assets({assets}) != Liabilities({liabilities}) + Equity({equity})")+ elif has_equity and (not has_assets or not has_liabilities):+ # Partial data - derive missing values if possible+ if not has_assets and has_liabilities:+ statements.balance_sheet['total_assets'] = liabilities + equity+ warnings.append(f"Derived total_assets from liabilities + equity: {liabilities + equity}")+ elif not has_liabilities and has_assets:+ statements.balance_sheet['total_liabilities'] = assets - equity+ warnings.append(f"Derived total_liabilities from assets - equity: {assets - equity}")+ elif not has_assets and not has_liabilities:+ # Only have equity - estimate assets as equity (conservative, no debt assumption)+ statements.balance_sheet['total_assets'] = equity+ statements.balance_sheet['total_liabilities'] = 0+ warnings.append(f"Incomplete balance sheet data - estimated assets={equity}, liabilities=0")# Cash Flow Statement: Net change should equal ending - beginning cashif statements.cash_flow:diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/agent_loader.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/agent_loader.pyindex 7f93474fe..9ecb15ed0 100644--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/agent_loader.py+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/agent_loader.py@@ -3,18 +3,43 @@ Dynamic Agent Loader - Load agents from configuration at runtimeSimilar to ValueCell's _resolve_local_agent_class_sync pattern.Enables runtime agent discovery and instantiation from JSON configs.++Performance optimizations:+- Uses targeted directory scanning instead of recursive rglob()+- Caches discovered agents to avoid repeated file I/O+- Limits discovery to known agent directories only+- Timeout protection for file operations"""import jsonimport importlibimport importlib.util+import os+import re+import timefrom pathlib import Path-from typing import Dict, Any, Optional, List, Type-from dataclasses import dataclass+from typing import Dict, Any, Optional, List, Type, Set+from dataclasses import dataclass, fieldimport logging+from functools import lru_cachelogger = logging.getLogger(__name__)+# Known agent directories to scan (avoids expensive rglob)+KNOWN_AGENT_DIRS = [+ "TraderInvestorsAgent",+ "hedgeFundAgents",+ "EconomicAgents",+ "GeopoliticsAgents",+ "finagent_core",+]++# Maximum time allowed for discovery (seconds)+DISCOVERY_TIMEOUT = 5.0++# Cache TTL for discovered agents (seconds)+CACHE_TTL = 300 # 5 minutes+@dataclassclass AgentCard:@@ -28,17 +53,11 @@ class AgentCard:category: strversion: str = "1.0.0"provider: str = "local"- capabilities: List[str] = None- config: Dict[str, Any] = None+ capabilities: List[str] = field(default_factory=list)+ config: Dict[str, Any] = field(default_factory=dict)module_path: Optional[str] = Noneclass_name: Optional[str] = None- def __post_init__(self):- if self.capabilities is None:- self.capabilities = []- if self.config is None:- self.config = {}-@classmethoddef from_dict(cls, data: Dict[str, Any]) -> "AgentCard":return cls(@@ -134,69 +153,209 @@ class AgentLoader:Features:- Load agents from JSON config files- - Discover agents from directory structure+ - Discover agents from directory structure (optimized - no rglob)- Dynamic module loading- Agent instantiation with config injection+ - Caching for performance"""def __init__(self, config_dir: Optional[Path] = None, agents_dir: Optional[Path] = None):self.config_dir = config_dir or Path(__file__).parent / "configs"self.agents_dir = agents_dir or Path(__file__).parent.parentself.registry = AgentRegistry()+ self._discovery_cache: Optional[List[AgentCard]] = None+ self._cache_timestamp: float = 0# Ensure directories exist- self.config_dir.mkdir(exist_ok=True)+ if self.config_dir.exists():+ pass # Don't create if not exists - avoid permission errors+ else:+ try:+ self.config_dir.mkdir(exist_ok=True)+ except Exception:+ pass # Ignore if can't createdef discover_agents(self) -> List[AgentCard]:"""Discover all available agents from config files and directory structure.Returns list of discovered agent cards.++ Optimizations:+ - Uses caching to avoid repeated discovery+ - Scans only known agent directories (not recursive rglob)+ - Has timeout protection+ - Skips __pycache__ and other non-agent directories"""+ # Check cache first+ if self._discovery_cache is not None:+ if time.time() - self._cache_timestamp < CACHE_TTL:+ logger.debug(f"Returning {len(self._discovery_cache)} cached agents")+ return self._discovery_cache++ start_time = time.time()discovered = []+ discovered_ids: Set[str] = set()- # 1. Load from JSON config files- for config_file in self.config_dir.glob("*_agent.json"):- try:- card = self._load_agent_config(config_file)- if card:- self.registry.register(card)- discovered.append(card)- except Exception as e:- logger.error(f"Failed to load config {config_file}: {e}")-- # 2. Auto-discover from directory structure- for agent_file in self.agents_dir.rglob("*_agent.py"):- if "__pycache__" in str(agent_file):- continue- try:- card = self._discover_from_file(agent_file)- if card and card.id not in [a.id for a in discovered]:- self.registry.register(card)- discovered.append(card)- except Exception as e:- logger.debug(f"Could not auto-discover {agent_file}: {e}")+ try:+ # 1. Load from JSON config files in config directory (fast)+ discovered.extend(self._load_config_files(discovered_ids))++ # Check timeout+ if time.time() - start_time > DISCOVERY_TIMEOUT:+ logger.warning("Discovery timeout after loading config files")+ return self._finalize_discovery(discovered)++ # 2. Load from known agent directories (targeted, not recursive)+ discovered.extend(self._load_from_known_dirs(discovered_ids, start_time))++ except Exception as e:+ logger.error(f"Discovery error: {e}")++ return self._finalize_discovery(discovered)++ def _finalize_discovery(self, discovered: List[AgentCard]) -> List[AgentCard]:+ """Finalize discovery and update cache"""+ # Register all discovered agents+ for card in discovered:+ self.registry.register(card)++ # Update cache+ self._discovery_cache = discovered+ self._cache_timestamp = time.time()logger.info(f"Discovered {len(discovered)} agents")return discovered+ def _load_config_files(self, discovered_ids: Set[str]) -> List[AgentCard]:+ """Load agents from JSON config files"""+ discovered = []++ if not self.config_dir.exists():+ return discovered++ try:+ # Use os.listdir for faster directory listing+ for filename in os.listdir(self.config_dir):+ if not filename.endswith('_agent.json'):+ continue++ config_file = self.config_dir / filename+ try:+ card = self._load_agent_config(config_file)+ if card and card.id not in discovered_ids:+ discovered.append(card)+ discovered_ids.add(card.id)+ except Exception as e:+ logger.debug(f"Failed to load config {filename}: {e}")+ except Exception as e:+ logger.debug(f"Error listing config dir: {e}")++ return discovered++ def _load_from_known_dirs(self, discovered_ids: Set[str], start_time: float) -> List[AgentCard]:+ """Load agents from known agent directories (targeted scanning)"""+ discovered = []++ for dir_name in KNOWN_AGENT_DIRS:+ # Check timeout+ if time.time() - start_time > DISCOVERY_TIMEOUT:+ logger.warning(f"Discovery timeout at directory: {dir_name}")+ break++ agent_dir = self.agents_dir / dir_name+ if not agent_dir.exists() or not agent_dir.is_dir():+ continue++ # Load from configs subdirectory if exists (JSON configs)+ configs_dir = agent_dir / "configs"+ if configs_dir.exists():+ discovered.extend(self._load_json_configs_from_dir(configs_dir, dir_name, discovered_ids))++ # Scan only top-level Python files (no recursion)+ discovered.extend(self._scan_directory_shallow(agent_dir, dir_name, discovered_ids))++ return discovered++ def _load_json_configs_from_dir(self, configs_dir: Path, category: str, discovered_ids: Set[str]) -> List[AgentCard]:+ """Load agent definitions from JSON config files in a directory"""+ discovered = []++ try:+ for filename in os.listdir(configs_dir):+ if not filename.endswith('.json'):+ continue++ config_file = configs_dir / filename+ try:+ with open(config_file, 'r', encoding='utf-8') as f:+ data = json.load(f)++ # Handle both single agent and multi-agent config files+ agents_data = data.get('agents', [data] if 'id' in data or 'name' in data else [])++ for agent_data in agents_data:+ if not agent_data:+ continue+ agent_data['category'] = agent_data.get('category', category)+ card = AgentCard.from_dict(agent_data)+ if card.id not in discovered_ids:+ discovered.append(card)+ discovered_ids.add(card.id)+ except Exception as e:+ logger.debug(f"Failed to load {filename}: {e}")+ except Exception as e:+ logger.debug(f"Error reading configs dir {configs_dir}: {e}")++ return discovered++ def _scan_directory_shallow(self, agent_dir: Path, category: str, discovered_ids: Set[str]) -> List[AgentCard]:+ """Scan directory for agent Python files (shallow, no recursion)"""+ discovered = []++ try:+ for filename in os.listdir(agent_dir):+ # Only look for *_agent.py files+ if not filename.endswith('_agent.py'):+ continue++ # Skip CLI scripts+ if '_cli' in filename:+ continue++ agent_file = agent_dir / filename+ if not agent_file.is_file():+ continue++ try:+ card = self._discover_from_file(agent_file, category)+ if card and card.id not in discovered_ids:+ discovered.append(card)+ discovered_ids.add(card.id)+ except Exception as e:+ logger.debug(f"Could not discover {filename}: {e}")+ except Exception as e:+ logger.debug(f"Error scanning {agent_dir}: {e}")++ return discovered+def _load_agent_config(self, config_file: Path) -> Optional[AgentCard]:"""Load agent card from JSON config file"""- with open(config_file, 'r', encoding='utf-8') as f:- data = json.load(f)- return AgentCard.from_dict(data)+ try:+ with open(config_file, 'r', encoding='utf-8') as f:+ data = json.load(f)+ return AgentCard.from_dict(data)+ except Exception as e:+ logger.debug(f"Error loading config {config_file}: {e}")+ return None- def _discover_from_file(self, agent_file: Path) -> Optional[AgentCard]:+ def _discover_from_file(self, agent_file: Path, category: str = "general") -> Optional[AgentCard]:"""Auto-discover agent from Python file structure"""# Extract agent name from filenamename = agent_file.stem.replace("_agent", "").replace("_", " ").title()agent_id = agent_file.stem- # Determine category from path- parts = agent_file.relative_to(self.agents_dir).parts- category = parts[0] if len(parts) > 1 else "general"-- # Find class name in file- class_name = self._find_agent_class(agent_file)+ # Find class name in file (with size limit to avoid reading huge files)+ class_name = self._find_agent_class_fast(agent_file)if not class_name:return None@@ -209,12 +368,17 @@ class AgentLoader:class_name=class_name)- def _find_agent_class(self, agent_file: Path) -> Optional[str]:- """Find the main agent class in a Python file"""+ def _find_agent_class_fast(self, agent_file: Path, max_bytes: int = 8192) -> Optional[str]:+ """+ Find the main agent class in a Python file.+ Only reads first max_bytes to avoid slow I/O on large files.+ """try:- content = agent_file.read_text(encoding='utf-8')+ # Read only the beginning of the file (class definitions are usually at top)+ with open(agent_file, 'r', encoding='utf-8') as f:+ content = f.read(max_bytes)+# Look for class definitions that end with Agent- import rematches = re.findall(r'class\s+(\w+Agent)\s*[:\(]', content)if matches:return matches[0]diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/main.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/main.pyindex 58d53538a..28c496b68 100644--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/main.py+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/main.py@@ -3,18 +3,28 @@ FinAgent Core Main Entry PointUnified entry point for all agent operations via Tauri.Handles JSON payload dispatch to appropriate modules.++Performance notes:+- Discovery actions have internal timeout protection+- Uses optimized agent loader to avoid slow file scanning"""import sysimport json+import signal+import timefrom pathlib import Pathfrom typing import Dict, Any+from concurrent.futures import ThreadPoolExecutor, TimeoutError as FuturesTimeoutError# Add parent directory to pathparent_dir = str(Path(__file__).parent.parent)if parent_dir not in sys.path:sys.path.insert(0, parent_dir)+# Timeout for discovery operations (seconds)+DISCOVERY_TIMEOUT = 4.0+def main(args=None):"""@@ -60,6 +70,12 @@ def main(args=None):return json.dumps({"success": False, "error": str(e)})+def _discover_agents_internal():+ """Internal helper for agent discovery with isolation"""+ from finagent_core.agent_loader import discover_agents+ return discover_agents()++def dispatch_action(action: str,api_keys: Dict[str, str],@@ -113,9 +129,16 @@ def dispatch_action(# =========================================================================if action == "discover_agents":- from finagent_core.agent_loader import discover_agents- agents = discover_agents()- return {"success": True, "agents": agents, "count": len(agents)}+ # Use timeout protection for discovery to prevent hanging+ try:+ with ThreadPoolExecutor(max_workers=1) as executor:+ future = executor.submit(_discover_agents_internal)+ agents = future.result(timeout=DISCOVERY_TIMEOUT)+ return {"success": True, "agents": agents, "count": len(agents)}+ except FuturesTimeoutError:+ return {"success": True, "agents": [], "count": 0, "warning": "Discovery timed out"}+ except Exception as e:+ return {"success": False, "error": f"Discovery failed: {str(e)}", "agents": []}if action == "list_agents":from finagent_core.agent_loader import list_agents, list_categoriesdiff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/akshare_data.py b/fincept-terminal-desktop/src-tauri/resources/scripts/akshare_data.pyindex 237c2deab..d03473187 100644--- a/fincept-terminal-desktop/src-tauri/resources/scripts/akshare_data.py+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/akshare_data.py@@ -343,21 +343,34 @@ class AKShareDataWrapper:def get_all_available_endpoints(self) -> Dict[str, Any]:"""Get list of all available endpoints in this wrapper"""- methods = [method for method in dir(self) if method.startswith('get_') and callable(getattr(self, method))]+ # Return the actual endpoint names used in endpoint_map, not method names+ endpoints = [+ "stock_zh_spot", "stock_us_spot", "stock_hk_spot", "stock_symbols", "us_stock_symbols",+ "fund_etf_spot", "fund_rank",+ "china_gdp", "china_cpi", "china_pmi",+ "bond_spot", "bond_yield",+ "currency_rates", "forex_spot",+ "futures_spot",+ "air_quality", "carbon_trading",+ "industry_pe", "hot_rank", "north_south_flow"+ ]return {- "available_endpoints": methods,- "total_count": len(methods),- "categories": {- "Stock Market": [m for m in methods if "stock" in m],- "Fund Data": [m for m in methods if "fund" in m],- "Economic": [m for m in methods if "macro" in m],- "Bond Market": [m for m in methods if "bond" in m],- "Currency": [m for m in methods if "currency" in m or "forex" in m],- "Futures": [m for m in methods if "futures" in m],- "Alternative": [m for m in methods if any(x in m for x in ["air", "energy"])],- "Market Analytics": [m for m in methods if any(x in m for x in ["industry", "board", "hot", "hsgt"])]- },- "timestamp": int(datetime.now().timestamp())+ "success": True,+ "data": {+ "available_endpoints": endpoints,+ "total_count": len(endpoints),+ "categories": {+ "Stock Market": ["stock_zh_spot", "stock_us_spot", "stock_hk_spot", "stock_symbols", "us_stock_symbols"],+ "Funds": ["fund_etf_spot", "fund_rank"],+ "Economic": ["china_gdp", "china_cpi", "china_pmi"],+ "Bonds": ["bond_spot", "bond_yield"],+ "Currency & Forex": ["currency_rates", "forex_spot"],+ "Futures": ["futures_spot"],+ "Alternative Data": ["air_quality", "carbon_trading"],+ "Market Analytics": ["industry_pe", "hot_rank", "north_south_flow"]+ },+ "timestamp": int(datetime.now().timestamp())+ }}diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/akshare_news.py b/fincept-terminal-desktop/src-tauri/resources/scripts/akshare_news.pyindex ecdb18ec0..eb9387d91 100644--- a/fincept-terminal-desktop/src-tauri/resources/scripts/akshare_news.py+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/akshare_news.py@@ -53,9 +53,9 @@ def get_news_cctv(date="20240101"):"""Get CCTV news"""return safe_call(ak.news_cctv, date=date)-def get_news_economic_baidu(symbol="财经"):+def get_news_economic_baidu():"""Get Baidu economic news"""- return safe_call(ak.news_economic_baidu, symbol=symbol)+ return safe_call(ak.news_economic_baidu)def get_news_report_time_baidu():"""Get Baidu report time news"""diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/compute_technicals.py b/fincept-terminal-desktop/src-tauri/resources/scripts/compute_technicals.pyindex a3d294f18..d3fb5b13f 100644--- a/fincept-terminal-desktop/src-tauri/resources/scripts/compute_technicals.py+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/compute_technicals.py@@ -111,15 +111,15 @@ def compute_all_technicals(historical_data_json):def main(args=None):"""- Main entry point for PyO3 and subprocess execution+ Main entry point for worker pool and subprocess executionArgs:- args: List of arguments (for PyO3) or None (for subprocess)+ args: List of arguments (for worker pool) or None (for subprocess/CLI)Returns:JSON string with technical indicators or error"""- # Support both PyO3 (args parameter) and subprocess (sys.argv)+ # Support both worker pool (args parameter) and subprocess/CLI (sys.argv)if args is None:args = sys.argv[1:]diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/translate_text.py b/fincept-terminal-desktop/src-tauri/resources/scripts/translate_text.pyindex f25688de2..a3280fe9a 100644--- a/fincept-terminal-desktop/src-tauri/resources/scripts/translate_text.py+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/translate_text.py@@ -6,6 +6,7 @@ Optimized with connection reuse and error handlingimport sysimport json+import asynciofrom googletrans import Translator# Reusable translator instance for better performance@@ -18,9 +19,9 @@ def get_translator():_translator = Translator()return _translator-def translate_text(text, source_lang='auto', target_lang='en'):+async def translate_text_async(text, source_lang='auto', target_lang='en'):"""- Translate text using googletrans library+ Translate text using googletrans library (async)Args:text: Text to translate@@ -32,13 +33,13 @@ def translate_text(text, source_lang='auto', target_lang='en'):"""try:translator = get_translator()- result = translator.translate(text, src=source_lang, dest=target_lang)+ result = await translator.translate(text, src=source_lang, dest=target_lang)return {"success": True,"translated_text": result.text,"detected_lang": result.src,- "confidence": getattr(result.extra_data, 'confidence', None)+ "confidence": getattr(result, 'confidence', None)}except Exception as e:return {@@ -47,9 +48,9 @@ def translate_text(text, source_lang='auto', target_lang='en'):"original_text": text}-def translate_batch(texts, source_lang='auto', target_lang='en'):+async def translate_batch_async(texts, source_lang='auto', target_lang='en'):"""- Translate multiple texts in batch+ Translate multiple texts in batch (async)Args:texts: List of texts to translate@@ -66,7 +67,7 @@ def translate_batch(texts, source_lang='auto', target_lang='en'):# Translate each text individually for better reliabilityfor text in texts:try:- result = translator.translate(text, src=source_lang, dest=target_lang)+ result = await translator.translate(text, src=source_lang, dest=target_lang)translations.append({"original": text,"translated": result.text if result else text,@@ -77,7 +78,8 @@ def translate_batch(texts, source_lang='auto', target_lang='en'):translations.append({"original": text,"translated": text,- "detected_lang": source_lang+ "detected_lang": source_lang,+ "error": str(e)})return {@@ -92,6 +94,14 @@ def translate_batch(texts, source_lang='auto', target_lang='en'):"count": 0}+def translate_text(text, source_lang='auto', target_lang='en'):+ """Sync wrapper for async translate_text"""+ return asyncio.run(translate_text_async(text, source_lang, target_lang))++def translate_batch(texts, source_lang='auto', target_lang='en'):+ """Sync wrapper for async translate_batch"""+ return asyncio.run(translate_batch_async(texts, source_lang, target_lang))+def main():"""Main function to handle command-line translation requests"""# Reconfigure stdout to UTF-8diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/yfinance_data.py b/fincept-terminal-desktop/src-tauri/resources/scripts/yfinance_data.pyindex 8fcaa9d7e..424cb26a0 100644--- a/fincept-terminal-desktop/src-tauri/resources/scripts/yfinance_data.py+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/yfinance_data.py@@ -35,18 +35,27 @@ def get_quote(symbol):"low": round(float(hist['Low'].iloc[-1]), 2) if not hist['Low'].empty else None,"open": round(float(hist['Open'].iloc[-1]), 2) if not hist['Open'].empty else None,"previous_close": round(float(previous_close), 2),- "timestamp": int(datetime.now().timestamp())+ "timestamp": int(datetime.now().timestamp()),+ "exchange": info.get('exchange', '')}return quote_dataexcept Exception as e:return {"error": str(e), "symbol": symbol}-def get_historical(symbol, start_date, end_date):- """Fetch historical data for a symbol"""+def get_historical(symbol, start_date, end_date, interval='1d'):+ """Fetch historical data for a symbol with specified interval++ Args:+ symbol: Stock symbol (e.g., 'AAPL')+ start_date: Start date (YYYY-MM-DD)+ end_date: End date (YYYY-MM-DD)+ interval: Data interval - valid values: 1m, 2m, 5m, 15m, 30m, 60m, 90m, 1h, 1d, 5d, 1wk, 1mo, 3mo+ Note: Intraday data (< 1d) is only available for last 60 days+ """try:ticker = yf.Ticker(symbol)- hist = ticker.history(start=start_date, end=end_date)+ hist = ticker.history(start=start_date, end=end_date, interval=interval)if hist.empty:return None@@ -271,8 +280,80 @@ def get_multiple_ratios(symbols):results.append(ratios)return results+def search_symbols(query, limit=50):+ """+ Search for stock symbols using yfinance+ Returns a list of matching symbols with company info+ """+ try:+ import yfinance as yf++ # Common exchanges and suffixes to try+ exchanges = ['', '.NS', '.BO', '.L', '.TO', '.AX', '.HK', '.SS', '.SZ']+ results = []+ query_upper = query.upper()++ # Try exact match first+ for exchange in exchanges:+ symbol_with_exchange = query_upper + exchange+ try:+ ticker = yf.Ticker(symbol_with_exchange)+ info = ticker.info++ # Check if ticker is valid by verifying it has a name+ if info.get('longName') or info.get('shortName'):+ results.append({+ 'symbol': symbol_with_exchange,+ 'name': info.get('longName', info.get('shortName', 'N/A')),+ 'exchange': info.get('exchange', 'N/A'),+ 'type': info.get('quoteType', 'EQUITY'),+ 'currency': info.get('currency', 'USD'),+ 'sector': info.get('sector', 'N/A'),+ 'industry': info.get('industry', 'N/A')+ })+ if len(results) >= limit:+ break+ except:+ continue++ # If no exact matches, try common US tickers that start with the query+ if len(results) == 0:+ # List of popular tickers for quick matching (you can expand this)+ popular_tickers = [+ 'AAPL', 'MSFT', 'GOOGL', 'GOOG', 'AMZN', 'TSLA', 'META', 'NVDA',+ 'BRK-B', 'BRK-A', 'V', 'JNJ', 'WMT', 'JPM', 'MA', 'PG', 'UNH',+ 'DIS', 'HD', 'PYPL', 'BAC', 'NFLX', 'ADBE', 'CRM', 'CMCSA',+ 'XOM', 'VZ', 'INTC', 'ABT', 'KO', 'NKE', 'PFE', 'MRK', 'PEP',+ 'TMO', 'CSCO', 'COST', 'AVGO', 'TXN', 'ACN', 'DHR', 'NEE', 'CVX'+ ]++ matching_tickers = [t for t in popular_tickers if t.startswith(query_upper)]++ for symbol in matching_tickers[:limit]:+ try:+ ticker = yf.Ticker(symbol)+ info = ticker.info++ if info.get('longName') or info.get('shortName'):+ results.append({+ 'symbol': symbol,+ 'name': info.get('longName', info.get('shortName', 'N/A')),+ 'exchange': info.get('exchange', 'N/A'),+ 'type': info.get('quoteType', 'EQUITY'),+ 'currency': info.get('currency', 'USD'),+ 'sector': info.get('sector', 'N/A'),+ 'industry': info.get('industry', 'N/A')+ })+ except:+ continue++ return {"results": results, "query": query, "count": len(results)}++ except Exception as e:+ return {"error": str(e), "query": query, "results": []}+def main(args=None):- # Support both PyO3 (args parameter) and subprocess (sys.argv)+ # Support both worker pool (args parameter) and subprocess/CLI (sys.argv)if args is None:args = sys.argv[1:]@@ -297,12 +378,13 @@ def main(args=None):elif command == "historical":if len(args) < 4:- result = {"error": "Usage: python yfinance_data.py historical <symbol> <start_date> <end_date>"}+ result = {"error": "Usage: python yfinance_data.py historical <symbol> <start_date> <end_date> [interval]"}else:symbol = args[1]start_date = args[2]end_date = args[3]- result = get_historical(symbol, start_date, end_date)+ interval = args[4] if len(args) > 4 else '1d'+ result = get_historical(symbol, start_date, end_date, interval)elif command == "info":if len(args) < 2:@@ -346,10 +428,18 @@ def main(args=None):symbols = args[1].split(",")result = get_multiple_ratios(symbols)+ elif command == "search":+ if len(args) < 2:+ result = {"error": "Usage: python yfinance_data.py search <query> [limit]"}+ else:+ query = args[1]+ limit = int(args[2]) if len(args) > 2 else 50+ result = search_symbols(query, limit)+else:result = {"error": f"Unknown command: {command}"}- # Return JSON for PyO3, print for subprocess+ # Return JSON for worker pool, print for subprocess/CLIoutput = json.dumps(result, indent=2)print(output)return outputdiff --git a/fincept-terminal-desktop/src-tauri/src/commands/agents.rs b/fincept-terminal-desktop/src-tauri/src/commands/agents.rsindex a6d361413..f350cc1be 100644--- a/fincept-terminal-desktop/src-tauri/src/commands/agents.rs+++ b/fincept-terminal-desktop/src-tauri/src/commands/agents.rs@@ -3,6 +3,13 @@ use crate::utils::python::get_script_path;use crate::python_runtime;use serde::{Deserialize, Serialize};use tauri::Manager;+use std::time::Duration;+use tokio::time::timeout;++/// Default timeout for agent operations (10 seconds)+const AGENT_TIMEOUT_SECS: u64 = 10;+/// Shorter timeout for discovery operations (5 seconds)+const DISCOVERY_TIMEOUT_SECS: u64 = 5;#[derive(Debug, Clone, Serialize, Deserialize)]pub struct AgentParameter {@@ -63,12 +70,34 @@ pub struct AgentExecutionResult {pub async fn execute_core_agent(app: tauri::AppHandle,payload: serde_json::Value,+) -> Result<String, String> {+ execute_core_agent_with_timeout(app, payload, AGENT_TIMEOUT_SECS).await+}++/// Execute CoreAgent with custom timeout+async fn execute_core_agent_with_timeout(+ app: tauri::AppHandle,+ payload: serde_json::Value,+ timeout_secs: u64,) -> Result<String, String> {// Use main.py as unified entry point for all actionslet script_path = get_script_path(&app, "agents/finagent_core/main.py")?;let payload_str = serde_json::to_string(&payload).map_err(|e| format!("Failed to serialize payload: {}", e))?;- python_runtime::execute_python_script(&script_path, vec![payload_str])++ // Execute with timeout protection+ let result = timeout(+ Duration::from_secs(timeout_secs),+ tokio::task::spawn_blocking(move || {+ python_runtime::execute_python_script(&script_path, vec![payload_str])+ })+ ).await;++ match result {+ Ok(Ok(inner_result)) => inner_result,+ Ok(Err(e)) => Err(format!("Task execution error: {}", e)),+ Err(_) => Err(format!("Operation timed out after {} seconds", timeout_secs)),+ }}/// Route a query to the appropriate agent using SuperAgent@@ -106,13 +135,15 @@ pub async fn execute_routed_query(}/// Discover all available agents from config files and directories+/// Uses shorter timeout since discovery should be fast#[tauri::command]pub async fn discover_agents(app: tauri::AppHandle) -> Result<String, String> {let payload = serde_json::json!({"action": "discover_agents","params": {}});- execute_core_agent(app, payload).await+ // Use shorter timeout for discovery - it should be fast+ execute_core_agent_with_timeout(app, payload, DISCOVERY_TIMEOUT_SECS).await}/// Create a stock analysis execution plandiff --git a/fincept-terminal-desktop/src-tauri/src/commands/akshare.rs b/fincept-terminal-desktop/src-tauri/src/commands/akshare.rsindex 5425808ac..b26c92170 100644--- a/fincept-terminal-desktop/src-tauri/src/commands/akshare.rs+++ b/fincept-terminal-desktop/src-tauri/src/commands/akshare.rs@@ -313,3 +313,41 @@ pub async fn build_akshare_database() -> Result<String, String> {Err(format!("Database build failed: {}", error_msg))}}++#[derive(Debug, Serialize, Deserialize)]+pub struct TranslateResponse {+ pub success: bool,+ pub translations: Option<Vec<Translation>>,+ pub error: Option<String>,+}++#[derive(Debug, Serialize, Deserialize)]+pub struct Translation {+ pub original: String,+ pub translated: String,+ pub detected_lang: String,+}++#[command]+pub async fn translate_batch(texts: Vec<String>, target_lang: String) -> Result<TranslateResponse, String> {+ let texts_json = serde_json::to_string(&texts)+ .map_err(|e| format!("Failed to serialize texts: {}", e))?;++ let output = Command::new("python")+ .arg("resources/scripts/translate_text.py")+ .arg("batch")+ .arg(&texts_json)+ .arg("auto")+ .arg(&target_lang)+ .output()+ .map_err(|e| format!("Failed to execute translation script: {}", e))?;++ if output.status.success() {+ let result: TranslateResponse = serde_json::from_slice(&output.stdout)+ .map_err(|e| format!("Failed to parse translation response: {}", e))?;+ Ok(result)+ } else {+ let error_msg = String::from_utf8_lossy(&output.stderr).to_string();+ Err(format!("Translation failed: {}", error_msg))+ }+}diff --git a/fincept-terminal-desktop/src-tauri/src/commands/financial_analysis.rs b/fincept-terminal-desktop/src-tauri/src/commands/financial_analysis.rsindex 631f18f9b..467409239 100644--- a/fincept-terminal-desktop/src-tauri/src/commands/financial_analysis.rs+++ b/fincept-terminal-desktop/src-tauri/src/commands/financial_analysis.rs@@ -1,5 +1,5 @@// Financial Analysis Module Commands-// CFA-compliant statement analysis via PyO3+// CFA-compliant statement analysis via worker pool or subprocessuse crate::utils::python::get_script_path;use crate::python_runtime;diff --git a/fincept-terminal-desktop/src-tauri/src/lib.rs b/fincept-terminal-desktop/src-tauri/src/lib.rsindex 34e451e67..9f4fb1682 100644--- a/fincept-terminal-desktop/src-tauri/src/lib.rs+++ b/fincept-terminal-desktop/src-tauri/src/lib.rs@@ -2303,6 +2303,7 @@ pub fn run() {// AKShare Commands (Free Chinese & Global market data)commands::akshare::akshare_query,commands::akshare::akshare_get_endpoints,+ commands::akshare::translate_batch,commands::akshare::get_stock_cn_spot,commands::akshare::get_stock_us_spot,commands::akshare::get_stock_hk_spot,diff --git a/fincept-terminal-desktop/src-tauri/src/python_runtime.rs b/fincept-terminal-desktop/src-tauri/src/python_runtime.rsindex 2298310bc..752a369a0 100644--- a/fincept-terminal-desktop/src-tauri/src/python_runtime.rs+++ b/fincept-terminal-desktop/src-tauri/src/python_runtime.rs@@ -1,5 +1,7 @@// Python Runtime Module - Worker Pool Integration-// Provides backward-compatible API using worker pool instead of PyO3+// Provides async/sync execution of Python scripts via persistent worker processes+// Primary method: Worker pool with Unix Domain Sockets (fast, persistent workers)+// Fallback method: Direct subprocess execution (slower but reliable)use std::path::PathBuf;@@ -101,35 +103,26 @@ if __name__ == '__main__':}/// Determine which venv to use based on script path+///+/// venv-numpy1 (NumPy <2.0): vectorbt, backtesting, gluonts, functime, PyPortfolioOpt, financepy+/// venv-numpy2 (NumPy 2.x): Everything else including ta, vnpy, edgartools, pyqlib, rdagent, etc.fn determine_venv_for_script(script_path: &PathBuf) -> &'static str {let path_str = script_path.to_string_lossy().to_lowercase();// NumPy 1.x libraries (from requirements-numpy1.txt)- // Includes backtesting, time series, portfolio optimization, and quant libraries+ // ONLY libraries that are INCOMPATIBLE with NumPy 2.x go hereif path_str.contains("vectorbt")|| path_str.contains("backtesting")|| path_str.contains("gluonts")|| path_str.contains("functime")|| path_str.contains("pyportfolioopt")- // Qlib and RD-Agent (match both script paths and library names)- || path_str.contains("qlib") // matches qlib_service.py, pyqlib- || path_str.contains("rd_agent") // matches rd_agent_service.py- || path_str.contains("rdagent") // matches library name- || path_str.contains("gs-quant")- || path_str.contains("gs_quant")- // Financial modeling libraries (NumPy 1.x dependent)- || path_str.contains("ffn") // matches ffn_wrapper, ffn_service.py- || path_str.contains("fortitudo") // matches fortitudo_tech_wrapper, fortitudo_service.py|| path_str.contains("financepy")- || path_str.contains("finquant")- // AI Quant Lab uses Qlib/RD-Agent which need NumPy 1.x- || path_str.contains("ai_quant_lab"){return "venv-numpy1";}- // NumPy 2.x libraries (vnpy, edgartools, modern ML)- // Default for everything else+ // NumPy 2.x libraries (DEFAULT - most libraries including modern quant tools)+ // Includes: ta, vnpy, edgartools, pyqlib, rdagent, gs-quant, ffn, fortitudo, finquant, etc."venv-numpy2"}diff --git a/fincept-terminal-desktop/src-tauri/src/utils/python.rs b/fincept-terminal-desktop/src-tauri/src/utils/python.rsindex dd0ee3f13..d5b5f02dc 100644--- a/fincept-terminal-desktop/src-tauri/src/utils/python.rs+++ b/fincept-terminal-desktop/src-tauri/src/utils/python.rs@@ -1,4 +1,8 @@-// Utility module for Python execution with PyO3+// Utility module for Python script execution and path resolution+// Handles dual-venv setup (NumPy 1.x and NumPy 2.x compatibility)+// Execution methods:+// 1. Worker pool via python_runtime (fast, persistent workers)+// 2. Direct subprocess execution (fallback, more reliable on Windows)use std::path::PathBuf;use tauri::Manager;@@ -222,11 +226,24 @@ pub fn get_script_path(app: &tauri::AppHandle, script_name: &str) -> Result<Path}// Try each candidate path- eprintln!("[SCRIPT_PATH_DEBUG] Searching for: {}", script_name);- for (i, path) in candidate_paths.iter().enumerate() {- eprintln!("[SCRIPT_PATH_DEBUG] Candidate {}: {:?}", i+1, path);+ // Debug logging only in debug builds+ #[cfg(debug_assertions)]+ {+ eprintln!("[SCRIPT_PATH_DEBUG] Searching for: {}", script_name);+ }++ for (_i, path) in candidate_paths.iter().enumerate() {+ #[cfg(debug_assertions)]+ {+ eprintln!("[SCRIPT_PATH_DEBUG] Candidate {}: {:?}", _i+1, path);+ }+if path.exists() {- eprintln!("[SCRIPT_PATH_DEBUG] Found at candidate {}", i+1);+ #[cfg(debug_assertions)]+ {+ eprintln!("[SCRIPT_PATH_DEBUG] Found at candidate {}", _i+1);+ }+// Strip the \\?\ prefix that Python can't handle on Windowslet path_str = path.to_string_lossy().to_string();let clean_path = if path_str.starts_with(r"\\?\") {diff --git a/fincept-terminal-desktop/src-tauri/src/worker_pool.rs b/fincept-terminal-desktop/src-tauri/src/worker_pool.rsindex ffb850a55..0d88463e3 100644--- a/fincept-terminal-desktop/src-tauri/src/worker_pool.rs+++ b/fincept-terminal-desktop/src-tauri/src/worker_pool.rs@@ -16,8 +16,9 @@ use std::os::windows::process::CommandExt;#[cfg(target_os = "windows")]const CREATE_NO_WINDOW: u32 = 0x08000000;-const NUM_WORKERS: usize = 2; // Two Python processes+const NUM_WORKERS: usize = 3; // Three Python processes for better concurrencyconst NUM_THREADS: usize = 4; // Number of concurrent scripts per process+const TASK_TIMEOUT_SECS: u64 = 30; // Maximum time for a task before timeout#[derive(Debug, Clone, Serialize, Deserialize)]pub struct WorkerTask {@@ -313,7 +314,7 @@ impl WorkerPool {}}- /// Execute a task using the worker pool+ /// Execute a task using the worker pool with timeout protectionpub async fn execute_task(&self, task: WorkerTask) -> Result<WorkerResponse, String> {let task_id = task.task_id.clone();@@ -335,11 +336,27 @@ impl WorkerPool {self.task_sender.send(prioritized_task).map_err(|e| format!("Failed to queue task: {}", e))?;- // Wait for response- let response = response_rx.await- .map_err(|e| format!("Failed to receive response: {}", e))?;-- Ok(response)+ // Wait for response with timeout protection+ let timeout_result = tokio::time::timeout(+ tokio::time::Duration::from_secs(TASK_TIMEOUT_SECS),+ response_rx+ ).await;++ match timeout_result {+ Ok(Ok(response)) => Ok(response),+ Ok(Err(e)) => {+ // Channel closed - clean up the sender+ let mut senders = self.response_senders.lock().await;+ senders.remove(&task_id);+ Err(format!("Failed to receive response: {}", e))+ }+ Err(_) => {+ // Timeout - clean up the sender to avoid memory leak+ let mut senders = self.response_senders.lock().await;+ senders.remove(&task_id);+ Err(format!("Task timed out after {} seconds", TASK_TIMEOUT_SECS))+ }+ }}/// Shutdown all workers@@ -382,30 +399,151 @@ pub async fn execute_python_script(}/// Execute a Python script using the worker pool with custom priority+/// Falls back to subprocess execution if worker pool is not availablepub async fn execute_python_script_with_priority(script_path: PathBuf,args: Vec<String>,venv: &str,priority: u8,) -> Result<String, String> {- let task = WorkerTask {- task_id: uuid::Uuid::new_v4().to_string(),- script_path: script_path.to_string_lossy().to_string(),- args,- venv: venv.to_string(),- priority,- };+ // Try worker pool first+ match get_worker_pool().await {+ Ok(pool_mutex) => {+ let pool_guard = pool_mutex.lock().await;+ if let Some(pool) = pool_guard.as_ref() {+ let task = WorkerTask {+ task_id: uuid::Uuid::new_v4().to_string(),+ script_path: script_path.to_string_lossy().to_string(),+ args: args.clone(),+ venv: venv.to_string(),+ priority,+ };- let pool_mutex = get_worker_pool().await?;- let pool_guard = pool_mutex.lock().await;- let pool = pool_guard.as_ref()- .ok_or("Worker pool not initialized")?;+ match pool.execute_task(task).await {+ Ok(response) => {+ if response.status == "success" {+ return Ok(response.data);+ } else {+ return Err(response.data);+ }+ }+ Err(e) => {+ eprintln!("[WorkerPool] Task execution failed, falling back to subprocess: {}", e);+ }+ }+ }+ }+ Err(e) => {+ eprintln!("[WorkerPool] Pool not available ({}), using subprocess fallback", e);+ }+ }- let response = pool.execute_task(task).await?;+ // Fallback to subprocess execution+ execute_python_subprocess(&script_path, &args).await+}- if response.status == "success" {- Ok(response.data)+/// Fallback subprocess execution when worker pool is not available+async fn execute_python_subprocess(+ script_path: &PathBuf,+ args: &[String],+) -> Result<String, String> {+ use std::process::Stdio;++ // Try to find Python executable+ let python_exe = find_python_executable()?;++ let mut cmd = Command::new(&python_exe);+ cmd.arg(script_path)+ .args(args)+ .stdout(Stdio::piped())+ .stderr(Stdio::piped());++ #[cfg(target_os = "windows")]+ cmd.creation_flags(CREATE_NO_WINDOW);++ let output = cmd.output()+ .map_err(|e| format!("Failed to execute Python subprocess: {}", e))?;++ if output.status.success() {+ let stdout = String::from_utf8_lossy(&output.stdout).to_string();+ // Try to extract just the JSON part (last line typically)+ let lines: Vec<&str> = stdout.lines().collect();+ if let Some(last_line) = lines.last() {+ if last_line.starts_with('{') || last_line.starts_with('[') {+ return Ok(last_line.to_string());+ }+ }+ Ok(stdout)} else {- Err(response.data)+ let stderr = String::from_utf8_lossy(&output.stderr);+ Err(format!("Python script failed: {}", stderr))}}++/// Find Python executable for subprocess fallback+fn find_python_executable() -> Result<PathBuf, String> {+ // First, try our installed venvs (preferred - has all required packages)+ #[cfg(target_os = "windows")]+ {+ if let Ok(local_app_data) = std::env::var("LOCALAPPDATA") {+ // Try venv-numpy2 first (default, has most libraries including ta, yfinance, etc.)+ let venv2_python = PathBuf::from(&local_app_data)+ .join("fincept-dev")+ .join("venv-numpy2")+ .join("Scripts")+ .join("python.exe");+ if venv2_python.exists() {+ return Ok(venv2_python);+ }++ // Fall back to venv-numpy1 (for vectorbt, backtesting, etc.)+ let venv1_python = PathBuf::from(&local_app_data)+ .join("fincept-dev")+ .join("venv-numpy1")+ .join("Scripts")+ .join("python.exe");+ if venv1_python.exists() {+ return Ok(venv1_python);+ }+ }+ }++ #[cfg(not(target_os = "windows"))]+ {+ // macOS/Linux: Check standard app data locations+ if let Ok(home) = std::env::var("HOME") {+ let base = if cfg!(target_os = "macos") {+ PathBuf::from(&home).join("Library/Application Support/fincept-dev")+ } else {+ PathBuf::from(&home).join(".local/share/fincept-dev")+ };++ let venv2_python = base.join("venv-numpy2/bin/python3");+ if venv2_python.exists() {+ return Ok(venv2_python);+ }++ let venv1_python = base.join("venv-numpy1/bin/python3");+ if venv1_python.exists() {+ return Ok(venv1_python);+ }+ }+ }++ // Fall back to system Python (may not have required packages)+ let candidates = if cfg!(target_os = "windows") {+ vec!["python.exe", "python3.exe", "py.exe"]+ } else {+ vec!["python3", "python"]+ };++ for candidate in candidates {+ if let Ok(output) = Command::new(candidate).arg("--version").output() {+ if output.status.success() {+ return Ok(PathBuf::from(candidate));+ }+ }+ }++ Err("No Python executable found".to_string())+}diff --git a/fincept-terminal-desktop/src/brokers/stocks/index.ts b/fincept-terminal-desktop/src/brokers/stocks/index.tsindex 262c6bdd8..069f316bd 100644--- a/fincept-terminal-desktop/src/brokers/stocks/index.ts+++ b/fincept-terminal-desktop/src/brokers/stocks/index.ts@@ -35,3 +35,6 @@ export { initializeStockBrokers } from './init';// Indian Brokersexport * from './india';++// YFinance Paper Trading+export * from './yfinance';diff --git a/fincept-terminal-desktop/src/brokers/stocks/init.ts b/fincept-terminal-desktop/src/brokers/stocks/init.tsindex 3aa47c465..ab723fb1b 100644--- a/fincept-terminal-desktop/src/brokers/stocks/init.ts+++ b/fincept-terminal-desktop/src/brokers/stocks/init.ts@@ -26,6 +26,8 @@ import { IBKRAdapter } from './us/ibkr/IBKRAdapter';import { TradierAdapter } from './us/tradier/TradierAdapter';// European Brokers+// Paper Trading+import { YFinancePaperTradingAdapter } from './yfinance/YFinancePaperTradingAdapter';import { SaxoBankAdapter } from './europe/saxobank/SaxoBankAdapter';/**@@ -54,4 +56,7 @@ export function initializeStockBrokers(): void {// Register European brokersregisterBrokerAdapter('saxobank', SaxoBankAdapter);++ // Register Paper Trading+ registerBrokerAdapter('yfinance', YFinancePaperTradingAdapter);}diff --git a/fincept-terminal-desktop/src/brokers/stocks/registry.ts b/fincept-terminal-desktop/src/brokers/stocks/registry.tsindex db30affec..76db0a3fe 100644--- a/fincept-terminal-desktop/src/brokers/stocks/registry.ts+++ b/fincept-terminal-desktop/src/brokers/stocks/registry.ts@@ -975,8 +975,78 @@ export const STOCK_BROKER_REGISTRY: Record<string, StockBrokerMetadata> = {'AZN:XLON', 'MC:XPAR', 'ROG:XSWX', 'NOVN:XSWX', 'ULVR:XLON',],},++ // ============================================================================+ // PAPER TRADING (YFinance Data)+ // ============================================================================++ yfinance: {+ id: 'yfinance',+ name: 'yfinance',+ displayName: 'YFinance (Paper Trading)',+ logo: 'https://fincept.in/brokers/yfinance.png',+ website: 'https://finance.yahoo.com',++ region: 'us',+ country: 'US',+ currency: 'USD',+ exchanges: ['NYSE', 'NASDAQ', 'AMEX', 'NSE', 'BSE', 'LSE', 'XETRA', 'TSX', 'ASX', 'HKEX'],+ marketHours: {+ open: '09:30',+ close: '16:00',+ timezone: 'America/New_York',+ preMarketOpen: '04:00',+ preMarketClose: '09:30',+ postMarketOpen: '16:00',+ postMarketClose: '20:00',+ },++ features: {+ webSocket: false,+ amo: false,+ gtt: false,+ bracketOrder: false,+ coverOrder: false,+ marginCalculator: false,+ optionsChain: false,+ paperTrading: true,+ },++ tradingFeatures: {+ marketOrders: true,+ limitOrders: true,+ stopOrders: true,+ stopLimitOrders: true,+ trailingStopOrders: false,+ },++ productTypes: ['CASH'],++ authType: 'api_key',++ rateLimit: {+ ordersPerSecond: 10,+ quotesPerSecond: 1,+ },++ fees: {+ equity: { brokerage: 0, stt: 0 },+ intraday: { brokerage: 0 },+ fno: { brokerage: 0 },+ },++ defaultSymbols: [+ 'AAPL', 'MSFT', 'GOOGL', 'AMZN', 'NVDA',+ 'META', 'TSLA', 'BRK-B', 'JPM', 'V',+ 'UNH', 'JNJ', 'XOM', 'PG', 'MA',+ 'NFLX', 'ADBE', 'CRM', 'INTC', 'AMD',+ 'RELIANCE.NS', 'TCS.NS', 'INFY.NS', 'HDFCBANK.NS', 'ICICIBANK.NS',+ ],+ },};+// ============================================================================+// ADAPTER REGISTRY (Runtime instances)// ============================================================================// ADAPTER REGISTRY (Runtime instances)// ============================================================================diff --git a/fincept-terminal-desktop/src/brokers/stocks/yfinance/YFinancePaperTradingAdapter.ts b/fincept-terminal-desktop/src/brokers/stocks/yfinance/YFinancePaperTradingAdapter.tsnew file mode 100644index 000000000..b0e9082a8--- /dev/null+++ b/fincept-terminal-desktop/src/brokers/stocks/yfinance/YFinancePaperTradingAdapter.ts@@ -0,0 +1,591 @@+/**+ * YFinance Paper Trading Adapter+ *+ * Simple paper trading broker using YFinance for market data.+ * Fetches quotes on-demand with caching - no real-time streaming.+ * All orders executed against local paper trading engine.+ */++import { invoke } from '@tauri-apps/api/core';+import { BaseStockBrokerAdapter } from '../BaseStockBrokerAdapter';+import { STOCK_BROKER_REGISTRY } from '../registry';+import type {+ Region,+ StockBrokerMetadata,+ BrokerCredentials,+ AuthResponse,+ Funds,+ MarginRequired,+ OrderParams,+ OrderResponse,+ ModifyOrderParams,+ Order,+ Trade,+ Position,+ Holding,+ Quote,+ OHLCV,+ MarketDepth,+ TimeFrame,+ StockExchange,+ Instrument,+ WebSocketConfig,+ SubscriptionMode,+ BulkOperationResult,+ SmartOrderParams,+} from '../types';++// Paper trading imports+import {+ createPortfolio,+ getPortfolio,+ listPortfolios,+ placeOrder as ptPlaceOrder,+ cancelOrder as ptCancelOrder,+ getOrders as ptGetOrders,+ getPositions as ptGetPositions,+ getTrades as ptGetTrades,+ fillOrder as ptFillOrder,+ type Portfolio,+ type Order as PaperOrder,+ type Position as PaperPosition,+ type Trade as PaperTrade,+} from '@/paper-trading';++// ============================================================================+// TYPES+// ============================================================================++export type UpdateInterval = 15 | 30 | 60 | 300 | 600; // seconds++interface YFinanceQuote {+ symbol: string;+ price: number;+ change: number;+ change_percent: number;+ volume: number | null;+ high: number | null;+ low: number | null;+ open: number | null;+ previous_close: number;+ timestamp: number;+ exchange?: string;+}++interface CachedQuote {+ quote: Quote;+ fetchedAt: number;+}++// ============================================================================+// YFINANCE PAPER TRADING ADAPTER+// ============================================================================++export class YFinancePaperTradingAdapter extends BaseStockBrokerAdapter {+ readonly brokerId = 'yfinance';+ readonly brokerName = 'YFinance Paper Trading';+ readonly region: Region = 'us';+ readonly metadata: StockBrokerMetadata = STOCK_BROKER_REGISTRY['yfinance'];++ // Paper trading state+ private portfolioId: string | null = null;+ private portfolio: Portfolio | null = null;++ // Quote cache - quotes are cached and refreshed on demand+ private quoteCache: Map<string, CachedQuote> = new Map();+ private cacheTTL: number = 60000; // 1 minute default cache TTL in ms++ // ============================================================================+ // SETTINGS+ // ============================================================================++ /**+ * Set cache TTL (how long quotes are considered fresh)+ */+ setCacheTTL(seconds: UpdateInterval): void {+ this.cacheTTL = seconds * 1000;+ console.log(`[YFinance] Cache TTL set to ${seconds}s`);+ }++ getCacheTTL(): number {+ return this.cacheTTL / 1000;+ }++ // ============================================================================+ // AUTHENTICATION (Paper Trading - Creates/loads portfolio)+ // ============================================================================++ async authenticate(_credentials: BrokerCredentials): Promise<AuthResponse> {+ try {+ console.log('[YFinance] Initializing paper trading...');++ const portfolios = await listPortfolios();+ let portfolio = portfolios.find(p => p.name === 'YFinance Paper Trading');++ if (!portfolio) {+ portfolio = await createPortfolio(+ 'YFinance Paper Trading',+ 100000, // $100k default+ 'USD',+ 1,+ 'cross',+ 0+ );+ console.log('[YFinance] Created new portfolio:', portfolio.id);+ } else {+ console.log('[YFinance] Using existing portfolio:', portfolio.id);+ }++ this.portfolioId = portfolio.id;+ this.portfolio = portfolio;+ this._isConnected = true;+ this.accessToken = 'paper_trading_enabled';++ return {+ success: true,+ accessToken: 'paper_trading_enabled',+ userId: portfolio.id,+ message: 'Paper trading initialized',+ };+ } catch (error) {+ console.error('[YFinance] Init failed:', error);+ return {+ success: false,+ message: error instanceof Error ? error.message : 'Init failed',+ errorCode: 'PAPER_INIT_FAILED',+ };+ }+ }++ getAuthUrl(): string {+ return '';+ }++ async logout(): Promise<void> {+ this.quoteCache.clear();+ this.portfolioId = null;+ this.portfolio = null;+ this._isConnected = false;+ this.accessToken = null;+ }++ // ============================================================================+ // YFINANCE DATA FETCHING (Simple, on-demand)+ // ============================================================================++ private async fetchQuote(symbol: string): Promise<YFinanceQuote | null> {+ try {+ const result = await invoke<string>('execute_yfinance_command', {+ command: 'quote',+ args: [symbol],+ });+ const data = JSON.parse(result);+ return data.error ? null : data;+ } catch (error) {+ console.error(`[YFinance] Quote error for ${symbol}:`, error);+ return null;+ }+ }++ private convertQuote(yq: YFinanceQuote, fallbackExchange: StockExchange): Quote {+ // Use exchange from API if available, otherwise use fallback+ const exchange = this.getExchange(yq.symbol, yq.exchange) || fallbackExchange;+ return {+ symbol: yq.symbol,+ exchange,+ lastPrice: yq.price,+ open: yq.open || yq.price,+ high: yq.high || yq.price,+ low: yq.low || yq.price,+ close: yq.price,+ previousClose: yq.previous_close,+ change: yq.change,+ changePercent: yq.change_percent,+ volume: yq.volume || 0,+ bid: yq.price - 0.01,+ bidQty: 100,+ ask: yq.price + 0.01,+ askQty: 100,+ timestamp: yq.timestamp * 1000,+ };+ }++ private getExchange(symbol: string, apiExchange?: string): StockExchange {+ // First check symbol suffix+ if (symbol.endsWith('.NS')) return 'NSE';+ if (symbol.endsWith('.BO')) return 'BSE';+ if (symbol.endsWith('.L')) return 'LSE';+ if (symbol.endsWith('.TO')) return 'TSX';+ if (symbol.endsWith('.AX')) return 'ASX';+ if (symbol.endsWith('.HK')) return 'HKEX';++ // Use API exchange info if available+ if (apiExchange) {+ const exchangeUpper = apiExchange.toUpperCase();+ if (exchangeUpper === 'NMS' || exchangeUpper === 'NGM' || exchangeUpper === 'NCM' || exchangeUpper.includes('NASDAQ')) return 'NASDAQ';+ if (exchangeUpper === 'NYQ' || exchangeUpper.includes('NYSE')) return 'NYSE';+ if (exchangeUpper === 'ASE' || exchangeUpper.includes('AMEX')) return 'AMEX';+ if (exchangeUpper === 'NSI' || exchangeUpper.includes('NSE')) return 'NSE';+ if (exchangeUpper === 'BOM' || exchangeUpper.includes('BSE')) return 'BSE';+ }++ // Default to NASDAQ for US stocks (most tech stocks)+ return 'NASDAQ';+ }++ // ============================================================================+ // MARKET DATA+ // ============================================================================++ protected async getQuoteInternal(symbol: string, exchange: StockExchange): Promise<Quote> {+ // Check cache+ const cached = this.quoteCache.get(symbol);+ if (cached && Date.now() - cached.fetchedAt < this.cacheTTL) {+ return cached.quote;+ }++ // Fetch fresh+ const yq = await this.fetchQuote(symbol);+ if (!yq) {+ throw new Error(`Failed to fetch quote for ${symbol}`);+ }++ const quote = this.convertQuote(yq, exchange);+ this.quoteCache.set(symbol, { quote, fetchedAt: Date.now() });+ return quote;+ }++ protected async getOHLCVInternal(+ symbol: string,+ _exchange: StockExchange,+ timeframe: TimeFrame,+ from: Date,+ to: Date+ ): Promise<OHLCV[]> {+ try {+ // Map TimeFrame to yfinance interval format+ const intervalMap: Record<TimeFrame, string> = {+ '1m': '1m',+ '2m': '2m',+ '3m': '5m', // yfinance doesn't have 3m, use 5m+ '5m': '5m',+ '10m': '15m', // yfinance doesn't have 10m, use 15m+ '15m': '15m',+ '30m': '30m',+ '1h': '1h',+ '2h': '60m', // yfinance doesn't have 2h, use 60m+ '4h': '60m', // yfinance doesn't have 4h, use 60m+ '1d': '1d',+ '1w': '1wk',+ '1M': '1mo',+ };+ const interval = intervalMap[timeframe] || '1d';++ const result = await invoke<string>('execute_yfinance_command', {+ command: 'historical',+ args: [symbol, from.toISOString().split('T')[0], to.toISOString().split('T')[0], interval],+ });+ const data = JSON.parse(result);+ if (data.error || !Array.isArray(data)) return [];+ return data.map((d: any) => ({+ timestamp: d.timestamp * 1000,+ open: d.open,+ high: d.high,+ low: d.low,+ close: d.close,+ volume: d.volume,+ }));+ } catch {+ return [];+ }+ }++ protected async getMarketDepthInternal(symbol: string, _exchange: StockExchange): Promise<MarketDepth> {+ const cached = this.quoteCache.get(symbol);+ const price = cached?.quote.lastPrice || 100;+ return {+ bids: Array.from({ length: 5 }, (_, i) => ({ price: price - 0.01 * (i + 1), quantity: 100 * (i + 1) })),+ asks: Array.from({ length: 5 }, (_, i) => ({ price: price + 0.01 * (i + 1), quantity: 100 * (i + 1) })),+ timestamp: Date.now(),+ };+ }++ // ============================================================================+ // ORDERS - PAPER TRADING+ // ============================================================================++ protected async placeOrderInternal(params: OrderParams): Promise<OrderResponse> {+ if (!this.portfolioId) {+ return { success: false, message: 'Paper trading not initialized' };+ }++ try {+ let price = params.price;+ if (params.orderType === 'MARKET') {+ const quote = await this.getQuoteInternal(params.symbol, params.exchange);+ price = quote.lastPrice;+ }++ const order = await ptPlaceOrder(+ this.portfolioId,+ params.symbol,+ params.side.toLowerCase() as 'buy' | 'sell',+ params.orderType.toLowerCase(),+ params.quantity,+ price,+ params.triggerPrice+ );++ if (params.orderType === 'MARKET' && price) {+ await ptFillOrder(order.id, price);+ }++ return { success: true, orderId: order.id };+ } catch (error) {+ return { success: false, message: error instanceof Error ? error.message : 'Order failed' };+ }+ }++ protected async modifyOrderInternal(params: ModifyOrderParams): Promise<OrderResponse> {+ try {+ await ptCancelOrder(params.orderId);+ return { success: true, orderId: params.orderId, message: 'Order cancelled (modify not supported)' };+ } catch {+ return { success: false, message: 'Modify failed' };+ }+ }++ protected async cancelOrderInternal(orderId: string): Promise<OrderResponse> {+ try {+ await ptCancelOrder(orderId);+ return { success: true, orderId };+ } catch {+ return { success: false, message: 'Cancel failed' };+ }+ }++ protected async getOrdersInternal(): Promise<Order[]> {+ if (!this.portfolioId) return [];+ const orders = await ptGetOrders(this.portfolioId);+ return orders.map(o => this.toOrder(o));+ }++ protected async getTradeBookInternal(): Promise<Trade[]> {+ if (!this.portfolioId) return [];+ const trades = await ptGetTrades(this.portfolioId);+ return trades.map(t => this.toTrade(t));+ }++ // ============================================================================+ // POSITIONS & HOLDINGS+ // ============================================================================++ protected async getPositionsInternal(): Promise<Position[]> {+ if (!this.portfolioId) return [];+ const positions = await ptGetPositions(this.portfolioId);+ return positions.map(p => this.toPosition(p));+ }++ protected async getHoldingsInternal(): Promise<Holding[]> {+ const positions = await this.getPositionsInternal();+ return positions.map(p => ({+ symbol: p.symbol,+ exchange: p.exchange,+ quantity: p.quantity,+ averagePrice: p.averagePrice,+ lastPrice: p.lastPrice,+ investedValue: p.averagePrice * p.quantity,+ currentValue: p.lastPrice * p.quantity,+ pnl: p.pnl,+ pnlPercent: p.pnlPercent,+ }));+ }++ protected async getFundsInternal(): Promise<Funds> {+ if (!this.portfolioId) {+ return { availableCash: 0, usedMargin: 0, availableMargin: 0, totalBalance: 0, currency: 'USD' };+ }+ const portfolio = await getPortfolio(this.portfolioId);+ return {+ availableCash: portfolio.balance,+ usedMargin: Math.max(0, portfolio.initial_balance - portfolio.balance),+ availableMargin: portfolio.balance,+ totalBalance: portfolio.initial_balance,+ currency: 'USD',+ };+ }++ // ============================================================================+ // CONVERTERS+ // ============================================================================++ private toOrder(po: PaperOrder): Order {+ const statusMap: Record<string, Order['status']> = {+ pending: 'PENDING', filled: 'FILLED', partial: 'PARTIALLY_FILLED', cancelled: 'CANCELLED'+ };+ return {+ orderId: po.id,+ symbol: po.symbol,+ exchange: this.getExchange(po.symbol),+ side: po.side.toUpperCase() as 'BUY' | 'SELL',+ quantity: po.quantity,+ filledQuantity: po.filled_qty,+ pendingQuantity: po.quantity - po.filled_qty,+ price: po.price || 0,+ averagePrice: po.avg_price || 0,+ triggerPrice: po.stop_price,+ orderType: po.order_type.toUpperCase() as Order['orderType'],+ productType: 'CASH',+ validity: 'DAY',+ status: statusMap[po.status] || 'PENDING',+ placedAt: new Date(po.created_at),+ updatedAt: po.filled_at ? new Date(po.filled_at) : undefined,+ };+ }++ private toPosition(pp: PaperPosition): Position {+ return {+ symbol: pp.symbol,+ exchange: this.getExchange(pp.symbol),+ productType: 'CASH',+ quantity: pp.quantity,+ buyQuantity: pp.side === 'long' ? pp.quantity : 0,+ sellQuantity: pp.side === 'short' ? pp.quantity : 0,+ buyValue: pp.side === 'long' ? pp.entry_price * pp.quantity : 0,+ sellValue: pp.side === 'short' ? pp.entry_price * pp.quantity : 0,+ averagePrice: pp.entry_price,+ lastPrice: pp.current_price,+ pnl: pp.unrealized_pnl,+ pnlPercent: pp.entry_price > 0 ? ((pp.current_price - pp.entry_price) / pp.entry_price) * 100 : 0,+ dayPnl: 0,+ };+ }++ private toTrade(pt: PaperTrade): Trade {+ return {+ tradeId: pt.id,+ orderId: pt.order_id,+ symbol: pt.symbol,+ exchange: this.getExchange(pt.symbol),+ side: pt.side.toUpperCase() as 'BUY' | 'SELL',+ quantity: pt.quantity,+ price: pt.price,+ productType: 'CASH',+ tradedAt: new Date(pt.timestamp),+ };+ }++ // ============================================================================+ // WEBSOCKET (Not used - just stubs for interface compliance)+ // ============================================================================++ protected async connectWebSocketInternal(_config: WebSocketConfig): Promise<void> {+ this.wsConnected = true;+ }++ async disconnectWebSocket(): Promise<void> {+ this.wsConnected = false;+ }++ protected async subscribeInternal(_symbol: string, _exchange: StockExchange, _mode: SubscriptionMode): Promise<void> {}+ protected async unsubscribeInternal(_symbol: string, _exchange: StockExchange): Promise<void> {}++ // ============================================================================+ // BULK OPERATIONS+ // ============================================================================++ protected async cancelAllOrdersInternal(): Promise<BulkOperationResult> {+ if (!this.portfolioId) {+ return { success: false, totalCount: 0, successCount: 0, failedCount: 0, results: [] };+ }+ const orders = await ptGetOrders(this.portfolioId, 'pending');+ let successCount = 0;+ const results = [];+ for (const order of orders) {+ try {+ await ptCancelOrder(order.id);+ results.push({ success: true, orderId: order.id });+ successCount++;+ } catch {+ results.push({ success: false, orderId: order.id, error: 'Failed' });+ }+ }+ return { success: successCount === orders.length, totalCount: orders.length, successCount, failedCount: orders.length - successCount, results };+ }++ protected async closeAllPositionsInternal(): Promise<BulkOperationResult> {+ if (!this.portfolioId) {+ return { success: false, totalCount: 0, successCount: 0, failedCount: 0, results: [] };+ }+ const positions = await ptGetPositions(this.portfolioId);+ let successCount = 0;+ const results = [];+ for (const pos of positions) {+ try {+ const side = pos.side === 'long' ? 'sell' : 'buy';+ const order = await ptPlaceOrder(this.portfolioId, pos.symbol, side, 'market', pos.quantity, pos.current_price, undefined, true);+ await ptFillOrder(order.id, pos.current_price);+ results.push({ success: true, symbol: pos.symbol });+ successCount++;+ } catch {+ results.push({ success: false, symbol: pos.symbol, error: 'Failed' });+ }+ }+ return { success: successCount === positions.length, totalCount: positions.length, successCount, failedCount: positions.length - successCount, results };+ }++ protected async placeSmartOrderInternal(params: SmartOrderParams): Promise<OrderResponse> {+ return this.placeOrderInternal(params);+ }++ protected async calculateMarginInternal(orders: OrderParams[]): Promise<MarginRequired> {+ const totalValue = orders.reduce((sum, o) => sum + (o.price || 100) * o.quantity, 0);+ return {+ totalMargin: totalValue,+ initialMargin: totalValue,+ orders: orders.map(o => ({ symbol: o.symbol, margin: (o.price || 100) * o.quantity })),+ };+ }++ // ============================================================================+ // SYMBOL SEARCH+ // ============================================================================++ async searchSymbols(query: string, _exchange?: StockExchange): Promise<Instrument[]> {+ try {+ const result = await invoke<string>('execute_yfinance_command', { command: 'search', args: [query, '20'] });+ const data = JSON.parse(result);+ if (data.error || !data.results) return [];+ return data.results.map((r: any) => ({+ symbol: r.symbol,+ name: r.name,+ exchange: r.exchange as StockExchange,+ instrumentType: 'EQUITY' as const,+ currency: r.currency as any,+ lotSize: 1,+ tickSize: 0.01,+ }));+ } catch {+ return [];+ }+ }++ async getInstrument(symbol: string, exchange: StockExchange): Promise<Instrument | null> {+ try {+ const result = await invoke<string>('execute_yfinance_command', { command: 'info', args: [symbol] });+ const data = JSON.parse(result);+ if (data.error) return null;+ return {+ symbol: data.symbol || symbol,+ name: data.company_name || symbol,+ exchange,+ instrumentType: 'EQUITY',+ currency: (data.currency || 'USD') as any,+ lotSize: 1,+ tickSize: 0.01,+ };+ } catch {+ return null;+ }+ }+}diff --git a/fincept-terminal-desktop/src/brokers/stocks/yfinance/index.ts b/fincept-terminal-desktop/src/brokers/stocks/yfinance/index.tsnew file mode 100644index 000000000..2dde38ea5--- /dev/null+++ b/fincept-terminal-desktop/src/brokers/stocks/yfinance/index.ts@@ -0,0 +1,7 @@+/**+ * YFinance Paper Trading Module+ *+ * Exports the YFinance paper trading adapter and related types+ */++export { YFinancePaperTradingAdapter, type UpdateInterval } from './YFinancePaperTradingAdapter';diff --git a/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx b/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsxindex a394cbcc4..2c872b75d 100644--- a/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx+++ b/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx@@ -348,19 +348,14 @@ function FinxeptTerminalContent() {if (!document.fullscreenElement) {document.documentElement.requestFullscreen().then(() => {setIsFullscreen(true);- setStatusMessage("Entered fullscreen mode");}).catch(() => {- setStatusMessage("Failed to enter fullscreen mode");+ // Silently fail});} else {document.exitFullscreen().then(() => {setIsFullscreen(false);- setStatusMessage("Exited fullscreen mode");});}-- // Clear status message after 3 seconds- setTimeout(() => setStatusMessage(""), 3000);};const handleMenuAction = async (item: any) => {diff --git a/fincept-terminal-desktop/src/components/tabs/agent-config/AgentConfigTab.tsx b/fincept-terminal-desktop/src/components/tabs/agent-config/AgentConfigTab.tsxindex 1ebd18e5e..99f5919c9 100644--- a/fincept-terminal-desktop/src/components/tabs/agent-config/AgentConfigTab.tsx+++ b/fincept-terminal-desktop/src/components/tabs/agent-config/AgentConfigTab.tsx@@ -20,7 +20,7 @@ import {GitBranch, Settings, Zap, MessageSquare, Trash2, Plus,ChevronRight, ChevronDown, Search, Copy, Check, Cpu,Sparkles, Route, ListTree, Save, Edit3, ToggleLeft, ToggleRight,- Loader2, Target, FileJson, Sliders, Database, Eye,+ Loader2, Target, FileJson, Sliders, Database, Eye, Workflow,} from 'lucide-react';import {getLLMConfigs,@@ -41,24 +41,45 @@ import agentService, {} from '@/services/agentService';// =============================================================================-// Constants & Types+// Constants & Types - Fincept Professional Terminal Palette// =============================================================================-const COLORS = {+const FINCEPT = {ORANGE: '#FF8800',WHITE: '#FFFFFF',RED: '#FF3B3B',GREEN: '#00D66F',- BLUE: '#3B82F6',- PURPLE: '#8B5CF6',+ BLUE: '#0088FF',+ PURPLE: '#9D4EDD',GRAY: '#787878',DARK_BG: '#000000',PANEL_BG: '#0F0F0F',+ HEADER_BG: '#1A1A1A',BORDER: '#2A2A2A',HOVER: '#1F1F1F',MUTED: '#4A4A4A',+ CYAN: '#00E5FF',+ YELLOW: '#FFD700',};+// Terminal Styles+const TERMINAL_STYLES = `+ .agent-terminal * {+ font-family: "IBM Plex Mono", "Consolas", monospace;+ }+ .agent-terminal::-webkit-scrollbar { width: 6px; height: 6px; }+ .agent-terminal::-webkit-scrollbar-track { background: ${FINCEPT.DARK_BG}; }+ .agent-terminal::-webkit-scrollbar-thumb { background: ${FINCEPT.BORDER}; border-radius: 3px; }+ .agent-terminal::-webkit-scrollbar-thumb:hover { background: ${FINCEPT.MUTED}; }+ .agent-hover:hover { background-color: ${FINCEPT.HOVER} !important; }+ .agent-selected {+ background-color: ${FINCEPT.ORANGE}15 !important;+ border-left: 2px solid ${FINCEPT.ORANGE} !important;+ }+ @keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.5; } }+ .agent-pulse { animation: pulse 2s infinite; }+`;+interface AgentDefinition {id: string;name: string;@@ -190,9 +211,33 @@ const AgentConfigTab: React.FC = () => {// =============================================================================useEffect(() => {- loadDiscoveredAgents();- loadSystemData();- loadLLMConfigs();+ // Load all data in parallel with timeout+ const loadInitialData = async () => {+ setLoading(true);+ setError(null);++ try {+ // Set a timeout for the entire loading process+ const timeoutPromise = new Promise((_, reject) =>+ setTimeout(() => reject(new Error('Loading timeout - please check your backend service')), 10000)+ );++ const loadPromise = Promise.all([+ loadDiscoveredAgents(),+ loadSystemData(),+ loadLLMConfigs(),+ ]);++ await Promise.race([loadPromise, timeoutPromise]);+ } catch (err: any) {+ console.error('Failed to load initial data:', err);+ setError(err.message || 'Failed to load agent data');+ } finally {+ setLoading(false);+ }+ };++ loadInitialData();}, []);useEffect(() => {@@ -230,64 +275,90 @@ const AgentConfigTab: React.FC = () => {};const loadSystemData = async () => {- const [sysInfo, tools] = await Promise.all([- agentService.getSystemInfo(),- agentService.getTools(),- ]);- if (sysInfo) setSystemInfo(sysInfo);- if (tools) setToolsInfo(tools);+ try {+ // Add timeout for system data loading+ const timeoutPromise = new Promise<never>((_, reject) =>+ setTimeout(() => reject(new Error('System data loading timeout')), 5000)+ );++ const dataPromise = Promise.all([+ agentService.getSystemInfo(),+ agentService.getTools(),+ ]);++ const [sysInfo, tools] = await Promise.race([dataPromise, timeoutPromise]);++ if (sysInfo) setSystemInfo(sysInfo);+ if (tools) setToolsInfo(tools);+ } catch (err) {+ console.error('Failed to load system data:', err);+ // Set default/empty system info+ setSystemInfo(null);+ setToolsInfo(null);+ }};const loadDiscoveredAgents = async () => {- setLoading(true);- setError(null);+ // Strategy: Use fast Rust-based discovery first (list_available_agents)+ // Only fall back to Python-based discovery if Rust failstry {- // Use the new discover_agents endpoint- const agents = await agentService.discoverAgents();- setDiscoveredAgents(agents);-- // Group by category- const byCategory: Record<string, AgentCard[]> = { all: agents };- agents.forEach(agent => {- const cat = agent.category || 'other';- if (!byCategory[cat]) byCategory[cat] = [];- byCategory[cat].push(agent);- });- setAgentsByCategory(byCategory);-- if (agents.length > 0) {- setSelectedAgent(agents[0]);- updateEditedConfigFromAgent(agents[0]);+ // First try: Fast Rust-based config file reading (no Python needed)+ console.log('[AgentConfigTab] Trying fast Rust-based agent discovery...');+ const agents = await invoke<AgentCard[]>('list_available_agents');++ if (Array.isArray(agents) && agents.length > 0) {+ console.log(`[AgentConfigTab] Loaded ${agents.length} agents via Rust (fast path)`);+ setAgentsFromList(agents);+ return;}- } catch (err: any) {- setError(err.toString());- // Fallback to legacy loading- await loadLegacyAgents();- } finally {- setLoading(false);+ } catch (rustErr) {+ console.warn('[AgentConfigTab] Rust discovery failed, trying Python fallback:', rustErr);}- };- const loadLegacyAgents = async () => {- // Fallback to reading config files directly+ // Second try: Python-based discovery with timeout (slower but more comprehensive)try {- const result = await invoke<string>('list_available_agents');- const agents = JSON.parse(result) as AgentCard[];- setDiscoveredAgents(agents);-- const byCategory: Record<string, AgentCard[]> = { all: agents };- agents.forEach(agent => {- const cat = agent.category || 'other';- if (!byCategory[cat]) byCategory[cat] = [];- byCategory[cat].push(agent);- });- setAgentsByCategory(byCategory);- } catch (err) {- console.error('Legacy agent loading failed:', err);+ const timeoutPromise = new Promise<AgentCard[]>((_, reject) =>+ setTimeout(() => reject(new Error('Agent discovery timeout')), 5000)+ );++ const discoveryPromise = agentService.discoverAgents();+ const agents = await Promise.race([discoveryPromise, timeoutPromise]);++ if (Array.isArray(agents) && agents.length > 0) {+ console.log(`[AgentConfigTab] Loaded ${agents.length} agents via Python discovery`);+ setAgentsFromList(agents);+ return;+ }+ } catch (pythonErr) {+ console.warn('[AgentConfigTab] Python discovery failed:', pythonErr);+ }++ // All methods failed - set empty state+ console.log('[AgentConfigTab] All discovery methods failed, using empty state');+ setDiscoveredAgents([]);+ setAgentsByCategory({ all: [] });+ };++ const setAgentsFromList = (agents: AgentCard[]) => {+ setDiscoveredAgents(agents);++ // Group by category+ const byCategory: Record<string, AgentCard[]> = { all: agents };+ agents.forEach(agent => {+ const cat = agent.category || 'other';+ if (!byCategory[cat]) byCategory[cat] = [];+ byCategory[cat].push(agent);+ });+ setAgentsByCategory(byCategory);++ if (agents.length > 0) {+ setSelectedAgent(agents[0]);+ updateEditedConfigFromAgent(agents[0]);}};+const updateEditedConfigFromAgent = (agent: AgentCard) => {const config = agent.config || {};const model = config.model || {};@@ -595,869 +666,1996 @@ const AgentConfigTab: React.FC = () => {};// =============================================================================- // Render: Agent Config Editor+ // Render: Agent Config Editor - Terminal Style// =============================================================================const renderAgentConfigEditor = () => (- <div className="space-y-4 p-4 rounded-lg" style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>- <div className="flex items-center justify-between">- <h3 className="text-sm font-semibold flex items-center gap-2" style={{ color: COLORS.WHITE }}>- <Sliders size={16} style={{ color: COLORS.ORANGE }} />- Agent Configuration- </h3>+ <div style={{+ backgroundColor: FINCEPT.PANEL_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ }}>+ {/* Header */}+ <div style={{+ padding: '12px',+ backgroundColor: FINCEPT.HEADER_BG,+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <Sliders size={14} style={{ color: FINCEPT.ORANGE }} />+ <span style={{ fontSize: '11px', fontWeight: 700, color: FINCEPT.WHITE }}>+ AGENT CONFIGURATION+ </span>+ </div><buttononClick={() => setEditMode(!editMode)}- className="px-2 py-1 rounded text-xs flex items-center gap-1"- style={{ backgroundColor: COLORS.BORDER, color: COLORS.WHITE }}+ style={{+ padding: '4px 10px',+ backgroundColor: editMode ? `${FINCEPT.GREEN}20` : 'transparent',+ border: `1px solid ${editMode ? FINCEPT.GREEN : FINCEPT.BORDER}`,+ color: editMode ? FINCEPT.GREEN : FINCEPT.GRAY,+ fontSize: '9px',+ fontWeight: 700,+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ borderRadius: '2px',+ }}>- <Edit3 size={12} />- {editMode ? 'Done' : 'Edit'}+ <Edit3 size={10} />+ {editMode ? 'EDITING' : 'EDIT'}</button></div>- {/* LLM Selection - Only from Settings */}- {configuredLLMs.length > 0 ? (- <div className="p-3 rounded-lg" style={{ backgroundColor: COLORS.DARK_BG, border: `1px solid ${COLORS.GREEN}40` }}>- <div className="text-xs font-medium mb-2 flex items-center gap-2" style={{ color: COLORS.GREEN }}>- <CheckCircle size={12} />- SELECT LLM (from Settings)+ <div style={{ padding: '16px', display: 'flex', flexDirection: 'column', gap: '16px' }}>+ {/* LLM Selection */}+ {configuredLLMs.length > 0 ? (+ <div style={{+ padding: '12px',+ backgroundColor: FINCEPT.DARK_BG,+ border: `1px solid ${FINCEPT.GREEN}40`,+ borderRadius: '2px',+ }}>+ <div style={{+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ marginBottom: '10px',+ }}>+ <CheckCircle size={10} style={{ color: FINCEPT.GREEN }} />+ <span style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.GREEN }}>+ SELECT LLM PROVIDER+ </span>+ </div>+ <div style={{ display: 'flex', flexWrap: 'wrap', gap: '6px' }}>+ {configuredLLMs.map((llm, idx) => {+ const hasKey = !!llm.api_key && llm.api_key.length > 0;+ const isSelected = editedConfig.provider === llm.provider && editedConfig.model_id === llm.model;+ return (+ <button+ key={idx}+ onClick={() => editMode && setEditedConfig(prev => ({+ ...prev,+ provider: llm.provider,+ model_id: llm.model,+ }))}+ style={{+ padding: '6px 10px',+ backgroundColor: isSelected ? FINCEPT.ORANGE : FINCEPT.BORDER,+ color: isSelected ? FINCEPT.DARK_BG : FINCEPT.WHITE,+ border: 'none',+ borderRadius: '2px',+ fontSize: '9px',+ fontWeight: 600,+ cursor: editMode ? 'pointer' : 'default',+ opacity: hasKey ? 1 : 0.5,+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ }}+ >+ {llm.is_active && <span style={{ color: isSelected ? FINCEPT.DARK_BG : FINCEPT.GREEN }}>●</span>}+ <span>{llm.provider.toUpperCase()}</span>+ <span style={{ color: isSelected ? FINCEPT.DARK_BG : FINCEPT.GRAY }}>/ {llm.model}</span>+ {!hasKey && <AlertCircle size={10} style={{ color: FINCEPT.RED }} />}+ </button>+ );+ })}+ </div>+ {configuredLLMs.some(l => !l.api_key || l.api_key.length === 0) && (+ <div style={{ fontSize: '9px', marginTop: '8px', color: FINCEPT.RED }}>+ ⚠ Some providers missing API keys - configure in Settings+ </div>+ )}</div>- <div className="flex flex-wrap gap-2">- {configuredLLMs.map((llm, idx) => {- const hasKey = !!llm.api_key && llm.api_key.length > 0;- const isSelected = editedConfig.provider === llm.provider && editedConfig.model_id === llm.model;- return (- <button- key={idx}- onClick={() => editMode && setEditedConfig(prev => ({- ...prev,- provider: llm.provider,- model_id: llm.model,- }))}- className="px-3 py-2 rounded text-xs flex items-center gap-2 transition-colors"- style={{- backgroundColor: isSelected ? COLORS.ORANGE : COLORS.BORDER,- color: COLORS.WHITE,- cursor: editMode ? 'pointer' : 'default',- opacity: hasKey ? 1 : 0.5,- }}- >- {llm.is_active && <span style={{ color: COLORS.GREEN }}>●</span>}- <span className="font-medium">{llm.provider}</span>- <span style={{ color: isSelected ? COLORS.WHITE : COLORS.GRAY }}>/ {llm.model}</span>- {!hasKey && <AlertCircle size={10} style={{ color: COLORS.RED }} />}- </button>- );- })}+ ) : (+ <div style={{+ padding: '12px',+ backgroundColor: FINCEPT.DARK_BG,+ border: `1px solid ${FINCEPT.RED}40`,+ borderRadius: '2px',+ }}>+ <div style={{+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ marginBottom: '6px',+ }}>+ <AlertCircle size={10} style={{ color: FINCEPT.RED }} />+ <span style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.RED }}>+ NO LLM CONFIGURED+ </span>+ </div>+ <span style={{ fontSize: '9px', color: FINCEPT.GRAY }}>+ Go to Settings → LLM Configuration to add API keys.+ </span></div>- {configuredLLMs.some(l => !l.api_key || l.api_key.length === 0) && (- <div className="text-xs mt-2" style={{ color: COLORS.RED }}>- ⚠ Some providers missing API keys - configure in Settings → LLM Configuration+ )}++ {/* Parameters Grid */}+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>+ {/* Provider */}+ <div>+ <label style={{ display: 'block', fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, marginBottom: '6px' }}>+ PROVIDER+ </label>+ <div style={{+ padding: '8px 10px',+ backgroundColor: FINCEPT.DARK_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ fontSize: '10px',+ color: FINCEPT.CYAN,+ }}>+ {editedConfig.provider || 'None'}</div>- )}- </div>- ) : (- <div className="p-3 rounded-lg" style={{ backgroundColor: COLORS.DARK_BG, border: `1px solid ${COLORS.RED}40` }}>- <div className="text-xs font-medium mb-2 flex items-center gap-2" style={{ color: COLORS.RED }}>- <AlertCircle size={12} />- NO LLM CONFIGURED</div>- <p className="text-xs" style={{ color: COLORS.GRAY }}>- Go to Settings → LLM Configuration to add API keys for your preferred providers.- </p>- </div>- )}- <div className="grid grid-cols-2 gap-4">- {/* Current Selection Display */}- <div>- <label className="text-xs mb-1 block" style={{ color: COLORS.GRAY }}>Selected Provider</label>- <div- className="w-full px-3 py-2 rounded text-sm"- style={{- backgroundColor: COLORS.DARK_BG,- color: COLORS.WHITE,- border: `1px solid ${COLORS.BORDER}`,- }}- >- {editedConfig.provider || 'None selected'}+ {/* Model */}+ <div>+ <label style={{ display: 'block', fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, marginBottom: '6px' }}>+ MODEL+ </label>+ <div style={{+ padding: '8px 10px',+ backgroundColor: FINCEPT.DARK_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ fontSize: '10px',+ color: FINCEPT.CYAN,+ }}>+ {editedConfig.model_id || 'None'}+ </div></div>- </div>- {/* Current Model Display */}- <div>- <label className="text-xs mb-1 block" style={{ color: COLORS.GRAY }}>Selected Model</label>- <div- className="w-full px-3 py-2 rounded text-sm"- style={{- backgroundColor: COLORS.DARK_BG,- color: COLORS.WHITE,- border: `1px solid ${COLORS.BORDER}`,- }}- >- {editedConfig.model_id || 'None selected'}+ {/* Temperature */}+ <div>+ <label style={{ display: 'block', fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, marginBottom: '6px' }}>+ TEMPERATURE: <span style={{ color: FINCEPT.YELLOW }}>{editedConfig.temperature.toFixed(2)}</span>+ </label>+ <input+ type="range"+ min="0"+ max="2"+ step="0.1"+ value={editedConfig.temperature}+ onChange={e => setEditedConfig(prev => ({ ...prev, temperature: parseFloat(e.target.value) }))}+ disabled={!editMode}+ style={{+ width: '100%',+ accentColor: FINCEPT.ORANGE,+ opacity: editMode ? 1 : 0.7,+ }}+ /></div>- </div>- {/* Temperature */}- <div>- <label className="text-xs mb-1 block" style={{ color: COLORS.GRAY }}>- Temperature: {editedConfig.temperature.toFixed(2)}- </label>- <input- type="range"- min="0"- max="2"- step="0.1"- value={editedConfig.temperature}- onChange={e => setEditedConfig(prev => ({ ...prev, temperature: parseFloat(e.target.value) }))}- disabled={!editMode}- className="w-full"- style={{ accentColor: COLORS.ORANGE }}- />+ {/* Max Tokens */}+ <div>+ <label style={{ display: 'block', fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, marginBottom: '6px' }}>+ MAX TOKENS+ </label>+ <input+ type="number"+ value={editedConfig.max_tokens}+ onChange={e => setEditedConfig(prev => ({ ...prev, max_tokens: parseInt(e.target.value) || 4096 }))}+ disabled={!editMode}+ style={{+ width: '100%',+ padding: '8px 10px',+ backgroundColor: FINCEPT.DARK_BG,+ color: FINCEPT.YELLOW,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ fontSize: '10px',+ fontFamily: '"IBM Plex Mono", monospace',+ opacity: editMode ? 1 : 0.7,+ }}+ />+ </div></div>- {/* Max Tokens */}- <div>- <label className="text-xs mb-1 block" style={{ color: COLORS.GRAY }}>Max Tokens</label>- <input- type="number"- value={editedConfig.max_tokens}- onChange={e => setEditedConfig(prev => ({ ...prev, max_tokens: parseInt(e.target.value) || 4096 }))}- disabled={!editMode}- className="w-full px-3 py-2 rounded text-sm"+ {/* Toggle Options */}+ <div style={{ display: 'flex', gap: '8px' }}>+ <button+ onClick={() => editMode && setEditedConfig(prev => ({ ...prev, enable_memory: !prev.enable_memory }))}style={{- backgroundColor: COLORS.DARK_BG,- color: COLORS.WHITE,- border: `1px solid ${COLORS.BORDER}`,- opacity: editMode ? 1 : 0.7,+ padding: '8px 12px',+ backgroundColor: editedConfig.enable_memory ? `${FINCEPT.ORANGE}20` : FINCEPT.DARK_BG,+ border: `1px solid ${editedConfig.enable_memory ? FINCEPT.ORANGE : FINCEPT.BORDER}`,+ color: editedConfig.enable_memory ? FINCEPT.ORANGE : FINCEPT.GRAY,+ fontSize: '9px',+ fontWeight: 700,+ cursor: editMode ? 'pointer' : 'default',+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ borderRadius: '2px',}}- />- </div>- </div>-- {/* Toggle Options */}- <div className="flex gap-4">- <button- onClick={() => editMode && setEditedConfig(prev => ({ ...prev, enable_memory: !prev.enable_memory }))}- className="flex items-center gap-2 px-3 py-2 rounded text-sm"- style={{- backgroundColor: editedConfig.enable_memory ? COLORS.ORANGE + '20' : COLORS.BORDER,- color: editedConfig.enable_memory ? COLORS.ORANGE : COLORS.GRAY,- cursor: editMode ? 'pointer' : 'default',- }}- >- {editedConfig.enable_memory ? <ToggleRight size={16} /> : <ToggleLeft size={16} />}- Memory- </button>-- <button- onClick={() => editMode && setEditedConfig(prev => ({ ...prev, enable_reasoning: !prev.enable_reasoning }))}- className="flex items-center gap-2 px-3 py-2 rounded text-sm"- style={{- backgroundColor: editedConfig.enable_reasoning ? COLORS.PURPLE + '20' : COLORS.BORDER,- color: editedConfig.enable_reasoning ? COLORS.PURPLE : COLORS.GRAY,- cursor: editMode ? 'pointer' : 'default',- }}- >- {editedConfig.enable_reasoning ? <ToggleRight size={16} /> : <ToggleLeft size={16} />}- Reasoning- </button>- </div>+ >+ {editedConfig.enable_memory ? <ToggleRight size={14} /> : <ToggleLeft size={14} />}+ MEMORY+ </button>- {/* Instructions */}- {editMode && (- <div>- <label className="text-xs mb-1 block" style={{ color: COLORS.GRAY }}>Instructions</label>- <textarea- value={editedConfig.instructions}- onChange={e => setEditedConfig(prev => ({ ...prev, instructions: e.target.value }))}- rows={4}- className="w-full px-3 py-2 rounded text-sm font-mono"+ <button+ onClick={() => editMode && setEditedConfig(prev => ({ ...prev, enable_reasoning: !prev.enable_reasoning }))}style={{- backgroundColor: COLORS.DARK_BG,- color: COLORS.WHITE,- border: `1px solid ${COLORS.BORDER}`,+ padding: '8px 12px',+ backgroundColor: editedConfig.enable_reasoning ? `${FINCEPT.PURPLE}20` : FINCEPT.DARK_BG,+ border: `1px solid ${editedConfig.enable_reasoning ? FINCEPT.PURPLE : FINCEPT.BORDER}`,+ color: editedConfig.enable_reasoning ? FINCEPT.PURPLE : FINCEPT.GRAY,+ fontSize: '9px',+ fontWeight: 700,+ cursor: editMode ? 'pointer' : 'default',+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ borderRadius: '2px',}}- placeholder="Enter agent instructions..."- />+ >+ {editedConfig.enable_reasoning ? <ToggleRight size={14} /> : <ToggleLeft size={14} />}+ REASONING+ </button></div>- )}- {/* Selected Tools */}- {editedConfig.tools.length > 0 && (- <div>- <label className="text-xs mb-1 block" style={{ color: COLORS.GRAY }}>- Tools ({editedConfig.tools.length})- </label>- <div className="flex flex-wrap gap-1">- {editedConfig.tools.map(tool => (- <span- key={tool}- onClick={() => editMode && toggleToolSelection(tool)}- className="px-2 py-0.5 rounded text-xs cursor-pointer"- style={{ backgroundColor: COLORS.ORANGE + '30', color: COLORS.ORANGE }}- >- {tool} {editMode && '×'}- </span>- ))}+ {/* Instructions */}+ {editMode && (+ <div>+ <label style={{ display: 'block', fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, marginBottom: '6px' }}>+ INSTRUCTIONS+ </label>+ <textarea+ value={editedConfig.instructions}+ onChange={e => setEditedConfig(prev => ({ ...prev, instructions: e.target.value }))}+ rows={3}+ placeholder="Enter agent instructions..."+ style={{+ width: '100%',+ padding: '10px',+ backgroundColor: FINCEPT.DARK_BG,+ color: FINCEPT.WHITE,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ fontSize: '10px',+ fontFamily: '"IBM Plex Mono", monospace',+ resize: 'none',+ }}+ /></div>- </div>- )}+ )}++ {/* Selected Tools */}+ {editedConfig.tools.length > 0 && (+ <div>+ <label style={{ display: 'block', fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, marginBottom: '6px' }}>+ TOOLS ({editedConfig.tools.length})+ </label>+ <div style={{ display: 'flex', flexWrap: 'wrap', gap: '4px' }}>+ {editedConfig.tools.map(tool => (+ <span+ key={tool}+ onClick={() => editMode && toggleToolSelection(tool)}+ style={{+ padding: '4px 8px',+ backgroundColor: `${FINCEPT.ORANGE}20`,+ color: FINCEPT.ORANGE,+ fontSize: '9px',+ borderRadius: '2px',+ cursor: editMode ? 'pointer' : 'default',+ }}+ >+ {tool} {editMode && '×'}+ </span>+ ))}+ </div>+ </div>+ )}+ </div></div>);// =============================================================================- // Render: Agents View+ // Render: Agents View - Three Panel Terminal Layout// =============================================================================const renderAgentsView = () => (- <div className="flex h-full">- {/* Sidebar */}- <div className="w-72 border-r flex flex-col" style={{ borderColor: COLORS.BORDER }}>- {/* Header with Refresh */}- <div className="p-3 border-b flex items-center justify-between" style={{ borderColor: COLORS.BORDER }}>- <div className="text-xs font-medium" style={{ color: COLORS.GRAY }}>- DISCOVERED AGENTS ({discoveredAgents.length})+ <div style={{+ display: 'flex',+ height: '100%',+ overflow: 'hidden',+ }}>+ {/* LEFT SIDEBAR - Agent List (280px fixed) */}+ <div style={{+ width: '280px',+ minWidth: '280px',+ backgroundColor: FINCEPT.PANEL_BG,+ borderRight: `1px solid ${FINCEPT.BORDER}`,+ display: 'flex',+ flexDirection: 'column',+ flexShrink: 0,+ }}>+ {/* Sidebar Header */}+ <div style={{+ padding: '12px',+ backgroundColor: FINCEPT.HEADER_BG,+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ }}>+ <div style={{+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ marginBottom: '8px',+ }}>+ <span style={{+ fontSize: '9px',+ fontWeight: 700,+ color: FINCEPT.GRAY,+ letterSpacing: '0.5px',+ }}>+ AGENTS ({discoveredAgents.length})+ </span>+ <button+ onClick={loadDiscoveredAgents}+ disabled={loading}+ style={{+ padding: '4px',+ backgroundColor: 'transparent',+ border: 'none',+ cursor: loading ? 'not-allowed' : 'pointer',+ opacity: loading ? 0.5 : 1,+ }}+ >+ <RefreshCw size={12} className={loading ? 'animate-spin' : ''} style={{ color: FINCEPT.ORANGE }} />+ </button></div>- <button- onClick={loadDiscoveredAgents}- disabled={loading}- className="p-1.5 rounded hover:bg-[#1F1F1F]"- >- <RefreshCw size={14} className={loading ? 'animate-spin' : ''} style={{ color: COLORS.ORANGE }} />- </button>- </div>-- {/* Category Filter */}- <div className="p-2 border-b" style={{ borderColor: COLORS.BORDER }}>+ {/* Category Filter */}<selectvalue={selectedCategory}onChange={e => setSelectedCategory(e.target.value)}- className="w-full px-2 py-1.5 rounded text-sm"- style={{ backgroundColor: COLORS.PANEL_BG, color: COLORS.WHITE, border: `1px solid ${COLORS.BORDER}` }}+ style={{+ width: '100%',+ padding: '6px 8px',+ backgroundColor: FINCEPT.DARK_BG,+ color: FINCEPT.WHITE,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ fontSize: '10px',+ cursor: 'pointer',+ }}><option value="all">All Categories ({discoveredAgents.length})</option>{Object.entries(agentsByCategory).filter(([k]) => k !== 'all').map(([cat, agents]) => (- <option key={cat} value={cat}>{cat} ({agents.length})</option>+ <option key={cat} value={cat}>{cat.toUpperCase()} ({agents.length})</option>))}</select></div>{/* Agent List */}- <div className="flex-1 overflow-y-auto p-2">+ <div style={{ flex: 1, overflow: 'auto', padding: '4px' }}>{loading ? (- <div className="flex items-center justify-center py-8">- <Loader2 size={20} className="animate-spin" style={{ color: COLORS.ORANGE }} />+ <div style={{+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ justifyContent: 'center',+ padding: '32px 16px',+ }}>+ <Loader2 size={20} className="animate-spin" style={{ color: FINCEPT.ORANGE, marginBottom: '12px' }} />+ <span style={{ fontSize: '10px', color: FINCEPT.GRAY }}>Loading agents...</span></div>- ) : (- <div className="space-y-1">- {(agentsByCategory[selectedCategory] || []).map(agent => (- <button- key={agent.id}- onClick={() => {- setSelectedAgent(agent);- updateEditedConfigFromAgent(agent);- }}- className="w-full text-left px-3 py-2 rounded text-sm transition-colors"- style={{- backgroundColor: selectedAgent?.id === agent.id ? COLORS.HOVER : 'transparent',- color: selectedAgent?.id === agent.id ? COLORS.ORANGE : COLORS.WHITE,- }}- >- <div className="font-medium truncate">{agent.name}</div>- <div className="text-xs truncate" style={{ color: COLORS.GRAY }}>- {agent.category} • v{agent.version}- </div>- </button>- ))}+ ) : discoveredAgents.length === 0 ? (+ <div style={{+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ justifyContent: 'center',+ padding: '32px 16px',+ textAlign: 'center',+ }}>+ <Bot size={32} style={{ color: FINCEPT.MUTED, marginBottom: '12px', opacity: 0.5 }} />+ <span style={{ fontSize: '10px', color: FINCEPT.GRAY, marginBottom: '8px' }}>No agents discovered</span>+ <button+ onClick={loadDiscoveredAgents}+ style={{+ padding: '6px 12px',+ backgroundColor: FINCEPT.ORANGE,+ color: FINCEPT.WHITE,+ border: 'none',+ borderRadius: '2px',+ fontSize: '9px',+ fontWeight: 700,+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ }}+ >+ <RefreshCw size={10} /> RETRY+ </button></div>+ ) : (+ (agentsByCategory[selectedCategory] || []).map(agent => (+ <div+ key={agent.id}+ onClick={() => {+ setSelectedAgent(agent);+ updateEditedConfigFromAgent(agent);+ }}+ style={{+ padding: '10px 12px',+ marginBottom: '2px',+ backgroundColor: selectedAgent?.id === agent.id ? `${FINCEPT.ORANGE}15` : 'transparent',+ borderLeft: selectedAgent?.id === agent.id ? `2px solid ${FINCEPT.ORANGE}` : '2px solid transparent',+ cursor: 'pointer',+ transition: 'all 0.2s',+ }}+ onMouseEnter={(e) => {+ if (selectedAgent?.id !== agent.id) {+ e.currentTarget.style.backgroundColor = FINCEPT.HOVER;+ }+ }}+ onMouseLeave={(e) => {+ if (selectedAgent?.id !== agent.id) {+ e.currentTarget.style.backgroundColor = 'transparent';+ }+ }}+ >+ <div style={{+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ marginBottom: '4px',+ }}>+ <span style={{+ fontSize: '11px',+ fontWeight: 600,+ color: selectedAgent?.id === agent.id ? FINCEPT.ORANGE : FINCEPT.WHITE,+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ }}>+ {agent.name}+ </span>+ <span style={{+ fontSize: '8px',+ padding: '2px 4px',+ backgroundColor: `${FINCEPT.CYAN}20`,+ color: FINCEPT.CYAN,+ borderRadius: '2px',+ }}>+ v{agent.version}+ </span>+ </div>+ <div style={{+ fontSize: '9px',+ color: FINCEPT.GRAY,+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ }}>+ {agent.category}+ </div>+ </div>+ )))}</div>++ {/* Quick Stats at Bottom */}+ <div style={{+ padding: '12px',+ backgroundColor: FINCEPT.HEADER_BG,+ borderTop: `1px solid ${FINCEPT.BORDER}`,+ display: 'grid',+ gridTemplateColumns: '1fr 1fr',+ gap: '8px',+ }}>+ <div style={{+ padding: '8px',+ backgroundColor: FINCEPT.DARK_BG,+ borderRadius: '2px',+ textAlign: 'center',+ }}>+ <div style={{ fontSize: '14px', fontWeight: 700, color: FINCEPT.CYAN }}>{discoveredAgents.length}</div>+ <div style={{ fontSize: '8px', color: FINCEPT.GRAY }}>TOTAL</div>+ </div>+ <div style={{+ padding: '8px',+ backgroundColor: FINCEPT.DARK_BG,+ borderRadius: '2px',+ textAlign: 'center',+ }}>+ <div style={{ fontSize: '14px', fontWeight: 700, color: FINCEPT.GREEN }}>{teamMembers.length}</div>+ <div style={{ fontSize: '8px', color: FINCEPT.GRAY }}>IN TEAM</div>+ </div>+ </div></div>- {/* Main Content */}- <div className="flex-1 flex flex-col overflow-hidden">+ {/* CENTER - Main Content Area */}+ <div style={{+ flex: 1,+ display: 'flex',+ flexDirection: 'column',+ overflow: 'hidden',+ minWidth: 0,+ }}>{selectedAgent ? (<>- {/* Agent Header */}- <div className="p-4 border-b" style={{ borderColor: COLORS.BORDER }}>- <div className="flex items-center justify-between">- <div>- <h2 className="text-lg font-semibold" style={{ color: COLORS.WHITE }}>{selectedAgent.name}</h2>- <p className="text-sm" style={{ color: COLORS.GRAY }}>{selectedAgent.description}</p>- </div>- <div className="flex gap-2">- <button- onClick={() => addToTeam(selectedAgent)}- className="px-3 py-1.5 rounded text-sm flex items-center gap-1"- style={{ backgroundColor: COLORS.BORDER, color: COLORS.WHITE }}- >- <Plus size={14} /> Add to Team- </button>- <button- onClick={() => setShowJsonEditor(!showJsonEditor)}- className="px-3 py-1.5 rounded text-sm flex items-center gap-1"- style={{ backgroundColor: COLORS.BORDER, color: COLORS.WHITE }}- >- <FileJson size={14} /> {showJsonEditor ? 'Hide' : 'Show'} JSON- </button>- </div>- </div>-- {/* Capabilities */}- {selectedAgent.capabilities && selectedAgent.capabilities.length > 0 && (- <div className="mt-2 flex flex-wrap gap-1">- {selectedAgent.capabilities.map(cap => (- <span key={cap} className="px-2 py-0.5 rounded text-xs" style={{ backgroundColor: COLORS.BLUE + '20', color: COLORS.BLUE }}>+ {/* Agent Info Bar */}+ <div style={{+ padding: '12px 16px',+ backgroundColor: FINCEPT.HEADER_BG,+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ }}>+ <div style={{ flex: 1, minWidth: 0 }}>+ <div style={{+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ marginBottom: '4px',+ }}>+ <span style={{+ fontSize: '14px',+ fontWeight: 700,+ color: FINCEPT.WHITE,+ }}>+ {selectedAgent.name}+ </span>+ {selectedAgent.capabilities && selectedAgent.capabilities.slice(0, 3).map(cap => (+ <span key={cap} style={{+ padding: '2px 6px',+ backgroundColor: `${FINCEPT.BLUE}20`,+ color: FINCEPT.BLUE,+ fontSize: '8px',+ borderRadius: '2px',+ }}>{cap}</span>))}</div>- )}+ <div style={{+ fontSize: '10px',+ color: FINCEPT.GRAY,+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ }}>+ {selectedAgent.description}+ </div>+ </div>+ <div style={{ display: 'flex', gap: '8px', flexShrink: 0 }}>+ <button+ onClick={() => addToTeam(selectedAgent)}+ style={{+ padding: '6px 10px',+ backgroundColor: 'transparent',+ border: `1px solid ${FINCEPT.BORDER}`,+ color: FINCEPT.WHITE,+ fontSize: '9px',+ fontWeight: 700,+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ borderRadius: '2px',+ }}+ >+ <Plus size={10} /> ADD TO TEAM+ </button>+ <button+ onClick={() => setShowJsonEditor(!showJsonEditor)}+ style={{+ padding: '6px 10px',+ backgroundColor: showJsonEditor ? `${FINCEPT.PURPLE}20` : 'transparent',+ border: `1px solid ${showJsonEditor ? FINCEPT.PURPLE : FINCEPT.BORDER}`,+ color: showJsonEditor ? FINCEPT.PURPLE : FINCEPT.GRAY,+ fontSize: '9px',+ fontWeight: 700,+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ borderRadius: '2px',+ }}+ >+ <FileJson size={10} /> JSON+ </button>+ </div></div>- {/* Content */}- <div className="flex-1 overflow-y-auto p-4 space-y-4">- {showJsonEditor ? (- <textarea- value={jsonText}- onChange={e => setJsonText(e.target.value)}- className="w-full h-64 p-3 rounded font-mono text-sm"- style={{ backgroundColor: COLORS.PANEL_BG, color: COLORS.WHITE, border: `1px solid ${COLORS.BORDER}` }}- />- ) : (- <>- {/* Config Editor */}- {renderAgentConfigEditor()}-- {/* SuperAgent Routing Toggle */}- <div className="p-3 rounded-lg flex items-center justify-between" style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>- <div className="flex items-center gap-2">- <Route size={16} style={{ color: COLORS.PURPLE }} />- <div>- <div className="text-sm font-medium" style={{ color: COLORS.WHITE }}>SuperAgent Auto-Routing</div>- <div className="text-xs" style={{ color: COLORS.GRAY }}>Automatically route queries to the best agent</div>+ {/* Main Content - Split View */}+ <div style={{+ flex: 1,+ display: 'flex',+ overflow: 'hidden',+ }}>+ {/* Config Area */}+ <div style={{+ flex: 1,+ overflow: 'auto',+ padding: '16px',+ }}>+ {showJsonEditor ? (+ <textarea+ value={jsonText}+ onChange={e => setJsonText(e.target.value)}+ style={{+ width: '100%',+ height: '100%',+ padding: '12px',+ backgroundColor: FINCEPT.DARK_BG,+ color: FINCEPT.WHITE,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ fontSize: '11px',+ fontFamily: '"IBM Plex Mono", monospace',+ resize: 'none',+ }}+ />+ ) : (+ <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>+ {/* Config Editor */}+ {renderAgentConfigEditor()}++ {/* Routing Toggle */}+ <div style={{+ padding: '12px',+ backgroundColor: FINCEPT.PANEL_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>+ <Route size={16} style={{ color: FINCEPT.PURPLE }} />+ <div>+ <div style={{ fontSize: '11px', fontWeight: 600, color: FINCEPT.WHITE }}>+ SuperAgent Auto-Routing+ </div>+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY }}>+ Automatically route queries to the best agent+ </div>+ </div></div>+ <button+ onClick={() => setUseAutoRouting(!useAutoRouting)}+ style={{+ background: 'none',+ border: 'none',+ cursor: 'pointer',+ color: useAutoRouting ? FINCEPT.GREEN : FINCEPT.GRAY,+ }}+ >+ {useAutoRouting ? <ToggleRight size={24} /> : <ToggleLeft size={24} />}+ </button></div>- <button- onClick={() => setUseAutoRouting(!useAutoRouting)}- className="p-2 rounded"- style={{ color: useAutoRouting ? COLORS.GREEN : COLORS.GRAY }}- >- {useAutoRouting ? <ToggleRight size={24} /> : <ToggleLeft size={24} />}- </button>- </div>- {/* Last Routing Result */}- {lastRoutingResult && (- <div className="p-3 rounded-lg" style={{ backgroundColor: COLORS.PURPLE + '10', border: `1px solid ${COLORS.PURPLE}40` }}>- <div className="text-xs font-medium mb-1" style={{ color: COLORS.PURPLE }}>LAST ROUTING</div>- <div className="text-sm" style={{ color: COLORS.WHITE }}>- Intent: <span style={{ color: COLORS.ORANGE }}>{lastRoutingResult.intent}</span>- {' • '}Agent: <span style={{ color: COLORS.ORANGE }}>{lastRoutingResult.agent_id}</span>- {' • '}Confidence: <span style={{ color: COLORS.GREEN }}>{(lastRoutingResult.confidence * 100).toFixed(0)}%</span>+ {/* Last Routing Result */}+ {lastRoutingResult && (+ <div style={{+ padding: '12px',+ backgroundColor: `${FINCEPT.PURPLE}10`,+ border: `1px solid ${FINCEPT.PURPLE}40`,+ borderRadius: '2px',+ }}>+ <div style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.PURPLE, marginBottom: '6px' }}>+ LAST ROUTING RESULT+ </div>+ <div style={{ fontSize: '11px', color: FINCEPT.WHITE }}>+ <span style={{ color: FINCEPT.GRAY }}>Intent:</span>{' '}+ <span style={{ color: FINCEPT.ORANGE }}>{lastRoutingResult.intent}</span>+ {' • '}+ <span style={{ color: FINCEPT.GRAY }}>Agent:</span>{' '}+ <span style={{ color: FINCEPT.ORANGE }}>{lastRoutingResult.agent_id}</span>+ {' • '}+ <span style={{ color: FINCEPT.GRAY }}>Confidence:</span>{' '}+ <span style={{ color: FINCEPT.GREEN }}>{(lastRoutingResult.confidence * 100).toFixed(0)}%</span>+ </div></div>- </div>- )}- </>- )}-- {/* Query Input */}- <div className="space-y-3">- <div>- <div className="text-xs font-medium mb-1" style={{ color: COLORS.GRAY }}>OUTPUT MODEL (Optional)</div>- <select- value={selectedOutputModel}- onChange={e => setSelectedOutputModel(e.target.value)}- className="w-full px-3 py-2 rounded text-sm"- style={{ backgroundColor: COLORS.PANEL_BG, color: COLORS.WHITE, border: `1px solid ${COLORS.BORDER}` }}- >- <option value="">None (free text)</option>- {OUTPUT_MODELS.map(m => (- <option key={m.id} value={m.id}>{m.name}</option>- ))}- </select>- </div>-- <div>- <div className="text-xs font-medium mb-1" style={{ color: COLORS.GRAY }}>QUERY</div>- <textarea- value={testQuery}- onChange={e => setTestQuery(e.target.value)}- placeholder="Enter your query..."- rows={3}- className="w-full px-3 py-2 rounded text-sm"- style={{ backgroundColor: COLORS.PANEL_BG, color: COLORS.WHITE, border: `1px solid ${COLORS.BORDER}` }}- />- </div>-- <button- onClick={runAgent}- disabled={loading}- className="w-full py-2 rounded font-medium flex items-center justify-center gap-2"- style={{ backgroundColor: COLORS.ORANGE, color: COLORS.WHITE, opacity: loading ? 0.5 : 1 }}- >- {loading ? <Loader2 size={16} className="animate-spin" /> : <Play size={16} />}- {useAutoRouting ? 'Run with Auto-Routing' : 'Run Agent'}- </button>+ )}+ </div>+ )}</div>-- {/* Result */}- {testResult && (- <div className="p-3 rounded" style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>- <div className="text-xs font-medium mb-2" style={{ color: COLORS.GRAY }}>RESULT</div>- <pre className="text-sm whitespace-pre-wrap" style={{ color: COLORS.WHITE }}>- {typeof testResult === 'string' ? testResult : JSON.stringify(testResult, null, 2)}- </pre>- </div>- )}</div></>) : (- <div className="flex-1 flex items-center justify-center" style={{ color: COLORS.GRAY }}>- <div className="text-center">- <Bot size={48} className="mx-auto mb-4 opacity-50" />- <p>Select an agent to view details</p>- <p className="text-sm mt-2">or click Refresh to discover agents</p>+ <div style={{+ flex: 1,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ backgroundColor: FINCEPT.PANEL_BG,+ }}>+ <div style={{ textAlign: 'center', padding: '32px' }}>+ <Bot size={48} style={{ color: FINCEPT.MUTED, marginBottom: '16px', opacity: 0.5 }} />+ <div style={{ fontSize: '12px', color: FINCEPT.GRAY, marginBottom: '8px' }}>+ Select an agent to view details+ </div>+ {discoveredAgents.length === 0 && (+ <button+ onClick={() => setViewMode('chat')}+ style={{+ padding: '8px 16px',+ backgroundColor: FINCEPT.ORANGE,+ color: FINCEPT.WHITE,+ border: 'none',+ borderRadius: '2px',+ fontSize: '10px',+ fontWeight: 700,+ cursor: 'pointer',+ }}+ >+ GO TO CHAT+ </button>+ )}</div></div>)}</div>- </div>- );- // =============================================================================- // Render: Teams View- // =============================================================================+ {/* RIGHT PANEL - Query & Results (300px fixed) */}+ <div style={{+ width: '300px',+ minWidth: '300px',+ backgroundColor: FINCEPT.PANEL_BG,+ borderLeft: `1px solid ${FINCEPT.BORDER}`,+ display: 'flex',+ flexDirection: 'column',+ flexShrink: 0,+ }}>+ {/* Panel Header */}+ <div style={{+ padding: '12px',+ backgroundColor: FINCEPT.HEADER_BG,+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ }}>+ <span style={{+ fontSize: '9px',+ fontWeight: 700,+ color: FINCEPT.GRAY,+ letterSpacing: '0.5px',+ }}>+ QUERY EXECUTION+ </span>+ </div>- const renderTeamsView = () => (- <div className="p-4 space-y-4">- <div className="flex items-center justify-between">- <h2 className="text-lg font-semibold" style={{ color: COLORS.WHITE }}>Team Builder</h2>- <select- value={teamMode}- onChange={e => setTeamMode(e.target.value as any)}- className="px-3 py-1.5 rounded text-sm"- style={{ backgroundColor: COLORS.PANEL_BG, color: COLORS.WHITE, border: `1px solid ${COLORS.BORDER}` }}- >- <option value="coordinate">Coordinate (Sequential)</option>- <option value="route">Route (Best Match)</option>- <option value="collaborate">Collaborate (Parallel)</option>- </select>- </div>+ {/* Query Form */}+ <div style={{ padding: '12px', display: 'flex', flexDirection: 'column', gap: '12px' }}>+ {/* Output Model */}+ <div>+ <label style={{+ display: 'block',+ fontSize: '9px',+ fontWeight: 700,+ color: FINCEPT.GRAY,+ marginBottom: '6px',+ }}>+ OUTPUT MODEL+ </label>+ <select+ value={selectedOutputModel}+ onChange={e => setSelectedOutputModel(e.target.value)}+ style={{+ width: '100%',+ padding: '8px 10px',+ backgroundColor: FINCEPT.DARK_BG,+ color: FINCEPT.WHITE,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ fontSize: '10px',+ }}+ >+ <option value="">None (free text)</option>+ {OUTPUT_MODELS.map(m => (+ <option key={m.id} value={m.id}>{m.name}</option>+ ))}+ </select>+ </div>- {/* Team Members */}- <div className="p-3 rounded" style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>- <div className="text-xs font-medium mb-2" style={{ color: COLORS.GRAY }}>TEAM MEMBERS ({teamMembers.length})</div>- {teamMembers.length === 0 ? (- <p className="text-sm" style={{ color: COLORS.GRAY }}>Add agents from the AGENTS tab</p>- ) : (- <div className="space-y-2">- {teamMembers.map((agent, idx) => (- <div key={agent.id} className="flex items-center justify-between p-2 rounded" style={{ backgroundColor: COLORS.BORDER }}>- <div className="flex items-center gap-2">- <span className="text-xs px-2 py-0.5 rounded" style={{ backgroundColor: COLORS.ORANGE, color: COLORS.WHITE }}>- {idx + 1}+ {/* Query Input */}+ <div>+ <label style={{+ display: 'block',+ fontSize: '9px',+ fontWeight: 700,+ color: FINCEPT.GRAY,+ marginBottom: '6px',+ }}>+ QUERY+ </label>+ <textarea+ value={testQuery}+ onChange={e => setTestQuery(e.target.value)}+ placeholder="Enter your query..."+ rows={4}+ style={{+ width: '100%',+ padding: '10px',+ backgroundColor: FINCEPT.DARK_BG,+ color: FINCEPT.WHITE,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ fontSize: '11px',+ fontFamily: '"IBM Plex Mono", monospace',+ resize: 'none',+ }}+ />+ </div>++ {/* Run Button */}+ <button+ onClick={runAgent}+ disabled={loading}+ style={{+ width: '100%',+ padding: '10px',+ backgroundColor: FINCEPT.ORANGE,+ color: FINCEPT.DARK_BG,+ border: 'none',+ borderRadius: '2px',+ fontSize: '10px',+ fontWeight: 700,+ cursor: loading ? 'not-allowed' : 'pointer',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ gap: '6px',+ opacity: loading ? 0.7 : 1,+ }}+ >+ {loading ? <Loader2 size={12} className="animate-spin" /> : <Play size={12} />}+ {useAutoRouting ? 'RUN WITH AUTO-ROUTING' : 'RUN AGENT'}+ </button>+ </div>++ {/* Results Area */}+ <div style={{+ flex: 1,+ borderTop: `1px solid ${FINCEPT.BORDER}`,+ overflow: 'hidden',+ display: 'flex',+ flexDirection: 'column',+ }}>+ <div style={{+ padding: '12px',+ backgroundColor: FINCEPT.HEADER_BG,+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ }}>+ <span style={{+ fontSize: '9px',+ fontWeight: 700,+ color: FINCEPT.GRAY,+ letterSpacing: '0.5px',+ }}>+ RESULT+ </span>+ {testResult && (+ <span style={{+ padding: '2px 6px',+ backgroundColor: `${FINCEPT.GREEN}20`,+ color: FINCEPT.GREEN,+ fontSize: '8px',+ borderRadius: '2px',+ }}>+ SUCCESS+ </span>+ )}+ </div>+ <div style={{+ flex: 1,+ overflow: 'auto',+ padding: '12px',+ }}>+ {testResult ? (+ <pre style={{+ fontSize: '10px',+ color: FINCEPT.WHITE,+ whiteSpace: 'pre-wrap',+ wordBreak: 'break-word',+ margin: 0,+ fontFamily: '"IBM Plex Mono", monospace',+ }}>+ {typeof testResult === 'string' ? testResult : JSON.stringify(testResult, null, 2)}+ </pre>+ ) : (+ <div style={{+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ justifyContent: 'center',+ height: '100%',+ color: FINCEPT.MUTED,+ fontSize: '10px',+ textAlign: 'center',+ }}>+ <Target size={24} style={{ marginBottom: '8px', opacity: 0.5 }} />+ <span>Run a query to see results</span>+ </div>+ )}+ </div>+ </div>+ </div>+ </div>+ );++ // =============================================================================+ // Render: Teams View+ // =============================================================================++ const renderTeamsView = () => (+ <div style={{+ display: 'flex',+ height: '100%',+ overflow: 'hidden',+ }}>+ {/* Left - Team Members */}+ <div style={{+ width: '280px',+ minWidth: '280px',+ backgroundColor: FINCEPT.PANEL_BG,+ borderRight: `1px solid ${FINCEPT.BORDER}`,+ display: 'flex',+ flexDirection: 'column',+ flexShrink: 0,+ }}>+ {/* Header */}+ <div style={{+ padding: '12px',+ backgroundColor: FINCEPT.HEADER_BG,+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ }}>+ <span style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, letterSpacing: '0.5px' }}>+ TEAM ({teamMembers.length})+ </span>+ <select+ value={teamMode}+ onChange={e => setTeamMode(e.target.value as any)}+ style={{+ padding: '4px 8px',+ backgroundColor: FINCEPT.DARK_BG,+ color: FINCEPT.WHITE,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ fontSize: '9px',+ }}+ >+ <option value="coordinate">SEQUENTIAL</option>+ <option value="route">ROUTE</option>+ <option value="collaborate">PARALLEL</option>+ </select>+ </div>++ {/* Team Members List */}+ <div style={{ flex: 1, overflow: 'auto', padding: '8px' }}>+ {teamMembers.length === 0 ? (+ <div style={{+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ justifyContent: 'center',+ padding: '32px 16px',+ textAlign: 'center',+ }}>+ <Users size={32} style={{ color: FINCEPT.MUTED, marginBottom: '12px', opacity: 0.5 }} />+ <span style={{ fontSize: '10px', color: FINCEPT.GRAY }}>No agents in team</span>+ <span style={{ fontSize: '9px', color: FINCEPT.MUTED, marginTop: '4px' }}>Add from available list</span>+ </div>+ ) : (+ teamMembers.map((agent, idx) => (+ <div key={agent.id} style={{+ padding: '10px',+ marginBottom: '4px',+ backgroundColor: FINCEPT.DARK_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <span style={{+ width: '20px',+ height: '20px',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ backgroundColor: FINCEPT.ORANGE,+ color: FINCEPT.DARK_BG,+ fontSize: '10px',+ fontWeight: 700,+ borderRadius: '2px',+ }}>+ {idx + 1}</span><div>- <div className="text-sm font-medium" style={{ color: COLORS.WHITE }}>{agent.name}</div>- <div className="text-xs" style={{ color: COLORS.GRAY }}>{agent.category}</div>+ <div style={{ fontSize: '11px', fontWeight: 600, color: FINCEPT.WHITE }}>{agent.name}</div>+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY }}>{agent.category}</div></div></div>- <button onClick={() => removeFromTeam(agent.id)} style={{ color: COLORS.RED }}>- <Trash2 size={14} />+ <button+ onClick={() => removeFromTeam(agent.id)}+ style={{+ background: 'none',+ border: 'none',+ cursor: 'pointer',+ color: FINCEPT.RED,+ padding: '4px',+ }}+ >+ <Trash2 size={12} /></button></div>- ))}- </div>- )}+ ))+ )}+ </div></div>- {/* Available Agents to Add */}- <div className="p-3 rounded" style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>- <div className="text-xs font-medium mb-2" style={{ color: COLORS.GRAY }}>AVAILABLE AGENTS</div>- <div className="max-h-48 overflow-y-auto space-y-1">+ {/* Center - Available Agents */}+ <div style={{+ flex: 1,+ display: 'flex',+ flexDirection: 'column',+ overflow: 'hidden',+ minWidth: 0,+ }}>+ {/* Header */}+ <div style={{+ padding: '12px',+ backgroundColor: FINCEPT.HEADER_BG,+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ }}>+ <span style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, letterSpacing: '0.5px' }}>+ AVAILABLE AGENTS ({discoveredAgents.filter(a => !teamMembers.find(m => m.id === a.id)).length})+ </span>+ </div>++ {/* Agent Grid */}+ <div style={{+ flex: 1,+ overflow: 'auto',+ padding: '16px',+ display: 'grid',+ gridTemplateColumns: 'repeat(auto-fill, minmax(200px, 1fr))',+ gap: '8px',+ alignContent: 'start',+ }}>{discoveredAgents.filter(a => !teamMembers.find(m => m.id === a.id)).map(agent => (- <button+ <divkey={agent.id}onClick={() => addToTeam(agent)}- className="w-full flex items-center justify-between p-2 rounded text-sm hover:bg-[#1F1F1F]"+ style={{+ padding: '12px',+ backgroundColor: FINCEPT.PANEL_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ cursor: 'pointer',+ transition: 'all 0.2s',+ }}+ onMouseEnter={(e) => {+ e.currentTarget.style.borderColor = FINCEPT.ORANGE;+ e.currentTarget.style.backgroundColor = FINCEPT.HOVER;+ }}+ onMouseLeave={(e) => {+ e.currentTarget.style.borderColor = FINCEPT.BORDER;+ e.currentTarget.style.backgroundColor = FINCEPT.PANEL_BG;+ }}>- <span style={{ color: COLORS.WHITE }}>{agent.name}</span>- <Plus size={14} style={{ color: COLORS.ORANGE }} />- </button>+ <div style={{+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ marginBottom: '4px',+ }}>+ <span style={{ fontSize: '11px', fontWeight: 600, color: FINCEPT.WHITE }}>{agent.name}</span>+ <Plus size={12} style={{ color: FINCEPT.ORANGE }} />+ </div>+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY }}>{agent.category}</div>+ </div>))}</div></div>- {/* Query */}- <div>- <div className="text-xs font-medium mb-1" style={{ color: COLORS.GRAY }}>TEAM QUERY</div>- <textarea- value={testQuery}- onChange={e => setTestQuery(e.target.value)}- rows={3}- className="w-full px-3 py-2 rounded text-sm"- style={{ backgroundColor: COLORS.PANEL_BG, color: COLORS.WHITE, border: `1px solid ${COLORS.BORDER}` }}- />- </div>+ {/* Right - Query Panel */}+ <div style={{+ width: '300px',+ minWidth: '300px',+ backgroundColor: FINCEPT.PANEL_BG,+ borderLeft: `1px solid ${FINCEPT.BORDER}`,+ display: 'flex',+ flexDirection: 'column',+ flexShrink: 0,+ }}>+ {/* Header */}+ <div style={{+ padding: '12px',+ backgroundColor: FINCEPT.HEADER_BG,+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ }}>+ <span style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, letterSpacing: '0.5px' }}>+ TEAM QUERY+ </span>+ </div>- <button- onClick={runTeam}- disabled={loading || teamMembers.length === 0}- className="w-full py-2 rounded font-medium flex items-center justify-center gap-2"- style={{ backgroundColor: COLORS.ORANGE, color: COLORS.WHITE, opacity: (loading || teamMembers.length === 0) ? 0.5 : 1 }}- >- {loading ? <Loader2 size={16} className="animate-spin" /> : <Play size={16} />}- Run Team- </button>-- {testResult && (- <div className="p-3 rounded" style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>- <pre className="text-sm whitespace-pre-wrap" style={{ color: COLORS.WHITE }}>- {JSON.stringify(testResult, null, 2)}- </pre>+ {/* Query Form */}+ <div style={{ padding: '12px', display: 'flex', flexDirection: 'column', gap: '12px' }}>+ <textarea+ value={testQuery}+ onChange={e => setTestQuery(e.target.value)}+ rows={6}+ placeholder="Enter your query for the team..."+ style={{+ width: '100%',+ padding: '10px',+ backgroundColor: FINCEPT.DARK_BG,+ color: FINCEPT.WHITE,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ fontSize: '11px',+ fontFamily: '"IBM Plex Mono", monospace',+ resize: 'none',+ }}+ />++ <button+ onClick={runTeam}+ disabled={loading || teamMembers.length === 0}+ style={{+ width: '100%',+ padding: '10px',+ backgroundColor: FINCEPT.ORANGE,+ color: FINCEPT.DARK_BG,+ border: 'none',+ borderRadius: '2px',+ fontSize: '10px',+ fontWeight: 700,+ cursor: (loading || teamMembers.length === 0) ? 'not-allowed' : 'pointer',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ gap: '6px',+ opacity: (loading || teamMembers.length === 0) ? 0.7 : 1,+ }}+ >+ {loading ? <Loader2 size={12} className="animate-spin" /> : <Play size={12} />}+ RUN TEAM+ </button></div>- )}++ {/* Results */}+ <div style={{ flex: 1, borderTop: `1px solid ${FINCEPT.BORDER}`, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>+ <div style={{+ padding: '12px',+ backgroundColor: FINCEPT.HEADER_BG,+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ }}>+ <span style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, letterSpacing: '0.5px' }}>+ RESULT+ </span>+ </div>+ <div style={{ flex: 1, overflow: 'auto', padding: '12px' }}>+ {testResult ? (+ <pre style={{+ fontSize: '10px',+ color: FINCEPT.WHITE,+ whiteSpace: 'pre-wrap',+ wordBreak: 'break-word',+ margin: 0,+ fontFamily: '"IBM Plex Mono", monospace',+ }}>+ {JSON.stringify(testResult, null, 2)}+ </pre>+ ) : (+ <div style={{+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ justifyContent: 'center',+ height: '100%',+ color: FINCEPT.MUTED,+ fontSize: '10px',+ textAlign: 'center',+ }}>+ <Users size={24} style={{ marginBottom: '8px', opacity: 0.5 }} />+ <span>Run team query to see results</span>+ </div>+ )}+ </div>+ </div>+ </div></div>);// =============================================================================- // Render: Workflows View+ // Render: Workflows View - Terminal Style// =============================================================================const renderWorkflowsView = () => (- <div className="p-4 space-y-4">- <h2 className="text-lg font-semibold" style={{ color: COLORS.WHITE }}>Financial Workflows</h2>-- <div className="grid grid-cols-1 md:grid-cols-3 gap-4">- {/* Stock Analysis */}- <div className="p-4 rounded" style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>- <div className="flex items-center gap-2 mb-3">- <TrendingUp size={20} style={{ color: COLORS.ORANGE }} />- <h3 className="font-medium" style={{ color: COLORS.WHITE }}>Stock Analysis</h3>- </div>- <input- type="text"- value={workflowSymbol}- onChange={e => setWorkflowSymbol(e.target.value.toUpperCase())}- placeholder="Symbol (e.g., AAPL)"- className="w-full px-3 py-2 rounded text-sm mb-3"- style={{ backgroundColor: COLORS.DARK_BG, color: COLORS.WHITE, border: `1px solid ${COLORS.BORDER}` }}- />- <button- onClick={() => runWorkflow('stock_analysis')}- disabled={loading}- className="w-full py-2 rounded text-sm font-medium"- style={{ backgroundColor: COLORS.ORANGE, color: COLORS.WHITE }}- >- Analyze- </button>+ <div style={{+ display: 'flex',+ height: '100%',+ overflow: 'hidden',+ }}>+ {/* Left - Workflow Cards */}+ <div style={{+ flex: 1,+ overflow: 'auto',+ padding: '16px',+ }}>+ {/* Header */}+ <div style={{+ marginBottom: '16px',+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ }}>+ <Workflow size={16} style={{ color: FINCEPT.ORANGE }} />+ <span style={{ fontSize: '12px', fontWeight: 700, color: FINCEPT.WHITE }}>+ FINANCIAL WORKFLOWS+ </span></div>- {/* Portfolio Rebalancing */}- <div className="p-4 rounded" style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>- <div className="flex items-center gap-2 mb-3">- <Brain size={20} style={{ color: COLORS.ORANGE }} />- <h3 className="font-medium" style={{ color: COLORS.WHITE }}>Portfolio Rebalancing</h3>+ {/* Workflow Grid */}+ <div style={{+ display: 'grid',+ gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))',+ gap: '12px',+ }}>+ {/* Stock Analysis */}+ <div style={{+ padding: '16px',+ backgroundColor: FINCEPT.PANEL_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ }}>+ <div style={{+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ marginBottom: '12px',+ }}>+ <TrendingUp size={16} style={{ color: FINCEPT.ORANGE }} />+ <span style={{ fontSize: '11px', fontWeight: 700, color: FINCEPT.WHITE }}>+ STOCK ANALYSIS+ </span>+ </div>+ <input+ type="text"+ value={workflowSymbol}+ onChange={e => setWorkflowSymbol(e.target.value.toUpperCase())}+ placeholder="Symbol (e.g., AAPL)"+ style={{+ width: '100%',+ padding: '8px 10px',+ backgroundColor: FINCEPT.DARK_BG,+ color: FINCEPT.WHITE,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ fontSize: '10px',+ marginBottom: '12px',+ fontFamily: '"IBM Plex Mono", monospace',+ }}+ />+ <button+ onClick={() => runWorkflow('stock_analysis')}+ disabled={loading}+ style={{+ width: '100%',+ padding: '8px',+ backgroundColor: FINCEPT.ORANGE,+ color: FINCEPT.DARK_BG,+ border: 'none',+ borderRadius: '2px',+ fontSize: '9px',+ fontWeight: 700,+ cursor: loading ? 'not-allowed' : 'pointer',+ opacity: loading ? 0.7 : 1,+ }}+ >+ ANALYZE+ </button></div>- <p className="text-xs mb-3" style={{ color: COLORS.GRAY }}>- Optimize your portfolio allocation based on risk/return targets.- </p>- <button- onClick={() => runWorkflow('portfolio_rebal')}- disabled={loading}- className="w-full py-2 rounded text-sm font-medium"- style={{ backgroundColor: COLORS.ORANGE, color: COLORS.WHITE }}- >- Rebalance- </button>- </div>- {/* Risk Assessment */}- <div className="p-4 rounded" style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>- <div className="flex items-center gap-2 mb-3">- <AlertCircle size={20} style={{ color: COLORS.ORANGE }} />- <h3 className="font-medium" style={{ color: COLORS.WHITE }}>Risk Assessment</h3>+ {/* Portfolio Rebalancing */}+ <div style={{+ padding: '16px',+ backgroundColor: FINCEPT.PANEL_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ }}>+ <div style={{+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ marginBottom: '12px',+ }}>+ <Brain size={16} style={{ color: FINCEPT.PURPLE }} />+ <span style={{ fontSize: '11px', fontWeight: 700, color: FINCEPT.WHITE }}>+ PORTFOLIO REBALANCING+ </span>+ </div>+ <p style={{ fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '12px', lineHeight: 1.4 }}>+ Optimize your portfolio allocation based on risk/return targets.+ </p>+ <button+ onClick={() => runWorkflow('portfolio_rebal')}+ disabled={loading}+ style={{+ width: '100%',+ padding: '8px',+ backgroundColor: FINCEPT.PURPLE,+ color: FINCEPT.WHITE,+ border: 'none',+ borderRadius: '2px',+ fontSize: '9px',+ fontWeight: 700,+ cursor: loading ? 'not-allowed' : 'pointer',+ opacity: loading ? 0.7 : 1,+ }}+ >+ REBALANCE+ </button>+ </div>++ {/* Risk Assessment */}+ <div style={{+ padding: '16px',+ backgroundColor: FINCEPT.PANEL_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ }}>+ <div style={{+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ marginBottom: '12px',+ }}>+ <AlertCircle size={16} style={{ color: FINCEPT.RED }} />+ <span style={{ fontSize: '11px', fontWeight: 700, color: FINCEPT.WHITE }}>+ RISK ASSESSMENT+ </span>+ </div>+ <p style={{ fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '12px', lineHeight: 1.4 }}>+ Analyze portfolio risk metrics and potential vulnerabilities.+ </p>+ <button+ onClick={() => runWorkflow('risk_assessment')}+ disabled={loading}+ style={{+ width: '100%',+ padding: '8px',+ backgroundColor: FINCEPT.RED,+ color: FINCEPT.WHITE,+ border: 'none',+ borderRadius: '2px',+ fontSize: '9px',+ fontWeight: 700,+ cursor: loading ? 'not-allowed' : 'pointer',+ opacity: loading ? 0.7 : 1,+ }}+ >+ ASSESS RISK+ </button></div>- <p className="text-xs mb-3" style={{ color: COLORS.GRAY }}>- Analyze portfolio risk metrics and potential vulnerabilities.- </p>- <button- onClick={() => runWorkflow('risk_assessment')}- disabled={loading}- className="w-full py-2 rounded text-sm font-medium"- style={{ backgroundColor: COLORS.ORANGE, color: COLORS.WHITE }}- >- Assess Risk- </button></div></div>- {testResult && (- <div className="p-3 rounded" style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>- <div className="text-xs font-medium mb-2" style={{ color: COLORS.GRAY }}>WORKFLOW RESULT</div>- <pre className="text-sm whitespace-pre-wrap" style={{ color: COLORS.WHITE }}>- {JSON.stringify(testResult, null, 2)}- </pre>+ {/* Right - Results Panel */}+ <div style={{+ width: '350px',+ minWidth: '350px',+ backgroundColor: FINCEPT.PANEL_BG,+ borderLeft: `1px solid ${FINCEPT.BORDER}`,+ display: 'flex',+ flexDirection: 'column',+ flexShrink: 0,+ }}>+ <div style={{+ padding: '12px',+ backgroundColor: FINCEPT.HEADER_BG,+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ }}>+ <span style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, letterSpacing: '0.5px' }}>+ WORKFLOW RESULT+ </span></div>- )}+ <div style={{ flex: 1, overflow: 'auto', padding: '12px' }}>+ {testResult ? (+ <pre style={{+ fontSize: '10px',+ color: FINCEPT.WHITE,+ whiteSpace: 'pre-wrap',+ wordBreak: 'break-word',+ margin: 0,+ fontFamily: '"IBM Plex Mono", monospace',+ }}>+ {JSON.stringify(testResult, null, 2)}+ </pre>+ ) : (+ <div style={{+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ justifyContent: 'center',+ height: '100%',+ color: FINCEPT.MUTED,+ fontSize: '10px',+ textAlign: 'center',+ }}>+ <Workflow size={24} style={{ marginBottom: '8px', opacity: 0.5 }} />+ <span>Run a workflow to see results</span>+ </div>+ )}+ </div>+ </div></div>);// =============================================================================- // Render: Planner View (NEW)+ // Render: Planner View - Terminal Style// =============================================================================const renderPlannerView = () => (- <div className="p-4 space-y-4">- <div className="flex items-center justify-between">- <h2 className="text-lg font-semibold flex items-center gap-2" style={{ color: COLORS.WHITE }}>- <ListTree size={20} style={{ color: COLORS.ORANGE }} />- Execution Planner- </h2>- {currentPlan && (- <span- className="px-2 py-1 rounded text-xs"- style={{- backgroundColor: currentPlan.is_complete ? COLORS.GREEN + '20' : currentPlan.has_failed ? COLORS.RED + '20' : COLORS.ORANGE + '20',- color: currentPlan.is_complete ? COLORS.GREEN : currentPlan.has_failed ? COLORS.RED : COLORS.ORANGE,- }}- >- {currentPlan.status}+ <div style={{+ display: 'flex',+ height: '100%',+ overflow: 'hidden',+ }}>+ {/* Left - Plan Creation & Templates */}+ <div style={{+ width: '320px',+ minWidth: '320px',+ backgroundColor: FINCEPT.PANEL_BG,+ borderRight: `1px solid ${FINCEPT.BORDER}`,+ display: 'flex',+ flexDirection: 'column',+ flexShrink: 0,+ }}>+ {/* Header */}+ <div style={{+ padding: '12px',+ backgroundColor: FINCEPT.HEADER_BG,+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ }}>+ <ListTree size={14} style={{ color: FINCEPT.ORANGE }} />+ <span style={{ fontSize: '11px', fontWeight: 700, color: FINCEPT.WHITE }}>+ EXECUTION PLANNER</span>- )}- </div>+ </div>- {/* Create Plan */}- <div className="p-4 rounded" style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>- <div className="text-xs font-medium mb-2" style={{ color: COLORS.GRAY }}>CREATE EXECUTION PLAN</div>- <div className="flex gap-2">+ {/* Create Plan Form */}+ <div style={{ padding: '12px', borderBottom: `1px solid ${FINCEPT.BORDER}` }}>+ <label style={{ display: 'block', fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, marginBottom: '8px' }}>+ CREATE PLAN+ </label><inputtype="text"value={workflowSymbol}onChange={e => setWorkflowSymbol(e.target.value.toUpperCase())}placeholder="Symbol (e.g., AAPL)"- className="flex-1 px-3 py-2 rounded text-sm"- style={{ backgroundColor: COLORS.DARK_BG, color: COLORS.WHITE, border: `1px solid ${COLORS.BORDER}` }}+ style={{+ width: '100%',+ padding: '8px 10px',+ backgroundColor: FINCEPT.DARK_BG,+ color: FINCEPT.WHITE,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ fontSize: '10px',+ marginBottom: '8px',+ fontFamily: '"IBM Plex Mono", monospace',+ }}/><buttononClick={createPlan}disabled={loading}- className="px-4 py-2 rounded text-sm font-medium flex items-center gap-2"- style={{ backgroundColor: COLORS.ORANGE, color: COLORS.WHITE }}+ style={{+ width: '100%',+ padding: '8px',+ backgroundColor: FINCEPT.ORANGE,+ color: FINCEPT.DARK_BG,+ border: 'none',+ borderRadius: '2px',+ fontSize: '9px',+ fontWeight: 700,+ cursor: loading ? 'not-allowed' : 'pointer',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ gap: '6px',+ opacity: loading ? 0.7 : 1,+ }}>- {loading ? <Loader2 size={14} className="animate-spin" /> : <Target size={14} />}- Create Plan+ {loading ? <Loader2 size={10} className="animate-spin" /> : <Target size={10} />}+ CREATE PLAN</button></div>- </div>- {/* Plan Visualization */}- {currentPlan && (- <div className="p-4 rounded" style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>- <div className="flex items-center justify-between mb-4">- <div>- <div className="text-sm font-medium" style={{ color: COLORS.WHITE }}>{currentPlan.name}</div>- <div className="text-xs" style={{ color: COLORS.GRAY }}>{currentPlan.description}</div>- </div>- <button- onClick={executePlan}- disabled={planExecuting || currentPlan.is_complete}- className="px-4 py-2 rounded text-sm font-medium flex items-center gap-2"- style={{- backgroundColor: currentPlan.is_complete ? COLORS.GREEN : COLORS.ORANGE,- color: COLORS.WHITE,- opacity: planExecuting ? 0.5 : 1,- }}- >- {planExecuting ? <Loader2 size={14} className="animate-spin" /> : <Play size={14} />}- {currentPlan.is_complete ? 'Completed' : 'Execute Plan'}- </button>- </div>-- {/* Steps */}- <div className="space-y-2">- {currentPlan.steps.map((step, idx) => (- <div- key={step.id}- className="flex items-center gap-3 p-3 rounded"+ {/* Plan Templates */}+ <div style={{ flex: 1, overflow: 'auto', padding: '12px' }}>+ <label style={{ display: 'block', fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, marginBottom: '8px' }}>+ TEMPLATES+ </label>+ <div style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}>+ {[+ { id: 'stock_analysis', name: 'Stock Analysis', desc: 'Fundamental + technical' },+ { id: 'portfolio_rebalance', name: 'Portfolio Rebalance', desc: 'Optimize allocation' },+ { id: 'sector_rotation', name: 'Sector Rotation', desc: 'Identify opportunities' },+ { id: 'risk_audit', name: 'Risk Audit', desc: 'Risk assessment' },+ ].map(template => (+ <button+ key={template.id}+ onClick={() => { setWorkflowSymbol('AAPL'); createPlan(); }}style={{- backgroundColor: COLORS.BORDER,- borderLeft: `3px solid ${- step.status === 'completed' ? COLORS.GREEN :- step.status === 'failed' ? COLORS.RED :- step.status === 'running' ? COLORS.ORANGE :- COLORS.GRAY- }`,+ padding: '10px',+ backgroundColor: FINCEPT.DARK_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ cursor: 'pointer',+ textAlign: 'left',+ transition: 'all 0.2s',}}+ onMouseEnter={(e) => { e.currentTarget.style.borderColor = FINCEPT.ORANGE; }}+ onMouseLeave={(e) => { e.currentTarget.style.borderColor = FINCEPT.BORDER; }}>- <span className="text-xs px-2 py-0.5 rounded" style={{ backgroundColor: COLORS.DARK_BG, color: COLORS.GRAY }}>- {idx + 1}- </span>- <div className="flex-1">- <div className="text-sm font-medium" style={{ color: COLORS.WHITE }}>{step.name}</div>- <div className="text-xs" style={{ color: COLORS.GRAY }}>- Type: {step.step_type}- {step.dependencies.length > 0 && ` • Depends on: ${step.dependencies.join(', ')}`}- </div>+ <div style={{ fontSize: '10px', fontWeight: 600, color: FINCEPT.WHITE, marginBottom: '2px' }}>+ {template.name}</div>- <span- className="text-xs px-2 py-0.5 rounded"+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY }}>{template.desc}</div>+ </button>+ ))}+ </div>+ </div>+ </div>++ {/* Center - Plan Visualization */}+ <div style={{+ flex: 1,+ display: 'flex',+ flexDirection: 'column',+ overflow: 'hidden',+ minWidth: 0,+ }}>+ {currentPlan ? (+ <>+ {/* Plan Header */}+ <div style={{+ padding: '12px 16px',+ backgroundColor: FINCEPT.HEADER_BG,+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ }}>+ <div>+ <div style={{ fontSize: '12px', fontWeight: 700, color: FINCEPT.WHITE }}>{currentPlan.name}</div>+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY }}>{currentPlan.description}</div>+ </div>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <span style={{+ padding: '4px 8px',+ backgroundColor: currentPlan.is_complete ? `${FINCEPT.GREEN}20` : currentPlan.has_failed ? `${FINCEPT.RED}20` : `${FINCEPT.ORANGE}20`,+ color: currentPlan.is_complete ? FINCEPT.GREEN : currentPlan.has_failed ? FINCEPT.RED : FINCEPT.ORANGE,+ fontSize: '8px',+ fontWeight: 700,+ borderRadius: '2px',+ }}>+ {currentPlan.status}+ </span>+ <button+ onClick={executePlan}+ disabled={planExecuting || currentPlan.is_complete}style={{- backgroundColor: step.status === 'completed' ? COLORS.GREEN + '20' :- step.status === 'failed' ? COLORS.RED + '20' :- step.status === 'running' ? COLORS.ORANGE + '20' :- COLORS.BORDER,- color: step.status === 'completed' ? COLORS.GREEN :- step.status === 'failed' ? COLORS.RED :- step.status === 'running' ? COLORS.ORANGE :- COLORS.GRAY,+ padding: '6px 12px',+ backgroundColor: currentPlan.is_complete ? FINCEPT.GREEN : FINCEPT.ORANGE,+ color: FINCEPT.DARK_BG,+ border: 'none',+ borderRadius: '2px',+ fontSize: '9px',+ fontWeight: 700,+ cursor: (planExecuting || currentPlan.is_complete) ? 'not-allowed' : 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ opacity: planExecuting ? 0.7 : 1,}}>- {step.status}- </span>+ {planExecuting ? <Loader2 size={10} className="animate-spin" /> : <Play size={10} />}+ {currentPlan.is_complete ? 'DONE' : 'EXECUTE'}+ </button></div>- ))}- </div>+ </div>- {/* Results */}- {currentPlan.is_complete && currentPlan.context && (- <div className="mt-4 p-3 rounded" style={{ backgroundColor: COLORS.DARK_BG }}>- <div className="text-xs font-medium mb-2" style={{ color: COLORS.GRAY }}>PLAN RESULTS</div>- <pre className="text-xs whitespace-pre-wrap" style={{ color: COLORS.WHITE }}>- {JSON.stringify(currentPlan.context, null, 2)}- </pre>+ {/* Steps */}+ <div style={{ flex: 1, overflow: 'auto', padding: '16px' }}>+ <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>+ {currentPlan.steps.map((step, idx) => (+ <div+ key={step.id}+ style={{+ padding: '12px',+ backgroundColor: FINCEPT.PANEL_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderLeft: `3px solid ${+ step.status === 'completed' ? FINCEPT.GREEN :+ step.status === 'failed' ? FINCEPT.RED :+ step.status === 'running' ? FINCEPT.ORANGE : FINCEPT.GRAY+ }`,+ borderRadius: '2px',+ display: 'flex',+ alignItems: 'center',+ gap: '12px',+ }}+ >+ <span style={{+ width: '24px',+ height: '24px',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ backgroundColor: FINCEPT.DARK_BG,+ color: FINCEPT.GRAY,+ fontSize: '10px',+ fontWeight: 700,+ borderRadius: '2px',+ }}>+ {idx + 1}+ </span>+ <div style={{ flex: 1 }}>+ <div style={{ fontSize: '11px', fontWeight: 600, color: FINCEPT.WHITE }}>{step.name}</div>+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY }}>+ {step.step_type}{step.dependencies.length > 0 && ` • Deps: ${step.dependencies.join(', ')}`}+ </div>+ </div>+ <span style={{+ padding: '4px 8px',+ backgroundColor: step.status === 'completed' ? `${FINCEPT.GREEN}20` :+ step.status === 'failed' ? `${FINCEPT.RED}20` :+ step.status === 'running' ? `${FINCEPT.ORANGE}20` : FINCEPT.BORDER,+ color: step.status === 'completed' ? FINCEPT.GREEN :+ step.status === 'failed' ? FINCEPT.RED :+ step.status === 'running' ? FINCEPT.ORANGE : FINCEPT.GRAY,+ fontSize: '8px',+ fontWeight: 700,+ borderRadius: '2px',+ textTransform: 'uppercase',+ }}>+ {step.status}+ </span>+ </div>+ ))}+ </div></div>- )}- </div>- )}+ </>+ ) : (+ <div style={{+ flex: 1,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ backgroundColor: FINCEPT.PANEL_BG,+ }}>+ <div style={{ textAlign: 'center', color: FINCEPT.MUTED }}>+ <ListTree size={40} style={{ marginBottom: '12px', opacity: 0.5 }} />+ <div style={{ fontSize: '11px' }}>Create a plan to visualize steps</div>+ </div>+ </div>+ )}+ </div>- {/* Plan Templates */}- <div className="p-4 rounded" style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>- <div className="text-xs font-medium mb-3" style={{ color: COLORS.GRAY }}>PLAN TEMPLATES</div>- <div className="grid grid-cols-2 gap-2">- {[- { id: 'stock_analysis', name: 'Stock Analysis', desc: 'Full fundamental + technical analysis' },- { id: 'portfolio_rebalance', name: 'Portfolio Rebalance', desc: 'Analyze and rebalance portfolio' },- { id: 'sector_rotation', name: 'Sector Rotation', desc: 'Identify sector opportunities' },- { id: 'risk_audit', name: 'Risk Audit', desc: 'Comprehensive risk assessment' },- ].map(template => (- <button- key={template.id}- onClick={() => {- setWorkflowSymbol('AAPL');- createPlan();- }}- className="p-3 rounded text-left hover:bg-[#1F1F1F] transition-colors"- style={{ backgroundColor: COLORS.BORDER }}- >- <div className="text-sm font-medium" style={{ color: COLORS.WHITE }}>{template.name}</div>- <div className="text-xs" style={{ color: COLORS.GRAY }}>{template.desc}</div>- </button>- ))}+ {/* Right - Results Panel */}+ {currentPlan?.is_complete && currentPlan.context && (+ <div style={{+ width: '300px',+ minWidth: '300px',+ backgroundColor: FINCEPT.PANEL_BG,+ borderLeft: `1px solid ${FINCEPT.BORDER}`,+ display: 'flex',+ flexDirection: 'column',+ flexShrink: 0,+ }}>+ <div style={{+ padding: '12px',+ backgroundColor: FINCEPT.HEADER_BG,+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ }}>+ <span style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, letterSpacing: '0.5px' }}>+ PLAN RESULTS+ </span>+ </div>+ <div style={{ flex: 1, overflow: 'auto', padding: '12px' }}>+ <pre style={{+ fontSize: '9px',+ color: FINCEPT.WHITE,+ whiteSpace: 'pre-wrap',+ wordBreak: 'break-word',+ margin: 0,+ fontFamily: '"IBM Plex Mono", monospace',+ }}>+ {JSON.stringify(currentPlan.context, null, 2)}+ </pre>+ </div></div>- </div>+ )}</div>);// =============================================================================- // Render: Tools View+ // Render: Tools View - Terminal Style// =============================================================================const renderToolsView = () => (- <div className="p-4 space-y-4">- <div className="flex items-center gap-3">- <h2 className="text-lg font-semibold" style={{ color: COLORS.WHITE }}>Available Tools</h2>- {toolsInfo && (- <span className="px-2 py-0.5 rounded text-xs" style={{ backgroundColor: COLORS.ORANGE + '20', color: COLORS.ORANGE }}>- {toolsInfo.total_count} tools+ <div style={{+ display: 'flex',+ height: '100%',+ overflow: 'hidden',+ }}>+ {/* Left - Selected Tools */}+ <div style={{+ width: '280px',+ minWidth: '280px',+ backgroundColor: FINCEPT.PANEL_BG,+ borderRight: `1px solid ${FINCEPT.BORDER}`,+ display: 'flex',+ flexDirection: 'column',+ flexShrink: 0,+ }}>+ <div style={{+ padding: '12px',+ backgroundColor: FINCEPT.HEADER_BG,+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ }}>+ <span style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, letterSpacing: '0.5px' }}>+ SELECTED ({selectedTools.length})</span>- )}- </div>-- {/* Search */}- <div className="relative">- <Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2" style={{ color: COLORS.GRAY }} />- <input- type="text"- value={toolSearch}- onChange={e => setToolSearch(e.target.value)}- placeholder="Search tools..."- className="w-full pl-10 pr-3 py-2 rounded text-sm"- style={{ backgroundColor: COLORS.PANEL_BG, color: COLORS.WHITE, border: `1px solid ${COLORS.BORDER}` }}- />- </div>-- {/* Selected Tools */}- {selectedTools.length > 0 && (- <div className="p-3 rounded" style={{ backgroundColor: COLORS.ORANGE + '10', border: `1px solid ${COLORS.ORANGE}40` }}>- <div className="text-xs font-medium mb-2" style={{ color: COLORS.ORANGE }}>SELECTED ({selectedTools.length})</div>- <div className="flex flex-wrap gap-1">- {selectedTools.map(tool => (- <span+ {selectedTools.length > 0 && (+ <button+ onClick={() => setSelectedTools([])}+ style={{+ padding: '2px 6px',+ backgroundColor: 'transparent',+ border: `1px solid ${FINCEPT.RED}`,+ color: FINCEPT.RED,+ fontSize: '8px',+ cursor: 'pointer',+ borderRadius: '2px',+ }}+ >+ CLEAR+ </button>+ )}+ </div>+ <div style={{ flex: 1, overflow: 'auto', padding: '8px' }}>+ {selectedTools.length === 0 ? (+ <div style={{+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ justifyContent: 'center',+ height: '100%',+ color: FINCEPT.MUTED,+ fontSize: '10px',+ textAlign: 'center',+ }}>+ <Wrench size={24} style={{ marginBottom: '8px', opacity: 0.5 }} />+ <span>No tools selected</span>+ </div>+ ) : (+ selectedTools.map(tool => (+ <divkey={tool}- onClick={() => toggleToolSelection(tool)}- className="px-2 py-0.5 rounded text-xs cursor-pointer"- style={{ backgroundColor: COLORS.ORANGE, color: COLORS.WHITE }}+ style={{+ padding: '8px 10px',+ marginBottom: '4px',+ backgroundColor: `${FINCEPT.ORANGE}15`,+ border: `1px solid ${FINCEPT.ORANGE}40`,+ borderRadius: '2px',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ }}>- {tool} ×+ <span style={{ fontSize: '10px', color: FINCEPT.ORANGE }}>{tool}</span>+ <button+ onClick={() => toggleToolSelection(tool)}+ style={{+ background: 'none',+ border: 'none',+ color: FINCEPT.RED,+ cursor: 'pointer',+ fontSize: '12px',+ }}+ >+ ×+ </button>+ </div>+ ))+ )}+ </div>+ </div>++ {/* Center - Tool Browser */}+ <div style={{+ flex: 1,+ display: 'flex',+ flexDirection: 'column',+ overflow: 'hidden',+ minWidth: 0,+ }}>+ {/* Header with Search */}+ <div style={{+ padding: '12px 16px',+ backgroundColor: FINCEPT.HEADER_BG,+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ display: 'flex',+ alignItems: 'center',+ gap: '12px',+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <Wrench size={14} style={{ color: FINCEPT.ORANGE }} />+ <span style={{ fontSize: '11px', fontWeight: 700, color: FINCEPT.WHITE }}>+ AVAILABLE TOOLS+ </span>+ {toolsInfo && (+ <span style={{+ padding: '2px 6px',+ backgroundColor: `${FINCEPT.CYAN}20`,+ color: FINCEPT.CYAN,+ fontSize: '8px',+ borderRadius: '2px',+ }}>+ {toolsInfo.total_count}</span>- ))}+ )}+ </div>+ <div style={{ flex: 1, position: 'relative' }}>+ <Search size={12} style={{+ position: 'absolute',+ left: '10px',+ top: '50%',+ transform: 'translateY(-50%)',+ color: FINCEPT.GRAY,+ }} />+ <input+ type="text"+ value={toolSearch}+ onChange={e => setToolSearch(e.target.value)}+ placeholder="Search tools..."+ style={{+ width: '100%',+ padding: '6px 10px 6px 30px',+ backgroundColor: FINCEPT.DARK_BG,+ color: FINCEPT.WHITE,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ fontSize: '10px',+ }}+ /></div></div>- )}-- {/* Tool Categories */}- <div className="space-y-2">- {toolsInfo?.categories?.map(category => {- const tools = toolsInfo.tools[category] || [];- const filteredTools = toolSearch- ? tools.filter(t => t.toLowerCase().includes(toolSearch.toLowerCase()))- : tools;- if (filteredTools.length === 0) return null;-- return (- <div key={category} className="rounded" style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>- <button- onClick={() => toggleToolCategory(category)}- className="w-full flex items-center justify-between p-3"- >- <span className="font-medium text-sm" style={{ color: COLORS.WHITE }}>{category}</span>- <div className="flex items-center gap-2">- <span className="text-xs" style={{ color: COLORS.GRAY }}>{filteredTools.length}</span>- {expandedCategories.has(category) ? <ChevronDown size={14} /> : <ChevronRight size={14} />}- </div>- </button>- {expandedCategories.has(category) && (- <div className="px-3 pb-3 flex flex-wrap gap-1">- {filteredTools.map(tool => (- <span- key={tool}- onClick={() => toggleToolSelection(tool)}- className="px-2 py-1 rounded text-xs cursor-pointer flex items-center gap-1"- style={{- backgroundColor: selectedTools.includes(tool) ? COLORS.ORANGE : COLORS.BORDER,- color: COLORS.WHITE,- }}- >- {tool}- <button onClick={e => { e.stopPropagation(); copyTool(tool); }}>- {copiedTool === tool ? <Check size={10} /> : <Copy size={10} />}- </button>- </span>- ))}- </div>- )}- </div>- );- })}+ {/* Categories */}+ <div style={{ flex: 1, overflow: 'auto', padding: '12px' }}>+ {toolsInfo?.categories?.map(category => {+ const tools = toolsInfo.tools[category] || [];+ const filteredTools = toolSearch+ ? tools.filter(t => t.toLowerCase().includes(toolSearch.toLowerCase()))+ : tools;++ if (filteredTools.length === 0) return null;++ return (+ <div key={category} style={{+ marginBottom: '8px',+ backgroundColor: FINCEPT.PANEL_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ }}>+ <button+ onClick={() => toggleToolCategory(category)}+ style={{+ width: '100%',+ padding: '10px 12px',+ backgroundColor: 'transparent',+ border: 'none',+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ }}+ >+ <span style={{ fontSize: '10px', fontWeight: 600, color: FINCEPT.WHITE }}>{category}</span>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <span style={{ fontSize: '9px', color: FINCEPT.GRAY }}>{filteredTools.length}</span>+ {expandedCategories.has(category) ? <ChevronDown size={12} color={FINCEPT.GRAY} /> : <ChevronRight size={12} color={FINCEPT.GRAY} />}+ </div>+ </button>+ {expandedCategories.has(category) && (+ <div style={{+ padding: '8px 12px 12px',+ borderTop: `1px solid ${FINCEPT.BORDER}`,+ display: 'flex',+ flexWrap: 'wrap',+ gap: '6px',+ }}>+ {filteredTools.map(tool => (+ <span+ key={tool}+ onClick={() => toggleToolSelection(tool)}+ style={{+ padding: '4px 8px',+ backgroundColor: selectedTools.includes(tool) ? FINCEPT.ORANGE : FINCEPT.DARK_BG,+ color: selectedTools.includes(tool) ? FINCEPT.DARK_BG : FINCEPT.WHITE,+ border: `1px solid ${selectedTools.includes(tool) ? FINCEPT.ORANGE : FINCEPT.BORDER}`,+ borderRadius: '2px',+ fontSize: '9px',+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ }}+ >+ {tool}+ <button+ onClick={e => { e.stopPropagation(); copyTool(tool); }}+ style={{+ background: 'none',+ border: 'none',+ cursor: 'pointer',+ color: selectedTools.includes(tool) ? FINCEPT.DARK_BG : FINCEPT.GRAY,+ padding: 0,+ }}+ >+ {copiedTool === tool ? <Check size={10} /> : <Copy size={10} />}+ </button>+ </span>+ ))}+ </div>+ )}+ </div>+ );+ })}+ </div></div></div>);@@ -1541,54 +2739,124 @@ const AgentConfigTab: React.FC = () => {};const renderChatView = () => (- <div className="flex flex-col h-full">+ <div style={{+ display: 'flex',+ flexDirection: 'column',+ height: '100%',+ backgroundColor: FINCEPT.PANEL_BG,+ }}>{/* Chat Header */}- <div className="p-3 border-b flex items-center justify-between" style={{ borderColor: COLORS.BORDER }}>- <div className="flex items-center gap-2">- <MessageSquare size={16} style={{ color: COLORS.ORANGE }} />- <span className="text-sm font-medium" style={{ color: COLORS.WHITE }}>Agent Chat</span>+ <div style={{+ padding: '12px 16px',+ backgroundColor: FINCEPT.HEADER_BG,+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <MessageSquare size={14} style={{ color: FINCEPT.ORANGE }} />+ <span style={{ fontSize: '11px', fontWeight: 700, color: FINCEPT.WHITE }}>+ AGENT CHAT+ </span>+ {selectedAgent && (+ <span style={{+ padding: '2px 6px',+ backgroundColor: `${FINCEPT.CYAN}20`,+ color: FINCEPT.CYAN,+ fontSize: '8px',+ borderRadius: '2px',+ }}>+ {selectedAgent.name}+ </span>+ )}</div>- <div className="flex items-center gap-2">- <span className="text-xs" style={{ color: COLORS.GRAY }}>Auto-Route</span>- <button- onClick={() => setUseAutoRouting(!useAutoRouting)}- style={{ color: useAutoRouting ? COLORS.GREEN : COLORS.GRAY }}- >- {useAutoRouting ? <ToggleRight size={20} /> : <ToggleLeft size={20} />}- </button>+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>+ <span style={{ fontSize: '9px', color: FINCEPT.GRAY }}>AUTO-ROUTE</span>+ <button+ onClick={() => setUseAutoRouting(!useAutoRouting)}+ style={{+ background: 'none',+ border: 'none',+ cursor: 'pointer',+ color: useAutoRouting ? FINCEPT.GREEN : FINCEPT.GRAY,+ }}+ >+ {useAutoRouting ? <ToggleRight size={18} /> : <ToggleLeft size={18} />}+ </button>+ </div></div></div>- {/* Messages */}- <div className="flex-1 overflow-y-auto p-4 space-y-3">+ {/* Messages Area */}+ <div style={{+ flex: 1,+ overflow: 'auto',+ padding: '16px',+ display: 'flex',+ flexDirection: 'column',+ gap: '12px',+ }}>{chatMessages.length === 0 ? (- <div className="text-center py-8" style={{ color: COLORS.GRAY }}>- <Sparkles size={32} className="mx-auto mb-2" />- <p>Start a conversation</p>- <p className="text-xs mt-1">+ <div style={{+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ justifyContent: 'center',+ height: '100%',+ color: FINCEPT.GRAY,+ textAlign: 'center',+ }}>+ <Sparkles size={40} style={{ marginBottom: '16px', opacity: 0.5 }} />+ <span style={{ fontSize: '12px', marginBottom: '8px' }}>Start a conversation</span>+ <span style={{ fontSize: '10px', color: FINCEPT.MUTED }}>{useAutoRouting ? 'Queries will be auto-routed to the best agent' : `Using: ${selectedAgent?.name || 'No agent selected'}`}- </p>+ </span></div>) : (chatMessages.map((msg, i) => (- <div key={i} className={`flex ${msg.role === 'user' ? 'justify-end' : 'justify-start'}`}>- <div- className="max-w-[85%] p-3 rounded-lg"- style={{- backgroundColor: msg.role === 'user' ? COLORS.ORANGE :- msg.role === 'system' ? COLORS.PURPLE + '20' : COLORS.PANEL_BG,- color: COLORS.WHITE,- border: msg.role === 'system' ? `1px solid ${COLORS.PURPLE}40` : 'none',- }}- >+ <div key={i} style={{+ display: 'flex',+ justifyContent: msg.role === 'user' ? 'flex-end' : 'flex-start',+ }}>+ <div style={{+ maxWidth: '80%',+ padding: '12px',+ borderRadius: '4px',+ backgroundColor: msg.role === 'user' ? FINCEPT.ORANGE :+ msg.role === 'system' ? `${FINCEPT.PURPLE}20` : FINCEPT.DARK_BG,+ color: msg.role === 'user' ? FINCEPT.DARK_BG : FINCEPT.WHITE,+ border: msg.role === 'system' ? `1px solid ${FINCEPT.PURPLE}40` :+ msg.role === 'user' ? 'none' : `1px solid ${FINCEPT.BORDER}`,+ }}>{msg.agentName && (- <div className="text-xs mb-1 flex items-center gap-1" style={{ color: COLORS.ORANGE }}>- <Bot size={12} />- {msg.agentName}+ <div style={{+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ marginBottom: '6px',+ fontSize: '9px',+ fontWeight: 700,+ color: FINCEPT.CYAN,+ }}>+ <Bot size={10} />+ {msg.agentName.toUpperCase()}</div>)}- <div className="text-sm whitespace-pre-wrap">{msg.content}</div>- <div className="text-xs mt-1 opacity-60">+ <div style={{+ fontSize: '11px',+ whiteSpace: 'pre-wrap',+ lineHeight: 1.5,+ }}>+ {msg.content}+ </div>+ <div style={{+ fontSize: '9px',+ marginTop: '8px',+ opacity: 0.6,+ color: msg.role === 'user' ? FINCEPT.DARK_BG : FINCEPT.GRAY,+ }}>{msg.timestamp.toLocaleTimeString()}</div></div>@@ -1598,9 +2866,13 @@ const AgentConfigTab: React.FC = () => {<div ref={chatEndRef} /></div>- {/* Input */}- <div className="p-4 border-t" style={{ borderColor: COLORS.BORDER }}>- <div className="flex gap-2">+ {/* Input Area */}+ <div style={{+ padding: '12px 16px',+ backgroundColor: FINCEPT.HEADER_BG,+ borderTop: `1px solid ${FINCEPT.BORDER}`,+ }}>+ <div style={{ display: 'flex', gap: '8px' }}><inputtype="text"value={chatInput}@@ -1612,17 +2884,37 @@ const AgentConfigTab: React.FC = () => {}}}placeholder={useAutoRouting ? 'Ask anything - auto-routed to best agent...' : 'Type a message...'}- className="flex-1 px-3 py-2 rounded text-sm"- style={{ backgroundColor: COLORS.PANEL_BG, color: COLORS.WHITE, border: `1px solid ${COLORS.BORDER}` }}+ style={{+ flex: 1,+ padding: '10px 12px',+ backgroundColor: FINCEPT.DARK_BG,+ color: FINCEPT.WHITE,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ fontSize: '11px',+ fontFamily: '"IBM Plex Mono", monospace',+ }}/><buttononClick={handleChatSubmit}disabled={loading || !chatInput.trim()}- className="px-4 py-2 rounded flex items-center gap-2"- style={{ backgroundColor: COLORS.ORANGE, color: COLORS.WHITE, opacity: loading ? 0.5 : 1 }}+ style={{+ padding: '10px 16px',+ backgroundColor: FINCEPT.ORANGE,+ color: FINCEPT.DARK_BG,+ border: 'none',+ borderRadius: '2px',+ fontSize: '10px',+ fontWeight: 700,+ cursor: (loading || !chatInput.trim()) ? 'not-allowed' : 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ opacity: (loading || !chatInput.trim()) ? 0.7 : 1,+ }}>- {loading ? <Loader2 size={16} className="animate-spin" /> : <Zap size={16} />}- Send+ {loading ? <Loader2 size={12} className="animate-spin" /> : <Zap size={12} />}+ SEND</button></div></div>@@ -1634,153 +2926,291 @@ const AgentConfigTab: React.FC = () => {// =============================================================================const renderSystemView = () => (- <div className="p-4 space-y-4">- <div className="flex items-center justify-between">- <h2 className="text-lg font-semibold" style={{ color: COLORS.WHITE }}>System Capabilities</h2>- <button- onClick={() => loadSystemData()}- className="p-2 rounded"- style={{ backgroundColor: COLORS.BORDER }}- >- <RefreshCw size={14} style={{ color: COLORS.WHITE }} />- </button>- </div>-- {systemInfo ? (- <div className="grid grid-cols-2 md:grid-cols-4 gap-4">- <div className="p-4 rounded text-center" style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>- <div className="text-2xl font-bold" style={{ color: COLORS.ORANGE }}>{systemInfo.capabilities.model_providers}</div>- <div className="text-xs" style={{ color: COLORS.GRAY }}>Model Providers</div>- </div>- <div className="p-4 rounded text-center" style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>- <div className="text-2xl font-bold" style={{ color: COLORS.ORANGE }}>{systemInfo.capabilities.tools}</div>- <div className="text-xs" style={{ color: COLORS.GRAY }}>Tools</div>- </div>- <div className="p-4 rounded text-center" style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>- <div className="text-2xl font-bold" style={{ color: COLORS.ORANGE }}>{discoveredAgents.length}</div>- <div className="text-xs" style={{ color: COLORS.GRAY }}>Discovered Agents</div>- </div>- <div className="p-4 rounded text-center" style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>- <div className="text-2xl font-bold" style={{ color: COLORS.ORANGE }}>{configuredLLMs.length}</div>- <div className="text-xs" style={{ color: COLORS.GRAY }}>Configured LLMs</div>+ <div style={{+ display: 'flex',+ height: '100%',+ overflow: 'hidden',+ }}>+ {/* Main Content */}+ <div style={{+ flex: 1,+ overflow: 'auto',+ padding: '16px',+ }}>+ {/* Header */}+ <div style={{+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ marginBottom: '16px',+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <Cpu size={16} style={{ color: FINCEPT.ORANGE }} />+ <span style={{ fontSize: '12px', fontWeight: 700, color: FINCEPT.WHITE }}>+ SYSTEM CAPABILITIES+ </span></div>- </div>- ) : (- <div className="text-center py-8" style={{ color: COLORS.GRAY }}>Loading system info...</div>- )}-- {/* Configured LLMs from Settings */}- <div className="p-4 rounded" style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>- <div className="flex items-center justify-between mb-3">- <div className="text-xs font-medium" style={{ color: COLORS.GRAY }}>CONFIGURED LLM PROVIDERS (from Settings)</div><button- onClick={() => loadLLMConfigs()}- className="px-2 py-1 rounded text-xs"- style={{ backgroundColor: COLORS.BORDER, color: COLORS.WHITE }}+ onClick={() => loadSystemData()}+ style={{+ padding: '6px 10px',+ backgroundColor: 'transparent',+ border: `1px solid ${FINCEPT.BORDER}`,+ color: FINCEPT.GRAY,+ fontSize: '9px',+ fontWeight: 700,+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ borderRadius: '2px',+ }}>- Refresh+ <RefreshCw size={10} /> REFRESH</button></div>- {configuredLLMs.length > 0 ? (- <div className="space-y-2">- {configuredLLMs.map((llm, idx) => {- const hasKey = !!llm.api_key && llm.api_key.length > 0;- return (- <div- key={idx}- className="flex items-center justify-between p-2 rounded"- style={{ backgroundColor: COLORS.BORDER }}- >- <div className="flex items-center gap-2">- {llm.is_active && (- <span className="px-1.5 py-0.5 rounded text-xs" style={{ backgroundColor: COLORS.GREEN + '30', color: COLORS.GREEN }}>- Active- </span>- )}- <span className="text-sm font-medium" style={{ color: COLORS.WHITE }}>- {llm.provider.charAt(0).toUpperCase() + llm.provider.slice(1)}- </span>- <span className="text-xs" style={{ color: COLORS.GRAY }}>- {llm.model}- </span>- </div>- <div className="flex items-center gap-2">- {hasKey ? (- <span className="flex items-center gap-1 text-xs" style={{ color: COLORS.GREEN }}>- <CheckCircle size={12} /> API Key Set- </span>- ) : (- <span className="flex items-center gap-1 text-xs" style={{ color: COLORS.RED }}>- <AlertCircle size={12} /> No API Key- </span>- )}- </div>- </div>- );- })}++ {/* Stats Grid */}+ {systemInfo ? (+ <div style={{+ display: 'grid',+ gridTemplateColumns: 'repeat(4, 1fr)',+ gap: '12px',+ marginBottom: '16px',+ }}>+ {[+ { value: systemInfo.capabilities.model_providers, label: 'PROVIDERS', color: FINCEPT.ORANGE },+ { value: systemInfo.capabilities.tools, label: 'TOOLS', color: FINCEPT.CYAN },+ { value: discoveredAgents.length, label: 'AGENTS', color: FINCEPT.GREEN },+ { value: configuredLLMs.length, label: 'LLMs', color: FINCEPT.PURPLE },+ ].map((stat, idx) => (+ <div key={idx} style={{+ padding: '16px',+ backgroundColor: FINCEPT.PANEL_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ textAlign: 'center',+ }}>+ <div style={{ fontSize: '24px', fontWeight: 700, color: stat.color }}>{stat.value}</div>+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY, marginTop: '4px' }}>{stat.label}</div>+ </div>+ ))}</div>) : (- <div className="text-center py-4" style={{ color: COLORS.GRAY }}>- <AlertCircle size={24} className="mx-auto mb-2" />- <p className="text-sm">No LLM providers configured</p>- <p className="text-xs mt-1">Go to Settings → LLM Configuration to add providers</p>- </div>- )}- {configuredLLMs.filter(l => !l.api_key || l.api_key.length === 0).length > 0 && (- <div className="mt-3 p-2 rounded text-xs" style={{ backgroundColor: COLORS.RED + '10', color: COLORS.RED }}>- {configuredLLMs.filter(l => !l.api_key || l.api_key.length === 0).length} provider(s) missing API keys. Go to Settings → LLM Configuration to add them.+ <div style={{+ padding: '32px',+ textAlign: 'center',+ color: FINCEPT.GRAY,+ fontSize: '11px',+ }}>+ Loading system info...</div>)}- </div>- {/* Cache Stats */}- <div className="p-4 rounded" style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>- <div className="flex items-center justify-between mb-3">- <div className="text-xs font-medium" style={{ color: COLORS.GRAY }}>CACHE STATISTICS</div>- <button- onClick={() => agentService.clearCache()}- className="px-2 py-1 rounded text-xs"- style={{ backgroundColor: COLORS.BORDER, color: COLORS.WHITE }}- >- Clear Cache- </button>- </div>- <div className="grid grid-cols-3 gap-4 text-sm">- <div>- <div style={{ color: COLORS.GRAY }}>Static Cache:</div>- <div style={{ color: COLORS.WHITE }}>{agentService.getCacheStats().cacheSize} items</div>- </div>- <div>- <div style={{ color: COLORS.GRAY }}>Response Cache:</div>- <div style={{ color: COLORS.WHITE }}>{agentService.getCacheStats().responseCacheSize} items</div>+ {/* LLM Providers Section */}+ <div style={{+ backgroundColor: FINCEPT.PANEL_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ marginBottom: '12px',+ }}>+ <div style={{+ padding: '12px',+ backgroundColor: FINCEPT.HEADER_BG,+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ }}>+ <span style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY }}>+ CONFIGURED LLM PROVIDERS+ </span>+ <button+ onClick={() => loadLLMConfigs()}+ style={{+ padding: '2px 6px',+ backgroundColor: 'transparent',+ border: `1px solid ${FINCEPT.BORDER}`,+ color: FINCEPT.GRAY,+ fontSize: '8px',+ cursor: 'pointer',+ borderRadius: '2px',+ }}+ >+ REFRESH+ </button></div>- <div>- <div style={{ color: COLORS.GRAY }}>Max Size:</div>- <div style={{ color: COLORS.WHITE }}>{agentService.getCacheStats().maxSize} items</div>+ <div style={{ padding: '12px' }}>+ {configuredLLMs.length > 0 ? (+ <div style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}>+ {configuredLLMs.map((llm, idx) => {+ const hasKey = !!llm.api_key && llm.api_key.length > 0;+ return (+ <div key={idx} style={{+ padding: '10px 12px',+ backgroundColor: FINCEPT.DARK_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ {llm.is_active && (+ <span style={{+ padding: '2px 6px',+ backgroundColor: `${FINCEPT.GREEN}20`,+ color: FINCEPT.GREEN,+ fontSize: '8px',+ fontWeight: 700,+ borderRadius: '2px',+ }}>+ ACTIVE+ </span>+ )}+ <span style={{ fontSize: '10px', fontWeight: 600, color: FINCEPT.WHITE }}>+ {llm.provider.toUpperCase()}+ </span>+ <span style={{ fontSize: '9px', color: FINCEPT.GRAY }}>{llm.model}</span>+ </div>+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>+ {hasKey ? (+ <>+ <CheckCircle size={10} style={{ color: FINCEPT.GREEN }} />+ <span style={{ fontSize: '9px', color: FINCEPT.GREEN }}>KEY SET</span>+ </>+ ) : (+ <>+ <AlertCircle size={10} style={{ color: FINCEPT.RED }} />+ <span style={{ fontSize: '9px', color: FINCEPT.RED }}>NO KEY</span>+ </>+ )}+ </div>+ </div>+ );+ })}+ </div>+ ) : (+ <div style={{+ padding: '24px',+ textAlign: 'center',+ color: FINCEPT.GRAY,+ }}>+ <AlertCircle size={20} style={{ marginBottom: '8px', opacity: 0.5 }} />+ <div style={{ fontSize: '10px' }}>No LLM providers configured</div>+ <div style={{ fontSize: '9px', color: FINCEPT.MUTED, marginTop: '4px' }}>+ Go to Settings → LLM Configuration+ </div>+ </div>+ )}</div></div>- </div>- {systemInfo?.features && (- <div className="p-4 rounded" style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>- <div className="text-xs font-medium mb-2" style={{ color: COLORS.GRAY }}>FEATURES</div>- <div className="flex flex-wrap gap-2">- {systemInfo.features.map(feature => (- <span key={feature} className="px-2 py-1 rounded text-xs" style={{ backgroundColor: COLORS.BORDER, color: COLORS.WHITE }}>- {feature.replace(/_/g, ' ')}- </span>+ {/* Cache Stats */}+ <div style={{+ backgroundColor: FINCEPT.PANEL_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ marginBottom: '12px',+ }}>+ <div style={{+ padding: '12px',+ backgroundColor: FINCEPT.HEADER_BG,+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ }}>+ <span style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY }}>CACHE STATISTICS</span>+ <button+ onClick={() => agentService.clearCache()}+ style={{+ padding: '2px 6px',+ backgroundColor: 'transparent',+ border: `1px solid ${FINCEPT.RED}`,+ color: FINCEPT.RED,+ fontSize: '8px',+ cursor: 'pointer',+ borderRadius: '2px',+ }}+ >+ CLEAR+ </button>+ </div>+ <div style={{+ padding: '12px',+ display: 'grid',+ gridTemplateColumns: 'repeat(3, 1fr)',+ gap: '12px',+ }}>+ {[+ { label: 'STATIC', value: agentService.getCacheStats().cacheSize },+ { label: 'RESPONSE', value: agentService.getCacheStats().responseCacheSize },+ { label: 'MAX SIZE', value: agentService.getCacheStats().maxSize },+ ].map((stat, idx) => (+ <div key={idx} style={{+ padding: '12px',+ backgroundColor: FINCEPT.DARK_BG,+ borderRadius: '2px',+ textAlign: 'center',+ }}>+ <div style={{ fontSize: '16px', fontWeight: 700, color: FINCEPT.CYAN }}>{stat.value}</div>+ <div style={{ fontSize: '8px', color: FINCEPT.GRAY, marginTop: '4px' }}>{stat.label}</div>+ </div>))}</div></div>- )}- <div className="p-4 rounded" style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>- <div className="text-xs font-medium mb-2" style={{ color: COLORS.GRAY }}>VERSION INFO</div>- <div className="grid grid-cols-2 gap-2 text-sm">- <div style={{ color: COLORS.GRAY }}>Version:</div>- <div style={{ color: COLORS.WHITE }}>{systemInfo?.version || 'N/A'}</div>- <div style={{ color: COLORS.GRAY }}>Framework:</div>- <div style={{ color: COLORS.WHITE }}>{systemInfo?.framework || 'N/A'}</div>+ {/* Features */}+ {systemInfo?.features && (+ <div style={{+ backgroundColor: FINCEPT.PANEL_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ marginBottom: '12px',+ }}>+ <div style={{+ padding: '12px',+ backgroundColor: FINCEPT.HEADER_BG,+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ }}>+ <span style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY }}>FEATURES</span>+ </div>+ <div style={{ padding: '12px', display: 'flex', flexWrap: 'wrap', gap: '6px' }}>+ {systemInfo.features.map(feature => (+ <span key={feature} style={{+ padding: '4px 8px',+ backgroundColor: FINCEPT.DARK_BG,+ color: FINCEPT.WHITE,+ fontSize: '9px',+ borderRadius: '2px',+ }}>+ {feature.replace(/_/g, ' ').toUpperCase()}+ </span>+ ))}+ </div>+ </div>+ )}++ {/* Version Info */}+ <div style={{+ backgroundColor: FINCEPT.PANEL_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ }}>+ <div style={{+ padding: '12px',+ backgroundColor: FINCEPT.HEADER_BG,+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ }}>+ <span style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY }}>VERSION INFO</span>+ </div>+ <div style={{ padding: '12px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px' }}>+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY }}>VERSION</div>+ <div style={{ fontSize: '10px', color: FINCEPT.CYAN }}>{systemInfo?.version || 'N/A'}</div>+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY }}>FRAMEWORK</div>+ <div style={{ fontSize: '10px', color: FINCEPT.CYAN }}>{systemInfo?.framework || 'N/A'}</div>+ </div></div></div></div>@@ -1790,54 +3220,271 @@ const AgentConfigTab: React.FC = () => {// Main Render// =============================================================================+ // Show initial loading screen+ if (loading && discoveredAgents.length === 0 && !systemInfo && !toolsInfo) {+ return (+ <div+ className="agent-terminal flex flex-col h-full items-center justify-center"+ style={{+ backgroundColor: FINCEPT.DARK_BG,+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',+ }}+ >+ <style>{TERMINAL_STYLES}</style>+ <div style={{+ padding: '48px',+ backgroundColor: FINCEPT.PANEL_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '4px',+ textAlign: 'center',+ }}>+ <Bot size={48} className="mx-auto mb-4" style={{ color: FINCEPT.ORANGE }} />+ <Loader2 size={32} className="animate-spin mx-auto mb-4" style={{ color: FINCEPT.ORANGE }} />+ <h2 style={{+ fontSize: '18px',+ fontWeight: 700,+ marginBottom: '8px',+ color: FINCEPT.WHITE,+ letterSpacing: '0.5px',+ }}>+ INITIALIZING AGENT STUDIO+ </h2>+ <p style={{ fontSize: '11px', marginBottom: '16px', color: FINCEPT.GRAY }}>+ Loading agents and system capabilities...+ </p>+ <button+ onClick={() => {+ setLoading(false);+ setError('Agent loading was skipped. Some features may not be available.');+ }}+ style={{+ padding: '8px 16px',+ backgroundColor: FINCEPT.BORDER,+ color: FINCEPT.WHITE,+ border: 'none',+ borderRadius: '2px',+ fontSize: '10px',+ fontWeight: 700,+ cursor: 'pointer',+ letterSpacing: '0.5px',+ }}+ >+ SKIP LOADING+ </button>+ </div>+ </div>+ );+ }+return (- <div className="flex flex-col h-full" style={{ backgroundColor: COLORS.DARK_BG }}>- {/* Header */}- <div className="flex items-center justify-between px-4 py-3 border-b" style={{ borderColor: COLORS.BORDER }}>- <div className="flex items-center gap-3">- <Bot size={20} style={{ color: COLORS.ORANGE }} />- <h1 className="text-lg font-semibold" style={{ color: COLORS.WHITE }}>Agent Studio</h1>- <span className="text-xs px-2 py-0.5 rounded" style={{ backgroundColor: COLORS.PURPLE + '20', color: COLORS.PURPLE }}>+ <div+ className="agent-terminal flex flex-col h-full overflow-hidden"+ style={{+ backgroundColor: FINCEPT.DARK_BG,+ color: FINCEPT.WHITE,+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',+ }}+ >+ <style>{TERMINAL_STYLES}</style>++ {/* Top Navigation Bar - Terminal Style with Orange Accent */}+ <div style={{+ backgroundColor: FINCEPT.HEADER_BG,+ borderBottom: `2px solid ${FINCEPT.ORANGE}`,+ padding: '8px 16px',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ flexShrink: 0,+ boxShadow: `0 2px 8px ${FINCEPT.ORANGE}20`,+ }}>+ {/* Left: Logo and Title */}+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>+ <Bot size={20} style={{ color: FINCEPT.ORANGE }} />+ <span style={{+ fontSize: '14px',+ fontWeight: 700,+ color: FINCEPT.WHITE,+ letterSpacing: '0.5px',+ }}>+ AGENT STUDIO+ </span>+ <span style={{+ padding: '2px 8px',+ backgroundColor: `${FINCEPT.PURPLE}20`,+ color: FINCEPT.PURPLE,+ fontSize: '9px',+ fontWeight: 700,+ borderRadius: '2px',+ }}>v2.1</span>+ <div style={{ height: '16px', width: '1px', backgroundColor: FINCEPT.BORDER, margin: '0 4px' }} />++ {/* Status Indicators */}+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>+ <div style={{+ width: '6px',+ height: '6px',+ borderRadius: '50%',+ backgroundColor: discoveredAgents.length > 0 ? FINCEPT.GREEN : FINCEPT.RED,+ }} />+ <span style={{ fontSize: '9px', color: FINCEPT.GRAY }}>+ {discoveredAgents.length} AGENTS+ </span>+ </div>+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>+ <div style={{+ width: '6px',+ height: '6px',+ borderRadius: '50%',+ backgroundColor: configuredLLMs.length > 0 ? FINCEPT.GREEN : FINCEPT.YELLOW,+ animation: configuredLLMs.length === 0 ? 'pulse 2s infinite' : 'none',+ }} />+ <span style={{ fontSize: '9px', color: FINCEPT.GRAY }}>+ {configuredLLMs.length} LLMs+ </span>+ </div>+ </div></div>- {/* View Mode Tabs */}- <div className="flex gap-1">+ {/* Center: View Mode Tabs */}+ <div style={{ display: 'flex', gap: '2px' }}>{VIEW_MODES.map(mode => (<buttonkey={mode.id}onClick={() => setViewMode(mode.id)}- className="px-3 py-1.5 rounded text-xs font-medium flex items-center gap-1.5 transition-colors"style={{- backgroundColor: viewMode === mode.id ? COLORS.ORANGE : 'transparent',- color: viewMode === mode.id ? COLORS.WHITE : COLORS.GRAY,+ padding: '6px 12px',+ backgroundColor: viewMode === mode.id ? FINCEPT.ORANGE : 'transparent',+ color: viewMode === mode.id ? FINCEPT.DARK_BG : FINCEPT.GRAY,+ border: 'none',+ fontSize: '9px',+ fontWeight: 700,+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ letterSpacing: '0.5px',+ transition: 'all 0.2s',+ }}+ onMouseEnter={(e) => {+ if (viewMode !== mode.id) {+ e.currentTarget.style.backgroundColor = FINCEPT.HOVER;+ e.currentTarget.style.color = FINCEPT.WHITE;+ }+ }}+ onMouseLeave={(e) => {+ if (viewMode !== mode.id) {+ e.currentTarget.style.backgroundColor = 'transparent';+ e.currentTarget.style.color = FINCEPT.GRAY;+ }}}>- <mode.icon size={14} />+ <mode.icon size={12} />{mode.name}</button>))}</div>++ {/* Right: Actions */}+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <button+ onClick={loadDiscoveredAgents}+ disabled={loading}+ style={{+ padding: '4px 8px',+ backgroundColor: 'transparent',+ border: `1px solid ${FINCEPT.BORDER}`,+ color: FINCEPT.GRAY,+ cursor: loading ? 'not-allowed' : 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ fontSize: '9px',+ borderRadius: '2px',+ opacity: loading ? 0.5 : 1,+ }}+ >+ <RefreshCw size={12} className={loading ? 'animate-spin' : ''} />+ REFRESH+ </button>+ <button+ onClick={() => setUseAutoRouting(!useAutoRouting)}+ style={{+ padding: '4px 8px',+ backgroundColor: useAutoRouting ? `${FINCEPT.GREEN}20` : 'transparent',+ border: `1px solid ${useAutoRouting ? FINCEPT.GREEN : FINCEPT.BORDER}`,+ color: useAutoRouting ? FINCEPT.GREEN : FINCEPT.GRAY,+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ fontSize: '9px',+ borderRadius: '2px',+ }}+ >+ <Route size={12} />+ AUTO-ROUTE+ </button>+ </div></div>{/* Notifications */}{error && (- <div className="mx-4 mt-2 p-3 rounded flex items-center gap-2" style={{ backgroundColor: COLORS.RED + '20', color: COLORS.RED }}>- <AlertCircle size={16} />- <span className="text-sm flex-1">{error}</span>- <button onClick={() => setError(null)}>×</button>+ <div style={{+ margin: '8px 16px',+ padding: '12px',+ backgroundColor: `${FINCEPT.RED}15`,+ border: `1px solid ${FINCEPT.RED}40`,+ borderRadius: '2px',+ }}>+ <div style={{ display: 'flex', alignItems: 'flex-start', gap: '8px' }}>+ <AlertCircle size={14} style={{ color: FINCEPT.RED, marginTop: '1px', flexShrink: 0 }} />+ <div style={{ flex: 1 }}>+ <div style={{ fontSize: '10px', fontWeight: 700, marginBottom: '4px', color: FINCEPT.RED }}>ERROR</div>+ <div style={{ fontSize: '10px', color: FINCEPT.RED }}>{error}</div>+ {error.includes('timeout') && (+ <div style={{ fontSize: '9px', marginTop: '4px', color: FINCEPT.MUTED }}>+ Backend may be slow. You can continue with manual configuration.+ </div>+ )}+ </div>+ <button+ onClick={() => setError(null)}+ style={{+ background: 'none',+ border: 'none',+ color: FINCEPT.RED,+ cursor: 'pointer',+ fontSize: '14px',+ lineHeight: 1,+ }}+ >+ ×+ </button>+ </div></div>)}{success && (- <div className="mx-4 mt-2 p-3 rounded flex items-center gap-2" style={{ backgroundColor: COLORS.GREEN + '20', color: COLORS.GREEN }}>- <CheckCircle size={16} />- <span className="text-sm">{success}</span>+ <div style={{+ margin: '8px 16px',+ padding: '12px',+ backgroundColor: `${FINCEPT.GREEN}15`,+ border: `1px solid ${FINCEPT.GREEN}40`,+ borderRadius: '2px',+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ }}>+ <CheckCircle size={14} style={{ color: FINCEPT.GREEN }} />+ <span style={{ fontSize: '10px', color: FINCEPT.GREEN }}>{success}</span></div>)}- {/* Content */}- <div className="flex-1 overflow-hidden">+ {/* Main Content Area */}+ <div style={{ flex: 1, overflow: 'hidden' }}>{viewMode === 'agents' && renderAgentsView()}{viewMode === 'teams' && renderTeamsView()}{viewMode === 'workflows' && renderWorkflowsView()}@@ -1847,7 +3494,42 @@ const AgentConfigTab: React.FC = () => {{viewMode === 'system' && renderSystemView()}</div>- <TabFooter tabName="Agent Studio v2.1" />+ {/* Status Bar at Bottom */}+ <div style={{+ backgroundColor: FINCEPT.HEADER_BG,+ borderTop: `1px solid ${FINCEPT.BORDER}`,+ padding: '4px 16px',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ fontSize: '9px',+ color: FINCEPT.GRAY,+ flexShrink: 0,+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>+ <span>+ MODE: <span style={{ color: useAutoRouting ? FINCEPT.GREEN : FINCEPT.ORANGE }}>+ {useAutoRouting ? 'AUTO-ROUTING' : 'MANUAL'}+ </span>+ </span>+ <span>+ VIEW: <span style={{ color: FINCEPT.CYAN }}>{viewMode.toUpperCase()}</span>+ </span>+ {selectedAgent && (+ <span>+ AGENT: <span style={{ color: FINCEPT.ORANGE }}>{selectedAgent.name}</span>+ </span>+ )}+ </div>+ <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>+ <span>+ LLM: <span style={{ color: FINCEPT.PURPLE }}>+ {editedConfig.provider}/{editedConfig.model_id}+ </span>+ </span>+ <span style={{ color: FINCEPT.MUTED }}>AGENT STUDIO v2.1</span>+ </div>+ </div></div>);};diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/NodeEditorTab.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/NodeEditorTab.tsxindex f5626fcda..faad8641f 100644--- a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/NodeEditorTab.tsx+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/NodeEditorTab.tsx@@ -536,6 +536,12 @@ export default function NodeEditorTab() {// Handle keyboard shortcutsuseEffect(() => {const handleKeyDown = (event: KeyboardEvent) => {+ // Don't trigger if user is typing in an input field+ const target = event.target as HTMLElement;+ if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable) {+ return;+ }+if (event.key === 'Delete' || event.key === 'Backspace') {deleteSelectedNodes();deleteSelectedEdges();diff --git a/fincept-terminal-desktop/src/components/tabs/akshare-data/AkShareDataTab.tsx b/fincept-terminal-desktop/src/components/tabs/akshare-data/AkShareDataTab.tsxindex 0b6869469..4b45b077e 100644--- a/fincept-terminal-desktop/src/components/tabs/akshare-data/AkShareDataTab.tsx+++ b/fincept-terminal-desktop/src/components/tabs/akshare-data/AkShareDataTab.tsx@@ -13,7 +13,7 @@import React, { useState, useEffect, useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';import { useTerminalTheme } from '@/contexts/ThemeContext';-import { TabFooter } from '@/components/common/TabFooter';+import { useLanguage } from '@/contexts/LanguageContext';import { AKShareAPI, AKSHARE_DATA_SOURCES, AKShareDataSource, AKShareResponse } from '@/services/akshareApi';import {Search, RefreshCw, Download, ChevronRight, ChevronDown, Database,@@ -21,29 +21,37 @@ import {AlertCircle, CheckCircle2, Clock, Filter, X, Copy, Table, Code,ArrowUpDown, ExternalLink, Bookmark, BookmarkCheck, History, Zap, Building2,Activity, DollarSign, Newspaper, Building, Bitcoin, FileText, Users,- ArrowRightLeft, LayoutGrid, Percent, Flame+ ArrowRightLeft, LayoutGrid, Percent, Flame, ChevronLeft, PanelLeftClose, PanelLeftOpen} from 'lucide-react';-// Color palette-const COLORS = {+// Fincept Terminal Color Palette+const FINCEPT = {ORANGE: '#FF8800',WHITE: '#FFFFFF',RED: '#FF3B3B',GREEN: '#00D66F',+ BLUE: '#0088FF',+ PURPLE: '#9D4EDD',GRAY: '#787878',DARK_BG: '#000000',- PANEL_BG: '#0A0A0A',- HEADER_BG: '#111111',+ PANEL_BG: '#0F0F0F',+ HEADER_BG: '#1A1A1A',+ BORDER: '#2A2A2A',+ HOVER: '#1F1F1F',+ MUTED: '#4A4A4A',CYAN: '#00E5FF',YELLOW: '#FFD700',- BLUE: '#3B82F6',- PURPLE: '#8B5CF6',- PINK: '#EC4899',- BORDER: '#1F1F1F',- HOVER: '#1A1A1A',- MUTED: '#4A4A4A'};+// Terminal CSS styles+const TERMINAL_STYLES = `+ .akshare-scrollbar::-webkit-scrollbar { width: 6px; height: 6px; }+ .akshare-scrollbar::-webkit-scrollbar-track { background: ${FINCEPT.DARK_BG}; }+ .akshare-scrollbar::-webkit-scrollbar-thumb { background: ${FINCEPT.BORDER}; border-radius: 3px; }+ .akshare-scrollbar::-webkit-scrollbar-thumb:hover { background: ${FINCEPT.MUTED}; }+ .akshare-hover-row:hover { background: ${FINCEPT.HOVER} !important; }+`;+// Icon mappingconst IconMap: Record<string, React.FC<{ size?: number; color?: string }>> = {Landmark,@@ -88,6 +96,7 @@ interface FavoriteEndpoint {const AkShareDataTab: React.FC = () => {const { t } = useTranslation();const { colors } = useTerminalTheme();+ const { currentLanguage } = useLanguage();// Stateconst [selectedSource, setSelectedSource] = useState<AKShareDataSource | null>(null);@@ -103,18 +112,72 @@ const AkShareDataTab: React.FC = () => {const [data, setData] = useState<any[] | null>(null);const [error, setError] = useState<string | null>(null);const [responseInfo, setResponseInfo] = useState<{ count: number; timestamp: number; source?: string } | null>(null);+ const [translatedColumns, setTranslatedColumns] = useState<Record<string, string>>({});+ const [translatedData, setTranslatedData] = useState<any[] | null>(null);+ const [translating, setTranslating] = useState(false);// View stateconst [viewMode, setViewMode] = useState<'table' | 'json'>('table');const [sortColumn, setSortColumn] = useState<string | null>(null);const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('asc');+ // Pagination state+ const [currentPage, setCurrentPage] = useState(1);+ const [pageSize, setPageSize] = useState(10);+ const [translatedPages, setTranslatedPages] = useState<Map<number, any[]>>(new Map());++ // Panel collapse state+ const [isSourcesPanelCollapsed, setIsSourcesPanelCollapsed] = useState(false);+ const [isEndpointsPanelCollapsed, setIsEndpointsPanelCollapsed] = useState(false);+// History & Favoritesconst [queryHistory, setQueryHistory] = useState<QueryHistoryItem[]>([]);const [favorites, setFavorites] = useState<FavoriteEndpoint[]>([]);const [showHistory, setShowHistory] = useState(false);const [showFavorites, setShowFavorites] = useState(false);+ // Debug: Log language on mount and changes+ useEffect(() => {+ console.log('AkShare Tab - Current Language:', currentLanguage);+ }, [currentLanguage]);++ // Translate current page when page changes or language changes+ useEffect(() => {+ const translateCurrentPage = async () => {+ if (!data || data.length === 0) return;++ const langCode = currentLanguage === 'zh' ? 'zh-CN' : (currentLanguage || 'en');+ if (langCode === 'zh-CN') return; // No translation needed for Chinese++ // Check if this page is already translated+ if (translatedPages.has(currentPage)) {+ console.log(`Page ${currentPage} already translated, using cached version`);+ return;+ }++ setTranslating(true);+ try {+ const startIdx = (currentPage - 1) * pageSize;+ const endIdx = startIdx + pageSize;+ const pageData = data.slice(startIdx, endIdx);++ console.log(`Translating page ${currentPage} (rows ${startIdx}-${endIdx})...`);+ const translatedPageData = await translatePageData(pageData, langCode);++ // Cache the translated page+ const newTranslatedPages = new Map(translatedPages);+ newTranslatedPages.set(currentPage, translatedPageData);+ setTranslatedPages(newTranslatedPages);+ } catch (err) {+ console.error('Failed to translate page:', err);+ } finally {+ setTranslating(false);+ }+ };++ translateCurrentPage();+ }, [currentPage, data, currentLanguage, pageSize, translatedPages]);+// Load endpoints when source changesuseEffect(() => {if (selectedSource) {@@ -150,7 +213,8 @@ const AkShareDataTab: React.FC = () => {try {const response = await AKShareAPI.getEndpoints(script);if (response.success && response.data) {- const endpointData = response.data as any;+ // Handle nested data structure from Python+ const endpointData = (response.data as any).data || response.data;setEndpoints(endpointData.available_endpoints || []);setCategories(endpointData.categories || {});// Auto-expand first category@@ -168,12 +232,72 @@ const AkShareDataTab: React.FC = () => {}};+ const translatePageData = async (pageData: any[], targetLang: string) => {+ try {+ // Collect text values that need translation from this page only+ const textsToTranslate: string[] = [];+ const textPositions: Array<{rowIdx: number, col: string}> = [];++ pageData.forEach((row, rowIdx) => {+ Object.entries(row).forEach(([col, value]) => {+ if (typeof value === 'string' && value.trim().length > 0) {+ // Check if contains Chinese/non-ASCII characters+ if (/[\u4e00-\u9fa5\u3000-\u303f]/.test(value)) {+ textsToTranslate.push(value);+ textPositions.push({rowIdx, col});+ }+ }+ });+ });++ if (textsToTranslate.length > 0) {+ console.log(`Translating ${textsToTranslate.length} text fields for current page...`);+ const contentResponse = await AKShareAPI.translateBatch(textsToTranslate, targetLang);++ if (contentResponse.success && contentResponse.translations) {+ const newData = JSON.parse(JSON.stringify(pageData)); // Deep clone+ contentResponse.translations.forEach((t: any, idx: number) => {+ const pos = textPositions[idx];+ if (pos && newData[pos.rowIdx]) {+ newData[pos.rowIdx][pos.col] = t.translated || t.original;+ }+ });+ return newData;+ }+ }++ return pageData;+ } catch (err) {+ console.error('Page translation failed:', err);+ return pageData;+ }+ };++ const translateColumnHeaders = async (columns: string[], targetLang: string) => {+ console.log(`Translating ${columns.length} column headers to ${targetLang}...`);+ const headerResponse = await AKShareAPI.translateBatch(columns, targetLang);+ console.log('Header translation response:', headerResponse);++ const translatedHeaders: Record<string, string> = {};+ if (headerResponse.success && headerResponse.translations) {+ headerResponse.translations.forEach((t: any) => {+ translatedHeaders[t.original] = t.translated;+ });+ setTranslatedColumns(translatedHeaders);+ console.log('Translated headers:', translatedHeaders);+ }+ };+const executeQuery = async (script: string, endpoint: string) => {setLoading(true);setError(null);setData(null);setResponseInfo(null);setSelectedEndpoint(endpoint);+ setTranslatedColumns({});+ setTranslatedData(null);+ setCurrentPage(1);+ setTranslatedPages(new Map());try {const response = await AKShareAPI.query(script, endpoint);@@ -199,6 +323,20 @@ const AkShareDataTab: React.FC = () => {timestamp: response.timestamp || Date.now(),source: response.source});++ // TRANSLATION LAYER: Only translate column headers initially+ if (dataArray.length > 0) {+ const langCode = currentLanguage === 'zh' ? 'zh-CN' : (currentLanguage || 'en');+ console.log(`Current language: ${currentLanguage}, Target translation: ${langCode}`);++ // If English or any non-Chinese language, translate column headers+ if (langCode !== 'zh-CN') {+ const columns = Object.keys(dataArray[0]);+ await translateColumnHeaders(columns, langCode);+ } else {+ console.log('Language is Chinese, skipping translation');+ }+ }} else {setError(typeof response.error === 'string' ? response.error : JSON.stringify(response.error));}@@ -259,10 +397,33 @@ const AkShareDataTab: React.FC = () => {return filtered;}, [categories, searchQuery]);+ // Get paginated data with translation+ const paginatedData = useMemo(() => {+ if (!data) return null;++ const startIdx = (currentPage - 1) * pageSize;+ const endIdx = startIdx + pageSize;++ // Check if we have translated version of current page+ const translatedPage = translatedPages.get(currentPage);+ if (translatedPage) {+ return translatedPage;+ }++ // Return original data for current page+ return data.slice(startIdx, endIdx);+ }, [data, currentPage, pageSize, translatedPages]);++ // Calculate total pages+ const totalPages = useMemo(() => {+ if (!data) return 0;+ return Math.ceil(data.length / pageSize);+ }, [data, pageSize]);+// Sort dataconst sortedData = useMemo(() => {- if (!data || !sortColumn) return data;- return [...data].sort((a, b) => {+ if (!paginatedData || !sortColumn) return paginatedData;+ return [...paginatedData].sort((a, b) => {const aVal = a[sortColumn];const bVal = b[sortColumn];if (aVal === bVal) return 0;@@ -271,24 +432,30 @@ const AkShareDataTab: React.FC = () => {const comparison = aVal < bVal ? -1 : 1;return sortDirection === 'asc' ? comparison : -comparison;});- }, [data, sortColumn, sortDirection]);+ }, [paginatedData, sortColumn, sortDirection]);// Get table columnsconst columns = useMemo(() => {- if (!data || data.length === 0) return [];- return Object.keys(data[0]);- }, [data]);+ if (!paginatedData || paginatedData.length === 0) return [];+ return Object.keys(paginatedData[0]);+ }, [paginatedData]);const copyToClipboard = (text: string) => {navigator.clipboard.writeText(text);};const downloadCSV = () => {+ // Download all data (original, not just current page)if (!data || data.length === 0) return;- const headers = columns.join(',');+ const allColumns = Object.keys(data[0]);++ // Use translated column names if available+ const headerNames = allColumns.map(col => translatedColumns[col] || col);+ const headers = headerNames.join(',');+const rows = data.map(row =>- columns.map(col => {+ allColumns.map(col => {const val = row[col];if (typeof val === 'string' && (val.includes(',') || val.includes('"'))) {return `"${val.replace(/"/g, '""')}"`;@@ -298,7 +465,7 @@ const AkShareDataTab: React.FC = () => {);const csv = [headers, ...rows].join('\n');- const blob = new Blob([csv], { type: 'text/csv' });+ const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });const url = URL.createObjectURL(blob);const a = document.createElement('a');a.href = url;@@ -308,9 +475,10 @@ const AkShareDataTab: React.FC = () => {};const downloadJSON = () => {+ // Download all data (original, not just current page)if (!data) return;const json = JSON.stringify(data, null, 2);- const blob = new Blob([json], { type: 'application/json' });+ const blob = new Blob([json], { type: 'application/json;charset=utf-8;' });const url = URL.createObjectURL(blob);const a = document.createElement('a');a.href = url;@@ -320,255 +488,579 @@ const AkShareDataTab: React.FC = () => {};return (- <div className="flex flex-col h-full" style={{ background: COLORS.DARK_BG }}>- {/* Header */}- <div className="flex items-center justify-between px-4 py-3 border-b" style={{ borderColor: COLORS.BORDER, background: COLORS.HEADER_BG }}>- <div className="flex items-center gap-3">- <Database size={20} color={COLORS.ORANGE} />- <span className="font-semibold text-white">AKShare Data Explorer</span>- <span className="text-xs px-2 py-0.5 rounded" style={{ background: COLORS.ORANGE + '20', color: COLORS.ORANGE }}>- 400+ Endpoints+ <div style={{+ display: 'flex',+ flexDirection: 'column',+ height: '100%',+ backgroundColor: FINCEPT.DARK_BG,+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',+ }}>+ {/* Inject terminal scrollbar styles */}+ <style>{TERMINAL_STYLES}</style>++ {/* Top Navigation Bar */}+ <div style={{+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ padding: '8px 16px',+ backgroundColor: FINCEPT.HEADER_BG,+ borderBottom: `2px solid ${FINCEPT.ORANGE}`,+ boxShadow: `0 2px 8px ${FINCEPT.ORANGE}20`,+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>+ <Database size={20} color={FINCEPT.ORANGE} />+ <span style={{ fontWeight: 700, color: FINCEPT.WHITE, fontSize: '12px', letterSpacing: '0.5px' }}>+ AKSHARE DATA EXPLORER+ </span>+ <span style={{+ padding: '2px 8px',+ backgroundColor: `${FINCEPT.ORANGE}20`,+ color: FINCEPT.ORANGE,+ fontSize: '9px',+ fontWeight: 700,+ borderRadius: '2px',+ }}>+ 400+ ENDPOINTS</span>+ {/* Status indicators */}+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginLeft: '16px' }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>+ <div style={{ width: '6px', height: '6px', borderRadius: '50%', backgroundColor: selectedSource ? FINCEPT.GREEN : FINCEPT.MUTED }} />+ <span style={{ fontSize: '9px', color: FINCEPT.GRAY }}>SOURCE</span>+ </div>+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>+ <div style={{ width: '6px', height: '6px', borderRadius: '50%', backgroundColor: data ? FINCEPT.GREEN : FINCEPT.MUTED }} />+ <span style={{ fontSize: '9px', color: FINCEPT.GRAY }}>DATA</span>+ </div>+ </div></div>- <div className="flex items-center gap-2">+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}><buttononClick={() => setShowFavorites(!showFavorites)}- className="p-2 rounded hover:bg-white/10 transition-colors"+ style={{+ padding: '6px',+ borderRadius: '2px',+ backgroundColor: showFavorites ? `${FINCEPT.YELLOW}15` : 'transparent',+ border: 'none',+ cursor: 'pointer',+ transition: 'all 0.2s',+ }}title="Favorites">- {showFavorites ? <BookmarkCheck size={18} color={COLORS.YELLOW} /> : <Bookmark size={18} color={COLORS.MUTED} />}+ {showFavorites ? <BookmarkCheck size={16} color={FINCEPT.YELLOW} /> : <Bookmark size={16} color={FINCEPT.MUTED} />}</button><buttononClick={() => setShowHistory(!showHistory)}- className="p-2 rounded hover:bg-white/10 transition-colors"+ style={{+ padding: '6px',+ borderRadius: '2px',+ backgroundColor: showHistory ? `${FINCEPT.CYAN}15` : 'transparent',+ border: 'none',+ cursor: 'pointer',+ transition: 'all 0.2s',+ }}title="History">- <History size={18} color={showHistory ? COLORS.CYAN : COLORS.MUTED} />+ <History size={16} color={showHistory ? FINCEPT.CYAN : FINCEPT.MUTED} /></button></div></div>- <div className="flex flex-1 overflow-hidden">- {/* Left Panel - Data Sources */}- <div className="w-64 border-r flex flex-col" style={{ borderColor: COLORS.BORDER, background: COLORS.PANEL_BG }}>- <div className="p-3 border-b" style={{ borderColor: COLORS.BORDER }}>- <span className="text-xs font-medium" style={{ color: COLORS.MUTED }}>DATA SOURCES</span>- </div>- <div className="flex-1 overflow-y-auto">- {AKSHARE_DATA_SOURCES.map(source => {- const IconComponent = IconMap[source.icon] || Database;- const isSelected = selectedSource?.id === source.id;+ {/* Main Content Area */}+ <div style={{ display: 'flex', flex: 1, overflow: 'hidden' }}>+ {/* Left Panel - Data Sources (280px fixed) */}+ {!isSourcesPanelCollapsed && (+ <div style={{+ width: '280px',+ borderRight: `1px solid ${FINCEPT.BORDER}`,+ display: 'flex',+ flexDirection: 'column',+ backgroundColor: FINCEPT.PANEL_BG,+ }}>+ {/* Section Header */}+ <div style={{+ padding: '12px',+ backgroundColor: FINCEPT.HEADER_BG,+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ }}>+ <span style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, letterSpacing: '0.5px' }}>+ DATA SOURCES+ </span>+ <button+ onClick={() => setIsSourcesPanelCollapsed(true)}+ style={{+ padding: '4px',+ borderRadius: '2px',+ backgroundColor: 'transparent',+ border: 'none',+ cursor: 'pointer',+ }}+ title="Collapse panel"+ >+ <ChevronLeft size={14} color={FINCEPT.MUTED} />+ </button>+ </div>+ {/* Source List */}+ <div className="akshare-scrollbar" style={{ flex: 1, overflowY: 'auto' }}>+ {AKSHARE_DATA_SOURCES.map(source => {+ const IconComponent = IconMap[source.icon] || Database;+ const isSelected = selectedSource?.id === source.id;- return (- <button- key={source.id}- onClick={() => setSelectedSource(source)}- className="w-full px-3 py-3 flex items-start gap-3 hover:bg-white/5 transition-colors text-left"- style={{- background: isSelected ? COLORS.HOVER : 'transparent',- borderLeft: isSelected ? `2px solid ${source.color}` : '2px solid transparent'- }}- >- <IconComponent size={18} color={source.color} />- <div className="flex-1 min-w-0">- <div className="font-medium text-white text-sm">{source.name}</div>- <div className="text-xs mt-0.5 line-clamp-2" style={{ color: COLORS.MUTED }}>- {source.description}+ return (+ <button+ key={source.id}+ onClick={() => setSelectedSource(source)}+ style={{+ width: '100%',+ padding: '10px 12px',+ display: 'flex',+ alignItems: 'flex-start',+ gap: '10px',+ textAlign: 'left',+ backgroundColor: isSelected ? `${FINCEPT.ORANGE}15` : 'transparent',+ borderLeft: isSelected ? `2px solid ${FINCEPT.ORANGE}` : '2px solid transparent',+ border: 'none',+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ cursor: 'pointer',+ transition: 'all 0.2s',+ }}+ >+ <IconComponent size={16} color={isSelected ? FINCEPT.ORANGE : source.color} />+ <div style={{ flex: 1, minWidth: 0 }}>+ <div style={{+ fontWeight: 600,+ color: isSelected ? FINCEPT.WHITE : FINCEPT.WHITE,+ fontSize: '10px',+ }}>{source.name}</div>+ <div style={{+ fontSize: '9px',+ marginTop: '2px',+ color: FINCEPT.MUTED,+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ display: '-webkit-box',+ WebkitLineClamp: 2,+ WebkitBoxOrient: 'vertical' as any,+ }}>+ {source.description}+ </div></div>- </div>- </button>- );- })}+ </button>+ );+ })}+ </div></div>- </div>+ )}- {/* Middle Panel - Endpoints */}- <div className="w-80 border-r flex flex-col" style={{ borderColor: COLORS.BORDER, background: COLORS.PANEL_BG }}>- {selectedSource ? (- <>- <div className="p-3 border-b" style={{ borderColor: COLORS.BORDER }}>- <div className="relative">- <Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2" color={COLORS.MUTED} />- <input- type="text"- value={searchQuery}- onChange={e => setSearchQuery(e.target.value)}- placeholder="Search endpoints..."- className="w-full pl-9 pr-8 py-2 rounded text-sm"- style={{- background: COLORS.DARK_BG,- border: `1px solid ${COLORS.BORDER}`,- color: COLORS.WHITE- }}- />- {searchQuery && (+ {/* Collapsed Sources Panel Button */}+ {isSourcesPanelCollapsed && (+ <div style={{+ width: '36px',+ borderRight: `1px solid ${FINCEPT.BORDER}`,+ display: 'flex',+ flexDirection: 'column',+ backgroundColor: FINCEPT.PANEL_BG,+ }}>+ <button+ onClick={() => setIsSourcesPanelCollapsed(false)}+ style={{+ padding: '10px',+ backgroundColor: 'transparent',+ border: 'none',+ cursor: 'pointer',+ }}+ title="Expand Data Sources"+ >+ <ChevronRight size={14} color={FINCEPT.ORANGE} />+ </button>+ </div>+ )}++ {/* Middle Panel - Endpoints (300px fixed) */}+ {!isEndpointsPanelCollapsed && (+ <div style={{+ width: '300px',+ borderRight: `1px solid ${FINCEPT.BORDER}`,+ display: 'flex',+ flexDirection: 'column',+ backgroundColor: FINCEPT.PANEL_BG,+ }}>+ {selectedSource ? (+ <>+ {/* Section Header with Search */}+ <div style={{+ padding: '12px',+ backgroundColor: FINCEPT.HEADER_BG,+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ }}>+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '8px' }}>+ <span style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, letterSpacing: '0.5px' }}>+ ENDPOINTS+ </span><button- onClick={() => setSearchQuery('')}- className="absolute right-2 top-1/2 -translate-y-1/2"+ onClick={() => setIsEndpointsPanelCollapsed(true)}+ style={{+ padding: '4px',+ borderRadius: '2px',+ backgroundColor: 'transparent',+ border: 'none',+ cursor: 'pointer',+ }}+ title="Collapse panel">- <X size={14} color={COLORS.MUTED} />+ <ChevronLeft size={14} color={FINCEPT.MUTED} /></button>- )}- </div>- <div className="mt-2 text-xs" style={{ color: COLORS.MUTED }}>- {filteredEndpoints.length} endpoints available- </div>- </div>-- <div className="flex-1 overflow-y-auto">- {loadingEndpoints ? (- <div className="flex items-center justify-center py-8">- <RefreshCw size={20} className="animate-spin" color={COLORS.ORANGE} /></div>- ) : Object.keys(filteredCategories).length > 0 ? (- Object.entries(filteredCategories).map(([category, categoryEndpoints]) => (- <div key={category}>+ <div style={{ position: 'relative' }}>+ <Search size={14} style={{ position: 'absolute', left: '10px', top: '50%', transform: 'translateY(-50%)' }} color={FINCEPT.MUTED} />+ <input+ type="text"+ value={searchQuery}+ onChange={e => setSearchQuery(e.target.value)}+ placeholder="Search endpoints..."+ style={{+ width: '100%',+ padding: '8px 10px 8px 32px',+ backgroundColor: FINCEPT.DARK_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ color: FINCEPT.WHITE,+ fontSize: '10px',+ fontFamily: '"IBM Plex Mono", monospace',+ }}+ />+ {searchQuery && (<button- onClick={() => toggleCategory(category)}- className="w-full px-3 py-2 flex items-center gap-2 hover:bg-white/5 text-left"- style={{ borderBottom: `1px solid ${COLORS.BORDER}` }}+ onClick={() => setSearchQuery('')}+ style={{+ position: 'absolute',+ right: '8px',+ top: '50%',+ transform: 'translateY(-50%)',+ background: 'none',+ border: 'none',+ cursor: 'pointer',+ }}>- {expandedCategories.has(category) ? (- <ChevronDown size={14} color={COLORS.MUTED} />- ) : (- <ChevronRight size={14} color={COLORS.MUTED} />- )}- <span className="text-xs font-medium" style={{ color: COLORS.ORANGE }}>- {category}- </span>- <span className="text-xs ml-auto" style={{ color: COLORS.MUTED }}>- {categoryEndpoints.length}- </span>+ <X size={12} color={FINCEPT.MUTED} /></button>+ )}+ </div>+ </div>+ {/* Endpoint Count */}+ <div style={{ padding: '8px 12px', fontSize: '9px', color: FINCEPT.MUTED, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>+ {filteredEndpoints.length} endpoints available+ </div>- {expandedCategories.has(category) && (- <div className="py-1">- {categoryEndpoints.map(endpoint => {- const isActive = selectedEndpoint === endpoint;- const isFav = isFavorite(selectedSource.script, endpoint);+ {/* Endpoint List */}+ <div className="akshare-scrollbar" style={{ flex: 1, overflowY: 'auto' }}>+ {loadingEndpoints ? (+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '32px' }}>+ <RefreshCw size={18} className="animate-spin" color={FINCEPT.ORANGE} />+ </div>+ ) : Object.keys(filteredCategories).length > 0 ? (+ Object.entries(filteredCategories).map(([category, categoryEndpoints]) => (+ <div key={category}>+ <button+ onClick={() => toggleCategory(category)}+ style={{+ width: '100%',+ padding: '8px 12px',+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ textAlign: 'left',+ backgroundColor: FINCEPT.HEADER_BG,+ border: 'none',+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ cursor: 'pointer',+ }}+ >+ {expandedCategories.has(category) ? (+ <ChevronDown size={12} color={FINCEPT.MUTED} />+ ) : (+ <ChevronRight size={12} color={FINCEPT.MUTED} />+ )}+ <span style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.ORANGE, letterSpacing: '0.5px' }}>+ {category.toUpperCase()}+ </span>+ <span style={{ fontSize: '9px', marginLeft: 'auto', color: FINCEPT.MUTED }}>+ {categoryEndpoints.length}+ </span>+ </button>- return (- <div- key={endpoint}- className="flex items-center gap-1 px-2"- >- <button- onClick={() => executeQuery(selectedSource.script, endpoint)}- className="flex-1 px-3 py-1.5 text-left text-xs rounded hover:bg-white/5 transition-colors truncate"+ {expandedCategories.has(category) && (+ <div style={{ padding: '4px 0' }}>+ {categoryEndpoints.map(endpoint => {+ const isActive = selectedEndpoint === endpoint;+ const isFav = isFavorite(selectedSource.script, endpoint);++ return (+ <div+ key={endpoint}style={{- color: isActive ? COLORS.CYAN : COLORS.WHITE,- background: isActive ? COLORS.CYAN + '10' : 'transparent'+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ padding: '0 8px',}}>- {endpoint}- </button>- <button- onClick={() => toggleFavorite(selectedSource.script, endpoint)}- className="p-1 rounded hover:bg-white/10"- >- {isFav ? (- <BookmarkCheck size={12} color={COLORS.YELLOW} />- ) : (- <Bookmark size={12} color={COLORS.MUTED} />- )}- </button>- </div>- );- })}- </div>- )}+ <button+ onClick={() => executeQuery(selectedSource.script, endpoint)}+ style={{+ flex: 1,+ padding: '6px 10px',+ textAlign: 'left',+ fontSize: '10px',+ backgroundColor: isActive ? `${FINCEPT.ORANGE}15` : 'transparent',+ borderLeft: isActive ? `2px solid ${FINCEPT.ORANGE}` : '2px solid transparent',+ color: isActive ? FINCEPT.CYAN : FINCEPT.WHITE,+ border: 'none',+ borderRadius: '2px',+ cursor: 'pointer',+ transition: 'all 0.2s',+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ }}+ >+ {endpoint}+ </button>+ <button+ onClick={() => toggleFavorite(selectedSource.script, endpoint)}+ style={{+ padding: '4px',+ backgroundColor: 'transparent',+ border: 'none',+ borderRadius: '2px',+ cursor: 'pointer',+ }}+ >+ {isFav ? (+ <BookmarkCheck size={12} color={FINCEPT.YELLOW} />+ ) : (+ <Bookmark size={12} color={FINCEPT.MUTED} />+ )}+ </button>+ </div>+ );+ })}+ </div>+ )}+ </div>+ ))+ ) : (+ // Show flat list if no categories+ <div style={{ padding: '4px 0' }}>+ {filteredEndpoints.map(endpoint => {+ const isActive = selectedEndpoint === endpoint;+ const isFav = isFavorite(selectedSource.script, endpoint);++ return (+ <div key={endpoint} style={{ display: 'flex', alignItems: 'center', gap: '4px', padding: '0 8px' }}>+ <button+ onClick={() => executeQuery(selectedSource.script, endpoint)}+ style={{+ flex: 1,+ padding: '6px 10px',+ textAlign: 'left',+ fontSize: '10px',+ backgroundColor: isActive ? `${FINCEPT.ORANGE}15` : 'transparent',+ borderLeft: isActive ? `2px solid ${FINCEPT.ORANGE}` : '2px solid transparent',+ color: isActive ? FINCEPT.CYAN : FINCEPT.WHITE,+ border: 'none',+ borderRadius: '2px',+ cursor: 'pointer',+ transition: 'all 0.2s',+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ }}+ >+ {endpoint}+ </button>+ <button+ onClick={() => toggleFavorite(selectedSource.script, endpoint)}+ style={{+ padding: '4px',+ backgroundColor: 'transparent',+ border: 'none',+ borderRadius: '2px',+ cursor: 'pointer',+ }}+ >+ {isFav ? (+ <BookmarkCheck size={12} color={FINCEPT.YELLOW} />+ ) : (+ <Bookmark size={12} color={FINCEPT.MUTED} />+ )}+ </button>+ </div>+ );+ })}</div>- ))- ) : (- // Show flat list if no categories- <div className="py-1">- {filteredEndpoints.map(endpoint => {- const isActive = selectedEndpoint === endpoint;- const isFav = isFavorite(selectedSource.script, endpoint);-- return (- <div key={endpoint} className="flex items-center gap-1 px-2">- <button- onClick={() => executeQuery(selectedSource.script, endpoint)}- className="flex-1 px-3 py-1.5 text-left text-xs rounded hover:bg-white/5 transition-colors truncate"- style={{- color: isActive ? COLORS.CYAN : COLORS.WHITE,- background: isActive ? COLORS.CYAN + '10' : 'transparent'- }}- >- {endpoint}- </button>- <button- onClick={() => toggleFavorite(selectedSource.script, endpoint)}- className="p-1 rounded hover:bg-white/10"- >- {isFav ? (- <BookmarkCheck size={12} color={COLORS.YELLOW} />- ) : (- <Bookmark size={12} color={COLORS.MUTED} />- )}- </button>- </div>- );- })}+ )}+ </div>+ </>+ ) : (+ <div style={{+ flex: 1,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ padding: '16px',+ }}>+ <div style={{ textAlign: 'center' }}>+ <Database size={24} color={FINCEPT.MUTED} style={{ marginBottom: '12px' }} />+ <div style={{ fontSize: '10px', color: FINCEPT.MUTED }}>+ Select a data source to browse endpoints</div>- )}- </div>- </>- ) : (- <div className="flex-1 flex items-center justify-center p-4">- <div className="text-center">- <Database size={32} color={COLORS.MUTED} className="mx-auto mb-3" />- <div className="text-sm" style={{ color: COLORS.MUTED }}>- Select a data source to browse endpoints</div></div>- </div>- )}- </div>+ )}+ </div>+ )}- {/* Right Panel - Data Display */}- <div className="flex-1 flex flex-col overflow-hidden">+ {/* Collapsed Endpoints Panel Button */}+ {isEndpointsPanelCollapsed && (+ <div style={{+ width: '36px',+ borderRight: `1px solid ${FINCEPT.BORDER}`,+ display: 'flex',+ flexDirection: 'column',+ backgroundColor: FINCEPT.PANEL_BG,+ }}>+ <button+ onClick={() => setIsEndpointsPanelCollapsed(false)}+ style={{+ padding: '10px',+ backgroundColor: 'transparent',+ border: 'none',+ cursor: 'pointer',+ }}+ title="Expand Endpoints"+ >+ <ChevronRight size={14} color={FINCEPT.ORANGE} />+ </button>+ </div>+ )}++ {/* Right Panel - Data Display (flex: 1) */}+ <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>{/* Toolbar */}- <div className="flex items-center justify-between px-4 py-2 border-b" style={{ borderColor: COLORS.BORDER }}>- <div className="flex items-center gap-4">+ <div style={{+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ padding: '8px 16px',+ backgroundColor: FINCEPT.HEADER_BG,+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>+ {/* Panel Toggle Buttons */}+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>+ <button+ onClick={() => setIsSourcesPanelCollapsed(!isSourcesPanelCollapsed)}+ style={{+ padding: '6px',+ borderRadius: '2px',+ backgroundColor: 'transparent',+ border: 'none',+ cursor: 'pointer',+ }}+ title={isSourcesPanelCollapsed ? "Show Data Sources" : "Hide Data Sources"}+ >+ {isSourcesPanelCollapsed ? (+ <PanelLeftOpen size={14} color={FINCEPT.ORANGE} />+ ) : (+ <PanelLeftClose size={14} color={FINCEPT.MUTED} />+ )}+ </button>+ <button+ onClick={() => setIsEndpointsPanelCollapsed(!isEndpointsPanelCollapsed)}+ style={{+ padding: '6px',+ borderRadius: '2px',+ backgroundColor: 'transparent',+ border: 'none',+ cursor: 'pointer',+ }}+ title={isEndpointsPanelCollapsed ? "Show Endpoints" : "Hide Endpoints"}+ >+ {isEndpointsPanelCollapsed ? (+ <PanelLeftOpen size={14} color={FINCEPT.ORANGE} />+ ) : (+ <PanelLeftClose size={14} color={FINCEPT.MUTED} />+ )}+ </button>+ </div>++ {/* Separator */}+ {selectedEndpoint && (+ <div style={{ width: '1px', height: '20px', backgroundColor: FINCEPT.BORDER }} />+ )}+{selectedEndpoint && (<>- <span className="font-mono text-sm" style={{ color: COLORS.CYAN }}>+ <span style={{ fontFamily: '"IBM Plex Mono", monospace', fontSize: '10px', color: FINCEPT.CYAN }}>{selectedEndpoint}</span>{responseInfo && (- <span className="text-xs" style={{ color: COLORS.MUTED }}>- {responseInfo.count} records+ <span style={{+ fontSize: '9px',+ padding: '2px 6px',+ backgroundColor: `${FINCEPT.GREEN}20`,+ color: FINCEPT.GREEN,+ borderRadius: '2px',+ }}>+ {responseInfo.count} RECORDS</span>)}</>)}</div>- <div className="flex items-center gap-2">+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>{/* View Mode Toggle */}- <div className="flex items-center rounded overflow-hidden" style={{ border: `1px solid ${COLORS.BORDER}` }}>+ <div style={{ display: 'flex', alignItems: 'center', border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '2px', overflow: 'hidden' }}><buttononClick={() => setViewMode('table')}- className="px-2 py-1 flex items-center gap-1"style={{- background: viewMode === 'table' ? COLORS.HOVER : 'transparent',- color: viewMode === 'table' ? COLORS.WHITE : COLORS.MUTED+ padding: '6px 10px',+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ backgroundColor: viewMode === 'table' ? FINCEPT.ORANGE : 'transparent',+ color: viewMode === 'table' ? FINCEPT.DARK_BG : FINCEPT.MUTED,+ border: 'none',+ fontSize: '9px',+ fontWeight: 700,+ cursor: 'pointer',}}>- <Table size={14} />- <span className="text-xs">Table</span>+ <Table size={12} />+ TABLE</button><buttononClick={() => setViewMode('json')}- className="px-2 py-1 flex items-center gap-1"style={{- background: viewMode === 'json' ? COLORS.HOVER : 'transparent',- color: viewMode === 'json' ? COLORS.WHITE : COLORS.MUTED+ padding: '6px 10px',+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ backgroundColor: viewMode === 'json' ? FINCEPT.ORANGE : 'transparent',+ color: viewMode === 'json' ? FINCEPT.DARK_BG : FINCEPT.MUTED,+ border: 'none',+ fontSize: '9px',+ fontWeight: 700,+ cursor: 'pointer',}}>- <Code size={14} />- <span className="text-xs">JSON</span>+ <Code size={12} />+ JSON</button></div>@@ -576,17 +1068,29 @@ const AkShareDataTab: React.FC = () => {<><buttononClick={downloadCSV}- className="p-2 rounded hover:bg-white/10 transition-colors"+ style={{+ padding: '6px',+ borderRadius: '2px',+ backgroundColor: 'transparent',+ border: `1px solid ${FINCEPT.BORDER}`,+ cursor: 'pointer',+ }}title="Download CSV">- <Download size={16} color={COLORS.MUTED} />+ <Download size={14} color={FINCEPT.MUTED} /></button><buttononClick={() => copyToClipboard(JSON.stringify(data, null, 2))}- className="p-2 rounded hover:bg-white/10 transition-colors"- title="Copy JSON"+ style={{+ padding: '6px',+ borderRadius: '2px',+ backgroundColor: 'transparent',+ border: `1px solid ${FINCEPT.BORDER}`,+ cursor: 'pointer',+ }}+ title="Copy JSON (All Data)">- <Copy size={16} color={COLORS.MUTED} />+ <Copy size={14} color={FINCEPT.MUTED} /></button></>)}@@ -595,46 +1099,65 @@ const AkShareDataTab: React.FC = () => {<buttononClick={() => executeQuery(selectedSource.script, selectedEndpoint)}disabled={loading}- className="px-3 py-1.5 rounded flex items-center gap-2 text-sm font-medium"- style={{ background: COLORS.ORANGE, color: COLORS.WHITE }}+ style={{+ padding: '8px 16px',+ borderRadius: '2px',+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ backgroundColor: FINCEPT.ORANGE,+ color: FINCEPT.DARK_BG,+ border: 'none',+ fontSize: '9px',+ fontWeight: 700,+ cursor: loading ? 'not-allowed' : 'pointer',+ opacity: loading ? 0.7 : 1,+ }}>- <RefreshCw size={14} className={loading ? 'animate-spin' : ''} />- Refresh+ <RefreshCw size={12} className={loading ? 'animate-spin' : ''} />+ REFRESH</button>)}</div></div>{/* Data Content */}- <div className="flex-1 overflow-auto p-4">- {loading ? (- <div className="flex items-center justify-center h-full">- <div className="text-center">- <RefreshCw size={32} className="animate-spin mx-auto mb-3" color={COLORS.ORANGE} />- <div className="text-sm" style={{ color: COLORS.MUTED }}>Loading data...</div>+ <div className="akshare-scrollbar" style={{ flex: 1, overflowX: 'auto', overflowY: 'auto', padding: '16px' }}>+ {loading || translating ? (+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: '100%' }}>+ <div style={{ textAlign: 'center' }}>+ <RefreshCw size={28} className="animate-spin" color={FINCEPT.ORANGE} style={{ marginBottom: '12px' }} />+ <div style={{ fontSize: '10px', color: FINCEPT.MUTED }}>+ {translating ? 'Translating data...' : 'Loading data...'}+ </div></div></div>) : error ? (- <div className="flex items-center justify-center h-full">- <div className="text-center max-w-md">- <AlertCircle size={32} color={COLORS.RED} className="mx-auto mb-3" />- <div className="text-sm font-medium text-white mb-2">Query Failed</div>- <div className="text-xs p-3 rounded font-mono" style={{ background: COLORS.RED + '20', color: COLORS.RED }}>+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: '100%' }}>+ <div style={{ textAlign: 'center', maxWidth: '400px' }}>+ <AlertCircle size={28} color={FINCEPT.RED} style={{ marginBottom: '12px' }} />+ <div style={{ fontSize: '11px', fontWeight: 600, color: FINCEPT.WHITE, marginBottom: '8px' }}>Query Failed</div>+ <div style={{+ fontSize: '10px',+ padding: '12px',+ borderRadius: '2px',+ fontFamily: '"IBM Plex Mono", monospace',+ backgroundColor: `${FINCEPT.RED}20`,+ color: FINCEPT.RED,+ }}>{error}</div></div></div>) : data && data.length > 0 ? (viewMode === 'table' ? (- <div className="overflow-auto">- <table className="w-full text-xs">- <thead>- <tr style={{ background: COLORS.HEADER_BG }}>+ <div style={{ width: '100%', height: '100%', overflow: 'auto' }}>+ <table style={{ minWidth: '100%', fontSize: '10px', borderCollapse: 'collapse' }}>+ <thead style={{ position: 'sticky', top: 0, zIndex: 10 }}>+ <tr style={{ backgroundColor: FINCEPT.HEADER_BG }}>{columns.map(col => (<thkey={col}- className="px-3 py-2 text-left font-medium cursor-pointer hover:bg-white/5"- style={{ color: COLORS.MUTED, borderBottom: `1px solid ${COLORS.BORDER}` }}onClick={() => {if (sortColumn === col) {setSortDirection(sortDirection === 'asc' ? 'desc' : 'asc');@@ -643,11 +1166,25 @@ const AkShareDataTab: React.FC = () => {setSortDirection('asc');}}}+ style={{+ padding: '10px 16px',+ textAlign: 'left',+ fontWeight: 700,+ fontSize: '9px',+ letterSpacing: '0.5px',+ color: FINCEPT.GRAY,+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ minWidth: '120px',+ whiteSpace: 'nowrap',+ cursor: 'pointer',+ }}>- <div className="flex items-center gap-1">- <span className="truncate max-w-[150px]" title={col}>{col}</span>+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>+ <span title={col}>+ {(translatedColumns[col] || col).toUpperCase()}+ </span>{sortColumn === col && (- <ArrowUpDown size={12} color={COLORS.ORANGE} />+ <ArrowUpDown size={10} color={FINCEPT.ORANGE} />)}</div></th>@@ -655,8 +1192,12 @@ const AkShareDataTab: React.FC = () => {</tr></thead><tbody>- {(sortedData || data).slice(0, 500).map((row, idx) => (- <tr key={idx} className="hover:bg-white/5" style={{ borderBottom: `1px solid ${COLORS.BORDER}` }}>+ {(sortedData || []).map((row, idx) => (+ <tr+ key={idx}+ className="akshare-hover-row"+ style={{ borderBottom: `1px solid ${FINCEPT.BORDER}` }}+ >{columns.map(col => {const value = row[col];const isNumber = typeof value === 'number';@@ -665,14 +1206,17 @@ const AkShareDataTab: React.FC = () => {return (<tdkey={col}- className="px-3 py-2"style={{- color: isNegative ? COLORS.RED : isNumber ? COLORS.GREEN : COLORS.WHITE+ padding: '8px 16px',+ whiteSpace: 'normal',+ color: isNegative ? FINCEPT.RED : isNumber ? FINCEPT.CYAN : FINCEPT.WHITE,+ maxWidth: '400px',+ fontSize: '10px',}}>- <span className="truncate block max-w-[200px]" title={String(value)}>+ <div style={{ wordBreak: 'break-word' }} title={String(value)}>{isNumber ? value.toLocaleString() : String(value ?? '-')}- </span>+ </div></td>);})}@@ -680,67 +1224,272 @@ const AkShareDataTab: React.FC = () => {))}</tbody></table>- {data.length > 500 && (- <div className="text-center py-4 text-xs" style={{ color: COLORS.MUTED }}>- Showing first 500 of {data.length} records++ {/* Pagination Controls */}+ {data && data.length > 0 && (+ <div style={{+ position: 'sticky',+ bottom: 0,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ padding: '10px 16px',+ borderTop: `1px solid ${FINCEPT.BORDER}`,+ backgroundColor: FINCEPT.HEADER_BG,+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>+ <span style={{ fontSize: '9px', color: FINCEPT.MUTED }}>+ Showing {((currentPage - 1) * pageSize) + 1} to {Math.min(currentPage * pageSize, data.length)} of {data.length} rows+ </span>+ <select+ value={pageSize}+ onChange={(e) => {+ setPageSize(Number(e.target.value));+ setCurrentPage(1);+ setTranslatedPages(new Map());+ }}+ style={{+ padding: '4px 8px',+ borderRadius: '2px',+ fontSize: '9px',+ backgroundColor: FINCEPT.DARK_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ color: FINCEPT.WHITE,+ }}+ >+ <option value={10}>10 rows</option>+ <option value={25}>25 rows</option>+ <option value={50}>50 rows</option>+ <option value={100}>100 rows</option>+ </select>+ </div>++ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>+ <button+ onClick={() => setCurrentPage(1)}+ disabled={currentPage === 1}+ style={{+ padding: '4px 10px',+ borderRadius: '2px',+ fontSize: '9px',+ fontWeight: 700,+ backgroundColor: currentPage === 1 ? FINCEPT.MUTED : 'transparent',+ color: currentPage === 1 ? FINCEPT.DARK_BG : FINCEPT.GRAY,+ border: `1px solid ${currentPage === 1 ? FINCEPT.MUTED : FINCEPT.BORDER}`,+ opacity: currentPage === 1 ? 0.5 : 1,+ cursor: currentPage === 1 ? 'not-allowed' : 'pointer',+ }}+ >+ FIRST+ </button>+ <button+ onClick={() => setCurrentPage(currentPage - 1)}+ disabled={currentPage === 1}+ style={{+ padding: '4px 10px',+ borderRadius: '2px',+ fontSize: '9px',+ fontWeight: 700,+ backgroundColor: currentPage === 1 ? FINCEPT.MUTED : 'transparent',+ color: currentPage === 1 ? FINCEPT.DARK_BG : FINCEPT.GRAY,+ border: `1px solid ${currentPage === 1 ? FINCEPT.MUTED : FINCEPT.BORDER}`,+ opacity: currentPage === 1 ? 0.5 : 1,+ cursor: currentPage === 1 ? 'not-allowed' : 'pointer',+ }}+ >+ PREV+ </button>+ <span style={{ fontSize: '9px', padding: '0 12px', color: FINCEPT.WHITE }}>+ Page <span style={{ color: FINCEPT.CYAN }}>{currentPage}</span> of {totalPages}+ </span>+ <button+ onClick={() => setCurrentPage(currentPage + 1)}+ disabled={currentPage === totalPages}+ style={{+ padding: '4px 10px',+ borderRadius: '2px',+ fontSize: '9px',+ fontWeight: 700,+ backgroundColor: currentPage === totalPages ? FINCEPT.MUTED : 'transparent',+ color: currentPage === totalPages ? FINCEPT.DARK_BG : FINCEPT.GRAY,+ border: `1px solid ${currentPage === totalPages ? FINCEPT.MUTED : FINCEPT.BORDER}`,+ opacity: currentPage === totalPages ? 0.5 : 1,+ cursor: currentPage === totalPages ? 'not-allowed' : 'pointer',+ }}+ >+ NEXT+ </button>+ <button+ onClick={() => setCurrentPage(totalPages)}+ disabled={currentPage === totalPages}+ style={{+ padding: '4px 10px',+ borderRadius: '2px',+ fontSize: '9px',+ fontWeight: 700,+ backgroundColor: currentPage === totalPages ? FINCEPT.MUTED : 'transparent',+ color: currentPage === totalPages ? FINCEPT.DARK_BG : FINCEPT.GRAY,+ border: `1px solid ${currentPage === totalPages ? FINCEPT.MUTED : FINCEPT.BORDER}`,+ opacity: currentPage === totalPages ? 0.5 : 1,+ cursor: currentPage === totalPages ? 'not-allowed' : 'pointer',+ }}+ >+ LAST+ </button>+ </div></div>)}</div>) : (- <pre- className="text-xs font-mono p-4 rounded overflow-auto"- style={{ background: COLORS.HEADER_BG, color: COLORS.WHITE }}- >- {JSON.stringify(data.slice(0, 100), null, 2)}- {data.length > 100 && `\n\n... and ${data.length - 100} more records`}- </pre>+ <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>+ <pre+ style={{+ flex: 1,+ fontSize: '10px',+ fontFamily: '"IBM Plex Mono", monospace',+ padding: '16px',+ borderRadius: '2px',+ overflow: 'auto',+ backgroundColor: FINCEPT.HEADER_BG,+ color: FINCEPT.WHITE,+ }}+ >+ {JSON.stringify(paginatedData, null, 2)}+ </pre>++ {/* Pagination Controls for JSON view */}+ {data && data.length > 0 && (+ <div style={{+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ padding: '10px 16px',+ borderTop: `1px solid ${FINCEPT.BORDER}`,+ backgroundColor: FINCEPT.HEADER_BG,+ }}>+ <span style={{ fontSize: '9px', color: FINCEPT.MUTED }}>+ Showing page {currentPage} of {totalPages}+ </span>+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>+ <button+ onClick={() => setCurrentPage(Math.max(1, currentPage - 1))}+ disabled={currentPage === 1}+ style={{+ padding: '4px 12px',+ borderRadius: '2px',+ fontSize: '9px',+ fontWeight: 700,+ backgroundColor: currentPage === 1 ? FINCEPT.MUTED : 'transparent',+ color: currentPage === 1 ? FINCEPT.DARK_BG : FINCEPT.GRAY,+ border: `1px solid ${currentPage === 1 ? FINCEPT.MUTED : FINCEPT.BORDER}`,+ opacity: currentPage === 1 ? 0.5 : 1,+ cursor: currentPage === 1 ? 'not-allowed' : 'pointer',+ }}+ >+ PREV+ </button>+ <button+ onClick={() => setCurrentPage(Math.min(totalPages, currentPage + 1))}+ disabled={currentPage === totalPages}+ style={{+ padding: '4px 12px',+ borderRadius: '2px',+ fontSize: '9px',+ fontWeight: 700,+ backgroundColor: currentPage === totalPages ? FINCEPT.MUTED : 'transparent',+ color: currentPage === totalPages ? FINCEPT.DARK_BG : FINCEPT.GRAY,+ border: `1px solid ${currentPage === totalPages ? FINCEPT.MUTED : FINCEPT.BORDER}`,+ opacity: currentPage === totalPages ? 0.5 : 1,+ cursor: currentPage === totalPages ? 'not-allowed' : 'pointer',+ }}+ >+ NEXT+ </button>+ </div>+ </div>+ )}+ </div>)) : !selectedEndpoint ? (- <div className="flex items-center justify-center h-full">- <div className="text-center max-w-lg">- <Zap size={48} color={COLORS.ORANGE} className="mx-auto mb-4" />- <div className="text-xl font-semibold text-white mb-2">AKShare Data Explorer</div>- <div className="text-sm mb-6" style={{ color: COLORS.MUTED }}>+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: '100%' }}>+ <div style={{ textAlign: 'center', maxWidth: '500px' }}>+ <Zap size={40} color={FINCEPT.ORANGE} style={{ marginBottom: '16px' }} />+ <div style={{ fontSize: '14px', fontWeight: 700, color: FINCEPT.WHITE, marginBottom: '8px' }}>+ AKSHARE DATA EXPLORER+ </div>+ <div style={{ fontSize: '10px', marginBottom: '24px', color: FINCEPT.MUTED }}>Access 400+ financial data endpoints covering bonds, derivatives, economics, funds, and alternative data from Chinese and global markets.</div>- <div className="grid grid-cols-3 gap-3 text-xs">+ <div style={{+ display: 'grid',+ gridTemplateColumns: 'repeat(3, 1fr)',+ gap: '12px',+ }}>{AKSHARE_DATA_SOURCES.slice(0, 6).map(source => (<buttonkey={source.id}onClick={() => setSelectedSource(source)}- className="p-3 rounded text-left hover:bg-white/5 transition-colors"- style={{ border: `1px solid ${COLORS.BORDER}` }}+ style={{+ padding: '12px',+ borderRadius: '2px',+ textAlign: 'left',+ backgroundColor: 'transparent',+ border: `1px solid ${FINCEPT.BORDER}`,+ cursor: 'pointer',+ transition: 'all 0.2s',+ }}>- <div className="font-medium text-white">{source.name}</div>- <div style={{ color: COLORS.MUTED }}>{source.categories.length} categories</div>+ <div style={{ fontWeight: 600, color: FINCEPT.WHITE, fontSize: '10px' }}>{source.name}</div>+ <div style={{ color: FINCEPT.MUTED, fontSize: '9px', marginTop: '4px' }}>{source.categories.length} categories</div></button>))}</div></div></div>) : (- <div className="flex items-center justify-center h-full">- <div className="text-center">- <CheckCircle2 size={32} color={COLORS.GREEN} className="mx-auto mb-3" />- <div className="text-sm" style={{ color: COLORS.MUTED }}>No data returned</div>+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: '100%' }}>+ <div style={{ textAlign: 'center' }}>+ <CheckCircle2 size={28} color={FINCEPT.GREEN} style={{ marginBottom: '12px' }} />+ <div style={{ fontSize: '10px', color: FINCEPT.MUTED }}>No data returned</div></div></div>)}</div></div>- {/* Favorites Panel */}+ {/* Favorites Panel (Right side panel - 280px) */}{showFavorites && (- <div className="w-64 border-l flex flex-col" style={{ borderColor: COLORS.BORDER, background: COLORS.PANEL_BG }}>- <div className="p-3 border-b flex items-center justify-between" style={{ borderColor: COLORS.BORDER }}>- <span className="text-xs font-medium" style={{ color: COLORS.YELLOW }}>FAVORITES</span>- <button onClick={() => setShowFavorites(false)}>- <X size={14} color={COLORS.MUTED} />+ <div style={{+ width: '280px',+ borderLeft: `1px solid ${FINCEPT.BORDER}`,+ display: 'flex',+ flexDirection: 'column',+ backgroundColor: FINCEPT.PANEL_BG,+ }}>+ <div style={{+ padding: '12px',+ backgroundColor: FINCEPT.HEADER_BG,+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ }}>+ <span style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.YELLOW, letterSpacing: '0.5px' }}>FAVORITES</span>+ <button+ onClick={() => setShowFavorites(false)}+ style={{+ padding: '4px',+ backgroundColor: 'transparent',+ border: 'none',+ cursor: 'pointer',+ }}+ >+ <X size={14} color={FINCEPT.MUTED} /></button></div>- <div className="flex-1 overflow-y-auto">+ <div className="akshare-scrollbar" style={{ flex: 1, overflowY: 'auto' }}>{favorites.length === 0 ? (- <div className="p-4 text-center text-xs" style={{ color: COLORS.MUTED }}>+ <div style={{ padding: '16px', textAlign: 'center', fontSize: '10px', color: FINCEPT.MUTED }}>No favorites yet. Click the bookmark icon on any endpoint to add it here.</div>) : (@@ -754,11 +1503,20 @@ const AkShareDataTab: React.FC = () => {executeQuery(fav.script, fav.endpoint);}}}- className="w-full px-3 py-2 text-left text-xs hover:bg-white/5 border-b"- style={{ borderColor: COLORS.BORDER }}+ style={{+ width: '100%',+ padding: '10px 12px',+ textAlign: 'left',+ fontSize: '10px',+ backgroundColor: 'transparent',+ border: 'none',+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ cursor: 'pointer',+ transition: 'all 0.2s',+ }}>- <div className="text-white truncate">{fav.endpoint}</div>- <div style={{ color: COLORS.MUTED }}>{fav.script.replace('akshare_', '').replace('.py', '')}</div>+ <div style={{ color: FINCEPT.WHITE, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{fav.endpoint}</div>+ <div style={{ color: FINCEPT.MUTED, fontSize: '9px', marginTop: '2px' }}>{fav.script.replace('akshare_', '').replace('.py', '')}</div></button>)))}@@ -766,18 +1524,39 @@ const AkShareDataTab: React.FC = () => {</div>)}- {/* History Panel */}+ {/* History Panel (Right side panel - 280px) */}{showHistory && (- <div className="w-64 border-l flex flex-col" style={{ borderColor: COLORS.BORDER, background: COLORS.PANEL_BG }}>- <div className="p-3 border-b flex items-center justify-between" style={{ borderColor: COLORS.BORDER }}>- <span className="text-xs font-medium" style={{ color: COLORS.CYAN }}>QUERY HISTORY</span>- <button onClick={() => setShowHistory(false)}>- <X size={14} color={COLORS.MUTED} />+ <div style={{+ width: '280px',+ borderLeft: `1px solid ${FINCEPT.BORDER}`,+ display: 'flex',+ flexDirection: 'column',+ backgroundColor: FINCEPT.PANEL_BG,+ }}>+ <div style={{+ padding: '12px',+ backgroundColor: FINCEPT.HEADER_BG,+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ }}>+ <span style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.CYAN, letterSpacing: '0.5px' }}>QUERY HISTORY</span>+ <button+ onClick={() => setShowHistory(false)}+ style={{+ padding: '4px',+ backgroundColor: 'transparent',+ border: 'none',+ cursor: 'pointer',+ }}+ >+ <X size={14} color={FINCEPT.MUTED} /></button></div>- <div className="flex-1 overflow-y-auto">+ <div className="akshare-scrollbar" style={{ flex: 1, overflowY: 'auto' }}>{queryHistory.length === 0 ? (- <div className="p-4 text-center text-xs" style={{ color: COLORS.MUTED }}>+ <div style={{ padding: '16px', textAlign: 'center', fontSize: '10px', color: FINCEPT.MUTED }}>No queries yet</div>) : (@@ -791,18 +1570,27 @@ const AkShareDataTab: React.FC = () => {executeQuery(item.script, item.endpoint);}}}- className="w-full px-3 py-2 text-left text-xs hover:bg-white/5 border-b"- style={{ borderColor: COLORS.BORDER }}+ style={{+ width: '100%',+ padding: '10px 12px',+ textAlign: 'left',+ fontSize: '10px',+ backgroundColor: 'transparent',+ border: 'none',+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ cursor: 'pointer',+ transition: 'all 0.2s',+ }}>- <div className="flex items-center gap-2">+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>{item.success ? (- <CheckCircle2 size={10} color={COLORS.GREEN} />+ <CheckCircle2 size={10} color={FINCEPT.GREEN} />) : (- <AlertCircle size={10} color={COLORS.RED} />+ <AlertCircle size={10} color={FINCEPT.RED} />)}- <span className="text-white truncate">{item.endpoint}</span>+ <span style={{ color: FINCEPT.WHITE, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{item.endpoint}</span></div>- <div className="flex items-center justify-between mt-1" style={{ color: COLORS.MUTED }}>+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: '4px', color: FINCEPT.MUTED, fontSize: '9px' }}><span>{new Date(item.timestamp).toLocaleTimeString()}</span>{item.count !== undefined && <span>{item.count} rows</span>}</div>@@ -814,7 +1602,42 @@ const AkShareDataTab: React.FC = () => {)}</div>- <TabFooter tabName="AKShare Data" />+ {/* Status Bar */}+ <div style={{+ backgroundColor: FINCEPT.HEADER_BG,+ borderTop: `1px solid ${FINCEPT.BORDER}`,+ padding: '4px 16px',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ fontSize: '9px',+ color: FINCEPT.GRAY,+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>+ <span>+ MODE: <span style={{ color: FINCEPT.ORANGE }}>DATA EXPLORER</span>+ </span>+ <span>+ SOURCE: <span style={{ color: selectedSource ? FINCEPT.CYAN : FINCEPT.MUTED }}>{selectedSource?.name || 'NONE'}</span>+ </span>+ <span>+ ENDPOINT: <span style={{ color: selectedEndpoint ? FINCEPT.CYAN : FINCEPT.MUTED }}>{selectedEndpoint || 'NONE'}</span>+ </span>+ </div>+ <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>+ <span>+ FAVORITES: <span style={{ color: FINCEPT.YELLOW }}>{favorites.length}</span>+ </span>+ <span>+ HISTORY: <span style={{ color: FINCEPT.CYAN }}>{queryHistory.length}</span>+ </span>+ {data && (+ <span>+ RECORDS: <span style={{ color: FINCEPT.GREEN }}>{data.length}</span>+ </span>+ )}+ </div>+ </div></div>);};diff --git a/fincept-terminal-desktop/src/components/tabs/equity-research/components/FinancialAnalysisPanel.tsx b/fincept-terminal-desktop/src/components/tabs/equity-research/components/FinancialAnalysisPanel.tsxindex 18571a820..bb66d86dc 100644--- a/fincept-terminal-desktop/src/components/tabs/equity-research/components/FinancialAnalysisPanel.tsx+++ b/fincept-terminal-desktop/src/components/tabs/equity-research/components/FinancialAnalysisPanel.tsx@@ -2,6 +2,7 @@import React, { useState, useCallback } from 'react';import { invoke } from '@tauri-apps/api/core';import { AlertCircle, CheckCircle, BarChart3, DollarSign, PieChart, Activity, FileText, ChevronDown, ChevronUp, Loader2 } from 'lucide-react';+import type { StockInfo } from '../types';// Fincept color constantsconst COLORS = {@@ -19,8 +20,40 @@ const COLORS = {HOVER: '#1F1F1F',};-interface FinancialsInput { revenue?: number; net_income?: number; total_assets?: number; operating_cash_flow?: number; }-interface FinancialDataInput { company: { ticker: string; name: string; sector?: string; country?: string }; period: { period_end: string; fiscal_year: number }; financials: FinancialsInput; }+interface FinancialsInput {+ // Income Statement+ revenue?: number;+ cost_of_sales?: number;+ gross_profit?: number;+ operating_income?: number;+ net_income?: number;+ interest_expense?: number;+ basic_eps?: number;+ diluted_eps?: number;+ // Balance Sheet - Assets+ total_assets?: number;+ current_assets?: number;+ cash_equivalents?: number;+ accounts_receivable?: number;+ inventory?: number;+ // Balance Sheet - Liabilities+ total_liabilities?: number;+ current_liabilities?: number;+ long_term_debt?: number;+ short_term_debt?: number;+ // Balance Sheet - Equity+ total_equity?: number;+ // Cash Flow+ operating_cash_flow?: number;+ capex?: number;+}++interface FinancialDataInput {+ company: { ticker: string; name: string; sector?: string; industry?: string; country?: string };+ period: { period_end: string; fiscal_year: number; period_type?: string; fiscal_period?: string };+ financials: FinancialsInput;+}+interface AnalysisResult { success: boolean; metrics?: Record<string, any>; summary?: string; error?: string; results?: any[]; }type AnalysisType = 'income' | 'balance' | 'cashflow' | 'comprehensive' | 'metrics';@@ -32,7 +65,17 @@ const ANALYSIS_TYPES = [{ type: 'metrics' as AnalysisType, label: 'Metrics', icon: BarChart3 },];-export const FinancialAnalysisPanel: React.FC<{ ticker?: string; companyName?: string; }> = ({ ticker = 'AAPL', companyName = 'Apple Inc.' }) => {+interface FinancialAnalysisPanelProps {+ ticker?: string;+ companyName?: string;+ stockInfo?: StockInfo | null;+}++export const FinancialAnalysisPanel: React.FC<FinancialAnalysisPanelProps> = ({+ ticker = 'AAPL',+ companyName = 'Apple Inc.',+ stockInfo+}) => {const [selected, setSelected] = useState<AnalysisType>('comprehensive');const [loading, setLoading] = useState(false);const [result, setResult] = useState<AnalysisResult | null>(null);@@ -48,13 +91,74 @@ export const FinancialAnalysisPanel: React.FC<{ ticker?: string; companyName?: scomprehensive: 'analyze_financial_statements',metrics: 'get_financial_key_metrics'};- const res = await invoke<string>(cmds[selected], {- data: {- company: { ticker, name: companyName },- period: { period_end: new Date().toISOString().split('T')[0], fiscal_year: new Date().getFullYear() },- financials: {}++ // Build financials object from stockInfo if available+ const financials: FinancialsInput = {};+ if (stockInfo) {+ // Income statement related+ if (stockInfo.total_revenue !== null) financials.revenue = stockInfo.total_revenue;+ if (stockInfo.gross_profits !== null) {+ // Calculate cost_of_sales from revenue and gross profits+ if (stockInfo.total_revenue !== null) {+ financials.cost_of_sales = stockInfo.total_revenue - stockInfo.gross_profits;+ }+ }+ // Use operating margin to estimate operating income+ if (stockInfo.operating_margins !== null && stockInfo.total_revenue !== null) {+ financials.operating_income = stockInfo.total_revenue * stockInfo.operating_margins;+ }+ // Net income from profit margin+ if (stockInfo.profit_margins !== null && stockInfo.total_revenue !== null) {+ financials.net_income = stockInfo.total_revenue * stockInfo.profit_margins;+ }++ // Balance sheet related+ if (stockInfo.total_cash !== null) financials.cash_equivalents = stockInfo.total_cash;+ if (stockInfo.total_debt !== null) {+ financials.long_term_debt = stockInfo.total_debt;+ // Use total_debt as an approximation for total_liabilities+ financials.total_liabilities = stockInfo.total_debt;+ }++ // Calculate total equity from book value and shares outstanding+ let totalEquity: number | null = null;+ if (stockInfo.book_value !== null && stockInfo.shares_outstanding !== null) {+ totalEquity = stockInfo.book_value * stockInfo.shares_outstanding;+ financials.total_equity = totalEquity;+ }++ // Derive total_assets from total_liabilities + total_equity (balance sheet equation)+ if (totalEquity !== null) {+ const totalLiabilities = financials.total_liabilities || 0;+ financials.total_assets = totalLiabilities + totalEquity;+ }++ // Cash flow related+ if (stockInfo.operating_cashflow !== null) financials.operating_cash_flow = stockInfo.operating_cashflow;+ if (stockInfo.free_cashflow !== null && stockInfo.operating_cashflow !== null) {+ // capex = operating cash flow - free cash flow+ financials.capex = stockInfo.operating_cashflow - stockInfo.free_cashflow;}- });+ }++ const data: FinancialDataInput = {+ company: {+ ticker,+ name: companyName,+ sector: stockInfo?.sector || undefined,+ industry: stockInfo?.industry || undefined,+ country: stockInfo?.country || 'USA'+ },+ period: {+ period_end: new Date().toISOString().split('T')[0],+ fiscal_year: new Date().getFullYear(),+ period_type: 'annual',+ fiscal_period: 'FY'+ },+ financials+ };++ const res = await invoke<string>(cmds[selected], { data });const p = JSON.parse(res);setResult({ success: p.success !== false, summary: p.summary || p.error, results: p.results, metrics: p.metrics, error: p.error });} catch (e) {@@ -62,7 +166,7 @@ export const FinancialAnalysisPanel: React.FC<{ ticker?: string; companyName?: s} finally {setLoading(false);}- }, [selected, ticker, companyName]);+ }, [selected, ticker, companyName, stockInfo]);return (<div style={{@@ -189,67 +293,228 @@ export const FinancialAnalysisPanel: React.FC<{ ticker?: string; companyName?: s{/* Results */}{result && (<div style={{- padding: '16px',- backgroundColor: result.success ? `${COLORS.GREEN}15` : `${COLORS.RED}15`,- border: `1px solid ${result.success ? COLORS.GREEN : COLORS.RED}`,+ backgroundColor: COLORS.DARK_BG,+ border: `1px solid ${COLORS.BORDER}`,+ overflow: 'hidden',}}>- <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '8px' }}>- {result.success ?- <CheckCircle size={18} color={COLORS.GREEN} /> :- <AlertCircle size={18} color={COLORS.RED} />- }- <span style={{- color: result.success ? COLORS.GREEN : COLORS.RED,- fontWeight: 700,- fontSize: '11px',- textTransform: 'uppercase',- letterSpacing: '0.5px',- }}>- {result.success ? 'Analysis Complete' : 'Analysis Failed'}- </span>+ {/* Results Header */}+ <div style={{+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ padding: '12px 16px',+ backgroundColor: result.success ? `${COLORS.GREEN}15` : `${COLORS.RED}15`,+ borderBottom: `2px solid ${result.success ? COLORS.GREEN : COLORS.RED}`,+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>+ {result.success ?+ <CheckCircle size={20} color={COLORS.GREEN} /> :+ <AlertCircle size={20} color={COLORS.RED} />+ }+ <span style={{+ color: result.success ? COLORS.GREEN : COLORS.RED,+ fontWeight: 700,+ fontSize: '12px',+ textTransform: 'uppercase',+ letterSpacing: '0.5px',+ }}>+ {result.success ? 'Analysis Complete' : 'Analysis Failed'}+ </span>+ </div>+ {result.results && (+ <span style={{+ color: COLORS.GRAY,+ fontSize: '10px',+ backgroundColor: COLORS.PANEL_BG,+ padding: '4px 8px',+ borderRadius: '2px',+ }}>+ {result.results.length} METRICS+ </span>+ )}</div>- {result.summary && (- <div style={{ color: COLORS.WHITE, fontSize: '10px', marginBottom: '8px' }}>- {result.summary}+ {/* Error Display */}+ {result.error && !result.success && (+ <div style={{+ padding: '16px',+ color: COLORS.RED,+ fontSize: '11px',+ fontFamily: 'monospace',+ backgroundColor: `${COLORS.RED}10`,+ }}>+ {result.error}</div>)}- {result.error && !result.success && (- <div style={{ color: COLORS.RED, fontSize: '10px' }}>- {result.error}+ {/* Results Grid */}+ {result.success && result.results && result.results.length > 0 && (+ <div style={{ padding: '16px' }}>+ {/* Metrics Grid */}+ <div style={{+ display: 'grid',+ gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))',+ gap: '12px',+ maxHeight: '400px',+ overflowY: 'auto',+ }}>+ {result.results.map((r: any, i: number) => {+ const riskColor = r.risk_level === 'low' ? COLORS.GREEN :+ r.risk_level === 'high' ? COLORS.RED :+ r.risk_level === 'medium' ? COLORS.YELLOW : COLORS.CYAN;+ const formatValue = (val: any) => {+ if (typeof val === 'number') {+ if (val >= 1000000000) return `${(val / 1000000000).toFixed(2)}B`;+ if (val >= 1000000) return `${(val / 1000000).toFixed(2)}M`;+ if (val >= 1000) return `${(val / 1000).toFixed(2)}K`;+ if (val < 1 && val > 0) return `${(val * 100).toFixed(1)}%`;+ return val.toFixed(2);+ }+ return val;+ };++ return (+ <div+ key={i}+ style={{+ backgroundColor: COLORS.PANEL_BG,+ border: `1px solid ${COLORS.BORDER}`,+ padding: '12px',+ display: 'flex',+ flexDirection: 'column',+ gap: '8px',+ }}+ >+ {/* Metric Header */}+ <div style={{+ display: 'flex',+ justifyContent: 'space-between',+ alignItems: 'flex-start',+ }}>+ <span style={{+ color: COLORS.WHITE,+ fontSize: '10px',+ fontWeight: 700,+ textTransform: 'uppercase',+ letterSpacing: '0.5px',+ flex: 1,+ }}>+ {r.metric_name?.replace(/_/g, ' ')}+ </span>+ <span style={{+ color: riskColor,+ fontSize: '9px',+ fontWeight: 600,+ textTransform: 'uppercase',+ padding: '2px 6px',+ backgroundColor: `${riskColor}20`,+ border: `1px solid ${riskColor}`,+ marginLeft: '8px',+ whiteSpace: 'nowrap',+ }}>+ {r.risk_level || 'N/A'}+ </span>+ </div>++ {/* Value */}+ <div style={{+ color: COLORS.ORANGE,+ fontSize: '20px',+ fontWeight: 700,+ fontFamily: 'monospace',+ }}>+ {formatValue(r.value)}+ </div>++ {/* Interpretation */}+ {r.interpretation && (+ <div style={{+ color: COLORS.GRAY,+ fontSize: '10px',+ lineHeight: '1.4',+ borderTop: `1px solid ${COLORS.BORDER}`,+ paddingTop: '8px',+ maxHeight: '60px',+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ }}>+ {r.interpretation.length > 150+ ? `${r.interpretation.substring(0, 150)}...`+ : r.interpretation}+ </div>+ )}++ {/* Analysis Type Badge */}+ {r.analysis_type && (+ <div style={{+ color: COLORS.CYAN,+ fontSize: '8px',+ textTransform: 'uppercase',+ letterSpacing: '0.5px',+ }}>+ {r.analysis_type}+ </div>+ )}+ </div>+ );+ })}+ </div></div>)}- {result.results && result.results.length > 0 && (- <div style={{ marginTop: '8px', maxHeight: '160px', overflowY: 'auto' }}>- <div style={{ color: COLORS.GRAY, fontSize: '9px', marginBottom: '4px' }}>- {result.results.length} metrics analyzed+ {/* Key Metrics Summary (for get_key_metrics) */}+ {result.success && result.metrics && Object.keys(result.metrics).length > 0 && (+ <div style={{ padding: '16px' }}>+ <div style={{+ color: COLORS.ORANGE,+ fontSize: '11px',+ fontWeight: 700,+ textTransform: 'uppercase',+ letterSpacing: '0.5px',+ marginBottom: '12px',+ paddingBottom: '8px',+ borderBottom: `1px solid ${COLORS.BORDER}`,+ }}>+ Key Metrics+ </div>+ <div style={{+ display: 'grid',+ gridTemplateColumns: 'repeat(auto-fill, minmax(150px, 1fr))',+ gap: '12px',+ }}>+ {Object.entries(result.metrics).map(([key, value]: [string, any], i: number) => (+ <div+ key={i}+ style={{+ backgroundColor: COLORS.PANEL_BG,+ border: `1px solid ${COLORS.BORDER}`,+ padding: '10px',+ }}+ >+ <div style={{+ color: COLORS.GRAY,+ fontSize: '9px',+ textTransform: 'uppercase',+ letterSpacing: '0.5px',+ marginBottom: '4px',+ }}>+ {key.replace(/_/g, ' ')}+ </div>+ <div style={{+ color: COLORS.CYAN,+ fontSize: '14px',+ fontWeight: 700,+ fontFamily: 'monospace',+ }}>+ {typeof value === 'number'+ ? (value >= 1000000+ ? `${(value / 1000000).toFixed(2)}M`+ : value.toFixed(2))+ : value}+ </div>+ </div>+ ))}</div>- {result.results.slice(0, 5).map((r: any, i: number) => (- <div- key={i}- style={{- display: 'flex',- justifyContent: 'space-between',- fontSize: '10px',- padding: '4px 0',- borderBottom: `1px solid ${COLORS.BORDER}`,- }}- >- <span style={{ color: COLORS.CYAN, textTransform: 'uppercase' }}>- {r.metric_name}- </span>- <span style={{- color: r.risk_level === 'low' ? COLORS.GREEN :- r.risk_level === 'high' ? COLORS.RED :- COLORS.YELLOW,- fontWeight: 600,- }}>- {typeof r.value === 'number' ? r.value.toFixed(4) : r.value}- </span>- </div>- ))}</div>)}</div>diff --git a/fincept-terminal-desktop/src/components/tabs/equity-research/components/IndicatorBox.tsx b/fincept-terminal-desktop/src/components/tabs/equity-research/components/IndicatorBox.tsxindex a78e0b4a6..0e832e39f 100644--- a/fincept-terminal-desktop/src/components/tabs/equity-research/components/IndicatorBox.tsx+++ b/fincept-terminal-desktop/src/components/tabs/equity-research/components/IndicatorBox.tsx@@ -1,7 +1,8 @@-import React, { useState } from 'react';-import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts';-import { FINCEPT } from '../../portfolio-tab/finceptStyles';+import React, { useState, useMemo } from 'react';+import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, ReferenceLine, Area, ComposedChart } from 'recharts';+import { FINCEPT, TYPOGRAPHY, SPACING, BORDERS, EFFECTS } from '../../portfolio-tab/finceptStyles';import { formatIndicatorValue } from '../utils/formatters';+import { TrendingUp, TrendingDown, Minus, Settings2, Activity, AlertCircle, CheckCircle, XCircle, ArrowUp, ArrowDown } from 'lucide-react';const COLORS = {ORANGE: FINCEPT.ORANGE,@@ -10,10 +11,13 @@ const COLORS = {GREEN: FINCEPT.GREEN,YELLOW: FINCEPT.YELLOW,GRAY: FINCEPT.GRAY,+ MUTED: FINCEPT.MUTED,CYAN: FINCEPT.CYAN,DARK_BG: FINCEPT.DARK_BG,PANEL_BG: FINCEPT.PANEL_BG,+ HEADER_BG: FINCEPT.HEADER_BG,BORDER: FINCEPT.BORDER,+ PURPLE: FINCEPT.PURPLE,};interface IndicatorBoxProps {@@ -30,89 +34,48 @@ interface IndicatorBoxProps {}/**- * Get default parameters for a given indicator+ * Get indicator zone info (overbought/oversold thresholds)*/-const getDefaultParams = (name: string): any => {+const getIndicatorZones = (name: string): {+ hasZones: boolean;+ overbought: number;+ oversold: number;+ neutral: { min: number; max: number };+ rangeMin: number;+ rangeMax: number;+ inverted?: boolean;+} => {const nameUpper = name.toUpperCase();- // Moving Averages- if (nameUpper.includes('SMA_5')) return { period: 5 };- if (nameUpper.includes('SMA_10')) return { period: 10 };- if (nameUpper.includes('SMA_20')) return { period: 20 };- if (nameUpper.includes('SMA_50')) return { period: 50 };- if (nameUpper.includes('SMA_200')) return { period: 200 };- if (nameUpper.includes('EMA_9')) return { period: 9 };- if (nameUpper.includes('EMA_12')) return { period: 12 };- if (nameUpper.includes('EMA_21')) return { period: 21 };- if (nameUpper.includes('EMA_26')) return { period: 26 };- if (nameUpper.includes('EMA_50')) return { period: 50 };- if (nameUpper.includes('WMA')) return { period: 9 };-- // RSI- if (nameUpper.includes('RSI')) return { period: 14 };-- // MACD- if (nameUpper.includes('MACD')) return { fast: 12, slow: 26, signal: 9 };-- // Stochastic- if (nameUpper.includes('STOCH')) return { k_period: 14, d_period: 3 };-- // Bollinger Bands- if (nameUpper.includes('BB_')) return { period: 20, std: 2 };-- // ATR- if (nameUpper.includes('ATR')) return { period: 14 };-- // ADX- if (nameUpper.includes('ADX')) return { period: 14 };-- // CCI- if (nameUpper.includes('CCI')) return { period: 20 };-- // Williams %R- if (nameUpper.includes('WILLIAMS')) return { period: 14 };-- // ROC- if (nameUpper.includes('ROC')) return { period: 12 };-- // MFI- if (nameUpper === 'MFI') return { period: 14 };-- // Aroon- if (nameUpper.includes('AROON')) return { period: 25 };-- // Awesome Oscillator- if (nameUpper.includes('AWESOME') || nameUpper === 'AO') return { fast: 5, slow: 34 };-- // TSI- if (nameUpper === 'TSI') return { long: 25, short: 13 };-- // Ultimate Oscillator- if (nameUpper === 'UO' || nameUpper.includes('ULTIMATE')) return { period1: 7, period2: 14, period3: 28 };-- return null;-};--/**- * Get default thresholds for a given indicator- */-const getDefaultThresholds = (name: string): { upper: number; lower: number; label: string } => {- const nameUpper = name.toUpperCase();+ if (nameUpper.includes('RSI')) {+ return { hasZones: true, overbought: 70, oversold: 30, neutral: { min: 30, max: 70 }, rangeMin: 0, rangeMax: 100 };+ }+ if (nameUpper.includes('STOCH') && !nameUpper.includes('RSI')) {+ return { hasZones: true, overbought: 80, oversold: 20, neutral: { min: 20, max: 80 }, rangeMin: 0, rangeMax: 100 };+ }+ if (nameUpper.includes('WILLIAMS')) {+ return { hasZones: true, overbought: -20, oversold: -80, neutral: { min: -80, max: -20 }, rangeMin: -100, rangeMax: 0, inverted: true };+ }+ if (nameUpper.includes('CCI')) {+ return { hasZones: true, overbought: 100, oversold: -100, neutral: { min: -100, max: 100 }, rangeMin: -200, rangeMax: 200 };+ }+ if (nameUpper === 'MFI') {+ return { hasZones: true, overbought: 80, oversold: 20, neutral: { min: 20, max: 80 }, rangeMin: 0, rangeMax: 100 };+ }+ if (nameUpper === 'TSI') {+ return { hasZones: true, overbought: 25, oversold: -25, neutral: { min: -25, max: 25 }, rangeMin: -50, rangeMax: 50 };+ }+ if (nameUpper === 'UO' || nameUpper.includes('ULTIMATE')) {+ return { hasZones: true, overbought: 70, oversold: 30, neutral: { min: 30, max: 70 }, rangeMin: 0, rangeMax: 100 };+ }+ if (nameUpper.includes('BB_PBAND') || nameUpper.includes('KC_PBAND') || nameUpper.includes('DC_PBAND')) {+ return { hasZones: true, overbought: 0.8, oversold: 0.2, neutral: { min: 0.2, max: 0.8 }, rangeMin: 0, rangeMax: 1 };+ }+ if (nameUpper.includes('ADX') && !nameUpper.includes('POS') && !nameUpper.includes('NEG')) {+ return { hasZones: true, overbought: 50, oversold: 20, neutral: { min: 20, max: 50 }, rangeMin: 0, rangeMax: 100 };+ }- if (nameUpper.includes('RSI')) return { upper: 70, lower: 30, label: 'Overbought/Oversold' };- if (nameUpper.includes('STOCH')) return { upper: 80, lower: 20, label: 'Overbought/Oversold' };- if (nameUpper.includes('WILLIAMS')) return { upper: -20, lower: -80, label: 'Overbought/Oversold' };- if (nameUpper.includes('CCI')) return { upper: 100, lower: -100, label: 'Overbought/Oversold' };- if (nameUpper === 'TSI') return { upper: 25, lower: -25, label: 'Overbought/Oversold' };- if (nameUpper === 'UO' || nameUpper.includes('ULTIMATE')) return { upper: 70, lower: 30, label: 'Overbought/Oversold' };- if (nameUpper === 'MFI') return { upper: 80, lower: 20, label: 'Overbought/Oversold' };- if (nameUpper.includes('ROC')) return { upper: 5, lower: -5, label: 'Strength %' };- if (nameUpper.includes('ADX') && !nameUpper.includes('POS') && !nameUpper.includes('NEG')) return { upper: 25, lower: 20, label: 'Trend Strength' };- if (nameUpper.includes('AROON')) return { upper: 70, lower: 30, label: 'Trend Strength' };- if (nameUpper.includes('BB_PBAND') || nameUpper.includes('KC_PBAND') || nameUpper.includes('DC_PBAND')) return { upper: 0.8, lower: 0.2, label: 'Band Position' };- if (nameUpper.includes('CMF')) return { upper: 0.1, lower: -0.1, label: 'Money Flow' };-- return { upper: 0, lower: 0, label: 'Custom' };+ return { hasZones: false, overbought: 0, oversold: 0, neutral: { min: 0, max: 0 }, rangeMin: 0, rangeMax: 100 };};/**@@ -122,199 +85,119 @@ const getSignal = (name: string,latestValue: number,prevValue: number,- avg: number,- activeThresholds: { upper: number; lower: number }-): { signal: 'BUY' | 'SELL' | 'NEUTRAL'; reason: string } => {+ avg: number+): { signal: 'BUY' | 'SELL' | 'NEUTRAL'; reason: string; strength: number; zone: 'OVERBOUGHT' | 'OVERSOLD' | 'NEUTRAL' | 'STRONG_TREND' | 'WEAK_TREND' } => {const nameUpper = name.toUpperCase();+ const zones = getIndicatorZones(name);// === MOMENTUM INDICATORS ===if (nameUpper.includes('RSI')) {- if (latestValue <= activeThresholds.lower) return { signal: 'BUY', reason: `Oversold <${activeThresholds.lower}` };- if (latestValue >= activeThresholds.upper) return { signal: 'SELL', reason: `Overbought >${activeThresholds.upper}` };- return { signal: 'NEUTRAL', reason: `${activeThresholds.lower}-${activeThresholds.upper} range` };+ if (latestValue <= 30) return { signal: 'BUY', reason: 'Oversold territory', strength: Math.min(100, (30 - latestValue) * 3), zone: 'OVERSOLD' };+ if (latestValue >= 70) return { signal: 'SELL', reason: 'Overbought territory', strength: Math.min(100, (latestValue - 70) * 3), zone: 'OVERBOUGHT' };+ if (latestValue > 50) return { signal: 'NEUTRAL', reason: 'Bullish momentum', strength: 50, zone: 'NEUTRAL' };+ return { signal: 'NEUTRAL', reason: 'Bearish momentum', strength: 50, zone: 'NEUTRAL' };}if (nameUpper.includes('STOCH') && !nameUpper.includes('RSI')) {- if (latestValue <= activeThresholds.lower) return { signal: 'BUY', reason: `Oversold <${activeThresholds.lower}` };- if (latestValue >= activeThresholds.upper) return { signal: 'SELL', reason: `Overbought >${activeThresholds.upper}` };- return { signal: 'NEUTRAL', reason: `${activeThresholds.lower}-${activeThresholds.upper} range` };+ if (latestValue <= 20) return { signal: 'BUY', reason: 'Oversold zone', strength: Math.min(100, (20 - latestValue) * 5), zone: 'OVERSOLD' };+ if (latestValue >= 80) return { signal: 'SELL', reason: 'Overbought zone', strength: Math.min(100, (latestValue - 80) * 5), zone: 'OVERBOUGHT' };+ return { signal: 'NEUTRAL', reason: 'Neutral zone', strength: 40, zone: 'NEUTRAL' };}if (nameUpper.includes('WILLIAMS')) {- if (latestValue <= -80) return { signal: 'BUY', reason: 'Oversold' };- if (latestValue >= -20) return { signal: 'SELL', reason: 'Overbought' };- return { signal: 'NEUTRAL', reason: '-20 to -80' };- }-- if (nameUpper === 'AO' || nameUpper.includes('AWESOME')) {- if (prevValue < 0 && latestValue > 0) return { signal: 'BUY', reason: 'Zero cross up' };- if (prevValue > 0 && latestValue < 0) return { signal: 'SELL', reason: 'Zero cross down' };- return { signal: 'NEUTRAL', reason: 'No crossover' };+ if (latestValue <= -80) return { signal: 'BUY', reason: 'Oversold', strength: Math.min(100, Math.abs(-100 - latestValue) * 5), zone: 'OVERSOLD' };+ if (latestValue >= -20) return { signal: 'SELL', reason: 'Overbought', strength: Math.min(100, Math.abs(latestValue) * 5), zone: 'OVERBOUGHT' };+ return { signal: 'NEUTRAL', reason: 'Mid range', strength: 40, zone: 'NEUTRAL' };}- if (nameUpper.includes('ROC')) {- if (latestValue > 5) return { signal: 'BUY', reason: 'Strong >5%' };- if (latestValue < -5) return { signal: 'SELL', reason: 'Weak <-5%' };- return { signal: 'NEUTRAL', reason: '-5% to 5%' };- }-- if (nameUpper === 'TSI') {- if (latestValue < -25) return { signal: 'BUY', reason: 'Oversold' };- if (latestValue > 25) return { signal: 'SELL', reason: 'Overbought' };- return { signal: 'NEUTRAL', reason: '-25 to 25' };- }-- if (nameUpper === 'UO' || nameUpper.includes('ULTIMATE')) {- if (latestValue < 30) return { signal: 'BUY', reason: 'Oversold <30' };- if (latestValue > 70) return { signal: 'SELL', reason: 'Overbought >70' };- return { signal: 'NEUTRAL', reason: '30-70 range' };- }-- if (nameUpper.includes('PPO') && !nameUpper.includes('SIGNAL') && !nameUpper.includes('HIST')) {- if (prevValue < 0 && latestValue > 0) return { signal: 'BUY', reason: 'Zero cross up' };- if (prevValue > 0 && latestValue < 0) return { signal: 'SELL', reason: 'Zero cross down' };- return { signal: 'NEUTRAL', reason: 'No crossover' };- }-- // === TREND INDICATORS ===if (nameUpper.includes('MACD') && !nameUpper.includes('SIGNAL') && !nameUpper.includes('DIFF')) {- if (prevValue < 0 && latestValue > 0) return { signal: 'BUY', reason: 'Bullish crossover' };- if (prevValue > 0 && latestValue < 0) return { signal: 'SELL', reason: 'Bearish crossover' };- return { signal: 'NEUTRAL', reason: 'No crossover' };+ if (prevValue < 0 && latestValue > 0) return { signal: 'BUY', reason: 'Bullish crossover', strength: 85, zone: 'NEUTRAL' };+ if (prevValue > 0 && latestValue < 0) return { signal: 'SELL', reason: 'Bearish crossover', strength: 85, zone: 'NEUTRAL' };+ if (latestValue > 0 && latestValue > prevValue) return { signal: 'BUY', reason: 'Bullish momentum', strength: 60, zone: 'NEUTRAL' };+ if (latestValue < 0 && latestValue < prevValue) return { signal: 'SELL', reason: 'Bearish momentum', strength: 60, zone: 'NEUTRAL' };+ return { signal: 'NEUTRAL', reason: 'Sideways', strength: 30, zone: 'NEUTRAL' };}if (nameUpper.includes('CCI')) {- if (latestValue <= -100) return { signal: 'BUY', reason: 'Oversold <-100' };- if (latestValue >= 100) return { signal: 'SELL', reason: 'Overbought >100' };- return { signal: 'NEUTRAL', reason: '-100 to 100' };+ if (latestValue <= -100) return { signal: 'BUY', reason: 'Oversold', strength: Math.min(100, Math.abs(latestValue + 100) / 2), zone: 'OVERSOLD' };+ if (latestValue >= 100) return { signal: 'SELL', reason: 'Overbought', strength: Math.min(100, (latestValue - 100) / 2), zone: 'OVERBOUGHT' };+ return { signal: 'NEUTRAL', reason: 'Normal range', strength: 40, zone: 'NEUTRAL' };}if (nameUpper.includes('ADX') && !nameUpper.includes('POS') && !nameUpper.includes('NEG')) {- if (latestValue > 25) return { signal: 'BUY', reason: 'Strong trend >25' };- if (latestValue < 20) return { signal: 'NEUTRAL', reason: 'Weak trend <20' };- return { signal: 'NEUTRAL', reason: 'Moderate 20-25' };- }-- if (nameUpper.includes('AROON_UP')) {- if (latestValue > 70) return { signal: 'BUY', reason: 'Strong uptrend' };- return { signal: 'NEUTRAL', reason: 'Weak uptrend' };- }-- if (nameUpper.includes('AROON_DOWN')) {- if (latestValue > 70) return { signal: 'SELL', reason: 'Strong downtrend' };- return { signal: 'NEUTRAL', reason: 'Weak downtrend' };+ if (latestValue > 50) return { signal: 'BUY', reason: 'Very strong trend', strength: 90, zone: 'STRONG_TREND' };+ if (latestValue > 25) return { signal: 'BUY', reason: 'Strong trend', strength: 70, zone: 'STRONG_TREND' };+ if (latestValue < 20) return { signal: 'NEUTRAL', reason: 'Weak/no trend', strength: 30, zone: 'WEAK_TREND' };+ return { signal: 'NEUTRAL', reason: 'Moderate trend', strength: 50, zone: 'NEUTRAL' };}- if (nameUpper.includes('AROON_INDICATOR')) {- if (latestValue > 50) return { signal: 'BUY', reason: 'Bullish' };- if (latestValue < -50) return { signal: 'SELL', reason: 'Bearish' };- return { signal: 'NEUTRAL', reason: '-50 to 50' };- }-- if (nameUpper.includes('PSAR_UP_INDICATOR')) {- if (latestValue === 1) return { signal: 'BUY', reason: 'Uptrend active' };- return { signal: 'NEUTRAL', reason: 'No uptrend' };- }-- if (nameUpper.includes('PSAR_DOWN_INDICATOR')) {- if (latestValue === 1) return { signal: 'SELL', reason: 'Downtrend active' };- return { signal: 'NEUTRAL', reason: 'No downtrend' };- }-- if (nameUpper.includes('TRIX')) {- if (prevValue < 0 && latestValue > 0) return { signal: 'BUY', reason: 'Zero cross up' };- if (prevValue > 0 && latestValue < 0) return { signal: 'SELL', reason: 'Zero cross down' };- return { signal: 'NEUTRAL', reason: 'No crossover' };- }-- if (nameUpper.includes('KST') && !nameUpper.includes('SIGNAL')) {- if (prevValue < 0 && latestValue > 0) return { signal: 'BUY', reason: 'Zero cross up' };- if (prevValue > 0 && latestValue < 0) return { signal: 'SELL', reason: 'Zero cross down' };- return { signal: 'NEUTRAL', reason: 'No crossover' };- }-- if (nameUpper.includes('VORTEX_POS')) {- if (latestValue > 1) return { signal: 'BUY', reason: 'Positive >1' };- return { signal: 'NEUTRAL', reason: 'Weak' };+ if (nameUpper === 'MFI') {+ if (latestValue <= 20) return { signal: 'BUY', reason: 'Oversold', strength: Math.min(100, (20 - latestValue) * 5), zone: 'OVERSOLD' };+ if (latestValue >= 80) return { signal: 'SELL', reason: 'Overbought', strength: Math.min(100, (latestValue - 80) * 5), zone: 'OVERBOUGHT' };+ return { signal: 'NEUTRAL', reason: 'Normal flow', strength: 40, zone: 'NEUTRAL' };}- if (nameUpper.includes('VORTEX_NEG')) {- if (latestValue > 1) return { signal: 'SELL', reason: 'Negative >1' };- return { signal: 'NEUTRAL', reason: 'Weak' };+ if (nameUpper.includes('ROC')) {+ if (latestValue > 5) return { signal: 'BUY', reason: 'Strong momentum', strength: Math.min(100, latestValue * 10), zone: 'NEUTRAL' };+ if (latestValue < -5) return { signal: 'SELL', reason: 'Weak momentum', strength: Math.min(100, Math.abs(latestValue) * 10), zone: 'NEUTRAL' };+ return { signal: 'NEUTRAL', reason: 'Flat', strength: 30, zone: 'NEUTRAL' };}- // === VOLATILITY INDICATORS ===if (nameUpper.includes('BB_PBAND') || nameUpper.includes('KC_PBAND') || nameUpper.includes('DC_PBAND')) {- if (latestValue < 0.2) return { signal: 'BUY', reason: 'Near lower band' };- if (latestValue > 0.8) return { signal: 'SELL', reason: 'Near upper band' };- return { signal: 'NEUTRAL', reason: 'Middle band' };+ if (latestValue < 0.2) return { signal: 'BUY', reason: 'Near lower band', strength: Math.min(100, (0.2 - latestValue) * 500), zone: 'OVERSOLD' };+ if (latestValue > 0.8) return { signal: 'SELL', reason: 'Near upper band', strength: Math.min(100, (latestValue - 0.8) * 500), zone: 'OVERBOUGHT' };+ return { signal: 'NEUTRAL', reason: 'Mid band', strength: 40, zone: 'NEUTRAL' };}- if (nameUpper.includes('BB_HBAND_INDICATOR')) {- if (latestValue === 1) return { signal: 'SELL', reason: 'Above upper BB' };- return { signal: 'NEUTRAL', reason: 'Below upper BB' };- }-- if (nameUpper.includes('BB_LBAND_INDICATOR')) {- if (latestValue === 1) return { signal: 'BUY', reason: 'Below lower BB' };- return { signal: 'NEUTRAL', reason: 'Above lower BB' };+ if (nameUpper.includes('CMF')) {+ if (latestValue > 0.1) return { signal: 'BUY', reason: 'Buying pressure', strength: Math.min(100, latestValue * 500), zone: 'NEUTRAL' };+ if (latestValue < -0.1) return { signal: 'SELL', reason: 'Selling pressure', strength: Math.min(100, Math.abs(latestValue) * 500), zone: 'NEUTRAL' };+ return { signal: 'NEUTRAL', reason: 'Balanced flow', strength: 30, zone: 'NEUTRAL' };}if (nameUpper.includes('ATR')) {- if (latestValue > avg * 1.5) return { signal: 'NEUTRAL', reason: 'High volatility' };- if (latestValue < avg * 0.5) return { signal: 'NEUTRAL', reason: 'Low volatility' };- return { signal: 'NEUTRAL', reason: 'Normal volatility' };+ if (latestValue > avg * 1.5) return { signal: 'NEUTRAL', reason: 'High volatility', strength: 70, zone: 'NEUTRAL' };+ if (latestValue < avg * 0.5) return { signal: 'NEUTRAL', reason: 'Low volatility', strength: 30, zone: 'NEUTRAL' };+ return { signal: 'NEUTRAL', reason: 'Normal volatility', strength: 50, zone: 'NEUTRAL' };}- if (nameUpper.includes('UI') || nameUpper.includes('ULCER')) {- if (latestValue > avg * 1.5) return { signal: 'SELL', reason: 'High risk' };- return { signal: 'NEUTRAL', reason: 'Normal risk' };+ // Moving averages - compare trend direction+ if (nameUpper.includes('SMA') || nameUpper.includes('EMA') || nameUpper.includes('WMA')) {+ const change = ((latestValue - prevValue) / prevValue) * 100;+ if (change > 0.5) return { signal: 'BUY', reason: 'Upward slope', strength: Math.min(100, change * 20), zone: 'NEUTRAL' };+ if (change < -0.5) return { signal: 'SELL', reason: 'Downward slope', strength: Math.min(100, Math.abs(change) * 20), zone: 'NEUTRAL' };+ return { signal: 'NEUTRAL', reason: 'Flat', strength: 30, zone: 'NEUTRAL' };}- // === VOLUME INDICATORS ===- if (nameUpper === 'MFI') {- if (latestValue <= 20) return { signal: 'BUY', reason: 'Oversold <20' };- if (latestValue >= 80) return { signal: 'SELL', reason: 'Overbought >80' };- return { signal: 'NEUTRAL', reason: '20-80 range' };- }+ return { signal: 'NEUTRAL', reason: 'Monitor', strength: 30, zone: 'NEUTRAL' };+};- if (nameUpper.includes('CMF')) {- if (latestValue > 0.1) return { signal: 'BUY', reason: 'Positive flow' };- if (latestValue < -0.1) return { signal: 'SELL', reason: 'Negative flow' };- return { signal: 'NEUTRAL', reason: 'Neutral flow' };- }+/**+ * Calculate momentum direction and strength+ */+const calculateMomentum = (values: number[]): { direction: 'UP' | 'DOWN' | 'FLAT'; change: number; shortTermTrend: 'BULLISH' | 'BEARISH' | 'NEUTRAL' } => {+ if (values.length < 5) return { direction: 'FLAT', change: 0, shortTermTrend: 'NEUTRAL' };- if (nameUpper === 'OBV' || nameUpper.includes('ADI') || nameUpper.includes('VPT')) {- if (latestValue > prevValue) return { signal: 'BUY', reason: 'Volume rising' };- if (latestValue < prevValue) return { signal: 'SELL', reason: 'Volume falling' };- return { signal: 'NEUTRAL', reason: 'Volume stable' };- }+ const recent = values.slice(-5);+ const older = values.slice(-10, -5);- if (nameUpper.includes('EOM')) {- if (latestValue > 0) return { signal: 'BUY', reason: 'Ease of movement +' };- if (latestValue < 0) return { signal: 'SELL', reason: 'Ease of movement -' };- return { signal: 'NEUTRAL', reason: 'No movement' };- }+ const recentAvg = recent.reduce((a, b) => a + b, 0) / recent.length;+ const olderAvg = older.length > 0 ? older.reduce((a, b) => a + b, 0) / older.length : recentAvg;- if (nameUpper.includes('FI') && !nameUpper.includes('MFI')) {- if (latestValue > 0) return { signal: 'BUY', reason: 'Force positive' };- if (latestValue < 0) return { signal: 'SELL', reason: 'Force negative' };- return { signal: 'NEUTRAL', reason: 'No force' };- }+ const change = olderAvg !== 0 ? ((recentAvg - olderAvg) / Math.abs(olderAvg)) * 100 : 0;- // === OTHERS (RETURNS) ===- if (nameUpper.includes('RETURN')) {- if (latestValue > 2) return { signal: 'BUY', reason: 'Positive return' };- if (latestValue < -2) return { signal: 'SELL', reason: 'Negative return' };- return { signal: 'NEUTRAL', reason: 'Flat return' };- }+ let direction: 'UP' | 'DOWN' | 'FLAT' = 'FLAT';+ let shortTermTrend: 'BULLISH' | 'BEARISH' | 'NEUTRAL' = 'NEUTRAL';- // Default for moving averages and others- if (nameUpper.includes('SMA') || nameUpper.includes('EMA') || nameUpper.includes('WMA')) {- return { signal: 'NEUTRAL', reason: 'Compare to price' };+ if (change > 2) {+ direction = 'UP';+ shortTermTrend = 'BULLISH';+ } else if (change < -2) {+ direction = 'DOWN';+ shortTermTrend = 'BEARISH';}- return { signal: 'NEUTRAL', reason: 'Monitor indicator' };+ return { direction, change, shortTermTrend };};export const IndicatorBox: React.FC<IndicatorBoxProps> = ({@@ -330,325 +213,449 @@ export const IndicatorBox: React.FC<IndicatorBoxProps> = ({onRecompute,}) => {const [showSettings, setShowSettings] = useState(false);- const [customThresholds, setCustomThresholds] = useState<{ upper: number; lower: number } | null>(null);- const [customParams, setCustomParams] = useState<any>(null);-- // Only create indicator chart data (no price data for performance)- const chartData = values.map((value, i) => ({- index: i,- value: value || null,- }));-- const defaultThresholds = getDefaultThresholds(name);- const activeThresholds = customThresholds || defaultThresholds;- const defaultParams = getDefaultParams(name);- const activeParams = customParams || defaultParams;-- const prevValue = values[values.length - 2] || 0;- const { signal, reason } = getSignal(name, latestValue, prevValue, avg, activeThresholds);++ const prevValue = values[values.length - 2] || latestValue;+ const { signal, reason, strength, zone } = getSignal(name, latestValue, prevValue, avg);const signalColor = signal === 'BUY' ? COLORS.GREEN : signal === 'SELL' ? COLORS.RED : COLORS.GRAY;+ const SignalIcon = signal === 'BUY' ? TrendingUp : signal === 'SELL' ? TrendingDown : Minus;++ const zones = getIndicatorZones(name);+ const momentum = calculateMomentum(values);++ // Calculate position in range (0-100%)+ const range = max - min;+ const position = range > 0 ? ((latestValue - min) / range) * 100 : 50;++ // Change from previous+ const change = prevValue !== 0 ? ((latestValue - prevValue) / Math.abs(prevValue)) * 100 : 0;++ // Chart data with zones+ const chartData = useMemo(() => {+ return values.map((value, i) => ({+ index: i,+ value: value || null,+ upper: zones.hasZones ? zones.overbought : null,+ lower: zones.hasZones ? zones.oversold : null,+ }));+ }, [values, zones]);++ // Zone color+ const getZoneColor = () => {+ if (zone === 'OVERBOUGHT') return COLORS.RED;+ if (zone === 'OVERSOLD') return COLORS.GREEN;+ if (zone === 'STRONG_TREND') return COLORS.CYAN;+ if (zone === 'WEAK_TREND') return COLORS.YELLOW;+ return COLORS.GRAY;+ };++ const getZoneLabel = () => {+ if (zone === 'OVERBOUGHT') return 'OVERBOUGHT';+ if (zone === 'OVERSOLD') return 'OVERSOLD';+ if (zone === 'STRONG_TREND') return 'STRONG TREND';+ if (zone === 'WEAK_TREND') return 'WEAK TREND';+ return 'NEUTRAL';+ };return (<div style={{backgroundColor: COLORS.PANEL_BG,- border: `1px solid ${COLORS.BORDER}`,- borderLeft: `3px solid ${color}`,- borderRadius: '6px',- padding: '12px',+ border: BORDERS.STANDARD,+ borderTop: `2px solid ${signalColor}`,display: 'flex',flexDirection: 'column',- gap: '8px',- minHeight: showSettings ? '480px' : '320px',- height: 'auto',- boxShadow: '0 1px 3px rgba(0, 0, 0, 0.3)',- transition: 'all 0.2s ease',- }}- onMouseEnter={(e) => {- e.currentTarget.style.borderColor = color;- e.currentTarget.style.boxShadow = `0 4px 12px rgba(0, 0, 0, 0.5)`;- }}- onMouseLeave={(e) => {- e.currentTarget.style.borderColor = COLORS.BORDER;- e.currentTarget.style.boxShadow = '0 1px 3px rgba(0, 0, 0, 0.3)';- }}- >- {/* Header */}- <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>- <div>- <div style={{ color: color, fontSize: '10px', fontWeight: 'bold', marginBottom: '2px' }}>+ fontFamily: TYPOGRAPHY.MONO,+ transition: EFFECTS.TRANSITION_STANDARD,+ }}>+ {/* Header with Signal */}+ <div style={{+ backgroundColor: COLORS.HEADER_BG,+ padding: `${SPACING.SMALL} ${SPACING.MEDIUM}`,+ display: 'flex',+ justifyContent: 'space-between',+ alignItems: 'center',+ borderBottom: BORDERS.STANDARD,+ }}>+ <div style={{ flex: 1 }}>+ <div style={{+ color: COLORS.GRAY,+ fontSize: TYPOGRAPHY.TINY,+ textTransform: 'uppercase',+ letterSpacing: TYPOGRAPHY.WIDE,+ marginBottom: '2px',+ }}>{category}</div>- <div style={{ color: COLORS.WHITE, fontSize: '11px', fontWeight: 'bold' }}>+ <div style={{+ color: COLORS.WHITE,+ fontSize: TYPOGRAPHY.DEFAULT,+ fontWeight: TYPOGRAPHY.BOLD,+ }}>{name.toUpperCase().replace(/_/g, ' ')}</div></div>- <div style={{ textAlign: 'right' }}>- <div style={{ color: COLORS.WHITE, fontSize: '16px', fontWeight: 'bold' }}>++ {/* Signal Badge */}+ <div style={{+ display: 'flex',+ alignItems: 'center',+ gap: SPACING.SMALL,+ padding: `${SPACING.TINY} ${SPACING.SMALL}`,+ backgroundColor: `${signalColor}20`,+ borderLeft: `2px solid ${signalColor}`,+ }}>+ <SignalIcon size={12} color={signalColor} />+ <span style={{+ color: signalColor,+ fontSize: TYPOGRAPHY.SMALL,+ fontWeight: TYPOGRAPHY.BOLD,+ }}>+ {signal}+ </span>+ </div>+ </div>++ {/* Main Value Display with Gauge */}+ <div style={{+ padding: SPACING.MEDIUM,+ display: 'flex',+ gap: SPACING.MEDIUM,+ borderBottom: BORDERS.STANDARD,+ }}>+ {/* Current Value */}+ <div style={{ flex: 1 }}>+ <div style={{+ color: COLORS.WHITE,+ fontSize: '24px',+ fontWeight: TYPOGRAPHY.BOLD,+ fontFamily: TYPOGRAPHY.MONO,+ lineHeight: 1,+ }}>{formatIndicatorValue(latestValue)}</div>- <div style={{ color: COLORS.GRAY, fontSize: '9px' }}>- Current+ <div style={{+ display: 'flex',+ alignItems: 'center',+ gap: SPACING.TINY,+ marginTop: SPACING.TINY,+ }}>+ {change >= 0 ? (+ <ArrowUp size={10} color={COLORS.GREEN} />+ ) : (+ <ArrowDown size={10} color={COLORS.RED} />+ )}+ <span style={{+ color: change >= 0 ? COLORS.GREEN : COLORS.RED,+ fontSize: TYPOGRAPHY.TINY,+ fontWeight: TYPOGRAPHY.SEMIBOLD,+ }}>+ {change >= 0 ? '+' : ''}{change.toFixed(2)}%+ </span>+ </div>+ </div>++ {/* Zone Indicator */}+ <div style={{+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'flex-end',+ justifyContent: 'center',+ }}>+ <div style={{+ color: getZoneColor(),+ fontSize: TYPOGRAPHY.TINY,+ fontWeight: TYPOGRAPHY.BOLD,+ textTransform: 'uppercase',+ padding: `${SPACING.TINY} ${SPACING.SMALL}`,+ backgroundColor: `${getZoneColor()}15`,+ border: `1px solid ${getZoneColor()}40`,+ }}>+ {getZoneLabel()}+ </div>+ <div style={{+ color: COLORS.MUTED,+ fontSize: TYPOGRAPHY.TINY,+ marginTop: SPACING.TINY,+ }}>+ {reason}</div></div></div>- {/* Lightweight Chart - ONLY indicator line */}- <div style={{ width: '100%', height: '80px', flex: '0 0 auto' }}>+ {/* Visual Gauge Bar */}+ {zones.hasZones && (+ <div style={{+ padding: `${SPACING.SMALL} ${SPACING.MEDIUM}`,+ backgroundColor: COLORS.DARK_BG,+ }}>+ <div style={{+ display: 'flex',+ alignItems: 'center',+ gap: SPACING.TINY,+ marginBottom: SPACING.TINY,+ }}>+ <span style={{ color: COLORS.GREEN, fontSize: TYPOGRAPHY.TINY }}>+ {zones.inverted ? zones.overbought : zones.oversold}+ </span>+ <div style={{+ flex: 1,+ height: '8px',+ backgroundColor: COLORS.PANEL_BG,+ border: BORDERS.STANDARD,+ position: 'relative',+ overflow: 'hidden',+ }}>+ {/* Oversold Zone */}+ <div style={{+ position: 'absolute',+ left: 0,+ top: 0,+ bottom: 0,+ width: `${((zones.oversold - zones.rangeMin) / (zones.rangeMax - zones.rangeMin)) * 100}%`,+ backgroundColor: `${COLORS.GREEN}30`,+ }} />+ {/* Overbought Zone */}+ <div style={{+ position: 'absolute',+ right: 0,+ top: 0,+ bottom: 0,+ width: `${((zones.rangeMax - zones.overbought) / (zones.rangeMax - zones.rangeMin)) * 100}%`,+ backgroundColor: `${COLORS.RED}30`,+ }} />+ {/* Current Position Marker */}+ <div style={{+ position: 'absolute',+ left: `${Math.max(0, Math.min(100, ((latestValue - zones.rangeMin) / (zones.rangeMax - zones.rangeMin)) * 100))}%`,+ top: '-2px',+ bottom: '-2px',+ width: '3px',+ backgroundColor: signalColor,+ transform: 'translateX(-50%)',+ boxShadow: `0 0 6px ${signalColor}`,+ }} />+ </div>+ <span style={{ color: COLORS.RED, fontSize: TYPOGRAPHY.TINY }}>+ {zones.inverted ? zones.oversold : zones.overbought}+ </span>+ </div>+ </div>+ )}++ {/* Chart with Reference Lines */}+ <div style={{ padding: SPACING.SMALL, height: '80px' }}><ResponsiveContainer width="100%" height="100%">- <LineChart data={chartData} margin={{ top: 5, right: 5, left: 5, bottom: 5 }}>- <CartesianGrid strokeDasharray="3 3" stroke={COLORS.BORDER} opacity={0.3} />+ <ComposedChart data={chartData} margin={{ top: 5, right: 5, left: 5, bottom: 5 }}>+ <CartesianGrid strokeDasharray="3 3" stroke={COLORS.BORDER} opacity={0.2} /><XAxis dataKey="index" hide /><YAxis domain={['auto', 'auto']} hide />+ {zones.hasZones && (+ <>+ <ReferenceLine y={zones.overbought} stroke={COLORS.RED} strokeDasharray="3 3" strokeOpacity={0.5} />+ <ReferenceLine y={zones.oversold} stroke={COLORS.GREEN} strokeDasharray="3 3" strokeOpacity={0.5} />+ </>+ )}<TooltipcontentStyle={{backgroundColor: COLORS.DARK_BG,- border: `1px solid ${COLORS.BORDER}`,- borderRadius: '4px',- fontSize: '10px',+ border: BORDERS.STANDARD,+ fontSize: TYPOGRAPHY.SMALL,+ fontFamily: TYPOGRAPHY.MONO,}}- formatter={(value: any) => formatIndicatorValue(value)}+ formatter={(value: any) => [formatIndicatorValue(value), name]}/><Linetype="monotone"dataKey="value"stroke={color}- strokeWidth={2}+ strokeWidth={1.5}dot={false}connectNullsisAnimationActive={false}/>- </LineChart>+ </ComposedChart></ResponsiveContainer></div>- {/* Signal Badge */}+ {/* Signal Strength + Momentum */}<div style={{- display: 'flex',- justifyContent: 'center',- alignItems: 'center',- gap: '8px',- padding: '4px',- backgroundColor: `${signalColor}15`,- border: `1px solid ${signalColor}`,- borderRadius: '4px',+ display: 'grid',+ gridTemplateColumns: '1fr 1fr',+ gap: SPACING.TINY,+ padding: `0 ${SPACING.MEDIUM} ${SPACING.SMALL}`,}}>- <span style={{ color: signalColor, fontSize: '11px', fontWeight: 'bold' }}>- {signal}- </span>- <span style={{ color: COLORS.GRAY, fontSize: '9px' }}>- {reason}- </span>- </div>-- {/* Settings Toggle & Parameters */}- <div style={{ flex: '0 0 auto' }}>- <button- onClick={() => setShowSettings(!showSettings)}- style={{- fontSize: '9px',- fontWeight: '500',- textAlign: 'center',- padding: '4px 8px',- cursor: 'pointer',+ {/* Signal Strength */}+ <div style={{+ backgroundColor: COLORS.DARK_BG,+ padding: SPACING.SMALL,+ border: BORDERS.STANDARD,+ }}>+ <div style={{+ color: COLORS.GRAY,+ fontSize: TYPOGRAPHY.TINY,+ textTransform: 'uppercase',+ marginBottom: SPACING.TINY,+ }}>+ SIGNAL STRENGTH+ </div>+ <div style={{display: 'flex',alignItems: 'center',- justifyContent: 'center',- gap: '4px',- width: '100%',- userSelect: 'none',- backgroundColor: showSettings ? COLORS.DARK_BG : COLORS.PANEL_BG,- border: `1px solid ${COLORS.BORDER}`,- borderRadius: '3px',+ gap: SPACING.SMALL,+ }}>+ <div style={{+ flex: 1,+ height: '4px',+ backgroundColor: COLORS.PANEL_BG,+ overflow: 'hidden',+ }}>+ <div style={{+ width: `${strength}%`,+ height: '100%',+ backgroundColor: signalColor,+ }} />+ </div>+ <span style={{+ color: signalColor,+ fontSize: TYPOGRAPHY.SMALL,+ fontWeight: TYPOGRAPHY.BOLD,+ }}>+ {strength}%+ </span>+ </div>+ </div>++ {/* Momentum */}+ <div style={{+ backgroundColor: COLORS.DARK_BG,+ padding: SPACING.SMALL,+ border: BORDERS.STANDARD,+ }}>+ <div style={{color: COLORS.GRAY,- transition: 'all 0.15s ease',- }}- onMouseEnter={(e) => {- e.currentTarget.style.borderColor = COLORS.ORANGE;- e.currentTarget.style.color = COLORS.ORANGE;- }}- onMouseLeave={(e) => {- e.currentTarget.style.borderColor = COLORS.BORDER;- e.currentTarget.style.color = COLORS.GRAY;- }}- >- <span style={{ fontSize: '10px' }}></span>- <span>{showSettings ? 'Hide' : 'Adjust'}</span>- </button>-- {showSettings && (+ fontSize: TYPOGRAPHY.TINY,+ textTransform: 'uppercase',+ marginBottom: SPACING.TINY,+ }}>+ MOMENTUM+ </div><div style={{- backgroundColor: COLORS.DARK_BG,- border: `1px solid ${COLORS.BORDER}`,- borderRadius: '4px',- padding: '10px',- marginTop: '8px',- fontSize: '10px',+ display: 'flex',+ alignItems: 'center',+ gap: SPACING.TINY,}}>- {/* Indicator Parameters Section */}- {defaultParams && (- <div style={{ marginBottom: defaultThresholds.upper !== 0 ? '12px' : '0' }}>- <div style={{ color: COLORS.CYAN, fontWeight: 'bold', marginBottom: '8px', fontSize: '10px', display: 'flex', alignItems: 'center', gap: '4px' }}>- <span>Indicator Parameters</span>- </div>-- <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(100px, 1fr))', gap: '8px', marginBottom: '8px' }}>- {Object.keys(defaultParams).map((key) => (- <div key={key}>- <label style={{ color: COLORS.GRAY, display: 'block', marginBottom: '3px', fontSize: '9px', textTransform: 'capitalize' }}>- {key.replace(/_/g, ' ')}- </label>- <input- type="number"- step="1"- value={customParams?.[key] ?? defaultParams[key]}- onChange={(e) => setCustomParams({- ...defaultParams,- ...customParams,- [key]: parseInt(e.target.value) || 1- })}- style={{- width: '100%',- backgroundColor: COLORS.PANEL_BG,- border: `1px solid ${COLORS.BORDER}`,- borderRadius: '3px',- color: COLORS.WHITE,- padding: '4px 6px',- fontSize: '10px',- }}- />- </div>- ))}- </div>-- {customParams && (- <button- onClick={() => {- if (onRecompute) {- onRecompute({ indicator: name, params: customParams });- }- }}- style={{- width: '100%',- backgroundColor: COLORS.CYAN,- border: 'none',- borderRadius: '3px',- color: COLORS.DARK_BG,- padding: '6px',- fontSize: '10px',- cursor: 'pointer',- fontWeight: 'bold',- marginBottom: '6px',- }}- >- Recompute with New Parameters- </button>- )}- </div>- )}-- {/* Signal Thresholds Section */}- {defaultThresholds.upper !== 0 && (- <div>- <div style={{ color: COLORS.ORANGE, fontWeight: 'bold', marginBottom: '8px', fontSize: '10px', display: 'flex', alignItems: 'center', gap: '4px' }}>- <span>{defaultThresholds.label}</span>- </div>-- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px', marginBottom: '8px' }}>- <div>- <label style={{ color: COLORS.GRAY, display: 'block', marginBottom: '3px', fontSize: '9px' }}>- Upper Threshold- </label>- <input- type="number"- step="0.1"- value={customThresholds?.upper ?? defaultThresholds.upper}- onChange={(e) => setCustomThresholds({- upper: parseFloat(e.target.value),- lower: customThresholds?.lower ?? defaultThresholds.lower- })}- style={{- width: '100%',- backgroundColor: COLORS.PANEL_BG,- border: `1px solid ${COLORS.BORDER}`,- borderRadius: '3px',- color: COLORS.WHITE,- padding: '4px 6px',- fontSize: '10px',- }}- />- </div>-- <div>- <label style={{ color: COLORS.GRAY, display: 'block', marginBottom: '3px', fontSize: '9px' }}>- Lower Threshold- </label>- <input- type="number"- step="0.1"- value={customThresholds?.lower ?? defaultThresholds.lower}- onChange={(e) => setCustomThresholds({- upper: customThresholds?.upper ?? defaultThresholds.upper,- lower: parseFloat(e.target.value)- })}- style={{- width: '100%',- backgroundColor: COLORS.PANEL_BG,- border: `1px solid ${COLORS.BORDER}`,- borderRadius: '3px',- color: COLORS.WHITE,- padding: '4px 6px',- fontSize: '10px',- }}- />- </div>- </div>- </div>- )}-- {/* Reset Button */}- <button- onClick={() => {- setCustomThresholds(null);- setCustomParams(null);- }}- style={{- width: '100%',- backgroundColor: COLORS.PANEL_BG,- border: `1px solid ${COLORS.BORDER}`,- borderRadius: '3px',- color: COLORS.GRAY,- padding: '5px',- fontSize: '9px',- cursor: 'pointer',- fontWeight: '600',- }}- >- Reset All to Defaults- </button>+ {momentum.direction === 'UP' && <ArrowUp size={12} color={COLORS.GREEN} />}+ {momentum.direction === 'DOWN' && <ArrowDown size={12} color={COLORS.RED} />}+ {momentum.direction === 'FLAT' && <Minus size={12} color={COLORS.GRAY} />}+ <span style={{+ color: momentum.shortTermTrend === 'BULLISH' ? COLORS.GREEN :+ momentum.shortTermTrend === 'BEARISH' ? COLORS.RED : COLORS.GRAY,+ fontSize: TYPOGRAPHY.SMALL,+ fontWeight: TYPOGRAPHY.BOLD,+ }}>+ {momentum.shortTermTrend}+ </span></div>- )}+ </div></div>- {/* Stats */}- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '8px', fontSize: '9px' }}>- <div>- <div style={{ color: COLORS.GRAY }}>MIN</div>- <div style={{ color: COLORS.RED, fontWeight: 'bold' }}>{formatIndicatorValue(min)}</div>+ {/* Stats Row */}+ <div style={{+ display: 'grid',+ gridTemplateColumns: '1fr 1fr 1fr 1fr',+ gap: '1px',+ backgroundColor: COLORS.BORDER,+ borderTop: BORDERS.STANDARD,+ }}>+ <div style={{+ backgroundColor: COLORS.DARK_BG,+ padding: SPACING.SMALL,+ textAlign: 'center',+ }}>+ <div style={{ color: COLORS.GRAY, fontSize: TYPOGRAPHY.TINY, textTransform: 'uppercase' }}>MIN</div>+ <div style={{ color: COLORS.RED, fontSize: TYPOGRAPHY.SMALL, fontWeight: TYPOGRAPHY.BOLD }}>+ {formatIndicatorValue(min)}+ </div></div>- <div>- <div style={{ color: COLORS.GRAY }}>AVG</div>- <div style={{ color: COLORS.YELLOW, fontWeight: 'bold' }}>{formatIndicatorValue(avg)}</div>+ <div style={{+ backgroundColor: COLORS.DARK_BG,+ padding: SPACING.SMALL,+ textAlign: 'center',+ }}>+ <div style={{ color: COLORS.GRAY, fontSize: TYPOGRAPHY.TINY, textTransform: 'uppercase' }}>AVG</div>+ <div style={{ color: COLORS.YELLOW, fontSize: TYPOGRAPHY.SMALL, fontWeight: TYPOGRAPHY.BOLD }}>+ {formatIndicatorValue(avg)}+ </div></div>- <div>- <div style={{ color: COLORS.GRAY }}>MAX</div>- <div style={{ color: COLORS.GREEN, fontWeight: 'bold' }}>{formatIndicatorValue(max)}</div>+ <div style={{+ backgroundColor: COLORS.DARK_BG,+ padding: SPACING.SMALL,+ textAlign: 'center',+ }}>+ <div style={{ color: COLORS.GRAY, fontSize: TYPOGRAPHY.TINY, textTransform: 'uppercase' }}>MAX</div>+ <div style={{ color: COLORS.GREEN, fontSize: TYPOGRAPHY.SMALL, fontWeight: TYPOGRAPHY.BOLD }}>+ {formatIndicatorValue(max)}+ </div>+ </div>+ <div style={{+ backgroundColor: COLORS.DARK_BG,+ padding: SPACING.SMALL,+ textAlign: 'center',+ }}>+ <div style={{ color: COLORS.GRAY, fontSize: TYPOGRAPHY.TINY, textTransform: 'uppercase' }}>PTS</div>+ <div style={{ color: COLORS.CYAN, fontSize: TYPOGRAPHY.SMALL, fontWeight: TYPOGRAPHY.BOLD }}>+ {values.length}+ </div></div></div>- {/* Data Points Count */}- <div style={{ color: COLORS.GRAY, fontSize: '9px', textAlign: 'center', borderTop: `1px solid ${COLORS.BORDER}`, paddingTop: '4px' }}>- {values.length} data points- </div>+ {/* Settings Toggle */}+ <button+ onClick={() => setShowSettings(!showSettings)}+ style={{+ fontSize: TYPOGRAPHY.TINY,+ fontWeight: TYPOGRAPHY.SEMIBOLD,+ textAlign: 'center',+ padding: SPACING.SMALL,+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ gap: SPACING.TINY,+ width: '100%',+ backgroundColor: showSettings ? COLORS.DARK_BG : 'transparent',+ border: 'none',+ borderTop: BORDERS.STANDARD,+ color: COLORS.MUTED,+ fontFamily: TYPOGRAPHY.MONO,+ textTransform: 'uppercase',+ letterSpacing: TYPOGRAPHY.WIDE,+ transition: EFFECTS.TRANSITION_FAST,+ }}+ onMouseEnter={(e) => {+ e.currentTarget.style.color = COLORS.ORANGE;+ e.currentTarget.style.backgroundColor = COLORS.HEADER_BG;+ }}+ onMouseLeave={(e) => {+ e.currentTarget.style.color = COLORS.MUTED;+ e.currentTarget.style.backgroundColor = showSettings ? COLORS.DARK_BG : 'transparent';+ }}+ >+ <Settings2 size={10} />+ <span>{showSettings ? 'HIDE' : 'SETTINGS'}</span>+ </button>++ {showSettings && (+ <div style={{+ padding: SPACING.SMALL,+ backgroundColor: COLORS.DARK_BG,+ borderTop: BORDERS.STANDARD,+ fontSize: TYPOGRAPHY.TINY,+ color: COLORS.GRAY,+ textAlign: 'center',+ }}>+ Parameter customization coming soon+ </div>+ )}</div>);};diff --git a/fincept-terminal-desktop/src/components/tabs/equity-research/components/PeerComparisonPanel.tsx b/fincept-terminal-desktop/src/components/tabs/equity-research/components/PeerComparisonPanel.tsxindex 3e44eae3f..8f6396fbf 100644--- a/fincept-terminal-desktop/src/components/tabs/equity-research/components/PeerComparisonPanel.tsx+++ b/fincept-terminal-desktop/src/components/tabs/equity-research/components/PeerComparisonPanel.tsx@@ -297,34 +297,25 @@ export const PeerComparisonPanel: React.FC<PeerComparisonPanelProps> = ({ initia}}><div style={{ flex: 1 }}>- <div style={{ display: 'flex', alignItems: 'center', gap: SPACING.SMALL }}>- <span style={{- fontWeight: TYPOGRAPHY.BOLD,- color: FINCEPT.WHITE,- fontSize: TYPOGRAPHY.DEFAULT,- }}>- {peer.symbol}- </span>- <span style={{- fontSize: TYPOGRAPHY.TINY,- padding: `${SPACING.TINY} ${SPACING.SMALL}`,- backgroundColor: `${FINCEPT.CYAN}20`,- color: FINCEPT.CYAN,- border: `1px solid ${FINCEPT.CYAN}`,- }}>- {(peer.similarityScore * 100).toFixed(0)}% MATCH- </span>- </div>- <p style={{- fontSize: TYPOGRAPHY.SMALL,- color: FINCEPT.GRAY,- marginTop: SPACING.TINY,- overflow: 'hidden',- textOverflow: 'ellipsis',- whiteSpace: 'nowrap',+ <span style={{+ fontWeight: TYPOGRAPHY.BOLD,+ color: FINCEPT.WHITE,+ fontSize: TYPOGRAPHY.DEFAULT,}}>- {peer.name}- </p>+ {peer.symbol}+ </span>+ {peer.name && peer.name !== peer.symbol && (+ <p style={{+ fontSize: TYPOGRAPHY.SMALL,+ color: FINCEPT.GRAY,+ marginTop: SPACING.TINY,+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ }}>+ {peer.name}+ </p>+ )}</div><buttononClick={() => removePeer(peer.symbol)}@@ -730,57 +721,89 @@ export const PeerComparisonPanel: React.FC<PeerComparisonPanelProps> = ({ initia)}{viewMode === 'chart' && (- <div className="bg-gray-900 rounded-lg p-6 border border-gray-700">- <div className="flex items-center justify-between mb-4">- <h3 className="text-lg font-semibold text-white">Metric Comparison - Bar Charts</h3>- <p className="text-xs text-gray-400">+ <div style={{+ ...COMMON_STYLES.panel,+ padding: SPACING.XLARGE,+ }}>+ <div style={{+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ marginBottom: SPACING.LARGE,+ }}>+ <h3 style={{+ fontSize: TYPOGRAPHY.SUBHEADING,+ fontWeight: TYPOGRAPHY.BOLD,+ color: FINCEPT.WHITE,+ letterSpacing: TYPOGRAPHY.WIDE,+ textTransform: 'uppercase',+ }}>+ METRIC COMPARISON - BAR CHARTS+ </h3>+ <p style={{+ fontSize: TYPOGRAPHY.SMALL,+ color: FINCEPT.GRAY,+ }}>Compare key financial metrics across all companies</p></div>- <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">+ <div style={{+ display: 'grid',+ gridTemplateColumns: 'repeat(auto-fit, minmax(400px, 1fr))',+ gap: SPACING.LARGE,+ }}>{selectedMetrics.map((metric) => {const targetValue = getMetricValue(comparisonData.target, metric);const chartData = [{name: comparisonData.target.symbol,value: targetValue || 0,- fill: '#3b82f6', // Blue for target+ fill: FINCEPT.ORANGE,},...comparisonData.peers.map((peer, index) => ({name: peer.symbol,value: getMetricValue(peer, metric) || 0,- fill: `hsl(${(index * 360) / comparisonData.peers.length}, 70%, 50%)`,+ fill: [FINCEPT.CYAN, FINCEPT.GREEN, FINCEPT.YELLOW, FINCEPT.PURPLE, FINCEPT.BLUE][index % 5],})),];return (- <div key={metric} className="bg-gray-800 rounded-lg p-4">- <h4 className="text-sm font-semibold text-white mb-3">{metric}</h4>+ <div key={metric} style={{+ backgroundColor: FINCEPT.DARK_BG,+ border: BORDERS.STANDARD,+ padding: SPACING.LARGE,+ }}>+ <h4 style={{+ fontSize: TYPOGRAPHY.DEFAULT,+ fontWeight: TYPOGRAPHY.BOLD,+ color: FINCEPT.WHITE,+ marginBottom: SPACING.MEDIUM,+ }}>{metric}</h4><ResponsiveContainer width="100%" height={200}><ComposedChart data={chartData} layout="vertical">- <CartesianGrid strokeDasharray="3 3" stroke="#374151" />+ <CartesianGrid strokeDasharray="3 3" stroke={FINCEPT.BORDER} /><XAxistype="number"- stroke="#9ca3af"- tick={{ fill: '#9ca3af', fontSize: 11 }}+ stroke={FINCEPT.GRAY}+ tick={{ fill: FINCEPT.GRAY, fontSize: 11 }}/><YAxistype="category"dataKey="name"- stroke="#9ca3af"- tick={{ fill: '#9ca3af', fontSize: 11 }}+ stroke={FINCEPT.GRAY}+ tick={{ fill: FINCEPT.GRAY, fontSize: 11 }}width={80}/><TooltipcontentStyle={{- backgroundColor: '#1f2937',- border: '1px solid #374151',- borderRadius: '8px',- color: '#fff',+ backgroundColor: FINCEPT.PANEL_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ color: FINCEPT.WHITE,}}formatter={(value: any) => [value.toFixed(2), metric]}/>- <Bar dataKey="value" radius={[0, 4, 4, 0]} />+ <Bar dataKey="value" radius={[0, 2, 2, 0]} /></ComposedChart></ResponsiveContainer></div>@@ -791,31 +814,50 @@ export const PeerComparisonPanel: React.FC<PeerComparisonPanelProps> = ({ initia)}{viewMode === 'radar' && (- <div className="bg-gray-900 rounded-lg p-6 border border-gray-700">- <div className="flex items-center justify-between mb-4">- <h3 className="text-lg font-semibold text-white">Metric Comparison</h3>- <p className="text-xs text-gray-400">+ <div style={{+ ...COMMON_STYLES.panel,+ padding: SPACING.XLARGE,+ }}>+ <div style={{+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ marginBottom: SPACING.LARGE,+ }}>+ <h3 style={{+ fontSize: TYPOGRAPHY.SUBHEADING,+ fontWeight: TYPOGRAPHY.BOLD,+ color: FINCEPT.WHITE,+ letterSpacing: TYPOGRAPHY.WIDE,+ textTransform: 'uppercase',+ }}>+ METRIC COMPARISON+ </h3>+ <p style={{+ fontSize: TYPOGRAPHY.SMALL,+ color: FINCEPT.GRAY,+ }}>Values normalized 0-100 for visualization</p></div><ResponsiveContainer width="100%" height={400}><RadarChart data={radarData}>- <PolarGrid stroke="#374151" />+ <PolarGrid stroke={FINCEPT.BORDER} /><PolarAngleAxisdataKey="metric"- stroke="#9ca3af"- tick={{ fill: '#9ca3af', fontSize: 12 }}+ stroke={FINCEPT.GRAY}+ tick={{ fill: FINCEPT.GRAY, fontSize: 12 }}/><PolarRadiusAxis- stroke="#9ca3af"- tick={{ fill: '#6b7280', fontSize: 10 }}+ stroke={FINCEPT.GRAY}+ tick={{ fill: FINCEPT.MUTED, fontSize: 10 }}domain={[0, 100]}/><Radarname={comparisonData.target.symbol}dataKey="target"- stroke="#3b82f6"- fill="#3b82f6"+ stroke={FINCEPT.ORANGE}+ fill={FINCEPT.ORANGE}fillOpacity={0.3}strokeWidth={2}/>@@ -824,19 +866,19 @@ export const PeerComparisonPanel: React.FC<PeerComparisonPanelProps> = ({ initiakey={peer.symbol}name={peer.symbol}dataKey={`peer${index + 1}`}- stroke={`hsl(${(index * 360) / comparisonData.peers.length}, 70%, 50%)`}- fill={`hsl(${(index * 360) / comparisonData.peers.length}, 70%, 50%)`}+ stroke={[FINCEPT.CYAN, FINCEPT.GREEN, FINCEPT.YELLOW, FINCEPT.PURPLE, FINCEPT.BLUE][index % 5]}+ fill={[FINCEPT.CYAN, FINCEPT.GREEN, FINCEPT.YELLOW, FINCEPT.PURPLE, FINCEPT.BLUE][index % 5]}fillOpacity={0.1}strokeWidth={2}/>))}- <Legend wrapperStyle={{ paddingTop: '20px' }} />+ <Legend wrapperStyle={{ paddingTop: '20px', color: FINCEPT.WHITE }} /><TooltipcontentStyle={{- backgroundColor: '#1f2937',- border: '1px solid #374151',- borderRadius: '8px',- color: '#fff'+ backgroundColor: FINCEPT.PANEL_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ color: FINCEPT.WHITE,}}formatter={(value: any, name: string, props: any) => {// Show original value in tooltip@@ -851,29 +893,55 @@ export const PeerComparisonPanel: React.FC<PeerComparisonPanelProps> = ({ initia)}{/* Percentile Rankings Section */}- <div className="mt-6 bg-gray-900 rounded-lg p-6 border border-gray-700">- <div className="flex items-start justify-between mb-4">+ <div style={{+ ...COMMON_STYLES.panel,+ padding: SPACING.XLARGE,+ marginTop: SPACING.LARGE,+ }}>+ <div style={{+ display: 'flex',+ alignItems: 'flex-start',+ justifyContent: 'space-between',+ marginBottom: SPACING.LARGE,+ }}><div>- <h3 className="text-lg font-semibold text-white mb-2">Percentile Rankings</h3>- <p className="text-sm text-gray-400">+ <h3 style={{+ fontSize: TYPOGRAPHY.SUBHEADING,+ fontWeight: TYPOGRAPHY.BOLD,+ color: FINCEPT.WHITE,+ marginBottom: SPACING.SMALL,+ letterSpacing: TYPOGRAPHY.WIDE,+ textTransform: 'uppercase',+ }}>+ PERCENTILE RANKINGS+ </h3>+ <p style={{+ fontSize: TYPOGRAPHY.BODY,+ color: FINCEPT.GRAY,+ }}>{comparisonData.target.symbol}'s position within selected peer group</p></div>{comparisonData.peers.length < 5 && (- <div className="bg-yellow-900/20 border border-yellow-700 rounded-lg px-3 py-2 max-w-md">- <div className="flex items-start gap-2">- <svg className="w-5 h-5 text-yellow-400 flex-shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">+ <div style={{+ backgroundColor: `${FINCEPT.YELLOW}15`,+ border: `1px solid ${FINCEPT.YELLOW}`,+ padding: `${SPACING.SMALL} ${SPACING.MEDIUM}`,+ maxWidth: '400px',+ }}>+ <div style={{ display: 'flex', alignItems: 'flex-start', gap: SPACING.SMALL }}>+ <svg style={{ width: '16px', height: '16px', color: FINCEPT.YELLOW, flexShrink: 0, marginTop: '2px' }} fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" /></svg>- <div className="text-xs text-yellow-400">- <p className="font-semibold mb-1">Limited Peer Sample</p>+ <div style={{ fontSize: TYPOGRAPHY.SMALL, color: FINCEPT.YELLOW }}>+ <p style={{ fontWeight: TYPOGRAPHY.BOLD, marginBottom: SPACING.TINY }}>LIMITED PEER SAMPLE</p><p>Add more peers (5-10 recommended) for statistically significant percentile rankings. With only {comparisonData.peers.length} {comparisonData.peers.length === 1 ? 'peer' : 'peers'}, percentiles will only show 0%, 50%, or 100%.</p></div></div></div>)}</div>- <div className="space-y-4">+ <div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.LARGE }}>{selectedMetrics.map((metric) => {const targetValue = getMetricValue(comparisonData.target, metric);const peerValues = comparisonData.peers.map((p) => getMetricValue(p, metric)).filter(v => v !== undefined) as number[];@@ -935,20 +1003,35 @@ const ComparisonTable: React.FC<ComparisonTableProps> = ({const allMetrics = getAllMetricNames(target);return (- <div className="bg-gray-900 rounded-lg border border-gray-700 overflow-hidden">+ <div style={{+ ...COMMON_STYLES.panel,+ padding: 0,+ overflow: 'hidden',+ }}>{/* Metric Selector */}- <div className="p-4 border-b border-gray-700">- <h4 className="text-sm font-medium text-gray-400 mb-2">Select Metrics</h4>- <div className="flex flex-wrap gap-2">+ <div style={{+ padding: SPACING.LARGE,+ borderBottom: BORDERS.STANDARD,+ }}>+ <h4 style={{+ ...COMMON_STYLES.dataLabel,+ marginBottom: SPACING.MEDIUM,+ }}>SELECT METRICS</h4>+ <div style={{ display: 'flex', flexWrap: 'wrap', gap: SPACING.SMALL }}>{allMetrics.map((metric) => (<buttonkey={metric}onClick={() => onToggleMetric(metric)}- className={`px-3 py-1 text-sm rounded transition-colors ${- selectedMetrics.includes(metric)- ? 'bg-blue-600 text-white'- : 'bg-gray-800 text-gray-400 hover:bg-gray-700'- }`}+ style={{+ padding: `${SPACING.SMALL} ${SPACING.MEDIUM}`,+ fontSize: TYPOGRAPHY.BODY,+ backgroundColor: selectedMetrics.includes(metric) ? FINCEPT.ORANGE : FINCEPT.DARK_BG,+ border: `1px solid ${selectedMetrics.includes(metric) ? FINCEPT.ORANGE : FINCEPT.BORDER}`,+ color: selectedMetrics.includes(metric) ? FINCEPT.DARK_BG : FINCEPT.GRAY,+ cursor: 'pointer',+ transition: 'all 0.2s',+ fontWeight: selectedMetrics.includes(metric) ? TYPOGRAPHY.BOLD : TYPOGRAPHY.REGULAR,+ }}>{metric}</button>@@ -957,28 +1040,40 @@ const ComparisonTable: React.FC<ComparisonTableProps> = ({</div>{/* Table */}- <div className="overflow-x-auto">- <table className="min-w-full divide-y divide-gray-700">- <thead className="bg-gray-800">- <tr>- <th className="px-4 py-3 text-left text-xs font-medium text-gray-400 uppercase">- Metric+ <div style={{ overflowX: 'auto' }}>+ <table style={{ width: '100%', borderCollapse: 'collapse' }}>+ <thead>+ <tr style={{ backgroundColor: FINCEPT.HEADER_BG }}>+ <th style={{+ ...COMMON_STYLES.tableHeader,+ padding: SPACING.MEDIUM,+ }}>+ METRIC</th>- <th className="px-4 py-3 text-right text-xs font-medium text-blue-400 uppercase">- {target.symbol} (Target)+ <th style={{+ ...COMMON_STYLES.tableHeader,+ padding: SPACING.MEDIUM,+ textAlign: 'right',+ color: FINCEPT.ORANGE,+ }}>+ {target.symbol} (TARGET)</th>{peers.map((peer) => (<thkey={peer.symbol}- className="px-4 py-3 text-right text-xs font-medium text-gray-400 uppercase"+ style={{+ ...COMMON_STYLES.tableHeader,+ padding: SPACING.MEDIUM,+ textAlign: 'right',+ }}>{peer.symbol}</th>))}</tr></thead>- <tbody className="divide-y divide-gray-800">- {selectedMetrics.map((metric) => {+ <tbody>+ {selectedMetrics.map((metric, idx) => {const targetValue = getMetricValue(target, metric);const peerValues = peers.map((p) => getMetricValue(p, metric));const allValues = [targetValue, ...peerValues].filter((v) => v !== undefined) as number[];@@ -986,21 +1081,43 @@ const ComparisonTable: React.FC<ComparisonTableProps> = ({const min = Math.min(...allValues);return (- <tr key={metric} className="hover:bg-gray-800 transition-colors">- <td className="px-4 py-3 whitespace-nowrap text-sm font-medium text-white">+ <tr+ key={metric}+ style={{+ borderBottom: BORDERS.STANDARD,+ backgroundColor: idx % 2 === 0 ? 'transparent' : 'rgba(255,255,255,0.02)',+ transition: 'background-color 0.2s',+ }}+ >+ <td style={{+ padding: SPACING.MEDIUM,+ whiteSpace: 'nowrap',+ fontSize: TYPOGRAPHY.BODY,+ fontWeight: TYPOGRAPHY.BOLD,+ color: FINCEPT.WHITE,+ }}>{metric}</td>- <td className="px-4 py-3 whitespace-nowrap text-sm text-right">- <span- className={`font-semibold ${- targetValue === max ? 'text-green-400' : targetValue === min ? 'text-red-400' : 'text-blue-400'- }`}- >- {formatMetricValue(targetValue, 'ratio')}- </span>+ <td style={{+ padding: SPACING.MEDIUM,+ whiteSpace: 'nowrap',+ fontSize: TYPOGRAPHY.BODY,+ textAlign: 'right',+ fontWeight: TYPOGRAPHY.SEMIBOLD,+ fontFamily: TYPOGRAPHY.MONO,+ color: targetValue === max ? FINCEPT.GREEN : targetValue === min ? FINCEPT.RED : FINCEPT.CYAN,+ }}>+ {formatMetricValue(targetValue, 'ratio')}</td>{peerValues.map((value, index) => (- <td key={index} className="px-4 py-3 whitespace-nowrap text-sm text-right text-gray-300">+ <td key={index} style={{+ padding: SPACING.MEDIUM,+ whiteSpace: 'nowrap',+ fontSize: TYPOGRAPHY.BODY,+ textAlign: 'right',+ fontFamily: TYPOGRAPHY.MONO,+ color: FINCEPT.GRAY,+ }}>{formatMetricValue(value, 'ratio')}</td>))}diff --git a/fincept-terminal-desktop/src/components/tabs/equity-research/components/PercentileRankChart.tsx b/fincept-terminal-desktop/src/components/tabs/equity-research/components/PercentileRankChart.tsxindex e8269ef72..8e0ec42cd 100644--- a/fincept-terminal-desktop/src/components/tabs/equity-research/components/PercentileRankChart.tsx+++ b/fincept-terminal-desktop/src/components/tabs/equity-research/components/PercentileRankChart.tsx@@ -5,6 +5,7 @@ import React from 'react';import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer, Cell } from 'recharts';import type { PercentileRanking } from '../../../../types/peer';import { getPercentileColor } from '../../../../types/peer';+import { FINCEPT, TYPOGRAPHY, SPACING, BORDERS, COMMON_STYLES } from '../../portfolio-tab/finceptStyles';interface PercentileRankChartProps {rankings: PercentileRanking[];@@ -33,20 +34,24 @@ export const PercentileRankChart: React.FC<PercentileRankChartProps> = ({if (active && payload && payload.length) {const data = payload[0].payload;return (- <div className="bg-gray-900 border border-gray-700 rounded-lg p-3 shadow-lg">- <p className="text-white font-semibold mb-2">{data.metric}</p>- <div className="space-y-1 text-sm">- <p className="text-blue-400">- Percentile: <span className="font-semibold">{data.percentile.toFixed(1)}%</span>+ <div style={{+ backgroundColor: FINCEPT.PANEL_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ padding: SPACING.MEDIUM,+ }}>+ <p style={{ color: FINCEPT.WHITE, fontWeight: TYPOGRAPHY.BOLD, marginBottom: SPACING.SMALL }}>{data.metric}</p>+ <div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.TINY, fontSize: TYPOGRAPHY.BODY }}>+ <p style={{ color: FINCEPT.CYAN }}>+ Percentile: <span style={{ fontWeight: TYPOGRAPHY.BOLD }}>{data.percentile.toFixed(1)}%</span></p>- <p className="text-green-400">- Value: <span className="font-semibold">{data.value.toFixed(2)}</span>+ <p style={{ color: FINCEPT.GREEN }}>+ Value: <span style={{ fontWeight: TYPOGRAPHY.BOLD }}>{data.value.toFixed(2)}</span></p>- <p className="text-yellow-400">- Peer Median: <span className="font-semibold">{data.median.toFixed(2)}</span>+ <p style={{ color: FINCEPT.YELLOW }}>+ Peer Median: <span style={{ fontWeight: TYPOGRAPHY.BOLD }}>{data.median.toFixed(2)}</span></p>- <p className="text-purple-400">- Z-Score: <span className="font-semibold">{data.zScore.toFixed(2)}</span>+ <p style={{ color: FINCEPT.PURPLE }}>+ Z-Score: <span style={{ fontWeight: TYPOGRAPHY.BOLD }}>{data.zScore.toFixed(2)}</span></p></div></div>@@ -57,20 +62,27 @@ export const PercentileRankChart: React.FC<PercentileRankChartProps> = ({if (orientation === 'horizontal') {return (- <div className="w-full">- {title && <h3 className="text-lg font-semibold text-white mb-4">{title}</h3>}+ <div style={{ width: '100%' }}>+ {title && <h3 style={{+ fontSize: TYPOGRAPHY.SUBHEADING,+ fontWeight: TYPOGRAPHY.BOLD,+ color: FINCEPT.WHITE,+ marginBottom: SPACING.LARGE,+ letterSpacing: TYPOGRAPHY.WIDE,+ textTransform: 'uppercase',+ }}>{title}</h3>}<ResponsiveContainer width="100%" height={height}><BarChartdata={chartData}layout="vertical"margin={{ top: 5, right: 30, left: 100, bottom: 5 }}>- <CartesianGrid strokeDasharray="3 3" stroke="#374151" />- <XAxis type="number" domain={[0, 100]} stroke="#9ca3af" />- <YAxis dataKey="metric" type="category" stroke="#9ca3af" width={90} />+ <CartesianGrid strokeDasharray="3 3" stroke={FINCEPT.BORDER} />+ <XAxis type="number" domain={[0, 100]} stroke={FINCEPT.GRAY} />+ <YAxis dataKey="metric" type="category" stroke={FINCEPT.GRAY} width={90} /><Tooltip content={<CustomTooltip />} /><Legend />- <Bar dataKey="percentile" name="Percentile Rank" radius={[0, 4, 4, 0]}>+ <Bar dataKey="percentile" name="Percentile Rank" radius={[0, 2, 2, 0]}>{chartData.map((entry, index) => (<Cell key={`cell-${index}`} fill={getPercentileColor(entry.percentile)} />))}@@ -83,25 +95,32 @@ export const PercentileRankChart: React.FC<PercentileRankChartProps> = ({// Vertical orientationreturn (- <div className="w-full">- {title && <h3 className="text-lg font-semibold text-white mb-4">{title}</h3>}+ <div style={{ width: '100%' }}>+ {title && <h3 style={{+ fontSize: TYPOGRAPHY.SUBHEADING,+ fontWeight: TYPOGRAPHY.BOLD,+ color: FINCEPT.WHITE,+ marginBottom: SPACING.LARGE,+ letterSpacing: TYPOGRAPHY.WIDE,+ textTransform: 'uppercase',+ }}>{title}</h3>}<ResponsiveContainer width="100%" height={height}><BarChartdata={chartData}margin={{ top: 5, right: 30, left: 20, bottom: 100 }}>- <CartesianGrid strokeDasharray="3 3" stroke="#374151" />+ <CartesianGrid strokeDasharray="3 3" stroke={FINCEPT.BORDER} /><XAxisdataKey="metric"- stroke="#9ca3af"+ stroke={FINCEPT.GRAY}angle={-45}textAnchor="end"height={100}/>- <YAxis domain={[0, 100]} stroke="#9ca3af" />+ <YAxis domain={[0, 100]} stroke={FINCEPT.GRAY} /><Tooltip content={<CustomTooltip />} /><Legend />- <Bar dataKey="percentile" name="Percentile Rank" radius={[4, 4, 0, 0]}>+ <Bar dataKey="percentile" name="Percentile Rank" radius={[2, 2, 0, 0]}>{chartData.map((entry, index) => (<Cell key={`cell-${index}`} fill={getPercentileColor(entry.percentile)} />))}@@ -138,23 +157,49 @@ export const PercentileRankMini: React.FC<{ ranking: PercentileRanking }> = ({ r}return (- <div className="space-y-1">- <div className="flex justify-between items-center text-sm">- <span className="text-gray-400">{ranking.metricName}</span>- <div className="flex items-center gap-2">- <span className="text-white font-semibold">{ranking.percentile !== null && ranking.percentile !== undefined ? ranking.percentile.toFixed(1) : 'N/A'}%</span>- <span className="text-xs text-gray-500">({interpretation})</span>+ <div style={{+ backgroundColor: FINCEPT.DARK_BG,+ border: BORDERS.STANDARD,+ padding: SPACING.MEDIUM,+ }}>+ <div style={{+ display: 'flex',+ justifyContent: 'space-between',+ alignItems: 'center',+ fontSize: TYPOGRAPHY.BODY,+ marginBottom: SPACING.SMALL,+ }}>+ <span style={{ color: FINCEPT.WHITE, fontWeight: TYPOGRAPHY.BOLD }}>{ranking.metricName}</span>+ <div style={{ display: 'flex', alignItems: 'center', gap: SPACING.SMALL }}>+ <span style={{ color, fontWeight: TYPOGRAPHY.BOLD, fontFamily: TYPOGRAPHY.MONO }}>+ {ranking.percentile !== null && ranking.percentile !== undefined ? ranking.percentile.toFixed(1) : 'N/A'}%+ </span>+ <span style={{ fontSize: TYPOGRAPHY.SMALL, color: FINCEPT.GRAY }}>({interpretation})</span></div></div>- <div className="w-full bg-gray-700 rounded-full h-2">+ <div style={{+ width: '100%',+ backgroundColor: FINCEPT.BORDER,+ height: '6px',+ marginBottom: SPACING.SMALL,+ }}><div- className="h-2 rounded-full transition-all duration-300"- style={{ width, backgroundColor: color }}+ style={{+ height: '6px',+ transition: 'all 0.3s',+ width,+ backgroundColor: color,+ }}/></div>- <div className="flex justify-between text-xs text-gray-500">- <span>Value: {ranking.value !== null && ranking.value !== undefined ? ranking.value.toFixed(2) : 'N/A'}</span>- <span>Median: {ranking.peerMedian !== null && ranking.peerMedian !== undefined ? ranking.peerMedian.toFixed(2) : 'N/A'}</span>+ <div style={{+ display: 'flex',+ justifyContent: 'space-between',+ fontSize: TYPOGRAPHY.SMALL,+ color: FINCEPT.GRAY,+ }}>+ <span>Value: <span style={{ color: FINCEPT.CYAN, fontFamily: TYPOGRAPHY.MONO }}>{ranking.value !== null && ranking.value !== undefined ? ranking.value.toFixed(2) : 'N/A'}</span></span>+ <span>Median: <span style={{ color: FINCEPT.YELLOW, fontFamily: TYPOGRAPHY.MONO }}>{ranking.peerMedian !== null && ranking.peerMedian !== undefined ? ranking.peerMedian.toFixed(2) : 'N/A'}</span></span></div></div>);@@ -167,64 +212,112 @@ interface PercentileTableProps {export const PercentileTable: React.FC<PercentileTableProps> = ({ rankings }) => {return (- <div className="overflow-x-auto">- <table className="min-w-full divide-y divide-gray-700">- <thead className="bg-gray-800">- <tr>- <th className="px-4 py-3 text-left text-xs font-medium text-gray-400 uppercase tracking-wider">- Metric+ <div style={{ overflowX: 'auto' }}>+ <table style={{ width: '100%', borderCollapse: 'collapse' }}>+ <thead>+ <tr style={{ backgroundColor: FINCEPT.HEADER_BG }}>+ <th style={{ ...COMMON_STYLES.tableHeader, padding: SPACING.MEDIUM }}>+ METRIC</th>- <th className="px-4 py-3 text-right text-xs font-medium text-gray-400 uppercase tracking-wider">- Value+ <th style={{ ...COMMON_STYLES.tableHeader, padding: SPACING.MEDIUM, textAlign: 'right' }}>+ VALUE</th>- <th className="px-4 py-3 text-right text-xs font-medium text-gray-400 uppercase tracking-wider">- Percentile+ <th style={{ ...COMMON_STYLES.tableHeader, padding: SPACING.MEDIUM, textAlign: 'right' }}>+ PERCENTILE</th>- <th className="px-4 py-3 text-right text-xs font-medium text-gray-400 uppercase tracking-wider">- Z-Score+ <th style={{ ...COMMON_STYLES.tableHeader, padding: SPACING.MEDIUM, textAlign: 'right' }}>+ Z-SCORE</th>- <th className="px-4 py-3 text-right text-xs font-medium text-gray-400 uppercase tracking-wider">- Peer Median+ <th style={{ ...COMMON_STYLES.tableHeader, padding: SPACING.MEDIUM, textAlign: 'right' }}>+ PEER MEDIAN</th>- <th className="px-4 py-3 text-right text-xs font-medium text-gray-400 uppercase tracking-wider">- Status+ <th style={{ ...COMMON_STYLES.tableHeader, padding: SPACING.MEDIUM, textAlign: 'right' }}>+ STATUS</th></tr></thead>- <tbody className="bg-gray-900 divide-y divide-gray-800">+ <tbody>{rankings.map((ranking, index) => {const color = getPercentileColor(ranking.percentile);const status =- ranking.percentile >= 75 ? 'Excellent' :- ranking.percentile >= 50 ? 'Above Average' :- ranking.percentile >= 25 ? 'Below Average' :- 'Poor';+ ranking.percentile >= 75 ? 'EXCELLENT' :+ ranking.percentile >= 50 ? 'ABOVE AVG' :+ ranking.percentile >= 25 ? 'BELOW AVG' :+ 'POOR';return (- <tr key={index} className="hover:bg-gray-800 transition-colors">- <td className="px-4 py-3 whitespace-nowrap text-sm font-medium text-white">+ <tr+ key={index}+ style={{+ borderBottom: BORDERS.STANDARD,+ backgroundColor: index % 2 === 0 ? 'transparent' : 'rgba(255,255,255,0.02)',+ transition: 'background-color 0.2s',+ }}+ >+ <td style={{+ padding: SPACING.MEDIUM,+ whiteSpace: 'nowrap',+ fontSize: TYPOGRAPHY.BODY,+ fontWeight: TYPOGRAPHY.BOLD,+ color: FINCEPT.WHITE,+ }}>{ranking.metricName}</td>- <td className="px-4 py-3 whitespace-nowrap text-sm text-right text-gray-300">+ <td style={{+ padding: SPACING.MEDIUM,+ whiteSpace: 'nowrap',+ fontSize: TYPOGRAPHY.BODY,+ textAlign: 'right',+ color: FINCEPT.GRAY,+ fontFamily: TYPOGRAPHY.MONO,+ }}>{ranking.value.toFixed(2)}</td>- <td className="px-4 py-3 whitespace-nowrap text-sm text-right">- <span className="font-semibold" style={{ color }}>- {ranking.percentile.toFixed(1)}%- </span>+ <td style={{+ padding: SPACING.MEDIUM,+ whiteSpace: 'nowrap',+ fontSize: TYPOGRAPHY.BODY,+ textAlign: 'right',+ fontWeight: TYPOGRAPHY.BOLD,+ fontFamily: TYPOGRAPHY.MONO,+ color,+ }}>+ {ranking.percentile.toFixed(1)}%</td>- <td className="px-4 py-3 whitespace-nowrap text-sm text-right text-gray-300">+ <td style={{+ padding: SPACING.MEDIUM,+ whiteSpace: 'nowrap',+ fontSize: TYPOGRAPHY.BODY,+ textAlign: 'right',+ color: FINCEPT.GRAY,+ fontFamily: TYPOGRAPHY.MONO,+ }}>{ranking.zScore.toFixed(2)}</td>- <td className="px-4 py-3 whitespace-nowrap text-sm text-right text-gray-400">+ <td style={{+ padding: SPACING.MEDIUM,+ whiteSpace: 'nowrap',+ fontSize: TYPOGRAPHY.BODY,+ textAlign: 'right',+ color: FINCEPT.MUTED,+ fontFamily: TYPOGRAPHY.MONO,+ }}>{ranking.peerMedian.toFixed(2)}</td>- <td className="px-4 py-3 whitespace-nowrap text-sm text-right">+ <td style={{+ padding: SPACING.MEDIUM,+ whiteSpace: 'nowrap',+ fontSize: TYPOGRAPHY.BODY,+ textAlign: 'right',+ }}><span- className="px-2 py-1 rounded-full text-xs font-medium"style={{+ padding: `${SPACING.TINY} ${SPACING.SMALL}`,+ fontSize: TYPOGRAPHY.SMALL,+ fontWeight: TYPOGRAPHY.BOLD,backgroundColor: `${color}20`,color: color,+ border: `1px solid ${color}`,}}>{status}diff --git a/fincept-terminal-desktop/src/components/tabs/equity-research/tabs/AnalysisTab.tsx b/fincept-terminal-desktop/src/components/tabs/equity-research/tabs/AnalysisTab.tsxindex 699aafc5b..bcbfc20b9 100644--- a/fincept-terminal-desktop/src/components/tabs/equity-research/tabs/AnalysisTab.tsx+++ b/fincept-terminal-desktop/src/components/tabs/equity-research/tabs/AnalysisTab.tsx@@ -35,6 +35,7 @@ export const AnalysisTab: React.FC<AnalysisTabProps> = ({<FinancialAnalysisPanelticker={currentSymbol}companyName={stockInfo?.company_name || currentSymbol}+ stockInfo={stockInfo}/></div>diff --git a/fincept-terminal-desktop/src/components/tabs/equity-research/tabs/FinancialsTab.tsx b/fincept-terminal-desktop/src/components/tabs/equity-research/tabs/FinancialsTab.tsxindex 504fb3e20..88fbcf975 100644--- a/fincept-terminal-desktop/src/components/tabs/equity-research/tabs/FinancialsTab.tsx+++ b/fincept-terminal-desktop/src/components/tabs/equity-research/tabs/FinancialsTab.tsx@@ -1,8 +1,20 @@-import React, { useState, useRef, useEffect } from 'react';-import { createChart, LineSeries } from 'lightweight-charts';-import { FINCEPT } from '../../portfolio-tab/finceptStyles';-import { formatNumber, formatLargeNumber, getYearFromPeriod } from '../utils/formatters';-import type { FinancialsData } from '../types';+import React, { useState, useMemo } from 'react';+import {+ BarChart, Bar, LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip,+ ResponsiveContainer, ComposedChart, ReferenceLine, Cell, PieChart, Pie,+ AreaChart, Area, RadarChart, Radar, PolarGrid, PolarAngleAxis, PolarRadiusAxis,+ Treemap, Legend+} from 'recharts';+import { FINCEPT, TYPOGRAPHY, BORDERS } from '../../portfolio-tab/finceptStyles';+import { formatLargeNumber, getYearFromPeriod } from '../utils/formatters';+import type { FinancialsData, StockInfo } from '../types';+import {+ DollarSign, CreditCard, ArrowUpRight, ArrowDownRight, TrendingUp, TrendingDown,+ Building2, Banknote, Receipt, CircleDollarSign, Landmark, PiggyBank,+ ChevronDown, ChevronRight, AlertTriangle, CheckCircle, XCircle, Info,+ BarChart3, PieChart as PieChartIcon, Activity, Wallet, Scale, Percent,+ ArrowRight, Zap, Target, Shield, Clock, Layers+} from 'lucide-react';const COLORS = {ORANGE: FINCEPT.ORANGE,@@ -11,526 +23,1289 @@ const COLORS = {GREEN: FINCEPT.GREEN,YELLOW: FINCEPT.YELLOW,GRAY: FINCEPT.GRAY,+ MUTED: FINCEPT.MUTED,BLUE: FINCEPT.BLUE,CYAN: FINCEPT.CYAN,DARK_BG: FINCEPT.DARK_BG,PANEL_BG: FINCEPT.PANEL_BG,+ HEADER_BG: FINCEPT.HEADER_BG,+ HOVER: FINCEPT.HOVER,BORDER: FINCEPT.BORDER,- MAGENTA: '#FF00FF',+ PURPLE: FINCEPT.PURPLE,};+const CHART_COLORS = [COLORS.GREEN, COLORS.CYAN, COLORS.ORANGE, COLORS.YELLOW, COLORS.PURPLE, COLORS.BLUE, COLORS.RED];+interface FinancialsTabProps {financials: FinancialsData | null;+ stockInfo?: StockInfo | null;loading: boolean;}+// Helper functions+const formatPercent = (value: number | null | undefined): string => {+ if (value === null || value === undefined || isNaN(value)) return 'N/A';+ return `${(value * 100).toFixed(1)}%`;+};++const formatCurrency = (value: number | null | undefined): string => {+ if (value === null || value === undefined || isNaN(value)) return 'N/A';+ const absValue = Math.abs(value);+ const sign = value < 0 ? '-' : '';+ if (absValue >= 1e12) return `${sign}$${(absValue / 1e12).toFixed(2)}T`;+ if (absValue >= 1e9) return `${sign}$${(absValue / 1e9).toFixed(2)}B`;+ if (absValue >= 1e6) return `${sign}$${(absValue / 1e6).toFixed(2)}M`;+ if (absValue >= 1e3) return `${sign}$${(absValue / 1e3).toFixed(2)}K`;+ return `${sign}$${absValue.toFixed(2)}`;+};++const formatRatio = (value: number | null | undefined): string => {+ if (value === null || value === undefined || isNaN(value)) return 'N/A';+ return `${value.toFixed(2)}x`;+};++const getHealthColor = (value: number, thresholds: { good: number; warning: number }, higherIsBetter: boolean = true): string => {+ if (higherIsBetter) {+ if (value >= thresholds.good) return COLORS.GREEN;+ if (value >= thresholds.warning) return COLORS.YELLOW;+ return COLORS.RED;+ } else {+ if (value <= thresholds.good) return COLORS.GREEN;+ if (value <= thresholds.warning) return COLORS.YELLOW;+ return COLORS.RED;+ }+};++const calculateGrowth = (current: number, previous: number): number | null => {+ if (!previous || previous === 0) return null;+ return ((current - previous) / Math.abs(previous)) * 100;+};++// ===== REUSABLE COMPONENTS =====++// Metric Card with proper sizing+const MetricCard: React.FC<{+ label: string;+ value: string | number;+ change?: number | null;+ color?: string;+ icon?: React.ReactNode;+ subtitle?: string;+ trend?: 'up' | 'down' | 'neutral';+ size?: 'small' | 'medium' | 'large';+}> = ({ label, value, change, color = COLORS.WHITE, icon, subtitle, trend, size = 'medium' }) => {+ const TrendIcon = trend === 'up' ? ArrowUpRight : trend === 'down' ? ArrowDownRight : null;+ const trendColor = trend === 'up' ? COLORS.GREEN : trend === 'down' ? COLORS.RED : COLORS.GRAY;++ const padding = size === 'small' ? '10px' : size === 'large' ? '16px' : '12px';+ const labelSize = size === 'small' ? '10px' : size === 'large' ? '12px' : '11px';+ const valueSize = size === 'small' ? '16px' : size === 'large' ? '24px' : '20px';++ return (+ <div style={{+ backgroundColor: COLORS.DARK_BG,+ border: BORDERS.STANDARD,+ borderLeft: `3px solid ${color}`,+ padding: padding,+ minHeight: size === 'large' ? '90px' : '70px',+ display: 'flex',+ flexDirection: 'column',+ justifyContent: 'space-between',+ }}>+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '6px' }}>+ <span style={{ color: COLORS.GRAY, fontSize: labelSize, textTransform: 'uppercase', fontWeight: 600 }}>{label}</span>+ {icon && <span style={{ color: color, opacity: 0.8 }}>{icon}</span>}+ </div>+ <div style={{ color: color, fontSize: valueSize, fontWeight: 700, fontFamily: TYPOGRAPHY.MONO }}>{value}</div>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginTop: '4px' }}>+ {(change !== undefined && change !== null) && (+ <div style={{ display: 'flex', alignItems: 'center', gap: '3px' }}>+ {TrendIcon && <TrendIcon size={12} color={trendColor} />}+ <span style={{ color: trendColor, fontSize: '11px', fontWeight: 600 }}>+ {change >= 0 ? '+' : ''}{change.toFixed(1)}% YoY+ </span>+ </div>+ )}+ {subtitle && <span style={{ color: COLORS.MUTED, fontSize: '10px' }}>{subtitle}</span>}+ </div>+ </div>+ );+};++// Health Score with visual bar+const HealthScore: React.FC<{+ label: string;+ value: number;+ max?: number;+ thresholds: { good: number; warning: number };+ higherIsBetter?: boolean;+ format?: 'percent' | 'ratio' | 'number';+ description?: string;+}> = ({ label, value, max = 100, thresholds, higherIsBetter = true, format = 'number', description }) => {+ const healthColor = getHealthColor(value, thresholds, higherIsBetter);+ const percentage = Math.min(100, Math.max(0, (Math.abs(value) / max) * 100));++ let displayValue = value.toFixed(2);+ if (format === 'percent') displayValue = `${(value * 100).toFixed(1)}%`;+ if (format === 'ratio') displayValue = `${value.toFixed(2)}x`;++ return (+ <div style={{ backgroundColor: COLORS.DARK_BG, border: BORDERS.STANDARD, padding: '12px' }}>+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '8px' }}>+ <span style={{ color: COLORS.WHITE, fontSize: '12px', fontWeight: 600 }}>{label}</span>+ <span style={{ color: healthColor, fontSize: '16px', fontWeight: 700, fontFamily: TYPOGRAPHY.MONO }}>{displayValue}</span>+ </div>+ <div style={{ height: '6px', backgroundColor: COLORS.PANEL_BG, borderRadius: '3px', overflow: 'hidden' }}>+ <div style={{+ width: `${percentage}%`,+ height: '100%',+ backgroundColor: healthColor,+ borderRadius: '3px',+ transition: 'width 0.3s ease'+ }} />+ </div>+ {description && <div style={{ color: COLORS.MUTED, fontSize: '10px', marginTop: '6px' }}>{description}</div>}+ </div>+ );+};++// Section Panel with collapsible content+const SectionPanel: React.FC<{+ title: string;+ color: string;+ icon: React.ReactNode;+ children: React.ReactNode;+ defaultExpanded?: boolean;+ subtitle?: string;+}> = ({ title, color, icon, children, defaultExpanded = true, subtitle }) => {+ const [expanded, setExpanded] = useState(defaultExpanded);++ return (+ <div style={{ backgroundColor: COLORS.PANEL_BG, border: BORDERS.STANDARD, marginBottom: '16px', borderRadius: '4px', overflow: 'hidden' }}>+ <div+ onClick={() => setExpanded(!expanded)}+ style={{+ backgroundColor: COLORS.HEADER_BG,+ padding: '12px 16px',+ borderBottom: expanded ? `2px solid ${color}` : 'none',+ display: 'flex',+ alignItems: 'center',+ gap: '10px',+ cursor: 'pointer',+ }}+ >+ {expanded ? <ChevronDown size={16} color={color} /> : <ChevronRight size={16} color={color} />}+ {icon}+ <div style={{ flex: 1 }}>+ <span style={{ color: color, fontSize: '13px', fontWeight: 700, textTransform: 'uppercase' }}>{title}</span>+ {subtitle && <span style={{ color: COLORS.MUTED, fontSize: '11px', marginLeft: '12px' }}>{subtitle}</span>}+ </div>+ </div>+ {expanded && <div style={{ padding: '16px' }}>{children}</div>}+ </div>+ );+};++// Chart Wrapper for consistent styling+const ChartWrapper: React.FC<{+ title: string;+ color: string;+ height?: number;+ children: React.ReactNode;+}> = ({ title, color, height = 220, children }) => (+ <div style={{ backgroundColor: COLORS.DARK_BG, border: BORDERS.STANDARD, borderRadius: '4px', overflow: 'hidden' }}>+ <div style={{+ padding: '10px 14px',+ borderBottom: `2px solid ${color}`,+ backgroundColor: COLORS.HEADER_BG+ }}>+ <span style={{ color: color, fontSize: '12px', fontWeight: 700, textTransform: 'uppercase' }}>{title}</span>+ </div>+ <div style={{ padding: '12px', height: height }}>+ {children}+ </div>+ </div>+);++// Custom Tooltip for charts+const CustomTooltip: React.FC<any> = ({ active, payload, label, formatter }) => {+ if (!active || !payload?.length) return null;+ return (+ <div style={{+ backgroundColor: COLORS.DARK_BG,+ border: BORDERS.STANDARD,+ padding: '10px 14px',+ borderRadius: '4px',+ boxShadow: '0 4px 12px rgba(0,0,0,0.3)'+ }}>+ <div style={{ color: COLORS.WHITE, fontSize: '12px', fontWeight: 600, marginBottom: '6px' }}>{label}</div>+ {payload.map((entry: any, idx: number) => (+ <div key={idx} style={{ display: 'flex', alignItems: 'center', gap: '8px', marginTop: '4px' }}>+ <div style={{ width: '10px', height: '10px', backgroundColor: entry.color, borderRadius: '2px' }} />+ <span style={{ color: COLORS.GRAY, fontSize: '11px' }}>{entry.name}:</span>+ <span style={{ color: entry.color, fontSize: '11px', fontWeight: 600, fontFamily: TYPOGRAPHY.MONO }}>+ {formatter ? formatter(entry.value) : entry.value}+ </span>+ </div>+ ))}+ </div>+ );+};+export const FinancialsTab: React.FC<FinancialsTabProps> = ({financials,+ stockInfo,loading,}) => {- const [fontSize, setFontSize] = useState(12);- const [showYearsCount, setShowYearsCount] = useState(4);- const [selectedMetrics, setSelectedMetrics] = useState<string[]>(['Total Revenue', 'Gross Profit', 'Operating Income', 'Net Income', 'EBITDA', 'Basic EPS', 'Diluted EPS']);- const [chart1Metrics, setChart1Metrics] = useState<string[]>(['Total Revenue', 'Gross Profit']);- const [chart2Metrics, setChart2Metrics] = useState<string[]>(['Net Income', 'Operating Income']);- const [chart3Metrics, setChart3Metrics] = useState<string[]>(['EBITDA']);-- const financialChart1Ref = useRef<HTMLDivElement>(null);- const financialChart2Ref = useRef<HTMLDivElement>(null);- const financialChart3Ref = useRef<HTMLDivElement>(null);- const financialChart1InstanceRef = useRef<any>(null);- const financialChart2InstanceRef = useRef<any>(null);- const financialChart3InstanceRef = useRef<any>(null);-- // Get all available metrics from income statement- const getAllMetrics = (): string[] => {- if (!financials || Object.keys(financials.income_statement).length === 0) return [];- const firstPeriod = Object.keys(financials.income_statement)[0];- return Object.keys(financials.income_statement[firstPeriod]);- };-- const toggleMetric = (metric: string) => {- setSelectedMetrics(prev =>- prev.includes(metric)- ? prev.filter(m => m !== metric)- : [...prev, metric]- );- };-- // Helper function to create a financial chart with dynamic metrics- const createFinancialChart = (- container: HTMLDivElement | null,- metrics: string[],- chartColors: string[]- ) => {- if (!container || !financials) return null;-- const chart = createChart(container, {- layout: {- background: { color: COLORS.DARK_BG },- textColor: COLORS.WHITE,- },- grid: {- vertLines: { color: COLORS.BORDER },- horzLines: { color: COLORS.BORDER },- },- width: container.clientWidth,- height: 250,- timeScale: {- borderColor: COLORS.GRAY,- timeVisible: true,- },- rightPriceScale: {- borderColor: COLORS.GRAY,- },+ const [activeStatement, setActiveStatement] = useState<'income' | 'balance' | 'cashflow'>('income');++ // Process financial data+ const processedData = useMemo(() => {+ if (!financials) return null;++ const incomeKeys = Object.keys(financials.income_statement).sort().reverse();+ const balanceKeys = Object.keys(financials.balance_sheet).sort().reverse();+ const cashflowKeys = Object.keys(financials.cash_flow).sort().reverse();++ // Get latest period data+ const latestIncome = incomeKeys[0] ? financials.income_statement[incomeKeys[0]] : {};+ const prevIncome = incomeKeys[1] ? financials.income_statement[incomeKeys[1]] : {};+ const latestBalance = balanceKeys[0] ? financials.balance_sheet[balanceKeys[0]] : {};+ const prevBalance = balanceKeys[1] ? financials.balance_sheet[balanceKeys[1]] : {};+ const latestCashflow = cashflowKeys[0] ? financials.cash_flow[cashflowKeys[0]] : {};+ const prevCashflow = cashflowKeys[1] ? financials.cash_flow[cashflowKeys[1]] : {};++ // ===== INCOME STATEMENT METRICS =====+ const revenue = latestIncome['Total Revenue'] || latestIncome['Revenue'] || 0;+ const prevRevenue = prevIncome['Total Revenue'] || prevIncome['Revenue'] || 0;+ const grossProfit = latestIncome['Gross Profit'] || 0;+ const prevGrossProfit = prevIncome['Gross Profit'] || 0;+ const operatingIncome = latestIncome['Operating Income'] || latestIncome['Operating Profit'] || 0;+ const prevOperatingIncome = prevIncome['Operating Income'] || prevIncome['Operating Profit'] || 0;+ const netIncome = latestIncome['Net Income'] || latestIncome['Net Income Common Stockholders'] || 0;+ const prevNetIncome = prevIncome['Net Income'] || prevIncome['Net Income Common Stockholders'] || 0;+ const ebitda = latestIncome['EBITDA'] || latestIncome['Normalized EBITDA'] || 0;+ const costOfRevenue = latestIncome['Cost Of Revenue'] || 0;+ const operatingExpenses = latestIncome['Operating Expense'] || latestIncome['Total Operating Expenses'] || 0;+ const interestExpense = latestIncome['Interest Expense'] || latestIncome['Interest Expense Non Operating'] || latestIncome['Net Interest Income'] || latestIncome['Interest And Debt Expense'] || Math.abs(latestIncome['Net Non Operating Interest Income Expense'] || 0) || 0;+ const interestIncome = latestIncome['Interest Income'] || 0;+ const taxExpense = latestIncome['Tax Provision'] || latestIncome['Income Tax Expense'] || 0;+ const researchDev = latestIncome['Research And Development'] || latestIncome['Research Development'] || 0;+ const sgaExpense = latestIncome['Selling General And Administration'] || latestIncome['SG&A'] || 0;+ const depreciation = latestIncome['Depreciation And Amortization'] || 0;+ const otherIncome = latestIncome['Other Income'] || latestIncome['Other Non Operating Income Expenses'] || 0;++ // ===== BALANCE SHEET METRICS =====+ const totalAssets = latestBalance['Total Assets'] || 0;+ const prevTotalAssets = prevBalance['Total Assets'] || 0;+ const totalLiabilities = latestBalance['Total Liabilities Net Minority Interest'] || latestBalance['Total Liabilities'] || 0;+ const totalEquity = latestBalance['Stockholders Equity'] || latestBalance['Total Equity'] || latestBalance['Total Stockholder Equity'] || 0;+ const prevTotalEquity = prevBalance['Stockholders Equity'] || prevBalance['Total Equity'] || prevBalance['Total Stockholder Equity'] || 0;+ const currentAssets = latestBalance['Current Assets'] || latestBalance['Total Current Assets'] || 0;+ const currentLiabilities = latestBalance['Current Liabilities'] || latestBalance['Total Current Liabilities'] || 0;+ const totalDebt = latestBalance['Total Debt'] || (latestBalance['Long Term Debt'] || 0) + (latestBalance['Short Term Debt'] || 0);+ const cash = latestBalance['Cash And Cash Equivalents'] || latestBalance['Cash'] || 0;+ const shortTermInvestments = latestBalance['Short Term Investments'] || latestBalance['Other Short Term Investments'] || 0;+ const inventory = latestBalance['Inventory'] || 0;+ const receivables = latestBalance['Accounts Receivable'] || latestBalance['Net Receivables'] || 0;+ const payables = latestBalance['Accounts Payable'] || 0;+ const longTermDebt = latestBalance['Long Term Debt'] || 0;+ const shortTermDebt = latestBalance['Short Term Debt'] || latestBalance['Current Debt'] || 0;+ const retainedEarnings = latestBalance['Retained Earnings'] || 0;+ const goodwill = latestBalance['Goodwill'] || 0;+ const intangibles = latestBalance['Intangible Assets'] || latestBalance['Other Intangible Assets'] || 0;+ const ppe = latestBalance['Net PPE'] || latestBalance['Property Plant Equipment'] || 0;+ const otherAssets = latestBalance['Other Assets'] || latestBalance['Other Non Current Assets'] || 0;+ const deferredRevenue = latestBalance['Deferred Revenue'] || 0;++ // ===== CASH FLOW METRICS =====+ const operatingCashflow = latestCashflow['Operating Cash Flow'] || latestCashflow['Total Cash From Operating Activities'] || 0;+ const prevOperatingCashflow = prevCashflow['Operating Cash Flow'] || prevCashflow['Total Cash From Operating Activities'] || 0;+ const investingCashflow = latestCashflow['Investing Cash Flow'] || latestCashflow['Total Cash From Investing Activities'] || 0;+ const financingCashflow = latestCashflow['Financing Cash Flow'] || latestCashflow['Total Cash From Financing Activities'] || 0;+ const capex = Math.abs(latestCashflow['Capital Expenditure'] || latestCashflow['Capital Expenditures'] || 0);+ const freeCashflow = operatingCashflow - capex;+ const prevFreeCashflow = prevOperatingCashflow - Math.abs(prevCashflow['Capital Expenditure'] || prevCashflow['Capital Expenditures'] || 0);+ const dividendsPaid = Math.abs(latestCashflow['Cash Dividends Paid'] || latestCashflow['Payment Of Dividends'] || 0);+ const stockRepurchase = Math.abs(latestCashflow['Repurchase Of Stock'] || latestCashflow['Common Stock Repurchased'] || latestCashflow['Repurchase Of Capital Stock'] || latestCashflow['Common Stock Payments'] || latestCashflow['Purchase Of Stock'] || 0);+ const depreciationCF = latestCashflow['Depreciation And Amortization'] || latestCashflow['Depreciation'] || 0;+ const stockBasedComp = latestCashflow['Stock Based Compensation'] || 0;+ const changeInWorkingCapital = latestCashflow['Change In Working Capital'] || 0;+ const debtIssuance = latestCashflow['Issuance Of Debt'] || latestCashflow['Long Term Debt Issuance'] || 0;+ const debtRepayment = Math.abs(latestCashflow['Repayment Of Debt'] || latestCashflow['Long Term Debt Payments'] || 0);++ // ===== CALCULATE RATIOS =====+ // Profitability Ratios+ const grossMargin = revenue ? (grossProfit / revenue) : 0;+ const operatingMargin = revenue ? (operatingIncome / revenue) : 0;+ const netMargin = revenue ? (netIncome / revenue) : 0;+ const ebitdaMargin = revenue ? (ebitda / revenue) : 0;++ // Return Ratios+ const avgTotalAssets = (totalAssets + prevTotalAssets) / 2 || totalAssets;+ const avgTotalEquity = (totalEquity + prevTotalEquity) / 2 || totalEquity;+ const roa = avgTotalAssets ? (netIncome / avgTotalAssets) : 0;+ const roe = avgTotalEquity ? (netIncome / avgTotalEquity) : 0;+ const investedCapital = totalEquity + totalDebt - cash;+ const roic = investedCapital > 0 ? (operatingIncome * (1 - 0.25)) / investedCapital : 0;+ const roce = (totalAssets - currentLiabilities) > 0 ? (operatingIncome / (totalAssets - currentLiabilities)) : 0;++ // Liquidity Ratios+ const currentRatio = currentLiabilities ? (currentAssets / currentLiabilities) : 0;+ const quickRatio = currentLiabilities ? ((currentAssets - inventory) / currentLiabilities) : 0;+ const cashRatio = currentLiabilities ? ((cash + shortTermInvestments) / currentLiabilities) : 0;+ const workingCapital = currentAssets - currentLiabilities;++ // Leverage/Solvency Ratios+ const debtToEquity = totalEquity ? (totalDebt / totalEquity) : 0;+ const debtToAssets = totalAssets ? (totalDebt / totalAssets) : 0;+ const debtToCapital = (totalDebt + totalEquity) ? (totalDebt / (totalDebt + totalEquity)) : 0;+ const equityMultiplier = totalEquity ? (totalAssets / totalEquity) : 0;+ const interestCoverage = interestExpense ? (ebitda / interestExpense) : 999;+ const netDebt = totalDebt - cash;++ // Efficiency Ratios+ const assetTurnover = avgTotalAssets ? (revenue / avgTotalAssets) : 0;+ const inventoryTurnover = inventory ? (costOfRevenue / inventory) : 0;+ const daysInventory = inventoryTurnover ? (365 / inventoryTurnover) : 0;+ const receivablesTurnover = receivables ? (revenue / receivables) : 0;+ const daysReceivables = receivablesTurnover ? (365 / receivablesTurnover) : 0;+ const payablesTurnover = payables ? (costOfRevenue / payables) : 0;+ const daysPayables = payablesTurnover ? (365 / payablesTurnover) : 0;+ const cashConversionCycle = daysInventory + daysReceivables - daysPayables;+ const fixedAssetTurnover = ppe ? (revenue / ppe) : 0;++ // Cash Flow Ratios+ const fcfMargin = revenue ? (freeCashflow / revenue) : 0;+ const fcfToNetIncome = netIncome ? (freeCashflow / netIncome) : 0;+ const capexToRevenue = revenue ? (capex / revenue) : 0;+ const capexToDepreciation = depreciationCF ? (capex / depreciationCF) : 0;+ const operatingCashflowRatio = currentLiabilities ? (operatingCashflow / currentLiabilities) : 0;+ const cashFlowCoverage = totalDebt ? (operatingCashflow / totalDebt) : 0;++ // DuPont Analysis+ const dupontNetMargin = netMargin;+ const dupontAssetTurnover = assetTurnover;+ const dupontEquityMultiplier = equityMultiplier;+ const dupontROE = dupontNetMargin * dupontAssetTurnover * dupontEquityMultiplier;++ // ===== CHART DATA =====++ // Revenue breakdown waterfall+ const revenueWaterfall = [+ { name: 'Revenue', value: revenue, fill: COLORS.GREEN },+ { name: 'Cost of Revenue', value: -costOfRevenue, fill: COLORS.RED },+ { name: 'Gross Profit', value: grossProfit, fill: COLORS.CYAN },+ { name: 'Operating Exp', value: -operatingExpenses, fill: COLORS.ORANGE },+ { name: 'Operating Income', value: operatingIncome, fill: COLORS.BLUE },+ { name: 'Interest & Tax', value: -(interestExpense + taxExpense - interestIncome), fill: COLORS.PURPLE },+ { name: 'Net Income', value: netIncome, fill: netIncome >= 0 ? COLORS.GREEN : COLORS.RED },+ ];++ // Historical trends (5 years)+ const revenueTrend = incomeKeys.slice(0, 5).reverse().map(period => ({+ period: getYearFromPeriod(period),+ revenue: (financials.income_statement[period]['Total Revenue'] || financials.income_statement[period]['Revenue'] || 0) / 1e9,+ netIncome: (financials.income_statement[period]['Net Income'] || financials.income_statement[period]['Net Income Common Stockholders'] || 0) / 1e9,+ grossProfit: (financials.income_statement[period]['Gross Profit'] || 0) / 1e9,+ operatingIncome: (financials.income_statement[period]['Operating Income'] || 0) / 1e9,+ ebitda: (financials.income_statement[period]['EBITDA'] || financials.income_statement[period]['Normalized EBITDA'] || 0) / 1e9,+ }));++ const marginTrend = incomeKeys.slice(0, 5).reverse().map(period => {+ const rev = financials.income_statement[period]['Total Revenue'] || financials.income_statement[period]['Revenue'] || 1;+ const gross = financials.income_statement[period]['Gross Profit'] || 0;+ const op = financials.income_statement[period]['Operating Income'] || 0;+ const net = financials.income_statement[period]['Net Income'] || financials.income_statement[period]['Net Income Common Stockholders'] || 0;+ const ebit = financials.income_statement[period]['EBITDA'] || financials.income_statement[period]['Normalized EBITDA'] || 0;+ return {+ period: getYearFromPeriod(period),+ grossMargin: (gross / rev) * 100,+ operatingMargin: (op / rev) * 100,+ netMargin: (net / rev) * 100,+ ebitdaMargin: (ebit / rev) * 100,+ };});- const periods = Object.keys(financials.income_statement);-- metrics.forEach((metric, idx) => {- const color = chartColors[idx % chartColors.length];- const series = chart.addSeries(LineSeries, {- color,- lineWidth: 2,- title: metric,- });-- const data: any[] = [];- periods.forEach((period) => {- const timestamp = new Date(period).getTime() / 1000;- const statements = financials.income_statement[period];-- if (statements[metric] !== undefined && statements[metric] !== null) {- const value = metric.includes('EPS')- ? statements[metric]- : statements[metric] / 1e9; // Convert to billions- data.push({ time: timestamp, value });- }- });-- if (data.length > 0) {- series.setData(data.sort((a, b) => a.time - b.time));- }+ const cashflowTrend = cashflowKeys.slice(0, 5).reverse().map(period => {+ const opCf = financials.cash_flow[period]['Operating Cash Flow'] || financials.cash_flow[period]['Total Cash From Operating Activities'] || 0;+ const invCf = financials.cash_flow[period]['Investing Cash Flow'] || financials.cash_flow[period]['Total Cash From Investing Activities'] || 0;+ const finCf = financials.cash_flow[period]['Financing Cash Flow'] || financials.cash_flow[period]['Total Cash From Financing Activities'] || 0;+ const capEx = Math.abs(financials.cash_flow[period]['Capital Expenditure'] || financials.cash_flow[period]['Capital Expenditures'] || 0);+ return {+ period: getYearFromPeriod(period),+ operating: opCf / 1e9,+ investing: invCf / 1e9,+ financing: finCf / 1e9,+ freeCashflow: (opCf - capEx) / 1e9,+ capex: -capEx / 1e9,+ };});- chart.timeScale().fitContent();- return chart;- };-- // Update financial charts when data or metrics change- useEffect(() => {- if (financials) {- // Cleanup existing charts- [financialChart1InstanceRef, financialChart2InstanceRef, financialChart3InstanceRef].forEach(ref => {- if (ref.current) {- try {- ref.current.remove();- } catch (e) {- // Chart already disposed- }- ref.current = null;- }- });-- const chartColors = [COLORS.GREEN, COLORS.CYAN, COLORS.ORANGE, COLORS.YELLOW, COLORS.MAGENTA, COLORS.BLUE];-- if (financialChart1Ref.current && chart1Metrics.length > 0) {- financialChart1InstanceRef.current = createFinancialChart(financialChart1Ref.current, chart1Metrics, chartColors);- }-- if (financialChart2Ref.current && chart2Metrics.length > 0) {- financialChart2InstanceRef.current = createFinancialChart(financialChart2Ref.current, chart2Metrics, chartColors);- }-- if (financialChart3Ref.current && chart3Metrics.length > 0) {- financialChart3InstanceRef.current = createFinancialChart(financialChart3Ref.current, chart3Metrics, chartColors);- }-- // Handle resize- const handleResize = () => {- if (financialChart1Ref.current && financialChart1InstanceRef.current) {- financialChart1InstanceRef.current.applyOptions({ width: financialChart1Ref.current.clientWidth });- }- if (financialChart2Ref.current && financialChart2InstanceRef.current) {- financialChart2InstanceRef.current.applyOptions({ width: financialChart2Ref.current.clientWidth });- }- if (financialChart3Ref.current && financialChart3InstanceRef.current) {- financialChart3InstanceRef.current.applyOptions({ width: financialChart3Ref.current.clientWidth });- }+ // Balance sheet trends+ const balanceTrend = balanceKeys.slice(0, 5).reverse().map(period => {+ const assets = financials.balance_sheet[period]['Total Assets'] || 0;+ const liabilities = financials.balance_sheet[period]['Total Liabilities Net Minority Interest'] || financials.balance_sheet[period]['Total Liabilities'] || 0;+ const equity = financials.balance_sheet[period]['Stockholders Equity'] || financials.balance_sheet[period]['Total Equity'] || 0;+ const debt = financials.balance_sheet[period]['Total Debt'] || 0;+ const cashVal = financials.balance_sheet[period]['Cash And Cash Equivalents'] || financials.balance_sheet[period]['Cash'] || 0;+ return {+ period: getYearFromPeriod(period),+ assets: assets / 1e9,+ liabilities: liabilities / 1e9,+ equity: equity / 1e9,+ debt: debt / 1e9,+ cash: cashVal / 1e9,+ netDebt: (debt - cashVal) / 1e9,};+ });- window.addEventListener('resize', handleResize);- return () => {- window.removeEventListener('resize', handleResize);- [financialChart1InstanceRef, financialChart2InstanceRef, financialChart3InstanceRef].forEach(ref => {- if (ref.current) {- try {- ref.current.remove();- } catch (e) {- // Chart already disposed- }- ref.current = null;- }- });+ // Return metrics trend+ const returnTrend = incomeKeys.slice(0, 5).reverse().map((period, idx) => {+ const net = financials.income_statement[period]['Net Income'] || financials.income_statement[period]['Net Income Common Stockholders'] || 0;+ const balPeriod = balanceKeys[idx];+ const assets = balPeriod ? (financials.balance_sheet[balPeriod]['Total Assets'] || 0) : 0;+ const equity = balPeriod ? (financials.balance_sheet[balPeriod]['Stockholders Equity'] || financials.balance_sheet[balPeriod]['Total Equity'] || 0) : 0;+ return {+ period: getYearFromPeriod(period),+ roe: equity ? ((net / equity) * 100) : 0,+ roa: assets ? ((net / assets) * 100) : 0,};- }- }, [financials, chart1Metrics, chart2Metrics, chart3Metrics]);+ });++ // Asset composition for pie chart+ const assetComposition = [+ { name: 'Cash & Investments', value: (cash + shortTermInvestments) / 1e9, color: COLORS.GREEN },+ { name: 'Receivables', value: receivables / 1e9, color: COLORS.CYAN },+ { name: 'Inventory', value: inventory / 1e9, color: COLORS.BLUE },+ { name: 'PP&E', value: ppe / 1e9, color: COLORS.ORANGE },+ { name: 'Goodwill & Intangibles', value: (goodwill + intangibles) / 1e9, color: COLORS.PURPLE },+ { name: 'Other Assets', value: Math.max(0, (totalAssets - cash - shortTermInvestments - receivables - inventory - ppe - goodwill - intangibles) / 1e9), color: COLORS.YELLOW },+ ].filter(item => item.value > 0.01);++ const liabilityComposition = [+ { name: 'Short-term Debt', value: shortTermDebt / 1e9, color: COLORS.RED },+ { name: 'Long-term Debt', value: longTermDebt / 1e9, color: COLORS.ORANGE },+ { name: 'Accounts Payable', value: payables / 1e9, color: COLORS.YELLOW },+ { name: 'Deferred Revenue', value: deferredRevenue / 1e9, color: COLORS.PURPLE },+ { name: 'Other Liabilities', value: Math.max(0, (totalLiabilities - shortTermDebt - longTermDebt - payables - deferredRevenue) / 1e9), color: COLORS.CYAN },+ ].filter(item => item.value > 0.01);++ // Capital structure+ const capitalStructure = [+ { name: 'Equity', value: totalEquity / 1e9, color: COLORS.GREEN },+ { name: 'Long-term Debt', value: longTermDebt / 1e9, color: COLORS.ORANGE },+ { name: 'Short-term Debt', value: shortTermDebt / 1e9, color: COLORS.RED },+ ].filter(item => item.value > 0.01);- if (!financials) {+ // Operating expenses breakdown+ const opexBreakdown = [+ { name: 'Cost of Revenue', value: costOfRevenue / 1e9, color: COLORS.RED },+ { name: 'R&D', value: researchDev / 1e9, color: COLORS.BLUE },+ { name: 'SG&A', value: sgaExpense / 1e9, color: COLORS.ORANGE },+ { name: 'Depreciation', value: depreciation / 1e9, color: COLORS.PURPLE },+ { name: 'Other', value: Math.max(0, (operatingExpenses - researchDev - sgaExpense - depreciation) / 1e9), color: COLORS.YELLOW },+ ].filter(item => item.value > 0.01);++ // Cash flow composition+ const cashFlowComposition = [+ { name: 'Operating CF', value: Math.abs(operatingCashflow) / 1e9, actual: operatingCashflow / 1e9, color: COLORS.GREEN, isPositive: operatingCashflow >= 0 },+ { name: 'Investing CF', value: Math.abs(investingCashflow) / 1e9, actual: investingCashflow / 1e9, color: COLORS.ORANGE, isPositive: investingCashflow >= 0 },+ { name: 'Financing CF', value: Math.abs(financingCashflow) / 1e9, actual: financingCashflow / 1e9, color: COLORS.PURPLE, isPositive: financingCashflow >= 0 },+ ];++ // DuPont analysis data+ const dupontData = [+ { subject: 'Net Margin', value: dupontNetMargin * 100, fullMark: 50 },+ { subject: 'Asset Turnover', value: dupontAssetTurnover * 50, fullMark: 100 },+ { subject: 'Equity Multiplier', value: dupontEquityMultiplier * 20, fullMark: 100 },+ { subject: 'ROE', value: roe * 100, fullMark: 50 },+ { subject: 'ROA', value: roa * 100, fullMark: 30 },+ ];++ // Efficiency metrics for radar+ const efficiencyRadar = [+ { metric: 'Asset Turn', value: Math.min(100, assetTurnover * 50), fullMark: 100 },+ { metric: 'Inv Turn', value: Math.min(100, inventoryTurnover * 10), fullMark: 100 },+ { metric: 'AR Turn', value: Math.min(100, receivablesTurnover * 10), fullMark: 100 },+ { metric: 'FA Turn', value: Math.min(100, fixedAssetTurnover * 10), fullMark: 100 },+ { metric: 'OCF Ratio', value: Math.min(100, operatingCashflowRatio * 50), fullMark: 100 },+ ];++ return {+ // Key metrics+ revenue, prevRevenue, grossProfit, prevGrossProfit, operatingIncome, prevOperatingIncome,+ netIncome, prevNetIncome, ebitda, costOfRevenue, operatingExpenses,+ interestExpense, taxExpense, researchDev, sgaExpense,+ // Balance sheet+ totalAssets, totalLiabilities, totalEquity, currentAssets, currentLiabilities,+ totalDebt, cash, shortTermInvestments, inventory, receivables, payables,+ longTermDebt, shortTermDebt, retainedEarnings, goodwill, intangibles, ppe,+ workingCapital, netDebt,+ // Cashflow+ operatingCashflow, prevOperatingCashflow, investingCashflow, financingCashflow,+ capex, freeCashflow, prevFreeCashflow, dividendsPaid, stockRepurchase,+ depreciationCF, stockBasedComp, changeInWorkingCapital, debtIssuance, debtRepayment,+ // Profitability ratios+ grossMargin, operatingMargin, netMargin, ebitdaMargin,+ // Return ratios+ roa, roe, roic, roce,+ // Liquidity ratios+ currentRatio, quickRatio, cashRatio,+ // Leverage ratios+ debtToEquity, debtToAssets, debtToCapital, equityMultiplier, interestCoverage,+ // Efficiency ratios+ assetTurnover, inventoryTurnover, daysInventory, receivablesTurnover, daysReceivables,+ payablesTurnover, daysPayables, cashConversionCycle, fixedAssetTurnover,+ // Cash flow ratios+ fcfMargin, fcfToNetIncome, capexToRevenue, capexToDepreciation, operatingCashflowRatio, cashFlowCoverage,+ // DuPont+ dupontNetMargin, dupontAssetTurnover, dupontEquityMultiplier, dupontROE,+ // Charts data+ revenueWaterfall, revenueTrend, marginTrend, cashflowTrend, balanceTrend, returnTrend,+ assetComposition, liabilityComposition, capitalStructure, opexBreakdown, cashFlowComposition,+ dupontData, efficiencyRadar,+ // Periods+ incomeKeys, balanceKeys, cashflowKeys,+ latestIncome, latestBalance, latestCashflow,+ };+ }, [financials]);++ if (loading) {return (- <div style={{- display: 'flex',- flexDirection: 'column',- alignItems: 'center',- justifyContent: 'center',- height: '400px',- gap: '16px',- }}>- {loading && (- <div style={{- width: '50px',- height: '50px',- border: '4px solid #404040',- borderTop: '4px solid #ea580c',- borderRadius: '50%',- animation: 'spin 1s linear infinite'- }} />- )}- <div style={{ color: COLORS.YELLOW, fontSize: '14px', fontWeight: 'bold' }}>- {loading ? 'LOADING FINANCIAL DATA...' : '[WARN] NO FINANCIAL DATA AVAILABLE'}- </div>- <div style={{ color: COLORS.GRAY, fontSize: '11px' }}>- {loading ? 'Please wait while we fetch the data' : 'Financial statements are not available for this symbol'}- </div>+ <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '400px', gap: '16px', fontFamily: TYPOGRAPHY.MONO }}>+ <div style={{ width: '40px', height: '40px', border: `3px solid ${COLORS.BORDER}`, borderTop: `3px solid ${COLORS.ORANGE}`, borderRadius: '50%', animation: 'spin 1s linear infinite' }} />+ <div style={{ color: COLORS.ORANGE, fontSize: '14px', fontWeight: 700, textTransform: 'uppercase' }}>Loading Financial Data</div></div>);}- const allMetrics = getAllMetrics();+ if (!financials || !processedData) {+ return (+ <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '400px', gap: '16px', fontFamily: TYPOGRAPHY.MONO }}>+ <AlertTriangle size={40} color={COLORS.YELLOW} />+ <div style={{ color: COLORS.YELLOW, fontSize: '16px', fontWeight: 700, textTransform: 'uppercase' }}>No Financial Data Available</div>+ <div style={{ color: COLORS.GRAY, fontSize: '13px' }}>Financial statements are not available for this symbol</div>+ </div>+ );+ }++ const {+ revenue, prevRevenue, grossProfit, operatingIncome, netIncome, prevNetIncome, ebitda,+ totalAssets, totalLiabilities, totalEquity, currentAssets, currentLiabilities,+ totalDebt, cash, freeCashflow, prevFreeCashflow, operatingCashflow, workingCapital, netDebt,+ grossMargin, operatingMargin, netMargin, ebitdaMargin,+ currentRatio, quickRatio, cashRatio, debtToEquity, debtToAssets, interestCoverage, equityMultiplier,+ roa, roe, roic, roce, fcfMargin,+ assetTurnover, inventoryTurnover, daysInventory, receivablesTurnover, daysReceivables,+ daysPayables, cashConversionCycle,+ capex, capexToRevenue, capexToDepreciation,+ dupontNetMargin, dupontAssetTurnover, dupontEquityMultiplier,+ revenueWaterfall, revenueTrend, marginTrend, cashflowTrend, balanceTrend, returnTrend,+ assetComposition, liabilityComposition, capitalStructure, opexBreakdown, cashFlowComposition,+ dupontData, efficiencyRadar,+ incomeKeys, latestIncome, latestBalance, latestCashflow,+ } = processedData;++ const revenueGrowth = calculateGrowth(revenue, prevRevenue);+ const netIncomeGrowth = calculateGrowth(netIncome, prevNetIncome);+ const fcfGrowth = calculateGrowth(freeCashflow, prevFreeCashflow);return (- <div id="research-financials" style={{ padding: '8px' }}>- {/* Controls Panel */}- <div id="financials-controls" style={{- backgroundColor: COLORS.PANEL_BG,- border: `1px solid ${COLORS.BORDER}`,- padding: '10px 12px',- marginBottom: '8px',- display: 'flex',- gap: '20px',- alignItems: 'center',- flexWrap: 'wrap',- }}>- <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>- <span style={{ color: COLORS.GRAY, fontSize: `${fontSize}px` }}>FONT SIZE:</span>- <button- onClick={() => setFontSize(Math.max(10, fontSize - 1))}- style={{- backgroundColor: COLORS.DARK_BG,- border: `1px solid ${COLORS.BORDER}`,- color: COLORS.WHITE,- padding: '4px 8px',- fontSize: `${fontSize}px`,- cursor: 'pointer',- }}- >- -- </button>- <span style={{ color: COLORS.ORANGE, fontSize: `${fontSize}px`, fontWeight: 'bold', minWidth: '30px', textAlign: 'center' }}>{fontSize}px</span>- <button- onClick={() => setFontSize(Math.min(20, fontSize + 1))}- style={{- backgroundColor: COLORS.DARK_BG,- border: `1px solid ${COLORS.BORDER}`,- color: COLORS.WHITE,- padding: '4px 8px',- fontSize: `${fontSize}px`,- cursor: 'pointer',- }}- >- +- </button>- </div>+ <div style={{+ padding: '16px',+ overflow: 'auto',+ height: '100%',+ fontFamily: TYPOGRAPHY.MONO,+ }} className="custom-scrollbar">- <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>- <span style={{ color: COLORS.GRAY, fontSize: `${fontSize}px` }}>SHOW YEARS:</span>- {[2, 3, 4, 5].map((count) => (- <button- key={count}- onClick={() => setShowYearsCount(count)}- style={{- backgroundColor: showYearsCount === count ? COLORS.ORANGE : COLORS.DARK_BG,- border: `1px solid ${COLORS.BORDER}`,- color: showYearsCount === count ? COLORS.DARK_BG : COLORS.WHITE,- padding: '4px 10px',- fontSize: `${fontSize - 1}px`,- cursor: 'pointer',- fontWeight: showYearsCount === count ? 'bold' : 'normal',- }}- >- {count}- </button>- ))}+ {/* ===== KEY FINANCIAL METRICS ===== */}+ <SectionPanel+ title="Key Financial Metrics"+ color={COLORS.ORANGE}+ icon={<DollarSign size={16} color={COLORS.ORANGE} />}+ subtitle={`Latest Period: ${incomeKeys[0] ? getYearFromPeriod(incomeKeys[0]) : 'N/A'}`}+ >+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px' }}>+ <MetricCard+ label="Total Revenue"+ value={formatCurrency(revenue)}+ change={revenueGrowth}+ color={COLORS.GREEN}+ icon={<Receipt size={18} />}+ trend={revenueGrowth && revenueGrowth > 0 ? 'up' : revenueGrowth && revenueGrowth < 0 ? 'down' : 'neutral'}+ size="large"+ />+ <MetricCard+ label="Gross Profit"+ value={formatCurrency(grossProfit)}+ color={COLORS.CYAN}+ icon={<DollarSign size={18} />}+ subtitle={`${formatPercent(grossMargin)} margin`}+ size="large"+ />+ <MetricCard+ label="Operating Income"+ value={formatCurrency(operatingIncome)}+ color={COLORS.BLUE}+ icon={<Activity size={18} />}+ subtitle={`${formatPercent(operatingMargin)} margin`}+ size="large"+ />+ <MetricCard+ label="Net Income"+ value={formatCurrency(netIncome)}+ change={netIncomeGrowth}+ color={netIncome >= 0 ? COLORS.GREEN : COLORS.RED}+ icon={<Banknote size={18} />}+ trend={netIncomeGrowth && netIncomeGrowth > 0 ? 'up' : netIncomeGrowth && netIncomeGrowth < 0 ? 'down' : 'neutral'}+ size="large"+ /></div>- <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>- <span style={{ color: COLORS.GRAY, fontSize: `${fontSize}px` }}>SELECT METRICS:</span>- <button- onClick={() => {- setSelectedMetrics(selectedMetrics.length === allMetrics.length ? [] : allMetrics);- }}- style={{- backgroundColor: COLORS.BLUE,- border: 'none',- color: COLORS.WHITE,- padding: '4px 10px',- fontSize: `${fontSize - 1}px`,- cursor: 'pointer',- fontWeight: 'bold',- }}- >- {selectedMetrics.length === allMetrics.length ? 'DESELECT ALL' : 'SELECT ALL'}- </button>+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '12px', marginTop: '12px' }}>+ <MetricCard label="EBITDA" value={formatCurrency(ebitda)} color={COLORS.PURPLE} icon={<BarChart3 size={16} />} subtitle={`${formatPercent(ebitdaMargin)} margin`} />+ <MetricCard label="Free Cash Flow" value={formatCurrency(freeCashflow)} change={fcfGrowth} color={freeCashflow >= 0 ? COLORS.CYAN : COLORS.RED} icon={<CircleDollarSign size={16} />} trend={fcfGrowth && fcfGrowth > 0 ? 'up' : 'down'} />+ <MetricCard label="Total Assets" value={formatCurrency(totalAssets)} color={COLORS.BLUE} icon={<Building2 size={16} />} />+ <MetricCard label="Total Debt" value={formatCurrency(totalDebt)} color={COLORS.ORANGE} icon={<CreditCard size={16} />} subtitle={`Net: ${formatCurrency(netDebt)}`} />+ <MetricCard label="Cash Position" value={formatCurrency(cash)} color={COLORS.GREEN} icon={<Wallet size={16} />} /></div>- </div>+ </SectionPanel>- {/* Metric Selector */}- <div style={{- backgroundColor: COLORS.PANEL_BG,- border: `1px solid ${COLORS.BORDER}`,- padding: '12px',- marginBottom: '8px',- }}>- <div style={{ color: COLORS.CYAN, fontSize: `${fontSize + 2}px`, fontWeight: 'bold', marginBottom: '10px' }}>- SELECT METRICS TO COMPARE- </div>- <div style={{ display: 'flex', flexWrap: 'wrap', gap: '6px' }}>- {allMetrics.map((metric) => (- <button- key={metric}- onClick={() => toggleMetric(metric)}- style={{- backgroundColor: selectedMetrics.includes(metric) ? COLORS.GREEN : COLORS.DARK_BG,- border: `1px solid ${selectedMetrics.includes(metric) ? COLORS.GREEN : COLORS.BORDER}`,- color: selectedMetrics.includes(metric) ? COLORS.DARK_BG : COLORS.WHITE,- padding: '6px 12px',- fontSize: `${fontSize - 1}px`,- cursor: 'pointer',- fontWeight: selectedMetrics.includes(metric) ? 'bold' : 'normal',- borderRadius: '3px',- }}- >- {metric}- </button>- ))}+ {/* ===== PROFITABILITY ANALYSIS ===== */}+ <SectionPanel+ title="Profitability Analysis"+ color={COLORS.GREEN}+ icon={<TrendingUp size={16} color={COLORS.GREEN} />}+ >+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>+ {/* Profit Margins */}+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '10px' }}>+ <HealthScore label="Gross Margin" value={grossMargin} max={1} thresholds={{ good: 0.4, warning: 0.2 }} format="percent" description="Revenue after COGS" />+ <HealthScore label="Operating Margin" value={operatingMargin} max={1} thresholds={{ good: 0.2, warning: 0.1 }} format="percent" description="Operational efficiency" />+ <HealthScore label="Net Profit Margin" value={netMargin} max={1} thresholds={{ good: 0.15, warning: 0.05 }} format="percent" description="Bottom line profitability" />+ <HealthScore label="EBITDA Margin" value={ebitdaMargin} max={1} thresholds={{ good: 0.25, warning: 0.15 }} format="percent" description="Cash flow proxy" />+ </div>++ {/* Margin Trends Chart */}+ <ChartWrapper title="Margin Trends (%)" color={COLORS.GREEN} height={200}>+ <ResponsiveContainer width="100%" height="100%">+ <LineChart data={marginTrend} margin={{ top: 10, right: 30, left: 0, bottom: 10 }}>+ <CartesianGrid strokeDasharray="3 3" stroke={COLORS.BORDER} opacity={0.3} />+ <XAxis dataKey="period" tick={{ fill: COLORS.GRAY, fontSize: 11 }} axisLine={{ stroke: COLORS.BORDER }} />+ <YAxis tick={{ fill: COLORS.GRAY, fontSize: 11 }} tickFormatter={(v) => `${v.toFixed(0)}%`} axisLine={{ stroke: COLORS.BORDER }} />+ <Tooltip content={<CustomTooltip formatter={(v: number) => `${v.toFixed(1)}%`} />} />+ <Legend wrapperStyle={{ fontSize: '11px' }} />+ <Line type="monotone" dataKey="grossMargin" stroke={COLORS.GREEN} strokeWidth={2} dot={{ r: 4 }} name="Gross" />+ <Line type="monotone" dataKey="operatingMargin" stroke={COLORS.CYAN} strokeWidth={2} dot={{ r: 4 }} name="Operating" />+ <Line type="monotone" dataKey="netMargin" stroke={COLORS.ORANGE} strokeWidth={2} dot={{ r: 4 }} name="Net" />+ <Line type="monotone" dataKey="ebitdaMargin" stroke={COLORS.PURPLE} strokeWidth={2} dot={{ r: 4 }} name="EBITDA" />+ </LineChart>+ </ResponsiveContainer>+ </ChartWrapper></div>- </div>- {/* Financial Comparison Charts - 3 Charts in a Row */}- <div style={{- backgroundColor: COLORS.PANEL_BG,- border: `1px solid ${COLORS.BORDER}`,- padding: '12px',- marginBottom: '8px',- }}>- <div style={{ color: COLORS.ORANGE, fontSize: `${fontSize + 3}px`, fontWeight: 'bold', marginBottom: '12px' }}>- FINANCIAL TRENDS COMPARISON (in Billions $)+ {/* Revenue & Earnings Trend */}+ <div style={{ marginTop: '16px' }}>+ <ChartWrapper title="Revenue & Earnings Trend (Billions $)" color={COLORS.BLUE} height={220}>+ <ResponsiveContainer width="100%" height="100%">+ <ComposedChart data={revenueTrend} margin={{ top: 10, right: 30, left: 0, bottom: 10 }}>+ <CartesianGrid strokeDasharray="3 3" stroke={COLORS.BORDER} opacity={0.3} />+ <XAxis dataKey="period" tick={{ fill: COLORS.GRAY, fontSize: 11 }} axisLine={{ stroke: COLORS.BORDER }} />+ <YAxis tick={{ fill: COLORS.GRAY, fontSize: 11 }} tickFormatter={(v) => `$${v.toFixed(0)}B`} axisLine={{ stroke: COLORS.BORDER }} />+ <Tooltip content={<CustomTooltip formatter={(v: number) => `$${v.toFixed(2)}B`} />} />+ <Legend wrapperStyle={{ fontSize: '11px' }} />+ <Bar dataKey="revenue" fill={COLORS.BLUE} name="Revenue" radius={[4, 4, 0, 0]} />+ <Bar dataKey="grossProfit" fill={COLORS.CYAN} name="Gross Profit" radius={[4, 4, 0, 0]} />+ <Line type="monotone" dataKey="operatingIncome" stroke={COLORS.ORANGE} strokeWidth={2} dot={{ r: 4 }} name="Operating Inc" />+ <Line type="monotone" dataKey="netIncome" stroke={COLORS.GREEN} strokeWidth={2} dot={{ r: 4 }} name="Net Income" />+ </ComposedChart>+ </ResponsiveContainer>+ </ChartWrapper></div>+ </SectionPanel>- {/* Chart Controls */}- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '12px', marginBottom: '12px' }}>- {[- { label: 'CHART 1 METRICS:', metrics: chart1Metrics, setMetrics: setChart1Metrics, color: COLORS.GREEN },- { label: 'CHART 2 METRICS:', metrics: chart2Metrics, setMetrics: setChart2Metrics, color: COLORS.ORANGE },- { label: 'CHART 3 METRICS:', metrics: chart3Metrics, setMetrics: setChart3Metrics, color: COLORS.MAGENTA },- ].map(({ label, metrics, setMetrics, color }) => (- <div key={label}>- <div style={{ color: COLORS.CYAN, fontSize: `${fontSize}px`, fontWeight: 'bold', marginBottom: '6px' }}>- {label}+ {/* ===== RETURN METRICS & DUPONT ANALYSIS ===== */}+ <SectionPanel+ title="Return on Investment & DuPont Analysis"+ color={COLORS.CYAN}+ icon={<Target size={16} color={COLORS.CYAN} />}+ >+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '16px' }}>+ {/* Return Metrics */}+ <div>+ <div style={{ color: COLORS.WHITE, fontSize: '12px', fontWeight: 600, marginBottom: '10px', paddingBottom: '6px', borderBottom: `1px solid ${COLORS.CYAN}40` }}>+ RETURN METRICS+ </div>+ <div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>+ <HealthScore label="Return on Equity (ROE)" value={roe} max={0.5} thresholds={{ good: 0.15, warning: 0.08 }} format="percent" description="Profit per shareholder dollar" />+ <HealthScore label="Return on Assets (ROA)" value={roa} max={0.3} thresholds={{ good: 0.08, warning: 0.04 }} format="percent" description="Asset utilization efficiency" />+ <HealthScore label="Return on Invested Capital" value={roic} max={0.3} thresholds={{ good: 0.12, warning: 0.06 }} format="percent" description="Capital allocation effectiveness" />+ <HealthScore label="Return on Capital Employed" value={roce} max={0.3} thresholds={{ good: 0.15, warning: 0.08 }} format="percent" description="Operating return on capital" />+ </div>+ </div>++ {/* DuPont Breakdown */}+ <div>+ <div style={{ color: COLORS.WHITE, fontSize: '12px', fontWeight: 600, marginBottom: '10px', paddingBottom: '6px', borderBottom: `1px solid ${COLORS.PURPLE}40` }}>+ DUPONT ANALYSIS+ </div>+ <div style={{ backgroundColor: COLORS.DARK_BG, border: BORDERS.STANDARD, padding: '16px', borderRadius: '4px' }}>+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '16px' }}>+ <div style={{ textAlign: 'center' }}>+ <div style={{ color: COLORS.GREEN, fontSize: '18px', fontWeight: 700 }}>{formatPercent(dupontNetMargin)}</div>+ <div style={{ color: COLORS.GRAY, fontSize: '10px' }}>Net Margin</div>+ </div>+ <div style={{ color: COLORS.MUTED, fontSize: '16px' }}>×</div>+ <div style={{ textAlign: 'center' }}>+ <div style={{ color: COLORS.CYAN, fontSize: '18px', fontWeight: 700 }}>{dupontAssetTurnover.toFixed(2)}x</div>+ <div style={{ color: COLORS.GRAY, fontSize: '10px' }}>Asset Turn</div>+ </div>+ <div style={{ color: COLORS.MUTED, fontSize: '16px' }}>×</div>+ <div style={{ textAlign: 'center' }}>+ <div style={{ color: COLORS.ORANGE, fontSize: '18px', fontWeight: 700 }}>{equityMultiplier.toFixed(2)}x</div>+ <div style={{ color: COLORS.GRAY, fontSize: '10px' }}>Eq. Mult</div>+ </div></div>- <div style={{ display: 'flex', flexWrap: 'wrap', gap: '4px' }}>- {allMetrics.slice(0, 8).map((metric) => (- <button- key={metric}- onClick={() => {- setMetrics(prev =>- prev.includes(metric)- ? prev.filter(m => m !== metric)- : [...prev, metric]- );- }}- style={{- backgroundColor: metrics.includes(metric) ? color : COLORS.DARK_BG,- border: `1px solid ${metrics.includes(metric) ? color : COLORS.BORDER}`,- color: metrics.includes(metric) ? COLORS.DARK_BG : COLORS.WHITE,- padding: '3px 6px',- fontSize: `${fontSize - 3}px`,- cursor: 'pointer',- fontWeight: metrics.includes(metric) ? 'bold' : 'normal',- }}- >- {metric.substring(0, 15)}- </button>- ))}+ <div style={{ borderTop: `1px solid ${COLORS.BORDER}`, paddingTop: '12px', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '8px' }}>+ <ArrowRight size={16} color={COLORS.PURPLE} />+ <span style={{ color: COLORS.WHITE, fontSize: '12px' }}>ROE =</span>+ <span style={{ color: COLORS.PURPLE, fontSize: '20px', fontWeight: 700 }}>{formatPercent(roe)}</span></div></div>- ))}++ {/* Four additional DuPont cards */}+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '10px', marginTop: '12px' }}>+ <div style={{ backgroundColor: COLORS.DARK_BG, border: BORDERS.STANDARD, padding: '12px', borderRadius: '4px', textAlign: 'center' }}>+ <div style={{ color: COLORS.GRAY, fontSize: '10px', marginBottom: '4px', textTransform: 'uppercase' }}>ROA (2-Step)</div>+ <div style={{ color: COLORS.BLUE, fontSize: '18px', fontWeight: 700 }}>{formatPercent(roa)}</div>+ <div style={{ color: COLORS.MUTED, fontSize: '9px', marginTop: '4px' }}>Net Margin × Asset Turnover</div>+ </div>+ <div style={{ backgroundColor: COLORS.DARK_BG, border: BORDERS.STANDARD, padding: '12px', borderRadius: '4px', textAlign: 'center' }}>+ <div style={{ color: COLORS.GRAY, fontSize: '10px', marginBottom: '4px', textTransform: 'uppercase' }}>Financial Leverage</div>+ <div style={{ color: equityMultiplier <= 2 ? COLORS.GREEN : equityMultiplier <= 3 ? COLORS.YELLOW : COLORS.RED, fontSize: '18px', fontWeight: 700 }}>{equityMultiplier.toFixed(2)}x</div>+ <div style={{ color: COLORS.MUTED, fontSize: '9px', marginTop: '4px' }}>Total Assets / Total Equity</div>+ </div>+ <div style={{ backgroundColor: COLORS.DARK_BG, border: BORDERS.STANDARD, padding: '12px', borderRadius: '4px', textAlign: 'center' }}>+ <div style={{ color: COLORS.GRAY, fontSize: '10px', marginBottom: '4px', textTransform: 'uppercase' }}>Profit per $ Equity</div>+ <div style={{ color: COLORS.CYAN, fontSize: '18px', fontWeight: 700 }}>${totalEquity > 0 ? (netIncome / totalEquity).toFixed(2) : '0.00'}</div>+ <div style={{ color: COLORS.MUTED, fontSize: '9px', marginTop: '4px' }}>Net Income / Shareholders Equity</div>+ </div>+ <div style={{ backgroundColor: COLORS.DARK_BG, border: BORDERS.STANDARD, padding: '12px', borderRadius: '4px', textAlign: 'center' }}>+ <div style={{ color: COLORS.GRAY, fontSize: '10px', marginBottom: '4px', textTransform: 'uppercase' }}>Leverage Effect</div>+ <div style={{ color: roe > roa ? COLORS.GREEN : COLORS.RED, fontSize: '18px', fontWeight: 700 }}>{roe > roa ? '+' : ''}{((roe - roa) * 100).toFixed(1)}%</div>+ <div style={{ color: COLORS.MUTED, fontSize: '9px', marginTop: '4px' }}>ROE - ROA (Debt Amplification)</div>+ </div>+ </div>+ </div>++ {/* Return Trends Chart */}+ <ChartWrapper title="Return Metrics Trend (%)" color={COLORS.CYAN} height={200}>+ <ResponsiveContainer width="100%" height="100%">+ <AreaChart data={returnTrend} margin={{ top: 10, right: 20, left: 0, bottom: 10 }}>+ <CartesianGrid strokeDasharray="3 3" stroke={COLORS.BORDER} opacity={0.3} />+ <XAxis dataKey="period" tick={{ fill: COLORS.GRAY, fontSize: 11 }} />+ <YAxis tick={{ fill: COLORS.GRAY, fontSize: 11 }} tickFormatter={(v) => `${v.toFixed(0)}%`} />+ <Tooltip content={<CustomTooltip formatter={(v: number) => `${v.toFixed(1)}%`} />} />+ <Area type="monotone" dataKey="roe" stroke={COLORS.CYAN} fill={COLORS.CYAN} fillOpacity={0.3} strokeWidth={2} name="ROE" />+ <Area type="monotone" dataKey="roa" stroke={COLORS.GREEN} fill={COLORS.GREEN} fillOpacity={0.3} strokeWidth={2} name="ROA" />+ </AreaChart>+ </ResponsiveContainer>+ </ChartWrapper></div>+ </SectionPanel>- {/* 3 Charts Side by Side */}- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '12px' }}>+ {/* ===== BALANCE SHEET ANALYSIS ===== */}+ <SectionPanel+ title="Balance Sheet Analysis"+ color={COLORS.BLUE}+ icon={<Scale size={16} color={COLORS.BLUE} />}+ >+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '16px' }}>+ {/* Liquidity Ratios */}<div>- <div style={{ color: COLORS.GREEN, fontSize: `${fontSize}px`, fontWeight: 'bold', marginBottom: '6px', textAlign: 'center' }}>- {chart1Metrics.join(', ') || 'Select metrics'}+ <div style={{ color: COLORS.CYAN, fontSize: '12px', fontWeight: 600, marginBottom: '10px', paddingBottom: '6px', borderBottom: `1px solid ${COLORS.CYAN}40` }}>+ LIQUIDITY RATIOS+ </div>+ <div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>+ <HealthScore label="Current Ratio" value={currentRatio} max={4} thresholds={{ good: 1.5, warning: 1.0 }} format="ratio" description="Short-term solvency" />+ <HealthScore label="Quick Ratio" value={quickRatio} max={3} thresholds={{ good: 1.0, warning: 0.5 }} format="ratio" description="Acid test ratio" />+ <HealthScore label="Cash Ratio" value={cashRatio} max={2} thresholds={{ good: 0.5, warning: 0.2 }} format="ratio" description="Immediate liquidity" />+ </div>+ <div style={{ marginTop: '12px', backgroundColor: COLORS.DARK_BG, border: BORDERS.STANDARD, padding: '12px', borderRadius: '4px' }}>+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>+ <span style={{ color: COLORS.GRAY, fontSize: '11px' }}>Working Capital</span>+ <span style={{ color: workingCapital >= 0 ? COLORS.GREEN : COLORS.RED, fontSize: '14px', fontWeight: 700 }}>{formatCurrency(workingCapital)}</span>+ </div></div>- <div ref={financialChart1Ref} style={{ backgroundColor: COLORS.DARK_BG }} /></div>++ {/* Leverage Ratios */}<div>- <div style={{ color: COLORS.ORANGE, fontSize: `${fontSize}px`, fontWeight: 'bold', marginBottom: '6px', textAlign: 'center' }}>- {chart2Metrics.join(', ') || 'Select metrics'}+ <div style={{ color: COLORS.ORANGE, fontSize: '12px', fontWeight: 600, marginBottom: '10px', paddingBottom: '6px', borderBottom: `1px solid ${COLORS.ORANGE}40` }}>+ LEVERAGE & SOLVENCY+ </div>+ <div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>+ <HealthScore label="Debt to Equity" value={debtToEquity} max={3} thresholds={{ good: 0.5, warning: 1.0 }} higherIsBetter={false} format="ratio" description="Financial leverage" />+ <HealthScore label="Debt to Assets" value={debtToAssets} max={1} thresholds={{ good: 0.3, warning: 0.5 }} higherIsBetter={false} format="percent" description="Asset coverage" />+ <HealthScore label="Interest Coverage" value={Math.min(interestCoverage, 20)} max={20} thresholds={{ good: 5, warning: 2 }} format="ratio" description="Debt service ability" />+ </div>+ <div style={{ marginTop: '12px', backgroundColor: COLORS.DARK_BG, border: BORDERS.STANDARD, padding: '12px', borderRadius: '4px' }}>+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>+ <span style={{ color: COLORS.GRAY, fontSize: '11px' }}>Net Debt</span>+ <span style={{ color: netDebt <= 0 ? COLORS.GREEN : COLORS.ORANGE, fontSize: '14px', fontWeight: 700 }}>{formatCurrency(netDebt)}</span>+ </div></div>- <div ref={financialChart2Ref} style={{ backgroundColor: COLORS.DARK_BG }} /></div>++ {/* Capital Structure Pie */}+ <ChartWrapper title="Capital Structure" color={COLORS.PURPLE} height={200}>+ <ResponsiveContainer width="100%" height="100%">+ <PieChart>+ <Pie+ data={capitalStructure}+ cx="50%"+ cy="45%"+ innerRadius={40}+ outerRadius={65}+ paddingAngle={2}+ dataKey="value"+ >+ {capitalStructure.map((entry, index) => (+ <Cell key={`cell-${index}`} fill={entry.color} />+ ))}+ </Pie>+ <Tooltip content={<CustomTooltip formatter={(v: number) => `$${v.toFixed(2)}B`} />} />+ <Legend+ wrapperStyle={{ fontSize: '10px' }}+ layout="horizontal"+ align="center"+ verticalAlign="bottom"+ formatter={(value, entry: any) => {+ const item = capitalStructure.find(d => d.name === value);+ const total = capitalStructure.reduce((sum, d) => sum + d.value, 0);+ const percent = item && total ? ((item.value / total) * 100).toFixed(0) : '0';+ return <span style={{ color: entry.color }}>{value}: {percent}%</span>;+ }}+ />+ </PieChart>+ </ResponsiveContainer>+ </ChartWrapper>+ </div>++ {/* Balance Sheet Trend & Composition */}+ <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 1fr', gap: '16px', marginTop: '16px' }}>+ {/* Balance Sheet Trend */}+ <ChartWrapper title="Balance Sheet Trend (Billions $)" color={COLORS.BLUE} height={220}>+ <ResponsiveContainer width="100%" height="100%">+ <ComposedChart data={balanceTrend} margin={{ top: 10, right: 30, left: 0, bottom: 10 }}>+ <CartesianGrid strokeDasharray="3 3" stroke={COLORS.BORDER} opacity={0.3} />+ <XAxis dataKey="period" tick={{ fill: COLORS.GRAY, fontSize: 11 }} />+ <YAxis tick={{ fill: COLORS.GRAY, fontSize: 11 }} tickFormatter={(v) => `$${v.toFixed(0)}B`} />+ <Tooltip content={<CustomTooltip formatter={(v: number) => `$${v.toFixed(2)}B`} />} />+ <Legend wrapperStyle={{ fontSize: '11px' }} />+ <Bar dataKey="assets" fill={COLORS.BLUE} name="Assets" radius={[4, 4, 0, 0]} />+ <Bar dataKey="liabilities" fill={COLORS.RED} name="Liabilities" radius={[4, 4, 0, 0]} />+ <Line type="monotone" dataKey="equity" stroke={COLORS.GREEN} strokeWidth={2} dot={{ r: 4 }} name="Equity" />+ <Line type="monotone" dataKey="netDebt" stroke={COLORS.ORANGE} strokeWidth={2} dot={{ r: 4 }} name="Net Debt" />+ </ComposedChart>+ </ResponsiveContainer>+ </ChartWrapper>++ {/* Asset Composition */}+ <ChartWrapper title="Asset Mix" color={COLORS.GREEN} height={220}>+ <ResponsiveContainer width="100%" height="100%">+ <PieChart>+ <Pie+ data={assetComposition}+ cx="50%"+ cy="50%"+ innerRadius={35}+ outerRadius={65}+ paddingAngle={2}+ dataKey="value"+ >+ {assetComposition.map((entry, index) => (+ <Cell key={`cell-${index}`} fill={entry.color} />+ ))}+ </Pie>+ <Tooltip content={<CustomTooltip formatter={(v: number) => `$${v.toFixed(2)}B`} />} />+ <Legend wrapperStyle={{ fontSize: '10px' }} layout="vertical" align="right" verticalAlign="middle" />+ </PieChart>+ </ResponsiveContainer>+ </ChartWrapper>++ {/* Liability Composition */}+ <ChartWrapper title="Liability Mix" color={COLORS.RED} height={220}>+ <ResponsiveContainer width="100%" height="100%">+ <PieChart>+ <Pie+ data={liabilityComposition}+ cx="50%"+ cy="50%"+ innerRadius={35}+ outerRadius={65}+ paddingAngle={2}+ dataKey="value"+ >+ {liabilityComposition.map((entry, index) => (+ <Cell key={`cell-${index}`} fill={entry.color} />+ ))}+ </Pie>+ <Tooltip content={<CustomTooltip formatter={(v: number) => `$${v.toFixed(2)}B`} />} />+ <Legend wrapperStyle={{ fontSize: '10px' }} layout="vertical" align="right" verticalAlign="middle" />+ </PieChart>+ </ResponsiveContainer>+ </ChartWrapper>+ </div>+ </SectionPanel>++ {/* ===== CASH FLOW ANALYSIS ===== */}+ <SectionPanel+ title="Cash Flow Analysis"+ color={COLORS.ORANGE}+ icon={<CircleDollarSign size={16} color={COLORS.ORANGE} />}+ >+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>+ {/* Cash Flow Summary */}<div>- <div style={{ color: COLORS.MAGENTA, fontSize: `${fontSize}px`, fontWeight: 'bold', marginBottom: '6px', textAlign: 'center' }}>- {chart3Metrics.join(', ') || 'Select metrics'}+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '10px', marginBottom: '16px' }}>+ <MetricCard label="Operating CF" value={formatCurrency(operatingCashflow)} color={operatingCashflow >= 0 ? COLORS.GREEN : COLORS.RED} icon={<Zap size={16} />} />+ <MetricCard label="Investing CF" value={formatCurrency(processedData.investingCashflow)} color={COLORS.ORANGE} icon={<Building2 size={16} />} />+ <MetricCard label="Financing CF" value={formatCurrency(processedData.financingCashflow)} color={COLORS.PURPLE} icon={<Landmark size={16} />} />+ <MetricCard label="Free Cash Flow" value={formatCurrency(freeCashflow)} color={freeCashflow >= 0 ? COLORS.CYAN : COLORS.RED} icon={<PiggyBank size={16} />} subtitle={`${formatPercent(fcfMargin)} of revenue`} />+ </div>++ {/* Cash Flow Ratios */}+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '10px' }}>+ <HealthScore label="FCF Margin" value={fcfMargin} max={0.5} thresholds={{ good: 0.1, warning: 0.05 }} format="percent" />+ <HealthScore label="CapEx / Revenue" value={capexToRevenue} max={0.3} thresholds={{ good: 0.05, warning: 0.1 }} higherIsBetter={false} format="percent" />+ <HealthScore label="CapEx / D&A" value={capexToDepreciation} max={3} thresholds={{ good: 1.2, warning: 2 }} format="ratio" description="Growth investment" />+ <HealthScore label="OCF / Current Liab" value={processedData.operatingCashflowRatio} max={2} thresholds={{ good: 1.0, warning: 0.5 }} format="ratio" /></div>- <div ref={financialChart3Ref} style={{ backgroundColor: COLORS.DARK_BG }} /></div>- </div>- </div>- {/* Financial Comparison Table */}- <div style={{- backgroundColor: COLORS.PANEL_BG,- border: `1px solid ${COLORS.BORDER}`,- padding: '12px',- marginBottom: '8px',- }}>- <div style={{ color: COLORS.CYAN, fontSize: `${fontSize + 3}px`, fontWeight: 'bold', marginBottom: '12px' }}>- YEAR-OVER-YEAR COMPARISON ({selectedMetrics.length} Metrics)+ {/* Cash Flow Trend Chart */}+ <ChartWrapper title="Cash Flow Trends (Billions $)" color={COLORS.ORANGE} height={280}>+ <ResponsiveContainer width="100%" height="100%">+ <ComposedChart data={cashflowTrend} margin={{ top: 10, right: 30, left: 0, bottom: 10 }}>+ <CartesianGrid strokeDasharray="3 3" stroke={COLORS.BORDER} opacity={0.3} />+ <XAxis dataKey="period" tick={{ fill: COLORS.GRAY, fontSize: 11 }} />+ <YAxis tick={{ fill: COLORS.GRAY, fontSize: 11 }} tickFormatter={(v) => `$${v.toFixed(0)}B`} />+ <Tooltip content={<CustomTooltip formatter={(v: number) => `$${v.toFixed(2)}B`} />} />+ <Legend wrapperStyle={{ fontSize: '11px' }} />+ <ReferenceLine y={0} stroke={COLORS.GRAY} strokeDasharray="3 3" />+ <Bar dataKey="operating" fill={COLORS.GREEN} name="Operating" radius={[4, 4, 0, 0]} />+ <Bar dataKey="investing" fill={COLORS.ORANGE} name="Investing" radius={[4, 4, 0, 0]} />+ <Bar dataKey="financing" fill={COLORS.PURPLE} name="Financing" radius={[4, 4, 0, 0]} />+ <Line type="monotone" dataKey="freeCashflow" stroke={COLORS.CYAN} strokeWidth={3} dot={{ r: 5 }} name="FCF" />+ </ComposedChart>+ </ResponsiveContainer>+ </ChartWrapper></div>- {selectedMetrics.length === 0 ? (- <div style={{ color: COLORS.YELLOW, fontSize: `${fontSize + 1}px`, textAlign: 'center', padding: '20px' }}>- Please select at least one metric to compare+ {/* Cash Flow Uses */}+ <div style={{ marginTop: '16px', display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px' }}>+ <div style={{ backgroundColor: COLORS.DARK_BG, border: BORDERS.STANDARD, padding: '14px', borderRadius: '4px', textAlign: 'center' }}>+ <div style={{ color: COLORS.ORANGE, fontSize: '11px', textTransform: 'uppercase', marginBottom: '6px' }}>Capital Expenditure</div>+ <div style={{ color: COLORS.WHITE, fontSize: '18px', fontWeight: 700 }}>{formatCurrency(-capex)}</div></div>- ) : (- <div style={{ overflowX: 'auto' }} className="custom-scrollbar">- <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: `${fontSize}px` }}>- <thead>- <tr style={{ borderBottom: `2px solid ${COLORS.BORDER}` }}>- <th style={{ textAlign: 'left', padding: '10px', color: COLORS.GRAY, fontSize: `${fontSize + 1}px` }}>METRIC</th>- {Object.keys(financials.income_statement).slice(0, showYearsCount).map((period) => (- <th key={period} style={{ textAlign: 'right', padding: '10px', color: COLORS.ORANGE, fontSize: `${fontSize + 1}px` }}>- {getYearFromPeriod(period)}- </th>- ))}- </tr>- </thead>- <tbody>- {selectedMetrics.map((metric) => {- const periods = Object.keys(financials.income_statement).slice(0, showYearsCount);- return (- <tr key={metric} style={{ borderBottom: `1px solid rgba(255,255,255,0.05)` }}>- <td style={{ padding: '10px', color: COLORS.WHITE, fontWeight: 'bold', fontSize: `${fontSize}px` }}>{metric}</td>- {periods.map((period) => {- const value = financials.income_statement[period][metric];- return (- <td key={period} style={{ textAlign: 'right', padding: '10px', color: COLORS.CYAN, fontSize: `${fontSize}px` }}>- {value ? (metric.includes('EPS') ? `$${formatNumber(value)}` : formatLargeNumber(value)) : 'N/A'}- </td>- );- })}- </tr>- );- })}- </tbody>- </table>+ <div style={{ backgroundColor: COLORS.DARK_BG, border: BORDERS.STANDARD, padding: '14px', borderRadius: '4px', textAlign: 'center' }}>+ <div style={{ color: COLORS.GREEN, fontSize: '11px', textTransform: 'uppercase', marginBottom: '6px' }}>Dividends Paid</div>+ <div style={{ color: COLORS.WHITE, fontSize: '18px', fontWeight: 700 }}>{formatCurrency(-processedData.dividendsPaid)}</div></div>- )}- </div>-- {/* Detailed Financial Statements */}- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '8px' }}>- {/* Income Statement */}- <div style={{- backgroundColor: COLORS.PANEL_BG,- border: `1px solid ${COLORS.BORDER}`,- padding: '8px',- }}>- <div style={{ color: COLORS.GREEN, fontSize: `${fontSize + 2}px`, fontWeight: 'bold', marginBottom: '8px', borderBottom: `1px solid ${COLORS.BORDER}`, paddingBottom: '4px' }}>- INCOME STATEMENT (Latest)+ <div style={{ backgroundColor: COLORS.DARK_BG, border: BORDERS.STANDARD, padding: '14px', borderRadius: '4px', textAlign: 'center' }}>+ <div style={{ color: COLORS.CYAN, fontSize: '11px', textTransform: 'uppercase', marginBottom: '6px' }}>Stock Repurchase</div>+ <div style={{ color: COLORS.WHITE, fontSize: '18px', fontWeight: 700 }}>{processedData.stockRepurchase > 0 ? formatCurrency(-processedData.stockRepurchase) : 'No Buybacks'}</div></div>- <div style={{ fontSize: `${fontSize}px`, maxHeight: '500px', overflow: 'auto' }} className="custom-scrollbar">- {Object.keys(financials.income_statement).length > 0 ? (- Object.entries(Object.values(financials.income_statement)[0] || {}).map(([metric, _], idx) => {- const latestPeriod = Object.keys(financials.income_statement)[0];- const value = financials.income_statement[latestPeriod][metric];- return (- <div key={idx} style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '6px', paddingBottom: '6px', borderBottom: `1px solid rgba(255,255,255,0.05)` }}>- <span style={{ color: COLORS.GRAY, fontSize: `${fontSize - 1}px`, maxWidth: '60%' }}>{metric}:</span>- <span style={{ color: COLORS.CYAN, fontSize: `${fontSize}px` }}>{formatLargeNumber(value)}</span>- </div>- );- })- ) : (- <div style={{ color: COLORS.GRAY, textAlign: 'center', padding: '20px', fontSize: `${fontSize}px` }}>No data available</div>- )}+ <div style={{ backgroundColor: COLORS.DARK_BG, border: BORDERS.STANDARD, padding: '14px', borderRadius: '4px', textAlign: 'center' }}>+ <div style={{ color: COLORS.PURPLE, fontSize: '11px', textTransform: 'uppercase', marginBottom: '6px' }}>Net Debt Change</div>+ <div style={{ color: COLORS.WHITE, fontSize: '18px', fontWeight: 700 }}>{formatCurrency(processedData.debtIssuance - processedData.debtRepayment)}</div></div></div>+ </SectionPanel>- {/* Balance Sheet */}- <div style={{- backgroundColor: COLORS.PANEL_BG,- border: `1px solid ${COLORS.BORDER}`,- padding: '8px',- }}>- <div style={{ color: COLORS.YELLOW, fontSize: `${fontSize + 2}px`, fontWeight: 'bold', marginBottom: '8px', borderBottom: `1px solid ${COLORS.BORDER}`, paddingBottom: '4px' }}>- BALANCE SHEET (Latest)+ {/* ===== EFFICIENCY METRICS ===== */}+ <SectionPanel+ title="Efficiency & Working Capital"+ color={COLORS.PURPLE}+ icon={<Clock size={16} color={COLORS.PURPLE} />}+ >+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '16px' }}>+ {/* Turnover Ratios */}+ <div>+ <div style={{ color: COLORS.PURPLE, fontSize: '12px', fontWeight: 600, marginBottom: '10px', paddingBottom: '6px', borderBottom: `1px solid ${COLORS.PURPLE}40` }}>+ TURNOVER RATIOS+ </div>+ <div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>+ <HealthScore label="Asset Turnover" value={assetTurnover} max={3} thresholds={{ good: 1.0, warning: 0.5 }} format="ratio" description="Revenue per $ of assets" />+ <HealthScore label="Inventory Turnover" value={inventoryTurnover} max={15} thresholds={{ good: 6, warning: 3 }} format="ratio" description="Inventory efficiency" />+ <HealthScore label="Receivables Turnover" value={receivablesTurnover} max={20} thresholds={{ good: 8, warning: 4 }} format="ratio" description="Collection efficiency" />+ <HealthScore label="Fixed Asset Turnover" value={processedData.fixedAssetTurnover} max={10} thresholds={{ good: 3, warning: 1.5 }} format="ratio" description="PP&E utilization" />+ </div></div>- <div style={{ fontSize: `${fontSize}px`, maxHeight: '500px', overflow: 'auto' }} className="custom-scrollbar">- {Object.keys(financials.balance_sheet).length > 0 ? (- Object.entries(Object.values(financials.balance_sheet)[0] || {}).map(([metric, _], idx) => {- const latestPeriod = Object.keys(financials.balance_sheet)[0];- const value = financials.balance_sheet[latestPeriod][metric];- return (- <div key={idx} style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '6px', paddingBottom: '6px', borderBottom: `1px solid rgba(255,255,255,0.05)` }}>- <span style={{ color: COLORS.GRAY, fontSize: `${fontSize - 1}px`, maxWidth: '60%' }}>{metric}:</span>- <span style={{ color: COLORS.CYAN, fontSize: `${fontSize}px` }}>{formatLargeNumber(value)}</span>- </div>- );- })- ) : (- <div style={{ color: COLORS.GRAY, textAlign: 'center', padding: '20px', fontSize: `${fontSize}px` }}>No data available</div>- )}++ {/* Cash Conversion Cycle */}+ <div>+ <div style={{ color: COLORS.CYAN, fontSize: '12px', fontWeight: 600, marginBottom: '10px', paddingBottom: '6px', borderBottom: `1px solid ${COLORS.CYAN}40` }}>+ CASH CONVERSION CYCLE+ </div>+ <div style={{ backgroundColor: COLORS.DARK_BG, border: BORDERS.STANDARD, padding: '16px', borderRadius: '4px' }}>+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '12px' }}>+ <div style={{ textAlign: 'center', flex: 1 }}>+ <div style={{ color: COLORS.BLUE, fontSize: '20px', fontWeight: 700 }}>{daysInventory.toFixed(0)}</div>+ <div style={{ color: COLORS.GRAY, fontSize: '10px' }}>Days Inventory</div>+ </div>+ <div style={{ color: COLORS.MUTED, fontSize: '14px' }}>+</div>+ <div style={{ textAlign: 'center', flex: 1 }}>+ <div style={{ color: COLORS.GREEN, fontSize: '20px', fontWeight: 700 }}>{daysReceivables.toFixed(0)}</div>+ <div style={{ color: COLORS.GRAY, fontSize: '10px' }}>Days Receivables</div>+ </div>+ <div style={{ color: COLORS.MUTED, fontSize: '14px' }}>−</div>+ <div style={{ textAlign: 'center', flex: 1 }}>+ <div style={{ color: COLORS.ORANGE, fontSize: '20px', fontWeight: 700 }}>{daysPayables.toFixed(0)}</div>+ <div style={{ color: COLORS.GRAY, fontSize: '10px' }}>Days Payables</div>+ </div>+ </div>+ <div style={{ borderTop: `1px solid ${COLORS.BORDER}`, paddingTop: '12px', textAlign: 'center' }}>+ <div style={{ color: COLORS.GRAY, fontSize: '11px', marginBottom: '4px' }}>Cash Conversion Cycle</div>+ <div style={{ color: cashConversionCycle <= 30 ? COLORS.GREEN : cashConversionCycle <= 60 ? COLORS.YELLOW : COLORS.RED, fontSize: '24px', fontWeight: 700 }}>+ {cashConversionCycle.toFixed(0)} days+ </div>+ </div>+ </div>++ {/* Four additional cards */}+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '10px', marginTop: '12px' }}>+ <div style={{ backgroundColor: COLORS.DARK_BG, border: BORDERS.STANDARD, padding: '12px', borderRadius: '4px', textAlign: 'center' }}>+ <div style={{ color: COLORS.GRAY, fontSize: '10px', marginBottom: '4px', textTransform: 'uppercase' }}>Working Capital</div>+ <div style={{ color: workingCapital >= 0 ? COLORS.GREEN : COLORS.RED, fontSize: '18px', fontWeight: 700 }}>{formatCurrency(workingCapital)}</div>+ <div style={{ color: COLORS.MUTED, fontSize: '9px', marginTop: '4px' }}>Current Assets - Current Liab</div>+ </div>+ <div style={{ backgroundColor: COLORS.DARK_BG, border: BORDERS.STANDARD, padding: '12px', borderRadius: '4px', textAlign: 'center' }}>+ <div style={{ color: COLORS.GRAY, fontSize: '10px', marginBottom: '4px', textTransform: 'uppercase' }}>Operating Cycle</div>+ <div style={{ color: COLORS.PURPLE, fontSize: '18px', fontWeight: 700 }}>{(daysInventory + daysReceivables).toFixed(0)} days</div>+ <div style={{ color: COLORS.MUTED, fontSize: '9px', marginTop: '4px' }}>Days Inv + Days Receivables</div>+ </div>+ <div style={{ backgroundColor: COLORS.DARK_BG, border: BORDERS.STANDARD, padding: '12px', borderRadius: '4px', textAlign: 'center' }}>+ <div style={{ color: COLORS.GRAY, fontSize: '10px', marginBottom: '4px', textTransform: 'uppercase' }}>WC Turnover</div>+ <div style={{ color: COLORS.BLUE, fontSize: '18px', fontWeight: 700 }}>{workingCapital !== 0 ? (revenue / workingCapital).toFixed(2) : '0.00'}x</div>+ <div style={{ color: COLORS.MUTED, fontSize: '9px', marginTop: '4px' }}>Revenue / Working Capital</div>+ </div>+ <div style={{ backgroundColor: COLORS.DARK_BG, border: BORDERS.STANDARD, padding: '12px', borderRadius: '4px', textAlign: 'center' }}>+ <div style={{ color: COLORS.GRAY, fontSize: '10px', marginBottom: '4px', textTransform: 'uppercase' }}>Cash to Current Liab</div>+ <div style={{ color: cashRatio >= 0.5 ? COLORS.GREEN : cashRatio >= 0.2 ? COLORS.YELLOW : COLORS.RED, fontSize: '18px', fontWeight: 700 }}>{formatPercent(cashRatio)}</div>+ <div style={{ color: COLORS.MUTED, fontSize: '9px', marginTop: '4px' }}>Immediate Liquidity Coverage</div>+ </div>+ </div>+ </div>++ {/* Efficiency Radar */}+ <div style={{ backgroundColor: COLORS.DARK_BG, border: BORDERS.STANDARD, borderRadius: '4px', overflow: 'hidden' }}>+ <div style={{+ padding: '10px 14px',+ borderBottom: `2px solid ${COLORS.PURPLE}`,+ backgroundColor: COLORS.HEADER_BG+ }}>+ <span style={{ color: COLORS.PURPLE, fontSize: '12px', fontWeight: 700, textTransform: 'uppercase' }}>Efficiency Scorecard</span>+ </div>+ <div style={{ height: '280px', padding: 0 }}>+ <ResponsiveContainer width="100%" height="100%">+ <RadarChart cx="50%" cy="50%" outerRadius="70%" data={efficiencyRadar}>+ <PolarGrid stroke={COLORS.BORDER} />+ <PolarAngleAxis dataKey="metric" tick={{ fill: COLORS.GRAY, fontSize: 12 }} />+ <PolarRadiusAxis angle={30} domain={[0, 100]} tick={false} axisLine={false} />+ <Radar name="Efficiency" dataKey="value" stroke={COLORS.PURPLE} fill={COLORS.PURPLE} fillOpacity={0.5} strokeWidth={2} />+ </RadarChart>+ </ResponsiveContainer>+ </div></div></div>+ </SectionPanel>- {/* Cash Flow */}- <div style={{- backgroundColor: COLORS.PANEL_BG,- border: `1px solid ${COLORS.BORDER}`,- padding: '8px',- }}>- <div style={{ color: COLORS.CYAN, fontSize: `${fontSize + 2}px`, fontWeight: 'bold', marginBottom: '8px', borderBottom: `1px solid ${COLORS.BORDER}`, paddingBottom: '4px' }}>- CASH FLOW STATEMENT (Latest)+ {/* ===== COST STRUCTURE ===== */}+ <SectionPanel+ title="Cost Structure & Operating Expenses"+ color={COLORS.YELLOW}+ icon={<Layers size={16} color={COLORS.YELLOW} />}+ defaultExpanded={false}+ >+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>+ {/* Operating Expenses Breakdown */}+ <ChartWrapper title="Operating Expense Breakdown" color={COLORS.YELLOW} height={250}>+ <ResponsiveContainer width="100%" height="100%">+ <BarChart data={opexBreakdown} layout="vertical" margin={{ top: 10, right: 30, left: 80, bottom: 10 }}>+ <CartesianGrid strokeDasharray="3 3" stroke={COLORS.BORDER} opacity={0.3} />+ <XAxis type="number" tick={{ fill: COLORS.GRAY, fontSize: 11 }} tickFormatter={(v) => `$${v.toFixed(0)}B`} />+ <YAxis type="category" dataKey="name" tick={{ fill: COLORS.GRAY, fontSize: 11 }} width={80} />+ <Tooltip content={<CustomTooltip formatter={(v: number) => `$${v.toFixed(2)}B`} />} />+ <Bar dataKey="value" radius={[0, 4, 4, 0]}>+ {opexBreakdown.map((entry, index) => (+ <Cell key={`cell-${index}`} fill={entry.color} />+ ))}+ </Bar>+ </BarChart>+ </ResponsiveContainer>+ </ChartWrapper>++ {/* Cost Metrics */}+ <div>+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '10px' }}>+ <div style={{ backgroundColor: COLORS.DARK_BG, border: BORDERS.STANDARD, padding: '14px', borderRadius: '4px' }}>+ <div style={{ color: COLORS.GRAY, fontSize: '11px', marginBottom: '6px' }}>Cost of Revenue</div>+ <div style={{ color: COLORS.RED, fontSize: '18px', fontWeight: 700 }}>{formatCurrency(processedData.costOfRevenue)}</div>+ <div style={{ color: COLORS.MUTED, fontSize: '10px' }}>{formatPercent(1 - grossMargin)} of revenue</div>+ </div>+ <div style={{ backgroundColor: COLORS.DARK_BG, border: BORDERS.STANDARD, padding: '14px', borderRadius: '4px' }}>+ <div style={{ color: COLORS.GRAY, fontSize: '11px', marginBottom: '6px' }}>Operating Expenses</div>+ <div style={{ color: COLORS.ORANGE, fontSize: '18px', fontWeight: 700 }}>{formatCurrency(processedData.operatingExpenses)}</div>+ <div style={{ color: COLORS.MUTED, fontSize: '10px' }}>{formatPercent(processedData.operatingExpenses / revenue)} of revenue</div>+ </div>+ <div style={{ backgroundColor: COLORS.DARK_BG, border: BORDERS.STANDARD, padding: '14px', borderRadius: '4px' }}>+ <div style={{ color: COLORS.GRAY, fontSize: '11px', marginBottom: '6px' }}>R&D Expense</div>+ <div style={{ color: COLORS.BLUE, fontSize: '18px', fontWeight: 700 }}>{formatCurrency(processedData.researchDev)}</div>+ <div style={{ color: COLORS.MUTED, fontSize: '10px' }}>{formatPercent(processedData.researchDev / revenue)} of revenue</div>+ </div>+ <div style={{ backgroundColor: COLORS.DARK_BG, border: BORDERS.STANDARD, padding: '14px', borderRadius: '4px' }}>+ <div style={{ color: COLORS.GRAY, fontSize: '11px', marginBottom: '6px' }}>SG&A Expense</div>+ <div style={{ color: COLORS.PURPLE, fontSize: '18px', fontWeight: 700 }}>{formatCurrency(processedData.sgaExpense)}</div>+ <div style={{ color: COLORS.MUTED, fontSize: '10px' }}>{formatPercent(processedData.sgaExpense / revenue)} of revenue</div>+ </div>+ <div style={{ backgroundColor: COLORS.DARK_BG, border: BORDERS.STANDARD, padding: '14px', borderRadius: '4px' }}>+ <div style={{ color: COLORS.GRAY, fontSize: '11px', marginBottom: '6px' }}>Interest Expense</div>+ <div style={{ color: COLORS.YELLOW, fontSize: '18px', fontWeight: 700 }}>{processedData.interestExpense > 0 ? formatCurrency(processedData.interestExpense) : 'Debt Free'}</div>+ <div style={{ color: COLORS.MUTED, fontSize: '10px' }}>{processedData.interestExpense > 0 ? `${formatPercent(processedData.interestExpense / revenue)} of revenue` : 'No interest payments'}</div>+ </div>+ <div style={{ backgroundColor: COLORS.DARK_BG, border: BORDERS.STANDARD, padding: '14px', borderRadius: '4px' }}>+ <div style={{ color: COLORS.GRAY, fontSize: '11px', marginBottom: '6px' }}>Tax Expense</div>+ <div style={{ color: COLORS.CYAN, fontSize: '18px', fontWeight: 700 }}>{formatCurrency(processedData.taxExpense)}</div>+ <div style={{ color: COLORS.MUTED, fontSize: '10px' }}>Effective Rate: {revenue > 0 && operatingIncome > 0 ? formatPercent(processedData.taxExpense / operatingIncome) : 'N/A'}</div>+ </div>+ </div></div>- <div style={{ fontSize: `${fontSize}px`, maxHeight: '500px', overflow: 'auto' }} className="custom-scrollbar">- {Object.keys(financials.cash_flow).length > 0 ? (- Object.entries(Object.values(financials.cash_flow)[0] || {}).map(([metric, _], idx) => {- const latestPeriod = Object.keys(financials.cash_flow)[0];- const value = financials.cash_flow[latestPeriod][metric];+ </div>+ </SectionPanel>++ {/* ===== DETAILED FINANCIAL STATEMENTS ===== */}+ <SectionPanel+ title="Detailed Financial Statements"+ color={COLORS.GRAY}+ icon={<Receipt size={16} color={COLORS.GRAY} />}+ defaultExpanded={false}+ >+ <div style={{ display: 'flex', gap: '8px', marginBottom: '16px' }}>+ {[+ { key: 'income', label: 'Income Statement', color: COLORS.GREEN },+ { key: 'balance', label: 'Balance Sheet', color: COLORS.YELLOW },+ { key: 'cashflow', label: 'Cash Flow', color: COLORS.CYAN },+ ].map(({ key, label, color }) => (+ <button+ key={key}+ onClick={() => setActiveStatement(key as any)}+ style={{+ padding: '8px 16px',+ backgroundColor: activeStatement === key ? color : 'transparent',+ border: `1px solid ${activeStatement === key ? color : COLORS.BORDER}`,+ color: activeStatement === key ? COLORS.DARK_BG : color,+ fontSize: '12px',+ fontWeight: 600,+ cursor: 'pointer',+ textTransform: 'uppercase',+ fontFamily: TYPOGRAPHY.MONO,+ borderRadius: '4px',+ transition: 'all 0.2s ease',+ }}+ >+ {label}+ </button>+ ))}+ </div>+ <div style={{ backgroundColor: COLORS.DARK_BG, border: BORDERS.STANDARD, maxHeight: '400px', overflow: 'auto', borderRadius: '4px' }} className="custom-scrollbar">+ <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '12px' }}>+ <thead>+ <tr style={{ backgroundColor: COLORS.HEADER_BG, position: 'sticky', top: 0 }}>+ <th style={{ padding: '12px', textAlign: 'left', color: COLORS.ORANGE, fontWeight: 700, borderBottom: `2px solid ${COLORS.ORANGE}` }}>METRIC</th>+ {(activeStatement === 'income' ? incomeKeys : activeStatement === 'balance' ? processedData.balanceKeys : processedData.cashflowKeys).slice(0, 4).map((period) => (+ <th key={period} style={{ padding: '12px', textAlign: 'right', color: COLORS.ORANGE, fontWeight: 700, borderBottom: `2px solid ${COLORS.ORANGE}` }}>{getYearFromPeriod(period)}</th>+ ))}+ </tr>+ </thead>+ <tbody>+ {Object.entries(activeStatement === 'income' ? latestIncome : activeStatement === 'balance' ? latestBalance : latestCashflow).map(([metric, _], idx) => {+ const periods = (activeStatement === 'income' ? incomeKeys : activeStatement === 'balance' ? processedData.balanceKeys : processedData.cashflowKeys).slice(0, 4);+ const statement = activeStatement === 'income' ? financials.income_statement : activeStatement === 'balance' ? financials.balance_sheet : financials.cash_flow;return (- <div key={idx} style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '6px', paddingBottom: '6px', borderBottom: `1px solid rgba(255,255,255,0.05)` }}>- <span style={{ color: COLORS.GRAY, fontSize: `${fontSize - 1}px`, maxWidth: '60%' }}>{metric}:</span>- <span style={{ color: COLORS.CYAN, fontSize: `${fontSize}px` }}>{formatLargeNumber(value)}</span>- </div>+ <tr key={metric} style={{ borderBottom: BORDERS.STANDARD, backgroundColor: idx % 2 === 0 ? 'transparent' : `${COLORS.WHITE}05` }}>+ <td style={{ padding: '10px 12px', color: COLORS.WHITE, fontWeight: 600 }}>{metric}</td>+ {periods.map((period) => {+ const value = statement[period]?.[metric];+ return (+ <td key={period} style={{ padding: '10px 12px', textAlign: 'right', color: value && value < 0 ? COLORS.RED : COLORS.CYAN, fontFamily: TYPOGRAPHY.MONO }}>+ {value !== undefined ? formatLargeNumber(value) : 'N/A'}+ </td>+ );+ })}+ </tr>);- })- ) : (- <div style={{ color: COLORS.GRAY, textAlign: 'center', padding: '20px', fontSize: `${fontSize}px` }}>No data available</div>- )}+ })}+ </tbody>+ </table>+ </div>+ </SectionPanel>++ {/* ===== FINANCIAL HEALTH SUMMARY ===== */}+ <div style={{ backgroundColor: COLORS.PANEL_BG, border: BORDERS.STANDARD, padding: '16px', borderRadius: '4px' }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '10px', marginBottom: '16px', paddingBottom: '10px', borderBottom: `2px solid ${COLORS.CYAN}` }}>+ <Shield size={18} color={COLORS.CYAN} />+ <span style={{ color: COLORS.CYAN, fontSize: '14px', fontWeight: 700, textTransform: 'uppercase' }}>Financial Health Summary</span>+ </div>+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '16px' }}>+ {/* Profitability */}+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px', padding: '14px', backgroundColor: COLORS.DARK_BG, border: BORDERS.STANDARD, borderRadius: '4px' }}>+ {netMargin >= 0.1 ? <CheckCircle size={24} color={COLORS.GREEN} /> : netMargin >= 0.05 ? <AlertTriangle size={24} color={COLORS.YELLOW} /> : <XCircle size={24} color={COLORS.RED} />}+ <div>+ <div style={{ color: COLORS.WHITE, fontSize: '13px', fontWeight: 700 }}>Profitability</div>+ <div style={{ color: COLORS.GRAY, fontSize: '11px' }}>{formatPercent(netMargin)} net margin</div>+ <div style={{ color: netMargin >= 0.1 ? COLORS.GREEN : netMargin >= 0.05 ? COLORS.YELLOW : COLORS.RED, fontSize: '10px', marginTop: '2px' }}>+ {netMargin >= 0.1 ? 'Strong' : netMargin >= 0.05 ? 'Moderate' : 'Weak'}+ </div>+ </div>+ </div>++ {/* Liquidity */}+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px', padding: '14px', backgroundColor: COLORS.DARK_BG, border: BORDERS.STANDARD, borderRadius: '4px' }}>+ {currentRatio >= 1.5 ? <CheckCircle size={24} color={COLORS.GREEN} /> : currentRatio >= 1.0 ? <AlertTriangle size={24} color={COLORS.YELLOW} /> : <XCircle size={24} color={COLORS.RED} />}+ <div>+ <div style={{ color: COLORS.WHITE, fontSize: '13px', fontWeight: 700 }}>Liquidity</div>+ <div style={{ color: COLORS.GRAY, fontSize: '11px' }}>{currentRatio.toFixed(2)}x current ratio</div>+ <div style={{ color: currentRatio >= 1.5 ? COLORS.GREEN : currentRatio >= 1.0 ? COLORS.YELLOW : COLORS.RED, fontSize: '10px', marginTop: '2px' }}>+ {currentRatio >= 1.5 ? 'Strong' : currentRatio >= 1.0 ? 'Adequate' : 'At Risk'}+ </div>+ </div>+ </div>++ {/* Leverage */}+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px', padding: '14px', backgroundColor: COLORS.DARK_BG, border: BORDERS.STANDARD, borderRadius: '4px' }}>+ {debtToEquity <= 0.5 ? <CheckCircle size={24} color={COLORS.GREEN} /> : debtToEquity <= 1.0 ? <AlertTriangle size={24} color={COLORS.YELLOW} /> : <XCircle size={24} color={COLORS.RED} />}+ <div>+ <div style={{ color: COLORS.WHITE, fontSize: '13px', fontWeight: 700 }}>Leverage</div>+ <div style={{ color: COLORS.GRAY, fontSize: '11px' }}>{debtToEquity.toFixed(2)}x D/E ratio</div>+ <div style={{ color: debtToEquity <= 0.5 ? COLORS.GREEN : debtToEquity <= 1.0 ? COLORS.YELLOW : COLORS.RED, fontSize: '10px', marginTop: '2px' }}>+ {debtToEquity <= 0.5 ? 'Conservative' : debtToEquity <= 1.0 ? 'Moderate' : 'High'}+ </div>+ </div>+ </div>++ {/* Cash Flow */}+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px', padding: '14px', backgroundColor: COLORS.DARK_BG, border: BORDERS.STANDARD, borderRadius: '4px' }}>+ {freeCashflow > 0 && fcfMargin >= 0.1 ? <CheckCircle size={24} color={COLORS.GREEN} /> : freeCashflow > 0 ? <AlertTriangle size={24} color={COLORS.YELLOW} /> : <XCircle size={24} color={COLORS.RED} />}+ <div>+ <div style={{ color: COLORS.WHITE, fontSize: '13px', fontWeight: 700 }}>Cash Generation</div>+ <div style={{ color: COLORS.GRAY, fontSize: '11px' }}>{formatCurrency(freeCashflow)} FCF</div>+ <div style={{ color: freeCashflow > 0 && fcfMargin >= 0.1 ? COLORS.GREEN : freeCashflow > 0 ? COLORS.YELLOW : COLORS.RED, fontSize: '10px', marginTop: '2px' }}>+ {freeCashflow > 0 && fcfMargin >= 0.1 ? 'Excellent' : freeCashflow > 0 ? 'Positive' : 'Negative'}+ </div>+ </div></div></div></div>diff --git a/fincept-terminal-desktop/src/components/tabs/equity-research/tabs/NewsTab.tsx b/fincept-terminal-desktop/src/components/tabs/equity-research/tabs/NewsTab.tsxindex 47795228a..b772e4f73 100644--- a/fincept-terminal-desktop/src/components/tabs/equity-research/tabs/NewsTab.tsx+++ b/fincept-terminal-desktop/src/components/tabs/equity-research/tabs/NewsTab.tsx@@ -1,5 +1,5 @@import React from 'react';-import { FINCEPT } from '../../portfolio-tab/finceptStyles';+import { FINCEPT, TYPOGRAPHY, SPACING, BORDERS, COMMON_STYLES, EFFECTS } from '../../portfolio-tab/finceptStyles';import type { NewsData, StockInfo } from '../types';const COLORS = {@@ -12,7 +12,9 @@ const COLORS = {CYAN: FINCEPT.CYAN,DARK_BG: FINCEPT.DARK_BG,PANEL_BG: FINCEPT.PANEL_BG,+ HEADER_BG: FINCEPT.HEADER_BG,BORDER: FINCEPT.BORDER,+ HOVER: FINCEPT.HOVER,};interface NewsTabProps {@@ -38,20 +40,20 @@ export const NewsTab: React.FC<NewsTabProps> = ({alignItems: 'center',justifyContent: 'center',height: '400px',- gap: '16px',+ gap: SPACING.LARGE,}}><div style={{width: '50px',height: '50px',- border: '4px solid #404040',- borderTop: '4px solid #ea580c',+ border: `4px solid ${COLORS.BORDER}`,+ borderTop: `4px solid ${COLORS.ORANGE}`,borderRadius: '50%',animation: 'spin 1s linear infinite'}} />- <div style={{ color: COLORS.YELLOW, fontSize: '14px', fontWeight: 'bold' }}>+ <div style={{ color: COLORS.YELLOW, fontSize: TYPOGRAPHY.HEADING, fontWeight: TYPOGRAPHY.BOLD }}>FETCHING LATEST NEWS...</div>- <div style={{ color: COLORS.GRAY, fontSize: '11px' }}>+ <div style={{ color: COLORS.GRAY, fontSize: TYPOGRAPHY.DEFAULT }}>Loading news for {currentSymbol}</div></div>@@ -66,25 +68,19 @@ export const NewsTab: React.FC<NewsTabProps> = ({alignItems: 'center',justifyContent: 'center',height: '400px',- gap: '16px',+ gap: SPACING.LARGE,}}>- <div style={{ color: COLORS.RED, fontSize: '14px', fontWeight: 'bold' }}>+ <div style={{ color: COLORS.RED, fontSize: TYPOGRAPHY.HEADING, fontWeight: TYPOGRAPHY.BOLD }}>[WARN] NO NEWS AVAILABLE</div>- <div style={{ color: COLORS.GRAY, fontSize: '11px' }}>+ <div style={{ color: COLORS.GRAY, fontSize: TYPOGRAPHY.DEFAULT }}>{newsData?.error || 'Unable to fetch news at this time'}</div><buttononClick={onRefresh}style={{- backgroundColor: COLORS.ORANGE,- border: 'none',- color: COLORS.DARK_BG,- padding: '8px 16px',- fontSize: '10px',- cursor: 'pointer',- fontWeight: 'bold',- marginTop: '8px',+ ...COMMON_STYLES.buttonPrimary,+ marginTop: SPACING.MEDIUM,}}>RETRY@@ -101,12 +97,12 @@ export const NewsTab: React.FC<NewsTabProps> = ({alignItems: 'center',justifyContent: 'center',height: '400px',- gap: '16px',+ gap: SPACING.LARGE,}}>- <div style={{ color: COLORS.YELLOW, fontSize: '14px', fontWeight: 'bold' }}>+ <div style={{ color: COLORS.YELLOW, fontSize: TYPOGRAPHY.HEADING, fontWeight: TYPOGRAPHY.BOLD }}>NO NEWS FOUND</div>- <div style={{ color: COLORS.GRAY, fontSize: '11px' }}>+ <div style={{ color: COLORS.GRAY, fontSize: TYPOGRAPHY.DEFAULT }}>No recent news articles found for {stockInfo?.company_name || currentSymbol}</div></div>@@ -114,39 +110,36 @@ export const NewsTab: React.FC<NewsTabProps> = ({}return (- <div style={{ padding: '8px', height: 'calc(100vh - 280px)', overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>+ <div style={{ padding: SPACING.MEDIUM, height: 'calc(100vh - 280px)', overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>{/* News Header */}<div style={{- backgroundColor: COLORS.PANEL_BG,- border: `1px solid ${COLORS.BORDER}`,- padding: '8px 12px',- marginBottom: '8px',+ ...COMMON_STYLES.panel,+ backgroundColor: COLORS.HEADER_BG,+ padding: `${SPACING.MEDIUM} ${SPACING.DEFAULT}`,+ marginBottom: SPACING.MEDIUM,display: 'flex',justifyContent: 'space-between',alignItems: 'center',flexShrink: 0,+ borderBottom: `2px solid ${COLORS.ORANGE}`,}}>- <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>- <span style={{ color: COLORS.ORANGE, fontSize: '11px', fontWeight: 'bold' }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: SPACING.DEFAULT }}>+ <span style={{ color: COLORS.ORANGE, fontSize: TYPOGRAPHY.DEFAULT, fontWeight: TYPOGRAPHY.BOLD, letterSpacing: TYPOGRAPHY.WIDE }}>LATEST NEWS</span>- <span style={{ color: COLORS.GRAY, fontSize: '9px' }}>+ <span style={{ color: COLORS.GRAY, fontSize: TYPOGRAPHY.SMALL }}>{newsData.count || 0} articles found</span>- <span style={{ color: COLORS.CYAN, fontSize: '9px' }}>+ <span style={{ color: COLORS.CYAN, fontSize: TYPOGRAPHY.SMALL }}>{stockInfo?.company_name || currentSymbol}</span></div><buttononClick={onRefresh}style={{- backgroundColor: COLORS.DARK_BG,- border: `1px solid ${COLORS.BORDER}`,- color: COLORS.WHITE,- padding: '4px 12px',- fontSize: '9px',- cursor: 'pointer',- fontWeight: 'bold',+ ...COMMON_STYLES.buttonSecondary,+ padding: `${SPACING.SMALL} ${SPACING.DEFAULT}`,+ fontSize: TYPOGRAPHY.SMALL,}}>REFRESH@@ -159,20 +152,19 @@ export const NewsTab: React.FC<NewsTabProps> = ({overflow: 'auto',display: 'flex',flexDirection: 'column',- gap: '8px',+ gap: SPACING.MEDIUM,}} className="custom-scrollbar">{newsData.data.map((article, index) => (<divkey={index}style={{- backgroundColor: COLORS.PANEL_BG,- border: `1px solid ${COLORS.BORDER}`,- padding: '12px',+ ...COMMON_STYLES.panel,+ padding: SPACING.DEFAULT,cursor: 'pointer',- transition: 'all 0.2s',+ transition: EFFECTS.TRANSITION_STANDARD,}}onMouseEnter={(e) => {- e.currentTarget.style.backgroundColor = '#252525';+ e.currentTarget.style.backgroundColor = COLORS.HOVER;e.currentTarget.style.borderColor = COLORS.ORANGE;}}onMouseLeave={(e) => {@@ -186,29 +178,29 @@ export const NewsTab: React.FC<NewsTabProps> = ({}}>{/* Article Header */}- <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '8px' }}>- <div style={{ flex: 1, marginRight: '12px' }}>+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: SPACING.MEDIUM }}>+ <div style={{ flex: 1, marginRight: SPACING.DEFAULT }}><h3 style={{color: COLORS.WHITE,- fontSize: '12px',- fontWeight: 'bold',+ fontSize: TYPOGRAPHY.SUBHEADING,+ fontWeight: TYPOGRAPHY.BOLD,margin: 0,- marginBottom: '6px',+ marginBottom: SPACING.GAP_SMALL,lineHeight: '1.4',}}>{article.title}</h3>- <div style={{ display: 'flex', gap: '12px', alignItems: 'center' }}>+ <div style={{ display: 'flex', gap: SPACING.DEFAULT, alignItems: 'center' }}><span style={{color: COLORS.CYAN,- fontSize: '9px',- fontWeight: 'bold',+ fontSize: TYPOGRAPHY.SMALL,+ fontWeight: TYPOGRAPHY.BOLD,}}>{article.publisher || 'Unknown Source'}</span><span style={{color: COLORS.GRAY,- fontSize: '9px',+ fontSize: TYPOGRAPHY.SMALL,}}>{article.published_date || 'Unknown Date'}</span>@@ -220,9 +212,9 @@ export const NewsTab: React.FC<NewsTabProps> = ({{article.description && article.description !== 'N/A' && (<div style={{color: COLORS.GRAY,- fontSize: '10px',+ fontSize: TYPOGRAPHY.BODY,lineHeight: '1.5',- marginBottom: '8px',+ marginBottom: SPACING.MEDIUM,}}>{article.description}</div>@@ -232,11 +224,12 @@ export const NewsTab: React.FC<NewsTabProps> = ({{article.url && article.url !== '#' && (<div style={{color: COLORS.ORANGE,- fontSize: '9px',- fontWeight: 'bold',+ fontSize: TYPOGRAPHY.SMALL,+ fontWeight: TYPOGRAPHY.BOLD,display: 'flex',alignItems: 'center',- gap: '4px',+ gap: SPACING.SMALL,+ letterSpacing: TYPOGRAPHY.WIDE,}}>READ FULL ARTICLE</div>diff --git a/fincept-terminal-desktop/src/components/tabs/equity-research/tabs/TechnicalsTab.tsx b/fincept-terminal-desktop/src/components/tabs/equity-research/tabs/TechnicalsTab.tsxindex cccf76592..18989d923 100644--- a/fincept-terminal-desktop/src/components/tabs/equity-research/tabs/TechnicalsTab.tsx+++ b/fincept-terminal-desktop/src/components/tabs/equity-research/tabs/TechnicalsTab.tsx@@ -1,7 +1,8 @@-import React from 'react';+import React, { useMemo, useState } from 'react';import { IndicatorBox } from '../components/IndicatorBox';-import { FINCEPT } from '../../portfolio-tab/finceptStyles';+import { FINCEPT, TYPOGRAPHY, SPACING, BORDERS, COMMON_STYLES, EFFECTS } from '../../portfolio-tab/finceptStyles';import type { HistoricalData, TechnicalsData } from '../types';+import { TrendingUp, TrendingDown, Minus, Activity, BarChart3, Waves, Volume2, Percent, ChevronDown, ChevronRight, Target, AlertTriangle, Gauge, Zap } from 'lucide-react';const COLORS = {ORANGE: FINCEPT.ORANGE,@@ -10,12 +11,15 @@ const COLORS = {GREEN: FINCEPT.GREEN,YELLOW: FINCEPT.YELLOW,GRAY: FINCEPT.GRAY,+ MUTED: FINCEPT.MUTED,BLUE: FINCEPT.BLUE,CYAN: FINCEPT.CYAN,DARK_BG: FINCEPT.DARK_BG,PANEL_BG: FINCEPT.PANEL_BG,+ HEADER_BG: FINCEPT.HEADER_BG,+ HOVER: FINCEPT.HOVER,BORDER: FINCEPT.BORDER,- MAGENTA: '#FF00FF',+ PURPLE: FINCEPT.PURPLE,};interface TechnicalsTabProps {@@ -24,11 +28,168 @@ interface TechnicalsTabProps {historicalData: HistoricalData[];}+// Helper to get signal from indicator+const getIndicatorSignal = (name: string, latestValue: number, prevValue: number): 'BUY' | 'SELL' | 'NEUTRAL' => {+ const nameUpper = name.toUpperCase();++ // RSI+ if (nameUpper.includes('RSI')) {+ if (latestValue <= 30) return 'BUY';+ if (latestValue >= 70) return 'SELL';+ return 'NEUTRAL';+ }++ // Stochastic+ if (nameUpper.includes('STOCH') && !nameUpper.includes('RSI')) {+ if (latestValue <= 20) return 'BUY';+ if (latestValue >= 80) return 'SELL';+ return 'NEUTRAL';+ }++ // MACD+ if (nameUpper.includes('MACD') && !nameUpper.includes('SIGNAL') && !nameUpper.includes('DIFF')) {+ if (prevValue < 0 && latestValue > 0) return 'BUY';+ if (prevValue > 0 && latestValue < 0) return 'SELL';+ return 'NEUTRAL';+ }++ // CCI+ if (nameUpper.includes('CCI')) {+ if (latestValue <= -100) return 'BUY';+ if (latestValue >= 100) return 'SELL';+ return 'NEUTRAL';+ }++ // Williams %R+ if (nameUpper.includes('WILLIAMS')) {+ if (latestValue <= -80) return 'BUY';+ if (latestValue >= -20) return 'SELL';+ return 'NEUTRAL';+ }++ // MFI+ if (nameUpper === 'MFI') {+ if (latestValue <= 20) return 'BUY';+ if (latestValue >= 80) return 'SELL';+ return 'NEUTRAL';+ }++ // ADX (trend strength)+ if (nameUpper.includes('ADX') && !nameUpper.includes('POS') && !nameUpper.includes('NEG')) {+ if (latestValue > 25) return 'BUY'; // Strong trend+ return 'NEUTRAL';+ }++ // Bollinger Bands %B+ if (nameUpper.includes('BB_PBAND')) {+ if (latestValue < 0.2) return 'BUY';+ if (latestValue > 0.8) return 'SELL';+ return 'NEUTRAL';+ }++ // CMF+ if (nameUpper.includes('CMF')) {+ if (latestValue > 0.1) return 'BUY';+ if (latestValue < -0.1) return 'SELL';+ return 'NEUTRAL';+ }++ // ROC+ if (nameUpper.includes('ROC')) {+ if (latestValue > 5) return 'BUY';+ if (latestValue < -5) return 'SELL';+ return 'NEUTRAL';+ }++ return 'NEUTRAL';+};++// Key indicators for quick view+const KEY_INDICATORS = ['RSI', 'MACD', 'STOCH_K', 'ADX', 'CCI', 'MFI', 'BB_PBAND', 'WILLIAMS_R'];+export const TechnicalsTab: React.FC<TechnicalsTabProps> = ({technicalsData,technicalsLoading,historicalData,}) => {+ const [expandedCategories, setExpandedCategories] = useState<Record<string, boolean>>({+ trend: true,+ momentum: true,+ volatility: false,+ volume: false,+ others: false,+ });++ // Calculate signal summary+ const signalSummary = useMemo(() => {+ if (!technicalsData?.data || !technicalsData?.indicator_columns) {+ return { buy: 0, sell: 0, neutral: 0, total: 0, recommendation: 'NEUTRAL' as const };+ }++ let buy = 0, sell = 0, neutral = 0;+ const allIndicators = [+ ...(technicalsData.indicator_columns.trend || []),+ ...(technicalsData.indicator_columns.momentum || []),+ ...(technicalsData.indicator_columns.volatility || []),+ ...(technicalsData.indicator_columns.volume || []),+ ...(technicalsData.indicator_columns.others || []),+ ];++ allIndicators.forEach((indicator) => {+ const values = technicalsData.data.map((d: any) => d[indicator]).filter((v: any) => v != null);+ if (values.length < 2) return;++ const latestValue = values[values.length - 1];+ const prevValue = values[values.length - 2];+ const signal = getIndicatorSignal(indicator, latestValue, prevValue);++ if (signal === 'BUY') buy++;+ else if (signal === 'SELL') sell++;+ else neutral++;+ });++ const total = buy + sell + neutral;+ let recommendation: 'STRONG BUY' | 'BUY' | 'NEUTRAL' | 'SELL' | 'STRONG SELL' = 'NEUTRAL';++ if (total > 0) {+ const buyPercent = (buy / total) * 100;+ const sellPercent = (sell / total) * 100;++ if (buyPercent >= 70) recommendation = 'STRONG BUY';+ else if (buyPercent >= 50) recommendation = 'BUY';+ else if (sellPercent >= 70) recommendation = 'STRONG SELL';+ else if (sellPercent >= 50) recommendation = 'SELL';+ }++ return { buy, sell, neutral, total, recommendation };+ }, [technicalsData]);++ // Get key indicator values+ const keyIndicatorValues = useMemo(() => {+ if (!technicalsData?.data || !technicalsData?.indicator_columns) return [];++ const allIndicators = [+ ...(technicalsData.indicator_columns.trend || []),+ ...(technicalsData.indicator_columns.momentum || []),+ ...(technicalsData.indicator_columns.volatility || []),+ ...(technicalsData.indicator_columns.volume || []),+ ];++ return KEY_INDICATORS.map((key) => {+ const indicator = allIndicators.find((ind) => ind.toUpperCase().includes(key));+ if (!indicator) return null;++ const values = technicalsData.data.map((d: any) => d[indicator]).filter((v: any) => v != null);+ if (values.length < 2) return null;++ const latestValue = values[values.length - 1];+ const prevValue = values[values.length - 2];+ const signal = getIndicatorSignal(indicator, latestValue, prevValue);++ return { name: indicator, value: latestValue, signal };+ }).filter(Boolean);+ }, [technicalsData]);+if (technicalsLoading) {return (<div style={{@@ -37,21 +198,32 @@ export const TechnicalsTab: React.FC<TechnicalsTabProps> = ({alignItems: 'center',justifyContent: 'center',height: '400px',- gap: '16px',+ gap: SPACING.LARGE,+ fontFamily: TYPOGRAPHY.MONO,}}><div style={{- width: '50px',- height: '50px',- border: '4px solid #404040',- borderTop: '4px solid #ea580c',+ width: '40px',+ height: '40px',+ border: `2px solid ${COLORS.BORDER}`,+ borderTop: `2px solid ${COLORS.ORANGE}`,borderRadius: '50%',animation: 'spin 1s linear infinite'}} />- <div style={{ color: COLORS.YELLOW, fontSize: '14px', fontWeight: 'bold' }}>- COMPUTING TECHNICAL INDICATORS...+ <div style={{+ color: COLORS.ORANGE,+ fontSize: TYPOGRAPHY.SUBHEADING,+ fontWeight: TYPOGRAPHY.BOLD,+ textTransform: 'uppercase',+ letterSpacing: TYPOGRAPHY.WIDE,+ }}>+ COMPUTING TECHNICAL INDICATORS</div>- <div style={{ color: COLORS.GRAY, fontSize: '11px' }}>- Analyzing {historicalData.length} data points+ <div style={{+ color: COLORS.GRAY,+ fontSize: TYPOGRAPHY.SMALL,+ textTransform: 'uppercase',+ }}>+ ANALYZING {historicalData.length} DATA POINTS</div></div>);@@ -65,84 +237,571 @@ export const TechnicalsTab: React.FC<TechnicalsTabProps> = ({alignItems: 'center',justifyContent: 'center',height: '400px',- gap: '16px',+ gap: SPACING.MEDIUM,+ fontFamily: TYPOGRAPHY.MONO,}}>- <div style={{ color: COLORS.RED, fontSize: '14px', fontWeight: 'bold' }}>- [WARN] NO TECHNICAL DATA AVAILABLE+ <AlertTriangle size={32} color={COLORS.RED} />+ <div style={{+ color: COLORS.RED,+ fontSize: TYPOGRAPHY.SUBHEADING,+ fontWeight: TYPOGRAPHY.BOLD,+ textTransform: 'uppercase',+ }}>+ NO TECHNICAL DATA AVAILABLE</div>- <div style={{ color: COLORS.GRAY, fontSize: '11px' }}>- Please wait for historical data to load+ <div style={{+ color: COLORS.GRAY,+ fontSize: TYPOGRAPHY.SMALL,+ textTransform: 'uppercase',+ }}>+ WAITING FOR HISTORICAL DATA</div></div>);}- // Check if we have valid indicator dataif (!technicalsData.indicator_columns || !technicalsData.data || !Array.isArray(technicalsData.data) || technicalsData.data.length === 0) {return (<div style={{- backgroundColor: COLORS.PANEL_BG,- border: `1px solid ${COLORS.BORDER}`,- padding: '16px',+ ...COMMON_STYLES.panel,+ padding: SPACING.LARGE,textAlign: 'center',- color: COLORS.YELLOW,+ fontFamily: TYPOGRAPHY.MONO,}}>- <div style={{ fontSize: '14px', fontWeight: 'bold', marginBottom: '8px' }}>- [WARN] NO INDICATOR DATA+ <div style={{+ color: COLORS.YELLOW,+ fontSize: TYPOGRAPHY.SUBHEADING,+ fontWeight: TYPOGRAPHY.BOLD,+ marginBottom: SPACING.MEDIUM,+ textTransform: 'uppercase',+ }}>+ NO INDICATOR DATA</div>- <div style={{ fontSize: '11px', color: COLORS.GRAY }}>- Technical indicators could not be computed. Please try again or select a different symbol.+ <div style={{+ fontSize: TYPOGRAPHY.SMALL,+ color: COLORS.GRAY,+ textTransform: 'uppercase',+ }}>+ Technical indicators could not be computed. Try selecting a different symbol.</div></div>);}- const renderIndicatorCategory = (indicators: string[] | undefined, color: string, category: string) => {- if (!indicators || !Array.isArray(indicators)) return null;+ const toggleCategory = (category: string) => {+ setExpandedCategories(prev => ({ ...prev, [category]: !prev[category] }));+ };- return indicators.map((indicator: string) => {- const values = technicalsData.data.map((d: any) => d[indicator]).filter((v: any) => v != null);- if (values.length === 0) return null;+ const renderIndicatorCategory = (indicators: string[] | undefined, color: string, category: string, icon: React.ReactNode, categoryKey: string) => {+ if (!indicators || !Array.isArray(indicators) || indicators.length === 0) return null;- const latestValue = values[values.length - 1];- const min = Math.min(...values);- const max = Math.max(...values);- const avg = values.reduce((a: number, b: number) => a + b, 0) / values.length;-- return (- <IndicatorBox- key={indicator}- name={indicator}- latestValue={latestValue}- min={min}- max={max}- avg={avg}- values={values}- priceData={historicalData}- color={color}- category={category}- />- );+ const isExpanded = expandedCategories[categoryKey];++ // Count signals in this category+ let buyCount = 0, sellCount = 0, neutralCount = 0;+ indicators.forEach((indicator) => {+ const values = technicalsData.data.map((d: any) => d[indicator]).filter((v: any) => v != null);+ if (values.length >= 2) {+ const signal = getIndicatorSignal(indicator, values[values.length - 1], values[values.length - 2]);+ if (signal === 'BUY') buyCount++;+ else if (signal === 'SELL') sellCount++;+ else neutralCount++;+ }});++ return (+ <div key={categoryKey} style={{ marginBottom: SPACING.SMALL }}>+ {/* Category Header */}+ <div+ onClick={() => toggleCategory(categoryKey)}+ style={{+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ padding: `${SPACING.MEDIUM} ${SPACING.DEFAULT}`,+ backgroundColor: COLORS.HEADER_BG,+ borderLeft: `2px solid ${color}`,+ borderBottom: isExpanded ? 'none' : BORDERS.STANDARD,+ cursor: 'pointer',+ transition: EFFECTS.TRANSITION_FAST,+ fontFamily: TYPOGRAPHY.MONO,+ }}+ onMouseEnter={(e) => {+ e.currentTarget.style.backgroundColor = COLORS.HOVER;+ }}+ onMouseLeave={(e) => {+ e.currentTarget.style.backgroundColor = COLORS.HEADER_BG;+ }}+ >+ <div style={{ display: 'flex', alignItems: 'center', gap: SPACING.MEDIUM }}>+ {isExpanded ? <ChevronDown size={14} color={color} /> : <ChevronRight size={14} color={color} />}+ {icon}+ <span style={{+ color: COLORS.WHITE,+ fontSize: TYPOGRAPHY.DEFAULT,+ fontWeight: TYPOGRAPHY.BOLD,+ textTransform: 'uppercase',+ letterSpacing: TYPOGRAPHY.WIDE,+ }}>+ {category}+ </span>+ <span style={{+ color: COLORS.MUTED,+ fontSize: TYPOGRAPHY.TINY,+ backgroundColor: COLORS.DARK_BG,+ padding: `${SPACING.TINY} ${SPACING.SMALL}`,+ border: BORDERS.STANDARD,+ textTransform: 'uppercase',+ }}>+ {indicators.length} INDICATORS+ </span>+ </div>++ {/* Mini Signal Summary for Category */}+ <div style={{ display: 'flex', gap: SPACING.SMALL }}>+ {buyCount > 0 && (+ <span style={{+ color: COLORS.GREEN,+ fontSize: TYPOGRAPHY.TINY,+ fontWeight: TYPOGRAPHY.BOLD,+ backgroundColor: `${COLORS.GREEN}15`,+ borderLeft: `2px solid ${COLORS.GREEN}`,+ padding: `${SPACING.TINY} ${SPACING.SMALL}`,+ textTransform: 'uppercase',+ }}>+ {buyCount} BUY+ </span>+ )}+ {sellCount > 0 && (+ <span style={{+ color: COLORS.RED,+ fontSize: TYPOGRAPHY.TINY,+ fontWeight: TYPOGRAPHY.BOLD,+ backgroundColor: `${COLORS.RED}15`,+ borderLeft: `2px solid ${COLORS.RED}`,+ padding: `${SPACING.TINY} ${SPACING.SMALL}`,+ textTransform: 'uppercase',+ }}>+ {sellCount} SELL+ </span>+ )}+ {neutralCount > 0 && (+ <span style={{+ color: COLORS.GRAY,+ fontSize: TYPOGRAPHY.TINY,+ fontWeight: TYPOGRAPHY.BOLD,+ backgroundColor: `${COLORS.GRAY}15`,+ borderLeft: `2px solid ${COLORS.GRAY}`,+ padding: `${SPACING.TINY} ${SPACING.SMALL}`,+ textTransform: 'uppercase',+ }}>+ {neutralCount} HOLD+ </span>+ )}+ </div>+ </div>++ {/* Indicator Grid */}+ {isExpanded && (+ <div style={{+ display: 'grid',+ gridTemplateColumns: 'repeat(auto-fill, minmax(340px, 1fr))',+ gap: SPACING.MEDIUM,+ padding: SPACING.MEDIUM,+ backgroundColor: COLORS.DARK_BG,+ borderLeft: `2px solid ${color}`,+ borderBottom: BORDERS.STANDARD,+ }}>+ {indicators.map((indicator: string) => {+ const values = technicalsData.data.map((d: any) => d[indicator]).filter((v: any) => v != null);+ if (values.length === 0) return null;++ const latestValue = values[values.length - 1];+ const min = Math.min(...values);+ const max = Math.max(...values);+ const avg = values.reduce((a: number, b: number) => a + b, 0) / values.length;++ return (+ <IndicatorBox+ key={indicator}+ name={indicator}+ latestValue={latestValue}+ min={min}+ max={max}+ avg={avg}+ values={values}+ priceData={historicalData}+ color={color}+ category={category}+ />+ );+ })}+ </div>+ )}+ </div>+ );};+ const recommendationColor = signalSummary.recommendation.includes('BUY') ? COLORS.GREEN :+ signalSummary.recommendation.includes('SELL') ? COLORS.RED : COLORS.YELLOW;+return (- <div style={{ padding: '8px', overflow: 'auto', height: 'calc(100vh - 280px)' }} className="custom-scrollbar">- <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(420px, 1fr))', gap: '16px' }}>- {/* Trend Indicators */}- {renderIndicatorCategory(technicalsData.indicator_columns?.trend, COLORS.CYAN, 'TREND')}+ <div style={{+ padding: SPACING.MEDIUM,+ overflow: 'auto',+ height: 'calc(100vh - 280px)',+ fontFamily: TYPOGRAPHY.MONO,+ }} className="custom-scrollbar">+ {/* Summary Dashboard */}+ <div style={{+ display: 'grid',+ gridTemplateColumns: '280px 1fr',+ gap: SPACING.MEDIUM,+ marginBottom: SPACING.MEDIUM,+ }}>+ {/* Overall Signal Panel */}+ <div style={{+ backgroundColor: COLORS.PANEL_BG,+ border: BORDERS.STANDARD,+ display: 'flex',+ flexDirection: 'column',+ }}>+ {/* Panel Header */}+ <div style={{+ backgroundColor: COLORS.HEADER_BG,+ padding: `${SPACING.SMALL} ${SPACING.MEDIUM}`,+ borderBottom: `2px solid ${COLORS.ORANGE}`,+ display: 'flex',+ alignItems: 'center',+ gap: SPACING.SMALL,+ }}>+ <Gauge size={14} color={COLORS.ORANGE} />+ <span style={{+ color: COLORS.ORANGE,+ fontSize: TYPOGRAPHY.SMALL,+ fontWeight: TYPOGRAPHY.BOLD,+ textTransform: 'uppercase',+ letterSpacing: TYPOGRAPHY.WIDE,+ }}>+ TECHNICAL RATING+ </span>+ </div>++ {/* Rating Content */}+ <div style={{+ padding: SPACING.DEFAULT,+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ gap: SPACING.MEDIUM,+ flex: 1,+ }}>+ <div style={{+ fontSize: '24px',+ fontWeight: TYPOGRAPHY.BOLD,+ color: recommendationColor,+ textShadow: `0 0 20px ${recommendationColor}40`,+ textTransform: 'uppercase',+ letterSpacing: TYPOGRAPHY.WIDE,+ }}>+ {signalSummary.recommendation}+ </div>++ {/* Signal Gauge */}+ <div style={{+ width: '100%',+ display: 'flex',+ alignItems: 'center',+ gap: SPACING.SMALL,+ }}>+ <TrendingDown size={12} color={COLORS.RED} />+ <div style={{+ flex: 1,+ height: '6px',+ backgroundColor: COLORS.DARK_BG,+ border: BORDERS.STANDARD,+ overflow: 'hidden',+ display: 'flex',+ }}>+ <div style={{+ width: `${signalSummary.total > 0 ? (signalSummary.sell / signalSummary.total) * 100 : 0}%`,+ backgroundColor: COLORS.RED,+ }} />+ <div style={{+ width: `${signalSummary.total > 0 ? (signalSummary.neutral / signalSummary.total) * 100 : 0}%`,+ backgroundColor: COLORS.MUTED,+ }} />+ <div style={{+ width: `${signalSummary.total > 0 ? (signalSummary.buy / signalSummary.total) * 100 : 0}%`,+ backgroundColor: COLORS.GREEN,+ }} />+ </div>+ <TrendingUp size={12} color={COLORS.GREEN} />+ </div>++ {/* Signal Counts */}+ <div style={{+ display: 'grid',+ gridTemplateColumns: '1fr 1fr 1fr',+ gap: SPACING.SMALL,+ width: '100%',+ }}>+ <div style={{+ textAlign: 'center',+ padding: SPACING.SMALL,+ backgroundColor: `${COLORS.GREEN}10`,+ borderLeft: `2px solid ${COLORS.GREEN}`,+ }}>+ <div style={{+ color: COLORS.GREEN,+ fontWeight: TYPOGRAPHY.BOLD,+ fontSize: TYPOGRAPHY.LARGE,+ }}>{signalSummary.buy}</div>+ <div style={{+ color: COLORS.GRAY,+ fontSize: TYPOGRAPHY.TINY,+ textTransform: 'uppercase',+ }}>BUY</div>+ </div>+ <div style={{+ textAlign: 'center',+ padding: SPACING.SMALL,+ backgroundColor: `${COLORS.GRAY}10`,+ borderLeft: `2px solid ${COLORS.GRAY}`,+ }}>+ <div style={{+ color: COLORS.WHITE,+ fontWeight: TYPOGRAPHY.BOLD,+ fontSize: TYPOGRAPHY.LARGE,+ }}>{signalSummary.neutral}</div>+ <div style={{+ color: COLORS.GRAY,+ fontSize: TYPOGRAPHY.TINY,+ textTransform: 'uppercase',+ }}>HOLD</div>+ </div>+ <div style={{+ textAlign: 'center',+ padding: SPACING.SMALL,+ backgroundColor: `${COLORS.RED}10`,+ borderLeft: `2px solid ${COLORS.RED}`,+ }}>+ <div style={{+ color: COLORS.RED,+ fontWeight: TYPOGRAPHY.BOLD,+ fontSize: TYPOGRAPHY.LARGE,+ }}>{signalSummary.sell}</div>+ <div style={{+ color: COLORS.GRAY,+ fontSize: TYPOGRAPHY.TINY,+ textTransform: 'uppercase',+ }}>SELL</div>+ </div>+ </div>++ {/* Total Indicators */}+ <div style={{+ color: COLORS.MUTED,+ fontSize: TYPOGRAPHY.TINY,+ textTransform: 'uppercase',+ letterSpacing: TYPOGRAPHY.WIDE,+ }}>+ {signalSummary.total} INDICATORS ANALYZED+ </div>+ </div>+ </div>++ {/* Key Indicators Quick View */}+ <div style={{+ backgroundColor: COLORS.PANEL_BG,+ border: BORDERS.STANDARD,+ display: 'flex',+ flexDirection: 'column',+ }}>+ {/* Panel Header */}+ <div style={{+ backgroundColor: COLORS.HEADER_BG,+ padding: `${SPACING.SMALL} ${SPACING.MEDIUM}`,+ borderBottom: `2px solid ${COLORS.CYAN}`,+ display: 'flex',+ alignItems: 'center',+ gap: SPACING.SMALL,+ }}>+ <Zap size={14} color={COLORS.CYAN} />+ <span style={{+ color: COLORS.CYAN,+ fontSize: TYPOGRAPHY.SMALL,+ fontWeight: TYPOGRAPHY.BOLD,+ textTransform: 'uppercase',+ letterSpacing: TYPOGRAPHY.WIDE,+ }}>+ KEY INDICATORS+ </span>+ </div>++ {/* Indicators Grid */}+ <div style={{+ padding: SPACING.MEDIUM,+ display: 'grid',+ gridTemplateColumns: 'repeat(auto-fill, minmax(140px, 1fr))',+ gap: SPACING.SMALL,+ flex: 1,+ }}>+ {keyIndicatorValues.map((ind: any) => {+ if (!ind) return null;+ const signalColor = ind.signal === 'BUY' ? COLORS.GREEN :+ ind.signal === 'SELL' ? COLORS.RED : COLORS.GRAY;+ const SignalIcon = ind.signal === 'BUY' ? TrendingUp :+ ind.signal === 'SELL' ? TrendingDown : Minus;++ return (+ <div+ key={ind.name}+ style={{+ backgroundColor: COLORS.DARK_BG,+ border: BORDERS.STANDARD,+ borderLeft: `2px solid ${signalColor}`,+ padding: SPACING.SMALL,+ display: 'flex',+ flexDirection: 'column',+ gap: SPACING.TINY,+ transition: EFFECTS.TRANSITION_FAST,+ }}+ onMouseEnter={(e) => {+ e.currentTarget.style.borderColor = signalColor;+ }}+ onMouseLeave={(e) => {+ e.currentTarget.style.borderColor = COLORS.BORDER;+ e.currentTarget.style.borderLeftColor = signalColor;+ }}+ >+ <div style={{+ display: 'flex',+ justifyContent: 'space-between',+ alignItems: 'center',+ }}>+ <span style={{+ color: COLORS.GRAY,+ fontSize: TYPOGRAPHY.TINY,+ textTransform: 'uppercase',+ letterSpacing: TYPOGRAPHY.TIGHT,+ }}>+ {ind.name.replace(/_/g, ' ').substring(0, 10)}+ </span>+ <SignalIcon size={10} color={signalColor} />+ </div>+ <div style={{+ color: COLORS.WHITE,+ fontSize: TYPOGRAPHY.HEADING,+ fontWeight: TYPOGRAPHY.BOLD,+ fontFamily: TYPOGRAPHY.MONO,+ }}>+ {typeof ind.value === 'number' ? ind.value.toFixed(2) : ind.value}+ </div>+ <div style={{+ color: signalColor,+ fontSize: TYPOGRAPHY.TINY,+ fontWeight: TYPOGRAPHY.BOLD,+ textTransform: 'uppercase',+ }}>+ {ind.signal}+ </div>+ </div>+ );+ })}+ </div>+ </div>+ </div>++ {/* Category Sections */}+ {renderIndicatorCategory(+ technicalsData.indicator_columns?.trend,+ COLORS.CYAN,+ 'TREND INDICATORS',+ <Activity size={16} color={COLORS.CYAN} />,+ 'trend'+ )}- {/* Momentum Indicators */}- {renderIndicatorCategory(technicalsData.indicator_columns?.momentum, COLORS.GREEN, 'MOMENTUM')}+ {renderIndicatorCategory(+ technicalsData.indicator_columns?.momentum,+ COLORS.GREEN,+ 'MOMENTUM INDICATORS',+ <BarChart3 size={16} color={COLORS.GREEN} />,+ 'momentum'+ )}- {/* Volatility Indicators */}- {renderIndicatorCategory(technicalsData.indicator_columns?.volatility, COLORS.YELLOW, 'VOLATILITY')}+ {renderIndicatorCategory(+ technicalsData.indicator_columns?.volatility,+ COLORS.YELLOW,+ 'VOLATILITY INDICATORS',+ <Waves size={16} color={COLORS.YELLOW} />,+ 'volatility'+ )}- {/* Volume Indicators */}- {renderIndicatorCategory(technicalsData.indicator_columns?.volume, COLORS.BLUE, 'VOLUME')}+ {renderIndicatorCategory(+ technicalsData.indicator_columns?.volume,+ COLORS.BLUE,+ 'VOLUME INDICATORS',+ <Volume2 size={16} color={COLORS.BLUE} />,+ 'volume'+ )}- {/* Others Indicators */}- {renderIndicatorCategory(technicalsData.indicator_columns?.others, COLORS.MAGENTA, 'RETURN')}+ {renderIndicatorCategory(+ technicalsData.indicator_columns?.others,+ COLORS.PURPLE,+ 'RETURN INDICATORS',+ <Percent size={16} color={COLORS.PURPLE} />,+ 'others'+ )}++ {/* Trading Notes */}+ <div style={{+ backgroundColor: COLORS.PANEL_BG,+ border: BORDERS.STANDARD,+ marginTop: SPACING.MEDIUM,+ }}>+ <div style={{+ backgroundColor: COLORS.HEADER_BG,+ padding: `${SPACING.SMALL} ${SPACING.MEDIUM}`,+ borderBottom: `2px solid ${COLORS.YELLOW}`,+ display: 'flex',+ alignItems: 'center',+ gap: SPACING.SMALL,+ }}>+ <AlertTriangle size={12} color={COLORS.YELLOW} />+ <span style={{+ color: COLORS.YELLOW,+ fontSize: TYPOGRAPHY.SMALL,+ fontWeight: TYPOGRAPHY.BOLD,+ textTransform: 'uppercase',+ letterSpacing: TYPOGRAPHY.WIDE,+ }}>+ TRADING NOTES+ </span>+ </div>+ <div style={{+ padding: SPACING.MEDIUM,+ color: COLORS.GRAY,+ fontSize: TYPOGRAPHY.SMALL,+ lineHeight: '1.6',+ }}>+ <div style={{ display: 'flex', gap: SPACING.SMALL, marginBottom: SPACING.SMALL }}>+ <span style={{ color: COLORS.MUTED }}>•</span>+ <span>Technical indicators should be used in conjunction with fundamental analysis and risk management.</span>+ </div>+ <div style={{ display: 'flex', gap: SPACING.SMALL, marginBottom: SPACING.SMALL }}>+ <span style={{ color: COLORS.MUTED }}>•</span>+ <span>Signal strength increases when multiple indicators align (confluence).</span>+ </div>+ <div style={{ display: 'flex', gap: SPACING.SMALL, marginBottom: SPACING.SMALL }}>+ <span style={{ color: COLORS.MUTED }}>•</span>+ <span>Overbought/oversold conditions can persist in strong trends - use with trend confirmation.</span>+ </div>+ <div style={{ display: 'flex', gap: SPACING.SMALL }}>+ <span style={{ color: COLORS.MUTED }}>•</span>+ <span>Past performance does not guarantee future results. Always use stop-losses.</span>+ </div>+ </div></div></div>);diff --git a/fincept-terminal-desktop/src/components/tabs/equity-research/types/index.ts b/fincept-terminal-desktop/src/components/tabs/equity-research/types/index.tsindex 6779a1d3c..d428f2ae6 100644--- a/fincept-terminal-desktop/src/components/tabs/equity-research/types/index.ts+++ b/fincept-terminal-desktop/src/components/tabs/equity-research/types/index.ts@@ -91,6 +91,10 @@ export interface SearchResult {symbol: string;name: string;type: string;+ exchange?: string;+ currency?: string;+ sector?: string;+ industry?: string;}export interface NewsArticle {diff --git a/fincept-terminal-desktop/src/components/tabs/equity-research/utils/formatters.ts b/fincept-terminal-desktop/src/components/tabs/equity-research/utils/formatters.tsindex 51965789b..9f9ff22e3 100644--- a/fincept-terminal-desktop/src/components/tabs/equity-research/utils/formatters.ts+++ b/fincept-terminal-desktop/src/components/tabs/equity-research/utils/formatters.ts@@ -9,14 +9,21 @@ export const formatNumber = (num: number | null | undefined, decimals = 2): stri};/**- * Format a large number with currency prefix and abbreviations (T, B, M)+ * Format a large number with currency prefix and abbreviations (T, B, M, K)+ * Handles negative numbers properly*/export const formatLargeNumber = (num: number | null | undefined): string => {- if (num === null || num === undefined) return 'N/A';- if (num >= 1e12) return `$${(num / 1e12).toFixed(2)}T`;- if (num >= 1e9) return `$${(num / 1e9).toFixed(2)}B`;- if (num >= 1e6) return `$${(num / 1e6).toFixed(2)}M`;- return `$${num.toFixed(2)}`;+ if (num === null || num === undefined || isNaN(num)) return 'N/A';++ const absNum = Math.abs(num);+ const sign = num < 0 ? '-' : '';++ if (absNum >= 1e12) return `${sign}$${(absNum / 1e12).toFixed(2)}T`;+ if (absNum >= 1e9) return `${sign}$${(absNum / 1e9).toFixed(2)}B`;+ if (absNum >= 1e6) return `${sign}$${(absNum / 1e6).toFixed(2)}M`;+ if (absNum >= 1e3) return `${sign}$${(absNum / 1e3).toFixed(2)}K`;+ if (absNum === 0) return '$0';+ return `${sign}$${absNum.toFixed(2)}`;};/**diff --git a/fincept-terminal-desktop/src/components/tabs/equity-trading/EquityTradingTab.tsx b/fincept-terminal-desktop/src/components/tabs/equity-trading/EquityTradingTab.tsxindex 45fb64a60..e7c9e2d39 100644--- a/fincept-terminal-desktop/src/components/tabs/equity-trading/EquityTradingTab.tsx+++ b/fincept-terminal-desktop/src/components/tabs/equity-trading/EquityTradingTab.tsx@@ -55,6 +55,71 @@ const FINCEPT = {MUTED: '#4A4A4A'};+// Currency configuration based on exchange/symbol+const CURRENCY_CONFIG: Record<string, { symbol: string; code: string; locale: string }> = {+ // Indian+ INR: { symbol: '₹', code: 'INR', locale: 'en-IN' },+ // US+ USD: { symbol: '$', code: 'USD', locale: 'en-US' },+ // European+ EUR: { symbol: '€', code: 'EUR', locale: 'de-DE' },+ GBP: { symbol: '£', code: 'GBP', locale: 'en-GB' },+ // Asian+ JPY: { symbol: '¥', code: 'JPY', locale: 'ja-JP' },+ HKD: { symbol: 'HK$', code: 'HKD', locale: 'zh-HK' },+ SGD: { symbol: 'S$', code: 'SGD', locale: 'en-SG' },+ // Others+ AUD: { symbol: 'A$', code: 'AUD', locale: 'en-AU' },+ CAD: { symbol: 'C$', code: 'CAD', locale: 'en-CA' },+};++// Map exchange to default currency+const EXCHANGE_CURRENCY: Record<string, string> = {+ NSE: 'INR', BSE: 'INR', NFO: 'INR', BFO: 'INR', MCX: 'INR', CDS: 'INR',+ NYSE: 'USD', NASDAQ: 'USD', AMEX: 'USD',+ LSE: 'GBP',+ XETRA: 'EUR', EURONEXT: 'EUR',+ TSX: 'CAD',+ ASX: 'AUD',+ HKEX: 'HKD',+ SGX: 'SGD',+ TSE: 'JPY',+};++// Detect currency from symbol suffix (for YFinance symbols like RELIANCE.NS)+const getCurrencyFromSymbol = (symbol: string, exchange?: string): string => {+ if (symbol.endsWith('.NS') || symbol.endsWith('.BO')) return 'INR';+ if (symbol.endsWith('.L')) return 'GBP';+ if (symbol.endsWith('.DE')) return 'EUR';+ if (symbol.endsWith('.TO')) return 'CAD';+ if (symbol.endsWith('.AX')) return 'AUD';+ if (symbol.endsWith('.HK')) return 'HKD';+ if (symbol.endsWith('.T')) return 'JPY';+ if (exchange) return EXCHANGE_CURRENCY[exchange] || 'USD';+ return 'USD'; // Default for US stocks without suffix+};++// Format currency value+const formatCurrency = (value: number, currencyCode: string = 'INR', compact: boolean = false): string => {+ const config = CURRENCY_CONFIG[currencyCode] || CURRENCY_CONFIG.USD;++ if (compact && Math.abs(value) >= 1000) {+ // Compact format for large numbers+ if (Math.abs(value) >= 10000000) { // 1 Crore+ return `${config.symbol}${(value / 10000000).toFixed(2)}Cr`;+ } else if (Math.abs(value) >= 100000) { // 1 Lakh+ return `${config.symbol}${(value / 100000).toFixed(2)}L`;+ } else if (Math.abs(value) >= 1000) {+ return `${config.symbol}${(value / 1000).toFixed(1)}K`;+ }+ }++ return `${config.symbol}${value.toLocaleString(config.locale, {+ minimumFractionDigits: 2,+ maximumFractionDigits: 2+ })}`;+};+// NIFTY 50 Components - Full watchlist (current constituents as of Jan 2025)const DEFAULT_WATCHLIST = [// Financials (Weight: ~35%)@@ -129,10 +194,9 @@ function EquityTradingContent() {// Watchlistconst [watchlist, setWatchlist] = useState<string[]>(DEFAULT_WATCHLIST);const [watchlistQuotes, setWatchlistQuotes] = useState<Record<string, Quote>>({});- // Auto-set WebSocket based on market hours - ON during market hours, OFF when closed- const [useWebSocketForWatchlist, setUseWebSocketForWatchlist] = useState<boolean>(() => {- return isMarketOpen(selectedExchange || 'NSE');- });+ // Auto-set WebSocket based on market hours AND broker support+ // OFF by default - will be enabled by useEffect if broker supports WS and market is open+ const [useWebSocketForWatchlist, setUseWebSocketForWatchlist] = useState<boolean>(false);// UI Stateconst [leftSidebarView, setLeftSidebarView] = useState<LeftSidebarView>('watchlist');@@ -152,22 +216,42 @@ function EquityTradingContent() {.slice(0, 50); // Keep last 50 trades}, [trades, selectedSymbol]);+ // Get currency based on selected symbol and exchange+ const currentCurrency = useMemo(() => {+ return getCurrencyFromSymbol(selectedSymbol, selectedExchange);+ }, [selectedSymbol, selectedExchange]);++ // Currency formatter for current symbol+ const fmtPrice = useCallback((value: number, compact = false) => {+ return formatCurrency(value, currentCurrency, compact);+ }, [currentCurrency]);+// Update clockuseEffect(() => {const timer = setInterval(() => setCurrentTime(new Date()), 1000);return () => clearInterval(timer);}, []);- // Auto-toggle WebSocket based on market hours+ // Auto-toggle WebSocket based on market hours AND broker support// Check every minute and switch WS on when market opens, off when it closes+ // Brokers without WebSocket support (like YFinance) always use REST pollinguseEffect(() => {const checkMarketStatus = () => {+ const brokerSupportsWs = activeBrokerMetadata?.features?.webSocket ?? false;const marketOpen = isMarketOpen(selectedExchange);++ // Only enable WebSocket if broker supports it AND market is open+ const shouldUseWs = brokerSupportsWs && marketOpen;+setUseWebSocketForWatchlist(prev => {- if (prev !== marketOpen) {- console.log(`[EquityTrading] Market ${marketOpen ? 'OPEN' : 'CLOSED'} - WebSocket ${marketOpen ? 'enabled' : 'disabled'}`);+ if (prev !== shouldUseWs) {+ if (!brokerSupportsWs) {+ console.log(`[EquityTrading] Broker doesn't support WebSocket - using REST polling`);+ } else {+ console.log(`[EquityTrading] Market ${marketOpen ? 'OPEN' : 'CLOSED'} - WebSocket ${shouldUseWs ? 'enabled' : 'disabled'}`);+ }}- return marketOpen;+ return shouldUseWs;});};@@ -177,22 +261,60 @@ function EquityTradingContent() {// Check every minuteconst interval = setInterval(checkMarketStatus, 60 * 1000);return () => clearInterval(interval);- }, [selectedExchange]);+ }, [selectedExchange, activeBrokerMetadata]);++ // Track previous broker to detect broker changes+ const prevBrokerRef = React.useRef<string | null>(null);- // Set default symbol when broker changes+ // Set default symbol and exchange when broker changesuseEffect(() => {- if (defaultSymbols.length > 0 && !selectedSymbol) {- setSelectedSymbol(defaultSymbols[0]);- }- // Update watchlist - use broker defaults if available, otherwise use full Nifty 50+ const brokerChanged = prevBrokerRef.current !== null && prevBrokerRef.current !== activeBroker;+ prevBrokerRef.current = activeBroker;+if (defaultSymbols.length > 0) {- // Use broker's default symbols (but not sliced - show all 50)+ // Always reset symbol when broker changes, or set if no symbol selected+ if (brokerChanged || !selectedSymbol) {+ setSelectedSymbol(defaultSymbols[0]);+ // Clear quote data when broker changes+ if (brokerChanged) {+ setQuote(null);+ setMarketDepth(null);+ }+ }++ // Update exchange based on broker region - on broker change OR initial load+ if (activeBrokerMetadata && (brokerChanged || selectedExchange === 'NSE')) {+ const brokerRegion = activeBrokerMetadata.region;+ const brokerExchanges = activeBrokerMetadata.exchanges || [];++ // Set exchange based on broker's home region+ if (brokerRegion === 'india') {+ setSelectedExchange('NSE');+ } else if (brokerRegion === 'us') {+ // NASDAQ is primary US exchange for tech stocks+ if (brokerExchanges.includes('NASDAQ')) {+ setSelectedExchange('NASDAQ');+ } else if (brokerExchanges.includes('NYSE')) {+ setSelectedExchange('NYSE');+ }+ } else if (brokerExchanges.includes('NASDAQ')) {+ setSelectedExchange('NASDAQ');+ } else if (brokerExchanges.includes('NYSE')) {+ setSelectedExchange('NYSE');+ } else if (brokerExchanges.includes('NSE')) {+ setSelectedExchange('NSE');+ } else if (brokerExchanges.length > 0) {+ setSelectedExchange(brokerExchanges[0] as StockExchange);+ }+ }++ // Update watchlist - use broker defaultssetWatchlist(defaultSymbols.slice(0, 50));} else {// Fallback to our DEFAULT_WATCHLIST (full Nifty 50)setWatchlist(DEFAULT_WATCHLIST);}- }, [defaultSymbols, selectedSymbol]);+ }, [defaultSymbols, activeBroker, activeBrokerMetadata]);// Subscribe to WebSocket for live prices and fetch initial datauseEffect(() => {@@ -726,86 +848,103 @@ function EquityTradingContent() {<div style={{ height: '16px', width: '1px', backgroundColor: FINCEPT.BORDER }} />- {/* Trading Mode Toggle */}- <div style={{- display: 'flex',- alignItems: 'center',- gap: '2px',- backgroundColor: FINCEPT.PANEL_BG,- border: `1px solid ${FINCEPT.BORDER}`,- padding: '2px',- }}>- <button- onClick={() => setTradingMode('paper')}- style={{- padding: '6px 14px',- backgroundColor: isPaper ? FINCEPT.GREEN : 'transparent',- border: 'none',- color: isPaper ? FINCEPT.DARK_BG : FINCEPT.GRAY,- cursor: 'pointer',- fontSize: '10px',- fontWeight: 700,- letterSpacing: '0.5px',- transition: 'all 0.2s',- display: 'flex',- alignItems: 'center',- gap: '6px',- }}- >- {isPaper && (- <div style={{- width: '6px',- height: '6px',- borderRadius: '50%',- backgroundColor: FINCEPT.DARK_BG,- }} />- )}- PAPER- </button>- <button- onClick={() => {- if (!isLive) {- const confirmed = window.confirm(- 'WARNING: SWITCHING TO LIVE TRADING\n\n' +- 'You are about to enable LIVE trading mode.\n\n' +- '- All orders will be placed with REAL funds\n' +- '- Trades will be executed on the actual exchange\n' +- '- You may lose money\n\n' +- 'Are you sure you want to continue?'- );- if (confirmed) {- setTradingMode('live');+ {/* Trading Mode Toggle - Hidden for paper-only brokers like YFinance */}+ {activeBroker === 'yfinance' ? (+ <div style={{+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ backgroundColor: FINCEPT.GREEN,+ padding: '6px 14px',+ fontSize: '10px',+ fontWeight: 700,+ letterSpacing: '0.5px',+ color: FINCEPT.DARK_BG,+ }}>+ <div style={{ width: '6px', height: '6px', borderRadius: '50%', backgroundColor: FINCEPT.DARK_BG }} />+ PAPER ONLY+ </div>+ ) : (+ <div style={{+ display: 'flex',+ alignItems: 'center',+ gap: '2px',+ backgroundColor: FINCEPT.PANEL_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ padding: '2px',+ }}>+ <button+ onClick={() => setTradingMode('paper')}+ style={{+ padding: '6px 14px',+ backgroundColor: isPaper ? FINCEPT.GREEN : 'transparent',+ border: 'none',+ color: isPaper ? FINCEPT.DARK_BG : FINCEPT.GRAY,+ cursor: 'pointer',+ fontSize: '10px',+ fontWeight: 700,+ letterSpacing: '0.5px',+ transition: 'all 0.2s',+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ }}+ >+ {isPaper && (+ <div style={{+ width: '6px',+ height: '6px',+ borderRadius: '50%',+ backgroundColor: FINCEPT.DARK_BG,+ }} />+ )}+ PAPER+ </button>+ <button+ onClick={() => {+ if (!isLive) {+ const confirmed = window.confirm(+ 'WARNING: SWITCHING TO LIVE TRADING\n\n' ++ 'You are about to enable LIVE trading mode.\n\n' ++ '- All orders will be placed with REAL funds\n' ++ '- Trades will be executed on the actual exchange\n' ++ '- You may lose money\n\n' ++ 'Are you sure you want to continue?'+ );+ if (confirmed) {+ setTradingMode('live');+ }}- }- }}- style={{- padding: '6px 14px',- backgroundColor: isLive ? FINCEPT.RED : 'transparent',- border: 'none',- color: isLive ? FINCEPT.WHITE : FINCEPT.GRAY,- cursor: 'pointer',- fontSize: '10px',- fontWeight: 700,- letterSpacing: '0.5px',- transition: 'all 0.2s',- display: 'flex',- alignItems: 'center',- gap: '6px',- }}- >- {isLive && (- <div style={{- width: '6px',- height: '6px',- borderRadius: '50%',- backgroundColor: FINCEPT.WHITE,- boxShadow: `0 0 6px ${FINCEPT.WHITE}`,- animation: 'pulse 1s infinite',- }} />- )}- LIVE- </button>- </div>+ }}+ style={{+ padding: '6px 14px',+ backgroundColor: isLive ? FINCEPT.RED : 'transparent',+ border: 'none',+ color: isLive ? FINCEPT.WHITE : FINCEPT.GRAY,+ cursor: 'pointer',+ fontSize: '10px',+ fontWeight: 700,+ letterSpacing: '0.5px',+ transition: 'all 0.2s',+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ }}+ >+ {isLive && (+ <div style={{+ width: '6px',+ height: '6px',+ borderRadius: '50%',+ backgroundColor: FINCEPT.WHITE,+ boxShadow: `0 0 6px ${FINCEPT.WHITE}`,+ animation: 'pulse 1s infinite',+ }} />+ )}+ LIVE+ </button>+ </div>+ )}</div><div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>@@ -894,7 +1033,7 @@ function EquityTradingContent() {willChange: 'contents',transition: 'none'}}>- {currentPrice > 0 ? `₹${currentPrice.toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}` : '--'}+ {currentPrice > 0 ? fmtPrice(currentPrice) : '--'}</span>{quote && (priceChange !== 0 || priceChangePercent !== 0) && (<div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>@@ -921,31 +1060,31 @@ function EquityTradingContent() {<div style={{ minWidth: '60px' }}><div style={{ color: FINCEPT.GRAY, fontSize: '9px', marginBottom: '2px' }}>BID</div><div style={{ color: FINCEPT.GREEN, fontWeight: 600, willChange: 'contents', transition: 'none' }}>- {quote?.bid ? `₹${quote.bid.toFixed(2)}` : '--'}+ {quote?.bid ? fmtPrice(quote.bid) : '--'}</div></div><div style={{ minWidth: '60px' }}><div style={{ color: FINCEPT.GRAY, fontSize: '9px', marginBottom: '2px' }}>ASK</div><div style={{ color: FINCEPT.RED, fontWeight: 600, willChange: 'contents', transition: 'none' }}>- {quote?.ask ? `₹${quote.ask.toFixed(2)}` : '--'}+ {quote?.ask ? fmtPrice(quote.ask) : '--'}</div></div><div style={{ minWidth: '100px' }}><div style={{ color: FINCEPT.GRAY, fontSize: '9px', marginBottom: '2px' }}>DAY RANGE</div><div style={{ color: FINCEPT.CYAN, fontWeight: 600, willChange: 'contents', transition: 'none' }}>- {dayRange > 0 ? `₹${dayRange.toFixed(2)} (${dayRangePercent.toFixed(2)}%)` : '--'}+ {dayRange > 0 ? `${fmtPrice(dayRange)} (${dayRangePercent.toFixed(2)}%)` : '--'}</div></div><div style={{ minWidth: '80px' }}><div style={{ color: FINCEPT.GRAY, fontSize: '9px', marginBottom: '2px' }}>HIGH</div><div style={{ color: FINCEPT.WHITE, fontWeight: 600, willChange: 'contents', transition: 'none' }}>- {quote?.high ? `₹${quote.high.toFixed(2)}` : '--'}+ {quote?.high ? fmtPrice(quote.high) : '--'}</div></div><div style={{ minWidth: '80px' }}><div style={{ color: FINCEPT.GRAY, fontSize: '9px', marginBottom: '2px' }}>LOW</div><div style={{ color: FINCEPT.WHITE, fontWeight: 600, willChange: 'contents', transition: 'none' }}>- {quote?.low ? `₹${quote.low.toFixed(2)}` : '--'}+ {quote?.low ? fmtPrice(quote.low) : '--'}</div></div><div style={{ minWidth: '100px' }}>@@ -964,13 +1103,13 @@ function EquityTradingContent() {<div><div style={{ color: FINCEPT.GRAY, fontSize: '9px', marginBottom: '2px' }}>MARGIN</div><div style={{ color: FINCEPT.CYAN, fontWeight: 600 }}>- ₹{(funds?.availableMargin || 0).toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}+ {fmtPrice(funds?.availableMargin || 0)}</div></div><div><div style={{ color: FINCEPT.GRAY, fontSize: '9px', marginBottom: '2px' }}>P&L</div><div style={{ color: totalPositionPnl >= 0 ? FINCEPT.GREEN : FINCEPT.RED, fontWeight: 600 }}>- {totalPositionPnl >= 0 ? '+' : ''}₹{totalPositionPnl.toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}+ {totalPositionPnl >= 0 ? '+' : ''}{fmtPrice(Math.abs(totalPositionPnl))}</div></div></div>@@ -1125,10 +1264,7 @@ function EquityTradingContent() {fontFamily: 'monospace',fontWeight: 600}}>- ₹{q.lastPrice >= 1000- ? q.lastPrice.toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })- : q.lastPrice.toFixed(2)- }+ {formatCurrency(q.lastPrice, getCurrencyFromSymbol(symbol, selectedExchange))}</div><div style={{fontSize: '9px',@@ -1330,7 +1466,17 @@ function EquityTradingContent() {<StockTradingChartsymbol={selectedSymbol}exchange={selectedExchange}- interval="5m"+ interval={activeBroker === 'yfinance' ? '1d' : '5m'}+ liveQuote={quote ? {+ lastPrice: quote.lastPrice,+ change: quote.change || 0,+ changePercent: quote.changePercent || 0,+ previousClose: quote.previousClose,+ open: quote.open,+ high: quote.high,+ low: quote.low,+ volume: quote.volume+ } : undefined}/></div>)}@@ -1390,7 +1536,7 @@ function EquityTradingContent() {textAlign: 'right',color: trade.side === 'BUY' ? FINCEPT.GREEN : FINCEPT.RED}}>- ₹{trade.price?.toFixed(2)}+ {formatCurrency(trade.price || 0, getCurrencyFromSymbol(trade.symbol, selectedExchange))}</td><td style={{ padding: '4px 6px', textAlign: 'right', color: FINCEPT.WHITE }}>{trade.quantity}@@ -1515,7 +1661,7 @@ function EquityTradingContent() {}}><div style={{ fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '8px' }}>TOTAL POSITIONS VALUE</div><div style={{ fontSize: '18px', fontWeight: 700, color: FINCEPT.CYAN }}>- ₹{totalPositionValue.toLocaleString('en-IN', { minimumFractionDigits: 2 })}+ {fmtPrice(totalPositionValue)}</div></div><div style={{@@ -1529,7 +1675,7 @@ function EquityTradingContent() {fontWeight: 700,color: totalPositionPnl >= 0 ? FINCEPT.GREEN : FINCEPT.RED}}>- {totalPositionPnl >= 0 ? '+' : ''}₹{totalPositionPnl.toLocaleString('en-IN', { minimumFractionDigits: 2 })}+ {totalPositionPnl >= 0 ? '+' : '-'}{fmtPrice(Math.abs(totalPositionPnl))}</div></div><div style={{@@ -1539,7 +1685,7 @@ function EquityTradingContent() {}}><div style={{ fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '8px' }}>PORTFOLIO VALUE</div><div style={{ fontSize: '18px', fontWeight: 700, color: FINCEPT.YELLOW }}>- ₹{totalHoldingsValue.toLocaleString('en-IN', { minimumFractionDigits: 2 })}+ {fmtPrice(totalHoldingsValue)}</div></div><div style={{@@ -1549,7 +1695,7 @@ function EquityTradingContent() {}}><div style={{ fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '8px' }}>AVAILABLE MARGIN</div><div style={{ fontSize: '18px', fontWeight: 700, color: FINCEPT.PURPLE }}>- ₹{(funds?.availableMargin || 0).toLocaleString('en-IN', { minimumFractionDigits: 2 })}+ {fmtPrice(funds?.availableMargin || 0)}</div></div></div>@@ -1723,7 +1869,7 @@ function EquityTradingContent() {{bid?.quantity ? bid.quantity.toLocaleString('en-IN') : '--'}</td><td style={{ padding: '4px', textAlign: 'right', color: FINCEPT.GREEN }}>- {bid?.price ? `₹${bid.price.toFixed(2)}` : '--'}+ {bid?.price ? fmtPrice(bid.price) : '--'}</td><td style={{ padding: '4px', textAlign: 'right', color: FINCEPT.GRAY }}>{bid?.orders || '--'}@@ -1744,7 +1890,7 @@ function EquityTradingContent() {}}><span style={{ color: FINCEPT.GRAY }}>Spread: </span><span style={{ color: FINCEPT.YELLOW, fontWeight: 600 }}>- {spread > 0 ? `₹${spread.toFixed(2)} (${spreadPercent.toFixed(3)}%)` : '--'}+ {spread > 0 ? `${fmtPrice(spread)} (${spreadPercent.toFixed(3)}%)` : '--'}</span></div>@@ -1768,7 +1914,7 @@ function EquityTradingContent() {).map((ask, i) => (<tr key={i} style={{ borderBottom: `1px solid ${FINCEPT.BORDER}40` }}><td style={{ padding: '4px', color: FINCEPT.RED }}>- {ask?.price ? `₹${ask.price.toFixed(2)}` : '--'}+ {ask?.price ? fmtPrice(ask.price) : '--'}</td><td style={{ padding: '4px', textAlign: 'right', color: FINCEPT.WHITE }}>{ask?.quantity ? ask.quantity.toLocaleString('en-IN') : '--'}@@ -1806,7 +1952,7 @@ function EquityTradingContent() {return (<div key={i} style={{ display: 'flex', alignItems: 'center', gap: '4px', height: '20px' }}><span style={{ fontSize: '9px', color: FINCEPT.GREEN, width: '60px', textAlign: 'right' }}>- ₹{bid.price.toFixed(2)}+ {fmtPrice(bid.price)}</span><div style={{ flex: 1, height: '16px', backgroundColor: FINCEPT.PANEL_BG, position: 'relative' }}><div style={{@@ -1836,7 +1982,7 @@ function EquityTradingContent() {borderTop: `1px solid ${FINCEPT.BORDER}`,borderBottom: `1px solid ${FINCEPT.BORDER}`,}}>- Spread: {spread > 0 ? `₹${spread.toFixed(2)}` : '--'}+ Spread: {spread > 0 ? fmtPrice(spread) : '--'}</div>{/* Ask depth bars */}@@ -1850,7 +1996,7 @@ function EquityTradingContent() {return (<div key={i} style={{ display: 'flex', alignItems: 'center', gap: '4px', height: '20px' }}><span style={{ fontSize: '9px', color: FINCEPT.RED, width: '60px', textAlign: 'right' }}>- ₹{ask.price.toFixed(2)}+ {fmtPrice(ask.price)}</span><div style={{ flex: 1, height: '16px', backgroundColor: FINCEPT.PANEL_BG, position: 'relative' }}><div style={{@@ -1905,10 +2051,10 @@ function EquityTradingContent() {{[{ label: 'Symbol', value: selectedSymbol || '--' },{ label: 'Exchange', value: selectedExchange },- { label: 'Open', value: quote?.open ? `₹${quote.open.toFixed(2)}` : '--' },- { label: 'Prev Close', value: quote?.previousClose ? `₹${quote.previousClose.toFixed(2)}` : '--' },- { label: 'Day High', value: quote?.high ? `₹${quote.high.toFixed(2)}` : '--' },- { label: 'Day Low', value: quote?.low ? `₹${quote.low.toFixed(2)}` : '--' },+ { label: 'Open', value: quote?.open ? fmtPrice(quote.open) : '--' },+ { label: 'Prev Close', value: quote?.previousClose ? fmtPrice(quote.previousClose) : '--' },+ { label: 'Day High', value: quote?.high ? fmtPrice(quote.high) : '--' },+ { label: 'Day Low', value: quote?.low ? fmtPrice(quote.low) : '--' },{ label: 'Volume', value: quote?.volume ? quote.volume.toLocaleString('en-IN') : '--' },].map((item) => (<divdiff --git a/fincept-terminal-desktop/src/components/tabs/equity-trading/components/StockTradingChart.tsx b/fincept-terminal-desktop/src/components/tabs/equity-trading/components/StockTradingChart.tsxindex 058ef8adb..fce4fe1bc 100644--- a/fincept-terminal-desktop/src/components/tabs/equity-trading/components/StockTradingChart.tsx+++ b/fincept-terminal-desktop/src/components/tabs/equity-trading/components/StockTradingChart.tsx@@ -12,12 +12,24 @@ import type { StockExchange, TimeFrame, OHLCV } from '@/brokers/stocks/types';import { useStockBrokerContext } from '@/contexts/StockBrokerContext';import { ProChartWithToolkit } from '../../trading/charts/ProChartWithToolkit';+interface LiveQuote {+ lastPrice: number;+ change: number;+ changePercent: number;+ previousClose?: number;+ open?: number;+ high?: number;+ low?: number;+ volume?: number;+}+interface StockTradingChartProps {symbol: string;exchange: StockExchange;interval?: TimeFrame;height?: number;timezone?: string; // e.g., 'Asia/Kolkata' for IST+ liveQuote?: LiveQuote; // Live quote data from parent for consistent display}// Available timeframes@@ -35,22 +47,21 @@ const TIMEFRAMES: { value: TimeFrame; label: string }[] = [];// Helper to convert TimeFrame to days for historical data range-// For timeframes < 1d, show only past 7 daysconst timeframeToDays = (tf: TimeFrame): number => {switch (tf) {case '1m': return 7; // 1 min -> 7 dayscase '3m': return 7; // 3 min -> 7 days- case '5m': return 7; // 5 min -> 7 days- case '10m': return 7; // 10 min -> 7 days- case '15m': return 7; // 15 min -> 7 days- case '30m': return 7; // 30 min -> 7 days- case '1h': return 7; // 1 hour -> 7 days- case '2h': return 7; // 2 hours -> 7 days- case '4h': return 7; // 4 hours -> 7 days- case '1d': return 365; // 1 day -> 1 year- case '1w': return 730; // 1 week -> 2 years+ case '5m': return 14; // 5 min -> 14 days+ case '10m': return 14; // 10 min -> 14 days+ case '15m': return 30; // 15 min -> 30 days+ case '30m': return 30; // 30 min -> 30 days+ case '1h': return 60; // 1 hour -> 60 days+ case '2h': return 90; // 2 hours -> 90 days (3 months)+ case '4h': return 90; // 4 hours -> 90 days (3 months)+ case '1d': return 90; // 1 day -> 90 days (3 months) - default for paper trading+ case '1w': return 365; // 1 week -> 1 yearcase '1M': return 1825; // 1 month -> 5 years- default: return 7;+ default: return 90; // Default to 3 months}};@@ -78,9 +89,10 @@ const EXCHANGE_TIMEZONES: Record<string, string> = {export function StockTradingChart({symbol,exchange,- interval: initialInterval = '5m',+ interval: initialInterval = '1d',height,- timezone: propTimezone+ timezone: propTimezone,+ liveQuote}: StockTradingChartProps) {// Auto-detect timezone based on exchange if not providedconst timezone = propTimezone || EXCHANGE_TIMEZONES[exchange] || EXCHANGE_TIMEZONES.DEFAULT;@@ -98,6 +110,11 @@ export function StockTradingChart({const { adapter, isAuthenticated } = useStockBrokerContext();+ // Sync selectedInterval when initialInterval prop changes (e.g., broker switch)+ useEffect(() => {+ setSelectedInterval(initialInterval);+ }, [initialInterval]);+// Fetch historical dataconst fetchHistoricalData = useCallback(async () => {if (!symbol || !exchange) {@@ -239,11 +256,17 @@ export function StockTradingChart({);}- // Calculate price change for display+ // Calculate price change for display - prefer live quote data if availableconst latestCandle = chartData[chartData.length - 1];- const firstCandle = chartData[0];- const priceChange = latestCandle && firstCandle ? latestCandle.close - firstCandle.open : 0;- const priceChangePercent = latestCandle && firstCandle ? ((priceChange / firstCandle.open) * 100) : 0;++ // Use live quote for price change (compares to previous close), fallback to chart data+ const displayPrice = liveQuote?.lastPrice ?? latestCandle?.close ?? 0;+ const priceChange = liveQuote?.change ?? (latestCandle && liveQuote?.previousClose+ ? latestCandle.close - liveQuote.previousClose+ : 0);+ const priceChangePercent = liveQuote?.changePercent ?? (liveQuote?.previousClose && liveQuote.previousClose > 0+ ? ((priceChange / liveQuote.previousClose) * 100)+ : 0);return (<div className="flex-1 flex flex-col bg-[#0A0A0A]" style={{ height: height || '100%', minHeight: 0, overflow: 'hidden' }}>@@ -256,43 +279,46 @@ export function StockTradingChart({{exchange}:{symbol}</span>- {/* OHLC Data */}- {latestCandle && (+ {/* OHLC Data - Use live quote if available, fallback to chart candle */}+ {(liveQuote || latestCandle) && (<div className="flex items-center gap-3 text-[10px] font-mono"><div className="flex items-center gap-1"><span className="text-gray-500">O</span>- <span className="text-white">{latestCandle.open.toFixed(2)}</span>+ <span className="text-white">{(liveQuote?.open ?? latestCandle?.open ?? 0).toFixed(2)}</span></div><div className="flex items-center gap-1"><span className="text-gray-500">H</span>- <span className="text-white">{latestCandle.high.toFixed(2)}</span>+ <span className="text-white">{(liveQuote?.high ?? latestCandle?.high ?? 0).toFixed(2)}</span></div><div className="flex items-center gap-1"><span className="text-gray-500">L</span>- <span className="text-white">{latestCandle.low.toFixed(2)}</span>+ <span className="text-white">{(liveQuote?.low ?? latestCandle?.low ?? 0).toFixed(2)}</span></div><div className="flex items-center gap-1"><span className="text-gray-500">C</span>- <span className={`font-semibold ${latestCandle.close >= latestCandle.open ? 'text-[#00D66F]' : 'text-[#FF3B3B]'}`}>- {latestCandle.close.toFixed(2)}+ <span className={`font-semibold ${priceChange >= 0 ? 'text-[#00D66F]' : 'text-[#FF3B3B]'}`}>+ {displayPrice.toFixed(2)}</span></div>- {/* Price Change & Percentage */}+ {/* Price Change & Percentage - from live quote */}<div className={`flex items-center gap-1 ${priceChange >= 0 ? 'text-[#00D66F]' : 'text-[#FF3B3B]'}`}><span>{priceChange >= 0 ? '+' : ''}{priceChange.toFixed(2)}</span>- <span>({priceChange >= 0 ? '+' : ''}{priceChangePercent.toFixed(2)}%)</span>+ <span>({priceChangePercent >= 0 ? '+' : ''}{priceChangePercent.toFixed(2)}%)</span></div>- {/* Volume */}+ {/* Volume - prefer live quote */}<div className="flex items-center gap-1"><span className="text-gray-500">Vol</span><span className="text-white">- {latestCandle.volume >= 1000000- ? `${(latestCandle.volume / 1000000).toFixed(2)}M`- : latestCandle.volume >= 1000- ? `${(latestCandle.volume / 1000).toFixed(2)}K`- : latestCandle.volume.toFixed(0)}+ {(() => {+ const vol = liveQuote?.volume ?? latestCandle?.volume ?? 0;+ return vol >= 1000000+ ? `${(vol / 1000000).toFixed(2)}M`+ : vol >= 1000+ ? `${(vol / 1000).toFixed(2)}K`+ : vol.toFixed(0);+ })()}</span></div></div>diff --git a/fincept-terminal-desktop/src/components/tabs/equity-trading/components/YFinanceSettings.tsx b/fincept-terminal-desktop/src/components/tabs/equity-trading/components/YFinanceSettings.tsxnew file mode 100644index 000000000..eb360ecc1--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/equity-trading/components/YFinanceSettings.tsx@@ -0,0 +1,67 @@+/**+ * YFinance Paper Trading Settings+ *+ * Simple settings for YFinance paper trading - just cache TTL selection+ */++import React from 'react';+import { Settings, Clock, Info } from 'lucide-react';+import type { UpdateInterval } from '@/brokers/stocks/yfinance';++const CACHE_OPTIONS: Array<{ value: UpdateInterval; label: string }> = [+ { value: 15, label: '15 sec' },+ { value: 30, label: '30 sec' },+ { value: 60, label: '1 min' },+ { value: 300, label: '5 min' },+ { value: 600, label: '10 min' },+];++interface YFinanceSettingsProps {+ cacheTTL: UpdateInterval;+ onCacheTTLChange: (ttl: UpdateInterval) => void;+ isConnected: boolean;+}++export function YFinanceSettings({ cacheTTL, onCacheTTLChange, isConnected }: YFinanceSettingsProps) {+ return (+ <div className="rounded-lg p-4 bg-[#0F0F0F] border border-[#2A2A2A]">+ <div className="flex items-center gap-2 mb-3">+ <Settings size={16} className="text-[#FF8800]" />+ <span className="font-medium text-white text-sm">YFinance Settings</span>+ {isConnected && (+ <span className="ml-auto text-xs px-2 py-0.5 rounded bg-[#00D66F]/20 text-[#00D66F]">+ Connected+ </span>+ )}+ </div>++ <div className="flex items-center gap-2 mb-2">+ <Clock size={12} className="text-[#787878]" />+ <span className="text-xs text-[#787878]">Quote Cache Duration</span>+ </div>++ <div className="flex gap-1">+ {CACHE_OPTIONS.map((opt) => (+ <button+ key={opt.value}+ onClick={() => onCacheTTLChange(opt.value)}+ className={`px-2 py-1 text-xs rounded transition-colors ${+ cacheTTL === opt.value+ ? 'bg-[#FF8800] text-white'+ : 'bg-[#1A1A1A] text-[#787878] hover:bg-[#2A2A2A]'+ }`}+ >+ {opt.label}+ </button>+ ))}+ </div>++ <div className="mt-3 flex items-start gap-2 text-xs text-[#787878]">+ <Info size={12} className="mt-0.5 shrink-0" />+ <span>Quotes are cached and fetched on-demand. Lower values = fresher data but more API calls.</span>+ </div>+ </div>+ );+}++export default YFinanceSettings;diff --git a/fincept-terminal-desktop/src/components/tabs/equity-trading/components/index.ts b/fincept-terminal-desktop/src/components/tabs/equity-trading/components/index.tsindex 1401403a0..d00bfe88b 100644--- a/fincept-terminal-desktop/src/components/tabs/equity-trading/components/index.ts+++ b/fincept-terminal-desktop/src/components/tabs/equity-trading/components/index.ts@@ -14,3 +14,4 @@ export { FundsPanel } from './FundsPanel';export { StockTradingChart } from './StockTradingChart';export { SymbolSearch } from './SymbolSearch';export { MasterContractManager } from './MasterContractManager';+export { YFinanceSettings } from './YFinanceSettings';diff --git a/fincept-terminal-desktop/src/components/tabs/report-builder/ProductivityFeatures.tsx b/fincept-terminal-desktop/src/components/tabs/report-builder/ProductivityFeatures.tsxindex cc07aa721..44ec0239e 100644--- a/fincept-terminal-desktop/src/components/tabs/report-builder/ProductivityFeatures.tsx+++ b/fincept-terminal-desktop/src/components/tabs/report-builder/ProductivityFeatures.tsx@@ -203,6 +203,12 @@ export const useKeyboardShortcuts = (shortcuts: ShortcutMap, enabled: boolean =if (!enabled) return;const handleKeyDown = (e: KeyboardEvent) => {+ // Don't trigger if user is typing in an input field+ const target = e.target as HTMLElement;+ if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable) {+ return;+ }+for (const [shortcutStr, action] of Object.entries(shortcuts)) {const { key, ctrl, shift, alt } = parseShortcut(shortcutStr);const keyMatch = e.key.toLowerCase() === key.toLowerCase();diff --git a/fincept-terminal-desktop/src/components/tabs/trading/TradingChart.tsx b/fincept-terminal-desktop/src/components/tabs/trading/TradingChart.tsxindex da826bf67..727c44d29 100644--- a/fincept-terminal-desktop/src/components/tabs/trading/TradingChart.tsx+++ b/fincept-terminal-desktop/src/components/tabs/trading/TradingChart.tsx@@ -1,6 +1,6 @@// TradingChart.tsx - TradingView Lightweight Charts with historical + live dataimport React, { useEffect, useRef, useState } from 'react';-import { createChart, IChartApi, ISeriesApi, CandlestickData, Time } from 'lightweight-charts';+import { createChart, IChartApi, ISeriesApi, CandlestickData, Time, CrosshairMode } from 'lightweight-charts';import { useRustCandles } from '../../../hooks/useRustWebSocket';import { useBrokerContext } from '../../../contexts/BrokerContext';@@ -49,7 +49,7 @@ export function TradingChart({ symbol, provider, interval = '1m' }: TradingCharthorzLines: { color: '#1a1a1a' },},crosshair: {- mode: 1, // Normal crosshair+ mode: CrosshairMode.Normal, // Free movement crosshair},rightPriceScale: {borderColor: '#2a2a2a',diff --git a/fincept-terminal-desktop/src/components/tabs/trading/charts/ProChartWithToolkit.tsx b/fincept-terminal-desktop/src/components/tabs/trading/charts/ProChartWithToolkit.tsxindex 51c8dcd8e..dcb584212 100644--- a/fincept-terminal-desktop/src/components/tabs/trading/charts/ProChartWithToolkit.tsx+++ b/fincept-terminal-desktop/src/components/tabs/trading/charts/ProChartWithToolkit.tsx@@ -5,7 +5,7 @@*/import React, { useEffect, useRef, useState, useCallback } from 'react';-import { createChart, ColorType, CandlestickSeries, HistogramSeries } from 'lightweight-charts';+import { createChart, ColorType, CandlestickSeries, HistogramSeries, CrosshairMode } from 'lightweight-charts';import type { IChartApi, CandlestickData, Time, ISeriesApi, MouseEventParams } from 'lightweight-charts';import {PluginManager,@@ -109,7 +109,7 @@ export function ProChartWithToolkit({horzLines: { color: '#1f1f1f' },},crosshair: {- mode: 0, // Normal mode (0) allows free cursor movement, Magnet mode (1) snaps to candles+ mode: CrosshairMode.Normal, // Free cursor movement (Magnet mode snaps to candles)vertLine: {width: 1,color: '#758696',@@ -206,6 +206,12 @@ export function ProChartWithToolkit({// Handle keyboard shortcutsconst handleKeyDown = (e: KeyboardEvent) => {+ // Don't trigger if user is typing in an input field+ const target = e.target as HTMLElement;+ if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable) {+ return;+ }+// Delete: Remove last drawing or selected drawingif (e.key === 'Delete' || e.key === 'Backspace') {if (toolkitRef.current && !activeTool) {diff --git a/fincept-terminal-desktop/src/components/tabs/trading/charts/TradingChartWithPlugins.tsx b/fincept-terminal-desktop/src/components/tabs/trading/charts/TradingChartWithPlugins.tsxindex de2f35b32..dec8b698f 100644--- a/fincept-terminal-desktop/src/components/tabs/trading/charts/TradingChartWithPlugins.tsx+++ b/fincept-terminal-desktop/src/components/tabs/trading/charts/TradingChartWithPlugins.tsx@@ -4,7 +4,7 @@*/import React, { useEffect, useRef, useState, useCallback } from 'react';-import { createChart, ColorType, CandlestickSeries, HistogramSeries } from 'lightweight-charts';+import { createChart, ColorType, CandlestickSeries, HistogramSeries, CrosshairMode } from 'lightweight-charts';import type { IChartApi, CandlestickData, Time, ISeriesApi, SeriesType } from 'lightweight-charts';import { useOHLCV } from '../hooks/useMarketData';import type { Timeframe, OHLCV } from '../types';@@ -66,7 +66,7 @@ export function TradingChartWithPlugins({horzLines: { color: '#1f1f1f' },},crosshair: {- mode: 1,+ mode: CrosshairMode.Normal, // Free movement crosshair},rightPriceScale: {borderColor: '#2a2a2a',diff --git a/fincept-terminal-desktop/src/contexts/StockBrokerContext.tsx b/fincept-terminal-desktop/src/contexts/StockBrokerContext.tsxindex 9a8b4a9c8..3afbb7310 100644--- a/fincept-terminal-desktop/src/contexts/StockBrokerContext.tsx+++ b/fincept-terminal-desktop/src/contexts/StockBrokerContext.tsx@@ -330,7 +330,42 @@ export function StockBrokerProvider({ children }: StockBrokerProviderProps) {const newAdapter = createStockBrokerAdapter(activeBroker);console.log(`[StockBrokerContext] Created adapter for: ${activeBroker}`);- // Load credentials from database+ // Check if this is a paper-only broker that doesn't need credentials (like yfinance)+ // YFinance is a special case - it only supports paper trading and needs no authentication+ const isPaperOnlyBroker = activeBroker === 'yfinance';++ if (isPaperOnlyBroker) {+ console.log(`[StockBrokerContext] Paper-only broker detected: ${activeBroker}, auto-authenticating...`);++ // Auto-authenticate for paper-only brokers (no real credentials needed)+ const authResult = await newAdapter.authenticate({ apiKey: 'paper_trading' });++ if (authResult.success) {+ console.log(`[StockBrokerContext] ✓ Paper trading auto-authenticated for ${activeBroker}`);++ // IMPORTANT: Set adapter BEFORE isAuthenticated to avoid race condition+ // where EquityTradingTab checks isAuthenticated but adapter is still null+ setAdapter(newAdapter);+ setIsAuthenticated(true);+ setError(null);++ // Initialize unified trading session in paper mode+ try {+ await initTradingSession(activeBroker, 'paper');+ console.log(`[StockBrokerContext] ✓ Paper trading session initialized`);+ } catch (sessionErr) {+ console.error('[StockBrokerContext] Failed to init paper trading session:', sessionErr);+ }+ } else {+ console.error(`[StockBrokerContext] Paper trading auto-auth failed:`, authResult.message);+ setError(authResult.message || 'Failed to initialize paper trading');+ setAdapter(newAdapter);+ }++ return;+ }++ // For other brokers, load credentials from databasetry {console.log(`[StockBrokerContext] Loading credentials from database...`);const storedCreds = await (newAdapter as any).loadCredentials();@@ -416,13 +451,20 @@ export function StockBrokerProvider({ children }: StockBrokerProviderProps) {setFunds(null);setError(null);+ // For paper-only brokers like yfinance, force paper mode+ if (brokerId === 'yfinance' && tradingMode !== 'paper') {+ console.log(`[StockBrokerContext] Paper-only broker ${brokerId} selected, forcing paper mode`);+ setTradingModeState('paper');+ await safeStorageSet(STORAGE_KEYS.STOCK_TRADING_MODE, 'paper');+ }+// Set new brokersetActiveBrokerState(brokerId);await safeStorageSet(STORAGE_KEYS.ACTIVE_STOCK_BROKER, brokerId);// Adapter will be created by useEffect watching activeBrokerconsole.log(`[StockBrokerContext] Active broker set to: ${brokerId}`);- }, [adapter]);+ }, [adapter, tradingMode]);const setTradingMode = useCallback(async (mode: 'live' | 'paper') => {setTradingModeState(mode);diff --git a/fincept-terminal-desktop/src/services/agentService.ts b/fincept-terminal-desktop/src/services/agentService.tsindex f6b90f8dc..ad926b970 100644--- a/fincept-terminal-desktop/src/services/agentService.ts+++ b/fincept-terminal-desktop/src/services/agentService.ts@@ -997,13 +997,29 @@ export async function executeRoutedQuery(/*** Discover all available agents+ * Now with proper error logging and timeout handling*/export async function discoverAgents(): Promise<AgentCard[]> {try {+ console.log('[AgentService] Starting agent discovery...');+ const startTime = Date.now();+const result = await invoke<string>('discover_agents');const parsed = JSON.parse(result);++ const elapsed = Date.now() - startTime;+ console.log(`[AgentService] Discovered ${parsed.agents?.length || 0} agents in ${elapsed}ms`);++ if (!parsed.success && parsed.error) {+ console.warn('[AgentService] Discovery returned error:', parsed.error);+ }+return parsed.agents || [];- } catch {+ } catch (error: any) {+ // Log the actual error instead of swallowing it+ console.error('[AgentService] Agent discovery failed:', error?.message || error);++ // Return empty array but the error is now logged for debuggingreturn [];}}diff --git a/fincept-terminal-desktop/src/services/akshareApi.ts b/fincept-terminal-desktop/src/services/akshareApi.tsindex 9670113e0..44f98366d 100644--- a/fincept-terminal-desktop/src/services/akshareApi.ts+++ b/fincept-terminal-desktop/src/services/akshareApi.ts@@ -433,4 +433,10 @@ export class AKShareAPI {static async getCarSales(): Promise<AKShareResponse> {return this.query('akshare_alternative.py', 'car_sales');}++ // ==================== TRANSLATION ====================++ static async translateBatch(texts: string[], targetLang: string): Promise<any> {+ return await invoke('translate_batch', { texts, targetLang });+ }}