Skip to content

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.

v4.0.2 portfolio and ai chat fix

tilakpatel22485376c42dcb
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index d1b2ff8f4..297a79272 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -352,18 +352,49 @@ jobs:
Categories=Finance;
EOF
- # Icon — use real one if available, else placeholder so linuxdeploy
- # doesn't abort on a missing .png (it's mandatory for valid AppImage).
+ # Icon — linuxdeploy requires a valid PNG (it runs libpng/CImg over
+ # the file to generate scaled variants). Convert the repo's .ico to
+ # a 256x256 PNG via ImageMagick (pre-installed on ubuntu-22.04). Fall
+ # back to a generated solid-color PNG only if no source icon exists —
+ # never hand-write PNG bytes inline, ImageMagick's CRC check rejects
+ # anything with a malformed IDAT chunk.
ICON_DEST="${APPDIR}/usr/share/icons/hicolor/256x256/apps/fincept-terminal.png"
if [ -f "resources/icons/app_icon_256.png" ]; then
cp "resources/icons/app_icon_256.png" "${ICON_DEST}"
elif [ -f "resources/fincept.png" ]; then
cp "resources/fincept.png" "${ICON_DEST}"
+ elif [ -f "resources/fincept.ico" ]; then
+ # .ico may hold multiple frames — "ico:file[0]" selects the first,
+ # which is conventionally the largest/primary. Explicit "ico:" prefix
+ # forces the ICO decoder in case policy.xml has format detection quirks.
+ convert "ico:resources/fincept.ico[0]" -resize 256x256 -background none -flatten "png:${ICON_DEST}"
else
- # 1x1 transparent PNG — keeps linuxdeploy happy.
- printf '\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x06\x00\x00\x00\x1f\x15\xc4\x89\x00\x00\x00\rIDATx\x9cc\x00\x01\x00\x00\x05\x00\x01\r\n-\xb4\x00\x00\x00\x00IEND\xaeB`\x82' > "${ICON_DEST}"
+ # Solid-color 256x256 PNG as last resort. ImageMagick writes it
+ # with a valid IDAT + CRC, unlike an inline printf of raw bytes.
+ convert -size 256x256 xc:'#1a1a1a' "png:${ICON_DEST}"
fi
+ # Sanity check — a broken PNG here will fail the AppImage build
+ # 30 seconds later inside linuxdeploy, so fail fast with a clear error.
+ # Check: file exists, is non-empty, `file` reports PNG, and libpng's
+ # own `pngcheck`-equivalent (imagemagick `identify`) can parse it.
+ if [ ! -s "${ICON_DEST}" ]; then
+ echo "::error::Icon at ${ICON_DEST} is missing or empty"
+ ls -la "${ICON_DEST}" 2>&1 || true
+ exit 1
+ fi
+ if ! file "${ICON_DEST}" | grep -q 'PNG image data'; then
+ echo "::error::Icon at ${ICON_DEST} is not a valid PNG"
+ file "${ICON_DEST}"
+ exit 1
+ fi
+ if ! identify "${ICON_DEST}" >/dev/null 2>&1; then
+ echo "::error::Icon at ${ICON_DEST} failed ImageMagick identify — libpng will reject it"
+ identify "${ICON_DEST}" 2>&1 || true
+ exit 1
+ fi
+ echo "Icon OK: $(identify -format '%wx%h %m' "${ICON_DEST}")"
+
# App resources + Python analytics scripts live next to the binary
# (matches AppPaths resolution on Linux).
cp -r resources "${APPDIR}/usr/bin/resources" 2>/dev/null || true
@@ -607,6 +638,14 @@ jobs:
PLIST
fi
+ # Note: CMake's POST_BUILD rule (CMakeLists.txt line 1907) copies
+ # scripts/ to Contents/MacOS/scripts/. This is REQUIRED — at runtime
+ # PythonRunner::find_scripts_dir() searches paths relative to
+ # applicationDirPath() (which is Contents/MacOS on macOS). Moving
+ # scripts to Contents/Resources/ would break script discovery.
+ # codesign can handle files in MacOS/; what it CANNOT handle is a
+ # malformed framework (see the Python.framework block below).
+
# Embed Python framework (before codesign so it gets signed with the bundle)
PY_FRAMEWORK=""
for candidate in \
@@ -620,28 +659,66 @@ jobs:
mkdir -p "${BUNDLE_FRAMEWORKS}"
if [ -n "${PY_FRAMEWORK}" ]; then
echo "Embedding Python.framework from: ${PY_FRAMEWORK}"
- # Use rsync to skip missing symlink targets (PrivateHeaders in Tk/Tcl
- # sub-frameworks don't exist on CI runners — cp -R would abort on them).
- rsync -a --copy-unsafe-links "${PY_FRAMEWORK}/" "${BUNDLE_FRAMEWORKS}/Python.framework/" 2>/dev/null || \
- cp -R "${PY_FRAMEWORK}" "${BUNDLE_FRAMEWORKS}/" 2>/dev/null || true
- # Remove any dangling PrivateHeaders symlinks that don't resolve
- find "${BUNDLE_FRAMEWORKS}/Python.framework" -name "PrivateHeaders" -type l \
+ # CRITICAL: preserve symlinks. `Python.framework` is a versioned
+ # framework — Versions/Current → 3.12, top-level Python/Resources/
+ # Headers → Versions/Current/Python etc. If we dereference symlinks
+ # (rsync --copy-unsafe-links, or `cp -RL`) the directory structure
+ # is no longer a valid framework bundle and codesign rejects it with
+ # "embedded framework contains modified or invalid version".
+ # `cp -R` on macOS preserves symlinks by default; `ditto` is the
+ # Apple-blessed way to copy bundles losslessly (preserves xattr,
+ # symlinks, resource forks).
+ if [ -d "${BUNDLE_FRAMEWORKS}/Python.framework" ]; then
+ rm -rf "${BUNDLE_FRAMEWORKS}/Python.framework"
+ fi
+ ditto "${PY_FRAMEWORK}" "${BUNDLE_FRAMEWORKS}/Python.framework"
+
+ # Strip dev-only files that shouldn't ship AND that confuse codesign:
+ # - .pyc caches (regenerated at runtime, and old hashes fail seal)
+ # - __pycache__ directories
+ # - .a / .la static libs (not needed at runtime)
+ # - test/ directories inside stdlib (huge, not needed)
+ find "${BUNDLE_FRAMEWORKS}/Python.framework" -name "__pycache__" -type d -exec rm -rf {} + 2>/dev/null || true
+ find "${BUNDLE_FRAMEWORKS}/Python.framework" -name "*.pyc" -delete 2>/dev/null || true
+ find "${BUNDLE_FRAMEWORKS}/Python.framework" -name "*.pyo" -delete 2>/dev/null || true
+
+ # Remove dangling symlinks (PrivateHeaders often points to missing targets)
+ find "${BUNDLE_FRAMEWORKS}/Python.framework" -type l \
! -exec test -e {} \; -delete 2>/dev/null || true
+
PY_VER="$(python3 -c 'import sys; print(f"{sys.version_info.major}.{sys.version_info.minor}")')"
ln -sf "../Frameworks/Python.framework/Versions/${PY_VER}/bin/python${PY_VER}" \
"${APP_BUNDLE}/Contents/MacOS/python3" 2>/dev/null || true
echo "Python ${PY_VER} embedded"
+
+ # Sanity check: verify the framework structure is intact before we
+ # hand it to codesign. A valid framework has Versions/Current as a
+ # symlink and the top-level Python binary as a symlink to Versions/
+ # Current/Python. If either is a real file or directory, codesign
+ # will reject it.
+ if [ ! -L "${BUNDLE_FRAMEWORKS}/Python.framework/Versions/Current" ]; then
+ echo "::error::Python.framework/Versions/Current is not a symlink — codesign will reject"
+ ls -la "${BUNDLE_FRAMEWORKS}/Python.framework/Versions/"
+ exit 1
+ fi
else
echo "WARNING: Python.framework not found"
fi
- # Copy app resources + Python analytics scripts into bundle
+ # Resources (icons, requirements-*.txt) go in Contents/Resources/ —
+ # macOS convention for non-code assets, read via QStandardPaths.
+ # Scripts are ALREADY in Contents/MacOS/scripts/ via CMake POST_BUILD;
+ # do not duplicate them into Resources/ (doubles bundle size and
+ # creates two trees for codesign to hash).
mkdir -p "${APP_BUNDLE}/Contents/Resources"
cp -r resources "${APP_BUNDLE}/Contents/Resources/" 2>/dev/null || true
- bash "${GITHUB_WORKSPACE}/.github/scripts/sync_scripts.sh" scripts "${APP_BUNDLE}/Contents/Resources/scripts"
echo "Bundle staged at: ${APP_BUNDLE}"
echo "Pre-sign size: $(du -sh "${APP_BUNDLE}" | cut -f1)"
+ echo "=== Contents/MacOS/ top level ==="
+ ls -la "${APP_BUNDLE}/Contents/MacOS/" | head -10
+ echo "=== Scripts count under MacOS/scripts ==="
+ find "${APP_BUNDLE}/Contents/MacOS/scripts" -type f 2>/dev/null | wc -l || true
# ── Run macdeployqt on the fully staged bundle ────────────────────────
# macdeployqt copies Qt frameworks, fixes rpaths, and signs everything
diff --git a/fincept-qt/CMakeLists.txt b/fincept-qt/CMakeLists.txt
index 001a49c52..575f2cd8f 100644
--- a/fincept-qt/CMakeLists.txt
+++ b/fincept-qt/CMakeLists.txt
@@ -1,6 +1,39 @@
cmake_minimum_required(VERSION 3.27)
+
+# ── RC compiler override (clang-cl + Windows only) ───────────────────────────
+# When building with clang-cl, CMake's Windows-Clang module auto-enables the
+# two-step `cmake -E cmake_llvm_rc` wrapper: preprocess the .rc with clang-cl
+# then pipe to rc.exe. That wrapper inherits incompatible C flags (-MD, -FS,
+# /showIncludes) and fails silently with exit 1 on Windows SDK rc.exe. Our
+# app.rc is a trivial ICON declaration with no macros or #includes, so we
+# bypass the wrapper and use rc.exe directly. Tracked as CMake issue #20198.
+# Must run before project() so CMAKE_RC_COMPILER is set before RC language init.
+if(WIN32 AND CMAKE_HOST_WIN32)
+ # Heuristic: if CC/CXX env vars point to clang-cl, or the generator is likely
+ # to pick up clang-cl from PATH, force MSVC rc.exe. Harmless on pure MSVC too.
+ find_program(_fincept_rc_exe NAMES rc rc.exe
+ HINTS
+ "$ENV{WindowsSdkVerBinPath}x64"
+ "$ENV{WindowsSdkDir}bin/$ENV{WindowsSDKVersion}x64"
+ "C:/Program Files (x86)/Windows Kits/10/bin/10.0.22621.0/x64"
+ "C:/Program Files (x86)/Windows Kits/10/bin/10.0.26100.0/x64")
+ if(_fincept_rc_exe)
+ set(CMAKE_RC_COMPILER "${_fincept_rc_exe}" CACHE FILEPATH "Windows resource compiler" FORCE)
+ set(CMAKE_RC_COMPILER_INIT "${_fincept_rc_exe}")
+ endif()
+endif()
+
project(FinceptTerminal VERSION 4.0.2 LANGUAGES CXX)
+# Strip C/C++ flags out of RC invocations — rc.exe only understands /D, /I, /fo.
+if(WIN32)
+ set(CMAKE_RC_FLAGS "/nologo" CACHE STRING "" FORCE)
+ set(CMAKE_RC_FLAGS_RELEASE "" CACHE STRING "" FORCE)
+ set(CMAKE_RC_FLAGS_DEBUG "" CACHE STRING "" FORCE)
+ set(CMAKE_RC_FLAGS_RELWITHDEBINFO "" CACHE STRING "" FORCE)
+ set(CMAKE_RC_FLAGS_MINSIZEREL "" CACHE STRING "" FORCE)
+endif()
+
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
@@ -439,7 +472,13 @@ set(CORE_SOURCES
src/core/session/SessionManager.cpp
src/core/session/ScreenStateManager.cpp
src/core/keys/KeyConfigManager.cpp
+ src/core/keys/WindowCycler.cpp
src/core/net/NetSpeedMeter.cpp
+ src/core/symbol/SymbolContext.cpp
+ src/core/symbol/SymbolMime.cpp
+ src/core/symbol/SymbolDragSource.cpp
+ src/core/components/ComponentCatalog.cpp
+ src/core/components/PopularityTracker.cpp
)
# Network
@@ -465,6 +504,7 @@ set(AUTH_SOURCES
src/auth/SessionGuard.cpp
src/auth/PinManager.cpp
src/auth/InactivityGuard.cpp
+ src/auth/SecurityAuditLog.cpp
)
# Storage
@@ -542,12 +582,15 @@ set(STORAGE_SOURCES
src/storage/sqlite/migrations/v016_broker_accounts.cpp
src/storage/sqlite/migrations/v017_perf_indexes.cpp
src/storage/sqlite/migrations/v018_widget_config.cpp
+ src/storage/sqlite/migrations/v019_sector_cache.cpp
+ src/storage/sqlite/migrations/v020_security_audit_log.cpp
)
# Python runner
set(PYTHON_SOURCES
src/python/PythonRunner.cpp
src/python/PythonSetupManager.cpp
+ src/python/PythonWorker.cpp
)
# AI Chat
@@ -667,6 +710,7 @@ set(SERVICE_SOURCES
src/services/economics/EconomicsService.cpp
src/services/agents/AgentService.cpp
src/services/file_manager/FileManagerService.cpp
+ src/services/sectors/SectorResolver.cpp
src/services/workflow/NodeRegistry.cpp
src/services/workflow/WorkflowService.cpp
src/services/workflow/WorkflowExecutor.cpp
@@ -675,6 +719,7 @@ set(SERVICE_SOURCES
src/services/workspace/WorkspaceSerializer.cpp
src/services/workspace/WorkspaceManager.cpp
src/services/workspace/WorkspaceTemplates.cpp
+ src/services/pushpins/PushpinService.cpp
src/services/workflow/nodes/TriggerNodes.cpp
src/services/workflow/nodes/ControlFlowNodes.cpp
src/services/workflow/nodes/UtilityNodes.cpp
@@ -739,7 +784,12 @@ set(UI_SOURCES
src/ui/theme/ThemeManager.cpp
src/ui/theme/StyleSheets.cpp
src/ui/widgets/Card.cpp
+ src/ui/widgets/GroupBadge.cpp
src/ui/widgets/StatusBadge.cpp
+ src/ui/pushpins/SymbolChip.cpp
+ src/ui/pushpins/PushpinBar.cpp
+ src/ui/components/ComponentCard.cpp
+ src/ui/components/ComponentBrowserDialog.cpp
src/ui/widgets/SearchBar.cpp
src/ui/widgets/GeometricBackground.cpp
src/ui/widgets/WorldMapWidget.cpp
@@ -1064,8 +1114,7 @@ set(SCREEN_SOURCES
src/screens/portfolio/views/PlanningView.cpp
src/screens/portfolio/views/EconomicsView.cpp
src/screens/portfolio/PortfolioFFNView.cpp
- src/screens/portfolio/PortfolioAiPanel.cpp
- src/screens/portfolio/PortfolioAgentPanel.cpp
+ src/screens/portfolio/PortfolioInsightsPanel.cpp
src/screens/agent_config/AgentConfigScreen.cpp
src/screens/agent_config/AgentsViewPanel.cpp
src/screens/agent_config/SystemViewPanel.cpp
@@ -1281,8 +1330,7 @@ set_source_files_properties(
src/screens/node_editor/toolbar/DeployDialog.cpp
src/screens/node_editor/toolbar/NodeEditorToolbar.cpp
src/screens/notes/NotesScreen.cpp
- src/screens/portfolio/PortfolioAgentPanel.cpp
- src/screens/portfolio/PortfolioAiPanel.cpp
+ src/screens/portfolio/PortfolioInsightsPanel.cpp
src/screens/portfolio/PortfolioBlotter.cpp
src/screens/portfolio/PortfolioCommandBar.cpp
src/screens/portfolio/PortfolioDetailWrapper.cpp
@@ -1369,6 +1417,8 @@ set_source_files_properties(
src/storage/sqlite/migrations/v016_broker_accounts.cpp
src/storage/sqlite/migrations/v017_perf_indexes.cpp
src/storage/sqlite/migrations/v018_widget_config.cpp
+ src/storage/sqlite/migrations/v019_sector_cache.cpp
+ src/storage/sqlite/migrations/v020_security_audit_log.cpp
# Polymarket screen files — each defines static fmt_* helpers in same namespace
src/screens/polymarket/PolymarketScreen.cpp
src/screens/polymarket/PolymarketCommandBar.cpp
@@ -1926,6 +1976,9 @@ add_custom_command(TARGET FinceptTerminal POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy_if_different
"${CMAKE_CURRENT_SOURCE_DIR}/resources/requirements-numpy2.txt"
"$<TARGET_FILE_DIR:FinceptTerminal>/resources/requirements-numpy2.txt"
+ COMMAND ${CMAKE_COMMAND} -E copy_if_different
+ "${CMAKE_CURRENT_SOURCE_DIR}/resources/component_catalog.json"
+ "$<TARGET_FILE_DIR:FinceptTerminal>/resources/component_catalog.json"
COMMENT "Copying requirements files to build output..."
)
diff --git a/fincept-qt/resources/component_catalog.json b/fincept-qt/resources/component_catalog.json
new file mode 100644
index 000000000..c29f5070d
--- /dev/null
+++ b/fincept-qt/resources/component_catalog.json
@@ -0,0 +1,56 @@
+{
+ "version": 1,
+ "components": [
+ { "id": "dashboard", "title": "Dashboard", "category": "Core", "description": "Customizable widget grid — quotes, charts, news, notes", "tags": ["grid","widgets","home"] },
+ { "id": "markets", "title": "Markets", "category": "Core", "description": "Cross-asset market overview and movers", "tags": ["markets","overview","movers"] },
+ { "id": "watchlist", "title": "Watchlist", "category": "Core", "description": "Symbol lists with live quotes", "tags": ["watchlist","quotes","symbols"] },
+ { "id": "news", "title": "News", "category": "Core", "description": "Global news wire with category filters and sentiment", "tags": ["news","wire","headlines"] },
+
+ { "id": "crypto_trading", "title": "Crypto Trading", "category": "Trading", "description": "Order entry + real-time book for Kraken / HyperLiquid", "tags": ["crypto","trading","order"] },
+ { "id": "equity_trading", "title": "Equity Trading", "category": "Trading", "description": "Multi-account equity trading across 16+ brokers", "tags": ["equity","trading","brokers"] },
+ { "id": "algo_trading", "title": "Algo Trading", "category": "Trading", "description": "Strategy runner, order router, and execution analytics", "tags": ["algo","strategy","execution"] },
+ { "id": "backtesting", "title": "Backtesting", "category": "Trading", "description": "Historical strategy simulation and reporting", "tags": ["backtest","simulation"] },
+ { "id": "trade_viz", "title": "Trade Viz", "category": "Trading", "description": "Order and position visualisation on price charts", "tags": ["trade","visualise","orders"] },
+
+ { "id": "portfolio", "title": "Portfolio", "category": "Research", "description": "Holdings, P&L, allocation and performance attribution", "tags": ["portfolio","pnl","holdings"] },
+ { "id": "equity_research", "title": "Equity Research", "category": "Research", "description": "Fundamentals, technicals, peers, sentiment in one view", "tags": ["research","fundamentals","peers"] },
+ { "id": "derivatives", "title": "Derivatives", "category": "Research", "description": "Bond, option, swap and CDS pricing", "tags": ["derivatives","pricing","options"] },
+ { "id": "surface_analytics", "title": "Surface Analytics", "category": "Research", "description": "Volatility surfaces, Greeks, yield curves, correlation", "tags": ["surface","vol","greeks"] },
+ { "id": "ma_analytics", "title": "M&A Analytics", "category": "Research", "description": "Deal comparables, accretion/dilution, event studies", "tags": ["m&a","deals","comparables"] },
+ { "id": "alt_investments", "title": "Alt. Investments", "category": "Research", "description": "Private markets, real assets, infrastructure screens", "tags": ["alts","private","infra"] },
+
+ { "id": "quantlib", "title": "QuantLib Suite", "category": "QuantLib", "description": "18 quantitative analysis tools — curves, models, risk", "tags": ["quantlib","curves","models"] },
+ { "id": "ai_quant_lab", "title": "AI Quant Lab", "category": "AI", "description": "ML factor discovery, HFT, RL trading, vision quant", "tags": ["ai","quant","ml"] },
+ { "id": "alpha_arena", "title": "Alpha Arena", "category": "AI", "description": "Competitive strategy arena with leaderboards", "tags": ["alpha","arena","contest"] },
+ { "id": "agent_config", "title": "Agent Config", "category": "AI", "description": "LLM agent framework configuration (hedge fund, macro)", "tags": ["agents","llm","config"] },
+ { "id": "mcp_servers", "title": "MCP Servers", "category": "AI", "description": "Model Context Protocol server management", "tags": ["mcp","tools","servers"] },
+ { "id": "ai_chat", "title": "AI Chat", "category": "AI", "description": "In-terminal chat with market-aware tool-use", "tags": ["chat","llm","assistant"] },
+
+ { "id": "economics", "title": "Economics", "category": "Economics", "description": "Macro dashboards — FRED, IMF, World Bank, OECD", "tags": ["economics","macro","fred"] },
+ { "id": "dbnomics", "title": "DBnomics", "category": "Economics", "description": "80+ provider unified economic data browser", "tags": ["dbnomics","providers","series"] },
+ { "id": "akshare", "title": "AkShare Data", "category": "Economics", "description": "China markets and alternative data", "tags": ["akshare","china","data"] },
+ { "id": "asia_markets", "title": "Asia Markets", "category": "Economics", "description": "APAC market overview — JP, KR, IN, CN, SG, HK", "tags": ["asia","apac","markets"] },
+
+ { "id": "geopolitics", "title": "Geopolitics", "category": "Geopolitics", "description": "Relationship maps, conflicts, sanctions monitors", "tags": ["geopolitics","conflict","sanctions"] },
+ { "id": "gov_data", "title": "Government Data", "category": "Geopolitics", "description": "US/EU/UK government open-data feeds", "tags": ["government","opendata"] },
+ { "id": "maritime", "title": "Maritime", "category": "Geopolitics", "description": "Vessel tracking, port activity, shipping flows", "tags": ["maritime","ships","ports"] },
+ { "id": "polymarket", "title": "Prediction Markets", "category": "Geopolitics", "description": "Polymarket and Kalshi event odds + order book", "tags": ["polymarket","kalshi","prediction"] },
+ { "id": "relationship_map", "title": "Relationship Map", "category": "Geopolitics", "description": "Entity relationship graph explorer", "tags": ["relationship","graph","entities"] },
+
+ { "id": "node_editor", "title": "Node Editor", "category": "Tools", "description": "Visual workflow node editor with 12 node categories", "tags": ["workflow","nodes","visual"] },
+ { "id": "code_editor", "title": "Code Editor", "category": "Tools", "description": "In-app code cells — Python, SQL, shell", "tags": ["code","python","cells"] },
+ { "id": "excel", "title": "Excel", "category": "Tools", "description": "Spreadsheet grid with formulas, XLSX import/export", "tags": ["excel","xlsx","spreadsheet"] },
+ { "id": "report_builder", "title": "Report Builder", "category": "Tools", "description": "PDF/HTML reports from terminal data", "tags": ["report","pdf","builder"] },
+ { "id": "data_sources", "title": "Data Sources", "category": "Tools", "description": "100+ connectors — APIs, DBs, websockets", "tags": ["data","sources","connectors"] },
+ { "id": "data_mapping", "title": "Data Mapping", "category": "Tools", "description": "Transform and route between data sources", "tags": ["mapping","etl","transform"] },
+ { "id": "file_manager", "title": "File Manager", "category": "Tools", "description": "Project-local file browser", "tags": ["files","browser"] },
+ { "id": "notes", "title": "Notes", "category": "Tools", "description": "Markdown scratchpad with live preview", "tags": ["notes","markdown"] },
+
+ { "id": "forum", "title": "Forum", "category": "Community", "description": "Community discussion threads", "tags": ["forum","community"] },
+ { "id": "profile", "title": "Profile", "category": "Community", "description": "User profile and account", "tags": ["profile","account"] },
+ { "id": "settings", "title": "Settings", "category": "Community", "description": "Preferences, keybindings, themes, voice, LLM", "tags": ["settings","preferences"] },
+ { "id": "support", "title": "Support", "category": "Community", "description": "Ticket + support", "tags": ["support","help"] },
+ { "id": "docs", "title": "Docs", "category": "Community", "description": "In-app documentation", "tags": ["docs","documentation"] },
+ { "id": "about", "title": "About", "category": "Community", "description": "Version, license, credits", "tags": ["about","version"] }
+ ]
+}
diff --git a/fincept-qt/scripts/agents/finagent_core/core_agent_stream.py b/fincept-qt/scripts/agents/finagent_core/core_agent_stream.py
index 06556c2b6..c211ba242 100644
--- a/fincept-qt/scripts/agents/finagent_core/core_agent_stream.py
+++ b/fincept-qt/scripts/agents/finagent_core/core_agent_stream.py
@@ -335,9 +335,9 @@ def main(args=None):
"metadata": metadata
}
chunks.append(chunk)
- # Escape backslashes first, then newlines so each printed line is one
- # logical chunk. The host unescapes
- -> newline after stripping prefix.
+ # Escape backslashes first, then newlines so each printed line is
+ # one logical chunk. The host unescapes "\\n" -> newline after
+ # stripping the TOKEN:/THINKING:/... prefix.
safe = content.replace("\\", "\\\\").replace("\n", "\\n").replace("\r", "")
if chunk_type in ["token", "agent_token"]:
full_response += content
diff --git a/fincept-qt/scripts/yfinance_data.py b/fincept-qt/scripts/yfinance_data.py
index 6fd6b89fa..0edc9118e 100644
--- a/fincept-qt/scripts/yfinance_data.py
+++ b/fincept-qt/scripts/yfinance_data.py
@@ -356,6 +356,68 @@ def get_batch_sparklines(symbols, period="5d", interval="1h"):
return {"error": str(e)}
+def get_batch_all(payload):
+ """Unified batch fetcher — returns quotes + sparklines + histories in a single call.
+
+ Called by MarketDataService::refresh() so one DataHub refresh tick spawns a single
+ Python process rather than three (quote + sparkline + history). Shares the same
+ underlying yf.download paths as the individual endpoints — no behaviour change
+ per family, just fewer process spawns.
+
+ payload = {
+ "quotes": [sym, ...], # optional
+ "sparklines": [sym, ...], # optional, 5d/1h
+ "histories": [{"symbol","period","interval"}, ...], # optional
+ }
+
+ Returns:
+ {
+ "quotes": [<quote dicts from get_batch_quotes>, ...],
+ "sparklines": {sym: [close, ...], ...},
+ "histories": [{"symbol","period","interval","points":[...]}],
+ }
+ Any family absent from `payload` is omitted from the result.
+ """
+ out = {}
+
+ quote_syms = payload.get("quotes") or []
+ if quote_syms:
+ out["quotes"] = get_batch_quotes(quote_syms)
+
+ spark_syms = payload.get("sparklines") or []
+ if spark_syms:
+ out["sparklines"] = get_batch_sparklines(spark_syms)
+
+ hist_reqs = payload.get("histories") or []
+ if hist_reqs:
+ histories = []
+ for req in hist_reqs:
+ try:
+ sym = req.get("symbol")
+ period = req.get("period", "6mo")
+ interval = req.get("interval", "1d")
+ if not sym:
+ continue
+ points = get_historical_period(sym, period, interval)
+ histories.append({
+ "symbol": sym,
+ "period": period,
+ "interval": interval,
+ "points": points if isinstance(points, list) else [],
+ })
+ except Exception as e:
+ histories.append({
+ "symbol": req.get("symbol", ""),
+ "period": req.get("period", ""),
+ "interval": req.get("interval", ""),
+ "points": [],
+ "error": str(e),
+ })
+ out["histories"] = histories
+
+ return out
+
+
def get_company_profile(symbol):
"""Get company profile data formatted for peer comparison"""
try:
@@ -556,6 +618,145 @@ def get_news(symbol, count=20):
except Exception as e:
return {"error": str(e), "symbol": symbol, "articles": []}
+def _candidate_yf_symbols(symbol):
+ """Generate yfinance ticker candidates for a portfolio symbol.
+
+ Heuristic — try the symbol as-given first, then common non-US exchange
+ suffixes. We can't ask the portfolio for currency here, so we just iterate
+ until something returns data. Order matters: most likely first.
+ """
+ s = symbol.strip().upper()
+ if not s:
+ return []
+ # Already has an exchange suffix or is an index/crypto/forex pair → trust it.
+ if '.' in s or s.startswith('^') or '-' in s or '=' in s:
+ return [s]
+ # Bare ticker — try US first, then Toronto, NSE, BSE, LSE, ASX, Hong Kong.
+ return [s, f"{s}.TO", f"{s}.NS", f"{s}.BO", f"{s}.L", f"{s}.AX", f"{s}.HK"]
+
+
+def _resolve_for_history(symbols, period):
+ """Resolve every input symbol to a yfinance ticker that returns data
+ in the given period, AND return the close-price DataFrame for each.
+
+ Returns: dict[input_symbol] -> (resolved_symbol, closes_series).
+ Symbols that fail every candidate are omitted.
+
+ We do this in two passes:
+ 1. Bulk download all bare symbols + obvious-suffix variants we need to
+ cover. yf.download is one HTTP fan-out so this is cheap.
+ 2. For each input, pick the first candidate that yielded a non-empty
+ close series.
+ """
+ import io, contextlib, logging
+ candidates_per_symbol = {s: _candidate_yf_symbols(s) for s in symbols}
+ all_candidates = sorted({c for variants in candidates_per_symbol.values() for c in variants})
+
+ if not all_candidates:
+ return {}
+
+ # yfinance prints "Failed download" / HTTP error lines straight to stdout
+ # AND uses the logging module. Silence both — we report misses via the
+ # `missing` key in the returned JSON, and noise on stdout corrupts the
+ # JSON the C++ caller is trying to parse.
+ yf_logger = logging.getLogger("yfinance")
+ prev_level = yf_logger.level
+ yf_logger.setLevel(logging.CRITICAL)
+ _buf_out = io.StringIO()
+ _buf_err = io.StringIO()
+ try:
+ with contextlib.redirect_stdout(_buf_out), contextlib.redirect_stderr(_buf_err):
+ data = yf.download(
+ tickers=all_candidates,
+ period=period,
+ interval="1d",
+ group_by="ticker",
+ auto_adjust=True,
+ progress=False,
+ threads=True,
+ )
+ finally:
+ yf_logger.setLevel(prev_level)
+
+ if data is None or data.empty:
+ return {}
+
+ single = len(all_candidates) == 1
+
+ def closes_for(ticker):
+ try:
+ if single:
+ return data["Close"].dropna()
+ return data[ticker]["Close"].dropna()
+ except Exception:
+ return None
+
+ resolved = {}
+ for s, variants in candidates_per_symbol.items():
+ for v in variants:
+ ser = closes_for(v)
+ if ser is not None and not ser.empty:
+ resolved[s] = (v, ser)
+ break
+ return resolved
+
+
+def get_portfolio_nav_history(positions, period='6mo'):
+ """Reconstruct a daily NAV time series from current positions.
+
+ positions: list of {"symbol": str, "quantity": float} dicts.
+ Returns: {"dates": [...], "navs": [...], "resolved": {sym: yf_sym},
+ "missing": [sym, ...]}.
+
+ Each input symbol is resolved to a yfinance ticker via _resolve_for_history,
+ which tries common exchange suffixes (.TO, .NS, .BO, .L, .AX, .HK) when the
+ bare symbol returns no data. Missing closes are forward-filled per symbol so
+ a symbol that listed mid-period doesn't drop the whole row.
+
+ NAV on each date = sum(close_i * quantity_i) over all resolved symbols.
+
+ NOTE: this back-projects NAV using CURRENT quantity at every date — it
+ does not account for buys/sells inside the window. That's acceptable for
+ risk metrics (Beta, MDD) which measure basket variability, not realised P&L.
+ """
+ try:
+ if not positions:
+ return {"dates": [], "navs": []}
+ symbols = [p["symbol"] for p in positions if p.get("symbol")]
+ qty_map = {p["symbol"]: float(p.get("quantity", 0)) for p in positions if p.get("symbol")}
+ if not symbols:
+ return {"dates": [], "navs": []}
+
+ resolved = _resolve_for_history(symbols, period)
+ if not resolved:
+ return {"dates": [], "navs": [], "error": "no historical data for any symbol",
+ "missing": symbols}
+
+ nav_series = None
+ for sym, (yf_sym, closes) in resolved.items():
+ contrib = closes.ffill() * qty_map[sym]
+ if nav_series is None:
+ nav_series = contrib
+ else:
+ nav_series = nav_series.add(contrib, fill_value=0)
+
+ if nav_series is None or nav_series.empty:
+ return {"dates": [], "navs": [], "error": "no usable closes",
+ "missing": [s for s in symbols if s not in resolved]}
+
+ nav_series = nav_series.dropna()
+ dates = [idx.strftime("%Y-%m-%d") for idx in nav_series.index]
+ navs = [float(v) for v in nav_series.values]
+ return {
+ "dates": dates,
+ "navs": navs,
+ "resolved": {s: yf for s, (yf, _) in resolved.items()},
+ "missing": [s for s in symbols if s not in resolved],
+ }
+ except Exception as e:
+ return {"dates": [], "navs": [], "error": str(e)}
+
+
def get_historical_period(symbol, period='6mo', interval='1d'):
"""Fetch historical data using a period string (e.g., '1mo', '6mo', '1y', '5y')"""
try:
@@ -730,6 +931,28 @@ def main(args=None):
count = int(args[2]) if len(args) > 2 else 20
result = get_news(symbol, count)
+ elif command == "portfolio_nav_history":
+ # Args layout: <period> <sym1> <qty1> <sym2> <qty2> ...
+ # Period defaults to 1y if first arg looks like a symbol.
+ if len(args) < 3:
+ result = {"error": "Usage: yfinance_data.py portfolio_nav_history <period> <sym1> <qty1> ..."}
+ else:
+ period = args[1]
+ tail = args[2:]
+ if len(tail) % 2 != 0:
+ result = {"error": "symbol/quantity arguments must be paired"}
+ else:
+ positions = []
+ for i in range(0, len(tail), 2):
+ try:
+ positions.append({"symbol": tail[i], "quantity": float(tail[i + 1])})
+ except ValueError:
+ result = {"error": f"invalid quantity for {tail[i]}"}
+ positions = None
+ break
+ if positions is not None:
+ result = get_portfolio_nav_history(positions, period)
+
elif command == "historical_period":
if len(args) < 2:
result = {"error": "Usage: python yfinance_data.py historical_period <symbol> [period] [interval]"}
@@ -746,6 +969,38 @@ def main(args=None):
symbols = args[1:]
result = get_batch_sparklines(symbols)
+ elif command == "batch_all":
+ # Unified hub-refresh endpoint: payload is a single JSON blob on argv[1]
+ # (or @tempfile via PythonRunner's arg-spill) describing quotes + sparklines
+ # + histories to fetch. One process, one yfinance warm-up, three family
+ # results. See MarketDataService::refresh().
+ if len(args) < 2:
+ result = {"error": "Usage: python yfinance_data.py batch_all <json_payload>"}
+ else:
+ raw = args[1]
+ # Handle PythonRunner arg-spill: args > ~8KB land as "@/tmp/…" and
+ # must be read back. Payloads for large symbol lists easily exceed
+ # that threshold on Windows (32KB cmdline limit).
+ if raw.startswith("@"):
+ path = raw[1:]
+ try:
+ with open(path, "r", encoding="utf-8") as f:
+ raw = f.read()
+ try:
+ import os as _os
+ _os.remove(path)
+ except Exception:
+ pass
+ except Exception as e:
+ result = {"error": f"batch_all: failed to read spill file: {e}"}
+ raw = None
+ if raw is not None:
+ try:
+ payload = json.loads(raw)
+ result = get_batch_all(payload)
+ except json.JSONDecodeError as e:
+ result = {"error": f"batch_all: invalid JSON payload: {e}"}
+
elif command == "resolve_symbol":
if len(args) < 2:
result = {"error": "Usage: python yfinance_data.py resolve_symbol <symbol>"}
@@ -773,5 +1028,119 @@ def main(args=None):
print(output)
return output
+# ── Daemon mode ──────────────────────────────────────────────────────────────
+#
+# Long-lived worker invoked by PythonWorker on the C++ side. Reads length-prefixed
+# JSON request frames from stdin, writes length-prefixed JSON response frames to
+# stdout. Keeps yfinance + pandas loaded so MarketDataService refreshes don't pay
+# the 2–3s import cost on every spawn.
+#
+# Frame format (stdin + stdout, network byte order):
+# [4 bytes big-endian uint32 length N] [N bytes UTF-8 JSON]
+#
+# Request JSON: {"id": <int>, "action": "batch_all"|"batch_quotes"|..., "payload": {...}}
+# Response JSON: {"id": <int>, "ok": true, "result": <any>} or
+# {"id": <int>, "ok": false, "error": "<msg>"}
+#
+# Special action "shutdown" causes a clean exit. EOF on stdin also exits.
+
+def _daemon_read_frame(stream):
+ """Read one length-prefixed frame. Returns bytes payload, or None on EOF."""
+ header = b""
+ while len(header) < 4:
+ chunk = stream.read(4 - len(header))
+ if not chunk:
+ return None
+ header += chunk
+ n = int.from_bytes(header, byteorder="big", signed=False)
+ if n == 0 or n > 64 * 1024 * 1024: # sanity: cap frames at 64 MB
+ return None
+ buf = b""
+ while len(buf) < n:
+ chunk = stream.read(n - len(buf))
+ if not chunk:
+ return None
+ buf += chunk
+ return buf
+
+
+def _daemon_write_frame(stream, data_bytes):
+ """Write one length-prefixed frame. `data_bytes` must be bytes."""
+ n = len(data_bytes)
+ stream.write(n.to_bytes(4, byteorder="big", signed=False))
+ stream.write(data_bytes)
+ stream.flush()
+
+
+def _daemon_dispatch(action, payload):
+ """Run one action and return the raw result object (not wrapped)."""
+ if action == "batch_all":
+ return get_batch_all(payload or {})
+ if action == "batch_quotes":
+ syms = (payload or {}).get("symbols") or []
+ return get_batch_quotes(syms)
+ if action == "batch_sparklines":
+ syms = (payload or {}).get("symbols") or []
+ return get_batch_sparklines(syms)
+ if action == "historical_period":
+ p = payload or {}
+ return get_historical_period(
+ p.get("symbol"), p.get("period", "6mo"), p.get("interval", "1d"))
+ if action == "quote":
+ return get_quote((payload or {}).get("symbol"))
+ if action == "info":
+ return get_info((payload or {}).get("symbol"))
+ if action == "news":
+ p = payload or {}
+ return get_news(p.get("symbol"), p.get("count", 20))
+ return {"error": f"Unknown action: {action}"}
+
+
+def run_daemon():
+ """Main daemon loop — read frame, dispatch, write frame, repeat."""
+ import io
+ # Use the raw binary stdio streams; we do our own framing.
+ stdin = sys.stdin.buffer
+ stdout = sys.stdout.buffer
+ # Ready marker so the C++ host knows imports are done and the worker is
+ # ready to accept requests. Uses the same framing.
+ try:
+ ready = json.dumps({"ready": True, "pid": __import__("os").getpid()}).encode("utf-8")
+ _daemon_write_frame(stdout, ready)
+ except Exception:
+ pass
+
+ while True:
+ frame = _daemon_read_frame(stdin)
+ if frame is None:
+ break # EOF or bad frame — exit
+ try:
+ req = json.loads(frame.decode("utf-8"))
+ except Exception as e:
+ err = {"id": 0, "ok": False, "error": f"bad request JSON: {e}"}
+ _daemon_write_frame(stdout, json.dumps(err).encode("utf-8"))
+ continue
+
+ req_id = req.get("id", 0)
+ action = req.get("action", "")
+ if action == "shutdown":
+ resp = {"id": req_id, "ok": True, "result": {"shutdown": True}}
+ _daemon_write_frame(stdout, json.dumps(resp).encode("utf-8"))
+ break
+
+ try:
+ result = _daemon_dispatch(action, req.get("payload"))
+ resp = {"id": req_id, "ok": True, "result": result}
+ except Exception as e:
+ resp = {"id": req_id, "ok": False, "error": str(e)}
+ try:
+ _daemon_write_frame(stdout, json.dumps(resp).encode("utf-8"))
+ except Exception:
+ break
+
+
if __name__ == "__main__":
- main()
+ if len(sys.argv) > 1 and sys.argv[1] == "--daemon":
+ run_daemon()
+ else:
+ main()
diff --git a/fincept-qt/src/ai_chat/AiChatScreen.cpp b/fincept-qt/src/ai_chat/AiChatScreen.cpp
index 92c59f1f1..d293ad8e7 100644
--- a/fincept-qt/src/ai_chat/AiChatScreen.cpp
+++ b/fincept-qt/src/ai_chat/AiChatScreen.cpp
@@ -37,6 +37,7 @@
#include <QToolButton>
#include <QtConcurrent/QtConcurrent>
+#include <cmath>
#include <memory>
namespace fincept::screens {
@@ -46,6 +47,30 @@ static constexpr const char* TAG = "AiChatScreen";
namespace fnt = fincept::ui::fonts;
namespace col = fincept::ui::colors;
+// ── Bubble sizing ─────────────────────────────────────────────────────────────
+//
+// Approach: QLabel with setWordWrap(true) + setMaximumWidth(N). QLabel's
+// built-in heightForWidth() handles height computation natively — no manual
+// measurement, no clone tricks, no crop risk. The label grows vertically as
+// text is set, and the surrounding QVBoxLayout picks that up automatically.
+//
+// These are the only sizing numbers we need: the column max widths and the
+// horizontal padding that bubble_style() bakes into the QFrame CSS. Inner
+// label width = col - 2 * padding_x.
+
+// Column widths (max). User bubbles are narrower so their right-aligned layout
+// floats toward the right edge; AI bubbles get more room.
+static constexpr int kUserColMaxWidth = 560;
+static constexpr int kAiColMaxWidth = 680;
+
+// Horizontal CSS padding in bubble_style(): "padding:10px 14px".
+static constexpr int kBubblePadX = 14;
+
+// The width QLabel should wrap at — the bubble's inner text area.
+static int bubble_inner_width(bool is_user) {
+ return (is_user ? kUserColMaxWidth : kAiColMaxWidth) - 2 * kBubblePadX;
+}
+
// ── Style helpers ─────────────────────────────────────────────────────────────
static QString bubble_style(const QString& role) {
@@ -67,7 +92,7 @@ static QString body_color(const QString& role) {
return col::TEXT_PRIMARY();
}
-// Default stylesheet for rendered markdown inside QTextEdit / QLabel bubbles.
+// Default stylesheet for rendered markdown inside QLabel bubbles.
// Comprehensive styling for LLM responses: paragraphs, lists, headings,
// code blocks, blockquotes, tables, and links.
static QString markdown_css(const QString& text_color) {
@@ -98,18 +123,6 @@ static QString markdown_css(const QString& text_color) {
.arg(text_color, col::AMBER(), col::BORDER_MED(), col::BG_RAISED(), col::TEXT_SECONDARY());
}
-// Override Qt's default blue palette on QTextEdit to match Obsidian theme.
-static void apply_obsidian_palette(QTextEdit* edit) {
- QPalette p = edit->palette();
- p.setColor(QPalette::Link, QColor(col::AMBER()));
- p.setColor(QPalette::LinkVisited, QColor(col::AMBER()));
- p.setColor(QPalette::Highlight, QColor(col::AMBER_DIM()));
- p.setColor(QPalette::HighlightedText, QColor(col::TEXT_PRIMARY()));
- p.setColor(QPalette::Base, Qt::transparent);
- p.setColor(QPalette::Text, QColor(col::TEXT_PRIMARY()));
- edit->setPalette(p);
-}
-
static QString generate_session_title() {
static const QStringList prefixes = {"Amber", "Apex", "Atlas", "Echo", "Flux", "Nova", "Slate", "Vector"};
static const QStringList nouns = {"Brief", "Drift", "Focus", "Ledger", "Macro", "Pulse", "Signal", "Tape"};
@@ -925,26 +938,27 @@ void AiChatScreen::on_send() {
void AiChatScreen::on_stream_chunk(const QString& chunk, bool done) {
// Snapshot QPointer to local — prevents TOCTOU between null-check and use.
- QTextEdit* bubble = streaming_bubble_;
+ QLabel* bubble = streaming_bubble_;
if (!bubble)
return;
// Tool-call clear sentinel: reset bubble content (removes partial XML)
if (chunk.startsWith("\x01__TOOL_CALL_CLEAR__")) {
- bubble->clear();
- bubble->setPlainText("Calling tool...");
+ bubble->setProperty("acc", QString("Calling tool..."));
+ bubble->setText("Calling tool...");
scroll_to_bottom();
return;
}
if (!chunk.isEmpty()) {
+ QString acc = bubble->property("acc").toString();
// If bubble shows the "Calling tool..." placeholder, replace it
- if (bubble->toPlainText() == "Calling tool...") {
- bubble->setPlainText(chunk);
- } else {
- bubble->moveCursor(QTextCursor::End);
- bubble->insertPlainText(chunk);
- }
+ if (acc == "Calling tool...")
+ acc = chunk;
+ else
+ acc += chunk;
+ bubble->setProperty("acc", acc);
+ bubble->setText(acc);
scroll_to_bottom();
}
Q_UNUSED(done)
@@ -962,8 +976,11 @@ void AiChatScreen::on_streaming_done(ai_chat::LlmResponse response) {
set_input_enabled(true);
if (!response.success) {
- if (streaming_bubble_)
- streaming_bubble_->setPlainText("Error: " + response.error);
+ if (streaming_bubble_) {
+ const QString err = "Error: " + response.error;
+ streaming_bubble_->setProperty("acc", err);
+ streaming_bubble_->setText(err);
+ }
streaming_bubble_ = nullptr;
return;
}
@@ -971,15 +988,16 @@ void AiChatScreen::on_streaming_done(ai_chat::LlmResponse response) {
const QString content = response.content;
if (streaming_bubble_) {
// Get final text (either from response or what was streamed)
- QString final_text = streaming_bubble_->toPlainText();
+ QString final_text = streaming_bubble_->property("acc").toString();
if (!content.isEmpty() && final_text.isEmpty())
final_text = content;
- // Re-render as markdown so **bold**, - lists, code blocks, etc. display properly
+ // Re-render as markdown so **bold**, - lists, code blocks, etc. display properly.
+ // Switching format on QLabel re-parses; no manual measurement needed.
if (!final_text.isEmpty()) {
- streaming_bubble_->document()->setDefaultStyleSheet(markdown_css(col::TEXT_PRIMARY()));
- streaming_bubble_->setMarkdown(final_text);
+ streaming_bubble_->setTextFormat(Qt::MarkdownText);
+ streaming_bubble_->setText(final_text);
+ streaming_bubble_->setProperty("acc", final_text);
}
- streaming_bubble_->setReadOnly(true);
// Show the copy button now that streaming is done
auto* copy_obj = streaming_bubble_->property("copy_btn").value<QObject*>();
@@ -1031,7 +1049,7 @@ void AiChatScreen::add_message_bubble(const QString& role, const QString& conten
auto* col_widget = new QWidget;
col_widget->setStyleSheet("background:transparent;");
- col_widget->setMaximumWidth(is_user ? 560 : 680);
+ col_widget->setMaximumWidth(is_user ? kUserColMaxWidth : kAiColMaxWidth);
auto* cvl = new QVBoxLayout(col_widget);
cvl->setContentsMargins(0, 0, 0, 0);
cvl->setSpacing(4);
@@ -1044,29 +1062,25 @@ void AiChatScreen::add_message_bubble(const QString& role, const QString& conten
.arg(fnt::TINY));
cvl->addWidget(role_lbl);
- // Bubble
+ // Bubble — QLabel auto-sizes to its content via heightForWidth(), so we
+ // just pin a max width and let Qt do the math. No scrollbars (QLabel has
+ // none), no clone tricks, no manual height callbacks.
auto* bubble = new QFrame;
bubble->setStyleSheet(bubble_style(role));
auto* bvl = new QVBoxLayout(bubble);
bvl->setContentsMargins(0, 0, 0, 0);
- auto* body = new QTextEdit;
- body->setReadOnly(true);
- body->setFrameShape(QFrame::NoFrame);
- body->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum);
- body->document()->setDocumentMargin(4);
- body->document()->setDefaultStyleSheet(markdown_css(body_color(role)));
- apply_obsidian_palette(body);
- body->setMarkdown(content);
- body->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
- body->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
- body->setStyleSheet(QString("QTextEdit{background:transparent;color:%1;border:none;font-size:%2px;}")
+ auto* body = new QLabel;
+ body->setTextFormat(Qt::MarkdownText);
+ body->setText(content);
+ body->setWordWrap(true);
+ body->setMaximumWidth(bubble_inner_width(is_user));
+ body->setTextInteractionFlags(Qt::TextBrowserInteraction);
+ body->setAlignment(Qt::AlignLeft | Qt::AlignTop);
+ body->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
+ body->setStyleSheet(QString("QLabel{background:transparent;color:%1;font-size:%2px;}")
.arg(body_color(role))
.arg(fnt::BODY));
- // Size to content
- body->document()->setTextWidth(is_user ? 520 : 640);
- const int doc_h = static_cast<int>(body->document()->size().height());
- body->setFixedHeight(qMax(doc_h + 16, 32));
bvl->addWidget(body);
cvl->addWidget(bubble);
@@ -1113,7 +1127,7 @@ void AiChatScreen::add_message_bubble(const QString& role, const QString& conten
messages_layout_->insertWidget(messages_layout_->count() - 1, row);
}
-QTextEdit* AiChatScreen::add_streaming_bubble() {
+QLabel* AiChatScreen::add_streaming_bubble() {
auto* row = new QWidget;
row->setStyleSheet("background:transparent;");
auto* rl = new QHBoxLayout(row);
@@ -1121,7 +1135,7 @@ QTextEdit* AiChatScreen::add_streaming_bubble() {
auto* col_widget = new QWidget;
col_widget->setStyleSheet("background:transparent;");
- col_widget->setMaximumWidth(680);
+ col_widget->setMaximumWidth(kAiColMaxWidth);
auto* cvl = new QVBoxLayout(col_widget);
cvl->setContentsMargins(0, 0, 0, 0);
cvl->setSpacing(4);
@@ -1137,29 +1151,23 @@ QTextEdit* AiChatScreen::add_streaming_bubble() {
auto* bvl = new QVBoxLayout(bubble);
bvl->setContentsMargins(0, 0, 0, 0);
- auto* body = new QTextEdit;
- body->setReadOnly(false);
- body->setFrameShape(QFrame::NoFrame);
- body->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum);
- body->document()->setDocumentMargin(4);
- body->document()->setDefaultStyleSheet(markdown_css(col::TEXT_PRIMARY()));
- apply_obsidian_palette(body);
- body->setMinimumHeight(32);
- body->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
- body->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
- body->setWordWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
- body->setStyleSheet(QString("QTextEdit{background:transparent;color:%1;border:none;font-size:%2px;}")
+ // Streaming body — QLabel with plain-text format during streaming (appending
+ // chunks as markdown would re-parse on every token; waste). on_streaming_done
+ // switches to Qt::MarkdownText and re-renders the final accumulated text.
+ // Accumulated text is stored on the widget as a dynamic property "acc" so
+ // chunk handlers don't need external state.
+ auto* body = new QLabel;
+ body->setTextFormat(Qt::PlainText);
+ body->setText({});
+ body->setProperty("acc", QString{});
+ body->setWordWrap(true);
+ body->setMaximumWidth(bubble_inner_width(/*is_user=*/false));
+ body->setTextInteractionFlags(Qt::TextBrowserInteraction);
+ body->setAlignment(Qt::AlignLeft | Qt::AlignTop);
+ body->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
+ body->setStyleSheet(QString("QLabel{background:transparent;color:%1;font-size:%2px;}")
.arg(col::TEXT_PRIMARY())
.arg(fnt::BODY));
- // Grow height to fit content as chunks stream in
- connect(body->document(), &QTextDocument::contentsChanged, body, [body, bubble, row]() {
- body->document()->setTextWidth(body->viewport()->width() > 0 ? body->viewport()->width() : 640);
- const int doc_h = static_cast<int>(body->document()->size().height());
- const int new_h = qMax(doc_h + 16, 32);
- body->setFixedHeight(new_h);
- bubble->adjustSize();
- row->adjustSize();
- });
bvl->addWidget(body);
cvl->addWidget(bubble);
@@ -1175,7 +1183,7 @@ QTextEdit* AiChatScreen::add_streaming_bubble() {
.arg(col::TEXT_PRIMARY()));
copy_btn->hide();
connect(copy_btn, &QPushButton::clicked, this, [body, copy_btn]() {
- QApplication::clipboard()->setText(body->toPlainText());
+ QApplication::clipboard()->setText(body->property("acc").toString());
copy_btn->setText("Copied!");
QTimer::singleShot(1500, copy_btn, [copy_btn]() { copy_btn->setText("Copy"); });
});
diff --git a/fincept-qt/src/ai_chat/AiChatScreen.h b/fincept-qt/src/ai_chat/AiChatScreen.h
index 6665f3e38..7c6d7b998 100644
--- a/fincept-qt/src/ai_chat/AiChatScreen.h
+++ b/fincept-qt/src/ai_chat/AiChatScreen.h
@@ -11,7 +11,6 @@
#include <QPointer>
#include <QPushButton>
#include <QScrollArea>
-#include <QTextEdit>
#include <QTimer>
#include <QVBoxLayout>
#include <QWidget>
@@ -92,7 +91,7 @@ class AiChatScreen : public QWidget, public IStatefulScreen {
mutable QMutex history_mutex_;
std::vector<ai_chat::ConversationMessage> history_;
bool streaming_ = false;
- QPointer<QTextEdit> streaming_bubble_;
+ QPointer<QLabel> streaming_bubble_;
int total_tokens_ = 0;
int total_messages_ = 0;
@@ -111,7 +110,7 @@ class AiChatScreen : public QWidget, public IStatefulScreen {
void load_messages(const QString& session_id);
void create_new_session();
void add_message_bubble(const QString& role, const QString& content, const QString& timestamp = {});
- QTextEdit* add_streaming_bubble();
+ QLabel* add_streaming_bubble();
void clear_messages();
void scroll_to_bottom();
void set_input_enabled(bool enabled);
diff --git a/fincept-qt/src/ai_chat/LlmService.cpp b/fincept-qt/src/ai_chat/LlmService.cpp
index 71306b799..e04b960f2 100644
--- a/fincept-qt/src/ai_chat/LlmService.cpp
+++ b/fincept-qt/src/ai_chat/LlmService.cpp
@@ -33,6 +33,102 @@ namespace fincept::ai_chat {
static constexpr const char* TAG = "LlmService";
+// ============================================================================
+// Content extractors (shared across non-streaming paths and tool follow-ups)
+// ============================================================================
+
+// Extract user-visible text from an OpenAI-compatible `message` object.
+// Handles: plain `content` string, reasoning-only replies (`reasoning_content`),
+// content-as-parts arrays (some providers echo OpenAI Responses-style parts),
+// and refusal messages. Never returns the empty string when the API actually
+// replied with something — the caller can rely on `isEmpty()` meaning "no reply".
+static QString extract_openai_message_text(const QJsonObject& msg) {
+ // Plain string content — the standard shape
+ QJsonValue cv = msg["content"];
+ if (cv.isString()) {
+ QString s = cv.toString();
+ if (!s.isEmpty())
+ return s;
+ } else if (cv.isArray()) {
+ // Some providers (GPT-4o vision, OpenRouter multimodal echoes) return
+ // content as an array of {type, text} parts. Concatenate all text parts.
+ QString joined;
+ for (const auto& pv : cv.toArray()) {
+ QJsonObject p = pv.toObject();
+ QString type = p["type"].toString();
+ if (type == "text" || type == "output_text")
+ joined += p["text"].toString();
+ }
+ if (!joined.isEmpty())
+ return joined;
+ }
+
+ // Reasoning models (kimi-k2.5/k2.6/k2-thinking, deepseek-reasoner, some
+ // xAI grok-4 reasoning variants) put the final answer in `reasoning_content`
+ // when max_tokens is exhausted mid-reasoning, or when `content` is deliberately
+ // empty. Fall back so the user sees the chain-of-thought instead of nothing.
+ QString rc = msg["reasoning_content"].toString();
+ if (!rc.isEmpty())
+ return rc;
+
+ // Some OpenAI-compatible providers (newer OpenAI, Groq) emit a `refusal`
+ // field instead of content when the model declines. Surfacing it is better
+ // than returning blank.
+ QString refusal = msg["refusal"].toString();
+ if (!refusal.isEmpty())
+ return refusal;
+
+ return {};
+}
+
+// Extract user-visible text from an Anthropic /v1/messages content-blocks array.
+// Handles: `text` blocks (the normal case), `thinking` blocks (extended-thinking
+// whose text lives in block.thinking — falls back only when no text block exists),
+// and concatenates multiple text blocks (Claude can emit several when a tool_use
+// block sits between them).
+static QString extract_anthropic_content_text(const QJsonArray& content) {
+ QString text;
+ QString thinking_fallback;
+ for (const auto& bv : content) {
+ QJsonObject b = bv.toObject();
+ const QString type = b["type"].toString();
+ if (type == "text") {
+ text += b["text"].toString();
+ } else if (type == "thinking" && thinking_fallback.isEmpty()) {
+ thinking_fallback = b["thinking"].toString();
+ }
+ }
+ if (!text.isEmpty())
+ return text;
+ return thinking_fallback; // may be empty — caller decides
+}
+
+// Extract user-visible text from a Gemini candidate's parts array.
+// Handles: multiple `text` parts (Gemini often splits long replies),
+// `thought:true` parts (extended thinking — only fallback if no normal text),
+// and silently skips `functionCall` parts which the caller handles separately.
+static QString extract_gemini_parts_text(const QJsonArray& parts) {
+ QString text;
+ QString thought_fallback;
+ for (const auto& pv : parts) {
+ QJsonObject p = pv.toObject();
+ if (p.contains("functionCall"))
+ continue;
+ QString t = p["text"].toString();
+ if (t.isEmpty())
+ continue;
+ if (p["thought"].toBool()) {
+ if (thought_fallback.isEmpty())
+ thought_fallback = t;
+ } else {
+ text += t;
+ }
+ }
+ if (!text.isEmpty())
+ return text;
+ return thought_fallback;
+}
+
// ============================================================================
// Singleton
// ============================================================================
@@ -244,8 +340,12 @@ QString LlmService::get_endpoint_url() const {
return "https://openrouter.ai/api/v1/chat/completions";
if (p == "minimax")
return "https://api.minimax.io/v1/chat/completions";
+ if (p == "kimi")
+ return "https://api.moonshot.ai/v1/chat/completions";
if (p == "ollama")
return "http://localhost:11434/v1/chat/completions";
+ if (p == "xai")
+ return "https://api.x.ai/v1/chat/completions";
return {};
}
@@ -257,7 +357,7 @@ QMap<QString, QString> LlmService::get_headers() const {
if (p == "anthropic") {
if (!api_key_.isEmpty())
h["x-api-key"] = api_key_;
- h["anthropic-version"] = "2024-10-22";
+ h["anthropic-version"] = "2023-06-01";
} else if (p == "gemini" || p == "google") {
if (!api_key_.isEmpty())
h["x-goog-api-key"] = api_key_;
@@ -274,6 +374,11 @@ QMap<QString, QString> LlmService::get_headers() const {
// OpenAI-compatible
if (!api_key_.isEmpty())
h["Authorization"] = "Bearer " + api_key_;
+ if (p == "openrouter") {
+ // Optional attribution — appears on openrouter.ai/rankings leaderboard
+ h["HTTP-Referer"] = "https://fincept.in";
+ h["X-Title"] = "Fincept Terminal";
+ }
}
return h;
}
@@ -285,6 +390,15 @@ QMap<QString, QString> LlmService::get_headers() const {
QJsonObject LlmService::build_openai_request(const QString& user_message,
const std::vector<ConversationMessage>& history, bool stream,
bool with_tools) {
+ const QString model_lower = model_.toLower();
+
+ // deepseek-reasoner doesn't accept `tools`.
+ const bool is_ds_reasoner = (provider_ == "deepseek" && model_lower.contains("reasoner"));
+
+ // Groq's whisper-* (audio) and llama-guard-* (safety classifier) do not accept tools.
+ const bool groq_no_tools =
+ (provider_ == "groq" && (model_lower.startsWith("whisper-") || model_lower.contains("llama-guard")));
+
QJsonArray messages;
if (!system_prompt_.isEmpty())
messages.append(QJsonObject{{"role", "system"}, {"content", system_prompt_}});
@@ -295,18 +409,23 @@ QJsonObject LlmService::build_openai_request(const QString& user_message,
QJsonObject req;
req["model"] = model_;
req["messages"] = messages;
- // MiniMax requires temperature in (0.0, 1.0]; clamp if needed
- if (provider_ == "minimax") {
- double t = std::max(0.01, std::min(temperature_, 1.0));
- req["temperature"] = t;
- } else {
- req["temperature"] = temperature_;
- }
- req["max_tokens"] = max_tokens_;
- if (stream)
+ // Temperature intentionally omitted — each provider uses its own default.
+ // OpenAI deprecated max_tokens; gpt-5 / o-series require max_completion_tokens.
+ // xAI also prefers max_completion_tokens. Other OpenAI-compatible providers
+ // still expect max_tokens.
+ if (provider_ == "openai" || provider_ == "xai")
+ req["max_completion_tokens"] = max_tokens_;
+ else
+ req["max_tokens"] = max_tokens_;
+ if (stream) {
req["stream"] = true;
+ // Streamed OpenAI / xAI responses omit usage unless we opt in
+ if (provider_ == "openai" || provider_ == "xai")
+ req["stream_options"] = QJsonObject{{"include_usage", true}};
+ }
- if (!stream && with_tools && tools_enabled_) {
+ // deepseek-reasoner rejects tools entirely.
+ if (!stream && with_tools && tools_enabled_ && !is_ds_reasoner && !groq_no_tools) {
QJsonArray tools = mcp::McpService::instance().format_tools_for_openai();
if (!tools.isEmpty())
req["tools"] = tools;
@@ -327,8 +446,7 @@ QJsonObject LlmService::build_anthropic_request(const QString& user_message,
req["model"] = model_;
req["messages"] = messages;
req["max_tokens"] = max_tokens_;
- if (temperature_ != 0.7)
- req["temperature"] = temperature_;
+ // Temperature intentionally omitted — Anthropic defaults to 1.0.
if (!system_prompt_.isEmpty())
req["system"] = system_prompt_;
if (stream)
@@ -367,7 +485,7 @@ QJsonObject LlmService::build_gemini_request(const QString& user_message,
contents.append(QJsonObject{{"role", "user"}, {"parts", QJsonArray{QJsonObject{{"text", user_message}}}}});
QJsonObject gen_cfg;
- gen_cfg["temperature"] = temperature_;
+ // Temperature intentionally omitted — Gemini defaults to 1.0.
gen_cfg["maxOutputTokens"] = max_tokens_;
QJsonObject req;
@@ -483,8 +601,24 @@ LlmService::HttpResult LlmService::eventloop_request(const QString& method, cons
auto err_doc = QJsonDocument::fromJson(result.body);
if (!err_doc.isNull() && err_doc.isObject()) {
QJsonObject ej = err_doc.object();
+ // Top-level {"message": ...} (OpenAI/Anthropic legacy shape)
if (ej.contains("message") && ej["message"].isString())
server_msg = ej["message"].toString();
+ // Nested {"error": {"message": ..., "metadata": {"raw": ...}}}
+ // (OpenAI current, OpenRouter, DeepSeek, Groq all use this shape)
+ if (server_msg.isEmpty() && ej.contains("error") && ej["error"].isObject()) {
+ QJsonObject eo = ej["error"].toObject();
+ if (eo.contains("message") && eo["message"].isString())
+ server_msg = eo["message"].toString();
+ // OpenRouter surfaces upstream errors in metadata.raw
+ if (eo.contains("metadata") && eo["metadata"].isObject()) {
+ QJsonObject md = eo["metadata"].toObject();
+ QString raw = md["raw"].toString();
+ QString provider_name = md["provider_name"].toString();
+ if (!raw.isEmpty())
+ server_msg += " (upstream " + provider_name + ": " + raw + ")";
+ }
+ }
}
result.error = server_msg.isEmpty() ? QString("HTTP %1: %2").arg(result.status).arg(reply->errorString())
: QString("HTTP %1: %2").arg(result.status).arg(server_msg);
@@ -561,7 +695,7 @@ LlmResponse LlmService::fincept_async_request(const QString& user_message,
QJsonObject submit_body;
submit_body["prompt"] = prompt;
submit_body["max_tokens"] = max_tokens_;
- submit_body["temperature"] = temperature_;
+ // Temperature intentionally omitted — Fincept backend uses its own default.
auto hdr = get_headers();
const QString async_url = "https://api.fincept.in/research/llm/async";
@@ -691,8 +825,8 @@ LlmResponse LlmService::do_request(const QString& user_message, const std::vecto
req_body = build_anthropic_request(user_message, history, false);
} else if (provider_ == "gemini" || provider_ == "google") {
req_body = build_gemini_request(user_message, history);
- if (!api_key_.isEmpty())
- url += "?key=" + api_key_;
+ // Auth goes via x-goog-api-key header (set by get_headers()).
+ // Do not append ?key= to URL — it leaks the key into access logs.
} else if (provider_ == "fincept") {
// Fincept uses two separate endpoints:
// Primary response → async (submit + poll, returns richer model output)
@@ -766,36 +900,24 @@ LlmResponse LlmService::do_request(const QString& user_message, const std::vecto
fu["model"] = model_;
fu["messages"] = loop_msgs;
fu["max_tokens"] = max_tokens_;
- if (temperature_ != 0.7)
- fu["temperature"] = temperature_;
+ // Temperature intentionally omitted — Anthropic default.
if (!system_prompt_.isEmpty())
fu["system"] = system_prompt_;
auto fu_http = blocking_post(url, fu, hdr);
if (fu_http.success) {
auto fu_doc = QJsonDocument::fromJson(fu_http.body);
- if (!fu_doc.isNull()) {
- QJsonArray fu_content = fu_doc.object()["content"].toArray();
- for (const auto& b : fu_content) {
- if (b.toObject()["type"].toString() == "text") {
- resp.content = b.toObject()["text"].toString();
- break;
- }
- }
- }
+ if (!fu_doc.isNull())
+ resp.content = extract_anthropic_content_text(fu_doc.object()["content"].toArray());
} else {
resp.error = "Anthropic tool follow-up failed: " + fu_http.error;
return resp;
}
} else {
- // Normal text response — find first text block
- for (const auto& block_val : content) {
- QJsonObject block = block_val.toObject();
- if (block["type"].toString() == "text") {
- resp.content = block["text"].toString();
- break;
- }
- }
+ // Normal text response — concatenate all text blocks and fall back
+ // to extended-thinking content if no text was emitted (e.g. when
+ // max_tokens is exhausted mid-thinking).
+ resp.content = extract_anthropic_content_text(content);
}
} else if (provider_ == "gemini" || provider_ == "google") {
@@ -814,7 +936,10 @@ LlmResponse LlmService::do_request(const QString& user_message, const std::vecto
if (has_function_calls) {
LOG_INFO(TAG, "Gemini requested function call(s)");
- QString tool_results;
+ // Execute each tool call and build matching functionResponse parts.
+ // Gemini's multi-turn contract: user turn → model turn with functionCall
+ // parts → user turn with functionResponse parts (NOT plain text).
+ QJsonArray fn_response_parts;
for (const auto& part_val : parts) {
QJsonObject part = part_val.toObject();
if (!part.contains("functionCall"))
@@ -826,36 +951,46 @@ LlmResponse LlmService::do_request(const QString& user_message, const std::vecto
LOG_INFO(TAG, "Executing Gemini tool: " + fn_name);
auto tr = mcp::McpService::instance().execute_openai_function(fn_name, fn_args);
- QString result_content;
- if (!tr.message.isEmpty())
- result_content = tr.message;
- else if (!tr.data.isNull() && !tr.data.isUndefined())
- result_content =
- QString::fromUtf8(QJsonDocument(tr.data.toObject()).toJson(QJsonDocument::Compact))
- .left(4000);
+ // Build a JSON response object. Gemini requires response to be an
+ // object (string values are wrapped under a key).
+ QJsonObject response_obj;
+ if (!tr.data.isNull() && !tr.data.isUndefined() && tr.data.isObject())
+ response_obj = tr.data.toObject();
+ else if (!tr.message.isEmpty())
+ response_obj["result"] = tr.message;
else
- result_content =
- QString::fromUtf8(QJsonDocument(tr.to_json()).toJson(QJsonDocument::Compact)).left(4000);
+ response_obj = tr.to_json();
- int sep = fn_name.indexOf("__");
- QString short_name = (sep >= 0) ? fn_name.mid(sep + 2) : fn_name;
- tool_results += "\n**Tool: " + short_name + "**\n" + result_content + "\n";
+ fn_response_parts.append(QJsonObject{
+ {"functionResponse",
+ QJsonObject{{"name", fn_name}, {"response", response_obj}}}});
}
- // Follow-up: ask Gemini to summarize tool results
- if (!tool_results.isEmpty()) {
+ if (!fn_response_parts.isEmpty()) {
+ // Rebuild contents: prior history + original user + model(functionCall) + user(functionResponse)
QJsonArray fu_contents;
+ for (const auto& m : history) {
+ if (m.role == "system")
+ continue;
+ QString role = (m.role == "assistant") ? "model" : "user";
+ fu_contents.append(QJsonObject{
+ {"role", role},
+ {"parts", QJsonArray{QJsonObject{{"text", m.content}}}}});
+ }
+ fu_contents.append(QJsonObject{
+ {"role", "user"},
+ {"parts", QJsonArray{QJsonObject{{"text", user_message}}}}});
+ fu_contents.append(QJsonObject{
+ {"role", "model"},
+ {"parts", parts}}); // echo the functionCall parts verbatim
fu_contents.append(QJsonObject{
{"role", "user"},
- {"parts", QJsonArray{QJsonObject{
- {"text", "The user asked: \"" + user_message +
- "\"\n\n"
- "Tool results:\n" +
- tool_results + "\n\nPlease provide a clear, concise summary."}}}}});
+ {"parts", fn_response_parts}});
+
QJsonObject fu_body;
fu_body["contents"] = fu_contents;
QJsonObject gen_cfg;
- gen_cfg["temperature"] = temperature_;
+ // Temperature intentionally omitted — Gemini default.
gen_cfg["maxOutputTokens"] = max_tokens_;
fu_body["generationConfig"] = gen_cfg;
if (!system_prompt_.isEmpty())
@@ -867,20 +1002,32 @@ LlmResponse LlmService::do_request(const QString& user_message, const std::vecto
auto fu_doc = QJsonDocument::fromJson(fu.body);
if (!fu_doc.isNull()) {
QJsonArray fu_cands = fu_doc.object()["candidates"].toArray();
- if (!fu_cands.isEmpty()) {
- QJsonArray fu_parts = fu_cands[0].toObject()["content"].toObject()["parts"].toArray();
- if (!fu_parts.isEmpty())
- resp.content = fu_parts[0].toObject()["text"].toString();
- }
+ if (!fu_cands.isEmpty())
+ resp.content = extract_gemini_parts_text(
+ fu_cands[0].toObject()["content"].toObject()["parts"].toArray());
}
}
- if (resp.content.isEmpty())
- resp.content = tool_results;
+ if (resp.content.isEmpty()) {
+ // Fallback: render function responses as readable text
+ QString fallback;
+ for (const auto& pv : fn_response_parts) {
+ QJsonObject fr = pv.toObject()["functionResponse"].toObject();
+ QString fn_name = fr["name"].toString();
+ int sep = fn_name.indexOf("__");
+ QString short_name = (sep >= 0) ? fn_name.mid(sep + 2) : fn_name;
+ fallback += "\n**Tool: " + short_name + "**\n" +
+ QString::fromUtf8(
+ QJsonDocument(fr["response"].toObject()).toJson(QJsonDocument::Compact))
+ .left(4000) +
+ "\n";
+ }
+ resp.content = fallback;
+ }
}
} else {
- // Normal text response
- if (!parts.isEmpty())
- resp.content = parts[0].toObject()["text"].toString();
+ // Normal text response — concatenate all text parts; fall back
+ // to `thought:true` parts if no normal text was emitted.
+ resp.content = extract_gemini_parts_text(parts);
}
}
@@ -889,9 +1036,8 @@ LlmResponse LlmService::do_request(const QString& user_message, const std::vecto
// {"success":true,"data":{"choices":[{"message":{"role":"assistant","content":"..."}}],...}}
QJsonObject data = rj.contains("data") ? rj["data"].toObject() : rj;
QJsonArray choices = data["choices"].toArray();
- if (!choices.isEmpty()) {
- resp.content = choices[0].toObject()["message"].toObject()["content"].toString();
- }
+ if (!choices.isEmpty())
+ resp.content = extract_openai_message_text(choices[0].toObject()["message"].toObject());
// API returned success=true but empty response text — treat as soft error
if (resp.content.isEmpty()) {
resp.error = "Fincept LLM returned an empty response. Please try again.";
@@ -940,8 +1086,10 @@ LlmResponse LlmService::do_request(const QString& user_message, const std::vecto
return resp;
} else {
- // Normal text response
- resp.content = msg["content"].toString();
+ // Normal text response — helper handles plain content, reasoning
+ // models (kimi-k2.x / deepseek-reasoner), content-as-parts arrays,
+ // and refusal messages in one place.
+ resp.content = extract_openai_message_text(msg);
}
}
}
@@ -979,7 +1127,7 @@ LlmResponse LlmService::do_tool_loop(QJsonArray loop_messages, const QString& ur
QJsonObject fu;
fu["model"] = model_;
fu["messages"] = loop_messages;
- fu["temperature"] = temperature_;
+ // Temperature intentionally omitted — provider default.
fu["max_tokens"] = max_tokens_;
QJsonArray tools = mcp::McpService::instance().format_tools_for_openai();
@@ -1028,7 +1176,7 @@ LlmResponse LlmService::do_tool_loop(QJsonArray loop_messages, const QString& ur
}
// Final text response
- resp.content = msg["content"].toString();
+ resp.content = extract_openai_message_text(msg);
parse_usage(resp, rj, provider_);
resp.success = !resp.content.isEmpty();
return resp;
@@ -1266,8 +1414,7 @@ std::optional<LlmResponse> LlmService::try_extract_and_execute_text_tool_calls(c
follow_body["model"] = model_;
follow_body["messages"] = msgs;
follow_body["max_tokens"] = max_tokens_;
- if (temperature_ != 0.7)
- follow_body["temperature"] = temperature_;
+ // Temperature intentionally omitted — Anthropic default.
if (!system_prompt_.isEmpty())
follow_body["system"] = system_prompt_;
} else if (provider_ == "fincept") {
@@ -1287,7 +1434,7 @@ std::optional<LlmResponse> LlmService::try_extract_and_execute_text_tool_calls(c
msgs.append(QJsonObject{{"role", "user"}, {"content", follow_prompt}});
follow_body["model"] = model_;
follow_body["messages"] = msgs;
- follow_body["temperature"] = temperature_;
+ // Temperature intentionally omitted — provider default.
follow_body["max_tokens"] = max_tokens_;
}
@@ -1311,23 +1458,17 @@ std::optional<LlmResponse> LlmService::try_extract_and_execute_text_tool_calls(c
// Extract text from follow-up response (provider-aware)
if (provider_ == "anthropic") {
- QJsonArray fu_content = fu_rj["content"].toArray();
- for (const auto& b : fu_content) {
- if (b.toObject()["type"].toString() == "text") {
- resp.content = b.toObject()["text"].toString();
- break;
- }
- }
+ resp.content = extract_anthropic_content_text(fu_rj["content"].toArray());
} else if (provider_ == "fincept") {
// /research/chat: {"success":true,"data":{"choices":[{"message":{"content":"..."}}]}}
QJsonObject data = fu_rj.contains("data") ? fu_rj["data"].toObject() : fu_rj;
QJsonArray fu_choices = data["choices"].toArray();
if (!fu_choices.isEmpty())
- resp.content = fu_choices[0].toObject()["message"].toObject()["content"].toString();
+ resp.content = extract_openai_message_text(fu_choices[0].toObject()["message"].toObject());
} else {
QJsonArray choices = fu_rj["choices"].toArray();
if (!choices.isEmpty())
- resp.content = choices[0].toObject()["message"].toObject()["content"].toString();
+ resp.content = extract_openai_message_text(choices[0].toObject()["message"].toObject());
}
if (resp.content.isEmpty())
@@ -1383,6 +1524,7 @@ LlmResponse LlmService::do_streaming_request(const QString& user_message,
QByteArray partial_line;
QString accumulated;
+ QJsonObject final_usage_obj;
bool done = false;
bool tool_call_detected = false;
@@ -1423,6 +1565,17 @@ LlmResponse LlmService::do_streaming_request(const QString& user_message,
return;
}
+ // Capture usage chunk (OpenAI sends usage in a trailing chunk with
+ // empty choices[] when stream_options.include_usage=true)
+ {
+ auto usage_doc = QJsonDocument::fromJson(data.toUtf8());
+ if (!usage_doc.isNull() && usage_doc.isObject()) {
+ QJsonObject uobj = usage_doc.object();
+ if (uobj.contains("usage") && uobj["usage"].isObject())
+ final_usage_obj = uobj["usage"].toObject();
+ }
+ }
+
// Detect tool calls in streaming SSE — all providers
if (!tool_call_detected) {
auto doc = QJsonDocument::fromJson(data.toUtf8());
@@ -1526,6 +1679,10 @@ LlmResponse LlmService::do_streaming_request(const QString& user_message,
} else if (status >= 200 && status < 300) {
resp.content = accumulated;
resp.success = true;
+ if (!final_usage_obj.isEmpty()) {
+ QJsonObject wrap{{"usage", final_usage_obj}};
+ parse_usage(resp, wrap, provider_);
+ }
} else {
resp.error = QString("HTTP %1").arg(status);
}
@@ -1549,8 +1706,18 @@ QString LlmService::parse_sse_chunk(const QString& data, const QString& provider
QJsonObject j = doc.object();
if (provider == "anthropic") {
+ // delta is a tagged union. text_delta carries the final answer;
+ // thinking_delta carries the chain-of-thought for extended-thinking
+ // models (claude-3-7 / claude-opus-4+ with `thinking` param). Surfacing
+ // both keeps the UI responsive during long reasoning phases. Other
+ // delta types (input_json_delta, signature_delta) must not be rendered.
if (j["type"].toString() == "content_block_delta") {
- return j["delta"].toObject()["text"].toString();
+ QJsonObject delta = j["delta"].toObject();
+ const QString dtype = delta["type"].toString();
+ if (dtype == "text_delta")
+ return delta["text"].toString();
+ if (dtype == "thinking_delta")
+ return delta["thinking"].toString();
}
return {};
}
@@ -1559,8 +1726,25 @@ QString LlmService::parse_sse_chunk(const QString& data, const QString& provider
QJsonArray choices = j["choices"].toArray();
if (!choices.isEmpty()) {
QJsonObject delta = choices[0].toObject()["delta"].toObject();
- if (!delta["content"].isNull() && !delta["content"].isUndefined())
- return delta["content"].toString();
+ if (!delta["content"].isNull() && !delta["content"].isUndefined()) {
+ QString s = delta["content"].toString();
+ if (!s.isEmpty())
+ return s;
+ }
+ // Reasoning models (kimi-k2.5 / kimi-k2.6 / kimi-k2-thinking*, deepseek-reasoner,
+ // grok-4 reasoning variants) stream their chain-of-thought as
+ // `delta.reasoning_content` and only emit `delta.content` after reasoning
+ // completes. Surface reasoning deltas so the user sees progress instead
+ // of a blank bubble for 10+ seconds.
+ if (!delta["reasoning_content"].isNull() && !delta["reasoning_content"].isUndefined()) {
+ QString s = delta["reasoning_content"].toString();
+ if (!s.isEmpty())
+ return s;
+ }
+ // Refusal deltas — newer OpenAI and some Groq safety paths stream a
+ // `refusal` field in place of `content` when the model declines.
+ if (!delta["refusal"].isNull() && !delta["refusal"].isUndefined())
+ return delta["refusal"].toString();
}
return {};
}
@@ -1606,10 +1790,8 @@ QString LlmService::get_models_url(const QString& provider, const QString& api_k
if (p == "anthropic")
return "https://api.anthropic.com/v1/models?limit=1000";
if (p == "gemini" || p == "google") {
- QString url = "https://generativelanguage.googleapis.com/v1beta/models?pageSize=100";
- if (!api_key.isEmpty())
- url += "&key=" + api_key;
- return url;
+ // Auth goes via x-goog-api-key header (set by get_models_headers()).
+ return "https://generativelanguage.googleapis.com/v1beta/models?pageSize=100";
}
if (p == "groq")
return "https://api.groq.com/openai/v1/models";
@@ -1623,6 +1805,10 @@ QString LlmService::get_models_url(const QString& provider, const QString& api_k
base.chop(1);
return base + "/api/tags";
}
+ if (p == "xai")
+ return "https://api.x.ai/v1/models";
+ if (p == "kimi")
+ return "https://api.moonshot.ai/v1/models";
if (p == "fincept")
return "https://api.fincept.in/research/llm/models";
// minimax: no public /v1/models endpoint — fallback models used instead
@@ -1636,7 +1822,7 @@ QMap<QString, QString> LlmService::get_models_headers(const QString& provider, c
if (p == "anthropic") {
if (!api_key.isEmpty())
h["x-api-key"] = api_key;
- h["anthropic-version"] = "2024-10-22";
+ h["anthropic-version"] = "2023-06-01";
} else if (p == "gemini" || p == "google") {
// Key is in URL query param
if (!api_key.isEmpty())
diff --git a/fincept-qt/src/ai_chat/LlmService.h b/fincept-qt/src/ai_chat/LlmService.h
index c69c011d1..91c090a8e 100644
--- a/fincept-qt/src/ai_chat/LlmService.h
+++ b/fincept-qt/src/ai_chat/LlmService.h
@@ -26,7 +26,7 @@ namespace fincept::ai_chat {
inline bool provider_supports_streaming(const QString& provider) {
return provider == "openai" || provider == "anthropic" || provider == "gemini" || provider == "google" ||
provider == "groq" || provider == "deepseek" || provider == "openrouter" || provider == "minimax" ||
- provider == "ollama" || provider == "fincept";
+ provider == "kimi" || provider == "ollama" || provider == "xai" || provider == "fincept";
}
inline bool provider_requires_api_key(const QString& provider) {
diff --git a/fincept-qt/src/app/DockScreenRouter.cpp b/fincept-qt/src/app/DockScreenRouter.cpp
index 371b9c2a2..1a94c9039 100644
--- a/fincept-qt/src/app/DockScreenRouter.cpp
+++ b/fincept-qt/src/app/DockScreenRouter.cpp
@@ -1,14 +1,26 @@
#include "app/DockScreenRouter.h"
+#include "auth/InactivityGuard.h"
+#include "core/components/PopularityTracker.h"
#include "core/logging/Logger.h"
#include "core/session/ScreenStateManager.h"
#include "core/session/SessionManager.h"
+#include "core/symbol/IGroupLinked.h"
+#include "core/symbol/SymbolContext.h"
+#include "core/symbol/SymbolRef.h"
#include "screens/IStatefulScreen.h"
+#include "ui/widgets/GroupBadge.h"
+#include <QApplication>
+#include <QClipboard>
+#include <QContextMenuEvent>
#include <QEvent>
+#include <QHBoxLayout>
+#include <QInputDialog>
#include <QKeyEvent>
#include <QLabel>
#include <QLineEdit>
+#include <QMenu>
#include <QVBoxLayout>
#include <DockAreaWidget.h>
@@ -74,6 +86,101 @@ QString DockScreenRouter::title_for_id(const QString& id) {
}
DockScreenRouter::DockScreenRouter(ads::CDockManager* manager, QObject* parent) : QObject(parent), manager_(manager) {
+ // Route SymbolContext broadcasts to the matching IGroupLinked screens.
+ // One central listener per router — cheaper and easier to reason about
+ // than per-screen connections, and it gives us a single filter point
+ // for source-suppression (skip re-delivery to the publisher).
+ connect(&SymbolContext::instance(), &SymbolContext::group_symbol_changed, this,
+ &DockScreenRouter::on_group_symbol_changed_external);
+}
+
+void DockScreenRouter::on_group_symbol_changed_external(SymbolGroup g, const SymbolRef& ref, QObject* source) {
+ for (auto it = group_linked_.begin(); it != group_linked_.end(); ++it) {
+ IGroupLinked* linked = it.value();
+ if (!linked || linked->group() != g)
+ continue;
+ auto* as_obj = dynamic_cast<QObject*>(linked);
+ if (as_obj && as_obj == source)
+ continue; // skip feedback to the publisher
+ linked->on_group_symbol_changed(ref);
+ }
+}
+
+QWidget* DockScreenRouter::wrap_with_group_badge(const QString& id, QWidget* screen) {
+ if (!screen)
+ return screen;
+ auto* linked = dynamic_cast<IGroupLinked*>(screen);
+ if (!linked)
+ return screen; // screen doesn't opt in — no wrapping, no overhead
+
+ // Container with a narrow strip on top holding the badge. The badge is
+ // parented to the strip so deleting the screen cascades-deletes it.
+ auto* container = new QWidget;
+ container->setObjectName("group_linked_container__" + id);
+ auto* v = new QVBoxLayout(container);
+ v->setContentsMargins(0, 0, 0, 0);
+ v->setSpacing(0);
+
+ auto* strip = new QWidget(container);
+ strip->setObjectName("group_badge_strip");
+ strip->setFixedHeight(22);
+ auto* h = new QHBoxLayout(strip);
+ h->setContentsMargins(6, 2, 6, 2);
+ h->setSpacing(6);
+
+ auto* badge = new ui::GroupBadge(strip);
+ badge->set_group_silent(linked->group());
+ h->addWidget(badge);
+
+ auto* label = new QLabel(strip);
+ label->setObjectName("group_badge_symbol");
+ label->setStyleSheet("color:#9ca3af;font-size:11px;");
+ const SymbolRef cur = SymbolContext::instance().group_symbol(linked->group());
+ if (cur.is_valid())
+ label->setText(cur.display());
+ h->addWidget(label);
+ h->addStretch(1);
+
+ v->addWidget(strip);
+ v->addWidget(screen, 1);
+
+ // Keep the strip label in sync with the group's active symbol.
+ auto sync_label = [label, linked]() {
+ const SymbolRef cur = SymbolContext::instance().group_symbol(linked->group());
+ label->setText(cur.is_valid() ? cur.display() : QString());
+ };
+
+ connect(badge, &ui::GroupBadge::group_change_requested, this,
+ [this, id, linked, badge, sync_label](SymbolGroup g) {
+ linked->set_group(g);
+ badge->set_group_silent(g);
+ sync_label();
+ // If the new group already has an active symbol, push it into
+ // the newly-linked screen immediately. If the screen itself
+ // has a current symbol and the group has none, seed the group
+ // from the screen.
+ const SymbolRef group_sym = SymbolContext::instance().group_symbol(g);
+ if (group_sym.is_valid()) {
+ linked->on_group_symbol_changed(group_sym);
+ } else if (g != SymbolGroup::None) {
+ const SymbolRef own = linked->current_symbol();
+ if (own.is_valid())
+ SymbolContext::instance().set_group_symbol(g, own,
+ dynamic_cast<QObject*>(linked));
+ }
+ });
+
+ // Re-sync the label when someone *else* publishes to the group this panel
+ // is linked to.
+ connect(&SymbolContext::instance(), &SymbolContext::group_symbol_changed, label,
+ [linked, sync_label](SymbolGroup g, const SymbolRef&, QObject*) {
+ if (linked->group() == g)
+ sync_label();
+ });
+
+ group_linked_[id] = linked;
+ group_badges_[id] = badge;
+ return container;
}
void DockScreenRouter::register_screen(const QString& id, QWidget* screen) {
@@ -88,8 +195,22 @@ void DockScreenRouter::register_factory(const QString& id, ScreenFactory factory
}
void DockScreenRouter::navigate(const QString& id, bool exclusive) {
+ // Hard refuse while the lock screen is showing — signals/timers/keyboard
+ // shortcuts that would otherwise mutate panel state behind the PIN gate
+ // must be no-ops. MainWindow also disables the dock_manager_ widget tree
+ // for keyboard/focus safety; this check catches programmatic callers.
+ if (auth::InactivityGuard::instance().is_terminal_locked()) {
+ LOG_DEBUG("DockRouter", QString("navigate('%1') suppressed — terminal locked").arg(id));
+ return;
+ }
+
LOG_INFO("DockRouter",
QString(">>> navigate('%1', exclusive=%2) panel_count=%3").arg(id).arg(exclusive).arg(panel_count_));
+ // Bump popularity so the Component Browser surfaces frequently-used
+ // panels at the top. Safe for unknown ids — PopularityTracker no-ops
+ // on failure and we still fall into the unknown-screen branch below.
+ PopularityTracker::instance().increment(id);
+
auto* dw = find_dock_widget(id);
bool needs_add = false;
@@ -423,6 +544,268 @@ ads::CDockWidget* DockScreenRouter::find_dock_widget(const QString& id) const {
return dock_widgets_.value(id, nullptr);
}
+void DockScreenRouter::cycle_focused_panel(bool forward) {
+ if (!manager_)
+ return;
+ // Build an ordered list of currently-visible dock widgets — we cycle
+ // through those, not the entire registration catalogue.
+ QList<ads::CDockWidget*> visible;
+ visible.reserve(dock_widgets_.size());
+ for (auto it = dock_widgets_.cbegin(); it != dock_widgets_.cend(); ++it) {
+ ads::CDockWidget* dw = it.value();
+ if (dw && !dw->isClosed())
+ visible.append(dw);
+ }
+ if (visible.size() < 2)
+ return;
+
+ // Find the currently-focused dock widget. ADS exposes focusedDockWidget()
+ // but it may be null if the focused QWidget isn't inside any dock —
+ // fall back to the dock containing current_id_.
+ ads::CDockWidget* current = manager_->focusedDockWidget();
+ if (!current)
+ current = dock_widgets_.value(current_id_, nullptr);
+
+ int idx = visible.indexOf(current);
+ if (idx < 0)
+ idx = 0;
+ else
+ idx = (idx + (forward ? 1 : -1) + visible.size()) % visible.size();
+
+ ads::CDockWidget* next = visible.at(idx);
+ next->raise();
+ next->setAsCurrentTab();
+ if (auto* w = next->widget())
+ w->setFocus(Qt::ShortcutFocusReason);
+ current_id_ = next->objectName();
+ emit screen_changed(current_id_);
+}
+
+ads::CDockWidget* DockScreenRouter::duplicate_panel(const QString& id) {
+ if (!manager_)
+ return nullptr;
+
+ // Strip any existing #dup<N> suffix so duplicates-of-duplicates all derive
+ // from the same original factory — prevents unbounded id drift.
+ QString base = id;
+ const int hash = id.indexOf('#');
+ if (hash > 0)
+ base = id.left(hash);
+
+ // We need a factory to produce a fresh widget — the eagerly-registered
+ // path gives one instance that we can't clone safely.
+ auto fit = factories_.find(base);
+ // Special case: the original factory was consumed on first materialise,
+ // so factories_ may no longer contain `base`. In that case reconstruct
+ // from a registered rebuild helper (we don't have one yet) — fail with a
+ // warning so the user sees a concrete reason rather than a silent no-op.
+ if (fit == factories_.end()) {
+ // Only eager (one-instance) screens reach here. Duplication is not
+ // supported for them in this phase.
+ LOG_WARN("DockRouter",
+ QString("duplicate_panel('%1'): factory not available — duplication requires "
+ "register_factory() and the original factory is consumed on first materialise. "
+ "Re-register a factory before duplication to support this path.").arg(base));
+ return nullptr;
+ }
+
+ // Allocate a unique suffixed id. Scan existing ids to avoid collisions.
+ int n = 2;
+ QString dup_id;
+ do {
+ dup_id = QString("%1#dup%2").arg(base).arg(n++);
+ } while (dock_widgets_.contains(dup_id) || factories_.contains(dup_id));
+
+ // Build the duplicate via a fresh factory copy so navigate() can
+ // materialize it on-demand through the existing path. Re-install the
+ // base factory too so further duplicates remain possible.
+ ScreenFactory factory_copy = fit.value();
+ factories_[dup_id] = factory_copy;
+ factories_[base] = factory_copy;
+
+ // Title: "<Original Title> 2", "<Original Title> 3", ...
+ const int dup_index = n - 1;
+ // Populate title for the synthetic id so the tab label reads cleanly.
+ // title_for_id() is static — we can't extend it at runtime, so we store
+ // the custom title via the existing user-rename path.
+ save_tab_title(dup_id, QString("%1 %2").arg(title_for_id(base)).arg(dup_index));
+
+ // Create the dock widget. This path also wraps the widget in a
+ // GroupBadge container if the source screen implements IGroupLinked,
+ // materialises via the factory, and adds the dock widget to the manager.
+ auto* dw = create_dock_widget(dup_id);
+ if (!dw) {
+ LOG_WARN("DockRouter", QString("duplicate_panel: create_dock_widget failed for %1").arg(dup_id));
+ return nullptr;
+ }
+ materialize_screen(dup_id);
+
+ // Copy IStatefulScreen state from source → duplicate so the user doesn't
+ // re-type the ticker etc. Source is the inner screen widget, not the
+ // group-badge container — screens_ always stores the inner widget.
+ auto* src_screen = screens_.value(base, nullptr);
+ auto* dup_screen = screens_.value(dup_id, nullptr);
+ if (src_screen && dup_screen) {
+ auto* src_stateful = dynamic_cast<screens::IStatefulScreen*>(src_screen);
+ auto* dup_stateful = dynamic_cast<screens::IStatefulScreen*>(dup_screen);
+ if (src_stateful && dup_stateful)
+ dup_stateful->restore_state(src_stateful->save_state());
+ }
+
+ // Place the duplicate next to the original as a tabbed sibling so the
+ // user sees it immediately without manually docking.
+ auto* src_dw = dock_widgets_.value(base, nullptr);
+ if (src_dw && src_dw->dockAreaWidget()) {
+ manager_->addDockWidgetTabToArea(dw, src_dw->dockAreaWidget());
+ } else {
+ manager_->addDockWidget(ads::CenterDockWidgetArea, dw);
+ }
+ dw->setAsCurrentTab();
+ dw->raise();
+
+ LOG_INFO("DockRouter", QString("Duplicated '%1' → '%2'").arg(base, dup_id));
+ return dw;
+}
+
+// ── Phase 12 — tab right-click context menu ──────────────────────────────────
+
+void DockScreenRouter::show_tab_context_menu(const QString& id, const QPoint& global_pos) {
+ auto* dw = dock_widgets_.value(id, nullptr);
+ if (!dw)
+ return;
+
+ QMenu menu;
+ menu.setStyleSheet(
+ "QMenu{background:#111827;color:#e5e7eb;border:1px solid #374151;padding:4px 0;}"
+ "QMenu::item{padding:5px 24px 5px 12px;}"
+ "QMenu::item:selected{background:#1f2937;color:#d97706;}"
+ "QMenu::item:disabled{color:#6b7280;}"
+ "QMenu::separator{background:#374151;height:1px;margin:4px 8px;}");
+
+ // Rename — reuses the inline editor code path. Simpler to pop a modal
+ // prompt here; the inline editor requires the label's geometry which is
+ // awkward to invoke from a menu click.
+ auto* act_rename = menu.addAction("Rename Tab…");
+ connect(act_rename, &QAction::triggered, this, [this, id, dw]() {
+ bool ok = false;
+ const QString name = QInputDialog::getText(nullptr, "Rename Tab", "New name:",
+ QLineEdit::Normal, dw->windowTitle(), &ok);
+ if (ok && !name.trimmed().isEmpty()) {
+ dw->setWindowTitle(name.trimmed());
+ save_tab_title(id, name.trimmed());
+ }
+ });
+
+ // Duplicate — only enabled for factory-registered screens. We can't tell
+ // from here reliably without re-running the factory lookup, so we flag the
+ // item as enabled and let duplicate_panel no-op with a log warning on
+ // unsupported screens.
+ auto* act_dup = menu.addAction("Duplicate Panel");
+ connect(act_dup, &QAction::triggered, this, [this, id]() { duplicate_panel(id); });
+
+ menu.addSeparator();
+
+ // Float or re-dock. ADS's setFloating() has no matching setDocked(); to
+ // re-dock a floating widget we close its view and re-open it, which
+ // causes ADS to re-attach it to the main container.
+ const bool floating = dw->isFloating();
+ auto* act_float = menu.addAction(floating ? "Re-dock Panel" : "Float Panel");
+ connect(act_float, &QAction::triggered, this, [this, dw, floating]() {
+ if (floating) {
+ dw->toggleView(false);
+ dw->toggleView(true);
+ if (manager_ && manager_->dockAreaCount() == 0)
+ manager_->addDockWidget(ads::CenterDockWidgetArea, dw);
+ } else {
+ dw->setFloating();
+ }
+ });
+
+ // Always-on-top — only meaningful when the dock is a top-level floating
+ // window. For docked tabs, the flag lives on the MainWindow; we don't
+ // expose it here to avoid confusion.
+ if (floating) {
+ if (auto* fc = dw->floatingDockContainer()) {
+ const bool on = fc->windowFlags().testFlag(Qt::WindowStaysOnTopHint);
+ auto* act_top = menu.addAction("Always on Top");
+ act_top->setCheckable(true);
+ act_top->setChecked(on);
+ connect(act_top, &QAction::triggered, this, [fc, on]() {
+ Qt::WindowFlags f = fc->windowFlags();
+ if (on)
+ f &= ~Qt::WindowStaysOnTopHint;
+ else
+ f |= Qt::WindowStaysOnTopHint;
+ fc->setWindowFlags(f);
+ fc->show();
+ });
+ }
+ }
+
+ menu.addSeparator();
+
+ // Link to Group (Phase 1) — only for screens implementing IGroupLinked.
+ // The inner screen is in screens_[id]; the container wrapping happens at
+ // dw->widget(), so cast from the stored screen to test the interface.
+ if (auto* screen = screens_.value(id, nullptr)) {
+ if (auto* linked = dynamic_cast<IGroupLinked*>(screen)) {
+ auto* group_menu = menu.addMenu("Link to Group");
+ group_menu->setStyleSheet(menu.styleSheet());
+ const SymbolGroup current = linked->group();
+
+ auto* unlink = group_menu->addAction("(None)");
+ unlink->setCheckable(true);
+ unlink->setChecked(current == SymbolGroup::None);
+ connect(unlink, &QAction::triggered, this, [this, id]() {
+ if (auto* s = screens_.value(id, nullptr)) {
+ if (auto* l = dynamic_cast<IGroupLinked*>(s))
+ l->set_group(SymbolGroup::None);
+ }
+ QPointer<ui::GroupBadge> badge = group_badges_.value(id);
+ if (badge)
+ badge->set_group_silent(SymbolGroup::None);
+ });
+ group_menu->addSeparator();
+
+ for (SymbolGroup g : all_symbol_groups()) {
+ auto* a = group_menu->addAction(QString("Group %1").arg(symbol_group_letter(g)));
+ a->setCheckable(true);
+ a->setChecked(g == current);
+ connect(a, &QAction::triggered, this, [this, id, g]() {
+ auto* s = screens_.value(id, nullptr);
+ auto* l = s ? dynamic_cast<IGroupLinked*>(s) : nullptr;
+ if (!l) return;
+ l->set_group(g);
+ QPointer<ui::GroupBadge> badge = group_badges_.value(id);
+ if (badge)
+ badge->set_group_silent(g);
+ // Seed the newly-linked group with the screen's current
+ // symbol (if any) so the other group panels follow it.
+ const SymbolRef own = l->current_symbol();
+ if (own.is_valid())
+ SymbolContext::instance().set_group_symbol(
+ g, own, dynamic_cast<QObject*>(l));
+ });
+ }
+ }
+ }
+
+ menu.addSeparator();
+
+ // Copy tab title to clipboard — small but handy for sharing a panel id
+ // over chat / for scripting.
+ auto* act_copy = menu.addAction("Copy Tab Title");
+ connect(act_copy, &QAction::triggered, this, [dw]() {
+ QApplication::clipboard()->setText(dw->windowTitle());
+ });
+
+ // Close tab.
+ auto* act_close = menu.addAction("Close Tab");
+ connect(act_close, &QAction::triggered, this, [dw]() { dw->toggleView(false); });
+
+ menu.exec(global_pos);
+}
+
QStringList DockScreenRouter::all_screen_ids() const {
QStringList ids;
ids.reserve(dock_widgets_.size() + factories_.size());
@@ -436,6 +819,18 @@ QStringList DockScreenRouter::all_screen_ids() const {
}
bool DockScreenRouter::eventFilter(QObject* obj, QEvent* event) {
+ // Phase 12 — right-click context menu on any installed tab/label. Handled
+ // first so we don't gate on QLabel-only below (the tab widget itself is
+ // also a watched object now).
+ if (event->type() == QEvent::ContextMenu) {
+ const QString id = obj->property("dock_id").toString();
+ if (!id.isEmpty() && dock_widgets_.contains(id)) {
+ auto* cm = static_cast<QContextMenuEvent*>(event);
+ show_tab_context_menu(id, cm->globalPos());
+ return true;
+ }
+ }
+
if (event->type() != QEvent::MouseButtonDblClick)
return QObject::eventFilter(obj, event);
@@ -523,7 +918,7 @@ ads::CDockWidget* DockScreenRouter::create_dock_widget(const QString& id) {
// in on first navigation via materialize_screen().
if (screens_.contains(id)) {
screens_[id]->setMinimumWidth(0);
- dw->setWidget(screens_[id]);
+ dw->setWidget(wrap_with_group_badge(id, screens_[id]));
} else {
auto* placeholder = new QWidget;
auto* lbl = new QLabel(title_for_id(id));
@@ -537,7 +932,14 @@ ads::CDockWidget* DockScreenRouter::create_dock_widget(const QString& id) {
// Intercept double-click on the title label inside CDockWidgetTab to allow
// inline rename. We use the label (objectName "dockWidgetTabLabel"), NOT the
// tab frame — ADS already uses tab frame double-click to undock/float.
+ //
+ // Phase 12 — also install the filter on the tab widget itself so right-click
+ // anywhere on the tab (including the icon / padding) opens the context
+ // menu. The event filter distinguishes by event type, not watched object.
if (auto* tab = dw->tabWidget()) {
+ tab->installEventFilter(this);
+ tab->setProperty("dock_id", id);
+ tab->setContextMenuPolicy(Qt::DefaultContextMenu);
if (auto* lbl = tab->findChild<QLabel*>("dockWidgetTabLabel")) {
lbl->installEventFilter(this);
lbl->setProperty("dock_id", id);
@@ -600,7 +1002,7 @@ void DockScreenRouter::materialize_screen(const QString& id) {
return;
QWidget* old = dw->widget();
- dw->setWidget(screen);
+ dw->setWidget(wrap_with_group_badge(id, screen));
if (old) {
old->setParent(nullptr);
old->deleteLater();
diff --git a/fincept-qt/src/app/DockScreenRouter.h b/fincept-qt/src/app/DockScreenRouter.h
index b5662fa64..59ded0751 100644
--- a/fincept-qt/src/app/DockScreenRouter.h
+++ b/fincept-qt/src/app/DockScreenRouter.h
@@ -1,13 +1,23 @@
#pragma once
+#include "core/symbol/SymbolGroup.h"
+
#include <QHash>
#include <QObject>
+#include <QPointer>
#include <DockManager.h>
#include <DockWidget.h>
#include <functional>
+namespace fincept::ui {
+class GroupBadge;
+}
+
namespace fincept {
+class IGroupLinked;
+struct SymbolRef;
+
/// ADS-aware screen router. Each screen is wrapped in a CDockWidget that can be
/// docked, tabbed, floated, or auto-hidden. Mirrors ScreenRouter's API so the
/// transition is straightforward.
@@ -61,6 +71,22 @@ class DockScreenRouter : public QObject {
/// Returns all registered screen IDs (both eager and factory).
QStringList all_screen_ids() const;
+ /// Cycle focus between all currently-open dock widgets in this manager.
+ /// Wraps at either end. No-op if fewer than 2 panels are open.
+ /// `forward = true` moves to the next panel in open order; false moves back.
+ void cycle_focused_panel(bool forward);
+
+ /// Duplicate an open dock widget into a new tab. Only works for screens
+ /// that were registered via register_factory() — eagerly-registered
+ /// screens use a single widget instance and cannot be duplicated. The
+ /// new tab gets a synthetic id `<base>#dup<N>` so it doesn't collide in
+ /// QSettings. If the source screen implements IStatefulScreen, its
+ /// save_state() is applied to the duplicate via restore_state() so the
+ /// duplicate starts in the same view (e.g. same ticker loaded in
+ /// EquityResearch, same watchlist selected in WatchlistScreen).
+ /// Returns the new dock widget or nullptr on failure.
+ ads::CDockWidget* duplicate_panel(const QString& id);
+
signals:
void screen_changed(const QString& id);
@@ -85,6 +111,22 @@ class DockScreenRouter : public QObject {
ads::CDockWidget* create_dock_widget(const QString& id);
void materialize_screen(const QString& id);
+
+ // ── Symbol group linking ──────────────────────────────────────────────────
+ // If `screen` (or one of its descendants) implements IGroupLinked, wraps
+ // it in a thin container with a top-bar GroupBadge and wires the badge to
+ // SymbolContext. Returns the container (or `screen` itself if no linking
+ // is supported). Safe to call once per materialised screen.
+ QWidget* wrap_with_group_badge(const QString& id, QWidget* screen);
+
+ // The IGroupLinked* for each screen id, so SymbolContext signals can be
+ // routed back. Held as raw pointer since lifetime matches the wrapped
+ // QWidget in screens_, which we already manage.
+ QHash<QString, IGroupLinked*> group_linked_;
+ QHash<QString, QPointer<ui::GroupBadge>> group_badges_;
+
+ void on_group_symbol_changed_external(fincept::SymbolGroup g, const fincept::SymbolRef& ref,
+ QObject* source);
/// Apply theme colors directly to all CDockAreaTitleBar and CDockWidgetTab
/// widgets. Called after any addDockWidget() call since those create new
/// QFrame-derived widgets that the app-level QFrame rule overrides.
@@ -102,6 +144,13 @@ class DockScreenRouter : public QObject {
/// Save/restore IStatefulScreen state for a materialized screen widget.
void save_screen_state(const QString& id);
void restore_screen_state(const QString& id);
+
+ /// Phase 12 — build + show the right-click tab context menu at the given
+ /// global position for the given dock widget id. Public so callers outside
+ /// the router can trigger it (e.g. a "menu" key or toolbar action), but
+ /// primarily invoked from the event filter on the tab widget.
+ public:
+ void show_tab_context_menu(const QString& id, const QPoint& global_pos);
};
} // namespace fincept
diff --git a/fincept-qt/src/app/MainWindow.cpp b/fincept-qt/src/app/MainWindow.cpp
index 98594cf2c..4ffebfa6c 100644
--- a/fincept-qt/src/app/MainWindow.cpp
+++ b/fincept-qt/src/app/MainWindow.cpp
@@ -9,6 +9,7 @@
#include "core/config/ProfileManager.h"
#include "core/events/EventBus.h"
#include "core/keys/KeyConfigManager.h"
+#include "core/keys/WindowCycler.h"
#include "core/logging/Logger.h"
#include "core/session/SessionManager.h"
#include "screens/ComingSoonScreen.h"
@@ -73,9 +74,11 @@
#include "ui/navigation/DockStatusBar.h"
#include "ui/navigation/DockToolBar.h"
#include "ui/navigation/FKeyBar.h"
+#include "ui/components/ComponentBrowserDialog.h"
#include "ui/navigation/NavigationBar.h"
#include "ui/navigation/StatusBar.h"
#include "ui/navigation/ToolBar.h"
+#include "ui/pushpins/PushpinBar.h"
#include "ui/theme/Theme.h"
#include "ui/workspace/WorkspaceNewDialog.h"
#include "ui/workspace/WorkspaceOpenDialog.h"
@@ -93,6 +96,7 @@
#include <QScreen>
#include <QShortcut>
#include <QStatusBar>
+#include <QToolBar>
#include <QVBoxLayout>
#include <QWindow>
@@ -202,6 +206,13 @@ MainWindow::MainWindow(int window_id, QWidget* parent) : QMainWindow(parent), wi
}
}
+ // Restore always-on-top before the first show() so the OS hint is
+ // applied cleanly. Cannot use set_always_on_top() here — it would call
+ // show() which only works after the widget has a fully built-out layout.
+ always_on_top_ = SessionManager::instance().load_window_flag(window_id_, "always_on_top", false);
+ if (always_on_top_)
+ setWindowFlags(windowFlags() | Qt::WindowStaysOnTopHint);
+
auto* master_stack = new QStackedWidget;
// ── Auth stack ───────────────────────────────────────────────────────────
@@ -238,6 +249,21 @@ MainWindow::MainWindow(int window_id, QWidget* parent) : QMainWindow(parent), wi
dock_toolbar_ = new ui::DockToolBar(this);
addToolBar(Qt::TopToolBarArea, dock_toolbar_);
+ // Pushpin bar lives on its own toolbar row below the main toolbar so the
+ // chips are always visible and drop targets across all panels. Start a
+ // new toolbar line via addToolBarBreak().
+ addToolBarBreak(Qt::TopToolBarArea);
+ pushpin_bar_ = new ui::PushpinBar;
+ pushpin_toolbar_ = new QToolBar(this);
+ pushpin_toolbar_->setObjectName("pushpinToolbar");
+ pushpin_toolbar_->setMovable(false);
+ pushpin_toolbar_->setFloatable(false);
+ pushpin_toolbar_->setAllowedAreas(Qt::TopToolBarArea);
+ pushpin_toolbar_->addWidget(pushpin_bar_);
+ addToolBar(Qt::TopToolBarArea, pushpin_toolbar_);
+ // Hidden until auth completes; set_shell_visible() shows it.
+ pushpin_toolbar_->setVisible(false);
+
dock_status_bar_ = new ui::DockStatusBar(this);
setStatusBar(dock_status_bar_);
@@ -246,6 +272,9 @@ MainWindow::MainWindow(int window_id, QWidget* parent) : QMainWindow(parent), wi
// ── Workspace + signal wiring ───────────────────────────────────────────
WorkspaceManager::instance().set_main_window(this);
+ WindowCycler::instance().register_window(this);
+ connect(this, &QObject::destroyed, this,
+ [this]() { WindowCycler::instance().unregister_window(this); });
connect(&WorkspaceManager::instance(), &WorkspaceManager::workspace_loaded, this,
[this](const WorkspaceDef&) { update_window_title(); });
connect(&WorkspaceManager::instance(), &WorkspaceManager::workspace_error, this,
@@ -365,6 +394,8 @@ MainWindow::MainWindow(int window_id, QWidget* parent) : QMainWindow(parent), wi
dock_toolbar_->setVisible(!focus_mode_);
if (dock_status_bar_)
dock_status_bar_->setVisible(!focus_mode_);
+ if (pushpin_toolbar_)
+ pushpin_toolbar_->setVisible(!focus_mode_);
});
auto* act_refresh = km.action(KeyAction::Refresh);
@@ -397,9 +428,102 @@ MainWindow::MainWindow(int window_id, QWidget* parent) : QMainWindow(parent), wi
}
});
+ // Manual lock (default Ctrl+L). Bypasses the inactivity timer — useful
+ // when stepping away from an unlocked terminal. This action is deliberately
+ // NOT guarded by `locked_` (it's a lock command; already-locked is a no-op
+ // via show_lock_screen's early-return). Requires authentication + a
+ // configured PIN, which show_lock_screen also enforces.
+ if (auto* act_lock = km.action(KeyAction::LockNow)) {
+ act_lock->setShortcutContext(Qt::ApplicationShortcut);
+ addAction(act_lock);
+ connect(act_lock, &QAction::triggered, this, [this]() {
+ auth::InactivityGuard::instance().trigger_manual_lock();
+ });
+ }
+
+ // Minimize-to-lock is handled in changeEvent() — see its override. We
+ // only install the key shortcut here. The setting `security.lock_on_minimize`
+ // (default off) governs the behaviour and is read each time the event fires.
+
+ // ── Phase 3: window/panel keyboard navigation ────────────────────────────
+ // All actions are WindowShortcut-scoped so they only fire against the
+ // active MainWindow. WindowCycler::current_focused() then routes the
+ // action across windows when needed.
+ auto bind_km = [this](KeyAction a, std::function<void()> fn) {
+ auto* act = KeyConfigManager::instance().action(a);
+ if (!act)
+ return;
+ act->setShortcutContext(Qt::WindowShortcut);
+ addAction(act);
+ connect(act, &QAction::triggered, this, [this, fn]() {
+ if (locked_) return;
+ fn();
+ });
+ };
+
+ // Focus window by 1-based ordinal.
+ const KeyAction focus_keys[] = {
+ KeyAction::FocusWindow1, KeyAction::FocusWindow2, KeyAction::FocusWindow3,
+ KeyAction::FocusWindow4, KeyAction::FocusWindow5, KeyAction::FocusWindow6,
+ KeyAction::FocusWindow7, KeyAction::FocusWindow8, KeyAction::FocusWindow9,
+ };
+ for (int i = 0; i < 9; ++i) {
+ bind_km(focus_keys[i], [i]() { WindowCycler::instance().focus_window_by_index(i); });
+ }
+
+ // Cycle panels inside the focused window.
+ bind_km(KeyAction::CyclePanelsForward,
+ []() { WindowCycler::instance().cycle_panels_in_current_window(true); });
+ bind_km(KeyAction::CyclePanelsBack,
+ []() { WindowCycler::instance().cycle_panels_in_current_window(false); });
+
+ // Cycle between MainWindow instances.
+ bind_km(KeyAction::CycleWindowsForward,
+ []() { WindowCycler::instance().cycle_windows(true); });
+ bind_km(KeyAction::CycleWindowsBack,
+ []() { WindowCycler::instance().cycle_windows(false); });
+
+ // New window on next monitor.
+ bind_km(KeyAction::NewWindowNextMonitor,
+ []() { WindowCycler::instance().new_window_on_next_monitor(); });
+
+ // Move current window to monitor N (1-based in the shortcut, 0-based to the API).
+ const KeyAction move_keys[] = {
+ KeyAction::MoveWindowToMonitor1, KeyAction::MoveWindowToMonitor2,
+ KeyAction::MoveWindowToMonitor3, KeyAction::MoveWindowToMonitor4,
+ KeyAction::MoveWindowToMonitor5, KeyAction::MoveWindowToMonitor6,
+ KeyAction::MoveWindowToMonitor7, KeyAction::MoveWindowToMonitor8,
+ KeyAction::MoveWindowToMonitor9,
+ };
+ for (int i = 0; i < 9; ++i) {
+ bind_km(move_keys[i], [i]() { WindowCycler::instance().move_current_window_to_monitor(i); });
+ }
+
+ // Component Browser (Phase 6)
+ bind_km(KeyAction::BrowseComponents, [this]() {
+ auto* dlg = new ui::ComponentBrowserDialog(this);
+ dlg->setAttribute(Qt::WA_DeleteOnClose);
+ connect(dlg, &ui::ComponentBrowserDialog::component_chosen, this, [this](const QString& id) {
+ if (dock_router_ && !id.isEmpty())
+ dock_router_->navigate(id);
+ });
+ dlg->show();
+ });
+
+ // Always-on-top toggle (Phase 11) — shortcut targets the focused window
+ // because bind_km installs QAction with WindowShortcut context.
+ bind_km(KeyAction::ToggleAlwaysOnTop, [this]() { set_always_on_top(!always_on_top_); });
+
// Toolbar actions
connect(toolbar, &ui::ToolBar::action_triggered, this, [this](const QString& action) {
if (locked_) return;
+ if (action == "browse_components") {
+ // Same path as the keyboard shortcut so the behavior stays in one
+ // place — the KeyConfigManager action will be triggered directly.
+ if (auto* act = KeyConfigManager::instance().action(KeyAction::BrowseComponents))
+ act->trigger();
+ return;
+ }
if (action == "new_window") {
auto* w = new MainWindow(MainWindow::next_window_id());
w->setAttribute(Qt::WA_DeleteOnClose);
@@ -435,32 +559,7 @@ MainWindow::MainWindow(int window_id, QWidget* parent) : QMainWindow(parent), wi
LOG_WARN("MainWindow", QString("Move to monitor: screen '%1' not found").arg(target_name));
return;
}
- if (screen() == target)
- return; // already there
-
- // Preserve maximised/fullscreen state across the move: Qt can't
- // directly relocate a maximised window to a different screen, so
- // we restore → move → re-apply the state.
- const bool was_maximised = isMaximized();
- const bool was_fullscreen = isFullScreen();
- if (was_maximised || was_fullscreen)
- showNormal();
-
- const QRect sg = target->availableGeometry();
- // Keep size if it fits, otherwise clamp to 90% of target screen.
- QSize new_size = size();
- if (new_size.width() > sg.width() || new_size.height() > sg.height())
- new_size = QSize(sg.width() * 9 / 10, sg.height() * 9 / 10);
- resize(new_size);
- move(sg.center() - QPoint(new_size.width() / 2, new_size.height() / 2));
-
- if (was_fullscreen)
- showFullScreen();
- else if (was_maximised)
- showMaximized();
-
- LOG_INFO("MainWindow", QString("Moved window %1 to monitor '%2'")
- .arg(window_id_).arg(target_name));
+ move_to_screen(target);
} else if (action.startsWith("panel_")) {
// Float a screen — in ADS mode, navigate dock_router; in legacy, spawn window
static const QMap<QString, QPair<QString, QString>> panel_map = {
@@ -546,14 +645,7 @@ MainWindow::MainWindow(int window_id, QWidget* parent) : QMainWindow(parent), wi
if (dock_status_bar_)
dock_status_bar_->setVisible(!focus_mode_);
} else if (action == "always_on_top") {
- always_on_top_ = !always_on_top_;
- Qt::WindowFlags flags = windowFlags();
- if (always_on_top_)
- flags |= Qt::WindowStaysOnTopHint;
- else
- flags &= ~Qt::WindowStaysOnTopHint;
- setWindowFlags(flags);
- show(); // required after setWindowFlags to re-show the window
+ set_always_on_top(!always_on_top_);
} else if (action == "refresh") {
if (dock_manager_) {
auto* focused = dock_manager_->focusedDockWidget();
@@ -736,6 +828,12 @@ MainWindow::MainWindow(int window_id, QWidget* parent) : QMainWindow(parent), wi
auto& auth = auth::AuthManager::instance();
if (auth.is_authenticated())
auth.refresh_user_data();
+ // Resume-from-sleep lock: QTimer pauses during OS suspend, so a
+ // 5-minute timer can carry 4:59 of remaining time across a
+ // 30-minute nap. Ask the guard to check wall-clock delta and
+ // force a lock if the user was effectively idle for the full
+ // timeout. No-op when the guard is disabled or already locked.
+ auth::InactivityGuard::instance().check_for_resume_lock();
}
});
}
@@ -749,6 +847,8 @@ void MainWindow::toggle_chat_mode() {
dock_toolbar_->setVisible(false);
if (dock_status_bar_)
dock_status_bar_->setVisible(false);
+ if (pushpin_toolbar_)
+ pushpin_toolbar_->setVisible(false);
if (chat_bubble_)
chat_bubble_->setVisible(false);
stack_->setCurrentIndex(2);
@@ -759,6 +859,8 @@ void MainWindow::toggle_chat_mode() {
dock_toolbar_->setVisible(true);
if (dock_status_bar_)
dock_status_bar_->setVisible(true);
+ if (pushpin_toolbar_)
+ pushpin_toolbar_->setVisible(true);
// Restore chat bubble based on setting
if (chat_bubble_) {
auto r = SettingsRepository::instance().get("appearance.show_chat_bubble");
@@ -1030,6 +1132,26 @@ void MainWindow::on_auth_state_changed() {
}
if (auth.session().has_paid_plan()) {
+ // Defensive: at this point the PIN gate above must have either
+ // routed us to the lock screen (and returned) or confirmed
+ // pin_gate_cleared_. If we are about to show the shell while
+ // still locked or ungated, log a warning so the regression is
+ // visible rather than leaking the dashboard for one frame.
+ if (locked_ || !pin_gate_cleared_) {
+ LOG_WARN("MainWindow",
+ QString("on_auth_state_changed: shell would become visible while "
+ "locked=%1 gate_cleared=%2 — forcing lock screen")
+ .arg(locked_).arg(pin_gate_cleared_));
+ if (auth::PinManager::instance().has_pin())
+ lock_screen_->show_unlock();
+ else
+ lock_screen_->show_setup();
+ locked_ = true;
+ set_shell_visible(false);
+ stack_->setCurrentIndex(3);
+ return;
+ }
+
// Paid user → straight to dashboard
set_shell_visible(true);
stack_->setCurrentIndex(1);
@@ -1053,8 +1175,10 @@ void MainWindow::on_auth_state_changed() {
auth_stack_->setCurrentIndex(3);
}
} else {
- // Disable inactivity guard when logged out
+ // Disable inactivity guard when logged out and drop the locked flag
+ // so a subsequent login is not immediately router-blocked.
auth::InactivityGuard::instance().set_enabled(false);
+ auth::InactivityGuard::instance().set_terminal_locked(false);
pin_gate_cleared_ = false;
set_shell_visible(false);
stack_->setCurrentIndex(0);
@@ -1108,12 +1232,21 @@ void MainWindow::show_info_help() {
void MainWindow::show_lock_screen() {
auto& auth = auth::AuthManager::instance();
- if (!auth.is_authenticated())
+ if (!auth.is_authenticated()) {
+ LOG_DEBUG("MainWindow", "show_lock_screen: ignored — not authenticated");
return;
+ }
- // Don't lock if already on lock screen or login screen
- if (stack_->currentIndex() == 3 || stack_->currentIndex() == 0)
+ // Don't lock if already on lock screen or login screen — traced so
+ // spurious inactivity ticks during auth transitions are visible in logs.
+ if (stack_->currentIndex() == 3) {
+ LOG_DEBUG("MainWindow", "show_lock_screen: ignored — already on lock screen");
return;
+ }
+ if (stack_->currentIndex() == 0) {
+ LOG_DEBUG("MainWindow", "show_lock_screen: ignored — currently on auth stack");
+ return;
+ }
LOG_INFO("MainWindow", "Inactivity timeout — showing lock screen");
lock_screen_->activate();
@@ -1123,6 +1256,23 @@ void MainWindow::show_lock_screen() {
stack_->setCurrentIndex(3);
if (chat_bubble_)
chat_bubble_->setVisible(false);
+
+ // Disable widgets behind the lock screen so keyboard shortcuts, focus
+ // traversal, and dock-manager hit-testing cannot mutate state while the
+ // lock screen is shown. Re-enabled in on_terminal_unlocked().
+ if (dock_manager_ && dock_manager_->parentWidget())
+ dock_manager_->parentWidget()->setEnabled(false);
+ if (dock_toolbar_) dock_toolbar_->setEnabled(false);
+ if (pushpin_toolbar_) pushpin_toolbar_->setEnabled(false);
+ if (dock_status_bar_) dock_status_bar_->setEnabled(false);
+
+ // Stop the inactivity guard while locked — the user-activity stream on
+ // the lock screen itself would otherwise keep firing no-op ticks, and
+ // there is nothing useful to do with them until the PIN is accepted.
+ // Also raise the process-wide locked flag so DockScreenRouter (and any
+ // other background navigator) refuses to mutate panel state.
+ auth::InactivityGuard::instance().set_terminal_locked(true);
+ auth::InactivityGuard::instance().set_enabled(false);
}
void MainWindow::on_terminal_unlocked() {
@@ -1131,7 +1281,19 @@ void MainWindow::on_terminal_unlocked() {
locked_ = false;
pin_gate_cleared_ = true;
- // Enable/restart inactivity guard
+ // Re-enable widgets disabled in show_lock_screen() and drop the
+ // process-wide locked flag that DockScreenRouter consults.
+ auth::InactivityGuard::instance().set_terminal_locked(false);
+
+ if (dock_manager_ && dock_manager_->parentWidget())
+ dock_manager_->parentWidget()->setEnabled(true);
+ if (dock_toolbar_) dock_toolbar_->setEnabled(true);
+ if (pushpin_toolbar_) pushpin_toolbar_->setEnabled(true);
+ if (dock_status_bar_) dock_status_bar_->setEnabled(true);
+
+ // Enable/restart inactivity guard. It is disabled in show_lock_screen()
+ // and on logout, so it may currently be off even though the filter is
+ // already installed on qApp from a previous unlock.
auto& guard = auth::InactivityGuard::instance();
if (!guard.is_enabled()) {
qApp->installEventFilter(&guard);
@@ -1177,6 +1339,8 @@ void MainWindow::set_shell_visible(bool visible) {
dock_toolbar_->setVisible(visible && !focus_mode_ && !chat_mode_);
if (dock_status_bar_)
dock_status_bar_->setVisible(visible && !focus_mode_ && !chat_mode_);
+ if (pushpin_toolbar_)
+ pushpin_toolbar_->setVisible(visible && !focus_mode_ && !chat_mode_);
if (!visible) {
// Reset title to plain app name — no screen suffix while on auth screens
const QString profile = ProfileManager::instance().active();
@@ -1213,6 +1377,53 @@ void MainWindow::update_window_title() {
setWindowTitle(title);
}
+void MainWindow::set_always_on_top(bool on) {
+ if (always_on_top_ == on)
+ return;
+ always_on_top_ = on;
+ Qt::WindowFlags flags = windowFlags();
+ if (on)
+ flags |= Qt::WindowStaysOnTopHint;
+ else
+ flags &= ~Qt::WindowStaysOnTopHint;
+ setWindowFlags(flags);
+ // setWindowFlags hides the window on most platforms; re-show it so the
+ // change is visible. Preserve maximised/fullscreen state across the toggle.
+ if (isVisible() || true) // always re-show; isVisible is false after the flag change
+ show();
+ SessionManager::instance().save_window_flag(window_id_, "always_on_top", on);
+ LOG_INFO("MainWindow",
+ QString("Window %1 always-on-top = %2").arg(window_id_).arg(on ? "on" : "off"));
+}
+
+void MainWindow::move_to_screen(QScreen* target) {
+ if (!target || screen() == target)
+ return;
+
+ // Preserve maximised/fullscreen state across the move: Qt can't directly
+ // relocate a maximised window to a different screen, so we restore →
+ // move → re-apply the state.
+ const bool was_maximised = isMaximized();
+ const bool was_fullscreen = isFullScreen();
+ if (was_maximised || was_fullscreen)
+ showNormal();
+
+ const QRect sg = target->availableGeometry();
+ QSize new_size = size();
+ if (new_size.width() > sg.width() || new_size.height() > sg.height())
+ new_size = QSize(sg.width() * 9 / 10, sg.height() * 9 / 10);
+ resize(new_size);
+ move(sg.center() - QPoint(new_size.width() / 2, new_size.height() / 2));
+
+ if (was_fullscreen)
+ showFullScreen();
+ else if (was_maximised)
+ showMaximized();
+
+ LOG_INFO("MainWindow", QString("Moved window %1 to monitor '%2'")
+ .arg(window_id_).arg(target->name()));
+}
+
void MainWindow::schedule_dock_layout_save() {
if (dock_layout_save_timer_)
dock_layout_save_timer_->start();
@@ -1250,7 +1461,7 @@ void MainWindow::closeEvent(QCloseEvent* event) {
open_ids.append(window_id_);
std::sort(open_ids.begin(), open_ids.end());
SessionManager::instance().save_window_ids(open_ids);
- SessionManager::instance().save_window_count(open_ids.size());
+ SessionManager::instance().save_window_count(static_cast<int>(open_ids.size()));
event->accept();
}
@@ -1261,4 +1472,21 @@ void MainWindow::resizeEvent(QResizeEvent* event) {
chat_bubble_->reposition();
}
+void MainWindow::changeEvent(QEvent* event) {
+ QMainWindow::changeEvent(event);
+ if (event->type() != QEvent::WindowStateChange)
+ return;
+ if (!(windowState() & Qt::WindowMinimized))
+ return;
+ // Only lock if the user opted in and we are actually in an authenticated
+ // session with a configured PIN — otherwise there is nothing to lock.
+ auto& auth = auth::AuthManager::instance();
+ if (!auth.is_authenticated() || !auth::PinManager::instance().has_pin())
+ return;
+ auto r = SettingsRepository::instance().get("security.lock_on_minimize");
+ const bool lock_on_min = r.is_ok() && r.value() == "true";
+ if (lock_on_min)
+ auth::InactivityGuard::instance().trigger_manual_lock();
+}
+
} // namespace fincept
diff --git a/fincept-qt/src/app/MainWindow.h b/fincept-qt/src/app/MainWindow.h
index d2d9e155f..c3c1781f3 100644
--- a/fincept-qt/src/app/MainWindow.h
+++ b/fincept-qt/src/app/MainWindow.h
@@ -6,6 +6,9 @@
#include <QStackedWidget>
#include <QTimer>
+class QScreen;
+class QToolBar;
+
namespace ads {
class CDockManager;
}
@@ -15,6 +18,7 @@ class DockScreenRouter;
namespace fincept::ui {
class DockToolBar;
class DockStatusBar;
+class PushpinBar;
class TabBar;
} // namespace fincept::ui
namespace fincept::chat_mode {
@@ -40,9 +44,26 @@ class MainWindow : public QMainWindow {
/// never collide with orphaned saved layouts from a previous session.
static int next_window_id();
+ /// Screen router used by this window. Exposed so WindowCycler can ask
+ /// the currently-focused window to cycle its own panels.
+ DockScreenRouter* dock_router() const { return dock_router_; }
+
+ /// Relocate this window to the given QScreen, preserving maximised /
+ /// fullscreen state and clamping size to the target's available area.
+ /// Called by WindowCycler for the Ctrl+Shift+N series of shortcuts.
+ void move_to_screen(QScreen* target);
+
+ /// Apply / clear Qt::WindowStaysOnTopHint. Handles the Qt requirement
+ /// that the window be re-shown after toggling the flag. Persists the
+ /// state per-window in SessionManager. Safe to call with the current
+ /// state (no-op). Also called from Phase 12's right-click context menu.
+ void set_always_on_top(bool on);
+ bool is_always_on_top() const { return always_on_top_; }
+
protected:
void closeEvent(QCloseEvent* event) override;
void resizeEvent(QResizeEvent* event) override;
+ void changeEvent(QEvent* event) override;
private:
QStackedWidget* stack_ = nullptr;
@@ -55,6 +76,8 @@ class MainWindow : public QMainWindow {
DockScreenRouter* dock_router_ = nullptr;
ui::DockToolBar* dock_toolbar_ = nullptr;
ui::DockStatusBar* dock_status_bar_ = nullptr;
+ ui::PushpinBar* pushpin_bar_ = nullptr;
+ QToolBar* pushpin_toolbar_ = nullptr; // outer QToolBar that hosts pushpin_bar_
ui::TabBar* tab_bar_ = nullptr;
// View state
diff --git a/fincept-qt/src/app/main.cpp b/fincept-qt/src/app/main.cpp
index 4a44d7c1d..4208924db 100644
--- a/fincept-qt/src/app/main.cpp
+++ b/fincept-qt/src/app/main.cpp
@@ -7,10 +7,13 @@
#include "core/config/AppConfig.h"
#include "core/config/AppPaths.h"
#include "core/config/ProfileManager.h"
+#include "core/components/ComponentCatalog.h"
#include "core/keys/KeyConfigManager.h"
#include "core/logging/Logger.h"
#include "core/session/ScreenStateManager.h"
#include "core/session/SessionManager.h"
+#include "core/symbol/SymbolGroup.h"
+#include "core/symbol/SymbolRef.h"
#include "datahub/DataHubMetaTypes.h"
#include "mcp/McpInit.h"
#include "network/http/HttpClient.h"
@@ -42,6 +45,7 @@
#include "ui/theme/Theme.h"
#include "ui/theme/ThemeManager.h"
+#include <QCoreApplication>
#include <QDir>
#include <QFile>
#include <QLockFile>
@@ -117,6 +121,18 @@ int main(int argc, char* argv[]) {
// fincept-qt/DATAHUB_ARCHITECTURE.md.
// Phase 2: register MarketDataService as the `market:quote:*` producer.
fincept::datahub::register_metatypes();
+ // SymbolContext payload types — signals cross threads when a producer
+ // service (not just UI) publishes a group change.
+ qRegisterMetaType<fincept::SymbolRef>("fincept::SymbolRef");
+ qRegisterMetaType<fincept::SymbolGroup>("fincept::SymbolGroup");
+ // Phase 6: load the Component Browser catalogue. Try the build-side copy
+ // first (present after cmake configure copies resources) and fall back to
+ // the source-tree path for local dev runs without install step.
+ fincept::ComponentCatalog::instance().load_with_fallbacks({
+ QCoreApplication::applicationDirPath() + "/resources/component_catalog.json",
+ QCoreApplication::applicationDirPath() + "/component_catalog.json",
+ "resources/component_catalog.json",
+ });
fincept::services::MarketDataService::instance().ensure_registered_with_hub();
// Phase 2 (multi-broker refactor): ExchangeSessionManager is the hub
// producer for `ws:kraken:*` / `ws:hyperliquid:*`. Individual sessions
@@ -289,6 +305,8 @@ int main(int argc, char* argv[]) {
fincept::register_migration_v016();
fincept::register_migration_v017();
fincept::register_migration_v018();
+ fincept::register_migration_v019();
+ fincept::register_migration_v020();
// Open main database
QString db_path = fincept::AppPaths::data() + "/fincept.db";
@@ -477,6 +495,12 @@ int main(int argc, char* argv[]) {
if (!fincept::ai_chat::LlmService::instance().is_configured())
LOG_WARN("App",
"LLM provider not configured — AI chat will prompt user to configure Settings → LLM Config");
+
+ // Warm agent discovery cache (same reason as the main path).
+ QTimer::singleShot(0, &app, []() {
+ fincept::services::AgentService::instance().discover_agents();
+ });
+
LOG_INFO("App", "Application ready (after setup)");
});
@@ -541,6 +565,16 @@ int main(int argc, char* argv[]) {
if (!fincept::ai_chat::LlmService::instance().is_configured())
LOG_WARN("App", "LLM provider not configured — AI chat will prompt user to configure Settings → LLM Config");
+
+ // Warm the agent discovery cache on startup. This populates
+ // AgentService::cached_agents() so any screen that lists agents
+ // (Agent Config, Portfolio → Agent Runner, Node Editor) shows the
+ // full finagent_core set immediately instead of falling back to the
+ // much smaller DB-only list. Run deferred so Python is fully ready.
+ QTimer::singleShot(0, &app, []() {
+ fincept::services::AgentService::instance().discover_agents();
+ });
+
LOG_INFO("App", "Application ready");
return app.exec();
}
diff --git a/fincept-qt/src/auth/InactivityGuard.cpp b/fincept-qt/src/auth/InactivityGuard.cpp
index e5177a2f2..c2c04bfa1 100644
--- a/fincept-qt/src/auth/InactivityGuard.cpp
+++ b/fincept-qt/src/auth/InactivityGuard.cpp
@@ -1,5 +1,6 @@
#include "auth/InactivityGuard.h"
+#include "auth/SecurityAuditLog.h"
#include "core/logging/Logger.h"
#include <QEvent>
@@ -15,10 +16,12 @@ InactivityGuard::InactivityGuard() : QObject(nullptr) {
timer_ = new QTimer(this);
timer_->setSingleShot(true);
timer_->setInterval(10 * 60 * 1000); // 10 minutes default
+ last_activity_ = QDateTime::currentDateTime();
connect(timer_, &QTimer::timeout, this, [this]() {
if (enabled_) {
LOG_INFO("Auth", "Inactivity timeout — requesting lock");
+ SecurityAuditLog::instance().record("inactivity_lock");
emit lock_requested();
}
});
@@ -49,6 +52,32 @@ int InactivityGuard::timeout_minutes() const {
void InactivityGuard::reset_timer() {
if (enabled_ && timer_)
timer_->start(); // restart from full interval
+ last_activity_ = QDateTime::currentDateTime();
+}
+
+bool InactivityGuard::check_for_resume_lock() {
+ if (!enabled_) return false;
+ if (!last_activity_.isValid()) {
+ last_activity_ = QDateTime::currentDateTime();
+ return false;
+ }
+ const qint64 elapsed_ms = last_activity_.msecsTo(QDateTime::currentDateTime());
+ const int interval_ms = timer_->interval();
+ if (elapsed_ms >= interval_ms) {
+ LOG_INFO("Auth", QString("Resume detected — wall-clock elapsed %1ms >= timeout %2ms, forcing lock")
+ .arg(elapsed_ms).arg(interval_ms));
+ SecurityAuditLog::instance().record(
+ "resume_lock", QString("elapsed_ms=%1 timeout_ms=%2").arg(elapsed_ms).arg(interval_ms));
+ emit lock_requested();
+ return true;
+ }
+ return false;
+}
+
+void InactivityGuard::trigger_manual_lock() {
+ LOG_INFO("Auth", "Manual lock requested");
+ SecurityAuditLog::instance().record("manual_lock");
+ emit lock_requested();
}
bool InactivityGuard::eventFilter(QObject* obj, QEvent* event) {
@@ -62,6 +91,7 @@ bool InactivityGuard::eventFilter(QObject* obj, QEvent* event) {
case QEvent::Wheel:
case QEvent::TouchBegin:
timer_->start(); // reset on any user interaction
+ last_activity_ = QDateTime::currentDateTime();
break;
default:
break;
diff --git a/fincept-qt/src/auth/InactivityGuard.h b/fincept-qt/src/auth/InactivityGuard.h
index 5a19ace57..9832e9185 100644
--- a/fincept-qt/src/auth/InactivityGuard.h
+++ b/fincept-qt/src/auth/InactivityGuard.h
@@ -1,4 +1,5 @@
#pragma once
+#include <QDateTime>
#include <QObject>
#include <QTimer>
@@ -29,6 +30,24 @@ class InactivityGuard : public QObject {
/// Reset the inactivity timer (called internally on user activity).
void reset_timer();
+ /// Check whether enough wall-clock time has elapsed since the last
+ /// recorded user activity that a lock should be forced now. Used after
+ /// resume from sleep/suspend — QTimer pauses while the OS is asleep, so
+ /// it cannot be relied on to fire immediately on wake. If the wall-clock
+ /// delta exceeds the configured timeout, emit lock_requested() directly.
+ /// Returns true if a lock was forced.
+ bool check_for_resume_lock();
+
+ /// Force an immediate lock (emits lock_requested). Called by the
+ /// manual "Lock Now" action and by minimize-to-lock.
+ void trigger_manual_lock();
+
+ /// Terminal-locked flag. MainWindow sets this to true while the lock
+ /// screen is active so other subsystems (e.g. DockScreenRouter) can
+ /// early-return and refuse to mutate state behind the lock screen.
+ void set_terminal_locked(bool locked) { terminal_locked_ = locked; }
+ bool is_terminal_locked() const { return terminal_locked_; }
+
signals:
/// Emitted when the idle timeout expires — MainWindow should show lock screen.
void lock_requested();
@@ -41,6 +60,11 @@ class InactivityGuard : public QObject {
QTimer* timer_ = nullptr;
bool enabled_ = false;
+ bool terminal_locked_ = false;
+ // Wall-clock timestamp of the last recorded user activity. Used by
+ // check_for_resume_lock() to decide whether the machine slept through
+ // the inactivity window (QTimer pauses during OS suspend).
+ QDateTime last_activity_;
};
} // namespace fincept::auth
diff --git a/fincept-qt/src/auth/PinManager.cpp b/fincept-qt/src/auth/PinManager.cpp
index 1e5b9feeb..f36c056a8 100644
--- a/fincept-qt/src/auth/PinManager.cpp
+++ b/fincept-qt/src/auth/PinManager.cpp
@@ -1,5 +1,6 @@
#include "auth/PinManager.h"
+#include "auth/SecurityAuditLog.h"
#include "core/logging/Logger.h"
#include "storage/secure/SecureStorage.h"
@@ -10,6 +11,51 @@
namespace fincept::auth {
+namespace {
+
+// Constant-time byte comparison. Returns true iff a and b are the same length
+// AND every byte matches. The XOR-accumulate loop touches every byte even on
+// mismatch so execution time does not reveal the first differing index.
+bool constant_time_equals(const QByteArray& a, const QByteArray& b) {
+ if (a.size() != b.size())
+ return false;
+ unsigned char diff = 0;
+ const int n = a.size();
+ for (int i = 0; i < n; ++i)
+ diff |= static_cast<unsigned char>(a[i]) ^ static_cast<unsigned char>(b[i]);
+ return diff == 0;
+}
+
+// Reject trivially weak 6-digit PINs. Returns an error message or empty string
+// if the PIN is acceptable. Centralized here (not in UI) so every caller —
+// future QR/companion setup, tests, scripted flows — gets the same guardrails.
+QString weak_pin_reason(const QString& pin) {
+ if (pin.length() != 6)
+ return QStringLiteral("PIN must be exactly 6 digits");
+ for (const QChar& c : pin) {
+ if (!c.isDigit())
+ return QStringLiteral("PIN must contain only digits");
+ }
+ bool all_same = true;
+ for (int i = 1; i < pin.length(); ++i) {
+ if (pin[i] != pin[0]) { all_same = false; break; }
+ }
+ if (all_same)
+ return QStringLiteral("PIN is too simple — use unique digits");
+
+ bool seq_up = true, seq_down = true;
+ for (int i = 1; i < pin.length(); ++i) {
+ if (pin[i].unicode() != pin[i - 1].unicode() + 1) seq_up = false;
+ if (pin[i].unicode() != pin[i - 1].unicode() - 1) seq_down = false;
+ }
+ if (seq_up || seq_down)
+ return QStringLiteral("PIN is too simple — avoid sequential digits");
+
+ return QString();
+}
+
+} // namespace
+
PinManager& PinManager::instance() {
static PinManager s;
return s;
@@ -103,11 +149,40 @@ void PinManager::load_state() {
void PinManager::save_lockout_state() {
auto& ss = SecureStorage::instance();
- ss.store("pin_failed_attempts", QString::number(failed_attempts_));
- if (lockout_until_.isValid())
- ss.store("pin_lockout_until", lockout_until_.toString(Qt::ISODate));
- else
- ss.remove("pin_lockout_until");
+
+ // Check every write. A silent failure here previously meant an attacker
+ // could hit the attempt counter with failures that never persisted,
+ // bypassing lockout across restarts. If any write fails we log ERROR and
+ // keep the in-memory counter authoritative for the rest of the session.
+ const auto r_att = ss.store("pin_failed_attempts", QString::number(failed_attempts_));
+ if (r_att.is_err())
+ LOG_ERROR("Auth", QString("Failed to persist pin_failed_attempts: %1")
+ .arg(QString::fromStdString(r_att.error())));
+
+ if (lockout_until_.isValid()) {
+ const auto r_until = ss.store("pin_lockout_until", lockout_until_.toString(Qt::ISODate));
+ if (r_until.is_err())
+ LOG_ERROR("Auth", QString("Failed to persist pin_lockout_until: %1")
+ .arg(QString::fromStdString(r_until.error())));
+
+ // Record the wall clock observed at the moment we wrote the deadline.
+ // On load, if current wall clock is earlier than this, the clock has
+ // been rolled back and we refuse to clear the lockout.
+ const auto r_stamp = ss.store("pin_lockout_stamp",
+ QDateTime::currentDateTime().toString(Qt::ISODate));
+ if (r_stamp.is_err())
+ LOG_ERROR("Auth", QString("Failed to persist pin_lockout_stamp: %1")
+ .arg(QString::fromStdString(r_stamp.error())));
+ } else {
+ const auto r1 = ss.remove("pin_lockout_until");
+ const auto r2 = ss.remove("pin_lockout_stamp");
+ if (r1.is_err())
+ LOG_ERROR("Auth", QString("Failed to remove pin_lockout_until: %1")
+ .arg(QString::fromStdString(r1.error())));
+ if (r2.is_err())
+ LOG_ERROR("Auth", QString("Failed to remove pin_lockout_stamp: %1")
+ .arg(QString::fromStdString(r2.error())));
+ }
}
void PinManager::load_lockout_state() {
@@ -120,8 +195,30 @@ void PinManager::load_lockout_state() {
auto lockout_r = ss.retrieve("pin_lockout_until");
if (lockout_r.is_ok() && !lockout_r.value().isEmpty()) {
lockout_until_ = QDateTime::fromString(lockout_r.value(), Qt::ISODate);
- // Clear expired lockout
- if (lockout_until_.isValid() && lockout_until_ <= QDateTime::currentDateTime())
+
+ // Clock-rollback defence: compare current wall clock to the timestamp
+ // we stored the last time we updated the lockout. If the clock has
+ // been moved backward by more than 60s (small NTP corrections are
+ // acceptable), refuse to trust "now" for lockout-expiry purposes —
+ // extend the deadline by the rollback delta so the attacker gains no
+ // free time.
+ auto stamp_r = ss.retrieve("pin_lockout_stamp");
+ const QDateTime now = QDateTime::currentDateTime();
+ if (stamp_r.is_ok() && !stamp_r.value().isEmpty()) {
+ const QDateTime stamp = QDateTime::fromString(stamp_r.value(), Qt::ISODate);
+ if (stamp.isValid() && now.secsTo(stamp) > 60) {
+ const qint64 rollback = now.secsTo(stamp); // positive seconds
+ LOG_WARN("Auth",
+ QString("System clock rolled back %1s since last lockout write — "
+ "extending lockout by that delta")
+ .arg(rollback));
+ if (lockout_until_.isValid())
+ lockout_until_ = lockout_until_.addSecs(rollback);
+ }
+ }
+
+ // Clear expired lockout only after the rollback check above.
+ if (lockout_until_.isValid() && lockout_until_ <= now)
lockout_until_ = QDateTime();
}
}
@@ -133,14 +230,11 @@ bool PinManager::has_pin() const {
}
Result<void> PinManager::set_pin(const QString& pin) {
- if (pin.length() != 6)
- return Result<void>::err("PIN must be exactly 6 digits");
-
- // Validate all digits
- for (const QChar& c : pin) {
- if (!c.isDigit())
- return Result<void>::err("PIN must contain only digits");
- }
+ // Centralized weak-PIN rejection — every caller goes through this, so the
+ // UI cannot be bypassed by a scripted flow or a future companion-setup path.
+ const QString weak = weak_pin_reason(pin);
+ if (!weak.isEmpty())
+ return Result<void>::err(weak.toStdString());
// Generate cryptographically random salt
QByteArray salt(kSaltLength, '\0');
@@ -172,9 +266,32 @@ Result<void> PinManager::set_pin(const QString& pin) {
save_lockout_state();
LOG_INFO("Auth", "PIN configured successfully");
+ SecurityAuditLog::instance().record("pin_set");
return Result<void>::ok();
}
+Result<void> PinManager::change_pin(const QString& old_pin, const QString& new_pin) {
+ // Must already have a PIN — otherwise the caller should go through set_pin.
+ if (!has_pin_)
+ return Result<void>::err("No PIN is configured — use set_pin()");
+
+ // Verify old PIN via the same path as an unlock attempt. This means a wrong
+ // old_pin increments failed_attempts_ and can trigger the normal lockout
+ // ladder, so an attacker who momentarily has an unlocked terminal cannot
+ // silently swap the PIN by guessing the old one.
+ if (!verify_pin(old_pin))
+ return Result<void>::err("Current PIN is incorrect");
+
+ // Disallow reusing the same PIN so users don't think the flow did nothing.
+ if (old_pin == new_pin)
+ return Result<void>::err("New PIN must differ from the current PIN");
+
+ auto r = set_pin(new_pin);
+ if (r.is_ok())
+ SecurityAuditLog::instance().record("pin_changed");
+ return r;
+}
+
bool PinManager::verify_pin(const QString& pin) {
if (!has_pin_)
return false;
@@ -189,35 +306,55 @@ bool PinManager::verify_pin(const QString& pin) {
return false;
}
- // Derive and compare
+ // Derive and compare. Use a constant-time comparison so execution time
+ // does not leak the position of the first differing byte — PBKDF2 already
+ // makes brute-force expensive, but the compare itself must not be a side
+ // channel.
QByteArray derived = derive_key(pin, stored_salt_);
- if (derived == stored_hash_) {
+ if (constant_time_equals(derived, stored_hash_)) {
// Success — reset lockout
failed_attempts_ = 0;
lockout_until_ = QDateTime();
save_lockout_state();
LOG_INFO("Auth", "PIN verified successfully");
+ SecurityAuditLog::instance().record("pin_verify_ok");
return true;
}
// Failed attempt
failed_attempts_++;
LOG_WARN("Auth", QString("PIN verification failed (attempt %1/%2)").arg(failed_attempts_).arg(kMaxAttempts));
+ SecurityAuditLog::instance().record(
+ "pin_verify_fail", QString("attempt=%1/%2").arg(failed_attempts_).arg(kMaxAttempts));
if (failed_attempts_ >= kMaxAttempts) {
// Permanent lockout — require server re-auth
save_lockout_state();
+ SecurityAuditLog::instance().record("max_attempts_exceeded");
emit max_attempts_exceeded();
emit lockout_changed(true, 0);
return false;
}
- // Apply timed lockout
- int tier = qMin(failed_attempts_ - 1, static_cast<int>(kLockoutTiers.size()) - 1);
+ // Grace period: the first kFreeAttempts mistakes just show "incorrect"
+ // with no timed lockout — users legitimately fat-finger a 6-digit PIN.
+ // The timed-lockout ladder starts at attempt (kFreeAttempts + 1), i.e.
+ // the 3rd failure triggers the first 30s lockout.
+ if (failed_attempts_ <= kFreeAttempts) {
+ save_lockout_state();
+ return false;
+ }
+
+ // Apply timed lockout. The ladder is indexed from the first *post-grace*
+ // failure so the first lockout is kLockoutTiers[0] (30s).
+ int tier = qMin(failed_attempts_ - kFreeAttempts - 1,
+ static_cast<int>(kLockoutTiers.size()) - 1);
int lockout_secs = kLockoutTiers[static_cast<size_t>(tier)];
lockout_until_ = QDateTime::currentDateTime().addSecs(lockout_secs);
save_lockout_state();
+ SecurityAuditLog::instance().record(
+ "lockout_started", QString("seconds=%1").arg(lockout_secs));
emit lockout_changed(true, lockout_secs);
return false;
@@ -229,6 +366,7 @@ void PinManager::clear_pin() {
ss.remove("pin_salt");
ss.remove("pin_failed_attempts");
ss.remove("pin_lockout_until");
+ ss.remove("pin_lockout_stamp");
stored_hash_.clear();
stored_salt_.clear();
@@ -237,6 +375,7 @@ void PinManager::clear_pin() {
lockout_until_ = QDateTime();
LOG_INFO("Auth", "PIN cleared");
+ SecurityAuditLog::instance().record("pin_cleared");
}
bool PinManager::is_locked_out() const {
@@ -258,6 +397,7 @@ void PinManager::reset_lockout() {
save_lockout_state();
emit lockout_changed(false, 0);
LOG_INFO("Auth", "PIN lockout reset after re-authentication");
+ SecurityAuditLog::instance().record("lockout_cleared");
}
} // namespace fincept::auth
diff --git a/fincept-qt/src/auth/PinManager.h b/fincept-qt/src/auth/PinManager.h
index ac469ee66..6c9071b33 100644
--- a/fincept-qt/src/auth/PinManager.h
+++ b/fincept-qt/src/auth/PinManager.h
@@ -23,9 +23,17 @@ class PinManager : public QObject {
/// True if user has configured a PIN (hash exists in SecureStorage).
bool has_pin() const;
- /// Set or update the PIN. Returns error if hash/storage fails.
+ /// Set or update the PIN. Returns error if hash/storage fails or the PIN
+ /// is trivially weak (all-same digits, ascending/descending sequence).
+ /// Note: this does NOT require the old PIN — use change_pin() for that.
Result<void> set_pin(const QString& pin);
+ /// Change the PIN, requiring the current PIN for authorization. A wrong
+ /// old_pin increments the failed-attempt counter exactly like a failed
+ /// unlock, so an attacker who unlocks an unattended terminal cannot
+ /// silently swap the PIN without facing the same lockout.
+ Result<void> change_pin(const QString& old_pin, const QString& new_pin);
+
/// Verify a PIN attempt. On failure increments attempt counter and
/// may trigger lockout. Returns true on match.
bool verify_pin(const QString& pin);
@@ -45,6 +53,12 @@ class PinManager : public QObject {
/// Max attempts before permanent lockout (requires server re-auth).
static constexpr int kMaxAttempts = 5;
+ /// Number of "free" wrong attempts before the timed-lockout ladder kicks
+ /// in. Set to 2 so the user gets 3 tries (attempts 1, 2, 3) with only a
+ /// generic "incorrect" error; the 3rd mistake starts the 30s lockout.
+ /// kMaxAttempts still caps the total at 5 before forced re-login.
+ static constexpr int kFreeAttempts = 2;
+
/// Reset lockout state (called after successful server re-auth).
void reset_lockout();
@@ -58,8 +72,10 @@ class PinManager : public QObject {
private:
PinManager();
- // PBKDF2-SHA256 parameters
- static constexpr int kIterations = 100000;
+ // PBKDF2-SHA256 parameters.
+ // 600_000 iterations per OWASP Password Storage Cheat Sheet (2023) for
+ // PBKDF2-SHA256. Verify cost stays well under 500ms on target hardware.
+ static constexpr int kIterations = 600000;
static constexpr int kSaltLength = 32;
static constexpr int kHashLength = 32;
diff --git a/fincept-qt/src/auth/SecurityAuditLog.cpp b/fincept-qt/src/auth/SecurityAuditLog.cpp
new file mode 100644
index 000000000..30e26da2e
--- /dev/null
+++ b/fincept-qt/src/auth/SecurityAuditLog.cpp
@@ -0,0 +1,58 @@
+#include "auth/SecurityAuditLog.h"
+
+#include "core/logging/Logger.h"
+#include "storage/sqlite/Database.h"
+
+#include <QSqlQuery>
+#include <QVariantList>
+
+namespace fincept::auth {
+
+SecurityAuditLog& SecurityAuditLog::instance() {
+ static SecurityAuditLog s;
+ return s;
+}
+
+void SecurityAuditLog::record(const QString& event, const QString& detail) {
+ auto& db = Database::instance();
+ if (!db.is_open()) {
+ // No DB yet — likely pre-migration startup. Skip silently; callers
+ // still log via the normal Logger so the information is not lost.
+ return;
+ }
+
+ const qint64 ts = QDateTime::currentSecsSinceEpoch();
+ const auto r = db.execute(
+ "INSERT INTO security_audit_log (ts, event, detail) VALUES (?, ?, ?)",
+ {QVariant(ts), QVariant(event), QVariant(detail)});
+ if (r.is_err()) {
+ LOG_ERROR("SecurityAudit",
+ QString("Failed to record event '%1': %2").arg(event, QString::fromStdString(r.error())));
+ }
+}
+
+QList<AuditEvent> SecurityAuditLog::recent(int limit) {
+ QList<AuditEvent> out;
+ auto& db = Database::instance();
+ if (!db.is_open())
+ return out;
+
+ auto r = db.execute(
+ "SELECT id, ts, event, detail FROM security_audit_log ORDER BY ts DESC LIMIT ?",
+ {QVariant(limit)});
+ if (r.is_err())
+ return out;
+
+ auto q = r.value();
+ while (q.next()) {
+ AuditEvent e;
+ e.id = q.value(0).toLongLong();
+ e.timestamp = QDateTime::fromSecsSinceEpoch(q.value(1).toLongLong());
+ e.event = q.value(2).toString();
+ e.detail = q.value(3).toString();
+ out.append(e);
+ }
+ return out;
+}
+
+} // namespace fincept::auth
diff --git a/fincept-qt/src/auth/SecurityAuditLog.h b/fincept-qt/src/auth/SecurityAuditLog.h
new file mode 100644
index 000000000..311e3864d
--- /dev/null
+++ b/fincept-qt/src/auth/SecurityAuditLog.h
@@ -0,0 +1,43 @@
+#pragma once
+#include <QDateTime>
+#include <QList>
+#include <QObject>
+#include <QString>
+
+namespace fincept::auth {
+
+/// One persisted security audit event. Mirrors the `security_audit_log`
+/// table created by migration v020.
+struct AuditEvent {
+ qint64 id = 0;
+ QDateTime timestamp;
+ QString event;
+ QString detail;
+};
+
+/// Persistent append-only record of PIN / lock-screen security events.
+/// Writes go to the `security_audit_log` table; recent reads power the
+/// Settings → Security audit-log view.
+///
+/// Callers record events with short stable identifiers so the stream remains
+/// grep-able and the read path is trivial. Event vocabulary:
+/// pin_set, pin_changed, pin_cleared,
+/// pin_verify_ok, pin_verify_fail,
+/// lockout_started, lockout_cleared, max_attempts_exceeded,
+/// inactivity_lock, manual_lock, resume_lock, minimize_lock
+class SecurityAuditLog {
+ public:
+ static SecurityAuditLog& instance();
+
+ /// Record an event. Silent on DB errors — failing to audit must not
+ /// break the calling flow (e.g. PIN verification). Errors go to LOG_ERROR.
+ void record(const QString& event, const QString& detail = QString());
+
+ /// Fetch the most recent events, newest first.
+ QList<AuditEvent> recent(int limit = 100);
+
+ private:
+ SecurityAuditLog() = default;
+};
+
+} // namespace fincept::auth
diff --git a/fincept-qt/src/core/components/ComponentCatalog.cpp b/fincept-qt/src/core/components/ComponentCatalog.cpp
new file mode 100644
index 000000000..8a11dd3dd
--- /dev/null
+++ b/fincept-qt/src/core/components/ComponentCatalog.cpp
@@ -0,0 +1,107 @@
+#include "core/components/ComponentCatalog.h"
+
+#include "core/components/PopularityTracker.h"
+#include "core/logging/Logger.h"
+
+#include <QFile>
+#include <QFileInfo>
+#include <QJsonArray>
+#include <QJsonDocument>
+#include <QJsonObject>
+
+#include <algorithm>
+
+namespace fincept {
+
+ComponentCatalog& ComponentCatalog::instance() {
+ static ComponentCatalog s;
+ return s;
+}
+
+int ComponentCatalog::load_from_file(const QString& path) {
+ entries_.clear();
+ index_by_id_.clear();
+ categories_in_order_.clear();
+
+ QFile f(path);
+ if (!f.open(QIODevice::ReadOnly)) {
+ LOG_WARN("ComponentCatalog", QString("Could not open %1").arg(path));
+ return 0;
+ }
+ const QByteArray blob = f.readAll();
+ f.close();
+
+ const QJsonDocument doc = QJsonDocument::fromJson(blob);
+ if (!doc.isObject()) {
+ LOG_WARN("ComponentCatalog", QString("Invalid JSON in %1").arg(path));
+ return 0;
+ }
+ const QJsonArray arr = doc.object().value("components").toArray();
+ for (const QJsonValue& v : arr) {
+ if (!v.isObject())
+ continue;
+ ComponentMeta m = ComponentMeta::from_json(v.toObject());
+ if (!m.is_valid())
+ continue;
+ if (index_by_id_.contains(m.id)) {
+ LOG_WARN("ComponentCatalog", QString("Duplicate id: %1").arg(m.id));
+ continue;
+ }
+ index_by_id_[m.id] = static_cast<int>(entries_.size());
+ entries_.append(m);
+ if (!m.category.isEmpty() && !categories_in_order_.contains(m.category))
+ categories_in_order_.append(m.category);
+ }
+
+ LOG_INFO("ComponentCatalog", QString("Loaded %1 components from %2").arg(entries_.size()).arg(path));
+ emit reloaded();
+ return static_cast<int>(entries_.size());
+}
+
+int ComponentCatalog::load_with_fallbacks(const QStringList& candidates) {
+ for (const QString& p : candidates) {
+ if (QFileInfo::exists(p))
+ return load_from_file(p);
+ }
+ LOG_WARN("ComponentCatalog", "No catalogue file found in any candidate path");
+ return 0;
+}
+
+QList<ComponentMeta> ComponentCatalog::all() const {
+ return entries_;
+}
+
+QList<ComponentMeta> ComponentCatalog::list_for_ui() const {
+ QList<ComponentMeta> out = entries_;
+ auto& tracker = PopularityTracker::instance();
+ for (ComponentMeta& m : out)
+ m.popularity = tracker.use_count(m.id);
+ std::sort(out.begin(), out.end(), [](const ComponentMeta& a, const ComponentMeta& b) {
+ if (a.popularity != b.popularity)
+ return a.popularity > b.popularity;
+ return a.title.localeAwareCompare(b.title) < 0;
+ });
+ return out;
+}
+
+QList<ComponentMeta> ComponentCatalog::by_category(const QString& category) const {
+ QList<ComponentMeta> out;
+ for (const ComponentMeta& m : list_for_ui()) {
+ if (m.category == category)
+ out.append(m);
+ }
+ return out;
+}
+
+QStringList ComponentCatalog::categories() const {
+ return categories_in_order_;
+}
+
+ComponentMeta ComponentCatalog::by_id(const QString& id) const {
+ const int idx = index_by_id_.value(id, -1);
+ if (idx < 0 || idx >= entries_.size())
+ return {};
+ return entries_.at(idx);
+}
+
+} // namespace fincept
diff --git a/fincept-qt/src/core/components/ComponentCatalog.h b/fincept-qt/src/core/components/ComponentCatalog.h
new file mode 100644
index 000000000..aef36d827
--- /dev/null
+++ b/fincept-qt/src/core/components/ComponentCatalog.h
@@ -0,0 +1,63 @@
+#pragma once
+#include "core/components/ComponentMeta.h"
+
+#include <QHash>
+#include <QList>
+#include <QObject>
+#include <QString>
+#include <QStringList>
+
+namespace fincept {
+
+/// Catalogue of all user-discoverable screens (components). The data lives
+/// in resources/component_catalog.json and is loaded once at startup.
+///
+/// This is *purely* a UI discovery layer — the authoritative screen registry
+/// is still DockScreenRouter. A catalogue entry with no matching
+/// DockScreenRouter factory is harmless (the browser will gracefully fail
+/// to navigate). A DockScreenRouter factory with no catalogue entry is
+/// invisible to the browser; that's also fine for screens we intentionally
+/// hide (auth, setup, lock, info, payment).
+class ComponentCatalog : public QObject {
+ Q_OBJECT
+ public:
+ static ComponentCatalog& instance();
+
+ /// Load the catalogue from the given file. Clears any previous state.
+ /// Returns the number of entries loaded (0 on failure). Safe to call
+ /// multiple times — the browser can reload the catalogue without
+ /// restarting.
+ int load_from_file(const QString& path);
+
+ /// Convenience: look in a list of candidate paths and use the first one
+ /// that exists. Used at startup to try the installed resource dir and
+ /// the build-dir fallback without forcing a Qt resource system round-trip.
+ int load_with_fallbacks(const QStringList& candidates);
+
+ /// All entries, unsorted. Popularity is NOT filled — use list_for_ui.
+ QList<ComponentMeta> all() const;
+
+ /// All entries with popularity populated from PopularityTracker and
+ /// sorted by popularity desc then title asc. Intended for the browser.
+ QList<ComponentMeta> list_for_ui() const;
+
+ /// Entries in a single category, popularity-sorted.
+ QList<ComponentMeta> by_category(const QString& category) const;
+
+ /// Distinct category names in insertion order of first appearance.
+ QStringList categories() const;
+
+ /// Lookup by id; empty `id` returns an invalid ComponentMeta.
+ ComponentMeta by_id(const QString& id) const;
+
+ signals:
+ void reloaded();
+
+ private:
+ ComponentCatalog() = default;
+ QList<ComponentMeta> entries_;
+ QHash<QString, int> index_by_id_; // id → position in entries_
+ QStringList categories_in_order_;
+};
+
+} // namespace fincept
diff --git a/fincept-qt/src/core/components/ComponentMeta.h b/fincept-qt/src/core/components/ComponentMeta.h
new file mode 100644
index 000000000..3c7e44a96
--- /dev/null
+++ b/fincept-qt/src/core/components/ComponentMeta.h
@@ -0,0 +1,51 @@
+#pragma once
+#include <QJsonArray>
+#include <QJsonObject>
+#include <QString>
+#include <QStringList>
+
+namespace fincept {
+
+/// Metadata describing a single "component" (screen) that can be discovered,
+/// browsed, and spawned via the Component Browser (Phase 6 — Bloomberg
+/// Launchpad Component Catalogue equivalent).
+///
+/// Populated from resources/component_catalog.json at startup. `popularity`
+/// is *not* stored in the catalogue file — it's read live from
+/// PopularityTracker at query time, so sort order reflects actual usage.
+struct ComponentMeta {
+ QString id; // matches DockScreenRouter screen id
+ QString title; // human-readable, e.g. "Equity Trading"
+ QString category; // "Trading", "Markets", "Research", etc.
+ QString description; // one-line summary; empty allowed
+ QStringList tags; // searchable keywords; empty allowed
+ int popularity = 0; // use count, filled by ComponentCatalog::list_for_ui
+
+ bool is_valid() const { return !id.isEmpty() && !title.isEmpty(); }
+
+ QJsonObject to_json() const {
+ QJsonObject o;
+ o["id"] = id;
+ o["title"] = title;
+ o["category"] = category;
+ o["description"] = description;
+ QJsonArray ta;
+ for (const QString& t : tags)
+ ta.append(t);
+ o["tags"] = ta;
+ return o;
+ }
+
+ static ComponentMeta from_json(const QJsonObject& o) {
+ ComponentMeta m;
+ m.id = o.value("id").toString();
+ m.title = o.value("title").toString();
+ m.category = o.value("category").toString();
+ m.description = o.value("description").toString();
+ for (const QJsonValue& v : o.value("tags").toArray())
+ m.tags.append(v.toString());
+ return m;
+ }
+};
+
+} // namespace fincept
diff --git a/fincept-qt/src/core/components/PopularityTracker.cpp b/fincept-qt/src/core/components/PopularityTracker.cpp
new file mode 100644
index 000000000..df7463df1
--- /dev/null
+++ b/fincept-qt/src/core/components/PopularityTracker.cpp
@@ -0,0 +1,60 @@
+#include "core/components/PopularityTracker.h"
+
+#include <QSettings>
+
+namespace fincept {
+
+static constexpr const char* kOrg = "Fincept";
+static constexpr const char* kApp = "FinceptTerminal";
+static constexpr const char* kGroup = "component_usage";
+
+PopularityTracker& PopularityTracker::instance() {
+ static PopularityTracker s;
+ return s;
+}
+
+PopularityTracker::PopularityTracker() {
+ load();
+}
+
+void PopularityTracker::load() {
+ QSettings settings(kOrg, kApp);
+ settings.beginGroup(kGroup);
+ const QStringList keys = settings.childKeys();
+ for (const QString& k : keys) {
+ const int n = settings.value(k, 0).toInt();
+ if (n > 0)
+ counts_[k] = n;
+ }
+ settings.endGroup();
+}
+
+void PopularityTracker::save(const QString& id, int count) {
+ QSettings settings(kOrg, kApp);
+ settings.beginGroup(kGroup);
+ settings.setValue(id, count);
+ settings.endGroup();
+}
+
+void PopularityTracker::increment(const QString& id) {
+ if (id.isEmpty())
+ return;
+ const int next = counts_.value(id, 0) + 1;
+ counts_[id] = next;
+ save(id, next);
+ emit usage_changed(id, next);
+}
+
+int PopularityTracker::use_count(const QString& id) const {
+ return counts_.value(id, 0);
+}
+
+void PopularityTracker::clear_all() {
+ counts_.clear();
+ QSettings settings(kOrg, kApp);
+ settings.beginGroup(kGroup);
+ settings.remove("");
+ settings.endGroup();
+}
+
+} // namespace fincept
diff --git a/fincept-qt/src/core/components/PopularityTracker.h b/fincept-qt/src/core/components/PopularityTracker.h
new file mode 100644
index 000000000..204ba00d2
--- /dev/null
+++ b/fincept-qt/src/core/components/PopularityTracker.h
@@ -0,0 +1,47 @@
+#pragma once
+#include <QHash>
+#include <QObject>
+#include <QString>
+
+namespace fincept {
+
+/// Tracks how often each screen (component) has been navigated to. Used by
+/// the Component Browser to surface frequently-used components at the top
+/// of the grid — a cheap equivalent of Bloomberg's popularity stars on
+/// Launchpad's component catalogue.
+///
+/// Storage: QSettings under "component_usage/<id>" = int. Per-user,
+/// per-profile (scoped through the existing "Fincept/FinceptTerminal"
+/// QSettings organisation/app). Does NOT sync to the cloud — a user's
+/// usage fingerprint is intentionally local.
+///
+/// The counter is monotonically increasing; we don't decay it. For a
+/// first pass that's fine; if rankings get stale after months of usage we
+/// can add a time-window later without breaking the schema.
+class PopularityTracker : public QObject {
+ Q_OBJECT
+ public:
+ static PopularityTracker& instance();
+
+ /// Bump the use count for a screen id. Idempotent — safe to call from
+ /// any navigation path. No-op for empty id.
+ void increment(const QString& id);
+
+ /// Current use count. Returns 0 for unknown ids (never navigated).
+ int use_count(const QString& id) const;
+
+ /// Reset all counts. Used by the "Clear usage history" setting.
+ void clear_all();
+
+ signals:
+ void usage_changed(const QString& id, int new_count);
+
+ private:
+ PopularityTracker();
+ void load();
+ void save(const QString& id, int count);
+
+ QHash<QString, int> counts_;
+};
+
+} // namespace fincept
diff --git a/fincept-qt/src/core/keys/KeyActions.h b/fincept-qt/src/core/keys/KeyActions.h
index 7aa44e90f..3c2dc9d7c 100644
--- a/fincept-qt/src/core/keys/KeyActions.h
+++ b/fincept-qt/src/core/keys/KeyActions.h
@@ -27,6 +27,51 @@ enum class KeyAction {
RunCell,
RunAndNext,
RenameCell,
+
+ // Window / Panel Navigation (Phase 3)
+ // Focus a specific MainWindow by its 1-based ordinal across open windows
+ // (Ctrl+1..9 by default). Ctrl+1 always targets window_id = 0.
+ FocusWindow1,
+ FocusWindow2,
+ FocusWindow3,
+ FocusWindow4,
+ FocusWindow5,
+ FocusWindow6,
+ FocusWindow7,
+ FocusWindow8,
+ FocusWindow9,
+
+ // Cycle active dock widget inside the focused MainWindow.
+ CyclePanelsForward,
+ CyclePanelsBack,
+
+ // Cycle focus between MainWindow instances (Bloomberg PANEL key).
+ CycleWindowsForward,
+ CycleWindowsBack,
+
+ // Spawn a new MainWindow, placed on the next available monitor.
+ NewWindowNextMonitor,
+
+ // Move the current MainWindow to monitor N (Ctrl+Shift+1..9).
+ MoveWindowToMonitor1,
+ MoveWindowToMonitor2,
+ MoveWindowToMonitor3,
+ MoveWindowToMonitor4,
+ MoveWindowToMonitor5,
+ MoveWindowToMonitor6,
+ MoveWindowToMonitor7,
+ MoveWindowToMonitor8,
+ MoveWindowToMonitor9,
+
+ // Phase 6 — Component Browser
+ BrowseComponents,
+
+ // Phase 11 — Always-on-top toggle on the focused window.
+ ToggleAlwaysOnTop,
+
+ // Phase 12 — Manual lock. Immediately shows the PIN-unlock screen
+ // without waiting for inactivity. Default binding: Ctrl+L.
+ LockNow,
};
} // namespace fincept
diff --git a/fincept-qt/src/core/keys/KeyConfigManager.cpp b/fincept-qt/src/core/keys/KeyConfigManager.cpp
index b4de7745a..9ca504207 100644
--- a/fincept-qt/src/core/keys/KeyConfigManager.cpp
+++ b/fincept-qt/src/core/keys/KeyConfigManager.cpp
@@ -27,6 +27,34 @@ static QString storage_key(KeyAction a) {
case KeyAction::RunCell: return "key.run_cell";
case KeyAction::RunAndNext: return "key.run_and_next";
case KeyAction::RenameCell: return "key.rename_cell";
+
+ case KeyAction::FocusWindow1: return "key.focus_window_1";
+ case KeyAction::FocusWindow2: return "key.focus_window_2";
+ case KeyAction::FocusWindow3: return "key.focus_window_3";
+ case KeyAction::FocusWindow4: return "key.focus_window_4";
+ case KeyAction::FocusWindow5: return "key.focus_window_5";
+ case KeyAction::FocusWindow6: return "key.focus_window_6";
+ case KeyAction::FocusWindow7: return "key.focus_window_7";
+ case KeyAction::FocusWindow8: return "key.focus_window_8";
+ case KeyAction::FocusWindow9: return "key.focus_window_9";
+ case KeyAction::CyclePanelsForward: return "key.cycle_panels_forward";
+ case KeyAction::CyclePanelsBack: return "key.cycle_panels_back";
+ case KeyAction::CycleWindowsForward: return "key.cycle_windows_forward";
+ case KeyAction::CycleWindowsBack: return "key.cycle_windows_back";
+ case KeyAction::NewWindowNextMonitor: return "key.new_window_next_monitor";
+ case KeyAction::MoveWindowToMonitor1: return "key.move_window_to_monitor_1";
+ case KeyAction::MoveWindowToMonitor2: return "key.move_window_to_monitor_2";
+ case KeyAction::MoveWindowToMonitor3: return "key.move_window_to_monitor_3";
+ case KeyAction::MoveWindowToMonitor4: return "key.move_window_to_monitor_4";
+ case KeyAction::MoveWindowToMonitor5: return "key.move_window_to_monitor_5";
+ case KeyAction::MoveWindowToMonitor6: return "key.move_window_to_monitor_6";
+ case KeyAction::MoveWindowToMonitor7: return "key.move_window_to_monitor_7";
+ case KeyAction::MoveWindowToMonitor8: return "key.move_window_to_monitor_8";
+ case KeyAction::MoveWindowToMonitor9: return "key.move_window_to_monitor_9";
+
+ case KeyAction::BrowseComponents: return "key.browse_components";
+ case KeyAction::ToggleAlwaysOnTop: return "key.toggle_always_on_top";
+ case KeyAction::LockNow: return "key.lock_now";
}
return {};
}
@@ -50,6 +78,45 @@ KeyConfigManager::KeyConfigManager() {
defaults_[KeyAction::RunAndNext] = QKeySequence(Qt::SHIFT | Qt::Key_Return);
defaults_[KeyAction::RenameCell] = QKeySequence(Qt::Key_F2);
+ // Phase 3 — window/panel navigation
+ defaults_[KeyAction::FocusWindow1] = QKeySequence(Qt::CTRL | Qt::Key_1);
+ defaults_[KeyAction::FocusWindow2] = QKeySequence(Qt::CTRL | Qt::Key_2);
+ defaults_[KeyAction::FocusWindow3] = QKeySequence(Qt::CTRL | Qt::Key_3);
+ defaults_[KeyAction::FocusWindow4] = QKeySequence(Qt::CTRL | Qt::Key_4);
+ defaults_[KeyAction::FocusWindow5] = QKeySequence(Qt::CTRL | Qt::Key_5);
+ defaults_[KeyAction::FocusWindow6] = QKeySequence(Qt::CTRL | Qt::Key_6);
+ defaults_[KeyAction::FocusWindow7] = QKeySequence(Qt::CTRL | Qt::Key_7);
+ defaults_[KeyAction::FocusWindow8] = QKeySequence(Qt::CTRL | Qt::Key_8);
+ defaults_[KeyAction::FocusWindow9] = QKeySequence(Qt::CTRL | Qt::Key_9);
+ defaults_[KeyAction::CyclePanelsForward] = QKeySequence(Qt::CTRL | Qt::Key_Tab);
+ defaults_[KeyAction::CyclePanelsBack] = QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_Tab);
+ // Ctrl+Alt+Tab is a window-manager shortcut on several platforms; wrap it
+ // with the same gesture plus a non-default modifier so it still feels
+ // related but doesn't clash. Users can rebind in Settings.
+ defaults_[KeyAction::CycleWindowsForward] = QKeySequence(Qt::CTRL | Qt::ALT | Qt::Key_Tab);
+ defaults_[KeyAction::CycleWindowsBack] = QKeySequence(Qt::CTRL | Qt::ALT | Qt::SHIFT | Qt::Key_Tab);
+ defaults_[KeyAction::NewWindowNextMonitor] = QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_N);
+ defaults_[KeyAction::MoveWindowToMonitor1] = QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_1);
+ defaults_[KeyAction::MoveWindowToMonitor2] = QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_2);
+ defaults_[KeyAction::MoveWindowToMonitor3] = QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_3);
+ defaults_[KeyAction::MoveWindowToMonitor4] = QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_4);
+ defaults_[KeyAction::MoveWindowToMonitor5] = QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_5);
+ defaults_[KeyAction::MoveWindowToMonitor6] = QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_6);
+ defaults_[KeyAction::MoveWindowToMonitor7] = QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_7);
+ defaults_[KeyAction::MoveWindowToMonitor8] = QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_8);
+ defaults_[KeyAction::MoveWindowToMonitor9] = QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_9);
+
+ // Phase 6 — Component Browser
+ defaults_[KeyAction::BrowseComponents] = QKeySequence(Qt::CTRL | Qt::Key_K);
+
+ // Phase 11 — Always-on-top window toggle. Ctrl+Shift+T is un-used by any
+ // existing binding in this project and is a common convention for "top".
+ defaults_[KeyAction::ToggleAlwaysOnTop] = QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_T);
+
+ // Phase 12 — Manual lock. Ctrl+L is the most common "lock" binding across
+ // terminal / Bloomberg workflows. Users can rebind in Settings.
+ defaults_[KeyAction::LockNow] = QKeySequence(Qt::CTRL | Qt::Key_L);
+
// Create QActions with default sequences
for (auto it = defaults_.begin(); it != defaults_.end(); ++it) {
auto* act = new QAction(this);
@@ -120,6 +187,34 @@ QString KeyConfigManager::display_name(KeyAction a) const {
case KeyAction::RunCell: return "Run Cell";
case KeyAction::RunAndNext: return "Run & Move Next";
case KeyAction::RenameCell: return "Rename Cell";
+
+ case KeyAction::FocusWindow1: return "Focus Window 1";
+ case KeyAction::FocusWindow2: return "Focus Window 2";
+ case KeyAction::FocusWindow3: return "Focus Window 3";
+ case KeyAction::FocusWindow4: return "Focus Window 4";
+ case KeyAction::FocusWindow5: return "Focus Window 5";
+ case KeyAction::FocusWindow6: return "Focus Window 6";
+ case KeyAction::FocusWindow7: return "Focus Window 7";
+ case KeyAction::FocusWindow8: return "Focus Window 8";
+ case KeyAction::FocusWindow9: return "Focus Window 9";
+ case KeyAction::CyclePanelsForward: return "Next Panel";
+ case KeyAction::CyclePanelsBack: return "Previous Panel";
+ case KeyAction::CycleWindowsForward: return "Next Window";
+ case KeyAction::CycleWindowsBack: return "Previous Window";
+ case KeyAction::NewWindowNextMonitor: return "New Window (Next Monitor)";
+ case KeyAction::MoveWindowToMonitor1: return "Move Window to Monitor 1";
+ case KeyAction::MoveWindowToMonitor2: return "Move Window to Monitor 2";
+ case KeyAction::MoveWindowToMonitor3: return "Move Window to Monitor 3";
+ case KeyAction::MoveWindowToMonitor4: return "Move Window to Monitor 4";
+ case KeyAction::MoveWindowToMonitor5: return "Move Window to Monitor 5";
+ case KeyAction::MoveWindowToMonitor6: return "Move Window to Monitor 6";
+ case KeyAction::MoveWindowToMonitor7: return "Move Window to Monitor 7";
+ case KeyAction::MoveWindowToMonitor8: return "Move Window to Monitor 8";
+ case KeyAction::MoveWindowToMonitor9: return "Move Window to Monitor 9";
+
+ case KeyAction::BrowseComponents: return "Browse Components";
+ case KeyAction::ToggleAlwaysOnTop: return "Toggle Always-on-Top";
+ case KeyAction::LockNow: return "Lock Terminal Now";
}
return {};
}
@@ -146,6 +241,36 @@ QString KeyConfigManager::group_name(KeyAction a) const {
case KeyAction::RunAndNext:
case KeyAction::RenameCell:
return "Code Editor";
+
+ case KeyAction::FocusWindow1:
+ case KeyAction::FocusWindow2:
+ case KeyAction::FocusWindow3:
+ case KeyAction::FocusWindow4:
+ case KeyAction::FocusWindow5:
+ case KeyAction::FocusWindow6:
+ case KeyAction::FocusWindow7:
+ case KeyAction::FocusWindow8:
+ case KeyAction::FocusWindow9:
+ case KeyAction::CyclePanelsForward:
+ case KeyAction::CyclePanelsBack:
+ case KeyAction::CycleWindowsForward:
+ case KeyAction::CycleWindowsBack:
+ case KeyAction::NewWindowNextMonitor:
+ case KeyAction::MoveWindowToMonitor1:
+ case KeyAction::MoveWindowToMonitor2:
+ case KeyAction::MoveWindowToMonitor3:
+ case KeyAction::MoveWindowToMonitor4:
+ case KeyAction::MoveWindowToMonitor5:
+ case KeyAction::MoveWindowToMonitor6:
+ case KeyAction::MoveWindowToMonitor7:
+ case KeyAction::MoveWindowToMonitor8:
+ case KeyAction::MoveWindowToMonitor9:
+ return "Windows";
+
+ case KeyAction::BrowseComponents:
+ case KeyAction::ToggleAlwaysOnTop:
+ case KeyAction::LockNow:
+ return "Global";
}
return {};
}
@@ -157,6 +282,20 @@ QList<KeyAction> KeyConfigManager::all_actions() const {
KeyAction::NavNext, KeyAction::NavPrev, KeyAction::NavAccept, KeyAction::NavEscape,
KeyAction::NewsNext, KeyAction::NewsPrev, KeyAction::NewsOpen, KeyAction::NewsClose,
KeyAction::RunCell, KeyAction::RunAndNext, KeyAction::RenameCell,
+ KeyAction::FocusWindow1, KeyAction::FocusWindow2, KeyAction::FocusWindow3,
+ KeyAction::FocusWindow4, KeyAction::FocusWindow5, KeyAction::FocusWindow6,
+ KeyAction::FocusWindow7, KeyAction::FocusWindow8, KeyAction::FocusWindow9,
+ KeyAction::CyclePanelsForward, KeyAction::CyclePanelsBack,
+ KeyAction::CycleWindowsForward, KeyAction::CycleWindowsBack,
+ KeyAction::NewWindowNextMonitor,
+ KeyAction::MoveWindowToMonitor1, KeyAction::MoveWindowToMonitor2,
+ KeyAction::MoveWindowToMonitor3, KeyAction::MoveWindowToMonitor4,
+ KeyAction::MoveWindowToMonitor5, KeyAction::MoveWindowToMonitor6,
+ KeyAction::MoveWindowToMonitor7, KeyAction::MoveWindowToMonitor8,
+ KeyAction::MoveWindowToMonitor9,
+ KeyAction::BrowseComponents,
+ KeyAction::ToggleAlwaysOnTop,
+ KeyAction::LockNow,
};
}
diff --git a/fincept-qt/src/core/keys/WindowCycler.cpp b/fincept-qt/src/core/keys/WindowCycler.cpp
new file mode 100644
index 000000000..a3a7daeba
--- /dev/null
+++ b/fincept-qt/src/core/keys/WindowCycler.cpp
@@ -0,0 +1,136 @@
+#include "core/keys/WindowCycler.h"
+
+#include "app/DockScreenRouter.h"
+#include "app/MainWindow.h"
+#include "core/logging/Logger.h"
+
+#include <QApplication>
+#include <QGuiApplication>
+#include <QScreen>
+
+#include <algorithm>
+
+namespace fincept {
+
+WindowCycler& WindowCycler::instance() {
+ static WindowCycler s;
+ return s;
+}
+
+void WindowCycler::register_window(MainWindow* w) {
+ if (!w)
+ return;
+ // Skip duplicates — idempotent register keeps callers simple.
+ for (const QPointer<MainWindow>& p : windows_) {
+ if (p == w)
+ return;
+ }
+ windows_.append(QPointer<MainWindow>(w));
+}
+
+void WindowCycler::unregister_window(MainWindow* w) {
+ if (!w)
+ return;
+ windows_.erase(std::remove_if(windows_.begin(), windows_.end(),
+ [w](const QPointer<MainWindow>& p) { return p == w || p.isNull(); }),
+ windows_.end());
+}
+
+QList<MainWindow*> WindowCycler::windows() const {
+ QList<MainWindow*> out;
+ out.reserve(windows_.size());
+ for (const QPointer<MainWindow>& p : windows_) {
+ if (p)
+ out.append(p.data());
+ }
+ std::sort(out.begin(), out.end(),
+ [](MainWindow* a, MainWindow* b) { return a->window_id() < b->window_id(); });
+ return out;
+}
+
+MainWindow* WindowCycler::current_focused() const {
+ auto* aw = QApplication::activeWindow();
+ if (auto* mw = qobject_cast<MainWindow*>(aw))
+ return mw;
+ // Fallback: first sorted window. Useful when activeWindow() is a modal
+ // dialog or the OS just handed focus to another app.
+ const auto list = windows();
+ return list.isEmpty() ? nullptr : list.first();
+}
+
+void WindowCycler::focus_window_by_index(int n) {
+ const auto list = windows();
+ if (n < 0 || n >= list.size())
+ return;
+ auto* w = list.at(n);
+ w->showNormal(); // de-minimise if needed
+ w->raise();
+ w->activateWindow();
+ w->setFocus(Qt::ShortcutFocusReason);
+}
+
+void WindowCycler::cycle_windows(bool forward) {
+ const auto list = windows();
+ if (list.size() < 2)
+ return;
+ auto* current = current_focused();
+ int idx = current ? list.indexOf(current) : -1;
+ if (idx < 0)
+ idx = 0;
+ else
+ idx = (idx + (forward ? 1 : -1) + list.size()) % list.size();
+ auto* next = list.at(idx);
+ next->showNormal();
+ next->raise();
+ next->activateWindow();
+ next->setFocus(Qt::ShortcutFocusReason);
+}
+
+void WindowCycler::cycle_panels_in_current_window(bool forward) {
+ auto* w = current_focused();
+ if (!w)
+ return;
+ if (auto* router = w->dock_router())
+ router->cycle_focused_panel(forward);
+}
+
+void WindowCycler::new_window_on_next_monitor() {
+ auto* src = current_focused();
+ auto* w = new MainWindow(MainWindow::next_window_id());
+ w->setAttribute(Qt::WA_DeleteOnClose);
+
+ // Smart placement: find a screen that doesn't contain the source
+ // window's centre. Matches the "new window" action in MainWindow's
+ // toolbar handler — kept in sync intentionally.
+ const auto screens = QGuiApplication::screens();
+ if (src && screens.size() > 1) {
+ const QPoint src_centre = src->geometry().center();
+ for (QScreen* s : screens) {
+ if (!s->geometry().contains(src_centre)) {
+ const QRect sg = s->availableGeometry();
+ w->resize(sg.width() * 9 / 10, sg.height() * 9 / 10);
+ w->move(sg.center() - w->rect().center());
+ break;
+ }
+ }
+ }
+ w->show();
+ w->raise();
+ w->activateWindow();
+}
+
+void WindowCycler::move_current_window_to_monitor(int monitor_index) {
+ const auto screens = QGuiApplication::screens();
+ if (monitor_index < 0 || monitor_index >= screens.size()) {
+ LOG_DEBUG("WindowCycler",
+ QString("Ignoring move-to-monitor %1 — only %2 screen(s) connected")
+ .arg(monitor_index).arg(screens.size()));
+ return;
+ }
+ auto* w = current_focused();
+ if (!w)
+ return;
+ w->move_to_screen(screens.at(monitor_index));
+}
+
+} // namespace fincept
diff --git a/fincept-qt/src/core/keys/WindowCycler.h b/fincept-qt/src/core/keys/WindowCycler.h
new file mode 100644
index 000000000..d05abc5aa
--- /dev/null
+++ b/fincept-qt/src/core/keys/WindowCycler.h
@@ -0,0 +1,66 @@
+#pragma once
+#include <QList>
+#include <QObject>
+#include <QPointer>
+
+namespace fincept {
+
+class MainWindow;
+
+/// Process-global registry of live MainWindow instances, plus the keyboard
+/// navigation policies that move focus between them. Kept out of
+/// QApplication/QCoreApplication so tests can introspect it without needing
+/// a full Qt app instance.
+///
+/// MainWindow::MainWindow() calls register_window(this); the destructor calls
+/// unregister_window(this) — the cycler holds weak (QPointer) refs so it
+/// never keeps a dying window alive.
+///
+/// Ordering: windows are stored in insertion order but surfaced to the user
+/// in ascending window_id order, so Ctrl+1 = primary, Ctrl+2 = first
+/// secondary, and so on. That mapping is stable across a session even if
+/// windows are created out of order.
+class WindowCycler : public QObject {
+ Q_OBJECT
+ public:
+ static WindowCycler& instance();
+
+ void register_window(MainWindow* w);
+ void unregister_window(MainWindow* w);
+
+ /// Return all live MainWindows sorted by window_id (ascending).
+ QList<MainWindow*> windows() const;
+
+ /// Focus the Nth window (0-based) in window_id order. No-op if N is out
+ /// of range. Activates, raises, and gives keyboard focus to the window.
+ void focus_window_by_index(int n);
+
+ /// Cycle focus forward/back through MainWindows in window_id order. No-op
+ /// if fewer than 2 windows are open.
+ void cycle_windows(bool forward);
+
+ /// Cycle the focused panel inside whichever MainWindow currently has
+ /// focus. Delegates to that window's DockScreenRouter.
+ void cycle_panels_in_current_window(bool forward);
+
+ /// Spawn a new MainWindow placed on the next available monitor (the
+ /// first monitor that doesn't already host the currently-focused
+ /// MainWindow's centre). Falls back to the primary screen.
+ void new_window_on_next_monitor();
+
+ /// Move the currently-focused MainWindow to monitor N (0-based index
+ /// into QGuiApplication::screens()). No-op if N is out of range or
+ /// the window is already there.
+ void move_current_window_to_monitor(int monitor_index);
+
+ private:
+ WindowCycler() = default;
+
+ MainWindow* current_focused() const;
+
+ /// Holds weak refs so a destroyed window is silently skipped until the
+ /// explicit unregister call cleans up the slot.
+ QList<QPointer<MainWindow>> windows_;
+};
+
+} // namespace fincept
diff --git a/fincept-qt/src/core/session/SessionManager.cpp b/fincept-qt/src/core/session/SessionManager.cpp
index c4316e7cc..3e58529e8 100644
--- a/fincept-qt/src/core/session/SessionManager.cpp
+++ b/fincept-qt/src/core/session/SessionManager.cpp
@@ -104,6 +104,16 @@ QString SessionManager::load_screen_name(int window_id) const {
return settings_.value(prefix + "screen_name").toString();
}
+void SessionManager::save_window_flag(int window_id, const QString& name, bool value) {
+ const QString key = QString("window_%1/flags/%2").arg(window_id).arg(name);
+ settings_.setValue(key, value);
+}
+
+bool SessionManager::load_window_flag(int window_id, const QString& name, bool default_value) const {
+ const QString key = QString("window_%1/flags/%2").arg(window_id).arg(name);
+ return settings_.value(key, default_value).toBool();
+}
+
void SessionManager::save_dock_layout(int window_id, const QByteArray& layout) {
const QString prefix = QString("window_%1/").arg(window_id);
settings_.setValue(prefix + "dock_layout", layout);
diff --git a/fincept-qt/src/core/session/SessionManager.h b/fincept-qt/src/core/session/SessionManager.h
index 8dc8eafef..92d6e4ee8 100644
--- a/fincept-qt/src/core/session/SessionManager.h
+++ b/fincept-qt/src/core/session/SessionManager.h
@@ -43,6 +43,11 @@ class SessionManager : public QObject {
void save_screen_name(int window_id, const QString& screen_name);
QString load_screen_name(int window_id) const;
+ // Per-window boolean flags — used by always-on-top and similar window
+ // state toggles. Namespaced under window_<id>/flags/<name>.
+ void save_window_flag(int window_id, const QString& name, bool value);
+ bool load_window_flag(int window_id, const QString& name, bool default_value = false) const;
+
// ADS dock layout — scoped per window_id
void save_dock_layout(int window_id, const QByteArray& layout);
QByteArray load_dock_layout(int window_id) const;
diff --git a/fincept-qt/src/core/symbol/IGroupLinked.h b/fincept-qt/src/core/symbol/IGroupLinked.h
new file mode 100644
index 000000000..fc68a2ff7
--- /dev/null
+++ b/fincept-qt/src/core/symbol/IGroupLinked.h
@@ -0,0 +1,44 @@
+#pragma once
+#include "core/symbol/SymbolGroup.h"
+#include "core/symbol/SymbolRef.h"
+
+#include <QtPlugin>
+
+namespace fincept {
+
+/// Mix-in interface implemented by any screen that participates in symbol
+/// group linking (Bloomberg Launchpad "Security Groups" equivalent).
+///
+/// A screen can be a publisher, a subscriber, or both:
+/// - Publishers: when the user changes the active symbol inside the
+/// screen, call SymbolContext::set_group_symbol(group(), ref, this)
+/// so other panels in the same group follow.
+/// - Subscribers: override on_group_symbol_changed() to react to a new
+/// symbol published by any other panel in the same group.
+///
+/// `set_group(None)` unlinks the screen — no traffic in either direction.
+///
+/// Implementations inherit this alongside QWidget; DockScreenRouter
+/// qobject_casts each registered widget to IGroupLinked to decide whether
+/// to attach a GroupBadge to its dock title.
+class IGroupLinked {
+ public:
+ virtual ~IGroupLinked() = default;
+
+ virtual void set_group(SymbolGroup g) = 0;
+ virtual SymbolGroup group() const = 0;
+
+ /// Called by DockScreenRouter when any publisher (including this one,
+ /// unless it filters itself out via the `source` arg of SymbolContext)
+ /// changes the group symbol. Implementations should update their UI
+ /// without re-publishing to avoid feedback loops.
+ virtual void on_group_symbol_changed(const SymbolRef& ref) = 0;
+
+ /// The screen's current symbol, for one-shot "load group from me" flows.
+ /// Return an invalid SymbolRef if the screen has nothing selected yet.
+ virtual SymbolRef current_symbol() const = 0;
+};
+
+} // namespace fincept
+
+Q_DECLARE_INTERFACE(fincept::IGroupLinked, "in.fincept.IGroupLinked/1.0")
diff --git a/fincept-qt/src/core/symbol/SymbolContext.cpp b/fincept-qt/src/core/symbol/SymbolContext.cpp
new file mode 100644
index 000000000..b143b8956
--- /dev/null
+++ b/fincept-qt/src/core/symbol/SymbolContext.cpp
@@ -0,0 +1,93 @@
+#include "core/symbol/SymbolContext.h"
+
+#include "core/logging/Logger.h"
+
+#include <QJsonObject>
+
+namespace fincept {
+
+SymbolContext& SymbolContext::instance() {
+ static SymbolContext s;
+ return s;
+}
+
+SymbolContext::SymbolContext() = default;
+
+SymbolRef SymbolContext::group_symbol(SymbolGroup g) const {
+ if (g == SymbolGroup::None)
+ return {};
+ return groups_.value(g);
+}
+
+bool SymbolContext::has_group_symbol(SymbolGroup g) const {
+ return g != SymbolGroup::None && groups_.contains(g) && groups_[g].is_valid();
+}
+
+void SymbolContext::set_group_symbol(SymbolGroup g, const SymbolRef& ref, QObject* source) {
+ // Update the "active anywhere" symbol regardless of group — this drives
+ // the breadcrumb/titlebar even for unlinked panels.
+ if (ref.is_valid() && ref != active_) {
+ active_ = ref;
+ emit active_symbol_changed(active_, source);
+ }
+
+ if (g == SymbolGroup::None)
+ return;
+
+ const SymbolRef prev = groups_.value(g);
+ if (prev == ref)
+ return; // no-op
+
+ groups_[g] = ref;
+ LOG_DEBUG("SymbolContext",
+ QString("Group %1 → %2").arg(symbol_group_letter(g)).arg(ref.display()));
+ emit group_symbol_changed(g, ref, source);
+}
+
+void SymbolContext::clear() {
+ if (groups_.isEmpty() && !active_.is_valid())
+ return;
+ groups_.clear();
+ active_ = {};
+ for (SymbolGroup g : all_symbol_groups())
+ emit group_symbol_changed(g, SymbolRef{}, nullptr);
+ emit active_symbol_changed(SymbolRef{}, nullptr);
+}
+
+QJsonObject SymbolContext::to_json() const {
+ QJsonObject o;
+ QJsonObject grp;
+ for (auto it = groups_.begin(); it != groups_.end(); ++it) {
+ if (!it.value().is_valid())
+ continue;
+ grp[QString(symbol_group_letter(it.key()))] = it.value().to_json();
+ }
+ o["groups"] = grp;
+ if (active_.is_valid())
+ o["active"] = active_.to_json();
+ return o;
+}
+
+void SymbolContext::from_json(const QJsonObject& o) {
+ clear();
+ const QJsonObject grp = o.value("groups").toObject();
+ for (auto it = grp.begin(); it != grp.end(); ++it) {
+ if (it.key().isEmpty())
+ continue;
+ const SymbolGroup g = symbol_group_from_char(it.key().at(0));
+ if (g == SymbolGroup::None)
+ continue;
+ const SymbolRef ref = SymbolRef::from_json(it.value().toObject());
+ if (ref.is_valid()) {
+ groups_[g] = ref;
+ emit group_symbol_changed(g, ref, nullptr);
+ }
+ }
+ if (o.contains("active")) {
+ active_ = SymbolRef::from_json(o.value("active").toObject());
+ if (active_.is_valid())
+ emit active_symbol_changed(active_, nullptr);
+ }
+}
+
+} // namespace fincept
diff --git a/fincept-qt/src/core/symbol/SymbolContext.h b/fincept-qt/src/core/symbol/SymbolContext.h
new file mode 100644
index 000000000..771033fea
--- /dev/null
+++ b/fincept-qt/src/core/symbol/SymbolContext.h
@@ -0,0 +1,60 @@
+#pragma once
+#include "core/symbol/SymbolGroup.h"
+#include "core/symbol/SymbolRef.h"
+
+#include <QHash>
+#include <QJsonObject>
+#include <QObject>
+#include <QString>
+
+namespace fincept {
+
+/// Singleton service holding the "active security" for each symbol group
+/// (Bloomberg Launchpad equivalent). Panels published via IGroupLinked
+/// listen to group_symbol_changed and update themselves in lockstep.
+///
+/// The `source` parameter on set_group_symbol() carries the QObject that
+/// originated the change; subscribers can compare against `this` to
+/// suppress their own re-publish and avoid feedback loops.
+///
+/// Lifetime: process-global. State persists per workspace via to_json() /
+/// from_json() — WorkspaceManager serialises the blob into the workspace
+/// file so the user's group→symbol assignments come back when the
+/// workspace is reloaded.
+class SymbolContext : public QObject {
+ Q_OBJECT
+ public:
+ static SymbolContext& instance();
+
+ SymbolRef group_symbol(SymbolGroup g) const;
+ bool has_group_symbol(SymbolGroup g) const;
+
+ /// Set the active symbol for a group. Emits group_symbol_changed and
+ /// active_symbol_changed. If `ref` matches the existing value the
+ /// signals are suppressed (no-op writes don't trigger UI churn).
+ void set_group_symbol(SymbolGroup g, const SymbolRef& ref, QObject* source = nullptr);
+
+ /// The most recently touched symbol anywhere in the app (group or not).
+ SymbolRef active() const { return active_; }
+
+ /// Reset everything to empty. Called when a fresh workspace is loaded
+ /// that has no saved group state.
+ void clear();
+
+ QJsonObject to_json() const;
+ void from_json(const QJsonObject& o);
+
+ signals:
+ /// `source` is whatever QObject* the caller passed into set_group_symbol;
+ /// may be nullptr. Subscribers that are also publishers should compare
+ /// `source == this` and skip re-publishing.
+ void group_symbol_changed(fincept::SymbolGroup g, fincept::SymbolRef ref, QObject* source);
+ void active_symbol_changed(fincept::SymbolRef ref, QObject* source);
+
+ private:
+ SymbolContext();
+ QHash<SymbolGroup, SymbolRef> groups_;
+ SymbolRef active_;
+};
+
+} // namespace fincept
diff --git a/fincept-qt/src/core/symbol/SymbolDragSource.cpp b/fincept-qt/src/core/symbol/SymbolDragSource.cpp
new file mode 100644
index 000000000..edeafa927
--- /dev/null
+++ b/fincept-qt/src/core/symbol/SymbolDragSource.cpp
@@ -0,0 +1,159 @@
+#include "core/symbol/SymbolDragSource.h"
+
+#include "core/symbol/SymbolMime.h"
+
+#include <QApplication>
+#include <QDrag>
+#include <QDragEnterEvent>
+#include <QDropEvent>
+#include <QFont>
+#include <QFontMetrics>
+#include <QMimeData>
+#include <QMouseEvent>
+#include <QPainter>
+#include <QPainterPath>
+#include <QPixmap>
+#include <QWidget>
+
+namespace fincept::symbol_dnd {
+
+static QPixmap make_drag_pixmap(const SymbolRef& ref) {
+ // Amber pill with the ticker. Small enough not to block the drop target.
+ QFont font;
+ font.setBold(true);
+ font.setPointSize(10);
+ QFontMetrics fm(font);
+ const QString text = ref.symbol;
+ const int text_w = fm.horizontalAdvance(text);
+ const int w = text_w + 20;
+ const int h = fm.height() + 10;
+
+ // High-DPI: draw at devicePixelRatio so the pill doesn't look blurry on
+ // mixed-DPI setups.
+ const qreal dpr = qApp ? qApp->devicePixelRatio() : 1.0;
+ QPixmap pm(static_cast<int>(w * dpr), static_cast<int>(h * dpr));
+ pm.setDevicePixelRatio(dpr);
+ pm.fill(Qt::transparent);
+
+ QPainter p(&pm);
+ p.setRenderHint(QPainter::Antialiasing, true);
+ QPainterPath path;
+ path.addRoundedRect(QRectF(0, 0, w, h), h / 2.0, h / 2.0);
+ p.fillPath(path, QColor("#d97706")); // amber
+ p.setPen(Qt::white);
+ p.setFont(font);
+ p.drawText(QRectF(0, 0, w, h), Qt::AlignCenter, text);
+ p.end();
+ return pm;
+}
+
+void startSymbolDrag(QWidget* source, const SymbolRef& ref, SymbolGroup source_group) {
+ if (!source || !ref.is_valid())
+ return;
+ auto* drag = new QDrag(source);
+ drag->setMimeData(symbol_mime::pack(ref, source_group));
+ const QPixmap pm = make_drag_pixmap(ref);
+ drag->setPixmap(pm);
+ drag->setHotSpot(QPoint(pm.width() / (2 * static_cast<int>(pm.devicePixelRatio() > 0 ? pm.devicePixelRatio() : 1)),
+ pm.height() / (2 * static_cast<int>(pm.devicePixelRatio() > 0 ? pm.devicePixelRatio() : 1))));
+ drag->exec(Qt::CopyAction, Qt::CopyAction);
+}
+
+SymbolDropFilter::SymbolDropFilter(QWidget* target, Handler handler)
+ : QObject(target), handler_(std::move(handler)) {}
+
+bool SymbolDropFilter::eventFilter(QObject* watched, QEvent* event) {
+ switch (event->type()) {
+ case QEvent::DragEnter: {
+ auto* e = static_cast<QDragEnterEvent*>(event);
+ if (symbol_mime::has_symbol(e->mimeData())) {
+ e->acceptProposedAction();
+ return true;
+ }
+ return false;
+ }
+ case QEvent::DragMove: {
+ auto* e = static_cast<QDragMoveEvent*>(event);
+ if (symbol_mime::has_symbol(e->mimeData())) {
+ e->acceptProposedAction();
+ return true;
+ }
+ return false;
+ }
+ case QEvent::Drop: {
+ auto* e = static_cast<QDropEvent*>(event);
+ if (!symbol_mime::has_symbol(e->mimeData()))
+ return false;
+ const SymbolRef ref = symbol_mime::unpack(e->mimeData());
+ const SymbolGroup src = symbol_mime::unpack_source_group(e->mimeData());
+ e->acceptProposedAction();
+ if (ref.is_valid() && handler_)
+ handler_(ref, src);
+ return true;
+ }
+ default:
+ return QObject::eventFilter(watched, event);
+ }
+}
+
+SymbolDropFilter* installDropFilter(QWidget* target, SymbolDropFilter::Handler handler) {
+ if (!target)
+ return nullptr;
+ target->setAcceptDrops(true);
+ auto* f = new SymbolDropFilter(target, std::move(handler));
+ target->installEventFilter(f);
+ return f;
+}
+
+// ── SymbolDragFilter ─────────────────────────────────────────────────────────
+
+SymbolDragFilter::SymbolDragFilter(QWidget* source, RefProvider provider, SymbolGroup source_group)
+ : QObject(source), source_(source), provider_(std::move(provider)), source_group_(source_group) {}
+
+bool SymbolDragFilter::eventFilter(QObject* /*watched*/, QEvent* event) {
+ switch (event->type()) {
+ case QEvent::MouseButtonPress: {
+ auto* me = static_cast<QMouseEvent*>(event);
+ if (me->button() == Qt::LeftButton) {
+ press_pos_ = me->pos();
+ pressed_ = true;
+ }
+ return false;
+ }
+ case QEvent::MouseMove: {
+ if (!pressed_)
+ return false;
+ auto* me = static_cast<QMouseEvent*>(event);
+ if (!(me->buttons() & Qt::LeftButton)) {
+ pressed_ = false;
+ return false;
+ }
+ if ((me->pos() - press_pos_).manhattanLength() < QApplication::startDragDistance())
+ return false;
+ pressed_ = false;
+ if (!provider_)
+ return false;
+ const SymbolRef ref = provider_();
+ if (!ref.is_valid())
+ return false;
+ startSymbolDrag(source_, ref, source_group_);
+ return true;
+ }
+ case QEvent::MouseButtonRelease:
+ pressed_ = false;
+ return false;
+ default:
+ return false;
+ }
+}
+
+SymbolDragFilter* installDragSource(QWidget* source, SymbolDragFilter::RefProvider provider,
+ SymbolGroup source_group) {
+ if (!source)
+ return nullptr;
+ auto* f = new SymbolDragFilter(source, std::move(provider), source_group);
+ source->installEventFilter(f);
+ return f;
+}
+
+} // namespace fincept::symbol_dnd
diff --git a/fincept-qt/src/core/symbol/SymbolDragSource.h b/fincept-qt/src/core/symbol/SymbolDragSource.h
new file mode 100644
index 000000000..ee45419fb
--- /dev/null
+++ b/fincept-qt/src/core/symbol/SymbolDragSource.h
@@ -0,0 +1,87 @@
+#pragma once
+#include "core/symbol/SymbolGroup.h"
+#include "core/symbol/SymbolRef.h"
+
+#include <QObject>
+#include <functional>
+
+class QWidget;
+class QDropEvent;
+class QDragEnterEvent;
+class QMouseEvent;
+
+namespace fincept::symbol_dnd {
+
+/// Start a QDrag carrying the given SymbolRef. Intended to be called from
+/// a mouseMoveEvent (with the left button held) once the user drags past
+/// QApplication::startDragDistance. Non-blocking — spawns the drag loop
+/// and returns when the drop completes.
+///
+/// The drag pixmap is a small amber pill showing the ticker (Bloomberg
+/// convention for "security in flight").
+void startSymbolDrag(QWidget* source, const SymbolRef& ref,
+ SymbolGroup source_group = SymbolGroup::None);
+
+/// Event filter that converts drops of application/x-fincept-symbol into
+/// a callback receiving the unpacked SymbolRef. Install on any QWidget
+/// you want to make a drop target.
+///
+/// The widget must have setAcceptDrops(true) set by the caller — this
+/// filter only handles the two events, not the attribute.
+class SymbolDropFilter : public QObject {
+ Q_OBJECT
+ public:
+ using Handler = std::function<void(const SymbolRef& ref, SymbolGroup source_group)>;
+
+ SymbolDropFilter(QWidget* target, Handler handler);
+
+ protected:
+ bool eventFilter(QObject* watched, QEvent* event) override;
+
+ private:
+ Handler handler_;
+};
+
+/// Convenience: install a drop filter on `target` and call `setAcceptDrops(true)`.
+/// Returns the created filter (owned by `target` as parent).
+SymbolDropFilter* installDropFilter(QWidget* target, SymbolDropFilter::Handler handler);
+
+/// Event filter that watches mouse events on a widget and starts a symbol
+/// drag whenever the user holds left-button and moves past the system drag
+/// threshold. The `ref_provider` callback is invoked at drag-start time to
+/// fetch the current SymbolRef (needed for widgets where the symbol changes
+/// — watchlist rows, dynamic title labels). Returns an invalid ref to cancel.
+///
+/// Typical use:
+/// symbol_dnd::installDragSource(my_label,
+/// []() { return SymbolRef::equity("AAPL"); });
+///
+/// The filter is parented to `source` so it's destroyed with the widget.
+class SymbolDragFilter : public QObject {
+ Q_OBJECT
+ public:
+ using RefProvider = std::function<SymbolRef()>;
+
+ SymbolDragFilter(QWidget* source, RefProvider provider,
+ SymbolGroup source_group = SymbolGroup::None);
+
+ /// The group embedded in the drag is read lazily at drag-start via this
+ /// setter — set to follow the screen's current link group.
+ void set_source_group(SymbolGroup g) { source_group_ = g; }
+
+ protected:
+ bool eventFilter(QObject* watched, QEvent* event) override;
+
+ private:
+ QWidget* source_;
+ RefProvider provider_;
+ SymbolGroup source_group_;
+ QPoint press_pos_;
+ bool pressed_ = false;
+};
+
+/// Convenience: create+install a SymbolDragFilter on `source`.
+SymbolDragFilter* installDragSource(QWidget* source, SymbolDragFilter::RefProvider provider,
+ SymbolGroup source_group = SymbolGroup::None);
+
+} // namespace fincept::symbol_dnd
diff --git a/fincept-qt/src/core/symbol/SymbolGroup.h b/fincept-qt/src/core/symbol/SymbolGroup.h
new file mode 100644
index 000000000..742e51311
--- /dev/null
+++ b/fincept-qt/src/core/symbol/SymbolGroup.h
@@ -0,0 +1,69 @@
+#pragma once
+#include <QChar>
+#include <QList>
+#include <QMetaType>
+#include <QString>
+
+namespace fincept {
+
+/// Symbol link groups (Bloomberg Launchpad "Security Groups" equivalent).
+/// A panel can be assigned to a group; all panels in the same group share
+/// the same "active security" and update in lockstep when any member panel
+/// publishes a symbol change.
+///
+/// `None` = unlinked; the panel ignores group traffic and publishes nothing.
+/// A–F = six colour-coded groups (Amber, Cyan, Magenta, Green, Purple, Red).
+///
+/// Stored as a single byte so it can live inside QSettings and JSON without
+/// ambiguity. Do NOT renumber — persisted workspaces reference these literals.
+enum class SymbolGroup : char {
+ None = '\0',
+ A = 'A',
+ B = 'B',
+ C = 'C',
+ D = 'D',
+ E = 'E',
+ F = 'F',
+};
+
+/// Returns all concrete groups in order (A..F); excludes None.
+inline const QList<SymbolGroup>& all_symbol_groups() {
+ static const QList<SymbolGroup> k = {SymbolGroup::A, SymbolGroup::B, SymbolGroup::C,
+ SymbolGroup::D, SymbolGroup::E, SymbolGroup::F};
+ return k;
+}
+
+inline QChar symbol_group_letter(SymbolGroup g) {
+ return g == SymbolGroup::None ? QChar(' ') : QChar(static_cast<char>(g));
+}
+
+inline SymbolGroup symbol_group_from_char(QChar c) {
+ const char ch = c.toLatin1();
+ switch (ch) {
+ case 'A': return SymbolGroup::A;
+ case 'B': return SymbolGroup::B;
+ case 'C': return SymbolGroup::C;
+ case 'D': return SymbolGroup::D;
+ case 'E': return SymbolGroup::E;
+ case 'F': return SymbolGroup::F;
+ default: return SymbolGroup::None;
+ }
+}
+
+/// Cycle forward: None → A → B → … → F → None.
+inline SymbolGroup next_symbol_group(SymbolGroup g) {
+ switch (g) {
+ case SymbolGroup::None: return SymbolGroup::A;
+ case SymbolGroup::A: return SymbolGroup::B;
+ case SymbolGroup::B: return SymbolGroup::C;
+ case SymbolGroup::C: return SymbolGroup::D;
+ case SymbolGroup::D: return SymbolGroup::E;
+ case SymbolGroup::E: return SymbolGroup::F;
+ case SymbolGroup::F: return SymbolGroup::None;
+ }
+ return SymbolGroup::None;
+}
+
+} // namespace fincept
+
+Q_DECLARE_METATYPE(fincept::SymbolGroup)
diff --git a/fincept-qt/src/core/symbol/SymbolMime.cpp b/fincept-qt/src/core/symbol/SymbolMime.cpp
new file mode 100644
index 000000000..a2ed5e100
--- /dev/null
+++ b/fincept-qt/src/core/symbol/SymbolMime.cpp
@@ -0,0 +1,46 @@
+#include "core/symbol/SymbolMime.h"
+
+#include <QJsonDocument>
+#include <QJsonObject>
+
+namespace fincept::symbol_mime {
+
+QMimeData* pack(const SymbolRef& ref, SymbolGroup source_group) {
+ QJsonObject o = ref.to_json();
+ if (source_group != SymbolGroup::None)
+ o["source_group"] = QString(symbol_group_letter(source_group));
+ auto* m = new QMimeData;
+ m->setData(kMimeType, QJsonDocument(o).toJson(QJsonDocument::Compact));
+ // Also set plain text so the drag can be dropped into generic text fields
+ // (Excel, chat boxes, external apps) — the symbol alone is the useful bit.
+ m->setText(ref.symbol);
+ return m;
+}
+
+SymbolRef unpack(const QMimeData* mime) {
+ if (!mime || !mime->hasFormat(kMimeType))
+ return {};
+ const QByteArray blob = mime->data(kMimeType);
+ const QJsonDocument doc = QJsonDocument::fromJson(blob);
+ if (!doc.isObject())
+ return {};
+ return SymbolRef::from_json(doc.object());
+}
+
+SymbolGroup unpack_source_group(const QMimeData* mime) {
+ if (!mime || !mime->hasFormat(kMimeType))
+ return SymbolGroup::None;
+ const QJsonDocument doc = QJsonDocument::fromJson(mime->data(kMimeType));
+ if (!doc.isObject())
+ return SymbolGroup::None;
+ const QString letter = doc.object().value("source_group").toString();
+ if (letter.isEmpty())
+ return SymbolGroup::None;
+ return symbol_group_from_char(letter.at(0));
+}
+
+bool has_symbol(const QMimeData* mime) {
+ return mime && mime->hasFormat(kMimeType);
+}
+
+} // namespace fincept::symbol_mime
diff --git a/fincept-qt/src/core/symbol/SymbolMime.h b/fincept-qt/src/core/symbol/SymbolMime.h
new file mode 100644
index 000000000..573736bed
--- /dev/null
+++ b/fincept-qt/src/core/symbol/SymbolMime.h
@@ -0,0 +1,36 @@
+#pragma once
+#include "core/symbol/SymbolGroup.h"
+#include "core/symbol/SymbolRef.h"
+
+#include <QMimeData>
+#include <QString>
+
+namespace fincept {
+
+/// MIME type used for cross-panel drag/drop of securities. Any panel that
+/// produces a drag of a symbol tags its QMimeData with this type; any panel
+/// that wants to accept a symbol registers it as an accepted type in its
+/// dragEnterEvent. The payload is a UTF-8 JSON blob of SymbolRef plus an
+/// optional `source_group` field so receivers can do things like
+/// "came from Group A — match colour".
+namespace symbol_mime {
+
+inline constexpr const char* kMimeType = "application/x-fincept-symbol";
+
+/// Stuff a SymbolRef into an owned QMimeData. Caller takes ownership of
+/// the returned pointer (or passes it to QDrag::setMimeData, which does).
+QMimeData* pack(const SymbolRef& ref, SymbolGroup source_group = SymbolGroup::None);
+
+/// Returns the SymbolRef embedded in the mime data, or an invalid ref if
+/// the blob is missing or malformed.
+SymbolRef unpack(const QMimeData* mime);
+
+/// Source group encoded alongside the symbol, or SymbolGroup::None.
+SymbolGroup unpack_source_group(const QMimeData* mime);
+
+/// Convenience: does this mime data carry a symbol drag?
+bool has_symbol(const QMimeData* mime);
+
+} // namespace symbol_mime
+
+} // namespace fincept
diff --git a/fincept-qt/src/core/symbol/SymbolRef.h b/fincept-qt/src/core/symbol/SymbolRef.h
new file mode 100644
index 000000000..0bad7ded8
--- /dev/null
+++ b/fincept-qt/src/core/symbol/SymbolRef.h
@@ -0,0 +1,70 @@
+#pragma once
+#include <QJsonObject>
+#include <QMetaType>
+#include <QString>
+
+namespace fincept {
+
+/// Strongly-typed reference to a tradable/observable security. Used as the
+/// payload for cross-panel symbol links (SymbolContext) so that receivers
+/// can disambiguate a ticker across asset classes (e.g. "AAPL" equity vs.
+/// "AAPL" option chain root) without string-munging.
+///
+/// `asset_class` uses lowercased slugs: "equity", "crypto", "fx", "future",
+/// "bond", "index", "commodity", "option". Empty string = unknown; consumers
+/// should treat unknown as equity for backward compatibility with older
+/// single-string symbol flows.
+struct SymbolRef {
+ QString symbol;
+ QString asset_class;
+ QString exchange;
+
+ bool is_valid() const { return !symbol.isEmpty(); }
+
+ /// Bloomberg-style display: "AAPL US Equity", "BTCUSD Binance Crypto",
+ /// falling back to the raw symbol if context is unknown.
+ QString display() const {
+ QString out = symbol;
+ if (!exchange.isEmpty())
+ out += ' ' + exchange;
+ if (!asset_class.isEmpty()) {
+ QString ac = asset_class;
+ if (!ac.isEmpty())
+ ac[0] = ac[0].toUpper();
+ out += ' ' + ac;
+ }
+ return out;
+ }
+
+ bool operator==(const SymbolRef& o) const {
+ return symbol == o.symbol && asset_class == o.asset_class && exchange == o.exchange;
+ }
+ bool operator!=(const SymbolRef& o) const { return !(*this == o); }
+
+ QJsonObject to_json() const {
+ QJsonObject o;
+ o["symbol"] = symbol;
+ o["asset_class"] = asset_class;
+ o["exchange"] = exchange;
+ return o;
+ }
+
+ static SymbolRef from_json(const QJsonObject& o) {
+ SymbolRef r;
+ r.symbol = o.value("symbol").toString();
+ r.asset_class = o.value("asset_class").toString();
+ r.exchange = o.value("exchange").toString();
+ return r;
+ }
+
+ /// Convenience for call sites that only have a ticker string; defaults
+ /// to equity asset class, which matches every existing single-string
+ /// flow in the codebase.
+ static SymbolRef equity(const QString& sym, const QString& exch = {}) {
+ return SymbolRef{sym.toUpper(), QStringLiteral("equity"), exch};
+ }
+};
+
+} // namespace fincept
+
+Q_DECLARE_METATYPE(fincept::SymbolRef)
diff --git a/fincept-qt/src/datahub/DataHub.cpp b/fincept-qt/src/datahub/DataHub.cpp
index b1c8d7d23..d55f1adc7 100644
--- a/fincept-qt/src/datahub/DataHub.cpp
+++ b/fincept-qt/src/datahub/DataHub.cpp
@@ -33,7 +33,28 @@ DataHub::DataHub() {
// measured in seconds.
connect(&scheduler_, &QTimer::timeout, this, &DataHub::scheduler_body);
scheduler_.start();
- LOG_INFO("DataHub", "Initialised (scheduler tick = 1s)");
+
+ // Coalesce timer — single-shot, armed by request(), fires once per window.
+ // Default 100ms so widget burst subscriptions (dashboard + markets both
+ // opening) collapse into one producer->refresh() per producer. Tunable
+ // via set_coalesce_window_ms() — tests commonly use 0 for synchronous
+ // dispatch.
+ coalesce_timer_.setSingleShot(true);
+ coalesce_timer_.setInterval(coalesce_window_ms_);
+ connect(&coalesce_timer_, &QTimer::timeout, this, &DataHub::flush_coalesced_requests);
+
+ LOG_INFO("DataHub", QString("Initialised (scheduler tick = 1s, coalesce window = %1ms)")
+ .arg(coalesce_window_ms_));
+}
+
+void DataHub::set_coalesce_window_ms(int ms) {
+ if (ms < 0) ms = 0;
+ coalesce_window_ms_ = ms;
+ // Apply on the hub thread so the timer's internal state isn't touched
+ // from a foreign thread.
+ QMetaObject::invokeMethod(this, [this, ms]() {
+ coalesce_timer_.setInterval(ms);
+ }, Qt::QueuedConnection);
}
// ── Pattern match ──────────────────────────────────────────────────────────
@@ -73,13 +94,46 @@ DataHub::TopicState& DataHub::state_for(const QString& topic) {
Producer* DataHub::find_producer(const QString& topic) const {
// Caller holds mutex_.
- for (Producer* p : producers_)
- for (const auto& pat : p->topic_patterns())
- if (pattern_matches(pat, topic))
- return p;
+ // Pattern index is sorted by prefix length DESC so the first entry
+ // whose prefix matches is also the most specific (longest-prefix win).
+ for (const auto& e : pattern_index_) {
+ if (e.is_wildcard) {
+ if (topic.size() >= e.prefix.size() &&
+ QStringView{topic}.startsWith(e.prefix))
+ return e.owner;
+ } else {
+ if (topic == e.prefix)
+ return e.owner;
+ }
+ }
return nullptr;
}
+void DataHub::rebuild_pattern_index() {
+ // Caller holds mutex_. Called from register_producer / unregister_producer.
+ pattern_index_.clear();
+ for (Producer* p : producers_) {
+ for (const auto& pat : p->topic_patterns()) {
+ PatternEntry e;
+ e.owner = p;
+ if (pat.endsWith(QLatin1Char('*'))) {
+ e.prefix = pat.left(pat.size() - 1);
+ e.is_wildcard = true;
+ } else {
+ e.prefix = pat;
+ e.is_wildcard = false;
+ }
+ pattern_index_.append(std::move(e));
+ }
+ }
+ // Sort longest prefix first so iteration in find_producer() returns
+ // the most specific match.
+ std::sort(pattern_index_.begin(), pattern_index_.end(),
+ [](const PatternEntry& a, const PatternEntry& b) {
+ return a.prefix.size() > b.prefix.size();
+ });
+}
+
// ── Subscription ───────────────────────────────────────────────────────────
void DataHub::on_owner_destroyed(QObject* owner) {
@@ -98,9 +152,13 @@ void DataHub::on_owner_destroyed(QObject* owner) {
vec.end());
if (vec.isEmpty()) {
subscriptions_.erase(sub_it);
+ // Topic just went idle — drop cached state if policy opted in.
+ // Done under the same lock to keep state coherent.
+ if (auto ts_it = topics_.find(topic);
+ ts_it != topics_.end() && ts_it->policy.drop_on_idle) {
+ topics_.erase(ts_it);
+ }
emit topic_idle(topic);
- if (Producer* p = find_producer(topic))
- p->on_topic_idle(topic);
}
}
owner_topics_.erase(topics_it);
@@ -156,6 +214,7 @@ QMetaObject::Connection DataHub::subscribe(
Q_ASSERT(owner && "subscribe requires a non-null owner for lifetime tracking");
bool became_active = false;
+ bool needs_cold_start_fetch = false;
{
QMutexLocker lock(&mutex_);
Subscription sub;
@@ -169,7 +228,18 @@ QMetaObject::Connection DataHub::subscribe(
owner_topics_[owner].insert(topic);
// Make sure the topic state exists with correct policy.
- state_for(topic);
+ auto& st = state_for(topic);
+
+ // Cold-start fetch: if we have no cached value AND nothing is in flight,
+ // request a forced refresh so the widget gets data on the first scheduler
+ // tick rather than waiting for TTL/min_interval to line up. `push_only`
+ // topics have no producer-side pull, so skip — they only get data via
+ // explicit publish() calls.
+ const bool have_fresh_value = st.value.isValid() && st.last_publish_ms > 0 &&
+ (now_ms() - st.last_publish_ms) < st.policy.ttl_ms;
+ if (!have_fresh_value && !st.in_flight && !st.policy.push_only) {
+ needs_cold_start_fetch = true;
+ }
}
// Auto-cleanup on owner destruction. The QObject::destroyed signal
@@ -183,6 +253,12 @@ QMetaObject::Connection DataHub::subscribe(
emit topic_active(topic);
}
deliver_initial_value(owner, topic, slot);
+
+ // Dispatch the cold-start fetch outside the mutex. force=true bypasses
+ // min_interval_ms but per-producer rate limit still applies.
+ if (needs_cold_start_fetch) {
+ request(topic, /*force=*/true);
+ }
return conn;
}
@@ -190,6 +266,7 @@ QMetaObject::Connection DataHub::subscribe_pattern(
QObject* owner, const QString& pattern,
std::function<void(const QString&, const QVariant&)> slot) {
Q_ASSERT(owner && "subscribe_pattern requires a non-null owner");
+ QStringList cold_start_topics;
{
QMutexLocker lock(&mutex_);
Subscription sub;
@@ -198,10 +275,29 @@ QMetaObject::Connection DataHub::subscribe_pattern(
sub.is_pattern = true;
pattern_subscriptions_[pattern].append(std::move(sub));
owner_patterns_[owner].insert(pattern);
+
+ // Cold-start parity with subscribe(): for every already-known topic
+ // that matches this pattern and has no fresh cached value, queue a
+ // forced refresh. Pattern-only subscribers (e.g. AgentErrorsWidget
+ // listening to `agent:error:*`) otherwise have to wait for TTL
+ // expiry + a scheduler tick before seeing anything.
+ const qint64 t = now_ms();
+ for (auto it = topics_.begin(); it != topics_.end(); ++it) {
+ if (!pattern_matches(pattern, it.key())) continue;
+ if (it->policy.push_only) continue;
+ if (it->in_flight) continue;
+ const bool have_fresh =
+ it->value.isValid() && it->last_publish_ms > 0 &&
+ (t - it->last_publish_ms) < it->policy.ttl_ms;
+ if (!have_fresh) cold_start_topics.append(it.key());
+ }
}
- return connect(owner, &QObject::destroyed, this,
+ auto conn = connect(owner, &QObject::destroyed, this,
[this, owner](QObject*) { on_owner_destroyed(owner); },
Qt::QueuedConnection);
+ if (!cold_start_topics.isEmpty())
+ request(cold_start_topics, /*force=*/true);
+ return conn;
}
void DataHub::unsubscribe(QObject* owner) {
@@ -218,9 +314,11 @@ void DataHub::unsubscribe(QObject* owner, const QString& topic) {
vec.end());
if (vec.isEmpty()) {
subscriptions_.erase(sub_it);
+ if (auto ts_it = topics_.find(topic);
+ ts_it != topics_.end() && ts_it->policy.drop_on_idle) {
+ topics_.erase(ts_it);
+ }
emit topic_idle(topic);
- if (Producer* p = find_producer(topic))
- p->on_topic_idle(topic);
}
if (auto it = owner_topics_.find(owner); it != owner_topics_.end()) {
it.value().remove(topic);
@@ -263,6 +361,7 @@ void DataHub::do_publish(const QString& topic, const QVariant& value,
st.last_publish_ms = now_ms();
st.total_publishes += 1;
st.in_flight = false;
+ st.last_error.clear(); // successful publish clears any stored error
if (ttl_override.count() > 0) {
st.policy.ttl_ms = static_cast<int>(ttl_override.count());
}
@@ -325,19 +424,53 @@ void DataHub::publish(const QString& topic, const QVariant& value,
do_publish(topic, value, ttl);
}
+void DataHub::publish_error(const QString& topic, const QString& error) {
+ if (QThread::currentThread() != this->thread()) {
+ QMetaObject::invokeMethod(this, [this, topic, error]() {
+ publish_error(topic, error);
+ }, Qt::QueuedConnection);
+ return;
+ }
+ {
+ QMutexLocker lock(&mutex_);
+ auto& st = state_for(topic);
+ st.in_flight = false;
+ st.last_error = error;
+ st.last_error_ms = now_ms();
+ st.total_errors += 1;
+ }
+ LOG_WARN("DataHub", QString("publish_error topic='%1' error='%2'").arg(topic).arg(error.left(200)));
+ emit topic_error(topic, error);
+}
+
// ── Producer registration ──────────────────────────────────────────────────
void DataHub::register_producer(Producer* producer) {
Q_ASSERT(producer);
QMutexLocker lock(&mutex_);
- if (!producers_.contains(producer))
+ if (!producers_.contains(producer)) {
producers_.append(producer);
+ rebuild_pattern_index();
+ }
}
void DataHub::unregister_producer(Producer* producer) {
QMutexLocker lock(&mutex_);
producers_.removeAll(producer);
producer_last_refresh_ms_.remove(producer);
+ rebuild_pattern_index();
+ // Drop any pending coalesced refresh requests targeting this producer —
+ // dispatching them after unregister would call refresh() on a dangling
+ // pointer. The topics involved have their `in_flight` flag cleared so
+ // the next find_producer() on the scheduler pass routes them to a new
+ // owner (if one registers) or leaves them alone.
+ if (auto it = coalesce_pending_.find(producer); it != coalesce_pending_.end()) {
+ for (const QString& topic : it.value()) {
+ if (auto ts_it = topics_.find(topic); ts_it != topics_.end())
+ ts_it->in_flight = false;
+ }
+ coalesce_pending_.erase(it);
+ }
}
void DataHub::set_policy(const QString& topic, const TopicPolicy& policy) {
@@ -358,9 +491,38 @@ void DataHub::set_policy_pattern(const QString& pattern, const TopicPolicy& poli
}
}
+int DataHub::clear_policy_pattern(const QString& pattern) {
+ QMutexLocker lock(&mutex_);
+ int removed = 0;
+ for (auto it = pattern_policies_.begin(); it != pattern_policies_.end(); ) {
+ if (it->first == pattern) {
+ it = pattern_policies_.erase(it);
+ ++removed;
+ } else {
+ ++it;
+ }
+ }
+ return removed;
+}
+
// ── Pull-through ───────────────────────────────────────────────────────────
QVariant DataHub::peek(const QString& topic) const {
+ QMutexLocker lock(&mutex_);
+ auto it = topics_.find(topic);
+ if (it == topics_.end() || !it->value.isValid())
+ return {};
+ // Push-only topics don't age — always return last published value.
+ if (it->policy.push_only)
+ return it->value;
+ if (it->last_publish_ms <= 0)
+ return {};
+ if ((now_ms() - it->last_publish_ms) >= it->policy.ttl_ms)
+ return {}; // stale
+ return it->value;
+}
+
+QVariant DataHub::peek_raw(const QString& topic) const {
QMutexLocker lock(&mutex_);
auto it = topics_.find(topic);
return it == topics_.end() ? QVariant{} : it->value;
@@ -371,14 +533,20 @@ void DataHub::request(const QString& topic, bool force) {
}
void DataHub::request(const QStringList& topics, bool force) {
- // Group topics by owning producer under the lock, then call outside.
+ // Apply gates under the lock, then buffer into coalesce_pending_. The
+ // coalesce timer (kCoalesceWindowMs) merges bursts of request() calls —
+ // e.g., dashboard + markets subscribing simultaneously — into one
+ // producer->refresh() per producer.
//
- // Gates applied here:
+ // Gates applied here (same as before — gating is at buffer time, not
+ // flush time, because in_flight/min_interval reflect intent to fetch):
// - in_flight: always skip; the producer is already working.
// - min_interval_ms: skipped when `force=true` (user-driven refresh).
// - max_requests_per_sec: always honoured — force doesn't open the
// rate-limit floodgate.
- QHash<Producer*, QStringList> by_producer;
+ int accepted = 0;
+ bool need_arm = false;
+ QStringList orphan_topics;
{
QMutexLocker lock(&mutex_);
const qint64 t = now_ms();
@@ -391,7 +559,10 @@ void DataHub::request(const QStringList& topics, bool force) {
continue;
}
Producer* p = find_producer(topic);
- if (!p) continue;
+ if (!p) {
+ orphan_topics.append(topic);
+ continue;
+ }
const int rps = p->max_requests_per_sec();
if (rps > 0) {
const qint64 last = producer_last_refresh_ms_.value(p, 0);
@@ -401,11 +572,59 @@ void DataHub::request(const QStringList& topics, bool force) {
st.in_flight = true;
st.last_refresh_request_ms = t;
producer_last_refresh_ms_[p] = t;
- by_producer[p].append(topic);
+ // Buffer instead of dispatching — duplicate topics within the
+ // window are naturally prevented by the in_flight gate above.
+ coalesce_pending_[p].append(topic);
+ ++accepted;
}
+ need_arm = accepted > 0;
+ }
+
+ if (!orphan_topics.isEmpty()) {
+ // Topic requested by a consumer but no producer claims a matching
+ // pattern. This is almost always a typo in the topic string or a
+ // missing ensure_registered_with_hub() call — log once per request
+ // so the miss surfaces during development.
+ LOG_WARN("DataHub",
+ QString("request(): %1 topic(s) have no producer — likely unregistered "
+ "service or typo. First few: %2")
+ .arg(orphan_topics.size())
+ .arg(orphan_topics.mid(0, 3).join(QStringLiteral(", "))));
+ }
+ if (need_arm) {
+ // The coalesce timer lives on the hub thread; arming from another
+ // thread requires a queued call. isSingleShot + not-active means
+ // restart resets the window, which is the behaviour we want: a
+ // second request() inside the window extends coalescing, it
+ // doesn't flush early.
+ QMetaObject::invokeMethod(this, [this]() {
+ if (!coalesce_timer_.isActive())
+ coalesce_timer_.start();
+ }, Qt::QueuedConnection);
+ }
+}
+
+void DataHub::flush_coalesced_requests() {
+ QHash<Producer*, QStringList> work;
+ {
+ QMutexLocker lock(&mutex_);
+ work.swap(coalesce_pending_);
}
- for (auto it = by_producer.begin(); it != by_producer.end(); ++it)
+ if (work.isEmpty())
+ return;
+
+ int total = 0;
+ for (auto it = work.begin(); it != work.end(); ++it) {
+ total += it.value().size();
+ LOG_DEBUG("DataHub", QString("coalesce flush: producer=%1 topics=%2")
+ .arg(reinterpret_cast<quintptr>(it.key()), 0, 16)
+ .arg(it.value().size()));
it.key()->refresh(it.value());
+ }
+ if (total > 0) {
+ LOG_DEBUG("DataHub", QString("coalesce flushed %1 topics across %2 producers")
+ .arg(total).arg(work.size()));
+ }
}
// ── Scheduler ──────────────────────────────────────────────────────────────
@@ -414,10 +633,34 @@ void DataHub::scheduler_body() {
// One pass: collect refresh work per producer, respecting TTL, min
// interval, in-flight, and per-producer rate limits.
QHash<Producer*, QStringList> work;
+ QStringList timed_out_topics;
{
QMutexLocker lock(&mutex_);
const qint64 t = now_ms();
+ // Pre-pass: clear `in_flight` on topics whose producer missed the
+ // refresh_timeout_ms window. Without this a crashed / hung producer
+ // pins the topic forever and subscribers never see fresh data.
+ for (auto it = topics_.begin(); it != topics_.end(); ++it) {
+ if (!it->in_flight) continue;
+ if (it->policy.refresh_timeout_ms <= 0) continue;
+ if (it->last_refresh_request_ms <= 0) continue;
+ if ((t - it->last_refresh_request_ms) >= it->policy.refresh_timeout_ms) {
+ it->in_flight = false;
+ timed_out_topics.append(it.key());
+ }
+ }
+
+ // Drop empty subscription buckets left behind by unsubscribe churn.
+ // The scheduler would otherwise skip them forever while still paying
+ // the hash iteration cost on every tick.
+ for (auto it = subscriptions_.begin(); it != subscriptions_.end(); ) {
+ if (it.value().isEmpty())
+ it = subscriptions_.erase(it);
+ else
+ ++it;
+ }
+
for (auto it = subscriptions_.begin(); it != subscriptions_.end(); ++it) {
const QString& topic = it.key();
if (it.value().isEmpty()) continue;
@@ -452,6 +695,13 @@ void DataHub::scheduler_body() {
}
}
+ for (const QString& topic : timed_out_topics) {
+ LOG_WARN("DataHub", QString("Producer refresh timed out for topic '%1' — clearing in_flight. "
+ "The producer failed to publish() or publish_error() within "
+ "refresh_timeout_ms; hub will retry on the next scheduler pass.").arg(topic));
+ emit topic_error(topic, QStringLiteral("refresh_timeout"));
+ }
+
for (auto it = work.begin(); it != work.end(); ++it) {
LOG_DEBUG("DataHub", QString("refresh(): producer=%1 topics=%2")
.arg(reinterpret_cast<quintptr>(it.key()), 0, 16)
@@ -480,9 +730,12 @@ QVector<TopicStats> DataHub::stats() const {
s.topic = it.key();
s.last_publish_ms = it->last_publish_ms;
s.last_refresh_request_ms = it->last_refresh_request_ms;
+ s.last_error_ms = it->last_error_ms;
s.total_publishes = it->total_publishes;
+ s.total_errors = it->total_errors;
s.in_flight = it->in_flight;
s.push_only = it->policy.push_only;
+ s.last_error = it->last_error;
if (auto sub_it = subscriptions_.find(it.key()); sub_it != subscriptions_.end())
s.subscriber_count = sub_it.value().size();
out.append(std::move(s));
@@ -492,4 +745,16 @@ QVector<TopicStats> DataHub::stats() const {
return out;
}
+QList<QObject*> DataHub::subscribers(const QString& topic) const {
+ QMutexLocker lock(&mutex_);
+ QList<QObject*> out;
+ auto it = subscriptions_.find(topic);
+ if (it == subscriptions_.end()) return out;
+ out.reserve(it.value().size());
+ for (const auto& s : it.value()) {
+ if (s.owner) out.append(s.owner.data());
+ }
+ return out;
+}
+
} // namespace fincept::datahub
diff --git a/fincept-qt/src/datahub/DataHub.h b/fincept-qt/src/datahub/DataHub.h
index bc5e35683..2d3526461 100644
--- a/fincept-qt/src/datahub/DataHub.h
+++ b/fincept-qt/src/datahub/DataHub.h
@@ -28,9 +28,12 @@ struct TopicStats {
int subscriber_count = 0;
qint64 last_publish_ms = 0; ///< QDateTime::currentMSecsSinceEpoch at last publish
qint64 last_refresh_request_ms = 0; ///< last time scheduler asked producer to refresh
+ qint64 last_error_ms = 0; ///< last time a refresh error was reported (0 = never)
int total_publishes = 0;
+ int total_errors = 0;
bool in_flight = false; ///< producer has an outstanding refresh()
bool push_only = false;
+ QString last_error; ///< most recent error string, empty if none or cleared
};
/// In-process pub/sub data layer. See DATAHUB_ARCHITECTURE.md §4.
@@ -92,6 +95,13 @@ class DataHub : public QObject {
void publish(const QString& topic, const QVariant& value,
std::chrono::milliseconds ttl);
+ /// Signal that a refresh() for `topic` has failed. Clears the
+ /// `in_flight` flag so the scheduler can retry on the next pass and
+ /// emits `topic_error(topic, error)` so subscribers can surface the
+ /// failure in the UI. Does NOT update the cached value — last-known-
+ /// good stays visible. Thread-safe; marshals to the hub thread.
+ void publish_error(const QString& topic, const QString& error);
+
// ── Registration ────────────────────────────────────────────────────────
void register_producer(Producer* producer);
@@ -99,14 +109,29 @@ class DataHub : public QObject {
void set_policy(const QString& topic, const TopicPolicy& policy);
void set_policy_pattern(const QString& pattern, const TopicPolicy& policy);
+ /// Remove a previously-registered pattern policy. Existing TopicState
+ /// entries that inherited the policy keep their current copy — to
+ /// apply a new policy, call `set_policy_pattern()` after clearing.
+ /// Returns the number of pattern entries removed (0 if not present).
+ int clear_policy_pattern(const QString& pattern);
// ── Pull-through ────────────────────────────────────────────────────────
/// Read the current cached value without subscribing. Returns an
- /// invalid `QVariant` if the topic is unknown or unset. Does NOT
- /// trigger a fetch.
+ /// invalid `QVariant` if the topic is unknown, unset, or the cached
+ /// value has aged past its `ttl_ms`. Push-only topics ignore TTL and
+ /// always return the last published value. Does NOT trigger a fetch.
+ ///
+ /// Use `peek_raw()` if you want the last-known-good value regardless
+ /// of TTL (diagnostic / stats / report-builder fallbacks).
QVariant peek(const QString& topic) const;
+ /// Read the cached value without TTL check. Intended for diagnostic
+ /// callers (DataHubTools MCP tool, stats inspector) and for fallbacks
+ /// that prefer stale data over a blank screen. Returns an invalid
+ /// QVariant if the topic has no cached value at all.
+ QVariant peek_raw(const QString& topic) const;
+
/// Ask the hub to refresh `topic` now (subject to policy + rate limit).
/// Subscribers are notified via the usual signal path when the
/// producer publishes. No-op if no producer owns the topic.
@@ -114,7 +139,7 @@ class DataHub : public QObject {
/// `force=true` bypasses `min_interval_ms` (so a user-driven refresh
/// button can refetch even inside the interval gate). Per-producer
/// `max_requests_per_sec()` is still honoured — rage-clicking can't
- /// hammer upstream. Phase 6.
+ /// hammer upstream.
void request(const QString& topic, bool force = false);
void request(const QStringList& topics, bool force = false);
@@ -122,12 +147,18 @@ class DataHub : public QObject {
QVector<TopicStats> stats() const;
+ /// Diagnostic: list the QObject owners currently subscribed to `topic`.
+ /// Pointers are raw (not QPointer) — only safe to use for identity
+ /// comparison, logging, or `QObject::objectName()` lookup on the GUI
+ /// thread while the hub mutex is not held by the caller.
+ /// Returns an empty list if the topic has no subscribers.
+ QList<QObject*> subscribers(const QString& topic) const;
+
/// Drop a topic's cached state entirely (value, publish counters,
/// coalesce state). Subscriptions are preserved — they remain attached
/// and will receive the next publish normally. Used by producers that
/// generate disposable per-run topics (e.g. agent output:<run_id>) to
/// avoid unbounded hub memory growth. No-op if the topic is unknown.
- /// Phase 9.
void retire_topic(const QString& topic);
/// Test hook: drive the scheduler manually. Normally the internal
@@ -135,10 +166,23 @@ class DataHub : public QObject {
/// have to spin the event loop for seconds.
void tick_scheduler();
+ /// Tune the request-coalesce window (default 100ms). Larger windows
+ /// merge more bursts into one producer dispatch at the cost of
+ /// perceived latency on user-initiated requests. Must be >= 0; 0
+ /// disables coalescing entirely (request() dispatches immediately).
+ void set_coalesce_window_ms(int ms);
+ int coalesce_window_ms() const { return coalesce_window_ms_; }
+
signals:
void topic_updated(const QString& topic, const QVariant& value);
void topic_idle(const QString& topic);
void topic_active(const QString& topic);
+ /// Emitted when a producer reports a refresh failure (via
+ /// `publish_error`) or when the scheduler times out a stuck in_flight
+ /// topic. `error` is a short diagnostic string ("http 429",
+ /// "refresh_timeout", ...). The topic's cached value is unchanged —
+ /// subscribers still see the last good value if any.
+ void topic_error(const QString& topic, const QString& error);
private:
DataHub();
@@ -158,10 +202,13 @@ class DataHub : public QObject {
QVariant value;
qint64 last_publish_ms = 0;
qint64 last_refresh_request_ms = 0;
+ qint64 last_error_ms = 0;
int total_publishes = 0;
+ int total_errors = 0;
bool in_flight = false;
TopicPolicy policy;
bool policy_explicit = false; ///< set_policy() was called
+ QString last_error; ///< most recent error string; cleared on successful publish
// Coalesce state — non-zero policy.coalesce_within_ms only.
bool coalesce_pending = false; ///< a deferred publish is armed
QVariant coalesce_latest; ///< most recent value inside window
@@ -202,7 +249,30 @@ class DataHub : public QObject {
// Per-producer: last time we called refresh() on it — for rate pacing.
QHash<Producer*, qint64> producer_last_refresh_ms_;
+ // Prefix index for find_producer() — sorted by prefix length DESC so a
+ // longest-match scan (linear in matching entries) picks the most
+ // specific pattern. Rebuilt on register/unregister; patterns are
+ // `*`-suffix so the prefix is pattern minus trailing '*' (or the full
+ // pattern for exact matches). Replaces O(N_producers × N_patterns)
+ // iteration with a cheaper cache-friendly scan.
+ struct PatternEntry {
+ QString prefix; ///< pattern with trailing '*' stripped, or full pattern
+ bool is_wildcard; ///< true if original pattern ended with '*'
+ Producer* owner;
+ };
+ QVector<PatternEntry> pattern_index_;
+ void rebuild_pattern_index(); // caller holds mutex_
+
QTimer scheduler_;
+
+ // Request coalescing — see DataHub::request(). Any topics queued here
+ // have already passed the in_flight / min_interval / rate-limit gates and
+ // are guaranteed to dispatch together on the next coalesce flush.
+ QHash<Producer*, QStringList> coalesce_pending_;
+ QTimer coalesce_timer_;
+ static constexpr int kDefaultCoalesceWindowMs = 100;
+ int coalesce_window_ms_ = kDefaultCoalesceWindowMs;
+ void flush_coalesced_requests();
};
} // namespace fincept::datahub
diff --git a/fincept-qt/src/datahub/Producer.h b/fincept-qt/src/datahub/Producer.h
index b82db3e04..4f4bdb322 100644
--- a/fincept-qt/src/datahub/Producer.h
+++ b/fincept-qt/src/datahub/Producer.h
@@ -3,15 +3,11 @@
#include <QString>
#include <QStringList>
-// Phase 0 stub — see fincept-qt/DATAHUB_ARCHITECTURE.md §3.3.
-// Full wiring into DataHub happens in Phase 1.
-
namespace fincept::datahub {
-/// A Producer owns refresh for a set of topic patterns. Existing services
+/// A Producer owns refresh for a set of topic patterns. Services
/// (MarketDataService, NewsService, ExchangeService, broker adapters, …)
-/// will implement this interface during Phases 2–9. The interface is
-/// declared now so Phase 1 can compile against it without churn.
+/// implement this interface to plug into DataHub.
class Producer {
public:
virtual ~Producer() = default;
@@ -23,7 +19,8 @@ class Producer {
/// Hub calls this when ≥1 subscriber exists and the cached value is
/// stale. Producer fetches asynchronously and calls
- /// `DataHub::publish()` when results are ready.
+ /// `DataHub::publish()` when results are ready, or
+ /// `DataHub::publish_error()` if the fetch failed.
virtual void refresh(const QStringList& topics) = 0;
/// Optional cap on outbound requests per second for this producer.
@@ -31,11 +28,6 @@ class Producer {
/// respect this limit. Typical values: Zerodha REST 3, Angel One
/// REST 1, Polymarket 10.
virtual int max_requests_per_sec() const { return 0; }
-
- /// Optional: called when the last subscriber leaves a topic owned
- /// by this producer. Producers may release per-topic resources
- /// here (close a WS channel, cancel a stream, etc.).
- virtual void on_topic_idle(const QString& /*topic*/) {}
};
} // namespace fincept::datahub
diff --git a/fincept-qt/src/datahub/TopicPolicy.h b/fincept-qt/src/datahub/TopicPolicy.h
index a503073bb..a6590fc3a 100644
--- a/fincept-qt/src/datahub/TopicPolicy.h
+++ b/fincept-qt/src/datahub/TopicPolicy.h
@@ -1,8 +1,5 @@
#pragma once
-// Phase 0 stub — see fincept-qt/DATAHUB_ARCHITECTURE.md §3.4.
-// Full definition lands in Phase 1 alongside DataHub.cpp.
-
namespace fincept::datahub {
/// Per-topic refresh + caching metadata.
@@ -17,28 +14,34 @@ struct TopicPolicy {
/// regardless of how many subscribers request it.
int min_interval_ms = 5'000;
+ /// If a producer's refresh() doesn't publish() (success) or
+ /// publish_error() (failure) within this window, the hub clears the
+ /// `in_flight` flag and logs a warning. Prevents a crashed / hung /
+ /// silently-failing producer from pinning a topic forever.
+ int refresh_timeout_ms = 30'000;
+
/// If true, the scheduler never touches this topic — producers are
/// expected to push updates as they arrive (e.g. WebSocket feeds).
- /// `ttl_ms` and `min_interval_ms` are ignored.
+ /// `ttl_ms`, `min_interval_ms`, and `refresh_timeout_ms` are ignored.
bool push_only = false;
- /// Higher priority topics are dispatched first when the scheduler
- /// has to shed load under producer rate limits.
- int priority = 0;
-
- /// Opt-in: when true, the hub rehydrates the last cached value from
- /// `CacheManager` on app start and emits it to subscribers. Default
- /// false per the Phase 0 decision — we start cold.
- bool rehydrate_on_start = false;
-
/// Backpressure guard for high-rate push_only feeds. When non-zero,
/// the hub stores the latest payload for the topic but delays fan-out
/// — each `publish()` within the window replaces the pending value,
/// and only the most-recent value is delivered to subscribers when
/// the window ends. `topic_updated`, pattern slots, and direct slots
- /// all fire exactly once per window. Added in Phase 4 for Kraken /
- /// HyperLiquid ticker feeds.
+ /// all fire exactly once per window.
int coalesce_within_ms = 0;
+
+ /// If true, the hub drops the entire TopicState (value, counters,
+ /// error history) when the last subscriber leaves. Use for topics
+ /// where the set of live topics is unbounded (e.g. agent run outputs,
+ /// per-session LLM streams) so the hub doesn't accumulate state for
+ /// every unique topic key seen in a long session.
+ ///
+ /// Default is false — most topics benefit from keeping last-known-
+ /// good values for `peek()` and for re-subscribe warm-start.
+ bool drop_on_idle = false;
};
} // namespace fincept::datahub
diff --git a/fincept-qt/src/mcp/tools/DataHubTools.cpp b/fincept-qt/src/mcp/tools/DataHubTools.cpp
index e3ddb884a..720de34e2 100644
--- a/fincept-qt/src/mcp/tools/DataHubTools.cpp
+++ b/fincept-qt/src/mcp/tools/DataHubTools.cpp
@@ -87,7 +87,9 @@ std::vector<ToolDef> get_datahub_tools() {
const QString topic = args["topic"].toString().trimmed();
if (topic.isEmpty()) return ToolResult::fail("Missing 'topic'");
auto& hub = fincept::datahub::DataHub::instance();
- const QVariant v = hub.peek(topic);
+ // peek_raw: MCP diagnostic tool shows stale data rather than
+ // nothing — callers use stats() / last_publish_ms to judge freshness.
+ const QVariant v = hub.peek_raw(topic);
QJsonObject out;
out["topic"] = topic;
if (!v.isValid()) {
diff --git a/fincept-qt/src/python/PythonRunner.cpp b/fincept-qt/src/python/PythonRunner.cpp
index e14865140..261082b18 100644
--- a/fincept-qt/src/python/PythonRunner.cpp
+++ b/fincept-qt/src/python/PythonRunner.cpp
@@ -378,6 +378,7 @@ void PythonRunner::start_next() {
// Initialize incremental output buffers (carry stream callback from the request)
proc_buffers_[proc] = {};
proc_buffers_[proc].on_line = req.on_line;
+ proc_buffers_[proc].start_ms = QDateTime::currentMSecsSinceEpoch();
// Helper: drain complete \n-terminated lines from a buffer starting at `offset`,
// invoke `on_line(line, is_stderr)` per line, advance `offset`. Trailing
@@ -422,6 +423,9 @@ void PythonRunner::start_next() {
bufs.stdout_buf.append(proc->readAllStandardOutput());
bufs.stderr_buf.append(proc->readAllStandardError());
+ const qint64 duration_ms = bufs.start_ms > 0
+ ? QDateTime::currentMSecsSinceEpoch() - bufs.start_ms : 0;
+
QString stdout_str = QString::fromUtf8(bufs.stdout_buf);
QString stderr_str = QString::fromUtf8(bufs.stderr_buf);
@@ -450,10 +454,15 @@ void PythonRunner::start_next() {
}
if (!result.success && !is_code) {
- LOG_ERROR("Python", QString("Script %1 failed (exit=%2): %3")
+ LOG_ERROR("Python", QString("Script %1 failed in %2ms (exit=%3): %4")
.arg(script_name)
+ .arg(duration_ms)
.arg(exit_code)
.arg(result.error.left(200)));
+ } else if (!is_code) {
+ LOG_DEBUG("Python", QString("Script %1 finished in %2ms")
+ .arg(script_name)
+ .arg(duration_ms));
}
cb(std::move(result));
diff --git a/fincept-qt/src/python/PythonRunner.h b/fincept-qt/src/python/PythonRunner.h
index 30d6a6f7b..287583be9 100644
--- a/fincept-qt/src/python/PythonRunner.h
+++ b/fincept-qt/src/python/PythonRunner.h
@@ -93,6 +93,7 @@ class PythonRunner : public QObject {
int stdout_streamed = 0; // offset into stdout_buf already streamed
int stderr_streamed = 0;
StreamCallback on_line;
+ qint64 start_ms = 0; // spawn timestamp for duration diagnostics
};
QHash<QProcess*, ProcessBuffers> proc_buffers_;
};
diff --git a/fincept-qt/src/python/PythonWorker.cpp b/fincept-qt/src/python/PythonWorker.cpp
new file mode 100644
index 000000000..2c0299ac9
--- /dev/null
+++ b/fincept-qt/src/python/PythonWorker.cpp
@@ -0,0 +1,293 @@
+#include "python/PythonWorker.h"
+
+#include "core/logging/Logger.h"
+#include "python/PythonRunner.h"
+#include "python/PythonSetupManager.h"
+
+#include <QByteArray>
+#include <QCoreApplication>
+#include <QDateTime>
+#include <QFileInfo>
+#include <QJsonDocument>
+
+namespace fincept::python {
+
+namespace {
+
+/// Pack a 4-byte big-endian length prefix followed by the JSON payload bytes.
+/// Mirrors `_daemon_write_frame` on the Python side.
+QByteArray encode_frame(const QJsonObject& obj) {
+ const QByteArray body = QJsonDocument(obj).toJson(QJsonDocument::Compact);
+ const quint32 n = static_cast<quint32>(body.size());
+ QByteArray out;
+ out.reserve(4 + body.size());
+ out.append(static_cast<char>((n >> 24) & 0xff));
+ out.append(static_cast<char>((n >> 16) & 0xff));
+ out.append(static_cast<char>((n >> 8) & 0xff));
+ out.append(static_cast<char>(n & 0xff));
+ out.append(body);
+ return out;
+}
+
+} // namespace
+
+PythonWorker& PythonWorker::instance() {
+ static PythonWorker s;
+ return s;
+}
+
+PythonWorker::PythonWorker() {
+ ready_watchdog_.setSingleShot(true);
+ ready_watchdog_.setInterval(kReadyTimeoutMs);
+ connect(&ready_watchdog_, &QTimer::timeout, this, [this]() {
+ if (ready_) return;
+ LOG_WARN("PythonWorker", "Daemon handshake timed out — killing and restarting");
+ if (proc_) {
+ proc_->kill();
+ }
+ });
+}
+
+PythonWorker::~PythonWorker() {
+ stop();
+}
+
+void PythonWorker::submit(const QString& action, const QJsonObject& payload, Callback cb) {
+ ensure_started();
+
+ const int id = next_id_++;
+ Pending p;
+ p.action = action;
+ p.payload = payload;
+ p.cb = std::move(cb);
+
+ if (!ready_ || !proc_ || proc_->state() != QProcess::Running) {
+ // Queue until the daemon is ready (or restarted).
+ queue_.append({id, std::move(p)});
+ return;
+ }
+
+ QJsonObject req;
+ req["id"] = id;
+ req["action"] = action;
+ req["payload"] = payload;
+ in_flight_.insert(id, std::move(p));
+ proc_->write(encode_frame(req));
+}
+
+void PythonWorker::stop() {
+ shutting_down_ = true;
+ if (!proc_)
+ return;
+ if (proc_->state() == QProcess::Running) {
+ QJsonObject req;
+ req["id"] = 0;
+ req["action"] = QStringLiteral("shutdown");
+ req["payload"] = QJsonObject{};
+ proc_->write(encode_frame(req));
+ proc_->closeWriteChannel();
+ proc_->waitForFinished(2'000); // destructor-only blocking call (P1 allows)
+ if (proc_->state() != QProcess::NotRunning)
+ proc_->kill();
+ }
+ fail_all_pending(QStringLiteral("worker shutting down"));
+}
+
+void PythonWorker::ensure_started() {
+ if (proc_ && proc_->state() != QProcess::NotRunning)
+ return;
+ launch_process();
+}
+
+void PythonWorker::launch_process() {
+ auto& runner = PythonRunner::instance();
+ const QString scripts_dir = runner.scripts_dir();
+ const QString script_path = scripts_dir + "/yfinance_data.py";
+ if (!QFileInfo::exists(script_path)) {
+ LOG_WARN("PythonWorker", "yfinance_data.py not found — worker disabled");
+ return;
+ }
+
+ // Always use venv-numpy2 — yfinance lives there. Fall back to the
+ // PythonRunner's resolved interpreter if the venv isn't present.
+ QString python_exe =
+ PythonSetupManager::instance().python_path(QStringLiteral("venv-numpy2"));
+ if (!QFileInfo::exists(python_exe))
+ python_exe = runner.python_path();
+ if (python_exe.isEmpty()) {
+ LOG_WARN("PythonWorker", "No Python interpreter resolved — worker disabled");
+ return;
+ }
+
+ if (proc_) {
+ proc_->deleteLater();
+ proc_ = nullptr;
+ }
+ proc_ = new QProcess(this);
+ proc_->setProcessEnvironment(runner.build_python_env());
+ proc_->setWorkingDirectory(scripts_dir);
+ proc_->setReadChannel(QProcess::StandardOutput);
+
+#ifdef _WIN32
+ proc_->setCreateProcessArgumentsModifier([](QProcess::CreateProcessArguments* cpa) {
+ cpa->flags |= 0x08000000; // CREATE_NO_WINDOW
+ });
+#endif
+
+ connect(proc_, &QProcess::readyReadStandardOutput, this, &PythonWorker::on_ready_read);
+ connect(proc_, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), this,
+ &PythonWorker::on_process_finished);
+ connect(proc_, &QProcess::errorOccurred, this, &PythonWorker::on_process_error);
+ // Drain stderr to the log so Python import/runtime errors surface.
+ connect(proc_, &QProcess::readyReadStandardError, this, [this]() {
+ if (!proc_) return;
+ const QByteArray err = proc_->readAllStandardError();
+ if (!err.isEmpty()) {
+ LOG_WARN("PythonWorker", QString("stderr: %1").arg(QString::fromUtf8(err).trimmed()));
+ }
+ });
+
+ read_buf_.clear();
+ ready_ = false;
+ LOG_INFO("PythonWorker", QString("Launching daemon: %1 %2 --daemon")
+ .arg(python_exe).arg(script_path));
+ proc_->start(python_exe, {script_path, QStringLiteral("--daemon")});
+ ready_watchdog_.start();
+}
+
+void PythonWorker::on_process_finished(int exit_code, QProcess::ExitStatus status) {
+ ready_ = false;
+ ready_watchdog_.stop();
+ const QString reason = QString("daemon exited (code=%1 status=%2)").arg(exit_code).arg(status);
+ LOG_INFO("PythonWorker", reason);
+
+ // Fail any in-flight requests; queued requests are preserved for the
+ // next restart so callers don't observe spurious failures.
+ for (auto it = in_flight_.begin(); it != in_flight_.end(); ++it) {
+ if (it.value().cb) it.value().cb(false, {}, reason);
+ }
+ in_flight_.clear();
+
+ if (shutting_down_ || QCoreApplication::closingDown()) {
+ return;
+ }
+
+ if (restart_count_ >= kMaxRestarts) {
+ LOG_ERROR("PythonWorker",
+ QString("Restart cap (%1) reached — giving up, pending requests will fail")
+ .arg(kMaxRestarts));
+ fail_all_pending(QStringLiteral("worker restart cap reached"));
+ return;
+ }
+ ++restart_count_;
+ LOG_INFO("PythonWorker", QString("Restarting daemon (attempt %1/%2)")
+ .arg(restart_count_).arg(kMaxRestarts));
+ launch_process();
+}
+
+void PythonWorker::on_process_error(QProcess::ProcessError err) {
+ LOG_WARN("PythonWorker", QString("QProcess error: %1 (%2)")
+ .arg(err)
+ .arg(proc_ ? proc_->errorString() : QString()));
+}
+
+void PythonWorker::on_ready_read() {
+ if (!proc_) return;
+ read_buf_.append(proc_->readAllStandardOutput());
+ try_drain_frames();
+}
+
+void PythonWorker::try_drain_frames() {
+ while (read_buf_.size() >= 4) {
+ const quint8 b0 = static_cast<quint8>(read_buf_.at(0));
+ const quint8 b1 = static_cast<quint8>(read_buf_.at(1));
+ const quint8 b2 = static_cast<quint8>(read_buf_.at(2));
+ const quint8 b3 = static_cast<quint8>(read_buf_.at(3));
+ const quint32 n =
+ (static_cast<quint32>(b0) << 24) | (static_cast<quint32>(b1) << 16) |
+ (static_cast<quint32>(b2) << 8) | static_cast<quint32>(b3);
+ if (n > 64u * 1024u * 1024u) {
+ LOG_ERROR("PythonWorker", QString("Frame size %1 exceeds 64MB cap — resetting stream").arg(n));
+ read_buf_.clear();
+ if (proc_) proc_->kill();
+ return;
+ }
+ if (static_cast<quint32>(read_buf_.size()) < 4 + n) {
+ return; // wait for more bytes
+ }
+ const QByteArray body = read_buf_.mid(4, static_cast<int>(n));
+ read_buf_.remove(0, 4 + static_cast<int>(n));
+
+ QJsonParseError pe;
+ const QJsonDocument doc = QJsonDocument::fromJson(body, &pe);
+ if (pe.error != QJsonParseError::NoError || !doc.isObject()) {
+ LOG_WARN("PythonWorker",
+ QString("Bad JSON frame: %1 (%2 bytes)").arg(pe.errorString()).arg(body.size()));
+ continue;
+ }
+ const QJsonObject obj = doc.object();
+
+ // Ready handshake
+ if (!ready_ && obj.value("ready").toBool()) {
+ ready_ = true;
+ ready_watchdog_.stop();
+ restart_count_ = 0; // clean handshake resets the retry budget
+ LOG_INFO("PythonWorker", QString("Daemon ready (pid=%1)")
+ .arg(obj.value("pid").toInt()));
+ dispatch_queued();
+ continue;
+ }
+
+ // Response
+ const int id = obj.value("id").toInt();
+ auto it = in_flight_.find(id);
+ if (it == in_flight_.end()) {
+ LOG_DEBUG("PythonWorker", QString("Unknown response id=%1 — ignoring").arg(id));
+ continue;
+ }
+ Pending p = std::move(it.value());
+ in_flight_.erase(it);
+ const bool ok = obj.value("ok").toBool();
+ const QString err = obj.value("error").toString();
+ QJsonObject result_obj;
+ // Result can be any JSON type; wrap non-object results in a container
+ // under "_value" so callers always receive an object.
+ const QJsonValue rv = obj.value("result");
+ if (rv.isObject()) {
+ result_obj = rv.toObject();
+ } else {
+ result_obj["_value"] = rv;
+ }
+ if (p.cb) p.cb(ok, result_obj, err);
+ }
+}
+
+void PythonWorker::dispatch_queued() {
+ if (!ready_ || !proc_)
+ return;
+ auto local = std::move(queue_);
+ queue_.clear();
+ for (auto& entry : local) {
+ const int id = entry.first;
+ Pending& p = entry.second;
+ QJsonObject req;
+ req["id"] = id;
+ req["action"] = p.action;
+ req["payload"] = p.payload;
+ in_flight_.insert(id, std::move(p));
+ proc_->write(encode_frame(req));
+ }
+}
+
+void PythonWorker::fail_all_pending(const QString& reason) {
+ for (auto& entry : queue_) {
+ if (entry.second.cb) entry.second.cb(false, {}, reason);
+ }
+ queue_.clear();
+ for (auto it = in_flight_.begin(); it != in_flight_.end(); ++it) {
+ if (it.value().cb) it.value().cb(false, {}, reason);
+ }
+ in_flight_.clear();
+}
+
+} // namespace fincept::python
diff --git a/fincept-qt/src/python/PythonWorker.h b/fincept-qt/src/python/PythonWorker.h
new file mode 100644
index 000000000..86f72d343
--- /dev/null
+++ b/fincept-qt/src/python/PythonWorker.h
@@ -0,0 +1,92 @@
+#pragma once
+
+#include <QHash>
+#include <QJsonObject>
+#include <QObject>
+#include <QPointer>
+#include <QProcess>
+#include <QString>
+#include <QTimer>
+
+#include <functional>
+
+namespace fincept::python {
+
+/// Persistent yfinance worker — long-lived Python process running
+/// `yfinance_data.py --daemon`. Avoids the 2–3 second yfinance/pandas import
+/// cost that every `PythonRunner::run()` spawn pays.
+///
+/// Scope: yfinance_data.py ONLY. Do NOT route agent/framework/numpy1 scripts
+/// through here — those need PythonRunner's per-script venv routing (numpy1
+/// vs numpy2 selection in PythonRunner.cpp::select_venv_for_script).
+///
+/// Framing: 4-byte big-endian length prefix, UTF-8 JSON body. Matches
+/// `run_daemon()` in scripts/yfinance_data.py.
+///
+/// Requests carry a monotonically increasing `id`. Callbacks are keyed by id
+/// and invoked on the Qt event loop when the matching response arrives.
+///
+/// Lifecycle: `start()` is lazy — call from the first producer. Restart on
+/// unexpected exit is automatic (up to a retry cap). `stop()` closes stdin
+/// and waits briefly for a clean exit.
+class PythonWorker : public QObject {
+ Q_OBJECT
+ public:
+ using Callback = std::function<void(bool ok, QJsonObject result, QString error)>;
+
+ static PythonWorker& instance();
+
+ /// True once the daemon has sent its `{"ready": true}` handshake and
+ /// is accepting requests. Requests submitted before this queue up and
+ /// dispatch once ready.
+ bool is_ready() const { return ready_; }
+
+ /// Submit one request. `action` maps to the daemon's dispatch table
+ /// (batch_all, batch_quotes, batch_sparklines, historical_period, ...).
+ /// `payload` is action-specific. Callback is invoked on the hub thread.
+ /// Safe to call before the daemon is ready — the request queues.
+ void submit(const QString& action, const QJsonObject& payload, Callback cb);
+
+ /// Graceful shutdown — sent automatically on app exit via destructor.
+ void stop();
+
+ private:
+ PythonWorker();
+ ~PythonWorker() override;
+
+ void ensure_started();
+ void launch_process();
+ void on_process_finished(int exit_code, QProcess::ExitStatus status);
+ void on_process_error(QProcess::ProcessError err);
+ void on_ready_read();
+ void try_drain_frames();
+ void dispatch_queued();
+ void fail_all_pending(const QString& reason);
+
+ QProcess* proc_ = nullptr;
+ bool ready_ = false;
+ bool shutting_down_ = false;
+ int restart_count_ = 0;
+ static constexpr int kMaxRestarts = 5;
+ static constexpr int kReadyTimeoutMs = 15'000; // import yfinance+pandas
+
+ // Pending request tracking. Keyed by request id for response correlation.
+ struct Pending {
+ QString action;
+ QJsonObject payload;
+ Callback cb;
+ };
+ QHash<int, Pending> in_flight_;
+ // Requests submitted before the daemon was ready, or queued during restart.
+ QVector<QPair<int, Pending>> queue_;
+ int next_id_ = 1;
+
+ // Read buffer — frames may span multiple readyRead() signals.
+ QByteArray read_buf_;
+
+ // Ready-wait watchdog — if the daemon hasn't handshaked within the
+ // timeout, kill it and restart.
+ QTimer ready_watchdog_;
+};
+
+} // namespace fincept::python
diff --git a/fincept-qt/src/screens/auth/LockScreen.cpp b/fincept-qt/src/screens/auth/LockScreen.cpp
index 260728774..38db12040 100644
--- a/fincept-qt/src/screens/auth/LockScreen.cpp
+++ b/fincept-qt/src/screens/auth/LockScreen.cpp
@@ -6,6 +6,8 @@
#include <QFrame>
#include <QHBoxLayout>
+#include <QIntValidator>
+#include <QKeyEvent>
#include <QPainter>
#include <QStackedWidget>
#include <QVBoxLayout>
@@ -79,6 +81,44 @@ static QString error_style() {
.arg(ui::colors::NEGATIVE());
}
+// Hardens a PIN QLineEdit against input-method leakage, predictive text, and
+// paste-based brute-force scripts. Called on every PIN entry field in this
+// screen.
+static void harden_pin_input(QLineEdit* edit) {
+ if (!edit) return;
+
+ // Tell IMEs / on-screen keyboards this is a 6-digit secret — no prediction,
+ // no suggestions, no clipboard history surfacing.
+ edit->setInputMethodHints(Qt::ImhDigitsOnly | Qt::ImhSensitiveData |
+ Qt::ImhNoPredictiveText | Qt::ImhNoAutoUppercase |
+ Qt::ImhHiddenText);
+
+ // Validator rejects non-digits at the keypress level so only 0-9 can be
+ // typed even if the paste block below is ever circumvented.
+ auto* validator = new QIntValidator(0, 999999, edit);
+ edit->setValidator(validator);
+
+ // Disable drag/drop into the field (dropped text would bypass validators).
+ edit->setDragEnabled(false);
+ edit->setAcceptDrops(false);
+
+ // No right-click → Paste, and no clipboard pull via the built-in menu.
+ edit->setContextMenuPolicy(Qt::NoContextMenu);
+
+ // Disable Qt's built-in paste shortcut so Ctrl+V / Shift+Insert cannot
+ // inject a scripted PIN attempt. We still allow manual digit entry only.
+ QObject::connect(edit, &QLineEdit::textChanged, edit, [edit](const QString& txt) {
+ // Belt-and-braces: if anything non-digit somehow lands here, strip it.
+ QString cleaned;
+ cleaned.reserve(txt.size());
+ for (const QChar& c : txt) if (c.isDigit()) cleaned.append(c);
+ if (cleaned != txt) {
+ QSignalBlocker b(edit);
+ edit->setText(cleaned);
+ }
+ });
+}
+
static QFrame* make_separator() {
auto* sep = new QFrame;
sep->setFixedHeight(1);
@@ -218,6 +258,7 @@ void LockScreen::build_setup_page() {
setup_pin_input_->setEchoMode(QLineEdit::Password);
setup_pin_input_->setFixedHeight(44);
setup_pin_input_->setStyleSheet(pin_input_style());
+ harden_pin_input(setup_pin_input_);
vl->addWidget(setup_pin_input_);
// Confirm PIN input
@@ -232,6 +273,7 @@ void LockScreen::build_setup_page() {
setup_confirm_input_->setEchoMode(QLineEdit::Password);
setup_confirm_input_->setFixedHeight(44);
setup_confirm_input_->setStyleSheet(pin_input_style());
+ harden_pin_input(setup_confirm_input_);
vl->addWidget(setup_confirm_input_);
// Error label
@@ -319,6 +361,7 @@ void LockScreen::build_unlock_page() {
unlock_pin_input_->setEchoMode(QLineEdit::Password);
unlock_pin_input_->setFixedHeight(48);
unlock_pin_input_->setStyleSheet(pin_input_style());
+ harden_pin_input(unlock_pin_input_);
vl->addWidget(unlock_pin_input_);
// Lockout / attempt display
@@ -467,24 +510,10 @@ void LockScreen::show_lockout() {
// ── Actions ─────────────────────────────────────────────────────────────────
void LockScreen::on_setup_submit() {
- QString pin = setup_pin_input_->text();
- QString confirm = setup_confirm_input_->text();
-
- if (pin.length() != 6) {
- setup_error_->setText("PIN must be exactly 6 digits");
- setup_error_->show();
- return;
- }
-
- // Check all digits
- for (const QChar& c : pin) {
- if (!c.isDigit()) {
- setup_error_->setText("PIN must contain only digits");
- setup_error_->show();
- return;
- }
- }
+ const QString pin = setup_pin_input_->text();
+ const QString confirm = setup_confirm_input_->text();
+ // Match check is UI-only — PinManager has no concept of a confirm field.
if (pin != confirm) {
setup_error_->setText("PINs do not match");
setup_error_->show();
@@ -493,35 +522,9 @@ void LockScreen::on_setup_submit() {
return;
}
- // Check for trivially weak PINs
- bool all_same = true;
- for (int i = 1; i < pin.length(); ++i) {
- if (pin[i] != pin[0]) {
- all_same = false;
- break;
- }
- }
- if (all_same) {
- setup_error_->setText("PIN is too simple — use unique digits");
- setup_error_->show();
- return;
- }
-
- // Sequential check (123456, 654321)
- bool sequential_up = true;
- bool sequential_down = true;
- for (int i = 1; i < pin.length(); ++i) {
- if (pin[i].unicode() != pin[i - 1].unicode() + 1)
- sequential_up = false;
- if (pin[i].unicode() != pin[i - 1].unicode() - 1)
- sequential_down = false;
- }
- if (sequential_up || sequential_down) {
- setup_error_->setText("PIN is too simple — avoid sequential digits");
- setup_error_->show();
- return;
- }
-
+ // All length / digit-only / weak-pattern rejection now lives in
+ // PinManager::set_pin() so future setup flows (QR companion, tests) hit
+ // the same guardrails. Render whatever message PinManager returns.
auto result = auth::PinManager::instance().set_pin(pin);
if (result.is_err()) {
setup_error_->setText(QString::fromStdString(result.error()));
diff --git a/fincept-qt/src/screens/dashboard/DashboardScreen.cpp b/fincept-qt/src/screens/dashboard/DashboardScreen.cpp
index 2fcc66a88..b3204f5cb 100644
--- a/fincept-qt/src/screens/dashboard/DashboardScreen.cpp
+++ b/fincept-qt/src/screens/dashboard/DashboardScreen.cpp
@@ -278,7 +278,11 @@ void DashboardScreen::hub_resubscribe_ticker() {
rebuild_ticker_from_cache();
});
}
- hub.request(topics);
+ // force=true: ticker bar re-subscribe happens on user edits and tab shows —
+ // bypass min_interval so the ticker doesn't sit blank. Subscribe's built-in
+ // cold-start fetch (task 4) already handles the cold case; force is for
+ // the "symbols changed, existing cache is for old symbols" case.
+ hub.request(topics, /*force=*/true);
hub_active_ = true;
}
diff --git a/fincept-qt/src/screens/dashboard/MarketPulsePanel.cpp b/fincept-qt/src/screens/dashboard/MarketPulsePanel.cpp
index dbfc0148b..c3d9a852c 100644
--- a/fincept-qt/src/screens/dashboard/MarketPulsePanel.cpp
+++ b/fincept-qt/src/screens/dashboard/MarketPulsePanel.cpp
@@ -992,7 +992,7 @@ void MarketPulsePanel::refresh_data() {
push(kBreadthSymbols);
push(kMoverSymbols);
push(kSnapshotSymbols);
- hub.request(topics);
+ hub.request(topics, /*force=*/true); // user-triggered refresh
}
} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/dashboard/widgets/MarketSentimentWidget.cpp b/fincept-qt/src/screens/dashboard/widgets/MarketSentimentWidget.cpp
index 7bfc4137b..7ca94d35e 100644
--- a/fincept-qt/src/screens/dashboard/widgets/MarketSentimentWidget.cpp
+++ b/fincept-qt/src/screens/dashboard/widgets/MarketSentimentWidget.cpp
@@ -170,12 +170,13 @@ void MarketSentimentWidget::hideEvent(QHideEvent* e) {
}
void MarketSentimentWidget::refresh_data() {
+ // User-triggered refresh — force past min_interval; producer rate limit still paces upstream.
auto& hub = datahub::DataHub::instance();
QStringList topics;
topics.reserve(kSentimentSymbols.size());
for (const auto& sym : kSentimentSymbols)
topics.append(QStringLiteral("market:quote:") + sym);
- hub.request(topics);
+ hub.request(topics, /*force=*/true);
}
diff --git a/fincept-qt/src/screens/dashboard/widgets/PerformanceWidget.cpp b/fincept-qt/src/screens/dashboard/widgets/PerformanceWidget.cpp
index 821f23561..b44ff263f 100644
--- a/fincept-qt/src/screens/dashboard/widgets/PerformanceWidget.cpp
+++ b/fincept-qt/src/screens/dashboard/widgets/PerformanceWidget.cpp
@@ -86,7 +86,7 @@ void PerformanceWidget::refresh_data() {
topics.reserve(kPerfSymbols.size());
for (const auto& sym : kPerfSymbols)
topics.append(QStringLiteral("market:quote:") + sym);
- hub.request(topics);
+ hub.request(topics, /*force=*/true); // user-triggered: bypass min_interval
}
diff --git a/fincept-qt/src/screens/dashboard/widgets/QuoteTableWidget.cpp b/fincept-qt/src/screens/dashboard/widgets/QuoteTableWidget.cpp
index ef065b19f..9a597ee6e 100644
--- a/fincept-qt/src/screens/dashboard/widgets/QuoteTableWidget.cpp
+++ b/fincept-qt/src/screens/dashboard/widgets/QuoteTableWidget.cpp
@@ -49,16 +49,15 @@ void QuoteTableWidget::hideEvent(QHideEvent* e) {
}
void QuoteTableWidget::refresh_data() {
- // User-triggered refresh (e.g. BaseWidget refresh button): ask the hub
- // to kick a fresh fetch for every symbol. This bypasses the scheduler's
- // TTL gate but is still paced by `min_interval_ms` and the producer's
- // `max_requests_per_sec()`.
+ // User-triggered refresh: force-bypass min_interval so a user tap on the
+ // refresh button always kicks a fetch. Producer-side rate limit still
+ // applies, so rage-clicking can't hammer upstream.
auto& hub = datahub::DataHub::instance();
QStringList topics;
topics.reserve(symbols_.size());
for (const auto& sym : symbols_)
topics.append(QStringLiteral("market:quote:") + sym);
- hub.request(topics);
+ hub.request(topics, /*force=*/true);
}
diff --git a/fincept-qt/src/screens/dashboard/widgets/RiskMetricsWidget.cpp b/fincept-qt/src/screens/dashboard/widgets/RiskMetricsWidget.cpp
index 94f546341..26932a3ba 100644
--- a/fincept-qt/src/screens/dashboard/widgets/RiskMetricsWidget.cpp
+++ b/fincept-qt/src/screens/dashboard/widgets/RiskMetricsWidget.cpp
@@ -201,7 +201,7 @@ void RiskMetricsWidget::refresh_data() {
topics.reserve(kRiskSymbols.size());
for (const auto& sym : kRiskSymbols)
topics.append(QStringLiteral("market:quote:") + sym);
- hub.request(topics);
+ hub.request(topics, /*force=*/true); // user-triggered: bypass min_interval
}
diff --git a/fincept-qt/src/screens/dashboard/widgets/ScreenerWidget.cpp b/fincept-qt/src/screens/dashboard/widgets/ScreenerWidget.cpp
index 6b4aa1552..482c217ec 100644
--- a/fincept-qt/src/screens/dashboard/widgets/ScreenerWidget.cpp
+++ b/fincept-qt/src/screens/dashboard/widgets/ScreenerWidget.cpp
@@ -137,7 +137,7 @@ void ScreenerWidget::refresh_data() {
topics.reserve(kScreenerSymbols.size());
for (const auto& sym : kScreenerSymbols)
topics.append(QStringLiteral("market:quote:") + sym);
- hub.request(topics);
+ hub.request(topics, /*force=*/true); // user-triggered: bypass min_interval
}
diff --git a/fincept-qt/src/screens/dashboard/widgets/SectorHeatmapWidget.cpp b/fincept-qt/src/screens/dashboard/widgets/SectorHeatmapWidget.cpp
index 2798d746c..283ed40bb 100644
--- a/fincept-qt/src/screens/dashboard/widgets/SectorHeatmapWidget.cpp
+++ b/fincept-qt/src/screens/dashboard/widgets/SectorHeatmapWidget.cpp
@@ -69,7 +69,7 @@ void SectorHeatmapWidget::refresh_data() {
QStringList topics;
for (const auto& sym : sector_symbols())
topics.append(QStringLiteral("market:quote:") + sym);
- hub.request(topics);
+ hub.request(topics, /*force=*/true); // user-triggered: bypass min_interval
}
diff --git a/fincept-qt/src/screens/dashboard/widgets/TopMoversWidget.cpp b/fincept-qt/src/screens/dashboard/widgets/TopMoversWidget.cpp
index 07bfd0aa3..69fc70afd 100644
--- a/fincept-qt/src/screens/dashboard/widgets/TopMoversWidget.cpp
+++ b/fincept-qt/src/screens/dashboard/widgets/TopMoversWidget.cpp
@@ -67,7 +67,7 @@ void TopMoversWidget::refresh_data() {
topics.reserve(symbols_.size());
for (const auto& sym : symbols_)
topics.append(QStringLiteral("market:quote:") + sym);
- hub.request(topics);
+ hub.request(topics, /*force=*/true); // user-triggered: bypass min_interval
}
diff --git a/fincept-qt/src/screens/dashboard/widgets/WatchlistWidget.cpp b/fincept-qt/src/screens/dashboard/widgets/WatchlistWidget.cpp
index 503b4ae98..1b408de6f 100644
--- a/fincept-qt/src/screens/dashboard/widgets/WatchlistWidget.cpp
+++ b/fincept-qt/src/screens/dashboard/widgets/WatchlistWidget.cpp
@@ -98,7 +98,7 @@ void WatchlistWidget::refresh_data() {
topics.reserve(symbols_.size());
for (const auto& sym : symbols_)
topics.append(QStringLiteral("market:quote:") + sym);
- hub.request(topics);
+ hub.request(topics, /*force=*/true); // user-triggered: bypass min_interval
}
diff --git a/fincept-qt/src/screens/equity_research/EquityResearchScreen.cpp b/fincept-qt/src/screens/equity_research/EquityResearchScreen.cpp
index 537483f14..0a424b06a 100644
--- a/fincept-qt/src/screens/equity_research/EquityResearchScreen.cpp
+++ b/fincept-qt/src/screens/equity_research/EquityResearchScreen.cpp
@@ -3,6 +3,8 @@
#include "core/events/EventBus.h"
#include "core/session/ScreenStateManager.h"
+#include "core/symbol/SymbolContext.h"
+#include "core/symbol/SymbolDragSource.h"
#include "screens/equity_research/EquityAnalysisTab.h"
#include "screens/equity_research/EquityFinancialsTab.h"
#include "screens/equity_research/EquityNewsTab.h"
@@ -46,6 +48,14 @@ EquityResearchScreen::EquityResearchScreen(QWidget* parent) : QWidget(parent) {
// Default symbol
load_symbol("AAPL");
+
+ // Drop any dragged symbol onto the screen to jump the research view
+ // to that ticker. Uses the existing load_symbol path so caching,
+ // signals, and the EventBus publish stay consistent.
+ symbol_dnd::installDropFilter(this, [this](const SymbolRef& ref, SymbolGroup) {
+ if (ref.is_valid())
+ load_symbol(ref.symbol);
+ });
}
void EquityResearchScreen::showEvent(QShowEvent* e) {
@@ -125,6 +135,14 @@ QWidget* EquityResearchScreen::build_title_bar() {
symbol_label_ = new QLabel;
symbol_label_->setStyleSheet(QString("color:%1; font-size:14px; font-weight:600;").arg(ui::colors::TEXT_PRIMARY()));
+ symbol_label_->setCursor(Qt::OpenHandCursor);
+ symbol_label_->setToolTip("Drag to broadcast this symbol to any panel");
+ // Drag-out: pull the current symbol from the live member so the filter
+ // always ships the most recent ticker, not whatever was loaded at build.
+ symbol_dnd::installDragSource(
+ symbol_label_,
+ [this]() { return current_symbol(); },
+ link_group_);
hl->addWidget(symbol_label_);
hl->addStretch();
@@ -239,6 +257,25 @@ void EquityResearchScreen::load_symbol(const QString& symbol) {
// Trigger quote + info + historical
services::equity::EquityResearchService::instance().load_symbol(symbol);
+
+ // Publish to linked group so Watchlist/EquityTrading/News/etc. follow.
+ if (link_group_ != SymbolGroup::None) {
+ SymbolContext::instance().set_group_symbol(
+ link_group_, SymbolRef::equity(symbol), this);
+ }
+}
+
+// ── IGroupLinked ─────────────────────────────────────────────────────────────
+
+void EquityResearchScreen::on_group_symbol_changed(const SymbolRef& ref) {
+ if (ref.is_valid())
+ load_symbol(ref.symbol);
+}
+
+SymbolRef EquityResearchScreen::current_symbol() const {
+ if (current_symbol_.isEmpty())
+ return {};
+ return SymbolRef::equity(current_symbol_);
}
void EquityResearchScreen::update_quote_bar(const services::equity::QuoteData& q) {
diff --git a/fincept-qt/src/screens/equity_research/EquityResearchScreen.h b/fincept-qt/src/screens/equity_research/EquityResearchScreen.h
index 6e87f29da..ad1cf936c 100644
--- a/fincept-qt/src/screens/equity_research/EquityResearchScreen.h
+++ b/fincept-qt/src/screens/equity_research/EquityResearchScreen.h
@@ -1,5 +1,6 @@
// src/screens/equity_research/EquityResearchScreen.h
#pragma once
+#include "core/symbol/IGroupLinked.h"
#include "screens/IStatefulScreen.h"
#include "services/equity/EquityResearchModels.h"
@@ -21,8 +22,9 @@ class EquityPeersTab;
class EquityNewsTab;
class EquitySentimentTab;
-class EquityResearchScreen : public QWidget, public IStatefulScreen {
+class EquityResearchScreen : public QWidget, public IStatefulScreen, public IGroupLinked {
Q_OBJECT
+ Q_INTERFACES(fincept::IGroupLinked)
public:
explicit EquityResearchScreen(QWidget* parent = nullptr);
@@ -30,6 +32,14 @@ class EquityResearchScreen : public QWidget, public IStatefulScreen {
QVariantMap save_state() const override;
QString state_key() const override { return "equity_research"; }
+ // IGroupLinked — receives group broadcasts and calls load_symbol();
+ // also publishes when load_symbol() is triggered internally via the
+ // existing EventBus wiring (see .cpp).
+ void set_group(SymbolGroup g) override { link_group_ = g; }
+ SymbolGroup group() const override { return link_group_; }
+ void on_group_symbol_changed(const SymbolRef& ref) override;
+ SymbolRef current_symbol() const override;
+
protected:
void showEvent(QShowEvent* event) override;
void hideEvent(QHideEvent* event) override;
@@ -72,6 +82,9 @@ class EquityResearchScreen : public QWidget, public IStatefulScreen {
QTimer* refresh_timer_ = nullptr;
QString current_symbol_;
QString current_currency_;
+
+ // Symbol group link — SymbolGroup::None when unlinked.
+ SymbolGroup link_group_ = SymbolGroup::None;
};
} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/equity_trading/EquityTradingScreen.cpp b/fincept-qt/src/screens/equity_trading/EquityTradingScreen.cpp
index 3b3759a8f..82a27a1c3 100644
--- a/fincept-qt/src/screens/equity_trading/EquityTradingScreen.cpp
+++ b/fincept-qt/src/screens/equity_trading/EquityTradingScreen.cpp
@@ -3,6 +3,11 @@
#include "core/logging/Logger.h"
#include "core/session/ScreenStateManager.h"
+#include "core/symbol/SymbolContext.h"
+#include "core/symbol/SymbolDragSource.h"
+
+#include <QApplication>
+#include <QMouseEvent>
#include "screens/equity_trading/AccountManagementDialog.h"
#include "screens/equity_trading/BroadcastOrderDialog.h"
#include "screens/equity_trading/EquityBottomPanel.h"
@@ -69,6 +74,14 @@ EquityTradingScreen::EquityTradingScreen(QWidget* parent) : QWidget(parent) {
setup_timers();
connect_data_stream_signals();
WorkspaceManager::instance().register_participant("equity_trading", this);
+
+ // Accept symbol drops anywhere on the screen — route through the
+ // existing selection path so sub-panels resync and the linked group is
+ // published to.
+ symbol_dnd::installDropFilter(this, [this](const SymbolRef& ref, SymbolGroup) {
+ if (ref.is_valid())
+ on_symbol_selected(ref.symbol);
+ });
}
EquityTradingScreen::~EquityTradingScreen() {
@@ -760,6 +773,14 @@ void EquityTradingScreen::switch_symbol(const QString& symbol) {
order_entry_->set_symbol(symbol);
watchlist_->set_active_symbol(symbol);
+ // Publish to the linked group so other panels (Watchlist, EquityResearch,
+ // News, Derivatives, SurfaceAnalytics) follow. `this` as source suppresses
+ // the echo back into this screen.
+ if (link_group_ != SymbolGroup::None) {
+ SymbolContext::instance().set_group_symbol(
+ link_group_, SymbolRef::equity(symbol, selected_exchange_), this);
+ }
+
auto* stream = DataStreamManager::instance().stream_for(focused_account_id_);
if (stream) {
stream->set_selected_symbol(symbol, selected_exchange_);
@@ -1315,4 +1336,19 @@ void EquityTradingScreen::on_import_holdings_requested(const QVector<trading::Br
}
}
+// ── IGroupLinked ─────────────────────────────────────────────────────────────
+
+void EquityTradingScreen::on_group_symbol_changed(const SymbolRef& ref) {
+ if (!ref.is_valid() || ref.symbol == selected_symbol_)
+ return;
+ // Route through the existing selection path so sub-panels sync.
+ on_symbol_selected(ref.symbol);
+}
+
+SymbolRef EquityTradingScreen::current_symbol() const {
+ if (selected_symbol_.isEmpty())
+ return {};
+ return SymbolRef::equity(selected_symbol_, selected_exchange_);
+}
+
} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/equity_trading/EquityTradingScreen.h b/fincept-qt/src/screens/equity_trading/EquityTradingScreen.h
index 0ebb41d5c..0b4129d77 100644
--- a/fincept-qt/src/screens/equity_trading/EquityTradingScreen.h
+++ b/fincept-qt/src/screens/equity_trading/EquityTradingScreen.h
@@ -3,6 +3,7 @@
// Supports multiple broker accounts simultaneously via DataStreamManager.
// Each account has its own data stream (WS/polling), portfolio, and credentials.
+#include "core/symbol/IGroupLinked.h"
#include "screens/IStatefulScreen.h"
#include "screens/equity_trading/EquityTypes.h"
#include "services/workspace/IWorkspaceParticipant.h"
@@ -31,8 +32,9 @@ class EquityBottomPanel;
namespace fincept::screens {
-class EquityTradingScreen : public QWidget, public IWorkspaceParticipant {
+class EquityTradingScreen : public QWidget, public IWorkspaceParticipant, public IGroupLinked {
Q_OBJECT
+ Q_INTERFACES(fincept::IGroupLinked)
public:
explicit EquityTradingScreen(QWidget* parent = nullptr);
~EquityTradingScreen();
@@ -40,6 +42,12 @@ class EquityTradingScreen : public QWidget, public IWorkspaceParticipant {
QJsonObject save_state() const override;
void restore_state(const QJsonObject& state) override;
+ // IGroupLinked — see WatchlistScreen for the propagation contract.
+ void set_group(SymbolGroup g) override { link_group_ = g; }
+ SymbolGroup group() const override { return link_group_; }
+ void on_group_symbol_changed(const SymbolRef& ref) override;
+ SymbolRef current_symbol() const override;
+
protected:
void showEvent(QShowEvent* event) override;
void hideEvent(QHideEvent* event) override;
@@ -123,6 +131,9 @@ class EquityTradingScreen : public QWidget, public IWorkspaceParticipant {
double current_price_ = 0.0; // last known LTP for selected symbol
bool initialized_ = false;
+
+ // Symbol group link — SymbolGroup::None when unlinked.
+ SymbolGroup link_group_ = SymbolGroup::None;
};
} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/markets/MarketPanel.cpp b/fincept-qt/src/screens/markets/MarketPanel.cpp
index 028745c26..c2e93857e 100644
--- a/fincept-qt/src/screens/markets/MarketPanel.cpp
+++ b/fincept-qt/src/screens/markets/MarketPanel.cpp
@@ -273,7 +273,11 @@ void MarketPanel::hub_resubscribe() {
}
});
}
- hub.request(topics);
+ // force=true: on cold start, DataHub::subscribe auto-triggers a fetch,
+ // but on user-initiated refresh_all() (F5 / auto-refresh tick / panel
+ // reconfig) we want to bypass min_interval. Producer rate limit still
+ // paces upstream calls.
+ hub.request(topics, /*force=*/true);
hub_active_ = true;
}
diff --git a/fincept-qt/src/screens/news/NewsScreen.cpp b/fincept-qt/src/screens/news/NewsScreen.cpp
index 49f059162..f5c8fb646 100644
--- a/fincept-qt/src/screens/news/NewsScreen.cpp
+++ b/fincept-qt/src/screens/news/NewsScreen.cpp
@@ -3,6 +3,7 @@
#include "core/keys/KeyConfigManager.h"
#include "core/logging/Logger.h"
#include "core/session/ScreenStateManager.h"
+#include "core/symbol/SymbolDragSource.h"
#include "screens/news/NewsCommandBar.h"
#include "screens/news/NewsDetailPanel.h"
#include "screens/news/NewsFeedPanel.h"
@@ -48,6 +49,15 @@ NewsScreen::NewsScreen(QWidget* parent) : QWidget(parent) {
build_ui();
connect_signals();
+
+ // Drop a symbol anywhere on the News screen to filter the feed by that
+ // ticker. Reuses the search-query pipeline so caching/highlighting stay
+ // coherent with keyword search.
+ symbol_dnd::installDropFilter(this, [this](const SymbolRef& ref, SymbolGroup) {
+ if (ref.is_valid())
+ on_search_changed(ref.symbol);
+ });
+
LOG_INFO("NewsScreen", "News screen constructed (no data fetch in constructor)");
}
@@ -347,6 +357,20 @@ void NewsScreen::on_search_changed(const QString& query) {
apply_filters_async();
}
+void NewsScreen::on_group_symbol_changed(const SymbolRef& ref) {
+ if (!ref.is_valid())
+ return;
+ // Route through the same pipeline the search box uses so caching,
+ // highlighting, and notifications stay consistent. We don't touch
+ // the command bar's text box — the search query is the data-layer
+ // filter, which is what drives feed filtering.
+ on_search_changed(ref.symbol);
+}
+
+// Drop hook installed in the constructor below is wired via symbol_dnd —
+// see constructor edits for the installDropFilter call that forwards to
+// on_search_changed().
+
void NewsScreen::on_refresh() {
refresh_data(true);
}
diff --git a/fincept-qt/src/screens/news/NewsScreen.h b/fincept-qt/src/screens/news/NewsScreen.h
index ae7a2951d..7a38c267f 100644
--- a/fincept-qt/src/screens/news/NewsScreen.h
+++ b/fincept-qt/src/screens/news/NewsScreen.h
@@ -1,4 +1,5 @@
#pragma once
+#include "core/symbol/IGroupLinked.h"
#include "screens/IStatefulScreen.h"
#include "services/news/NewsClusterService.h"
#include "services/news/NewsMonitorService.h"
@@ -28,8 +29,9 @@ class NewsTickerStrip;
/// 3. Content area — full-width feed | optional right detail overlay (420px)
/// optional left intel drawer (280px, toggled)
/// 4. Ticker strip (22px) — scrolling breaking headlines
-class NewsScreen : public QWidget, public IStatefulScreen {
+class NewsScreen : public QWidget, public IStatefulScreen, public IGroupLinked {
Q_OBJECT
+ Q_INTERFACES(fincept::IGroupLinked)
public:
explicit NewsScreen(QWidget* parent = nullptr);
@@ -38,6 +40,14 @@ class NewsScreen : public QWidget, public IStatefulScreen {
QString state_key() const override { return "news"; }
int state_version() const override { return 1; }
+ // IGroupLinked — subscribe-only. When the group's active symbol
+ // changes, the news feed's search query becomes that symbol so the
+ // article list filters to mentions.
+ void set_group(SymbolGroup g) override { link_group_ = g; }
+ SymbolGroup group() const override { return link_group_; }
+ void on_group_symbol_changed(const SymbolRef& ref) override;
+ SymbolRef current_symbol() const override { return {}; }
+
protected:
void showEvent(QShowEvent* event) override;
void hideEvent(QHideEvent* event) override;
@@ -134,6 +144,9 @@ class NewsScreen : public QWidget, public IStatefulScreen {
// Active variant for feed filtering
QString active_variant_ = "FULL";
+
+ // Symbol group link — SymbolGroup::None when unlinked.
+ SymbolGroup link_group_ = SymbolGroup::None;
};
} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/portfolio/PortfolioAgentPanel.cpp b/fincept-qt/src/screens/portfolio/PortfolioAgentPanel.cpp
deleted file mode 100644
index 514a312c5..000000000
--- a/fincept-qt/src/screens/portfolio/PortfolioAgentPanel.cpp
+++ /dev/null
@@ -1,257 +0,0 @@
-// src/screens/portfolio/PortfolioAgentPanel.cpp
-#include "screens/portfolio/PortfolioAgentPanel.h"
-
-#include "ai_chat/LlmService.h"
-#include "core/logging/Logger.h"
-#include "storage/repositories/AgentConfigRepository.h"
-#include "ui/theme/Theme.h"
-
-#include <QHBoxLayout>
-#include <QJsonDocument>
-#include <QJsonObject>
-#include <QPointer>
-#include <QRegularExpression>
-#include <QVBoxLayout>
-#include <QtConcurrent>
-
-namespace fincept::screens {
-
-PortfolioAgentPanel::PortfolioAgentPanel(QWidget* parent) : QWidget(parent) {
- setFixedWidth(480);
- build_ui();
- hide();
-}
-
-void PortfolioAgentPanel::build_ui() {
- setStyleSheet(QString("background:%1; border:1px solid #00D4AA;").arg(ui::colors::BG_BASE()));
-
- auto* layout = new QVBoxLayout(this);
- layout->setContentsMargins(0, 0, 0, 0);
- layout->setSpacing(0);
-
- // ── Header ───────────────────────────────────────────────────────────────
- auto* header = new QWidget(this);
- header->setFixedHeight(32);
- header->setStyleSheet(
- QString("background:rgba(0,212,170,0.07); border-bottom:1px solid %1;").arg(ui::colors::BORDER_MED()));
-
- auto* h_layout = new QHBoxLayout(header);
- h_layout->setContentsMargins(12, 0, 8, 0);
- h_layout->setSpacing(6);
-
- auto* icon = new QLabel("\U0001F916");
- icon->setStyleSheet("font-size:12px;");
- h_layout->addWidget(icon);
-
- auto* title = new QLabel("AGENT RUNNER");
- title->setStyleSheet("color:#00D4AA; font-size:10px; font-weight:800; letter-spacing:1px;");
- h_layout->addWidget(title);
-
- status_lbl_ = new QLabel;
- status_lbl_->setStyleSheet("color:#00D4AA; font-size:9px;");
- h_layout->addWidget(status_lbl_);
-
- h_layout->addStretch();
-
- close_btn_ = new QPushButton("\u2715");
- close_btn_->setFixedSize(18, 18);
- close_btn_->setCursor(Qt::PointingHandCursor);
- close_btn_->setStyleSheet(QString("QPushButton { background:none; border:none; color:%1; font-size:11px; }"
- "QPushButton:hover { color:%2; }")
- .arg(ui::colors::TEXT_SECONDARY(), ui::colors::TEXT_PRIMARY()));
- connect(close_btn_, &QPushButton::clicked, this, [this]() {
- hide();
- emit close_requested();
- });
- h_layout->addWidget(close_btn_);
-
- layout->addWidget(header);
-
- // ── Agent selector ───────────────────────────────────────────────────────
- auto* selector = new QWidget(this);
- selector->setStyleSheet(
- QString("background:%1; border-bottom:1px solid %2;").arg(ui::colors::BG_SURFACE(), ui::colors::BORDER_DIM()));
- auto* sel_layout = new QVBoxLayout(selector);
- sel_layout->setContentsMargins(12, 8, 12, 8);
- sel_layout->setSpacing(4);
-
- auto* sel_label = new QLabel("SELECT AGENT");
- sel_label->setStyleSheet(
- QString("color:%1; font-size:8px; font-weight:700; letter-spacing:0.5px;").arg(ui::colors::TEXT_TERTIARY()));
- sel_layout->addWidget(sel_label);
-
- agent_cb_ = new QComboBox;
- agent_cb_->setFixedHeight(26);
- agent_cb_->setStyleSheet(QString("QComboBox { background:%1; color:%2; border:1px solid %3;"
- " padding:0 8px; font-size:10px; }"
- "QComboBox::drop-down { border:none; }"
- "QComboBox QAbstractItemView { background:%1; color:%2; }")
- .arg(ui::colors::BG_BASE(), ui::colors::TEXT_PRIMARY(), ui::colors::BORDER_MED()));
- connect(agent_cb_, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [this](int) {
- QString id = agent_cb_->currentData().toString();
- if (result_cache_.contains(id))
- content_->setHtml(result_cache_[id]);
- else
- content_->clear();
- });
- sel_layout->addWidget(agent_cb_);
-
- // Run button
- run_btn_ = new QPushButton("\U0001F916 RUN AGENT ON PORTFOLIO");
- run_btn_->setFixedHeight(26);
- run_btn_->setCursor(Qt::PointingHandCursor);
- run_btn_->setStyleSheet(QString("QPushButton { background:rgba(0,212,170,0.13); color:#00D4AA;"
- " border:1px solid rgba(0,212,170,0.27); font-size:9px; font-weight:700;"
- " letter-spacing:0.5px; margin-top:6px; }"
- "QPushButton:hover { background:rgba(0,212,170,0.22); }"
- "QPushButton:disabled { color:%1; }")
- .arg(ui::colors::TEXT_TERTIARY()));
- connect(run_btn_, &QPushButton::clicked, this, [this]() { run_agent(true); });
- sel_layout->addWidget(run_btn_);
-
- layout->addWidget(selector);
-
- // ── Content ──────────────────────────────────────────────────────────────
- content_ = new QTextBrowser;
- content_->setOpenExternalLinks(true);
- content_->setStyleSheet(QString("QTextBrowser { background:%1; color:%2; border:none; padding:12px;"
- " font-size:11px; line-height:1.6; }")
- .arg(ui::colors::BG_BASE(), ui::colors::TEXT_PRIMARY()));
- content_->setPlaceholderText("Select an agent above and click Run.");
- layout->addWidget(content_, 1);
-}
-
-void PortfolioAgentPanel::set_summary(const portfolio::PortfolioSummary& summary) {
- if (summary.portfolio.id != last_portfolio_id_) {
- result_cache_.clear();
- content_->clear();
- last_portfolio_id_ = summary.portfolio.id;
- }
- summary_ = summary;
-}
-
-void PortfolioAgentPanel::show_panel() {
- reload_agents();
- show();
- raise();
-}
-
-void PortfolioAgentPanel::reload_agents() {
- agent_cb_->clear();
- auto r = AgentConfigRepository::instance().list_all();
- if (r.is_ok()) {
- for (const auto& a : r.value()) {
- QString label = a.name;
- if (!a.description.isEmpty())
- label += " \u2014 " + a.description.left(40);
- agent_cb_->addItem(label, a.id);
- }
- }
- if (agent_cb_->count() == 0) {
- agent_cb_->addItem("No agents saved \u2014 create one in Agent Config", "");
- }
-}
-
-void PortfolioAgentPanel::run_agent(bool force) {
- if (running_ || summary_.holdings.isEmpty())
- return;
-
- QString agent_id = agent_cb_->currentData().toString();
- if (agent_id.isEmpty())
- return;
-
- if (!force && result_cache_.contains(agent_id)) {
- content_->setHtml(result_cache_[agent_id]);
- return;
- }
-
- auto& llm = ai_chat::LlmService::instance();
- if (!llm.is_configured()) {
- content_->setPlainText("No LLM configured. Please add a model in Settings -> LLM Configuration.");
- return;
- }
-
- // Get agent config
- auto agent_r = AgentConfigRepository::instance().get(agent_id);
- if (agent_r.is_err()) {
- content_->setPlainText("Failed to load agent configuration.");
- return;
- }
-
- auto agent_cfg = agent_r.value();
- QString instructions =
- "You are a professional portfolio analyst. Analyze the provided portfolio data and give actionable insights.";
-
- // Parse config JSON for custom instructions
- auto cfg_doc = QJsonDocument::fromJson(agent_cfg.config_json.toUtf8());
- if (cfg_doc.isObject()) {
- auto cfg_obj = cfg_doc.object();
- if (cfg_obj.contains("instructions"))
- instructions = cfg_obj["instructions"].toString();
- }
-
- running_ = true;
- run_btn_->setEnabled(false);
- status_lbl_->setText("\u23F3");
- content_->setPlainText("Agent is analyzing your portfolio...");
-
- // Build portfolio context
- QStringList lines;
- lines << QString("Portfolio: %1 | NAV: %2 %3")
- .arg(summary_.portfolio.name, summary_.portfolio.currency)
- .arg(QString::number(summary_.total_market_value, 'f', 2));
- lines << QString("Total P&L: %1% | Positions: %2")
- .arg(QString::number(summary_.total_unrealized_pnl_percent, 'f', 2))
- .arg(summary_.total_positions);
-
- for (const auto& h : summary_.holdings) {
- lines << QString("%1: %2 units @ %3 | P&L: %4% | Weight: %5%")
- .arg(h.symbol)
- .arg(QString::number(h.quantity, 'f', 2))
- .arg(QString::number(h.current_price, 'f', 2))
- .arg(QString::number(h.unrealized_pnl_percent, 'f', 2))
- .arg(QString::number(h.weight, 'f', 1));
- }
- lines << "" << instructions;
-
- QString prompt = lines.join("\n");
- QPointer<PortfolioAgentPanel> self = this;
-
- (void)QtConcurrent::run([self, prompt, agent_id]() {
- auto response = ai_chat::LlmService::instance().chat(prompt, {});
-
- if (!self)
- return;
- QMetaObject::invokeMethod(
- self,
- [self, response, agent_id]() {
- if (!self)
- return;
- self->running_ = false;
- self->run_btn_->setEnabled(true);
- self->status_lbl_->clear();
-
- if (response.success) {
- QString html = response.content;
- html.replace("&", "&amp;");
- html.replace("<", "&lt;");
- html.replace(">", "&gt;");
- html.replace("\n", "<br>");
- static const QRegularExpression bold_re("\\*\\*(.+?)\\*\\*");
- html.replace(bold_re, "<b>\\1</b>");
- html = QString("<div style='font-size:11px; line-height:1.6; color:%1;'>%2</div>")
- .arg(ui::colors::TEXT_PRIMARY())
- .arg(html);
-
- self->result_cache_[agent_id] = html;
- self->content_->setHtml(html);
- self->run_btn_->setText("\U0001F916 RE-RUN AGENT");
- } else {
- self->content_->setPlainText("Agent run failed: " + response.error);
- }
- },
- Qt::QueuedConnection);
- });
-}
-
-} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/portfolio/PortfolioAgentPanel.h b/fincept-qt/src/screens/portfolio/PortfolioAgentPanel.h
deleted file mode 100644
index 195a572f2..000000000
--- a/fincept-qt/src/screens/portfolio/PortfolioAgentPanel.h
+++ /dev/null
@@ -1,42 +0,0 @@
-// src/screens/portfolio/PortfolioAgentPanel.h
-#pragma once
-#include "screens/portfolio/PortfolioTypes.h"
-
-#include <QComboBox>
-#include <QLabel>
-#include <QPushButton>
-#include <QTextBrowser>
-#include <QWidget>
-
-namespace fincept::screens {
-
-/// Floating agent runner panel — selects a saved agent config and runs it on portfolio data.
-class PortfolioAgentPanel : public QWidget {
- Q_OBJECT
- public:
- explicit PortfolioAgentPanel(QWidget* parent = nullptr);
-
- void set_summary(const portfolio::PortfolioSummary& summary);
- void show_panel();
- void reload_agents();
-
- signals:
- void close_requested();
-
- private:
- void build_ui();
- void run_agent(bool force = false);
-
- QPushButton* close_btn_ = nullptr;
- QLabel* status_lbl_ = nullptr;
- QComboBox* agent_cb_ = nullptr;
- QPushButton* run_btn_ = nullptr;
- QTextBrowser* content_ = nullptr;
-
- portfolio::PortfolioSummary summary_;
- bool running_ = false;
- QHash<QString, QString> result_cache_; // agent_id -> result
- QString last_portfolio_id_;
-};
-
-} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/portfolio/PortfolioAiPanel.cpp b/fincept-qt/src/screens/portfolio/PortfolioAiPanel.cpp
deleted file mode 100644
index a9fa6d824..000000000
--- a/fincept-qt/src/screens/portfolio/PortfolioAiPanel.cpp
+++ /dev/null
@@ -1,253 +0,0 @@
-// src/screens/portfolio/PortfolioAiPanel.cpp
-#include "screens/portfolio/PortfolioAiPanel.h"
-
-#include "ai_chat/LlmService.h"
-#include "core/logging/Logger.h"
-#include "ui/theme/Theme.h"
-
-#include <QHBoxLayout>
-#include <QPointer>
-#include <QRegularExpression>
-#include <QVBoxLayout>
-#include <QtConcurrent>
-
-namespace fincept::screens {
-
-PortfolioAiPanel::PortfolioAiPanel(QWidget* parent) : QWidget(parent) {
- setFixedWidth(480);
- build_ui();
- hide();
-}
-
-void PortfolioAiPanel::build_ui() {
- setStyleSheet(QString("background:%1; border:1px solid #9D4EDD;").arg(ui::colors::BG_BASE()));
-
- auto* layout = new QVBoxLayout(this);
- layout->setContentsMargins(0, 0, 0, 0);
- layout->setSpacing(0);
-
- // ── Header ───────────────────────────────────────────────────────────────
- auto* header = new QWidget(this);
- header->setFixedHeight(32);
- header->setStyleSheet(
- QString("background:rgba(157,78,221,0.09); border-bottom:1px solid %1;").arg(ui::colors::BORDER_MED()));
-
- auto* h_layout = new QHBoxLayout(header);
- h_layout->setContentsMargins(12, 0, 8, 0);
- h_layout->setSpacing(6);
-
- auto* icon = new QLabel("\U0001F916");
- icon->setStyleSheet("font-size:12px;");
- h_layout->addWidget(icon);
-
- auto* title = new QLabel("AI PORTFOLIO ANALYSIS");
- title->setStyleSheet("color:#9D4EDD; font-size:10px; font-weight:800; letter-spacing:1px;");
- h_layout->addWidget(title);
-
- status_lbl_ = new QLabel;
- status_lbl_->setStyleSheet("color:#9D4EDD; font-size:9px;");
- h_layout->addWidget(status_lbl_);
-
- h_layout->addStretch();
-
- close_btn_ = new QPushButton("\u2715");
- close_btn_->setFixedSize(18, 18);
- close_btn_->setCursor(Qt::PointingHandCursor);
- close_btn_->setStyleSheet(QString("QPushButton { background:none; border:none; color:%1; font-size:11px; }"
- "QPushButton:hover { color:%2; }")
- .arg(ui::colors::TEXT_SECONDARY(), ui::colors::TEXT_PRIMARY()));
- connect(close_btn_, &QPushButton::clicked, this, [this]() {
- hide();
- emit close_requested();
- });
- h_layout->addWidget(close_btn_);
-
- layout->addWidget(header);
-
- // ── Analysis type selector ───────────────────────────────────────────────
- auto* type_bar = new QWidget(this);
- type_bar->setFixedHeight(28);
- type_bar->setStyleSheet(
- QString("background:%1; border-bottom:1px solid %2;").arg(ui::colors::BG_SURFACE(), ui::colors::BORDER_MED()));
-
- auto* type_layout = new QHBoxLayout(type_bar);
- type_layout->setContentsMargins(0, 0, 0, 0);
- type_layout->setSpacing(0);
-
- auto make_type_btn = [&](const QString& text, const QString& type_id) {
- auto* btn = new QPushButton(text);
- btn->setCheckable(true);
- btn->setCursor(Qt::PointingHandCursor);
- btn->setStyleSheet(QString("QPushButton { background:transparent; color:%1; border:none;"
- " border-bottom:2px solid transparent; padding:4px 8px;"
- " font-size:8px; font-weight:700; letter-spacing:0.5px; }"
- "QPushButton:checked { color:#9D4EDD; border-bottom:2px solid #9D4EDD;"
- " background:rgba(157,78,221,0.08); }"
- "QPushButton:hover { color:#9D4EDD; }")
- .arg(ui::colors::TEXT_SECONDARY()));
- connect(btn, &QPushButton::clicked, this, [this, type_id]() { set_analysis_type(type_id); });
- type_layout->addWidget(btn, 1);
- return btn;
- };
-
- full_btn_ = make_type_btn("FULL", "full");
- risk_btn_ = make_type_btn("RISK", "risk");
- rebal_btn_ = make_type_btn("REBALANCE", "rebalance");
- opport_btn_ = make_type_btn("OPPORTUNITIES", "opportunities");
- full_btn_->setChecked(true);
-
- layout->addWidget(type_bar);
-
- // ── Run button ───────────────────────────────────────────────────────────
- run_btn_ = new QPushButton("\U0001F916 RUN FULL ANALYSIS");
- run_btn_->setFixedHeight(28);
- run_btn_->setCursor(Qt::PointingHandCursor);
- run_btn_->setStyleSheet(QString("QPushButton { background:rgba(157,78,221,0.13); color:#9D4EDD;"
- " border:1px solid rgba(157,78,221,0.27); font-size:9px; font-weight:700;"
- " letter-spacing:0.5px; margin:6px 12px; }"
- "QPushButton:hover { background:rgba(157,78,221,0.22); }"
- "QPushButton:disabled { color:%1; }")
- .arg(ui::colors::TEXT_TERTIARY()));
- connect(run_btn_, &QPushButton::clicked, this, [this]() { run_analysis(true); });
- layout->addWidget(run_btn_);
-
- // ── Content ──────────────────────────────────────────────────────────────
- content_ = new QTextBrowser;
- content_->setOpenExternalLinks(true);
- content_->setStyleSheet(QString("QTextBrowser { background:%1; color:%2; border:none; padding:12px;"
- " font-size:11px; line-height:1.6; }")
- .arg(ui::colors::BG_BASE(), ui::colors::TEXT_PRIMARY()));
- content_->setPlaceholderText("Select an analysis type above and click Run.");
- layout->addWidget(content_, 1);
-}
-
-void PortfolioAiPanel::set_summary(const portfolio::PortfolioSummary& summary) {
- // Clear cache if portfolio changed
- if (summary.portfolio.id != last_portfolio_id_) {
- result_cache_.clear();
- content_->clear();
- last_portfolio_id_ = summary.portfolio.id;
- }
- summary_ = summary;
-}
-
-void PortfolioAiPanel::show_panel() {
- show();
- raise();
-}
-
-void PortfolioAiPanel::set_analysis_type(const QString& type) {
- current_type_ = type;
- full_btn_->setChecked(type == "full");
- risk_btn_->setChecked(type == "risk");
- rebal_btn_->setChecked(type == "rebalance");
- opport_btn_->setChecked(type == "opportunities");
-
- run_btn_->setText(
- QString("\U0001F916 %1 %2 ANALYSIS").arg(result_cache_.contains(type) ? "RE-RUN" : "RUN").arg(type.toUpper()));
-
- // Show cached result if available
- if (result_cache_.contains(type)) {
- content_->setHtml(result_cache_[type]);
- } else {
- content_->clear();
- }
-}
-
-QString PortfolioAiPanel::build_portfolio_prompt() const {
- QStringList lines;
- lines << QString("Portfolio: %1 | NAV: %2 %3")
- .arg(summary_.portfolio.name, summary_.portfolio.currency)
- .arg(QString::number(summary_.total_market_value, 'f', 2));
- lines << QString("Total P&L: %1% | Day Change: %2%")
- .arg(QString::number(summary_.total_unrealized_pnl_percent, 'f', 2))
- .arg(QString::number(summary_.total_day_change_percent, 'f', 2));
- lines << QString("Holdings (%1):").arg(summary_.holdings.size());
-
- for (const auto& h : summary_.holdings) {
- lines << QString(" %1: %2 units @ %3 | P&L: %4% | Weight: %5%")
- .arg(h.symbol)
- .arg(QString::number(h.quantity, 'f', 2))
- .arg(QString::number(h.current_price, 'f', 2))
- .arg(QString::number(h.unrealized_pnl_percent, 'f', 2))
- .arg(QString::number(h.weight, 'f', 1));
- }
-
- QString type_instruction;
- if (current_type_ == "risk")
- type_instruction =
- "Focus on risk analysis: identify concentration risks, correlation risks, and downside scenarios.";
- else if (current_type_ == "rebalance")
- type_instruction = "Suggest rebalancing actions with specific weight targets and rationale.";
- else if (current_type_ == "opportunities")
- type_instruction = "Identify opportunities: undervalued positions, missing sectors, and potential additions.";
- else
- type_instruction = "Provide a comprehensive portfolio analysis with actionable recommendations.";
-
- lines << "" << type_instruction;
- return lines.join("\n");
-}
-
-void PortfolioAiPanel::run_analysis(bool force) {
- if (analyzing_ || summary_.holdings.isEmpty())
- return;
-
- if (!force && result_cache_.contains(current_type_)) {
- content_->setHtml(result_cache_[current_type_]);
- return;
- }
-
- auto& llm = ai_chat::LlmService::instance();
- if (!llm.is_configured()) {
- content_->setPlainText("No LLM configured. Please add a model in Settings -> LLM Configuration.");
- return;
- }
-
- analyzing_ = true;
- run_btn_->setEnabled(false);
- status_lbl_->setText("\u23F3");
- content_->setPlainText(QString("Running %1 analysis...").arg(current_type_));
-
- QString prompt = build_portfolio_prompt();
- QString type = current_type_;
- QPointer<PortfolioAiPanel> self = this;
-
- (void)QtConcurrent::run([self, prompt, type]() {
- auto response = ai_chat::LlmService::instance().chat(prompt, {});
-
- if (!self)
- return;
- QMetaObject::invokeMethod(
- self,
- [self, response, type]() {
- if (!self)
- return;
- self->analyzing_ = false;
- self->run_btn_->setEnabled(true);
- self->status_lbl_->clear();
-
- if (response.success) {
- // Simple markdown-to-html: preserve line breaks, bold
- QString html = response.content;
- html.replace("&", "&amp;");
- html.replace("<", "&lt;");
- html.replace(">", "&gt;");
- html.replace("\n", "<br>");
- static const QRegularExpression bold_re("\\*\\*(.+?)\\*\\*");
- html.replace(bold_re, "<b>\\1</b>");
- html = QString("<div style='font-size:11px; line-height:1.6; color:%1;'>%2</div>")
- .arg(ui::colors::TEXT_PRIMARY())
- .arg(html);
-
- self->result_cache_[type] = html;
- self->content_->setHtml(html);
- self->run_btn_->setText(QString("\U0001F916 RE-RUN %1 ANALYSIS").arg(type.toUpper()));
- } else {
- self->content_->setPlainText("Analysis failed: " + response.error);
- }
- },
- Qt::QueuedConnection);
- });
-}
-
-} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/portfolio/PortfolioAiPanel.h b/fincept-qt/src/screens/portfolio/PortfolioAiPanel.h
deleted file mode 100644
index 3309879fb..000000000
--- a/fincept-qt/src/screens/portfolio/PortfolioAiPanel.h
+++ /dev/null
@@ -1,55 +0,0 @@
-// src/screens/portfolio/PortfolioAiPanel.h
-#pragma once
-#include "screens/portfolio/PortfolioTypes.h"
-
-#include <QLabel>
-#include <QPushButton>
-#include <QTextBrowser>
-#include <QWidget>
-
-namespace fincept::screens {
-
-/// Floating AI analysis panel overlaying the portfolio screen.
-/// Supports 4 analysis types with cached results per portfolio.
-class PortfolioAiPanel : public QWidget {
- Q_OBJECT
- public:
- explicit PortfolioAiPanel(QWidget* parent = nullptr);
-
- void set_summary(const portfolio::PortfolioSummary& summary);
- void show_panel();
-
- signals:
- void close_requested();
-
- private:
- void build_ui();
- void set_analysis_type(const QString& type);
- void run_analysis(bool force = false);
- QString build_portfolio_prompt() const;
-
- // Header
- QPushButton* close_btn_ = nullptr;
- QLabel* status_lbl_ = nullptr;
-
- // Type selector buttons
- QPushButton* full_btn_ = nullptr;
- QPushButton* risk_btn_ = nullptr;
- QPushButton* rebal_btn_ = nullptr;
- QPushButton* opport_btn_ = nullptr;
-
- // Run button
- QPushButton* run_btn_ = nullptr;
-
- // Content
- QTextBrowser* content_ = nullptr;
-
- // State
- portfolio::PortfolioSummary summary_;
- QString current_type_ = "full";
- bool analyzing_ = false;
- QHash<QString, QString> result_cache_; // type -> result
- QString last_portfolio_id_;
-};
-
-} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/portfolio/PortfolioBlotter.cpp b/fincept-qt/src/screens/portfolio/PortfolioBlotter.cpp
index 6b734237b..10b1445f2 100644
--- a/fincept-qt/src/screens/portfolio/PortfolioBlotter.cpp
+++ b/fincept-qt/src/screens/portfolio/PortfolioBlotter.cpp
@@ -57,15 +57,23 @@ void PortfolioBlotter::build_ui() {
"QTableWidget::item { padding:5px 8px; border-bottom:1px solid %4; }"
"QTableWidget::item:selected { background:rgba(217,119,6,0.10); color:%6; }"
"QTableWidget::item:hover { background:%7; }"
- "QHeaderView::section { background:%8; color:%9; border:none;"
- " border-bottom:2px solid %10; border-right:1px solid %4; padding:5px 8px;"
- " font-size:10px; font-weight:700; letter-spacing:0.5px; }"
"QScrollBar:vertical { width:5px; background:%1; }"
"QScrollBar::handle:vertical { background:%4; min-height:20px; }")
.arg(ui::colors::BG_BASE(), ui::colors::TEXT_PRIMARY(), ui::fonts::DATA_FAMILY,
ui::colors::BORDER_DIM(), ui::colors::AMBER_DIM(), ui::colors::AMBER(),
- ui::colors::BG_HOVER(), ui::colors::BG_SURFACE(), ui::colors::TEXT_SECONDARY())
- .arg(ui::colors::AMBER()));
+ ui::colors::BG_HOVER()));
+
+ // Apply the header rule directly on the header widget — the global qApp
+ // stylesheet (ThemeManager.cpp) defines QHeaderView::section with
+ // text_dim color, and Qt resolves header sub-controls from the header's
+ // OWN stylesheet, not the parent QTableWidget's. Setting it on the table
+ // is silently overridden, which is why headers stayed dim grey.
+ hdr->setStyleSheet(QString("QHeaderView::section { background:%1; color:%2; border:none;"
+ " border-bottom:2px solid %3; border-right:1px solid %4;"
+ " padding:5px 8px; font-size:10px; font-weight:700;"
+ " letter-spacing:0.5px; }")
+ .arg(ui::colors::BG_SURFACE(), ui::colors::TEXT_PRIMARY(),
+ ui::colors::AMBER(), ui::colors::BORDER_DIM()));
connect(hdr, &QHeaderView::sectionClicked, this, &PortfolioBlotter::on_header_clicked);
connect(table_, &QTableWidget::cellClicked, this, &PortfolioBlotter::on_row_clicked);
@@ -142,7 +150,9 @@ void PortfolioBlotter::hub_resubscribe_sparklines() {
repaint_sparkline_cells();
});
}
- hub.request(topics);
+ // force=true: holdings set changes on portfolio edits; bypass the sparkline
+ // min_interval so the row reflects the new symbol without waiting 30s.
+ hub.request(topics, /*force=*/true);
hub_active_ = true;
}
@@ -271,8 +281,10 @@ void PortfolioBlotter::populate_table() {
Qt::Alignment align = Qt::AlignRight | Qt::AlignVCenter) {
auto* item = new QTableWidgetItem(text);
item->setTextAlignment(align);
- if (color)
- item->setForeground(QColor(color));
+ // QTableWidgetItem ignores QTableWidget's stylesheet `color` and
+ // falls back to QPalette::Text (which renders as black on Windows).
+ // Always set an explicit foreground.
+ item->setForeground(QColor(color ? color : ui::colors::TEXT_PRIMARY()));
table_->setItem(r, col, item);
};
@@ -431,17 +443,20 @@ void PortfolioBlotter::refresh_theme() {
"QTableWidget::item { padding:5px 8px; border-bottom:1px solid %4; }"
"QTableWidget::item:selected { background:rgba(217,119,6,0.10); color:%6; }"
"QTableWidget::item:hover { background:%7; }"
- "QHeaderView::section { background:%8; color:%9; border:none;"
- " border-bottom:2px solid %10; border-right:1px solid %4; padding:5px 8px;"
- " font-size:" +
- hsz +
- "px; font-weight:700; letter-spacing:0.5px; }"
"QScrollBar:vertical { width:5px; background:%1; }"
"QScrollBar::handle:vertical { background:%4; min-height:20px; }")
.arg(ui::colors::BG_BASE(), ui::colors::TEXT_PRIMARY(), ui::fonts::DATA_FAMILY,
ui::colors::BORDER_DIM(), ui::colors::AMBER_DIM(), ui::colors::AMBER(),
- ui::colors::BG_HOVER(), ui::colors::BG_SURFACE(), ui::colors::TEXT_SECONDARY())
- .arg(ui::colors::AMBER()));
+ ui::colors::BG_HOVER()));
+ // See note in build constructor — header rule must live on the header
+ // widget itself or the global qApp stylesheet wins.
+ table_->horizontalHeader()->setStyleSheet(
+ QString("QHeaderView::section { background:%1; color:%2; border:none;"
+ " border-bottom:2px solid %3; border-right:1px solid %4;"
+ " padding:5px 8px; font-size:" + hsz +
+ "px; font-weight:700; letter-spacing:0.5px; }")
+ .arg(ui::colors::BG_SURFACE(), ui::colors::TEXT_PRIMARY(),
+ ui::colors::AMBER(), ui::colors::BORDER_DIM()));
populate_table();
}
diff --git a/fincept-qt/src/screens/portfolio/PortfolioDetailWrapper.cpp b/fincept-qt/src/screens/portfolio/PortfolioDetailWrapper.cpp
index e080e9deb..ac8ac5f9b 100644
--- a/fincept-qt/src/screens/portfolio/PortfolioDetailWrapper.cpp
+++ b/fincept-qt/src/screens/portfolio/PortfolioDetailWrapper.cpp
@@ -151,9 +151,13 @@ QWidget* PortfolioDetailWrapper::get_or_create_view(portfolio::DetailView view)
QWidget* widget = nullptr;
switch (view) {
- case portfolio::DetailView::AnalyticsSectors:
- widget = new AnalyticsSectorsView;
+ case portfolio::DetailView::AnalyticsSectors: {
+ auto* asv = new AnalyticsSectorsView;
+ connect(asv, &AnalyticsSectorsView::sector_selected,
+ this, &PortfolioDetailWrapper::sector_selected);
+ widget = asv;
break;
+ }
case portfolio::DetailView::PerfRisk: {
auto* prv = new PerformanceRiskView;
if (!current_snapshots_.isEmpty())
diff --git a/fincept-qt/src/screens/portfolio/PortfolioDetailWrapper.h b/fincept-qt/src/screens/portfolio/PortfolioDetailWrapper.h
index fd31fc184..6265a4994 100644
--- a/fincept-qt/src/screens/portfolio/PortfolioDetailWrapper.h
+++ b/fincept-qt/src/screens/portfolio/PortfolioDetailWrapper.h
@@ -25,6 +25,7 @@ class PortfolioDetailWrapper : public QWidget {
signals:
void back_requested();
+ void sector_selected(QString sector); // forwarded from AnalyticsSectorsView
private:
void build_ui();
diff --git a/fincept-qt/src/screens/portfolio/PortfolioInsightsPanel.cpp b/fincept-qt/src/screens/portfolio/PortfolioInsightsPanel.cpp
new file mode 100644
index 000000000..536fa09b6
--- /dev/null
+++ b/fincept-qt/src/screens/portfolio/PortfolioInsightsPanel.cpp
@@ -0,0 +1,670 @@
+// src/screens/portfolio/PortfolioInsightsPanel.cpp
+#include "screens/portfolio/PortfolioInsightsPanel.h"
+
+#include "ai_chat/LlmService.h"
+#include "core/logging/Logger.h"
+#include "services/agents/AgentService.h"
+#include "ui/markdown/MarkdownRenderer.h"
+#include "ui/theme/Theme.h"
+
+#include <QComboBox>
+#include <QDateTime>
+#include <QHBoxLayout>
+#include <QJsonArray>
+#include <QJsonDocument>
+#include <QJsonObject>
+#include <QKeyEvent>
+#include <QLabel>
+#include <QPointer>
+#include <QPushButton>
+#include <QScrollBar>
+#include <QShowEvent>
+#include <QStackedWidget>
+#include <QTextBrowser>
+#include <QVBoxLayout>
+
+namespace fincept::screens {
+
+namespace {
+
+QString fmt_now() {
+ return QDateTime::currentDateTime().toString("HH:mm:ss");
+}
+
+// Markdown rendering is delegated to ui::MarkdownRenderer — the same path used
+// by AgentChatPanel and AI Chat so portfolio responses look consistent.
+
+} // namespace
+
+PortfolioInsightsPanel::PortfolioInsightsPanel(QWidget* parent) : QWidget(parent) {
+ setObjectName("PortfolioInsightsPanel");
+ setFocusPolicy(Qt::StrongFocus);
+ setAttribute(Qt::WA_StyledBackground, true);
+ setFixedWidth(560);
+ build_ui();
+ hide();
+
+ // Wire AgentService results. Both run_portfolio_analysis (AI tab) and
+ // run_agent_streaming (Agent tab) come back through this service — we
+ // demultiplex by the pending type / request id we stored when we kicked
+ // off the run.
+ auto& svc = services::AgentService::instance();
+
+ connect(&svc, &services::AgentService::agent_result, this, [this](services::AgentExecutionResult r) {
+ // Only the AI tab uses the non-streaming run_portfolio_analysis path.
+ if (ai_pending_type_.isEmpty())
+ return;
+ const QString type = ai_pending_type_;
+ ai_pending_type_.clear();
+ ai_busy_ = false;
+ ai_run_->setEnabled(true);
+ header_status_->clear();
+ if (r.success && !r.response.isEmpty()) {
+ ai_cache_.insert(type, r.response);
+ ai_meta_->setText(QString("Last run %1 • %2ms").arg(fmt_now()).arg(r.execution_time_ms));
+ render_result(ai_content_, r.response);
+ QString upper = type.toUpper();
+ if (upper == "OPPORTUNITIES")
+ upper = "OPPS";
+ ai_run_->setText(QString("RE-RUN %1 ANALYSIS").arg(upper));
+ } else {
+ const QString msg = r.error.isEmpty() ? QStringLiteral("No response received.") : r.error;
+ render_error(ai_content_, "Analysis failed.\n\n" + msg);
+ }
+ });
+
+ connect(&svc, &services::AgentService::agent_stream_thinking, this,
+ [this](const QString& request_id, const QString& status) {
+ if (request_id != agent_pending_req_id_)
+ return;
+ header_status_->setText("● " + status);
+ });
+
+ // Live token streaming — accumulate into agent_streaming_text_ and show
+ // the partial response as plain text so the user sees progress. Final
+ // markdown rendering happens on agent_stream_done.
+ connect(&svc, &services::AgentService::agent_stream_token, this,
+ [this](const QString& request_id, const QString& token) {
+ if (request_id != agent_pending_req_id_)
+ return;
+ agent_streaming_text_ += token;
+ if (agent_content_) {
+ agent_content_->setPlainText(agent_streaming_text_);
+ auto* sb = agent_content_->verticalScrollBar();
+ sb->setValue(sb->maximum());
+ }
+ });
+
+ connect(&svc, &services::AgentService::agent_stream_done, this,
+ [this](services::AgentExecutionResult r) {
+ if (r.request_id != agent_pending_req_id_)
+ return;
+ const QString agent_id = agent_pending_id_;
+ agent_pending_req_id_.clear();
+ agent_pending_id_.clear();
+ agent_busy_ = false;
+ agent_run_->setEnabled(true);
+ header_status_->clear();
+
+ // finagent_core emits some agents via the final JSON line
+ // (r.response populated) and others via streamed tokens (where
+ // r.response may come back empty). Mirror AgentChatPanel's
+ // logic: prefer r.response, fall back to accumulated tokens.
+ QString final_text = r.response.trimmed();
+ if (final_text.isEmpty())
+ final_text = agent_streaming_text_.trimmed();
+ agent_streaming_text_.clear();
+
+ if (r.success && !final_text.isEmpty()) {
+ agent_cache_.insert(agent_id, final_text);
+ agent_meta_->setText(QString("Last run %1 • %2ms").arg(fmt_now()).arg(r.execution_time_ms));
+ render_result(agent_content_, final_text);
+ agent_run_->setText("RE-RUN AGENT");
+ } else if (r.success) {
+ // Agent reported success but produced no text — likely a
+ // config issue (no LLM key in the agent's profile, etc.).
+ render_error(agent_content_,
+ "Agent completed but returned no content.\n\n"
+ "Check the agent's LLM profile in Agent Config → Agents, "
+ "and make sure an API key is set in Settings → LLM Configuration.");
+ } else {
+ const QString msg = r.error.isEmpty() ? QStringLiteral("No response received.") : r.error;
+ render_error(agent_content_, "Agent run failed.\n\n" + msg);
+ }
+ });
+
+ // Refresh the agent dropdown whenever finagent_core discovers agents.
+ // This matches the AgentChatPanel wiring so both lists stay in sync.
+ connect(&svc, &services::AgentService::agents_discovered, this,
+ [this](QVector<services::AgentInfo>, QVector<services::AgentCategory>) {
+ if (current_tab_ == Tab::Agent)
+ reload_agents();
+ });
+
+ connect(&svc, &services::AgentService::error_occurred, this,
+ [this](const QString& context, const QString& message) {
+ if (context != "run_portfolio_analysis" && context != "run_agent_streaming")
+ return;
+ ai_busy_ = agent_busy_ = false;
+ ai_run_->setEnabled(true);
+ agent_run_->setEnabled(true);
+ header_status_->clear();
+ QTextBrowser* target = current_tab_ == Tab::AI ? ai_content_ : agent_content_;
+ render_error(target, QString("Error (%1).\n\n%2").arg(context, message));
+ });
+
+ // If the user edits LLM config while the panel is open, refresh the
+ // is_configured() check on the next run — nothing to do here except
+ // keep a hook for future UI (status badge etc.).
+ connect(&ai_chat::LlmService::instance(), &ai_chat::LlmService::config_changed, this,
+ []() { LOG_INFO("InsightsPanel", "LLM config changed — next run will pick up new settings"); });
+}
+
+void PortfolioInsightsPanel::build_ui() {
+ const QString bg = ui::colors::BG_BASE();
+ const QString surface = ui::colors::BG_SURFACE();
+ const QString hover = ui::colors::BG_HOVER();
+ const QString border = ui::colors::BORDER_MED();
+ const QString border_dim = ui::colors::BORDER_DIM();
+ const QString amber = ui::colors::AMBER();
+ const QString text1 = ui::colors::TEXT_PRIMARY();
+ const QString text2 = ui::colors::TEXT_SECONDARY();
+ const QString text3 = ui::colors::TEXT_TERTIARY();
+
+ // Opaque background — this is the whole fix for the previous overlap bug.
+ setStyleSheet(QString("#PortfolioInsightsPanel { background:%1; border-left:1px solid %2; }")
+ .arg(bg, border));
+
+ auto* root = new QVBoxLayout(this);
+ root->setContentsMargins(0, 0, 0, 0);
+ root->setSpacing(0);
+
+ // ── Header ────────────────────────────────────────────────────────────────
+ auto* header = new QWidget(this);
+ header->setFixedHeight(44);
+ header->setStyleSheet(QString("background:%1; border-bottom:1px solid %2;").arg(surface, border));
+ auto* hl = new QHBoxLayout(header);
+ hl->setContentsMargins(16, 0, 8, 0);
+ hl->setSpacing(8);
+
+ auto* title = new QLabel("PORTFOLIO INSIGHTS");
+ title->setStyleSheet(QString("color:%1; font-size:11px; font-weight:800; letter-spacing:2px;").arg(amber));
+ hl->addWidget(title);
+
+ header_status_ = new QLabel;
+ header_status_->setStyleSheet(QString("color:%1; font-size:10px;").arg(text2));
+ hl->addWidget(header_status_);
+ hl->addStretch();
+
+ auto* close_btn = new QPushButton("×");
+ close_btn->setFixedSize(28, 28);
+ close_btn->setCursor(Qt::PointingHandCursor);
+ close_btn->setToolTip("Close (Esc)");
+ close_btn->setStyleSheet(QString("QPushButton { background:transparent; border:none; color:%1;"
+ " font-size:20px; font-weight:300; }"
+ "QPushButton:hover { color:%2; background:%3; }")
+ .arg(text2, text1, hover));
+ connect(close_btn, &QPushButton::clicked, this, [this]() { hide(); emit close_requested(); });
+ hl->addWidget(close_btn);
+ root->addWidget(header);
+
+ // ── Tab bar ───────────────────────────────────────────────────────────────
+ auto* tab_bar = new QWidget(this);
+ tab_bar->setFixedHeight(36);
+ tab_bar->setStyleSheet(QString("background:%1; border-bottom:1px solid %2;").arg(bg, border_dim));
+ auto* tl = new QHBoxLayout(tab_bar);
+ tl->setContentsMargins(0, 0, 0, 0);
+ tl->setSpacing(0);
+
+ auto make_tab = [&](const QString& txt) {
+ auto* b = new QPushButton(txt);
+ b->setCheckable(true);
+ b->setCursor(Qt::PointingHandCursor);
+ b->setStyleSheet(QString("QPushButton { background:transparent; color:%1; border:none;"
+ " border-bottom:2px solid transparent; padding:8px 0;"
+ " font-size:10px; font-weight:700; letter-spacing:1.5px; }"
+ "QPushButton:checked { color:%2; border-bottom:2px solid %2;"
+ " background:rgba(217,119,6,0.06); }"
+ "QPushButton:hover:!checked { color:%3; }")
+ .arg(text2, amber, text1));
+ return b;
+ };
+ tab_ai_btn_ = make_tab("AI ANALYSIS");
+ tab_agent_btn_ = make_tab("AGENT RUNNER");
+ tab_ai_btn_->setChecked(true);
+ connect(tab_ai_btn_, &QPushButton::clicked, this, [this]() { switch_tab(Tab::AI); });
+ connect(tab_agent_btn_, &QPushButton::clicked, this, [this]() { switch_tab(Tab::Agent); });
+ tl->addWidget(tab_ai_btn_, 1);
+ tl->addWidget(tab_agent_btn_, 1);
+ root->addWidget(tab_bar);
+
+ // ── Pages ─────────────────────────────────────────────────────────────────
+ pages_ = new QStackedWidget(this);
+ pages_->addWidget(build_ai_page());
+ pages_->addWidget(build_agent_page());
+ root->addWidget(pages_, 1);
+}
+
+QWidget* PortfolioInsightsPanel::build_ai_page() {
+ const QString bg = ui::colors::BG_BASE();
+ const QString surface = ui::colors::BG_SURFACE();
+ const QString border_dim = ui::colors::BORDER_DIM();
+ const QString amber = ui::colors::AMBER();
+ const QString text1 = ui::colors::TEXT_PRIMARY();
+ const QString text2 = ui::colors::TEXT_SECONDARY();
+ const QString text3 = ui::colors::TEXT_TERTIARY();
+
+ auto* page = new QWidget;
+ page->setStyleSheet(QString("background:%1;").arg(bg));
+ auto* lay = new QVBoxLayout(page);
+ lay->setContentsMargins(0, 0, 0, 0);
+ lay->setSpacing(0);
+
+ // Config block
+ auto* cfg = new QWidget(page);
+ cfg->setStyleSheet(QString("background:%1; border-bottom:1px solid %2;").arg(surface, border_dim));
+ auto* cl = new QVBoxLayout(cfg);
+ cl->setContentsMargins(16, 12, 16, 12);
+ cl->setSpacing(10);
+
+ auto* label = new QLabel("ANALYSIS TYPE");
+ label->setStyleSheet(QString("color:%1; font-size:9px; font-weight:700; letter-spacing:1.5px;").arg(text3));
+ cl->addWidget(label);
+
+ auto* pill_row = new QHBoxLayout;
+ pill_row->setSpacing(6);
+ auto make_pill = [&](const QString& txt, const QString& id) {
+ auto* p = new QPushButton(txt);
+ p->setCheckable(true);
+ p->setCursor(Qt::PointingHandCursor);
+ p->setFixedHeight(28);
+ p->setStyleSheet(QString("QPushButton { background:%1; color:%2; border:1px solid %3;"
+ " padding:0 14px; font-size:10px; font-weight:700; letter-spacing:1px; }"
+ "QPushButton:checked { background:rgba(217,119,6,0.15); color:%4;"
+ " border:1px solid %4; }"
+ "QPushButton:hover:!checked { color:%5; border:1px solid %5; }")
+ .arg(bg, text2, border_dim, amber, text1));
+ connect(p, &QPushButton::clicked, this, [this, id]() { set_ai_type(id); });
+ pill_row->addWidget(p);
+ return p;
+ };
+ ai_full_ = make_pill("FULL", "full");
+ ai_risk_ = make_pill("RISK", "risk");
+ ai_rebal_ = make_pill("REBALANCE", "rebalance");
+ ai_opport_ = make_pill("OPPS", "opportunities");
+ ai_full_->setChecked(true);
+ pill_row->addStretch();
+ cl->addLayout(pill_row);
+
+ ai_run_ = new QPushButton("RUN FULL ANALYSIS");
+ ai_run_->setCursor(Qt::PointingHandCursor);
+ ai_run_->setFixedHeight(36);
+ ai_run_->setStyleSheet(QString("QPushButton { background:%1; color:%2; border:none;"
+ " font-size:11px; font-weight:700; letter-spacing:2px; }"
+ "QPushButton:hover { background:%3; }"
+ "QPushButton:disabled { background:%4; color:%5; }")
+ .arg(amber, bg, ui::colors::AMBER_DIM(), border_dim, text3));
+ connect(ai_run_, &QPushButton::clicked, this, [this]() { run_ai(true); });
+ cl->addWidget(ai_run_);
+
+ ai_meta_ = new QLabel;
+ ai_meta_->setStyleSheet(QString("color:%1; font-size:9px;").arg(text3));
+ cl->addWidget(ai_meta_);
+
+ lay->addWidget(cfg);
+
+ // Results
+ ai_content_ = new QTextBrowser(page);
+ ai_content_->setOpenExternalLinks(true);
+ ai_content_->setStyleSheet(QString("QTextBrowser { background:%1; color:%2; border:none; padding:16px;"
+ " font-size:12px; }")
+ .arg(bg, text1));
+ lay->addWidget(ai_content_, 1);
+ render_empty(ai_content_, "Select an analysis type and press RUN.\n\n"
+ "FULL — broad review of holdings and allocation.\n"
+ "RISK — concentration, correlation, downside scenarios.\n"
+ "REBALANCE — target weights with rationale.\n"
+ "OPPS — undervalued positions and gaps.");
+ return page;
+}
+
+QWidget* PortfolioInsightsPanel::build_agent_page() {
+ const QString bg = ui::colors::BG_BASE();
+ const QString surface = ui::colors::BG_SURFACE();
+ const QString border_dim = ui::colors::BORDER_DIM();
+ const QString amber = ui::colors::AMBER();
+ const QString text1 = ui::colors::TEXT_PRIMARY();
+ const QString text2 = ui::colors::TEXT_SECONDARY();
+ const QString text3 = ui::colors::TEXT_TERTIARY();
+
+ auto* page = new QWidget;
+ page->setStyleSheet(QString("background:%1;").arg(bg));
+ auto* lay = new QVBoxLayout(page);
+ lay->setContentsMargins(0, 0, 0, 0);
+ lay->setSpacing(0);
+
+ auto* cfg = new QWidget(page);
+ cfg->setStyleSheet(QString("background:%1; border-bottom:1px solid %2;").arg(surface, border_dim));
+ auto* cl = new QVBoxLayout(cfg);
+ cl->setContentsMargins(16, 12, 16, 12);
+ cl->setSpacing(8);
+
+ auto* label = new QLabel("SELECT AGENT");
+ label->setStyleSheet(QString("color:%1; font-size:9px; font-weight:700; letter-spacing:1.5px;").arg(text3));
+ cl->addWidget(label);
+
+ agent_cb_ = new QComboBox;
+ agent_cb_->setFixedHeight(30);
+ agent_cb_->setStyleSheet(QString("QComboBox { background:%1; color:%2; border:1px solid %3;"
+ " padding:0 10px; font-size:11px; }"
+ "QComboBox::drop-down { border:none; width:20px; }"
+ "QComboBox QAbstractItemView { background:%1; color:%2; border:1px solid %3;"
+ " selection-background-color:rgba(217,119,6,0.15); }")
+ .arg(bg, text1, border_dim));
+ connect(agent_cb_, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [this](int) {
+ if (!agent_cb_ || !agent_desc_ || !agent_content_)
+ return;
+ agent_desc_->setText(agent_cb_->currentData(Qt::UserRole + 1).toString());
+ QString id = agent_cb_->currentData().toString();
+ if (agent_cache_.contains(id))
+ render_result(agent_content_, agent_cache_.value(id));
+ else
+ render_empty(agent_content_, "Press RUN to analyze your portfolio with this agent.");
+ });
+ cl->addWidget(agent_cb_);
+
+ agent_desc_ = new QLabel;
+ agent_desc_->setWordWrap(true);
+ agent_desc_->setStyleSheet(QString("color:%1; font-size:10px; line-height:1.5;").arg(text2));
+ cl->addWidget(agent_desc_);
+
+ agent_run_ = new QPushButton("RUN AGENT");
+ agent_run_->setCursor(Qt::PointingHandCursor);
+ agent_run_->setFixedHeight(36);
+ agent_run_->setStyleSheet(QString("QPushButton { background:%1; color:%2; border:none;"
+ " font-size:11px; font-weight:700; letter-spacing:2px; }"
+ "QPushButton:hover { background:%3; }"
+ "QPushButton:disabled { background:%4; color:%5; }")
+ .arg(amber, bg, ui::colors::AMBER_DIM(), border_dim, text3));
+ connect(agent_run_, &QPushButton::clicked, this, [this]() { run_agent(true); });
+ cl->addWidget(agent_run_);
+
+ agent_meta_ = new QLabel;
+ agent_meta_->setStyleSheet(QString("color:%1; font-size:9px;").arg(text3));
+ cl->addWidget(agent_meta_);
+
+ lay->addWidget(cfg);
+
+ agent_content_ = new QTextBrowser(page);
+ agent_content_->setOpenExternalLinks(true);
+ agent_content_->setStyleSheet(QString("QTextBrowser { background:%1; color:%2; border:none; padding:16px;"
+ " font-size:12px; }")
+ .arg(bg, text1));
+ lay->addWidget(agent_content_, 1);
+ render_empty(agent_content_, "Load a saved agent above and press RUN.");
+ return page;
+}
+
+void PortfolioInsightsPanel::set_summary(const portfolio::PortfolioSummary& summary) {
+ if (summary.portfolio.id != last_portfolio_id_) {
+ ai_cache_.clear();
+ agent_cache_.clear();
+ if (ai_content_)
+ render_empty(ai_content_, "Select an analysis type and press RUN.");
+ if (agent_content_)
+ render_empty(agent_content_, "Load a saved agent above and press RUN.");
+ last_portfolio_id_ = summary.portfolio.id;
+ }
+ summary_ = summary;
+}
+
+void PortfolioInsightsPanel::open_tab(Tab tab) {
+ switch_tab(tab);
+ show();
+ raise();
+ setFocus();
+}
+
+void PortfolioInsightsPanel::showEvent(QShowEvent* e) {
+ QWidget::showEvent(e);
+ if (current_tab_ == Tab::Agent)
+ reload_agents();
+}
+
+void PortfolioInsightsPanel::keyPressEvent(QKeyEvent* e) {
+ if (e->key() == Qt::Key_Escape) {
+ hide();
+ emit close_requested();
+ return;
+ }
+ QWidget::keyPressEvent(e);
+}
+
+void PortfolioInsightsPanel::switch_tab(Tab tab) {
+ current_tab_ = tab;
+ tab_ai_btn_->setChecked(tab == Tab::AI);
+ tab_agent_btn_->setChecked(tab == Tab::Agent);
+ pages_->setCurrentIndex(tab == Tab::AI ? 0 : 1);
+ if (tab == Tab::Agent)
+ reload_agents();
+}
+
+void PortfolioInsightsPanel::set_ai_type(const QString& type) {
+ ai_type_ = type;
+ ai_full_->setChecked(type == "full");
+ ai_risk_->setChecked(type == "risk");
+ ai_rebal_->setChecked(type == "rebalance");
+ ai_opport_->setChecked(type == "opportunities");
+
+ QString upper = type.toUpper();
+ if (upper == "OPPORTUNITIES")
+ upper = "OPPS";
+ ai_run_->setText(ai_cache_.contains(type) ? QString("RE-RUN %1 ANALYSIS").arg(upper)
+ : QString("RUN %1 ANALYSIS").arg(upper));
+
+ if (ai_cache_.contains(type))
+ render_result(ai_content_, ai_cache_.value(type));
+ else
+ render_empty(ai_content_, "Press RUN to start this analysis.");
+}
+
+void PortfolioInsightsPanel::reload_agents() {
+ if (!agent_cb_)
+ return;
+ const QString prev = agent_cb_->currentData().toString();
+ agent_cb_->blockSignals(true);
+ agent_cb_->clear();
+
+ // Single source of truth: finagent_core agents from AgentService. We do
+ // NOT fall back to AgentConfigRepository — that table only contains
+ // user-saved overrides (often 0 or 2 rows) which would mislead the user
+ // into thinking only those agents are available.
+ const auto cached = services::AgentService::instance().cached_agents();
+ if (!cached.isEmpty()) {
+ for (const auto& a : cached) {
+ const QString label = a.category.isEmpty()
+ ? a.name
+ : QString("[%1] %2").arg(a.category, a.name);
+ agent_cb_->addItem(label, a.id);
+ agent_cb_->setItemData(agent_cb_->count() - 1, a.description, Qt::UserRole + 1);
+ }
+ } else {
+ // Cache cold — show a disabled "discovering" placeholder and kick
+ // off discovery. agents_discovered will repopulate us when it lands.
+ agent_cb_->addItem("Discovering agents…", "");
+ agent_cb_->setItemData(0, "Loading agents from finagent_core. If this persists, make sure "
+ "Python is installed and open Agent Config for more details.",
+ Qt::UserRole + 1);
+ services::AgentService::instance().discover_agents();
+ }
+
+ int idx = prev.isEmpty() ? 0 : agent_cb_->findData(prev);
+ agent_cb_->setCurrentIndex(idx < 0 ? 0 : idx);
+ agent_cb_->blockSignals(false);
+ if (agent_desc_)
+ agent_desc_->setText(agent_cb_->currentData(Qt::UserRole + 1).toString());
+}
+
+QString PortfolioInsightsPanel::build_portfolio_context() const {
+ QStringList lines;
+ lines << QString("Portfolio: %1 | NAV: %2 %3")
+ .arg(summary_.portfolio.name, summary_.portfolio.currency)
+ .arg(QString::number(summary_.total_market_value, 'f', 2));
+ lines << QString("Total P&L: %1% | Day Change: %2% | Positions: %3")
+ .arg(QString::number(summary_.total_unrealized_pnl_percent, 'f', 2))
+ .arg(QString::number(summary_.total_day_change_percent, 'f', 2))
+ .arg(summary_.total_positions);
+ lines << "";
+ lines << "Holdings:";
+ for (const auto& h : summary_.holdings) {
+ lines << QString(" %1 [%2] qty %3 @ %4 | P&L %5% | wt %6%")
+ .arg(h.symbol, h.sector.isEmpty() ? "Unclassified" : h.sector)
+ .arg(QString::number(h.quantity, 'f', 2))
+ .arg(QString::number(h.current_price, 'f', 2))
+ .arg(QString::number(h.unrealized_pnl_percent, 'f', 2))
+ .arg(QString::number(h.weight, 'f', 1));
+ }
+ return lines.join("\n");
+}
+
+void PortfolioInsightsPanel::run_ai(bool force) {
+ if (ai_busy_ || summary_.holdings.isEmpty())
+ return;
+ if (!force && ai_cache_.contains(ai_type_)) {
+ render_result(ai_content_, ai_cache_.value(ai_type_));
+ return;
+ }
+ auto& llm = ai_chat::LlmService::instance();
+ if (!llm.is_configured()) {
+ render_error(ai_content_,
+ "No LLM configured.\n\nOpen Settings → LLM Configuration, add a provider with an API key, "
+ "then try again. The Agent Config tab shares the same LLM setup.");
+ return;
+ }
+
+ // Serialize the portfolio summary so the Python side can format it however
+ // the analysis_type requires. Keys mirror what finagent_core expects.
+ QJsonArray holdings;
+ for (const auto& h : summary_.holdings) {
+ QJsonObject o;
+ o["symbol"] = h.symbol;
+ o["sector"] = h.sector.isEmpty() ? QStringLiteral("Unclassified") : h.sector;
+ o["quantity"] = h.quantity;
+ o["avg_buy_price"] = h.avg_buy_price;
+ o["current_price"] = h.current_price;
+ o["market_value"] = h.market_value;
+ o["cost_basis"] = h.cost_basis;
+ o["unrealized_pnl"] = h.unrealized_pnl;
+ o["unrealized_pnl_percent"] = h.unrealized_pnl_percent;
+ o["weight"] = h.weight;
+ holdings.append(o);
+ }
+ QJsonObject summary_json;
+ summary_json["name"] = summary_.portfolio.name;
+ summary_json["currency"] = summary_.portfolio.currency;
+ summary_json["total_market_value"] = summary_.total_market_value;
+ summary_json["total_cost_basis"] = summary_.total_cost_basis;
+ summary_json["total_unrealized_pnl"] = summary_.total_unrealized_pnl;
+ summary_json["total_unrealized_pnl_percent"] = summary_.total_unrealized_pnl_percent;
+ summary_json["total_day_change_percent"] = summary_.total_day_change_percent;
+ summary_json["total_positions"] = summary_.total_positions;
+ summary_json["holdings"] = holdings;
+ // Include a plain-text fallback for Python paths that ignore the structured
+ // summary and just forward the prompt verbatim to the LLM.
+ summary_json["context_text"] = build_portfolio_context();
+
+ ai_busy_ = true;
+ ai_pending_type_ = ai_type_;
+ ai_run_->setEnabled(false);
+ header_status_->setText(QString("● running %1…").arg(ai_type_));
+ render_empty(ai_content_, QString("Running %1 analysis through the agent stack…").arg(ai_type_));
+
+ services::AgentService::instance().run_portfolio_analysis(ai_type_, summary_json);
+}
+
+void PortfolioInsightsPanel::run_agent(bool force) {
+ if (agent_busy_ || summary_.holdings.isEmpty())
+ return;
+ const QString agent_id = agent_cb_->currentData().toString();
+ if (agent_id.isEmpty()) {
+ render_error(agent_content_, "No agent selected.\n\nCreate one in the Agent Config screen, then return here.");
+ return;
+ }
+ if (!force && agent_cache_.contains(agent_id)) {
+ render_result(agent_content_, agent_cache_.value(agent_id));
+ return;
+ }
+ auto& llm = ai_chat::LlmService::instance();
+ if (!llm.is_configured()) {
+ render_error(agent_content_,
+ "No LLM configured.\n\nOpen Settings → LLM Configuration, add a provider with an API key, "
+ "then try again.");
+ return;
+ }
+
+ // Resolve the friendly agent name from the cached finagent list (the
+ // canonical source). Fall back to the dropdown label if the cache was
+ // cleared between populate and click.
+ QString agent_name;
+ for (const auto& a : services::AgentService::instance().cached_agents()) {
+ if (a.id == agent_id) {
+ agent_name = a.name;
+ break;
+ }
+ }
+ if (agent_name.isEmpty())
+ agent_name = agent_cb_->currentText();
+
+ // Compose the query that finagent_core will run through the configured
+ // agent: portfolio context first, then a task prompt. The agent's own
+ // system prompt (configured in Agent Config) shapes the style.
+ const QString query = build_portfolio_context() +
+ "\n\nTask: Analyze this portfolio as " + agent_name +
+ ". Provide clear sections, concrete recommendations, and quantify exposures "
+ "where data allows.";
+
+ QJsonObject config;
+ config["agent_id"] = agent_id;
+
+ agent_busy_ = true;
+ agent_streaming_text_.clear();
+ agent_run_->setEnabled(false);
+ header_status_->setText(QString("● running %1…").arg(agent_name));
+ render_empty(agent_content_, QString("Running %1 on this portfolio…").arg(agent_name));
+
+ agent_pending_id_ = agent_id;
+ agent_pending_req_id_ = services::AgentService::instance().run_agent_streaming(query, config);
+}
+
+void PortfolioInsightsPanel::render_result(QTextBrowser* target, const QString& markdown) {
+ if (!target)
+ return;
+ if (markdown.trimmed().isEmpty()) {
+ render_empty(target, "(empty response)");
+ return;
+ }
+ target->setHtml(ui::MarkdownRenderer::render(markdown));
+ target->verticalScrollBar()->setValue(0);
+}
+
+void PortfolioInsightsPanel::render_error(QTextBrowser* target, const QString& message) {
+ if (!target)
+ return;
+ QString safe = message;
+ safe.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace("\n", "<br>");
+ target->setHtml(QString("<div style='color:%1; font-size:12px; line-height:1.55;'>"
+ "<div style='color:%2; font-weight:700; letter-spacing:1px; margin-bottom:8px;'>"
+ "⚠ ERROR</div>%3</div>")
+ .arg(ui::colors::TEXT_PRIMARY(), ui::colors::NEGATIVE(), safe));
+}
+
+void PortfolioInsightsPanel::render_empty(QTextBrowser* target, const QString& hint) {
+ if (!target)
+ return;
+ QString safe = hint;
+ safe.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace("\n", "<br>");
+ target->setHtml(QString("<div style='color:%1; font-size:11px; line-height:1.7; padding-top:8px;'>%2</div>")
+ .arg(ui::colors::TEXT_TERTIARY(), safe));
+}
+
+} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/portfolio/PortfolioInsightsPanel.h b/fincept-qt/src/screens/portfolio/PortfolioInsightsPanel.h
new file mode 100644
index 000000000..45e4e09a4
--- /dev/null
+++ b/fincept-qt/src/screens/portfolio/PortfolioInsightsPanel.h
@@ -0,0 +1,92 @@
+// src/screens/portfolio/PortfolioInsightsPanel.h
+#pragma once
+#include "screens/portfolio/PortfolioTypes.h"
+
+#include <QHash>
+#include <QWidget>
+
+class QComboBox;
+class QLabel;
+class QPushButton;
+class QStackedWidget;
+class QTextBrowser;
+class QVBoxLayout;
+
+namespace fincept::screens {
+
+/// Unified right-hand dock that exposes both AI analysis and Agent Runner in
+/// one coherent surface. Replaces the old PortfolioAiPanel / PortfolioAgentPanel
+/// floating overlays, which clashed with the charts and each other.
+///
+/// The panel is positioned by PortfolioScreen via open_tab(); it fills the
+/// available vertical space below the command bar and anchors to the right
+/// edge. A scrim beneath it dims the rest of the screen so focus is obvious.
+class PortfolioInsightsPanel : public QWidget {
+ Q_OBJECT
+ public:
+ enum class Tab { AI, Agent };
+
+ explicit PortfolioInsightsPanel(QWidget* parent = nullptr);
+
+ void set_summary(const portfolio::PortfolioSummary& summary);
+ void open_tab(Tab tab);
+ void reload_agents();
+
+ signals:
+ void close_requested();
+
+ protected:
+ void keyPressEvent(QKeyEvent* e) override;
+ void showEvent(QShowEvent* e) override;
+
+ private:
+ void build_ui();
+ QWidget* build_ai_page();
+ QWidget* build_agent_page();
+ void switch_tab(Tab tab);
+ void set_ai_type(const QString& type);
+ void run_ai(bool force);
+ void run_agent(bool force);
+ void render_result(QTextBrowser* target, const QString& markdown);
+ void render_error(QTextBrowser* target, const QString& message);
+ void render_empty(QTextBrowser* target, const QString& hint);
+ QString build_portfolio_context() const;
+
+ // Layout
+ QPushButton* tab_ai_btn_ = nullptr;
+ QPushButton* tab_agent_btn_ = nullptr;
+ QStackedWidget* pages_ = nullptr;
+ QLabel* header_status_ = nullptr;
+
+ // AI page
+ QPushButton* ai_full_ = nullptr;
+ QPushButton* ai_risk_ = nullptr;
+ QPushButton* ai_rebal_ = nullptr;
+ QPushButton* ai_opport_ = nullptr;
+ QPushButton* ai_run_ = nullptr;
+ QLabel* ai_meta_ = nullptr;
+ QTextBrowser* ai_content_ = nullptr;
+
+ // Agent page
+ QComboBox* agent_cb_ = nullptr;
+ QLabel* agent_desc_ = nullptr;
+ QPushButton* agent_run_ = nullptr;
+ QLabel* agent_meta_ = nullptr;
+ QTextBrowser* agent_content_ = nullptr;
+
+ // State
+ Tab current_tab_ = Tab::AI;
+ portfolio::PortfolioSummary summary_;
+ QString last_portfolio_id_;
+ QString ai_type_ = "full";
+ bool ai_busy_ = false;
+ bool agent_busy_ = false;
+ QString ai_pending_type_; // analysis_type in flight (for result routing)
+ QString agent_pending_req_id_; // run_agent_streaming request id in flight
+ QString agent_pending_id_; // agent_id matching that request
+ QString agent_streaming_text_; // accumulated tokens for live rendering
+ QHash<QString, QString> ai_cache_; // type -> markdown
+ QHash<QString, QString> agent_cache_; // agent_id -> markdown
+};
+
+} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/portfolio/PortfolioPerfChart.cpp b/fincept-qt/src/screens/portfolio/PortfolioPerfChart.cpp
index b6f0b1911..bf2b69165 100644
--- a/fincept-qt/src/screens/portfolio/PortfolioPerfChart.cpp
+++ b/fincept-qt/src/screens/portfolio/PortfolioPerfChart.cpp
@@ -161,12 +161,13 @@ void PortfolioPerfChart::build_ui() {
period_btns_.append(btn);
}
- // Benchmark toggle
- benchmark_btn_ = new QPushButton("SPY");
- benchmark_btn_->setFixedSize(34, 22);
+ // Benchmark toggle (label updates when set_benchmark_history fires with a
+ // non-SPY symbol — e.g. ^GSPTSE for CAD portfolios).
+ benchmark_btn_ = new QPushButton(benchmark_symbol_);
+ benchmark_btn_->setFixedSize(60, 22);
benchmark_btn_->setCheckable(true);
benchmark_btn_->setCursor(Qt::PointingHandCursor);
- benchmark_btn_->setToolTip("Overlay SPY benchmark (normalised to portfolio start value)");
+ benchmark_btn_->setToolTip("Overlay benchmark index (auto-selected by portfolio currency)");
benchmark_btn_->setStyleSheet(
QString("QPushButton { background:transparent; color:%1; border:1px solid %1;"
" font-size:9px; font-weight:700; border-radius:2px; }"
@@ -180,6 +181,30 @@ void PortfolioPerfChart::build_ui() {
header->addSpacing(6);
header->addWidget(benchmark_btn_);
+ // Indexed-mode toggle: switches the y-axis from currency value to
+ // percent-indexed (base 100). Required for fair benchmark comparison
+ // when the portfolio and benchmark are in different currencies — without
+ // this, comparing CAD NAV against USD SPY closes is meaningless.
+ indexed_btn_ = new QPushButton("%");
+ indexed_btn_->setFixedSize(28, 22);
+ indexed_btn_->setCheckable(true);
+ indexed_btn_->setCursor(Qt::PointingHandCursor);
+ indexed_btn_->setToolTip("Indexed view: rebase portfolio and benchmark to 100 at the start of\n"
+ "the selected period. Use when comparing different currencies.");
+ indexed_btn_->setStyleSheet(
+ QString("QPushButton { background:transparent; color:%1; border:1px solid %1;"
+ " font-size:9px; font-weight:700; border-radius:2px; }"
+ "QPushButton:checked { color:%4; background:%2; border:1px solid %2; }"
+ "QPushButton:hover:!checked { color:%3; border-color:%3; }")
+ .arg(ui::colors::TEXT_TERTIARY(), ui::colors::AMBER(), ui::colors::TEXT_PRIMARY(),
+ ui::colors::BG_BASE()));
+ connect(indexed_btn_, &QPushButton::clicked, this, [this]() {
+ indexed_mode_ = indexed_btn_->isChecked();
+ update_chart();
+ });
+ header->addSpacing(4);
+ header->addWidget(indexed_btn_);
+
layout->addLayout(header);
// Info bar: period change, total return, NAV
@@ -209,6 +234,16 @@ void PortfolioPerfChart::build_ui() {
nav_label_->setStyleSheet(QString("color:%1; font-size:11px; font-weight:600;").arg(ui::colors::WARNING()));
info_bar->addWidget(nav_label_);
+ auto* sep3 = new QLabel("|");
+ sep3->setStyleSheet(QString("color:%1; font-size:11px;").arg(ui::colors::BORDER_MED()));
+ info_bar->addWidget(sep3);
+
+ cost_basis_label_ = new QLabel;
+ cost_basis_label_->setStyleSheet(
+ QString("color:%1; font-size:11px;").arg(ui::colors::TEXT_TERTIARY()));
+ cost_basis_label_->setToolTip("Total cost basis — the dashed horizontal line on the chart.");
+ info_bar->addWidget(cost_basis_label_);
+
info_bar->addStretch();
layout->addLayout(info_bar);
@@ -232,6 +267,10 @@ void PortfolioPerfChart::set_summary(const portfolio::PortfolioSummary& summary)
void PortfolioPerfChart::set_snapshots(const QVector<portfolio::PortfolioSnapshot>& snapshots) {
snapshots_ = snapshots;
+ // Sort once so iso_date_to_ms_utc downstream produces a monotonic series.
+ std::sort(snapshots_.begin(), snapshots_.end(),
+ [](const auto& a, const auto& b) { return a.snapshot_date < b.snapshot_date; });
+ update_period_buttons_enabled();
update_chart();
}
@@ -240,19 +279,73 @@ void PortfolioPerfChart::set_currency(const QString& currency) {
}
void PortfolioPerfChart::set_spy_history(const QStringList& dates, const QVector<double>& closes) {
- spy_dates_ = dates;
+ set_benchmark_history(QStringLiteral("SPY"), dates, closes);
+}
+
+void PortfolioPerfChart::set_benchmark_history(const QString& symbol, const QStringList& dates,
+ const QVector<double>& closes) {
+ benchmark_symbol_ = symbol.isEmpty() ? QStringLiteral("SPY") : symbol;
+ spy_dates_ = dates; // field name kept for back-compat; holds chosen benchmark
spy_closes_ = closes;
+ if (benchmark_btn_)
+ benchmark_btn_->setText(benchmark_symbol_);
if (show_benchmark_)
- update_chart(); // refresh only if overlay is visible
+ update_chart();
}
void PortfolioPerfChart::set_period(const QString& period) {
+ const QString prev = current_period_;
current_period_ = period;
for (auto* btn : period_btns_)
btn->setChecked(btn->text() == period);
+
+ // If the user is asking for a longer window than we have snapshots for,
+ // request a backfill. The owner re-feeds set_snapshots when it lands.
+ if (prev != period && !snapshots_.isEmpty()) {
+ const QDate earliest = QDate::fromString(snapshots_.first().snapshot_date.left(10), Qt::ISODate);
+ const QDate today = QDate::currentDate();
+ const int needed_days = (period == "5Y" || period == "ALL") ? 1825
+ : (period == "1Y" || period == "YTD") ? 365
+ : (period == "3M") ? 95
+ : (period == "1M") ? 32
+ : 10;
+ if (earliest.isValid() && earliest.daysTo(today) < needed_days - 5) {
+ const QString backfill_period =
+ (period == "5Y" || period == "ALL") ? "5y" : "1y";
+ emit backfill_period_requested(backfill_period);
+ }
+ }
update_chart();
}
+qint64 PortfolioPerfChart::iso_date_to_ms_utc(const QString& iso_date) {
+ const QDate d = QDate::fromString(iso_date.left(10), Qt::ISODate);
+ if (!d.isValid())
+ return QDateTime::currentMSecsSinceEpoch();
+ return QDateTime(d, QTime(0, 0), QTimeZone::UTC).toMSecsSinceEpoch();
+}
+
+void PortfolioPerfChart::update_period_buttons_enabled() {
+ if (snapshots_.isEmpty())
+ return;
+ const QDate earliest = QDate::fromString(snapshots_.first().snapshot_date.left(10), Qt::ISODate);
+ const QDate today = QDate::currentDate();
+ const int span_days = earliest.isValid() ? earliest.daysTo(today) : 0;
+ for (auto* btn : period_btns_) {
+ const QString p = btn->text();
+ // Daily snapshots only — 1D needs intraday data we don't capture.
+ bool feasible = true;
+ if (p == "1D")
+ feasible = false; // explicitly unsupported with daily snapshots
+ else if (p == "1W")
+ feasible = span_days >= 5;
+ // Other periods are always allowed: backfill kicks in when clicked.
+ btn->setEnabled(feasible);
+ btn->setToolTip(feasible ? QString()
+ : QStringLiteral("Needs intraday data — daily snapshots only."));
+ }
+}
+
QColor PortfolioPerfChart::chart_color() const {
return summary_.total_unrealized_pnl >= 0 ? QColor(ui::colors::POSITIVE()) : QColor(ui::colors::NEGATIVE());
}
@@ -271,10 +364,15 @@ void PortfolioPerfChart::update_chart() {
period_change_label_->setText("No data");
total_return_label_->clear();
nav_label_->clear();
+ if (cost_basis_label_)
+ cost_basis_label_->clear();
chart_view_->set_series_data({}, currency_);
return;
}
+ const double live_nav = summary_.total_market_value;
+ const double cost_basis = summary_.total_cost_basis;
+
// ── Determine cutoff date from selected period ────────────────────────────
QDate cutoff = QDate::currentDate();
if (current_period_ == "1D")
@@ -289,81 +387,84 @@ void PortfolioPerfChart::update_chart() {
cutoff = QDate(QDate::currentDate().year(), 1, 1);
else if (current_period_ == "1Y")
cutoff = cutoff.addYears(-1);
+ else if (current_period_ == "5Y")
+ cutoff = cutoff.addYears(-5);
else
cutoff = cutoff.addYears(-10); // ALL
- // ── Filter snapshots by period ────────────────────────────────────────────
+ // ── Filter snapshots (already sorted ascending by set_snapshots) ─────────
QVector<portfolio::PortfolioSnapshot> filtered;
+ filtered.reserve(snapshots_.size());
for (const auto& s : snapshots_) {
- QDate d = QDate::fromString(s.snapshot_date.left(10), Qt::ISODate);
+ const QDate d = QDate::fromString(s.snapshot_date.left(10), Qt::ISODate);
if (d.isValid() && d >= cutoff)
filtered.append(s);
}
- // Sort ascending by date
- std::sort(filtered.begin(), filtered.end(),
- [](const auto& a, const auto& b) { return a.snapshot_date < b.snapshot_date; });
+ // ── Build raw NAV series in absolute currency value ──────────────────────
+ QVector<QPointF> nav_pts; // (ms_utc, NAV)
+ nav_pts.reserve(filtered.size() + 1);
+ double period_baseline = 0; // first snapshot value within window
+
+ if (filtered.size() >= 2) {
+ period_baseline = filtered.first().total_value;
+ for (const auto& s : filtered)
+ nav_pts.append(QPointF(static_cast<double>(iso_date_to_ms_utc(s.snapshot_date)),
+ s.total_value));
+ // Pin a final point at "now" so the line meets the live NAV.
+ const qint64 now_ms = QDateTime::currentDateTimeUtc().toMSecsSinceEpoch();
+ if (nav_pts.last().x() < now_ms)
+ nav_pts.append(QPointF(static_cast<double>(now_ms), live_nav));
+ } else {
+ // No real history yet — render a clean cost→NAV reference segment.
+ // (Backfill is auto-triggered on import / first metrics call.)
+ period_baseline = cost_basis > 0 ? cost_basis : live_nav;
+ const qint64 yest = QDateTime::currentDateTimeUtc().addDays(-1).toMSecsSinceEpoch();
+ const qint64 now_ms = QDateTime::currentDateTimeUtc().toMSecsSinceEpoch();
+ nav_pts.append(QPointF(static_cast<double>(yest), period_baseline));
+ nav_pts.append(QPointF(static_cast<double>(now_ms), live_nav));
+ }
- // ── Build chart series ────────────────────────────────────────────────────
- auto* line = new QLineSeries;
+ // ── Period P&L is *always* relative to the period baseline ───────────────
+ const double period_pnl = live_nav - period_baseline;
+ const double period_pnl_pct = period_baseline > 0 ? (period_pnl / period_baseline) * 100.0 : 0.0;
+
+ // ── Convert series to display space (currency value vs. base-100 indexed) ─
+ auto to_display = [&](double v) -> double {
+ if (!indexed_mode_)
+ return v;
+ return period_baseline > 0 ? (v / period_baseline) * 100.0 : 0.0;
+ };
+
+ auto* nav_line = new QLineSeries;
auto* area_upper = new QLineSeries;
auto* area_lower = new QLineSeries;
- double first_val = 0;
- double last_val = summary_.total_market_value;
- double min_val = last_val;
- double max_val = last_val;
-
- if (filtered.size() >= 2) {
- // Real snapshot data
- first_val = filtered.first().total_value;
- for (const auto& s : filtered) {
- QDateTime dt = QDateTime::fromString(s.snapshot_date.left(10), Qt::ISODate);
- if (!dt.isValid())
- dt = QDateTime::currentDateTime();
- const qint64 ms = dt.toMSecsSinceEpoch();
- line->append(ms, s.total_value);
- area_upper->append(ms, s.total_value);
- area_lower->append(ms, first_val);
- min_val = std::min(min_val, s.total_value);
- max_val = std::max(max_val, s.total_value);
- }
- // Append current live value at now
- const qint64 now_ms = QDateTime::currentDateTime().toMSecsSinceEpoch();
- line->append(now_ms, last_val);
- area_upper->append(now_ms, last_val);
- area_lower->append(now_ms, first_val);
- min_val = std::min(min_val, last_val);
- max_val = std::max(max_val, last_val);
- } else {
- // Insufficient real data — show a single cost→NAV segment and a note.
- // Do NOT synthesise fake data points.
- const double cost = summary_.total_cost_basis > 0 ? summary_.total_cost_basis : last_val;
- first_val = cost;
- const qint64 start_ms = QDateTime::currentDateTime().addDays(-1).toMSecsSinceEpoch();
- const qint64 now_ms = QDateTime::currentDateTime().toMSecsSinceEpoch();
- line->append(start_ms, cost);
- line->append(now_ms, last_val);
- area_upper->append(start_ms, cost);
- area_upper->append(now_ms, last_val);
- area_lower->append(start_ms, cost);
- area_lower->append(now_ms, cost);
- min_val = std::min(cost, last_val);
- max_val = std::max(cost, last_val);
-
- // Overlay a note inside the chart area
- period_change_label_->setText(QString("%1 — (no history yet, showing NAV only)").arg(current_period_));
- period_change_label_->setStyleSheet(
- QString("color:%1; font-size:11px; font-weight:500;").arg(ui::colors::TEXT_TERTIARY()));
+ double y_min = std::numeric_limits<double>::max();
+ double y_max = std::numeric_limits<double>::lowest();
+ const double area_baseline_disp = to_display(period_baseline);
+
+ for (const auto& p : nav_pts) {
+ const double y = to_display(p.y());
+ nav_line->append(p.x(), y);
+ area_upper->append(p.x(), y);
+ area_lower->append(p.x(), area_baseline_disp);
+ y_min = std::min(y_min, y);
+ y_max = std::max(y_max, y);
}
- // ── Period P&L from the series endpoints ─────────────────────────────────
- double period_pnl = last_val - first_val;
- double period_pnl_pct = (first_val > 0) ? (period_pnl / first_val) * 100.0 : 0;
+ // Y-axis must always include the cost-basis reference so the user can see
+ // the gap between NAV and cost. Skip in indexed mode where 100 is the line.
+ const double cost_disp = to_display(cost_basis);
+ if (cost_basis > 0) {
+ y_min = std::min(y_min, cost_disp);
+ y_max = std::max(y_max, cost_disp);
+ }
+ y_min = std::min(y_min, area_baseline_disp);
+ y_max = std::max(y_max, area_baseline_disp);
QColor lc = period_pnl >= 0 ? QColor(ui::colors::POSITIVE()) : QColor(ui::colors::NEGATIVE());
- QPen pen(lc, 2);
- line->setPen(pen);
+ nav_line->setPen(QPen(lc, 2));
auto* area = new QAreaSeries(area_upper, area_lower);
QColor fill = lc;
@@ -372,13 +473,26 @@ void PortfolioPerfChart::update_chart() {
area->setPen(Qt::NoPen);
chart->addSeries(area);
- chart->addSeries(line);
+ chart->addSeries(nav_line);
+
+ // ── Cost basis reference line ────────────────────────────────────────────
+ // Skipped in indexed mode (where the period baseline IS the reference at 100).
+ QLineSeries* cost_line = nullptr;
+ if (cost_basis > 0 && !indexed_mode_) {
+ cost_line = new QLineSeries;
+ cost_line->setName("Cost basis");
+ cost_line->append(nav_pts.first().x(), cost_disp);
+ cost_line->append(nav_pts.last().x(), cost_disp);
+ QPen cp(QColor(ui::colors::TEXT_TERTIARY()), 1, Qt::DashLine);
+ cost_line->setPen(cp);
+ chart->addSeries(cost_line);
+ }
// ── Axes ──────────────────────────────────────────────────────────────────
auto* x_axis = new QDateTimeAxis;
if (current_period_ == "1D" || current_period_ == "1W")
x_axis->setFormat("MMM dd");
- else if (current_period_ == "ALL" || current_period_ == "1Y")
+ else if (current_period_ == "ALL" || current_period_ == "5Y" || current_period_ == "1Y")
x_axis->setFormat("MMM yy");
else
x_axis->setFormat("dd MMM");
@@ -389,84 +503,87 @@ void PortfolioPerfChart::update_chart() {
x_axis->setLinePen(QPen(QColor(ui::colors::BORDER_DIM()), 1));
x_axis->setLabelsFont(QFont(ui::fonts::DATA_FAMILY(), 8));
- double padding = std::max((max_val - min_val) * 0.08, max_val * 0.01);
auto* y_axis = new QValueAxis;
- y_axis->setRange(min_val - padding, max_val + padding);
- y_axis->setLabelFormat("%.0f");
+ const double padding = std::max((y_max - y_min) * 0.08, std::abs(y_max) * 0.01);
+ y_axis->setRange(y_min - padding, y_max + padding);
+ y_axis->setLabelFormat(indexed_mode_ ? "%.1f" : "%.0f");
y_axis->setTickCount(5);
y_axis->setLabelsColor(QColor(ui::colors::TEXT_TERTIARY()));
- {
- QPen grid_pen(QColor(ui::colors::BORDER_DIM()), 1, Qt::DotLine);
- y_axis->setGridLinePen(grid_pen);
- }
+ y_axis->setGridLinePen(QPen(QColor(ui::colors::BORDER_DIM()), 1, Qt::DotLine));
y_axis->setMinorGridLineVisible(false);
y_axis->setLinePen(QPen(QColor(ui::colors::BORDER_DIM()), 1));
y_axis->setLabelsFont(QFont(ui::fonts::DATA_FAMILY(), 8));
chart->addAxis(x_axis, Qt::AlignBottom);
chart->addAxis(y_axis, Qt::AlignLeft);
- line->attachAxis(x_axis);
- line->attachAxis(y_axis);
+ nav_line->attachAxis(x_axis);
+ nav_line->attachAxis(y_axis);
area->attachAxis(x_axis);
area->attachAxis(y_axis);
+ if (cost_line) {
+ cost_line->attachAxis(x_axis);
+ cost_line->attachAxis(y_axis);
+ }
- // ── Feed crosshair with series points ────────────────────────────────────
- chart_view_->set_series_data(line->points(), currency_);
+ chart_view_->set_series_data(nav_line->points(), indexed_mode_ ? QStringLiteral("idx") : currency_);
- // ── Benchmark overlay (real SPY prices normalised to first_val) ──────────
- if (show_benchmark_ && line->count() >= 2) {
+ // ── Benchmark overlay ─────────────────────────────────────────────────────
+ if (show_benchmark_ && nav_line->count() >= 2) {
if (spy_dates_.isEmpty() || spy_closes_.isEmpty()) {
- // Real data not yet available — show a note; do NOT draw fake curve
- nav_label_->setText(nav_label_->text() + QString(" | SPY: loading…"));
+ nav_label_->setText(nav_label_->text() +
+ QString(" | %1: loading…").arg(benchmark_symbol_));
} else {
- // Filter SPY history to the same date window as the portfolio line
- const QPointF& p0 = line->at(0);
- const QPointF& pN = line->at(line->count() - 1);
- const QDate start_date = QDateTime::fromMSecsSinceEpoch(static_cast<qint64>(p0.x())).date();
- const QDate end_date = QDateTime::fromMSecsSinceEpoch(static_cast<qint64>(pN.x())).date();
-
- // Find first SPY close on or after start_date to use as base
- double spy_base = 0.0;
+ const QDate start_date = QDateTime::fromMSecsSinceEpoch(
+ static_cast<qint64>(nav_line->at(0).x()), QTimeZone::UTC).date();
+ const QDate end_date = QDateTime::fromMSecsSinceEpoch(
+ static_cast<qint64>(nav_line->at(nav_line->count() - 1).x()), QTimeZone::UTC).date();
+
+ // First benchmark close on/after period start = base for normalisation.
+ double bench_base = 0.0;
int base_idx = -1;
for (int i = 0; i < spy_dates_.size(); ++i) {
const QDate d = QDate::fromString(spy_dates_[i], Qt::ISODate);
if (d >= start_date) {
- spy_base = spy_closes_[i];
+ bench_base = spy_closes_[i];
base_idx = i;
break;
}
}
- if (base_idx >= 0 && spy_base > 1e-6) {
- auto* spy_line = new QLineSeries;
- double spy_min = first_val, spy_max = first_val;
-
+ if (base_idx >= 0 && bench_base > 1e-6) {
+ auto* bench_line = new QLineSeries;
+ double b_min = std::numeric_limits<double>::max();
+ double b_max = std::numeric_limits<double>::lowest();
for (int i = base_idx; i < spy_dates_.size(); ++i) {
const QDate d = QDate::fromString(spy_dates_[i], Qt::ISODate);
if (d > end_date)
break;
- const qint64 ms = QDateTime(d, QTime(), QTimeZone::UTC).toMSecsSinceEpoch();
- const double val = first_val * (spy_closes_[i] / spy_base);
- spy_line->append(ms, val);
- spy_min = std::min(spy_min, val);
- spy_max = std::max(spy_max, val);
+ const qint64 ms = iso_date_to_ms_utc(spy_dates_[i]);
+ // In currency mode, scale benchmark to start at the
+ // portfolio's period baseline so they share the y-axis
+ // visually. In indexed mode, base-100 normalisation puts
+ // them on the same dimensionless scale.
+ const double bench_disp = indexed_mode_
+ ? (spy_closes_[i] / bench_base) * 100.0
+ : period_baseline * (spy_closes_[i] / bench_base);
+ bench_line->append(ms, bench_disp);
+ b_min = std::min(b_min, bench_disp);
+ b_max = std::max(b_max, bench_disp);
}
- if (spy_line->count() >= 2) {
- QPen spy_pen(QColor(ui::colors::CYAN()), 1, Qt::DashLine);
- spy_line->setPen(spy_pen);
- spy_line->setName("SPY");
- chart->addSeries(spy_line);
- spy_line->attachAxis(x_axis);
- spy_line->attachAxis(y_axis);
-
- // Extend y-axis if SPY goes outside portfolio range
- const double new_min = std::min(min_val, spy_min);
- const double new_max = std::max(max_val, spy_max);
- const double new_pad = std::max((new_max - new_min) * 0.08, new_max * 0.01);
+ if (bench_line->count() >= 2) {
+ QPen bp(QColor(ui::colors::CYAN()), 1, Qt::DashLine);
+ bench_line->setPen(bp);
+ bench_line->setName(benchmark_symbol_);
+ chart->addSeries(bench_line);
+ bench_line->attachAxis(x_axis);
+ bench_line->attachAxis(y_axis);
+ const double new_min = std::min(y_min, b_min);
+ const double new_max = std::max(y_max, b_max);
+ const double new_pad = std::max((new_max - new_min) * 0.08, std::abs(new_max) * 0.01);
y_axis->setRange(new_min - new_pad, new_max + new_pad);
} else {
- delete spy_line;
+ delete bench_line;
}
}
}
@@ -474,20 +591,28 @@ void PortfolioPerfChart::update_chart() {
// ── Info labels ───────────────────────────────────────────────────────────
const char* pnl_color = period_pnl_pct >= 0 ? ui::colors::POSITIVE : ui::colors::NEGATIVE;
-
period_change_label_->setText(QString("%1 %2%3%")
.arg(current_period_)
.arg(period_pnl_pct >= 0 ? "+" : "")
.arg(QString::number(period_pnl_pct, 'f', 2)));
- period_change_label_->setStyleSheet(QString("color:%1; font-size:11px; font-weight:600;").arg(pnl_color));
+ period_change_label_->setStyleSheet(
+ QString("color:%1; font-size:11px; font-weight:600;").arg(pnl_color));
- double total_pnl_pct = summary_.total_unrealized_pnl_percent;
+ const double total_pnl_pct = summary_.total_unrealized_pnl_percent;
const char* total_color = total_pnl_pct >= 0 ? ui::colors::POSITIVE : ui::colors::NEGATIVE;
total_return_label_->setText(
QString("TOTAL %1%2%").arg(total_pnl_pct >= 0 ? "+" : "").arg(QString::number(total_pnl_pct, 'f', 2)));
- total_return_label_->setStyleSheet(QString("color:%1; font-size:14px; font-weight:700;").arg(total_color));
-
- nav_label_->setText(QString("NAV %1 %2").arg(currency_).arg(QString::number(last_val, 'f', 2)));
+ total_return_label_->setStyleSheet(
+ QString("color:%1; font-size:14px; font-weight:700;").arg(total_color));
+
+ nav_label_->setText(QString("NAV %1 %2").arg(currency_).arg(QString::number(live_nav, 'f', 2)));
+ if (cost_basis_label_) {
+ if (cost_basis > 0)
+ cost_basis_label_->setText(
+ QString("COST %1 %2").arg(currency_).arg(QString::number(cost_basis, 'f', 2)));
+ else
+ cost_basis_label_->clear();
+ }
}
void PortfolioPerfChart::refresh_theme() {
diff --git a/fincept-qt/src/screens/portfolio/PortfolioPerfChart.h b/fincept-qt/src/screens/portfolio/PortfolioPerfChart.h
index 1467759e2..9d547641f 100644
--- a/fincept-qt/src/screens/portfolio/PortfolioPerfChart.h
+++ b/fincept-qt/src/screens/portfolio/PortfolioPerfChart.h
@@ -42,28 +42,45 @@ class PortfolioPerfChart : public QWidget {
void set_summary(const portfolio::PortfolioSummary& summary);
void set_snapshots(const QVector<portfolio::PortfolioSnapshot>& snapshots);
void set_currency(const QString& currency);
- /// Feed real SPY close prices for benchmark overlay.
+ /// Feed real benchmark closes for the overlay. The symbol is shown on the
+ /// toggle button and used to disambiguate currencies in indexed mode.
+ void set_benchmark_history(const QString& symbol, const QStringList& dates,
+ const QVector<double>& closes);
+ /// Legacy shim — same as set_benchmark_history("SPY", dates, closes).
void set_spy_history(const QStringList& dates, const QVector<double>& closes);
void refresh_theme();
+ signals:
+ /// Emitted when the user clicks a period button that requires backfilling
+ /// (e.g. 5Y when only 1Y is cached). Owner can call
+ /// PortfolioService::backfill_history(portfolio_id, period) in response.
+ void backfill_period_requested(QString period);
+
private:
void build_ui();
void update_chart();
void set_period(const QString& period);
+ void update_period_buttons_enabled();
QColor chart_color() const;
+ /// Convert a UTC ISO date string to ms since epoch (UTC midnight).
+ /// Centralised so portfolio and benchmark series share the same time axis.
+ static qint64 iso_date_to_ms_utc(const QString& iso_date);
// Period selector buttons
QVector<QPushButton*> period_btns_;
QString current_period_ = "1M";
- // Benchmark toggle button
+ // Benchmark toggle + indexed-mode toggle
QPushButton* benchmark_btn_ = nullptr;
+ QPushButton* indexed_btn_ = nullptr;
bool show_benchmark_ = false;
+ bool indexed_mode_ = false; // false = currency value, true = base-100 indexed
// Info bar
QLabel* period_change_label_ = nullptr;
QLabel* total_return_label_ = nullptr;
QLabel* nav_label_ = nullptr;
+ QLabel* cost_basis_label_ = nullptr;
// Chart
CrosshairChartView* chart_view_ = nullptr;
@@ -73,7 +90,8 @@ class PortfolioPerfChart : public QWidget {
QVector<portfolio::PortfolioSnapshot> snapshots_;
QString currency_ = "USD";
- // SPY benchmark history (real prices)
+ // Benchmark history — symbol may differ from "SPY" depending on currency
+ QString benchmark_symbol_ = "SPY";
QStringList spy_dates_;
QVector<double> spy_closes_;
};
diff --git a/fincept-qt/src/screens/portfolio/PortfolioScreen.cpp b/fincept-qt/src/screens/portfolio/PortfolioScreen.cpp
index e06269735..4c7d36735 100644
--- a/fincept-qt/src/screens/portfolio/PortfolioScreen.cpp
+++ b/fincept-qt/src/screens/portfolio/PortfolioScreen.cpp
@@ -2,8 +2,7 @@
#include "screens/portfolio/PortfolioScreen.h"
#include "core/session/ScreenStateManager.h"
-#include "screens/portfolio/PortfolioAgentPanel.h"
-#include "screens/portfolio/PortfolioAiPanel.h"
+#include "screens/portfolio/PortfolioInsightsPanel.h"
#include "screens/portfolio/PortfolioBlotter.h"
#include "screens/portfolio/PortfolioCommandBar.h"
#include "screens/portfolio/PortfolioDetailWrapper.h"
@@ -28,6 +27,7 @@
#include <QKeyEvent>
#include <QLabel>
#include <QLineEdit>
+#include <QMessageBox>
#include <QPropertyAnimation>
#include <QPushButton>
#include <QSplitter>
@@ -61,18 +61,40 @@ PortfolioScreen::PortfolioScreen(QWidget* parent) : QWidget(parent) {
sector_panel_->set_correlation(matrix);
});
connect(&svc, &services::PortfolioService::spy_history_loaded, this,
- [this](QStringList dates, QVector<double> closes) {
- if (perf_chart_)
- perf_chart_->set_spy_history(dates, closes);
- // Recompute metrics now that SPY data is available for OLS beta
+ [this](QStringList /*dates*/, QVector<double> /*closes*/) {
+ // Recompute metrics now that SPY data is available for OLS beta.
+ // The chart consumes the per-symbol benchmark_history_loaded
+ // signal below — SPY here is purely a Beta signal.
if (summary_loaded_)
services::PortfolioService::instance().compute_metrics(current_summary_);
});
+ connect(&svc, &services::PortfolioService::benchmark_history_loaded, this,
+ [this](QString symbol, QStringList dates, QVector<double> closes) {
+ // Hand the chart whichever benchmark was actually requested
+ // (SPY for USD, ^GSPTSE for CAD, etc.) so the overlay label and
+ // currency-normalisation are correct.
+ if (!perf_chart_ || !summary_loaded_)
+ return;
+ const QString want = services::PortfolioService::default_benchmark_for_currency(
+ current_summary_.portfolio.currency);
+ if (symbol != want)
+ return; // ignore the secondary SPY-for-Beta fetch
+ perf_chart_->set_benchmark_history(symbol, dates, closes);
+ });
connect(&svc, &services::PortfolioService::risk_free_rate_loaded, this, [this](double /*rate*/) {
// Recompute metrics with updated risk-free rate for Sharpe
if (summary_loaded_)
services::PortfolioService::instance().compute_metrics(current_summary_);
});
+ // After yfinance backfill lands, refresh snapshots and metrics so Beta/MDD
+ // populate without requiring a manual refresh.
+ connect(&svc, &services::PortfolioService::history_backfilled, this,
+ [this](QString portfolio_id, int point_count) {
+ if (point_count <= 0 || !summary_loaded_ || portfolio_id != selected_id_)
+ return;
+ services::PortfolioService::instance().load_snapshots(portfolio_id);
+ services::PortfolioService::instance().compute_metrics(current_summary_);
+ });
// Restore persisted refresh interval (P17)
{
@@ -170,6 +192,24 @@ void PortfolioScreen::build_ui() {
command_bar_->set_detail_view(std::nullopt);
update_content_state();
});
+ // AnalyticsSectorsView → filter the main blotter by the clicked sector.
+ // Mirrors the PortfolioSectorPanel::sector_selected wiring below so both
+ // entry points behave identically.
+ connect(detail_wrapper_, &PortfolioDetailWrapper::sector_selected, this, [this](const QString& sector) {
+ if (!blotter_)
+ return;
+ if (sector.isEmpty()) {
+ blotter_->set_sector_filter({});
+ return;
+ }
+ QStringList matching;
+ for (const auto& h : current_summary_.holdings) {
+ QString h_sector = h.sector.isEmpty() ? QStringLiteral("Unclassified") : h.sector;
+ if (h_sector == sector)
+ matching.append(h.symbol);
+ }
+ blotter_->set_sector_filter(matching);
+ });
// FFN view
ffn_view_ = new PortfolioFFNView(this);
@@ -190,9 +230,19 @@ void PortfolioScreen::build_ui() {
status_bar_ = new PortfolioStatusBar(this);
layout->addWidget(status_bar_);
- // ── Floating panels (overlay, not in layout) ─────────────────────────────
- ai_panel_ = new PortfolioAiPanel(this);
- agent_panel_ = new PortfolioAgentPanel(this);
+ // ── Insights dock (unified AI + Agent right-hand panel) ─────────────────
+ // Sits above all other widgets as a child overlay, positioned in
+ // resizeEvent so it tracks window size. A scrim behind it dims the rest
+ // of the screen so the user knows focus has moved.
+ insights_scrim_ = new QWidget(this);
+ insights_scrim_->setObjectName("PortfolioInsightsScrim");
+ insights_scrim_->setStyleSheet("#PortfolioInsightsScrim { background:rgba(0,0,0,0.45); }");
+ insights_scrim_->hide();
+
+ insights_panel_ = new PortfolioInsightsPanel(this);
+ connect(insights_panel_, &PortfolioInsightsPanel::close_requested, this, [this]() {
+ insights_scrim_->hide();
+ });
// Wire export/import/AI/Agent signals from CommandBar
connect(command_bar_, &PortfolioCommandBar::export_csv_requested, this, [this]() {
@@ -219,30 +269,48 @@ void PortfolioScreen::build_ui() {
services::PortfolioService::instance().import_json(dlg.file_path(), dlg.mode(), dlg.merge_target_id());
}
});
- connect(command_bar_, &PortfolioCommandBar::ai_analyze_requested, this, [this]() {
+ auto open_insights = [this](PortfolioInsightsPanel::Tab tab) {
if (!summary_loaded_)
return;
- ai_panel_->set_summary(current_summary_);
- const int top = command_bar_->height() + 6;
- ai_panel_->move(width() - 492, top);
- ai_panel_->setFixedHeight(height() - top - 60);
- ai_panel_->show_panel();
- });
- connect(command_bar_, &PortfolioCommandBar::agent_run_requested, this, [this]() {
- if (!summary_loaded_)
- return;
- agent_panel_->set_summary(current_summary_);
- const int top = command_bar_->height() + 6;
- agent_panel_->move(width() - 984, top);
- agent_panel_->setFixedHeight(height() - top - 60);
- agent_panel_->show_panel();
- });
+ insights_panel_->set_summary(current_summary_);
+ const int top = command_bar_->height();
+ const int bottom_reserve = status_bar_ ? status_bar_->height() : 0;
+ const int h = qMax(200, height() - top - bottom_reserve);
+ insights_scrim_->setGeometry(0, top, width(), h);
+ insights_scrim_->show();
+ insights_scrim_->raise();
+ insights_panel_->setFixedHeight(h);
+ insights_panel_->move(width() - insights_panel_->width(), top);
+ insights_panel_->raise();
+ insights_panel_->open_tab(tab);
+ };
+ connect(command_bar_, &PortfolioCommandBar::ai_analyze_requested, this,
+ [open_insights]() { open_insights(PortfolioInsightsPanel::Tab::AI); });
+ connect(command_bar_, &PortfolioCommandBar::agent_run_requested, this,
+ [open_insights]() { open_insights(PortfolioInsightsPanel::Tab::Agent); });
// Wire import completion
connect(&services::PortfolioService::instance(), &services::PortfolioService::import_complete, this,
[this](portfolio::ImportResult result) {
- if (!result.portfolio_id.isEmpty())
- on_portfolio_selected(result.portfolio_id);
+ if (result.portfolio_id.isEmpty()) {
+ QString detail = result.errors.isEmpty()
+ ? QString("Import failed with no details.")
+ : result.errors.join("\n");
+ QMessageBox::warning(this, "Portfolio Import Failed",
+ "Could not import the portfolio.\n\n" + detail +
+ "\n\nExpected format:\n"
+ "{\n"
+ " \"portfolio_name\": \"My Portfolio\",\n"
+ " \"currency\": \"USD\",\n"
+ " \"owner\": \"...\",\n"
+ " \"transactions\": [\n"
+ " {\"date\": \"YYYY-MM-DD\", \"symbol\": \"AAPL\", \"type\": \"BUY\",\n"
+ " \"quantity\": 10, \"price\": 150.0}\n"
+ " ]\n"
+ "}");
+ return;
+ }
+ on_portfolio_selected(result.portfolio_id);
});
}
@@ -582,8 +650,18 @@ void PortfolioScreen::on_summary_loaded(portfolio::PortfolioSummary summary) {
services::PortfolioService::instance().fetch_correlation(syms);
}
- // Fetch SPY benchmark history for perf chart overlay
- services::PortfolioService::instance().fetch_spy_history("1y");
+ // Fetch benchmark history for perf chart overlay. Use the portfolio's
+ // currency to pick a sensible default index (TSX for CAD, SPY for USD,
+ // FTSE for GBP, …). We also always fetch SPY itself because Beta in
+ // compute_metrics() regresses against SPY regardless of currency.
+ {
+ auto& svc = services::PortfolioService::instance();
+ const QString bench = services::PortfolioService::default_benchmark_for_currency(
+ summary.portfolio.currency);
+ svc.fetch_benchmark_history(bench, "1y");
+ if (bench != QStringLiteral("SPY"))
+ svc.fetch_benchmark_history("SPY", "1y");
+ }
// Fetch live risk-free rate (DGS10) for Sharpe computation — cached 24h
services::PortfolioService::instance().fetch_risk_free_rate();
@@ -722,6 +800,15 @@ QWidget* PortfolioScreen::build_main_view() {
top_split->setStyleSheet(QString("QSplitter::handle { background:%1; }").arg(ui::colors::BORDER_DIM()));
perf_chart_ = new PortfolioPerfChart;
+ // Trigger backfill when the user clicks a period that needs more history
+ // than we have cached. PortfolioService re-emits history_backfilled when
+ // done, which routes back through the chart via load_snapshots.
+ connect(perf_chart_, &PortfolioPerfChart::backfill_period_requested, this,
+ [this](const QString& period) {
+ if (selected_id_.isEmpty())
+ return;
+ services::PortfolioService::instance().backfill_history(selected_id_, period);
+ });
sector_panel_ = new PortfolioSectorPanel;
connect(sector_panel_, &PortfolioSectorPanel::sector_selected, this, [this](const QString& sector) {
if (sector.isEmpty()) {
@@ -730,7 +817,8 @@ QWidget* PortfolioScreen::build_main_view() {
}
QStringList matching;
for (const auto& h : current_summary_.holdings) {
- if (PortfolioSectorPanel::infer_sector(h.symbol) == sector)
+ QString h_sector = h.sector.isEmpty() ? QStringLiteral("Unclassified") : h.sector;
+ if (h_sector == sector)
matching.append(h.symbol);
}
blotter_->set_sector_filter(matching);
@@ -1016,6 +1104,20 @@ void PortfolioScreen::animate_order_panel_in() {
void PortfolioScreen::resizeEvent(QResizeEvent* event) {
QWidget::resizeEvent(event);
reposition_order_panel();
+
+ // Keep the insights dock (and its scrim) glued to the right edge when
+ // the window is resized.
+ if (insights_panel_ && command_bar_) {
+ const int top = command_bar_->height();
+ const int bottom_reserve = status_bar_ ? status_bar_->height() : 0;
+ const int h = qMax(200, height() - top - bottom_reserve);
+ if (insights_scrim_ && insights_scrim_->isVisible())
+ insights_scrim_->setGeometry(0, top, width(), h);
+ if (insights_panel_->isVisible()) {
+ insights_panel_->setFixedHeight(h);
+ insights_panel_->move(width() - insights_panel_->width(), top);
+ }
+ }
}
const portfolio::HoldingWithQuote* PortfolioScreen::find_holding(const QString& symbol) const {
diff --git a/fincept-qt/src/screens/portfolio/PortfolioScreen.h b/fincept-qt/src/screens/portfolio/PortfolioScreen.h
index e9c9f5a63..41791233c 100644
--- a/fincept-qt/src/screens/portfolio/PortfolioScreen.h
+++ b/fincept-qt/src/screens/portfolio/PortfolioScreen.h
@@ -26,8 +26,7 @@ class PortfolioTxnPanel;
class PortfolioOrderPanel;
class PortfolioDetailWrapper;
class PortfolioFFNView;
-class PortfolioAiPanel;
-class PortfolioAgentPanel;
+class PortfolioInsightsPanel;
class PortfolioScreen : public QWidget, public IStatefulScreen {
Q_OBJECT
@@ -96,8 +95,8 @@ class PortfolioScreen : public QWidget, public IStatefulScreen {
PortfolioOrderPanel* order_panel_ = nullptr;
PortfolioDetailWrapper* detail_wrapper_ = nullptr;
PortfolioFFNView* ffn_view_ = nullptr;
- PortfolioAiPanel* ai_panel_ = nullptr;
- PortfolioAgentPanel* agent_panel_ = nullptr;
+ PortfolioInsightsPanel* insights_panel_ = nullptr;
+ QWidget* insights_scrim_ = nullptr;
// State
QVector<portfolio::Portfolio> portfolios_;
diff --git a/fincept-qt/src/screens/portfolio/PortfolioSectorPanel.cpp b/fincept-qt/src/screens/portfolio/PortfolioSectorPanel.cpp
index 1e4f6fc54..5793b22c1 100644
--- a/fincept-qt/src/screens/portfolio/PortfolioSectorPanel.cpp
+++ b/fincept-qt/src/screens/portfolio/PortfolioSectorPanel.cpp
@@ -42,492 +42,6 @@ QColor PortfolioSectorPanel::sector_color(int index) {
return kSectorColors[index % 16];
}
-QString PortfolioSectorPanel::infer_sector(const QString& sym) {
- const QString s = sym.toUpper();
-
- // ── Exact symbol map (300+ common tickers) ───────────────────────────────
- static const QHash<QString, QString> known = {
- // Technology
- {"AAPL", "Technology"},
- {"MSFT", "Technology"},
- {"GOOGL", "Technology"},
- {"GOOG", "Technology"},
- {"AMZN", "Technology"},
- {"NVDA", "Technology"},
- {"META", "Technology"},
- {"AVGO", "Technology"},
- {"ORCL", "Technology"},
- {"CRM", "Technology"},
- {"ADBE", "Technology"},
- {"CSCO", "Technology"},
- {"AMD", "Technology"},
- {"INTC", "Technology"},
- {"QCOM", "Technology"},
- {"TXN", "Technology"},
- {"IBM", "Technology"},
- {"AMAT", "Technology"},
- {"MU", "Technology"},
- {"LRCX", "Technology"},
- {"KLAC", "Technology"},
- {"SNPS", "Technology"},
- {"CDNS", "Technology"},
- {"ADI", "Technology"},
- {"MCHP", "Technology"},
- {"NXPI", "Technology"},
- {"STX", "Technology"},
- {"WDC", "Technology"},
- {"HPQ", "Technology"},
- {"DELL", "Technology"},
- {"ACN", "Technology"},
- {"INTU", "Technology"},
- {"NOW", "Technology"},
- {"SNOW", "Technology"},
- {"DDOG", "Technology"},
- {"ZS", "Technology"},
- {"CRWD", "Technology"},
- {"PANW", "Technology"},
- {"FTNT", "Technology"},
- {"NET", "Technology"},
- {"OKTA", "Technology"},
- {"MDB", "Technology"},
- {"TEAM", "Technology"},
- {"ATLASSIAN", "Technology"},
- {"SHOP", "Technology"},
- {"UBER", "Technology"},
- {"LYFT", "Technology"},
- {"ABNB", "Technology"},
- {"PLTR", "Technology"},
- {"RBLX", "Technology"},
- {"U", "Technology"},
- {"TWLO", "Technology"},
- {"ZM", "Technology"},
- {"DOCUSIGN", "Technology"},
- {"COIN", "Technology"},
- {"HOOD", "Technology"},
- {"APP", "Technology"},
- {"APPF", "Technology"},
- {"GTLB", "Technology"},
- {"PATH", "Technology"},
- // Communication
- {"NFLX", "Communication"},
- {"DIS", "Communication"},
- {"CMCSA", "Communication"},
- {"T", "Communication"},
- {"VZ", "Communication"},
- {"TMUS", "Communication"},
- {"CHTR", "Communication"},
- {"WBD", "Communication"},
- {"PARA", "Communication"},
- {"FOXA", "Communication"},
- {"FOX", "Communication"},
- {"MTCH", "Communication"},
- {"PINS", "Communication"},
- {"SNAP", "Communication"},
- {"RDDT", "Communication"},
- {"SPOT", "Communication"},
- {"LYV", "Communication"},
- {"WMG", "Communication"},
- // Consumer Cyclical
- {"TSLA", "Consumer Cyclical"},
- {"AMZN", "Consumer Cyclical"},
- {"HD", "Consumer Cyclical"},
- {"LOW", "Consumer Cyclical"},
- {"TGT", "Consumer Cyclical"},
- {"BKNG", "Consumer Cyclical"},
- {"MAR", "Consumer Cyclical"},
- {"HLT", "Consumer Cyclical"},
- {"GM", "Consumer Cyclical"},
- {"F", "Consumer Cyclical"},
- {"STLA", "Consumer Cyclical"},
- {"NKE", "Consumer Cyclical"},
- {"SBUX", "Consumer Cyclical"},
- {"MCD", "Consumer Cyclical"},
- {"YUM", "Consumer Cyclical"},
- {"CMG", "Consumer Cyclical"},
- {"DPZ", "Consumer Cyclical"},
- {"ROST", "Consumer Cyclical"},
- {"TJX", "Consumer Cyclical"},
- {"EBAY", "Consumer Cyclical"},
- {"ETSY", "Consumer Cyclical"},
- {"W", "Consumer Cyclical"},
- {"RH", "Consumer Cyclical"},
- {"DHI", "Consumer Cyclical"},
- {"LEN", "Consumer Cyclical"},
- {"PHM", "Consumer Cyclical"},
- {"TOL", "Consumer Cyclical"},
- {"MGM", "Consumer Cyclical"},
- {"WYNN", "Consumer Cyclical"},
- {"LVS", "Consumer Cyclical"},
- {"CCL", "Consumer Cyclical"},
- {"RCL", "Consumer Cyclical"},
- {"NCLH", "Consumer Cyclical"},
- {"UAL", "Consumer Cyclical"},
- {"DAL", "Consumer Cyclical"},
- {"AAL", "Consumer Cyclical"},
- {"LUV", "Consumer Cyclical"},
- {"EXPE", "Consumer Cyclical"},
- // Consumer Defensive
- {"WMT", "Consumer Defensive"},
- {"PG", "Consumer Defensive"},
- {"KO", "Consumer Defensive"},
- {"PEP", "Consumer Defensive"},
- {"COST", "Consumer Defensive"},
- {"PM", "Consumer Defensive"},
- {"MO", "Consumer Defensive"},
- {"MDLZ", "Consumer Defensive"},
- {"KHC", "Consumer Defensive"},
- {"GIS", "Consumer Defensive"},
- {"K", "Consumer Defensive"},
- {"CPB", "Consumer Defensive"},
- {"SJM", "Consumer Defensive"},
- {"HSY", "Consumer Defensive"},
- {"CAG", "Consumer Defensive"},
- {"CL", "Consumer Defensive"},
- {"CHD", "Consumer Defensive"},
- {"KMB", "Consumer Defensive"},
- {"EL", "Consumer Defensive"},
- {"ULTA", "Consumer Defensive"},
- // Healthcare
- {"JNJ", "Healthcare"},
- {"UNH", "Healthcare"},
- {"LLY", "Healthcare"},
- {"ABBV", "Healthcare"},
- {"MRK", "Healthcare"},
- {"PFE", "Healthcare"},
- {"TMO", "Healthcare"},
- {"ABT", "Healthcare"},
- {"DHR", "Healthcare"},
- {"BMY", "Healthcare"},
- {"AMGN", "Healthcare"},
- {"GILD", "Healthcare"},
- {"ISRG", "Healthcare"},
- {"SYK", "Healthcare"},
- {"BSX", "Healthcare"},
- {"MDT", "Healthcare"},
- {"BDX", "Healthcare"},
- {"EW", "Healthcare"},
- {"DXCM", "Healthcare"},
- {"ALGN", "Healthcare"},
- {"HCA", "Healthcare"},
- {"HUM", "Healthcare"},
- {"CI", "Healthcare"},
- {"CVS", "Healthcare"},
- {"MCK", "Healthcare"},
- {"ABC", "Healthcare"},
- {"CAH", "Healthcare"},
- {"BIIB", "Healthcare"},
- {"REGN", "Healthcare"},
- {"VRTX", "Healthcare"},
- {"ILMN", "Healthcare"},
- {"MRNA", "Healthcare"},
- {"BNTX", "Healthcare"},
- {"IQV", "Healthcare"},
- {"A", "Healthcare"},
- {"WAT", "Healthcare"},
- // Financial Services
- {"JPM", "Financial Services"},
- {"BAC", "Financial Services"},
- {"WFC", "Financial Services"},
- {"GS", "Financial Services"},
- {"MS", "Financial Services"},
- {"C", "Financial Services"},
- {"AXP", "Financial Services"},
- {"BLK", "Financial Services"},
- {"SCHW", "Financial Services"},
- {"BRK-B", "Financial Services"},
- {"BRK-A", "Financial Services"},
- {"V", "Financial Services"},
- {"MA", "Financial Services"},
- {"PYPL", "Financial Services"},
- {"SQ", "Financial Services"},
- {"FIS", "Financial Services"},
- {"FI", "Financial Services"},
- {"GPN", "Financial Services"},
- {"ALLY", "Financial Services"},
- {"COF", "Financial Services"},
- {"DFS", "Financial Services"},
- {"USB", "Financial Services"},
- {"PNC", "Financial Services"},
- {"TFC", "Financial Services"},
- {"MTB", "Financial Services"},
- {"RF", "Financial Services"},
- {"KEY", "Financial Services"},
- {"CFG", "Financial Services"},
- {"FITB", "Financial Services"},
- {"HBAN", "Financial Services"},
- {"STT", "Financial Services"},
- {"BK", "Financial Services"},
- {"ICE", "Financial Services"},
- {"CME", "Financial Services"},
- {"CBOE", "Financial Services"},
- {"NDAQ", "Financial Services"},
- {"MCO", "Financial Services"},
- {"SPGI", "Financial Services"},
- {"MMC", "Financial Services"},
- {"AJG", "Financial Services"},
- {"AON", "Financial Services"},
- {"PRU", "Financial Services"},
- {"MET", "Financial Services"},
- {"AFL", "Financial Services"},
- {"ALL", "Financial Services"},
- {"PGR", "Financial Services"},
- {"CB", "Financial Services"},
- {"TRV", "Financial Services"},
- {"HIG", "Financial Services"},
- {"AIG", "Financial Services"},
- // Energy
- {"XOM", "Energy"},
- {"CVX", "Energy"},
- {"COP", "Energy"},
- {"EOG", "Energy"},
- {"SLB", "Energy"},
- {"PXD", "Energy"},
- {"OXY", "Energy"},
- {"MPC", "Energy"},
- {"PSX", "Energy"},
- {"VLO", "Energy"},
- {"WMB", "Energy"},
- {"KMI", "Energy"},
- {"ET", "Energy"},
- {"EPD", "Energy"},
- {"BKR", "Energy"},
- {"HAL", "Energy"},
- {"DVN", "Energy"},
- {"FANG", "Energy"},
- {"HES", "Energy"},
- {"APA", "Energy"},
- {"MRO", "Energy"},
- {"NOG", "Energy"},
- // Utilities
- {"NEE", "Utilities"},
- {"DUK", "Utilities"},
- {"SO", "Utilities"},
- {"D", "Utilities"},
- {"AEP", "Utilities"},
- {"EXC", "Utilities"},
- {"XEL", "Utilities"},
- {"ES", "Utilities"},
- {"WEC", "Utilities"},
- {"AWK", "Utilities"},
- {"ED", "Utilities"},
- {"PPL", "Utilities"},
- {"FE", "Utilities"},
- {"EIX", "Utilities"},
- {"PEG", "Utilities"},
- {"ETR", "Utilities"},
- {"CMS", "Utilities"},
- {"ATO", "Utilities"},
- {"NI", "Utilities"},
- {"OGE", "Utilities"},
- // Industrials
- {"GE", "Industrials"},
- {"HON", "Industrials"},
- {"UPS", "Industrials"},
- {"BA", "Industrials"},
- {"CAT", "Industrials"},
- {"DE", "Industrials"},
- {"LMT", "Industrials"},
- {"RTX", "Industrials"},
- {"NOC", "Industrials"},
- {"GD", "Industrials"},
- {"LHX", "Industrials"},
- {"HII", "Industrials"},
- {"MMM", "Industrials"},
- {"EMR", "Industrials"},
- {"ETN", "Industrials"},
- {"PH", "Industrials"},
- {"ROK", "Industrials"},
- {"DOV", "Industrials"},
- {"AME", "Industrials"},
- {"IEX", "Industrials"},
- {"FDX", "Industrials"},
- {"CSX", "Industrials"},
- {"UNP", "Industrials"},
- {"NSC", "Industrials"},
- {"DAL", "Industrials"},
- {"WM", "Industrials"},
- {"RSG", "Industrials"},
- {"GWW", "Industrials"},
- {"FAST", "Industrials"},
- {"GNRC", "Industrials"},
- {"IR", "Industrials"},
- {"XYL", "Industrials"},
- // Real Estate
- {"PLD", "Real Estate"},
- {"AMT", "Real Estate"},
- {"CCI", "Real Estate"},
- {"EQIX", "Real Estate"},
- {"PSA", "Real Estate"},
- {"SPG", "Real Estate"},
- {"O", "Real Estate"},
- {"WELL", "Real Estate"},
- {"DLR", "Real Estate"},
- {"VTR", "Real Estate"},
- {"AVB", "Real Estate"},
- {"EQR", "Real Estate"},
- {"MAA", "Real Estate"},
- {"UDR", "Real Estate"},
- {"ESS", "Real Estate"},
- {"CPT", "Real Estate"},
- {"NNN", "Real Estate"},
- {"STAG", "Real Estate"},
- {"ARE", "Real Estate"},
- {"BXP", "Real Estate"},
- // Basic Materials
- {"LIN", "Basic Materials"},
- {"APD", "Basic Materials"},
- {"SHW", "Basic Materials"},
- {"ECL", "Basic Materials"},
- {"DD", "Basic Materials"},
- {"DOW", "Basic Materials"},
- {"LYB", "Basic Materials"},
- {"CF", "Basic Materials"},
- {"MOS", "Basic Materials"},
- {"NEM", "Basic Materials"},
- {"FCX", "Basic Materials"},
- {"AA", "Basic Materials"},
- {"NUE", "Basic Materials"},
- {"STLD", "Basic Materials"},
- {"CLF", "Basic Materials"},
- {"X", "Basic Materials"},
- {"RS", "Basic Materials"},
- // ETFs / Index funds
- {"SPY", "ETF/Index"},
- {"QQQ", "ETF/Index"},
- {"IWM", "ETF/Index"},
- {"DIA", "ETF/Index"},
- {"VTI", "ETF/Index"},
- {"VOO", "ETF/Index"},
- {"VEA", "ETF/Index"},
- {"VWO", "ETF/Index"},
- {"GLD", "ETF/Index"},
- {"SLV", "ETF/Index"},
- {"IAU", "ETF/Index"},
- {"USO", "ETF/Index"},
- {"TLT", "ETF/Index"},
- {"IEF", "ETF/Index"},
- {"SHY", "ETF/Index"},
- {"AGG", "ETF/Index"},
- {"BND", "ETF/Index"},
- {"HYG", "ETF/Index"},
- {"LQD", "ETF/Index"},
- {"EMB", "ETF/Index"},
- {"XLK", "ETF/Index"},
- {"XLF", "ETF/Index"},
- {"XLV", "ETF/Index"},
- {"XLE", "ETF/Index"},
- {"XLI", "ETF/Index"},
- {"XLY", "ETF/Index"},
- {"XLP", "ETF/Index"},
- {"XLU", "ETF/Index"},
- {"XLB", "ETF/Index"},
- {"XLRE", "ETF/Index"},
- {"XLC", "ETF/Index"},
- {"ARKK", "ETF/Index"},
- {"ARKW", "ETF/Index"},
- {"ARKG", "ETF/Index"},
- // Crypto
- {"BTC-USD", "Cryptocurrency"},
- {"ETH-USD", "Cryptocurrency"},
- {"BNB-USD", "Cryptocurrency"},
- {"SOL-USD", "Cryptocurrency"},
- {"XRP-USD", "Cryptocurrency"},
- {"ADA-USD", "Cryptocurrency"},
- {"AVAX-USD", "Cryptocurrency"},
- {"DOGE-USD", "Cryptocurrency"},
- {"DOT-USD", "Cryptocurrency"},
- {"MATIC-USD", "Cryptocurrency"},
- {"LINK-USD", "Cryptocurrency"},
- {"LTC-USD", "Cryptocurrency"},
- {"UNI-USD", "Cryptocurrency"},
- {"ATOM-USD", "Cryptocurrency"},
- {"NEAR-USD", "Cryptocurrency"},
- {"ALGO-USD", "Cryptocurrency"},
- {"XLM-USD", "Cryptocurrency"},
- {"VET-USD", "Cryptocurrency"},
- // Indian markets (NSE/BSE)
- {"RELIANCE.NS", "Energy"},
- {"TCS.NS", "Technology"},
- {"INFY.NS", "Technology"},
- {"HDFCBANK.NS", "Financial Services"},
- {"ICICIBANK.NS", "Financial Services"},
- {"SBIN.NS", "Financial Services"},
- {"AXISBANK.NS", "Financial Services"},
- {"KOTAKBANK.NS", "Financial Services"},
- {"BAJFINANCE.NS", "Financial Services"},
- {"WIPRO.NS", "Technology"},
- {"HCLTECH.NS", "Technology"},
- {"TECHM.NS", "Technology"},
- {"LTIM.NS", "Technology"},
- {"PERSISTENT.NS", "Technology"},
- {"SUNPHARMA.NS", "Healthcare"},
- {"CIPLA.NS", "Healthcare"},
- {"DRREDDY.NS", "Healthcare"},
- {"DIVISLAB.NS", "Healthcare"},
- {"APOLLOHOSP.NS", "Healthcare"},
- {"HINDUNILVR.NS", "Consumer Defensive"},
- {"ITC.NS", "Consumer Defensive"},
- {"NESTLEIND.NS", "Consumer Defensive"},
- {"BRITANNIA.NS", "Consumer Defensive"},
- {"TITAN.NS", "Consumer Cyclical"},
- {"MARUTI.NS", "Consumer Cyclical"},
- {"TATAMOTORS.NS", "Consumer Cyclical"},
- {"M&M.NS", "Consumer Cyclical"},
- {"BAJAJ-AUTO.NS", "Consumer Cyclical"},
- {"HEROMOTOCO.NS", "Consumer Cyclical"},
- {"ADANIENT.NS", "Industrials"},
- {"ADANIPORTS.NS", "Industrials"},
- {"POWERGRID.NS", "Utilities"},
- {"NTPC.NS", "Utilities"},
- {"ONGC.NS", "Energy"},
- {"BPCL.NS", "Energy"},
- {"IOC.NS", "Energy"},
- {"COAL.NS", "Basic Materials"},
- {"JSWSTEEL.NS", "Basic Materials"},
- {"TATASTEEL.NS", "Basic Materials"},
- {"HINDALCO.NS", "Basic Materials"},
- {"GRASIM.NS", "Basic Materials"},
- {"ULTRACEMCO.NS", "Basic Materials"},
- {"ACC.NS", "Basic Materials"},
- {"LT.NS", "Industrials"},
- {"SIEMENS.NS", "Industrials"},
- {"ABB.NS", "Industrials"},
- {"BHARTIARTL.NS", "Communication"},
- {"IDEA.NS", "Communication"},
- };
-
- auto it = known.find(s);
- if (it != known.end())
- return *it;
-
- // ── Suffix / pattern inference ────────────────────────────────────────────
- // Crypto: ends with -USD, -USDT, -BTC, -ETH
- if (s.endsWith("-USD") || s.endsWith("-USDT") || s.endsWith("-BTC") || s.endsWith("-ETH"))
- return "Cryptocurrency";
-
- // Indian market suffix
- if (s.endsWith(".NS") || s.endsWith(".BO"))
- return "Other (India)";
-
- // London
- if (s.endsWith(".L"))
- return "Other (UK)";
-
- // European
- if (s.endsWith(".DE") || s.endsWith(".PA") || s.endsWith(".MI") || s.endsWith(".AS"))
- return "Other (Europe)";
-
- // Bond ETF pattern
- if (s.startsWith("TLT") || s.startsWith("AGG") || s.startsWith("BND") || s.contains("BOND") || s.contains("TREAS"))
- return "Fixed Income";
-
- // Commodity pattern
- if (s.contains("OIL") || s.contains("GOLD") || s.contains("SILV") || s.contains("CORN") || s.contains("WHEAT"))
- return "Commodities";
-
- return "Other";
-}
-
PortfolioSectorPanel::PortfolioSectorPanel(QWidget* parent) : QWidget(parent) {
build_ui();
}
@@ -641,7 +155,7 @@ void PortfolioSectorPanel::update_donut() {
QHash<QString, int> sector_counts;
for (const auto& h : holdings_) {
- QString sector = infer_sector(h.symbol);
+ QString sector = h.sector.isEmpty() ? QStringLiteral("Unclassified") : h.sector;
sector_weights[sector] += h.weight;
sector_pnl[sector] += h.unrealized_pnl;
sector_counts[sector]++;
diff --git a/fincept-qt/src/screens/portfolio/PortfolioSectorPanel.h b/fincept-qt/src/screens/portfolio/PortfolioSectorPanel.h
index 44ca5c9c1..2c00cb025 100644
--- a/fincept-qt/src/screens/portfolio/PortfolioSectorPanel.h
+++ b/fincept-qt/src/screens/portfolio/PortfolioSectorPanel.h
@@ -20,9 +20,8 @@ class PortfolioSectorPanel : public QWidget {
/// Feed real pairwise Pearson correlation matrix (key = "SYM1|SYM2").
void set_correlation(const QHash<QString, double>& matrix);
- // Sector utilities — public so callers can map symbols to sectors
+ // Sector utilities — public so callers can map indices to colors
static QColor sector_color(int index);
- static QString infer_sector(const QString& symbol);
signals:
/// Emitted when the user clicks a pie slice. Empty string = clear filter.
diff --git a/fincept-qt/src/screens/portfolio/PortfolioTypes.h b/fincept-qt/src/screens/portfolio/PortfolioTypes.h
index c6647e654..02c934bd9 100644
--- a/fincept-qt/src/screens/portfolio/PortfolioTypes.h
+++ b/fincept-qt/src/screens/portfolio/PortfolioTypes.h
@@ -28,6 +28,7 @@ struct PortfolioAsset {
double avg_buy_price = 0;
QString first_purchase_date;
QString last_updated;
+ QString sector; // empty = not yet resolved; filled from import JSON or SectorResolver
};
struct Transaction {
@@ -50,6 +51,7 @@ struct HoldingWithQuote {
QString symbol;
double quantity = 0;
double avg_buy_price = 0;
+ QString sector;
// Live market data
double current_price = 0;
diff --git a/fincept-qt/src/screens/portfolio/views/AnalyticsSectorsView.cpp b/fincept-qt/src/screens/portfolio/views/AnalyticsSectorsView.cpp
index b223580e5..970d3223d 100644
--- a/fincept-qt/src/screens/portfolio/views/AnalyticsSectorsView.cpp
+++ b/fincept-qt/src/screens/portfolio/views/AnalyticsSectorsView.cpp
@@ -4,10 +4,18 @@
#include "ui/theme/Theme.h"
#include <QChart>
+#include <QChartView>
+#include <QFrame>
#include <QGridLayout>
#include <QHBoxLayout>
#include <QHeaderView>
+#include <QLabel>
+#include <QLocale>
+#include <QPainter>
#include <QPieSeries>
+#include <QScrollArea>
+#include <QTabWidget>
+#include <QTableWidget>
#include <QVBoxLayout>
#include <algorithm>
@@ -15,128 +23,347 @@
namespace fincept::screens {
-static const QColor kSectorPalette[] = {
- QColor("#0891b2"), QColor("#16a34a"), QColor("#d97706"), QColor("#ca8a04"), QColor("#9333ea"), QColor("#84cc16"),
- QColor("#0d9488"), QColor("#f97316"), QColor("#60a5fa"), QColor("#f43f5e"), QColor("#a78bfa"), QColor("#fbbf24"),
+namespace {
+
+// Balanced 16-color palette — same hues used by PortfolioSectorPanel so the
+// two sector views share the same colour language.
+const QColor kSectorPalette[] = {
+ QColor("#0891b2"), QColor("#16a34a"), QColor("#d97706"), QColor("#ca8a04"),
+ QColor("#9333ea"), QColor("#84cc16"), QColor("#0d9488"), QColor("#f97316"),
+ QColor("#60a5fa"), QColor("#f43f5e"), QColor("#a78bfa"), QColor("#fbbf24"),
QColor("#2dd4bf"), QColor("#fb923c"), QColor("#818cf8"), QColor("#e879f9"),
};
-QColor AnalyticsSectorsView::sector_color(int index) {
- return kSectorPalette[index % 16];
+// Solid coloured rectangle used as a legend swatch / table colour dot.
+class Swatch : public QWidget {
+ public:
+ Swatch(QColor c, int w, int h, QWidget* parent = nullptr) : QWidget(parent), color_(c) {
+ setFixedSize(w, h);
+ }
+ protected:
+ void paintEvent(QPaintEvent*) override {
+ QPainter p(this);
+ p.fillRect(rect(), color_);
+ }
+ private:
+ QColor color_;
+};
+
+// Forwards mouse clicks on a card into a sector_selected emission on the
+// parent view. Lives at file scope so MOC doesn't choke on local classes.
+class SectorCardClickForwarder : public QObject {
+ public:
+ SectorCardClickForwarder(class AnalyticsSectorsView* owner, QString sector, QObject* parent)
+ : QObject(parent), owner_(owner), sector_(std::move(sector)) {}
+ protected:
+ bool eventFilter(QObject* obj, QEvent* ev) override;
+ private:
+ class AnalyticsSectorsView* owner_;
+ QString sector_;
+};
+
+QString verdict_for_hhi(double hhi) {
+ // HHI convention uses fractions of 10,000; we use percent-squared so
+ // divide by 100 to get the standard range. 1500-2500 = moderate, 2500+ = concentrated.
+ if (hhi < 1500) return QStringLiteral("Diversified");
+ if (hhi < 2500) return QStringLiteral("Balanced");
+ return QStringLiteral("Concentrated");
}
-QString AnalyticsSectorsView::infer_sector(const QString& symbol) {
- static const QHash<QString, QString> known = {
- {"AAPL", "Technology"},
- {"MSFT", "Technology"},
- {"GOOGL", "Technology"},
- {"AMZN", "Technology"},
- {"NVDA", "Technology"},
- {"META", "Technology"},
- {"TSLA", "Consumer Cyclical"},
- {"JPM", "Financial Services"},
- {"JNJ", "Healthcare"},
- {"UNH", "Healthcare"},
- {"PFE", "Healthcare"},
- {"XOM", "Energy"},
- {"CVX", "Energy"},
- {"V", "Financial Services"},
- {"MA", "Financial Services"},
- {"WMT", "Consumer Defensive"},
- {"DIS", "Communication"},
- {"SPY", "US Equity"},
- {"QQQ", "US Equity"},
- {"BTC-USD", "Cryptocurrency"},
- {"ETH-USD", "Cryptocurrency"},
- };
- auto it = known.find(symbol.toUpper());
- return it != known.end() ? *it : "Other";
+QString verdict_for_top3(double pct) {
+ if (pct < 50.0) return QStringLiteral("Diversified");
+ if (pct < 75.0) return QStringLiteral("Balanced");
+ return QStringLiteral("Concentrated");
+}
+
+QColor verdict_color(const QString& verdict) {
+ if (verdict == QStringLiteral("Diversified")) return QColor(ui::colors::POSITIVE());
+ if (verdict == QStringLiteral("Balanced")) return QColor(ui::colors::AMBER());
+ return QColor(ui::colors::NEGATIVE());
+}
+
+} // namespace
+
+// ============================================================================
+// AnalyticsSectorsView
+// ============================================================================
+
+QColor AnalyticsSectorsView::sector_color(int index) {
+ return kSectorPalette[index % (sizeof(kSectorPalette) / sizeof(kSectorPalette[0]))];
}
AnalyticsSectorsView::AnalyticsSectorsView(QWidget* parent) : QWidget(parent) {
build_ui();
}
+QString AnalyticsSectorsView::format_money(double v) const {
+ QLocale loc = QLocale::system();
+ QString body = loc.toString(v, 'f', 2);
+ return currency_.isEmpty() ? body : QString("%1 %2").arg(currency_, body);
+}
+
+QString AnalyticsSectorsView::format_pct(double v, bool signed_) {
+ QString body = QString::number(v, 'f', 2) + QStringLiteral("%");
+ if (signed_ && v > 0)
+ return QStringLiteral("+") + body;
+ return body;
+}
+
void AnalyticsSectorsView::build_ui() {
- auto* layout = new QVBoxLayout(this);
- layout->setContentsMargins(0, 0, 0, 0);
+ setStyleSheet(QString("background:%1;").arg(ui::colors::BG_BASE()));
+
+ auto* root = new QVBoxLayout(this);
+ root->setContentsMargins(0, 0, 0, 0);
+ root->setSpacing(0);
tabs_ = new QTabWidget;
tabs_->setDocumentMode(true);
- tabs_->setStyleSheet(QString("QTabWidget::pane { border:0; background:%1; }"
- "QTabBar::tab { background:%2; color:%3; padding:8px 18px; border:0;"
- " border-bottom:2px solid transparent; font-size:10px; font-weight:700;"
- " letter-spacing:1px; text-transform:uppercase; }"
- "QTabBar::tab:selected { color:%4; border-bottom:2px solid %4; }"
- "QTabBar::tab:hover { color:%5; }")
- .arg(ui::colors::BG_BASE(), ui::colors::BG_SURFACE(), ui::colors::TEXT_SECONDARY(),
- ui::colors::AMBER(), ui::colors::TEXT_PRIMARY()));
-
- // ── Overview tab ─────────────────────────────────────────────────────────
- auto* overview_w = new QWidget(this);
- auto* overview_layout = new QHBoxLayout(overview_w);
- overview_layout->setContentsMargins(12, 8, 12, 8);
- overview_layout->setSpacing(16);
+ tabs_->setStyleSheet(
+ QString("QTabWidget::pane { border:0; background:%1; }"
+ "QTabBar::tab { background:%2; color:%3; padding:8px 18px; border:0;"
+ " border-bottom:2px solid transparent; font-size:%6px; font-weight:700;"
+ " letter-spacing:1px; text-transform:uppercase; }"
+ "QTabBar::tab:selected { color:%4; border-bottom:2px solid %4;"
+ " background:rgba(217,119,6,0.08); }"
+ "QTabBar::tab:hover:!selected { color:%5; }")
+ .arg(ui::colors::BG_BASE(), ui::colors::BG_SURFACE(), ui::colors::TEXT_SECONDARY(),
+ ui::colors::AMBER(), ui::colors::TEXT_PRIMARY())
+ .arg(ui::fonts::font_px(-3)));
+
+ tabs_->addTab(build_overview_tab(), "OVERVIEW");
+ tabs_->addTab(build_correlation_tab(), "CORRELATION");
+ root->addWidget(tabs_);
+}
+QWidget* AnalyticsSectorsView::build_overview_tab() {
+ auto* scroll = new QScrollArea;
+ scroll->setWidgetResizable(true);
+ scroll->setFrameShape(QFrame::NoFrame);
+ scroll->setStyleSheet(QString("QScrollArea { background:%1; border:none; }"
+ "QScrollBar:vertical { width:6px; background:%1; }"
+ "QScrollBar::handle:vertical { background:%2; min-height:20px; }")
+ .arg(ui::colors::BG_BASE(), ui::colors::BORDER_DIM()));
+
+ auto* page = new QWidget;
+ page->setStyleSheet(QString("background:%1;").arg(ui::colors::BG_BASE()));
+ auto* col = new QVBoxLayout(page);
+ col->setContentsMargins(16, 14, 16, 14);
+ col->setSpacing(14);
+
+ const QString text1 = ui::colors::TEXT_PRIMARY();
+ const QString text2 = ui::colors::TEXT_SECONDARY();
+ const QString text3 = ui::colors::TEXT_TERTIARY();
+ const QString border = ui::colors::BORDER_DIM();
+ const QString surface = ui::colors::BG_SURFACE();
+ const QString amber = ui::colors::AMBER();
+
+ // ── KPI strip ────────────────────────────────────────────────────────────
+ auto* kpi = new QWidget(page);
+ kpi->setStyleSheet(QString("background:%1; border:1px solid %2;").arg(surface, border));
+ auto* kpi_lay = new QHBoxLayout(kpi);
+ kpi_lay->setContentsMargins(18, 10, 18, 10);
+ kpi_lay->setSpacing(28);
+
+ auto make_kpi = [&](const QString& label, QLabel*& out_value) {
+ auto* box = new QVBoxLayout;
+ box->setSpacing(2);
+ auto* l = new QLabel(label);
+ l->setStyleSheet(QString("color:%1; font-size:%2px; font-weight:700; letter-spacing:1.5px;")
+ .arg(text3).arg(ui::fonts::font_px(-4)));
+ box->addWidget(l);
+ out_value = new QLabel("—");
+ out_value->setStyleSheet(QString("color:%1; font-size:%2px; font-weight:700;")
+ .arg(text1).arg(ui::fonts::font_px(2)));
+ box->addWidget(out_value);
+ kpi_lay->addLayout(box);
+ };
+ make_kpi("SECTORS", kpi_sectors_);
+ make_kpi("POSITIONS", kpi_positions_);
+ make_kpi("MARKET VALUE", kpi_market_value_);
+ make_kpi("P&L", kpi_pnl_);
+ kpi_lay->addStretch();
+ col->addWidget(kpi);
+
+ // ── Donut + sector table row ─────────────────────────────────────────────
+ auto* main_row = new QHBoxLayout;
+ main_row->setSpacing(16);
+
+ // Donut card
+ auto* donut_card = new QWidget(page);
+ donut_card->setStyleSheet(QString("background:%1; border:1px solid %2;").arg(surface, border));
+ donut_card->setFixedWidth(320);
+ auto* donut_lay = new QVBoxLayout(donut_card);
+ donut_lay->setContentsMargins(14, 14, 14, 14);
+ donut_lay->setSpacing(8);
+
+ auto* donut_title = new QLabel("SECTOR ALLOCATION");
+ donut_title->setStyleSheet(QString("color:%1; font-size:%2px; font-weight:700; letter-spacing:1.5px;")
+ .arg(text3).arg(ui::fonts::font_px(-4)));
+ donut_lay->addWidget(donut_title);
+
+ // Chart itself
auto* chart = new QChart;
chart->setBackgroundBrush(Qt::transparent);
chart->setMargins(QMargins(0, 0, 0, 0));
chart->legend()->setVisible(false);
chart->setAnimationOptions(QChart::NoAnimation);
-
- sector_chart_ = new QChartView(chart);
- sector_chart_->setRenderHint(QPainter::Antialiasing);
- sector_chart_->setFixedSize(240, 240);
- sector_chart_->setStyleSheet("border:none; background:transparent;");
- overview_layout->addWidget(sector_chart_);
+ donut_view_ = new QChartView(chart);
+ donut_view_->setRenderHint(QPainter::Antialiasing);
+ donut_view_->setFixedHeight(220);
+ donut_view_->setStyleSheet("border:none; background:transparent;");
+
+ // Overlay label at the centre of the donut. The chart widget is in a
+ // vertical stack here; we stack the label on top of the chart using a
+ // QWidget parented to the chart view.
+ donut_center_ = new QLabel(donut_view_);
+ donut_center_->setAlignment(Qt::AlignCenter);
+ donut_center_->setStyleSheet(QString("background:transparent; color:%1;"
+ "font-size:%2px; font-weight:700; letter-spacing:.5px;")
+ .arg(text1).arg(ui::fonts::font_px(-1)));
+
+ donut_lay->addWidget(donut_view_);
+
+ // Legend
+ legend_container_ = new QWidget(donut_card);
+ legend_container_->setStyleSheet("background:transparent;");
+ auto* legend_lay = new QVBoxLayout(legend_container_);
+ legend_lay->setContentsMargins(0, 4, 0, 0);
+ legend_lay->setSpacing(4);
+ donut_lay->addWidget(legend_container_);
+ donut_lay->addStretch();
+
+ main_row->addWidget(donut_card);
+
+ // Sector table card
+ auto* table_card = new QWidget(page);
+ table_card->setStyleSheet(QString("background:%1; border:1px solid %2;").arg(surface, border));
+ auto* table_lay = new QVBoxLayout(table_card);
+ table_lay->setContentsMargins(14, 14, 14, 14);
+ table_lay->setSpacing(8);
+
+ auto* table_title = new QLabel("SECTOR BREAKDOWN");
+ table_title->setStyleSheet(QString("color:%1; font-size:%2px; font-weight:700; letter-spacing:1.5px;")
+ .arg(text3).arg(ui::fonts::font_px(-4)));
+ table_lay->addWidget(table_title);
sector_table_ = new QTableWidget;
- sector_table_->setColumnCount(5);
- sector_table_->setHorizontalHeaderLabels({"SECTOR", "HOLDINGS", "WEIGHT", "P&L", "ALLOCATION"});
- sector_table_->setSelectionMode(QAbstractItemView::NoSelection);
+ sector_table_->setColumnCount(7);
+ sector_table_->setHorizontalHeaderLabels(
+ {"", "SECTOR", "POS", "MKT VAL", "WT", "P&L", "P&L%"});
+ sector_table_->setSelectionBehavior(QAbstractItemView::SelectRows);
+ sector_table_->setSelectionMode(QAbstractItemView::SingleSelection);
sector_table_->setEditTriggers(QAbstractItemView::NoEditTriggers);
sector_table_->setShowGrid(false);
sector_table_->verticalHeader()->setVisible(false);
- sector_table_->horizontalHeader()->setStretchLastSection(true);
- sector_table_->setStyleSheet(QString("QTableWidget { background:%1; color:%2; border:none; font-size:11px; }"
- "QTableWidget::item { padding:4px 8px; border-bottom:1px solid %3; }"
- "QHeaderView::section { background:%4; color:%5; border:none;"
- " border-bottom:2px solid %6; padding:4px 8px; font-size:9px;"
- " font-weight:700; letter-spacing:0.5px; }")
- .arg(ui::colors::BG_BASE(), ui::colors::TEXT_PRIMARY(), ui::colors::BORDER_DIM(),
- ui::colors::BG_SURFACE(), ui::colors::TEXT_SECONDARY(), ui::colors::AMBER()));
- overview_layout->addWidget(sector_table_, 1);
-
- tabs_->addTab(overview_w, "OVERVIEW");
-
- // ── Analytics tab ────────────────────────────────────────────────────────
- analytics_panel_ = new QWidget(this);
- analytics_panel_->setStyleSheet(QString("background:%1;").arg(ui::colors::BG_BASE()));
- tabs_->addTab(analytics_panel_, "ANALYTICS");
-
- // ── Correlation tab ──────────────────────────────────────────────────────
- corr_panel_ = new QWidget(this);
- corr_panel_->setStyleSheet(QString("background:%1;").arg(ui::colors::BG_BASE()));
- tabs_->addTab(corr_panel_, "CORRELATION");
+ sector_table_->horizontalHeader()->setStretchLastSection(false);
+ sector_table_->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Stretch);
+ sector_table_->setStyleSheet(
+ QString("QTableWidget { background:%1; color:%2; border:none;"
+ " font-family:%3; font-size:%4px; gridline-color:transparent; }"
+ "QTableWidget::item { padding:6px 8px; border-bottom:1px solid %5; }"
+ "QTableWidget::item:selected { background:rgba(217,119,6,0.10); color:%2; }"
+ "QHeaderView::section { background:%6; color:%2; border:none;"
+ " border-bottom:1px solid %7; padding:6px 8px;"
+ " font-size:%8px; font-weight:700; letter-spacing:1px; }")
+ .arg(surface, text1, ui::fonts::DATA_FAMILY)
+ .arg(ui::fonts::font_px(-2))
+ .arg(border, ui::colors::BG_BASE(), amber)
+ .arg(ui::fonts::font_px(-4)));
+ sector_table_->setColumnWidth(0, 14);
+ sector_table_->setColumnWidth(2, 50);
+ sector_table_->setColumnWidth(3, 130);
+ sector_table_->setColumnWidth(4, 70);
+ sector_table_->setColumnWidth(5, 110);
+ sector_table_->setColumnWidth(6, 80);
+ connect(sector_table_, &QTableWidget::cellClicked, this, [this](int row, int) {
+ auto* item = sector_table_->item(row, 1);
+ if (item)
+ emit sector_selected(item->text());
+ });
+ table_lay->addWidget(sector_table_);
+
+ main_row->addWidget(table_card, 1);
+ col->addLayout(main_row);
+
+ // ── Performers row ───────────────────────────────────────────────────────
+ performers_row_ = new QWidget(page);
+ auto* perf_lay = new QHBoxLayout(performers_row_);
+ perf_lay->setContentsMargins(0, 0, 0, 0);
+ perf_lay->setSpacing(12);
+ col->addWidget(performers_row_);
+
+ // ── Concentration row ────────────────────────────────────────────────────
+ concentration_row_ = new QWidget(page);
+ auto* conc_lay = new QHBoxLayout(concentration_row_);
+ conc_lay->setContentsMargins(0, 0, 0, 0);
+ conc_lay->setSpacing(12);
+ col->addWidget(concentration_row_);
+
+ col->addStretch();
+
+ scroll->setWidget(page);
+ return scroll;
+}
+
+QWidget* AnalyticsSectorsView::build_correlation_tab() {
+ auto* scroll = new QScrollArea;
+ scroll->setWidgetResizable(true);
+ scroll->setFrameShape(QFrame::NoFrame);
+ scroll->setStyleSheet(QString("QScrollArea { background:%1; border:none; }")
+ .arg(ui::colors::BG_BASE()));
- layout->addWidget(tabs_);
+ corr_panel_ = new QWidget;
+ corr_panel_->setStyleSheet(QString("background:%1;").arg(ui::colors::BG_BASE()));
+ auto* lay = new QVBoxLayout(corr_panel_);
+ lay->setContentsMargins(16, 14, 16, 14);
+ lay->setSpacing(10);
+
+ auto* title = new QLabel("HOLDINGS CORRELATION MATRIX");
+ title->setStyleSheet(QString("color:%1; font-size:%2px; font-weight:700; letter-spacing:1.5px;")
+ .arg(ui::colors::TEXT_TERTIARY())
+ .arg(ui::fonts::font_px(-4)));
+ lay->addWidget(title);
+
+ corr_note_ = new QLabel(
+ "Top-10 holdings by weight. Values use a day-change sign proxy until "
+ "OHLC history is wired in — treat the magnitudes as directional, not precise.");
+ corr_note_->setWordWrap(true);
+ corr_note_->setStyleSheet(QString("color:%1; font-size:%2px;")
+ .arg(ui::colors::TEXT_TERTIARY())
+ .arg(ui::fonts::font_px(-3)));
+ lay->addWidget(corr_note_);
+
+ auto* card = new QWidget(corr_panel_);
+ card->setStyleSheet(QString("background:%1; border:1px solid %2;")
+ .arg(ui::colors::BG_SURFACE(), ui::colors::BORDER_DIM()));
+ auto* card_lay = new QVBoxLayout(card);
+ card_lay->setContentsMargins(16, 16, 16, 16);
+ corr_grid_ = new QGridLayout;
+ corr_grid_->setSpacing(2);
+ card_lay->addLayout(corr_grid_);
+ lay->addWidget(card);
+ lay->addStretch();
+
+ scroll->setWidget(corr_panel_);
+ return scroll;
}
void AnalyticsSectorsView::set_data(const portfolio::PortfolioSummary& summary, const QString& currency) {
summary_ = summary;
currency_ = currency;
update_overview();
- update_analytics();
update_correlation();
}
QVector<AnalyticsSectorsView::SectorInfo> AnalyticsSectorsView::compute_sectors() const {
QHash<QString, SectorInfo> map;
for (const auto& h : summary_.holdings) {
- QString sec = infer_sector(h.symbol);
+ QString sec = h.sector.isEmpty() ? QStringLiteral("Unclassified") : h.sector;
auto& info = map[sec];
info.name = sec;
info.weight += h.weight;
+ info.market_value += h.market_value;
+ info.cost_basis += h.cost_basis;
info.pnl += h.unrealized_pnl;
info.count++;
info.holdings.append(h);
@@ -144,8 +371,11 @@ QVector<AnalyticsSectorsView::SectorInfo> AnalyticsSectorsView::compute_sectors(
QVector<SectorInfo> result;
result.reserve(map.size());
- for (auto it = map.begin(); it != map.end(); ++it)
- result.append(it.value());
+ for (auto it = map.begin(); it != map.end(); ++it) {
+ auto v = it.value();
+ v.pnl_percent = v.cost_basis > 0 ? (v.pnl / v.cost_basis) * 100.0 : 0.0;
+ result.append(v);
+ }
std::sort(result.begin(), result.end(),
[](const SectorInfo& a, const SectorInfo& b) { return a.weight > b.weight; });
@@ -154,168 +384,366 @@ QVector<AnalyticsSectorsView::SectorInfo> AnalyticsSectorsView::compute_sectors(
void AnalyticsSectorsView::update_overview() {
auto sectors = compute_sectors();
+ update_kpi_strip(sectors);
+ update_donut(sectors);
+ update_sector_table(sectors);
+ update_performers(sectors);
+ update_concentration(sectors);
+}
+
+void AnalyticsSectorsView::update_kpi_strip(const QVector<SectorInfo>& sectors) {
+ kpi_sectors_->setText(QString::number(sectors.size()));
+ kpi_positions_->setText(QString::number(summary_.total_positions));
+ kpi_market_value_->setText(format_money(summary_.total_market_value));
+ const QString sign = summary_.total_unrealized_pnl >= 0 ? "+" : "";
+ kpi_pnl_->setText(QString("%1%2 (%3)")
+ .arg(sign)
+ .arg(QLocale::system().toString(summary_.total_unrealized_pnl, 'f', 2))
+ .arg(format_pct(summary_.total_unrealized_pnl_percent, true)));
+ kpi_pnl_->setStyleSheet(QString("color:%1; font-size:%2px; font-weight:700;")
+ .arg(summary_.total_unrealized_pnl >= 0 ? ui::colors::POSITIVE()
+ : ui::colors::NEGATIVE())
+ .arg(ui::fonts::font_px(2)));
+}
- // Update donut chart
- auto* chart = sector_chart_->chart();
+void AnalyticsSectorsView::update_donut(const QVector<SectorInfo>& sectors) {
+ auto* chart = donut_view_->chart();
chart->removeAllSeries();
auto* series = new QPieSeries;
- series->setHoleSize(0.55);
-
+ series->setHoleSize(0.60);
+ series->setPieSize(0.95);
for (int i = 0; i < sectors.size(); ++i) {
auto* slice = series->append(sectors[i].name, sectors[i].weight);
slice->setColor(sector_color(i));
slice->setBorderColor(QColor(ui::colors::BG_BASE()));
- slice->setBorderWidth(1);
+ slice->setBorderWidth(2);
}
chart->addSeries(series);
- // Update table
+ connect(series, &QPieSeries::clicked, this, [this](QPieSlice* slice) {
+ if (slice) emit sector_selected(slice->label());
+ });
+
+ // Center label
+ donut_center_->setText(QString("%1\nsectors").arg(sectors.size()));
+ donut_center_->adjustSize();
+ auto reposition_center = [this]() {
+ if (!donut_view_ || !donut_center_)
+ return;
+ donut_center_->move((donut_view_->width() - donut_center_->width()) / 2,
+ (donut_view_->height() - donut_center_->height()) / 2);
+ };
+ reposition_center();
+
+ // Rebuild legend
+ if (auto* old = legend_container_->layout()) {
+ QLayoutItem* item;
+ while ((item = old->takeAt(0)) != nullptr) {
+ if (item->widget())
+ item->widget()->deleteLater();
+ delete item;
+ }
+ delete old;
+ }
+ auto* legend_lay = new QVBoxLayout(legend_container_);
+ legend_lay->setContentsMargins(0, 4, 0, 0);
+ legend_lay->setSpacing(4);
+
+ int shown = std::min(sectors.size(), qsizetype{8});
+ for (int i = 0; i < shown; ++i) {
+ auto* row = new QHBoxLayout;
+ row->setSpacing(8);
+ row->addWidget(new Swatch(sector_color(i), 10, 10, legend_container_));
+
+ auto* name = new QLabel(sectors[i].name, legend_container_);
+ name->setStyleSheet(QString("color:%1; font-size:%2px; background:transparent;")
+ .arg(ui::colors::TEXT_PRIMARY())
+ .arg(ui::fonts::font_px(-3)));
+ row->addWidget(name, 1);
+
+ auto* wt = new QLabel(format_pct(sectors[i].weight, false), legend_container_);
+ wt->setAlignment(Qt::AlignRight);
+ wt->setStyleSheet(QString("color:%1; font-size:%2px; font-weight:700; background:transparent;")
+ .arg(ui::colors::AMBER())
+ .arg(ui::fonts::font_px(-3)));
+ row->addWidget(wt);
+
+ legend_lay->addLayout(row);
+ }
+ if (sectors.size() > shown) {
+ auto* more = new QLabel(QString("+%1 more").arg(sectors.size() - shown), legend_container_);
+ more->setStyleSheet(QString("color:%1; font-size:%2px; background:transparent;")
+ .arg(ui::colors::TEXT_TERTIARY())
+ .arg(ui::fonts::font_px(-3)));
+ legend_lay->addWidget(more);
+ }
+}
+
+void AnalyticsSectorsView::update_sector_table(const QVector<SectorInfo>& sectors) {
sector_table_->setRowCount(sectors.size());
+ sector_table_->clearSelection();
+
for (int r = 0; r < sectors.size(); ++r) {
const auto& s = sectors[r];
sector_table_->setRowHeight(r, 30);
- auto set_cell = [&](int col, const QString& text, const char* color = nullptr) {
+ // Col 0 — color swatch
+ sector_table_->setCellWidget(r, 0, new Swatch(sector_color(r), 10, 10, sector_table_));
+
+ auto set_text = [&](int col, const QString& text, QColor color, Qt::Alignment align) {
auto* item = new QTableWidgetItem(text);
- item->setTextAlignment(col == 0 ? (Qt::AlignLeft | Qt::AlignVCenter) : (Qt::AlignRight | Qt::AlignVCenter));
- if (color)
- item->setForeground(QColor(color));
+ item->setTextAlignment(align | Qt::AlignVCenter);
+ item->setForeground(color);
sector_table_->setItem(r, col, item);
};
- set_cell(0, QString("\u25CF %1").arg(s.name));
- // Color the swatch in the name
- auto* name_item = sector_table_->item(r, 0);
- if (name_item)
- name_item->setForeground(sector_color(r));
+ set_text(1, s.name, QColor(ui::colors::TEXT_PRIMARY()), Qt::AlignLeft);
+ set_text(2, QString::number(s.count), QColor(ui::colors::TEXT_SECONDARY()), Qt::AlignRight);
+ set_text(3, format_money(s.market_value), QColor(ui::colors::TEXT_PRIMARY()), Qt::AlignRight);
+ set_text(4, format_pct(s.weight), QColor(ui::colors::AMBER()), Qt::AlignRight);
- set_cell(1, QString::number(s.count), ui::colors::TEXT_SECONDARY);
- set_cell(2, QString("%1%").arg(QString::number(s.weight, 'f', 1)), ui::colors::AMBER);
-
- const char* pnl_color = s.pnl >= 0 ? ui::colors::POSITIVE : ui::colors::NEGATIVE;
- set_cell(3, QString("%1%2").arg(s.pnl >= 0 ? "+" : "").arg(QString::number(s.pnl, 'f', 2)), pnl_color);
-
- // Allocation bar (text representation)
- int bar_len = static_cast<int>(s.weight / 5.0);
- set_cell(4, QString(bar_len, QChar(0x2588)) + QString(" %1%").arg(QString::number(s.weight, 'f', 1)),
- ui::colors::CYAN);
+ const QColor pnl_color = s.pnl >= 0 ? QColor(ui::colors::POSITIVE()) : QColor(ui::colors::NEGATIVE());
+ const QString pnl_text = (s.pnl >= 0 ? QStringLiteral("+") : QString()) +
+ QLocale::system().toString(s.pnl, 'f', 2);
+ set_text(5, pnl_text, pnl_color, Qt::AlignRight);
+ set_text(6, format_pct(s.pnl_percent, true), pnl_color, Qt::AlignRight);
}
}
-void AnalyticsSectorsView::update_analytics() {
- if (analytics_panel_->layout())
- delete analytics_panel_->layout();
-
- auto* layout = new QVBoxLayout(analytics_panel_);
- layout->setContentsMargins(16, 12, 16, 12);
- layout->setSpacing(8);
+void AnalyticsSectorsView::update_performers(const QVector<SectorInfo>& sectors) {
+ // Clear existing cards
+ if (auto* lay = performers_row_->layout()) {
+ QLayoutItem* it;
+ while ((it = lay->takeAt(0)) != nullptr) {
+ if (it->widget())
+ it->widget()->deleteLater();
+ delete it;
+ }
+ }
- auto* title = new QLabel("SECTOR PERFORMANCE ANALYSIS");
- title->setStyleSheet(
- QString("color:%1; font-size:12px; font-weight:700; letter-spacing:1px;").arg(ui::colors::AMBER()));
- layout->addWidget(title);
+ if (sectors.isEmpty())
+ return;
- auto sectors = compute_sectors();
- for (int i = 0; i < sectors.size(); ++i) {
- const auto& s = sectors[i];
- auto* row = new QHBoxLayout;
- row->setSpacing(8);
+ auto* lay = qobject_cast<QHBoxLayout*>(performers_row_->layout());
+ if (!lay) {
+ lay = new QHBoxLayout(performers_row_);
+ lay->setContentsMargins(0, 0, 0, 0);
+ lay->setSpacing(12);
+ }
- auto* swatch = new QWidget(this);
- swatch->setFixedSize(12, 12);
- swatch->setStyleSheet(QString("background:%1;").arg(sector_color(i).name()));
- row->addWidget(swatch);
-
- auto* name = new QLabel(s.name);
- name->setFixedWidth(150);
- name->setStyleSheet(QString("color:%1; font-size:11px; font-weight:600;").arg(ui::colors::TEXT_PRIMARY()));
- row->addWidget(name);
-
- // Weight bar
- auto* bar_container = new QWidget(this);
- bar_container->setFixedHeight(14);
- auto* bar_layout = new QHBoxLayout(bar_container);
- bar_layout->setContentsMargins(0, 0, 0, 0);
- bar_layout->setSpacing(0);
-
- auto* bar = new QWidget(this);
- int bar_width = static_cast<int>(s.weight * 3.0);
- bar->setFixedSize(std::max(bar_width, 2), 12);
- bar->setStyleSheet(QString("background:%1;").arg(sector_color(i).name()));
- bar_layout->addWidget(bar);
- bar_layout->addStretch();
-
- row->addWidget(bar_container, 1);
-
- auto* weight_lbl = new QLabel(QString("%1%").arg(QString::number(s.weight, 'f', 1)));
- weight_lbl->setFixedWidth(50);
- weight_lbl->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
- weight_lbl->setStyleSheet(
- QString("color:%1; font-size:10px; font-weight:600;").arg(ui::colors::TEXT_SECONDARY()));
- row->addWidget(weight_lbl);
-
- const char* pnl_color = s.pnl >= 0 ? ui::colors::POSITIVE : ui::colors::NEGATIVE;
- auto* pnl_lbl = new QLabel(QString("%1%2").arg(s.pnl >= 0 ? "+" : "").arg(QString::number(s.pnl, 'f', 2)));
- pnl_lbl->setFixedWidth(80);
- pnl_lbl->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
- pnl_lbl->setStyleSheet(QString("color:%1; font-size:10px; font-weight:600;").arg(pnl_color));
- row->addWidget(pnl_lbl);
-
- layout->addLayout(row);
+ // Identify interesting sectors
+ SectorInfo largest = sectors.first(); // already weight-sorted desc
+ SectorInfo smallest = sectors.last();
+ SectorInfo best = sectors.first();
+ SectorInfo worst = sectors.first();
+ for (const auto& s : sectors) {
+ if (s.pnl_percent > best.pnl_percent) best = s;
+ if (s.pnl_percent < worst.pnl_percent) worst = s;
}
- layout->addStretch();
+ struct Card {
+ QString label;
+ const SectorInfo* s;
+ QColor accent;
+ QString metric_text;
+ };
+ const QVector<Card> cards = {
+ {"LARGEST", &largest, QColor(ui::colors::AMBER()), format_pct(largest.weight)},
+ {"SMALLEST", &smallest, QColor(ui::colors::TEXT_SECONDARY()), format_pct(smallest.weight)},
+ {"BEST", &best, QColor(ui::colors::POSITIVE()), format_pct(best.pnl_percent, true)},
+ {"WORST", &worst, QColor(ui::colors::NEGATIVE()), format_pct(worst.pnl_percent, true)},
+ };
+
+ for (const auto& c : cards) {
+ auto* card = new QWidget(performers_row_);
+ card->setCursor(Qt::PointingHandCursor);
+ card->setStyleSheet(QString("QWidget { background:%1; border:1px solid %2; }"
+ "QWidget:hover { border:1px solid %3; }")
+ .arg(ui::colors::BG_SURFACE())
+ .arg(ui::colors::BORDER_DIM())
+ .arg(c.accent.name()));
+ auto* cl = new QVBoxLayout(card);
+ cl->setContentsMargins(14, 10, 14, 10);
+ cl->setSpacing(4);
+
+ auto* label = new QLabel(c.label, card);
+ label->setStyleSheet(QString("color:%1; font-size:%2px; font-weight:700;"
+ "letter-spacing:1.5px; background:transparent;")
+ .arg(c.accent.name())
+ .arg(ui::fonts::font_px(-4)));
+ cl->addWidget(label);
+
+ auto* name = new QLabel(c.s->name, card);
+ name->setStyleSheet(QString("color:%1; font-size:%2px; font-weight:700; background:transparent;")
+ .arg(ui::colors::TEXT_PRIMARY())
+ .arg(ui::fonts::font_px()));
+ cl->addWidget(name);
+
+ auto* metric = new QLabel(c.metric_text, card);
+ metric->setStyleSheet(QString("color:%1; font-size:%2px; font-weight:700;"
+ "font-family:%3; background:transparent;")
+ .arg(c.accent.name())
+ .arg(ui::fonts::font_px(1))
+ .arg(ui::fonts::DATA_FAMILY));
+ cl->addWidget(metric);
+
+ auto* sub = new QLabel(QString("%1 positions").arg(c.s->count), card);
+ sub->setStyleSheet(QString("color:%1; font-size:%2px; background:transparent;")
+ .arg(ui::colors::TEXT_TERTIARY())
+ .arg(ui::fonts::font_px(-3)));
+ cl->addWidget(sub);
+
+ // Click to filter blotter by this sector
+ card->installEventFilter(new SectorCardClickForwarder(this, c.s->name, card));
+
+ lay->addWidget(card, 1);
+ }
}
-void AnalyticsSectorsView::update_correlation() {
- if (corr_panel_->layout())
- delete corr_panel_->layout();
+void AnalyticsSectorsView::update_concentration(const QVector<SectorInfo>& sectors) {
+ if (auto* lay = concentration_row_->layout()) {
+ QLayoutItem* it;
+ while ((it = lay->takeAt(0)) != nullptr) {
+ if (it->widget())
+ it->widget()->deleteLater();
+ delete it;
+ }
+ }
+ auto* lay = qobject_cast<QHBoxLayout*>(concentration_row_->layout());
+ if (!lay) {
+ lay = new QHBoxLayout(concentration_row_);
+ lay->setContentsMargins(0, 0, 0, 0);
+ lay->setSpacing(12);
+ }
+
+ if (sectors.isEmpty())
+ return;
- auto* layout = new QVBoxLayout(corr_panel_);
- layout->setContentsMargins(16, 12, 16, 12);
- layout->setSpacing(8);
+ // HHI: Σ (weight%)² over all sectors. Units already in percent-squared.
+ double hhi = 0.0;
+ for (const auto& s : sectors)
+ hhi += s.weight * s.weight;
- auto* title = new QLabel("FULL CORRELATION MATRIX");
- title->setStyleSheet(
- QString("color:%1; font-size:12px; font-weight:700; letter-spacing:1px;").arg(ui::colors::AMBER()));
- layout->addWidget(title);
+ double top3 = 0.0;
+ for (int i = 0; i < std::min(qsizetype{3}, sectors.size()); ++i)
+ top3 += sectors[i].weight;
- auto* note = new QLabel("Based on day-change proxy (requires historical data for precise calculation)");
- note->setStyleSheet(QString("color:%1; font-size:9px;").arg(ui::colors::TEXT_TERTIARY()));
- layout->addWidget(note);
+ struct Box {
+ QString title;
+ QString value;
+ QString verdict;
+ QString sub;
+ };
+ const QVector<Box> boxes = {
+ {"HHI CONCENTRATION", QString::number(hhi, 'f', 0),
+ verdict_for_hhi(hhi),
+ "Herfindahl index across sectors (lower = more diversified)"},
+ {"TOP-3 CONCENTRATION", format_pct(top3),
+ verdict_for_top3(top3),
+ QString("Weight of the three largest sectors (%1)").arg(
+ [&]() {
+ QStringList parts;
+ for (int i = 0; i < std::min(qsizetype{3}, sectors.size()); ++i)
+ parts << sectors[i].name;
+ return parts.join(", ");
+ }())},
+ };
+
+ for (const auto& b : boxes) {
+ auto* card = new QWidget(concentration_row_);
+ card->setStyleSheet(QString("background:%1; border:1px solid %2;")
+ .arg(ui::colors::BG_SURFACE(), ui::colors::BORDER_DIM()));
+ auto* cl = new QVBoxLayout(card);
+ cl->setContentsMargins(16, 12, 16, 12);
+ cl->setSpacing(6);
+
+ auto* title = new QLabel(b.title, card);
+ title->setStyleSheet(QString("color:%1; font-size:%2px; font-weight:700;"
+ "letter-spacing:1.5px; background:transparent;")
+ .arg(ui::colors::TEXT_TERTIARY())
+ .arg(ui::fonts::font_px(-4)));
+ cl->addWidget(title);
+
+ auto* value_row = new QHBoxLayout;
+ value_row->setSpacing(10);
+ auto* val = new QLabel(b.value, card);
+ val->setStyleSheet(QString("color:%1; font-size:%2px; font-weight:700;"
+ "font-family:%3; background:transparent;")
+ .arg(ui::colors::TEXT_PRIMARY())
+ .arg(ui::fonts::font_px(4))
+ .arg(ui::fonts::DATA_FAMILY));
+ value_row->addWidget(val);
+
+ auto* verdict = new QLabel(b.verdict, card);
+ const QColor vc = verdict_color(b.verdict);
+ verdict->setStyleSheet(QString("color:%1; font-size:%2px; font-weight:700;"
+ "letter-spacing:1.5px; padding:4px 10px;"
+ "background:rgba(%3,%4,%5,0.15); border:1px solid %1;")
+ .arg(vc.name())
+ .arg(ui::fonts::font_px(-3))
+ .arg(vc.red()).arg(vc.green()).arg(vc.blue()));
+ verdict->setAlignment(Qt::AlignCenter);
+ value_row->addWidget(verdict);
+ value_row->addStretch();
+ cl->addLayout(value_row);
+
+ auto* sub = new QLabel(b.sub, card);
+ sub->setWordWrap(true);
+ sub->setStyleSheet(QString("color:%1; font-size:%2px; background:transparent;")
+ .arg(ui::colors::TEXT_TERTIARY())
+ .arg(ui::fonts::font_px(-3)));
+ cl->addWidget(sub);
+
+ lay->addWidget(card, 1);
+ }
+}
+
+void AnalyticsSectorsView::update_correlation() {
+ // Clear existing grid contents
+ if (corr_grid_) {
+ QLayoutItem* it;
+ while ((it = corr_grid_->takeAt(0)) != nullptr) {
+ if (it->widget())
+ it->widget()->deleteLater();
+ delete it;
+ }
+ }
if (summary_.holdings.size() < 2) {
- auto* msg = new QLabel("Need 2+ holdings for correlation analysis");
+ auto* msg = new QLabel("Need 2+ holdings for correlation analysis", corr_panel_);
msg->setAlignment(Qt::AlignCenter);
- msg->setStyleSheet(QString("color:%1; font-size:12px; padding:40px;").arg(ui::colors::TEXT_TERTIARY()));
- layout->addWidget(msg);
+ msg->setStyleSheet(QString("color:%1; font-size:%2px; padding:40px; background:transparent;")
+ .arg(ui::colors::TEXT_TERTIARY())
+ .arg(ui::fonts::font_px()));
+ corr_grid_->addWidget(msg, 0, 0);
return;
}
- // Sort by weight, take top 10
auto sorted = summary_.holdings;
- std::sort(sorted.begin(), sorted.end(), [](const auto& a, const auto& b) { return a.weight > b.weight; });
+ std::sort(sorted.begin(), sorted.end(),
+ [](const auto& a, const auto& b) { return a.weight > b.weight; });
int n = static_cast<int>(std::min(qsizetype{10}, sorted.size()));
- auto* grid = new QGridLayout;
- grid->setSpacing(2);
-
- // Header
- auto* empty = new QLabel;
- grid->addWidget(empty, 0, 0);
- for (int i = 0; i < n; ++i) {
- auto* lbl = new QLabel(sorted[i].symbol.left(5));
+ auto make_header = [this](const QString& s, bool rotate) {
+ auto* lbl = new QLabel(s);
lbl->setAlignment(Qt::AlignCenter);
- lbl->setFixedHeight(22);
- lbl->setStyleSheet(QString("color:%1; font-size:8px; font-weight:700;").arg(ui::colors::TEXT_SECONDARY()));
- grid->addWidget(lbl, 0, i + 1);
- }
+ lbl->setFixedHeight(rotate ? 46 : 24);
+ lbl->setStyleSheet(QString("color:%1; font-size:%2px; font-weight:700;"
+ "letter-spacing:.5px; background:transparent;")
+ .arg(ui::colors::TEXT_SECONDARY())
+ .arg(ui::fonts::font_px(-3)));
+ return lbl;
+ };
+
+ // Corner
+ corr_grid_->addWidget(make_header(QString(), false), 0, 0);
+ // Top headers
+ for (int c = 0; c < n; ++c)
+ corr_grid_->addWidget(make_header(sorted[c].symbol.left(6), false), 0, c + 1);
for (int r = 0; r < n; ++r) {
- auto* row_lbl = new QLabel(sorted[r].symbol.left(5));
- row_lbl->setStyleSheet(QString("color:%1; font-size:8px; font-weight:700;").arg(ui::colors::TEXT_SECONDARY()));
- grid->addWidget(row_lbl, r + 1, 0);
+ corr_grid_->addWidget(make_header(sorted[r].symbol.left(6), false), r + 1, 0);
for (int c = 0; c < n; ++c) {
double corr;
@@ -324,38 +752,49 @@ void AnalyticsSectorsView::update_correlation() {
} else {
double a = sorted[r].day_change_percent;
double b = sorted[c].day_change_percent;
- bool same = (a >= 0) == (b >= 0);
+ bool same_sign = (a >= 0) == (b >= 0);
double mag = std::min(std::abs(a) + std::abs(b), 10.0) / 10.0;
- corr = same ? (mag * 0.8 + 0.1) : -(mag * 0.6 + 0.05);
+ corr = same_sign ? (mag * 0.8 + 0.1) : -(mag * 0.6 + 0.05);
}
auto* cell = new QLabel(QString::number(corr, 'f', 2));
cell->setAlignment(Qt::AlignCenter);
- cell->setFixedSize(42, 22);
+ cell->setFixedSize(54, 26);
QColor bg;
- if (r == c)
- bg = QColor(ui::colors::TEXT_PRIMARY());
- else if (corr > 0)
- bg = QColor(22, 163, 74, static_cast<int>(std::abs(corr) * 140));
- else
- bg = QColor(220, 38, 38, static_cast<int>(std::abs(corr) * 140));
-
- const char* tc = (r == c) ? ui::colors::BG_BASE : ui::colors::TEXT_PRIMARY;
+ QString fg;
+ if (r == c) {
+ bg = QColor(ui::colors::AMBER());
+ fg = ui::colors::BG_BASE();
+ } else if (corr > 0) {
+ int alpha = static_cast<int>(std::min(1.0, std::abs(corr)) * 180);
+ bg = QColor(22, 163, 74, alpha);
+ fg = ui::colors::TEXT_PRIMARY();
+ } else {
+ int alpha = static_cast<int>(std::min(1.0, std::abs(corr)) * 180);
+ bg = QColor(220, 38, 38, alpha);
+ fg = ui::colors::TEXT_PRIMARY();
+ }
+
cell->setStyleSheet(QString("background:rgba(%1,%2,%3,%4); color:%5;"
- "font-size:8px; font-weight:600;")
+ "font-size:%6px; font-weight:700; font-family:%7;")
.arg(bg.red())
.arg(bg.green())
.arg(bg.blue())
.arg(bg.alpha())
- .arg(tc));
+ .arg(fg)
+ .arg(ui::fonts::font_px(-3))
+ .arg(ui::fonts::DATA_FAMILY));
- grid->addWidget(cell, r + 1, c + 1);
+ corr_grid_->addWidget(cell, r + 1, c + 1);
}
}
+}
- layout->addLayout(grid);
- layout->addStretch();
+bool SectorCardClickForwarder::eventFilter(QObject* obj, QEvent* ev) {
+ if (ev->type() == QEvent::MouseButtonRelease && owner_)
+ emit owner_->sector_selected(sector_);
+ return QObject::eventFilter(obj, ev);
}
} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/portfolio/views/AnalyticsSectorsView.h b/fincept-qt/src/screens/portfolio/views/AnalyticsSectorsView.h
index 8a0d43914..e2740840a 100644
--- a/fincept-qt/src/screens/portfolio/views/AnalyticsSectorsView.h
+++ b/fincept-qt/src/screens/portfolio/views/AnalyticsSectorsView.h
@@ -2,15 +2,26 @@
#pragma once
#include "screens/portfolio/PortfolioTypes.h"
-#include <QChartView>
-#include <QLabel>
-#include <QTabWidget>
-#include <QTableWidget>
+#include <QColor>
#include <QWidget>
+class QChartView;
+class QGridLayout;
+class QLabel;
+class QTableWidget;
+class QTabWidget;
+class QVBoxLayout;
+
namespace fincept::screens {
-/// Analytics & Sectors detail view with 3 sub-tabs: Overview, Analytics, Correlation.
+/// Analytics & Sectors detail view.
+///
+/// Two sub-tabs:
+/// - OVERVIEW: KPI strip, donut + sector table, 4 performer cards, HHI +
+/// top-3 concentration badges. Everything the user needs to
+/// reason about sector exposure on one page.
+/// - CORRELATION: symbol×symbol matrix using a day-change proxy until
+/// OHLC history is wired (note displayed inline).
class AnalyticsSectorsView : public QWidget {
Q_OBJECT
public:
@@ -18,39 +29,70 @@ class AnalyticsSectorsView : public QWidget {
void set_data(const portfolio::PortfolioSummary& summary, const QString& currency);
+ signals:
+ /// Fired when the user clicks a sector row / donut slice / performer card.
+ /// Empty string = clear filter.
+ void sector_selected(QString sector);
+
private:
+ struct SectorInfo {
+ QString name;
+ double weight = 0; // percent of portfolio (0..100)
+ double market_value = 0; // in portfolio currency
+ double cost_basis = 0;
+ double pnl = 0;
+ double pnl_percent = 0;
+ int count = 0;
+ QVector<portfolio::HoldingWithQuote> holdings;
+ };
+
void build_ui();
+ QWidget* build_overview_tab();
+ QWidget* build_correlation_tab();
void update_overview();
- void update_analytics();
void update_correlation();
+ void update_kpi_strip(const QVector<SectorInfo>& sectors);
+ void update_donut(const QVector<SectorInfo>& sectors);
+ void update_sector_table(const QVector<SectorInfo>& sectors);
+ void update_performers(const QVector<SectorInfo>& sectors);
+ void update_concentration(const QVector<SectorInfo>& sectors);
+
+ QVector<SectorInfo> compute_sectors() const;
+ static QColor sector_color(int index);
+ QString format_money(double v) const;
+ static QString format_pct(double v, bool signed_ = false);
+ // Layout
QTabWidget* tabs_ = nullptr;
- // Overview tab
- QChartView* sector_chart_ = nullptr;
+ // KPI strip
+ QLabel* kpi_sectors_ = nullptr;
+ QLabel* kpi_positions_ = nullptr;
+ QLabel* kpi_market_value_ = nullptr;
+ QLabel* kpi_pnl_ = nullptr;
+
+ // Donut + legend
+ QChartView* donut_view_ = nullptr;
+ QLabel* donut_center_ = nullptr;
+ QWidget* legend_container_ = nullptr;
+
+ // Sector table
QTableWidget* sector_table_ = nullptr;
- // Analytics tab
- QWidget* analytics_panel_ = nullptr;
+ // Performer cards
+ QWidget* performers_row_ = nullptr;
+
+ // Concentration
+ QWidget* concentration_row_ = nullptr;
- // Correlation tab
+ // Correlation
QWidget* corr_panel_ = nullptr;
+ QGridLayout* corr_grid_ = nullptr;
+ QLabel* corr_note_ = nullptr;
// Data
portfolio::PortfolioSummary summary_;
QString currency_;
-
- // Sector helpers
- struct SectorInfo {
- QString name;
- double weight = 0;
- double pnl = 0;
- int count = 0;
- QVector<portfolio::HoldingWithQuote> holdings;
- };
- QVector<SectorInfo> compute_sectors() const;
- static QString infer_sector(const QString& symbol);
- static QColor sector_color(int index);
};
} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/portfolio/views/RiskManagementView.cpp b/fincept-qt/src/screens/portfolio/views/RiskManagementView.cpp
index 485f53731..d51253b49 100644
--- a/fincept-qt/src/screens/portfolio/views/RiskManagementView.cpp
+++ b/fincept-qt/src/screens/portfolio/views/RiskManagementView.cpp
@@ -248,9 +248,10 @@ void RiskManagementView::update_overview() {
void RiskManagementView::update_stress_test() {
double total_mv = summary_.total_market_value;
- // ── Compute actual sector weights from holdings ───────────────────────────
- // Classify each holding into equity / bond / commodity / crypto / other
- // based on symbol patterns — mirrors PortfolioSectorPanel::infer_sector
+ // ── Compute actual asset-class weights from holdings ──────────────────────
+ // Classify each holding into equity / bond / commodity / crypto for the
+ // stress scenarios below. This is an asset-class heuristic distinct from
+ // the GICS-style sector used by SectorResolver / AnalyticsSectorsView.
double equity_wt = 0, bond_wt = 0, commodity_wt = 0, crypto_wt = 0;
for (const auto& h : summary_.holdings) {
const QString s = h.symbol.toUpper();
diff --git a/fincept-qt/src/screens/settings/LlmConfigSection.cpp b/fincept-qt/src/screens/settings/LlmConfigSection.cpp
index 72888dfc9..b8f819f5e 100644
--- a/fincept-qt/src/screens/settings/LlmConfigSection.cpp
+++ b/fincept-qt/src/screens/settings/LlmConfigSection.cpp
@@ -27,8 +27,8 @@ namespace fincept::screens {
static constexpr const char* TAG = "LlmConfigSection";
-const QStringList LlmConfigSection::KNOWN_PROVIDERS = {"openai", "anthropic", "gemini", "groq", "deepseek",
- "openrouter", "minimax", "ollama", "fincept"};
+const QStringList LlmConfigSection::KNOWN_PROVIDERS = {"openai", "anthropic", "gemini", "groq", "deepseek",
+ "openrouter", "minimax", "kimi", "ollama", "xai", "fincept"};
QString LlmConfigSection::default_base_url(const QString& provider) {
const QString p = provider.toLower();
@@ -46,8 +46,12 @@ QString LlmConfigSection::default_base_url(const QString& provider) {
return {};
if (p == "minimax")
return "https://api.minimax.io/v1";
+ if (p == "kimi")
+ return {}; // defaults to https://api.moonshot.ai
if (p == "ollama")
return "http://localhost:11434";
+ if (p == "xai")
+ return {};
if (p == "fincept")
return {}; // endpoints are hardcoded in LlmService, no base_url needed
return {};
@@ -70,8 +74,25 @@ QStringList LlmConfigSection::fallback_models(const QString& provider) {
return {"openai/gpt-4o", "anthropic/claude-sonnet-4-5", "google/gemini-2.5-flash"};
if (p == "minimax")
return {"MiniMax-M2.7", "MiniMax-M2.7-highspeed", "MiniMax-M2.5", "MiniMax-M2.5-highspeed"};
+ if (p == "kimi")
+ return {"moonshot-v1-auto",
+ "moonshot-v1-8k",
+ "moonshot-v1-32k",
+ "moonshot-v1-128k",
+ "kimi-k2.5",
+ "kimi-k2.6",
+ "kimi-k2-thinking",
+ "kimi-k2-thinking-turbo",
+ "kimi-k2-0905-preview",
+ "kimi-k2-turbo-preview",
+ "kimi-k2-0711-preview",
+ "moonshot-v1-8k-vision-preview",
+ "moonshot-v1-32k-vision-preview",
+ "moonshot-v1-128k-vision-preview"};
if (p == "ollama")
- return {"llama3:8b", "mistral:7b", "codellama:7b"};
+ return {"llama3.1:8b", "qwen2.5:7b", "mistral:7b"};
+ if (p == "xai")
+ return {"grok-4-latest", "grok-4", "grok-3", "grok-3-mini"};
if (p == "fincept")
return {"MiniMax-M2.7", "MiniMax-M2.7-highspeed", "MiniMax-M2.5", "MiniMax-M2.5-highspeed"};
return {};
@@ -523,16 +544,26 @@ QWidget* LlmConfigSection::build_global_panel() {
// ============================================================================
void LlmConfigSection::load_providers() {
+ // Remember the currently-selected provider so a reload (e.g. after Save)
+ // doesn't snap the user back to the first row. Fall back to the active
+ // provider on first load, then row 0 if nothing else applies.
+ QString prior_selection;
+ if (provider_list_->currentItem())
+ prior_selection = provider_list_->currentItem()->data(Qt::UserRole).toString();
+
provider_list_->blockSignals(true);
provider_list_->clear();
+ QString active_provider;
auto result = LlmConfigRepository::instance().list_providers();
if (result.is_ok()) {
for (const auto& p : result.value()) {
bool is_fincept = (p.provider.toLower() == "fincept");
QString display = is_fincept ? "Fincept LLM" : p.provider;
- if (p.is_active)
+ if (p.is_active) {
display += " ✓";
+ active_provider = p.provider;
+ }
// Show model tag only for non-fincept providers
if (!is_fincept && !p.model.isEmpty())
display += " [" + p.model + "]";
@@ -558,8 +589,24 @@ void LlmConfigSection::load_providers() {
}
delete_btn_->setEnabled(false);
- if (provider_list_->count() > 0)
- provider_list_->setCurrentRow(0);
+
+ // Selection precedence: prior selection (preserves UX across Save reloads)
+ // > active provider (so first load lands on what the user is actually using)
+ // > row 0 (fallback).
+ int target_row = -1;
+ const QString wanted = !prior_selection.isEmpty() ? prior_selection : active_provider;
+ if (!wanted.isEmpty()) {
+ for (int i = 0; i < provider_list_->count(); ++i) {
+ if (provider_list_->item(i)->data(Qt::UserRole).toString() == wanted) {
+ target_row = i;
+ break;
+ }
+ }
+ }
+ if (target_row < 0 && provider_list_->count() > 0)
+ target_row = 0;
+ if (target_row >= 0)
+ provider_list_->setCurrentRow(target_row);
}
void LlmConfigSection::populate_form(const QString& provider) {
@@ -701,16 +748,36 @@ void LlmConfigSection::on_save_provider() {
auto r2 = LlmConfigRepository::instance().save_provider(cfg);
if (r2.is_err()) {
show_status("Failed to save: " + QString::fromStdString(r2.error()), true);
+ LOG_ERROR(TAG, "save_provider failed for " + provider + ": " + QString::fromStdString(r2.error()));
+ return;
+ }
+ auto r3 = LlmConfigRepository::instance().set_active(provider);
+ if (r3.is_err()) {
+ show_status("Failed to activate: " + QString::fromStdString(r3.error()), true);
+ LOG_ERROR(TAG, "set_active failed for " + provider + ": " + QString::fromStdString(r3.error()));
+ return;
+ }
+
+ // Read-after-write verification — catches silent failures where the INSERT
+ // reports success but the row never lands (e.g. autocommit off, FK rollback,
+ // wrong DB path). Without this the old code would say "Saved" and the user
+ // only finds out on restart.
+ auto verify = LlmConfigRepository::instance().get_active_provider();
+ if (!verify.is_ok() || verify.value().provider.toLower() != provider) {
+ QString detail = verify.is_ok()
+ ? QString("active is '%1' not '%2'").arg(verify.value().provider, provider)
+ : QString::fromStdString(verify.error());
+ show_status("Save verification failed: " + detail, true);
+ LOG_ERROR(TAG, "Save verification failed — " + detail);
return;
}
- LlmConfigRepository::instance().set_active(provider);
show_status("Saved and set as active provider", false);
load_providers();
ai_chat::LlmService::instance().reload_config();
emit config_changed();
- LOG_INFO(TAG, "LLM provider saved: " + provider + " / " + cfg.model);
+ LOG_INFO(TAG, "LLM provider saved and verified: " + provider + " / " + cfg.model);
}
void LlmConfigSection::on_delete_provider() {
diff --git a/fincept-qt/src/screens/settings/SettingsScreen.cpp b/fincept-qt/src/screens/settings/SettingsScreen.cpp
index 51dc71e06..7cb4929f8 100644
--- a/fincept-qt/src/screens/settings/SettingsScreen.cpp
+++ b/fincept-qt/src/screens/settings/SettingsScreen.cpp
@@ -6,6 +6,7 @@
#include "ai_chat/LlmService.h"
#include "auth/InactivityGuard.h"
#include "auth/PinManager.h"
+#include "auth/SecurityAuditLog.h"
#include "core/config/AppConfig.h"
#include "core/config/AppPaths.h"
#include "core/config/ProfileManager.h"
@@ -2643,7 +2644,13 @@ QWidget* SettingsScreen::build_security() {
}
});
- // Save PIN handler
+ // Save PIN handler.
+ //
+ // All validation (length, digits, weak pattern, old-PIN verification, same-
+ // as-old rejection) lives in PinManager::change_pin so there is exactly
+ // one enforcement path and a wrong current PIN correctly feeds the
+ // shared lockout counter. The UI only checks "new" == "confirm" since the
+ // manager has no notion of a confirm field.
connect(save_pin_btn, &QPushButton::clicked, this, [this]() {
sec_pin_error_->hide();
sec_pin_success_->hide();
@@ -2653,28 +2660,6 @@ QWidget* SettingsScreen::build_security() {
const QString new_pin = sec_new_pin_->text();
const QString confirm = sec_confirm_pin_->text();
- // Verify current PIN
- if (!pm.verify_pin(current)) {
- sec_pin_error_->setText("Current PIN is incorrect");
- sec_pin_error_->show();
- sec_current_pin_->clear();
- sec_current_pin_->setFocus();
- return;
- }
-
- // Validate new PIN
- if (new_pin.length() != 6) {
- sec_pin_error_->setText("New PIN must be exactly 6 digits");
- sec_pin_error_->show();
- return;
- }
- for (const QChar& c : new_pin) {
- if (!c.isDigit()) {
- sec_pin_error_->setText("PIN must contain only digits");
- sec_pin_error_->show();
- return;
- }
- }
if (new_pin != confirm) {
sec_pin_error_->setText("New PINs do not match");
sec_pin_error_->show();
@@ -2682,16 +2667,16 @@ QWidget* SettingsScreen::build_security() {
sec_confirm_pin_->setFocus();
return;
}
- if (new_pin == current) {
- sec_pin_error_->setText("New PIN must be different from current PIN");
- sec_pin_error_->show();
- return;
- }
- auto result = pm.set_pin(new_pin);
+ auto result = pm.change_pin(current, new_pin);
if (result.is_err()) {
sec_pin_error_->setText(QString::fromStdString(result.error()));
sec_pin_error_->show();
+ // On a wrong current PIN the manager incremented the attempt
+ // counter; clear the field and let the user try again (up to
+ // kMaxAttempts, at which point the lock screen takes over).
+ sec_current_pin_->clear();
+ sec_current_pin_->setFocus();
return;
}
@@ -2736,6 +2721,11 @@ QWidget* SettingsScreen::build_security() {
connect(sec_autolock_toggle_, &QCheckBox::toggled, this,
[this](bool checked) { sec_lock_timeout_->setEnabled(checked); });
+ sec_lock_on_minimize_ = new QCheckBox("Lock when the window is minimized");
+ sec_lock_on_minimize_->setStyleSheet(check_ss());
+ vl->addWidget(make_row("Lock on Minimize", sec_lock_on_minimize_,
+ "When on, minimizing the terminal immediately shows the PIN screen."));
+
vl->addSpacing(16);
// ── SAVE ──────────────────────────────────────────────────────────────────
@@ -2751,6 +2741,10 @@ QWidget* SettingsScreen::build_security() {
repo.set("security.autolock_enabled", autolock ? "true" : "false", "security");
repo.set("security.lock_timeout_minutes", QString::number(minutes), "security");
+ if (sec_lock_on_minimize_) {
+ repo.set("security.lock_on_minimize",
+ sec_lock_on_minimize_->isChecked() ? "true" : "false", "security");
+ }
guard.set_timeout_minutes(minutes);
guard.set_enabled(autolock);
@@ -2759,11 +2753,55 @@ QWidget* SettingsScreen::build_security() {
});
vl->addWidget(save_btn);
+ // ── AUDIT LOG ─────────────────────────────────────────────────────────────
+ vl->addSpacing(16);
+ auto* t_audit = new QLabel("AUDIT LOG");
+ t_audit->setStyleSheet(sub_title_ss());
+ vl->addWidget(t_audit);
+ vl->addSpacing(4);
+
+ auto* audit_note = new QLabel("Recent security events (PIN setup, failed unlocks, inactivity locks).");
+ audit_note->setWordWrap(true);
+ audit_note->setStyleSheet(QString("color:%1;font-size:12px;background:transparent;")
+ .arg(ui::colors::TEXT_DIM()));
+ vl->addWidget(audit_note);
+
+ sec_audit_list_ = new QListWidget;
+ sec_audit_list_->setFixedHeight(180);
+ sec_audit_list_->setStyleSheet(
+ QString("QListWidget { background:%1; color:%2; border:1px solid %3;"
+ "font-family:'Consolas','Courier New',monospace; font-size:12px; }"
+ "QListWidget::item { padding:2px 6px; }")
+ .arg(ui::colors::BG_SURFACE(), ui::colors::TEXT_PRIMARY(), ui::colors::BORDER_DIM()));
+ vl->addWidget(sec_audit_list_);
+
+ auto* refresh_audit = new QPushButton("Refresh");
+ refresh_audit->setFixedWidth(140);
+ refresh_audit->setStyleSheet(btn_secondary_ss());
+ connect(refresh_audit, &QPushButton::clicked, this, [this]() { refresh_audit_log(); });
+ vl->addWidget(refresh_audit);
+
vl->addStretch();
scroll->setWidget(page);
return scroll;
}
+void SettingsScreen::refresh_audit_log() {
+ if (!sec_audit_list_)
+ return;
+ sec_audit_list_->clear();
+ const auto events = auth::SecurityAuditLog::instance().recent(100);
+ for (const auto& e : events) {
+ const QString ts = e.timestamp.toString("yyyy-MM-dd hh:mm:ss");
+ const QString line = e.detail.isEmpty()
+ ? QString("%1 %2").arg(ts, e.event)
+ : QString("%1 %2 (%3)").arg(ts, e.event, e.detail);
+ sec_audit_list_->addItem(line);
+ }
+ if (events.isEmpty())
+ sec_audit_list_->addItem("(no events recorded yet)");
+}
+
void SettingsScreen::load_security() {
auto& pm = auth::PinManager::instance();
auto& repo = SettingsRepository::instance();
@@ -2815,6 +2853,17 @@ void SettingsScreen::load_security() {
}
}
}
+
+ if (sec_lock_on_minimize_) {
+ const QSignalBlocker b(sec_lock_on_minimize_);
+ auto r = repo.get("security.lock_on_minimize");
+ // Default off — most users minimize frequently and don't expect a lock.
+ sec_lock_on_minimize_->setChecked(r.is_ok() && r.value() == "true");
+ }
+
+ // Populate audit log when the Security tab is shown. Cheap — the query
+ // is LIMIT 100 against an indexed column.
+ refresh_audit_log();
}
// ── Profiles ──────────────────────────────────────────────────────────────────
diff --git a/fincept-qt/src/screens/settings/SettingsScreen.h b/fincept-qt/src/screens/settings/SettingsScreen.h
index 8240077f9..825054e1b 100644
--- a/fincept-qt/src/screens/settings/SettingsScreen.h
+++ b/fincept-qt/src/screens/settings/SettingsScreen.h
@@ -7,6 +7,7 @@
#include <QHash>
#include <QLabel>
#include <QLineEdit>
+#include <QListWidget>
#include <QPushButton>
#include <QStackedWidget>
#include <QTimer>
@@ -115,6 +116,8 @@ class SettingsScreen : public QWidget, public IStatefulScreen {
QLabel* sec_pin_status_ = nullptr;
QComboBox* sec_lock_timeout_ = nullptr;
QCheckBox* sec_autolock_toggle_ = nullptr;
+ QCheckBox* sec_lock_on_minimize_ = nullptr;
+ QListWidget* sec_audit_list_ = nullptr;
QLabel* sec_lockout_status_ = nullptr;
QPushButton* sec_change_pin_btn_ = nullptr;
// Change PIN sub-widgets (shown/hidden dynamically)
@@ -131,6 +134,7 @@ class SettingsScreen : public QWidget, public IStatefulScreen {
void load_appearance();
void load_notifications();
void load_security();
+ void refresh_audit_log();
void refresh_storage_stats();
// ── Notification helpers ──────────────────────────────────────────────────
diff --git a/fincept-qt/src/screens/surface_analytics/SurfaceAnalyticsScreen.cpp b/fincept-qt/src/screens/surface_analytics/SurfaceAnalyticsScreen.cpp
index aeab230c4..8f04d9a4b 100644
--- a/fincept-qt/src/screens/surface_analytics/SurfaceAnalyticsScreen.cpp
+++ b/fincept-qt/src/screens/surface_analytics/SurfaceAnalyticsScreen.cpp
@@ -1106,4 +1106,27 @@ void SurfaceAnalyticsScreen::restore_state(const QVariantMap& state) {
on_category_clicked(cat);
}
+// ── IGroupLinked ─────────────────────────────────────────────────────────────
+
+void SurfaceAnalyticsScreen::on_group_symbol_changed(const fincept::SymbolRef& ref) {
+ if (!ref.is_valid() || !symbol_combo_)
+ return;
+ // Only act when the incoming symbol matches one of our supported tickers
+ // (VOL_SYMBOLS). For anything else the screen has no data surface, so
+ // silently ignore rather than clearing the current view.
+ for (int i = 0; i < N_SYMBOLS; ++i) {
+ if (ref.symbol.compare(QString::fromLatin1(VOL_SYMBOLS[i]), Qt::CaseInsensitive) == 0) {
+ if (symbol_combo_->currentIndex() != i)
+ symbol_combo_->setCurrentIndex(i); // triggers on_symbol_changed
+ return;
+ }
+ }
+}
+
+fincept::SymbolRef SurfaceAnalyticsScreen::current_symbol() const {
+ if (selected_symbol_ < 0 || selected_symbol_ >= N_SYMBOLS)
+ return {};
+ return fincept::SymbolRef::equity(QString::fromLatin1(VOL_SYMBOLS[selected_symbol_]));
+}
+
} // namespace fincept::surface
diff --git a/fincept-qt/src/screens/surface_analytics/SurfaceAnalyticsScreen.h b/fincept-qt/src/screens/surface_analytics/SurfaceAnalyticsScreen.h
index 8cf4981fe..6cd925c29 100644
--- a/fincept-qt/src/screens/surface_analytics/SurfaceAnalyticsScreen.h
+++ b/fincept-qt/src/screens/surface_analytics/SurfaceAnalyticsScreen.h
@@ -4,6 +4,7 @@
#include "SurfaceDemoData.h"
#include "SurfaceTypes.h"
+#include "core/symbol/IGroupLinked.h"
#include "screens/IStatefulScreen.h"
#include "services/databento/DatabentoService.h"
@@ -23,8 +24,11 @@ class SurfaceTableWidget;
class SurfaceMetricsPanel;
class SurfaceDatabentoPanel;
-class SurfaceAnalyticsScreen : public QWidget, public fincept::screens::IStatefulScreen {
+class SurfaceAnalyticsScreen : public QWidget,
+ public fincept::screens::IStatefulScreen,
+ public fincept::IGroupLinked {
Q_OBJECT
+ Q_INTERFACES(fincept::IGroupLinked)
public:
explicit SurfaceAnalyticsScreen(QWidget* parent = nullptr);
@@ -33,6 +37,13 @@ class SurfaceAnalyticsScreen : public QWidget, public fincept::screens::IStatefu
QString state_key() const override { return "surface_analytics"; }
int state_version() const override { return 1; }
+ // IGroupLinked — subscribe-only. Only equity group changes are honoured,
+ // and only if the symbol is in VOL_SYMBOLS (the screen's supported list).
+ void set_group(fincept::SymbolGroup g) override { link_group_ = g; }
+ fincept::SymbolGroup group() const override { return link_group_; }
+ void on_group_symbol_changed(const fincept::SymbolRef& ref) override;
+ fincept::SymbolRef current_symbol() const override;
+
private slots:
void on_category_clicked(int index);
void on_surface_clicked(int cat, int surf_index);
@@ -124,6 +135,9 @@ class SurfaceAnalyticsScreen : public QWidget, public fincept::screens::IStatefu
InflationExpData inflation_data_;
MonetaryPolicyData monetary_data_;
+ // Symbol group link — SymbolGroup::None when unlinked.
+ fincept::SymbolGroup link_group_ = fincept::SymbolGroup::None;
+
// Category accent colors (R,G,B)
static constexpr int CAT_COLORS[][3] = {
{51, 153, 255}, // EQUITY DERIV — blue
diff --git a/fincept-qt/src/screens/watchlist/WatchlistScreen.cpp b/fincept-qt/src/screens/watchlist/WatchlistScreen.cpp
index c66063b87..def7d5d9a 100644
--- a/fincept-qt/src/screens/watchlist/WatchlistScreen.cpp
+++ b/fincept-qt/src/screens/watchlist/WatchlistScreen.cpp
@@ -2,6 +2,8 @@
#include "core/logging/Logger.h"
#include "core/session/ScreenStateManager.h"
+#include "core/symbol/SymbolContext.h"
+#include "core/symbol/SymbolDragSource.h"
#include "ui/theme/Theme.h"
#include "ui/theme/ThemeManager.h"
@@ -242,8 +244,33 @@ QWidget* WatchlistScreen::build_main_panel() {
table_->set_column_widths({100, 160, 100, 90, 80, 90, 90, 110});
table_->setSelectionBehavior(QAbstractItemView::SelectRows);
table_->setSelectionMode(QAbstractItemView::SingleSelection);
+
+ // When the user selects a row, publish its symbol into the linked group.
+ // Use itemSelectionChanged rather than cellClicked so keyboard navigation
+ // also propagates.
+ connect(table_, &QTableWidget::itemSelectionChanged, this,
+ &WatchlistScreen::publish_selection_to_group);
+
+ // Drag-out: hold-and-drag a symbol row to broadcast the ticker to any
+ // panel. The provider callback reads the current row at drag-start so
+ // keyboard row-changes are reflected without reinstalling the filter.
+ symbol_dnd::installDragSource(
+ table_->viewport(),
+ [this]() { return current_symbol(); },
+ link_group_);
+
lay->addWidget(table_, 1);
+ // Drop: dropping a symbol onto the watchlist body adds it to the current
+ // watchlist. Happens on the main_panel_ so the drop target is generous
+ // (header, table, sidebar edge all count).
+ symbol_dnd::installDropFilter(main_panel_, [this](const SymbolRef& ref, SymbolGroup) {
+ if (current_wl_id_.isEmpty() || !ref.is_valid())
+ return;
+ fincept::WatchlistRepository::instance().add_stock(current_wl_id_, ref.symbol);
+ load_stocks();
+ });
+
return main_panel_;
}
@@ -450,7 +477,10 @@ void WatchlistScreen::hub_resubscribe_stocks() {
rebuild_from_cache();
});
}
- hub.request(topics);
+ // force=true: watchlist symbols change on user edit; bypass min_interval
+ // so newly-added tickers resolve immediately instead of waiting for the
+ // scheduler tick.
+ hub.request(topics, /*force=*/true);
hub_active_ = true;
}
@@ -599,4 +629,40 @@ void WatchlistScreen::restore_state(const QVariantMap& state) {
// Watchlist not found (may have been deleted) — leave default selection
}
+// ── IGroupLinked ─────────────────────────────────────────────────────────────
+
+void WatchlistScreen::on_group_symbol_changed(const SymbolRef& ref) {
+ if (!table_ || !ref.is_valid())
+ return;
+ // Select the row whose symbol matches; scroll into view. No-op if the
+ // ticker isn't in this watchlist.
+ for (int r = 0; r < stocks_.size(); ++r) {
+ if (stocks_[r].symbol.compare(ref.symbol, Qt::CaseInsensitive) == 0) {
+ QSignalBlocker block(table_); // avoid re-emitting publish
+ table_->selectRow(r);
+ table_->scrollToItem(table_->item(r, 0), QAbstractItemView::PositionAtCenter);
+ return;
+ }
+ }
+}
+
+SymbolRef WatchlistScreen::current_symbol() const {
+ if (!table_)
+ return {};
+ const int r = table_->currentRow();
+ if (r < 0 || r >= stocks_.size())
+ return {};
+ return SymbolRef::equity(stocks_[r].symbol);
+}
+
+void WatchlistScreen::publish_selection_to_group() {
+ if (link_group_ == SymbolGroup::None || !table_)
+ return;
+ const int r = table_->currentRow();
+ if (r < 0 || r >= stocks_.size())
+ return;
+ const SymbolRef ref = SymbolRef::equity(stocks_[r].symbol);
+ SymbolContext::instance().set_group_symbol(link_group_, ref, this);
+}
+
} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/watchlist/WatchlistScreen.h b/fincept-qt/src/screens/watchlist/WatchlistScreen.h
index c1886a5e1..e88749199 100644
--- a/fincept-qt/src/screens/watchlist/WatchlistScreen.h
+++ b/fincept-qt/src/screens/watchlist/WatchlistScreen.h
@@ -1,4 +1,5 @@
#pragma once
+#include "core/symbol/IGroupLinked.h"
#include "screens/IStatefulScreen.h"
#include "services/markets/MarketDataService.h"
#include "storage/repositories/WatchlistRepository.h"
@@ -19,8 +20,9 @@ namespace fincept::screens {
/// Full-screen Watchlist — manage multiple watchlists with live quotes.
/// Layout: Watchlist Sidebar | Stock Table + Controls
-class WatchlistScreen : public QWidget, public IStatefulScreen {
+class WatchlistScreen : public QWidget, public IStatefulScreen, public IGroupLinked {
Q_OBJECT
+ Q_INTERFACES(fincept::IGroupLinked)
public:
explicit WatchlistScreen(QWidget* parent = nullptr);
@@ -29,6 +31,12 @@ class WatchlistScreen : public QWidget, public IStatefulScreen {
QString state_key() const override { return "watchlist"; }
int state_version() const override { return 1; }
+ // IGroupLinked
+ void set_group(SymbolGroup g) override { link_group_ = g; }
+ SymbolGroup group() const override { return link_group_; }
+ void on_group_symbol_changed(const SymbolRef& ref) override;
+ SymbolRef current_symbol() const override;
+
protected:
void showEvent(QShowEvent* event) override;
void hideEvent(QHideEvent* event) override;
@@ -85,6 +93,13 @@ class WatchlistScreen : public QWidget, public IStatefulScreen {
QHash<QString, services::QuoteData> row_cache_;
bool hub_active_ = false;
+
+ // Symbol group link — SymbolGroup::None when unlinked.
+ SymbolGroup link_group_ = SymbolGroup::None;
+
+ // Emit the currently-selected symbol into the linked group, if any.
+ // Safe to call with no selection — no-op.
+ void publish_selection_to_group();
};
} // namespace fincept::screens
diff --git a/fincept-qt/src/services/agents/AgentService.cpp b/fincept-qt/src/services/agents/AgentService.cpp
index 1b6a85edb..7ccc97ca0 100644
--- a/fincept-qt/src/services/agents/AgentService.cpp
+++ b/fincept-qt/src/services/agents/AgentService.cpp
@@ -87,6 +87,8 @@ QJsonObject AgentService::build_api_keys() const {
{"mistral", "MISTRAL_API_KEY"},
{"cohere", "COHERE_API_KEY"},
{"xai", "XAI_API_KEY"},
+ {"kimi", "MOONSHOT_API_KEY"},
+ {"moonshot", "MOONSHOT_API_KEY"},
};
QJsonObject keys;
@@ -1249,6 +1251,28 @@ void AgentService::run_portfolio_analysis(const QString& analysis_type, const QJ
if (!portfolio_summary.isEmpty())
params["portfolio_summary"] = portfolio_summary;
+ // finagent_core's "run" action requires a non-empty `query`. Synthesize
+ // one from the analysis type and include the portfolio context so the
+ // agent has something to answer even if it ignores `portfolio_summary`.
+ QString query;
+ if (analysis_type == "risk")
+ query = "Analyze the risk of this portfolio — concentration, correlation, and downside scenarios. "
+ "Quantify exposures where possible.";
+ else if (analysis_type == "rebalance")
+ query = "Suggest rebalancing actions for this portfolio with specific weight targets and rationale. "
+ "Call out sectors that are over- or under-weight.";
+ else if (analysis_type == "opportunities")
+ query = "Identify opportunities in this portfolio — undervalued positions, missing sectors, and potential "
+ "additions. Prefer concrete candidate tickers.";
+ else
+ query = "Provide a comprehensive analysis of this portfolio with actionable recommendations. "
+ "Organize the output with clear headings.";
+
+ const QString ctx = portfolio_summary.value("context_text").toString();
+ if (!ctx.isEmpty())
+ query = ctx + "\n\nTask: " + query;
+ params["query"] = query;
+
QPointer<AgentService> self = this;
run_python_stdin("run", params, {}, [self](bool ok, QJsonObject result) {
if (!self)
@@ -1256,8 +1280,17 @@ void AgentService::run_portfolio_analysis(const QString& analysis_type, const QJ
AgentExecutionResult r;
r.success = ok && result["success"].toBool(ok);
r.execution_time_ms = result["execution_time_ms"].toInt();
- r.response = result.contains("response") ? result["response"].toString()
- : QJsonDocument(result).toJson(QJsonDocument::Indented);
+ // finagent_core emits the response under one of several keys depending
+ // on the underlying agent (same spread handled by run_agent). Mirror
+ // that extraction order so callers always get usable text.
+ if (result.contains("response") && !result["response"].toString().isEmpty())
+ r.response = result["response"].toString();
+ else if (result.contains("result") && !result["result"].toString().isEmpty())
+ r.response = result["result"].toString();
+ else if (result.contains("data"))
+ r.response = QJsonDocument(result["data"].toObject()).toJson(QJsonDocument::Indented);
+ else
+ r.response = QJsonDocument(result).toJson(QJsonDocument::Indented);
r.error = result["error"].toString();
emit self->agent_result(r);
self->publish_agent_result(r, /*final=*/true);
diff --git a/fincept-qt/src/services/markets/MarketDataService.cpp b/fincept-qt/src/services/markets/MarketDataService.cpp
index 796b0522d..802dcf3f9 100644
--- a/fincept-qt/src/services/markets/MarketDataService.cpp
+++ b/fincept-qt/src/services/markets/MarketDataService.cpp
@@ -2,12 +2,14 @@
#include "core/logging/Logger.h"
#include "python/PythonRunner.h"
+#include "python/PythonWorker.h"
#include "storage/cache/CacheManager.h"
# include "datahub/DataHub.h"
# include "datahub/DataHubMetaTypes.h"
# include "datahub/TopicPolicy.h"
+#include <QDateTime>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
@@ -34,72 +36,185 @@ QStringList MarketDataService::topic_patterns() const {
}
int MarketDataService::max_requests_per_sec() const {
- // PythonRunner caps at 3 concurrent processes; a batched-quote fetch
- // is 2–3 s typical. Capping hub-driven refreshes at 2/s keeps at
- // least one PythonRunner slot for non-quote work.
- return 2;
+ // Raised from 2 to 10: with the merged batch-all refresh path and the
+ // persistent yfinance worker, refreshes complete in <200ms, so gating at
+ // 2 req/s starved cold-start (quote + spark + history arrived 500ms apart).
+ // 10 req/s still backs off enough for upstream yfinance rate limits while
+ // letting dashboard + markets refresh converge in one scheduler tick.
+ return 10;
}
void MarketDataService::refresh(const QStringList& topics) {
- // Hub guarantees `topics` all match one of our patterns. Route each
- // topic family to the matching fetcher.
+ // Hub guarantees `topics` all match one of our patterns. We bundle ALL
+ // three families into a single `yfinance_data.py batch_all` invocation so
+ // one refresh tick spawns one Python process instead of three. Individual
+ // fetch_quotes/fetch_sparklines/fetch_history callback APIs remain untouched
+ // — they're still used by report builder and other one-shot paths.
static const QString kQuote = QStringLiteral("market:quote:");
static const QString kSpark = QStringLiteral("market:sparkline:");
static const QString kHist = QStringLiteral("market:history:");
+ const qint64 refresh_t0 = QDateTime::currentMSecsSinceEpoch();
+
QStringList quote_syms;
QStringList spark_syms;
- QStringList hist_topics; // keep raw — history is parameterised by period/interval
+ struct HistReq { QString topic; QString symbol; QString period; QString interval; };
+ QVector<HistReq> hist_reqs;
for (const auto& t : topics) {
- if (t.startsWith(kQuote))
+ if (t.startsWith(kQuote)) {
quote_syms.append(t.mid(kQuote.size()));
- else if (t.startsWith(kSpark))
+ } else if (t.startsWith(kSpark)) {
spark_syms.append(t.mid(kSpark.size()));
- else if (t.startsWith(kHist))
- hist_topics.append(t);
+ } else if (t.startsWith(kHist)) {
+ const QString tail = t.mid(kHist.size());
+ const QStringList parts = tail.split(QLatin1Char(':'));
+ if (parts.size() == 3)
+ hist_reqs.append({t, parts.at(0), parts.at(1), parts.at(2)});
+ }
}
+ LOG_INFO("DataHub", QString("refresh() quotes=%1 sparks=%2 histories=%3 (1 python spawn)")
+ .arg(quote_syms.size())
+ .arg(spark_syms.size())
+ .arg(hist_reqs.size()));
+
+ // Build the unified batch_all payload.
+ QJsonObject payload;
if (!quote_syms.isEmpty()) {
- LOG_INFO("DataHub", QString("refresh market:quote batch=%1").arg(quote_syms.size()));
- // Routed through batched fetch path. Per-symbol publish happens in
- // flush_batch() so consumers see each result as soon as it resolves.
- fetch_quotes(quote_syms, [](bool, QVector<QuoteData>) {});
+ QJsonArray arr;
+ for (const auto& s : quote_syms) arr.append(s);
+ payload["quotes"] = arr;
}
-
if (!spark_syms.isEmpty()) {
- LOG_INFO("DataHub", QString("refresh market:sparkline batch=%1").arg(spark_syms.size()));
- // Sparkline fetcher returns QHash<symbol, prices>; fan out to hub.
- QPointer<MarketDataService> self = this;
- fetch_sparklines(spark_syms, [self](bool ok, QHash<QString, QVector<double>> data) {
- if (!self || !ok)
- return;
- for (auto it = data.cbegin(); it != data.cend(); ++it)
- self->publish_sparkline_to_hub(it.key(), it.value());
- });
+ QJsonArray arr;
+ for (const auto& s : spark_syms) arr.append(s);
+ payload["sparklines"] = arr;
}
-
- if (!hist_topics.isEmpty()) {
- // History topics are parameterised: `market:history:<sym>:<period>:<interval>`.
- // Dispatch one fetch per unique topic.
- LOG_INFO("DataHub", QString("refresh market:history batch=%1").arg(hist_topics.size()));
- QPointer<MarketDataService> self = this;
- for (const QString& topic : hist_topics) {
- // Strip the prefix and split "<sym>:<period>:<interval>".
- const QString tail = topic.mid(kHist.size());
- const QStringList parts = tail.split(QLatin1Char(':'));
- if (parts.size() != 3)
- continue;
- const QString sym = parts.at(0);
- const QString period = parts.at(1);
- const QString interval = parts.at(2);
- fetch_history(sym, period, interval,
- [self, sym, period, interval](bool ok, QVector<HistoryPoint> points) {
- if (!self || !ok)
- return;
- self->publish_history_to_hub(sym, period, interval, points);
- });
+ if (!hist_reqs.isEmpty()) {
+ QJsonArray arr;
+ for (const auto& h : hist_reqs) {
+ QJsonObject o;
+ o["symbol"] = h.symbol;
+ o["period"] = h.period;
+ o["interval"] = h.interval;
+ arr.append(o);
}
+ payload["histories"] = arr;
+ }
+
+ if (payload.isEmpty()) {
+ return; // Nothing to fetch — hub guarantees this won't happen in practice.
}
+
+ QPointer<MarketDataService> self = this;
+
+ // Route via PythonWorker (persistent daemon) instead of PythonRunner so
+ // we don't pay the 2–3s yfinance/pandas import cost per refresh tick. See
+ // PythonWorker docs — scope is yfinance_data.py only.
+ python::PythonWorker::instance().submit(
+ "batch_all", payload,
+ [self, quote_syms, spark_syms, hist_reqs, refresh_t0](bool ok, QJsonObject root, QString err) {
+ if (!self)
+ return;
+
+ const qint64 elapsed = QDateTime::currentMSecsSinceEpoch() - refresh_t0;
+
+ if (!ok) {
+ LOG_WARN("MarketData",
+ QString("batch_all failed in %1ms: %2").arg(elapsed).arg(err.left(200)));
+ return;
+ }
+
+ // PythonWorker passes through the `result` JSON as-is (or wraps
+ // a scalar under "_value"). For batch_all the daemon returns an
+ // object so root is already the {quotes,sparklines,histories} map.
+ // publish to hub, store in cache. We don't need the flush_batch code
+ // path here because no callback chain is waiting on this refresh tick.
+ const QJsonArray quotes_arr = root.value("quotes").toArray();
+ int quotes_ok = 0;
+ for (const auto& v : quotes_arr) {
+ const QJsonObject q = v.toObject();
+ if (q.isEmpty() || q.contains("error"))
+ continue;
+ QuoteData qd{
+ q["symbol"].toString(),
+ q["name"].toString(q["symbol"].toString()),
+ q["price"].toDouble(),
+ q["change"].toDouble(),
+ q["change_percent"].toDouble(),
+ q["high"].toDouble(),
+ q["low"].toDouble(),
+ q["volume"].toDouble()};
+
+ // Cache write — mirrors store_quote() in flush_batch.
+ QJsonObject co;
+ co["symbol"] = qd.symbol;
+ co["name"] = qd.name;
+ co["price"] = qd.price;
+ co["change"] = qd.change;
+ co["change_pct"] = qd.change_pct;
+ co["high"] = qd.high;
+ co["low"] = qd.low;
+ co["volume"] = qd.volume;
+ fincept::CacheManager::instance().put(
+ "market:" + qd.symbol,
+ QVariant(QString::fromUtf8(QJsonDocument(co).toJson(QJsonDocument::Compact))),
+ kQuoteCacheTtlSec, "market_data");
+
+ self->publish_quote_to_hub(qd);
+ ++quotes_ok;
+ }
+
+ // Sparklines — {sym: [closes]}
+ const QJsonObject sparks = root.value("sparklines").toObject();
+ int sparks_ok = 0;
+ for (auto it = sparks.begin(); it != sparks.end(); ++it) {
+ const QJsonArray closes = it.value().toArray();
+ if (closes.isEmpty())
+ continue;
+ QVector<double> prices;
+ prices.reserve(closes.size());
+ for (const auto& c : closes)
+ prices.append(c.toDouble());
+ self->publish_sparkline_to_hub(it.key(), prices);
+ ++sparks_ok;
+ }
+
+ // Histories — array of {symbol, period, interval, points[]}
+ const QJsonArray hists = root.value("histories").toArray();
+ int hists_ok = 0;
+ for (const auto& hv : hists) {
+ const QJsonObject h = hv.toObject();
+ if (h.contains("error"))
+ continue;
+ const QString sym = h.value("symbol").toString();
+ const QString per = h.value("period").toString();
+ const QString ivl = h.value("interval").toString();
+ const QJsonArray pts = h.value("points").toArray();
+ QVector<HistoryPoint> points;
+ points.reserve(pts.size());
+ for (const auto& pv : pts) {
+ const QJsonObject p = pv.toObject();
+ HistoryPoint pt;
+ pt.timestamp = static_cast<qint64>(p["timestamp"].toDouble());
+ pt.open = p["open"].toDouble();
+ pt.high = p["high"].toDouble();
+ pt.low = p["low"].toDouble();
+ pt.close = p["close"].toDouble();
+ pt.volume = static_cast<qint64>(p["volume"].toDouble());
+ points.append(pt);
+ }
+ self->publish_history_to_hub(sym, per, ivl, points);
+ ++hists_ok;
+ }
+
+ LOG_INFO("MarketData",
+ QString("batch_all OK in %1ms: quotes=%2/%3 sparks=%4/%5 hists=%6/%7")
+ .arg(elapsed)
+ .arg(quotes_ok).arg(quote_syms.size())
+ .arg(sparks_ok).arg(spark_syms.size())
+ .arg(hists_ok).arg(hist_reqs.size()));
+ });
}
void MarketDataService::publish_quote_to_hub(const QuoteData& q) {
@@ -127,25 +242,30 @@ void MarketDataService::ensure_registered_with_hub() {
auto& hub = datahub::DataHub::instance();
hub.register_producer(this);
- // Quotes: 30s TTL, 5s min interval (matches Phase 2 pilot).
+ // Quotes: 30s TTL, 2s min interval. Dropped min_interval from 5s → 2s so
+ // user-triggered refreshes and initial cold-start paint don't queue behind
+ // the gate. 2s still prevents hammering yfinance on scheduler ticks.
datahub::TopicPolicy quote_p;
quote_p.ttl_ms = 30'000;
- quote_p.min_interval_ms = 5'000;
+ quote_p.min_interval_ms = 2'000;
hub.set_policy_pattern(QStringLiteral("market:quote:*"), quote_p);
- // Sparklines: 5-day hourly data, changes slowly — cache 10 minutes, refresh at most
- // every 60s so a dashboard with 20 holdings doesn't hammer the sparkline script.
+ // Sparklines: 5-day hourly data, changes slowly — cache 10 minutes,
+ // refresh at most every 30s. Reduced from 60s so a user flipping between
+ // screens doesn't wait a full minute for sparkline refresh after swapping
+ // the symbol set.
datahub::TopicPolicy spark_p;
spark_p.ttl_ms = 10 * 60'000;
- spark_p.min_interval_ms = 60'000;
+ spark_p.min_interval_ms = 30'000;
hub.set_policy_pattern(QStringLiteral("market:sparkline:*"), spark_p);
// History: OHLCV series. One-shot per chart; policies are conservative to
- // avoid re-fetching for every open of the same chart. 30 min TTL, 5 min
- // min-interval so a user flipping periods still triggers a fresh fetch.
+ // avoid re-fetching for every open of the same chart. 30 min TTL, 60s
+ // min-interval (was 5 min) so a user flipping periods/intervals on a
+ // chart doesn't stare at a stale view for 5 minutes.
datahub::TopicPolicy hist_p;
hist_p.ttl_ms = 30 * 60'000;
- hist_p.min_interval_ms = 5 * 60'000;
+ hist_p.min_interval_ms = 60'000;
hub.set_policy_pattern(QStringLiteral("market:history:*"), hist_p);
hub_registered_ = true;
diff --git a/fincept-qt/src/services/portfolio/PortfolioService.cpp b/fincept-qt/src/services/portfolio/PortfolioService.cpp
index f4f834965..ac4ec0acd 100644
--- a/fincept-qt/src/services/portfolio/PortfolioService.cpp
+++ b/fincept-qt/src/services/portfolio/PortfolioService.cpp
@@ -3,6 +3,7 @@
#include "core/logging/Logger.h"
#include "python/PythonRunner.h"
+#include "services/sectors/SectorResolver.h"
#include "storage/repositories/PortfolioRepository.h"
#include "storage/repositories/SettingsRepository.h"
@@ -25,7 +26,38 @@ PortfolioService& PortfolioService::instance() {
return s;
}
-PortfolioService::PortfolioService() : QObject(nullptr) {}
+PortfolioService::PortfolioService() : QObject(nullptr) {
+ // When the SectorResolver lands a fresh sector for a symbol, persist it
+ // onto whichever portfolios hold it and invalidate their summary caches
+ // so the Sectors tab refreshes on next refresh.
+ connect(&SectorResolver::instance(), &SectorResolver::sector_resolved, this,
+ [this](QString symbol, QString sector) {
+ if (symbol.isEmpty() || sector.isEmpty())
+ return;
+ auto& repo = PortfolioRepository::instance();
+ auto ports = repo.list_portfolios();
+ if (ports.is_err())
+ return;
+ for (const auto& p : ports.value()) {
+ auto assets = repo.get_assets(p.id);
+ if (assets.is_err())
+ continue;
+ bool touched = false;
+ for (const auto& a : assets.value()) {
+ if (a.symbol == symbol && a.sector != sector) {
+ repo.set_asset_sector(p.id, symbol, sector);
+ touched = true;
+ }
+ }
+ if (touched) {
+ invalidate_cache(p.id);
+ // Refresh the active portfolio view so sectors appear
+ // without the user having to hit refresh manually.
+ load_summary(p.id);
+ }
+ }
+ });
+}
// ── Portfolio CRUD ───────────────────────────────────────────────────────────
@@ -145,6 +177,11 @@ void PortfolioService::build_summary(const QString& portfolio_id, const QVector<
h.quantity = asset.quantity;
h.avg_buy_price = asset.avg_buy_price;
h.cost_basis = asset.quantity * asset.avg_buy_price;
+ // Prefer stored sector; fall back to resolver cache (which may
+ // populate async — see sector_resolved handler in constructor).
+ h.sector = asset.sector.isEmpty()
+ ? SectorResolver::instance().sector_for(asset.symbol)
+ : asset.sector;
auto it = quote_map.find(asset.symbol);
if (it != quote_map.end()) {
@@ -393,14 +430,34 @@ print(json.dumps(matrix))
// ── SPY benchmark data ────────────────────────────────────────────────────────
+QString PortfolioService::default_benchmark_for_currency(const QString& currency) {
+ const QString c = currency.trimmed().toUpper();
+ if (c == "CAD") return QStringLiteral("^GSPTSE");
+ if (c == "GBP") return QStringLiteral("^FTSE");
+ if (c == "EUR") return QStringLiteral("^STOXX50E");
+ if (c == "AUD") return QStringLiteral("^AXJO");
+ if (c == "INR") return QStringLiteral("^NSEI");
+ if (c == "JPY") return QStringLiteral("^N225");
+ if (c == "HKD") return QStringLiteral("^HSI");
+ return QStringLiteral("SPY"); // USD and unknown
+}
+
void PortfolioService::fetch_spy_history(const QString& period) {
+ fetch_benchmark_history(QStringLiteral("SPY"), period);
+}
+
+void PortfolioService::fetch_benchmark_history(const QString& symbol, const QString& period) {
+ // Allow callers to omit the symbol → defaults to SPY (legacy behaviour).
+ const QString sym = symbol.isEmpty() ? QStringLiteral("SPY") : symbol;
+
const QString code = QString(R"python(
import json, sys
import yfinance as yf
-period = "%1"
+symbol = "%1"
+period = "%2"
try:
- hist = yf.download("SPY", period=period, interval="1d", progress=False)
+ hist = yf.download(symbol, period=period, interval="1d", progress=False, auto_adjust=True)
dates = []
closes = []
if hist is not None and not hist.empty:
@@ -409,42 +466,46 @@ try:
if hasattr(v, "item"): v = v.item()
dates.append(dt.strftime("%Y-%m-%d"))
closes.append(float(v))
- print(json.dumps({"dates": dates, "closes": closes}))
+ print(json.dumps({"symbol": symbol, "dates": dates, "closes": closes}))
except Exception as e:
- print(json.dumps({"dates": [], "closes": [], "error": str(e)}))
+ print(json.dumps({"symbol": symbol, "dates": [], "closes": [], "error": str(e)}))
)python")
- .arg(period);
+ .arg(sym, period);
QPointer<PortfolioService> self = this;
- python::PythonRunner::instance().run_code(code, [self](python::PythonResult result) {
+ python::PythonRunner::instance().run_code(code, [self, sym](python::PythonResult result) {
if (!self)
return;
+ QStringList dates;
+ QVector<double> closes;
if (!result.success || result.output.trimmed().isEmpty()) {
- LOG_WARN("PortfolioSvc", "SPY fetch failed: " + result.error.left(200));
- emit self->spy_history_loaded({}, {});
- return;
+ LOG_WARN("PortfolioSvc",
+ QString("Benchmark %1 fetch failed: %2").arg(sym, result.error.left(200)));
+ } else {
+ QJsonParseError err;
+ const auto doc = QJsonDocument::fromJson(result.output.trimmed().toUtf8(), &err);
+ if (err.error == QJsonParseError::NoError && doc.isObject()) {
+ const auto obj = doc.object();
+ const auto dates_arr = obj["dates"].toArray();
+ const auto closes_arr = obj["closes"].toArray();
+ dates.reserve(dates_arr.size());
+ closes.reserve(closes_arr.size());
+ for (const auto& v : dates_arr)
+ dates.append(v.toString());
+ for (const auto& v : closes_arr)
+ closes.append(v.toDouble());
+ }
}
- QJsonParseError err;
- const auto doc = QJsonDocument::fromJson(result.output.trimmed().toUtf8(), &err);
- if (err.error != QJsonParseError::NoError) {
- emit self->spy_history_loaded({}, {});
- return;
+
+ // Beta computation in compute_metrics() always regresses against SPY,
+ // so only update that cache when SPY is what the caller asked for —
+ // otherwise we would corrupt Beta with e.g. TSX returns.
+ if (sym == QStringLiteral("SPY")) {
+ self->spy_dates_cache_ = dates;
+ self->spy_closes_cache_ = closes;
+ emit self->spy_history_loaded(dates, closes);
}
- const auto obj = doc.object();
- const auto dates_arr = obj["dates"].toArray();
- const auto closes_arr = obj["closes"].toArray();
- QStringList dates;
- QVector<double> closes;
- dates.reserve(dates_arr.size());
- closes.reserve(closes_arr.size());
- for (const auto& v : dates_arr)
- dates.append(v.toString());
- for (const auto& v : closes_arr)
- closes.append(v.toDouble());
- // Cache for OLS beta in compute_metrics
- self->spy_dates_cache_ = dates;
- self->spy_closes_cache_ = closes;
- emit self->spy_history_loaded(dates, closes);
+ emit self->benchmark_history_loaded(sym, dates, closes);
});
}
@@ -540,6 +601,17 @@ void PortfolioService::compute_metrics(const portfolio::PortfolioSummary& summar
// loading snapshots from SQLite which is sub-millisecond for <365 rows)
auto snap_r = PortfolioRepository::instance().get_snapshots(summary.portfolio.id, 365);
if (snap_r.is_err() || snap_r.value().size() < 3) {
+ // Trigger an async backfill so the next compute_metrics call has data.
+ // This is one-shot per process to avoid hammering yfinance — once we've
+ // attempted, the user can manually re-trigger via re-import.
+ if (!backfill_attempted_.contains(summary.portfolio.id)) {
+ backfill_attempted_.insert(summary.portfolio.id);
+ QPointer<PortfolioService> self = this;
+ const QString pid = summary.portfolio.id;
+ QMetaObject::invokeMethod(this, [self, pid]() {
+ if (self) self->backfill_history(pid, "1y");
+ }, Qt::QueuedConnection);
+ }
// Fallback: derive volatility from cross-sectional day changes only
double sum = 0, sum_sq = 0;
int n = 0;
@@ -815,11 +887,61 @@ void PortfolioService::import_json(const QString& file_path, portfolio::ImportMo
}
auto root = doc.object();
- QString name = root["portfolio_name"].toString("Imported Portfolio");
+
+ // Schema validation — the importer only accepts the terminal's own export format:
+ // { "portfolio_name": "...", "currency": "...", "transactions": [ {date,symbol,type,quantity,price}, ... ] }
+ // Reject anything else up front so we don't create empty/mis-named portfolios.
+ const QString schema_msg =
+ "Unsupported JSON format. Expected the terminal's export format with fields "
+ "'portfolio_name' (string) and 'transactions' (array of {date, symbol, type, quantity, price}). "
+ "Holdings-only snapshots are not supported — convert each holding to a BUY transaction first.";
+
+ if (!root.contains("portfolio_name") || !root.value("portfolio_name").isString() ||
+ root.value("portfolio_name").toString().trimmed().isEmpty()) {
+ emit import_complete({"", "", 0, {schema_msg}});
+ LOG_ERROR("PortfolioSvc", "Import rejected: missing/invalid 'portfolio_name'");
+ return;
+ }
+ if (!root.contains("transactions") || !root.value("transactions").isArray()) {
+ emit import_complete({"", "", 0, {schema_msg}});
+ LOG_ERROR("PortfolioSvc", "Import rejected: missing/invalid 'transactions' array");
+ return;
+ }
+
+ QString name = root["portfolio_name"].toString();
QString owner = root["owner"].toString("");
QString currency = root["currency"].toString("USD");
auto txn_arr = root["transactions"].toArray();
+ if (txn_arr.isEmpty()) {
+ emit import_complete({"", name, 0, {"No transactions found in file. " + schema_msg}});
+ LOG_ERROR("PortfolioSvc", "Import rejected: 'transactions' array is empty");
+ return;
+ }
+
+ // Collect symbol → sector mapping from any hints the file provides:
+ // 1. top-level "holdings[]" (legacy broker-export format) — symbol + sector
+ // 2. per-transaction "sector" field
+ // Either/both populate an authoritative override we hand to SectorResolver
+ // so the Sectors tab is correct without waiting on a yfinance round-trip.
+ QHash<QString, QString> sector_hints;
+ if (root.contains("holdings") && root.value("holdings").isArray()) {
+ for (const auto& v : root.value("holdings").toArray()) {
+ auto obj = v.toObject();
+ QString sym = obj.value("symbol").toString().trimmed().toUpper();
+ QString sec = obj.value("sector").toString().trimmed();
+ if (!sym.isEmpty() && !sec.isEmpty())
+ sector_hints.insert(sym, sec);
+ }
+ }
+ for (const auto& v : txn_arr) {
+ auto obj = v.toObject();
+ QString sym = obj.value("symbol").toString().trimmed().toUpper();
+ QString sec = obj.value("sector").toString().trimmed();
+ if (!sym.isEmpty() && !sec.isEmpty() && !sector_hints.contains(sym))
+ sector_hints.insert(sym, sec);
+ }
+
auto& repo = PortfolioRepository::instance();
QString target_id;
@@ -854,7 +976,8 @@ void PortfolioService::import_json(const QString& file_path, portfolio::ImportMo
QString date = obj["date"].toString();
if (type == "BUY") {
- auto r = repo.add_asset(target_id, sym, qty, price, date);
+ QString hint_sector = sector_hints.value(sym.toUpper());
+ auto r = repo.add_asset(target_id, sym, qty, price, date, hint_sector);
if (r.is_err()) {
errors.append(QString("BUY %1: %2").arg(sym, QString::fromStdString(r.error())));
continue;
@@ -890,12 +1013,32 @@ void PortfolioService::import_json(const QString& file_path, portfolio::ImportMo
++replayed;
}
+ // Seed SectorResolver with authoritative mapping from the import file,
+ // and kick off async resolution for any symbols that had no hint.
+ for (auto it = sector_hints.constBegin(); it != sector_hints.constEnd(); ++it)
+ SectorResolver::instance().remember(it.key(), it.value());
+
+ QStringList unresolved;
+ if (auto assets = repo.get_assets(target_id); assets.is_ok()) {
+ for (const auto& a : assets.value())
+ if (a.sector.isEmpty())
+ unresolved << a.symbol;
+ }
+ if (!unresolved.isEmpty())
+ SectorResolver::instance().prefetch(unresolved);
+
invalidate_cache(target_id);
load_portfolios();
emit import_complete({target_id, name, replayed, errors});
LOG_INFO("PortfolioSvc",
QString("Imported %1 transactions into %2, %3 errors").arg(replayed).arg(target_id).arg(errors.size()));
+
+ // Backfill 1y of historical NAV from yfinance so Beta and MDD have data
+ // immediately. Async — fires history_backfilled when done; the screen's
+ // metrics_computed handler will already have reloaded snapshots once the
+ // user refreshes (or on next compute_metrics call).
+ backfill_history(target_id, "1y");
}
// ── Snapshots ────────────────────────────────────────────────────────────────
@@ -909,6 +1052,82 @@ void PortfolioService::load_snapshots(const QString& portfolio_id, int days) {
}
}
+void PortfolioService::backfill_history(const QString& portfolio_id, const QString& period) {
+ if (portfolio_id.isEmpty())
+ return;
+
+ auto& repo = PortfolioRepository::instance();
+ auto assets_r = repo.get_assets(portfolio_id);
+ if (assets_r.is_err() || assets_r.value().isEmpty()) {
+ emit history_backfilled(portfolio_id, 0);
+ return;
+ }
+ const auto assets = assets_r.value();
+
+ // Build the args list: [portfolio_nav_history, period, sym1, qty1, sym2, qty2, ...]
+ // Cost basis is the same for every backfilled day (we don't have transaction-time
+ // cost basis), so save_snapshot's pnl_pct uses today's cost — see comment below.
+ QStringList args;
+ args << "portfolio_nav_history" << period;
+ double total_cost_basis = 0.0;
+ for (const auto& a : assets) {
+ args << a.symbol << QString::number(a.quantity, 'f', 8);
+ total_cost_basis += a.quantity * a.avg_buy_price;
+ }
+
+ QPointer<PortfolioService> self = this;
+ python::PythonRunner::instance().run("yfinance_data.py", args,
+ [self, portfolio_id, total_cost_basis](python::PythonResult result) {
+ if (!self)
+ return;
+ if (!result.success || result.output.trimmed().isEmpty()) {
+ LOG_WARN("PortfolioSvc",
+ QString("backfill_history failed for %1: %2").arg(portfolio_id, result.error.left(200)));
+ emit self->history_backfilled(portfolio_id, 0);
+ return;
+ }
+ QJsonParseError err;
+ const auto doc = QJsonDocument::fromJson(result.output.trimmed().toUtf8(), &err);
+ if (err.error != QJsonParseError::NoError || !doc.isObject()) {
+ LOG_WARN("PortfolioSvc", "backfill_history: bad JSON: " + err.errorString());
+ emit self->history_backfilled(portfolio_id, 0);
+ return;
+ }
+ const auto obj = doc.object();
+ if (obj.contains("error")) {
+ LOG_WARN("PortfolioSvc", "backfill_history: " + obj["error"].toString());
+ emit self->history_backfilled(portfolio_id, 0);
+ return;
+ }
+ const auto dates = obj["dates"].toArray();
+ const auto navs = obj["navs"].toArray();
+ if (dates.isEmpty() || dates.size() != navs.size()) {
+ emit self->history_backfilled(portfolio_id, 0);
+ return;
+ }
+
+ // Upsert each row. INSERT OR REPLACE keyed by (portfolio_id, snapshot_date)
+ // so re-running backfill (with a different period or after the user adds
+ // holdings) corrects existing rows in place.
+ auto& repo = PortfolioRepository::instance();
+ int written = 0;
+ for (int i = 0; i < dates.size(); ++i) {
+ const QString d = dates[i].toString();
+ const double nav = navs[i].toDouble();
+ const double pnl = nav - total_cost_basis;
+ const double pnl_pct = total_cost_basis > 0 ? (pnl / total_cost_basis) * 100.0 : 0.0;
+ auto wr = repo.save_snapshot(portfolio_id, nav, total_cost_basis, pnl, pnl_pct, d);
+ if (wr.is_ok())
+ ++written;
+ }
+
+ LOG_INFO("PortfolioSvc",
+ QString("Backfilled %1 historical snapshots for %2").arg(written).arg(portfolio_id));
+ self->invalidate_cache(portfolio_id);
+ emit self->history_backfilled(portfolio_id, written);
+ });
+}
+
// ── Cache control ────────────────────────────────────────────────────────────
void PortfolioService::invalidate_cache(const QString& portfolio_id) {
diff --git a/fincept-qt/src/services/portfolio/PortfolioService.h b/fincept-qt/src/services/portfolio/PortfolioService.h
index 3c63f9201..c1272e2fd 100644
--- a/fincept-qt/src/services/portfolio/PortfolioService.h
+++ b/fincept-qt/src/services/portfolio/PortfolioService.h
@@ -7,6 +7,7 @@
#include <QDateTime>
#include <QHash>
#include <QMutex>
+#include <QSet>
#include <QObject>
#include <QPointer>
#include <QTimer>
@@ -51,9 +52,16 @@ class PortfolioService : public QObject {
/// correlation matrix. Result emitted via correlation_computed().
void fetch_correlation(const QStringList& symbols);
- // ── SPY benchmark data ────────────────────────────────────────────────────
- /// Fetch SPY daily closes for the given period string (e.g. "1y", "6mo").
- /// Emits spy_history_loaded(dates, closes).
+ // ── Benchmark data ───────────────────────────────────────────────────────
+ /// Fetch daily closes for an arbitrary benchmark ticker (defaults to SPY
+ /// for backward compatibility). Emits benchmark_history_loaded(symbol, ...)
+ /// AND the legacy spy_history_loaded(...) so older consumers keep working.
+ void fetch_benchmark_history(const QString& symbol = "SPY", const QString& period = "1y");
+ /// Convenience wrapper: pick a default benchmark from a portfolio currency
+ /// (CAD → ^GSPTSE, USD → SPY, GBP → ^FTSE, EUR → ^STOXX50E, AUD → ^AXJO,
+ /// INR → ^NSEI). Falls back to SPY for unknown currencies.
+ static QString default_benchmark_for_currency(const QString& currency);
+ /// Legacy shim — calls fetch_benchmark_history("SPY", period).
void fetch_spy_history(const QString& period = "1y");
// ── Risk-free rate ────────────────────────────────────────────────────────
@@ -72,6 +80,15 @@ class PortfolioService : public QObject {
// ── Snapshots (performance history) ─────────────────────────────────────
void load_snapshots(const QString& portfolio_id, int days = 365);
+ /// Reconstruct daily NAV from yfinance OHLC for the current holdings and
+ /// upsert one row per trading day into portfolio_snapshots. This is what
+ /// gives Beta and MDD a real time series on a freshly imported portfolio
+ /// — without it both metrics show "—" until the user keeps the app open
+ /// across enough days for daily snapshots to accumulate.
+ /// Period: e.g. "1mo" / "6mo" / "1y" / "5y" (yfinance period strings).
+ /// Emits history_backfilled(portfolio_id, point_count) on success.
+ void backfill_history(const QString& portfolio_id, const QString& period = "1y");
+
// ── Cache control ────────────────────────────────────────────────────────
void invalidate_cache(const QString& portfolio_id);
@@ -99,11 +116,21 @@ class PortfolioService : public QObject {
void correlation_computed(QHash<QString, double> matrix);
/// SPY daily close history: parallel vectors of ISO date strings and prices.
+ /// Kept for back-compat — also fired whenever benchmark_history_loaded fires
+ /// with symbol == "SPY" so existing consumers don't break.
void spy_history_loaded(QStringList dates, QVector<double> closes);
+ /// Generalised benchmark history: includes the symbol so chart consumers
+ /// can label the overlay correctly when a non-SPY benchmark is requested.
+ void benchmark_history_loaded(QString symbol, QStringList dates, QVector<double> closes);
+
/// Current 10-year risk-free rate as annual decimal (e.g. 0.043 = 4.3%).
void risk_free_rate_loaded(double rate);
+ /// Fired when backfill_history finishes. point_count is the number of
+ /// trading days written (0 on failure).
+ void history_backfilled(QString portfolio_id, int point_count);
+
private:
PortfolioService();
@@ -124,11 +151,18 @@ class PortfolioService : public QObject {
static constexpr int kCacheTtlSec = 300; // 5 minutes
// ── SPY cache (for OLS beta in compute_metrics) ──────────────────────────
+ // Beta is always computed against SPY regardless of which benchmark is
+ // shown on the chart, so the cache keys to "SPY" specifically.
QStringList spy_dates_cache_;
QVector<double> spy_closes_cache_;
// ── Risk-free rate cache (annual decimal, e.g. 0.043) ────────────────────
double rf_rate_ = 0.04; // default 4% until FRED responds
+
+ // ── Backfill state ───────────────────────────────────────────────────────
+ // Per-portfolio guard so compute_metrics doesn't kick off backfill on
+ // every refresh tick. Cleared on app restart — that's the explicit retry.
+ QSet<QString> backfill_attempted_;
};
} // namespace fincept::services
diff --git a/fincept-qt/src/services/pushpins/PushpinService.cpp b/fincept-qt/src/services/pushpins/PushpinService.cpp
new file mode 100644
index 000000000..2851680bd
--- /dev/null
+++ b/fincept-qt/src/services/pushpins/PushpinService.cpp
@@ -0,0 +1,85 @@
+#include "services/pushpins/PushpinService.h"
+
+#include <QJsonArray>
+#include <QJsonDocument>
+#include <QJsonObject>
+#include <QSettings>
+
+namespace fincept {
+
+PushpinService& PushpinService::instance() {
+ static PushpinService s;
+ return s;
+}
+
+PushpinService::PushpinService() {
+ load();
+}
+
+bool PushpinService::contains(const SymbolRef& ref) const {
+ for (const SymbolRef& p : pins_)
+ if (p == ref)
+ return true;
+ return false;
+}
+
+void PushpinService::pin(const SymbolRef& ref) {
+ if (!ref.is_valid() || contains(ref))
+ return;
+ pins_.append(ref);
+ save();
+ emit pins_changed();
+}
+
+void PushpinService::unpin(const SymbolRef& ref) {
+ const int before = static_cast<int>(pins_.size());
+ pins_.erase(std::remove_if(pins_.begin(), pins_.end(),
+ [&ref](const SymbolRef& p) { return p == ref; }),
+ pins_.end());
+ if (static_cast<int>(pins_.size()) != before) {
+ save();
+ emit pins_changed();
+ }
+}
+
+void PushpinService::clear() {
+ if (pins_.isEmpty())
+ return;
+ pins_.clear();
+ save();
+ emit pins_changed();
+}
+
+void PushpinService::move(const SymbolRef& ref, int new_index) {
+ const int old = pins_.indexOf(ref);
+ if (old < 0 || new_index < 0 || new_index >= pins_.size() || old == new_index)
+ return;
+ pins_.move(old, new_index);
+ save();
+ emit pins_changed();
+}
+
+void PushpinService::load() {
+ QSettings settings("Fincept", "FinceptTerminal");
+ const QByteArray blob = settings.value("pushpins/list").toByteArray();
+ const QJsonDocument doc = QJsonDocument::fromJson(blob);
+ if (!doc.isArray())
+ return;
+ for (const QJsonValue& v : doc.array()) {
+ if (!v.isObject())
+ continue;
+ const SymbolRef r = SymbolRef::from_json(v.toObject());
+ if (r.is_valid())
+ pins_.append(r);
+ }
+}
+
+void PushpinService::save() const {
+ QJsonArray arr;
+ for (const SymbolRef& p : pins_)
+ arr.append(p.to_json());
+ QSettings settings("Fincept", "FinceptTerminal");
+ settings.setValue("pushpins/list", QJsonDocument(arr).toJson(QJsonDocument::Compact));
+}
+
+} // namespace fincept
diff --git a/fincept-qt/src/services/pushpins/PushpinService.h b/fincept-qt/src/services/pushpins/PushpinService.h
new file mode 100644
index 000000000..127e3784b
--- /dev/null
+++ b/fincept-qt/src/services/pushpins/PushpinService.h
@@ -0,0 +1,45 @@
+#pragma once
+#include "core/symbol/SymbolRef.h"
+
+#include <QList>
+#include <QObject>
+
+namespace fincept {
+
+/// Singleton model backing the persistent symbol chip strip (Bloomberg
+/// "Pushpins" equivalent). Pins are user-scoped — they follow the user
+/// across workspaces and terminal sessions, stored in QSettings under
+/// "pushpins/list".
+///
+/// The service is deliberately thin: add/remove/list/clear plus a single
+/// signal that fires after any mutation. Consumers (PushpinBar) simply
+/// rebuild themselves from pins() on change.
+class PushpinService : public QObject {
+ Q_OBJECT
+ public:
+ static PushpinService& instance();
+
+ QList<SymbolRef> pins() const { return pins_; }
+ bool contains(const SymbolRef& ref) const;
+
+ /// Idempotent — pinning the same symbol twice has no effect.
+ void pin(const SymbolRef& ref);
+ void unpin(const SymbolRef& ref);
+ void clear();
+
+ /// Move `ref` to a new index (for drag-reorder within the bar).
+ /// No-op if ref is not pinned or new_index is out of range.
+ void move(const SymbolRef& ref, int new_index);
+
+ signals:
+ void pins_changed();
+
+ private:
+ PushpinService();
+ void load();
+ void save() const;
+
+ QList<SymbolRef> pins_;
+};
+
+} // namespace fincept
diff --git a/fincept-qt/src/services/sectors/SectorResolver.cpp b/fincept-qt/src/services/sectors/SectorResolver.cpp
new file mode 100644
index 000000000..4f2904974
--- /dev/null
+++ b/fincept-qt/src/services/sectors/SectorResolver.cpp
@@ -0,0 +1,195 @@
+#include "services/sectors/SectorResolver.h"
+
+#include "core/logging/Logger.h"
+#include "services/markets/MarketDataService.h"
+#include "storage/sqlite/Database.h"
+
+#include <QDateTime>
+#include <QPointer>
+#include <QSqlError>
+#include <QSqlQuery>
+#include <QVariant>
+
+namespace fincept::services {
+
+namespace {
+
+constexpr qint64 kNegativeTtlSeconds = 7 * 24 * 3600; // 7 days
+
+// Symbols that look like TSX bare tickers (letters only, 1–4 chars, no dot).
+// We try a `.TO` suffix first before giving up, since many Canadian holdings
+// in imported portfolios arrive without the exchange suffix.
+bool looks_like_canadian_bare(const QString& symbol) {
+ if (symbol.contains('.') || symbol.contains('-') || symbol.contains('='))
+ return false;
+ if (symbol.length() < 1 || symbol.length() > 5)
+ return false;
+ for (auto ch : symbol) {
+ if (!ch.isLetter())
+ return false;
+ }
+ return true;
+}
+
+} // namespace
+
+SectorResolver& SectorResolver::instance() {
+ static SectorResolver s;
+ return s;
+}
+
+SectorResolver::SectorResolver() {
+ load_cache();
+}
+
+QString SectorResolver::normalize(const QString& symbol) {
+ return symbol.trimmed().toUpper();
+}
+
+QString SectorResolver::fallback_for_unresolvable(const QString& symbol) {
+ // Heuristic: symbols ending in letters with no exchange suffix and length
+ // >= 5 that failed yfinance are almost always Canadian mutual fund codes
+ // like TDB8150. Treat those as Cash/Fund.
+ if (symbol.length() >= 6 && symbol.startsWith("TDB"))
+ return "Cash";
+ return "Unclassified";
+}
+
+void SectorResolver::load_cache() {
+ auto& db_mgr = fincept::Database::instance();
+ if (!db_mgr.is_open())
+ return;
+
+ QSqlQuery q(db_mgr.raw_db());
+ if (!q.exec("SELECT symbol, sector, resolved_at FROM sector_cache")) {
+ LOG_WARN("SectorResolver", "Cache load failed: " + q.lastError().text());
+ return;
+ }
+
+ QMutexLocker lock(&mutex_);
+ qint64 now = QDateTime::currentSecsSinceEpoch();
+ int loaded = 0;
+ while (q.next()) {
+ QString sym = q.value(0).toString();
+ QString sec = q.value(1).toString();
+ qint64 resolved = q.value(2).toLongLong();
+
+ // Drop stale negative cache entries (sector == Unclassified/empty and
+ // older than TTL) so we retry on next access.
+ bool is_negative = sec.isEmpty() || sec == "Unclassified";
+ if (is_negative && (now - resolved) > kNegativeTtlSeconds)
+ continue;
+
+ if (!sec.isEmpty()) {
+ cache_.insert(sym, sec);
+ ++loaded;
+ }
+ }
+ LOG_INFO("SectorResolver", QString("Loaded %1 sector cache entries").arg(loaded));
+}
+
+void SectorResolver::persist(const QString& symbol, const QString& sector, const QString& industry,
+ const QString& quote_type) {
+ auto& db_mgr = fincept::Database::instance();
+ if (!db_mgr.is_open())
+ return;
+
+ QSqlQuery q(db_mgr.raw_db());
+ q.prepare("INSERT INTO sector_cache (symbol, sector, industry, quote_type, resolved_at) "
+ "VALUES (?, ?, ?, ?, ?) "
+ "ON CONFLICT(symbol) DO UPDATE SET "
+ "sector=excluded.sector, industry=excluded.industry, "
+ "quote_type=excluded.quote_type, resolved_at=excluded.resolved_at");
+ q.addBindValue(symbol);
+ q.addBindValue(sector);
+ q.addBindValue(industry);
+ q.addBindValue(quote_type);
+ q.addBindValue(QDateTime::currentSecsSinceEpoch());
+ if (!q.exec())
+ LOG_WARN("SectorResolver", "Cache write failed: " + q.lastError().text());
+}
+
+void SectorResolver::remember(const QString& symbol, const QString& sector) {
+ QString sym = normalize(symbol);
+ QString sec = sector.trimmed();
+ if (sym.isEmpty() || sec.isEmpty())
+ return;
+
+ {
+ QMutexLocker lock(&mutex_);
+ cache_.insert(sym, sec);
+ }
+ persist(sym, sec, {}, "override");
+ emit sector_resolved(sym, sec);
+}
+
+QString SectorResolver::sector_for(const QString& symbol) {
+ QString sym = normalize(symbol);
+ if (sym.isEmpty())
+ return {};
+
+ QMutexLocker lock(&mutex_);
+ auto it = cache_.constFind(sym);
+ if (it != cache_.constEnd())
+ return it.value();
+
+ if (!inflight_.contains(sym)) {
+ inflight_.insert(sym);
+ lock.unlock();
+ resolve_async(sym);
+ }
+ return {};
+}
+
+void SectorResolver::prefetch(const QStringList& symbols) {
+ for (const auto& s : symbols)
+ (void)sector_for(s);
+}
+
+void SectorResolver::resolve_async(const QString& symbol) {
+ QPointer<SectorResolver> self = this;
+
+ auto finish = [self, symbol](QString sector, QString industry, QString quote_type) {
+ if (!self)
+ return;
+ QString final_sector = sector.trimmed();
+ if (final_sector.isEmpty() || final_sector == "N/A") {
+ // yfinance didn't resolve — use a graceful fallback.
+ final_sector = SectorResolver::fallback_for_unresolvable(symbol);
+ }
+ {
+ QMutexLocker lock(&self->mutex_);
+ self->cache_.insert(symbol, final_sector);
+ self->inflight_.remove(symbol);
+ }
+ self->persist(symbol, final_sector, industry, quote_type);
+ emit self->sector_resolved(symbol, final_sector);
+ };
+
+ // Try 1: as-is.
+ MarketDataService::instance().fetch_info(symbol, [self, symbol, finish](bool ok, InfoData info) {
+ if (!self)
+ return;
+ QString sector = info.sector.trimmed();
+ bool resolved = ok && !sector.isEmpty() && sector != "N/A";
+ if (resolved) {
+ finish(sector, info.industry, {});
+ return;
+ }
+
+ // Try 2: TSX suffix fallback for bare Canadian tickers.
+ if (looks_like_canadian_bare(symbol)) {
+ QString tsx_symbol = symbol + ".TO";
+ MarketDataService::instance().fetch_info(
+ tsx_symbol, [self, symbol, finish](bool ok2, InfoData info2) {
+ if (!self)
+ return;
+ finish(ok2 ? info2.sector : QString{}, info2.industry, {});
+ });
+ return;
+ }
+ finish({}, info.industry, {});
+ });
+}
+
+} // namespace fincept::services
diff --git a/fincept-qt/src/services/sectors/SectorResolver.h b/fincept-qt/src/services/sectors/SectorResolver.h
new file mode 100644
index 000000000..465d8dd72
--- /dev/null
+++ b/fincept-qt/src/services/sectors/SectorResolver.h
@@ -0,0 +1,68 @@
+#pragma once
+// SectorResolver.h — Singleton that maps symbols to sector labels.
+//
+// Resolution order per symbol:
+// 1. In-memory cache (populated from `sector_cache` SQLite table at startup).
+// 2. Explicit override passed via remember().
+// 3. yfinance `info` lookup through MarketDataService. We retry with a `.TO`
+// suffix for Canadian TSX symbols that didn't resolve bare.
+// 4. Persistent fallback "Unclassified".
+//
+// Negative hits (yfinance returns N/A or request fails) are cached with a
+// 7-day TTL so we don't hammer the script every launch for tickers that
+// genuinely don't have a sector (mutual funds, cash, obscure ETFs).
+//
+// The resolver is sync-for-cache-hits and async-for-misses. Consumers should
+// either:
+// - call sector_for() (returns empty for unknowns, triggers async fetch)
+// - subscribe to sector_resolved() to be notified when the fetch lands.
+
+#include <QHash>
+#include <QMutex>
+#include <QObject>
+#include <QSet>
+#include <QString>
+
+namespace fincept::services {
+
+class SectorResolver : public QObject {
+ Q_OBJECT
+
+ public:
+ static SectorResolver& instance();
+
+ // Synchronous lookup. Returns the cached sector or an empty string if
+ // unknown. When empty, triggers an async fetch (unless already in flight)
+ // — subscribe to sector_resolved() to get the result.
+ QString sector_for(const QString& symbol);
+
+ // Remember an authoritative sector (e.g. from portfolio import JSON).
+ // Overwrites any cached value and persists to disk.
+ void remember(const QString& symbol, const QString& sector);
+
+ // Kick off resolution for multiple symbols at once. Results fan out via
+ // sector_resolved() as they come back.
+ void prefetch(const QStringList& symbols);
+
+ signals:
+ void sector_resolved(QString symbol, QString sector);
+
+ private:
+ SectorResolver();
+ ~SectorResolver() override = default;
+ SectorResolver(const SectorResolver&) = delete;
+ SectorResolver& operator=(const SectorResolver&) = delete;
+
+ void load_cache();
+ void persist(const QString& symbol, const QString& sector, const QString& industry,
+ const QString& quote_type);
+ void resolve_async(const QString& symbol);
+ static QString normalize(const QString& symbol);
+ static QString fallback_for_unresolvable(const QString& symbol);
+
+ mutable QMutex mutex_;
+ QHash<QString, QString> cache_; // symbol → sector
+ QSet<QString> inflight_; // symbols currently being fetched
+};
+
+} // namespace fincept::services
diff --git a/fincept-qt/src/services/workspace/WorkspaceManager.cpp b/fincept-qt/src/services/workspace/WorkspaceManager.cpp
index 65a7a2be3..10409e734 100644
--- a/fincept-qt/src/services/workspace/WorkspaceManager.cpp
+++ b/fincept-qt/src/services/workspace/WorkspaceManager.cpp
@@ -3,6 +3,7 @@
#include "app/ScreenRouter.h"
#include "core/config/AppPaths.h"
#include "core/logging/Logger.h"
+#include "core/symbol/SymbolContext.h"
#include "screens/dashboard/canvas/GridLayout.h"
#include "services/workspace/WorkspaceSerializer.h"
#include "services/workspace/WorkspaceTemplates.h"
@@ -306,6 +307,10 @@ void WorkspaceManager::capture_from_ui() {
ss.state = it.value()->save_state();
current_workspace_->screen_states.append(ss);
}
+
+ // Symbol context (group→symbol assignments) is a singleton, captured once
+ // per workspace save. Empty object if the user hasn't touched any groups.
+ current_workspace_->symbol_context = SymbolContext::instance().to_json();
}
void WorkspaceManager::apply_to_ui() {
@@ -361,6 +366,10 @@ void WorkspaceManager::apply_to_ui() {
// Navigate to active screen — apply to primary router
if (!routers_.isEmpty() && !ws.active_screen.isEmpty())
routers_.first()->navigate(ws.active_screen);
+
+ // Restore symbol group context last so every subscriber has been
+ // constructed (or at least queued) before signals fan out.
+ SymbolContext::instance().from_json(ws.symbol_context);
}
void WorkspaceManager::ensure_workspaces_dir() const {
diff --git a/fincept-qt/src/services/workspace/WorkspaceSerializer.cpp b/fincept-qt/src/services/workspace/WorkspaceSerializer.cpp
index ad6d88a10..669baa264 100644
--- a/fincept-qt/src/services/workspace/WorkspaceSerializer.cpp
+++ b/fincept-qt/src/services/workspace/WorkspaceSerializer.cpp
@@ -82,6 +82,7 @@ QJsonDocument WorkspaceSerializer::to_json(const WorkspaceDef& ws) {
}
root["screen_states"] = QJsonValue(states);
root["window_geometry"] = ws.window_geometry_base64;
+ root["symbol_context"] = QJsonValue(ws.symbol_context);
return QJsonDocument(root);
}
@@ -160,6 +161,7 @@ Result<WorkspaceDef> WorkspaceSerializer::from_json(const QJsonDocument& doc) {
}
ws.window_geometry_base64 = root["window_geometry"].toString();
+ ws.symbol_context = root["symbol_context"].toObject();
return Result<WorkspaceDef>::ok(std::move(ws));
}
diff --git a/fincept-qt/src/services/workspace/WorkspaceTypes.h b/fincept-qt/src/services/workspace/WorkspaceTypes.h
index 8b986662f..86f4214e1 100644
--- a/fincept-qt/src/services/workspace/WorkspaceTypes.h
+++ b/fincept-qt/src/services/workspace/WorkspaceTypes.h
@@ -50,6 +50,11 @@ struct WorkspaceDef {
// Window geometry (base64 of QWidget::saveGeometry())
QString window_geometry_base64;
+
+ // SymbolContext snapshot — per-group active security assignments.
+ // Opaque blob authored by SymbolContext::to_json(), consumed by
+ // SymbolContext::from_json() on workspace load. Empty on first run.
+ QJsonObject symbol_context;
};
// ── Lightweight summary for listing dialogs ───────────────────────────────────
diff --git a/fincept-qt/src/storage/repositories/PortfolioRepository.cpp b/fincept-qt/src/storage/repositories/PortfolioRepository.cpp
index 50f17d08b..9c1b956eb 100644
--- a/fincept-qt/src/storage/repositories/PortfolioRepository.cpp
+++ b/fincept-qt/src/storage/repositories/PortfolioRepository.cpp
@@ -36,6 +36,7 @@ portfolio::PortfolioAsset PortfolioRepository::map_asset(QSqlQuery& q) {
q.value(4).toDouble(), // avg_buy_price
q.value(5).toString(), // first_purchase_date
q.value(6).toString(), // last_updated
+ q.value(7).toString(), // sector
};
}
@@ -107,18 +108,21 @@ Result<void> PortfolioRepository::delete_portfolio(const QString& id) {
Result<QVector<portfolio::PortfolioAsset>> PortfolioRepository::get_assets(const QString& portfolio_id) {
return query_list_as<portfolio::PortfolioAsset>(
- "SELECT id, portfolio_id, symbol, quantity, avg_buy_price, first_purchase_date, last_updated "
+ "SELECT id, portfolio_id, symbol, quantity, avg_buy_price, first_purchase_date, last_updated, "
+ "COALESCE(sector, '') "
"FROM portfolio_assets WHERE portfolio_id = ? ORDER BY symbol",
{portfolio_id}, map_asset);
}
Result<qint64> PortfolioRepository::add_asset(const QString& portfolio_id, const QString& symbol, double qty,
- double price, const QString& date) {
+ double price, const QString& date, const QString& sector) {
QString purchase_date = date.isEmpty() ? QDateTime::currentDateTimeUtc().toString(Qt::ISODate) : date;
- // Upsert: if symbol already exists in portfolio, update quantity and avg price
+ // Upsert: if symbol already exists in portfolio, update quantity and avg price.
+ // Preserve existing sector unless the caller provides a non-empty one.
auto existing = query_list_as<portfolio::PortfolioAsset>(
- "SELECT id, portfolio_id, symbol, quantity, avg_buy_price, first_purchase_date, last_updated "
+ "SELECT id, portfolio_id, symbol, quantity, avg_buy_price, first_purchase_date, last_updated, "
+ "COALESCE(sector, '') "
"FROM portfolio_assets WHERE portfolio_id = ? AND symbol = ?",
{portfolio_id, symbol.toUpper()}, map_asset);
@@ -126,18 +130,26 @@ Result<qint64> PortfolioRepository::add_asset(const QString& portfolio_id, const
auto& asset = existing.value().first();
double new_qty = asset.quantity + qty;
double new_avg = ((asset.avg_buy_price * asset.quantity) + (price * qty)) / new_qty;
- auto r = exec_write("UPDATE portfolio_assets SET quantity = ?, avg_buy_price = ?, "
+ QString merged_sector = sector.isEmpty() ? asset.sector : sector;
+ auto r = exec_write("UPDATE portfolio_assets SET quantity = ?, avg_buy_price = ?, sector = ?, "
"last_updated = datetime('now') WHERE id = ?",
- {new_qty, new_avg, asset.id});
+ {new_qty, new_avg, merged_sector, asset.id});
if (r.is_err())
return Result<qint64>::err(r.error());
return Result<qint64>::ok(static_cast<qint64>(asset.id));
}
return exec_insert(
- "INSERT INTO portfolio_assets (portfolio_id, symbol, quantity, avg_buy_price, first_purchase_date) "
- "VALUES (?, ?, ?, ?, ?)",
- {portfolio_id, symbol.toUpper(), qty, price, purchase_date});
+ "INSERT INTO portfolio_assets (portfolio_id, symbol, quantity, avg_buy_price, first_purchase_date, sector) "
+ "VALUES (?, ?, ?, ?, ?, ?)",
+ {portfolio_id, symbol.toUpper(), qty, price, purchase_date, sector});
+}
+
+Result<void> PortfolioRepository::set_asset_sector(const QString& portfolio_id, const QString& symbol,
+ const QString& sector) {
+ return exec_write("UPDATE portfolio_assets SET sector = ? "
+ "WHERE portfolio_id = ? AND symbol = ?",
+ {sector, portfolio_id, symbol.toUpper()});
}
Result<void> PortfolioRepository::update_asset(const QString& portfolio_id, const QString& symbol, double qty,
diff --git a/fincept-qt/src/storage/repositories/PortfolioRepository.h b/fincept-qt/src/storage/repositories/PortfolioRepository.h
index 49df97751..f73324f07 100644
--- a/fincept-qt/src/storage/repositories/PortfolioRepository.h
+++ b/fincept-qt/src/storage/repositories/PortfolioRepository.h
@@ -21,8 +21,9 @@ class PortfolioRepository : public BaseRepository<portfolio::Portfolio> {
// ── Assets CRUD ──────────────────────────────────────────────────────────
Result<QVector<portfolio::PortfolioAsset>> get_assets(const QString& portfolio_id);
Result<qint64> add_asset(const QString& portfolio_id, const QString& symbol, double qty, double price,
- const QString& date = {});
+ const QString& date = {}, const QString& sector = {});
Result<void> update_asset(const QString& portfolio_id, const QString& symbol, double qty, double avg_price);
+ Result<void> set_asset_sector(const QString& portfolio_id, const QString& symbol, const QString& sector);
Result<void> remove_asset(const QString& portfolio_id, const QString& symbol);
// ── Transactions ─────────────────────────────────────────────────────────
diff --git a/fincept-qt/src/storage/secure/SecureStorage.cpp b/fincept-qt/src/storage/secure/SecureStorage.cpp
index 5cfd0b571..5be87511b 100644
--- a/fincept-qt/src/storage/secure/SecureStorage.cpp
+++ b/fincept-qt/src/storage/secure/SecureStorage.cpp
@@ -34,6 +34,21 @@ namespace fincept {
SecureStorage& SecureStorage::instance() {
static SecureStorage s;
+
+#if !defined(Q_OS_WIN) && !defined(Q_OS_MAC)
+ // One-time honest warning on Linux: the backend here is XOR-obfuscated
+ // QSettings, not real encryption. Emit at first access so it always
+ // shows up in the startup log for operators, and only once per process.
+ static bool warned_once = false;
+ if (!warned_once) {
+ warned_once = true;
+ LOG_WARN("SecureStorage",
+ "Linux backend is XOR-obfuscated QSettings — NOT cryptographically "
+ "secure. Anyone with read access to the user profile can recover "
+ "stored secrets. libsecret/KWallet backend is planned.");
+ }
+#endif
+
return s;
}
diff --git a/fincept-qt/src/storage/secure/SecureStorage.h b/fincept-qt/src/storage/secure/SecureStorage.h
index 69a91f573..5cf6bb2c5 100644
--- a/fincept-qt/src/storage/secure/SecureStorage.h
+++ b/fincept-qt/src/storage/secure/SecureStorage.h
@@ -6,10 +6,21 @@
namespace fincept {
/// Secure credential storage using OS-native backends:
-/// Windows : Windows Credential Manager (DPAPI-encrypted)
-/// macOS : Security.framework Keychain
-/// Linux : XOR-obfuscated QSettings (NOT cryptographically secure —
-/// prevents casual inspection; libsecret backend planned)
+/// Windows : Windows Credential Manager (DPAPI-encrypted, per-user DPAPI key)
+/// macOS : Security.framework Keychain (per-user Keychain, OS-protected)
+/// Linux : **XOR-obfuscated QSettings — NOT cryptographically secure.**
+/// The obfuscation key is derived from machine-local identifiers
+/// and stored alongside the data, so anyone with read access to
+/// the user profile can recover every secret. This is a stopgap
+/// that only stops casual `grep`-through-config inspection. It is
+/// NOT safe against: another process running as the same user,
+/// a stolen/cloned profile directory, forensic tools, or backups.
+/// TODO: swap for a libsecret / KWallet / Secret Service backend
+/// via a conditional build-time dependency. Track in issue
+/// "Security: real Linux SecureStorage backend" (unfiled).
+/// The PIN-manager PBKDF2 path still protects the PIN itself even on Linux —
+/// but API keys, session tokens, and PIN-salt/hash stored here inherit only
+/// the XOR obfuscation on that platform.
class SecureStorage {
public:
static SecureStorage& instance();
diff --git a/fincept-qt/src/storage/sqlite/migrations/MigrationRunner.h b/fincept-qt/src/storage/sqlite/migrations/MigrationRunner.h
index fa0f5c343..1a152a0be 100644
--- a/fincept-qt/src/storage/sqlite/migrations/MigrationRunner.h
+++ b/fincept-qt/src/storage/sqlite/migrations/MigrationRunner.h
@@ -65,5 +65,7 @@ void register_migration_v015();
void register_migration_v016();
void register_migration_v017();
void register_migration_v018();
+void register_migration_v019();
+void register_migration_v020();
} // namespace fincept
diff --git a/fincept-qt/src/storage/sqlite/migrations/v019_sector_cache.cpp b/fincept-qt/src/storage/sqlite/migrations/v019_sector_cache.cpp
new file mode 100644
index 000000000..7ed3639fa
--- /dev/null
+++ b/fincept-qt/src/storage/sqlite/migrations/v019_sector_cache.cpp
@@ -0,0 +1,60 @@
+// v019_sector_cache — Adds sector column to portfolio_assets and creates the
+// sector_cache table used by SectorResolver to memoize yfinance sector lookups
+// across app launches.
+
+#include "storage/sqlite/migrations/MigrationRunner.h"
+
+#include <QSqlError>
+#include <QSqlQuery>
+
+namespace fincept {
+namespace {
+
+static Result<void> sql(QSqlDatabase& db, const char* stmt) {
+ QSqlQuery q(db);
+ if (!q.exec(stmt))
+ return Result<void>::err(q.lastError().text().toStdString());
+ return Result<void>::ok();
+}
+
+static bool column_exists(QSqlDatabase& db, const QString& table, const QString& column) {
+ QSqlQuery q(db);
+ q.exec(QString("PRAGMA table_info(%1)").arg(table));
+ while (q.next()) {
+ if (q.value(1).toString().compare(column, Qt::CaseInsensitive) == 0)
+ return true;
+ }
+ return false;
+}
+
+Result<void> apply_v019(QSqlDatabase& db) {
+ if (!column_exists(db, "portfolio_assets", "sector")) {
+ auto r = sql(db, "ALTER TABLE portfolio_assets ADD COLUMN sector TEXT DEFAULT ''");
+ if (r.is_err())
+ return r;
+ }
+
+ auto r = sql(db, "CREATE TABLE IF NOT EXISTS sector_cache ("
+ " symbol TEXT PRIMARY KEY,"
+ " sector TEXT NOT NULL DEFAULT '',"
+ " industry TEXT DEFAULT '',"
+ " quote_type TEXT DEFAULT '',"
+ " resolved_at INTEGER NOT NULL"
+ ")");
+ if (r.is_err())
+ return r;
+
+ return Result<void>::ok();
+}
+
+} // anonymous namespace
+
+void register_migration_v019() {
+ static bool done = false;
+ if (done)
+ return;
+ done = true;
+ MigrationRunner::register_migration({19, "sector_cache", apply_v019});
+}
+
+} // namespace fincept
diff --git a/fincept-qt/src/storage/sqlite/migrations/v020_security_audit_log.cpp b/fincept-qt/src/storage/sqlite/migrations/v020_security_audit_log.cpp
new file mode 100644
index 000000000..1de398ae8
--- /dev/null
+++ b/fincept-qt/src/storage/sqlite/migrations/v020_security_audit_log.cpp
@@ -0,0 +1,52 @@
+// v020_security_audit_log — Persistent audit trail for PIN / lock-screen
+// security events. Used by SecurityAuditService to record PIN setup, change,
+// failed unlock attempts, lockout transitions, inactivity locks, and
+// resume-from-sleep locks. Read back by Settings → Security → Audit log.
+
+#include "storage/sqlite/migrations/MigrationRunner.h"
+
+#include <QSqlError>
+#include <QSqlQuery>
+
+namespace fincept {
+namespace {
+
+static Result<void> sql(QSqlDatabase& db, const char* stmt) {
+ QSqlQuery q(db);
+ if (!q.exec(stmt))
+ return Result<void>::err(q.lastError().text().toStdString());
+ return Result<void>::ok();
+}
+
+Result<void> apply_v020(QSqlDatabase& db) {
+ // `event` is a short stable identifier (e.g. "pin_set", "pin_verify_fail").
+ // `detail` holds free-form context (attempt number, lockout seconds, etc.).
+ // `ts` is Unix epoch seconds — indexed for recent-events queries.
+ auto r = sql(db, "CREATE TABLE IF NOT EXISTS security_audit_log ("
+ " id INTEGER PRIMARY KEY AUTOINCREMENT,"
+ " ts INTEGER NOT NULL,"
+ " event TEXT NOT NULL,"
+ " detail TEXT DEFAULT ''"
+ ")");
+ if (r.is_err())
+ return r;
+
+ r = sql(db, "CREATE INDEX IF NOT EXISTS idx_security_audit_ts "
+ "ON security_audit_log(ts DESC)");
+ if (r.is_err())
+ return r;
+
+ return Result<void>::ok();
+}
+
+} // anonymous namespace
+
+void register_migration_v020() {
+ static bool done = false;
+ if (done)
+ return;
+ done = true;
+ MigrationRunner::register_migration({20, "security_audit_log", apply_v020});
+}
+
+} // namespace fincept
diff --git a/fincept-qt/src/ui/components/ComponentBrowserDialog.cpp b/fincept-qt/src/ui/components/ComponentBrowserDialog.cpp
new file mode 100644
index 000000000..8183581ed
--- /dev/null
+++ b/fincept-qt/src/ui/components/ComponentBrowserDialog.cpp
@@ -0,0 +1,176 @@
+#include "ui/components/ComponentBrowserDialog.h"
+
+#include "core/components/ComponentCatalog.h"
+#include "core/components/PopularityTracker.h"
+#include "ui/components/ComponentCard.h"
+
+#include <QGridLayout>
+#include <QHBoxLayout>
+#include <QKeyEvent>
+#include <QLabel>
+#include <QLineEdit>
+#include <QListWidget>
+#include <QScrollArea>
+#include <QVBoxLayout>
+
+namespace fincept::ui {
+
+namespace {
+
+constexpr int kCardsPerRow = 3;
+
+bool matches_query(const ComponentMeta& m, const QString& query) {
+ if (query.isEmpty())
+ return true;
+ const QString q = query.toLower();
+ if (m.title.toLower().contains(q)) return true;
+ if (m.description.toLower().contains(q)) return true;
+ if (m.id.toLower().contains(q)) return true;
+ for (const QString& tag : m.tags) {
+ if (tag.toLower().contains(q)) return true;
+ }
+ return false;
+}
+
+} // namespace
+
+ComponentBrowserDialog::ComponentBrowserDialog(QWidget* parent) : QDialog(parent) {
+ setWindowTitle("Component Browser");
+ setModal(true);
+ resize(960, 640);
+ setStyleSheet("QDialog{background:#0f172a;} QLabel{color:#e5e7eb;}");
+ build_ui();
+ rebuild_cards();
+}
+
+void ComponentBrowserDialog::build_ui() {
+ auto* root = new QVBoxLayout(this);
+ root->setContentsMargins(0, 0, 0, 0);
+ root->setSpacing(0);
+
+ // Header bar — title + search.
+ auto* header = new QWidget(this);
+ header->setFixedHeight(56);
+ header->setStyleSheet("background:#111827;border-bottom:1px solid #374151;");
+ auto* hl = new QHBoxLayout(header);
+ hl->setContentsMargins(16, 8, 16, 8);
+ hl->setSpacing(12);
+
+ auto* title = new QLabel("COMPONENT BROWSER", header);
+ title->setStyleSheet("color:#d97706;font-size:13px;font-weight:700;letter-spacing:2px;");
+ hl->addWidget(title);
+
+ hl->addSpacing(24);
+
+ search_ = new QLineEdit(header);
+ search_->setPlaceholderText("Search components…");
+ search_->setClearButtonEnabled(true);
+ search_->setStyleSheet(
+ "QLineEdit{background:#0b1220;border:1px solid #374151;border-radius:3px;"
+ "color:#f3f4f6;padding:6px 10px;min-width:280px;}"
+ "QLineEdit:focus{border-color:#d97706;}");
+ connect(search_, &QLineEdit::textChanged, this, &ComponentBrowserDialog::on_search_changed);
+ hl->addWidget(search_);
+
+ hl->addStretch(1);
+
+ count_label_ = new QLabel(header);
+ count_label_->setStyleSheet("color:#9ca3af;font-size:11px;");
+ hl->addWidget(count_label_);
+
+ root->addWidget(header);
+
+ // Split: sidebar (categories) + grid.
+ auto* split = new QWidget(this);
+ auto* sl = new QHBoxLayout(split);
+ sl->setContentsMargins(0, 0, 0, 0);
+ sl->setSpacing(0);
+
+ category_list_ = new QListWidget(split);
+ category_list_->setFixedWidth(180);
+ category_list_->setStyleSheet(
+ "QListWidget{background:#0b1220;border:none;border-right:1px solid #374151;color:#e5e7eb;}"
+ "QListWidget::item{padding:8px 14px;border:none;}"
+ "QListWidget::item:selected{background:#1f2937;color:#d97706;border-left:3px solid #d97706;}"
+ "QListWidget::item:hover{background:#111827;}");
+ category_list_->addItem("All");
+ for (const QString& c : ComponentCatalog::instance().categories())
+ category_list_->addItem(c);
+ category_list_->setCurrentRow(0);
+ connect(category_list_, &QListWidget::currentRowChanged, this,
+ &ComponentBrowserDialog::on_category_changed);
+ sl->addWidget(category_list_);
+
+ scroll_ = new QScrollArea(split);
+ scroll_->setWidgetResizable(true);
+ scroll_->setFrameShape(QFrame::NoFrame);
+ scroll_->setStyleSheet("background:#0f172a;");
+ grid_host_ = new QWidget;
+ grid_host_->setStyleSheet("background:transparent;");
+ grid_layout_ = new QGridLayout(grid_host_);
+ grid_layout_->setContentsMargins(16, 16, 16, 16);
+ grid_layout_->setSpacing(12);
+ scroll_->setWidget(grid_host_);
+ sl->addWidget(scroll_, 1);
+
+ root->addWidget(split, 1);
+}
+
+void ComponentBrowserDialog::rebuild_cards() {
+ // Tear down existing cards.
+ while (grid_layout_->count() > 0) {
+ QLayoutItem* it = grid_layout_->takeAt(0);
+ if (it->widget())
+ it->widget()->deleteLater();
+ delete it;
+ }
+
+ const auto all = ComponentCatalog::instance().list_for_ui();
+ int row = 0, col = 0;
+ int shown = 0;
+ for (const ComponentMeta& m : all) {
+ if (active_category_ != "All" && m.category != active_category_)
+ continue;
+ if (!matches_query(m, search_query_))
+ continue;
+
+ auto* card = new ComponentCard(m, grid_host_);
+ connect(card, &ComponentCard::activated, this, [this](const QString& id) {
+ emit component_chosen(id);
+ accept();
+ });
+ connect(card, &ComponentCard::selected_changed, this, [this](const QString& id) {
+ selected_id_ = id;
+ });
+ grid_layout_->addWidget(card, row, col);
+ if (++col >= kCardsPerRow) {
+ col = 0;
+ ++row;
+ }
+ ++shown;
+ }
+
+ // Pad the last row so cards don't stretch to fill when there's an
+ // awkward remainder (e.g. 7 cards on a 3-wide grid).
+ if (col != 0) {
+ for (int c = col; c < kCardsPerRow; ++c)
+ grid_layout_->addWidget(new QWidget(grid_host_), row, c);
+ }
+ grid_layout_->setRowStretch(row + 1, 1);
+
+ count_label_->setText(QString("%1 component%2").arg(shown).arg(shown == 1 ? "" : "s"));
+}
+
+void ComponentBrowserDialog::on_search_changed(const QString& query) {
+ search_query_ = query.trimmed();
+ rebuild_cards();
+}
+
+void ComponentBrowserDialog::on_category_changed(int row) {
+ if (row < 0)
+ return;
+ active_category_ = category_list_->item(row)->text();
+ rebuild_cards();
+}
+
+} // namespace fincept::ui
diff --git a/fincept-qt/src/ui/components/ComponentBrowserDialog.h b/fincept-qt/src/ui/components/ComponentBrowserDialog.h
new file mode 100644
index 000000000..fea47d482
--- /dev/null
+++ b/fincept-qt/src/ui/components/ComponentBrowserDialog.h
@@ -0,0 +1,57 @@
+#pragma once
+#include <QDialog>
+#include <QString>
+
+class QLineEdit;
+class QListWidget;
+class QScrollArea;
+class QGridLayout;
+class QLabel;
+
+namespace fincept::ui {
+
+class ComponentCard;
+
+/// Modal dialog letting users browse every registered screen (component)
+/// and launch one into the active workspace. Bloomberg Launchpad
+/// Component Browser equivalent.
+///
+/// Layout:
+/// Left — category sidebar ("All" at top, then distinct categories in
+/// catalogue order)
+/// Top — search box (matches against title + tags, case-insensitive)
+/// Main — grid of ComponentCards, sorted by popularity desc
+///
+/// Keyboard: Esc closes, Enter activates the current selection, arrow keys
+/// navigate between cards when the list-view equivalent focus is wired up
+/// (grid cards don't natively support keyboard focus yet — future polish).
+class ComponentBrowserDialog : public QDialog {
+ Q_OBJECT
+ public:
+ explicit ComponentBrowserDialog(QWidget* parent = nullptr);
+
+ signals:
+ /// Emitted when the user double-clicks a card or presses Enter.
+ /// The caller (MainWindow) is expected to navigate to the screen.
+ /// The dialog closes itself after emitting.
+ void component_chosen(const QString& screen_id);
+
+ private:
+ void build_ui();
+ void rebuild_cards();
+ void on_search_changed(const QString& query);
+ void on_category_changed(int row);
+
+ QLineEdit* search_ = nullptr;
+ QListWidget* category_list_ = nullptr;
+ QScrollArea* scroll_ = nullptr;
+ QWidget* grid_host_ = nullptr;
+ QGridLayout* grid_layout_ = nullptr;
+ QLabel* count_label_ = nullptr;
+
+ QString active_category_ = "All";
+ QString search_query_;
+ QString selected_id_;
+};
+
+} // namespace fincept::ui
diff --git a/fincept-qt/src/ui/components/ComponentCard.cpp b/fincept-qt/src/ui/components/ComponentCard.cpp
new file mode 100644
index 000000000..2cda7fb7e
--- /dev/null
+++ b/fincept-qt/src/ui/components/ComponentCard.cpp
@@ -0,0 +1,183 @@
+#include "ui/components/ComponentCard.h"
+
+#include <QApplication>
+#include <QDrag>
+#include <QFontMetrics>
+#include <QHBoxLayout>
+#include <QLabel>
+#include <QMimeData>
+#include <QVBoxLayout>
+
+namespace fincept::ui {
+
+namespace {
+
+// Shared MIME type for dragging a screen id out of the browser. Kept as a
+// constexpr free name so a future drop-on-dock-area handler can include
+// this header and share the string.
+constexpr const char* kScreenIdMime = "application/x-fincept-screen-id";
+
+// Per-category accent colour. Keeps the browser visually parseable at a
+// glance — the same Bloomberg trick of colour-coding asset classes in the
+// Function Menu.
+QString category_color(const QString& category) {
+ if (category == "Core") return "#d97706"; // amber
+ if (category == "Trading") return "#16a34a"; // green
+ if (category == "Research") return "#0891b2"; // cyan
+ if (category == "QuantLib") return "#7c3aed"; // purple
+ if (category == "AI") return "#c026d3"; // magenta
+ if (category == "Economics") return "#2563eb"; // blue
+ if (category == "Geopolitics") return "#dc2626"; // red
+ if (category == "Tools") return "#64748b"; // slate
+ if (category == "Community") return "#059669"; // emerald
+ return "#4b5563";
+}
+
+QString popularity_stars(int count) {
+ // Cap at 5 stars; thresholds are logarithmic-ish so low-use components
+ // still earn one filled star after a couple of visits, and popular ones
+ // eventually max out.
+ int filled = 0;
+ if (count >= 1) filled = 1;
+ if (count >= 5) filled = 2;
+ if (count >= 20) filled = 3;
+ if (count >= 50) filled = 4;
+ if (count >= 150) filled = 5;
+
+ QString out;
+ for (int i = 0; i < 5; ++i)
+ out += (i < filled) ? QChar(0x2605) : QChar(0x2606); // ★ / ☆
+ return out;
+}
+
+} // namespace
+
+ComponentCard::ComponentCard(ComponentMeta meta, QWidget* parent)
+ : QFrame(parent), meta_(std::move(meta)) {
+ setFixedSize(260, 120);
+ setCursor(Qt::PointingHandCursor);
+ setObjectName("componentCard");
+ setAttribute(Qt::WA_Hover, true);
+ build_ui();
+ restyle();
+}
+
+void ComponentCard::build_ui() {
+ auto* root = new QVBoxLayout(this);
+ root->setContentsMargins(0, 0, 0, 0);
+ root->setSpacing(0);
+
+ // Category strip across the top.
+ auto* strip = new QWidget(this);
+ strip->setFixedHeight(6);
+ strip->setStyleSheet(QString("background:%1;").arg(category_color(meta_.category)));
+ root->addWidget(strip);
+
+ auto* body = new QWidget(this);
+ auto* bl = new QVBoxLayout(body);
+ bl->setContentsMargins(12, 8, 12, 8);
+ bl->setSpacing(4);
+
+ auto* cat_row = new QHBoxLayout;
+ cat_row->setContentsMargins(0, 0, 0, 0);
+ cat_row->setSpacing(0);
+ auto* cat = new QLabel(meta_.category.toUpper(), body);
+ cat->setStyleSheet(QString("color:%1;font-size:10px;letter-spacing:1.5px;font-weight:700;")
+ .arg(category_color(meta_.category)));
+ cat_row->addWidget(cat);
+ cat_row->addStretch(1);
+ auto* stars = new QLabel(popularity_stars(meta_.popularity), body);
+ stars->setStyleSheet("color:#d97706;font-size:12px;");
+ stars->setToolTip(QString("Use count: %1").arg(meta_.popularity));
+ cat_row->addWidget(stars);
+ bl->addLayout(cat_row);
+
+ auto* title = new QLabel(meta_.title, body);
+ title->setStyleSheet("color:#f3f4f6;font-size:14px;font-weight:700;");
+ bl->addWidget(title);
+
+ auto* desc = new QLabel(body);
+ desc->setWordWrap(true);
+ desc->setStyleSheet("color:#9ca3af;font-size:11px;");
+ const QString text = meta_.description.isEmpty() ? QStringLiteral(" ") : meta_.description;
+ desc->setText(text);
+ desc->setMaximumHeight(36); // clamps to ~2 lines
+ bl->addWidget(desc);
+ bl->addStretch(1);
+
+ root->addWidget(body, 1);
+}
+
+void ComponentCard::restyle() {
+ QString border = "#374151";
+ QString bg = "#111827";
+ if (selected_) {
+ border = "#d97706";
+ bg = "#1f2937";
+ } else if (hovered_) {
+ border = "#6b7280";
+ bg = "#1a2332";
+ }
+ setStyleSheet(QString("#componentCard{background:%1;border:1px solid %2;border-radius:4px;}")
+ .arg(bg, border));
+}
+
+void ComponentCard::set_selected(bool s) {
+ if (selected_ == s)
+ return;
+ selected_ = s;
+ restyle();
+}
+
+void ComponentCard::mousePressEvent(QMouseEvent* e) {
+ if (e->button() == Qt::LeftButton) {
+ press_pos_ = e->pos();
+ pressed_ = true;
+ set_selected(true);
+ emit selected_changed(meta_.id);
+ e->accept();
+ return;
+ }
+ QFrame::mousePressEvent(e);
+}
+
+void ComponentCard::mouseMoveEvent(QMouseEvent* e) {
+ if (!pressed_ || !(e->buttons() & Qt::LeftButton))
+ return;
+ if ((e->pos() - press_pos_).manhattanLength() < QApplication::startDragDistance())
+ return;
+ pressed_ = false;
+
+ // Drag-out: the MIME payload is just the screen id, no extra
+ // serialisation. A future drop handler on the dock manager can call
+ // DockScreenRouter::navigate with it.
+ auto* drag = new QDrag(this);
+ auto* mime = new QMimeData;
+ mime->setData(kScreenIdMime, meta_.id.toUtf8());
+ mime->setText(meta_.title); // fallback for generic text drop targets
+ drag->setMimeData(mime);
+ drag->exec(Qt::CopyAction, Qt::CopyAction);
+}
+
+void ComponentCard::mouseDoubleClickEvent(QMouseEvent* e) {
+ if (e->button() == Qt::LeftButton) {
+ emit activated(meta_.id);
+ e->accept();
+ return;
+ }
+ QFrame::mouseDoubleClickEvent(e);
+}
+
+void ComponentCard::enterEvent(QEnterEvent* e) {
+ hovered_ = true;
+ restyle();
+ QFrame::enterEvent(e);
+}
+
+void ComponentCard::leaveEvent(QEvent* e) {
+ hovered_ = false;
+ restyle();
+ QFrame::leaveEvent(e);
+}
+
+} // namespace fincept::ui
diff --git a/fincept-qt/src/ui/components/ComponentCard.h b/fincept-qt/src/ui/components/ComponentCard.h
new file mode 100644
index 000000000..ceb3351ad
--- /dev/null
+++ b/fincept-qt/src/ui/components/ComponentCard.h
@@ -0,0 +1,52 @@
+#pragma once
+#include "core/components/ComponentMeta.h"
+
+#include <QFrame>
+#include <QMouseEvent>
+
+class QLabel;
+
+namespace fincept::ui {
+
+/// One tile in the Component Browser grid. Shows category strip, title,
+/// description, and popularity stars (filled circles rendered via text
+/// — no icon assets required). Emits signals on click / double-click, and
+/// supports drag-out with MIME type application/x-fincept-screen-id so a
+/// future "drop a card onto a dock area to open it there" flow can plug
+/// in without reworking the card.
+///
+/// Sized for a 3-across grid at ~900px browser width. Keeps the card
+/// compact so 30+ components can fit without scrolling on a 1080p display.
+class ComponentCard : public QFrame {
+ Q_OBJECT
+ public:
+ explicit ComponentCard(ComponentMeta meta, QWidget* parent = nullptr);
+
+ const ComponentMeta& meta() const { return meta_; }
+ bool is_selected() const { return selected_; }
+ void set_selected(bool s);
+
+ signals:
+ void activated(const QString& id); // double-click or Enter
+ void selected_changed(const QString& id); // single click
+
+ protected:
+ void mousePressEvent(QMouseEvent* e) override;
+ void mouseMoveEvent(QMouseEvent* e) override;
+ void mouseDoubleClickEvent(QMouseEvent* e) override;
+ void enterEvent(QEnterEvent* e) override;
+ void leaveEvent(QEvent* e) override;
+
+ private:
+ void build_ui();
+ void restyle();
+
+ ComponentMeta meta_;
+ bool selected_ = false;
+ bool hovered_ = false;
+
+ QPoint press_pos_;
+ bool pressed_ = false;
+};
+
+} // namespace fincept::ui
diff --git a/fincept-qt/src/ui/navigation/ToolBar.cpp b/fincept-qt/src/ui/navigation/ToolBar.cpp
index ee0fc64ff..6c573a57c 100644
--- a/fincept-qt/src/ui/navigation/ToolBar.cpp
+++ b/fincept-qt/src/ui/navigation/ToolBar.cpp
@@ -386,10 +386,20 @@ QMenu* ToolBar::build_navigate_menu() {
QMenu* ToolBar::build_view_menu() {
auto* m = new QMenu("View", this);
m->setStyleSheet(popup_ss());
+ // Component Browser at the top — Bloomberg's discoverability hook.
+ m->addAction("Component Browser\tCtrl+K", this,
+ [this]() { emit action_triggered("browse_components"); });
+ m->addSeparator();
m->addAction("Fullscreen\tF11", this, [this]() { emit action_triggered("fullscreen"); });
m->addSeparator();
m->addAction("Focus Mode\tF10", this, [this]() { emit action_triggered("focus_mode"); });
- m->addAction("Always on Top", this, [this]() { emit action_triggered("always_on_top"); });
+ // Phase 11: the shortcut is Ctrl+Shift+T; we don't mark the QAction as
+ // checkable because its state is owned by MainWindow::always_on_top_ —
+ // a checkable toolbar action would drift out of sync on window focus
+ // changes. If the user cares about the visual, the window's title bar
+ // retains the OS-level "always on top" decoration on most platforms.
+ m->addAction("Always on Top\tCtrl+Shift+T", this,
+ [this]() { emit action_triggered("always_on_top"); });
m->addSeparator();
// Float any screen as a separate window on another monitor
diff --git a/fincept-qt/src/ui/pushpins/PushpinBar.cpp b/fincept-qt/src/ui/pushpins/PushpinBar.cpp
new file mode 100644
index 000000000..d6a96cf3e
--- /dev/null
+++ b/fincept-qt/src/ui/pushpins/PushpinBar.cpp
@@ -0,0 +1,77 @@
+#include "ui/pushpins/PushpinBar.h"
+
+#include "core/symbol/SymbolDragSource.h"
+#include "services/pushpins/PushpinService.h"
+#include "ui/pushpins/SymbolChip.h"
+
+#include <QHBoxLayout>
+#include <QLabel>
+#include <QScrollArea>
+
+namespace fincept::ui {
+
+PushpinBar::PushpinBar(QWidget* parent) : QWidget(parent) {
+ setObjectName("pushpinBar");
+ setFixedHeight(30);
+ setStyleSheet("#pushpinBar{background:#111827;border-bottom:1px solid #374151;}");
+
+ auto* outer = new QHBoxLayout(this);
+ outer->setContentsMargins(6, 2, 6, 2);
+ outer->setSpacing(0);
+
+ scroll_ = new QScrollArea(this);
+ scroll_->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
+ scroll_->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
+ scroll_->setFrameShape(QFrame::NoFrame);
+ scroll_->setWidgetResizable(true);
+ scroll_->setStyleSheet("QScrollArea{background:transparent;}"
+ "QScrollBar:horizontal{height:6px;}");
+ outer->addWidget(scroll_, 1);
+
+ strip_ = new QWidget;
+ strip_->setObjectName("pushpinStrip");
+ strip_->setStyleSheet("#pushpinStrip{background:transparent;}");
+ strip_layout_ = new QHBoxLayout(strip_);
+ strip_layout_->setContentsMargins(0, 0, 0, 0);
+ strip_layout_->setSpacing(4);
+ strip_layout_->addStretch(1);
+ scroll_->setWidget(strip_);
+
+ empty_hint_ = new QLabel("Drag any symbol here to pin", strip_);
+ empty_hint_->setStyleSheet("color:#6b7280;font-size:11px;font-style:italic;");
+
+ // Dropping a symbol anywhere on the bar pins it.
+ symbol_dnd::installDropFilter(this, [](const SymbolRef& ref, SymbolGroup) {
+ PushpinService::instance().pin(ref);
+ });
+
+ connect(&PushpinService::instance(), &PushpinService::pins_changed, this, &PushpinBar::rebuild);
+ rebuild();
+}
+
+void PushpinBar::rebuild() {
+ // Tear down existing chip widgets (keep the trailing stretch + hint).
+ QLayoutItem* item;
+ while ((item = strip_layout_->takeAt(0)) != nullptr) {
+ if (auto* w = item->widget()) {
+ if (w != empty_hint_)
+ w->deleteLater();
+ }
+ delete item;
+ }
+
+ const auto pins = PushpinService::instance().pins();
+ if (pins.isEmpty()) {
+ strip_layout_->addWidget(empty_hint_);
+ empty_hint_->show();
+ } else {
+ empty_hint_->hide();
+ for (const SymbolRef& p : pins) {
+ auto* chip = new SymbolChip(p, strip_);
+ strip_layout_->addWidget(chip);
+ }
+ }
+ strip_layout_->addStretch(1);
+}
+
+} // namespace fincept::ui
diff --git a/fincept-qt/src/ui/pushpins/PushpinBar.h b/fincept-qt/src/ui/pushpins/PushpinBar.h
new file mode 100644
index 000000000..f526df2c1
--- /dev/null
+++ b/fincept-qt/src/ui/pushpins/PushpinBar.h
@@ -0,0 +1,33 @@
+#pragma once
+#include <QWidget>
+
+class QHBoxLayout;
+class QLabel;
+class QScrollArea;
+
+namespace fincept::ui {
+
+class SymbolChip;
+
+/// Thin horizontal strip of symbol chips shown at the top of every
+/// MainWindow. Rebuilt from PushpinService on every pins_changed signal.
+/// Accepts drops of symbol MIME data (drag a symbol from any panel onto
+/// the bar to pin it).
+///
+/// Empty state shows a muted hint label ("Drag any symbol here to pin")
+/// so first-time users discover the feature without a tutorial.
+class PushpinBar : public QWidget {
+ Q_OBJECT
+ public:
+ explicit PushpinBar(QWidget* parent = nullptr);
+
+ private:
+ void rebuild();
+
+ QScrollArea* scroll_ = nullptr;
+ QWidget* strip_ = nullptr;
+ QHBoxLayout* strip_layout_ = nullptr;
+ QLabel* empty_hint_ = nullptr;
+};
+
+} // namespace fincept::ui
diff --git a/fincept-qt/src/ui/pushpins/SymbolChip.cpp b/fincept-qt/src/ui/pushpins/SymbolChip.cpp
new file mode 100644
index 000000000..7baca7e52
--- /dev/null
+++ b/fincept-qt/src/ui/pushpins/SymbolChip.cpp
@@ -0,0 +1,104 @@
+#include "ui/pushpins/SymbolChip.h"
+
+#include "core/symbol/SymbolContext.h"
+#include "core/symbol/SymbolDragSource.h"
+#include "services/pushpins/PushpinService.h"
+
+#include <QAction>
+#include <QApplication>
+#include <QClipboard>
+#include <QContextMenuEvent>
+#include <QFontMetrics>
+#include <QMenu>
+#include <QPainter>
+#include <QPainterPath>
+
+namespace fincept::ui {
+
+SymbolChip::SymbolChip(SymbolRef ref, QWidget* parent) : QWidget(parent), ref_(std::move(ref)) {
+ setCursor(Qt::PointingHandCursor);
+ setToolTip(ref_.display() + "\nLeft-click: broadcast to Group A\nDrag: send to any panel\nRight-click: menu");
+ setAttribute(Qt::WA_Hover);
+}
+
+QSize SymbolChip::sizeHint() const {
+ QFontMetrics fm(font());
+ return QSize(fm.horizontalAdvance(ref_.symbol) + 18, fm.height() + 8);
+}
+
+void SymbolChip::mousePressEvent(QMouseEvent* e) {
+ if (e->button() == Qt::LeftButton) {
+ press_pos_ = e->pos();
+ pressed_ = true;
+ e->accept();
+ return;
+ }
+ QWidget::mousePressEvent(e);
+}
+
+void SymbolChip::mouseMoveEvent(QMouseEvent* e) {
+ if (!pressed_ || !(e->buttons() & Qt::LeftButton))
+ return;
+ if ((e->pos() - press_pos_).manhattanLength() < QApplication::startDragDistance())
+ return;
+ // Threshold crossed — hand off to the drag machinery. Clear pressed_
+ // so the subsequent mouseReleaseEvent doesn't also fire the click.
+ pressed_ = false;
+ symbol_dnd::startSymbolDrag(this, ref_);
+}
+
+void SymbolChip::mouseReleaseEvent(QMouseEvent* e) {
+ const bool was_click = pressed_ && e->button() == Qt::LeftButton;
+ pressed_ = false;
+ if (was_click)
+ broadcast_to_group(SymbolGroup::A);
+ QWidget::mouseReleaseEvent(e);
+}
+
+void SymbolChip::contextMenuEvent(QContextMenuEvent* e) {
+ QMenu menu(this);
+
+ auto* copy = menu.addAction("Copy Ticker");
+ connect(copy, &QAction::triggered, this, [this]() {
+ QApplication::clipboard()->setText(ref_.symbol);
+ });
+
+ auto* remove = menu.addAction("Remove Pin");
+ connect(remove, &QAction::triggered, this, [this]() {
+ emit remove_requested(ref_);
+ PushpinService::instance().unpin(ref_);
+ });
+
+ menu.addSeparator();
+ for (SymbolGroup g : all_symbol_groups()) {
+ auto* act = menu.addAction(QString("Broadcast to Group %1").arg(symbol_group_letter(g)));
+ connect(act, &QAction::triggered, this, [this, g]() { broadcast_to_group(g); });
+ }
+ menu.exec(e->globalPos());
+}
+
+void SymbolChip::paintEvent(QPaintEvent*) {
+ QPainter p(this);
+ p.setRenderHint(QPainter::Antialiasing, true);
+ const QRectF r = QRectF(rect()).adjusted(0.5, 0.5, -0.5, -0.5);
+
+ QPainterPath path;
+ path.addRoundedRect(r, r.height() / 2.0, r.height() / 2.0);
+ p.fillPath(path, QColor("#1f2937")); // slate-800
+ p.setPen(QColor("#d97706")); // amber border — echoes Bloomberg's amber
+ p.drawPath(path);
+
+ p.setPen(QColor("#f3f4f6"));
+ QFont f = p.font();
+ f.setBold(true);
+ p.setFont(f);
+ p.drawText(r, Qt::AlignCenter, ref_.symbol);
+}
+
+void SymbolChip::broadcast_to_group(SymbolGroup g) {
+ if (g == SymbolGroup::None)
+ return;
+ SymbolContext::instance().set_group_symbol(g, ref_, this);
+}
+
+} // namespace fincept::ui
diff --git a/fincept-qt/src/ui/pushpins/SymbolChip.h b/fincept-qt/src/ui/pushpins/SymbolChip.h
new file mode 100644
index 000000000..8082aa64c
--- /dev/null
+++ b/fincept-qt/src/ui/pushpins/SymbolChip.h
@@ -0,0 +1,47 @@
+#pragma once
+#include "core/symbol/SymbolGroup.h"
+#include "core/symbol/SymbolRef.h"
+
+#include <QMouseEvent>
+#include <QWidget>
+
+namespace fincept::ui {
+
+/// Single-symbol chip rendered in the PushpinBar. Interactions:
+/// - Left-click: publish to the current "default broadcast group"
+/// (Group A if no group is selected; configurable via user setting
+/// "pushpins/default_group" in future). Also sets `active_group`
+/// on the SymbolContext implicitly by reusing that group.
+/// - Drag out: starts a symbol drag so the user can drop onto any panel.
+/// - Right-click: menu with Remove, Broadcast to Group A/B/…, Copy ticker.
+///
+/// The chip is intentionally a plain QWidget (not QPushButton) so we can
+/// freely paint the amber pill style and handle mouseMove for drag
+/// initiation without QPushButton's internal state machine interfering.
+class SymbolChip : public QWidget {
+ Q_OBJECT
+ public:
+ explicit SymbolChip(SymbolRef ref, QWidget* parent = nullptr);
+
+ const SymbolRef& ref() const { return ref_; }
+
+ signals:
+ void remove_requested(fincept::SymbolRef ref);
+
+ protected:
+ void mousePressEvent(QMouseEvent* e) override;
+ void mouseMoveEvent(QMouseEvent* e) override;
+ void mouseReleaseEvent(QMouseEvent* e) override;
+ void contextMenuEvent(QContextMenuEvent* e) override;
+ void paintEvent(QPaintEvent* e) override;
+ QSize sizeHint() const override;
+
+ private:
+ void broadcast_to_group(SymbolGroup g);
+
+ SymbolRef ref_;
+ QPoint press_pos_;
+ bool pressed_ = false;
+};
+
+} // namespace fincept::ui
diff --git a/fincept-qt/src/ui/theme/ThemeManager.cpp b/fincept-qt/src/ui/theme/ThemeManager.cpp
index c89363613..9e356fefc 100644
--- a/fincept-qt/src/ui/theme/ThemeManager.cpp
+++ b/fincept-qt/src/ui/theme/ThemeManager.cpp
@@ -544,6 +544,15 @@ QString ThemeManager::build_ads_qss() const {
ads--CTitleBarButton:hover { background: %8; }
ads--CAutoHideSideBar { background: %1; border: none; }
QScrollArea#dockWidgetScrollArea { padding: 0px; border: none; }
+
+ /* Phase 14 — auto-dock polish. Echoes Bloomberg Launchpad's amber
+ yellow snap-line when two components touch. ADS paints the drop
+ preview (COverlayDropArea / COverlayCrossWidget) and the splitter
+ handle hover — both styled with the accent colour so the visual
+ intent across drag + resize is consistent. */
+ ads--CDockOverlay { background: transparent; }
+ ads--CDockOverlayCross { background: transparent; }
+ ads--CDockSplitter::handle:hover { background-color: %4; }
)")
.arg(t.bg_base) // %1
.arg(t.bg_raised) // %2
diff --git a/fincept-qt/src/ui/widgets/GroupBadge.cpp b/fincept-qt/src/ui/widgets/GroupBadge.cpp
new file mode 100644
index 000000000..df7776795
--- /dev/null
+++ b/fincept-qt/src/ui/widgets/GroupBadge.cpp
@@ -0,0 +1,91 @@
+#include "ui/widgets/GroupBadge.h"
+
+#include <QAction>
+#include <QContextMenuEvent>
+#include <QMenu>
+#include <QMouseEvent>
+#include <QPainter>
+#include <QPainterPath>
+
+namespace fincept::ui {
+
+GroupBadge::GroupBadge(QWidget* parent) : QWidget(parent) {
+ setCursor(Qt::PointingHandCursor);
+ setToolTip("Symbol link group — click to cycle, right-click for menu");
+ setAttribute(Qt::WA_Hover);
+}
+
+QColor GroupBadge::color_for_group(SymbolGroup g) {
+ // Bloomberg-ish six-colour palette, tuned to remain readable on both
+ // dark and light themes.
+ switch (g) {
+ case SymbolGroup::A: return QColor("#d97706"); // amber
+ case SymbolGroup::B: return QColor("#0891b2"); // cyan
+ case SymbolGroup::C: return QColor("#c026d3"); // magenta
+ case SymbolGroup::D: return QColor("#16a34a"); // green
+ case SymbolGroup::E: return QColor("#7c3aed"); // purple
+ case SymbolGroup::F: return QColor("#dc2626"); // red
+ case SymbolGroup::None: return QColor("#4b5563"); // slate (unlinked)
+ }
+ return QColor("#4b5563");
+}
+
+void GroupBadge::set_group_silent(SymbolGroup g) {
+ if (group_ == g)
+ return;
+ group_ = g;
+ update();
+}
+
+void GroupBadge::mousePressEvent(QMouseEvent* e) {
+ if (e->button() == Qt::LeftButton) {
+ emit group_change_requested(next_symbol_group(group_));
+ e->accept();
+ return;
+ }
+ QWidget::mousePressEvent(e);
+}
+
+void GroupBadge::contextMenuEvent(QContextMenuEvent* e) {
+ QMenu menu(this);
+ auto* unlink = menu.addAction("Unlink");
+ unlink->setEnabled(group_ != SymbolGroup::None);
+ connect(unlink, &QAction::triggered, this,
+ [this]() { emit group_change_requested(SymbolGroup::None); });
+ menu.addSeparator();
+ for (SymbolGroup g : all_symbol_groups()) {
+ auto* act = menu.addAction(QString("Link to Group %1").arg(symbol_group_letter(g)));
+ act->setCheckable(true);
+ act->setChecked(g == group_);
+ connect(act, &QAction::triggered, this, [this, g]() { emit group_change_requested(g); });
+ }
+ menu.exec(e->globalPos());
+}
+
+void GroupBadge::paintEvent(QPaintEvent*) {
+ QPainter p(this);
+ p.setRenderHint(QPainter::Antialiasing, true);
+ const QColor fill = color_for_group(group_);
+ const QRectF r = QRectF(rect()).adjusted(1.0, 1.0, -1.0, -1.0);
+
+ QPainterPath path;
+ path.addRoundedRect(r, 3.0, 3.0);
+ p.fillPath(path, fill);
+
+ // Letter
+ p.setPen(QColor("#ffffff"));
+ QFont f = p.font();
+ f.setPointSizeF(f.pointSizeF() - 1.0);
+ f.setBold(true);
+ p.setFont(f);
+ const QString label = group_ == SymbolGroup::None
+ ? QStringLiteral("·") // middle dot for unlinked
+ : QString(symbol_group_letter(group_));
+ p.drawText(r, Qt::AlignCenter, label);
+}
+
+QSize GroupBadge::sizeHint() const {
+ return QSize(18, 18);
+}
+
+} // namespace fincept::ui
diff --git a/fincept-qt/src/ui/widgets/GroupBadge.h b/fincept-qt/src/ui/widgets/GroupBadge.h
new file mode 100644
index 000000000..61fc33609
--- /dev/null
+++ b/fincept-qt/src/ui/widgets/GroupBadge.h
@@ -0,0 +1,51 @@
+#pragma once
+#include "core/symbol/SymbolGroup.h"
+
+#include <QColor>
+#include <QWidget>
+
+class QLabel;
+
+namespace fincept::ui {
+
+/// Small coloured letter pill shown in the top-left of any dock widget
+/// whose screen implements IGroupLinked. Mirrors Bloomberg Launchpad's
+/// group indicator:
+/// - `[A]` amber, `[B]` cyan, `[C]` magenta, `[D]` green, `[E]` purple, `[F]` red
+/// - Empty badge ("·") when the panel is unlinked (SymbolGroup::None)
+///
+/// Left-click: cycle None→A→B→…→F→None.
+/// Right-click: context menu with explicit pick + "Unlink" + "Show current".
+///
+/// The badge does not talk to SymbolContext directly — it only emits
+/// group_change_requested(). DockScreenRouter owns the wiring so that a
+/// single code path updates both the screen's IGroupLinked::set_group()
+/// and the SymbolContext subscription.
+class GroupBadge : public QWidget {
+ Q_OBJECT
+ public:
+ explicit GroupBadge(QWidget* parent = nullptr);
+
+ SymbolGroup group() const { return group_; }
+
+ /// Update the displayed group without emitting a change request. Used
+ /// by DockScreenRouter to reflect external state changes (workspace
+ /// load, programmatic set_group).
+ void set_group_silent(SymbolGroup g);
+
+ static QColor color_for_group(SymbolGroup g);
+
+ signals:
+ void group_change_requested(fincept::SymbolGroup g);
+
+ protected:
+ void mousePressEvent(QMouseEvent* e) override;
+ void contextMenuEvent(QContextMenuEvent* e) override;
+ void paintEvent(QPaintEvent* e) override;
+ QSize sizeHint() const override;
+
+ private:
+ SymbolGroup group_ = SymbolGroup::None;
+};
+
+} // namespace fincept::ui
diff --git a/fincept-qt/tests/datahub/test_datahub.cpp b/fincept-qt/tests/datahub/test_datahub.cpp
index 34a5688c2..efaa7adea 100644
--- a/fincept-qt/tests/datahub/test_datahub.cpp
+++ b/fincept-qt/tests/datahub/test_datahub.cpp
@@ -38,14 +38,9 @@ class RecordingProducer : public Producer {
all_requested_topics.append(t);
}
- void on_topic_idle(const QString& topic) override {
- idle_topics.append(topic);
- }
-
int refresh_count = 0;
QStringList last_refresh_topics;
QStringList all_requested_topics;
- QStringList idle_topics;
private:
QStringList patterns_;
@@ -59,6 +54,15 @@ class TestDataHub : public QObject {
private slots:
+ // Drain any queued invocations between tests so timer fires from one
+ // test don't leak into the next. DataHub is a singleton so state is
+ // shared across the whole run; we reset per-test side-effects here.
+ void cleanup() {
+ QCoreApplication::processEvents();
+ QCoreApplication::sendPostedEvents();
+ QCoreApplication::processEvents();
+ }
+
// Core flow — subscribe, publish, slot invoked.
void subscribe_publish_delivers() {
auto& hub = DataHub::instance();
@@ -101,6 +105,10 @@ class TestDataHub : public QObject {
} // owner destroyed here
// Give the queued destroyed() → on_owner_destroyed a chance to run.
+ // processEvents once may only deliver the first queued item; run a
+ // couple to drain all cascaded queued invocations.
+ QCoreApplication::sendPostedEvents();
+ QCoreApplication::processEvents();
QCoreApplication::processEvents();
hub.publish("test:destroy:1", QVariant(2));
@@ -110,6 +118,8 @@ class TestDataHub : public QObject {
QCOMPARE(call_count, 1);
// Subscriber count for this topic should have dropped to 0.
+ // After unsubscribe the subscriptions_ bucket is erased, so stats()
+ // reports the default zero (via missing bucket).
const auto stats = hub.stats();
for (const auto& s : stats)
if (s.topic == "test:destroy:1")
@@ -164,6 +174,12 @@ class TestDataHub : public QObject {
RecordingProducer prod({"test:flight:*"});
hub.register_producer(&prod);
+ // Disable coalesce window for deterministic synchronous testing —
+ // request() then dispatches on the next event-loop iteration instead
+ // of waiting ~100ms. Restored at end of test.
+ const int saved_coalesce = hub.coalesce_window_ms();
+ hub.set_coalesce_window_ms(0);
+
QObject owner;
hub.subscribe(&owner, "test:flight:1",
[](const QVariant&) {});
@@ -171,7 +187,8 @@ class TestDataHub : public QObject {
hub.request("test:flight:1");
hub.request("test:flight:1"); // should be deduped — already in-flight
- QCOMPARE(prod.refresh_count, 1);
+ // Let the zero-ms coalesce timer fire once.
+ QTRY_COMPARE(prod.refresh_count, 1);
// Once the producer publishes, the in-flight flag clears and the
// next request() should go through again.
@@ -179,9 +196,10 @@ class TestDataHub : public QObject {
QCoreApplication::processEvents();
hub.request("test:flight:1");
- QCOMPARE(prod.refresh_count, 2);
+ QTRY_COMPARE(prod.refresh_count, 2);
hub.unregister_producer(&prod);
+ hub.set_coalesce_window_ms(saved_coalesce);
}
// Cross-thread publish() must marshal to the hub thread safely.
@@ -218,6 +236,11 @@ class TestDataHub : public QObject {
RecordingProducer prod({"test:ttl:*"});
hub.register_producer(&prod);
+ // Clear any stale pattern policy from prior tests + use sync coalesce.
+ hub.clear_policy_pattern("test:ttl:*");
+ const int saved_coalesce = hub.coalesce_window_ms();
+ hub.set_coalesce_window_ms(0);
+
TopicPolicy p;
p.ttl_ms = 60'000;
p.min_interval_ms = 0;
@@ -226,9 +249,9 @@ class TestDataHub : public QObject {
QObject owner;
hub.subscribe(&owner, "test:ttl:1", [](const QVariant&) {});
- // First tick: no cached value → refresh fires.
- hub.tick_scheduler();
- QCOMPARE(prod.refresh_count, 1);
+ // subscribe() auto cold-starts a forced request — give the coalesce
+ // flush a chance to run and drive refresh_count to 1.
+ QTRY_COMPARE(prod.refresh_count, 1);
// Producer publishes; TTL is 60 s so next tick should skip.
hub.publish("test:ttl:1", QVariant(1));
@@ -238,6 +261,26 @@ class TestDataHub : public QObject {
QCOMPARE(prod.refresh_count, 1); // unchanged
hub.unregister_producer(&prod);
+ hub.set_coalesce_window_ms(saved_coalesce);
+ }
+
+ // peek() returns invalid when value is past TTL; peek_raw() returns anyway.
+ void peek_respects_ttl() {
+ auto& hub = DataHub::instance();
+
+ TopicPolicy p;
+ p.ttl_ms = 1; // effectively immediate expiry
+ p.min_interval_ms = 0;
+ hub.clear_policy_pattern(QStringLiteral("test:peek:*")); // idempotent if absent
+ hub.set_policy_pattern(QStringLiteral("test:peek:*"), p);
+
+ hub.publish(QStringLiteral("test:peek:ttl:1"), QVariant(QString("stale")));
+ QCoreApplication::processEvents();
+
+ QVERIFY(hub.peek_raw(QStringLiteral("test:peek:ttl:1")).isValid());
+ QTest::qWait(5); // exceed ttl
+ QVERIFY(!hub.peek(QStringLiteral("test:peek:ttl:1")).isValid()); // stale → invalid
+ QVERIFY(hub.peek_raw(QStringLiteral("test:peek:ttl:1")).isValid()); // raw still there
}
};