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
v4.0.1
tilakpatel22fd84a4130983
diff --git a/fincept-qt/CMakeLists.txt b/fincept-qt/CMakeLists.txtindex 38866b07c..431893ac1 100644--- a/fincept-qt/CMakeLists.txt+++ b/fincept-qt/CMakeLists.txt@@ -587,6 +587,7 @@ set(SCREEN_SOURCESsrc/screens/settings/LlmConfigSection.cppsrc/screens/settings/McpServersSection.cppsrc/screens/settings/KeybindingsSection.cpp+ src/screens/settings/PythonEnvSection.cppsrc/screens/about/AboutScreen.cppsrc/screens/support/SupportScreen.cppsrc/screens/trade_viz/TradeVizScreen.cpp@@ -1095,6 +1096,7 @@ set_source_files_properties(src/screens/report_builder/PropertiesPanel.cppsrc/screens/report_builder/ReportBuilderScreen.cppsrc/screens/settings/KeybindingsSection.cpp+ src/screens/settings/PythonEnvSection.cppsrc/screens/settings/LlmConfigSection.cppsrc/screens/settings/McpServersSection.cppsrc/screens/settings/SettingsScreen.cpp@@ -1676,6 +1678,22 @@ add_custom_command(TARGET FinceptTerminal POST_BUILDCOMMENT "Copying Python scripts to build output...")+# ── Copy requirements files to build output ──────────────────────────────────+# PythonSetupManager::find_requirements_file() searches exe_dir/resources/ first.+# Without this POST_BUILD step the files are only available via cmake --install,+# causing setup to silently fail in dev/debug builds.+add_custom_command(TARGET FinceptTerminal POST_BUILD+ COMMAND ${CMAKE_COMMAND} -E make_directory+ "$<TARGET_FILE_DIR:FinceptTerminal>/resources"+ COMMAND ${CMAKE_COMMAND} -E copy_if_different+ "${CMAKE_CURRENT_SOURCE_DIR}/resources/requirements-numpy1.txt"+ "$<TARGET_FILE_DIR:FinceptTerminal>/resources/requirements-numpy1.txt"+ COMMAND ${CMAKE_COMMAND} -E copy_if_different+ "${CMAKE_CURRENT_SOURCE_DIR}/resources/requirements-numpy2.txt"+ "$<TARGET_FILE_DIR:FinceptTerminal>/resources/requirements-numpy2.txt"+ COMMENT "Copying requirements files to build output..."+)+# Bundle yt-dlp for dashboard YouTube playback on all platforms.# Override path with: -DFINCEPT_YTDLP_EXE=/abs/path/to/yt-dlp[.exe]set(FINCEPT_YTDLP_EXE "" CACHE FILEPATH "Path to yt-dlp executable to bundle with FinceptTerminal")@@ -1734,10 +1752,22 @@ if(WIN32)install(TARGETS FinceptTerminal RUNTIME DESTINATION "." COMPONENT core)install(DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/scripts/"DESTINATION "scripts" COMPONENT scripts)+ # Requirements files — needed by PythonSetupManager at first run to install+ # Python packages. Must be deployed beside the exe so find_requirements_file()+ # can locate them at C:/Program Files/FinceptTerminal/resources/*.txt.+ install(FILES+ "${CMAKE_CURRENT_SOURCE_DIR}/resources/requirements-numpy1.txt"+ "${CMAKE_CURRENT_SOURCE_DIR}/resources/requirements-numpy2.txt"+ DESTINATION "resources" COMPONENT core)elseif(APPLE)# macOS: install the .app bundleinstall(TARGETS FinceptTerminal BUNDLE DESTINATION "." COMPONENT core)+ # Requirements files — deployed beside the .app so PythonSetupManager finds them+ install(FILES+ "${CMAKE_CURRENT_SOURCE_DIR}/resources/requirements-numpy1.txt"+ "${CMAKE_CURRENT_SOURCE_DIR}/resources/requirements-numpy2.txt"+ DESTINATION "FinceptTerminal.app/Contents/Resources/resources" COMPONENT core)else()# Linux: FHS-compliant layoutdiff --git a/fincept-qt/build.bat b/fincept-qt/build.batnew file mode 100644index 000000000..5caea04a3--- /dev/null+++ b/fincept-qt/build.bat@@ -0,0 +1,3 @@+@echo off+call "C:\Program Files\Microsoft Visual Studio\2022\Preview\VC\Auxiliary\Build\vcvars64.bat"+cmake --build build --config Releasediff --git a/fincept-qt/build2.bat b/fincept-qt/build2.batnew file mode 100644index 000000000..ed888cc94--- /dev/null+++ b/fincept-qt/build2.bat@@ -0,0 +1,4 @@+@echo off+call "C:\Program Files\Microsoft Visual Studio\2022\Preview\VC\Auxiliary\Build\vcvars64.bat"+cmake --build build --config Release > build_output.txt 2>&1+echo EXIT_CODE=%ERRORLEVEL% >> build_output.txtdiff --git a/fincept-qt/build_output.txt b/fincept-qt/build_output.txtnew file mode 100644index 000000000..9320e6a1aBinary files /dev/null and b/fincept-qt/build_output.txt differdiff --git a/fincept-qt/src/ai_chat/AiChatScreen.cpp b/fincept-qt/src/ai_chat/AiChatScreen.cppindex 0c425c5f6..8dc3e7f10 100644--- a/fincept-qt/src/ai_chat/AiChatScreen.cpp+++ b/fincept-qt/src/ai_chat/AiChatScreen.cpp@@ -411,6 +411,11 @@ void AiChatScreen::build_chat_area() {scroll_area_->setWidget(messages_container_);vl->addWidget(scroll_area_, 1);+ // Debounced persistence when the user scrolls through chat history.+ if (auto* vbar = scroll_area_->verticalScrollBar())+ connect(vbar, &QScrollBar::valueChanged, this,+ [this](int) { ScreenStateManager::instance().notify_changed(this); });+// Typing indicator sits above input, inside chat areavl->addWidget(build_typing_indicator());vl->addWidget(build_input_area());@@ -590,6 +595,7 @@ QWidget* AiChatScreen::build_input_area() {connect(input_box_, &QPlainTextEdit::textChanged, this, [this]() {const int lines = input_box_->document()->blockCount();input_box_->setFixedHeight(qMin(qMax(lines, 1), 6) * 24 + 20);+ ScreenStateManager::instance().notify_changed(this);});hl->addWidget(input_box_, 1);@@ -658,6 +664,7 @@ void AiChatScreen::on_search_changed(const QString& text) {auto* item = session_list_->item(i);item->setHidden(!filter.isEmpty() && !item->text().toLower().contains(filter));}+ ScreenStateManager::instance().notify_changed(this);}// ── Typing indicator slot ─────────────────────────────────────────────────────@@ -820,6 +827,7 @@ void AiChatScreen::on_attach_file() {}if (attach_btn_)attach_btn_->setProperty("active", true);+ ScreenStateManager::instance().notify_changed(this);}void AiChatScreen::on_send() {@@ -1292,26 +1300,68 @@ void AiChatScreen::show_welcome(bool show) {// ── IStatefulScreen ───────────────────────────────────────────────────────────QVariantMap AiChatScreen::save_state() const {- return {- {"session_id", active_session_id_},- };+ QVariantMap s{{"session_id", active_session_id_}};++ if (input_box_)+ s.insert("draft", input_box_->toPlainText());+ if (search_edit_)+ s.insert("search", search_edit_->text());+ if (scroll_area_ && scroll_area_->verticalScrollBar())+ s.insert("scroll", scroll_area_->verticalScrollBar()->value());+ if (!attached_file_path_.isEmpty())+ s.insert("attached_file", attached_file_path_);++ return s;}void AiChatScreen::restore_state(const QVariantMap& state) {const QString sid = state.value("session_id").toString();- if (sid.isEmpty())- return;- // Find and select the matching row in the session list- for (int i = 0; i < session_list_->count(); ++i) {- auto* item = session_list_->item(i);- if (item && item->data(Qt::UserRole).toString() == sid) {- session_list_->setCurrentRow(i);- on_session_selected(i);- return;+ // Session selection — find the matching row and select it.+ if (!sid.isEmpty()) {+ for (int i = 0; i < session_list_->count(); ++i) {+ auto* item = session_list_->item(i);+ if (item && item->data(Qt::UserRole).toString() == sid) {+ session_list_->setCurrentRow(i);+ on_session_selected(i);+ break;+ }+ }+ // Session not found (may have been deleted) — leave default selection+ }++ // Search box — apply before (or after) session restore; filter text is independent.+ const QString search_text = state.value("search").toString();+ if (search_edit_ && !search_text.isEmpty())+ search_edit_->setText(search_text);++ // Draft composer text — restore what the user was typing.+ const QString draft = state.value("draft").toString();+ if (input_box_ && !draft.isEmpty())+ input_box_->setPlainText(draft);++ // Attached file — restore the badge only if the file still exists on disk.+ const QString attached = state.value("attached_file").toString();+ if (!attached.isEmpty() && QFile::exists(attached)) {+ attached_file_path_ = attached;+ if (attach_badge_) {+ attach_badge_->setText(QFileInfo(attached).fileName());+ attach_badge_->setVisible(true);}}- // Session not found (may have been deleted) — leave default selection++ // Scroll position — defer until after message_layout has laid out,+ // otherwise the scrollbar max is still 0.+ const int scroll = state.value("scroll", -1).toInt();+ if (scroll >= 0 && scroll_area_) {+ QPointer<AiChatScreen> self = this;+ QTimer::singleShot(0, this, [self, scroll]() {+ if (!self || !self->scroll_area_)+ return;+ if (auto* bar = self->scroll_area_->verticalScrollBar())+ bar->setValue(scroll);+ });+ }}} // namespace fincept::screensdiff --git a/fincept-qt/src/ai_chat/AiChatScreen.h b/fincept-qt/src/ai_chat/AiChatScreen.hindex ecb98985a..6665f3e38 100644--- a/fincept-qt/src/ai_chat/AiChatScreen.h+++ b/fincept-qt/src/ai_chat/AiChatScreen.h@@ -28,7 +28,8 @@ class AiChatScreen : public QWidget, public IStatefulScreen {void restore_state(const QVariantMap& state) override;QVariantMap save_state() const override;QString state_key() const override { return "ai_chat"; }- int state_version() const override { return 1; }+ // v2 adds: draft text, search text, scroll position, attached file path.+ int state_version() const override { return 2; }protected:void showEvent(QShowEvent* e) override;diff --git a/fincept-qt/src/app/MainWindow.cpp b/fincept-qt/src/app/MainWindow.cppindex ba1e37031..7c744117c 100644--- a/fincept-qt/src/app/MainWindow.cpp+++ b/fincept-qt/src/app/MainWindow.cpp@@ -99,6 +99,7 @@#include <DockAreaWidget.h>#include <DockManager.h>#include <DockWidget.h>+#include <FloatingDockContainer.h>namespace fincept {@@ -204,7 +205,9 @@ MainWindow::MainWindow(int window_id, QWidget* parent) : QMainWindow(parent), wi// Tab bar navigation: open the selected screen exclusively — closes all other// panels and fills the full area. Each tab is a fresh independent screen,// not nested into whatever was previously open.- connect(tab_bar_, &ui::TabBar::tab_changed, this, [this](const QString& id) { dock_router_->navigate(id, true); });+ connect(tab_bar_, &ui::TabBar::tab_changed, this, [this](const QString& id) {+ if (!locked_) dock_router_->navigate(id, true);+ });connect(dock_router_, &DockScreenRouter::screen_changed, tab_bar_, &ui::TabBar::set_active);// Update the main window title bar to reflect the current screen name.@@ -237,16 +240,34 @@ MainWindow::MainWindow(int window_id, QWidget* parent) : QMainWindow(parent), wi});connect(toolbar, &ui::ToolBar::chat_mode_toggled, this, &MainWindow::toggle_chat_mode);- connect(toolbar, &ui::ToolBar::navigate_to, this, [this](const QString& id) { dock_router_->navigate(id, true); });+ connect(toolbar, &ui::ToolBar::navigate_to, this, [this](const QString& id) {+ if (!locked_) dock_router_->navigate(id, true);+ });++ // Debounced dock-layout save: ADS emits a burst of signals during+ // add/replace/remove; coalesce into one write ~500 ms after the last change+ // so rapid edits don't hammer QSettings and so crashes preserve layout.+ dock_layout_save_timer_ = new QTimer(this);+ dock_layout_save_timer_->setSingleShot(true);+ dock_layout_save_timer_->setInterval(500);+ connect(dock_layout_save_timer_, &QTimer::timeout, this, [this]() {+ if (!dock_manager_)+ return;+ SessionManager::instance().save_dock_layout(window_id_, dock_manager_->saveState());+ if (WorkspaceManager::instance().has_current_workspace())+ WorkspaceManager::instance().save_workspace();+ });connect(toolbar, &ui::ToolBar::dock_command, this,[this](const QString& action, const QString& primary, const QString& secondary) {+ if (locked_) return;if (action == "add")dock_router_->add_alongside(primary, secondary);else if (action == "remove")dock_router_->remove_screen(primary);else if (action == "replace")dock_router_->replace_screen(primary, secondary);+ schedule_dock_layout_save();});// MCP navigation tool → dock_router (cross-thread safe)@@ -254,7 +275,9 @@ MainWindow::MainWindow(int window_id, QWidget* parent) : QMainWindow(parent), wiQString screen_id = data["screen_id"].toString();if (!screen_id.isEmpty())QMetaObject::invokeMethod(- dock_router_, [this, screen_id]() { dock_router_->navigate(screen_id); }, Qt::QueuedConnection);+ dock_router_, [this, screen_id]() {+ if (!locked_) dock_router_->navigate(screen_id);+ }, Qt::QueuedConnection);});// ── Keyboard shortcuts via KeyConfigManager ───────────────────────────────@@ -263,7 +286,9 @@ MainWindow::MainWindow(int window_id, QWidget* parent) : QMainWindow(parent), wiauto* act_chat = km.action(KeyAction::ToggleChat);act_chat->setShortcutContext(Qt::WindowShortcut);addAction(act_chat);- connect(act_chat, &QAction::triggered, this, &MainWindow::toggle_chat_mode);+ connect(act_chat, &QAction::triggered, this, [this]() {+ if (!locked_) toggle_chat_mode();+ });auto* act_fs = km.action(KeyAction::Fullscreen);act_fs->setShortcutContext(Qt::WindowShortcut);@@ -279,6 +304,7 @@ MainWindow::MainWindow(int window_id, QWidget* parent) : QMainWindow(parent), wiact_focus->setShortcutContext(Qt::WindowShortcut);addAction(act_focus);connect(act_focus, &QAction::triggered, this, [this]() {+ if (locked_) return;focus_mode_ = !focus_mode_;if (dock_toolbar_)dock_toolbar_->setVisible(!focus_mode_);@@ -290,6 +316,7 @@ MainWindow::MainWindow(int window_id, QWidget* parent) : QMainWindow(parent), wiact_refresh->setShortcutContext(Qt::WindowShortcut);addAction(act_refresh);connect(act_refresh, &QAction::triggered, this, [this]() {+ if (locked_) return;if (dock_manager_) {auto* focused = dock_manager_->focusedDockWidget();if (focused && focused->widget())@@ -317,6 +344,7 @@ MainWindow::MainWindow(int window_id, QWidget* parent) : QMainWindow(parent), wi// Toolbar actionsconnect(toolbar, &ui::ToolBar::action_triggered, this, [this](const QString& action) {+ if (locked_) return;if (action == "new_window") {auto* w = new MainWindow(MainWindow::next_window_id());w->setAttribute(Qt::WA_DeleteOnClose);@@ -563,6 +591,8 @@ MainWindow::MainWindow(int window_id, QWidget* parent) : QMainWindow(parent), wiif (auth_mgr.is_authenticated() && auth::PinManager::instance().has_pin()) {LOG_INFO("MainWindow", "Session restored — showing PIN unlock");lock_screen_->show_unlock();+ locked_ = true;+ set_shell_visible(false);stack_->setCurrentIndex(3);} else if (auth_mgr.is_authenticated()) {// Authenticated but no PIN yet — will be caught by on_auth_state_changed@@ -613,6 +643,7 @@ MainWindow::MainWindow(int window_id, QWidget* parent) : QMainWindow(parent), wi}void MainWindow::toggle_chat_mode() {+ if (locked_) return;chat_mode_ = !chat_mode_;if (chat_mode_) {@@ -739,6 +770,20 @@ void MainWindow::setup_docking_mode() {dock_manager_->setStyleSheet(ui::ThemeManager::instance().build_ads_qss());dock_layout->addWidget(dock_manager_);+ // ── Layout mutation watchdog ──────────────────────────────────────────────+ // Any ADS-level structural change (dock area created, widget added/removed,+ // floating window created) persists within ~500 ms so a crash doesn't lose+ // the user's layout. Per-widget signals (topLevelChanged, closeRequested)+ // are wired in DockScreenRouter::create_dock_widget() so user-driven float+ // or close is also captured.+ connect(dock_manager_, &ads::CDockManager::dockAreaCreated, this,+ [this](ads::CDockAreaWidget*) { schedule_dock_layout_save(); });+ connect(dock_manager_, &ads::CDockManager::dockWidgetAdded, this,+ [this](ads::CDockWidget*) { schedule_dock_layout_save(); });+ connect(dock_manager_, &ads::CDockManager::dockWidgetRemoved, this,+ [this](ads::CDockWidget*) { schedule_dock_layout_save(); });+ connect(dock_manager_, &ads::CDockManager::floatingWidgetCreated, this,+ [this](ads::CFloatingDockContainer*) { schedule_dock_layout_save(); });}void MainWindow::setup_dock_screens() {@@ -809,6 +854,16 @@ void MainWindow::setup_navigation() {}void MainWindow::on_auth_state_changed() {auto& auth = auth::AuthManager::instance();+ // If logged out while the lock screen is active (e.g. max PIN attempts → reauth),+ // clear locked_ so the login screen can show. Otherwise stay on the lock screen.+ if (locked_) {+ if (!auth.is_authenticated()) {+ locked_ = false; // fall through to show login screen+ } else {+ return; // still authenticated — stay on lock screen+ }+ }+// Still validating saved session — don't flash the login screen.// Stay on whatever is currently shown until validation completes.if (auth.is_loading())@@ -816,13 +871,38 @@ void MainWindow::on_auth_state_changed() {if (auth.is_authenticated()) {// Don't redirect if user is already on the app stack (dashboard/workspace- // at index 1, or chat mode at index 2) or is intentionally viewing the- // pricing screen from the toolbar.+ // at index 1, or chat mode at index 2) — UNLESS the PIN gate hasn't been+ // cleared yet (auth completed while loading state showed dashboard early).+ //+ // pin_gate_cleared_ is critical: once the user has entered their PIN this+ // session, subsequent auth_state_changed events (periodic refresh_user_data,+ // focus-driven applicationStateChanged refresh, subscription_fetched, etc.)+ // must NOT re-lock the terminal. Without this guard, any auth refresh+ // while the user is working on the dashboard will re-show the PIN prompt.if (stack_->currentIndex() == 1 || stack_->currentIndex() == 2) {+ if (!pin_gate_cleared_) {+ if (auth.needs_pin_setup()) {+ LOG_INFO("MainWindow", "Authenticated (on app stack) but no PIN — showing PIN setup");+ lock_screen_->show_setup();+ locked_ = true;+ set_shell_visible(false);+ stack_->setCurrentIndex(3);+ return;+ }+ if (auth::PinManager::instance().has_pin()) {+ LOG_INFO("MainWindow", "Authenticated (on app stack) with PIN — showing PIN unlock");+ lock_screen_->show_unlock();+ locked_ = true;+ set_shell_visible(false);+ stack_->setCurrentIndex(3);+ return;+ }+ }LOG_DEBUG("MainWindow", QString("on_auth_state_changed: skipping redirect, "- "stack index=%1, chat_mode=%2")+ "stack index=%1, chat_mode=%2, gate_cleared=%3").arg(stack_->currentIndex())- .arg(chat_mode_));+ .arg(chat_mode_)+ .arg(pin_gate_cleared_));return;}if (stack_->currentIndex() == 0 && auth_stack_->currentIndex() == 3)@@ -836,12 +916,16 @@ void MainWindow::on_auth_state_changed() {if (auth.needs_pin_setup()) {LOG_INFO("MainWindow", "Authenticated but no PIN — showing PIN setup");lock_screen_->show_setup();+ locked_ = true;+ set_shell_visible(false);stack_->setCurrentIndex(3);return;}if (auth::PinManager::instance().has_pin()) {LOG_INFO("MainWindow", "Authenticated with PIN — showing PIN unlock");lock_screen_->show_unlock();+ locked_ = true;+ set_shell_visible(false);stack_->setCurrentIndex(3);return;}@@ -867,6 +951,7 @@ void MainWindow::on_auth_state_changed() {} else {// Disable inactivity guard when logged outauth::InactivityGuard::instance().set_enabled(false);+ pin_gate_cleared_ = false;set_shell_visible(false);stack_->setCurrentIndex(0);auth_stack_->setCurrentIndex(0);@@ -917,13 +1002,10 @@ void MainWindow::show_lock_screen() {LOG_INFO("MainWindow", "Inactivity timeout — showing lock screen");lock_screen_->activate();+ locked_ = true;+ pin_gate_cleared_ = false;+ set_shell_visible(false);stack_->setCurrentIndex(3);-- // Hide toolbar/statusbar while locked- if (dock_toolbar_)- dock_toolbar_->setVisible(false);- if (dock_status_bar_)- dock_status_bar_->setVisible(false);if (chat_bubble_)chat_bubble_->setVisible(false);}@@ -931,6 +1013,8 @@ void MainWindow::show_lock_screen() {void MainWindow::on_terminal_unlocked() {auto& auth = auth::AuthManager::instance();LOG_INFO("MainWindow", "Terminal unlocked via PIN");+ locked_ = false;+ pin_gate_cleared_ = true;// Enable/restart inactivity guardauto& guard = auth::InactivityGuard::instance();@@ -1003,6 +1087,11 @@ void MainWindow::update_window_title() {setWindowTitle(title);}+void MainWindow::schedule_dock_layout_save() {+ if (dock_layout_save_timer_)+ dock_layout_save_timer_->start();+}+void MainWindow::closeEvent(QCloseEvent* event) {WorkspaceManager::instance().save_workspace();SessionManager::instance().save_geometry(window_id_, saveGeometry(), saveState());diff --git a/fincept-qt/src/app/MainWindow.h b/fincept-qt/src/app/MainWindow.hindex 9b18c92df..a03996cf4 100644--- a/fincept-qt/src/app/MainWindow.h+++ b/fincept-qt/src/app/MainWindow.h@@ -62,9 +62,20 @@ class MainWindow : public QMainWindow {bool focus_mode_ = false;bool chat_mode_ = false;bool always_on_top_ = false;+ bool locked_ = false; ///< True while lock/PIN screen is active — blocks navigation.+ bool pin_gate_cleared_ = false; ///< Set once the user has passed the PIN gate this session.+ ///< Prevents subsequent auth_state_changed events (profile+ ///< refresh, subscription fetch, focus refresh) from+ ///< re-locking the terminal. Reset on lock / logout.AiChatBubble* chat_bubble_ = nullptr;QTimer* user_refresh_timer_ = nullptr;+ // Debounced persistence of dock layout on add/replace/remove via command bar.+ // Without this, layout changes only survive clean shutdown (closeEvent),+ // so a crash or kill loses the user's dock setup.+ QTimer* dock_layout_save_timer_ = nullptr;+ void schedule_dock_layout_save();+// Chat modechat_mode::ChatModeScreen* chat_mode_screen_ = nullptr;diff --git a/fincept-qt/src/app/main.cpp b/fincept-qt/src/app/main.cppindex c23c2e95d..faa30543b 100644--- a/fincept-qt/src/app/main.cpp+++ b/fincept-qt/src/app/main.cpp@@ -26,6 +26,7 @@#include <QDir>#include <QFile>#include <QLockFile>+#include <QPointer>#include <QSqlDatabase>#include <QSqlQuery>#include <QStandardPaths>@@ -309,22 +310,32 @@ int main(int argc, char* argv[]) {fincept::mcp::initialize_all_tools();// ── Python environment check ─────────────────────────────────────────────- // On first run, Python + venvs may not be installed. Show a setup screen- // that downloads and configures everything before launching the main app.+ // check_status() fast path (sentinel + markers present) is synchronous and+ // cheap. The slow path (first run) can spawn processes — but at this point+ // no window is visible yet so the brief block is acceptable. The SetupScreen+ // itself offloads prefill_completed_steps() to a background thread (P1).auto setup_status = fincept::python::PythonSetupManager::instance().check_status();if (setup_status.needs_setup) {LOG_INFO("App", "Python environment not ready — showing setup screen");+ // Use QPointer so the setup_complete lambda is safe against double-fire+ // (e.g. user somehow triggers it twice before the window is hidden).auto* setup_screen = new fincept::screens::SetupScreen;+ QPointer<fincept::screens::SetupScreen> screen_guard(setup_screen);setup_screen->setWindowTitle("Fincept Terminal — First-Time Setup");setup_screen->resize(800, 600);setup_screen->show();- // When setup completes, hide setup screen and launch main window- QObject::connect(setup_screen, &fincept::screens::SetupScreen::setup_complete, [&app, setup_screen]() {- setup_screen->hide();- setup_screen->deleteLater();+ // When setup completes, hide setup screen and launch main window.+ // 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]() {+ if (!screen_guard)+ return; // already cleaned up — ignore+ screen_guard->hide();+ screen_guard->deleteLater();fincept::KeyConfigManager::instance(); // init before MainWindow registers shortcutsauto* window = new fincept::MainWindow(0); // primary window@@ -376,10 +387,19 @@ int main(int argc, char* argv[]) {QObject::connect(&app, &QApplication::lastWindowClosed, &app, &QApplication::quit);// If requirements files changed (app update), sync packages in background- // without blocking the user.+ // without blocking the user. Connect setup_complete so failures are logged+ // (no SetupScreen in this path, so we only log — don't show UI).if (setup_status.needs_package_sync) {LOG_INFO("App", "Requirements changed — syncing packages in background");- fincept::python::PythonSetupManager::instance().run_setup();+ auto& mgr = fincept::python::PythonSetupManager::instance();+ QObject::connect(&mgr, &fincept::python::PythonSetupManager::setup_complete,+ &mgr, [](bool success, const QString& error) {+ if (success)+ LOG_INFO("App", "Background package sync completed successfully");+ else+ LOG_WARN("App", "Background package sync failed (non-fatal): " + error);+ }, Qt::SingleShotConnection);+ mgr.run_setup();}if (!fincept::ai_chat::LlmService::instance().is_configured())diff --git a/fincept-qt/src/auth/PinManager.cpp b/fincept-qt/src/auth/PinManager.cppindex cff1c1726..1e5b9feeb 100644--- a/fincept-qt/src/auth/PinManager.cpp+++ b/fincept-qt/src/auth/PinManager.cpp@@ -6,6 +6,8 @@#include <QCryptographicHash>#include <QRandomGenerator>+#include <climits>+namespace fincept::auth {PinManager& PinManager::instance() {@@ -31,7 +33,9 @@ static QByteArray hmac_sha256(const QByteArray& key, const QByteArray& message)while (k.size() < kBlockSize)k.append('\0');- // Step 2: Create inner/outer padded keys+ // Step 2: Create inner/outer padded keys.+ // 0x36 = ipad byte (RFC 2104 §2): XOR'd with key to form inner-hash input.+ // 0x5C = opad byte (RFC 2104 §2): XOR'd with key to form outer-hash input.QByteArray ipad(kBlockSize, '\0');QByteArray opad(kBlockSize, '\0');for (int i = 0; i < kBlockSize; ++i) {@@ -244,8 +248,8 @@ bool PinManager::is_locked_out() const {int PinManager::lockout_remaining_seconds() const {if (!lockout_until_.isValid())return 0;- int secs = static_cast<int>(QDateTime::currentDateTime().secsTo(lockout_until_));- return qMax(0, secs);+ const qint64 secs = QDateTime::currentDateTime().secsTo(lockout_until_);+ return static_cast<int>(qBound(qint64{0}, secs, qint64{INT_MAX}));}void PinManager::reset_lockout() {diff --git a/fincept-qt/src/core/config/AppPaths.cpp b/fincept-qt/src/core/config/AppPaths.cppindex 614d9c7ba..157187b41 100644--- a/fincept-qt/src/core/config/AppPaths.cpp+++ b/fincept-qt/src/core/config/AppPaths.cpp@@ -9,13 +9,12 @@ namespace fincept {QString AppPaths::root() {#ifdef _WIN32- // AppLocalDataLocation = %LOCALAPPDATA%\Fincept\FinceptTerminal- // Walk up two levels to reach %LOCALAPPDATA%, then append our app folder.- QString base = QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation);- QDir d(base);- d.cdUp(); // %LOCALAPPDATA%\Fincept- d.cdUp(); // %LOCALAPPDATA%- return d.absolutePath() + "/com.fincept.terminal";+ // Use GenericDataLocation which returns %LOCALAPPDATA% directly on Windows,+ // avoiding the fragile double-cdUp() from AppLocalDataLocation.+ // GenericDataLocation = %LOCALAPPDATA% on Windows (Qt docs: QStandardPaths).+ const QString local_app_data =+ QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation);+ return local_app_data + "/com.fincept.terminal";#elif defined(__APPLE__)return QDir::homePath() + "/Library/Application Support/com.fincept.terminal";#elsediff --git a/fincept-qt/src/core/logging/Logger.cpp b/fincept-qt/src/core/logging/Logger.cppindex 5511b5d3e..b4122195a 100644--- a/fincept-qt/src/core/logging/Logger.cpp+++ b/fincept-qt/src/core/logging/Logger.cpp@@ -1,5 +1,8 @@#include "core/logging/Logger.h"+#include <array>+#include <cstddef>+namespace fincept {Logger& Logger::instance() {@@ -71,7 +74,9 @@ void Logger::write(LogLevel level, const QString& tag, const QString& msg) {if (level < effective)return;- static const char* names[] = {"DEBUG", "INFO", "WARN", "ERROR"};+ static constexpr std::array<const char*, 4> names = {"DEBUG", "INFO", "WARN", "ERROR"};+ static_assert(names.size() == static_cast<std::size_t>(LogLevel::Error) + 1,+ "LogLevel names array size must match LogLevel enum count");QString timestamp = QDateTime::currentDateTime().toString("HH:mm:ss.zzz");QString line = QString("[%1] [%2] [%3] %4").arg(timestamp, names[static_cast<int>(level)], tag, msg);diff --git a/fincept-qt/src/core/session/SessionManager.cpp b/fincept-qt/src/core/session/SessionManager.cppindex f711d076f..7dcf628f8 100644--- a/fincept-qt/src/core/session/SessionManager.cpp+++ b/fincept-qt/src/core/session/SessionManager.cpp@@ -34,12 +34,11 @@ void SessionManager::save_tab_state(const QString& tab_id, const QVariantMap& stQVariantMap SessionManager::load_tab_state(const QString& tab_id) const {QVariantMap result;- QSettings& s = const_cast<QSettings&>(settings_);- s.beginGroup("tab_state/" + tab_id);- for (const auto& key : s.childKeys()) {- result[key] = s.value(key);+ settings_.beginGroup("tab_state/" + tab_id);+ for (const auto& key : settings_.childKeys()) {+ result[key] = settings_.value(key);}- s.endGroup();+ settings_.endGroup();return result;}@@ -97,29 +96,27 @@ int SessionManager::dock_layout_version(int window_id) const {return settings_.value(prefix + "dock_layout_version", 0).toInt();}-void SessionManager::save_perspectives(const QSettings& source) {+void SessionManager::save_perspectives(QSettings& source) {// Copy all keys from the source QSettings (written by ADS savePerspectives)// into our own settings_ under a "perspectives/" prefix.- QSettings& src = const_cast<QSettings&>(source);- src.beginGroup("Perspectives");- const QStringList keys = src.allKeys();+ source.beginGroup("Perspectives");+ const QStringList keys = source.allKeys();settings_.beginGroup("perspectives");settings_.remove(""); // clear previousfor (const QString& k : keys)- settings_.setValue(k, src.value(k));+ settings_.setValue(k, source.value(k));settings_.endGroup();- src.endGroup();+ source.endGroup();}void SessionManager::load_perspectives(QSettings& target) const {- QSettings& s = const_cast<QSettings&>(settings_);- s.beginGroup("perspectives");- const QStringList keys = s.allKeys();+ settings_.beginGroup("perspectives");+ const QStringList keys = settings_.allKeys();target.beginGroup("Perspectives");for (const QString& k : keys)- target.setValue(k, s.value(k));+ target.setValue(k, settings_.value(k));target.endGroup();- s.endGroup();+ settings_.endGroup();}void SessionManager::set_last_screen(const QString& screen_id) {diff --git a/fincept-qt/src/core/session/SessionManager.h b/fincept-qt/src/core/session/SessionManager.hindex 47d1f7d95..d1d460cce 100644--- a/fincept-qt/src/core/session/SessionManager.h+++ b/fincept-qt/src/core/session/SessionManager.h@@ -38,7 +38,7 @@ class SessionManager : public QObject {int dock_layout_version(int window_id) const;// Named perspectives (Bloomberg-style saved layouts)- void save_perspectives(const QSettings& source);+ void save_perspectives(QSettings& source);void load_perspectives(QSettings& target) const;// Last active screen@@ -51,7 +51,7 @@ class SessionManager : public QObject {private:SessionManager() = default;QElapsedTimer elapsed_;- QSettings settings_{"Fincept", "FinceptTerminal"};+ mutable QSettings settings_{"Fincept", "FinceptTerminal"};};} // namespace finceptdiff --git a/fincept-qt/src/python/PythonRunner.cpp b/fincept-qt/src/python/PythonRunner.cppindex ad3313e7f..b3540f854 100644--- a/fincept-qt/src/python/PythonRunner.cpp+++ b/fincept-qt/src/python/PythonRunner.cpp@@ -11,6 +11,7 @@#include <QHash>#include <QProcessEnvironment>#include <QStandardPaths>+#include <QUuid>namespace fincept::python {@@ -284,8 +285,7 @@ void PythonRunner::start_next() {if (arg.size() > kArgSpillThreshold) {QString temp_dir = QStandardPaths::writableLocation(QStandardPaths::TempLocation);QString temp_path = temp_dir + "/fincept_arg_" +- QString::number(QDateTime::currentMSecsSinceEpoch()) + "_" +- QString::number(reinterpret_cast<quintptr>(proc)) + ".json";+ QUuid::createUuid().toString(QUuid::WithoutBraces) + ".json";QFile tf(temp_path);if (tf.open(QIODevice::WriteOnly | QIODevice::Text)) {tf.write(arg.toUtf8());@@ -315,14 +315,20 @@ void PythonRunner::start_next() {env.insert("PYTHONUNBUFFERED", "1");env.insert("FINCEPT_DATA_DIR", PythonSetupManager::instance().install_dir());- QString existing_pypath = env.value("PYTHONPATH");- QString new_pypath = scripts_dir_ + (existing_pypath.isEmpty() ? "" : ";" + existing_pypath);+ const QString existing_pypath = env.value("PYTHONPATH");+#ifdef _WIN32+ const QChar kPathSep = ';';+#else+ const QChar kPathSep = ':';+#endif+ QString new_pypath =+ existing_pypath.isEmpty() ? scripts_dir_ : (scripts_dir_ + kPathSep + existing_pypath);if (!is_code && req.script.contains('/')) {QString script_dir = QFileInfo(scripts_dir_ + "/" + req.script).dir().absolutePath();QString parent_of_pkg = QFileInfo(script_dir).dir().absolutePath();if (parent_of_pkg != scripts_dir_ && !new_pypath.contains(parent_of_pkg))- new_pypath = parent_of_pkg + ";" + new_pypath;+ new_pypath = parent_of_pkg + kPathSep + new_pypath;}env.insert("PYTHONPATH", new_pypath);diff --git a/fincept-qt/src/python/PythonSetupManager.cpp b/fincept-qt/src/python/PythonSetupManager.cppindex ef58997fc..5ea22604e 100644--- a/fincept-qt/src/python/PythonSetupManager.cpp+++ b/fincept-qt/src/python/PythonSetupManager.cpp@@ -15,7 +15,10 @@#include <QFuture>#include <QMetaObject>#include <QProcess>+#include <QRegularExpression>+#include <QSet>#include <QSysInfo>+#include <QThread>#include <QtConcurrent>#include <atomic>@@ -54,30 +57,40 @@ QString PythonSetupManager::uv_path() const {}QString PythonSetupManager::base_python_path() const {- // UV-managed Python lives under UV's python dir- // We'll resolve it dynamically via `uv python find`+ // Guard: this function may block up to 10s — must not be called from the UI thread.+ // Acceptable call sites: main() before exec(), background threads, QtConcurrent::run().+ Q_ASSERT(QCoreApplication::instance() == nullptr ||+ QThread::currentThread() != QCoreApplication::instance()->thread());++ // Return cached result if already resolved this session.+ if (!cached_python_path_.isEmpty())+ return cached_python_path_;++ // Resolve via `uv python find` — spawns a process, so we only do this once.QProcess proc;QProcessEnvironment env = QProcessEnvironment::systemEnvironment();env.insert("UV_PYTHON_INSTALL_DIR", install_dir() + "/python");proc.setProcessEnvironment(env);proc.start(uv_path(), {"python", "find", kPythonVersion});if (proc.waitForFinished(10000) && proc.exitCode() == 0) {- return QString::fromUtf8(proc.readAllStandardOutput()).trimmed();+ cached_python_path_ = QString::fromUtf8(proc.readAllStandardOutput()).trimmed();+ return cached_python_path_;}- // Fallback: check known locations+ // Fallback: scan known install directory for the cpython-3.12 subdirectory.#ifdef _WIN32- // UV installs Python to UV_PYTHON_INSTALL_DIRQDir py_dir(install_dir() + "/python");auto entries = py_dir.entryList({"cpython-3.12*"}, QDir::Dirs);if (!entries.isEmpty()) {- return py_dir.filePath(entries.first() + "/python.exe");+ cached_python_path_ = py_dir.filePath(entries.first() + "/python.exe");+ return cached_python_path_;}#elseQDir py_dir(install_dir() + "/python");auto entries = py_dir.entryList({"cpython-3.12*"}, QDir::Dirs);if (!entries.isEmpty()) {- return py_dir.filePath(entries.first() + "/bin/python3");+ cached_python_path_ = py_dir.filePath(entries.first() + "/bin/python3");+ return cached_python_path_;}#endifreturn {};@@ -92,44 +105,252 @@ QString PythonSetupManager::python_path(const QString& venv_name) const {}// ─────────────────────────────────────────────────────────────────────────────-// Check status (fast, synchronous)+// Marker / hash helpers+//+// The .packages_installed marker now stores the SHA-256 hex of the requirements+// file that was used for the last *successful* install. A venv is "ready" only+// when this hash matches the current requirements file on disk.+//+// Old installs wrote "ok\n" — that never matches a 64-char hex string, so the+// first launch after updating to this code transparently migrates via the slow+// path (uv pip list check), then writes the real hash.// ─────────────────────────────────────────────────────────────────────────────-// Sentinel file written after a successful full setup. Its presence means we-// can skip the slow per-venv import checks on every subsequent launch.static QString sentinel_path_for(const QString& install_dir) {return install_dir + "/.setup_complete";}+static QString packages_marker_for(const QString& install_dir, const QString& venv_name) {+ return install_dir + "/" + venv_name + "/.packages_installed";+}++QString PythonSetupManager::read_marker_hash(const QString& venv_name) const {+ QFile f(packages_marker_for(install_dir(), venv_name));+ if (!f.open(QIODevice::ReadOnly))+ return {};+ return QString::fromUtf8(f.readAll()).trimmed();+}++void PythonSetupManager::write_marker_hash(const QString& venv_name, const QString& req_hash) const {+ if (req_hash.isEmpty())+ return;+ QFile f(packages_marker_for(install_dir(), venv_name));+ if (f.open(QIODevice::WriteOnly | QIODevice::Truncate))+ f.write((req_hash + "\n").toUtf8());+}++// ─────────────────────────────────────────────────────────────────────────────+// verify_packages_installed — slow-path cross-check via `uv pip list`+//+// Reads every package name from requirements_file, then asks UV what is+// actually installed in the venv. Returns true only if every required package+// is present. This runs on first launch, after marker deletion, or after a+// partial install — never on the fast path.+// ─────────────────────────────────────────────────────────────────────────────++bool PythonSetupManager::verify_packages_installed(const QString& venv_name,+ const QString& requirements_file) const {+ QString req_path = find_requirements_file(requirements_file);+ if (req_path.isEmpty()) {+ LOG_WARN("PythonSetup",+ QString("[%1] verify: requirements file not found: %2").arg(venv_name, requirements_file));+ return false;+ }++ QStringList expected = read_packages_from_file(req_path);+ if (expected.isEmpty())+ return false;++ // Run `uv pip list --python <venv_python>` — output is "name version" per line.+ QProcess proc;+ QProcessEnvironment env = QProcessEnvironment::systemEnvironment();+ env.insert("UV_PYTHON_INSTALL_DIR", install_dir() + "/python");+ proc.setProcessEnvironment(env);+#ifdef _WIN32+ proc.setCreateProcessArgumentsModifier([](QProcess::CreateProcessArguments* cpa) {+ cpa->flags |= 0x08000000; // CREATE_NO_WINDOW+ });+#endif+ proc.start(uv_path(), {"pip", "list", "--python", python_path(venv_name)});+ // 90s — generous headroom for large venvs (300+ packages) on slow disks or+ // when Windows Defender is scanning the venv directory. A false 30s timeout+ // previously marked a correctly-installed venv as broken, forcing a full reinstall.+ if (!proc.waitForFinished(90000) || proc.exitCode() != 0) {+ LOG_WARN("PythonSetup",+ QString("[%1] verify: uv pip list failed or timed out").arg(venv_name));+ return false;+ }++ // Build a normalised set of installed package names.+ // PEP 503: canonical name = lowercase, replace [-_.] with a single '-'.+ // We normalise both sides to lowercase + replace '-'/'.' with '_' for+ // a simple consistent comparison.+ auto normalise = [](const QString& name) -> QString {+ QString n = name.toLower();+ n.replace('-', '_');+ n.replace('.', '_');+ return n;+ };++ QSet<QString> installed;+ const QString output = QString::fromUtf8(proc.readAllStandardOutput());+ for (const QString& line : output.split('\n', Qt::SkipEmptyParts)) {+ const QString name = line.split(' ', Qt::SkipEmptyParts).value(0);+ if (!name.isEmpty())+ installed.insert(normalise(name));+ }++ // Check each required package. Strip version specifiers and extras before+ // comparing: "numpy>=1.26,<2.0" → "numpy", "scikit-learn>=1.4" → "scikit_learn".+ static const QRegularExpression kVersionRe(R"([><=!~\s\[].*)");+ QStringList missing;+ for (const QString& pkg : expected) {+ QString base = pkg;+ base.remove(kVersionRe);+ base = normalise(base.trimmed());+ if (base.isEmpty())+ continue;+ if (!installed.contains(base))+ missing << base;+ }++ if (!missing.isEmpty()) {+ LOG_WARN("PythonSetup",+ QString("[%1] verify: %2 package(s) missing: %3")+ .arg(venv_name).arg(missing.size()).arg(missing.join(", ").left(400)));+ return false;+ }++ LOG_INFO("PythonSetup",+ QString("[%1] verify: all %2 required packages present").arg(venv_name).arg(expected.size()));+ return true;+}++// ─────────────────────────────────────────────────────────────────────────────+// check_status (fast, synchronous)+// ─────────────────────────────────────────────────────────────────────────────+SetupStatus PythonSetupManager::check_status() const {SetupStatus status;status.install_dir = install_dir();- // ── Fast path: sentinel file written by run_setup() on success ───────────- // If it exists, trust that setup completed. Still do lightweight file-exists- // checks to catch a partially-deleted installation.- bool sentinel_exists = QFileInfo::exists(sentinel_path_for(install_dir()));- status.uv_installed = QFileInfo::exists(uv_path());- status.venv_numpy1_ready = QFileInfo::exists(python_path("venv-numpy1"));- status.venv_numpy2_ready = QFileInfo::exists(python_path("venv-numpy2"));-+ LOG_INFO("PythonSetup", "=== check_status BEGIN === install_dir: " + status.install_dir);++ // ── File-existence checks (always fast) ───────────────────────────────────+ status.uv_installed = QFileInfo::exists(uv_path());+ status.venv_numpy1_created = QFileInfo::exists(python_path("venv-numpy1"));+ status.venv_numpy2_created = QFileInfo::exists(python_path("venv-numpy2"));++ LOG_INFO("PythonSetup",+ QString("Existence: uv=%1 (%2) venv1_python=%3 (%4) venv2_python=%5 (%6)")+ .arg(status.uv_installed ? "YES" : "NO", uv_path())+ .arg(status.venv_numpy1_created ? "YES" : "NO", python_path("venv-numpy1"))+ .arg(status.venv_numpy2_created ? "YES" : "NO", python_path("venv-numpy2")));++ // ── Compute current requirements hashes ───────────────────────────────────+ // If a file is not found the hash is empty — treated as "not current",+ // which forces reinstall (correct) rather than silently skipping.+ const QString req_hash1 = compute_requirements_hash("requirements-numpy1.txt");+ const QString req_hash2 = compute_requirements_hash("requirements-numpy2.txt");++ LOG_INFO("PythonSetup",+ QString("Requirements hashes — numpy1: %1 numpy2: %2")+ .arg(req_hash1.isEmpty() ? "(file not found)" : req_hash1.left(16) + "...")+ .arg(req_hash2.isEmpty() ? "(file not found)" : req_hash2.left(16) + "..."));++ if (req_hash1.isEmpty())+ LOG_WARN("PythonSetup",+ "requirements-numpy1.txt NOT FOUND — find_requirements_file() returned empty. "+ "Check that resources/ folder is deployed beside the exe.");+ if (req_hash2.isEmpty())+ LOG_WARN("PythonSetup",+ "requirements-numpy2.txt NOT FOUND — find_requirements_file() returned empty. "+ "Check that resources/ folder is deployed beside the exe.");++ // A venv is "ready" only when its marker content equals the current hash.+ // Empty stored hash → old "ok\n" marker or absent file → not current.+ // Empty req hash → requirements file missing → not current (will fail at install).+ const QString stored1 = read_marker_hash("venv-numpy1");+ const QString stored2 = read_marker_hash("venv-numpy2");+ const bool pkg1_current = !req_hash1.isEmpty() && (stored1 == req_hash1);+ const bool pkg2_current = !req_hash2.isEmpty() && (stored2 == req_hash2);++ LOG_INFO("PythonSetup",+ QString("Markers — venv1 stored: %1 venv2 stored: %2 venv1_current: %3 venv2_current: %4")+ .arg(stored1.isEmpty() ? "(absent)" : stored1.left(16) + "...")+ .arg(stored2.isEmpty() ? "(absent)" : stored2.left(16) + "...")+ .arg(pkg1_current ? "YES" : "NO")+ .arg(pkg2_current ? "YES" : "NO"));++ status.venv_numpy1_ready = status.venv_numpy1_created && pkg1_current;+ status.venv_numpy2_ready = status.venv_numpy2_created && pkg2_current;++ const bool sentinel_exists = QFileInfo::exists(sentinel_path_for(install_dir()));+ LOG_INFO("PythonSetup",+ QString("Sentinel: %1 (%2)")+ .arg(sentinel_exists ? "EXISTS" : "ABSENT", sentinel_path_for(install_dir())));++ // ── Fast path: sentinel + UV + both markers current ───────────────────────if (sentinel_exists && status.uv_installed && status.venv_numpy1_ready && status.venv_numpy2_ready) {- // Everything looks intact — skip spawning any Python processes.status.python_installed = true;- status.needs_setup = false;- status.needs_package_sync = check_requirements_changed();- LOG_INFO("PythonSetup",- QString("Fast-path OK (sentinel present). needs_sync=%1").arg(status.needs_package_sync));+ status.needs_setup = false;+ LOG_INFO("PythonSetup", "Fast-path OK — sentinel + both hash-markers current → needs_setup=false");return status;}- // ── Slow path: first run or broken install — do full verification ─────────- LOG_INFO("PythonSetup", "Sentinel absent or install incomplete — running full check");+ // ── Package-sync sub-case: infra present but ≥1 venv hash is stale ────────+ // This sub-case is ONLY for a hash mismatch (requirements file updated after+ // a successful install). A missing marker (stored1/stored2 empty) means the+ // packages were never installed at all — that is needs_setup=true, not sync.+ //+ // Guard: skip this sub-case if either venv has an empty marker AND its venv+ // directory exists — that indicates an incomplete/empty venv that needs a+ // full package install, not just a background sync.+ const bool venv1_marker_absent = stored1.isEmpty();+ const bool venv2_marker_absent = stored2.isEmpty();+ const bool venv1_needs_full_install = status.venv_numpy1_created && venv1_marker_absent;+ const bool venv2_needs_full_install = status.venv_numpy2_created && venv2_marker_absent;++ if (sentinel_exists && status.uv_installed && status.venv_numpy1_created && status.venv_numpy2_created+ && !venv1_needs_full_install && !venv2_needs_full_install) {+ // Verify Python is present (cheap — just check the exe path).+ QString py = base_python_path();+ LOG_INFO("PythonSetup",+ QString("Sync-check: base python = %1 exists = %2")+ .arg(py.isEmpty() ? "(not found)" : py)+ .arg(QFileInfo::exists(py) ? "YES" : "NO"));+ if (!py.isEmpty() && QFileInfo::exists(py)) {+ status.python_installed = true;+ if (!pkg1_current || !pkg2_current) {+ status.needs_setup = false;+ status.needs_package_sync = true;+ LOG_INFO("PythonSetup",+ QString("Package-sync path: infra OK, hash stale — needs_sync=true "+ "(venv1_current=%1 venv2_current=%2)")+ .arg(pkg1_current ? "YES" : "NO")+ .arg(pkg2_current ? "YES" : "NO"));+ return status;+ }+ }+ } else if (venv1_needs_full_install || venv2_needs_full_install) {+ LOG_WARN("PythonSetup",+ QString("Skipping sync sub-case — venv(s) have empty markers (packages never installed): "+ "venv1_needs_full=%1 venv2_needs_full=%2")+ .arg(venv1_needs_full_install ? "YES" : "NO")+ .arg(venv2_needs_full_install ? "YES" : "NO"));+ }- // Check Python (via UV) — run uv python find on a background-safe call- // (this function is only reached on first run, so blocking is acceptable)+ // ── Slow path: first run or broken install ────────────────────────────────+ LOG_INFO("PythonSetup", "Slow path: running full status check (sentinel/markers absent or stale)");++ // Check Python is working (blocking — only runs on first launch or after+ // partial install when no window is visible yet).if (status.uv_installed) {QString py = base_python_path();+ LOG_INFO("PythonSetup",+ QString("Python check: path=%1 exists=%2")+ .arg(py.isEmpty() ? "(not found)" : py)+ .arg(py.isEmpty() ? "N/A" : (QFileInfo::exists(py) ? "YES" : "NO")));if (!py.isEmpty() && QFileInfo::exists(py)) {QProcess proc;#ifdef _WIN32@@ -140,62 +361,74 @@ SetupStatus PythonSetupManager::check_status() const {proc.start(py, {"--version"});if (proc.waitForFinished(5000) && proc.exitCode() == 0) {status.python_installed = true;- status.python_version = QString::fromUtf8(proc.readAllStandardOutput()).trimmed();+ status.python_version = QString::fromUtf8(proc.readAllStandardOutput()).trimmed();+ LOG_INFO("PythonSetup", "Python OK: " + status.python_version);+ } else {+ LOG_WARN("PythonSetup",+ QString("Python --version failed: exit=%1 stderr=%2")+ .arg(proc.exitCode())+ .arg(QString::fromUtf8(proc.readAllStandardError()).left(300)));}+ } else {+ LOG_WARN("PythonSetup", "Python not installed yet (UV present but python path missing)");}+ } else {+ LOG_WARN("PythonSetup", "UV not installed — skipping Python check");}- // Check venvs — verify python runs AND key packages are importable- auto check_venv = [this](const QString& name, const QStringList& marker_packages) -> bool {- QString vpy = python_path(name);- if (!QFileInfo::exists(vpy))- return false;-- QProcess ver_proc;-#ifdef _WIN32- ver_proc.setCreateProcessArgumentsModifier(- [](QProcess::CreateProcessArguments* cpa) { cpa->flags |= 0x08000000; });-#endif- ver_proc.start(vpy, {"--version"});- if (!ver_proc.waitForFinished(5000) || ver_proc.exitCode() != 0)- return false;-- QStringList imports;- for (const auto& pkg : marker_packages)- imports << ("import " + pkg);- QString check_code = imports.join("; ") + "; print('OK')";-- QProcess pkg_proc;-#ifdef _WIN32- pkg_proc.setCreateProcessArgumentsModifier(- [](QProcess::CreateProcessArguments* cpa) { cpa->flags |= 0x08000000; });-#endif- pkg_proc.start(vpy, {"-c", check_code});- if (!pkg_proc.waitForFinished(15000) || pkg_proc.exitCode() != 0) {- QString err = QString::fromUtf8(pkg_proc.readAllStandardError());- LOG_WARN("PythonSetup", QString("Venv %1 missing packages: %2").arg(name, err.left(200)));- return false;+ // ── Slow-path package verification ────────────────────────────────────────+ // The marker is absent OR stale (hash mismatch). Run `uv pip list` to+ // check whether every required package is actually present. This covers:+ // - First launch after updating the app (old "ok\n" marker)+ // - Manual marker deletion+ // - Partial install that failed to write the marker+ // If verification passes we write the current hash marker so future launches+ // use the fast path. If it fails we leave needs_setup=true → full install.+ if (status.venv_numpy1_created && !pkg1_current) {+ LOG_INFO("PythonSetup", "venv-numpy1: marker stale/absent — running uv pip list verification");+ if (!req_hash1.isEmpty() && verify_packages_installed("venv-numpy1", "requirements-numpy1.txt")) {+ write_marker_hash("venv-numpy1", req_hash1);+ status.venv_numpy1_ready = true;+ LOG_INFO("PythonSetup", "venv-numpy1: verification passed — marker written");+ } else {+ LOG_WARN("PythonSetup",+ QString("venv-numpy1: packages absent/incomplete/changed — needs install "+ "(req_hash_empty=%1)")+ .arg(req_hash1.isEmpty() ? "YES" : "NO"));}- return QString::fromUtf8(pkg_proc.readAllStandardOutput()).trimmed().contains("OK");- };-- status.venv_numpy1_ready = check_venv("venv-numpy1", {"numpy", "pandas", "vectorbt"});- status.venv_numpy2_ready = check_venv("venv-numpy2", {"numpy", "pandas", "requests", "sklearn"});-- status.needs_setup =- !status.uv_installed || !status.python_installed || !status.venv_numpy1_ready || !status.venv_numpy2_ready;+ }- if (!status.needs_setup) {- status.needs_package_sync = check_requirements_changed();+ if (status.venv_numpy2_created && !pkg2_current) {+ LOG_INFO("PythonSetup", "venv-numpy2: marker stale/absent — running uv pip list verification");+ if (!req_hash2.isEmpty() && verify_packages_installed("venv-numpy2", "requirements-numpy2.txt")) {+ write_marker_hash("venv-numpy2", req_hash2);+ status.venv_numpy2_ready = true;+ LOG_INFO("PythonSetup", "venv-numpy2: verification passed — marker written");+ } else {+ LOG_WARN("PythonSetup",+ QString("venv-numpy2: packages absent/incomplete/changed — needs install "+ "(req_hash_empty=%1)")+ .arg(req_hash2.isEmpty() ? "YES" : "NO"));+ }}- LOG_INFO("PythonSetup", QString("Full check: uv=%1 py=%2 venv1=%3 venv2=%4 needs_setup=%5 needs_sync=%6")- .arg(status.uv_installed)- .arg(status.python_installed)- .arg(status.venv_numpy1_ready)- .arg(status.venv_numpy2_ready)- .arg(status.needs_setup)- .arg(status.needs_package_sync));+ status.needs_setup =+ !status.uv_installed || !status.python_installed ||+ !status.venv_numpy1_ready || !status.venv_numpy2_ready;++ LOG_INFO("PythonSetup",+ QString("=== check_status RESULT === uv=%1 py=%2 "+ "venv1_created=%3 venv1_ready=%4 "+ "venv2_created=%5 venv2_ready=%6 "+ "needs_setup=%7 needs_sync=%8")+ .arg(status.uv_installed ? "YES" : "NO")+ .arg(status.python_installed ? "YES" : "NO")+ .arg(status.venv_numpy1_created ? "YES" : "NO")+ .arg(status.venv_numpy1_ready ? "YES" : "NO")+ .arg(status.venv_numpy2_created ? "YES" : "NO")+ .arg(status.venv_numpy2_ready ? "YES" : "NO")+ .arg(status.needs_setup ? "YES" : "NO")+ .arg(status.needs_package_sync ? "YES" : "NO"));return status;}@@ -204,6 +437,7 @@ SetupStatus PythonSetupManager::check_status() const {// ─────────────────────────────────────────────────────────────────────────────void PythonSetupManager::run_setup() {+ LOG_INFO("PythonSetup", "=== run_setup START ===");QPointer<PythonSetupManager> self = this;QtConcurrent::run([self]() {@@ -211,6 +445,7 @@ void PythonSetupManager::run_setup() {return;auto fail = [&](const QString& msg) {+ LOG_ERROR("PythonSetup", "run_setup FAILED: " + msg);QMetaObject::invokeMethod(self,[self, msg]() {@@ -220,7 +455,14 @@ void PythonSetupManager::run_setup() {Qt::QueuedConnection);};+ LOG_INFO("PythonSetup", "run_setup: calling check_status...");auto status = self->check_status();+ LOG_INFO("PythonSetup",+ QString("run_setup: status — uv=%1 py=%2 venv1_ready=%3 venv2_ready=%4")+ .arg(status.uv_installed ? "YES" : "NO")+ .arg(status.python_installed ? "YES" : "NO")+ .arg(status.venv_numpy1_ready ? "YES" : "NO")+ .arg(status.venv_numpy2_ready ? "YES" : "NO"));// ── Step 1: Download UV standalone binary (~13MB) ────────────────────if (!status.uv_installed) {@@ -249,8 +491,10 @@ void PythonSetupManager::run_setup() {}// ── Step 3: Create both venvs in PARALLEL ───────────────────────────- bool need_venv1 = !status.venv_numpy1_ready;- bool need_venv2 = !status.venv_numpy2_ready;+ // Use venv_NNN_created (python exe exists) to decide if venv creation+ // is needed — distinct from venv_NNN_ready (packages installed).+ bool need_venv1 = !status.venv_numpy1_created;+ bool need_venv2 = !status.venv_numpy2_created;if (need_venv1 || need_venv2) {self->emit_progress("venv", 0, "Creating virtual environments...");@@ -282,6 +526,9 @@ void PythonSetupManager::run_setup() {}// ── Step 4: Install packages in PARALLEL ────────────────────────────+ // Use venv_NNN_ready (packages marker exists) — not venv_NNN_created —+ // so we always install packages when only the venv dir exists but the+ // package-install marker is absent (e.g. network failed last time).bool need_pkg1 = !status.venv_numpy1_ready;bool need_pkg2 = !status.venv_numpy2_ready;@@ -332,15 +579,9 @@ void PythonSetupManager::run_setup() {return;}- // ── Save requirements hashes so we can detect changes on next app update ──- QString h1 = self->compute_requirements_hash("requirements-numpy1.txt");- QString h2 = self->compute_requirements_hash("requirements-numpy2.txt");- if (!h1.isEmpty())- self->save_hash("venv-numpy1", h1);- if (!h2.isEmpty())- self->save_hash("venv-numpy2", h2);-// ── Write sentinel so future launches skip the slow import checks ────+ // (Package markers already written with the requirements hash inside+ // install_packages() — no separate hash-file step needed.){QFile sentinel(sentinel_path_for(self->install_dir()));if (sentinel.open(QIODevice::WriteOnly | QIODevice::Truncate)) {@@ -399,13 +640,27 @@ bool PythonSetupManager::download_uv() {emit_progress("uv", 60, "Extracting UV...");- // Extract+ // Extract — prefer tar.exe (ships with Windows 10 1803+, much faster than+ // PowerShell Expand-Archive). Fall back to PowerShell on older systems.#ifdef _WIN32- if (!run_command("powershell",- {"-NoProfile", "-Command",- QString("Expand-Archive -Path '%1' -DestinationPath '%2' -Force").arg(archive_path, dir)})) {- LOG_ERROR("PythonSetup", "Failed to extract UV");- return false;+ {+ QString unused;+ bool extracted = false;+ if (run_command_capture("tar.exe", {"--version"}, {}, unused)) {+ // tar on Windows accepts -xf for zip since Windows 10 build 17063+ extracted = run_command("tar.exe", {"-xf", archive_path, "-C", dir});+ }+ if (!extracted) {+ // Fallback: PowerShell Expand-Archive+ extracted = run_command("powershell",+ {"-NoProfile", "-NonInteractive", "-Command",+ QString("Expand-Archive -Path '%1' -DestinationPath '%2' -Force")+ .arg(archive_path, dir)});+ }+ if (!extracted) {+ LOG_ERROR("PythonSetup", "Failed to extract UV archive");+ return false;+ }}// The zip contains uv.exe inside a subfolder — move it up if neededQString nested = dir + "/uv-" + target + "/uv.exe";@@ -463,6 +718,10 @@ bool PythonSetupManager::install_python_via_uv() {emit_progress("python", 80, "Verifying Python...");+ // Clear the cached path — Python was just installed so the previous+ // (empty or stale) cached value must not be returned by base_python_path().+ cached_python_path_.clear();+// VerifyQString py = base_python_path();if (py.isEmpty() || !QFileInfo::exists(py)) {@@ -507,16 +766,32 @@ bool PythonSetupManager::create_venv(const QString& venv_name) {// ─────────────────────────────────────────────────────────────────────────────bool PythonSetupManager::install_packages(const QString& venv_name, const QString& requirements_file) {+ // Derive step key first — needed for all emit_progress calls including early returns+ const QString step_key = venv_name.contains("numpy1") ? "packages-numpy1" : "packages-numpy2";++ LOG_INFO("PythonSetup",+ QString("install_packages: venv=%1 req_file=%2 venv_python=%3")+ .arg(venv_name, requirements_file, python_path(venv_name)));+QString req_path = find_requirements_file(requirements_file);if (req_path.isEmpty()) {- LOG_ERROR("PythonSetup", "Requirements file not found: " + requirements_file);+ QString exe_dir = QCoreApplication::applicationDirPath();+ LOG_ERROR("PythonSetup",+ QString("Requirements file not found: %1\n"+ " exe_dir: %2\n"+ " Expected: %2/resources/%1\n"+ " The resources/ folder must be deployed beside the exe.\n"+ " CMakeLists.txt POST_BUILD should copy resources/*.txt — rebuild to fix.")+ .arg(requirements_file, exe_dir));+ emit_progress(step_key, 0,+ QString("Setup file missing: %1 — reinstall the application").arg(requirements_file), true);return false;}+ LOG_INFO("PythonSetup", QString("install_packages: resolved req_path=%1").arg(req_path));LOG_INFO("PythonSetup", QString("Installing packages into %1 from %2").arg(venv_name, req_path));- QString venv_python = python_path(venv_name);- QString step_key = venv_name.contains("numpy1") ? "packages-numpy1" : "packages-numpy2";+ const QString venv_python = python_path(venv_name);QStringList env = {"UV_PYTHON_INSTALL_DIR=" + install_dir() + "/python",@@ -535,13 +810,19 @@ bool PythonSetupManager::install_packages(const QString& venv_name, const QStrinif (bulk_ok) {LOG_INFO("PythonSetup", QString("[%1] Bulk install succeeded").arg(venv_name));+ // Write the requirements hash as the marker — future check_status() calls+ // compare this hash against the current requirements file to detect changes.+ write_marker_hash(venv_name, compute_requirements_hash(requirements_file));emit_progress(step_key, 100, "All packages installed");return true;}// ── Pass 2: bulk failed — install packages one-by-one, skip failures ────- LOG_WARN("PythonSetup", QString("[%1] Bulk install failed (stderr: %2) — falling back to per-package install")- .arg(venv_name, bulk_stderr.left(300)));+ LOG_WARN("PythonSetup",+ QString("[%1] Bulk install failed — falling back to per-package install.\n"+ " UV command: %2 pip install --python %3 -r %4\n"+ " stderr (first 600 chars): %5")+ .arg(venv_name, uv_path(), venv_python, req_path, bulk_stderr.left(600)));emit_progress(step_key, 10, "Bulk install failed — retrying package by package...");QStringList packages = read_packages_from_file(req_path);@@ -554,17 +835,21 @@ bool PythonSetupManager::install_packages(const QString& venv_name, const QStrinif (failed.isEmpty()) {LOG_INFO("PythonSetup", QString("[%1] All packages installed individually").arg(venv_name));+ // 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) skipped: %3")+ LOG_WARN("PythonSetup", QString("[%1] %2 package(s) failed: %3").arg(venv_name).arg(failed.size()).arg(failed.join(", ").left(300)));- emit_progress(step_key, 100, QString("Done — %1 package(s) skipped (see log)").arg(failed.size()));+ // 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()));}- // Always return true from pass 2 — a partial environment is more useful- // than no environment. The skipped packages are logged for diagnosis.return true;}@@ -631,7 +916,15 @@ QStringList PythonSetupManager::install_packages_individually(const QString& ven// ─────────────────────────────────────────────────────────────────────────────QString PythonSetupManager::find_requirements_file(const QString& filename) const {+ // Return cached path — requirements files never move at runtime.+ auto it = cached_req_paths_.find(filename);+ if (it != cached_req_paths_.end()) {+ LOG_DEBUG("PythonSetup", "find_requirements_file cache hit: " + filename + " → " + it.value());+ return it.value();+ }+QString exe_dir = QCoreApplication::applicationDirPath();+ LOG_INFO("PythonSetup", "find_requirements_file: searching for " + filename + " exe_dir=" + exe_dir);// Search relative to executableQStringList candidates = {@@ -640,103 +933,105 @@ QString PythonSetupManager::find_requirements_file(const QString& filename) consexe_dir + "/../../resources/" + filename,};- // Walk up from exe to find project root+ // Walk up from exe to find project root (dev/build layout)QDir dir(exe_dir);while (dir.cdUp()) {QString c = dir.filePath("resources/" + filename);- if (QFileInfo::exists(c))- return QDir::cleanPath(c);+ if (QFileInfo::exists(c)) {+ QString resolved = QDir::cleanPath(c);+ LOG_INFO("PythonSetup", "find_requirements_file found (walk-up): " + resolved);+ cached_req_paths_.insert(filename, resolved);+ return resolved;+ }if (dir.isRoot())break;}for (const auto& c : candidates) {- if (QFileInfo::exists(c))- return QDir::cleanPath(c);+ LOG_DEBUG("PythonSetup", "find_requirements_file candidate: " + c ++ (QFileInfo::exists(c) ? " [EXISTS]" : " [missing]"));+ if (QFileInfo::exists(c)) {+ QString resolved = QDir::cleanPath(c);+ LOG_INFO("PythonSetup", "find_requirements_file found (candidate): " + resolved);+ cached_req_paths_.insert(filename, resolved);+ return resolved;+ }}+ LOG_ERROR("PythonSetup",+ "find_requirements_file: " + filename + " NOT FOUND anywhere.\n"+ " exe_dir=" + exe_dir + "\n"+ " Tried: " + candidates.join(", ") + "\n"+ " Fix: ensure the POST_BUILD CMake step copies resources/ beside the exe.");return {};}// ─────────────────────────────────────────────────────────────────────────────-// Helper: run command (synchronous, used on background threads)+// Internal: configure and run a QProcess synchronously (background threads only)+//+// Both run_command() and run_command_capture() delegate here.+// Returns true on exit-code 0; populates stderr_out (may be nullptr to discard).// ─────────────────────────────────────────────────────────────────────────────-bool PythonSetupManager::run_command(const QString& program, const QStringList& args,- const QStringList& env_vars) const {+static bool run_process(const QString& program, const QStringList& args,+ const QStringList& env_vars, QString* stderr_out) {QProcess proc;if (!env_vars.isEmpty()) {QProcessEnvironment env = QProcessEnvironment::systemEnvironment();for (const auto& var : env_vars) {- int eq = var.indexOf('=');- if (eq > 0) {+ const int eq = var.indexOf('=');+ if (eq > 0)env.insert(var.left(eq), var.mid(eq + 1));- }}proc.setProcessEnvironment(env);}#ifdef _WIN32proc.setCreateProcessArgumentsModifier([](QProcess::CreateProcessArguments* cpa) {- cpa->flags |= 0x08000000; // CREATE_NO_WINDOW+ cpa->flags |= 0x08000000; // CREATE_NO_WINDOW — prevent console flash});#endif- LOG_INFO("PythonSetup", QString("Running: %1 %2").arg(program, args.join(" ")));-proc.start(program, args);- if (!proc.waitForFinished(30 * 60 * 1000)) { // 30 min timeout- LOG_ERROR("PythonSetup", "Command timed out: " + program);+ constexpr int kTimeoutMs = 30 * 60 * 1000; // 30 minutes+ if (!proc.waitForFinished(kTimeoutMs)) {proc.kill();+ if (stderr_out)+ *stderr_out = QStringLiteral("timed out");return false;}- if (proc.exitCode() != 0) {- QString stderr_out = QString::fromUtf8(proc.readAllStandardError());- LOG_ERROR("PythonSetup", QString("Command failed (exit %1): %2\nStderr: %3")- .arg(proc.exitCode())- .arg(program)- .arg(stderr_out.left(500)));- return false;- }+ if (stderr_out)+ *stderr_out = QString::fromUtf8(proc.readAllStandardError());- return true;+ return proc.exitCode() == 0;}// ─────────────────────────────────────────────────────────────────────────────-// Helper: run command, capture stderr (used for per-package failure diagnosis)+// Helper: run command (synchronous, used on background threads)// ─────────────────────────────────────────────────────────────────────────────-bool PythonSetupManager::run_command_capture(const QString& program, const QStringList& args,- const QStringList& env_vars, QString& stderr_out) const {- QProcess proc;+bool PythonSetupManager::run_command(const QString& program, const QStringList& args,+ const QStringList& env_vars) const {+ LOG_INFO("PythonSetup", QString("Running: %1 %2").arg(program, args.join(' ')));- if (!env_vars.isEmpty()) {- QProcessEnvironment env = QProcessEnvironment::systemEnvironment();- for (const auto& var : env_vars) {- int eq = var.indexOf('=');- if (eq > 0)- env.insert(var.left(eq), var.mid(eq + 1));- }- proc.setProcessEnvironment(env);+ QString stderr_out;+ const bool ok = run_process(program, args, env_vars, &stderr_out);+ if (!ok) {+ LOG_ERROR("PythonSetup",+ QString("Command failed: %1\nStderr: %2").arg(program, stderr_out.left(500)));}+ return ok;+}-#ifdef _WIN32- proc.setCreateProcessArgumentsModifier([](QProcess::CreateProcessArguments* cpa) {- cpa->flags |= 0x08000000; // CREATE_NO_WINDOW- });-#endif-- proc.start(program, args);- if (!proc.waitForFinished(30 * 60 * 1000)) {- proc.kill();- stderr_out = "timed out";- return false;- }+// ─────────────────────────────────────────────────────────────────────────────+// Helper: run command, capture stderr (used for per-package failure diagnosis)+// ─────────────────────────────────────────────────────────────────────────────- stderr_out = QString::fromUtf8(proc.readAllStandardError());- return proc.exitCode() == 0;+bool PythonSetupManager::run_command_capture(const QString& program, const QStringList& args,+ const QStringList& env_vars, QString& stderr_out) const {+ return run_process(program, args, env_vars, &stderr_out);}// ─────────────────────────────────────────────────────────────────────────────@@ -745,19 +1040,36 @@ bool PythonSetupManager::run_command_capture(const QString& program, const QStriQString PythonSetupManager::download_file(const QString& url, const QString& dest_path) const {#ifdef _WIN32- QProcess proc;- proc.setCreateProcessArgumentsModifier([](QProcess::CreateProcessArguments* cpa) { cpa->flags |= 0x08000000; });- proc.start("powershell",- {"-NoProfile", "-Command",- QString("[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; "- "Invoke-WebRequest -Uri '%1' -OutFile '%2' -UseBasicParsing")- .arg(url, dest_path)});- if (!proc.waitForFinished(15 * 60 * 1000)) {- proc.kill();- return "Download timed out";+ // Windows 10 1803+ ships curl.exe in System32. Try it first — clear errors,+ // --retry support, and starts much faster than spawning PowerShell.+ bool downloaded = false;++ {+ // Probe for curl.exe availability (3-second timeout)+ QString unused;+ if (run_process("curl.exe", {"--version"}, {}, &unused)) {+ QString curl_err;+ downloaded = run_process("curl.exe",+ {"-L", "--fail", "--retry", "3",+ "--connect-timeout", "30", "-o", dest_path, url},+ {}, &curl_err);+ if (!downloaded)+ LOG_WARN("PythonSetup", "curl.exe failed, falling back to PowerShell: " + curl_err.left(300));+ }}- if (proc.exitCode() != 0) {- return "Download failed: " + QString::fromUtf8(proc.readAllStandardError()).left(200);++ if (!downloaded) {+ // Fallback: PowerShell Invoke-WebRequest+ QString ps_err;+ const QString ps_cmd =+ QString("[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; "+ "Invoke-WebRequest -Uri '%1' -OutFile '%2' -UseBasicParsing")+ .arg(url, dest_path);+ if (!run_process("powershell", {"-NoProfile", "-NonInteractive", "-Command", ps_cmd}, {}, &ps_err)) {+ if (ps_err.isEmpty())+ ps_err = "unknown error (no stderr)";+ return "Download failed. Check your internet connection.\nDetail: " + ps_err.left(300);+ }}#else// Verify curl is available before launching — gives a clear error@@ -799,6 +1111,11 @@ QString PythonSetupManager::download_file(const QString& url, const QString& des// ─────────────────────────────────────────────────────────────────────────────QString PythonSetupManager::compute_requirements_hash(const QString& filename) const {+ // Return cached hash — requirements files never change at runtime.+ auto it = cached_req_hashes_.find(filename);+ if (it != cached_req_hashes_.end())+ return it.value();+QString path = find_requirements_file(filename);if (path.isEmpty())return {};@@ -808,41 +1125,9 @@ QString PythonSetupManager::compute_requirements_hash(const QString& filename) creturn {};QByteArray content = file.readAll();- return QString(QCryptographicHash::hash(content, QCryptographicHash::Sha256).toHex());-}--QString PythonSetupManager::load_stored_hash(const QString& venv_name) const {- QString hash_file = install_dir() + "/" + venv_name + "/.requirements_hash";- QFile file(hash_file);- if (!file.open(QIODevice::ReadOnly))- return {};- return QString::fromUtf8(file.readAll()).trimmed();-}--void PythonSetupManager::save_hash(const QString& venv_name, const QString& hash) const {- QString hash_file = install_dir() + "/" + venv_name + "/.requirements_hash";- QFile file(hash_file);- if (file.open(QIODevice::WriteOnly | QIODevice::Truncate)) {- file.write(hash.toUtf8());- }-}--bool PythonSetupManager::check_requirements_changed() const {- // Compare current requirements file hashes with stored ones- QString hash1 = compute_requirements_hash("requirements-numpy1.txt");- QString hash2 = compute_requirements_hash("requirements-numpy2.txt");-- if (hash1.isEmpty() || hash2.isEmpty())- return false; // can't compute, skip-- QString stored1 = load_stored_hash("venv-numpy1");- QString stored2 = load_stored_hash("venv-numpy2");-- bool changed = (stored1 != hash1) || (stored2 != hash2);- if (changed) {- LOG_INFO("PythonSetup", "Requirements files have changed since last install");- }- return changed;+ QString hash = QString(QCryptographicHash::hash(content, QCryptographicHash::Sha256).toHex());+ cached_req_hashes_.insert(filename, hash);+ return hash;}// ─────────────────────────────────────────────────────────────────────────────diff --git a/fincept-qt/src/python/PythonSetupManager.h b/fincept-qt/src/python/PythonSetupManager.hindex f43ff77c2..b999f50e0 100644--- a/fincept-qt/src/python/PythonSetupManager.h+++ b/fincept-qt/src/python/PythonSetupManager.h@@ -12,6 +12,7 @@// Estimated setup time: 3-5 minutes (down from 10-20 minutes).#pragma once+#include <QMap>#include <QObject>#include <QString>@@ -21,20 +22,22 @@ namespace fincept::python {struct SetupStatus {bool uv_installed = false;bool python_installed = false;- bool venv_numpy1_ready = false;+ bool venv_numpy1_created = false; // venv directory and python exe exist+ bool venv_numpy2_created = false;+ bool venv_numpy1_ready = false; // venv created AND current requirements hash matches markerbool venv_numpy2_ready = false;bool needs_setup = true;- bool needs_package_sync = false; // true if requirements files changed since last install+ bool needs_package_sync = false; // infra OK but ≥1 venv has a stale requirements hashQString python_version;QString install_dir;};/// Progress emitted during setupstruct SetupProgress {- QString step; // "uv", "python", "venv", "packages-numpy1", "packages-numpy2", "complete"- int progress; // 0-100+ QString step; // "uv", "python", "venv", "packages-numpy1", "packages-numpy2", "complete"+ int progress = 0; // 0-100 — default-initialized to prevent garbage readsQString message;- bool is_error = false;+ bool is_error = false;};class PythonSetupManager : public QObject {@@ -66,7 +69,7 @@ class PythonSetupManager : public QObject {private:explicit PythonSetupManager(QObject* parent = nullptr);- Q_DISABLE_COPY(PythonSetupManager)+ Q_DISABLE_COPY_MOVE(PythonSetupManager)void emit_progress(const QString& step, int pct, const QString& msg, bool err = false);@@ -89,14 +92,24 @@ class PythonSetupManager : public QObject {QStringList install_packages_individually(const QString& venv_name, const QStringList& packages,const QStringList& env_vars, const QString& step_key);- // Requirements hash tracking — detect when requirements change across app versions+ // Hash-based marker helpers — marker stores the SHA-256 of the requirements+ // file used for the last successful install; stale or absent → reinstall.QString compute_requirements_hash(const QString& filename) const;- QString load_stored_hash(const QString& venv_name) const;- void save_hash(const QString& venv_name, const QString& hash) const;- bool check_requirements_changed() const;+ QString read_marker_hash(const QString& venv_name) const;+ void write_marker_hash(const QString& venv_name, const QString& req_hash) const;++ // Slow-path package verification via `uv pip list` — checks every package+ // in requirements_file is actually present in the given venv.+ bool verify_packages_installed(const QString& venv_name,+ const QString& requirements_file) const;static constexpr const char* kPythonVersion = "3.12";static constexpr const char* kUvVersion = "0.7.12";++ // Session-lifetime caches — requirements files never change at runtime.+ mutable QString cached_python_path_; // cleared after fresh Python install+ mutable QMap<QString, QString> cached_req_paths_; // filename → resolved absolute path+ mutable QMap<QString, QString> cached_req_hashes_; // filename → SHA-256 hex};} // namespace fincept::pythondiff --git a/fincept-qt/src/screens/agent_config/AgentConfigScreen.cpp b/fincept-qt/src/screens/agent_config/AgentConfigScreen.cppindex ed1daf46e..88aec5a47 100644--- a/fincept-qt/src/screens/agent_config/AgentConfigScreen.cpp+++ b/fincept-qt/src/screens/agent_config/AgentConfigScreen.cpp@@ -2,6 +2,7 @@#include "screens/agent_config/AgentConfigScreen.h"#include "core/logging/Logger.h"+#include "core/session/ScreenStateManager.h"#include "screens/agent_config/AgentChatPanel.h"#include "screens/agent_config/AgentsViewPanel.h"#include "screens/agent_config/CreateAgentPanel.h"@@ -290,6 +291,8 @@ void AgentConfigScreen::set_view(services::AgentViewMode mode) {for (int i = 0; i < nav_buttons_.size(); ++i)nav_buttons_[i]->setChecked(i == idx);++ fincept::ScreenStateManager::instance().notify_changed(this);}// ── Service-level connections (global signals, no per-panel wiring) ──────────@@ -345,4 +348,17 @@ void AgentConfigScreen::hideEvent(QHideEvent* event) {QWidget::hideEvent(event);}+// ── IStatefulScreen ──────────────────────────────────────────────────────────++QVariantMap AgentConfigScreen::save_state() const {+ return {{"view", static_cast<int>(current_view_)}};+}++void AgentConfigScreen::restore_state(const QVariantMap& state) {+ const int v = state.value("view", -1).toInt();+ if (v < 0)+ return;+ set_view(static_cast<services::AgentViewMode>(v));+}+} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/agent_config/AgentConfigScreen.h b/fincept-qt/src/screens/agent_config/AgentConfigScreen.hindex cfdb593dd..6459b6071 100644--- a/fincept-qt/src/screens/agent_config/AgentConfigScreen.h+++ b/fincept-qt/src/screens/agent_config/AgentConfigScreen.h@@ -1,5 +1,6 @@// src/screens/agent_config/AgentConfigScreen.h#pragma once+#include "screens/IStatefulScreen.h"#include "services/agents/AgentTypes.h"#include <QLabel>@@ -24,11 +25,17 @@ namespace fincept::screens {/// Main Agent Studio screen — 8-view navigation shell./// Panels are constructed lazily on first navigation (P2 compliance).-class AgentConfigScreen : public QWidget {+class AgentConfigScreen : public QWidget, public IStatefulScreen {Q_OBJECTpublic:explicit AgentConfigScreen(QWidget* parent = nullptr);+ // IStatefulScreen — persists the currently active sub-view so users+ // return to the same panel after restart.+ QVariantMap save_state() const override;+ void restore_state(const QVariantMap& state) override;+ QString state_key() const override { return "agent_config"; }+protected:void showEvent(QShowEvent* event) override;void hideEvent(QHideEvent* event) override;diff --git a/fincept-qt/src/screens/akshare/AkShareScreen.cpp b/fincept-qt/src/screens/akshare/AkShareScreen.cppindex d9020c361..160b0d989 100644--- a/fincept-qt/src/screens/akshare/AkShareScreen.cpp+++ b/fincept-qt/src/screens/akshare/AkShareScreen.cpp@@ -1,6 +1,7 @@#include "screens/akshare/AkShareScreen.h"#include "core/logging/Logger.h"+#include "core/session/ScreenStateManager.h"#include "python/PythonRunner.h"#include "storage/cache/CacheManager.h"#include "ui/theme/Theme.h"@@ -9,6 +10,7 @@#include <QHBoxLayout>#include <QJsonDocument>#include <QPointer>+#include <QTimer>#include <QScrollArea>#include <QVBoxLayout>@@ -496,6 +498,8 @@ void AkShareScreen::on_source_clicked(int index) {} else {load_endpoints(sources_[index]);}++ fincept::ScreenStateManager::instance().notify_changed(this);}void AkShareScreen::on_endpoint_clicked(QListWidgetItem* item) {@@ -505,6 +509,8 @@ void AkShareScreen::on_endpoint_clicked(QListWidgetItem* item) {status_endpoint_->setText(active_endpoint_);refresh_btn_->setEnabled(true);+ fincept::ScreenStateManager::instance().notify_changed(this);+// Auto-executeon_execute();}@@ -516,6 +522,7 @@ void AkShareScreen::on_search_changed(const QString& text) {item->data(Qt::UserRole).toString().contains(text, Qt::CaseInsensitive);item->setHidden(!match);}+ fincept::ScreenStateManager::instance().notify_changed(this);}void AkShareScreen::on_execute() {@@ -541,6 +548,7 @@ void AkShareScreen::on_view_toggle() {is_table_view_ = !is_table_view_;view_stack_->setCurrentIndex(is_table_view_ ? 0 : 1);view_toggle_btn_->setText(is_table_view_ ? "JSON" : "TABLE");+ fincept::ScreenStateManager::instance().notify_changed(this);}void AkShareScreen::on_refresh() {@@ -857,4 +865,49 @@ void AkShareScreen::set_loading(bool loading) {}}+// ── IStatefulScreen ──────────────────────────────────────────────────────────++QVariantMap AkShareScreen::save_state() const {+ return {+ {"source", active_source_},+ {"endpoint", active_endpoint_},+ {"search", search_input_ ? search_input_->text() : QString()},+ {"table_view", is_table_view_},+ };+}++void AkShareScreen::restore_state(const QVariantMap& state) {+ const int src = state.value("source", -1).toInt();+ if (src >= 0 && src < sources_.size())+ on_source_clicked(src);++ const QString search = state.value("search").toString();+ if (search_input_ && !search.isEmpty())+ search_input_->setText(search);++ const bool table_view = state.value("table_view", true).toBool();+ if (table_view != is_table_view_)+ on_view_toggle();++ // Endpoint selection requires the endpoint list to be populated first,+ // which happens async after load_endpoints(). Defer restore.+ const QString ep = state.value("endpoint").toString();+ if (!ep.isEmpty() && endpoint_list_) {+ QPointer<AkShareScreen> self = this;+ QTimer::singleShot(500, this, [self, ep]() {+ if (!self || !self->endpoint_list_)+ return;+ for (int i = 0; i < self->endpoint_list_->count(); ++i) {+ auto* item = self->endpoint_list_->item(i);+ if (item && item->data(Qt::UserRole).toString() == ep) {+ self->endpoint_list_->setCurrentItem(item);+ self->active_endpoint_ = ep;+ self->status_endpoint_->setText(ep);+ break;+ }+ }+ });+ }+}+} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/akshare/AkShareScreen.h b/fincept-qt/src/screens/akshare/AkShareScreen.hindex d62d589d4..d6576c4b6 100644--- a/fincept-qt/src/screens/akshare/AkShareScreen.h+++ b/fincept-qt/src/screens/akshare/AkShareScreen.h@@ -1,4 +1,5 @@#pragma once+#include "screens/IStatefulScreen.h"#include <QComboBox>#include <QHeaderView>@@ -30,11 +31,17 @@ struct AkShareSource {/// Provides access to 26+ AkShare data sources with 1000+ endpoints./// Users select a source, pick an endpoint, optionally set parameters,/// and view results in a table or raw JSON.-class AkShareScreen : public QWidget {+class AkShareScreen : public QWidget, public IStatefulScreen {Q_OBJECTpublic:explicit AkShareScreen(QWidget* parent = nullptr);+ // IStatefulScreen — remembers active source, last endpoint, search text,+ // and whether the user prefers table vs JSON view.+ QVariantMap save_state() const override;+ void restore_state(const QVariantMap& state) override;+ QString state_key() const override { return "akshare"; }+private slots:void on_source_clicked(int index);void on_endpoint_clicked(QListWidgetItem* item);diff --git a/fincept-qt/src/screens/alt_investments/AltInvestmentsScreen.cpp b/fincept-qt/src/screens/alt_investments/AltInvestmentsScreen.cppindex f224d782f..cd357d0bb 100644--- a/fincept-qt/src/screens/alt_investments/AltInvestmentsScreen.cpp+++ b/fincept-qt/src/screens/alt_investments/AltInvestmentsScreen.cpp@@ -1,6 +1,7 @@#include "screens/alt_investments/AltInvestmentsScreen.h"#include "core/logging/Logger.h"+#include "core/session/ScreenStateManager.h"#include "python/PythonRunner.h"#include "storage/cache/CacheManager.h"#include "ui/theme/Theme.h"@@ -841,6 +842,8 @@ void AltInvestmentsScreen::on_analyzer_changed(int index) {status_analyzer_->setText(ana.name.toUpper());analyzer_combo_->setCurrentIndex(index);rebuild_form(active_category_, index);++ fincept::ScreenStateManager::instance().notify_changed(this);}void AltInvestmentsScreen::on_analyze() {@@ -1175,4 +1178,23 @@ void AltInvestmentsScreen::set_loading(bool loading) {analyze_btn_->setText(loading ? "ANALYZING..." : "ANALYZE");}+// ── IStatefulScreen ──────────────────────────────────────────────────────────++QVariantMap AltInvestmentsScreen::save_state() const {+ return {+ {"category", active_category_},+ {"analyzer", active_analyzer_},+ };+}++void AltInvestmentsScreen::restore_state(const QVariantMap& state) {+ const int cat = state.value("category", -1).toInt();+ const int ana = state.value("analyzer", -1).toInt();+ if (cat < 0 || cat >= categories_.size())+ return;+ on_category_changed(cat);+ if (ana >= 0 && ana < categories_[cat].analyzers.size())+ on_analyzer_changed(ana);+}+} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/alt_investments/AltInvestmentsScreen.h b/fincept-qt/src/screens/alt_investments/AltInvestmentsScreen.hindex 88b447706..0f6a0950a 100644--- a/fincept-qt/src/screens/alt_investments/AltInvestmentsScreen.h+++ b/fincept-qt/src/screens/alt_investments/AltInvestmentsScreen.h@@ -1,4 +1,5 @@#pragma once+#include "screens/IStatefulScreen.h"#include <QComboBox>#include <QDoubleSpinBox>@@ -42,11 +43,16 @@ struct AltField {bool divide_100 = false; // divide UI value by 100 before sending (for % fields)};-class AltInvestmentsScreen : public QWidget {+class AltInvestmentsScreen : public QWidget, public IStatefulScreen {Q_OBJECTpublic:explicit AltInvestmentsScreen(QWidget* parent = nullptr);+ // IStatefulScreen — remembers which category + analyzer the user had open.+ QVariantMap save_state() const override;+ void restore_state(const QVariantMap& state) override;+ QString state_key() const override { return "alt_investments"; }+protected:void showEvent(QShowEvent* e) override;void hideEvent(QHideEvent* e) override;diff --git a/fincept-qt/src/screens/chat_mode/ChatMessagePanel.cpp b/fincept-qt/src/screens/chat_mode/ChatMessagePanel.cppindex ea037ad0e..898d7825f 100644--- a/fincept-qt/src/screens/chat_mode/ChatMessagePanel.cpp+++ b/fincept-qt/src/screens/chat_mode/ChatMessagePanel.cpp@@ -11,6 +11,7 @@#include <QPalette>#include <QScrollBar>#include <QSizePolicy>+#include <QTextCursor>#include <algorithm>@@ -151,6 +152,12 @@ QWidget* ChatMessagePanel::build_messages_area() {messages_layout_->addStretch(1);scroll_area_->setWidget(messages_container_);++ // Scroll persistence signal — emitted when the user scrolls within the+ // message history; ChatModeScreen listens and debounces a save.+ if (auto* vbar = scroll_area_->verticalScrollBar())+ connect(vbar, &QScrollBar::valueChanged, this, [this](int) { emit scroll_changed(); });+return scroll_area_;}@@ -271,6 +278,7 @@ QWidget* ChatMessagePanel::build_input_area() {char_lbl_->setText(QString("%1 / 4000").arg(text.length()));if (text.isEmpty()) {input_box_->setFixedHeight(36);+ emit draft_changed();return;}auto* doc = input_box_->document();@@ -279,6 +287,7 @@ QWidget* ChatMessagePanel::build_input_area() {const int h = (need < 36) ? 36 : (need > 160) ? 160 : need;if (input_box_->height() != h)input_box_->setFixedHeight(h);+ emit draft_changed();});optimize_btn_ = new QPushButton("Optimize");@@ -721,4 +730,35 @@ void ChatMessagePanel::on_typing_tick() {++typing_step_;}+// ── Draft + scroll accessors (consumed by ChatModeScreen persistence) ───────++QString ChatMessagePanel::draft_text() const {+ return input_box_ ? input_box_->toPlainText() : QString();+}++void ChatMessagePanel::set_draft_text(const QString& text) {+ if (!input_box_ || input_box_->toPlainText() == text)+ return;+ input_box_->setPlainText(text);+ // Move cursor to end so the user can continue typing where they left off.+ auto c = input_box_->textCursor();+ c.movePosition(QTextCursor::End);+ input_box_->setTextCursor(c);+}++int ChatMessagePanel::scroll_position() const {+ if (!scroll_area_)+ return 0;+ auto* bar = scroll_area_->verticalScrollBar();+ return bar ? bar->value() : 0;+}++void ChatMessagePanel::set_scroll_position(int pos) {+ if (!scroll_area_)+ return;+ auto* bar = scroll_area_->verticalScrollBar();+ if (bar)+ bar->setValue(pos);+}+} // namespace fincept::chat_modediff --git a/fincept-qt/src/screens/chat_mode/ChatMessagePanel.h b/fincept-qt/src/screens/chat_mode/ChatMessagePanel.hindex 9af1e3e53..4171fe475 100644--- a/fincept-qt/src/screens/chat_mode/ChatMessagePanel.h+++ b/fincept-qt/src/screens/chat_mode/ChatMessagePanel.h@@ -24,6 +24,16 @@ class ChatMessagePanel : public QWidget {void set_stream_mode(StreamMode mode);StreamMode current_mode() const { return current_mode_; }+ // Draft + scroll accessors used by ChatModeScreen for session persistence.+ QString draft_text() const;+ void set_draft_text(const QString& text);+ int scroll_position() const;+ void set_scroll_position(int pos);++ signals:+ void draft_changed();+ void scroll_changed();+signals:void send_requested(const QString& message, StreamMode mode);void mode_toggled(StreamMode mode);diff --git a/fincept-qt/src/screens/chat_mode/ChatModeScreen.cpp b/fincept-qt/src/screens/chat_mode/ChatModeScreen.cppindex 8e1d79416..bb6264065 100644--- a/fincept-qt/src/screens/chat_mode/ChatModeScreen.cpp+++ b/fincept-qt/src/screens/chat_mode/ChatModeScreen.cpp@@ -44,6 +44,12 @@ void ChatModeScreen::build_ui() {void ChatModeScreen::wire_signals() {auto& svc = ChatModeService::instance();+ // Draft + scroll persistence — debounced through ScreenStateManager.+ connect(message_panel_, &ChatMessagePanel::draft_changed, this,+ [this]() { fincept::ScreenStateManager::instance().notify_changed(this); });+ connect(message_panel_, &ChatMessagePanel::scroll_changed, this,+ [this]() { fincept::ScreenStateManager::instance().notify_changed(this); });+// Session panel -> screenconnect(session_panel_, &ChatSessionPanel::session_selected, this, &ChatModeScreen::on_session_selected);connect(session_panel_, &ChatSessionPanel::new_session_requested, this, &ChatModeScreen::on_new_session);@@ -258,13 +264,38 @@ void ChatModeScreen::ensure_active_session(std::function<void(const QString&)> t// ── IStatefulScreen ───────────────────────────────────────────────────────────QVariantMap ChatModeScreen::save_state() const {- return {{"session_uuid", active_session_uuid_}};+ QVariantMap s{{"session_uuid", active_session_uuid_}};+ if (message_panel_) {+ s.insert("draft", message_panel_->draft_text());+ s.insert("scroll", message_panel_->scroll_position());+ }+ return s;}void ChatModeScreen::restore_state(const QVariantMap& state) {const QString uuid = state.value("session_uuid").toString();if (!uuid.isEmpty() && uuid != active_session_uuid_)on_session_selected(uuid);++ if (!message_panel_)+ return;++ const QString draft = state.value("draft").toString();+ if (!draft.isEmpty())+ message_panel_->set_draft_text(draft);++ // Scroll position is only meaningful after messages have loaded; the+ // session fetch above is async, so defer with singleShot(0) which runs+ // after the current event-loop turn and after QVBoxLayout has done its+ // first layout pass on the newly loaded bubbles.+ const int scroll = state.value("scroll", -1).toInt();+ if (scroll >= 0) {+ QPointer<ChatModeScreen> self = this;+ QTimer::singleShot(150, this, [self, scroll]() {+ if (self && self->message_panel_)+ self->message_panel_->set_scroll_position(scroll);+ });+ }}} // namespace fincept::chat_modediff --git a/fincept-qt/src/screens/chat_mode/ChatModeScreen.h b/fincept-qt/src/screens/chat_mode/ChatModeScreen.hindex 9e4a23317..8768f4414 100644--- a/fincept-qt/src/screens/chat_mode/ChatModeScreen.h+++ b/fincept-qt/src/screens/chat_mode/ChatModeScreen.h@@ -23,7 +23,8 @@ class ChatModeScreen : public QWidget, public fincept::screens::IStatefulScreenvoid restore_state(const QVariantMap& state) override;QVariantMap save_state() const override;QString state_key() const override { return "chat_mode"; }- int state_version() const override { return 1; }+ // v2 adds: draft composer text, scroll position.+ int state_version() const override { return 2; }signals:void exit_requested();diff --git a/fincept-qt/src/screens/dashboard/DashboardScreen.cpp b/fincept-qt/src/screens/dashboard/DashboardScreen.cppindex 932b17ef8..9b482c6b4 100644--- a/fincept-qt/src/screens/dashboard/DashboardScreen.cpp+++ b/fincept-qt/src/screens/dashboard/DashboardScreen.cpp@@ -4,6 +4,7 @@#include "screens/dashboard/canvas/DashboardTemplates.h"#include "screens/dashboard/canvas/TemplatePicker.h"#include "screens/dashboard/canvas/WidgetRegistry.h"+#include "services/markets/MarketDataService.h"#include "services/notifications/NotificationService.h"#include "storage/repositories/SettingsRepository.h"#include "ui/theme/Theme.h"@@ -54,6 +55,8 @@ DashboardScreen::DashboardScreen(QWidget* parent) : QWidget(parent) {// ── Scrolling Ticker Bar ──ticker_bar_ = new TickerBar;vl->addWidget(ticker_bar_);+ // When user saves a new symbol list, re-fetch quotes immediately.+ connect(ticker_bar_, &TickerBar::symbols_changed, this, &DashboardScreen::refresh_ticker);// ── Main Content: Canvas (in scroll) + Market Pulse ──content_split_ = new QSplitter(Qt::Horizontal);@@ -107,6 +110,11 @@ DashboardScreen::DashboardScreen(QWidget* parent) : QWidget(parent) {save_timer_->setInterval(800);connect(save_timer_, &QTimer::timeout, this, &DashboardScreen::save_layout);+ // ── Ticker refresh timer: 5-minute interval, started in showEvent (P3) ──+ ticker_refresh_timer_ = new QTimer(this);+ ticker_refresh_timer_->setInterval(5 * 60 * 1000);+ connect(ticker_refresh_timer_, &QTimer::timeout, this, &DashboardScreen::refresh_ticker);+// ── Canvas signals → toolbar/statusbar ──connect(canvas_, &DashboardCanvas::widget_count_changed, toolbar_, &DashboardToolBar::set_widget_count);connect(canvas_, &DashboardCanvas::widget_count_changed, status_bar_, &DashboardStatusBar::set_widget_count);@@ -184,6 +192,11 @@ void DashboardScreen::showEvent(QShowEvent* event) {if (ticker_bar_)ticker_bar_->resume();+ // Fetch live data for the ticker on first show, then every 5 minutes.+ refresh_ticker();+ if (ticker_refresh_timer_)+ ticker_refresh_timer_->start();+// Set splitter sizes on first show using actual pixel width.// Must be done here (not in constructor) because the widget has no size yet// during construction. MarketPulsePanel's large sizeHint otherwise causes it@@ -207,6 +220,31 @@ void DashboardScreen::hideEvent(QHideEvent* event) {QWidget::hideEvent(event);if (ticker_bar_)ticker_bar_->pause();+ if (ticker_refresh_timer_)+ ticker_refresh_timer_->stop();+}++// ── Ticker refresh ────────────────────────────────────────────────────────────++void DashboardScreen::refresh_ticker() {+ if (!ticker_bar_)+ return;++ const QStringList symbols = ticker_bar_->symbols();+ if (symbols.isEmpty())+ return;++ QPointer<DashboardScreen> self = this;+ services::MarketDataService::instance().fetch_quotes(symbols,+ [self](bool ok, QVector<services::QuoteData> quotes) {+ if (!self || !ok || quotes.isEmpty())+ return;+ QVector<TickerBar::Entry> entries;+ entries.reserve(quotes.size());+ for (const auto& q : quotes)+ entries.append({q.symbol, q.price, q.change});+ self->ticker_bar_->set_data(entries);+ });}// ── Event filter: sync canvas width to scroll viewport ────────────────────────diff --git a/fincept-qt/src/screens/dashboard/DashboardScreen.h b/fincept-qt/src/screens/dashboard/DashboardScreen.hindex ac31272a7..3be8cadc6 100644--- a/fincept-qt/src/screens/dashboard/DashboardScreen.h+++ b/fincept-qt/src/screens/dashboard/DashboardScreen.h@@ -34,6 +34,7 @@ class DashboardScreen : public QWidget {void build_default_layout();void save_layout();void restore_layout();+ void refresh_ticker();DashboardToolBar* toolbar_ = nullptr;TickerBar* ticker_bar_ = nullptr;@@ -44,6 +45,7 @@ class DashboardScreen : public QWidget {DashboardStatusBar* status_bar_ = nullptr;fincept::ui::NotifToast* notif_toast_ = nullptr;QTimer* save_timer_ = nullptr;+ QTimer* ticker_refresh_timer_ = nullptr;bool pulse_visible_ = true;bool layout_restored_ = false;bool split_sized_ = false;diff --git a/fincept-qt/src/screens/dashboard/TickerBar.cpp b/fincept-qt/src/screens/dashboard/TickerBar.cppindex 1ed934cb2..93c23ad38 100644--- a/fincept-qt/src/screens/dashboard/TickerBar.cpp+++ b/fincept-qt/src/screens/dashboard/TickerBar.cpp@@ -1,15 +1,34 @@#include "screens/dashboard/TickerBar.h"+#include "services/markets/MarketDataService.h"+#include "storage/repositories/SettingsRepository.h"#include "ui/theme/Theme.h"#include "ui/theme/ThemeManager.h"+#include <QContextMenuEvent>+#include <QHBoxLayout>+#include <QMenu>#include <QPaintEvent>#include <QPainter>+#include <QPointer>+#include <QResizeEvent>+#include <QtConcurrent>namespace fincept::screens {+static constexpr int kItemSpacing = 40;+static constexpr int kSegmentGap = 8;+static constexpr int kEditBarHeight = 24;+static const char* kSettingsKey = "ticker_bar_symbols";+static const char* kSettingsCategory = "dashboard";++// ─────────────────────────────────────────────────────────────────────────────+// Constructor+// ─────────────────────────────────────────────────────────────────────────────+TickerBar::TickerBar(QWidget* parent) : QWidget(parent) {- setFixedHeight(24);+ setFixedHeight(kEditBarHeight);+ setContextMenuPolicy(Qt::DefaultContextMenu);auto apply_bg = [this]() {setStyleSheet(QString("background-color: %1;").arg(ui::colors::BG_BASE()));@@ -21,28 +40,213 @@ TickerBar::TickerBar(QWidget* parent) : QWidget(parent) {update();});- // Dummy data until service provides real data- entries_ = {- {"AAPL", 189.84, 1.23}, {"MSFT", 378.91, -0.45}, {"GOOGL", 141.80, 0.67}, {"AMZN", 178.25, -1.12},- {"NVDA", 875.28, 2.34}, {"META", 485.39, 0.89}, {"TSLA", 175.21, -2.45}, {"JPM", 183.12, 0.56},- {"V", 275.45, -0.23}, {"BRK.B", 408.92, 1.05}, {"SPY", 511.34, 0.78}, {"QQQ", 435.67, 1.12},- };-connect(&scroll_timer_, &QTimer::timeout, this, [this]() {offset_ += 1.0;+ if (total_width_ > 0 && offset_ >= total_width_)+ offset_ = 0;update();});- scroll_timer_.setInterval(50); // 20fps — started by resume() / showEvent, not here (P3)+ scroll_timer_.setInterval(50); // 20fps — started by showEvent (P3)++ // ── Inline edit overlay (hidden by default) ───────────────────────────────+ edit_bar_ = new QWidget(this);+ edit_bar_->setFixedHeight(kEditBarHeight);+ edit_bar_->hide();++ auto* hl = new QHBoxLayout(edit_bar_);+ hl->setContentsMargins(6, 2, 6, 2);+ hl->setSpacing(4);++ auto* lbl = new QLabel("SYMBOLS:", edit_bar_);+ lbl->setStyleSheet(QString("color:%1; font-size:9px; font-weight:bold; background:transparent;")+ .arg(ui::colors::TEXT_TERTIARY()));+ hl->addWidget(lbl);++ edit_input_ = new QLineEdit(edit_bar_);+ edit_input_->setPlaceholderText("AAPL, MSFT, ^GSPC, BTC-USD ...");+ edit_input_->setStyleSheet(+ QString("QLineEdit { background:%1; color:%2; border:1px solid %3;"+ " font-size:10px; padding:1px 6px; font-family:Consolas; }"+ "QLineEdit:focus { border-color:%4; }")+ .arg(ui::colors::BG_BASE(), ui::colors::TEXT_PRIMARY(),+ ui::colors::BORDER_DIM(), ui::colors::AMBER()));+ connect(edit_input_, &QLineEdit::returnPressed, this, &TickerBar::commit_edit);+ hl->addWidget(edit_input_, 1);++ edit_ok_ = new QPushButton("OK", edit_bar_);+ edit_ok_->setFixedWidth(32);+ edit_ok_->setStyleSheet(+ QString("QPushButton { background:%1; color:%2; border:none;"+ " font-size:9px; font-weight:bold; padding:2px; }"+ "QPushButton:hover { background:%3; }")+ .arg(ui::colors::AMBER(), ui::colors::BG_BASE(), ui::colors::AMBER()));+ connect(edit_ok_, &QPushButton::clicked, this, &TickerBar::commit_edit);+ hl->addWidget(edit_ok_);++ edit_cancel_ = new QPushButton("✕", edit_bar_);+ edit_cancel_->setFixedWidth(24);+ edit_cancel_->setStyleSheet(+ QString("QPushButton { background:transparent; color:%1; border:none;"+ " font-size:11px; padding:2px; }"+ "QPushButton:hover { color:%2; }")+ .arg(ui::colors::TEXT_TERTIARY(), ui::colors::RED()));+ connect(edit_cancel_, &QPushButton::clicked, this, &TickerBar::hide_edit_bar);+ hl->addWidget(edit_cancel_);++ // Load persisted symbols (falls back to defaults if nothing saved yet).+ load_symbols();+}++// ─────────────────────────────────────────────────────────────────────────────+// Symbol persistence+// ─────────────────────────────────────────────────────────────────────────────++void TickerBar::load_symbols() {+ // Build default list: indices + movers+ const QStringList defaults = services::MarketDataService::indices_symbols()+ + services::MarketDataService::mover_symbols();++ // Attempt to load from settings on a background thread; fall back to defaults+ // immediately so the ticker isn't blank while the DB read is in flight.+ symbols_ = defaults;++ QPointer<TickerBar> self = this;+ QtConcurrent::run([self, defaults]() {+ auto result = fincept::SettingsRepository::instance().get(kSettingsKey);+ QStringList loaded;+ if (result.is_ok() && !result.value().isEmpty()) {+ for (const QString& s : result.value().split(',')) {+ const QString t = s.trimmed().toUpper();+ if (!t.isEmpty())+ loaded << t;+ }+ }+ QMetaObject::invokeMethod(self, [self, loaded, defaults]() {+ if (!self) return;+ self->symbols_ = loaded.isEmpty() ? defaults : loaded;+ emit self->symbols_changed(self->symbols_);+ }, Qt::QueuedConnection);+ });+}++void TickerBar::save_symbols() {+ const QString value = symbols_.join(",");+ QtConcurrent::run([value]() {+ fincept::SettingsRepository::instance().set(kSettingsKey, value, kSettingsCategory);+ });}+// ─────────────────────────────────────────────────────────────────────────────+// set_data — called by DashboardScreen after fetch_quotes returns+// ─────────────────────────────────────────────────────────────────────────────+void TickerBar::set_data(const QVector<Entry>& entries) {entries_ = entries;- offset_ = 0;+ offset_ = 0;++ // Cache total width — paintEvent runs every 50ms, no per-frame allocation.+ QFont font(ui::fonts::DATA_FAMILY(), ui::fonts::font_px(-2));+ QFontMetrics fm(font);+ total_width_ = 0;+ for (const auto& e : entries_) {+ const int symbol_w = fm.horizontalAdvance(e.symbol);+ const int price_w = fm.horizontalAdvance(QString::number(e.price, 'f', 2));+ const QString change_str =+ QString("%1%2%").arg(e.change >= 0 ? "+" : "").arg(e.change, 0, 'f', 2);+ const int change_w = fm.horizontalAdvance(change_str);+ total_width_ += symbol_w + kSegmentGap + price_w + kSegmentGap + change_w + kItemSpacing;+ }++ if (total_width_ > 0 && isVisible() && !edit_bar_->isVisible())+ scroll_timer_.start();+update();}+// ─────────────────────────────────────────────────────────────────────────────+// Show / Hide+// ─────────────────────────────────────────────────────────────────────────────++void TickerBar::showEvent(QShowEvent* event) {+ QWidget::showEvent(event);+ if (total_width_ > 0)+ scroll_timer_.start();+}++void TickerBar::hideEvent(QHideEvent* event) {+ QWidget::hideEvent(event);+ scroll_timer_.stop();+ hide_edit_bar();+}++void TickerBar::resizeEvent(QResizeEvent* event) {+ QWidget::resizeEvent(event);+ if (edit_bar_)+ edit_bar_->setGeometry(0, 0, width(), kEditBarHeight);+}++// ─────────────────────────────────────────────────────────────────────────────+// Context menu — right-click to edit symbols+// ─────────────────────────────────────────────────────────────────────────────++void TickerBar::contextMenuEvent(QContextMenuEvent* event) {+ QMenu menu(this);+ menu.setStyleSheet(+ QString("QMenu { background:%1; color:%2; border:1px solid %3; font-size:11px; }"+ "QMenu::item:selected { background:%4; color:%5; }")+ .arg(ui::colors::BG_RAISED(), ui::colors::TEXT_PRIMARY(),+ ui::colors::BORDER_DIM(), ui::colors::AMBER(), ui::colors::BG_BASE()));++ auto* edit_action = menu.addAction("Edit Symbols...");+ connect(edit_action, &QAction::triggered, this, &TickerBar::show_edit_bar);++ menu.exec(event->globalPos());+}++// ─────────────────────────────────────────────────────────────────────────────+// Inline edit bar+// ─────────────────────────────────────────────────────────────────────────────++void TickerBar::show_edit_bar() {+ scroll_timer_.stop();+ edit_input_->setText(symbols_.join(", "));+ edit_bar_->setGeometry(0, 0, width(), kEditBarHeight);+ edit_bar_->raise();+ edit_bar_->show();+ edit_input_->setFocus();+ edit_input_->selectAll();+}++void TickerBar::hide_edit_bar() {+ edit_bar_->hide();+ if (total_width_ > 0 && isVisible())+ scroll_timer_.start();+}++void TickerBar::commit_edit() {+ QStringList updated;+ for (const QString& s : edit_input_->text().split(',')) {+ const QString t = s.trimmed().toUpper();+ if (!t.isEmpty())+ updated << t;+ }++ hide_edit_bar();++ if (updated.isEmpty() || updated == symbols_)+ return;++ symbols_ = updated;+ save_symbols();+ emit symbols_changed(symbols_);+}++// ─────────────────────────────────────────────────────────────────────────────+// Paint+// ─────────────────────────────────────────────────────────────────────────────+void TickerBar::paintEvent(QPaintEvent*) {- if (entries_.isEmpty())+ if (entries_.isEmpty() || total_width_ <= 0)return;QPainter p(this);@@ -52,43 +256,29 @@ void TickerBar::paintEvent(QPaintEvent*) {p.setFont(font);QFontMetrics fm(font);- // Calculate total width of one cycle- int item_spacing = 40;- int total_width = 0;- for (const auto& e : entries_) {- QString text = QString("%1 %2 %3%4%")- .arg(e.symbol)- .arg(e.price, 0, 'f', 2)- .arg(e.change >= 0 ? "+" : "")- .arg(e.change, 0, 'f', 2);- total_width += fm.horizontalAdvance(text) + item_spacing;- }-- if (total_width > 0 && offset_ >= total_width) {- offset_ = 0;- }-- double x = -offset_;- int passes = (width() / total_width) + 2;+ const int text_y = (height() + fm.ascent() - fm.descent()) / 2;+ double x = -offset_;+ const int passes = (width() / total_width_) + 2;for (int pass = 0; pass < passes; ++pass) {for (const auto& e : entries_) {- // Symbol in white+ // Symbol — primary textp.setPen(QColor(ui::colors::WHITE()));- p.drawText(QPointF(x, 17), e.symbol);- x += fm.horizontalAdvance(e.symbol) + 8;+ p.drawText(QPointF(x, text_y), e.symbol);+ x += fm.horizontalAdvance(e.symbol) + kSegmentGap;- // Price in grey- QString price_str = QString::number(e.price, 'f', 2);+ // Price — muted+ const QString price_str = QString::number(e.price, 'f', 2);p.setPen(QColor(ui::colors::GRAY()));- p.drawText(QPointF(x, 17), price_str);- x += fm.horizontalAdvance(price_str) + 8;+ p.drawText(QPointF(x, text_y), price_str);+ x += fm.horizontalAdvance(price_str) + kSegmentGap;- // Change in green/red- QString change_str = QString("%1%2%").arg(e.change >= 0 ? "+" : "").arg(e.change, 0, 'f', 2);+ // Change — green / red+ const QString change_str =+ QString("%1%2%").arg(e.change >= 0 ? "+" : "").arg(e.change, 0, 'f', 2);p.setPen(QColor(ui::change_color(e.change)));- p.drawText(QPointF(x, 17), change_str);- x += fm.horizontalAdvance(change_str) + item_spacing;+ p.drawText(QPointF(x, text_y), change_str);+ x += fm.horizontalAdvance(change_str) + kItemSpacing;}}}diff --git a/fincept-qt/src/screens/dashboard/TickerBar.h b/fincept-qt/src/screens/dashboard/TickerBar.hindex 7101bf58c..d4801ff7d 100644--- a/fincept-qt/src/screens/dashboard/TickerBar.h+++ b/fincept-qt/src/screens/dashboard/TickerBar.h@@ -1,11 +1,17 @@#pragma once+#include <QHideEvent>+#include <QLineEdit>+#include <QPushButton>+#include <QShowEvent>#include <QTimer>#include <QVector>#include <QWidget>namespace fincept::screens {-/// Scrolling ticker bar with market data.+/// Scrolling ticker bar with live market data.+/// Right-click → "Edit Symbols" to customise the symbol list.+/// Symbol list is persisted via SettingsRepository under "ticker_bar_symbols".class TickerBar : public QWidget {Q_OBJECTpublic:@@ -13,21 +19,49 @@ class TickerBar : public QWidget {struct Entry {QString symbol;- double price;- double change;+ double price = 0;+ double change = 0;};void set_data(const QVector<Entry>& entries);- void pause() { scroll_timer_.stop(); }- void resume() { scroll_timer_.start(); }+ void pause() { scroll_timer_.stop(); }+ void resume() { if (total_width_ > 0) scroll_timer_.start(); }++ /// Returns the current symbol list (persisted user preference).+ QStringList symbols() const { return symbols_; }++ signals:+ /// Emitted when the user saves a new symbol list — caller should re-fetch.+ void symbols_changed(const QStringList& symbols);protected:void paintEvent(QPaintEvent* event) override;+ void showEvent(QShowEvent* event) override;+ void hideEvent(QHideEvent* event) override;+ void contextMenuEvent(QContextMenuEvent* event) override;+ void resizeEvent(QResizeEvent* event) override;private:+ void load_symbols();+ void save_symbols();+ void show_edit_bar();+ void hide_edit_bar();+ void commit_edit();++ // ── Scrolling ──QVector<Entry> entries_;- QTimer scroll_timer_;- double offset_ = 0;+ QTimer scroll_timer_;+ double offset_ = 0;+ int total_width_ = 0;++ // ── Symbol list ──+ QStringList symbols_;++ // ── Inline edit overlay ──+ QWidget* edit_bar_ = nullptr;+ QLineEdit* edit_input_ = nullptr;+ QPushButton* edit_ok_ = nullptr;+ QPushButton* edit_cancel_ = nullptr;};} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/dashboard/widgets/BaseWidget.cpp b/fincept-qt/src/screens/dashboard/widgets/BaseWidget.cppindex a5110c7db..779b3a6ff 100644--- a/fincept-qt/src/screens/dashboard/widgets/BaseWidget.cpp+++ b/fincept-qt/src/screens/dashboard/widgets/BaseWidget.cpp@@ -149,7 +149,8 @@ void BaseWidget::set_error(const QString& error) {// Clear content and show errorQLayoutItem* item;while ((item = content_layout_->takeAt(0)) != nullptr) {- delete item->widget();+ if (item->widget())+ item->widget()->deleteLater();delete item;}diff --git a/fincept-qt/src/screens/dashboard/widgets/NewsWidget.cpp b/fincept-qt/src/screens/dashboard/widgets/NewsWidget.cppindex 75039d891..ec6b689df 100644--- a/fincept-qt/src/screens/dashboard/widgets/NewsWidget.cpp+++ b/fincept-qt/src/screens/dashboard/widgets/NewsWidget.cpp@@ -65,7 +65,8 @@ void NewsWidget::populate(const QJsonArray& articles) {// Clear old items (keep the stretch)while (news_layout_->count() > 1) {auto* item = news_layout_->takeAt(0);- delete item->widget();+ if (item->widget())+ item->widget()->deleteLater();delete item;}diff --git a/fincept-qt/src/screens/dashboard/widgets/SectorHeatmapWidget.cpp b/fincept-qt/src/screens/dashboard/widgets/SectorHeatmapWidget.cppindex 4f15d6252..0657ee190 100644--- a/fincept-qt/src/screens/dashboard/widgets/SectorHeatmapWidget.cpp+++ b/fincept-qt/src/screens/dashboard/widgets/SectorHeatmapWidget.cpp@@ -68,7 +68,8 @@ void SectorHeatmapWidget::populate(const QVector<services::QuoteData>& quotes) {// Clear gridQLayoutItem* item;while ((item = grid_->takeAt(0)) != nullptr) {- delete item->widget();+ if (item->widget())+ item->widget()->deleteLater();delete item;}diff --git a/fincept-qt/src/screens/derivatives/DerivativesScreen.cpp b/fincept-qt/src/screens/derivatives/DerivativesScreen.cppindex ee20c5d5a..d80693f76 100644--- a/fincept-qt/src/screens/derivatives/DerivativesScreen.cpp+++ b/fincept-qt/src/screens/derivatives/DerivativesScreen.cpp@@ -1,6 +1,7 @@#include "screens/derivatives/DerivativesScreen.h"#include "core/logging/Logger.h"+#include "core/session/ScreenStateManager.h"#include "python/PythonRunner.h"#include "storage/cache/CacheManager.h"#include "ui/theme/StyleSheets.h"@@ -719,6 +720,8 @@ void DerivativesScreen::on_instrument_changed(int index) {const QStringList names = {"BONDS", "EQUITY OPTIONS", "FX OPTIONS", "IR SWAPS", "CREDIT"};status_instrument_->setText("INSTRUMENT: " + names[index]);LOG_INFO("Derivatives", "Switched to: " + names[index]);++ fincept::ScreenStateManager::instance().notify_changed(this);}void DerivativesScreen::on_calculate() {@@ -1117,4 +1120,17 @@ void DerivativesScreen::display_results(const QJsonObject& result) {LOG_INFO("Derivatives", "Results displayed");}+// ── IStatefulScreen ──────────────────────────────────────────────────────────++QVariantMap DerivativesScreen::save_state() const {+ return {{"instrument", active_instrument_}};+}++void DerivativesScreen::restore_state(const QVariantMap& state) {+ const int idx = state.value("instrument", -1).toInt();+ if (idx < 0 || idx >= instrument_btns_.size())+ return;+ on_instrument_changed(idx);+}+} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/derivatives/DerivativesScreen.h b/fincept-qt/src/screens/derivatives/DerivativesScreen.hindex 021d9e3ea..418b44f3f 100644--- a/fincept-qt/src/screens/derivatives/DerivativesScreen.h+++ b/fincept-qt/src/screens/derivatives/DerivativesScreen.h@@ -1,4 +1,5 @@#pragma once+#include "screens/IStatefulScreen.h"#include <QComboBox>#include <QDateEdit>@@ -15,11 +16,17 @@ namespace fincept::screens {/// Professional derivatives pricing screen./// Supports: Bonds, Equity Options, FX Options, IR Swaps, Credit (CDS)./// Calculations run via PythonRunner (derivatives_pricing.py).-class DerivativesScreen : public QWidget {+class DerivativesScreen : public QWidget, public IStatefulScreen {Q_OBJECTpublic:explicit DerivativesScreen(QWidget* parent = nullptr);+ // IStatefulScreen — persists which instrument the user last had open+ // (bonds/equity/fx/swaps/credit).+ QVariantMap save_state() const override;+ void restore_state(const QVariantMap& state) override;+ QString state_key() const override { return "derivatives"; }+private slots:void on_instrument_changed(int index);void on_calculate();diff --git a/fincept-qt/src/screens/maritime/MaritimeScreen.cpp b/fincept-qt/src/screens/maritime/MaritimeScreen.cppindex 854e997ce..5869f5639 100644--- a/fincept-qt/src/screens/maritime/MaritimeScreen.cpp+++ b/fincept-qt/src/screens/maritime/MaritimeScreen.cpp@@ -2,6 +2,7 @@#include "screens/maritime/MaritimeScreen.h"#include "core/logging/Logger.h"+#include "core/session/ScreenStateManager.h"#include "services/maritime/MaritimeService.h"#include "ui/theme/Theme.h"#include "ui/theme/ThemeManager.h"@@ -436,6 +437,8 @@ QWidget* MaritimeScreen::build_right_panel() {imo_edit_->setPlaceholderText("e.g. 9344745");imo_edit_->setStyleSheet(input_ss());connect(imo_edit_, &QLineEdit::returnPressed, this, &MaritimeScreen::on_search_vessel);+ connect(imo_edit_, &QLineEdit::textChanged, this,+ [this](const QString&) { fincept::ScreenStateManager::instance().notify_changed(this); });vl->addWidget(imo_edit_);auto* track_btn = new QPushButton("TRACK", content);@@ -844,4 +847,34 @@ void MaritimeScreen::on_vessel_history(QVector<VesselData> history) {LOG_INFO("Maritime", QString("Vessel history: %1 — %2 positions").arg(vessel_name).arg(total));}+// ── IStatefulScreen ──────────────────────────────────────────────────────────++QVariantMap MaritimeScreen::save_state() const {+ QVariantMap s;+ if (imo_edit_)+ s.insert("imo", imo_edit_->text());+ if (area_min_lat_)+ s.insert("min_lat", area_min_lat_->value());+ if (area_max_lat_)+ s.insert("max_lat", area_max_lat_->value());+ if (area_min_lng_)+ s.insert("min_lng", area_min_lng_->value());+ if (area_max_lng_)+ s.insert("max_lng", area_max_lng_->value());+ return s;+}++void MaritimeScreen::restore_state(const QVariantMap& state) {+ if (imo_edit_)+ imo_edit_->setText(state.value("imo").toString());+ if (area_min_lat_ && state.contains("min_lat"))+ area_min_lat_->setValue(state.value("min_lat").toDouble());+ if (area_max_lat_ && state.contains("max_lat"))+ area_max_lat_->setValue(state.value("max_lat").toDouble());+ if (area_min_lng_ && state.contains("min_lng"))+ area_min_lng_->setValue(state.value("min_lng").toDouble());+ if (area_max_lng_ && state.contains("max_lng"))+ area_max_lng_->setValue(state.value("max_lng").toDouble());+}+} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/maritime/MaritimeScreen.h b/fincept-qt/src/screens/maritime/MaritimeScreen.hindex 575ed8ae5..f6781a10b 100644--- a/fincept-qt/src/screens/maritime/MaritimeScreen.h+++ b/fincept-qt/src/screens/maritime/MaritimeScreen.h@@ -1,5 +1,6 @@// src/screens/maritime/MaritimeScreen.h#pragma once+#include "screens/IStatefulScreen.h"#include "services/maritime/MaritimeTypes.h"#include "ui/theme/Theme.h"@@ -22,11 +23,17 @@ namespace fincept::screens {/// Maritime Intelligence screen — vessel tracking, trade routes, search./// Layout: Left stats panel | Center content (tabs) | Right detail panel-class MaritimeScreen : public QWidget {+class MaritimeScreen : public QWidget, public IStatefulScreen {Q_OBJECTpublic:explicit MaritimeScreen(QWidget* parent = nullptr);+ // IStatefulScreen — persists the IMO search text and the area-search+ // bounds (common user inputs for vessel lookup).+ QVariantMap save_state() const override;+ void restore_state(const QVariantMap& state) override;+ QString state_key() const override { return "maritime"; }+protected:void showEvent(QShowEvent* event) override;void hideEvent(QHideEvent* event) override;diff --git a/fincept-qt/src/screens/settings/PythonEnvSection.cpp b/fincept-qt/src/screens/settings/PythonEnvSection.cppnew file mode 100644index 000000000..78e6dcd3d--- /dev/null+++ b/fincept-qt/src/screens/settings/PythonEnvSection.cpp@@ -0,0 +1,809 @@+// PythonEnvSection.cpp — Python venv package manager panel.+#include "screens/settings/PythonEnvSection.h"++#include "core/logging/Logger.h"+#include "python/PythonSetupManager.h"+#include "ui/theme/Theme.h"++#include <QCheckBox>+#include <QCoreApplication>+#include <QDir>+#include <QFile>+#include <QFileInfo>+#include <QFrame>+#include <QHBoxLayout>+#include <QHeaderView>+#include <QLabel>+#include <QProcessEnvironment>+#include <QRegularExpression>+#include <QScrollArea>+#include <QShowEvent>+#include <QVBoxLayout>++namespace fincept::screens {++// ── Style helpers (live — read active theme tokens) ───────────────────────────++static QString section_title_ss() {+ return QString("color:%1;font-weight:bold;letter-spacing:0.5px;background:transparent;")+ .arg(ui::colors::AMBER());+}+static QString label_ss() {+ return QString("color:%1;background:transparent;").arg(ui::colors::TEXT_SECONDARY());+}+static QString input_ss() {+ return QString("QLineEdit{background:%1;color:%2;border:1px solid %3;padding:5px 8px;}"+ "QLineEdit:focus{border:1px solid %4;}")+ .arg(ui::colors::BG_RAISED(), ui::colors::TEXT_PRIMARY(), ui::colors::BORDER_MED(), ui::colors::AMBER());+}+static QString combo_ss() {+ return QString(+ "QComboBox{background:%1;color:%2;border:1px solid %3;padding:5px 8px;min-width:120px;}"+ "QComboBox:focus{border:1px solid %4;}"+ "QComboBox::drop-down{border:none;width:20px;}"+ "QComboBox QAbstractItemView{background:%1;color:%2;"+ "selection-background-color:%5;border:1px solid %3;}")+ .arg(ui::colors::BG_RAISED(), ui::colors::TEXT_PRIMARY(), ui::colors::BORDER_MED(),+ ui::colors::AMBER(), ui::colors::BG_HOVER());+}+static QString btn_primary_ss() {+ return QString("QPushButton{background:%1;color:%2;border:none;font-weight:700;"+ "padding:0 14px;height:30px;}"+ "QPushButton:hover{background:%3;}"+ "QPushButton:disabled{background:%4;color:%5;}")+ .arg(ui::colors::AMBER(), ui::colors::BG_BASE(), ui::colors::AMBER_DIM(),+ ui::colors::BG_RAISED(), ui::colors::TEXT_TERTIARY());+}+static QString btn_secondary_ss() {+ return QString("QPushButton{background:%1;color:%2;border:1px solid %3;"+ "padding:0 12px;height:30px;}"+ "QPushButton:hover{background:%4;}"+ "QPushButton:disabled{color:%5;border-color:%6;}")+ .arg(ui::colors::BG_RAISED(), ui::colors::TEXT_PRIMARY(), ui::colors::BORDER_BRIGHT(),+ ui::colors::BG_HOVER(), ui::colors::TEXT_TERTIARY(), ui::colors::BORDER_DIM());+}+static QString table_ss() {+ return QString(+ "QTableWidget{background:%1;color:%2;border:1px solid %3;"+ "gridline-color:%3;outline:none;}"+ "QTableWidget::item{padding:4px 6px;border:none;}"+ "QTableWidget::item:selected{background:%4;color:%2;}"+ "QHeaderView::section{background:%5;color:%6;border:none;"+ "border-bottom:1px solid %3;padding:4px 6px;font-weight:600;}"+ "QScrollBar:vertical{width:6px;background:transparent;}"+ "QScrollBar::handle:vertical{background:%3;border-radius:3px;}"+ "QScrollBar::add-line:vertical,QScrollBar::sub-line:vertical{height:0;}"+ "QScrollBar:horizontal{height:6px;background:transparent;}"+ "QScrollBar::handle:horizontal{background:%3;border-radius:3px;}"+ "QScrollBar::add-line:horizontal,QScrollBar::sub-line:horizontal{width:0;}")+ .arg(ui::colors::BG_BASE(), ui::colors::TEXT_PRIMARY(), ui::colors::BORDER_DIM(),+ ui::colors::BG_HOVER(), ui::colors::BG_RAISED(), ui::colors::TEXT_SECONDARY());+}+static QString progress_ss() {+ return QString("QProgressBar{background:%1;border:1px solid %2;border-radius:3px;}"+ "QProgressBar::chunk{background:%3;border-radius:3px;}")+ .arg(ui::colors::BG_RAISED(), ui::colors::BORDER_DIM(), ui::colors::AMBER());+}++// ── Canonical name normalisation (mirrors PythonSetupManager logic) ───────────++QString PythonEnvSection::canonicalise(const QString& name) {+ QString n = name.toLower();+ n.replace('-', '_');+ n.replace('.', '_');+ return n;+}++// ── Constructor ───────────────────────────────────────────────────────────────++PythonEnvSection::PythonEnvSection(QWidget* parent) : QWidget(parent) {+ list_proc_ = new QProcess(this);+ action_proc_ = new QProcess(this);++#ifdef _WIN32+ auto hide_window = [](QProcess::CreateProcessArguments* cpa) {+ cpa->flags |= 0x08000000; // CREATE_NO_WINDOW+ };+ list_proc_->setCreateProcessArgumentsModifier(hide_window);+ action_proc_->setCreateProcessArgumentsModifier(hide_window);+#endif++ build_ui();+}++// ── build_ui ──────────────────────────────────────────────────────────────────++void PythonEnvSection::build_ui() {+ auto* root = new QVBoxLayout(this);+ root->setContentsMargins(24, 24, 24, 16);+ root->setSpacing(0);++ // Title+ auto* title = new QLabel("PYTHON ENVIRONMENTS");+ title->setStyleSheet(section_title_ss());+ root->addWidget(title);+ root->addSpacing(4);++ auto* info = new QLabel(+ "Inspect and manage packages installed in both Python environments. "+ "Trading (venv-numpy1) contains NumPy 1.x-dependent libraries. "+ "Analytics (venv-numpy2) contains NumPy 2.x / ML / AI libraries.");+ info->setWordWrap(true);+ info->setStyleSheet(label_ss());+ root->addWidget(info);+ root->addSpacing(10);++ // ── Warning banner ────────────────────────────────────────────────────────+ auto* warn_frame = new QFrame(this);+ warn_frame->setFrameShape(QFrame::NoFrame);+ warn_frame->setStyleSheet(+ QString("QFrame{background:%1;border:1px solid %2;padding:2px;}")+ .arg(ui::colors::BG_RAISED(), ui::colors::AMBER()));+ auto* warn_layout = new QHBoxLayout(warn_frame);+ warn_layout->setContentsMargins(10, 7, 10, 7);+ warn_layout->setSpacing(8);++ auto* warn_icon = new QLabel("⚠", this);+ warn_icon->setStyleSheet(+ QString("color:%1;font-size:14px;background:transparent;font-weight:bold;")+ .arg(ui::colors::AMBER()));+ warn_layout->addWidget(warn_icon);++ auto* warn_text = new QLabel(+ "<b>Upgrading packages may break the terminal.</b> "+ "Only proceed if you know what you are doing. "+ "Incompatible version changes can cause analytics scripts to crash or produce incorrect results.",+ this);+ warn_text->setWordWrap(true);+ warn_text->setStyleSheet(+ QString("color:%1;background:transparent;font-size:11px;")+ .arg(ui::colors::AMBER()));+ warn_layout->addWidget(warn_text, 1);++ root->addWidget(warn_frame);+ root->addSpacing(14);++ // ── Toolbar row ───────────────────────────────────────────────────────────+ auto* toolbar = new QWidget(this);+ auto* thl = new QHBoxLayout(toolbar);+ thl->setContentsMargins(0, 0, 0, 0);+ thl->setSpacing(8);++ search_input_ = new QLineEdit(this);+ search_input_->setPlaceholderText("Filter packages...");+ search_input_->setFixedWidth(200);+ search_input_->setStyleSheet(input_ss());+ thl->addWidget(search_input_);++ venv_filter_ = new QComboBox(this);+ venv_filter_->addItems({"All", "Trading", "Analytics"});+ venv_filter_->setStyleSheet(combo_ss());+ thl->addWidget(venv_filter_);++ thl->addStretch();++ refresh_btn_ = new QPushButton("Refresh", this);+ refresh_btn_->setStyleSheet(btn_secondary_ss());+ refresh_btn_->setCursor(Qt::PointingHandCursor);+ thl->addWidget(refresh_btn_);++ install_missing_btn_ = new QPushButton("Install Missing", this);+ install_missing_btn_->setStyleSheet(btn_secondary_ss());+ install_missing_btn_->setCursor(Qt::PointingHandCursor);+ thl->addWidget(install_missing_btn_);++ upgrade_all_btn_ = new QPushButton("Upgrade All", this);+ upgrade_all_btn_->setStyleSheet(btn_secondary_ss());+ upgrade_all_btn_->setCursor(Qt::PointingHandCursor);+ thl->addWidget(upgrade_all_btn_);++ root->addWidget(toolbar);+ root->addSpacing(10);++ // ── Package table ─────────────────────────────────────────────────────────+ pkg_table_ = new QTableWidget(0, 7, this);+ pkg_table_->setHorizontalHeaderLabels(+ {"", "Package", "Venv", "Required", "Installed", "Status", "Action"});+ pkg_table_->setStyleSheet(table_ss());+ pkg_table_->setSelectionMode(QAbstractItemView::NoSelection);+ pkg_table_->setEditTriggers(QAbstractItemView::NoEditTriggers);+ pkg_table_->setAlternatingRowColors(false);+ pkg_table_->verticalHeader()->setVisible(false);+ pkg_table_->horizontalHeader()->setStretchLastSection(false);+ pkg_table_->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Fixed);+ pkg_table_->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Stretch);+ pkg_table_->horizontalHeader()->setSectionResizeMode(2, QHeaderView::Fixed);+ pkg_table_->horizontalHeader()->setSectionResizeMode(3, QHeaderView::ResizeToContents);+ pkg_table_->horizontalHeader()->setSectionResizeMode(4, QHeaderView::ResizeToContents);+ pkg_table_->horizontalHeader()->setSectionResizeMode(5, QHeaderView::Fixed);+ pkg_table_->horizontalHeader()->setSectionResizeMode(6, QHeaderView::Fixed);+ pkg_table_->setColumnWidth(0, 30); // checkbox+ pkg_table_->setColumnWidth(2, 90); // venv+ pkg_table_->setColumnWidth(5, 76); // status+ pkg_table_->setColumnWidth(6, 80); // action button+ pkg_table_->setShowGrid(true);+ root->addWidget(pkg_table_, 1);+ root->addSpacing(8);++ // ── Bottom bar: batch button + status ─────────────────────────────────────+ auto* bottom = new QWidget(this);+ auto* bhl = new QHBoxLayout(bottom);+ bhl->setContentsMargins(0, 0, 0, 0);+ bhl->setSpacing(10);++ batch_action_btn_ = new QPushButton("Install / Upgrade Selected", this);+ batch_action_btn_->setStyleSheet(btn_primary_ss());+ batch_action_btn_->setCursor(Qt::PointingHandCursor);+ bhl->addWidget(batch_action_btn_);+ bhl->addStretch();++ status_lbl_ = new QLabel(this);+ status_lbl_->setStyleSheet(label_ss());+ bhl->addWidget(status_lbl_);++ root->addWidget(bottom);+ root->addSpacing(8);++ // ── Progress bar + log line ───────────────────────────────────────────────+ install_bar_ = new QProgressBar(this);+ install_bar_->setRange(0, 100);+ install_bar_->setValue(0);+ install_bar_->setTextVisible(false);+ install_bar_->setFixedHeight(6);+ install_bar_->setStyleSheet(progress_ss());+ install_bar_->setVisible(false);+ root->addWidget(install_bar_);++ install_log_ = new QLabel(this);+ install_log_->setStyleSheet(+ QString("color:%1;background:transparent;font-size:10px;")+ .arg(ui::colors::TEXT_TERTIARY()));+ install_log_->setVisible(false);+ root->addWidget(install_log_);++ // ── Signal connections ────────────────────────────────────────────────────+ connect(refresh_btn_, &QPushButton::clicked, this, &PythonEnvSection::load_packages);++ connect(search_input_, &QLineEdit::textChanged, this, &PythonEnvSection::apply_filter);+ connect(venv_filter_, qOverload<int>(&QComboBox::currentIndexChanged),+ this, &PythonEnvSection::apply_filter);++ connect(install_missing_btn_, &QPushButton::clicked, this, [this]() {+ ActionBatch b1, b2;+ b1.venv = "venv-numpy1";+ b1.upgrade = false;+ b2.venv = "venv-numpy2";+ b2.upgrade = false;+ for (const auto& row : std::as_const(all_packages_)) {+ if (row.missing) {+ if (row.venv == "venv-numpy1")+ b1.packages << row.required_spec;+ else+ b2.packages << row.required_spec;+ }+ }+ QList<ActionBatch> q;+ if (!b1.packages.isEmpty()) q << b1;+ if (!b2.packages.isEmpty()) q << b2;+ if (!q.isEmpty()) start_action(q);+ });++ connect(upgrade_all_btn_, &QPushButton::clicked, this, [this]() {+ ActionBatch b1, b2;+ b1.venv = "venv-numpy1";+ b1.upgrade = true;+ b2.venv = "venv-numpy2";+ b2.upgrade = true;+ for (const auto& row : std::as_const(all_packages_)) {+ if (!row.missing) {+ if (row.venv == "venv-numpy1")+ b1.packages << row.required_spec;+ else+ b2.packages << row.required_spec;+ }+ }+ QList<ActionBatch> q;+ if (!b1.packages.isEmpty()) q << b1;+ if (!b2.packages.isEmpty()) q << b2;+ if (!q.isEmpty()) start_action(q);+ });++ connect(batch_action_btn_, &QPushButton::clicked, this, [this]() {+ auto batches = build_batches_for_selected();+ if (!batches.isEmpty())+ start_action(batches);+ });+}++// ── showEvent ─────────────────────────────────────────────────────────────────++void PythonEnvSection::showEvent(QShowEvent* e) {+ QWidget::showEvent(e);+ if (all_packages_.isEmpty())+ load_packages();+}++void PythonEnvSection::reload() {+ load_packages();+}++// ── Requirements file resolution ──────────────────────────────────────────────+// Mirrors PythonSetupManager::find_requirements_file() — walks up from exe dir.++QString PythonEnvSection::find_req_file(const QString& filename) const {+ QString exe_dir = QCoreApplication::applicationDirPath();++ // Direct candidate beside the exe+ QStringList candidates = {+ exe_dir + "/resources/" + filename,+ exe_dir + "/../resources/" + filename,+ exe_dir + "/../../resources/" + filename,+ };++ // Walk up from exe dir+ QDir dir(exe_dir);+ while (dir.cdUp()) {+ QString c = dir.filePath("resources/" + filename);+ if (QFileInfo::exists(c))+ return QDir::cleanPath(c);+ if (dir.isRoot())+ break;+ }++ for (const auto& c : candidates) {+ if (QFileInfo::exists(c))+ return QDir::cleanPath(c);+ }++ LOG_WARN("PythonEnv", "Requirements file not found: " + filename);+ return {};+}++// ── parse_requirements ────────────────────────────────────────────────────────+// Reads one requirements file, appends PackageRow entries to all_packages_.+// Mirrors PythonSetupManager::read_packages_from_file() parsing rules.++void PythonEnvSection::parse_requirements(const QString& req_file,+ const QString& venv_name,+ const QString& venv_label) {+ QString path = find_req_file(req_file);+ if (path.isEmpty()) {+ LOG_ERROR("PythonEnv", "Cannot load requirements: " + req_file);+ return;+ }++ QFile f(path);+ if (!f.open(QIODevice::ReadOnly | QIODevice::Text)) {+ LOG_ERROR("PythonEnv", "Cannot open: " + path);+ return;+ }++ // Version specifier regex — strips ">=1.2,<3.0" and extras "[torch]" from name+ static const QRegularExpression kVerRe(R"([><=!~\s\[].*)");++ while (!f.atEnd()) {+ QString line = QString::fromUtf8(f.readLine()).trimmed();+ if (line.isEmpty() || line.startsWith('#') || line.startsWith('-'))+ continue;+ int comment = line.indexOf('#');+ if (comment > 0)+ line = line.left(comment).trimmed();+ if (line.isEmpty())+ continue;++ PackageRow row;+ row.required_spec = line;+ row.venv = venv_name;+ row.venv_label = venv_label;++ QString base = line;+ base.remove(kVerRe);+ row.display_name = base.trimmed();+ row.name = canonicalise(row.display_name);+ row.missing = true;++ if (!row.name.isEmpty())+ all_packages_ << row;+ }+}++// ── load_packages ─────────────────────────────────────────────────────────────++void PythonEnvSection::load_packages() {+ using python::PythonSetupManager;++ if (!QFileInfo::exists(PythonSetupManager::instance().uv_path())) {+ show_status("Python environment not set up — run Setup first", true);+ return;+ }++ all_packages_.clear();+ installed_v1_.clear();+ installed_v2_.clear();+ v1_loaded_ = false;+ v2_loaded_ = false;+ pkg_table_->setRowCount(0);+ show_status("Loading...");++ parse_requirements("requirements-numpy1.txt", "venv-numpy1", "Trading");+ parse_requirements("requirements-numpy2.txt", "venv-numpy2", "Analytics");++ LOG_INFO("PythonEnv",+ QString("Parsed %1 packages from requirements files").arg(all_packages_.size()));++ start_list_venv("venv-numpy1");+}++// ── start_list_venv ───────────────────────────────────────────────────────────++void PythonEnvSection::start_list_venv(const QString& venv_name) {+ using python::PythonSetupManager;+ auto& mgr = PythonSetupManager::instance();++ QString python = mgr.python_path(venv_name);+ if (!QFileInfo::exists(python)) {+ LOG_WARN("PythonEnv", "Venv python not found: " + python);+ on_list_finished(venv_name, -1);+ return;+ }++ list_stdout_buf_.clear();++ QProcessEnvironment env = QProcessEnvironment::systemEnvironment();+ env.insert("UV_PYTHON_INSTALL_DIR", mgr.install_dir() + "/python");+ list_proc_->setProcessEnvironment(env);++ list_proc_->disconnect();++ connect(list_proc_, &QProcess::readyReadStandardOutput, this, [this]() {+ list_stdout_buf_ += list_proc_->readAllStandardOutput();+ });++ connect(list_proc_, qOverload<int, QProcess::ExitStatus>(&QProcess::finished),+ this, [this, venv_name](int exit_code, QProcess::ExitStatus) {+ on_list_finished(venv_name, exit_code);+ });++ list_proc_->start(mgr.uv_path(), {"pip", "list", "--python", python});+ LOG_DEBUG("PythonEnv", "Started uv pip list for " + venv_name);+}++// ── on_list_finished ──────────────────────────────────────────────────────────++void PythonEnvSection::on_list_finished(const QString& venv_name, int exit_code) {+ QMap<QString, QString>& target = (venv_name == "venv-numpy1") ? installed_v1_ : installed_v2_;++ if (exit_code == 0) {+ const QString output = QString::fromUtf8(list_stdout_buf_);+ for (const QString& line : output.split('\n', Qt::SkipEmptyParts)) {+ QStringList parts = line.split(' ', Qt::SkipEmptyParts);+ if (parts.size() < 2)+ continue;+ QString pkg_name = canonicalise(parts.value(0));+ QString version = parts.value(1);+ if (!pkg_name.isEmpty() && !version.isEmpty())+ target.insert(pkg_name, version);+ }+ LOG_INFO("PythonEnv",+ QString("[%1] parsed %2 installed packages").arg(venv_name).arg(target.size()));+ } else {+ LOG_WARN("PythonEnv",+ QString("[%1] uv pip list failed (exit=%2) — treating as empty")+ .arg(venv_name).arg(exit_code));+ }++ list_stdout_buf_.clear();++ if (venv_name == "venv-numpy1") {+ v1_loaded_ = true;+ start_list_venv("venv-numpy2");+ } else {+ v2_loaded_ = true;+ merge_and_populate_table();+ }+}++// ── merge_and_populate_table ──────────────────────────────────────────────────++void PythonEnvSection::merge_and_populate_table() {+ for (auto& row : all_packages_) {+ const QMap<QString, QString>& installed_map =+ (row.venv == "venv-numpy1") ? installed_v1_ : installed_v2_;++ auto it = installed_map.find(row.name);+ if (it != installed_map.end()) {+ row.installed_ver = it.value();+ row.missing = false;+ } else {+ row.installed_ver.clear();+ row.missing = true;+ }+ }++ int total = all_packages_.size();+ int missing = 0;+ for (const auto& row : std::as_const(all_packages_))+ if (row.missing) ++missing;++ pkg_table_->setUpdatesEnabled(false);+ pkg_table_->setRowCount(0);++ for (int i = 0; i < all_packages_.size(); ++i) {+ const PackageRow& row = all_packages_[i];++ pkg_table_->insertRow(i);+ pkg_table_->setRowHeight(i, 28);++ // Col 0: checkbox+ auto* chk = new QCheckBox(this);+ chk->setStyleSheet(+ QString("QCheckBox{background:transparent;}"+ "QCheckBox::indicator{width:13px;height:13px;}"+ "QCheckBox::indicator:unchecked{border:1px solid %1;background:%2;}"+ "QCheckBox::indicator:checked{border:1px solid %3;background:%3;}")+ .arg(ui::colors::BORDER_BRIGHT(), ui::colors::BG_RAISED(), ui::colors::AMBER()));+ auto* chk_cell = new QWidget(this);+ auto* chk_hl = new QHBoxLayout(chk_cell);+ chk_hl->setContentsMargins(4, 0, 4, 0);+ chk_hl->setAlignment(Qt::AlignCenter);+ chk_hl->addWidget(chk);+ pkg_table_->setCellWidget(i, 0, chk_cell);++ // Col 1: package name+ auto* name_item = new QTableWidgetItem(row.display_name);+ name_item->setForeground(QColor(ui::colors::TEXT_PRIMARY()));+ pkg_table_->setItem(i, 1, name_item);++ // Col 2: venv label — Trading=blue, Analytics=amber so they're visually distinct+ auto* venv_item = new QTableWidgetItem(row.venv_label);+ venv_item->setForeground(QColor(+ row.venv == "venv-numpy1" ? "#38bdf8" : ui::colors::AMBER()));+ venv_item->setTextAlignment(Qt::AlignCenter);+ QFont venv_font = venv_item->font();+ venv_font.setBold(true);+ venv_item->setFont(venv_font);+ pkg_table_->setItem(i, 2, venv_item);++ // Col 3: required spec+ auto* req_item = new QTableWidgetItem(row.required_spec);+ req_item->setForeground(QColor(ui::colors::TEXT_SECONDARY()));+ pkg_table_->setItem(i, 3, req_item);++ // Col 4: installed version+ auto* inst_item = new QTableWidgetItem(row.missing ? QString("—") : row.installed_ver);+ inst_item->setForeground(QColor(row.missing ? ui::colors::TEXT_TERTIARY() : ui::colors::TEXT_PRIMARY()));+ inst_item->setTextAlignment(Qt::AlignCenter);+ pkg_table_->setItem(i, 4, inst_item);++ // Col 5: status badge+ auto* status_item = new QTableWidgetItem(row.missing ? "MISSING" : "OK");+ status_item->setForeground(QColor(row.missing ? ui::colors::NEGATIVE() : ui::colors::POSITIVE()));+ status_item->setTextAlignment(Qt::AlignCenter);+ pkg_table_->setItem(i, 5, status_item);++ // Col 6: action button+ auto* btn = new QPushButton(row.missing ? "Install" : "Upgrade", this);+ btn->setFixedHeight(22);+ btn->setStyleSheet(+ row.missing+ ? QString("QPushButton{background:%1;color:%2;border:none;font-size:10px;"+ "font-weight:700;}"+ "QPushButton:hover{background:%3;}")+ .arg(ui::colors::AMBER(), ui::colors::BG_BASE(), ui::colors::AMBER_DIM())+ : QString("QPushButton{background:transparent;color:%1;border:1px solid %2;"+ "font-size:10px;}"+ "QPushButton:hover{background:%3;}")+ .arg(ui::colors::TEXT_SECONDARY(), ui::colors::BORDER_DIM(), ui::colors::BG_RAISED()));+ btn->setCursor(Qt::PointingHandCursor);+ connect(btn, &QPushButton::clicked, this, [this, i]() { on_row_action_clicked(i); });+ pkg_table_->setCellWidget(i, 6, btn);+ }++ pkg_table_->setUpdatesEnabled(true);++ show_status(+ QString("%1 packages — %2 missing").arg(total).arg(missing),+ missing > 0);++ LOG_INFO("PythonEnv",+ QString("Table populated: %1 total, %2 missing").arg(total).arg(missing));++ apply_filter();+}++// ── on_row_action_clicked ────────────────────────────────────────────────────++void PythonEnvSection::on_row_action_clicked(int row) {+ if (row < 0 || row >= all_packages_.size())+ return;+ const PackageRow& pkg = all_packages_[row];++ ActionBatch batch;+ batch.venv = pkg.venv;+ batch.packages = {pkg.required_spec};+ batch.upgrade = !pkg.missing;++ start_action({batch});+}++// ── build_batches_for_selected ────────────────────────────────────────────────++QList<PythonEnvSection::ActionBatch> PythonEnvSection::build_batches_for_selected() const {+ ActionBatch b1, b2;+ b1.venv = "venv-numpy1";+ b1.upgrade = false;+ b2.venv = "venv-numpy2";+ b2.upgrade = false;++ for (int i = 0; i < pkg_table_->rowCount(); ++i) {+ if (pkg_table_->isRowHidden(i))+ continue;+ auto* cell = pkg_table_->cellWidget(i, 0);+ if (!cell)+ continue;+ auto* chk = cell->findChild<QCheckBox*>();+ if (!chk || !chk->isChecked())+ continue;++ if (i >= all_packages_.size())+ continue;+ const PackageRow& row = all_packages_[i];++ if (row.venv == "venv-numpy1") {+ b1.packages << row.required_spec;+ b1.upgrade = !row.missing;+ } else {+ b2.packages << row.required_spec;+ b2.upgrade = !row.missing;+ }+ }++ QList<ActionBatch> result;+ if (!b1.packages.isEmpty()) result << b1;+ if (!b2.packages.isEmpty()) result << b2;+ return result;+}++// ── start_action ──────────────────────────────────────────────────────────────++void PythonEnvSection::start_action(const QList<ActionBatch>& batches) {+ if (batches.isEmpty())+ return;++ action_queue_ = batches;+ set_actions_enabled(false);+ install_bar_->setValue(0);+ install_bar_->setVisible(true);+ install_log_->setVisible(true);+ install_log_->setText("Starting...");++ run_next_batch();+}++// ── run_next_batch ────────────────────────────────────────────────────────────++void PythonEnvSection::run_next_batch() {+ using python::PythonSetupManager;+ auto& mgr = PythonSetupManager::instance();++ if (action_queue_.isEmpty()) {+ on_action_finished(0);+ return;+ }++ ActionBatch batch = action_queue_.takeFirst();+ QString venv_python = mgr.python_path(batch.venv);++ QStringList args = {"pip", "install", "--python", venv_python};+ if (batch.upgrade)+ args << "--upgrade";+ args << batch.packages;++ QProcessEnvironment env = QProcessEnvironment::systemEnvironment();+ env.insert("UV_PYTHON_INSTALL_DIR", mgr.install_dir() + "/python");+ env.insert("PEEWEE_NO_SQLITE_EXTENSIONS", "1");+ env.insert("PEEWEE_NO_C_EXTENSION", "1");+ action_proc_->setProcessEnvironment(env);++ action_stdout_buf_.clear();+ action_proc_->disconnect();++ connect(action_proc_, &QProcess::readyReadStandardOutput, this, [this]() {+ action_stdout_buf_ += action_proc_->readAllStandardOutput();+ const QString out = QString::fromUtf8(action_stdout_buf_);+ const QStringList lines = out.split('\n', Qt::SkipEmptyParts);+ if (!lines.isEmpty())+ install_log_->setText(lines.last().trimmed().left(120));+ });++ connect(action_proc_, qOverload<int, QProcess::ExitStatus>(&QProcess::finished),+ this, [this](int exit_code, QProcess::ExitStatus) {+ action_stdout_buf_.clear();+ if (!action_queue_.isEmpty()) {+ run_next_batch();+ } else {+ on_action_finished(exit_code);+ }+ });++ LOG_INFO("PythonEnv",+ QString("uv pip install: venv=%1 upgrade=%2 packages=%3")+ .arg(batch.venv).arg(batch.upgrade).arg(batch.packages.join(", ").left(200)));++ install_log_->setText(+ QString("Installing into %1...").arg(batch.venv == "venv-numpy1" ? "Trading" : "Analytics"));+ install_bar_->setValue(10);++ action_proc_->start(mgr.uv_path(), args);+}++// ── on_action_finished ────────────────────────────────────────────────────────++void PythonEnvSection::on_action_finished(int exit_code) {+ install_bar_->setVisible(false);+ install_log_->setVisible(false);+ set_actions_enabled(true);++ if (exit_code == 0) {+ show_status("Install complete — refreshing...");+ LOG_INFO("PythonEnv", "Install/upgrade finished successfully");+ } else {+ show_status(QString("Install finished with errors (exit %1)").arg(exit_code), true);+ LOG_WARN("PythonEnv", QString("Install finished with exit code %1").arg(exit_code));+ }++ load_packages();+}++// ── apply_filter ──────────────────────────────────────────────────────────────++void PythonEnvSection::apply_filter() {+ const QString search = search_input_->text().trimmed().toLower();+ const int venv_idx = venv_filter_->currentIndex(); // 0=All, 1=Trading, 2=Analytics++ for (int i = 0; i < pkg_table_->rowCount(); ++i) {+ if (i >= all_packages_.size()) {+ pkg_table_->setRowHidden(i, false);+ continue;+ }+ const PackageRow& row = all_packages_[i];++ bool venv_match = true;+ if (venv_idx == 1) venv_match = (row.venv == "venv-numpy1");+ if (venv_idx == 2) venv_match = (row.venv == "venv-numpy2");++ bool name_match = search.isEmpty() ||+ row.display_name.toLower().contains(search);++ pkg_table_->setRowHidden(i, !(venv_match && name_match));+ }+}++// ── set_actions_enabled ───────────────────────────────────────────────────────++void PythonEnvSection::set_actions_enabled(bool enabled) {+ refresh_btn_->setEnabled(enabled);+ install_missing_btn_->setEnabled(enabled);+ upgrade_all_btn_->setEnabled(enabled);+ batch_action_btn_->setEnabled(enabled);++ for (int i = 0; i < pkg_table_->rowCount(); ++i) {+ auto* w = pkg_table_->cellWidget(i, 6);+ if (w) {+ auto* btn = qobject_cast<QPushButton*>(w);+ if (!btn) btn = w->findChild<QPushButton*>();+ if (btn) btn->setEnabled(enabled);+ }+ }+}++// ── show_status ───────────────────────────────────────────────────────────────++void PythonEnvSection::show_status(const QString& msg, bool error) {+ status_lbl_->setText(msg);+ status_lbl_->setStyleSheet(+ QString("color:%1;background:transparent;")+ .arg(error ? ui::colors::NEGATIVE() : ui::colors::TEXT_SECONDARY()));+}++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/settings/PythonEnvSection.h b/fincept-qt/src/screens/settings/PythonEnvSection.hnew file mode 100644index 000000000..b0720bdc3--- /dev/null+++ b/fincept-qt/src/screens/settings/PythonEnvSection.h@@ -0,0 +1,104 @@+#pragma once+// PythonEnvSection.h — Python venv package manager panel for SettingsScreen.+// Shows all packages from requirements-numpy1.txt and requirements-numpy2.txt,+// their installed versions, and allows install/upgrade via uv pip.++#include <QComboBox>+#include <QLabel>+#include <QLineEdit>+#include <QProcess>+#include <QProgressBar>+#include <QPushButton>+#include <QTableWidget>+#include <QWidget>++namespace fincept::screens {++class PythonEnvSection : public QWidget {+ Q_OBJECT+ public:+ explicit PythonEnvSection(QWidget* parent = nullptr);++ /// Trigger a package list refresh — called when section becomes visible.+ void reload();++ protected:+ void showEvent(QShowEvent* e) override;++ private:+ // ── UI ────────────────────────────────────────────────────────────────────+ QTableWidget* pkg_table_ = nullptr;+ QLineEdit* search_input_ = nullptr;+ QComboBox* venv_filter_ = nullptr; // All / Trading / Analytics+ QLabel* status_lbl_ = nullptr;+ QProgressBar* install_bar_ = nullptr; // hidden when idle+ QLabel* install_log_ = nullptr; // last stdout line from uv+ QPushButton* refresh_btn_ = nullptr;+ QPushButton* install_missing_btn_ = nullptr;+ QPushButton* upgrade_all_btn_ = nullptr;+ QPushButton* batch_action_btn_ = nullptr; // "Install/Upgrade Selected"++ // ── Processes — signal-driven, never waitForFinished on UI thread ─────────+ QProcess* list_proc_ = nullptr; // uv pip list, reused sequentially+ QProcess* action_proc_ = nullptr; // uv pip install / upgrade++ // ── Data ──────────────────────────────────────────────────────────────────+ struct PackageRow {+ QString name; // canonical: lowercase, hyphens/dots → underscore+ QString display_name; // original name from requirements file+ QString venv; // "venv-numpy1" or "venv-numpy2"+ QString venv_label; // "Trading" or "Analytics"+ QString required_spec; // raw spec, e.g. ">=2.2.3,<3.0"+ QString installed_ver; // from uv pip list; empty if not installed+ bool missing = true;+ };++ QList<PackageRow> all_packages_; // merged from both req files+ QMap<QString, QString> installed_v1_; // canonical_name → version, venv-numpy1+ QMap<QString, QString> installed_v2_; // canonical_name → version, venv-numpy2+ bool v1_loaded_ = false;+ bool v2_loaded_ = false;++ // ── Action queue — drained one batch at a time ────────────────────────────+ struct ActionBatch {+ QString venv; // "venv-numpy1" or "venv-numpy2"+ QStringList packages; // raw spec strings to pass to uv+ bool upgrade = false;+ };+ QList<ActionBatch> action_queue_;++ // ── stdout accumulators — readyReadStandardOutput fires many times ────────+ QByteArray list_stdout_buf_;+ QByteArray action_stdout_buf_;++ // ── Builders ──────────────────────────────────────────────────────────────+ void build_ui();++ // ── Load phase ────────────────────────────────────────────────────────────+ void load_packages();+ void start_list_venv(const QString& venv_name);+ void on_list_finished(const QString& venv_name, int exit_code);+ void parse_requirements(const QString& req_file,+ const QString& venv_name,+ const QString& venv_label);+ void merge_and_populate_table();+ QString find_req_file(const QString& filename) const;++ // ── Action phase ──────────────────────────────────────────────────────────+ void start_action(const QList<ActionBatch>& batches);+ void run_next_batch();+ void on_action_finished(int exit_code);++ // ── Table helpers ─────────────────────────────────────────────────────────+ void apply_filter();+ void on_row_action_clicked(int row);+ QList<ActionBatch> build_batches_for_selected() const;++ // ── Misc ──────────────────────────────────────────────────────────────────+ void set_actions_enabled(bool enabled);+ void show_status(const QString& msg, bool error = false);++ static QString canonicalise(const QString& name);+};++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/settings/SettingsScreen.cpp b/fincept-qt/src/screens/settings/SettingsScreen.cppindex a87b31b4d..5b55ca1a4 100644--- a/fincept-qt/src/screens/settings/SettingsScreen.cpp+++ b/fincept-qt/src/screens/settings/SettingsScreen.cpp@@ -14,6 +14,7 @@#include "screens/settings/KeybindingsSection.h"#include "screens/settings/LlmConfigSection.h"#include "screens/settings/McpServersSection.h"+#include "screens/settings/PythonEnvSection.h"#include "services/notifications/NotificationService.h"#include "storage/StorageManager.h"#include "storage/cache/CacheManager.h"@@ -160,6 +161,7 @@ SettingsScreen::SettingsScreen(QWidget* parent) : QWidget(parent) {sections_->addWidget(build_security()); // 8sections_->addWidget(build_profiles()); // 9sections_->addWidget(build_keybindings()); // 10+ sections_->addWidget(build_python_env()); // 11QList<QPushButton*> nav_btns;auto make_btn = [&](const QString& text, int idx) {@@ -194,6 +196,7 @@ SettingsScreen::SettingsScreen(QWidget* parent) : QWidget(parent) {make_btn("Security", 8);make_btn("Profiles", 9);make_btn("Keybindings", 10);+ make_btn("Python Env", 11);first->setChecked(true);@@ -2862,4 +2865,10 @@ QWidget* SettingsScreen::build_keybindings() {return new KeybindingsSection(this);}+// ── Python Env ────────────────────────────────────────────────────────────────++QWidget* SettingsScreen::build_python_env() {+ return new PythonEnvSection(this);+}+} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/settings/SettingsScreen.h b/fincept-qt/src/screens/settings/SettingsScreen.hindex 0ff1c7608..083286e64 100644--- a/fincept-qt/src/screens/settings/SettingsScreen.h+++ b/fincept-qt/src/screens/settings/SettingsScreen.h@@ -46,6 +46,7 @@ class SettingsScreen : public QWidget, public IStatefulScreen {QWidget* build_security();QWidget* build_profiles();QWidget* build_keybindings();+ QWidget* build_python_env();// ── Shared layout helper ──────────────────────────────────────────────────static QWidget* make_row(const QString& label, QWidget* control, const QString& description = {});diff --git a/fincept-qt/src/screens/setup/SetupScreen.cpp b/fincept-qt/src/screens/setup/SetupScreen.cppindex 52416577f..99bd9798a 100644--- a/fincept-qt/src/screens/setup/SetupScreen.cpp+++ b/fincept-qt/src/screens/setup/SetupScreen.cpp@@ -8,10 +8,13 @@#include <QHBoxLayout>#include <QLabel>#include <QMessageBox>+#include <QMetaObject>+#include <QPointer>#include <QProgressBar>#include <QPushButton>#include <QTimer>#include <QVBoxLayout>+#include <QtConcurrent>namespace fincept::screens {@@ -204,7 +207,7 @@ QWidget* SetupScreen::build_step_row(const QString& key, const QString& label, c// Pulse timer — drives the indeterminate animation while step is in-flightauto* pulse = new QTimer(row);- pulse->setInterval(40); // ~25 fps — smooth but cheap+ pulse->setInterval(100); // ~10 fps — imperceptible vs 25 fps for a progress barpulse->setSingleShot(false);StepUI step;@@ -374,40 +377,53 @@ void SetupScreen::mark_step_done(const QString& key) {}void SetupScreen::prefill_completed_steps() {- const auto status = python::PythonSetupManager::instance().check_status();-- if (status.uv_installed)- mark_step_done("uv");- if (status.python_installed)- mark_step_done("python");- if (status.venv_numpy1_ready && status.venv_numpy2_ready)- mark_step_done("venv");- if (status.venv_numpy1_ready)- mark_step_done("packages-numpy1");- if (status.venv_numpy2_ready)- mark_step_done("packages-numpy2");-- const bool any_done = status.uv_installed || status.python_installed || status.venv_numpy1_ready ||- status.venv_numpy2_ready;- const bool all_done = status.uv_installed && status.python_installed && status.venv_numpy1_ready &&- status.venv_numpy2_ready;-- summary_lbl_->setText({});-- if (all_done) {- subtitle_lbl_->setText("Your workspace is fully configured");- begin_btn_->setEnabled(false);- begin_btn_->setText("ALREADY COMPLETE");- status_label_->setText("Everything is installed and ready to go.");- } else if (any_done) {- subtitle_lbl_->setText("Finishing your workspace setup");- begin_btn_->setText("CONTINUE SETUP");- status_label_->setText("Only the missing pieces will be downloaded. Needs an internet connection.");- } else {- subtitle_lbl_->setText("Getting your workspace ready");- begin_btn_->setText("BEGIN SETUP");- status_label_->setText("Takes about 3–5 minutes. Needs an internet connection.");- }+ // check_status() slow path can spawn Python processes (up to ~15s on first run).+ // Run it on a background thread and post results back to the UI thread — P1/P8.+ QPointer<SetupScreen> self = this;+ QtConcurrent::run([self]() {+ const auto status = python::PythonSetupManager::instance().check_status();+ QMetaObject::invokeMethod(self, [self, status]() {+ if (!self)+ return;++ if (status.uv_installed)+ self->mark_step_done("uv");+ if (status.python_installed)+ self->mark_step_done("python");+ // "venv" step = both venv directories created (python exe present)+ if (status.venv_numpy1_created && status.venv_numpy2_created)+ self->mark_step_done("venv");+ // package steps = packages actually installed (marker file present)+ if (status.venv_numpy1_ready)+ self->mark_step_done("packages-numpy1");+ if (status.venv_numpy2_ready)+ self->mark_step_done("packages-numpy2");++ const bool any_done = status.uv_installed || status.python_installed ||+ status.venv_numpy1_created || status.venv_numpy2_created ||+ status.venv_numpy1_ready || status.venv_numpy2_ready;+ const bool all_done = status.uv_installed && status.python_installed &&+ status.venv_numpy1_ready && status.venv_numpy2_ready;++ self->summary_lbl_->setText({});++ if (all_done) {+ self->subtitle_lbl_->setText("Your workspace is fully configured");+ self->begin_btn_->setEnabled(false);+ self->begin_btn_->setText("ALREADY COMPLETE");+ self->status_label_->setText("Everything is installed and ready to go.");+ } else if (any_done) {+ self->subtitle_lbl_->setText("Finishing your workspace setup");+ self->begin_btn_->setText("CONTINUE SETUP");+ self->status_label_->setText(+ "Only the missing pieces will be downloaded. Needs an internet connection.");+ } else {+ self->subtitle_lbl_->setText("Getting your workspace ready");+ self->begin_btn_->setText("BEGIN SETUP");+ self->status_label_->setText("Takes about 3–5 minutes. Needs an internet connection.");+ }+ }, Qt::QueuedConnection);+ });}} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/trade_viz/TradeVizScreen.cpp b/fincept-qt/src/screens/trade_viz/TradeVizScreen.cppindex 1f16b24f2..7f4137ab8 100644--- a/fincept-qt/src/screens/trade_viz/TradeVizScreen.cpp+++ b/fincept-qt/src/screens/trade_viz/TradeVizScreen.cpp@@ -1,6 +1,7 @@// Trade Visualization — Bloomberg ECTR Trade Flow style#include "screens/trade_viz/TradeVizScreen.h"+#include "core/session/ScreenStateManager.h"#include "ui/theme/Theme.h"#include <QDateTime>@@ -417,6 +418,14 @@ QWidget* TradeVizScreen::build_filter_bar() {.arg(ui::colors::TEXT_TERTIARY()));hl->addWidget(clock_label_);+ // Persist filter selections so the user returns to the same country/period+ // after restarting the app.+ auto on_filter = [this]() { fincept::ScreenStateManager::instance().notify_changed(this); };+ connect(country_combo_, QOverload<int>::of(&QComboBox::currentIndexChanged), this, on_filter);+ connect(order_combo_, QOverload<int>::of(&QComboBox::currentIndexChanged), this, on_filter);+ connect(period_combo_, QOverload<int>::of(&QComboBox::currentIndexChanged), this, on_filter);+ connect(year_combo_, QOverload<int>::of(&QComboBox::currentIndexChanged), this, on_filter);+return bar;}@@ -546,4 +555,33 @@ void TradeVizScreen::setup_ui() {root->addWidget(splitter, 1);}+// ── IStatefulScreen ──────────────────────────────────────────────────────────++QVariantMap TradeVizScreen::save_state() const {+ QVariantMap s;+ if (country_combo_)+ s.insert("country", country_combo_->currentIndex());+ if (order_combo_)+ s.insert("order", order_combo_->currentIndex());+ if (period_combo_)+ s.insert("period", period_combo_->currentIndex());+ if (year_combo_)+ s.insert("year", year_combo_->currentIndex());+ return s;+}++void TradeVizScreen::restore_state(const QVariantMap& state) {+ auto apply = [&](QComboBox* box, const char* key) {+ if (!box)+ return;+ const int v = state.value(key, -1).toInt();+ if (v >= 0 && v < box->count())+ box->setCurrentIndex(v);+ };+ apply(country_combo_, "country");+ apply(order_combo_, "order");+ apply(period_combo_, "period");+ apply(year_combo_, "year");+}+} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/trade_viz/TradeVizScreen.h b/fincept-qt/src/screens/trade_viz/TradeVizScreen.hindex 942264173..9a3ecfc49 100644--- a/fincept-qt/src/screens/trade_viz/TradeVizScreen.h+++ b/fincept-qt/src/screens/trade_viz/TradeVizScreen.h@@ -1,4 +1,6 @@#pragma once+#include "screens/IStatefulScreen.h"+#include <QComboBox>#include <QHideEvent>#include <QLabel>@@ -11,11 +13,17 @@ namespace fincept::screens {/// Bloomberg ECTR-style Trade Flow visualization./// Chord diagram showing bilateral trade flows + partner ranking table.-class TradeVizScreen : public QWidget {+class TradeVizScreen : public QWidget, public IStatefulScreen {Q_OBJECTpublic:explicit TradeVizScreen(QWidget* parent = nullptr);+ // IStatefulScreen — persists the filter combo selections+ // (country/order/period/year).+ QVariantMap save_state() const override;+ void restore_state(const QVariantMap& state) override;+ QString state_key() const override { return "trade_viz"; }+protected:void showEvent(QShowEvent* event) override;void hideEvent(QHideEvent* event) override;diff --git a/fincept-qt/src/services/equity/EquityResearchService.cpp b/fincept-qt/src/services/equity/EquityResearchService.cppindex 9fe8ac74e..038f7d6b4 100644--- a/fincept-qt/src/services/equity/EquityResearchService.cpp+++ b/fincept-qt/src/services/equity/EquityResearchService.cpp@@ -321,8 +321,8 @@ StockInfo EquityResearchService::parse_info(const QJsonObject& o) const {s.exchange = o["exchange"].toString();s.employees = o["employees"].toInt();- s.market_cap = o["market_cap"].toVariant().toDouble();- s.enterprise_value = o["enterprise_value"].toVariant().toDouble();+ s.market_cap = o["market_cap"].toDouble();+ s.enterprise_value = o["enterprise_value"].toDouble();s.pe_ratio = o["pe_ratio"].toDouble();s.forward_pe = o["forward_pe"].toDouble();s.peg_ratio = o["peg_ratio"].toDouble();@@ -340,17 +340,17 @@ StockInfo EquityResearchService::parse_info(const QJsonObject& o) const {s.book_value = o["book_value"].toDouble();s.revenue_per_share = o["revenue_per_share"].toDouble();- s.free_cashflow = o["free_cashflow"].toVariant().toDouble();- s.operating_cashflow = o["operating_cashflow"].toVariant().toDouble();- s.total_cash = o["total_cash"].toVariant().toDouble();- s.total_debt = o["total_debt"].toVariant().toDouble();- s.total_revenue = o["total_revenue"].toVariant().toDouble();+ s.free_cashflow = o["free_cashflow"].toDouble();+ s.operating_cashflow = o["operating_cashflow"].toDouble();+ s.total_cash = o["total_cash"].toDouble();+ s.total_debt = o["total_debt"].toDouble();+ s.total_revenue = o["total_revenue"].toDouble();s.earnings_growth = o["earnings_growth"].toDouble();s.revenue_growth = o["revenue_growth"].toDouble();- s.shares_outstanding = o["shares_outstanding"].toVariant().toDouble();- s.float_shares = o["float_shares"].toVariant().toDouble();+ s.shares_outstanding = o["shares_outstanding"].toDouble();+ s.float_shares = o["float_shares"].toDouble();s.held_insiders_pct = o["held_percent_insiders"].toDouble();s.held_institutions_pct = o["held_percent_institutions"].toDouble();s.short_ratio = o["short_ratio"].toDouble();@@ -675,3 +675,4 @@ QVector<NewsArticle> EquityResearchService::parse_news(const QJsonArray& arr) co}} // namespace fincept::services::equity+diff --git a/fincept-qt/src/services/forum/ForumService.cpp b/fincept-qt/src/services/forum/ForumService.cppindex 9dd6ea645..1174715b1 100644--- a/fincept-qt/src/services/forum/ForumService.cpp+++ b/fincept-qt/src/services/forum/ForumService.cpp@@ -13,9 +13,10 @@#include <QUrl>#include <QUrlQuery>-static constexpr int kCategoriesTtlSec = 5 * 60;-static constexpr int kStatsTtlSec = 2 * 60;-static constexpr int kTrendingTtlSec = 2 * 60;+static constexpr int kCategoriesTtlSec = 5 * 60;+static constexpr int kStatsTtlSec = 2 * 60;+static constexpr int kTrendingTtlSec = 2 * 60;+static constexpr int kTransferTimeoutMs = 10000; // 10s per API requestnamespace fincept::services {@@ -38,7 +39,7 @@ void ForumService::get(const QString& path, std::function<void(bool, QJsonObjectQNetworkRequest req(QUrl(QString(BASE) + path));req.setRawHeader("X-API-KEY", api_key().toUtf8());req.setRawHeader("Accept", "application/json");- req.setTransferTimeout(10000);+ req.setTransferTimeout(kTransferTimeoutMs);auto* reply = nam_->get(req);connect(reply, &QNetworkReply::finished, this, [reply, cb]() {@@ -63,7 +64,7 @@ void ForumService::post_req(const QString& path, const QJsonObject& body, std::fQNetworkRequest req(QUrl(QString(BASE) + path));req.setRawHeader("X-API-KEY", api_key().toUtf8());req.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");- req.setTransferTimeout(10000);+ req.setTransferTimeout(kTransferTimeoutMs);auto* reply = nam_->post(req, QJsonDocument(body).toJson(QJsonDocument::Compact));connect(reply, &QNetworkReply::finished, this, [reply, cb]() {@@ -83,7 +84,7 @@ void ForumService::put_req(const QString& path, const QJsonObject& body, std::fuQNetworkRequest req(QUrl(QString(BASE) + path));req.setRawHeader("X-API-KEY", api_key().toUtf8());req.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");- req.setTransferTimeout(10000);+ req.setTransferTimeout(kTransferTimeoutMs);auto* reply = nam_->put(req, QJsonDocument(body).toJson(QJsonDocument::Compact));connect(reply, &QNetworkReply::finished, this, [reply, cb]() {@@ -400,3 +401,4 @@ void ForumService::update_profile(const QString& display_name, const QString& bi}} // namespace fincept::services+diff --git a/fincept-qt/src/services/news/NewsService.cpp b/fincept-qt/src/services/news/NewsService.cppindex e89ecab21..8f2e92a26 100644--- a/fincept-qt/src/services/news/NewsService.cpp+++ b/fincept-qt/src/services/news/NewsService.cpp@@ -23,6 +23,10 @@namespace fincept::services {+static constexpr int kFeedTransferTimeoutMs = 5000; // 5s per RSS feed request+static constexpr int kWsReconnectDelayMs = 10000; // 10s before WebSocket reconnect+static constexpr int kSummaryMaxChars = 300; // max chars for article summary+// ── Singleton ───────────────────────────────────────────────────────────────NewsService& NewsService::instance() {@@ -94,7 +98,7 @@ void NewsService::fetch_all_news(bool force, ArticlesCallback cb) {QNetworkRequest req(QUrl(feed.url));req.setHeader(QNetworkRequest::UserAgentHeader, "FinceptTerminal/4.0");req.setRawHeader("Accept", "application/rss+xml, application/xml, text/xml, */*");- req.setTransferTimeout(5000); // 5s timeout per feed — fail fast+ req.setTransferTimeout(kFeedTransferTimeoutMs);auto* reply = nam_->get(req);connect(reply, &QNetworkReply::finished, this, [reply, feed, state]() {@@ -222,7 +226,7 @@ void NewsService::fetch_all_news_progressive(bool force, ArticlesCallback final_QNetworkRequest req(QUrl(feed.url));req.setHeader(QNetworkRequest::UserAgentHeader, "FinceptTerminal/4.0");req.setRawHeader("Accept", "application/rss+xml, application/xml, text/xml, */*");- req.setTransferTimeout(5000);+ req.setTransferTimeout(kFeedTransferTimeoutMs);auto* reply = nam_->get(req);connect(reply, &QNetworkReply::finished, this, [reply, feed, state, total, this]() {@@ -417,8 +421,8 @@ void NewsService::connect_live_feed(const QString& ws_url) {connect(live_ws_, &QWebSocket::disconnected, this, [this]() {live_connected_ = false;LOG_WARN("NewsService", "WebSocket live feed disconnected");- // Auto-reconnect after 10s- QTimer::singleShot(10000, this, [this]() {+ // Auto-reconnect after delay+ QTimer::singleShot(kWsReconnectDelayMs, this, [this]() {if (live_ws_ && !live_connected_)live_ws_->open(live_ws_->requestUrl());});@@ -578,7 +582,7 @@ QVector<NewsArticle> NewsService::parse_rss_xml(const QByteArray& xml, const RSScurrent.headline = text.left(200);} else if ((current_tag == "description" || current_tag == "summary" || current_tag == "encoded") &¤t.summary.isEmpty()) {- current.summary = strip_html(text).left(300);+ current.summary = strip_html(text).left(kSummaryMaxChars);} else if (current_tag == "link" && current.link.isEmpty()) {current.link = text.trimmed();} else if ((current_tag == "guid" || current_tag == "id") && current.link.isEmpty()) {diff --git a/fincept-qt/src/services/polymarket/PolymarketService.cpp b/fincept-qt/src/services/polymarket/PolymarketService.cppindex d049aaf65..a5ae54077 100644--- a/fincept-qt/src/services/polymarket/PolymarketService.cpp+++ b/fincept-qt/src/services/polymarket/PolymarketService.cpp@@ -36,26 +36,26 @@ static QJsonArray parse_json_arr(const QJsonValue& val) {Market Market::from_json(const QJsonObject& obj) {Market m;- m.id = obj["id"].toVariant().toInt();+ m.id = obj["id"].toInt();m.question = obj["question"].toString();m.slug = obj["slug"].toString();m.description = obj["description"].toString();m.condition_id = obj["conditionId"].toString();m.image = obj["image"].toString();- m.volume = obj["volume"].toVariant().toDouble();- m.liquidity = obj["liquidity"].toVariant().toDouble();+ m.volume = obj["volume"].toDouble();+ m.liquidity = obj["liquidity"].toDouble();m.active = obj["active"].toBool();m.closed = obj["closed"].toBool();m.end_date = obj["endDate"].toString();m.category = obj["category"].toString();- m.event_id = obj["eventId"].toVariant().toInt();+ m.event_id = obj["eventId"].toInt();auto outcomes_arr = parse_json_arr(obj["outcomes"]);auto prices_arr = parse_json_arr(obj["outcomePrices"]);for (int i = 0; i < outcomes_arr.size(); ++i) {Outcome o;o.name = outcomes_arr[i].toString();- o.price = (i < prices_arr.size()) ? prices_arr[i].toVariant().toDouble() : 0.0;+ o.price = (i < prices_arr.size()) ? prices_arr[i].toDouble() : 0.0;m.outcomes.append(o);}@@ -80,13 +80,13 @@ Market Market::from_json(const QJsonObject& obj) {Event Event::from_json(const QJsonObject& obj) {Event e;- e.id = obj["id"].toVariant().toInt();+ e.id = obj["id"].toInt();e.title = obj["title"].toString();e.slug = obj["slug"].toString();e.description = obj["description"].toString();e.image = obj["image"].toString();- e.volume = obj["volume"].toVariant().toDouble();- e.liquidity = obj["liquidity"].toVariant().toDouble();+ e.volume = obj["volume"].toDouble();+ e.liquidity = obj["liquidity"].toDouble();e.active = obj["active"].toBool();e.closed = obj["closed"].toBool();e.end_date = obj["endDate"].toString();@@ -111,17 +111,17 @@ OrderBook OrderBook::from_json(const QJsonObject& obj) {OrderBook book;book.market = obj["market"].toString();book.asset_id = obj["asset_id"].toString();- book.tick_size = obj["tick_size"].toVariant().toDouble();- book.min_order_size = obj["min_order_size"].toVariant().toDouble();+ book.tick_size = obj["tick_size"].toDouble();+ book.min_order_size = obj["min_order_size"].toDouble();book.neg_risk = obj["neg_risk"].toBool();for (const auto& b : obj["bids"].toArray()) {auto bo = b.toObject();- book.bids.append({bo["price"].toVariant().toDouble(), bo["size"].toVariant().toDouble()});+ book.bids.append({bo["price"].toDouble(), bo["size"].toDouble()});}for (const auto& a : obj["asks"].toArray()) {auto ao = a.toObject();- book.asks.append({ao["price"].toVariant().toDouble(), ao["size"].toVariant().toDouble()});+ book.asks.append({ao["price"].toDouble(), ao["size"].toDouble()});}return book;}@@ -134,7 +134,7 @@ PriceHistory PriceHistory::from_json(const QJsonObject& obj) {auto po = pt.toObject();PricePoint pp;pp.timestamp = static_cast<int64_t>(po["t"].toVariant().toLongLong());- pp.price = po["p"].toVariant().toDouble();+ pp.price = po["p"].toDouble();ph.points.append(pp);}return ph;@@ -143,8 +143,8 @@ PriceHistory PriceHistory::from_json(const QJsonObject& obj) {Trade Trade::from_json(const QJsonObject& obj) {Trade t;t.side = obj["side"].toString();- t.price = obj["price"].toVariant().toDouble();- t.size = obj["size"].toVariant().toDouble();+ t.price = obj["price"].toDouble();+ t.size = obj["size"].toDouble();t.timestamp = static_cast<int64_t>(obj["timestamp"].toVariant().toLongLong());t.condition_id = obj["conditionId"].toString();return t;@@ -160,9 +160,9 @@ TopHolder TopHolder::from_json(const QJsonObject& obj) {h.display_name = obj["name"].toString();if (h.display_name.isEmpty() && !h.address.isEmpty())h.display_name = h.address.left(6) + "..." + h.address.right(4);- h.position_size = obj["size"].toVariant().toDouble();- h.entry_price = obj["avgPrice"].toVariant().toDouble();- h.rank = obj["rank"].toVariant().toInt();+ h.position_size = obj["size"].toDouble();+ h.entry_price = obj["avgPrice"].toDouble();+ h.rank = obj["rank"].toInt();return h;}@@ -177,12 +177,12 @@ LeaderboardEntry LeaderboardEntry::from_json(const QJsonObject& obj) {if (e.display_name.isEmpty() && !e.address.isEmpty())e.display_name = e.address.left(6) + "..." + e.address.right(4);e.profile_image = obj["profileImage"].toString();- e.pnl = obj["pnl"].toVariant().toDouble();+ e.pnl = obj["pnl"].toDouble();if (e.pnl == 0)- e.pnl = obj["cashPnl"].toVariant().toDouble();- e.volume = obj["volume"].toVariant().toDouble();- e.num_trades = obj["numTrades"].toVariant().toInt();- e.rank = obj["rank"].toVariant().toInt();+ e.pnl = obj["cashPnl"].toDouble();+ e.volume = obj["volume"].toDouble();+ e.num_trades = obj["numTrades"].toInt();+ e.rank = obj["rank"].toInt();return e;}@@ -192,9 +192,9 @@ Activity Activity::from_json(const QJsonObject& obj) {a.address = obj["proxyWallet"].toString();if (a.address.isEmpty())a.address = obj["address"].toString();- a.amount = obj["size"].toVariant().toDouble();- a.usdc_size = obj["usdcSize"].toVariant().toDouble();- a.price = obj["price"].toVariant().toDouble();+ a.amount = obj["size"].toDouble();+ a.usdc_size = obj["usdcSize"].toDouble();+ a.price = obj["price"].toDouble();a.timestamp = static_cast<int64_t>(obj["timestamp"].toVariant().toLongLong());a.condition_id = obj["conditionId"].toString();a.title = obj["title"].toString();@@ -204,7 +204,7 @@ Activity Activity::from_json(const QJsonObject& obj) {Comment Comment::from_json(const QJsonObject& obj) {Comment c;- c.id = obj["id"].toVariant().toInt();+ c.id = obj["id"].toInt();c.body = obj["body"].toString();if (c.body.isEmpty())c.body = obj["content"].toString();@@ -213,14 +213,14 @@ Comment Comment::from_json(const QJsonObject& obj) {c.author = obj["author"].toString();c.author_address = obj["address"].toString();c.created_at = static_cast<int64_t>(obj["createdAt"].toVariant().toLongLong());- c.parent_id = obj["parentId"].toVariant().toInt();- c.likes = obj["likes"].toVariant().toInt();+ c.parent_id = obj["parentId"].toInt();+ c.likes = obj["likes"].toInt();return c;}Series Series::from_json(const QJsonObject& obj) {Series s;- s.id = obj["id"].toVariant().toInt();+ s.id = obj["id"].toInt();s.title = obj["title"].toString();s.slug = obj["slug"].toString();for (const auto& e : obj["events"].toArray()) {@@ -243,9 +243,9 @@ OpenInterest OpenInterest::from_json(const QJsonObject& obj) {oi.condition_id = obj["conditionId"].toString();if (oi.condition_id.isEmpty())oi.condition_id = obj["market"].toString();- oi.open_interest = obj["openInterest"].toVariant().toDouble();+ oi.open_interest = obj["openInterest"].toDouble();if (oi.open_interest == 0)- oi.open_interest = obj["value"].toVariant().toDouble();+ oi.open_interest = obj["value"].toDouble();return oi;}@@ -254,22 +254,22 @@ LiveVolume LiveVolume::from_json(const QJsonObject& obj) {lv.event_id = obj["eventId"].toString();if (lv.event_id.isEmpty())lv.event_id = obj["event_id"].toString();- lv.volume_24h = obj["volume"].toVariant().toDouble();+ lv.volume_24h = obj["volume"].toDouble();return lv;}WsMarketUpdate WsMarketUpdate::from_json(const QJsonObject& obj) {WsMarketUpdate u;u.asset_id = obj["asset_id"].toString();- u.price = obj["price"].toVariant().toDouble();+ u.price = obj["price"].toDouble();u.timestamp = static_cast<int64_t>(obj["timestamp"].toVariant().toLongLong());for (const auto& b : obj["bids"].toArray()) {auto bo = b.toObject();- u.bids.append({bo["price"].toVariant().toDouble(), bo["size"].toVariant().toDouble()});+ u.bids.append({bo["price"].toDouble(), bo["size"].toDouble()});}for (const auto& a : obj["asks"].toArray()) {auto ao = a.toObject();- u.asks.append({ao["price"].toVariant().toDouble(), ao["size"].toVariant().toDouble()});+ u.asks.append({ao["price"].toDouble(), ao["size"].toDouble()});}return u;}@@ -636,7 +636,7 @@ void PolymarketService::fetch_price_summary(const QString& token_id) {get_clob("/midpoint?token_id=" + token_id,[acc, maybe_emit](const QJsonDocument& doc) {- acc->summary.midpoint = doc.object()["mid"].toVariant().toDouble();+ acc->summary.midpoint = doc.object()["mid"].toDouble();maybe_emit();},"Midpoint");@@ -644,7 +644,7 @@ void PolymarketService::fetch_price_summary(const QString& token_id) {get_clob("/spread?token_id=" + token_id,[acc, maybe_emit](const QJsonDocument& doc) {- acc->summary.spread = doc.object()["spread"].toVariant().toDouble();+ acc->summary.spread = doc.object()["spread"].toDouble();maybe_emit();},"Spread");@@ -652,7 +652,7 @@ void PolymarketService::fetch_price_summary(const QString& token_id) {get_clob("/last-trade-price?token_id=" + token_id,[acc, maybe_emit](const QJsonDocument& doc) {- acc->summary.last_trade_price = doc.object()["price"].toVariant().toDouble();+ acc->summary.last_trade_price = doc.object()["price"].toDouble();maybe_emit();},"LastTradePrice");@@ -793,3 +793,4 @@ void PolymarketService::fetch_open_interest(const QStringList& condition_ids) {}} // namespace fincept::services::polymarket+diff --git a/fincept-qt/src/services/polymarket/PolymarketWebSocket.cpp b/fincept-qt/src/services/polymarket/PolymarketWebSocket.cppindex 56f5c069a..003ae5e9c 100644--- a/fincept-qt/src/services/polymarket/PolymarketWebSocket.cpp+++ b/fincept-qt/src/services/polymarket/PolymarketWebSocket.cpp@@ -9,6 +9,8 @@namespace fincept::services::polymarket {+static constexpr int kPingIntervalMs = 50000;+PolymarketWebSocket& PolymarketWebSocket::instance() {static PolymarketWebSocket s;return s;@@ -23,7 +25,7 @@ PolymarketWebSocket::PolymarketWebSocket() : QObject(nullptr) {connect(ws_, &WebSocketClient::error_occurred, this, &PolymarketWebSocket::on_ws_error);ping_timer_ = new QTimer(this);- ping_timer_->setInterval(50000);+ ping_timer_->setInterval(kPingIntervalMs);connect(ping_timer_, &QTimer::timeout, this, &PolymarketWebSocket::send_ping);}@@ -121,7 +123,7 @@ void PolymarketWebSocket::on_ws_message(const QString& msg) {continue;if (obj.contains("price")) {- double price = obj["price"].toVariant().toDouble();+ double price = obj["price"].toDouble();if (price > 0)emit price_updated(asset_id, price);}@@ -131,11 +133,11 @@ void PolymarketWebSocket::on_ws_message(const QString& msg) {book.asset_id = asset_id;for (const auto& b : obj["bids"].toArray()) {auto bo = b.toObject();- book.bids.append({bo["price"].toVariant().toDouble(), bo["size"].toVariant().toDouble()});+ book.bids.append({bo["price"].toDouble(), bo["size"].toDouble()});}for (const auto& a : obj["asks"].toArray()) {auto ao = a.toObject();- book.asks.append({ao["price"].toVariant().toDouble(), ao["size"].toVariant().toDouble()});+ book.asks.append({ao["price"].toDouble(), ao["size"].toDouble()});}if (!book.bids.isEmpty() || !book.asks.isEmpty())emit orderbook_updated(asset_id, book);@@ -148,3 +150,4 @@ void PolymarketWebSocket::on_ws_error(const QString& error) {}} // namespace fincept::services::polymarket+diff --git a/fincept-qt/src/services/stt/SpeechService.cpp b/fincept-qt/src/services/stt/SpeechService.cppindex 5cf486c90..e0d3c75fb 100644--- a/fincept-qt/src/services/stt/SpeechService.cpp+++ b/fincept-qt/src/services/stt/SpeechService.cpp@@ -22,6 +22,7 @@namespace fincept::services {static constexpr auto TAG = "SpeechService";+static constexpr int kShutdownTimeoutMs = 2000;// ── Singleton ────────────────────────────────────────────────────────────────@@ -96,8 +97,14 @@ void SpeechService::spawn_process() {env.insert("PYTHONUNBUFFERED", "1");env.insert("FINCEPT_DATA_DIR", python::PythonSetupManager::instance().install_dir());- QString existing_pypath = env.value("PYTHONPATH");- QString new_pypath = scripts_dir + (existing_pypath.isEmpty() ? "" : ";" + existing_pypath);+ const QString existing_pypath = env.value("PYTHONPATH");+#ifdef _WIN32+ const QChar kPathSep = ';';+#else+ const QChar kPathSep = ':';+#endif+ const QString new_pypath =+ existing_pypath.isEmpty() ? scripts_dir : (scripts_dir + kPathSep + existing_pypath);env.insert("PYTHONPATH", new_pypath);process_->setProcessEnvironment(env);@@ -137,7 +144,7 @@ void SpeechService::kill_process() {if (process_->state() != QProcess::NotRunning) {process_->kill();- process_->waitForFinished(2000);+ process_->waitForFinished(kShutdownTimeoutMs);}process_->deleteLater();process_ = nullptr;diff --git a/fincept-qt/src/services/workflow/nodes/AgentNodes.cpp b/fincept-qt/src/services/workflow/nodes/AgentNodes.cppindex 0f7f84976..36cf92e68 100644--- a/fincept-qt/src/services/workflow/nodes/AgentNodes.cpp+++ b/fincept-qt/src/services/workflow/nodes/AgentNodes.cpp@@ -167,11 +167,12 @@ void register_agent_nodes(NodeRegistry& registry) {// QObject::connect with a lambda capture; the connection is// stored and disconnected after first matching result.struct Guard : QObject {+ explicit Guard(QObject* parent = nullptr) : QObject(parent) {}std::function<void(bool, QJsonValue, QString)> cb;QString req_id;QMetaObject::Connection conn;};- auto* guard = new Guard;+ auto* guard = new Guard(&svc); // parent ensures cleanup if result never firesguard->cb = cb;guard->req_id = req_id;guard->conn = QObject::connect(diff --git a/fincept-qt/src/services/workspace/WorkspaceManager.cpp b/fincept-qt/src/services/workspace/WorkspaceManager.cppindex 2b433b969..65a7a2be3 100644--- a/fincept-qt/src/services/workspace/WorkspaceManager.cpp+++ b/fincept-qt/src/services/workspace/WorkspaceManager.cpp@@ -345,9 +345,18 @@ void WorkspaceManager::apply_to_ui() {}}- // Restore window geometry — apply to primary window- if (!windows_.isEmpty() && !ws.window_geometry_base64.isEmpty())- windows_.first()->restoreGeometry(QByteArray::fromBase64(ws.window_geometry_base64.toLatin1()));+ // Restore window geometry — apply to primary window, but never clobber+ // the user's current maximized/fullscreen state. Workspace load is+ // triggered after PIN unlock and on every auth refresh; if the user+ // maximized the window before entering their PIN, blindly restoring a+ // stale saved geometry would unexpectedly shrink the window back down.+ if (!windows_.isEmpty() && !ws.window_geometry_base64.isEmpty()) {+ auto* win = windows_.first();+ const Qt::WindowStates st = win->windowState();+ const bool preserve_size = st.testFlag(Qt::WindowMaximized) || st.testFlag(Qt::WindowFullScreen);+ if (!preserve_size)+ win->restoreGeometry(QByteArray::fromBase64(ws.window_geometry_base64.toLatin1()));+ }// Navigate to active screen — apply to primary routerif (!routers_.isEmpty() && !ws.active_screen.isEmpty())diff --git a/fincept-qt/src/ui/navigation/CommandBar.cpp b/fincept-qt/src/ui/navigation/CommandBar.cppindex abdc7950d..5c89f4664 100644--- a/fincept-qt/src/ui/navigation/CommandBar.cpp+++ b/fincept-qt/src/ui/navigation/CommandBar.cpp@@ -2,6 +2,7 @@#include "core/events/EventBus.h"#include "core/keys/KeyConfigManager.h"+#include "core/session/ScreenStateManager.h"#include "network/http/HttpClient.h"#include "ui/theme/Theme.h"#include "ui/theme/ThemeManager.h"@@ -514,6 +515,7 @@ CommandBar::CommandBar(QWidget* parent) : QWidget(parent) {});connect(input_, &QLineEdit::textChanged, this, &CommandBar::on_text_changed);+ connect(input_, &QLineEdit::textChanged, this, [this](const QString&) { schedule_draft_save(); });connect(input_, &QLineEdit::returnPressed, this, &CommandBar::on_return_pressed);connect(list_, &QListWidget::itemClicked, this, &CommandBar::on_item_clicked);connect(list_, &QListWidget::itemEntered, this, &CommandBar::on_item_entered);@@ -528,6 +530,59 @@ CommandBar::CommandBar(QWidget* parent) : QWidget(parent) {[this](const ThemeTokens&) { refresh_theme(); });setup_key_actions();++ // ── Draft persistence ────────────────────────────────────────────────────+ // Debounce so every keystroke doesn't hit SQLite — 400 ms quiet period.+ draft_save_timer_ = new QTimer(this);+ draft_save_timer_->setSingleShot(true);+ draft_save_timer_->setInterval(400);+ connect(draft_save_timer_, &QTimer::timeout, this, &CommandBar::save_draft_now);++ // Restore last draft after the full UI tree is wired up so text-changed+ // logic (mode transitions, dropdown) re-establishes the right state.+ QTimer::singleShot(0, this, &CommandBar::restore_draft);+}++// ── Draft persistence (cache.db screen_state[key="command_bar"]) ────────────++void CommandBar::restore_draft() {+ const QVariantMap s = ScreenStateManager::instance().load_direct("command_bar", kDraftStateVersion);+ if (s.isEmpty())+ return;++ // Restore parser bookkeeping BEFORE setting text — on_text_changed() will+ // see the right mode_ and dock_*/active_asset_type_ values.+ active_asset_type_ = s.value("active_asset_type").toString();+ dock_primary_id_ = s.value("dock_primary_id").toString();+ dock_verb_ = s.value("dock_verb").toString();+ mode_ = static_cast<Mode>(s.value("mode", static_cast<int>(Mode::Screen)).toInt());++ const QString text = s.value("text").toString();+ if (text.isEmpty())+ return;++ // QLineEdit::setText() fires textChanged() which re-runs the parser.+ // That will rebuild the correct dropdown for the restored mode.+ input_->setText(text);+ input_->setCursorPosition(text.length());+}++void CommandBar::save_draft_now() {+ if (!input_)+ return;+ const QVariantMap s{+ {"text", input_->text()},+ {"mode", static_cast<int>(mode_)},+ {"active_asset_type", active_asset_type_},+ {"dock_primary_id", dock_primary_id_},+ {"dock_verb", dock_verb_},+ };+ ScreenStateManager::instance().save_direct("command_bar", s, kDraftStateVersion);+}++void CommandBar::schedule_draft_save() {+ if (draft_save_timer_)+ draft_save_timer_->start();}void CommandBar::setup_key_actions() {diff --git a/fincept-qt/src/ui/navigation/CommandBar.h b/fincept-qt/src/ui/navigation/CommandBar.hindex d32c78e9a..f4d29d90e 100644--- a/fincept-qt/src/ui/navigation/CommandBar.h+++ b/fincept-qt/src/ui/navigation/CommandBar.h@@ -99,6 +99,15 @@ class CommandBar : public QWidget {// ── Theme ─────────────────────────────────────────────────────────────────void refresh_theme();+ // ── Draft persistence (cache.db screen_state[key="command_bar"]) ─────────+ // Persists the in-progress command text and parser mode so a restart+ // restores exactly what the user had typed before closing.+ static constexpr int kDraftStateVersion = 1;+ QTimer* draft_save_timer_ = nullptr;+ void restore_draft();+ void save_draft_now();+ void schedule_draft_save();+// ── Dropdown helpers ───────────────────────────────────────────────────────void show_dropdown();void hide_dropdown();