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
general bug fixes
tilakpatel2277fa50a0bd72
diff --git a/fincept-terminal-desktop/package.json b/fincept-terminal-desktop/package.jsonindex be7eb1b86..e4099befa 100644--- a/fincept-terminal-desktop/package.json+++ b/fincept-terminal-desktop/package.json@@ -1,7 +1,7 @@{"name": "fincept-terminal-desktop","private": true,- "version": "3.3.0",+ "version": "3.3.1","type": "module","license": "AGPL-3.0-or-later","scripts": {diff --git a/fincept-terminal-desktop/src-tauri/Cargo.lock b/fincept-terminal-desktop/src-tauri/Cargo.lockindex 2b1279c30..ba779a733 100644--- a/fincept-terminal-desktop/src-tauri/Cargo.lock+++ b/fincept-terminal-desktop/src-tauri/Cargo.lock@@ -1247,7 +1247,7 @@ dependencies = [[[package]]name = "fincept-terminal-desktop"-version = "3.3.0"+version = "3.3.1"dependencies = ["aes-gcm","ahash",diff --git a/fincept-terminal-desktop/src-tauri/Cargo.toml b/fincept-terminal-desktop/src-tauri/Cargo.tomlindex 40fa513d8..99a39a1cb 100644--- a/fincept-terminal-desktop/src-tauri/Cargo.toml+++ b/fincept-terminal-desktop/src-tauri/Cargo.toml@@ -1,6 +1,6 @@[package]name = "fincept-terminal-desktop"-version = "3.3.0"+version = "3.3.1"description = "Professional-grade financial analysis platform with AI-powered insights and real-time market data"authors = ["Fincept Corporation <[email protected]>"]edition = "2021"diff --git a/fincept-terminal-desktop/src-tauri/capabilities/default.json b/fincept-terminal-desktop/src-tauri/capabilities/default.jsonindex daa309bf0..6de847a23 100644--- a/fincept-terminal-desktop/src-tauri/capabilities/default.json+++ b/fincept-terminal-desktop/src-tauri/capabilities/default.json@@ -38,11 +38,13 @@"fs:allow-appdata-write","fs:allow-appdata-read-recursive","fs:allow-appdata-write-recursive",+ "fs:allow-resource-read-recursive",{"identifier": "fs:scope","allow": [{ "path": "**" },- { "path": "$APPDATA/**" }+ { "path": "$APPDATA/**" },+ { "path": "$RESOURCE/**" }]},"updater:default",diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/gluonts_wrapper/worker_handler.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/gluonts_wrapper/gluonts_service.pysimilarity index 100%rename from fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/gluonts_wrapper/worker_handler.pyrename to fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/gluonts_wrapper/gluonts_service.pydiff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/gs_quant_wrapper/worker_handler.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/gs_quant_wrapper/gs_quant_service.pysimilarity index 100%rename from fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/gs_quant_wrapper/worker_handler.pyrename to fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/gs_quant_wrapper/gs_quant_service.pydiff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/portfolioManagement/active_management.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/portfolioManagement/active_management.pyindex 2a11bfac3..ff7fb926d 100644--- a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/portfolioManagement/active_management.py+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/portfolioManagement/active_management.py@@ -165,7 +165,7 @@ class ValueAddedMeasurement:return {"t_statistic": t_statistic,"significance_level": significance_level,- "is_significant_95": abs(t_statistic) > critical_95,+ "is_significant_95": bool(abs(t_statistic) > critical_95),"sample_size": n_periods,"standard_error": std_active / np.sqrt(n_periods)}@@ -285,7 +285,7 @@ class InformationRatioAnalysis:return {"quality_rating": quality,"industry_percentile": percentile,- "sustainability_concern": ir_annualized > 1.0 # Very high IRs often not sustainable+ "sustainability_concern": bool(ir_annualized > 1.0) # Very high IRs often not sustainable}@staticmethoddiff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/py_vollib_wrapper/worker_handler.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/py_vollib_wrapper/vollib_service.pysimilarity index 100%rename from fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/py_vollib_wrapper/worker_handler.pyrename to fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/py_vollib_wrapper/vollib_service.pydiff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/pypme_wrapper/worker_handler.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/pypme_wrapper/pypme_service.pysimilarity index 100%rename from fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/pypme_wrapper/worker_handler.pyrename to fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/pypme_wrapper/pypme_service.pydiff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/pyportfolioopt_wrapper/worker_handler.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/pyportfolioopt_wrapper/pyportfolioopt_service.pysimilarity index 100%rename from fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/pyportfolioopt_wrapper/worker_handler.pyrename to fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/pyportfolioopt_wrapper/pyportfolioopt_service.pydiff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/python_skfolio_lib/worker_handler.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/python_skfolio_lib/skfolio_service.pysimilarity index 100%rename from fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/python_skfolio_lib/worker_handler.pyrename to fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/python_skfolio_lib/skfolio_service.pydiff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/talipp_wrapper/worker_handler.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/talipp_wrapper/talipp_service.pysimilarity index 100%rename from fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/talipp_wrapper/worker_handler.pyrename to fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/talipp_wrapper/talipp_service.pydiff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/core_agent.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/core_agent.pyindex 7339fd89e..264a274f2 100644--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/core_agent.py+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/core_agent.py@@ -405,8 +405,17 @@ class CoreAgent:def get_response_content(self, response) -> str:"""Extract text content from response."""+ # Try .content attribute (standard agno response)if hasattr(response, 'content'):return response.content++ # If response is a dict (from custom models), try to extract the text+ if isinstance(response, dict):+ for key in ['response', 'content', 'text', 'answer', 'message']:+ if key in response:+ return str(response[key])++ # Fallback to string conversionreturn str(response)def get_module(self, name: str) -> Optional[Any]:diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/registries/fincept_model.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/registries/fincept_model.pyindex e9c9ed256..8a130757d 100644--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/registries/fincept_model.py+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/registries/fincept_model.py@@ -135,11 +135,19 @@ class FinceptChat(Model):def _extract_content(self, data: Any) -> str:"""Extract text content from various response formats."""if isinstance(data, dict):+ # Fincept API format: {"success": true, "data": {"response": "..."}}+ if "data" in data and isinstance(data["data"], dict):+ if "response" in data["data"]:+ return str(data["data"]["response"])++ # OpenAI-style formatif "choices" in data:choices = data["choices"]if choices:msg = choices[0].get("message", {})return msg.get("content", "")++ # Other common formatsif "response" in data:return str(data["response"])if "content" in data:@@ -148,7 +156,9 @@ class FinceptChat(Model):return str(data["text"])if "answer" in data:return str(data["answer"])+return str(data)+return str(data) if data else ""def get_provider(self) -> str:diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/bis_data.py b/fincept-terminal-desktop/src-tauri/resources/scripts/bis_data.pyindex 4d583db90..9b1420bc2 100644--- a/fincept-terminal-desktop/src-tauri/resources/scripts/bis_data.py+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/bis_data.py@@ -911,7 +911,9 @@ class BISAPI:# CLI Interfaceasync def main():"""CLI interface for BIS API"""- if len(args) + 1 < 2:+ args = sys.argv[1:]++ if len(args) < 1:print(json.dumps({"error": "Usage: python bis_data.py <command> [args...]","available_commands": [@@ -937,13 +939,13 @@ async def main():async with BISAPI() as bis:try:if command == "get_data":- if len(args) + 1 < 3:+ if len(args) < 2:raise ValueError("Usage: get_data <flow> [key] [start_period] [end_period]")flow = args[1]- key = args[2] if len(args) + 1 > 3 else "all"- start_period = args[3] if len(args) + 1 > 4 else None- end_period = args[4] if len(args) + 1 > 5 else None+ key = args[2] if len(args) > 2 else "all"+ start_period = args[3] if len(args) > 3 else None+ end_period = args[4] if len(args) > 4 else Noneresult = await bis.get_data(flow, key, start_period, end_period)@@ -1099,14 +1101,14 @@ async def main():result = await bis.get_available_datasets()elif command == "get_data_structures":- agency_id = args[1] if len(args) + 1 > 2 else "all"- resource_id = args[2] if len(args) + 1 > 3 else "all"- version = args[3] if len(args) + 1 > 4 else "all"+ agency_id = args[1] if len(args) > 2 else "all"+ resource_id = args[2] if len(args) > 3 else "all"+ version = args[3] if len(args) > 4 else "all"result = await bis.get_data_structures(agency_id, resource_id, version)elif command == "search_datasets":- if len(args) + 1 < 3:+ if len(args) < 3:raise ValueError("Usage: search_datasets <query>")query = args[1]result = await bis.search_datasets(query)@@ -1131,151 +1133,151 @@ async def main():)elif command == "get_dataset_metadata":- if len(args) + 1 < 3:+ if len(args) < 3:raise ValueError("Usage: get_dataset_metadata <flow>")flow = args[1]result = await bis.get_dataset_metadata(flow)elif command == "get_available_constraints":- if len(args) + 1 < 5:+ if len(args) < 5:raise ValueError("Usage: get_available_constraints <flow> <key> <component_id> [mode] [references]")flow = args[1]key = args[2]component_id = args[3]- mode = args[4] if len(args) + 1 > 5 else "exact"- references = sys.argv[6] if len(args) + 1 > 6 else "none"+ mode = args[4] if len(args) > 5 else "exact"+ references = sys.argv[6] if len(args) > 6 else "none"result = await bis.get_available_constraints(flow, key, component_id, mode, references)elif command == "get_dataflows":- agency_id = args[1] if len(args) + 1 > 2 else "all"- resource_id = args[2] if len(args) + 1 > 3 else "all"- version = args[3] if len(args) + 1 > 4 else "all"- references = args[4] if len(args) + 1 > 5 else "none"- detail = sys.argv[6] if len(args) + 1 > 6 else "full"+ agency_id = args[1] if len(args) > 2 else "all"+ resource_id = args[2] if len(args) > 3 else "all"+ version = args[3] if len(args) > 4 else "all"+ references = args[4] if len(args) > 5 else "none"+ detail = sys.argv[6] if len(args) > 6 else "full"result = await bis.get_dataflows(agency_id, resource_id, version, references, detail)elif command == "get_categorisations":- agency_id = args[1] if len(args) + 1 > 2 else "all"- resource_id = args[2] if len(args) + 1 > 3 else "all"- version = args[3] if len(args) + 1 > 4 else "all"- references = args[4] if len(args) + 1 > 5 else "none"- detail = sys.argv[6] if len(args) + 1 > 6 else "full"+ agency_id = args[1] if len(args) > 2 else "all"+ resource_id = args[2] if len(args) > 3 else "all"+ version = args[3] if len(args) > 4 else "all"+ references = args[4] if len(args) > 5 else "none"+ detail = sys.argv[6] if len(args) > 6 else "full"result = await bis.get_categorisations(agency_id, resource_id, version, references, detail)elif command == "get_content_constraints":- agency_id = args[1] if len(args) + 1 > 2 else "all"- resource_id = args[2] if len(args) + 1 > 3 else "all"- version = args[3] if len(args) + 1 > 4 else "all"- references = args[4] if len(args) + 1 > 5 else "none"- detail = sys.argv[6] if len(args) + 1 > 6 else "full"+ agency_id = args[1] if len(args) > 2 else "all"+ resource_id = args[2] if len(args) > 3 else "all"+ version = args[3] if len(args) > 4 else "all"+ references = args[4] if len(args) > 5 else "none"+ detail = sys.argv[6] if len(args) > 6 else "full"result = await bis.get_content_constraints(agency_id, resource_id, version, references, detail)elif command == "get_actual_constraints":- agency_id = args[1] if len(args) + 1 > 2 else "all"- resource_id = args[2] if len(args) + 1 > 3 else "all"- version = args[3] if len(args) + 1 > 4 else "all"- references = args[4] if len(args) + 1 > 5 else "none"- detail = sys.argv[6] if len(args) + 1 > 6 else "full"+ agency_id = args[1] if len(args) > 2 else "all"+ resource_id = args[2] if len(args) > 3 else "all"+ version = args[3] if len(args) > 4 else "all"+ references = args[4] if len(args) > 5 else "none"+ detail = sys.argv[6] if len(args) > 6 else "full"result = await bis.get_actual_constraints(agency_id, resource_id, version, references, detail)elif command == "get_allowed_constraints":- agency_id = args[1] if len(args) + 1 > 2 else "all"- resource_id = args[2] if len(args) + 1 > 3 else "all"- version = args[3] if len(args) + 1 > 4 else "all"- references = args[4] if len(args) + 1 > 5 else "none"- detail = sys.argv[6] if len(args) + 1 > 6 else "full"+ agency_id = args[1] if len(args) > 2 else "all"+ resource_id = args[2] if len(args) > 3 else "all"+ version = args[3] if len(args) > 4 else "all"+ references = args[4] if len(args) > 5 else "none"+ detail = sys.argv[6] if len(args) > 6 else "full"result = await bis.get_allowed_constraints(agency_id, resource_id, version, references, detail)elif command == "get_structures":- agency_id = args[1] if len(args) + 1 > 2 else "all"- resource_id = args[2] if len(args) + 1 > 3 else "all"- version = args[3] if len(args) + 1 > 4 else "all"- references = args[4] if len(args) + 1 > 5 else "none"- detail = sys.argv[6] if len(args) + 1 > 6 else "full"+ agency_id = args[1] if len(args) > 2 else "all"+ resource_id = args[2] if len(args) > 3 else "all"+ version = args[3] if len(args) > 4 else "all"+ references = args[4] if len(args) > 5 else "none"+ detail = sys.argv[6] if len(args) > 6 else "full"result = await bis.get_structures(agency_id, resource_id, version, references, detail)elif command == "get_concept_schemes":- agency_id = args[1] if len(args) + 1 > 2 else "all"- resource_id = args[2] if len(args) + 1 > 3 else "all"- version = args[3] if len(args) + 1 > 4 else "all"- references = args[4] if len(args) + 1 > 5 else "none"- detail = sys.argv[6] if len(args) + 1 > 6 else "full"+ agency_id = args[1] if len(args) > 2 else "all"+ resource_id = args[2] if len(args) > 3 else "all"+ version = args[3] if len(args) > 4 else "all"+ references = args[4] if len(args) > 5 else "none"+ detail = sys.argv[6] if len(args) > 6 else "full"result = await bis.get_concept_schemes(agency_id, resource_id, version, references, detail)elif command == "get_codelists":- agency_id = args[1] if len(args) + 1 > 2 else "all"- resource_id = args[2] if len(args) + 1 > 3 else "all"- version = args[3] if len(args) + 1 > 4 else "all"- references = args[4] if len(args) + 1 > 5 else "none"- detail = sys.argv[6] if len(args) + 1 > 6 else "full"+ agency_id = args[1] if len(args) > 2 else "all"+ resource_id = args[2] if len(args) > 3 else "all"+ version = args[3] if len(args) > 4 else "all"+ references = args[4] if len(args) > 5 else "none"+ detail = sys.argv[6] if len(args) > 6 else "full"result = await bis.get_codelists(agency_id, resource_id, version, references, detail)elif command == "get_category_schemes":- agency_id = args[1] if len(args) + 1 > 2 else "all"- resource_id = args[2] if len(args) + 1 > 3 else "all"- version = args[3] if len(args) + 1 > 4 else "all"- references = args[4] if len(args) + 1 > 5 else "none"- detail = sys.argv[6] if len(args) + 1 > 6 else "full"+ agency_id = args[1] if len(args) > 2 else "all"+ resource_id = args[2] if len(args) > 3 else "all"+ version = args[3] if len(args) > 4 else "all"+ references = args[4] if len(args) > 5 else "none"+ detail = sys.argv[6] if len(args) > 6 else "full"result = await bis.get_category_schemes(agency_id, resource_id, version, references, detail)elif command == "get_hierarchical_codelists":- agency_id = args[1] if len(args) + 1 > 2 else "all"- resource_id = args[2] if len(args) + 1 > 3 else "all"- version = args[3] if len(args) + 1 > 4 else "all"- references = args[4] if len(args) + 1 > 5 else "none"- detail = sys.argv[6] if len(args) + 1 > 6 else "full"+ agency_id = args[1] if len(args) > 2 else "all"+ resource_id = args[2] if len(args) > 3 else "all"+ version = args[3] if len(args) > 4 else "all"+ references = args[4] if len(args) > 5 else "none"+ detail = sys.argv[6] if len(args) > 6 else "full"result = await bis.get_hierarchical_codelists(agency_id, resource_id, version, references, detail)elif command == "get_agency_schemes":- agency_id = args[1] if len(args) + 1 > 2 else "all"- resource_id = args[2] if len(args) + 1 > 3 else "all"- version = args[3] if len(args) + 1 > 4 else "all"- references = args[4] if len(args) + 1 > 5 else "none"- detail = sys.argv[6] if len(args) + 1 > 6 else "full"+ agency_id = args[1] if len(args) > 2 else "all"+ resource_id = args[2] if len(args) > 3 else "all"+ version = args[3] if len(args) > 4 else "all"+ references = args[4] if len(args) > 5 else "none"+ detail = sys.argv[6] if len(args) > 6 else "full"result = await bis.get_agency_schemes(agency_id, resource_id, version, references, detail)elif command == "get_concepts":- if len(args) + 1 < 4:+ if len(args) < 4:raise ValueError("Usage: get_concepts <agency_id> <resource_id> <version> [item_id] [references] [detail]")agency_id = args[1]resource_id = args[2]version = args[3]- item_id = args[4] if len(args) + 1 > 5 else "all"- references = sys.argv[6] if len(args) + 1 > 6 else "none"- detail = sys.argv[7] if len(args) + 1 > 7 else "full"+ item_id = args[4] if len(args) > 5 else "all"+ references = sys.argv[6] if len(args) > 6 else "none"+ detail = sys.argv[7] if len(args) > 7 else "full"result = await bis.get_concepts(agency_id, resource_id, version, item_id, references, detail)elif command == "get_codes":- if len(args) + 1 < 4:+ if len(args) < 4:raise ValueError("Usage: get_codes <agency_id> <resource_id> <version> [item_id] [references] [detail]")agency_id = args[1]resource_id = args[2]version = args[3]- item_id = args[4] if len(args) + 1 > 5 else "all"- references = sys.argv[6] if len(args) + 1 > 6 else "none"- detail = sys.argv[7] if len(args) + 1 > 7 else "full"+ item_id = args[4] if len(args) > 5 else "all"+ references = sys.argv[6] if len(args) > 6 else "none"+ detail = sys.argv[7] if len(args) > 7 else "full"result = await bis.get_codes(agency_id, resource_id, version, item_id, references, detail)elif command == "get_categories":- if len(args) + 1 < 4:+ if len(args) < 4:raise ValueError("Usage: get_categories <agency_id> <resource_id> <version> [item_id] [references] [detail]")agency_id = args[1]resource_id = args[2]version = args[3]- item_id = args[4] if len(args) + 1 > 5 else "all"- references = sys.argv[6] if len(args) + 1 > 6 else "none"- detail = sys.argv[7] if len(args) + 1 > 7 else "full"+ item_id = args[4] if len(args) > 5 else "all"+ references = sys.argv[6] if len(args) > 6 else "none"+ detail = sys.argv[7] if len(args) > 7 else "full"result = await bis.get_categories(agency_id, resource_id, version, item_id, references, detail)elif command == "get_hierarchies":- if len(args) + 1 < 4:+ if len(args) < 4:raise ValueError("Usage: get_hierarchies <agency_id> <resource_id> <version> [item_id] [references] [detail]")agency_id = args[1]resource_id = args[2]version = args[3]- item_id = args[4] if len(args) + 1 > 5 else "all"- references = sys.argv[6] if len(args) + 1 > 6 else "none"- detail = sys.argv[7] if len(args) + 1 > 7 else "full"+ item_id = args[4] if len(args) > 5 else "all"+ references = sys.argv[6] if len(args) > 6 else "none"+ detail = sys.argv[7] if len(args) > 7 else "full"result = await bis.get_hierarchies(agency_id, resource_id, version, item_id, references, detail)else:diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/fincept_output_standard.py b/fincept-terminal-desktop/src-tauri/resources/scripts/fincept_output_standard.pynew file mode 100644index 000000000..98d6c2d95--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/fincept_output_standard.py@@ -0,0 +1,632 @@+"""+Fincept Terminal - Python Output Standardization Library+=========================================================++This library provides a standard output format for all Python scripts in the Fincept Terminal.+It ensures consistent JSON output across 100+ scripts, making frontend parsing simple and reliable.++Standard Output Format:+{+ "success": true/false,+ "data": { ... },+ "metadata": {+ "script": "script_name",+ "timestamp": "ISO-8601",+ "output_type": "table|dict|array|text|number|multi|error",+ "version": "1.0.0",+ "execution_time_ms": 123+ },+ "error": null or {"message": "...", "type": "...", "traceback": "..."}+}++Usage:+ from fincept_output_standard import standardize_output, OutputType++ # Simple usage+ result = standardize_output(data, script_name="my_script")++ # With explicit type+ result = standardize_output(dataframe, output_type=OutputType.TABLE)++ # Print standardized output+ print_standard_output(data, script_name="my_script")+"""++import json+import sys+import traceback+from datetime import datetime+from enum import Enum+from typing import Any, Dict, List, Optional, Union+import time+++class OutputType(Enum):+ """Enumeration of supported output types"""+ TABLE = "table" # Pandas DataFrames, tabular data+ DICT = "dict" # Dictionary/object data+ ARRAY = "array" # Lists, arrays+ TEXT = "text" # String outputs+ NUMBER = "number" # Numeric outputs+ MULTI = "multi" # Multiple outputs of different types+ ERROR = "error" # Error state+ CHART = "chart" # Chart/visualization data+ TIMESERIES = "timeseries" # Time series data+ MATRIX = "matrix" # 2D numeric arrays+ EMPTY = "empty" # No data/null result+++class FinceptOutputStandardizer:+ """Main class for standardizing Python script outputs"""++ VERSION = "1.0.0"++ def __init__(self, script_name: str = "unknown", include_metadata: bool = True):+ """+ Initialize standardizer++ Args:+ script_name: Name of the script producing output+ include_metadata: Whether to include metadata in output+ """+ self.script_name = script_name+ self.include_metadata = include_metadata+ self.start_time = time.time()++ def standardize(self, data: Any, output_type: Optional[OutputType] = None) -> Dict:+ """+ Standardize any Python object into standard format++ Args:+ data: The data to standardize (DataFrame, dict, list, etc.)+ output_type: Optional explicit type specification++ Returns:+ Standardized dictionary ready for JSON serialization+ """+ try:+ # Auto-detect type if not specified+ if output_type is None:+ output_type = self._detect_type(data)++ # Convert data based on type+ converted_data = self._convert_data(data, output_type)++ # Build standard response+ response = {+ "success": True,+ "data": converted_data,+ "error": None+ }++ # Add metadata if requested+ if self.include_metadata:+ response["metadata"] = self._build_metadata(output_type)++ return response++ except Exception as e:+ return self._create_error_response(e)++ def _detect_type(self, data: Any) -> OutputType:+ """Auto-detect the type of data"""++ # Check for None/null+ if data is None:+ return OutputType.EMPTY++ # Check for pandas DataFrame+ try:+ import pandas as pd+ if isinstance(data, pd.DataFrame):+ return OutputType.TABLE+ if isinstance(data, pd.Series):+ return OutputType.ARRAY+ except ImportError:+ pass++ # Check for numpy array+ try:+ import numpy as np+ if isinstance(data, np.ndarray):+ if data.ndim == 1:+ return OutputType.ARRAY+ elif data.ndim == 2:+ return OutputType.MATRIX+ else:+ return OutputType.ARRAY+ except ImportError:+ pass++ # Check Python built-in types+ if isinstance(data, dict):+ # Check if it's a multi-output structure+ if self._is_multi_output(data):+ return OutputType.MULTI+ return OutputType.DICT++ if isinstance(data, (list, tuple)):+ # Check if it's tabular data (list of dicts with same keys)+ if self._is_tabular_list(data):+ return OutputType.TABLE+ return OutputType.ARRAY++ if isinstance(data, str):+ return OutputType.TEXT++ if isinstance(data, (int, float, complex)):+ return OutputType.NUMBER++ # Default to dict (will JSON serialize the object)+ return OutputType.DICT++ def _is_multi_output(self, data: dict) -> bool:+ """Check if dictionary represents multiple outputs"""+ # Look for keys like 'output1', 'output2' or 'result1', 'result2'+ keys = list(data.keys())+ if len(keys) > 1:+ # Check for patterns indicating multiple distinct outputs+ has_varied_types = len(set(type(v).__name__ for v in data.values())) > 1+ if has_varied_types:+ return True+ return False++ def _is_tabular_list(self, data: list) -> bool:+ """Check if list is tabular data (list of dicts with consistent keys)"""+ if not data or len(data) < 2:+ return False++ if not all(isinstance(item, dict) for item in data):+ return False++ # Check if all dicts have the same keys+ first_keys = set(data[0].keys())+ return all(set(item.keys()) == first_keys for item in data[1:])++ def _convert_data(self, data: Any, output_type: OutputType) -> Dict:+ """Convert data to standardized structure based on type"""++ if output_type == OutputType.TABLE:+ return self._convert_table(data)++ elif output_type == OutputType.DICT:+ return self._convert_dict(data)++ elif output_type == OutputType.ARRAY:+ return self._convert_array(data)++ elif output_type == OutputType.TEXT:+ return self._convert_text(data)++ elif output_type == OutputType.NUMBER:+ return self._convert_number(data)++ elif output_type == OutputType.MULTI:+ return self._convert_multi(data)++ elif output_type == OutputType.MATRIX:+ return self._convert_matrix(data)++ elif output_type == OutputType.TIMESERIES:+ return self._convert_timeseries(data)++ elif output_type == OutputType.EMPTY:+ return {"type": "empty", "value": None}++ else:+ # Fallback: try to serialize as-is+ return {"type": "unknown", "value": self._make_serializable(data)}++ def _convert_table(self, data: Any) -> Dict:+ """Convert tabular data to standard format"""+ try:+ import pandas as pd++ # Convert to DataFrame if not already+ if isinstance(data, pd.DataFrame):+ df = data+ elif isinstance(data, list) and self._is_tabular_list(data):+ df = pd.DataFrame(data)+ else:+ df = pd.DataFrame([data])++ # Convert to records format+ result = {+ "type": "table",+ "columns": list(df.columns),+ "rows": df.to_dict('records'),+ "shape": list(df.shape),+ "dtypes": {col: str(dtype) for col, dtype in df.dtypes.items()}+ }++ # Add index if it's not default+ if not isinstance(df.index, pd.RangeIndex):+ result["index"] = df.index.tolist()++ return result++ except Exception as e:+ # Fallback to simple list representation+ return {+ "type": "table",+ "columns": [],+ "rows": data if isinstance(data, list) else [data],+ "error": f"Conversion warning: {str(e)}"+ }++ def _convert_dict(self, data: Any) -> Dict:+ """Convert dictionary to standard format"""+ if isinstance(data, dict):+ serializable_data = self._make_serializable(data)+ else:+ # Try to convert object to dict+ try:+ serializable_data = data.__dict__+ except:+ serializable_data = {"value": str(data)}++ return {+ "type": "dict",+ "value": serializable_data+ }++ def _convert_array(self, data: Any) -> Dict:+ """Convert array/list to standard format"""+ try:+ import numpy as np+ if isinstance(data, np.ndarray):+ array_data = data.tolist()+ elif isinstance(data, (list, tuple)):+ array_data = list(data)+ else:+ array_data = [data]++ return {+ "type": "array",+ "items": self._make_serializable(array_data),+ "length": len(array_data)+ }+ except Exception as e:+ return {+ "type": "array",+ "items": [str(data)],+ "length": 1,+ "error": f"Conversion warning: {str(e)}"+ }++ def _convert_text(self, data: Any) -> Dict:+ """Convert text to standard format"""+ return {+ "type": "text",+ "value": str(data),+ "length": len(str(data))+ }++ def _convert_number(self, data: Any) -> Dict:+ """Convert number to standard format"""+ try:+ import numpy as np+ # Handle numpy scalar types+ if isinstance(data, (np.integer, np.floating)):+ value = data.item()+ else:+ value = float(data) if '.' in str(data) else int(data)+ except:+ value = data++ return {+ "type": "number",+ "value": value+ }++ def _convert_multi(self, data: Dict) -> Dict:+ """Convert multiple outputs to standard format"""+ outputs = []++ for key, value in data.items():+ output_type = self._detect_type(value)+ converted = self._convert_data(value, output_type)+ outputs.append({+ "name": key,+ "data": converted+ })++ return {+ "type": "multi",+ "outputs": outputs,+ "count": len(outputs)+ }++ def _convert_matrix(self, data: Any) -> Dict:+ """Convert 2D matrix to standard format"""+ try:+ import numpy as np++ if isinstance(data, np.ndarray):+ matrix_data = data.tolist()+ else:+ matrix_data = data++ return {+ "type": "matrix",+ "values": matrix_data,+ "shape": [len(matrix_data), len(matrix_data[0]) if matrix_data else 0]+ }+ except Exception as e:+ return {+ "type": "matrix",+ "values": [[str(data)]],+ "error": f"Conversion warning: {str(e)}"+ }++ def _convert_timeseries(self, data: Any) -> Dict:+ """Convert time series data to standard format"""+ try:+ import pandas as pd++ if isinstance(data, pd.Series):+ return {+ "type": "timeseries",+ "timestamps": data.index.tolist() if hasattr(data.index, 'tolist') else list(data.index),+ "values": data.tolist(),+ "length": len(data)+ }+ else:+ # Assume dict with 'timestamps' and 'values'+ return {+ "type": "timeseries",+ "timestamps": data.get("timestamps", []),+ "values": data.get("values", []),+ "length": len(data.get("values", []))+ }+ except Exception as e:+ return {+ "type": "timeseries",+ "error": f"Conversion error: {str(e)}"+ }++ def _make_serializable(self, obj: Any) -> Any:+ """Make an object JSON serializable"""+ try:+ import numpy as np+ import pandas as pd++ # Handle pandas types+ if isinstance(obj, pd.DataFrame):+ return obj.to_dict('records')+ if isinstance(obj, pd.Series):+ return obj.tolist()+ if isinstance(obj, (pd.Timestamp, pd.DatetimeTZDtype)):+ return obj.isoformat() if hasattr(obj, 'isoformat') else str(obj)++ # Handle numpy types+ if isinstance(obj, np.ndarray):+ return obj.tolist()+ if isinstance(obj, (np.integer, np.floating)):+ return obj.item()+ if isinstance(obj, np.bool_):+ return bool(obj)++ # Handle datetime+ if hasattr(obj, 'isoformat'):+ return obj.isoformat()++ # Handle dictionaries recursively+ if isinstance(obj, dict):+ return {k: self._make_serializable(v) for k, v in obj.items()}++ # Handle lists/tuples recursively+ if isinstance(obj, (list, tuple)):+ return [self._make_serializable(item) for item in obj]++ # Handle objects with __dict__+ if hasattr(obj, '__dict__'):+ return self._make_serializable(obj.__dict__)++ # Primitive types+ if isinstance(obj, (str, int, float, bool, type(None))):+ return obj++ # Last resort: convert to string+ return str(obj)++ except Exception as e:+ return f"<non-serializable: {type(obj).__name__}>"++ def _build_metadata(self, output_type: OutputType) -> Dict:+ """Build metadata object"""+ execution_time = (time.time() - self.start_time) * 1000 # Convert to ms++ return {+ "script": self.script_name,+ "timestamp": datetime.utcnow().isoformat() + "Z",+ "output_type": output_type.value,+ "version": self.VERSION,+ "execution_time_ms": round(execution_time, 2)+ }++ def _create_error_response(self, error: Exception) -> Dict:+ """Create standardized error response"""+ execution_time = (time.time() - self.start_time) * 1000++ return {+ "success": False,+ "data": None,+ "error": {+ "message": str(error),+ "type": type(error).__name__,+ "traceback": traceback.format_exc()+ },+ "metadata": {+ "script": self.script_name,+ "timestamp": datetime.utcnow().isoformat() + "Z",+ "output_type": OutputType.ERROR.value,+ "version": self.VERSION,+ "execution_time_ms": round(execution_time, 2)+ }+ }+++# ============================================================================+# Convenience Functions+# ============================================================================++def standardize_output(data: Any,+ script_name: str = "unknown",+ output_type: Optional[OutputType] = None,+ include_metadata: bool = True) -> Dict:+ """+ Standardize output data in one function call++ Args:+ data: The data to standardize+ script_name: Name of the script+ output_type: Optional explicit type+ include_metadata: Whether to include metadata++ Returns:+ Standardized dictionary+ """+ standardizer = FinceptOutputStandardizer(script_name, include_metadata)+ return standardizer.standardize(data, output_type)+++def print_standard_output(data: Any,+ script_name: str = "unknown",+ output_type: Optional[OutputType] = None,+ include_metadata: bool = True,+ indent: Optional[int] = None):+ """+ Standardize and print output directly to stdout++ Args:+ data: The data to standardize and print+ script_name: Name of the script+ output_type: Optional explicit type+ include_metadata: Whether to include metadata+ indent: JSON indentation (None for compact, 2 for readable)+ """+ result = standardize_output(data, script_name, output_type, include_metadata)+ print(json.dumps(result, indent=indent))+++def wrap_script_execution(func):+ """+ Decorator to wrap script execution with standard output formatting++ Usage:+ @wrap_script_execution+ def main():+ # Your script logic+ return some_data+ """+ def wrapper(*args, **kwargs):+ script_name = func.__module__ if func.__module__ != "__main__" else func.__name__+ standardizer = FinceptOutputStandardizer(script_name)++ try:+ result = func(*args, **kwargs)+ output = standardizer.standardize(result)+ print(json.dumps(output))+ return 0+ except Exception as e:+ error_output = standardizer._create_error_response(e)+ print(json.dumps(error_output))+ return 1++ return wrapper+++# ============================================================================+# Legacy Output Handler (for gradual migration)+# ============================================================================++class LegacyOutputHandler:+ """+ Handler for wrapping legacy script outputs without modifying the scripts+ This can be used at the Rust level to intercept stdout+ """++ @staticmethod+ def try_parse_and_standardize(raw_output: str, script_name: str = "unknown") -> Dict:+ """+ Attempt to parse legacy output and standardize it++ Args:+ raw_output: Raw stdout from script+ script_name: Name of the script++ Returns:+ Standardized output+ """+ try:+ # Try to parse as JSON first+ parsed = json.loads(raw_output)+ return standardize_output(parsed, script_name=script_name)+ except json.JSONDecodeError:+ # Not JSON, treat as text+ return standardize_output(raw_output, script_name=script_name, output_type=OutputType.TEXT)+ except Exception as e:+ # Complete failure, wrap in error+ return {+ "success": False,+ "data": None,+ "error": {+ "message": f"Failed to parse output: {str(e)}",+ "type": "OutputParsingError",+ "raw_output": raw_output[:1000] # First 1000 chars+ },+ "metadata": {+ "script": script_name,+ "timestamp": datetime.utcnow().isoformat() + "Z",+ "output_type": OutputType.ERROR.value,+ "version": FinceptOutputStandardizer.VERSION+ }+ }+++# ============================================================================+# Example Usage+# ============================================================================++if __name__ == "__main__":+ # Example 1: DataFrame output+ try:+ import pandas as pd+ df = pd.DataFrame({+ 'A': [1, 2, 3],+ 'B': [4, 5, 6]+ })+ print("Example 1 - DataFrame:")+ print_standard_output(df, script_name="example_dataframe", indent=2)+ except ImportError:+ print("Pandas not available, skipping DataFrame example")++ print("\n" + "="*50 + "\n")++ # Example 2: Dictionary output+ data = {+ "symbol": "AAPL",+ "price": 150.25,+ "change": 2.5,+ "metrics": {"pe_ratio": 25.3, "volume": 1000000}+ }+ print("Example 2 - Dictionary:")+ print_standard_output(data, script_name="example_dict", indent=2)++ print("\n" + "="*50 + "\n")++ # Example 3: Array output+ array_data = [100, 200, 300, 400]+ print("Example 3 - Array:")+ print_standard_output(array_data, script_name="example_array", indent=2)++ print("\n" + "="*50 + "\n")++ # Example 4: Using decorator+ @wrap_script_execution+ def example_script():+ return {"result": "success", "value": 42}++ print("Example 4 - Decorator:")+ example_script()diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/worker.py b/fincept-terminal-desktop/src-tauri/resources/scripts/worker.pydeleted file mode 100644index 512ca1dd1..000000000--- a/fincept-terminal-desktop/src-tauri/resources/scripts/worker.py+++ /dev/null@@ -1,344 +0,0 @@-#!/usr/bin/env python3-"""-Python Worker Process - Persistent process with ThreadPoolExecutor-Communicates with Rust via Named Pipes (Windows) or Unix Domain Sockets-Single process handles multiple requests concurrently using threads--IMPORTANT: This worker LISTENS (server mode), Rust CONNECTS (client mode)-"""--import sys-import os-import json-import traceback-import importlib.util-import socket-import struct-import threading-from pathlib import Path-from concurrent.futures import ThreadPoolExecutor--# Try to import msgpack, fall back to json if not available-try:- import msgpack- USE_MSGPACK = True-except ImportError:- USE_MSGPACK = False- print("[Worker] msgpack not available, using JSON fallback", file=sys.stderr, flush=True)---class PythonWorker:- def __init__(self, socket_name, worker_id, num_threads=4):- self.socket_name = socket_name- self.worker_id = worker_id- self.num_threads = num_threads- self.server_socket = None- self.client_socket = None- self.running = True- self.executor = ThreadPoolExecutor(max_workers=num_threads)- self.send_lock = threading.Lock()-- print(f"[Worker {worker_id}] Initializing with {num_threads} threads", file=sys.stderr, flush=True)- print(f"[Worker {worker_id}] Python: {sys.version}", file=sys.stderr, flush=True)- print(f"[Worker {worker_id}] Socket: {socket_name}", file=sys.stderr, flush=True)-- def start_server(self):- """Create socket/pipe and listen for Rust connection"""- if sys.platform == 'win32':- self._start_windows_pipe_server()- else:- self._start_unix_socket_server()-- def _start_windows_pipe_server(self):- """Create Windows named pipe server"""- try:- import win32pipe- import win32file- import pywintypes- except ImportError:- # Fallback to TCP socket on localhost for Windows without pywin32- print(f"[Worker {self.worker_id}] pywin32 not available, using TCP fallback", file=sys.stderr, flush=True)- self._start_tcp_server()- return-- pipe_name = f"\\\\.\\pipe\\{self.socket_name}"- print(f"[Worker {self.worker_id}] Creating named pipe: {pipe_name}", file=sys.stderr, flush=True)-- try:- # Create named pipe (server mode)- self.server_socket = win32pipe.CreateNamedPipe(- pipe_name,- win32pipe.PIPE_ACCESS_DUPLEX,- win32pipe.PIPE_TYPE_BYTE | win32pipe.PIPE_READMODE_BYTE | win32pipe.PIPE_WAIT,- 1, # Max instances- 65536, # Out buffer size- 65536, # In buffer size- 0, # Default timeout- None # Security attributes- )-- print(f"[Worker {self.worker_id}] Named pipe created, waiting for connection...", file=sys.stderr, flush=True)-- # Wait for client (Rust) to connect- win32pipe.ConnectNamedPipe(self.server_socket, None)- self.client_socket = self.server_socket # Use same handle for read/write-- print(f"[Worker {self.worker_id}] Client connected to named pipe", file=sys.stderr, flush=True)-- except pywintypes.error as e:- print(f"[Worker {self.worker_id}] Named pipe error: {e}, falling back to TCP", file=sys.stderr, flush=True)- self._start_tcp_server()-- def _start_unix_socket_server(self):- """Create Unix domain socket server"""- # Determine socket path- if self.socket_name.startswith('/'):- sock_path = self.socket_name- else:- sock_path = f"/tmp/{self.socket_name}"-- # Remove existing socket file if present- try:- os.unlink(sock_path)- except FileNotFoundError:- pass-- print(f"[Worker {self.worker_id}] Creating Unix socket: {sock_path}", file=sys.stderr, flush=True)-- self.server_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)- self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)- self.server_socket.bind(sock_path)- self.server_socket.listen(1)-- print(f"[Worker {self.worker_id}] Listening for connection...", file=sys.stderr, flush=True)-- # Accept one connection from Rust- self.client_socket, addr = self.server_socket.accept()- print(f"[Worker {self.worker_id}] Client connected", file=sys.stderr, flush=True)-- def _start_tcp_server(self):- """Fallback TCP server on localhost (cross-platform)"""- # Use port based on worker ID to avoid conflicts- base_port = 19876- port = base_port + int(self.socket_name.split('-')[-1]) if '-' in self.socket_name else base_port-- print(f"[Worker {self.worker_id}] Creating TCP socket on port {port}", file=sys.stderr, flush=True)-- self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)- self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)- self.server_socket.bind(('127.0.0.1', port))- self.server_socket.listen(1)-- # Write port to a temp file so Rust can find it- port_file = Path(os.environ.get('TEMP', '/tmp')) / f"{self.socket_name}.port"- port_file.write_text(str(port))- print(f"[Worker {self.worker_id}] Port file: {port_file}", file=sys.stderr, flush=True)-- print(f"[Worker {self.worker_id}] Listening on TCP port {port}...", file=sys.stderr, flush=True)-- # Accept one connection from Rust- self.client_socket, addr = self.server_socket.accept()- print(f"[Worker {self.worker_id}] Client connected from {addr}", file=sys.stderr, flush=True)-- def read_message(self):- """Read a MessagePack/JSON message from socket"""- try:- if sys.platform == 'win32' and hasattr(self, 'using_pipe') and self.using_pipe:- import win32file- # Read length (4 bytes)- _, len_bytes = win32file.ReadFile(self.client_socket, 4)- if len(len_bytes) < 4:- return None- msg_len = struct.unpack('<I', len_bytes)[0]-- # Read message- _, msg_bytes = win32file.ReadFile(self.client_socket, msg_len)- else:- # TCP or Unix socket- len_bytes = self._recv_exact(4)- if not len_bytes or len(len_bytes) < 4:- return None-- msg_len = struct.unpack('<I', len_bytes)[0]- msg_bytes = self._recv_exact(msg_len)- if not msg_bytes:- return None-- if USE_MSGPACK:- return msgpack.unpackb(msg_bytes, raw=False)- else:- return json.loads(msg_bytes.decode('utf-8'))-- except Exception as e:- print(f"[Worker {self.worker_id}] Error reading message: {e}", file=sys.stderr, flush=True)- return None-- def _recv_exact(self, n):- """Receive exactly n bytes from socket"""- data = b''- while len(data) < n:- chunk = self.client_socket.recv(n - len(data))- if not chunk:- return None- data += chunk- return data-- def send_message(self, message):- """Send a MessagePack/JSON message to socket"""- with self.send_lock:- try:- if USE_MSGPACK:- msg_bytes = msgpack.packb(message, use_bin_type=True)- else:- msg_bytes = json.dumps(message).encode('utf-8')-- len_bytes = struct.pack('<I', len(msg_bytes))-- if sys.platform == 'win32' and hasattr(self, 'using_pipe') and self.using_pipe:- import win32file- win32file.WriteFile(self.client_socket, len_bytes + msg_bytes)- else:- self.client_socket.sendall(len_bytes + msg_bytes)-- except Exception as e:- print(f"[Worker {self.worker_id}] Error sending message: {e}", file=sys.stderr, flush=True)-- def execute_script(self, task):- """Execute a Python script and return the result"""- try:- script_path = task['script_path']- args = task.get('args', [])- task_id = task['task_id']-- print(f"[Worker {self.worker_id}] Executing: {script_path}", file=sys.stderr, flush=True)-- # Check if script exists- if not os.path.exists(script_path):- return {- 'task_id': task_id,- 'status': 'error',- 'data': f'Script not found: {script_path}'- }-- # Load script as module- spec = importlib.util.spec_from_file_location("dynamic_script", script_path)- module = importlib.util.module_from_spec(spec)-- # Add script directory to sys.path- script_dir = os.path.dirname(script_path)- if script_dir not in sys.path:- sys.path.insert(0, script_dir)-- # Execute script- spec.loader.exec_module(module)-- # Check for main() function- if hasattr(module, 'main'):- result = module.main(args)-- # If result is already JSON string, use it directly- if isinstance(result, str):- result_data = result- else:- result_data = json.dumps(result)-- return {- 'task_id': task_id,- 'status': 'success',- 'data': result_data- }- else:- return {- 'task_id': task_id,- 'status': 'error',- 'data': f'Script {script_path} must have a main() function'- }-- except Exception as e:- error_msg = f"Error executing script: {str(e)}\n{traceback.format_exc()}"- print(f"[Worker {self.worker_id}] ERROR: {error_msg}", file=sys.stderr, flush=True)-- return {- 'task_id': task.get('task_id', 'unknown'),- 'status': 'error',- 'data': error_msg- }-- def handle_task_completion(self, future):- """Callback when a task completes - sends response back"""- try:- response = future.result()- self.send_message(response)- print(f"[Worker {self.worker_id}] Task {response['task_id']} completed", file=sys.stderr, flush=True)- except Exception as e:- print(f"[Worker {self.worker_id}] ERROR sending response: {e}", file=sys.stderr, flush=True)- traceback.print_exc()-- def run(self):- """Main worker loop - handles multiple concurrent requests via thread pool"""- try:- # Start server and wait for Rust to connect- self.start_server()-- print(f"[Worker {self.worker_id}] Ready to accept tasks (thread pool with {self.num_threads} threads)", file=sys.stderr, flush=True)-- while self.running:- # Read next task from socket- task = self.read_message()- if task is None:- print(f"[Worker {self.worker_id}] Connection closed", file=sys.stderr, flush=True)- break-- print(f"[Worker {self.worker_id}] Received task: {task.get('task_id', 'unknown')}", file=sys.stderr, flush=True)-- # Submit task to thread pool- future = self.executor.submit(self.execute_script, task)- future.add_done_callback(self.handle_task_completion)-- except KeyboardInterrupt:- print(f"[Worker {self.worker_id}] Shutting down...", file=sys.stderr, flush=True)- except Exception as e:- print(f"[Worker {self.worker_id}] FATAL ERROR: {e}", file=sys.stderr, flush=True)- traceback.print_exc()- finally:- self.shutdown()-- def shutdown(self):- """Clean up resources"""- self.running = False- self.executor.shutdown(wait=False)-- if self.client_socket:- try:- if sys.platform == 'win32' and hasattr(self, 'using_pipe') and self.using_pipe:- import win32file- win32file.CloseHandle(self.client_socket)- else:- self.client_socket.close()- except:- pass-- if self.server_socket and self.server_socket != self.client_socket:- try:- self.server_socket.close()- except:- pass-- print(f"[Worker {self.worker_id}] Shutdown complete", file=sys.stderr, flush=True)---def main():- if len(sys.argv) < 3:- print("Usage: worker.py <socket_name> <worker_id> [num_threads]", file=sys.stderr)- sys.exit(1)-- socket_name = sys.argv[1]- worker_id = int(sys.argv[2])- num_threads = int(sys.argv[3]) if len(sys.argv) > 3 else 4-- worker = PythonWorker(socket_name, worker_id, num_threads)- worker.run()---if __name__ == "__main__":- main()diff --git a/fincept-terminal-desktop/src-tauri/src/commands/agents.rs b/fincept-terminal-desktop/src-tauri/src/commands/agents.rsindex b72841a2d..0959c9372 100644--- a/fincept-terminal-desktop/src-tauri/src/commands/agents.rs+++ b/fincept-terminal-desktop/src-tauri/src/commands/agents.rs@@ -99,19 +99,43 @@ async fn execute_core_agent_with_timeout(.and_then(|c| c.get("model")).map(|m| m.to_string()).unwrap_or_else(|| "no model config".to_string());- eprintln!("[AgentCmd] action={}, model_config={}, payload_len={}", action, model_info, payload_str.len());++ // Log API keys presence (not values for security)+ let api_keys_info = payload.get("api_keys")+ .and_then(|k| k.as_object())+ .map(|obj| {+ let keys: Vec<String> = obj.keys().map(|k| k.clone()).collect();+ format!("keys={:?}", keys)+ })+ .unwrap_or_else(|| "no api_keys".to_string());++ eprintln!("[AgentCmd] action={}, model_config={}, payload_len={}, {}",+ action, model_info, payload_str.len(), api_keys_info);++ // Log first 1000 chars of payload for debugging+ let payload_preview: String = payload_str.chars().take(1000).collect();+ eprintln!("[AgentCmd] Payload preview: {}", payload_preview);let app_clone = app.clone();- let args: Vec<String> = vec![payload_str];+ let args: Vec<String> = vec![payload_str.clone()];++ eprintln!("[AgentCmd] Starting Python execution with timeout={}s...", timeout_secs);+ let start_time = std::time::Instant::now();// Execute Python subprocess in a blocking task with timeoutlet result = timeout(Duration::from_secs(timeout_secs),tokio::task::spawn_blocking(move || {- python::execute_sync(&app_clone, "agents/finagent_core/main.py", args)+ eprintln!("[AgentCmd] Inside blocking task, calling python::execute_sync...");+ let exec_result = python::execute_sync(&app_clone, "agents/finagent_core/main.py", args);+ eprintln!("[AgentCmd] python::execute_sync returned");+ exec_result})).await;+ let elapsed = start_time.elapsed();+ eprintln!("[AgentCmd] Python execution completed in {:.2}s", elapsed.as_secs_f64());+match &result {Ok(Ok(Ok(ref output))) => {// Log first 500 chars of successful output@@ -120,19 +144,25 @@ async fn execute_core_agent_with_timeout(}Ok(Ok(Err(ref e))) => {eprintln!("[AgentCmd] PYTHON ERROR: {}", e);+ eprintln!("[AgentCmd] This likely means the Python script failed to execute or returned an error.");}Ok(Err(ref e)) => {- eprintln!("[AgentCmd] TASK ERROR: {}", e);+ eprintln!("[AgentCmd] TASK ERROR (tokio spawn_blocking failed): {}", e);}Err(_) => {- eprintln!("[AgentCmd] TIMEOUT after {}s", timeout_secs);+ eprintln!("[AgentCmd] TIMEOUT after {}s - Python script did not complete in time", timeout_secs);+ eprintln!("[AgentCmd] This could mean:");+ eprintln!("[AgentCmd] 1. Python script is hanging/waiting for response");+ eprintln!("[AgentCmd] 2. API call to LLM provider is taking too long");+ eprintln!("[AgentCmd] 3. Network issues preventing API access");+ eprintln!("[AgentCmd] 4. API key is invalid or missing");}}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)),+ Err(_) => Err(format!("Operation timed out after {} seconds. Check if API key is configured and LLM endpoint is accessible.", timeout_secs)),}}diff --git a/fincept-terminal-desktop/src-tauri/src/commands/alpha_arena_v2.rs b/fincept-terminal-desktop/src-tauri/src/commands/alpha_arena_v2.rsdeleted file mode 100644index bfcca869b..000000000--- a/fincept-terminal-desktop/src-tauri/src/commands/alpha_arena_v2.rs+++ /dev/null@@ -1,135 +0,0 @@-//! Alpha Arena V2 Commands-//!-//! Tauri commands for the refactored Alpha Arena system.-//! Refactored to use unified python module API.--use tauri::AppHandle;-use crate::python;--/// Extract the last valid JSON object from output that may contain log lines-fn extract_json(output: &str) -> Option<String> {- let mut brace_count: i32 = 0;- let mut json_start: Option<usize> = None;- let mut last_valid_json: Option<String> = None;-- let chars: Vec<char> = output.chars().collect();-- for (i, ch) in chars.iter().enumerate() {- match ch {- '{' => {- if brace_count == 0 {- json_start = Some(i);- }- brace_count += 1;- }- '}' => {- if brace_count > 0 {- brace_count -= 1;- if brace_count == 0 {- if let Some(start) = json_start {- let candidate: String = chars[start..=i].iter().collect();- if serde_json::from_str::<serde_json::Value>(&candidate).is_ok() {- last_valid_json = Some(candidate);- }- json_start = None;- }- }- }- }- _ => {}- }- }-- last_valid_json-}--/// Execute an Alpha Arena action-///-/// Takes a JSON payload with:-/// - action: The action to perform-/// - api_keys: Dict of provider API keys-/// - params: Action-specific parameters-#[tauri::command]-pub async fn alpha_arena_action(- app: AppHandle,- payload: String,-) -> Result<String, String> {- // Use the unified python module API- let output = python::execute_sync(&app, "alpha_arena/main.py", vec![payload])?;-- // Find JSON in output- extract_json(&output)- .ok_or_else(|| "No JSON output from Python script".to_string())-}--/// Get API keys from database-#[tauri::command]-pub async fn get_api_keys(app: AppHandle) -> Result<String, String> {- use crate::commands::db_commands::get_db_path;-- let db_path = get_db_path(&app).map_err(|e| e.to_string())?;-- let conn = rusqlite::Connection::open(&db_path)- .map_err(|e| format!("Failed to open database: {}", e))?;-- // Create table if not exists- conn.execute(- "CREATE TABLE IF NOT EXISTS api_keys (- provider TEXT PRIMARY KEY,- api_key TEXT NOT NULL- )",- [],- )- .map_err(|e| format!("Failed to create table: {}", e))?;-- // Fetch all keys- let mut stmt = conn- .prepare("SELECT provider, api_key FROM api_keys")- .map_err(|e| format!("Failed to prepare statement: {}", e))?;-- let keys: std::collections::HashMap<String, String> = stmt- .query_map([], |row| {- Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))- })- .map_err(|e| format!("Failed to query: {}", e))?- .filter_map(|r| r.ok())- .collect();-- serde_json::to_string(&keys).map_err(|e| format!("Failed to serialize: {}", e))-}--/// Save API keys to database-#[tauri::command]-pub async fn save_api_keys(app: AppHandle, keys: String) -> Result<(), String> {- use crate::commands::db_commands::get_db_path;-- let db_path = get_db_path(&app).map_err(|e| e.to_string())?;-- let conn = rusqlite::Connection::open(&db_path)- .map_err(|e| format!("Failed to open database: {}", e))?;-- // Create table if not exists- conn.execute(- "CREATE TABLE IF NOT EXISTS api_keys (- provider TEXT PRIMARY KEY,- api_key TEXT NOT NULL- )",- [],- )- .map_err(|e| format!("Failed to create table: {}", e))?;-- // Parse keys- let keys_map: std::collections::HashMap<String, String> =- serde_json::from_str(&keys).map_err(|e| format!("Failed to parse keys: {}", e))?;-- // Insert/update each key- for (provider, api_key) in keys_map {- conn.execute(- "INSERT OR REPLACE INTO api_keys (provider, api_key) VALUES (?1, ?2)",- [&provider, &api_key],- )- .map_err(|e| format!("Failed to insert key: {}", e))?;- }-- Ok(())-}diff --git a/fincept-terminal-desktop/src-tauri/src/commands/brokers/common_commands.rs b/fincept-terminal-desktop/src-tauri/src/commands/brokers/common_commands.rsindex c5d6cda92..a90fe9835 100644--- a/fincept-terminal-desktop/src-tauri/src/commands/brokers/common_commands.rs+++ b/fincept-terminal-desktop/src-tauri/src/commands/brokers/common_commands.rs@@ -148,7 +148,7 @@ pub async fn get_indian_broker_credentials(})}Err(e) => {- eprintln!("[get_indian_broker_credentials] ❌ Error: {}", e);+ eprintln!("[get_indian_broker_credentials] Error: {}", e);Ok(ApiResponse {success: false,data: None,diff --git a/fincept-terminal-desktop/src-tauri/src/commands/brokers/fyers.rs b/fincept-terminal-desktop/src-tauri/src/commands/brokers/fyers.rsindex ee100e41f..410080314 100644--- a/fincept-terminal-desktop/src-tauri/src/commands/brokers/fyers.rs+++ b/fincept-terminal-desktop/src-tauri/src/commands/brokers/fyers.rs@@ -682,7 +682,7 @@ pub async fn fyers_get_history(.send().await.map_err(|e| {- eprintln!("[fyers_get_history] ❌ Request failed: {}", e);+ eprintln!("[fyers_get_history] Request failed: {}", e);format!("Request failed: {}", e)})?;@@ -693,7 +693,7 @@ pub async fn fyers_get_history(eprintln!("[fyers_get_history] Response body length: {}", text.len());if text.is_empty() {- eprintln!("[fyers_get_history] ❌ Empty response from Fyers API");+ eprintln!("[fyers_get_history] Empty response from Fyers API");return Ok(ApiResponse {success: false,data: None,@@ -705,7 +705,7 @@ pub async fn fyers_get_history(eprintln!("[fyers_get_history] Response body preview: {}...", &text[..text.len().min(200)]);let body: Value = serde_json::from_str(&text).map_err(|e| {- eprintln!("[fyers_get_history] ❌ Parse error. Response was: {}", text);+ eprintln!("[fyers_get_history] Parse error. Response was: {}", text);format!("Failed to parse response: {}. Response: {}", e, text)})?;diff --git a/fincept-terminal-desktop/src-tauri/src/commands/databento.rs b/fincept-terminal-desktop/src-tauri/src/commands/databento.rsindex b266422a3..6037e3095 100644--- a/fincept-terminal-desktop/src-tauri/src/commands/databento.rs+++ b/fincept-terminal-desktop/src-tauri/src/commands/databento.rs@@ -459,11 +459,12 @@ pub async fn databento_live_start("snapshot": snapshot.unwrap_or(false)});- // Get Python path from resources- let python_path = app.path().resolve("resources/python/python.exe", tauri::path::BaseDirectory::Resource)+ // Get Python path (use the python module's resolver)+ let python_path = crate::python::get_python_path(&app, None).map_err(|e| format!("Failed to resolve Python path: {}", e))?;- let script_path = app.path().resolve("resources/scripts/databento_live.py", tauri::path::BaseDirectory::Resource)+ // Get script path (tauri.conf.json maps resources/scripts -> scripts)+ let script_path = app.path().resolve("scripts/databento_live.py", tauri::path::BaseDirectory::Resource).map_err(|e| format!("Failed to resolve script path: {}", e))?;// Spawn the live streaming processdiff --git a/fincept-terminal-desktop/src-tauri/src/commands/gluonts.rs b/fincept-terminal-desktop/src-tauri/src/commands/gluonts.rsindex d0e395556..9e502deb8 100644--- a/fincept-terminal-desktop/src-tauri/src/commands/gluonts.rs+++ b/fincept-terminal-desktop/src-tauri/src/commands/gluonts.rs@@ -1,14 +1,14 @@use crate::python;use tauri::command;-/// Helper to execute a GluonTS operation via worker_handler.py+/// Helper to execute a GluonTS operation via gluonts_service.pyfn execute_gluonts(app: &tauri::AppHandle,operation: &str,data: serde_json::Value,) -> Result<String, String> {let args = vec![operation.to_string(), data.to_string()];- python::execute_sync(app, "Analytics/gluonts_wrapper/worker_handler.py", args)+ python::execute_sync(app, "Analytics/gluonts_wrapper/gluonts_service.py", args)}// ==================== DEEP LEARNING FORECASTERS ====================diff --git a/fincept-terminal-desktop/src-tauri/src/commands/gs_quant.rs b/fincept-terminal-desktop/src-tauri/src/commands/gs_quant.rsindex c578e09d2..91c3ab22b 100644--- a/fincept-terminal-desktop/src-tauri/src/commands/gs_quant.rs+++ b/fincept-terminal-desktop/src-tauri/src/commands/gs_quant.rs@@ -1,14 +1,14 @@// GS-Quant Wrapper Commands - Goldman Sachs quant analytics via subprocessuse crate::python;-/// Helper to execute a gs_quant_wrapper operation via worker_handler.py+/// Helper to execute a gs_quant_wrapper operation via descriptive_service.pyfn execute_gs_quant(app: &tauri::AppHandle,operation: &str,data: serde_json::Value,) -> Result<String, String> {let args = vec![operation.to_string(), data.to_string()];- python::execute_sync(app, "Analytics/gs_quant_wrapper/worker_handler.py", args)+ python::execute_sync(app, "Analytics/gs_quant_wrapper/gs_quant_service.py", args)}// ============================================================================diff --git a/fincept-terminal-desktop/src-tauri/src/commands/pypme.rs b/fincept-terminal-desktop/src-tauri/src/commands/pypme.rsindex 21051debc..002cd4058 100644--- a/fincept-terminal-desktop/src-tauri/src/commands/pypme.rs+++ b/fincept-terminal-desktop/src-tauri/src/commands/pypme.rs@@ -1,14 +1,14 @@use crate::python;use tauri::command;-/// Helper to execute a PyPME operation via worker_handler.py+/// Helper to execute a PyPME operation via descriptive_service.pyfn execute_pypme(app: &tauri::AppHandle,operation: &str,data: serde_json::Value,) -> Result<String, String> {let args = vec![operation.to_string(), data.to_string()];- python::execute_sync(app, "Analytics/pypme_wrapper/worker_handler.py", args)+ python::execute_sync(app, "Analytics/pypme_wrapper/pypme_service.py", args)}// ==================== BASIC PME ====================diff --git a/fincept-terminal-desktop/src-tauri/src/commands/pyportfolioopt.rs b/fincept-terminal-desktop/src-tauri/src/commands/pyportfolioopt.rsindex 7fa563039..d37ea985f 100644--- a/fincept-terminal-desktop/src-tauri/src/commands/pyportfolioopt.rs+++ b/fincept-terminal-desktop/src-tauri/src/commands/pyportfolioopt.rs@@ -130,7 +130,7 @@ async fn execute_pyportfolioopt_operation(let args = vec![operation.to_string(), data_json];- crate::python::execute(&app, "Analytics/pyportfolioopt_wrapper/worker_handler.py", args).await+ crate::python::execute(&app, "Analytics/pyportfolioopt_wrapper/pyportfolioopt_service.py", args).await}/// Optimize portfolio using PyPortfolioOptdiff --git a/fincept-terminal-desktop/src-tauri/src/commands/skfolio.rs b/fincept-terminal-desktop/src-tauri/src/commands/skfolio.rsindex 4a90b41da..dd95f168d 100644--- a/fincept-terminal-desktop/src-tauri/src/commands/skfolio.rs+++ b/fincept-terminal-desktop/src-tauri/src/commands/skfolio.rs@@ -1,16 +1,16 @@// skfolio Portfolio Optimization Commands-// Uses python_skfolio_lib/worker_handler.py with operation + JSON dispatch+// Uses python_skfolio_lib/skfolio_descriptive_service.py with operation + JSON dispatchuse crate::python;use tauri::command;-/// Helper to execute a skfolio operation via worker_handler.py+/// Helper to execute a skfolio operation via descriptive_service.pyfn execute_skfolio_op(app: &tauri::AppHandle,operation: &str,data: serde_json::Value,) -> Result<String, String> {let args = vec![operation.to_string(), data.to_string()];- python::execute_sync(app, "Analytics/python_skfolio_lib/worker_handler.py", args)+ python::execute_sync(app, "Analytics/python_skfolio_lib/skfolio_service.py", args)}// ==================== PORTFOLIO OPTIMIZATION ====================diff --git a/fincept-terminal-desktop/src-tauri/src/commands/talipp.rs b/fincept-terminal-desktop/src-tauri/src/commands/talipp.rsindex 795584162..8e7318af4 100644--- a/fincept-terminal-desktop/src-tauri/src/commands/talipp.rs+++ b/fincept-terminal-desktop/src-tauri/src/commands/talipp.rs@@ -1,14 +1,14 @@use crate::python;use tauri::command;-/// Helper to execute a TALIpp indicator calculation via worker_handler.py+/// Helper to execute a TALIpp indicator calculation via descriptive_service.pyfn execute_talipp(app: &tauri::AppHandle,operation: &str,data: serde_json::Value,) -> Result<String, String> {let args = vec![operation.to_string(), data.to_string()];- python::execute_sync(app, "Analytics/talipp_wrapper/worker_handler.py", args)+ python::execute_sync(app, "Analytics/talipp_wrapper/talipp_service.py", args)}// ==================== TREND INDICATORS ====================diff --git a/fincept-terminal-desktop/src-tauri/src/commands/vollib.rs b/fincept-terminal-desktop/src-tauri/src/commands/vollib.rsindex fb898a90a..0e10446cd 100644--- a/fincept-terminal-desktop/src-tauri/src/commands/vollib.rs+++ b/fincept-terminal-desktop/src-tauri/src/commands/vollib.rs@@ -1,14 +1,14 @@use crate::python;use tauri::command;-/// Helper to execute a py_vollib operation via worker_handler.py+/// Helper to execute a py_vollib operation via descriptive_service.pyfn execute_vollib(app: &tauri::AppHandle,operation: &str,data: serde_json::Value,) -> Result<String, String> {let args = vec![operation.to_string(), data.to_string()];- python::execute_sync(app, "Analytics/py_vollib_wrapper/worker_handler.py", args)+ python::execute_sync(app, "Analytics/py_vollib_wrapper/vollib_service.py", args)}// ==================== BLACK MODEL (futures/forwards) ====================diff --git a/fincept-terminal-desktop/src-tauri/src/lib.rs b/fincept-terminal-desktop/src-tauri/src/lib.rsindex b24fb6b70..1285b109e 100644--- a/fincept-terminal-desktop/src-tauri/src/lib.rs+++ b/fincept-terminal-desktop/src-tauri/src/lib.rs@@ -609,8 +609,7 @@ use std::os::windows::process::CommandExt;#[cfg(target_os = "windows")]const CREATE_NO_WINDOW: u32 = 0x08000000;-// Execute Python script via worker pool (persistent processes, no subprocess spawn per call)-// Falls back to subprocess if worker pool is not initialized+// Execute Python script via subprocess#[tauri::command]async fn execute_python_script(app: tauri::AppHandle,diff --git a/fincept-terminal-desktop/src-tauri/src/python.rs b/fincept-terminal-desktop/src-tauri/src/python.rsindex d2e4018fc..6218d1f55 100644--- a/fincept-terminal-desktop/src-tauri/src/python.rs+++ b/fincept-terminal-desktop/src-tauri/src/python.rs@@ -97,26 +97,94 @@ fn resolve_python_path(app: &tauri::AppHandle, script: &str) -> Result<PathBuf,fn resolve_script_path(app: &tauri::AppHandle, script: &str) -> Result<PathBuf, String> {let mut candidates = Vec::new();+ // Tauri v2 preferred method: use resolve() with BaseDirectory::Resource+ // This handles all platform-specific path resolution automatically+ // tauri.conf.json maps "resources/scripts" -> "scripts", so path is just "scripts/{script}"+ let script_resource_path = format!("scripts/{}", script);+ match app.path().resolve(&script_resource_path, tauri::path::BaseDirectory::Resource) {+ Ok(resolved) => {+ // Clean up any "../" in the path (common on macOS)+ let cleaned = if resolved.to_string_lossy().contains("..") {+ match resolved.canonicalize() {+ Ok(canonical) => canonical,+ Err(_) => resolved.clone(),+ }+ } else {+ resolved.clone()+ };+ candidates.push(cleaned);+ }+ Err(_) => {+ // Silent fallback to other methods+ }+ }++ // Fallback: resource_dir() methodif let Ok(res) = app.path().resource_dir() {+ // Primary: scripts/{script} (after tauri.conf.json mapping)candidates.push(res.join("scripts").join(script));+ // Fallback: resources/scripts/{script} (legacy path, just in case)+ candidates.push(res.join("resources").join("scripts").join(script));+ // Direct path (unlikely but possible)+ candidates.push(res.join(script));}++ // Current executable location-based pathsif let Ok(exe) = std::env::current_exe() {if let Some(dir) = exe.parent() {candidates.push(dir.join("resources").join("scripts").join(script));candidates.push(dir.join("scripts").join(script));++ // macOS-specific: Contents/Resources/ relative to MacOS directory+ #[cfg(target_os = "macos")]+ {+ // exe is in Contents/MacOS/, so go up and into Resources/+ if let Some(contents_dir) = dir.parent() {+ let resources_dir = contents_dir.join("Resources");+ candidates.push(resources_dir.join("scripts").join(script));+ candidates.push(resources_dir.join(script));+ }+ }}}++ // Development: working directory based pathsif let Ok(cwd) = std::env::current_dir() {candidates.push(cwd.join("resources").join("scripts").join(script));candidates.push(cwd.join("src-tauri").join("resources").join("scripts").join(script));}+ // macOS-specific: Check app bundle structure using bundle identifier+ #[cfg(target_os = "macos")]+ {+ // Standard macOS app bundle locations+ let app_bundle_paths = [+ "/Applications/FinceptTerminal.app/Contents/Resources/scripts",+ ];+ for base in &app_bundle_paths {+ candidates.push(PathBuf::from(base).join(script));+ }++ // Check home directory Applications folder+ if let Ok(home) = std::env::var("HOME") {+ candidates.push(PathBuf::from(&home)+ .join("Applications/FinceptTerminal.app/Contents/Resources/scripts")+ .join(script));+ }+ }+for p in &candidates {if p.exists() {return Ok(clean_path(p.clone()));}}+ // Only log on failure+ eprintln!("[Python] Script '{}' NOT FOUND. Searched paths:", script);+ for (i, p) in candidates.iter().enumerate() {+ eprintln!("[Python] {}: {:?}", i, p);+ }+Err(format!("Script '{}' not found. Searched: {}",script,@@ -162,13 +230,15 @@ fn run_subprocess(data_dir: Option<&PathBuf>,) -> Result<String, String> {let mut cmd = Command::new(python);+ // -u flag: unbuffered output (so we see prints immediately)// -B flag: don't write .pyc files AND ignore existing __pycache__- cmd.arg("-B").arg(script).args(args)+ cmd.arg("-u").arg("-B").arg(script).args(args).stdout(Stdio::piped()).stderr(Stdio::piped());// Also set env var as belt-and-suspenderscmd.env("PYTHONDONTWRITEBYTECODE", "1");+ cmd.env("PYTHONUNBUFFERED", "1");// Set FINCEPT_DATA_DIR environment variable for Python scriptsif let Some(dir) = data_dir {diff --git a/fincept-terminal-desktop/src-tauri/src/setup.rs b/fincept-terminal-desktop/src-tauri/src/setup.rsindex 280dba608..a50c9537d 100644--- a/fincept-terminal-desktop/src-tauri/src/setup.rs+++ b/fincept-terminal-desktop/src-tauri/src/setup.rs@@ -322,18 +322,45 @@ async fn install_python(app: &AppHandle, install_dir: &PathBuf) -> Result<(), St}// Enable pip by modifying python312._pth (Windows only)+ // The embeddable Python has import site commented out by default, which prevents pip from working#[cfg(target_os = "windows")]{let pth_file = python_dir.join("python312._pth");+ eprintln!("[SETUP] Checking ._pth file at: {:?}", pth_file);+if pth_file.exists() {if let Ok(content) = std::fs::read_to_string(&pth_file) {+ eprintln!("[SETUP] Original ._pth content:\n{}", content);++ // Enable import site (required for pip to work)let new_content = content.replace("#import site", "import site");- let _ = std::fs::write(&pth_file, new_content);++ // Also add Lib/site-packages to the path if not present+ let new_content = if !new_content.contains("Lib/site-packages") && !new_content.contains("Lib\\site-packages") {+ format!("{}\nLib/site-packages\n", new_content.trim_end())+ } else {+ new_content+ };++ eprintln!("[SETUP] New ._pth content:\n{}", new_content);++ std::fs::write(&pth_file, &new_content)+ .map_err(|e| format!("Failed to write ._pth file: {}", e))?;}} else {// Create _pth file if it doesn't exist- let pth_content = "python312.zip\n.\n\nimport site\n";- let _ = std::fs::write(&pth_file, pth_content);+ eprintln!("[SETUP] Creating new ._pth file");+ let pth_content = "python312.zip\n.\nLib/site-packages\n\nimport site\n";+ std::fs::write(&pth_file, pth_content)+ .map_err(|e| format!("Failed to create ._pth file: {}", e))?;+ }++ // Also create Lib/site-packages directory if it doesn't exist+ let site_packages = python_dir.join("Lib").join("site-packages");+ if !site_packages.exists() {+ std::fs::create_dir_all(&site_packages)+ .map_err(|e| format!("Failed to create site-packages directory: {}", e))?;+ eprintln!("[SETUP] Created site-packages directory: {:?}", site_packages);}}@@ -349,17 +376,43 @@ async fn install_python(app: &AppHandle, install_dir: &PathBuf) -> Result<(), Stlet mut cmd = Command::new("powershell");cmd.args(&["-Command",- &format!("Invoke-WebRequest -Uri '{}' -OutFile '{}'", get_pip_url, get_pip_path.display())+ &format!(+ "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; Invoke-WebRequest -Uri '{}' -OutFile '{}'",+ get_pip_url, get_pip_path.display()+ )]);cmd.creation_flags(CREATE_NO_WINDOW);- cmd.output().map_err(|e| format!("Failed to download get-pip.py: {}", e))?;+ let output = cmd.output().map_err(|e| format!("Failed to download get-pip.py: {}", e))?;++ if !output.status.success() {+ eprintln!("[SETUP] get-pip.py download failed: {}", String::from_utf8_lossy(&output.stderr));+ return Err(format!("Failed to download get-pip.py: {}", String::from_utf8_lossy(&output.stderr)));+ }}#[cfg(not(target_os = "windows"))]{let mut cmd = Command::new("curl");cmd.args(&["-L", "-o", get_pip_path.to_str().unwrap(), get_pip_url]);- cmd.output().map_err(|e| format!("Failed to download get-pip.py: {}", e))?;+ let output = cmd.output().map_err(|e| format!("Failed to download get-pip.py: {}", e))?;++ if !output.status.success() {+ return Err(format!("Failed to download get-pip.py: {}", String::from_utf8_lossy(&output.stderr)));+ }+ }++ // Verify get-pip.py was downloaded+ if !get_pip_path.exists() {+ return Err("get-pip.py download failed - file does not exist".to_string());+ }++ let file_size = std::fs::metadata(&get_pip_path)+ .map(|m| m.len())+ .unwrap_or(0);+ eprintln!("[SETUP] get-pip.py downloaded, size: {} bytes", file_size);++ if file_size < 1000 {+ return Err(format!("get-pip.py appears corrupted (size: {} bytes)", file_size));}// Install pip@@ -374,8 +427,12 @@ async fn install_python(app: &AppHandle, install_dir: &PathBuf) -> Result<(), Streturn Err(format!("Python executable not found at: {:?}", python_exe));}+ eprintln!("[SETUP] Running: {:?} {:?}", python_exe, get_pip_path);+let mut cmd = Command::new(&python_exe);cmd.arg(get_pip_path.to_str().unwrap());+ // Add --no-warn-script-location to suppress warnings+ cmd.arg("--no-warn-script-location");#[cfg(target_os = "windows")]cmd.creation_flags(CREATE_NO_WINDOW);@@ -391,6 +448,24 @@ async fn install_python(app: &AppHandle, install_dir: &PathBuf) -> Result<(), Stlet _ = std::fs::remove_file(&get_pip_path);+ // Verify pip was installed successfully+ emit_progress(app, "python", 90, "Verifying pip installation...", false);++ let mut verify_cmd = Command::new(&python_exe);+ verify_cmd.args(&["-m", "pip", "--version"]);++ #[cfg(target_os = "windows")]+ verify_cmd.creation_flags(CREATE_NO_WINDOW);++ let verify_output = verify_cmd.output().map_err(|e| format!("Failed to verify pip: {}", e))?;++ if !verify_output.status.success() {+ eprintln!("[SETUP] pip verification failed: {}", String::from_utf8_lossy(&verify_output.stderr));+ return Err("Pip installation verification failed - pip module not found".to_string());+ }++ eprintln!("[SETUP] pip verified: {}", String::from_utf8_lossy(&verify_output.stdout).trim());+emit_progress(app, "python", 100, "Python installed", false);Ok(())}@@ -567,8 +642,27 @@ async fn install_uv(app: &AppHandle, install_dir: &PathBuf) -> Result<(), Stringinstall_dir.join("python/bin/python3")};+ // First verify pip is available+ let mut verify_cmd = Command::new(&python_exe);+ verify_cmd.args(&["-m", "pip", "--version"]);++ #[cfg(target_os = "windows")]+ verify_cmd.creation_flags(CREATE_NO_WINDOW);++ eprintln!("[SETUP] Verifying pip before UV install...");+ let verify_output = verify_cmd.output().map_err(|e| format!("Failed to check pip: {}", e))?;++ if !verify_output.status.success() {+ let stderr = String::from_utf8_lossy(&verify_output.stderr);+ eprintln!("[SETUP] pip not available: {}", stderr);+ return Err(format!("UV installation failed: {}: No module named pip", python_exe.display()));+ }++ eprintln!("[SETUP] pip available: {}", String::from_utf8_lossy(&verify_output.stdout).trim());++ // Now install UVlet mut cmd = Command::new(&python_exe);- cmd.args(&["-m", "pip", "install", "uv"]);+ cmd.args(&["-m", "pip", "install", "--no-warn-script-location", "uv"]);#[cfg(target_os = "windows")]cmd.creation_flags(CREATE_NO_WINDOW);@@ -675,8 +769,9 @@ async fn install_packages_in_venv(let uv_exe = uv_candidates.iter().find(|p| p.exists());+ // tauri.conf.json maps resources/requirements-*.txt directly to requirements-*.txtlet requirements_path = app.path()- .resolve(&format!("resources/{}", requirements_file), tauri::path::BaseDirectory::Resource)+ .resolve(requirements_file, tauri::path::BaseDirectory::Resource).map_err(|e| format!("Failed to find {}: {}", requirements_file, e))?;emit_progress(app, "packages", 20, &format!("Installing {} packages with UV...", progress_label), false);@@ -720,9 +815,10 @@ async fn install_packages_in_venv(/// Compute SHA-256 hash of a bundled requirements filefn compute_requirements_hash(app: &AppHandle, requirements_file: &str) -> Result<String, String> {+ // tauri.conf.json maps resources/requirements-*.txt directly to requirements-*.txtlet requirements_path = app.path().resolve(- &format!("resources/{}", requirements_file),+ requirements_file,tauri::path::BaseDirectory::Resource,).map_err(|e| format!("Failed to resolve {}: {}", requirements_file, e))?;diff --git a/fincept-terminal-desktop/src-tauri/tauri.conf.json b/fincept-terminal-desktop/src-tauri/tauri.conf.jsonindex b087315f8..2c02b414e 100644--- a/fincept-terminal-desktop/src-tauri/tauri.conf.json+++ b/fincept-terminal-desktop/src-tauri/tauri.conf.json@@ -1,7 +1,7 @@{"$schema": "https://schema.tauri.app/config/2","productName": "FinceptTerminal",- "version": "3.3.0",+ "version": "3.3.1","identifier": "com.fincept.terminal","build": {"beforeDevCommand": "bun run dev",@@ -44,11 +44,11 @@"category": "Finance","shortDescription": "Professional-grade financial analysis platform with AI-powered insights","longDescription": "FinceptTerminal is an AI-Powered Finance Terminal For Investment Research. Access real-time market data, advanced analytics, and institutional-grade tools for informed investment decisions.",- "resources": [- "resources/scripts",- "resources/requirements-numpy1.txt",- "resources/requirements-numpy2.txt"- ],+ "resources": {+ "resources/scripts": "scripts",+ "resources/requirements-numpy1.txt": "requirements-numpy1.txt",+ "resources/requirements-numpy2.txt": "requirements-numpy2.txt"+ },"windows": {"digestAlgorithm": "sha256","timestampUrl": "http://timestamp.digicert.com",@@ -69,7 +69,7 @@"plugins": {"updater": {"endpoints": [- "https://github.com/Fincept-Corporation/FinceptTerminal/releases/latest/download/latest.json"+ "https://github.com/Fincept-Corporation/FinceptTerminal/releases/download/v3.3.0-rc.14/latest.json"],"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IERCRURCNzE2RUI4OTFDREUKUldUZUhJbnJGcmZ0MjFSQVhvYVR3eUFNYWZBK0t3cWtUTnUvc0hTM1BOVTgveENtMzBHZ3BRUFgK","windows": {diff --git a/fincept-terminal-desktop/src/components/command-bar/commandRegistry.ts b/fincept-terminal-desktop/src/components/command-bar/commandRegistry.tsindex eb1aba53f..6260114ba 100644--- a/fincept-terminal-desktop/src/components/command-bar/commandRegistry.ts+++ b/fincept-terminal-desktop/src/components/command-bar/commandRegistry.ts@@ -374,16 +374,6 @@ export const COMMANDS: Command[] = [keywords: ['settings', 'preferences', 'configuration', 'options']},- // Missing Tabs - Added- {- id: 'analytics',- name: 'Analytics',- description: 'Financial analytics and models',- aliases: ['analytics', 'analysis', 'models'],- category: 'data',- action: 'analytics',- keywords: ['analytics', 'analysis', 'financial', 'models', 'statistics']- },{id: 'akshare',name: 'AKShare Data',diff --git a/fincept-terminal-desktop/src/components/common/AutoUpdater.tsx b/fincept-terminal-desktop/src/components/common/AutoUpdater.tsxindex 2e0eff070..974f57bb6 100644--- a/fincept-terminal-desktop/src/components/common/AutoUpdater.tsx+++ b/fincept-terminal-desktop/src/components/common/AutoUpdater.tsx@@ -1,18 +1,23 @@import { useEffect, useState, useRef, useCallback } from 'react';import { check, Update } from '@tauri-apps/plugin-updater';import { relaunch } from '@tauri-apps/plugin-process';-import { Button } from '@/components/ui/button';-import {- Dialog,- DialogContent,- DialogDescription,- DialogFooter,- DialogHeader,- DialogTitle,-} from '@/components/ui/dialog';-import { Progress } from '@/components/ui/progress';-import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';-import { Download, RefreshCw, CheckCircle2, XCircle, Info } from 'lucide-react';+import { Download, RefreshCw, CheckCircle2, XCircle, Info, ArrowUpCircle, X } from 'lucide-react';++const FINCEPT = {+ ORANGE: '#FF8800',+ WHITE: '#FFFFFF',+ RED: '#FF3B3B',+ GREEN: '#00D66F',+ GRAY: '#787878',+ DARK_BG: '#000000',+ PANEL_BG: '#0F0F0F',+ HEADER_BG: '#1A1A1A',+ BORDER: '#2A2A2A',+ HOVER: '#1F1F1F',+ MUTED: '#4A4A4A',+ CYAN: '#00E5FF',+ YELLOW: '#FFD700',+};interface AutoUpdaterProps {checkOnMount?: boolean;@@ -33,7 +38,6 @@ export function AutoUpdater({ checkOnMount = true, checkIntervalMinutes = 30 }:const relaunchTimerRef = useRef<NodeJS.Timeout | undefined>(undefined);const checkForUpdates = useCallback(async (silent = false) => {- // Prevent duplicate checksif (checkingRef.current) {console.log('[AutoUpdater Component] Check already in progress, skipping');return;@@ -62,7 +66,6 @@ export function AutoUpdater({ checkOnMount = true, checkIntervalMinutes = 30 }:console.log('[AutoUpdater Component] No updates available');if (!silent) {- // Show a brief notification that app is up to datesetError('You are running the latest version!');setTimeout(() => setError(null), 3000);}@@ -71,7 +74,6 @@ export function AutoUpdater({ checkOnMount = true, checkIntervalMinutes = 30 }:const errorMessage = err instanceof Error ? err.message : 'Unknown error occurred';console.error('[AutoUpdater Component] Error checking for updates:', errorMessage, err);- // Silently fail for development/network errorsif (!silent) {if (!errorMessage.toLowerCase().includes('network') &&!errorMessage.toLowerCase().includes('fetch') &&@@ -97,7 +99,6 @@ export function AutoUpdater({ checkOnMount = true, checkIntervalMinutes = 30 }:console.log('[AutoUpdater Component] Starting download and installation...');- // Download and install with progress trackinglet totalBytes = 0;let downloadedBytes = 0;@@ -124,12 +125,10 @@ export function AutoUpdater({ checkOnMount = true, checkIntervalMinutes = 30 }:console.log('[AutoUpdater Component] Update installed successfully! Preparing to relaunch...');setUpdateReady(true);- // Clear any existing relaunch timerif (relaunchTimerRef.current) {clearTimeout(relaunchTimerRef.current);}- // Auto-relaunch after 2 secondsrelaunchTimerRef.current = setTimeout(async () => {console.log('[AutoUpdater Component] Relaunching application...');await relaunch();@@ -148,15 +147,13 @@ export function AutoUpdater({ checkOnMount = true, checkIntervalMinutes = 30 }:console.log('[AutoUpdater Component] Update postponed by user');}, []);- // Check for updates on mountuseEffect(() => {if (checkOnMount) {console.log('[AutoUpdater Component] Initialized');- // Delay initial check by 15 seconds to not interfere with app startupconst timer = setTimeout(() => {console.log('[AutoUpdater Component] Running initial update check...');checkForUpdates(true);- }, 15000); // Increased to 15s to avoid conflict with hook+ }, 15000);return () => {clearTimeout(timer);@@ -167,7 +164,6 @@ export function AutoUpdater({ checkOnMount = true, checkIntervalMinutes = 30 }:}}, [checkOnMount, checkForUpdates]);- // Set up periodic update checksuseEffect(() => {if (checkIntervalMinutes > 0) {const interval = setInterval(() => {@@ -179,129 +175,469 @@ export function AutoUpdater({ checkOnMount = true, checkIntervalMinutes = 30 }:}}, [checkIntervalMinutes, checkForUpdates]);+ const formatBytes = (bytes: number) => {+ if (bytes === 0) return '0 B';+ const k = 1024;+ const sizes = ['B', 'KB', 'MB', 'GB'];+ const i = Math.floor(Math.log(bytes) / Math.log(k));+ return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];+ };+return (<>- {/* Update Dialog */}- <Dialog open={showDialog} onOpenChange={setShowDialog}>- <DialogContent className="sm:max-w-[500px]">- <DialogHeader>- <DialogTitle className="flex items-center gap-2">- <Download className="h-5 w-5" />- Update Available- </DialogTitle>- <DialogDescription>- A new version of FinceptTerminal is available.- </DialogDescription>- </DialogHeader>-- <div className="space-y-4 py-4">- {updateInfo && (- <div className="space-y-2">- <div className="flex justify-between text-sm">- <span className="text-muted-foreground">Current Version:</span>- <span className="font-mono">{updateInfo.currentVersion}</span>+ {/* Update Dialog - Overlay */}+ {showDialog && (+ <div style={{+ position: 'fixed',+ top: 0,+ left: 0,+ right: 0,+ bottom: 0,+ backgroundColor: 'rgba(0, 0, 0, 0.8)',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ zIndex: 9999,+ }}>+ <div style={{+ width: '460px',+ backgroundColor: FINCEPT.PANEL_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ overflow: 'hidden',+ boxShadow: `0 4px 24px rgba(0, 0, 0, 0.6), 0 0 1px ${FINCEPT.ORANGE}40`,+ }}>+ {/* Header */}+ <div style={{+ padding: '12px 16px',+ backgroundColor: FINCEPT.HEADER_BG,+ borderBottom: `2px solid ${FINCEPT.ORANGE}`,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <ArrowUpCircle size={14} color={FINCEPT.ORANGE} />+ <span style={{+ fontSize: '11px',+ fontWeight: 700,+ color: FINCEPT.WHITE,+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',+ letterSpacing: '0.5px',+ }}>+ UPDATE AVAILABLE+ </span>+ </div>+ {!downloading && !updateReady && (+ <button+ onClick={handleLater}+ style={{+ background: 'none',+ border: 'none',+ cursor: 'pointer',+ padding: '2px',+ display: 'flex',+ alignItems: 'center',+ }}+ >+ <X size={14} color={FINCEPT.GRAY} />+ </button>+ )}+ </div>++ {/* Body */}+ <div style={{ padding: '16px' }}>+ {/* Version Info */}+ {updateInfo && (+ <div style={{+ backgroundColor: FINCEPT.DARK_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ padding: '12px',+ marginBottom: '12px',+ }}>+ <div style={{+ display: 'flex',+ justifyContent: 'space-between',+ alignItems: 'center',+ marginBottom: '8px',+ }}>+ <span style={{+ fontSize: '9px',+ fontWeight: 700,+ color: FINCEPT.GRAY,+ letterSpacing: '0.5px',+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',+ }}>+ CURRENT VERSION+ </span>+ <span style={{+ fontSize: '10px',+ color: FINCEPT.MUTED,+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',+ }}>+ v{updateInfo.currentVersion}+ </span>+ </div>+ <div style={{+ display: 'flex',+ justifyContent: 'space-between',+ alignItems: 'center',+ marginBottom: '8px',+ }}>+ <span style={{+ fontSize: '9px',+ fontWeight: 700,+ color: FINCEPT.GRAY,+ letterSpacing: '0.5px',+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',+ }}>+ NEW VERSION+ </span>+ <span style={{+ fontSize: '10px',+ color: FINCEPT.GREEN,+ fontWeight: 700,+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',+ }}>+ v{updateInfo.version}+ </span>+ </div>+ {updateInfo.date && (+ <div style={{+ display: 'flex',+ justifyContent: 'space-between',+ alignItems: 'center',+ }}>+ <span style={{+ fontSize: '9px',+ fontWeight: 700,+ color: FINCEPT.GRAY,+ letterSpacing: '0.5px',+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',+ }}>+ RELEASE DATE+ </span>+ <span style={{+ fontSize: '10px',+ color: FINCEPT.CYAN,+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',+ }}>+ {new Date(updateInfo.date).toLocaleDateString()}+ </span>+ </div>+ )}</div>- <div className="flex justify-between text-sm">- <span className="text-muted-foreground">New Version:</span>- <span className="font-mono font-bold text-green-600">{updateInfo.version}</span>+ )}++ {/* Release Notes */}+ {updateInfo?.body && (+ <div style={{ marginBottom: '12px' }}>+ <span style={{+ fontSize: '9px',+ fontWeight: 700,+ color: FINCEPT.GRAY,+ letterSpacing: '0.5px',+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',+ display: 'block',+ marginBottom: '6px',+ }}>+ RELEASE NOTES+ </span>+ <div style={{+ backgroundColor: FINCEPT.DARK_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ padding: '10px',+ maxHeight: '120px',+ overflowY: 'auto',+ }}>+ <pre style={{+ fontSize: '10px',+ color: FINCEPT.WHITE,+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',+ whiteSpace: 'pre-wrap',+ wordBreak: 'break-word',+ margin: 0,+ lineHeight: '1.5',+ }}>+ {updateInfo.body}+ </pre>+ </div></div>- <div className="flex justify-between text-sm">- <span className="text-muted-foreground">Release Date:</span>- <span>{updateInfo.date ? new Date(updateInfo.date).toLocaleDateString() : 'N/A'}</span>+ )}++ {/* Download Progress */}+ {downloading && !updateReady && (+ <div style={{ marginBottom: '12px' }}>+ <div style={{+ display: 'flex',+ justifyContent: 'space-between',+ alignItems: 'center',+ marginBottom: '6px',+ }}>+ <span style={{+ fontSize: '9px',+ fontWeight: 700,+ color: FINCEPT.GRAY,+ letterSpacing: '0.5px',+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',+ }}>+ {downloadProgress === 100 ? 'INSTALLING' : 'DOWNLOADING'}+ </span>+ <span style={{+ fontSize: '10px',+ color: FINCEPT.ORANGE,+ fontWeight: 700,+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',+ }}>+ {downloadProgress.toFixed(0)}%+ </span>+ </div>+ {/* Custom Progress Bar */}+ <div style={{+ width: '100%',+ height: '4px',+ backgroundColor: FINCEPT.DARK_BG,+ borderRadius: '2px',+ overflow: 'hidden',+ border: `1px solid ${FINCEPT.BORDER}`,+ }}>+ <div style={{+ width: `${downloadProgress}%`,+ height: '100%',+ backgroundColor: FINCEPT.ORANGE,+ transition: 'width 0.3s ease',+ borderRadius: '2px',+ }} />+ </div></div>- </div>- )}-- {updateInfo?.body && (- <div className="rounded-md bg-muted p-3 text-sm">- <p className="font-semibold mb-2">Release Notes:</p>- <p className="text-muted-foreground whitespace-pre-wrap">{updateInfo.body}</p>- </div>- )}-- {downloading && (- <div className="space-y-2">- <div className="flex items-center justify-between text-sm">- <span>Downloading update...</span>- <span>{downloadProgress.toFixed(0)}%</span>+ )}++ {/* Update Ready */}+ {updateReady && (+ <div style={{+ padding: '10px 12px',+ backgroundColor: `${FINCEPT.GREEN}15`,+ border: `1px solid ${FINCEPT.GREEN}40`,+ borderRadius: '2px',+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ marginBottom: '12px',+ }}>+ <CheckCircle2 size={14} color={FINCEPT.GREEN} />+ <div>+ <span style={{+ fontSize: '10px',+ fontWeight: 700,+ color: FINCEPT.GREEN,+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',+ display: 'block',+ }}>+ UPDATE INSTALLED+ </span>+ <span style={{+ fontSize: '9px',+ color: FINCEPT.GRAY,+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',+ }}>+ Restarting application...+ </span>+ </div></div>- <Progress value={downloadProgress} />- </div>- )}-- {updateReady && (- <Alert className="border-green-500 bg-green-50 dark:bg-green-950">- <CheckCircle2 className="h-4 w-4 text-green-600" />- <AlertTitle>Update Ready!</AlertTitle>- <AlertDescription>- The application will restart in a moment...- </AlertDescription>- </Alert>- )}-- {error && (- <Alert variant="destructive">- <XCircle className="h-4 w-4" />- <AlertTitle>Error</AlertTitle>- <AlertDescription>{error}</AlertDescription>- </Alert>- )}+ )}++ {/* Error */}+ {error && (+ <div style={{+ padding: '10px 12px',+ backgroundColor: `${FINCEPT.RED}15`,+ border: `1px solid ${FINCEPT.RED}40`,+ borderRadius: '2px',+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ marginBottom: '12px',+ }}>+ <XCircle size={14} color={FINCEPT.RED} />+ <span style={{+ fontSize: '10px',+ color: FINCEPT.RED,+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',+ }}>+ {error}+ </span>+ </div>+ )}++ {/* Info text */}+ {!downloading && !updateReady && !error && (+ <span style={{+ fontSize: '9px',+ color: FINCEPT.MUTED,+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',+ }}>+ The update will download and install automatically. Your app will restart after installation.+ </span>+ )}+ </div>++ {/* Footer */}+ <div style={{+ padding: '12px 16px',+ backgroundColor: FINCEPT.HEADER_BG,+ borderTop: `1px solid ${FINCEPT.BORDER}`,+ display: 'flex',+ justifyContent: 'flex-end',+ gap: '8px',+ }}>+ {!downloading && !updateReady && (+ <>+ <button+ onClick={handleLater}+ style={{+ padding: '6px 10px',+ backgroundColor: 'transparent',+ border: `1px solid ${FINCEPT.BORDER}`,+ color: FINCEPT.GRAY,+ fontSize: '9px',+ fontWeight: 700,+ borderRadius: '2px',+ cursor: 'pointer',+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',+ letterSpacing: '0.5px',+ transition: 'all 0.2s',+ }}+ onMouseEnter={(e) => {+ e.currentTarget.style.borderColor = FINCEPT.ORANGE;+ e.currentTarget.style.color = FINCEPT.WHITE;+ }}+ onMouseLeave={(e) => {+ e.currentTarget.style.borderColor = FINCEPT.BORDER;+ e.currentTarget.style.color = FINCEPT.GRAY;+ }}+ >+ LATER+ </button>+ <button+ onClick={downloadAndInstall}+ disabled={downloading}+ style={{+ padding: '6px 14px',+ backgroundColor: FINCEPT.ORANGE,+ color: FINCEPT.DARK_BG,+ border: 'none',+ borderRadius: '2px',+ fontSize: '9px',+ fontWeight: 700,+ cursor: 'pointer',+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',+ letterSpacing: '0.5px',+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ transition: 'all 0.2s',+ }}+ >+ <Download size={10} />+ UPDATE NOW+ </button>+ </>+ )}+ {downloading && !updateReady && (+ <button+ disabled+ style={{+ padding: '6px 14px',+ backgroundColor: FINCEPT.MUTED,+ color: FINCEPT.DARK_BG,+ border: 'none',+ borderRadius: '2px',+ fontSize: '9px',+ fontWeight: 700,+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',+ letterSpacing: '0.5px',+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ cursor: 'not-allowed',+ opacity: 0.7,+ }}+ >+ <RefreshCw size={10} className="animate-spin" />+ {downloadProgress === 100 ? 'INSTALLING...' : 'DOWNLOADING...'}+ </button>+ )}+ </div></div>+ </div>+ )}- <DialogFooter>- {!downloading && !updateReady && (- <>- <Button variant="outline" onClick={handleLater}>- Later- </Button>- <Button onClick={downloadAndInstall} disabled={downloading}>- <Download className="mr-2 h-4 w-4" />- Download & Install- </Button>- </>- )}- {downloading && (- <Button disabled>- <RefreshCw className="mr-2 h-4 w-4 animate-spin" />- Installing...- </Button>- )}- </DialogFooter>- </DialogContent>- </Dialog>-- {/* Manual Check Button (can be placed in settings/menu) */}- <Button- variant="ghost"- size="sm"+ {/* Manual Check Button */}+ <buttononClick={() => checkForUpdates(false)}disabled={checking || downloading}- className="gap-2"+ style={{+ padding: '6px 10px',+ backgroundColor: 'transparent',+ border: `1px solid ${FINCEPT.BORDER}`,+ color: FINCEPT.GRAY,+ fontSize: '9px',+ fontWeight: 700,+ borderRadius: '2px',+ cursor: checking || downloading ? 'not-allowed' : 'pointer',+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',+ letterSpacing: '0.5px',+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ transition: 'all 0.2s',+ opacity: checking || downloading ? 0.5 : 1,+ }}>{checking ? (<>- <RefreshCw className="h-4 w-4 animate-spin" />- Checking...+ <RefreshCw size={10} className="animate-spin" />+ CHECKING...</>) : (<>- <Info className="h-4 w-4" />- Check for Updates+ <Info size={10} />+ CHECK FOR UPDATES</>)}- </Button>+ </button>- {/* Success/Error Toast */}+ {/* Toast notification */}{error && !showDialog && (- <div className="fixed bottom-4 right-4 z-50 max-w-md">- <Alert className={error.includes('latest version') ? 'border-green-500' : 'border-red-500'}>- {error.includes('latest version') ? (- <CheckCircle2 className="h-4 w-4 text-green-600" />- ) : (- <XCircle className="h-4 w-4" />- )}- <AlertDescription>{error}</AlertDescription>- </Alert>+ <div style={{+ position: 'fixed',+ bottom: '16px',+ right: '16px',+ zIndex: 9999,+ maxWidth: '320px',+ padding: '10px 12px',+ backgroundColor: FINCEPT.PANEL_BG,+ border: `1px solid ${error.includes('latest version') ? FINCEPT.GREEN + '40' : FINCEPT.RED + '40'}`,+ borderRadius: '2px',+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ boxShadow: '0 4px 12px rgba(0, 0, 0, 0.4)',+ }}>+ {error.includes('latest version') ? (+ <CheckCircle2 size={12} color={FINCEPT.GREEN} />+ ) : (+ <XCircle size={12} color={FINCEPT.RED} />+ )}+ <span style={{+ fontSize: '10px',+ color: error.includes('latest version') ? FINCEPT.GREEN : FINCEPT.RED,+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',+ }}>+ {error}+ </span></div>)}</>diff --git a/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx b/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsxindex 76de17a0d..d00ffcfc1 100644--- a/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx+++ b/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx@@ -1,6 +1,6 @@import React, { useState, useRef, useEffect } from 'react';import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';-import { Maximize, Minimize, Download, Settings, RefreshCw, User, Database, Eye, HelpCircle, LogOut, CheckCircle2, XCircle, MessageSquare, Terminal, Bot } from 'lucide-react';+import { Maximize, Minimize, Download, Settings, RefreshCw, User, Database, Eye, HelpCircle, LogOut, CheckCircle2, XCircle, MessageSquare, Terminal, Bot, ArrowUpCircle, X } from 'lucide-react';import { useAuth } from '@/contexts/AuthContext';import { useNavigation } from '@/contexts/NavigationContext';import { InterfaceModeProvider, useInterfaceMode } from '@/contexts/InterfaceModeContext';@@ -9,9 +9,6 @@ import { ChatModeInterface } from '@/components/chat-mode';import { APP_VERSION } from '@/constants/version';import { useAutoUpdater } from '@/hooks/useAutoUpdater';import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';-import { Button } from '@/components/ui/button';-import { Progress } from '@/components/ui/progress';-import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';import { CommandBar } from '@/components/command-bar';// Eagerly loaded tabs (needed immediately)@@ -1176,103 +1173,391 @@ function FinxeptTerminalContent() {</div>{/* Update Available Dialog */}- <Dialog open={updateAvailable} onOpenChange={(open) => !open && dismissUpdate()}>- <DialogContent className="sm:max-w-[500px]">- <DialogHeader>- <DialogTitle className="flex items-center gap-2">- <Download className="h-5 w-5" />- Update Available- </DialogTitle>- <DialogDescription>- A new version of FinceptTerminal is available.- </DialogDescription>- </DialogHeader>+ {updateAvailable && (+ <div style={{+ position: 'fixed',+ top: 0,+ left: 0,+ right: 0,+ bottom: 0,+ backgroundColor: 'rgba(0, 0, 0, 0.8)',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ zIndex: 9999,+ }}>+ <div style={{+ width: '460px',+ backgroundColor: '#0F0F0F',+ border: '1px solid #2A2A2A',+ borderRadius: '2px',+ overflow: 'hidden',+ boxShadow: '0 4px 24px rgba(0, 0, 0, 0.6), 0 0 1px #FF880040',+ }}>+ {/* Header */}+ <div style={{+ padding: '12px 16px',+ backgroundColor: '#1A1A1A',+ borderBottom: '2px solid #FF8800',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <ArrowUpCircle size={14} color="#FF8800" />+ <span style={{+ fontSize: '11px',+ fontWeight: 700,+ color: '#FFFFFF',+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',+ letterSpacing: '0.5px',+ }}>+ UPDATE AVAILABLE+ </span>+ </div>+ {!isInstalling && (+ <button+ onClick={dismissUpdate}+ style={{+ background: 'none',+ border: 'none',+ cursor: 'pointer',+ padding: '2px',+ display: 'flex',+ alignItems: 'center',+ }}+ >+ <X size={14} color="#787878" />+ </button>+ )}+ </div>- <div className="space-y-4 py-4">- {updateInfo && (- <div className="space-y-2">- <div className="flex justify-between text-sm">- <span className="text-muted-foreground">Current Version:</span>- <span className="font-mono">{updateInfo.currentVersion}</span>- </div>- <div className="flex justify-between text-sm">- <span className="text-muted-foreground">New Version:</span>- <span className="font-mono font-bold text-green-600">{updateInfo.version}</span>+ {/* Body */}+ <div style={{ padding: '16px' }}>+ {/* Version Info */}+ {updateInfo && (+ <div style={{+ backgroundColor: '#000000',+ border: '1px solid #2A2A2A',+ borderRadius: '2px',+ padding: '12px',+ marginBottom: '12px',+ }}>+ <div style={{+ display: 'flex',+ justifyContent: 'space-between',+ alignItems: 'center',+ marginBottom: '8px',+ }}>+ <span style={{+ fontSize: '9px',+ fontWeight: 700,+ color: '#787878',+ letterSpacing: '0.5px',+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',+ }}>+ CURRENT VERSION+ </span>+ <span style={{+ fontSize: '10px',+ color: '#4A4A4A',+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',+ }}>+ v{updateInfo.currentVersion}+ </span>+ </div>+ <div style={{+ display: 'flex',+ justifyContent: 'space-between',+ alignItems: 'center',+ marginBottom: '8px',+ }}>+ <span style={{+ fontSize: '9px',+ fontWeight: 700,+ color: '#787878',+ letterSpacing: '0.5px',+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',+ }}>+ NEW VERSION+ </span>+ <span style={{+ fontSize: '10px',+ color: '#00D66F',+ fontWeight: 700,+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',+ }}>+ v{updateInfo.version}+ </span>+ </div>+ {updateInfo.date && (+ <div style={{+ display: 'flex',+ justifyContent: 'space-between',+ alignItems: 'center',+ }}>+ <span style={{+ fontSize: '9px',+ fontWeight: 700,+ color: '#787878',+ letterSpacing: '0.5px',+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',+ }}>+ RELEASE DATE+ </span>+ <span style={{+ fontSize: '10px',+ color: '#00E5FF',+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',+ }}>+ {new Date(updateInfo.date).toLocaleDateString()}+ </span>+ </div>+ )}</div>- {updateInfo.date && (- <div className="flex justify-between text-sm">- <span className="text-muted-foreground">Release Date:</span>- <span>{new Date(updateInfo.date).toLocaleDateString()}</span>+ )}++ {/* Release Notes */}+ {updateInfo?.body && (+ <div style={{ marginBottom: '12px' }}>+ <span style={{+ fontSize: '9px',+ fontWeight: 700,+ color: '#787878',+ letterSpacing: '0.5px',+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',+ display: 'block',+ marginBottom: '6px',+ }}>+ RELEASE NOTES+ </span>+ <div style={{+ backgroundColor: '#000000',+ border: '1px solid #2A2A2A',+ borderRadius: '2px',+ padding: '10px',+ maxHeight: '120px',+ overflowY: 'auto',+ }}>+ <pre style={{+ fontSize: '10px',+ color: '#FFFFFF',+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',+ whiteSpace: 'pre-wrap',+ wordBreak: 'break-word',+ margin: 0,+ lineHeight: '1.5',+ }}>+ {updateInfo.body}+ </pre></div>- )}- </div>- )}+ </div>+ )}- {updateInfo?.body && (- <div className="rounded-md bg-muted p-3 text-sm">- <p className="font-semibold mb-2">Release Notes:</p>- <div className="max-h-48 overflow-y-auto">- <p className="text-muted-foreground whitespace-pre-wrap text-xs">{updateInfo.body}</p>+ {/* Download Progress */}+ {isInstalling && installProgress < 100 && (+ <div style={{ marginBottom: '12px' }}>+ <div style={{+ display: 'flex',+ justifyContent: 'space-between',+ alignItems: 'center',+ marginBottom: '6px',+ }}>+ <span style={{+ fontSize: '9px',+ fontWeight: 700,+ color: '#787878',+ letterSpacing: '0.5px',+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',+ }}>+ DOWNLOADING+ </span>+ <span style={{+ fontSize: '10px',+ color: '#FF8800',+ fontWeight: 700,+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',+ }}>+ {installProgress.toFixed(0)}%+ </span>+ </div>+ <div style={{+ width: '100%',+ height: '4px',+ backgroundColor: '#000000',+ borderRadius: '2px',+ overflow: 'hidden',+ border: '1px solid #2A2A2A',+ }}>+ <div style={{+ width: `${installProgress}%`,+ height: '100%',+ backgroundColor: '#FF8800',+ transition: 'width 0.3s ease',+ borderRadius: '2px',+ }} />+ </div></div>- </div>- )}+ )}- {isInstalling && (- <div className="space-y-2">- <div className="flex items-center justify-between text-sm">- <span>{installProgress === 100 ? 'Installing...' : 'Downloading...'}</span>- <span>{installProgress.toFixed(0)}%</span>+ {/* Update Ready */}+ {installProgress === 100 && isInstalling && (+ <div style={{+ padding: '10px 12px',+ backgroundColor: '#00D66F15',+ border: '1px solid #00D66F40',+ borderRadius: '2px',+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ marginBottom: '12px',+ }}>+ <CheckCircle2 size={14} color="#00D66F" />+ <div>+ <span style={{+ fontSize: '10px',+ fontWeight: 700,+ color: '#00D66F',+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',+ display: 'block',+ }}>+ UPDATE INSTALLED+ </span>+ <span style={{+ fontSize: '9px',+ color: '#787878',+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',+ }}>+ Restarting application...+ </span>+ </div></div>- <Progress value={installProgress} />- </div>- )}+ )}- {installProgress === 100 && isInstalling && (- <Alert className="border-green-500 bg-green-50 dark:bg-green-950">- <CheckCircle2 className="h-4 w-4 text-green-600" />- <AlertTitle>Update Ready!</AlertTitle>- <AlertDescription>- The application will restart in a moment...- </AlertDescription>- </Alert>- )}+ {/* Error */}+ {error && (+ <div style={{+ padding: '10px 12px',+ backgroundColor: '#FF3B3B15',+ border: '1px solid #FF3B3B40',+ borderRadius: '2px',+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ marginBottom: '12px',+ }}>+ <XCircle size={14} color="#FF3B3B" />+ <span style={{+ fontSize: '10px',+ color: '#FF3B3B',+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',+ }}>+ {error}+ </span>+ </div>+ )}- {error && (- <Alert variant="destructive">- <XCircle className="h-4 w-4" />- <AlertTitle>Error</AlertTitle>- <AlertDescription>{error}</AlertDescription>- </Alert>- )}+ {/* Info text */}+ {!isInstalling && !error && (+ <span style={{+ fontSize: '9px',+ color: '#4A4A4A',+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',+ }}>+ The update will download and install automatically. Your app will restart after installation.+ </span>+ )}+ </div>- {!isInstalling && (- <p className="text-xs text-muted-foreground">- The update will download and install automatically. Your app will restart after installation.- </p>- )}+ {/* Footer */}+ <div style={{+ padding: '12px 16px',+ backgroundColor: '#1A1A1A',+ borderTop: '1px solid #2A2A2A',+ display: 'flex',+ justifyContent: 'flex-end',+ gap: '8px',+ }}>+ {!isInstalling && !error && (+ <>+ <button+ onClick={dismissUpdate}+ style={{+ padding: '6px 10px',+ backgroundColor: 'transparent',+ border: '1px solid #2A2A2A',+ color: '#787878',+ fontSize: '9px',+ fontWeight: 700,+ borderRadius: '2px',+ cursor: 'pointer',+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',+ letterSpacing: '0.5px',+ transition: 'all 0.2s',+ }}+ onMouseEnter={(e) => {+ e.currentTarget.style.borderColor = '#FF8800';+ e.currentTarget.style.color = '#FFFFFF';+ }}+ onMouseLeave={(e) => {+ e.currentTarget.style.borderColor = '#2A2A2A';+ e.currentTarget.style.color = '#787878';+ }}+ >+ LATER+ </button>+ <button+ onClick={installUpdate}+ style={{+ padding: '6px 14px',+ backgroundColor: '#FF8800',+ color: '#000000',+ border: 'none',+ borderRadius: '2px',+ fontSize: '9px',+ fontWeight: 700,+ cursor: 'pointer',+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',+ letterSpacing: '0.5px',+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ transition: 'all 0.2s',+ }}+ >+ <Download size={10} />+ UPDATE NOW+ </button>+ </>+ )}+ {isInstalling && installProgress < 100 && (+ <button+ disabled+ style={{+ padding: '6px 14px',+ backgroundColor: '#4A4A4A',+ color: '#000000',+ border: 'none',+ borderRadius: '2px',+ fontSize: '9px',+ fontWeight: 700,+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',+ letterSpacing: '0.5px',+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ cursor: 'not-allowed',+ opacity: 0.7,+ }}+ >+ <RefreshCw size={10} className="animate-spin" />+ DOWNLOADING...+ </button>+ )}+ </div></div>-- <DialogFooter>- {!isInstalling && !error && (- <>- <Button variant="outline" onClick={dismissUpdate}>- Later- </Button>- <Button onClick={installUpdate}>- <Download className="mr-2 h-4 w-4" />- Update Now- </Button>- </>- )}- {isInstalling && (- <Button disabled>- <RefreshCw className="mr-2 h-4 w-4 animate-spin" />- {installProgress === 100 ? 'Installing...' : 'Downloading...'}- </Button>- )}- </DialogFooter>- </DialogContent>- </Dialog>+ </div>+ )}{workspaceDialogMode && (<WorkspaceDialogdiff --git a/fincept-terminal-desktop/src/components/tabs/agent-config/AgentConfigTab.tsx b/fincept-terminal-desktop/src/components/tabs/agent-config/AgentConfigTab.tsxindex 4926847d7..f002dac05 100644--- a/fincept-terminal-desktop/src/components/tabs/agent-config/AgentConfigTab.tsx+++ b/fincept-terminal-desktop/src/components/tabs/agent-config/AgentConfigTab.tsx@@ -10,10 +10,20 @@* - Tools browser with selection* - Chat interface with routing* - System capabilities view+ *+ * State Management (STATE_MANAGEMENT.md compliance):+ * - ErrorBoundary wrapper for graceful error handling+ * - AbortController for cleanup on unmount+ * - mountedRef to prevent stale state updates+ * - Input validation before API calls+ * - Timeout protection for external calls*/import React, { useState, useEffect, useCallback, useRef } from 'react';import { invoke } from '@tauri-apps/api/core';+import { withTimeout } from '@/services/core/apiUtils';+import { validateSymbol, sanitizeSymbol, validateString } from '@/services/core/validators';+import { ErrorBoundary } from '@/components/common/ErrorBoundary';import {Bot, RefreshCw, Play, Code, AlertCircle, CheckCircle,Users, TrendingUp, Globe, Building2, Wrench, Brain,@@ -294,8 +304,8 @@ const AgentConfigTab: React.FC = () => {memory_create_user_memories: boolean;memory_create_session_summary: boolean;}>({- provider: 'openai',- model_id: 'gpt-4-turbo',+ provider: 'fincept', // Default to Fincept LLM until user changes+ model_id: 'fincept-llm',temperature: 0.7,max_tokens: 4096,tools: [],@@ -371,6 +381,11 @@ const AgentConfigTab: React.FC = () => {const [chatInput, setChatInput] = useState('');const chatEndRef = useRef<HTMLDivElement>(null);+ // Cleanup refs (STATE_MANAGEMENT.md: Point 3 - Cleanup on Unmount)+ const mountedRef = useRef(true);+ const abortControllerRef = useRef<AbortController | null>(null);+ const fetchIdRef = useRef(0); // For race condition prevention+// Tools stateconst [toolSearch, setToolSearch] = useState('');const [expandedCategories, setExpandedCategories] = useState<Set<string>>(new Set(['finance']));@@ -408,9 +423,21 @@ const AgentConfigTab: React.FC = () => {// Effects// =============================================================================+ // Cleanup on unmount (STATE_MANAGEMENT.md: Point 3)+ useEffect(() => {+ mountedRef.current = true;+ return () => {+ mountedRef.current = false;+ abortControllerRef.current?.abort();+ };+ }, []);+useEffect(() => {// Load all data in parallel with timeoutconst loadInitialData = async () => {+ // Track this fetch operation for race condition prevention+ const currentFetchId = ++fetchIdRef.current;+setLoading(true);setError(null);@@ -422,16 +449,22 @@ const AgentConfigTab: React.FC = () => {loadLLMConfigs(),]);+ // STATE_MANAGEMENT.md: Point 8 - Timeout Protectionconst timeoutPromise = new Promise((_, reject) =>setTimeout(() => reject(new Error('Loading timeout - please check your backend service')), 30000));await Promise.race([criticalPromise, timeoutPromise]);} catch (err: any) {+ // Only update state if still mounted and this is the current request+ if (!mountedRef.current || currentFetchId !== fetchIdRef.current) return;console.error('Failed to load initial data:', err);setError(err.message || 'Failed to load agent data');} finally {- setLoading(false);+ // Only update state if still mounted and this is the current request+ if (mountedRef.current && currentFetchId === fetchIdRef.current) {+ setLoading(false);+ }}// Load system data in background (non-blocking)@@ -454,21 +487,38 @@ const AgentConfigTab: React.FC = () => {const configs = await getLLMConfigs();setConfiguredLLMs(configs);- // Set active config as default if available- const activeConfig = await getActiveLLMConfig();- if (activeConfig) {- setEditedConfig(prev => ({- ...prev,- provider: activeConfig.provider,- model_id: activeConfig.model,- }));- } else if (configs.length > 0) {- // Use first configured LLM if no active one+ // Priority order for default LLM selection:+ // 1. Fincept LLM (provider='fincept', always preferred if available)+ // 2. User's active config from settings+ // 3. First configured LLM as fallback++ // Check if Fincept LLM is available (provider ID is 'fincept')+ const finceptLLM = configs.find(c => c.provider === 'fincept');+ if (finceptLLM) {+ // Use Fincept LLM as defaultsetEditedConfig(prev => ({...prev,- provider: configs[0].provider,- model_id: configs[0].model,+ provider: finceptLLM.provider,+ model_id: finceptLLM.model,}));+ console.log('[AgentConfigTab] Using Fincept LLM as default provider');+ } else {+ // Fall back to active config or first available+ const activeConfig = await getActiveLLMConfig();+ if (activeConfig) {+ setEditedConfig(prev => ({+ ...prev,+ provider: activeConfig.provider,+ model_id: activeConfig.model,+ }));+ } else if (configs.length > 0) {+ // Use first configured LLM if no active one+ setEditedConfig(prev => ({+ ...prev,+ provider: configs[0].provider,+ model_id: configs[0].model,+ }));+ }}console.log('[AgentConfigTab] Loaded LLM configs from settings:', configs.length);@@ -658,16 +708,28 @@ const AgentConfigTab: React.FC = () => {for (const config of llmConfigs) {if (config.api_key) {const providerUpper = config.provider.toUpperCase();+ // Add API key in multiple formats for maximum compatibilityapiKeys[`${providerUpper}_API_KEY`] = config.api_key;apiKeys[config.provider] = config.api_key;+ apiKeys[config.provider.toLowerCase()] = config.api_key;}// Pass base_url for custom endpoints (Ollama, Azure, etc.)if (config.base_url) {apiKeys[`${config.provider.toUpperCase()}_BASE_URL`] = config.base_url;+ apiKeys[`${config.provider}_base_url`] = config.base_url;}}++ // Debug logging+ console.log('[AgentConfigTab] API Keys prepared:', {+ keysAvailable: Object.keys(apiKeys),+ hasFincept: !!(apiKeys['FINCEPT_API_KEY'] || apiKeys['fincept'] || apiKeys['FINCEPT']),+ hasOpenAI: !!(apiKeys['OPENAI_API_KEY'] || apiKeys['openai'] || apiKeys['OPENAI']),+ });+return apiKeys;- } catch {+ } catch (err) {+ console.error('[AgentConfigTab] Failed to get API keys:', err);return {};}};@@ -735,7 +797,15 @@ const AgentConfigTab: React.FC = () => {// =============================================================================const runAgent = async () => {- if (!testQuery.trim()) return;+ // STATE_MANAGEMENT.md: Point 10 - Input Validation+ const queryValidation = validateString(testQuery, { minLength: 1, maxLength: 10000 });+ if (!queryValidation.valid) {+ setError(queryValidation.error || 'Invalid query');+ return;+ }++ // Track this execution for race condition prevention+ const currentFetchId = ++fetchIdRef.current;setExecuting(true);setError(null);@@ -744,10 +814,43 @@ const AgentConfigTab: React.FC = () => {try {const apiKeys = await getApiKeys();+ // Check if component is still mounted+ if (!mountedRef.current || currentFetchId !== fetchIdRef.current) return;++ // Validate that the selected provider has an API key configured+ const providerKey = editedConfig.provider.toLowerCase();+ const providerKeyUpper = `${editedConfig.provider.toUpperCase()}_API_KEY`;+ const hasProviderKey = apiKeys[providerKey] || apiKeys[providerKeyUpper];++ console.log('[AgentConfigTab] API Key validation:', {+ provider: editedConfig.provider,+ providerKey,+ providerKeyUpper,+ hasProviderKey,+ availableKeys: Object.keys(apiKeys),+ apiKeysSnapshot: Object.keys(apiKeys).reduce((acc, key) => {+ acc[key] = apiKeys[key] ? `***${apiKeys[key].slice(-4)}` : 'undefined';+ return acc;+ }, {} as Record<string, string>),+ });++ if (!hasProviderKey && editedConfig.provider !== 'ollama') {+ setError(+ `${editedConfig.provider.toUpperCase()} API key not configured. ` ++ `Please go to Settings → LLM Configuration and add your API key for ${editedConfig.provider}.`+ );+ setExecuting(false);+ return;+ }+// Check if we should use auto-routingif (useAutoRouting) {- // First, route the query- const routingResult = await agentService.routeQuery(testQuery, apiKeys);+ // First, route the query with timeout protection+ const routingResult = await withTimeout(+ agentService.routeQuery(testQuery, apiKeys),+ 15000, // 15 second timeout for routing+ 'Query routing timed out'+ );setLastRoutingResult(routingResult);// Add system message about routing@@ -768,7 +871,11 @@ const AgentConfigTab: React.FC = () => {editedConfig.instructions,buildDetailedConfigOptions());- const result = await agentService.executeRoutedQuery(testQuery, apiKeys, undefined, userConfig);+ const result = await withTimeout(+ agentService.executeRoutedQuery(testQuery, apiKeys, undefined, userConfig),+ 60000, // 60 second timeout for execution+ 'Agent execution timed out'+ );setTestResult(result);setChatMessages(prev => [@@ -790,11 +897,29 @@ const AgentConfigTab: React.FC = () => {buildDetailedConfigOptions());+ // Debug logging+ console.log('[AgentConfigTab] Running agent with config:', {+ provider: editedConfig.provider,+ model_id: editedConfig.model_id,+ hasApiKey: !!apiKeys[editedConfig.provider.toLowerCase()] || !!apiKeys[`${editedConfig.provider.toUpperCase()}_API_KEY`],+ apiKeyKeys: Object.keys(apiKeys),+ configKeys: Object.keys(config),+ fullConfig: config,+ });+let result;if (selectedOutputModel) {- result = await agentService.runAgentStructured(testQuery, config, selectedOutputModel, apiKeys);+ result = await withTimeout(+ agentService.runAgentStructured(testQuery, config, selectedOutputModel, apiKeys),+ 60000, // 60 second timeout+ 'Agent execution timed out'+ );} else {- result = await agentService.runAgent(testQuery, config, apiKeys);+ result = await withTimeout(+ agentService.runAgent(testQuery, config, apiKeys),+ 60000, // 60 second timeout+ 'Agent execution timed out'+ );}setTestResult(result);@@ -811,17 +936,37 @@ const AgentConfigTab: React.FC = () => {]);}+ // Only update state if still mounted+ if (!mountedRef.current || currentFetchId !== fetchIdRef.current) return;+setSuccess('Query executed successfully');setTimeout(() => setSuccess(null), 3000);} catch (err: any) {+ // Only update state if still mounted+ if (!mountedRef.current || currentFetchId !== fetchIdRef.current) return;setError(err.toString());} finally {- setExecuting(false);+ // Only update state if still mounted+ if (mountedRef.current && currentFetchId === fetchIdRef.current) {+ setExecuting(false);+ }}};const runTeam = async () => {- if (teamMembers.length === 0 || !testQuery.trim()) return;+ // STATE_MANAGEMENT.md: Point 10 - Input Validation+ if (teamMembers.length === 0) {+ setError('Please add at least one agent to the team');+ return;+ }+ const queryValidation = validateString(testQuery, { minLength: 1, maxLength: 10000 });+ if (!queryValidation.valid) {+ setError(queryValidation.error || 'Invalid query');+ return;+ }++ // Track this execution for race condition prevention+ const currentFetchId = ++fetchIdRef.current;setExecuting(true);setIsStreaming(true);@@ -837,6 +982,9 @@ const AgentConfigTab: React.FC = () => {try {const apiKeys = await getApiKeys();+ // Check if component is still mounted+ if (!mountedRef.current || currentFetchId !== fetchIdRef.current) return;+const teamConfig = agentService.buildTeamConfig('Custom Team',teamMode,@@ -925,16 +1073,32 @@ const AgentConfigTab: React.FC = () => {};const runWorkflow = async (workflowType: string, extraParams?: Record<string, any>) => {+ // STATE_MANAGEMENT.md: Point 10 - Input Validation for stock analysis+ if (workflowType === 'stock_analysis') {+ const symbolValidation = validateSymbol(workflowSymbol);+ if (!symbolValidation.valid) {+ setError(symbolValidation.error || 'Invalid symbol');+ return;+ }+ }++ // Track this execution for race condition prevention+ const currentFetchId = ++fetchIdRef.current;+setExecuting(true);setError(null);try {const apiKeys = await getApiKeys();++ // Check if component is still mounted+ if (!mountedRef.current || currentFetchId !== fetchIdRef.current) return;+let result;switch (workflowType) {case 'stock_analysis':- result = await agentService.runStockAnalysis(workflowSymbol, apiKeys);+ result = await agentService.runStockAnalysis(sanitizeSymbol(workflowSymbol), apiKeys);break;case 'portfolio_rebal':result = await agentService.runPortfolioRebalancing({ holdings: [] }, apiKeys);@@ -997,15 +1161,23 @@ const AgentConfigTab: React.FC = () => {throw new Error(`Unknown workflow: ${workflowType}`);}+ // Only update state if still mounted+ if (!mountedRef.current || currentFetchId !== fetchIdRef.current) return;+setTestResult(result);if (result.success) {setSuccess(`${workflowType} completed`);setTimeout(() => setSuccess(null), 3000);}} catch (err: any) {+ // Only update state if still mounted+ if (!mountedRef.current || currentFetchId !== fetchIdRef.current) return;setError(err.toString());} finally {- setExecuting(false);+ // Only update state if still mounted+ if (mountedRef.current && currentFetchId === fetchIdRef.current) {+ setExecuting(false);+ }}};@@ -4377,4 +4549,20 @@ const AgentConfigTab: React.FC = () => {);};-export default AgentConfigTab;+// =============================================================================+// EXPORTED COMPONENT - Wrapped with ErrorBoundary (STATE_MANAGEMENT.md: Point 5)+// =============================================================================++const AgentConfigTabWithErrorBoundary: React.FC = () => (+ <ErrorBoundary+ name="Agent Studio"+ variant="default"+ onError={(error, errorInfo) => {+ console.error('[Agent Studio Error]', error.message, errorInfo.componentStack);+ }}+ >+ <AgentConfigTab />+ </ErrorBoundary>+);++export default AgentConfigTabWithErrorBoundary;diff --git a/fincept-terminal-desktop/src/components/tabs/agent-config/RenaissanceTechnologiesPanel.tsx b/fincept-terminal-desktop/src/components/tabs/agent-config/RenaissanceTechnologiesPanel.tsxindex c00bcd48d..197b376d6 100644--- a/fincept-terminal-desktop/src/components/tabs/agent-config/RenaissanceTechnologiesPanel.tsx+++ b/fincept-terminal-desktop/src/components/tabs/agent-config/RenaissanceTechnologiesPanel.tsx@@ -8,10 +8,20 @@* - Real-time Position Sizing & Risk Management* - Team Collaboration Workflows* - Professional Terminal UI/UX+ *+ * State Management:+ * - Uses useReducer for atomic state updates+ * - Implements explicit state machine (idle→loading→success|error)+ * - Proper cleanup on unmount with AbortController pattern+ * - Input validation before API calls+ * - Timeout protection for external calls*/-import React, { useState, useEffect } from 'react';+import React, { useReducer, useEffect, useRef, useCallback } from 'react';import { invoke } from '@tauri-apps/api/core';+import { withTimeout } from '@/services/core/apiUtils';+import { validateSymbol, sanitizeSymbol } from '@/services/core/validators';+import { ErrorBoundary } from '@/components/common/ErrorBoundary';import {TrendingUp, AlertCircle, CheckCircle, Users, Sparkles,Brain, Shield, FileText, Zap, Settings, Play, RefreshCw,@@ -120,77 +130,255 @@ const SIGNAL_TYPES = [{ value: 'pairs_trading', label: 'Pairs Trading', desc: 'Correlated asset trading' },];+// API timeout for external calls (30 seconds)+const API_TIMEOUT_MS = 30000;+// =============================================================================-// MAIN COMPONENT+// STATE MANAGEMENT - useReducer for atomic updates// =============================================================================-export default function RenaissanceTechnologiesPanel() {- // State- const [activeTab, setActiveTab] = useState<'analysis' | 'agents' | 'config'>('analysis');- const [ticker, setTicker] = useState('');- const [signalType, setSignalType] = useState('momentum');- const [isAnalyzing, setIsAnalyzing] = useState(false);- const [analysisResult, setAnalysisResult] = useState<SignalAnalysisResult | null>(null);- const [currentTime, setCurrentTime] = useState(new Date());- const [showAdvanced, setShowAdvanced] = useState(false);+// State machine: idle → loading → success | error+type AnalysisStatus = 'idle' | 'loading' | 'success' | 'error';++interface PanelState {+ // UI state+ activeTab: 'analysis' | 'agents' | 'config';+ showAdvanced: boolean;+ currentTime: Date;++ // Form state+ ticker: string;+ signalType: string;++ // Analysis state (state machine pattern)+ analysisStatus: AnalysisStatus;+ analysisResult: SignalAnalysisResult | null;+ analysisError: string | null;// Config state- const [riskLimits, setRiskLimits] = useState<RiskLimits>({+ riskLimits: RiskLimits;++ // Validation+ tickerValidationError: string | null;+}++type PanelAction =+ | { type: 'SET_ACTIVE_TAB'; payload: 'analysis' | 'agents' | 'config' }+ | { type: 'SET_SHOW_ADVANCED'; payload: boolean }+ | { type: 'UPDATE_TIME'; payload: Date }+ | { type: 'SET_TICKER'; payload: string }+ | { type: 'SET_TICKER_ERROR'; payload: string | null }+ | { type: 'SET_SIGNAL_TYPE'; payload: string }+ | { type: 'ANALYSIS_START' }+ | { type: 'ANALYSIS_SUCCESS'; payload: SignalAnalysisResult }+ | { type: 'ANALYSIS_ERROR'; payload: string }+ | { type: 'ANALYSIS_RESET' }+ | { type: 'UPDATE_RISK_LIMITS'; payload: RiskLimits };++const initialState: PanelState = {+ activeTab: 'analysis',+ showAdvanced: false,+ currentTime: new Date(),+ ticker: '',+ signalType: 'momentum',+ analysisStatus: 'idle',+ analysisResult: null,+ analysisError: null,+ riskLimits: {max_position_size_pct: 5.0,max_leverage: 12.5,max_drawdown_pct: 15.0,max_daily_var_pct: 2.0,min_signal_confidence: 0.5075,- });+ },+ tickerValidationError: null,+};- // Update time+function panelReducer(state: PanelState, action: PanelAction): PanelState {+ switch (action.type) {+ case 'SET_ACTIVE_TAB':+ return { ...state, activeTab: action.payload };+ case 'SET_SHOW_ADVANCED':+ return { ...state, showAdvanced: action.payload };+ case 'UPDATE_TIME':+ return { ...state, currentTime: action.payload };+ case 'SET_TICKER':+ return { ...state, ticker: action.payload, tickerValidationError: null };+ case 'SET_TICKER_ERROR':+ return { ...state, tickerValidationError: action.payload };+ case 'SET_SIGNAL_TYPE':+ return { ...state, signalType: action.payload };+ case 'ANALYSIS_START':+ // Atomic update: loading state + clear previous results+ return {+ ...state,+ analysisStatus: 'loading',+ analysisResult: null,+ analysisError: null,+ };+ case 'ANALYSIS_SUCCESS':+ return {+ ...state,+ analysisStatus: 'success',+ analysisResult: action.payload,+ analysisError: null,+ };+ case 'ANALYSIS_ERROR':+ return {+ ...state,+ analysisStatus: 'error',+ analysisResult: null,+ analysisError: action.payload,+ };+ case 'ANALYSIS_RESET':+ return {+ ...state,+ analysisStatus: 'idle',+ analysisResult: null,+ analysisError: null,+ };+ case 'UPDATE_RISK_LIMITS':+ return { ...state, riskLimits: action.payload };+ default:+ return state;+ }+}++// =============================================================================+// MAIN COMPONENT+// =============================================================================++function RenaissanceTechnologiesPanelInner() {+ // State via reducer - atomic updates, explicit state machine+ const [state, dispatch] = useReducer(panelReducer, initialState);++ // Refs for cleanup and mounted check+ const mountedRef = useRef(true);+ const abortControllerRef = useRef<AbortController | null>(null);+ const fetchIdRef = useRef(0); // For race condition prevention++ // Destructure state for convenience+ const {+ activeTab,+ showAdvanced,+ currentTime,+ ticker,+ signalType,+ analysisStatus,+ analysisResult,+ analysisError,+ riskLimits,+ tickerValidationError,+ } = state;++ // Derived state+ const isAnalyzing = analysisStatus === 'loading';++ // Cleanup on unmountuseEffect(() => {- const timer = setInterval(() => setCurrentTime(new Date()), 1000);+ mountedRef.current = true;+ return () => {+ mountedRef.current = false;+ abortControllerRef.current?.abort();+ };+ }, []);++ // Update time - with cleanup+ useEffect(() => {+ const timer = setInterval(() => {+ if (mountedRef.current) {+ dispatch({ type: 'UPDATE_TIME', payload: new Date() });+ }+ }, 1000);return () => clearInterval(timer);}, []);- // Run signal analysis- const runSignalAnalysis = async () => {- if (!ticker) return;+ // Validated ticker setter+ const handleTickerChange = useCallback((value: string) => {+ const upperValue = value.toUpperCase();+ dispatch({ type: 'SET_TICKER', payload: upperValue });- setIsAnalyzing(true);- setAnalysisResult(null);+ // Validate on change+ if (upperValue.length > 0) {+ const validation = validateSymbol(upperValue);+ if (!validation.valid) {+ dispatch({ type: 'SET_TICKER_ERROR', payload: validation.error || 'Invalid ticker' });+ }+ }+ }, []);++ // Run signal analysis with proper state management+ const runSignalAnalysis = useCallback(async () => {+ // Point 10: Input validation before API call+ const validation = validateSymbol(ticker);+ if (!validation.valid) {+ dispatch({ type: 'SET_TICKER_ERROR', payload: validation.error || 'Invalid ticker' });+ return;+ }++ const sanitizedTicker = sanitizeSymbol(ticker);++ // Increment fetch ID for race condition handling (Point 1)+ const currentFetchId = ++fetchIdRef.current;++ // Abort previous request (Point 3: cleanup)+ abortControllerRef.current?.abort();+ const abortController = new AbortController();+ abortControllerRef.current = abortController;++ // Point 2: State machine transition to loading+ dispatch({ type: 'ANALYSIS_START' });try {// Send only user inputs - backend will calculate signal metrics from real dataconst cliInput = {- ticker,+ ticker: sanitizedTicker,signal_type: signalType,trade_value: 1_000_000, // Default $1M tradeperiod: '1y',include_deliberation: true, // Include IC deliberation};- const result = await invoke<string>('execute_renaissance_cli', {- command: 'analyze_signal',- data: JSON.stringify(cliInput),- });+ // Point 8: Timeout protection for external call+ const result = await withTimeout(+ invoke<string>('execute_renaissance_cli', {+ command: 'analyze_signal',+ data: JSON.stringify(cliInput),+ }),+ API_TIMEOUT_MS,+ 'Analysis request timed out'+ );++ // Check for abort and race conditions (Points 1, 3)+ if (abortController.signal.aborted || currentFetchId !== fetchIdRef.current || !mountedRef.current) {+ return;+ }const parsed = JSON.parse(result);if (parsed.success) {- setAnalysisResult(parsed.data || parsed);+ // Point 2: State machine transition to success+ dispatch({ type: 'ANALYSIS_SUCCESS', payload: parsed.data || parsed });} else {- setAnalysisResult({- success: false,- error: parsed.error || 'Analysis failed',- });+ // Point 2: State machine transition to error+ dispatch({ type: 'ANALYSIS_ERROR', payload: parsed.error || 'Analysis failed' });}} catch (error: any) {+ // Check if component is still mounted and this is the current request+ if (!mountedRef.current || currentFetchId !== fetchIdRef.current) {+ return;+ }++ // Don't report abort errors+ if (error.name === 'AbortError' || error.message === 'Request aborted') {+ return;+ }+console.error('Analysis error:', error);- setAnalysisResult({- success: false,- error: error.message || 'Analysis failed',- });- } finally {- setIsAnalyzing(false);+ // Point 2: State machine transition to error+ dispatch({ type: 'ANALYSIS_ERROR', payload: error.message || 'Analysis failed' });}- };+ }, [ticker, signalType]);return (<div style={{@@ -233,7 +421,7 @@ export default function RenaissanceTechnologiesPanel() {{(['analysis', 'agents', 'config'] as const).map((tab) => (<buttonkey={tab}- onClick={() => setActiveTab(tab)}+ onClick={() => dispatch({ type: 'SET_ACTIVE_TAB', payload: tab })}style={{...COMMON_STYLES.tabButton(activeTab === tab),display: 'flex',@@ -304,14 +492,16 @@ export default function RenaissanceTechnologiesPanel() {{activeTab === 'analysis' && (<AnalysisTabticker={ticker}- setTicker={setTicker}+ setTicker={handleTickerChange}signalType={signalType}- setSignalType={setSignalType}+ setSignalType={(v) => dispatch({ type: 'SET_SIGNAL_TYPE', payload: v })}isAnalyzing={isAnalyzing}analysisResult={analysisResult}+ analysisError={analysisError}+ tickerValidationError={tickerValidationError}onRunAnalysis={runSignalAnalysis}showAdvanced={showAdvanced}- setShowAdvanced={setShowAdvanced}+ setShowAdvanced={(v) => dispatch({ type: 'SET_SHOW_ADVANCED', payload: v })}/>)}@@ -322,7 +512,7 @@ export default function RenaissanceTechnologiesPanel() {{activeTab === 'config' && (<ConfigTabriskLimits={riskLimits}- onUpdateLimits={setRiskLimits}+ onUpdateLimits={(limits) => dispatch({ type: 'UPDATE_RISK_LIMITS', payload: limits })}/>)}</div>@@ -353,6 +543,8 @@ function AnalysisTab({setSignalType,isAnalyzing,analysisResult,+ analysisError,+ tickerValidationError,onRunAnalysis,showAdvanced,setShowAdvanced,@@ -363,6 +555,8 @@ function AnalysisTab({setSignalType: (v: string) => void;isAnalyzing: boolean;analysisResult: SignalAnalysisResult | null;+ analysisError: string | null;+ tickerValidationError: string | null;onRunAnalysis: () => void;showAdvanced: boolean;setShowAdvanced: (v: boolean) => void;@@ -417,17 +611,31 @@ function AnalysisTab({<inputtype="text"value={ticker}- onChange={(e) => setTicker(e.target.value.toUpperCase())}+ onChange={(e) => setTicker(e.target.value)}placeholder="AAPL"style={{...COMMON_STYLES.inputField,marginTop: SPACING.SMALL,textTransform: 'uppercase',width: '200px',+ borderColor: tickerValidationError ? FINCEPT.RED : FINCEPT.BORDER,}}- onFocus={(e) => e.currentTarget.style.borderColor = FINCEPT.ORANGE}- onBlur={(e) => e.currentTarget.style.borderColor = FINCEPT.BORDER}+ onFocus={(e) => e.currentTarget.style.borderColor = tickerValidationError ? FINCEPT.RED : FINCEPT.ORANGE}+ onBlur={(e) => e.currentTarget.style.borderColor = tickerValidationError ? FINCEPT.RED : FINCEPT.BORDER}/>+ {tickerValidationError && (+ <div style={{+ marginTop: SPACING.TINY,+ fontSize: TYPOGRAPHY.TINY,+ color: FINCEPT.RED,+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ }}>+ <AlertCircle size={10} />+ {tickerValidationError}+ </div>+ )}</div>{/* Strategy Type & Execute - Full Width Section */}@@ -534,6 +742,22 @@ function AnalysisTab({)}</div>+ {/* Error Display */}+ {analysisError && (+ <div style={{+ ...COMMON_STYLES.panel,+ border: `2px solid ${FINCEPT.RED}`,+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: SPACING.DEFAULT, color: FINCEPT.RED }}>+ <AlertCircle size={24} />+ <div>+ <div style={{ fontSize: TYPOGRAPHY.SUBHEADING, fontWeight: TYPOGRAPHY.BOLD }}>ANALYSIS FAILED</div>+ <div style={{ fontSize: TYPOGRAPHY.SMALL, marginTop: SPACING.TINY }}>{analysisError}</div>+ </div>+ </div>+ </div>+ )}+{/* Results */}{analysisResult && <ResultsDisplay result={analysisResult} />}</div>@@ -1057,3 +1281,21 @@ function ConfigTab({</div>);}++// =============================================================================+// EXPORTED COMPONENT - Wrapped with ErrorBoundary (Point 5)+// =============================================================================++export default function RenaissanceTechnologiesPanel() {+ return (+ <ErrorBoundary+ name="Renaissance Technologies Panel"+ variant="default"+ onError={(error, errorInfo) => {+ console.error('[RenTech Panel Error]', error.message, errorInfo.componentStack);+ }}+ >+ <RenaissanceTechnologiesPanelInner />+ </ErrorBoundary>+ );+}diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/GluonTSPanel.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/GluonTSPanel.tsxindex d56bb44bb..ac42c4037 100644--- a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/GluonTSPanel.tsx+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/GluonTSPanel.tsx@@ -1,18 +1,25 @@/*** GluonTSPanel - Deep Learning Time Series Forecasting* Amazon GluonTS: 9 DL models + 3 baselines + evaluation+ *+ * Redesigned UI with:+ * - Clear input labels with help text+ * - How to use guide panel+ * - Model descriptions and tips*/import React, { useState } from 'react';import { invoke } from '@tauri-apps/api/core';import { useTerminalTheme } from '@/contexts/ThemeContext';import {- TrendingUp, Play, AlertCircle, BarChart3, Zap, Brain+ TrendingUp, Play, AlertCircle, BarChart3, Zap, Brain, HelpCircle, Info, RefreshCw} from 'lucide-react';import {ResponsiveContainer, LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Area, AreaChart} from 'recharts';+const GLUON_BLUE = '#00A1E4';+interface ForecastResult {mean: number[];quantiles: { '0.1': number[]; '0.5': number[]; '0.9': number[] };@@ -29,35 +36,179 @@ interface EvalResult {num_forecasts: number;}+// Tooltip component for help text+function TooltipHelp({ text }: { text: string }) {+ const [show, setShow] = useState(false);+ const [position, setPosition] = useState({ top: 0, left: 0 });+ const triggerRef = React.useRef<HTMLDivElement>(null);+ const { colors } = useTerminalTheme();++ const handleMouseEnter = () => {+ if (triggerRef.current) {+ const rect = triggerRef.current.getBoundingClientRect();+ setPosition({+ top: rect.top - 10,+ left: rect.left + rect.width / 2,+ });+ }+ setShow(true);+ };++ return (+ <div+ ref={triggerRef}+ style={{ position: 'relative', display: 'inline-flex', alignItems: 'center' }}+ onMouseEnter={handleMouseEnter}+ onMouseLeave={() => setShow(false)}+ >+ <HelpCircle size={12} color={colors.textMuted} style={{ cursor: 'help' }} />+ {show && (+ <div+ style={{+ position: 'fixed',+ zIndex: 9999,+ padding: '10px 14px',+ backgroundColor: '#1a1a2e',+ border: `1px solid ${GLUON_BLUE}60`,+ borderRadius: '6px',+ color: colors.text,+ fontSize: '12px',+ lineHeight: 1.5,+ whiteSpace: 'normal',+ width: '260px',+ textAlign: 'left',+ boxShadow: '0 8px 24px rgba(0,0,0,0.5)',+ top: position.top,+ left: position.left,+ transform: 'translate(-50%, -100%)',+ }}+ >+ {text}+ </div>+ )}+ </div>+ );+}++// How to Use Panel+function HowToUsePanel() {+ const { colors } = useTerminalTheme();+ const [expanded, setExpanded] = useState(true);++ return (+ <div+ style={{+ backgroundColor: `${GLUON_BLUE}08`,+ border: `1px solid ${GLUON_BLUE}25`,+ borderRadius: '6px',+ marginBottom: '16px',+ }}+ >+ {/* Header */}+ <div+ style={{+ display: 'flex',+ alignItems: 'center',+ gap: '10px',+ padding: '12px 16px',+ backgroundColor: `${GLUON_BLUE}15`,+ cursor: 'pointer',+ borderBottom: expanded ? `1px solid ${GLUON_BLUE}20` : 'none',+ }}+ onClick={() => setExpanded(!expanded)}+ >+ <Info size={16} color={GLUON_BLUE} />+ <span style={{ color: colors.text, fontWeight: 600, fontSize: '13px', flex: 1 }}>+ GluonTS Time Series Forecasting+ </span>+ <span style={{ color: colors.textMuted, fontSize: '11px' }}>+ {expanded ? '▼ Hide guide' : '▶ How to use this'}+ </span>+ </div>++ {expanded && (+ <div style={{ padding: '16px', display: 'flex', flexDirection: 'column', gap: '16px', maxHeight: '300px', overflowY: 'scroll' }}>+ {/* What is it */}+ <div style={{ color: colors.text, fontSize: '12px', lineHeight: 1.5 }}>+ Forecast future values using Amazon's GluonTS deep learning library. Choose from 9 neural network models or 3 statistical baselines.+ </div>++ {/* Two columns */}+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>+ {/* Where to get data */}+ <div style={{ backgroundColor: colors.background, border: '1px solid #333', borderRadius: '4px', padding: '12px' }}>+ <div style={{ color: GLUON_BLUE, fontSize: '11px', fontWeight: 600, marginBottom: '8px', textTransform: 'uppercase' }}>+ Where to Get the Data+ </div>+ <ol style={{ margin: 0, paddingLeft: '18px', color: colors.textMuted, fontSize: '11px', lineHeight: 1.6 }}>+ <li style={{ marginBottom: '4px' }}>Get historical prices from Yahoo Finance or your broker</li>+ <li style={{ marginBottom: '4px' }}>Use closing prices, sales figures, or any time series</li>+ <li style={{ marginBottom: '4px' }}>Need at least 10 data points (30+ recommended)</li>+ <li style={{ marginBottom: '4px' }}>Enter values separated by commas</li>+ </ol>+ </div>++ {/* What you will get */}+ <div style={{ backgroundColor: colors.background, border: '1px solid #333', borderRadius: '4px', padding: '12px' }}>+ <div style={{ color: GLUON_BLUE, fontSize: '11px', fontWeight: 600, marginBottom: '8px', textTransform: 'uppercase' }}>+ Output You Will Get+ </div>+ <ul style={{ margin: 0, paddingLeft: '18px', color: colors.textMuted, fontSize: '11px', lineHeight: 1.6 }}>+ <li style={{ marginBottom: '4px' }}>Mean forecast - Expected future values</li>+ <li style={{ marginBottom: '4px' }}>10-90% quantiles - Uncertainty range</li>+ <li style={{ marginBottom: '4px' }}>Interactive chart with historical + forecast</li>+ <li style={{ marginBottom: '4px' }}>Evaluation metrics (MSE, RMSE, MAE, MAPE)</li>+ </ul>+ </div>+ </div>++ {/* Example use case */}+ <div style={{+ backgroundColor: `${GLUON_BLUE}10`,+ padding: '10px 12px',+ borderRadius: '4px',+ borderLeft: `3px solid ${GLUON_BLUE}`,+ flexShrink: 0,+ }}>+ <div style={{ color: GLUON_BLUE, fontSize: '10px', fontWeight: 600, textTransform: 'uppercase', marginBottom: '4px' }}>+ Example Use Case:+ </div>+ <div style={{ color: colors.text, fontSize: '11px', lineHeight: 1.5 }}>+ You have 30 days of stock prices and want to predict the next 10 days. Use DeepAR for probabilistic forecasts with confidence intervals.+ </div>+ </div>+ </div>+ )}+ </div>+ );+}+const DL_MODELS = [- { id: 'forecast_feedforward', label: 'SimpleFeedForward', desc: 'Basic feedforward neural network' },- { id: 'forecast_deepar', label: 'DeepAR', desc: 'Autoregressive RNN (Amazon)' },- { id: 'forecast_tft', label: 'Temporal Fusion Transformer', desc: 'Attention-based transformer' },- { id: 'forecast_wavenet', label: 'WaveNet', desc: 'Dilated causal convolutions' },- { id: 'forecast_dlinear', label: 'DLinear', desc: 'Decomposition linear model' },- { id: 'forecast_patchtst', label: 'PatchTST', desc: 'Patch time-series transformer' },- { id: 'forecast_tide', label: 'TiDE', desc: 'Time-series dense encoder' },- { id: 'forecast_lagtst', label: 'LagTST', desc: 'Lag-based transformer' },- { id: 'forecast_deepnpts', label: 'DeepNPTS', desc: 'Non-parametric time series' },+ { id: 'forecast_feedforward', label: 'SimpleFeedForward', desc: 'Basic feedforward neural network - fast training, good baseline', category: 'Basic' },+ { id: 'forecast_deepar', label: 'DeepAR', desc: 'Amazon\'s autoregressive RNN - best for probabilistic forecasts', category: 'RNN' },+ { id: 'forecast_tft', label: 'Temporal Fusion Transformer', desc: 'Attention-based transformer - handles multiple inputs', category: 'Transformer' },+ { id: 'forecast_wavenet', label: 'WaveNet', desc: 'Dilated causal convolutions - captures long-range patterns', category: 'CNN' },+ { id: 'forecast_dlinear', label: 'DLinear', desc: 'Decomposition linear model - simple but effective', category: 'Linear' },+ { id: 'forecast_patchtst', label: 'PatchTST', desc: 'Patch time-series transformer - state-of-the-art accuracy', category: 'Transformer' },+ { id: 'forecast_tide', label: 'TiDE', desc: 'Time-series dense encoder - efficient for long sequences', category: 'MLP' },+ { id: 'forecast_lagtst', label: 'LagTST', desc: 'Lag-based transformer - uses lagged features', category: 'Transformer' },+ { id: 'forecast_deepnpts', label: 'DeepNPTS', desc: 'Non-parametric time series - flexible distributions', category: 'Advanced' },];const BASELINE_MODELS = [- { id: 'predict_seasonal_naive', label: 'Seasonal Naive', desc: 'Repeats last season' },- { id: 'predict_mean', label: 'Mean', desc: 'Predicts historical mean' },- { id: 'predict_constant', label: 'Constant', desc: 'Predicts a fixed value' },+ { id: 'predict_seasonal_naive', label: 'Seasonal Naive', desc: 'Repeats last season - good baseline for seasonal data', category: 'Statistical' },+ { id: 'predict_mean', label: 'Mean', desc: 'Predicts historical mean - simplest baseline', category: 'Statistical' },+ { id: 'predict_constant', label: 'Constant', desc: 'Predicts last value - random walk baseline', category: 'Statistical' },];export function GluonTSPanel() {- const { colors, fontFamily } = useTerminalTheme();- // Derived colors for properties not in ColorTheme- const borderColor = colors.textMuted;- const textSecondary = colors.textMuted;+ const { colors } = useTerminalTheme();// Config state- const [dataInput, setDataInput] = useState('100,102,101,105,108,107,110,112,115,118,120,119,122,125,128,130,127,132,135,138,140,142,145,148,150');+ const [dataInput, setDataInput] = useState('100, 102, 101, 105, 108, 107, 110, 112, 115, 118, 120, 119, 122, 125, 128, 130, 127, 132, 135, 138, 140, 142, 145, 148, 150');const [selectedModel, setSelectedModel] = useState('forecast_deepar');- const [predictionLength, setPredictionLength] = useState(10);- const [epochs, setEpochs] = useState(5);+ const [predictionLength, setPredictionLength] = useState('10');+ const [epochs, setEpochs] = useState('5');const [freq, setFreq] = useState('D');// Results state@@ -77,19 +228,20 @@ export function GluonTSPanel() {if (data.length < 10) throw new Error('Need at least 10 data points');const commandName = `gluonts_${selectedModel}`;+ const predLen = parseInt(predictionLength) || 10;+ const ep = parseInt(epochs) || 5;let resultStr: string;- // Commands with freq param vs withoutif (['forecast_feedforward', 'forecast_dlinear'].includes(selectedModel)) {- resultStr = await invoke<string>(commandName, { data, predictionLength, epochs });+ resultStr = await invoke<string>(commandName, { data, predictionLength: predLen, epochs: ep });} else if (selectedModel === 'predict_seasonal_naive') {- resultStr = await invoke<string>(commandName, { data, predictionLength, seasonLength: 7 });+ resultStr = await invoke<string>(commandName, { data, predictionLength: predLen, seasonLength: 7 });} else if (selectedModel === 'predict_mean') {- resultStr = await invoke<string>(commandName, { data, predictionLength });+ resultStr = await invoke<string>(commandName, { data, predictionLength: predLen });} else if (selectedModel === 'predict_constant') {- resultStr = await invoke<string>(commandName, { data, predictionLength, constantValue: data[data.length - 1] });+ resultStr = await invoke<string>(commandName, { data, predictionLength: predLen, constantValue: data[data.length - 1] });} else {- resultStr = await invoke<string>(commandName, { data, predictionLength, freq, epochs });+ resultStr = await invoke<string>(commandName, { data, predictionLength: predLen, freq, epochs: ep });}setForecastResult(JSON.parse(resultStr));@@ -107,9 +259,10 @@ export function GluonTSPanel() {const splitIdx = Math.floor(data.length * 0.8);const trainData = data.slice(0, splitIdx);const testData = data.slice(splitIdx);+ const predLen = parseInt(predictionLength) || 10;const resultStr = await invoke<string>('gluonts_evaluate', {- trainData, testData, predictionLength, freq+ trainData, testData, predictionLength: predLen, freq});setEvalResult(JSON.parse(resultStr));} catch (e: any) {@@ -125,12 +278,10 @@ export function GluonTSPanel() {const data = parseData();const items: any[] = [];- // Historical datadata.forEach((val, i) => {items.push({ idx: i, historical: val, mean: null, q10: null, q90: null });});- // Forecast data (connect to last historical)const lastVal = data[data.length - 1];items[items.length - 1] = {...items[items.length - 1],@@ -156,216 +307,338 @@ export function GluonTSPanel() {const currentModel = allModels.find(m => m.id === selectedModel);const isDL = DL_MODELS.some(m => m.id === selectedModel);+ const inputStyle: React.CSSProperties = {+ backgroundColor: colors.background,+ border: '1px solid #333',+ color: colors.text,+ padding: '8px 10px',+ fontSize: '13px',+ fontFamily: 'monospace',+ width: '100%',+ outline: 'none',+ borderRadius: '2px',+ };++ const labelStyle: React.CSSProperties = {+ color: colors.textMuted,+ fontSize: '11px',+ fontWeight: 600,+ textTransform: 'uppercase' as const,+ letterSpacing: '0.5px',+ marginBottom: '6px',+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ };++ const cardStyle: React.CSSProperties = {+ backgroundColor: colors.background,+ border: '1px solid #333',+ padding: '12px',+ borderRadius: '4px',+ };+return (- <div className="flex flex-col h-full gap-3 p-3" style={{ fontFamily }}>- {/* Header */}- <div className="flex items-center justify-between px-3 py-2 rounded" style={{ backgroundColor: colors.panel, border: `1px solid ${borderColor}` }}>- <div className="flex items-center gap-2">- <Brain size={16} style={{ color: colors.primary }} />- <span className="font-bold text-xs tracking-wider" style={{ color: colors.text }}>GLUONTS TIME SERIES FORECASTING</span>- </div>- <span className="text-xs" style={{ color: textSecondary }}>9 DL Models + 3 Baselines</span>+ <div style={{ height: '100%', display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>+ {/* Mode Tabs - Header */}+ <div+ style={{+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ padding: '8px 12px',+ backgroundColor: colors.panel,+ borderBottom: '1px solid #333',+ }}+ >+ <Brain size={16} color={GLUON_BLUE} />+ <span style={{ color: colors.text, fontWeight: 700, fontSize: '12px', letterSpacing: '0.5px' }}>+ GLUONTS FORECASTING+ </span>+ <span style={{ color: colors.textMuted, fontSize: '11px', marginLeft: 'auto' }}>+ {parseData().length} data points | {currentModel?.category || 'Model'}+ </span></div>- {/* Main Grid */}- <div className="grid grid-cols-3 gap-3 flex-1 min-h-0">- {/* LEFT: Config */}- <div className="flex flex-col gap-3" style={{ overflow: 'auto' }}>- {/* Data Input */}- <div className="p-3 rounded" style={{ backgroundColor: colors.panel, border: `1px solid ${borderColor}` }}>- <label className="block text-xs font-bold mb-1 tracking-wider" style={{ color: textSecondary }}>TIME SERIES DATA (comma-separated)</label>- <textarea- value={dataInput}- onChange={(e) => setDataInput(e.target.value)}- rows={3}- className="w-full p-2 rounded text-xs"- style={{ backgroundColor: colors.background, color: colors.text, border: `1px solid ${borderColor}`, fontFamily, resize: 'vertical' }}- />- <div className="text-xs mt-1" style={{ color: textSecondary }}>- {parseData().length} data points+ {/* Content Area */}+ <div style={{ flex: 1, overflow: 'auto', padding: '12px', display: 'flex', flexDirection: 'column', gap: '12px' }}>+ {/* How to Use Guide */}+ <HowToUsePanel />++ {/* Main Grid: Inputs Left, Results Right */}+ <div style={{ display: 'grid', gridTemplateColumns: '350px 1fr', gap: '16px', flex: 1, minHeight: 0 }}>+ {/* LEFT: Configuration */}+ <div style={{ display: 'flex', flexDirection: 'column', gap: '12px', overflowY: 'auto' }}>+ {/* Time Series Data Input */}+ <div style={cardStyle}>+ <div style={labelStyle}>+ <span>Time Series Data</span>+ <TooltipHelp text="Enter your historical values separated by commas. These can be stock prices, sales figures, temperatures, or any sequential data." />+ </div>+ <textarea+ value={dataInput}+ onChange={(e) => setDataInput(e.target.value)}+ rows={3}+ style={{ ...inputStyle, resize: 'vertical' }}+ placeholder="100, 102, 105, 108, 110, ..."+ />+ <div style={{ color: colors.textMuted, fontSize: '10px', marginTop: '4px' }}>+ {parseData().length} data points detected (minimum 10 required)+ </div></div>- </div>- {/* Model Selector */}- <div className="p-3 rounded" style={{ backgroundColor: colors.panel, border: `1px solid ${borderColor}` }}>- <label className="block text-xs font-bold mb-1 tracking-wider" style={{ color: textSecondary }}>MODEL</label>- <select- value={selectedModel}- onChange={(e) => setSelectedModel(e.target.value)}- className="w-full p-2 rounded text-xs"- style={{ backgroundColor: colors.background, color: colors.text, border: `1px solid ${borderColor}`, fontFamily }}- >- <optgroup label="Deep Learning">- {DL_MODELS.map(m => <option key={m.id} value={m.id}>{m.label}</option>)}- </optgroup>- <optgroup label="Baselines">- {BASELINE_MODELS.map(m => <option key={m.id} value={m.id}>{m.label}</option>)}- </optgroup>- </select>- {currentModel && (- <div className="text-xs mt-1" style={{ color: colors.accent }}>{currentModel.desc}</div>- )}- </div>+ {/* Model Selection */}+ <div style={cardStyle}>+ <div style={labelStyle}>+ <span>Forecasting Model</span>+ <TooltipHelp text="Deep Learning models learn patterns from data. Baselines are simple statistical methods for comparison." />+ </div>+ <select+ value={selectedModel}+ onChange={(e) => setSelectedModel(e.target.value)}+ style={inputStyle}+ >+ <optgroup label="Deep Learning Models">+ {DL_MODELS.map(m => <option key={m.id} value={m.id}>{m.label}</option>)}+ </optgroup>+ <optgroup label="Statistical Baselines">+ {BASELINE_MODELS.map(m => <option key={m.id} value={m.id}>{m.label}</option>)}+ </optgroup>+ </select>+ {currentModel && (+ <div style={{+ color: GLUON_BLUE,+ fontSize: '11px',+ marginTop: '6px',+ padding: '8px',+ backgroundColor: `${GLUON_BLUE}10`,+ borderRadius: '4px',+ borderLeft: `2px solid ${GLUON_BLUE}`,+ }}>+ {currentModel.desc}+ </div>+ )}+ </div>- {/* Parameters */}- <div className="p-3 rounded" style={{ backgroundColor: colors.panel, border: `1px solid ${borderColor}` }}>- <label className="block text-xs font-bold mb-2 tracking-wider" style={{ color: textSecondary }}>PARAMETERS</label>- <div className="grid grid-cols-2 gap-2">- <div>- <label className="block text-xs mb-1" style={{ color: textSecondary }}>Prediction Length</label>- <input type="number" value={predictionLength} onChange={(e) => setPredictionLength(parseInt(e.target.value) || 10)}- className="w-full p-1.5 rounded text-xs" style={{ backgroundColor: colors.background, color: colors.text, border: `1px solid ${borderColor}`, fontFamily }} />+ {/* Parameters */}+ <div style={cardStyle}>+ <div style={labelStyle}>+ <span>Parameters</span></div>- {isDL && (+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}><div>- <label className="block text-xs mb-1" style={{ color: textSecondary }}>Epochs</label>- <input type="number" value={epochs} onChange={(e) => setEpochs(parseInt(e.target.value) || 5)}- className="w-full p-1.5 rounded text-xs" style={{ backgroundColor: colors.background, color: colors.text, border: `1px solid ${borderColor}`, fontFamily }} />+ <div style={{ ...labelStyle, fontSize: '10px', marginBottom: '4px' }}>+ <span>Prediction Length</span>+ <TooltipHelp text="How many future time steps to predict. E.g., 10 for next 10 days if using daily data." />+ </div>+ <input+ type="number"+ value={predictionLength}+ onChange={(e) => setPredictionLength(e.target.value)}+ style={inputStyle}+ placeholder="10"+ /></div>- )}- <div>- <label className="block text-xs mb-1" style={{ color: textSecondary }}>Frequency</label>- <select value={freq} onChange={(e) => setFreq(e.target.value)}- className="w-full p-1.5 rounded text-xs" style={{ backgroundColor: colors.background, color: colors.text, border: `1px solid ${borderColor}`, fontFamily }}>- <option value="D">Daily</option>- <option value="W">Weekly</option>- <option value="M">Monthly</option>- <option value="h">Hourly</option>- </select>+ <div>+ <div style={{ ...labelStyle, fontSize: '10px', marginBottom: '4px' }}>+ <span>Frequency</span>+ <TooltipHelp text="Time interval between data points. Must match your input data frequency." />+ </div>+ <select value={freq} onChange={(e) => setFreq(e.target.value)} style={inputStyle}>+ <option value="D">Daily</option>+ <option value="W">Weekly</option>+ <option value="M">Monthly</option>+ <option value="h">Hourly</option>+ </select>+ </div>+ {isDL && (+ <div style={{ gridColumn: '1 / -1' }}>+ <div style={{ ...labelStyle, fontSize: '10px', marginBottom: '4px' }}>+ <span>Training Epochs</span>+ <TooltipHelp text="Number of times to train on the data. More epochs = better fit but slower. Start with 5-10." />+ </div>+ <input+ type="number"+ value={epochs}+ onChange={(e) => setEpochs(e.target.value)}+ style={inputStyle}+ placeholder="5"+ />+ </div>+ )}</div></div>++ {/* Action Buttons */}+ <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>+ <button+ onClick={runForecast}+ disabled={loading}+ style={{+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ gap: '6px',+ padding: '10px 16px',+ backgroundColor: loading ? `${GLUON_BLUE}60` : GLUON_BLUE,+ color: '#fff',+ border: 'none',+ borderRadius: '4px',+ cursor: loading ? 'not-allowed' : 'pointer',+ fontSize: '12px',+ fontWeight: 600,+ }}+ >+ {loading ? <RefreshCw size={14} className="animate-spin" /> : <Play size={14} />}+ {loading ? 'RUNNING...' : 'RUN FORECAST'}+ </button>+ <button+ onClick={runEvaluation}+ disabled={loading}+ style={{+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ gap: '6px',+ padding: '10px 16px',+ backgroundColor: 'transparent',+ color: loading ? colors.textMuted : GLUON_BLUE,+ border: `1px solid ${loading ? '#333' : GLUON_BLUE}`,+ borderRadius: '4px',+ cursor: loading ? 'not-allowed' : 'pointer',+ fontSize: '12px',+ fontWeight: 600,+ }}+ >+ <BarChart3 size={14} />+ EVALUATE (80/20 SPLIT)+ </button>+ </div></div>- {/* Buttons */}- <div className="flex flex-col gap-2">- <button onClick={runForecast} disabled={loading}- className="w-full flex items-center justify-center gap-2 py-2 rounded font-bold text-xs tracking-wider"- style={{- backgroundColor: loading ? borderColor : colors.primary,- color: colors.background,- opacity: loading ? 0.6 : 1,- cursor: loading ? 'not-allowed' : 'pointer',- border: 'none', fontFamily,- }}>- <Play size={12} />- {loading ? 'RUNNING...' : 'RUN FORECAST'}- </button>- <button onClick={runEvaluation} disabled={loading}- className="w-full flex items-center justify-center gap-2 py-2 rounded font-bold text-xs tracking-wider"- style={{- backgroundColor: 'transparent',- color: loading ? textSecondary : colors.accent,- border: `1px solid ${loading ? borderColor : colors.accent}`,- opacity: loading ? 0.6 : 1,- cursor: loading ? 'not-allowed' : 'pointer',- fontFamily,+ {/* RIGHT: Results */}+ <div style={{ display: 'flex', flexDirection: 'column', gap: '12px', overflowY: 'auto' }}>+ {/* Error */}+ {error && (+ <div style={{+ display: 'flex',+ alignItems: 'flex-start',+ gap: '8px',+ padding: '12px',+ backgroundColor: `${colors.alert}15`,+ border: `1px solid ${colors.alert}`,+ borderRadius: '4px',}}>- <BarChart3 size={12} />- EVALUATE (80/20 SPLIT)- </button>- </div>- </div>+ <AlertCircle size={14} color={colors.alert} style={{ flexShrink: 0, marginTop: 2 }} />+ <div style={{ color: colors.alert, fontSize: '12px', fontFamily: 'monospace' }}>{error}</div>+ </div>+ )}- {/* CENTER + RIGHT: Results */}- <div className="col-span-2 flex flex-col gap-3" style={{ overflow: 'auto' }}>- {/* Error */}- {error && (- <div className="flex items-center gap-2 p-3 rounded" style={{ backgroundColor: `${colors.alert}20`, border: `1px solid ${colors.alert}` }}>- <AlertCircle size={14} style={{ color: colors.alert }} />- <span className="text-xs" style={{ color: colors.alert }}>{error}</span>- </div>- )}-- {/* Forecast Chart */}- {forecastResult && (- <div className="p-3 rounded" style={{ backgroundColor: colors.panel, border: `1px solid ${borderColor}` }}>- <div className="flex items-center justify-between mb-2">- <div className="flex items-center gap-2">- <TrendingUp size={14} style={{ color: colors.primary }} />- <span className="font-bold text-xs tracking-wider" style={{ color: colors.text }}>- {forecastResult.model} FORECAST+ {/* Forecast Chart */}+ {forecastResult && (+ <div style={cardStyle}>+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '12px' }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <TrendingUp size={14} color={GLUON_BLUE} />+ <span style={{ color: colors.text, fontWeight: 600, fontSize: '12px' }}>+ {forecastResult.model} FORECAST+ </span>+ </div>+ <span style={{ color: colors.textMuted, fontSize: '11px' }}>+ {forecastResult.prediction_length} steps ahead</span></div>- <span className="text-xs" style={{ color: textSecondary }}>- {forecastResult.prediction_length} steps ahead- </span>- </div>- <ResponsiveContainer width="100%" height={280}>- <AreaChart data={buildChartData()}>- <CartesianGrid strokeDasharray="3 3" stroke={borderColor} strokeOpacity={0.3} />- <XAxis dataKey="idx" stroke={textSecondary} tick={{ fill: textSecondary, fontSize: 9 }} />- <YAxis stroke={textSecondary} tick={{ fill: textSecondary, fontSize: 9 }} />- <Tooltip- contentStyle={{ backgroundColor: colors.panel, border: `1px solid ${colors.accent}`, borderRadius: '2px', fontSize: 10 }}- labelStyle={{ color: colors.accent }}- />- <Area type="monotone" dataKey="q90" stackId="1" stroke="none" fill={colors.accent} fillOpacity={0.1} />- <Area type="monotone" dataKey="q10" stackId="2" stroke="none" fill={colors.panel} fillOpacity={1} />- <Line type="monotone" dataKey="historical" stroke={colors.text} strokeWidth={1.5} dot={false} connectNulls={false} />- <Line type="monotone" dataKey="mean" stroke={colors.primary} strokeWidth={2} dot={false} connectNulls={false} />- </AreaChart>- </ResponsiveContainer>- <div className="flex gap-4 mt-2 text-xs" style={{ color: textSecondary }}>- <span><span style={{ color: colors.text }}>---</span> Historical</span>- <span><span style={{ color: colors.primary }}>---</span> Forecast Mean</span>- <span><span style={{ color: colors.accent, opacity: 0.3 }}>|||</span> 10-90% Quantile</span>+ <ResponsiveContainer width="100%" height={250}>+ <AreaChart data={buildChartData()}>+ <CartesianGrid strokeDasharray="3 3" stroke="#333" strokeOpacity={0.5} />+ <XAxis dataKey="idx" stroke={colors.textMuted} tick={{ fill: colors.textMuted, fontSize: 10 }} />+ <YAxis stroke={colors.textMuted} tick={{ fill: colors.textMuted, fontSize: 10 }} />+ <Tooltip+ contentStyle={{ backgroundColor: colors.background, border: `1px solid ${GLUON_BLUE}`, borderRadius: '4px', fontSize: 11 }}+ labelStyle={{ color: GLUON_BLUE }}+ />+ <Area type="monotone" dataKey="q90" stackId="1" stroke="none" fill={GLUON_BLUE} fillOpacity={0.15} />+ <Area type="monotone" dataKey="q10" stackId="2" stroke="none" fill={colors.background} fillOpacity={1} />+ <Line type="monotone" dataKey="historical" stroke={colors.text} strokeWidth={1.5} dot={false} connectNulls={false} />+ <Line type="monotone" dataKey="mean" stroke={GLUON_BLUE} strokeWidth={2} dot={false} connectNulls={false} />+ </AreaChart>+ </ResponsiveContainer>+ <div style={{ display: 'flex', gap: '16px', marginTop: '8px', fontSize: '11px', color: colors.textMuted }}>+ <span><span style={{ color: colors.text }}>---</span> Historical</span>+ <span><span style={{ color: GLUON_BLUE }}>---</span> Forecast Mean</span>+ <span><span style={{ color: GLUON_BLUE, opacity: 0.3 }}>|||</span> 10-90% Confidence</span>+ </div></div>- </div>- )}-- {/* Forecast Values Table */}- {forecastResult && (- <div className="p-3 rounded" style={{ backgroundColor: colors.panel, border: `1px solid ${borderColor}` }}>- <span className="font-bold text-xs tracking-wider" style={{ color: textSecondary }}>FORECAST VALUES</span>- <div className="grid grid-cols-5 gap-1 mt-2 text-xs" style={{ color: textSecondary }}>- <span className="font-bold">Step</span>- <span className="font-bold">Q10</span>- <span className="font-bold">Mean</span>- <span className="font-bold">Q50</span>- <span className="font-bold">Q90</span>+ )}++ {/* Forecast Values Table */}+ {forecastResult && (+ <div style={cardStyle}>+ <div style={{ ...labelStyle, color: GLUON_BLUE, marginBottom: '8px' }}>FORECAST VALUES</div>+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '4px', fontSize: '11px' }}>+ <span style={{ color: colors.textMuted, fontWeight: 600, padding: '4px 0' }}>Step</span>+ <span style={{ color: colors.textMuted, fontWeight: 600, padding: '4px 0' }}>Q10</span>+ <span style={{ color: colors.textMuted, fontWeight: 600, padding: '4px 0' }}>Mean</span>+ <span style={{ color: colors.textMuted, fontWeight: 600, padding: '4px 0' }}>Q50</span>+ <span style={{ color: colors.textMuted, fontWeight: 600, padding: '4px 0' }}>Q90</span>+ </div>+ <div style={{ maxHeight: '150px', overflowY: 'auto' }}>+ {forecastResult.mean.map((val, i) => (+ <div key={i} style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '4px', padding: '4px 0', borderBottom: '1px solid #222', fontSize: '11px' }}>+ <span style={{ color: colors.textMuted }}>t+{i + 1}</span>+ <span style={{ color: colors.warning }}>{forecastResult.quantiles['0.1'][i]?.toFixed(2)}</span>+ <span style={{ color: GLUON_BLUE, fontWeight: 700 }}>{val.toFixed(2)}</span>+ <span style={{ color: colors.accent }}>{forecastResult.quantiles['0.5'][i]?.toFixed(2)}</span>+ <span style={{ color: colors.warning }}>{forecastResult.quantiles['0.9'][i]?.toFixed(2)}</span>+ </div>+ ))}+ </div></div>- {forecastResult.mean.map((val, i) => (- <div key={i} className="grid grid-cols-5 gap-1 py-0.5 text-xs" style={{ borderBottom: `1px solid ${borderColor}` }}>- <span style={{ color: textSecondary }}>t+{i + 1}</span>- <span style={{ color: colors.warning }}>{forecastResult.quantiles['0.1'][i]?.toFixed(2)}</span>- <span style={{ color: colors.primary, fontWeight: 700 }}>{val.toFixed(2)}</span>- <span style={{ color: colors.accent }}>{forecastResult.quantiles['0.5'][i]?.toFixed(2)}</span>- <span style={{ color: colors.warning }}>{forecastResult.quantiles['0.9'][i]?.toFixed(2)}</span>+ )}++ {/* Evaluation Results */}+ {evalResult && (+ <div style={cardStyle}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '12px' }}>+ <BarChart3 size={14} color={colors.success} />+ <span style={{ color: colors.text, fontWeight: 600, fontSize: '12px' }}>EVALUATION METRICS</span>+ <span style={{ color: colors.textMuted, fontSize: '11px' }}>({evalResult.num_forecasts} forecasts)</span>+ </div>+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '8px' }}>+ {Object.entries(evalResult.aggregate_metrics).map(([key, val]) => (+ <div key={key} style={{ backgroundColor: colors.panel, padding: '10px', borderRadius: '4px', border: '1px solid #333' }}>+ <div style={{ fontSize: '10px', color: colors.textMuted, marginBottom: '4px', fontWeight: 600 }}>{key}</div>+ <div style={{ fontSize: '14px', color: GLUON_BLUE, fontWeight: 700 }}>{val.toFixed(4)}</div>+ </div>+ ))}</div>- ))}- </div>- )}-- {/* Evaluation Results */}- {evalResult && (- <div className="p-3 rounded" style={{ backgroundColor: colors.panel, border: `1px solid ${borderColor}` }}>- <div className="flex items-center gap-2 mb-2">- <BarChart3 size={14} style={{ color: colors.success }} />- <span className="font-bold text-xs tracking-wider" style={{ color: colors.text }}>EVALUATION METRICS</span>- <span className="text-xs" style={{ color: textSecondary }}>({evalResult.num_forecasts} forecasts)</span></div>- <div className="grid grid-cols-4 gap-2">- {Object.entries(evalResult.aggregate_metrics).map(([key, val]) => (- <div key={key} className="p-2 rounded" style={{ backgroundColor: colors.background }}>- <div className="text-xs font-bold mb-1" style={{ color: textSecondary }}>{key}</div>- <div className="text-sm font-bold" style={{ color: colors.accent }}>{val.toFixed(4)}</div>+ )}++ {/* Empty state */}+ {!forecastResult && !evalResult && !error && !loading && (+ <div style={{+ flex: 1,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ backgroundColor: colors.panel,+ border: '1px solid #333',+ borderRadius: '4px',+ minHeight: '200px',+ }}>+ <div style={{ textAlign: 'center' }}>+ <Zap size={32} color="#333" style={{ marginBottom: '8px' }} />+ <div style={{ color: colors.textMuted, fontSize: '12px' }}>+ Enter time series data and click RUN FORECAST+ </div>+ <div style={{ color: colors.textMuted, fontSize: '11px', marginTop: '4px' }}>+ Or use EVALUATE to test model accuracy on your data</div>- ))}- </div>- </div>- )}-- {/* Empty state */}- {!forecastResult && !evalResult && !error && !loading && (- <div className="flex-1 flex items-center justify-center rounded" style={{ backgroundColor: colors.panel, border: `1px solid ${borderColor}` }}>- <div className="text-center">- <Zap size={32} style={{ color: borderColor, margin: '0 auto 8px' }} />- <div className="text-xs" style={{ color: textSecondary }}>- Select a model and click RUN FORECAST to generate predictions</div></div>- </div>- )}+ )}+ </div></div></div></div>diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/GsQuantPanel.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/GsQuantPanel.tsxindex 3ad42ebbc..aa16c8509 100644--- a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/GsQuantPanel.tsx+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/GsQuantPanel.tsx@@ -1,6 +1,12 @@/*** GS Quant Panel - Goldman Sachs Quant Analytics* Covers: Risk Metrics, Portfolio Analytics, Greeks, VaR, Stress Testing, Backtesting, Statistics+ *+ * User-friendly interface with:+ * - Clear input labels with units (%, $, months)+ * - Tooltips explaining each field+ * - Example values for guidance+ * - Percentage inputs converted to decimals internally*/import React, { useState, useCallback } from 'react';@@ -19,11 +25,403 @@ import {PieChart,LineChart,BarChart3,+ HelpCircle,+ Info,} from 'lucide-react';import { useTerminalTheme } from '@/contexts/ThemeContext';const GS_PURPLE = '#6F42C1';+// Tooltip component for help text+interface TooltipProps {+ text: string;+ children: React.ReactNode;+}++function Tooltip({ text, children }: TooltipProps) {+ const [show, setShow] = useState(false);+ const [position, setPosition] = useState({ top: 0, left: 0 });+ const triggerRef = React.useRef<HTMLDivElement>(null);+ const { colors } = useTerminalTheme();++ const handleMouseEnter = () => {+ if (triggerRef.current) {+ const rect = triggerRef.current.getBoundingClientRect();+ setPosition({+ top: rect.top - 10,+ left: rect.left + rect.width / 2,+ });+ }+ setShow(true);+ };++ return (+ <div+ ref={triggerRef}+ style={{ position: 'relative', display: 'inline-flex', alignItems: 'center' }}+ onMouseEnter={handleMouseEnter}+ onMouseLeave={() => setShow(false)}+ >+ {children}+ {show && (+ <div+ style={{+ position: 'fixed',+ zIndex: 9999,+ padding: '10px 14px',+ backgroundColor: '#1a1a2e',+ border: `1px solid ${GS_PURPLE}60`,+ borderRadius: '6px',+ color: colors.text,+ fontSize: '12px',+ lineHeight: 1.5,+ whiteSpace: 'normal',+ width: '260px',+ textAlign: 'left',+ boxShadow: '0 8px 24px rgba(0,0,0,0.5)',+ top: position.top,+ left: position.left,+ transform: 'translate(-50%, -100%)',+ }}+ >+ {text}+ </div>+ )}+ </div>+ );+}++// Input field with label, unit, help tooltip, and example+interface InputFieldProps {+ label: string;+ value: string;+ onChange: (value: string) => void;+ unit?: string;+ help?: string;+ example?: string;+ placeholder?: string;+ type?: 'text' | 'number' | 'textarea';+ rows?: number;+ style?: React.CSSProperties;+}++function InputField({ label, value, onChange, unit, help, example, placeholder, type = 'text', rows, style }: InputFieldProps) {+ const { colors } = useTerminalTheme();++ const inputStyle: React.CSSProperties = {+ backgroundColor: colors.background,+ border: `1px solid #333`,+ color: colors.text,+ padding: '8px 10px',+ paddingRight: unit ? '40px' : '10px',+ fontSize: '13px',+ fontFamily: 'monospace',+ width: '100%',+ outline: 'none',+ borderRadius: '2px',+ };++ const labelStyle: React.CSSProperties = {+ color: colors.textMuted,+ fontSize: '11px',+ fontWeight: 600,+ textTransform: 'uppercase' as const,+ letterSpacing: '0.5px',+ marginBottom: '6px',+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ };++ return (+ <div style={style}>+ <div style={labelStyle}>+ <span>{label}</span>+ {unit && <span style={{ color: GS_PURPLE, fontWeight: 400 }}>({unit})</span>}+ {help && (+ <Tooltip text={help}>+ <HelpCircle size={12} color={colors.textMuted} style={{ cursor: 'help' }} />+ </Tooltip>+ )}+ </div>+ <div style={{ position: 'relative' }}>+ {type === 'textarea' ? (+ <textarea+ value={value}+ onChange={e => onChange(e.target.value)}+ rows={rows || 3}+ style={{ ...inputStyle, resize: 'vertical' }}+ placeholder={placeholder || example}+ />+ ) : (+ <input+ type={type}+ value={value}+ onChange={e => onChange(e.target.value)}+ style={inputStyle}+ placeholder={placeholder || example}+ />+ )}+ {unit && type !== 'textarea' && (+ <span+ style={{+ position: 'absolute',+ right: '10px',+ top: '50%',+ transform: 'translateY(-50%)',+ color: colors.textMuted,+ fontSize: '11px',+ pointerEvents: 'none',+ }}+ >+ {unit}+ </span>+ )}+ </div>+ {example && (+ <div style={{ color: colors.textMuted, fontSize: '10px', marginTop: '4px', fontStyle: 'italic' }}>+ Example: {example}+ </div>+ )}+ </div>+ );+}++// Comprehensive "How to Use" panel with input guide and output preview+interface HowToUsePanelProps {+ mode: AnalysisMode;+}++function HowToUsePanel({ mode }: HowToUsePanelProps) {+ const { colors } = useTerminalTheme();+ const [expanded, setExpanded] = useState(true);++ const guides: Record<AnalysisMode, {+ title: string;+ whatIsIt: string;+ whereToGetData: string[];+ whatYouWillGet: string[];+ exampleUseCase: string;+ }> = {+ risk_metrics: {+ title: 'Risk Metrics Analysis',+ whatIsIt: 'Calculate how risky your investment is based on its historical price movements.',+ whereToGetData: [+ 'Go to Yahoo Finance, enter a stock ticker (e.g., AAPL)',+ 'Download historical prices (1 year of daily data recommended)',+ 'Calculate daily returns: (Today\'s Price - Yesterday\'s Price) / Yesterday\'s Price × 100',+ 'Or use our Equity Research tab to get returns automatically',+ ],+ whatYouWillGet: [+ 'Sharpe Ratio - Risk-adjusted return (>1 is good, >2 is excellent)',+ 'Sortino Ratio - Like Sharpe but only penalizes downside risk',+ 'Max Drawdown - Largest peak-to-trough decline (worst case loss)',+ 'Volatility - How much the price swings (annualized)',+ 'VaR 95%/99% - Maximum expected loss at 95%/99% confidence',+ ],+ exampleUseCase: 'You want to compare AAPL vs MSFT - which stock has better risk-adjusted returns?',+ },+ portfolio: {+ title: 'Portfolio vs Benchmark Analysis',+ whatIsIt: 'Compare how your portfolio performs against a benchmark like S&P 500.',+ whereToGetData: [+ 'Your Portfolio Returns: Calculate daily % change of your portfolio value',+ 'Benchmark Returns: Get S&P 500 (^GSPC) daily returns from Yahoo Finance',+ 'Both should cover the same date range',+ 'Make sure both have the same number of data points',+ ],+ whatYouWillGet: [+ 'Alpha - Excess return over benchmark (positive = outperforming)',+ 'Beta - Sensitivity to market movements (1 = moves with market)',+ 'Information Ratio - Skill of active management (>0.5 is good)',+ 'Tracking Error - How much your returns deviate from benchmark',+ 'Up/Down Capture - Performance in up vs down markets',+ ],+ exampleUseCase: 'Is your stock picks portfolio beating the S&P 500 after adjusting for risk?',+ },+ greeks: {+ title: 'Options Greeks Calculator',+ whatIsIt: 'Calculate option price sensitivities using Black-Scholes model.',+ whereToGetData: [+ 'Spot Price: Current stock price (e.g., AAPL at $175)',+ 'Strike Price: The exercise price of your option',+ 'Expiry: Time until expiration in months',+ 'Volatility: Look up IV on options chain or use historical vol (20-40% typical)',+ 'Risk-Free Rate: Current T-bill rate (~5% as of 2024)',+ ],+ whatYouWillGet: [+ 'Delta - How much option price moves per $1 stock move',+ 'Gamma - Rate of change of Delta',+ 'Theta - Time decay per day (usually negative)',+ 'Vega - Sensitivity to volatility changes',+ 'Rho - Sensitivity to interest rate changes',+ 'Option Price - Theoretical fair value',+ ],+ exampleUseCase: 'You\'re buying AAPL $180 calls expiring in 3 months. What\'s the fair price and Greeks?',+ },+ var_analysis: {+ title: 'Value at Risk (VaR) Analysis',+ whatIsIt: 'Estimate the maximum potential loss over a time period at a confidence level.',+ whereToGetData: [+ 'Historical daily returns of your portfolio/asset',+ 'Position value: Total $ amount invested',+ 'Confidence level: 95% (standard) or 99% (conservative)',+ ],+ whatYouWillGet: [+ 'Parametric VaR - Assumes normal distribution of returns',+ 'Historical VaR - Based on actual historical percentiles',+ 'Monte Carlo VaR - Simulated using 10,000 scenarios',+ 'CVaR (Expected Shortfall) - Average loss when VaR is exceeded',+ 'Dollar VaR - Actual $ amount at risk',+ ],+ exampleUseCase: 'You have $1M in stocks. What\'s the worst-case daily loss you should expect 95% of the time?',+ },+ stress_test: {+ title: 'Stress Test Scenarios',+ whatIsIt: 'See how your portfolio would perform in historical crisis events.',+ whereToGetData: [+ 'Your portfolio\'s historical daily returns',+ 'Total position value in $',+ 'The system applies 9 built-in stress scenarios automatically',+ ],+ whatYouWillGet: [+ '2008 Financial Crisis scenario',+ 'COVID-19 March 2020 crash',+ 'Interest Rate Shock (+200bps)',+ 'Equity Market Crash (-20%)',+ 'Currency Crisis scenario',+ 'Commodity Shock scenario',+ 'And 3 more stress scenarios',+ ],+ exampleUseCase: 'If 2008 happens again, how much would your current portfolio lose?',+ },+ backtest: {+ title: 'Strategy Backtesting',+ whatIsIt: 'Test how different trading strategies would have performed historically.',+ whereToGetData: [+ 'Historical returns of the asset you want to trade',+ 'Choose initial capital amount',+ 'Select strategy: Buy & Hold, Momentum, Mean Reversion, or Rebalancing',+ 'Set lookback period for signal calculation',+ ],+ whatYouWillGet: [+ 'Total Return - Overall % gain/loss',+ 'Sharpe Ratio - Risk-adjusted performance',+ 'Max Drawdown - Worst peak-to-trough decline',+ 'Win Rate - % of profitable trades',+ 'Comparison across strategies',+ ],+ exampleUseCase: 'Would a 20-day momentum strategy beat buy-and-hold for Bitcoin?',+ },+ statistics: {+ title: 'Descriptive Statistics',+ whatIsIt: 'Calculate comprehensive statistics for any numeric dataset.',+ whereToGetData: [+ 'Any comma-separated numbers (returns, prices, volumes, etc.)',+ 'For returns analysis, enter daily % changes',+ 'For price analysis, enter raw prices',+ 'More data points = more reliable statistics',+ ],+ whatYouWillGet: [+ 'Mean, Median, Mode - Central tendency measures',+ 'Standard Deviation, Variance - Spread measures',+ 'Skewness - Distribution asymmetry (negative = more losses)',+ 'Kurtosis - Tail thickness (high = more extreme events)',+ 'Percentiles (1st, 5th, 25th, 50th, 75th, 95th, 99th)',+ 'Min, Max, Range',+ ],+ exampleUseCase: 'Analyze the distribution of your trading returns to understand if they\'re normally distributed.',+ },+ };++ const guide = guides[mode];++ return (+ <div+ style={{+ backgroundColor: `${GS_PURPLE}08`,+ border: `1px solid ${GS_PURPLE}25`,+ borderRadius: '6px',+ marginBottom: '16px',+ }}+ >+ {/* Header */}+ <div+ style={{+ display: 'flex',+ alignItems: 'center',+ gap: '10px',+ padding: '12px 16px',+ backgroundColor: `${GS_PURPLE}15`,+ cursor: 'pointer',+ borderBottom: expanded ? `1px solid ${GS_PURPLE}20` : 'none',+ }}+ onClick={() => setExpanded(!expanded)}+ >+ <Info size={16} color={GS_PURPLE} />+ <span style={{ color: colors.text, fontWeight: 600, fontSize: '13px', flex: 1 }}>+ {guide.title}+ </span>+ <span style={{ color: colors.textMuted, fontSize: '11px' }}>+ {expanded ? '▼ Hide guide' : '▶ How to use this'}+ </span>+ </div>++ {expanded && (+ <div style={{ padding: '16px', display: 'flex', flexDirection: 'column', gap: '16px', maxHeight: '300px', overflowY: 'scroll' }}>+ {/* What is it */}+ <div style={{ color: colors.text, fontSize: '12px', lineHeight: 1.5 }}>+ {guide.whatIsIt}+ </div>++ {/* Two columns: Input guide and Output preview */}+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>+ {/* Where to get data */}+ <div style={{ backgroundColor: `${colors.background}`, border: `1px solid #333`, borderRadius: '4px', padding: '12px' }}>+ <div style={{ color: GS_PURPLE, fontSize: '11px', fontWeight: 600, marginBottom: '8px', textTransform: 'uppercase' }}>+ Where to Get the Data+ </div>+ <ol style={{ margin: 0, paddingLeft: '18px', color: colors.textMuted, fontSize: '11px', lineHeight: 1.6 }}>+ {guide.whereToGetData.map((item, i) => (+ <li key={i} style={{ marginBottom: '4px' }}>{item}</li>+ ))}+ </ol>+ </div>++ {/* What you will get */}+ <div style={{ backgroundColor: `${colors.background}`, border: `1px solid #333`, borderRadius: '4px', padding: '12px' }}>+ <div style={{ color: GS_PURPLE, fontSize: '11px', fontWeight: 600, marginBottom: '8px', textTransform: 'uppercase' }}>+ Output You Will Get+ </div>+ <ul style={{ margin: 0, paddingLeft: '18px', color: colors.textMuted, fontSize: '11px', lineHeight: 1.6 }}>+ {guide.whatYouWillGet.map((item, i) => (+ <li key={i} style={{ marginBottom: '4px' }}>{item}</li>+ ))}+ </ul>+ </div>+ </div>++ {/* Example use case */}+ <div style={{+ backgroundColor: `${GS_PURPLE}10`,+ padding: '10px 12px',+ borderRadius: '4px',+ borderLeft: `3px solid ${GS_PURPLE}`,+ flexShrink: 0,+ }}>+ <div style={{ color: GS_PURPLE, fontSize: '10px', fontWeight: 600, textTransform: 'uppercase', marginBottom: '4px' }}>+ Example Use Case:+ </div>+ <div style={{ color: colors.text, fontSize: '11px', lineHeight: 1.5 }}>+ {guide.exampleUseCase}+ </div>+ </div>+ </div>+ )}+ </div>+ );+}+type AnalysisMode = 'risk_metrics' | 'portfolio' | 'greeks' | 'var_analysis' | 'stress_test' | 'backtest' | 'statistics';interface ModeConfig {@@ -31,16 +429,102 @@ interface ModeConfig {label: string;icon: React.ElementType;description: string;+ detailedDescription: string;+ tips: string[];}const MODES: ModeConfig[] = [- { id: 'risk_metrics', label: 'Risk Metrics', icon: Shield, description: 'Volatility, drawdown, Sharpe, Sortino, VaR' },- { id: 'portfolio', label: 'Portfolio Analytics', icon: PieChart, description: 'Alpha, tracking error, capture ratio, information ratio' },- { id: 'greeks', label: 'Greeks', icon: Calculator, description: 'Delta, gamma, vega, theta, rho + higher-order' },- { id: 'var_analysis', label: 'VaR Analysis', icon: Target, description: 'Parametric, historical, Monte Carlo VaR + CVaR' },- { id: 'stress_test', label: 'Stress Test', icon: Zap, description: '9 standard market stress scenarios' },- { id: 'backtest', label: 'Backtest', icon: BarChart3, description: 'Buy-and-hold, momentum, mean-reversion, rebalancing' },- { id: 'statistics', label: 'Statistics', icon: LineChart, description: 'Descriptive statistics, distribution, percentiles' },+ {+ id: 'risk_metrics',+ label: 'Risk Metrics',+ icon: Shield,+ description: 'Calculate volatility, drawdown, Sharpe, Sortino, and VaR ratios',+ detailedDescription: 'Analyze the risk profile of your portfolio or asset returns. Enter historical returns to calculate key risk metrics used by professional investors.',+ tips: [+ 'Enter daily returns as percentages (e.g., 1.5 for +1.5%, -0.8 for -0.8%)',+ 'More data points = more accurate metrics (aim for 20+ returns)',+ 'Risk-free rate is the annual rate (e.g., 5 for 5% annual T-bill rate)',+ 'Sharpe ratio > 1 is good, > 2 is excellent',+ ],+ },+ {+ id: 'portfolio',+ label: 'Portfolio Analytics',+ icon: PieChart,+ description: 'Compare portfolio vs benchmark: alpha, tracking error, information ratio',+ detailedDescription: 'Measure how your portfolio performs relative to a benchmark. Calculates alpha, beta, capture ratios, and other relative performance metrics.',+ tips: [+ 'Enter both portfolio and benchmark returns for the same time periods',+ 'Returns should be in the same format (daily, weekly, or monthly)',+ 'Alpha > 0 means you\'re outperforming the benchmark',+ 'Information ratio > 0.5 indicates skilled active management',+ ],+ },+ {+ id: 'greeks',+ label: 'Options Greeks',+ icon: Calculator,+ description: 'Calculate Delta, Gamma, Vega, Theta, Rho and higher-order Greeks',+ detailedDescription: 'Compute option sensitivities using Black-Scholes model. Essential for options traders to understand position risk and manage hedging.',+ tips: [+ 'Spot & Strike prices should be in the same currency (e.g., $100)',+ 'Expiry is in months (e.g., 3 for 3-month option)',+ 'Volatility is annualized implied volatility in % (e.g., 25 for 25%)',+ 'Delta ranges from 0-1 for calls, 0 to -1 for puts',+ ],+ },+ {+ id: 'var_analysis',+ label: 'VaR Analysis',+ icon: Target,+ description: 'Value at Risk: parametric, historical, and Monte Carlo methods',+ detailedDescription: 'Calculate potential portfolio loss using multiple VaR methodologies. Includes Conditional VaR (CVaR) for tail risk analysis.',+ tips: [+ '95% confidence = expect loss to exceed VaR ~5% of the time',+ '99% confidence is more conservative (used by banks)',+ 'Monte Carlo VaR uses 10,000 simulations for accuracy',+ 'CVaR shows average loss when VaR is exceeded',+ ],+ },+ {+ id: 'stress_test',+ label: 'Stress Test',+ icon: Zap,+ description: 'Simulate portfolio impact across 9 market stress scenarios',+ detailedDescription: 'Test how your portfolio would perform in historical crisis scenarios like 2008 Financial Crisis, COVID crash, and interest rate shocks.',+ tips: [+ 'Scenarios are based on historical market events',+ 'Position value is your total portfolio value in $',+ 'Shows both % drawdown and $ loss for each scenario',+ 'Use this to understand worst-case risks',+ ],+ },+ {+ id: 'backtest',+ label: 'Backtest',+ icon: BarChart3,+ description: 'Test trading strategies: buy-and-hold, momentum, mean-reversion',+ detailedDescription: 'Backtest common trading strategies against historical data. Compare returns, Sharpe ratios, and drawdowns across different approaches.',+ tips: [+ 'Returns are converted to prices internally (starting at $100)',+ 'Lookback period is used for momentum/mean-reversion signals',+ 'Compare strategies to find what works best for your data',+ 'Past performance doesn\'t guarantee future results!',+ ],+ },+ {+ id: 'statistics',+ label: 'Statistics',+ icon: LineChart,+ description: 'Descriptive statistics: mean, std dev, skewness, kurtosis, percentiles',+ detailedDescription: 'Calculate comprehensive descriptive statistics for any dataset. Includes distribution shape analysis and percentile breakdowns.',+ tips: [+ 'Enter any numeric values separated by commas',+ 'Negative skewness = more extreme losses than gains',+ 'High kurtosis = fat tails (more extreme events)',+ 'Percentiles show value distribution breakdown',+ ],+ },];export function GsQuantPanel() {@@ -50,19 +534,25 @@ export function GsQuantPanel() {const [error, setError] = useState<string | null>(null);const [result, setResult] = useState<Record<string, any> | null>(null);- // Common form state- const [returnsInput, setReturnsInput] = useState('0.01, -0.005, 0.008, -0.003, 0.012, -0.007, 0.006, 0.009, -0.004, 0.011, -0.002, 0.007, -0.006, 0.013, -0.001, 0.005, -0.008, 0.010, 0.003, -0.009');- const [benchmarkInput, setBenchmarkInput] = useState('0.008, -0.003, 0.006, -0.002, 0.009, -0.005, 0.004, 0.007, -0.003, 0.008, -0.001, 0.005, -0.004, 0.010, -0.002, 0.003, -0.006, 0.007, 0.002, -0.007');- const [riskFreeRate, setRiskFreeRate] = useState('0.02');- const [confidence, setConfidence] = useState('0.95');+ // Common form state - VALUES ARE IN USER-FRIENDLY PERCENTAGES+ // Returns as percentages (1.0 = 1%, -0.5 = -0.5%)+ const [returnsInput, setReturnsInput] = useState('1.0, -0.5, 0.8, -0.3, 1.2, -0.7, 0.6, 0.9, -0.4, 1.1, -0.2, 0.7, -0.6, 1.3, -0.1, 0.5, -0.8, 1.0, 0.3, -0.9');+ const [benchmarkInput, setBenchmarkInput] = useState('0.8, -0.3, 0.6, -0.2, 0.9, -0.5, 0.4, 0.7, -0.3, 0.8, -0.1, 0.5, -0.4, 1.0, -0.2, 0.3, -0.6, 0.7, 0.2, -0.7');+ // Risk-free rate as percentage (2 = 2% annual)+ const [riskFreeRate, setRiskFreeRate] = useState('2');+ // Confidence as percentage (95 = 95%)+ const [confidence, setConfidence] = useState('95');const [positionValue, setPositionValue] = useState('1000000');- // Greeks form+ // Greeks form - expiry in months, rates/vol in percentagesconst [spot, setSpot] = useState('100');const [strike, setStrike] = useState('100');- const [expiry, setExpiry] = useState('0.25');- const [rate, setRate] = useState('0.05');- const [vol, setVol] = useState('0.2');+ // Expiry in months (3 = 3 months)+ const [expiry, setExpiry] = useState('3');+ // Rate as percentage (5 = 5%)+ const [rate, setRate] = useState('5');+ // Volatility as percentage (20 = 20%)+ const [vol, setVol] = useState('20');const [optionType, setOptionType] = useState('call');// Backtest form@@ -70,6 +560,27 @@ export function GsQuantPanel() {const [initialCapital, setInitialCapital] = useState('100000');const [lookback, setLookback] = useState('20');+ // Helper to convert user-friendly percentage to decimal+ const pctToDecimal = (pct: string): number => {+ const val = parseFloat(pct);+ return isNaN(val) ? 0 : val / 100;+ };++ // Helper to convert months to years+ const monthsToYears = (months: string): number => {+ const val = parseFloat(months);+ return isNaN(val) ? 0.25 : val / 12;+ };++ // Parse comma-separated values, converting from % to decimal+ const parseFloatArrayAsDecimal = (input: string): number[] => {+ return input.split(',')+ .map(s => parseFloat(s.trim()))+ .filter(n => !isNaN(n))+ .map(n => n / 100); // Convert percentage to decimal (1% -> 0.01)+ };++ // Parse comma-separated values as-is (for statistics mode)const parseFloatArray = (input: string): number[] => {return input.split(',').map(s => parseFloat(s.trim())).filter(n => !isNaN(n));};@@ -81,14 +592,17 @@ export function GsQuantPanel() {try {let response: string;- const returns = parseFloatArray(returnsInput);- const benchmark = parseFloatArray(benchmarkInput);+ // Convert user-friendly percentage returns to decimals for API+ const returns = parseFloatArrayAsDecimal(returnsInput);+ const benchmark = parseFloatArrayAsDecimal(benchmarkInput);+ // Convert user-friendly percentage risk-free rate to decimal+ const riskFreeRateDecimal = pctToDecimal(riskFreeRate);switch (mode) {case 'risk_metrics':response = await invoke<string>('gs_quant_risk_metrics', {returns,- riskFreeRate: parseFloat(riskFreeRate) || 0,+ riskFreeRate: riskFreeRateDecimal,});break;@@ -96,7 +610,7 @@ export function GsQuantPanel() {response = await invoke<string>('gs_quant_portfolio_analytics', {returns,benchmarkReturns: benchmark,- riskFreeRate: parseFloat(riskFreeRate) || 0,+ riskFreeRate: riskFreeRateDecimal,});break;@@ -104,9 +618,9 @@ export function GsQuantPanel() {response = await invoke<string>('gs_quant_greeks', {spot: parseFloat(spot),strike: parseFloat(strike),- expiry: parseFloat(expiry),- rate: parseFloat(rate),- vol: parseFloat(vol),+ expiry: monthsToYears(expiry), // Convert months to years+ rate: pctToDecimal(rate), // Convert % to decimal+ vol: pctToDecimal(vol), // Convert % to decimaloptionType,});break;@@ -114,7 +628,7 @@ export function GsQuantPanel() {case 'var_analysis':response = await invoke<string>('gs_quant_var_analysis', {returns,- confidence: parseFloat(confidence) || 0.95,+ confidence: pctToDecimal(confidence) || 0.95, // Convert 95 -> 0.95positionValue: parseFloat(positionValue) || 1000000,});break;@@ -143,8 +657,9 @@ export function GsQuantPanel() {}case 'statistics':+ // For statistics, use raw values (not percentages)response = await invoke<string>('gs_quant_statistics', {- values: returns,+ values: parseFloatArray(returnsInput),});break;@@ -192,90 +707,177 @@ export function GsQuantPanel() {};const renderCommonInputs = () => (- <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>- <div>- <div style={labelStyle}>Returns (comma-separated)</div>- <textarea- value={returnsInput}- onChange={e => setReturnsInput(e.target.value)}- rows={3}- style={{ ...inputStyle, resize: 'vertical' }}- placeholder="0.01, -0.005, 0.008, ..."- />- </div>+ <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>+ <InputField+ label="Daily Returns"+ value={returnsInput}+ onChange={setReturnsInput}+ unit="%"+ help="Enter daily returns as percentages. Positive = gain, negative = loss."+ example="1.5, -0.8, 2.1, -1.2 (representing +1.5%, -0.8%, +2.1%, -1.2%)"+ type="textarea"+ rows={3}+ placeholder="1.0, -0.5, 0.8, -0.3, ..."+ />{(mode === 'portfolio') && (- <div>- <div style={labelStyle}>Benchmark Returns</div>- <textarea- value={benchmarkInput}- onChange={e => setBenchmarkInput(e.target.value)}- rows={2}- style={{ ...inputStyle, resize: 'vertical' }}- placeholder="0.008, -0.003, 0.006, ..."- />- </div>+ <InputField+ label="Benchmark Returns"+ value={benchmarkInput}+ onChange={setBenchmarkInput}+ unit="%"+ help="Enter benchmark (e.g., S&P 500) returns for the same time periods."+ example="0.9, -0.4, 1.8, -0.9"+ type="textarea"+ rows={2}+ placeholder="0.8, -0.3, 0.6, -0.2, ..."+ />)}{['risk_metrics', 'portfolio'].includes(mode) && (- <div>- <div style={labelStyle}>Risk-Free Rate</div>- <input value={riskFreeRate} onChange={e => setRiskFreeRate(e.target.value)} style={inputStyle} />- </div>+ <InputField+ label="Risk-Free Rate"+ value={riskFreeRate}+ onChange={setRiskFreeRate}+ unit="% annual"+ help="Annual risk-free rate, typically T-bill or savings rate."+ example="2 for 2% annual rate, 5 for 5%"+ placeholder="2"+ />)}{['var_analysis', 'stress_test'].includes(mode) && (- <div style={{ display: 'flex', gap: '8px' }}>- <div style={{ flex: 1 }}>- <div style={labelStyle}>Confidence</div>- <input value={confidence} onChange={e => setConfidence(e.target.value)} style={inputStyle} />- </div>- <div style={{ flex: 1 }}>- <div style={labelStyle}>Position Value</div>- <input value={positionValue} onChange={e => setPositionValue(e.target.value)} style={inputStyle} />- </div>+ <div style={{ display: 'flex', gap: '12px' }}>+ <InputField+ label="Confidence Level"+ value={confidence}+ onChange={setConfidence}+ unit="%"+ help="VaR confidence level. 95% means loss exceeds VaR only 5% of the time."+ example="95 for 95% confidence, 99 for 99%"+ placeholder="95"+ style={{ flex: 1 }}+ />+ <InputField+ label="Position Value"+ value={positionValue}+ onChange={setPositionValue}+ unit="$"+ help="Total value of your position or portfolio in dollars."+ example="1000000 for $1 million"+ placeholder="1000000"+ style={{ flex: 1 }}+ /></div>)}</div>);const renderGreeksInputs = () => (- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '8px' }}>- <div><div style={labelStyle}>Spot Price</div><input value={spot} onChange={e => setSpot(e.target.value)} style={inputStyle} /></div>- <div><div style={labelStyle}>Strike Price</div><input value={strike} onChange={e => setStrike(e.target.value)} style={inputStyle} /></div>- <div><div style={labelStyle}>Expiry (years)</div><input value={expiry} onChange={e => setExpiry(e.target.value)} style={inputStyle} /></div>- <div><div style={labelStyle}>Risk-Free Rate</div><input value={rate} onChange={e => setRate(e.target.value)} style={inputStyle} /></div>- <div><div style={labelStyle}>Volatility</div><input value={vol} onChange={e => setVol(e.target.value)} style={inputStyle} /></div>+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '12px' }}>+ <InputField+ label="Spot Price"+ value={spot}+ onChange={setSpot}+ unit="$"+ help="Current price of the underlying asset."+ example="100 for $100"+ placeholder="100"+ />+ <InputField+ label="Strike Price"+ value={strike}+ onChange={setStrike}+ unit="$"+ help="Option exercise price."+ example="105 for $105 strike"+ placeholder="100"+ />+ <InputField+ label="Time to Expiry"+ value={expiry}+ onChange={setExpiry}+ unit="months"+ help="Time until option expiration in months."+ example="3 for 3-month option, 12 for 1-year"+ placeholder="3"+ />+ <InputField+ label="Risk-Free Rate"+ value={rate}+ onChange={setRate}+ unit="% annual"+ help="Annual risk-free interest rate."+ example="5 for 5% annual rate"+ placeholder="5"+ />+ <InputField+ label="Implied Volatility"+ value={vol}+ onChange={setVol}+ unit="% annual"+ help="Annualized implied volatility of the underlying."+ example="20 for 20% volatility, 35 for higher vol stocks"+ placeholder="20"+ /><div>- <div style={labelStyle}>Option Type</div>+ <div style={labelStyle}>+ <span>Option Type</span>+ <Tooltip text="Call = right to buy, Put = right to sell">+ <HelpCircle size={12} color={colors.textMuted} style={{ cursor: 'help' }} />+ </Tooltip>+ </div><select value={optionType} onChange={e => setOptionType(e.target.value)} style={inputStyle}>- <option value="call">Call</option>- <option value="put">Put</option>+ <option value="call">Call (right to buy)</option>+ <option value="put">Put (right to sell)</option></select></div></div>);const renderBacktestInputs = () => (- <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>- <div>- <div style={labelStyle}>Returns (comma-separated)</div>- <textarea- value={returnsInput}- onChange={e => setReturnsInput(e.target.value)}- rows={3}- style={{ ...inputStyle, resize: 'vertical' }}- />- </div>- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '8px' }}>+ <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>+ <InputField+ label="Historical Returns"+ value={returnsInput}+ onChange={setReturnsInput}+ unit="%"+ help="Daily returns to backtest against. Will be converted to price series."+ example="1.0, -0.5, 0.8, -0.3 (representing +1%, -0.5%, +0.8%, -0.3%)"+ type="textarea"+ rows={3}+ placeholder="1.0, -0.5, 0.8, -0.3, ..."+ />+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '12px' }}><div>- <div style={labelStyle}>Strategy</div>+ <div style={labelStyle}>+ <span>Strategy</span>+ <Tooltip text="Trading strategy to backtest against historical data">+ <HelpCircle size={12} color={colors.textMuted} style={{ cursor: 'help' }} />+ </Tooltip>+ </div><select value={strategy} onChange={e => setStrategy(e.target.value)} style={inputStyle}>- <option value="buy_and_hold">Buy & Hold</option>- <option value="momentum">Momentum</option>- <option value="mean_reversion">Mean Reversion</option>- <option value="rebalancing">Rebalancing</option>+ <option value="buy_and_hold">Buy & Hold (baseline)</option>+ <option value="momentum">Momentum (trend following)</option>+ <option value="mean_reversion">Mean Reversion (contrarian)</option>+ <option value="rebalancing">Rebalancing (periodic)</option></select></div>- <div><div style={labelStyle}>Initial Capital</div><input value={initialCapital} onChange={e => setInitialCapital(e.target.value)} style={inputStyle} /></div>- <div><div style={labelStyle}>Lookback</div><input value={lookback} onChange={e => setLookback(e.target.value)} style={inputStyle} /></div>+ <InputField+ label="Initial Capital"+ value={initialCapital}+ onChange={setInitialCapital}+ unit="$"+ help="Starting capital for the backtest simulation."+ example="100000 for $100K, 1000000 for $1M"+ placeholder="100000"+ />+ <InputField+ label="Lookback Period"+ value={lookback}+ onChange={setLookback}+ unit="days"+ help="Number of days to look back for momentum/mean-reversion signals."+ example="20 for 20-day moving average"+ placeholder="20"+ /></div></div>);@@ -505,10 +1107,8 @@ export function GsQuantPanel() {{/* Content Area */}<div style={{ flex: 1, overflow: 'auto', padding: '12px', display: 'flex', flexDirection: 'column', gap: '12px' }}>- {/* Description */}- <div style={{ color: colors.textMuted, fontSize: '11px', padding: '6px 0' }}>- {MODES.find(m => m.id === mode)?.description}- </div>+ {/* How to Use Guide */}+ <HowToUsePanel mode={mode} />{/* Inputs */}{mode === 'greeks' ? renderGreeksInputs() :diff --git a/fincept-terminal-desktop/src/constants/version.ts b/fincept-terminal-desktop/src/constants/version.tsindex 96dc83a12..3bfba7ba0 100644--- a/fincept-terminal-desktop/src/constants/version.ts+++ b/fincept-terminal-desktop/src/constants/version.ts@@ -6,7 +6,7 @@// Run `bun run sync-version` to sync from package.json// Or edit package.json and run build/dev to auto-sync-export const APP_VERSION = '3.3.0';+export const APP_VERSION = '3.3.1';export const APP_NAME = 'Fincept Terminal';export const APP_BUILD_DATE = new Date().toISOString().split('T')[0];diff --git a/fincept-terminal-desktop/src/hooks/usePeerComparison.ts b/fincept-terminal-desktop/src/hooks/usePeerComparison.tsdeleted file mode 100644index 48911932e..000000000--- a/fincept-terminal-desktop/src/hooks/usePeerComparison.ts+++ /dev/null@@ -1,233 +0,0 @@-// Custom React Hook for Peer Comparison-// Manages state and API calls for peer analysis--import { useState, useCallback, useEffect } from 'react';-import { invoke } from '@tauri-apps/api/core';-import type {- PeerCompany,- PeerComparisonResult,- PeerSearchInput,- ComparisonInput,- PeerCommandResponse,- MetricRanking,- PercentileInput,-} from '../types/peer';--export interface UsePeerComparisonReturn {- // State- targetSymbol: string;- selectedPeers: PeerCompany[];- availablePeers: PeerCompany[];- comparisonData: PeerComparisonResult | null;- loading: boolean;- error: string | null;-- // Actions- setTargetSymbol: (symbol: string) => void;- fetchPeers: (input: PeerSearchInput) => Promise<void>;- addPeer: (peer: PeerCompany) => void;- removePeer: (symbol: string) => void;- selectPeer: (symbol: string) => void;- deselectPeer: (symbol: string) => void;- selectAllPeers: () => void;- clearPeers: () => void;- runComparison: () => Promise<void>;- calculatePercentiles: (input: PercentileInput) => Promise<MetricRanking | null>;- reset: () => void;-}--export function usePeerComparison(initialSymbol?: string): UsePeerComparisonReturn {- const [targetSymbol, setTargetSymbol] = useState<string>(initialSymbol || '');- const [selectedPeers, setSelectedPeers] = useState<PeerCompany[]>([]);- const [availablePeers, setAvailablePeers] = useState<PeerCompany[]>([]);- const [comparisonData, setComparisonData] = useState<PeerComparisonResult | null>(null);- const [loading, setLoading] = useState(false);- const [error, setError] = useState<string | null>(null);-- // Fetch peer companies- const fetchPeers = useCallback(async (input: PeerSearchInput) => {- console.log('[usePeerComparison] Fetching peers with input:', input);- setLoading(true);- setError(null);-- try {- console.log('[usePeerComparison] Calling invoke find_peers...');- const response = await invoke<PeerCommandResponse<PeerCompany[]>>('find_peers', { input });- console.log('[usePeerComparison] Response:', response);-- if (response.success && response.data) {- console.log('[usePeerComparison] Found', response.data.length, 'peers');- setAvailablePeers(response.data);- // Auto-select top 5 peers by similarity- const topPeers = response.data.slice(0, 5);- setSelectedPeers(topPeers);- console.log('[usePeerComparison] Auto-selected', topPeers.length, 'peers');- } else {- console.error('[usePeerComparison] Failed:', response.error);- setError(response.error || 'Failed to fetch peers');- }- } catch (err) {- console.error('[usePeerComparison] Error fetching peers:', err);- setError(err instanceof Error ? err.message : 'Unknown error occurred');- } finally {- setLoading(false);- }- }, []);-- // Add a peer to selected list- const addPeer = useCallback((peer: PeerCompany) => {- setSelectedPeers((prev) => {- if (prev.find((p) => p.symbol === peer.symbol)) {- return prev;- }- return [...prev, peer];- });- }, []);-- // Remove a peer from selected list- const removePeer = useCallback((symbol: string) => {- setSelectedPeers((prev) => prev.filter((p) => p.symbol !== symbol));- }, []);-- // Select a peer from available list- const selectPeer = useCallback((symbol: string) => {- const peer = availablePeers.find((p) => p.symbol === symbol);- if (peer) {- addPeer(peer);- }- }, [availablePeers, addPeer]);-- // Deselect a peer- const deselectPeer = useCallback((symbol: string) => {- removePeer(symbol);- }, [removePeer]);-- // Select all available peers- const selectAllPeers = useCallback(() => {- setSelectedPeers(availablePeers);- }, [availablePeers]);-- // Clear all selected peers- const clearPeers = useCallback(() => {- setSelectedPeers([]);- }, []);-- // Run peer comparison- const runComparison = useCallback(async () => {- if (!targetSymbol || selectedPeers.length === 0) {- setError('Please select a target symbol and at least one peer');- return;- }-- setLoading(true);- setError(null);-- try {- const input: ComparisonInput = {- targetSymbol,- peerSymbols: selectedPeers.map((p) => p.symbol),- metrics: [- 'peRatio',- 'pbRatio',- 'psRatio',- 'roe',- 'roa',- 'netMargin',- 'revenueGrowth',- 'earningsGrowth',- 'debtToEquity',- ],- };-- const response = await invoke<PeerCommandResponse<PeerComparisonResult>>('compare_peers', { input });-- if (response.success && response.data) {- setComparisonData(response.data);- } else {- setError(response.error || 'Failed to run comparison');- }- } catch (err) {- setError(err instanceof Error ? err.message : 'Unknown error occurred');- console.error('Error running comparison:', err);- } finally {- setLoading(false);- }- }, [targetSymbol, selectedPeers]);-- // Calculate percentile ranking for a metric- const calculatePercentiles = useCallback(- async (input: PercentileInput): Promise<MetricRanking | null> => {- try {- const response = await invoke<PeerCommandResponse<MetricRanking>>('calculate_peer_percentiles', { input });-- if (response.success && response.data) {- return response.data;- } else {- console.error('Failed to calculate percentiles:', response.error);- return null;- }- } catch (err) {- console.error('Error calculating percentiles:', err);- return null;- }- },- []- );-- // Reset all state- const reset = useCallback(() => {- setTargetSymbol('');- setSelectedPeers([]);- setAvailablePeers([]);- setComparisonData(null);- setError(null);- }, []);-- // Auto-fetch peers when target symbol changes- useEffect(() => {- console.log('[usePeerComparison] useEffect triggered. targetSymbol:', targetSymbol, 'availablePeers.length:', availablePeers.length);- if (targetSymbol && targetSymbol.length >= 1) {- // Create a mock search input for demo purposes- // In production, you'd fetch company info first- const mockInput: PeerSearchInput = {- symbol: targetSymbol,- sector: 'Information Technology',- industry: 'Software',- marketCap: 2000000000000,- minSimilarity: 0.5,- maxPeers: 15,- };-- // Only fetch if we don't have peers yet- if (availablePeers.length === 0) {- console.log('[usePeerComparison] Triggering fetchPeers...');- fetchPeers(mockInput);- } else {- console.log('[usePeerComparison] Peers already loaded, skipping fetch');- }- }- }, [targetSymbol]); // Intentionally not including fetchPeers and availablePeers to avoid loops-- return {- // State- targetSymbol,- selectedPeers,- availablePeers,- comparisonData,- loading,- error,-- // Actions- setTargetSymbol,- fetchPeers,- addPeer,- removePeer,- selectPeer,- deselectPeer,- selectAllPeers,- clearPeers,- runComparison,- calculatePercentiles,- reset,- };-}diff --git a/fincept-terminal-desktop/src/services/payment/paymentApi.tsx b/fincept-terminal-desktop/src/services/payment/paymentApi.tsxindex 4ca37ac1c..ab3d956ec 100644--- a/fincept-terminal-desktop/src/services/payment/paymentApi.tsx+++ b/fincept-terminal-desktop/src/services/payment/paymentApi.tsx@@ -222,11 +222,6 @@ export class PaymentApiService {};}- // Get specific plan details- static async getPlanDetails(planId: string): Promise<PaymentApiResponse<SubscriptionPlan>> {- return makePaymentApiRequest<SubscriptionPlan>('GET', `/cashfree/plans/${planId}`);- }-// Create checkout session - Updated to use /cashfree/create-order endpointstatic async createCheckoutSession(apiKey: string,@@ -322,19 +317,6 @@ export class PaymentApiService {);}- // Get specific payment details- static async getPaymentDetails(- apiKey: string,- paymentUuid: string- ): Promise<PaymentApiResponse<any>> {- return makePaymentApiRequest(- 'GET',- `/cashfree/payments/${paymentUuid}`,- undefined,- { 'X-API-Key': apiKey }- );- }-// Get transaction status - New endpointstatic async getTransactionStatus(apiKey: string,@@ -348,17 +330,6 @@ export class PaymentApiService {);}- // Webhook validation (for future use)- static async validateWebhook(webhookData: any): Promise<PaymentApiResponse<any>> {- return makePaymentApiRequest('POST', '/cashfree/webhook', webhookData);- }-- // Debug function to test API key validity- static async testApiKey(apiKey: string): Promise<PaymentApiResponse<any>> {- return await makePaymentApiRequest('GET', '/cashfree/subscription', undefined, {- 'X-API-Key': apiKey- });- }}// Updated PaymentUtils class with in-app window support@@ -373,77 +344,6 @@ export class PaymentUtils {}).format(amount);}- // Calculate annual savings- static calculateAnnualSavings(monthlyPrice: number): number {- const annualPrice = monthlyPrice * 10; // 2 months free- const fullYearPrice = monthlyPrice * 12;- return fullYearPrice - annualPrice;- }-- // Get plan recommendation based on usage- static getRecommendedPlan(apiCallsPerMonth: number): string {- if (apiCallsPerMonth <= 10000) return 'starter_20';- if (apiCallsPerMonth <= 50000) return 'professional_49';- if (apiCallsPerMonth <= 200000) return 'enterprise_99';- return 'unlimited_199';- }-- // Validate plan selection- static validatePlanSelection(planId: string, availablePlans: SubscriptionPlan[]): boolean {- return availablePlans.some(plan => plan.plan_id === planId);- }-- // Parse URL parameters for payment success page- static parsePaymentParams(url: string): { sessionId?: string; paymentId?: string } {- const urlParams = new URLSearchParams(url.split('?')[1]);- return {- sessionId: urlParams.get('session_id') || undefined,- paymentId: urlParams.get('payment_id') || undefined- };- }-- // Check if subscription is expiring soon (within 7 days)- static isSubscriptionExpiringSoon(endDate: string): boolean {- const end = new Date(endDate);- const now = new Date();- const daysUntilExpiry = Math.ceil((end.getTime() - now.getTime()) / (1000 * 60 * 60 * 24));- return daysUntilExpiry <= 7 && daysUntilExpiry > 0;- }-- // Get usage percentage with color coding- static getUsageStatus(used: number, limit: number | string): {- percentage: number;- status: 'low' | 'medium' | 'high' | 'critical';- color: string;- } {- if (limit === 'unlimited' || limit === -1) {- return { percentage: 0, status: 'low', color: 'green' };- }-- const limitNum = typeof limit === 'string' ? parseInt(limit) : limit;- const percentage = Math.min((used / limitNum) * 100, 100);-- let status: 'low' | 'medium' | 'high' | 'critical';- let color: string;-- if (percentage >= 95) {- status = 'critical';- color = 'red';- } else if (percentage >= 80) {- status = 'high';- color = 'orange';- } else if (percentage >= 50) {- status = 'medium';- color = 'yellow';- } else {- status = 'low';- color = 'green';- }-- return { percentage: Math.round(percentage), status, color };- }-- // Validate payment URL before opening// Validate payment URL before openingstatic validatePaymentUrl(url: string): boolean {if (!url || url === 'undefined' || url === 'null') {@@ -485,101 +385,6 @@ static validatePaymentUrl(url: string): boolean {}}- // Open payment URL in external browser (Tauri shell)- static async openPaymentUrl(- checkoutUrl: string,- planName: string = 'Subscription',- planPrice: number = 0- ): Promise<boolean> {- if (!this.validatePaymentUrl(checkoutUrl)) {- console.error('Invalid checkout URL provided');- const { showError } = await import('@/utils/notifications');- showError('Payment URL is invalid. Please try again or contact support.');- return false;- }-- try {- // Always use external browser for Tauri- return this.openPaymentUrlExternal(checkoutUrl);- } catch (error) {- console.error('Failed to open payment window:', error);- return false;- }- }-- // Enhanced payment URL opener with validation- static async openValidatedPaymentUrl(- checkoutUrl: string,- planName: string = 'Subscription',- planPrice: number = 0- ): Promise<boolean> {- if (!this.validatePaymentUrl(checkoutUrl)) {- console.error('Invalid or suspicious payment URL');- const { showError } = await import('@/utils/notifications');- showError('Invalid payment URL. Please contact support.');- return false;- }-- return this.openPaymentUrl(checkoutUrl, planName, planPrice);- }-- // Fallback method: Open external payment URL- private static async openPaymentUrlExternal(checkoutUrl: string): Promise<boolean> {- try {- const newWindow = window.open(checkoutUrl, '_blank', 'noopener,noreferrer');-- if (!newWindow) {- const { showWarning } = await import('@/utils/notifications');-- // Try to copy URL to clipboard as fallback- if (navigator.clipboard && checkoutUrl !== 'undefined') {- try {- await navigator.clipboard.writeText(checkoutUrl);- showWarning('Popup blocked. Payment URL copied to clipboard', [- { label: 'URL', value: checkoutUrl }- ]);- } catch {- showWarning('Please visit this URL to complete payment', [- { label: 'URL', value: checkoutUrl }- ]);- }- } else {- showWarning('Please visit this URL to complete payment', [- { label: 'URL', value: checkoutUrl }- ]);- }-- return false;- }-- return true;-- } catch (error) {- console.error('PaymentUtils: Failed to open external payment URL:', error);- const { showError } = await import('@/utils/notifications');- showError('Failed to open payment window', [- { label: 'URL', value: checkoutUrl }- ]);- return false;- }- }-- // Generate receipt data for successful payment- static generateReceiptData(paymentData: any): {- receiptId: string;- date: string;- description: string;- amount: string;- status: string;- } {- return {- receiptId: paymentData.payment_uuid || 'N/A',- date: new Date().toLocaleDateString(),- description: `Fincept API Subscription - ${paymentData.plan?.name || 'Plan'}`,- amount: this.formatCurrency(paymentData.plan?.price || 0),- status: paymentData.status || 'Completed'- };- }}export default PaymentApiService;\ No newline at end of file