FinceptTerminal is a modern finance application offering advanced market analytics, investment research, and economic data tools, designed for interactive exploration and data-driven decision-making in a user-friendly environment.
C++ ai-agentsalgorithmic-tradingbloomberg-terminalcppfinancefinancial-marketsfintechgood-first-issueinvestmentinvestment-researchmachine-learningopensourcepythonqtquantitative-financestock-markettrading
Bug fixes and mac stable
Tilak09fed31555c9
diff --git a/3crcEyvNvGTvmzgXdb1HVw== b/3crcEyvNvGTvmzgXdb1HVw==new file mode 100644index 000000000..e69de29bbdiff --git a/README.md b/README.mdindex ac9ad73a9..d0a0311e1 100644--- a/README.md+++ b/README.md@@ -41,7 +41,7 @@ State-of-the-art financial intelligence platform with institutional-grade financ## About-**Fincept Terminal v4** is a pure native C++20 desktop application. It uses **Qt6** for UI and rendering, embedded **Python** for analytics, and delivers Bloomberg-terminal-class performance in a single native binary.+**Fincept Terminal v4** is a pure native C++20 desktop application. It uses **Qt6** for UI and rendering, embedded **Python** for analytics, and delivers professional terminal-class performance in a single native binary.---@@ -154,6 +154,8 @@ cmake --build --preset linux-release # Linuxcmake --build --preset macos-release # macOS```+> **Older or RAM-constrained machines:** add `--parallel 4` (or any small number) to cap concurrent compile jobs. The default saturates every core, which can overheat older CPUs and slow the rest of your system. Example: `cmake --build --preset macos-release --parallel 4`.+Debug variants: replace `release` with `debug` (e.g. `win-debug`, `linux-debug`, `macos-debug`).> **Windows prerequisite:** The PowerShell profile at `~/Documents/PowerShell/Microsoft.PowerShell_profile.ps1`diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex d3dc231f3..ee1e4d2d3 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -14,7 +14,7 @@ This document provides a comprehensive overview of Fincept Terminal v4's archite│ User Interface Layer ││ ┌─────────────────────────────────────────────────────────────┐ ││ │ Qt6 Widgets + Qt6 Charts │ │-│ │ - Obsidian design system (Bloomberg-style terminal UI) │ │+│ │ - Obsidian design system (professional terminal UI) │ ││ │ - Real-time data visualization │ ││ │ - Native platform rendering │ ││ └─────────────────────────────────────────────────────────────┘ │diff --git a/docs/CONTRIBUTING.md b/docs/CONTRIBUTING.mdindex c472ada26..22df005bf 100644--- a/docs/CONTRIBUTING.md+++ b/docs/CONTRIBUTING.md@@ -95,6 +95,8 @@ cmake --build --preset linux-release # Linuxcmake --build --preset macos-release # macOS```+> **Older or RAM-constrained machines:** add `--parallel 4` (or any small number) to cap concurrent compile jobs. The default saturates every core, which can overheat older CPUs and slow the rest of your system. Example: `cmake --build --preset macos-release --parallel 4`.+Debug builds: replace `release` with `debug` in both commands.Manual configure if presets can't resolve Qt:diff --git a/docs/CPP_CONTRIBUTOR_GUIDE.md b/docs/CPP_CONTRIBUTOR_GUIDE.mdindex 15284afd6..5dfba0236 100644--- a/docs/CPP_CONTRIBUTOR_GUIDE.md+++ b/docs/CPP_CONTRIBUTOR_GUIDE.md@@ -27,6 +27,8 @@ cmake --preset <win-release|linux-release|macos-release>cmake --build --preset <same-preset>```+> **Older or RAM-constrained machines:** add `--parallel 4` (or any small number) to cap concurrent compile jobs. The default saturates every core, which can overheat older CPUs and slow the rest of your system. Example: `cmake --build --preset macos-release --parallel 4`.+Debug variants: `win-debug`, `linux-debug`, `macos-debug`. See `fincept-qt/CMakePresets.json`.**Emergency override only** — pass `-DFINCEPT_ALLOW_QT_DRIFT=ON` to bypass the Qt `EXACT` check for local experiments. Never commit work built this way; CI rejects it.diff --git a/docs/GETTING_STARTED.md b/docs/GETTING_STARTED.mdindex 06e098c4f..f70eabd46 100644--- a/docs/GETTING_STARTED.md+++ b/docs/GETTING_STARTED.md@@ -7,13 +7,13 @@ Welcome to Fincept Terminal! This guide will get you from zero to your first con## What is Fincept Terminal?-Fincept Terminal is an **open-source financial analysis platform** — a free, open-source alternative to Bloomberg Terminal. Version 4 is a native C++20 application built with Qt6.+Fincept Terminal is an **open-source financial analysis platform** — a free, open-source alternative to legacy professional financial terminals. Version 4 is a native C++20 application built with Qt6.### The Big Picture**Current Reality:**-- Bloomberg Terminal: $24,000/year per user-- Refinitiv Eikon: $20,000+/year+- Legacy professional terminals: $20,000+/year per user+- Industry-standard market data subscriptions: $20,000+/year- Professional tools locked behind paywalls**Our Vision:**@@ -93,6 +93,10 @@ cmake --preset win-release && cmake --build --preset win-release # Windocmake --preset linux-release && cmake --build --preset linux-release # Linuxcmake --preset macos-release && cmake --build --preset macos-release # macOS+# Older or RAM-constrained machines: cap concurrent compile jobs to avoid+# saturating every core (the default behaviour). Example:+# cmake --build --preset macos-release --parallel 4+# 3. Run./build/linux-release/FinceptTerminal # Linux./build/macos-release/FinceptTerminal.app/Contents/MacOS/FinceptTerminal # macOSdiff --git a/docs/translations/README.de.md b/docs/translations/README.de.mdindex 7efedb11d..696f7b515 100644--- a/docs/translations/README.de.md+++ b/docs/translations/README.de.md@@ -20,7 +20,7 @@ Hochmoderne Financial-Intelligence-Plattform mit Finanzanalysen auf institutione## Um-**Fincept Terminal vch**ist eine rein native C++20-Desktopanwendung. Es nutzt**Qt6**für Benutzeroberfläche und Rendering, eingebettet**Python**für Analysen und liefert eine Leistung der Bloomberg-Terminal-Klasse in einer einzigen nativen Binärdatei.+**Fincept Terminal vch**ist eine rein native C++20-Desktopanwendung. Es nutzt**Qt6**für Benutzeroberfläche und Rendering, eingebettet**Python**für Analysen und liefert eine Leistung professioneller Terminal-Klasse in einer einzigen nativen Binärdatei.* * *diff --git a/docs/translations/README.es.md b/docs/translations/README.es.mdindex ba910524d..9c522de1a 100644--- a/docs/translations/README.es.md+++ b/docs/translations/README.es.md@@ -20,7 +20,7 @@ Plataforma de inteligencia financiera de última generación con análisis finan## Acerca de-**Terminal fincept vch**es una aplicación de escritorio nativa pura de C++20. se utiliza**qt6**para interfaz de usuario y renderizado, integrado**Pitón**para análisis y ofrece rendimiento de clase terminal Bloomberg en un único binario nativo.+**Terminal fincept vch**es una aplicación de escritorio nativa pura de C++20. se utiliza**qt6**para interfaz de usuario y renderizado, integrado**Pitón**para análisis y ofrece rendimiento de clase terminal profesional en un único binario nativo.* * *diff --git a/docs/translations/README.fr.md b/docs/translations/README.fr.mdindex a0027e501..2e14c2cce 100644--- a/docs/translations/README.fr.md+++ b/docs/translations/README.fr.md@@ -20,7 +20,7 @@ Plateforme de renseignement financier de pointe avec analyses financières de ni## À propos-**Fincept Terminal vch**est une application de bureau C++20 purement native. Il utilise**Qt6**pour l'interface utilisateur et le rendu, intégré**Python**pour l'analyse et offre des performances de classe terminal Bloomberg dans un seul binaire natif.+**Fincept Terminal vch**est une application de bureau C++20 purement native. Il utilise**Qt6**pour l'interface utilisateur et le rendu, intégré**Python**pour l'analyse et offre des performances de classe terminal professionnel dans un seul binaire natif.* * *diff --git a/docs/translations/README.ko.md b/docs/translations/README.ko.mdindex e8742320f..7013bb59c 100644--- a/docs/translations/README.ko.md+++ b/docs/translations/README.ko.md@@ -20,7 +20,7 @@## 에 대한-**Fincept 터미널 vch**순수 네이티브 C++20 데스크톱 애플리케이션입니다. 그것은 사용한다**Qt6**UI 및 렌더링용, 임베디드**파이썬**분석을 위해 단일 네이티브 바이너리로 Bloomberg 터미널 수준의 성능을 제공합니다.+**Fincept 터미널 vch**순수 네이티브 C++20 데스크톱 애플리케이션입니다. 그것은 사용한다**Qt6**UI 및 렌더링용, 임베디드**파이썬**분석을 위해 단일 네이티브 바이너리로 전문 금융 터미널 수준의 성능을 제공합니다.* * *diff --git a/docs/translations/README.zh-TW.md b/docs/translations/README.zh-TW.mdindex 3c54c7c64..a33e0fb89 100644--- a/docs/translations/README.zh-TW.md+++ b/docs/translations/README.zh-TW.md@@ -20,7 +20,7 @@## 關於-**Fincept Terminal v4** 是一個純原生的 C++20 桌面應用程式。它採用 **Qt6** 負責使用者介面與圖表渲染,並嵌入 **Python** 作為分析引擎,在單一原生執行檔中,提供媲美彭博終端機 (Bloomberg Terminal) 級別的強大效能。+**Fincept Terminal v4** 是一個純原生的 C++20 桌面應用程式。它採用 **Qt6** 負責使用者介面與圖表渲染,並嵌入 **Python** 作為分析引擎,在單一原生執行檔中,提供媲美專業金融終端機級別的強大效能。* * *diff --git a/fincept-qt/CMakeLists.txt b/fincept-qt/CMakeLists.txtindex e738a4141..8911f7ec0 100644--- a/fincept-qt/CMakeLists.txt+++ b/fincept-qt/CMakeLists.txt@@ -487,38 +487,14 @@ if(APPLE)endforeach()endif()-# ── SingleApplication (single-process enforcement + new-window IPC) ──────────-# When the user re-launches the exe, the secondary instance sends "--new-window"-# to the primary, which opens a new MainWindow instead of a second process.-# QAPPLICATION_CLASS must be set before FetchContent_MakeAvailable so the lib-# compiles inheriting QApplication (not QCoreApplication).-set(QT_DEFAULT_MAJOR_VERSION 6 CACHE STRING "" FORCE)-set(QAPPLICATION_CLASS QApplication CACHE STRING "" FORCE)-FetchContent_Declare(- SingleApplication- GIT_REPOSITORY https://github.com/itay-grudev/SingleApplication.git- GIT_TAG a8da87d78238ac9ac92d2cda41793d4879c188b3 # v3.5.4- GIT_SHALLOW TRUE- UPDATE_DISCONNECTED TRUE-)-FetchContent_MakeAvailable(SingleApplication)-# ── Patch SingleApplication for Qt 6.8 QSharedMemory compat ────────────────────-# Qt 6.8 changed the default QSharedMemory backend to PosixRealtime, but macOS's-# shm_open rejects the keys that SingleApplication generates ("bad name").-# Fix: use SystemV type which works on macOS (and Linux) with Qt 6.6+.-if(UNIX)- file(READ ${SingleApplication_SOURCE_DIR}/singleapplication.cpp _sa_src)- string(REPLACE- "d->memory = new QSharedMemory( QNativeIpcKey( d->blockServerName ) );"- "d->memory = new QSharedMemory(); d->memory->setNativeKey(d->blockServerName, QNativeIpcKey::Type::SystemV);"- _sa_src "${_sa_src}")- file(WRITE ${SingleApplication_SOURCE_DIR}/singleapplication.cpp "${_sa_src}")-endif()-if(MSVC)- target_compile_options(SingleApplication PRIVATE /W0 /WX-)-else()- target_compile_options(SingleApplication PRIVATE -w -Wno-error)-endif()+# ── Single-instance enforcement: in-tree InstanceLock (replaced SingleApplication)+# Previously used the SingleApplication library, which combined QSharedMemory+# and QSystemSemaphore. That stack leaked on macOS Qt 6.6+ (QTBUG-111855),+# silently exiting on Finder / `open` launches — see issues #234 and #252.+# We now ship src/app/InstanceLock.{h,cpp}: a small QLocalServer-based lock+# that uses Unix domain sockets / Windows named pipes. Same effective API+# (primary/secondary + IPC for "open new window"), no semaphore leaks, no+# path-length traps, no sandbox quirks.# ── Qt Advanced Docking System (detachable panels) ───────────────────────────# Panels become CDockWidgets — drag to float, dock, move to any monitor.@@ -736,6 +712,7 @@ set(STORAGE_SOURCESsrc/storage/sqlite/migrations/v022_portfolio_broker_link.cppsrc/storage/sqlite/migrations/v023_algo_trading_deploy.cppsrc/storage/sqlite/migrations/v024_alpha_arena.cpp+ src/storage/sqlite/migrations/v025_secure_credentials.cpp)# Python runner@@ -866,6 +843,7 @@ set(SERVICE_SOURCESsrc/services/alpha_arena/ModelDispatcher.cppsrc/services/alpha_arena/OrderRouter.cppsrc/services/alpha_arena/AlphaArenaEngine.cpp+ src/services/alpha_arena/AlphaArenaService.cppsrc/services/asia_markets/AsiaMarketsService.cppsrc/services/crypto/TotpService.cppsrc/services/python_cli/PythonCliService.cpp@@ -1112,6 +1090,7 @@ set(SCREEN_SOURCESsrc/screens/dashboard/canvas/AddWidgetDialog.cppsrc/screens/dashboard/canvas/TemplatePicker.cppsrc/screens/dashboard/widgets/BaseWidget.cpp+ src/screens/dashboard/widgets/LoadingOverlay.cppsrc/screens/dashboard/widgets/QuoteTableWidget.cppsrc/screens/dashboard/widgets/TopMoversWidget.cppsrc/screens/dashboard/widgets/NewsWidget.cpp@@ -1272,6 +1251,8 @@ set(SCREEN_SOURCESsrc/screens/ai_quant_lab/QuantModulePanel_AIMLDisplays.cppsrc/screens/ai_quant_lab/QuantModulePanel_CoreDisplays.cppsrc/screens/ai_quant_lab/QuantModulePanel_Misc.cpp+ src/screens/ai_quant_lab/QuantModulePanel_HFT.cpp+ src/screens/ai_quant_lab/QuantModulePanel_LiveLearning.cpp# Backtestingsrc/screens/backtesting/BacktestingScreen.cpp@@ -1451,6 +1432,7 @@ set(SCREEN_SOURCES# Appset(APP_SOURCESsrc/app/main.cpp+ src/app/InstanceLock.cppsrc/app/WindowFrame.cppsrc/app/ScreenRouter.cppsrc/app/DockScreenRouter.cpp@@ -1488,6 +1470,8 @@ set_source_files_properties(src/screens/ai_quant_lab/QuantModulePanel_AIMLDisplays.cppsrc/screens/ai_quant_lab/QuantModulePanel_CoreDisplays.cppsrc/screens/ai_quant_lab/QuantModulePanel_Misc.cpp+ src/screens/ai_quant_lab/QuantModulePanel_HFT.cpp+ src/screens/ai_quant_lab/QuantModulePanel_LiveLearning.cppsrc/screens/akshare/AkShareScreen.cppsrc/screens/algo_trading/AlgoTradingScreen.cppsrc/screens/algo_trading/DeploymentDashboard.cpp@@ -1552,6 +1536,7 @@ set_source_files_properties(src/screens/dashboard/canvas/WidgetRegistry.cppsrc/screens/dashboard/canvas/WidgetTile.cppsrc/screens/dashboard/widgets/BaseWidget.cpp+ src/screens/dashboard/widgets/LoadingOverlay.cppsrc/screens/dashboard/widgets/EconomicCalendarWidget.cppsrc/screens/dashboard/widgets/MarketSentimentWidget.cppsrc/screens/dashboard/widgets/NewsWidget.cpp@@ -1977,7 +1962,6 @@ add_executable(FinceptTerminal ${_FINCEPT_EXE_FLAGS}target_include_directories(FinceptTerminal PRIVATEsrc- ${SingleApplication_SOURCE_DIR})# ── macOS bundle properties ───────────────────────────────────────────────────@@ -2216,48 +2200,20 @@ target_link_libraries(FinceptTerminal PRIVATEqgeoviewmd4cmd4c-html- SingleApplication::SingleApplicationqtadvanceddocking-qt6OpenSSL::SSLOpenSSL::Cryptofincept_ed25519)-# macOS: link Security.framework + CoreFoundation for SecItem API in SecureStorage-if(APPLE)- target_link_libraries(FinceptTerminal PRIVATE "-framework Security" "-framework CoreFoundation")-endif()--# Linux: optionally link libsecret for cryptographically-secure credential-# storage (Secret Service / GNOME Keyring / KWallet via the freedesktop-# compatibility layer). Without libsecret, SecureStorage falls back to-# XOR-obfuscated QSettings which is NOT secure. Install libsecret-1-dev-# (Debian/Ubuntu), libsecret-devel (Fedora), or libsecret (Arch) and-# reconfigure to enable.-if(UNIX AND NOT APPLE)- find_package(PkgConfig QUIET)- if(PkgConfig_FOUND)- pkg_check_modules(LIBSECRET IMPORTED_TARGET libsecret-1)- if(LIBSECRET_FOUND)- target_link_libraries(FinceptTerminal PRIVATE PkgConfig::LIBSECRET)- target_compile_definitions(FinceptTerminal PRIVATE FINCEPT_HAVE_LIBSECRET)- message(STATUS "libsecret found — Linux SecureStorage will use Secret Service backend")- else()- message(WARNING- "libsecret-1 not found — Linux credential storage falls back to "- "XOR-obfuscated QSettings (NOT cryptographically secure). "- "Install libsecret-1-dev and rebuild for production deployments.")- endif()- endif()-endif()+# SecureStorage no longer needs platform-specific credential frameworks —+# it's pure SQLite + AES-256-GCM (OpenSSL) on every platform. See+# storage/secure/SecureStorage.cpp.# Windows: link dbghelp for the crash-handler minidump writer (see-# src/core/crash/CrashHandler.cpp). Also link Advapi32/Crypt32 explicitly for-# SecureStorage — they're normally pulled in transitively, but when MSVC runs-# /OPT:REF aggressively on release builds the indirect reference via wincred.h-# can get stripped, producing late-link errors.+# src/core/crash/CrashHandler.cpp).if(WIN32)- target_link_libraries(FinceptTerminal PRIVATE dbghelp Advapi32 Crypt32)+ target_link_libraries(FinceptTerminal PRIVATE dbghelp)endif()# Copy OpenSSL DLLs to build output — Windows only@@ -2636,6 +2592,17 @@ if(FINCEPT_BUILD_INSTALLER)set(CPACK_IFW_PACKAGE_WIZARD_STYLE "Modern")set(CPACK_IFW_PACKAGE_ALLOW_SPACE_IN_PATH ON)set(CPACK_IFW_PACKAGE_ALLOW_NON_ASCII_CHARACTERS ON)+ # Explicitly enable target-dir removal on uninstall. Defaults to ON in+ # CPackIFW, but #240 surfaced a case where the install root survived a+ # `purge` run — set explicit so the generated config.xml always carries+ # <RemoveTargetDir>true</RemoveTargetDir> regardless of CPackIFW version.+ set(CPACK_IFW_PACKAGE_REMOVE_TARGET_DIR ON)+ # Controller script for headless invocations (e.g. `purge --confirm-command+ # --accept-messages --default-answer`). Without it, IFW blocks on wizard+ # pages even with --confirm-command set, because page auto-advance is only+ # wired for the install path.+ set(CPACK_IFW_PACKAGE_CONTROL_SCRIPT+ "${CMAKE_CURRENT_SOURCE_DIR}/packaging/installer/config/controlscript.qs")# Target directory defaults per platformif(WIN32)diff --git a/fincept-qt/build-clang.pid b/fincept-qt/build-clang.piddeleted file mode 100644index 90c63ca45..000000000--- a/fincept-qt/build-clang.pid+++ /dev/null@@ -1 +0,0 @@-16744diff --git a/fincept-qt/packaging/installer/config/controlscript.qs b/fincept-qt/packaging/installer/config/controlscript.qsnew file mode 100644index 000000000..30c1bc129--- /dev/null+++ b/fincept-qt/packaging/installer/config/controlscript.qs@@ -0,0 +1,63 @@+// controlscript.qs — Fincept Terminal QtIFW Controller script.+//+// Wizard-page automation for headless invocations (e.g.+// `FinceptMaintenanceTool.exe purge --confirm-command --accept-messages+// --default-answer`). Without this, IFW would block on each wizard page+// even when --confirm-command is set, because some pages (Introduction,+// ReadyForInstallation, Finished) only auto-advance for the *installer*+// path, not the uninstaller path.+//+// Reference: https://doc.qt.io/qtinstallerframework/noninteractive.html++function Controller() {+ // No-op constructor. Page callbacks below are what actually drive+ // headless flows. Defining a Controller at all is what makes IFW+ // load this file.+}++// ── Headless install path (rare in maintenance-tool context, but harmless) ──++Controller.prototype.IntroductionPageCallback = function() {+ if (gui && gui.clickButton)+ gui.clickButton(buttons.NextButton);+};++Controller.prototype.TargetDirectoryPageCallback = function() {+ if (gui && gui.clickButton)+ gui.clickButton(buttons.NextButton);+};++Controller.prototype.ComponentSelectionPageCallback = function() {+ if (gui && gui.clickButton)+ gui.clickButton(buttons.NextButton);+};++Controller.prototype.LicenseAgreementPageCallback = function() {+ // Per Qt IFW docs example: explicitly check the accept radio before+ // clicking Next, otherwise the Next button stays disabled and silent+ // installs hang. Guard each access — `pageWidgetByObjectName` returns+ // null if the page isn't in the wizard for this run (e.g. uninstall+ // doesn't show a license page).+ if (!gui || !gui.pageWidgetByObjectName) return;+ var page = gui.pageWidgetByObjectName("LicenseAgreementPage");+ if (page && typeof page.AcceptLicenseRadioButton !== "undefined") {+ page.AcceptLicenseRadioButton.checked = true;+ }+ if (gui.clickButton)+ gui.clickButton(buttons.NextButton);+};++Controller.prototype.ReadyForInstallationPageCallback = function() {+ if (gui && gui.clickButton)+ gui.clickButton(buttons.CommitButton);+};++Controller.prototype.PerformInstallationPageCallback = function() {+ if (gui && gui.clickButton)+ gui.clickButton(buttons.CommitButton);+};++Controller.prototype.FinishedPageCallback = function() {+ if (gui && gui.clickButton)+ gui.clickButton(buttons.FinishButton);+};diff --git a/fincept-qt/packaging/installer/packages/com.fincept.terminal.core/meta/installscript.qs b/fincept-qt/packaging/installer/packages/com.fincept.terminal.core/meta/installscript.qsindex aaab9e6e9..d93682082 100644--- a/fincept-qt/packaging/installer/packages/com.fincept.terminal.core/meta/installscript.qs+++ b/fincept-qt/packaging/installer/packages/com.fincept.terminal.core/meta/installscript.qs@@ -30,22 +30,41 @@function Component(){- console.log("[Fincept] Component() constructor — isInstaller=" +- installer.isInstaller() +- " isUninstaller=" + installer.isUninstaller() +- " isUpdater=" + installer.isUpdater() +- " isPackageManager=" + installer.isPackageManager());-- // Connect signals using the 1-arg form. The 2-arg form (thisObj, fn) is- // not reliably supported by the QJSEngine that backs QtIFW component- // scripts — connections silently no-op on some versions.- if (installer.isInstaller()) {- installer.installationFinished.connect(onInstallationFinished);- }+ try {+ console.log("[Fincept] Component() constructor — isInstaller=" ++ installer.isInstaller() ++ " isUninstaller=" + installer.isUninstaller() ++ " isUpdater=" + installer.isUpdater() ++ " isPackageManager=" + installer.isPackageManager());++ // Pre-register the auto-answer for the data-cleanup confirmation+ // dialog. Without this, headless invocations (`purge --default-answer`)+ // deadlock on QMessageBox.question() in onUninstallationStarted —+ // --default-answer only handles IFW's *own* dialogs, not script-+ // spawned ones. This is what was causing the bug reported in #240+ // where `purge` exited 1 with no cleanup.+ // ID must match the first arg of QMessageBox.question() below.+ if (typeof QMessageBox !== "undefined" && installer.setMessageBoxAutomaticAnswer) {+ installer.setMessageBoxAutomaticAnswer(+ "fincept.uninstall.data", QMessageBox.No);+ }++ // Connect signals using the 1-arg form. The 2-arg form (thisObj, fn) is+ // not reliably supported by the QJSEngine that backs QtIFW component+ // scripts — connections silently no-op on some versions.+ if (installer.isInstaller()) {+ installer.installationFinished.connect(onInstallationFinished);+ }- if (installer.isUninstaller()) {- installer.uninstallationStarted.connect(onUninstallationStarted);- installer.uninstallationFinished.connect(onUninstallationFinished);+ if (installer.isUninstaller()) {+ installer.uninstallationStarted.connect(onUninstallationStarted);+ installer.uninstallationFinished.connect(onUninstallationFinished);+ }+ } catch (e) {+ // Never throw out of Component() — IFW treats that as a fatal load+ // error and aborts before any UI shows (the "GUI flashes and closes"+ // symptom in #240). Log and continue with defaults.+ console.log("[Fincept] Component() constructor error: " + e);}}@@ -111,35 +130,72 @@ function onInstallationFinished()function onUninstallationStarted(){- console.log("[Fincept] uninstallationStarted — prompting for user-data removal.");-- var answer = QMessageBox.question(- "fincept.uninstall.data",- "Remove Fincept Terminal User Data?",- "Do you want to remove all Fincept Terminal user data?\n\n" +- "This includes:\n" +- " - Databases (chat history, portfolio, watchlists)\n" +- " - Log files\n" +- " - Downloaded files and cached data\n" +- " - ML models (Whisper, etc.)\n" +- " - Python runtime and virtual environments\n" +- " - Workspaces and profiles\n" +- " - Saved credentials and API keys\n" +- " - Application settings\n\n" +- "Choose 'No' to keep your data for a future reinstall.",- QMessageBox.Yes | QMessageBox.No,- QMessageBox.No- );-- if (answer === QMessageBox.Yes) {- console.log("[Fincept] User chose Yes — cleaning all user data.");- try {- cleanUserData();- } catch (e) {- console.log("[Fincept] cleanUserData threw: " + e);+ try {+ console.log("[Fincept] uninstallationStarted.");++ // Per-machine install at C:\Program Files\... requires elevation to+ // delete files. Without this, the cmd.exe / reg.exe calls below+ // silently fail and IFW's own RemoveTargetDir step hits ACCESS_DENIED.+ // gainAdminRights() is a no-op if we're already elevated, and on+ // non-Windows it just returns. Failure here is non-fatal — log and+ // continue; some Windows configurations let `cmd /c rmdir` work+ // unelevated for user-owned trees.+ if (systemInfo.kernelType === "winnt") {+ try {+ installer.gainAdminRights();+ } catch (e) {+ console.log("[Fincept] gainAdminRights failed (continuing): " + e);+ }}- } else {- console.log("[Fincept] User chose No — keeping user data.");++ // Headless invocations (`purge --default-answer`, `--accept-messages`)+ // skip script-spawned QMessageBox confirmation entirely. The auto-+ // answer registered in Component() handles IFW's accounting; we just+ // need to not block here.+ var headless =+ (typeof installer.isCommandLineInstance === "function" &&+ installer.isCommandLineInstance()) ||+ (typeof gui === "undefined" || gui === null);++ var clean = false;+ if (headless) {+ console.log("[Fincept] Headless uninstall — skipping data-cleanup prompt.");+ } else {+ var answer = QMessageBox.question(+ "fincept.uninstall.data",+ "Remove Fincept Terminal User Data?",+ "Do you want to remove all Fincept Terminal user data?\n\n" ++ "This includes:\n" ++ " - Databases (chat history, portfolio, watchlists)\n" ++ " - Log files\n" ++ " - Downloaded files and cached data\n" ++ " - ML models (Whisper, etc.)\n" ++ " - Python runtime and virtual environments\n" ++ " - Workspaces and profiles\n" ++ " - Saved credentials and API keys\n" ++ " - Application settings\n\n" ++ "Choose 'No' to keep your data for a future reinstall.",+ QMessageBox.Yes | QMessageBox.No,+ QMessageBox.No+ );+ clean = (answer === QMessageBox.Yes);+ }++ if (clean) {+ console.log("[Fincept] Cleaning user data.");+ try {+ cleanUserData();+ } catch (e) {+ console.log("[Fincept] cleanUserData threw: " + e);+ }+ } else {+ console.log("[Fincept] Keeping user data.");+ }+ } catch (e) {+ // Never propagate — IFW treats a thrown signal handler as a fatal+ // uninstall error and exits 1 with no cleanup, which is exactly the+ // symptom from #240.+ console.log("[Fincept] onUninstallationStarted error: " + e);}}@@ -191,14 +247,15 @@ function cleanUserDataWindows()runAndLog("reg.exe", ["delete", "HKCU\\Software\\Fincept", "/f"]);// 5. Windows Credential Manager entries: FinceptTerminal/*- // cmdkey has no wildcard delete. Enumerate via PowerShell and delete each.- runAndLog("powershell.exe", [- "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command",- "$list = cmdkey /list 2>$null | Select-String -Pattern 'FinceptTerminal/'; " +- "foreach ($line in $list) { " +- " $target = ($line.ToString() -replace '^\\s*Target:\\s*','').Trim(); " +- " if ($target) { cmdkey /delete:$target | Out-Null } " +- "}"+ // cmdkey has no wildcard delete. Enumerate via a cmd.exe FOR loop —+ // we used PowerShell originally but #240 confirmed the maintenance+ // tool fails on locked-down Win11 boxes where AppLocker/Defender+ // blocks installer-spawned powershell.exe. cmd.exe has no such+ // restrictions. The FOR /F parses `cmdkey /list` lines that match+ // "Target: FinceptTerminal/..." and deletes each.+ runAndLog("cmd.exe", ["/c",+ "for /f \"tokens=1,* delims=:\" %a in ('cmdkey /list 2^>nul ^| findstr /i \"FinceptTerminal/\"') do " ++ "(for /f \"tokens=*\" %c in (\"%b\") do cmdkey /delete:\"%c\" >nul 2>&1) & exit /b 0"]);// 6. Temp files — single shell string so wildcards expand inside cmd.@@ -210,16 +267,17 @@ function cleanUserDataWindows()"exit /b 0"]);// 7. Screenshots saved under %USERPROFILE% by MainWindow "save screenshot"- // with the strict pattern fincept_YYYYMMDD_HHMMSS.png. Only match that- // exact shape so we don't delete unrelated user files.+ // with the strict pattern fincept_YYYYMMDD_HHMMSS.png. cmd.exe's `del`+ // wildcards aren't strict enough on their own ("fincept_*.png" would+ // nuke any user file matching), so we narrow with a FOR loop that+ // checks the digit-shape via findstr.var userProfile = installer.environmentVariable("USERPROFILE");if (userProfile) {- runAndLog("powershell.exe", [- "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command",- "Get-ChildItem -LiteralPath '" + toWin(userProfile) + "' -File " +- "-Filter 'fincept_*.png' -ErrorAction SilentlyContinue | " +- "Where-Object { $_.Name -match '^fincept_\\d{8}_\\d{6}\\.png$' } | " +- "Remove-Item -Force -ErrorAction SilentlyContinue"+ var up = toWin(userProfile);+ runAndLog("cmd.exe", ["/c",+ "for /f \"delims=\" %f in ('dir /b /a-d \"" + up + "\\fincept_*.png\" 2^>nul ^| " ++ "findstr /r \"^fincept_[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]_[0-9][0-9][0-9][0-9][0-9][0-9]\\.png$\"') do " ++ "del /q /f \"" + up + "\\%f\" 2>nul & exit /b 0"]);}}diff --git a/fincept-qt/resources/fincept.icns b/fincept-qt/resources/fincept.icnsnew file mode 100644index 000000000..23abcc4b9Binary files /dev/null and b/fincept-qt/resources/fincept.icns differdiff --git a/fincept-qt/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/organization/personas.py b/fincept-qt/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/organization/personas.pyindex 136f9feb8..9b9b939df 100644--- a/fincept-qt/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/organization/personas.py+++ b/fincept-qt/scripts/agents/hedgeFundAgents/renaissance_technologies_hedge_fund_agent/organization/personas.py@@ -401,7 +401,7 @@ When providing data, always include:DATA RETRIEVED:- Price data: 252 trading days (1 year)-- Source: Primary exchange feed, validated against Bloomberg+- Source: Primary exchange feed, validated against tier-1 vendor data- Quality score: 98/100 (2 minor gaps filled via interpolation)FEATURES COMPUTED:diff --git a/fincept-qt/scripts/akshare_index.py b/fincept-qt/scripts/akshare_index.pyindex 53b304e30..18681b5e0 100644--- a/fincept-qt/scripts/akshare_index.py+++ b/fincept-qt/scripts/akshare_index.py@@ -443,11 +443,11 @@ def get_index_news_sentiment_scope():return safe_call(ak.index_news_sentiment_scope)def get_index_bloomberg_billionaires():- """Get Bloomberg Billionaires Index"""+ """Get global billionaires index (akshare endpoint: index_bloomberg_billionaires)"""return safe_call(ak.index_bloomberg_billionaires)def get_index_bloomberg_billionaires_hist(symbol="�马化腾"):- """Get Bloomberg Billionaires historical data"""+ """Get global billionaires historical data (akshare endpoint: index_bloomberg_billionaires_hist)"""return safe_call(ak.index_bloomberg_billionaires_hist, symbol=symbol)@@ -542,7 +542,7 @@ ENDPOINTS = {"index_yiwu": {"func": get_index_yw, "desc": "YiWu Small Commodity Index", "category": "Other Index"},"index_fashion": {"func": get_index_kq_fashion, "desc": "KQ Fashion Index", "category": "Other Index"},"index_news_sentiment": {"func": get_index_news_sentiment_scope, "desc": "News sentiment index", "category": "Other Index"},- "index_billionaires": {"func": get_index_bloomberg_billionaires, "desc": "Bloomberg Billionaires", "category": "Other Index"},+ "index_billionaires": {"func": get_index_bloomberg_billionaires, "desc": "Global Billionaires Index", "category": "Other Index"},}diff --git a/fincept-qt/scripts/openfigi_data.py b/fincept-qt/scripts/openfigi_data.pyindex 5455f7e3a..24945b339 100644--- a/fincept-qt/scripts/openfigi_data.py+++ b/fincept-qt/scripts/openfigi_data.py@@ -1,6 +1,6 @@"""OpenFIGI Data Fetcher-Map tickers/ISINs/CUSIPs to Bloomberg FIGI identifiers. 1700+ asset classes globally.+Map tickers/ISINs/CUSIPs to global FIGI identifiers. 1700+ asset classes globally.No key for basic use (higher rate with OPENFIGI_API_KEY)."""import sysdiff --git a/fincept-qt/src/ai_chat/LlmFinceptAsync.cpp b/fincept-qt/src/ai_chat/LlmFinceptAsync.cppindex ba889e49b..afd19c1d7 100644--- a/fincept-qt/src/ai_chat/LlmFinceptAsync.cpp+++ b/fincept-qt/src/ai_chat/LlmFinceptAsync.cpp@@ -1,10 +1,5 @@-// LlmFinceptAsync.cpp — Fincept-specific async LLM path.-//-// POST /research/llm/async to submit, then poll /research/llm/status/{id}-// every 3s up to 120s. The submit endpoint takes a flat prompt (not OpenAI-// messages), so we synthesise system + tool catalog + history into a single-// string here. Follow-ups after tool execution use the sync /research/chat-// endpoint via try_extract_and_execute_text_tool_calls.+// Fincept async LLM path: POST /research/llm/async then poll status every 3s up to 120s.+// Submit takes a flat prompt, so system + tool catalog + history are flattened here.#include "ai_chat/LlmService.h"@@ -26,20 +21,11 @@namespace fincept::ai_chat {-namespace { constexpr const char* TAG = "LlmService"; }--// Build a compact tool catalog string for injection into the system prompt.-// This allows models that don't support structured tool_calls to still emit-// text-based tool invocations that try_extract_and_execute_text_tool_calls-// can detect and execute.-//-// Two modes:-// • Tool RAG ON + default filter: emit only the Tier-0 tools + explicit-// instructions to use tool.list for everything else. Same disclosure-// model as structured providers — keeps the catalog small and forces-// deliberate discovery.-// • Tool RAG OFF or explicit filter: legacy behaviour — list up to 60-// filtered tools inline.+namespace { constexpr const char* kFinceptAsyncTag = "LlmService"; }++/// Tool catalog injected into the system prompt for models without structured tool_calls.+/// RAG mode (default filter): Tier-0 tools only + tool.list discovery hint.+/// Otherwise: up to 60 filtered tools inline.static QString build_tool_catalog_for_prompt(const mcp::ToolFilter& filter) {auto all_tools = mcp::McpService::instance().get_all_tools(filter);if (all_tools.empty())@@ -60,8 +46,7 @@ static QString build_tool_catalog_for_prompt(const mcp::ToolFilter& filter) {catalog += "<tool_call>{\"name\": \"TOOL_NAME\", \"arguments\": {\"param\": \"value\"}}</tool_call>\n\n";if (use_rag) {- // Mirror McpService::tier_0_tool_names() (kept in sync manually — small- // list, low churn).+ // Mirrors McpService::tier_0_tool_names() — kept in sync manually.static const QSet<QString> kTier0 = {"tool.list", "tool.describe", "navigate_to_tab", "list_tabs","get_current_tab", "get_auth_status",@@ -84,7 +69,6 @@ static QString build_tool_catalog_for_prompt(const mcp::ToolFilter& filter) {return catalog;}- // ── Legacy mode ──catalog += "Available tools:\n";int count = 0;for (const auto& tool : all_tools) {@@ -111,12 +95,11 @@ LlmResponse LlmService::fincept_async_request(const QString& user_message,const std::vector<ConversationMessage>& history) {LlmResponse resp;- // Build prompt string for the async endpoint (it takes a plain prompt, not messages)+ // Endpoint takes a plain prompt, not OpenAI messages.QString prompt;if (!system_prompt_.isEmpty())prompt += system_prompt_ + "\n\n";- // Inject tool catalog so the model can emit text-based tool callsif (detail::effective_tools_enabled(tools_enabled_)) {QString tool_catalog = build_tool_catalog_for_prompt(detail::apply_request_policy(tool_filter_));if (!tool_catalog.isEmpty())@@ -134,13 +117,12 @@ LlmResponse LlmService::fincept_async_request(const QString& user_message,QJsonObject submit_body;submit_body["prompt"] = prompt;submit_body["max_tokens"] = resolved_max_tokens();- // Temperature intentionally omitted — Fincept backend uses its own default.auto hdr = get_headers();const QString async_url = "https://api.fincept.in/research/llm/async";const QString status_base = "https://api.fincept.in/research/llm/status/";- LOG_INFO(TAG, QString("Fincept async: submitting to %1 (api_key=%2, prompt_len=%3)")+ LOG_INFO(kFinceptAsyncTag, QString("Fincept async: submitting to %1 (api_key=%2, prompt_len=%3)").arg(async_url).arg(api_key_.isEmpty() ? "EMPTY" : api_key_.left(12) + "...").arg(prompt.length()));@@ -149,7 +131,7 @@ LlmResponse LlmService::fincept_async_request(const QString& user_message,auto submit = eventloop_request("POST", async_url, json_data, hdr, 30000);if (!submit.success) {resp.error = "Fincept async submit failed: " + submit.error;- LOG_ERROR(TAG, resp.error);+ LOG_ERROR(kFinceptAsyncTag, resp.error);return resp;}@@ -159,7 +141,7 @@ LlmResponse LlmService::fincept_async_request(const QString& user_message,return resp;}- // Response can nest task_id at top level or inside data+ // task_id may be top-level or under data.QJsonObject sj = submit_doc.object();QString task_id = sj["task_id"].toString();if (task_id.isEmpty())@@ -168,9 +150,8 @@ LlmResponse LlmService::fincept_async_request(const QString& user_message,resp.error = "Fincept async: no task_id in submit response";return resp;}- LOG_INFO(TAG, "Fincept async task_id: " + task_id);+ LOG_INFO(kFinceptAsyncTag, "Fincept async task_id: " + task_id);- // Poll every 3 seconds, up to 120 seconds totalconst QString poll_url = status_base + task_id;constexpr int MAX_POLLS = 40;for (int i = 0; i < MAX_POLLS; ++i) {@@ -178,7 +159,7 @@ LlmResponse LlmService::fincept_async_request(const QString& user_message,auto poll = eventloop_request("GET", poll_url, {}, hdr, 15000);if (!poll.success) {- LOG_WARN(TAG, "Fincept async poll failed: " + poll.error);+ LOG_WARN(kFinceptAsyncTag, "Fincept async poll failed: " + poll.error);continue;}@@ -192,16 +173,15 @@ LlmResponse LlmService::fincept_async_request(const QString& user_message,if (status.isEmpty())status = data_obj["status"].toString();- LOG_INFO(TAG, QString("Fincept async poll %1 status=%2").arg(i + 1).arg(status));+ LOG_INFO(kFinceptAsyncTag, QString("Fincept async poll %1 status=%2").arg(i + 1).arg(status));if (status == "completed") {- // data.data.responseQString response = data_obj["data"].toObject()["response"].toString();if (response.isEmpty())response = data_obj["response"].toString();if (response.isEmpty()) {resp.error = "Fincept async completed but response is empty";- LOG_WARN(TAG, "Fincept async task completed with empty response field");+ LOG_WARN(kFinceptAsyncTag, "Fincept async task completed with empty response field");return resp;}resp.content = response;@@ -214,17 +194,15 @@ LlmResponse LlmService::fincept_async_request(const QString& user_message,resp.total_tokens = usage["total_tokens"].toInt();}- // Check for text-based tool calls in the response.- // The model may have emitted <tool_call>...</tool_call> blocks.+ // Detect <tool_call>...</tool_call> blocks the model may have emitted; follow up via sync /research/chat.if (!resp.content.isEmpty()) {- LOG_INFO(TAG, "Fincept: checking response for text-based tool calls");- // Use the sync /research/chat endpoint for follow-up after tool execution+ LOG_INFO(kFinceptAsyncTag, "Fincept: checking response for text-based tool calls");QString followup_url = get_endpoint_url();auto followup_hdr = get_headers();auto tool_result =try_extract_and_execute_text_tool_calls(resp.content, user_message, followup_url, followup_hdr);if (tool_result.has_value()) {- LOG_INFO(TAG, "Fincept: text tool calls detected and executed");+ LOG_INFO(kFinceptAsyncTag, "Fincept: text tool calls detected and executed");return tool_result.value();}}diff --git a/fincept-qt/src/ai_chat/LlmModelsApi.cpp b/fincept-qt/src/ai_chat/LlmModelsApi.cppindex b9d12dd09..c426a03e4 100644--- a/fincept-qt/src/ai_chat/LlmModelsApi.cpp+++ b/fincept-qt/src/ai_chat/LlmModelsApi.cpp@@ -1,13 +1,11 @@-// LlmModelsApi.cpp — dynamic model discovery for each supported provider.-// Builds the right URL + headers per provider, then runs an async GET on a-// worker thread and emits models_fetched on completion.+// Per-provider model-list discovery. Async GET on the GUI thread; emits models_fetched.#include "ai_chat/LlmService.h"+#include "core/logging/Logger.h"#include "storage/repositories/SettingsRepository.h"#include <QByteArray>-#include <QEventLoop>#include <QJsonArray>#include <QJsonDocument>#include <QJsonObject>@@ -15,20 +13,29 @@#include <QNetworkAccessManager>#include <QNetworkReply>#include <QNetworkRequest>-#include <QPointer>#include <QString>#include <QStringList>#include <QTimer>#include <QUrl>-#include <QtConcurrent/QtConcurrent>namespace fincept::ai_chat {+static constexpr const char* TAG = "LlmModelsApi";+QString LlmService::get_models_url(const QString& provider, const QString& api_key, const QString& base_url) {- Q_UNUSED(api_key) // Auth goes via headers (see get_models_headers()), URL is provider-based.+ Q_UNUSED(api_key) // Auth in headers, not URL.const QString p = provider.toLower();- // Custom base_url (except fincept)+ // Ollama uses /api/tags, not /v1/models — must short-circuit before the custom-base_url branch+ // or a user with base_url=http://localhost:11434 hits the wrong path and parses a 404 page.+ if (p == "ollama") {+ QString base = base_url.isEmpty() ? "http://localhost:11434" : base_url;+ if (base.endsWith('/'))+ base.chop(1);+ return base + "/api/tags";+ }++ // Custom base_url (except fincept) — assume OpenAI-compatible /v1/models.if (!base_url.isEmpty() && p != "fincept") {QString base = base_url;if (base.endsWith('/'))@@ -41,22 +48,15 @@ QString LlmService::get_models_url(const QString& provider, const QString& api_kif (p == "openai") return "https://api.openai.com/v1/models";if (p == "anthropic") return "https://api.anthropic.com/v1/models?limit=1000";if (p == "gemini" || p == "google") {- // 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";if (p == "deepseek") return "https://api.deepseek.com/models";if (p == "openrouter") return "https://openrouter.ai/api/v1/models";- if (p == "ollama") {- QString base = base_url.isEmpty() ? "http://localhost:11434" : base_url;- if (base.endsWith('/'))- 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+ // minimax has no public /v1/models — caller falls back to known models.return {};}@@ -69,13 +69,12 @@ QMap<QString, QString> LlmService::get_models_headers(const QString& provider, ch["x-api-key"] = api_key;h["anthropic-version"] = "2023-06-01";} else if (p == "gemini" || p == "google") {- // Key is in URL query param OR headerif (!api_key.isEmpty())h["x-goog-api-key"] = api_key;} else if (p == "ollama") {- // No auth needed+ // No auth.} else if (p == "fincept") {- // Resolve API key from session (same logic as ensure_config)+ // Same fallback as ensure_config.QString resolved_key = api_key;if (resolved_key.isEmpty()) {auto stored = SettingsRepository::instance().get("fincept_api_key");@@ -85,7 +84,7 @@ QMap<QString, QString> LlmService::get_models_headers(const QString& provider, cif (!resolved_key.isEmpty())h["X-API-Key"] = resolved_key;} else {- // OpenAI-compatible: OpenAI, Groq, DeepSeek, OpenRouter+ // OpenAI-compatible.if (!api_key.isEmpty())h["Authorization"] = "Bearer " + api_key;}@@ -101,11 +100,10 @@ QStringList LlmService::parse_models_response(const QString& provider, const QByconst QString p = provider.toLower();if (p == "gemini" || p == "google") {- // {"models": [{"name": "models/gemini-...", "supportedGenerationMethods": [...]}]}QJsonArray arr = root["models"].toArray();for (const auto& v : arr) {QJsonObject m = v.toObject();- // Only include models that support generateContent+ // Filter to models that support generateContent.QJsonArray methods = m["supportedGenerationMethods"].toArray();bool can_generate = false;for (const auto& method : methods) {@@ -118,14 +116,12 @@ QStringList LlmService::parse_models_response(const QString& provider, const QBycontinue;QString name = m["name"].toString();- // Strip "models/" prefixif (name.startsWith("models/"))name = name.mid(7);if (!name.isEmpty())models.append(name);}} else if (p == "ollama") {- // {"models": [{"name": "llama3:8b", ...}]}QJsonArray arr = root["models"].toArray();for (const auto& v : arr) {QString name = v.toObject()["name"].toString();@@ -133,8 +129,7 @@ QStringList LlmService::parse_models_response(const QString& provider, const QBymodels.append(name);}} else if (p == "fincept") {- // {"success":true,"data":{"models":["MiniMax-M2.7",...]}}- // or {"success":true,"data":["model1","model2",...]}+ // data may be either {"models":[...]} or a direct array.QJsonValue data_val = root["data"];QJsonArray arr;if (data_val.isObject())@@ -146,12 +141,10 @@ QStringList LlmService::parse_models_response(const QString& provider, const QByif (!id.isEmpty())models.append(id);}- // If API doesn't expose a models endpoint yet, fall back to known modelsif (models.isEmpty())models = {"MiniMax-M2.7", "MiniMax-M2.7-highspeed", "MiniMax-M2.5"};} else {- // OpenAI-compatible: OpenAI, Anthropic, Groq, DeepSeek, OpenRouter- // {"data": [{"id": "model-id", ...}]}+ // OpenAI-compatible: {"data": [{"id": ...}]}.QJsonArray arr = root["data"].toArray();for (const auto& v : arr) {QString id = v.toObject()["id"].toString();@@ -165,70 +158,70 @@ QStringList LlmService::parse_models_response(const QString& provider, const QBy}void LlmService::fetch_models(const QString& provider, const QString& api_key, const QString& base_url) {- // Fincept has no public /models listing endpoint — return known models immediately.+ // No public /models endpoint for fincept — return known list immediately.if (provider.toLower() == "fincept") {emit models_fetched(provider,{"MiniMax-M2.7", "MiniMax-M2.7-highspeed", "MiniMax-M2.5", "MiniMax-M2.5-highspeed"}, {});return;}- QString url = get_models_url(provider, api_key, base_url);+ const QString url = get_models_url(provider, api_key, base_url);if (url.isEmpty()) {emit models_fetched(provider, {}, "Unknown provider: " + provider);return;}+ // NAM must live on the main thread — its DNS/TLS path needs a pumping event loop.+ if (!models_nam_)+ models_nam_ = new QNetworkAccessManager(this);++ QNetworkRequest req{QUrl(url)};+ req.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy);auto headers = get_models_headers(provider, api_key);+ for (auto it = headers.constBegin(); it != headers.constEnd(); ++it)+ req.setRawHeader(it.key().toUtf8(), it.value().toUtf8());++ LOG_INFO(TAG, QString("fetch_models start: provider=%1 url=%2").arg(provider, url));- QPointer<LlmService> self = this;- (void)QtConcurrent::run([self, provider, url, headers]() {- // Blocking GET (reuse blocking_post pattern but with GET)- QNetworkAccessManager nam;- QNetworkRequest req{QUrl(url)};- for (auto it = headers.constBegin(); it != headers.constEnd(); ++it)- req.setRawHeader(it.key().toUtf8(), it.value().toUtf8());+ QNetworkReply* reply = models_nam_->get(req);- QNetworkReply* reply = nam.get(req);+ reply->setProperty("_provider", provider);+ auto* timer = new QTimer(reply);+ timer->setSingleShot(true);+ connect(timer, &QTimer::timeout, reply, [reply]() {+ if (reply->isRunning())+ reply->abort();+ });+ timer->start(15000);- QEventLoop loop;- QTimer timer;- timer.setSingleShot(true);- QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);- QObject::connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit);- timer.start(15000);- loop.exec();+ connect(reply, &QNetworkReply::finished, this, [this, reply]() {+ reply->deleteLater();+ const QString p = reply->property("_provider").toString();QString error;QStringList models;+ const int status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();- if (!timer.isActive()) {- reply->abort();- error = "Request timed out";- } else {- timer.stop();- int status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();- if (reply->error() != QNetworkReply::NoError || status < 200 || status >= 300) {+ if (reply->error() != QNetworkReply::NoError || status < 200 || status >= 300) {+ if (reply->error() == QNetworkReply::OperationCanceledError)+ error = "Request timed out";+ else {error = reply->errorString();if (error.isEmpty())- error = "HTTP " + QString::number(status);- } else {- models = parse_models_response(provider, reply->readAll());- if (models.isEmpty())- error = "No models found";+ error = QString("HTTP %1").arg(status);}+ LOG_WARN(TAG, QString("fetch_models %1 failed: %2 (status=%3 qt_error=%4)")+ .arg(p, error)+ .arg(status)+ .arg(static_cast<int>(reply->error())));+ } else {+ models = parse_models_response(p, reply->readAll());+ if (models.isEmpty())+ error = "No models found";+ LOG_INFO(TAG, QString("fetch_models %1 → %2 models").arg(p).arg(models.size()));}- reply->deleteLater();-- if (self) {- QMetaObject::invokeMethod(- self,- [self, provider, models, error]() {- if (self)- emit self->models_fetched(provider, models, error);- },- Qt::QueuedConnection);- }+ emit models_fetched(p, models, error);});}diff --git a/fincept-qt/src/ai_chat/LlmRequestBuilders.cpp b/fincept-qt/src/ai_chat/LlmRequestBuilders.cppindex 24861dabe..dff1ef7ca 100644--- a/fincept-qt/src/ai_chat/LlmRequestBuilders.cpp+++ b/fincept-qt/src/ai_chat/LlmRequestBuilders.cpp@@ -1,6 +1,4 @@-// LlmRequestBuilders.cpp — per-provider JSON request shape builders.-// Each method translates the conversation + active config into the wire-// format the provider's chat-completion endpoint expects.+// Per-provider chat-completion request shape builders.#include "ai_chat/LlmService.h"@@ -15,17 +13,15 @@namespace fincept::ai_chat {-namespace { constexpr const char* TAG = "LlmService"; }+namespace { constexpr const char* kRequestBuildersTag = "LlmService"; }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`.+ // Models that reject `tools`: deepseek-reasoner, groq whisper-* (audio), groq llama-guard-* (classifier).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")));@@ -39,10 +35,7 @@ QJsonObject LlmService::build_openai_request(const QString& user_message,QJsonObject req;req["model"] = model_;req["messages"] = messages;- // 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.+ // Temperature omitted — each provider's default. OpenAI/xAI use max_completion_tokens; others max_tokens.const int mx = resolved_max_tokens();if (provider_ == "openai" || provider_ == "xai")req["max_completion_tokens"] = mx;@@ -50,29 +43,24 @@ QJsonObject LlmService::build_openai_request(const QString& user_message,req["max_tokens"] = mx;if (stream) {req["stream"] = true;- // Streamed OpenAI / xAI responses omit usage unless we opt in+ // OpenAI/xAI omit usage on streamed responses unless we opt in.if (provider_ == "openai" || provider_ == "xai")req["stream_options"] = QJsonObject{{"include_usage", true}};}- // Send tools on BOTH streaming and non-streaming requests. The streaming- // path detects a tool-call response (finish_reason="tool_calls" or- // delta.tool_calls) and falls back to non-streaming do_request, which- // executes the tools and follows up. Without sending tools on stream,- // the model has no idea they exist and answers from training data —- // which silently breaks live tool calling for OpenAI/Kimi/Groq/etc.- // deepseek-reasoner rejects tools entirely; some Groq models also.+ // Send tools on streaming requests too — the stream path detects tool_calls and falls back+ // to do_request to execute. Otherwise the model answers from training and tool calling silently breaks.const bool tools_effectively_on = detail::effective_tools_enabled(tools_enabled_);if (with_tools && tools_effectively_on && !is_ds_reasoner && !groq_no_tools) {QJsonArray tools = mcp::McpService::instance().format_tools_for_openai(detail::apply_request_policy(tool_filter_));if (!tools.isEmpty())req["tools"] = tools;- LOG_INFO(TAG, QString("OpenAI request: stream=%1 provider=%2 tools=%3 (count=%4)")+ LOG_INFO(kRequestBuildersTag, QString("OpenAI request: stream=%1 provider=%2 tools=%3 (count=%4)").arg(stream ? "true" : "false", provider_,tools.isEmpty() ? "none" : "attached").arg(tools.size()));} else {- LOG_WARN(TAG, QString("OpenAI request: stream=%1 provider=%2 NO TOOLS — "+ LOG_WARN(kRequestBuildersTag, QString("OpenAI request: stream=%1 provider=%2 NO TOOLS — ""with_tools=%3 tools_effectively_on=%4 ds_reasoner=%5 groq_no_tools=%6").arg(stream ? "true" : "false", provider_).arg(with_tools ? "true" : "false")@@ -96,17 +84,12 @@ QJsonObject LlmService::build_anthropic_request(const QString& user_message,req["model"] = model_;req["messages"] = messages;req["max_tokens"] = resolved_max_tokens();- // Temperature intentionally omitted — Anthropic defaults to 1.0.if (!system_prompt_.isEmpty())req["system"] = system_prompt_;if (stream)req["stream"] = true;- // Anthropic tool format: array of {name, description, input_schema}- // (no "type":"function" wrapper like OpenAI). Tools are sent for both- // streaming and non-streaming requests so the model can request a- // tool_use even mid-stream — the streaming code path detects this and- // falls back to do_request to execute and follow up.+ // Anthropic tools: bare {name, description, input_schema} — no OpenAI-style "type":"function" wrapper.if (detail::effective_tools_enabled(tools_enabled_)) {QJsonArray ant_tools;auto all_tools = mcp::McpService::instance().get_all_tools(detail::apply_request_policy(tool_filter_));@@ -138,7 +121,6 @@ QJsonObject LlmService::build_gemini_request(const QString& user_message,contents.append(QJsonObject{{"role", "user"}, {"parts", QJsonArray{QJsonObject{{"text", user_message}}}}});QJsonObject gen_cfg;- // Temperature intentionally omitted — Gemini defaults to 1.0.gen_cfg["maxOutputTokens"] = resolved_max_tokens();QJsonObject req;@@ -148,7 +130,7 @@ QJsonObject LlmService::build_gemini_request(const QString& user_message,req["systemInstruction"] = QJsonObject{{"parts", QJsonArray{QJsonObject{{"text", system_prompt_}}}}};}- // Gemini tool format: tools[{functionDeclarations:[{name, description, parameters}]}]+ // Gemini tools: tools[{functionDeclarations:[{name, description, parameters}]}].auto all_tools = detail::effective_tools_enabled(tools_enabled_)? mcp::McpService::instance().get_all_tools(detail::apply_request_policy(tool_filter_)): std::vector<mcp::UnifiedTool>{};@@ -172,7 +154,7 @@ QJsonObject LlmService::build_gemini_request(const QString& user_message,QJsonObject LlmService::build_fincept_request(const QString& user_message,const std::vector<ConversationMessage>& history, bool with_tools) {- // Fincept /research/chat uses the OpenAI messages array format+ // /research/chat uses OpenAI messages format.QJsonArray messages;if (!system_prompt_.isEmpty())messages.append(QJsonObject{{"role", "system"}, {"content", system_prompt_}});@@ -182,11 +164,11 @@ QJsonObject LlmService::build_fincept_request(const QString& user_message,QJsonObject req;req["messages"] = messages;- // Pass model if set to a real model name (not the legacy placeholder)+ // Skip the legacy "fincept-llm" placeholder.if (!model_.isEmpty() && model_ != "fincept-llm")req["model"] = model_;- Q_UNUSED(with_tools) // Fincept /research/chat does not support tools yet+ Q_UNUSED(with_tools) // /research/chat does not support tools yet.return req;}diff --git a/fincept-qt/src/ai_chat/LlmService.cpp b/fincept-qt/src/ai_chat/LlmService.cppindex 8d9542ed7..c0bc02dc2 100644--- a/fincept-qt/src/ai_chat/LlmService.cpp+++ b/fincept-qt/src/ai_chat/LlmService.cpp@@ -9,6 +9,7 @@#include "ai_chat/LlmContentExtractors.h"#include "ai_chat/LlmRequestPolicy.h"#include "ai_chat/ModelCatalog.h"+#include "auth/AuthManager.h"#include "core/logging/Logger.h"#include "core/config/AppConfig.h"@@ -63,9 +64,27 @@ void LlmService::reload_config() {}void LlmService::ensure_config() const {- // Called with mutex_ held- if (config_loaded_)+ // Called with mutex_ held.+ //+ // Fincept credentials are refreshed on every call regardless of cache+ // state — the cache is a one-shot for everything else (tool-RAG hint+ // generation walks the entire MCP registry), but credentials track the+ // auth lifecycle. The user can authenticate AFTER the first+ // ensure_config() ran (e.g. AI chat opened before login completes), and+ // a stale cached empty key would 401 every subsequent request.+ if (config_loaded_) {+ if (provider_ == "fincept") {+ const auto& sess = fincept::auth::AuthManager::instance().session();+ if (!sess.api_key.isEmpty()) {+ api_key_ = sess.api_key;+ } else {+ auto stored = SettingsRepository::instance().get("fincept_api_key");+ if (stored.is_ok() && !stored.value().isEmpty())+ api_key_ = stored.value();+ }+ }return;+ }provider_ = model_ = api_key_ = base_url_ = system_prompt_ = {};temperature_ = 0.7;@@ -108,11 +127,19 @@ void LlmService::ensure_config() const {LOG_INFO(TAG, "No LLM provider configured — using Fincept default");}- // Fincept always resolves API key from session (never stored in llm_configs)+ // Fincept always resolves API key from the authenticated session, never+ // from llm_configs. Prefer AuthManager's in-memory session (authoritative+ // and live); fall back to SettingsRepository("fincept_api_key") which+ // AuthManager writes during auto_configure_fincept_llm (legacy path).if (provider_ == "fincept") {- auto stored_key = SettingsRepository::instance().get("fincept_api_key");- if (stored_key.is_ok() && !stored_key.value().isEmpty())- api_key_ = stored_key.value();+ const auto& sess = fincept::auth::AuthManager::instance().session();+ if (!sess.api_key.isEmpty()) {+ api_key_ = sess.api_key;+ } else {+ auto stored_key = SettingsRepository::instance().get("fincept_api_key");+ if (stored_key.is_ok() && !stored_key.value().isEmpty())+ api_key_ = stored_key.value();+ }}auto gs = LlmConfigRepository::instance().get_global_settings();@@ -382,12 +409,16 @@ QMap<QString, QString> LlmService::get_headers() const {if (!api_key_.isEmpty())h["x-goog-api-key"] = api_key_;} else if (p == "fincept") {- // api_key_ already resolved from session by ensure_config()+ // api_key_ is refreshed from AuthManager on every ensure_config() call,+ // so it tracks the auth lifecycle even if it was empty when the cache+ // was first populated.if (!api_key_.isEmpty())h["X-API-Key"] = api_key_;- auto tok = SettingsRepository::instance().get("session_token");- if (tok.is_ok() && !tok.value().isEmpty())- h["X-Session-Token"] = tok.value();+ // session_token lives only in AuthManager (never written to+ // SettingsRepository) — read it live so it's always current.+ const auto& sess = fincept::auth::AuthManager::instance().session();+ if (!sess.session_token.isEmpty())+ h["X-Session-Token"] = sess.session_token;// Cloudflare requires a User-Agent headerh["User-Agent"] = "FinceptTerminal/4.0";} else {diff --git a/fincept-qt/src/ai_chat/LlmService.h b/fincept-qt/src/ai_chat/LlmService.hindex 477acc53e..a3a357889 100644--- a/fincept-qt/src/ai_chat/LlmService.h+++ b/fincept-qt/src/ai_chat/LlmService.h@@ -1,8 +1,5 @@#pragma once-// LlmService.h — Multi-provider LLM API client (Qt port)-// Supports OpenAI-compatible APIs (OpenAI, Groq, DeepSeek, OpenRouter, Ollama),-// Anthropic, Google Gemini, and Fincept's own endpoint.-// Streaming via QNetworkReply::readyRead + SSE parsing.+// Multi-provider LLM client (OpenAI-compatible, Anthropic, Gemini, Fincept). Streams via SSE.#include "core/result/Result.h"#include "mcp/McpTypes.h"@@ -22,8 +19,6 @@namespace fincept::ai_chat {-// ── Provider helpers ──────────────────────────────────────────────────────────-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" ||@@ -34,10 +29,8 @@ inline bool provider_requires_api_key(const QString& provider) {return provider != "ollama" && provider != "fincept";}-// ── Data types ────────────────────────────────────────────────────────────────-struct ConversationMessage {- QString role; // "system", "user", "assistant"+ QString role; // system | user | assistantQString content;};@@ -50,53 +43,33 @@ struct LlmResponse {bool success = false;};-// chunk_text, is_done+/// (chunk_text, is_done) — invoked on a background thread.using StreamCallback = std::function<void(const QString&, bool)>;-// ── LlmService ────────────────────────────────────────────────────────────────-class LlmService : public QObject {Q_OBJECTpublic:static LlmService& instance();- // Non-streaming (blocking — call from background thread via QtConcurrent::run)- // use_tools: when false, disables MCP tool execution for this request- // (use for the floating bubble to prevent unintended navigation)+ /// Blocking — call from a background thread (QtConcurrent::run).LlmResponse chat(const QString& user_message, const std::vector<ConversationMessage>& history,bool use_tools = true);- // Per-request tool policy. Replaces the legacy `bool use_tools` so callers- // can opt into the common middle ground (tools enabled but navigation- // tools hidden — used by the floating bubble so the model can still hit- // benign tools like add_to_watchlist without yanking the user out of- // their current screen).- //- // Values:- // All — every tool advertised (AI Chat tab default).- // NoNavigation — drop the `navigation` category (floating bubble).- // None — no tools attached at all (legacy use_tools=false).+ /// Per-request tool scope. NoNavigation lets the floating bubble keep benign tools+ /// without yanking the user away. None drops tools entirely.enum class ToolPolicy { All, NoNavigation, None };- // Streaming — launches background thread; on_chunk called on that thread.- // Emit finished_streaming(response) when done to get result on UI thread.+ /// Spawns a background thread. on_chunk runs on that thread; finished_streaming() lands on UI thread.void chat_streaming(const QString& user_message, const std::vector<ConversationMessage>& history,StreamCallback on_chunk, ToolPolicy policy = ToolPolicy::All);- // Back-compat overload — `use_tools=false` maps to ToolPolicy::None,- // `true` maps to ToolPolicy::All. Prefer the enum form for new callers.+ /// Back-compat: false→None, true→All. Prefer the enum overload.void chat_streaming(const QString& user_message, const std::vector<ConversationMessage>& history,StreamCallback on_chunk, bool use_tools);- // Reload config from DB (call after user changes LLM settings)+ /// Call after the user changes LLM settings.void reload_config();- // (Per-request ToolFilter setters removed — superseded by Tool RAG- // tool.list / Tier-0 advertisement model. The internal tool_filter_- // field stays default-constructed; an empty filter is the signal that- // tells McpService::format_tools_for_openai to engage Tier-0 mode.)-- // ── Active config accessors (AI Chat context) ─────────────────────────────QString active_provider() const;QString active_model() const;QString active_api_key() const;@@ -106,18 +79,14 @@ class LlmService : public QObject {bool tools_enabled() const;bool is_configured() const;- // ── Profile-aware resolution ──────────────────────────────────────────────- // Returns the resolved LLM profile for a given context.- // context_type: "ai_chat" | "agent" | "agent_default" |- // "team" | "team_default" | "team_coordinator"- // context_id: agent/team id, or empty for type-level queries.+ /// context_type ∈ {ai_chat, agent, agent_default, team, team_default, team_coordinator}.+ /// context_id is the agent/team id; empty for type-level queries.ResolvedLlmProfile resolve_profile(const QString& context_type, const QString& context_id = {}) const;- // Convenience: build a QJsonObject suitable for embedding in AgentService- // payloads (provider, model_id, api_key, base_url, temperature, max_tokens).+ /// JSON shape for embedding in AgentService payloads.static QJsonObject profile_to_json(const ResolvedLlmProfile& p);- // Fetch available models for a provider (async — emits models_fetched)+ /// Async — emits models_fetched.void fetch_models(const QString& provider, const QString& api_key, const QString& base_url = {});LlmService(const LlmService&) = delete;@@ -125,7 +94,7 @@ class LlmService : public QObject {signals:void finished_streaming(LlmResponse response);- void config_changed(); // emitted after reload_config() — UI can react+ void config_changed();void models_fetched(const QString& provider, const QStringList& models, const QString& error);private:@@ -133,7 +102,7 @@ class LlmService : public QObject {mutable QMutex mutex_;- // Active config (reloaded lazily — all mutable so ensure_config() can be called from const accessors)+ // Lazily reloaded; mutable so const accessors can call ensure_config().mutable QString provider_;mutable QString api_key_;mutable QString base_url_;@@ -144,13 +113,15 @@ class LlmService : public QObject {mutable bool tools_enabled_ = true;mutable bool config_loaded_ = false;- // Phase 6 wiring: scopes the tool catalogue per-request. Empty = full- // catalogue. Read inside the build_*_request paths under mutex_.+ // Empty filter = full catalogue. Read in build_*_request under mutex_.mcp::ToolFilter tool_filter_;+ // Lives on main thread — fetch_models() runs the reply on the GUI event loop.+ // Don't move to a worker thread: QNAM's DNS/TLS resolvers expect a Qt-managed thread.+ QNetworkAccessManager* models_nam_ = nullptr;+void ensure_config() const;- // Request builders → QJsonObjectQJsonObject build_openai_request(const QString& user_message, const std::vector<ConversationMessage>& history,bool stream, bool with_tools = true);QJsonObject build_anthropic_request(const QString& user_message, const std::vector<ConversationMessage>& history,@@ -162,41 +133,30 @@ class LlmService : public QObject {QString get_endpoint_url() const;QMap<QString, QString> get_headers() const;- /// Resolve the max output tokens for a request. Order:- /// 1. user-set max_tokens (max_tokens_ > 0) → use it, but clamp to- /// the model's published cap so we don't get a 400 from the API.- /// 2. model's published cap from ModelCatalog.- /// 3. conservative fallback (8192).- /// Called with mutex_ held.+ /// Resolution order: user max_tokens (clamped to model cap) → model cap → 8192. Called with mutex_ held.int resolved_max_tokens() const;- // Synchronous HTTP helpers (use QNetworkAccessManager + QEventLoop)- // Must be called from a background thread.+ // Sync HTTP helpers (QNAM + QEventLoop) — call from background thread only.LlmResponse do_request(const QString& user_message, const std::vector<ConversationMessage>& history);LlmResponse do_streaming_request(const QString& user_message, const std::vector<ConversationMessage>& history,StreamCallback on_chunk);- // Tool-call follow-up loop (OpenAI-compatible)LlmResponse do_tool_loop(QJsonArray loop_messages, const QString& url, const QMap<QString, QString>& headers);- // Detect and execute tool calls embedded as text/XML in the response content.- // Returns std::nullopt if no text-based tool calls were found.+ /// Returns nullopt if the content had no text/XML tool calls.std::optional<LlmResponse> try_extract_and_execute_text_tool_calls(const QString& content,const QString& user_message, const QString& url,const QMap<QString, QString>& headers);- // Models-list helpersstatic QString get_models_url(const QString& provider, const QString& api_key, const QString& base_url);static QMap<QString, QString> get_models_headers(const QString& provider, const QString& api_key);static QStringList parse_models_response(const QString& provider, const QByteArray& body);- // Parse SSE data line → extracted text chunkstatic QString parse_sse_chunk(const QString& data, const QString& provider);- // Parse token usage from response JSONstatic void parse_usage(LlmResponse& resp, const QJsonObject& rj, const QString& provider);- // Synchronous POST helper (blocks calling thread via QEventLoop)+ /// Blocks the calling thread via QEventLoop.struct HttpResult {bool success = false;int status = 0;@@ -207,11 +167,11 @@ class LlmService : public QObject {int timeout_ms = 120000);static HttpResult blocking_get(const QString& url, const QMap<QString, QString>& headers, int timeout_ms = 30000);- // QEventLoop-based HTTP for Cloudflare-protected endpoints (Fincept)+ /// QEventLoop-based path used for Cloudflare-protected Fincept endpoints.static HttpResult eventloop_request(const QString& method, const QString& url, const QByteArray& body,const QMap<QString, QString>& headers, int timeout_ms = 30000);- // Fincept async path: POST /research/llm/async → poll /research/llm/status/{id}+ /// POST /research/llm/async then poll /research/llm/status/{id}.LlmResponse fincept_async_request(const QString& user_message, const std::vector<ConversationMessage>& history);};diff --git a/fincept-qt/src/ai_chat/LlmToolLoop.cpp b/fincept-qt/src/ai_chat/LlmToolLoop.cppindex d5af834b8..722a81833 100644--- a/fincept-qt/src/ai_chat/LlmToolLoop.cpp+++ b/fincept-qt/src/ai_chat/LlmToolLoop.cpp@@ -1,11 +1,6 @@-// LlmToolLoop.cpp — tool-execution layer for LlmService.-//-// Two entry points:-// - do_tool_loop: structured OpenAI-compatible tool-call follow-up loop-// (handles up to 15 reasoning rounds with parallel tool execution).-// - try_extract_and_execute_text_tool_calls: detects XML/text tool calls-// emitted by models that don't support structured tool_calls (minimax,-// some OpenRouter models). Executes them and asks the LLM to summarise.+// Tool-execution layer for LlmService.+// do_tool_loop: structured OpenAI-style follow-up (15 rounds of parallel calls).+// try_extract_and_execute_text_tool_calls: XML/text fallback for models without structured tool_calls.#include "ai_chat/LlmService.h"@@ -24,22 +19,19 @@namespace fincept::ai_chat {-namespace { constexpr const char* TAG = "LlmService"; }+namespace { constexpr const char* kToolLoopTag = "LlmService"; }LlmResponse LlmService::do_tool_loop(QJsonArray loop_messages, const QString& url,const QMap<QString, QString>& headers) {LlmResponse resp;- // 15 rounds covers complex agentic workflows (multi-step research →- // template → fill → polish). Each round can contain many parallel- // tool calls so this isn't 15 tool calls — it's 15 reasoning steps.+ // 15 reasoning steps (each may issue many parallel tool calls).static constexpr int MAX_ROUNDS = 15;- LOG_INFO(TAG, QString("TOOL LOOP: starting (max %1 rounds, model=%2)").arg(MAX_ROUNDS).arg(model_));+ LOG_INFO(kToolLoopTag, QString("TOOL LOOP: starting (max %1 rounds, model=%2)").arg(MAX_ROUNDS).arg(model_));for (int round = 0; round < MAX_ROUNDS; ++round) {QJsonObject fu;fu["model"] = model_;fu["messages"] = loop_messages;- // Temperature intentionally omitted — provider default.fu["max_tokens"] = resolved_max_tokens();QJsonArray tools = mcp::McpService::instance().format_tools_for_openai(detail::apply_request_policy(tool_filter_));@@ -69,7 +61,6 @@ LlmResponse LlmService::do_tool_loop(QJsonArray loop_messages, const QString& urQJsonArray tcs = msg["tool_calls"].toArray();if (!tcs.isEmpty()) {- // Another roundloop_messages.append(msg);for (const auto& tc_val : tcs) {QJsonObject tc = tc_val.toObject();@@ -78,10 +69,10 @@ LlmResponse LlmService::do_tool_loop(QJsonArray loop_messages, const QString& urQJsonObject fa =QJsonDocument::fromJson(tc["function"].toObject()["arguments"].toString("{}").toUtf8()).object();- LOG_INFO(TAG, QString("TOOL LOOP r%1: executing %2 args=%3").arg(round).arg(fname,+ LOG_INFO(kToolLoopTag, QString("TOOL LOOP r%1: executing %2 args=%3").arg(round).arg(fname,QString::fromUtf8(QJsonDocument(fa).toJson(QJsonDocument::Compact)).left(200)));auto tr = mcp::McpService::instance().execute_openai_function(fname, fa);- LOG_INFO(TAG, QString("TOOL LOOP r%1: %2 -> %3 (msg=%4 err=%5)")+ LOG_INFO(kToolLoopTag, QString("TOOL LOOP r%1: %2 -> %3 (msg=%4 err=%5)").arg(round).arg(fname,tr.success ? "OK" : "FAIL", tr.message.left(120), tr.error.left(120)));loop_messages.append(QJsonObject{@@ -92,21 +83,17 @@ LlmResponse LlmService::do_tool_loop(QJsonArray loop_messages, const QString& urcontinue;}- // Final text responseresp.content = extract_openai_message_text(msg);parse_usage(resp, rj, provider_);resp.success = !resp.content.isEmpty();- LOG_INFO(TAG, QString("TOOL LOOP: finished after %1 round(s) — %2 chars of text")+ LOG_INFO(kToolLoopTag, QString("TOOL LOOP: finished after %1 round(s) — %2 chars of text").arg(round + 1).arg(resp.content.length()));return resp;}- // Max rounds exhausted. The user would see an empty bubble. Force one- // final non-tool turn so the model summarizes whatever it accomplished- // so the chat doesn't go silent.- LOG_WARN(TAG, "TOOL LOOP: exceeded max rounds — forcing summary turn (no tools)");+ // Force one tool-less summary turn so the user doesn't see an empty bubble.+ LOG_WARN(kToolLoopTag, "TOOL LOOP: exceeded max rounds — forcing summary turn (no tools)");{- // Append a synthetic system nudge instructing the model to wrap up.loop_messages.append(QJsonObject{{"role", "system"},{"content", "You have used your tool-call budget. Reply now with a final answer to the user "@@ -117,7 +104,7 @@ LlmResponse LlmService::do_tool_loop(QJsonArray loop_messages, const QString& urfu["model"] = model_;fu["messages"] = loop_messages;fu["max_tokens"] = resolved_max_tokens();- // Deliberately omit the tools field so the model is forced to produce text.+ // No tools field — forces a text response.auto http = blocking_post(url, fu, headers);if (http.success) {@@ -130,7 +117,7 @@ LlmResponse LlmService::do_tool_loop(QJsonArray loop_messages, const QString& urresp.content = extract_openai_message_text(msg);parse_usage(resp, rj, provider_);resp.success = !resp.content.isEmpty();- LOG_INFO(TAG, QString("TOOL LOOP: summary fallback produced %1 chars")+ LOG_INFO(kToolLoopTag, QString("TOOL LOOP: summary fallback produced %1 chars").arg(resp.content.length()));if (resp.success)return resp;@@ -142,32 +129,21 @@ LlmResponse LlmService::do_tool_loop(QJsonArray loop_messages, const QString& urreturn resp;}-// ============================================================================-// Text-based tool call extraction-// ============================================================================-// Models that don't support structured tool_calls (e.g. minimax, some-// OpenRouter models) may emit tool invocations as XML/text markup in their-// response. This method detects common patterns and executes the tools.-+/// Detect XML/text tool invocations from models without structured tool_calls.std::optional<LlmResponse> LlmService::try_extract_and_execute_text_tool_calls(const QString& content,const QString& user_message,const QString& url,const QMap<QString, QString>& headers) {- // ── Pattern 1: <tool_call>{"name":"...", "arguments":{...}}</tool_call>- // ── Pattern 2: <invoke name="..." args='{"key":"val"}'>- // ── Pattern 3: minimax:tool_call CONTENT /minimax:tool_call- // ── Pattern 4: ```tool_call\n{"name":"...", "arguments":{...}}\n```- // ── Pattern 5: function_name(arg1, arg2) style calls embedded in text-+ // Patterns tried in order: <tool_call>JSON</tool_call>, <invoke name="..."/>,+ // (ns:)tool_call ... /(ns:)tool_call, ```tool_call``` fenced blocks.struct TextToolCall {QString name;QJsonObject args;};std::vector<TextToolCall> calls;- LOG_INFO(TAG, "Checking for text-based tool calls in response (" + QString::number(content.length()) + " chars)");+ LOG_INFO(kToolLoopTag, "Checking for text-based tool calls in response (" + QString::number(content.length()) + " chars)");- // --- Pattern 1: XML <tool_call> blocks (without namespace prefix) ---{static const QRegularExpression rx("<tool_call>\\s*(\\{[\\s\\S]*?\\})\\s*</tool_call>",QRegularExpression::MultilineOption |@@ -190,7 +166,6 @@ std::optional<LlmResponse> LlmService::try_extract_and_execute_text_tool_calls(c}}- // --- Pattern 2: <invoke name="..."> with <parameter> children or JSON body ---if (calls.empty()) {static const QRegularExpression rx_invoke("<invoke\\s+name=\"([^\"]+)\"[^>]*>([\\s\\S]*?)</invoke>",QRegularExpression::MultilineOption |@@ -199,9 +174,9 @@ std::optional<LlmResponse> LlmService::try_extract_and_execute_text_tool_calls(cQRegularExpression::MultilineOption |QRegularExpression::DotMatchesEverythingOption);- LOG_INFO(TAG, "Pattern 2: invoke regex valid=" + QString(rx_invoke.isValid() ? "yes" : "no"));+ LOG_INFO(kToolLoopTag, "Pattern 2: invoke regex valid=" + QString(rx_invoke.isValid() ? "yes" : "no"));auto dbg_match = rx_invoke.match(content);- LOG_INFO(TAG, "Pattern 2: hasMatch=" + QString(dbg_match.hasMatch() ? "yes" : "no"));+ LOG_INFO(kToolLoopTag, "Pattern 2: hasMatch=" + QString(dbg_match.hasMatch() ? "yes" : "no"));auto it = rx_invoke.globalMatch(content);while (it.hasNext()) {@@ -210,7 +185,7 @@ std::optional<LlmResponse> LlmService::try_extract_and_execute_text_tool_calls(cQString body = m.captured(2).trimmed();QJsonObject args;- // Try parsing <parameter> children first+ // <parameter> children first.auto pit = rx_param.globalMatch(body);bool has_params = false;while (pit.hasNext()) {@@ -219,7 +194,6 @@ std::optional<LlmResponse> LlmService::try_extract_and_execute_text_tool_calls(cQString pval = pm.captured(2).trimmed();has_params = true;- // Try to parse value as JSON (for arrays/objects)auto pdoc = QJsonDocument::fromJson(pval.toUtf8());if (!pdoc.isNull()) {if (pdoc.isArray())@@ -233,7 +207,7 @@ std::optional<LlmResponse> LlmService::try_extract_and_execute_text_tool_calls(c}}- // Fallback: try body as JSON object (no <parameter> tags)+ // No <parameter> tags — try the body as a JSON object.if (!has_params && !body.isEmpty()) {auto jdoc = QJsonDocument::fromJson(body.toUtf8());if (jdoc.isObject())@@ -245,7 +219,6 @@ std::optional<LlmResponse> LlmService::try_extract_and_execute_text_tool_calls(c}}- // --- Pattern 3: minimax:tool_call ... /minimax:tool_call or similar ---if (calls.empty()) {static const QRegularExpression rx("(?:\\w+:)?tool_call\\s+([\\s\\S]*?)\\s*/(?:\\w+:)?tool_call",QRegularExpression::MultilineOption);@@ -254,7 +227,6 @@ std::optional<LlmResponse> LlmService::try_extract_and_execute_text_tool_calls(cauto m = it.next();QString body = m.captured(1).trimmed();- // Try as JSON firstauto doc = QJsonDocument::fromJson(body.toUtf8());if (doc.isObject()) {QJsonObject obj = doc.object();@@ -270,9 +242,7 @@ std::optional<LlmResponse> LlmService::try_extract_and_execute_text_tool_calls(c}}- // Not JSON — treat as raw SQL/command from the model.- // Look for an external tool that accepts a "query"/"sql"/"statement" param- // (the user's case: model emits raw SQL inside minimax:tool_call tags).+ // Not JSON — model emitted a raw query/SQL. Route to any external tool whose schema accepts query|sql|statement.auto all_tools = mcp::McpService::instance().get_all_tools();for (const auto& tool : all_tools) {if (tool.is_internal)@@ -295,7 +265,6 @@ std::optional<LlmResponse> LlmService::try_extract_and_execute_text_tool_calls(c}}- // --- Pattern 4: ```tool_call\n...\n``` code blocks ---if (calls.empty()) {static const QRegularExpression rx("```tool_call\\s*\\n([\\s\\S]*?)\\n\\s*```",QRegularExpression::MultilineOption);@@ -318,12 +287,11 @@ std::optional<LlmResponse> LlmService::try_extract_and_execute_text_tool_calls(cif (calls.empty())return std::nullopt;- LOG_INFO(TAG, QString("Detected %1 text-based tool call(s) in response").arg(calls.size()));+ LOG_INFO(kToolLoopTag, QString("Detected %1 text-based tool call(s) in response").arg(calls.size()));- // Execute each detected tool callQString tool_results;for (const auto& tc : calls) {- LOG_INFO(TAG, "Executing text-detected tool: " + tc.name);+ LOG_INFO(kToolLoopTag, "Executing text-detected tool: " + tc.name);auto tr = mcp::McpService::instance().execute_openai_function(tc.name, tc.args);QString result_content;@@ -343,7 +311,6 @@ std::optional<LlmResponse> LlmService::try_extract_and_execute_text_tool_calls(cif (tool_results.isEmpty())return std::nullopt;- // Build follow-up request asking the LLM to summarize the tool resultsLlmResponse resp;QString follow_prompt = "The user asked: \"" + user_message +"\"\n\n"@@ -359,11 +326,9 @@ std::optional<LlmResponse> LlmService::try_extract_and_execute_text_tool_calls(cfollow_body["model"] = model_;follow_body["messages"] = msgs;follow_body["max_tokens"] = resolved_max_tokens();- // Temperature intentionally omitted — Anthropic default.if (!system_prompt_.isEmpty())follow_body["system"] = system_prompt_;} else if (provider_ == "fincept") {- // /research/chat uses messages arrayQJsonArray msgs;if (!system_prompt_.isEmpty())msgs.append(QJsonObject{{"role", "system"}, {"content", system_prompt_}});@@ -372,21 +337,18 @@ std::optional<LlmResponse> LlmService::try_extract_and_execute_text_tool_calls(cif (!model_.isEmpty() && model_ != "fincept-llm")follow_body["model"] = model_;} else {- // OpenAI-compatibleQJsonArray msgs;if (!system_prompt_.isEmpty())msgs.append(QJsonObject{{"role", "system"}, {"content", system_prompt_}});msgs.append(QJsonObject{{"role", "user"}, {"content", follow_prompt}});follow_body["model"] = model_;follow_body["messages"] = msgs;- // Temperature intentionally omitted — provider default.follow_body["max_tokens"] = resolved_max_tokens();}- // No tools in follow-up to prevent infinite loop+ // Follow-up has no tools — prevents infinite loop.auto fu = blocking_post(url, follow_body, headers);if (!fu.success) {- // Even if follow-up fails, return the raw tool resultsresp.content = tool_results;resp.success = true;return resp;@@ -401,11 +363,10 @@ std::optional<LlmResponse> LlmService::try_extract_and_execute_text_tool_calls(cQJsonObject fu_rj = fu_doc.object();- // Extract text from follow-up response (provider-aware)if (provider_ == "anthropic") {resp.content = extract_anthropic_content_text(fu_rj["content"].toArray());} else if (provider_ == "fincept") {- // /research/chat: {"success":true,"data":{"choices":[{"message":{"content":"..."}}]}}+ // {"success":..., "data":{"choices":[...]}} or top-level shape.QJsonObject data = fu_rj.contains("data") ? fu_rj["data"].toObject() : fu_rj;QJsonArray fu_choices = data["choices"].toArray();if (!fu_choices.isEmpty())@@ -417,7 +378,7 @@ std::optional<LlmResponse> LlmService::try_extract_and_execute_text_tool_calls(c}if (resp.content.isEmpty())- resp.content = tool_results; // fallback to raw results+ resp.content = tool_results;resp.success = true;parse_usage(resp, fu_rj, provider_);diff --git a/fincept-qt/src/app/DockScreenRouter.cpp b/fincept-qt/src/app/DockScreenRouter.cppindex 04f80ea69..183551a2f 100644--- a/fincept-qt/src/app/DockScreenRouter.cpp+++ b/fincept-qt/src/app/DockScreenRouter.cpp@@ -280,7 +280,7 @@ void DockScreenRouter::navigate(const QString& id, bool exclusive) {// existing right-click "Float Panel" / "Tear off into new window"// entries also remain). The pre-Phase-4 hard-coded// "right-of-TL → below-TL → right-of-BL" cycle was a v1- // simplification; this is the cleaner Bloomberg-grade behaviour+ // simplification; this is the cleaner Fincept-grade behaviour// (everything tabs into centre by default; user splits explicitly).const auto opened = manager_->openedDockAreas();ads::CDockAreaWidget* target = nullptr;diff --git a/fincept-qt/src/app/InstanceLock.cpp b/fincept-qt/src/app/InstanceLock.cppnew file mode 100644index 000000000..d93876706--- /dev/null+++ b/fincept-qt/src/app/InstanceLock.cpp@@ -0,0 +1,179 @@+#include "app/InstanceLock.h"++#include "core/logging/Logger.h"++#include <QByteArray>+#include <QCryptographicHash>+#include <QDataStream>+#include <QJsonArray>+#include <QJsonDocument>+#include <QJsonObject>+#include <QJsonParseError>+#include <QLocalSocket>++namespace fincept {++namespace {+constexpr const char* kTag = "InstanceLock";++// 200 ms is enough for a hot kernel + same-host connect. Cold starts on a+// loaded box may need more, but if the connect actually times out we fall+// through to "no primary running" and become primary ourselves — degraded+// but not broken.+constexpr int kConnectTimeoutMs = 200;++// 1 second to flush our argv to the primary. Argv is tiny (<1 KiB normally)+// so this is generous; only matters on a hung primary.+constexpr int kSendTimeoutMs = 1000;++// Property name we stash the partial-frame length on, while waiting for the+// rest of the bytes on a slow connection.+constexpr const char* kPendingLenProp = "_pendingLen";++QByteArray serialise_args(const QStringList& args) {+ QJsonArray arr;+ for (const auto& a : args)+ arr.append(a);+ QJsonObject obj;+ obj["args"] = arr;+ return QJsonDocument(obj).toJson(QJsonDocument::Compact);+}++QStringList parse_args(const QByteArray& payload) {+ QJsonParseError err{};+ auto doc = QJsonDocument::fromJson(payload, &err);+ if (err.error != QJsonParseError::NoError || !doc.isObject()) {+ LOG_WARN(kTag, QString("Invalid IPC payload: %1").arg(err.errorString()));+ return {};+ }+ QStringList out;+ const auto arr = doc.object()["args"].toArray();+ out.reserve(arr.size());+ for (const auto& v : arr)+ out.append(v.toString());+ return out;+}++void write_framed(QLocalSocket* sock, const QByteArray& payload) {+ QByteArray block;+ {+ QDataStream out(&block, QIODevice::WriteOnly);+ out.setVersion(QDataStream::Qt_6_0);+ out << static_cast<quint32>(payload.size());+ }+ block.append(payload);+ sock->write(block);+}+} // namespace++QString InstanceLock::socket_name_for(const QString& key) {+ // SHA-1 of the key in hex, truncated to 16 chars. Stable across runs of+ // the same key, unique enough that two profile keys won't collide, and+ // short enough that even on macOS (where local-socket paths are subject+ // to OS-level length caps via $TMPDIR) we won't trip the cap.+ const auto hash = QCryptographicHash::hash(key.toUtf8(), QCryptographicHash::Sha1).toHex();+ return QStringLiteral("fincept-%1").arg(QString::fromLatin1(hash).left(16));+}++InstanceLock::InstanceLock(QObject* parent) : QObject(parent) {}++InstanceLock::~InstanceLock() {+ if (server_) {+ server_->close();+ // QLocalServer's destructor unlinks the socket file on POSIX. On+ // Windows the named pipe is reference-counted and goes away when+ // the last handle closes.+ }+}++InstanceLock::Status InstanceLock::acquire(const QString& key, const QStringList& args) {+ name_ = socket_name_for(key);++ // 1. Probe: is a primary already listening for this key?+ if (send_to_existing(name_, args)) {+ LOG_INFO(kTag, QString("Secondary handed args to primary at %1").arg(name_));+ return Status::Secondary;+ }++ // 2. Become primary. If listen() fails (most often: stale socket file+ // from a previously-crashed primary), wipe the address and retry.+ if (!try_listen(name_)) {+ LOG_WARN(kTag, QString("Initial listen failed on %1 (%2) — clearing stale socket")+ .arg(name_, server_ ? server_->errorString() : QStringLiteral("?")));+ QLocalServer::removeServer(name_);+ if (!try_listen(name_)) {+ LOG_ERROR(kTag, QString("Failed to bind socket %1 after retry: %2")+ .arg(name_, server_ ? server_->errorString() : QStringLiteral("?")));+ // Degrade gracefully: every launch becomes a primary, no IPC.+ // Better than refusing to start (the SingleApplication failure+ // mode that #234 reports).+ return Status::Primary;+ }+ }++ LOG_INFO(kTag, QString("Primary instance bound to %1").arg(name_));+ return Status::Primary;+}++bool InstanceLock::try_listen(const QString& name) {+ if (!server_) {+ server_ = new QLocalServer(this);+ // Per docs, WorldAccessOption is the right choice for cross-user-+ // session apps; for our case (single user, multi-instance) the+ // default is fine and slightly safer.+ connect(server_, &QLocalServer::newConnection, this, &InstanceLock::on_new_connection);+ }+ return server_->listen(name);+}++bool InstanceLock::send_to_existing(const QString& name, const QStringList& args) {+ QLocalSocket sock;+ sock.connectToServer(name);+ if (!sock.waitForConnected(kConnectTimeoutMs))+ return false; // No one listening, or timed out — caller becomes primary.++ write_framed(&sock, serialise_args(args));+ sock.waitForBytesWritten(kSendTimeoutMs);+ sock.disconnectFromServer();+ if (sock.state() != QLocalSocket::UnconnectedState)+ sock.waitForDisconnected(kSendTimeoutMs);+ return true;+}++void InstanceLock::on_new_connection() {+ while (auto* client = server_->nextPendingConnection()) {+ client->setParent(this);++ // Each client may send its frame across multiple readyRead emissions+ // on slow networks (rare for local sockets, but possible). Buffer the+ // length prefix on the socket itself via a property so the lambda+ // can resume mid-frame without per-client state outside the socket.+ connect(client, &QLocalSocket::readyRead, this, [this, client]() {+ QVariant pending = client->property(kPendingLenProp);+ quint32 len = pending.isValid() ? pending.toUInt() : 0;++ if (len == 0) {+ if (client->bytesAvailable() < static_cast<qint64>(sizeof(quint32)))+ return; // wait for at least the length prefix+ QDataStream in(client);+ in.setVersion(QDataStream::Qt_6_0);+ in >> len;+ client->setProperty(kPendingLenProp, len);+ }++ if (client->bytesAvailable() < len)+ return; // wait for the rest of the payload++ const QByteArray payload = client->read(len);+ client->setProperty(kPendingLenProp, QVariant{});++ const auto args = parse_args(payload);+ LOG_INFO(kTag, QString("Secondary connected: %1 args").arg(args.size()));+ emit message_received(args);+ });++ connect(client, &QLocalSocket::disconnected, client, &QLocalSocket::deleteLater);+ }+}++} // namespace finceptdiff --git a/fincept-qt/src/app/InstanceLock.h b/fincept-qt/src/app/InstanceLock.hnew file mode 100644index 000000000..81fcd55a3--- /dev/null+++ b/fincept-qt/src/app/InstanceLock.h@@ -0,0 +1,68 @@+#pragma once++// InstanceLock — single-instance enforcement + cross-instance IPC.+//+// Replaces the SingleApplication library, which used QSharedMemory ++// QSystemSemaphore. That combo leaks on macOS Qt 6.6+ (QTBUG-111855), causing+// the app to silently exit on Finder/`open` launch — see issues #234 and #252.+//+// Design: one QLocalServer per profile key. Filesystem-addressable (Unix+// socket on POSIX, named pipe on Windows), so stale locks from a crashed+// previous primary can be detected and removed — something the semaphore+// approach can't do portably. No path-length limits, no sandbox quirks, no+// per-platform IPC restrictions.+//+// Wire format: 4-byte big-endian length prefix, followed by a JSON object+// `{"args": [...]}` carrying the secondary's argv. Length-prefixing handles+// short reads on slow connections; JSON keeps the format extensible without+// breaking older builds.++#include <QLocalServer>+#include <QObject>+#include <QString>+#include <QStringList>++namespace fincept {++class InstanceLock : public QObject {+ Q_OBJECT+ public:+ enum class Status { Primary, Secondary };++ explicit InstanceLock(QObject* parent = nullptr);+ ~InstanceLock() override;++ /// Try to become the primary instance for `key`. If another primary is+ /// already running, send `args` to it and return Secondary — the caller+ /// should exit cleanly. Otherwise begin listening for secondaries and+ /// return Primary.+ ///+ /// Failure mode: if listen() fails twice (once normally, once after+ /// removing a stale socket), the call still returns Primary. Better to+ /// run as an unsynchronised primary than to refuse to start. Logged.+ Status acquire(const QString& key, const QStringList& args = {});++ /// Map an arbitrary key into a stable, length-bounded local-socket name.+ /// Static so tests can verify the mapping. Uses SHA-1 truncation for the+ /// uniqueness component — long enough to avoid collisions, short enough+ /// to fit inside macOS POSIX semaphore-style namespaces (the original+ /// bug at the heart of #252).+ static QString socket_name_for(const QString& key);++ signals:+ /// Emitted on the primary when a secondary connects and sends its argv.+ /// `args` is the literal argv vector the secondary passed to `acquire()`.+ void message_received(const QStringList& args);++ private slots:+ void on_new_connection();++ private:+ QLocalServer* server_ = nullptr;+ QString name_;++ bool try_listen(const QString& name);+ bool send_to_existing(const QString& name, const QStringList& args);+};++} // namespace finceptdiff --git a/fincept-qt/src/app/WindowFrame.h b/fincept-qt/src/app/WindowFrame.hindex 8ec7d86a2..65d479a51 100644--- a/fincept-qt/src/app/WindowFrame.h+++ b/fincept-qt/src/app/WindowFrame.h@@ -174,7 +174,7 @@ class WindowFrame : public QMainWindow {void toggle_debug_overlay();/// Phase 9: toggle the per-frame CommandBar (line-edit at the bottom).- /// Lazily constructed on first invocation. Bloomberg-style "just type"+ /// Lazily constructed on first invocation. Fincept-style "just type"/// surface that reads ActionRegistry and CommandParser.void toggle_command_bar();diff --git a/fincept-qt/src/app/main.cpp b/fincept-qt/src/app/main.cppindex e6c8781b8..a8f579afe 100644--- a/fincept-qt/src/app/main.cpp+++ b/fincept-qt/src/app/main.cpp@@ -80,7 +80,7 @@#include <memory>-#include <singleapplication.h>+#include "app/InstanceLock.h"#ifdef Q_OS_WIN# include <Windows.h>@@ -95,14 +95,15 @@#endif// Wire the two app-level lifecycle handlers that fire after the primary-// window exists: SingleApplication::receivedMessage (a re-launch of the exe-// asks us to open another WindowFrame) and QApplication::lastWindowClosed-// (surface the Launchpad instead of quitting; the Launchpad's own close-// handler quits explicitly). Called from both the post-setup-screen path-// and the no-setup path so the two branches stay in sync.-static void wire_app_lifecycle(SingleApplication& app) {- QObject::connect(&app, &SingleApplication::receivedMessage,- [](quint32 /*instanceId*/, QByteArray /*message*/) {+// window exists: InstanceLock::message_received (a re-launch of the exe+// asks us to open another WindowFrame — args ignored, the request itself is+// the trigger) and QApplication::lastWindowClosed (surface the Launchpad+// instead of quitting; the Launchpad's own close handler quits explicitly).+// Called from both the post-setup-screen path and the no-setup path so the+// two branches stay in sync.+static void wire_app_lifecycle(QApplication& app, fincept::InstanceLock& lock) {+ QObject::connect(&lock, &fincept::InstanceLock::message_received,+ [](const QStringList& /*args*/) {auto* w = new fincept::WindowFrame(fincept::WindowFrame::next_window_id());w->setAttribute(Qt::WA_DeleteOnClose);w->show();@@ -132,7 +133,7 @@ int main(int argc, char* argv[]) {// ── Parse --profile <name> from argv before Qt initialises ───────────────// This must happen first so that:// 1. AppPaths returns the correct per-profile directories- // 2. SingleApplication uses a profile-scoped IPC key so two different+ // 2. InstanceLock uses a profile-scoped IPC key so two different// profiles can run simultaneously as independent primary instances{for (int i = 1; i < argc - 1; ++i) {@@ -158,14 +159,19 @@ int main(int argc, char* argv[]) {// (Qt Charts, QOpenGLWidget) — prevents black rendering in floating windows.QApplication::setAttribute(Qt::AA_ShareOpenGLContexts);- // SingleApplication enforces one process per profile.+ // QApplication first — InstanceLock's QLocalServer needs an event loop+ // owner. Then the lock probes for an existing primary; if found, it+ // ships our argv to the primary (which opens a new WindowFrame in+ // response) and we exit cleanly.+ //+ // Why not SingleApplication? Its QSharedMemory + QSystemSemaphore lock+ // leaks on macOS Qt 6.6+ (QTBUG-111855), causing silent exits on Finder+ // launch. See InstanceLock.h for the fuller story (issues #234, #252).+ //// The instance key is scoped to the active profile name, so// "FinceptTerminal --profile work" and "FinceptTerminal --profile personal"- // are treated as two separate primary instances and run simultaneously.- // allowSecondary=true: secondary instances send "--new-window" and exit.- const QString profile_key = QString("FinceptTerminal-%1").arg(fincept::ProfileManager::instance().active());- SingleApplication app(argc, argv, /*allowSecondary=*/true, SingleApplication::Mode::User, 100,- profile_key.toUtf8());+ // run as two independent primaries.+ QApplication app(argc, argv);app.setApplicationName("FinceptTerminal");app.setOrganizationName("Fincept");#ifndef FINCEPT_VERSION_STRING@@ -181,15 +187,21 @@ int main(int argc, char* argv[]) {// explicit one in LaunchpadScreen::closeEvent.app.setQuitOnLastWindowClosed(false);- // ── Secondary instance: signal primary to open a new window, then exit ───- // The primary receives receivedMessage() and calls open_new_window().- if (app.isSecondary()) {+ // ── Single-instance lock + new-window IPC ────────────────────────────────+ const QString profile_key = QString("FinceptTerminal-%1").arg(fincept::ProfileManager::instance().active());+ fincept::InstanceLock instance_lock;+ const auto lock_status = instance_lock.acquire(profile_key, QCoreApplication::arguments());++ // ── Secondary instance: argv was already shipped to the primary. Exit. ──+ if (lock_status == fincept::InstanceLock::Status::Secondary) {#ifdef Q_OS_WIN- // Grant the primary process permission to bring its new window to the- // foreground — Windows blocks focus-steal without this.- AllowSetForegroundWindow(static_cast<DWORD>(app.primaryPid()));+ // Grant the primary process permission to bring its new window to+ // the foreground — Windows blocks focus-steal without this. Pre-+ // SingleApplication this used app.primaryPid(); without that we+ // call AllowSetForegroundWindow(ASFW_ANY) which whitelists the+ // whole foreground request from this process.+ AllowSetForegroundWindow(ASFW_ANY);#endif- app.sendMessage(QByteArray("--new-window"));return 0;}@@ -540,6 +552,7 @@ int main(int argc, char* argv[]) {fincept::register_migration_v022();fincept::register_migration_v023();fincept::register_migration_v024();+ fincept::register_migration_v025();// Open main databaseQString db_path = fincept::AppPaths::data() + "/fincept.db";@@ -691,7 +704,7 @@ int main(int argc, char* argv[]) {// The connection uses Qt::SingleShotConnection (Qt 6.0+) so the lambda// fires exactly once even if setup_complete is somehow emitted twice.QObject::connect(setup_screen, &fincept::screens::SetupScreen::setup_complete,- [&app, screen_guard]() {+ [&app, &instance_lock, screen_guard]() {if (!screen_guard)return; // already cleaned up — ignorescreen_guard->hide();@@ -742,7 +755,7 @@ int main(int argc, char* argv[]) {// Wire new-window handler + Launchpad surface now that the// primary window exists. Single source of truth — see// wire_app_lifecycle() at the top of this file.- wire_app_lifecycle(app);+ wire_app_lifecycle(app, instance_lock);if (!fincept::ai_chat::LlmService::instance().is_configured())LOG_WARN("App",@@ -806,7 +819,7 @@ int main(int argc, char* argv[]) {// Wire new-window handler + Launchpad surface — see wire_app_lifecycle()// at the top of this file for the contract.- wire_app_lifecycle(app);+ wire_app_lifecycle(app, instance_lock);// If requirements files changed (app update), sync packages in background// without blocking the user. Connect setup_complete so failures are loggeddiff --git a/fincept-qt/src/core/components/ComponentMeta.h b/fincept-qt/src/core/components/ComponentMeta.hindex 3c7e44a96..e009156d9 100644--- a/fincept-qt/src/core/components/ComponentMeta.h+++ b/fincept-qt/src/core/components/ComponentMeta.h@@ -6,13 +6,8 @@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.+/// One screen's catalogue entry. Loaded from resources/component_catalog.json.+/// `popularity` is filled live by ComponentCatalog from PopularityTracker, not stored on disk.struct ComponentMeta {QString id; // matches DockScreenRouter screen idQString title; // human-readable, e.g. "Equity Trading"diff --git a/fincept-qt/src/core/components/PopularityTracker.h b/fincept-qt/src/core/components/PopularityTracker.hindex 204ba00d2..35d3724e8 100644--- a/fincept-qt/src/core/components/PopularityTracker.h+++ b/fincept-qt/src/core/components/PopularityTracker.h@@ -5,32 +5,18 @@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.+/// Per-screen navigation counts driving Component Browser ordering.+/// Stored locally in QSettings under "component_usage/<id>"; monotonic, no decay.class PopularityTracker : public QObject {Q_OBJECTpublic:static PopularityTracker& instance();- /// Bump the use count for a screen id. Idempotent — safe to call from- /// any navigation path. No-op for empty id.+ /// 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:diff --git a/fincept-qt/src/core/keys/KeyActions.h b/fincept-qt/src/core/keys/KeyActions.hindex cedf73706..ffe7bbdfd 100644--- a/fincept-qt/src/core/keys/KeyActions.h+++ b/fincept-qt/src/core/keys/KeyActions.h@@ -1,36 +1,33 @@-// src/core/keys/KeyActions.h-#pragma once+#pragma oncenamespace fincept {enum class KeyAction {- // Global (WindowFrame)+ // GlobalRefresh,ToggleChat,FocusMode,Fullscreen,Screenshot,- // Navigation (CommandBar)+ // CommandBar navigationNavNext,NavPrev,NavAccept,NavEscape,- // News Screen+ // NewsNewsNext,NewsPrev,NewsOpen,NewsClose,- // Code Editor+ // Code editorRunCell,RunAndNext,RenameCell,- // Window / Panel Navigation (Phase 3)- // Focus a specific WindowFrame by its 1-based ordinal across open windows- // (Ctrl+1..9 by default). Ctrl+1 always targets window_id = 0.+ // Focus WindowFrame N (Ctrl+1..9; Ctrl+1 = window_id 0).FocusWindow1,FocusWindow2,FocusWindow3,@@ -41,18 +38,15 @@ enum class KeyAction {FocusWindow8,FocusWindow9,- // Cycle active dock widget inside the focused WindowFrame.CyclePanelsForward,CyclePanelsBack,- // Cycle focus between WindowFrame instances (Bloomberg PANEL key).CycleWindowsForward,CycleWindowsBack,- // Spawn a new WindowFrame, placed on the next available monitor.NewWindowNextMonitor,- // Move the current WindowFrame to monitor N (Ctrl+Shift+1..9).+ // Move WindowFrame to monitor N (Ctrl+Shift+1..9).MoveWindowToMonitor1,MoveWindowToMonitor2,MoveWindowToMonitor3,@@ -63,14 +57,10 @@ enum class KeyAction {MoveWindowToMonitor8,MoveWindowToMonitor9,- // Phase 6 — Component BrowserBrowseComponents,-- // 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.+ /// Manual lock — bypasses inactivity timer. Default Ctrl+L.LockNow,};diff --git a/fincept-qt/src/core/keys/KeyConfigManager.cpp b/fincept-qt/src/core/keys/KeyConfigManager.cppindex 9ca504207..c7236dc2c 100644--- a/fincept-qt/src/core/keys/KeyConfigManager.cpp+++ b/fincept-qt/src/core/keys/KeyConfigManager.cpp@@ -114,7 +114,7 @@ KeyConfigManager::KeyConfigManager() {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.+ // terminal / Fincept workflows. Users can rebind in Settings.defaults_[KeyAction::LockNow] = QKeySequence(Qt::CTRL | Qt::Key_L);// Create QActions with default sequencesdiff --git a/fincept-qt/src/core/panel/PanelMaterialiser.h b/fincept-qt/src/core/panel/PanelMaterialiser.hindex f95a18d21..d8a9986ad 100644--- a/fincept-qt/src/core/panel/PanelMaterialiser.h+++ b/fincept-qt/src/core/panel/PanelMaterialiser.h@@ -8,65 +8,28 @@namespace fincept {-/// Phase 8 / decision 9.3: staged panel-widget construction.-///-/// On layout load with many panels (50+ panels in a Bloomberg-style-/// workspace), materialising every panel's screen widget synchronously-/// freezes the UI for several seconds. This class spreads construction-/// across UI ticks so the user sees the foreground tab of each visible-/// frame appear immediately, then the rest fill in over the next ~200ms-/// without blocking.-///-/// Usage:-/// ```-/// PanelMaterialiser::instance().enqueue("watchlist",-/// [](){ DockScreenRouter::navigate("watchlist"); }, /*priority=*/0);-/// ```-///-/// Priorities (lower number = higher priority — runs sooner):-/// 0 — foreground tab on a visible frame (drained immediately)-/// 1 — non-foreground tabs on visible frames-/// 2 — anything on hidden / minimised frames-///-/// Each tick the materialiser drains up to `kMaxPerTick` items, picking-/// from the highest-priority bucket first.-///-/// Threading: UI-thread only (we're calling into Qt widgets directly).+/// Spreads panel-widget construction across UI ticks so layout loads don't freeze.+/// UI-thread only. Lower priority = runs sooner: 0=foreground/visible, 1=other tabs visible, 2=hidden frames.class PanelMaterialiser : public QObject {Q_OBJECTpublic:static PanelMaterialiser& instance();- /// Construction work to run later. The id is for logging/dedup;- /// the lambda is the actual constructor invocation (typically a call- /// into DockScreenRouter::navigate or materialize_screen).void enqueue(const QString& id, std::function<void()> work, int priority = 1);- /// Drain everything synchronously. Used by tests + by tear-off paths- /// that need a panel up *now*. Avoid on the UI thread during normal- /// operation — the whole point of this class is to NOT block.+ /// Synchronous drain. Used by tests and tear-off paths; avoid during normal UI flow.void drain_all_now();- /// Number of items still queued. Inspectable from the debug overlay.int pending_count() const;- /// Interval between materialisation ticks. Default 16ms (~60fps frame- /// budget). Tunable for tests.void set_tick_interval_ms(int ms);- /// How many items to drain per tick. Default 4. Lower = smoother UI- /// during a layout load, higher = layout finishes faster.void set_max_per_tick(int n);- /// Default max-per-tick. 4 keeps layout-load under ~16ms per frame- /// budget on the panel constructors that take 2-4ms each (the typical- /// case once factories are warm).static constexpr int kDefaultMaxPerTick = 4;static constexpr int kDefaultTickIntervalMs = 16;signals:- /// Fires after every drain — useful for the debug overlay's pending- /// count and for tests that want to wait until the queue is empty.void queue_drained();private:@@ -79,7 +42,6 @@ class PanelMaterialiser : public QObject {std::function<void()> work;};- // Three priority buckets. Drained in 0 → 1 → 2 order each tick.QQueue<Item> q_priority_0_;QQueue<Item> q_priority_1_;QQueue<Item> q_priority_2_;diff --git a/fincept-qt/src/core/report/ReportDocument.h b/fincept-qt/src/core/report/ReportDocument.hindex bee05b3aa..3568a6444 100644--- a/fincept-qt/src/core/report/ReportDocument.h+++ b/fincept-qt/src/core/report/ReportDocument.h@@ -72,8 +72,8 @@ inline ReportTheme dark_corporate() {"#e5e5e5", "#d97706", "#1e1e1e", "#cccccc", "#2a2a2a","#e5e5e5", "#111111", "#1a1a1a", "#808080", "#444444"};}-inline ReportTheme bloomberg() {- return {"Bloomberg Terminal",+inline ReportTheme fincept_terminal() {+ return {"Fincept Terminal","#ff8c00", "#ff8c00", "#0a0a0a", "#d4d4d4", "#1a0a00","#ff8c00", "#050505", "#0f0f0f", "#888888", "#333300"};}@@ -89,15 +89,15 @@ inline ReportTheme midnight_blue() {inline ReportTheme by_name(const QString& name) {if (name == "Dark Corporate")return dark_corporate();- if (name == "Bloomberg Terminal")- return bloomberg();+ if (name == "Fincept Terminal")+ return fincept_terminal();if (name == "Midnight Blue")return midnight_blue();return light_professional();}inline QStringList all_names() {- return {"Light Professional", "Dark Corporate", "Bloomberg Terminal", "Midnight Blue"};+ return {"Light Professional", "Dark Corporate", "Fincept Terminal", "Midnight Blue"};}} // namespace themesdiff --git a/fincept-qt/src/core/symbol/IGroupLinked.h b/fincept-qt/src/core/symbol/IGroupLinked.hindex fc68a2ff7..b7850fcfc 100644--- a/fincept-qt/src/core/symbol/IGroupLinked.h+++ b/fincept-qt/src/core/symbol/IGroupLinked.h@@ -6,21 +6,8 @@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.+/// Mix-in for screens that participate in symbol-group linking.+/// `set_group(None)` unlinks; subscribers must not re-publish in on_group_symbol_changed.class IGroupLinked {public:virtual ~IGroupLinked() = default;@@ -28,14 +15,9 @@ class IGroupLinked {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.+ /// Returns invalid SymbolRef if nothing selected.virtual SymbolRef current_symbol() const = 0;};diff --git a/fincept-qt/src/core/symbol/SymbolContext.h b/fincept-qt/src/core/symbol/SymbolContext.hindex cc8bfa43c..0b2ec4ecc 100644--- a/fincept-qt/src/core/symbol/SymbolContext.h+++ b/fincept-qt/src/core/symbol/SymbolContext.h@@ -9,18 +9,8 @@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 layout via to_json() /-/// from_json() — WorkspaceShell stores the blob in-/// `Workspace.link_state["symbol_context"]` so the user's group→symbol-/// assignments come back when the layout is reloaded.+/// Process-global registry of the active symbol per group. Persisted per layout via to/from_json.+/// `source` lets subscribers detect their own publishes and avoid feedback loops.class SymbolContext : public QObject {Q_OBJECTpublic:@@ -29,25 +19,18 @@ class SymbolContext : public QObject {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).+ /// No-op when ref matches existing value (signals suppressed).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.+ /// `source` may be nullptr. Subscribers that publish should compare `source == this` to skip re-publish.void group_symbol_changed(fincept::SymbolGroup g, fincept::SymbolRef ref, QObject* source);void active_symbol_changed(fincept::SymbolRef ref, QObject* source);diff --git a/fincept-qt/src/core/symbol/SymbolDragSource.h b/fincept-qt/src/core/symbol/SymbolDragSource.hindex ee45419fb..3c43f7597 100644--- a/fincept-qt/src/core/symbol/SymbolDragSource.h+++ b/fincept-qt/src/core/symbol/SymbolDragSource.h@@ -12,22 +12,11 @@ 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").+/// Start a QDrag carrying a SymbolRef. Caller must invoke past startDragDistance.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.+/// Drop handler for application/x-fincept-symbol. Caller must setAcceptDrops(true) on the target.class SymbolDropFilter : public QObject {Q_OBJECTpublic:@@ -42,21 +31,11 @@ class SymbolDropFilter : public QObject {Handler handler_;};-/// Convenience: install a drop filter on `target` and call `setAcceptDrops(true)`.-/// Returns the created filter (owned by `target` as parent).+/// Installs a drop filter on `target` and enables setAcceptDrops. Filter is parented to target.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.+/// Watches mouse events and starts a symbol drag past the drag threshold.+/// `provider` is invoked at drag-start (for widgets whose symbol changes); return invalid to cancel.class SymbolDragFilter : public QObject {Q_OBJECTpublic:@@ -65,8 +44,6 @@ class SymbolDragFilter : public QObject {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:@@ -80,7 +57,6 @@ class SymbolDragFilter : public QObject {bool pressed_ = false;};-/// Convenience: create+install a SymbolDragFilter on `source`.SymbolDragFilter* installDragSource(QWidget* source, SymbolDragFilter::RefProvider provider,SymbolGroup source_group = SymbolGroup::None);diff --git a/fincept-qt/src/core/symbol/SymbolGroup.h b/fincept-qt/src/core/symbol/SymbolGroup.hindex 1025f987f..c93ecc0d6 100644--- a/fincept-qt/src/core/symbol/SymbolGroup.h+++ b/fincept-qt/src/core/symbol/SymbolGroup.h@@ -6,20 +6,8 @@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–J = ten slots. Default colour palette: A=amber, B=cyan, C=magenta,-/// D=green, E=purple, F=red, G=yellow, H=orange, I=teal, J=pink. The first-/// seven (A–G) are enabled by default; H/I/J start disabled and the user-/// activates them from the badge menu. Names and colours per slot are-/// user-editable via SymbolGroupRegistry.-///-/// Stored as a single byte so it can live inside QSettings and JSON without-/// ambiguity. Do NOT renumber — persisted workspaces reference these literals.+/// Symbol link groups. None = unlinked; A–J are ten slots (A–G enabled by default).+/// Stored as a single byte for QSettings/JSON; do NOT renumber — persisted layouts reference these literals.enum class SymbolGroup : char {None = '\0',A = 'A',@@ -34,9 +22,7 @@ enum class SymbolGroup : char {J = 'J',};-/// Returns all concrete slots in order (A..J); excludes None. Includes-/// disabled slots — callers that only want active groups should consult-/// SymbolGroupRegistry::enabled_groups() instead.+/// All slots A..J (excludes None, includes disabled). For active-only, see SymbolGroupRegistry::enabled_groups().inline const QList<SymbolGroup>& all_symbol_groups() {static const QList<SymbolGroup> k = {SymbolGroup::A, SymbolGroup::B, SymbolGroup::C,SymbolGroup::D, SymbolGroup::E, SymbolGroup::F,@@ -66,10 +52,7 @@ inline SymbolGroup symbol_group_from_char(QChar c) {}}-/// Cycle forward through the static slot list, ignoring enabled/disabled-/// state. GroupBadge uses the enabled-aware variant in SymbolGroupRegistry-/// for click-cycle; this raw version exists for callers that need a stable-/// total ordering (tests, deterministic enumeration).+/// Cycle forward ignoring enabled/disabled — stable total ordering. For UI cycling, use SymbolGroupRegistry.inline SymbolGroup next_symbol_group(SymbolGroup g) {switch (g) {case SymbolGroup::None: return SymbolGroup::A;diff --git a/fincept-qt/src/core/symbol/SymbolRef.h b/fincept-qt/src/core/symbol/SymbolRef.hindex 0bad7ded8..59aeacc04 100644--- a/fincept-qt/src/core/symbol/SymbolRef.h+++ b/fincept-qt/src/core/symbol/SymbolRef.h@@ -5,15 +5,8 @@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.+/// Typed security reference used as SymbolContext payload.+/// `asset_class` slugs: equity|crypto|fx|future|bond|index|commodity|option. Empty = treat as equity.struct SymbolRef {QString symbol;QString asset_class;@@ -21,8 +14,7 @@ struct SymbolRef {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.+ /// "AAPL US Equity" / "BTCUSD Binance Crypto"; falls back to raw symbol.QString display() const {QString out = symbol;if (!exchange.isEmpty())@@ -57,9 +49,6 @@ struct SymbolRef {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};}diff --git a/fincept-qt/src/core/window/WindowRegistry.h b/fincept-qt/src/core/window/WindowRegistry.hindex fffc4f749..af9cce1d5 100644--- a/fincept-qt/src/core/window/WindowRegistry.h+++ b/fincept-qt/src/core/window/WindowRegistry.h@@ -7,22 +7,7 @@ namespace fincept {class WindowFrame;-/// Process-global registry of live WindowFrame instances.-///-/// `WindowCycler` previously combined two responsibilities:-/// 1. Storage of which windows exist (lifecycle).-/// 2. Keyboard policy for moving focus / spawning windows.-///-/// `WindowRegistry` owns (1). `WindowCycler` keeps (2) but delegates to the-/// registry for the actual window list. This split lets the command bar,-/// link manager, telemetry, status bar, and the lock controller all observe-/// window add/remove without coupling to keyboard handling.-///-/// WindowFrame constructor calls `register_frame(this)`; destructor calls-/// `unregister_frame(this)`. Storage is weak (QPointer) so a destroyed-/// window is silently skipped until its explicit unregister tidies the slot.-///-/// Threading: UI-thread only.+/// Process-global registry of live WindowFrames. UI-thread only; storage is QPointer (weak).class WindowRegistry : public QObject {Q_OBJECTpublic:@@ -31,39 +16,22 @@ class WindowRegistry : public QObject {void register_frame(WindowFrame* w);void unregister_frame(WindowFrame* w);- /// All live windows sorted by `window_id` ascending. Stable ordering for- /// keyboard shortcuts (`Ctrl+1` always = the lowest window_id).+ /// Sorted by window_id ascending — stable ordering for Ctrl+1..9.QList<WindowFrame*> frames() const;- /// Count of live windows.int frame_count() const;- /// True if every live window is currently in the minimised state. Used- /// by the lock-on-minimise policy: per multi-window Bloomberg semantics,- /// minimising one window is normal, but minimising the entire terminal- /// (every frame) is a "walked away from desk" event that should trigger- /// the inactivity lock.+ /// True only when every frame is minimised. Drives lock-on-minimise.bool all_minimised() const;- /// Frame ids in ascending order — used by SessionManager to persist- /// "which windows were open at shutdown" without callers needing to- /// touch each WindowFrame.QList<int> frame_ids() const;signals:- /// Emitted after register_frame() inserts a new entry. Subscribers can- /// hook into the new frame here (lock overlay injection in Phase 1b,- /// link manager subscription in Phase 7).void frame_added(WindowFrame* w);- /// Emitted before unregister_frame() removes the entry. The pointer is- /// still valid at signal emission time so subscribers can do final- /// cleanup (disconnect signals, snapshot state).+ /// Pointer is still valid at emission time — subscribers can do final cleanup.void frame_removing(WindowFrame* w);- /// Emitted whenever the result of `frames()` changes order or contents.- /// Coarse signal that simplifies consumers who don't care about- /// add-vs-remove specifics.void display_order_changed();private:diff --git a/fincept-qt/src/mcp/tools/ReportBuilderTools.cpp b/fincept-qt/src/mcp/tools/ReportBuilderTools.cppindex 6d8b636df..c2fbbb1eb 100644--- a/fincept-qt/src/mcp/tools/ReportBuilderTools.cpp+++ b/fincept-qt/src/mcp/tools/ReportBuilderTools.cpp@@ -419,7 +419,7 @@ std::vector<ToolDef> get_report_builder_tools() {ToolDef t;t.name = "report_set_theme";t.description = "Set the report color theme. Valid names: 'Light Professional', 'Dark Corporate', "- "'Bloomberg Terminal', 'Midnight Blue'.";+ "'Fincept Terminal', 'Midnight Blue'.";t.category = "report-builder";t.input_schema.properties =QJsonObject{{"name", QJsonObject{{"type", "string"}, {"description", "Theme name (case-sensitive)"}}}};diff --git a/fincept-qt/src/network/http/HttpClient.cpp b/fincept-qt/src/network/http/HttpClient.cppindex a82b5732b..b9759cd01 100644--- a/fincept-qt/src/network/http/HttpClient.cpp+++ b/fincept-qt/src/network/http/HttpClient.cpp@@ -23,11 +23,8 @@ QNetworkRequest HttpClient::build_request(const QString& url) const {req.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");req.setHeader(QNetworkRequest::UserAgentHeader, "FinceptTerminal/4.0");- // Only attach Fincept auth headers when the request targets the configured- // Fincept API host. Notification providers (Slack, Discord, Telegram,- // PagerDuty, user webhooks, …) and other services pass absolute third-party- // URLs through this same singleton — without this guard their servers would- // receive the user's X-API-Key and X-Session-Token in every call.+ // Only attach auth on same-host requests — third-party absolute URLs (Slack/Discord/webhooks)+ // share this singleton and must NOT receive X-API-Key / X-Session-Token.const bool same_host = is_relative || [&]() {const QUrl base(base_url_);return !base.host().isEmpty() && qurl.host().compare(base.host(), Qt::CaseInsensitive) == 0;@@ -44,8 +41,10 @@ QNetworkRequest HttpClient::build_request(const QString& url) const {return req;}-void HttpClient::handle_reply(QNetworkReply* reply, JsonCallback callback) {- connect(reply, &QNetworkReply::finished, this, [reply, cb = std::move(callback)]() {+void HttpClient::handle_reply(QNetworkReply* reply, JsonCallback callback, const QObject* context) {+ // Connect to caller-provided context so caller destruction auto-disconnects before the lambda fires.+ const QObject* receiver = context ? context : static_cast<const QObject*>(this);+ connect(reply, &QNetworkReply::finished, receiver, [reply, cb = std::move(callback)]() {reply->deleteLater();QByteArray data = reply->readAll();@@ -55,27 +54,23 @@ void HttpClient::handle_reply(QNetworkReply* reply, JsonCallback callback) {QJsonDocument doc = QJsonDocument::fromJson(data, &parse_err);if (reply->error() != QNetworkReply::NoError) {- // Strip query string to avoid logging embedded tokens/keysQUrl sanitized = reply->url();- sanitized.setQuery(QString{});+ sanitized.setQuery(QString{}); // strip query to keep tokens out of logsLOG_WARN("HTTP",QString("HTTP %1: %2 — %3").arg(status).arg(sanitized.toString()).arg(reply->errorString()));- // 401/403 must always be returned as err() so session expiry detection- // in AuthApi/SessionGuard works correctly — even when the body is valid JSON.+ // 401/403 must always be err() — session-expiry detection in AuthApi/SessionGuard depends on it.if (status == 401 || status == 403) {cb(Result<QJsonDocument>::err(QString("HTTP_%1").arg(status).toStdString()));return;}- // For other HTTP errors with a parseable JSON body, pass it through- // so callers (AuthApi) can extract server-side error messages.+ // Pass through parseable JSON bodies so AuthApi can extract server error messages.if (!data.isEmpty() && parse_err.error == QJsonParseError::NoError && doc.isObject()) {cb(Result<QJsonDocument>::ok(doc));return;}- // No parseable body — return sentinel so callers map status to fallback messagecb(Result<QJsonDocument>::err(QString("HTTP_%1").arg(status).toStdString()));return;}@@ -88,30 +83,30 @@ void HttpClient::handle_reply(QNetworkReply* reply, JsonCallback callback) {});}-void HttpClient::get(const QString& url, JsonCallback callback) {+void HttpClient::get(const QString& url, JsonCallback callback, const QObject* context) {LOG_DEBUG("HTTP", "GET " + url);auto* reply = nam_->get(build_request(url));- handle_reply(reply, std::move(callback));+ handle_reply(reply, std::move(callback), context);}-void HttpClient::post(const QString& url, const QJsonObject& body, JsonCallback callback) {+void HttpClient::post(const QString& url, const QJsonObject& body, JsonCallback callback, const QObject* context) {LOG_DEBUG("HTTP", "POST " + url);QJsonDocument doc(body);auto* reply = nam_->post(build_request(url), doc.toJson());- handle_reply(reply, std::move(callback));+ handle_reply(reply, std::move(callback), context);}-void HttpClient::put(const QString& url, const QJsonObject& body, JsonCallback callback) {+void HttpClient::put(const QString& url, const QJsonObject& body, JsonCallback callback, const QObject* context) {LOG_DEBUG("HTTP", "PUT " + url);QJsonDocument doc(body);auto* reply = nam_->put(build_request(url), doc.toJson());- handle_reply(reply, std::move(callback));+ handle_reply(reply, std::move(callback), context);}-void HttpClient::del(const QString& url, JsonCallback callback) {+void HttpClient::del(const QString& url, JsonCallback callback, const QObject* context) {LOG_DEBUG("HTTP", "DELETE " + url);auto* reply = nam_->deleteResource(build_request(url));- handle_reply(reply, std::move(callback));+ handle_reply(reply, std::move(callback), context);}void HttpClient::set_auth_header(const QString& api_key) {diff --git a/fincept-qt/src/network/http/HttpClient.h b/fincept-qt/src/network/http/HttpClient.hindex eb5a9cf29..84a16c7f2 100644--- a/fincept-qt/src/network/http/HttpClient.h+++ b/fincept-qt/src/network/http/HttpClient.h@@ -12,8 +12,7 @@namespace fincept {-/// Async HTTP client wrapping QNetworkAccessManager.-/// All responses delivered via callbacks on the Qt event loop.+/// Async HTTP client wrapping QNetworkAccessManager. Responses delivered on the Qt event loop.class HttpClient : public QObject {Q_OBJECTpublic:@@ -21,10 +20,12 @@ class HttpClient : public QObject {using JsonCallback = std::function<void(Result<QJsonDocument>)>;- void get(const QString& url, JsonCallback callback);- void post(const QString& url, const QJsonObject& body, JsonCallback callback);- void put(const QString& url, const QJsonObject& body, JsonCallback callback);- void del(const QString& url, JsonCallback callback);+ /// `context` scopes callback lifetime — pass `this` from anything that can outlive its reply.+ /// nullptr is safe only for objects whose lifetime equals the app's (singletons).+ void get(const QString& url, JsonCallback callback, const QObject* context = nullptr);+ void post(const QString& url, const QJsonObject& body, JsonCallback callback, const QObject* context = nullptr);+ void put(const QString& url, const QJsonObject& body, JsonCallback callback, const QObject* context = nullptr);+ void del(const QString& url, JsonCallback callback, const QObject* context = nullptr);void set_auth_header(const QString& api_key);void set_session_token(const QString& token);@@ -34,7 +35,7 @@ class HttpClient : public QObject {private:HttpClient();QNetworkRequest build_request(const QString& url) const;- void handle_reply(QNetworkReply* reply, JsonCallback callback);+ void handle_reply(QNetworkReply* reply, JsonCallback callback, const QObject* context);QNetworkAccessManager* nam_ = nullptr;QString base_url_;diff --git a/fincept-qt/src/python/PythonSetupManager.cpp b/fincept-qt/src/python/PythonSetupManager.cppindex 238c98a83..93ec4666e 100644--- a/fincept-qt/src/python/PythonSetupManager.cpp+++ b/fincept-qt/src/python/PythonSetupManager.cpp@@ -862,19 +862,26 @@ bool PythonSetupManager::install_packages(const QString& venv_name, const QStrin// Write the requirements hash as the marker — all packages installed.write_marker_hash(venv_name, compute_requirements_hash(requirements_file));emit_progress(step_key, 100, "All packages installed");- } else {- LOG_WARN("PythonSetup", QString("[%1] %2 package(s) failed: %3")- .arg(venv_name)- .arg(failed.size())- .arg(failed.join(", ").left(300)));- // Do NOT write the marker when any packages failed — the stale/absent- // marker ensures check_status() returns needs_setup=true on the next- // launch so the failed packages are retried automatically.- emit_progress(step_key, 100,- QString("Done — %1 package(s) failed (will retry on next launch)").arg(failed.size()));+ return true;}- return true;+ LOG_WARN("PythonSetup", QString("[%1] %2 package(s) failed: %3")+ .arg(venv_name)+ .arg(failed.size())+ .arg(failed.join(", ").left(300)));+ // Do NOT write the marker when any packages failed — the stale/absent+ // marker ensures check_status() returns needs_setup=true on the next+ // launch so the failed packages are retried automatically.+ emit_progress(step_key, 100,+ QString("Done — %1 package(s) failed (will retry on next launch)").arg(failed.size()),+ /*is_error=*/true);+ // Returning false here prevents run_setup() from writing the .setup_complete+ // sentinel. Without this, the sentinel would be written even though one or+ // more packages are missing, and the user would be stuck looping on the+ // setup screen forever (every launch detects the absent marker, every+ // re-run hits the same package failure, every successful-looking finish+ // re-writes the sentinel without writing the marker).+ return false;}// ─────────────────────────────────────────────────────────────────────────────diff --git a/fincept-qt/src/screens/crypto_center/CryptoCenterScreen.cpp b/fincept-qt/src/screens/crypto_center/CryptoCenterScreen.cppindex c5d05689a..71cf74ad2 100644--- a/fincept-qt/src/screens/crypto_center/CryptoCenterScreen.cpp+++ b/fincept-qt/src/screens/crypto_center/CryptoCenterScreen.cpp@@ -284,7 +284,7 @@ void CryptoCenterScreen::apply_theme() {" letter-spacing:1.5px; padding:0 16px; }""QPushButton#cryptoCenterPrimaryButton:hover { background:%4; color:%1; }"- // Tab bar — Bloomberg-flat with object-name styling (Phase 1.5 §1.5.3)+ // Tab bar — Fincept-flat with object-name styling (Phase 1.5 §1.5.3)"QTabWidget#cryptoCenterTabs::pane { background:%1; border:none;"" border-top:1px solid %3; }""QTabWidget#cryptoCenterTabs QTabBar::tab { background:%2; color:%8;"diff --git a/fincept-qt/src/screens/dashboard/MarketPulsePanel.cpp b/fincept-qt/src/screens/dashboard/MarketPulsePanel.cppindex c3d9a852c..1ff7b9c2c 100644--- a/fincept-qt/src/screens/dashboard/MarketPulsePanel.cpp+++ b/fincept-qt/src/screens/dashboard/MarketPulsePanel.cpp@@ -1,5 +1,6 @@#include "screens/dashboard/MarketPulsePanel.h"+#include "screens/dashboard/widgets/LoadingOverlay.h"#include "services/markets/MarketDataService.h"#include "ui/theme/Theme.h"#include "ui/theme/ThemeManager.h"@@ -120,6 +121,13 @@ MarketPulsePanel::MarketPulsePanel(QWidget* parent) : QWidget(parent) {scroll_area_->setWidget(content);vl->addWidget(scroll_area_, 1);+ // ── Loading overlay ──+ // Layered over the scroll area so the user sees an animated "LOADING X+ // / Y" while quotes for the breadth/movers/snapshot symbol union are+ // streaming in. Denominator is the unique union size, computed once.+ loading_overlay_ = new widgets::LoadingOverlay(scroll_area_);+ loading_overlay_->attach_to(scroll_area_);+// ── Timers ──hours_timer_ = new QTimer(this);@@ -940,6 +948,9 @@ void MarketPulsePanel::hub_subscribe_all() {for (const auto& s : kSnapshotSymbols)all_syms.insert(s);+ total_expected_symbols_ = all_syms.size();+ update_loading_progress();+for (const QString& sym : all_syms) {const QString topic = QStringLiteral("market:quote:") + sym;const bool in_breadth = kBreadthSymbols.contains(sym);@@ -962,11 +973,28 @@ void MarketPulsePanel::hub_subscribe_all() {snapshot_cache_.insert(sym, q);rebuild_snapshot_from_cache();}+ update_loading_progress();});}hub_active_ = true;}+void MarketPulsePanel::update_loading_progress() {+ if (!loading_overlay_)+ return;+ // Numerator = unique symbols received across the three caches. Each+ // cache only holds its own subset, but a symbol can be in more than+ // one — union via QSet to avoid double-counting.+ QSet<QString> seen;+ for (auto it = breadth_cache_.constBegin(); it != breadth_cache_.constEnd(); ++it)+ seen.insert(it.key());+ for (auto it = movers_cache_.constBegin(); it != movers_cache_.constEnd(); ++it)+ seen.insert(it.key());+ for (auto it = snapshot_cache_.constBegin(); it != snapshot_cache_.constEnd(); ++it)+ seen.insert(it.key());+ loading_overlay_->set_progress(seen.size(), total_expected_symbols_);+}+void MarketPulsePanel::hub_unsubscribe_all() {if (!hub_active_)return;diff --git a/fincept-qt/src/screens/dashboard/MarketPulsePanel.h b/fincept-qt/src/screens/dashboard/MarketPulsePanel.hindex 6f62993ff..4a37d3807 100644--- a/fincept-qt/src/screens/dashboard/MarketPulsePanel.h+++ b/fincept-qt/src/screens/dashboard/MarketPulsePanel.h@@ -4,12 +4,17 @@#include <QHash>#include <QLabel>#include <QScrollArea>+#include <QSet>#include <QTimer>#include <QVBoxLayout>#include <QWidget>class QFrame;+namespace fincept::screens::widgets {+class LoadingOverlay;+}+namespace fincept::screens {/// Right-side market pulse panel — Fear/Greed, breadth, top movers, global@@ -139,6 +144,13 @@ class MarketPulsePanel : public QWidget {QHash<QString, services::QuoteData> snapshot_cache_;bool hub_active_ = false;QTimer* hours_timer_ = nullptr;++ // Loading overlay shown over the scroll area while the union of the+ // breadth/movers/snapshot caches fills up. The denominator is the+ // unique-symbol union size (~70), updated every time a cache changes.+ int total_expected_symbols_ = 0;+ widgets::LoadingOverlay* loading_overlay_ = nullptr;+ void update_loading_progress();};} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/dashboard/canvas/WidgetRegistry.cpp b/fincept-qt/src/screens/dashboard/canvas/WidgetRegistry.cppindex d9668a1c9..a1e44391f 100644--- a/fincept-qt/src/screens/dashboard/canvas/WidgetRegistry.cpp+++ b/fincept-qt/src/screens/dashboard/canvas/WidgetRegistry.cpp@@ -125,7 +125,7 @@ WidgetRegistry::WidgetRegistry() {// ── Tools ────────────────────────────────────────────────────────────────register_widget({"video_player", "Live TV / Streams", "Tools",- "Financial TV — Bloomberg, CNBC, Reuters and custom streams", 4, 5, 3, 4,+ "Financial TV — major networks and custom streams", 4, 5, 3, 4,[](const QJsonObject&) { return widgets::create_video_player_widget(); }});register_widget({"recent_files", "Recent Files", "Tools",diff --git a/fincept-qt/src/screens/dashboard/widgets/BaseWidget.cpp b/fincept-qt/src/screens/dashboard/widgets/BaseWidget.cppindex dbb2e5a1d..65169adfc 100644--- a/fincept-qt/src/screens/dashboard/widgets/BaseWidget.cpp+++ b/fincept-qt/src/screens/dashboard/widgets/BaseWidget.cpp@@ -1,5 +1,6 @@#include "screens/dashboard/widgets/BaseWidget.h"+#include "screens/dashboard/widgets/LoadingOverlay.h"#include "ui/theme/Theme.h"#include "ui/theme/ThemeManager.h"@@ -126,6 +127,12 @@ BaseWidget::BaseWidget(const QString& title, QWidget* parent, const QString& acccontent_layout_->setSpacing(0);vl->addWidget(content_, 1);++ // ── Loading overlay ──+ // Lives as a child of the content area so it covers exactly the data+ // region (not the title bar). Sized via an event filter on `content_`.+ loading_overlay_ = new LoadingOverlay(content_);+ loading_overlay_->attach_to(content_);}void BaseWidget::refresh_base_theme() {@@ -158,12 +165,35 @@ void BaseWidget::refresh_base_theme() {void BaseWidget::set_loading(bool loading) {loading_label_->setVisible(loading);loading_label_->setText(loading ? "LOADING..." : "");+ if (!loading_overlay_)+ return;+ if (loading)+ loading_overlay_->start_indeterminate();+ else+ loading_overlay_->finish();+}++void BaseWidget::set_loading_progress(int loaded, int expected) {+ if (!loading_overlay_)+ return;+ const bool active = (expected > 0) && (loaded < expected);+ loading_label_->setVisible(active);+ loading_label_->setText(active ? QStringLiteral("LOADING...") : QString());+ loading_overlay_->set_progress(loaded, expected);}void BaseWidget::set_error(const QString& error) {if (error.isEmpty())return;+ // Hide loading state — error overrides any in-flight progress.+ if (loading_overlay_)+ loading_overlay_->finish();+ if (loading_label_) {+ loading_label_->setVisible(false);+ loading_label_->setText(QString());+ }+// Clear content and show errorQLayoutItem* item;while ((item = content_layout_->takeAt(0)) != nullptr) {diff --git a/fincept-qt/src/screens/dashboard/widgets/BaseWidget.h b/fincept-qt/src/screens/dashboard/widgets/BaseWidget.hindex d46014e78..07b50c5ba 100644--- a/fincept-qt/src/screens/dashboard/widgets/BaseWidget.h+++ b/fincept-qt/src/screens/dashboard/widgets/BaseWidget.h@@ -11,6 +11,8 @@namespace fincept::screens::widgets {+class LoadingOverlay;+/// Reusable widget container — title bar with accent color, close/refresh/config buttons.////// Configurable widgets override `make_config_dialog(parent)` to return a@@ -28,6 +30,16 @@ class BaseWidget : public QFrame {QWidget* drag_handle() const { return title_bar_; }void set_loading(bool loading);++ /// Determinate-progress variant of `set_loading`. Shows an animated+ /// "LOADING X / Y ITEMS" overlay over the content area; widget+ /// subclasses call this from their data-arrival slot with the running+ /// (loaded, expected) counts. When `loaded >= expected` the overlay+ /// fades out automatically. If `expected <= 0`, falls back to the+ /// indeterminate "LOADING…" animation. The title-bar text indicator is+ /// also toggled in lockstep.+ void set_loading_progress(int loaded, int expected);+void set_error(const QString& error);void set_title(const QString& title);@@ -77,6 +89,7 @@ class BaseWidget : public QFrame {QVBoxLayout* content_layout_ = nullptr;QPushButton* refresh_btn_ = nullptr;QPushButton* config_btn_ = nullptr;+ LoadingOverlay* loading_overlay_ = nullptr;QString accent_color_;};diff --git a/fincept-qt/src/screens/dashboard/widgets/CryptoTickerWidget.cpp b/fincept-qt/src/screens/dashboard/widgets/CryptoTickerWidget.cppindex a52ad84a6..36e9e6111 100644--- a/fincept-qt/src/screens/dashboard/widgets/CryptoTickerWidget.cpp+++ b/fincept-qt/src/screens/dashboard/widgets/CryptoTickerWidget.cpp@@ -112,6 +112,8 @@ void CryptoTickerWidget::build_rows() {void CryptoTickerWidget::hub_resubscribe() {auto& hub = datahub::DataHub::instance();hub.unsubscribe(this);+ received_.clear();+ set_loading_progress(received_.size(), pairs_.size());for (const auto& pair : pairs_) {const QString topic =QStringLiteral("ws:") + exchange_ + QStringLiteral(":ticker:") + pair;@@ -153,7 +155,8 @@ void CryptoTickerWidget::on_ticker(const QString& pair, const fincept::trading::const QColor col = t.percentage >= 0 ? ui::colors::POSITIVE() : ui::colors::NEGATIVE();r.change->setStyleSheet(QString("color:%1;font-size:11px;font-weight:600;background:transparent;").arg(col.name()));- set_loading(false);+ received_.insert(pair);+ set_loading_progress(received_.size(), pairs_.size());}QDialog* CryptoTickerWidget::make_config_dialog(QWidget* parent) {diff --git a/fincept-qt/src/screens/dashboard/widgets/CryptoTickerWidget.h b/fincept-qt/src/screens/dashboard/widgets/CryptoTickerWidget.hindex 40797d201..35236a5de 100644--- a/fincept-qt/src/screens/dashboard/widgets/CryptoTickerWidget.h+++ b/fincept-qt/src/screens/dashboard/widgets/CryptoTickerWidget.h@@ -11,6 +11,7 @@#include "screens/dashboard/widgets/BaseWidget.h"#include <QHash>+#include <QSet>#include <QString>#include <QStringList>@@ -52,6 +53,7 @@ class CryptoTickerWidget : public BaseWidget {QString exchange_;QStringList pairs_;QHash<QString, Row> rows_;+ QSet<QString> received_; // pairs that have published at least oncebool hub_active_ = false;};diff --git a/fincept-qt/src/screens/dashboard/widgets/LoadingOverlay.cpp b/fincept-qt/src/screens/dashboard/widgets/LoadingOverlay.cppnew file mode 100644index 000000000..8acd2f279--- /dev/null+++ b/fincept-qt/src/screens/dashboard/widgets/LoadingOverlay.cpp@@ -0,0 +1,308 @@+#include "screens/dashboard/widgets/LoadingOverlay.h"++#include "ui/theme/Theme.h"+#include "ui/theme/ThemeManager.h"++#include <QEasingCurve>+#include <QEvent>+#include <QFont>+#include <QFontMetrics>+#include <QGraphicsOpacityEffect>+#include <QLinearGradient>+#include <QPaintEvent>+#include <QPainter>+#include <QPainterPath>+#include <QResizeEvent>++#include <algorithm>++namespace fincept::screens::widgets {++namespace {++constexpr int kShimmerPeriodMs = 1200;+constexpr int kFadeMs = 220;+constexpr int kProgressEaseMs = 380;++QColor with_alpha(const QString& css, int alpha) {+ QColor c(css);+ c.setAlpha(alpha);+ return c;+}++} // namespace++LoadingOverlay::LoadingOverlay(QWidget* parent) : QWidget(parent) {+ setAttribute(Qt::WA_TransparentForMouseEvents, true);+ setAttribute(Qt::WA_NoSystemBackground, true);+ setAttribute(Qt::WA_TranslucentBackground, true);+ setFocusPolicy(Qt::NoFocus);+ setVisible(false);++ opacity_effect_ = new QGraphicsOpacityEffect(this);+ opacity_effect_->setOpacity(0.0);+ setGraphicsEffect(opacity_effect_);++ shimmer_anim_ = new QPropertyAnimation(this, "shimmerPhase", this);+ shimmer_anim_->setDuration(kShimmerPeriodMs);+ shimmer_anim_->setStartValue(0.0);+ shimmer_anim_->setEndValue(1.0);+ shimmer_anim_->setLoopCount(-1);++ progress_anim_ = new QPropertyAnimation(this, "displayedProgress", this);+ progress_anim_->setDuration(kProgressEaseMs);+ progress_anim_->setEasingCurve(QEasingCurve::OutCubic);++ fade_anim_ = new QPropertyAnimation(opacity_effect_, "opacity", this);+ fade_anim_->setDuration(kFadeMs);+ connect(fade_anim_, &QPropertyAnimation::finished, this, [this]() {+ // If we faded out, actually hide so we stop drawing on top.+ if (opacity_effect_->opacity() <= 0.001) {+ setVisible(false);+ stop_shimmer();+ }+ });++ connect(&ui::ThemeManager::instance(), &ui::ThemeManager::theme_changed, this,+ [this](const ui::ThemeTokens&) { update(); });+}++void LoadingOverlay::attach_to(QWidget* target) {+ if (target_ == target)+ return;+ if (target_)+ target_->removeEventFilter(this);+ target_ = target;+ if (!target) {+ setParent(nullptr);+ return;+ }+ setParent(target);+ target->installEventFilter(this);+ sync_geometry();+ raise();+}++void LoadingOverlay::set_shimmer_phase(qreal v) {+ shimmer_phase_ = v;+ update();+}++void LoadingOverlay::set_displayed_progress(qreal v) {+ displayed_progress_ = v;+ update();+}++void LoadingOverlay::start_indeterminate() {+ indeterminate_ = true;+ loaded_ = 0;+ expected_ = 0;+ progress_anim_->stop();+ displayed_progress_ = 0.0;++ if (!active_) {+ active_ = true;+ sync_geometry();+ setVisible(true);+ raise();+ fade_in();+ }+ start_shimmer();+ update();+}++void LoadingOverlay::set_progress(int loaded, int expected) {+ if (expected <= 0) {+ start_indeterminate();+ return;+ }++ indeterminate_ = false;+ loaded_ = std::clamp(loaded, 0, expected);+ expected_ = expected;++ if (!active_ && loaded_ < expected_) {+ active_ = true;+ sync_geometry();+ setVisible(true);+ raise();+ fade_in();+ start_shimmer();+ }++ const qreal target = static_cast<qreal>(loaded_) / static_cast<qreal>(expected_);+ progress_anim_->stop();+ progress_anim_->setStartValue(displayed_progress_);+ progress_anim_->setEndValue(target);+ progress_anim_->start();++ if (loaded_ >= expected_)+ finish();+ else+ update();+}++void LoadingOverlay::finish() {+ if (!active_)+ return;+ active_ = false;+ fade_out_and_hide();+}++void LoadingOverlay::start_shimmer() {+ if (shimmer_anim_->state() != QAbstractAnimation::Running)+ shimmer_anim_->start();+}++void LoadingOverlay::stop_shimmer() {+ shimmer_anim_->stop();+}++void LoadingOverlay::fade_in() {+ fade_anim_->stop();+ fade_anim_->setStartValue(opacity_effect_->opacity());+ fade_anim_->setEndValue(1.0);+ fade_anim_->start();+}++void LoadingOverlay::fade_out_and_hide() {+ fade_anim_->stop();+ fade_anim_->setStartValue(opacity_effect_->opacity());+ fade_anim_->setEndValue(0.0);+ fade_anim_->start();+}++void LoadingOverlay::sync_geometry() {+ if (target_)+ setGeometry(target_->rect());+}++bool LoadingOverlay::eventFilter(QObject* obj, QEvent* e) {+ if (obj == target_.data()) {+ if (e->type() == QEvent::Resize || e->type() == QEvent::Show) {+ sync_geometry();+ if (active_)+ raise();+ }+ }+ return QWidget::eventFilter(obj, e);+}++void LoadingOverlay::paintEvent(QPaintEvent* /*e*/) {+ QPainter p(this);+ p.setRenderHint(QPainter::Antialiasing, true);+ p.setRenderHint(QPainter::TextAntialiasing, true);++ const QRect r = rect();+ if (r.isEmpty())+ return;++ // ── Backdrop ──+ // Mostly opaque so the underlying half-rendered widget doesn't bleed+ // through and look like a glitch — but tinted with the surface color so+ // the loading state still feels like part of the widget.+ p.fillRect(r, with_alpha(ui::colors::BG_SURFACE(), 235));++ // ── Skeleton bars ──+ // Three rows of varying widths simulate where content will appear. The+ // shimmer sweeps across these, not across the full widget background.+ const QColor skel_bg = with_alpha(ui::colors::BORDER_DIM(), 170);+ const QColor accent = QColor(ui::colors::AMBER());+ const QColor accent_dim = with_alpha(ui::colors::AMBER(), 70);++ const int margin_x = 12;+ const int bar_h = 8;+ const int row_gap = 10;+ const int center_y = r.center().y();+ const int progress_block_h = 56; // text + progress bar reserved+ const int top = std::max(r.top() + 12, center_y - progress_block_h / 2 - bar_h * 3 - row_gap * 2);++ struct SkelRow {+ qreal width_pct;+ };+ const SkelRow rows[] = {{1.0}, {0.85}, {0.62}};+ for (int i = 0; i < 3; ++i) {+ const int row_w = static_cast<int>((r.width() - 2 * margin_x) * rows[i].width_pct);+ const QRect row(margin_x, top + i * (bar_h + row_gap), row_w, bar_h);+ QPainterPath path;+ path.addRoundedRect(row, bar_h / 2.0, bar_h / 2.0);+ p.fillPath(path, skel_bg);++ // Shimmer — a soft moving highlight on each row, offset so they+ // don't all flash in lockstep.+ const qreal phase = std::fmod(shimmer_phase_ + i * 0.15, 1.0);+ const qreal sweep_w = row.width() * 0.35;+ const qreal sweep_x = row.left() - sweep_w + (row.width() + sweep_w) * phase;++ QLinearGradient grad(sweep_x, 0, sweep_x + sweep_w, 0);+ grad.setColorAt(0.0, QColor(0, 0, 0, 0));+ grad.setColorAt(0.5, accent_dim);+ grad.setColorAt(1.0, QColor(0, 0, 0, 0));+ p.save();+ p.setClipPath(path);+ p.fillRect(row.adjusted(-int(sweep_w), 0, int(sweep_w), 0), grad);+ p.restore();+ }++ // ── Status text + progress bar ──+ const int text_y = top + 3 * (bar_h + row_gap) + 8;+ QFont label_font;+ label_font.setFamily(ui::fonts::DATA_FAMILY);+ label_font.setPixelSize(11);+ label_font.setBold(true);+ label_font.setLetterSpacing(QFont::AbsoluteSpacing, 0.8);+ p.setFont(label_font);++ QString status_text;+ if (indeterminate_ || expected_ <= 0) {+ // Animate "LOADING" with a pulse on the trailing dots so the user+ // sees motion even before any item count is known.+ const int dots = static_cast<int>(shimmer_phase_ * 4) % 4;+ QString trail(dots, QChar('.'));+ status_text = QStringLiteral("LOADING%1").arg(trail);+ } else {+ // Display the *animated* count rather than the raw one — this is+ // why displayed_progress_ exists: a watchlist filling 8 of 8+ // symbols animates 0→1→2→…→8 instead of jumping.+ const int shown = static_cast<int>(std::round(displayed_progress_ * expected_));+ status_text = QStringLiteral("LOADING %1 / %2 ITEMS").arg(shown).arg(expected_);+ }++ p.setPen(QColor(ui::colors::TEXT_SECONDARY()));+ QFontMetrics fm(label_font);+ const int text_w = fm.horizontalAdvance(status_text);+ const int text_h = fm.height();+ p.drawText(QRect((r.width() - text_w) / 2, text_y, text_w, text_h), Qt::AlignCenter, status_text);++ // Progress bar — drawn underneath the text. In indeterminate mode it's+ // a moving block; in determinate mode it fills based on+ // displayed_progress_.+ const int bar_y = text_y + text_h + 6;+ const int bar_full_w = r.width() - 2 * margin_x;+ const int bar_track_h = 3;+ const QRect track(margin_x, bar_y, bar_full_w, bar_track_h);+ QPainterPath track_path;+ track_path.addRoundedRect(track, bar_track_h / 2.0, bar_track_h / 2.0);+ p.fillPath(track_path, with_alpha(ui::colors::BORDER_DIM(), 200));++ p.save();+ p.setClipPath(track_path);+ if (indeterminate_ || expected_ <= 0) {+ const qreal block_w = bar_full_w * 0.30;+ const qreal x = track.left() - block_w + (track.width() + block_w) * shimmer_phase_;+ QLinearGradient grad(x, 0, x + block_w, 0);+ grad.setColorAt(0.0, QColor(0, 0, 0, 0));+ grad.setColorAt(0.5, accent);+ grad.setColorAt(1.0, QColor(0, 0, 0, 0));+ p.fillRect(QRectF(x, track.top(), block_w, track.height()), grad);+ } else {+ const int fill_w = static_cast<int>(bar_full_w * displayed_progress_);+ QLinearGradient grad(track.left(), 0, track.left() + fill_w, 0);+ grad.setColorAt(0.0, accent_dim);+ grad.setColorAt(1.0, accent);+ p.fillRect(QRect(track.left(), track.top(), fill_w, track.height()), grad);+ }+ p.restore();+}++} // namespace fincept::screens::widgetsdiff --git a/fincept-qt/src/screens/dashboard/widgets/LoadingOverlay.h b/fincept-qt/src/screens/dashboard/widgets/LoadingOverlay.hnew file mode 100644index 000000000..f50cf8930--- /dev/null+++ b/fincept-qt/src/screens/dashboard/widgets/LoadingOverlay.h@@ -0,0 +1,87 @@+#pragma once++#include <QPointer>+#include <QPropertyAnimation>+#include <QWidget>++class QGraphicsOpacityEffect;++namespace fincept::screens::widgets {++/// Animated loading state shown on top of a widget's content area while data+/// streams in from the DataHub.+///+/// Two modes:+/// * Indeterminate — caller does not know the expected item count. The+/// overlay shows skeleton rows with a sweeping shimmer and a "LOADING…"+/// label. Use this when a widget receives its data in a single payload.+/// * Determinate — caller passes (loaded, expected). The overlay shows a+/// thin progress bar plus "LOADING X / Y ITEMS". When `loaded >=+/// expected`, the overlay fades out and hides itself. Use this for+/// widgets that fan out per-symbol / per-topic subscriptions where the+/// UI fills up incrementally.+///+/// The overlay reparents itself to a target widget (`attach_to`) and tracks+/// the target's geometry via an event filter so it always covers the+/// content area exactly. It draws its own background and content with+/// QPainter — no stylesheet on the overlay itself, so it composites cleanly+/// over whatever widgets the caller has placed underneath.+class LoadingOverlay : public QWidget {+ Q_OBJECT+ Q_PROPERTY(qreal shimmerPhase READ shimmer_phase WRITE set_shimmer_phase)+ Q_PROPERTY(qreal displayedProgress READ displayed_progress WRITE set_displayed_progress)++ public:+ explicit LoadingOverlay(QWidget* parent = nullptr);++ /// Reparent the overlay to `target` and resize-track it so the overlay+ /// always matches the target's geometry. Pass nullptr to detach.+ void attach_to(QWidget* target);++ /// Begin showing the overlay in indeterminate mode (no item count).+ /// Idempotent — safe to call repeatedly.+ void start_indeterminate();++ /// Set determinate progress. Switches the overlay into determinate mode+ /// on first call, and auto-hides when `loaded >= expected` and+ /// `expected > 0`. If `expected <= 0`, behaves like+ /// `start_indeterminate()`.+ void set_progress(int loaded, int expected);++ /// Hide the overlay (with fade-out) and stop animations.+ void finish();++ bool is_active() const { return active_; }++ qreal shimmer_phase() const { return shimmer_phase_; }+ void set_shimmer_phase(qreal v);+ qreal displayed_progress() const { return displayed_progress_; }+ void set_displayed_progress(qreal v);++ protected:+ void paintEvent(QPaintEvent* e) override;+ bool eventFilter(QObject* obj, QEvent* e) override;++ private:+ void start_shimmer();+ void stop_shimmer();+ void fade_in();+ void fade_out_and_hide();+ void sync_geometry();++ QPointer<QWidget> target_;+ bool active_ = false;+ bool indeterminate_ = true;+ int loaded_ = 0;+ int expected_ = 0;++ qreal shimmer_phase_ = 0.0; ///< 0..1 — drives the sweeping highlight+ qreal displayed_progress_ = 0.0; ///< 0..1 — eased toward loaded_/expected_++ QPropertyAnimation* shimmer_anim_ = nullptr;+ QPropertyAnimation* progress_anim_ = nullptr;+ QPropertyAnimation* fade_anim_ = nullptr;+ QGraphicsOpacityEffect* opacity_effect_ = nullptr;+};++} // namespace fincept::screens::widgetsdiff --git a/fincept-qt/src/screens/dashboard/widgets/MarketQuoteStripWidget.cpp b/fincept-qt/src/screens/dashboard/widgets/MarketQuoteStripWidget.cppindex 3983a3362..17d4b3658 100644--- a/fincept-qt/src/screens/dashboard/widgets/MarketQuoteStripWidget.cpp+++ b/fincept-qt/src/screens/dashboard/widgets/MarketQuoteStripWidget.cpp@@ -107,6 +107,10 @@ void MarketQuoteStripWidget::build_rows() {void MarketQuoteStripWidget::hub_resubscribe() {auto& hub = datahub::DataHub::instance();hub.unsubscribe(this);+ // Drop the cross-config received set so a re-subscribe after a config+ // change shows the loading overlay until each new symbol publishes once.+ received_.clear();+ set_loading_progress(received_.size(), symbols_.size());for (const auto& sym : symbols_) {const QString topic = QStringLiteral("market:quote:") + sym;hub.subscribe(this, topic, [this](const QVariant& v) {@@ -146,7 +150,8 @@ void MarketQuoteStripWidget::on_quote(const fincept::services::QuoteData& q) {const QColor col = q.change_pct >= 0 ? ui::colors::POSITIVE() : ui::colors::NEGATIVE();r.change->setStyleSheet(QString("color:%1;font-size:11px;font-weight:600;background:transparent;").arg(col.name()));- set_loading(false);+ received_.insert(q.symbol);+ set_loading_progress(received_.size(), symbols_.size());}QDialog* MarketQuoteStripWidget::make_config_dialog(QWidget* parent) {diff --git a/fincept-qt/src/screens/dashboard/widgets/MarketQuoteStripWidget.h b/fincept-qt/src/screens/dashboard/widgets/MarketQuoteStripWidget.hindex c02e6ebce..1df8be56e 100644--- a/fincept-qt/src/screens/dashboard/widgets/MarketQuoteStripWidget.h+++ b/fincept-qt/src/screens/dashboard/widgets/MarketQuoteStripWidget.h@@ -9,6 +9,7 @@#include "screens/dashboard/widgets/BaseWidget.h"#include <QHash>+#include <QSet>#include <QString>#include <QStringList>@@ -49,6 +50,7 @@ class MarketQuoteStripWidget : public BaseWidget {QStringList symbols_;QHash<QString, Row> rows_; // symbol → widgets+ QSet<QString> received_; // symbols that have published at least once — used to drive the loading overlaybool hub_active_ = false;};diff --git a/fincept-qt/src/screens/dashboard/widgets/MarketSentimentWidget.cpp b/fincept-qt/src/screens/dashboard/widgets/MarketSentimentWidget.cppindex 7ca94d35e..05fc5bc7a 100644--- a/fincept-qt/src/screens/dashboard/widgets/MarketSentimentWidget.cpp+++ b/fincept-qt/src/screens/dashboard/widgets/MarketSentimentWidget.cpp@@ -182,13 +182,14 @@ void MarketSentimentWidget::refresh_data() {void MarketSentimentWidget::hub_subscribe_all() {auto& hub = datahub::DataHub::instance();+ set_loading_progress(row_cache_.size(), kSentimentSymbols.size());for (const auto& sym : kSentimentSymbols) {const QString topic = QStringLiteral("market:quote:") + sym;hub.subscribe(this, topic, [this, sym](const QVariant& v) {if (!v.canConvert<services::QuoteData>())return;row_cache_.insert(sym, v.value<services::QuoteData>());- set_loading(false);+ set_loading_progress(row_cache_.size(), kSentimentSymbols.size());rebuild_from_cache();});}diff --git a/fincept-qt/src/screens/dashboard/widgets/PerformanceWidget.cpp b/fincept-qt/src/screens/dashboard/widgets/PerformanceWidget.cppindex b44ff263f..bed74082c 100644--- a/fincept-qt/src/screens/dashboard/widgets/PerformanceWidget.cpp+++ b/fincept-qt/src/screens/dashboard/widgets/PerformanceWidget.cpp@@ -92,13 +92,14 @@ void PerformanceWidget::refresh_data() {void PerformanceWidget::hub_subscribe_all() {auto& hub = datahub::DataHub::instance();+ set_loading_progress(row_cache_.size(), kPerfSymbols.size());for (const auto& sym : kPerfSymbols) {const QString topic = QStringLiteral("market:quote:") + sym;hub.subscribe(this, topic, [this, sym](const QVariant& v) {if (!v.canConvert<services::QuoteData>())return;row_cache_.insert(sym, v.value<services::QuoteData>());- set_loading(false);+ set_loading_progress(row_cache_.size(), kPerfSymbols.size());rebuild_from_cache();});}diff --git a/fincept-qt/src/screens/dashboard/widgets/QuoteTableWidget.cpp b/fincept-qt/src/screens/dashboard/widgets/QuoteTableWidget.cppindex 9a597ee6e..48602619c 100644--- a/fincept-qt/src/screens/dashboard/widgets/QuoteTableWidget.cpp+++ b/fincept-qt/src/screens/dashboard/widgets/QuoteTableWidget.cpp@@ -63,13 +63,14 @@ void QuoteTableWidget::refresh_data() {void QuoteTableWidget::hub_subscribe_all() {auto& hub = datahub::DataHub::instance();+ set_loading_progress(row_cache_.size(), symbols_.size());for (const auto& sym : symbols_) {const QString topic = QStringLiteral("market:quote:") + sym;hub.subscribe(this, topic, [this, sym](const QVariant& v) {if (!v.canConvert<services::QuoteData>())return;row_cache_.insert(sym, v.value<services::QuoteData>());- set_loading(false);+ set_loading_progress(row_cache_.size(), symbols_.size());render_from_cache();});}diff --git a/fincept-qt/src/screens/dashboard/widgets/RiskMetricsWidget.cpp b/fincept-qt/src/screens/dashboard/widgets/RiskMetricsWidget.cppindex 26932a3ba..209a92b5d 100644--- a/fincept-qt/src/screens/dashboard/widgets/RiskMetricsWidget.cpp+++ b/fincept-qt/src/screens/dashboard/widgets/RiskMetricsWidget.cpp@@ -207,13 +207,14 @@ void RiskMetricsWidget::refresh_data() {void RiskMetricsWidget::hub_subscribe_all() {auto& hub = datahub::DataHub::instance();+ set_loading_progress(row_cache_.size(), kRiskSymbols.size());for (const auto& sym : kRiskSymbols) {const QString topic = QStringLiteral("market:quote:") + sym;hub.subscribe(this, topic, [this, sym](const QVariant& v) {if (!v.canConvert<services::QuoteData>())return;row_cache_.insert(sym, v.value<services::QuoteData>());- set_loading(false);+ set_loading_progress(row_cache_.size(), kRiskSymbols.size());rebuild_from_cache();});}diff --git a/fincept-qt/src/screens/dashboard/widgets/ScreenerWidget.cpp b/fincept-qt/src/screens/dashboard/widgets/ScreenerWidget.cppindex 482c217ec..4e6179682 100644--- a/fincept-qt/src/screens/dashboard/widgets/ScreenerWidget.cpp+++ b/fincept-qt/src/screens/dashboard/widgets/ScreenerWidget.cpp@@ -143,13 +143,14 @@ void ScreenerWidget::refresh_data() {void ScreenerWidget::hub_subscribe_all() {auto& hub = datahub::DataHub::instance();+ set_loading_progress(row_cache_.size(), kScreenerSymbols.size());for (const auto& sym : kScreenerSymbols) {const QString topic = QStringLiteral("market:quote:") + sym;hub.subscribe(this, topic, [this, sym](const QVariant& v) {if (!v.canConvert<services::QuoteData>())return;row_cache_.insert(sym, v.value<services::QuoteData>());- set_loading(false);+ set_loading_progress(row_cache_.size(), kScreenerSymbols.size());rebuild_all_quotes();});}diff --git a/fincept-qt/src/screens/dashboard/widgets/SectorHeatmapWidget.cpp b/fincept-qt/src/screens/dashboard/widgets/SectorHeatmapWidget.cppindex 283ed40bb..a734ad958 100644--- a/fincept-qt/src/screens/dashboard/widgets/SectorHeatmapWidget.cpp+++ b/fincept-qt/src/screens/dashboard/widgets/SectorHeatmapWidget.cpp@@ -75,13 +75,15 @@ void SectorHeatmapWidget::refresh_data() {void SectorHeatmapWidget::hub_subscribe_all() {auto& hub = datahub::DataHub::instance();- for (const auto& sym : sector_symbols()) {+ const auto syms = sector_symbols();+ set_loading_progress(row_cache_.size(), syms.size());+ for (const auto& sym : syms) {const QString topic = QStringLiteral("market:quote:") + sym;- hub.subscribe(this, topic, [this, sym](const QVariant& v) {+ hub.subscribe(this, topic, [this, sym, total = syms.size()](const QVariant& v) {if (!v.canConvert<services::QuoteData>())return;row_cache_.insert(sym, v.value<services::QuoteData>());- set_loading(false);+ set_loading_progress(row_cache_.size(), total);rebuild_from_cache();});}diff --git a/fincept-qt/src/screens/dashboard/widgets/SparklineStripWidget.cpp b/fincept-qt/src/screens/dashboard/widgets/SparklineStripWidget.cppindex 04be9e146..71a5ede84 100644--- a/fincept-qt/src/screens/dashboard/widgets/SparklineStripWidget.cpp+++ b/fincept-qt/src/screens/dashboard/widgets/SparklineStripWidget.cpp@@ -147,6 +147,8 @@ void SparklineStripWidget::build_rows() {void SparklineStripWidget::hub_resubscribe() {auto& hub = datahub::DataHub::instance();hub.unsubscribe(this);+ received_.clear();+ set_loading_progress(received_.size(), symbols_.size());for (const auto& sym : symbols_) {const QString topic = QStringLiteral("market:sparkline:") + sym;const QString sym_copy = sym;@@ -182,7 +184,8 @@ void SparklineStripWidget::on_points(const QString& symbol, const QVector<doublereturn;it->spark->set_points(points);it->last->setText(QString::number(points.last(), 'f', 2));- set_loading(false);+ received_.insert(symbol);+ set_loading_progress(received_.size(), symbols_.size());}QDialog* SparklineStripWidget::make_config_dialog(QWidget* parent) {diff --git a/fincept-qt/src/screens/dashboard/widgets/SparklineStripWidget.h b/fincept-qt/src/screens/dashboard/widgets/SparklineStripWidget.hindex 901833de1..2ca8381fb 100644--- a/fincept-qt/src/screens/dashboard/widgets/SparklineStripWidget.h+++ b/fincept-qt/src/screens/dashboard/widgets/SparklineStripWidget.h@@ -7,6 +7,7 @@#include "screens/dashboard/widgets/BaseWidget.h"#include <QHash>+#include <QSet>#include <QString>#include <QStringList>#include <QVector>@@ -46,6 +47,7 @@ class SparklineStripWidget : public BaseWidget {QStringList symbols_;QHash<QString, Row> rows_;+ QSet<QString> received_; // symbols whose sparkline has rendered at least oncebool hub_active_ = false;};diff --git a/fincept-qt/src/screens/dashboard/widgets/TopMoversWidget.cpp b/fincept-qt/src/screens/dashboard/widgets/TopMoversWidget.cppindex 69fc70afd..82aa4899b 100644--- a/fincept-qt/src/screens/dashboard/widgets/TopMoversWidget.cpp+++ b/fincept-qt/src/screens/dashboard/widgets/TopMoversWidget.cpp@@ -73,13 +73,14 @@ void TopMoversWidget::refresh_data() {void TopMoversWidget::hub_subscribe_all() {auto& hub = datahub::DataHub::instance();+ set_loading_progress(row_cache_.size(), symbols_.size());for (const auto& sym : symbols_) {const QString topic = QStringLiteral("market:quote:") + sym;hub.subscribe(this, topic, [this, sym](const QVariant& v) {if (!v.canConvert<services::QuoteData>())return;row_cache_.insert(sym, v.value<services::QuoteData>());- set_loading(false);+ set_loading_progress(row_cache_.size(), symbols_.size());rebuild_from_cache();});}diff --git a/fincept-qt/src/screens/dashboard/widgets/WatchlistWidget.cpp b/fincept-qt/src/screens/dashboard/widgets/WatchlistWidget.cppindex 1b408de6f..ff14591c1 100644--- a/fincept-qt/src/screens/dashboard/widgets/WatchlistWidget.cpp+++ b/fincept-qt/src/screens/dashboard/widgets/WatchlistWidget.cpp@@ -106,13 +106,19 @@ void WatchlistWidget::hub_resubscribe() {auto& hub = datahub::DataHub::instance();// Drop old subscriptions wholesale — symbol set may have changed.hub.unsubscribe(this);+ // Kick off the determinate loading overlay — count is the live symbol+ // count, not a hardcoded constant, so adding/removing symbols via the+ // GO button updates the denominator correctly.+ set_loading_progress(row_cache_.size(), symbols_.size());for (const auto& sym : symbols_) {const QString topic = QStringLiteral("market:quote:") + sym;hub.subscribe(this, topic, [this, sym](const QVariant& v) {if (!v.canConvert<services::QuoteData>())return;row_cache_.insert(sym, v.value<services::QuoteData>());- set_loading(false);+ // Numerator = unique symbols delivered so far; the overlay+ // animates the count up and fades out when row_cache_ is full.+ set_loading_progress(row_cache_.size(), symbols_.size());render_from_cache();});}diff --git a/fincept-qt/src/screens/data_mapping/DataMappingScreen.cpp b/fincept-qt/src/screens/data_mapping/DataMappingScreen.cppindex 448b332e3..14650efde 100644--- a/fincept-qt/src/screens/data_mapping/DataMappingScreen.cpp+++ b/fincept-qt/src/screens/data_mapping/DataMappingScreen.cpp@@ -16,8 +16,6 @@#include <QUuid>#include <QVBoxLayout>-// ── Stylesheet ──────────────────────────────────────────────────────────────-namespace {using namespace fincept::ui;static const QString kStyle =@@ -140,7 +138,6 @@ namespace fincept::screens {using namespace fincept::ui;-// ── Schema definitions ──────────────────────────────────────────────────────struct SchemaField {QString name;@@ -254,7 +251,6 @@ static QList<SchemaInfo> build_schemas() {static QList<SchemaInfo> g_schemas = build_schemas();-// ── Template definitions ────────────────────────────────────────────────────struct FieldMapping {QString target;@@ -284,7 +280,7 @@ struct MappingTemplate {static QList<MappingTemplate> build_templates() {return {- // ── Free Public APIs (no auth) ─────────────────────────────────────+ // Free public APIs.{"coingecko_quote","CoinGecko Coin Price → QUOTE",@@ -430,7 +426,7 @@ static QList<MappingTemplate> build_templates() {{"trades", "$.result.XXBTZUSD[*][7]", "to_number", "0"},{"symbol", "", "", "XBTUSD"}}},- // ── API Key Required (Free Tier) ───────────────────────────────────+ // API key required (free tier).{"alphavantage_ohlcv","Alpha Vantage Intraday → OHLCV",@@ -525,7 +521,7 @@ static QList<MappingTemplate> build_templates() {{"changePercent", "$.data.BTC.quote.USD.percent_change_24h", "", "0"},{"timestamp", "$.data.BTC.quote.USD.last_updated", "", ""}}},- // ── Global Broker APIs (Auth Required) ─────────────────────────────+ // Global broker APIs.{"alpaca_ohlcv","Alpaca Bars → OHLCV",@@ -604,7 +600,7 @@ static QList<MappingTemplate> build_templates() {{"low", "$.quotes.quote.low", "", "0"},{"previousClose", "$.quotes.quote.prevclose", "", "0"}}},- // ── Macro / Economic Data ──────────────────────────────────────────+ // Macro / economic data.{"dbnomics_ohlcv","DBnomics Series → OHLCV",@@ -629,7 +625,6 @@ static QList<MappingTemplate> build_templates() {static QList<MappingTemplate> g_templates = build_templates();-// ── Constructor ─────────────────────────────────────────────────────────────DataMappingScreen::DataMappingScreen(QWidget* parent) : QWidget(parent) {setObjectName("dmScreen");@@ -638,7 +633,6 @@ DataMappingScreen::DataMappingScreen(QWidget* parent) : QWidget(parent) {LOG_INFO("DataMapping", "Screen constructed");}-// ── UI Setup ────────────────────────────────────────────────────────────────void DataMappingScreen::setup_ui() {auto* root = new QVBoxLayout(this);@@ -910,7 +904,6 @@ QWidget* DataMappingScreen::create_right_panel() {return panel;}-// ── Step panels ─────────────────────────────────────────────────────────────QWidget* DataMappingScreen::create_api_config_panel() {auto* panel = new QWidget(this);@@ -1261,7 +1254,6 @@ QWidget* DataMappingScreen::create_test_save_panel() {return panel;}-// ── View panels ─────────────────────────────────────────────────────────────QWidget* DataMappingScreen::create_list_view() {auto* scroll = new QScrollArea;@@ -1407,7 +1399,6 @@ QWidget* DataMappingScreen::create_template_view() {return outer;}-// ── Footer / Status ─────────────────────────────────────────────────────────QWidget* DataMappingScreen::create_nav_footer() {auto* bar = new QWidget(this);@@ -1654,11 +1645,11 @@ void DataMappingScreen::on_test_api() {body = doc.object();}if (method == "POST")- HttpClient::instance().post(url, body, callback);+ HttpClient::instance().post(url, body, callback, this);else- HttpClient::instance().put(url, body, callback);+ HttpClient::instance().put(url, body, callback, this);} else {- HttpClient::instance().get(url, callback);+ HttpClient::instance().get(url, callback, this);}}diff --git a/fincept-qt/src/screens/fno/FnoHeaderBar.cpp b/fincept-qt/src/screens/fno/FnoHeaderBar.cppindex cea11e4b2..712933d67 100644--- a/fincept-qt/src/screens/fno/FnoHeaderBar.cpp+++ b/fincept-qt/src/screens/fno/FnoHeaderBar.cpp@@ -28,7 +28,7 @@ QString fmt_compact(qint64 v) {return QLocale(QLocale::English).toString(v);}-QLabel* make_kv(QWidget* parent, QLabel*& value_out, const QString& key) {+QWidget* make_kv(QWidget* parent, QLabel*& value_out, const QString& key) {auto* wrap = new QWidget(parent);auto* lay = new QVBoxLayout(wrap);lay->setContentsMargins(0, 0, 0, 0);diff --git a/fincept-qt/src/screens/fno/FnoScreen.h b/fincept-qt/src/screens/fno/FnoScreen.hindex 8571cdc25..2231071ac 100644--- a/fincept-qt/src/screens/fno/FnoScreen.h+++ b/fincept-qt/src/screens/fno/FnoScreen.h@@ -59,7 +59,7 @@ class FnoScreen : public QWidget,private slots:void on_tab_clicked(int index);- private:+ public:enum SubTab : int {TabChain = 0,TabBuilder = 1,@@ -70,6 +70,7 @@ class FnoScreen : public QWidget,TabCount};+ private:void setup_ui();QWidget* build_tab_bar();QWidget* build_placeholder(const QString& tab_name, const QString& detail);diff --git a/fincept-qt/src/screens/launchpad/LaunchpadScreen.cpp b/fincept-qt/src/screens/launchpad/LaunchpadScreen.cppindex a576581e7..2019e3653 100644--- a/fincept-qt/src/screens/launchpad/LaunchpadScreen.cpp+++ b/fincept-qt/src/screens/launchpad/LaunchpadScreen.cpp@@ -215,6 +215,10 @@ void LaunchpadScreen::surface() {LOG_INFO(kLaunchpadTag, "Surfaced");}+bool LaunchpadScreen::eventFilter(QObject* obj, QEvent* event) {+ return QMainWindow::eventFilter(obj, event);+}+void LaunchpadScreen::closeEvent(QCloseEvent* event) {// Reaching closeEvent always means the OS sent a window-close (X button// / Alt-F4 / system menu). Programmatic dismissals from button handlersdiff --git a/fincept-qt/src/screens/ma_analytics/MAAdvancedPanel.cpp b/fincept-qt/src/screens/ma_analytics/MAAdvancedPanel.cppindex def1f4832..84b102bda 100644--- a/fincept-qt/src/screens/ma_analytics/MAAdvancedPanel.cpp+++ b/fincept-qt/src/screens/ma_analytics/MAAdvancedPanel.cpp@@ -3,6 +3,7 @@#include "screens/ma_analytics/MAModulePanel.h"+#include "services/ma_analytics/MAAnalyticsService.h"#include "ui/theme/Theme.h"#include <QComboBox>@@ -15,6 +16,8 @@#include <QVBoxLayout>#include <QWidget>+using namespace fincept::services::ma;+namespace fincept::screens {// ═══════════════════════════════════════════════════════════════════════════════diff --git a/fincept-qt/src/screens/ma_analytics/MAComparisonPanel.cpp b/fincept-qt/src/screens/ma_analytics/MAComparisonPanel.cppindex 5d1819e90..a1cf82388 100644--- a/fincept-qt/src/screens/ma_analytics/MAComparisonPanel.cpp+++ b/fincept-qt/src/screens/ma_analytics/MAComparisonPanel.cpp@@ -3,6 +3,7 @@#include "screens/ma_analytics/MAModulePanel.h"+#include "services/ma_analytics/MAAnalyticsService.h"#include "ui/theme/Theme.h"#include <QComboBox>@@ -15,6 +16,8 @@#include <QVBoxLayout>#include <QWidget>+using namespace fincept::services::ma;+namespace fincept::screens {// ═══════════════════════════════════════════════════════════════════════════════diff --git a/fincept-qt/src/screens/ma_analytics/MADealsPanel.cpp b/fincept-qt/src/screens/ma_analytics/MADealsPanel.cppindex fcad60792..50b59b959 100644--- a/fincept-qt/src/screens/ma_analytics/MADealsPanel.cpp+++ b/fincept-qt/src/screens/ma_analytics/MADealsPanel.cpp@@ -3,6 +3,7 @@#include "screens/ma_analytics/MAModulePanel.h"+#include "services/ma_analytics/MAAnalyticsService.h"#include "ui/theme/Theme.h"#include <QComboBox>@@ -15,6 +16,8 @@#include <QVBoxLayout>#include <QWidget>+using namespace fincept::services::ma;+namespace fincept::screens {diff --git a/fincept-qt/src/screens/ma_analytics/MAFairnessPanel.cpp b/fincept-qt/src/screens/ma_analytics/MAFairnessPanel.cppindex abe468a27..e4a29b82b 100644--- a/fincept-qt/src/screens/ma_analytics/MAFairnessPanel.cpp+++ b/fincept-qt/src/screens/ma_analytics/MAFairnessPanel.cpp@@ -3,6 +3,7 @@#include "screens/ma_analytics/MAModulePanel.h"+#include "services/ma_analytics/MAAnalyticsService.h"#include "ui/theme/Theme.h"#include <QComboBox>@@ -15,6 +16,8 @@#include <QVBoxLayout>#include <QWidget>+using namespace fincept::services::ma;+namespace fincept::screens {// ═══════════════════════════════════════════════════════════════════════════════diff --git a/fincept-qt/src/screens/ma_analytics/MAIndustryPanel.cpp b/fincept-qt/src/screens/ma_analytics/MAIndustryPanel.cppindex eddc7d1ce..900113fc9 100644--- a/fincept-qt/src/screens/ma_analytics/MAIndustryPanel.cpp+++ b/fincept-qt/src/screens/ma_analytics/MAIndustryPanel.cpp@@ -3,6 +3,7 @@#include "screens/ma_analytics/MAModulePanel.h"+#include "services/ma_analytics/MAAnalyticsService.h"#include "ui/theme/Theme.h"#include <QComboBox>@@ -15,6 +16,8 @@#include <QVBoxLayout>#include <QWidget>+using namespace fincept::services::ma;+namespace fincept::screens {// ═══════════════════════════════════════════════════════════════════════════════diff --git a/fincept-qt/src/screens/ma_analytics/MAMergerPanel.cpp b/fincept-qt/src/screens/ma_analytics/MAMergerPanel.cppindex 91d62a9e9..bd4e0154d 100644--- a/fincept-qt/src/screens/ma_analytics/MAMergerPanel.cpp+++ b/fincept-qt/src/screens/ma_analytics/MAMergerPanel.cpp@@ -3,6 +3,7 @@#include "screens/ma_analytics/MAModulePanel.h"+#include "services/ma_analytics/MAAnalyticsService.h"#include "ui/theme/Theme.h"#include <QComboBox>@@ -15,6 +16,8 @@#include <QVBoxLayout>#include <QWidget>+using namespace fincept::services::ma;+namespace fincept::screens {// ═══════════════════════════════════════════════════════════════════════════════diff --git a/fincept-qt/src/screens/ma_analytics/MAStartupPanel.cpp b/fincept-qt/src/screens/ma_analytics/MAStartupPanel.cppindex b40de0d8f..af9a5d557 100644--- a/fincept-qt/src/screens/ma_analytics/MAStartupPanel.cpp+++ b/fincept-qt/src/screens/ma_analytics/MAStartupPanel.cpp@@ -3,6 +3,7 @@#include "screens/ma_analytics/MAModulePanel.h"+#include "services/ma_analytics/MAAnalyticsService.h"#include "ui/theme/Theme.h"#include <QComboBox>@@ -15,6 +16,8 @@#include <QVBoxLayout>#include <QWidget>+using namespace fincept::services::ma;+namespace fincept::screens {// ═══════════════════════════════════════════════════════════════════════════════diff --git a/fincept-qt/src/screens/ma_analytics/MAValuationPanel.cpp b/fincept-qt/src/screens/ma_analytics/MAValuationPanel.cppindex a972d0396..e345c02d7 100644--- a/fincept-qt/src/screens/ma_analytics/MAValuationPanel.cpp+++ b/fincept-qt/src/screens/ma_analytics/MAValuationPanel.cpp@@ -4,6 +4,7 @@#include "screens/ma_analytics/MAModulePanel.h"+#include "services/ma_analytics/MAAnalyticsService.h"#include "ui/theme/Theme.h"#include <QComboBox>@@ -16,6 +17,8 @@#include <QVBoxLayout>#include <QWidget>+using namespace fincept::services::ma;+namespace fincept::screens {diff --git a/fincept-qt/src/screens/recovery/CrashRecoveryDialog.cpp b/fincept-qt/src/screens/recovery/CrashRecoveryDialog.cppindex 7a4ab1b9f..867b5eaa8 100644--- a/fincept-qt/src/screens/recovery/CrashRecoveryDialog.cpp+++ b/fincept-qt/src/screens/recovery/CrashRecoveryDialog.cpp@@ -8,18 +8,34 @@#include <QDateTime>#include <QHBoxLayout>+#include <QInputDialog>#include <QJsonDocument>#include <QJsonObject>#include <QJsonParseError>#include <QLabel>#include <QListWidget>#include <QListWidgetItem>+#include <QMessageBox>#include <QPushButton>#include <QVBoxLayout>namespace {constexpr const char* kRecoveryTag = "CrashRecovery";constexpr int kMaxListed = 5;++// Theme tokens — hardcoded for now because the dialog runs *before* any+// WindowFrame exists, so ui::ThemeManager may not be subscribable yet.+// Values match the project's "obsidian / amber" theme (see ui/theme/Theme.h).+constexpr const char* kBgBase = "#0a0a0a";+constexpr const char* kBgSurface = "#111111";+constexpr const char* kBgRaised = "#161616";+constexpr const char* kBorder = "#1f1f1f";+constexpr const char* kText = "#e5e5e5";+constexpr const char* kTextDim = "#808080";+constexpr const char* kTextMuted = "#404040";+constexpr const char* kAmber = "#d97706";+constexpr const char* kAmberDim = "#a85a05";+constexpr const char* kRed = "#dc2626";} // namespacenamespace fincept::screens {@@ -31,66 +47,296 @@ CrashRecoveryDialog::CrashRecoveryDialog(fincept::CrashRecovery* recovery,setWindowTitle(QStringLiteral("Fincept Terminal — Recover Previous Session"));setObjectName(QStringLiteral("CrashRecoveryDialog"));setModal(true);- resize(560, 420);+ resize(640, 480);build_ui();+ apply_styles();populate_snapshots();}void CrashRecoveryDialog::build_ui() {+ // Outer frame: zero margin so the title bar bleeds to the dialog edges.auto* root = new QVBoxLayout(this);- root->setContentsMargins(20, 20, 20, 16);- root->setSpacing(12);-- heading_ = new QLabel(QStringLiteral("The previous session ended unexpectedly."), this);+ root->setContentsMargins(0, 0, 0, 0);+ root->setSpacing(0);++ // ── Title bar (amber accent stripe + title) ──────────────────────────+ auto* title_bar = new QWidget(this);+ title_bar->setObjectName(QStringLiteral("recoveryTitleBar"));+ title_bar->setFixedHeight(44);+ auto* tbl = new QHBoxLayout(title_bar);+ tbl->setContentsMargins(20, 0, 20, 0);+ tbl->setSpacing(12);++ heading_ = new QLabel(QStringLiteral("RECOVER PREVIOUS SESSION"), title_bar);heading_->setObjectName(QStringLiteral("recoveryHeading"));- QFont f = heading_->font();- f.setBold(true);- f.setPointSize(f.pointSize() + 2);- heading_->setFont(f);- explainer_ = new QLabel(this);+ auto* badge = new QLabel(QStringLiteral("UNCLEAN SHUTDOWN DETECTED"), title_bar);+ badge->setObjectName(QStringLiteral("recoveryBadge"));++ tbl->addWidget(heading_);+ tbl->addStretch();+ tbl->addWidget(badge);+ root->addWidget(title_bar);++ // ── Body panel ───────────────────────────────────────────────────────+ auto* body = new QWidget(this);+ body->setObjectName(QStringLiteral("recoveryBody"));+ auto* bl = new QVBoxLayout(body);+ bl->setContentsMargins(20, 16, 20, 16);+ bl->setSpacing(12);++ explainer_ = new QLabel(body);explainer_->setObjectName(QStringLiteral("recoveryExplainer"));explainer_->setWordWrap(true);explainer_->setText(QStringLiteral(- "Fincept Terminal saves periodic snapshots of your workspace so you "- "can recover from a crash, power loss, or process kill. Pick a "- "snapshot to restore your windows and panels, or skip to start "- "fresh. Skipping does not delete the snapshots."));-- list_ = new QListWidget(this);+ "Pick a snapshot to restore your workspace, or skip to start fresh. "+ "Skipping does not delete the snapshots."));+ bl->addWidget(explainer_);++ // Section header above the list — column labels, terminal-style.+ auto* col_header = new QWidget(body);+ col_header->setObjectName(QStringLiteral("recoveryColHeader"));+ col_header->setFixedHeight(24);+ auto* chl = new QHBoxLayout(col_header);+ chl->setContentsMargins(10, 0, 10, 0);+ auto* col_name = new QLabel(QStringLiteral("SESSION"), col_header);+ auto* col_meta = new QLabel(QStringLiteral("WHEN"), col_header);+ col_name->setObjectName(QStringLiteral("recoveryColLabel"));+ col_meta->setObjectName(QStringLiteral("recoveryColLabel"));+ chl->addWidget(col_name);+ chl->addStretch();+ chl->addWidget(col_meta);+ bl->addWidget(col_header);++ list_ = new QListWidget(body);list_->setObjectName(QStringLiteral("recoverySnapshotList"));list_->setSelectionMode(QAbstractItemView::SingleSelection);- list_->setUniformItemSizes(true);- list_->setAlternatingRowColors(true);+ list_->setAlternatingRowColors(false);+ list_->setSpacing(0);+ list_->setFrameShape(QFrame::Box);connect(list_, &QListWidget::itemSelectionChanged, this,&CrashRecoveryDialog::on_selection_changed);connect(list_, &QListWidget::itemDoubleClicked, this,[this](QListWidgetItem*) { on_restore_clicked(); });- auto* button_row = new QHBoxLayout();- button_row->setContentsMargins(0, 0, 0, 0);- button_row->addStretch();-- skip_button_ = new QPushButton(QStringLiteral("Skip"), this);- skip_button_->setObjectName(QStringLiteral("recoverySkipButton"));+ empty_label_ = new QLabel(+ QStringLiteral("NO SNAPSHOTS AVAILABLE — START FRESH"), body);+ empty_label_->setObjectName(QStringLiteral("recoveryEmptyLabel"));+ empty_label_->setAlignment(Qt::AlignCenter);+ empty_label_->hide();++ bl->addWidget(list_, 1);+ bl->addWidget(empty_label_, 1);++ root->addWidget(body, 1);++ // ── Action bar at bottom (separator + buttons) ───────────────────────+ auto* action_bar = new QWidget(this);+ action_bar->setObjectName(QStringLiteral("recoveryActionBar"));+ action_bar->setFixedHeight(56);+ auto* abl = new QHBoxLayout(action_bar);+ abl->setContentsMargins(20, 12, 20, 12);+ abl->setSpacing(8);++ rename_button_ = new QPushButton(QStringLiteral("RENAME"), action_bar);+ rename_button_->setObjectName(QStringLiteral("recoverySecondaryButton"));+ rename_button_->setAutoDefault(false);+ rename_button_->setEnabled(false);+ connect(rename_button_, &QPushButton::clicked, this, &CrashRecoveryDialog::on_rename_clicked);++ delete_button_ = new QPushButton(QStringLiteral("DELETE"), action_bar);+ delete_button_->setObjectName(QStringLiteral("recoveryDangerButton"));+ delete_button_->setAutoDefault(false);+ delete_button_->setEnabled(false);+ connect(delete_button_, &QPushButton::clicked, this, &CrashRecoveryDialog::on_delete_clicked);++ skip_button_ = new QPushButton(QStringLiteral("SKIP"), action_bar);+ skip_button_->setObjectName(QStringLiteral("recoverySecondaryButton"));skip_button_->setAutoDefault(false);connect(skip_button_, &QPushButton::clicked, this, &CrashRecoveryDialog::on_skip_clicked);- restore_button_ = new QPushButton(QStringLiteral("Restore Selected"), this);- restore_button_->setObjectName(QStringLiteral("recoveryRestoreButton"));+ restore_button_ = new QPushButton(QStringLiteral("RESTORE"), action_bar);+ restore_button_->setObjectName(QStringLiteral("recoveryPrimaryButton"));restore_button_->setDefault(true);restore_button_->setEnabled(false);connect(restore_button_, &QPushButton::clicked, this, &CrashRecoveryDialog::on_restore_clicked);- button_row->addWidget(skip_button_);- button_row->addSpacing(8);- button_row->addWidget(restore_button_);+ abl->addWidget(rename_button_);+ abl->addWidget(delete_button_);+ abl->addStretch();+ abl->addWidget(skip_button_);+ abl->addWidget(restore_button_);- root->addWidget(heading_);- root->addWidget(explainer_);- root->addWidget(list_, 1);- root->addLayout(button_row);+ root->addWidget(action_bar);+}++void CrashRecoveryDialog::apply_styles() {+ // Fincept-terminal aesthetic: zero radii, sharp 1px borders, monospaced+ // tracking on labels. Single dialog stylesheet keyed by objectName so+ // children inherit without per-widget styling.+ setStyleSheet(QString(R"(+ QDialog#CrashRecoveryDialog {+ background: %1;+ color: %2;+ }++ /* Title bar — amber underline like a Fincept header */+ QWidget#recoveryTitleBar {+ background: %5;+ border-bottom: 2px solid %8;+ }+ QLabel#recoveryHeading {+ color: %2;+ font-size: 13px;+ font-weight: 700;+ letter-spacing: 1.5px;+ }+ QLabel#recoveryBadge {+ color: %1;+ background: %8;+ font-size: 9px;+ font-weight: 700;+ letter-spacing: 1px;+ padding: 3px 8px;+ }++ /* Body */+ QWidget#recoveryBody { background: %1; }+ QLabel#recoveryExplainer {+ color: %3;+ font-size: 11px;+ padding: 0 2px;+ }++ /* Column header strip above the list */+ QWidget#recoveryColHeader {+ background: %5;+ border: 1px solid %6;+ border-bottom: none;+ }+ QLabel#recoveryColLabel {+ color: %3;+ font-size: 9px;+ font-weight: 700;+ letter-spacing: 1px;+ background: transparent;+ }++ /* Empty state */+ QLabel#recoveryEmptyLabel {+ color: %4;+ font-size: 11px;+ font-weight: 700;+ letter-spacing: 1px;+ background: %5;+ border: 1px solid %6;+ padding: 32px;+ }++ /* Snapshot list — boxed, no rounding, sharp row dividers */+ QListWidget#recoverySnapshotList {+ background: %5;+ color: %2;+ border: 1px solid %6;+ border-radius: 0;+ padding: 0;+ outline: none;+ }+ QListWidget#recoverySnapshotList::item {+ color: %2;+ background: transparent;+ padding: 0;+ border-bottom: 1px solid %6;+ border-radius: 0;+ }+ QListWidget#recoverySnapshotList::item:hover {+ background: %7;+ }+ QListWidget#recoverySnapshotList::item:selected {+ background: %7;+ color: %8;+ border-left: 3px solid %8;+ }+ QListWidget#recoverySnapshotList::item:disabled {+ color: %4;+ }++ /* Action bar */+ QWidget#recoveryActionBar {+ background: %5;+ border-top: 1px solid %6;+ }++ /* Buttons — flat rectangles, zero radius */+ QPushButton {+ min-height: 30px;+ min-width: 90px;+ padding: 0 16px;+ font-size: 10px;+ font-weight: 700;+ letter-spacing: 1px;+ border-radius: 0;+ }+ QPushButton#recoveryPrimaryButton {+ background: %8;+ color: %1;+ border: 1px solid %8;+ }+ QPushButton#recoveryPrimaryButton:hover {+ background: %9;+ border-color: %9;+ }+ QPushButton#recoveryPrimaryButton:disabled {+ background: %6;+ color: %4;+ border-color: %6;+ }+ QPushButton#recoverySecondaryButton {+ background: %7;+ color: %2;+ border: 1px solid %6;+ }+ QPushButton#recoverySecondaryButton:hover {+ border-color: %3;+ color: %2;+ }+ QPushButton#recoverySecondaryButton:disabled {+ color: %4;+ border-color: %6;+ }+ QPushButton#recoveryDangerButton {+ background: transparent;+ color: %10;+ border: 1px solid %10;+ }+ QPushButton#recoveryDangerButton:hover {+ background: rgba(220, 38, 38, 0.12);+ }+ QPushButton#recoveryDangerButton:disabled {+ color: %4;+ border-color: %6;+ }++ QScrollBar:vertical {+ background: %5;+ width: 8px;+ border: none;+ border-radius: 0;+ }+ QScrollBar::handle:vertical {+ background: %6;+ border-radius: 0;+ min-height: 20px;+ }+ QScrollBar::handle:vertical:hover {+ background: %3;+ }+ QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {+ height: 0;+ }+ )").arg(kBgBase, kText, kTextDim, kTextMuted, kBgSurface,+ kBorder, kBgRaised, kAmber, kAmberDim, kRed));}void CrashRecoveryDialog::populate_snapshots() {@@ -99,6 +345,8 @@ void CrashRecoveryDialog::populate_snapshots() {if (!recovery_) {LOG_WARN(kRecoveryTag, "CrashRecoveryDialog has no recovery pointer — empty list");+ list_->hide();+ empty_label_->show();return;}@@ -106,40 +354,141 @@ void CrashRecoveryDialog::populate_snapshots() {if (r.is_err()) {LOG_ERROR(kRecoveryTag,QString("latest_snapshots failed: %1").arg(QString::fromStdString(r.error())));+ list_->hide();+ empty_label_->show();return;}entries_ = r.value();+ if (entries_.isEmpty()) {+ list_->hide();+ empty_label_->show();+ return;+ }+ list_->show();+ empty_label_->hide();++ // Custom row widget: name left, timestamp right, kind badge. Two-line+ // layout for the left side keeps long names readable. QListWidgetItem+ // text alone doesn't render \n as a line break.for (const auto& e : entries_) {- const QString ts = format_timestamp(e.created_at_ms);- const QString kind = format_kind(e.kind);- QString label = e.name.isEmpty()- ? QString("%1 — %2").arg(ts, kind)- : QString("%1 — %2 — %3").arg(ts, kind, e.name);- auto* item = new QListWidgetItem(label, list_);+ const QString name = display_name(e);+ const QString relative = format_relative(e.created_at_ms);+ const QString absolute = format_timestamp(e.created_at_ms);+ const QString kind = format_kind(e.kind);++ auto* row = new QWidget(list_);+ row->setAttribute(Qt::WA_TransparentForMouseEvents);+ row->setStyleSheet("background: transparent;");++ auto* hl = new QHBoxLayout(row);+ hl->setContentsMargins(12, 8, 12, 8);+ hl->setSpacing(12);++ // Left column: name + kind badge.+ auto* left = new QVBoxLayout;+ left->setContentsMargins(0, 0, 0, 0);+ left->setSpacing(3);++ auto* name_lbl = new QLabel(name, row);+ name_lbl->setStyleSheet(+ QString("color:%1;font-size:12px;font-weight:600;background:transparent;")+ .arg(kText));++ auto* kind_lbl = new QLabel(kind.toUpper().remove('[').remove(']'), row);+ kind_lbl->setStyleSheet(+ QString("color:%1;background:%2;padding:1px 6px;font-size:8px;"+ "font-weight:700;letter-spacing:1px;")+ .arg(kTextDim, kBgRaised));+ kind_lbl->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);+ kind_lbl->setMaximumWidth(80);++ left->addWidget(name_lbl);+ left->addWidget(kind_lbl, 0, Qt::AlignLeft);+ hl->addLayout(left, 1);++ // Right column: relative + absolute timestamp.+ auto* right = new QVBoxLayout;+ right->setContentsMargins(0, 0, 0, 0);+ right->setSpacing(3);++ auto* rel_lbl = new QLabel(relative.toUpper(), row);+ rel_lbl->setStyleSheet(+ QString("color:%1;font-size:10px;font-weight:700;letter-spacing:0.5px;"+ "background:transparent;")+ .arg(kAmber));+ rel_lbl->setAlignment(Qt::AlignRight | Qt::AlignVCenter);++ auto* abs_lbl = new QLabel(absolute, row);+ abs_lbl->setStyleSheet(+ QString("color:%1;font-size:10px;background:transparent;")+ .arg(kTextMuted));+ abs_lbl->setAlignment(Qt::AlignRight | Qt::AlignVCenter);++ right->addWidget(rel_lbl);+ right->addWidget(abs_lbl);+ hl->addLayout(right, 0);++ auto* item = new QListWidgetItem(list_);item->setData(Qt::UserRole, e.snapshot_id);+ item->setSizeHint(QSize(0, row->sizeHint().height() + 2));+ list_->setItemWidget(item, row);}- if (!entries_.isEmpty()) {- list_->setCurrentRow(0); // pre-select newest- }+ list_->setCurrentRow(0); // pre-select newest}QString CrashRecoveryDialog::format_timestamp(qint64 unix_ms) const {if (unix_ms <= 0) return QStringLiteral("(unknown time)");const auto dt = QDateTime::fromMSecsSinceEpoch(unix_ms);- return dt.toLocalTime().toString(QStringLiteral("yyyy-MM-dd hh:mm:ss"));+ return dt.toLocalTime().toString(QStringLiteral("MMM d, yyyy h:mm AP"));+}++QString CrashRecoveryDialog::format_relative(qint64 unix_ms) const {+ if (unix_ms <= 0) return QStringLiteral("(unknown)");+ const qint64 now_ms = QDateTime::currentMSecsSinceEpoch();+ qint64 diff = now_ms - unix_ms;+ if (diff < 0) diff = 0;+ const qint64 sec = diff / 1000;+ if (sec < 60) return QStringLiteral("just now");+ const qint64 min = sec / 60;+ if (min < 60) return min == 1 ? QStringLiteral("1 minute ago")+ : QString("%1 minutes ago").arg(min);+ const qint64 hr = min / 60;+ if (hr < 24) return hr == 1 ? QStringLiteral("1 hour ago")+ : QString("%1 hours ago").arg(hr);+ const qint64 day = hr / 24;+ if (day == 1) return QStringLiteral("yesterday");+ if (day < 7) return QString("%1 days ago").arg(day);+ // Older than a week — let the absolute timestamp carry the weight.+ return format_timestamp(unix_ms);}QString CrashRecoveryDialog::format_kind(const QString& kind) const {- if (kind == QLatin1String("auto")) return QStringLiteral("autosave");- if (kind == QLatin1String("crash_recovery")) return QStringLiteral("crash snapshot");- if (kind == QLatin1String("named_save")) return QStringLiteral("named");- return kind;+ if (kind == QLatin1String("auto")) return QStringLiteral("[autosave]");+ if (kind == QLatin1String("crash_recovery")) return QStringLiteral("[crash]");+ if (kind == QLatin1String("named_save")) return QStringLiteral("[saved]");+ return QString("[%1]").arg(kind);+}++QString CrashRecoveryDialog::display_name(+ const fincept::WorkspaceSnapshotRing::Entry& e) const {+ if (!e.name.isEmpty())+ return e.name;+ // Auto-generate a unique, human-readable name from the timestamp so each+ // snapshot has a recognisable identifier. Users can override via Rename.+ if (e.created_at_ms <= 0)+ return QString("Session #%1").arg(e.snapshot_id);+ const auto dt = QDateTime::fromMSecsSinceEpoch(e.created_at_ms);+ return QString("Session — %1").arg(+ dt.toLocalTime().toString(QStringLiteral("MMM d, h:mm AP")));}void CrashRecoveryDialog::on_selection_changed() {- restore_button_->setEnabled(list_->currentItem() != nullptr);+ const bool has = (list_->currentItem() != nullptr);+ restore_button_->setEnabled(has);+ rename_button_->setEnabled(has);+ delete_button_->setEnabled(has);}void CrashRecoveryDialog::on_restore_clicked() {@@ -156,7 +505,6 @@ void CrashRecoveryDialog::on_restore_clicked() {QString("load_payload(%1) failed: %2").arg(id).arg(QString::fromStdString(payload_r.error())));- // Stay open so the user can pick a different snapshot.item->setFlags(item->flags() & ~Qt::ItemIsEnabled);return;}@@ -207,4 +555,84 @@ void CrashRecoveryDialog::on_skip_clicked() {reject();}+void CrashRecoveryDialog::on_rename_clicked() {+ auto* item = list_->currentItem();+ if (!item || !ring_)+ return;+ const qint64 id = item->data(Qt::UserRole).toLongLong();++ // Find the current entry to seed the dialog with its current display name.+ QString current_name;+ for (const auto& e : entries_) {+ if (e.snapshot_id == id) {+ current_name = display_name(e);+ break;+ }+ }++ bool ok = false;+ const QString new_name = QInputDialog::getText(+ this, QStringLiteral("Rename Session"),+ QStringLiteral("Session name:"),+ QLineEdit::Normal, current_name, &ok);+ if (!ok)+ return;++ auto r = ring_->rename(id, new_name);+ if (r.is_err()) {+ LOG_ERROR(kRecoveryTag,+ QString("rename(%1) failed: %2")+ .arg(id).arg(QString::fromStdString(r.error())));+ QMessageBox::warning(this, QStringLiteral("Rename failed"),+ QString::fromStdString(r.error()));+ return;+ }++ LOG_INFO(kRecoveryTag,+ QString("Renamed snapshot %1 → '%2'").arg(id).arg(new_name));+ populate_snapshots();+ // Re-select the renamed row so the user sees the new label immediately.+ for (int i = 0; i < list_->count(); ++i) {+ if (list_->item(i)->data(Qt::UserRole).toLongLong() == id) {+ list_->setCurrentRow(i);+ break;+ }+ }+}++void CrashRecoveryDialog::on_delete_clicked() {+ auto* item = list_->currentItem();+ if (!item || !ring_)+ return;+ const qint64 id = item->data(Qt::UserRole).toLongLong();++ QString name;+ for (const auto& e : entries_) {+ if (e.snapshot_id == id) {+ name = display_name(e);+ break;+ }+ }++ const auto reply = QMessageBox::question(+ this, QStringLiteral("Delete snapshot"),+ QString("Delete \"%1\"?\n\nThis cannot be undone.").arg(name),+ QMessageBox::Yes | QMessageBox::No, QMessageBox::No);+ if (reply != QMessageBox::Yes)+ return;++ auto r = ring_->erase(id);+ if (r.is_err()) {+ LOG_ERROR(kRecoveryTag,+ QString("erase(%1) failed: %2")+ .arg(id).arg(QString::fromStdString(r.error())));+ QMessageBox::warning(this, QStringLiteral("Delete failed"),+ QString::fromStdString(r.error()));+ return;+ }++ LOG_INFO(kRecoveryTag, QString("Deleted snapshot %1 ('%2')").arg(id).arg(name));+ populate_snapshots();+}+} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/recovery/CrashRecoveryDialog.h b/fincept-qt/src/screens/recovery/CrashRecoveryDialog.hindex f9db5c1df..a4c522696 100644--- a/fincept-qt/src/screens/recovery/CrashRecoveryDialog.h+++ b/fincept-qt/src/screens/recovery/CrashRecoveryDialog.h@@ -55,19 +55,27 @@ class CrashRecoveryDialog : public QDialog {void on_selection_changed();void on_restore_clicked();void on_skip_clicked();+ void on_rename_clicked();+ void on_delete_clicked();private:void build_ui();void populate_snapshots();+ void apply_styles();QString format_timestamp(qint64 unix_ms) const;+ QString format_relative(qint64 unix_ms) const;QString format_kind(const QString& kind) const;+ QString display_name(const fincept::WorkspaceSnapshotRing::Entry& e) const;fincept::CrashRecovery* recovery_ = nullptr;fincept::WorkspaceSnapshotRing* ring_ = nullptr;QLabel* heading_ = nullptr;QLabel* explainer_ = nullptr;+ QLabel* empty_label_ = nullptr;QListWidget* list_ = nullptr;+ QPushButton* rename_button_ = nullptr;+ QPushButton* delete_button_ = nullptr;QPushButton* restore_button_ = nullptr;QPushButton* skip_button_ = nullptr;diff --git a/fincept-qt/src/screens/settings/AppearanceSection.cpp b/fincept-qt/src/screens/settings/AppearanceSection.cppindex 581afd7ce..9390cb582 100644--- a/fincept-qt/src/screens/settings/AppearanceSection.cpp+++ b/fincept-qt/src/screens/settings/AppearanceSection.cpp@@ -9,8 +9,11 @@#include "ui/theme/Theme.h"#include "ui/theme/ThemeManager.h"+#include <QApplication>#include <QFontDatabase>#include <QLabel>+#include <QMetaObject>+#include <QPointer>#include <QPushButton>#include <QScrollArea>#include <QShowEvent>@@ -76,21 +79,49 @@ void AppearanceSection::build_ui() {app_font_family_->setStyleSheet(combo_ss());vl->addWidget(make_row("Font Family", app_font_family_));- // Debounced live preview — coalesce rapid changes into one apply after 300ms idle+ // Debounced live preview — coalesce rapid changes into one apply after 300ms idle.+ //+ // Two safety properties beyond the debounce window matter for KDE Plasma 6 ++ // Qt6 + Wayland (issue #247: app segfaulted on Font Size / Font Family change):+ //+ // 1. apply_typography_and_density() coalesces font + density into ONE+ // qApp->setStyleSheet() call. Two back-to-back global restyles during+ // a QComboBox event chain are a documented crash trigger on Wayland —+ // the second restyle mutates surface state while the popup is still+ // tearing down.+ //+ // 2. The apply is dispatched via Qt::QueuedConnection (singleShot(0))+ // so the QComboBox::currentTextChanged → debounce::timeout call stack+ // fully unwinds before we re-style every widget in the app, including+ // the combo box that started the chain.appearance_debounce_ = new QTimer(this);appearance_debounce_->setSingleShot(true);appearance_debounce_->setInterval(300);connect(appearance_debounce_, &QTimer::timeout, this, [this]() {- auto& tm = ui::ThemeManager::instance();- int px = QString(app_font_size_->currentText()).replace("px", "").toInt();- if (px > 0)- tm.apply_font(app_font_family_->currentText(), px);- tm.apply_density(app_density_->currentText());+ if (!app_font_size_ || !app_font_family_ || !app_density_)+ return;+ const QString family = app_font_family_->currentText();+ const QString density = app_density_->currentText();+ const int px = QString(app_font_size_->currentText()).replace("px", "").toInt();+ // Skip families that aren't actually installed — Qt would otherwise+ // hand QFont an invalid family which on some Wayland font backends+ // turns into a setPointSizeF(0) / null-glyph crash.+ if (!family.isEmpty() && !QFontDatabase::families().contains(family))+ return;++ QPointer<AppearanceSection> guard(this);+ QMetaObject::invokeMethod(qApp, [guard, family, px, density]() {+ if (!guard)+ return;+ ui::ThemeManager::instance().apply_typography_and_density(family, px, density);+ }, Qt::QueuedConnection);});auto restart_debounce = [this]() { appearance_debounce_->start(); };- connect(app_font_size_, &QComboBox::currentTextChanged, this, restart_debounce);- connect(app_font_family_, &QComboBox::currentTextChanged, this, restart_debounce);+ connect(app_font_size_, &QComboBox::currentTextChanged, this, restart_debounce,+ Qt::UniqueConnection);+ connect(app_font_family_, &QComboBox::currentTextChanged, this, restart_debounce,+ Qt::UniqueConnection);vl->addSpacing(8);vl->addWidget(make_sep());@@ -108,7 +139,8 @@ void AppearanceSection::build_ui() {app_density_->setStyleSheet(combo_ss());vl->addWidget(make_row("Content Density", app_density_, "Controls padding and spacing throughout the UI."));- connect(app_density_, &QComboBox::currentTextChanged, this, restart_debounce);+ connect(app_density_, &QComboBox::currentTextChanged, this, restart_debounce,+ Qt::UniqueConnection);vl->addSpacing(8);vl->addWidget(make_sep());@@ -144,7 +176,6 @@ void AppearanceSection::build_ui() {apply_btn->setStyleSheet(btn_primary_ss());connect(apply_btn, &QPushButton::clicked, this, [this]() {auto& repo = SettingsRepository::instance();- auto& tm = ui::ThemeManager::instance();repo.set("appearance.font_size", app_font_size_->currentText(), "appearance");repo.set("appearance.font_family", app_font_family_->currentText(), "appearance");@@ -153,13 +184,22 @@ void AppearanceSection::build_ui() {repo.set("appearance.show_ticker_bar", ticker_bar_toggle_->isChecked() ? "true" : "false", "appearance");repo.set("appearance.animations", animations_toggle_->isChecked() ? "true" : "false", "appearance");- // Flush any pending debounce immediately on save+ // Flush any pending debounce immediately on save. Same coalesced ++ // queued path as the live-preview lambda above so a Save click that+ // happens while a combo box just changed cannot trigger the+ // back-to-back-restyle Wayland crash.if (appearance_debounce_->isActive()) {appearance_debounce_->stop();+ const QString family = app_font_family_->currentText();+ const QString density = app_density_->currentText();int px = QString(app_font_size_->currentText()).replace("px", "").toInt();if (px <= 0) px = 14;- tm.apply_font(app_font_family_->currentText(), px);- tm.apply_density(app_density_->currentText());+ QPointer<AppearanceSection> guard(this);+ QMetaObject::invokeMethod(qApp, [guard, family, px, density]() {+ if (!guard)+ return;+ ui::ThemeManager::instance().apply_typography_and_density(family, px, density);+ }, Qt::QueuedConnection);}LOG_INFO("Settings", "Appearance saved and applied");diff --git a/fincept-qt/src/screens/settings/GeneralSection.cpp b/fincept-qt/src/screens/settings/GeneralSection.cppindex cba8dfbc8..4087a356c 100644--- a/fincept-qt/src/screens/settings/GeneralSection.cpp+++ b/fincept-qt/src/screens/settings/GeneralSection.cpp@@ -72,7 +72,7 @@ void GeneralSection::build_ui() {[this](int idx) {const QString val = on_close_combo_->itemData(idx).toString();SettingsRepository::instance().set(- QStringLiteral(kKeyOnClose), val, QStringLiteral("general"));+ QString::fromLatin1(kKeyOnClose), val, QStringLiteral("general"));LOG_INFO("Settings", QString("on_last_window_close → %1").arg(val));});@@ -85,8 +85,8 @@ void GeneralSection::build_ui() {void GeneralSection::reload() {if (!on_close_combo_) return;const auto r = SettingsRepository::instance().get(- QStringLiteral(kKeyOnClose), QStringLiteral(kDefaultOnClose));- const QString cur = r.is_ok() ? r.value() : QStringLiteral(kDefaultOnClose);+ QString::fromLatin1(kKeyOnClose), QString::fromLatin1(kDefaultOnClose));+ const QString cur = r.is_ok() ? r.value() : QString::fromLatin1(kDefaultOnClose);const int idx = on_close_combo_->findData(cur);QSignalBlocker block(on_close_combo_);on_close_combo_->setCurrentIndex(idx >= 0 ? idx : 0);diff --git a/fincept-qt/src/screens/settings/LlmConfigSection.cpp b/fincept-qt/src/screens/settings/LlmConfigSection.cppindex b8f819f5e..621efb935 100644--- a/fincept-qt/src/screens/settings/LlmConfigSection.cpp+++ b/fincept-qt/src/screens/settings/LlmConfigSection.cpp@@ -90,7 +90,8 @@ QStringList LlmConfigSection::fallback_models(const QString& provider) {"moonshot-v1-32k-vision-preview","moonshot-v1-128k-vision-preview"};if (p == "ollama")- return {"llama3.1:8b", "qwen2.5:7b", "mistral:7b"};+ return {}; // Local provider — models fetched live from /api/tags. No fallback so the+ // combo only shows what the user actually has installed locally.if (p == "xai")return {"grok-4-latest", "grok-4", "grok-3", "grok-3-mini"};if (p == "fincept")@@ -613,8 +614,9 @@ void LlmConfigSection::populate_form(const QString& provider) {provider_edit_->setText(provider);bool is_fincept = (provider.toLower() == "fincept");+ bool is_ollama = (provider.toLower() == "ollama");- // Populate model combo with fallback suggestions+ // Populate model combo with fallback suggestions (empty for ollama — see fallback_models).model_combo_->blockSignals(true);model_combo_->clear();model_combo_->addItems(fallback_models(provider));@@ -657,6 +659,21 @@ void LlmConfigSection::populate_form(const QString& provider) {model_combo_->setVisible(false);fetch_btn_->setVisible(false);base_url_edit_->setVisible(false);+ } else if (is_ollama) {+ // Local provider — no API key needed. Mark the field clearly so users+ // don't think it's broken or required.+ api_key_edit_->clear();+ api_key_edit_->setEnabled(false);+ api_key_edit_->setPlaceholderText("Not required — local provider");+ model_combo_->setVisible(true);+ model_combo_->setEnabled(true);+ fetch_btn_->setVisible(true);+ fetch_btn_->setEnabled(true);+ base_url_edit_->setVisible(true);+ base_url_edit_->setEnabled(true);+ // Auto-fetch installed models from the local Ollama server so the+ // combo only shows what the user actually has, not hardcoded guesses.+ QTimer::singleShot(0, this, [this]() { on_fetch_models(); });} else {api_key_edit_->setText(p.api_key);api_key_edit_->setEnabled(true);@@ -674,7 +691,7 @@ void LlmConfigSection::populate_form(const QString& provider) {// New provider — clear formapi_key_edit_->clear();- api_key_edit_->setEnabled(!is_fincept);+ api_key_edit_->setEnabled(!is_fincept && !is_ollama);if (is_fincept) {auto stored = SettingsRepository::instance().get("fincept_api_key");if (stored.is_ok() && !stored.value().isEmpty())@@ -684,7 +701,18 @@ void LlmConfigSection::populate_form(const QString& provider) {model_combo_->setVisible(false);fetch_btn_->setVisible(false);base_url_edit_->setVisible(false);+ } else if (is_ollama) {+ api_key_edit_->setPlaceholderText("Not required — local provider");+ model_combo_->setVisible(true);+ model_combo_->setEnabled(true);+ fetch_btn_->setVisible(true);+ fetch_btn_->setEnabled(true);+ base_url_edit_->setVisible(true);+ base_url_edit_->setEnabled(true);+ base_url_edit_->setText(def_url);+ QTimer::singleShot(0, this, [this]() { on_fetch_models(); });} else {+ api_key_edit_->setPlaceholderText("sk-...");model_combo_->setVisible(true);model_combo_->setEnabled(true);fetch_btn_->setVisible(true);@@ -900,7 +928,13 @@ void LlmConfigSection::on_models_fetched(const QString& provider, const QStringLreturn;if (!error.isEmpty()) {- show_status("Fetch failed: " + error + " — using suggestions", true);+ // Show the actual error so users can act on it (timeout, 401, host+ // not found, etc.) instead of guessing. For ollama add a hint about+ // the local server in case that's the cause.+ if (provider.toLower() == "ollama")+ show_status("Ollama fetch failed: " + error + " — check `ollama serve` and base URL", true);+ else+ show_status("Fetch failed: " + error, true);return;}@@ -1241,10 +1275,44 @@ void LlmConfigSection::on_profile_selected(int row) {}void LlmConfigSection::on_profile_provider_changed(const QString& provider) {+ const bool is_ollama = (provider.toLower() == "ollama");+profile_model_combo_->clear();profile_model_combo_->addItems(fallback_models(provider));profile_base_url_edit_->setText(default_base_url(provider));+ if (is_ollama) {+ // Local provider — no API key needed. One-shot listener pulls live models+ // from the local Ollama server into the profile combo. Receiver is `this`,+ // so the connection is auto-severed if the section is destroyed.+ profile_api_key_edit_->clear();+ profile_api_key_edit_->setEnabled(false);+ profile_api_key_edit_->setPlaceholderText("Not required — local provider");++ auto conn = std::make_shared<QMetaObject::Connection>();+ *conn = connect(&ai_chat::LlmService::instance(), &ai_chat::LlmService::models_fetched, this,+ [this, conn](const QString& p, const QStringList& models, const QString& err) {+ if (p.toLower() != "ollama")+ return;+ disconnect(*conn);+ if (!err.isEmpty()) {+ show_profile_status(+ "Cannot reach Ollama — is `ollama serve` running locally?", true);+ return;+ }+ const QString current = profile_model_combo_->currentText();+ profile_model_combo_->clear();+ profile_model_combo_->addItems(models);+ if (!current.isEmpty())+ profile_model_combo_->setCurrentText(current);+ });+ ai_chat::LlmService::instance().fetch_models("ollama", {}, profile_base_url_edit_->text().trimmed());+ return;+ }++ profile_api_key_edit_->setEnabled(true);+ profile_api_key_edit_->setPlaceholderText("Leave blank to inherit from provider");+// Pre-fill api_key from saved provider if present and field is emptyif (profile_api_key_edit_->text().isEmpty()) {auto providers = LlmConfigRepository::instance().list_providers();diff --git a/fincept-qt/src/services/alpha_arena/AlphaArenaEngine.cpp b/fincept-qt/src/services/alpha_arena/AlphaArenaEngine.cppindex defd84fcd..cb92633ea 100644--- a/fincept-qt/src/services/alpha_arena/AlphaArenaEngine.cpp+++ b/fincept-qt/src/services/alpha_arena/AlphaArenaEngine.cpp@@ -47,7 +47,12 @@ void AlphaArenaEngine::init() {router_, &OrderRouter::on_decision);connect(router_, &OrderRouter::action_evaluated,- this, &AlphaArenaEngine::action_evaluated);+ this, [this](const QString& agent_id, const QString& coin,+ fincept::services::alpha_arena::Signal sig,+ int risk_outcome, const QString& reason) {+ emit action_evaluated(agent_id, coin, static_cast<int>(sig),+ risk_outcome, reason);+ });connect(router_, &OrderRouter::order_placed,this, &AlphaArenaEngine::order_placed);connect(router_, &OrderRouter::hitl_requested,diff --git a/fincept-qt/src/services/alpha_arena/AlphaArenaService.cpp b/fincept-qt/src/services/alpha_arena/AlphaArenaService.cppnew file mode 100644index 000000000..d374c9013--- /dev/null+++ b/fincept-qt/src/services/alpha_arena/AlphaArenaService.cpp@@ -0,0 +1,63 @@+#include "services/alpha_arena/AlphaArenaService.h"++#include "core/logging/Logger.h"+#include "python/PythonRunner.h"++#include <QJsonDocument>+#include <QJsonParseError>++namespace fincept::services::alpha_arena {++AlphaArenaService& AlphaArenaService::instance() {+ static AlphaArenaService s;+ return s;+}++void AlphaArenaService::run_action(const QJsonObject& payload, ActionCallback cb) {+ const QString json_arg =+ QString::fromUtf8(QJsonDocument(payload).toJson(QJsonDocument::Compact));+ const QString action = payload.value("action").toString();++ fincept::python::PythonRunner::instance().run(+ QStringLiteral("alpha_arena/main.py"), {json_arg},+ [cb = std::move(cb), action](const fincept::python::PythonResult& result) {+ ActionResult out;+ if (!result.success) {+ out.error = result.error.isEmpty()+ ? QStringLiteral("Engine call failed")+ : result.error;+ LOG_ERROR("AlphaArenaService",+ QStringLiteral("%1 failed: %2").arg(action, out.error.left(300)));+ if (cb) cb(out);+ return;+ }++ const QString json_str = fincept::python::extract_json(result.output);+ if (json_str.isEmpty()) {+ out.error = QStringLiteral("No response from engine");+ if (cb) cb(out);+ return;+ }++ QJsonParseError err;+ const auto doc = QJsonDocument::fromJson(json_str.toUtf8(), &err);+ if (doc.isNull() || !doc.isObject()) {+ out.error = QStringLiteral("Invalid response: %1").arg(err.errorString());+ if (cb) cb(out);+ return;+ }++ const QJsonObject obj = doc.object();+ if (!obj.value("success").toBool(false)) {+ out.error = obj.value("error").toString(QStringLiteral("Engine reported failure"));+ if (cb) cb(out);+ return;+ }++ out.success = true;+ out.data = obj;+ if (cb) cb(out);+ });+}++} // namespace fincept::services::alpha_arenadiff --git a/fincept-qt/src/services/alpha_arena/AlphaArenaService.h b/fincept-qt/src/services/alpha_arena/AlphaArenaService.hnew file mode 100644index 000000000..dc1d2a461--- /dev/null+++ b/fincept-qt/src/services/alpha_arena/AlphaArenaService.h@@ -0,0 +1,39 @@+#pragma once+// AlphaArenaService — thin wrapper around the Alpha Arena Python engine so+// the screen does not spawn Python directly (D1 / P6).+//+// Alpha Arena is a user-driven competition runner: the user creates a+// competition, runs cycles, refreshes leaderboard. All actions are one-shot+// JSON-in / JSON-out calls against alpha_arena/main.py — no streaming cadence+// to put on the hub, so a non-Producer service wrapper is the right shape.++#include <QJsonObject>+#include <QObject>+#include <QString>++#include <functional>++namespace fincept::services::alpha_arena {++struct ActionResult {+ bool success = false;+ QJsonObject data; // engine response (top-level JSON)+ QString error;+};++using ActionCallback = std::function<void(const ActionResult&)>;++class AlphaArenaService : public QObject {+ Q_OBJECT+ public:+ static AlphaArenaService& instance();++ /// Runs `alpha_arena/main.py <payload>` where payload is `{action, params, api_keys?}`.+ /// The caller builds the payload; we dispatch and parse the JSON response.+ void run_action(const QJsonObject& payload, ActionCallback cb);++ private:+ AlphaArenaService() = default;+};++} // namespace fincept::services::alpha_arenadiff --git a/fincept-qt/src/services/alpha_arena/PaperVenue.h b/fincept-qt/src/services/alpha_arena/PaperVenue.hindex d374ac519..0dac287e6 100644--- a/fincept-qt/src/services/alpha_arena/PaperVenue.h+++ b/fincept-qt/src/services/alpha_arena/PaperVenue.h@@ -98,6 +98,8 @@ class PaperVenue : public QObject, public IExchangeVenue {/// Sequential venue-order-id generator (paper only).quint64 next_order_seq_ = 1;++ friend void paper_seed_agent(PaperVenue& venue, const QString& agent_id, double initial_capital);};/// Convenience — the engine seeds each agent's paper book at agent-add time.diff --git a/fincept-qt/src/services/dbnomics/DBnomicsService.cpp b/fincept-qt/src/services/dbnomics/DBnomicsService.cppindex 3909480e0..8c8807826 100644--- a/fincept-qt/src/services/dbnomics/DBnomicsService.cpp+++ b/fincept-qt/src/services/dbnomics/DBnomicsService.cpp@@ -81,7 +81,7 @@ void DBnomicsService::fetch_providers() {kProviderCacheSec, "dbnomics");LOG_INFO("DBnomicsService", QString("Loaded %1 providers").arg(out.size()));emit providers_loaded(out);- });+ }, this);}void DBnomicsService::fetch_datasets(const QString& provider_code, int offset) {@@ -146,7 +146,7 @@ void DBnomicsService::fetch_datasets(const QString& provider_code, int offset) {}LOG_INFO("DBnomicsService", QString("Loaded %1 datasets (total=%2)").arg(out.size()).arg(total));emit datasets_loaded(out, page, append);- });+ }, this);}void DBnomicsService::fetch_series(const QString& provider_code, const QString& dataset_code, const QString& query,@@ -221,7 +221,8 @@ void DBnomicsService::fetch_series(const QString& provider_code, const QString&}LOG_INFO("DBnomicsService", QString("Loaded %1 series (total=%2)").arg(out.size()).arg(total));emit series_loaded(out, page, append);- });+ },+ this);}void DBnomicsService::fetch_observations(const QString& provider_code, const QString& dataset_code,@@ -273,7 +274,7 @@ void DBnomicsService::fetch_observations(const QString& provider_code, const QStconst QString topic = hub_topic(provider_code, dataset_code, series_code);fincept::datahub::DataHub::instance().publish(topic, QVariant::fromValue(dp));}- });+ }, this);}void DBnomicsService::global_search(const QString& query, int offset) {@@ -303,7 +304,7 @@ void DBnomicsService::global_search(const QString& query, int offset) {}DbnPagination page{offset, 20, total};emit search_results_loaded(out, page, offset > 0);- });+ }, this);}void DBnomicsService::schedule_series_search(const QString& prov, const QString& ds, const QString& query) {diff --git a/fincept-qt/src/services/news/NewsService.cpp b/fincept-qt/src/services/news/NewsService.cppindex 70d77cf8f..582740cbd 100644--- a/fincept-qt/src/services/news/NewsService.cpp+++ b/fincept-qt/src/services/news/NewsService.cpp@@ -30,9 +30,9 @@ static constexpr int kFeedTransferTimeoutMs = 8000; // 8s per RSS feed requeststatic constexpr int kWsReconnectDelayMs = 10000; // 10s before WebSocket reconnectstatic constexpr int kSummaryMaxChars = 300; // max chars for article summary-// Use a real browser User-Agent — Bloomberg, WSJ, FT and other major-// publishers reject "FinceptTerminal/4.0" as scraper traffic. Browser UA-// gets us 200s on the same endpoints.+// Use a real browser User-Agent — major financial publishers reject+// "FinceptTerminal/4.0" as scraper traffic. Browser UA gets us 200s on+// the same endpoints.static constexpr const char* kBrowserUserAgent ="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 ""(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36";@@ -366,6 +366,8 @@ void NewsService::analyze_article(const QString& url, AnalysisCallback cb) {QJsonObject body;body["url"] = url;+ // context = `this` ensures the callback drops if NewsService ever stops+ // being a singleton — today it always outlives the request.HttpClient::instance().post("/news/analyze", body, [this, cb](Result<QJsonDocument> result) {if (result.is_err()) {LOG_ERROR("NewsService", "Analysis failed: " + QString::fromStdString(result.error()));@@ -411,7 +413,7 @@ void NewsService::analyze_article(const QString& url, AnalysisCallback cb) {cb(true, analysis);emit this->analysis_ready(analysis);- });+ }, this);}// ── AI Headline Summarization ────────────────────────────────────────────────@@ -991,7 +993,7 @@ QVector<RSSFeed> NewsService::default_feeds() {return {// Tier 1 — Wire Services & Regulators// Reuters discontinued public RSS in 2020 (feeds.reuters.com is dead).- // We keep tier-1 coverage via AP, BBC, FT, Bloomberg, WSJ instead.+ // We keep tier-1 coverage via AP, BBC, FT, WSJ and other majors instead.{"ap-top", "AP Top News", "https://rsshub.app/apnews/topics/ap-top-news", "GEOPOLITICS", "GLOBAL", "AP", 1},{"sec-press", "SEC Press Releases", "https://www.sec.gov/news/pressreleases.rss", "REGULATORY", "US", "SEC", 1},{"fed-press", "Federal Reserve", "https://www.federalreserve.gov/feeds/press_all.xml", "REGULATORY", "US",@@ -999,8 +1001,8 @@ QVector<RSSFeed> NewsService::default_feeds() {{"un-news", "UN News", "https://news.un.org/feed/subscribe/en/news/all/rss.xml", "GEOPOLITICS", "GLOBAL", "UN",1},// (IMF News removed — endpoint serves an Akamai access-denied HTML page,- // not RSS. Fincept's macro coverage is already provided by Bloomberg /- // WSJ / Economist / IMF press is reachable via UN feeds.)+ // not RSS. Fincept's macro coverage is already provided by WSJ /+ // Economist / IMF press is reachable via UN feeds.)// Tier 2 — Major Financial Media{"bloomberg-mkts", "Bloomberg Markets", "https://feeds.bloomberg.com/markets/news.rss", "MARKETS", "GLOBAL",diff --git a/fincept-qt/src/services/options/OptionChainTypes.h b/fincept-qt/src/services/options/OptionChainTypes.hindex 113b6e2a5..c66d128e7 100644--- a/fincept-qt/src/services/options/OptionChainTypes.h+++ b/fincept-qt/src/services/options/OptionChainTypes.h@@ -7,6 +7,7 @@// flow through DataHub topics.#include "trading/TradingTypes.h"+#include "trading/instruments/InstrumentTypes.h"#include <QDateTime>#include <QMetaType>diff --git a/fincept-qt/src/services/pushpins/PushpinService.h b/fincept-qt/src/services/pushpins/PushpinService.hindex 127e3784b..9c535e013 100644--- a/fincept-qt/src/services/pushpins/PushpinService.h+++ b/fincept-qt/src/services/pushpins/PushpinService.h@@ -6,7 +6,7 @@namespace fincept {-/// Singleton model backing the persistent symbol chip strip (Bloomberg+/// Singleton model backing the persistent symbol chip strip (Fincept/// "Pushpins" equivalent). Pins are user-scoped — they follow the user/// across workspaces and terminal sessions, stored in QSettings under/// "pushpins/list".diff --git a/fincept-qt/src/storage/secure/SecureStorage.cpp b/fincept-qt/src/storage/secure/SecureStorage.cppindex 83c785638..5777d70a0 100644--- a/fincept-qt/src/storage/secure/SecureStorage.cpp+++ b/fincept-qt/src/storage/secure/SecureStorage.cpp@@ -1,381 +1,283 @@#include "storage/secure/SecureStorage.h"#include "core/logging/Logger.h"+#include "storage/sqlite/Database.h"-// ── Platform-specific credential storage ──────────────────────────────────────+#include <QByteArray>+#include <QCryptographicHash>+#include <QMutex>+#include <QMutexLocker>+#include <QRandomGenerator>+#include <QSqlError>+#include <QSqlQuery>+#include <QSysInfo>++#include <openssl/err.h>+#include <openssl/evp.h>++// ── SQLite-backed credential store ───────────────────────────────────────────+//+// Values live in `secure_credentials` (created by migration v025) encrypted+// with AES-256-GCM. The 256-bit key is derived once per process from a+// machine-local seed and cached in static storage; rotating the seed (e.g.+// after copying the profile to another machine) makes the existing rows+// undecryptable, which is the desired behaviour.//-// Windows : Windows Credential Manager (DPAPI-backed, encrypted at rest)-// macOS : Security.framework SecItem API (SecItemAdd/Update/CopyMatching)-// Linux : libsecret / Secret Service when available (GNOME Keyring, KWallet-// via the Secret Service compatibility layer), falling back to-// XOR-obfuscated QSettings when libsecret is absent.-// The XOR fallback is NOT cryptographically secure — it only stops-// casual inspection. Build with libsecret-1-dev for production.--#ifdef Q_OS_WIN-# include <windows.h>-# include <wincred.h>-# include <wincrypt.h>-# pragma comment(lib, "Advapi32.lib")-#endif--#ifdef Q_OS_MAC-# include <CoreFoundation/CoreFoundation.h>-# include <Security/Security.h>-#endif--#if !defined(Q_OS_WIN) && !defined(Q_OS_MAC)-# include <QCryptographicHash>-# include <QSettings>-# include <QSysInfo>-# ifdef FINCEPT_HAVE_LIBSECRET-# include <libsecret/secret.h>-# endif-#endif+// Crypto is OpenSSL EVP — already linked transitively for Google Sheets JWT+// signing, so no new dependency. All EVP allocations are stack-bounded and+// freed on every exit path; no heap thrash on the hot path.static constexpr auto TAG = "SecureStorage";-static constexpr const char* kService = "com.fincept.terminal";namespace fincept {--SecureStorage& SecureStorage::instance() {- static SecureStorage s;--#if !defined(Q_OS_WIN) && !defined(Q_OS_MAC) && !defined(FINCEPT_HAVE_LIBSECRET)- // Warn once at startup when running on Linux without libsecret. Operators- // should install libsecret-1-dev and rebuild for production deployments.- static bool warned_once = false;- if (!warned_once) {- warned_once = true;- LOG_WARN(TAG,- "Linux credential storage is using XOR-obfuscated QSettings — "- "NOT cryptographically secure. Install libsecret-1-dev and rebuild "- "to enable the Secret Service (GNOME Keyring / KWallet) backend.");- }-#endif-- return s;+namespace {++constexpr int kKeyLen = 32; // AES-256+constexpr int kIvLen = 12; // GCM-recommended nonce size (RFC 5116 §5)+constexpr int kTagLen = 16; // GCM authentication tag (128 bits)++// Stable per-app salt mixed into the machine-ID hash so a different app+// on the same machine derives a different key. Bumping this rotates+// every key — only do that with a fresh DB.+constexpr const char* kAppSalt = "fincept-terminal/secure-storage/v1";++// Derive the AES-256 key once and cache. Called via QMutex so the first+// caller wins; subsequent calls return the cached buffer without rehashing.+const QByteArray& master_key() {+ static QMutex m;+ static QByteArray cached;+ QMutexLocker lock(&m);+ if (!cached.isEmpty())+ return cached;++ // Two stable inputs: the platform-provided machine ID (per-user on+ // macOS, per-machine on Windows/Linux) and the OS product type. The+ // app salt suffix prevents collisions with other apps that hash the+ // same identifiers.+ QByteArray seed;+ seed.append(QSysInfo::machineUniqueId());+ seed.append('\x1f');+ seed.append(QSysInfo::productType().toUtf8());+ seed.append('\x1f');+ seed.append(kAppSalt);++ cached = QCryptographicHash::hash(seed, QCryptographicHash::Sha256);+ Q_ASSERT(cached.size() == kKeyLen);+ return cached;}-// ─────────────────────────────────────────────────────────────────────────────-// Linux helpers-// ─────────────────────────────────────────────────────────────────────────────-#if !defined(Q_OS_WIN) && !defined(Q_OS_MAC)--#ifdef FINCEPT_HAVE_LIBSECRET--// Schema describing the structure of secrets we store. The single attribute-// "fincept-key" holds the per-secret name (e.g. FRED_API_KEY) so we can look-// it up later without scanning the whole keyring.-static const SecretSchema* fincept_schema() {- static const SecretSchema schema = {- "com.fincept.terminal",- SECRET_SCHEMA_NONE,- {- {"fincept-key", SECRET_SCHEMA_ATTRIBUTE_STRING},- {nullptr, SecretSchemaAttributeType(0)},- },- };- return &schema;+QByteArray random_iv() {+ QByteArray iv(kIvLen, '\0');+ QRandomGenerator* rng = QRandomGenerator::system();+ for (int i = 0; i < kIvLen; ++i)+ iv[i] = static_cast<char>(rng->bounded(256));+ return iv;}-#else // XOR fallback helpers+// AES-256-GCM encrypt. Returns ciphertext + the GCM tag through `tag_out`.+// On any OpenSSL error returns an empty QByteArray and logs — callers must+// check both isEmpty() AND tag_out.size() == kTagLen before persisting.+QByteArray aes_gcm_encrypt(const QByteArray& key, const QByteArray& iv,+ const QByteArray& plaintext, QByteArray& tag_out) {+ EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new();+ if (!ctx)+ return {};-// Derive a machine-unique obfuscation key from stable system identifiers.-// Not a secret — just prevents the file being readable at a glance.-static QByteArray machine_key() {- const QString seed = QSysInfo::machineUniqueId() + QSysInfo::productType()- + QLatin1String(kService);- return QCryptographicHash::hash(seed.toUtf8(), QCryptographicHash::Sha256);+ QByteArray out;+ bool ok = false;+ do {+ if (1 != EVP_EncryptInit_ex(ctx, EVP_aes_256_gcm(), nullptr, nullptr, nullptr))+ break;+ if (1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, kIvLen, nullptr))+ break;+ if (1 != EVP_EncryptInit_ex(ctx, nullptr, nullptr,+ reinterpret_cast<const unsigned char*>(key.constData()),+ reinterpret_cast<const unsigned char*>(iv.constData())))+ break;++ // Reserve plaintext.size() + block size; AES has 16-byte blocks but+ // GCM is a stream cipher (CTR-mode under the hood) so output length+ // equals input length. The +16 margin keeps us safe if EVP ever+ // reports cipher block size for compatibility reasons.+ out.resize(plaintext.size() + 16);+ int len = 0;+ if (1 != EVP_EncryptUpdate(ctx,+ reinterpret_cast<unsigned char*>(out.data()), &len,+ reinterpret_cast<const unsigned char*>(plaintext.constData()),+ plaintext.size()))+ break;+ int written = len;++ if (1 != EVP_EncryptFinal_ex(ctx,+ reinterpret_cast<unsigned char*>(out.data()) + written,+ &len))+ break;+ written += len;+ out.resize(written);++ tag_out.resize(kTagLen);+ if (1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, kTagLen, tag_out.data()))+ break;++ ok = true;+ } while (false);++ EVP_CIPHER_CTX_free(ctx);+ if (!ok) {+ LOG_ERROR(TAG, QString("AES-GCM encrypt failed: OpenSSL err 0x%1")+ .arg(ERR_get_error(), 0, 16));+ return {};+ }+ return out;}-static QByteArray xor_obfuscate(const QByteArray& data) {- const QByteArray key = machine_key();+// AES-256-GCM decrypt with tag verification. Returns plaintext on success or+// an empty QByteArray if the tag doesn't verify (tampered ciphertext, wrong+// machine, corrupted DB row). Callers must NOT use the returned bytes if+// `ok_out` is false — an empty QByteArray is also a valid plaintext.+QByteArray aes_gcm_decrypt(const QByteArray& key, const QByteArray& iv,+ const QByteArray& ciphertext, const QByteArray& tag,+ bool& ok_out) {+ ok_out = false;+ if (iv.size() != kIvLen || tag.size() != kTagLen)+ return {};++ EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new();+ if (!ctx)+ return {};+QByteArray out;- out.resize(data.size());- for (int i = 0; i < data.size(); ++i)- out[i] = static_cast<char>(- static_cast<unsigned char>(data[i]) ^- static_cast<unsigned char>(key[i % key.size()]));+ do {+ if (1 != EVP_DecryptInit_ex(ctx, EVP_aes_256_gcm(), nullptr, nullptr, nullptr))+ break;+ if (1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, kIvLen, nullptr))+ break;+ if (1 != EVP_DecryptInit_ex(ctx, nullptr, nullptr,+ reinterpret_cast<const unsigned char*>(key.constData()),+ reinterpret_cast<const unsigned char*>(iv.constData())))+ break;++ out.resize(ciphertext.size() + 16);+ int len = 0;+ if (1 != EVP_DecryptUpdate(ctx,+ reinterpret_cast<unsigned char*>(out.data()), &len,+ reinterpret_cast<const unsigned char*>(ciphertext.constData()),+ ciphertext.size()))+ break;+ int written = len;++ // EVP_CTRL_GCM_SET_TAG must be called before EVP_DecryptFinal_ex —+ // Final is what actually verifies the tag and returns 0 on mismatch.+ if (1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, kTagLen,+ const_cast<char*>(tag.constData())))+ break;++ if (1 != EVP_DecryptFinal_ex(ctx,+ reinterpret_cast<unsigned char*>(out.data()) + written,+ &len))+ break; // tag mismatch — leave ok_out=false+ written += len;+ out.resize(written);+ ok_out = true;+ } while (false);++ EVP_CIPHER_CTX_free(ctx);return out;}-#endif // FINCEPT_HAVE_LIBSECRET-#endif // Linux helpers+} // anonymous namespace-// ─────────────────────────────────────────────────────────────────────────────-// store-// ─────────────────────────────────────────────────────────────────────────────+SecureStorage& SecureStorage::instance() {+ static SecureStorage s;+ return s;+}Result<void> SecureStorage::store(const QString& key, const QString& value) {-#ifdef Q_OS_WIN- // Windows Credential Manager — DPAPI-encrypted, user-scoped- std::wstring target = L"FinceptTerminal/" + key.toStdWString();- QByteArray data = value.toUtf8();-- CREDENTIALW cred = {};- cred.Type = CRED_TYPE_GENERIC;- cred.TargetName = const_cast<LPWSTR>(target.c_str());- cred.CredentialBlobSize = static_cast<DWORD>(data.size());- cred.CredentialBlob = reinterpret_cast<LPBYTE>(data.data());- cred.Persist = CRED_PERSIST_LOCAL_MACHINE;-- if (!CredWriteW(&cred, 0)) {- LOG_ERROR(TAG, "CredWriteW failed for key: " + key);- return Result<void>::err("Failed to store credential");+ auto& db = Database::instance();+ if (!db.is_open()) {+ LOG_ERROR(TAG, "SecureStorage::store called before Database::open()");+ return Result<void>::err("Database not open");}- return Result<void>::ok();-#elif defined(Q_OS_MAC)- // macOS Keychain via modern SecItem API. Try SecItemUpdate first; if no- // existing item, fall through to SecItemAdd. Any other status is logged- // (it indicates a real Keychain problem we don't want to silently mask- // by overwriting with Add).- const QByteArray svc_bytes = QByteArray(kService);- const QByteArray acct_bytes = key.toUtf8();- const QByteArray data_bytes = value.toUtf8();-- CFStringRef service = CFStringCreateWithBytes(- nullptr, reinterpret_cast<const UInt8*>(svc_bytes.constData()),- svc_bytes.size(), kCFStringEncodingUTF8, false);- CFStringRef account = CFStringCreateWithBytes(- nullptr, reinterpret_cast<const UInt8*>(acct_bytes.constData()),- acct_bytes.size(), kCFStringEncodingUTF8, false);- CFDataRef secret_data = CFDataCreate(- nullptr, reinterpret_cast<const UInt8*>(data_bytes.constData()),- static_cast<CFIndex>(data_bytes.size()));-- const void* find_keys[] = {kSecClass, kSecAttrService, kSecAttrAccount};- const void* find_vals[] = {kSecClassGenericPassword, service, account};- CFDictionaryRef find_query = CFDictionaryCreate(- nullptr, find_keys, find_vals, 3,- &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);-- const void* upd_keys[] = {kSecValueData};- const void* upd_vals[] = {secret_data};- CFDictionaryRef upd_attrs = CFDictionaryCreate(- nullptr, upd_keys, upd_vals, 1,- &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);-- OSStatus status = SecItemUpdate(find_query, upd_attrs);- CFRelease(upd_attrs);-- if (status == errSecItemNotFound) {- // No existing item — add a new one.- const void* add_keys[] = {kSecClass, kSecAttrService, kSecAttrAccount, kSecValueData};- const void* add_vals[] = {kSecClassGenericPassword, service, account, secret_data};- CFDictionaryRef add_attrs = CFDictionaryCreate(- nullptr, add_keys, add_vals, 4,- &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);- status = SecItemAdd(add_attrs, nullptr);- CFRelease(add_attrs);- } else if (status != errSecSuccess) {- // Update returned an unexpected status — log it. Do NOT fall through- // to Add: if the item exists but Update is rejected (ACL, locked- // keychain, etc.) the right answer is to surface the failure, not- // create a duplicate item.- LOG_WARN(TAG, QString("SecItemUpdate returned unexpected OSStatus %1 for key %2")- .arg(status).arg(key));+ const QByteArray plaintext = value.toUtf8();+ const QByteArray iv = random_iv();+ QByteArray tag;+ const QByteArray ciphertext = aes_gcm_encrypt(master_key(), iv, plaintext, tag);+ if (tag.size() != kTagLen) {+ // aes_gcm_encrypt already logged the OpenSSL error.+ return Result<void>::err("Encryption failed");}- CFRelease(find_query);- CFRelease(secret_data);- CFRelease(account);- CFRelease(service);-- if (status != errSecSuccess) {- LOG_ERROR(TAG, QString("Keychain store failed (OSStatus %1) for key: %2")- .arg(status).arg(key));- return Result<void>::err("Failed to store in Keychain");- }- return Result<void>::ok();--#else-# ifdef FINCEPT_HAVE_LIBSECRET- // Linux — Secret Service (GNOME Keyring / KWallet compatibility layer).- GError* err = nullptr;- const QByteArray key_bytes = key.toUtf8();- const QByteArray val_bytes = value.toUtf8();- const QByteArray label = ("Fincept Terminal: " + key).toUtf8();-- secret_password_store_sync(- fincept_schema(),- SECRET_COLLECTION_DEFAULT,- label.constData(),- val_bytes.constData(),- nullptr,- &err,- "fincept-key", key_bytes.constData(),- nullptr);-- if (err) {- QString msg = QString::fromUtf8(err->message);- g_error_free(err);- LOG_ERROR(TAG, "libsecret store failed for key " + key + ": " + msg);- return Result<void>::err("Failed to store in Secret Service: " + msg.toStdString());+ QSqlQuery q(db.raw_db());+ q.prepare(R"sql(+ INSERT INTO secure_credentials (key, ciphertext, iv, tag, updated_at)+ VALUES (?, ?, ?, ?, datetime('now'))+ ON CONFLICT(key) DO UPDATE SET+ ciphertext = excluded.ciphertext,+ iv = excluded.iv,+ tag = excluded.tag,+ updated_at = excluded.updated_at+ )sql");+ q.addBindValue(key);+ q.addBindValue(ciphertext);+ q.addBindValue(iv);+ q.addBindValue(tag);+ if (!q.exec()) {+ LOG_ERROR(TAG, QString("SQL upsert failed for key %1: %2")+ .arg(key, q.lastError().text()));+ return Result<void>::err("Failed to write credential row");}return Result<void>::ok();--# else- // XOR-obfuscated QSettings fallback — NOT cryptographically secure.- QSettings s("Fincept", "FinceptTerminal-Secure");- const QByteArray obfuscated = xor_obfuscate(value.toUtf8()).toBase64();- s.setValue("secure/" + key, QString::fromLatin1(obfuscated));- return Result<void>::ok();-# endif-#endif}-// ─────────────────────────────────────────────────────────────────────────────-// retrieve-// ─────────────────────────────────────────────────────────────────────────────-Result<QString> SecureStorage::retrieve(const QString& key) {-#ifdef Q_OS_WIN- std::wstring target = L"FinceptTerminal/" + key.toStdWString();- PCREDENTIALW cred = nullptr;-- if (!CredReadW(target.c_str(), CRED_TYPE_GENERIC, 0, &cred)) {- return Result<QString>::err("Credential not found");- }-- QString value = QString::fromUtf8(reinterpret_cast<const char*>(cred->CredentialBlob),- static_cast<int>(cred->CredentialBlobSize));- CredFree(cred);- return Result<QString>::ok(value);--#elif defined(Q_OS_MAC)- const QByteArray svc_bytes = QByteArray(kService);- const QByteArray acct_bytes = key.toUtf8();-- CFStringRef service = CFStringCreateWithBytes(- nullptr, reinterpret_cast<const UInt8*>(svc_bytes.constData()),- svc_bytes.size(), kCFStringEncodingUTF8, false);- CFStringRef account = CFStringCreateWithBytes(- nullptr, reinterpret_cast<const UInt8*>(acct_bytes.constData()),- acct_bytes.size(), kCFStringEncodingUTF8, false);-- const void* keys[] = {kSecClass, kSecAttrService, kSecAttrAccount,- kSecReturnData, kSecMatchLimit};- const void* vals[] = {kSecClassGenericPassword, service, account,- kCFBooleanTrue, kSecMatchLimitOne};- CFDictionaryRef query = CFDictionaryCreate(- nullptr, keys, vals, 5,- &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);-- CFTypeRef result_ref = nullptr;- OSStatus status = SecItemCopyMatching(query, &result_ref);- CFRelease(query);- CFRelease(account);- CFRelease(service);-- if (status != errSecSuccess || !result_ref) {- return Result<QString>::err("Credential not found in Keychain");+ auto& db = Database::instance();+ if (!db.is_open())+ return Result<QString>::err("Database not open");++ QSqlQuery q(db.raw_db());+ q.prepare("SELECT ciphertext, iv, tag FROM secure_credentials WHERE key = ?");+ q.addBindValue(key);+ if (!q.exec()) {+ LOG_ERROR(TAG, QString("SQL select failed for key %1: %2")+ .arg(key, q.lastError().text()));+ return Result<QString>::err("Read failed");}-- CFDataRef data = static_cast<CFDataRef>(result_ref);- QString value = QString::fromUtf8(- reinterpret_cast<const char*>(CFDataGetBytePtr(data)),- static_cast<int>(CFDataGetLength(data)));- CFRelease(result_ref);- return Result<QString>::ok(value);--#else-# ifdef FINCEPT_HAVE_LIBSECRET- GError* err = nullptr;- const QByteArray key_bytes = key.toUtf8();-- gchar* password = secret_password_lookup_sync(- fincept_schema(),- nullptr,- &err,- "fincept-key", key_bytes.constData(),- nullptr);-- if (err) {- QString msg = QString::fromUtf8(err->message);- g_error_free(err);- return Result<QString>::err("libsecret lookup failed: " + msg.toStdString());- }- if (!password) {- return Result<QString>::err("Not found");- }-- QString value = QString::fromUtf8(password);- secret_password_free(password);- return Result<QString>::ok(value);--# else- QSettings s("Fincept", "FinceptTerminal-Secure");- QVariant v = s.value("secure/" + key);- if (!v.isValid())+ if (!q.next())return Result<QString>::err("Not found");- const QByteArray raw = QByteArray::fromBase64(v.toString().toLatin1());- if (raw.isEmpty())+ const QByteArray ciphertext = q.value(0).toByteArray();+ const QByteArray iv = q.value(1).toByteArray();+ const QByteArray tag = q.value(2).toByteArray();++ bool ok = false;+ const QByteArray plaintext = aes_gcm_decrypt(master_key(), iv, ciphertext, tag, ok);+ if (!ok) {+ // Tag mismatch — either the row is corrupted, the ciphertext was+ // tampered with, or the profile was copied from another machine.+ // Surface as a plain "not found" so the caller's recovery path+ // (re-prompt for PIN, re-login, etc.) kicks in cleanly. Logged as+ // WARN so a forensic reader can still see it happened.+ LOG_WARN(TAG, QString("AES-GCM tag mismatch for key %1 — row unreadable").arg(key));return Result<QString>::err("Not found");- return Result<QString>::ok(QString::fromUtf8(xor_obfuscate(raw)));-# endif-#endif+ }+ return Result<QString>::ok(QString::fromUtf8(plaintext));}-// ─────────────────────────────────────────────────────────────────────────────-// remove-// ─────────────────────────────────────────────────────────────────────────────-Result<void> SecureStorage::remove(const QString& key) {-#ifdef Q_OS_WIN- std::wstring target = L"FinceptTerminal/" + key.toStdWString();- if (!CredDeleteW(target.c_str(), CRED_TYPE_GENERIC, 0)) {- return Result<void>::err("Failed to delete credential");+ auto& db = Database::instance();+ if (!db.is_open())+ return Result<void>::err("Database not open");++ QSqlQuery q(db.raw_db());+ q.prepare("DELETE FROM secure_credentials WHERE key = ?");+ q.addBindValue(key);+ if (!q.exec()) {+ LOG_ERROR(TAG, QString("SQL delete failed for key %1: %2")+ .arg(key, q.lastError().text()));+ return Result<void>::err("Delete failed");}return Result<void>::ok();--#elif defined(Q_OS_MAC)- const QByteArray svc_bytes = QByteArray(kService);- const QByteArray acct_bytes = key.toUtf8();-- CFStringRef service = CFStringCreateWithBytes(- nullptr, reinterpret_cast<const UInt8*>(svc_bytes.constData()),- svc_bytes.size(), kCFStringEncodingUTF8, false);- CFStringRef account = CFStringCreateWithBytes(- nullptr, reinterpret_cast<const UInt8*>(acct_bytes.constData()),- acct_bytes.size(), kCFStringEncodingUTF8, false);-- const void* keys[] = {kSecClass, kSecAttrService, kSecAttrAccount};- const void* vals[] = {kSecClassGenericPassword, service, account};- CFDictionaryRef query = CFDictionaryCreate(- nullptr, keys, vals, 3,- &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);-- SecItemDelete(query);- CFRelease(query);- CFRelease(account);- CFRelease(service);- return Result<void>::ok();--#else-# ifdef FINCEPT_HAVE_LIBSECRET- GError* err = nullptr;- const QByteArray key_bytes = key.toUtf8();-- secret_password_clear_sync(- fincept_schema(),- nullptr,- &err,- "fincept-key", key_bytes.constData(),- nullptr);-- if (err)- g_error_free(err); // not fatal — item may simply not have existed- return Result<void>::ok();--# else- QSettings s("Fincept", "FinceptTerminal-Secure");- s.remove("secure/" + key);- return Result<void>::ok();-# endif-#endif}} // namespace finceptdiff --git a/fincept-qt/src/storage/secure/SecureStorage.h b/fincept-qt/src/storage/secure/SecureStorage.hindex 5cf6bb2c5..103b50fa6 100644--- a/fincept-qt/src/storage/secure/SecureStorage.h+++ b/fincept-qt/src/storage/secure/SecureStorage.h@@ -5,22 +5,31 @@namespace fincept {-/// Secure credential storage using OS-native backends:-/// 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.+/// Local credential store backed by SQLite + AES-256-GCM.+///+/// Values are encrypted with a 256-bit key derived once per process from+/// machine-local identifiers (`QSysInfo::machineUniqueId()` + a fixed app+/// salt, hashed with SHA-256). Each row carries its own random 96-bit IV+/// and 128-bit GCM authentication tag, so a tampered ciphertext fails+/// `retrieve()` rather than returning corrupted plaintext.+///+/// Threat model — what this protects against:+/// * Casual `grep` / inspection of the on-disk SQLite file.+/// * Profile copies moved to a different machine — the key derives from+/// the source machine's ID and won't decrypt elsewhere.+/// * Bit-flips or partial writes — GCM tag verification rejects them.+///+/// What this does NOT protect against:+/// * Another process running as the same user on the same machine — it+/// can read the DB file and re-derive the key from the same machine ID.+/// This matches the previous Linux fallback's threat model.+/// * Forensic tools that dump kernel memory while the app is running.+/// * Targeted malware that knows where to look.+///+/// Latency: AES-NI / ARM-Crypto-Extensions accelerate AES-GCM in hardware+/// on every supported CPU. Per-call cost is dominated by the SQLite write,+/// not the crypto — typically well under 1ms for the values we store+/// (PIN hash, API tokens, session IDs).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.hindex 3d7affd0b..6a26b59ae 100644--- a/fincept-qt/src/storage/sqlite/migrations/MigrationRunner.h+++ b/fincept-qt/src/storage/sqlite/migrations/MigrationRunner.h@@ -71,5 +71,6 @@ void register_migration_v021();void register_migration_v022();void register_migration_v023();void register_migration_v024();+void register_migration_v025();} // namespace finceptdiff --git a/fincept-qt/src/storage/sqlite/migrations/v025_secure_credentials.cpp b/fincept-qt/src/storage/sqlite/migrations/v025_secure_credentials.cppnew file mode 100644index 000000000..ddc7a58ae--- /dev/null+++ b/fincept-qt/src/storage/sqlite/migrations/v025_secure_credentials.cpp@@ -0,0 +1,48 @@+// v025_secure_credentials — pure-SQL credential store backing SecureStorage.+//+// Replaces the OS-native keychain backends (Windows Credential Manager,+// macOS Keychain via SecItem, Linux libsecret/QSettings). Values are+// encrypted at rest with AES-256-GCM; the key is derived from machine-local+// identifiers in SecureStorage.cpp. Schema is intentionally minimal — every+// column is needed to decrypt. `iv` is the AES-GCM nonce (12 bytes) and+// `tag` is the authentication tag (16 bytes); both are stored alongside the+// ciphertext per NIST SP 800-38D.++#include "storage/sqlite/migrations/MigrationRunner.h"++#include <QSqlError>+#include <QSqlQuery>++namespace fincept {+namespace {++static Result<void> v025_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_v025(QSqlDatabase& db) {+ auto r = v025_sql(db, R"sql(+ CREATE TABLE IF NOT EXISTS secure_credentials (+ key TEXT PRIMARY KEY,+ ciphertext BLOB NOT NULL,+ iv BLOB NOT NULL,+ tag BLOB NOT NULL,+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP+ )+ )sql");+ return r;+}++} // anonymous namespace++void register_migration_v025() {+ static bool done = false;+ if (done) return;+ done = true;+ MigrationRunner::register_migration({25, "secure_credentials", apply_v025});+}++} // namespace finceptdiff --git a/fincept-qt/src/storage/workspace/WorkspaceFwspImporter.cpp b/fincept-qt/src/storage/workspace/WorkspaceFwspImporter.cppindex 42c71de95..c7a828c9c 100644--- a/fincept-qt/src/storage/workspace/WorkspaceFwspImporter.cpp+++ b/fincept-qt/src/storage/workspace/WorkspaceFwspImporter.cpp@@ -21,7 +21,7 @@ constexpr const char* kFlagKey = "fwsp_import_done";} // namespacevoid WorkspaceFwspImporter::run_once_if_needed() {- auto done = LayoutCatalog::instance().meta(QStringLiteral(kFlagKey));+ auto done = LayoutCatalog::instance().meta(QString::fromLatin1(kFlagKey));if (done.is_ok() && done.value() == QStringLiteral("1")) {// Already imported — fast path.return;@@ -31,7 +31,7 @@ void WorkspaceFwspImporter::run_once_if_needed() {QDir d(dir_path);if (!d.exists()) {// Nothing to import; mark done so we don't keep checking.- LayoutCatalog::instance().set_meta(QStringLiteral(kFlagKey), QStringLiteral("1"));+ LayoutCatalog::instance().set_meta(QString::fromLatin1(kFlagKey), QStringLiteral("1"));return;}@@ -80,7 +80,7 @@ void WorkspaceFwspImporter::run_once_if_needed() {++skipped;}- LayoutCatalog::instance().set_meta(QStringLiteral(kFlagKey), QStringLiteral("1"));+ LayoutCatalog::instance().set_meta(QString::fromLatin1(kFlagKey), QStringLiteral("1"));LOG_INFO(kTag, QString("Imported %1 legacy workspace name(s); %2 skipped").arg(imported).arg(skipped));}diff --git a/fincept-qt/src/storage/workspace/WorkspaceSnapshotRing.cpp b/fincept-qt/src/storage/workspace/WorkspaceSnapshotRing.cppindex b3f25623c..417883dba 100644--- a/fincept-qt/src/storage/workspace/WorkspaceSnapshotRing.cpp+++ b/fincept-qt/src/storage/workspace/WorkspaceSnapshotRing.cpp@@ -147,6 +147,20 @@ Result<void> WorkspaceSnapshotRing::erase(qint64 snapshot_id) {return Result<void>::ok();}+Result<void> WorkspaceSnapshotRing::rename(qint64 snapshot_id, const QString& name) {+ if (!db_ || !db_->is_open())+ return Result<void>::err("WorkspaceDb not open");+ // Empty name → store NULL so the dialog falls back to the auto-generated+ // timestamp label. Trimming protects against whitespace-only renames.+ const QString trimmed = name.trimmed();+ QVariant value = trimmed.isEmpty() ? QVariant() : QVariant(trimmed);+ auto r = db_->execute("UPDATE workspace_snapshot SET name = ? WHERE snapshot_id = ?",+ {value, snapshot_id});+ if (r.is_err())+ return Result<void>::err(r.error());+ return Result<void>::ok();+}+Result<void> WorkspaceSnapshotRing::trim_auto() {if (!db_ || !db_->is_open())return Result<void>::err("WorkspaceDb not open");diff --git a/fincept-qt/src/storage/workspace/WorkspaceSnapshotRing.h b/fincept-qt/src/storage/workspace/WorkspaceSnapshotRing.hindex 2102f9a57..81422d7b6 100644--- a/fincept-qt/src/storage/workspace/WorkspaceSnapshotRing.h+++ b/fincept-qt/src/storage/workspace/WorkspaceSnapshotRing.h@@ -87,6 +87,10 @@ class WorkspaceSnapshotRing {/// Drop one snapshot. Used when the user dismisses a stale recovery row.Result<void> erase(qint64 snapshot_id);+ /// Set or clear the user-visible name on a snapshot. Pass an empty string+ /// to clear (stored as NULL). Used by the recovery dialog's rename action.+ Result<void> rename(qint64 snapshot_id, const QString& name);+/// Trim auto rows so at most `max_auto` remain. Called automatically/// inside `add()` after each successful auto insert. Exposed for tests.Result<void> trim_auto();diff --git a/fincept-qt/src/trading/ExchangeSessionManager.h b/fincept-qt/src/trading/ExchangeSessionManager.hindex 2066aa985..b721032b1 100644--- a/fincept-qt/src/trading/ExchangeSessionManager.h+++ b/fincept-qt/src/trading/ExchangeSessionManager.h@@ -2,7 +2,7 @@// ExchangeSessionManager — registry of live ExchangeSession objects.//// Lazy-creates one ExchangeSession per exchange id on demand. Sessions stay-// warm for the application lifetime (Bloomberg-style) — switching exchanges+// warm for the application lifetime (Fincept-style) — switching exchanges// does not tear down the previous session's WS stream. This buys sub-500ms// exchange switches because the daemon + WS handshake were already paid.//diff --git a/fincept-qt/src/ui/command/CommandParser.cpp b/fincept-qt/src/ui/command/CommandParser.cppindex 3ff92191f..da5080a61 100644--- a/fincept-qt/src/ui/command/CommandParser.cpp+++ b/fincept-qt/src/ui/command/CommandParser.cpp@@ -9,8 +9,7 @@ namespace fincept::ui {namespace {-// Tokenise respecting double-quoted strings: `layout switch "Earnings Day"`-// → ["layout", "switch", "Earnings Day"].+/// Splits on whitespace but preserves double-quoted strings as single tokens.QStringList tokenise(const QString& s) {QStringList out;QString cur;@@ -49,29 +48,21 @@ ParsedCommand CommandParser::parse(const QString& input) {return p;}- // Function-code precedence first. A bare uppercase token (with optional- // dots/underscores/digits) is more likely a Bloomberg-style code or a- // ticker than a verb. Verbs typically start lowercase or have a space.auto fc = try_function_code_(trimmed);if (fc.kind != ParsedCommand::Kind::Unknown && fc.kind != ParsedCommand::Kind::Empty)return fc;- // Else fall through to verb-object.return try_verb_object_(trimmed);}ParsedCommand CommandParser::try_function_code_(const QString& input) {- // Match: alphanumeric/digit-led single token, no spaces, no dots either- // (a dotted form like "layout.switch" is the action-id form, handled- // by verb-object). Examples that match: AAPL, MSFT, 1, 25, WEI.+ // Single token without dots — dotted forms go through verb-object.static const QRegularExpression rx(R"(^[A-Z0-9][A-Z0-9_]*$)",QRegularExpression::CaseInsensitiveOption);if (!rx.match(input).hasMatch())return ParsedCommand{ParsedCommand::Kind::Unknown, {}, {}, input, {}};- // Two paths — try ActionRegistry first (for registered numeric/short- // codes if any), else treat as a symbol publish.const QString upper = input.toUpper();if (auto* action = ActionRegistry::instance().find(upper.toLower())) {ParsedCommand p;@@ -80,8 +71,6 @@ ParsedCommand CommandParser::try_function_code_(const QString& input) {return p;}- // Treat as symbol. Caller maps to link.publish_to_group with the active- // (or first enabled) group.ParsedCommand p;p.kind = ParsedCommand::Kind::Symbol;p.raw_remainder = upper;@@ -95,9 +84,7 @@ ParsedCommand CommandParser::try_verb_object_(const QString& input) {return ParsedCommand{ParsedCommand::Kind::Empty, {}, {}, {}, {}};}- // Greedy match: try the longest prefix as a dotted action id.- // "layout switch foo" → try "layout.switch.foo", "layout.switch", "layout".- // First registered match wins.+ // Greedy: longest prefix wins. "layout switch foo" → tries "layout.switch.foo", then "layout.switch", then "layout".auto& reg = ActionRegistry::instance();for (int n = tokens.size(); n > 0; --n) {QStringList prefix = tokens.mid(0, n);@@ -113,8 +100,6 @@ ParsedCommand CommandParser::try_verb_object_(const QString& input) {}}- // No prefix matched — also try matching aliases. Cheaper to walk all- // actions once with their full-string display + alias forms.for (const QString& id : reg.all_ids()) {const ActionDef* def = reg.find(id);if (!def) continue;@@ -145,8 +130,7 @@ QVariantMap CommandParser::bind_positional_(const QList<ParameterSlot>& slot_lisconst ParameterSlot& slot = slot_list.at(i);out.insert(slot.name, positionals.at(i));}- // Defaults for required slots that weren't supplied. Caller's predicate- // / handler should detect missing required args.+ // Apply slot defaults. Handler validates required slots.for (int i = positionals.size(); i < slot_list.size(); ++i) {const ParameterSlot& slot = slot_list.at(i);if (slot.default_value.isValid())diff --git a/fincept-qt/src/ui/command/CommandParser.h b/fincept-qt/src/ui/command/CommandParser.hindex d6df18f0d..4ba43f432 100644--- a/fincept-qt/src/ui/command/CommandParser.h+++ b/fincept-qt/src/ui/command/CommandParser.h@@ -6,49 +6,33 @@namespace fincept::ui {-/// Phase 9 / decision 7.2: dual-grammar command parser.-///-/// Two parses tried in priority order:-/// 1. **Function-code precedence**: input matching `^[A-Z][A-Z0-9._]*$`-/// or starting with a digit (Bloomberg "1<GO>", "WEI") is treated-/// as a function code. We resolve via ActionRegistry::match() and-/// symbol lookup. (For v1 we treat un-claimed-by-action input as-/// a symbol publish via `link.publish_to_group` to the active group.)-/// 2. **Verb-object**: `<verb> [args...]`. The verb is the action id-/// ("layout switch") with spaces collapsed to dots-/// ("layout.switch"); remaining tokens become positional args-/// mapped to the action's ParameterSlot list.-///-/// The parser returns a `Parse` describing which path matched, the-/// resolved action_id, and the bag of args ready to feed `CommandContext`.-/// Callers (CommandBar / CommandPalette) call `ActionRegistry::invoke`.+/// Dual-grammar command parser.+/// Tries function-code (^[A-Z][A-Z0-9._]*$ or leading digit) first, then verb-object ("layout switch" → "layout.switch").+/// Pure — does not invoke. Caller dispatches via ActionRegistry::invoke.struct ParsedCommand {enum class Kind {Empty,- Action, ///< matched a registered action; invoke directly- Symbol, ///< looks like a ticker — caller may route to link.publish_to_group- Help, ///< user typed `?` → caller shows the cheat sheet+ Action,+ Symbol, ///< ticker-shaped — caller may route to link.publish_to_group+ Help, ///< user typed `?`Unknown,};Kind kind = Kind::Empty;QString action_id;QVariantMap args;- QString raw_remainder; ///< text after the verb (or the whole input for Symbol)- QString error; ///< populated when kind==Unknown to surface a hint+ QString raw_remainder;+ QString error;};class CommandParser {public:- /// Pure function. Reads ActionRegistry to resolve verb-object matches.- /// Does NOT invoke the action.static ParsedCommand parse(const QString& input);private:static ParsedCommand try_function_code_(const QString& input);static ParsedCommand try_verb_object_(const QString& input);- /// Map positional tokens to parameter slot names. The first N tokens- /// fill the first N slots in declaration order.+ /// First N positionals fill the first N slots in declaration order.static QVariantMap bind_positional_(const QList<ParameterSlot>& slot_list,const QStringList& positionals);};diff --git a/fincept-qt/src/ui/command/QuickCommandBar.h b/fincept-qt/src/ui/command/QuickCommandBar.hindex d80f6dbf4..09bab9a51 100644--- a/fincept-qt/src/ui/command/QuickCommandBar.h+++ b/fincept-qt/src/ui/command/QuickCommandBar.h@@ -8,23 +8,15 @@ class QLabel;namespace fincept::ui {-/// Phase 9: persistent status-line command input on every frame.-/// Reads `ActionRegistry`, parses with `CommandParser`, invokes via-/// `ActionRegistry::invoke(id, ctx)`. Bloomberg-style "just type" UX.-///-/// Sits at the bottom of WindowFrame above the status bar. Hidden by-/// default — toggle with Ctrl+\ or via the `cmdbar.toggle` action.-/// Phase 9 follow-up adds inline autocomplete + ?-prefix help.+/// "Just type" command input above the status bar. Hidden by default; toggle with Ctrl+\ or `cmdbar.toggle`.class QuickCommandBar : public QFrame {Q_OBJECTpublic:explicit QuickCommandBar(QWidget* parent = nullptr);- /// Toggle visibility. Focuses the input on show.void toggle_visible();- /// Surface the bar (show + focus). Used when palette/launchpad- /// dispatch a "type a command" action.+ /// Show + focus. Used by palette/launchpad "type a command" dispatch.void surface();private:diff --git a/fincept-qt/src/ui/components/ComponentBrowserDialog.h b/fincept-qt/src/ui/components/ComponentBrowserDialog.hindex 1c208d9dc..fb25e03ec 100644--- a/fincept-qt/src/ui/components/ComponentBrowserDialog.h+++ b/fincept-qt/src/ui/components/ComponentBrowserDialog.h@@ -12,28 +12,14 @@ 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).+/// Modal browser of registered screens. Cards sorted by popularity desc; search matches title+tags.class ComponentBrowserDialog : public QDialog {Q_OBJECTpublic:explicit ComponentBrowserDialog(QWidget* parent = nullptr);signals:- /// Emitted when the user double-clicks a card or presses Enter.- /// The caller (WindowFrame) is expected to navigate to the screen.- /// The dialog closes itself after emitting.+ /// Dialog closes itself after emitting; caller navigates.void component_chosen(const QString& screen_id);private:diff --git a/fincept-qt/src/ui/components/ComponentCard.cpp b/fincept-qt/src/ui/components/ComponentCard.cppindex 2cda7fb7e..11b391917 100644--- a/fincept-qt/src/ui/components/ComponentCard.cpp+++ b/fincept-qt/src/ui/components/ComponentCard.cpp@@ -12,14 +12,8 @@ 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"; // amberif (category == "Trading") return "#16a34a"; // green@@ -33,10 +27,8 @@ QString category_color(const QString& category) {return "#4b5563";}+/// Logarithmic thresholds: one star after a couple visits, five at 150+.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;@@ -67,7 +59,6 @@ void ComponentCard::build_ui() {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)));@@ -101,7 +92,7 @@ void ComponentCard::build_ui() {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+ desc->setMaximumHeight(36);bl->addWidget(desc);bl->addStretch(1);@@ -148,13 +139,10 @@ void ComponentCard::mouseMoveEvent(QMouseEvent* e) {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+ mime->setText(meta_.title); // fallback for generic text targetsdrag->setMimeData(mime);drag->exec(Qt::CopyAction, Qt::CopyAction);}diff --git a/fincept-qt/src/ui/navigation/StatusBar.h b/fincept-qt/src/ui/navigation/StatusBar.hindex a49f788be..6502b226c 100644--- a/fincept-qt/src/ui/navigation/StatusBar.h+++ b/fincept-qt/src/ui/navigation/StatusBar.h@@ -10,8 +10,7 @@ enum class SymbolGroup : char;namespace fincept::ui {-/// Bottom status bar — version, feed indicators, ready status, and the-/// Phase 7-polish active-symbol indicator.+/// Bottom status bar: version, feed indicators, ready status, active-symbol indicator.class StatusBar : public QWidget {Q_OBJECTpublic:@@ -21,12 +20,7 @@ class StatusBar : public QWidget {private:void refresh_theme();- /// Phase 7 polish: subscribe to SymbolContext to display the most-- /// recently-published symbol + which colour group it lives in.- /// Bloomberg's bottom bar shows the active security; this is the- /// equivalent. Drives off SymbolContext::active_symbol_changed- /// (which fires whenever any panel anywhere publishes via- /// set_group_symbol).+ /// Subscribes to SymbolContext::active_symbol_changed to mirror the most recent group publish.void wire_link_indicator();void update_link_label(SymbolGroup g, const SymbolRef& ref);diff --git a/fincept-qt/src/ui/navigation/ToolBar.cpp b/fincept-qt/src/ui/navigation/ToolBar.cppindex bd5bc059a..cf091c160 100644--- a/fincept-qt/src/ui/navigation/ToolBar.cpp+++ b/fincept-qt/src/ui/navigation/ToolBar.cpp@@ -43,7 +43,6 @@ ToolBar::ToolBar(QWidget* parent) : QWidget(parent) {hl->setContentsMargins(4, 0, 6, 0);hl->setSpacing(0);- // Menusmenu_bar_ = new QMenuBar(this);menu_bar_->setStyleSheet(menu_ss());menu_bar_->addMenu(build_file_menu());@@ -52,7 +51,6 @@ ToolBar::ToolBar(QWidget* parent) : QWidget(parent) {menu_bar_->addMenu(build_help_menu());hl->addWidget(menu_bar_);- // Command bar — shrinks gracefullycommand_bar_ = new CommandBar(this);command_bar_->setMinimumWidth(80);command_bar_->setMaximumWidth(240);@@ -145,19 +143,15 @@ ToolBar::ToolBar(QWidget* parent) : QWidget(parent) {}void ToolBar::refresh_theme() {- // Bar backgroundsetStyleSheet(QString("background:%1;border-bottom:1px solid %2;").arg(colors::BG_BASE()).arg(colors::BORDER_DIM()));- // Menu bar + popup menusif (menu_bar_) {menu_bar_->setStyleSheet(menu_ss());for (auto* action : menu_bar_->actions())if (action->menu())action->menu()->setStyleSheet(popup_ss());}- // Separatorsfor (auto* s : separators_)s->setStyleSheet(QString("color:%1;background:transparent;padding:0 3px;").arg(colors::TEXT_DIM()));- // Branding labelsauto lbl = [](QLabel* l, const QString& c, bool b = false) {if (l)l->setStyleSheet(QString("color:%1;%2background:transparent;").arg(c, b ? "font-weight:700;" : ""));@@ -170,7 +164,6 @@ void ToolBar::refresh_theme() {lbl(clock_label_, colors::TEXT_PRIMARY());lbl(user_label_, colors::AMBER());lbl(credits_label_, colors::POSITIVE());- // Buttonsif (plan_btn_)plan_btn_->setStyleSheet(QString("QPushButton{color:%1;background:transparent;border:none;padding:0 2px;}""QPushButton:hover{color:%2;}")@@ -197,13 +190,7 @@ void ToolBar::resizeEvent(QResizeEvent* e) {}void ToolBar::apply_responsive_layout(int w) {- // Progressive disclosure: hide less-critical elements as width shrinks- // >= 1200: everything visible- // >= 1000: hide subtitle- // >= 800: also hide clock, LIVE label- // >= 650: also hide credits, chat button- // < 650: minimal — menus + branding + user + plan + logout-+ // Progressive disclosure thresholds: 1200=subtitle, 800=clock+LIVE, 650=credits+chat.bool show_subtitle = (w >= 1200);bool show_clock = (w >= 800);bool show_live = (w >= 800);@@ -223,12 +210,9 @@ void ToolBar::apply_responsive_layout(int w) {if (chat_mode_btn_)chat_mode_btn_->setVisible(show_chat);- // Hide separators adjacent to hidden widgets — check each separator's neighbors- // Simple approach: hide seps 3 (after credits) and 4 (after plan/before chat)- // when their adjacent content is hiddenif (separators_.size() >= 5) {- separators_[2]->setVisible(show_credits); // sep before credits- separators_[3]->setVisible(show_chat); // sep before chat+ separators_[2]->setVisible(show_credits);+ separators_[3]->setVisible(show_chat);}}@@ -246,13 +230,11 @@ void ToolBar::refresh_user_display() {return;}- // Elide username/email to fit within maxWidthQString name = s.user_info.username.isEmpty() ? s.user_info.email : s.user_info.username;QFontMetrics fm(user_label_->font());user_label_->setText(fm.elidedText(name, Qt::ElideRight, user_label_->maximumWidth() - 4));user_label_->setToolTip(name);- // Credits — compact formatint credits = static_cast<int>(s.user_info.credit_balance);credits_label_->setText(QString("%1 CR").arg(credits));credits_label_->setStyleSheet(@@ -268,9 +250,7 @@ QMenu* ToolBar::build_file_menu() {m->setStyleSheet(popup_ss());m->addAction("New Window", this, [this]() { emit action_triggered("new_window"); });- // "Move to Monitor" — rebuilt on every popup so plug/unplug events are- // reflected without restarting the app. Emits "move_to_monitor:<name>"- // so WindowFrame can look the screen up by name (indices are unstable).+ // Rebuilt on popup so plug/unplug is reflected. Emits "move_to_monitor:<name>" — names are stable, indices aren't.auto* monitors = m->addMenu("Move to Monitor");monitors->setStyleSheet(popup_ss());connect(monitors, &QMenu::aboutToShow, this, [this, monitors]() {@@ -294,9 +274,6 @@ QMenu* ToolBar::build_file_menu() {});m->addSeparator();- // Layout = "named arrangement of frames + panels + dock state". Replaces- // the old "Workspace" terminology. Routes through builtin_actions- // (layout.new / .open / .save / .save_as) via WindowFrame's dispatch.m->addAction("New Layout", this, [this]() { emit action_triggered("layout_new"); });m->addAction("Open Layout…", this, [this]() { emit action_triggered("layout_open"); });m->addAction("Save Layout", this, [this]() { emit action_triggered("layout_save"); });@@ -326,7 +303,6 @@ QMenu* ToolBar::build_navigate_menu() {.arg(colors::BG_RAISED()).arg(colors::AMBER()));- // Use submenus for each group — cleaner and no scroll neededauto add_sub = [&](const QString& title) -> QMenu* {auto* sub = m->addMenu(title);sub->setStyleSheet(m->styleSheet());@@ -337,7 +313,6 @@ QMenu* ToolBar::build_navigate_menu() {menu->addAction(label, this, [this, id]() { emit navigate_to(id); });};- // Markets & Dataauto* mkt = add_sub("Markets & Data");nav(mkt, "Economics", "economics");nav(mkt, "GOVT Data", "gov_data");@@ -346,7 +321,6 @@ QMenu* ToolBar::build_navigate_menu() {nav(mkt, "Asia Markets", "asia_markets");nav(mkt, "Relationship Map", "relationship_map");- // Trading & Portfolioauto* trd = add_sub("Trading & Portfolio");nav(trd, "Equity Trading", "equity_trading");nav(trd, "Alpha Arena", "alpha_arena");@@ -355,11 +329,9 @@ QMenu* ToolBar::build_navigate_menu() {nav(trd, "F&&O", "fno");nav(trd, "Watchlist", "watchlist");- // Crypto / on-chain identityauto* crypto = add_sub("Crypto");nav(crypto, "Crypto Center", "crypto_center");- // Research & Intelligenceauto* res = add_sub("Research & Intelligence");nav(res, "Equity Research", "equity_research");nav(res, "M&A Analytics", "ma_analytics");@@ -368,7 +340,6 @@ QMenu* ToolBar::build_navigate_menu() {nav(res, "Maritime", "maritime");nav(res, "Surface Analytics", "surface_analytics");- // Toolsauto* tools = add_sub("Tools");nav(tools, "Agent Config", "agent_config");nav(tools, "MCP Servers", "mcp_servers");@@ -382,7 +353,6 @@ QMenu* ToolBar::build_navigate_menu() {m->addSeparator();- // Direct items (no submenu)nav(m, "Forum", "forum");nav(m, "Docs", "docs");nav(m, "Support", "support");@@ -394,23 +364,17 @@ 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"); });- // Phase 11: the shortcut is Ctrl+Shift+T; we don't mark the QAction as- // checkable because its state is owned by WindowFrame::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.+ // Not checkable — state lives on WindowFrame::always_on_top_; a checkable QAction would drift on focus changes.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 monitorauto* panels = m->addMenu("Float Panel");panels->setStyleSheet(popup_ss());panels->addAction("Dashboard", this, [this]() { emit action_triggered("panel_dashboard"); });@@ -429,47 +393,39 @@ QMenu* ToolBar::build_view_menu() {panels->addAction("AI Chat", this, [this]() { emit action_triggered("panel_ai_chat"); });m->addSeparator();- // Quick Switch — jump to a preset screen layoutauto* persp = m->addMenu("Quick Switch");persp->setStyleSheet(popup_ss());persp->addAction("Save Workspace", this, [this]() { emit action_triggered("perspective_save"); });persp->addSeparator();- // Tradingauto* qs_trading = persp->addMenu("Trading");qs_trading->setStyleSheet(popup_ss());qs_trading->addAction("Crypto Trading", this, [this]() { emit action_triggered("perspective_trading"); });qs_trading->addAction("Equity Trading", this, [this]() { emit action_triggered("perspective_equity"); });qs_trading->addAction("Algo Trading", this, [this]() { emit action_triggered("perspective_algo"); });- // Researchauto* qs_research = persp->addMenu("Research");qs_research->setStyleSheet(popup_ss());qs_research->addAction("Equity Research", this, [this]() { emit action_triggered("perspective_research"); });qs_research->addAction("Derivatives", this, [this]() { emit action_triggered("perspective_derivatives"); });qs_research->addAction("M&&A Analytics", this, [this]() { emit action_triggered("perspective_ma"); });- // Portfolio & Marketspersp->addAction("Portfolio View", this, [this]() { emit action_triggered("perspective_portfolio"); });persp->addAction("Markets View", this, [this]() { emit action_triggered("perspective_markets"); });persp->addAction("News View", this, [this]() { emit action_triggered("perspective_news"); });- // Economics & Dataauto* qs_econ = persp->addMenu("Economics && Data");qs_econ->setStyleSheet(popup_ss());qs_econ->addAction("Economics", this, [this]() { emit action_triggered("perspective_economics"); });qs_econ->addAction("Data Sources", this, [this]() { emit action_triggered("perspective_data"); });- // Geopoliticspersp->addAction("Geopolitics View", this, [this]() { emit action_triggered("perspective_geopolitics"); });- // AI & Quantauto* qs_ai = persp->addMenu("AI && Quant");qs_ai->setStyleSheet(popup_ss());qs_ai->addAction("Quant Lab", this, [this]() { emit action_triggered("perspective_quant"); });qs_ai->addAction("AI Chat", this, [this]() { emit action_triggered("perspective_ai"); });- // Toolspersp->addAction("Tools View", this, [this]() { emit action_triggered("perspective_tools"); });m->addSeparator();diff --git a/fincept-qt/src/ui/pushpins/SymbolChip.cpp b/fincept-qt/src/ui/pushpins/SymbolChip.cppindex ca4df2f1b..b1091fd6e 100644--- a/fincept-qt/src/ui/pushpins/SymbolChip.cpp+++ b/fincept-qt/src/ui/pushpins/SymbolChip.cpp@@ -42,8 +42,7 @@ void SymbolChip::mouseMoveEvent(QMouseEvent* e) {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.+ // Clear pressed_ so the release doesn't also fire as a click.pressed_ = false;symbol_dnd::startSymbolDrag(this, ref_);}@@ -88,8 +87,8 @@ void SymbolChip::paintEvent(QPaintEvent*) {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.fillPath(path, QColor("#1f2937"));+ p.setPen(QColor("#d97706"));p.drawPath(path);p.setPen(QColor("#f3f4f6"));diff --git a/fincept-qt/src/ui/theme/ThemeManager.cpp b/fincept-qt/src/ui/theme/ThemeManager.cppindex 9e356fefc..df6137620 100644--- a/fincept-qt/src/ui/theme/ThemeManager.cpp+++ b/fincept-qt/src/ui/theme/ThemeManager.cpp@@ -7,10 +7,6 @@namespace fincept::ui {-// ----------------------------------------------------------------------------// Built-in theme preset definitions-// ----------------------------------------------------------------------------const ThemeTokens THEME_OBSIDIAN = {.name = "Obsidian",.bg_base = "#080808",@@ -45,10 +41,6 @@ const ThemeTokens THEME_OBSIDIAN = {.chart_colors = {"#d97706", "#0891b2", "#16a34a", "#dc2626", "#2563eb", "#ca8a04"},};-// ----------------------------------------------------------------------------// ThemeManager implementation-// ----------------------------------------------------------------------------ThemeManager::ThemeManager() : QObject(nullptr), current_(THEME_OBSIDIAN) {}ThemeManager& ThemeManager::instance() {@@ -64,7 +56,6 @@ void ThemeManager::apply_theme(const QString& /*name*/) {void ThemeManager::apply_font(const QString& family, int size_px) {font_family_ = family;font_size_px_ = (size_px > 0) ? size_px : 14;- // rebuild_and_apply() will sync qApp->setFont() and QSS together.rebuild_and_apply();}@@ -79,6 +70,20 @@ void ThemeManager::apply_density(const QString& density) {rebuild_and_apply();}+void ThemeManager::apply_typography_and_density(const QString& family, int size_px,+ const QString& density) {+ if (!family.isEmpty())+ font_family_ = family;+ font_size_px_ = (size_px > 0) ? size_px : 14;+ if (density == "Compact")+ density_pad_ = 2;+ else if (density == "Comfortable")+ density_pad_ = 8;+ else+ density_pad_ = 4;+ rebuild_and_apply();+}+QString ThemeManager::current_theme_name() const {return QString(current_.name);}@@ -121,8 +126,8 @@ void ThemeManager::rebuild_and_apply() {QString ThemeManager::build_global_qss() const {const auto& t = current_;- const int p = density_pad_; // padding px- const int p2 = density_pad_ * 2; // double padding+ const int p = density_pad_;+ const int p2 = density_pad_ * 2;return QString(R"(* {@@ -211,14 +216,9 @@ QString ThemeManager::build_global_qss() const {QMenu::separator { background: %6; height: 1px; }QScrollArea { border: none; background: %1; }- /* QFrame transparent background — EXCLUDE ADS classes that extend QFrame- (CDockWidgetTab, CDockAreaTitleBar) because this app-level rule would- override their widget-level styling from CDockManager, making tabs- transparent and labels invisible. We use :!property selectors are not- available, so we explicitly re-set ADS widgets after. */+ /* App-level QFrame transparent rule would erase ADS tab/title styling,+ so re-assert ADS widget backgrounds below — later, more-specific rules win. */QFrame { background: transparent; border: none; }- /* Re-assert ADS widget backgrounds AFTER the QFrame rule.- In app-level QSS, later rules with more specific selectors win. */ads--CDockContainerWidget { background: %1; border: none; }ads--CDockAreaWidget { background: %1; border: none; }ads--CDockWidget { background: %1; border: none; }@@ -427,69 +427,40 @@ QString ThemeManager::build_global_qss() const {#negativeText { color: %21; }#warningText { color: %22; })")- // %1 bg_base- .arg(t.bg_base)- // %2 text_primary- .arg(t.text_primary)- // %3 border_med- .arg(t.border_med)- // %4 border_bright- .arg(t.border_bright)- // %5 bg_surface- .arg(t.bg_surface)- // %6 border_dim- .arg(t.border_dim)- // %7 padding (density)- .arg(p)- // %8 double padding- .arg(p2)- // %9 accent- .arg(t.accent)- // %10 text_secondary- .arg(t.text_secondary)- // %11 bg_hover- .arg(t.bg_hover)- // %12 bg_raised- .arg(t.bg_raised)- // %13 text_dim- .arg(t.text_dim)- // %14 row_alt- .arg(t.row_alt)- // %15 font-family- .arg(font_family_)- // %16 font-size- .arg(font_size_px_)- // %17 text_on_accent- .arg(t.text_on_accent)- // %18 icon_dim- .arg(t.icon_dim)- // %19 icon_hover- .arg(t.icon_hover)- // %20 positive- .arg(t.positive)- // %21 negative- .arg(t.negative)- // %22 warning- .arg(t.warning)- // %23 positive_dim- .arg(t.positive_dim)- // %24 negative_dim- .arg(t.negative_dim)- // %25 accent_bg- .arg(t.accent_bg)- // %26 positive_bg- .arg(t.positive_bg)- // %27 negative_bg- .arg(t.negative_bg);+ .arg(t.bg_base) // %1+ .arg(t.text_primary) // %2+ .arg(t.border_med) // %3+ .arg(t.border_bright) // %4+ .arg(t.bg_surface) // %5+ .arg(t.border_dim) // %6+ .arg(p) // %7 padding+ .arg(p2) // %8 double padding+ .arg(t.accent) // %9+ .arg(t.text_secondary) // %10+ .arg(t.bg_hover) // %11+ .arg(t.bg_raised) // %12+ .arg(t.text_dim) // %13+ .arg(t.row_alt) // %14+ .arg(font_family_) // %15+ .arg(font_size_px_) // %16+ .arg(t.text_on_accent) // %17+ .arg(t.icon_dim) // %18+ .arg(t.icon_hover) // %19+ .arg(t.positive) // %20+ .arg(t.negative) // %21+ .arg(t.warning) // %22+ .arg(t.positive_dim) // %23+ .arg(t.negative_dim) // %24+ .arg(t.accent_bg) // %25+ .arg(t.positive_bg) // %26+ .arg(t.negative_bg); // %27}QString ThemeManager::build_ads_qss() const {const auto& t = current_;LOG_INFO("ThemeManager", QString("build_ads_qss: bg_base=%1 bg_raised=%2 bg_surface=%3 accent=%4 border_dim=%5").arg(t.bg_base).arg(t.bg_raised).arg(t.bg_surface).arg(t.accent).arg(t.border_dim));- // This stylesheet is applied directly to CDockManager to completely override- // ADS's internally loaded default.css / focus_highlighting.css which use- // palette(window)/palette(highlight) — the Windows system gray/blue colors.+ // Applied to CDockManager to override ADS's default.css/focus_highlighting.css palette() colours.QString qss = QString(R"(ads--CDockContainerWidget { background: %1; }ads--CDockAreaWidget { background: %1; }@@ -545,11 +516,7 @@ QString ThemeManager::build_ads_qss() const {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. */+ /* Drop overlay + splitter hover both use accent for visual consistency across drag/resize. */ads--CDockOverlay { background: transparent; }ads--CDockOverlayCross { background: transparent; }ads--CDockSplitter::handle:hover { background-color: %4; }diff --git a/fincept-qt/src/ui/theme/ThemeManager.h b/fincept-qt/src/ui/theme/ThemeManager.hindex 9e0f54957..bf0d01e18 100644--- a/fincept-qt/src/ui/theme/ThemeManager.h+++ b/fincept-qt/src/ui/theme/ThemeManager.h@@ -34,6 +34,15 @@ class ThemeManager : public QObject {/// Adjusts padding token in global QSS and re-applies.void apply_density(const QString& density);+ /// Coalesced apply: updates font family/size and density, then calls+ /// rebuild_and_apply() exactly once. Use this in live-preview / debounced+ /// handlers so qApp->setStyleSheet() runs once instead of twice — important+ /// on KDE Plasma 6 + Qt6 + Wayland where back-to-back global restyles+ /// during a QComboBox event chain can crash the process. See GitHub issue+ /// #247 for the original repro.+ void apply_typography_and_density(const QString& family, int size_px,+ const QString& density);+/// Read access to the currently active token set./// Custom painters call: QColor(ThemeManager::instance().tokens().accent)const ThemeTokens& tokens() const { return current_; }diff --git a/fincept-qt/src/ui/widgets/GroupBadge.h b/fincept-qt/src/ui/widgets/GroupBadge.hindex 61fc33609..dd72f2e35 100644--- a/fincept-qt/src/ui/widgets/GroupBadge.h+++ b/fincept-qt/src/ui/widgets/GroupBadge.h@@ -8,19 +8,8 @@ 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.+/// Coloured letter pill on dock titles whose screen implements IGroupLinked.+/// Click cycles group; emits group_change_requested only — DockScreenRouter owns the wiring to SymbolContext.class GroupBadge : public QWidget {Q_OBJECTpublic:@@ -28,9 +17,7 @@ class GroupBadge : public QWidget {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).+ /// Update display without emitting — for workspace load and programmatic set_group.void set_group_silent(SymbolGroup g);static QColor color_for_group(SymbolGroup g);diff --git a/funding.json b/funding.jsonindex 88b6fd9ea..6843ac097 100644--- a/funding.json+++ b/funding.json@@ -15,7 +15,7 @@{"guid": "fincept-terminal","name": "Fincept Terminal",- "description": "Native C++20 financial intelligence terminal built with Dear ImGui and embedded Python. Features full multi-asset analytics across equity, portfolio, derivatives, fixed income, and alternatives, 20+ AI investor personas, 100+ data connectors, visual workflow automation, maritime tracking, and geopolitical intelligence frameworks. A professional alternative to Bloomberg Terminal, built for analysts who refuse to be limited by traditional software.",+ "description": "Native C++20 financial intelligence terminal built with Dear ImGui and embedded Python. Features full multi-asset analytics across equity, portfolio, derivatives, fixed income, and alternatives, 20+ AI investor personas, 100+ data connectors, visual workflow automation, maritime tracking, and geopolitical intelligence frameworks. A professional, open-source alternative to legacy financial terminals, built for analysts who refuse to be limited by traditional software.","webpageUrl": {"url": "https://github.com/Fincept-Corporation/FinceptTerminal"},diff --git a/setup.sh b/setup.shindex 9fb9b882c..f761d7eb3 100755--- a/setup.sh+++ b/setup.sh@@ -91,7 +91,38 @@ elif [ "$PLATFORM" = "macos" ]; theninfo "Homebrew not found. Installing..."/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"fi- brew install cmake ninja [email protected] openssl@3 yt-dlp+ # portaudio: C dep for pyaudio; without it pyaudio's source build fails+ # at `#include "portaudio.h"` and the analytical-library setup loops on+ # every launch (see PythonSetupManager::install_packages — a partial+ # install leaves venv-numpy2's marker absent → setup screen reappears).+ brew install cmake ninja [email protected] openssl@3 yt-dlp expat portaudio++ # ── Self-heal brewed Python's pyexpat on macOS 26+ ──────────────────────+ # On macOS Tahoe (Darwin 25+), the Homebrew [email protected] / [email protected]+ # bottles' pyexpat extension links to /usr/lib/libexpat.1.dylib but expects+ # symbols (e.g. _XML_SetAllocTrackerActivationThreshold) that are absent+ # from the system dylib in the dyld shared cache. Result: `python -m venv`+ # aborts because ensurepip's bootstrap of pip imports xmlrpc → xml.parsers+ # → pyexpat and fails with a Symbol-not-found ImportError.+ #+ # Fix: rewrite the install-name reference in pyexpat.cpython-*-darwin.so+ # to point at brew's libexpat (which has the symbol), then re-sign the+ # binary so the kernel will load it. Idempotent — install_name_tool is a+ # no-op on the second run.+ BREW_EXPAT_LIB="$(brew --prefix expat)/lib/libexpat.1.dylib"+ if [ -f "$BREW_EXPAT_LIB" ]; then+ for py_ver in 3.11 3.14; do+ py_bin="$(command -v "python$py_ver" || true)"+ [ -z "$py_bin" ] && continue+ # Quick probe: does pyexpat import? If yes, nothing to do.+ if "$py_bin" -c "import pyexpat" 2>/dev/null; then continue; fi+ so_path="$("$py_bin" -c 'import importlib.util,sys; s=importlib.util.find_spec("pyexpat"); print(s.origin or "")' 2>/dev/null || true)"+ [ -f "$so_path" ] || continue+ info "Patching $so_path → $BREW_EXPAT_LIB"+ install_name_tool -change /usr/lib/libexpat.1.dylib "$BREW_EXPAT_LIB" "$so_path" 2>/dev/null || true+ codesign --force --sign - "$so_path" 2>/dev/null || true+ done+ fifiok