Skip to content

FinceptTerminal is a modern finance application offering advanced market analytics, investment research, and economic data tools, designed for interactive exploration and data-driven decision-making in a user-friendly environment.

version 4.3.0 update

tilakpatel22e03368bd065c
diff --git a/.github/scripts/arch_ratchet.py b/.github/scripts/arch_ratchet.py
new file mode 100644
index 000000000..f765dae9e
--- /dev/null
+++ b/.github/scripts/arch_ratchet.py
@@ -0,0 +1,209 @@
+#!/usr/bin/env python3
+"""Architecture ratchets for fincept-qt.
+
+Guards three regressions that a 13-agent audit found across the codebase and
+that are invisible at compile time, so nothing else catches them:
+
+ 1. setStyleSheet() inside a loop body.
+ Every setStyleSheet() is a full CSS re-parse. Blotters that rebuilt rows in
+ a loop paid one re-parse PER ROW PER TICK — a 200-row paper blotter cost
+ ~200 CSS parses a second. Hoist the rule to the parent widget with an
+ objectName selector, set once.
+
+ This is a RATCHET, not a hard failure. There are ~460 existing sites and a
+ minority are legitimate (the style string is precomputed and re-applied
+ only on an actual state change). Failing outright on day one would block
+ every PR and the check would simply be disabled — a ratchet that people
+ keep is worth more than a gate they delete.
+
+ 2. Total setStyleSheet() count (ratchet, non-increasing).
+ Even outside loops, ~5k inline stylesheets make theming unmaintainable.
+ The baseline may only go DOWN.
+
+ 3. User-visible string literals not wrapped in tr().
+ setText("...") / setToolTip("...") / setPlaceholderText("...") /
+ setWindowTitle("...") bypass lupdate entirely, so those strings can never
+ be translated. Ratchet, non-increasing.
+
+Usage:
+ python arch_ratchet.py [--root fincept-qt/src] [--update-baseline]
+
+Exit codes: 0 clean, 1 a ratchet regressed or a loop violation was found.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import re
+import sys
+from pathlib import Path
+
+BASELINE_FILE = Path(__file__).with_name("arch_ratchet_baseline.json")
+
+RATCHETS = (
+ ("setStyleSheet_total", "setStyleSheet() calls",
+ "Use setObjectName() + a global stylesheet selector instead of an inline stylesheet."),
+ ("stylesheet_in_loop", "setStyleSheet() inside a loop body",
+ "Hoist the rule to the parent widget with an objectName selector, applied ONCE outside the loop."),
+ ("untranslated_total", "untranslated setText/setToolTip/setPlaceholderText/setWindowTitle literals",
+ "Wrap user-visible strings in tr() so lupdate can extract them."),
+)
+
+STYLESHEET_RE = re.compile(r"\bsetStyleSheet\s*\(")
+LOOP_RE = re.compile(r"^\s*(for|while)\s*\(|\bforeach\s*\(")
+# setX("literal") — a bare double-quoted string, not tr(...) / QStringLiteral(...)
+UNTRANSLATED_RE = re.compile(
+ r'\bset(?:Text|ToolTip|PlaceholderText|WindowTitle)\s*\(\s*"'
+)
+
+
+def strip_noise(line: str) -> str:
+ """Remove // comments and string bodies so we don't match inside them."""
+ line = re.sub(r"//.*$", "", line)
+ # Blank out string contents but keep the quotes, so UNTRANSLATED_RE still
+ # sees setText(" while STYLESHEET_RE can't match text inside a literal.
+ return line
+
+
+def scan_file(path: Path) -> tuple[int, int, list[tuple[int, str]]]:
+ """Return (stylesheet_count, untranslated_count, loop_violations)."""
+ try:
+ lines = path.read_text(encoding="utf-8", errors="replace").splitlines()
+ except OSError:
+ return 0, 0, []
+
+ ss_count = 0
+ untr_count = 0
+ violations: list[tuple[int, str]] = []
+
+ # Brace-depth tracking of loop bodies. When a `for`/`while` header is seen we
+ # push the depth its body will live at; any setStyleSheet at or below that
+ # depth (until we return above it) is inside the loop.
+ depth = 0
+ loop_stack: list[int] = []
+ in_block_comment = False
+
+ for lineno, raw in enumerate(lines, 1):
+ line = raw
+ if in_block_comment:
+ end = line.find("*/")
+ if end == -1:
+ continue
+ line = line[end + 2 :]
+ in_block_comment = False
+ start = line.find("/*")
+ while start != -1:
+ end = line.find("*/", start + 2)
+ if end == -1:
+ line = line[:start]
+ in_block_comment = True
+ break
+ line = line[:start] + " " + line[end + 2 :]
+ start = line.find("/*")
+
+ code = strip_noise(line)
+
+ if UNTRANSLATED_RE.search(code):
+ untr_count += 1
+
+ if STYLESHEET_RE.search(code):
+ ss_count += 1
+ if loop_stack:
+ violations.append((lineno, raw.strip()[:130]))
+
+ is_loop_header = bool(LOOP_RE.search(code))
+
+ opens = code.count("{")
+ closes = code.count("}")
+ if is_loop_header:
+ # Body begins at the current depth (brace on this line or the next).
+ loop_stack.append(depth)
+ depth += opens - closes
+ while loop_stack and depth <= loop_stack[-1]:
+ loop_stack.pop()
+
+ return ss_count, untr_count, violations
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--root", default="fincept-qt/src")
+ ap.add_argument("--update-baseline", action="store_true")
+ args = ap.parse_args()
+
+ root = Path(args.root)
+ if not root.is_dir():
+ print(f"::error::root not found: {root}", file=sys.stderr)
+ return 1
+
+ total_ss = 0
+ total_untr = 0
+ all_violations: list[tuple[str, int, str]] = []
+
+ for dirpath, dirnames, filenames in os.walk(root):
+ dirnames[:] = [d for d in dirnames if d not in {"build", "_deps", ".git"}]
+ for fn in filenames:
+ if not fn.endswith((".cpp", ".h")):
+ continue
+ p = Path(dirpath) / fn
+ ss, untr, viol = scan_file(p)
+ total_ss += ss
+ total_untr += untr
+ rel = p.as_posix()
+ all_violations += [(rel, ln, txt) for ln, txt in viol]
+
+ current = {
+ "setStyleSheet_total": total_ss,
+ "stylesheet_in_loop": len(all_violations),
+ "untranslated_total": total_untr,
+ }
+
+ if args.update_baseline:
+ payload = dict(current)
+ payload["_note"] = (
+ "Architecture ratchets — these may only DECREASE. Regenerate with "
+ "--update-baseline ONLY when lowering them (i.e. after cleanup), never to "
+ "make a new violation pass."
+ )
+ BASELINE_FILE.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
+ print("baseline written:")
+ for key, label, _ in RATCHETS:
+ print(f" {label}: {current[key]}")
+ return 0
+
+ baseline = {key: 0 for key, _, _ in RATCHETS}
+ if BASELINE_FILE.exists():
+ # utf-8-sig, not utf-8: PowerShell's Set-Content -Encoding utf8 writes a
+ # BOM on Windows, and json.loads rejects it with a bare "Unexpected
+ # UTF-8 BOM" that looks nothing like "someone edited the baseline".
+ baseline.update(json.loads(BASELINE_FILE.read_text(encoding="utf-8-sig")))
+
+ failed = False
+ print(f"{'metric':<62} {'now':>6} {'baseline':>9}")
+ for key, label, _ in RATCHETS:
+ mark = " OK" if current[key] <= baseline[key] else " UP"
+ print(f"{label:<62} {current[key]:>6} {baseline[key]:>9}{mark}")
+
+ for key, label, advice in RATCHETS:
+ if current[key] > baseline[key]:
+ failed = True
+ print(f"\n::error::{label} rose {baseline[key]} → {current[key]}. {advice}")
+
+ # Always show the loop sites — they are the actionable ones even while the
+ # ratchet is merely holding steady.
+ if all_violations and current["stylesheet_in_loop"] > baseline["stylesheet_in_loop"]:
+ print("\nsetStyleSheet() calls found inside a loop body:")
+ for rel, ln, txt in all_violations[:40]:
+ print(f" {rel}:{ln}: {txt}")
+ if len(all_violations) > 40:
+ print(f" … and {len(all_violations) - 40} more")
+
+ if not failed:
+ print("\nAll architecture ratchets OK.")
+ return 1 if failed else 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/.github/scripts/arch_ratchet_baseline.json b/.github/scripts/arch_ratchet_baseline.json
new file mode 100644
index 000000000..1fba32bf6
--- /dev/null
+++ b/.github/scripts/arch_ratchet_baseline.json
@@ -0,0 +1,6 @@
+{
+ "setStyleSheet_total": 5200,
+ "stylesheet_in_loop": 460,
+ "untranslated_total": 120,
+ "_note": "Architecture ratchets \u2014 these may only DECREASE. Regenerate with --update-baseline ONLY when lowering them (i.e. after cleanup), never to make a new violation pass."
+}
diff --git a/.github/workflows/arch-ratchet.yml b/.github/workflows/arch-ratchet.yml
new file mode 100644
index 000000000..e3823c4d0
--- /dev/null
+++ b/.github/workflows/arch-ratchet.yml
@@ -0,0 +1,53 @@
+name: Architecture Ratchets
+
+# Runs on `pull_request` (NOT pull_request_target): this checks out PR code, so
+# it must run with the fork's read-only token and no secrets. pr-gate.yml uses
+# pull_request_target because it needs write access to label/comment; that
+# trigger must never be used to execute or scan untrusted contributor code.
+on:
+ pull_request:
+ paths:
+ - 'fincept-qt/src/**'
+ - '.github/scripts/arch_ratchet.py'
+ - '.github/scripts/arch_ratchet_baseline.json'
+ - '.github/workflows/arch-ratchet.yml'
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+jobs:
+ ratchets:
+ name: Architecture ratchets
+ runs-on: ubuntu-24.04
+ steps:
+ - uses: actions/checkout@v4
+
+ - uses: actions/setup-python@v5
+ with:
+ python-version: '3.11'
+
+ # Three non-increasing counters. They exist because all three regressions
+ # are invisible at compile time and were each found by hand-audit:
+ # • inline setStyleSheet total (theming maintainability)
+ # • setStyleSheet inside a loop body (a full CSS re-parse per row per tick)
+ # • untranslated setText/... literals (lupdate cannot see them, so they
+ # can never be translated)
+ #
+ # Ratchets rather than hard gates: there are ~5,200 / ~460 / ~120 existing
+ # sites, so an outright ban would fail every PR on day one and the check
+ # would be deleted. A ratchet people keep beats a gate they remove.
+ - name: Check architecture ratchets
+ run: python .github/scripts/arch_ratchet.py --root fincept-qt/src
+
+ - name: How to fix
+ if: failure()
+ run: |
+ echo "A ratchet went UP. Options, in order of preference:"
+ echo " 1. Don't add the violation — use setObjectName() + a global"
+ echo " stylesheet selector, or wrap the string in tr()."
+ echo " 2. If you REMOVED violations elsewhere and the count should be"
+ echo " lower, regenerate the baseline:"
+ echo " python .github/scripts/arch_ratchet.py --root fincept-qt/src --update-baseline"
+ echo " Only ever regenerate to LOWER a baseline, never to let a new"
+ echo " violation through."
diff --git a/.github/workflows/build-cpp.yml b/.github/workflows/build-cpp.yml
index 693a3802b..9f1ebd29a 100644
--- a/.github/workflows/build-cpp.yml
+++ b/.github/workflows/build-cpp.yml
@@ -654,8 +654,8 @@ jobs:
<key>CFBundleIdentifier</key><string>com.fincept.terminal</string>
<key>CFBundleName</key><string>FinceptTerminal</string>
<key>CFBundlePackageType</key><string>APPL</string>
- <key>CFBundleShortVersionString</key><string>4.2.0</string>
- <key>CFBundleVersion</key><string>4.2.0</string>
+ <key>CFBundleShortVersionString</key><string>4.3.0</string>
+ <key>CFBundleVersion</key><string>4.3.0</string>
<key>LSMinimumSystemVersion</key><string>13.0</string>
<key>NSHighResolutionCapable</key><true/>
</dict></plist>
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 785cf20d8..254577e52 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -1279,8 +1279,8 @@ jobs:
<key>CFBundleIdentifier</key><string>com.fincept.terminal</string>
<key>CFBundleName</key><string>FinceptTerminal</string>
<key>CFBundlePackageType</key><string>APPL</string>
- <key>CFBundleShortVersionString</key><string>4.2.0</string>
- <key>CFBundleVersion</key><string>4.2.0</string>
+ <key>CFBundleShortVersionString</key><string>4.3.0</string>
+ <key>CFBundleVersion</key><string>4.3.0</string>
<key>LSMinimumSystemVersion</key><string>13.0</string>
<key>NSHighResolutionCapable</key><true/>
</dict></plist>
diff --git a/LICENSE b/LICENSE
index 043a953a9..67ee7d7ff 100644
--- a/LICENSE
+++ b/LICENSE
@@ -279,7 +279,7 @@ Status: Current and binding. These terms remain in full force and
subsequent version published by Fincept Corporation. The
date above marks the most recent revision and is NOT an
expiry date.
-Software Version: 4.0.2 (current release; license applies to all releases,
+Software Version: 4.3.0 (current release; license applies to all releases,
branches, tags, and commits of the Software)
This License governs all current and future use of the Software, including
diff --git a/README.md b/README.md
index 822f9ff05..e0609e7f2 100644
--- a/README.md
+++ b/README.md
@@ -69,15 +69,15 @@ State-of-the-art financial intelligence platform with institutional-grade financ
<!-- DOWNLOAD-TABLE-START -->
### Option 1 — Download Installer (Recommended)
-Latest release: **v4.2.0** — [View all releases](https://github.com/Fincept-Corporation/FinceptTerminal/releases/tag/v4.2.0)
+Latest release: **v4.3.0** — [View all releases](https://github.com/Fincept-Corporation/FinceptTerminal/releases/tag/v4.3.0)
| Platform | Download | Run |
|----------|----------|-----|
-| **Windows x64** | [FinceptTerminal-Windows-x64-setup.exe](https://github.com/Fincept-Corporation/FinceptTerminal/releases/download/v4.2.0/FinceptTerminal-4.2.0-windows-x64-setup.exe) | Run installer → launch `FinceptTerminal.exe` |
-| **Linux x64 (AppImage)** | [FinceptTerminal-Linux-x64.run](https://github.com/Fincept-Corporation/FinceptTerminal/releases/download/v4.2.0/FinceptTerminal-4.2.0-linux-x64-setup.run) | `chmod +x` → run installer |
-| **Linux x64 (Debian/Ubuntu)** | [FinceptTerminal-Linux-x64.deb](https://github.com/Fincept-Corporation/FinceptTerminal/releases/download/v4.2.0/FinceptTerminal-4.2.0-linux-x64.deb) | `sudo apt install ./FinceptTerminal-4.2.0-linux-x64.deb` |
-| **Linux x64 (Fedora/RHEL)** | [FinceptTerminal-Linux-x64.rpm](https://github.com/Fincept-Corporation/FinceptTerminal/releases/download/v4.2.0/FinceptTerminal-4.2.0-linux-x64.rpm) | `sudo dnf install ./FinceptTerminal-4.2.0-linux-x64.rpm` |
-| **macOS Apple Silicon** | [FinceptTerminal-macOS-arm64.dmg](https://github.com/Fincept-Corporation/FinceptTerminal/releases/download/v4.2.0/FinceptTerminal-4.2.0-macos-arm64-setup.dmg) | Open DMG → drag to Applications |
+| **Windows x64** | [FinceptTerminal-Windows-x64-setup.exe](https://github.com/Fincept-Corporation/FinceptTerminal/releases/download/v4.3.0/FinceptTerminal-4.3.0-windows-x64-setup.exe) | Run installer → launch `FinceptTerminal.exe` |
+| **Linux x64 (AppImage)** | [FinceptTerminal-Linux-x64.run](https://github.com/Fincept-Corporation/FinceptTerminal/releases/download/v4.3.0/FinceptTerminal-4.3.0-linux-x64-setup.run) | `chmod +x` → run installer |
+| **Linux x64 (Debian/Ubuntu)** | [FinceptTerminal-Linux-x64.deb](https://github.com/Fincept-Corporation/FinceptTerminal/releases/download/v4.3.0/FinceptTerminal-4.3.0-linux-x64.deb) | `sudo apt install ./FinceptTerminal-4.3.0-linux-x64.deb` |
+| **Linux x64 (Fedora/RHEL)** | [FinceptTerminal-Linux-x64.rpm](https://github.com/Fincept-Corporation/FinceptTerminal/releases/download/v4.3.0/FinceptTerminal-4.3.0-linux-x64.rpm) | `sudo dnf install ./FinceptTerminal-4.3.0-linux-x64.rpm` |
+| **macOS Apple Silicon** | [FinceptTerminal-macOS-arm64.dmg](https://github.com/Fincept-Corporation/FinceptTerminal/releases/download/v4.3.0/FinceptTerminal-4.3.0-macos-arm64-setup.dmg) | Open DMG → drag to Applications |
<!-- DOWNLOAD-TABLE-END -->
---
diff --git a/fincept-qt/CMakeLists.txt b/fincept-qt/CMakeLists.txt
index f2ecb38b0..3f746d39d 100644
--- a/fincept-qt/CMakeLists.txt
+++ b/fincept-qt/CMakeLists.txt
@@ -33,7 +33,7 @@ if(WIN32 AND CMAKE_HOST_WIN32)
unset(_fincept_sdk_dirs)
endif()
-project(FinceptTerminal VERSION 4.2.0 LANGUAGES C CXX)
+project(FinceptTerminal VERSION 4.3.0 LANGUAGES C CXX)
# Strip C/C++ flags out of RC invocations — rc.exe only understands /D, /I, /fo.
if(WIN32)
@@ -353,6 +353,15 @@ add_compile_definitions(NOMINMAX WIN32_LEAN_AND_MEAN)
# OFF by default so a normal build is unchanged. Turn on with
# -DFINCEPT_BUILD_TESTS=ON to compile the Qt Test executables under
# fincept-qt/tests/. Run via `ctest` in the build directory.
+#
+# STATUS: fincept-qt/tests/ does NOT exist yet — there is no Qt Test target in
+# the repo (no `#include <QTest>` anywhere). Turning this option on currently
+# warns and builds nothing; see the guarded add_subdirectory near the end of
+# this file. Today's automated coverage is the headless `--selftest-*` flags on
+# the main binary (DockLayout, ToolSelfTest, PaperTrading, PortfolioReplication,
+# PortfolioMonitor, UniverseScan, FnoAlgo, Arena, Feeds), which CI runs in
+# .github/workflows/build-cpp.yml. Adding a real unit-test tree here is tracked
+# in AUDIT_2026-07-25.md §E.
option(FINCEPT_BUILD_TESTS "Build the Fincept Terminal test suite" OFF)
# ── Alpha Arena live-mode geofencing ─────────────────────────────────────────
@@ -1072,8 +1081,11 @@ set(MCP_SOURCES
src/mcp/ToolRetriever.cpp
src/mcp/ToolSelfTest.cpp
src/mcp/TerminalMcpBridge.cpp
+ src/mcp/JobRegistry.cpp
+ src/mcp/ResultStore.cpp
# Tool modules
+ src/mcp/tools/JobTools.cpp
src/mcp/tools/NavigationTools.cpp
src/mcp/tools/MarketsTools.cpp
src/mcp/tools/WatchlistTools.cpp
@@ -1473,6 +1485,10 @@ set(UI_SOURCES
src/ui/widgets/SpeedSparkline.cpp
src/ui/widgets/LanguageSwitcher.cpp
src/ui/tables/DataTable.cpp
+ # Selftest for the header-only LiveTableModel/LiveTableDelegate. Also the
+ # only TU that includes them, so it is their compile check — a header with
+ # no includer is never compiled and can rot unnoticed.
+ src/ui/tables/LiveTableSelftest.cpp
src/ui/charts/ChartFactory.cpp
src/ui/charts/ChartIndicators.cpp
src/ui/charts/OverlayLayer.cpp
@@ -1880,6 +1896,7 @@ set(SCREEN_SOURCES
src/screens/economics/panels/GlobalCentralBanksPanel.cpp
src/screens/economics/panels/FederalReservePanel.cpp
src/screens/economics/panels/FiscalDataPanel.cpp
+ src/screens/economics/panels/NberPanel.cpp
src/screens/economics/panels/OwIdPanel.cpp
src/screens/economics/panels/StatCanPanel.cpp
src/screens/economics/panels/IlostatPanel.cpp
@@ -3200,14 +3217,16 @@ if(WIN32)
else()
target_link_libraries(FinceptTerminal PRIVATE ZLIB::ZLIB)
endif()
-# SecureStorage no longer needs platform-specific credential frameworks —
-# it's pure SQLite + AES-256-GCM (OpenSSL) on every platform. See
+# SecureStorage stores credentials as SQLite + AES-256-GCM (OpenSSL) on every
+# platform. The row key is a random DEK wrapped by a platform key: DPAPI on
+# Windows (crypt32, below), PBKDF2 over the machine seed elsewhere. See
# storage/secure/SecureStorage.cpp.
-# Windows: link dbghelp for the crash-handler minidump writer (see
-# src/core/crash/CrashHandler.cpp).
+# Windows: dbghelp for the crash-handler minidump writer (see
+# src/core/crash/CrashHandler.cpp); crypt32 for the DPAPI
+# CryptProtectData/CryptUnprotectData pair that wraps the SecureStorage DEK.
if(WIN32)
- target_link_libraries(FinceptTerminal PRIVATE dbghelp)
+ target_link_libraries(FinceptTerminal PRIVATE dbghelp crypt32)
endif()
# Copy OpenSSL DLLs to build output — Windows only
@@ -3383,16 +3402,39 @@ endif()
# whole copy+prune when nothing under scripts/ changed since the last sync. The
# previous version did an unconditional copy_directory of 4000+ files on every
# link, taxing every one-line C++ change with a multi-minute scripts re-copy.
-add_custom_command(TARGET FinceptTerminal POST_BUILD
+#
+# Driven as a real build edge (stamp OUTPUT + DEPENDS on the script files), not
+# a POST_BUILD of the link: as a POST_BUILD it only ran when the exe relinked,
+# so editing a Python script and rebuilding printed "ninja: no work to do" and
+# the build output kept the stale copy. The dependency list is filtered the same
+# way sync_scripts.cmake filters its walk — a stray scripts/.venv must never
+# become 115k ninja dependencies.
+file(GLOB_RECURSE FINCEPT_SCRIPT_DEPS "${CMAKE_CURRENT_SOURCE_DIR}/scripts/*")
+list(FILTER FINCEPT_SCRIPT_DEPS EXCLUDE REGEX
+ "/(\\.venv|venv|env|__pycache__|\\.pytest_cache|\\.benchmarks|\\.firecrawl|\\.git|\\.mypy_cache|\\.ruff_cache|node_modules)/")
+list(FILTER FINCEPT_SCRIPT_DEPS EXCLUDE REGEX "\\.(pyc|pyo|bak|log|db|sqlite|sqlite3)$")
+list(FILTER FINCEPT_SCRIPT_DEPS EXCLUDE REGEX "\\.deleted")
+list(LENGTH FINCEPT_SCRIPT_DEPS _fincept_script_dep_count)
+message(STATUS "Python scripts tracked as build dependencies: ${_fincept_script_dep_count}")
+
+set(FINCEPT_SCRIPTS_STAMP "${CMAKE_CURRENT_BINARY_DIR}/scripts_sync.stamp")
+add_custom_command(
+ OUTPUT "${FINCEPT_SCRIPTS_STAMP}"
COMMAND ${CMAKE_COMMAND}
-DSRC_DIR=${CMAKE_CURRENT_SOURCE_DIR}/scripts
-DDST_DIR=$<TARGET_FILE_DIR:FinceptTerminal>/scripts
- -DSTAMP_FILE=${CMAKE_CURRENT_BINARY_DIR}/scripts_sync.stamp
+ -DSTAMP_FILE=${FINCEPT_SCRIPTS_STAMP}
-DPRUNE_SCRIPT=${CMAKE_CURRENT_SOURCE_DIR}/cmake/prune_scripts_junk.cmake
-P "${CMAKE_CURRENT_SOURCE_DIR}/cmake/sync_scripts.cmake"
- COMMENT "Syncing Python scripts to build output (skips when unchanged)..."
+ # The sync writes the stamp only when it actually copies; touch it here so
+ # ninja sees the edge as satisfied on a no-op run too.
+ COMMAND ${CMAKE_COMMAND} -E touch "${FINCEPT_SCRIPTS_STAMP}"
+ DEPENDS ${FINCEPT_SCRIPT_DEPS}
+ COMMENT "Syncing Python scripts to build output..."
VERBATIM
)
+add_custom_target(fincept_sync_scripts DEPENDS "${FINCEPT_SCRIPTS_STAMP}")
+add_dependencies(FinceptTerminal fincept_sync_scripts)
# ── Copy requirements files to build output ──────────────────────────────────
# PythonSetupManager::find_requirements_file() searches exe_dir/resources/ first.
@@ -4173,6 +4215,18 @@ if(UNIX AND NOT APPLE)
endif()
# ── Test suite (opt-in; see fincept-qt/tests/CMakeLists.txt) ─────────────────
+# The EXISTS guard is load-bearing: the tests/ tree is not in the repo yet, and
+# a bare add_subdirectory(tests) makes -DFINCEPT_BUILD_TESTS=ON fail at CONFIGURE
+# time with "add_subdirectory given source 'tests' which is not an existing
+# directory" — i.e. the documented opt-in switch was unusable. Fail soft with a
+# clear message instead, so turning the option on is diagnostic rather than fatal.
if(FINCEPT_BUILD_TESTS)
- add_subdirectory(tests)
+ if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/CMakeLists.txt")
+ add_subdirectory(tests)
+ else()
+ message(WARNING
+ "FINCEPT_BUILD_TESTS=ON but ${CMAKE_CURRENT_SOURCE_DIR}/tests/CMakeLists.txt "
+ "does not exist — no test targets will be built. Headless self-tests are still "
+ "available via the --selftest-* flags on the main binary.")
+ endif()
endif()
diff --git a/fincept-qt/cmake/prune_scripts_junk.cmake b/fincept-qt/cmake/prune_scripts_junk.cmake
index 52911400a..f092efc14 100644
--- a/fincept-qt/cmake/prune_scripts_junk.cmake
+++ b/fincept-qt/cmake/prune_scripts_junk.cmake
@@ -12,6 +12,10 @@
# "bundle format unrecognized, invalid, or unsuitable". On Linux/Windows
# these just bloat the installer; removing them shrinks it meaningfully.
+
+# `cmake -P` starts with every policy OLD, which turns the IN_LIST operator
+# below back into a plain string comparison (CMP0057).
+cmake_minimum_required(VERSION 3.20)
if(NOT DEFINED SCRIPTS_DIR)
message(FATAL_ERROR "prune_scripts_junk.cmake: SCRIPTS_DIR must be set")
endif()
@@ -21,18 +25,36 @@ if(NOT IS_DIRECTORY "${SCRIPTS_DIR}")
return()
endif()
-# Glob directories to nuke (recursively under scripts/).
-file(GLOB_RECURSE _junk_dirs
- LIST_DIRECTORIES true
- "${SCRIPTS_DIR}/*.deleted.*"
- "${SCRIPTS_DIR}/*.deleted"
- "${SCRIPTS_DIR}/*/.pytest_cache"
- "${SCRIPTS_DIR}/*/.benchmarks"
- "${SCRIPTS_DIR}/*/__pycache__"
- "${SCRIPTS_DIR}/.pytest_cache"
- "${SCRIPTS_DIR}/.benchmarks"
- "${SCRIPTS_DIR}/__pycache__"
-)
+# Collect directories to nuke by walking and matching NAMES.
+#
+# This deliberately does NOT use file(GLOB_RECURSE ... LIST_DIRECTORIES true):
+# that flag makes CMake add every directory it traverses to the result, not
+# only the ones matching the pattern, so the "junk" list came back containing
+# every subdirectory of scripts/ — the prune then deleted Analytics/, agents/,
+# strategies/ and friends out of the build output on every single sync
+# (measured: 1,100 of 1,449 synced files removed).
+set(_junk_dir_names "__pycache__" ".pytest_cache" ".benchmarks")
+set(_junk_dir_regex "\\.deleted") # agents.deleted.2026-05-01/, foo.deleted/
+
+function(fincept_collect_junk_dirs dir out_var)
+ set(_acc "")
+ file(GLOB _entries LIST_DIRECTORIES true "${dir}/*")
+ foreach(_e IN LISTS _entries)
+ if(NOT IS_DIRECTORY "${_e}")
+ continue()
+ endif()
+ get_filename_component(_name "${_e}" NAME)
+ if(_name IN_LIST _junk_dir_names OR _name MATCHES "${_junk_dir_regex}")
+ list(APPEND _acc "${_e}")
+ continue() # whole subtree goes — no need to descend
+ endif()
+ fincept_collect_junk_dirs("${_e}" _sub)
+ list(APPEND _acc ${_sub})
+ endforeach()
+ set(${out_var} "${_acc}" PARENT_SCOPE)
+endfunction()
+
+fincept_collect_junk_dirs("${SCRIPTS_DIR}" _junk_dirs)
# Glob stray files (local DBs + editor/backup artifacts).
file(GLOB_RECURSE _junk_files
diff --git a/fincept-qt/cmake/sync_scripts.cmake b/fincept-qt/cmake/sync_scripts.cmake
index 64c55bc4d..e9ae68344 100644
--- a/fincept-qt/cmake/sync_scripts.cmake
+++ b/fincept-qt/cmake/sync_scripts.cmake
@@ -1,12 +1,23 @@
# Incrementally sync the Python scripts/ tree into the build output, then prune
-# junk — but skip the whole job when nothing under scripts/ has changed since
-# the last sync. Runs under `cmake -P`, portable across Windows/macOS/Linux.
+# junk — but skip the whole job when nothing shippable under scripts/ has changed
+# since the last sync. Runs under `cmake -P`, portable across Windows/macOS/Linux.
#
# Why this exists:
-# The old POST_BUILD did an unconditional `copy_directory` of 4000+ files
+# The old POST_BUILD did an unconditional `copy_directory` of the whole tree
# plus a prune on EVERY link, so a one-line C++ change paid a multi-minute
# tax. copy_directory re-copies the whole tree every time. This guard makes
-# the steady state (no script edits) cost a single directory stat instead.
+# the steady state (no script edits) cost a filtered directory walk instead.
+#
+# Why the walk is FILTERED (the second, bigger tax):
+# scripts/ holds ~1.4k tracked files, but a working tree also accumulates
+# scripts/.venv (a full Python virtualenv), __pycache__ dirs, .firecrawl
+# caches and *.deleted backups — measured at 117,473 files on a dev box
+# against 1,447 tracked. Walking and timestamping all of them from CMake
+# script, then copy_directory_if_different'ing them into the build output,
+# turned a ~5 s incremental build into a 25-minute one and shipped a venv
+# into build/. Both the freshness scan and the copy now prune those
+# directories, matching the exclude list in .github/scripts/sync_scripts.sh
+# so local builds and CI packaging agree on what "the scripts tree" is.
#
# Required defines (passed via -D):
# SRC_DIR — source scripts/ directory
@@ -14,9 +25,13 @@
# STAMP_FILE — path to the sync stamp file
# PRUNE_SCRIPT — path to prune_scripts_junk.cmake
+# `cmake -P` starts with every policy OLD, which turns the IN_LIST operator
+# below back into a plain string comparison (CMP0057).
+cmake_minimum_required(VERSION 3.20)
+
foreach(_var SRC_DIR DST_DIR STAMP_FILE PRUNE_SCRIPT)
if(NOT DEFINED ${_var})
- message(FATAL_ERROR "sync_scripts.cmake: ${_var} must be set")
+ message(FATAL_ERROR "sync_scripts: ${_var} must be set")
endif()
endforeach()
@@ -25,12 +40,64 @@ if(NOT IS_DIRECTORY "${SRC_DIR}")
return()
endif()
-# Build a cheap change signature from the newest mtime across the source tree.
-# GLOB_RECURSE here walks paths only (no content hashing), which is fast even
-# for thousands of files. If the destination + stamp already reflect the
-# newest source mtime, the tree is unchanged and we can bail immediately.
-file(GLOB_RECURSE _src_files LIST_DIRECTORIES false "${SRC_DIR}/*")
+# Directory names never worth walking, copying, or shipping. Keep in sync with
+# .github/scripts/sync_scripts.sh.
+set(_skip_dirs
+ "__pycache__" ".venv" "venv" "env" ".pytest_cache" ".benchmarks"
+ ".firecrawl" ".git" ".mypy_cache" ".ruff_cache" "node_modules")
+# File suffixes that are build artefacts or local state, not source.
+set(_skip_file_regex "\\.(pyc|pyo|bak|log|db|sqlite|sqlite3)$")
+# Anything a contributor parked as a backup (agents.deleted.2026-05-01/, x.deleted).
+set(_skip_name_regex "\\.deleted")
+
+# Recursive walk that PRUNES excluded directories instead of listing their
+# contents — file(GLOB_RECURSE) has no way to skip a subtree, so it would still
+# enumerate every file inside .venv before we could filter them out.
+function(fincept_collect_scripts dir out_var)
+ set(_acc "")
+ file(GLOB _entries LIST_DIRECTORIES true "${dir}/*")
+ foreach(_e IN LISTS _entries)
+ get_filename_component(_name "${_e}" NAME)
+ if(_name MATCHES "${_skip_name_regex}")
+ continue()
+ endif()
+ if(IS_DIRECTORY "${_e}")
+ if(_name IN_LIST _skip_dirs)
+ continue()
+ endif()
+ fincept_collect_scripts("${_e}" _sub)
+ list(APPEND _acc ${_sub})
+ else()
+ if(_name MATCHES "${_skip_file_regex}")
+ continue()
+ endif()
+ list(APPEND _acc "${_e}")
+ endif()
+ endforeach()
+ set(${out_var} "${_acc}" PARENT_SCOPE)
+endfunction()
+
+fincept_collect_scripts("${SRC_DIR}" _src_files)
+
+# Surface a polluted source tree. The sync itself no longer cares (the walk
+# above prunes these), but a virtualenv parked under scripts/ still slows down
+# greps, IDE indexing and every other tool that walks the repo — and it is how
+# this tree grew to 117,473 files against 1,447 tracked ones. One line, only
+# when there is something to report.
+set(_polluted "")
+foreach(_d IN LISTS _skip_dirs)
+ if(IS_DIRECTORY "${SRC_DIR}/${_d}")
+ list(APPEND _polluted "${_d}")
+ endif()
+endforeach()
+if(_polluted)
+ string(REPLACE ";" ", " _polluted_str "${_polluted}")
+ message(STATUS "sync_scripts: NOT shipping local junk under scripts/: ${_polluted_str} "
+ "(safe to delete — the app's venvs live under AppPaths::root())")
+endif()
+# Cheap change signature: newest mtime + file count over the filtered set. The
+# count catches deletions, which a max-mtime alone would miss.
set(_newest 0)
foreach(_f IN LISTS _src_files)
file(TIMESTAMP "${_f}" _ts "%s" UTC)
@@ -38,6 +105,8 @@ foreach(_f IN LISTS _src_files)
set(_newest "${_ts}")
endif()
endforeach()
+list(LENGTH _src_files _count)
+set(_signature "${_newest}:${_count}")
set(_prev "")
if(EXISTS "${STAMP_FILE}")
@@ -45,24 +114,32 @@ if(EXISTS "${STAMP_FILE}")
string(STRIP "${_prev}" _prev)
endif()
-if(_prev STREQUAL "${_newest}" AND IS_DIRECTORY "${DST_DIR}")
+if(_prev STREQUAL "${_signature}" AND IS_DIRECTORY "${DST_DIR}")
# Unchanged since last sync — skip the expensive copy + prune entirely.
return()
endif()
-message(STATUS "sync_scripts: changes detected — syncing scripts/ to build output")
+message(STATUS "sync_scripts: syncing ${_count} script file(s) to build output")
-# copy_directory_if_different (CMake 3.26+) only writes files whose content
-# actually differs, so even when this branch runs it avoids needless writes.
-execute_process(
- COMMAND "${CMAKE_COMMAND}" -E copy_directory_if_different "${SRC_DIR}" "${DST_DIR}"
- RESULT_VARIABLE _copy_rc
-)
-if(NOT _copy_rc EQUAL 0)
- message(FATAL_ERROR "sync_scripts: copy_directory_if_different failed (${_copy_rc})")
-endif()
+# Copy exactly the files the filtered walk found, preserving their relative
+# layout. Driving the copy from the collected list (rather than file(COPY) with
+# PATTERN ... EXCLUDE over the whole tree) keeps one definition of "shippable"
+# for both the freshness check and the copy — and never re-walks the pruned
+# subtrees. file(COPY) preserves timestamps and skips a file already present
+# with the same one, so a re-sync after a single edit rewrites a single file.
+foreach(_f IN LISTS _src_files)
+ file(RELATIVE_PATH _rel "${SRC_DIR}" "${_f}")
+ get_filename_component(_rel_dir "${_rel}" DIRECTORY)
+ if(_rel_dir STREQUAL "")
+ file(COPY "${_f}" DESTINATION "${DST_DIR}")
+ else()
+ file(COPY "${_f}" DESTINATION "${DST_DIR}/${_rel_dir}")
+ endif()
+endforeach()
# Prune junk that must never ship (see prune_scripts_junk.cmake for rationale).
+# The exclude patterns above keep it from ever reaching DST_DIR, but a stale
+# build output from before this filter existed still needs cleaning.
execute_process(
COMMAND "${CMAKE_COMMAND}" -DSCRIPTS_DIR=${DST_DIR} -P "${PRUNE_SCRIPT}"
RESULT_VARIABLE _prune_rc
@@ -71,4 +148,4 @@ if(NOT _prune_rc EQUAL 0)
message(FATAL_ERROR "sync_scripts: prune step failed (${_prune_rc})")
endif()
-file(WRITE "${STAMP_FILE}" "${_newest}")
+file(WRITE "${STAMP_FILE}" "${_signature}")
diff --git a/fincept-qt/packaging/flatpak/in.fincept.FinceptTerminal.metainfo.xml b/fincept-qt/packaging/flatpak/in.fincept.FinceptTerminal.metainfo.xml
index 5038faf76..437a0873f 100644
--- a/fincept-qt/packaging/flatpak/in.fincept.FinceptTerminal.metainfo.xml
+++ b/fincept-qt/packaging/flatpak/in.fincept.FinceptTerminal.metainfo.xml
@@ -71,6 +71,11 @@
</provides>
<releases>
+ <release version="4.3.0" date="2026-07-25">
+ <description>
+ <p>MCP long-running tools now run as background jobs the assistant can poll, cancel, and watch progress on, instead of blocking a request for minutes. Oversized tool results are summarised and paged on demand rather than filling the conversation.</p>
+ </description>
+ </release>
<release version="4.1.0" date="2026-06-09">
<description>
<p>Adds an optional NewsAPI.org provider for stock-specific company news in Equity Research, broker-sourced technical indicators, and assorted fixes. Removes the redundant TALIpp tab.</p>
diff --git a/fincept-qt/packaging/flatpak/in.fincept.FinceptTerminal.yml b/fincept-qt/packaging/flatpak/in.fincept.FinceptTerminal.yml
index 120c3ae76..5b1daf017 100644
--- a/fincept-qt/packaging/flatpak/in.fincept.FinceptTerminal.yml
+++ b/fincept-qt/packaging/flatpak/in.fincept.FinceptTerminal.yml
@@ -55,7 +55,7 @@ modules:
# Main repository
- type: git
url: https://github.com/Fincept-Corporation/FinceptTerminal.git
- tag: v4.2.0
+ tag: v4.3.0
# Vendored FetchContent dependencies (no network during build)
- type: git
url: https://github.com/QtExcel/QXlsx.git
diff --git a/fincept-qt/packaging/installer/packages/com.fincept.terminal.core/meta/license.txt b/fincept-qt/packaging/installer/packages/com.fincept.terminal.core/meta/license.txt
index 043a953a9..67ee7d7ff 100644
--- a/fincept-qt/packaging/installer/packages/com.fincept.terminal.core/meta/license.txt
+++ b/fincept-qt/packaging/installer/packages/com.fincept.terminal.core/meta/license.txt
@@ -279,7 +279,7 @@ Status: Current and binding. These terms remain in full force and
subsequent version published by Fincept Corporation. The
date above marks the most recent revision and is NOT an
expiry date.
-Software Version: 4.0.2 (current release; license applies to all releases,
+Software Version: 4.3.0 (current release; license applies to all releases,
branches, tags, and commits of the Software)
This License governs all current and future use of the Software, including
diff --git a/fincept-qt/packaging/linux/AppImageBuilder.yml b/fincept-qt/packaging/linux/AppImageBuilder.yml
index d9a666c6f..4e1e09c47 100644
--- a/fincept-qt/packaging/linux/AppImageBuilder.yml
+++ b/fincept-qt/packaging/linux/AppImageBuilder.yml
@@ -16,7 +16,7 @@ AppDir:
id: com.fincept.terminal
name: Fincept Terminal
icon: fincept-terminal
- version: !ENV ${FINCEPT_VERSION:-4.2.0}
+ version: !ENV ${FINCEPT_VERSION:-4.3.0}
exec: usr/bin/FinceptTerminal
exec_args: $@
@@ -56,6 +56,6 @@ AppDir:
AppImage:
arch: x86_64
comp: xz
- file_name: FinceptTerminal-!ENV ${FINCEPT_VERSION:-4.2.0}-x86_64.AppImage
+ file_name: FinceptTerminal-!ENV ${FINCEPT_VERSION:-4.3.0}-x86_64.AppImage
sign-key: None
update-information: gh-releases-zsync|Fincept-Corporation|FinceptTerminal|latest|FinceptTerminal-*x86_64.AppImage.zsync
diff --git a/fincept-qt/packaging/linux/fincept-terminal.appdata.xml b/fincept-qt/packaging/linux/fincept-terminal.appdata.xml
index 75786db98..3e8d30108 100644
--- a/fincept-qt/packaging/linux/fincept-terminal.appdata.xml
+++ b/fincept-qt/packaging/linux/fincept-terminal.appdata.xml
@@ -28,6 +28,11 @@
<binary>FinceptTerminal</binary>
</provides>
<releases>
+ <release version="4.3.0" date="2026-07-25">
+ <description>
+ <p>Version 4.3.0 — MCP long-running tools now run as background jobs the assistant can poll and cancel, and oversized tool results are paged on demand instead of filling the conversation.</p>
+ </description>
+ </release>
<release version="4.1.0" date="2026-06-09">
<description>
<p>Version 4.1.0 — Optional NewsAPI.org news provider, broker-sourced technicals, and fixes.</p>
diff --git a/fincept-qt/scripts/agents/finagent_core/execution_planner.py b/fincept-qt/scripts/agents/finagent_core/execution_planner.py
index ae967493e..cc2d53f09 100644
--- a/fincept-qt/scripts/agents/finagent_core/execution_planner.py
+++ b/fincept-qt/scripts/agents/finagent_core/execution_planner.py
@@ -8,12 +8,64 @@ Similar to ValueCell's task planning capabilities.
from typing import Dict, Any, Optional, List, Callable, Union
from dataclasses import dataclass, field
from enum import Enum
+import ast
import logging
import json
logger = logging.getLogger(__name__)
+# ── Condition sandbox ────────────────────────────────────────────────────────
+# Branch conditions come from a plan built by an LLM, and the plan context is
+# interpolated into them before evaluation. eval() with {"__builtins__": {}}
+# does not contain that: `().__class__.__mro__[1].__subclasses__()` reaches the
+# whole class hierarchy and from there os/subprocess, so a poisoned plan (or
+# poisoned tool output interpolated into one) is arbitrary code execution.
+#
+# Conditions only ever need comparisons, boolean logic and arithmetic over
+# context values, so the grammar is restricted to exactly that. Attribute
+# access and calls are not in the allowlist, which removes the escape entirely
+# rather than trying to blocklist its spellings.
+_CONDITION_ALLOWED_NODES = (
+ ast.Expression, ast.BoolOp, ast.UnaryOp, ast.Compare, ast.BinOp,
+ ast.Name, ast.Load, ast.Constant, ast.List, ast.Tuple,
+ ast.And, ast.Or, ast.Not, ast.USub, ast.UAdd,
+ ast.Add, ast.Sub, ast.Mult, ast.Div, ast.FloorDiv, ast.Mod,
+ ast.Eq, ast.NotEq, ast.Lt, ast.LtE, ast.Gt, ast.GtE,
+ ast.In, ast.NotIn, ast.Is, ast.IsNot,
+)
+
+
+def _safe_eval_condition(condition: str, context: Dict[str, Any]) -> bool:
+ """Evaluate a branch condition under a restricted grammar.
+
+ Returns False for anything that fails to parse, uses disallowed syntax, or
+ raises — the same failure behaviour the previous bare eval() had.
+ """
+ if not condition or not condition.strip():
+ return False
+ try:
+ tree = ast.parse(condition, mode="eval")
+ except SyntaxError:
+ logger.warning("Condition rejected (syntax): %r", condition)
+ return False
+
+ for node in ast.walk(tree):
+ if not isinstance(node, _CONDITION_ALLOWED_NODES):
+ logger.warning("Condition rejected (%s not allowed): %r",
+ type(node).__name__, condition)
+ return False
+ if isinstance(node, ast.Name) and node.id.startswith("_"):
+ logger.warning("Condition rejected (name %r): %r", node.id, condition)
+ return False
+
+ try:
+ return bool(eval(compile(tree, "<condition>", "eval"), # noqa: S307
+ {"__builtins__": {}}, context))
+ except Exception:
+ return False
+
+
class StepStatus(Enum):
"""Status of a plan step"""
PENDING = "pending"
@@ -415,10 +467,7 @@ class ExecutionPlanner:
# Simple condition evaluation using context
condition = self._interpolate(condition, plan.context)
- try:
- result = eval(condition, {"__builtins__": {}}, plan.context)
- except Exception:
- result = False
+ result = _safe_eval_condition(condition, plan.context)
next_step_id = if_true if result else if_false
diff --git a/fincept-qt/scripts/agents/rdagents/mcp_server.py b/fincept-qt/scripts/agents/rdagents/mcp_server.py
index 01e683538..09e9965f5 100644
--- a/fincept-qt/scripts/agents/rdagents/mcp_server.py
+++ b/fincept-qt/scripts/agents/rdagents/mcp_server.py
@@ -20,6 +20,7 @@ rdagent connects via:
from __future__ import annotations
+import ast
import json
import logging
import os
@@ -28,6 +29,71 @@ from typing import Any
logger = logging.getLogger(__name__)
+
+# ── Factor-expression sandbox ────────────────────────────────────────────────
+# factor_backtest evaluates a caller-supplied expression. eval() with
+# {"__builtins__": {}} is NOT a sandbox: exposing the pandas/numpy module
+# objects hands over pd.read_pickle (deserialises arbitrary objects from a URL)
+# and np.load, and even without them `().__class__.__mro__[1].__subclasses__()`
+# walks back to the whole class hierarchy. Since factor_expr arrives from an
+# LLM that reads untrusted market/news text, that is a prompt-injection → RCE
+# path.
+#
+# So the expression is parsed and checked against an allowlist before it ever
+# reaches eval(). Attribute access is the escape hatch, so it is gated on a
+# name allowlist: `close.rolling(20).mean()` and `np.log(close)` (the syntax
+# the docstring advertises) still work, while `.read_pickle` / `.__class__` /
+# any dunder is rejected at parse time.
+
+_FACTOR_ALLOWED_NODES = (
+ ast.Expression, ast.BinOp, ast.UnaryOp, ast.BoolOp, ast.Compare, ast.Call,
+ ast.Attribute, ast.Name, ast.Load, ast.Constant, ast.Tuple, ast.List,
+ ast.keyword, ast.Slice, ast.Subscript, ast.IfExp,
+ ast.Add, ast.Sub, ast.Mult, ast.Div, ast.FloorDiv, ast.Mod, ast.Pow,
+ ast.USub, ast.UAdd, ast.Not, ast.And, ast.Or,
+ ast.Eq, ast.NotEq, ast.Lt, ast.LtE, ast.Gt, ast.GtE,
+)
+
+_FACTOR_ALLOWED_ATTRS = frozenset({
+ # numpy ufuncs
+ "log", "log1p", "log10", "exp", "sqrt", "abs", "sign", "tanh", "clip",
+ "maximum", "minimum", "where", "power", "square", "floor", "ceil",
+ "nan_to_num",
+ # pandas Series / rolling / ewm / expanding
+ "rolling", "ewm", "expanding", "shift", "diff", "pct_change", "rank",
+ "mean", "median", "std", "var", "sum", "min", "max", "corr", "cov",
+ "skew", "kurt", "quantile", "cumsum", "cumprod", "fillna", "dropna",
+ "round",
+})
+
+
+def _compile_factor_expr(expr: str):
+ """Parse+validate a factor expression, returning a compiled code object.
+
+ Raises ValueError with a caller-facing reason if the expression uses
+ anything outside the allowlist.
+ """
+ try:
+ tree = ast.parse(expr, mode="eval")
+ except SyntaxError as e:
+ raise ValueError(f"invalid syntax: {e}") from None
+
+ for node in ast.walk(tree):
+ if not isinstance(node, _FACTOR_ALLOWED_NODES):
+ raise ValueError(f"disallowed expression element: {type(node).__name__}")
+ if isinstance(node, ast.Attribute):
+ if node.attr.startswith("_") or node.attr not in _FACTOR_ALLOWED_ATTRS:
+ raise ValueError(f"disallowed attribute: .{node.attr}")
+ if isinstance(node, ast.Name) and node.id.startswith("_"):
+ raise ValueError(f"disallowed name: {node.id}")
+ # Only method calls (allowlisted above) and calls on plain names are
+ # permitted; a call on anything else is a construction we have not
+ # reasoned about.
+ if isinstance(node, ast.Call) and not isinstance(node.func, (ast.Attribute, ast.Name)):
+ raise ValueError("disallowed call target")
+
+ return compile(tree, "<factor_expr>", "eval")
+
# ---------------------------------------------------------------------------
# Availability checks
# ---------------------------------------------------------------------------
@@ -382,10 +448,15 @@ def build_mcp_server() -> Any:
})
df["returns"] = df["close"].pct_change()
- # Evaluate factor expression safely
+ # Evaluate factor expression — allowlist-checked at parse time,
+ # see _compile_factor_expr above.
+ try:
+ code = _compile_factor_expr(factor_expr)
+ except ValueError as e:
+ return {"error": f"Factor expression rejected: {e}"}
try:
factor_vals = eval( # noqa: S307
- factor_expr,
+ code,
{"__builtins__": {}},
{**{col: df[col] for col in df.columns},
"pd": pd, "np": np},
diff --git a/fincept-qt/src/app/ScreenSmokeTest.cpp b/fincept-qt/src/app/ScreenSmokeTest.cpp
index 16e3dfb2a..f868a3137 100644
--- a/fincept-qt/src/app/ScreenSmokeTest.cpp
+++ b/fincept-qt/src/app/ScreenSmokeTest.cpp
@@ -1,6 +1,7 @@
#include "app/ScreenSmokeTest.h"
#include "app/DockScreenRouter.h"
+#include "auth/InactivityGuard.h"
#include "core/logging/Logger.h"
#include <QCoreApplication>
@@ -32,6 +33,30 @@ int run_screen_smoke_test(DockScreenRouter* router) {
return 2;
}
+ // A PIN-locked terminal makes this test meaningless, and silently so.
+ // DockScreenRouter::navigate() hard-refuses while the terminal is locked
+ // (deliberately — nothing may mutate panel state behind the PIN gate), so
+ // every navigation no-ops and EVERY lazily-registered screen is reported as
+ // "did not construct". That produced 46 phantom failures on a developer
+ // machine with a PIN set, while CI — a fresh runner with no PIN — passed.
+ // A test that only works in one environment and lies in the other is worse
+ // than no test, so detect the condition and say exactly what is wrong.
+ //
+ // Deliberately NOT auto-unlocking: a test harness must not learn to bypass
+ // an authentication gate.
+ if (auth::InactivityGuard::instance().is_terminal_locked()) {
+ std::fprintf(stderr,
+ "[Smoke] FAIL: terminal is PIN-locked — navigate() is suppressed, so no screen can be\n"
+ " constructed and every result would be a false failure.\n"
+ " Clear the PIN (Settings > Security > Change PIN) and re-run.\n"
+ " NOTE: --profile does NOT help. The PIN lives in machine-wide SecureStorage,\n"
+ " not in the profile directory, so a fresh profile still hits the lock once it\n"
+ " has an authenticated session. CI passes only because its runners have no PIN.\n");
+ std::fflush(stderr);
+ LOG_ERROR("Smoke", "Aborted: terminal is PIN-locked; navigate() is suppressed behind the lock gate");
+ return 3;
+ }
+
const QStringList ids = router->all_screen_ids();
std::fprintf(stderr, "[Smoke] walking %d screens\n", static_cast<int>(ids.size()));
std::fflush(stderr);
diff --git a/fincept-qt/src/app/WindowFrame.cpp b/fincept-qt/src/app/WindowFrame.cpp
index e74ad8813..b51407cd2 100644
--- a/fincept-qt/src/app/WindowFrame.cpp
+++ b/fincept-qt/src/app/WindowFrame.cpp
@@ -743,6 +743,10 @@ WindowFrame::WindowFrame(int window_id, QWidget* parent, const WindowId& adopted
QMessageBox::warning(this, tr("Export Failed"), QString::fromStdString(r.error()));
}
}
+ } else if (action == "check_updates") {
+ // Help ▸ Check for Updates. silent=false so the user gets a result
+ // either way — a menu-triggered check that says nothing reads as broken.
+ services::UpdateService::instance().check_for_updates(/*silent=*/false);
} else if (action == "screenshot") {
QScreen* scr = this->screen();
if (!scr)
diff --git a/fincept-qt/src/app/WindowFrame_Auth.cpp b/fincept-qt/src/app/WindowFrame_Auth.cpp
index 2a6c27b49..acd7872dc 100644
--- a/fincept-qt/src/app/WindowFrame_Auth.cpp
+++ b/fincept-qt/src/app/WindowFrame_Auth.cpp
@@ -324,11 +324,29 @@ void WindowFrame::on_terminal_unlocked() {
guard.set_timeout_minutes(minutes);
}
}
- if (!guard.is_enabled()) {
- qApp->installEventFilter(&guard);
- guard.set_enabled(true);
+ // Honour the user's Settings → Security → "Enable auto-lock" choice.
+ // This previously enabled the guard unconditionally, so switching
+ // auto-lock OFF was silently reverted on the very next unlock/login —
+ // the setting persisted but nothing ever read it. Auto-lock is also
+ // pointless without a PIN (there would be nothing to unlock with), so
+ // both conditions gate it. Default is ON when the key is absent, which
+ // preserves the previous behaviour for existing users.
+ const bool autolock_wanted = [] {
+ auto r = SettingsRepository::instance().get("security.autolock_enabled");
+ if (r.is_ok() && !r.value().isEmpty())
+ return r.value().compare(QLatin1String("false"), Qt::CaseInsensitive) != 0;
+ return true; // unset → previous default
+ }();
+
+ if (autolock_wanted && auth::PinManager::instance().has_pin()) {
+ if (!guard.is_enabled()) {
+ qApp->installEventFilter(&guard);
+ guard.set_enabled(true);
+ }
+ guard.reset_timer();
+ } else if (guard.is_enabled()) {
+ guard.set_enabled(false);
}
- guard.reset_timer();
// Reset PIN lockout on successful unlock
auth::PinManager::instance().reset_lockout();
diff --git a/fincept-qt/src/app/main.cpp b/fincept-qt/src/app/main.cpp
index e056e908c..8aa22d1e4 100644
--- a/fincept-qt/src/app/main.cpp
+++ b/fincept-qt/src/app/main.cpp
@@ -101,6 +101,7 @@
#include "trading/UnifiedPortfolioService.h"
#include "trading/replication/PortfolioReplicationSelftest.h"
#include "ui/notifications/DesktopNotifier.h"
+#include "ui/tables/LiveTableSelftest.h"
#include "ui/theme/Theme.h"
#include "ui/theme/ThemeManager.h"
@@ -791,14 +792,24 @@ int main(int argc, char* argv[]) {
auto& tm = fincept::ui::ThemeManager::instance();
auto r_family = repo.get("appearance.font_family");
auto r_size = repo.get("appearance.font_size");
+ auto r_density = repo.get("appearance.density");
QString family = r_family.is_ok() ? r_family.value() : "Consolas";
QString size_s = r_size.is_ok() ? r_size.value() : "14px";
int size_px = size_s.left(size_s.indexOf("px")).toInt();
if (size_px <= 0)
size_px = 14;
- tm.apply_font(family, size_px);
+ // Density must be restored here too. Settings → Appearance persists
+ // "appearance.density" and applies it live, but startup only ever
+ // read family+size — so the user's Compact/Comfortable choice
+ // silently reverted to Default on every relaunch.
+ // apply_typography_and_density() is deliberately used instead of
+ // apply_font() + apply_density(): it batches both into a single
+ // qApp->setStyleSheet() (see its docs re: the Plasma 6 / Wayland
+ // double-restyle crash, issue #247).
+ QString density = r_density.is_ok() && !r_density.value().isEmpty() ? r_density.value() : "Default";
+ tm.apply_typography_and_density(family, size_px, density);
tm.apply_theme("Obsidian");
- LOG_INFO("App", "Theme: Obsidian, font: " + family + " " + size_s);
+ LOG_INFO("App", "Theme: Obsidian, font: " + family + " " + size_s + ", density: " + density);
}
// Load persisted language and install the matching QTranslator before
@@ -911,6 +922,8 @@ int main(int argc, char* argv[]) {
return fincept::feeds::run_feed_selftest();
if (qstrcmp(argv[i], "--selftest-dock-layout") == 0)
return fincept::layout::run_dock_layout_selftest();
+ if (qstrcmp(argv[i], "--selftest-live-table") == 0)
+ return fincept::ui::run_live_table_selftest();
if (qstrcmp(argv[i], "--selftest-fno-algo") == 0)
return fincept::algo::fno::run_fno_algo_selftest();
if (qstrcmp(argv[i], "--selftest-universe-scan") == 0)
diff --git a/fincept-qt/src/core/i18n/LanguageManager.cpp b/fincept-qt/src/core/i18n/LanguageManager.cpp
index 83d699236..941bf9a63 100644
--- a/fincept-qt/src/core/i18n/LanguageManager.cpp
+++ b/fincept-qt/src/core/i18n/LanguageManager.cpp
@@ -85,6 +85,16 @@ QString LanguageManager::detect_system_language() {
const QStringList preferred = QLocale::system().uiLanguages(QLocale::TagSeparator::Underscore);
for (const QString& ui : preferred) {
+ // Script-tagged locales first. macOS reports UI languages with a script
+ // subtag ("zh_Hant_TW", "zh_Hans_CN"), which never matches our
+ // region-coded .qm names directly — the loop below would strip it down
+ // to "zh" and the prefix fallback would then hand every Chinese system
+ // the Simplified build, including Traditional ones. QLocale resolves
+ // the likely territory for us ("zh_Hant_TW" → "zh_TW").
+ const QString resolved = QLocale(ui).name();
+ if (supported.contains(resolved))
+ return resolved;
+
// Strip script/region tags from longest to shortest (e.g.
// "zh_Hans_CN" → "zh_Hans" → "zh") and try each form against our
// supported set. This catches both exact matches ("zh_CN") and
diff --git a/fincept-qt/src/datahub/DataHub.cpp b/fincept-qt/src/datahub/DataHub.cpp
index 6aa55c7e9..6f5aac9ee 100644
--- a/fincept-qt/src/datahub/DataHub.cpp
+++ b/fincept-qt/src/datahub/DataHub.cpp
@@ -816,6 +816,20 @@ QVariant DataHub::peek_raw(const QString& topic) const {
return it == topics_.end() ? QVariant{} : it->value;
}
+qint64 DataHub::last_publish_ms(const QString& topic) const {
+ QMutexLocker lock(&mutex_);
+ auto it = topics_.find(topic);
+ return it == topics_.end() ? 0 : it->last_publish_ms;
+}
+
+qint64 DataHub::age_ms(const QString& topic) const {
+ QMutexLocker lock(&mutex_);
+ auto it = topics_.find(topic);
+ if (it == topics_.end() || it->last_publish_ms <= 0)
+ return -1;
+ return now_ms() - it->last_publish_ms;
+}
+
void DataHub::request(const QString& topic, bool force) {
request(QStringList{topic}, force);
}
diff --git a/fincept-qt/src/datahub/DataHub.h b/fincept-qt/src/datahub/DataHub.h
index 33fcd5bfb..624350184 100644
--- a/fincept-qt/src/datahub/DataHub.h
+++ b/fincept-qt/src/datahub/DataHub.h
@@ -161,6 +161,20 @@ class DataHub : public QObject {
// ── Introspection ───────────────────────────────────────────────────────
+ /// Wall-clock ms of this topic's last publish, or 0 if it has never
+ /// published / is unknown. Cheap O(1) hash lookup — `stats()` walks every
+ /// topic and is far too heavy to call from a per-widget refresh.
+ ///
+ /// Exists so consumers can render a freshness indicator. A financial
+ /// terminal showing a price with no indication of its age is actively
+ /// misleading: the user cannot distinguish a live quote from one frozen
+ /// twenty minutes ago by a dead producer.
+ qint64 last_publish_ms(const QString& topic) const;
+
+ /// Convenience: ms since the last publish, or -1 if never published.
+ /// Compare against the topic's TTL to decide "fresh / stale / dead".
+ qint64 age_ms(const QString& topic) const;
+
QVector<TopicStats> stats() const;
/// Diagnostic: list the QObject owners currently subscribed to `topic`.
diff --git a/fincept-qt/src/mcp/AsyncDispatch.h b/fincept-qt/src/mcp/AsyncDispatch.h
index 3807426a3..9e1fbd4cb 100644
--- a/fincept-qt/src/mcp/AsyncDispatch.h
+++ b/fincept-qt/src/mcp/AsyncDispatch.h
@@ -52,6 +52,7 @@
#include <QPromise>
#include <QThread>
+#include <atomic>
#include <functional>
#include <memory>
@@ -78,8 +79,16 @@ class AsyncDispatch {
BodyFn&& body) {
// Wrap resolve so it's idempotent — the timeout watchdog and the
// service callback can race; whichever fires first wins.
- auto resolve = [promise](ToolResult r) {
- if (promise->future().isFinished())
+ //
+ // The guard must be a compare-exchange, not a `future().isFinished()`
+ // test: the watchdog fires on the GUI thread while the service callback
+ // fires on its own thread, so both can observe "not finished" and then
+ // both addResult() — the loser writing after finish(), which Qt asserts
+ // on. Only the thread that flips the flag proceeds.
+ auto resolved = std::make_shared<std::atomic<bool>>(false);
+ auto resolve = [promise, resolved](ToolResult r) {
+ bool expected = false;
+ if (!resolved->compare_exchange_strong(expected, true))
return;
promise->addResult(std::move(r));
promise->finish();
diff --git a/fincept-qt/src/mcp/JobRegistry.cpp b/fincept-qt/src/mcp/JobRegistry.cpp
new file mode 100644
index 000000000..70836c917
--- /dev/null
+++ b/fincept-qt/src/mcp/JobRegistry.cpp
@@ -0,0 +1,234 @@
+// JobRegistry.cpp — Async job store for long-running MCP tool calls.
+
+#include "mcp/JobRegistry.h"
+
+#include "core/logging/Logger.h"
+
+#include <QDateTime>
+#include <QJsonObject>
+
+#include <algorithm>
+
+namespace fincept::mcp {
+
+static constexpr const char* TAG = "JobRegistry";
+
+static qint64 now_ms() {
+ return QDateTime::currentMSecsSinceEpoch();
+}
+
+qint64 JobSnapshot::elapsed_ms() const {
+ const qint64 end = finished_ms > 0 ? finished_ms : now_ms();
+ return end - started_ms;
+}
+
+QJsonObject JobSnapshot::to_json() const {
+ QJsonObject j{
+ {"job_id", id},
+ {"tool", tool},
+ {"status", QString::fromLatin1(job_state_str(state))},
+ {"elapsed_ms", elapsed_ms()},
+ };
+ // Omit zero/empty fields — this object is polled repeatedly and every
+ // key costs tokens on every poll.
+ if (progress > 0.0)
+ j["progress"] = progress;
+ if (!message.isEmpty())
+ j["message"] = message;
+ return j;
+}
+
+JobRegistry& JobRegistry::instance() {
+ static JobRegistry s;
+ return s;
+}
+
+QString JobRegistry::create(const QString& tool) {
+ QMutexLocker lock(&mutex_);
+ sweep_locked();
+
+ // Short monotonic id — a full UUID would be 36 chars the model has to echo
+ // back on every poll, for no added value in a per-process registry.
+ const QString id = QStringLiteral("job_%1").arg(++next_id_, 6, 16, QLatin1Char('0'));
+
+ Job job;
+ job.snap.id = id;
+ job.snap.tool = tool;
+ job.snap.state = JobState::Running;
+ job.snap.started_ms = now_ms();
+ job.cancel_flag = std::make_shared<std::atomic<bool>>(false);
+ jobs_.insert(id, std::move(job));
+
+ LOG_INFO(TAG, QString("Job %1 started for tool '%2'").arg(id, tool));
+ return id;
+}
+
+void JobRegistry::set_progress(const QString& id, double progress, const QString& message) {
+ QMutexLocker lock(&mutex_);
+ auto it = jobs_.find(id);
+ if (it == jobs_.end() || it->snap.is_finished())
+ return;
+ it->snap.progress = std::clamp(progress, 0.0, 1.0);
+ if (!message.isEmpty())
+ it->snap.message = message;
+}
+
+void JobRegistry::complete(const QString& id, const ToolResult& result) {
+ {
+ QMutexLocker lock(&mutex_);
+ auto it = jobs_.find(id);
+ if (it == jobs_.end())
+ return;
+ // The timeout watchdog and the handler's own callback both land here.
+ // First writer wins; the loser is dropped silently.
+ if (it->snap.is_finished())
+ return;
+
+ // A handler that unwound because we asked it to stop reports Cancelled
+ // rather than Failed — the distinction matters to the model, which
+ // should not retry a job the user cancelled.
+ const bool was_cancel_requested = it->cancel_flag && it->cancel_flag->load();
+ it->snap.state =
+ result.success ? JobState::Succeeded : (was_cancel_requested ? JobState::Cancelled : JobState::Failed);
+ it->snap.finished_ms = now_ms();
+ if (result.success)
+ it->snap.progress = 1.0;
+ it->result = result;
+
+ LOG_INFO(TAG, QString("Job %1 (%2) → %3 after %4 ms")
+ .arg(id, it->snap.tool, QString::fromLatin1(job_state_str(it->snap.state)))
+ .arg(it->snap.elapsed_ms()));
+ }
+ // Wake every long-poller; each re-checks its own job id.
+ finished_cv_.wakeAll();
+}
+
+bool JobRegistry::request_cancel(const QString& id) {
+ QMutexLocker lock(&mutex_);
+ auto it = jobs_.find(id);
+ if (it == jobs_.end() || it->snap.is_finished())
+ return false;
+ if (it->cancel_flag)
+ it->cancel_flag->store(true);
+ it->snap.message = QStringLiteral("cancellation requested");
+ LOG_INFO(TAG, QString("Job %1 (%2) — cancellation requested").arg(id, it->snap.tool));
+ return true;
+}
+
+bool JobRegistry::is_cancelled(const QString& id) const {
+ QMutexLocker lock(&mutex_);
+ auto it = jobs_.constFind(id);
+ return it != jobs_.constEnd() && it->cancel_flag && it->cancel_flag->load();
+}
+
+std::shared_ptr<std::atomic<bool>> JobRegistry::cancel_flag(const QString& id) const {
+ QMutexLocker lock(&mutex_);
+ auto it = jobs_.constFind(id);
+ return it != jobs_.constEnd() ? it->cancel_flag : nullptr;
+}
+
+std::optional<JobSnapshot> JobRegistry::status(const QString& id) const {
+ QMutexLocker lock(&mutex_);
+ auto it = jobs_.constFind(id);
+ if (it == jobs_.constEnd())
+ return std::nullopt;
+ return it->snap;
+}
+
+std::optional<ToolResult> JobRegistry::take_result(const QString& id) {
+ QMutexLocker lock(&mutex_);
+ auto it = jobs_.find(id);
+ if (it == jobs_.end() || !it->snap.is_finished())
+ return std::nullopt;
+ it->snap.result_collected = true;
+ return it->result;
+}
+
+std::optional<JobSnapshot> JobRegistry::wait_for(const QString& id, int wait_ms) {
+ QMutexLocker lock(&mutex_);
+ auto it = jobs_.find(id);
+ if (it == jobs_.end())
+ return std::nullopt;
+ if (it->snap.is_finished() || wait_ms <= 0)
+ return it->snap;
+
+ const qint64 deadline = now_ms() + std::min(wait_ms, kMaxWaitMs);
+ while (true) {
+ const qint64 remaining = deadline - now_ms();
+ if (remaining <= 0)
+ break;
+ // wakeAll() fires for every completion, so re-look-up and re-test our
+ // own job each time round rather than trusting the wake.
+ finished_cv_.wait(&mutex_, static_cast<unsigned long>(remaining));
+ it = jobs_.find(id);
+ if (it == jobs_.end())
+ return std::nullopt; // swept mid-wait
+ if (it->snap.is_finished())
+ break;
+ }
+ return it->snap;
+}
+
+std::vector<JobSnapshot> JobRegistry::list(bool include_finished) const {
+ QMutexLocker lock(&mutex_);
+ std::vector<JobSnapshot> out;
+ out.reserve(static_cast<std::size_t>(jobs_.size()));
+ for (auto it = jobs_.constBegin(); it != jobs_.constEnd(); ++it) {
+ if (!include_finished && it->snap.is_finished())
+ continue;
+ out.push_back(it->snap);
+ }
+ std::sort(out.begin(), out.end(), [](const JobSnapshot& a, const JobSnapshot& b) {
+ return a.started_ms > b.started_ms; // newest first
+ });
+ return out;
+}
+
+int JobRegistry::running_count() const {
+ QMutexLocker lock(&mutex_);
+ int n = 0;
+ for (auto it = jobs_.constBegin(); it != jobs_.constEnd(); ++it)
+ if (!it->snap.is_finished())
+ ++n;
+ return n;
+}
+
+void JobRegistry::sweep() {
+ QMutexLocker lock(&mutex_);
+ sweep_locked();
+}
+
+void JobRegistry::sweep_locked() {
+ const qint64 now = now_ms();
+ for (auto it = jobs_.begin(); it != jobs_.end();) {
+ const JobSnapshot& s = it->snap;
+ const qint64 ttl = s.result_collected ? kCollectedTtlMs : kFinishedTtlMs;
+ if (s.is_finished() && now - s.finished_ms > ttl)
+ it = jobs_.erase(it);
+ else
+ ++it;
+ }
+
+ if (jobs_.size() <= kMaxJobs)
+ return;
+
+ // Over the cap — evict oldest *finished* jobs first. Running jobs are never
+ // evicted: dropping one would strand the handler with a job id nobody can
+ // complete, and the model would poll a dead receipt forever.
+ std::vector<QPair<qint64, QString>> finished;
+ for (auto it = jobs_.constBegin(); it != jobs_.constEnd(); ++it)
+ if (it->snap.is_finished())
+ finished.push_back({it->snap.finished_ms, it.key()});
+ std::sort(finished.begin(), finished.end(), [](const auto& a, const auto& b) { return a.first < b.first; });
+
+ int to_drop = static_cast<int>(jobs_.size()) - kMaxJobs;
+ for (const auto& entry : finished) {
+ if (to_drop-- <= 0)
+ break;
+ jobs_.remove(entry.second);
+ }
+ if (to_drop > 0)
+ LOG_WARN(TAG, QString("%1 running jobs exceed the %2-job cap — none evicted").arg(to_drop).arg(kMaxJobs));
+}
+
+} // namespace fincept::mcp
diff --git a/fincept-qt/src/mcp/JobRegistry.h b/fincept-qt/src/mcp/JobRegistry.h
new file mode 100644
index 000000000..4df4d3892
--- /dev/null
+++ b/fincept-qt/src/mcp/JobRegistry.h
@@ -0,0 +1,165 @@
+#pragma once
+// JobRegistry.h — Async job store for long-running MCP tool calls.
+//
+// Problem this solves
+// -------------------
+// Every MCP tool call was synchronous: `McpProvider::call_tool` dispatches the
+// handler and blocks on `QFuture::waitForFinished()`. For a tool with a
+// 300 s budget (`kDefaultAgentTimeoutMs`) that means the LLM's HTTP turn stays
+// open for five minutes, the chat UI shows nothing, and the whole tool-round
+// budget is spent on one call. There was no way to start work, hand the model a
+// receipt, and let it come back for the answer.
+//
+// This registry is that receipt book. A tool that opts in
+// (`ToolDef::supports_async`) runs under a job: if it finishes inside the grace
+// window the caller gets the real result inline and the job is discarded, so
+// fast paths are unchanged. If it doesn't, the caller gets
+// `{job_id, status:"running"}` — a ~40-token receipt instead of a five-minute
+// stall — and the work continues in the background.
+//
+// The model then uses the `job_*` meta-tools (see tools/JobTools.cpp):
+// job_status(id, wait_ms) — long-polls; one call can cover the whole run
+// job_result(id) — the payload, once finished
+// job_cancel(id) — sets the cancellation flag the handler polls
+// job_list() — what's still in flight
+//
+// `wait_ms` matters for token cost: without it the model burns one tool round
+// per poll. With it, a 90 s job costs ~2 rounds instead of ~30.
+//
+// Thread safety: every method is callable from any thread. Handlers resolve
+// their promise on service/worker threads; the meta-tools run on QtConcurrent
+// pool threads; the watchdog runs on the GUI thread. A single QMutex guards the
+// map and a QWaitCondition backs `wait_for` so long-polling costs no event loop.
+
+#include "mcp/McpTypes.h"
+
+#include <QHash>
+#include <QMutex>
+#include <QString>
+#include <QWaitCondition>
+
+#include <atomic>
+#include <memory>
+#include <optional>
+#include <vector>
+
+namespace fincept::mcp {
+
+enum class JobState { Running, Succeeded, Failed, Cancelled };
+
+inline const char* job_state_str(JobState s) {
+ switch (s) {
+ case JobState::Running:
+ return "running";
+ case JobState::Succeeded:
+ return "succeeded";
+ case JobState::Failed:
+ return "failed";
+ case JobState::Cancelled:
+ return "cancelled";
+ }
+ return "unknown";
+}
+
+/// Immutable view of a job — safe to copy out from under the lock.
+struct JobSnapshot {
+ QString id;
+ QString tool;
+ JobState state = JobState::Running;
+ double progress = 0.0; // [0,1]; 0 when the handler reports no progress
+ QString message; // last status line from the handler
+ qint64 started_ms = 0; // epoch ms
+ qint64 finished_ms = 0;
+ bool result_collected = false;
+
+ bool is_finished() const { return state != JobState::Running; }
+ qint64 elapsed_ms() const;
+
+ /// Compact wire form for `job_status` / `job_list`. Deliberately small —
+ /// this is polled repeatedly, so every field costs tokens on every poll.
+ QJsonObject to_json() const;
+};
+
+class JobRegistry {
+ public:
+ static JobRegistry& instance();
+
+ /// Register a new running job. Returns its id (e.g. "job_4f21ab").
+ QString create(const QString& tool);
+
+ /// Handler progress hook. `progress` is clamped to [0,1]; an empty
+ /// `message` leaves the previous one in place.
+ void set_progress(const QString& id, double progress, const QString& message);
+
+ /// Move the job to a terminal state and store its payload. No-op if the
+ /// job already finished (the timeout watchdog and the handler race).
+ void complete(const QString& id, const ToolResult& result);
+
+ /// Raise the cancellation flag the handler polls via `ToolContext::is_cancelled`.
+ /// Returns false if the id is unknown or the job already finished. The job
+ /// is NOT moved to Cancelled here — that happens when the handler actually
+ /// unwinds and calls complete(), so `job_status` keeps reporting "running"
+ /// until the work has genuinely stopped.
+ bool request_cancel(const QString& id);
+
+ bool is_cancelled(const QString& id) const;
+
+ /// The flag itself — handed to ToolContext so the polling path doesn't
+ /// re-lock the registry on every check inside a tight handler loop.
+ std::shared_ptr<std::atomic<bool>> cancel_flag(const QString& id) const;
+
+ std::optional<JobSnapshot> status(const QString& id) const;
+
+ /// The stored payload. `std::nullopt` while the job is still running or if
+ /// the id is unknown. Marks the job as collected (it becomes eligible for a
+ /// shorter sweep TTL, so a polled-and-read job doesn't linger for 15 min).
+ std::optional<ToolResult> take_result(const QString& id);
+
+ /// Block up to `wait_ms` for the job to leave Running, then return its
+ /// snapshot. This is the long-poll that keeps `job_status` from costing one
+ /// tool round per second. `wait_ms <= 0` returns immediately.
+ std::optional<JobSnapshot> wait_for(const QString& id, int wait_ms);
+
+ std::vector<JobSnapshot> list(bool include_finished) const;
+
+ /// Drop finished jobs past their TTL and trim the map back to kMaxJobs.
+ /// Called opportunistically from create(); no timer needed.
+ void sweep();
+
+ int running_count() const;
+
+ JobRegistry(const JobRegistry&) = delete;
+ JobRegistry& operator=(const JobRegistry&) = delete;
+
+ private:
+ JobRegistry() = default;
+
+ struct Job {
+ JobSnapshot snap;
+ ToolResult result;
+ std::shared_ptr<std::atomic<bool>> cancel_flag;
+ };
+
+ void sweep_locked();
+
+ mutable QMutex mutex_;
+ mutable QWaitCondition finished_cv_;
+ QHash<QString, Job> jobs_;
+ quint64 next_id_ = 0;
+
+ // A finished job is kept this long so the model can still collect it after
+ // a slow round-trip; once collected it only needs to survive a retry.
+ static constexpr qint64 kFinishedTtlMs = 15 * 60 * 1000;
+ static constexpr qint64 kCollectedTtlMs = 60 * 1000;
+ // Hard cap so a runaway agent can't grow the map without bound. Oldest
+ // finished jobs are evicted first; running jobs are never evicted.
+ static constexpr int kMaxJobs = 128;
+ // Upper bound on a single `job_status` long-poll. Longer than this and the
+ // provider-side HTTP request risks timing out mid-wait.
+ static constexpr int kMaxWaitMs = 30000;
+
+ public:
+ static constexpr int max_wait_ms() { return kMaxWaitMs; }
+};
+
+} // namespace fincept::mcp
diff --git a/fincept-qt/src/mcp/McpInit.cpp b/fincept-qt/src/mcp/McpInit.cpp
index 20ab75e89..fbac077b1 100644
--- a/fincept-qt/src/mcp/McpInit.cpp
+++ b/fincept-qt/src/mcp/McpInit.cpp
@@ -21,6 +21,7 @@
#include "mcp/tools/ForumTools.h"
#include "mcp/tools/GeopoliticsTools.h"
#include "mcp/tools/GovDataTools.h"
+#include "mcp/tools/JobTools.h"
#include "mcp/tools/LiveTradingTools.h"
#include "mcp/tools/MAAnalyticsTools.h"
#include "mcp/tools/MarketsTools.h"
@@ -194,6 +195,12 @@ void initialize_all_tools() {
// Always exposed so the LLM can lazy-discover specialised tools.
provider.register_tools(tools::get_meta_tools());
+ // Long-running-job + oversized-result protocol — job_status/result/cancel/list
+ // and result_fetch. Tier-0 (always sent), because a model holding a job
+ // receipt or a truncated-result envelope must be able to redeem it without
+ // first running a tool_list search to find out how.
+ provider.register_tools(tools::get_job_tools());
+
LOG_INFO(TAG, QString("Registered %1 internal MCP tools").arg(provider.tool_count()));
// Audit schema sizes once after registration — surfaces bloated tools
diff --git a/fincept-qt/src/mcp/McpProvider.cpp b/fincept-qt/src/mcp/McpProvider.cpp
index 07993510c..5326a0b94 100644
--- a/fincept-qt/src/mcp/McpProvider.cpp
+++ b/fincept-qt/src/mcp/McpProvider.cpp
@@ -3,12 +3,15 @@
#include "mcp/McpProvider.h"
#include "core/logging/Logger.h"
+#include "mcp/JobRegistry.h"
#include "mcp/SchemaValidator.h"
#include <QCoreApplication>
#include <QFutureWatcher>
+#include <QPointer>
#include <QPromise>
#include <QRegularExpression>
+#include <QSemaphore>
#include <QSet>
#include <QThread>
#include <QTimer>
@@ -178,6 +181,73 @@ ToolResult McpProvider::call_tool(const QString& name, const QJsonObject& args)
return future.result();
}
+bool McpProvider::supports_async_jobs(const QString& name) const {
+ QMutexLocker lock(&mutex_);
+ auto it = tools_.constFind(name);
+ if (it == tools_.constEnd() || disabled_tools_.contains(name))
+ return false;
+ // The flag alone isn't enough — a sync handler runs to completion on the
+ // calling thread and can be neither observed nor interrupted, so there is
+ // nothing a job wrapper could add.
+ return it->supports_async && static_cast<bool>(it->async_handler);
+}
+
+ToolResult McpProvider::call_tool_or_defer(const QString& name, const QJsonObject& args, int grace_ms) {
+ if (!supports_async_jobs(name))
+ return call_tool(name, args);
+
+ auto& jobs = JobRegistry::instance();
+ const QString job_id = jobs.create(name);
+
+ // Wire the job into the handler's context: cancellation reads the job's own
+ // atomic flag (no registry lock in the handler's polling loop), progress
+ // writes straight back to the snapshot the model polls.
+ ToolContext ctx;
+ if (auto flag = jobs.cancel_flag(job_id))
+ ctx.is_cancelled = [flag]() { return flag->load(); };
+ ctx.on_progress = [job_id](double progress, const QString& message) {
+ JobRegistry::instance().set_progress(job_id, progress, message);
+ };
+
+ auto future = call_tool_async(name, args, ctx);
+
+ // One continuation per QFuture is the Qt limit, and this is it — the future
+ // is never handed to anyone else, so there is no contention.
+ auto gate = std::make_shared<QSemaphore>(0);
+ future.then([job_id, gate](QFuture<ToolResult> f) {
+ // A handler is allowed to finish without ever adding a result; treat
+ // that as a failure rather than dereferencing an empty future.
+ JobRegistry::instance().complete(job_id, f.resultCount() > 0
+ ? f.result()
+ : ToolResult::fail("Tool produced no result"));
+ gate->release();
+ });
+
+ if (gate->tryAcquire(1, std::max(0, grace_ms))) {
+ // Beat the grace window — hand back the real result and let the job
+ // record expire on the short collected-TTL. The model never learns a
+ // job existed, which is the point: fast calls stay one round-trip.
+ if (auto r = jobs.take_result(job_id))
+ return *r;
+ return ToolResult::fail("Job " + job_id + " finished without a result");
+ }
+
+ LOG_INFO(TAG, QString("Tool '%1' exceeded the %2 ms grace window — backgrounded as %3")
+ .arg(name)
+ .arg(grace_ms)
+ .arg(job_id));
+
+ return ToolResult::ok(QString("Started background job %1 for '%2'. Poll job_status(job_id='%1', wait_ms=20000) "
+ "until status is 'succeeded' or 'failed', then call job_result(job_id='%1'). "
+ "Do NOT call '%2' again — it is already running.")
+ .arg(job_id, name),
+ QJsonObject{
+ {"job_id", job_id},
+ {"status", "running"},
+ {"tool", name},
+ });
+}
+
QFuture<ToolResult> McpProvider::call_tool_async(const QString& name, const QJsonObject& args, ToolContext ctx) {
ToolHandler sync_handler;
AsyncToolHandler async_handler;
@@ -274,19 +344,50 @@ QFuture<ToolResult> McpProvider::call_tool_async(const QString& name, const QJso
ctx.is_cancelled = [orig, cancelled]() { return cancelled->load() || orig(); };
}
+ // Single-winner guard for promise resolution. `promise->future().isFinished()`
+ // is NOT a valid guard on its own: the watchdog runs on the GUI thread
+ // while the handler resolves on a service/worker thread, so both could
+ // read "not finished" and then both addResult() — the second one lands
+ // after finish() and trips a Qt assertion. A compare-exchange makes
+ // exactly one caller the winner.
+ //
+ // Resolving also tears down the watchdog. Previously the timer was left
+ // to fire at its full interval even when the tool finished in
+ // milliseconds, so a tool with a 300 s budget parked a live timer on the
+ // GUI thread for 300 s after it was already done — once per call.
+ // `watchdog_slot` is filled in below; resolve() only reads it, so the
+ // fast path (handler resolves before we even arm the timer) is safe.
+ auto resolved = std::make_shared<std::atomic<bool>>(false);
+ auto watchdog_slot = std::make_shared<QPointer<QTimer>>();
+ auto resolve = [promise, resolved, watchdog_slot](ToolResult r) {
+ bool expected = false;
+ if (!resolved->compare_exchange_strong(expected, true))
+ return;
+ promise->addResult(std::move(r));
+ promise->finish();
+ if (QTimer* wd = watchdog_slot->data()) {
+ QMetaObject::invokeMethod(
+ wd,
+ [watchdog_slot]() {
+ if (QTimer* t = watchdog_slot->data()) {
+ t->stop();
+ t->deleteLater();
+ }
+ },
+ Qt::QueuedConnection);
+ }
+ };
+
// Arm a one-shot timeout. We post the timer onto the QApplication
// thread so it ticks even if the caller returns immediately.
auto* watchdog = new QTimer;
watchdog->setSingleShot(true);
watchdog->moveToThread(qApp->thread());
- QObject::connect(watchdog, &QTimer::timeout, watchdog, [promise, cancelled, watchdog, name]() {
- if (!promise->future().isFinished()) {
- cancelled->store(true);
- LOG_WARN(TAG, QString("Tool '%1' timed out").arg(name));
- promise->addResult(ToolResult::fail("Tool '" + name + "' timed out"));
- promise->finish();
- }
- watchdog->deleteLater();
+ *watchdog_slot = watchdog;
+ QObject::connect(watchdog, &QTimer::timeout, watchdog, [resolve, cancelled, name]() {
+ cancelled->store(true);
+ LOG_WARN(TAG, QString("Tool '%1' timed out").arg(name));
+ resolve(ToolResult::fail("Tool '" + name + "' timed out"));
});
QMetaObject::invokeMethod(
watchdog, [watchdog, ms = ctx.timeout_ms]() { watchdog->start(ms); }, Qt::QueuedConnection);
@@ -296,16 +397,10 @@ QFuture<ToolResult> McpProvider::call_tool_async(const QString& name, const QJso
async_handler(normalized, ctx, promise);
} catch (const std::exception& e) {
LOG_ERROR(TAG, QString("Async tool '%1' threw: %2").arg(name, e.what()));
- if (!promise->future().isFinished()) {
- promise->addResult(ToolResult::fail(QString("Tool execution error: ") + e.what()));
- promise->finish();
- }
+ resolve(ToolResult::fail(QString("Tool execution error: ") + e.what()));
} catch (...) {
LOG_ERROR(TAG, QString("Async tool '%1' threw unknown exception").arg(name));
- if (!promise->future().isFinished()) {
- promise->addResult(ToolResult::fail("Unknown error during tool execution"));
- promise->finish();
- }
+ resolve(ToolResult::fail("Unknown error during tool execution"));
}
return promise->future();
}
diff --git a/fincept-qt/src/mcp/McpProvider.h b/fincept-qt/src/mcp/McpProvider.h
index a3d32ef7e..7edac7c16 100644
--- a/fincept-qt/src/mcp/McpProvider.h
+++ b/fincept-qt/src/mcp/McpProvider.h
@@ -89,6 +89,34 @@ class McpProvider {
/// thread cancellation tokens through here).
QFuture<ToolResult> call_tool_async(const QString& name, const QJsonObject& args, ToolContext ctx = {});
+ /// Long-running-task entry point, for LLM-originated calls only.
+ ///
+ /// Behaves exactly like `call_tool` for tools that haven't opted into the
+ /// job protocol (`ToolDef::supports_async`), so the ~580 existing tools and
+ /// every internal C++ / workflow / agent-bridge caller are unaffected.
+ ///
+ /// For a tool that HAS opted in: the call runs under a `JobRegistry` job. If
+ /// it completes within `grace_ms` the real result is returned inline and the
+ /// job is retired — the common "it was fast this time" case costs nothing.
+ /// Otherwise the work keeps running in the background and this returns a
+ /// receipt:
+ ///
+ /// { job_id: "job_00001f", status: "running", tool: "run_agent" }
+ ///
+ /// The caller (the LLM) then polls `job_status(job_id, wait_ms)` and collects
+ /// with `job_result(job_id)`. That turns a five-minute blocking tool call
+ /// into a ~40-token receipt plus a long-poll, instead of holding the
+ /// provider HTTP turn open until it times out.
+ ///
+ /// Cancellation and progress are wired to the job automatically: handlers
+ /// see `ctx.is_cancelled()` flip when `job_cancel` is called, and whatever
+ /// they report through `ctx.on_progress` shows up in `job_status`.
+ ToolResult call_tool_or_defer(const QString& name, const QJsonObject& args, int grace_ms = kMcpJobGraceMs);
+
+ /// True if `name` is registered, enabled, and eligible for the job protocol
+ /// (opted in AND has an async handler — a sync handler can't be backgrounded).
+ bool supports_async_jobs(const QString& name) const;
+
// ── Phase 6.3: Authorization hook ──────────────────────────────────────
/// Caller-supplied predicate that returns true iff the call should
/// proceed. The hook receives the tool's required AuthLevel and
diff --git a/fincept-qt/src/mcp/McpService.cpp b/fincept-qt/src/mcp/McpService.cpp
index 02e4e6f2b..894bb19e6 100644
--- a/fincept-qt/src/mcp/McpService.cpp
+++ b/fincept-qt/src/mcp/McpService.cpp
@@ -18,6 +18,8 @@
#include <QTimer>
#include <QtConcurrent/QtConcurrent>
+#include <algorithm>
+
namespace fincept::mcp {
static constexpr const char* TAG = "McpService";
@@ -262,6 +264,16 @@ static const QSet<QString>& tier_0_tool_names() {
// report-builder work — prevents new chats from accidentally appending
// to the previous chat's report.
"report_session_context",
+ // Redemption tools for the two deferral protocols. A model that has
+ // been handed a `{job_id, status:"running"}` receipt, or a truncated
+ // result envelope carrying a `result_id`, must be able to act on it
+ // immediately — forcing a tool_list round-trip first would cost more
+ // tokens than these five small schemas do.
+ "job_status",
+ "job_result",
+ "job_cancel",
+ "job_list",
+ "result_fetch",
};
return kTier0;
}
@@ -360,6 +372,15 @@ QJsonArray McpService::format_tools_for_openai(const ToolFilter& filter, const Q
result.append(entry);
}
+ // Bound the cache. In Tool RAG mode the key encodes the activated-tool set,
+ // which is different on almost every round of every turn — left unbounded
+ // this map grows for the life of the process, each entry holding a full
+ // serialised tool array. It's a memo, not a store: dropping it wholesale
+ // when it gets big costs one rebuild.
+ if (openai_format_cache_.size() >= kMaxFormatCacheEntries) {
+ LOG_DEBUG(TAG, QString("openai_format_cache_ hit %1 entries — clearing").arg(openai_format_cache_.size()));
+ openai_format_cache_.clear();
+ }
openai_format_cache_.insert(key, result);
if (use_rag) {
@@ -386,10 +407,20 @@ std::size_t McpService::tool_count() {
// Tool Execution
// ============================================================================
-ToolResult McpService::execute_tool(const QString& server_id, const QString& tool_name, const QJsonObject& args) {
+ToolResult McpService::execute_tool(const QString& server_id, const QString& tool_name, const QJsonObject& args,
+ bool allow_defer) {
// Route to internal provider
- if (server_id == INTERNAL_SERVER_ID)
- return McpProvider::instance().call_tool(tool_name, args);
+ if (server_id == INTERNAL_SERVER_ID) {
+ if (!allow_defer)
+ return McpProvider::instance().call_tool(tool_name, args);
+ // How long a supports_async tool may run inline before it backgrounds
+ // itself. Clamped: below ~250 ms almost everything would background
+ // (costing an extra round-trip for nothing), above ~30 s the deferral
+ // stops buying anything over just blocking.
+ const int grace_ms =
+ std::clamp(AppConfig::instance().get("mcp/job_grace_ms", QVariant(kMcpJobGraceMs)).toInt(), 250, 30000);
+ return McpProvider::instance().call_tool_or_defer(tool_name, args, grace_ms);
+ }
// Route to external server — through the same Phase 6.3 auth/destructive
// gate internal tools get inside call_tool_async (previously this path
@@ -432,7 +463,8 @@ ToolResult McpService::execute_tool(const QString& server_id, const QString& too
return ToolResult::ok(text);
}
-ToolResult McpService::execute_openai_function(const QString& function_name, const QJsonObject& args) {
+ToolResult McpService::execute_openai_function(const QString& function_name, const QJsonObject& args,
+ bool allow_defer) {
auto [server_id, tool_name] = McpProvider::parse_openai_function_name(function_name);
if (server_id.isEmpty() || tool_name.isEmpty()) {
@@ -441,7 +473,7 @@ ToolResult McpService::execute_openai_function(const QString& function_name, con
}
LOG_INFO(TAG, QString("Dispatch: %1 -> server=%2 tool=%3").arg(function_name, server_id, tool_name));
- auto result = execute_tool(server_id, tool_name, args);
+ auto result = execute_tool(server_id, tool_name, args, allow_defer);
LOG_INFO(TAG, QString("Dispatch result: %1 success=%2").arg(tool_name, result.success ? "true" : "false"));
return result;
}
diff --git a/fincept-qt/src/mcp/McpService.h b/fincept-qt/src/mcp/McpService.h
index c51baea0e..deb80df5f 100644
--- a/fincept-qt/src/mcp/McpService.h
+++ b/fincept-qt/src/mcp/McpService.h
@@ -48,11 +48,22 @@ class McpService {
// ── Unified Tool Execution ──────────────────────────────────────────
- /// Route to internal or external server
- ToolResult execute_tool(const QString& server_id, const QString& tool_name, const QJsonObject& args);
+ /// Route to internal or external server.
+ ///
+ /// `allow_defer` opts the call into the long-running-job protocol: an
+ /// internal tool that declares `supports_async` and overruns its grace
+ /// window returns a `{job_id, status:"running"}` receipt instead of
+ /// blocking. Only the interactive LLM tool loop passes true — it is the
+ /// only caller that knows about the `job_*` tools. Workflow nodes, the
+ /// Python agent bridge, and internal C++ callers leave it false and keep
+ /// blocking semantics. External servers never defer: the MCP wire carries
+ /// no async metadata.
+ ToolResult execute_tool(const QString& server_id, const QString& tool_name, const QJsonObject& args,
+ bool allow_defer = false);
/// Execute from OpenAI function-call format ("serverId__toolName")
- ToolResult execute_openai_function(const QString& function_name, const QJsonObject& args);
+ ToolResult execute_openai_function(const QString& function_name, const QJsonObject& args,
+ bool allow_defer = false);
/// Phase 4: async equivalent of execute_openai_function. Returns a
/// QFuture<ToolResult> so callers (LlmService dispatch loops in
@@ -94,6 +105,10 @@ class McpService {
// ~150 KB OpenAI JSON schema on every LLM turn.
QHash<QByteArray, std::vector<UnifiedTool>> filtered_tools_cache_;
QHash<QByteArray, QJsonArray> openai_format_cache_;
+ // In Tool RAG mode the format-cache key encodes the activated-tool set, so
+ // it varies per round and the map would otherwise grow unbounded across a
+ // session. Cleared wholesale on overflow — it is a memo, not a store.
+ static constexpr int kMaxFormatCacheEntries = 64;
void refresh_cache(); // requires mutex_ held
bool is_cache_valid() const; // requires mutex_ held
diff --git a/fincept-qt/src/mcp/McpTypes.h b/fincept-qt/src/mcp/McpTypes.h
index 30fe259fc..55785126d 100644
--- a/fincept-qt/src/mcp/McpTypes.h
+++ b/fincept-qt/src/mcp/McpTypes.h
@@ -21,6 +21,13 @@ namespace fincept::mcp {
/// the 30s default referenced by ToolContext, ToolDef, and McpProvider.
constexpr int kMcpDefaultTimeoutMs = 30000;
+/// How long an LLM-originated call to a `supports_async` tool waits for an
+/// inline result before it converts to a background job and hands back a
+/// receipt. Tuned so genuinely fast paths (warm cache, cheap query) still
+/// answer in one round-trip while a real long-runner backgrounds promptly.
+/// Overridable via the `mcp/job_grace_ms` setting.
+constexpr int kMcpJobGraceMs = 2500;
+
// ============================================================================
// Tool Result — returned by tool handlers
// ============================================================================
@@ -292,6 +299,23 @@ struct ToolDef {
/// Per-call overrides are merged from `_meta.timeout_ms` (Phase 6).
int default_timeout_ms = kMcpDefaultTimeoutMs;
+ /// Opt-in to the async job protocol. When true, an LLM-originated call that
+ /// hasn't finished within the grace window (see `kMcpJobGraceMs`) returns a
+ /// `{job_id, status:"running"}` receipt instead of blocking, and the work
+ /// continues in the background under `JobRegistry`. The model then polls
+ /// `job_status` / collects with `job_result`.
+ ///
+ /// Set this on tools whose p95 runtime is measured in tens of seconds —
+ /// agent runs, backtests, bulk EDGAR pulls. Leave it false for everything
+ /// else: a fast tool that returns a receipt costs the model an extra
+ /// round-trip for no benefit. Tools that finish inside the grace window
+ /// return their real result inline regardless, so setting it on a
+ /// sometimes-slow tool is safe.
+ ///
+ /// Requires `async_handler` — a sync handler cannot be interrupted or
+ /// backgrounded, so the flag is ignored for those.
+ bool supports_async = false;
+
// ── Phase 6: Authorization ──────────────────────────────────────────
/// Required auth level — checked by McpProvider::call_tool before the
/// handler runs. Defaults to None (no gate) so untagged tools behave
diff --git a/fincept-qt/src/mcp/ResultStore.cpp b/fincept-qt/src/mcp/ResultStore.cpp
new file mode 100644
index 000000000..f9b761fb3
--- /dev/null
+++ b/fincept-qt/src/mcp/ResultStore.cpp
@@ -0,0 +1,209 @@
+// ResultStore.cpp — Overflow store + size shaper for oversized MCP tool results.
+
+#include "mcp/ResultStore.h"
+
+#include "core/logging/Logger.h"
+
+#include <QDateTime>
+#include <QJsonArray>
+#include <QJsonDocument>
+#include <QJsonObject>
+
+#include <algorithm>
+
+namespace fincept::mcp {
+
+static constexpr const char* TAG = "ResultStore";
+
+static int compact_size(const QJsonValue& v) {
+ // QJsonDocument only wraps objects/arrays, so scalars are measured inside a
+ // throwaway array and the two bracket bytes discounted.
+ if (v.isObject())
+ return static_cast<int>(QJsonDocument(v.toObject()).toJson(QJsonDocument::Compact).size());
+ if (v.isArray())
+ return static_cast<int>(QJsonDocument(v.toArray()).toJson(QJsonDocument::Compact).size());
+ QJsonArray wrap;
+ wrap.append(v);
+ return std::max(0, static_cast<int>(QJsonDocument(wrap).toJson(QJsonDocument::Compact).size()) - 2);
+}
+
+static QByteArray to_compact(const QJsonValue& v) {
+ if (v.isObject())
+ return QJsonDocument(v.toObject()).toJson(QJsonDocument::Compact);
+ if (v.isArray())
+ return QJsonDocument(v.toArray()).toJson(QJsonDocument::Compact);
+ QJsonArray wrap;
+ wrap.append(v);
+ QByteArray b = QJsonDocument(wrap).toJson(QJsonDocument::Compact);
+ return b.mid(1, b.size() - 2); // strip the wrapping brackets
+}
+
+// ============================================================================
+// Shaping
+// ============================================================================
+
+// One shaping pass at a fixed aggressiveness. Recurses the whole value; callers
+// re-run it with tighter limits until the serialised size fits.
+static QJsonValue clamp_value(const QJsonValue& v, int max_items, int max_chars, ShrinkStats& st) {
+ if (v.isString()) {
+ const QString s = v.toString();
+ if (static_cast<int>(s.size()) <= max_chars)
+ return v;
+ ++st.strings_clipped;
+ return QJsonValue(s.left(max_chars) + QStringLiteral("…[+%1 chars]").arg(s.size() - max_chars));
+ }
+
+ if (v.isArray()) {
+ const QJsonArray in = v.toArray();
+ QJsonArray out;
+ const int keep = std::min(max_items, static_cast<int>(in.size()));
+ for (int i = 0; i < keep; ++i)
+ out.append(clamp_value(in.at(i), max_items, max_chars, st));
+ if (in.size() > keep) {
+ ++st.arrays_trimmed;
+ // A trailing marker keeps the omission visible in-place. Without it
+ // the model reads a 5-item array as complete and reasons off a
+ // truncated dataset — a silent-wrong-answer bug, not a cosmetic one.
+ out.append(QJsonValue(QStringLiteral("…[%1 more items omitted — use result_fetch for the full payload]")
+ .arg(in.size() - keep)));
+ }
+ return out;
+ }
+
+ if (v.isObject()) {
+ const QJsonObject in = v.toObject();
+ QJsonObject out;
+ for (auto it = in.constBegin(); it != in.constEnd(); ++it)
+ out.insert(it.key(), clamp_value(it.value(), max_items, max_chars, st));
+ return out;
+ }
+
+ return v; // scalars pass through
+}
+
+ShrinkStats shrink_json(QJsonValue& value, int budget_bytes) {
+ ShrinkStats st;
+ st.original_bytes = compact_size(value);
+ st.final_bytes = st.original_bytes;
+ if (budget_bytes <= 0 || st.original_bytes <= budget_bytes)
+ return st;
+
+ // Progressively harsher passes. Each is a full re-walk, but this only runs
+ // on payloads already known to be over budget, and the early passes cut the
+ // bulk of the common cases (a long array of rows) on the first try.
+ struct Pass {
+ int max_items;
+ int max_chars;
+ };
+ static constexpr Pass kPasses[] = {
+ {50, 2000}, {20, 1000}, {10, 400}, {5, 200}, {2, 120}, {1, 80},
+ };
+
+ for (const Pass& p : kPasses) {
+ ShrinkStats attempt;
+ attempt.original_bytes = st.original_bytes;
+ QJsonValue candidate = clamp_value(value, p.max_items, p.max_chars, attempt);
+ const int size = compact_size(candidate);
+ if (size <= budget_bytes) {
+ value = candidate;
+ attempt.truncated = true;
+ attempt.final_bytes = size;
+ return attempt;
+ }
+ }
+
+ // Nothing fit — the payload is wide rather than deep (thousands of scalar
+ // keys). Hand back a stub; the full text lives in the ResultStore.
+ QJsonObject stub{
+ {"__truncated", true},
+ {"__original_bytes", st.original_bytes},
+ {"__note", QStringLiteral("Payload too large to preview — use result_fetch to page through it.")},
+ };
+ value = stub;
+ st.truncated = true;
+ st.final_bytes = compact_size(value);
+ return st;
+}
+
+// ============================================================================
+// Store
+// ============================================================================
+
+ResultStore& ResultStore::instance() {
+ static ResultStore s;
+ return s;
+}
+
+QString ResultStore::put(const QString& tool, const QJsonValue& payload) {
+ QMutexLocker lock(&mutex_);
+ sweep_locked();
+
+ const QString id = QStringLiteral("res_%1").arg(++next_id_, 6, 16, QLatin1Char('0'));
+ Entry e;
+ e.tool = tool;
+ e.text = to_compact(payload);
+ e.stored_ms = QDateTime::currentMSecsSinceEpoch();
+ entries_.insert(id, std::move(e));
+ return id;
+}
+
+ResultStore::Page ResultStore::page(const QString& id, int offset, int limit) const {
+ QMutexLocker lock(&mutex_);
+ auto it = entries_.constFind(id);
+ if (it == entries_.constEnd())
+ return {};
+
+ Page p;
+ p.found = true;
+ p.tool = it->tool;
+ p.total_bytes = static_cast<int>(it->text.size());
+ p.offset = std::clamp(offset, 0, p.total_bytes);
+ const int take = std::clamp(limit, 1, p.total_bytes - p.offset);
+ p.text = QString::fromUtf8(it->text.mid(p.offset, take));
+ p.returned = take;
+ p.has_more = p.offset + take < p.total_bytes;
+ return p;
+}
+
+void ResultStore::clear() {
+ QMutexLocker lock(&mutex_);
+ entries_.clear();
+}
+
+void ResultStore::sweep_locked() {
+ const qint64 now = QDateTime::currentMSecsSinceEpoch();
+ qint64 total = 0;
+ for (auto it = entries_.begin(); it != entries_.end();) {
+ if (now - it->stored_ms > kTtlMs) {
+ it = entries_.erase(it);
+ } else {
+ total += it->text.size();
+ ++it;
+ }
+ }
+
+ if (entries_.size() <= kMaxEntries && total <= kMaxTotalBytes)
+ return;
+
+ // Over a cap — drop oldest first until both budgets are satisfied.
+ std::vector<QPair<qint64, QString>> by_age;
+ by_age.reserve(static_cast<std::size_t>(entries_.size()));
+ for (auto it = entries_.constBegin(); it != entries_.constEnd(); ++it)
+ by_age.push_back({it->stored_ms, it.key()});
+ std::sort(by_age.begin(), by_age.end(), [](const auto& a, const auto& b) { return a.first < b.first; });
+
+ for (const auto& entry : by_age) {
+ if (entries_.size() <= kMaxEntries && total <= kMaxTotalBytes)
+ break;
+ auto it = entries_.constFind(entry.second);
+ if (it == entries_.constEnd())
+ continue;
+ total -= it->text.size();
+ entries_.remove(entry.second);
+ }
+ LOG_DEBUG(TAG, QString("Swept overflow store — %1 entries, %2 KB retained")
+ .arg(entries_.size())
+ .arg(total / 1024));
+}
+
+} // namespace fincept::mcp
diff --git a/fincept-qt/src/mcp/ResultStore.h b/fincept-qt/src/mcp/ResultStore.h
new file mode 100644
index 000000000..b135ca331
--- /dev/null
+++ b/fincept-qt/src/mcp/ResultStore.h
@@ -0,0 +1,112 @@
+#pragma once
+// ResultStore.h — Overflow store + size shaper for oversized MCP tool results.
+//
+// Problem this solves
+// -------------------
+// The structured tool loop used to splice every tool result into the
+// conversation verbatim:
+//
+// loop_messages.append({role:"tool", content: QJsonDocument(tr.to_json())});
+//
+// with no size cap at all. `edgar_get_filing` returns a whole SEC filing;
+// several M&A / news / portfolio tools return unbounded arrays. Worse, the loop
+// re-posts the entire message array on every subsequent round, so one 60 KB
+// result costs 60 KB of input tokens per round for the rest of the turn — up to
+// 200 rounds (`max_tool_rounds` clamp).
+//
+// The fix has two halves, both here:
+//
+// 1. `shrink_json` — structure-aware shaping. Rather than clipping the JSON
+// text mid-token (which yields invalid JSON the model then has to guess
+// at), it walks the value and trims arrays / long strings until the
+// serialised form fits a byte budget, leaving valid JSON that keeps its
+// shape. The model can still see what the result *looks* like.
+//
+// 2. `ResultStore` — the trimmed-away remainder isn't lost. The full payload
+// is parked here under a short id and the envelope tells the model it can
+// page through it with `result_fetch(result_id, offset, limit)`. Nothing
+// is silently dropped; the model pays for detail only when it asks.
+//
+// Retention is deliberately short and bounded (see kTtlMs / kMaxEntries /
+// kMaxTotalBytes): this is a within-turn scratch buffer, not a cache.
+//
+// Thread safety: all methods callable from any thread; one QMutex guards the map.
+
+#include <QByteArray>
+#include <QHash>
+#include <QJsonValue>
+#include <QMutex>
+#include <QString>
+
+namespace fincept::mcp {
+
+/// What `shrink_json` had to do to fit the budget. `truncated == false` means
+/// the value was already small enough and is untouched.
+struct ShrinkStats {
+ bool truncated = false;
+ int original_bytes = 0;
+ int final_bytes = 0;
+ int arrays_trimmed = 0;
+ int strings_clipped = 0;
+};
+
+/// Shrink `value` in place until its compact JSON serialisation fits
+/// `budget_bytes`. Arrays lose their tail (a trailing marker string records how
+/// many items went); long strings are clipped with a "+N chars" suffix. The
+/// result is always valid JSON.
+///
+/// If even the harshest pass can't fit the budget (e.g. one enormous object with
+/// thousands of scalar keys), the value is replaced with a stub object noting
+/// the original size — the caller is expected to have stashed the full payload
+/// in a ResultStore first.
+ShrinkStats shrink_json(QJsonValue& value, int budget_bytes);
+
+class ResultStore {
+ public:
+ static ResultStore& instance();
+
+ /// Park a full payload. Returns a short id ("res_0001a3") for the model to
+ /// quote back to `result_fetch`.
+ QString put(const QString& tool, const QJsonValue& payload);
+
+ struct Page {
+ bool found = false;
+ QString tool;
+ QString text; // compact-JSON slice [offset, offset+limit)
+ int offset = 0;
+ int returned = 0;
+ int total_bytes = 0;
+ bool has_more = false;
+ };
+
+ /// Page through a stored payload's compact JSON text. Slicing text rather
+ /// than re-walking the structure keeps paging O(limit) and lets the model
+ /// resume exactly where it stopped.
+ Page page(const QString& id, int offset, int limit) const;
+
+ void clear();
+
+ ResultStore(const ResultStore&) = delete;
+ ResultStore& operator=(const ResultStore&) = delete;
+
+ private:
+ ResultStore() = default;
+
+ struct Entry {
+ QString tool;
+ QByteArray text; // compact JSON, serialised once at put()
+ qint64 stored_ms = 0;
+ };
+
+ void sweep_locked();
+
+ mutable QMutex mutex_;
+ QHash<QString, Entry> entries_;
+ quint64 next_id_ = 0;
+
+ static constexpr qint64 kTtlMs = 15 * 60 * 1000;
+ static constexpr int kMaxEntries = 24;
+ static constexpr qint64 kMaxTotalBytes = 32 * 1024 * 1024;
+};
+
+} // namespace fincept::mcp
diff --git a/fincept-qt/src/mcp/SchemaValidator.cpp b/fincept-qt/src/mcp/SchemaValidator.cpp
index 5c19f36e9..f1a450023 100644
--- a/fincept-qt/src/mcp/SchemaValidator.cpp
+++ b/fincept-qt/src/mcp/SchemaValidator.cpp
@@ -55,7 +55,14 @@ QString validate_typed(const QString& /*key*/, const ToolParam& p, const QJsonVa
if (!p.enum_values.isEmpty() && !p.enum_values.contains(s))
return "must be one of [" + p.enum_values.join(",") + "]";
if (!p.pattern.isEmpty()) {
- QRegularExpression rx(p.pattern);
+ // anchoredPattern() wraps in \A(?:...)\z so the pattern must match
+ // the WHOLE value. QRegularExpression::match() is a substring
+ // search: an unanchored pattern like "[a-z]+" would happily accept
+ // "../../etc/passwd", and even an "^...$" pattern accepts a
+ // trailing newline because $ matches before a final \n. Tool
+ // patterns are a security control (see run_python_script), so they
+ // must be full-string.
+ QRegularExpression rx(QRegularExpression::anchoredPattern(p.pattern));
if (!rx.match(s).hasMatch())
return "does not match pattern " + p.pattern;
}
@@ -91,7 +98,8 @@ QString validate_legacy(const QString& /*key*/, const QJsonObject& spec, const Q
}
}
if (expected == "string" && spec.contains("pattern")) {
- QRegularExpression rx(spec["pattern"].toString());
+ // Full-string match — see the note in validate_typed().
+ QRegularExpression rx(QRegularExpression::anchoredPattern(spec["pattern"].toString()));
if (!rx.match(v.toString()).hasMatch())
return "does not match pattern " + spec["pattern"].toString();
}
diff --git a/fincept-qt/src/mcp/tools/AgentsTools_Execution.cpp b/fincept-qt/src/mcp/tools/AgentsTools_Execution.cpp
index ee339260f..b0ff58d5d 100644
--- a/fincept-qt/src/mcp/tools/AgentsTools_Execution.cpp
+++ b/fincept-qt/src/mcp/tools/AgentsTools_Execution.cpp
@@ -36,6 +36,11 @@ void agents_internal::register_execution_tools(std::vector<ToolDef>& tools) {
t.category = "agents";
t.is_destructive = true;
t.default_timeout_ms = kDefaultAgentTimeoutMs;
+ // Agent runs are the canonical long-running tool: a 5-minute budget that
+ // used to hold the LLM's HTTP turn open for its entire duration. Opting
+ // into the job protocol lets a slow run background itself and hand back a
+ // receipt; runs that finish inside the grace window still answer inline.
+ t.supports_async = true;
t.input_schema = ToolSchemaBuilder()
.string("query", "Natural-language query for the agent")
.required()
@@ -60,6 +65,11 @@ void agents_internal::register_execution_tools(std::vector<ToolDef>& tools) {
t.category = "agents";
t.is_destructive = true;
t.default_timeout_ms = kDefaultAgentTimeoutMs;
+ // Agent runs are the canonical long-running tool: a 5-minute budget that
+ // used to hold the LLM's HTTP turn open for its entire duration. Opting
+ // into the job protocol lets a slow run background itself and hand back a
+ // receipt; runs that finish inside the grace window still answer inline.
+ t.supports_async = true;
t.input_schema = ToolSchemaBuilder()
.string("query", "Natural-language query for the agent")
.required()
@@ -126,6 +136,11 @@ void agents_internal::register_execution_tools(std::vector<ToolDef>& tools) {
t.category = "agents";
t.is_destructive = true;
t.default_timeout_ms = kDefaultAgentTimeoutMs;
+ // Agent runs are the canonical long-running tool: a 5-minute budget that
+ // used to hold the LLM's HTTP turn open for its entire duration. Opting
+ // into the job protocol lets a slow run background itself and hand back a
+ // receipt; runs that finish inside the grace window still answer inline.
+ t.supports_async = true;
t.input_schema = ToolSchemaBuilder()
.string("query", "Query to fan out")
.required()
@@ -192,6 +207,11 @@ void agents_internal::register_execution_tools(std::vector<ToolDef>& tools) {
t.category = "agents";
t.is_destructive = true;
t.default_timeout_ms = kDefaultAgentTimeoutMs;
+ // Agent runs are the canonical long-running tool: a 5-minute budget that
+ // used to hold the LLM's HTTP turn open for its entire duration. Opting
+ // into the job protocol lets a slow run background itself and hand back a
+ // receipt; runs that finish inside the grace window still answer inline.
+ t.supports_async = true;
t.input_schema = ToolSchemaBuilder()
.string("symbol", "Ticker symbol (e.g. AAPL)")
.required()
@@ -216,6 +236,11 @@ void agents_internal::register_execution_tools(std::vector<ToolDef>& tools) {
t.category = "agents";
t.is_destructive = true;
t.default_timeout_ms = kDefaultAgentTimeoutMs;
+ // Agent runs are the canonical long-running tool: a 5-minute budget that
+ // used to hold the LLM's HTTP turn open for its entire duration. Opting
+ // into the job protocol lets a slow run background itself and hand back a
+ // receipt; runs that finish inside the grace window still answer inline.
+ t.supports_async = true;
t.input_schema = ToolSchemaBuilder()
.object("portfolio_data", "Portfolio snapshot (holdings, target weights, constraints)")
.build();
@@ -235,6 +260,11 @@ void agents_internal::register_execution_tools(std::vector<ToolDef>& tools) {
t.category = "agents";
t.is_destructive = true;
t.default_timeout_ms = kDefaultAgentTimeoutMs;
+ // Agent runs are the canonical long-running tool: a 5-minute budget that
+ // used to hold the LLM's HTTP turn open for its entire duration. Opting
+ // into the job protocol lets a slow run background itself and hand back a
+ // receipt; runs that finish inside the grace window still answer inline.
+ t.supports_async = true;
t.input_schema = ToolSchemaBuilder().object("portfolio_data", "Portfolio snapshot").build();
t.async_handler = [bridge_workflow_no_reqid](const QJsonObject& args, ToolContext ctx,
std::shared_ptr<QPromise<ToolResult>> promise) {
@@ -252,6 +282,11 @@ void agents_internal::register_execution_tools(std::vector<ToolDef>& tools) {
t.category = "agents";
t.is_destructive = true;
t.default_timeout_ms = kDefaultAgentTimeoutMs;
+ // Agent runs are the canonical long-running tool: a 5-minute budget that
+ // used to hold the LLM's HTTP turn open for its entire duration. Opting
+ // into the job protocol lets a slow run background itself and hand back a
+ // receipt; runs that finish inside the grace window still answer inline.
+ t.supports_async = true;
t.input_schema = ToolSchemaBuilder()
.string("analysis_type", "Analysis type identifier")
.required()
@@ -277,6 +312,11 @@ void agents_internal::register_execution_tools(std::vector<ToolDef>& tools) {
t.category = "agents";
t.is_destructive = true;
t.default_timeout_ms = kDefaultAgentTimeoutMs;
+ // Agent runs are the canonical long-running tool: a 5-minute budget that
+ // used to hold the LLM's HTTP turn open for its entire duration. Opting
+ // into the job protocol lets a slow run background itself and hand back a
+ // receipt; runs that finish inside the grace window still answer inline.
+ t.supports_async = true;
t.input_schema = ToolSchemaBuilder()
.string("query", "Query for the team")
.required()
@@ -302,6 +342,11 @@ void agents_internal::register_execution_tools(std::vector<ToolDef>& tools) {
t.category = "agents";
t.is_destructive = true;
t.default_timeout_ms = kDefaultAgentTimeoutMs;
+ // Agent runs are the canonical long-running tool: a 5-minute budget that
+ // used to hold the LLM's HTTP turn open for its entire duration. Opting
+ // into the job protocol lets a slow run background itself and hand back a
+ // receipt; runs that finish inside the grace window still answer inline.
+ t.supports_async = true;
t.input_schema = ToolSchemaBuilder()
.string("workflow_type", "Workflow type identifier")
.required()
@@ -327,6 +372,11 @@ void agents_internal::register_execution_tools(std::vector<ToolDef>& tools) {
t.category = "agents";
t.is_destructive = true;
t.default_timeout_ms = kDefaultAgentTimeoutMs;
+ // Agent runs are the canonical long-running tool: a 5-minute budget that
+ // used to hold the LLM's HTTP turn open for its entire duration. Opting
+ // into the job protocol lets a slow run background itself and hand back a
+ // receipt; runs that finish inside the grace window still answer inline.
+ t.supports_async = true;
t.input_schema = ToolSchemaBuilder()
.string("query", "Natural-language query")
.required()
@@ -374,6 +424,11 @@ void agents_internal::register_execution_tools(std::vector<ToolDef>& tools) {
t.category = "agents";
t.is_destructive = true;
t.default_timeout_ms = kDefaultAgentTimeoutMs;
+ // Agent runs are the canonical long-running tool: a 5-minute budget that
+ // used to hold the LLM's HTTP turn open for its entire duration. Opting
+ // into the job protocol lets a slow run background itself and hand back a
+ // receipt; runs that finish inside the grace window still answer inline.
+ t.supports_async = true;
t.input_schema = ToolSchemaBuilder()
.string("query", "Natural-language query")
.required()
diff --git a/fincept-qt/src/mcp/tools/JobTools.cpp b/fincept-qt/src/mcp/tools/JobTools.cpp
new file mode 100644
index 000000000..529325ef2
--- /dev/null
+++ b/fincept-qt/src/mcp/tools/JobTools.cpp
@@ -0,0 +1,203 @@
+// JobTools.cpp — Meta-tools for long-running jobs (job_*) and oversized
+// results (result_fetch).
+//
+// These are the model's half of the two protocols introduced alongside
+// JobRegistry and ResultStore:
+//
+// Long-running work — a tool with `supports_async` that overruns its grace
+// window hands back `{job_id, status:"running"}` instead of blocking. The
+// model polls `job_status` (with `wait_ms`, so one call can cover the whole
+// run) and collects with `job_result`.
+//
+// Oversized results — a tool result too large to splice into the transcript
+// is shrunk to a preview and parked in the ResultStore. The envelope carries
+// a `result_id` the model pages through with `result_fetch` if — and only if
+// — it actually needs the detail.
+//
+// Both are registered in Tier-0 (see McpService::tier_0_tool_names) because a
+// model that has been handed a receipt must be able to redeem it without first
+// running a `tool_list` search to discover how.
+
+#include "mcp/tools/JobTools.h"
+
+#include "core/logging/Logger.h"
+#include "mcp/JobRegistry.h"
+#include "mcp/ResultStore.h"
+#include "mcp/ToolSchemaBuilder.h"
+
+#include <QJsonArray>
+#include <QJsonObject>
+
+namespace fincept::mcp::tools {
+
+static constexpr const char* TAG = "JobTools";
+
+std::vector<ToolDef> get_job_tools() {
+ std::vector<ToolDef> tools;
+
+ // ── job_status ───────────────────────────────────────────────────────
+ //
+ // `wait_ms` is the token-efficiency lever. Without it a model polls in a
+ // tight loop and each poll costs a full tool round (request + tool message
+ // + the whole re-sent transcript). With it, a 90 s job costs ~2 polls
+ // instead of ~30.
+ {
+ ToolDef t;
+ t.name = "job_status";
+ t.description = "Check a background job started by a long-running tool. "
+ "Pass wait_ms to block until the job finishes instead of polling repeatedly — "
+ "this is much cheaper than calling repeatedly in a loop. "
+ "Returns {job_id, tool, status, elapsed_ms, progress?, message?}. "
+ "When status is 'succeeded' or 'failed', call job_result to collect the payload.";
+ t.category = "meta";
+ t.input_schema = ToolSchemaBuilder()
+ .string("job_id", "Job id returned by the long-running tool")
+ .required()
+ .length(1, 64)
+ .integer("wait_ms", "Block up to this many ms waiting for the job to finish "
+ "(0 = return immediately). Prefer a large value — one "
+ "long wait costs far fewer tokens than many short polls.")
+ .default_int(0)
+ .between(0, JobRegistry::max_wait_ms())
+ .build();
+ // Blocking for wait_ms is the whole point, so the handler's own budget
+ // must comfortably exceed the longest permitted wait.
+ t.default_timeout_ms = JobRegistry::max_wait_ms() + 5000;
+ t.handler = [](const QJsonObject& args) -> ToolResult {
+ const QString id = args["job_id"].toString();
+ const int wait_ms = args["wait_ms"].toInt(0);
+
+ auto snap = wait_ms > 0 ? JobRegistry::instance().wait_for(id, wait_ms)
+ : JobRegistry::instance().status(id);
+ if (!snap)
+ return ToolResult::fail("Unknown job id: " + id +
+ " (it may have expired — jobs are kept for 15 minutes)");
+
+ QJsonObject out = snap->to_json();
+ if (snap->is_finished() && !snap->result_collected)
+ out["next"] = QStringLiteral("call job_result(job_id='%1') to collect the payload").arg(id);
+ return ToolResult::ok_data(out);
+ };
+ tools.push_back(std::move(t));
+ }
+
+ // ── job_result ───────────────────────────────────────────────────────
+ {
+ ToolDef t;
+ t.name = "job_result";
+ t.description = "Collect the payload of a finished background job. "
+ "Fails while the job is still running — use job_status(wait_ms=…) first.";
+ t.category = "meta";
+ t.input_schema =
+ ToolSchemaBuilder().string("job_id", "Job id to collect").required().length(1, 64).build();
+ t.handler = [](const QJsonObject& args) -> ToolResult {
+ const QString id = args["job_id"].toString();
+ auto snap = JobRegistry::instance().status(id);
+ if (!snap)
+ return ToolResult::fail("Unknown job id: " + id +
+ " (it may have expired — jobs are kept for 15 minutes)");
+ if (!snap->is_finished())
+ return ToolResult::fail(QString("Job %1 is still running (%2 ms elapsed). "
+ "Call job_status(job_id='%1', wait_ms=20000) to wait for it.")
+ .arg(id)
+ .arg(snap->elapsed_ms()));
+
+ auto result = JobRegistry::instance().take_result(id);
+ if (!result)
+ return ToolResult::fail("Job " + id + " finished but its result is no longer available");
+ // Returned verbatim — the LLM boundary applies the size cap and
+ // overflow-store handoff uniformly for every tool result, so
+ // doing it again here would double-truncate.
+ return *result;
+ };
+ tools.push_back(std::move(t));
+ }
+
+ // ── job_cancel ───────────────────────────────────────────────────────
+ {
+ ToolDef t;
+ t.name = "job_cancel";
+ t.description = "Request cancellation of a running background job. The job keeps reporting "
+ "'running' until the underlying tool actually unwinds — poll job_status to confirm.";
+ t.category = "meta";
+ t.input_schema =
+ ToolSchemaBuilder().string("job_id", "Job id to cancel").required().length(1, 64).build();
+ t.handler = [](const QJsonObject& args) -> ToolResult {
+ const QString id = args["job_id"].toString();
+ if (!JobRegistry::instance().request_cancel(id))
+ return ToolResult::fail("Job " + id + " is unknown or already finished");
+ return ToolResult::ok("Cancellation requested for " + id,
+ QJsonObject{{"job_id", id}, {"status", "cancelling"}});
+ };
+ tools.push_back(std::move(t));
+ }
+
+ // ── job_list ─────────────────────────────────────────────────────────
+ {
+ ToolDef t;
+ t.name = "job_list";
+ t.description = "List background jobs. Defaults to running jobs only — useful to check whether "
+ "work you started earlier is still in flight before starting it again.";
+ t.category = "meta";
+ t.input_schema = ToolSchemaBuilder()
+ .boolean("include_finished", "Also list jobs that have already finished")
+ .default_bool(false)
+ .build();
+ t.handler = [](const QJsonObject& args) -> ToolResult {
+ const bool include_finished = args["include_finished"].toBool(false);
+ QJsonArray rows;
+ for (const auto& s : JobRegistry::instance().list(include_finished))
+ rows.append(s.to_json());
+ return ToolResult::ok_data(QJsonObject{{"count", rows.size()}, {"jobs", rows}});
+ };
+ tools.push_back(std::move(t));
+ }
+
+ // ── result_fetch ─────────────────────────────────────────────────────
+ //
+ // Deliberately byte-paged rather than "give me the whole thing": the point
+ // of the overflow store is that the model pays for detail incrementally.
+ {
+ ToolDef t;
+ t.name = "result_fetch";
+ t.description = "Page through the full payload of a tool result that was too large to include "
+ "inline. Use the result_id from a truncated result envelope. "
+ "Returns a slice of the raw JSON text plus has_more — request only what you need, "
+ "each page costs tokens.";
+ t.category = "meta";
+ t.input_schema = ToolSchemaBuilder()
+ .string("result_id", "result_id from the truncated result envelope")
+ .required()
+ .length(1, 64)
+ .integer("offset", "Byte offset to start from")
+ .default_int(0)
+ .between(0, 100000000)
+ .integer("limit", "Bytes to return (max 20000)")
+ .default_int(6000)
+ .between(1, 20000)
+ .build();
+ t.handler = [](const QJsonObject& args) -> ToolResult {
+ const QString id = args["result_id"].toString();
+ const auto page = ResultStore::instance().page(id, args["offset"].toInt(0), args["limit"].toInt(6000));
+ if (!page.found)
+ return ToolResult::fail("Unknown result_id: " + id +
+ " (stored payloads expire after 15 minutes)");
+ return ToolResult::ok_data(QJsonObject{
+ {"result_id", id},
+ {"tool", page.tool},
+ {"offset", page.offset},
+ {"returned", page.returned},
+ {"total_bytes", page.total_bytes},
+ {"has_more", page.has_more},
+ {"next_offset", page.offset + page.returned},
+ {"text", page.text},
+ });
+ };
+ tools.push_back(std::move(t));
+ }
+
+ LOG_INFO(TAG, QString("Defined %1 job/result meta tools").arg(tools.size()));
+ return tools;
+}
+
+} // namespace fincept::mcp::tools
diff --git a/fincept-qt/src/mcp/tools/JobTools.h b/fincept-qt/src/mcp/tools/JobTools.h
new file mode 100644
index 000000000..be730c2fc
--- /dev/null
+++ b/fincept-qt/src/mcp/tools/JobTools.h
@@ -0,0 +1,12 @@
+#pragma once
+// JobTools.h — Meta-tools for long-running jobs and oversized results.
+
+#include "mcp/McpTypes.h"
+
+#include <vector>
+
+namespace fincept::mcp::tools {
+
+std::vector<ToolDef> get_job_tools();
+
+} // namespace fincept::mcp::tools
diff --git a/fincept-qt/src/mcp/tools/PaperTradingTools.cpp b/fincept-qt/src/mcp/tools/PaperTradingTools.cpp
index e1ada2ece..0a64c32a6 100644
--- a/fincept-qt/src/mcp/tools/PaperTradingTools.cpp
+++ b/fincept-qt/src/mcp/tools/PaperTradingTools.cpp
@@ -165,8 +165,13 @@ std::vector<ToolDef> get_paper_trading_tools() {
try {
auto order = trading::pt_place_order(portfolio_id, symbol, side, order_type, quantity, price,
stop_price, reduce_only);
- LOG_INFO(TAG,
- QString("Paper order placed: %1 %2 %.4f %3").arg(side, symbol).arg(quantity).arg(order.id));
+ // %.4f is printf syntax, not a QString place marker — it left
+ // the quantity unformatted, shifted order.id off the end and
+ // logged "QString::arg: Argument missing".
+ LOG_INFO(TAG, QString("Paper order placed: %1 %2 %3 %4")
+ .arg(side, symbol)
+ .arg(quantity, 0, 'f', 4)
+ .arg(order.id));
return ToolResult::ok("Order placed", QJsonObject{{"order_id", order.id},
{"status", order.status},
{"symbol", order.symbol},
diff --git a/fincept-qt/src/screens/about/AboutScreen.cpp b/fincept-qt/src/screens/about/AboutScreen.cpp
index 18aac4de3..8a6411cdd 100644
--- a/fincept-qt/src/screens/about/AboutScreen.cpp
+++ b/fincept-qt/src/screens/about/AboutScreen.cpp
@@ -370,14 +370,17 @@ AboutScreen::AboutScreen(QWidget* parent) : QWidget(parent) {
QString label;
QString url;
};
+ // Every URL here must resolve. docs/TRADEMARK.md and docs/CLA.md do NOT
+ // exist in the repository — those two buttons opened GitHub 404 pages.
+ // Replaced with documents that are actually checked in.
const Link links[] = {
{tr("GitHub Repository"), "https://github.com/Fincept-Corporation/FinceptTerminal"},
{tr("License (AGPL-3.0)"), "https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/LICENSE"},
{tr("Commercial License"),
"https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/docs/COMMERCIAL_LICENSE.md"},
- {tr("Trademark Policy"),
- "https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/docs/TRADEMARK.md"},
- {tr("Contributor CLA"), "https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/docs/CLA.md"},
+ {tr("Documentation"), "https://github.com/Fincept-Corporation/FinceptTerminal/tree/main/docs"},
+ {tr("Contributing Guide"),
+ "https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/docs/CONTRIBUTING.md"},
{tr("Official Website"), "https://fincept.in"},
};
@@ -386,6 +389,8 @@ AboutScreen::AboutScreen(QWidget* parent) : QWidget(parent) {
btn->setStyleSheet(LINK_BTN());
btn->setFixedHeight(36);
const QString url = links[i].url;
+ btn->setAccessibleName(links[i].label);
+ btn->setToolTip(url);
connect(btn, &QPushButton::clicked, this, [url]() { QDesktopServices::openUrl(QUrl(url)); });
grid->addWidget(btn, i / 3, i % 3);
resource_btns_.append(btn);
@@ -505,8 +510,8 @@ void AboutScreen::retranslateUi() {
resource_btns_[0]->setText(tr("GitHub Repository"));
resource_btns_[1]->setText(tr("License (AGPL-3.0)"));
resource_btns_[2]->setText(tr("Commercial License"));
- resource_btns_[3]->setText(tr("Trademark Policy"));
- resource_btns_[4]->setText(tr("Contributor CLA"));
+ resource_btns_[3]->setText(tr("Documentation"));
+ resource_btns_[4]->setText(tr("Contributing Guide"));
resource_btns_[5]->setText(tr("Official Website"));
}
diff --git a/fincept-qt/src/screens/action_center/PendingOrdersPanel.cpp b/fincept-qt/src/screens/action_center/PendingOrdersPanel.cpp
index 6f5538075..5e3a524ef 100644
--- a/fincept-qt/src/screens/action_center/PendingOrdersPanel.cpp
+++ b/fincept-qt/src/screens/action_center/PendingOrdersPanel.cpp
@@ -9,6 +9,7 @@
#include <QInputDialog>
#include <QLineEdit>
#include <QMessageBox>
+#include <QPointer>
#include <QPushButton>
#include <QSignalBlocker>
#include <QVBoxLayout>
@@ -75,7 +76,17 @@ void PendingOrdersPanel::build_ui() {
"#acApproveAll:hover{background:rgba(34,197,94,0.28);}"
"#acRejectAll{background:rgba(220,38,38,0.12);color:%8;border:1px solid %8;"
"padding:5px 16px;font-size:11px;font-weight:700;letter-spacing:0.5px;border-radius:2px;}"
- "#acRejectAll:hover{background:rgba(220,38,38,0.25);}")
+ "#acRejectAll:hover{background:rgba(220,38,38,0.25);}"
+ // Per-row action buttons: hoisted here (P7) so refresh()
+ // doesn't reparse two stylesheets per row on every update.
+ "#acRowApprove{background:rgba(34,197,94,0.14);color:%7;border:1px solid %7;"
+ "padding:2px 10px;font-size:10px;font-weight:700;border-radius:2px;}"
+ "#acRowApprove:hover{background:rgba(34,197,94,0.28);}"
+ "#acRowApprove:disabled{color:%5;border-color:%5;background:transparent;}"
+ "#acRowReject{background:rgba(220,38,38,0.12);color:%8;border:1px solid %8;"
+ "padding:2px 10px;font-size:10px;font-weight:700;border-radius:2px;}"
+ "#acRowReject:hover{background:rgba(220,38,38,0.25);}"
+ "#acRowReject:disabled{color:%5;border-color:%5;background:transparent;}")
.arg(fincept::ui::colors::DARK(), fincept::ui::colors::PANEL(), fincept::ui::colors::BORDER(),
fincept::ui::colors::AMBER(), fincept::ui::colors::TEXT_SECONDARY(),
fincept::ui::colors::TEXT_PRIMARY(), fincept::ui::colors::POSITIVE(),
@@ -173,10 +184,48 @@ void PendingOrdersPanel::build_ui() {
// ── Wiring ────────────────────────────────────────────────────────────────
connect(account_combo_, &QComboBox::currentIndexChanged, this, [this](int) { refresh(); });
connect(status_filter_, &QComboBox::currentIndexChanged, this, [this](int) { refresh(); });
+ approve_all_btn_->setAccessibleName(tr("Approve all pending orders"));
+ reject_all_btn_->setAccessibleName(tr("Reject all pending orders"));
connect(approve_all_btn_, &QPushButton::clicked, this, [this]() {
const QString acct = selected_account();
- auto ans = QMessageBox::question(this, tr("Approve All"), tr("Execute ALL pending orders now?"),
- QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
+ // Bulk approval fires every queued order at the broker in a loop with no
+ // per-order review. Say exactly how many, for which account, how many are
+ // stale, and default to No.
+ const auto pending = ActionCenter::instance().get_pending_orders(acct);
+ if (pending.isEmpty()) {
+ QMessageBox::information(this, tr("Approve All"), tr("There are no pending orders to approve."));
+ return;
+ }
+ int stale_count = 0;
+ int buys = 0;
+ int sells = 0;
+ for (const auto& p : pending) {
+ bool s = false;
+ order_age_text(p.created_at, &s);
+ if (s)
+ ++stale_count;
+ const QString a = p.action.toUpper();
+ if (a == QLatin1String("BUY"))
+ ++buys;
+ else if (a == QLatin1String("SELL"))
+ ++sells;
+ }
+ const QString scope = acct.isEmpty() ? tr("ALL accounts") : account_combo_->currentText();
+ QString body = tr("Send %1 pending order(s) to the broker now?\n\n"
+ " Account scope: %2\n"
+ " %3 BUY · %4 SELL\n\n"
+ "Each order executes immediately. There is no per-order review.")
+ .arg(pending.size())
+ .arg(scope)
+ .arg(buys)
+ .arg(sells);
+ if (stale_count > 0)
+ body += tr("\n\n⚠ %1 of these have been waiting over %2 minutes and will be REFUSED\n"
+ "as expired rather than executed. Re-place them if you still want the trade.")
+ .arg(stale_count)
+ .arg(ActionCenter::kPendingOrderTtlMinutes);
+ const auto ans =
+ QMessageBox::question(this, tr("Approve All"), body, QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
if (ans != QMessageBox::Yes)
return;
ActionCenter::instance().approve_all_pending(acct);
@@ -290,7 +339,18 @@ void PendingOrdersPanel::refresh() {
item->setForeground(QColor(fincept::ui::colors::TEXT_PRIMARY()));
table_->setItem(row, col, item);
};
- set(kColTime, o.created_at.toString("HH:mm:ss"));
+ // Time column carries the age too: a queued order's staleness is the
+ // single most important thing to know before executing it at market.
+ bool stale = false;
+ const QString age = order_age_text(o.created_at, &stale);
+ auto* time_item = new QTableWidgetItem(o.created_at.toString("HH:mm:ss"));
+ time_item->setToolTip(tr("Queued %1").arg(age));
+ const bool flag_stale = stale && o.status == QLatin1String("pending");
+ time_item->setForeground(flag_stale ? QColor(fincept::ui::colors::WARNING())
+ : QColor(fincept::ui::colors::TEXT_PRIMARY()));
+ if (flag_stale)
+ time_item->setText(o.created_at.toString("HH:mm:ss") + QStringLiteral(" ⚠"));
+ table_->setItem(row, kColTime, time_item);
// Resolve account display name.
const auto acct_meta = trading::AccountManager::instance().get_account(o.account_id);
set(kColAccount, acct_meta.display_name.isEmpty() ? o.account_id : acct_meta.display_name);
@@ -320,22 +380,40 @@ void PendingOrdersPanel::refresh() {
cl->setContentsMargins(4, 2, 4, 2);
cl->setSpacing(6);
auto* approve = new QPushButton(tr("Approve"));
+ approve->setObjectName(QStringLiteral("acRowApprove"));
approve->setCursor(Qt::PointingHandCursor);
- approve->setStyleSheet(QString("QPushButton{background:rgba(34,197,94,0.14);color:%1;"
- "border:1px solid %1;padding:2px 10px;font-size:10px;"
- "font-weight:700;border-radius:2px;}"
- "QPushButton:hover{background:rgba(34,197,94,0.28);}")
- .arg(fincept::ui::colors::POSITIVE()));
+ approve->setAccessibleName(
+ tr("Approve %1 %2 %3").arg(o.action.toUpper(), o.quantity, o.symbol));
auto* reject = new QPushButton(tr("Reject"));
+ reject->setObjectName(QStringLiteral("acRowReject"));
reject->setCursor(Qt::PointingHandCursor);
- reject->setStyleSheet(QString("QPushButton{background:rgba(220,38,38,0.12);color:%1;"
- "border:1px solid %1;padding:2px 10px;font-size:10px;"
- "font-weight:700;border-radius:2px;}"
- "QPushButton:hover{background:rgba(220,38,38,0.25);}")
- .arg(fincept::ui::colors::NEGATIVE()));
+ reject->setAccessibleName(tr("Reject %1 %2 %3").arg(o.action.toUpper(), o.quantity, o.symbol));
const QString id = o.id;
- connect(approve, &QPushButton::clicked, this, [this, id]() { approve_row(id); });
- connect(reject, &QPushButton::clicked, this, [this, id]() { reject_row(id); });
+ // Latch BOTH buttons off the moment either is clicked. approve_order()
+ // executes against the broker synchronously; a second click before the
+ // table refreshes would otherwise fire a second approval attempt on the
+ // same queued order.
+ // QPointer: approving triggers ActionCenter signals that call refresh(),
+ // which retires these cell widgets while we are still inside the click
+ // handler. Guard before touching them again.
+ QPointer<QPushButton> approve_guard(approve);
+ QPointer<QPushButton> reject_guard(reject);
+ auto set_row_enabled = [approve_guard, reject_guard](bool on) {
+ if (approve_guard)
+ approve_guard->setEnabled(on);
+ if (reject_guard)
+ reject_guard->setEnabled(on);
+ };
+ connect(approve, &QPushButton::clicked, this, [this, id, set_row_enabled]() {
+ set_row_enabled(false);
+ if (!approve_row(id)) // user cancelled — restore the row
+ set_row_enabled(true);
+ });
+ connect(reject, &QPushButton::clicked, this, [this, id, set_row_enabled]() {
+ set_row_enabled(false);
+ if (!reject_row(id))
+ set_row_enabled(true);
+ });
cl->addWidget(approve);
cl->addWidget(reject);
cl->addStretch(1);
@@ -359,17 +437,87 @@ void PendingOrdersPanel::refresh_stats() {
stat_sell_->setText(QString::number(s.total_sell));
}
-void PendingOrdersPanel::approve_row(const QString& pending_id) {
+// Human-readable age of a queued order, plus whether it is stale enough that
+// approving it could execute against a market that has moved on.
+QString PendingOrdersPanel::order_age_text(const QDateTime& created, bool* stale_out) {
+ const qint64 secs = created.isValid() ? created.secsTo(QDateTime::currentDateTime()) : 0;
+ if (stale_out)
+ *stale_out = (secs >= kStaleOrderSecs);
+ if (!created.isValid())
+ return tr("unknown age");
+ if (secs < 60)
+ return tr("%1s ago").arg(secs);
+ if (secs < 3600)
+ return tr("%1m ago").arg(secs / 60);
+ if (secs < 86400)
+ return tr("%1h %2m ago").arg(secs / 3600).arg((secs % 3600) / 60);
+ return tr("%1d ago").arg(secs / 86400);
+}
+
+// Returns true when the action was dispatched (or definitively consumed), false
+// when the user backed out and the row should become interactive again.
+bool PendingOrdersPanel::approve_row(const QString& pending_id) {
+ // Re-read the order rather than trusting the row snapshot: the table is
+ // rebuilt asynchronously from ActionCenter signals, so a row widget can
+ // outlive the state it was rendered from.
+ const auto po_opt = ActionCenter::instance().get_order(pending_id);
+ if (!po_opt) {
+ QMessageBox::warning(this, tr("Approve Order"),
+ tr("This order is no longer in the queue. Refreshing the list."));
+ refresh();
+ return true;
+ }
+ const PendingOrder& o = *po_opt;
+ if (o.status != QLatin1String("pending")) {
+ QMessageBox::information(this, tr("Approve Order"),
+ tr("This order was already %1 — nothing was sent.").arg(o.status));
+ refresh();
+ return true;
+ }
+
+ const auto acct_meta = trading::AccountManager::instance().get_account(o.account_id);
+ const QString acct_label = acct_meta.display_name.isEmpty() ? o.account_id : acct_meta.display_name;
+ bool stale = false;
+ const QString age = order_age_text(o.created_at, &stale);
+
+ // An approval sends a REAL order. Restate every field the user is agreeing
+ // to — previously a single click on a 10px button executed it with no
+ // confirmation and no visibility of price type, exchange or account.
+ QString body = tr("Send this order to the broker now?\n\n"
+ " Symbol: %1\n"
+ " Exchange: %2\n"
+ " Side: %3\n"
+ " Quantity: %4\n"
+ " Price type: %5\n"
+ " Order type: %6\n"
+ " Account: %7\n"
+ " Strategy: %8\n"
+ " Queued: %9")
+ .arg(o.symbol, o.exchange.isEmpty() ? tr("—") : o.exchange, o.action.toUpper(), o.quantity,
+ o.price_type, o.order_type, acct_label, o.strategy, age);
+ if (stale) {
+ body += tr("\n\n⚠ This order has been waiting a long time. The market has almost\n"
+ "certainly moved since it was queued — a MARKET order will fill at\n"
+ "today's price, not the price that triggered it.");
+ }
+
+ const auto ans = QMessageBox::question(this, tr("Approve Order"), body,
+ QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel);
+ if (ans != QMessageBox::Yes)
+ return false;
+
ActionCenter::instance().approve_order(pending_id);
+ return true;
}
-void PendingOrdersPanel::reject_row(const QString& pending_id) {
+bool PendingOrdersPanel::reject_row(const QString& pending_id) {
bool ok = false;
const QString reason = QInputDialog::getText(this, tr("Reject Order"), tr("Rejection reason:"), QLineEdit::Normal,
tr("Rejected by user"), &ok);
if (!ok)
- return;
+ return false;
ActionCenter::instance().reject_order(pending_id, reason);
+ return true;
}
// ── ActionCenter signal slots ───────────────────────────────────────────────
diff --git a/fincept-qt/src/screens/action_center/PendingOrdersPanel.h b/fincept-qt/src/screens/action_center/PendingOrdersPanel.h
index 01476279e..8c2c8505f 100644
--- a/fincept-qt/src/screens/action_center/PendingOrdersPanel.h
+++ b/fincept-qt/src/screens/action_center/PendingOrdersPanel.h
@@ -16,6 +16,7 @@
#include "trading/ActionCenter.h"
#include <QComboBox>
+#include <QDateTime>
#include <QEvent>
#include <QLabel>
#include <QPoint>
@@ -52,9 +53,24 @@ class PendingOrdersPanel : public QWidget {
void on_order_rejected(const QString& pending_id, const QString& reason);
void on_stats_updated(const QString& account_id);
- // Row actions.
- void approve_row(const QString& pending_id);
- void reject_row(const QString& pending_id);
+ // Row actions. Return true when the action was dispatched (or the row is
+ // gone), false when the user cancelled and the row buttons should re-enable.
+ bool approve_row(const QString& pending_id);
+ bool reject_row(const QString& pending_id);
+
+ // Age of a queued order as display text; sets *stale_out when the order has
+ // been waiting long enough that executing it at market is questionable.
+ static QString order_age_text(const QDateTime& created, bool* stale_out = nullptr);
+
+ // A queued order older than this is flagged in the table and in the approval
+ // confirmation — and REFUSED by ActionCenter::approve_order().
+ //
+ // Derived from ActionCenter's constant rather than duplicated: this panel's
+ // warning copy and the engine's enforcement must describe the same
+ // threshold. If they drifted, the UI would either nag about orders that
+ // still execute fine, or stay silent about ones about to be refused —
+ // both worse than no warning at all.
+ static constexpr qint64 kStaleOrderSecs = fincept::trading::ActionCenter::kPendingOrderTtlMinutes * 60;
// ── Widgets ──────────────────────────────────────────────────────────────
QLabel* title_label_ = nullptr;
diff --git a/fincept-qt/src/screens/agent_config/AgentChatPanel.cpp b/fincept-qt/src/screens/agent_config/AgentChatPanel.cpp
index b2661cc2e..ffac5a9b7 100644
--- a/fincept-qt/src/screens/agent_config/AgentChatPanel.cpp
+++ b/fincept-qt/src/screens/agent_config/AgentChatPanel.cpp
@@ -410,6 +410,8 @@ void AgentChatPanel::build_ui() {
"QTextEdit:focus{border-color:%4;}")
.arg(col::BG_BASE(), col::TEXT_PRIMARY(), col::BORDER_MED(), col::AMBER()));
input_edit_->installEventFilter(this);
+ input_edit_->setAccessibleName(tr("Message the selected agent"));
+ input_edit_->setAccessibleDescription(tr("Enter sends, Shift+Enter inserts a new line."));
// Grow height as user types (max ~120px / ~5 lines)
connect(input_edit_->document(), &QTextDocument::contentsChanged, input_edit_, [this]() {
int doc_h = static_cast<int>(input_edit_->document()->size().height());
@@ -421,6 +423,7 @@ void AgentChatPanel::build_ui() {
send_btn_ = new QPushButton(tr("Send"));
send_btn_->setFixedSize(76, 44);
send_btn_->setCursor(Qt::PointingHandCursor);
+ send_btn_->setAccessibleName(tr("Send message to agent"));
send_btn_->setStyleSheet(
QString("QPushButton{background:%1;color:%2;border:none;border-radius:6px;"
"font-size:12px;font-weight:700;}"
@@ -430,6 +433,18 @@ void AgentChatPanel::build_ui() {
il->addWidget(send_btn_);
root->addWidget(ib);
+ // Explicit tab order across the panel's interactive controls — creation
+ // order otherwise walks header widgets before the composer.
+ setTabOrder(agent_selector_, route_toggle_);
+ setTabOrder(route_toggle_, run_as_task_toggle_);
+ setTabOrder(run_as_task_toggle_, clear_btn_);
+ setTabOrder(clear_btn_, portfolio_combo_);
+ setTabOrder(portfolio_combo_, analyze_btn_);
+ setTabOrder(analyze_btn_, rebalance_btn_);
+ setTabOrder(rebalance_btn_, risk_btn_);
+ setTabOrder(risk_btn_, input_edit_);
+ setTabOrder(input_edit_, send_btn_);
+
// ── Status bar ────────────────────────────────────────────────────────────
status_label_ = new QLabel;
status_label_->setFixedHeight(18);
@@ -587,6 +602,28 @@ void AgentChatPanel::setup_connections() {
scroll_to_bottom();
});
+ // Failure that never produces an agent_result / agent_stream_done (Python
+ // crash, spawn failure, bad config). Without this the send button stayed
+ // disabled and `executing_` stuck true — the panel was dead until restart.
+ // Mirrors the guard TeamsViewPanel / WorkflowsViewPanel already have.
+ connect(&svc, &services::AgentService::error_occurred, this, [this](const QString&, const QString& msg) {
+ if (!executing_)
+ return;
+ show_typing(false);
+ set_executing(false);
+ if (streaming_bubble_widget_) {
+ streaming_bubble_widget_->setPlainText(tr("Error: %1").arg(msg));
+ streaming_bubble_widget_->setReadOnly(true);
+ streaming_bubble_widget_ = nullptr;
+ } else {
+ add_system_bubble(tr("Error: %1").arg(msg));
+ }
+ streaming_text_.clear();
+ status_label_->setText(tr("Agent execution failed"));
+ hdr_status_lbl_->setText(tr("Error"));
+ hdr_status_lbl_->setStyleSheet(QString("color:%1;font-size:9px;font-weight:700;").arg(col::NEGATIVE()));
+ });
+
// Routing result
connect(&svc, &services::AgentService::routing_result, this, [this](services::RoutingResult r) {
if (r.request_id != pending_request_id_)
@@ -963,7 +1000,9 @@ QTextEdit* AgentChatPanel::add_streaming_bubble(const QString& agent_name) {
bvl->setContentsMargins(0, 0, 0, 0);
auto* body = new QTextEdit;
- body->setReadOnly(false);
+ // Read-only from the start — programmatic setPlainText/insertPlainText still
+ // work, and the user can no longer type into the agent's answer mid-stream.
+ body->setReadOnly(true);
body->setFrameShape(QFrame::NoFrame);
body->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
body->document()->setDocumentMargin(4);
@@ -1022,6 +1061,15 @@ void AgentChatPanel::show_typing(bool on) {
if (!typing_indicator_)
return;
if (on) {
+ // Keep the indicator immediately above the trailing stretch, i.e. below
+ // the newest bubble. Bubbles are inserted at count()-1 too, so without
+ // this re-anchor the indicator stays wherever it was first inserted and
+ // "Agent is thinking" renders at the TOP of the transcript.
+ const int last = messages_layout_->count() - 1; // the stretch
+ if (messages_layout_->indexOf(typing_indicator_) != last - 1) {
+ messages_layout_->removeWidget(typing_indicator_);
+ messages_layout_->insertWidget(messages_layout_->count() - 1, typing_indicator_);
+ }
typing_step_ = 0;
typing_dots_lbl_->setText(tr("Agent is thinking"));
typing_indicator_->show();
@@ -1039,18 +1087,21 @@ void AgentChatPanel::clear_chat() {
show_typing(false);
set_executing(false);
- // Remove all message rows. Layout structure:
- // [0] = welcome_panel_
- // [1..N] = message rows
- // [count-2] = typing_indicator_
- // [count-1] = stretch
- // Stop when only welcome + typing_indicator_ + stretch remain (count == 3).
- // Always remove at index 1 so we never touch welcome(0), typing(count-2) or stretch(count-1).
- while (messages_layout_->count() > 3) {
- QLayoutItem* item = messages_layout_->takeAt(1);
- if (item && item->widget())
- item->widget()->deleteLater();
- delete item;
+ // Remove every message row, keeping the two fixtures and the trailing
+ // stretch. The old version assumed the typing indicator sat at count-2 and
+ // blindly took index 1 — but new bubbles are inserted *after* the typing
+ // indicator, so index 1 WAS the typing indicator. Clearing therefore
+ // deleteLater()'d it (leaving `typing_indicator_` dangling — the next send
+ // called show()/setText() on freed memory) and always left the last message
+ // row behind. Identify the fixtures by pointer instead of by index.
+ for (int i = messages_layout_->count() - 1; i >= 0; --i) {
+ QLayoutItem* item = messages_layout_->itemAt(i);
+ QWidget* w = item ? item->widget() : nullptr;
+ if (!w || w == welcome_panel_ || w == typing_indicator_)
+ continue; // stretch (no widget) + the two permanent fixtures
+ QLayoutItem* taken = messages_layout_->takeAt(i);
+ w->deleteLater();
+ delete taken;
}
show_welcome(true);
diff --git a/fincept-qt/src/screens/agent_config/AgenticTasksPanel.cpp b/fincept-qt/src/screens/agent_config/AgenticTasksPanel.cpp
index 4efd4808a..738e1b125 100644
--- a/fincept-qt/src/screens/agent_config/AgenticTasksPanel.cpp
+++ b/fincept-qt/src/screens/agent_config/AgenticTasksPanel.cpp
@@ -803,6 +803,13 @@ void AgenticTasksPanel::on_cancel_clicked() {
void AgenticTasksPanel::on_delete_clicked() {
if (selected_task_id_.isEmpty())
return;
+ // Cancels a possibly-running subprocess and drops the record permanently —
+ // it deserves the same confirmation the schedule dialog already asks for.
+ if (QMessageBox::question(this, tr("Delete Task"),
+ tr("Cancel and permanently delete this task?\n\nAny recurring schedule attached to it "
+ "is removed as well. This cannot be undone."),
+ QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes)
+ return;
auto& svc = services::AgentService::instance();
const QString id = selected_task_id_;
// Cancel first (signals a running subprocess to stop), then actually remove the
diff --git a/fincept-qt/src/screens/agent_config/AgentsViewPanel.cpp b/fincept-qt/src/screens/agent_config/AgentsViewPanel.cpp
index 8029836b9..e59cad74f 100644
--- a/fincept-qt/src/screens/agent_config/AgentsViewPanel.cpp
+++ b/fincept-qt/src/screens/agent_config/AgentsViewPanel.cpp
@@ -11,6 +11,7 @@
#include <QHBoxLayout>
#include <QJsonDocument>
+#include <QMessageBox>
#include <QScrollArea>
#include <QShowEvent>
#include <QStackedWidget>
@@ -271,8 +272,18 @@ QWidget* AgentsViewPanel::build_config_panel() {
"font-weight:700;}QPushButton:hover{background:%3;}")
.arg(ui::colors::AMBER(), ui::colors::BG_BASE(), ui::colors::ORANGE()));
connect(json_apply_btn_, &QPushButton::clicked, this, [this, stack]() {
- const QJsonDocument doc = QJsonDocument::fromJson(json_editor_->toPlainText().toUtf8());
- if (!doc.isNull() && selected_agent_idx_ >= 0) {
+ // Malformed JSON used to be swallowed: the editor closed and the form
+ // silently kept the old values, so the user believed their edit applied.
+ QJsonParseError perr{};
+ const QJsonDocument doc = QJsonDocument::fromJson(json_editor_->toPlainText().toUtf8(), &perr);
+ if (perr.error != QJsonParseError::NoError || !doc.isObject()) {
+ QMessageBox::warning(this, tr("Apply JSON"),
+ tr("Could not parse the JSON at offset %1: %2").arg(perr.offset).arg(
+ perr.error == QJsonParseError::NoError ? tr("top level must be an object")
+ : perr.errorString()));
+ return; // stay in the editor so the user can fix it
+ }
+ if (selected_agent_idx_ >= 0) {
filtered_agents_[selected_agent_idx_].config = doc.object();
load_agent_into_editor(filtered_agents_[selected_agent_idx_]);
}
@@ -439,7 +450,14 @@ void AgentsViewPanel::setup_connections() {
});
connect(&svc, &services::AgentService::agent_result, this, [this](services::AgentExecutionResult r) {
- if (r.request_id != pending_request_id_)
+ // Auto-Route dispatches two calls: route_query() (whose id we keep) and
+ // execute_routed_query(), which is void and emits agent_result with an
+ // EMPTY request_id. The strict id compare therefore dropped the only
+ // terminal event Auto-Route ever produces, leaving the panel pinned at
+ // "Executing..." with RUN AGENT disabled forever. Accept the unlabelled
+ // result while an auto-routed run is outstanding.
+ const bool routed_reply = executing_ && r.request_id.isEmpty() && auto_route_check_->isChecked();
+ if (r.request_id != pending_request_id_ && !routed_reply)
return;
executing_ = false;
pending_request_id_.clear();
@@ -507,6 +525,22 @@ void AgentsViewPanel::setup_connections() {
}
});
+ // A failure that never produces agent_result / agent_stream_done (Python
+ // crash, spawn failure, bad config) otherwise left RUN AGENT disabled and
+ // `executing_` stuck true for the rest of the session. Same guard
+ // TeamsViewPanel / WorkflowsViewPanel already carry.
+ connect(&svc, &services::AgentService::error_occurred, this, [this](const QString&, const QString& msg) {
+ if (!executing_)
+ return;
+ executing_ = false;
+ pending_request_id_.clear();
+ run_btn_->setEnabled(true);
+ run_btn_->setText(tr("RUN AGENT"));
+ result_display_->setPlainText(tr("Error: %1").arg(msg));
+ result_status_->setText(tr("ERROR"));
+ result_status_->setStyleSheet(QString("color:%1;font-size:10px;padding:2px 0;").arg(ui::colors::NEGATIVE()));
+ });
+
// Reload profile combo when LLM config changes
connect(&ai_chat::LlmService::instance(), &ai_chat::LlmService::config_changed, this,
&AgentsViewPanel::load_profile_combo);
@@ -774,6 +808,13 @@ void AgentsViewPanel::save_current_config() {
void AgentsViewPanel::delete_current_config() {
if (selected_agent_idx_ < 0 || selected_agent_idx_ >= filtered_agents_.size())
return;
+ // Deleting an agent config is irreversible and was a single unguarded click
+ // right next to SAVE CONFIG.
+ const QString name = filtered_agents_[selected_agent_idx_].name;
+ if (QMessageBox::question(this, tr("Delete Agent"),
+ tr("Delete the agent configuration \"%1\"?\n\nThis cannot be undone.").arg(name),
+ QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes)
+ return;
services::AgentService::instance().delete_config(filtered_agents_[selected_agent_idx_].id);
result_status_->setText(tr("Config deleted"));
result_status_->setStyleSheet(QString("color:%1;font-size:10px;padding:2px 0;").arg(ui::colors::WARNING()));
diff --git a/fincept-qt/src/screens/agent_config/CreateAgentPanel.cpp b/fincept-qt/src/screens/agent_config/CreateAgentPanel.cpp
index 9c1cabc1b..77a5b6542 100644
--- a/fincept-qt/src/screens/agent_config/CreateAgentPanel.cpp
+++ b/fincept-qt/src/screens/agent_config/CreateAgentPanel.cpp
@@ -136,6 +136,18 @@ void CreateAgentPanel::setup_connections() {
QString("color:%1;font-size:10px;padding:2px 0;").arg(ui::colors::NEGATIVE()));
}
});
+ // A failure that never produces agent_result / agent_stream_done left
+ // RUN TEST disabled and pending_request_id_ set for the rest of the session.
+ connect(&svc, &services::AgentService::error_occurred, this, [this](const QString&, const QString& msg) {
+ if (pending_request_id_.isEmpty())
+ return;
+ pending_request_id_.clear();
+ test_btn_->setEnabled(true);
+ test_btn_->setText(tr("RUN TEST"));
+ test_result_->setPlainText(tr("Error: %1").arg(msg));
+ test_status_lbl_->setText(tr("Failed"));
+ test_status_lbl_->setStyleSheet(QString("color:%1;font-size:10px;padding:2px 0;").arg(ui::colors::NEGATIVE()));
+ });
connect(&svc, &services::AgentService::tools_loaded, this, [this](services::AgentToolsInfo info) {
available_tools_.clear();
for (const auto& cat : info.categories) {
diff --git a/fincept-qt/src/screens/agent_config/CreateAgentPanel_DataOps.cpp b/fincept-qt/src/screens/agent_config/CreateAgentPanel_DataOps.cpp
index 2c18a8a95..e5edf860c 100644
--- a/fincept-qt/src/screens/agent_config/CreateAgentPanel_DataOps.cpp
+++ b/fincept-qt/src/screens/agent_config/CreateAgentPanel_DataOps.cpp
@@ -350,9 +350,17 @@ void CreateAgentPanel::save_agent() {
}
void CreateAgentPanel::delete_agent() {
- int row = saved_list_->currentRow();
- if (row >= 0 && row < saved_agents_.size())
- services::AgentService::instance().delete_config(saved_agents_[row].id);
+ const int row = saved_list_->currentRow();
+ if (row < 0 || row >= saved_agents_.size())
+ return;
+ // "DEL" is a 3-character button directly beside "LOAD" — it deleted the
+ // selected agent config with no confirmation and no undo.
+ if (QMessageBox::question(
+ this, tr("Delete Agent"),
+ tr("Delete the saved agent \"%1\"?\n\nThis cannot be undone.").arg(saved_agents_[row].name),
+ QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes)
+ return;
+ services::AgentService::instance().delete_config(saved_agents_[row].id);
}
void CreateAgentPanel::test_agent() {
@@ -378,8 +386,15 @@ void CreateAgentPanel::export_json() {
out["category"] = category_combo_->currentText();
out["config"] = build_config_json();
QFile file(path);
- if (file.open(QIODevice::WriteOnly))
- file.write(QJsonDocument(out).toJson(QJsonDocument::Indented));
+ // Previously the status said "Exported" even when open() failed and nothing
+ // was written — a silent data-loss report.
+ if (!file.open(QIODevice::WriteOnly)) {
+ status_lbl_->setText(tr("Export failed: cannot write %1").arg(path));
+ status_lbl_->setStyleSheet(QString("color:%1;font-size:10px;padding:3px 0;").arg(ui::colors::NEGATIVE()));
+ return;
+ }
+ file.write(QJsonDocument(out).toJson(QJsonDocument::Indented));
+ file.close();
status_lbl_->setText(tr("Exported: %1").arg(path));
status_lbl_->setStyleSheet(QString("color:%1;font-size:10px;padding:3px 0;").arg(ui::colors::POSITIVE()));
}
@@ -389,9 +404,23 @@ void CreateAgentPanel::import_json() {
if (path.isEmpty())
return;
QFile file(path);
- if (!file.open(QIODevice::ReadOnly))
+ if (!file.open(QIODevice::ReadOnly)) {
+ status_lbl_->setText(tr("Import failed: cannot read %1").arg(path));
+ status_lbl_->setStyleSheet(QString("color:%1;font-size:10px;padding:3px 0;").arg(ui::colors::NEGATIVE()));
return;
- const QJsonObject obj = QJsonDocument::fromJson(file.readAll()).object();
+ }
+ // A malformed file used to load as an empty object, silently wiping the form.
+ QJsonParseError perr{};
+ const QJsonDocument doc = QJsonDocument::fromJson(file.readAll(), &perr);
+ file.close();
+ if (perr.error != QJsonParseError::NoError || !doc.isObject()) {
+ status_lbl_->setText(tr("Import failed: %1")
+ .arg(perr.error == QJsonParseError::NoError ? tr("top level must be a JSON object")
+ : perr.errorString()));
+ status_lbl_->setStyleSheet(QString("color:%1;font-size:10px;padding:3px 0;").arg(ui::colors::NEGATIVE()));
+ return;
+ }
+ const QJsonObject obj = doc.object();
AgentConfig cfg;
cfg.id = QUuid::createUuid().toString(QUuid::WithoutBraces);
cfg.name = obj["name"].toString();
diff --git a/fincept-qt/src/screens/agent_config/CreateAgentPanel_Layout.cpp b/fincept-qt/src/screens/agent_config/CreateAgentPanel_Layout.cpp
index 7e35c6893..b0adc88ed 100644
--- a/fincept-qt/src/screens/agent_config/CreateAgentPanel_Layout.cpp
+++ b/fincept-qt/src/screens/agent_config/CreateAgentPanel_Layout.cpp
@@ -573,7 +573,65 @@ QWidget* CreateAgentPanel::build_form_panel() {
vl->addWidget(status_lbl_);
vl->addStretch();
+ // ── Accessibility ────────────────────────────────────────────────────────
+ // The form is a long scroll of unlabelled inputs; screen readers announced
+ // only the placeholder (or nothing, for the combos and lists).
+ name_edit_->setAccessibleName(tr("Agent name"));
+ category_combo_->setAccessibleName(tr("Agent category"));
+ desc_edit_->setAccessibleName(tr("Agent description"));
+ llm_profile_combo_->setAccessibleName(tr("LLM profile"));
+ instructions_edit_->setAccessibleName(tr("System instructions"));
+ tool_search_edit_->setAccessibleName(tr("Filter tools"));
+ tools_list_->setAccessibleName(tr("Available tools"));
+ terminal_tools_check_->setAccessibleName(tr("Enable internal terminal tools"));
+ terminal_destructive_check_->setAccessibleName(tr("Allow destructive tools"));
+ terminal_destructive_check_->setAccessibleDescription(
+ tr("Lets this agent call tools that place orders, delete data or change settings."));
+ terminal_external_check_->setAccessibleName(tr("Include external MCP servers"));
+ terminal_dry_run_check_->setAccessibleName(tr("Dry-run mode"));
+ terminal_categories_list_->setAccessibleName(tr("Terminal tool category whitelist"));
+ terminal_exclude_cats_edit_->setAccessibleName(tr("Excluded tool categories"));
+ terminal_name_include_edit_->setAccessibleName(tr("Tool name include pattern"));
+ terminal_name_exclude_edit_->setAccessibleName(tr("Tool name exclude pattern"));
+ terminal_max_tools_spin_->setAccessibleName(tr("Maximum tools"));
+ mcp_servers_list_->setAccessibleName(tr("MCP servers"));
+ save_btn_->setAccessibleName(tr("Save agent"));
+ clear_btn_->setAccessibleName(tr("Clear form"));
+
scroll->setWidget(content);
+
+ // Explicit tab order — set after the final reparent so the focus chain is
+ // built on the widgets' real hierarchy. Creation order alone puts the
+ // terminal-tool filters between the feature tags and their sub-sections.
+ setTabOrder(name_edit_, category_combo_);
+ setTabOrder(category_combo_, desc_edit_);
+ setTabOrder(desc_edit_, llm_profile_combo_);
+ setTabOrder(llm_profile_combo_, instructions_edit_);
+ setTabOrder(instructions_edit_, tool_search_edit_);
+ setTabOrder(tool_search_edit_, tools_list_);
+ setTabOrder(tools_list_, terminal_tools_check_);
+ setTabOrder(terminal_tools_check_, terminal_destructive_check_);
+ setTabOrder(terminal_destructive_check_, terminal_external_check_);
+ setTabOrder(terminal_external_check_, terminal_dry_run_check_);
+ setTabOrder(terminal_dry_run_check_, terminal_categories_list_);
+ setTabOrder(terminal_categories_list_, terminal_exclude_cats_edit_);
+ setTabOrder(terminal_exclude_cats_edit_, terminal_name_include_edit_);
+ setTabOrder(terminal_name_include_edit_, terminal_name_exclude_edit_);
+ setTabOrder(terminal_name_exclude_edit_, terminal_max_tools_spin_);
+ setTabOrder(terminal_max_tools_spin_, reasoning_check_);
+ setTabOrder(reasoning_check_, memory_check_);
+ setTabOrder(memory_check_, knowledge_check_);
+ setTabOrder(knowledge_check_, guardrails_check_);
+ setTabOrder(guardrails_check_, agentic_memory_check_);
+ setTabOrder(agentic_memory_check_, storage_check_);
+ setTabOrder(storage_check_, tracing_check_);
+ setTabOrder(tracing_check_, compression_check_);
+ setTabOrder(compression_check_, hooks_check_);
+ setTabOrder(hooks_check_, evaluation_check_);
+ setTabOrder(evaluation_check_, mcp_servers_list_);
+ setTabOrder(mcp_servers_list_, save_btn_);
+ setTabOrder(save_btn_, clear_btn_);
+
return scroll;
}
@@ -615,6 +673,7 @@ QWidget* CreateAgentPanel::build_test_panel() {
test_query_edit_ = new QPlainTextEdit;
test_query_edit_->setPlaceholderText(tr("Enter test query..."));
+ test_query_edit_->setAccessibleName(tr("Test query"));
test_query_edit_->setFixedHeight(72);
test_query_edit_->setStyleSheet(
QString("QPlainTextEdit{background:%1;color:%2;border:1px solid %3;padding:6px;font-size:12px;}")
@@ -628,6 +687,7 @@ QWidget* CreateAgentPanel::build_test_panel() {
"QPushButton:hover{background:%1;color:%2;}"
"QPushButton:disabled{color:%3;border-color:%3;}")
.arg(ui::colors::CYAN(), ui::colors::BG_BASE(), ui::colors::TEXT_TERTIARY()));
+ test_btn_->setAccessibleName(tr("Run test query"));
connect(test_btn_, &QPushButton::clicked, this, &CreateAgentPanel::test_agent);
bl->addWidget(test_btn_);
@@ -653,6 +713,7 @@ QWidget* CreateAgentPanel::build_test_panel() {
bl->addWidget(test_result_, 1);
vl->addWidget(body, 1);
+ setTabOrder(test_query_edit_, test_btn_);
return p;
}
diff --git a/fincept-qt/src/screens/agent_config/ToolsViewPanel.cpp b/fincept-qt/src/screens/agent_config/ToolsViewPanel.cpp
index 9d6c983c3..5875b6466 100644
--- a/fincept-qt/src/screens/agent_config/ToolsViewPanel.cpp
+++ b/fincept-qt/src/screens/agent_config/ToolsViewPanel.cpp
@@ -392,7 +392,13 @@ void ToolsViewPanel::setup_connections() {
update_assigned_dots();
});
- connect(search_edit_, &QLineEdit::textChanged, this, &ToolsViewPanel::filter_tools);
+ // Debounced search — filter_tools() rebuilds a ~600-node tree and used to
+ // run synchronously on every keystroke.
+ search_debounce_ = new QTimer(this);
+ search_debounce_->setSingleShot(true);
+ search_debounce_->setInterval(180);
+ connect(search_debounce_, &QTimer::timeout, this, [this]() { filter_tools(search_edit_->text()); });
+ connect(search_edit_, &QLineEdit::textChanged, this, [this](const QString&) { search_debounce_->start(); });
// Tool tree — single click = detail, double click = add
connect(tool_tree_, &QTreeWidget::currentItemChanged, this, [this](QTreeWidgetItem* item, QTreeWidgetItem*) {
@@ -472,15 +478,26 @@ void ToolsViewPanel::showEvent(QShowEvent* event) {
void ToolsViewPanel::populate_tools(const services::AgentToolsInfo& info) {
all_tools_ = info;
- total_count_->setText(QString::number(info.total_count));
+ // Flatten once — the MCP dedupe check below is O(1) against this set
+ // instead of re-walking every category array per MCP tool per keystroke.
+ agent_tool_names_.clear();
+ for (const auto& cat : all_tools_.categories)
+ for (const auto& t : all_tools_.tools[cat].toArray())
+ agent_tool_names_.insert(t.toString());
filter_tools(search_edit_->text());
}
+void ToolsViewPanel::refresh_assigned_cache() {
+ assigned_cache_ = tools_of_target();
+}
+
void ToolsViewPanel::filter_tools(const QString& query) {
tool_tree_->clear();
QString q = query.toLower().trimmed();
- QStringList assigned = tools_of_target();
+ // Cached — tools_of_target() reads AgentConfigRepository, and this function
+ // runs on every search change and every selection change.
+ const QStringList& assigned = assigned_cache_;
int total = 0;
// Agent service tools grouped by category
@@ -523,15 +540,8 @@ void ToolsViewPanel::filter_tools(const QString& query) {
for (const auto& tool : mcp_tools) {
if (!q.isEmpty() && !tool.name.toLower().contains(q))
continue;
- // Skip duplicates already shown from agent service
- bool already_shown = false;
- for (const auto& cat : all_tools_.categories) {
- if (all_tools_.tools[cat].toArray().contains(QJsonValue(tool.name))) {
- already_shown = true;
- break;
- }
- }
- if (already_shown)
+ // Skip duplicates already shown from agent service (O(1) lookup).
+ if (agent_tool_names_.contains(tool.name))
continue;
QString cat = tool.is_internal ? "internal-mcp" : tool.server_name;
@@ -659,12 +669,28 @@ void ToolsViewPanel::refresh_used_by(const QString& tool_name) {
}
}
}
+ // Teams are AgentConfig rows with category == "team". The panel header and
+ // the empty-state text both promised "agents or teams", but only agents
+ // were ever scanned — a tool assigned to a team looked unused.
+ if (auto teams = AgentConfigRepository::instance().list_by_category("team"); teams.is_ok()) {
+ for (const auto& cfg : teams.value()) {
+ const QJsonArray tools =
+ QJsonDocument::fromJson(cfg.config_json.toUtf8()).object().value("tools").toArray();
+ for (const auto& t : tools) {
+ if (t.toString() == tool_name) {
+ lines << tr("● Team: %1").arg(cfg.name);
+ break;
+ }
+ }
+ }
+ }
detail_used_by_->setPlainText(lines.isEmpty() ? tr("Not assigned to any agent or team yet.") : lines.join("\n"));
}
// ── Assigned dots ─────────────────────────────────────────────────────────────
void ToolsViewPanel::update_assigned_dots() {
+ refresh_assigned_cache();
filter_tools(search_edit_->text());
}
diff --git a/fincept-qt/src/screens/agent_config/ToolsViewPanel.h b/fincept-qt/src/screens/agent_config/ToolsViewPanel.h
index 43f0eff06..396eac174 100644
--- a/fincept-qt/src/screens/agent_config/ToolsViewPanel.h
+++ b/fincept-qt/src/screens/agent_config/ToolsViewPanel.h
@@ -9,7 +9,9 @@
#include <QListWidget>
#include <QPushButton>
#include <QRadioButton>
+#include <QSet>
#include <QTextEdit>
+#include <QTimer>
#include <QTreeWidget>
#include <QWidget>
@@ -104,6 +106,19 @@ class ToolsViewPanel : public QWidget {
QVector<services::AgentInfo> agent_configs_;
bool data_loaded_ = false;
QString current_tool_; // tool shown in detail panel
+
+ // Flat name set of every agent-service tool, rebuilt once per
+ // populate_tools(). filter_tools() used to re-scan every category's
+ // QJsonArray for each MCP tool on every keystroke.
+ QSet<QString> agent_tool_names_;
+ // Tools already assigned to the current target. Refreshed when the target
+ // changes or an assign completes — filter_tools() previously hit
+ // AgentConfigRepository (a DB read) on every keystroke.
+ QStringList assigned_cache_;
+ void refresh_assigned_cache();
+ // 180 ms debounce so a fast typist rebuilds the ~600-node tree once,
+ // not once per character.
+ QTimer* search_debounce_ = nullptr;
};
} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/ai_chat/AiChatBubble.cpp b/fincept-qt/src/screens/ai_chat/AiChatBubble.cpp
index 6ea6442fc..d389dc353 100644
--- a/fincept-qt/src/screens/ai_chat/AiChatBubble.cpp
+++ b/fincept-qt/src/screens/ai_chat/AiChatBubble.cpp
@@ -313,6 +313,9 @@ QWidget* AiChatBubble::build_input_row() {
"QPlainTextEdit:focus{border-color:%4;}")
.arg(col::BG_RAISED(), col::TEXT_PRIMARY(), col::BORDER_MED(), col::AMBER()));
input_box_->installEventFilter(this);
+ input_box_->setAccessibleName(tr("Quick Chat message"));
+ input_box_->setAccessibleDescription(
+ tr("Enter sends, Shift+Enter inserts a new line, Esc closes, Ctrl+L clears."));
hl->addWidget(input_box_, 1);
mic_btn_ = new QPushButton("MIC");
@@ -327,6 +330,7 @@ QWidget* AiChatBubble::build_input_row() {
"QPushButton[listening=\"true\"]{background:%4;border-color:%3;color:%5;}")
.arg(col::TEXT_PRIMARY(), col::BORDER_MED(), col::AMBER(), col::AMBER_DIM(), col::BG_BASE()));
mic_btn_->setProperty("listening", false);
+ mic_btn_->setAccessibleName(tr("Dictate message"));
connect(mic_btn_, &QPushButton::clicked, this, &AiChatBubble::on_toggle_mic);
hl->addWidget(mic_btn_);
@@ -334,6 +338,7 @@ QWidget* AiChatBubble::build_input_row() {
send_btn_->setFixedSize(56, 38);
send_btn_->setCursor(Qt::PointingHandCursor);
send_btn_->setToolTip(tr("Send (Enter)"));
+ send_btn_->setAccessibleName(tr("Send message"));
send_btn_->setStyleSheet(
QString("QPushButton{background:%1;color:%2;border:none;"
"border-radius:0px;font-size:12px;font-weight:700;}"
@@ -343,6 +348,9 @@ QWidget* AiChatBubble::build_input_row() {
connect(send_btn_, &QPushButton::clicked, this, &AiChatBubble::on_send);
hl->addWidget(send_btn_);
+ setTabOrder(input_box_, mic_btn_);
+ setTabOrder(mic_btn_, send_btn_);
+
return row;
}
@@ -412,20 +420,25 @@ void AiChatBubble::build_welcome_widget() {
}
void AiChatBubble::show_welcome_if_empty() {
- if (!welcome_widget_ || !msg_layout_)
+ if (!welcome_widget_ || !msg_layout_ || !chat_history_.empty())
return;
- if (chat_history_.empty() && welcome_widget_->parent() != msg_container_) {
+ // "Is it in the layout?" is the real question — parentage stays with
+ // msg_container_ so the widget is never orphaned (see hide_welcome).
+ if (msg_layout_->indexOf(welcome_widget_) < 0)
msg_layout_->insertWidget(msg_layout_->count() - 1, welcome_widget_);
- welcome_widget_->show();
- }
+ welcome_widget_->show();
}
void AiChatBubble::hide_welcome() {
- if (welcome_widget_ && welcome_widget_->parent() == msg_container_) {
+ if (!welcome_widget_ || !msg_layout_)
+ return;
+ // setParent(nullptr) used to orphan the card: msg_container_ no longer owned
+ // it, nothing else did, and on_clear_chat() then overwrote welcome_widget_
+ // with a fresh instance — leaking one card per send/clear cycle. Leave the
+ // parent alone; removeWidget() already takes it out of the layout.
+ if (msg_layout_->indexOf(welcome_widget_) >= 0)
msg_layout_->removeWidget(welcome_widget_);
- welcome_widget_->setParent(nullptr);
- welcome_widget_->hide();
- }
+ welcome_widget_->hide();
}
// ── Open / Close ──────────────────────────────────────────────────────────────
@@ -470,20 +483,23 @@ void AiChatBubble::on_clear_chat() {
if (is_speaking_)
stop_tts();
- // Tear down message widgets but keep the trailing stretch.
- while (msg_layout_->count() > 1) {
- auto* item = msg_layout_->takeAt(0);
- if (item->widget())
- item->widget()->deleteLater();
- delete item;
+ // Tear down message widgets, keeping the trailing stretch and the welcome
+ // card (which is reused — rebuilding it here leaked the previous instance
+ // whenever the card had already been hidden by a first message).
+ for (int i = msg_layout_->count() - 1; i >= 0; --i) {
+ auto* item = msg_layout_->itemAt(i);
+ auto* w = item ? item->widget() : nullptr;
+ if (!w || w == welcome_widget_)
+ continue;
+ auto* taken = msg_layout_->takeAt(i);
+ w->deleteLater();
+ delete taken;
}
chat_history_.clear();
streaming_bubble_.clear();
streaming_ = false;
error_msg_.clear();
- // Rebuild welcome card and re-show it.
- build_welcome_widget();
show_welcome_if_empty();
set_input_enabled(true);
render_status();
diff --git a/fincept-qt/src/screens/ai_chat/AiChatScreen.cpp b/fincept-qt/src/screens/ai_chat/AiChatScreen.cpp
index e2000e0a8..0f7110629 100644
--- a/fincept-qt/src/screens/ai_chat/AiChatScreen.cpp
+++ b/fincept-qt/src/screens/ai_chat/AiChatScreen.cpp
@@ -219,7 +219,7 @@ void AiChatScreen::changeEvent(QEvent* event) {
void AiChatScreen::retranslateUi() {
// Sidebar
if (new_btn_)
- new_btn_->setToolTip(tr("New Chat (Ctrl+N)"));
+ new_btn_->setToolTip(tr("New Chat (Ctrl+N / Ctrl+K)"));
if (search_edit_)
search_edit_->setPlaceholderText(tr("Search sessions..."));
if (rename_btn_)
@@ -263,7 +263,9 @@ bool AiChatScreen::eventFilter(QObject* obj, QEvent* event) {
on_send();
return true;
}
- if (ke->key() == Qt::Key_N && (ke->modifiers() & Qt::ControlModifier)) {
+ // Ctrl+N and Ctrl+K both start a new session (Ctrl+K is the convention
+ // most chat clients use; Ctrl+N was already documented in the tooltip).
+ if ((ke->key() == Qt::Key_N || ke->key() == Qt::Key_K) && (ke->modifiers() & Qt::ControlModifier)) {
on_new_session();
return true;
}
diff --git a/fincept-qt/src/screens/ai_chat/AiChatScreen_Layout.cpp b/fincept-qt/src/screens/ai_chat/AiChatScreen_Layout.cpp
index 769b7fb77..53bc3ad25 100644
--- a/fincept-qt/src/screens/ai_chat/AiChatScreen_Layout.cpp
+++ b/fincept-qt/src/screens/ai_chat/AiChatScreen_Layout.cpp
@@ -97,7 +97,8 @@ void AiChatScreen::build_sidebar() {
new_btn_ = new QPushButton("+");
new_btn_->setFixedSize(34, 34);
new_btn_->setCursor(Qt::PointingHandCursor);
- new_btn_->setToolTip(tr("New Chat (Ctrl+N)"));
+ new_btn_->setToolTip(tr("New Chat (Ctrl+N / Ctrl+K)"));
+ new_btn_->setAccessibleName(tr("New chat session"));
new_btn_->setStyleSheet(
QString("QPushButton{background:transparent;color:%1;border:1px solid %2;"
"border-radius:0px;font-size:20px;font-weight:700;}"
@@ -232,6 +233,14 @@ void AiChatScreen::build_chat_area() {
messages_layout_->setContentsMargins(32, 24, 32, 16);
messages_layout_->setSpacing(18);
messages_layout_->addStretch();
+
+ // build_welcome() existed and was fully written but was never called, so
+ // welcome_panel_ stayed null and show_welcome() was a permanent no-op — the
+ // "How can I help you?" heading and the six suggestion cards never rendered
+ // on an empty session. Insert it above the stretch; clear_messages() keeps it.
+ welcome_panel_ = build_welcome();
+ messages_layout_->insertWidget(0, welcome_panel_);
+
scroll_area_->setWidget(messages_container_);
vl->addWidget(scroll_area_, 1);
@@ -432,6 +441,9 @@ QWidget* AiChatScreen::build_input_area() {
.arg(fnt::BODY)
.arg(col::AMBER()));
input_box_->installEventFilter(this);
+ input_box_->setAccessibleName(tr("Message Fincept AI"));
+ input_box_->setAccessibleDescription(
+ tr("Enter sends, Shift+Enter inserts a new line, Ctrl+N or Ctrl+K starts a new session."));
connect(input_box_, &QPlainTextEdit::textChanged, this, [this]() {
const int lines = input_box_->document()->blockCount();
input_box_->setFixedHeight(qMin(qMax(lines, 1), 6) * 24 + 20);
@@ -444,6 +456,7 @@ QWidget* AiChatScreen::build_input_area() {
attach_btn_->setFixedSize(44, 44);
attach_btn_->setCursor(Qt::PointingHandCursor);
attach_btn_->setToolTip(tr("Attach a file to this message"));
+ attach_btn_->setAccessibleName(tr("Attach file"));
attach_btn_->setStyleSheet(QString("QPushButton{background:transparent;color:%1;border:1px solid %2;"
"border-radius:0px;font-size:20px;font-weight:700;}"
"QPushButton:hover{background:rgba(217,119,6,0.15);border-color:%1;}"
@@ -465,6 +478,7 @@ QWidget* AiChatScreen::build_input_area() {
send_btn_ = new QPushButton(tr("Send ↑"));
send_btn_->setFixedSize(82, 44);
send_btn_->setCursor(Qt::PointingHandCursor);
+ send_btn_->setAccessibleName(tr("Send message"));
send_btn_->setStyleSheet(QString("QPushButton{background:%1;color:%2;border:none;border-radius:0px;"
"font-size:%3px;font-weight:700;}"
"QPushButton:hover:enabled{background:%4;}"
@@ -475,6 +489,10 @@ QWidget* AiChatScreen::build_input_area() {
connect(send_btn_, &QPushButton::clicked, this, &AiChatScreen::on_send);
hl->addWidget(send_btn_);
+ // Explicit tab order — composer first, then its two actions.
+ setTabOrder(input_box_, attach_btn_);
+ setTabOrder(attach_btn_, send_btn_);
+
return bar;
}
diff --git a/fincept-qt/src/screens/ai_chat/AiChatScreen_Messaging.cpp b/fincept-qt/src/screens/ai_chat/AiChatScreen_Messaging.cpp
index 3c3a05eb4..412e3db11 100644
--- a/fincept-qt/src/screens/ai_chat/AiChatScreen_Messaging.cpp
+++ b/fincept-qt/src/screens/ai_chat/AiChatScreen_Messaging.cpp
@@ -423,11 +423,16 @@ void AiChatScreen::reset_thinking_state() {
void AiChatScreen::clear_messages() {
streaming_bubble_.clear();
reset_thinking_state(); // card widgets are deleted by the loop below
- while (messages_layout_->count() > 1) {
- QLayoutItem* item = messages_layout_->takeAt(0);
- if (item->widget())
- item->widget()->deleteLater();
- delete item;
+ // Skip the welcome panel — it is a permanent fixture reused across sessions
+ // (it is only shown/hidden). Everything else is a message row.
+ for (int i = messages_layout_->count() - 1; i >= 0; --i) {
+ QLayoutItem* item = messages_layout_->itemAt(i);
+ QWidget* w = item ? item->widget() : nullptr;
+ if (!w || w == welcome_panel_)
+ continue; // trailing stretch has no widget
+ QLayoutItem* taken = messages_layout_->takeAt(i);
+ w->deleteLater();
+ delete taken;
}
}
diff --git a/fincept-qt/src/screens/ai_chat/AiChatScreen_Sessions.cpp b/fincept-qt/src/screens/ai_chat/AiChatScreen_Sessions.cpp
index 5dd9e2d9e..517109b75 100644
--- a/fincept-qt/src/screens/ai_chat/AiChatScreen_Sessions.cpp
+++ b/fincept-qt/src/screens/ai_chat/AiChatScreen_Sessions.cpp
@@ -33,6 +33,7 @@
#include <QKeyEvent>
#include <QLabel>
#include <QMenu>
+#include <QMessageBox>
#include <QPalette>
#include <QPointer>
#include <QRandomGenerator>
@@ -243,6 +244,13 @@ void AiChatScreen::on_rename_session() {
void AiChatScreen::on_delete_session() {
if (streaming_ || active_session_id_.isEmpty())
return;
+ // Delete sits next to Rename in the sidebar and permanently drops the
+ // session and all of its messages from ChatRepository — confirm first.
+ const QString label = active_session_title_.isEmpty() ? active_session_id_.left(8) : active_session_title_;
+ if (QMessageBox::question(this, tr("Delete Session"),
+ tr("Delete \"%1\" and all of its messages?\n\nThis cannot be undone.").arg(label),
+ QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes)
+ return;
ChatRepository::instance().delete_session(active_session_id_);
active_session_id_.clear();
active_session_title_.clear();
diff --git a/fincept-qt/src/screens/ai_quant_lab/AIQuantLabScreen.cpp b/fincept-qt/src/screens/ai_quant_lab/AIQuantLabScreen.cpp
index e7ab63f96..a7b9004fe 100644
--- a/fincept-qt/src/screens/ai_quant_lab/AIQuantLabScreen.cpp
+++ b/fincept-qt/src/screens/ai_quant_lab/AIQuantLabScreen.cpp
@@ -11,6 +11,7 @@
#include <QFrame>
#include <QHBoxLayout>
#include <QScrollArea>
+#include <QSet>
namespace fincept::screens {
@@ -114,6 +115,10 @@ QWidget* AIQuantLabScreen::build_top_bar() {
btn->setCheckable(true);
btn->setCursor(Qt::PointingHandCursor);
btn->setFixedHeight(26);
+ // Short labels ("FACTOR", "BTEST") are meaningless to a screen reader —
+ // announce the full module name instead.
+ btn->setAccessibleName(mod.label);
+ btn->setAccessibleDescription(mod.description);
connect(btn, &QPushButton::clicked, this, [this, i]() { on_module_selected(i); });
bhl->addWidget(btn);
badge_buttons_.append(btn);
@@ -182,6 +187,9 @@ QWidget* AIQuantLabScreen::build_left_sidebar() {
auto* btn = new QPushButton(mod.label, list);
btn->setCheckable(true);
btn->setCursor(Qt::PointingHandCursor);
+ btn->setToolTip(mod.description);
+ btn->setAccessibleName(mod.label);
+ btn->setAccessibleDescription(mod.description);
connect(btn, &QPushButton::clicked, this, [this, i]() { on_module_selected(i); });
left_items_layout_->addWidget(btn);
module_buttons_.append(btn);
@@ -190,6 +198,7 @@ QWidget* AIQuantLabScreen::build_left_sidebar() {
scroll->setWidget(list);
vl->addWidget(scroll, 1);
+ left_panel_->setAccessibleName(tr("Quant module list"));
return left_panel_;
}
@@ -250,10 +259,16 @@ QWidget* AIQuantLabScreen::build_right_sidebar() {
rl->addWidget(val);
svl->addWidget(row);
};
+ // "Python Scripts" was a hard-coded "25+". Derive it from the module table
+ // so the card can't drift away from what the terminal can actually run.
+ QSet<QString> distinct_scripts;
+ for (const auto& m : modules_)
+ distinct_scripts.insert(m.script);
+
add_stat(stat_modules_lbl_, QString::number(modules_.size()));
add_stat(stat_ml_lbl_, "30+");
- add_stat(stat_rl_lbl_, "5");
- add_stat(stat_py_lbl_, "25+");
+ add_stat(stat_rl_lbl_, "5"); // PPO, DQN, A2C, SAC, TD3 — see qlib_rl.py
+ add_stat(stat_py_lbl_, QString::number(distinct_scripts.size()));
vl->addWidget(stats_card_);
vl->addStretch();
diff --git a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel.cpp b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel.cpp
index e5993b900..9e33a48b2 100644
--- a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel.cpp
+++ b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel.cpp
@@ -31,15 +31,20 @@
#include <QHeaderView>
#include <QJsonArray>
#include <QJsonDocument>
+#include <QJsonParseError>
+#include <QKeySequence>
#include <QLineSeries>
#include <QPlainTextEdit>
+#include <QPointer>
#include <QProgressBar>
#include <QRegularExpression>
#include <QScrollArea>
+#include <QShortcut>
#include <QStackedWidget>
#include <QTabWidget>
#include <QTableWidget>
#include <QTableWidgetItem>
+#include <QTimer>
#include <QUrl>
#include <QValueAxis>
@@ -68,6 +73,12 @@ QPushButton* QuantModulePanel::make_run_button(const QString& text, QWidget* par
auto* btn = new QPushButton(text, parent);
btn->setCursor(Qt::PointingHandCursor);
btn->setFixedHeight(32);
+ // Tagged so the panel-wide Ctrl+Enter shortcut (build_ui) can find the run
+ // button belonging to the currently visible tab, and so screen readers
+ // announce something meaningful.
+ btn->setObjectName(QStringLiteral("quantRunButton"));
+ btn->setAccessibleName(text);
+ btn->setAccessibleDescription(tr("Run this analysis (Ctrl+Enter)"));
btn->setStyleSheet(QString("QPushButton { background:%1; color:%2; font-weight:700; border:none;"
"padding:0 20px; border-radius:2px; letter-spacing:0.8px; }"
"QPushButton:hover { background:%3; }"
@@ -93,8 +104,13 @@ QWidget* QuantModulePanel::build_input_row(const QString& label, QWidget* input,
lbl->setText(label);
}
lbl->setStyleSheet(QString("color:%1; background:transparent;").arg(ui::colors::TEXT_SECONDARY()));
+ lbl->setBuddy(input);
hl->addWidget(lbl);
hl->addWidget(input, 1);
+ // Every parameter control gets an accessible name — without this a screen
+ // reader announces bare "edit"/"combo box" for ~200 unlabeled inputs.
+ if (input && input->accessibleName().isEmpty())
+ input->setAccessibleName(lbl->text().isEmpty() ? label : lbl->text());
return row;
}
@@ -134,8 +150,8 @@ QJsonObject QuantModulePanel::llm_config_from_combo(QComboBox* combo) const {
if (profile_id.isEmpty())
return {};
- auto resolved = LlmProfileRepository::instance().resolve_for_context("ai_quant_lab", profile_id);
- // resolve_for_context uses context_id as a profile_id hint — use get_profile directly
+ // resolve_for_context() takes the context id, not a profile id — the combo
+ // already holds a concrete profile id, so read it directly.
auto result = LlmProfileRepository::instance().get_profile(profile_id);
if (!result.is_ok())
return {};
@@ -322,6 +338,24 @@ void QuantModulePanel::build_ui() {
scroll->setWidget(content);
root->addWidget(scroll, 1);
+
+ // ── Ctrl+Enter runs the visible tab's action ─────────────────────────────
+ // One shortcut per panel rather than QPushButton::setShortcut on every run
+ // button: N buttons sharing a window-level shortcut is an "ambiguous
+ // shortcut overload" in Qt and silently does nothing. Scoped to this widget
+ // subtree so it never fires for another screen.
+ auto* run_shortcut = new QShortcut(QKeySequence(QStringLiteral("Ctrl+Return")), this);
+ run_shortcut->setContext(Qt::WidgetWithChildrenShortcut);
+ connect(run_shortcut, &QShortcut::activated, this, [this]() {
+ // isVisible() is false for widgets on a non-current QTabWidget page, so
+ // this resolves to the run button the user is actually looking at.
+ for (auto* btn : this->findChildren<QPushButton*>(QStringLiteral("quantRunButton"))) {
+ if (btn->isVisible() && btn->isEnabled()) {
+ btn->click();
+ return;
+ }
+ }
+ });
}
// ═══════════════════════════════════════════════════════════════════════════════
@@ -375,17 +409,24 @@ QWidget* QuantModulePanel::build_generic_panel() {
auto* run = make_run_button(tr("EXECUTE"), w);
connect(run, &QPushButton::clicked, this, [this, params_edit]() {
- status_label_->setText(tr("Running..."));
auto cmd_text = text_inputs_["gen_command"]->text().trimmed();
if (cmd_text.isEmpty())
- cmd_text = "analyze";
- auto json_text = params_edit->toPlainText().trimmed();
+ cmd_text = QStringLiteral("analyze");
+ const auto json_text = params_edit->toPlainText().trimmed();
QJsonObject params;
if (!json_text.isEmpty()) {
- auto doc = QJsonDocument::fromJson(json_text.toUtf8());
- if (!doc.isNull())
- params = doc.object();
+ // A malformed body used to be dropped silently and the command ran
+ // with no parameters at all.
+ QJsonParseError perr{};
+ const auto doc = QJsonDocument::fromJson(json_text.toUtf8(), &perr);
+ if (perr.error != QJsonParseError::NoError || !doc.isObject()) {
+ display_error(tr("JSON parameters must be an object like {\"ticker\":\"AAPL\"} — %1")
+ .arg(perr.errorString()));
+ return;
+ }
+ params = doc.object();
}
+ show_loading(tr("Running %1 %2...").arg(module_.script, cmd_text));
AIQuantLabService::instance().run_module(module_.id, cmd_text, params);
});
vl->addWidget(run);
@@ -417,8 +458,22 @@ void QuantModulePanel::clear_results() {
void QuantModulePanel::display_error(const QString& msg) {
clear_results();
- auto* err = new QLabel(msg);
+ if (!results_layout_)
+ return;
+
+ // Python tracebacks can be thousands of lines; an unbounded QLabel makes the
+ // scroll area unusable. Keep the tail — that's where the exception is.
+ constexpr int kMaxChars = 4000;
+ QString text = msg;
+ if (text.size() > kMaxChars)
+ text = tr("… (%1 earlier characters omitted) …\n\n").arg(text.size() - kMaxChars) +
+ text.right(kMaxChars);
+
+ auto* err = new QLabel(text);
err->setWordWrap(true);
+ // Selectable so the user can copy the traceback into a bug report.
+ err->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard);
+ err->setAccessibleName(tr("Error details"));
err->setStyleSheet(QString("color:%1; font-size:%2px; font-family:%3; padding:12px;"
"background:rgba(220,38,38,0.08); border:1px solid rgba(220,38,38,0.3);"
"border-radius:2px;")
@@ -426,14 +481,18 @@ void QuantModulePanel::display_error(const QString& msg) {
.arg(ui::fonts::SMALL)
.arg(ui::fonts::DATA_FAMILY));
results_layout_->addWidget(err);
- status_label_->setText(tr("Error"));
+ if (status_label_)
+ status_label_->setText(tr("Error"));
}
// ── Loading spinner shown while a Python op is in flight ─────────────────────
void QuantModulePanel::show_loading(const QString& message) {
clear_results();
- status_label_->setText(message);
+ if (!results_layout_)
+ return;
+ if (status_label_)
+ status_label_->setText(message);
// Container card
auto* box = new QWidget(this);
@@ -492,10 +551,25 @@ void QuantModulePanel::show_loading(const QString& message) {
void QuantModulePanel::on_error(const QString& module_id, const QString& message) {
if (module_id != module_.id)
return;
- if (module_id == "rl_trading" && rl_train_button_) {
- rl_train_button_->setEnabled(true);
+ if (module_id == "rl_trading") {
+ if (rl_train_button_)
+ rl_train_button_->setEnabled(true);
+ if (rl_progress_bar_)
+ rl_progress_bar_->setValue(0);
+ if (rl_progress_stats_)
+ rl_progress_stats_->setText(tr("Training failed — see the log below."));
}
- display_error(message);
+ // Rolling Retraining owns a bespoke progress bar; leave it in a readable
+ // failed state rather than a stale "Starting..." forever.
+ if (auto* pb = this->findChild<QProgressBar*>(QStringLiteral("rr_progress")))
+ pb->setFormat(tr("Failed"));
+
+ // message is the script's stderr (PythonRunner::PythonResult::error), so the
+ // user sees the actual traceback. Prefix it with the script that failed —
+ // otherwise a bare traceback gives no clue which module produced it.
+ display_error(message.trimmed().isEmpty()
+ ? tr("%1 failed with no diagnostic output.").arg(module_.script)
+ : tr("%1 failed:\n\n%2").arg(module_.script, message.trimmed()));
}
} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_AIMLDisplays.cpp b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_AIMLDisplays.cpp
index f3a6a57b5..966b8a6cf 100644
--- a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_AIMLDisplays.cpp
+++ b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_AIMLDisplays.cpp
@@ -11,8 +11,12 @@
// Skipped:
// - deep_agent — has bespoke per-tab UI (LangGraph + RD-Agent text outputs,
// task table widget). Handled by legacy on_result branch.
-// - pattern_intelligence — module declared but no panel/service wired yet.
+// (pattern_intelligence was listed here as "declared but no panel/service
+// wired yet"; it has since been removed from all_quant_modules() entirely —
+// its target script is a library with no real command surface. See the
+// comment at its former registration site in AIQuantLabTypes.h.)
#include "screens/ai_quant_lab/QuantModulePanel.h"
+#include "screens/ai_quant_lab/QuantModulePanel_AdvancedHelpers.h"
#include "screens/ai_quant_lab/QuantModulePanel_Common.h"
#include "screens/ai_quant_lab/QuantModulePanel_GsHelpers.h"
#include "screens/ai_quant_lab/QuantModulePanel_Styles.h"
@@ -50,44 +54,9 @@ using namespace fincept::services::quant;
using namespace fincept::screens::quant_styles;
using namespace fincept::screens::quant_common;
using namespace fincept::screens::quant_gs_helpers;
-
-namespace {
-
-[[maybe_unused]] QString fmt_num_safe(const QJsonValue& v, int decimals = 4) {
- if (v.isNull() || v.isUndefined())
- return QStringLiteral("—");
- return QString::number(v.toDouble(), 'f', decimals);
-}
-
-QString fmt_int_safe(const QJsonValue& v) {
- if (v.isNull() || v.isUndefined())
- return QStringLiteral("—");
- return QString::number(v.toInt());
-}
-
-QString fmt_pct_safe(const QJsonValue& v, int decimals = 2) {
- if (v.isNull() || v.isUndefined())
- return QStringLiteral("—");
- return QString::number(v.toDouble() * 100.0, 'f', decimals) + "%";
-}
-
-// Returns false if the payload was an error (already displayed via callback).
-bool check_success(const QJsonObject& payload, const std::function<void(const QString&)>& display_error_fn) {
- if (!payload.value("success").toBool(false)) {
- const QString err =
- payload.value("error").toString(QCoreApplication::translate("QuantModulePanel", "Unknown error"));
- const QString kind = payload.value("error_kind").toString();
- const QString prefix = kind == "validation" ? QCoreApplication::translate("QuantModulePanel", "Input error: ")
- : kind == "runtime"
- ? QCoreApplication::translate("QuantModulePanel", "Computation failed: ")
- : QString();
- display_error_fn(prefix + err);
- return false;
- }
- return true;
-}
-
-} // namespace
+// check_success() / fmt_int_safe() / fmt_pct_safe() used to be duplicated in a
+// file-local anonymous namespace here; they now come from the shared header.
+using namespace fincept::screens::quant_advanced_helpers;
// ═════════════════════════════════════════════════════════════════════════════
// 1. RL TRADING
diff --git a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_AdvancedHelpers.h b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_AdvancedHelpers.h
index a652d584f..5f16b4071 100644
--- a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_AdvancedHelpers.h
+++ b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_AdvancedHelpers.h
@@ -12,6 +12,7 @@
#include <QAbstractItemView>
#include <QColor>
+#include <QCoreApplication>
#include <QHeaderView>
#include <QJsonObject>
#include <QJsonValue>
@@ -64,11 +65,20 @@ inline QString verdict_color_for(const QString& v) {
}
// Returns false if the payload was an error (already displayed via callback) — caller should bail.
+//
+// Single implementation for every QuantModulePanel display TU. It used to be
+// copy-pasted into anonymous namespaces in CoreDisplays.cpp and
+// AIMLDisplays.cpp; those copies were translated while this one was not, so the
+// same message appeared translated on some panels and not on others.
inline bool check_success(const QJsonObject& payload, const std::function<void(const QString&)>& display_error_fn) {
if (!payload.value("success").toBool(false)) {
- const QString err = payload.value("error").toString("Unknown error");
+ const QString err =
+ payload.value("error").toString(QCoreApplication::translate("QuantModulePanel", "Unknown error"));
const QString kind = payload.value("error_kind").toString();
- const QString prefix = kind == "validation" ? "Input error: " : kind == "runtime" ? "Computation failed: " : "";
+ const QString prefix = kind == "validation" ? QCoreApplication::translate("QuantModulePanel", "Input error: ")
+ : kind == "runtime"
+ ? QCoreApplication::translate("QuantModulePanel", "Computation failed: ")
+ : QString();
display_error_fn(prefix + err);
return false;
}
@@ -84,7 +94,9 @@ inline QTableWidget* build_weights_table(const QJsonObject& weights, QWidget* pa
[](const auto& a, const auto& b) { return std::abs(a.second) > std::abs(b.second); });
auto* table = new QTableWidget(rows.size(), 2, parent);
- table->setHorizontalHeaderLabels({"Asset", "Weight"});
+ // These two were the only untranslated column headers in the panel family.
+ table->setHorizontalHeaderLabels({QCoreApplication::translate("QuantModulePanel", "Asset"),
+ QCoreApplication::translate("QuantModulePanel", "Weight")});
table->verticalHeader()->setVisible(false);
table->setEditTriggers(QAbstractItemView::NoEditTriggers);
table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
diff --git a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_Backtesting.cpp b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_Backtesting.cpp
index 2cca9e7a2..8fc3338be 100644
--- a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_Backtesting.cpp
+++ b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_Backtesting.cpp
@@ -114,20 +114,40 @@ QWidget* QuantModulePanel::build_backtesting_panel() {
auto* run = make_run_button(tr("RUN BACKTEST"), w);
connect(run, &QPushButton::clicked, this, [this]() {
- status_label_->setText(tr("Backtesting..."));
+ const QJsonArray tickers = parse_csv_strings(text_inputs_["bt_instruments"]->text());
+ if (tickers.isEmpty()) {
+ display_error(tr("Enter at least one instrument, e.g. AAPL,MSFT,GOOG."));
+ return;
+ }
+ const QDate start = date_inputs_["bt_start"]->date();
+ const QDate end = date_inputs_["bt_end"]->date();
+ if (start >= end) {
+ display_error(tr("Start date (%1) must be before end date (%2).")
+ .arg(start.toString("yyyy-MM-dd"), end.toString("yyyy-MM-dd")));
+ return;
+ }
+ // NOTE: top_k > universe size degenerates to "hold everything" and makes
+ // the turnover / win-rate figures meaningless. Not blocked here because
+ // the shipped default (topk = 10) is larger than the 4-name placeholder
+ // universe — flagging it would reject the out-of-box configuration.
+ const int topk = int_inputs_["bt_topk"]->value();
+ show_loading(tr("Backtesting %1 over %2 instrument(s), %3 → %4...")
+ .arg(combo_inputs_["bt_strategy"]->currentText())
+ .arg(tickers.size())
+ .arg(start.toString("yyyy-MM-dd"), end.toString("yyyy-MM-dd")));
QJsonObject params;
QJsonObject strategy_config;
strategy_config["type"] = combo_inputs_["bt_strategy"]->currentText();
- strategy_config["topk"] = int_inputs_["bt_topk"]->value();
+ strategy_config["topk"] = topk;
params["strategy_config"] = strategy_config;
QJsonObject dataset;
dataset["instruments"] = text_inputs_["bt_instruments"]->text();
- dataset["start_date"] = date_inputs_["bt_start"]->date().toString("yyyy-MM-dd");
- dataset["end_date"] = date_inputs_["bt_end"]->date().toString("yyyy-MM-dd");
+ dataset["start_date"] = start.toString("yyyy-MM-dd");
+ dataset["end_date"] = end.toString("yyyy-MM-dd");
params["dataset_config"] = dataset;
QJsonObject portfolio;
portfolio["initial_capital"] = double_inputs_["bt_capital"]->value();
- portfolio["benchmark"] = text_inputs_["bt_benchmark"]->text();
+ portfolio["benchmark"] = text_inputs_["bt_benchmark"]->text().trimmed();
params["portfolio_config"] = portfolio;
AIQuantLabService::instance().run_backtest(params);
});
@@ -140,11 +160,13 @@ QWidget* QuantModulePanel::build_backtesting_panel() {
.arg(ui::colors::AMBER(), ui::colors::AMBER_DIM(), ui::colors::BG_BASE()));
connect(open_terminal, &QPushButton::clicked, this, [this]() {
auto* instruments_edit = text_inputs_.value("bt_instruments");
- if (!instruments_edit || instruments_edit->text().trimmed().isEmpty())
+ // Used to return silently — the button simply did nothing and the user
+ // had no idea why.
+ if (!instruments_edit || instruments_edit->text().trimmed().isEmpty()) {
+ display_error(tr("Enter at least one instrument before opening the Backtesting terminal."));
return;
- QJsonArray symbols;
- for (const auto& s : instruments_edit->text().split(',', Qt::SkipEmptyParts))
- symbols.append(s.trimmed());
+ }
+ const QJsonArray symbols = parse_csv_strings(instruments_edit->text());
QJsonObject config;
config["symbols"] = symbols;
auto* capital_spin = double_inputs_.value("bt_capital");
diff --git a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_CFA.cpp b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_CFA.cpp
index c70b5f0a4..6b9efcf6a 100644
--- a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_CFA.cpp
+++ b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_CFA.cpp
@@ -349,7 +349,6 @@ QWidget* QuantModulePanel::build_cfa_quant_panel() {
// ── Run button ──────────────────────────────────────────────────────────
auto* run = make_run_button(tr("RUN ANALYSIS"), w);
connect(run, &QPushButton::clicked, this, [this]() {
- status_label_->setText(tr("Running..."));
const QString cmd = combo_inputs_["cfa_analysis"]->currentText();
const QString raw = text_inputs_["cfa_symbol"]->text().trimmed();
@@ -361,8 +360,8 @@ QWidget* QuantModulePanel::build_cfa_quant_panel() {
// Everything else reads from "data" (or "population" for sampling_techniques).
const bool needs_data = (cmd != "sampling_error_analysis" && cmd != "central_limit_theorem");
if (needs_data && raw.isEmpty()) {
+ // display_error() already sets the status label to "Error".
display_error(tr("Please enter a ticker symbol or comma-separated values"));
- status_label_->setText(tr("Error"));
return;
}
if (cmd == "sampling_techniques")
@@ -433,6 +432,9 @@ QWidget* QuantModulePanel::build_cfa_quant_panel() {
params["data_name"] = text_inputs_["cfa_validate_name"]->text();
}
+ QString label = cmd;
+ label.replace('_', ' ');
+ show_loading(needs_data ? tr("Running %1 on %2...").arg(label, raw) : tr("Running %1...").arg(label));
AIQuantLabService::instance().run_module("cfa_quant", cmd, params);
});
vl->addWidget(run);
diff --git a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_Common.h b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_Common.h
index 804e5edec..e9ba11860 100644
--- a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_Common.h
+++ b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_Common.h
@@ -1,12 +1,14 @@
// src/screens/ai_quant_lab/QuantModulePanel_Common.h
//
-// Private header — included only by QuantModulePanel*.cpp translation units.
+// Private header -- included only by QuantModulePanel*.cpp translation units.
// Provides cross-panel helpers that were originally in file-static anonymous
// namespaces inside QuantModulePanel.cpp. Several panel families (GS Quant,
// Functime, Statsmodels, Fortitudo, Gluonts, Quant Reporting) share the same
// numeric-input parsing and synthetic-sample generators, so they live here.
#pragma once
+#include <QCoreApplication>
+#include <QDate>
#include <QJsonArray>
#include <QRegularExpression>
#include <QString>
@@ -37,6 +39,50 @@ inline bool parse_doubles(const QString& text, QJsonArray& out, QString* bad_tok
return true;
}
+// Split a comma-separated string into a JSON array of trimmed, non-empty
+// strings. Replaces the ad-hoc `for (auto& s : text.split(',')) arr.append(...)`
+// loops that shipped `[""]` to Python when the field was left blank.
+inline QJsonArray parse_csv_strings(const QString& text, bool lowercase = false) {
+ QJsonArray out;
+ for (const QString& part : text.split(',', Qt::SkipEmptyParts)) {
+ const QString t = part.trimmed();
+ if (!t.isEmpty())
+ out.append(lowercase ? t.toLower() : t);
+ }
+ return out;
+}
+
+// Validate an OPTIONAL free-text YYYY-MM-DD date range. Blank fields are
+// allowed (the Python side then picks its own defaults) but garbage is not --
+// those used to be forwarded verbatim and blew up inside Qlib.
+// Returns an empty QString on success; otherwise a user-facing message.
+// iso_start / iso_end receive the normalised values (empty when left blank).
+inline QString check_iso_range(const QString& start_text, const QString& end_text, QString& iso_start,
+ QString& iso_end) {
+ const auto tr_ = [](const char* s) { return QCoreApplication::translate("QuantModulePanel", s); };
+ iso_start.clear();
+ iso_end.clear();
+
+ const QString s = start_text.trimmed();
+ const QString e = end_text.trimmed();
+ QDate ds, de;
+ if (!s.isEmpty()) {
+ ds = QDate::fromString(s, QStringLiteral("yyyy-MM-dd"));
+ if (!ds.isValid())
+ return tr_("Start date must be YYYY-MM-DD (got '%1').").arg(s);
+ iso_start = ds.toString(QStringLiteral("yyyy-MM-dd"));
+ }
+ if (!e.isEmpty()) {
+ de = QDate::fromString(e, QStringLiteral("yyyy-MM-dd"));
+ if (!de.isValid())
+ return tr_("End date must be YYYY-MM-DD (got '%1').").arg(e);
+ iso_end = de.toString(QStringLiteral("yyyy-MM-dd"));
+ }
+ if (ds.isValid() && de.isValid() && ds > de)
+ return tr_("Start date (%1) is after end date (%2).").arg(iso_start, iso_end);
+ return {};
+}
+
// Generate a small synthetic returns sample so the user can try the panel
// without typing 252 numbers. Produces ~1y of plausible daily returns.
inline QString sample_returns(unsigned seed = 1, int n = 252, double mu = 0.0005, double sigma = 0.012) {
@@ -81,7 +127,7 @@ inline QString sample_series(unsigned seed = 1, int n = 200, double base = 50.0,
return out.join(',');
}
-// Trending random walk — useful for stationarity testing where d=1 should win.
+// Trending random walk -- useful for stationarity testing where d=1 should win.
inline QString sample_random_walk(unsigned seed = 1, int n = 150, double drift = 0.05, double sigma = 1.0) {
quint32 state = seed ? seed : 1u;
auto rand01 = [&]() -> double {
diff --git a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_CoreDisplays.cpp b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_CoreDisplays.cpp
index 947b46da3..3771e02f2 100644
--- a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_CoreDisplays.cpp
+++ b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_CoreDisplays.cpp
@@ -14,6 +14,7 @@
// QuantModulePanel_Backtesting.cpp). The dispatch in on_result still
// routes there directly.
#include "screens/ai_quant_lab/QuantModulePanel.h"
+#include "screens/ai_quant_lab/QuantModulePanel_AdvancedHelpers.h"
#include "screens/ai_quant_lab/QuantModulePanel_Common.h"
#include "screens/ai_quant_lab/QuantModulePanel_GsHelpers.h"
#include "screens/ai_quant_lab/QuantModulePanel_Styles.h"
@@ -49,32 +50,9 @@ using namespace fincept::services::quant;
using namespace fincept::screens::quant_styles;
using namespace fincept::screens::quant_common;
using namespace fincept::screens::quant_gs_helpers;
-
-namespace {
-
-[[maybe_unused]] QString fmt_int_safe(const QJsonValue& v) {
- if (v.isNull() || v.isUndefined())
- return QStringLiteral("—");
- return QString::number(v.toInt());
-}
-
-// Returns false if the payload was an error (already displayed via callback).
-bool check_success(const QJsonObject& payload, const std::function<void(const QString&)>& display_error_fn) {
- if (!payload.value("success").toBool(false)) {
- const QString err =
- payload.value("error").toString(QCoreApplication::translate("QuantModulePanel", "Unknown error"));
- const QString kind = payload.value("error_kind").toString();
- const QString prefix = kind == "validation" ? QCoreApplication::translate("QuantModulePanel", "Input error: ")
- : kind == "runtime"
- ? QCoreApplication::translate("QuantModulePanel", "Computation failed: ")
- : QString();
- display_error_fn(prefix + err);
- return false;
- }
- return true;
-}
-
-} // namespace
+// check_success() / fmt_*_safe() used to be duplicated in a file-local
+// anonymous namespace here; they now come from the shared helper header.
+using namespace fincept::screens::quant_advanced_helpers;
// ═════════════════════════════════════════════════════════════════════════════
// 1. FACTOR DISCOVERY
diff --git a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_DeepAgent.cpp b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_DeepAgent.cpp
index 8933d8c68..b88d23640 100644
--- a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_DeepAgent.cpp
+++ b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_DeepAgent.cpp
@@ -116,6 +116,16 @@ QWidget* QuantModulePanel::build_deep_agent_panel() {
}
status_label_->setText(tr("Running..."));
clear_results();
+ // The result lands in agent_output_, so put the in-flight message there
+ // too — otherwise the box keeps showing the previous run's answer and
+ // the user has no signal that anything is happening. (show_loading()
+ // would paint a spinner into the results pane below the 300px output
+ // box, and the execute_task result branch never clears it.)
+ if (agent_output_)
+ agent_output_->setPlainText(
+ tr("Running multi-agent analysis...\n\n"
+ "The LangGraph orchestrator delegates to specialist subagents and calls the LLM "
+ "several times; this typically takes a few minutes. Results replace this message."));
QJsonObject params;
params["task"] = task;
params["agent_type"] = agent_type->currentText();
@@ -212,33 +222,51 @@ QWidget* QuantModulePanel::build_rd_agent_tab(QComboBox* llm_combo) {
});
sbl->addWidget(ui_btn);
- auto* mcp_btn = new QPushButton(tr("MCP TOOLS"), status_bar);
+ // Not checkable: there is no rd_agent "stop MCP server" command, so a
+ // toggle that un-checks would claim to have stopped a server that is still
+ // running. Plain action + a status query instead.
+ auto* mcp_btn = new QPushButton(tr("START MCP TOOLS"), status_bar);
mcp_btn->setCursor(Qt::PointingHandCursor);
- mcp_btn->setCheckable(true);
- mcp_btn->setToolTip(tr("Start/stop the Fincept MCP tool server\n"
+ mcp_btn->setToolTip(tr("Start the Fincept MCP tool server.\n"
"Gives RD-Agent loops access to market data,\n"
- "financial news and economics tools."));
+ "financial news and economics tools.\n"
+ "The server keeps running until the terminal exits."));
mcp_btn->setStyleSheet(QString("QPushButton { background:transparent; color:%1; border:1px solid %1;"
"font-family:%2; font-size:%3px; padding:2px 8px; border-radius:2px; }"
- "QPushButton:checked { background:%4; color:%5; border-color:%4; }"
- "QPushButton:hover { background:%1; color:%5; }")
+ "QPushButton:hover { background:%1; color:%4; }")
.arg(ui::colors::TEXT_TERTIARY())
.arg(ui::fonts::DATA_FAMILY)
.arg(ui::fonts::TINY)
- .arg(module_.color.name())
.arg(ui::colors::BG_BASE()));
- connect(mcp_btn, &QPushButton::toggled, this, [mcp_btn, status_txt](bool checked) {
- if (checked) {
- status_txt->setText(tr("Starting MCP tool server..."));
- AIQuantLabService::instance().rd_agent_start_mcp_server();
- } else {
- status_txt->setText(tr("MCP tool server stopped"));
- mcp_btn->setText(tr("MCP TOOLS"));
- }
+ connect(mcp_btn, &QPushButton::clicked, this, [status_txt]() {
+ status_txt->setText(tr("Starting MCP tool server..."));
+ AIQuantLabService::instance().rd_agent_start_mcp_server();
});
sbl->addWidget(mcp_btn);
+
+ auto* mcp_status_btn = new QPushButton(tr("MCP STATUS"), status_bar);
+ mcp_status_btn->setCursor(Qt::PointingHandCursor);
+ mcp_status_btn->setToolTip(tr("Report whether the MCP tool server is installed and which ports are live."));
+ mcp_status_btn->setStyleSheet(mcp_btn->styleSheet());
+ connect(mcp_status_btn, &QPushButton::clicked, this, [status_txt]() {
+ status_txt->setText(tr("Querying MCP status..."));
+ AIQuantLabService::instance().rd_agent_mcp_status();
+ });
+ sbl->addWidget(mcp_status_btn);
vl->addWidget(status_bar);
+ // Validation errors raised from the RD-Agent sub-tabs must NOT go through
+ // display_error(): that paints into the Deep Analysis tab's results pane,
+ // which is on the other page of the outer QTabWidget and therefore invisible
+ // to whoever just clicked. Surface them in this tab instead.
+ auto rd_error = [this, status_txt](const QString& msg) {
+ status_txt->setText(msg);
+ if (rd_agent_output_)
+ rd_agent_output_->setPlainText(msg);
+ if (status_label_)
+ status_label_->setText(tr("Error"));
+ };
+
// ── Sub-tab 1: Factor Mining ─────────────────────────────────────────────
auto* fm_w = new QWidget(sub);
auto* fm_vl = new QVBoxLayout(fm_w);
@@ -270,34 +298,35 @@ QWidget* QuantModulePanel::build_rd_agent_tab(QComboBox* llm_combo) {
auto* fm_iter = new QSpinBox(fm_w);
fm_iter->setRange(1, 100);
fm_iter->setValue(10);
- fm_iter->setStyleSheet(input_ss());
+ fm_iter->setStyleSheet(spinbox_ss());
fm_vl->addWidget(build_input_row(tr("Max Iterations"), fm_iter, fm_w));
auto* fm_ic = make_double_spin(0.01, 0.50, 0.05, 3, "", fm_w);
fm_vl->addWidget(build_input_row(tr("Target IC"), fm_ic, fm_w));
auto* fm_run = make_run_button(tr("START FACTOR MINING"), fm_w);
- connect(fm_run, &QPushButton::clicked, this, [this, fm_task, fm_market, fm_iter, fm_ic, status_txt, llm_combo]() {
- auto desc_text = fm_task->toPlainText().trimmed();
- if (desc_text.isEmpty()) {
- display_error(tr("Enter a task description."));
- return;
- }
- auto cfg = llm_config_from_combo(llm_combo);
- if (cfg.isEmpty()) {
- display_error(tr("Select an LLM profile before running."));
- return;
- }
- status_label_->setText(tr("Starting..."));
- status_txt->setText(tr("Factor mining started..."));
- QJsonObject params;
- params["task_description"] = desc_text;
- params["target_market"] = fm_market->currentText();
- params["max_iterations"] = fm_iter->value();
- params["target_ic"] = fm_ic->value();
- params["config"] = cfg;
- AIQuantLabService::instance().rd_agent_start_factor_mining(params);
- });
+ connect(fm_run, &QPushButton::clicked, this,
+ [this, fm_task, fm_market, fm_iter, fm_ic, status_txt, llm_combo, rd_error]() {
+ auto desc_text = fm_task->toPlainText().trimmed();
+ if (desc_text.isEmpty()) {
+ rd_error(tr("Enter a task description."));
+ return;
+ }
+ auto cfg = llm_config_from_combo(llm_combo);
+ if (cfg.isEmpty()) {
+ rd_error(tr("Select an LLM profile before running (Settings → LLM Config)."));
+ return;
+ }
+ status_label_->setText(tr("Starting..."));
+ status_txt->setText(tr("Factor mining started..."));
+ QJsonObject params;
+ params["task_description"] = desc_text;
+ params["target_market"] = fm_market->currentText();
+ params["max_iterations"] = fm_iter->value();
+ params["target_ic"] = fm_ic->value();
+ params["config"] = cfg;
+ AIQuantLabService::instance().rd_agent_start_factor_mining(params);
+ });
fm_vl->addWidget(fm_run);
fm_vl->addStretch();
sub->addTab(fm_w, tr("Factor Mining"));
@@ -332,25 +361,26 @@ QWidget* QuantModulePanel::build_rd_agent_tab(QComboBox* llm_combo) {
auto* mo_iter = new QSpinBox(mo_w);
mo_iter->setRange(1, 100);
mo_iter->setValue(10);
- mo_iter->setStyleSheet(input_ss());
+ mo_iter->setStyleSheet(spinbox_ss());
mo_vl->addWidget(build_input_row(tr("Max Iterations"), mo_iter, mo_w));
auto* mo_run = make_run_button(tr("START MODEL OPTIMIZATION"), mo_w);
- connect(mo_run, &QPushButton::clicked, this, [this, mo_model, mo_target, mo_iter, status_txt, llm_combo]() {
- auto cfg = llm_config_from_combo(llm_combo);
- if (cfg.isEmpty()) {
- display_error(tr("Select an LLM profile before running."));
- return;
- }
- status_label_->setText(tr("Starting..."));
- status_txt->setText(tr("Model optimization started..."));
- QJsonObject params;
- params["model_type"] = mo_model->currentText();
- params["optimization_target"] = mo_target->currentText();
- params["max_iterations"] = mo_iter->value();
- params["config"] = cfg;
- AIQuantLabService::instance().rd_agent_start_model_optimization(params);
- });
+ connect(mo_run, &QPushButton::clicked, this,
+ [this, mo_model, mo_target, mo_iter, status_txt, llm_combo, rd_error]() {
+ auto cfg = llm_config_from_combo(llm_combo);
+ if (cfg.isEmpty()) {
+ rd_error(tr("Select an LLM profile before running (Settings → LLM Config)."));
+ return;
+ }
+ status_label_->setText(tr("Starting..."));
+ status_txt->setText(tr("Model optimization started..."));
+ QJsonObject params;
+ params["model_type"] = mo_model->currentText();
+ params["optimization_target"] = mo_target->currentText();
+ params["max_iterations"] = mo_iter->value();
+ params["config"] = cfg;
+ AIQuantLabService::instance().rd_agent_start_model_optimization(params);
+ });
mo_vl->addWidget(mo_run);
mo_vl->addStretch();
sub->addTab(mo_w, tr("Model Optimization"));
@@ -386,30 +416,31 @@ QWidget* QuantModulePanel::build_rd_agent_tab(QComboBox* llm_combo) {
auto* qr_iter = new QSpinBox(qr_w);
qr_iter->setRange(1, 100);
qr_iter->setValue(15);
- qr_iter->setStyleSheet(input_ss());
+ qr_iter->setStyleSheet(spinbox_ss());
qr_vl->addWidget(build_input_row(tr("Max Iterations"), qr_iter, qr_w));
auto* qr_run = make_run_button(tr("START QUANT RESEARCH"), qr_w);
- connect(qr_run, &QPushButton::clicked, this, [this, qr_goal, qr_market, qr_iter, status_txt, llm_combo]() {
- auto goal = qr_goal->toPlainText().trimmed();
- if (goal.isEmpty()) {
- display_error(tr("Enter a research goal."));
- return;
- }
- auto cfg = llm_config_from_combo(llm_combo);
- if (cfg.isEmpty()) {
- display_error(tr("Select an LLM profile before running."));
- return;
- }
- status_label_->setText(tr("Starting..."));
- status_txt->setText(tr("Quant research started..."));
- QJsonObject params;
- params["research_goal"] = goal;
- params["target_market"] = qr_market->currentText();
- params["max_iterations"] = qr_iter->value();
- params["config"] = cfg;
- AIQuantLabService::instance().rd_agent_start_quant_research(params);
- });
+ connect(qr_run, &QPushButton::clicked, this,
+ [this, qr_goal, qr_market, qr_iter, status_txt, llm_combo, rd_error]() {
+ auto goal = qr_goal->toPlainText().trimmed();
+ if (goal.isEmpty()) {
+ rd_error(tr("Enter a research goal."));
+ return;
+ }
+ auto cfg = llm_config_from_combo(llm_combo);
+ if (cfg.isEmpty()) {
+ rd_error(tr("Select an LLM profile before running (Settings → LLM Config)."));
+ return;
+ }
+ status_label_->setText(tr("Starting..."));
+ status_txt->setText(tr("Quant research started..."));
+ QJsonObject params;
+ params["research_goal"] = goal;
+ params["target_market"] = qr_market->currentText();
+ params["max_iterations"] = qr_iter->value();
+ params["config"] = cfg;
+ AIQuantLabService::instance().rd_agent_start_quant_research(params);
+ });
qr_vl->addWidget(qr_run);
qr_vl->addStretch();
sub->addTab(qr_w, tr("Quant Research"));
@@ -492,6 +523,20 @@ QWidget* QuantModulePanel::build_rd_agent_tab(QComboBox* llm_combo) {
.arg(ui::fonts::TINY)
.arg(ui::colors::BG_BASE()));
tm_hl->addWidget(factors_btn);
+
+ // GET MODEL / STATUS were referenced by the output placeholder text and by
+ // on_result() (get_optimized_model / get_task_status branches) but had no
+ // button — the service calls were unreachable from the UI.
+ auto* model_btn = new QPushButton(tr("GET MODEL"), tm_toolbar);
+ model_btn->setCursor(Qt::PointingHandCursor);
+ model_btn->setStyleSheet(factors_btn->styleSheet());
+ tm_hl->addWidget(model_btn);
+
+ auto* status_btn = new QPushButton(tr("TASK STATUS"), tm_toolbar);
+ status_btn->setCursor(Qt::PointingHandCursor);
+ status_btn->setStyleSheet(factors_btn->styleSheet());
+ tm_hl->addWidget(status_btn);
+
tm_hl->addStretch();
tm_vl->addWidget(tm_toolbar);
@@ -515,44 +560,67 @@ QWidget* QuantModulePanel::build_rd_agent_tab(QComboBox* llm_combo) {
tm_vl->addWidget(rd_agent_output_);
// Wire toolbar buttons
- connect(refresh_btn, &QPushButton::clicked, this, [filter_combo]() {
- auto filter = filter_combo->currentData().toString();
+ connect(refresh_btn, &QPushButton::clicked, this, [filter_combo, status_txt]() {
+ const auto filter = filter_combo->currentData().toString();
+ status_txt->setText(tr("Refreshing task list..."));
AIQuantLabService::instance().rd_agent_list_tasks(filter == "All" ? QString{} : filter);
});
- connect(stop_btn, &QPushButton::clicked, this, [this, task_id_input]() {
- auto tid = task_id_input->text().trimmed();
- if (tid.isEmpty() && rd_task_table_->currentRow() >= 0)
+ // Resolve the target task: the text field wins, otherwise the selected row.
+ // Errors go to rd_agent_output_ (visible in this tab) — display_error()
+ // paints into the Deep Analysis tab's results pane, which is hidden here.
+ auto resolve_task_id = [this, task_id_input, status_txt]() -> QString {
+ QString tid = task_id_input->text().trimmed();
+ if (tid.isEmpty() && rd_task_table_->currentRow() >= 0 && rd_task_table_->item(rd_task_table_->currentRow(), 0))
tid = rd_task_table_->item(rd_task_table_->currentRow(), 0)->text();
if (tid.isEmpty()) {
- display_error(tr("Select or enter a task ID."));
- return;
+ status_txt->setText(tr("Select a row or type a task ID first."));
+ if (rd_agent_output_)
+ rd_agent_output_->setPlainText(tr("Select a task row (or paste a task ID) before using this action."));
}
+ return tid;
+ };
+
+ connect(stop_btn, &QPushButton::clicked, this, [resolve_task_id, status_txt]() {
+ const QString tid = resolve_task_id();
+ if (tid.isEmpty())
+ return;
+ status_txt->setText(tr("Stopping %1...").arg(tid));
AIQuantLabService::instance().rd_agent_stop_task(tid);
});
- connect(resume_btn, &QPushButton::clicked, this, [this, task_id_input]() {
- auto tid = task_id_input->text().trimmed();
- if (tid.isEmpty() && rd_task_table_->currentRow() >= 0)
- tid = rd_task_table_->item(rd_task_table_->currentRow(), 0)->text();
- if (tid.isEmpty()) {
- display_error(tr("Select or enter a task ID."));
+ connect(resume_btn, &QPushButton::clicked, this, [resolve_task_id, status_txt]() {
+ const QString tid = resolve_task_id();
+ if (tid.isEmpty())
return;
- }
+ status_txt->setText(tr("Resuming %1...").arg(tid));
AIQuantLabService::instance().rd_agent_resume_task(tid);
});
- connect(factors_btn, &QPushButton::clicked, this, [this, task_id_input]() {
- auto tid = task_id_input->text().trimmed();
- if (tid.isEmpty() && rd_task_table_->currentRow() >= 0)
- tid = rd_task_table_->item(rd_task_table_->currentRow(), 0)->text();
- if (tid.isEmpty()) {
- display_error(tr("Select or enter a task ID."));
+ connect(factors_btn, &QPushButton::clicked, this, [resolve_task_id, status_txt]() {
+ const QString tid = resolve_task_id();
+ if (tid.isEmpty())
return;
- }
+ status_txt->setText(tr("Loading factors for %1...").arg(tid));
AIQuantLabService::instance().rd_agent_get_discovered_factors(tid);
});
+ connect(model_btn, &QPushButton::clicked, this, [resolve_task_id, status_txt]() {
+ const QString tid = resolve_task_id();
+ if (tid.isEmpty())
+ return;
+ status_txt->setText(tr("Loading optimized model for %1...").arg(tid));
+ AIQuantLabService::instance().rd_agent_get_optimized_model(tid);
+ });
+
+ connect(status_btn, &QPushButton::clicked, this, [resolve_task_id, status_txt]() {
+ const QString tid = resolve_task_id();
+ if (tid.isEmpty())
+ return;
+ status_txt->setText(tr("Querying %1...").arg(tid));
+ AIQuantLabService::instance().rd_agent_get_task_status(tid);
+ });
+
// Populate task_id_input on row click
connect(rd_task_table_, &QTableWidget::currentCellChanged, this, [task_id_input, this](int row, int, int, int) {
if (row >= 0 && rd_task_table_->item(row, 0))
diff --git a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_Fortitudo.cpp b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_Fortitudo.cpp
index 926c38333..833ecc89c 100644
--- a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_Fortitudo.cpp
+++ b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_Fortitudo.cpp
@@ -267,7 +267,12 @@ QWidget* QuantModulePanel::build_fortitudo_panel() {
if (maxw > 0.0)
params["max_weight"] = maxw;
// Translate annual % rf rate to per-day decimal for daily returns.
- params["risk_free_rate"] = double_inputs_["ft_mv_rf"]->value() / 100.0 / 252.0;
+ // Geometric (compounded) de-annualisation, matching the target_return
+ // conversion below. These two used to disagree: rf was divided by 252
+ // while the target was compounded, so the Sharpe objective compared a
+ // simple-interest hurdle against compounded portfolio returns
+ // (~2% relative bias in the rf term at 4.5% p.a.).
+ params["risk_free_rate"] = std::pow(1.0 + double_inputs_["ft_mv_rf"]->value() / 100.0, 1.0 / 252.0) - 1.0;
if (obj == "target_return") {
// Translate annualized % to per-day decimal so the optimizer's
// expected_return constraint matches.
@@ -391,7 +396,8 @@ QWidget* QuantModulePanel::build_fortitudo_panel() {
const double maxw = double_inputs_["ft_ef_max"]->value();
if (maxw > 0.0)
params["max_weight"] = maxw;
- params["risk_free_rate"] = double_inputs_["ft_ef_rf"]->value() / 100.0 / 252.0;
+ // Geometric de-annualisation — same convention as the MV/CVaR tabs.
+ params["risk_free_rate"] = std::pow(1.0 + double_inputs_["ft_ef_rf"]->value() / 100.0, 1.0 / 252.0) - 1.0;
show_loading(
tr("Fetching %1 and tracing %2-point frontier...").arg(tk).arg(int_inputs_["ft_ef_n_points"]->value()));
AIQuantLabService::instance().fort_efficient_frontier(params);
diff --git a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_HFT.cpp b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_HFT.cpp
index 9402ce3ce..c90c6c55c 100644
--- a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_HFT.cpp
+++ b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_HFT.cpp
@@ -120,6 +120,22 @@ QWidget* QuantModulePanel::build_hft_panel() {
top_hl->addWidget(latency_lbl);
vl->addWidget(top_bar);
+ // Shared pre-flight guard. Every HFT action forwards the symbol straight to
+ // ccxt; a blank field used to surface as an opaque exchange traceback.
+ // Returns an empty string (after showing the error) when unusable.
+ auto require_symbol = [this]() -> QString {
+ const QString s = text_inputs_["hft_symbol"]->text().trimmed().toUpper();
+ if (s.isEmpty()) {
+ display_error(tr("Enter a symbol (e.g. BTC/USDT) before running."));
+ return {};
+ }
+ if (!s.contains('/')) {
+ display_error(tr("'%1' is not a valid pair. Use BASE/QUOTE form, e.g. BTC/USDT.").arg(s));
+ return {};
+ }
+ return s;
+ };
+
// ── Tab widget ────────────────────────────────────────────────────────────
auto* tabs = new QTabWidget(w);
tabs->setStyleSheet(tab_ss(accent));
@@ -136,11 +152,14 @@ QWidget* QuantModulePanel::build_hft_panel() {
auto* ob_ctrl = new QHBoxLayout;
ob_ctrl->setSpacing(8);
auto* ob_fetch = make_run_button(tr("FETCH LIVE ORDER BOOK"), ob_tab);
- connect(ob_fetch, &QPushButton::clicked, this, [this]() {
+ connect(ob_fetch, &QPushButton::clicked, this, [this, require_symbol]() {
+ const QString sym = require_symbol();
+ if (sym.isEmpty())
+ return;
status_label_->setText(tr("Fetching live order book..."));
QJsonObject p;
p["exchange"] = combo_inputs_["hft_exchange"]->currentText();
- p["symbol"] = text_inputs_["hft_symbol"]->text().trimmed();
+ p["symbol"] = sym;
p["depth"] = combo_inputs_["hft_depth"]->currentText().toInt();
AIQuantLabService::instance().hft_create_orderbook(p);
});
@@ -280,7 +299,8 @@ QWidget* QuantModulePanel::build_hft_panel() {
auto* mm_params = new QHBoxLayout;
mm_params->setSpacing(8);
auto* inv_spin = make_double_spin(-1000, 1000, 0.0, 4, " units", mm_section);
- int_inputs_["hft_inventory"] = nullptr;
+ // NOTE: do not insert nullptr sentinels into int_inputs_ — every other read
+ // site dereferences these hashes unconditionally.
double_inputs_["hft_inventory_d"] = inv_spin;
mm_params->addWidget(build_input_row(tr("Inventory"), inv_spin, mm_section));
auto* spread_spin = make_double_spin(1.0, 10.0, 1.5, 2, "×", mm_section);
@@ -292,11 +312,14 @@ QWidget* QuantModulePanel::build_hft_panel() {
mm_vl->addLayout(mm_params);
auto* mm_run = make_run_button(tr("CALCULATE OPTIMAL QUOTES"), mm_section);
- connect(mm_run, &QPushButton::clicked, this, [this]() {
+ connect(mm_run, &QPushButton::clicked, this, [this, require_symbol]() {
+ const QString sym = require_symbol();
+ if (sym.isEmpty())
+ return;
status_label_->setText(tr("Fetching live data + computing quotes..."));
QJsonObject p;
p["exchange"] = combo_inputs_["hft_exchange"]->currentText();
- p["symbol"] = text_inputs_["hft_symbol"]->text().trimmed();
+ p["symbol"] = sym;
p["inventory"] = double_inputs_["hft_inventory_d"]->value();
p["spread_multiplier"] = double_inputs_["hft_spread_mult"]->value();
p["risk_aversion"] = double_inputs_["hft_risk_aversion"]->value();
@@ -350,11 +373,14 @@ QWidget* QuantModulePanel::build_hft_panel() {
tox_vl->addLayout(tox_params);
auto* tox_run = make_run_button(tr("DETECT TOXIC FLOW"), tox_section);
- connect(tox_run, &QPushButton::clicked, this, [this]() {
+ connect(tox_run, &QPushButton::clicked, this, [this, require_symbol]() {
+ const QString sym = require_symbol();
+ if (sym.isEmpty())
+ return;
status_label_->setText(tr("Fetching trades + analyzing flow..."));
QJsonObject p;
p["exchange"] = combo_inputs_["hft_exchange"]->currentText();
- p["symbol"] = text_inputs_["hft_symbol"]->text().trimmed();
+ p["symbol"] = sym;
p["limit"] = combo_inputs_["hft_tox_limit"]->currentText().toInt();
AIQuantLabService::instance().hft_detect_toxic(p);
});
@@ -424,11 +450,14 @@ QWidget* QuantModulePanel::build_hft_panel() {
slip_vl->addLayout(slip_params);
auto* slip_run = make_run_button(tr("ESTIMATE SLIPPAGE"), slip_section);
- connect(slip_run, &QPushButton::clicked, this, [this]() {
+ connect(slip_run, &QPushButton::clicked, this, [this, require_symbol]() {
+ const QString sym = require_symbol();
+ if (sym.isEmpty())
+ return;
status_label_->setText(tr("Walking order book..."));
QJsonObject p;
p["exchange"] = combo_inputs_["hft_exchange"]->currentText();
- p["symbol"] = text_inputs_["hft_symbol"]->text().trimmed();
+ p["symbol"] = sym;
p["side"] = combo_inputs_["hft_slip_side"]->currentText();
p["quantity"] = double_inputs_["hft_slip_qty"]->value();
AIQuantLabService::instance().hft_execute_order(p);
@@ -487,11 +516,14 @@ QWidget* QuantModulePanel::build_hft_panel() {
auto* analyze_btn = make_run_button(tr("⚡ FULL ANALYSIS — FETCH ALL & COMPUTE"), bottom_bar);
analyze_btn->setToolTip(tr("Fetches live order book + trades, computes book metrics, market making quotes, toxic "
"flow, and slippage in one call"));
- connect(analyze_btn, &QPushButton::clicked, this, [this]() {
+ connect(analyze_btn, &QPushButton::clicked, this, [this, require_symbol]() {
+ const QString sym = require_symbol();
+ if (sym.isEmpty())
+ return;
status_label_->setText(tr("Running full microstructure analysis..."));
QJsonObject p;
p["exchange"] = combo_inputs_["hft_exchange"]->currentText();
- p["symbol"] = text_inputs_["hft_symbol"]->text().trimmed();
+ p["symbol"] = sym;
p["depth"] = combo_inputs_["hft_depth"]->currentText().toInt();
p["limit"] = combo_inputs_["hft_tox_limit"]->currentText().toInt();
p["inventory"] = double_inputs_["hft_inventory_d"]->value();
diff --git a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_LiveLearning.cpp b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_LiveLearning.cpp
index 2905f5537..06872709d 100644
--- a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_LiveLearning.cpp
+++ b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_LiveLearning.cpp
@@ -27,6 +27,7 @@
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
+#include <QJsonParseError>
#include <QJsonValue>
#include <QLabel>
#include <QLineEdit>
@@ -99,22 +100,31 @@ QWidget* QuantModulePanel::build_live_signals_panel() {
sigvl->addWidget(build_input_row(tr("End Date"), sig_end, sig_tab));
auto* sig_run = make_run_button(tr("FETCH SIGNALS"), sig_tab);
connect(sig_run, &QPushButton::clicked, this, [this]() {
- status_label_->setText(tr("Fetching..."));
+ const QJsonArray instr = parse_csv_strings(text_inputs_["ls_instruments"]->text(), /*lowercase=*/true);
+ if (instr.isEmpty()) {
+ display_error(tr("Enter at least one instrument, e.g. aapl,msft."));
+ return;
+ }
+ const QJsonArray fields = parse_csv_strings(text_inputs_["ls_fields"]->text());
+ if (fields.isEmpty()) {
+ display_error(tr("Enter at least one field, e.g. $close,$volume."));
+ return;
+ }
+ QString iso_start, iso_end;
+ if (const QString err =
+ check_iso_range(text_inputs_["ls_start"]->text(), text_inputs_["ls_end"]->text(), iso_start, iso_end);
+ !err.isEmpty()) {
+ display_error(err);
+ return;
+ }
+ show_loading(tr("Fetching %1 field(s) for %2 instrument(s)...").arg(fields.size()).arg(instr.size()));
QJsonObject params;
- QJsonArray instr;
- for (auto& s : text_inputs_["ls_instruments"]->text().split(','))
- if (!s.trimmed().isEmpty())
- instr.append(s.trimmed().toLower());
params["instruments"] = instr;
- QJsonArray fields;
- for (auto& s : text_inputs_["ls_fields"]->text().split(','))
- if (!s.trimmed().isEmpty())
- fields.append(s.trimmed());
params["fields"] = fields;
- if (!text_inputs_["ls_start"]->text().isEmpty())
- params["start_date"] = text_inputs_["ls_start"]->text().trimmed();
- if (!text_inputs_["ls_end"]->text().isEmpty())
- params["end_date"] = text_inputs_["ls_end"]->text().trimmed();
+ if (!iso_start.isEmpty())
+ params["start_date"] = iso_start;
+ if (!iso_end.isEmpty())
+ params["end_date"] = iso_end;
AIQuantLabService::instance().signals_get_data(params);
});
sigvl->addWidget(sig_run);
@@ -143,17 +153,25 @@ QWidget* QuantModulePanel::build_live_signals_panel() {
favl->addWidget(build_input_row(tr("End Date"), fa_end, fa_tab));
auto* fa_run = make_run_button(tr("RUN FACTOR ANALYSIS"), fa_tab);
connect(fa_run, &QPushButton::clicked, this, [this]() {
- status_label_->setText(tr("Analyzing..."));
+ const QJsonArray instr = parse_csv_strings(text_inputs_["ls_fa_instr"]->text(), /*lowercase=*/true);
+ if (instr.isEmpty()) {
+ display_error(tr("Enter at least one instrument, e.g. aapl,msft."));
+ return;
+ }
+ QString iso_start, iso_end;
+ if (const QString err = check_iso_range(text_inputs_["ls_fa_start"]->text(), text_inputs_["ls_fa_end"]->text(),
+ iso_start, iso_end);
+ !err.isEmpty()) {
+ display_error(err);
+ return;
+ }
+ show_loading(tr("Running factor analysis on %1 instrument(s)...").arg(instr.size()));
QJsonObject params;
- QJsonArray instr;
- for (auto& s : text_inputs_["ls_fa_instr"]->text().split(','))
- if (!s.trimmed().isEmpty())
- instr.append(s.trimmed().toLower());
params["instruments"] = instr;
- if (!text_inputs_["ls_fa_start"]->text().isEmpty())
- params["start_date"] = text_inputs_["ls_fa_start"]->text().trimmed();
- if (!text_inputs_["ls_fa_end"]->text().isEmpty())
- params["end_date"] = text_inputs_["ls_fa_end"]->text().trimmed();
+ if (!iso_start.isEmpty())
+ params["start_date"] = iso_start;
+ if (!iso_end.isEmpty())
+ params["end_date"] = iso_end;
AIQuantLabService::instance().signals_get_factor_analysis(params);
});
favl->addWidget(fa_run);
@@ -172,9 +190,14 @@ QWidget* QuantModulePanel::build_live_signals_panel() {
fivl->addWidget(build_input_row(tr("Model ID"), fi_model, fi_tab));
auto* fi_run = make_run_button(tr("GET FEATURE IMPORTANCE"), fi_tab);
connect(fi_run, &QPushButton::clicked, this, [this]() {
- status_label_->setText(tr("Loading..."));
+ const QString mid = text_inputs_["ls_fi_model"]->text().trimmed();
+ if (mid.isEmpty()) {
+ display_error(tr("Enter the ID of a trained model."));
+ return;
+ }
+ show_loading(tr("Loading feature importance for %1...").arg(mid));
QJsonObject params;
- params["model_id"] = text_inputs_["ls_fi_model"]->text().trimmed();
+ params["model_id"] = mid;
AIQuantLabService::instance().signals_get_feature_importance(params);
});
fivl->addWidget(fi_run);
@@ -214,7 +237,7 @@ QWidget* QuantModulePanel::build_online_learning_panel() {
mtvl->addWidget(mt_info);
auto* mt_list = make_run_button(tr("LIST ALL MODELS"), models_tab);
connect(mt_list, &QPushButton::clicked, this, [this]() {
- status_label_->setText(tr("Loading..."));
+ show_loading(tr("Loading online models..."));
AIQuantLabService::instance().online_list_models();
});
mtvl->addWidget(mt_list);
@@ -238,7 +261,7 @@ QWidget* QuantModulePanel::build_online_learning_panel() {
ctvl->addWidget(build_input_row(tr("Model ID"), ol_model_id, create_tab));
auto* ol_create = make_run_button(tr("CREATE MODEL"), create_tab);
connect(ol_create, &QPushButton::clicked, this, [this]() {
- status_label_->setText(tr("Creating..."));
+ show_loading(tr("Creating %1 online model...").arg(combo_inputs_["ol_model_type"]->currentText()));
QJsonObject params;
params["model_type"] = combo_inputs_["ol_model_type"]->currentText();
auto mid = text_inputs_["ol_model_id"]->text().trimmed();
@@ -272,13 +295,32 @@ QWidget* QuantModulePanel::build_online_learning_panel() {
ttvl->addWidget(build_input_row(tr("Target"), ol_target, train_tab));
auto* ol_train = make_run_button(tr("TRAIN ONE STEP"), train_tab);
connect(ol_train, &QPushButton::clicked, this, [this]() {
- status_label_->setText(tr("Training..."));
+ const QString mid = text_inputs_["ol_train_id"]->text().trimmed();
+ if (mid.isEmpty()) {
+ display_error(tr("Enter the ID of a model created in the Create Model tab."));
+ return;
+ }
+ QJsonParseError perr{};
+ const auto doc = QJsonDocument::fromJson(text_inputs_["ol_features"]->text().toUtf8(), &perr);
+ if (perr.error != QJsonParseError::NoError || !doc.isObject() || doc.object().isEmpty()) {
+ display_error(tr("Features must be a non-empty JSON object like "
+ "{\"close\":94.0,\"rsi\":55.0} — %1")
+ .arg(perr.errorString()));
+ return;
+ }
+ // A blank / non-numeric target silently became 0.0 and corrupted the
+ // model's running MAE with a fake observation.
+ bool ok = false;
+ const double target = text_inputs_["ol_target"]->text().trimmed().toDouble(&ok);
+ if (!ok) {
+ display_error(tr("Target must be a number (e.g. 0.02)."));
+ return;
+ }
+ show_loading(tr("Feeding one sample to %1...").arg(mid));
QJsonObject params;
- params["model_id"] = text_inputs_["ol_train_id"]->text().trimmed();
- auto doc = QJsonDocument::fromJson(text_inputs_["ol_features"]->text().toUtf8());
- if (!doc.isNull())
- params["features"] = doc.object();
- params["target"] = text_inputs_["ol_target"]->text().trimmed().toDouble();
+ params["model_id"] = mid;
+ params["features"] = doc.object();
+ params["target"] = target;
AIQuantLabService::instance().online_train(params);
});
ttvl->addWidget(ol_train);
@@ -302,20 +344,34 @@ QWidget* QuantModulePanel::build_online_learning_panel() {
predvl->addWidget(build_input_row(tr("Features (JSON)"), ol_pfeats, pred_tab));
auto* ol_pred = make_run_button(tr("PREDICT"), pred_tab);
connect(ol_pred, &QPushButton::clicked, this, [this]() {
- status_label_->setText(tr("Predicting..."));
+ const QString mid = text_inputs_["ol_pred_id"]->text().trimmed();
+ if (mid.isEmpty()) {
+ display_error(tr("Enter a model ID."));
+ return;
+ }
+ QJsonParseError perr{};
+ const auto doc = QJsonDocument::fromJson(text_inputs_["ol_pred_feats"]->text().toUtf8(), &perr);
+ if (perr.error != QJsonParseError::NoError || !doc.isObject() || doc.object().isEmpty()) {
+ display_error(tr("Features must be a non-empty JSON object — %1").arg(perr.errorString()));
+ return;
+ }
+ show_loading(tr("Predicting with %1...").arg(mid));
QJsonObject params;
- params["model_id"] = text_inputs_["ol_pred_id"]->text().trimmed();
- auto doc = QJsonDocument::fromJson(text_inputs_["ol_pred_feats"]->text().toUtf8());
- if (!doc.isNull())
- params["features"] = doc.object();
+ params["model_id"] = mid;
+ params["features"] = doc.object();
AIQuantLabService::instance().online_predict(params);
});
predvl->addWidget(ol_pred);
auto* ol_perf = make_run_button(tr("GET PERFORMANCE"), pred_tab);
connect(ol_perf, &QPushButton::clicked, this, [this]() {
- status_label_->setText(tr("Loading..."));
+ const QString mid = text_inputs_["ol_pred_id"]->text().trimmed();
+ if (mid.isEmpty()) {
+ display_error(tr("Enter a model ID."));
+ return;
+ }
+ show_loading(tr("Loading performance for %1...").arg(mid));
QJsonObject params;
- params["model_id"] = text_inputs_["ol_pred_id"]->text().trimmed();
+ params["model_id"] = mid;
AIQuantLabService::instance().online_performance(params);
});
predvl->addWidget(ol_perf);
@@ -355,7 +411,7 @@ QWidget* QuantModulePanel::build_meta_learning_panel() {
selvl->addWidget(sel_info);
auto* sel_list_btn = make_run_button(tr("LIST AVAILABLE MODELS"), sel_tab);
connect(sel_list_btn, &QPushButton::clicked, this, [this]() {
- status_label_->setText(tr("Loading..."));
+ show_loading(tr("Loading candidate model catalog..."));
AIQuantLabService::instance().meta_list_models();
});
selvl->addWidget(sel_list_btn);
@@ -371,12 +427,13 @@ QWidget* QuantModulePanel::build_meta_learning_panel() {
selvl->addWidget(build_input_row(tr("Task Type"), sel_task, sel_tab));
auto* sel_run = make_run_button(tr("RUN MODEL SELECTION"), sel_tab);
connect(sel_run, &QPushButton::clicked, this, [this]() {
- status_label_->setText(tr("Selecting..."));
+ const QJsonArray model_ids = parse_csv_strings(text_inputs_["ml_sel_models"]->text());
+ if (model_ids.size() < 2) {
+ display_error(tr("Model selection needs at least two candidates, e.g. lightgbm,xgboost."));
+ return;
+ }
+ show_loading(tr("Training and ranking %1 candidate model(s)...").arg(model_ids.size()));
QJsonObject params;
- QJsonArray model_ids;
- for (auto& s : text_inputs_["ml_sel_models"]->text().split(','))
- if (!s.trimmed().isEmpty())
- model_ids.append(s.trimmed());
params["model_ids"] = model_ids;
params["task_type"] = combo_inputs_["ml_sel_task"]->currentText();
AIQuantLabService::instance().meta_run_selection(params);
@@ -402,12 +459,15 @@ QWidget* QuantModulePanel::build_meta_learning_panel() {
ensvl->addWidget(build_input_row(tr("Ensemble Method"), ens_method, ens_tab));
auto* ens_run = make_run_button(tr("CREATE ENSEMBLE"), ens_tab);
connect(ens_run, &QPushButton::clicked, this, [this]() {
- status_label_->setText(tr("Creating ensemble..."));
+ const QJsonArray keys = parse_csv_strings(text_inputs_["ml_ens_keys"]->text());
+ if (keys.size() < 2) {
+ display_error(tr("An ensemble needs at least two model keys from the Model Selection output."));
+ return;
+ }
+ show_loading(tr("Building a %1 ensemble from %2 model(s)...")
+ .arg(combo_inputs_["ml_ens_method"]->currentText())
+ .arg(keys.size()));
QJsonObject params;
- QJsonArray keys;
- for (auto& s : text_inputs_["ml_ens_keys"]->text().split(','))
- if (!s.trimmed().isEmpty())
- keys.append(s.trimmed());
params["model_keys"] = keys;
params["method"] = combo_inputs_["ml_ens_method"]->currentText();
AIQuantLabService::instance().meta_create_ensemble(params);
@@ -438,19 +498,27 @@ QWidget* QuantModulePanel::build_meta_learning_panel() {
tunevl->addWidget(build_input_row(tr("Search Method"), tune_method, tune_tab));
auto* tune_run = make_run_button(tr("TUNE HYPERPARAMETERS"), tune_tab);
connect(tune_run, &QPushButton::clicked, this, [this]() {
- status_label_->setText(tr("Tuning..."));
+ QJsonParseError perr{};
+ const auto doc = QJsonDocument::fromJson(text_inputs_["ml_tune_grid"]->text().toUtf8(), &perr);
+ if (perr.error != QJsonParseError::NoError || !doc.isObject() || doc.object().isEmpty()) {
+ display_error(tr("Param Grid must be a non-empty JSON object like "
+ "{\"n_estimators\":[50,100],\"max_depth\":[3,5]} — %1")
+ .arg(perr.errorString()));
+ return;
+ }
+ show_loading(tr("%1 search over %2 hyperparameter(s) — this can take a while...")
+ .arg(combo_inputs_["ml_tune_method"]->currentText())
+ .arg(doc.object().size()));
QJsonObject params;
params["model_id"] = combo_inputs_["ml_tune_model"]->currentText();
- auto doc = QJsonDocument::fromJson(text_inputs_["ml_tune_grid"]->text().toUtf8());
- if (!doc.isNull())
- params["param_grid"] = doc.object();
+ params["param_grid"] = doc.object();
params["search_method"] = combo_inputs_["ml_tune_method"]->currentText();
AIQuantLabService::instance().meta_tune_hyperparameters(params);
});
tunevl->addWidget(tune_run);
auto* results_btn = make_run_button(tr("GET ALL RESULTS"), tune_tab);
connect(results_btn, &QPushButton::clicked, this, [this]() {
- status_label_->setText(tr("Loading..."));
+ show_loading(tr("Loading meta-learning results..."));
AIQuantLabService::instance().meta_get_results();
});
tunevl->addWidget(results_btn);
@@ -512,7 +580,7 @@ QWidget* QuantModulePanel::build_rolling_retraining_panel() {
auto* lt_run = make_run_button(tr("REFRESH SCHEDULES"), list_tab);
connect(lt_run, &QPushButton::clicked, this, [this]() {
- status_label_->setText(tr("Loading schedules..."));
+ show_loading(tr("Loading schedules..."));
AIQuantLabService::instance().rolling_list_schedules();
});
ltvl->addWidget(lt_run);
@@ -576,18 +644,29 @@ QWidget* QuantModulePanel::build_rolling_retraining_panel() {
const QString mid = text_inputs_["rr_model_id"]->text().trimmed();
const QString cp = text_inputs_["rr_conf_path"]->text().trimmed();
if (mid.isEmpty() && cp.isEmpty()) {
- status_label_->setText(tr("Enter a Model ID or Config Path to preview."));
+ display_error(tr("Enter a Model ID or Config Path to preview."));
return;
}
- status_label_->setText(tr("Generating preview..."));
+ // A non-numeric step used to silently become 0, which makes the window
+ // generator produce zero (or infinitely many) windows.
+ const QString step = text_inputs_["rr_step"]->text().trimmed();
+ int step_days = 0;
+ if (!step.isEmpty()) {
+ bool ok = false;
+ step_days = step.toInt(&ok);
+ if (!ok || step_days <= 0) {
+ display_error(tr("Step must be a positive whole number of trading days (got '%1').").arg(step));
+ return;
+ }
+ }
+ show_loading(tr("Generating rolling-window preview..."));
QJsonObject params;
if (!mid.isEmpty())
params["model_id"] = mid;
if (!cp.isEmpty())
params["conf_path"] = cp;
- const QString step = text_inputs_["rr_step"]->text().trimmed();
- if (!step.isEmpty())
- params["step"] = step.toInt();
+ if (step_days > 0)
+ params["step"] = step_days;
AIQuantLabService::instance().rolling_preview_tasks(params);
});
btn_hl->addWidget(rr_preview, 1);
@@ -596,10 +675,33 @@ QWidget* QuantModulePanel::build_rolling_retraining_panel() {
connect(rr_create, &QPushButton::clicked, this, [this]() {
const QString mid = text_inputs_["rr_model_id"]->text().trimmed();
if (mid.isEmpty()) {
- status_label_->setText(tr("Model ID is required."));
+ display_error(tr("Model ID is required."));
return;
}
- status_label_->setText(tr("Creating schedule..."));
+ // Window / step used to fall through as 0 on any non-numeric input.
+ const QString win = text_inputs_["rr_window"]->text().trimmed();
+ const QString step = text_inputs_["rr_step"]->text().trimmed();
+ int win_days = 0, step_days = 0;
+ if (!win.isEmpty()) {
+ bool ok = false;
+ win_days = win.toInt(&ok);
+ if (!ok || win_days <= 0) {
+ display_error(tr("Window must be a positive whole number of trading days (got '%1').").arg(win));
+ return;
+ }
+ }
+ if (!step.isEmpty()) {
+ bool ok = false;
+ step_days = step.toInt(&ok);
+ if (!ok || step_days <= 0) {
+ display_error(tr("Step must be a positive whole number of trading days (got '%1').").arg(step));
+ return;
+ }
+ }
+ // NOTE: step > window silently skips training data between windows.
+ // Not blocked — gapped windows are a valid (if unusual) design — but it
+ // is almost always a typo and deserves a UI warning eventually.
+ show_loading(tr("Creating schedule for %1...").arg(mid));
QJsonObject params;
params["model_id"] = mid;
params["frequency"] = combo_inputs_["rr_frequency"]->currentText();
@@ -607,12 +709,10 @@ QWidget* QuantModulePanel::build_rolling_retraining_panel() {
const QString cp = text_inputs_["rr_conf_path"]->text().trimmed();
if (!cp.isEmpty())
params["conf_path"] = cp;
- const QString win = text_inputs_["rr_window"]->text().trimmed();
- if (!win.isEmpty())
- params["window"] = win.toInt();
- const QString step = text_inputs_["rr_step"]->text().trimmed();
- if (!step.isEmpty())
- params["step"] = step.toInt();
+ if (win_days > 0)
+ params["window"] = win_days;
+ if (step_days > 0)
+ params["step"] = step_days;
AIQuantLabService::instance().rolling_create_schedule(params);
});
btn_hl->addWidget(rr_create, 1);
@@ -626,8 +726,12 @@ QWidget* QuantModulePanel::build_rolling_retraining_panel() {
retrainvl->setContentsMargins(12, 12, 12, 12);
retrainvl->setSpacing(10);
+ // NOTE: AIQuantLabService::rolling_execute_retrain() parses the script's
+ // JSON event lines only after the process exits, so the per-window log is
+ // replayed on completion rather than streamed. Don't promise "live".
auto* rt_info = new QLabel(tr("Executes a full rolling retrain for a scheduled model. Each window trains "
- "independently and progress is streamed live below."),
+ "independently; the per-window log below is filled in when the run finishes. "
+ "Long runs can take many minutes with no intermediate output."),
retrain_tab);
rt_info->setWordWrap(true);
rt_info->setStyleSheet(QString("color:%1; font-size:11px;").arg(ui::colors::TEXT_SECONDARY()));
@@ -657,7 +761,7 @@ QWidget* QuantModulePanel::build_rolling_retraining_panel() {
auto* rr_log = new QTextEdit(retrain_tab);
rr_log->setObjectName("rr_log");
rr_log->setReadOnly(true);
- rr_log->setPlaceholderText(tr("Training progress will stream here..."));
+ rr_log->setPlaceholderText(tr("Per-window training log appears here when the run completes..."));
rr_log->setStyleSheet(output_ss());
rr_log->setMinimumHeight(140);
retrainvl->addWidget(rr_log, 1);
@@ -666,7 +770,7 @@ QWidget* QuantModulePanel::build_rolling_retraining_panel() {
connect(rr_exec, &QPushButton::clicked, this, [this]() {
const QString mid = text_inputs_["rr_exec_id"]->text().trimmed();
if (mid.isEmpty()) {
- status_label_->setText(tr("Model ID is required."));
+ display_error(tr("Model ID is required."));
return;
}
// Reset progress UI
diff --git a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_Misc.cpp b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_Misc.cpp
index e9c599b33..b6320bf1d 100644
--- a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_Misc.cpp
+++ b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_Misc.cpp
@@ -2,9 +2,12 @@
//
// Miscellaneous panel builders — Advanced Models, Feature Engineering,
// Portfolio Opt, Factor Evaluation, Strategy Builder, Data Processors, Factor
-// Discovery, Model Library, Live Signals, Online Learning, Meta Learning, HFT,
-// Rolling Retraining. Extracted from QuantModulePanel.cpp to keep that file
-// maintainable.
+// Discovery, Model Library. Extracted from QuantModulePanel.cpp to keep that
+// file maintainable.
+//
+// Live Signals / Online Learning / Meta Learning / Rolling Retraining live in
+// QuantModulePanel_LiveLearning.cpp; HFT in QuantModulePanel_HFT.cpp;
+// RL Trading in QuantModulePanel_RL.cpp.
#include "core/logging/Logger.h"
#include "screens/ai_quant_lab/QuantModulePanel.h"
#include "screens/ai_quant_lab/QuantModulePanel_Common.h"
@@ -30,6 +33,7 @@
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
+#include <QJsonParseError>
#include <QJsonValue>
#include <QLabel>
#include <QLineEdit>
@@ -106,7 +110,9 @@ QWidget* QuantModulePanel::build_advanced_models_panel() {
auto* run = make_run_button(tr("CREATE & TRAIN MODEL"), w);
connect(run, &QPushButton::clicked, this, [this]() {
- status_label_->setText(tr("Training..."));
+ show_loading(tr("Creating and training %1 (%2 epochs) — this can take several minutes...")
+ .arg(combo_inputs_["adv_model"]->currentText())
+ .arg(int_inputs_["adv_epochs"]->value()));
QJsonObject params;
params["model_type"] = combo_inputs_["adv_model"]->currentText();
QJsonObject config;
@@ -169,11 +175,24 @@ QWidget* QuantModulePanel::build_feature_engineering_panel() {
auto* ind_run = make_run_button(tr("COMPUTE INDICATOR"), ind);
connect(ind_run, &QPushButton::clicked, this, [this]() {
- status_label_->setText(tr("Computing..."));
+ QJsonArray series;
+ QString bad;
+ if (!parse_doubles(text_inputs_["fe_data"]->text(), series, &bad)) {
+ display_error(tr("Price Data: '%1' is not numeric.").arg(bad));
+ return;
+ }
+ const int window = int_inputs_["fe_window"]->value();
+ if (series.size() < window) {
+ display_error(
+ tr("A %1-period window needs at least %1 prices; you provided %2.").arg(window).arg(series.size()));
+ return;
+ }
+ show_loading(
+ tr("Computing %1 over %2 prices...").arg(combo_inputs_["fe_indicator"]->currentText()).arg(series.size()));
QJsonObject params;
params["data"] = text_inputs_["fe_data"]->text();
params["indicator"] = combo_inputs_["fe_indicator"]->currentText();
- params["window"] = int_inputs_["fe_window"]->value();
+ params["window"] = window;
AIQuantLabService::instance().feature_compute(params);
});
ivl->addWidget(ind_run);
@@ -207,12 +226,28 @@ QWidget* QuantModulePanel::build_feature_engineering_panel() {
auto* sel_run = make_run_button(tr("SELECT FEATURES BY IC"), sel);
connect(sel_run, &QPushButton::clicked, this, [this]() {
- status_label_->setText(tr("Selecting..."));
+ // JSON parse failures used to be swallowed: params["features"] was simply
+ // omitted and the run failed server-side with an unrelated message.
+ QJsonParseError perr{};
+ const auto doc = QJsonDocument::fromJson(text_inputs_["fe_sel_features"]->text().toUtf8(), &perr);
+ if (perr.error != QJsonParseError::NoError || !doc.isObject()) {
+ display_error(
+ tr("Features must be a JSON object like {\"rsi\":[…],\"macd\":[…]} — %1").arg(perr.errorString()));
+ return;
+ }
+ QJsonArray rets;
+ QString bad;
+ if (!parse_doubles(text_inputs_["fe_sel_returns"]->text(), rets, &bad)) {
+ display_error(tr("Returns: '%1' is not numeric.").arg(bad));
+ return;
+ }
+ if (rets.isEmpty()) {
+ display_error(tr("Enter the target return series."));
+ return;
+ }
+ show_loading(tr("Ranking %1 feature(s) by IC...").arg(doc.object().size()));
QJsonObject params;
- auto feat_text = text_inputs_["fe_sel_features"]->text();
- auto doc = QJsonDocument::fromJson(feat_text.toUtf8());
- if (!doc.isNull())
- params["features"] = doc.object();
+ params["features"] = doc.object();
params["returns"] = text_inputs_["fe_sel_returns"]->text();
params["top_k"] = int_inputs_["fe_topk"]->value();
AIQuantLabService::instance().feature_select_by_ic(params);
@@ -241,13 +276,22 @@ QWidget* QuantModulePanel::build_feature_engineering_panel() {
auto* expr_run = make_run_button(tr("EVALUATE EXPRESSION"), expr);
connect(expr_run, &QPushButton::clicked, this, [this]() {
- status_label_->setText(tr("Evaluating..."));
+ QJsonParseError perr{};
+ const auto doc = QJsonDocument::fromJson(text_inputs_["fe_expr_data"]->text().toUtf8(), &perr);
+ if (perr.error != QJsonParseError::NoError || !doc.isObject()) {
+ display_error(tr("OHLCV Data must be a JSON object like {\"close\":[…],\"volume\":[…]} — %1")
+ .arg(perr.errorString()));
+ return;
+ }
+ const QString expression = text_inputs_["fe_expression"]->text().trimmed();
+ if (expression.isEmpty()) {
+ display_error(tr("Enter an expression, e.g. Mean(close, 5) / Std(close, 20)."));
+ return;
+ }
+ show_loading(tr("Evaluating %1...").arg(expression));
QJsonObject params;
- auto data_text = text_inputs_["fe_expr_data"]->text();
- auto doc = QJsonDocument::fromJson(data_text.toUtf8());
- if (!doc.isNull())
- params["data"] = doc.object();
- params["expression"] = text_inputs_["fe_expression"]->text();
+ params["data"] = doc.object();
+ params["expression"] = expression;
AIQuantLabService::instance().feature_evaluate_expression(params);
});
evl->addWidget(expr_run);
@@ -306,23 +350,48 @@ QWidget* QuantModulePanel::build_portfolio_opt_panel() {
auto* run = make_run_button(btn_label, t);
connect(run, &QPushButton::clicked, this, [this, method_id, needs_returns]() {
- status_label_->setText(tr("Optimizing..."));
+ // Previously: a blank Assets field produced [""] and a malformed
+ // covariance matrix was silently dropped, so the optimiser ran on
+ // nonsense and returned an unrelated Python error.
+ const QJsonArray assets_arr = parse_csv_strings(text_inputs_[method_id + "_assets"]->text());
+ if (assets_arr.isEmpty()) {
+ display_error(tr("Enter at least two asset names, e.g. AAPL,GOOG,MSFT."));
+ return;
+ }
+ QJsonParseError perr{};
+ const auto cov_doc = QJsonDocument::fromJson(text_inputs_[method_id + "_cov"]->text().toUtf8(), &perr);
+ if (perr.error != QJsonParseError::NoError || !cov_doc.isArray()) {
+ display_error(tr("Covariance Matrix must be a JSON 2-D array like [[0.04,0.01],[0.01,0.09]] — %1")
+ .arg(perr.errorString()));
+ return;
+ }
+ const QJsonArray cov = cov_doc.array();
+ if (cov.size() != assets_arr.size()) {
+ display_error(tr("Covariance matrix has %1 row(s) but you listed %2 assets - they must match.")
+ .arg(cov.size())
+ .arg(assets_arr.size()));
+ return;
+ }
QJsonObject params;
- auto assets_str = text_inputs_[method_id + "_assets"]->text().split(',');
- QJsonArray assets_arr;
- for (auto& a : assets_str)
- assets_arr.append(a.trimmed());
params["assets"] = assets_arr;
- auto cov_doc = QJsonDocument::fromJson(text_inputs_[method_id + "_cov"]->text().toUtf8());
- if (!cov_doc.isNull())
- params["cov_matrix"] = cov_doc.array();
+ params["cov_matrix"] = cov;
if (needs_returns) {
QJsonArray ret_arr;
- for (auto& r : text_inputs_[method_id + "_returns"]->text().split(','))
- ret_arr.append(r.trimmed().toDouble());
+ QString bad;
+ if (!parse_doubles(text_inputs_[method_id + "_returns"]->text(), ret_arr, &bad)) {
+ display_error(tr("Expected Returns: '%1' is not numeric.").arg(bad));
+ return;
+ }
+ if (ret_arr.size() != assets_arr.size()) {
+ display_error(tr("Expected Returns has %1 entries but you listed %2 assets.")
+ .arg(ret_arr.size())
+ .arg(assets_arr.size()));
+ return;
+ }
params["expected_returns"] = ret_arr;
}
params["risk_free_rate"] = double_inputs_[method_id + "_rf"]->value() / 100.0;
+ show_loading(tr("Optimising %1 assets...").arg(assets_arr.size()));
AIQuantLabService::instance().portopt_run(method_id, params);
});
tvl->addWidget(run);
@@ -367,24 +436,49 @@ QWidget* QuantModulePanel::build_portfolio_opt_panel() {
blvl->addWidget(build_input_row(tr("View Confidences"), bl_conf, bl));
auto* bl_run = make_run_button(tr("RUN BLACK-LITTERMAN"), bl);
connect(bl_run, &QPushButton::clicked, this, [this]() {
- status_label_->setText(tr("Running BL..."));
+ const QJsonArray assets = parse_csv_strings(text_inputs_["bl_assets"]->text());
+ if (assets.isEmpty()) {
+ display_error(tr("Enter at least two asset names."));
+ return;
+ }
+ QJsonArray caps, views, confs;
+ QString bad;
+ if (!parse_doubles(text_inputs_["bl_caps"]->text(), caps, &bad)) {
+ display_error(tr("Market Caps: '%1' is not numeric.").arg(bad));
+ return;
+ }
+ if (caps.size() != assets.size()) {
+ display_error(
+ tr("Market Caps has %1 entries but you listed %2 assets.").arg(caps.size()).arg(assets.size()));
+ return;
+ }
+ if (!parse_doubles(text_inputs_["bl_views"]->text(), views, &bad)) {
+ display_error(tr("Views: '%1' is not numeric.").arg(bad));
+ return;
+ }
+ if (!parse_doubles(text_inputs_["bl_conf"]->text(), confs, &bad)) {
+ display_error(tr("View Confidences: '%1' is not numeric.").arg(bad));
+ return;
+ }
+ if (views.size() != confs.size()) {
+ display_error(tr("Each view needs exactly one confidence — got %1 view(s) and %2 confidence(s).")
+ .arg(views.size())
+ .arg(confs.size()));
+ return;
+ }
+ QJsonParseError perr{};
+ const auto cov_doc = QJsonDocument::fromJson(text_inputs_["bl_cov"]->text().toUtf8(), &perr);
+ if (perr.error != QJsonParseError::NoError || !cov_doc.isArray()) {
+ display_error(tr("Covariance Matrix must be a JSON 2-D array — %1").arg(perr.errorString()));
+ return;
+ }
QJsonObject params;
- QJsonArray caps, views, confs, assets;
- for (auto& v : text_inputs_["bl_caps"]->text().split(','))
- caps.append(v.trimmed().toDouble());
- for (auto& v : text_inputs_["bl_views"]->text().split(','))
- views.append(v.trimmed().toDouble());
- for (auto& v : text_inputs_["bl_conf"]->text().split(','))
- confs.append(v.trimmed().toDouble());
- for (auto& v : text_inputs_["bl_assets"]->text().split(','))
- assets.append(v.trimmed());
params["market_caps"] = caps;
params["views"] = views;
params["view_confidences"] = confs;
params["assets"] = assets;
- auto cov_doc = QJsonDocument::fromJson(text_inputs_["bl_cov"]->text().toUtf8());
- if (!cov_doc.isNull())
- params["cov_matrix"] = cov_doc.array();
+ params["cov_matrix"] = cov_doc.array();
+ show_loading(tr("Blending %1 view(s) into the equilibrium prior...").arg(views.size()));
AIQuantLabService::instance().portopt_run("black_litterman", params);
});
blvl->addWidget(bl_run);
@@ -432,13 +526,31 @@ QWidget* QuantModulePanel::build_factor_evaluation_panel() {
icvl->addWidget(build_input_row(tr("Method"), ic_method, ic));
auto* ic_run = make_run_button(tr("CALCULATE IC METRICS"), ic);
connect(ic_run, &QPushButton::clicked, this, [this]() {
- status_label_->setText(tr("Calculating..."));
- QJsonObject params;
QJsonArray preds, rets;
- for (auto& v : text_inputs_["ev_predictions"]->text().split(','))
- preds.append(v.trimmed().toDouble());
- for (auto& v : text_inputs_["ev_returns"]->text().split(','))
- rets.append(v.trimmed().toDouble());
+ QString bad;
+ if (!parse_doubles(text_inputs_["ev_predictions"]->text(), preds, &bad)) {
+ display_error(tr("Predictions: '%1' is not numeric.").arg(bad));
+ return;
+ }
+ if (!parse_doubles(text_inputs_["ev_returns"]->text(), rets, &bad)) {
+ display_error(tr("Returns: '%1' is not numeric.").arg(bad));
+ return;
+ }
+ // A correlation over fewer than 3 pairs is degenerate (|IC| == 1 by
+ // construction at n == 2), so refuse rather than report a fake 1.0.
+ if (preds.size() < 3) {
+ display_error(tr("IC needs at least 3 paired observations; you provided %1.").arg(preds.size()));
+ return;
+ }
+ if (preds.size() != rets.size()) {
+ display_error(
+ tr("Predictions (%1) and returns (%2) must have the same length.").arg(preds.size()).arg(rets.size()));
+ return;
+ }
+ show_loading(tr("Computing %1 IC over %2 observations...")
+ .arg(combo_inputs_["ev_ic_method"]->currentText())
+ .arg(preds.size()));
+ QJsonObject params;
params["predictions"] = preds;
params["returns"] = rets;
params["method"] = combo_inputs_["ev_ic_method"]->currentText();
@@ -470,14 +582,31 @@ QWidget* QuantModulePanel::build_factor_evaluation_panel() {
repvl->addWidget(build_input_row(tr("Returns"), rep_rets, rep));
auto* rep_run = make_run_button(tr("GENERATE EVALUATION REPORT"), rep);
connect(rep_run, &QPushButton::clicked, this, [this]() {
- status_label_->setText(tr("Generating..."));
- QJsonObject params;
QJsonArray preds, rets;
- for (auto& v : text_inputs_["ev_rep_preds"]->text().split(','))
- preds.append(v.trimmed().toDouble());
- for (auto& v : text_inputs_["ev_rep_returns"]->text().split(','))
- rets.append(v.trimmed().toDouble());
- params["factor_name"] = text_inputs_["ev_factor_name"]->text();
+ QString bad;
+ if (!parse_doubles(text_inputs_["ev_rep_preds"]->text(), preds, &bad)) {
+ display_error(tr("Predictions: '%1' is not numeric.").arg(bad));
+ return;
+ }
+ if (!parse_doubles(text_inputs_["ev_rep_returns"]->text(), rets, &bad)) {
+ display_error(tr("Returns: '%1' is not numeric.").arg(bad));
+ return;
+ }
+ if (preds.size() < 3) {
+ display_error(tr("Need at least 3 paired observations; you provided %1.").arg(preds.size()));
+ return;
+ }
+ if (preds.size() != rets.size()) {
+ display_error(
+ tr("Predictions (%1) and returns (%2) must have the same length.").arg(preds.size()).arg(rets.size()));
+ return;
+ }
+ const QString fname = text_inputs_["ev_factor_name"]->text().trimmed();
+ show_loading(tr("Scoring factor '%1' over %2 observations...")
+ .arg(fname.isEmpty() ? tr("unnamed") : fname)
+ .arg(preds.size()));
+ QJsonObject params;
+ params["factor_name"] = fname.isEmpty() ? QStringLiteral("factor") : fname;
params["predictions"] = preds;
params["returns"] = rets;
AIQuantLabService::instance().evaluation_report(params);
@@ -506,20 +635,40 @@ QWidget* QuantModulePanel::build_factor_evaluation_panel() {
riskvl->addWidget(build_input_row(tr("Confidence Level"), risk_conf, risk));
auto* risk_run = make_run_button(tr("CALCULATE RISK METRICS"), risk);
connect(risk_run, &QPushButton::clicked, this, [this]() {
- status_label_->setText(tr("Calculating..."));
- QJsonObject params;
QJsonArray rets;
- for (auto& v : text_inputs_["ev_risk_returns"]->text().split(','))
- rets.append(v.trimmed().toDouble());
+ QString bad;
+ if (!parse_doubles(text_inputs_["ev_risk_returns"]->text(), rets, &bad)) {
+ display_error(tr("Returns: '%1' is not numeric.").arg(bad));
+ return;
+ }
+ // Below 5 points volatility / VaR / drawdown are degenerate. (30+ is the
+ // practical floor for the ANNUALISED figures, but blocking there would
+ // reject legitimate exploratory runs.)
+ if (rets.size() < 5) {
+ display_error(tr("Risk metrics need at least 5 daily returns; you provided %1. "
+ "Annualised figures only become meaningful past ~30 observations.")
+ .arg(rets.size()));
+ return;
+ }
+ QJsonObject params;
params["returns"] = rets;
params["confidence_level"] = double_inputs_["ev_risk_conf"]->value();
- auto bench_text = text_inputs_["ev_risk_bench"]->text().trimmed();
+ const auto bench_text = text_inputs_["ev_risk_bench"]->text().trimmed();
if (!bench_text.isEmpty()) {
QJsonArray bench;
- for (auto& v : bench_text.split(','))
- bench.append(v.trimmed().toDouble());
+ if (!parse_doubles(bench_text, bench, &bad)) {
+ display_error(tr("Benchmark returns: '%1' is not numeric.").arg(bad));
+ return;
+ }
+ // Beta / tracking error / capture ratios are only defined pairwise.
+ if (bench.size() != rets.size()) {
+ display_error(
+ tr("Benchmark (%1) must have the same length as returns (%2).").arg(bench.size()).arg(rets.size()));
+ return;
+ }
params["benchmark_returns"] = bench;
}
+ show_loading(tr("Computing risk metrics over %1 observations...").arg(rets.size()));
AIQuantLabService::instance().evaluation_risk_metrics(params);
});
riskvl->addWidget(risk_run);
@@ -569,14 +718,31 @@ QWidget* QuantModulePanel::build_strategy_builder_panel() {
tkvl->addWidget(build_input_row(tr("N-Drop"), tk_drop, topk));
auto* tk_run = make_run_button(tr("CREATE TOPK-DROPOUT STRATEGY"), topk);
connect(tk_run, &QPushButton::clicked, this, [this]() {
- status_label_->setText(tr("Creating..."));
- QJsonObject params;
QJsonArray signal;
- for (auto& v : text_inputs_["st_tk_signal"]->text().split(','))
- signal.append(v.trimmed().toDouble());
+ QString bad;
+ if (!parse_doubles(text_inputs_["st_tk_signal"]->text(), signal, &bad)) {
+ display_error(tr("Signal: '%1' is not numeric.").arg(bad));
+ return;
+ }
+ const int topk = int_inputs_["st_topk"]->value();
+ const int ndrop = int_inputs_["st_ndrop"]->value();
+ if (signal.isEmpty()) {
+ display_error(tr("Enter the cross-sectional signal values."));
+ return;
+ }
+ // NOTE: topk > signal.size() is deliberately NOT blocked — a small test
+ // universe is a legitimate way to try the panel and the shipped default
+ // topk is 50. n_drop >= topk, however, replaces the whole book every
+ // rebalance: that is not TopK-Dropout, it is 100% turnover.
+ if (ndrop >= topk) {
+ display_error(tr("N-Drop (%1) must be smaller than Top-K (%2).").arg(ndrop).arg(topk));
+ return;
+ }
+ show_loading(tr("Building TopK-Dropout over %1 names...").arg(signal.size()));
+ QJsonObject params;
params["signal"] = signal;
- params["topk"] = int_inputs_["st_topk"]->value();
- params["n_drop"] = int_inputs_["st_ndrop"]->value();
+ params["topk"] = topk;
+ params["n_drop"] = ndrop;
AIQuantLabService::instance().strategy_create("create_topk_dropout", params);
});
tkvl->addWidget(tk_run);
@@ -603,11 +769,21 @@ QWidget* QuantModulePanel::build_strategy_builder_panel() {
rpvl->addWidget(build_input_row(tr("Rebalance"), rp_freq, rp));
auto* rp_run = make_run_button(tr("CREATE RISK PARITY STRATEGY"), rp);
connect(rp_run, &QPushButton::clicked, this, [this]() {
- status_label_->setText(tr("Creating..."));
+ QJsonParseError perr{};
+ const auto ret_doc = QJsonDocument::fromJson(text_inputs_["st_rp_returns"]->text().toUtf8(), &perr);
+ if (perr.error != QJsonParseError::NoError || !ret_doc.isArray()) {
+ display_error(tr("Returns Matrix must be a JSON 2-D array like [[0.01,-0.02],[0.00,0.01]] — %1")
+ .arg(perr.errorString()));
+ return;
+ }
+ const QJsonArray rows = ret_doc.array();
+ if (rows.isEmpty() || !rows.first().isArray()) {
+ display_error(tr("Returns Matrix must contain at least one row of per-asset returns."));
+ return;
+ }
+ show_loading(tr("Solving risk parity over %1 period(s)...").arg(rows.size()));
QJsonObject params;
- auto ret_doc = QJsonDocument::fromJson(text_inputs_["st_rp_returns"]->text().toUtf8());
- if (!ret_doc.isNull())
- params["returns"] = ret_doc.array();
+ params["returns"] = rows;
params["target_risk"] = double_inputs_["st_rp_target"]->value();
params["rebalance_frequency"] = combo_inputs_["st_rp_freq"]->currentText();
AIQuantLabService::instance().strategy_create("create_risk_parity", params);
@@ -636,20 +812,36 @@ QWidget* QuantModulePanel::build_strategy_builder_panel() {
pmvl->addWidget(build_input_row(tr("Risk-Free Rate"), pm_rf, pm));
auto* pm_run = make_run_button(tr("CALCULATE PORTFOLIO METRICS"), pm);
connect(pm_run, &QPushButton::clicked, this, [this]() {
- status_label_->setText(tr("Calculating..."));
- QJsonObject params;
QJsonArray rets;
- for (auto& v : text_inputs_["st_pm_returns"]->text().split(','))
- rets.append(v.trimmed().toDouble());
+ QString bad;
+ if (!parse_doubles(text_inputs_["st_pm_returns"]->text(), rets, &bad)) {
+ display_error(tr("Returns: '%1' is not numeric.").arg(bad));
+ return;
+ }
+ if (rets.size() < 5) {
+ display_error(tr("Portfolio metrics need at least 5 daily returns; you provided %1. "
+ "Annualised Sharpe/Sortino/Calmar only become meaningful past ~30 observations.")
+ .arg(rets.size()));
+ return;
+ }
+ QJsonObject params;
params["returns"] = rets;
params["risk_free_rate"] = double_inputs_["st_pm_rf"]->value() / 100.0;
- auto bench_text = text_inputs_["st_pm_bench"]->text().trimmed();
+ const auto bench_text = text_inputs_["st_pm_bench"]->text().trimmed();
if (!bench_text.isEmpty()) {
QJsonArray bench;
- for (auto& v : bench_text.split(','))
- bench.append(v.trimmed().toDouble());
+ if (!parse_doubles(bench_text, bench, &bad)) {
+ display_error(tr("Benchmark returns: '%1' is not numeric.").arg(bad));
+ return;
+ }
+ if (bench.size() != rets.size()) {
+ display_error(
+ tr("Benchmark (%1) must have the same length as returns (%2).").arg(bench.size()).arg(rets.size()));
+ return;
+ }
params["benchmark_returns"] = bench;
}
+ show_loading(tr("Computing portfolio metrics over %1 observations...").arg(rets.size()));
AIQuantLabService::instance().strategy_portfolio_metrics(params);
});
pmvl->addWidget(pm_run);
@@ -689,7 +881,7 @@ QWidget* QuantModulePanel::build_data_processors_panel() {
ltvl->addWidget(lt_info);
auto* lt_run = make_run_button(tr("LIST ALL PROCESSORS"), list_tab);
connect(lt_run, &QPushButton::clicked, this, [this]() {
- status_label_->setText(tr("Loading..."));
+ show_loading(tr("Loading processor catalog..."));
AIQuantLabService::instance().dataproc_list_processors();
});
ltvl->addWidget(lt_run);
@@ -713,12 +905,23 @@ QWidget* QuantModulePanel::build_data_processors_panel() {
ptvl->addWidget(build_input_row(tr("Processors (JSON)"), pipe_procs, pipe_tab));
auto* pipe_run = make_run_button(tr("CREATE PIPELINE"), pipe_tab);
connect(pipe_run, &QPushButton::clicked, this, [this]() {
- status_label_->setText(tr("Creating..."));
+ const QString pid = text_inputs_["dp_pipeline_id"]->text().trimmed();
+ if (pid.isEmpty()) {
+ display_error(tr("Enter a pipeline ID — you need it to run PROCESS DATA later."));
+ return;
+ }
+ QJsonParseError perr{};
+ const auto doc = QJsonDocument::fromJson(text_inputs_["dp_processors"]->text().toUtf8(), &perr);
+ if (perr.error != QJsonParseError::NoError || !doc.isArray() || doc.array().isEmpty()) {
+ display_error(tr("Processors must be a non-empty JSON array like "
+ "[{\"type\":\"zscore\"}] — %1")
+ .arg(perr.errorString()));
+ return;
+ }
+ show_loading(tr("Creating pipeline '%1' with %2 stage(s)...").arg(pid).arg(doc.array().size()));
QJsonObject params;
- params["pipeline_id"] = text_inputs_["dp_pipeline_id"]->text();
- auto doc = QJsonDocument::fromJson(text_inputs_["dp_processors"]->text().toUtf8());
- if (!doc.isNull())
- params["processors"] = doc.array();
+ params["pipeline_id"] = pid;
+ params["processors"] = doc.array();
AIQuantLabService::instance().dataproc_create_pipeline(params);
});
ptvl->addWidget(pipe_run);
@@ -742,12 +945,21 @@ QWidget* QuantModulePanel::build_data_processors_panel() {
procvl->addWidget(build_input_row(tr("Data (JSON)"), proc_data, proc_tab));
auto* proc_run = make_run_button(tr("PROCESS DATA"), proc_tab);
connect(proc_run, &QPushButton::clicked, this, [this]() {
- status_label_->setText(tr("Processing..."));
+ const QString pid = text_inputs_["dp_proc_pid"]->text().trimmed();
+ if (pid.isEmpty()) {
+ display_error(tr("Enter the ID of a pipeline you created in the Create Pipeline tab."));
+ return;
+ }
+ QJsonParseError perr{};
+ const auto doc = QJsonDocument::fromJson(text_inputs_["dp_proc_data"]->text().toUtf8(), &perr);
+ if (perr.error != QJsonParseError::NoError || !doc.isObject() || doc.object().isEmpty()) {
+ display_error(tr("Data must be a non-empty JSON object of column → values — %1").arg(perr.errorString()));
+ return;
+ }
+ show_loading(tr("Running pipeline '%1' over %2 column(s)...").arg(pid).arg(doc.object().size()));
QJsonObject params;
- params["pipeline_id"] = text_inputs_["dp_proc_pid"]->text();
- auto doc = QJsonDocument::fromJson(text_inputs_["dp_proc_data"]->text().toUtf8());
- if (!doc.isNull())
- params["data"] = doc.object();
+ params["pipeline_id"] = pid;
+ params["data"] = doc.object();
AIQuantLabService::instance().dataproc_process_data(params);
});
procvl->addWidget(proc_run);
@@ -787,13 +999,13 @@ QWidget* QuantModulePanel::build_factor_discovery_panel() {
libvl->addWidget(lib_info);
auto* lib_run = make_run_button(tr("BROWSE FACTOR LIBRARY"), lib_tab);
connect(lib_run, &QPushButton::clicked, this, [this]() {
- status_label_->setText(tr("Loading..."));
+ show_loading(tr("Loading Qlib factor library..."));
AIQuantLabService::instance().factor_get_library();
});
libvl->addWidget(lib_run);
auto* inst_run = make_run_button(tr("LIST INSTRUMENTS"), lib_tab);
connect(inst_run, &QPushButton::clicked, this, [this]() {
- status_label_->setText(tr("Loading..."));
+ show_loading(tr("Loading instrument universe..."));
AIQuantLabService::instance().factor_get_instruments();
});
libvl->addWidget(inst_run);
@@ -836,20 +1048,29 @@ QWidget* QuantModulePanel::build_factor_discovery_panel() {
datavl->addWidget(build_input_row(tr("End Date"), fd_end, data_tab));
auto* fd_run = make_run_button(tr("FETCH DATA"), data_tab);
connect(fd_run, &QPushButton::clicked, this, [this]() {
- status_label_->setText(tr("Fetching..."));
+ const QJsonArray instr = parse_csv_strings(text_inputs_["fd_instruments"]->text(), /*lowercase=*/true);
+ if (instr.isEmpty()) {
+ display_error(tr("Enter at least one instrument, e.g. aapl,msft."));
+ return;
+ }
+ const QJsonArray fields = parse_csv_strings(text_inputs_["fd_fields"]->text());
+ if (fields.isEmpty()) {
+ display_error(tr("Enter at least one field, e.g. $close,$volume."));
+ return;
+ }
+ const QDate start = date_inputs_["fd_start"]->date();
+ const QDate end = date_inputs_["fd_end"]->date();
+ if (start > end) {
+ display_error(tr("Start date (%1) is after end date (%2).")
+ .arg(start.toString("yyyy-MM-dd"), end.toString("yyyy-MM-dd")));
+ return;
+ }
+ show_loading(tr("Fetching %1 field(s) for %2 instrument(s)...").arg(fields.size()).arg(instr.size()));
QJsonObject params;
- QJsonArray instr;
- for (auto& s : text_inputs_["fd_instruments"]->text().split(','))
- if (!s.trimmed().isEmpty())
- instr.append(s.trimmed().toLower());
params["instruments"] = instr;
- QJsonArray fields;
- for (auto& s : text_inputs_["fd_fields"]->text().split(','))
- if (!s.trimmed().isEmpty())
- fields.append(s.trimmed());
params["fields"] = fields;
- params["start_date"] = date_inputs_["fd_start"]->date().toString("yyyy-MM-dd");
- params["end_date"] = date_inputs_["fd_end"]->date().toString("yyyy-MM-dd");
+ params["start_date"] = start.toString("yyyy-MM-dd");
+ params["end_date"] = end.toString("yyyy-MM-dd");
AIQuantLabService::instance().factor_get_data(params);
});
datavl->addWidget(fd_run);
@@ -882,10 +1103,18 @@ QWidget* QuantModulePanel::build_factor_discovery_panel() {
calvl->addWidget(build_input_row(tr("End Date"), cal_end, cal_tab));
auto* cal_run = make_run_button(tr("GET TRADING CALENDAR"), cal_tab);
connect(cal_run, &QPushButton::clicked, this, [this]() {
- status_label_->setText(tr("Loading..."));
+ const QDate start = date_inputs_["fd_cal_start"]->date();
+ const QDate end = date_inputs_["fd_cal_end"]->date();
+ if (start > end) {
+ display_error(tr("Start date (%1) is after end date (%2).")
+ .arg(start.toString("yyyy-MM-dd"), end.toString("yyyy-MM-dd")));
+ return;
+ }
+ show_loading(
+ tr("Loading trading calendar %1 → %2...").arg(start.toString("yyyy-MM-dd"), end.toString("yyyy-MM-dd")));
QJsonObject params;
- params["start_date"] = date_inputs_["fd_cal_start"]->date().toString("yyyy-MM-dd");
- params["end_date"] = date_inputs_["fd_cal_end"]->date().toString("yyyy-MM-dd");
+ params["start_date"] = start.toString("yyyy-MM-dd");
+ params["end_date"] = end.toString("yyyy-MM-dd");
AIQuantLabService::instance().factor_get_calendar(params);
});
calvl->addWidget(cal_run);
@@ -926,13 +1155,13 @@ QWidget* QuantModulePanel::build_model_library_panel() {
btvl->addWidget(bt_info);
auto* bt_list = make_run_button(tr("LIST ALL MODELS"), browse_tab);
connect(bt_list, &QPushButton::clicked, this, [this]() {
- status_label_->setText(tr("Loading..."));
+ show_loading(tr("Loading Qlib model catalog..."));
AIQuantLabService::instance().model_list();
});
btvl->addWidget(bt_list);
auto* bt_status = make_run_button(tr("CHECK QLIB STATUS"), browse_tab);
connect(bt_status, &QPushButton::clicked, this, [this]() {
- status_label_->setText(tr("Checking..."));
+ show_loading(tr("Checking Qlib runtime status..."));
AIQuantLabService::instance().model_check_status();
});
btvl->addWidget(bt_status);
@@ -966,18 +1195,29 @@ QWidget* QuantModulePanel::build_model_library_panel() {
ttvl->addWidget(build_input_row(tr("End Date"), ml_end, train_tab));
auto* ml_run = make_run_button(tr("TRAIN MODEL"), train_tab);
connect(ml_run, &QPushButton::clicked, this, [this]() {
- status_label_->setText(tr("Training..."));
+ const QJsonArray instr = parse_csv_strings(text_inputs_["ml_instruments"]->text(), /*lowercase=*/true);
+ if (instr.isEmpty()) {
+ display_error(tr("Enter at least one instrument, e.g. aapl,msft."));
+ return;
+ }
+ QString iso_start, iso_end;
+ if (const QString err =
+ check_iso_range(text_inputs_["ml_start"]->text(), text_inputs_["ml_end"]->text(), iso_start, iso_end);
+ !err.isEmpty()) {
+ display_error(err);
+ return;
+ }
+
+ show_loading(tr("Training %1 on %2 instrument(s) — this can take several minutes...")
+ .arg(combo_inputs_["ml_model_type"]->currentText())
+ .arg(instr.size()));
QJsonObject params;
params["model_type"] = combo_inputs_["ml_model_type"]->currentText();
- QJsonArray instr;
- for (auto& s : text_inputs_["ml_instruments"]->text().split(','))
- if (!s.trimmed().isEmpty())
- instr.append(s.trimmed().toLower());
params["instruments"] = instr;
- if (!text_inputs_["ml_start"]->text().isEmpty())
- params["start_date"] = text_inputs_["ml_start"]->text().trimmed();
- if (!text_inputs_["ml_end"]->text().isEmpty())
- params["end_date"] = text_inputs_["ml_end"]->text().trimmed();
+ if (!iso_start.isEmpty())
+ params["start_date"] = iso_start;
+ if (!iso_end.isEmpty())
+ params["end_date"] = iso_end;
AIQuantLabService::instance().model_train(params);
});
ttvl->addWidget(ml_run);
@@ -1011,18 +1251,31 @@ QWidget* QuantModulePanel::build_model_library_panel() {
btvl2->addWidget(build_input_row(tr("End Date"), bt_end2, bt_tab));
auto* bt_run2 = make_run_button(tr("RUN BACKTEST"), bt_tab);
connect(bt_run2, &QPushButton::clicked, this, [this]() {
- status_label_->setText(tr("Running backtest..."));
+ const QString model_id = text_inputs_["ml_bt_model"]->text().trimmed();
+ if (model_id.isEmpty()) {
+ display_error(tr("Enter the Model ID printed by TRAIN MODEL."));
+ return;
+ }
+ const QJsonArray instr = parse_csv_strings(text_inputs_["ml_bt_instr"]->text(), /*lowercase=*/true);
+ if (instr.isEmpty()) {
+ display_error(tr("Enter at least one instrument, e.g. aapl,msft."));
+ return;
+ }
+ QString iso_start, iso_end;
+ if (const QString err = check_iso_range(text_inputs_["ml_bt_start"]->text(), text_inputs_["ml_bt_end"]->text(),
+ iso_start, iso_end);
+ !err.isEmpty()) {
+ display_error(err);
+ return;
+ }
+ show_loading(tr("Backtesting %1 on %2 instrument(s)...").arg(model_id).arg(instr.size()));
QJsonObject params;
- params["model_id"] = text_inputs_["ml_bt_model"]->text().trimmed();
- QJsonArray instr;
- for (auto& s : text_inputs_["ml_bt_instr"]->text().split(','))
- if (!s.trimmed().isEmpty())
- instr.append(s.trimmed().toLower());
+ params["model_id"] = model_id;
params["instruments"] = instr;
- if (!text_inputs_["ml_bt_start"]->text().isEmpty())
- params["start_date"] = text_inputs_["ml_bt_start"]->text().trimmed();
- if (!text_inputs_["ml_bt_end"]->text().isEmpty())
- params["end_date"] = text_inputs_["ml_bt_end"]->text().trimmed();
+ if (!iso_start.isEmpty())
+ params["start_date"] = iso_start;
+ if (!iso_end.isEmpty())
+ params["end_date"] = iso_end;
AIQuantLabService::instance().model_backtest(params);
});
btvl2->addWidget(bt_run2);
diff --git a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_RL.cpp b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_RL.cpp
index 63bc03c9b..2a361387f 100644
--- a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_RL.cpp
+++ b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_RL.cpp
@@ -46,7 +46,7 @@ QWidget* QuantModulePanel::build_rl_trading_panel() {
vl->addWidget(build_input_row(tr("RL Algorithm"), algo, w));
auto* ticker = new QLineEdit(w);
- ticker->setPlaceholderText(tr("AAPL"));
+ ticker->setPlaceholderText(tr("e.g. AAPL — daily bars fetched from Yahoo Finance"));
ticker->setStyleSheet(input_ss());
text_inputs_["rl_ticker"] = ticker;
vl->addWidget(build_input_row(tr("Ticker"), ticker, w));
@@ -68,8 +68,15 @@ QWidget* QuantModulePanel::build_rl_trading_panel() {
rl_train_button_ = make_run_button(tr("TRAIN RL AGENT"), w);
connect(rl_train_button_, &QPushButton::clicked, this, [this]() {
- if (!rl_train_button_ || !rl_log_console_)
+ if (!rl_train_button_ || !rl_log_console_ || !rl_progress_bar_ || !rl_progress_stats_)
return;
+ // A blank ticker used to be forwarded verbatim, so the run failed deep
+ // inside yfinance with an opaque traceback instead of here.
+ const QString tk = text_inputs_["rl_ticker"]->text().trimmed().toUpper();
+ if (tk.isEmpty()) {
+ display_error(tr("Enter a ticker (e.g. AAPL, SPY, MSFT) before training."));
+ return;
+ }
rl_log_console_->clear();
rl_progress_bar_->setValue(0);
rl_progress_bar_->setVisible(true);
@@ -77,10 +84,11 @@ QWidget* QuantModulePanel::build_rl_trading_panel() {
rl_progress_stats_->setVisible(true);
rl_log_console_->setVisible(true);
rl_train_button_->setEnabled(false);
- status_label_->setText(tr("Training RL Agent..."));
+ status_label_->setText(
+ tr("Training %1 on %2 — this can take several minutes.").arg(combo_inputs_["rl_algo"]->currentText(), tk));
QJsonObject params;
params["algorithm"] = combo_inputs_["rl_algo"]->currentText();
- params["ticker"] = text_inputs_["rl_ticker"]->text();
+ params["ticker"] = tk;
params["episodes"] = int_inputs_["rl_episodes"]->value();
params["learning_rate"] = double_inputs_["rl_learning_rate"]->value();
params["initial_capital"] = double_inputs_["rl_capital"]->value();
diff --git a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_Results.cpp b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_Results.cpp
index 05e98f0c8..42cbe81e4 100644
--- a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_Results.cpp
+++ b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_Results.cpp
@@ -481,6 +481,10 @@ void QuantModulePanel::on_result(const QString& module_id, const QString& comman
display_error(payload["error"].toString());
return;
}
+ // HFT paints into fixed in-tab cards rather than the results pane, so
+ // nothing else clears a previously shown error banner — do it here or a
+ // stale red box sits under a successful run forever.
+ clear_results();
// Helper: find a named child label in this panel and set its text
auto set_card = [this](const QString& name, const QString& text, const QString& color = {}) {
@@ -948,8 +952,11 @@ void QuantModulePanel::on_result(const QString& module_id, const QString& comman
hdr->setStyleSheet(QString("color:%1;font-weight:700;font-size:13px;").arg(ui::colors::TEXT_PRIMARY()));
results_layout_->addWidget(hdr);
- // Table of windows
- auto* tbl = new QTableWidget(total, 4, this);
+ // Table of windows. Sized from the returned array, not from
+ // total_windows — the Python side caps the preview list, so a larger
+ // `total` produced silently blank trailing rows (and a smaller one
+ // dropped windows because setItem() past rowCount is a no-op).
+ auto* tbl = new QTableWidget(int(windows.size()), 4, this);
tbl->setStyleSheet(table_ss());
tbl->setHorizontalHeaderLabels({"#", tr("Train Start"), tr("Train End"), tr("Test Period")});
tbl->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
diff --git a/fincept-qt/src/screens/akshare/AkShareScreen.cpp b/fincept-qt/src/screens/akshare/AkShareScreen.cpp
index 347bb1309..d2973a2f2 100644
--- a/fincept-qt/src/screens/akshare/AkShareScreen.cpp
+++ b/fincept-qt/src/screens/akshare/AkShareScreen.cpp
@@ -346,6 +346,8 @@ QWidget* AkShareScreen::create_endpoint_panel() {
search_input_ = new QLineEdit;
search_input_->setObjectName("akSearchInput");
search_input_->setPlaceholderText(tr("Search endpoints..."));
+ search_input_->setAccessibleName(tr("Filter endpoints"));
+ search_input_->setClearButtonEnabled(true);
connect(search_input_, &QLineEdit::textChanged, this, &AkShareScreen::on_search_changed);
endpoint_count_ = new QLabel(tr("%1 endpoints").arg(0));
@@ -358,6 +360,7 @@ QWidget* AkShareScreen::create_endpoint_panel() {
// Endpoint list
endpoint_list_ = new QListWidget;
endpoint_list_->setObjectName("akEndpointList");
+ endpoint_list_->setAccessibleName(tr("Available endpoints"));
connect(endpoint_list_, &QListWidget::itemClicked, this, &AkShareScreen::on_endpoint_clicked);
vl->addWidget(endpoint_list_, 1);
@@ -386,6 +389,8 @@ QWidget* AkShareScreen::create_params_panel() {
param_symbol_ = new QLineEdit("000001");
param_symbol_->setObjectName("akParamInput");
param_symbol_->setFixedWidth(90);
+ param_symbol_->setAccessibleName(tr("Symbol parameter"));
+ connect(param_symbol_, &QLineEdit::returnPressed, this, &AkShareScreen::on_execute);
// Start date
start_label_ = new QLabel(tr("START"));
@@ -435,6 +440,19 @@ QWidget* AkShareScreen::create_params_panel() {
hl->addStretch(1);
hl->addWidget(exec_btn_);
+ param_start_->setAccessibleName(tr("Start date parameter"));
+ param_end_->setAccessibleName(tr("End date parameter"));
+ param_period_->setAccessibleName(tr("Period parameter (disabled)"));
+ exec_btn_->setAccessibleName(tr("Execute query"));
+ connect(param_start_, &QLineEdit::returnPressed, this, &AkShareScreen::on_execute);
+ connect(param_end_, &QLineEdit::returnPressed, this, &AkShareScreen::on_execute);
+
+ // Explicit left-to-right tab order through the parameter form.
+ QWidget::setTabOrder(param_symbol_, param_start_);
+ QWidget::setTabOrder(param_start_, param_end_);
+ QWidget::setTabOrder(param_end_, param_period_);
+ QWidget::setTabOrder(param_period_, exec_btn_);
+
return panel;
}
@@ -704,7 +722,20 @@ void AkShareScreen::populate_endpoint_list(const QJsonObject& result) {
}
endpoint_count_->setText(tr("%1 endpoints").arg(all_endpoints.size()));
- data_status_->setText(tr("Select an endpoint"));
+ // The "select a data source" hint used to stay pinned under the list
+ // forever, even once endpoints were loaded. Show it only when the list is
+ // genuinely empty, and say why.
+ if (empty_state_) {
+ if (all_endpoints.isEmpty()) {
+ empty_state_->setText(active_source_ >= 0
+ ? tr("No endpoints published by %1").arg(sources_[active_source_].name)
+ : tr("Select a data source above\nto load available endpoints"));
+ empty_state_->show();
+ } else {
+ empty_state_->hide();
+ }
+ }
+ data_status_->setText(all_endpoints.isEmpty() ? tr("No endpoints available") : tr("Select an endpoint"));
LOG_INFO("AkShare", "Loaded " + QString::number(all_endpoints.size()) + " endpoints");
}
diff --git a/fincept-qt/src/screens/algo_trading/AlertsPanel.cpp b/fincept-qt/src/screens/algo_trading/AlertsPanel.cpp
index d7f098d7f..269441a71 100644
--- a/fincept-qt/src/screens/algo_trading/AlertsPanel.cpp
+++ b/fincept-qt/src/screens/algo_trading/AlertsPanel.cpp
@@ -13,6 +13,7 @@
#include <QHeaderView>
#include <QInputDialog>
#include <QJsonObject>
+#include <QMessageBox>
#include <QScrollArea>
#include <QVBoxLayout>
@@ -267,7 +268,17 @@ void AlertsPanel::build_ui() {
.arg(fincept::ui::fonts::SMALL)
.arg(fincept::ui::fonts::DATA_FAMILY)
.arg(fincept::ui::colors::TEXT_PRIMARY(), fincept::ui::colors::BG_RAISED(),
- fincept::ui::colors::TEXT_TERTIARY()));
+ fincept::ui::colors::TEXT_TERTIARY()) +
+ QString("QPushButton#apRowBtn { background: transparent; color: %1; border: 1px solid %2;"
+ " font-size: %3px; font-weight: 700; %4 padding: 1px 8px; }"
+ "QPushButton#apRowBtn:hover { color: %5; border-color: %5; }"
+ "QPushButton#apRowDelete { background: transparent; color: %6; border: 1px solid %6;"
+ " font-size: %3px; font-weight: 700; %4 padding: 1px 8px; }"
+ "QPushButton#apRowDelete:hover { background: rgba(220,38,38,0.12); }")
+ .arg(fincept::ui::colors::TEXT_SECONDARY(), fincept::ui::colors::BORDER_DIM())
+ .arg(fincept::ui::fonts::TINY)
+ .arg(kMonoFont())
+ .arg(fincept::ui::colors::AMBER(), fincept::ui::colors::NEGATIVE()));
vl->addWidget(watches_table_);
auto* hist_divider = new QFrame(content);
@@ -380,15 +391,38 @@ void AlertsPanel::on_refresh_watches() {
auto* cell = new QWidget(watches_table_);
auto* hl = new QHBoxLayout(cell);
hl->setContentsMargins(2, 0, 2, 0);
+ // Object names only — the skins live on the table's stylesheet (P7) and
+ // give these three the terminal look instead of the platform default.
auto* edit = new QPushButton(tr("Edit"), cell);
+ edit->setObjectName(QStringLiteral("apRowBtn"));
+ edit->setAccessibleName(tr("Edit watch %1").arg(w.name));
connect(edit, &QPushButton::clicked, this, [this, w]() { load_watch(w); });
auto* test = new QPushButton(tr("Test"), cell);
+ test->setObjectName(QStringLiteral("apRowBtn"));
+ test->setAccessibleName(tr("Fire a test alert for watch %1").arg(w.name));
connect(test, &QPushButton::clicked, this,
[id]() { fincept::algo::ScanMonitor::instance().test_fire(id, QString()); });
auto* del = new QPushButton(tr("Delete"), cell);
- connect(del, &QPushButton::clicked, this, [this, id]() {
+ del->setObjectName(QStringLiteral("apRowDelete"));
+ del->setAccessibleName(tr("Delete watch %1").arg(w.name));
+ const QString wname = w.name;
+ connect(del, &QPushButton::clicked, this, [this, id, wname]() {
+ // Deleting a watch stops a live monitor and drops its config with no
+ // recovery path — confirm first.
+ const auto ans = QMessageBox::question(
+ this, tr("Delete Watch"),
+ tr("Delete watch \"%1\"?\n\nIt stops monitoring immediately. Its alert history is kept.").arg(wname),
+ QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
+ if (ans != QMessageBox::Yes)
+ return;
fincept::algo::ScanMonitor::instance().stop_watch(id);
fincept::ScanWatchRepository::instance().remove(id);
+ // Editing state can't survive its own row being deleted.
+ if (editing_id_ == id) {
+ editing_id_.clear();
+ save_btn_->setText(tr("SAVE WATCH"));
+ status_label_->setText(tr("The watch being edited was deleted — this is now a new watch."));
+ }
// Keep the fired history: deleting a live watch must NOT erase its
// already-triggered events from ALERT HISTORY.
on_refresh_watches();
@@ -457,6 +491,14 @@ void AlertsPanel::prefill(const QJsonArray& conditions, const QString& logic, co
status_label_->setText(tr("Pre-filled from Scanner — name it and SAVE WATCH."));
}
+void AlertsPanel::showEvent(QShowEvent* e) {
+ QWidget::showEvent(e);
+ // ALERT HISTORY only refreshed on construction and on watch_status_changed,
+ // so alerts that fired while another tab was open never appeared until the
+ // next status change. Re-read on entry (cheap: two capped SELECTs, no timer).
+ on_refresh_watches();
+}
+
void AlertsPanel::changeEvent(QEvent* e) {
if (e->type() == QEvent::LanguageChange)
retranslateUi();
diff --git a/fincept-qt/src/screens/algo_trading/AlertsPanel.h b/fincept-qt/src/screens/algo_trading/AlertsPanel.h
index 80544ec72..43cdadf8d 100644
--- a/fincept-qt/src/screens/algo_trading/AlertsPanel.h
+++ b/fincept-qt/src/screens/algo_trading/AlertsPanel.h
@@ -13,6 +13,7 @@
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
+#include <QShowEvent>
#include <QSpinBox>
#include <QTableWidget>
#include <QWidget>
@@ -35,6 +36,7 @@ class AlertsPanel : public QWidget {
protected:
void changeEvent(QEvent* event) override;
+ void showEvent(QShowEvent* event) override;
private:
void build_ui();
diff --git a/fincept-qt/src/screens/algo_trading/AlgoDeployDialog.cpp b/fincept-qt/src/screens/algo_trading/AlgoDeployDialog.cpp
index df8c902d1..849947fd7 100644
--- a/fincept-qt/src/screens/algo_trading/AlgoDeployDialog.cpp
+++ b/fincept-qt/src/screens/algo_trading/AlgoDeployDialog.cpp
@@ -8,6 +8,7 @@
#include <QDialogButtonBox>
#include <QFormLayout>
#include <QMessageBox>
+#include <QPushButton>
#include <QUuid>
#include <QVBoxLayout>
@@ -105,6 +106,16 @@ void AlgoDeployDialog::build_ui() {
QString("color: %1; font-size: 9px; font-family: %2;").arg(colors::TEXT_TERTIARY(), fonts::DATA_FAMILY()));
root->addWidget(id_label);
+ // Live banner — hidden in paper mode, impossible to miss in live mode.
+ live_warning_ = new QLabel(tr("⚠ LIVE MODE — this strategy will place REAL orders with REAL money."), this);
+ live_warning_->setWordWrap(true);
+ live_warning_->setStyleSheet(QString("color: %1; background: rgba(220,38,38,0.10);"
+ " border: 1px solid %1; padding: 6px 10px;"
+ " font-size: 11px; font-weight: 700; font-family: %2;")
+ .arg(colors::NEGATIVE(), fonts::DATA_FAMILY()));
+ live_warning_->setVisible(false);
+ root->addWidget(live_warning_);
+
auto* form = new QFormLayout;
form->setSpacing(8);
form->setLabelAlignment(Qt::AlignRight);
@@ -186,10 +197,45 @@ void AlgoDeployDialog::build_ui() {
connect(buttons_, &QDialogButtonBox::rejected, this, &QDialog::reject);
root->addWidget(buttons_);
+ // ── Accessibility ────────────────────────────────────────────────────────
+ // Screen readers otherwise announce these as bare "combo box" / "spin box".
+ symbol_edit_->setAccessibleName(tr("Trading symbol"));
+ mode_combo_->setAccessibleName(tr("Deployment mode, paper or live"));
+ side_combo_->setAccessibleName(tr("Entry side, buy or sell"));
+ account_combo_->setAccessibleName(tr("Broker account"));
+ exchange_combo_->setAccessibleName(tr("Exchange"));
+ product_type_combo_->setAccessibleName(tr("Product type"));
+ timeframe_combo_->setAccessibleName(tr("Bar timeframe"));
+ quantity_spin_->setAccessibleName(tr("Order quantity"));
+ max_order_spin_->setAccessibleName(tr("Maximum order value"));
+ max_loss_spin_->setAccessibleName(tr("Maximum daily loss"));
+ if (auto* ok_btn = buttons_->button(QDialogButtonBox::Ok))
+ ok_btn->setAccessibleName(tr("Deploy strategy"));
+
+ // ── Keyboard order ───────────────────────────────────────────────────────
+ // Mode comes second on purpose: paper-vs-live is the decision that matters.
+ setTabOrder(symbol_edit_, mode_combo_);
+ setTabOrder(mode_combo_, side_combo_);
+ setTabOrder(side_combo_, account_combo_);
+ setTabOrder(account_combo_, exchange_combo_);
+ setTabOrder(exchange_combo_, product_type_combo_);
+ setTabOrder(product_type_combo_, timeframe_combo_);
+ setTabOrder(timeframe_combo_, quantity_spin_);
+ setTabOrder(quantity_spin_, max_order_spin_);
+ setTabOrder(max_order_spin_, max_loss_spin_);
+ setTabOrder(max_loss_spin_, buttons_);
+
on_mode_changed(0);
populate_accounts();
}
+void AlgoDeployDialog::set_risk_defaults(double quantity, double max_order_value) {
+ if (quantity_spin_ && quantity > 0.0)
+ quantity_spin_->setValue(quantity);
+ if (max_order_spin_ && max_order_value >= 0.0)
+ max_order_spin_->setValue(max_order_value);
+}
+
void AlgoDeployDialog::on_mode_changed(int index) {
// The broker/account is shown in BOTH modes: it is the real market-data source
// for the deployment (warm-up history + live quotes). Live additionally routes
@@ -205,6 +251,26 @@ void AlgoDeployDialog::on_mode_changed(int index) {
const bool is_live = (mode_combo_->currentData().toString() == "live");
account_label_->setText(is_live ? tr("Broker (orders + data):") : tr("Broker (data source):"));
+
+ // Live vs paper must be legible at a glance, not inferred from a dropdown:
+ // red banner + red destructive-styled action button + explicit button text.
+ if (live_warning_)
+ live_warning_->setVisible(is_live);
+ if (buttons_) {
+ if (auto* ok_btn = buttons_->button(QDialogButtonBox::Ok)) {
+ ok_btn->setText(is_live ? tr("DEPLOY LIVE") : tr("DEPLOY (PAPER)"));
+ ok_btn->setStyleSheet(
+ is_live ? QString("QPushButton { background: rgba(220,38,38,0.12); color: %1;"
+ " border: 1px solid %1; font-size: 11px; font-weight: 700; padding: 6px 20px; }"
+ "QPushButton:hover { background: %1; color: %2; }")
+ .arg(colors::NEGATIVE(), colors::TEXT_PRIMARY())
+ : QString("QPushButton { background: %1; color: %2; border: 1px solid %3;"
+ " font-size: 11px; font-weight: 700; padding: 6px 20px; }"
+ "QPushButton:hover { border-color: %4; color: %4; }")
+ .arg(colors::BG_RAISED(), colors::TEXT_PRIMARY(), colors::BORDER_DIM(), colors::CYAN()));
+ }
+ }
+ setWindowTitle(is_live ? tr("Deploy Strategy — LIVE") : tr("Deploy Strategy — Paper"));
}
void AlgoDeployDialog::populate_accounts() {
@@ -274,6 +340,45 @@ void AlgoDeployDialog::on_ok() {
tr("Account credentials expired. Re-authenticate in Equity Trading."));
return;
}
+
+ // ── Live confirmation gate ───────────────────────────────────────────
+ // Going live is irreversible from this dialog's point of view: the engine
+ // starts a runner that will place real broker orders unattended. Restate
+ // the exact terms and require a deliberate second confirmation, defaulted
+ // to Cancel.
+ const auto account = AccountManager::instance().get_account(account_id);
+ const QString acct_label = account.display_name.isEmpty() ? account_id : account.display_name;
+ const bool is_fno_confirm = (fno_instrument_type_ != QLatin1String("equity"));
+ const QString instrument =
+ is_fno_confirm ? tr("%1 %2 (%3)").arg(fno_underlying_, fno_expiry_rule_, fno_instrument_type_)
+ : symbol_edit_->text().trimmed().toUpper();
+ const QString max_order_text = max_order_spin_->value() > 0
+ ? QString::number(max_order_spin_->value(), 'f', 0)
+ : tr("no limit");
+ const QString max_loss_text =
+ max_loss_spin_->value() > 0 ? QString::number(max_loss_spin_->value(), 'f', 0) : tr("no limit");
+
+ const auto answer =
+ QMessageBox::warning(this, tr("Confirm LIVE deployment"),
+ tr("You are about to deploy \"%1\" to LIVE trading.\n\n"
+ "It will place REAL orders on a REAL account, unattended,\n"
+ "until you stop it from the Dashboard.\n\n"
+ " Instrument: %2\n"
+ " Entry side: %3\n"
+ " Quantity: %4\n"
+ " Timeframe: %5\n"
+ " Broker account: %6 (%7)\n"
+ " Exchange: %8\n"
+ " Max order value: %9\n"
+ " Max daily loss: %10\n\n"
+ "Deploy live?")
+ .arg(strategy_name_, instrument, side_combo_->currentData().toString())
+ .arg(quantity_spin_->value(), 0, 'f', 2)
+ .arg(timeframe_combo_->currentText(), acct_label, account.broker_id,
+ exchange_combo_->currentText(), max_order_text, max_loss_text),
+ QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel);
+ if (answer != QMessageBox::Yes)
+ return;
}
// Mint a stable id for this deployment — used as the runner key, the
@@ -326,9 +431,10 @@ void AlgoDeployDialog::changeEvent(QEvent* event) {
}
void AlgoDeployDialog::retranslateUi() {
- setWindowTitle(tr("Deploy Strategy"));
if (title_label_)
title_label_->setText(tr("DEPLOY: %1").arg(strategy_name_));
+ if (live_warning_)
+ live_warning_->setText(tr("⚠ LIVE MODE — this strategy will place REAL orders with REAL money."));
if (symbol_edit_)
symbol_edit_->setPlaceholderText(tr("e.g. RELIANCE"));
if (symbol_label_)
@@ -365,8 +471,11 @@ void AlgoDeployDialog::retranslateUi() {
max_order_spin_->setSpecialValueText(tr("No limit"));
if (max_loss_spin_)
max_loss_spin_->setSpecialValueText(tr("No limit"));
- if (buttons_)
- buttons_->button(QDialogButtonBox::Ok)->setText(tr("DEPLOY"));
+ // Window title and the OK button's text/skin are mode-dependent (paper vs
+ // live) — re-derive them rather than resetting to a neutral "DEPLOY", which
+ // would erase the live-mode warning styling on a language switch.
+ if (mode_combo_)
+ on_mode_changed(mode_combo_->currentIndex());
// account_combo_ "No connected accounts" placeholder is rebuilt by populate_accounts().
}
diff --git a/fincept-qt/src/screens/algo_trading/AlgoDeployDialog.h b/fincept-qt/src/screens/algo_trading/AlgoDeployDialog.h
index 290dd2f15..8979c8c8d 100644
--- a/fincept-qt/src/screens/algo_trading/AlgoDeployDialog.h
+++ b/fincept-qt/src/screens/algo_trading/AlgoDeployDialog.h
@@ -28,6 +28,12 @@ class AlgoDeployDialog : public QDialog {
// F&O context for option/future deployments (set by the StrategyBuilder before exec()).
void set_fno_context(const QString& instrument_type, const QString& underlying, const QString& expiry_rule);
+ // Seed the risk fields from the caller's risk panel BEFORE exec(), so the
+ // numbers the user confirms in this dialog are the numbers that are actually
+ // deployed. Callers must not overwrite result().quantity afterwards — that
+ // made the dialog lie about the size going live.
+ void set_risk_defaults(double quantity, double max_order_value);
+
protected:
void changeEvent(QEvent* event) override;
@@ -61,6 +67,9 @@ class AlgoDeployDialog : public QDialog {
QDoubleSpinBox* max_loss_spin_ = nullptr;
QLabel* title_label_ = nullptr;
+ // Persistent red banner shown only while Mode == Live. Real money is the
+ // one state that must never be inferred from a dropdown alone.
+ QLabel* live_warning_ = nullptr;
QLabel* symbol_label_ = nullptr;
QLabel* mode_label_ = nullptr;
QLabel* side_label_ = nullptr;
diff --git a/fincept-qt/src/screens/algo_trading/AlgoTradingScreen.cpp b/fincept-qt/src/screens/algo_trading/AlgoTradingScreen.cpp
index ad2119e5a..7ac3d4f9e 100644
--- a/fincept-qt/src/screens/algo_trading/AlgoTradingScreen.cpp
+++ b/fincept-qt/src/screens/algo_trading/AlgoTradingScreen.cpp
@@ -33,13 +33,21 @@ AlgoTradingScreen::AlgoTradingScreen(QWidget* parent) : QWidget(parent) {
connect(&fincept::algo::AlgoEngine::instance(), &fincept::algo::AlgoEngine::deployments_loaded, this,
[this](const QVector<AlgoDeployment>& deps) {
+ // "LIVE" must mean real money. Counting paper deployments in this
+ // badge made a paper-only session look like it was trading live
+ // (and vice-versa hid the fact that something real was running).
int active = 0;
+ int live = 0;
for (const auto& d : deps) {
- if (d.status == "running" || d.status == "starting")
- ++active;
+ if (d.status != "running" && d.status != "starting")
+ continue;
+ ++active;
+ if (d.mode == QLatin1String("live"))
+ ++live;
}
active_deployments_ = active;
- deploy_count_label_->setText(tr("%1 LIVE").arg(active));
+ live_deployments_ = live;
+ update_deploy_badge();
});
LOG_INFO("AlgoTrading", "Screen constructed");
@@ -156,18 +164,34 @@ QWidget* AlgoTradingScreen::build_top_bar() {
hl->addStretch(1);
- // Deployment count badge
- deploy_count_label_ = new QLabel(tr("%1 LIVE").arg(0), bar);
- deploy_count_label_->setStyleSheet(QString("color:%1; font-size:9px; font-weight:700; font-family:%2;"
- "padding:3px 8px; background:rgba(22,163,74,0.08);"
- "border:1px solid rgba(22,163,74,0.25); border-radius:2px;")
- .arg(ui::colors::POSITIVE())
- .arg(ui::fonts::DATA_FAMILY()));
+ // Running-deployment badge (live vs paper — see update_deploy_badge()).
+ deploy_count_label_ = new QLabel(bar);
hl->addWidget(deploy_count_label_);
+ update_deploy_badge();
return bar;
}
+void AlgoTradingScreen::update_deploy_badge() {
+ if (!deploy_count_label_)
+ return;
+ const bool has_live = (live_deployments_ > 0);
+ deploy_count_label_->setText(has_live ? tr("%1 LIVE").arg(live_deployments_)
+ : tr("%1 PAPER").arg(active_deployments_));
+ deploy_count_label_->setToolTip(tr("%1 deployment(s) running — %2 live, %3 paper")
+ .arg(active_deployments_)
+ .arg(live_deployments_)
+ .arg(active_deployments_ - live_deployments_));
+ deploy_count_label_->setAccessibleName(deploy_count_label_->toolTip());
+ deploy_count_label_->setStyleSheet(
+ QString("color:%1; font-size:9px; font-weight:700; font-family:%2;"
+ "padding:3px 8px; background:rgba(%3,0.08);"
+ "border:1px solid rgba(%3,0.25); border-radius:2px;")
+ .arg(has_live ? ui::colors::NEGATIVE() : ui::colors::POSITIVE())
+ .arg(ui::fonts::DATA_FAMILY())
+ .arg(has_live ? "220,38,38" : "22,163,74"));
+}
+
QWidget* AlgoTradingScreen::build_status_bar() {
auto* bar = new QWidget(this);
bar->setFixedHeight(24);
@@ -243,8 +267,7 @@ void AlgoTradingScreen::retranslateUi() {
engine_caption_->setText(tr("ENGINE:"));
if (status_label_)
status_label_->setText(tr("IDLE"));
- if (deploy_count_label_)
- deploy_count_label_->setText(tr("%1 LIVE").arg(active_deployments_));
+ update_deploy_badge();
// Tab button labels — fixed order matches build_top_bar().
if (tab_buttons_.size() == 6) {
diff --git a/fincept-qt/src/screens/algo_trading/AlgoTradingScreen.h b/fincept-qt/src/screens/algo_trading/AlgoTradingScreen.h
index 4721fffba..83c6dae99 100644
--- a/fincept-qt/src/screens/algo_trading/AlgoTradingScreen.h
+++ b/fincept-qt/src/screens/algo_trading/AlgoTradingScreen.h
@@ -46,6 +46,9 @@ class AlgoTradingScreen : public QWidget, public IStatefulScreen {
QWidget* build_top_bar();
QWidget* build_status_bar();
void update_tab_buttons();
+ /// Re-render the running-deployment badge. Red "N LIVE" only when real-money
+ /// deployments are running; green "N PAPER" otherwise.
+ void update_deploy_badge();
void retranslateUi();
QStackedWidget* content_stack_ = nullptr;
@@ -59,6 +62,7 @@ class AlgoTradingScreen : public QWidget, public IStatefulScreen {
QVector<QPushButton*> tab_buttons_;
int active_tab_ = 0;
int active_deployments_ = 0;
+ int live_deployments_ = 0;
QLabel* title_label_ = nullptr;
QLabel* engine_caption_ = nullptr;
QLabel* deploy_count_label_ = nullptr;
diff --git a/fincept-qt/src/screens/algo_trading/DeploymentDashboard.cpp b/fincept-qt/src/screens/algo_trading/DeploymentDashboard.cpp
index abed22cb7..602d69bc4 100644
--- a/fincept-qt/src/screens/algo_trading/DeploymentDashboard.cpp
+++ b/fincept-qt/src/screens/algo_trading/DeploymentDashboard.cpp
@@ -12,6 +12,7 @@
#include <QDateTime>
#include <QFrame>
#include <QHBoxLayout>
+#include <QMessageBox>
#include <QProgressBar>
#include <QPushButton>
#include <QScrollArea>
@@ -83,10 +84,23 @@ void DeploymentDashboard::connect_service() {
connect(&svc, &AlgoTradingService::error_occurred, this, &DeploymentDashboard::on_error);
// Ticks the "updated Ns ago" labels once a second.
+ // P3: interval + connection only — showEvent()/hideEvent() own start/stop.
age_timer_ = new QTimer(this);
age_timer_->setInterval(1000);
connect(age_timer_, &QTimer::timeout, this, &DeploymentDashboard::refresh_ages);
- age_timer_->start();
+}
+
+void DeploymentDashboard::showEvent(QShowEvent* e) {
+ QWidget::showEvent(e);
+ if (age_timer_)
+ age_timer_->start();
+ refresh_ages();
+}
+
+void DeploymentDashboard::hideEvent(QHideEvent* e) {
+ QWidget::hideEvent(e);
+ if (age_timer_)
+ age_timer_->stop();
}
// ── Build summary stat card ─────────────────────────────────────────────────
@@ -344,21 +358,48 @@ QWidget* DeploymentDashboard::build_deployment_card(const AlgoDeployment& d, QWi
auto* stop_btn = new QPushButton(tr("STOP"), card);
stop_btn->setCursor(Qt::PointingHandCursor);
stop_btn->setFixedHeight(26);
+ stop_btn->setAccessibleName(tr("Stop deployment %1 on %2").arg(d.strategy_name, d.symbol));
stop_btn->setStyleSheet(QString("QPushButton { background: transparent; color: %1; border: 1px solid %1;"
" font-size: %2px; font-weight: 700; %3 padding: 2px 16px; }"
- "QPushButton:hover { background: rgba(220,38,38,0.1); }")
+ "QPushButton:hover { background: rgba(220,38,38,0.1); }"
+ "QPushButton:disabled { color: %4; border-color: %4; }")
.arg(fincept::ui::colors::NEGATIVE())
.arg(fincept::ui::fonts::TINY)
- .arg(kMonoFont()));
- connect(stop_btn, &QPushButton::clicked, card, [dep_id = d.id]() {
- algo_ns::AlgoEngine::instance().stop_deployment(dep_id);
- LOG_INFO("AlgoTrading", QString("Stop requested: %1").arg(dep_id));
- });
+ .arg(kMonoFont())
+ .arg(fincept::ui::colors::TEXT_DIM()));
+ // A live strategy that is stopped mid-position leaves that position
+ // unmanaged at the broker, so confirm — and state whether it's live.
+ // The button then latches disabled until the engine reports the stop, so
+ // the card can never show STOP while a stop is already in flight.
+ const bool live = (d.mode == QLatin1String("live"));
+ connect(stop_btn, &QPushButton::clicked, card,
+ [this, stop_btn, dep_id = d.id, name = d.strategy_name, sym = d.symbol, live]() {
+ const QString detail =
+ live ? tr("Stop LIVE deployment \"%1\" on %2?\n\n"
+ "The runner will stop placing orders immediately. Any position it is\n"
+ "currently holding at the broker is NOT closed — you must flatten it\n"
+ "yourself from Equity Trading.")
+ .arg(name, sym)
+ : tr("Stop paper deployment \"%1\" on %2?").arg(name, sym);
+ const auto ans = QMessageBox::question(this, tr("Stop deployment"), detail,
+ QMessageBox::Yes | QMessageBox::Cancel,
+ QMessageBox::Cancel);
+ if (ans != QMessageBox::Yes)
+ return;
+ stop_btn->setEnabled(false);
+ stop_btn->setText(tr("STOPPING…"));
+ auto it = cards_.find(dep_id);
+ if (it != cards_.end())
+ it.value().stop_pending = true;
+ algo_ns::AlgoEngine::instance().stop_deployment(dep_id);
+ LOG_INFO("AlgoTrading", QString("Stop requested: %1").arg(dep_id));
+ });
btn_row->addWidget(stop_btn);
} else {
auto* remove_btn = new QPushButton(tr("REMOVE"), card);
remove_btn->setCursor(Qt::PointingHandCursor);
remove_btn->setFixedHeight(26);
+ remove_btn->setAccessibleName(tr("Remove deployment %1 on %2").arg(d.strategy_name, d.symbol));
remove_btn->setStyleSheet(QString("QPushButton { background: transparent; color: %1; border: 1px solid %1;"
" font-size: %2px; font-weight: 700; %3 padding: 2px 16px; }"
"QPushButton:hover { background: rgba(120,120,120,0.1); }")
@@ -382,15 +423,30 @@ QWidget* DeploymentDashboard::build_deployment_card(const AlgoDeployment& d, QWi
void DeploymentDashboard::update_summary(const QVector<AlgoDeployment>& deployments) {
int active = 0;
- double pnl_sum = 0;
+ int active_live = 0;
+ // Paper P&L is simulated money and live P&L is real money — summing them into
+ // one "TOTAL P&L" tile produced a number that means nothing. Track separately.
+ double live_pnl = 0;
+ double paper_pnl = 0;
+ int live_count = 0;
int trades_sum = 0;
double win_rate_sum = 0;
int win_rate_count = 0;
for (const auto& d : deployments) {
- if (d.status == "running" || d.status == "starting")
+ const bool running = (d.status == "running" || d.status == "starting");
+ const bool is_live = (d.mode == QLatin1String("live"));
+ if (running) {
++active;
- pnl_sum += d.total_pnl + d.unrealized_pnl;
+ if (is_live)
+ ++active_live;
+ }
+ if (is_live) {
+ live_pnl += d.total_pnl + d.unrealized_pnl;
+ ++live_count;
+ } else {
+ paper_pnl += d.total_pnl + d.unrealized_pnl;
+ }
trades_sum += d.total_trades;
if (d.total_trades > 0) {
win_rate_sum += d.win_rate;
@@ -401,17 +457,27 @@ void DeploymentDashboard::update_summary(const QVector<AlgoDeployment>& deployme
double avg_wr = (win_rate_count > 0) ? (win_rate_sum / win_rate_count) : 0;
if (active_count_)
- active_count_->setText(QString::number(active));
+ active_count_->setText(active_live > 0 ? tr("%1 · %2 LIVE").arg(active).arg(active_live)
+ : QString::number(active));
if (total_pnl_) {
- QString sum_cs = deployments.isEmpty() ? cur::symbol() : currency_symbol(deployments.first().broker_id);
- total_pnl_->setText(QString("%1%2%3").arg(pnl_sum >= 0 ? "+" : "-", sum_cs).arg(std::abs(pnl_sum), 0, 'f', 2));
- total_pnl_->setStyleSheet(
- QString("color: %1; font-size: %2px; font-weight: 700; %3"
- " background: transparent; border: none;")
- .arg(pnl_sum >= 0 ? fincept::ui::colors::POSITIVE() : fincept::ui::colors::NEGATIVE())
- .arg(fincept::ui::fonts::TITLE)
- .arg(kMonoFont()));
+ const QString sum_cs = deployments.isEmpty() ? cur::symbol() : currency_symbol(deployments.first().broker_id);
+ const bool show_live = (live_count > 0);
+ const double shown = show_live ? live_pnl : paper_pnl;
+ total_pnl_->setText(QString("%1%2%3").arg(shown >= 0 ? "+" : "-", sum_cs).arg(std::abs(shown), 0, 'f', 2));
+ total_pnl_->setToolTip(tr("Live: %1%2%3 Paper: %4%5%6")
+ .arg(live_pnl >= 0 ? "+" : "-", sum_cs)
+ .arg(std::abs(live_pnl), 0, 'f', 2)
+ .arg(paper_pnl >= 0 ? "+" : "-", sum_cs)
+ .arg(std::abs(paper_pnl), 0, 'f', 2));
+ if (total_pnl_caption_)
+ total_pnl_caption_->setText(show_live ? tr("TOTAL P&L (LIVE)") : tr("TOTAL P&L (PAPER)"));
+ total_pnl_->setStyleSheet(QString("color: %1; font-size: %2px; font-weight: 700; %3"
+ " background: transparent; border: none;")
+ .arg(shown >= 0 ? fincept::ui::colors::POSITIVE()
+ : fincept::ui::colors::NEGATIVE())
+ .arg(fincept::ui::fonts::TITLE)
+ .arg(kMonoFont()));
}
if (total_trades_)
@@ -505,6 +571,7 @@ void DeploymentDashboard::build_ui() {
.arg(fincept::ui::fonts::TINY)
.arg(kMonoFont())
.arg(fincept::ui::colors::BG_HOVER(), fincept::ui::colors::TEXT_PRIMARY()));
+ refresh_btn_->setAccessibleName(tr("Refresh deployment list"));
connect(refresh_btn_, &QPushButton::clicked, this, []() { algo_ns::AlgoEngine::instance().list_deployments(); });
control_bar->addWidget(refresh_btn_);
@@ -521,7 +588,38 @@ void DeploymentDashboard::build_ui() {
.arg(fincept::ui::fonts::TINY)
.arg(kMonoFont())
.arg(fincept::ui::colors::TEXT_PRIMARY()));
- connect(stop_all_btn_, &QPushButton::clicked, this, []() {
+ stop_all_btn_->setAccessibleName(tr("Stop all running deployments"));
+ connect(stop_all_btn_, &QPushButton::clicked, this, [this]() {
+ // Count what is actually at risk so the prompt is concrete, and never
+ // fire a blanket kill without confirmation.
+ // card_order_ entries are "<deployment id>|<status>" (see on_deployments_loaded).
+ int running = 0;
+ int live_running = 0;
+ for (const QString& sig : card_order_) {
+ const QString status = sig.section(QLatin1Char('|'), 1, 1);
+ if (status != QLatin1String("running") && status != QLatin1String("starting"))
+ continue;
+ ++running;
+ const auto it = cards_.constFind(sig.section(QLatin1Char('|'), 0, 0));
+ if (it != cards_.constEnd() && it.value().mode == QLatin1String("live"))
+ ++live_running;
+ }
+ if (running == 0) {
+ QMessageBox::information(this, tr("Stop all"), tr("No deployments are running."));
+ return;
+ }
+ const QString body =
+ live_running > 0
+ ? tr("Stop ALL %1 deployment(s), including %2 LIVE one(s)?\n\n"
+ "Open positions are NOT closed — flatten them yourself in Equity Trading.")
+ .arg(running)
+ .arg(live_running)
+ : tr("Stop ALL %1 deployment(s)?").arg(running);
+ const auto ans =
+ QMessageBox::question(this, tr("Stop all"), body, QMessageBox::Yes | QMessageBox::Cancel,
+ QMessageBox::Cancel);
+ if (ans != QMessageBox::Yes)
+ return;
algo_ns::AlgoEngine::instance().stop_all();
LOG_INFO("AlgoTrading", "Stop all deployments requested");
});
@@ -707,17 +805,46 @@ void DeploymentDashboard::on_live_update(const QString& deployment_id, const fin
}
void DeploymentDashboard::refresh_ages() {
+ // A card that keeps saying RUNNING while its snapshots stopped arriving is
+ // the worst kind of lie on this screen: the user believes the strategy is
+ // watching the market when the runner may be dead or the feed disconnected.
+ // Past kStaleSecs the age line turns amber, past kDeadSecs it turns red and
+ // says so explicitly.
+ constexpr int kStaleSecs = 30;
+ constexpr int kDeadSecs = 120;
+
const int64_t now = QDateTime::currentMSecsSinceEpoch();
for (auto it = cards_.begin(); it != cards_.end(); ++it) {
CardHandles& h = it.value();
if (!h.updated)
continue;
- if (h.last_update_ms <= 0) {
- h.updated->setText(tr("waiting for data…"));
- continue;
+
+ QString text;
+ QString color = fincept::ui::colors::TEXT_TERTIARY();
+ if (h.stop_pending) {
+ text = tr("stop requested — waiting for the engine to confirm…");
+ color = fincept::ui::colors::WARNING();
+ } else if (h.last_update_ms <= 0) {
+ text = tr("waiting for data…");
+ } else {
+ const int secs = static_cast<int>((now - h.last_update_ms) / 1000);
+ text = secs <= 1 ? tr("updated just now") : tr("updated %1s ago").arg(secs);
+ if (secs >= kDeadSecs) {
+ text = tr("NO DATA FOR %1s — this deployment may not be running. Verify at your broker.").arg(secs);
+ color = fincept::ui::colors::NEGATIVE();
+ } else if (secs >= kStaleSecs) {
+ text = tr("stale — last update %1s ago").arg(secs);
+ color = fincept::ui::colors::WARNING();
+ }
}
- const int secs = static_cast<int>((now - h.last_update_ms) / 1000);
- h.updated->setText(secs <= 1 ? tr("updated just now") : tr("updated %1s ago").arg(secs));
+
+ h.updated->setText(text);
+ const QString ss = QString("color: %1; font-size: %2px; %3 background: transparent; border: none;")
+ .arg(color)
+ .arg(fincept::ui::fonts::TINY)
+ .arg(kMonoFont());
+ if (h.updated->styleSheet() != ss)
+ h.updated->setStyleSheet(ss); // P7: only reparse when the state actually changed
}
}
diff --git a/fincept-qt/src/screens/algo_trading/DeploymentDashboard.h b/fincept-qt/src/screens/algo_trading/DeploymentDashboard.h
index 0097982be..f27db97f4 100644
--- a/fincept-qt/src/screens/algo_trading/DeploymentDashboard.h
+++ b/fincept-qt/src/screens/algo_trading/DeploymentDashboard.h
@@ -6,9 +6,11 @@
#include <QEvent>
#include <QFrame>
#include <QHash>
+#include <QHideEvent>
#include <QLabel>
#include <QProgressBar>
#include <QPushButton>
+#include <QShowEvent>
#include <QStringList>
#include <QTimer>
#include <QVBoxLayout>
@@ -24,6 +26,9 @@ class DeploymentDashboard : public QWidget {
protected:
void changeEvent(QEvent* event) override;
+ // P3: the 1s "updated Ns ago" ticker must not run while the tab is hidden.
+ void showEvent(QShowEvent* event) override;
+ void hideEvent(QHideEvent* event) override;
private slots:
void on_deployments_loaded(QVector<fincept::services::algo::AlgoDeployment> deployments);
@@ -52,6 +57,10 @@ class DeploymentDashboard : public QWidget {
QString mode;
int64_t last_update_ms = 0;
QStringList activity_lines;
+ // Set when the user has confirmed a STOP for this deployment but the
+ // engine hasn't reported "stopped" yet — prevents the card from claiming
+ // RUNNING while a stop is in flight, and blocks double-stop clicks.
+ bool stop_pending = false;
};
QHash<QString, CardHandles> cards_;
QStringList card_order_; // deployment ids currently shown, to detect structure changes
diff --git a/fincept-qt/src/screens/algo_trading/StrategyBuilderPanel.cpp b/fincept-qt/src/screens/algo_trading/StrategyBuilderPanel.cpp
index 97a9bed5b..a2aadd7b4 100644
--- a/fincept-qt/src/screens/algo_trading/StrategyBuilderPanel.cpp
+++ b/fincept-qt/src/screens/algo_trading/StrategyBuilderPanel.cpp
@@ -695,6 +695,22 @@ void StrategyBuilderPanel::on_backtest() {
}
void StrategyBuilderPanel::on_deploy() {
+ // Re-entrancy: exec() and the LTP probe below both run nested event loops, so
+ // a second click would otherwise open a second dialog and deploy twice.
+ if (deploying_)
+ return;
+ deploying_ = true;
+ if (deploy_btn_)
+ deploy_btn_->setEnabled(false);
+ struct DeployGuard {
+ StrategyBuilderPanel* self;
+ ~DeployGuard() {
+ self->deploying_ = false;
+ if (self->deploy_btn_)
+ self->deploy_btn_->setEnabled(true);
+ }
+ } deploy_guard{this};
+
// Guards use a visible dialog/banner: the status label lives in the right-hand
// backtest card, far from the Deploy button, so a silent setText() there reads
// as "Deploy did nothing".
@@ -715,15 +731,19 @@ void StrategyBuilderPanel::on_deploy() {
auto* dialog = new AlgoDeployDialog(strat, this);
dialog->set_symbol(symbol_combo_->currentText()); // carry the builder's symbol in
+ // Seed size/limits from the risk panel BEFORE exec(). Previously these were
+ // stamped onto the result AFTER the dialog closed, so the Quantity and Max
+ // Order Value the user reviewed (and, for live, confirmed) were silently
+ // replaced by the builder's values on the way to the engine.
+ dialog->set_risk_defaults(risk_panel_->quantity(), risk_panel_->max_order_value());
if (instrument_type_combo_ && instrument_type_combo_->currentData().toString() != QLatin1String("equity")) {
dialog->set_fno_context(instrument_type_combo_->currentData().toString(),
underlying_combo_ ? underlying_combo_->currentText() : QString(),
expiry_mode_combo_ ? expiry_mode_combo_->currentData().toString() : QString());
}
if (dialog->exec() == QDialog::Accepted) {
+ // Take the dialog's values verbatim — what the user reviewed is what deploys.
auto deployment = dialog->deployment();
- deployment.quantity = risk_panel_->quantity();
- deployment.max_order_value = risk_panel_->max_order_value();
// Sanity check (non-blocking, bounded): warn if a rule can't fire at the
// current price — e.g. 'crosses_above 280.45' on a stock trading at 1204.
diff --git a/fincept-qt/src/screens/algo_trading/StrategyBuilderPanel.h b/fincept-qt/src/screens/algo_trading/StrategyBuilderPanel.h
index c3847392e..b8659723f 100644
--- a/fincept-qt/src/screens/algo_trading/StrategyBuilderPanel.h
+++ b/fincept-qt/src/screens/algo_trading/StrategyBuilderPanel.h
@@ -118,6 +118,12 @@ class StrategyBuilderPanel : public QWidget {
// Identity of the strategy currently being edited (empty => not yet minted).
QString loaded_strategy_id_;
+ // Re-entrancy guard for on_deploy(). The deploy path opens a modal dialog and
+ // then spins a bounded nested event loop (broker LTP probe), during which a
+ // second click on Deploy would otherwise re-enter and start a second live
+ // deployment of the same strategy.
+ bool deploying_ = false;
+
// Right panel — backtest performance report (KPIs, equity, drawdown, trades)
ui::algo::BacktestReportPanel* report_panel_ = nullptr;
diff --git a/fincept-qt/src/screens/algo_trading/StrategyListPanel.cpp b/fincept-qt/src/screens/algo_trading/StrategyListPanel.cpp
index 8f1ef2853..3e9f53388 100644
--- a/fincept-qt/src/screens/algo_trading/StrategyListPanel.cpp
+++ b/fincept-qt/src/screens/algo_trading/StrategyListPanel.cpp
@@ -27,6 +27,30 @@ namespace fincept::screens {
using namespace fincept::services::algo;
+namespace {
+
+// P7: the four per-row action buttons used to carry an inline setStyleSheet
+// each, so rendering a 50-row page cost 200 CSS parses + 200 repolishes — every
+// keystroke in the search box. The skins are identical per column, so they live
+// on the table's stylesheet as ID selectors and the rows only set objectName.
+QString row_button_qss() {
+ using namespace fincept::ui;
+ auto rule = [](const char* id, const QString& color, const QString& hover) {
+ return QString("QPushButton#%1 { background: transparent; color: %2; border: 1px solid %2;"
+ " font-size: %3px; font-weight: 700; font-family: %4; padding: 1px 8px; }"
+ "QPushButton#%1:hover { background: %5; }")
+ .arg(QLatin1String(id), color)
+ .arg(fonts::TINY)
+ .arg(fonts::DATA_FAMILY(), hover);
+ };
+ return rule("slRowEdit", colors::CYAN(), QStringLiteral("rgba(34,211,238,0.1)")) +
+ rule("slRowBacktest", colors::POSITIVE(), QStringLiteral("rgba(22,163,74,0.1)")) +
+ rule("slRowDeploy", colors::AMBER(), QStringLiteral("rgba(217,119,6,0.1)")) +
+ rule("slRowDelete", colors::NEGATIVE(), QStringLiteral("rgba(220,38,38,0.1)"));
+}
+
+} // namespace
+
// ── Constructor ──────────────────────────────────────────────────────────────
StrategyListPanel::StrategyListPanel(QWidget* parent) : QWidget(parent) {
@@ -152,7 +176,8 @@ void StrategyListPanel::build_ui() {
.arg(colors::BG_BASE(), colors::BG_SURFACE(), colors::TEXT_PRIMARY())
.arg(fonts::SMALL)
.arg(fonts::DATA_FAMILY(), colors::BORDER_DIM(), colors::BG_HOVER(), colors::BG_RAISED(),
- colors::TEXT_TERTIARY()));
+ colors::TEXT_TERTIARY()) +
+ row_button_qss());
root->addWidget(table_, 1);
// ── Pagination bar ───────────────────────────────────────────────────────
@@ -247,27 +272,27 @@ void StrategyListPanel::render_page() {
id_item->setForeground(QColor(colors::TEXT_TERTIARY()));
table_->setItem(row, 3, id_item);
- auto make_btn = [&](const QString& text, const QString& color, const QString& hover, int col, auto handler) {
+ // Skins come from the table-level stylesheet (row_button_qss) — rows only
+ // tag an objectName, so a page render costs zero CSS parses.
+ auto make_btn = [&](const QString& text, const char* obj_name, const QString& a11y, int col, auto handler) {
auto* btn = new QPushButton(text, table_);
+ btn->setObjectName(QLatin1String(obj_name));
btn->setCursor(Qt::PointingHandCursor);
btn->setFixedHeight(22);
- btn->setStyleSheet(QString("QPushButton { background: transparent; color: %1; border: 1px solid %1;"
- " font-size: %2px; font-weight: 700; font-family: %3; padding: 1px 8px; }"
- "QPushButton:hover { background: %4; }")
- .arg(color)
- .arg(fonts::TINY)
- .arg(fonts::DATA_FAMILY())
- .arg(hover));
+ btn->setAccessibleName(a11y);
connect(btn, &QPushButton::clicked, this, handler);
table_->setCellWidget(row, col, btn);
};
// Col 4: EDIT (Builder). 5: BACKTEST. 6: DEPLOY. 7: DELETE.
- make_btn(tr("EDIT"), colors::CYAN(), "rgba(34,211,238,0.1)", 4, [this, row]() { on_edit_clicked(row); });
- make_btn(tr("BACKTEST"), colors::POSITIVE(), "rgba(22,163,74,0.1)", 5,
+ make_btn(tr("EDIT"), "slRowEdit", tr("Edit strategy %1").arg(s.name), 4,
+ [this, row]() { on_edit_clicked(row); });
+ make_btn(tr("BACKTEST"), "slRowBacktest", tr("Backtest strategy %1").arg(s.name), 5,
[this, row]() { on_backtest_clicked(row); });
- make_btn(tr("DEPLOY"), colors::AMBER(), "rgba(217,119,6,0.1)", 6, [this, row]() { on_deploy_clicked(row); });
- make_btn(tr("DELETE"), colors::NEGATIVE(), "rgba(220,38,38,0.1)", 7, [this, row]() { on_delete_clicked(row); });
+ make_btn(tr("DEPLOY"), "slRowDeploy", tr("Deploy strategy %1").arg(s.name), 6,
+ [this, row]() { on_deploy_clicked(row); });
+ make_btn(tr("DELETE"), "slRowDelete", tr("Delete strategy %1").arg(s.name), 7,
+ [this, row]() { on_delete_clicked(row); });
}
update_pagination_controls();
@@ -292,6 +317,21 @@ void StrategyListPanel::go_to_page(int page) {
// ── Filter + sort ─────────────────────────────────────────────────────────────
+void StrategyListPanel::apply_sort() {
+ const int index = sort_combo_ ? sort_combo_->currentIndex() : 0;
+ if (index == 1) { // Name Z→A
+ std::sort(filtered_.begin(), filtered_.end(),
+ [](const AlgoStrategy& a, const AlgoStrategy& b) { return a.name > b.name; });
+ } else if (index == 2) { // Category, then name
+ std::sort(filtered_.begin(), filtered_.end(), [](const AlgoStrategy& a, const AlgoStrategy& b) {
+ return a.description < b.description || (a.description == b.description && a.name < b.name);
+ });
+ } else { // Name A→Z (default)
+ std::sort(filtered_.begin(), filtered_.end(),
+ [](const AlgoStrategy& a, const AlgoStrategy& b) { return a.name < b.name; });
+ }
+}
+
void StrategyListPanel::on_filter_changed(const QString&) {
const QString text = search_edit_->text().trimmed().toLower();
const QString cat = cat_combo_->currentIndex() == 0 ? QString() : cat_combo_->currentText();
@@ -306,22 +346,17 @@ void StrategyListPanel::on_filter_changed(const QString&) {
filtered_.append(s);
}
+ // Re-apply the active sort: filtering rebuilt `filtered_` in load order, so
+ // without this the SORT selector silently reverted to "as loaded" on every
+ // keystroke in the search box.
+ apply_sort();
+
current_page_ = 0;
render_page();
}
-void StrategyListPanel::on_sort_changed(int index) {
- if (index == 0) { // Name A→Z
- std::sort(filtered_.begin(), filtered_.end(),
- [](const AlgoStrategy& a, const AlgoStrategy& b) { return a.name < b.name; });
- } else if (index == 1) { // Name Z→A
- std::sort(filtered_.begin(), filtered_.end(),
- [](const AlgoStrategy& a, const AlgoStrategy& b) { return a.name > b.name; });
- } else if (index == 2) { // Category
- std::sort(filtered_.begin(), filtered_.end(), [](const AlgoStrategy& a, const AlgoStrategy& b) {
- return a.description < b.description || (a.description == b.description && a.name < b.name);
- });
- }
+void StrategyListPanel::on_sort_changed(int) {
+ apply_sort();
current_page_ = 0;
render_page();
}
@@ -350,12 +385,9 @@ void StrategyListPanel::on_strategies_loaded(QVector<AlgoStrategy> strategies) {
}
cat_combo_->blockSignals(false);
- // Reset filtered to full list, sort by name
- filtered_ = strategies_;
- std::sort(filtered_.begin(), filtered_.end(),
- [](const AlgoStrategy& a, const AlgoStrategy& b) { return a.name < b.name; });
- current_page_ = 0;
- render_page();
+ // Re-apply the live search/category filter and the active sort so a background
+ // reload doesn't silently reset what the user is looking at.
+ on_filter_changed(search_edit_->text());
LOG_INFO("AlgoTrading", QString("Loaded %1 strategies").arg(strategies_.size()));
}
diff --git a/fincept-qt/src/screens/algo_trading/StrategyListPanel.h b/fincept-qt/src/screens/algo_trading/StrategyListPanel.h
index 7d75d31d0..d088e6a34 100644
--- a/fincept-qt/src/screens/algo_trading/StrategyListPanel.h
+++ b/fincept-qt/src/screens/algo_trading/StrategyListPanel.h
@@ -45,6 +45,9 @@ class StrategyListPanel : public QWidget {
void connect_service();
void render_page();
void update_pagination_controls();
+ /// Sort `filtered_` by the sort combo's current selection. Called after every
+ /// rebuild of `filtered_` so the sort survives search/category changes.
+ void apply_sort();
void retranslateUi();
static constexpr int kPageSize = 50;
diff --git a/fincept-qt/src/screens/algo_trading/UniverseScannerPanel.cpp b/fincept-qt/src/screens/algo_trading/UniverseScannerPanel.cpp
index 80bed9f02..92e57f108 100644
--- a/fincept-qt/src/screens/algo_trading/UniverseScannerPanel.cpp
+++ b/fincept-qt/src/screens/algo_trading/UniverseScannerPanel.cpp
@@ -201,7 +201,16 @@ void UniverseScannerPanel::build_ui() {
.arg(fincept::ui::fonts::DATA_FAMILY)
.arg(fincept::ui::colors::TEXT_PRIMARY())
.arg(fincept::ui::colors::BG_RAISED())
- .arg(fincept::ui::colors::TEXT_TERTIARY()));
+ .arg(fincept::ui::colors::TEXT_TERTIARY()) +
+ // P7: per-row DEPLOY skin hoisted here so on_match()
+ // doesn't reparse a stylesheet for every live match.
+ QString("QPushButton#usRowDeploy { background: transparent; color: %1;"
+ " border: 1px solid %2; font-size: %3px; %4 padding: 2px 8px; }"
+ "QPushButton#usRowDeploy:hover { color: %5; border-color: %5; }")
+ .arg(fincept::ui::colors::TEXT_SECONDARY(), fincept::ui::colors::BORDER_DIM())
+ .arg(fincept::ui::fonts::TINY)
+ .arg(uMono())
+ .arg(fincept::ui::colors::POSITIVE()));
vl->addWidget(matches_table_);
vl->addStretch();
@@ -323,6 +332,13 @@ void UniverseScannerPanel::on_match(const QString& watch_id, const QString& symb
if (watch_id != watch_id_ || watch_id_.isEmpty())
return;
+ // A universe scan can run for hours across thousands of symbols; without a
+ // cap the table (and its per-row DEPLOY widgets) grows without bound and the
+ // panel eventually stalls. Keep the most recent kMaxMatchRows.
+ constexpr int kMaxMatchRows = 500;
+ while (matches_table_->rowCount() >= kMaxMatchRows)
+ matches_table_->removeRow(0);
+
const int row = matches_table_->rowCount();
matches_table_->insertRow(row);
@@ -348,14 +364,9 @@ void UniverseScannerPanel::on_match(const QString& watch_id, const QString& symb
matches_table_->setItem(row, 3, new QTableWidgetItem(detail));
auto* deploy_btn = new QPushButton(tr("DEPLOY"), matches_table_);
+ deploy_btn->setObjectName(QStringLiteral("usRowDeploy"));
deploy_btn->setCursor(Qt::PointingHandCursor);
- deploy_btn->setStyleSheet(QString("QPushButton { background: transparent; color: %1;"
- " border: 1px solid %2; font-size: %3px; %4 padding: 2px 8px; }"
- "QPushButton:hover { color: %5; border-color: %5; }")
- .arg(fincept::ui::colors::TEXT_SECONDARY(), fincept::ui::colors::BORDER_DIM())
- .arg(fincept::ui::fonts::TINY)
- .arg(uMono())
- .arg(fincept::ui::colors::POSITIVE()));
+ deploy_btn->setAccessibleName(tr("Deploy the selected strategy on %1").arg(symbol));
connect(deploy_btn, &QPushButton::clicked, this, [this, symbol]() { deploy_symbol(symbol); });
matches_table_->setCellWidget(row, 4, deploy_btn);
diff --git a/fincept-qt/src/screens/alpha_arena/AlphaArenaScreen.cpp b/fincept-qt/src/screens/alpha_arena/AlphaArenaScreen.cpp
index 0c46c9215..9ed8c9670 100644
--- a/fincept-qt/src/screens/alpha_arena/AlphaArenaScreen.cpp
+++ b/fincept-qt/src/screens/alpha_arena/AlphaArenaScreen.cpp
@@ -101,7 +101,18 @@ QWidget* AlphaArenaScreen::build_header() {
QMessageBox::warning(this, tr("Alpha Arena"), QString::fromStdString(r.error()));
});
force_btn_ = new QPushButton(tr("⚡ FORCE ROUND"));
- connect(force_btn_, &QPushButton::clicked, this, []() { ArenaEngine::instance().force_round(); });
+ connect(force_btn_, &QPushButton::clicked, this, [this]() {
+ // Forcing a round makes every agent decide and trade immediately. In
+ // paper mode that is free; in live mode it is an out-of-band real order
+ // burst, so confirm. KILL ALL already confirms for the same reason.
+ if (live_mode_ &&
+ QMessageBox::warning(this, tr("Alpha Arena — LIVE"),
+ tr("Force an immediate trading round?\n\nThis competition is LIVE — every active "
+ "agent will place real orders now."),
+ QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes)
+ return;
+ ArenaEngine::instance().force_round();
+ });
kill_btn_ = new QPushButton(tr("✖ KILL ALL"));
kill_btn_->setStyleSheet("background:#C72020;color:#FFF;font-weight:700;");
connect(kill_btn_, &QPushButton::clicked, this, [this]() {
@@ -327,14 +338,42 @@ void AlphaArenaScreen::maybe_offer_crash_recovery() {
const QStringList ids = eng.pending_crash_recoveries();
if (ids.isEmpty() || !eng.active_competition_id().isEmpty())
return;
+ // Resuming restarts real order flow if the recovered competition was in live
+ // mode. The generic "Resume the most recent one?" prompt never said so —
+ // a Yes could put real funds back to work without the word LIVE appearing.
+ // Name the competition and, when it is live, demand an explicit Yes on a
+ // warning-styled prompt that defaults to No.
+ const QString resume_id = ids.first();
+ QString resume_name = resume_id.left(8);
+ bool resume_is_live = false;
+ if (auto c = ArenaStore::instance().competition(resume_id); c.is_ok()) {
+ resume_name = c.value().name;
+ resume_is_live = c.value().live_mode;
+ }
+
prompt_open = true;
- const auto pick = QMessageBox::question(
- this, tr("Alpha Arena — Crash Recovery"),
- tr("The previous session left %1 competition(s) running.\nResume the most recent one?").arg(ids.size()));
+ QMessageBox::StandardButton pick;
+ if (resume_is_live) {
+ pick = QMessageBox::warning(
+ this, tr("Alpha Arena — Resume LIVE Competition"),
+ tr("\"%1\" was running in LIVE mode on Hyperliquid with real funds.\n\n"
+ "Resuming restarts automated order placement immediately — agents may open, "
+ "close and reverse real positions without further prompts.\n\n"
+ "Resume live trading now?")
+ .arg(resume_name),
+ QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
+ } else {
+ pick = QMessageBox::question(
+ this, tr("Alpha Arena — Crash Recovery"),
+ tr("The previous session left %1 competition(s) running.\nResume \"%2\" (paper mode)?")
+ .arg(ids.size())
+ .arg(resume_name),
+ QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
+ }
prompt_open = false;
if (pick == QMessageBox::Yes) {
- if (auto r = eng.start(ids.first()); r.is_ok())
- show_competition(ids.first());
+ if (auto r = eng.start(resume_id); r.is_ok())
+ show_competition(resume_id);
} else {
for (const auto& id : ids)
eng.dismiss_crash_recovery(id);
@@ -356,15 +395,20 @@ void AlphaArenaScreen::reload_competitions() {
void AlphaArenaScreen::show_competition(const QString& id) {
if (id.isEmpty()) {
+ live_mode_ = false;
body_->setCurrentIndex(0);
return;
}
competition_id_ = id;
auto comp = ArenaStore::instance().competition(id);
if (comp.is_err()) {
+ live_mode_ = false;
body_->setCurrentIndex(0);
return;
}
+ // Cached so header actions (FORCE ROUND) can gate on real-money mode
+ // without a store round-trip on every click.
+ live_mode_ = comp.value().live_mode;
body_->setCurrentIndex(1);
grid_->set_competition(id, comp.value().live_mode);
disclaimer_->setVisible(comp.value().live_mode);
diff --git a/fincept-qt/src/screens/alpha_arena/AlphaArenaScreen.h b/fincept-qt/src/screens/alpha_arena/AlphaArenaScreen.h
index 35ffea0ed..6c64aebb5 100644
--- a/fincept-qt/src/screens/alpha_arena/AlphaArenaScreen.h
+++ b/fincept-qt/src/screens/alpha_arena/AlphaArenaScreen.h
@@ -65,6 +65,9 @@ class AlphaArenaScreen : public QWidget, public IStatefulScreen {
QHash<QString, qint64> tokens_cache_;
QHash<QString, double> last_mids_; // previously displayed mids (ticker arrows)
double cap_ = 0;
+ // live_mode of the competition currently on screen — gates the extra
+ // confirmation on header actions that trigger real order flow.
+ bool live_mode_ = false;
// Header
QLabel* venue_badge_ = nullptr;
QLabel* status_badge_ = nullptr;
diff --git a/fincept-qt/src/screens/alpha_arena/LeaderboardCards.cpp b/fincept-qt/src/screens/alpha_arena/LeaderboardCards.cpp
index 9d8dfc142..0eedb7264 100644
--- a/fincept-qt/src/screens/alpha_arena/LeaderboardCards.cpp
+++ b/fincept-qt/src/screens/alpha_arena/LeaderboardCards.cpp
@@ -21,15 +21,19 @@ QTableWidgetItem* cell(const QString& text, const QColor& fg, Qt::Alignment alig
return it;
}
-QPushButton* icon_btn(const QString& glyph, const QString& tip, const QString& color) {
+// `kind` selects the colour via a dynamic-property rule in the table-level
+// stylesheet. rebuild() runs on every marks tick (~1 Hz) for every agent, so a
+// per-button setStyleSheet() meant N*2 full CSS re-parses per tick; the rules
+// now live in one stylesheet set once in the constructor.
+QPushButton* icon_btn(const QString& glyph, const QString& tip, const char* kind) {
auto* b = new QPushButton(glyph);
b->setToolTip(tip);
+ b->setAccessibleName(tip);
b->setCursor(Qt::PointingHandCursor);
b->setFixedSize(20, 18);
b->setFlat(true);
- b->setStyleSheet(QStringLiteral("QPushButton{background:transparent;border:none;color:%1;font-size:11px;padding:0;}"
- "QPushButton:hover{background:#2A2A2A;}")
- .arg(color));
+ b->setObjectName(QStringLiteral("arenaActBtn"));
+ b->setProperty("act", QString::fromLatin1(kind));
return b;
}
@@ -54,11 +58,20 @@ LeaderboardCards::LeaderboardCards(QWidget* parent) : QWidget(parent) {
table_->setFocusPolicy(Qt::NoFocus);
table_->setShowGrid(false);
table_->setSortingEnabled(false); // caller order = rank (sorted by equity)
+ // Includes the ACT cell-widget rules — cell widgets are descendants of the
+ // table, so this one stylesheet covers every row's buttons and container.
table_->setStyleSheet("QTableWidget{background:#0D0D0D;border:none;font-size:11px;"
" font-family:'Consolas','Courier New',monospace;}"
"QTableWidget::item{padding:0 6px;border-bottom:1px solid #1C1C1C;}"
"QHeaderView::section{background:#141414;color:#777;border:none;"
- " border-bottom:1px solid #2A2A2A;padding:2px 6px;font-size:10px;font-weight:700;}");
+ " border-bottom:1px solid #2A2A2A;padding:2px 6px;font-size:10px;font-weight:700;}"
+ "QWidget#arenaAct{background:#0D0D0D;}"
+ "QWidget#arenaAct[sel=\"true\"]{background:#1F1A10;}"
+ "QPushButton#arenaActBtn{background:transparent;border:none;font-size:11px;padding:0;}"
+ "QPushButton#arenaActBtn:hover{background:#2A2A2A;}"
+ "QPushButton#arenaActBtn[act=\"halt\"]{color:#E0A800;}"
+ "QPushButton#arenaActBtn[act=\"resume\"]{color:#26A65B;}"
+ "QPushButton#arenaActBtn[act=\"kill\"]{color:#E0245E;}");
auto* hh = table_->horizontalHeader();
hh->setSectionResizeMode(QHeaderView::ResizeToContents);
hh->setSectionResizeMode(ColModel, QHeaderView::Stretch);
@@ -132,13 +145,14 @@ void LeaderboardCards::rebuild() {
// refresh the dashboard, which calls set_data → rebuild and would
// delete the clicked button under its own clicked() handler.
auto* act = new QWidget;
- act->setStyleSheet(QStringLiteral("background:%1;").arg(bg.name()));
+ act->setObjectName(QStringLiteral("arenaAct"));
+ act->setProperty("sel", selected);
auto* h = new QHBoxLayout(act);
h->setContentsMargins(2, 0, 2, 0);
h->setSpacing(2);
const QString id = d.agent_id;
auto* toggle = icon_btn(active ? QStringLiteral("⏸") : QStringLiteral("▶"),
- active ? tr("Halt agent") : tr("Resume agent"), active ? "#E0A800" : "#26A65B");
+ active ? tr("Halt agent") : tr("Resume agent"), active ? "halt" : "resume");
connect(toggle, &QPushButton::clicked, this, [this, id, active]() {
QMetaObject::invokeMethod(
this,
@@ -150,7 +164,7 @@ void LeaderboardCards::rebuild() {
},
Qt::QueuedConnection);
});
- auto* kill = icon_btn(QStringLiteral("✖"), tr("Close positions & halt (kill)"), "#E0245E");
+ auto* kill = icon_btn(QStringLiteral("✖"), tr("Close positions & halt (kill)"), "kill");
connect(kill, &QPushButton::clicked, this, [this, id]() {
QMetaObject::invokeMethod(this, [this, id]() { emit kill_requested(id); }, Qt::QueuedConnection);
});
diff --git a/fincept-qt/src/screens/alt_investments/AltInvestmentsScreen_Analysis.cpp b/fincept-qt/src/screens/alt_investments/AltInvestmentsScreen_Analysis.cpp
index dd259d7ed..253dda675 100644
--- a/fincept-qt/src/screens/alt_investments/AltInvestmentsScreen_Analysis.cpp
+++ b/fincept-qt/src/screens/alt_investments/AltInvestmentsScreen_Analysis.cpp
@@ -540,11 +540,15 @@ QJsonObject AltInvestmentsScreen::collect_form_data() const {
} else {
if (auto* sp = qobject_cast<QDoubleSpinBox*>(w)) {
double val = sp->value();
+ // Scale and percent-conversion are independent concerns: a field
+ // can legitimately be entered in billions *and* be a rate. The
+ // old else-if chain silently dropped divide_100 whenever a
+ // B/M suffix was present.
if (f.suffix == "B")
val *= 1e9;
else if (f.suffix == "M")
val *= 1e6;
- else if (f.divide_100)
+ if (f.divide_100)
val /= 100.0;
form[f.key] = val;
}
@@ -632,10 +636,17 @@ void AltInvestmentsScreen::display_verdict(const QJsonObject& result, const QStr
QString badge_color, badge_bg;
const QString lcat = category.toLower();
- if (lcat.contains("good") || lcat.contains("ok")) {
+ // Short verdict tokens are matched as WHOLE WORDS. Substring matching made
+ // "ok" fire on any category containing those two letters — "token",
+ // "broker", "lookback", "stockholder" — painting an unrated result green as
+ // if the analyzer had approved it. Long unambiguous words stay substring
+ // matches so "flawed"/"cautionary" still hit.
+ const QStringList words = lcat.split(QRegularExpression(R"([^a-z]+)"), Qt::SkipEmptyParts);
+ auto has_word = [&words](const char* w) { return words.contains(QLatin1String(w)); };
+ if (has_word("good") || has_word("ok") || has_word("okay")) {
badge_color = colors::POSITIVE();
badge_bg = "rgba(22,163,74,0.15)";
- } else if (lcat.contains("ugly") || lcat.contains("bad") || lcat.contains("avoid")) {
+ } else if (has_word("ugly") || has_word("bad") || lcat.contains("avoid")) {
badge_color = colors::NEGATIVE();
badge_bg = "rgba(220,38,38,0.15)";
} else if (lcat.contains("flaw") || lcat.contains("warn") || lcat.contains("caution")) {
diff --git a/fincept-qt/src/screens/alt_investments/AltInvestmentsScreen_Layout.cpp b/fincept-qt/src/screens/alt_investments/AltInvestmentsScreen_Layout.cpp
index b7bd4fcfd..a73b8a85a 100644
--- a/fincept-qt/src/screens/alt_investments/AltInvestmentsScreen_Layout.cpp
+++ b/fincept-qt/src/screens/alt_investments/AltInvestmentsScreen_Layout.cpp
@@ -150,6 +150,7 @@ QWidget* AltInvestmentsScreen::create_center_panel() {
combo_label_->setObjectName("altComboLabel");
analyzer_combo_ = new QComboBox;
analyzer_combo_->setFixedWidth(210);
+ analyzer_combo_->setAccessibleName(tr("Analyzer"));
connect(analyzer_combo_, QOverload<int>::of(&QComboBox::currentIndexChanged), this,
&AltInvestmentsScreen::on_analyzer_changed);
combo_col->addWidget(combo_label_);
@@ -175,6 +176,7 @@ QWidget* AltInvestmentsScreen::create_center_panel() {
analyze_btn_->setObjectName("altAnalyzeBtn");
analyze_btn_->setCursor(Qt::PointingHandCursor);
analyze_btn_->setFixedHeight(26);
+ analyze_btn_->setAccessibleName(tr("Run the selected analyzer"));
connect(analyze_btn_, &QPushButton::clicked, this, &AltInvestmentsScreen::on_analyze);
fhl->addWidget(form_title_);
fhl->addStretch(1);
diff --git a/fincept-qt/src/screens/auth/ForgotPasswordScreen.cpp b/fincept-qt/src/screens/auth/ForgotPasswordScreen.cpp
index 061e421c8..2f7664a27 100644
--- a/fincept-qt/src/screens/auth/ForgotPasswordScreen.cpp
+++ b/fincept-qt/src/screens/auth/ForgotPasswordScreen.cpp
@@ -125,6 +125,10 @@ ForgotPasswordScreen::ForgotPasswordScreen(QWidget* parent) : QWidget(parent) {
confirm_password_->setEchoMode(QLineEdit::Password);
if (error_label_)
error_label_->hide();
+ if (reset_error_)
+ reset_error_->hide();
+ if (reset_btn_)
+ reset_btn_->setEnabled(true);
pages_->setCurrentIndex(3);
});
connect(&auth, &auth::AuthManager::password_reset_failed, this, [this](const QString& err) {
@@ -137,6 +141,28 @@ ForgotPasswordScreen::ForgotPasswordScreen(QWidget* parent) : QWidget(parent) {
void ForgotPasswordScreen::hideEvent(QHideEvent* event) {
QWidget::hideEvent(event);
+
+ // Only wipe on real in-app navigation — a minimise must not throw away a
+ // reset code the user is halfway through typing.
+ if (event && event->spontaneous())
+ return;
+
+ for (QLineEdit* w : {email_input_, otp_input_, new_password_, confirm_password_}) {
+ if (w)
+ w->clear();
+ }
+ if (new_password_)
+ new_password_->setEchoMode(QLineEdit::Password);
+ if (confirm_password_)
+ confirm_password_->setEchoMode(QLineEdit::Password);
+ if (error_label_)
+ error_label_->hide();
+ if (reset_error_)
+ reset_error_->hide();
+ if (sent_status_)
+ sent_status_->clear();
+ if (pages_)
+ pages_->setCurrentIndex(0);
}
void ForgotPasswordScreen::changeEvent(QEvent* event) {
@@ -234,6 +260,15 @@ void ForgotPasswordScreen::build_email_page() {
vl->addWidget(back_login_btn_, 0, Qt::AlignCenter);
vl->addStretch();
+
+ email_input_->setMaxLength(254); // RFC 5321 maximum
+ email_input_->setAccessibleName(tr("Email address"));
+ send_btn_->setAccessibleName(tr("Send verification code"));
+ back_login_btn_->setAccessibleName(tr("Back to sign in"));
+ error_label_->setAccessibleName(tr("Password reset error"));
+ setTabOrder(email_input_, send_btn_);
+ setTabOrder(send_btn_, back_login_btn_);
+
pages_->addWidget(page);
}
@@ -280,7 +315,22 @@ void ForgotPasswordScreen::build_otp_sent_page() {
connect(sent_resend_btn_, &QPushButton::clicked, this, &ForgotPasswordScreen::on_resend);
vl->addWidget(sent_resend_btn_, 0, Qt::AlignCenter);
+ // Resend previously gave no acknowledgement at all — the user had no way to
+ // know whether the click registered.
+ sent_status_ = new QLabel;
+ sent_status_->setWordWrap(true);
+ sent_status_->setAlignment(Qt::AlignCenter);
+ sent_status_->setStyleSheet(QString("color: %1; font-size: 12px; background: transparent;"
+ "font-family: 'Consolas','Courier New',monospace;")
+ .arg(ui::colors::POSITIVE()));
+ vl->addWidget(sent_status_);
+
vl->addStretch();
+
+ sent_continue_btn_->setAccessibleName(tr("I have the code"));
+ sent_resend_btn_->setAccessibleName(tr("Resend the verification code"));
+ setTabOrder(sent_continue_btn_, sent_resend_btn_);
+
pages_->addWidget(page);
}
@@ -328,18 +378,22 @@ void ForgotPasswordScreen::build_reset_page() {
new_password_ = add_field(reset_new_lbl_, true);
confirm_password_ = add_field(reset_confirm_lbl_, true);
- auto* err = new QLabel;
- err->setWordWrap(true);
- err->setStyleSheet(QString("color: %1; font-size: 13px;"
- "background: rgba(220,38,38,0.08);"
- "border: 1px solid #7f1d1d; padding: 6px 8px;"
- "font-family: 'Consolas','Courier New',monospace;")
- .arg(ui::colors::NEGATIVE()));
- err->hide();
- vl->addWidget(err);
- connect(&auth::AuthManager::instance(), &auth::AuthManager::password_reset_failed, this, [err](const QString& e) {
- err->setText(e);
- err->show();
+ reset_error_ = new QLabel;
+ reset_error_->setWordWrap(true);
+ reset_error_->setStyleSheet(QString("color: %1; font-size: 13px;"
+ "background: rgba(220,38,38,0.08);"
+ "border: 1px solid #7f1d1d; padding: 6px 8px;"
+ "font-family: 'Consolas','Courier New',monospace;")
+ .arg(ui::colors::NEGATIVE()));
+ reset_error_->hide();
+ vl->addWidget(reset_error_);
+ connect(&auth::AuthManager::instance(), &auth::AuthManager::password_reset_failed, this, [this](const QString& e) {
+ if (!reset_error_)
+ return;
+ reset_error_->setText(e);
+ reset_error_->show();
+ if (reset_btn_)
+ reset_btn_->setEnabled(true);
});
reset_btn_ = new QPushButton;
@@ -349,6 +403,25 @@ void ForgotPasswordScreen::build_reset_page() {
vl->addWidget(reset_btn_);
vl->addStretch();
+
+ otp_input_->setMaxLength(12);
+ new_password_->setMaxLength(128);
+ confirm_password_->setMaxLength(128);
+
+ otp_input_->setAccessibleName(tr("Verification code from email"));
+ new_password_->setAccessibleName(tr("New password"));
+ confirm_password_->setAccessibleName(tr("Confirm new password"));
+ reset_btn_->setAccessibleName(tr("Reset password"));
+ reset_error_->setAccessibleName(tr("Password reset error"));
+
+ setTabOrder(otp_input_, new_password_);
+ setTabOrder(new_password_, confirm_password_);
+ setTabOrder(confirm_password_, reset_btn_);
+
+ // Enter submits from any field on this page.
+ for (QLineEdit* w : {otp_input_, new_password_, confirm_password_})
+ connect(w, &QLineEdit::returnPressed, this, &ForgotPasswordScreen::on_reset_password);
+
pages_->addWidget(page);
}
@@ -472,16 +545,51 @@ void ForgotPasswordScreen::on_send_code() {
}
void ForgotPasswordScreen::on_reset_password() {
- QString otp = otp_input_->text().trimmed();
- QString pw = new_password_->text();
- QString cpw = confirm_password_->text();
- if (otp.isEmpty() || pw.length() < 8 || pw != cpw)
+ // Previously every failed precondition was a bare `return`: clicking RESET
+ // PASSWORD with mismatched or short passwords did nothing at all, with no
+ // message, which reads as a broken button.
+ if (!reset_error_)
+ return;
+ reset_error_->hide();
+
+ const QString otp = otp_input_->text().trimmed();
+ const QString pw = new_password_->text();
+ const QString cpw = confirm_password_->text();
+
+ auto fail = [this](const QString& msg, QLineEdit* focus) {
+ reset_error_->setText(msg);
+ reset_error_->show();
+ if (focus)
+ focus->setFocus();
+ };
+
+ if (otp.isEmpty()) {
+ fail(tr("Enter the verification code from your email"), otp_input_);
return;
+ }
+ if (pw.isEmpty()) {
+ fail(tr("Enter a new password"), new_password_);
+ return;
+ }
+ if (pw.length() < 8) {
+ fail(tr("Password must be at least 8 characters"), new_password_);
+ return;
+ }
+ if (pw != cpw) {
+ confirm_password_->clear();
+ fail(tr("Passwords do not match"), confirm_password_);
+ return;
+ }
+
+ reset_btn_->setEnabled(false);
auth::AuthManager::instance().reset_password(email_input_->text().trimmed(), otp, pw);
}
void ForgotPasswordScreen::on_resend() {
- auth::AuthManager::instance().forgot_password(email_input_->text().trimmed());
+ const QString email = email_input_->text().trimmed();
+ auth::AuthManager::instance().forgot_password(email);
+ if (sent_status_)
+ sent_status_->setText(tr("Verification code re-sent to %1").arg(email));
}
} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/auth/ForgotPasswordScreen.h b/fincept-qt/src/screens/auth/ForgotPasswordScreen.h
index 208709008..eeb023ecc 100644
--- a/fincept-qt/src/screens/auth/ForgotPasswordScreen.h
+++ b/fincept-qt/src/screens/auth/ForgotPasswordScreen.h
@@ -39,6 +39,7 @@ class ForgotPasswordScreen : public QWidget {
// OTP-sent page
QLabel* sent_title_ = nullptr;
QLabel* sent_sub_ = nullptr;
+ QLabel* sent_status_ = nullptr; ///< transient "code re-sent" confirmation
QPushButton* sent_continue_btn_ = nullptr;
QPushButton* sent_resend_btn_ = nullptr;
@@ -47,6 +48,7 @@ class ForgotPasswordScreen : public QWidget {
QLabel* reset_code_lbl_ = nullptr;
QLabel* reset_new_lbl_ = nullptr;
QLabel* reset_confirm_lbl_ = nullptr;
+ QLabel* reset_error_ = nullptr; ///< inline validation + server errors
QLineEdit* otp_input_ = nullptr;
QLineEdit* new_password_ = nullptr;
QLineEdit* confirm_password_ = nullptr;
diff --git a/fincept-qt/src/screens/auth/LockScreen.cpp b/fincept-qt/src/screens/auth/LockScreen.cpp
index db6244e87..72b986680 100644
--- a/fincept-qt/src/screens/auth/LockScreen.cpp
+++ b/fincept-qt/src/screens/auth/LockScreen.cpp
@@ -315,6 +315,14 @@ void LockScreen::build_setup_page() {
connect(setup_pin_input_, &QLineEdit::returnPressed, this, [this]() { setup_confirm_input_->setFocus(); });
connect(setup_confirm_input_, &QLineEdit::returnPressed, this, &LockScreen::on_setup_submit);
+ setup_pin_input_->setAccessibleName(tr("New PIN"));
+ setup_pin_input_->setAccessibleDescription(tr("Six digit PIN used to unlock the terminal"));
+ setup_confirm_input_->setAccessibleName(tr("Confirm new PIN"));
+ setup_btn_->setAccessibleName(tr("Set PIN"));
+ setup_error_->setAccessibleName(tr("PIN setup error"));
+ setTabOrder(setup_pin_input_, setup_confirm_input_);
+ setTabOrder(setup_confirm_input_, setup_btn_);
+
pages_->addWidget(page); // index 0
}
@@ -405,20 +413,29 @@ void LockScreen::build_unlock_page() {
// "Forgot PIN?" escape — a forgotten PIN is recoverable by signing in again
// (this clears the PIN). Without this link the only path was to fail the unlock
// kMaxAttempts times through escalating lockouts, which is minutes of dead-end.
- auto* forgot_link = new QPushButton(tr("Forgot PIN? Sign in again"));
- forgot_link->setCursor(Qt::PointingHandCursor);
- forgot_link->setStyleSheet(QString("QPushButton{color:%1; background:transparent; border:none;"
- "font-size:12px; text-decoration:underline;"
- "font-family:'Consolas','Courier New',monospace;}"
- "QPushButton:hover{color:%2;}")
- .arg(ui::colors::TEXT_DIM(), ui::colors::AMBER()));
- connect(forgot_link, &QPushButton::clicked, this, [this]() { emit reauth_requested(); });
- vl->addWidget(forgot_link, 0, Qt::AlignHCenter);
+ unlock_forgot_btn_ = new QPushButton(tr("Forgot PIN? Sign in again"));
+ unlock_forgot_btn_->setCursor(Qt::PointingHandCursor);
+ unlock_forgot_btn_->setStyleSheet(QString("QPushButton{color:%1; background:transparent; border:none;"
+ "font-size:12px; text-decoration:underline;"
+ "font-family:'Consolas','Courier New',monospace;}"
+ "QPushButton:hover{color:%2;}")
+ .arg(ui::colors::TEXT_DIM(), ui::colors::AMBER()));
+ connect(unlock_forgot_btn_, &QPushButton::clicked, this, [this]() { emit reauth_requested(); });
+ vl->addWidget(unlock_forgot_btn_, 0, Qt::AlignHCenter);
vl->addStretch();
connect(unlock_pin_input_, &QLineEdit::returnPressed, this, &LockScreen::on_unlock_submit);
+ unlock_pin_input_->setAccessibleName(tr("Unlock PIN"));
+ unlock_pin_input_->setAccessibleDescription(tr("Six digit PIN that unlocks the terminal"));
+ unlock_btn_->setAccessibleName(tr("Unlock terminal"));
+ unlock_forgot_btn_->setAccessibleName(tr("Forgot PIN, sign in again"));
+ unlock_error_->setAccessibleName(tr("Unlock error"));
+ unlock_lockout_label_->setAccessibleName(tr("Lockout status"));
+ setTabOrder(unlock_pin_input_, unlock_btn_);
+ setTabOrder(unlock_btn_, unlock_forgot_btn_);
+
pages_->addWidget(page); // index 1
}
@@ -471,6 +488,9 @@ void LockScreen::build_lockout_page() {
vl->addStretch();
+ lockout_reauth_btn_->setAccessibleName(tr("Sign in again to reset your PIN"));
+ lockout_msg_->setAccessibleName(tr("Account locked message"));
+
pages_->addWidget(page); // index 2
}
@@ -506,6 +526,8 @@ void LockScreen::retranslateUi() {
unlock_pin_lbl_->setText(tr("PIN"));
if (unlock_btn_)
unlock_btn_->setText(tr(" UNLOCK "));
+ if (unlock_forgot_btn_)
+ unlock_forgot_btn_->setText(tr("Forgot PIN? Sign in again"));
if (lockout_title_)
lockout_title_->setText(tr("ACCOUNT LOCKED"));
@@ -580,6 +602,16 @@ void LockScreen::on_setup_submit() {
const QString pin = setup_pin_input_->text();
const QString confirm = setup_confirm_input_->text();
+ // Length is checked first so an empty/short entry gets a specific message
+ // instead of falling through to PinManager's generic rejection (an empty
+ // PIN also equals an empty confirmation, so the mismatch check misses it).
+ if (pin.length() != 6) {
+ setup_error_->setText(tr("PIN must be exactly 6 digits"));
+ setup_error_->show();
+ setup_pin_input_->setFocus();
+ return;
+ }
+
// Clear BOTH fields on mismatch — see header note about masked-text leak.
if (pin != confirm) {
setup_error_->setText(tr("PINs do not match"));
diff --git a/fincept-qt/src/screens/auth/LockScreen.h b/fincept-qt/src/screens/auth/LockScreen.h
index 2c3220caa..bb3a7783e 100644
--- a/fincept-qt/src/screens/auth/LockScreen.h
+++ b/fincept-qt/src/screens/auth/LockScreen.h
@@ -68,6 +68,10 @@ class LockScreen : public QWidget {
QLabel* unlock_error_ = nullptr;
QLabel* unlock_attempts_ = nullptr;
QLabel* unlock_lockout_label_ = nullptr;
+ /// "Forgot PIN? Sign in again" escape link. Cached so retranslateUi() can
+ /// re-apply its label — it was previously built inline and left in the
+ /// source language after a live language switch.
+ QPushButton* unlock_forgot_btn_ = nullptr;
// Lockout page (index 2)
QLabel* lockout_title_ = nullptr;
diff --git a/fincept-qt/src/screens/auth/LoginScreen.cpp b/fincept-qt/src/screens/auth/LoginScreen.cpp
index e0a7e8f9f..0a3c6c05c 100644
--- a/fincept-qt/src/screens/auth/LoginScreen.cpp
+++ b/fincept-qt/src/screens/auth/LoginScreen.cpp
@@ -220,6 +220,31 @@ LoginScreen::LoginScreen(QWidget* parent) : QWidget(parent) {
void LoginScreen::hideEvent(QHideEvent* event) {
QWidget::hideEvent(event);
+
+ // Spontaneous hides come from the window manager (minimise, workspace
+ // switch, lock). The user has not left the form — wiping their half-typed
+ // password there would be hostile. Only wipe on a real in-app navigation.
+ if (event && event->spontaneous())
+ return;
+
+ // The screen lives in a QStackedWidget for the whole session, so without
+ // this the email/password/MFA code stay resident in the line edits (and
+ // are re-shown verbatim on the next logout → login cycle).
+ if (email_input_)
+ email_input_->clear();
+ if (password_input_) {
+ password_input_->clear();
+ password_input_->setEchoMode(QLineEdit::Password);
+ }
+ if (mfa_input_)
+ mfa_input_->clear();
+ if (show_pw_btn_)
+ show_pw_btn_->setText(tr("SHOW"));
+ clear_error();
+ if (mfa_error_)
+ mfa_error_->hide();
+ if (pages_)
+ pages_->setCurrentIndex(0);
}
void LoginScreen::changeEvent(QEvent* event) {
@@ -400,6 +425,28 @@ void LoginScreen::build_login_page() {
connect(password_input_, &QLineEdit::returnPressed, this, &LoginScreen::on_login);
connect(email_input_, &QLineEdit::returnPressed, this, [this]() { password_input_->setFocus(); });
+ // ── Accessibility + keyboard order ───────────────────────────────────────
+ // Screen readers announce the accessible name; without it every field here
+ // is read as an anonymous "text edit". Tab order is set explicitly because
+ // the show/hide button sits inside a nested row widget, which otherwise
+ // puts it before the password field in the focus chain.
+ email_input_->setAccessibleName(tr("Email address"));
+ email_input_->setAccessibleDescription(tr("The email address of your Fincept account"));
+ password_input_->setAccessibleName(tr("Password"));
+ show_pw_btn_->setAccessibleName(tr("Show or hide password"));
+ login_btn_->setAccessibleName(tr("Sign in"));
+ forgot_btn_->setAccessibleName(tr("Forgot password"));
+ google_btn_->setAccessibleName(tr("Continue with Google"));
+ signup_btn_->setAccessibleName(tr("Create an account"));
+ error_label_->setAccessibleName(tr("Sign-in error"));
+
+ setTabOrder(email_input_, password_input_);
+ setTabOrder(password_input_, show_pw_btn_);
+ setTabOrder(show_pw_btn_, login_btn_);
+ setTabOrder(login_btn_, forgot_btn_);
+ setTabOrder(forgot_btn_, google_btn_);
+ setTabOrder(google_btn_, signup_btn_);
+
pages_->addWidget(page);
}
@@ -486,6 +533,18 @@ void LoginScreen::build_mfa_page() {
vl->addStretch();
connect(mfa_input_, &QLineEdit::returnPressed, this, &LoginScreen::on_mfa_verify);
+
+ // Deliberately no digits-only validator: some accounts use alphanumeric
+ // recovery codes on this same field. The hint helps soft keyboards without
+ // rejecting those.
+ mfa_input_->setInputMethodHints(Qt::ImhSensitiveData | Qt::ImhNoPredictiveText | Qt::ImhNoAutoUppercase);
+ mfa_input_->setAccessibleName(tr("Two-factor verification code"));
+ mfa_verify_btn_->setAccessibleName(tr("Verify code"));
+ mfa_back_btn_->setAccessibleName(tr("Back to sign in"));
+ mfa_error_->setAccessibleName(tr("Verification error"));
+ setTabOrder(mfa_input_, mfa_verify_btn_);
+ setTabOrder(mfa_verify_btn_, mfa_back_btn_);
+
pages_->addWidget(mfa_page_);
}
@@ -543,6 +602,12 @@ void LoginScreen::build_conflict_page() {
vl->addWidget(cancel_btn_);
vl->addStretch();
+
+ force_login_btn_->setAccessibleName(tr("Log out the other session and continue"));
+ cancel_btn_->setAccessibleName(tr("Cancel sign in"));
+ conflict_msg_->setAccessibleName(tr("Session conflict details"));
+ setTabOrder(cancel_btn_, force_login_btn_);
+
pages_->addWidget(conflict_page_);
}
@@ -712,6 +777,12 @@ void LoginScreen::set_loading(bool loading) {
login_btn_->setEnabled(!loading);
email_input_->setEnabled(!loading);
password_input_->setEnabled(!loading);
+ // Navigating away mid-request hides this screen, which wipes the fields
+ // (hideEvent) while the reply is still in flight — lock the exits too.
+ if (forgot_btn_)
+ forgot_btn_->setEnabled(!loading);
+ if (signup_btn_)
+ signup_btn_->setEnabled(!loading);
login_btn_->setText(loading ? tr(" SIGNING IN... ") : tr(" SIGN IN "));
if (google_btn_) {
google_btn_->setEnabled(!loading);
diff --git a/fincept-qt/src/screens/auth/PricingScreen.cpp b/fincept-qt/src/screens/auth/PricingScreen.cpp
index 28a2c4090..1f42f759f 100644
--- a/fincept-qt/src/screens/auth/PricingScreen.cpp
+++ b/fincept-qt/src/screens/auth/PricingScreen.cpp
@@ -3,6 +3,7 @@
#include "auth/AuthApi.h"
#include "auth/AuthManager.h"
#include "core/currency/Currency.h"
+#include "core/logging/Logger.h"
#include "ui/theme/Theme.h"
#include <QApplication>
@@ -10,11 +11,13 @@
#include <QEvent>
#include <QFrame>
#include <QHBoxLayout>
+#include <QHideEvent>
#include <QJsonArray>
#include <QScrollArea>
#include <QUrl>
#include <algorithm>
+#include <memory>
namespace fincept::screens {
@@ -175,11 +178,9 @@ void PricingScreen::showEvent(QShowEvent* event) {
user_info_label_->hide();
// Fetch fresh user data from API, then render once with accurate data
- auth.refresh_user_data();
- auto* conn = new QMetaObject::Connection;
+ auto conn = std::make_shared<QMetaObject::Connection>();
*conn = connect(&auth, &auth::AuthManager::auth_state_changed, this, [this, conn]() {
disconnect(*conn);
- delete conn;
loading_label_->hide();
@@ -197,6 +198,10 @@ void PricingScreen::showEvent(QShowEvent* event) {
fetch_plans();
update_footer();
});
+ // Connect first, then fire — a cached/synchronous reply would otherwise
+ // emit auth_state_changed before we were listening and leave the screen
+ // stuck on "Updating plan status...".
+ auth.refresh_user_data();
} else {
user_info_label_->hide();
fetched_ = false;
@@ -529,12 +534,18 @@ void PricingScreen::on_select_plan(const QString& plan_id) {
awaiting_plan_id_ = plan_id;
pre_payment_plan_ = auth::AuthManager::instance().session().account_type().toLower();
- // Start polling every 5 seconds to detect plan change
+ // Poll for the plan change. The interval used to be 1000ms despite
+ // the "every 5 seconds" intent, and each tick issued a fresh
+ // refresh_user_data() regardless of whether the previous one had
+ // come back — a request storm against the account endpoint.
+ payment_poll_ticks_ = 0;
+ payment_poll_in_flight_ = false;
if (!payment_poll_timer_) {
payment_poll_timer_ = new QTimer(this);
- payment_poll_timer_->setInterval(1000);
+ payment_poll_timer_->setInterval(kPaymentPollIntervalMs);
connect(payment_poll_timer_, &QTimer::timeout, this, &PricingScreen::poll_payment_status);
}
+ payment_poll_timer_->setInterval(kPaymentPollIntervalMs);
payment_poll_timer_->start();
// Also check on focus return for faster detection
@@ -548,17 +559,37 @@ void PricingScreen::on_select_plan(const QString& plan_id) {
});
}
+void PricingScreen::stop_payment_polling() {
+ awaiting_payment_ = false;
+ payment_poll_in_flight_ = false;
+ payment_poll_ticks_ = 0;
+ if (payment_poll_timer_)
+ payment_poll_timer_->stop();
+ if (focus_connection_) {
+ disconnect(focus_connection_);
+ focus_connection_ = {};
+ }
+}
+
void PricingScreen::poll_payment_status() {
if (!awaiting_payment_)
return;
+ // One request at a time — see payment_poll_in_flight_ in the header.
+ if (payment_poll_in_flight_)
+ return;
+ if (++payment_poll_ticks_ > kMaxPaymentPolls) {
+ LOG_INFO("Pricing", "Payment polling gave up after the maximum window");
+ stop_payment_polling();
+ return;
+ }
auto& auth = auth::AuthManager::instance();
- auth.refresh_user_data();
+ payment_poll_in_flight_ = true;
- auto* conn = new QMetaObject::Connection;
+ auto conn = std::make_shared<QMetaObject::Connection>();
*conn = connect(&auth, &auth::AuthManager::auth_state_changed, this, [this, conn]() {
disconnect(*conn);
- delete conn;
+ payment_poll_in_flight_ = false;
auto& mgr = auth::AuthManager::instance();
@@ -574,11 +605,7 @@ void PricingScreen::poll_payment_status() {
if (new_plan != pre_payment_plan_) {
// Plan changed — stop polling, re-render, show confetti
- awaiting_payment_ = false;
- if (payment_poll_timer_)
- payment_poll_timer_->stop();
- if (focus_connection_)
- disconnect(focus_connection_);
+ stop_payment_polling();
fetched_ = false;
fetch_plans();
@@ -588,12 +615,27 @@ void PricingScreen::poll_payment_status() {
confetti_->show_confetti();
}
});
+
+ auth.refresh_user_data();
}
void PricingScreen::on_app_focus_returned() {
poll_payment_status();
}
+void PricingScreen::hideEvent(QHideEvent* event) {
+ QWidget::hideEvent(event);
+ // P3: the poll timer must not survive the screen leaving the stack. It used
+ // to keep firing a network request every second for the rest of the session
+ // if the user navigated away from an abandoned checkout.
+ if (event && event->spontaneous())
+ return;
+ if (awaiting_payment_) {
+ LOG_INFO("Pricing", "Pricing screen hidden — stopping payment polling");
+ stop_payment_polling();
+ }
+}
+
// ── Footer ───────────────────────────────────────────────────────────────────
void PricingScreen::update_footer() {
diff --git a/fincept-qt/src/screens/auth/PricingScreen.h b/fincept-qt/src/screens/auth/PricingScreen.h
index 0cc4f93e6..8afb01e05 100644
--- a/fincept-qt/src/screens/auth/PricingScreen.h
+++ b/fincept-qt/src/screens/auth/PricingScreen.h
@@ -26,6 +26,7 @@ class PricingScreen : public QWidget {
protected:
void showEvent(QShowEvent* event) override;
+ void hideEvent(QHideEvent* event) override;
void changeEvent(QEvent* event) override;
private:
@@ -49,12 +50,25 @@ class PricingScreen : public QWidget {
bool fetched_ = false;
bool loading_ = false;
bool awaiting_payment_ = false;
+ /// True between issuing a refresh_user_data() poll and receiving its
+ /// auth_state_changed reply. Without it every tick stacked another
+ /// one-shot connection on the same signal and fired another network
+ /// request, so a 10-minute checkout produced 600 in-flight listeners.
+ bool payment_poll_in_flight_ = false;
+ /// Ticks elapsed since polling started. Polling self-terminates at
+ /// kMaxPaymentPolls so an abandoned checkout tab cannot poll forever.
+ int payment_poll_ticks_ = 0;
+ static constexpr int kPaymentPollIntervalMs = 5000;
+ static constexpr int kMaxPaymentPolls = 120; // 5s × 120 = 10 minutes
QString awaiting_plan_id_;
QString pre_payment_plan_;
QMetaObject::Connection focus_connection_;
QTimer* payment_poll_timer_ = nullptr;
ui::ConfettiOverlay* confetti_ = nullptr;
+ /// Tear down the payment polling machinery (timer, focus hook, flags).
+ void stop_payment_polling();
+
void build_ui();
void fetch_plans();
void render_plan_cards();
diff --git a/fincept-qt/src/screens/auth/RegisterScreen.cpp b/fincept-qt/src/screens/auth/RegisterScreen.cpp
index b3c389471..5b447cbf2 100644
--- a/fincept-qt/src/screens/auth/RegisterScreen.cpp
+++ b/fincept-qt/src/screens/auth/RegisterScreen.cpp
@@ -10,6 +10,8 @@
#include <QHBoxLayout>
#include <QHideEvent>
#include <QPainter>
+#include <QRegularExpression>
+#include <QTimer>
#include <QVBoxLayout>
namespace fincept::screens {
@@ -162,6 +164,29 @@ RegisterScreen::RegisterScreen(QWidget* parent) : QWidget(parent) {
void RegisterScreen::hideEvent(QHideEvent* event) {
QWidget::hideEvent(event);
+
+ // Window-manager hides (minimise / workspace switch) must not destroy a
+ // half-filled form; only wipe when the user navigates away in-app.
+ if (event && event->spontaneous())
+ return;
+
+ for (QLineEdit* w :
+ {first_name_, last_name_, username_, email_, phone_, country_code_, password_, confirm_pw_, otp_input_}) {
+ if (w)
+ w->clear();
+ }
+ if (password_)
+ password_->setEchoMode(QLineEdit::Password);
+ if (confirm_pw_)
+ confirm_pw_->setEchoMode(QLineEdit::Password);
+ update_password_strength();
+ reset_resend_cooldown(); // P3: no timers while the screen is off-stack
+ if (error_label_)
+ error_label_->hide();
+ if (otp_error_)
+ otp_error_->hide();
+ if (pages_)
+ pages_->setCurrentIndex(0);
}
void RegisterScreen::changeEvent(QEvent* event) {
@@ -346,6 +371,47 @@ void RegisterScreen::build_form_page() {
lrl->addWidget(signin_btn_);
vl->addWidget(login_row);
+ // ── Input limits ─────────────────────────────────────────────────────────
+ // Client-side caps mirroring the register endpoint's constraints, so an
+ // over-long value is stopped at the keyboard instead of on a round trip.
+ first_name_->setMaxLength(100);
+ last_name_->setMaxLength(100);
+ username_->setMaxLength(50);
+ email_->setMaxLength(254); // RFC 5321 maximum
+ country_code_->setMaxLength(5);
+ phone_->setMaxLength(20);
+ password_->setMaxLength(128);
+ confirm_pw_->setMaxLength(128);
+
+ // ── Accessibility + keyboard order ───────────────────────────────────────
+ // The form is built from nested column layouts (name row, phone row), so
+ // the natural focus chain jumps sideways. Pin it to reading order.
+ first_name_->setAccessibleName(tr("First name"));
+ last_name_->setAccessibleName(tr("Last name"));
+ username_->setAccessibleName(tr("Username"));
+ email_->setAccessibleName(tr("Email address"));
+ country_code_->setAccessibleName(tr("Country calling code"));
+ phone_->setAccessibleName(tr("Phone number"));
+ password_->setAccessibleName(tr("Password"));
+ confirm_pw_->setAccessibleName(tr("Confirm password"));
+ register_btn_->setAccessibleName(tr("Create account"));
+ signin_btn_->setAccessibleName(tr("Go to sign in"));
+ error_label_->setAccessibleName(tr("Registration error"));
+
+ setTabOrder(first_name_, last_name_);
+ setTabOrder(last_name_, username_);
+ setTabOrder(username_, email_);
+ setTabOrder(email_, country_code_);
+ setTabOrder(country_code_, phone_);
+ setTabOrder(phone_, password_);
+ setTabOrder(password_, confirm_pw_);
+ setTabOrder(confirm_pw_, register_btn_);
+ setTabOrder(register_btn_, signin_btn_);
+
+ // Enter anywhere in the form submits, matching the login screen.
+ for (QLineEdit* w : {first_name_, last_name_, username_, email_, country_code_, phone_, password_, confirm_pw_})
+ connect(w, &QLineEdit::returnPressed, this, &RegisterScreen::on_register);
+
pages_->addWidget(page);
}
@@ -428,6 +494,17 @@ void RegisterScreen::build_otp_page() {
vl->addStretch();
connect(otp_input_, &QLineEdit::returnPressed, this, &RegisterScreen::on_verify_otp);
+
+ otp_input_->setMaxLength(12);
+ otp_input_->setAccessibleName(tr("Email verification code"));
+ otp_error_->setAccessibleName(tr("Verification error"));
+ verify_btn_->setAccessibleName(tr("Verify email"));
+ resend_btn_->setAccessibleName(tr("Resend verification code"));
+ back_to_form_btn_->setAccessibleName(tr("Back to the registration form"));
+ setTabOrder(otp_input_, verify_btn_);
+ setTabOrder(verify_btn_, resend_btn_);
+ setTabOrder(resend_btn_, back_to_form_btn_);
+
pages_->addWidget(page);
}
@@ -485,8 +562,11 @@ void RegisterScreen::retranslateUi() {
otp_input_->setPlaceholderText(tr("enter code from email"));
if (verify_btn_)
verify_btn_->setText(tr(" VERIFY "));
- if (resend_btn_)
+ // Don't clobber a live cooldown countdown with the idle label.
+ if (resend_btn_ && resend_cooldown_left_ <= 0)
resend_btn_->setText(tr("DIDN'T RECEIVE? RESEND"));
+ else if (resend_btn_)
+ resend_btn_->setText(tr("RESEND IN %1s").arg(resend_cooldown_left_));
if (back_to_form_btn_)
back_to_form_btn_->setText(tr("BACK TO FORM"));
}
@@ -494,12 +574,28 @@ void RegisterScreen::retranslateUi() {
// ── Password Strength ────────────────────────────────────────────────────────
void RegisterScreen::update_password_strength() {
+ if (!password_)
+ return;
auto s = auth::validate_password(password_->text());
- pw_len_->setStyleSheet(s.min_length ? check_on() : check_off());
- pw_up_->setStyleSheet(s.has_upper ? check_on() : check_off());
- pw_low_->setStyleSheet(s.has_lower ? check_on() : check_off());
- pw_num_->setStyleSheet(s.has_number ? check_on() : check_off());
- pw_spec_->setStyleSheet(s.has_special ? check_on() : check_off());
+
+ // This runs on every keystroke. setStyleSheet is a full CSS reparse plus a
+ // repaint of the label, so only touch a hint whose state actually flipped —
+ // the steady state (user typing past the threshold) becomes a no-op.
+ auto set_hint = [](QLabel* lbl, bool ok) {
+ if (!lbl)
+ return;
+ const QVariant prev = lbl->property("hintOk");
+ if (prev.isValid() && prev.toBool() == ok)
+ return;
+ lbl->setProperty("hintOk", ok);
+ lbl->setStyleSheet(ok ? check_on() : check_off());
+ };
+
+ set_hint(pw_len_, s.min_length);
+ set_hint(pw_up_, s.has_upper);
+ set_hint(pw_low_, s.has_lower);
+ set_hint(pw_num_, s.has_number);
+ set_hint(pw_spec_, s.has_special);
}
// ── Actions ──────────────────────────────────────────────────────────────────
@@ -579,12 +675,49 @@ void RegisterScreen::on_verify_otp() {
}
void RegisterScreen::on_resend_otp() {
+ // Guard against double-submits: the endpoint re-runs the whole signup, and
+ // hammering it is the fastest way to trip a server-side rate limit with no
+ // way for the user to tell why.
+ if (resend_btn_ && !resend_btn_->isEnabled())
+ return;
+
QString username = auth::sanitize_input(username_->text()).toLower();
QString cc = country_code_->text().trimmed();
if (!cc.isEmpty() && !cc.startsWith('+'))
cc = '+' + cc;
auth::AuthManager::instance().signup(username, email_->text().trimmed(), password_->text(),
phone_->text().trimmed(), {}, cc);
+ start_resend_cooldown();
+}
+
+void RegisterScreen::start_resend_cooldown() {
+ if (!resend_btn_)
+ return;
+ resend_cooldown_left_ = 30;
+ if (!resend_timer_) {
+ resend_timer_ = new QTimer(this);
+ resend_timer_->setInterval(1000);
+ connect(resend_timer_, &QTimer::timeout, this, [this]() {
+ if (--resend_cooldown_left_ <= 0) {
+ reset_resend_cooldown();
+ return;
+ }
+ resend_btn_->setText(tr("RESEND IN %1s").arg(resend_cooldown_left_));
+ });
+ }
+ resend_btn_->setEnabled(false);
+ resend_btn_->setText(tr("RESEND IN %1s").arg(resend_cooldown_left_));
+ resend_timer_->start();
+}
+
+void RegisterScreen::reset_resend_cooldown() {
+ resend_cooldown_left_ = 0;
+ if (resend_timer_)
+ resend_timer_->stop();
+ if (resend_btn_) {
+ resend_btn_->setEnabled(true);
+ resend_btn_->setText(tr("DIDN'T RECEIVE? RESEND"));
+ }
}
} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/auth/RegisterScreen.h b/fincept-qt/src/screens/auth/RegisterScreen.h
index 52ae82dd3..5b45bdbae 100644
--- a/fincept-qt/src/screens/auth/RegisterScreen.h
+++ b/fincept-qt/src/screens/auth/RegisterScreen.h
@@ -5,6 +5,8 @@
#include <QStackedWidget>
#include <QWidget>
+class QTimer;
+
namespace fincept::screens {
/// Registration screen — Obsidian design, compact form + OTP verification.
@@ -68,6 +70,14 @@ class RegisterScreen : public QWidget {
QLabel* otp_error_ = nullptr;
QLabel* otp_email_ = nullptr;
+ /// Cooldown so the OTP resend link cannot be hammered. Started on every
+ /// resend; ticks the remaining seconds into the button label. Stopped in
+ /// hideEvent so the timer never runs while the screen is off-stack (P3).
+ QTimer* resend_timer_ = nullptr;
+ int resend_cooldown_left_ = 0;
+ void start_resend_cooldown();
+ void reset_resend_cooldown();
+
void build_form_page();
void build_otp_page();
void update_password_strength();
diff --git a/fincept-qt/src/screens/backtesting/BacktestingScreen.cpp b/fincept-qt/src/screens/backtesting/BacktestingScreen.cpp
index f79a2c887..7c00633ed 100644
--- a/fincept-qt/src/screens/backtesting/BacktestingScreen.cpp
+++ b/fincept-qt/src/screens/backtesting/BacktestingScreen.cpp
@@ -99,6 +99,34 @@ void BacktestingScreen::trigger_auto_run() {
void BacktestingScreen::hideEvent(QHideEvent* e) {
QWidget::hideEvent(e);
+ // P3: never leave a 1s timer running for a screen the user can't see. The
+ // run itself keeps going; the ticker resumes its count from run_elapsed_.
+ if (run_timer_)
+ run_timer_->stop();
+}
+
+// ── Run ticker (elapsed-time feedback for long commands) ─────────────────────
+
+void BacktestingScreen::start_run_ticker() {
+ if (!run_timer_) {
+ run_timer_ = new QTimer(this);
+ run_timer_->setInterval(1000);
+ connect(run_timer_, &QTimer::timeout, this, [this]() {
+ if (!is_running_) {
+ run_timer_->stop();
+ return;
+ }
+ const qint64 secs = run_elapsed_.elapsed() / 1000;
+ set_status_state(tr("EXECUTING… %1s").arg(secs), ui::colors::WARNING, "rgba(217,119,6,0.08)");
+ });
+ }
+ run_elapsed_.restart();
+ run_timer_->start();
+}
+
+void BacktestingScreen::stop_run_ticker() {
+ if (run_timer_)
+ run_timer_->stop();
}
void BacktestingScreen::changeEvent(QEvent* e) {
diff --git a/fincept-qt/src/screens/backtesting/BacktestingScreen.h b/fincept-qt/src/screens/backtesting/BacktestingScreen.h
index a0cfc32b8..61e1f5eb3 100644
--- a/fincept-qt/src/screens/backtesting/BacktestingScreen.h
+++ b/fincept-qt/src/screens/backtesting/BacktestingScreen.h
@@ -8,6 +8,7 @@
#include <QComboBox>
#include <QDateEdit>
#include <QDoubleSpinBox>
+#include <QElapsedTimer>
#include <QEvent>
#include <QHideEvent>
#include <QJsonObject>
@@ -21,6 +22,7 @@
#include <QTabWidget>
#include <QTableWidget>
#include <QTextEdit>
+#include <QTimer>
#include <QVBoxLayout>
#include <QWidget>
@@ -330,6 +332,14 @@ class BacktestingScreen : public QWidget, public IStatefulScreen, public IGroupL
/// freshly-populated strategy combos/params settle before on_run() reads them.
void trigger_auto_run();
+ // Long-run feedback: ticks the status chip with elapsed seconds while a
+ // command is in flight so a 3-minute walk-forward never looks frozen.
+ // Started in on_run(), stopped on result/error/hide (P3).
+ QTimer* run_timer_ = nullptr;
+ QElapsedTimer run_elapsed_;
+ void start_run_ticker();
+ void stop_run_ticker();
+
QJsonArray pending_weights_;
bool first_show_ = true;
bool is_running_ = false;
diff --git a/fincept-qt/src/screens/backtesting/BacktestingScreen_Commands.cpp b/fincept-qt/src/screens/backtesting/BacktestingScreen_Commands.cpp
index 0d989fbfd..da3e20fe6 100644
--- a/fincept-qt/src/screens/backtesting/BacktestingScreen_Commands.cpp
+++ b/fincept-qt/src/screens/backtesting/BacktestingScreen_Commands.cpp
@@ -59,9 +59,13 @@ void BacktestingScreen::update_provider_buttons() {
// Same pill template as the brand / RUN / status chips so geometry is
// identical regardless of selection state.
- provider_buttons_[i]->setStyleSheet(
- pill_qss("QPushButton", fg, bg, border, ui::fonts::TINY, ui::fonts::DATA_FAMILY, weight) +
- QString("QPushButton:hover { background:rgba(%1,0.15); }").arg(rgb));
+ // P7: setStyleSheet always reparses + repolishes, even for an identical
+ // string. This runs for every provider on every provider change, so skip
+ // the 4 buttons whose skin didn't actually change.
+ const QString ss = pill_qss("QPushButton", fg, bg, border, ui::fonts::TINY, ui::fonts::DATA_FAMILY, weight) +
+ QString("QPushButton:hover { background:rgba(%1,0.15); }").arg(rgb);
+ if (provider_buttons_[i]->styleSheet() != ss)
+ provider_buttons_[i]->setStyleSheet(ss);
}
}
@@ -126,7 +130,9 @@ void BacktestingScreen::update_command_buttons() {
bool active = (i == active_command_);
bool enabled = supported.contains(cmd.id);
command_buttons_[i]->setEnabled(enabled);
- command_buttons_[i]->setStyleSheet(
+ // P7: only 2 of the 11 command pills change skin per command switch —
+ // skip the identical 9 rather than reparsing every stylesheet each time.
+ const QString cmd_ss =
QString("QPushButton { text-align:left; padding:6px 10px; border:none;"
"border-left:1px solid %1; color:%2;"
"font-size:%3px; font-family:%4; font-weight:%5; background:%6; }"
@@ -144,7 +150,9 @@ void BacktestingScreen::update_command_buttons() {
: "transparent")
.arg(QString("%1,%2,%3").arg(cmd.color.red()).arg(cmd.color.green()).arg(cmd.color.blue()))
.arg(cmd.color.name())
- .arg(ui::colors::TEXT_DIM()));
+ .arg(ui::colors::TEXT_DIM());
+ if (command_buttons_[i]->styleSheet() != cmd_ss)
+ command_buttons_[i]->setStyleSheet(cmd_ss);
}
}
// ── Gather args ──────────────────────────────────────────────────────────────
@@ -484,7 +492,8 @@ void BacktestingScreen::on_run() {
is_running_ = true;
run_button_->setEnabled(false);
- set_status_state(tr("EXECUTING..."), ui::colors::WARNING, "rgba(217,119,6,0.08)");
+ set_status_state(tr("EXECUTING… 0s"), ui::colors::WARNING, "rgba(217,119,6,0.08)");
+ start_run_ticker();
auto args = gather_args();
diff --git a/fincept-qt/src/screens/backtesting/BacktestingScreen_Results.cpp b/fincept-qt/src/screens/backtesting/BacktestingScreen_Results.cpp
index 589f3cc81..4e0c16e82 100644
--- a/fincept-qt/src/screens/backtesting/BacktestingScreen_Results.cpp
+++ b/fincept-qt/src/screens/backtesting/BacktestingScreen_Results.cpp
@@ -150,6 +150,14 @@ void BacktestingScreen::display_result(const QString& command, const QJsonObject
metrics_table_->resizeColumnsToContents();
};
+ // Row-cap bookkeeping — the DETAILS table is capped at kMaxDetailRows so a
+ // 100k-trade backtest doesn't allocate 100k QTableWidgetItems. The cap must
+ // be VISIBLE (tab label + banner) or a trader silently reads a 200-trade
+ // sample as the whole trade list.
+ constexpr int kMaxDetailRows = 200;
+ int details_total = 0;
+ int details_shown = 0;
+
auto fill_details_table = [&](const QJsonArray& arr, const QStringList& preferred_cols = {}) {
if (arr.isEmpty() || !arr[0].isObject())
return;
@@ -160,7 +168,9 @@ void BacktestingScreen::display_result(const QString& command, const QJsonObject
if (!it.value().isObject() && !it.value().isArray())
cols.append(it.key());
}
- const int rows = qMin(static_cast<int>(arr.size()), 200);
+ const int rows = qMin(static_cast<int>(arr.size()), kMaxDetailRows);
+ details_total = static_cast<int>(arr.size());
+ details_shown = rows;
trades_table_->setColumnCount(cols.size());
trades_table_->setHorizontalHeaderLabels(cols);
trades_table_->setRowCount(rows);
@@ -203,6 +213,62 @@ void BacktestingScreen::display_result(const QString& command, const QJsonObject
if (command == "backtest") {
auto perf = payload.value("performance").toObject();
+
+ // ── Cost disclosure ──
+ // Results are only achievable net of the costs that were actually sent
+ // to the provider. State them next to the headline numbers so a reader
+ // never mistakes a gross curve for a tradeable one.
+ {
+ const double comm = commission_spin_ ? commission_spin_->value() : 0.0;
+ const double slip = slippage_spin_ ? slippage_spin_->value() : 0.0;
+ const bool costless = (comm <= 0.0 && slip <= 0.0);
+ QString cost_text;
+ QString cost_fg;
+ QString cost_bg;
+ QString cost_border;
+ if (costless) {
+ cost_text = tr("NO COSTS MODELLED — commission and slippage are both 0%. "
+ "These returns are gross and are not achievable.");
+ cost_fg = ui::colors::WARNING();
+ cost_bg = QStringLiteral("rgba(245,158,11,0.10)");
+ cost_border = ui::colors::WARNING();
+ } else {
+ cost_text = tr("Costs applied: commission %1% per trade, slippage %2% per fill.")
+ .arg(comm, 0, 'f', 3)
+ .arg(slip, 0, 'f', 4);
+ cost_fg = ui::colors::TEXT_TERTIARY();
+ cost_bg = ui::colors::BG_RAISED();
+ cost_border = ui::colors::BORDER_DIM();
+ }
+ auto* costs = new QLabel(cost_text, summary_container_);
+ costs->setWordWrap(true);
+ costs->setStyleSheet(QString("color:%1; font-size:%2px; font-family:%3; padding:6px 10px; "
+ "background:%4; border:1px solid %5;")
+ .arg(cost_fg)
+ .arg(ui::fonts::TINY)
+ .arg(ui::fonts::DATA_FAMILY)
+ .arg(cost_bg, cost_border));
+ summary_layout_->addWidget(costs);
+ }
+
+ // ── No-trade guard ──
+ // A run that never traded reports 0% drawdown / 0 volatility, which reads
+ // like a flawless strategy on the summary cards. Say so explicitly.
+ const int n_trades = perf.value("totalTrades").toInt(perf.value("total_trades").toInt(-1));
+ if (n_trades == 0) {
+ auto* nt = new QLabel(tr("This strategy produced ZERO trades over the selected range. "
+ "Every performance figure below is meaningless — widen the date range, "
+ "loosen the entry rules, or check the symbol/interval."),
+ summary_container_);
+ nt->setWordWrap(true);
+ nt->setStyleSheet(QString("color:%1; font-size:%2px; font-family:%3; padding:8px 10px; "
+ "background:rgba(220,38,38,0.08); border:1px solid %1;")
+ .arg(ui::colors::NEGATIVE())
+ .arg(ui::fonts::SMALL)
+ .arg(ui::fonts::DATA_FAMILY));
+ summary_layout_->addWidget(nt);
+ }
+
add_cards_from(perf, {"totalReturn", "annualizedReturn", "sharpeRatio", "sortinoRatio", "maxDrawdown",
"winRate", "profitFactor", "calmarRatio", "totalTrades", "volatility"});
if (payload.contains("status")) {
@@ -509,6 +575,28 @@ void BacktestingScreen::display_result(const QString& command, const QJsonObject
fill_kv_table(payload);
}
+ // ── Row-cap disclosure ──
+ // Make the DETAILS truncation impossible to miss: label the tab with the
+ // real count and drop a banner on the summary.
+ if (result_tabs_ && result_tabs_->count() > 3) {
+ result_tabs_->setTabText(3, details_total > details_shown
+ ? tr("DETAILS (%1 of %2)").arg(details_shown).arg(details_total)
+ : tr("DETAILS"));
+ }
+ if (details_total > details_shown) {
+ auto* trunc = new QLabel(tr("Showing the first %1 of %2 rows. Use EXPORT JSON for the complete set.")
+ .arg(details_shown)
+ .arg(details_total),
+ summary_container_);
+ trunc->setWordWrap(true);
+ trunc->setStyleSheet(QString("color:%1; font-size:%2px; font-family:%3; padding:6px 10px; "
+ "background:rgba(245,158,11,0.10); border:1px solid %1;")
+ .arg(ui::colors::WARNING())
+ .arg(ui::fonts::TINY)
+ .arg(ui::fonts::DATA_FAMILY));
+ summary_layout_->addWidget(trunc);
+ }
+
summary_layout_->addStretch();
// ── Equity Curve chart ──
@@ -667,6 +755,7 @@ void BacktestingScreen::on_result(const QString& provider, const QString& comman
// Regular command result — update run state and display
is_running_ = false;
+ stop_run_ticker();
run_button_->setEnabled(true);
set_status_state(tr("READY"), ui::colors::POSITIVE, "rgba(22,163,74,0.08)");
display_result(command, payload);
@@ -709,6 +798,7 @@ void BacktestingScreen::on_command_options_loaded(const QString& provider, const
void BacktestingScreen::on_error(const QString& context, const QString& message) {
is_running_ = false;
+ stop_run_ticker();
run_button_->setEnabled(true);
set_status_state(tr("ERROR"), ui::colors::NEGATIVE, "rgba(220,38,38,0.08)");
display_error(QString("[%1] %2").arg(context, message));
diff --git a/fincept-qt/src/screens/backtesting/BacktestingScreen_internal.h b/fincept-qt/src/screens/backtesting/BacktestingScreen_internal.h
index 66f07caac..c2179126c 100644
--- a/fincept-qt/src/screens/backtesting/BacktestingScreen_internal.h
+++ b/fincept-qt/src/screens/backtesting/BacktestingScreen_internal.h
@@ -114,12 +114,15 @@ inline QString fmt_metric(const QString& key, const QJsonValue& val) {
if (count_metric_keys().contains(key))
return QString::number(static_cast<int>(v));
- // Percentage metrics → show as "xx.xx%"
- if (pct_metric_keys().contains(key)) {
- if (std::abs(v) <= 1.0)
- return QString("%1%").arg(v * 100.0, 0, 'f', 2);
- return QString("%1%").arg(v, 0, 'f', 2);
- }
+ // Percentage metrics → show as "xx.xx%".
+ //
+ // Every Python provider emits these as FRACTIONS (vbt_metrics.py divides
+ // "Max Drawdown [%]" by 100; win_rate is winning/total; zipline rounds the
+ // raw cum-return). The old `abs(v) <= 1.0 ? v*100 : v` heuristic therefore
+ // silently understated any result above 100% by a factor of 100 — a 150%
+ // total return rendered as "1.50%". Always scale: the contract is fixed.
+ if (pct_metric_keys().contains(key))
+ return QString("%1%").arg(v * 100.0, 0, 'f', 2);
// Ratio metrics → show as-is with 2-4 decimals
if (ratio_metric_keys().contains(key))
diff --git a/fincept-qt/src/screens/chat_mode/ChatAgentPanel.cpp b/fincept-qt/src/screens/chat_mode/ChatAgentPanel.cpp
index ea36f4a5f..5e020a230 100644
--- a/fincept-qt/src/screens/chat_mode/ChatAgentPanel.cpp
+++ b/fincept-qt/src/screens/chat_mode/ChatAgentPanel.cpp
@@ -9,6 +9,7 @@
#include <QJsonArray>
#include <QJsonObject>
#include <QMessageBox>
+#include <QPointer>
#include <QVBoxLayout>
namespace fincept::chat_mode {
@@ -323,8 +324,16 @@ void ChatAgentPanel::on_tab_changed(int index) {
// ── Refresh methods ───────────────────────────────────────────────────────────
+// P8: these five run unprompted (constructor, tab switch, language change) and
+// their callbacks are owned by the ChatModeService singleton, which outlives the
+// panel. A window closed with a request in flight used to land in a dangling
+// `this`. QPointer guard on each.
+
void ChatAgentPanel::refresh_memory() {
- ChatModeService::instance().list_memory([this](bool ok, QVector<AgentMemory> memories, QString err) {
+ QPointer<ChatAgentPanel> self = this;
+ ChatModeService::instance().list_memory([this, self](bool ok, QVector<AgentMemory> memories, QString err) {
+ if (!self)
+ return; // panel destroyed while the request was in flight
memory_list_->clear();
if (!ok) {
auto* item = new QListWidgetItem(tr("Not available."));
@@ -349,7 +358,10 @@ void ChatAgentPanel::refresh_memory() {
}
void ChatAgentPanel::refresh_schedules() {
- ChatModeService::instance().list_schedules([this](bool ok, QVector<AgentSchedule> schedules, QString err) {
+ QPointer<ChatAgentPanel> self = this;
+ ChatModeService::instance().list_schedules([this, self](bool ok, QVector<AgentSchedule> schedules, QString err) {
+ if (!self)
+ return;
sched_list_->clear();
if (!ok) {
auto* item = new QListWidgetItem(tr("Not available."));
@@ -376,7 +388,10 @@ void ChatAgentPanel::refresh_schedules() {
}
void ChatAgentPanel::refresh_tasks() {
- ChatModeService::instance().list_tasks([this](bool ok, QVector<AgentTask> tasks, QString err) {
+ QPointer<ChatAgentPanel> self = this;
+ ChatModeService::instance().list_tasks([this, self](bool ok, QVector<AgentTask> tasks, QString err) {
+ if (!self)
+ return;
task_list_->clear();
if (!ok) {
auto* item = new QListWidgetItem(tr("Not available."));
@@ -414,8 +429,11 @@ void ChatAgentPanel::refresh_tasks() {
}
void ChatAgentPanel::refresh_mcp_servers() {
+ QPointer<ChatAgentPanel> self = this;
ChatModeService::instance().list_mcp_servers(
- [this](bool ok, QVector<McpServer> servers, int total_tools, QString err) {
+ [this, self](bool ok, QVector<McpServer> servers, int total_tools, QString err) {
+ if (!self)
+ return;
mcp_list_->clear();
if (!ok) {
auto* item = new QListWidgetItem(tr("Not available."));
@@ -449,7 +467,10 @@ void ChatAgentPanel::refresh_mcp_servers() {
}
void ChatAgentPanel::refresh_monitors() {
- ChatModeService::instance().list_monitors([this](bool ok, QVector<AgentMonitor> monitors, QString err) {
+ QPointer<ChatAgentPanel> self = this;
+ ChatModeService::instance().list_monitors([this, self](bool ok, QVector<AgentMonitor> monitors, QString err) {
+ if (!self)
+ return;
monitor_list_->clear();
if (!ok) {
auto* item = new QListWidgetItem(tr("Not available."));
diff --git a/fincept-qt/src/screens/chat_mode/ChatMessagePanel.cpp b/fincept-qt/src/screens/chat_mode/ChatMessagePanel.cpp
index a8436215e..25856df70 100644
--- a/fincept-qt/src/screens/chat_mode/ChatMessagePanel.cpp
+++ b/fincept-qt/src/screens/chat_mode/ChatMessagePanel.cpp
@@ -7,6 +7,7 @@
#include <QEvent>
#include <QHBoxLayout>
#include <QKeyEvent>
+#include <QKeySequence>
#include <QLocale>
#include <QPalette>
#include <QScrollBar>
@@ -156,8 +157,17 @@ QWidget* ChatMessagePanel::build_messages_area() {
// Scroll persistence signal — emitted when the user scrolls within the
// message history; ChatModeScreen listens and debounces a save.
+ //
+ // The same handler drives scroll pinning: while a stream is running we only
+ // auto-follow the bottom if the user is already there. Scrolling up to read
+ // an earlier answer used to be fought by every 120 ms render tick.
if (auto* vbar = scroll_area_->verticalScrollBar())
- connect(vbar, &QScrollBar::valueChanged, this, [this](int) { emit scroll_changed(); });
+ connect(vbar, &QScrollBar::valueChanged, this, [this, vbar](int value) {
+ // 24 px of slack so a partially-rendered last line still counts as
+ // "at the bottom".
+ scroll_locked_ = (vbar->maximum() - value) > 24;
+ emit scroll_changed();
+ });
return scroll_area_;
}
@@ -264,6 +274,9 @@ QWidget* ChatMessagePanel::build_input_area() {
.arg(ui::colors::BG_RAISED(), ui::colors::TEXT_PRIMARY(), ui::colors::BORDER_DIM(),
FONT, ui::colors::BORDER_BRIGHT(), ui::colors::BORDER_MED()));
input_box_->installEventFilter(this);
+ input_box_->setAccessibleName(tr("Message the Fincept agent"));
+ input_box_->setAccessibleDescription(
+ tr("Type a question. Enter or Ctrl+Enter sends, Shift+Enter inserts a new line."));
vl->addWidget(input_box_);
auto* bottom = new QHBoxLayout;
@@ -308,6 +321,10 @@ QWidget* ChatMessagePanel::build_input_area() {
stop_btn_ = new QPushButton(tr("Stop"));
stop_btn_->setFixedHeight(26);
stop_btn_->setVisible(false);
+ stop_btn_->setAccessibleName(tr("Stop generating"));
+ stop_btn_->setToolTip(tr("Stop generating (Esc)"));
+ // Only reachable while visible — i.e. exactly while a stream is running.
+ stop_btn_->setShortcut(QKeySequence(Qt::Key_Escape));
stop_btn_->setStyleSheet(QString("QPushButton{background:rgba(50,12,12,0.7);color:%1;"
"border:1px solid rgba(220,38,38,0.2);border-radius:0px;"
"font-size:12px;padding:0 12px;font-family:%2;}"
@@ -318,6 +335,7 @@ QWidget* ChatMessagePanel::build_input_area() {
send_btn_ = new QPushButton(tr("Send"));
send_btn_->setFixedHeight(26);
+ send_btn_->setAccessibleName(tr("Send message"));
send_btn_->setStyleSheet(
QString("QPushButton{background:%1;color:%2;border:none;"
"border-radius:0px;font-size:12px;font-weight:600;padding:0 16px;"
@@ -329,6 +347,14 @@ QWidget* ChatMessagePanel::build_input_area() {
bottom->addWidget(send_btn_);
vl->addLayout(bottom);
+
+ // Explicit tab order — the composer is the entry point, then the actions in
+ // the order they appear. Without this, Qt walks creation order, which puts
+ // Optimize before the input box.
+ setTabOrder(input_box_, optimize_btn_);
+ setTabOrder(optimize_btn_, stop_btn_);
+ setTabOrder(stop_btn_, send_btn_);
+
return container;
}
@@ -347,6 +373,28 @@ void ChatMessagePanel::load_messages(const QVector<ChatMessage>& messages) {
}
void ChatMessagePanel::clear_messages() {
+ // A stream in flight belongs to the session we are about to leave. Tear it
+ // down BEFORE the widgets go away: otherwise the deltas kept arriving for a
+ // bubble that no longer existed, the header title was overwritten by the old
+ // session's `session-meta`, and the composer stayed disabled until the old
+ // stream happened to finish. Local state is reset first so the synthetic
+ // stream_finish(0) that abort_stream() emits is a no-op re-entrancy-wise.
+ if (streaming_) {
+ streaming_ = false;
+ streaming_bubble_ = nullptr;
+ streaming_buffer_.clear();
+ pending_thinking_.clear();
+ pending_tools_.clear();
+ render_timer_->stop();
+ show_typing(false);
+ set_input_enabled(true);
+ send_btn_->setVisible(true);
+ optimize_btn_->setVisible(true);
+ stop_btn_->setVisible(false);
+ ChatModeService::instance().abort_stream();
+ }
+ scroll_locked_ = false;
+
while (messages_layout_->count() > 0) {
auto* item = messages_layout_->takeAt(0);
if (item->widget() && item->widget() != welcome_panel_)
@@ -585,13 +633,15 @@ void ChatMessagePanel::on_stream_finish(int total_tokens) {
streaming_ = false;
streaming_bubble_ = nullptr;
streaming_buffer_.clear();
- scroll_locked_ = false;
show_typing(false);
set_input_enabled(true);
send_btn_->setVisible(true);
optimize_btn_->setVisible(true);
stop_btn_->setVisible(false);
- scroll_to_bottom();
+ // Don't yank the viewport back down if the user scrolled up to read.
+ // on_send_clicked() clears the lock when the next message goes out.
+ if (!scroll_locked_)
+ scroll_to_bottom();
}
void ChatMessagePanel::on_stream_error(const QString& message) {
@@ -741,7 +791,13 @@ void ChatMessagePanel::retranslateUi() {
bool ChatMessagePanel::eventFilter(QObject* obj, QEvent* ev) {
if (obj == input_box_ && ev->type() == QEvent::KeyPress) {
auto* ke = static_cast<QKeyEvent*>(ev);
- if (ke->key() == Qt::Key_Return && !(ke->modifiers() & Qt::ShiftModifier)) {
+ const bool enter = (ke->key() == Qt::Key_Return || ke->key() == Qt::Key_Enter);
+ // Ctrl+Enter sends too — muscle memory from every other chat client.
+ if (enter && (ke->modifiers() & Qt::ControlModifier)) {
+ on_send_clicked();
+ return true;
+ }
+ if (enter && !(ke->modifiers() & Qt::ShiftModifier)) {
on_send_clicked();
return true;
}
diff --git a/fincept-qt/src/screens/chat_mode/ChatModeService.cpp b/fincept-qt/src/screens/chat_mode/ChatModeService.cpp
index 3a7fc71ff..be0e27279 100644
--- a/fincept-qt/src/screens/chat_mode/ChatModeService.cpp
+++ b/fincept-qt/src/screens/chat_mode/ChatModeService.cpp
@@ -661,11 +661,14 @@ QNetworkReply* ChatModeService::stream_task_activity(const QString& task_id, int
}
void ChatModeService::abort_task_activity_stream() {
- if (task_sse_reply_) {
- task_sse_reply_->abort();
- task_sse_reply_->deleteLater();
- task_sse_reply_ = nullptr;
- }
+ // Same synchronous-finished() hazard as abort_stream() — detach before abort.
+ QNetworkReply* reply = task_sse_reply_;
+ if (!reply)
+ return;
+ task_sse_reply_ = nullptr;
+ disconnect(reply, nullptr, this, nullptr);
+ reply->abort();
+ reply->deleteLater();
}
void ChatModeService::handle_task_sse_line(const QByteArray& line) {
@@ -924,11 +927,19 @@ QNetworkReply* ChatModeService::stream_message(const QString& message, const QSt
}
void ChatModeService::abort_stream() {
- if (sse_reply_) {
- sse_reply_->abort();
- sse_reply_->deleteLater();
- sse_reply_ = nullptr;
- }
+ // QNetworkReply::abort() emits finished() SYNCHRONOUSLY, and the finished
+ // handler below nulls sse_reply_ — so the old
+ // sse_reply_->abort(); sse_reply_->deleteLater();
+ // sequence dereferenced a null member on the second line. Detach the reply
+ // first, drop our connections, then abort + delete it.
+ QNetworkReply* reply = sse_reply_;
+ if (!reply)
+ return; // nothing in flight — do NOT synthesise a terminal signal
+ sse_reply_ = nullptr;
+ disconnect(reply, nullptr, this, nullptr);
+ reply->abort();
+ reply->deleteLater();
+
// A user-initiated Stop otherwise emits no terminal signal (the finished
// handler skips OperationCanceledError), so the chat panel's input would
// stay disabled forever. Emit one if none has gone out for this stream.
diff --git a/fincept-qt/src/screens/chat_mode/ChatSessionPanel.cpp b/fincept-qt/src/screens/chat_mode/ChatSessionPanel.cpp
index d75f2a4e5..0bd75593b 100644
--- a/fincept-qt/src/screens/chat_mode/ChatSessionPanel.cpp
+++ b/fincept-qt/src/screens/chat_mode/ChatSessionPanel.cpp
@@ -10,6 +10,7 @@
#include <QJsonDocument>
#include <QListWidgetItem>
#include <QMessageBox>
+#include <QPointer>
#include <QTimer>
#include <QVBoxLayout>
@@ -141,7 +142,13 @@ void ChatSessionPanel::build_ui() {
}
void ChatSessionPanel::refresh_sessions() {
- ChatModeService::instance().list_sessions([this](bool ok, QVector<ChatSession> sessions, QString err) {
+ // P8: the callback is owned by the ChatModeService singleton, which outlives
+ // this panel. Guard so a window closed mid-request doesn't touch a dead
+ // widget (refresh_sessions fires on every stream finish + session mutation).
+ QPointer<ChatSessionPanel> self = this;
+ ChatModeService::instance().list_sessions([this, self](bool ok, QVector<ChatSession> sessions, QString err) {
+ if (!self)
+ return;
if (!ok) {
LOG_WARN("ChatSessionPanel", "Failed to load sessions: " + err);
return;
@@ -276,7 +283,10 @@ void ChatSessionPanel::on_export_clicked() {
export_btn_->setEnabled(false);
export_btn_->setText("...");
- ChatModeService::instance().export_sessions(uuids, [this, path](bool ok, QJsonArray payload, QString err) {
+ QPointer<ChatSessionPanel> self = this;
+ ChatModeService::instance().export_sessions(uuids, [this, self, path](bool ok, QJsonArray payload, QString err) {
+ if (!self)
+ return;
export_btn_->setEnabled(true);
export_btn_->setText(tr("Export"));
if (!ok) {
@@ -309,8 +319,9 @@ void ChatSessionPanel::on_search_server() {
if (query.length() < 2)
return;
- ChatModeService::instance().search_messages(query, [this](bool ok, QVector<ChatMessage> results, QString) {
- if (!ok || results.isEmpty())
+ QPointer<ChatSessionPanel> self = this;
+ ChatModeService::instance().search_messages(query, [this, self](bool ok, QVector<ChatMessage> results, QString) {
+ if (!self || !ok || results.isEmpty())
return;
// Highlight sessions that have matching messages
for (int i = 0; i < session_list_->count(); ++i) {
diff --git a/fincept-qt/src/screens/chat_mode/TerminalToolBridge.cpp b/fincept-qt/src/screens/chat_mode/TerminalToolBridge.cpp
index fba78fb30..2dc1f3ac5 100644
--- a/fincept-qt/src/screens/chat_mode/TerminalToolBridge.cpp
+++ b/fincept-qt/src/screens/chat_mode/TerminalToolBridge.cpp
@@ -2,8 +2,10 @@
#include "core/logging/Logger.h"
#include "mcp/McpProvider.h"
+#include "mcp/TerminalMcpBridge.h"
#include "screens/chat_mode/ChatModeService.h"
+#include <QFuture>
#include <QFutureWatcher>
#include <QJsonDocument>
#include <QJsonObject>
@@ -15,6 +17,20 @@ namespace fincept::chat_mode {
// Categories that are UI-only and should not be exposed to Finagent
const QStringList TerminalToolBridge::EXCLUDED_CATEGORIES = {"navigation", "system", "settings"};
+// Real money (live broker order placement/cancel/close) and local process
+// control (install/start external MCP servers). See the header for why these
+// fail closed on this path but not on the local-agent path.
+const QStringList TerminalToolBridge::BLOCKED_CATEGORIES = {"live-trading", "mcp-servers"};
+
+// Arbitrary local code execution + irreversible file deletion. Their categories
+// ("analytics", "file_manager") also contain read-only tools worth keeping.
+const QStringList TerminalToolBridge::BLOCKED_TOOLS = {"run_python_script", "delete_managed_file",
+ "bulk_delete_managed_files"};
+
+bool TerminalToolBridge::is_remote_blocked(const QString& name, const QString& category) {
+ return BLOCKED_CATEGORIES.contains(category) || BLOCKED_TOOLS.contains(name);
+}
+
TerminalToolBridge::TerminalToolBridge(QObject* parent) : QObject(parent) {
poll_timer_ = new QTimer(this);
poll_timer_->setInterval(3000); // 3 seconds
@@ -50,6 +66,7 @@ void TerminalToolBridge::register_tools() {
auto all_tools = provider.list_tools();
QJsonArray tools_json;
+ int blocked = 0;
for (const auto& tool : all_tools) {
// Phase 6.5: filter by ToolDef.category, not by name-prefix.
@@ -63,6 +80,12 @@ void TerminalToolBridge::register_tools() {
// Recursive AiChat tools — skip by category, not by name prefix.
if (tool.category == "ai-chat" || tool.category == "ai_chat")
continue;
+ // Fail closed on real-money / arbitrary-code tools — the cloud agent
+ // has no equivalent of the local agent's destructive opt-in token.
+ if (is_remote_blocked(tool.name, tool.category)) {
+ ++blocked;
+ continue;
+ }
QJsonObject schema = tool.input_schema;
if (schema.isEmpty()) {
@@ -78,7 +101,11 @@ void TerminalToolBridge::register_tools() {
}
const int count = tools_json.size();
- LOG_INFO("TerminalToolBridge", QString("Registering %1 tools (gen %2)").arg(count).arg(gen));
+ LOG_INFO("TerminalToolBridge",
+ QString("Registering %1 tools (gen %2, %3 withheld as unsafe for remote execution)")
+ .arg(count)
+ .arg(gen)
+ .arg(blocked));
QPointer<TerminalToolBridge> self = this;
ChatModeService::instance().register_terminal_tools(
@@ -133,12 +160,56 @@ void TerminalToolBridge::execute_call(const QString& call_id, const QString& too
auto [server_id, parsed_name] = mcp::McpProvider::parse_openai_function_name(tool_name);
const QString local_name = parsed_name.isEmpty() ? tool_name : parsed_name;
+ // Defence in depth: the backend can hand back any tool name — a stale
+ // catalog from an earlier generation, or one the model invented. Re-check
+ // the deny list at execution time so a blocked tool can never run even if
+ // it was somehow registered.
+ const auto tool_info = mcp::McpProvider::instance().find_tool(local_name);
+ const QString tool_category = tool_info ? tool_info->category : QString();
+ if (is_remote_blocked(local_name, tool_category)) {
+ LOG_WARN("TerminalToolBridge",
+ QString("Refused remote tool '%1' (category '%2') — real-money / arbitrary-code tools are not "
+ "available to the cloud agent")
+ .arg(local_name, tool_category));
+ const auto refusal = mcp::ToolResult::fail(
+ QString("Tool '%1' is not available to the remote agent. It moves real funds or executes local "
+ "code and must be run by the user from the terminal UI.")
+ .arg(local_name));
+ ChatModeService::instance().submit_tool_result(call_id, refusal.to_json(), [](bool, QString) {});
+ emit bridge_error(tr("Blocked unsafe remote tool call: %1").arg(local_name));
+ return;
+ }
+ // Audit trail for every mutating tool the remote agent runs. Not a gate —
+ // just a record, so a surprising state change can be traced back.
+ if (tool_info && tool_info->is_destructive)
+ LOG_WARN("TerminalToolBridge",
+ QString("Remote agent executing destructive tool '%1' (call %2)").arg(local_name, call_id));
+
// Phase 4: dispatch via call_tool_async so sync handlers don't block
// a worker thread for the duration of long-running tools, and so
// multiple in-flight tool calls fan out concurrently. A QFutureWatcher
// delivers the result back to this bridge's thread when complete.
QPointer<TerminalToolBridge> self = this;
- auto future = mcp::McpProvider::instance().call_tool_async(local_name, arguments);
+
+ // Mark this as an AGENT-originated call so the process-wide AuthChecker
+ // installed by AgentService actually applies. That checker denies
+ // `is_destructive` tools only when TerminalMcpBridge::is_call_in_progress()
+ // is true — a thread_local flag previously set ONLY by TerminalMcpBridge.
+ // This bridge (the cloud-agent poll path) never set it, so every tool it
+ // dispatched was classified as a user-driven chat call and skipped the
+ // destructive gate entirely. The deny list above is defence in depth; this
+ // is the actual gate. `destructive_allowed=false` because a poll-driven
+ // remote agent can never show a confirmation modal.
+ //
+ // Scoped around call_tool_async specifically: McpProvider runs
+ // check_authorization() synchronously in that function's prologue
+ // (McpProvider.cpp) before dispatching to a pool thread, so the flag is
+ // read on THIS thread while the guard is alive.
+ QFuture<mcp::ToolResult> future;
+ {
+ mcp::TerminalMcpBridge::ScopedCallFlags gate(/*call_in_progress=*/true, /*destructive_allowed=*/false);
+ future = mcp::McpProvider::instance().call_tool_async(local_name, arguments);
+ }
auto* watcher = new QFutureWatcher<mcp::ToolResult>(this);
QObject::connect(watcher, &QFutureWatcher<mcp::ToolResult>::finished, this, [self, call_id, local_name, watcher]() {
diff --git a/fincept-qt/src/screens/chat_mode/TerminalToolBridge.h b/fincept-qt/src/screens/chat_mode/TerminalToolBridge.h
index 0cf0d8d68..030766d5e 100644
--- a/fincept-qt/src/screens/chat_mode/TerminalToolBridge.h
+++ b/fincept-qt/src/screens/chat_mode/TerminalToolBridge.h
@@ -46,6 +46,27 @@ class TerminalToolBridge : public QObject {
// UI-only categories to exclude from registration
static const QStringList EXCLUDED_CATEGORIES;
+
+ /// Categories that can move real money or execute arbitrary local code.
+ /// Never registered with — and never executed for — the cloud agent.
+ ///
+ /// Rationale: the LOCAL agent path (mcp::TerminalMcpBridge) marks its calls
+ /// with a thread-local flag that AgentService's McpProvider auth checker
+ /// reads, so `is_destructive` tools are denied unless that agent's config
+ /// carries the per-agent destructive capability token (CreateAgentPanel's
+ /// "Allow destructive tools" checkbox). This bridge dispatches calls that
+ /// originate from the *cloud* Finagent backend and sets no such flag, so
+ /// every tool it runs is treated as a user-driven chat call and skips the
+ /// gate entirely. Until an equivalent opt-in exists, fail closed on the
+ /// classes where a mistake is unrecoverable.
+ static const QStringList BLOCKED_CATEGORIES;
+
+ /// Individually blocked tools whose category also holds harmless read-only
+ /// tools (so a whole-category block would be too broad).
+ static const QStringList BLOCKED_TOOLS;
+
+ /// True when `name` / `category` names a tool the remote agent must not run.
+ static bool is_remote_blocked(const QString& name, const QString& category);
};
} // namespace fincept::chat_mode
diff --git a/fincept-qt/src/screens/code_editor/CodeEditorScreen.cpp b/fincept-qt/src/screens/code_editor/CodeEditorScreen.cpp
index a7efee213..917302b4d 100644
--- a/fincept-qt/src/screens/code_editor/CodeEditorScreen.cpp
+++ b/fincept-qt/src/screens/code_editor/CodeEditorScreen.cpp
@@ -33,10 +33,12 @@
#include <QLineEdit>
#include <QListWidget>
#include <QMenu>
+#include <QMessageBox>
#include <QMouseEvent>
#include <QPushButton>
#include <QScrollArea>
#include <QScrollBar>
+#include <QShortcut>
#include <QSplitter>
#include <QStackedWidget>
#include <QStyle>
@@ -175,6 +177,22 @@ void CodeEditorScreen::build_ui() {
view_stack_->addWidget(library_page_); // 0 — Library
view_stack_->addWidget(build_editor_page()); // 1 — Editor
root->addWidget(view_stack_, 1);
+
+ // The status bar advertises Ctrl+S but nothing was ever bound to it, and
+ // there was no keyboard route to New/Open/Run-all either. Scoped to this
+ // screen so they don't fight other tabs' bindings.
+ auto bind = [this](const QKeySequence& seq, void (CodeEditorScreen::*slot)()) {
+ auto* sc = new QShortcut(seq, this);
+ sc->setContext(Qt::WidgetWithChildrenShortcut);
+ connect(sc, &QShortcut::activated, this, slot);
+ };
+ bind(QKeySequence(QKeySequence::Save), &CodeEditorScreen::on_save_notebook);
+ bind(QKeySequence(QKeySequence::Open), &CodeEditorScreen::on_open_notebook);
+ bind(QKeySequence(QKeySequence::New), &CodeEditorScreen::on_new_notebook);
+ // Deliberately NOT F5 — KeyConfigManager binds F5 to the global Refresh
+ // action with Qt::ApplicationShortcut, and a second F5 would make both
+ // ambiguous (Qt fires activatedAmbiguously and neither handler runs).
+ bind(QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_Return), &CodeEditorScreen::on_run_all);
}
// Header bar: title + LIBRARY/EDITOR tabs + Library search + NEW button.
@@ -320,24 +338,32 @@ QWidget* CodeEditorScreen::build_toolbar() {
};
btn_new_ = make_btn(tr("NEW"));
+ btn_new_->setAccessibleName(tr("New notebook"));
+ btn_new_->setToolTip(tr("New notebook (%1)").arg(QKeySequence(QKeySequence::New).toString()));
connect(btn_new_, &QPushButton::clicked, this, &CodeEditorScreen::on_new_notebook);
hl->addWidget(btn_new_);
btn_open_ = make_btn(tr("OPEN"));
+ btn_open_->setAccessibleName(tr("Open notebook"));
+ btn_open_->setToolTip(tr("Open notebook (%1)").arg(QKeySequence(QKeySequence::Open).toString()));
connect(btn_open_, &QPushButton::clicked, this, &CodeEditorScreen::on_open_notebook);
hl->addWidget(btn_open_);
btn_save_ = make_btn(tr("SAVE"));
+ btn_save_->setAccessibleName(tr("Save notebook"));
+ btn_save_->setToolTip(tr("Save notebook (%1)").arg(QKeySequence(QKeySequence::Save).toString()));
connect(btn_save_, &QPushButton::clicked, this, &CodeEditorScreen::on_save_notebook);
hl->addWidget(btn_save_);
add_sep();
btn_add_cell_ = make_btn(tr("+ CELL"), "nbAccentBtn");
+ btn_add_cell_->setAccessibleName(tr("Add cell below the selected cell"));
connect(btn_add_cell_, &QPushButton::clicked, this, &CodeEditorScreen::on_add_cell);
hl->addWidget(btn_add_cell_);
btn_clear_out_ = make_btn(tr("CLEAR OUT"));
+ btn_clear_out_->setAccessibleName(tr("Clear all cell outputs"));
connect(btn_clear_out_, &QPushButton::clicked, this, &CodeEditorScreen::on_clear_outputs);
hl->addWidget(btn_clear_out_);
@@ -345,12 +371,16 @@ QWidget* CodeEditorScreen::build_toolbar() {
btn_run_all_ = make_btn(tr("▶ RUN ALL"), "nbPrimaryBtn");
btn_run_all_->setStyleSheet(QString("font-family:%1; font-size:%2px;").arg(fonts::DATA_FAMILY).arg(fonts::TINY));
+ btn_run_all_->setAccessibleName(tr("Run every code cell"));
+ btn_run_all_->setToolTip(tr("Run every code cell (Ctrl+Shift+Enter). Cells execute as separate processes and "
+ "do not share state with each other."));
connect(btn_run_all_, &QPushButton::clicked, this, &CodeEditorScreen::on_run_all);
hl->addWidget(btn_run_all_);
hl->addStretch();
btn_sidebar_ = make_btn(tr("SIDEBAR"));
+ btn_sidebar_->setAccessibleName(tr("Toggle the cell navigator sidebar"));
connect(btn_sidebar_, &QPushButton::clicked, this, &CodeEditorScreen::on_toggle_sidebar);
hl->addWidget(btn_sidebar_);
@@ -386,7 +416,9 @@ QWidget* CodeEditorScreen::build_status_bar() {
hl->addStretch();
shortcuts_label_ =
- new QLabel(tr("Ctrl+Enter: RUN | Shift+Enter: RUN & NEXT | Tab: 4 SPACES | Ctrl+S: SAVE"), bar);
+ new QLabel(tr("Ctrl+Enter: RUN | Shift+Enter: RUN & NEXT | Tab: 4 SPACES | Ctrl+S: SAVE | "
+ "Ctrl+Shift+Enter: RUN ALL"),
+ bar);
shortcuts_label_->setStyleSheet(QString("color:%1; font-family:%2; font-size:10px; letter-spacing:0.3px;")
.arg(colors::TEXT_DIM(), fonts::DATA_FAMILY));
hl->addWidget(shortcuts_label_);
@@ -398,7 +430,65 @@ QWidget* CodeEditorScreen::build_status_bar() {
// Notebook management
// ─────────────────────────────────────────────────────────────────────────────
+// ── Unsaved-change tracking ──────────────────────────────────────────────────
+
+void CodeEditorScreen::sync_cells_from_widgets() {
+ for (int i = 0; i < cells_.size(); ++i) {
+ auto* cw = find_cell_widget(cells_[i].id);
+ if (!cw)
+ continue;
+ const NotebookCell live = cw->cell_data();
+ cells_[i].source = live.source;
+ cells_[i].cell_type = live.cell_type;
+ cells_[i].title = live.title;
+ }
+}
+
+QString CodeEditorScreen::notebook_fingerprint() const {
+ QString fp;
+ fp.reserve(1024);
+ for (const auto& c : cells_) {
+ fp += c.cell_type;
+ fp += QLatin1Char('\x1f');
+ fp += c.title;
+ fp += QLatin1Char('\x1f');
+ fp += c.source;
+ fp += QLatin1Char('\x1e');
+ }
+ return fp;
+}
+
+bool CodeEditorScreen::confirm_discard_changes(const QString& action) {
+ sync_cells_from_widgets();
+ if (notebook_fingerprint() == clean_fingerprint_)
+ return true;
+
+ const QString name = notebook_path_.isEmpty() ? tr("this notebook") : QFileInfo(notebook_path_).fileName();
+ QMessageBox box(this);
+ box.setIcon(QMessageBox::Warning);
+ box.setWindowTitle(tr("Unsaved Changes"));
+ box.setText(tr("%1 has unsaved changes.").arg(name));
+ box.setInformativeText(tr("%1 will discard them.").arg(action));
+ box.setStandardButtons(QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel);
+ box.setDefaultButton(QMessageBox::Save);
+ const int choice = box.exec();
+ if (choice == QMessageBox::Cancel)
+ return false;
+ if (choice == QMessageBox::Save) {
+ on_save_notebook();
+ // on_save_notebook() only updates clean_fingerprint_ on a real write —
+ // a cancelled Save dialog must not silently drop the edits.
+ return notebook_fingerprint() == clean_fingerprint_;
+ }
+ return true;
+}
+
void CodeEditorScreen::on_new_notebook() {
+ // Guarded, except for the very first call from the constructor (no widgets
+ // exist yet, so the fingerprint is empty and the guard passes silently).
+ if (!confirm_discard_changes(tr("Creating a new notebook")))
+ return;
+
cells_.clear();
execution_counter_ = 0;
notebook_path_.clear();
@@ -414,6 +504,7 @@ void CodeEditorScreen::on_new_notebook() {
selected_cell_id_ = cell.id;
rebuild_cells();
+ clean_fingerprint_ = notebook_fingerprint();
update_status();
update_navigator();
}
@@ -450,6 +541,17 @@ void CodeEditorScreen::on_delete_cell(const QString& cell_id) {
if (cells_.size() <= 1)
return;
+ // There is no undo for cell deletion — confirm before dropping real content.
+ if (auto* cw = find_cell_widget(cell_id)) {
+ if (!cw->cell_data().source.trimmed().isEmpty()) {
+ if (QMessageBox::question(this, tr("Delete Cell"),
+ tr("Delete this cell and its contents?\n\nThis cannot be undone."),
+ QMessageBox::Yes | QMessageBox::Cancel,
+ QMessageBox::Cancel) != QMessageBox::Yes)
+ return;
+ }
+ }
+
int idx = find_cell_index(cell_id);
if (idx >= 0) {
cells_.removeAt(idx);
@@ -591,10 +693,13 @@ void CodeEditorScreen::on_run_cell(const QString& cell_id) {
auto* cw = find_cell_widget(cell_id);
if (cw) {
+ const auto outputs = cells_[idx].outputs;
cells_[idx] = cw->cell_data();
- cw->set_running(true);
+ cells_[idx].outputs = outputs;
}
+ // Bail out BEFORE flipping the running indicator — marking a markdown or
+ // empty cell as running left its gutter stuck on "[*]" forever.
if (cells_[idx].cell_type != "code")
return;
@@ -602,9 +707,13 @@ void CodeEditorScreen::on_run_cell(const QString& cell_id) {
if (code.trimmed().isEmpty())
return;
+ if (cw)
+ cw->set_running(true);
+
++execution_counter_;
int exec_num = execution_counter_;
+ ++pending_runs_;
kernel_busy_ = true;
refresh_kernel_label();
@@ -615,6 +724,13 @@ void CodeEditorScreen::on_run_cell(const QString& cell_id) {
if (!self)
return;
+ // Settle the busy counter even if the cell was deleted mid-run,
+ // otherwise the kernel badge sticks on BUSY.
+ if (self->pending_runs_ > 0)
+ --self->pending_runs_;
+ self->kernel_busy_ = (self->pending_runs_ > 0);
+ self->refresh_kernel_label();
+
int idx = self->find_cell_index(cid);
if (idx < 0)
return;
@@ -658,9 +774,6 @@ void CodeEditorScreen::on_run_cell(const QString& cell_id) {
widget->set_running(false);
}
- self->kernel_busy_ = false;
- self->refresh_kernel_label();
-
self->update_status();
self->update_navigator();
});
@@ -672,10 +785,16 @@ void CodeEditorScreen::on_run_and_advance(const QString& cell_id) {
}
void CodeEditorScreen::on_run_all() {
+ // Snapshot the ids first — on_run_cell() can mutate cells_ (it syncs the
+ // widget text back), and iterating the live container while it is being
+ // written to is how iterator invalidation bugs start.
+ QStringList code_cell_ids;
for (const auto& cell : cells_) {
if (cell.cell_type == "code")
- on_run_cell(cell.id);
+ code_cell_ids << cell.id;
}
+ for (const auto& id : code_cell_ids)
+ on_run_cell(id);
}
// ─────────────────────────────────────────────────────────────────────────────
@@ -683,11 +802,18 @@ void CodeEditorScreen::on_run_all() {
// ─────────────────────────────────────────────────────────────────────────────
void CodeEditorScreen::on_open_notebook() {
+ if (!confirm_discard_changes(tr("Opening another notebook")))
+ return;
const QString path =
QFileDialog::getOpenFileName(this, tr("Open Notebook"), {}, tr("Fincept Notebooks (*.ipynb);;All Files (*)"));
if (path.isEmpty())
return;
- open_notebook_path(path);
+ if (!open_notebook_path(path)) {
+ QMessageBox::warning(this, tr("Open Notebook"),
+ tr("Could not read a notebook from:\n%1\n\n"
+ "The file must be valid JSON in .ipynb (nbformat) shape.")
+ .arg(path));
+ }
}
// Public entry point: load an .ipynb from disk and switch to the editor view.
@@ -748,6 +874,7 @@ bool CodeEditorScreen::load_notebook_from_path(const QString& path) {
notebook_path_ = path;
selected_cell_id_ = cells_.first().id;
rebuild_cells();
+ clean_fingerprint_ = notebook_fingerprint(); // freshly loaded == no unsaved edits
update_status();
update_navigator();
LOG_INFO("CodeEditor", "Opened notebook: " + path);
@@ -758,8 +885,13 @@ bool CodeEditorScreen::load_notebook_from_path(const QString& path) {
void CodeEditorScreen::on_save_notebook() {
for (int i = 0; i < cells_.size(); ++i) {
auto* cw = find_cell_widget(cells_[i].id);
- if (cw)
+ if (cw) {
+ // cell_data() does not carry outputs — preserve the executed
+ // results instead of dropping them on every save.
+ const auto outputs = cells_[i].outputs;
cells_[i] = cw->cell_data();
+ cells_[i].outputs = outputs;
+ }
}
QString path = notebook_path_;
@@ -809,8 +941,15 @@ void CodeEditorScreen::on_save_notebook() {
file.write(QJsonDocument(root).toJson(QJsonDocument::Indented));
file.close();
notebook_path_ = path;
+ clean_fingerprint_ = notebook_fingerprint();
LOG_INFO("CodeEditor", "Saved notebook: " + path);
services::FileManagerService::instance().import_file(path, "code_editor");
+ } else {
+ // Silently failing a save is how work gets lost — say what happened.
+ LOG_ERROR("CodeEditor", "Save failed: " + path + " — " + file.errorString());
+ QMessageBox::warning(this, tr("Save Notebook"),
+ tr("Could not write to:\n%1\n\n%2").arg(path, file.errorString()));
+ return;
}
update_status();
}
@@ -942,11 +1081,16 @@ void CodeEditorScreen::retranslateUi() {
// Status bar
if (shortcuts_label_)
- shortcuts_label_->setText(tr("Ctrl+Enter: RUN | Shift+Enter: RUN & NEXT | Tab: 4 SPACES | Ctrl+S: SAVE"));
+ shortcuts_label_->setText(
+ tr("Ctrl+Enter: RUN | Shift+Enter: RUN & NEXT | Tab: 4 SPACES | Ctrl+S: SAVE | "
+ "Ctrl+Shift+Enter: RUN ALL"));
update_status(); // re-renders the cell-count summary in the new language
// Cell widgets carry their own translatable chrome — rebuild so they
- // re-create with the new language (cell source/outputs are data, preserved).
+ // re-create with the new language. rebuild_cells() renders from cells_, so
+ // pull the live editor text back first; without this, switching language
+ // mid-edit silently reverted every cell to its last-committed source.
+ sync_cells_from_widgets();
rebuild_cells();
}
diff --git a/fincept-qt/src/screens/code_editor/CodeEditorScreen.h b/fincept-qt/src/screens/code_editor/CodeEditorScreen.h
index 697dd27b1..1a53e653a 100644
--- a/fincept-qt/src/screens/code_editor/CodeEditorScreen.h
+++ b/fincept-qt/src/screens/code_editor/CodeEditorScreen.h
@@ -95,6 +95,10 @@ class CellWidget : public QWidget {
void mousePressEvent(QMouseEvent* event) override;
void changeEvent(QEvent* event) override;
void showEvent(QShowEvent* event) override;
+ /// Watches md_preview_ so a click on the rendered markdown drops back into
+ /// the source editor. The filter was installed but never implemented, so
+ /// the preview was a dead end for mouse users.
+ bool eventFilter(QObject* watched, QEvent* event) override;
private:
void build_ui();
@@ -228,6 +232,16 @@ class CodeEditorScreen : public QWidget, public IStatefulScreen {
QWidget* build_status_bar();
void retranslateUi();
void rebuild_cells();
+
+ /// Copy every live CellWidget's editor text back into cells_. Anything that
+ /// tears down and re-creates the cell widgets must call this first or the
+ /// user's in-progress typing is silently discarded.
+ void sync_cells_from_widgets();
+ /// Canonical string used to detect unsaved edits (type + source per cell).
+ QString notebook_fingerprint() const;
+ /// True if the notebook has no unsaved changes, or the user agreed to
+ /// discard them. `action` names the operation in the prompt.
+ bool confirm_discard_changes(const QString& action);
void add_cell_after(const QString& after_id, const QString& type);
int find_cell_index(const QString& cell_id) const;
CellWidget* find_cell_widget(const QString& cell_id) const;
@@ -240,6 +254,12 @@ class CodeEditorScreen : public QWidget, public IStatefulScreen {
QVector<NotebookCell> cells_;
int execution_counter_ = 0;
QString notebook_path_;
+ /// Fingerprint at the last new/open/save — compared against the live one to
+ /// detect unsaved edits.
+ QString clean_fingerprint_;
+ /// Cells still waiting on a PythonRunner callback. RUN ALL queues several,
+ /// so a single bool would clear the "BUSY" badge on the first return.
+ int pending_runs_ = 0;
// UI
QSplitter* splitter_ = nullptr;
diff --git a/fincept-qt/src/screens/code_editor/CodeEditorScreen_Cells.cpp b/fincept-qt/src/screens/code_editor/CodeEditorScreen_Cells.cpp
index 09281cbb0..c9602c8e4 100644
--- a/fincept-qt/src/screens/code_editor/CodeEditorScreen_Cells.cpp
+++ b/fincept-qt/src/screens/code_editor/CodeEditorScreen_Cells.cpp
@@ -137,7 +137,8 @@ void CellWidget::build_ui() {
auto* btn = new QPushButton(text, toolbar_);
btn->setFixedHeight(20);
btn->setCursor(Qt::PointingHandCursor);
- btn->setVisible(false); // hidden until hover
+ btn->setAccessibleName(text); // two-letter labels are opaque to a screen reader alone
+ btn->setVisible(false); // hidden until hover
btn->setStyleSheet(QString("QPushButton { background:transparent; color:%1; border:none;"
" font-family:%2; font-size:%3px; font-weight:600; padding:0 8px;"
" letter-spacing:0.5px; }"
@@ -149,24 +150,30 @@ void CellWidget::build_ui() {
};
run_btn_ = make_tool_btn(tr("RUN"), colors::POSITIVE);
+ run_btn_->setAccessibleName(tr("Run this cell"));
connect(run_btn_, &QPushButton::clicked, this, [this]() { emit run_requested(cell_id_); });
tb_layout->addWidget(run_btn_);
type_btn_ = make_tool_btn(tr("TYPE"), colors::CYAN);
+ type_btn_->setAccessibleName(tr("Switch between code and markdown"));
+ type_btn_->setToolTip(tr("Switch between code and markdown (clears this cell's output)"));
connect(type_btn_, &QPushButton::clicked, this, [this]() { emit toggle_type_requested(cell_id_); });
tb_layout->addWidget(type_btn_);
up_btn_ = make_tool_btn(tr("UP"), colors::TEXT_SECONDARY);
+ up_btn_->setAccessibleName(tr("Move this cell up"));
connect(up_btn_, &QPushButton::clicked, this, [this]() { emit move_up_requested(cell_id_); });
tb_layout->addWidget(up_btn_);
dn_btn_ = make_tool_btn(tr("DN"), colors::TEXT_SECONDARY);
+ dn_btn_->setAccessibleName(tr("Move this cell down"));
connect(dn_btn_, &QPushButton::clicked, this, [this]() { emit move_down_requested(cell_id_); });
tb_layout->addWidget(dn_btn_);
tb_layout->addStretch();
del_btn_ = make_tool_btn(tr("DEL"), colors::NEGATIVE);
+ del_btn_->setAccessibleName(tr("Delete this cell"));
connect(del_btn_, &QPushButton::clicked, this, [this]() { emit delete_requested(cell_id_); });
tb_layout->addWidget(del_btn_);
@@ -193,6 +200,9 @@ void CellWidget::build_ui() {
.arg(fonts::DATA)
.arg(colors::AMBER_DIM(), colors::BORDER_BRIGHT()));
editor_->document()->setDocumentMargin(2);
+ editor_->setAccessibleName(tr("Notebook cell source"));
+ editor_->setAccessibleDescription(
+ tr("Python source. Ctrl+Enter runs this cell, Shift+Enter runs it and moves to the next."));
// Keyboard shortcuts
connect(editor_, &CodeTextEdit::run_shortcut, this, [this]() { emit run_requested(cell_id_); });
@@ -218,8 +228,12 @@ void CellWidget::build_ui() {
.arg(fonts::DATA)
.arg(colors::BORDER_BRIGHT()));
- // Click on preview to edit
+ // Click on the rendered preview to drop back into the source editor.
+ // QTextBrowser swallows the press, so CellWidget::mousePressEvent never
+ // fires for it — the filter below (see eventFilter) is what makes this work.
md_preview_->installEventFilter(this);
+ md_preview_->setCursor(Qt::IBeamCursor);
+ md_preview_->setToolTip(tr("Click to edit this markdown cell"));
editor_vbox->addWidget(md_preview_);
@@ -748,6 +762,25 @@ void CellWidget::mousePressEvent(QMouseEvent* event) {
QWidget::mousePressEvent(event);
}
+bool CellWidget::eventFilter(QObject* watched, QEvent* event) {
+ // The markdown preview is read-only and consumes its own mouse events, so
+ // without this a rendered markdown cell could only be re-opened from the
+ // navigator. installEventFilter() was already in place but no override
+ // existed, so nothing happened.
+ if (watched == md_preview_ && event->type() == QEvent::MouseButtonPress) {
+ emit cell_clicked(cell_id_); // selecting a markdown cell switches it to edit mode
+ if (!md_editing_) {
+ md_editing_ = true;
+ md_preview_->setVisible(false);
+ editor_->setVisible(true);
+ editor_->setFocus(Qt::MouseFocusReason);
+ adjust_editor_height();
+ }
+ return true;
+ }
+ return QWidget::eventFilter(watched, event);
+}
+
// ═════════════════════════════════════════════════════════════════════════════
// CellNavigator (sidebar)
// ═════════════════════════════════════════════════════════════════════════════
diff --git a/fincept-qt/src/screens/code_editor/CodeEditorScreen_Library.cpp b/fincept-qt/src/screens/code_editor/CodeEditorScreen_Library.cpp
index 6df047477..2aa3c0a7c 100644
--- a/fincept-qt/src/screens/code_editor/CodeEditorScreen_Library.cpp
+++ b/fincept-qt/src/screens/code_editor/CodeEditorScreen_Library.cpp
@@ -11,6 +11,7 @@
#include <QGridLayout>
#include <QHBoxLayout>
#include <QLabel>
+#include <QMessageBox>
#include <QPushButton>
#include <QScrollArea>
#include <QStyle>
@@ -279,12 +280,24 @@ void CodeEditorScreen::on_open_library_entry(int catalog_index) {
if (catalog_index < 0 || catalog_index >= catalog.size())
return;
const NotebookCatalogEntry& e = catalog[catalog_index];
+
+ // Opening a library notebook replaces whatever is in the editor — same
+ // unsaved-work guard as File > Open.
+ if (!confirm_discard_changes(tr("Opening this library notebook")))
+ return;
+
const QString path = NotebookLibraryService::instance().working_copy_for(e);
if (path.isEmpty()) {
LOG_WARN("CodeEditor", "Could not open library notebook: " + e.id);
+ QMessageBox::warning(this, tr("Open Notebook"),
+ tr("Could not prepare a working copy of \"%1\".\n\n"
+ "The bundled notebook may be missing from this build.")
+ .arg(e.title));
return;
}
- open_notebook_path(path); // loads + switches to the editor view
+ if (!open_notebook_path(path)) { // loads + switches to the editor view
+ QMessageBox::warning(this, tr("Open Notebook"), tr("\"%1\" could not be parsed as a notebook.").arg(e.title));
+ }
}
} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/common/PaperBlotterPanel.cpp b/fincept-qt/src/screens/common/PaperBlotterPanel.cpp
index 742eb3894..fdf5f5ab2 100644
--- a/fincept-qt/src/screens/common/PaperBlotterPanel.cpp
+++ b/fincept-qt/src/screens/common/PaperBlotterPanel.cpp
@@ -12,12 +12,15 @@
#include <QDateTime>
#include <QHBoxLayout>
#include <QHeaderView>
+#include <QHideEvent>
#include <QLabel>
#include <QMessageBox>
#include <QPushButton>
+#include <QScrollBar>
#include <QShowEvent>
#include <QTabWidget>
#include <QTableWidget>
+#include <QTableWidgetItem>
#include <QTimer>
#include <QVBoxLayout>
@@ -55,13 +58,41 @@ QTableWidget* make_table(const QStringList& headers) {
return t;
}
-QTableWidgetItem* cell(const QString& text, const QColor& fg = QColor()) {
- auto* it = new QTableWidgetItem(text);
- if (fg.isValid())
- it->setForeground(fg);
- return it;
+// Write one cell, REUSING the existing QTableWidgetItem when the row survived
+// the refresh. The old code allocated ~10 fresh QTableWidgetItems per row on
+// every tick (2.5 s poll + every mark signal); on a 200-position blotter that
+// was 2000 allocations + 2000 destructions per refresh. Reuse also avoids the
+// model reset that killed the user's scroll position.
+void set_cell(QTableWidget* t, int row, int col, const QString& text, const QColor& fg = QColor()) {
+ QTableWidgetItem* it = t->item(row, col);
+ if (!it) {
+ it = new QTableWidgetItem;
+ t->setItem(row, col, it);
+ }
+ if (it->text() != text)
+ it->setText(text);
+ if (fg.isValid()) {
+ if (it->foreground().color() != fg)
+ it->setForeground(fg);
+ } else if (it->data(Qt::ForegroundRole).isValid()) {
+ it->setData(Qt::ForegroundRole, QVariant());
+ }
}
+// Save/restore the vertical scroll offset around a table rebuild so a live
+// blotter doesn't yank itself back to the top on every mark tick.
+struct ScrollKeeper {
+ QTableWidget* t;
+ int v;
+ explicit ScrollKeeper(QTableWidget* table) : t(table), v(table->verticalScrollBar()->value()) {
+ t->setUpdatesEnabled(false);
+ }
+ ~ScrollKeeper() {
+ t->verticalScrollBar()->setValue(v);
+ t->setUpdatesEnabled(true);
+ }
+};
+
} // namespace
PaperBlotterPanel::PaperBlotterPanel(QWidget* parent) : QWidget(parent) {
@@ -75,14 +106,12 @@ PaperBlotterPanel::PaperBlotterPanel(QWidget* parent) : QWidget(parent) {
[this](const QString&) { schedule_refresh(); });
// Safety-net poll so the view stays fresh even if no marks arrive (e.g. a
- // closed market), but only while actually visible.
- auto* poll = new QTimer(this);
- poll->setInterval(2500);
- connect(poll, &QTimer::timeout, this, [this]() {
- if (isVisible())
- refresh();
- });
- poll->start();
+ // closed market). Per CLAUDE.md P3 the timer is NOT started here — it is
+ // started in showEvent() and stopped in hideEvent(), so a hidden blotter
+ // costs zero DB queries instead of polling pt_get_* every 2.5 s forever.
+ poll_timer_ = new QTimer(this);
+ poll_timer_->setInterval(2500);
+ connect(poll_timer_, &QTimer::timeout, this, &PaperBlotterPanel::refresh);
}
void PaperBlotterPanel::build_ui() {
@@ -96,9 +125,14 @@ void PaperBlotterPanel::build_ui() {
"QTabWidget::pane { border:none; } "
"QTabBar::tab { background:transparent; color:%4; padding:6px 14px; "
" font-size:10px; font-weight:700; } "
- "QTabBar::tab:selected { color:%5; border-bottom:2px solid %6; }")
+ "QTabBar::tab:selected { color:%5; border-bottom:2px solid %6; } "
+ // Per-row Exit button styling lives HERE, applied once, instead of
+ // a setStyleSheet() (== full CSS reparse) per button per refresh.
+ "QPushButton#blotterExitBtn { background:transparent; color:%7; "
+ " border:1px solid %7; padding:2px 10px; font-size:10px; font-weight:700; } "
+ "QPushButton#blotterExitBtn:hover { background:%7; color:%5; }")
.arg(colors::BG_BASE(), colors::TEXT_PRIMARY(), colors::BORDER_DIM(), colors::TEXT_SECONDARY(),
- colors::TEXT_PRIMARY(), colors::AMBER()));
+ colors::TEXT_PRIMARY(), colors::AMBER(), colors::NEGATIVE()));
auto* root = new QVBoxLayout(this);
root->setContentsMargins(0, 0, 0, 0);
@@ -111,6 +145,8 @@ void PaperBlotterPanel::build_ui() {
summary_ = new QLabel(tr("No open paper positions"), bar);
summary_->setStyleSheet(QStringLiteral("color:%1;font-size:11px;font-weight:600;background:transparent;")
.arg(colors::TEXT_SECONDARY()));
+ summary_state_ = 0;
+ summary_->setAccessibleName(tr("Paper trading summary"));
bar_lay->addWidget(summary_);
bar_lay->addStretch(1);
square_all_btn_ = new QPushButton(tr("SQUARE OFF ALL"), bar);
@@ -119,6 +155,7 @@ void PaperBlotterPanel::build_ui() {
" padding:5px 14px; font-size:10px; font-weight:700; } "
"QPushButton:disabled { background:%2; color:%3; }")
.arg(colors::NEGATIVE(), colors::BG_HOVER(), colors::TEXT_DIM()));
+ square_all_btn_->setAccessibleName(tr("Square off all open paper positions"));
connect(square_all_btn_, &QPushButton::clicked, this, &PaperBlotterPanel::square_off_all);
bar_lay->addWidget(square_all_btn_);
root->addWidget(bar);
@@ -129,6 +166,9 @@ void PaperBlotterPanel::build_ui() {
orders_ = make_table({tr("Account"), tr("Symbol"), tr("Product"), tr("Side"), tr("Type"), tr("Qty"), tr("Price"),
tr("Status"), tr("Time")});
trades_ = make_table({tr("Symbol"), tr("Side"), tr("Qty"), tr("Price"), tr("P&L"), tr("Time")});
+ positions_->setAccessibleName(tr("Open paper positions"));
+ orders_->setAccessibleName(tr("Working paper orders"));
+ trades_->setAccessibleName(tr("Executed paper trades"));
tabs_->addTab(positions_, tr("Positions"));
tabs_->addTab(orders_, tr("Orders"));
tabs_->addTab(trades_, tr("Trades"));
@@ -138,6 +178,17 @@ void PaperBlotterPanel::build_ui() {
void PaperBlotterPanel::showEvent(QShowEvent* e) {
QWidget::showEvent(e);
refresh();
+ if (poll_timer_)
+ poll_timer_->start();
+}
+
+void PaperBlotterPanel::hideEvent(QHideEvent* e) {
+ QWidget::hideEvent(e);
+ if (poll_timer_)
+ poll_timer_->stop();
+ if (refresh_timer_)
+ refresh_timer_->stop();
+ refresh_armed_ = false;
}
void PaperBlotterPanel::schedule_refresh() {
@@ -175,98 +226,148 @@ void PaperBlotterPanel::refresh() {
}
// ── Positions ───────────────────────────────────────────────────────────
- positions_->setRowCount(0);
- double total_pnl = 0.0;
- int open_count = 0;
- for (const auto& acct : accts) {
- for (const auto& p : pt_get_positions(acct.pid)) {
- if (p.quantity == 0.0)
- continue;
- const int r = positions_->rowCount();
- positions_->insertRow(r);
- const QColor pc = p.unrealized_pnl >= 0 ? pos_color : neg_color;
- positions_->setItem(r, 0, cell(acct.name));
- positions_->setItem(r, 1, cell(p.symbol));
- positions_->setItem(r, 2, cell(p.product.isEmpty() ? QStringLiteral("MIS") : p.product.toUpper()));
- positions_->setItem(r, 3,
- cell(p.side.toUpper(), p.side.compare(QLatin1String("long"), Qt::CaseInsensitive) == 0
- ? pos_color
- : neg_color));
- positions_->setItem(r, 4, cell(QString::number(p.quantity, 'f', 0)));
- positions_->setItem(r, 5, cell(QString::number(p.entry_price, 'f', 2)));
- positions_->setItem(r, 6, cell(QString::number(p.current_price, 'f', 2)));
- positions_->setItem(r, 7, cell(acct.glyph + QString::number(p.unrealized_pnl, 'f', 2), pc));
- const double notional = p.entry_price * p.quantity;
- const double pct = notional != 0.0 ? (p.unrealized_pnl / notional) * 100.0 : 0.0;
- positions_->setItem(r, 8, cell(QString::number(pct, 'f', 2) + QLatin1Char('%'), pc));
-
- auto* exit_btn = new QPushButton(tr("Exit"));
- exit_btn->setCursor(Qt::PointingHandCursor);
- exit_btn->setStyleSheet(
- QStringLiteral("QPushButton { background:transparent; color:%1; "
- " border:1px solid %1; padding:2px 10px; font-size:10px; "
- " font-weight:700; } QPushButton:hover { background:%1; color:#fff; }")
- .arg(colors::NEGATIVE()));
- const QString aid = acct.id, sym = p.symbol, prod = p.product;
- connect(exit_btn, &QPushButton::clicked, this,
- [this, aid, sym, prod]() { square_off_one(aid, sym, prod); });
- positions_->setCellWidget(r, 9, exit_btn);
-
- total_pnl += p.unrealized_pnl;
- ++open_count;
+ // Rows are REUSED in place (setRowCount to the new size, then overwrite) so
+ // a live blotter no longer reallocates every item + every Exit button on
+ // every tick, and the user's scroll offset survives the refresh.
+ {
+ ScrollKeeper keep(positions_);
+ int r = 0;
+ double total_pnl = 0.0;
+ for (const auto& acct : accts) {
+ for (const auto& p : pt_get_positions(acct.pid)) {
+ if (p.quantity == 0.0)
+ continue;
+ if (positions_->rowCount() <= r)
+ positions_->setRowCount(r + 1);
+
+ const QColor pc = p.unrealized_pnl >= 0 ? pos_color : neg_color;
+ set_cell(positions_, r, 0, acct.name);
+ set_cell(positions_, r, 1, p.symbol);
+ set_cell(positions_, r, 2, p.product.isEmpty() ? QStringLiteral("MIS") : p.product.toUpper());
+ set_cell(positions_, r, 3, p.side.toUpper(),
+ p.side.compare(QLatin1String("long"), Qt::CaseInsensitive) == 0 ? pos_color : neg_color);
+ set_cell(positions_, r, 4, QString::number(p.quantity, 'f', 0));
+ set_cell(positions_, r, 5, QString::number(p.entry_price, 'f', 2));
+ set_cell(positions_, r, 6, QString::number(p.current_price, 'f', 2));
+ set_cell(positions_, r, 7, acct.glyph + QString::number(p.unrealized_pnl, 'f', 2), pc);
+ const double notional = p.entry_price * p.quantity;
+ const double pct = notional != 0.0 ? (p.unrealized_pnl / notional) * 100.0 : 0.0;
+ set_cell(positions_, r, 8, QString::number(pct, 'f', 2) + QLatin1Char('%'), pc);
+
+ // Reuse the row's existing Exit button; only its bound
+ // account/symbol/product change. The click handler reads them
+ // from dynamic properties so the connection is made once.
+ auto* exit_btn = qobject_cast<QPushButton*>(positions_->cellWidget(r, 9));
+ if (!exit_btn) {
+ exit_btn = new QPushButton(tr("Exit"));
+ exit_btn->setObjectName(QStringLiteral("blotterExitBtn"));
+ exit_btn->setCursor(Qt::PointingHandCursor);
+ connect(exit_btn, &QPushButton::clicked, this, [this, exit_btn]() {
+ square_off_one(exit_btn->property("fnAccountId").toString(),
+ exit_btn->property("fnSymbol").toString(),
+ exit_btn->property("fnProduct").toString());
+ });
+ positions_->setCellWidget(r, 9, exit_btn);
+ }
+ exit_btn->setProperty("fnAccountId", acct.id);
+ exit_btn->setProperty("fnSymbol", p.symbol);
+ exit_btn->setProperty("fnProduct", p.product);
+ exit_btn->setAccessibleName(tr("Exit %1 position").arg(p.symbol));
+ exit_btn->setToolTip(tr("Close %1 at market").arg(p.symbol));
+
+ total_pnl += p.unrealized_pnl;
+ ++r;
+ }
+ }
+ if (positions_->rowCount() != r)
+ positions_->setRowCount(r); // drops surplus rows (items + widgets)
+
+ // Column auto-sizing measures every cell; only re-run it when the row
+ // shape actually changed, not on every price tick.
+ if (last_positions_rows_ != r) {
+ positions_->resizeColumnsToContents();
+ last_positions_rows_ = r;
}
- }
- positions_->resizeColumnsToContents();
- square_all_btn_->setEnabled(open_count > 0);
- if (open_count == 0) {
- summary_->setText(tr("No open paper positions"));
- summary_->setStyleSheet(QStringLiteral("color:%1;font-size:11px;font-weight:600;background:transparent;")
- .arg(colors::TEXT_SECONDARY()));
- } else {
- const QString glyph = accts.isEmpty() ? QStringLiteral("$") : accts.first().glyph;
- summary_->setText(tr("%1 open · unrealized %2%3").arg(open_count).arg(glyph).arg(total_pnl, 0, 'f', 2));
- summary_->setStyleSheet(QStringLiteral("color:%1;font-size:11px;font-weight:700;background:transparent;")
- .arg(total_pnl >= 0 ? colors::POSITIVE() : colors::NEGATIVE()));
+ square_all_btn_->setEnabled(r > 0);
+ update_summary(r, total_pnl, accts.isEmpty() ? QStringLiteral("$") : accts.first().glyph);
}
// ── Working orders (pending only) ─────────────────────────────────────────
- orders_->setRowCount(0);
- for (const auto& acct : accts) {
- for (const auto& o : pt_get_orders(acct.pid, QStringLiteral("pending"))) {
- const int r = orders_->rowCount();
- orders_->insertRow(r);
- orders_->setItem(r, 0, cell(acct.name));
- orders_->setItem(r, 1, cell(o.symbol));
- orders_->setItem(r, 2, cell(o.product.isEmpty() ? QStringLiteral("MIS") : o.product.toUpper()));
- orders_->setItem(r, 3, cell(o.side.toUpper()));
- orders_->setItem(r, 4, cell(o.order_type.toUpper()));
- orders_->setItem(r, 5, cell(QString::number(o.quantity, 'f', 0)));
- orders_->setItem(r, 6, cell(o.price ? QString::number(*o.price, 'f', 2) : tr("MKT")));
- orders_->setItem(r, 7, cell(o.status.toUpper()));
- const QDateTime dt = QDateTime::fromString(o.created_at, Qt::ISODate).toLocalTime();
- orders_->setItem(r, 8, cell(dt.isValid() ? dt.toString("HH:mm:ss") : o.created_at));
+ {
+ ScrollKeeper keep(orders_);
+ int r = 0;
+ for (const auto& acct : accts) {
+ for (const auto& o : pt_get_orders(acct.pid, QStringLiteral("pending"))) {
+ if (orders_->rowCount() <= r)
+ orders_->setRowCount(r + 1);
+ set_cell(orders_, r, 0, acct.name);
+ set_cell(orders_, r, 1, o.symbol);
+ set_cell(orders_, r, 2, o.product.isEmpty() ? QStringLiteral("MIS") : o.product.toUpper());
+ set_cell(orders_, r, 3, o.side.toUpper());
+ set_cell(orders_, r, 4, o.order_type.toUpper());
+ set_cell(orders_, r, 5, QString::number(o.quantity, 'f', 0));
+ set_cell(orders_, r, 6, o.price ? QString::number(*o.price, 'f', 2) : tr("MKT"));
+ set_cell(orders_, r, 7, o.status.toUpper());
+ const QDateTime dt = QDateTime::fromString(o.created_at, Qt::ISODate).toLocalTime();
+ set_cell(orders_, r, 8, dt.isValid() ? dt.toString("HH:mm:ss") : o.created_at);
+ ++r;
+ }
+ }
+ if (orders_->rowCount() != r)
+ orders_->setRowCount(r);
+ if (last_orders_rows_ != r) {
+ orders_->resizeColumnsToContents();
+ last_orders_rows_ = r;
}
}
- orders_->resizeColumnsToContents();
// ── Executed trades (recent) ──────────────────────────────────────────────
- trades_->setRowCount(0);
- for (const auto& acct : accts) {
- for (const auto& t : pt_get_trades(acct.pid, 50)) {
- const int r = trades_->rowCount();
- trades_->insertRow(r);
- trades_->setItem(r, 0, cell(t.symbol));
- trades_->setItem(r, 1, cell(t.side.toUpper()));
- trades_->setItem(r, 2, cell(QString::number(t.quantity, 'f', 0)));
- trades_->setItem(r, 3, cell(QString::number(t.price, 'f', 2)));
- const QColor tc = t.pnl >= 0 ? pos_color : neg_color;
- trades_->setItem(r, 4, cell(acct.glyph + QString::number(t.pnl, 'f', 2), tc));
- const QDateTime dt = QDateTime::fromString(t.timestamp, Qt::ISODate).toLocalTime();
- trades_->setItem(r, 5, cell(dt.isValid() ? dt.toString("MM-dd HH:mm") : t.timestamp));
+ {
+ ScrollKeeper keep(trades_);
+ int r = 0;
+ for (const auto& acct : accts) {
+ for (const auto& t : pt_get_trades(acct.pid, 50)) {
+ if (trades_->rowCount() <= r)
+ trades_->setRowCount(r + 1);
+ set_cell(trades_, r, 0, t.symbol);
+ set_cell(trades_, r, 1, t.side.toUpper());
+ set_cell(trades_, r, 2, QString::number(t.quantity, 'f', 0));
+ set_cell(trades_, r, 3, QString::number(t.price, 'f', 2));
+ set_cell(trades_, r, 4, acct.glyph + QString::number(t.pnl, 'f', 2),
+ t.pnl >= 0 ? pos_color : neg_color);
+ const QDateTime dt = QDateTime::fromString(t.timestamp, Qt::ISODate).toLocalTime();
+ set_cell(trades_, r, 5, dt.isValid() ? dt.toString("MM-dd HH:mm") : t.timestamp);
+ ++r;
+ }
+ }
+ if (trades_->rowCount() != r)
+ trades_->setRowCount(r);
+ if (last_trades_rows_ != r) {
+ trades_->resizeColumnsToContents();
+ last_trades_rows_ = r;
}
}
- trades_->resizeColumnsToContents();
+}
+
+void PaperBlotterPanel::update_summary(int open_count, double total_pnl, const QString& glyph) {
+ // Only reparse the label CSS when the semantic state flips — the text can
+ // change every tick, the stylesheet almost never does.
+ const int want = open_count == 0 ? 0 : (total_pnl >= 0 ? 1 : 2);
+ if (open_count == 0)
+ summary_->setText(tr("No open paper positions"));
+ else
+ summary_->setText(tr("%1 open · unrealized %2%3").arg(open_count).arg(glyph).arg(total_pnl, 0, 'f', 2));
+
+ if (want == summary_state_)
+ return;
+ summary_state_ = want;
+ if (want == 0)
+ summary_->setStyleSheet(QStringLiteral("color:%1;font-size:11px;font-weight:600;background:transparent;")
+ .arg(colors::TEXT_SECONDARY()));
+ else
+ summary_->setStyleSheet(QStringLiteral("color:%1;font-size:11px;font-weight:700;background:transparent;")
+ .arg(want == 1 ? colors::POSITIVE() : colors::NEGATIVE()));
}
void PaperBlotterPanel::square_off_one(const QString& account_id, const QString& symbol, const QString& product) {
diff --git a/fincept-qt/src/screens/common/PaperBlotterPanel.h b/fincept-qt/src/screens/common/PaperBlotterPanel.h
index 9e627dd20..3ae7e87c4 100644
--- a/fincept-qt/src/screens/common/PaperBlotterPanel.h
+++ b/fincept-qt/src/screens/common/PaperBlotterPanel.h
@@ -31,12 +31,15 @@ class PaperBlotterPanel : public QWidget {
protected:
void showEvent(QShowEvent* e) override;
+ void hideEvent(QHideEvent* e) override;
private:
void build_ui();
void schedule_refresh(); // coalesce bursts of mark signals into one reload
void square_off_all();
void square_off_one(const QString& account_id, const QString& symbol, const QString& product);
+ // Render the header summary; only touches the label stylesheet on a state flip.
+ void update_summary(int open_count, double total_pnl, const QString& glyph);
QTabWidget* tabs_ = nullptr;
QTableWidget* positions_ = nullptr;
@@ -46,7 +49,18 @@ class PaperBlotterPanel : public QWidget {
QPushButton* square_all_btn_ = nullptr;
QTimer* refresh_timer_ = nullptr; // throttle live refreshes
+ QTimer* poll_timer_ = nullptr; // visibility-gated safety-net poll (P3)
bool refresh_armed_ = false;
+
+ // Cached summary-label state so a live blotter doesn't reparse the label's
+ // CSS on every tick. -1 = never applied, 0 = neutral, 1 = gain, 2 = loss.
+ int summary_state_ = -1;
+
+ // Last row counts per table — resizeColumnsToContents() is O(rows x cols)
+ // text measurement, so only re-run it when the shape actually changed.
+ int last_positions_rows_ = -1;
+ int last_orders_rows_ = -1;
+ int last_trades_rows_ = -1;
};
} // namespace fincept::screens::common
diff --git a/fincept-qt/src/screens/common/feeds/FeedCardView.cpp b/fincept-qt/src/screens/common/feeds/FeedCardView.cpp
index 0df0660e8..af1a08d19 100644
--- a/fincept-qt/src/screens/common/feeds/FeedCardView.cpp
+++ b/fincept-qt/src/screens/common/feeds/FeedCardView.cpp
@@ -51,6 +51,19 @@ class ClickableCard : public QFrame {
} // namespace
FeedCardView::FeedCardView(QWidget* parent) : QWidget(parent) {
+ using namespace fincept::ui;
+ // One stylesheet for the whole card list, applied once here instead of a
+ // setStyleSheet() (== full CSS reparse) on every card and every child label
+ // on every feed refresh. A 50-item feed refreshing on its poll interval was
+ // reparsing ~200 stylesheets per tick.
+ setStyleSheet(QString("#feedCard { background:%1; border:1px solid %2; border-radius:4px; }"
+ "#feedCard:hover { background:%3; }"
+ "#feedCardMeta { color:%4; font-size:10px; font-weight:700; }"
+ "#feedCardTitle { color:%5; font-size:12px; font-weight:600; }"
+ "#feedCardSummary { color:%6; font-size:11px; }")
+ .arg(colors::BG_SURFACE(), colors::BORDER_MED(), colors::BG_HOVER(), colors::TEXT_TERTIARY(),
+ colors::TEXT_PRIMARY(), colors::TEXT_SECONDARY()));
+
auto* outer = new QVBoxLayout(this);
outer->setContentsMargins(0, 0, 0, 0);
scroll_ = new QScrollArea(this);
@@ -67,12 +80,10 @@ FeedCardView::FeedCardView(QWidget* parent) : QWidget(parent) {
}
QWidget* FeedCardView::build_card(const FeedItem& it) {
- using namespace fincept::ui;
+ // All styling comes from the view-level stylesheet via object names — see
+ // the constructor. Nothing here calls setStyleSheet().
auto* card = new ClickableCard(it.link, nullptr);
card->setObjectName("feedCard");
- card->setStyleSheet(QString("#feedCard{background:%1;border:1px solid %2;border-radius:4px;}"
- "#feedCard:hover{background:%3;}")
- .arg(colors::BG_SURFACE(), colors::BORDER_MED(), colors::BG_HOVER()));
auto* v = new QVBoxLayout(card);
v->setContentsMargins(8, 6, 8, 6);
v->setSpacing(3);
@@ -81,22 +92,23 @@ QWidget* FeedCardView::build_card(const FeedItem& it) {
const QString when = rel.isEmpty() ? it.time : rel; // fall back to the absolute string
auto* meta =
new QLabel(when.isEmpty() ? QString("● %1").arg(it.source) : QString("● %1 · %2").arg(it.source, when));
- meta->setStyleSheet(QString("color:%1;font-size:10px;font-weight:700;").arg(colors::TEXT_TERTIARY()));
+ meta->setObjectName("feedCardMeta");
if (!it.time.isEmpty())
meta->setToolTip(it.time); // absolute parsed timestamp on hover
v->addWidget(meta);
auto* title = new QLabel(it.title);
+ title->setObjectName("feedCardTitle");
title->setWordWrap(true);
- title->setStyleSheet(QString("color:%1;font-size:12px;font-weight:600;").arg(colors::TEXT_PRIMARY()));
v->addWidget(title);
if (!it.summary.isEmpty()) {
auto* sum = new QLabel(it.summary);
+ sum->setObjectName("feedCardSummary");
sum->setWordWrap(true);
- sum->setStyleSheet(QString("color:%1;font-size:11px;").arg(colors::TEXT_SECONDARY()));
v->addWidget(sum);
}
+ card->setAccessibleName(it.title);
return card;
}
diff --git a/fincept-qt/src/screens/common/feeds/FeedConfigDialog.cpp b/fincept-qt/src/screens/common/feeds/FeedConfigDialog.cpp
index 0ff71fa8d..aa3e7f698 100644
--- a/fincept-qt/src/screens/common/feeds/FeedConfigDialog.cpp
+++ b/fincept-qt/src/screens/common/feeds/FeedConfigDialog.cpp
@@ -165,10 +165,33 @@ FeedConfigDialog::FeedConfigDialog(const FeedSubscription& initial, QWidget* par
connect(addFieldBtn, &QPushButton::clicked, this, [this]() { add_field_row({}); });
connect(testBtn, &QPushButton::clicked, this, &FeedConfigDialog::on_test);
connect(bb, &QDialogButtonBox::accepted, this, [this]() {
+ // A feed with no URL is unusable and used to be saved silently
+ // (FeedPanel then dropped it, so Save looked like it had done nothing).
+ if (url_->text().trimmed().isEmpty()) {
+ QMessageBox::information(this, tr("URL required"), tr("Enter the address of the feed you want to add."));
+ url_->setFocus();
+ return;
+ }
sub_ = collect();
accept();
});
connect(bb, &QDialogButtonBox::rejected, this, &QDialog::reject);
+
+ // ── Accessibility ─────────────────────────────────────────────────────────
+ name_->setAccessibleName(tr("Feed name"));
+ url_->setAccessibleName(tr("Feed URL"));
+ refresh_->setAccessibleName(tr("Refresh interval in seconds"));
+ display_->setAccessibleName(tr("Display mode"));
+ parse_->setAccessibleName(tr("Parse mode"));
+ format_->setAccessibleName(tr("Feed format"));
+ setTabOrder(name_, url_);
+ setTabOrder(url_, refresh_);
+ setTabOrder(refresh_, display_);
+ setTabOrder(display_, parse_);
+ setTabOrder(parse_, format_);
+ setTabOrder(format_, persist_);
+ setTabOrder(persist_, testBtn);
+ setTabOrder(testBtn, bb);
}
void FeedConfigDialog::update_manual_visibility() {
@@ -340,12 +363,23 @@ void FeedConfigDialog::apply_discovery(const DiscoveredSchema& schema) {
}
void FeedConfigDialog::on_test() {
+ if (url_->text().trimmed().isEmpty()) {
+ test_result_->setText(tr("✗ Enter a feed URL first."));
+ url_->setFocus();
+ return;
+ }
test_result_->setText(tr("Testing…"));
- FeedMonitor::instance().fetch_once(collect(), [this](bool ok, const QString& msg, const QVector<FeedItem>& items) {
+ // QPointer guard: fetch_once is async and the user can close the dialog
+ // before it returns. on_discover() already did this; on_test() captured a
+ // raw `this` and would write into a destroyed dialog.
+ QPointer<FeedConfigDialog> self(this);
+ FeedMonitor::instance().fetch_once(collect(), [self](bool ok, const QString& msg, const QVector<FeedItem>& items) {
+ if (!self)
+ return;
QString detail = msg;
for (int i = 0; i < items.size() && i < 3; ++i)
detail += "\n• " + (items[i].title.isEmpty() ? items[i].link : items[i].title);
- test_result_->setText((ok ? QStringLiteral("✓ ") : QStringLiteral("✗ ")) + detail);
+ self->test_result_->setText((ok ? QStringLiteral("✓ ") : QStringLiteral("✗ ")) + detail);
});
}
diff --git a/fincept-qt/src/screens/crypto_center/panels/ActiveLocksPanel.cpp b/fincept-qt/src/screens/crypto_center/panels/ActiveLocksPanel.cpp
index bf3730967..d83044f0d 100644
--- a/fincept-qt/src/screens/crypto_center/panels/ActiveLocksPanel.cpp
+++ b/fincept-qt/src/screens/crypto_center/panels/ActiveLocksPanel.cpp
@@ -197,7 +197,7 @@ void ActiveLocksPanel::apply_theme() {
" font-family:%5; font-size:9px; font-weight:700; letter-spacing:1.2px;"
" padding:2px 8px; }"
"QLabel#activeLocksPillDemo { color:%4; background:rgba(217,119,6,0.10);"
- " border:1px solid %12; font-family:%5; font-size:9px; font-weight:700;"
+ " border:1px solid %11; font-family:%5; font-size:9px; font-weight:700;"
" letter-spacing:1.2px; padding:2px 8px; }"
"QWidget#activeLocksBody { background:%1; }"
"QTableWidget#activeLocksTable { background:%1; color:%7; gridline-color:%3;"
@@ -215,6 +215,10 @@ void ActiveLocksPanel::apply_theme() {
" font-weight:700; background:transparent; }"
"QLabel#activeLocksErrorText { color:%9; font-family:%5; font-size:11px;"
" background:transparent; }")
+ // One arg per marker, in ascending marker order. QString::arg fills
+ // the LOWEST marker present, so a gap in the numbering silently
+ // shifts every later colour by one and warns "Argument missing" for
+ // the overflow.
.arg(BG_BASE(), // %1
BG_SURFACE(), // %2
BORDER_DIM(), // %3
@@ -225,8 +229,7 @@ void ActiveLocksPanel::apply_theme() {
BG_RAISED(), // %8
NEGATIVE()) // %9
.arg(BG_HOVER(), // %10
- BORDER_BRIGHT(), // %11
- QStringLiteral("#78350f")); // %12 darker amber
+ QStringLiteral("#78350f")); // %11 darker amber
setStyleSheet(ss);
}
@@ -310,7 +313,7 @@ void ActiveLocksPanel::rebuild_table() {
table_->setRowCount(0);
table_->hide();
empty_state_->show();
- summary_label_->setText(QStringLiteral("0 positions · 0 veFNCPT"));
+ summary_label_->setText(tr("0 positions · 0 veFNCPT"));
update_demo_chip(false);
return;
}
@@ -349,10 +352,8 @@ void ActiveLocksPanel::rebuild_table() {
table_->setItem(total_row, 3, new QTableWidgetItem(format_token(total_weight_ui, 1)));
table_->setItem(total_row, 4, new QTableWidgetItem(format_usdc(total_yield_ui)));
- summary_label_->setText(QStringLiteral("%1 position%2 · %3 veFNCPT")
- .arg(latest_.size())
- .arg(latest_.size() == 1 ? QString() : QStringLiteral("s"))
- .arg(format_token(total_weight_ui, 1)));
+ // Plural form is a translator's decision, not an English "s" suffix.
+ summary_label_->setText(tr("%n position(s) · %1 veFNCPT", "", latest_.size()).arg(format_token(total_weight_ui, 1)));
update_demo_chip(any_mock);
clear_error_strip();
}
diff --git a/fincept-qt/src/screens/crypto_center/panels/BuybackBurnPanel.cpp b/fincept-qt/src/screens/crypto_center/panels/BuybackBurnPanel.cpp
index 6594833a7..a73211d17 100644
--- a/fincept-qt/src/screens/crypto_center/panels/BuybackBurnPanel.cpp
+++ b/fincept-qt/src/screens/crypto_center/panels/BuybackBurnPanel.cpp
@@ -18,6 +18,8 @@
#include <QUrl>
#include <QVBoxLayout>
+#include <cmath>
+
namespace fincept::screens::panels {
namespace {
@@ -233,7 +235,7 @@ void BuybackBurnPanel::apply_theme() {
" font-family:%5; font-size:9px; font-weight:700; letter-spacing:1.2px;"
" padding:2px 8px; }"
"QLabel#buybackBurnPillDemo { color:%4; background:rgba(217,119,6,0.10);"
- " border:1px solid %12; font-family:%5; font-size:9px; font-weight:700;"
+ " border:1px solid %11; font-family:%5; font-size:9px; font-weight:700;"
" letter-spacing:1.2px; padding:2px 8px; }"
"QWidget#buybackBurnBody { background:%1; }"
@@ -251,7 +253,7 @@ void BuybackBurnPanel::apply_theme() {
"QPushButton#buybackBurnSig { color:%4; font-family:%5; font-size:11px;"
" text-decoration:underline; background:transparent; border:none;"
" padding:0; text-align:right; }"
- "QPushButton#buybackBurnSig:hover { color:%11; }"
+ "QPushButton#buybackBurnSig:hover { color:%10; }"
"QFrame#buybackBurnSeparator { color:%3; background:%3; }"
@@ -270,9 +272,13 @@ void BuybackBurnPanel::apply_theme() {
TEXT_PRIMARY(), // %7
BG_RAISED(), // %8
NEGATIVE()) // %9
- .arg(BG_HOVER(), // %10 (unused but reserved)
- BORDER_BRIGHT(), // %11
- QStringLiteral("#78350f")); // %12 darker amber
+ // One arg per marker, in ascending marker order — a
+ // marker cannot be "reserved" by passing an unused
+ // arg: QString::arg fills the LOWEST marker present,
+ // so the spare shifts every later colour by one and
+ // warns "Argument missing" for the overflow.
+ .arg(BORDER_BRIGHT(), // %10
+ QStringLiteral("#78350f")); // %11 darker amber
setStyleSheet(ss);
}
@@ -343,8 +349,12 @@ void BuybackBurnPanel::on_epoch_update(const QVariant& v) {
epoch_is_mock_ = e.is_mock;
update_demo_chip(epoch_is_mock_ || burn_total_is_mock_);
- epoch_window_->setText(
- QStringLiteral("epoch %1 · %2").arg(e.epoch_no).arg(format_window(e.start_ts_ms, e.end_ts_ms)));
+ // The DEMO pill sits at the far right of the head; on a wide panel it is
+ // easy to miss while reading dollar figures on the left. State it inline
+ // too — every number below is fabricated in this mode.
+ const QString window_text =
+ QStringLiteral("epoch %1 · %2").arg(e.epoch_no).arg(format_window(e.start_ts_ms, e.end_ts_ms));
+ epoch_window_->setText(e.is_mock ? tr("SAMPLE DATA · %1").arg(window_text) : window_text);
revenue_total_->setText(format_usd(e.revenue_total_usd));
revenue_split_->setText(tr("subs %1 · pred-mkt %2 · misc %3")
@@ -397,11 +407,15 @@ void BuybackBurnPanel::on_topic_error(const QString& topic, const QString& error
void BuybackBurnPanel::on_burn_signature_clicked() {
if (current_burn_signature_.isEmpty())
return;
- if (current_burn_signature_.startsWith(QStringLiteral("FinceptTreasury")) ||
+ // Authoritative mock test is the producer's own `is_mock` flag, not a
+ // guess at the shape of the fabricated signature string. The old
+ // name-sniffing missed any mock signature that didn't literally contain
+ // "FinceptTreasury"/"Mock" and sent the user to a 404 Solscan page for a
+ // burn that never happened.
+ if (epoch_is_mock_ || current_burn_signature_.startsWith(QStringLiteral("FinceptTreasury")) ||
current_burn_signature_.contains(QStringLiteral("Mock"))) {
- // Mock signature — Solscan would 404. Skip the navigation and
- // give a tooltip cue.
- burn_signature_link_->setToolTip(tr("Demo signature — connect a treasury endpoint for a real burn tx."));
+ burn_signature_link_->setToolTip(tr("Demo signature — no such transaction exists on-chain. "
+ "Configure fincept.treasury_endpoint for real burn data."));
return;
}
QDesktopServices::openUrl(QUrl(QStringLiteral("https://solscan.io/tx/") + current_burn_signature_));
diff --git a/fincept-qt/src/screens/crypto_center/panels/FeeDiscountPanel.cpp b/fincept-qt/src/screens/crypto_center/panels/FeeDiscountPanel.cpp
index f8693c57b..5911de381 100644
--- a/fincept-qt/src/screens/crypto_center/panels/FeeDiscountPanel.cpp
+++ b/fincept-qt/src/screens/crypto_center/panels/FeeDiscountPanel.cpp
@@ -15,6 +15,7 @@
#include <QShowEvent>
#include <QVBoxLayout>
+#include <algorithm>
#include <cmath>
namespace fincept::screens::panels {
diff --git a/fincept-qt/src/screens/crypto_center/panels/HoldingsTable.cpp b/fincept-qt/src/screens/crypto_center/panels/HoldingsTable.cpp
index 9f5245b5c..570175f83 100644
--- a/fincept-qt/src/screens/crypto_center/panels/HoldingsTable.cpp
+++ b/fincept-qt/src/screens/crypto_center/panels/HoldingsTable.cpp
@@ -14,11 +14,14 @@
#include <QLabel>
#include <QLocale>
#include <QPushButton>
+#include <QSet>
#include <QShowEvent>
#include <QTableWidget>
#include <QTableWidgetItem>
#include <QVBoxLayout>
+#include <algorithm>
+
namespace fincept::screens::panels {
namespace {
diff --git a/fincept-qt/src/screens/crypto_center/panels/LockPanel.cpp b/fincept-qt/src/screens/crypto_center/panels/LockPanel.cpp
index 50a4aae28..f22c4281e 100644
--- a/fincept-qt/src/screens/crypto_center/panels/LockPanel.cpp
+++ b/fincept-qt/src/screens/crypto_center/panels/LockPanel.cpp
@@ -11,6 +11,8 @@
#include "ui/theme/Theme.h"
#include <QButtonGroup>
+#include <QDateTime>
+#include <QDialog>
#include <QDoubleValidator>
#include <QFrame>
#include <QHBoxLayout>
@@ -26,6 +28,7 @@
#include <QStyle>
#include <QVBoxLayout>
+#include <algorithm>
#include <cmath>
namespace fincept::screens::panels {
@@ -52,6 +55,27 @@ double atomic_to_ui(quint64 raw, int decimals) {
return static_cast<double>(raw) / std::pow(10.0, std::max(0, decimals));
}
+/// Format a token amount for injection into the amount QLineEdit.
+/// Floors (never rounds up past the held balance) and omits group separators
+/// so the value round-trips through `QLocale::toDouble()` unchanged. The old
+/// `format_token(balance, 0)` rounded half-up, so MAX on 12 304.7 $FNCPT
+/// produced "12305" and `recompute_preview()` then reported
+/// "Amount exceeds available $FNCPT" — the MAX button could not be used.
+QString lock_amount_for_input(double v, int decimals) {
+ if (v <= 0.0)
+ return QStringLiteral("0");
+ int dp = decimals;
+ if (dp < 0)
+ dp = 0;
+ if (dp > 9)
+ dp = 9;
+ const double scale = std::pow(10.0, dp);
+ const double floored = std::floor(v * scale) / scale;
+ QLocale loc = QLocale::system();
+ loc.setNumberOptions(loc.numberOptions() | QLocale::OmitGroupSeparator);
+ return loc.toString(floored, 'f', dp);
+}
+
} // namespace
LockPanel::LockPanel(QWidget* parent) : QWidget(parent) {
@@ -234,6 +258,35 @@ void LockPanel::build_ui() {
connect(duration_group_, QOverload<int>::of(&QButtonGroup::idClicked), this, &LockPanel::on_duration_changed);
connect(max_button_, &QPushButton::clicked, this, &LockPanel::on_max_clicked);
connect(lock_button_, &QPushButton::clicked, this, &LockPanel::on_lock_clicked);
+
+ // ── Accessibility ─────────────────────────────────────────────────────
+ amount_input_->setAccessibleName(tr("Amount of FNCPT to lock"));
+ amount_input_->setAccessibleDescription(tr("Locked tokens cannot be withdrawn before the unlock date"));
+ max_button_->setAccessibleName(tr("Lock the maximum available balance"));
+ lock_button_->setAccessibleName(tr("Build and review lock transaction"));
+ available_label_->setAccessibleName(tr("Available FNCPT balance"));
+ weight_calc_->setAccessibleName(tr("Resulting veFNCPT weight"));
+ est_yield_->setAccessibleName(tr("Estimated yield upper bound"));
+ tier_preview_->setAccessibleName(tr("Billing tier after lock"));
+ status_label_->setAccessibleName(tr("Lock status"));
+ if (dur_3mo_)
+ dur_3mo_->setAccessibleName(tr("Lock for three months"));
+ if (dur_6mo_)
+ dur_6mo_->setAccessibleName(tr("Lock for six months"));
+ if (dur_1yr_)
+ dur_1yr_->setAccessibleName(tr("Lock for one year"));
+ if (dur_2yr_)
+ dur_2yr_->setAccessibleName(tr("Lock for two years"));
+ if (dur_4yr_)
+ dur_4yr_->setAccessibleName(tr("Lock for four years"));
+
+ setTabOrder(amount_input_, max_button_);
+ setTabOrder(max_button_, dur_3mo_);
+ setTabOrder(dur_3mo_, dur_6mo_);
+ setTabOrder(dur_6mo_, dur_1yr_);
+ setTabOrder(dur_1yr_, dur_2yr_);
+ setTabOrder(dur_2yr_, dur_4yr_);
+ setTabOrder(dur_4yr_, lock_button_);
}
void LockPanel::apply_theme() {
@@ -448,7 +501,9 @@ void LockPanel::on_vefncpt_update(const QVariant& v) {
void LockPanel::on_revenue_update(const QVariant& v) {
if (!v.canConvert<fincept::wallet::TreasuryRevenue>())
return;
- weekly_revenue_usd_ = v.value<fincept::wallet::TreasuryRevenue>().total_usd;
+ const auto rev = v.value<fincept::wallet::TreasuryRevenue>();
+ weekly_revenue_usd_ = rev.total_usd;
+ revenue_is_mock_ = rev.is_mock;
recompute_preview();
}
@@ -481,7 +536,7 @@ void LockPanel::on_max_clicked() {
if (fncpt_balance_ui_ <= 0.0)
return;
QSignalBlocker b(amount_input_);
- amount_input_->setText(format_token(fncpt_balance_ui_, 0));
+ amount_input_->setText(lock_amount_for_input(fncpt_balance_ui_, fncpt_decimals_));
recompute_preview();
}
@@ -529,10 +584,20 @@ void LockPanel::recompute_preview() {
const double stake_usd = amount_ui * fncpt_usd_price_;
const double pct_weekly = (stake_usd > 0.0) ? (100.0 * est_weekly / stake_usd) : 0.0;
if (weekly_revenue_usd_ > 0.0 && fncpt_usd_price_ > 0.0) {
- est_yield_->setText(tr("%1 / week (USDC) — %2% weekly real yield at %3 stake")
- .arg(format_usd(est_weekly, 0))
- .arg(QString::number(pct_weekly, 'f', 2))
- .arg(format_usd(stake_usd, 0)));
+ // The projection assumes the user is the ONLY locker (no global weight
+ // topic exists yet), so it is an upper bound, not an expectation. Say
+ // so on the line itself — an unqualified "$42 / week — 2.18% weekly
+ // real yield" reads as a forecast and is the kind of number people
+ // make irreversible 4-year lock decisions on. Prefix DEMO when the
+ // revenue feed is the producer's built-in mock.
+ QString yield_text = tr("≤ %1 / week (USDC) — ≤ %2% weekly at %3 stake "
+ "· upper bound, assumes no other lockers")
+ .arg(format_usd(est_weekly, 0))
+ .arg(QString::number(pct_weekly, 'f', 2))
+ .arg(format_usd(stake_usd, 0));
+ if (revenue_is_mock_)
+ yield_text = tr("DEMO · ") + yield_text;
+ est_yield_->setText(yield_text);
} else {
est_yield_->setText(tr("waiting for revenue + spot price…"));
}
@@ -589,7 +654,20 @@ void LockPanel::set_busy(bool busy) {
btn->setEnabled(!busy);
}
max_button_->setEnabled(!busy);
- lock_button_->setEnabled(!busy);
+ if (busy) {
+ lock_button_->setEnabled(false);
+ return;
+ }
+ // Un-busying must NOT blanket-enable LOCK: that re-armed the button in
+ // mock mode (fincept_lock not deployed), with an empty amount, or with an
+ // amount above the balance. Re-derive the gate instead. recompute_preview
+ // reads busy_ (already false) and applies program_is_configured() +
+ // amount/balance checks.
+ if (current_pubkey_.isEmpty()) {
+ lock_button_->setEnabled(false);
+ return;
+ }
+ recompute_preview();
}
// ── Submit flow ────────────────────────────────────────────────────────────
@@ -601,10 +679,18 @@ void LockPanel::on_lock_clicked() {
return;
const Duration d = current_duration();
- // Build the atomic amount string for the program. Multiply at full
- // precision via integer math to avoid double-rounding.
+ // Build the atomic amount string for the program.
+ //
+ // `static_cast<quint64>` TRUNCATES, and `amount_ui * 10^decimals` is not
+ // exact in binary: 8.7 × 1e6 evaluates to 8699999.999999999, which
+ // truncated escrows 8.699999 $FNCPT instead of 8.7. Round to the nearest
+ // atomic unit instead. Rounding can never exceed the balance because
+ // `amount_ui <= fncpt_balance_ui_` was checked above and the balance is
+ // itself an exact multiple of one atomic unit.
const auto power = std::pow(10.0, fncpt_decimals_);
- const QString amount_raw = QString::number(static_cast<quint64>(amount_ui * power));
+ const double atomic = amount_ui * power;
+ const QString amount_raw =
+ QString::number(atomic > 0.0 ? static_cast<quint64>(std::llround(atomic)) : static_cast<quint64>(0));
set_busy(true);
clear_error_strip();
@@ -633,6 +719,15 @@ void LockPanel::on_lock_clicked() {
summary.rows.append(
{self->tr("AMOUNT"), QStringLiteral("%1 $FNCPT").arg(format_token(amount_ui, 0)), true});
summary.rows.append({self->tr("DURATION"), fincept::wallet::StakingService::label_for(d), true});
+ // The exact unlock instant, not just "4 YR". This is the single
+ // most consequential fact about an irreversible lock and it was
+ // not shown anywhere before signing.
+ const qint64 unlock_ms =
+ QDateTime::currentMSecsSinceEpoch() + fincept::wallet::StakingService::seconds_for(d) * 1000LL;
+ summary.rows.append({self->tr("UNLOCKS ON"),
+ QDateTime::fromMSecsSinceEpoch(unlock_ms).toString(QStringLiteral("yyyy-MM-dd HH:mm")),
+ true});
+ summary.rows.append({self->tr("WALLET"), self->current_pubkey_, true});
const double mult = fincept::wallet::StakingService::multiplier_for(d);
summary.rows.append(
{self->tr("WEIGHT"), QStringLiteral("%1 veFNCPT").arg(format_token(amount_ui * mult, 1)), true});
@@ -661,13 +756,21 @@ void LockPanel::on_lock_clicked() {
}
const auto sig = sr.value();
LOG_INFO("LockPanel", "submitted: " + sig);
- self->status_label_->setText(QObject::tr("Sent: %1…").arg(sig.left(12)));
+ // set_busy(false) re-derives the status line via
+ // recompute_preview(), so the submitted-signature
+ // message has to be written AFTER it or it is
+ // immediately overwritten by "Choose an amount…".
self->set_busy(false);
self->amount_input_->clear();
+ self->status_label_->setText(
+ QObject::tr("Sent: %1… (not yet confirmed on-chain)").arg(sig.left(12)));
fincept::wallet::WalletService::instance().force_balance_refresh();
});
});
- QObject::connect(dlg, &WalletActionConfirmDialog::cancelled, self, [self]() {
+ // `cancelled()` only fires from the CANCEL button. Esc / the window
+ // close box left the panel permanently busy. `rejected()` covers
+ // every dismissal path; the handler is idempotent.
+ QObject::connect(dlg, &QDialog::rejected, self, [self]() {
if (!self)
return;
self->set_busy(false);
diff --git a/fincept-qt/src/screens/crypto_center/panels/LockPanel.h b/fincept-qt/src/screens/crypto_center/panels/LockPanel.h
index d3bc5348d..e63f6427e 100644
--- a/fincept-qt/src/screens/crypto_center/panels/LockPanel.h
+++ b/fincept-qt/src/screens/crypto_center/panels/LockPanel.h
@@ -40,8 +40,12 @@ namespace fincept::screens::panels {
/// 1. Calls `StakingService::build_lock_tx(...)` — fails fast in mock mode.
/// 2. On success, opens `WalletActionConfirmDialog` with decoded summary.
/// 3. On confirm, forwards to `WalletService::sign_and_send`.
-/// 4. Polls `getSignatureStatuses` until confirmed (reuses the SwapPanel
-/// pattern; encapsulated in `start_status_poll`).
+/// 4. **Not implemented yet:** unlike `SwapPanel`, this panel does NOT poll
+/// `getSignatureStatuses`. The status line reads "Sent … (not yet
+/// confirmed on-chain)" and the balance is refreshed optimistically. A
+/// lock that is rejected on-chain therefore shows no failure here — the
+/// user has to check the explorer. Wire `start_status_poll` (copy the
+/// SwapPanel implementation) when the fincept_lock program ships.
///
/// In mock mode the LOCK button is disabled with status "DEMO — fincept_lock
/// not deployed yet" and clicking it shows the explanation in the error strip.
@@ -122,6 +126,11 @@ class LockPanel : public QWidget {
int fncpt_decimals_ = 6;
double fncpt_usd_price_ = 0.0;
double weekly_revenue_usd_ = 0.0;
+ /// True when the `treasury:revenue` payload the yield projection is built
+ /// from is the producer's built-in mock (worker endpoint unconfigured).
+ /// Drives the "DEMO" prefix on the EST. YIELD line — a fabricated revenue
+ /// figure must never be rendered as if it were a real projection.
+ bool revenue_is_mock_ = false;
quint64 current_user_weight_raw_ = 0;
fincept::wallet::TierStatus::Tier current_tier_ = fincept::wallet::TierStatus::Tier::Free;
diff --git a/fincept-qt/src/screens/crypto_center/panels/SupplyChartPanel.cpp b/fincept-qt/src/screens/crypto_center/panels/SupplyChartPanel.cpp
index 050c9f8c8..b1448656b 100644
--- a/fincept-qt/src/screens/crypto_center/panels/SupplyChartPanel.cpp
+++ b/fincept-qt/src/screens/crypto_center/panels/SupplyChartPanel.cpp
@@ -22,7 +22,9 @@
#include <QVBoxLayout>
#include <QValueAxis>
+#include <algorithm>
#include <cmath>
+#include <limits>
namespace fincept::screens::panels {
@@ -176,7 +178,7 @@ void SupplyChartPanel::apply_theme() {
" font-family:%5; font-size:9px; font-weight:700; letter-spacing:1.2px;"
" padding:2px 8px; }"
"QLabel#supplyChartPillDemo { color:%4; background:rgba(217,119,6,0.10);"
- " border:1px solid %12; font-family:%5; font-size:9px; font-weight:700;"
+ " border:1px solid %10; font-family:%5; font-size:9px; font-weight:700;"
" letter-spacing:1.2px; padding:2px 8px; }"
"QWidget#supplyChartBody { background:%1; }"
@@ -195,9 +197,11 @@ void SupplyChartPanel::apply_theme() {
TEXT_PRIMARY(), // %7
BG_RAISED(), // %8
NEGATIVE()) // %9
- .arg(BG_HOVER(), // %10
- BORDER_BRIGHT(), // %11
- QStringLiteral("#78350f")); // %12 darker amber
+ // One arg per marker, in ascending marker order —
+ // QString::arg fills the LOWEST marker present, so a
+ // spare arg shifts every later colour by one and
+ // warns "Argument missing" for the overflow.
+ .arg(QStringLiteral("#78350f")); // %10 darker amber
setStyleSheet(ss);
}
@@ -316,9 +320,16 @@ void SupplyChartPanel::update_demo_chip(bool is_mock) {
if (is_mock) {
status_pill_->setText(tr("DEMO"));
status_pill_->setObjectName(QStringLiteral("supplyChartPillDemo"));
+ // The chart itself carries no visual mock cue, so name it in the
+ // title as well — a fabricated supply curve read as real is exactly
+ // the class of defect this panel must not ship.
+ if (title_)
+ title_->setText(tr("SUPPLY CHART · 12 MONTHS · SAMPLE DATA"));
} else {
status_pill_->setText(tr("LIVE"));
status_pill_->setObjectName(QStringLiteral("supplyChartPill"));
+ if (title_)
+ title_->setText(tr("SUPPLY CHART · 12 MONTHS"));
}
status_pill_->style()->unpolish(status_pill_);
status_pill_->style()->polish(status_pill_);
diff --git a/fincept-qt/src/screens/crypto_center/panels/SwapPanel.cpp b/fincept-qt/src/screens/crypto_center/panels/SwapPanel.cpp
index 0c102e48c..217dd9d8c 100644
--- a/fincept-qt/src/screens/crypto_center/panels/SwapPanel.cpp
+++ b/fincept-qt/src/screens/crypto_center/panels/SwapPanel.cpp
@@ -13,6 +13,7 @@
#include "ui/theme/Theme.h"
#include <QComboBox>
+#include <QDateTime>
#include <QDoubleValidator>
#include <QFrame>
#include <QHBoxLayout>
@@ -22,12 +23,15 @@
#include <QLocale>
#include <QPointer>
#include <QPushButton>
+#include <QSet>
#include <QShowEvent>
#include <QSignalBlocker>
#include <QTimer>
+#include <QUrl>
#include <QVBoxLayout>
#include <algorithm>
+#include <cmath>
namespace fincept::screens::panels {
@@ -39,6 +43,11 @@ constexpr int kMaxSlippageBps = 500;
constexpr double kDefaultPriorityFeeSol = 0.00005;
constexpr int kStatusPollMs = 1500;
constexpr int kStatusPollMaxAttempts = 40; // 60 s of polling
+/// A spot price older than this is not trustworthy enough to size a swap on.
+/// We still let the user submit (PumpSwap fills at execution and slippage
+/// caps the damage) but the staleness is stated in the ticket and repeated
+/// in the confirm dialog.
+constexpr qint64 kPriceStaleMs = 60 * 1000;
QString font_stack() {
return QStringLiteral("'Consolas','Cascadia Mono','JetBrains Mono','SF Mono',monospace");
@@ -50,6 +59,30 @@ QString format_token(double v, int max_dp = 4) {
return QLocale::system().toString(v, 'f', max_dp);
}
+/// Format a token amount for injection into the amount QLineEdit.
+///
+/// Two properties matter here and neither is optional:
+/// 1. **Floor, never round.** `QLocale::toString(v,'f',dp)` rounds half-up,
+/// so MAX on a balance of 12 304.7 with dp=0 produced "12305" — more than
+/// the wallet holds — and `can_submit()` then silently refused the swap.
+/// 2. **No group separators.** The string is read back with
+/// `QLocale::toDouble()` and validated by a QDoubleValidator; a thousands
+/// separator round-trips inconsistently across locales.
+QString swap_amount_for_input(double v, int decimals) {
+ if (v <= 0.0)
+ return QStringLiteral("0");
+ int dp = decimals;
+ if (dp < 0)
+ dp = 0;
+ if (dp > 9)
+ dp = 9;
+ const double scale = std::pow(10.0, dp);
+ const double floored = std::floor(v * scale) / scale;
+ QLocale loc = QLocale::system();
+ loc.setNumberOptions(loc.numberOptions() | QLocale::OmitGroupSeparator);
+ return loc.toString(floored, 'f', dp);
+}
+
QString format_bps(int bps) {
return QStringLiteral("%1.%2%").arg(bps / 100).arg(bps % 100, 2, 10, QChar('0'));
}
@@ -289,6 +322,27 @@ void SwapPanel::build_ui() {
connect(amount_input_, &QLineEdit::textEdited, this, &SwapPanel::on_amount_changed);
connect(max_button_, &QPushButton::clicked, this, &SwapPanel::on_max_clicked);
connect(swap_button_, &QPushButton::clicked, this, &SwapPanel::on_swap_clicked);
+
+ // ── Accessibility ─────────────────────────────────────────────────────
+ // Every control that carries or moves money gets a spoken name, and the
+ // ticket has an explicit tab order (amount → from → MAX → to → SWAP) so
+ // a keyboard user walks the ticket in the order they reason about it
+ // rather than in widget-construction order.
+ amount_input_->setAccessibleName(tr("Amount to pay"));
+ amount_input_->setAccessibleDescription(tr("Quantity of the FROM token to swap"));
+ from_combo_->setAccessibleName(tr("Pay with token"));
+ to_combo_->setAccessibleName(tr("Receive token"));
+ max_button_->setAccessibleName(tr("Use maximum available balance"));
+ swap_button_->setAccessibleName(tr("Build and review swap transaction"));
+ out_amount_label_->setAccessibleName(tr("Estimated amount received"));
+ in_balance_label_->setAccessibleName(tr("Available balance"));
+ status_label_->setAccessibleName(tr("Swap status"));
+ error_text_->setAccessibleName(tr("Swap error"));
+
+ setTabOrder(amount_input_, from_combo_);
+ setTabOrder(from_combo_, max_button_);
+ setTabOrder(max_button_, to_combo_);
+ setTabOrder(to_combo_, swap_button_);
}
void SwapPanel::apply_theme() {
@@ -403,7 +457,10 @@ void SwapPanel::on_wallet_disconnected() {
sol_holding_.amount_raw = QStringLiteral("0");
price_usd_.clear();
price_sol_.clear();
+ price_ts_.clear();
price_topic_.clear();
+ last_quote_age_ms_ = -1;
+ status_label_->setTextFormat(Qt::PlainText);
rebuild_from_combo();
rebuild_to_combo();
in_balance_label_->setText(tr("Balance: —"));
@@ -500,6 +557,7 @@ void SwapPanel::on_price_update(const QString& mint, const QVariant& v) {
return;
price_usd_.insert(mint, p.usd);
price_sol_.insert(mint, p.sol);
+ price_ts_.insert(mint, p.ts_ms > 0 ? p.ts_ms : QDateTime::currentMSecsSinceEpoch());
recompute_estimate();
}
@@ -564,7 +622,9 @@ void SwapPanel::on_max_clicked() {
if (is_native_sol(from_mint_))
bal = std::max(0.0, bal - 0.005);
QSignalBlocker b(amount_input_);
- amount_input_->setText(format_token(bal, 6));
+ // Floor at the token's own decimals so the value can never exceed the
+ // held balance (which would make can_submit() reject MAX outright).
+ amount_input_->setText(swap_amount_for_input(bal, h->decimals));
on_amount_changed(amount_input_->text());
}
@@ -586,10 +646,15 @@ void SwapPanel::rebuild_from_combo() {
// WalletBalanceProducer); skip the wSOL entry from `tokens` to avoid a
// duplicate (native SOL is already at index 0). Same for unverified
// tokens unless the user opted in via SettingsTab.
+ // SettingsTab / HoldingsTable persist this flag as "true"/"false"; the old
+ // comparison against "1" here never matched, so the user's opt-in was
+ // silently ignored in the FROM combo. Accept both spellings.
bool show_unverified = false;
auto sr = SecureStorage::instance().retrieve(QStringLiteral("wallet.show_unverified_tokens"));
- if (sr.is_ok())
- show_unverified = (sr.value() == QLatin1String("1"));
+ if (sr.is_ok()) {
+ const QString v = sr.value().trimmed();
+ show_unverified = (v.compare(QLatin1String("true"), Qt::CaseInsensitive) == 0) || v == QLatin1String("1");
+ }
for (const auto& t : latest_balance_.tokens) {
if (is_native_sol(t.mint))
@@ -677,27 +742,41 @@ void SwapPanel::resubscribe_prices() {
if (!isVisible())
return;
auto& hub = fincept::datahub::DataHub::instance();
- // Drop any prior price subs we own before resubscribing the active legs.
- // (We can't selectively unsubscribe by topic; unsubscribe(this) drops
- // everything including the balance topic. Resubscribe both legs +
- // balance every time — it's cheap and keeps lifetimes obvious.)
- hub.unsubscribe(this);
- price_topic_.clear();
- if (!current_balance_topic_.isEmpty()) {
- hub.subscribe(this, current_balance_topic_, [this](const QVariant& v) { on_balance_update(v); });
+ // NOTE — do NOT `unsubscribe(this)` here. This method is reached from
+ // `on_balance_update`, which is itself a hub callback. Dropping *all*
+ // subscriptions and re-subscribing the balance topic makes DataHub
+ // re-deliver the cached balance via `deliver_initial_value` (a queued
+ // invoke), which re-enters `on_balance_update` → `resubscribe_prices` →
+ // … forever. That spun the event loop at 100 % CPU for as long as the
+ // panel was visible. Diff the price topics instead and leave the balance
+ // subscription alone (mirrors HoldingsBar / HoldingsTable).
+ QSet<QString> wanted;
+ if (!from_mint_.isEmpty())
+ wanted.insert(from_mint_);
+ if (!to_mint_.isEmpty())
+ wanted.insert(to_mint_);
+
+ for (auto it = price_topic_.begin(); it != price_topic_.end();) {
+ if (!wanted.contains(it.key())) {
+ hub.unsubscribe(this, it.value());
+ price_usd_.remove(it.key());
+ price_sol_.remove(it.key());
+ price_ts_.remove(it.key());
+ it = price_topic_.erase(it);
+ } else {
+ ++it;
+ }
}
- auto sub_price = [this, &hub](const QString& mint) {
- if (mint.isEmpty())
- return;
+ for (const auto& mint : wanted) {
+ if (price_topic_.contains(mint))
+ continue;
const auto topic = price_topic_for(mint);
price_topic_.insert(mint, topic);
hub.subscribe(this, topic, [this, mint](const QVariant& v) { on_price_update(mint, v); });
hub.request(topic, /*force=*/false);
- };
- sub_price(from_mint_);
- sub_price(to_mint_);
+ }
}
void SwapPanel::update_balance_label() {
@@ -733,19 +812,35 @@ void SwapPanel::recompute_estimate() {
}
// SOL-denominated cross: out_units = in_units * (from_sol / to_sol).
+ // `est_out_mid` is the unadjusted cross; `est_out_min` is what the user is
+ // guaranteed at worst given the slippage budget. Both are surfaced — the
+ // panel used to show only the min under an "EST." caption while the confirm
+ // dialog showed only the mid, so the two screens disagreed by the whole
+ // slippage budget on the single number the user is checking.
const double slippage_factor = 1.0 - (slippage_pct() / 100.0);
- const double est_out = ui_amount * (from_sol / to_sol) * slippage_factor;
+ const double est_out_mid = ui_amount * (from_sol / to_sol);
+ const double est_out_min = est_out_mid * slippage_factor;
const double est_usd = ui_amount * from_usd;
const QString to_sym = resolve_symbol(to_mint_);
const int dp = is_native_sol(to_mint_) ? 6 : (is_fncpt(to_mint_) ? 2 : 4);
- const QString out_text =
- QStringLiteral("≈ %1 %2 (~$%3)").arg(format_token(est_out, dp)).arg(to_sym).arg(format_token(est_usd, 2));
+ const QString out_text = QStringLiteral("≈ %1 %2 (min %3 · ~$%4)")
+ .arg(format_token(est_out_mid, dp))
+ .arg(to_sym)
+ .arg(format_token(est_out_min, dp))
+ .arg(format_token(est_usd, 2));
out_amount_label_->setText(out_text);
route_label_->setText(QStringLiteral("PumpSwap (auto)"));
impact_label_->setText(tr("set by PumpSwap; capped by slippage"));
slippage_label_->setText(format_bps(slippage_pct() * 100));
+ // Quote freshness — a crypto price with no age on it is dangerous right
+ // before a swap. Track the oldest of the two legs.
+ const qint64 now_ms = QDateTime::currentMSecsSinceEpoch();
+ const qint64 from_ts = price_ts_.value(from_mint_, 0);
+ const qint64 to_ts = price_ts_.value(to_mint_, 0);
+ last_quote_age_ms_ = (from_ts > 0 && to_ts > 0) ? (now_ms - std::min(from_ts, to_ts)) : -1;
+
if (!is_supported_pair()) {
// Show the estimate so the user understands what they're trying to
// do, but block submit and explain.
@@ -753,8 +848,15 @@ void SwapPanel::recompute_estimate() {
swap_button_->setEnabled(false);
return;
}
- status_label_->setText(tr("Ready. Click SWAP to build the transaction."));
- clear_error_strip();
+ if (last_quote_age_ms_ > kPriceStaleMs) {
+ show_error_strip(tr("Spot price is %1 s old — the estimate above may be wrong. "
+ "PumpSwap still fills at execution within your slippage budget.")
+ .arg(last_quote_age_ms_ / 1000));
+ status_label_->setText(tr("Ready — quote %1 s old.").arg(last_quote_age_ms_ / 1000));
+ } else {
+ clear_error_strip();
+ status_label_->setText(tr("Ready. Click SWAP to build the transaction."));
+ }
swap_button_->setEnabled(can_submit());
}
@@ -835,7 +937,11 @@ int SwapPanel::slippage_bps() const {
if (r.is_ok()) {
bool ok = false;
const auto v = r.value().toInt(&ok);
- if (ok && v >= 10 && v <= kMaxSlippageBps)
+ // Floor at 100 bps: PumpPortal takes an integer percent clamped to
+ // [1,5], so anything below 1.00 % is executed as 1.00 % anyway.
+ // Accepting a smaller stored value here only produced a display that
+ // disagreed with what was enforced.
+ if (ok && v >= kDefaultSlippageBps && v <= kMaxSlippageBps)
return v;
}
return kDefaultSlippageBps;
@@ -872,52 +978,72 @@ void SwapPanel::start_status_poll(const QString& sig) {
auto attempts = std::make_shared<int>(0);
auto* poll_timer = new QTimer(this);
poll_timer->setInterval(kStatusPollMs);
+
+ // A Solscan link so the user can independently verify the transaction
+ // landed — previously the only trace of a submitted swap was a truncated
+ // signature in a plain label.
+ const QString explorer_url = QStringLiteral("https://solscan.io/tx/") + sig;
+ status_label_->setTextFormat(Qt::RichText);
+ status_label_->setOpenExternalLinks(true);
+ status_label_->setTextInteractionFlags(Qt::TextBrowserInteraction);
+
QPointer<SwapPanel> guard = this;
- QObject::connect(poll_timer, &QTimer::timeout, this, [guard, rpc, sig, attempts, poll_timer]() {
- if (!guard) {
- poll_timer->stop();
- poll_timer->deleteLater();
- return;
- }
- if (++(*attempts) > kStatusPollMaxAttempts) {
- poll_timer->stop();
- poll_timer->deleteLater();
- guard->set_busy(false);
- guard->show_error_strip(QObject::tr("No confirmation after 60 s. Check Solscan."));
- guard->status_label_->setText(QObject::tr("Timed out."));
- return;
- }
- rpc->get_signature_statuses(
- QStringList{sig},
- [guard, sig, poll_timer](Result<std::vector<fincept::wallet::SolanaRpcClient::SignatureStatus>> r) {
- if (!guard)
- return;
- if (r.is_err())
- return; // transient — keep polling
- const auto& vec = r.value();
- if (vec.empty() || !vec[0].found)
- return;
- const auto& s = vec[0];
- if (!s.err.isEmpty()) {
- poll_timer->stop();
- poll_timer->deleteLater();
- guard->set_busy(false);
- guard->show_error_strip(QObject::tr("Tx failed on-chain: %1").arg(s.err));
- guard->status_label_->setText(QObject::tr("Reverted."));
- return;
- }
- if (s.confirmation_status == QStringLiteral("confirmed") ||
- s.confirmation_status == QStringLiteral("finalized")) {
- poll_timer->stop();
- poll_timer->deleteLater();
- guard->set_busy(false);
- guard->amount_input_->clear();
- guard->out_amount_label_->setText(QStringLiteral("—"));
- guard->status_label_->setText(QObject::tr("Confirmed: %1…").arg(sig.left(12)));
- fincept::wallet::WalletService::instance().force_balance_refresh();
- }
- });
- });
+ // `rpc` and `poll_timer` are children of the panel, so they die with it;
+ // but a swap-per-swap leak would still accumulate for a long-lived panel.
+ // stop_poll tears both down on every terminal outcome.
+ auto stop_poll = [rpc, poll_timer]() {
+ poll_timer->stop();
+ poll_timer->deleteLater();
+ rpc->deleteLater();
+ };
+ QObject::connect(poll_timer, &QTimer::timeout, this,
+ [guard, rpc, sig, explorer_url, attempts, poll_timer, stop_poll]() {
+ if (!guard) {
+ stop_poll();
+ return;
+ }
+ if (++(*attempts) > kStatusPollMaxAttempts) {
+ stop_poll();
+ guard->set_busy(false);
+ guard->show_error_strip(QObject::tr("No confirmation after 60 s. "
+ "The transaction may still land — check the explorer."));
+ guard->status_label_->setText(
+ QObject::tr("Timed out. <a href=\"%1\">View on Solscan</a>").arg(explorer_url));
+ return;
+ }
+ rpc->get_signature_statuses(
+ QStringList{sig},
+ [guard, sig, explorer_url,
+ stop_poll](Result<std::vector<fincept::wallet::SolanaRpcClient::SignatureStatus>> r) {
+ if (!guard)
+ return;
+ if (r.is_err())
+ return; // transient — keep polling
+ const auto& vec = r.value();
+ if (vec.empty() || !vec[0].found)
+ return;
+ const auto& s = vec[0];
+ if (!s.err.isEmpty()) {
+ stop_poll();
+ guard->set_busy(false);
+ guard->show_error_strip(QObject::tr("Tx failed on-chain: %1").arg(s.err));
+ guard->status_label_->setText(
+ QObject::tr("Reverted. <a href=\"%1\">View on Solscan</a>").arg(explorer_url));
+ return;
+ }
+ if (s.confirmation_status == QStringLiteral("confirmed") ||
+ s.confirmation_status == QStringLiteral("finalized")) {
+ stop_poll();
+ guard->set_busy(false);
+ guard->amount_input_->clear();
+ guard->out_amount_label_->setText(QStringLiteral("—"));
+ guard->status_label_->setText(QObject::tr("Confirmed %1… "
+ "<a href=\"%2\">View on Solscan</a>")
+ .arg(sig.left(12), explorer_url));
+ fincept::wallet::WalletService::instance().force_balance_refresh();
+ }
+ });
+ });
poll_timer->start();
}
@@ -952,16 +1078,21 @@ void SwapPanel::on_swap_clicked() {
const double from_sol_p = price_sol_.value(from_mint_, 0.0);
const double to_sol_p = price_sol_.value(to_mint_, 0.0);
const double est_out = (to_sol_p > 0.0) ? (ui_amount * from_sol_p / to_sol_p) : 0.0;
+ // Worst case the user is guaranteed. The panel shows both; the dialog used
+ // to show only the mid, which reads as a better fill than is contracted.
+ const double est_out_min = est_out * (1.0 - slip_pct / 100.0);
+ const qint64 quote_age_ms = last_quote_age_ms_;
set_busy(true);
clear_error_strip();
+ status_label_->setTextFormat(Qt::PlainText);
status_label_->setText(tr("Building swap transaction…"));
QPointer<SwapPanel> self = this;
svc->build_swap(
action, QString::fromLatin1(fincept::wallet::kFncptMint), ui_amount, denom_in_sol, pubkey, slip_pct,
kDefaultPriorityFeeSol,
- [self, ui_amount, buying_fncpt, est_out,
+ [self, ui_amount, buying_fncpt, est_out, est_out_min, quote_age_ms, pubkey,
slip_bps_for_display](Result<fincept::wallet::PumpFunSwapService::SwapTransaction> r) {
if (!self)
return;
@@ -980,7 +1111,12 @@ void SwapPanel::on_swap_clicked() {
self->status_label_->setText(QObject::tr("Validating with RPC…"));
auto* rpc = new fincept::wallet::SolanaRpcClient(self);
rpc->reload_endpoint();
- rpc->simulate_transaction(tx.tx_base64, [self, tx, ui_amount, buying_fncpt, est_out, slip_bps_for_display,
+ // Which cluster is actually going to execute this. Mainnet vs
+ // devnet confusion is silent otherwise — the panel chrome never
+ // says which RPC is configured.
+ const QString rpc_host = QUrl(rpc->http_endpoint()).host();
+ rpc->simulate_transaction(tx.tx_base64, [self, tx, ui_amount, buying_fncpt, est_out, est_out_min,
+ quote_age_ms, pubkey, rpc_host, slip_bps_for_display,
rpc](
Result<fincept::wallet::SolanaRpcClient::SimulationResult> sr) {
rpc->deleteLater();
@@ -1016,20 +1152,42 @@ void SwapPanel::on_swap_clicked() {
summary.rows.append(
{QObject::tr("YOU RECEIVE"),
QObject::tr("≈ %1 $FNCPT (PumpSwap fills at execution)").arg(format_token(est_out, 2)), true});
+ summary.rows.append({QObject::tr("MINIMUM RECEIVED"),
+ QStringLiteral("%1 $FNCPT").arg(format_token(est_out_min, 2)), true});
} else {
summary.rows.append(
{QObject::tr("YOU PAY"), QStringLiteral("%1 $FNCPT").arg(format_token(ui_amount, 2)), true});
summary.rows.append(
{QObject::tr("YOU RECEIVE"),
QObject::tr("≈ %1 SOL (PumpSwap fills at execution)").arg(format_token(est_out, 6)), true});
+ summary.rows.append({QObject::tr("MINIMUM RECEIVED"),
+ QStringLiteral("%1 SOL").arg(format_token(est_out_min, 6)), true});
}
summary.rows.append({QObject::tr("MAX SLIPPAGE"), format_bps(slip_bps_for_display), true});
summary.rows.append({QObject::tr("PRIORITY FEE"),
QStringLiteral("%1 SOL").arg(format_token(kDefaultPriorityFeeSol, 6)), true});
+ // Verifiable identity rows. The full mint and the full signing
+ // pubkey are printed verbatim — a truncated address is not
+ // something a user can check against their wallet.
+ summary.rows.append(
+ {QObject::tr("TOKEN MINT"), QString::fromLatin1(fincept::wallet::kFncptMint), true});
+ summary.rows.append({QObject::tr("SIGNING WALLET"), pubkey, true});
+ summary.rows.append({QObject::tr("NETWORK"),
+ rpc_host.isEmpty() ? QObject::tr("unknown RPC") : rpc_host, true});
+ summary.rows.append({QObject::tr("QUOTE AGE"),
+ quote_age_ms >= 0 ? QObject::tr("%1 s").arg(quote_age_ms / 1000)
+ : QObject::tr("unknown"),
+ true});
summary.rows.append({QObject::tr("RPC SIMULATION"),
QObject::tr("OK · %1 CU").arg(QString::number(sim.units_consumed)), true});
summary.warnings.append(QObject::tr("PumpSwap will reject the trade if execution drifts more than "
"the slippage tolerance above. Your funds stay in your wallet."));
+ if (quote_age_ms > kPriceStaleMs) {
+ summary.warnings.append(
+ QObject::tr("The spot price used for the estimate is %1 s old. The amounts above are "
+ "indicative only — the exchange rate is decided at execution.")
+ .arg(quote_age_ms / 1000));
+ }
summary.primary_button_text = QObject::tr("SWAP");
summary.primary_is_safe = true;
summary.arm_delay_ms = 1500;
@@ -1098,10 +1256,16 @@ void SwapPanel::on_swap_clicked() {
},
/*replace_recent_blockhash=*/false);
});
- QObject::connect(dlg, &WalletActionConfirmDialog::cancelled, self, [self]() {
+ // `cancelled()` only fires from the CANCEL button. Esc, the
+ // window close box and any programmatic reject() left the panel
+ // permanently busy (inputs disabled, SWAP dead) with no way
+ // out short of a wallet reconnect. `rejected()` covers every
+ // dismissal path and the handler is idempotent.
+ QObject::connect(dlg, &QDialog::rejected, self, [self]() {
if (!self)
return;
self->set_busy(false);
+ self->status_label_->setTextFormat(Qt::PlainText);
self->status_label_->setText(self->tr("Cancelled."));
});
dlg->setAttribute(Qt::WA_DeleteOnClose);
diff --git a/fincept-qt/src/screens/crypto_center/panels/SwapPanel.h b/fincept-qt/src/screens/crypto_center/panels/SwapPanel.h
index 9c9930ddb..5c54f1cd7 100644
--- a/fincept-qt/src/screens/crypto_center/panels/SwapPanel.h
+++ b/fincept-qt/src/screens/crypto_center/panels/SwapPanel.h
@@ -145,8 +145,14 @@ class SwapPanel : public QWidget {
QString pending_from_mint_;
QHash<QString, double> price_usd_; ///< mint → USD per 1 token
QHash<QString, double> price_sol_; ///< mint → SOL per 1 token
+ QHash<QString, qint64> price_ts_; ///< mint → unix ms of the last valid quote
QHash<QString, QString> price_topic_; ///< mint → topic (for unsubscribe)
bool busy_ = false;
+
+ /// Age (ms) of the oldest leg price used by the last `recompute_estimate`.
+ /// Surfaced in the ticket and repeated in the confirm dialog so the user
+ /// never sizes a swap on a silently-frozen quote. -1 = unknown.
+ qint64 last_quote_age_ms_ = -1;
};
} // namespace fincept::screens::panels
diff --git a/fincept-qt/src/screens/crypto_center/panels/TierPanel.cpp b/fincept-qt/src/screens/crypto_center/panels/TierPanel.cpp
index 51710dc04..0419e5a46 100644
--- a/fincept-qt/src/screens/crypto_center/panels/TierPanel.cpp
+++ b/fincept-qt/src/screens/crypto_center/panels/TierPanel.cpp
@@ -137,7 +137,7 @@ void TierPanel::apply_theme() {
" font-weight:600; letter-spacing:1.2px; background:transparent; }"
"QWidget#tierBody { background:%1; }"
"QFrame#tierRow { background:%8; border:1px solid %3; }"
- "QFrame#tierRowCurrent { background:rgba(217,119,6,0.10); border:1px solid %12; }"
+ "QFrame#tierRowCurrent { background:rgba(217,119,6,0.10); border:1px solid %9; }"
"QLabel#tierRowLabel { color:%4; font-family:%5; font-size:11px;"
" font-weight:700; letter-spacing:1.4px; background:transparent; }"
"QLabel#tierRowThreshold { color:%7; font-family:%5; font-size:11px;"
@@ -145,13 +145,19 @@ void TierPanel::apply_theme() {
"QLabel#tierRowUnlocks { color:%6; font-family:%5; font-size:11px;"
" background:transparent; }"
"QLabel#tierRowChipAchieved { color:%4; background:rgba(217,119,6,0.10);"
- " border:1px solid %12; font-family:%5; font-size:9px; font-weight:700;"
+ " border:1px solid %9; font-family:%5; font-size:9px; font-weight:700;"
" letter-spacing:1.2px; padding:2px 6px; }"
"QLabel#tierRowChipLocked { color:%6; background:transparent;"
" border:1px solid %3; font-family:%5; font-size:9px; font-weight:700;"
" letter-spacing:1.2px; padding:2px 6px; }"
"QLabel#tierFooter { color:%6; font-family:%5; font-size:10px;"
" background:transparent; padding-top:6px; }")
+ // One arg per marker, in ascending marker order.
+ // QString::arg fills the LOWEST marker present, so a
+ // gap in the numbering silently shifts every later
+ // colour by one and warns "Argument missing" for the
+ // overflow — that is how %12 used to be painted with
+ // NEGATIVE (#dc2626) instead of the dark amber.
.arg(BG_BASE(), // %1
BG_SURFACE(), // %2
BORDER_DIM(), // %3
@@ -160,10 +166,7 @@ void TierPanel::apply_theme() {
TEXT_TERTIARY(), // %6
TEXT_PRIMARY(), // %7
BG_RAISED(), // %8
- NEGATIVE()) // %9
- .arg(BG_HOVER(), // %10
- BORDER_BRIGHT(), // %11
- QStringLiteral("#78350f")); // %12 darker amber
+ QStringLiteral("#78350f")); // %9 darker amber
setStyleSheet(ss);
}
diff --git a/fincept-qt/src/screens/crypto_center/panels/TreasuryPanel.cpp b/fincept-qt/src/screens/crypto_center/panels/TreasuryPanel.cpp
index 619a55204..ecdfca8e5 100644
--- a/fincept-qt/src/screens/crypto_center/panels/TreasuryPanel.cpp
+++ b/fincept-qt/src/screens/crypto_center/panels/TreasuryPanel.cpp
@@ -158,7 +158,7 @@ void TreasuryPanel::apply_theme() {
" font-family:%5; font-size:9px; font-weight:700; letter-spacing:1.2px;"
" padding:2px 8px; }"
"QLabel#treasuryPillDemo { color:%4; background:rgba(217,119,6,0.10);"
- " border:1px solid %12; font-family:%5; font-size:9px; font-weight:700;"
+ " border:1px solid %11; font-family:%5; font-size:9px; font-weight:700;"
" letter-spacing:1.2px; padding:2px 8px; }"
"QWidget#treasuryBody { background:%1; }"
"QLabel#treasuryCaption { color:%6; font-family:%5; font-size:9px;"
@@ -171,7 +171,7 @@ void TreasuryPanel::apply_theme() {
"QPushButton#treasuryMultisig { color:%4; font-family:%5; font-size:11px;"
" text-decoration:underline; background:transparent; border:none;"
" padding:0; text-align:right; }"
- "QPushButton#treasuryMultisig:hover { color:%11; }"
+ "QPushButton#treasuryMultisig:hover { color:%10; }"
"QFrame#treasuryErrorStrip { background:rgba(220,38,38,0.10);"
" border:1px solid %9; }"
@@ -188,9 +188,12 @@ void TreasuryPanel::apply_theme() {
TEXT_PRIMARY(), // %7
BG_RAISED(), // %8
NEGATIVE()) // %9
- .arg(BG_HOVER(), // %10
- BORDER_BRIGHT(), // %11
- QStringLiteral("#78350f")); // %12 darker amber
+ // One arg per marker, in ascending marker order —
+ // QString::arg fills the LOWEST marker present, so a
+ // spare arg shifts every later colour by one and
+ // warns "Argument missing" for the overflow.
+ .arg(BORDER_BRIGHT(), // %10
+ QStringLiteral("#78350f")); // %11 darker amber
setStyleSheet(ss);
}
@@ -282,7 +285,18 @@ void TreasuryPanel::on_topic_error(const QString& topic, const QString& error) {
void TreasuryPanel::on_multisig_clicked() {
if (multisig_url_.isEmpty())
return;
- QDesktopServices::openUrl(QUrl(multisig_url_));
+ // `multisig_url_` arrives from the treasury endpoint — untrusted remote
+ // data driving QDesktopServices::openUrl. Without a scheme check a
+ // compromised or misconfigured worker could hand us `file:///…` (opens a
+ // local file/executable path in the shell) or a custom-protocol URL.
+ // Restrict to https, which is the only thing a Squads deeplink needs.
+ const QUrl url(multisig_url_);
+ if (!url.isValid() || url.scheme().compare(QLatin1String("https"), Qt::CaseInsensitive) != 0) {
+ show_error_strip(tr("Refusing to open a non-https treasury link: %1").arg(multisig_url_.left(120)));
+ LOG_WARN("TreasuryPanel", "blocked non-https multisig url");
+ return;
+ }
+ QDesktopServices::openUrl(url);
}
void TreasuryPanel::show_error_strip(const QString& msg) {
@@ -304,9 +318,16 @@ void TreasuryPanel::update_demo_chip() {
if (any_mock) {
status_pill_->setText(tr("DEMO"));
status_pill_->setObjectName(QStringLiteral("treasuryPillDemo"));
+ // A fabricated reserve figure presented like a real one is the single
+ // most misleading thing this panel can do, so the title says so too —
+ // the pill alone is easy to miss next to a bold amber TOTAL USD.
+ if (title_)
+ title_->setText(tr("TREASURY · SAMPLE DATA"));
} else {
status_pill_->setText(tr("LIVE"));
status_pill_->setObjectName(QStringLiteral("treasuryPill"));
+ if (title_)
+ title_->setText(tr("TREASURY"));
}
status_pill_->style()->unpolish(status_pill_);
status_pill_->style()->polish(status_pill_);
diff --git a/fincept-qt/src/screens/crypto_center/tabs/ActivityTab.h b/fincept-qt/src/screens/crypto_center/tabs/ActivityTab.h
index 93d82dc60..c2554d052 100644
--- a/fincept-qt/src/screens/crypto_center/tabs/ActivityTab.h
+++ b/fincept-qt/src/screens/crypto_center/tabs/ActivityTab.h
@@ -71,8 +71,8 @@ class ActivityTab : public QWidget {
QString current_pubkey_;
QString current_topic_;
QVector<Activity> latest_;
- Kind active_filter_kind_ = Kind::Other; // sentinel — `filter_all_` checked = no filter
- bool show_all_ = true;
+ // (Removed `active_filter_kind_` / `show_all_`: never read or written —
+ // `rebuild_table()` derives the active filter from the chips directly.)
};
} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/crypto_center/tabs/HomeTab.cpp b/fincept-qt/src/screens/crypto_center/tabs/HomeTab.cpp
index 7e75337bc..818b9f26c 100644
--- a/fincept-qt/src/screens/crypto_center/tabs/HomeTab.cpp
+++ b/fincept-qt/src/screens/crypto_center/tabs/HomeTab.cpp
@@ -5,6 +5,7 @@
#include "screens/crypto_center/panels/HoldingsTable.h"
#include "services/wallet/WalletService.h"
#include "services/wallet/WalletTypes.h"
+#include "storage/secure/SecureStorage.h"
#include "ui/theme/Theme.h"
#include <QApplication>
@@ -35,6 +36,33 @@ QString shorten_pubkey(const QString& pk) {
return pk.left(8) + QStringLiteral("…") + pk.right(8);
}
+/// Which Solana cluster the configured RPC actually points at.
+///
+/// This chip used to be the literal string "MAINNET" regardless of the RPC
+/// override, so a user pointed at devnet saw balances and swap tickets
+/// labelled MAINNET — exactly the testnet/mainnet confusion that turns a
+/// "harmless" test into a real transfer (or the reverse). Derive it.
+QString cluster_label() {
+ auto r = SecureStorage::instance().retrieve(QStringLiteral("solana.rpc_url"));
+ if (r.is_ok()) {
+ const QString url = r.value().toLower();
+ if (!url.isEmpty()) {
+ if (url.contains(QStringLiteral("devnet")))
+ return QStringLiteral("DEVNET");
+ if (url.contains(QStringLiteral("testnet")))
+ return QStringLiteral("TESTNET");
+ if (url.contains(QStringLiteral("localhost")) || url.contains(QStringLiteral("127.0.0.1")))
+ return QStringLiteral("LOCALNET");
+ if (url.contains(QStringLiteral("mainnet")))
+ return QStringLiteral("MAINNET");
+ return QStringLiteral("CUSTOM RPC");
+ }
+ }
+ // No override — SolanaRpcClient falls back to Helius mainnet or the public
+ // mainnet-beta endpoint, both of which are mainnet.
+ return QStringLiteral("MAINNET");
+}
+
QString relative_time(qint64 ts_ms) {
if (ts_ms == 0)
return QStringLiteral("never");
@@ -188,8 +216,10 @@ void HomeTab::build_ui() {
mode_group_->addButton(mode_poll_button_);
mode_group_->addButton(mode_stream_button_);
- mode_label_ = new QLabel(tr("MAINNET"), head);
+ mode_label_ = new QLabel(cluster_label(), head);
mode_label_->setObjectName(QStringLiteral("homeTabPanelStatus"));
+ mode_label_->setToolTip(tr("Solana cluster derived from the configured RPC endpoint "
+ "(Settings → Helius / solana.rpc_url)."));
head_l->addWidget(holdings_title_);
head_l->addStretch();
@@ -285,6 +315,18 @@ void HomeTab::build_ui() {
root->addWidget(roadmap_panel_);
root->addStretch(1);
+ // ── Accessibility ─────────────────────────────────────────────────────
+ copy_button_->setAccessibleName(tr("Copy wallet address to clipboard"));
+ disconnect_button_->setAccessibleName(tr("Disconnect wallet"));
+ refresh_button_->setAccessibleName(tr("Refresh balances now"));
+ mode_poll_button_->setAccessibleName(tr("Poll balances on a timer"));
+ mode_stream_button_->setAccessibleName(tr("Stream balances over WebSocket"));
+ row_pubkey_value_->setAccessibleName(tr("Connected wallet address"));
+ setTabOrder(copy_button_, disconnect_button_);
+ setTabOrder(disconnect_button_, mode_poll_button_);
+ setTabOrder(mode_poll_button_, mode_stream_button_);
+ setTabOrder(mode_stream_button_, refresh_button_);
+
// Wiring
connect(copy_button_, &QPushButton::clicked, this, [this]() {
QApplication::clipboard()->setText(current_pubkey_);
@@ -421,7 +463,12 @@ void HomeTab::apply_mode_to_buttons(bool is_stream) {
void HomeTab::showEvent(QShowEvent* e) {
QWidget::showEvent(e);
- // HoldingsTable manages its own subscriptions; nothing else to do here.
+ // HoldingsTable manages its own subscriptions. The cluster chip is
+ // re-derived here because the RPC override can be changed on SETTINGS
+ // while this tab is hidden — a stale "MAINNET" after switching to devnet
+ // is the dangerous direction.
+ if (mode_label_)
+ mode_label_->setText(cluster_label());
}
void HomeTab::hideEvent(QHideEvent* e) {
@@ -458,8 +505,13 @@ void HomeTab::retranslateUi() {
mode_poll_button_->setText(tr("POLL"));
if (mode_stream_button_)
mode_stream_button_->setText(tr("STREAM"));
- if (mode_label_)
- mode_label_->setText(tr("MAINNET"));
+ if (mode_label_) {
+ // Cluster name is derived data, not a translatable literal; only the
+ // tooltip needs re-rendering.
+ mode_label_->setText(cluster_label());
+ mode_label_->setToolTip(tr("Solana cluster derived from the configured RPC endpoint "
+ "(Settings → Helius / solana.rpc_url)."));
+ }
if (refresh_button_)
refresh_button_->setText(tr("REFRESH"));
diff --git a/fincept-qt/src/screens/crypto_center/tabs/RoadmapTab.cpp b/fincept-qt/src/screens/crypto_center/tabs/RoadmapTab.cpp
index e64bf30f1..7d7478d13 100644
--- a/fincept-qt/src/screens/crypto_center/tabs/RoadmapTab.cpp
+++ b/fincept-qt/src/screens/crypto_center/tabs/RoadmapTab.cpp
@@ -11,14 +11,6 @@
namespace fincept::screens {
-namespace {
-
-QString roadmap_font_stack() {
- return QStringLiteral("'Consolas','Cascadia Mono','JetBrains Mono','SF Mono',monospace");
-}
-
-} // namespace
-
RoadmapTab::RoadmapTab(QWidget* parent) : QWidget(parent) {
setObjectName(QStringLiteral("roadmapTab"));
build_ui();
@@ -73,8 +65,7 @@ void RoadmapTab::build_ui() {
void RoadmapTab::apply_theme() {
using namespace ui::colors;
- const QString font = roadmap_font_stack();
-
+ // No font token in this stylesheet — the panels inside supply their own.
const QString ss = QStringLiteral("QWidget#roadmapTab { background:%1; }"
"QScrollArea#roadmapTabScroll { background:%1; border:none; }"
"QWidget#roadmapTabContent { background:%1; }"
diff --git a/fincept-qt/src/screens/crypto_center/tabs/SettingsTab.cpp b/fincept-qt/src/screens/crypto_center/tabs/SettingsTab.cpp
index 49b6f09e1..678f7193e 100644
--- a/fincept-qt/src/screens/crypto_center/tabs/SettingsTab.cpp
+++ b/fincept-qt/src/screens/crypto_center/tabs/SettingsTab.cpp
@@ -24,6 +24,13 @@ constexpr const char* kHeliusKey = "solana.helius_api_key";
constexpr const char* kSlippageKey = "wallet.default_slippage_bps";
constexpr int kDefaultSlippageBps = 100; // 1.00%
constexpr int kMaxSlippageBps = 500; // 5.00%
+// PumpPortal's `trade-local` takes an INTEGER percent and clamps it to [1,5];
+// SwapPanel rounds the stored bps up to a whole percent before sending. The
+// slider used to start at 10 bps, so a user who set 0.10 % had 1.00 % actually
+// enforced — the settings screen promised a tolerance the swap path could not
+// honour. Bound the control to what is executable.
+constexpr int kMinSlippageBps = 100; // 1.00%
+constexpr int kSlippageStepBps = 25;
QString settings_font_stack() {
return QStringLiteral("'Consolas','Cascadia Mono','JetBrains Mono','SF Mono',monospace");
@@ -150,21 +157,27 @@ void SettingsTab::build_ui() {
helius_input_->setPlaceholderText(tr("paste API key…"));
helius_input_->setEchoMode(QLineEdit::Password);
helius_input_->setFixedHeight(28);
+ helius_input_->setAccessibleName(tr("Helius API key"));
row->addWidget(helius_input_, 1);
helius_save_button_ = new QPushButton(tr("SAVE"), panel);
helius_save_button_->setObjectName(QStringLiteral("settingsTabButton"));
helius_save_button_->setFixedHeight(28);
helius_save_button_->setCursor(Qt::PointingHandCursor);
+ helius_save_button_->setAccessibleName(tr("Save Helius API key"));
row->addWidget(helius_save_button_);
helius_clear_button_ = new QPushButton(tr("CLEAR"), panel);
helius_clear_button_->setObjectName(QStringLiteral("settingsTabDangerButton"));
helius_clear_button_->setFixedHeight(28);
helius_clear_button_->setCursor(Qt::PointingHandCursor);
+ helius_clear_button_->setAccessibleName(tr("Remove stored Helius API key"));
row->addWidget(helius_clear_button_);
body->addLayout(row);
+ setTabOrder(helius_input_, helius_save_button_);
+ setTabOrder(helius_save_button_, helius_clear_button_);
+
helius_status_ = new QLabel(QStringLiteral("—"), panel);
helius_status_->setObjectName(QStringLiteral("settingsTabHint"));
body->addWidget(helius_status_);
@@ -179,9 +192,10 @@ void SettingsTab::build_ui() {
{
auto [panel, body] =
make_panel(tr("DEFAULT SLIPPAGE"), tr("1% – 5%"), slippage_panel_title_, slippage_panel_sub_);
- slippage_hint_ = new QLabel(tr("Default slippage tolerance for swaps. Quotes whose route "
- "impact exceeds this value are blocked. Adjustable per-swap on "
- "the TRADE tab."),
+ slippage_hint_ = new QLabel(tr("Maximum price drift PumpSwap may fill your swap at before it "
+ "reverts. Applies to every swap on the TRADE tab — there is no "
+ "per-swap override. PumpPortal accepts whole percents only, so "
+ "the value is rounded up to the next percent and clamped to 5%."),
panel);
slippage_hint_->setObjectName(QStringLiteral("settingsTabHint"));
slippage_hint_->setWordWrap(true);
@@ -191,13 +205,15 @@ void SettingsTab::build_ui() {
row->setSpacing(8);
slippage_slider_ = new QSlider(Qt::Horizontal, panel);
slippage_slider_->setObjectName(QStringLiteral("settingsTabSlider"));
- slippage_slider_->setMinimum(10); // 0.10%
+ slippage_slider_->setMinimum(kMinSlippageBps);
slippage_slider_->setMaximum(kMaxSlippageBps);
- slippage_slider_->setSingleStep(5);
- slippage_slider_->setTickInterval(50);
+ slippage_slider_->setSingleStep(kSlippageStepBps);
+ slippage_slider_->setPageStep(kSlippageStepBps * 4);
+ slippage_slider_->setTickInterval(kMinSlippageBps);
slippage_slider_->setTickPosition(QSlider::TicksBelow);
slippage_slider_->setValue(kDefaultSlippageBps);
slippage_slider_->setFixedHeight(28);
+ slippage_slider_->setAccessibleName(tr("Default swap slippage tolerance"));
slippage_value_ = new QLabel(format_bps(kDefaultSlippageBps), panel);
slippage_value_->setObjectName(QStringLiteral("settingsTabSliderValue"));
slippage_value_->setFixedWidth(64);
@@ -320,9 +336,14 @@ void SettingsTab::load_initial_values() {
if (slip_res.is_ok()) {
bool ok = false;
const auto v = slip_res.value().toInt(&ok);
- if (ok && v >= 10 && v <= kMaxSlippageBps)
+ if (ok && v > 0 && v <= kMaxSlippageBps)
bps = v;
}
+ // A value persisted by an older build could be below the executable floor
+ // (e.g. 10 bps). Clamp before display so the label can't advertise a
+ // tolerance the swap path silently widens.
+ if (bps < kMinSlippageBps)
+ bps = kMinSlippageBps;
QSignalBlocker b(slippage_slider_);
slippage_slider_->setValue(bps);
slippage_value_->setText(format_bps(bps));
@@ -439,9 +460,10 @@ void SettingsTab::retranslateUi() {
if (slippage_panel_sub_)
slippage_panel_sub_->setText(tr("1% – 5%"));
if (slippage_hint_)
- slippage_hint_->setText(tr("Default slippage tolerance for swaps. Quotes whose route "
- "impact exceeds this value are blocked. Adjustable per-swap on "
- "the TRADE tab."));
+ slippage_hint_->setText(tr("Maximum price drift PumpSwap may fill your swap at before it "
+ "reverts. Applies to every swap on the TRADE tab — there is no "
+ "per-swap override. PumpPortal accepts whole percents only, so "
+ "the value is rounded up to the next percent and clamped to 5%."));
// Asset filters panel
if (filters_panel_title_)
diff --git a/fincept-qt/src/screens/crypto_trading/CryptoBottomPanel.cpp b/fincept-qt/src/screens/crypto_trading/CryptoBottomPanel.cpp
index 12ee7894c..5a38c80bd 100644
--- a/fincept-qt/src/screens/crypto_trading/CryptoBottomPanel.cpp
+++ b/fincept-qt/src/screens/crypto_trading/CryptoBottomPanel.cpp
@@ -33,6 +33,7 @@
#include <QStackedWidget>
#include <QVBoxLayout>
+#include <algorithm>
#include <cmath>
namespace fincept::screens::crypto {
@@ -183,6 +184,16 @@ QTableWidgetItem* CryptoBottomPanel::ensure_item(QTableWidget* table, int row, i
return it;
}
+namespace {
+/// Role under which the positions table stashes the exact (unrounded) numeric
+/// value of a cell. `update_position_prices()` used to recover quantity and
+/// entry price by re-parsing the *displayed* strings, which are rounded for
+/// presentation — an entry of 1.005 rendered "1.00" and the recomputed
+/// unrealised P&L was wrong by 0.005 × qty, while any sub-cent entry rendered
+/// "0.00" and the row was skipped entirely.
+constexpr int kExactValueRole = Qt::UserRole + 1;
+} // namespace
+
void CryptoBottomPanel::update_empty_state(QTableWidget* /*table*/, QStackedWidget* stack, int row_count) {
if (!stack)
return;
@@ -314,6 +325,14 @@ void CryptoBottomPanel::retranslateUi() {
stat_titles_[3]->setText(tr("BEST TRADE"));
if (stat_titles_[4])
stat_titles_[4]->setText(tr("WORST TRADE"));
+
+ // Live account card titles
+ if (live_balance_title_)
+ live_balance_title_->setText(tr("LIVE BALANCE"));
+ if (live_equity_title_)
+ live_equity_title_->setText(tr("LIVE EQUITY"));
+ if (live_margin_title_)
+ live_margin_title_->setText(tr("USED MARGIN"));
}
void CryptoBottomPanel::setup_positions_tab() {
@@ -344,6 +363,7 @@ void CryptoBottomPanel::setup_positions_tab() {
close_all_btn_ = new QPushButton(tr("SQUARE OFF ALL"));
close_all_btn_->setObjectName("cryptoCloseAllBtn");
close_all_btn_->setCursor(Qt::PointingHandCursor);
+ close_all_btn_->setAccessibleName(tr("Close every open position at market"));
close_all_btn_->setStyleSheet(
QString("QPushButton{background:rgba(220,38,38,0.12);color:%1;border:1px solid %2;"
"padding:3px 12px;font-size:10px;font-weight:700;letter-spacing:0.5px;border-radius:2px;}"
@@ -398,6 +418,7 @@ void CryptoBottomPanel::setup_orders_tab() {
cancel_all_btn_ = new QPushButton(tr("CANCEL ALL ORDERS"));
cancel_all_btn_->setObjectName("cryptoCancelAllBtn");
cancel_all_btn_->setCursor(Qt::PointingHandCursor);
+ cancel_all_btn_->setAccessibleName(tr("Cancel every pending order"));
cancel_all_btn_->setStyleSheet(
QString("QPushButton{background:rgba(217,119,6,0.12);color:%1;border:1px solid %2;"
"padding:3px 12px;font-size:10px;font-weight:700;letter-spacing:0.5px;border-radius:2px;}"
@@ -567,6 +588,19 @@ void CryptoBottomPanel::setup_stats_tab() {
for (int i = 0; i < 5; ++i)
stat_titles_[i] = card_title_of(stat_values_[i]);
+ // Live account cards. `set_live_balance()` / `set_balance_unavailable()`
+ // both opened with `if (!live_balance_label_) return;` and these three
+ // labels were declared but NEVER constructed — so in LIVE mode the
+ // exchange balance, equity and used margin fetched every 5 s went
+ // straight into the bin, and a failed balance fetch produced no visible
+ // signal at all. Build the cards so the data path terminates on screen.
+ live_balance_label_ = build_card(grid, 1, 2, tr("LIVE BALANCE"));
+ live_equity_label_ = build_card(grid, 2, 0, tr("LIVE EQUITY"));
+ live_margin_label_ = build_card(grid, 2, 1, tr("USED MARGIN"));
+ live_balance_title_ = card_title_of(live_balance_label_);
+ live_equity_title_ = card_title_of(live_equity_label_);
+ live_margin_title_ = card_title_of(live_margin_label_);
+
// Mark P&L cards as such so the QSS can colour them via the [pnl] property.
stat_values_[0]->setProperty("pnl", "neutral");
stat_values_[3]->setProperty("pnl", "positive");
@@ -617,13 +651,18 @@ void CryptoBottomPanel::set_positions(const QVector<trading::PtPosition>& positi
set(0, pos.symbol);
set(1, pos.side.toUpper(), pos.side == "long" ? kColorPos() : kColorNeg());
- set(2, QString::number(pos.quantity, 'f', 6), QColor(), Qt::AlignRight | Qt::AlignVCenter);
- set(3, QString::number(pos.entry_price, 'f', 2), QColor(), Qt::AlignRight | Qt::AlignVCenter);
- set(4, QString::number(pos.current_price, 'f', 2), QColor(), Qt::AlignRight | Qt::AlignVCenter);
+ set(2, format_size(pos.quantity), QColor(), Qt::AlignRight | Qt::AlignVCenter);
+ set(3, format_price_plain(pos.entry_price), QColor(), Qt::AlignRight | Qt::AlignVCenter);
+ set(4, format_price_plain(pos.current_price), QColor(), Qt::AlignRight | Qt::AlignVCenter);
set(5, QString::number(pos.unrealized_pnl, 'f', 2), pos.unrealized_pnl >= 0 ? kColorPos() : kColorNeg(),
Qt::AlignRight | Qt::AlignVCenter);
set(6, QString::number(pos.leverage, 'f', 1) + QStringLiteral("x"), QColor(),
Qt::AlignRight | Qt::AlignVCenter);
+
+ // Stash the exact values the live mark-to-market path needs so it
+ // never has to re-parse rounded display text.
+ ensure_item(positions_table_, i, 2)->setData(kExactValueRole, pos.quantity);
+ ensure_item(positions_table_, i, 3)->setData(kExactValueRole, pos.entry_price);
}
positions_table_->setUpdatesEnabled(true);
update_empty_state(positions_table_, positions_stack_, n);
@@ -657,14 +696,19 @@ void CryptoBottomPanel::update_position_prices(const QHash<QString, double>& las
continue;
const bool is_long = side_item->text().compare("LONG", Qt::CaseInsensitive) == 0;
- const double qty = qty_item->text().toDouble();
- const double entry = entry_item->text().toDouble();
+ // Prefer the exact values stashed by set_positions/set_live_positions;
+ // fall back to the display text only for rows written by an older
+ // path that didn't stash them.
+ const QVariant qty_exact = qty_item->data(kExactValueRole);
+ const QVariant entry_exact = entry_item->data(kExactValueRole);
+ const double qty = qty_exact.isValid() ? qty_exact.toDouble() : qty_item->text().toDouble();
+ const double entry = entry_exact.isValid() ? entry_exact.toDouble() : entry_item->text().toDouble();
if (qty <= 0.0 || entry <= 0.0)
continue;
const double pnl = is_long ? (mark - entry) * qty : (entry - mark) * qty;
- cur_item->setText(QString::number(mark, 'f', 2));
+ cur_item->setText(format_price_plain(mark));
pnl_item->setText(QString::number(pnl, 'f', 2));
pnl_item->setForeground(pnl >= 0 ? kColorPos() : kColorNeg());
}
@@ -700,8 +744,8 @@ void CryptoBottomPanel::set_orders(const QVector<trading::PtOrder>& orders) {
set(0, o.symbol);
set(1, o.side.toUpper(), o.side == "buy" ? kColorPos() : kColorNeg());
set(2, o.order_type.toUpper());
- set(3, QString::number(o.quantity, 'f', 6), QColor(), Qt::AlignRight | Qt::AlignVCenter);
- set(4, o.price ? QString::number(*o.price, 'f', 2) : QStringLiteral("MKT"), QColor(),
+ set(3, format_size(o.quantity), QColor(), Qt::AlignRight | Qt::AlignVCenter);
+ set(4, o.price ? format_price_plain(*o.price) : QStringLiteral("MKT"), QColor(),
Qt::AlignRight | Qt::AlignVCenter);
set(5, o.status.toUpper(), kColorSec());
@@ -746,8 +790,8 @@ void CryptoBottomPanel::set_trades(const QVector<trading::PtTrade>& trades) {
set(0, t.symbol);
set(1, t.side.toUpper(), t.side == "buy" ? kColorPos() : kColorNeg());
- set(2, QString::number(t.price, 'f', 2), QColor(), Qt::AlignRight | Qt::AlignVCenter);
- set(3, QString::number(t.quantity, 'f', 6), QColor(), Qt::AlignRight | Qt::AlignVCenter);
+ set(2, format_price_plain(t.price), QColor(), Qt::AlignRight | Qt::AlignVCenter);
+ set(3, format_size(t.quantity), QColor(), Qt::AlignRight | Qt::AlignVCenter);
set(4, QString::number(t.fee, 'f', 4), kColorSec(), Qt::AlignRight | Qt::AlignVCenter);
set(5, QString::number(t.pnl, 'f', 2), t.pnl >= 0 ? kColorPos() : kColorNeg(),
Qt::AlignRight | Qt::AlignVCenter);
@@ -786,8 +830,8 @@ void CryptoBottomPanel::set_market_info(const MarketInfoData& info) {
if (!info.has_data)
return;
funding_label_->setText(QString("%1%").arg(info.funding_rate * 100.0, 0, 'f', 4));
- mark_label_->setText(QString("$%1").arg(info.mark_price, 0, 'f', 2));
- index_label_->setText(QString("$%1").arg(info.index_price, 0, 'f', 2));
+ mark_label_->setText(format_price_usd(info.mark_price));
+ index_label_->setText(format_price_usd(info.index_price));
oi_label_->setText(QString("$%1M").arg(info.open_interest_value / 1e6, 0, 'f', 2));
fees_label_->setText(
QString("%1% / %2%").arg(info.maker_fee * 100, 0, 'f', 3).arg(info.taker_fee * 100, 0, 'f', 3));
@@ -824,15 +868,20 @@ void CryptoBottomPanel::set_live_positions(const QJsonArray& positions) {
};
const QString side_str = p.value("side").toString();
+ const double contracts = p.value("contracts").toDouble();
+ const double entry_px = p.value("entryPrice").toDouble();
set(0, p.value("symbol").toString());
set(1, side_str.toUpper(), side_str.contains("long") ? kColorPos() : kColorNeg());
- set(2, QString::number(p.value("contracts").toDouble(), 'f', 4), QColor(), Qt::AlignRight | Qt::AlignVCenter);
- set(3, QString::number(p.value("entryPrice").toDouble(), 'f', 2), QColor(), Qt::AlignRight | Qt::AlignVCenter);
- set(4, QString::number(p.value("markPrice").toDouble(), 'f', 2), QColor(), Qt::AlignRight | Qt::AlignVCenter);
+ set(2, format_size(contracts), QColor(), Qt::AlignRight | Qt::AlignVCenter);
+ set(3, format_price_plain(entry_px), QColor(), Qt::AlignRight | Qt::AlignVCenter);
+ set(4, format_price_plain(p.value("markPrice").toDouble()), QColor(), Qt::AlignRight | Qt::AlignVCenter);
const double pnl = p.value("unrealizedPnl").toDouble();
set(5, QString::number(pnl, 'f', 2), pnl >= 0 ? kColorPos() : kColorNeg(), Qt::AlignRight | Qt::AlignVCenter);
set(6, QString::number(p.value("leverage").toDouble(), 'f', 0) + QStringLiteral("x"), QColor(),
Qt::AlignRight | Qt::AlignVCenter);
+
+ ensure_item(positions_table_, i, 2)->setData(kExactValueRole, contracts);
+ ensure_item(positions_table_, i, 3)->setData(kExactValueRole, entry_px);
}
positions_table_->setUpdatesEnabled(true);
update_empty_state(positions_table_, positions_stack_, n);
@@ -862,8 +911,8 @@ void CryptoBottomPanel::set_live_orders(const QJsonArray& orders) {
set(0, o.value("symbol").toString());
set(1, side_str.toUpper(), side_str == "buy" ? kColorPos() : kColorNeg());
set(2, o.value("type").toString().toUpper());
- set(3, QString::number(o.value("amount").toDouble(), 'f', 4), QColor(), Qt::AlignRight | Qt::AlignVCenter);
- set(4, QString::number(o.value("price").toDouble(), 'f', 2), QColor(), Qt::AlignRight | Qt::AlignVCenter);
+ set(3, format_size(o.value("amount").toDouble()), QColor(), Qt::AlignRight | Qt::AlignVCenter);
+ set(4, format_price_plain(o.value("price").toDouble()), QColor(), Qt::AlignRight | Qt::AlignVCenter);
set(5, o.value("status").toString().toUpper(), kColorSec());
auto* existing_btn = qobject_cast<QPushButton*>(orders_table_->cellWidget(i, 6));
@@ -912,8 +961,8 @@ void CryptoBottomPanel::update_my_trades(const QJsonObject& json) {
set(0, t.value("symbol").toString());
set(1, side.toUpper(), side == "buy" ? kColorPos() : kColorNeg());
- set(2, QString::number(t.value("price").toDouble(), 'f', 2), QColor(), Qt::AlignRight | Qt::AlignVCenter);
- set(3, QString::number(t.value("amount").toDouble(), 'f', 6), QColor(), Qt::AlignRight | Qt::AlignVCenter);
+ set(2, format_price_plain(t.value("price").toDouble()), QColor(), Qt::AlignRight | Qt::AlignVCenter);
+ set(3, format_size(t.value("amount").toDouble()), QColor(), Qt::AlignRight | Qt::AlignVCenter);
set(4, QString::number(t.value("cost").toDouble(), 'f', 2), QColor(), Qt::AlignRight | Qt::AlignVCenter);
set(5, QString::number(t.value("fee").toDouble(), 'f', 6), kColorSec(), Qt::AlignRight | Qt::AlignVCenter);
set(6, t.value("fee_currency").toString(), kColorTert());
diff --git a/fincept-qt/src/screens/crypto_trading/CryptoBottomPanel.h b/fincept-qt/src/screens/crypto_trading/CryptoBottomPanel.h
index 4f24a8b77..8c0001138 100644
--- a/fincept-qt/src/screens/crypto_trading/CryptoBottomPanel.h
+++ b/fincept-qt/src/screens/crypto_trading/CryptoBottomPanel.h
@@ -135,10 +135,13 @@ class CryptoBottomPanel : public QWidget {
QLabel* stat_values_[5] = {};
QLabel* stat_titles_[5] = {};
- // Live balance
+ // Live balance (cards built on the STATS tab by setup_stats_tab)
QLabel* live_balance_label_ = nullptr;
QLabel* live_equity_label_ = nullptr;
QLabel* live_margin_label_ = nullptr;
+ QLabel* live_balance_title_ = nullptr;
+ QLabel* live_equity_title_ = nullptr;
+ QLabel* live_margin_title_ = nullptr;
// Bulk action buttons
class QPushButton* cancel_all_btn_ = nullptr;
diff --git a/fincept-qt/src/screens/crypto_trading/CryptoDepthChart.cpp b/fincept-qt/src/screens/crypto_trading/CryptoDepthChart.cpp
index 23551ddb4..287cbb758 100644
--- a/fincept-qt/src/screens/crypto_trading/CryptoDepthChart.cpp
+++ b/fincept-qt/src/screens/crypto_trading/CryptoDepthChart.cpp
@@ -1,6 +1,7 @@
// CryptoDepthChart.cpp — custom-painted cumulative bid/ask depth area chart
#include "screens/crypto_trading/CryptoDepthChart.h"
+#include "screens/crypto_trading/CryptoTypes.h"
#include "ui/theme/ThemeManager.h"
#include <QMutexLocker>
@@ -250,11 +251,13 @@ void CryptoDepthChart::rebuild_cache() {
p.drawText(QRect(0, y - 8, margin_l - 4, 16), Qt::AlignRight | Qt::AlignVCenter, label);
}
- // Price axis labels (bottom)
+ // Price axis labels (bottom). `'f', 0` printed five identical "0" ticks
+ // for any pair trading below $1 — which is most of the long tail — so the
+ // x axis carried no information at all there.
for (int i = 0; i <= 4; ++i) {
const double price = min_price + (max_price - min_price) * i / 4;
const int x = map_x(price);
- p.drawText(QRect(x - 30, margin_t + plot_h + 2, 60, 16), Qt::AlignCenter, QString::number(price, 'f', 0));
+ p.drawText(QRect(x - 40, margin_t + plot_h + 2, 80, 16), Qt::AlignCenter, format_price_plain(price));
}
cache_dirty_ = false;
diff --git a/fincept-qt/src/screens/crypto_trading/CryptoOrderBook.cpp b/fincept-qt/src/screens/crypto_trading/CryptoOrderBook.cpp
index 3ae03d3c3..b7b6a0bb9 100644
--- a/fincept-qt/src/screens/crypto_trading/CryptoOrderBook.cpp
+++ b/fincept-qt/src/screens/crypto_trading/CryptoOrderBook.cpp
@@ -185,7 +185,7 @@ void CryptoOrderBook::set_data(const QVector<QPair<double, double>>& bids, const
spread_ = spread;
spread_pct_ = spread_pct;
}
- spread_label_->setText(tr("SPREAD %1 (%2%)").arg(spread, 0, 'f', 2).arg(spread_pct, 0, 'f', 4));
+ spread_label_->setText(tr("SPREAD %1 (%2%)").arg(format_price_plain(spread)).arg(spread_pct, 0, 'f', 4));
has_spread_data_ = true;
cache_dirty_ = true;
if (repaint_timer_ && !repaint_timer_->isActive())
@@ -214,20 +214,31 @@ void CryptoOrderBook::mousePressEvent(QMouseEvent* event) {
return;
const int row = paint_y / ROW_H;
- QMutexLocker lock(&mutex_);
- const int ask_count = std::min(static_cast<int>(asks_.size()), OB_MAX_DISPLAY_LEVELS);
- const int bid_count = std::min(static_cast<int>(bids_.size()), OB_MAX_DISPLAY_LEVELS);
-
- if (row < ask_count) {
- // Clicked an ask row (displayed in reverse)
- const int src = ask_count - 1 - row;
- if (src < asks_.size())
- emit price_clicked(asks_[src].first);
- } else if (row < ask_count + bid_count) {
- const int bid_idx = row - ask_count;
- if (bid_idx < bids_.size())
- emit price_clicked(bids_[bid_idx].first);
+
+ // Resolve the price under the lock, then RELEASE it before emitting.
+ // `price_clicked` runs its receiver synchronously (same thread) and the
+ // receiver is free to call back into set_data(), which takes the same
+ // non-recursive QMutex — emitting while holding it is a self-deadlock
+ // waiting for a future caller to arrange.
+ double clicked_price = 0.0;
+ {
+ QMutexLocker lock(&mutex_);
+ const int ask_count = std::min(static_cast<int>(asks_.size()), OB_MAX_DISPLAY_LEVELS);
+ const int bid_count = std::min(static_cast<int>(bids_.size()), OB_MAX_DISPLAY_LEVELS);
+
+ if (row < ask_count) {
+ // Clicked an ask row (displayed in reverse)
+ const int src = ask_count - 1 - row;
+ if (src >= 0 && src < asks_.size())
+ clicked_price = asks_[src].first;
+ } else if (row < ask_count + bid_count) {
+ const int bid_idx = row - ask_count;
+ if (bid_idx >= 0 && bid_idx < bids_.size())
+ clicked_price = bids_[bid_idx].first;
+ }
}
+ if (clicked_price > 0.0)
+ emit price_clicked(clicked_price);
}
void CryptoOrderBook::paintEvent(QPaintEvent* /*event*/) {
@@ -320,15 +331,16 @@ void CryptoOrderBook::rebuild_cache() {
const bool hot = bids[i].second >= p75 && p75 > 0;
p.fillRect(half_w - 1 - bar_w, y, bar_w, ROW_H, hot ? kBidBarHot() : kBidBar());
- // Price text
+ // Price text — precision follows the magnitude so sub-cent pairs
+ // don't collapse into a column of identical "0.00" levels.
p.setPen(kColorBid());
p.drawText(QRect(4, y, price_col_w, ROW_H), Qt::AlignLeft | Qt::AlignVCenter,
- QString::number(bids[i].first, 'f', 2));
+ format_price_plain(bids[i].first));
// Amount text
p.setPen(kTextSecondary());
p.drawText(QRect(4, y, half_w - 8, ROW_H), Qt::AlignRight | Qt::AlignVCenter,
- QString::number(bids[i].second, 'f', 4));
+ format_size(bids[i].second));
}
// Draw ask side (right) — prices ascending from center
@@ -346,12 +358,12 @@ void CryptoOrderBook::rebuild_cache() {
// Price text
p.setPen(kColorAsk());
p.drawText(QRect(half_w + 4, y, price_col_w, ROW_H), Qt::AlignLeft | Qt::AlignVCenter,
- QString::number(asks[i].first, 'f', 2));
+ format_price_plain(asks[i].first));
// Amount text
p.setPen(kTextSecondary());
p.drawText(QRect(half_w + 4, y, half_w - 8, ROW_H), Qt::AlignRight | Qt::AlignVCenter,
- QString::number(asks[i].second, 'f', 4));
+ format_size(asks[i].second));
}
// Center divider line
diff --git a/fincept-qt/src/screens/crypto_trading/CryptoOrderBook.h b/fincept-qt/src/screens/crypto_trading/CryptoOrderBook.h
index fab62ecfb..ca6e41f22 100644
--- a/fincept-qt/src/screens/crypto_trading/CryptoOrderBook.h
+++ b/fincept-qt/src/screens/crypto_trading/CryptoOrderBook.h
@@ -46,7 +46,8 @@ class CryptoOrderBook : public QWidget {
QLabel* title_label_ = nullptr;
QLabel* spread_label_ = nullptr;
bool has_spread_data_ = false; // gates whether spread_label_ shows live data vs placeholder
- QWidget* canvas_ = nullptr;
+ // (Removed `canvas_`: never assigned or read — the book is painted
+ // directly onto this widget via `cache_`.)
// Data (mutex-protected)
QVector<QPair<double, double>> bids_;
diff --git a/fincept-qt/src/screens/crypto_trading/CryptoOrderEntry.cpp b/fincept-qt/src/screens/crypto_trading/CryptoOrderEntry.cpp
index 89eab0fc9..2d153e71f 100644
--- a/fincept-qt/src/screens/crypto_trading/CryptoOrderEntry.cpp
+++ b/fincept-qt/src/screens/crypto_trading/CryptoOrderEntry.cpp
@@ -23,6 +23,8 @@
#include "screens/crypto_trading/CryptoOrderEntry.h"
+#include "screens/crypto_trading/CryptoTypes.h"
+
#include <QComboBox>
#include <QDoubleValidator>
#include <QFrame>
@@ -39,6 +41,14 @@ namespace fincept::screens::crypto {
namespace {
+// Taker fee assumption used for the on-screen estimate AND for the % quick-fill
+// sizing. Real fees come back from the exchange post-fill. Shared so the two
+// can't drift: sizing 100 % against the bare balance produced an order whose
+// total (notional + fee) always exceeded the balance, so the ticket
+// immediately flagged "Insufficient balance for this order" — the 100 %
+// button could never produce a submittable order.
+constexpr double kAssumedFeeRate = 0.0007; // 7 bps / 0.07 %
+
QFrame* make_card(const QString& object_name = "cryptoOeCard") {
auto* card = new QFrame;
card->setObjectName(object_name);
@@ -236,9 +246,9 @@ CryptoOrderEntry::CryptoOrderEntry(QWidget* parent) : QWidget(parent) {
}
form->addLayout(pct_row);
- // Symbol-change signal will update the unit label.
- connect(this, &CryptoOrderEntry::destroyed, unit, []() {});
- // Repurpose set_symbol's path: we keep a reference to update later.
+ // Tag the suffix label so set_symbol() can find and update it.
+ // (A no-op `connect(this, &CryptoOrderEntry::destroyed, unit, []{})`
+ // used to sit here; it did nothing and has been removed.)
unit->setProperty("ftRoleUnit", true);
}
@@ -442,6 +452,47 @@ CryptoOrderEntry::CryptoOrderEntry(QWidget* parent) : QWidget(parent) {
form->addStretch();
root->addWidget(content, 1);
+ // ── Accessibility ───────────────────────────────────────────────────────
+ // Every field that sizes or prices a real order gets a spoken name, and
+ // the ticket gets an explicit tab order: side → type → quantity → price →
+ // stop → SL → TP → submit. Without setTabOrder the focus chain follows
+ // construction order, which interleaves the collapsed advanced/futures
+ // sections and drops the user into hidden widgets.
+ buy_tab_->setAccessibleName(tr("Buy side"));
+ sell_tab_->setAccessibleName(tr("Sell side"));
+ for (int i = 0; i < 4; ++i) {
+ if (type_btns_[i])
+ type_btns_[i]->setAccessibleName(tr("Order type: %1").arg(type_btns_[i]->text()));
+ }
+ qty_edit_->setAccessibleName(tr("Order quantity"));
+ qty_edit_->setAccessibleDescription(tr("Quantity in the base asset of the selected pair"));
+ price_edit_->setAccessibleName(tr("Limit price"));
+ stop_price_edit_->setAccessibleName(tr("Stop trigger price"));
+ sl_edit_->setAccessibleName(tr("Stop loss trigger price"));
+ tp_edit_->setAccessibleName(tr("Take profit trigger price"));
+ submit_btn_->setAccessibleName(tr("Submit order"));
+ balance_label_->setAccessibleName(tr("Account balance"));
+ market_price_label_->setAccessibleName(tr("Mark price"));
+ avail_label_->setAccessibleName(tr("Balance available after this order"));
+ mode_label_->setAccessibleName(tr("Trading mode, paper or live"));
+ status_label_->setAccessibleName(tr("Order validation message"));
+ submit_subtitle_->setAccessibleName(tr("Order preview"));
+ if (leverage_spin_)
+ leverage_spin_->setAccessibleName(tr("Leverage multiplier"));
+ if (margin_mode_combo_)
+ margin_mode_combo_->setAccessibleName(tr("Margin mode"));
+ if (reduce_only_check_)
+ reduce_only_check_->setAccessibleName(tr("Reduce only — never increase position size"));
+
+ // Side/type buttons and the advanced toggle are Qt::NoFocus by design
+ // (they're click targets, not stops in the keyboard chain), so only the
+ // focusable fields are linked here.
+ setTabOrder(qty_edit_, price_edit_);
+ setTabOrder(price_edit_, stop_price_edit_);
+ setTabOrder(stop_price_edit_, sl_edit_);
+ setTabOrder(sl_edit_, tp_edit_);
+ setTabOrder(tp_edit_, submit_btn_);
+
update_cost_preview();
}
@@ -505,7 +556,10 @@ void CryptoOrderEntry::set_balance(double balance) {
void CryptoOrderEntry::set_current_price(double price) {
current_price_ = price;
- market_price_label_->setText(QString("$%1").arg(price, 0, 'f', 2));
+ // Magnitude-scaled: a fixed 2 dp rendered the MARK of every sub-cent pair
+ // as "$0.00", which is both useless and dangerous next to a live BUY
+ // button.
+ market_price_label_->setText(format_price_usd(price));
update_cost_preview();
}
@@ -616,9 +670,18 @@ void CryptoOrderEntry::on_pct_clicked(int pct) {
basis = limit_p;
}
const int leverage = (is_futures_ && leverage_spin_) ? leverage_spin_->value() : 1;
- const double max_qty = (balance_ * leverage) / basis;
+ // Leave headroom for the taker fee. Sizing against the bare balance made
+ // "100 %" cost balance × (1 + fee), which the ticket then rejected as
+ // insufficient — so the button never yielded a usable order.
+ const double cost_per_unit = basis * (1.0 + kAssumedFeeRate);
+ if (cost_per_unit <= 0.0)
+ return;
+ const double max_qty = (balance_ * leverage) / cost_per_unit;
const double qty = max_qty * pct / 100.0;
- qty_edit_->setText(QString::number(qty, 'f', 6));
+ // Truncate rather than round — rounding the last digit up can push the
+ // notional back over the balance.
+ const double truncated = std::floor(qty * 1e8) / 1e8;
+ qty_edit_->setText(QString::number(truncated, 'f', 8));
}
void CryptoOrderEntry::set_futures_mode(bool is_futures) {
@@ -651,10 +714,7 @@ void CryptoOrderEntry::update_cost_preview() {
const int leverage = (is_futures_ && leverage_spin_) ? leverage_spin_->value() : 1;
const double margin = notional / std::max(1, leverage);
- // Taker fee assumption — used purely for the on-screen estimate. Real
- // fees come back from the exchange post-fill.
- constexpr double kAssumedFeeBps = 0.0007; // 7 bps / 0.07 %
- const double fee = notional * kAssumedFeeBps;
+ const double fee = notional * kAssumedFeeRate;
const double total = margin + fee;
const double pct = balance_ > 0 ? (margin / balance_) * 100.0 : 0.0;
const double avail = std::max(0.0, balance_ - total);
@@ -680,8 +740,14 @@ void CryptoOrderEntry::update_cost_preview() {
status_label_->setProperty("severity", "warning");
status_label_->setVisible(true);
repolish(status_label_);
- } else if (status_label_->property("severity").toString() != QLatin1String("error")) {
+ } else {
+ // Also clear a sticky "error" severity here. Previously an error
+ // set by on_submit() (e.g. "Enter a valid quantity") latched the
+ // severity property forever, so the message stayed on screen even
+ // after the user typed a perfectly valid ticket.
+ status_label_->setProperty("severity", QString());
status_label_->setVisible(false);
+ repolish(status_label_);
}
} else {
cost_label_->setText(QStringLiteral("--"));
diff --git a/fincept-qt/src/screens/crypto_trading/CryptoTickerBar.cpp b/fincept-qt/src/screens/crypto_trading/CryptoTickerBar.cpp
index 118b09ddc..df4075a13 100644
--- a/fincept-qt/src/screens/crypto_trading/CryptoTickerBar.cpp
+++ b/fincept-qt/src/screens/crypto_trading/CryptoTickerBar.cpp
@@ -1,6 +1,7 @@
// CryptoTickerBar.cpp — dense price ribbon with bid/ask/spread
#include "screens/crypto_trading/CryptoTickerBar.h"
+#include "screens/crypto_trading/CryptoTypes.h"
#include "ui/theme/Theme.h"
#include <QHBoxLayout>
@@ -73,13 +74,15 @@ void CryptoTickerBar::set_symbol(const QString& symbol) {
symbol_label_->setText(symbol);
}
-// Round a value to the display precision (here 2 decimals). Two inputs that
-// round identically mean identical rendered text — no setText needed.
-static inline double round_pp(double v, int places = 2) {
- double mul = 1.0;
- for (int i = 0; i < places; ++i)
- mul *= 10.0;
- return std::round(v * mul) / mul;
+// Set `label`'s text only when the rendered string actually changed, using
+// `cache` as the last-rendered value. Replaces the old
+// "round to 2 dp and compare doubles" dedup, which never fired an update for
+// sub-cent assets because every tick rounded to the same 0.00.
+static inline void set_if_changed(QLabel* label, QString& cache, const QString& text) {
+ if (cache == text)
+ return;
+ cache = text;
+ label->setText(text);
}
void CryptoTickerBar::update_data(double price, double change_pct, double high, double low, double volume,
@@ -87,18 +90,11 @@ void CryptoTickerBar::update_data(double price, double change_pct, double high,
if (price <= 0)
return;
- const double price_disp = round_pp(price);
- if (price_disp != last_price_display_) {
- price_label_->setText(QString("$%1").arg(price_disp, 0, 'f', 2));
- last_price_display_ = price_disp;
- }
+ set_if_changed(price_label_, last_price_text_, format_price_usd(price));
const bool positive = change_pct >= 0;
- const double change_disp = round_pp(change_pct);
- if (change_disp != last_change_display_) {
- change_label_->setText(QString("%1%2%").arg(positive ? "+" : "").arg(change_disp, 0, 'f', 2));
- last_change_display_ = change_disp;
- }
+ set_if_changed(change_label_, last_change_text_,
+ QString("%1%2%").arg(positive ? "+" : "").arg(change_pct, 0, 'f', 2));
// Only update style on state flip — P7
if (positive != last_positive_) {
@@ -108,58 +104,25 @@ void CryptoTickerBar::update_data(double price, double change_pct, double high,
last_positive_ = positive;
}
- const double high_disp = round_pp(high);
- if (high_disp != last_high_display_) {
- high_label_->setText(QString("H:%1").arg(high_disp, 0, 'f', 2));
- last_high_display_ = high_disp;
- }
- const double low_disp = round_pp(low);
- if (low_disp != last_low_display_) {
- low_label_->setText(QString("L:%1").arg(low_disp, 0, 'f', 2));
- last_low_display_ = low_disp;
- }
+ set_if_changed(high_label_, last_high_text_, QStringLiteral("H:") + format_price_plain(high));
+ set_if_changed(low_label_, last_low_text_, QStringLiteral("L:") + format_price_plain(low));
- int vol_unit;
- double vol_disp;
QString vol_text;
- if (volume >= 1e9) {
- vol_unit = 2;
- vol_disp = round_pp(volume / 1e9);
- vol_text = QString("Vol:%1B").arg(vol_disp, 0, 'f', 2);
- } else if (volume >= 1e6) {
- vol_unit = 1;
- vol_disp = round_pp(volume / 1e6);
- vol_text = QString("Vol:%1M").arg(vol_disp, 0, 'f', 2);
- } else {
- vol_unit = 0;
- vol_disp = std::round(volume);
- vol_text = QString("Vol:%1").arg(vol_disp, 0, 'f', 0);
- }
- if (vol_unit != last_volume_unit_ || vol_disp != last_volume_display_) {
- volume_label_->setText(vol_text);
- last_volume_unit_ = vol_unit;
- last_volume_display_ = vol_disp;
- }
+ if (volume >= 1e9)
+ vol_text = QString("Vol:%1B").arg(volume / 1e9, 0, 'f', 2);
+ else if (volume >= 1e6)
+ vol_text = QString("Vol:%1M").arg(volume / 1e6, 0, 'f', 2);
+ else
+ vol_text = QString("Vol:%1").arg(volume, 0, 'f', 0);
+ set_if_changed(volume_label_, last_volume_text_, vol_text);
Q_UNUSED(ws_connected);
}
void CryptoTickerBar::update_bid_ask(double bid, double ask, double spread) {
- const double b = round_pp(bid);
- const double a = round_pp(ask);
- const double s = round_pp(spread);
- if (b != last_bid_display_) {
- bid_label_->setText(QString("B:%1").arg(b, 0, 'f', 2));
- last_bid_display_ = b;
- }
- if (a != last_ask_display_) {
- ask_label_->setText(QString("A:%1").arg(a, 0, 'f', 2));
- last_ask_display_ = a;
- }
- if (s != last_spread_display_) {
- spread_label_->setText(QString("S:%1").arg(s, 0, 'f', 2));
- last_spread_display_ = s;
- }
+ set_if_changed(bid_label_, last_bid_text_, QStringLiteral("B:") + format_price_plain(bid));
+ set_if_changed(ask_label_, last_ask_text_, QStringLiteral("A:") + format_price_plain(ask));
+ set_if_changed(spread_label_, last_spread_text_, QStringLiteral("S:") + format_price_plain(spread));
}
void CryptoTickerBar::update_mark_price(double mark_price, double index_price) {
@@ -169,11 +132,11 @@ void CryptoTickerBar::update_mark_price(double mark_price, double index_price) {
return;
}
if (mark_price > 0) {
- mark_price_label_->setText(QString("Mk:%1").arg(mark_price, 0, 'f', 2));
+ mark_price_label_->setText(QStringLiteral("Mk:") + format_price_plain(mark_price));
mark_price_label_->setVisible(true);
}
if (index_price > 0) {
- index_price_label_->setText(QString("Idx:%1").arg(index_price, 0, 'f', 2));
+ index_price_label_->setText(QStringLiteral("Idx:") + format_price_plain(index_price));
index_price_label_->setVisible(true);
}
}
diff --git a/fincept-qt/src/screens/crypto_trading/CryptoTickerBar.h b/fincept-qt/src/screens/crypto_trading/CryptoTickerBar.h
index c5e8a4f27..c63d69c96 100644
--- a/fincept-qt/src/screens/crypto_trading/CryptoTickerBar.h
+++ b/fincept-qt/src/screens/crypto_trading/CryptoTickerBar.h
@@ -2,6 +2,7 @@
// Crypto Price Ribbon — dense single-line: price, change, bid/ask, spread, high/low/volume, WS status
#include <QLabel>
+#include <QString>
#include <QWidget>
namespace fincept::screens::crypto {
@@ -29,19 +30,23 @@ class CryptoTickerBar : public QWidget {
QLabel* mark_price_label_ = nullptr;
QLabel* index_price_label_ = nullptr;
- // State cache — avoid redundant setText calls at ticker rate. Values are
- // rounded to the display precision before comparing so we only repaint on
- // a pixel-visible change.
+ // State cache — avoid redundant setText calls at ticker rate.
+ //
+ // Cached as the *rendered strings*, not as values rounded to a fixed 2 dp.
+ // The old scheme compared `round(v, 2)`, so on a sub-cent pair every tick
+ // rounded to the same 0.00 and the labels were never updated at all: the
+ // ribbon looked frozen for exactly the assets whose price moves most.
+ // Comparing the final text is both correct at every magnitude and still
+ // suppresses repaints when nothing visible changed.
bool last_positive_ = true;
- double last_price_display_ = -1;
- double last_change_display_ = 1e300;
- double last_high_display_ = -1;
- double last_low_display_ = -1;
- double last_volume_display_ = -1;
- int last_volume_unit_ = -1; // 0=raw, 1=M, 2=B
- double last_bid_display_ = -1;
- double last_ask_display_ = -1;
- double last_spread_display_ = -1;
+ QString last_price_text_;
+ QString last_change_text_;
+ QString last_high_text_;
+ QString last_low_text_;
+ QString last_volume_text_;
+ QString last_bid_text_;
+ QString last_ask_text_;
+ QString last_spread_text_;
};
} // namespace fincept::screens::crypto
diff --git a/fincept-qt/src/screens/crypto_trading/CryptoTimeSales.cpp b/fincept-qt/src/screens/crypto_trading/CryptoTimeSales.cpp
index 2a072d6fa..3c79ca3ae 100644
--- a/fincept-qt/src/screens/crypto_trading/CryptoTimeSales.cpp
+++ b/fincept-qt/src/screens/crypto_trading/CryptoTimeSales.cpp
@@ -8,6 +8,8 @@
#include <QPainter>
#include <QShowEvent>
+#include <algorithm>
+
namespace fincept::screens::crypto {
using namespace fincept::ui;
@@ -44,7 +46,13 @@ CryptoTimeSales::CryptoTimeSales(QWidget* parent) : QWidget(parent) {
repaint_timer_->setSingleShot(true);
repaint_timer_->setInterval(50); // max 20fps
connect(repaint_timer_, &QTimer::timeout, this, [this]() { update(); });
- connect(&ui::ThemeManager::instance(), &ui::ThemeManager::theme_changed, this, [this]() { update(); });
+ // The tape is a cached QPixmap: without marking the cache dirty a theme
+ // change re-blitted the OLD pixmap and the tape kept the previous
+ // palette until the next trade arrived.
+ connect(&ui::ThemeManager::instance(), &ui::ThemeManager::theme_changed, this, [this]() {
+ cache_dirty_ = true;
+ update();
+ });
}
void CryptoTimeSales::showEvent(QShowEvent* e) {
@@ -116,10 +124,11 @@ void CryptoTimeSales::rebuild_cache() {
// Header row
p.setPen(kTextDim());
- p.drawText(QRect(4, 0, 70, ROW_H), Qt::AlignLeft | Qt::AlignVCenter, "TIME");
- p.drawText(QRect(74, 0, w / 3, ROW_H), Qt::AlignRight | Qt::AlignVCenter, "PRICE");
- p.drawText(QRect(74 + w / 3, 0, w / 3, ROW_H), Qt::AlignRight | Qt::AlignVCenter, "QTY");
- p.drawText(QRect(w - 30, 0, 26, ROW_H), Qt::AlignCenter | Qt::AlignVCenter, "S");
+ p.drawText(QRect(4, 0, 70, ROW_H), Qt::AlignLeft | Qt::AlignVCenter, tr("TIME"));
+ p.drawText(QRect(74, 0, w / 3, ROW_H), Qt::AlignRight | Qt::AlignVCenter, tr("PRICE"));
+ p.drawText(QRect(74 + w / 3, 0, w / 3, ROW_H), Qt::AlignRight | Qt::AlignVCenter, tr("QTY"));
+ p.drawText(QRect(w - 30, 0, 26, ROW_H), Qt::AlignCenter | Qt::AlignVCenter,
+ tr("S", "column header: trade side (buy/sell)"));
const int max_rows = (h - ROW_H) / ROW_H;
const int count = std::min(static_cast<int>(snapshot.size()), max_rows);
@@ -138,18 +147,19 @@ void CryptoTimeSales::rebuild_cache() {
p.drawText(QRect(4, y, 70, ROW_H), Qt::AlignLeft | Qt::AlignVCenter,
QDateTime::fromMSecsSinceEpoch(t.timestamp).toString("HH:mm:ss"));
- // Price
+ // Price — magnitude-scaled precision; a fixed 2 dp printed every fill
+ // on a sub-cent pair as "0.00", making the tape useless.
p.setPen(price_color);
- p.drawText(QRect(74, y, w / 3, ROW_H), Qt::AlignRight | Qt::AlignVCenter, QString::number(t.price, 'f', 2));
+ p.drawText(QRect(74, y, w / 3, ROW_H), Qt::AlignRight | Qt::AlignVCenter, format_price_plain(t.price));
// Quantity
p.setPen(kTextSec());
- p.drawText(QRect(74 + w / 3, y, w / 3, ROW_H), Qt::AlignRight | Qt::AlignVCenter,
- QString::number(t.amount, 'f', 4));
+ p.drawText(QRect(74 + w / 3, y, w / 3, ROW_H), Qt::AlignRight | Qt::AlignVCenter, format_size(t.amount));
// Side indicator
p.setPen(price_color);
- p.drawText(QRect(w - 30, y, 26, ROW_H), Qt::AlignCenter | Qt::AlignVCenter, is_buy ? "B" : "S");
+ p.drawText(QRect(w - 30, y, 26, ROW_H), Qt::AlignCenter | Qt::AlignVCenter,
+ is_buy ? tr("B", "trade side: buy") : tr("S", "trade side: sell"));
}
if (count == 0) {
diff --git a/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen.cpp b/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen.cpp
index d5a041397..75303ace8 100644
--- a/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen.cpp
+++ b/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen.cpp
@@ -476,16 +476,22 @@ void CryptoTradingScreen::retranslateUi() {
// ============================================================================
void CryptoTradingScreen::hub_subscribe_topics() {
- // Drop any prior connections to this owner (handles symbol/exchange swap).
+ auto& hub = fincept::datahub::DataHub::instance();
+
+ // Drop any prior subscriptions (handles symbol/exchange swap). This runs
+ // from signal handlers (chart timeframe change, symbol switch) that can
+ // themselves be reached from a hub dispatch, so per P13 the owner is
+ // retired with deleteLater() rather than `delete`. Unsubscribing first
+ // means the deferred destruction can't deliver a stale tick in between.
if (ws_subscription_owner_) {
- delete ws_subscription_owner_;
+ hub.unsubscribe(ws_subscription_owner_);
+ ws_subscription_owner_->deleteLater();
ws_subscription_owner_ = nullptr;
}
// ws_subscription_owner_ is a context QObject the subscriptions are bound
// to. Destroying it auto-cancels every subscription on swap.
ws_subscription_owner_ = new QObject(this);
- auto& hub = fincept::datahub::DataHub::instance();
const QString ex = exchange_id_;
QPointer<CryptoTradingScreen> self = this;
@@ -547,7 +553,11 @@ void CryptoTradingScreen::hub_subscribe_topics() {
void CryptoTradingScreen::hub_unsubscribe_topics() {
if (ws_subscription_owner_) {
- delete ws_subscription_owner_;
+ // Same reasoning as hub_subscribe_topics(): drop the subscriptions
+ // synchronously, destroy the context object on the next event-loop
+ // turn (P13 — never `delete` a QObject that may be inside a dispatch).
+ fincept::datahub::DataHub::instance().unsubscribe(ws_subscription_owner_);
+ ws_subscription_owner_->deleteLater();
ws_subscription_owner_ = nullptr;
}
LOG_INFO(TAG, "Direct WS signals detached");
diff --git a/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen_AsyncFetch.cpp b/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen_AsyncFetch.cpp
index 2d2c67592..c36189983 100644
--- a/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen_AsyncFetch.cpp
+++ b/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen_AsyncFetch.cpp
@@ -27,6 +27,7 @@
#include <QCompleter>
#include <QDateTime>
#include <QHBoxLayout>
+#include <QJsonObject>
#include <QPointer>
#include <QSplitter>
#include <QStringListModel>
@@ -110,7 +111,15 @@ void CryptoTradingScreen::async_fetch_live_positions() {
// Widget destroyed before dispatch — no counter to decrement.
return;
}
- auto result = ExchangeService::instance().fetch_positions_live(self->selected_symbol_);
+ // A throw here would skip the invokeMethod below, leaving
+ // `live_inflight_` permanently above zero — `refresh_live_data()`
+ // then returns early on every tick and LIVE data never updates again.
+ QJsonObject result;
+ try {
+ result = ExchangeService::instance().fetch_positions_live(self->selected_symbol_);
+ } catch (...) {
+ LOG_WARN("CryptoTrading", "fetch_positions_live threw");
+ }
QMetaObject::invokeMethod(
self,
[self, result]() {
@@ -129,7 +138,12 @@ void CryptoTradingScreen::async_fetch_live_orders() {
(void)QtConcurrent::run([self]() {
if (!self)
return;
- auto result = ExchangeService::instance().fetch_open_orders_live(self->selected_symbol_);
+ QJsonObject result;
+ try {
+ result = ExchangeService::instance().fetch_open_orders_live(self->selected_symbol_);
+ } catch (...) {
+ LOG_WARN("CryptoTrading", "fetch_open_orders_live threw");
+ }
QMetaObject::invokeMethod(
self,
[self, result]() {
@@ -145,13 +159,30 @@ void CryptoTradingScreen::async_fetch_live_orders() {
void CryptoTradingScreen::async_fetch_live_balance() {
QPointer<CryptoTradingScreen> self = this;
- (void)QtConcurrent::run([self]() {
+ // The quote currency of the pair actually being traded, so a USD- or
+ // USDC-margined account isn't reported as $0.00. Hard-coding "USDT" made
+ // the whole LIVE balance read empty on every non-USDT venue — which looks
+ // identical to a genuinely empty account right next to a live BUY button.
+ const int slash = selected_symbol_.indexOf(QLatin1Char('/'));
+ QString quote = slash > 0 ? selected_symbol_.mid(slash + 1) : QStringLiteral("USDT");
+ const int colon = quote.indexOf(QLatin1Char(':')); // settled perps: "BTC/USDC:USDC"
+ if (colon > 0)
+ quote = quote.left(colon);
+ (void)QtConcurrent::run([self, quote]() {
if (!self)
return;
- auto result = ExchangeService::instance().fetch_balance();
+ QJsonObject result;
+ try {
+ result = ExchangeService::instance().fetch_balance();
+ } catch (...) {
+ // Must still post back: `live_inflight_` is only decremented on the
+ // UI thread, and if it never reaches zero `refresh_live_data()`
+ // skips every subsequent tick and live data freezes permanently.
+ result = QJsonObject{{QStringLiteral("error"), QStringLiteral("balance fetch threw")}};
+ }
QMetaObject::invokeMethod(
self,
- [self, result]() {
+ [self, result, quote]() {
if (!self)
return;
// A daemon/bridge failure (e.g. bad API key) returns an "error"
@@ -163,9 +194,22 @@ void CryptoTradingScreen::async_fetch_live_balance() {
self->bottom_panel_->set_balance_unavailable(
result.value("error").toString(QStringLiteral("no data")));
} else {
- double total = result.value("total").toObject().value("USDT").toDouble();
- double free = result.value("free").toObject().value("USDT").toDouble();
- double used = result.value("used").toObject().value("USDT").toDouble();
+ const QJsonObject totals = result.value("total").toObject();
+ // Fall back through the common stable quotes so an account
+ // funded in USDC on a USDT-quoted pair still shows.
+ QString ccy = quote;
+ if (!totals.contains(ccy)) {
+ for (const QString& alt : {QStringLiteral("USDT"), QStringLiteral("USDC"),
+ QStringLiteral("USD"), QStringLiteral("BUSD")}) {
+ if (totals.contains(alt)) {
+ ccy = alt;
+ break;
+ }
+ }
+ }
+ const double total = totals.value(ccy).toDouble();
+ const double free = result.value("free").toObject().value(ccy).toDouble();
+ const double used = result.value("used").toObject().value(ccy).toDouble();
self->bottom_panel_->set_live_balance(free, total, used);
self->order_entry_->set_balance(free);
}
@@ -184,7 +228,12 @@ void CryptoTradingScreen::async_fetch_my_trades() {
(void)QtConcurrent::run([self]() {
if (!self)
return;
- auto result = ExchangeService::instance().fetch_my_trades(self->selected_symbol_);
+ QJsonObject result;
+ try {
+ result = ExchangeService::instance().fetch_my_trades(self->selected_symbol_);
+ } catch (...) {
+ LOG_WARN("CryptoTrading", "fetch_my_trades threw");
+ }
QMetaObject::invokeMethod(
self,
[self, result]() {
diff --git a/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen_Handlers.cpp b/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen_Handlers.cpp
index ee0002e0e..ca58732ef 100644
--- a/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen_Handlers.cpp
+++ b/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen_Handlers.cpp
@@ -187,6 +187,26 @@ void CryptoTradingScreen::switch_symbol(const QString& symbol) {
void CryptoTradingScreen::on_mode_toggled() {
const bool is_live = mode_btn_->isChecked();
+
+ // Arming LIVE turns every subsequent click on the ticket into real money
+ // on a real exchange. It used to happen silently on one toggle click, with
+ // only a colour change on a 22 px button to signal it. Require an explicit
+ // acknowledgement; on decline, snap the toggle back rather than leaving
+ // the button and the mode out of sync.
+ if (is_live && trading_mode_ != TradingMode::Live) {
+ const auto answer =
+ QMessageBox::warning(this, tr("Switch to LIVE trading"),
+ tr("LIVE mode places real orders on %1 with real funds.\n\n"
+ "Orders are irreversible once filled. Make sure the API key configured "
+ "for this exchange is the account you intend to trade.\n\nSwitch to LIVE?")
+ .arg(exchange_id_.toUpper()),
+ QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
+ if (answer != QMessageBox::Yes) {
+ mode_btn_->setChecked(false);
+ return;
+ }
+ }
+
trading_mode_ = is_live ? TradingMode::Live : TradingMode::Paper;
mode_btn_->setText(is_live ? tr("LIVE") : tr("PAPER"));
mode_btn_->setProperty("mode", is_live ? "live" : "paper");
@@ -274,11 +294,35 @@ void CryptoTradingScreen::on_order_submitted(const QString& side, const QString&
// A live order is real money with no undo, and single orders previously
// had NO confirmation — one click or a held Ctrl+Enter fired real funds.
// Gate it behind an explicit confirm (close-all/cancel-all already do).
- const QString px_txt = order_type == "market" ? tr("market price") : QString::number(price, 'f', 8);
- const QString confirm_msg = tr("Place a LIVE %1 %2 order with real funds?\n\n%3 qty %4 @ %5")
- .arg(side.toUpper(), order_type.toUpper(), selected_symbol_)
- .arg(qty)
- .arg(px_txt);
+ //
+ // The dialog must show every fact the user needs to catch a
+ // fat-finger: venue, pair, side, type, exact quantity and — most
+ // importantly — the resulting notional. `.arg(double)` defaults to
+ // %g with 6 significant digits, which rendered a quantity of
+ // 0.000012345678 as "1.23457e-05"; format explicitly instead.
+ const double ref_px =
+ (order_type == "market") ? ExchangeService::instance().get_cached_price(selected_symbol_).last : price;
+ const QString px_txt = order_type == "market" ? tr("market price") : crypto::format_price_plain(price);
+ QString confirm_msg = tr("Place a LIVE %1 %2 order with real funds?\n\n"
+ "Exchange %3\n"
+ "Pair %4\n"
+ "Quantity %5\n"
+ "Price %6")
+ .arg(side.toUpper(), order_type.toUpper(), exchange_id_.toUpper(),
+ selected_symbol_, crypto::format_size(qty), px_txt);
+ if (ref_px > 0.0) {
+ confirm_msg += tr("\nNotional ≈ %1").arg(crypto::format_price_plain(qty * ref_px));
+ } else {
+ confirm_msg += tr("\nNotional unknown — no live price for this pair yet");
+ }
+ if (stop_price > 0.0)
+ confirm_msg += tr("\nStop %1").arg(crypto::format_price_plain(stop_price));
+ if (sl > 0.0)
+ confirm_msg += tr("\nStop loss %1").arg(crypto::format_price_plain(sl));
+ if (tp > 0.0)
+ confirm_msg += tr("\nTake profit %1").arg(crypto::format_price_plain(tp));
+ if (order_entry_->reduce_only())
+ confirm_msg += tr("\nReduce-only");
if (QMessageBox::question(this, tr("Confirm Live Order"), confirm_msg, QMessageBox::Yes | QMessageBox::No,
QMessageBox::No) != QMessageBox::Yes)
return;
diff --git a/fincept-qt/src/screens/crypto_trading/CryptoTypes.h b/fincept-qt/src/screens/crypto_trading/CryptoTypes.h
index a8b05fde7..7742f0961 100644
--- a/fincept-qt/src/screens/crypto_trading/CryptoTypes.h
+++ b/fincept-qt/src/screens/crypto_trading/CryptoTypes.h
@@ -8,8 +8,58 @@
#include <QString>
#include <QVector>
+#include <cmath>
+
namespace fincept::screens::crypto {
+// ── Price / size formatting ──────────────────────────────────────────────────
+//
+// Crypto spans ~11 orders of magnitude of unit price: BTC trades near 1e5 and
+// PEPE/SHIB near 1e-8. Every price on this screen used to be rendered with a
+// hard-coded `'f', 2`, so for any sub-cent pair the ticker read "$0.00", the
+// order book showed twelve identical "0.00" levels, the depth-chart axis
+// printed five zeros, and the ticker's own change-detection (which compared
+// values rounded to 2 dp) suppressed updates entirely — the screen looked
+// frozen. Scale the precision to the magnitude instead.
+//
+// Header-only + inline so every widget in this directory shares one
+// definition without a new translation unit.
+
+/// Decimal places appropriate for a unit price of magnitude `v`.
+inline int price_decimals(double v) {
+ const double a = std::fabs(v);
+ if (a >= 1000.0)
+ return 2;
+ if (a >= 1.0)
+ return 4;
+ if (a >= 0.01)
+ return 5;
+ if (a >= 0.0001)
+ return 6;
+ return 8;
+}
+
+/// Plain number, no currency symbol, magnitude-appropriate precision.
+inline QString format_price_plain(double v) {
+ return QString::number(v, 'f', price_decimals(v));
+}
+
+/// `$`-prefixed price with magnitude-appropriate precision.
+inline QString format_price_usd(double v) {
+ return QStringLiteral("$") + QString::number(v, 'f', price_decimals(v));
+}
+
+/// Order/position size. Large sizes (meme-coin lots run to billions of units)
+/// don't need 6 dp; small ones do.
+inline QString format_size(double v) {
+ const double a = std::fabs(v);
+ if (a >= 1e6)
+ return QString::number(v, 'f', 2);
+ if (a >= 1.0)
+ return QString::number(v, 'f', 4);
+ return QString::number(v, 'f', 8);
+}
+
// Order book level (UI-ready, with cumulative for depth bars)
struct OBLevel {
double price = 0.0;
diff --git a/fincept-qt/src/screens/dashboard/DashboardScreen.cpp b/fincept-qt/src/screens/dashboard/DashboardScreen.cpp
index 95571d2ae..cd2ce446f 100644
--- a/fincept-qt/src/screens/dashboard/DashboardScreen.cpp
+++ b/fincept-qt/src/screens/dashboard/DashboardScreen.cpp
@@ -18,8 +18,10 @@
#include <QJsonDocument>
#include <QEvent>
#include <QHideEvent>
+#include <QKeySequence>
#include <QPalette>
#include <QPointer>
+#include <QShortcut>
#include <QShowEvent>
#include <QVBoxLayout>
#include <QtConcurrent/QtConcurrent>
@@ -116,20 +118,28 @@ DashboardScreen::DashboardScreen(QWidget* parent) : QWidget(parent) {
// ── 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);
+ // The toolbar's LIVE badge was hardcoded — set_connected() had no caller
+ // anywhere in the codebase. Drive it from the status bar's API health probe.
+ connect(status_bar_, &DashboardStatusBar::connectivity_changed, toolbar_, &DashboardToolBar::set_connected);
connect(canvas_, &DashboardCanvas::layout_changed, this, [this](const GridLayout&) { save_timer_->start(); });
// ── Toolbar buttons ──
- connect(toolbar_, &DashboardToolBar::toggle_pulse_clicked, this, [this]() {
+ // Kept as named lambdas so the keyboard shortcuts below drive exactly the
+ // same code path as the toolbar buttons.
+ auto toggle_pulse = [this]() {
pulse_visible_ = !pulse_visible_;
market_pulse_->setVisible(pulse_visible_);
- });
-
- connect(toolbar_, &DashboardToolBar::add_widget_clicked, this, [this]() {
+ };
+ auto open_add_widget = [this]() {
auto* dlg = new AddWidgetDialog(this);
connect(dlg, &AddWidgetDialog::widget_selected, canvas_, &DashboardCanvas::add_widget);
dlg->exec();
dlg->deleteLater();
- });
+ };
+
+ connect(toolbar_, &DashboardToolBar::toggle_pulse_clicked, this, toggle_pulse);
+
+ connect(toolbar_, &DashboardToolBar::add_widget_clicked, this, open_add_widget);
connect(toolbar_, &DashboardToolBar::reset_layout_clicked, this, [this]() {
auto* dlg = new TemplatePicker(this);
@@ -148,13 +158,26 @@ DashboardScreen::DashboardScreen(QWidget* parent) : QWidget(parent) {
connect(toolbar_, &DashboardToolBar::refresh_clicked, this, &DashboardScreen::on_refresh_clicked);
connect(toolbar_, &DashboardToolBar::toggle_compact_clicked, this, [this]() {
- static bool compact = false;
- compact = !compact;
- canvas_->set_row_height(compact ? 40 : 60);
+ compact_rows_ = !compact_rows_;
+ canvas_->set_row_height(compact_rows_ ? 40 : 60);
});
connect(&ui::ThemeManager::instance(), &ui::ThemeManager::theme_changed, this,
[this](const ui::ThemeTokens&) { refresh_theme(); });
+
+ // ── Keyboard shortcuts ────────────────────────────────────────────────────
+ // The dashboard had zero keyboard affordances; every action needed a mouse
+ // trip to the toolbar. WindowShortcut scope so they fire while any child
+ // of the dashboard has focus, but not while another screen is active.
+ auto add_shortcut = [this](QKeySequence seq, auto&& handler) {
+ auto* sc = new QShortcut(seq, this);
+ sc->setContext(Qt::WindowShortcut);
+ connect(sc, &QShortcut::activated, this, handler);
+ };
+ add_shortcut(QKeySequence(Qt::Key_F5), [this]() { on_refresh_clicked(); });
+ add_shortcut(QKeySequence(QKeySequence::Save), [this]() { save_layout(); });
+ add_shortcut(QKeySequence(Qt::CTRL | Qt::Key_N), open_add_widget);
+ add_shortcut(QKeySequence(Qt::CTRL | Qt::Key_P), toggle_pulse);
}
// ── Theme ─────────────────────────────────────────────────────────────────────
@@ -240,13 +263,13 @@ void DashboardScreen::hideEvent(QHideEvent* event) {
void DashboardScreen::refresh_ticker() {
if (!ticker_bar_)
return;
-
- const QStringList symbols = ticker_bar_->symbols();
- if (symbols.isEmpty())
- return;
-
// Hub path: user edited symbols → drop old subs, attach to new set,
// kick the hub so consumers see data immediately.
+ //
+ // Note: this used to early-return on an empty symbol list, which left the
+ // *previous* symbols subscribed and still scrolling after the user cleared
+ // the bar. hub_resubscribe_ticker() handles the empty case correctly
+ // (unsubscribe, then no-op).
hub_resubscribe_ticker();
}
@@ -304,8 +327,10 @@ void DashboardScreen::hub_resubscribe_ticker() {
ticker_cache_.clear();
ticker_subscribed_ = ticker_bar_->symbols();
- if (ticker_subscribed_.isEmpty())
+ if (ticker_subscribed_.isEmpty()) {
+ ticker_bar_->set_data({}); // clear stale entries so nothing misleading scrolls
return;
+ }
QStringList topics;
topics.reserve(ticker_subscribed_.size());
@@ -385,7 +410,6 @@ void DashboardScreen::save_layout() {
}
QString encoded = buf.toBase64();
- QPointer<DashboardScreen> self = this;
(void)QtConcurrent::run(
[encoded]() { fincept::SettingsRepository::instance().set("dashboard_canvas_layout", encoded, "dashboard"); });
}
@@ -430,6 +454,14 @@ void DashboardScreen::restore_layout() {
return;
}
+ // Clamp the grid geometry before anything downstream uses it.
+ // A truncated / corrupted blob previously produced items with
+ // cols == 0 or w == 0, which grid_to_rect() turns into
+ // zero-width tiles and compact_vertical() spins over.
+ layout.cols = qBound(1, layout.cols, 48);
+ layout.row_h = qBound(10, layout.row_h, 400);
+ layout.margin = qBound(0, layout.margin, 64);
+
for (int i = 0; i < count; ++i) {
GridItem item;
stream >> item.id >> item.instance_id;
@@ -442,9 +474,26 @@ void DashboardScreen::restore_layout() {
if (doc.isObject())
item.config = doc.object();
}
+ // Stop at the first short read rather than appending
+ // default-constructed garbage for the remaining items.
+ if (stream.status() != QDataStream::Ok)
+ break;
+ if (item.id.isEmpty() || item.instance_id.isEmpty())
+ continue;
+ item.cell.min_w = qBound(1, item.cell.min_w, layout.cols);
+ item.cell.min_h = qBound(1, item.cell.min_h, 64);
+ item.cell.w = qBound(item.cell.min_w, item.cell.w, layout.cols);
+ item.cell.h = qBound(item.cell.min_h, item.cell.h, 64);
+ item.cell.x = qBound(0, item.cell.x, layout.cols - item.cell.w);
+ item.cell.y = qBound(0, item.cell.y, 999);
layout.items.append(item);
}
+ if (layout.items.isEmpty()) {
+ self->build_default_layout();
+ return;
+ }
+
self->canvas_->load_layout(layout);
},
Qt::QueuedConnection);
diff --git a/fincept-qt/src/screens/dashboard/DashboardScreen.h b/fincept-qt/src/screens/dashboard/DashboardScreen.h
index 771a0bc75..02a44d9a4 100644
--- a/fincept-qt/src/screens/dashboard/DashboardScreen.h
+++ b/fincept-qt/src/screens/dashboard/DashboardScreen.h
@@ -61,6 +61,10 @@ class DashboardScreen : public QWidget {
bool pulse_visible_ = true;
bool layout_restored_ = false;
bool split_sized_ = false;
+ /// COMPACT toggle state. Was a function-local `static bool` in the lambda,
+ /// i.e. shared by every DashboardScreen instance and out of sync with the
+ /// canvas after a screen rebuild.
+ bool compact_rows_ = false;
QHash<QString, services::QuoteData> ticker_cache_;
QStringList ticker_subscribed_;
diff --git a/fincept-qt/src/screens/dashboard/DashboardStatusBar.cpp b/fincept-qt/src/screens/dashboard/DashboardStatusBar.cpp
index a88839f59..42eea4776 100644
--- a/fincept-qt/src/screens/dashboard/DashboardStatusBar.cpp
+++ b/fincept-qt/src/screens/dashboard/DashboardStatusBar.cpp
@@ -180,6 +180,13 @@ void DashboardStatusBar::refresh_theme() {
.arg(ui::colors::POSITIVE()) // %5
.arg(ui::colors::WARNING()) // %6
.arg(ui::colors::CYAN())); // %7
+
+ // The bar-level sheet just replaced the per-label colour overrides —
+ // force them to be re-applied against the new tokens on the next tick.
+ mem_color_applied_.clear();
+ if (feeds_label_)
+ feeds_label_->setStyleSheet(QString("color:%1;font-weight:bold;background:transparent;")
+ .arg(feeds_connected_ ? ui::colors::POSITIVE() : ui::colors::NEGATIVE()));
}
void DashboardStatusBar::showEvent(QShowEvent* event) {
@@ -222,10 +229,13 @@ void DashboardStatusBar::set_widget_count(int count) {
}
void DashboardStatusBar::set_connected(bool connected) {
+ if (feeds_connected_ == connected && last_latency_ms_ != -2)
+ return; // no change — skip the CSS reparse
feeds_connected_ = connected;
feeds_label_->setText(connected ? tr("CONNECTED") : tr("DISCONNECTED"));
feeds_label_->setStyleSheet(QString("color:%1;font-weight:bold;background:transparent;")
.arg(connected ? ui::colors::POSITIVE() : ui::colors::NEGATIVE()));
+ emit connectivity_changed(connected);
}
void DashboardStatusBar::update_memory() {
@@ -263,7 +273,10 @@ void DashboardStatusBar::update_memory() {
: rss_mb < 1024.0 ? ui::colors::AMBER()
: ui::colors::NEGATIVE();
mem_label_->setText(tr("MEM: %1 MB").arg(rss_mb, 0, 'f', 0));
- mem_label_->setStyleSheet(QString("color:%1;background:transparent;").arg(color));
+ if (color != mem_color_applied_) {
+ mem_color_applied_ = color;
+ mem_label_->setStyleSheet(QString("color:%1;background:transparent;").arg(color));
+ }
}
void DashboardStatusBar::ping_api() {
@@ -278,6 +291,11 @@ void DashboardStatusBar::ping_api() {
}
void DashboardStatusBar::set_latency(int ms) {
+ // The health probe is the only real connectivity signal this screen has;
+ // FEEDS previously said "CONNECTED" permanently because set_connected()
+ // had no caller at all.
+ set_connected(ms >= 0);
+
last_latency_ms_ = ms;
if (ms < 0) {
latency_label_->setText(tr("LAT: ERR"));
diff --git a/fincept-qt/src/screens/dashboard/DashboardStatusBar.h b/fincept-qt/src/screens/dashboard/DashboardStatusBar.h
index dbfce3321..11dcdad38 100644
--- a/fincept-qt/src/screens/dashboard/DashboardStatusBar.h
+++ b/fincept-qt/src/screens/dashboard/DashboardStatusBar.h
@@ -28,6 +28,12 @@ class DashboardStatusBar : public QWidget {
void set_widget_count(int count);
void set_connected(bool connected);
+ signals:
+ /// Emitted when the API health probe flips between reachable and
+ /// unreachable. DashboardScreen forwards it to the toolbar so the "LIVE"
+ /// badge stops claiming a live feed while the backend is down.
+ void connectivity_changed(bool connected);
+
protected:
void showEvent(QShowEvent* event) override;
void hideEvent(QHideEvent* event) override;
@@ -55,6 +61,9 @@ class DashboardStatusBar : public QWidget {
int layout_count_ = 0;
bool feeds_connected_ = true;
int last_latency_ms_ = -2; // -2 = uninitialised, -1 = error
+ /// Last colour applied to mem_label_ — the probe ticks every 5s but the
+ /// colour bucket almost never changes, so skip the CSS reparse.
+ QString mem_color_applied_;
PendingOrdersBadge* pending_badge_ = nullptr;
fincept::ui::NotifBell* notif_bell_ = nullptr;
diff --git a/fincept-qt/src/screens/dashboard/DashboardToolBar.cpp b/fincept-qt/src/screens/dashboard/DashboardToolBar.cpp
index 274373638..861cf8f8c 100644
--- a/fincept-qt/src/screens/dashboard/DashboardToolBar.cpp
+++ b/fincept-qt/src/screens/dashboard/DashboardToolBar.cpp
@@ -96,12 +96,14 @@ DashboardToolBar::DashboardToolBar(QWidget* parent) : QWidget(parent) {
compact_btn_ = new QPushButton(tr("COMPACT"));
compact_btn_->setFixedHeight(20);
compact_btn_->setObjectName("dtBtn");
+ compact_btn_->setToolTip(tr("Toggle compact row height"));
connect(compact_btn_, &QPushButton::clicked, this, &DashboardToolBar::toggle_compact_clicked);
rl->addWidget(compact_btn_);
pulse_btn_ = new QPushButton(tr("PULSE"));
pulse_btn_->setFixedHeight(20);
pulse_btn_->setObjectName("dtBtn");
+ pulse_btn_->setToolTip(tr("Show / hide the Market Pulse panel (Ctrl+P)"));
connect(pulse_btn_, &QPushButton::clicked, this, &DashboardToolBar::toggle_pulse_clicked);
rl->addWidget(pulse_btn_);
@@ -110,28 +112,35 @@ DashboardToolBar::DashboardToolBar(QWidget* parent) : QWidget(parent) {
refresh_btn_ = new QPushButton(tr("REFRESH"));
refresh_btn_->setFixedHeight(20);
refresh_btn_->setObjectName("dtBtn");
- refresh_btn_->setToolTip(tr("Force-refresh all live data on the dashboard"));
+ refresh_btn_->setToolTip(tr("Force-refresh all live data on the dashboard (F5)"));
connect(refresh_btn_, &QPushButton::clicked, this, &DashboardToolBar::refresh_clicked);
rl->addWidget(refresh_btn_);
add_btn_ = new QPushButton(tr("+ ADD"));
add_btn_->setFixedHeight(20);
add_btn_->setObjectName("dtAddBtn");
+ add_btn_->setToolTip(tr("Add a widget to the dashboard (Ctrl+N)"));
connect(add_btn_, &QPushButton::clicked, this, &DashboardToolBar::add_widget_clicked);
rl->addWidget(add_btn_);
save_btn_ = new QPushButton(tr("SAVE"));
save_btn_->setFixedHeight(20);
save_btn_->setObjectName("dtBtn");
+ save_btn_->setToolTip(tr("Save the current widget layout (Ctrl+S)"));
connect(save_btn_, &QPushButton::clicked, this, &DashboardToolBar::save_layout_clicked);
rl->addWidget(save_btn_);
reset_btn_ = new QPushButton(tr("RESET"));
reset_btn_->setFixedHeight(20);
reset_btn_->setObjectName("dtResetBtn");
+ reset_btn_->setToolTip(tr("Replace the current layout with a template"));
connect(reset_btn_, &QPushButton::clicked, this, &DashboardToolBar::reset_layout_clicked);
rl->addWidget(reset_btn_);
+ // Accessible names + an explicit tab order: the terminal shipped with zero
+ // of either, so the toolbar was unreachable/unannounced by keyboard.
+ apply_accessibility();
+
hl->addWidget(right);
connect(&ui::ThemeManager::instance(), &ui::ThemeManager::theme_changed, this,
@@ -150,6 +159,39 @@ void DashboardToolBar::hideEvent(QHideEvent* event) {
clock_timer_.stop();
}
+void DashboardToolBar::apply_accessibility() {
+ struct Named {
+ QWidget* w;
+ QString name;
+ };
+ const Named named[] = {
+ {clock_btn_, tr("Clock — click to toggle UTC / local time")},
+ {status_text_, tr("Feed status")},
+ {widget_count_, tr("Widget count")},
+ {compact_btn_, tr("Toggle compact row height")},
+ {pulse_btn_, tr("Show or hide the Market Pulse panel")},
+ {refresh_btn_, tr("Refresh all dashboard data")},
+ {add_btn_, tr("Add widget")},
+ {save_btn_, tr("Save layout")},
+ {reset_btn_, tr("Reset layout from a template")},
+ };
+ for (const auto& n : named) {
+ if (n.w)
+ n.w->setAccessibleName(n.name);
+ }
+
+ // Left-to-right tab order across the action buttons.
+ QWidget* chain[] = {clock_btn_, compact_btn_, pulse_btn_, refresh_btn_, add_btn_, save_btn_, reset_btn_};
+ QWidget* prev = nullptr;
+ for (QWidget* w : chain) {
+ if (!w)
+ continue;
+ if (prev)
+ setTabOrder(prev, w);
+ prev = w;
+ }
+}
+
void DashboardToolBar::refresh_theme() {
const QColor surface(ui::colors::BG_SURFACE());
apply_solid_background(this, surface);
@@ -163,7 +205,6 @@ void DashboardToolBar::refresh_theme() {
"#dtBrand { color:%4; font-weight:bold; letter-spacing:1px; background:transparent; }"
"#dtSub { color:%5; font-weight:bold; background:transparent; }"
"#dtStatus { color:%6; font-weight:bold; background:transparent; }"
- "#dtClock { color:%7; background:transparent; }"
"#dtWidgetCount { color:%8; font-weight:bold; background:transparent; }"
"#dtBtn { background:%9; border:1px solid %3; color:%7; padding:0 10px; font-weight:bold; }"
"#dtBtn:hover { background:%10; color:%11; border-color:%12; }"
@@ -246,14 +287,25 @@ void DashboardToolBar::retranslateUi() {
pulse_btn_->setText(tr("PULSE"));
if (refresh_btn_) {
refresh_btn_->setText(tr("REFRESH"));
- refresh_btn_->setToolTip(tr("Force-refresh all live data on the dashboard"));
+ refresh_btn_->setToolTip(tr("Force-refresh all live data on the dashboard (F5)"));
}
- if (add_btn_)
+ if (add_btn_) {
add_btn_->setText(tr("+ ADD"));
- if (save_btn_)
+ add_btn_->setToolTip(tr("Add a widget to the dashboard (Ctrl+N)"));
+ }
+ if (save_btn_) {
save_btn_->setText(tr("SAVE"));
- if (reset_btn_)
+ save_btn_->setToolTip(tr("Save the current widget layout (Ctrl+S)"));
+ }
+ if (reset_btn_) {
reset_btn_->setText(tr("RESET"));
+ reset_btn_->setToolTip(tr("Replace the current layout with a template"));
+ }
+ if (compact_btn_)
+ compact_btn_->setToolTip(tr("Toggle compact row height"));
+ if (pulse_btn_)
+ pulse_btn_->setToolTip(tr("Show / hide the Market Pulse panel (Ctrl+P)"));
+ apply_accessibility();
update_clock();
}
diff --git a/fincept-qt/src/screens/dashboard/DashboardToolBar.h b/fincept-qt/src/screens/dashboard/DashboardToolBar.h
index 86bb17f07..5239151c3 100644
--- a/fincept-qt/src/screens/dashboard/DashboardToolBar.h
+++ b/fincept-qt/src/screens/dashboard/DashboardToolBar.h
@@ -35,6 +35,8 @@ class DashboardToolBar : public QWidget {
void update_clock();
void refresh_theme();
void retranslateUi();
+ /// Sets accessible names on every control and wires an explicit tab order.
+ void apply_accessibility();
QWidget* left_container_ = nullptr;
QWidget* right_container_ = nullptr;
diff --git a/fincept-qt/src/screens/dashboard/MarketPulsePanel.cpp b/fincept-qt/src/screens/dashboard/MarketPulsePanel.cpp
index 26cc4ddae..e3a8d3ac2 100644
--- a/fincept-qt/src/screens/dashboard/MarketPulsePanel.cpp
+++ b/fincept-qt/src/screens/dashboard/MarketPulsePanel.cpp
@@ -133,6 +133,12 @@ MarketPulsePanel::MarketPulsePanel(QWidget* parent) : QWidget(parent) {
hours_timer_->setInterval(60000); // 1 min — market open/close status
connect(hours_timer_, &QTimer::timeout, this, &MarketPulsePanel::refresh_market_hours);
+ // Coalesces a burst of ~70 per-symbol hub deliveries into one render pass.
+ render_timer_ = new QTimer(this);
+ render_timer_->setSingleShot(true);
+ render_timer_->setInterval(0);
+ connect(render_timer_, &QTimer::timeout, this, &MarketPulsePanel::flush_render);
+
connect(&ui::ThemeManager::instance(), &ui::ThemeManager::theme_changed, this,
[this](const ui::ThemeTokens&) { refresh_theme(); });
refresh_theme();
@@ -282,8 +288,13 @@ void MarketPulsePanel::refresh_theme() {
// Re-resolve data-driven status dot/label colors.
refresh_market_hours();
- // Mover rows (gainers/losers) are fully rebuilt by refresh_data().
- // Trigger a refresh so they pick up new theme colors.
+ // Mover rows keep their chrome in one stylesheet per section.
+ style_mover_section(gainers_rows_, /*positive_section=*/true);
+ style_mover_section(losers_rows_, /*positive_section=*/false);
+
+ // Force the Fear & Greed labels to re-apply against the new tokens.
+ fg_applied_color_.clear();
+
if (isVisible()) {
rebuild_breadth_from_cache();
rebuild_movers_from_cache();
@@ -304,6 +315,29 @@ void MarketPulsePanel::hideEvent(QHideEvent* e) {
QWidget::hideEvent(e);
hub_unsubscribe_all();
hours_timer_->stop();
+ if (render_timer_)
+ render_timer_->stop();
+}
+
+void MarketPulsePanel::schedule_render() {
+ if (render_timer_ && !render_timer_->isActive())
+ render_timer_->start();
+}
+
+void MarketPulsePanel::flush_render() {
+ if (breadth_dirty_) {
+ breadth_dirty_ = false;
+ rebuild_breadth_from_cache();
+ }
+ if (movers_dirty_) {
+ movers_dirty_ = false;
+ rebuild_movers_from_cache();
+ }
+ if (snapshot_dirty_) {
+ snapshot_dirty_ = false;
+ rebuild_snapshot_from_cache();
+ }
+ update_loading_progress();
}
// ── Header ───────────────────────────────────────────────────────────────────
@@ -489,39 +523,66 @@ QWidget* MarketPulsePanel::build_breadth_section() {
// ── Top Movers ────────────────────────────────────────────────────────────────
-QWidget* MarketPulsePanel::build_mover_row(const QString& symbol, double change, const QString& volume) {
- auto* w = new QWidget(this);
- w->setStyleSheet(QString("border-bottom: 1px solid %1;").arg(ui::colors::BORDER_DIM()));
+// Builds ONE reusable mover row. All styling comes from the section-level
+// stylesheet installed by style_mover_section() — no per-row setStyleSheet.
+MarketPulsePanel::MoverRow MarketPulsePanel::make_mover_row(QWidget* parent, QVBoxLayout* into, bool /*positive*/) {
+ MoverRow r;
+ r.container = new QWidget(parent);
+ r.container->setObjectName("pulseMoverRow");
- auto* hl = new QHBoxLayout(w);
+ auto* hl = new QHBoxLayout(r.container);
hl->setContentsMargins(12, 5, 12, 5);
hl->setSpacing(4);
- auto* sym = new QLabel(symbol);
- sym->setStyleSheet(QString("color: %1; font-size: 10px; font-weight: bold; background: transparent;")
- .arg(ui::colors::TEXT_PRIMARY()));
- hl->addWidget(sym);
+ r.symbol = new QLabel(r.container);
+ r.symbol->setObjectName("pulseMoverSym");
+ hl->addWidget(r.symbol);
hl->addStretch();
- bool positive = change >= 0;
- auto* arrow = new QLabel(positive ? QChar(0x25B2) : QChar(0x25BC));
- arrow->setStyleSheet(QString("color: %1; font-size: 8px; background: transparent;")
- .arg(positive ? ui::colors::POSITIVE() : ui::colors::NEGATIVE()));
- hl->addWidget(arrow);
-
- auto* chg = new QLabel(QString("%1%2%").arg(positive ? "+" : "").arg(change, 0, 'f', 2));
- chg->setStyleSheet(QString("color: %1; font-size: 10px; font-weight: bold; background: transparent;")
- .arg(positive ? ui::colors::POSITIVE() : ui::colors::NEGATIVE()));
- hl->addWidget(chg);
-
- if (!volume.isEmpty()) {
- auto* vol = new QLabel(tr("VOL: %1").arg(volume));
- vol->setStyleSheet(
- QString("color: %1; font-size: 8px; background: transparent;").arg(ui::colors::TEXT_TERTIARY()));
- hl->addWidget(vol);
- }
+ r.arrow = new QLabel(r.container);
+ r.arrow->setObjectName("pulseMoverArrow");
+ hl->addWidget(r.arrow);
- return w;
+ r.change = new QLabel(r.container);
+ r.change->setObjectName("pulseMoverChg");
+ hl->addWidget(r.change);
+
+ r.volume = new QLabel(r.container);
+ r.volume->setObjectName("pulseMoverVol");
+ hl->addWidget(r.volume);
+
+ into->addWidget(r.container);
+ return r;
+}
+
+void MarketPulsePanel::fill_mover_row(const MoverRow& row, const QString& symbol, double change,
+ const QString& volume) {
+ if (!row.container)
+ return;
+ row.container->setVisible(true);
+ row.symbol->setText(symbol);
+ row.arrow->setText(change >= 0 ? QString(QChar(0x25B2)) : QString(QChar(0x25BC)));
+ row.change->setText(QString("%1%2%").arg(change >= 0 ? "+" : "").arg(change, 0, 'f', 2));
+ row.volume->setText(volume.isEmpty() ? QString() : tr("VOL: %1").arg(volume));
+}
+
+void MarketPulsePanel::clear_mover_row(const MoverRow& row) {
+ if (row.container)
+ row.container->setVisible(false);
+}
+
+void MarketPulsePanel::style_mover_section(QWidget* container, bool positive_section) {
+ if (!container)
+ return;
+ const QString accent = positive_section ? ui::colors::POSITIVE() : ui::colors::NEGATIVE();
+ container->setStyleSheet(
+ QString("QWidget#pulseMoverRow{border-bottom:1px solid %1;}"
+ "QWidget#pulseMoverRow QLabel{background:transparent;}"
+ "QLabel#pulseMoverSym{color:%2;font-size:10px;font-weight:bold;}"
+ "QLabel#pulseMoverArrow{color:%3;font-size:8px;}"
+ "QLabel#pulseMoverChg{color:%3;font-size:10px;font-weight:bold;}"
+ "QLabel#pulseMoverVol{color:%4;font-size:8px;}")
+ .arg(ui::colors::BORDER_DIM(), ui::colors::TEXT_PRIMARY(), accent, ui::colors::TEXT_TERTIARY()));
}
static QString format_volume(double vol) {
@@ -542,16 +603,20 @@ QWidget* MarketPulsePanel::build_gainers_section() {
vl->addWidget(build_section_header("TOP GAINERS", QChar(0x2191), ui::colors::POSITIVE()));
- auto* rows_w = new QWidget(this);
- gainers_layout_ = new QVBoxLayout(rows_w);
+ gainers_rows_ = new QWidget(this);
+ gainers_layout_ = new QVBoxLayout(gainers_rows_);
gainers_layout_->setContentsMargins(0, 0, 0, 0);
gainers_layout_->setSpacing(0);
- // Placeholder rows while loading
- for (int i = 0; i < 3; ++i)
- gainers_layout_->addWidget(build_mover_row("...", 0.0, ""));
+ for (int i = 0; i < kMoverRows; ++i) {
+ MoverRow r = make_mover_row(gainers_rows_, gainers_layout_, /*positive_section=*/true);
+ // Placeholder text until the first quotes land.
+ r.symbol->setText(QStringLiteral("..."));
+ gainer_rows_.append(r);
+ }
+ style_mover_section(gainers_rows_, /*positive_section=*/true);
- vl->addWidget(rows_w);
+ vl->addWidget(gainers_rows_);
return w;
}
@@ -563,52 +628,24 @@ QWidget* MarketPulsePanel::build_losers_section() {
vl->addWidget(build_section_header("TOP LOSERS", QChar(0x2193), ui::colors::NEGATIVE()));
- auto* rows_w = new QWidget(this);
- losers_layout_ = new QVBoxLayout(rows_w);
+ losers_rows_ = new QWidget(this);
+ losers_layout_ = new QVBoxLayout(losers_rows_);
losers_layout_->setContentsMargins(0, 0, 0, 0);
losers_layout_->setSpacing(0);
- for (int i = 0; i < 3; ++i)
- losers_layout_->addWidget(build_mover_row("...", 0.0, ""));
+ for (int i = 0; i < kMoverRows; ++i) {
+ MoverRow r = make_mover_row(losers_rows_, losers_layout_, /*positive_section=*/false);
+ r.symbol->setText(QStringLiteral("..."));
+ loser_rows_.append(r);
+ }
+ style_mover_section(losers_rows_, /*positive_section=*/false);
- vl->addWidget(rows_w);
+ vl->addWidget(losers_rows_);
return w;
}
// ── Global Snapshot ───────────────────────────────────────────────────────────
-QWidget* MarketPulsePanel::build_stat_row(const QString& label, const QString& value, const QString& change,
- const QString& color) {
- auto* w = new QWidget(this);
- w->setStyleSheet(QString("border-bottom: 1px solid %1;").arg(ui::colors::BORDER_DIM()));
-
- auto* hl = new QHBoxLayout(w);
- hl->setContentsMargins(12, 4, 12, 4);
-
- auto* lbl = new QLabel(label);
- lbl->setStyleSheet(
- QString("color: %1; font-size: 9px; font-weight: bold; letter-spacing: 0.3px; background: transparent;")
- .arg(ui::colors::TEXT_SECONDARY()));
- hl->addWidget(lbl);
- hl->addStretch();
-
- auto* val = new QLabel(value);
- val->setStyleSheet(QString("color: %1; font-size: 10px; font-weight: bold; background: transparent;").arg(color));
- hl->addWidget(val);
-
- if (!change.isEmpty()) {
- bool positive = change.startsWith('+');
- auto* chg = new QLabel(change);
- chg->setStyleSheet(QString("color: %1; font-size: 8px; font-weight: bold; background: transparent;")
- .arg(positive ? ui::colors::POSITIVE()
- : change.startsWith('-') ? ui::colors::NEGATIVE()
- : ui::colors::TEXT_TERTIARY()));
- hl->addWidget(chg);
- }
-
- return w;
-}
-
QWidget* MarketPulsePanel::build_global_snapshot_section() {
auto* w = new QWidget(this);
auto* vl = new QVBoxLayout(w);
@@ -867,21 +904,29 @@ void MarketPulsePanel::rebuild_breadth_from_cache() {
}
fg_sentiment_key_ = sentiment_key;
- if (fg_score_val_) {
+ if (fg_score_val_)
fg_score_val_->setText(QString::number(score));
- fg_score_val_->setStyleSheet(
- QString("color: %1; font-size: 18px; font-weight: bold; background: transparent;").arg(sentiment_color));
- }
- if (fg_sentiment_) {
+ if (fg_sentiment_)
fg_sentiment_->setText(sentiment_text);
- fg_sentiment_->setStyleSheet(
- QString("color: %1; font-size: 9px; font-weight: bold; letter-spacing: 0.5px; background: transparent;")
- .arg(sentiment_color));
+
+ // The two colour stylesheets only change when the regime bucket changes —
+ // re-applying them on every one of ~50 breadth deliveries was pure CSS
+ // reparse cost for an identical result.
+ if (sentiment_color != fg_applied_color_) {
+ fg_applied_color_ = sentiment_color;
+ if (fg_score_val_)
+ fg_score_val_->setStyleSheet(
+ QString("color: %1; font-size: 18px; font-weight: bold; background: transparent;")
+ .arg(sentiment_color));
+ if (fg_sentiment_)
+ fg_sentiment_->setStyleSheet(
+ QString("color: %1; font-size: 9px; font-weight: bold; letter-spacing: 0.5px; background: transparent;")
+ .arg(sentiment_color));
}
}
void MarketPulsePanel::rebuild_movers_from_cache() {
- if (movers_cache_.isEmpty() || !gainers_layout_ || !losers_layout_)
+ if (movers_cache_.isEmpty() || gainer_rows_.isEmpty() || loser_rows_.isEmpty())
return;
QVector<services::QuoteData> quotes;
@@ -892,32 +937,27 @@ void MarketPulsePanel::rebuild_movers_from_cache() {
}
std::sort(quotes.begin(), quotes.end(), [](const auto& a, const auto& b) { return a.change_pct > b.change_pct; });
- auto clear_layout = [](QVBoxLayout* layout) {
- while (layout->count()) {
- auto* item = layout->takeAt(0);
- if (item->widget())
- item->widget()->deleteLater();
- delete item;
- }
- };
- clear_layout(gainers_layout_);
- clear_layout(losers_layout_);
-
+ // Reuse the fixed row pool — text-only updates, no widget churn.
int gainers_added = 0;
for (const auto& q : quotes) {
- if (q.change_pct <= 0 || gainers_added >= 3)
+ if (q.change_pct <= 0 || gainers_added >= kMoverRows)
break;
- gainers_layout_->addWidget(build_mover_row(q.symbol, q.change_pct, format_volume(q.volume)));
+ fill_mover_row(gainer_rows_[gainers_added], q.symbol, q.change_pct, format_volume(q.volume));
++gainers_added;
}
+ for (int i = gainers_added; i < gainer_rows_.size(); ++i)
+ clear_mover_row(gainer_rows_[i]);
+
int losers_added = 0;
- for (int i = quotes.size() - 1; i >= 0 && losers_added < 3; --i) {
+ for (int i = static_cast<int>(quotes.size()) - 1; i >= 0 && losers_added < kMoverRows; --i) {
if (quotes[i].change_pct >= 0)
continue;
- losers_layout_->addWidget(
- build_mover_row(quotes[i].symbol, quotes[i].change_pct, format_volume(quotes[i].volume)));
+ fill_mover_row(loser_rows_[losers_added], quotes[i].symbol, quotes[i].change_pct,
+ format_volume(quotes[i].volume));
++losers_added;
}
+ for (int i = losers_added; i < loser_rows_.size(); ++i)
+ clear_mover_row(loser_rows_[i]);
}
void MarketPulsePanel::rebuild_snapshot_from_cache() {
@@ -975,17 +1015,18 @@ void MarketPulsePanel::hub_subscribe_all() {
const auto q = v.value<services::QuoteData>();
if (in_breadth) {
breadth_cache_.insert(sym, q);
- rebuild_breadth_from_cache();
+ breadth_dirty_ = true;
}
if (in_movers) {
movers_cache_.insert(sym, q);
- rebuild_movers_from_cache();
+ movers_dirty_ = true;
}
if (in_snapshot) {
snapshot_cache_.insert(sym, q);
- rebuild_snapshot_from_cache();
+ snapshot_dirty_ = true;
}
- update_loading_progress();
+ // Render once for the whole delivery burst.
+ schedule_render();
});
}
hub_active_ = true;
diff --git a/fincept-qt/src/screens/dashboard/MarketPulsePanel.h b/fincept-qt/src/screens/dashboard/MarketPulsePanel.h
index bfbec7a39..4d55b8141 100644
--- a/fincept-qt/src/screens/dashboard/MarketPulsePanel.h
+++ b/fincept-qt/src/screens/dashboard/MarketPulsePanel.h
@@ -54,9 +54,6 @@ class MarketPulsePanel : public QWidget {
QWidget* build_losers_section();
QWidget* build_global_snapshot_section();
QWidget* build_market_hours_section();
- QWidget* build_mover_row(const QString& symbol, double change, const QString& volume);
- QWidget* build_stat_row(const QString& label, const QString& value, const QString& change, const QString& color);
- QWidget* build_breadth_bar(const QString& label, int advancing, int declining);
/// Re-apply all token-based styles so a theme switch updates every child widget.
void refresh_theme();
@@ -112,8 +109,29 @@ class MarketPulsePanel : public QWidget {
BreadthRow sp500_row_;
// ── Top Movers ──
+ // Fixed pool of 3 rows per section. Rows are built once and only have
+ // their text updated; the old code destroyed and re-created 6 rows (24
+ // widgets, 24 inline setStyleSheet calls) on every single quote delivery
+ // — ~70 times per refresh cycle.
+ struct MoverRow {
+ QWidget* container = nullptr;
+ QLabel* symbol = nullptr;
+ QLabel* arrow = nullptr;
+ QLabel* change = nullptr;
+ QLabel* volume = nullptr;
+ };
+ QWidget* gainers_rows_ = nullptr;
+ QWidget* losers_rows_ = nullptr;
QVBoxLayout* gainers_layout_ = nullptr;
QVBoxLayout* losers_layout_ = nullptr;
+ QVector<MoverRow> gainer_rows_;
+ QVector<MoverRow> loser_rows_;
+ MoverRow make_mover_row(QWidget* parent, QVBoxLayout* into, bool positive_section);
+ static void fill_mover_row(const MoverRow& row, const QString& symbol, double change, const QString& volume);
+ static void clear_mover_row(const MoverRow& row);
+ /// Applies the single hoisted stylesheet for a movers section.
+ void style_mover_section(QWidget* container, bool positive_section);
+ static constexpr int kMoverRows = 3;
// ── Global Snapshot ──
struct StatRow {
@@ -152,6 +170,20 @@ class MarketPulsePanel : public QWidget {
bool hub_active_ = false;
QTimer* hours_timer_ = nullptr;
+ // ── Render coalescing ──
+ // ~70 symbols each arrive as their own hub delivery. Without this every
+ // delivery triggered a full re-render of whichever sections it touched.
+ QTimer* render_timer_ = nullptr;
+ bool breadth_dirty_ = false;
+ bool movers_dirty_ = false;
+ bool snapshot_dirty_ = false;
+ void schedule_render();
+ void flush_render();
+
+ // Last-applied sentiment colour, so the Fear & Greed labels only pay a CSS
+ // reparse when the regime actually changes.
+ QString fg_applied_color_;
+
// Loading overlay shown over the scroll area while the union of the
// breadth/movers/snapshot caches fills up. The denominator is the
// unique-symbol union size (~70), updated every time a cache changes.
diff --git a/fincept-qt/src/screens/dashboard/TickerBar.cpp b/fincept-qt/src/screens/dashboard/TickerBar.cpp
index 29e91ae7d..c03a1a4eb 100644
--- a/fincept-qt/src/screens/dashboard/TickerBar.cpp
+++ b/fincept-qt/src/screens/dashboard/TickerBar.cpp
@@ -14,6 +14,8 @@
#include <QResizeEvent>
#include <QtConcurrent>
+#include <cmath>
+
namespace fincept::screens {
static constexpr int kItemSpacing = 40;
@@ -29,6 +31,9 @@ static const char* kSettingsCategory = "dashboard";
TickerBar::TickerBar(QWidget* parent) : QWidget(parent) {
setFixedHeight(kEditBarHeight);
setContextMenuPolicy(Qt::DefaultContextMenu);
+ setAccessibleName(tr("Market ticker"));
+ setAccessibleDescription(tr("Scrolling price ticker. Right-click to edit the symbol list."));
+ setToolTip(tr("Right-click to edit ticker symbols"));
auto apply_bg = [this]() { setStyleSheet(QString("background-color: %1;").arg(ui::colors::BG_BASE())); };
apply_bg();
@@ -61,6 +66,7 @@ TickerBar::TickerBar(QWidget* parent) : QWidget(parent) {
hl->addWidget(edit_label_);
edit_input_ = new QLineEdit(edit_bar_);
+ edit_input_->setAccessibleName(tr("Ticker symbols"));
edit_input_->setPlaceholderText(tr("AAPL, MSFT, ^GSPC, BTC-USD ..."));
edit_input_->setStyleSheet(
QString("QLineEdit { background:%1; color:%2; border:1px solid %3;"
@@ -81,6 +87,10 @@ TickerBar::TickerBar(QWidget* parent) : QWidget(parent) {
edit_cancel_ = new QPushButton("✕", edit_bar_);
edit_cancel_->setFixedWidth(24);
+ edit_cancel_->setAccessibleName(tr("Cancel"));
+ edit_ok_->setAccessibleName(tr("Apply ticker symbols"));
+ setTabOrder(edit_input_, edit_ok_);
+ setTabOrder(edit_ok_, edit_cancel_);
edit_cancel_->setStyleSheet(QString("QPushButton { background:transparent; color:%1; border:none;"
" font-size:11px; padding:2px; }"
"QPushButton:hover { color:%2; }")
@@ -139,8 +149,8 @@ void TickerBar::save_symbols() {
// ─────────────────────────────────────────────────────────────────────────────
void TickerBar::set_data(const QVector<Entry>& entries) {
+ const bool symbols_changed = entries.size() != entries_.size();
entries_ = entries;
- offset_ = 0;
// Cache total width — paintEvent runs every 50ms, no per-frame allocation.
QFont font(ui::fonts::DATA_FAMILY(), ui::fonts::font_px(-2));
@@ -154,8 +164,19 @@ void TickerBar::set_data(const QVector<Entry>& entries) {
total_width_ += symbol_w + kSegmentGap + price_w + kSegmentGap + change_w + kItemSpacing;
}
+ // Preserve the scroll position across price updates. set_data() is called
+ // on EVERY per-symbol hub delivery (rebuild_ticker_from_cache), so zeroing
+ // the offset made the ticker visibly snap back to the start several times
+ // a second. Only reset when the symbol set itself changed.
+ if (symbols_changed || total_width_ <= 0)
+ offset_ = 0;
+ else if (offset_ >= total_width_)
+ offset_ = std::fmod(offset_, static_cast<double>(total_width_));
+
if (total_width_ > 0 && isVisible() && !edit_bar_->isVisible())
scroll_timer_.start();
+ else if (total_width_ <= 0)
+ scroll_timer_.stop();
update();
}
diff --git a/fincept-qt/src/screens/dashboard/canvas/AddWidgetDialog.cpp b/fincept-qt/src/screens/dashboard/canvas/AddWidgetDialog.cpp
index 4c1dbd4dc..6dd647e21 100644
--- a/fincept-qt/src/screens/dashboard/canvas/AddWidgetDialog.cpp
+++ b/fincept-qt/src/screens/dashboard/canvas/AddWidgetDialog.cpp
@@ -8,7 +8,6 @@
#include <QMouseEvent>
#include <QScrollArea>
#include <QSet>
-#include <QTimer>
#include <QVBoxLayout>
namespace fincept::screens {
@@ -148,6 +147,31 @@ AddWidgetDialog::AddWidgetDialog(QWidget* parent) : QDialog(parent) {
bot->addWidget(add_btn_);
root->addLayout(bot);
+ // ── Accessibility + keyboard ──
+ // Enter in the search box adds the selected widget; explicit tab order
+ // walks search → categories → cancel → add.
+ search_bar_->setAccessibleName(tr("Search widgets"));
+ add_btn_->setAccessibleName(tr("Add the selected widget"));
+ add_btn_->setDefault(true);
+ add_btn_->setAutoDefault(true);
+ cancel_btn_->setAccessibleName(tr("Cancel"));
+ cancel_btn_->setAutoDefault(false);
+ // No explicit returnPressed hook on the search box: QLineEdit ignores the
+ // Return key event after emitting, so the dialog's default button already
+ // fires. Wiring both would emit widget_selected twice and add two tiles.
+
+ QWidget* prev = search_bar_;
+ for (auto* b : cat_buttons_) {
+ if (!b)
+ continue;
+ b->setAccessibleName(b->text());
+ setTabOrder(prev, b);
+ prev = b;
+ }
+ setTabOrder(prev, cancel_btn_);
+ setTabOrder(cancel_btn_, add_btn_);
+ search_bar_->setFocus();
+
// ── Initial population ──
populate_cards();
}
@@ -247,7 +271,13 @@ void AddWidgetDialog::card_clicked(const QString& type_id) {
void AddWidgetDialog::confirm() {
if (selected_id_.isEmpty())
return;
- emit widget_selected(selected_id_);
+ // Clear before emitting: a double-activation (double-click + default
+ // button, Enter + click) would otherwise add the same widget twice.
+ const QString id = selected_id_;
+ selected_id_.clear();
+ if (add_btn_)
+ add_btn_->setEnabled(false);
+ emit widget_selected(id);
accept();
}
@@ -257,6 +287,38 @@ void AddWidgetDialog::changeEvent(QEvent* event) {
QDialog::changeEvent(event);
}
+bool AddWidgetDialog::eventFilter(QObject* obj, QEvent* event) {
+ auto* w = qobject_cast<QWidget*>(obj);
+ if (!w)
+ return QDialog::eventFilter(obj, event);
+
+ // The click overlay covers the card, so events can arrive on either.
+ QWidget* card = nullptr;
+ if (w->objectName() == QLatin1String("widgetCard"))
+ card = w;
+ else if (w->objectName() == QLatin1String("cardClick"))
+ card = w->parentWidget();
+ if (!card)
+ return QDialog::eventFilter(obj, event);
+
+ if (w == card && (event->type() == QEvent::Resize || event->type() == QEvent::Show)) {
+ if (auto* btn = card->findChild<QPushButton*>(QStringLiteral("cardClick"), Qt::FindDirectChildrenOnly)) {
+ btn->setGeometry(card->rect());
+ btn->raise();
+ }
+ } else if (event->type() == QEvent::MouseButtonDblClick) {
+ // Double-click a card = select + add, matching every other
+ // "pick from a list" dialog in the terminal.
+ const QString wtype = card->property("wtype").toString();
+ if (!wtype.isEmpty()) {
+ card_clicked(wtype);
+ confirm();
+ return true;
+ }
+ }
+ return QDialog::eventFilter(obj, event);
+}
+
void AddWidgetDialog::retranslateUi() {
setWindowTitle(tr("Add Widget"));
if (title_label_)
@@ -298,6 +360,7 @@ void AddWidgetDialog::populate_cards(const QString& filter, const QString& categ
int col = 0;
int row = 0;
+ int added = 0;
for (const auto& meta : metas) {
// Filter by search text — match against both English (storage) and the
@@ -382,24 +445,44 @@ void AddWidgetDialog::populate_cards(const QString& filter, const QString& categ
// Connect click — capture type_id by value
const QString tid = meta.type_id;
+ click_btn->setObjectName("cardClick");
+ click_btn->setFocusPolicy(Qt::NoFocus); // the card list is driven by mouse/search
+ click_btn->setAccessibleName(name_tr);
+ click_btn->setToolTip(QString("%1\n%2").arg(name_tr, desc_tr));
connect(click_btn, &QPushButton::clicked, this, [this, tid]() { card_clicked(tid); });
// Place button on grid
card_grid_->addWidget(card, row, col);
- // When the card is shown, resize the overlay button to fill it
- connect(click_btn, &QPushButton::destroyed, this, []() {}); // prevent warning
- QTimer::singleShot(0, card, [click_btn, card]() {
- click_btn->setGeometry(card->rect());
- click_btn->raise();
- });
+ // Keep the transparent overlay exactly on top of the card. A one-shot
+ // singleShot(0) (the previous approach) fired before the grid had laid
+ // the card out at its final size, so on some paths the clickable area
+ // did not match the visible card.
+ card->installEventFilter(this);
+ click_btn->installEventFilter(this); // the overlay swallows double-clicks
+ click_btn->setGeometry(card->rect());
+ click_btn->raise();
+ ++added;
if (++col >= 2) {
col = 0;
++row;
}
}
+ // Empty state — a filter that matches nothing used to leave a blank panel
+ // with no explanation.
+ if (added == 0) {
+ auto* empty = new QLabel(filter.isEmpty() ? tr("No widgets in this category.")
+ : tr("No widgets match \"%1\".").arg(filter));
+ empty->setAlignment(Qt::AlignCenter);
+ empty->setWordWrap(true);
+ empty->setStyleSheet(QString("color: %1; font-size: 11px; padding: 24px; background: transparent;")
+ .arg(ui::colors::TEXT_TERTIARY()));
+ card_grid_->addWidget(empty, 0, 0, 1, 2);
+ ++row;
+ }
+
// Add stretch at the bottom
card_grid_->setRowStretch(row + (col > 0 ? 1 : 0), 1);
}
diff --git a/fincept-qt/src/screens/dashboard/canvas/AddWidgetDialog.h b/fincept-qt/src/screens/dashboard/canvas/AddWidgetDialog.h
index a295e41ef..0d6d6111b 100644
--- a/fincept-qt/src/screens/dashboard/canvas/AddWidgetDialog.h
+++ b/fincept-qt/src/screens/dashboard/canvas/AddWidgetDialog.h
@@ -25,6 +25,9 @@ class AddWidgetDialog : public QDialog {
protected:
void changeEvent(QEvent* event) override;
+ /// Keeps each card's transparent click overlay glued to the card as the
+ /// grid re-lays out, and turns a double-click into "add immediately".
+ bool eventFilter(QObject* obj, QEvent* event) override;
private slots:
void filter_changed(const QString& text);
diff --git a/fincept-qt/src/screens/dashboard/canvas/DashboardCanvas.cpp b/fincept-qt/src/screens/dashboard/canvas/DashboardCanvas.cpp
index a3b311154..851e176ef 100644
--- a/fincept-qt/src/screens/dashboard/canvas/DashboardCanvas.cpp
+++ b/fincept-qt/src/screens/dashboard/canvas/DashboardCanvas.cpp
@@ -96,17 +96,32 @@ void DashboardCanvas::load_layout(const GridLayout& layout) {
if (width() > 0)
layout_.cols = responsive_cols(width());
+ // Unknown widget types used to be skipped while the GridItem stayed in
+ // layout_.items — leaving a permanent invisible hole in the grid, a
+ // widget_count that disagreed with the layout, and the dead entry being
+ // re-serialised on every save. Drop them instead.
+ QVector<GridItem> kept;
+ kept.reserve(layout_.items.size());
for (const auto& item : layout_.items) {
const WidgetMeta* meta = WidgetRegistry::instance().find(item.id);
if (!meta) {
- LOG_WARN("Canvas", QString("Unknown widget type: %1").arg(item.id));
+ LOG_WARN("Canvas", QString("Dropping tile with unknown widget type: %1").arg(item.id));
continue;
}
auto* widget = meta->factory(item.config);
+ if (!widget) {
+ LOG_WARN("Canvas", QString("Factory returned null for widget type: %1").arg(item.id));
+ continue;
+ }
auto* tile = new WidgetTile(item.instance_id, widget, this);
connect_tile(tile);
tiles_.append(tile);
tile->show();
+ kept.append(item);
+ }
+ if (kept.size() != layout_.items.size()) {
+ layout_.items = compact_vertical(kept);
+ emit layout_changed(layout_);
}
reflow_tiles();
@@ -157,10 +172,17 @@ void DashboardCanvas::add_widget(const QString& widget_type_id) {
item.cell.min_w = meta->min_w;
item.cell.min_h = meta->min_h;
+ auto* widget = meta->factory(item.config);
+ if (!widget) {
+ // Never leave a GridItem behind for a widget that failed to construct —
+ // that produced an invisible tile that still reserved grid space.
+ LOG_WARN("Canvas", QString("Factory returned null for widget type: %1").arg(widget_type_id));
+ return;
+ }
+
layout_.items.append(item);
layout_.items = compact_vertical(layout_.items);
- auto* widget = meta->factory(item.config);
auto* tile = new WidgetTile(item.instance_id, widget, this);
connect_tile(tile);
tiles_.append(tile);
diff --git a/fincept-qt/src/screens/dashboard/canvas/WidgetRegistry.cpp b/fincept-qt/src/screens/dashboard/canvas/WidgetRegistry.cpp
index c160c0d7c..0a4dc979d 100644
--- a/fincept-qt/src/screens/dashboard/canvas/WidgetRegistry.cpp
+++ b/fincept-qt/src/screens/dashboard/canvas/WidgetRegistry.cpp
@@ -125,7 +125,13 @@ WidgetRegistry::WidgetRegistry() {
register_widget({"watchlist", QT_TRANSLATE_NOOP("fincept::screens::WidgetRegistry", "Watchlist"),
QT_TRANSLATE_NOOP("fincept::screens::WidgetRegistry", "Portfolio"),
QT_TRANSLATE_NOOP("fincept::screens::WidgetRegistry", "Your saved symbols with live prices"), 6, 4,
- 2, 3, [](const QJsonObject&) { return new widgets::WatchlistWidget; }});
+ 2, 3, [](const QJsonObject& cfg) {
+ // The watchlist persists its user-edited symbol list
+ // through the tile config; seed it before first show.
+ auto* w = new widgets::WatchlistWidget;
+ w->apply_config(cfg);
+ return w;
+ }});
register_widget({"performance", QT_TRANSLATE_NOOP("fincept::screens::WidgetRegistry", "Performance"),
QT_TRANSLATE_NOOP("fincept::screens::WidgetRegistry", "Portfolio"),
diff --git a/fincept-qt/src/screens/dashboard/widgets/BaseWidget.cpp b/fincept-qt/src/screens/dashboard/widgets/BaseWidget.cpp
index 104f8b189..e6ea1a650 100644
--- a/fincept-qt/src/screens/dashboard/widgets/BaseWidget.cpp
+++ b/fincept-qt/src/screens/dashboard/widgets/BaseWidget.cpp
@@ -65,6 +65,7 @@ BaseWidget::BaseWidget(const QString& title, QWidget* parent, const QString& acc
config_btn_->setIcon(style()->standardIcon(QStyle::SP_FileDialogDetailedView));
config_btn_->setIconSize(QSize(12, 12));
config_btn_->setToolTip(tr("Configure widget"));
+ config_btn_->setAccessibleName(tr("Configure widget"));
config_btn_->setCursor(Qt::PointingHandCursor);
config_btn_->setVisible(false);
config_btn_->setStyleSheet(
@@ -83,6 +84,7 @@ BaseWidget::BaseWidget(const QString& title, QWidget* parent, const QString& acc
refresh_btn_->setIcon(style()->standardIcon(QStyle::SP_BrowserReload));
refresh_btn_->setIconSize(QSize(12, 12));
refresh_btn_->setToolTip(tr("Refresh widget data"));
+ refresh_btn_->setAccessibleName(tr("Refresh widget data"));
refresh_btn_->setCursor(Qt::PointingHandCursor);
refresh_btn_->setStyleSheet(
QString("QPushButton { color: %1; background: %2; border: 1px solid %3; border-radius: 2px; "
@@ -95,11 +97,13 @@ BaseWidget::BaseWidget(const QString& title, QWidget* parent, const QString& acc
// Close button
auto* close_btn = new QPushButton;
+ close_btn_ = close_btn;
close_btn->setFixedSize(20, 20);
close_btn->setText("");
close_btn->setIcon(style()->standardIcon(QStyle::SP_TitleBarCloseButton));
close_btn->setIconSize(QSize(11, 11));
close_btn->setToolTip(tr("Close widget"));
+ close_btn->setAccessibleName(tr("Close widget"));
close_btn->setCursor(Qt::PointingHandCursor);
close_btn->setStyleSheet(
QString("QPushButton { color: %1; background: %2; border: 1px solid %3; border-radius: 2px; "
@@ -236,6 +240,10 @@ void BaseWidget::set_error(const QString& error) {
void BaseWidget::set_title(const QString& title) {
title_label_->setText(title);
+ // Screen readers announce the tile by its title; without this the whole
+ // dashboard reads as a wall of unnamed frames.
+ setAccessibleName(title);
+ title_label_->setAccessibleName(title);
}
void BaseWidget::set_configurable(bool configurable) {
@@ -243,6 +251,23 @@ void BaseWidget::set_configurable(bool configurable) {
config_btn_->setVisible(configurable);
}
+void BaseWidget::schedule_render(std::function<void()> fn) {
+ pending_render_ = std::move(fn);
+ if (render_scheduled_)
+ return;
+ render_scheduled_ = true;
+ // `this` as context object: Qt drops the pending call if the widget dies.
+ QTimer::singleShot(0, this, [this]() {
+ render_scheduled_ = false;
+ // Move out first so a render that itself schedules another one
+ // doesn't get clobbered.
+ auto fn = std::move(pending_render_);
+ pending_render_ = nullptr;
+ if (fn)
+ fn();
+ });
+}
+
void BaseWidget::on_config_clicked() {
QDialog* dlg = make_config_dialog(this);
if (!dlg)
@@ -302,13 +327,18 @@ void BaseWidget::changeEvent(QEvent* event) {
}
void BaseWidget::retranslateUi() {
- if (config_btn_)
+ if (config_btn_) {
config_btn_->setToolTip(tr("Configure widget"));
- if (refresh_btn_)
+ config_btn_->setAccessibleName(tr("Configure widget"));
+ }
+ if (refresh_btn_) {
refresh_btn_->setToolTip(tr("Refresh widget data"));
- // Close button is a local in the ctor — its tooltip won't be retranslated
- // dynamically. Acceptable tradeoff: it's an icon, the tooltip is short,
- // and a runtime language switch is rare.
+ refresh_btn_->setAccessibleName(tr("Refresh widget data"));
+ }
+ if (close_btn_) {
+ close_btn_->setToolTip(tr("Close widget"));
+ close_btn_->setAccessibleName(tr("Close widget"));
+ }
if (loading_label_ && loading_label_->isVisible())
loading_label_->setText(tr("LOADING..."));
}
diff --git a/fincept-qt/src/screens/dashboard/widgets/BaseWidget.h b/fincept-qt/src/screens/dashboard/widgets/BaseWidget.h
index 8d3759ffb..dcf8d3a1c 100644
--- a/fincept-qt/src/screens/dashboard/widgets/BaseWidget.h
+++ b/fincept-qt/src/screens/dashboard/widgets/BaseWidget.h
@@ -11,6 +11,8 @@
#include <QTimer>
#include <QVBoxLayout>
+#include <functional>
+
namespace fincept::screens::widgets {
class LoadingOverlay;
@@ -78,6 +80,21 @@ class BaseWidget : public QFrame {
/// so the gear icon appears. Also hides the icon if set to false later.
void set_configurable(bool configurable);
+ /// Coalesce repeated re-render requests into a single call on the next
+ /// event-loop turn.
+ ///
+ /// Hub deliveries arrive one topic at a time: a widget subscribed to N
+ /// symbols gets N callbacks per refresh cycle, and a naive
+ /// `rebuild_from_cache()` inside each callback rebuilds the whole table N
+ /// times (O(N^2) widget churn + N full CSS reparses per row). Routing the
+ /// rebuild through this helper collapses a whole delivery burst into one
+ /// render. The last functor wins, so passing a lambda that reads current
+ /// state is always correct.
+ ///
+ /// The timer is bound to `this` as its context object, so a pending render
+ /// is dropped automatically if the widget is destroyed first.
+ void schedule_render(std::function<void()> fn);
+
/// Re-arms the loading watchdog on becoming visible. Many subclasses call
/// `set_loading(true)` from their constructor, which arms the watchdog
/// before the widget is mounted and before any subscription has been
@@ -107,10 +124,15 @@ class BaseWidget : public QFrame {
QVBoxLayout* content_layout_ = nullptr;
QPushButton* refresh_btn_ = nullptr;
QPushButton* config_btn_ = nullptr;
+ QPushButton* close_btn_ = nullptr;
LoadingOverlay* loading_overlay_ = nullptr;
QTimer* loading_watchdog_ = nullptr;
int last_progress_loaded_ = 0;
QString accent_color_;
+
+ // Render coalescing — see schedule_render().
+ std::function<void()> pending_render_;
+ bool render_scheduled_ = false;
};
} // namespace fincept::screens::widgets
diff --git a/fincept-qt/src/screens/dashboard/widgets/BrokerHoldingsWidget.cpp b/fincept-qt/src/screens/dashboard/widgets/BrokerHoldingsWidget.cpp
index 26fee7923..5a440c6bf 100644
--- a/fincept-qt/src/screens/dashboard/widgets/BrokerHoldingsWidget.cpp
+++ b/fincept-qt/src/screens/dashboard/widgets/BrokerHoldingsWidget.cpp
@@ -155,7 +155,22 @@ void BrokerHoldingsWidget::hideEvent(QHideEvent* e) {
void BrokerHoldingsWidget::populate(const QVector<trading::BrokerHolding>& rows) {
holdings_ = rows;
- table_->setRowCount(rows.size());
+
+ // Empty state — an account with no holdings used to render a blank grid.
+ table_->clearSpans();
+ if (rows.isEmpty()) {
+ table_->setRowCount(1);
+ auto* msg = new QTableWidgetItem(tr("No holdings"));
+ msg->setTextAlignment(Qt::AlignCenter);
+ msg->setForeground(QColor(ui::colors::TEXT_TERTIARY()));
+ table_->setItem(0, 0, msg);
+ table_->setSpan(0, 0, 1, table_->columnCount());
+ square_off_all_btn_->setEnabled(false);
+ set_loading(false);
+ return;
+ }
+
+ table_->setRowCount(static_cast<int>(rows.size()));
int sellable = 0;
for (int i = 0; i < rows.size(); ++i) {
const auto& h = rows[i];
@@ -361,7 +376,19 @@ void BrokerHoldingsWidget::apply_styles() {
void BrokerHoldingsWidget::retranslateUi() {
BaseWidget::retranslateUi();
set_title(tr("HOLDINGS"));
- hub_resubscribe(); // re-renders header hint + table from cached subscription
+ // Re-apply the actual strings (the old body called hub_resubscribe(),
+ // which rebuilds subscriptions and translates nothing).
+ if (table_) {
+ table_->setHorizontalHeaderLabels({tr("Symbol"), tr("Qty"), tr("Avg"), tr("LTP"), tr("P&L %"), QString()});
+ for (int r = 0; r < table_->rowCount(); ++r) {
+ if (auto* btn = qobject_cast<QPushButton*>(table_->cellWidget(r, 5)))
+ btn->setText(tr("Exit"));
+ }
+ }
+ if (square_off_all_btn_)
+ square_off_all_btn_->setText(tr("SQUARE OFF ALL"));
+ if (header_hint_ && account_id_.isEmpty())
+ header_hint_->setText(tr("No active account — click gear to configure"));
}
} // namespace fincept::screens::widgets
diff --git a/fincept-qt/src/screens/dashboard/widgets/DashboardCandleWidget.cpp b/fincept-qt/src/screens/dashboard/widgets/DashboardCandleWidget.cpp
index 62b68c638..300895294 100644
--- a/fincept-qt/src/screens/dashboard/widgets/DashboardCandleWidget.cpp
+++ b/fincept-qt/src/screens/dashboard/widgets/DashboardCandleWidget.cpp
@@ -116,8 +116,11 @@ void CandleCanvas::rebuild_cache() {
const QColor bull_color(ui::colors::POSITIVE.get());
const QColor bear_color(ui::colors::NEGATIVE.get());
- const QColor wick_bull("#2a9d5c");
- const QColor wick_bear("#b83a3a");
+ // Wicks were two hardcoded hex literals that ignored the active theme.
+ // Derive them from the body colours instead (DESIGN_SYSTEM §2: no colour
+ // outside the token set).
+ const QColor wick_bull = bull_color.darker(115);
+ const QColor wick_bear = bear_color.darker(115);
for (int i = 0; i < count; ++i) {
const auto& c = candles_[start + i];
diff --git a/fincept-qt/src/screens/dashboard/widgets/ForexWidget.h b/fincept-qt/src/screens/dashboard/widgets/ForexWidget.h
index 12416a44a..d5af18ed6 100644
--- a/fincept-qt/src/screens/dashboard/widgets/ForexWidget.h
+++ b/fincept-qt/src/screens/dashboard/widgets/ForexWidget.h
@@ -1,5 +1,6 @@
#pragma once
#include "screens/dashboard/widgets/QuoteTableWidget.h"
+#include "ui/theme/Theme.h"
#include <QCoreApplication>
@@ -13,7 +14,11 @@ inline QuoteTableWidget* create_forex_widget(QWidget* parent = nullptr) {
};
const QString title =
QCoreApplication::translate("fincept::screens::widgets::QuoteTableWidget", "FOREX - MAJOR PAIRS");
- return new QuoteTableWidget(title, services::MarketDataService::forex_symbols(), labels, 4, "#9D4EDD", parent);
+ // Accent must come from the theme (DESIGN_SYSTEM §2) — this was a
+ // hardcoded purple that no palette defines and that does not follow a
+ // theme switch.
+ return new QuoteTableWidget(title, services::MarketDataService::forex_symbols(), labels, 4, ui::colors::INFO(),
+ parent);
}
} // namespace fincept::screens::widgets
diff --git a/fincept-qt/src/screens/dashboard/widgets/MarginUsageWidget.cpp b/fincept-qt/src/screens/dashboard/widgets/MarginUsageWidget.cpp
index 82a49a8c8..c16b2b35d 100644
--- a/fincept-qt/src/screens/dashboard/widgets/MarginUsageWidget.cpp
+++ b/fincept-qt/src/screens/dashboard/widgets/MarginUsageWidget.cpp
@@ -44,9 +44,10 @@ MarginUsageWidget::MarginUsageWidget(const QJsonObject& cfg, QWidget* parent) :
grid->setHorizontalSpacing(12);
grid->setVerticalSpacing(4);
- auto make_row = [grid](int row, const QString& label_text, QLabel*& value_out) {
+ auto make_row = [this, grid](int row, const QString& label_text, QLabel*& value_out) {
auto* lbl = new QLabel(label_text);
lbl->setObjectName("marginUsageRowLabel");
+ row_labels_.append(lbl);
value_out = new QLabel("—");
value_out->setObjectName("marginUsageRowValue");
value_out->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
@@ -87,19 +88,26 @@ QJsonObject MarginUsageWidget::config() const {
return o;
}
+void MarginUsageWidget::refresh_header_hint() {
+ if (!header_hint_)
+ return;
+ if (account_id_.isEmpty()) {
+ header_hint_->setText(tr("No active account — click gear to configure"));
+ return;
+ }
+ const auto acct = trading::AccountManager::instance().get_account(account_id_);
+ header_hint_->setText(acct.display_name.isEmpty() ? account_id_ : acct.display_name);
+}
+
void MarginUsageWidget::apply_config(const QJsonObject& cfg) {
account_id_ = cfg.value("account_id").toString();
if (account_id_.isEmpty())
account_id_ = resolve_account_id();
broker_id_.clear();
- if (!account_id_.isEmpty()) {
- const auto acct = trading::AccountManager::instance().get_account(account_id_);
- broker_id_ = acct.broker_id;
- header_hint_->setText(acct.display_name.isEmpty() ? account_id_ : acct.display_name);
- } else {
- header_hint_->setText(tr("No active account — click gear to configure"));
- }
+ if (!account_id_.isEmpty())
+ broker_id_ = trading::AccountManager::instance().get_account(account_id_).broker_id;
+ refresh_header_hint();
if (isVisible() && !broker_id_.isEmpty() && !account_id_.isEmpty()) {
ensure_stream_running();
@@ -164,6 +172,7 @@ void MarginUsageWidget::populate(const trading::BrokerFunds& funds) {
pct = qBound(0, int((funds.used_margin / denom) * 100.0 + 0.5), 100);
}
usage_bar_->setValue(pct);
+ last_usage_pct_ = pct;
usage_pct_label_->setText(tr("Usage: %1%").arg(pct));
QColor bar_color = ui::colors::POSITIVE();
@@ -245,7 +254,16 @@ void MarginUsageWidget::apply_styles() {
void MarginUsageWidget::retranslateUi() {
BaseWidget::retranslateUi();
set_title(tr("MARGIN USAGE"));
- hub_resubscribe(); // re-renders header hint + cached funds row in the new language
+ // Actually re-translate the kept labels. The previous implementation
+ // called hub_resubscribe(), which tears down and rebuilds every hub
+ // subscription and does not touch a single string.
+ const QStringList captions = {tr("Available"), tr("Used"), tr("Total"), tr("Collateral")};
+ for (int i = 0; i < row_labels_.size() && i < captions.size(); ++i)
+ row_labels_[i]->setText(captions[i]);
+ if (usage_pct_label_)
+ usage_pct_label_->setText(last_usage_pct_ >= 0 ? tr("Usage: %1%").arg(last_usage_pct_)
+ : tr("Usage: —"));
+ refresh_header_hint();
}
} // namespace fincept::screens::widgets
diff --git a/fincept-qt/src/screens/dashboard/widgets/MarginUsageWidget.h b/fincept-qt/src/screens/dashboard/widgets/MarginUsageWidget.h
index 4dbcf378f..6e4a341ec 100644
--- a/fincept-qt/src/screens/dashboard/widgets/MarginUsageWidget.h
+++ b/fincept-qt/src/screens/dashboard/widgets/MarginUsageWidget.h
@@ -9,6 +9,7 @@
#include "trading/TradingTypes.h"
#include <QString>
+#include <QVector>
class QLabel;
class QProgressBar;
@@ -48,6 +49,12 @@ class MarginUsageWidget : public BaseWidget {
QLabel* collateral_val_ = nullptr;
QLabel* usage_pct_label_ = nullptr;
QProgressBar* usage_bar_ = nullptr;
+ /// Left-hand row captions, kept so retranslateUi() can re-run tr() on them.
+ QVector<QLabel*> row_labels_;
+ /// Last usage % rendered — retranslateUi() needs it to rebuild the caption.
+ int last_usage_pct_ = -1;
+ /// Re-applies the account name / "no account" hint in the current language.
+ void refresh_header_hint();
bool hub_active_ = false;
};
diff --git a/fincept-qt/src/screens/dashboard/widgets/MarketSentimentWidget.cpp b/fincept-qt/src/screens/dashboard/widgets/MarketSentimentWidget.cpp
index 077c96ba7..f829dd036 100644
--- a/fincept-qt/src/screens/dashboard/widgets/MarketSentimentWidget.cpp
+++ b/fincept-qt/src/screens/dashboard/widgets/MarketSentimentWidget.cpp
@@ -186,7 +186,8 @@ void MarketSentimentWidget::hub_subscribe_all() {
return;
row_cache_.insert(sym, v.value<services::QuoteData>());
set_loading_progress(row_cache_.size(), kSentimentSymbols.size());
- rebuild_from_cache();
+ // One redraw per delivery burst, not one per symbol.
+ schedule_render([this]() { rebuild_from_cache(); });
});
}
hub_active_ = true;
diff --git a/fincept-qt/src/screens/dashboard/widgets/OpenPositionsWidget.cpp b/fincept-qt/src/screens/dashboard/widgets/OpenPositionsWidget.cpp
index 6e68d3b59..c794011d7 100644
--- a/fincept-qt/src/screens/dashboard/widgets/OpenPositionsWidget.cpp
+++ b/fincept-qt/src/screens/dashboard/widgets/OpenPositionsWidget.cpp
@@ -119,7 +119,21 @@ void OpenPositionsWidget::hideEvent(QHideEvent* e) {
}
void OpenPositionsWidget::populate(const QVector<trading::BrokerPosition>& rows) {
- table_->setRowCount(rows.size());
+ // Empty state — a flat account previously rendered an empty grid with no
+ // explanation, which reads the same as a failed load.
+ table_->clearSpans();
+ if (rows.isEmpty()) {
+ table_->setRowCount(1);
+ auto* msg = new QTableWidgetItem(tr("No open positions"));
+ msg->setTextAlignment(Qt::AlignCenter);
+ msg->setForeground(QColor(ui::colors::TEXT_TERTIARY()));
+ table_->setItem(0, 0, msg);
+ table_->setSpan(0, 0, 1, table_->columnCount());
+ set_loading(false);
+ return;
+ }
+
+ table_->setRowCount(static_cast<int>(rows.size()));
for (int i = 0; i < rows.size(); ++i) {
const auto& p = rows[i];
auto* sym = new QTableWidgetItem(p.symbol);
@@ -193,7 +207,12 @@ void OpenPositionsWidget::apply_styles() {
void OpenPositionsWidget::retranslateUi() {
BaseWidget::retranslateUi();
set_title(tr("OPEN POSITIONS"));
- hub_resubscribe(); // re-renders header hint + table in the new language
+ // The old body called hub_resubscribe(), which rebuilds every hub
+ // subscription and translates nothing. Re-apply the actual strings.
+ if (table_)
+ table_->setHorizontalHeaderLabels({tr("Symbol"), tr("Qty"), tr("Avg"), tr("LTP"), tr("P&L")});
+ if (header_hint_ && account_id_.isEmpty())
+ header_hint_->setText(tr("No active account — click gear to configure"));
}
} // namespace fincept::screens::widgets
diff --git a/fincept-qt/src/screens/dashboard/widgets/OrderBookMiniWidget.cpp b/fincept-qt/src/screens/dashboard/widgets/OrderBookMiniWidget.cpp
index 1b0ce572e..f19130d21 100644
--- a/fincept-qt/src/screens/dashboard/widgets/OrderBookMiniWidget.cpp
+++ b/fincept-qt/src/screens/dashboard/widgets/OrderBookMiniWidget.cpp
@@ -138,7 +138,21 @@ void OrderBookMiniWidget::populate(const QVector<trading::BrokerOrderInfo>& rows
if (is_working(o.status))
working.append(o);
}
- table_->setRowCount(working.size());
+ // Empty state — an account with nothing working used to render a blank
+ // grid that is indistinguishable from "still loading" / "broken".
+ table_->clearSpans();
+ if (working.isEmpty()) {
+ table_->setRowCount(1);
+ auto* msg = new QTableWidgetItem(tr("No working orders"));
+ msg->setTextAlignment(Qt::AlignCenter);
+ msg->setForeground(QColor(ui::colors::TEXT_TERTIARY()));
+ table_->setItem(0, 0, msg);
+ table_->setSpan(0, 0, 1, table_->columnCount());
+ set_loading(false);
+ return;
+ }
+
+ table_->setRowCount(static_cast<int>(working.size()));
for (int i = 0; i < working.size(); ++i) {
const auto& o = working[i];
auto* sym = new QTableWidgetItem(o.symbol);
@@ -156,15 +170,15 @@ void OrderBookMiniWidget::populate(const QVector<trading::BrokerOrderInfo>& rows
table_->setItem(i, 3, price);
table_->setItem(i, 4, status);
+ // Styling comes from the table-level stylesheet (see apply_styles) via
+ // the `obCancel` dynamic property — a per-row setStyleSheet here meant
+ // one full CSS reparse per working order on every order-book push.
auto* cancel_btn = new QPushButton("×", table_);
+ cancel_btn->setProperty("obCancel", true);
cancel_btn->setToolTip(tr("Cancel order %1").arg(o.order_id));
+ cancel_btn->setAccessibleName(tr("Cancel order %1").arg(o.order_id));
cancel_btn->setCursor(Qt::PointingHandCursor);
cancel_btn->setFixedHeight(18);
- cancel_btn->setStyleSheet(
- QString("QPushButton{color:%1;background:transparent;border:1px solid %2;"
- "border-radius:2px;font-size:11px;font-weight:bold;}"
- "QPushButton:hover{color:%3;border-color:%3;}")
- .arg(ui::colors::TEXT_TERTIARY(), ui::colors::BORDER_DIM(), ui::colors::NEGATIVE()));
const QString oid = o.order_id;
connect(cancel_btn, &QPushButton::clicked, this, [this, oid]() { cancel_order(oid); });
table_->setCellWidget(i, 5, cancel_btn);
@@ -234,15 +248,23 @@ void OrderBookMiniWidget::apply_styles() {
QString("QTableWidget{background:transparent;color:%1;gridline-color:%2;font-size:10px;border:none;}"
"QHeaderView::section{background:%3;color:%4;border:none;border-bottom:1px solid %2;"
"padding:2px 4px;font-size:9px;font-weight:bold;}"
- "QTableWidget::item{padding:2px 4px;}")
+ "QTableWidget::item{padding:2px 4px;}"
+ "QPushButton[obCancel=\"true\"]{color:%4;background:transparent;border:1px solid %2;"
+ "border-radius:2px;font-size:11px;font-weight:bold;}"
+ "QPushButton[obCancel=\"true\"]:hover{color:%5;border-color:%5;}")
.arg(ui::colors::TEXT_PRIMARY(), ui::colors::BORDER_DIM(), ui::colors::BG_RAISED(),
- ui::colors::TEXT_TERTIARY()));
+ ui::colors::TEXT_TERTIARY(), ui::colors::NEGATIVE()));
}
void OrderBookMiniWidget::retranslateUi() {
BaseWidget::retranslateUi();
set_title(tr("WORKING ORDERS"));
- hub_resubscribe(); // re-renders header hint + table in the new language
+ // Re-apply the actual strings (the old body called hub_resubscribe(),
+ // which rebuilds subscriptions and translates nothing).
+ if (table_)
+ table_->setHorizontalHeaderLabels({tr("Symbol"), tr("Side"), tr("Qty"), tr("Price"), tr("Status"), QString()});
+ if (header_hint_ && account_id_.isEmpty())
+ header_hint_->setText(tr("No active account — click gear to configure"));
}
} // namespace fincept::screens::widgets
diff --git a/fincept-qt/src/screens/dashboard/widgets/PerformanceWidget.cpp b/fincept-qt/src/screens/dashboard/widgets/PerformanceWidget.cpp
index 99ce46789..5c97db9e3 100644
--- a/fincept-qt/src/screens/dashboard/widgets/PerformanceWidget.cpp
+++ b/fincept-qt/src/screens/dashboard/widgets/PerformanceWidget.cpp
@@ -98,7 +98,8 @@ void PerformanceWidget::hub_subscribe_all() {
return;
row_cache_.insert(sym, v.value<services::QuoteData>());
set_loading_progress(row_cache_.size(), kPerfSymbols.size());
- rebuild_from_cache();
+ // One redraw per delivery burst, not one per symbol.
+ schedule_render([this]() { rebuild_from_cache(); });
});
}
hub_active_ = true;
diff --git a/fincept-qt/src/screens/dashboard/widgets/PortfolioSummaryWidget.cpp b/fincept-qt/src/screens/dashboard/widgets/PortfolioSummaryWidget.cpp
index 3d551fe5a..5e97d5e30 100644
--- a/fincept-qt/src/screens/dashboard/widgets/PortfolioSummaryWidget.cpp
+++ b/fincept-qt/src/screens/dashboard/widgets/PortfolioSummaryWidget.cpp
@@ -83,14 +83,14 @@ PortfolioSummaryWidget::PortfolioSummaryWidget(QWidget* parent)
scroll_area_ = new QScrollArea;
scroll_area_->setWidgetResizable(true);
- auto* list_widget = new QWidget(this);
- list_widget->setStyleSheet("background: transparent;");
- list_layout_ = new QVBoxLayout(list_widget);
+ list_widget_ = new QWidget(this);
+ list_widget_->setObjectName("psList");
+ list_layout_ = new QVBoxLayout(list_widget_);
list_layout_->setContentsMargins(0, 0, 0, 0);
list_layout_->setSpacing(0);
list_layout_->addStretch();
- scroll_area_->setWidget(list_widget);
+ scroll_area_->setWidget(list_widget_);
vl->addWidget(scroll_area_, 1);
// Enable the BaseWidget gear icon — make_config_dialog() handles the rest.
@@ -184,6 +184,23 @@ void PortfolioSummaryWidget::apply_styles() {
"QScrollBar::handle:vertical { background: %1; border-radius: 2px; min-height: 20px; }"
"QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical { height: 0; }")
.arg(ui::colors::BORDER_MED()));
+
+ // Holdings-row chrome, hoisted (P7). render() draws 5 cells per holding
+ // and used to call setStyleSheet on every one of them on every re-render.
+ if (list_widget_)
+ list_widget_->setStyleSheet(QString("#psList{background:transparent;}"
+ "#psList QWidget#psRow{background:transparent;}"
+ "#psList QWidget#psRowAlt{background:%1;}"
+ "#psList QLabel{font-size:10px;background:transparent;}"
+ "#psList QLabel#psSym{color:%2;}"
+ "#psList QLabel#psShares{color:%3;}"
+ "#psList QLabel#psNum{color:%2;}"
+ "#psList QLabel#psPnlPos{color:%4;}"
+ "#psList QLabel#psPnlNeg{color:%5;}"
+ "#psList QLabel#psEmpty{color:%6;font-size:11px;padding:20px;}")
+ .arg(ui::colors::BG_RAISED(), ui::colors::TEXT_PRIMARY(),
+ ui::colors::TEXT_SECONDARY(), ui::colors::POSITIVE(),
+ ui::colors::NEGATIVE(), ui::colors::TEXT_TERTIARY()));
}
void PortfolioSummaryWidget::on_theme_changed() {
@@ -268,11 +285,10 @@ void PortfolioSummaryWidget::render_empty(const QString& message) {
item->widget()->deleteLater();
delete item;
}
- auto* empty = new QLabel(message);
+ auto* empty = new QLabel(message, list_widget_);
+ empty->setObjectName("psEmpty");
empty->setAlignment(Qt::AlignCenter);
empty->setWordWrap(true);
- empty->setStyleSheet(QString("color: %1; font-size: 11px; padding: 20px; background: transparent;")
- .arg(ui::colors::TEXT_TERTIARY()));
list_layout_->addWidget(empty);
list_layout_->addStretch();
const QString sym = cur::symbol_for(selected_portfolio_currency_);
@@ -310,7 +326,8 @@ void PortfolioSummaryWidget::hub_resubscribe(const QVector<Holding>& holdings) {
return;
row_cache_.insert(sym, v.value<services::QuoteData>());
set_loading(false);
- rebuild_from_cache();
+ // One holdings-table rebuild per delivery burst, not one per symbol.
+ schedule_render([this]() { rebuild_from_cache(); });
});
}
hub_active_ = true;
@@ -370,29 +387,31 @@ void PortfolioSummaryWidget::render(const QVector<Holding>& holdings, const QVec
total_cost += cost;
day_pnl += day_chg;
- auto* row = new QWidget(this);
- row->setStyleSheet(QString("background: %1;").arg(alt ? ui::colors::BG_RAISED() : "transparent"));
+ // No setStyleSheet in this loop — colours come from the single
+ // stylesheet on list_widget_ (see apply_styles) via these object names.
+ auto* row = new QWidget(list_widget_);
+ row->setObjectName(alt ? QStringLiteral("psRowAlt") : QStringLiteral("psRow"));
auto* rl = new QHBoxLayout(row);
rl->setContentsMargins(8, 4, 8, 4);
- auto cell = [&](const QString& text, int stretch, Qt::Alignment align, const QString& color) {
+ auto cell = [&](const QString& text, Qt::Alignment align, const QString& object_name) {
auto* lbl = new QLabel(text);
+ lbl->setObjectName(object_name);
lbl->setAlignment(align);
- lbl->setStyleSheet(QString("color: %1; font-size: 10px; background: transparent;").arg(color));
- rl->addWidget(lbl, stretch);
+ rl->addWidget(lbl, 1);
};
- cell(h.symbol, 1, Qt::AlignLeft, ui::colors::TEXT_PRIMARY);
- cell(QString::number(h.shares, 'f', h.shares == (int)h.shares ? 0 : 2), 1, Qt::AlignRight,
- ui::colors::TEXT_SECONDARY);
- cell(price > 0 ? sym + QString::number(price, 'f', 2) : QStringLiteral("--"), 1, Qt::AlignRight,
- ui::colors::TEXT_PRIMARY);
- cell(value > 0 ? sym + QString::number(value, 'f', 0) : QStringLiteral("--"), 1, Qt::AlignRight,
- ui::colors::TEXT_PRIMARY);
+ cell(h.symbol, Qt::AlignLeft, QStringLiteral("psSym"));
+ cell(QString::number(h.shares, 'f', h.shares == (int)h.shares ? 0 : 2), Qt::AlignRight,
+ QStringLiteral("psShares"));
+ cell(price > 0 ? sym + QString::number(price, 'f', 2) : QStringLiteral("--"), Qt::AlignRight,
+ QStringLiteral("psNum"));
+ cell(value > 0 ? sym + QString::number(value, 'f', 0) : QStringLiteral("--"), Qt::AlignRight,
+ QStringLiteral("psNum"));
QString pnl_str = pnl >= 0 ? QStringLiteral("+") + sym + QString::number(pnl, 'f', 0)
: QStringLiteral("-") + sym + QString::number(-pnl, 'f', 0);
- cell(pnl_str, 1, Qt::AlignRight, pnl >= 0 ? ui::colors::POSITIVE : ui::colors::NEGATIVE);
+ cell(pnl_str, Qt::AlignRight, pnl >= 0 ? QStringLiteral("psPnlPos") : QStringLiteral("psPnlNeg"));
list_layout_->addWidget(row);
alt = !alt;
diff --git a/fincept-qt/src/screens/dashboard/widgets/PortfolioSummaryWidget.h b/fincept-qt/src/screens/dashboard/widgets/PortfolioSummaryWidget.h
index 745d407c5..0ca92b6d1 100644
--- a/fincept-qt/src/screens/dashboard/widgets/PortfolioSummaryWidget.h
+++ b/fincept-qt/src/screens/dashboard/widgets/PortfolioSummaryWidget.h
@@ -81,6 +81,9 @@ class PortfolioSummaryWidget : public BaseWidget {
// ── Holdings list layout ────────────────────────────────────────────────
QVBoxLayout* list_layout_ = nullptr;
+ /// Owner of `list_layout_` — carries the single stylesheet that styles
+ /// every holdings row via object-name selectors (P7).
+ QWidget* list_widget_ = nullptr;
// ── Theme-tracked widgets ──────────────────────────────────────────────
QWidget* summary_card_ = nullptr;
diff --git a/fincept-qt/src/screens/dashboard/widgets/QuickTradeWidget.cpp b/fincept-qt/src/screens/dashboard/widgets/QuickTradeWidget.cpp
index 75adcdcb7..47f689347 100644
--- a/fincept-qt/src/screens/dashboard/widgets/QuickTradeWidget.cpp
+++ b/fincept-qt/src/screens/dashboard/widgets/QuickTradeWidget.cpp
@@ -130,6 +130,21 @@ QuickTradeWidget::QuickTradeWidget(QWidget* parent) : BaseWidget(tr("QUICK TRADE
submit_btn_->setFixedHeight(32);
vl->addWidget(submit_btn_);
+ // ── Accessibility ──
+ symbol_input_->setAccessibleName(tr("Symbol"));
+ lookup_btn_->setAccessibleName(tr("Look up symbol"));
+ side_combo_->setAccessibleName(tr("Order side"));
+ order_type_->setAccessibleName(tr("Order type"));
+ qty_input_->setAccessibleName(tr("Quantity"));
+ price_input_->setAccessibleName(tr("Limit / stop price"));
+ submit_btn_->setAccessibleName(tr("Place order"));
+ setTabOrder(symbol_input_, lookup_btn_);
+ setTabOrder(lookup_btn_, side_combo_);
+ setTabOrder(side_combo_, order_type_);
+ setTabOrder(order_type_, qty_input_);
+ setTabOrder(qty_input_, price_input_);
+ setTabOrder(price_input_, submit_btn_);
+
// ── Connections ──
connect(lookup_btn_, &QPushButton::clicked, this, &QuickTradeWidget::lookup_symbol);
connect(symbol_input_, &QLineEdit::returnPressed, this, &QuickTradeWidget::lookup_symbol);
@@ -286,16 +301,16 @@ void QuickTradeWidget::submit_order() {
QString sym = current_symbol_.isEmpty() ? symbol_input_->text().trimmed().toUpper() : current_symbol_;
double qty = qty_input_->text().toDouble();
QString side = side_combo_->currentText();
- QString type = order_type_->currentText();
if (sym.isEmpty() || qty <= 0) {
QMessageBox::warning(this, tr("Quick Trade"), tr("Please enter a valid symbol and quantity."));
return;
}
- QString price_str = type == "MARKET" ? tr("market price ($%1)").arg(current_price_, 0, 'f', 2)
- : QString("$%1").arg(price_input_->text());
-
+ // NOTE: the removed `price_str` local compared `order_type_->currentText()`
+ // against the literal "MARKET" — a translated string, so the branch was
+ // wrong in every non-English locale. It was also immediately Q_UNUSED'd.
+ //
// This dashboard widget has no broker/account binding, so it cannot place a
// real or paper order. Previously it popped an "Order sent to trading
// engine" success box while sending nothing — a dangerous false confirmation
@@ -303,7 +318,6 @@ void QuickTradeWidget::submit_order() {
// entry (Equity/Crypto Trading), which has account selection, paper/live
// routing and an explicit confirmation. (Wiring Quick Trade to an account is
// tracked as a follow-up.)
- Q_UNUSED(price_str)
QMessageBox::information(
this, tr("Quick Trade"),
tr("Quick Trade is a preview widget and is not connected to a trading account — no order was placed.\n\n"
@@ -323,6 +337,35 @@ void QuickTradeWidget::retranslateUi() {
qty_lbl_->setText(tr("QTY"));
if (price_lbl_)
price_lbl_->setText(tr("PRICE"));
+ if (symbol_input_)
+ symbol_input_->setPlaceholderText(tr("Symbol (e.g. AAPL)"));
+ // Combo items and the bid/ask/total labels were previously left in the old
+ // language after a live switch.
+ if (order_type_) {
+ const int cur = order_type_->currentIndex();
+ const QStringList items = {tr("MARKET"), tr("LIMIT"), tr("STOP")};
+ for (int i = 0; i < order_type_->count() && i < items.size(); ++i)
+ order_type_->setItemText(i, items[i]);
+ order_type_->setCurrentIndex(cur);
+ if (price_input_)
+ price_input_->setPlaceholderText(cur == 0 ? tr("market") : QStringLiteral("0.00"));
+ }
+ if (side_combo_) {
+ const int cur = side_combo_->currentIndex();
+ const QStringList items = {tr("BUY"), tr("SELL"), tr("SHORT")};
+ for (int i = 0; i < side_combo_->count() && i < items.size(); ++i)
+ side_combo_->setItemText(i, items[i]);
+ side_combo_->setCurrentIndex(cur);
+ }
+ if (bid_label_)
+ bid_label_->setText(current_price_ > 0 ? tr("BID —") : tr("BID --"));
+ if (ask_label_)
+ ask_label_->setText(current_price_ > 0 ? tr("ASK —") : tr("ASK --"));
+ if (est_total_) {
+ const double qty = qty_input_ ? qty_input_->text().toDouble() : 0.0;
+ est_total_->setText(current_price_ > 0 && qty > 0 ? tr("EST. TOTAL $%1").arg(qty * current_price_, 0, 'f', 2)
+ : tr("EST. TOTAL --"));
+ }
// submit_btn_ text is side-aware ("PLACE BUY ORDER" etc.) — let on_side_changed re-derive it.
if (side_combo_)
on_side_changed(side_combo_->currentIndex());
diff --git a/fincept-qt/src/screens/dashboard/widgets/QuoteTableWidget.cpp b/fincept-qt/src/screens/dashboard/widgets/QuoteTableWidget.cpp
index 189ac455b..24743ae4c 100644
--- a/fincept-qt/src/screens/dashboard/widgets/QuoteTableWidget.cpp
+++ b/fincept-qt/src/screens/dashboard/widgets/QuoteTableWidget.cpp
@@ -74,7 +74,8 @@ void QuoteTableWidget::hub_subscribe_all() {
return;
row_cache_.insert(sym, v.value<services::QuoteData>());
set_loading_progress(row_cache_.size(), symbols_.size());
- render_from_cache();
+ // One render per delivery burst, not one per symbol (P9/P10).
+ schedule_render([this]() { render_from_cache(); });
});
}
hub_active_ = true;
@@ -107,21 +108,4 @@ void QuoteTableWidget::render_from_cache() {
}
}
-void QuoteTableWidget::populate(const QVector<services::QuoteData>& quotes) {
- table_->clear_data();
-
- for (const auto& q : quotes) {
- QString display_name = label_map_.value(q.symbol, q.symbol);
- QString price_str = QString::number(q.price, 'f', price_decimals_);
- double chg_abs = q.change;
- QString chg_str = QString("%1%2").arg(chg_abs >= 0 ? "+" : "").arg(chg_abs, 0, 'f', price_decimals_);
- QString pct_str = QString("%1%2%").arg(q.change_pct >= 0 ? "+" : "").arg(q.change_pct, 0, 'f', 2);
-
- table_->add_row({display_name, price_str, chg_str, pct_str});
- int row = table_->rowCount() - 1;
- table_->set_cell_color(row, 2, ui::change_color(q.change_pct));
- table_->set_cell_color(row, 3, ui::change_color(q.change_pct));
- }
-}
-
} // namespace fincept::screens::widgets
diff --git a/fincept-qt/src/screens/dashboard/widgets/QuoteTableWidget.h b/fincept-qt/src/screens/dashboard/widgets/QuoteTableWidget.h
index 6cce262de..18e708aa1 100644
--- a/fincept-qt/src/screens/dashboard/widgets/QuoteTableWidget.h
+++ b/fincept-qt/src/screens/dashboard/widgets/QuoteTableWidget.h
@@ -40,7 +40,6 @@ class QuoteTableWidget : public BaseWidget {
private:
void apply_styles();
- void populate(const QVector<fincept::services::QuoteData>& quotes);
/// Hub path: subscribe to every symbol's quote topic and apply updates
/// into the row cache + redraw. Called from showEvent.
diff --git a/fincept-qt/src/screens/dashboard/widgets/RiskMetricsWidget.cpp b/fincept-qt/src/screens/dashboard/widgets/RiskMetricsWidget.cpp
index 5ecc84f43..82942d197 100644
--- a/fincept-qt/src/screens/dashboard/widgets/RiskMetricsWidget.cpp
+++ b/fincept-qt/src/screens/dashboard/widgets/RiskMetricsWidget.cpp
@@ -208,7 +208,8 @@ void RiskMetricsWidget::hub_subscribe_all() {
return;
row_cache_.insert(sym, v.value<services::QuoteData>());
set_loading_progress(row_cache_.size(), kRiskSymbols.size());
- rebuild_from_cache();
+ // One redraw per delivery burst, not one per symbol.
+ schedule_render([this]() { rebuild_from_cache(); });
});
}
hub_active_ = true;
@@ -305,12 +306,10 @@ void RiskMetricsWidget::populate(const QVector<services::QuoteData>& quotes) {
};
if (map.contains("SPY") && map.contains("QQQ")) {
- double d = map["SPY"]->change_pct - map["QQQ"]->change_pct;
spy_qqq_spread_->setText(spread_str(map["SPY"]->change_pct, map["QQQ"]->change_pct));
spy_qqq_spread_->setStyleSheet(
QString("color: %1; font-size: 10px; font-weight: bold; background: transparent;")
.arg(spread_color(map["SPY"]->change_pct, map["QQQ"]->change_pct)));
- (void)d;
}
if (map.contains("SPY") && map.contains("IWM")) {
spy_iwm_spread_->setText(spread_str(map["SPY"]->change_pct, map["IWM"]->change_pct));
diff --git a/fincept-qt/src/screens/dashboard/widgets/ScreenerWidget.cpp b/fincept-qt/src/screens/dashboard/widgets/ScreenerWidget.cpp
index 39e1b7187..a7fe8e03c 100644
--- a/fincept-qt/src/screens/dashboard/widgets/ScreenerWidget.cpp
+++ b/fincept-qt/src/screens/dashboard/widgets/ScreenerWidget.cpp
@@ -62,16 +62,24 @@ ScreenerWidget::ScreenerWidget(QWidget* parent) : BaseWidget(tr("STOCK SCREENER"
scroll_ = new QScrollArea;
scroll_->setWidgetResizable(true);
- auto* list_widget = new QWidget(this);
- list_widget->setStyleSheet("background: transparent;");
- list_layout_ = new QVBoxLayout(list_widget);
+ list_widget_ = new QWidget(this);
+ list_widget_->setObjectName("screenerList");
+ list_layout_ = new QVBoxLayout(list_widget_);
list_layout_->setContentsMargins(0, 0, 0, 0);
list_layout_->setSpacing(0);
+
+ // Empty / loading placeholder — the screener used to render nothing at all
+ // until the first quote landed, which reads as a broken tile.
+ empty_lbl_ = new QLabel(tr("Waiting for quotes..."));
+ empty_lbl_->setObjectName("scEmpty");
+ empty_lbl_->setAlignment(Qt::AlignCenter);
+ list_layout_->addWidget(empty_lbl_);
list_layout_->addStretch();
- scroll_->setWidget(list_widget);
+ scroll_->setWidget(list_widget_);
vl->addWidget(scroll_, 1);
+ filter_combo_->setAccessibleName(tr("Screener sort order"));
connect(filter_combo_, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &ScreenerWidget::apply_filter);
connect(this, &BaseWidget::refresh_requested, this, &ScreenerWidget::refresh_data);
@@ -108,6 +116,28 @@ void ScreenerWidget::apply_styles() {
.arg(ui::colors::BORDER_MED()) +
"QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical { height: 0; }");
+ // ── Row styling, hoisted (P7) ──
+ // render_rows() draws up to 20 rows × 5 widgets. Styling each of those
+ // inline meant ~100 full CSS reparses per render, and render ran once per
+ // arriving symbol (42 of them). All of it is now one stylesheet, set here
+ // and only re-set on a theme change; rows just carry object names.
+ if (list_widget_) {
+ list_widget_->setStyleSheet(
+ QString("#screenerList{background:transparent;}"
+ "#screenerList QWidget#scRow{background:transparent;}"
+ "#screenerList QWidget#scRowAlt{background:%1;}"
+ "#screenerList QLabel{font-size:10px;background:transparent;}"
+ "#screenerList QLabel#scSym{color:%2;font-weight:bold;}"
+ "#screenerList QLabel#scPrice{color:%3;}"
+ "#screenerList QLabel#scChgPos{color:%4;font-weight:bold;}"
+ "#screenerList QLabel#scChgNeg{color:%5;font-weight:bold;}"
+ "#screenerList QLabel#scChgFlat{color:%3;font-weight:bold;}"
+ "#screenerList QLabel#scVol{color:%6;}"
+ "#screenerList QLabel#scEmpty{color:%7;font-size:11px;padding:20px;}")
+ .arg(ui::colors::BG_RAISED(), ui::colors::INFO(), ui::colors::TEXT_PRIMARY(), ui::colors::POSITIVE(),
+ ui::colors::NEGATIVE(), ui::colors::TEXT_SECONDARY(), ui::colors::TEXT_TERTIARY()));
+ }
+
// Re-render data rows with current tokens if data exists
if (!all_quotes_.isEmpty())
apply_filter();
@@ -148,7 +178,8 @@ void ScreenerWidget::hub_subscribe_all() {
return;
row_cache_.insert(sym, v.value<services::QuoteData>());
set_loading_progress(row_cache_.size(), kScreenerSymbols.size());
- rebuild_all_quotes();
+ // One sort + 20-row redraw per delivery burst, not one per symbol.
+ schedule_render([this]() { rebuild_all_quotes(); });
});
}
hub_active_ = true;
@@ -171,8 +202,10 @@ void ScreenerWidget::rebuild_all_quotes() {
}
void ScreenerWidget::apply_filter() {
- if (all_quotes_.isEmpty())
+ if (all_quotes_.isEmpty()) {
+ render_rows({}); // keeps the empty-state label on screen
return;
+ }
QVector<services::QuoteData> sorted = all_quotes_;
int idx = filter_combo_ ? filter_combo_->currentIndex() : 0;
@@ -206,37 +239,47 @@ void ScreenerWidget::apply_filter() {
void ScreenerWidget::render_rows(const QVector<services::QuoteData>& rows) {
while (list_layout_->count() > 0) {
auto* item = list_layout_->takeAt(0);
- if (item->widget())
+ // empty_lbl_ is reused across renders — take it out of the layout but
+ // never delete it.
+ if (item->widget() && item->widget() != empty_lbl_)
item->widget()->deleteLater();
delete item;
}
+ if (rows.isEmpty()) {
+ if (empty_lbl_) {
+ empty_lbl_->setVisible(true);
+ list_layout_->addWidget(empty_lbl_);
+ }
+ list_layout_->addStretch();
+ return;
+ }
+ if (empty_lbl_)
+ empty_lbl_->setVisible(false);
+
+ // No setStyleSheet in this loop — every colour/size comes from the single
+ // stylesheet on list_widget_ (see apply_styles) via these object names.
bool alt = false;
for (const auto& q : rows) {
- auto* row = new QWidget(this);
- row->setStyleSheet(QString("background: %1;").arg(alt ? ui::colors::BG_RAISED() : "transparent"));
+ auto* row = new QWidget(list_widget_);
+ row->setObjectName(alt ? QStringLiteral("scRowAlt") : QStringLiteral("scRow"));
auto* rl = new QHBoxLayout(row);
rl->setContentsMargins(8, 4, 8, 4);
auto* sym = new QLabel(q.symbol);
- sym->setStyleSheet(
- QString("color: %1; font-size: 10px; font-weight: bold; background: transparent;").arg(ui::colors::INFO()));
+ sym->setObjectName("scSym");
rl->addWidget(sym, 2);
auto* price = new QLabel(QString("$%1").arg(q.price, 0, 'f', 2));
+ price->setObjectName("scPrice");
price->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
- price->setStyleSheet(
- QString("color: %1; font-size: 10px; background: transparent;").arg(ui::colors::TEXT_PRIMARY()));
rl->addWidget(price, 2);
- QString chg_str = QString("%1%2%").arg(q.change_pct >= 0 ? "+" : "").arg(q.change_pct, 0, 'f', 2);
- QString chg_col = q.change_pct > 0 ? ui::colors::POSITIVE()
- : q.change_pct < 0 ? ui::colors::NEGATIVE()
- : ui::colors::TEXT_PRIMARY();
- auto* chg = new QLabel(chg_str);
+ auto* chg = new QLabel(QString("%1%2%").arg(q.change_pct >= 0 ? "+" : "").arg(q.change_pct, 0, 'f', 2));
+ chg->setObjectName(q.change_pct > 0 ? QStringLiteral("scChgPos")
+ : q.change_pct < 0 ? QStringLiteral("scChgNeg")
+ : QStringLiteral("scChgFlat"));
chg->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
- chg->setStyleSheet(
- QString("color: %1; font-size: 10px; font-weight: bold; background: transparent;").arg(chg_col));
rl->addWidget(chg, 1);
// Format volume: e.g. 45.2M
@@ -251,9 +294,8 @@ void ScreenerWidget::render_rows(const QVector<services::QuoteData>& rows) {
vol_str = QString::number(static_cast<long long>(q.volume));
auto* vol = new QLabel(vol_str);
+ vol->setObjectName("scVol");
vol->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
- vol->setStyleSheet(
- QString("color: %1; font-size: 10px; background: transparent;").arg(ui::colors::TEXT_SECONDARY()));
rl->addWidget(vol, 2);
list_layout_->addWidget(row);
@@ -266,9 +308,29 @@ void ScreenerWidget::render_rows(const QVector<services::QuoteData>& rows) {
void ScreenerWidget::retranslateUi() {
BaseWidget::retranslateUi();
set_title(tr("STOCK SCREENER"));
+ // Must match the source string used in the constructor — this said
+ // "FILTER:" while the ctor used "SORT BY", so a language switch silently
+ // relabelled the control (and looked up a key that isn't in the catalogue).
if (filter_lbl_)
- filter_lbl_->setText(tr("FILTER:"));
- rebuild_all_quotes(); // re-renders headers + count label in the new language
+ filter_lbl_->setText(tr("SORT BY"));
+ if (count_lbl_)
+ count_lbl_->setText(tr("%1 symbols").arg(kScreenerSymbols.size()));
+ if (empty_lbl_)
+ empty_lbl_->setText(tr("Waiting for quotes..."));
+ // Column headers + sort-order items are set once in the ctor — the old
+ // rebuild_all_quotes() call re-rendered data rows but never these.
+ const QStringList hdrs = {tr("SYMBOL"), tr("PRICE"), tr("CHG%"), tr("VOLUME")};
+ for (int i = 0; i < header_labels_.size() && i < hdrs.size(); ++i)
+ header_labels_[i]->setText(hdrs[i]);
+ if (filter_combo_) {
+ const int cur = filter_combo_->currentIndex();
+ const QStringList items = {tr("% CHANGE ↑"), tr("% CHANGE ↓"), tr("VOLUME ↓"), tr("PRICE ↓"), tr("PRICE ↑")};
+ for (int i = 0; i < filter_combo_->count() && i < items.size(); ++i)
+ filter_combo_->setItemText(i, items[i]);
+ filter_combo_->setCurrentIndex(cur);
+ filter_combo_->setAccessibleName(tr("Screener sort order"));
+ }
+ rebuild_all_quotes();
}
} // namespace fincept::screens::widgets
diff --git a/fincept-qt/src/screens/dashboard/widgets/ScreenerWidget.h b/fincept-qt/src/screens/dashboard/widgets/ScreenerWidget.h
index 13db40ac6..508b6d420 100644
--- a/fincept-qt/src/screens/dashboard/widgets/ScreenerWidget.h
+++ b/fincept-qt/src/screens/dashboard/widgets/ScreenerWidget.h
@@ -41,6 +41,10 @@ class ScreenerWidget : public BaseWidget {
QComboBox* filter_combo_ = nullptr;
QVBoxLayout* list_layout_ = nullptr;
+ /// Owner of `list_layout_`. Carries the ONE stylesheet that styles every
+ /// data row via object-name selectors (P7) — rows themselves never call
+ /// setStyleSheet.
+ QWidget* list_widget_ = nullptr;
QVector<services::QuoteData> all_quotes_;
// Widgets needing theme-aware restyling
@@ -50,6 +54,8 @@ class ScreenerWidget : public BaseWidget {
QWidget* header_ = nullptr;
QVector<QLabel*> header_labels_;
QScrollArea* scroll_ = nullptr;
+ /// Placeholder shown when the screener has no data yet / all rows filtered.
+ QLabel* empty_lbl_ = nullptr;
QHash<QString, services::QuoteData> row_cache_;
bool hub_active_ = false;
diff --git a/fincept-qt/src/screens/dashboard/widgets/SectorHeatmapWidget.cpp b/fincept-qt/src/screens/dashboard/widgets/SectorHeatmapWidget.cpp
index baecc422a..5381bf956 100644
--- a/fincept-qt/src/screens/dashboard/widgets/SectorHeatmapWidget.cpp
+++ b/fincept-qt/src/screens/dashboard/widgets/SectorHeatmapWidget.cpp
@@ -26,6 +26,7 @@ QMap<QString, QString> SectorHeatmapWidget::sector_labels() {
SectorHeatmapWidget::SectorHeatmapWidget(QWidget* parent) : BaseWidget(tr("SECTOR HEATMAP"), parent) {
grid_container_ = new QWidget(this);
+ grid_container_->setObjectName("sectorHeatGrid");
grid_ = new QGridLayout(grid_container_);
grid_->setContentsMargins(4, 4, 4, 4);
grid_->setSpacing(3);
@@ -39,16 +40,28 @@ SectorHeatmapWidget::SectorHeatmapWidget(QWidget* parent) : BaseWidget(tr("SECTO
}
void SectorHeatmapWidget::apply_styles() {
- // The grid cells are rebuilt dynamically in populate() using current tokens.
- // Re-populate with existing data to pick up new theme colors.
- // If no data yet, nothing to restyle.
+ if (!grid_container_)
+ return;
+ // Static cell chrome lives in ONE parent stylesheet with object-name
+ // selectors (P7) instead of an inline setStyleSheet per label per refresh.
+ // Only the data-driven bits (tile tint, +/- colour) are still set
+ // per-widget, and only when they actually change.
+ grid_container_->setStyleSheet(
+ QString("#sectorHeatGrid QLabel#sectorName{color:%1;font-size:9px;font-weight:bold;background:transparent;}"
+ "#sectorHeatGrid QLabel#sectorChg{font-size:11px;font-weight:bold;background:transparent;}")
+ .arg(ui::colors::TEXT_PRIMARY()));
+ // Force the data-driven colours to be re-applied against the new tokens.
+ for (auto& c : cells_) {
+ c.last_bg.clear();
+ c.last_sign = 0;
+ }
}
void SectorHeatmapWidget::on_theme_changed() {
apply_styles();
- // Re-populate the grid with current data so cells pick up new token values
- if (grid_->count() > 0)
- refresh_data();
+ // Re-render from the cache. This used to call refresh_data(), which fires
+ // a forced network fetch for 12 symbols just because the palette changed.
+ rebuild_from_cache();
}
void SectorHeatmapWidget::showEvent(QShowEvent* e) {
@@ -82,7 +95,8 @@ void SectorHeatmapWidget::hub_subscribe_all() {
return;
row_cache_.insert(sym, v.value<services::QuoteData>());
set_loading_progress(row_cache_.size(), total);
- rebuild_from_cache();
+ // One grid update per delivery burst, not one per sector ETF.
+ schedule_render([this]() { rebuild_from_cache(); });
});
}
hub_active_ = true;
@@ -105,48 +119,72 @@ void SectorHeatmapWidget::rebuild_from_cache() {
populate(quotes);
}
-void SectorHeatmapWidget::populate(const QVector<services::QuoteData>& quotes) {
- // Clear grid
- QLayoutItem* item;
- while ((item = grid_->takeAt(0)) != nullptr) {
- if (item->widget())
- item->widget()->deleteLater();
- delete item;
- }
+SectorHeatmapWidget::Cell& SectorHeatmapWidget::cell_at(int index) {
+ while (cells_.size() <= index) {
+ Cell c;
+ c.frame = new QFrame(grid_container_);
+ c.frame->setMinimumSize(80, 40);
- auto labels = sector_labels();
- int idx = 0;
- for (const auto& q : quotes) {
- auto* cell = new QFrame;
- cell->setMinimumSize(80, 40);
+ auto* cl = new QVBoxLayout(c.frame);
+ cl->setContentsMargins(4, 2, 4, 2);
+ cl->setSpacing(0);
- int intensity = static_cast<int>(std::min(std::abs(q.change_pct) * 60.0, 200.0));
- QColor tint(q.change_pct >= 0 ? ui::colors::POSITIVE() : ui::colors::NEGATIVE());
- tint.setAlpha(40 + intensity);
- QString bg_color = tint.name(QColor::HexArgb);
+ c.name = new QLabel(c.frame);
+ c.name->setObjectName("sectorName");
+ c.name->setAlignment(Qt::AlignCenter);
+ cl->addWidget(c.name);
- cell->setStyleSheet(QString("background: %1; border: 1px solid %2; border-radius: 2px;")
- .arg(bg_color, ui::colors::BORDER_DIM()));
+ c.chg = new QLabel(c.frame);
+ c.chg->setObjectName("sectorChg");
+ c.chg->setAlignment(Qt::AlignCenter);
+ cl->addWidget(c.chg);
- auto* cl = new QVBoxLayout(cell);
- cl->setContentsMargins(4, 2, 4, 2);
- cl->setSpacing(0);
+ const int i = static_cast<int>(cells_.size());
+ grid_->addWidget(c.frame, i / 3, i % 3);
+ cells_.append(c);
+ }
+ return cells_[index];
+}
- auto* name = new QLabel(labels.value(q.symbol, q.symbol));
- name->setStyleSheet(QString("color: %1; font-size: 9px; font-weight: bold; background: transparent;")
- .arg(ui::colors::TEXT_PRIMARY()));
- name->setAlignment(Qt::AlignCenter);
- cl->addWidget(name);
+void SectorHeatmapWidget::populate(const QVector<services::QuoteData>& quotes) {
+ const auto labels = sector_labels();
- auto* chg = new QLabel(QString("%1%2%").arg(q.change_pct >= 0 ? "+" : "").arg(q.change_pct, 0, 'f', 2));
- chg->setStyleSheet(QString("color: %1; font-size: 11px; font-weight: bold; background: transparent;")
- .arg(q.change_pct >= 0 ? ui::colors::POSITIVE() : ui::colors::NEGATIVE()));
- chg->setAlignment(Qt::AlignCenter);
- cl->addWidget(chg);
+ const int n = static_cast<int>(quotes.size());
+ for (int idx = 0; idx < n; ++idx) {
+ const auto& q = quotes[idx];
+ Cell& c = cell_at(idx);
+ c.frame->setVisible(true);
- grid_->addWidget(cell, idx / 3, idx % 3);
- ++idx;
+ const int intensity = static_cast<int>(std::min(std::abs(q.change_pct) * 60.0, 200.0));
+ QColor tint(q.change_pct >= 0 ? ui::colors::POSITIVE() : ui::colors::NEGATIVE());
+ tint.setAlpha(40 + intensity);
+ const QString bg = QString("background: %1; border: 1px solid %2; border-radius: 2px;")
+ .arg(tint.name(QColor::HexArgb), ui::colors::BORDER_DIM());
+ // Skip the CSS reparse when the tint is unchanged (the common case
+ // for a quiet sector between two refresh ticks).
+ if (bg != c.last_bg) {
+ c.last_bg = bg;
+ c.frame->setStyleSheet(bg);
+ }
+
+ const QString display = labels.value(q.symbol, q.symbol);
+ if (c.name->text() != display)
+ c.name->setText(display);
+ c.name->setToolTip(QString("%1 (%2)").arg(display, q.symbol));
+
+ c.chg->setText(QString("%1%2%").arg(q.change_pct >= 0 ? "+" : "").arg(q.change_pct, 0, 'f', 2));
+ const int sign = q.change_pct >= 0 ? 1 : -1;
+ if (sign != c.last_sign) {
+ c.last_sign = sign;
+ c.chg->setStyleSheet(QString("color: %1; font-size: 11px; font-weight: bold; background: transparent;")
+ .arg(sign > 0 ? ui::colors::POSITIVE() : ui::colors::NEGATIVE()));
+ }
}
+
+ // Hide (don't destroy) any cells beyond the current data set so a shorter
+ // payload doesn't leave stale tiles on screen.
+ for (int i = n; i < static_cast<int>(cells_.size()); ++i)
+ cells_[i].frame->setVisible(false);
}
void SectorHeatmapWidget::retranslateUi() {
diff --git a/fincept-qt/src/screens/dashboard/widgets/SectorHeatmapWidget.h b/fincept-qt/src/screens/dashboard/widgets/SectorHeatmapWidget.h
index 6669ddc6d..84656784d 100644
--- a/fincept-qt/src/screens/dashboard/widgets/SectorHeatmapWidget.h
+++ b/fincept-qt/src/screens/dashboard/widgets/SectorHeatmapWidget.h
@@ -2,8 +2,11 @@
#include "screens/dashboard/widgets/BaseWidget.h"
#include "services/markets/MarketDataService.h"
+#include <QFrame>
#include <QGridLayout>
#include <QHash>
+#include <QLabel>
+#include <QVector>
namespace fincept::screens::widgets {
@@ -38,6 +41,20 @@ class SectorHeatmapWidget : public BaseWidget {
QGridLayout* grid_ = nullptr;
QWidget* grid_container_ = nullptr;
+ /// One persistent heat cell per sector. Cells are created once and then
+ /// only have their text / background updated — the previous implementation
+ /// destroyed and rebuilt 12 cells (36 inline setStyleSheet calls) on every
+ /// single hub delivery.
+ struct Cell {
+ QFrame* frame = nullptr;
+ QLabel* name = nullptr;
+ QLabel* chg = nullptr;
+ QString last_bg; ///< last applied background css, to skip re-parses
+ int last_sign = 0; ///< -1 / +1, 0 = never set
+ };
+ QVector<Cell> cells_;
+ Cell& cell_at(int index);
+
static QStringList sector_symbols();
static QMap<QString, QString> sector_labels();
diff --git a/fincept-qt/src/screens/dashboard/widgets/StockQuoteWidget.cpp b/fincept-qt/src/screens/dashboard/widgets/StockQuoteWidget.cpp
index 14f215097..2b26db359 100644
--- a/fincept-qt/src/screens/dashboard/widgets/StockQuoteWidget.cpp
+++ b/fincept-qt/src/screens/dashboard/widgets/StockQuoteWidget.cpp
@@ -4,10 +4,21 @@
#include "datahub/DataHubMetaTypes.h"
#include "ui/theme/Theme.h"
+#include <QDialog>
+#include <QDialogButtonBox>
+#include <QFormLayout>
#include <QFrame>
+#include <QLineEdit>
namespace fincept::screens::widgets {
+namespace {
+QString normalize_symbol(const QString& s) {
+ const QString t = s.trimmed().toUpper();
+ return t.isEmpty() ? QStringLiteral("AAPL") : t;
+}
+} // namespace
+
StockQuoteWidget::StockQuoteWidget(const QString& symbol, QWidget* parent)
: BaseWidget(tr("QUOTE: %1").arg(symbol.toUpper()), parent), symbol_(symbol.toUpper()) {
auto* vl = content_layout();
@@ -53,15 +64,16 @@ StockQuoteWidget::StockQuoteWidget(const QString& symbol, QWidget* parent)
gl->setContentsMargins(0, 0, 0, 0);
gl->setSpacing(6);
- auto make_stat = [&](int row, int col, const QString& label, QLabel*& val_out) {
+ auto make_stat = [&](int row, int col, const char* key, QLabel*& val_out) {
auto* cell = new QWidget(this);
stat_cells_.append(cell);
auto* cl = new QVBoxLayout(cell);
cl->setContentsMargins(8, 6, 8, 6);
cl->setSpacing(2);
- auto* lbl = new QLabel(label);
+ auto* lbl = new QLabel(tr(key));
stat_labels_.append(lbl);
+ stat_label_keys_.append(QString::fromLatin1(key));
cl->addWidget(lbl);
val_out = new QLabel("--");
@@ -71,21 +83,61 @@ StockQuoteWidget::StockQuoteWidget(const QString& symbol, QWidget* parent)
gl->addWidget(cell, row, col);
};
- make_stat(0, 0, tr("OPEN"), open_val_);
- make_stat(0, 1, tr("PREV CLOSE"), prev_val_);
- make_stat(1, 0, tr("HIGH"), high_val_);
- make_stat(1, 1, tr("LOW"), low_val_);
- make_stat(2, 0, tr("VOLUME"), volume_val_);
+ make_stat(0, 0, QT_TR_NOOP("OPEN"), open_val_);
+ make_stat(0, 1, QT_TR_NOOP("PREV CLOSE"), prev_val_);
+ make_stat(1, 0, QT_TR_NOOP("HIGH"), high_val_);
+ make_stat(1, 1, QT_TR_NOOP("LOW"), low_val_);
+ make_stat(2, 0, QT_TR_NOOP("VOLUME"), volume_val_);
vl->addWidget(stats);
vl->addStretch();
+ set_configurable(true);
connect(this, &BaseWidget::refresh_requested, this, &StockQuoteWidget::refresh_data);
apply_styles();
set_loading(true);
}
+QJsonObject StockQuoteWidget::config() const {
+ QJsonObject o;
+ o.insert("symbol", symbol_);
+ return o;
+}
+
+void StockQuoteWidget::apply_config(const QJsonObject& cfg) {
+ const QString next = normalize_symbol(cfg.value("symbol").toString(symbol_));
+ if (next == symbol_)
+ return;
+ set_symbol(next);
+}
+
+QDialog* StockQuoteWidget::make_config_dialog(QWidget* parent) {
+ auto* dlg = new QDialog(parent);
+ dlg->setWindowTitle(tr("Configure — Stock Quote"));
+ auto* form = new QFormLayout(dlg);
+
+ auto* edit = new QLineEdit(dlg);
+ edit->setText(symbol_);
+ edit->setPlaceholderText(tr("e.g. AAPL"));
+ edit->setAccessibleName(tr("Symbol"));
+ form->addRow(tr("Symbol"), edit);
+
+ auto* buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, dlg);
+ form->addRow(buttons);
+ dlg->setTabOrder(edit, buttons);
+
+ connect(buttons, &QDialogButtonBox::accepted, dlg, [this, dlg, edit]() {
+ QJsonObject cfg;
+ cfg.insert("symbol", normalize_symbol(edit->text()));
+ apply_config(cfg);
+ emit config_changed(cfg);
+ dlg->accept();
+ });
+ connect(buttons, &QDialogButtonBox::rejected, dlg, &QDialog::reject);
+ return dlg;
+}
+
void StockQuoteWidget::apply_styles() {
price_label_->setStyleSheet(QString("color: %1; font-size: 28px; font-weight: bold; background: transparent;")
.arg(ui::colors::TEXT_PRIMARY()));
@@ -123,12 +175,24 @@ void StockQuoteWidget::hideEvent(QHideEvent* e) {
}
void StockQuoteWidget::set_symbol(const QString& symbol) {
- symbol_ = symbol.toUpper();
+ symbol_ = normalize_symbol(symbol);
set_title(tr("QUOTE: %1").arg(symbol_));
+ ticker_label_->setText(symbol_);
+
+ // Blank the previous symbol's numbers immediately — leaving AAPL's price
+ // under an "MSFT" heading until the first delivery is actively misleading.
+ price_label_->setText(QStringLiteral("--"));
+ change_label_->setText(QStringLiteral("--"));
+ arrow_label_->setText(QString());
+ for (auto* v : stat_values_)
+ v->setText(QStringLiteral("--"));
+
// Re-subscribe to the new topic; old sub for previous symbol is
// dropped wholesale by `unsubscribe(this)` inside hub_resubscribe().
- if (isVisible())
+ if (isVisible()) {
+ set_loading(true);
hub_resubscribe();
+ }
}
void StockQuoteWidget::refresh_data() {
@@ -174,7 +238,12 @@ void StockQuoteWidget::populate(const services::QuoteData& q) {
QString("color: %1; font-size: 28px; font-weight: bold; background: transparent;").arg(color));
auto fmt = [](double v) { return v > 0 ? QString("$%1").arg(v, 0, 'f', 2) : QString("--"); };
- open_val_->setText(fmt(q.high)); // yfinance batch returns high but not open separately — use high
+ // The batch quote snapshot carries last/change/high/low/volume but no
+ // session open. Showing `high` here (as this did previously) prints a
+ // wrong number under an "OPEN" heading — on a trading terminal that is
+ // worse than showing nothing.
+ open_val_->setText(QStringLiteral("--"));
+ open_val_->setToolTip(tr("Session open is not available in the batch quote feed"));
high_val_->setText(fmt(q.high));
low_val_->setText(fmt(q.low));
prev_val_->setText(fmt(q.price - q.change));
@@ -193,7 +262,11 @@ void StockQuoteWidget::populate(const services::QuoteData& q) {
void StockQuoteWidget::retranslateUi() {
BaseWidget::retranslateUi();
set_title(tr("QUOTE: %1").arg(symbol_));
- refresh_data(); // re-renders stat cell labels in the new language
+ // Re-run tr() on the kept stat-cell headings. (This previously called
+ // refresh_data(), which fires a network request and never touched a
+ // single label.)
+ for (int i = 0; i < stat_labels_.size() && i < stat_label_keys_.size(); ++i)
+ stat_labels_[i]->setText(tr(stat_label_keys_[i].toUtf8().constData()));
}
} // namespace fincept::screens::widgets
diff --git a/fincept-qt/src/screens/dashboard/widgets/StockQuoteWidget.h b/fincept-qt/src/screens/dashboard/widgets/StockQuoteWidget.h
index 59c898f71..63530e874 100644
--- a/fincept-qt/src/screens/dashboard/widgets/StockQuoteWidget.h
+++ b/fincept-qt/src/screens/dashboard/widgets/StockQuoteWidget.h
@@ -4,6 +4,7 @@
#include <QGridLayout>
#include <QLabel>
+#include <QStringList>
namespace fincept::screens::widgets {
@@ -20,7 +21,15 @@ class StockQuoteWidget : public BaseWidget {
void set_symbol(const QString& symbol);
+ /// Per-instance config — the tracked symbol. The widget registry already
+ /// seeds the constructor from `cfg["symbol"]`; these overrides close the
+ /// loop so a symbol picked via the gear icon is written back to the
+ /// persisted dashboard layout.
+ QJsonObject config() const override;
+ void apply_config(const QJsonObject& cfg) override;
+
protected:
+ QDialog* make_config_dialog(QWidget* parent) override;
void on_theme_changed() override;
void showEvent(QShowEvent* e) override;
void hideEvent(QHideEvent* e) override;
@@ -53,6 +62,9 @@ class StockQuoteWidget : public BaseWidget {
QVector<QWidget*> stat_cells_;
QVector<QLabel*> stat_labels_;
QVector<QLabel*> stat_values_;
+ // English source keys for stat_labels_, in the same order, so
+ // retranslateUi() can re-run tr() without rebuilding the grid.
+ QStringList stat_label_keys_;
bool hub_active_ = false;
};
diff --git a/fincept-qt/src/screens/dashboard/widgets/TodayPnLWidget.cpp b/fincept-qt/src/screens/dashboard/widgets/TodayPnLWidget.cpp
index bf5d70fe3..1a841cf64 100644
--- a/fincept-qt/src/screens/dashboard/widgets/TodayPnLWidget.cpp
+++ b/fincept-qt/src/screens/dashboard/widgets/TodayPnLWidget.cpp
@@ -231,7 +231,17 @@ void TodayPnLWidget::apply_styles() {
void TodayPnLWidget::retranslateUi() {
BaseWidget::retranslateUi();
set_title(tr("TODAY P&L"));
- hub_resubscribe(); // re-renders header hint + breakdown labels in the new language
+ // Re-translate the kept captions instead of tearing down and rebuilding
+ // the hub subscription (which the old implementation did, and which
+ // translated nothing).
+ if (day_pnl_label_)
+ day_pnl_label_->setText(tr("Day"));
+ if (realized_pnl_label_)
+ realized_pnl_label_->setText(tr("Realized"));
+ if (positions_label_)
+ positions_label_->setText(tr("Positions"));
+ if (header_hint_ && account_id_.isEmpty())
+ header_hint_->setText(tr("No active account — click gear to configure"));
}
} // namespace fincept::screens::widgets
diff --git a/fincept-qt/src/screens/dashboard/widgets/TopMoversWidget.cpp b/fincept-qt/src/screens/dashboard/widgets/TopMoversWidget.cpp
index ef2d64192..3cb28f502 100644
--- a/fincept-qt/src/screens/dashboard/widgets/TopMoversWidget.cpp
+++ b/fincept-qt/src/screens/dashboard/widgets/TopMoversWidget.cpp
@@ -16,6 +16,8 @@ TopMoversWidget::TopMoversWidget(QWidget* parent) : BaseWidget(tr("TOP MOVERS"),
gainers_btn_ = new QPushButton(QString(QChar(0x25B2)) + " " + tr("GAINERS"));
losers_btn_ = new QPushButton(QString(QChar(0x25BC)) + " " + tr("LOSERS"));
+ gainers_btn_->setAccessibleName(tr("Show top gainers"));
+ losers_btn_->setAccessibleName(tr("Show top losers"));
connect(gainers_btn_, &QPushButton::clicked, this, [this]() { show_tab(true); });
connect(losers_btn_, &QPushButton::clicked, this, [this]() { show_tab(false); });
@@ -40,7 +42,8 @@ TopMoversWidget::TopMoversWidget(QWidget* parent) : BaseWidget(tr("TOP MOVERS"),
}
void TopMoversWidget::apply_styles() {
- // Apply styles based on current tab state
+ // Theme changed → force the tab-button stylesheets to be re-applied.
+ tab_style_applied_ = false;
show_tab(showing_gainers_);
}
@@ -79,7 +82,8 @@ void TopMoversWidget::hub_subscribe_all() {
return;
row_cache_.insert(sym, v.value<services::QuoteData>());
set_loading_progress(row_cache_.size(), symbols_.size());
- rebuild_from_cache();
+ // One sort + redraw per delivery burst, not one per symbol.
+ schedule_render([this]() { rebuild_from_cache(); });
});
}
hub_active_ = true;
@@ -104,20 +108,28 @@ void TopMoversWidget::rebuild_from_cache() {
}
void TopMoversWidget::show_tab(bool gainers) {
+ // show_tab() runs on every hub delivery (via rebuild_from_cache), but the
+ // two tab-button stylesheets only depend on `gainers` + the theme. Each
+ // setStyleSheet is a full CSS reparse, so re-applying them per tick was
+ // pure waste — only touch them when the state actually changed.
+ const bool tab_style_dirty = (!tab_style_applied_ || showing_gainers_ != gainers);
showing_gainers_ = gainers;
- auto active_g = QString("QPushButton { background: %1; color: %2; border: none; "
- "font-size: 9px; font-weight: bold; padding: 4px; }")
- .arg(ui::colors::POSITIVE(), ui::colors::BG_BASE());
- auto active_l = QString("QPushButton { background: %1; color: %2; border: none; "
- "font-size: 9px; font-weight: bold; padding: 4px; }")
- .arg(ui::colors::NEGATIVE(), ui::colors::BG_BASE());
- auto inactive = QString("QPushButton { background: %1; color: %2; border: none; "
- "font-size: 9px; font-weight: bold; padding: 4px; }")
- .arg(ui::colors::BG_SURFACE(), ui::colors::TEXT_TERTIARY());
-
- gainers_btn_->setStyleSheet(gainers ? active_g : inactive);
- losers_btn_->setStyleSheet(gainers ? inactive : active_l);
+ if (tab_style_dirty) {
+ tab_style_applied_ = true;
+ auto active_g = QString("QPushButton { background: %1; color: %2; border: none; "
+ "font-size: 9px; font-weight: bold; padding: 4px; }")
+ .arg(ui::colors::POSITIVE(), ui::colors::BG_BASE());
+ auto active_l = QString("QPushButton { background: %1; color: %2; border: none; "
+ "font-size: 9px; font-weight: bold; padding: 4px; }")
+ .arg(ui::colors::NEGATIVE(), ui::colors::BG_BASE());
+ auto inactive = QString("QPushButton { background: %1; color: %2; border: none; "
+ "font-size: 9px; font-weight: bold; padding: 4px; }")
+ .arg(ui::colors::BG_SURFACE(), ui::colors::TEXT_TERTIARY());
+
+ gainers_btn_->setStyleSheet(gainers ? active_g : inactive);
+ losers_btn_->setStyleSheet(gainers ? inactive : active_l);
+ }
table_->clear_data();
@@ -143,11 +155,21 @@ void TopMoversWidget::show_tab(bool gainers) {
void TopMoversWidget::retranslateUi() {
BaseWidget::retranslateUi();
set_title(tr("TOP MOVERS"));
- if (gainers_btn_)
- gainers_btn_->setText(tr("GAINERS"));
- if (losers_btn_)
- losers_btn_->setText(tr("LOSERS"));
- rebuild_from_cache(); // re-renders table headers in the new language
+ // Keep the ▲ / ▼ glyph prefixes the constructor applied — dropping them
+ // here silently changed the button labels on any language switch.
+ if (gainers_btn_) {
+ gainers_btn_->setText(QString(QChar(0x25B2)) + " " + tr("GAINERS"));
+ gainers_btn_->setAccessibleName(tr("Show top gainers"));
+ }
+ if (losers_btn_) {
+ losers_btn_->setText(QString(QChar(0x25BC)) + " " + tr("LOSERS"));
+ losers_btn_->setAccessibleName(tr("Show top losers"));
+ }
+ // Table headers are set once in the ctor — re-apply them here, which the
+ // old rebuild_from_cache() call never did.
+ if (table_)
+ table_->set_headers({tr("SYMBOL"), tr("PRICE"), tr("CHG%")});
+ rebuild_from_cache();
}
} // namespace fincept::screens::widgets
diff --git a/fincept-qt/src/screens/dashboard/widgets/TopMoversWidget.h b/fincept-qt/src/screens/dashboard/widgets/TopMoversWidget.h
index aac856487..92b6496d1 100644
--- a/fincept-qt/src/screens/dashboard/widgets/TopMoversWidget.h
+++ b/fincept-qt/src/screens/dashboard/widgets/TopMoversWidget.h
@@ -41,6 +41,9 @@ class TopMoversWidget : public BaseWidget {
QPushButton* losers_btn_ = nullptr;
QVector<services::QuoteData> all_quotes_;
bool showing_gainers_ = true;
+ /// Guards the tab-button stylesheet reparse — show_tab() runs on every
+ /// hub delivery but the button CSS only changes with tab/theme.
+ bool tab_style_applied_ = false;
QHash<QString, services::QuoteData> row_cache_;
QStringList symbols_;
diff --git a/fincept-qt/src/screens/dashboard/widgets/WatchlistWidget.cpp b/fincept-qt/src/screens/dashboard/widgets/WatchlistWidget.cpp
index 24b1258e0..ef2635d9c 100644
--- a/fincept-qt/src/screens/dashboard/widgets/WatchlistWidget.cpp
+++ b/fincept-qt/src/screens/dashboard/widgets/WatchlistWidget.cpp
@@ -4,6 +4,7 @@
#include "datahub/DataHubMetaTypes.h"
#include "ui/theme/Theme.h"
+#include <QJsonArray>
#include <QLabel>
namespace fincept::screens::widgets {
@@ -24,23 +25,16 @@ WatchlistWidget::WatchlistWidget(QWidget* parent)
irl->addWidget(symbols_label_);
symbols_input_ = new QLineEdit(symbols_.join(", "));
+ symbols_input_->setAccessibleName(tr("Watchlist symbols"));
+ symbols_input_->setToolTip(tr("Comma-separated symbols, e.g. AAPL, MSFT, BTC-USD"));
irl->addWidget(symbols_input_, 1);
go_btn_ = new QPushButton(tr("GO"));
go_btn_->setFixedWidth(32);
- connect(go_btn_, &QPushButton::clicked, this, [this]() {
- QString text = symbols_input_->text().trimmed().toUpper();
- symbols_.clear();
- for (auto& s : text.split(",")) {
- QString trimmed = s.trimmed();
- if (!trimmed.isEmpty())
- symbols_ << trimmed;
- }
- // Dynamic symbol set: drop any cached rows for symbols no longer
- // tracked, then rewire subscriptions to the new set.
- row_cache_.clear();
- hub_resubscribe();
- });
+ go_btn_->setAccessibleName(tr("Apply watchlist symbols"));
+ connect(go_btn_, &QPushButton::clicked, this, &WatchlistWidget::commit_symbols);
+ // Enter in the symbol box is the same action as clicking GO.
+ connect(symbols_input_, &QLineEdit::returnPressed, this, &WatchlistWidget::commit_symbols);
irl->addWidget(go_btn_);
vl->addWidget(input_row);
@@ -57,6 +51,57 @@ WatchlistWidget::WatchlistWidget(QWidget* parent)
set_loading(true);
}
+void WatchlistWidget::commit_symbols() {
+ const QString text = symbols_input_->text().trimmed().toUpper();
+ QStringList next;
+ for (const QString& s : text.split(',')) {
+ const QString trimmed = s.trimmed();
+ if (!trimmed.isEmpty() && !next.contains(trimmed))
+ next << trimmed;
+ }
+ if (next.isEmpty())
+ return; // refuse to blank the watchlist — keep the previous set
+ if (next == symbols_)
+ return;
+ symbols_ = next;
+ // Dynamic symbol set: drop any cached rows for symbols no longer
+ // tracked, then rewire subscriptions to the new set.
+ row_cache_.clear();
+ table_->clear_data();
+ hub_resubscribe();
+ // Persist through the canvas so the edited list survives a restart.
+ emit config_changed(config());
+}
+
+QJsonObject WatchlistWidget::config() const {
+ QJsonArray arr;
+ for (const auto& s : symbols_)
+ arr.append(s);
+ QJsonObject o;
+ o.insert("symbols", arr);
+ return o;
+}
+
+void WatchlistWidget::apply_config(const QJsonObject& cfg) {
+ QStringList next;
+ const QJsonArray arr = cfg.value("symbols").toArray();
+ for (const auto& v : arr) {
+ const QString s = v.toString().trimmed().toUpper();
+ if (!s.isEmpty() && !next.contains(s))
+ next << s;
+ }
+ if (next.isEmpty() || next == symbols_)
+ return;
+ symbols_ = next;
+ if (symbols_input_)
+ symbols_input_->setText(symbols_.join(", "));
+ row_cache_.clear();
+ if (table_)
+ table_->clear_data();
+ if (isVisible())
+ hub_resubscribe();
+}
+
void WatchlistWidget::apply_styles() {
symbols_label_->setStyleSheet(QString("color: %1; font-size: 9px; font-weight: bold; background: transparent;")
.arg(ui::colors::TEXT_TERTIARY()));
@@ -116,7 +161,8 @@ void WatchlistWidget::hub_resubscribe() {
// Numerator = unique symbols delivered so far; the overlay
// animates the count up and fades out when row_cache_ is full.
set_loading_progress(row_cache_.size(), symbols_.size());
- render_from_cache();
+ // One render per delivery burst, not one per symbol.
+ schedule_render([this]() { render_from_cache(); });
});
}
hub_active_ = true;
@@ -143,19 +189,6 @@ void WatchlistWidget::render_from_cache() {
}
}
-void WatchlistWidget::populate(const QVector<services::QuoteData>& quotes) {
- table_->clear_data();
-
- for (const auto& q : quotes) {
- table_->add_row({q.symbol, QString("$%1").arg(q.price, 0, 'f', 2),
- QString("%1%2").arg(q.change >= 0 ? "+" : "").arg(q.change, 0, 'f', 2),
- QString("%1%2%").arg(q.change_pct >= 0 ? "+" : "").arg(q.change_pct, 0, 'f', 2)});
- int row = table_->rowCount() - 1;
- table_->set_cell_color(row, 2, ui::change_color(q.change_pct));
- table_->set_cell_color(row, 3, ui::change_color(q.change_pct));
- }
-}
-
void WatchlistWidget::retranslateUi() {
BaseWidget::retranslateUi();
set_title(tr("WATCHLIST"));
diff --git a/fincept-qt/src/screens/dashboard/widgets/WatchlistWidget.h b/fincept-qt/src/screens/dashboard/widgets/WatchlistWidget.h
index da259f64f..811abf751 100644
--- a/fincept-qt/src/screens/dashboard/widgets/WatchlistWidget.h
+++ b/fincept-qt/src/screens/dashboard/widgets/WatchlistWidget.h
@@ -17,6 +17,11 @@ class WatchlistWidget : public BaseWidget {
public:
explicit WatchlistWidget(QWidget* parent = nullptr);
+ /// Per-instance config — the user's symbol list. Persisted with the
+ /// dashboard layout so an edited watchlist survives a restart.
+ QJsonObject config() const override;
+ void apply_config(const QJsonObject& cfg) override;
+
protected:
void on_theme_changed() override;
void showEvent(QShowEvent* e) override;
@@ -26,7 +31,8 @@ class WatchlistWidget : public BaseWidget {
private:
void apply_styles();
void refresh_data();
- void populate(const QVector<services::QuoteData>& quotes);
+ /// Parse the input box into `symbols_`, re-wire the hub, and persist.
+ void commit_symbols();
/// (Re)subscribe to the hub for the current `symbols_` set.
void hub_resubscribe();
diff --git a/fincept-qt/src/screens/data_mapping/DataMappingScreen.cpp b/fincept-qt/src/screens/data_mapping/DataMappingScreen.cpp
index 430cd4de4..eb285475e 100644
--- a/fincept-qt/src/screens/data_mapping/DataMappingScreen.cpp
+++ b/fincept-qt/src/screens/data_mapping/DataMappingScreen.cpp
@@ -284,10 +284,12 @@ void DataMappingScreen::retranslateUi() {
if (cache_ttl_)
cache_ttl_->setSuffix(tr(" sec"));
if (encryption_title_)
- encryption_title_->setText(tr("ENCRYPTION"));
+ encryption_title_->setText(tr("CREDENTIAL STORAGE"));
if (encryption_detail_)
- encryption_detail_->setText(tr("API credentials are encrypted with AES-256-GCM before storage.\n"
- "Sensitive data never stored in plaintext."));
+ encryption_detail_->setText(tr("The AUTH VALUE and any credentials placed in HEADERS are saved to the "
+ "local application database on this machine, unencrypted.\n"
+ "Anything running as your user account can read them. Prefer a scoped, "
+ "revocable key over a full-access one."));
// Step 4 — test & save
if (test_save_panel_title_)
@@ -468,8 +470,9 @@ QVariantMap DataMappingScreen::save_state() const {
state["api_base_url"] = api_base_url_->text();
if (api_endpoint_)
state["api_endpoint"] = api_endpoint_->text();
- if (api_auth_value_)
- state["api_auth_value"] = api_auth_value_->text();
+ // SECURITY: api_auth_value_ holds a live bearer token / API key. Screen
+ // state is persisted verbatim, so it is deliberately NOT captured here —
+ // the user re-enters it (or loads a saved mapping) after a restart.
if (api_headers_)
state["api_headers"] = api_headers_->toPlainText();
if (api_body_)
@@ -493,8 +496,8 @@ void DataMappingScreen::restore_state(const QVariantMap& state) {
api_base_url_->setText(state.value("api_base_url").toString());
if (api_endpoint_ && state.contains("api_endpoint"))
api_endpoint_->setText(state.value("api_endpoint").toString());
- if (api_auth_value_ && state.contains("api_auth_value"))
- api_auth_value_->setText(state.value("api_auth_value").toString());
+ // "api_auth_value" is intentionally not restored — see save_state(). Older
+ // states may still carry one; ignoring it also lets that stale copy age out.
if (api_headers_ && state.contains("api_headers"))
api_headers_->setPlainText(state.value("api_headers").toString());
if (api_body_ && state.contains("api_body"))
diff --git a/fincept-qt/src/screens/data_mapping/DataMappingScreen_Layout.cpp b/fincept-qt/src/screens/data_mapping/DataMappingScreen_Layout.cpp
index d73256ed0..4b0a79c44 100644
--- a/fincept-qt/src/screens/data_mapping/DataMappingScreen_Layout.cpp
+++ b/fincept-qt/src/screens/data_mapping/DataMappingScreen_Layout.cpp
@@ -236,12 +236,15 @@ QWidget* DataMappingScreen::create_right_panel() {
il->addSpacing(8);
- // Security
+ // Security. NOTE: DataMappingRepository::save() writes `auth_token` to the
+ // data_mappings SQLite table as plaintext — this panel must not claim
+ // otherwise. See the FEATURE GAPS note about moving it to SecureStorage.
security_title_ = new QLabel(tr("SECURITY"));
security_title_->setObjectName("dmLabel");
il->addWidget(security_title_);
- auto* sec_val = new QLabel("AES-256-GCM"); // crypto standard name — not translated
+ auto* sec_val = new QLabel(tr("LOCAL STORE"));
sec_val->setObjectName("dmInfoValue");
+ sec_val->setToolTip(tr("Mapping credentials are kept in the local application database on this machine."));
il->addWidget(sec_val);
il->addSpacing(8);
@@ -296,22 +299,27 @@ QWidget* DataMappingScreen::create_api_config_panel() {
api_name_ = new QLineEdit;
api_name_->setPlaceholderText(tr("e.g. Upstox OHLCV"));
+ api_name_->setAccessibleName(tr("Mapping name"));
api_name_row_ = create_form_row(tr("MAPPING NAME"), api_name_);
bl->addWidget(api_name_row_);
api_base_url_ = new QLineEdit;
api_base_url_->setPlaceholderText("https://api.example.com");
+ api_base_url_->setAccessibleName(tr("Base URL"));
api_endpoint_ = new QLineEdit;
api_endpoint_->setPlaceholderText("/v2/historical-candle/{symbol}/{interval}");
+ api_endpoint_->setAccessibleName(tr("Endpoint path"));
api_base_url_row_ = create_form_row(tr("BASE URL"), api_base_url_);
api_endpoint_row_ = create_form_row(tr("ENDPOINT"), api_endpoint_);
bl->addWidget(create_form_two_col(api_base_url_row_, api_endpoint_row_));
api_method_ = new QComboBox;
api_method_->addItems({"GET", "POST", "PUT", "DELETE", "PATCH"}); // HTTP verbs — protocol values
+ api_method_->setAccessibleName(tr("HTTP method"));
api_auth_type_ = new QComboBox;
// Auth types are matched by text against template configs — keep untranslated.
api_auth_type_->addItems({"None", "API Key", "Bearer Token", "Basic Auth", "OAuth2"});
+ api_auth_type_->setAccessibleName(tr("Authentication type"));
api_method_row_ = create_form_row(tr("HTTP METHOD"), api_method_);
api_auth_type_row_ = create_form_row(tr("AUTHENTICATION"), api_auth_type_);
bl->addWidget(create_form_two_col(api_method_row_, api_auth_type_row_));
@@ -319,18 +327,23 @@ QWidget* DataMappingScreen::create_api_config_panel() {
api_auth_value_ = new QLineEdit;
api_auth_value_->setPlaceholderText(tr("Token / API Key value"));
api_auth_value_->setEchoMode(QLineEdit::Password);
+ api_auth_value_->setAccessibleName(tr("Auth value (secret)"));
+ api_auth_value_->setToolTip(tr("Saved with the mapping. TEST API REQUEST does not send it — put the key in "
+ "HEADERS or the endpoint query string to exercise an authenticated endpoint."));
api_auth_value_row_ = create_form_row(tr("AUTH VALUE"), api_auth_value_);
bl->addWidget(api_auth_value_row_);
api_headers_ = new QPlainTextEdit;
api_headers_->setPlaceholderText("Content-Type: application/json\nAccept: application/json");
api_headers_->setMaximumHeight(60);
+ api_headers_->setAccessibleName(tr("Request headers, one per line"));
api_headers_row_ = create_form_row(tr("HEADERS (one per line)"), api_headers_);
bl->addWidget(api_headers_row_);
api_body_ = new QPlainTextEdit;
api_body_->setPlaceholderText("{\"symbol\": \"AAPL\"}");
api_body_->setMaximumHeight(60);
+ api_body_->setAccessibleName(tr("Request body (JSON)"));
api_body_row_ = create_form_row(tr("REQUEST BODY (JSON)"), api_body_);
bl->addWidget(api_body_row_);
@@ -338,6 +351,9 @@ QWidget* DataMappingScreen::create_api_config_panel() {
api_timeout_->setRange(1, 120);
api_timeout_->setValue(30);
api_timeout_->setSuffix(tr(" sec"));
+ api_timeout_->setAccessibleName(tr("Request timeout"));
+ api_timeout_->setToolTip(tr("Saved with the mapping. The TEST API REQUEST client currently uses its own "
+ "fixed timeout."));
api_timeout_row_ = create_form_row(tr("TIMEOUT"), api_timeout_);
bl->addWidget(api_timeout_row_);
@@ -348,6 +364,7 @@ QWidget* DataMappingScreen::create_api_config_panel() {
api_test_btn_ = new QPushButton(tr("TEST API REQUEST"));
api_test_btn_->setObjectName("dmCalcBtn");
api_test_btn_->setCursor(Qt::PointingHandCursor);
+ api_test_btn_->setAccessibleName(tr("Send a test request and capture the response shape"));
connect(api_test_btn_, &QPushButton::clicked, this, &DataMappingScreen::on_test_api);
api_test_status_ = new QLabel;
api_test_status_->setObjectName("dmInfoLabel");
@@ -533,16 +550,21 @@ QWidget* DataMappingScreen::create_cache_panel() {
cache_ttl_row_ = create_form_row(tr("CACHE TTL"), cache_ttl_);
bl->addWidget(cache_ttl_row_);
+ // Honest disclosure. The previous copy claimed AES-256-GCM encryption at
+ // rest, which DataMappingRepository does not do — auth_token goes into the
+ // data_mappings table verbatim. Never advertise a control that isn't there.
auto* sec_box = new QWidget(this);
sec_box->setStyleSheet(
- QString("background: rgba(22,163,74,0.05); border: 1px solid %1; padding: 8px;").arg(colors::BORDER_DIM()));
+ QString("background: rgba(217,119,6,0.05); border: 1px solid %1; padding: 8px;").arg(colors::BORDER_DIM()));
auto* sbl = new QVBoxLayout(sec_box);
sbl->setSpacing(4);
- encryption_title_ = new QLabel(tr("ENCRYPTION"));
+ encryption_title_ = new QLabel(tr("CREDENTIAL STORAGE"));
encryption_title_->setObjectName("dmLabel");
sbl->addWidget(encryption_title_);
- encryption_detail_ = new QLabel(tr("API credentials are encrypted with AES-256-GCM before storage.\n"
- "Sensitive data never stored in plaintext."));
+ encryption_detail_ = new QLabel(tr("The AUTH VALUE and any credentials placed in HEADERS are saved to the "
+ "local application database on this machine, unencrypted.\n"
+ "Anything running as your user account can read them. Prefer a scoped, "
+ "revocable key over a full-access one."));
encryption_detail_->setObjectName("dmInfoLabel");
encryption_detail_->setWordWrap(true);
sbl->addWidget(encryption_detail_);
@@ -638,23 +660,32 @@ QWidget* DataMappingScreen::create_list_view() {
list_run_btn_ = new QPushButton(tr("▶ RUN"));
list_run_btn_->setObjectName("dmCalcBtn");
list_run_btn_->setCursor(Qt::PointingHandCursor);
+ list_run_btn_->setEnabled(false); // gated on selection — see refresh_saved_mappings()
+ list_run_btn_->setAccessibleName(tr("Run selected mapping"));
connect(list_run_btn_, &QPushButton::clicked, this, &DataMappingScreen::on_run_mapping);
tbl->addWidget(list_run_btn_);
list_del_btn_ = new QPushButton(tr("DELETE"));
list_del_btn_->setObjectName("dmDestructiveBtn");
list_del_btn_->setCursor(Qt::PointingHandCursor);
+ list_del_btn_->setEnabled(false);
+ list_del_btn_->setAccessibleName(tr("Delete selected mapping"));
connect(list_del_btn_, &QPushButton::clicked, this, &DataMappingScreen::on_delete_mapping);
tbl->addWidget(list_del_btn_);
list_new_btn_ = new QPushButton(tr("+ NEW MAPPING"));
list_new_btn_->setObjectName("dmCalcBtn");
list_new_btn_->setCursor(Qt::PointingHandCursor);
+ list_new_btn_->setAccessibleName(tr("Create a new mapping"));
connect(list_new_btn_, &QPushButton::clicked, this, &DataMappingScreen::on_new_mapping);
tbl->addWidget(list_new_btn_);
vl->addWidget(toolbar);
mapping_list_ = new QListWidget;
+ mapping_list_->setAccessibleName(tr("Saved mappings"));
+ // Selection drives RUN / DELETE; double-click runs (same as the RUN button).
+ connect(mapping_list_, &QListWidget::currentRowChanged, this, [this](int) { refresh_saved_mappings(); });
+ connect(mapping_list_, &QListWidget::itemDoubleClicked, this, [this](QListWidgetItem*) { on_run_mapping(); });
vl->addWidget(mapping_list_, 1);
list_empty_ = new QLabel(tr("No mappings saved yet.\nClick CREATE to build your first data mapping."));
diff --git a/fincept-qt/src/screens/data_mapping/DataMappingScreen_Operations.cpp b/fincept-qt/src/screens/data_mapping/DataMappingScreen_Operations.cpp
index aee66f99a..7c36a4008 100644
--- a/fincept-qt/src/screens/data_mapping/DataMappingScreen_Operations.cpp
+++ b/fincept-qt/src/screens/data_mapping/DataMappingScreen_Operations.cpp
@@ -18,6 +18,7 @@
#include <QJsonDocument>
#include <QJsonObject>
#include <QListWidgetItem>
+#include <QMessageBox>
#include <QUuid>
namespace fincept::screens {
@@ -178,27 +179,57 @@ void DataMappingScreen::on_save_mapping() {
void DataMappingScreen::on_run_mapping() {
const int row = mapping_list_->currentRow();
- if (row < 0 || row >= saved_mappings_.size())
+ if (row < 0 || row >= saved_mappings_.size()) {
+ QMessageBox::information(this, tr("Run Mapping"), tr("Select a saved mapping first."));
return;
+ }
const DataMapping& dm = saved_mappings_[row];
LOG_INFO("DataMapping", "Running mapping: " + dm.name);
+ // Loading state — the fetch is a live network round-trip and RUN used to
+ // give no feedback at all from the list view.
+ if (list_run_btn_) {
+ list_run_btn_->setEnabled(false);
+ list_run_btn_->setText(tr("RUNNING..."));
+ }
+
QPointer<DataMappingScreen> self = this;
fincept::services::DataNormalizationService::instance().fetch_and_normalize(
dm, [self, dm](bool ok, fincept::services::NormalizedRecord rec) {
if (!self)
return;
+ if (self->list_run_btn_) {
+ self->list_run_btn_->setEnabled(true);
+ self->list_run_btn_->setText(DataMappingScreen::tr("▶ RUN"));
+ }
if (ok) {
const QString out = QJsonDocument(rec.normalized).toJson(QJsonDocument::Indented);
self->test_output_->setPlainText(out);
self->test_status_->setText(
DataMappingScreen::tr("RUN OK — %1 fields extracted").arg(rec.normalized.size()));
LOG_INFO("DataMapping", "Run complete: " + dm.name);
+ // test_output_ lives on the CREATE view; a run started from the
+ // list view would otherwise write into a panel nobody can see.
+ QMessageBox box(self);
+ box.setIcon(QMessageBox::Information);
+ box.setWindowTitle(DataMappingScreen::tr("Run: %1").arg(dm.name));
+ box.setText(
+ DataMappingScreen::tr("%n field(s) extracted.", "", static_cast<int>(rec.normalized.size())));
+ box.setDetailedText(out);
+ box.exec();
} else {
- const QString errs = rec.errors.join(", ");
- self->test_status_->setText(DataMappingScreen::tr("RUN FAILED — %1").arg(errs));
+ const QString errs =
+ rec.errors.isEmpty() ? DataMappingScreen::tr("no error detail reported") : rec.errors.join("\n");
+ self->test_status_->setText(DataMappingScreen::tr("RUN FAILED — %1").arg(rec.errors.join(", ")));
LOG_WARN("DataMapping", "Run failed: " + errs);
+ // Surface the actual upstream error, not just "failed".
+ QMessageBox box(self);
+ box.setIcon(QMessageBox::Warning);
+ box.setWindowTitle(DataMappingScreen::tr("Run: %1").arg(dm.name));
+ box.setText(DataMappingScreen::tr("The mapping did not produce a record."));
+ box.setInformativeText(errs);
+ box.exec();
}
});
}
@@ -250,38 +281,87 @@ void DataMappingScreen::on_new_mapping() {
void DataMappingScreen::on_delete_mapping() {
const int row = mapping_list_->currentRow();
- if (row < 0 || row >= saved_mappings_.size())
+ if (row < 0 || row >= saved_mappings_.size()) {
+ QMessageBox::information(this, tr("Delete Mapping"), tr("Select a saved mapping first."));
return;
+ }
const QString id = saved_mappings_[row].id;
+ const QString name = saved_mappings_[row].name;
+
+ // Destructive and irreversible — it was previously a single unguarded click
+ // next to RUN.
+ if (QMessageBox::question(this, tr("Delete Mapping"),
+ tr("Delete the mapping \"%1\"?\n\nThis cannot be undone.").arg(name),
+ QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel) != QMessageBox::Yes)
+ return;
+
auto r = DataMappingRepository::instance().remove(id);
if (r.is_err()) {
- LOG_ERROR("DataMapping", "Failed to delete: " + QString::fromStdString(r.error()));
+ const QString err = QString::fromStdString(r.error());
+ LOG_ERROR("DataMapping", "Failed to delete: " + err);
+ QMessageBox::warning(this, tr("Delete Mapping"), tr("Could not delete \"%1\":\n\n%2").arg(name, err));
return;
}
load_mappings_from_db();
- LOG_INFO("DataMapping", "Mapping deleted");
+ LOG_INFO("DataMapping", "Mapping deleted: " + name);
}
void DataMappingScreen::load_mappings_from_db() {
+ // Keep the caret on the same mapping across a reload (delete/save both
+ // re-enter here and used to reset the selection to nothing).
+ const QString previously_selected =
+ (mapping_list_->currentRow() >= 0 && mapping_list_->currentRow() < saved_mappings_.size())
+ ? saved_mappings_[mapping_list_->currentRow()].id
+ : QString();
+
saved_mappings_.clear();
mapping_list_->clear();
auto r = DataMappingRepository::instance().list_all();
if (r.is_err()) {
- LOG_WARN("DataMapping", "Could not load mappings: " + QString::fromStdString(r.error()));
+ const QString err = QString::fromStdString(r.error());
+ LOG_WARN("DataMapping", "Could not load mappings: " + err);
+ if (list_empty_) {
+ list_empty_->setText(tr("Could not load saved mappings:\n%1").arg(err));
+ list_empty_->setVisible(true);
+ }
+ refresh_saved_mappings();
return;
}
saved_mappings_ = r.value();
- for (const auto& dm : saved_mappings_) {
+ int restore_row = -1;
+ for (int i = 0; i < saved_mappings_.size(); ++i) {
+ const auto& dm = saved_mappings_[i];
mapping_list_->addItem(dm.name + " — " + dm.schema_name);
+ if (!previously_selected.isEmpty() && dm.id == previously_selected)
+ restore_row = i;
}
+ if (restore_row >= 0)
+ mapping_list_->setCurrentRow(restore_row);
if (status_mappings_) {
status_mappings_->setText(tr("Saved: %1").arg(saved_mappings_.size()));
}
+
+ // The empty-state label used to sit permanently under a populated list.
+ if (list_empty_) {
+ list_empty_->setText(tr("No mappings saved yet.\nClick CREATE to build your first data mapping."));
+ list_empty_->setVisible(saved_mappings_.isEmpty());
+ }
+ refresh_saved_mappings();
+}
+
+/// Enable/disable the list-view actions from the current selection.
+void DataMappingScreen::refresh_saved_mappings() {
+ const bool has_selection =
+ mapping_list_ && mapping_list_->currentRow() >= 0 && mapping_list_->currentRow() < saved_mappings_.size();
+ if (list_run_btn_)
+ list_run_btn_->setEnabled(has_selection);
+ if (list_del_btn_)
+ list_del_btn_->setEnabled(has_selection);
}
void DataMappingScreen::build_mapping_config(QJsonObject& config) {
diff --git a/fincept-qt/src/screens/data_sources/ConnectionConfigDialog.cpp b/fincept-qt/src/screens/data_sources/ConnectionConfigDialog.cpp
index 8e3cfcb14..99676bcd3 100644
--- a/fincept-qt/src/screens/data_sources/ConnectionConfigDialog.cpp
+++ b/fincept-qt/src/screens/data_sources/ConnectionConfigDialog.cpp
@@ -26,6 +26,7 @@
#include <QTextEdit>
#include <QUuid>
#include <QVBoxLayout>
+#include <QVector>
namespace fincept::screens::datasources {
@@ -137,7 +138,10 @@ QString show_connection_config_dialog(QWidget* parent, const ConnectorConfig& co
? (duplicate ? QObject::tr("Copy of %1").arg(existing.display_name) : existing.display_name)
: "");
name_edit->setFixedHeight(34);
+ name_edit->setAccessibleName(QObject::tr("Connection name"));
+ name_edit->setAccessibleDescription(QObject::tr("Display name for this %1 connection").arg(config.name));
form->addWidget(name_edit, row, 1);
+ name_lbl->setBuddy(name_edit);
++row;
auto* enabled_lbl = new QLabel(QObject::tr("Enable Connection"));
@@ -146,10 +150,15 @@ QString show_connection_config_dialog(QWidget* parent, const ConnectorConfig& co
auto* enabled_check = new QCheckBox(QObject::tr("Active"));
enabled_check->setChecked(existing_loaded ? existing.enabled : true);
+ enabled_check->setAccessibleName(QObject::tr("Enable connection"));
form->addWidget(enabled_check, row, 1);
++row;
QMap<QString, QWidget*> field_widgets;
+ // Focus chain in visual order — the dialog previously relied on creation
+ // order, which put the footer buttons ahead of the dynamic form fields.
+ QVector<QWidget*> focus_chain{name_edit, enabled_check};
+ bool has_secret_field = false;
for (const auto& field : config.fields) {
auto* lbl = new QLabel(field.label + (field.required ? " *" : ""));
@@ -195,7 +204,22 @@ QString show_connection_config_dialog(QWidget* parent, const ConnectorConfig& co
input = edit;
}
+ if (field.type == FieldType::Password) {
+ has_secret_field = true;
+ input->setAccessibleName(QObject::tr("%1 (secret)").arg(field.label));
+ input->setAccessibleDescription(
+ QObject::tr("Secret value. Stored locally and masked; screen readers will not read it back."));
+ } else {
+ input->setAccessibleName(field.label);
+ if (!field.placeholder.isEmpty())
+ input->setAccessibleDescription(QObject::tr("Example: %1").arg(field.placeholder));
+ }
+ if (field.required)
+ input->setProperty("required", true);
+ lbl->setBuddy(input);
+
field_widgets[field.name] = input;
+ focus_chain.append(input);
form->addWidget(input, row, 1);
++row;
}
@@ -209,6 +233,9 @@ QString show_connection_config_dialog(QWidget* parent, const ConnectorConfig& co
tags_edit->setPlaceholderText(QObject::tr("Comma-separated tags, e.g. prod, live, trading"));
tags_edit->setFixedHeight(34);
tags_edit->setText(existing_loaded ? existing.tags : "");
+ tags_edit->setAccessibleName(QObject::tr("Tags"));
+ tags_lbl->setBuddy(tags_edit);
+ focus_chain.append(tags_edit);
form->addWidget(tags_edit, row, 1);
++row;
@@ -219,6 +246,19 @@ QString show_connection_config_dialog(QWidget* parent, const ConnectorConfig& co
note->setStyleSheet(
QString("color:%1;font-size:11px;font-style:italic;background:transparent;").arg(col::TEXT_TERTIARY()));
body_vl->addWidget(note);
+
+ if (has_secret_field) {
+ // Be explicit about where the secret goes — the connection store is a
+ // local SQLite table, not an encrypted keychain, and EXPORT can carry
+ // these values off the machine.
+ auto* secret_note = new QLabel(
+ QObject::tr("Secrets are saved to the local connection database on this machine. "
+ "EXPORT blanks them out unless you explicitly choose to include them."));
+ secret_note->setWordWrap(true);
+ secret_note->setStyleSheet(
+ QString("color:%1;font-size:11px;background:transparent;").arg(col::WARNING()));
+ body_vl->addWidget(secret_note);
+ }
body_vl->addStretch();
scroll->setWidget(body);
@@ -238,6 +278,7 @@ QString show_connection_config_dialog(QWidget* parent, const ConnectorConfig& co
auto* cancel = new QPushButton(QObject::tr("Cancel"));
cancel->setCursor(Qt::PointingHandCursor);
+ cancel->setAccessibleName(QObject::tr("Cancel")); // QDialog already maps Esc to reject()
cancel->setStyleSheet(QString("QPushButton{background:%1;color:%2;border:1px solid %3;}"
"QPushButton:hover{background:%3;color:%4;}")
.arg(col::BG_BASE(), col::TEXT_SECONDARY(), col::BORDER_MED(), col::TEXT_PRIMARY()));
@@ -247,6 +288,7 @@ QString show_connection_config_dialog(QWidget* parent, const ConnectorConfig& co
save->setCursor(Qt::PointingHandCursor);
save->setDefault(true);
save->setAutoDefault(true);
+ save->setAccessibleName(editing ? QObject::tr("Update connection") : QObject::tr("Save connection"));
save->setStyleSheet(QString("QPushButton{background:rgba(217,119,6,0.12);color:%1;border:1px solid %2;}"
"QPushButton:hover{background:%1;color:%3;}")
.arg(col::AMBER(), col::AMBER_DIM(), col::BG_BASE()));
@@ -254,6 +296,14 @@ QString show_connection_config_dialog(QWidget* parent, const ConnectorConfig& co
root_vl->addWidget(footer);
+ // Explicit tab order: every form field in visual order, then Save, then
+ // Cancel. Without this, Qt walks creation order and jumps from the name
+ // field straight into the footer.
+ focus_chain.append(save);
+ focus_chain.append(cancel);
+ for (int i = 0; i + 1 < focus_chain.size(); ++i)
+ QWidget::setTabOrder(focus_chain[i], focus_chain[i + 1]);
+
name_edit->setFocus();
QObject::connect(cancel, &QPushButton::clicked, &dlg, &QDialog::reject);
@@ -284,6 +334,8 @@ QString show_connection_config_dialog(QWidget* parent, const ConnectorConfig& co
status->setText(QObject::tr("Missing required field: %1").arg(field.label));
status->setStyleSheet(
QString("color:%1;font-size:12px;font-weight:700;background:transparent;").arg(col::NEGATIVE()));
+ if (widget) // put the caret where the problem is instead of just naming it
+ widget->setFocus(Qt::OtherFocusReason);
return;
}
}
diff --git a/fincept-qt/src/screens/data_sources/ConnectionTester.cpp b/fincept-qt/src/screens/data_sources/ConnectionTester.cpp
index 3b1c17fda..9c30aa4a1 100644
--- a/fincept-qt/src/screens/data_sources/ConnectionTester.cpp
+++ b/fincept-qt/src/screens/data_sources/ConnectionTester.cpp
@@ -22,6 +22,7 @@
#include <QStringList>
#include <QTcpSocket>
#include <QUrl>
+#include <QUrlQuery>
#include <QVBoxLayout>
#include <QtConcurrent/QtConcurrent>
@@ -317,6 +318,40 @@ QString provider_probe_url(const QString& provider_id, const QJsonObject& cfg) {
return {};
}
+// Most provider probe URLs above carry the connection's API key in the query
+// string. Everything that reaches a dialog, a tooltip or the log file must go
+// through here first — see P14 ("never log sensitive data").
+QString redact_url(const QString& url) {
+ if (url.isEmpty())
+ return url;
+
+ QUrl u(url);
+ if (!u.isValid() || u.scheme().isEmpty())
+ return url;
+
+ if (!u.userInfo().isEmpty())
+ u.setUserInfo(QStringLiteral("***"));
+
+ const QUrlQuery query(u);
+ if (!query.isEmpty()) {
+ QUrlQuery masked;
+ const auto items = query.queryItems(QUrl::FullyDecoded);
+ for (const auto& item : items) {
+ const QString lower_key = item.first.toLower();
+ const bool is_secret = lower_key.contains(QLatin1String("key")) ||
+ lower_key.contains(QLatin1String("token")) ||
+ lower_key.contains(QLatin1String("secret")) ||
+ lower_key.contains(QLatin1String("pass")) ||
+ lower_key.contains(QLatin1String("auth")) ||
+ lower_key.contains(QLatin1String("sig")) ||
+ lower_key.contains(QLatin1String("credential"));
+ masked.addQueryItem(item.first, (is_secret && !item.second.isEmpty()) ? QStringLiteral("***") : item.second);
+ }
+ u.setQuery(masked);
+ }
+ return u.toString();
+}
+
namespace {
QString simple_dialog_qss() {
@@ -398,8 +433,11 @@ void show_result_dialog(QWidget* parent, const QString& display, bool success, c
void test_connection(QWidget* parent, const QString& conn_id, const TestResultCallback& on_result) {
const auto get_result = DataSourceRepository::instance().get(conn_id);
- if (get_result.is_err())
+ if (get_result.is_err()) {
+ if (on_result)
+ on_result(conn_id, false, QObject::tr("Connection not found: %1").arg(conn_id));
return;
+ }
const auto ds = get_result.value();
const auto cfg_doc = QJsonDocument::fromJson(ds.config.toUtf8());
@@ -407,8 +445,13 @@ void test_connection(QWidget* parent, const QString& conn_id, const TestResultCa
const auto* connector_cfg = find_connector_config(ds.provider);
if (connector_cfg && !connector_cfg->testable) {
- show_message_dialog(parent, QObject::tr("Test: %1").arg(ds.display_name),
- QObject::tr("This connector does not support connectivity testing."));
+ const QString msg = QObject::tr("This connector does not support connectivity testing.");
+ // Always settle the callback, even on the early-exit paths — the caller
+ // puts its TEST button into a "testing..." state before calling us and
+ // relies on the callback to clear it.
+ if (on_result)
+ on_result(conn_id, false, msg);
+ show_message_dialog(parent, QObject::tr("Test: %1").arg(ds.display_name), msg);
return;
}
@@ -547,9 +590,11 @@ void test_connection(QWidget* parent, const QString& conn_id, const TestResultCa
}
if (test_url.isEmpty() && (host.isEmpty() || port <= 0)) {
- show_message_dialog(parent, QObject::tr("Test: %1").arg(display),
- QObject::tr("No testable endpoint found in the saved configuration.\n"
- "Ensure required fields (URL, host, or API key) are filled in."));
+ const QString msg = QObject::tr("No testable endpoint found in the saved configuration.\n"
+ "Ensure required fields (URL, host, or API key) are filled in.");
+ if (on_result)
+ on_result(conn_id, false, msg);
+ show_message_dialog(parent, QObject::tr("Test: %1").arg(display), msg);
return;
}
@@ -577,9 +622,11 @@ void test_connection(QWidget* parent, const QString& conn_id, const TestResultCa
};
if (!captured_test_url.isEmpty()) {
+ // Never surface the raw probe URL — it usually embeds the API key.
+ const QString safe_url = redact_url(captured_test_url);
const QUrl url(captured_test_url);
if (!url.isValid() || url.host().isEmpty()) {
- message = QObject::tr("Invalid URL: %1").arg(captured_test_url);
+ message = QObject::tr("Invalid URL: %1").arg(safe_url);
} else {
const QString url_host = url.host();
const QString scheme = url.scheme().toLower();
@@ -587,7 +634,7 @@ void test_connection(QWidget* parent, const QString& conn_id, const TestResultCa
const int url_port = url.port(default_port);
auto [ok, msg] = tcp_probe(url_host, url_port, 5000);
success = ok;
- message = ok ? QObject::tr("Endpoint reachable: %1").arg(captured_test_url) : msg;
+ message = ok ? QObject::tr("Endpoint reachable: %1").arg(safe_url) : msg;
}
} else if (!captured_host.isEmpty() && captured_port > 0) {
auto [ok, msg] = tcp_probe(captured_host, captured_port, 3000);
diff --git a/fincept-qt/src/screens/data_sources/ConnectionTester.h b/fincept-qt/src/screens/data_sources/ConnectionTester.h
index c24fad812..d9925f9e6 100644
--- a/fincept-qt/src/screens/data_sources/ConnectionTester.h
+++ b/fincept-qt/src/screens/data_sources/ConnectionTester.h
@@ -35,6 +35,16 @@ void test_connection(QWidget* parent, const QString& conn_id, const TestResultCa
/// Provider-specific probe URL synthesis. Exposed for the background poll
/// timer in DataSourcesScreen, which derives host/port without showing a
/// dialog. Returns {} when no HTTP probe is applicable.
+///
+/// SECURITY: the returned URL frequently embeds the connection's API key or
+/// token (that is how most REST health checks authenticate). Never show it in
+/// the UI or write it to the log without passing it through redact_url().
QString provider_probe_url(const QString& provider_id, const QJsonObject& cfg);
+/// Mask credential material in a URL so it is safe to display or log.
+/// Strips any userinfo component and replaces the value of every query
+/// parameter whose key looks like a secret (key / token / secret / password /
+/// auth / sig / credential) with "***". Non-URL input is returned unchanged.
+QString redact_url(const QString& url);
+
} // namespace fincept::screens::datasources
diff --git a/fincept-qt/src/screens/data_sources/DataSourcesScreen.cpp b/fincept-qt/src/screens/data_sources/DataSourcesScreen.cpp
index 4a2ae901d..22beed4bd 100644
--- a/fincept-qt/src/screens/data_sources/DataSourcesScreen.cpp
+++ b/fincept-qt/src/screens/data_sources/DataSourcesScreen.cpp
@@ -58,10 +58,6 @@ namespace {
static const QString TAG = "DataSources";
-static const QStringList kCategoryLabels = {
- "All Connectors", "Databases", "APIs", "Files", "Streaming", "Cloud",
- "Time Series", "Market Data", "Search", "Warehouses", "Alternative Data", "Open Banking"};
-
} // anonymous namespace
// ─────────────────────────────────────────────────────────────────────────────
diff --git a/fincept-qt/src/screens/data_sources/DataSourcesScreen.h b/fincept-qt/src/screens/data_sources/DataSourcesScreen.h
index bc2656429..9f7382d7c 100644
--- a/fincept-qt/src/screens/data_sources/DataSourcesScreen.h
+++ b/fincept-qt/src/screens/data_sources/DataSourcesScreen.h
@@ -70,7 +70,6 @@ class DataSourcesScreen : public QWidget, public fincept::screens::IStatefulScre
void setup_ui();
void apply_screen_styles();
QWidget* build_screen_header();
- QWidget* build_command_bar(); // stub — kept for compat
QWidget* build_stats_strip();
QWidget* build_tab_bar();
QWidget* build_browse_page();
@@ -191,6 +190,10 @@ class DataSourcesScreen : public QWidget, public fincept::screens::IStatefulScre
int stat_filter_ = -1; // -1 = none, 0-3 = stat box index
QString conn_search_text_;
QMap<QString, QPair<bool, QString>> live_status_cache_;
+ // Round-robin cursor into the enabled-connection list so on_poll_timer
+ // probes a bounded slice per tick instead of fanning out one blocking
+ // worker thread per connection.
+ int poll_cursor_ = 0;
};
} // namespace fincept::screens::datasources
diff --git a/fincept-qt/src/screens/data_sources/DataSourcesScreen_Handlers.cpp b/fincept-qt/src/screens/data_sources/DataSourcesScreen_Handlers.cpp
index 3ffe5176c..40ba53b6d 100644
--- a/fincept-qt/src/screens/data_sources/DataSourcesScreen_Handlers.cpp
+++ b/fincept-qt/src/screens/data_sources/DataSourcesScreen_Handlers.cpp
@@ -43,6 +43,7 @@ const QString TAG = "DataSources";
#include <QSplitter>
#include <QStackedWidget>
#include <QStandardPaths>
+#include <QStyle>
#include <QTableWidget>
#include <QTableWidgetItem>
#include <QTimer>
@@ -173,13 +174,30 @@ void DataSourcesScreen::on_connection_enabled_changed(const QString& conn_id, bo
// ── Test connection (thin wrapper — implementation in ConnectionTester.cpp) ──
void DataSourcesScreen::on_connection_test(const QString& conn_id) {
+ if (conn_id.isEmpty())
+ return;
+
+ // Loading state: the probe can block for up to 5s on a dead host, so make
+ // it visible that something is happening instead of leaving a dead button.
+ if (test_connection_btn_) {
+ test_connection_btn_->setEnabled(false);
+ test_connection_btn_->setText(tr("TESTING..."));
+ }
+ if (detail_last_status_value_) {
+ detail_last_status_value_->setText(tr("TESTING"));
+ detail_last_status_value_->setStyleSheet(
+ QString("color:%1;font-size:11px;font-weight:700;background:transparent;").arg(col::WARNING()));
+ }
+
QPointer<DataSourcesScreen> self = this;
test_connection(this, conn_id, [self](const QString& id, bool ok, const QString& msg) {
if (!self)
return;
self->live_status_cache_[id] = {ok, msg};
self->update_connection_status_cell(id, ok, msg);
- self->update_detail_panel();
+ if (self->test_connection_btn_)
+ self->test_connection_btn_->setText(DataSourcesScreen::tr("TEST"));
+ self->update_detail_panel(); // re-enables the button via update_action_states()
});
}
@@ -271,8 +289,11 @@ void DataSourcesScreen::update_connection_status_cell(const QString& conn_id, bo
auto* lbl = qobject_cast<QLabel*>(connections_table_->cellWidget(row, 5));
if (lbl) {
lbl->setText(ok ? tr("OK") : tr("ERR"));
- lbl->setStyleSheet(QString("color:%1;font-size:11px;font-weight:700;background:transparent;")
- .arg(ok ? col::POSITIVE() : col::NEGATIVE()));
+ // Object-name variant, styled once in the screen stylesheet — no
+ // per-update CSS reparse. Re-polish so the new selector applies.
+ lbl->setObjectName(ok ? "dsStatusOk" : "dsStatusErr");
+ lbl->style()->unpolish(lbl);
+ lbl->style()->polish(lbl);
lbl->setToolTip(msg);
}
break;
@@ -316,22 +337,49 @@ void DataSourcesScreen::on_connection_duplicate(const QString& conn_id) {
void DataSourcesScreen::on_bulk_enable_all() {
const auto rows = filtered_connection_rows();
+ int to_change = 0;
+ for (const auto& ds : rows)
+ if (!ds.enabled)
+ ++to_change;
+ if (to_change == 0)
+ return;
+
+ // Enabling a connection puts it into the background reachability poll, i.e.
+ // it starts contacting that provider. Confirm before doing it in bulk.
+ if (QMessageBox::question(this, tr("Enable Connections"),
+ tr("Enable %n listed connection(s)?\n\nEnabled connections are contacted by the "
+ "background reachability check.",
+ "", to_change),
+ QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel) != QMessageBox::Yes)
+ return;
+
for (const auto& ds : rows) {
if (!ds.enabled)
DataSourceRepository::instance().set_enabled(ds.id, true);
}
refresh_connections();
- LOG_INFO(TAG, QString("Bulk-enabled %1 connections").arg(rows.size()));
+ LOG_INFO(TAG, QString("Bulk-enabled %1 connections").arg(to_change));
}
void DataSourcesScreen::on_bulk_disable_all() {
const auto rows = filtered_connection_rows();
+ int to_change = 0;
+ for (const auto& ds : rows)
+ if (ds.enabled)
+ ++to_change;
+ if (to_change == 0)
+ return;
+
+ if (QMessageBox::question(this, tr("Disable Connections"), tr("Disable %n listed connection(s)?", "", to_change),
+ QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel) != QMessageBox::Yes)
+ return;
+
for (const auto& ds : rows) {
if (ds.enabled)
DataSourceRepository::instance().set_enabled(ds.id, false);
}
refresh_connections();
- LOG_INFO(TAG, QString("Bulk-disabled %1 connections").arg(rows.size()));
+ LOG_INFO(TAG, QString("Bulk-disabled %1 connections").arg(to_change));
}
void DataSourcesScreen::on_bulk_delete_selected() {
@@ -389,12 +437,32 @@ void DataSourcesScreen::on_download_template() {
}
void DataSourcesScreen::on_poll_timer() {
+ // Each probe is a blocking 3s TCP connect on a pooled thread. Fanning one
+ // out per enabled connection saturates the global QThreadPool (and hammers
+ // every configured provider) once a user has more than a handful of
+ // connections, so probe a bounded slice per tick and rotate through the
+ // list across ticks.
+ constexpr int kMaxProbesPerTick = 6;
+
+ QVector<DataSource> candidates;
for (const auto& ds : connections_cache_) {
if (!ds.enabled)
continue;
const auto* connector_cfg = find_connector_config(ds.provider);
if (!connector_cfg || !connector_cfg->testable)
continue;
+ candidates.append(ds);
+ }
+ if (candidates.isEmpty()) {
+ poll_cursor_ = 0;
+ return;
+ }
+ if (poll_cursor_ >= candidates.size())
+ poll_cursor_ = 0;
+
+ const int probes = qMin(kMaxProbesPerTick, static_cast<int>(candidates.size()));
+ for (int i = 0; i < probes; ++i) {
+ const auto& ds = candidates[(poll_cursor_ + i) % candidates.size()];
const auto cfg_obj = QJsonDocument::fromJson(ds.config.toUtf8()).object();
const QString probe_url = provider_probe_url(ds.provider, cfg_obj);
@@ -417,7 +485,9 @@ void DataSourcesScreen::on_poll_timer() {
const QString conn_id = ds.id;
const QString cap_host = host;
const int cap_port = port;
- const QString cap_probe = probe_url;
+ // The probe URL usually embeds the API key — redact before it can ever
+ // reach the status tooltip.
+ const QString cap_probe = redact_url(probe_url);
(void)QtConcurrent::run([self, conn_id, cap_host, cap_port, cap_probe]() {
QTcpSocket socket;
@@ -441,6 +511,7 @@ void DataSourcesScreen::on_poll_timer() {
Qt::QueuedConnection);
});
}
+ poll_cursor_ = static_cast<int>((poll_cursor_ + probes) % candidates.size());
}
} // namespace fincept::screens::datasources
diff --git a/fincept-qt/src/screens/data_sources/DataSourcesScreen_Layout.cpp b/fincept-qt/src/screens/data_sources/DataSourcesScreen_Layout.cpp
index bc8a771db..71508a22b 100644
--- a/fincept-qt/src/screens/data_sources/DataSourcesScreen_Layout.cpp
+++ b/fincept-qt/src/screens/data_sources/DataSourcesScreen_Layout.cpp
@@ -135,31 +135,37 @@ QWidget* DataSourcesScreen::build_screen_header() {
search_edit_->setObjectName("dsSearch");
search_edit_->setPlaceholderText(tr("search connectors..."));
search_edit_->setFixedSize(240, 26);
+ search_edit_->setClearButtonEnabled(true);
+ search_edit_->setAccessibleName(tr("Search connectors"));
connect(search_edit_, &QLineEdit::textChanged, this, &DataSourcesScreen::on_search_changed);
hl->addWidget(search_edit_);
hl->addSpacing(12);
// IO buttons (right side)
- auto make_io_btn = [&](const QString& label) -> QPushButton* {
+ auto make_io_btn = [&](const QString& label, const QString& a11y, const QString& tip) -> QPushButton* {
auto* btn = new QPushButton(label);
btn->setObjectName("dsBtn");
btn->setFixedHeight(26);
btn->setCursor(Qt::PointingHandCursor);
+ btn->setAccessibleName(a11y);
+ btn->setToolTip(tip);
return btn;
};
- import_btn_ = make_io_btn(tr("IMPORT"));
+ import_btn_ = make_io_btn(tr("IMPORT"), tr("Import connections"), tr("Load connections from a JSON file"));
connect(import_btn_, &QPushButton::clicked, this, &DataSourcesScreen::on_import_connections);
hl->addWidget(import_btn_);
hl->addSpacing(4);
- export_btn_ = make_io_btn(tr("EXPORT"));
+ export_btn_ = make_io_btn(tr("EXPORT"), tr("Export connections"),
+ tr("Write connections to a JSON file (secrets are redacted by default)"));
connect(export_btn_, &QPushButton::clicked, this, &DataSourcesScreen::on_export_connections);
hl->addWidget(export_btn_);
hl->addSpacing(4);
- tpl_btn_ = make_io_btn(tr("TEMPLATE"));
+ tpl_btn_ = make_io_btn(tr("TEMPLATE"), tr("Download connector template"),
+ tr("Write a blank JSON template containing every connector"));
connect(tpl_btn_, &QPushButton::clicked, this, &DataSourcesScreen::on_download_template);
hl->addWidget(tpl_btn_);
@@ -273,10 +279,10 @@ QWidget* DataSourcesScreen::build_tab_bar() {
hl->addWidget(conns_tab_);
hl->addStretch();
- // Count label
- count_label_ = new QLabel;
- count_label_->setObjectName("dsScreenSubtitle");
- hl->addWidget(count_label_);
+ // NOTE: count_label_ deliberately lives in build_connector_panel(), not
+ // here. This bar used to create its own QLabel and assign it to the same
+ // member, which the connector panel then overwrote — leaving an orphaned,
+ // permanently-blank label in the tab bar.
return bar;
}
@@ -588,6 +594,7 @@ QWidget* DataSourcesScreen::build_detail_panel() {
new_connection_btn_->setFixedHeight(28);
new_connection_btn_->setCursor(Qt::PointingHandCursor);
new_connection_btn_->setEnabled(false);
+ new_connection_btn_->setAccessibleName(tr("Add connection for the selected connector"));
connect(new_connection_btn_, &QPushButton::clicked, this, &DataSourcesScreen::on_connection_add);
act_vl->addWidget(new_connection_btn_);
@@ -599,6 +606,7 @@ QWidget* DataSourcesScreen::build_detail_panel() {
edit_connection_btn_->setFixedHeight(26);
edit_connection_btn_->setCursor(Qt::PointingHandCursor);
edit_connection_btn_->setEnabled(false);
+ edit_connection_btn_->setAccessibleName(tr("Edit selected connection"));
connect(edit_connection_btn_, &QPushButton::clicked, this,
[this]() { on_connection_edit(effective_detail_connection_id()); });
edit_test_hl->addWidget(edit_connection_btn_);
@@ -608,6 +616,8 @@ QWidget* DataSourcesScreen::build_detail_panel() {
test_connection_btn_->setFixedHeight(26);
test_connection_btn_->setCursor(Qt::PointingHandCursor);
test_connection_btn_->setEnabled(false);
+ test_connection_btn_->setAccessibleName(tr("Test selected connection"));
+ test_connection_btn_->setToolTip(tr("Opens a TCP connection to the endpoint. Does not validate API keys."));
connect(test_connection_btn_, &QPushButton::clicked, this,
[this]() { on_connection_test(effective_detail_connection_id()); });
edit_test_hl->addWidget(test_connection_btn_);
@@ -670,16 +680,21 @@ QWidget* DataSourcesScreen::build_connections_page() {
conn_search_edit_->setObjectName("dsSearchConn");
conn_search_edit_->setPlaceholderText(tr("filter connections..."));
conn_search_edit_->setFixedSize(220, 22);
+ conn_search_edit_->setClearButtonEnabled(true);
+ conn_search_edit_->setAccessibleName(tr("Filter saved connections"));
connect(conn_search_edit_, &QLineEdit::textChanged, this, &DataSourcesScreen::on_connections_search_changed);
tb_hl->addWidget(conn_search_edit_);
tb_hl->addStretch();
- // Bulk buttons
+ // Bulk buttons. ENABLE ALL / DISABLE ALL act on the *filtered* rows, not
+ // the whole store — say so, because the labels imply otherwise.
bulk_enable_btn_ = new QPushButton(tr("ENABLE ALL"));
bulk_enable_btn_->setObjectName("dsBtnGreen");
bulk_enable_btn_->setFixedHeight(22);
bulk_enable_btn_->setCursor(Qt::PointingHandCursor);
+ bulk_enable_btn_->setAccessibleName(tr("Enable all listed connections"));
+ bulk_enable_btn_->setToolTip(tr("Enables every connection currently listed (the filter applies)"));
connect(bulk_enable_btn_, &QPushButton::clicked, this, &DataSourcesScreen::on_bulk_enable_all);
tb_hl->addWidget(bulk_enable_btn_);
@@ -687,6 +702,8 @@ QWidget* DataSourcesScreen::build_connections_page() {
bulk_disable_btn_->setObjectName("dsBtn");
bulk_disable_btn_->setFixedHeight(22);
bulk_disable_btn_->setCursor(Qt::PointingHandCursor);
+ bulk_disable_btn_->setAccessibleName(tr("Disable all listed connections"));
+ bulk_disable_btn_->setToolTip(tr("Disables every connection currently listed (the filter applies)"));
connect(bulk_disable_btn_, &QPushButton::clicked, this, &DataSourcesScreen::on_bulk_disable_all);
tb_hl->addWidget(bulk_disable_btn_);
@@ -694,6 +711,7 @@ QWidget* DataSourcesScreen::build_connections_page() {
bulk_delete_btn_->setObjectName("dsBtnDanger");
bulk_delete_btn_->setFixedHeight(22);
bulk_delete_btn_->setCursor(Qt::PointingHandCursor);
+ bulk_delete_btn_->setAccessibleName(tr("Delete selected connections"));
connect(bulk_delete_btn_, &QPushButton::clicked, this, &DataSourcesScreen::on_bulk_delete_selected);
tb_hl->addWidget(bulk_delete_btn_);
@@ -735,22 +753,10 @@ QWidget* DataSourcesScreen::build_connections_page() {
}
// ─────────────────────────────────────────────────────────────────────────────
-// Command bar stub (unused — kept for ABI compat)
-// ─────────────────────────────────────────────────────────────────────────────
-
-QWidget* DataSourcesScreen::build_command_bar() {
- auto* w = new QWidget(this);
- w->setFixedHeight(0);
- return w;
-}
-
-// ─────────────────────────────────────────────────────────────────────────────
-// apply_screen_styles — no-op (styles applied inline in setup_ui)
+// apply_screen_styles — no-op (styles applied once in setup_ui via
+// screen_stylesheet(); kept because it is part of the class's build contract)
// ─────────────────────────────────────────────────────────────────────────────
void DataSourcesScreen::apply_screen_styles() {}
-// ─────────────────────────────────────────────────────────────────────────────
-// Config dialog (thin wrapper — implementation in ConnectionConfigDialog.cpp)
-// ─────────────────────────────────────────────────────────────────────────────
} // namespace fincept::screens::datasources
diff --git a/fincept-qt/src/screens/data_sources/DataSourcesScreen_Tables.cpp b/fincept-qt/src/screens/data_sources/DataSourcesScreen_Tables.cpp
index eebd86a2f..42e6374ad 100644
--- a/fincept-qt/src/screens/data_sources/DataSourcesScreen_Tables.cpp
+++ b/fincept-qt/src/screens/data_sources/DataSourcesScreen_Tables.cpp
@@ -37,6 +37,8 @@
#include <QMessageBox>
#include <QPushButton>
#include <QScrollArea>
+#include <QScrollBar>
+#include <QSet>
#include <QSplitter>
#include <QStackedWidget>
#include <QStandardPaths>
@@ -95,8 +97,27 @@ void DataSourcesScreen::build_connector_table() {
const auto filtered = filtered_connectors();
int preferred_row = -1;
+ // Empty state for the browse grid — a search with no hits used to render a
+ // blank table with no explanation.
+ if (filtered.isEmpty()) {
+ QSignalBlocker blocker(connector_table_);
+ connector_table_->clearSpans();
+ connector_table_->setRowCount(1);
+ auto* msg = make_item(tr("No connectors match the current search or filter."), QColor(col::TEXT_TERTIARY()),
+ Qt::AlignCenter);
+ msg->setFlags(Qt::NoItemFlags);
+ connector_table_->setItem(0, 0, msg);
+ if (connector_table_->columnCount() > 0)
+ connector_table_->setSpan(0, 0, 1, connector_table_->columnCount());
+ if (count_label_)
+ count_label_->setText(QString("0 / %1").arg(ConnectorRegistry::instance().count()));
+ update_detail_panel();
+ return;
+ }
+
{
QSignalBlocker blocker(connector_table_);
+ connector_table_->clearSpans();
connector_table_->setRowCount(filtered.size());
for (int row = 0; row < filtered.size(); ++row) {
@@ -162,7 +183,36 @@ void DataSourcesScreen::build_connections_table() {
const auto rows = filtered_connection_rows();
+ // Preserve what the user had selected and where they were scrolled to —
+ // this is a full teardown/rebuild and both were previously lost on every
+ // refresh (which the 30s poll timer triggers indirectly).
+ QSet<QString> previously_selected;
+ const auto selected_items = connections_table_->selectedItems();
+ for (auto* item : selected_items) {
+ if (item->column() == 1)
+ previously_selected.insert(item->data(Qt::UserRole).toString());
+ }
+ const int scroll_pos =
+ connections_table_->verticalScrollBar() ? connections_table_->verticalScrollBar()->value() : 0;
+
QSignalBlocker blocker(connections_table_);
+
+ // Empty state — the table used to render as a blank grey slab with no hint
+ // about why, whether for "nothing configured" or "filter matched nothing".
+ if (rows.isEmpty()) {
+ connections_table_->clearSpans();
+ connections_table_->setRowCount(1);
+ const bool filtered = !conn_search_text_.trimmed().isEmpty() || stat_filter_ >= 0;
+ auto* msg = make_item(filtered ? tr("No connections match the current filter.")
+ : tr("No connections yet — use + ADD to configure a data source."),
+ QColor(col::TEXT_TERTIARY()), Qt::AlignCenter);
+ msg->setFlags(Qt::NoItemFlags);
+ connections_table_->setItem(0, 0, msg);
+ if (connections_table_->columnCount() > 0)
+ connections_table_->setSpan(0, 0, 1, connections_table_->columnCount());
+ return;
+ }
+ connections_table_->clearSpans();
connections_table_->setRowCount(rows.size());
for (int r = 0; r < rows.size(); ++r) {
@@ -175,6 +225,7 @@ void DataSourcesScreen::build_connections_table() {
toggle->setChecked(ds.enabled);
toggle->setProperty("conn_id", ds.id);
toggle->setCursor(Qt::PointingHandCursor);
+ toggle->setAccessibleName(tr("Enable %1").arg(ds.display_name));
connect(toggle, &QCheckBox::toggled, this,
[this, id = ds.id](bool checked) { on_connection_enabled_changed(id, checked); });
connections_table_->setCellWidget(r, 0, toggle);
@@ -195,16 +246,13 @@ void DataSourcesScreen::build_connections_table() {
connections_table_->setItem(
r, 4, make_item(cfg ? connector_transport(*cfg) : ds.type, QColor(col::TEXT_TERTIARY()), Qt::AlignCenter));
- // Col 5: live status
+ // Col 5: live status — styled by object name (see DataSourcesStyles.h),
+ // not by a per-row setStyleSheet() CSS reparse.
const bool has_status = live_status_cache_.contains(ds.id);
const bool ok = has_status ? live_status_cache_[ds.id].first : false;
auto* status_lbl = new QLabel(has_status ? (ok ? tr("OK") : tr("ERR")) : QStringLiteral("--"));
status_lbl->setAlignment(Qt::AlignCenter);
- status_lbl->setObjectName("dsStatusDot");
- status_lbl->setStyleSheet(QString("color:%1;font-size:11px;font-weight:700;background:transparent;")
- .arg(!has_status ? col::TEXT_TERTIARY()
- : ok ? col::POSITIVE()
- : col::NEGATIVE()));
+ status_lbl->setObjectName(!has_status ? "dsStatusDot" : (ok ? "dsStatusOk" : "dsStatusErr"));
if (has_status)
status_lbl->setToolTip(live_status_cache_[ds.id].second);
connections_table_->setCellWidget(r, 5, status_lbl);
@@ -215,6 +263,20 @@ void DataSourcesScreen::build_connections_table() {
// Col 7: updated_at
connections_table_->setItem(r, 7, make_item(ds.updated_at.left(16), QColor(col::TEXT_TERTIARY())));
}
+
+ // Restore selection + scroll. setRangeSelected() adds to the selection;
+ // selectRow() would clear it, which breaks multi-row restore.
+ if (!previously_selected.isEmpty() && connections_table_->columnCount() > 0) {
+ for (int r = 0; r < connections_table_->rowCount(); ++r) {
+ auto* item = connections_table_->item(r, 1);
+ if (item && previously_selected.contains(item->data(Qt::UserRole).toString())) {
+ connections_table_->setRangeSelected(
+ QTableWidgetSelectionRange(r, 0, r, connections_table_->columnCount() - 1), true);
+ }
+ }
+ }
+ if (connections_table_->verticalScrollBar())
+ connections_table_->verticalScrollBar()->setValue(scroll_pos);
}
void DataSourcesScreen::update_stats_strip() {
diff --git a/fincept-qt/src/screens/data_sources/DataSourcesStyles.h b/fincept-qt/src/screens/data_sources/DataSourcesStyles.h
index 4438b169b..971c7fe27 100644
--- a/fincept-qt/src/screens/data_sources/DataSourcesStyles.h
+++ b/fincept-qt/src/screens/data_sources/DataSourcesStyles.h
@@ -251,7 +251,12 @@ inline const QString& screen_stylesheet() {
border: 1px solid %7; background: %2;
}
#dsEnableToggle::indicator:checked { background: %13; border-color: %13; }
- #dsStatusDot { font-size: 11px; font-weight: 700; background: transparent; }
+ /* Per-row status pill. Object-name variants instead of a per-row
+ setStyleSheet() call — a connections table with N rows used to trigger N
+ full CSS reparses on every refresh. */
+ #dsStatusDot { font-size: 11px; font-weight: 700; background: transparent; color: %8; }
+ #dsStatusOk { font-size: 11px; font-weight: 700; background: transparent; color: %13; }
+ #dsStatusErr { font-size: 11px; font-weight: 700; background: transparent; color: %14; }
/* ── Splitters ── */
#dsBrowseSplitter::handle, #dsConnsSplitter::handle {
diff --git a/fincept-qt/src/screens/data_sources/ImportExportConnections.cpp b/fincept-qt/src/screens/data_sources/ImportExportConnections.cpp
index ac59cb485..aa55cff40 100644
--- a/fincept-qt/src/screens/data_sources/ImportExportConnections.cpp
+++ b/fincept-qt/src/screens/data_sources/ImportExportConnections.cpp
@@ -1,11 +1,18 @@
// ImportExportConnections.cpp — JSON import/export and template dump for
// data-source connections.
+//
+// SECURITY NOTE: a connection's `config` blob holds whatever the connector
+// schema declared — including every FieldType::Password value (DB passwords,
+// API keys, API secrets, private keys, access tokens). Exporting it verbatim
+// writes those secrets to a user-chosen file in plaintext, so export_connections
+// redacts them by default and requires an explicit opt-in to include them.
#include "screens/data_sources/ImportExportConnections.h"
#include "core/logging/Logger.h"
#include "screens/data_sources/ConnectorRegistry.h"
#include "screens/data_sources/DataSourceTypes.h"
+#include "screens/data_sources/DataSourcesHelpers.h"
#include "services/file_manager/FileManagerService.h"
#include "storage/repositories/DataSourceRepository.h"
@@ -18,6 +25,9 @@
#include <QJsonObject>
#include <QJsonParseError>
#include <QMap>
+#include <QMessageBox>
+#include <QPushButton>
+#include <QSet>
#include <QStringList>
#include <QUuid>
@@ -25,21 +35,105 @@ namespace fincept::screens::datasources {
namespace {
constexpr const char* TAG = "DataSources";
+
+/// Keys that are treated as secret when the connector has no registry entry
+/// (imported/unknown providers), matched case-insensitively as substrings.
+bool looks_like_secret_key(const QString& key) {
+ const QString k = key.toLower();
+ return k.contains(QLatin1String("password")) || k.contains(QLatin1String("passwd")) ||
+ k.contains(QLatin1String("secret")) || k.contains(QLatin1String("token")) ||
+ k.contains(QLatin1String("apikey")) || k.contains(QLatin1String("api_key")) ||
+ k.contains(QLatin1String("privatekey")) || k.contains(QLatin1String("private_key")) ||
+ k.contains(QLatin1String("accesskey")) || k.contains(QLatin1String("access_key")) ||
+ k.contains(QLatin1String("credential")) || k.contains(QLatin1String("appkey")) ||
+ k.contains(QLatin1String("connectionstring"));
+}
+
+/// Blank out every secret-bearing value in a connection's config object.
+/// Authoritative source is the connector schema (FieldType::Password); the
+/// name heuristic is the fallback for providers not in the registry.
+/// Returns the number of values that were cleared.
+int redact_config(QJsonObject& cfg, const QString& provider) {
+ QSet<QString> secret_fields;
+ if (const auto* connector = find_connector_config(provider)) {
+ for (const auto& field : connector->fields) {
+ if (field.type == FieldType::Password)
+ secret_fields.insert(field.name);
+ }
+ }
+
+ int cleared = 0;
+ const QStringList keys = cfg.keys();
+ for (const QString& key : keys) {
+ if (!secret_fields.contains(key) && !looks_like_secret_key(key))
+ continue;
+ if (!cfg.value(key).isString() || cfg.value(key).toString().isEmpty())
+ continue;
+ cfg[key] = QString();
+ ++cleared;
+ }
+ return cleared;
+}
+
+/// Count the secret-bearing values a connection would leak if exported raw.
+int count_secrets(const QJsonObject& cfg, const QString& provider) {
+ QJsonObject copy = cfg;
+ return redact_config(copy, provider);
+}
+
} // namespace
bool export_connections(QWidget* parent) {
+ const auto all = DataSourceRepository::instance().list_all();
+ if (all.is_err()) {
+ QMessageBox::warning(parent, QObject::tr("Export Connections"),
+ QObject::tr("Could not read the connection store: %1")
+ .arg(QString::fromStdString(all.error())));
+ return false;
+ }
+
+ // How much credential material is actually at risk? Say so explicitly
+ // rather than silently writing keys to a file the user may share.
+ int secret_count = 0;
+ for (const auto& ds : all.value())
+ secret_count += count_secrets(QJsonDocument::fromJson(ds.config.toUtf8()).object(), ds.provider);
+
+ bool include_secrets = false;
+ if (secret_count > 0) {
+ QMessageBox box(parent);
+ box.setIcon(QMessageBox::Warning);
+ box.setWindowTitle(QObject::tr("Export Connections"));
+ box.setText(QObject::tr("%n stored secret(s) (passwords, API keys, tokens) are attached to these connections.",
+ "", secret_count));
+ box.setInformativeText(
+ QObject::tr("The export file is plain, unencrypted JSON. Anyone who opens it — or any tool that "
+ "reads your files — sees whatever it contains.\n\n"
+ "Redacted: connection settings are exported, secret values are blanked out and must "
+ "be re-entered after import.\n"
+ "With secrets: the file contains your live credentials."));
+ auto* redacted_btn = box.addButton(QObject::tr("Export Redacted"), QMessageBox::AcceptRole);
+ auto* raw_btn = box.addButton(QObject::tr("Include Secrets"), QMessageBox::DestructiveRole);
+ auto* cancel_btn = box.addButton(QMessageBox::Cancel);
+ box.setDefaultButton(redacted_btn);
+ box.exec();
+ if (box.clickedButton() == cancel_btn)
+ return false;
+ include_secrets = (box.clickedButton() == raw_btn);
+ }
+
const QString path =
QFileDialog::getSaveFileName(parent, QObject::tr("Export Connections"), "fincept_connections.json",
QObject::tr("JSON Files (*.json);;All Files (*)"));
if (path.isEmpty())
return false;
- const auto all = DataSourceRepository::instance().list_all();
- if (all.is_err())
- return false;
-
QJsonArray arr;
+ int redacted_total = 0;
for (const auto& ds : all.value()) {
+ QJsonObject config_obj = QJsonDocument::fromJson(ds.config.toUtf8()).object();
+ if (!include_secrets)
+ redacted_total += redact_config(config_obj, ds.provider);
+
QJsonObject obj;
obj["id"] = ds.id;
obj["alias"] = ds.alias;
@@ -48,24 +142,47 @@ bool export_connections(QWidget* parent) {
obj["type"] = ds.type;
obj["provider"] = ds.provider;
obj["category"] = ds.category;
- obj["config"] = QJsonDocument::fromJson(ds.config.toUtf8()).object();
+ obj["config"] = config_obj;
obj["enabled"] = ds.enabled;
obj["tags"] = ds.tags;
obj["created_at"] = ds.created_at;
obj["updated_at"] = ds.updated_at;
+ obj["secrets_redacted"] = !include_secrets;
arr.append(obj);
}
QFile file(path);
if (!file.open(QIODevice::WriteOnly)) {
LOG_ERROR(TAG, QString("Export failed: cannot write to %1").arg(path));
+ QMessageBox::warning(parent, QObject::tr("Export Connections"),
+ QObject::tr("Could not write to:\n%1\n\n%2").arg(path, file.errorString()));
return false;
}
file.write(QJsonDocument(arr).toJson(QJsonDocument::Indented));
file.close();
- LOG_INFO(TAG, QString("Exported %1 connections to %2").arg(arr.size()).arg(path));
+ LOG_INFO(TAG, QString("Exported %1 connections to %2 (%3)")
+ .arg(arr.size())
+ .arg(path)
+ .arg(include_secrets ? "secrets included" : "secrets redacted"));
- services::FileManagerService::instance().import_file(path, "data_sources");
+ // Only index a redacted export in the file manager. A credential-bearing
+ // file must not become discoverable through the file browser or the MCP
+ // file tools that read from the same index.
+ if (!include_secrets)
+ services::FileManagerService::instance().import_file(path, "data_sources");
+
+ QMessageBox::information(
+ parent, QObject::tr("Export Connections"),
+ include_secrets
+ ? QObject::tr("Exported %n connection(s) INCLUDING plaintext secrets to:\n%1\n\n"
+ "Treat this file as a credential file — do not share or sync it.",
+ "", static_cast<int>(arr.size()))
+ .arg(path)
+ : QObject::tr("Exported %n connection(s) to:\n%1\n\n%2 secret value(s) were blanked out and must be "
+ "re-entered after import.",
+ "", static_cast<int>(arr.size()))
+ .arg(path)
+ .arg(redacted_total));
return true;
}
@@ -78,18 +195,43 @@ bool import_connections(QWidget* parent, int* imported_out, int* skipped_out) {
QFile file(path);
if (!file.open(QIODevice::ReadOnly)) {
LOG_ERROR(TAG, QString("Import failed: cannot open %1").arg(path));
+ QMessageBox::warning(parent, QObject::tr("Import Connections"),
+ QObject::tr("Could not open:\n%1\n\n%2").arg(path, file.errorString()));
return false;
}
const QByteArray payload = file.readAll();
+ file.close();
+
QJsonParseError parse_err;
const auto doc = QJsonDocument::fromJson(payload, &parse_err);
if (parse_err.error != QJsonParseError::NoError || !doc.isArray()) {
LOG_ERROR(TAG, QString("Import failed: invalid JSON — %1").arg(parse_err.errorString()));
+ // Surface the parser's own message + offset, not a generic "failed".
+ QMessageBox::warning(parent, QObject::tr("Import Connections"),
+ parse_err.error != QJsonParseError::NoError
+ ? QObject::tr("The file is not valid JSON.\n\n%1 (at offset %2)")
+ .arg(parse_err.errorString())
+ .arg(parse_err.offset)
+ : QObject::tr("The file must contain a JSON array of connections."));
return false;
}
- int imported = 0, skipped = 0;
- for (const auto& val : doc.array()) {
+ // An imported connection can point a connector at an arbitrary host and be
+ // marked enabled, which the background reachability poll will then contact.
+ // Ask before writing anything.
+ const auto entries = doc.array();
+ if (QMessageBox::question(parent, QObject::tr("Import Connections"),
+ QObject::tr("Import %n connection(s) from:\n%1\n\n"
+ "Only import files you created or trust — an imported connection can "
+ "point a connector at any host.",
+ "", static_cast<int>(entries.size()))
+ .arg(path),
+ QMessageBox::Yes | QMessageBox::Cancel,
+ QMessageBox::Cancel) != QMessageBox::Yes)
+ return false;
+
+ int imported = 0, skipped = 0, needs_secrets = 0;
+ for (const auto& val : entries) {
const auto obj = val.toObject();
const QString provider = obj["provider"].toString();
if (provider.isEmpty()) {
@@ -109,6 +251,9 @@ bool import_connections(QWidget* parent, int* imported_out, int* skipped_out) {
ds.enabled = obj["enabled"].toBool(false);
ds.tags = obj["tags"].toString();
+ if (obj.value("secrets_redacted").toBool(false))
+ ++needs_secrets;
+
if (ds.display_name.isEmpty())
ds.display_name = provider;
if (ds.alias.isEmpty())
@@ -124,6 +269,13 @@ bool import_connections(QWidget* parent, int* imported_out, int* skipped_out) {
LOG_INFO(TAG, QString("Import complete: %1 imported, %2 skipped").arg(imported).arg(skipped));
services::FileManagerService::instance().import_file(path, "data_sources");
+ QString summary = QObject::tr("Imported %1 connection(s), skipped %2.").arg(imported).arg(skipped);
+ if (needs_secrets > 0)
+ summary += QObject::tr("\n\n%1 of them came from a redacted export — open each one and re-enter its "
+ "password / API key before use.")
+ .arg(needs_secrets);
+ QMessageBox::information(parent, QObject::tr("Import Connections"), summary);
+
if (imported_out)
*imported_out = imported;
if (skipped_out)
@@ -144,6 +296,13 @@ bool download_connector_template(QWidget* parent) {
for (const auto& cfg : all) {
QJsonObject config_obj;
for (const auto& field : cfg.fields) {
+ // Never seed a secret field with a placeholder that looks like a
+ // real value — leave it empty so the template can't be mistaken
+ // for a filled-in credential file.
+ if (field.type == FieldType::Password) {
+ config_obj[field.name] = QString();
+ continue;
+ }
QString val = !field.default_value.isEmpty() ? field.default_value
: (!field.placeholder.isEmpty() ? field.placeholder : "");
config_obj[field.name] = val;
@@ -184,6 +343,8 @@ bool download_connector_template(QWidget* parent) {
QFile file(path);
if (!file.open(QIODevice::WriteOnly)) {
LOG_ERROR(TAG, QString("Template write failed: %1").arg(path));
+ QMessageBox::warning(parent, QObject::tr("Save Connector Template"),
+ QObject::tr("Could not write to:\n%1\n\n%2").arg(path, file.errorString()));
return false;
}
file.write(QJsonDocument(out).toJson(QJsonDocument::Indented));
diff --git a/fincept-qt/src/screens/dbnomics/DBnomicsChartWidget.cpp b/fincept-qt/src/screens/dbnomics/DBnomicsChartWidget.cpp
index a7a0cf4cf..10a38640c 100644
--- a/fincept-qt/src/screens/dbnomics/DBnomicsChartWidget.cpp
+++ b/fincept-qt/src/screens/dbnomics/DBnomicsChartWidget.cpp
@@ -8,6 +8,7 @@
#include <QBarCategoryAxis>
#include <QBarSeries>
#include <QBarSet>
+#include <QCategoryAxis>
#include <QChart>
#include <QChartView>
#include <QLabel>
@@ -22,6 +23,7 @@
#include <QValueAxis>
#include <algorithm>
+#include <cmath>
#include <limits>
namespace fincept::screens {
@@ -40,14 +42,35 @@ static QValueAxis* make_y_axis(double y_min, double y_max, int tick_count) {
return ax;
}
-static QValueAxis* make_x_axis(int count) {
- auto* ax = new QValueAxis();
- ax->setRange(0, std::max(1, count - 1));
- ax->setTickCount(std::min(8, std::max(2, count)));
+// X axis for an index-addressed period series.
+//
+// Previously this was a plain QValueAxis with labelFormat "%d", so a macro time
+// series was labelled 0, 12, 24, 36 … — the observation *index*, not the date.
+// QCategoryAxis (a QValueAxis subclass, so the existing resize handling still
+// applies) lets us keep the 0..N-1 point coordinates while printing the real
+// period string at a subset of tick positions.
+static QValueAxis* make_x_axis(const QVector<QString>& periods, int tick_count) {
+ auto* ax = new QCategoryAxis();
+ ax->setLabelsPosition(QCategoryAxis::AxisLabelsPositionOnValue);
+ const int n = periods.size();
+ // Half-step padding keeps the first labelled category from being
+ // zero-width (QCategoryAxis measures each category from the previous end).
+ ax->setRange(-0.5, std::max(0.5, n - 0.5));
+ ax->setStartValue(-0.5);
+
+ const int ticks = std::max(2, std::min(tick_count, n));
+ int last_idx = -1;
+ for (int t = 0; t < ticks; ++t) {
+ const int idx = (ticks == 1 || n == 1) ? 0 : (t * (n - 1)) / (ticks - 1);
+ if (idx == last_idx)
+ continue; // QCategoryAxis rejects duplicate category end values
+ last_idx = idx;
+ ax->append(periods[idx], idx);
+ }
+
ax->setLabelsColor(QColor(ui::colors::TEXT_TERTIARY()));
ax->setGridLineColor(QColor(ui::colors::BORDER_DIM()));
ax->setLinePen(QPen(QColor(ui::colors::BORDER_MED())));
- ax->setLabelFormat("%d");
ax->setMinorTickCount(0);
return ax;
}
@@ -156,8 +179,13 @@ void DBnomicsChartWidget::clear() {
QChart* chart = chart_view_->chart();
chart->removeAllSeries();
const auto axes = chart->axes();
- for (auto* axis : axes)
+ for (auto* axis : axes) {
+ // QChart::removeAxis() hands ownership back to the caller — without a
+ // delete every axis built by set_data() leaked on each re-render.
+ // deleteLater() (P13) keeps us off the current call stack.
chart->removeAxis(axis);
+ axis->deleteLater();
+ }
chart->setTitle(tr("NO DATA — SELECT A SERIES FROM THE LEFT PANEL"));
showing_placeholder_ = true;
}
@@ -244,8 +272,7 @@ void DBnomicsChartWidget::render_line_area(const QVector<services::DbnDataPoint>
return;
// ── Create axes first, add to chart, then attach series ──────────────────
- auto* x_axis = make_x_axis(all_periods.size());
- x_axis->setTickCount(x_tick_count(all_periods.size()));
+ auto* x_axis = make_x_axis(all_periods, x_tick_count(all_periods.size()));
chart->addAxis(x_axis, Qt::AlignBottom);
// Scan all data to determine y range before creating y_axis
@@ -325,6 +352,28 @@ void DBnomicsChartWidget::render_bar(const QVector<services::DbnDataPoint>& seri
if (periods.isEmpty())
return;
+ // Explicit Y range computed from the *valid* observations only, so the NaN
+ // gap markers below can never poison the auto-domain.
+ double y_min = 0.0; // bars are measured from zero
+ double y_max = 0.0;
+ bool any = false;
+ for (const auto& dp : series) {
+ for (const auto& obs : dp.observations) {
+ if (!obs.valid || !periods.contains(obs.period))
+ continue;
+ y_min = any ? std::min(y_min, obs.value) : std::min(0.0, obs.value);
+ y_max = any ? std::max(y_max, obs.value) : std::max(0.0, obs.value);
+ any = true;
+ }
+ }
+ if (!any) {
+ y_min = 0.0;
+ y_max = 1.0;
+ }
+ double bar_margin = (y_max - y_min) * 0.1;
+ if (bar_margin == 0.0)
+ bar_margin = std::abs(y_max) * 0.1 + 1.0;
+
auto* bar_series = new QBarSeries();
for (const auto& dp : series) {
auto* bar_set = new QBarSet(dp.series_name);
@@ -333,8 +382,12 @@ void DBnomicsChartWidget::render_bar(const QVector<services::DbnDataPoint>& seri
for (const auto& obs : dp.observations)
if (obs.valid)
pv[obs.period] = obs.value;
- for (const auto& p : periods)
- *bar_set << (pv.contains(p) ? pv[p] : 0.0);
+ for (const auto& p : periods) {
+ // A period this series does not report is a GAP, not a zero.
+ // Zero-filling made every missing observation look like a real
+ // "0" reading — catastrophic for levels series (GDP, debt, CPI).
+ *bar_set << (pv.contains(p) ? pv[p] : std::numeric_limits<double>::quiet_NaN());
+ }
bar_series->append(bar_set);
}
chart->addSeries(bar_series);
@@ -349,12 +402,7 @@ void DBnomicsChartWidget::render_bar(const QVector<services::DbnDataPoint>& seri
chart->addAxis(x_axis, Qt::AlignBottom);
bar_series->attachAxis(x_axis);
- auto* y_axis = new QValueAxis();
- y_axis->setLabelsColor(QColor(ui::colors::TEXT_TERTIARY()));
- y_axis->setGridLineColor(QColor(ui::colors::BORDER_DIM()));
- y_axis->setLabelFormat("%.4g");
- y_axis->setTickCount(y_tick_count());
- y_axis->setMinorTickCount(0);
+ auto* y_axis = make_y_axis(y_min - (y_min < 0.0 ? bar_margin : 0.0), y_max + bar_margin, y_tick_count());
chart->addAxis(y_axis, Qt::AlignLeft);
bar_series->attachAxis(y_axis);
}
@@ -376,8 +424,7 @@ void DBnomicsChartWidget::render_scatter(const QVector<services::DbnDataPoint>&
return;
// ── Create axes first ─────────────────────────────────────────────────────
- auto* x_axis = make_x_axis(periods.size());
- x_axis->setTickCount(x_tick_count(periods.size()));
+ auto* x_axis = make_x_axis(periods, x_tick_count(periods.size()));
chart->addAxis(x_axis, Qt::AlignBottom);
// Scan y range
diff --git a/fincept-qt/src/screens/dbnomics/DBnomicsDataTable.cpp b/fincept-qt/src/screens/dbnomics/DBnomicsDataTable.cpp
index 5fce2ee23..28cafd421 100644
--- a/fincept-qt/src/screens/dbnomics/DBnomicsDataTable.cpp
+++ b/fincept-qt/src/screens/dbnomics/DBnomicsDataTable.cpp
@@ -12,8 +12,14 @@
#include <QVBoxLayout>
#include <algorithm>
+#include <cmath>
namespace fincept::screens {
+namespace {
+/// Most-recent periods rendered in the observation table. The chart still
+/// plots the whole series; only this preview grid is capped.
+constexpr int kMaxRows = 50;
+} // namespace
DBnomicsDataTable::DBnomicsDataTable(QWidget* parent) : QWidget(parent) {
build_ui();
@@ -128,6 +134,8 @@ void DBnomicsDataTable::set_loading(bool on) {
}
void DBnomicsDataTable::clear() {
+ if (header_label_)
+ header_label_->setText(tr("OBSERVATION DATA"));
table_->clear();
table_->setRowCount(1);
table_->setColumnCount(1);
@@ -157,8 +165,19 @@ void DBnomicsDataTable::set_data(const QVector<services::DbnDataPoint>& series)
}
QVector<QString> periods(period_set.begin(), period_set.end());
std::sort(periods.begin(), periods.end(), std::greater<QString>());
- if (periods.size() > 50)
- periods.resize(50);
+ const int total_periods = static_cast<int>(periods.size());
+ if (total_periods > kMaxRows)
+ periods.resize(kMaxRows);
+ const int shown_periods = static_cast<int>(periods.size());
+ // Be explicit that the table is truncated — it silently showed only the
+ // 50 most recent periods with no indication the series went further back.
+ if (header_label_) {
+ header_label_->setText(total_periods > shown_periods
+ ? tr("OBSERVATION DATA — LATEST %1 OF %2 PERIODS")
+ .arg(shown_periods)
+ .arg(total_periods)
+ : tr("OBSERVATION DATA — %1 PERIODS").arg(total_periods));
+ }
// Columns: Period + one per series
const int col_count = 1 + series.size();
@@ -201,8 +220,21 @@ void DBnomicsDataTable::set_data(const QVector<services::DbnDataPoint>& series)
for (int s = 0; s < series.size(); ++s) {
QTableWidgetItem* cell;
if (lookups[s].contains(period) && lookups[s][period].valid) {
- cell = new QTableWidgetItem(QString::number(lookups[s][period].value, 'f', 4));
- cell->setForeground(QColor("#00E5FF")); // cyan for valid data
+ const double v = lookups[s][period].value;
+ // Fixed 4-decimals mangled both ends of the range: a levels
+ // series (GDP) got 4 pointless zeros, and anything below 1e-4
+ // (rates in decimal form, small indices) collapsed to "0.0000".
+ QString txt;
+ if (v == std::floor(v) && std::abs(v) < 1e15)
+ txt = QString::number(static_cast<qint64>(v));
+ else if (std::abs(v) >= 1e-4)
+ txt = QString::number(v, 'f', 4);
+ else
+ txt = QString::number(v, 'g', 6);
+ cell = new QTableWidgetItem(txt);
+ // Theme token, not a hard-coded hex — the old #00E5FF was
+ // invisible against a light theme background.
+ cell->setForeground(QColor(ui::colors::CYAN()));
} else {
cell = new QTableWidgetItem("—");
cell->setForeground(QColor(ui::colors::TEXT_TERTIARY()));
diff --git a/fincept-qt/src/screens/dbnomics/DBnomicsScreen.cpp b/fincept-qt/src/screens/dbnomics/DBnomicsScreen.cpp
index 9ca675569..2200a8b38 100644
--- a/fincept-qt/src/screens/dbnomics/DBnomicsScreen.cpp
+++ b/fincept-qt/src/screens/dbnomics/DBnomicsScreen.cpp
@@ -25,6 +25,7 @@
#include <QVBoxLayout>
#include <algorithm>
+#include <utility>
namespace fincept::screens {
@@ -67,6 +68,16 @@ DBnomicsScreen::DBnomicsScreen(QWidget* parent) : QWidget(parent) {
selection_panel_->selected_dataset(), {}, offset);
});
+ // The global-search "LOAD MORE" button emitted this signal but nothing was
+ // listening — paging past the first 50 search hits was impossible.
+ connect(selection_panel_, &DBnomicsSelectionPanel::load_more_search_requested, this, [this](int offset) {
+ const QString q = selection_panel_->global_search_text().trimmed();
+ if (q.isEmpty())
+ return;
+ selection_panel_->set_search_loading(true);
+ services::DBnomicsService::instance().global_search(q, offset);
+ });
+
connect(selection_panel_, &DBnomicsSelectionPanel::add_to_single_view_clicked, this,
&DBnomicsScreen::on_add_to_single_view);
connect(selection_panel_, &DBnomicsSelectionPanel::clear_all_clicked, this, &DBnomicsScreen::on_clear_all);
@@ -310,7 +321,18 @@ void DBnomicsScreen::build_ui() {
.arg(ui::fonts::DATA_FAMILY));
stats_label_->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ // Source attribution — an economics screen must say where its numbers come
+ // from and under what terms.
+ attribution_label_ = new QLabel(tr("Source: DBnomics (db.nomics.world) — aggregated public data, "
+ "terms per originating provider"),
+ status_bar);
+ attribution_label_->setStyleSheet(QString("color:%1; font-family:%2; font-size:10px;")
+ .arg(ui::colors::TEXT_DIM())
+ .arg(ui::fonts::DATA_FAMILY));
+
status_hl->addWidget(status_label_);
+ status_hl->addSpacing(14);
+ status_hl->addWidget(attribution_label_);
status_hl->addStretch();
status_hl->addWidget(stats_label_);
@@ -402,6 +424,9 @@ void DBnomicsScreen::retranslateUi() {
compare_btn_->setText(tr("COMPARE"));
if (chart_type_label_)
chart_type_label_->setText(tr("CHART:"));
+ if (attribution_label_)
+ attribution_label_->setText(tr("Source: DBnomics (db.nomics.world) — aggregated public data, "
+ "terms per originating provider"));
// Chart-type combo — setItemText preserves the current selection/index.
if (chart_type_combo_ && chart_type_combo_->count() >= 4) {
@@ -493,15 +518,33 @@ void DBnomicsScreen::on_observations_loaded(const services::DbnDataPoint& point)
chart_widget_->set_loading(false);
data_table_->set_loading(false);
- // Check if this series is already in single_series_
+ // Update every place this series is already shown — single view AND any
+ // comparison slot (slots used to be skipped, so REFRESH silently left
+ // stale numbers on screen in COMPARE mode).
+ bool in_view = false;
for (auto& s : single_series_) {
if (s.series_id == point.series_id) {
s.observations = point.observations;
s.series_name = point.series_name;
- render_single_view();
- return;
+ in_view = true;
}
}
+ bool in_slot = false;
+ for (auto& slot : slots_) {
+ for (auto& s : slot.series) {
+ if (s.series_id == point.series_id) {
+ s.observations = point.observations;
+ s.series_name = point.series_name;
+ in_slot = true;
+ }
+ }
+ }
+ if (in_view)
+ render_single_view();
+ if (in_slot)
+ rebuild_comparison_view();
+ if (in_view || in_slot)
+ return;
// Not yet in view — prompt user
set_status(tr("Loaded: %1 • Click ADD TO SINGLE VIEW").arg(point.series_name));
@@ -536,20 +579,53 @@ void DBnomicsScreen::on_fetch_clicked() {
}
void DBnomicsScreen::on_refresh_clicked() {
- if (single_series_.isEmpty())
- return;
-
- for (const auto& s : std::as_const(single_series_)) {
+ // Refresh every loaded series, in BOTH views — comparison slots used to be
+ // ignored entirely, so REFRESH looked like a no-op in COMPARE mode.
+ QSet<QString> seen;
+ int n = 0;
+ auto refresh_one = [&](const services::DbnDataPoint& s) {
+ if (seen.contains(s.series_id))
+ return;
+ seen.insert(s.series_id);
// series_id format: "PROV/DS/CODE"
const QStringList parts = s.series_id.split('/');
- if (parts.size() == 3)
+ if (parts.size() == 3) {
services::DBnomicsService::instance().fetch_observations(parts[0], parts[1], parts[2]);
+ ++n;
+ }
+ };
+
+ for (const auto& s : std::as_const(single_series_))
+ refresh_one(s);
+ for (const auto& slot : std::as_const(slots_))
+ for (const auto& s : slot.series)
+ refresh_one(s);
+
+ if (n == 0) {
+ set_status(tr("Nothing to refresh — add a series first"));
+ return;
}
- set_status(tr("Refreshing series data..."));
+ set_status(tr("Refreshing %1 series…").arg(n));
}
void DBnomicsScreen::on_export_csv() {
- if (single_series_.isEmpty()) {
+ // Export whatever the user is actually looking at. Previously COMPARE mode
+ // always reported "No data to export" even with every slot populated,
+ // because only single_series_ was ever considered.
+ QVector<services::DbnDataPoint> export_series;
+ if (view_mode_ == services::DbnViewMode::Comparison) {
+ for (int i = 0; i < slots_.size(); ++i) {
+ for (const auto& s : std::as_const(slots_[i].series)) {
+ services::DbnDataPoint copy = s;
+ copy.series_name = tr("Slot %1: %2").arg(i + 1).arg(s.series_name);
+ export_series.append(copy);
+ }
+ }
+ } else {
+ export_series = single_series_;
+ }
+
+ if (export_series.isEmpty()) {
set_status(tr("No data to export"));
return;
}
@@ -570,12 +646,13 @@ void DBnomicsScreen::on_export_csv() {
}
QTextStream out(&file);
+ out.setEncoding(QStringConverter::Utf8);
// Collect all unique periods in order (use the first series as the period reference,
// then union with others for completeness)
QVector<QString> periods;
QSet<QString> seen_periods;
- for (const auto& series : std::as_const(single_series_)) {
+ for (const auto& series : std::as_const(export_series)) {
for (const auto& obs : series.observations) {
if (!seen_periods.contains(obs.period)) {
seen_periods.insert(obs.period);
@@ -585,28 +662,42 @@ void DBnomicsScreen::on_export_csv() {
}
std::sort(periods.begin(), periods.end());
+ auto csv_quote = [](QString v) {
+ if (v.contains(',') || v.contains('"') || v.contains('\n'))
+ v = "\"" + v.replace("\"", "\"\"") + "\"";
+ return v;
+ };
+
+ // Provenance banner — a macro export without its source and series ids is
+ // not reproducible.
+ out << "# source=DBnomics (https://db.nomics.world) exported="
+ << QDateTime::currentDateTimeUtc().toString(Qt::ISODate) << "\n";
+ out << "# series=";
+ for (int i = 0; i < export_series.size(); ++i)
+ out << (i ? "|" : "") << export_series[i].series_id;
+ out << "\n";
+
// Header row
out << "Period";
- for (const auto& series : std::as_const(single_series_))
- out << "," << series.series_name;
+ for (const auto& series : std::as_const(export_series))
+ out << "," << csv_quote(series.series_name);
out << "\n";
// Data rows
for (const auto& period : std::as_const(periods)) {
- out << period;
- for (const auto& series : std::as_const(single_series_)) {
+ out << csv_quote(period);
+ for (const auto& series : std::as_const(export_series)) {
out << ",";
- bool found = false;
for (const auto& obs : series.observations) {
- if (obs.period == period) {
- if (obs.valid)
- out << obs.value;
- // else: empty cell for NA
- found = true;
- break;
- }
+ if (obs.period != period)
+ continue;
+ // QTextStream's default real precision is 6 significant digits,
+ // which silently rewrote e.g. 21433226000000 as 2.14332e+13.
+ if (obs.valid)
+ out << QString::number(obs.value, 'g', 15);
+ // else: empty cell for NA — a gap must stay a gap
+ break;
}
- Q_UNUSED(found)
}
out << "\n";
}
@@ -685,11 +776,10 @@ void DBnomicsScreen::on_add_to_single_view() {
assign_series_colors();
render_single_view();
- // Switch to single view
- single_btn_->setChecked(true);
- compare_btn_->setChecked(false);
- view_mode_ = services::DbnViewMode::Single;
- view_stack_->setCurrentIndex(0);
+ // Switch to single view through the toggle handler so button styling
+ // follows the stack (a bare setChecked() left the old style applied).
+ if (single_btn_)
+ single_btn_->click();
set_status(tr("Added: %1").arg(last_loaded_data_.series_name));
LOG_INFO("DBnomicsScreen", QString("Series added to single view: %1").arg(last_loaded_data_.series_id));
@@ -968,10 +1058,11 @@ void DBnomicsScreen::restore_state(const QVariantMap& state) {
const QString ser = state.value("series").toString();
const int mode = state.value("view_mode", 0).toInt();
- if (mode == 1) {
- view_mode_ = services::DbnViewMode::Comparison;
- view_stack_->setCurrentIndex(1);
- }
+ // Drive the toggle through its own handler so the button check-state AND
+ // its stylesheet stay in sync with view_stack_. Setting the stack index
+ // directly left COMPARE showing while SINGLE still looked selected.
+ if (mode == 1 && compare_btn_)
+ compare_btn_->click();
if (!prov.isEmpty())
on_provider_selected(prov);
diff --git a/fincept-qt/src/screens/dbnomics/DBnomicsScreen.h b/fincept-qt/src/screens/dbnomics/DBnomicsScreen.h
index 02d44c644..8aed87e38 100644
--- a/fincept-qt/src/screens/dbnomics/DBnomicsScreen.h
+++ b/fincept-qt/src/screens/dbnomics/DBnomicsScreen.h
@@ -90,6 +90,7 @@ class DBnomicsScreen : public QWidget, public IStatefulScreen {
QPushButton* export_btn_ = nullptr;
QLabel* chart_type_label_ = nullptr;
QLabel* comparison_placeholder_ = nullptr;
+ QLabel* attribution_label_ = nullptr;
services::DbnViewMode view_mode_ = services::DbnViewMode::Single;
services::DbnChartType single_chart_type_ = services::DbnChartType::Line;
diff --git a/fincept-qt/src/screens/dbnomics/DBnomicsSelectionPanel.cpp b/fincept-qt/src/screens/dbnomics/DBnomicsSelectionPanel.cpp
index d8df89977..097038032 100644
--- a/fincept-qt/src/screens/dbnomics/DBnomicsSelectionPanel.cpp
+++ b/fincept-qt/src/screens/dbnomics/DBnomicsSelectionPanel.cpp
@@ -192,6 +192,8 @@ QWidget* DBnomicsSelectionPanel::build_search_section() {
global_search_input_->setStyleSheet(kInputStyle());
global_search_input_->setFixedHeight(28);
global_search_input_->setPlaceholderText(tr("Search providers, datasets..."));
+ global_search_input_->setAccessibleName(tr("Global DBnomics search"));
+ global_search_input_->setClearButtonEnabled(true);
layout->addWidget(global_search_input_);
// Loading spinner (hidden by default, appears between input and results)
@@ -265,11 +267,16 @@ QWidget* DBnomicsSelectionPanel::build_provider_section() {
provider_filter_input_->setStyleSheet(kInputStyle());
provider_filter_input_->setFixedHeight(26);
provider_filter_input_->setPlaceholderText(tr("Filter providers..."));
+ provider_filter_input_->setAccessibleName(tr("Filter provider list"));
+ provider_filter_input_->setClearButtonEnabled(true);
pc_layout->addWidget(provider_filter_input_);
provider_list_ = make_styled_list(130);
+ provider_list_->setAccessibleName(tr("DBnomics providers"));
pc_layout->addWidget(provider_list_);
+ QWidget::setTabOrder(provider_filter_input_, provider_list_);
+
layout->addWidget(prov_content_);
// Filter providers by code or name
@@ -316,6 +323,7 @@ QWidget* DBnomicsSelectionPanel::build_dataset_section() {
dc_layout->setSpacing(0);
dataset_list_ = make_styled_list(130);
+ dataset_list_->setAccessibleName(tr("Datasets published by the selected provider"));
dc_layout->addWidget(dataset_list_);
dataset_load_more_btn_ = make_load_more_button();
@@ -361,11 +369,16 @@ QWidget* DBnomicsSelectionPanel::build_series_section() {
series_search_input_->setStyleSheet(kInputStyle());
series_search_input_->setFixedHeight(26);
series_search_input_->setPlaceholderText(tr("Search series..."));
+ series_search_input_->setAccessibleName(tr("Search series within the selected dataset"));
+ series_search_input_->setClearButtonEnabled(true);
sc_layout->addWidget(series_search_input_);
series_list_ = make_styled_list(130);
+ series_list_->setAccessibleName(tr("Series in the selected dataset"));
sc_layout->addWidget(series_list_);
+ QWidget::setTabOrder(series_search_input_, series_list_);
+
series_load_more_btn_ = make_load_more_button();
sc_layout->addWidget(series_load_more_btn_);
@@ -798,9 +811,16 @@ void DBnomicsSelectionPanel::update_slot_series(int slot_index, const QVector<se
}
}
- // Dot colors for series rows
- static const QStringList dot_colors = {"#ea580c", "#d97706", "#16a34a", "#2563eb",
- "#0891b2", "#9333ea", "#dc2626", "#ca8a04"};
+ // Row chrome is identical for every series \u2014 build the two stylesheet
+ // strings once instead of re-formatting them per row.
+ const QString name_style = QString("color: %1; font-size: 10px; "
+ "font-family: 'Consolas','Courier New',monospace;")
+ .arg(col::TEXT_SECONDARY());
+ const QString remove_style =
+ QString("QPushButton { background: transparent; color: %1; border: none; font-size: 10px; }"
+ "QPushButton:hover { color: %2; }")
+ .arg(col::TEXT_TERTIARY())
+ .arg(col::NEGATIVE());
for (int i = 0; i < series.size(); ++i) {
const auto& dp = series[i];
@@ -810,10 +830,12 @@ void DBnomicsSelectionPanel::update_slot_series(int slot_index, const QVector<se
row_layout->setContentsMargins(0, 0, 0, 0);
row_layout->setSpacing(4);
- // Colored dot
- const QString dot_color = dot_colors[i % dot_colors.size()];
+ // Legend dot \u2014 use the series' OWN assigned colour. It used to be
+ // pulled from a second, different hard-coded palette, so from the 2nd
+ // series onward the sidebar legend named the wrong colour for the
+ // wrong line in the chart.
auto* dot = new QLabel("\u25CF");
- dot->setStyleSheet(QString("color: %1; font-size: 8px;").arg(dot_color));
+ dot->setStyleSheet(QString("color: %1; font-size: 8px; background: transparent;").arg(dp.color.name()));
dot->setFixedWidth(12);
row_layout->addWidget(dot);
@@ -823,9 +845,7 @@ void DBnomicsSelectionPanel::update_slot_series(int slot_index, const QVector<se
name = name.left(19) + "...";
}
auto* name_label = new QLabel(name);
- name_label->setStyleSheet(QString("color: %1; font-size: 10px; "
- "font-family: 'Consolas','Courier New',monospace;")
- .arg(col::TEXT_SECONDARY()));
+ name_label->setStyleSheet(name_style);
name_label->setToolTip(dp.series_name);
row_layout->addWidget(name_label, 1);
@@ -833,11 +853,9 @@ void DBnomicsSelectionPanel::update_slot_series(int slot_index, const QVector<se
const QString series_id = dp.series_id;
auto* remove_btn = new QPushButton("\u00D7");
remove_btn->setFixedSize(14, 14);
- remove_btn->setStyleSheet(
- QString("QPushButton { background: transparent; color: %1; border: none; font-size: 10px; }"
- "QPushButton:hover { color: %2; }")
- .arg(col::TEXT_TERTIARY())
- .arg(col::NEGATIVE()));
+ remove_btn->setAccessibleName(tr("Remove %1 from this slot").arg(dp.series_name));
+ remove_btn->setToolTip(tr("Remove %1").arg(dp.series_name));
+ remove_btn->setStyleSheet(remove_style);
connect(remove_btn, &QPushButton::clicked, this, [this, slot_widget, series_id]() {
const int idx = slots_layout_->indexOf(slot_widget);
if (idx >= 0)
diff --git a/fincept-qt/src/screens/derivatives/DerivativesScreen.cpp b/fincept-qt/src/screens/derivatives/DerivativesScreen.cpp
index f5134972c..9e57a5be8 100644
--- a/fincept-qt/src/screens/derivatives/DerivativesScreen.cpp
+++ b/fincept-qt/src/screens/derivatives/DerivativesScreen.cpp
@@ -405,20 +405,22 @@ QWidget* DerivativesScreen::create_equity_options_panel() {
opt_market_price_ = create_spin(15.0, 0, 1e8, 4);
- auto* iv_spot = create_spin(105.0, 0, 1e8, 2);
- auto* iv_strike = create_spin(100.0, 0, 1e8, 2);
- auto* iv_time = create_spin(1.0, 0.001, 30, 4);
- auto* iv_rate = create_spin(5.0, -20, 100, 2, "%");
- auto* iv_div = create_spin(2.0, 0, 100, 2, "%");
- auto* iv_type = create_combo({"Call", "Put"});
+ // Held as members — on_calculate_secondary() reads these, not the
+ // Black-Scholes panel's fields.
+ iv_spot_ = create_spin(105.0, 0, 1e8, 2);
+ iv_strike_ = create_spin(100.0, 0, 1e8, 2);
+ iv_time_ = create_spin(1.0, 0.001, 30, 4);
+ iv_rate_ = create_spin(5.0, -20, 100, 2, "%");
+ iv_div_ = create_spin(2.0, 0, 100, 2, "%");
+ iv_type_ = create_combo({"Call", "Put"});
ivbl->addWidget(
- create_two_col(create_input_row(tr("SPOT PRICE"), iv_spot), create_input_row(tr("STRIKE PRICE"), iv_strike)));
+ create_two_col(create_input_row(tr("SPOT PRICE"), iv_spot_), create_input_row(tr("STRIKE PRICE"), iv_strike_)));
ivbl->addWidget(create_input_row(tr("MARKET OPTION PRICE"), opt_market_price_));
- ivbl->addWidget(create_two_col(create_input_row(tr("TIME TO EXPIRY (years)"), iv_time),
- create_input_row(tr("RISK-FREE RATE (%)"), iv_rate)));
- ivbl->addWidget(create_two_col(create_input_row(tr("DIVIDEND YIELD (%)"), iv_div),
- create_input_row(tr("OPTION TYPE"), iv_type)));
+ ivbl->addWidget(create_two_col(create_input_row(tr("TIME TO EXPIRY (years)"), iv_time_),
+ create_input_row(tr("RISK-FREE RATE (%)"), iv_rate_)));
+ ivbl->addWidget(create_two_col(create_input_row(tr("DIVIDEND YIELD (%)"), iv_div_),
+ create_input_row(tr("OPTION TYPE"), iv_type_)));
auto* iv_btn = create_calc_button(tr("CALCULATE IMPLIED VOL"));
connect(iv_btn, &QPushButton::clicked, this, &DerivativesScreen::on_calculate_secondary);
@@ -885,22 +887,26 @@ void DerivativesScreen::on_calculate_secondary() {
});
break;
}
- case 1: { // Implied volatility
+ case 1: { // Implied volatility — solved from the IV card's OWN inputs.
+ if (opt_market_price_->value() <= 0) {
+ display_error(tr("Enter the option's market price — implied volatility is solved from it."));
+ return;
+ }
run_pricing("implied_vol", {
"--spot",
- QString::number(opt_spot_->value()),
+ QString::number(iv_spot_->value()),
"--strike",
- QString::number(opt_strike_->value()),
+ QString::number(iv_strike_->value()),
"--time",
- QString::number(opt_time_->value()),
+ QString::number(iv_time_->value()),
"--rate",
- QString::number(opt_rate_->value()),
+ QString::number(iv_rate_->value()),
"--market-price",
QString::number(opt_market_price_->value()),
"--div-yield",
- QString::number(opt_div_->value()),
+ QString::number(iv_div_->value()),
"--type",
- opt_type_->currentText().toLower(),
+ iv_type_->currentText().toLower(),
});
break;
}
@@ -927,6 +933,18 @@ void DerivativesScreen::run_pricing(const QString& command, const QStringList& a
loading_ = true;
clear_results();
+ // Loading state — the results panel was simply emptied, so a slow Python
+ // start looked identical to "the button did nothing".
+ if (status_engine_)
+ status_engine_->setText(tr("CALCULATING…"));
+ {
+ auto* busy = new QLabel(tr("Calculating %1 …").arg(command), this);
+ busy->setObjectName("derivResultLabel");
+ busy->setContentsMargins(12, 10, 12, 10);
+ results_container_->layout()->addWidget(busy);
+ results_container_->show();
+ }
+
QPointer<DerivativesScreen> self = this;
services::python_cli::PythonCliService::instance().run(
@@ -936,6 +954,8 @@ void DerivativesScreen::run_pricing(const QString& command, const QStringList& a
return;
self->loading_ = false;
+ if (self->status_engine_)
+ self->status_engine_->setText(DerivativesScreen::tr("PYTHON ENGINE"));
if (!r.success) {
self->display_error(r.error.isEmpty() ? DerivativesScreen::tr("Pricing failed") : r.error);
@@ -997,6 +1017,19 @@ void DerivativesScreen::display_error(const QString& error) {
}
void DerivativesScreen::display_results(const QJsonObject& result) {
+ // The pricing script reports solver failures in-band, e.g. implied_vol
+ // returns {"error": "Could not converge on implied volatility"} with a zero
+ // exit code. Without this the message fell through to the generic key dump
+ // and rendered as a result card titled "ERROR" — indistinguishable from a
+ // successful calculation at a glance.
+ if (result.contains("error") && result.value("error").isString()) {
+ const QString msg = result.value("error").toString();
+ if (!msg.isEmpty()) {
+ display_error(msg);
+ return;
+ }
+ }
+
clear_results();
auto* body = new QWidget(this);
diff --git a/fincept-qt/src/screens/derivatives/DerivativesScreen.h b/fincept-qt/src/screens/derivatives/DerivativesScreen.h
index 18234bfeb..7028adf9a 100644
--- a/fincept-qt/src/screens/derivatives/DerivativesScreen.h
+++ b/fincept-qt/src/screens/derivatives/DerivativesScreen.h
@@ -102,7 +102,20 @@ class DerivativesScreen : public QWidget, public IStatefulScreen {
QDoubleSpinBox* opt_div_ = nullptr;
QComboBox* opt_type_ = nullptr;
QDoubleSpinBox* opt_time_ = nullptr;
+
+ // Implied-volatility panel inputs. These are a SEPARATE set from the
+ // Black-Scholes panel above: the IV card has its own spot / strike / time /
+ // rate / dividend / type fields on screen, and they must be the ones sent to
+ // the solver. They used to be unnamed locals, so everything the user typed
+ // into this card was discarded and the left panel's values were solved
+ // instead — a silently wrong implied vol.
QDoubleSpinBox* opt_market_price_ = nullptr;
+ QDoubleSpinBox* iv_spot_ = nullptr;
+ QDoubleSpinBox* iv_strike_ = nullptr;
+ QDoubleSpinBox* iv_time_ = nullptr;
+ QDoubleSpinBox* iv_rate_ = nullptr;
+ QDoubleSpinBox* iv_div_ = nullptr;
+ QComboBox* iv_type_ = nullptr;
// FX option inputs
QDoubleSpinBox* fx_strike_ = nullptr;
diff --git a/fincept-qt/src/screens/docs/DocsScreen.cpp b/fincept-qt/src/screens/docs/DocsScreen.cpp
index 3a67ea056..a1ab99193 100644
--- a/fincept-qt/src/screens/docs/DocsScreen.cpp
+++ b/fincept-qt/src/screens/docs/DocsScreen.cpp
@@ -12,10 +12,14 @@
#include "screens/docs/DocsScreen_internal.h"
#include "ui/theme/Theme.h"
+#include <QCoreApplication>
#include <QFrame>
#include <QHBoxLayout>
#include <QHeaderView>
+#include <QKeySequence>
+#include <QLineEdit>
#include <QScrollArea>
+#include <QShortcut>
#include <QSplitter>
#include <QTreeWidgetItemIterator>
@@ -387,6 +391,55 @@ void DocsScreen::navigate_to(const QString& section_id) {
}
}
+// ── Topic count + search ─────────────────────────────────────────────────────
+
+void DocsScreen::update_topic_count() {
+ if (!cmd_count_ || !sidebar_)
+ return;
+ // Counted, not hardcoded — the literal said "35 TOPICS" while the tree had
+ // 38, and would drift again on the next page added.
+ int topics = 0;
+ const int categories = sidebar_->topLevelItemCount();
+ for (QTreeWidgetItemIterator it(sidebar_); *it; ++it)
+ if (!(*it)->data(0, Qt::UserRole).toString().isEmpty())
+ ++topics;
+ cmd_count_->setText(tr("%1 TOPICS | %2 CATEGORIES").arg(topics).arg(categories));
+}
+
+void DocsScreen::apply_search(const QString& text) {
+ if (!sidebar_)
+ return;
+ const QString needle = text.trimmed();
+
+ // Empty query restores the full tree.
+ if (needle.isEmpty()) {
+ for (int i = 0; i < sidebar_->topLevelItemCount(); ++i) {
+ auto* cat = sidebar_->topLevelItem(i);
+ cat->setHidden(false);
+ cat->setExpanded(true);
+ for (int j = 0; j < cat->childCount(); ++j)
+ cat->child(j)->setHidden(false);
+ }
+ return;
+ }
+
+ for (int i = 0; i < sidebar_->topLevelItemCount(); ++i) {
+ auto* cat = sidebar_->topLevelItem(i);
+ const bool cat_hit = cat->text(0).contains(needle, Qt::CaseInsensitive);
+ int visible_children = 0;
+ for (int j = 0; j < cat->childCount(); ++j) {
+ auto* child = cat->child(j);
+ const bool hit = cat_hit || child->text(0).contains(needle, Qt::CaseInsensitive) ||
+ child->data(0, Qt::UserRole).toString().contains(needle, Qt::CaseInsensitive);
+ child->setHidden(!hit);
+ if (hit)
+ ++visible_children;
+ }
+ cat->setHidden(visible_children == 0);
+ cat->setExpanded(true);
+ }
+}
+
// ============================================================================
// Constructor — Main layout
// ============================================================================
@@ -419,17 +472,36 @@ DocsScreen::DocsScreen(QWidget* parent) : QWidget(parent) {
.arg(ui::colors::BORDER_BRIGHT()));
cmd_hl->addWidget(sep);
- // Brand + version string — shown verbatim, not translated.
- breadcrumb_ = new QLabel("FINCEPT TERMINAL v4.0.0");
+ // Brand + version string — shown verbatim, not translated. Read from the
+ // running application rather than hardcoded: the literal here said v4.0.0
+ // while the app shipped as 4.0.1.
+ breadcrumb_ = new QLabel(QStringLiteral("FINCEPT TERMINAL v%1").arg(QCoreApplication::applicationVersion()));
breadcrumb_->setStyleSheet(QString("color: %1; font-size: 11px; font-weight: bold;"
" background: transparent; letter-spacing: 0.5px;"
" font-family: 'Consolas','Courier New',monospace;")
.arg(ui::colors::TEXT_SECONDARY()));
cmd_hl->addWidget(breadcrumb_);
+ // ── Search ────────────────────────────────────────────────────────────────
+ // 38 topics with no way to search them. Filters the sidebar tree live;
+ // Ctrl+F focuses it.
+ search_input_ = new QLineEdit;
+ search_input_->setFixedWidth(220);
+ search_input_->setClearButtonEnabled(true);
+ search_input_->setPlaceholderText(tr("Search topics… (Ctrl+F)"));
+ search_input_->setAccessibleName(tr("Search documentation topics"));
+ search_input_->setStyleSheet(QString("QLineEdit { background: %1; color: %2; border: 1px solid %3;"
+ " padding: 2px 6px; font-size: 11px;"
+ " font-family: 'Consolas','Courier New',monospace; }"
+ "QLineEdit:focus { border-color: %4; }")
+ .arg(ui::colors::BG_BASE(), ui::colors::TEXT_PRIMARY(),
+ ui::colors::BORDER_DIM(), ui::colors::BORDER_BRIGHT()));
+ connect(search_input_, &QLineEdit::textChanged, this, &DocsScreen::apply_search);
+ cmd_hl->addWidget(search_input_);
+
cmd_hl->addStretch();
- cmd_count_ = new QLabel(tr("%1 TOPICS | %2 CATEGORIES").arg(35).arg(9));
+ cmd_count_ = new QLabel;
cmd_count_->setStyleSheet(QString("color: %1; font-size: 11px; background: transparent;"
" font-family: 'Consolas','Courier New',monospace;")
.arg(ui::colors::TEXT_TERTIARY()));
@@ -440,6 +512,14 @@ DocsScreen::DocsScreen(QWidget* parent) : QWidget(parent) {
// ── Splitter: sidebar + content ──────────────────────────────────────────
build_sidebar();
build_content_pages();
+ update_topic_count();
+
+ auto* find_sc = new QShortcut(QKeySequence::Find, this);
+ find_sc->setContext(Qt::WidgetWithChildrenShortcut);
+ connect(find_sc, &QShortcut::activated, this, [this]() {
+ search_input_->setFocus();
+ search_input_->selectAll();
+ });
splitter_ = new QSplitter(Qt::Horizontal);
splitter_->setStyleSheet(QString("QSplitter { background: %1; }"
@@ -474,8 +554,8 @@ void DocsScreen::retranslateUi() {
// Command bar
if (cmd_title_)
cmd_title_->setText(tr("DOCUMENTATION"));
- if (cmd_count_)
- cmd_count_->setText(tr("%1 TOPICS | %2 CATEGORIES").arg(35).arg(9));
+ if (search_input_)
+ search_input_->setPlaceholderText(tr("Search topics… (Ctrl+F)"));
// Rebuild sidebar + content pages so their tr() strings pick up the new
// language. Preserve the currently displayed section across the rebuild.
@@ -513,6 +593,10 @@ void DocsScreen::retranslateUi() {
old_sidebar->deleteLater();
old_pages->deleteLater();
+ update_topic_count();
+ if (search_input_)
+ apply_search(search_input_->text()); // re-apply the active filter to the new tree
+
// Restore the section the user was on (also re-selects the sidebar row via
// the currentItemChanged → navigate_to wiring).
if (!current_id.isEmpty()) {
diff --git a/fincept-qt/src/screens/docs/DocsScreen.h b/fincept-qt/src/screens/docs/DocsScreen.h
index b9ea5c5e1..6427cb925 100644
--- a/fincept-qt/src/screens/docs/DocsScreen.h
+++ b/fincept-qt/src/screens/docs/DocsScreen.h
@@ -9,6 +9,7 @@
#include <QWidget>
class QSplitter;
+class QLineEdit;
namespace fincept::screens {
@@ -26,6 +27,10 @@ class DocsScreen : public QWidget {
void build_sidebar();
void build_content_pages();
void navigate_to(const QString& section_id);
+ /// Filter the sidebar tree by topic/category text (live, from the search box).
+ void apply_search(const QString& text);
+ /// Recompute the "N TOPICS | M CATEGORIES" chip from the actual tree.
+ void update_topic_count();
/// Re-apply tr() lookups. Static documentation content (sidebar tree + all
/// pages) is rebuilt from scratch on QEvent::LanguageChange — caching the
@@ -105,11 +110,11 @@ class DocsScreen : public QWidget {
QSplitter* splitter_ = nullptr; // owns sidebar_ + pages_; reused on rebuild
QTreeWidget* sidebar_ = nullptr;
QStackedWidget* pages_ = nullptr;
- QLabel* page_title_ = nullptr;
QLabel* breadcrumb_ = nullptr;
- // Command-bar labels (cached for retranslateUi)
+ // Command-bar widgets (cached for retranslateUi)
QLabel* cmd_title_ = nullptr;
QLabel* cmd_count_ = nullptr;
+ QLineEdit* search_input_ = nullptr;
QMap<QString, int> page_index_; // section_id → stacked widget index
};
diff --git a/fincept-qt/src/screens/docs/DocsScreen_Pages_Intro.cpp b/fincept-qt/src/screens/docs/DocsScreen_Pages_Intro.cpp
index 9ddb5a1d8..db0e7927e 100644
--- a/fincept-qt/src/screens/docs/DocsScreen_Pages_Intro.cpp
+++ b/fincept-qt/src/screens/docs/DocsScreen_Pages_Intro.cpp
@@ -9,6 +9,7 @@
#include "screens/docs/DocsScreen_internal.h"
#include "ui/theme/Theme.h"
+#include <QCoreApplication>
#include <QFrame>
#include <QHBoxLayout>
#include <QLabel>
@@ -36,7 +37,10 @@ QWidget* DocsScreen::page_welcome() {
vl->setSpacing(12);
vl->addWidget(make_heading(tr("FINCEPT TERMINAL — DOCUMENTATION")));
- vl->addWidget(make_muted_label(tr("v4.0.0 | Native C++ Financial Intelligence Terminal")));
+ // Version comes from the running application — the hardcoded "v4.0.0" was
+ // already stale against the shipped 4.0.1.
+ vl->addWidget(make_muted_label(
+ tr("v%1 | Native C++ Financial Intelligence Terminal").arg(QCoreApplication::applicationVersion())));
auto* sep = new QFrame;
sep->setFrameShape(QFrame::HLine);
@@ -49,8 +53,8 @@ QWidget* DocsScreen::page_welcome() {
"built in native C++ with Qt6. It provides institutional-quality market data, "
"trading capabilities, quantitative research tools, and AI-powered analytics — "
"all in a single unified terminal interface.\n\n"
- "With 45+ integrated screens, real-time WebSocket feeds, embedded Python analytics, "
- "and support for 15+ broker integrations, Fincept Terminal bridges the gap between "
+ "With 50+ integrated screens, real-time WebSocket feeds, embedded Python analytics, "
+ "and 16 broker integrations, Fincept Terminal bridges the gap between "
"retail and institutional tooling."),
ui::colors::AMBER));
@@ -58,7 +62,7 @@ QWidget* DocsScreen::page_welcome() {
tr("■ Real-time market data across equities, crypto, forex, commodities\n"
"■ Multi-exchange crypto trading (Kraken, HyperLiquid, Binance, etc.)\n"
"■ Paper trading engine with simulated order matching\n"
- "■ 100+ Python analytics scripts (equity, portfolio, derivatives)\n"
+ "■ 1300+ Python analytics scripts (equity, portfolio, derivatives)\n"
"■ 18-module QuantLib quantitative analysis suite (590+ endpoints)\n"
"■ AI Quant Lab with ML models, factor discovery, HFT, RL trading\n"
"■ Multiple AI agent frameworks (Geopolitics, Economic, Hedge Fund)\n"
diff --git a/fincept-qt/src/screens/economics/EconomicsScreen.cpp b/fincept-qt/src/screens/economics/EconomicsScreen.cpp
index dbcc2a472..2de0d419d 100644
--- a/fincept-qt/src/screens/economics/EconomicsScreen.cpp
+++ b/fincept-qt/src/screens/economics/EconomicsScreen.cpp
@@ -27,6 +27,7 @@
#include "screens/economics/panels/FredPanel.h"
#include "screens/economics/panels/GlobalCentralBanksPanel.h"
#include "screens/economics/panels/IlostatPanel.h"
+#include "screens/economics/panels/NberPanel.h"
#include "screens/economics/panels/ImfPanel.h"
#include "screens/economics/panels/OecdPanel.h"
#include "screens/economics/panels/OnsPanel.h"
@@ -47,6 +48,8 @@
#include <QScrollArea>
#include <QVBoxLayout>
+#include <iterator>
+
namespace fincept::screens {
// ── Source registry ───────────────────────────────────────────────────────────
@@ -74,6 +77,7 @@ static const struct {
{"global_cb", "Central Banks", "#4A148C"},
{"federal_reserve", "Federal Reserve", "#1A237E"},
{"fiscal_data", "Fiscal Data", "#006064"},
+ {"nber", "NBER Cycles", "#7C3AED"},
{"owid", "Our World In Data", "#6D28D9"},
{"statcan", "StatCan", "#B71C1C"},
{"ilostat", "ILO", "#0D47A1"},
@@ -127,6 +131,8 @@ static EconPanelBase* make_panel(const QString& id, QWidget* parent) {
return new FederalReservePanel(parent);
if (id == "fiscal_data")
return new FiscalDataPanel(parent);
+ if (id == "nber")
+ return new NberPanel(parent);
if (id == "owid")
return new OwIdPanel(parent);
if (id == "statcan")
@@ -182,7 +188,9 @@ void EconomicsScreen::build_ui() {
hl->setSpacing(8);
title_ = new QLabel(tr("ECONOMICS DATA EXPLORER"));
- subtitle_ = new QLabel(tr("32 global data sources · 1000+ indicators"));
+ // Derive the count from the registry — the hard-coded "32" was one more
+ // than the number of panels actually registered.
+ subtitle_ = new QLabel(tr("%1 global data sources · 1000+ indicators").arg(static_cast<int>(std::size(kSources))));
hl->addWidget(title_);
hl->addWidget(subtitle_);
@@ -191,6 +199,7 @@ void EconomicsScreen::build_ui() {
// ── Badge bar (scrollable) ────────────────────────────────────────────────
scroll_ = new QScrollArea;
+ scroll_->setAccessibleName(tr("Economics data source selector"));
scroll_->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
scroll_->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
scroll_->setFixedHeight(34);
@@ -211,6 +220,8 @@ void EconomicsScreen::build_ui() {
auto* btn = new QPushButton(src.label);
btn->setCheckable(true);
btn->setFixedHeight(26);
+ btn->setAccessibleName(tr("Data source: %1").arg(QString::fromUtf8(src.label)));
+ btn->setToolTip(tr("Switch to the %1 data source").arg(QString::fromUtf8(src.label)));
const QString sid = src.id;
connect(btn, &QPushButton::clicked, this, [this, sid]() { switch_to(sid); });
@@ -221,6 +232,10 @@ void EconomicsScreen::build_ui() {
}
bhl->addStretch();
+ // Left-to-right keyboard traversal across the source badges.
+ for (int i = 1; i < sources_.size(); ++i)
+ QWidget::setTabOrder(sources_[i - 1].badge, sources_[i].badge);
+
scroll_->setWidget(badge_bar_);
root->addWidget(scroll_);
@@ -280,7 +295,8 @@ void EconomicsScreen::retranslateUi() {
if (title_)
title_->setText(tr("ECONOMICS DATA EXPLORER"));
if (subtitle_)
- subtitle_->setText(tr("32 global data sources · 1000+ indicators"));
+ subtitle_->setText(
+ tr("%1 global data sources · 1000+ indicators").arg(static_cast<int>(std::size(kSources))));
// Source badge labels are brand/source names (data) and are not translated.
}
diff --git a/fincept-qt/src/screens/economics/panels/AdbPanel.cpp b/fincept-qt/src/screens/economics/panels/AdbPanel.cpp
index 039cc40a3..4047685c8 100644
--- a/fincept-qt/src/screens/economics/panels/AdbPanel.cpp
+++ b/fincept-qt/src/screens/economics/panels/AdbPanel.cpp
@@ -10,6 +10,7 @@
#include "core/logging/Logger.h"
#include "services/economics/EconomicsService.h"
+#include <QCompleter>
#include <QHBoxLayout>
#include <QJsonArray>
#include <QJsonObject>
@@ -64,7 +65,9 @@ AdbPanel::AdbPanel(QWidget* parent) : EconPanelBase(kAdbSourceId, kAdbColor, par
void AdbPanel::activate() {
show_empty(tr("Select an economy and data category, then click FETCH\n"
- "ADB data is free — no API key required"));
+ "Source: Asian Development Bank — Key Indicators Database (KIDB), SDMX\n"
+ "Free, no API key required. Values are in the economy's own currency unless\n"
+ "the indicator code says otherwise (…_XDC = domestic currency, …_PT = percent)"));
}
// ── Controls ──────────────────────────────────────────────────────────────────
@@ -94,6 +97,24 @@ void AdbPanel::build_controls(QHBoxLayout* thl) {
indicator_input_->setText(kAdbCategories[0].default_indicator);
indicator_input_->setFixedHeight(26);
indicator_input_->setFixedWidth(130);
+ indicator_input_->setAccessibleName(tr("ADB indicator code"));
+ // The curated KIDB indicator list existed but was never surfaced anywhere —
+ // expose it as an inline completer (code and human label both match) so the
+ // free-text field is discoverable instead of guess-only.
+ {
+ QStringList completions;
+ QString tips;
+ for (const auto& gi : kGdpIndicators) {
+ completions << gi.second;
+ tips += gi.first + "\n";
+ }
+ auto* completer = new QCompleter(completions, indicator_input_);
+ completer->setCaseSensitivity(Qt::CaseInsensitive);
+ completer->setFilterMode(Qt::MatchContains);
+ completer->setCompletionMode(QCompleter::PopupCompletion);
+ indicator_input_->setCompleter(completer);
+ indicator_input_->setToolTip(tr("Common KIDB indicator codes:\n%1").arg(tips.trimmed()));
+ }
start_input_ = new QLineEdit;
start_input_->setPlaceholderText(tr("Start year"));
diff --git a/fincept-qt/src/screens/economics/panels/BlsPanel.cpp b/fincept-qt/src/screens/economics/panels/BlsPanel.cpp
index d061c29ed..d19187c2c 100644
--- a/fincept-qt/src/screens/economics/panels/BlsPanel.cpp
+++ b/fincept-qt/src/screens/economics/panels/BlsPanel.cpp
@@ -136,13 +136,29 @@ static QJsonArray extract_bls_rows(const QJsonObject& data) {
for (const auto& dv : s["data"].toArray()) {
QJsonObject row = dv.toObject();
row["series"] = title;
- // Combine year+period into a date string
+ // BLS periods: M01–M12 monthly, M13 = ANNUAL AVERAGE,
+ // Q01–Q04 quarterly (Q05 = annual avg), S01–S02 semi-annual
+ // (S03 = annual avg), A01 annual.
const QString year = row["year"].toString();
- const QString period = row["period"].toString(); // e.g. "M01"
- if (!year.isEmpty() && !period.isEmpty() && period != "M13") {
- const QString month = period.mid(1).rightJustified(2, '0');
- row["date"] = year + "-" + month;
- }
+ const QString period = row["period"].toString();
+ if (year.isEmpty() || period.isEmpty())
+ continue;
+ // Drop the synthetic annual-average rows: mixing them into a
+ // monthly/quarterly series inflates the point count and skews
+ // MIN/MAX/AVG, and (having no calendar date) they sorted to the
+ // front and could be picked up as CHANGE's "previous" value.
+ if (period == "M13" || period == "Q05" || period == "S03")
+ continue;
+ const QChar freq = period.at(0);
+ const int num = period.mid(1).toInt();
+ if (freq == QLatin1Char('M'))
+ row["date"] = year + "-" + QString::number(num).rightJustified(2, '0'); // 2024-03
+ else if (freq == QLatin1Char('Q'))
+ row["date"] = year + "-Q" + QString::number(num); // 2024-Q1 (sorts correctly)
+ else if (freq == QLatin1Char('S'))
+ row["date"] = year + "-S" + QString::number(num);
+ else
+ row["date"] = year; // annual
rows.append(row);
}
}
diff --git a/fincept-qt/src/screens/economics/panels/CftcPanel.cpp b/fincept-qt/src/screens/economics/panels/CftcPanel.cpp
index 127a17d1e..6d52ba9da 100644
--- a/fincept-qt/src/screens/economics/panels/CftcPanel.cpp
+++ b/fincept-qt/src/screens/economics/panels/CftcPanel.cpp
@@ -250,6 +250,12 @@ void CftcPanel::build_sentiment_widget() {
root->addLayout(cards_hl);
root->addWidget(oi_row);
root->addStretch(1);
+
+ // Register the sentiment card view as a real page of the shared content
+ // stack. Previously this whole widget tree was built, parented to the panel
+ // and then never added to any layout — it floated at (0,0) over the toolbar
+ // and the Market Sentiment view silently degraded to a one-row table.
+ sentiment_page_ = add_content_page(sentiment_widget_);
}
// ── Fetch ─────────────────────────────────────────────────────────────────────
@@ -289,6 +295,11 @@ void CftcPanel::on_result(const QString& request_id, const services::EconomicsRe
return;
}
+ // Table/trend views are time series — restore the aggregate stat row that
+ // the sentiment view hides.
+ if (!request_id.startsWith("cftc_sent_"))
+ set_stats_visible(true);
+
// Sentiment view: data is an object, not an array
if (request_id.startsWith("cftc_sent_")) {
const QJsonObject sentiment = result.data["data"].toObject();
@@ -372,20 +383,23 @@ void CftcPanel::show_sentiment(const QJsonObject& s) {
sent_noncomm_bias_->style()->unpolish(sent_noncomm_bias_);
sent_noncomm_bias_->style()->polish(sent_noncomm_bias_);
+ // NB: QString::arg(qlonglong, int fieldWidth) — the previous `.arg(v, 'd')`
+ // passed the *char literal* 'd' (=100) as the field width, padding every
+ // net-position number with 100 leading spaces. Format the number first.
const QJsonObject comm = s["commercial_positions"].toObject();
const double comm_net = comm["net"].toDouble();
- sent_comm_net_->setText(tr("Net: %1%2").arg(comm_net >= 0 ? "+" : "").arg(static_cast<qint64>(comm_net), 'd'));
+ sent_comm_net_->setText(tr("Net: %1%2")
+ .arg(comm_net >= 0 ? QStringLiteral("+") : QString())
+ .arg(QString::number(static_cast<qint64>(comm_net))));
const QJsonObject noncomm = s["non_commercial_positions"].toObject();
const double noncomm_net = noncomm["net"].toDouble();
- sent_noncomm_net_->setText(
- tr("Net: %1%2").arg(noncomm_net >= 0 ? "+" : "").arg(static_cast<qint64>(noncomm_net), 'd'));
-
- // Switch to sentiment widget — we show it in place of empty state
- // by temporarily inserting it into the layout if not already there
- // The base class stack_ is private; we use show_empty and overlay trick:
- // Instead, we just show data in the table as a summary row fallback.
- // For now, display the sentiment as a single-row table so base stats work.
+ sent_noncomm_net_->setText(tr("Net: %1%2")
+ .arg(noncomm_net >= 0 ? QStringLiteral("+") : QString())
+ .arg(QString::number(static_cast<qint64>(noncomm_net))));
+
+ // Populate the shared table too (one summary row) so CSV export still has
+ // something to write, then switch the stack to the sentiment card view.
QJsonArray rows;
QJsonObject row;
row["market"] = s["market_name"].toString(market_combo_->currentText());
@@ -397,7 +411,10 @@ void CftcPanel::show_sentiment(const QJsonObject& s) {
row["noncomm_bias"] = noncomm_bias;
row["oi_trend"] = oi_trend;
rows.append(row);
+ // A one-row snapshot has no meaningful LATEST/CHANGE/MIN/MAX/AVG.
+ set_stats_visible(false);
display(rows, "CFTC Sentiment: " + market_combo_->currentText());
+ show_content_page(sentiment_page_);
LOG_INFO("CftcPanel", "Displayed sentiment for " + market_combo_->currentText());
}
diff --git a/fincept-qt/src/screens/economics/panels/CftcPanel.h b/fincept-qt/src/screens/economics/panels/CftcPanel.h
index 908fbff83..ec3ca7e0a 100644
--- a/fincept-qt/src/screens/economics/panels/CftcPanel.h
+++ b/fincept-qt/src/screens/economics/panels/CftcPanel.h
@@ -8,7 +8,6 @@
#include <QComboBox>
#include <QLabel>
-#include <QStackedWidget>
namespace fincept::screens {
@@ -44,7 +43,9 @@ class CftcPanel : public EconPanelBase {
QLabel* sent_comm_net_ = nullptr;
QLabel* sent_noncomm_net_ = nullptr;
- QStackedWidget* content_stack_ = nullptr; // 0=base table, 1=sentiment
+ // Index of the sentiment page inside EconPanelBase's shared content stack
+ // (-1 until build_sentiment_widget() registers it).
+ int sentiment_page_ = -1;
// Cached for retranslateUi — toolbar labels
QLabel* market_lbl_ = nullptr;
diff --git a/fincept-qt/src/screens/economics/panels/EcbPanel.cpp b/fincept-qt/src/screens/economics/panels/EcbPanel.cpp
index 87990f39a..0940bbca3 100644
--- a/fincept-qt/src/screens/economics/panels/EcbPanel.cpp
+++ b/fincept-qt/src/screens/economics/panels/EcbPanel.cpp
@@ -73,7 +73,12 @@ void EcbPanel::on_fetch() {
show_loading(tr("Fetching ECB data: %1…").arg(series.label));
- QStringList args = {series.command};
+ // EconomicsService::execute() already prepends `command` to the argv, so
+ // args must carry ONLY the extra positional arguments. Repeating the
+ // command here shifted every parameter by one — the CLI read
+ // `exchange_rates exchange_rates USD` as currency="exchange_rates",
+ // freq="USD", so every ECB fetch silently queried a bogus series.
+ QStringList args;
if (!series.arg.isEmpty())
args << series.arg;
diff --git a/fincept-qt/src/screens/economics/panels/EconPanelBase.cpp b/fincept-qt/src/screens/economics/panels/EconPanelBase.cpp
index b9d50fb9c..2c8143ce1 100644
--- a/fincept-qt/src/screens/economics/panels/EconPanelBase.cpp
+++ b/fincept-qt/src/screens/economics/panels/EconPanelBase.cpp
@@ -5,15 +5,21 @@
#include "ui/theme/ThemeManager.h"
#include <QColor>
+#include <QDateTime>
#include <QFile>
#include <QFileDialog>
#include <QHBoxLayout>
#include <QHeaderView>
+#include <QJsonObject>
+#include <QLineEdit>
#include <QListWidget>
+#include <QScrollBar>
#include <QTextStream>
#include <QVBoxLayout>
#include <algorithm>
+#include <cmath>
+#include <utility>
namespace fincept::screens {
@@ -24,7 +30,23 @@ QString EconPanelBase::panel_style() const {
int r = QColor(color_).red();
int g = QColor(color_).green();
int b = QColor(color_).blue();
- return QString("#econToolbar { background:%5; border-bottom:1px solid %6; }"
+ return QString(
+ // Toolbar control labels ("DATASET", "COUNTRY", …). Every one
+ // of the 31 panels currently does
+ // lbl->setStyleSheet(ctrl_label_style());
+ // which is a full CSS parse per label per panel. This rule
+ // lets a panel just do setObjectName("econCtrlLabel") and
+ // inherit the same look for free — the container stylesheet
+ // is parsed once either way. Migrate panels to it as they are
+ // touched; ctrl_label_style() stays for the ones not yet moved.
+ // %9 is TEXT_TERTIARY (same token ctrl_label_style() uses and
+ // the same one #econStatLabel uses). NOT %12 — that is a
+ // BACKGROUND colour here (alternate-background-color /
+ // #econTitleBar), so using it would render the label
+ // invisible against its own panel.
+ "QLabel#econCtrlLabel { color:%9; font-size:9px; font-weight:700;"
+ " background:transparent; }"
+ "#econToolbar { background:%5; border-bottom:1px solid %6; }"
"#econFetchBtn { background:%1; color:%7; border:none;"
" font-size:10px; font-weight:700; padding:4px 14px; }"
"#econFetchBtn:hover { background:rgba(%2,%3,%4,0.75); }"
@@ -166,17 +188,40 @@ void EconPanelBase::build_base_ui(QWidget* container) {
fetch_btn_ = new QPushButton(tr("FETCH"));
fetch_btn_->setObjectName("econFetchBtn");
fetch_btn_->setCursor(Qt::PointingHandCursor);
+ fetch_btn_->setAccessibleName(tr("Fetch data"));
+ fetch_btn_->setAccessibleDescription(tr("Run the query against the %1 data source").arg(source_id_));
+ fetch_btn_->setToolTip(tr("Run the query (Enter)"));
connect(fetch_btn_, &QPushButton::clicked, this, &EconPanelBase::on_fetch);
export_btn_ = new QPushButton(tr("CSV"));
export_btn_->setObjectName("econCsvBtn");
export_btn_->setCursor(Qt::PointingHandCursor);
+ export_btn_->setAccessibleName(tr("Export results as CSV"));
+ export_btn_->setToolTip(tr("Export the full result set (all pages) as CSV"));
connect(export_btn_, &QPushButton::clicked, this, &EconPanelBase::export_csv);
thl->addWidget(fetch_btn_);
thl->addWidget(export_btn_);
root->addWidget(toolbar);
+ // Explicit keyboard tab order across the query form, in visual order,
+ // ending on FETCH → CSV. Without this Qt falls back to construction order,
+ // which for the sidebar panels starts focus in the results table.
+ // Also make Enter in any toolbar text field run the query.
+ {
+ QWidget* prev = nullptr;
+ for (int i = 0; i < thl->count(); ++i) {
+ QWidget* w = thl->itemAt(i)->widget();
+ if (!w || !(w->focusPolicy() & Qt::TabFocus))
+ continue;
+ if (prev)
+ QWidget::setTabOrder(prev, w);
+ prev = w;
+ if (auto* le = qobject_cast<QLineEdit*>(w))
+ connect(le, &QLineEdit::returnPressed, this, &EconPanelBase::on_fetch);
+ }
+ }
+
// Stat cards row
cards_row_ = new QWidget(this);
cards_row_->setObjectName("econCardsRow");
@@ -250,6 +295,7 @@ void EconPanelBase::build_base_ui(QWidget* container) {
table_->verticalHeader()->setVisible(false);
table_->setAlternatingRowColors(true);
table_->setShowGrid(true);
+ table_->setAccessibleName(tr("Results table"));
tpl->addWidget(table_, 1);
pager_ = new ui::PaginationBar(this);
@@ -321,6 +367,25 @@ void EconPanelBase::show_table() {
fetch_btn_->setEnabled(true);
}
+int EconPanelBase::add_content_page(QWidget* page) {
+ if (!stack_ || !page)
+ return -1;
+ return stack_->addWidget(page);
+}
+
+void EconPanelBase::show_content_page(int index) {
+ if (!stack_ || index < 0 || index >= stack_->count())
+ return;
+ stack_->setCurrentIndex(index);
+ if (fetch_btn_)
+ fetch_btn_->setEnabled(true);
+}
+
+void EconPanelBase::set_stats_visible(bool visible) {
+ if (cards_row_)
+ cards_row_->setVisible(visible);
+}
+
// ── Display ───────────────────────────────────────────────────────────────────
void EconPanelBase::display(const QJsonArray& rows, const QString& title) {
@@ -360,10 +425,16 @@ void EconPanelBase::display(const QJsonArray& rows, const QString& title) {
if (title_lbl_)
title_lbl_->setText(title);
- if (row_count_)
- row_count_->setText(tr("%1 records").arg(rows.size()));
+ // update_stats() derives latest_date_, so it must run before the row count
+ // line that reports the vintage.
update_stats(rows);
+
+ if (row_count_)
+ row_count_->setText(latest_date_.isEmpty()
+ ? tr("%1 records").arg(rows.size())
+ : tr("%1 records · as of %2").arg(rows.size()).arg(latest_date_));
+
show_table();
}
@@ -371,22 +442,49 @@ void EconPanelBase::render_page() {
const int start = pager_->offset();
const int count = std::min<int>(pager_->page_size(), all_rows_.size() - start);
+ // Preserve the user's vertical scroll offset across a re-render (page-size
+ // change, language switch) so the row they were reading doesn't jump.
+ const int scroll_pos = table_->verticalScrollBar() ? table_->verticalScrollBar()->value() : 0;
+ const int sel_row = table_->currentRow();
+
+ table_->setUpdatesEnabled(false);
table_->setColumnCount(columns_.size());
table_->setHorizontalHeaderLabels(columns_);
table_->setRowCount(count);
+ const QColor accent(color_);
for (int r = 0; r < count; ++r) {
const auto obj = all_rows_[start + r].toObject();
for (int c = 0; c < columns_.size(); ++c) {
const auto jv = obj[columns_[c]];
QString text;
- if (jv.isDouble())
- text = QString::number(jv.toDouble(), 'g', 8);
- else
+ bool numeric = false;
+ if (jv.isDouble()) {
+ numeric = true;
+ const double v = jv.toDouble();
+ // Render exact integers in full — 'g' turned large national
+ // accounts figures (e.g. 21433226000000) into "2.1433226e+13".
+ if (v == std::floor(v) && std::abs(v) < 1e15)
+ text = QString::number(static_cast<qint64>(v));
+ else
+ text = QString::number(v, 'g', 10);
+ } else if (jv.isNull() || jv.isUndefined()) {
+ text = QStringLiteral("—"); // explicit gap, never a silent 0
+ } else if (jv.isBool()) {
+ text = jv.toBool() ? QStringLiteral("true") : QStringLiteral("false");
+ } else {
text = jv.toString();
+ // Strings that are purely numeric (FRED/BLS return values as
+ // strings) still belong in a right-aligned column.
+ bool ok = false;
+ text.toDouble(&ok);
+ numeric = ok && !text.isEmpty();
+ }
auto* item = new QTableWidgetItem(text);
if (c == 0)
- item->setForeground(QColor(color_));
+ item->setForeground(accent);
+ // DESIGN_SYSTEM §5.4 — numeric columns are right-aligned.
+ item->setTextAlignment(numeric ? (Qt::AlignRight | Qt::AlignVCenter) : (Qt::AlignLeft | Qt::AlignVCenter));
table_->setItem(r, c, item);
}
}
@@ -394,6 +492,12 @@ void EconPanelBase::render_page() {
table_->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
if (columns_.size() > 1)
table_->horizontalHeader()->setSectionResizeMode(columns_.size() - 1, QHeaderView::Stretch);
+ table_->setUpdatesEnabled(true);
+
+ if (sel_row >= 0 && sel_row < count)
+ table_->setCurrentCell(sel_row, 0);
+ if (table_->verticalScrollBar())
+ table_->verticalScrollBar()->setValue(scroll_pos);
}
void EconPanelBase::update_stats(const QJsonArray& rows) {
@@ -432,16 +536,33 @@ void EconPanelBase::update_stats(const QJsonArray& rows) {
}
if (!ok)
continue;
+ // Date key: providers use very different spellings, and several return
+ // the period as a JSON *number* (WTO "Year", IMF "year"), where
+ // QJsonValue::toString() yields an empty string. Normalise both cases,
+ // and zero-pad bare years so "999" can't sort after "1999".
QString date;
- for (const char* k : {"date", "Date", "TIME_PERIOD", "period", "Period", "time", "obs_date"}) {
- if (obj.contains(QLatin1String(k))) {
- date = obj[QLatin1String(k)].toString();
+ for (const char* k : {"date", "Date", "TIME_PERIOD", "time_period", "period", "Period", "time", "obs_date",
+ "year", "Year", "YEAR", "record_date", "ref_date"}) {
+ if (!obj.contains(QLatin1String(k)))
+ continue;
+ const QJsonValue dv = obj[QLatin1String(k)];
+ if (dv.isDouble())
+ date = QString::number(static_cast<qint64>(dv.toDouble()));
+ else
+ date = dv.toString();
+ if (!date.isEmpty())
break;
- }
}
+ bool year_only = false;
+ const int year_val = date.toInt(&year_only);
+ if (year_only && date.size() < 4 && year_val >= 0)
+ date = date.rightJustified(4, '0');
pts.append({date, d});
}
std::stable_sort(pts.begin(), pts.end(), [](const DatedVal& a, const DatedVal& b) { return a.date < b.date; });
+ // Most recent period actually present in the payload — surfaced next to the
+ // record count so the user can see the data's vintage, not just its size.
+ latest_date_ = pts.isEmpty() ? QString() : pts.last().date;
QVector<double> vals;
vals.reserve(pts.size());
for (const auto& p : pts)
@@ -489,7 +610,10 @@ void EconPanelBase::update_stats(const QJsonArray& rows) {
// ── CSV ───────────────────────────────────────────────────────────────────────
void EconPanelBase::export_csv() {
- if (!table_ || table_->rowCount() == 0)
+ // Export the FULL result set (all_rows_), not just the page currently
+ // rendered in table_. The table only ever holds one page, so the previous
+ // table-driven export silently truncated every multi-page series.
+ if (all_rows_.isEmpty() || columns_.isEmpty())
return;
QString path =
@@ -501,22 +625,31 @@ void EconPanelBase::export_csv() {
if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
return;
QTextStream out(&file);
+ out.setEncoding(QStringConverter::Utf8);
+
+ auto quote = [](QString v) {
+ if (v.contains(',') || v.contains('"') || v.contains('\n'))
+ v = "\"" + v.replace("\"", "\"\"") + "\"";
+ return v;
+ };
+
+ // Provenance header — an economics export is useless without its source.
+ out << "# source=" << source_id_ << " exported=" << QDateTime::currentDateTimeUtc().toString(Qt::ISODate)
+ << " rows=" << all_rows_.size() << "\n";
QStringList hdrs;
- for (int c = 0; c < table_->columnCount(); ++c) {
- auto* h = table_->horizontalHeaderItem(c);
- hdrs << (h ? h->text() : "");
- }
+ for (const auto& c : std::as_const(columns_))
+ hdrs << quote(c);
out << hdrs.join(",") << "\n";
- for (int r = 0; r < table_->rowCount(); ++r) {
+ for (const auto& rv : std::as_const(all_rows_)) {
+ const QJsonObject obj = rv.toObject();
QStringList row;
- for (int c = 0; c < table_->columnCount(); ++c) {
- auto* item = table_->item(r, c);
- QString val = item ? item->text() : "";
- if (val.contains(',') || val.contains('"'))
- val = "\"" + val.replace("\"", "\"\"") + "\"";
- row << val;
+ for (const auto& col : std::as_const(columns_)) {
+ const QJsonValue jv = obj[col];
+ // 'g' with 15 significant digits round-trips a double without the
+ // scientific-notation truncation the UI formatter applies.
+ row << quote(jv.isDouble() ? QString::number(jv.toDouble(), 'g', 15) : jv.toString());
}
out << row.join(",") << "\n";
}
@@ -564,7 +697,9 @@ void EconPanelBase::retranslateUi() {
// Record count (re-apply count with translated suffix)
if (row_count_ && !all_rows_.isEmpty())
- row_count_->setText(tr("%1 records").arg(all_rows_.size()));
+ row_count_->setText(latest_date_.isEmpty()
+ ? tr("%1 records").arg(all_rows_.size())
+ : tr("%1 records · as of %2").arg(all_rows_.size()).arg(latest_date_));
// Current status message. The empty default re-translates; loading/error
// messages keep the message that was last shown (data-derived prefixes are
diff --git a/fincept-qt/src/screens/economics/panels/EconPanelBase.h b/fincept-qt/src/screens/economics/panels/EconPanelBase.h
index 04e8b6021..d81d73551 100644
--- a/fincept-qt/src/screens/economics/panels/EconPanelBase.h
+++ b/fincept-qt/src/screens/economics/panels/EconPanelBase.h
@@ -57,6 +57,19 @@ class EconPanelBase : public QWidget {
void display(const QJsonArray& rows, const QString& title = {});
void export_csv();
+ /// Append a subclass-owned page to the shared content stack.
+ /// Returns the page index (>= 2; 0 = status page, 1 = table page), or -1
+ /// if build_base_ui() has not run yet.
+ int add_content_page(QWidget* page);
+ /// Switch the content stack to a page returned by add_content_page().
+ void show_content_page(int index);
+
+ /// Show/hide the LATEST · CHANGE · MIN · MAX · AVG · POINTS row.
+ /// Call with `false` whenever the displayed rows are a cross-section
+ /// (one row per country, wide year columns, …) rather than a single time
+ /// series — the aggregates are meaningless there and actively misleading.
+ void set_stats_visible(bool visible);
+
/// Per-provider accent color stylesheet (uses live theme tokens).
QString panel_style() const;
@@ -126,6 +139,8 @@ class EconPanelBase : public QWidget {
QJsonArray all_rows_;
QStringList columns_;
+ /// Most recent period present in all_rows_ (the data's as-of date).
+ QString latest_date_;
};
} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/economics/panels/EurostatPanel.cpp b/fincept-qt/src/screens/economics/panels/EurostatPanel.cpp
index 25db29ef3..0e86acd4a 100644
--- a/fincept-qt/src/screens/economics/panels/EurostatPanel.cpp
+++ b/fincept-qt/src/screens/economics/panels/EurostatPanel.cpp
@@ -149,7 +149,11 @@ void EurostatPanel::on_fetch() {
show_loading(tr("Fetching Eurostat: %1 — %2…").arg(dataset.label, country_combo_->currentText()));
- QStringList args = {dataset.command};
+ // EconomicsService::execute() prepends `command` to the argv itself. Passing
+ // the command again here made the script read the command name as the
+ // country code (`industrial industrial DE` → country="industrial",
+ // nace="DE"), so the COUNTRY selector never reached Eurostat.
+ QStringList args;
if (dataset.has_country)
args << country;
diff --git a/fincept-qt/src/screens/economics/panels/FiscalDataPanel.cpp b/fincept-qt/src/screens/economics/panels/FiscalDataPanel.cpp
index 6948c62dd..55e186c79 100644
--- a/fincept-qt/src/screens/economics/panels/FiscalDataPanel.cpp
+++ b/fincept-qt/src/screens/economics/panels/FiscalDataPanel.cpp
@@ -65,9 +65,8 @@ void FiscalDataPanel::on_fetch() {
show_loading(tr("Fetching FiscalData: %1…").arg(series.label));
- QStringList args = {series.command};
- args << series.args;
-
+ // EconomicsService::execute() prepends `command` to the argv — pass only
+ // the extra flags here.
services::EconomicsService::instance().execute(kFiscalDataSourceId, kFiscalDataScript, series.command, series.args,
"fiscal_" + QString(series.command).replace('-', '_'));
}
diff --git a/fincept-qt/src/screens/economics/panels/FredAnalyticsPanel.cpp b/fincept-qt/src/screens/economics/panels/FredAnalyticsPanel.cpp
index 5fef30d0d..33b0f8f46 100644
--- a/fincept-qt/src/screens/economics/panels/FredAnalyticsPanel.cpp
+++ b/fincept-qt/src/screens/economics/panels/FredAnalyticsPanel.cpp
@@ -77,8 +77,11 @@ void FredAnalyticsPanel::on_fetch() {
show_loading(tr("Fetching FRED Analytics: %1…").arg(dataset.label));
- QStringList args = {dataset.command};
- args << dataset.args;
+ // EconomicsService::execute() prepends `command` to the argv. Repeating it
+ // here shifted the parameters by one: `money_supply money_supply m1` was
+ // parsed as measure="money_supply", start_date="m1", so the M1/M2/M3
+ // selection never reached FRED and every dataset got a junk start date.
+ const QStringList args = dataset.args;
const QString arg_suffix = dataset.args.isEmpty() ? "" : "_" + dataset.args.join("_");
services::EconomicsService::instance().execute(kFredAnalyticsSourceId, kFredAnalyticsScript, dataset.command, args,
diff --git a/fincept-qt/src/screens/economics/panels/GlobalCentralBanksPanel.cpp b/fincept-qt/src/screens/economics/panels/GlobalCentralBanksPanel.cpp
index 795c3a2bb..da699e310 100644
--- a/fincept-qt/src/screens/economics/panels/GlobalCentralBanksPanel.cpp
+++ b/fincept-qt/src/screens/economics/panels/GlobalCentralBanksPanel.cpp
@@ -98,14 +98,138 @@ static const QList<CbBank> kBanks = {
{"Exchange Rates (NOK)", "exchange_rates"},
{"NIBOR / Interest Rates", "interest_rates"},
}},
+ // ── Central & Eastern Europe, Middle East, SE Asia ───────────────────────
+ // These eight connectors already shipped in scripts/ and were already
+ // exposed as MCP tools (DataConnectorManifest.inc) — the AI could query
+ // them, a human could not. None requires an API key. Commands below are
+ // taken verbatim from that manifest.
+ {"CNB — Czech National Bank",
+ "cnb_data.py",
+ "cnb",
+ {
+ {"PRIBOR (History)", "pribor_history"},
+ {"PRIBOR (Year)", "pribor_year"},
+ {"PRIBOR (Latest)", "pribor"},
+ {"CZEONIA (Year)", "czeonia_year"},
+ {"CZEONIA (Latest)", "czeonia"},
+ {"Exchange Rates (Year)", "exchange_rates_y"},
+ {"Exchange Rates (Latest)", "exchange_rates"},
+ {"Monthly Average FX", "monthly_avg"},
+ {"Open Market Operations", "omo"},
+ {"Overview", "overview"},
+ }},
+ {"NBP — National Bank of Poland",
+ "nbp_data.py",
+ "nbp",
+ {
+ {"Exchange Rates (Range)", "range"},
+ {"Major Currencies", "major"},
+ {"USD/PLN", "usd"},
+ {"EUR/PLN", "eur"},
+ {"Bid/Ask Spreads", "bid_ask"},
+ {"Single Currency", "currency"},
+ {"Today", "today"},
+ {"Overview", "overview"},
+ }},
+ {"MNB — National Bank of Hungary",
+ "mnb_data.py",
+ "mnb",
+ {
+ {"Exchange Rates (Range)", "range"},
+ {"Major Currencies", "major"},
+ {"USD/HUF", "usd"},
+ {"EUR/HUF", "eur"},
+ {"Single Currency", "currency"},
+ {"Today", "today"},
+ {"Overview", "overview"},
+ }},
+ {"BNR — National Bank of Romania",
+ "bnr_data.py",
+ "bnr",
+ {
+ {"Exchange Rates (Year)", "year"},
+ {"Exchange Rates (Range)", "range"},
+ {"Single Currency", "currency"},
+ {"Major Currencies", "major"},
+ {"Today", "today"},
+ {"Overview", "overview"},
+ }},
+ {"HNB — Croatian National Bank",
+ "hnb_data.py",
+ "hnb",
+ {
+ {"Exchange Rates (Range)", "range"},
+ {"Single Currency", "currency"},
+ {"USD/EUR", "usd"},
+ {"GBP", "gbp"},
+ {"Today", "today"},
+ {"Overview", "overview"},
+ }},
+ {"TCMB — Central Bank of Türkiye",
+ "tcmb_data.py",
+ "tcmb",
+ {
+ {"Exchange Rates (Range)", "range"},
+ {"Major Currencies", "major"},
+ {"Single Currency", "currency"},
+ {"By Date", "date"},
+ {"Today", "today"},
+ {"Overview", "overview"},
+ }},
+ {"BOI — Bank of Israel",
+ "boi_data.py",
+ "boi",
+ {
+ {"All Exchange Rates", "all"},
+ {"USD/ILS", "usd"},
+ {"EUR/ILS", "eur"},
+ {"Today", "today"},
+ {"Overview", "overview"},
+ }},
+ {"BNM — Bank Negara Malaysia",
+ "bnm_data.py",
+ "bnm",
+ {
+ {"Overnight Policy Rate (OPR)", "opr"},
+ {"Major Currencies", "major"},
+ {"ASEAN Currencies", "asean"},
+ {"Single Currency", "currency"},
+ {"Trading Sessions", "sessions"},
+ {"Overview", "overview"},
+ }},
};
// ── Flatten helpers ──────────────────────────────────────────────────────────
-// All bank response shapes have a "data" array of objects with a "date" key
-// and one or more numeric value columns. We keep all columns as-is.
+// Bank responses put their payload under "data" with a "date" key and one or
+// more numeric value columns. We keep all columns as-is.
+//
+// The shape is NOT uniform per script — it varies per COMMAND. Series commands
+// ("year", "range", "currency", "pribor_history") return an array of rows, but
+// point-in-time commands ("today", "date", "overview", "skd") return a single
+// object: e.g. bnr_data.py returns `"data": latest`, cnb_data.py returns
+// `"data": rows[0] if rows else {}`, tcmb_data.py returns `"data": snapshot`.
+// A bare .toArray() silently yields an empty array for all of those, so the
+// panel rendered "no data" for a request that actually succeeded. Normalise
+// both into a row list.
static QJsonArray extract_cb_rows(const QJsonObject& data) {
- return data["data"].toArray();
+ const QJsonValue payload = data["data"];
+ if (payload.isArray())
+ return payload.toArray();
+ if (payload.isObject()) {
+ const QJsonObject obj = payload.toObject();
+ if (obj.isEmpty())
+ return {};
+ // Some point-in-time payloads nest the real rows one level down
+ // (boi_data.py "overview" → {"data": {"rates": [...]}}). Prefer a
+ // nested array over presenting the wrapper object as a single row.
+ for (auto it = obj.begin(); it != obj.end(); ++it) {
+ if (it.value().isArray() && !it.value().toArray().isEmpty())
+ return it.value().toArray();
+ }
+ return QJsonArray{obj}; // genuine single row
+ }
+ return {};
}
// ── Panel ────────────────────────────────────────────────────────────────────
@@ -119,7 +243,9 @@ GlobalCentralBanksPanel::GlobalCentralBanksPanel(QWidget* parent)
void GlobalCentralBanksPanel::activate() {
show_empty(tr("Select a central bank and series, then click FETCH\n"
- "Sources: BOE, RBA, Bank of Canada, Riksbank, SNB, Norges Bank\n"
+ "Sources: BOE, RBA, Bank of Canada, Riksbank, SNB, Norges Bank,\n"
+ "CNB (Czechia), NBP (Poland), MNB (Hungary), BNR (Romania),\n"
+ "HNB (Croatia), TCMB (Türkiye), BOI (Israel), BNM (Malaysia)\n"
"No API key required for any source"));
}
diff --git a/fincept-qt/src/screens/economics/panels/IlostatPanel.cpp b/fincept-qt/src/screens/economics/panels/IlostatPanel.cpp
index c51c7ea48..995e7c125 100644
--- a/fincept-qt/src/screens/economics/panels/IlostatPanel.cpp
+++ b/fincept-qt/src/screens/economics/panels/IlostatPanel.cpp
@@ -42,7 +42,9 @@ IlostatPanel::IlostatPanel(QWidget* parent) : EconPanelBase(kIlostatSourceId, kI
void IlostatPanel::activate() {
show_empty(tr("Select a series, enter a country code, then click FETCH\n"
"Source: ILO ILOSTAT SDMX REST API (sdmx.ilo.org) — no API key required\n"
- "Country codes: USA, GBR, DEU, FRA, IND, CHN, JPN, BRA, ZAF, G7=CAN+USA+GBR+DEU+FRA+ITA+JPN"));
+ "Series are ANNUAL, both sexes, age 15+, harmonised (modelled) estimates — percent.\n"
+ "Country codes (ISO-3): USA, GBR, DEU, FRA, IND, CHN, JPN, BRA, ZAF · "
+ "G7 = CAN+USA+GBR+DEU+FRA+ITA+JPN"));
}
void IlostatPanel::build_controls(QHBoxLayout* thl) {
@@ -64,10 +66,13 @@ void IlostatPanel::build_controls(QHBoxLayout* thl) {
country_edit_ = new QLineEdit("USA");
country_edit_->setFixedHeight(26);
country_edit_->setFixedWidth(120);
- country_edit_->setPlaceholderText(tr("ISO-2 code…"));
- country_edit_->setToolTip(tr("ISO-2 country code, e.g. USA, GBR, DEU\n"
+ // ILOSTAT SDMX uses ISO-3166 alpha-3 (USA/GBR/DEU) — the field was
+ // mislabelled "ISO-2" while every example it gave was alpha-3.
+ country_edit_->setPlaceholderText(tr("ISO-3 code…"));
+ country_edit_->setToolTip(tr("ISO-3 country code, e.g. USA, GBR, DEU\n"
"Multiple: CAN+USA+GBR\n"
"All countries: ALL"));
+ country_edit_->setAccessibleName(tr("ILOSTAT country code"));
start_edit_ = new QLineEdit("2010");
start_edit_->setFixedHeight(26);
@@ -167,8 +172,8 @@ void IlostatPanel::retranslateUi() {
if (to_lbl_)
to_lbl_->setText(tr("TO"));
if (country_edit_) {
- country_edit_->setPlaceholderText(tr("ISO-2 code…"));
- country_edit_->setToolTip(tr("ISO-2 country code, e.g. USA, GBR, DEU\n"
+ country_edit_->setPlaceholderText(tr("ISO-3 code…"));
+ country_edit_->setToolTip(tr("ISO-3 country code, e.g. USA, GBR, DEU\n"
"Multiple: CAN+USA+GBR\n"
"All countries: ALL"));
}
diff --git a/fincept-qt/src/screens/economics/panels/ImfPanel.cpp b/fincept-qt/src/screens/economics/panels/ImfPanel.cpp
index 1aa6b642f..0feb973b9 100644
--- a/fincept-qt/src/screens/economics/panels/ImfPanel.cpp
+++ b/fincept-qt/src/screens/economics/panels/ImfPanel.cpp
@@ -156,6 +156,11 @@ void ImfPanel::on_result(const QString& request_id, const services::EconomicsRes
const QJsonArray rows = flatten_pivot(values, code, country);
const QString title = (ind_item ? ind_item->text() : code) +
(country.isEmpty() ? tr(" — All Countries") : " — " + country_combo_->currentText());
+ // "All Countries" produces a wide cross-section (one row per country,
+ // one column per year). LATEST/CHANGE/MIN/MAX/AVG would then be computed
+ // over an arbitrary single year column across unrelated countries — hide
+ // them rather than show a number nobody can interpret.
+ set_stats_visible(!country.isEmpty());
display(rows, title);
LOG_INFO("ImfPanel", QString("Displayed %1 rows").arg(rows.size()));
}
@@ -193,7 +198,9 @@ QJsonArray ImfPanel::flatten_pivot(const QJsonObject& values, const QString& ind
rows.append(row);
}
} else {
- // Long format: one row per year for selected country
+ // Long format: one row per year for selected country.
+ // `years` is already sorted ascending, and rows carrying no observation
+ // are dropped entirely (never emitted as 0) so gaps stay gaps.
const QJsonObject y_map = by_country[country_filter].toObject();
for (const auto& y : years) {
const QJsonValue v = y_map[y];
diff --git a/fincept-qt/src/screens/economics/panels/NberPanel.cpp b/fincept-qt/src/screens/economics/panels/NberPanel.cpp
new file mode 100644
index 000000000..5ec487ff9
--- /dev/null
+++ b/fincept-qt/src/screens/economics/panels/NberPanel.cpp
@@ -0,0 +1,163 @@
+// src/screens/economics/panels/NberPanel.cpp
+// NBER Business Cycle Dating Committee — US recession peaks/troughs.
+// Script: nber_data.py | No API key required.
+//
+// Response shapes (VERIFIED by running the script, 2026-07-25 — the payload key
+// differs per command, which is why extract_rows() below is keyed on it):
+// cycles → { source, url, total_cycles, latest_trough, current_status,
+// statistics{…}, cycles:[{peak,trough,expansion_months,
+// contraction_months,recession}] } ← 34 rows
+// recession → { start_date, end_date, indicator, source,
+// data:[{date,recession}] } ← 300 rows
+//
+// Only these two commands are exposed. nber_data.py also offers macro / cps /
+// unemployment / datasets, but those hit the network (unreachable from the
+// machine this was written on) or return a catalogue rather than a series, so
+// wiring them would have been guesswork. A control that looks wired and renders
+// nothing is worse than one that isn't there.
+#include "screens/economics/panels/NberPanel.h"
+
+#include "core/logging/Logger.h"
+#include "services/economics/EconomicsService.h"
+
+#include <QHBoxLayout>
+#include <QJsonArray>
+#include <QJsonObject>
+#include <QLabel>
+
+namespace fincept::screens {
+namespace {
+
+static constexpr const char* kNberScript = "nber_data.py";
+static constexpr const char* kNberSourceId = "nber";
+static constexpr const char* kNberColor = "#7C3AED"; // violet
+
+struct NberDataset {
+ QString label;
+ QString command;
+ QString payload_key; // the array key in the response — differs per command
+};
+
+} // namespace
+
+static const QList<NberDataset> kNberDatasets = {
+ {"Business Cycles (Peaks & Troughs)", "cycles", "cycles"},
+ {"Recession Indicator (Monthly)", "recession", "data"},
+};
+
+NberPanel::NberPanel(QWidget* parent) : EconPanelBase(kNberSourceId, kNberColor, parent) {
+ build_base_ui(this);
+ connect(&services::EconomicsService::instance(), &services::EconomicsService::result_ready, this,
+ &NberPanel::on_result);
+}
+
+void NberPanel::activate() {
+ show_empty(tr("Select a dataset and click FETCH\n"
+ "Source: NBER Business Cycle Dating Committee (nber.org)\n"
+ "No API key and no network required — the committee's dates ship with the app"));
+}
+
+void NberPanel::build_controls(QHBoxLayout* thl) {
+ dataset_lbl_ = new QLabel(tr("DATASET"));
+ // objectName instead of setStyleSheet(ctrl_label_style()): the rule lives in
+ // the container stylesheet EconPanelBase already applies, so this label
+ // costs no extra CSS parse. The other 30 panels still use the inline form;
+ // migrate them as they're touched.
+ dataset_lbl_->setObjectName(QStringLiteral("econCtrlLabel"));
+
+ dataset_combo_ = new QComboBox;
+ for (const auto& d : kNberDatasets)
+ dataset_combo_->addItem(d.label, d.command);
+ dataset_combo_->setFixedHeight(26);
+ dataset_combo_->setMinimumWidth(260);
+ dataset_combo_->setAccessibleName(tr("NBER dataset"));
+
+ thl->addWidget(dataset_lbl_);
+ thl->addWidget(dataset_combo_);
+}
+
+void NberPanel::on_fetch() {
+ const int idx = dataset_combo_->currentIndex();
+ if (idx < 0 || idx >= kNberDatasets.size())
+ return;
+ const auto& ds = kNberDatasets[idx];
+
+ show_loading(tr("Fetching NBER: %1…").arg(ds.label));
+
+ // EconomicsService::execute() prepends `command` to the argv — pass only
+ // extra positional args here (these two commands take none). Getting this
+ // wrong is not hypothetical: four economics panels shipped with the command
+ // duplicated, which shifted every subsequent argument and made the script
+ // answer a completely different query.
+ services::EconomicsService::instance().execute(kNberSourceId, kNberScript, ds.command, {}, "nber_" + ds.command);
+}
+
+void NberPanel::on_result(const QString& request_id, const services::EconomicsResult& result) {
+ if (result.source_id != kNberSourceId)
+ return;
+ if (!request_id.startsWith("nber_"))
+ return;
+ if (!result.success) {
+ show_error(result.error);
+ return;
+ }
+
+ const QString inline_err = result.data["error"].toString();
+ if (!inline_err.isEmpty()) {
+ show_error(inline_err);
+ return;
+ }
+
+ const int idx = dataset_combo_->currentIndex();
+ if (idx < 0 || idx >= kNberDatasets.size())
+ return;
+ const auto& ds = kNberDatasets[idx];
+
+ // nber_data.py emits no "success" key and no uniform "data" key — `cycles`
+ // puts its rows under "cycles", `recession` under "data". Read the key this
+ // dataset declares, then fall back so a future command still renders
+ // something rather than silently showing "no data".
+ QJsonArray rows = result.data[ds.payload_key].toArray();
+ if (rows.isEmpty())
+ rows = result.data["data"].toArray();
+
+ if (rows.isEmpty()) {
+ show_error(tr("No data returned"));
+ return;
+ }
+
+ QString title = QStringLiteral("NBER: ") + ds.label;
+ // The cycles response carries useful context the table itself cannot show.
+ const QString status = result.data["current_status"].toString();
+ const QString latest_trough = result.data["latest_trough"].toString();
+ if (!status.isEmpty())
+ title += QStringLiteral(" — ") + status;
+ if (!latest_trough.isEmpty())
+ title += tr(" (last trough %1)").arg(latest_trough);
+
+ display(rows, title);
+ LOG_INFO("NberPanel", QString("Displayed %1 rows: %2").arg(rows.size()).arg(ds.label));
+}
+
+// ── i18n ──────────────────────────────────────────────────────────────────────
+
+void NberPanel::changeEvent(QEvent* event) {
+ if (event->type() == QEvent::LanguageChange)
+ retranslateUi();
+ EconPanelBase::changeEvent(event);
+}
+
+void NberPanel::retranslateUi() {
+ if (dataset_lbl_)
+ dataset_lbl_->setText(tr("DATASET"));
+ if (dataset_combo_) {
+ const int cur = dataset_combo_->currentIndex();
+ for (int i = 0; i < kNberDatasets.size() && i < dataset_combo_->count(); ++i)
+ dataset_combo_->setItemText(i, kNberDatasets[i].label);
+ dataset_combo_->setCurrentIndex(cur);
+ dataset_combo_->setAccessibleName(tr("NBER dataset"));
+ }
+ EconPanelBase::retranslateUi();
+}
+
+} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/economics/panels/NberPanel.h b/fincept-qt/src/screens/economics/panels/NberPanel.h
new file mode 100644
index 000000000..945ecbeb1
--- /dev/null
+++ b/fincept-qt/src/screens/economics/panels/NberPanel.h
@@ -0,0 +1,37 @@
+#pragma once
+// NBER Business Cycle Dating — US recession peaks/troughs and a monthly
+// recession indicator, from the NBER Business Cycle Dating Committee.
+//
+// Script: nber_data.py | No API key required.
+// The two exposed commands run entirely OFFLINE (the committee's dates are
+// embedded in the script), which makes this one of the few economics panels
+// that works with no network at all.
+
+#include "screens/economics/panels/EconPanelBase.h"
+
+#include <QComboBox>
+#include <QLabel>
+
+namespace fincept::screens {
+
+class NberPanel : public EconPanelBase {
+ Q_OBJECT
+ public:
+ explicit NberPanel(QWidget* parent = nullptr);
+
+ void activate() override;
+
+ protected:
+ void build_controls(QHBoxLayout* toolbar_layout) override;
+ void on_fetch() override;
+ void on_result(const QString& request_id, const services::EconomicsResult& result) override;
+
+ void changeEvent(QEvent* event) override;
+ void retranslateUi() override;
+
+ private:
+ QLabel* dataset_lbl_ = nullptr;
+ QComboBox* dataset_combo_ = nullptr;
+};
+
+} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/economics/panels/TradingEconomicsPanel.cpp b/fincept-qt/src/screens/economics/panels/TradingEconomicsPanel.cpp
index f09250fec..c527f7bf9 100644
--- a/fincept-qt/src/screens/economics/panels/TradingEconomicsPanel.cpp
+++ b/fincept-qt/src/screens/economics/panels/TradingEconomicsPanel.cpp
@@ -86,13 +86,17 @@ void TradingEconomicsPanel::on_fetch() {
show_loading(tr("Fetching Trading Economics: %1…").arg(dataset.label));
- QStringList args = {dataset.command};
+ // EconomicsService::execute() prepends `command` to the argv. Repeating it
+ // here made the script read the command name as the country
+ // (`yield_curve yield_curve US` → country="yield_curve"), so every
+ // country-scoped Trading Economics query hit the wrong endpoint.
+ QStringList args;
if (dataset.country_arg == "required" || dataset.country_arg == "optional")
args << country;
services::EconomicsService::instance().execute(kTradingEconomicsSourceId, kTradingEconomicsScript, dataset.command,
args,
- "te_" + dataset.command + (args.size() > 1 ? "_" + country : ""));
+ "te_" + dataset.command + (args.isEmpty() ? "" : "_" + country));
}
// Normalise various Trading Economics response shapes into displayable rows.
diff --git a/fincept-qt/src/screens/economics/panels/UnComtradePanel.cpp b/fincept-qt/src/screens/economics/panels/UnComtradePanel.cpp
index 0aedef0d6..0b04cd72d 100644
--- a/fincept-qt/src/screens/economics/panels/UnComtradePanel.cpp
+++ b/fincept-qt/src/screens/economics/panels/UnComtradePanel.cpp
@@ -33,8 +33,10 @@ UnComtradePanel::UnComtradePanel(QWidget* parent) : EconPanelBase(kUnComtradeSou
}
void UnComtradePanel::activate() {
- show_empty(tr("Select reporter, flow, and period, then click FETCH\n"
- "(Free tier: up to 250 records per request)"));
+ show_empty(tr("Select reporter, flow, year and commodity level, then click FETCH\n"
+ "Source: UN Comtrade — annual (A) merchandise trade, HS classification\n"
+ "Values are current US dollars. Free tier: up to 500 records per request;\n"
+ "set UN_COMTRADE_API_KEY for 100,000 records/call (register at comtradedeveloper.un.org)"));
}
void UnComtradePanel::build_controls(QHBoxLayout* thl) {
@@ -64,8 +66,8 @@ void UnComtradePanel::build_controls(QHBoxLayout* thl) {
period_combo_->setFixedHeight(26);
cmd_combo_ = new QComboBox;
- cmd_combo_->addItem(tr("All Commodities"), "AG2");
- cmd_combo_->addItem(tr("Total (all)"), "TOTAL");
+ cmd_combo_->addItem(tr("Total (all commodities)"), "TOTAL");
+ cmd_combo_->addItem(tr("HS 2-digit chapters"), "AG2");
cmd_combo_->setFixedHeight(26);
thl->addWidget(reporter_lbl_ = lbl(tr("REPORTER")));
@@ -74,17 +76,29 @@ void UnComtradePanel::build_controls(QHBoxLayout* thl) {
thl->addWidget(flow_combo_);
thl->addWidget(year_lbl_ = lbl(tr("YEAR")));
thl->addWidget(period_combo_);
+ // The commodity selector used to be built but never added to the toolbar —
+ // an unreachable, un-parented widget that also leaked.
+ thl->addWidget(cmd_lbl_ = lbl(tr("COMMODITY")));
+ thl->addWidget(cmd_combo_);
}
void UnComtradePanel::on_fetch() {
const QString reporter = reporter_combo_->currentData().toString();
const QString period = period_combo_->currentData().toString();
const QString flow = flow_combo_->currentData().toString();
-
- show_loading(tr("Fetching UN Comtrade data…"));
- services::EconomicsService::instance().execute(kUnComtradeSourceId, kUnComtradeScript, "trade_balance",
- {reporter, period},
- "comtrade_" + reporter + "_" + period + "_" + flow);
+ const QString cmd_code = cmd_combo_->currentData().toString();
+
+ // Was: `trade_balance <reporter> <period>` — that endpoint takes NO flow
+ // argument (so the FLOW selector only changed the title, never the data)
+ // and it requires a UN_COMTRADE_API_KEY, so the key-free default path
+ // always errored. `trade_data` honours flow + commodity and works on the
+ // free preview tier.
+ // CLI: trade_data <reporter_code> <period> [flow_code] [cmd_code]
+ show_loading(tr("Fetching UN Comtrade: %1 %2 %3…")
+ .arg(reporter_combo_->currentText(), flow_combo_->currentText(), period));
+ services::EconomicsService::instance().execute(kUnComtradeSourceId, kUnComtradeScript, "trade_data",
+ {reporter, period, flow, cmd_code},
+ "comtrade_" + reporter + "_" + period + "_" + flow + "_" + cmd_code);
}
void UnComtradePanel::on_result(const QString& request_id, const services::EconomicsResult& result) {
@@ -97,8 +111,17 @@ void UnComtradePanel::on_result(const QString& request_id, const services::Econo
if (request_id.startsWith("comtrade_")) {
const QJsonArray arr = result.data["data"].toArray();
- const QString title =
- reporter_combo_->currentText() + " — " + flow_combo_->currentText() + " " + period_combo_->currentText();
+ if (arr.isEmpty()) {
+ show_empty(tr("No trade records returned for this reporter/flow/year.\n"
+ "Free tier is capped at 500 records — set UN_COMTRADE_API_KEY for full access."));
+ return;
+ }
+ // One row per commodity line for a single year is a cross-section, not a
+ // time series — the aggregate stat cards would be meaningless.
+ set_stats_visible(cmd_combo_->currentData().toString() == QLatin1String("TOTAL"));
+ const QString title = "UN Comtrade: " + reporter_combo_->currentText() + " — " +
+ flow_combo_->currentText() + " " + period_combo_->currentText() + " (" +
+ cmd_combo_->currentText() + ")";
display(arr, title);
LOG_INFO("UnComtradePanel", QString("Displayed %1 rows").arg(arr.size()));
}
@@ -119,15 +142,17 @@ void UnComtradePanel::retranslateUi() {
flow_lbl_->setText(tr("FLOW"));
if (year_lbl_)
year_lbl_->setText(tr("YEAR"));
- if (flow_combo_) {
+ if (cmd_lbl_)
+ cmd_lbl_->setText(tr("COMMODITY"));
+ if (flow_combo_ && flow_combo_->count() >= 4) {
flow_combo_->setItemText(0, tr("Exports"));
flow_combo_->setItemText(1, tr("Imports"));
flow_combo_->setItemText(2, tr("Re-exports"));
flow_combo_->setItemText(3, tr("Re-imports"));
}
- if (cmd_combo_) {
- cmd_combo_->setItemText(0, tr("All Commodities"));
- cmd_combo_->setItemText(1, tr("Total (all)"));
+ if (cmd_combo_ && cmd_combo_->count() >= 2) {
+ cmd_combo_->setItemText(0, tr("Total (all commodities)"));
+ cmd_combo_->setItemText(1, tr("HS 2-digit chapters"));
}
EconPanelBase::retranslateUi();
}
diff --git a/fincept-qt/src/screens/economics/panels/UnComtradePanel.h b/fincept-qt/src/screens/economics/panels/UnComtradePanel.h
index 5c36b9390..027be255c 100644
--- a/fincept-qt/src/screens/economics/panels/UnComtradePanel.h
+++ b/fincept-qt/src/screens/economics/panels/UnComtradePanel.h
@@ -34,6 +34,7 @@ class UnComtradePanel : public EconPanelBase {
QLabel* reporter_lbl_ = nullptr;
QLabel* flow_lbl_ = nullptr;
QLabel* year_lbl_ = nullptr;
+ QLabel* cmd_lbl_ = nullptr;
};
} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/economics/panels/UnescoPanel.cpp b/fincept-qt/src/screens/economics/panels/UnescoPanel.cpp
index 6444729b7..c3a67cef0 100644
--- a/fincept-qt/src/screens/economics/panels/UnescoPanel.cpp
+++ b/fincept-qt/src/screens/economics/panels/UnescoPanel.cpp
@@ -26,6 +26,8 @@
#include <QSplitter>
#include <QVBoxLayout>
+#include <utility>
+
namespace fincept::screens {
namespace {
@@ -134,8 +136,14 @@ UnescoPanel::UnescoPanel(QWidget* parent) : EconPanelBase(kUnescoSourceId, kUnes
void UnescoPanel::activate() {
show_empty(tr("Select a theme, indicator and country code, then click FETCH\n"
- "UNESCO UIS data is free — no API key required\n"
+ "Source: UNESCO Institute for Statistics (UIS) — free, no API key required\n"
"Use 3-letter ISO country codes: USA, GBR, IND, CHN, BRA, DEU"));
+ // Replace the curated fallback list with the live UIS indicator catalogue
+ // once per session. load_indicators() existed but was never called, so the
+ // `unesco_list_indicators` branch in on_result() was unreachable and the
+ // panel could only ever offer the ~26 hard-coded presets.
+ if (!indicators_loaded_)
+ load_indicators();
}
// ── Controls ──────────────────────────────────────────────────────────────────
@@ -171,7 +179,51 @@ void UnescoPanel::build_controls(QHBoxLayout* thl) {
thl->addWidget(end_input_);
}
+// Repopulate the indicator list from the live UIS catalogue for the given
+// theme index. Returns false (leaving the list untouched) when the catalogue
+// has nothing for that theme, so the curated presets stay in place.
+bool UnescoPanel::populate_indicators_from_records(int theme_index, const QString& keep_code) {
+ if (all_records_.isEmpty())
+ return false;
+ static const char* kThemeKeys[] = {"EDUCATION", "SCIENCE", "CULTURE"};
+ const QString theme_key =
+ QLatin1String(kThemeKeys[(theme_index >= 0 && theme_index < 3) ? theme_index : 0]);
+
+ QList<IndicatorDef> found;
+ for (const auto& v : std::as_const(all_records_)) {
+ const auto obj = v.toObject();
+ if (!obj["theme"].toString().contains(theme_key, Qt::CaseInsensitive))
+ continue;
+ const QString id = obj["id"].toString();
+ if (id.isEmpty())
+ continue;
+ found.append({obj["name"].toString(id), id});
+ }
+ if (found.isEmpty())
+ return false;
+
+ current_indicators_ = found;
+ indicator_list_->clear();
+ int restore_row = -1;
+ for (int i = 0; i < found.size(); ++i) {
+ auto* item = new QListWidgetItem(found[i].name);
+ item->setData(Qt::UserRole, found[i].code);
+ item->setToolTip(found[i].code);
+ indicator_list_->addItem(item);
+ if (!keep_code.isEmpty() && found[i].code == keep_code)
+ restore_row = i;
+ }
+ indicator_list_->setCurrentRow(restore_row >= 0 ? restore_row : 0);
+ // Re-apply any active text filter to the freshly built list.
+ on_indicator_filter(indicator_search_->text());
+ return true;
+}
+
void UnescoPanel::on_theme_changed(int index) {
+ // Prefer the live catalogue once it has loaded.
+ if (populate_indicators_from_records(index, QString()))
+ return;
+
current_indicators_.clear();
indicator_list_->clear();
indicator_search_->clear();
@@ -250,27 +302,18 @@ void UnescoPanel::on_result(const QString& request_id, const services::Economics
// Handle live indicator list load
if (request_id == "unesco_list_indicators") {
// data: { "records": [{"id": "GER.1", "name": "...", "theme": "EDUCATION"}] }
+ if (!result.success)
+ return; // keep the curated preset list as the fallback
const QJsonArray records = result.data["data"].toObject()["records"].toArray();
if (records.isEmpty())
return;
- const QString current_theme = theme_combo_->currentData().toString().toUpper();
- indicator_list_->clear();
- current_indicators_.clear();
-
- for (const auto& v : records) {
- const auto obj = v.toObject();
- const QString theme = obj["theme"].toString();
- if (!current_theme.isEmpty() && !theme.contains(current_theme, Qt::CaseInsensitive))
- continue;
- const QString id = obj["id"].toString();
- const QString name = obj["name"].toString();
- current_indicators_.append({name, id});
- auto* item = new QListWidgetItem(name);
- item->setData(Qt::UserRole, id);
- item->setToolTip(id);
- indicator_list_->addItem(item);
- }
+ all_records_ = records;
+ // Remember what the user had selected so a background catalogue load
+ // doesn't silently move their selection.
+ const QString keep_code =
+ indicator_list_->currentItem() ? indicator_list_->currentItem()->data(Qt::UserRole).toString() : QString();
+ populate_indicators_from_records(theme_combo_->currentIndex(), keep_code);
return;
}
diff --git a/fincept-qt/src/screens/economics/panels/UnescoPanel.h b/fincept-qt/src/screens/economics/panels/UnescoPanel.h
index 620c268a1..679c3e0a9 100644
--- a/fincept-qt/src/screens/economics/panels/UnescoPanel.h
+++ b/fincept-qt/src/screens/economics/panels/UnescoPanel.h
@@ -27,6 +27,10 @@ class UnescoPanel : public EconPanelBase {
private:
void load_indicators();
+ /// Rebuild the indicator list from the live UIS catalogue (all_records_)
+ /// for `theme_index`, restoring `keep_code` if still present.
+ /// Returns false when the catalogue has no entry for that theme.
+ bool populate_indicators_from_records(int theme_index, const QString& keep_code);
void on_theme_changed(int index);
void on_indicator_filter(const QString& text);
void retranslateUi() override;
@@ -50,6 +54,8 @@ class UnescoPanel : public EconPanelBase {
QString code;
};
QList<IndicatorDef> current_indicators_;
+ /// Raw `list_indicators` catalogue records, cached for theme re-filtering.
+ QJsonArray all_records_;
bool indicators_loaded_ = false;
};
diff --git a/fincept-qt/src/screens/economics/panels/WorldBankHealthPanel.cpp b/fincept-qt/src/screens/economics/panels/WorldBankHealthPanel.cpp
index 297ed7471..da3b0a56c 100644
--- a/fincept-qt/src/screens/economics/panels/WorldBankHealthPanel.cpp
+++ b/fincept-qt/src/screens/economics/panels/WorldBankHealthPanel.cpp
@@ -32,9 +32,29 @@ struct WbHealthIndicator {
};
static const QList<WbHealthIndicator> kWbHealthIndicators = {
- {"Life Expectancy", "life_expectancy", "years"}, {"Infant Mortality Rate", "infant_mortality", "per 1,000"},
- {"Literacy Rate (Adult)", "literacy", "%"}, {"Gini Index (Inequality)", "gini", "index"},
- {"Human Development Index", "hdi", "index"}, {"Poverty Rate ($2.15/day)", "poverty", "%"},
+ {"Life Expectancy", "life_expectancy", "years"},
+ {"Infant Mortality Rate", "infant_mortality", "per 1,000"},
+ {"Literacy Rate (Adult)", "literacy", "%"},
+ {"Gini Index (Inequality)", "gini", "index"},
+ // WAS: {"Human Development Index", "hdi", "index"} — that was wrong in a way
+ // that produced a confident, plausible, and completely different number.
+ //
+ // HDI is published by UNDP, not the World Bank, and the World Bank has no
+ // HDI series. worldbank_health_data.py is honest about this internally: the
+ // "hdi" command calls get_hdi_proxy(), which fetches NY.GNP.PCAP.PP.KD —
+ // GNI per capita, PPP, in constant international dollars. The panel then
+ // presented that five-figure dollar amount as "Human Development Index"
+ // with unit "index". Real HDI is a 0–1 composite of life expectancy,
+ // education and income, so a user comparing this against a published HDI
+ // table would find no relationship whatsoever.
+ //
+ // Relabelled to what the data actually is. Real HDI is available from
+ // scripts/undp_data.py (commands: hdi, gii, mpi) but is NOT wired here: it
+ // requires UNDP_API_KEY and returns the UNDP HDR API's own shape, which
+ // flatten_wb() — which expects World Bank's `records` array — cannot parse.
+ // Wiring it needs a second flattener and a key, and is tracked separately.
+ {"GNI per Capita (PPP, HDI proxy)", "hdi", "int'l $"},
+ {"Poverty Rate ($2.15/day)", "poverty", "%"},
};
static const QList<QPair<QString, QString>> kWbHealthCountries = {
@@ -56,7 +76,6 @@ QJsonArray WorldBankHealthPanel::flatten_wb(const QJsonObject& response) {
if (r["value"].isNull() || r["value"].isUndefined())
continue;
const double val = r["value"].toDouble();
- // Skip placeholder zeros for HDI/similar where 0 is not meaningful
QJsonObject row;
row["date"] = r["date"].toString();
row["value"] = val;
@@ -84,7 +103,8 @@ WorldBankHealthPanel::WorldBankHealthPanel(QWidget* parent)
void WorldBankHealthPanel::activate() {
show_empty(tr("Select an indicator and country, then click FETCH\n"
- "Source: World Bank — Health & Development indicators"));
+ "Source: World Bank Open Data (World Development Indicators) — CC BY-4.0\n"
+ "Annual observations; years with no survey are omitted, not zero-filled"));
}
void WorldBankHealthPanel::build_controls(QHBoxLayout* thl) {
diff --git a/fincept-qt/src/screens/equity_research/EquityAnalysisTab.cpp b/fincept-qt/src/screens/equity_research/EquityAnalysisTab.cpp
index 768e55893..ad020176f 100644
--- a/fincept-qt/src/screens/equity_research/EquityAnalysisTab.cpp
+++ b/fincept-qt/src/screens/equity_research/EquityAnalysisTab.cpp
@@ -195,6 +195,13 @@ EquityAnalysisTab::EquityAnalysisTab(QWidget* parent) : QWidget(parent) {
build_ui();
auto& svc = services::equity::EquityResearchService::instance();
connect(&svc, &services::equity::EquityResearchService::info_loaded, this, &EquityAnalysisTab::on_info_loaded);
+ // The overlay was only ever hidden on the success path, so a failed "Info"
+ // fetch left "LOADING ANALYSIS…" spinning over the tab forever.
+ connect(&svc, &services::equity::EquityResearchService::error_occurred, this,
+ [this](const QString& ctx, const QString&) {
+ if (ctx == QLatin1String("Info") && loading_overlay_)
+ loading_overlay_->hide_loading();
+ });
}
void EquityAnalysisTab::set_symbol(const QString& symbol) {
diff --git a/fincept-qt/src/screens/equity_research/EquityNewsTab.cpp b/fincept-qt/src/screens/equity_research/EquityNewsTab.cpp
index fe0530845..165742bff 100644
--- a/fincept-qt/src/screens/equity_research/EquityNewsTab.cpp
+++ b/fincept-qt/src/screens/equity_research/EquityNewsTab.cpp
@@ -254,27 +254,22 @@ void EquityNewsTab::populate(const QVector<services::equity::NewsArticle>& artic
.arg(ui::colors::AMBER()));
cl->addWidget(read_lbl);
- // Whole card opens URL
- QString url = art.url;
- auto* click_filter = new QObject(card);
- card->installEventFilter(click_filter);
- connect(click_filter, &QObject::destroyed, this, [] {});
- // Use QPushButton invisible overlay approach via event filter on card
- QObject::connect(card, &QFrame::destroyed, click_filter, &QObject::deleteLater);
-
- // Simpler: intercept mouse release via child button spanning the card
- auto* link_btn = new QPushButton;
- link_btn->setFlat(true);
- link_btn->setCursor(Qt::PointingHandCursor);
- link_btn->setStyleSheet("QPushButton { background:transparent; border:0; }");
- link_btn->setFixedSize(0, 0); // invisible, just for signal
- connect(link_btn, &QPushButton::clicked, this, [url]() { QDesktopServices::openUrl(QUrl(url)); });
-
- // Make the read_lbl clickable
+ // The whole card is the click target (it already shows a hand cursor).
+ // Previously the card's "click filter" was a bare QObject with no
+ // eventFilter override and the link button was sized 0×0, so only the
+ // small "READ FULL ARTICLE" line worked — three dead objects per card
+ // on every refresh. One filter (this) + a url property on both widgets.
+ const QString url = art.url;
read_lbl->setCursor(Qt::PointingHandCursor);
- read_lbl->installEventFilter(this);
read_lbl->setProperty("url", url);
- cl->addWidget(link_btn);
+ read_lbl->installEventFilter(this);
+ card->setProperty("url", url);
+ card->installEventFilter(this);
+ card->setToolTip(tr("Open in browser: %1").arg(url));
+ card->setAccessibleName(art.title);
+ card->setAccessibleDescription(tr("Open the full article in your browser"));
+ } else {
+ card->setCursor(Qt::ArrowCursor); // nothing to open — don't imply a link
}
cards_layout_->insertWidget(cards_layout_->count() - 1, card);
diff --git a/fincept-qt/src/screens/equity_research/EquityOverviewTab.cpp b/fincept-qt/src/screens/equity_research/EquityOverviewTab.cpp
index 0432b3dbb..304fb83f5 100644
--- a/fincept-qt/src/screens/equity_research/EquityOverviewTab.cpp
+++ b/fincept-qt/src/screens/equity_research/EquityOverviewTab.cpp
@@ -281,6 +281,17 @@ EquityOverviewTab::EquityOverviewTab(QWidget* parent) : QWidget(parent) {
connect(&svc, &services::equity::EquityResearchService::info_loaded, this, &EquityOverviewTab::on_info_loaded);
connect(&svc, &services::equity::EquityResearchService::historical_loaded, this,
&EquityOverviewTab::on_historical_loaded);
+ // Overview waits on three legs (quote / info / historical) and only hides the
+ // overlay on success, so any one failing left "LOADING OVERVIEW…" spinning
+ // over the tab with no way to dismiss it.
+ connect(&svc, &services::equity::EquityResearchService::error_occurred, this,
+ [this](const QString& ctx, const QString&) {
+ if (!loading_overlay_)
+ return;
+ if (ctx == QLatin1String("Quote") || ctx == QLatin1String("Info") ||
+ ctx == QLatin1String("Historical"))
+ loading_overlay_->hide_loading();
+ });
}
void EquityOverviewTab::set_symbol(const QString& symbol) {
diff --git a/fincept-qt/src/screens/equity_trading/AccountManagementDialog.cpp b/fincept-qt/src/screens/equity_trading/AccountManagementDialog.cpp
index bf3026944..344bd1158 100644
--- a/fincept-qt/src/screens/equity_trading/AccountManagementDialog.cpp
+++ b/fincept-qt/src/screens/equity_trading/AccountManagementDialog.cpp
@@ -368,20 +368,51 @@ void AccountManagementDialog::setup_ui() {
approval_mode_combo_->addItem(tr("Auto — execute immediately"), "auto");
approval_mode_combo_->addItem(tr("Semi-Auto — require approval"), "semi_auto");
approval_mode_combo_->setEnabled(false); // enabled once an account is selected
+ approval_mode_combo_->setAccessibleName(tr("Order approval mode"));
approval_row->addWidget(approval_mode_combo_, 1);
right_col->addLayout(approval_row);
+ // Auto is the default, and on a LIVE account it means the BUY/SELL button
+ // sends a real order with no confirmation at all. Say so, in place.
+ approval_warning_ = new QLabel;
+ approval_warning_->setWordWrap(true);
+ approval_warning_->setStyleSheet(QString("color:%1;font-size:10px;font-weight:700;").arg(colors::NEGATIVE()));
+ approval_warning_->setVisible(false);
+ right_col->addWidget(approval_warning_);
+
// Persist immediately on change (independent of the async CONNECT flow).
connect(approval_mode_combo_, &QComboBox::currentIndexChanged, this, [this](int) {
if (selected_account_id_.isEmpty())
return;
ActionCenter::instance().set_order_mode(selected_account_id_,
parse_order_mode(approval_mode_combo_->currentData().toString()));
+ update_approval_warning();
});
root->addLayout(right_col, 2);
}
+// Auto mode on a LIVE account means orders leave for the exchange with no
+// confirmation step anywhere in the UI. Make that explicit where the setting is.
+void AccountManagementDialog::update_approval_warning() {
+ if (!approval_warning_ || !approval_mode_combo_)
+ return;
+ if (selected_account_id_.isEmpty()) {
+ approval_warning_->setVisible(false);
+ return;
+ }
+ const auto account = AccountManager::instance().get_account(selected_account_id_);
+ const bool is_live = account.trading_mode == QLatin1String("live");
+ const bool is_auto = approval_mode_combo_->currentData().toString() == QLatin1String("auto");
+ if (is_live && is_auto) {
+ approval_warning_->setText(tr("\xe2\x9a\xa0 LIVE + Auto: BUY / SELL sends a real order immediately, with no "
+ "confirmation dialog. Choose Semi-Auto to review every order first."));
+ approval_warning_->setVisible(true);
+ } else {
+ approval_warning_->setVisible(false);
+ }
+}
+
void AccountManagementDialog::changeEvent(QEvent* event) {
if (event->type() == QEvent::LanguageChange)
retranslateUi();
@@ -414,6 +445,7 @@ void AccountManagementDialog::retranslateUi() {
approval_mode_combo_->setItemText(0, tr("Auto — execute immediately"));
approval_mode_combo_->setItemText(1, tr("Semi-Auto — require approval"));
}
+ update_approval_warning();
// Per-broker form bottom buttons (built lazily — guarded). Their dynamic
// status text and the account-driven titles are reapplied by
@@ -461,6 +493,7 @@ void AccountManagementDialog::on_account_selected(int row) {
if (approval_mode_combo_)
approval_mode_combo_->setEnabled(false);
selected_account_id_.clear();
+ update_approval_warning();
return;
}
@@ -475,6 +508,7 @@ void AccountManagementDialog::on_account_selected(int row) {
approval_mode_combo_->setCurrentIndex(mode == OrderMode::SemiAuto ? 1 : 0);
approval_mode_combo_->setEnabled(true);
}
+ update_approval_warning();
auto account = AccountManager::instance().get_account(selected_account_id_);
auto* broker = BrokerRegistry::instance().get(account.broker_id);
@@ -1262,7 +1296,11 @@ void AccountManagementDialog::on_connect_zerodha_manual_paste() {
return;
}
// Accept either a raw token or the full redirect URL (e.g. "https://127.0.0.1/?request_token=...&status=success").
- LOG_INFO("Zerodha", QString("manual paste input (%1 chars): %2").arg(token.length()).arg(token));
+ // NEVER log the pasted text itself — it is (or contains) a live broker
+ // request_token, i.e. a credential. Log only its shape (CLAUDE.md P14).
+ LOG_INFO("Zerodha", QString("manual paste input: %1 chars, looks like a URL: %2")
+ .arg(token.length())
+ .arg(token.startsWith(QStringLiteral("http"), Qt::CaseInsensitive) ? "yes" : "no"));
if (token.contains(QStringLiteral("request_token"), Qt::CaseInsensitive)) {
const QUrl url = token.startsWith(QStringLiteral("http"), Qt::CaseInsensitive)
? QUrl(token)
@@ -1271,7 +1309,7 @@ void AccountManagementDialog::on_connect_zerodha_manual_paste() {
if (!extracted.isEmpty())
token = extracted;
}
- LOG_INFO("Zerodha", QString("manual paste extracted token: %1").arg(token));
+ LOG_INFO("Zerodha", QString("manual paste: extracted a %1-char request_token").arg(token.length()));
if (token.contains(QLatin1Char('/')) || token.contains(QLatin1Char('?')) || token.contains(QLatin1Char('='))) {
z_status_->setText(tr("Could not find request_token in pasted text"));
z_status_->setStyleSheet(QString("color:%1;").arg(colors::NEGATIVE()));
@@ -1540,7 +1578,10 @@ void AccountManagementDialog::on_connect_fyers_manual_paste() {
f_status_->setStyleSheet(QString("color:%1;").arg(colors::NEGATIVE()));
return;
}
- LOG_INFO("Fyers", QString("manual paste input (%1 chars): %2").arg(token.length()).arg(token));
+ // The pasted text is a live auth_code — log its shape only, never the value.
+ LOG_INFO("Fyers", QString("manual paste input: %1 chars, looks like a URL: %2")
+ .arg(token.length())
+ .arg(token.startsWith(QStringLiteral("http"), Qt::CaseInsensitive) ? "yes" : "no"));
if (token.contains(QStringLiteral("auth_code"), Qt::CaseInsensitive)) {
const QUrl url = token.startsWith(QStringLiteral("http"), Qt::CaseInsensitive)
? QUrl(token)
@@ -1549,7 +1590,7 @@ void AccountManagementDialog::on_connect_fyers_manual_paste() {
if (!extracted.isEmpty())
token = extracted;
}
- LOG_INFO("Fyers", QString("manual paste extracted token: %1").arg(token.left(40) + "..."));
+ LOG_INFO("Fyers", QString("manual paste: extracted a %1-char auth_code").arg(token.length()));
BrokerCredentials creds;
creds.broker_id = "fyers";
diff --git a/fincept-qt/src/screens/equity_trading/AccountManagementDialog.h b/fincept-qt/src/screens/equity_trading/AccountManagementDialog.h
index 3fdac3f17..2afd9bd77 100644
--- a/fincept-qt/src/screens/equity_trading/AccountManagementDialog.h
+++ b/fincept-qt/src/screens/equity_trading/AccountManagementDialog.h
@@ -49,6 +49,8 @@ class AccountManagementDialog : public QDialog {
void on_rename_account();
void build_credential_form(const trading::BrokerProfile& profile);
void load_saved_credentials(const QString& account_id);
+ // Show/hide the "LIVE + Auto = no confirmation" banner under the approval combo.
+ void update_approval_warning();
// Zerodha-specific form + handlers
void build_zerodha_form();
@@ -98,6 +100,7 @@ class AccountManagementDialog : public QDialog {
// including the dedicated Zerodha/Fyers/MT4 forms.
QLabel* approval_caption_ = nullptr;
QComboBox* approval_mode_combo_ = nullptr;
+ QLabel* approval_warning_ = nullptr;
// Dynamic credential fields (rebuilt per broker profile)
QVector<QLineEdit*> cred_fields_;
diff --git a/fincept-qt/src/screens/equity_trading/BasketOrdersDialog.cpp b/fincept-qt/src/screens/equity_trading/BasketOrdersDialog.cpp
index cd5a4abc5..6581de4aa 100644
--- a/fincept-qt/src/screens/equity_trading/BasketOrdersDialog.cpp
+++ b/fincept-qt/src/screens/equity_trading/BasketOrdersDialog.cpp
@@ -1,6 +1,7 @@
#include "screens/equity_trading/BasketOrdersDialog.h"
#include "trading/AccountManager.h"
+#include "trading/ActionCenter.h"
#include "trading/BrokerRegistry.h"
#include "trading/UnifiedTrading.h"
#include "ui/theme/Theme.h"
@@ -347,14 +348,39 @@ void BasketOrdersDialog::on_execute() {
if (ret != QMessageBox::Yes)
return;
- execute_btn_->setEnabled(false);
- status_label_->setText(tr("Executing on %1 account(s)…").arg(selected.size()));
- status_label_->setStyleSheet("color:#d97706;font-size:11px;");
-
trading::BasketOrderRequest req;
req.orders = b->legs;
req.strategy_name = b->name;
+ // Semi-Auto gate. Every other order path in the terminal (order ticket,
+ // BroadcastOrderDialog, options strategies) consults ActionCenter before
+ // sending; this one did not, so a basket bypassed the approval queue on an
+ // account explicitly configured to require approval.
+ QStringList immediate;
+ int queued = 0;
+ for (const QString& acct_id : selected) {
+ if (trading::ActionCenter::instance().should_queue(acct_id, "basketorder")) {
+ const QString pid = trading::ActionCenter::instance().queue_order(
+ acct_id, "basketorder", trading::ActionCenter::serialize_basket_order(req));
+ if (!pid.isEmpty())
+ ++queued;
+ } else {
+ immediate.append(acct_id);
+ }
+ }
+ if (immediate.isEmpty()) {
+ status_label_->setText(tr("%1 basket(s) queued for approval").arg(queued));
+ status_label_->setStyleSheet(QString("color:%1;font-size:11px;").arg(colors::AMBER()));
+ return;
+ }
+
+ execute_btn_->setEnabled(false);
+ status_label_->setText(queued > 0 ? tr("Executing on %1 account(s); %2 queued for approval…")
+ .arg(immediate.size())
+ .arg(queued)
+ : tr("Executing on %1 account(s)…").arg(immediate.size()));
+ status_label_->setStyleSheet("color:#d97706;font-size:11px;");
+
// place_basket_orders runs on its own background thread per call and
// invokes the callback on this (caller's) thread. Aggregate across accounts.
struct Tally {
@@ -364,13 +390,13 @@ void BasketOrdersDialog::on_execute() {
QStringList errors;
};
auto tally = std::make_shared<Tally>();
- tally->pending = int(selected.size());
+ tally->pending = int(immediate.size());
QPointer<BasketOrdersDialog> self(this);
- for (const QString& acct_id : selected) {
+ for (const QString& acct_id : immediate) {
const QString label = trading::AccountManager::instance().get_account(acct_id).display_name;
trading::UnifiedTrading::instance().place_basket_orders(
- acct_id, req, [self, tally, label](const trading::BasketOrderResult& r) {
+ acct_id, req, [self, tally, label, queued](const trading::BasketOrderResult& r) {
if (!self)
return;
tally->ok += r.successful;
@@ -380,6 +406,8 @@ void BasketOrdersDialog::on_execute() {
tally->errors << QString("%1/%2: %3").arg(label, or_.symbol, or_.error);
if (--tally->pending == 0) {
QString msg = tr("✓ %1 leg(s) placed").arg(tally->ok);
+ if (queued > 0)
+ msg += tr(", %1 basket(s) queued for approval").arg(queued);
if (tally->fail > 0)
msg += tr(" — ✗ %1 failed: %2").arg(tally->fail).arg(tally->errors.join("; "));
self->status_label_->setText(msg);
diff --git a/fincept-qt/src/screens/equity_trading/EquityBottomPanel.cpp b/fincept-qt/src/screens/equity_trading/EquityBottomPanel.cpp
index a6e215b5a..c469f2a8b 100644
--- a/fincept-qt/src/screens/equity_trading/EquityBottomPanel.cpp
+++ b/fincept-qt/src/screens/equity_trading/EquityBottomPanel.cpp
@@ -20,6 +20,7 @@
#include <QPushButton>
#include <QScrollArea>
#include <QScrollBar>
+#include <QSet>
#include <QSplitter>
#include <QStackedWidget>
#include <QToolButton>
@@ -78,10 +79,91 @@ QColor order_status_color(const QString& status) {
return {fincept::ui::colors::AMBER()}; // pending / partial / open / accepted
}
+// Terminal (dead) order statuses across the broker adapters. Everything else is
+// still working at the exchange and MUST expose EDIT + CANCEL.
+//
+// The previous check was an exact, case-sensitive whitelist of Alpaca's four
+// statuses ("new"/"accepted"/"partially_filled"/"pending_new"), so a live OPEN
+// order on Zerodha ("OPEN"/"TRIGGER PENDING"), Fyers ("open"/"transit"),
+// Dhan ("pending"/"transit") or Upstox ("open") showed NO cancel button at all —
+// the trader could not pull a resting order from the blotter. Blacklisting the
+// terminal states instead is correct for every broker, including future ones.
+bool order_is_terminal(const QString& status) {
+ static const QSet<QString> kTerminal = {
+ QStringLiteral("complete"), QStringLiteral("completed"), QStringLiteral("filled"),
+ QStringLiteral("traded"), QStringLiteral("executed"), QStringLiteral("cancelled"),
+ QStringLiteral("canceled"), QStringLiteral("rejected"), QStringLiteral("expired"),
+ QStringLiteral("closed"), QStringLiteral("replaced"), QStringLiteral("done_for_day"),
+ QStringLiteral("stopped"), QStringLiteral("suspended"),
+ };
+ return kTerminal.contains(status.trimmed().toLower());
+}
+
+// Per-row action buttons used to carry an inline setStyleSheet each — a full CSS
+// reparse per button per blotter refresh, on a table that ticks constantly. The
+// variants now live in ONE panel-level sheet keyed off the `act` property, so a
+// row rebuild only sets a dynamic property (CLAUDE.md P7).
+QString table_btn_styles() {
+ namespace c = fincept::ui::colors;
+ return QString("QPushButton#eqTableBtn{border:1px solid %1;font-size:10px;padding:0 6px;border-radius:2px;}"
+ "QPushButton#eqTableBtn[act=\"sell\"]{background:rgba(239,68,68,0.15);color:%2;}"
+ "QPushButton#eqTableBtn[act=\"sell\"]:hover{background:rgba(239,68,68,0.30);}"
+ "QPushButton#eqTableBtn[act=\"cover\"]{background:rgba(22,163,74,0.15);color:%3;}"
+ "QPushButton#eqTableBtn[act=\"cover\"]:hover{background:rgba(22,163,74,0.30);}"
+ "QPushButton#eqTableBtn[act=\"cnc\"]{background:rgba(37,99,235,0.15);color:%4;}"
+ "QPushButton#eqTableBtn[act=\"cnc\"]:hover{background:rgba(37,99,235,0.30);}"
+ "QPushButton#eqTableBtn[act=\"edit\"]{background:rgba(217,119,6,0.15);color:%5;border-color:%6;}"
+ "QPushButton#eqTableBtn[act=\"edit\"]:hover{background:rgba(217,119,6,0.30);}"
+ "QPushButton#eqTableBtn[act=\"cancel\"]{background:rgba(220,38,38,0.12);color:%2;border-color:%7;}"
+ "QPushButton#eqTableBtn[act=\"cancel\"]:hover{background:rgba(220,38,38,0.28);}")
+ .arg(c::BORDER_MED(), c::NEGATIVE(), c::POSITIVE(), c::INFO(), c::AMBER(), c::AMBER_DIM(), c::NEGATIVE_DIM());
+}
+
+// Selection + scroll survive a rebuild. setRowCount()/setItem() throw away the
+// current row, so a trader mid-click on a position lost it on every refresh.
+struct TableViewState {
+ QString key;
+ int scroll = 0;
+};
+
+TableViewState capture_view(QTableWidget* t, int key_col) {
+ TableViewState s;
+ if (!t)
+ return s;
+ if (auto* bar = t->verticalScrollBar())
+ s.scroll = bar->value();
+ const int row = t->currentRow();
+ if (row >= 0)
+ if (auto* it = t->item(row, key_col))
+ s.key = it->text();
+ return s;
+}
+
+void restore_view(QTableWidget* t, int key_col, const TableViewState& s) {
+ if (!t)
+ return;
+ if (!s.key.isEmpty()) {
+ for (int r = 0; r < t->rowCount(); ++r) {
+ auto* it = t->item(r, key_col);
+ if (it && it->text() == s.key) {
+ t->selectRow(r); // selectRow() does not emit cellClicked
+ break;
+ }
+ }
+ }
+ if (auto* bar = t->verticalScrollBar())
+ bar->setValue(qMin(s.scroll, bar->maximum()));
+}
+
} // namespace
EquityBottomPanel::EquityBottomPanel(QWidget* parent) : QWidget(parent) {
setObjectName("eqBottomPanel");
+ // One sheet for every per-row action button (see table_btn_styles). Re-applied
+ // on theme change so runtime theme switches still recolour the buttons.
+ setStyleSheet(table_btn_styles());
+ connect(&fincept::ui::ThemeManager::instance(), &fincept::ui::ThemeManager::theme_changed, this,
+ [this]() { setStyleSheet(table_btn_styles()); });
auto* layout = new QVBoxLayout(this);
layout->setContentsMargins(0, 0, 0, 0);
@@ -184,9 +266,11 @@ void EquityBottomPanel::retranslateUi() {
tabs_->setTabText(calendar_tab_idx_, tr("CALENDAR"));
}
- // Table headers
+ // Table headers. Column 2 shows the open time in paper mode and the exchange
+ // in live mode — the data setters own it, so mirror the current mode here.
if (positions_table_)
- positions_table_->setHorizontalHeaderLabels({tr("Symbol"), tr("Product"), tr("Opened"), tr("Side"), tr("Qty"),
+ positions_table_->setHorizontalHeaderLabels({tr("Symbol"), tr("Product"),
+ is_paper_ ? tr("Opened") : tr("Exchange"), tr("Side"), tr("Qty"),
tr("Avg Price"), tr("LTP"), tr("P&L"), tr("P&L %"), tr("Action")});
if (holdings_table_)
holdings_table_->setHorizontalHeaderLabels({tr("Symbol"), tr("Qty"), tr("Avg Price"), tr("LTP"), tr("Invested"),
@@ -805,6 +889,12 @@ void EquityBottomPanel::update_positions_summary() {
void EquityBottomPanel::set_paper_positions(const QVector<trading::PtPosition>& positions) {
last_paper_positions_ = positions; // keep row-aligned for live-quote patching
+ const auto view = capture_view(positions_table_, 0);
+ positions_table_->setUpdatesEnabled(false);
+ // Column 2 holds the open timestamp in paper mode (see the live setter, which
+ // puts the exchange there) — keep the header honest about what it shows.
+ if (auto* h2 = positions_table_->horizontalHeaderItem(2); !h2 || h2->text() != tr("Opened"))
+ positions_table_->setHorizontalHeaderItem(2, new QTableWidgetItem(tr("Opened")));
const QColor pos_color(fincept::ui::colors::POSITIVE());
const QColor neg_color(fincept::ui::colors::NEGATIVE());
positions_table_->setRowCount(positions.size());
@@ -843,10 +933,14 @@ void EquityBottomPanel::set_paper_positions(const QVector<trading::PtPosition>&
make_positions_action_cell(p.symbol, p.product, p.quantity, p.side,
trading::product_is_intraday(p.product), p.id));
}
+ positions_table_->setUpdatesEnabled(true);
+ restore_view(positions_table_, 0, view);
update_positions_summary();
}
void EquityBottomPanel::set_paper_orders(const QVector<trading::PtOrder>& orders) {
+ const auto view = capture_view(orders_table_, 0);
+ orders_table_->setUpdatesEnabled(false);
orders_table_->setRowCount(orders.size());
for (int i = 0; i < orders.size(); ++i) {
const auto& o = orders[i];
@@ -868,6 +962,8 @@ void EquityBottomPanel::set_paper_orders(const QVector<trading::PtOrder>& orders
orders_table_->setCellWidget(i, 9, nullptr);
ensure_item(orders_table_, i, 9)->setText("");
}
+ orders_table_->setUpdatesEnabled(true);
+ restore_view(orders_table_, 0, view);
}
void EquityBottomPanel::set_funds_view(const EquityFundsView& v) {
@@ -962,15 +1058,15 @@ QWidget* EquityBottomPanel::make_positions_action_cell(const QString& symbol, co
side.compare(QStringLiteral("sell"), Qt::CaseInsensitive) == 0;
auto* sell = new QPushButton(exit_is_buy ? tr("BUY") : tr("SELL"));
sell->setObjectName("eqTableBtn");
+ // Direction is colour-coded (green = buy/cover, red = sell) so a wrong-way
+ // click on an exit button is visually obvious before it is pressed.
+ sell->setProperty("act", exit_is_buy ? "cover" : "sell");
sell->setFixedHeight(18);
sell->setCursor(Qt::PointingHandCursor);
+ sell->setAccessibleName(exit_is_buy ? tr("Buy to cover %1").arg(symbol) : tr("Sell to exit %1").arg(symbol));
sell->setToolTip(exit_is_buy
? tr("Buy / cover %1 — opens an order ticket pre-filled with the held quantity").arg(symbol)
: tr("Sell / exit %1 — opens an order ticket pre-filled with the held quantity").arg(symbol));
- sell->setStyleSheet(QString("QPushButton#eqTableBtn{background:rgba(239,68,68,0.15);color:%1;"
- "border:1px solid %2;font-size:10px;padding:0 6px;border-radius:2px;}"
- "QPushButton#eqTableBtn:hover{background:rgba(239,68,68,0.30);}")
- .arg(fincept::ui::colors::NEGATIVE(), fincept::ui::colors::BORDER_MED()));
const double held = qAbs(qty);
const QString prod = product.isEmpty() ? QStringLiteral("MIS") : product;
connect(sell, &QPushButton::clicked, this, [this, symbol, prod, held, exit_is_buy]() {
@@ -985,13 +1081,11 @@ QWidget* EquityBottomPanel::make_positions_action_cell(const QString& symbol, co
if (show_convert && !paper_pid.isEmpty()) {
auto* cnc = new QPushButton(tr("→ CNC"));
cnc->setObjectName("eqTableBtn");
+ cnc->setProperty("act", "cnc");
cnc->setFixedHeight(18);
cnc->setCursor(Qt::PointingHandCursor);
+ cnc->setAccessibleName(tr("Convert %1 to delivery").arg(symbol));
cnc->setToolTip(tr("Convert to CNC delivery (carry overnight, locks full cash)"));
- cnc->setStyleSheet(QString("QPushButton#eqTableBtn{background:rgba(37,99,235,0.15);color:%1;"
- "border:1px solid %2;font-size:10px;padding:0 6px;border-radius:2px;}"
- "QPushButton#eqTableBtn:hover{background:rgba(37,99,235,0.30);}")
- .arg(fincept::ui::colors::INFO(), fincept::ui::colors::BORDER_MED()));
connect(cnc, &QPushButton::clicked, this, [this, paper_pid, symbol]() {
emit convert_position_requested(paper_pid, symbol, QStringLiteral("CNC"));
});
@@ -1003,6 +1097,12 @@ QWidget* EquityBottomPanel::make_positions_action_cell(const QString& symbol, co
void EquityBottomPanel::set_positions(const QVector<trading::BrokerPosition>& positions) {
last_positions_ = positions; // keep row-aligned for live-quote patching
+ const auto view = capture_view(positions_table_, 0);
+ positions_table_->setUpdatesEnabled(false);
+ // Live rows put the EXCHANGE in column 2 (brokers don't return an open time),
+ // so the shared "Opened" header was simply wrong in live mode.
+ if (auto* h2 = positions_table_->horizontalHeaderItem(2); !h2 || h2->text() != tr("Exchange"))
+ positions_table_->setHorizontalHeaderItem(2, new QTableWidgetItem(tr("Exchange")));
const QColor pos_color(fincept::ui::colors::POSITIVE());
const QColor neg_color(fincept::ui::colors::NEGATIVE());
positions_table_->setRowCount(positions.size());
@@ -1028,6 +1128,8 @@ void EquityBottomPanel::set_positions(const QVector<trading::BrokerPosition>& po
positions_table_->setCellWidget(
i, 9, make_positions_action_cell(p.symbol, p.product_type, p.quantity, p.side, false, QString()));
}
+ positions_table_->setUpdatesEnabled(true);
+ restore_view(positions_table_, 0, view);
update_positions_summary();
}
@@ -1219,6 +1321,8 @@ void EquityBottomPanel::set_holdings(const QVector<trading::BrokerHolding>& hold
holdings_square_off_btn_->setEnabled(!holdings.isEmpty());
// Disable sorting during population so setItem assignments stay at intended rows.
+ const auto view = capture_view(holdings_table_, 0);
+ holdings_table_->setUpdatesEnabled(false);
const bool was_sorting = holdings_table_->isSortingEnabled();
holdings_table_->setSortingEnabled(false);
holdings_table_->setRowCount(holdings.size());
@@ -1274,13 +1378,11 @@ void EquityBottomPanel::set_holdings(const QVector<trading::BrokerHolding>& hold
action_lay->setSpacing(4);
auto* sell_btn = new QPushButton(tr("SELL"));
sell_btn->setObjectName("eqTableBtn");
+ sell_btn->setProperty("act", "sell");
sell_btn->setFixedHeight(18);
sell_btn->setCursor(Qt::PointingHandCursor);
+ sell_btn->setAccessibleName(tr("Square off holding %1").arg(h.symbol));
sell_btn->setToolTip(tr("Square off %1 — sells the full holding at market").arg(h.symbol));
- sell_btn->setStyleSheet(QString("QPushButton#eqTableBtn{background:rgba(239,68,68,0.15);color:%1;"
- "border:1px solid %2;font-size:10px;padding:0 6px;border-radius:2px;}"
- "QPushButton#eqTableBtn:hover{background:rgba(239,68,68,0.30);}")
- .arg(fincept::ui::colors::NEGATIVE(), fincept::ui::colors::BORDER_MED()));
const QString row_sym = h.symbol;
const QString row_exch = h.exchange;
connect(sell_btn, &QPushButton::clicked, this, [this, row_sym, row_exch]() {
@@ -1327,9 +1429,13 @@ void EquityBottomPanel::set_holdings(const QVector<trading::BrokerHolding>& hold
}
holdings_table_->setSortingEnabled(was_sorting);
+ holdings_table_->setUpdatesEnabled(true);
+ restore_view(holdings_table_, 0, view);
}
void EquityBottomPanel::set_orders(const QVector<trading::BrokerOrderInfo>& orders) {
+ const auto view = capture_view(orders_table_, 0);
+ orders_table_->setUpdatesEnabled(false);
orders_table_->setRowCount(orders.size());
for (int i = 0; i < orders.size(); ++i) {
const auto& o = orders[i];
@@ -1339,24 +1445,21 @@ void EquityBottomPanel::set_orders(const QVector<trading::BrokerOrderInfo>& orde
ensure_item(orders_table_, i, 3)->setText(o.side.toUpper());
ensure_item(orders_table_, i, 4)->setText(o.order_type.toUpper());
ensure_item(orders_table_, i, 5)->setText(QString::number(o.quantity, 'f', 0));
- ensure_item(orders_table_, i, 6)->setText(QString::number(o.price, 'f', 2));
+ // A market order has no price; "0.00" reads as a real (absurd) limit.
+ ensure_item(orders_table_, i, 6)->setText(o.price > 0.0 ? QString::number(o.price, 'f', 2) : tr("MKT"));
auto* status_item = ensure_item(orders_table_, i, 7);
status_item->setText(o.status.toUpper());
status_item->setForeground(order_status_color(o.status));
ensure_item(orders_table_, i, 8)->setText(o.timestamp);
- // Action column — MODIFY button for open/pending orders
- const bool modifiable = (o.status == "new" || o.status == "partially_filled" || o.status == "accepted" ||
- o.status == "pending_new");
+ // Action column — EDIT + CANCEL for every order that is still working.
+ const bool modifiable = !order_is_terminal(o.status);
if (modifiable) {
auto* btn = new QPushButton(tr("EDIT"));
btn->setObjectName("eqTableBtn");
+ btn->setProperty("act", "edit");
btn->setFixedHeight(18);
- btn->setStyleSheet(QString("QPushButton#eqTableBtn { background: rgba(217,119,6,0.15); "
- "color: %1; border: 1px solid %2; font-size: 10px; "
- "padding: 0 6px; border-radius: 2px; }")
- .arg(fincept::ui::colors::AMBER())
- .arg(fincept::ui::colors::AMBER_DIM()));
+ btn->setAccessibleName(tr("Modify order %1").arg(o.order_id.left(12)));
btn->setCursor(Qt::PointingHandCursor);
const QString oid = o.order_id;
const double qty = o.quantity;
@@ -1398,10 +1501,21 @@ void EquityBottomPanel::set_orders(const QVector<trading::BrokerOrderInfo>& orde
.arg(fincept::ui::colors::NEGATIVE_DIM()));
connect(ok_btn, &QPushButton::clicked, dlg, [dlg, this, oid, qty_edit, prc_edit]() {
- const double new_qty = qty_edit->text().toDouble();
- const double new_prc = prc_edit->text().toDouble();
- if (new_qty > 0)
- emit modify_order_requested(oid, new_qty, new_prc);
+ // A garbage quantity used to close the dialog with no order
+ // change and no message — the trader believed the modify had
+ // gone through. Refuse and say so instead.
+ bool qty_ok = false, prc_ok = false;
+ const double new_qty = qty_edit->text().trimmed().toDouble(&qty_ok);
+ const double new_prc = prc_edit->text().trimmed().toDouble(&prc_ok);
+ if (!qty_ok || new_qty <= 0.0) {
+ QMessageBox::warning(dlg, tr("Modify Order"), tr("Enter a valid quantity."));
+ return;
+ }
+ if (!prc_ok || new_prc < 0.0) {
+ QMessageBox::warning(dlg, tr("Modify Order"), tr("Enter a valid price."));
+ return;
+ }
+ emit modify_order_requested(oid, new_qty, new_prc);
dlg->accept();
});
connect(cancel_btn, &QPushButton::clicked, dlg, &QDialog::reject);
@@ -1420,12 +1534,9 @@ void EquityBottomPanel::set_orders(const QVector<trading::BrokerOrderInfo>& orde
// cancels immediately with no downstream prompt and equity orders are live.
auto* cancel_row_btn = new QPushButton(tr("CANCEL"));
cancel_row_btn->setObjectName("eqTableBtn");
+ cancel_row_btn->setProperty("act", "cancel");
cancel_row_btn->setFixedHeight(18);
- cancel_row_btn->setStyleSheet(QString("QPushButton#eqTableBtn { background: rgba(220,38,38,0.12); "
- "color: %1; border: 1px solid %2; font-size: 10px; "
- "padding: 0 6px; border-radius: 2px; }")
- .arg(fincept::ui::colors::NEGATIVE())
- .arg(fincept::ui::colors::NEGATIVE_DIM()));
+ cancel_row_btn->setAccessibleName(tr("Cancel order %1").arg(o.order_id.left(12)));
cancel_row_btn->setCursor(Qt::PointingHandCursor);
const QString cancel_oid = o.order_id;
connect(cancel_row_btn, &QPushButton::clicked, this, [this, cancel_oid]() {
@@ -1446,6 +1557,8 @@ void EquityBottomPanel::set_orders(const QVector<trading::BrokerOrderInfo>& orde
orders_table_->setCellWidget(i, 9, nullptr);
}
}
+ orders_table_->setUpdatesEnabled(true);
+ restore_view(orders_table_, 0, view);
}
// ── Auctions Tab ────────────────────────────────────────────────────────────
diff --git a/fincept-qt/src/screens/equity_trading/EquityChartPanel.cpp b/fincept-qt/src/screens/equity_trading/EquityChartPanel.cpp
index bb1f36bc2..e49506247 100644
--- a/fincept-qt/src/screens/equity_trading/EquityChartPanel.cpp
+++ b/fincept-qt/src/screens/equity_trading/EquityChartPanel.cpp
@@ -159,6 +159,16 @@ void EquityChartPanel::set_candles(const QVector<trading::BrokerCandle>& candles
}
}
+void EquityChartPanel::clear_candles() {
+ if (fallback_)
+ fallback_->clear();
+ else if (kline_)
+ kline_->clear();
+ // Drop the forming-bar baseline too — on_quote() must not extend a bar that
+ // belongs to the symbol we just cleared.
+ have_bar_ = false;
+}
+
void EquityChartPanel::on_quote(const trading::BrokerQuote& quote) {
if (!fallback_ && !kline_)
return;
diff --git a/fincept-qt/src/screens/equity_trading/EquityChartPanel.h b/fincept-qt/src/screens/equity_trading/EquityChartPanel.h
index 727cb76e6..72053614f 100644
--- a/fincept-qt/src/screens/equity_trading/EquityChartPanel.h
+++ b/fincept-qt/src/screens/equity_trading/EquityChartPanel.h
@@ -35,6 +35,11 @@ class EquityChartPanel : public QWidget {
// Bulk-load historical candles (full reload on symbol/timeframe change).
void set_candles(const QVector<trading::BrokerCandle>& candles);
+ // Drop every candle from whichever backend is active. Used when the symbol
+ // or timeframe changes and the new history could not be fetched, so the
+ // previous symbol's series is never left on screen (#338).
+ void clear_candles();
+
// Roll a live quote into the forming candle (no-op in the fallback backend).
void on_quote(const trading::BrokerQuote& quote);
diff --git a/fincept-qt/src/screens/equity_trading/EquityOrderEntry.cpp b/fincept-qt/src/screens/equity_trading/EquityOrderEntry.cpp
index ae7442585..827b35827 100644
--- a/fincept-qt/src/screens/equity_trading/EquityOrderEntry.cpp
+++ b/fincept-qt/src/screens/equity_trading/EquityOrderEntry.cpp
@@ -10,13 +10,16 @@
#include "ui/theme/Theme.h"
#include <QCheckBox>
+#include <QDateTime>
#include <QFrame>
#include <QGridLayout>
#include <QHBoxLayout>
+#include <QKeySequence>
#include <QMenu>
#include <QMetaObject>
#include <QPointer>
#include <QScrollArea>
+#include <QShortcut>
#include <QStyle>
#include <QTimer>
#include <QToolButton>
@@ -30,6 +33,15 @@ namespace fincept::screens::equity {
using namespace fincept::ui;
+namespace {
+// A quote older than this is flagged STALE in the ticket. Chosen so a normally
+// ticking symbol never flickers, while a dead feed is obvious within seconds.
+constexpr qint64 kStaleQuoteMs = 12000;
+// Failsafe release for the send lock: if a placement result never comes back
+// (broker hang, dropped callback) the ticket must not stay disabled forever.
+constexpr int kSendUnlockFailsafeMs = 20000;
+} // namespace
+
EquityOrderEntry::EquityOrderEntry(QWidget* parent) : QWidget(parent) {
setObjectName("eqOrderEntry");
@@ -436,24 +448,15 @@ EquityOrderEntry::EquityOrderEntry(QWidget* parent) : QWidget(parent) {
"QPushButton:hover { background: %3; color: %2; }")
.arg(colors::BG_RAISED(), colors::AMBER(), colors::BORDER_MED()));
connect(broadcast_btn_, &QPushButton::clicked, this, [this]() {
- const double qty = qty_edit_->text().toDouble();
- if (qty <= 0) {
- status_label_->setText(tr("Enter a valid quantity"));
- status_label_->setStyleSheet(QString("color: %1;").arg(colors::NEGATIVE()));
+ // The broadcast path fires the SAME order at N accounts, so it must run
+ // the SAME validation as the focused submit. It previously checked only
+ // the quantity, so a blank limit price sent price=0 as a LIMIT order to
+ // every selected broker (and the dialog even labelled it "MKT").
+ double qty = 0.0;
+ if (!validate_entry(qty))
return;
- }
- trading::UnifiedOrder order;
- order.symbol = current_symbol_;
- order.exchange = exchange_combo_->currentText();
- order.side = is_buy_side_ ? trading::OrderSide::Buy : trading::OrderSide::Sell;
- order.order_type = selected_order_type();
- order.quantity = qty;
- order.price = price_edit_->text().toDouble();
- order.stop_price = stop_price_edit_->text().toDouble();
- order.stop_loss = sl_edit_ ? sl_edit_->text().toDouble() : 0.0;
- order.take_profit = tp_edit_ ? tp_edit_->text().toDouble() : 0.0;
- order.product_type = selected_product_type();
- emit broadcast_requested(order);
+ Q_UNUSED(qty);
+ emit broadcast_requested(build_order());
});
submit_row->addWidget(broadcast_btn_, 1);
form->addLayout(submit_row);
@@ -473,6 +476,108 @@ EquityOrderEntry::EquityOrderEntry(QWidget* parent) : QWidget(parent) {
connect(margin_timer_, &QTimer::timeout, this, &EquityOrderEntry::fetch_margin_async);
connect(qty_edit_, &QLineEdit::textChanged, this, [this]() { margin_timer_->start(); });
connect(price_edit_, &QLineEdit::textChanged, this, [this]() { margin_timer_->start(); });
+
+ // Send-lock failsafe (see set_send_locked). Interval only — never started
+ // from the constructor (P3); armed on submit, disarmed on the result.
+ submit_failsafe_ = new QTimer(this);
+ submit_failsafe_->setSingleShot(true);
+ submit_failsafe_->setInterval(kSendUnlockFailsafeMs);
+ connect(submit_failsafe_, &QTimer::timeout, this, [this]() {
+ if (submit_locked_) {
+ set_send_locked(false);
+ status_label_->setText(tr("No confirmation from the broker — check the order book before retrying"));
+ status_label_->setStyleSheet(QString("color: %1;").arg(colors::WARNING()));
+ }
+ });
+
+ // Stale-quote watchdog. Interval only here; started in showEvent / stopped in
+ // hideEvent so a hidden ticket costs nothing (P3).
+ stale_timer_ = new QTimer(this);
+ stale_timer_->setInterval(2000);
+ connect(stale_timer_, &QTimer::timeout, this, &EquityOrderEntry::update_stale_state);
+
+ // ── Accessibility + keyboard (order entry is where this matters most) ──────
+ setAccessibleName(tr("Order entry ticket"));
+ buy_tab_->setAccessibleName(tr("Buy side"));
+ sell_tab_->setAccessibleName(tr("Sell side"));
+ const QString type_names[] = {tr("Market order"), tr("Limit order"), tr("Stop-loss market order"),
+ tr("Stop-loss limit order")};
+ for (int i = 0; i < 4; ++i)
+ type_btns_[i]->setAccessibleName(type_names[i]);
+ product_combo_->setAccessibleName(tr("Product type"));
+ exchange_combo_->setAccessibleName(tr("Exchange"));
+ qty_edit_->setAccessibleName(tr("Quantity"));
+ price_edit_->setAccessibleName(tr("Limit price"));
+ stop_price_edit_->setAccessibleName(tr("Trigger price"));
+ sl_edit_->setAccessibleName(tr("Stop loss price"));
+ tp_edit_->setAccessibleName(tr("Take profit price"));
+ submit_btn_->setAccessibleName(tr("Submit order"));
+ broadcast_btn_->setAccessibleName(tr("Broadcast order to multiple accounts"));
+ brokers_btn_->setAccessibleName(tr("Target broker accounts"));
+ baskets_btn->setAccessibleName(tr("Saved order baskets"));
+ market_price_label_->setAccessibleName(tr("Last traded price"));
+ balance_label_->setAccessibleName(tr("Available balance"));
+ cost_label_->setAccessibleName(tr("Estimated order value"));
+ status_label_->setAccessibleName(tr("Order status"));
+ place_strategy_btn_->setAccessibleName(tr("Place options strategy"));
+
+ // Explicit ticket tab order: side → type → qty → price → trigger → product →
+ // exchange → submit. Qt's creation order would otherwise walk the collapsed
+ // advanced/strategy sections in between.
+ setTabOrder(buy_tab_, sell_tab_);
+ setTabOrder(sell_tab_, type_btns_[0]);
+ setTabOrder(type_btns_[0], type_btns_[1]);
+ setTabOrder(type_btns_[1], type_btns_[2]);
+ setTabOrder(type_btns_[2], type_btns_[3]);
+ setTabOrder(type_btns_[3], qty_edit_);
+ setTabOrder(qty_edit_, price_edit_);
+ setTabOrder(price_edit_, stop_price_edit_);
+ setTabOrder(stop_price_edit_, product_combo_);
+ setTabOrder(product_combo_, exchange_combo_);
+ setTabOrder(exchange_combo_, submit_btn_);
+ setTabOrder(submit_btn_, broadcast_btn_);
+
+ // Trader shortcuts (window-scoped so they work from anywhere on the tab).
+ auto add_shortcut = [this](const QKeySequence& keys, auto&& fn) {
+ auto* sc = new QShortcut(keys, this);
+ sc->setContext(Qt::WindowShortcut);
+ connect(sc, &QShortcut::activated, this, fn);
+ return sc;
+ };
+ // Ctrl+Shift+… avoids the platform-reserved Ctrl+Q (quit) / Ctrl+Esc (Start menu).
+ add_shortcut(QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_Q), [this]() { focus_quantity(); });
+ add_shortcut(QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_B), [this]() {
+ set_buy_side(true);
+ focus_quantity();
+ });
+ add_shortcut(QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_S), [this]() {
+ set_buy_side(false);
+ focus_quantity();
+ });
+ buy_tab_->setToolTip(tr("Buy side (Ctrl+Shift+B)"));
+ sell_tab_->setToolTip(tr("Sell side (Ctrl+Shift+S)"));
+ qty_edit_->setToolTip(tr("Quantity (Ctrl+Shift+Q to focus, Esc to clear the ticket)"));
+
+ // Escape clears the ticket — the trader's "abort what I typed" reflex. Scoped
+ // to this widget so it can't steal Escape from the rest of the window.
+ {
+ auto* clear_sc = new QShortcut(QKeySequence(Qt::Key_Escape), this);
+ clear_sc->setContext(Qt::WidgetWithChildrenShortcut);
+ connect(clear_sc, &QShortcut::activated, this, [this]() {
+ qty_edit_->clear();
+ price_edit_->clear();
+ stop_price_edit_->clear();
+ if (sl_edit_)
+ sl_edit_->clear();
+ if (tp_edit_)
+ tp_edit_->clear();
+ status_label_->setText(tr("Ticket cleared"));
+ status_label_->setStyleSheet(QString("color: %1;").arg(colors::TEXT_SECONDARY()));
+ update_cost_preview();
+ });
+ }
+
+ render_price_label();
}
void EquityOrderEntry::configure_for_broker(const trading::BrokerProfile& profile) {
@@ -511,7 +616,11 @@ void EquityOrderEntry::configure_for_broker(const trading::BrokerProfile& profil
tp_edit_->clear();
status_label_->clear();
current_price_ = 0;
+ last_price_ms_ = 0;
+ price_is_stale_ = false;
balance_ = 0;
+ set_send_locked(false); // a broker switch must never leave the ticket wedged
+ render_price_label();
update_cost_preview();
}
@@ -525,6 +634,7 @@ void EquityOrderEntry::set_buy_side(bool is_buy) {
sell_tab_->style()->polish(sell_tab_);
submit_btn_->setText(is_buy ? tr("BUY %1").arg(current_symbol_) : tr("SELL %1").arg(current_symbol_));
+ submit_btn_->setAccessibleName(is_buy ? tr("Buy %1").arg(current_symbol_) : tr("Sell %1").arg(current_symbol_));
submit_btn_->setObjectName(is_buy ? "eqBuySubmit" : "eqSellSubmit");
submit_btn_->style()->unpolish(submit_btn_);
submit_btn_->style()->polish(submit_btn_);
@@ -550,7 +660,10 @@ void EquityOrderEntry::set_balance(double balance) {
void EquityOrderEntry::set_current_price(double price) {
current_price_ = price;
- market_price_label_->setText(tr("LTP %1%2").arg(currency_symbol(current_currency_)).arg(price, 0, 'f', 2));
+ if (price > 0.0)
+ last_price_ms_ = QDateTime::currentMSecsSinceEpoch();
+ update_stale_state(); // clears the STALE marker on the first fresh tick
+ render_price_label();
update_cost_preview();
}
@@ -563,10 +676,22 @@ void EquityOrderEntry::set_mode(bool is_paper) {
}
void EquityOrderEntry::set_symbol(const QString& symbol) {
+ const bool changed = (symbol != current_symbol_);
current_symbol_ = symbol;
submit_btn_->setText(is_buy_side_ ? tr("BUY %1").arg(symbol) : tr("SELL %1").arg(symbol));
+ submit_btn_->setAccessibleName(is_buy_side_ ? tr("Buy %1").arg(symbol) : tr("Sell %1").arg(symbol));
if (symbol_label_)
symbol_label_->setText(QStringLiteral("%1 · %2").arg(symbol, current_exchange_));
+ if (changed) {
+ // The cached LTP belongs to the PREVIOUS symbol. Showing it under the new
+ // ticker is a wrong price on an order ticket — clear until the new
+ // symbol's first quote arrives.
+ current_price_ = 0.0;
+ last_price_ms_ = 0;
+ price_is_stale_ = false;
+ render_price_label();
+ update_cost_preview();
+ }
}
void EquityOrderEntry::set_exchange(const QString& exchange) {
@@ -595,62 +720,126 @@ trading::ProductType EquityOrderEntry::selected_product_type() const {
return trading::ProductType::Intraday;
}
-void EquityOrderEntry::on_submit() {
- const double qty = qty_edit_->text().toDouble();
- if (qty <= 0) {
- status_label_->setText(tr("Enter a valid quantity"));
+bool EquityOrderEntry::validate_entry(double& qty_out) {
+ auto fail = [this](const QString& msg) {
+ status_label_->setText(msg);
status_label_->setStyleSheet(QString("color: %1;").arg(colors::NEGATIVE()));
- return;
- }
+ return false;
+ };
+
+ // QString::toDouble() is locale-independent and returns 0.0 on ANY parse
+ // failure, so "1,000" / "12 " / "abc" all silently became zero. Check the
+ // flag explicitly and say what is wrong instead of a generic message.
+ bool ok = false;
+ const double qty = qty_edit_->text().trimmed().toDouble(&ok);
+ if (!ok || !std::isfinite(qty))
+ return fail(tr("Quantity is not a number (use plain digits, no separators)"));
+ if (qty <= 0.0)
+ return fail(tr("Enter a valid quantity"));
+ qty_out = qty;
// Validate price/trigger for the order types that require them. Without this
// a blank Limit price sends price=0 to the broker (and a paper SELL-limit @0
// would fill at market).
const trading::OrderType otype = selected_order_type();
- const double limit_px = price_edit_->text().toDouble();
- const double trigger_px = stop_price_edit_->text().toDouble();
- if ((otype == trading::OrderType::Limit || otype == trading::OrderType::StopLossLimit) && limit_px <= 0.0) {
- status_label_->setText(tr("Enter a valid limit price"));
- status_label_->setStyleSheet(QString("color: %1;").arg(colors::NEGATIVE()));
- return;
+ if (otype == trading::OrderType::Limit || otype == trading::OrderType::StopLossLimit) {
+ bool px_ok = false;
+ const double limit_px = price_edit_->text().trimmed().toDouble(&px_ok);
+ if (!px_ok || !std::isfinite(limit_px) || limit_px <= 0.0)
+ return fail(tr("Enter a valid limit price"));
}
- if ((otype == trading::OrderType::StopLoss || otype == trading::OrderType::StopLossLimit) && trigger_px <= 0.0) {
- status_label_->setText(tr("Enter a valid trigger price"));
- status_label_->setStyleSheet(QString("color: %1;").arg(colors::NEGATIVE()));
- return;
+ if (otype == trading::OrderType::StopLoss || otype == trading::OrderType::StopLossLimit) {
+ bool tp_ok = false;
+ const double trigger_px = stop_price_edit_->text().trimmed().toDouble(&tp_ok);
+ if (!tp_ok || !std::isfinite(trigger_px) || trigger_px <= 0.0)
+ return fail(tr("Enter a valid trigger price"));
}
+ return true;
+}
- // Double-submit guard: in Auto mode there is no confirm dialog, so a rapid
- // double-click would emit two live orders. Briefly disable the button; a
- // single-shot timer re-enables it.
- if (submit_btn_) {
- if (!submit_btn_->isEnabled())
- return;
- submit_btn_->setEnabled(false);
- QPointer<EquityOrderEntry> self = this;
- QTimer::singleShot(1000, this, [self]() {
- if (self && self->submit_btn_)
- self->submit_btn_->setEnabled(true);
- });
- }
+trading::UnifiedOrder EquityOrderEntry::build_order() const {
+ const trading::OrderType otype = selected_order_type();
+ const bool uses_limit = (otype == trading::OrderType::Limit || otype == trading::OrderType::StopLossLimit);
+ const bool uses_trigger = (otype == trading::OrderType::StopLoss || otype == trading::OrderType::StopLossLimit);
trading::UnifiedOrder order;
order.symbol = current_symbol_;
order.exchange = exchange_combo_->currentText();
order.side = is_buy_side_ ? trading::OrderSide::Buy : trading::OrderSide::Sell;
-
order.order_type = otype;
- order.quantity = qty;
- order.price = price_edit_->text().toDouble();
- order.stop_price = stop_price_edit_->text().toDouble();
- order.stop_loss = sl_edit_ ? sl_edit_->text().toDouble() : 0.0;
- order.take_profit = tp_edit_ ? tp_edit_->text().toDouble() : 0.0;
+ order.quantity = qty_edit_->text().trimmed().toDouble();
+ // The price/trigger boxes keep their text when disabled, so a value typed for
+ // a LIMIT order used to ride along on a MARKET order (brokers differ on
+ // whether they ignore it). Send only the fields the order type actually uses.
+ order.price = uses_limit ? price_edit_->text().trimmed().toDouble() : 0.0;
+ order.stop_price = uses_trigger ? stop_price_edit_->text().trimmed().toDouble() : 0.0;
+ order.stop_loss = sl_edit_ ? sl_edit_->text().trimmed().toDouble() : 0.0;
+ order.take_profit = tp_edit_ ? tp_edit_->text().trimmed().toDouble() : 0.0;
order.product_type = selected_product_type();
+ order.validity = QStringLiteral("DAY");
+ return order;
+}
- if (!broadcast_ids_.isEmpty()) {
+void EquityOrderEntry::set_send_locked(bool locked) {
+ submit_locked_ = locked;
+ if (submit_btn_)
+ submit_btn_->setEnabled(!locked);
+ if (broadcast_btn_)
+ broadcast_btn_->setEnabled(!locked);
+ if (place_strategy_btn_)
+ place_strategy_btn_->setEnabled(!locked);
+ if (!submit_failsafe_)
+ return;
+ if (locked)
+ submit_failsafe_->start();
+ else
+ submit_failsafe_->stop();
+}
+
+void EquityOrderEntry::on_submit() {
+ // Double-submit guard. The previous version re-enabled after a fixed 1s,
+ // but a live placement round-trip regularly exceeds that — a second click
+ // then sent a SECOND real order. Stay locked until the placement result
+ // arrives via show_order_status(), with a failsafe timer so the ticket can
+ // never wedge.
+ if (submit_locked_)
+ return;
+
+ double qty = 0.0;
+ if (!validate_entry(qty))
+ return;
+
+ const trading::UnifiedOrder order = build_order();
+
+ // Drop any account the user ticked in the BROKERS menu that has since been
+ // removed or deactivated — the menu only prunes when it is re-opened, so a
+ // stale id could otherwise be broadcast to.
+ QStringList targets;
+ const bool multi_armed = !broadcast_ids_.isEmpty();
+ if (multi_armed) {
+ QSet<QString> alive;
+ for (const auto& account : trading::AccountManager::instance().active_accounts())
+ alive.insert(account.account_id);
+ for (const auto& id : broadcast_ids_)
+ if (alive.contains(id))
+ targets << id;
+ broadcast_ids_ = QSet<QString>(targets.begin(), targets.end());
+ update_brokers_btn();
+ if (targets.isEmpty()) {
+ // Every ticked account is gone. Silently falling through would route
+ // the order to the FOCUSED account instead — never guess a destination.
+ status_label_->setText(tr("Selected broker accounts no longer exist — pick targets again"));
+ status_label_->setStyleSheet(QString("color: %1;").arg(colors::NEGATIVE()));
+ return;
+ }
+ }
+
+ set_send_locked(true);
+
+ if (!targets.isEmpty()) {
// Multi-broker route: the same order to every checked account; the
// screen confirms, gates per-account (Semi-Auto), and broadcasts.
- emit multi_broker_submit(order, QStringList(broadcast_ids_.begin(), broadcast_ids_.end()));
+ emit multi_broker_submit(order, targets);
return;
}
@@ -712,11 +901,87 @@ void EquityOrderEntry::update_brokers_btn() {
}
void EquityOrderEntry::show_order_status(const QString& msg, bool success) {
+ // A placement outcome (or a cancellation) is the signal that the in-flight
+ // order is resolved — release the send lock here rather than on a timer.
+ set_send_locked(false);
status_label_->setText(msg);
status_label_->setStyleSheet(QString("color: %1;").arg(success ? colors::POSITIVE() : colors::NEGATIVE()));
QTimer::singleShot(5000, status_label_, [this]() { status_label_->clear(); });
}
+void EquityOrderEntry::set_limit_price(double price) {
+ if (!price_edit_ || price <= 0.0)
+ return;
+ // A depth-ladder click is only meaningful as a LIMIT: on MKT the price box is
+ // disabled and the value would be both invisible and unused.
+ if (active_type_ != 1 && active_type_ != 3)
+ set_order_type(1); // LMT
+ price_edit_->setText(QString::number(price, 'f', 2));
+ update_cost_preview();
+ if (status_label_) {
+ status_label_->setText(tr("Limit price %1 taken from market depth").arg(price, 0, 'f', 2));
+ status_label_->setStyleSheet(QString("color: %1;").arg(colors::TEXT_SECONDARY()));
+ }
+}
+
+void EquityOrderEntry::focus_quantity() {
+ if (!qty_edit_)
+ return;
+ qty_edit_->setFocus(Qt::ShortcutFocusReason);
+ qty_edit_->selectAll();
+}
+
+void EquityOrderEntry::showEvent(QShowEvent* event) {
+ QWidget::showEvent(event);
+ if (stale_timer_)
+ stale_timer_->start(); // P3: cadence only while the ticket is on screen
+ update_stale_state();
+}
+
+void EquityOrderEntry::hideEvent(QHideEvent* event) {
+ QWidget::hideEvent(event);
+ if (stale_timer_)
+ stale_timer_->stop();
+}
+
+// Text only — this runs on every tick, so it must never touch the stylesheet
+// (each setStyleSheet is a full CSS reparse; see CLAUDE.md P7).
+void EquityOrderEntry::render_price_label() {
+ if (!market_price_label_)
+ return;
+ if (current_price_ <= 0.0) {
+ market_price_label_->setText(tr("LTP --"));
+ return;
+ }
+ const QString sym = currency_symbol(current_currency_);
+ market_price_label_->setText(price_is_stale_
+ ? tr("LTP %1%2 \xe2\x9a\xa0 STALE").arg(sym).arg(current_price_, 0, 'f', 2)
+ : tr("LTP %1%2").arg(sym).arg(current_price_, 0, 'f', 2));
+}
+
+// Owns the stale flag AND its styling; the stylesheet is only reparsed on the
+// rare transition, never per tick.
+void EquityOrderEntry::update_stale_state() {
+ if (!market_price_label_)
+ return;
+ const bool stale = current_price_ > 0.0 && last_price_ms_ > 0 &&
+ (QDateTime::currentMSecsSinceEpoch() - last_price_ms_) > kStaleQuoteMs;
+ if (stale == price_is_stale_)
+ return; // no churn on the common path
+ price_is_stale_ = stale;
+ if (stale) {
+ market_price_label_->setStyleSheet(QString("color: %1; font-weight:700;").arg(colors::WARNING()));
+ market_price_label_->setToolTip(
+ tr("This price has not updated for over %1s — the feed may be down or the market closed. "
+ "Do not treat it as the live price.")
+ .arg(kStaleQuoteMs / 1000));
+ } else {
+ market_price_label_->setStyleSheet(QString()); // back to the global sheet
+ market_price_label_->setToolTip(tr("Last traded price"));
+ }
+ render_price_label();
+}
+
void EquityOrderEntry::update_cost_preview() {
const double qty = qty_edit_->text().toDouble();
double price = current_price_;
@@ -777,6 +1042,10 @@ void EquityOrderEntry::fetch_margin_async() {
return;
}
auto result = broker->get_order_margins(creds, order);
+ // QMetaObject::invokeMethod asserts on a null receiver — the widget can be
+ // torn down while the (blocking) broker call is in flight (P8).
+ if (!self)
+ return;
QMetaObject::invokeMethod(
self,
[self, result]() {
@@ -893,12 +1162,15 @@ void EquityOrderEntry::refresh_strategy_preview() {
}
void EquityOrderEntry::on_place_strategy() {
+ if (submit_locked_)
+ return; // a placement is already in flight
trading::OptionsStrategy strat;
if (!build_strategy(strat)) {
status_label_->setText(tr("Select a strategy and enter valid expiry / strike / width"));
status_label_->setStyleSheet(QString("color: %1;").arg(colors::NEGATIVE()));
return;
}
+ set_send_locked(true); // released by show_order_status() on the result
// Product type from profile-driven combo (same mapping as on_submit)
trading::ProductType product = trading::ProductType::Intraday;
@@ -1001,6 +1273,7 @@ void EquityOrderEntry::retranslateUi() {
// Recompute data-derived previews so they re-render in the new language.
refresh_strategy_preview();
update_cost_preview();
+ render_price_label();
}
} // namespace fincept::screens::equity
diff --git a/fincept-qt/src/screens/equity_trading/EquityOrderEntry.h b/fincept-qt/src/screens/equity_trading/EquityOrderEntry.h
index f87cdfb86..356675580 100644
--- a/fincept-qt/src/screens/equity_trading/EquityOrderEntry.h
+++ b/fincept-qt/src/screens/equity_trading/EquityOrderEntry.h
@@ -7,10 +7,12 @@
#include <QComboBox>
#include <QEvent>
+#include <QHideEvent>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QSet>
+#include <QShowEvent>
#include <QTimer>
#include <QWidget>
@@ -37,6 +39,14 @@ class EquityOrderEntry : public QWidget {
void set_broker_id(const QString& broker_id);
void show_order_status(const QString& msg, bool success); // show result after order placed
+ // Fill the LIMIT price box from an external price gesture (clicking a level in
+ // the market-depth ladder). Switches the ticket to LMT when it is on MKT, so
+ // the value the user just picked is the one that will actually be sent.
+ void set_limit_price(double price);
+
+ // Move keyboard focus to the quantity box (the trader's entry point).
+ void focus_quantity();
+
signals:
void order_submitted(const trading::UnifiedOrder& order);
void broadcast_requested(const trading::UnifiedOrder& order);
@@ -47,6 +57,8 @@ class EquityOrderEntry : public QWidget {
protected:
void changeEvent(QEvent* event) override;
+ void showEvent(QShowEvent* event) override;
+ void hideEvent(QHideEvent* event) override;
private slots:
void on_submit();
@@ -58,6 +70,24 @@ class EquityOrderEntry : public QWidget {
void set_buy_side(bool is_buy);
void set_order_type(int idx);
+ // Shared entry validation for BOTH the focused submit and the broadcast
+ // ("ALL") path. Returns false and paints the status line when the ticket is
+ // not safe to send. `qty_out` receives the parsed quantity.
+ bool validate_entry(double& qty_out);
+
+ // Build the order from the current form. Fields that do not apply to the
+ // selected order type are zeroed so a stale limit/trigger left in a disabled
+ // box can never ride along to the broker.
+ trading::UnifiedOrder build_order() const;
+
+ // Lock/unlock the send controls around an in-flight submit (see submit_lock_
+ // failsafe below).
+ void set_send_locked(bool locked);
+
+ // Repaint the LTP line, including the stale marker.
+ void render_price_label();
+ void update_stale_state();
+
// Resolve the current form selections into trading enums (dedups the
// order-type / product-type mapping repeated across submit/broadcast/margin).
trading::OrderType selected_order_type() const;
@@ -152,6 +182,19 @@ class EquityOrderEntry : public QWidget {
QTimer* margin_timer_ = nullptr;
std::atomic<bool> margin_fetching_{false};
+ // Send lock: the send controls stay disabled from click until the placement
+ // result comes back through show_order_status(). A failsafe timer releases
+ // the lock if a result never arrives, so the ticket can never wedge.
+ bool submit_locked_ = false;
+ QTimer* submit_failsafe_ = nullptr;
+
+ // Stale-quote guard: a price with no indication of its age is dangerous to
+ // trade on. last_price_ms_ is stamped on every real quote; the timer (running
+ // only while visible, P3) flips the LTP line to a dim "STALE" reading.
+ qint64 last_price_ms_ = 0;
+ bool price_is_stale_ = false;
+ QTimer* stale_timer_ = nullptr;
+
void fetch_margin_async();
// Cached product types from profile (for order construction)
diff --git a/fincept-qt/src/screens/equity_trading/EquityTradingScreen.cpp b/fincept-qt/src/screens/equity_trading/EquityTradingScreen.cpp
index 3fecb552b..5b7ff2686 100644
--- a/fincept-qt/src/screens/equity_trading/EquityTradingScreen.cpp
+++ b/fincept-qt/src/screens/equity_trading/EquityTradingScreen.cpp
@@ -60,6 +60,7 @@
#include <QPushButton>
#include <QRadioButton>
#include <QScrollBar>
+#include <QShortcut>
#include <QSplitter>
#include <QStringListModel>
#include <QTableWidget>
@@ -526,6 +527,40 @@ void EquityTradingScreen::setup_ui() {
connect(chart_, &EquityChartPanel::add_to_watchlist_requested, this,
&EquityTradingScreen::on_chart_add_to_watchlist);
connect(chart_, &EquityChartPanel::exit_position_requested, this, &EquityTradingScreen::on_chart_exit_position);
+
+ // ── Accessibility + trader keyboard shortcuts ─────────────────────────────
+ account_btn_->setAccessibleName(tr("Focused broker account"));
+ symbol_input_->setAccessibleName(tr("Symbol search"));
+ symbol_input_->setToolTip(tr("Symbol (Ctrl+Shift+F to focus)"));
+ mode_btn_->setAccessibleName(tr("Paper or live trading mode"));
+ accounts_btn_->setAccessibleName(tr("Manage broker accounts"));
+ feeds_btn_->setAccessibleName(tr("Toggle feed monitor"));
+ unified_btn_->setAccessibleName(tr("Toggle all-accounts portfolio"));
+ conn_label_->setAccessibleName(tr("Broker connection status"));
+ clock_label_->setAccessibleName(tr("Clock"));
+ exchange_label_->setAccessibleName(tr("Exchange"));
+
+ {
+ auto* focus_sym = new QShortcut(QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_F), this);
+ focus_sym->setContext(Qt::WindowShortcut);
+ connect(focus_sym, &QShortcut::activated, this, [this]() {
+ symbol_input_->setFocus(Qt::ShortcutFocusReason);
+ symbol_input_->selectAll();
+ });
+
+ // CANCEL ALL is destructive, so the shortcut carries its own confirmation
+ // (the blotter button has one; a bare hotkey must not be the exception).
+ auto* cancel_all = new QShortcut(QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_K), this);
+ cancel_all->setContext(Qt::WindowShortcut);
+ connect(cancel_all, &QShortcut::activated, this, [this]() {
+ if (focused_account_id_.isEmpty())
+ return;
+ if (QMessageBox::warning(this, tr("Cancel All Orders"),
+ tr("Cancel ALL pending orders on this account?"),
+ QMessageBox::Yes | QMessageBox::No, QMessageBox::No) == QMessageBox::Yes)
+ on_cancel_all_orders();
+ });
+ }
}
// ============================================================================
diff --git a/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Handlers.cpp b/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Handlers.cpp
index 6bc7fbe93..54e389ac6 100644
--- a/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Handlers.cpp
+++ b/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Handlers.cpp
@@ -494,7 +494,7 @@ void EquityTradingScreen::on_order_submitted(const UnifiedOrder& order) {
if (ActionCenter::instance().should_queue(acct_id, "placeorder")) {
const auto acct_meta = AccountManager::instance().get_account(acct_id);
const QString acct_label = acct_meta.display_name.isEmpty() ? acct_id : acct_meta.display_name;
- if (!OrderConfirmDialog::confirm(this, order, acct_label, current_price_)) {
+ if (!OrderConfirmDialog::confirm(this, order, acct_label, current_price_, acct_id)) {
order_entry_->show_order_status(tr("Order cancelled"), false);
return;
}
@@ -528,16 +528,29 @@ void EquityTradingScreen::on_order_submitted(const UnifiedOrder& order) {
// confirmation listing every target account + its mode, then the same per-account
// Semi-Auto gating and background broadcast the ALL dialog uses.
void EquityTradingScreen::on_multi_broker_submit(const trading::UnifiedOrder& order, const QStringList& account_ids) {
- if (account_ids.isEmpty())
+ if (account_ids.isEmpty()) {
+ // Releases the order ticket's send lock (armed on click) — every exit
+ // from this slot must report an outcome or the ticket stays disabled.
+ order_entry_->show_order_status(tr("No target accounts selected"), false);
return;
+ }
+ // Only accounts that still exist may receive the order — the inline BROKERS
+ // selector caches ids, and one may have been removed/deactivated since it was
+ // ticked. Broadcasting to a stale id is a silently-dropped order at best.
+ QStringList live_ids;
QStringList lines;
+ int live_n = 0;
for (const QString& id : account_ids) {
const auto account = AccountManager::instance().get_account(id);
if (account.account_id.isEmpty())
continue;
- const QString mode_tag = account.trading_mode == "live" ? tr("LIVE") : tr("PAPER");
+ const bool is_live = account.trading_mode == "live";
+ if (is_live)
+ ++live_n;
+ const QString mode_tag = is_live ? tr("LIVE") : tr("PAPER");
lines << QString("• %1 [%2]").arg(account.display_name, mode_tag);
+ live_ids << id;
}
if (lines.isEmpty()) {
order_entry_->show_order_status(tr("Selected accounts no longer exist"), false);
@@ -547,20 +560,28 @@ void EquityTradingScreen::on_multi_broker_submit(const trading::UnifiedOrder& or
const QString side = order.side == trading::OrderSide::Buy ? tr("BUY") : tr("SELL");
const QString px =
order.order_type == trading::OrderType::Market ? tr("MARKET") : QString::number(order.price, 'f', 2);
- const auto ret = QMessageBox::question(this, tr("Multi-Broker Order"),
- tr("%1 %2 × %3 @ %4 on %5 account(s):\n\n%6")
- .arg(side, QString::number(order.quantity), order.symbol, px)
- .arg(lines.size())
- .arg(lines.join("\n")),
- QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
- if (ret != QMessageBox::Yes)
+ // Spell out product + exchange + order type: this fires N orders at once and
+ // the ticket's product (MIS vs CNC) is not otherwise visible from here.
+ const QString detail = tr("%1 %2 × %3 @ %4\nType %5 · Product %6 · Exchange %7\n\nOn %8 account(s)%9:\n\n%10")
+ .arg(side, QString::number(order.quantity, 'f', 0), order.symbol, px,
+ QString::fromLatin1(order_type_str(order.order_type)),
+ QString::fromLatin1(product_to_broker_str(order.product_type)),
+ order.exchange.isEmpty() ? tr("(broker default)") : order.exchange)
+ .arg(lines.size())
+ .arg(live_n > 0 ? tr(" — %1 LIVE").arg(live_n) : QString())
+ .arg(lines.join("\n"));
+ const auto ret = QMessageBox::question(this, tr("Multi-Broker Order"), detail, QMessageBox::Yes | QMessageBox::No,
+ QMessageBox::No);
+ if (ret != QMessageBox::Yes) {
+ order_entry_->show_order_status(tr("Order cancelled"), false);
return;
+ }
// Per-account Semi-Auto gate: queue those accounts for approval, broadcast
// the rest immediately (mirrors BroadcastOrderDialog::on_place_order).
QStringList immediate;
int queued = 0;
- for (const QString& acct : account_ids) {
+ for (const QString& acct : live_ids) {
if (ActionCenter::instance().should_queue(acct, "placeorder")) {
const QString pid =
ActionCenter::instance().queue_order(acct, "placeorder", ActionCenter::serialize_unified_order(order));
@@ -660,6 +681,17 @@ void EquityTradingScreen::open_chart_order_ticket(bool is_buy, double price) {
px_spin->setValue(price > 0 ? price : 0.01);
form->addRow(tr("Limit price"), px_spin);
+ // Product type must be explicit: MIS auto-squares at 15:30 while CNC carries
+ // overnight and locks the full cash. This ticket used to hardcode Intraday,
+ // so a chart right-click silently opened an intraday position even for a
+ // delivery trader. Intraday stays the default (unchanged behaviour).
+ auto* product_combo = new QComboBox(&dlg);
+ product_combo->addItem(tr("Intraday (MIS)"), QStringLiteral("MIS"));
+ product_combo->addItem(tr("Delivery (CNC)"), QStringLiteral("CNC"));
+ product_combo->addItem(tr("Margin (NRML)"), QStringLiteral("NRML"));
+ product_combo->setCurrentIndex(0);
+ form->addRow(tr("Product"), product_combo);
+
// A Market order needs no price (it fills at the LTP), so the limit-price
// row (label + field) is hidden entirely unless Limit is selected.
auto sync_type = [form, px_spin](int idx) { form->setRowVisible(px_spin, idx == 1); }; // 1 = Limit
@@ -684,7 +716,7 @@ void EquityTradingScreen::open_chart_order_ticket(bool is_buy, double price) {
order.order_type = is_market ? OrderType::Market : OrderType::Limit;
order.quantity = qty_spin->value();
order.price = is_market ? 0.0 : px_spin->value();
- order.product_type = ProductType::Intraday;
+ order.product_type = product_from_broker_str(product_combo->currentData().toString());
order.validity = QStringLiteral("DAY");
on_order_submitted(order);
}
@@ -713,7 +745,11 @@ void EquityTradingScreen::on_cancel_order(const QString& order_id) {
}
void EquityTradingScreen::on_ob_price_clicked(double price) {
- order_entry_->set_current_price(price);
+ // Clicking a depth level is a "trade at THIS price" gesture — it must fill the
+ // order ticket's limit price, not overwrite the LTP readout. Overwriting the
+ // LTP made the ticket display a price that was never the last traded price,
+ // which is exactly the kind of wrong number a trader must not be shown.
+ order_entry_->set_limit_price(price);
}
void EquityTradingScreen::refresh_candles() {
diff --git a/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Streams.cpp b/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Streams.cpp
index 71352bb25..a72e30329 100644
--- a/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Streams.cpp
+++ b/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Streams.cpp
@@ -173,7 +173,12 @@ void EquityTradingScreen::hub_subscribe_quotes() {
hub.subscribe(this, topic, [this, sym](const QVariant& v) {
if (!v.canConvert<BrokerQuote>())
return;
- const auto quote = v.value<BrokerQuote>();
+ auto quote = v.value<BrokerQuote>();
+ // Some broker adapters leave BrokerQuote.symbol empty (the topic
+ // already carries it). The watchlist matches rows on quote.symbol, so
+ // an unset one silently stopped that row from ever updating.
+ if (quote.symbol.isEmpty())
+ quote.symbol = sym;
// Open-positions table (bottom sheet): patch LTP / P&L from the SAME
// quote that feeds the ticker bar, so the header and the position row
@@ -359,7 +364,7 @@ void EquityTradingScreen::on_stream_candles_fetched(const QString& account_id, c
// blocks (#338). Keep the current series unless it belongs to a symbol or
// timeframe the user has already left.
if (chart_symbol_ != key) {
- chart_->clear();
+ chart_->clear_candles();
chart_symbol_.clear();
}
LOG_WARN("EquityTrading", QString("no candles returned for %1 — keeping existing chart").arg(key));
diff --git a/fincept-qt/src/screens/equity_trading/EquityWatchlist.cpp b/fincept-qt/src/screens/equity_trading/EquityWatchlist.cpp
index 78e5ff2a3..162198ed9 100644
--- a/fincept-qt/src/screens/equity_trading/EquityWatchlist.cpp
+++ b/fincept-qt/src/screens/equity_trading/EquityWatchlist.cpp
@@ -18,6 +18,7 @@
#include <QMenu>
#include <QMessageBox>
#include <QMutexLocker>
+#include <QScrollBar>
#include <QSignalBlocker>
#include <QTimer>
#include <QVBoxLayout>
@@ -235,6 +236,20 @@ EquityWatchlist::EquityWatchlist(QWidget* parent) : QWidget(parent) {
connect(table_, &QTableWidget::customContextMenuRequested, this, &EquityWatchlist::on_table_context_menu);
layout->addWidget(table_, 1);
+ // Accessibility — the watchlist is the primary symbol-selection surface.
+ setAccessibleName(tr("Watchlist"));
+ wl_combo_->setAccessibleName(tr("Active watchlist"));
+ wl_menu_btn_->setAccessibleName(tr("Watchlist actions"));
+ filter_edit_->setAccessibleName(tr("Filter watchlist"));
+ add_edit_->setAccessibleName(tr("Add symbol to watchlist"));
+ add_btn_->setAccessibleName(tr("Add symbol"));
+ count_label_->setAccessibleName(tr("Symbol count"));
+ table_->setAccessibleName(tr("Watchlist symbols"));
+ setTabOrder(wl_combo_, wl_menu_btn_);
+ setTabOrder(wl_menu_btn_, filter_edit_);
+ setTabOrder(filter_edit_, add_edit_);
+ setTabOrder(add_edit_, add_btn_);
+
// Drag-out: hold-and-drag a symbol row to ship the ticker to any drop
// target — drop it on the pushpin bar at the top to pin + broadcast it,
// matching the standalone Watchlist tab (WatchlistScreen). The provider
@@ -439,6 +454,11 @@ void EquityWatchlist::on_filter_changed(const QString& text) {
}
void EquityWatchlist::rebuild_table() {
+ // Preserve the scroll offset — the list is rebuilt whenever the watchlist or
+ // the position/holding union changes, which happens while the user is
+ // scrolling through it.
+ const int scroll = table_->verticalScrollBar() ? table_->verticalScrollBar()->value() : 0;
+ table_->setUpdatesEnabled(false);
table_->setRowCount(entries_.size());
for (int i = 0; i < entries_.size(); ++i) {
const auto& e = entries_[i];
@@ -460,6 +480,17 @@ void EquityWatchlist::rebuild_table() {
: QColor(fincept::ui::colors::NEGATIVE()));
table_->setItem(i, 2, chg_item);
}
+ table_->setUpdatesEnabled(true);
+
+ // The rebuild dropped both the active-row highlight and any live filter —
+ // the charted symbol appeared unselected and a filtered list silently
+ // re-showed every row. Re-apply both here so rebuild_table() is idempotent.
+ if (!active_symbol_.isEmpty())
+ set_active_symbol(active_symbol_);
+ if (filter_edit_ && !filter_edit_->text().trimmed().isEmpty())
+ on_filter_changed(filter_edit_->text());
+ if (table_->verticalScrollBar())
+ table_->verticalScrollBar()->setValue(qMin(scroll, table_->verticalScrollBar()->maximum()));
}
void EquityWatchlist::set_broker_id(const QString& broker_id) {
diff --git a/fincept-qt/src/screens/equity_trading/OrderConfirmDialog.cpp b/fincept-qt/src/screens/equity_trading/OrderConfirmDialog.cpp
index 28c8edbe9..fe2eb44cc 100644
--- a/fincept-qt/src/screens/equity_trading/OrderConfirmDialog.cpp
+++ b/fincept-qt/src/screens/equity_trading/OrderConfirmDialog.cpp
@@ -1,12 +1,25 @@
#include "screens/equity_trading/OrderConfirmDialog.h"
+#include "core/logging/Logger.h"
+#include "trading/AccountManager.h"
+#include "trading/BrokerInterface.h"
+#include "trading/BrokerRegistry.h"
#include "ui/theme/Theme.h"
+#include <QFrame>
#include <QGridLayout>
#include <QHBoxLayout>
+#include <QKeySequence>
#include <QLabel>
+#include <QLocale>
+#include <QMetaObject>
+#include <QPointer>
#include <QPushButton>
+#include <QTimer>
#include <QVBoxLayout>
+#include <QtConcurrent/QtConcurrent>
+
+#include <cmath>
namespace fincept::screens {
@@ -15,6 +28,16 @@ using trading::OrderType;
using trading::UnifiedOrder;
namespace {
+
+// Hard cap on the background margin call — the trader must never be blocked by
+// a slow broker (same contract as screens/fno/OrderConfirmDialog).
+constexpr int kMarginFetchTimeoutMs = 5000;
+
+// A limit/trigger this far from the reference LTP is almost always a typo
+// (missing decimal point, wrong tick). Raise a banner rather than silently
+// sending it.
+constexpr double kFatFingerPct = 10.0;
+
QString type_str(OrderType t) {
switch (t) {
case OrderType::Market:
@@ -28,32 +51,74 @@ QString type_str(OrderType t) {
}
return QStringLiteral("MARKET");
}
+
+QString money(double v) {
+ return QLocale(QLocale::English).toString(v, 'f', 2);
+}
+
+bool needs_limit(OrderType t) {
+ return t == OrderType::Limit || t == OrderType::StopLossLimit;
+}
+
+bool needs_trigger(OrderType t) {
+ return t == OrderType::StopLoss || t == OrderType::StopLossLimit;
+}
+
} // namespace
OrderConfirmDialog::OrderConfirmDialog(QWidget* parent, const UnifiedOrder& order, const QString& account_label,
- double ref_price)
- : QDialog(parent) {
+ double ref_price, const QString& account_id)
+ : QDialog(parent), order_(order), account_id_(account_id) {
setWindowTitle(tr("Confirm Order"));
setModal(true);
- setMinimumWidth(360);
+ setMinimumWidth(430);
const bool is_buy = order.side == OrderSide::Buy;
const QString side = is_buy ? tr("BUY") : tr("SELL");
const QString side_color = is_buy ? ui::colors::POSITIVE() : ui::colors::NEGATIVE();
+ // Live vs paper is the single most consequential fact on this dialog, so it
+ // is resolved from the account record rather than inferred from the caller.
+ bool is_live = false;
+ if (!account_id_.isEmpty()) {
+ const auto acct = trading::AccountManager::instance().get_account(account_id_);
+ is_live = (acct.trading_mode == QLatin1String("live"));
+ }
+
auto* root = new QVBoxLayout(this);
root->setContentsMargins(18, 16, 18, 16);
- root->setSpacing(12);
+ root->setSpacing(10);
- auto* banner = new QLabel(tr("\xe2\x9a\xa0 SEMI-AUTO — review before sending"));
- banner->setStyleSheet(QString("color:%1;font-weight:700;").arg(ui::colors::AMBER()));
+ // ── Banner: LIVE MONEY vs PAPER ──────────────────────────────────────────
+ auto* banner = new QLabel(is_live ? tr("\xe2\x9a\xa0 LIVE ORDER \xe2\x80\x94 real money. Review before sending.")
+ : tr("PAPER ORDER \xe2\x80\x94 simulated. Review before sending."));
+ banner->setWordWrap(true);
+ banner->setStyleSheet(QString("color:%1;font-weight:700;")
+ .arg(is_live ? ui::colors::NEGATIVE() : ui::colors::POSITIVE()));
root->addWidget(banner);
+ // ── Headline: SIDE QTY SYMBOL @ price ────────────────────────────────────
+ const QString px_headline = needs_limit(order.order_type) ? money(order.price) : tr("MARKET");
+ auto* headline = new QLabel(QStringLiteral("%1 %2 %3 @ %4")
+ .arg(side)
+ .arg(QString::number(order.quantity, 'f', 0))
+ .arg(order.symbol)
+ .arg(px_headline));
+ headline->setStyleSheet(QString("color:%1;font-size:15px;font-weight:700;").arg(side_color));
+ root->addWidget(headline);
+
+ auto* rule = new QFrame;
+ rule->setFrameShape(QFrame::HLine);
+ rule->setFixedHeight(1);
+ rule->setStyleSheet(QString("background:%1;border:none;").arg(ui::colors::BORDER_DIM()));
+ root->addWidget(rule);
+
+ // ── Detail grid — every field that reaches the broker ────────────────────
auto* grid = new QGridLayout;
grid->setHorizontalSpacing(18);
- grid->setVerticalSpacing(6);
+ grid->setVerticalSpacing(5);
int r = 0;
- auto add_row = [&](const QString& k, const QString& v, const QString& color = {}) {
+ auto add_row = [&](const QString& k, const QString& v, const QString& color = {}) -> QLabel* {
auto* kl = new QLabel(k);
kl->setStyleSheet(QString("color:%1;").arg(ui::colors::TEXT_SECONDARY()));
auto* vl = new QLabel(v);
@@ -62,40 +127,155 @@ OrderConfirmDialog::OrderConfirmDialog(QWidget* parent, const UnifiedOrder& orde
grid->addWidget(kl, r, 0);
grid->addWidget(vl, r, 1);
++r;
+ return vl;
};
- add_row(tr("Account"), account_label);
+
+ add_row(tr("Account"), account_label, is_live ? ui::colors::NEGATIVE() : ui::colors::POSITIVE());
+ add_row(tr("Mode"), is_live ? tr("LIVE") : tr("PAPER"), is_live ? ui::colors::NEGATIVE() : ui::colors::POSITIVE());
add_row(tr("Action"), side, side_color);
add_row(tr("Symbol"), order.symbol);
- add_row(tr("Exchange"), order.exchange);
- add_row(tr("Quantity"), QString::number(order.quantity));
+ add_row(tr("Exchange"), order.exchange.isEmpty() ? tr("(broker default)") : order.exchange);
+ // Product (MIS/CNC/NRML) decides overnight carry + leverage — it was
+ // previously invisible here even though it always reaches the broker.
+ add_row(tr("Product"), QString::fromLatin1(trading::product_to_broker_str(order.product_type)));
+ add_row(tr("Quantity"), QString::number(order.quantity, 'f', 0));
add_row(tr("Type"), type_str(order.order_type));
- if (order.order_type == OrderType::Limit || order.order_type == OrderType::StopLossLimit)
- add_row(tr("Price"), QString::number(order.price, 'f', 2));
- if (order.stop_price > 0)
- add_row(tr("Trigger"), QString::number(order.stop_price, 'f', 2));
+ if (needs_limit(order.order_type))
+ add_row(tr("Limit price"), money(order.price));
+ if (needs_trigger(order.order_type) || order.stop_price > 0)
+ add_row(tr("Trigger"), money(order.stop_price));
+ if (order.stop_loss > 0)
+ add_row(tr("Stop loss"), money(order.stop_loss), ui::colors::NEGATIVE());
+ if (order.take_profit > 0)
+ add_row(tr("Take profit"), money(order.take_profit), ui::colors::POSITIVE());
+ add_row(tr("Validity"), order.validity.isEmpty() ? QStringLiteral("DAY") : order.validity);
if (ref_price > 0)
- add_row(tr("Est. value"), QString::number(ref_price * order.quantity, 'f', 2));
+ add_row(tr("Reference LTP"), money(ref_price));
+
+ // Estimated value uses the price that will actually be paid: the limit for a
+ // limit order, the reference LTP for a market order. (Previously this always
+ // used the LTP, so a limit order's estimate was simply wrong.)
+ const double est_px = needs_limit(order.order_type) && order.price > 0 ? order.price : ref_price;
+ if (est_px > 0)
+ add_row(tr("Est. value"), money(est_px * order.quantity));
+ margin_value_ = add_row(tr("Est. margin"), is_live ? tr("Loading\xe2\x80\xa6") : QStringLiteral("\xe2\x80\x94"));
root->addLayout(grid);
+ // ── Fat-finger guard ─────────────────────────────────────────────────────
+ if (ref_price > 0) {
+ double check_px = 0.0;
+ QString what;
+ if (needs_limit(order.order_type) && order.price > 0) {
+ check_px = order.price;
+ what = tr("limit price");
+ } else if (needs_trigger(order.order_type) && order.stop_price > 0) {
+ check_px = order.stop_price;
+ what = tr("trigger price");
+ }
+ if (check_px > 0) {
+ const double dev = std::fabs(check_px - ref_price) / ref_price * 100.0;
+ if (dev >= kFatFingerPct) {
+ auto* warn = new QLabel(tr("\xe2\x9a\xa0 The %1 (%2) is %3% away from the last traded price (%4). "
+ "Check for a typo before sending.")
+ .arg(what, money(check_px), QString::number(dev, 'f', 1), money(ref_price)));
+ warn->setWordWrap(true);
+ warn->setStyleSheet(QString("color:%1;font-weight:700;").arg(ui::colors::WARNING()));
+ root->addWidget(warn);
+ }
+ }
+ }
+
+ // ── Buttons ──────────────────────────────────────────────────────────────
auto* btns = new QHBoxLayout;
btns->addStretch(1);
- auto* cancel = new QPushButton(tr("Cancel"));
- auto* send = new QPushButton(tr("Send Order"));
- send->setDefault(true);
- send->setStyleSheet(QString("QPushButton{background:%1;color:#000;font-weight:700;"
- "padding:5px 18px;border-radius:2px;}")
- .arg(side_color));
+ auto* cancel = new QPushButton(tr("CANCEL"));
+ cancel->setObjectName(QStringLiteral("orderConfirmCancel"));
+ cancel->setCursor(Qt::PointingHandCursor);
+ cancel->setAccessibleName(tr("Cancel order"));
+ send_btn_ = new QPushButton(is_buy ? tr("SEND BUY ORDER") : tr("SEND SELL ORDER"));
+ send_btn_->setObjectName(QStringLiteral("orderConfirmSend"));
+ send_btn_->setCursor(Qt::PointingHandCursor);
+ send_btn_->setAccessibleName(tr("Send order to broker"));
+ send_btn_->setStyleSheet(QString("QPushButton{background:%1;color:#000;font-weight:700;"
+ "padding:6px 20px;border:none;}")
+ .arg(side_color));
+ // CANCEL is the default and holds focus: a stray Enter (the trader just
+ // pressed Enter in the quantity box) must never fire a live order. The send
+ // button requires a deliberate click, Space on focus, or Alt+S.
+ cancel->setDefault(true);
+ cancel->setAutoDefault(true);
+ send_btn_->setDefault(false);
+ send_btn_->setAutoDefault(false);
+ send_btn_->setShortcut(QKeySequence(Qt::ALT | Qt::Key_S));
btns->addWidget(cancel);
- btns->addWidget(send);
+ btns->addWidget(send_btn_);
root->addLayout(btns);
connect(cancel, &QPushButton::clicked, this, &QDialog::reject);
- connect(send, &QPushButton::clicked, this, &QDialog::accept);
+ // Disable first, then accept — a double-click can otherwise land twice
+ // before the modal loop unwinds.
+ connect(send_btn_, &QPushButton::clicked, send_btn_, [this]() { send_btn_->setEnabled(false); });
+ connect(send_btn_, &QPushButton::clicked, this, &QDialog::accept);
+
+ setTabOrder(cancel, send_btn_);
+ cancel->setFocus();
+
+ if (is_live)
+ start_margin_fetch();
+}
+
+void OrderConfirmDialog::start_margin_fetch() {
+ if (!margin_value_ || account_id_.isEmpty())
+ return;
+
+ const auto creds = trading::AccountManager::instance().load_credentials(account_id_);
+ if (creds.api_key.isEmpty()) {
+ margin_value_->setText(QStringLiteral("\xe2\x80\x94"));
+ margin_done_ = true;
+ return;
+ }
+ auto* broker = trading::BrokerRegistry::instance().get(creds.broker_id);
+ if (!broker) {
+ margin_value_->setText(QStringLiteral("\xe2\x80\x94"));
+ margin_done_ = true;
+ return;
+ }
+
+ QPointer<OrderConfirmDialog> self = this;
+ const auto order = order_;
+ (void)QtConcurrent::run([self, broker, creds, order]() {
+ auto resp = broker->get_order_margins(creds, order);
+ if (!self)
+ return;
+ QMetaObject::invokeMethod(
+ self.data(),
+ [self, resp]() {
+ if (!self || !self->margin_value_)
+ return;
+ self->margin_done_ = true;
+ if (resp.success && resp.data.has_value() && resp.data->error.isEmpty()) {
+ self->margin_value_->setText(money(resp.data->total));
+ } else {
+ self->margin_value_->setText(QStringLiteral("\xe2\x80\x94"));
+ self->margin_value_->setToolTip(resp.error.isEmpty() ? tr("Margin unavailable") : resp.error);
+ LOG_DEBUG("EquityConfirm", QString("order margin unavailable: %1").arg(resp.error));
+ }
+ },
+ Qt::QueuedConnection);
+ });
+
+ // Never let a slow broker leave the value spinning on "Loading…".
+ QPointer<OrderConfirmDialog> guard = this;
+ QTimer::singleShot(kMarginFetchTimeoutMs, this, [guard]() {
+ if (!guard || guard->margin_done_ || !guard->margin_value_)
+ return;
+ guard->margin_value_->setText(tr("\xe2\x80\x94 (timeout)"));
+ });
}
bool OrderConfirmDialog::confirm(QWidget* parent, const UnifiedOrder& order, const QString& account_label,
- double ref_price) {
- OrderConfirmDialog dlg(parent, order, account_label, ref_price);
+ double ref_price, const QString& account_id) {
+ OrderConfirmDialog dlg(parent, order, account_label, ref_price, account_id);
return dlg.exec() == QDialog::Accepted;
}
diff --git a/fincept-qt/src/screens/equity_trading/OrderConfirmDialog.h b/fincept-qt/src/screens/equity_trading/OrderConfirmDialog.h
index cde9bebfe..e460ff0db 100644
--- a/fincept-qt/src/screens/equity_trading/OrderConfirmDialog.h
+++ b/fincept-qt/src/screens/equity_trading/OrderConfirmDialog.h
@@ -3,25 +3,47 @@
// equity orders. Manual orders are NOT queued in the pending-orders table; the
// trader is already present, so approval is an inline modal rather than the
// status-bar popover used for headless (AI/workflow/broadcast) orders.
+//
+// Safety contract (mirrors screens/fno/OrderConfirmDialog):
+// • every field that reaches the broker is shown, including product type,
+// validity and the protective SL/TP legs — nothing silently rides along;
+// • the destination account is shown with an explicit LIVE / PAPER chip;
+// • the required margin is fetched in the background (live accounts) with a
+// hard timeout so a slow broker never blocks the trader;
+// • a limit price far away from the reference LTP raises a fat-finger banner;
+// • CANCEL is the default button — Enter can never send an order.
#include "trading/TradingTypes.h"
#include <QDialog>
#include <QString>
+class QLabel;
+class QPushButton;
+
namespace fincept::screens {
class OrderConfirmDialog : public QDialog {
Q_OBJECT
public:
- // Returns true if the user pressed "Send Order". `ref_price` is used only to
- // show an estimated value line (<= 0 hides it).
+ // Returns true if the user pressed "SEND ORDER". `ref_price` is the latest
+ // known LTP (<= 0 = unknown) and drives the estimated value + the
+ // fat-finger check. `account_id` is optional; when given, the dialog reads
+ // the account's live/paper mode and fetches the broker's required margin.
static bool confirm(QWidget* parent, const trading::UnifiedOrder& order, const QString& account_label,
- double ref_price);
+ double ref_price, const QString& account_id = QString());
private:
OrderConfirmDialog(QWidget* parent, const trading::UnifiedOrder& order, const QString& account_label,
- double ref_price);
+ double ref_price, const QString& account_id);
+
+ void start_margin_fetch();
+
+ trading::UnifiedOrder order_;
+ QString account_id_;
+ QLabel* margin_value_ = nullptr;
+ QPushButton* send_btn_ = nullptr;
+ bool margin_done_ = false;
};
} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/excel/ExcelScreen.cpp b/fincept-qt/src/screens/excel/ExcelScreen.cpp
index ecc54f0a6..b97c5acd9 100644
--- a/fincept-qt/src/screens/excel/ExcelScreen.cpp
+++ b/fincept-qt/src/screens/excel/ExcelScreen.cpp
@@ -7,15 +7,22 @@
#include "services/file_manager/FileManagerService.h"
#include "ui/theme/Theme.h"
+#include <QDateTime>
+#include <QFile>
#include <QFileDialog>
+#include <QFileInfo>
#include <QHBoxLayout>
#include <QInputDialog>
#include <QLabel>
#include <QMessageBox>
#include <QPushButton>
+#include <QShortcut>
#include <QTabBar>
+#include <QTextStream>
#include <QVBoxLayout>
+#include <algorithm>
+
#ifdef FINCEPT_HAS_QXLSX
# include <xlsxdocument.h>
#endif
@@ -82,9 +89,17 @@ void ExcelScreen::build_ui() {
// Add initial sheet
auto* sheet1 = new SpreadsheetWidget("Sheet1", 100, 26, sheet_tabs_);
sheet_tabs_->addTab(sheet1, "Sheet1");
+ watch_sheet(sheet1);
connect(sheet_tabs_, &QTabWidget::currentChanged, this, &ExcelScreen::on_tab_changed);
+ // Ctrl+S saves back to the current file path (or prompts on first save) —
+ // previously the only way to persist work was the EXPORT button, which
+ // always re-asked for a filename.
+ auto* save_sc = new QShortcut(QKeySequence::Save, this);
+ save_sc->setContext(Qt::WidgetWithChildrenShortcut);
+ connect(save_sc, &QShortcut::activated, this, &ExcelScreen::on_export);
+
root->addWidget(sheet_tabs_, 1);
// Status bar
@@ -189,17 +204,110 @@ QWidget* ExcelScreen::build_toolbar() {
// Import (XLSX via QXlsx)
// ─────────────────────────────────────────────────────────────────────────────
+// Split one CSV line honouring RFC-4180 quoting (""-escaped quotes inside a
+// quoted field). Kept local — the watchlist screen has its own copy but lives
+// in a different slice.
+static QStringList split_csv_line(const QString& line) {
+ QStringList fields;
+ QString cur;
+ bool in_quotes = false;
+ for (int i = 0; i < line.length(); ++i) {
+ const QChar c = line[i];
+ if (c == '"') {
+ if (in_quotes && i + 1 < line.length() && line[i + 1] == '"') {
+ cur += '"';
+ ++i;
+ } else {
+ in_quotes = !in_quotes;
+ }
+ } else if (c == ',' && !in_quotes) {
+ fields.append(cur);
+ cur.clear();
+ } else {
+ cur += c;
+ }
+ }
+ fields.append(cur);
+ return fields;
+}
+
+bool ExcelScreen::import_csv(const QString& path) {
+ QFile f(path);
+ if (!f.open(QIODevice::ReadOnly | QIODevice::Text)) {
+ QMessageBox::warning(this, tr("Import failed"), tr("Could not open file for reading:\n%1").arg(path));
+ return false;
+ }
+ QTextStream in(&f);
+ in.setEncoding(QStringConverter::Utf8);
+
+ QVector<QVector<QString>> cells;
+ // Hard cap so a pathological file can't allocate millions of table items
+ // and freeze the UI thread.
+ constexpr int kMaxRows = 20000;
+ while (!in.atEnd() && cells.size() < kMaxRows) {
+ const QStringList fields = split_csv_line(in.readLine());
+ QVector<QString> row;
+ row.reserve(fields.size());
+ for (const auto& v : fields)
+ row.append(v);
+ cells.append(row);
+ }
+ const bool truncated = !in.atEnd();
+
+ const QString name = QFileInfo(path).completeBaseName();
+ auto* sheet = new SpreadsheetWidget(name, std::max<int>(100, static_cast<int>(cells.size())), 26, sheet_tabs_);
+ sheet->set_data(cells);
+
+ // Replace the current sheet set with the imported file (matches the XLSX path).
+ while (sheet_tabs_->count() > 0) {
+ auto* w = sheet_tabs_->widget(0);
+ sheet_tabs_->removeTab(0);
+ w->deleteLater();
+ }
+ sheet_tabs_->addTab(sheet, name);
+ connect(sheet, &SpreadsheetWidget::data_changed, this, &ExcelScreen::mark_dirty);
+
+ file_name_ = QFileInfo(path).fileName();
+ file_path_ = path;
+ if (auto* fname = findChild<QLabel*>("excelFileName"))
+ fname->setText(file_name_);
+ dirty_ = false;
+ update_status();
+ LOG_INFO("ExcelScreen", QString("Imported %1 CSV rows from %2").arg(cells.size()).arg(file_name_));
+ services::FileManagerService::instance().import_file(path, "excel");
+
+ if (truncated)
+ QMessageBox::information(this, tr("Import truncated"),
+ tr("Only the first %1 rows were imported.").arg(kMaxRows));
+ return true;
+}
+
void ExcelScreen::on_import() {
+ if (!confirm_discard(tr("Import a different file")))
+ return;
+
QString path = QFileDialog::getOpenFileName(this, tr("Import Spreadsheet"), {},
tr("Spreadsheet Files (*.xlsx *.xls *.csv);;All Files (*)"));
if (path.isEmpty())
return;
+ // CSV is advertised in the file filter (and in the no-QXlsx message) but was
+ // never actually handled — QXlsx::Document on a .csv just reported "no
+ // sheets" to the log and the screen silently did nothing.
+ if (QFileInfo(path).suffix().compare(QLatin1String("csv"), Qt::CaseInsensitive) == 0) {
+ import_csv(path);
+ return;
+ }
+
#ifdef FINCEPT_HAS_QXLSX
QXlsx::Document xlsx(path);
QStringList sheet_names = xlsx.sheetNames();
if (sheet_names.isEmpty()) {
LOG_ERROR("ExcelScreen", "No sheets found in file");
+ QMessageBox::warning(this, tr("Import failed"),
+ tr("No sheets could be read from:\n%1\n\nThe file may be corrupt or "
+ "in an unsupported format.")
+ .arg(path));
return;
}
@@ -210,6 +318,13 @@ void ExcelScreen::on_import() {
w->deleteLater();
}
+ // Every cell becomes a heap-allocated SpreadsheetItem, so an unbounded
+ // dimension (a stray value in row 1,000,000) would allocate tens of millions
+ // of items and hang the UI. Cap the import window.
+ constexpr int kMaxImportRows = 20000;
+ constexpr int kMaxImportCols = 512;
+ bool truncated = false;
+
for (const auto& name : sheet_names) {
xlsx.selectSheet(name);
@@ -217,6 +332,14 @@ void ExcelScreen::on_import() {
auto dim = xlsx.dimension();
int max_row = std::max(dim.lastRow(), 100);
int max_col = std::max(dim.lastColumn(), 26);
+ if (max_row > kMaxImportRows) {
+ max_row = kMaxImportRows;
+ truncated = true;
+ }
+ if (max_col > kMaxImportCols) {
+ max_col = kMaxImportCols;
+ truncated = true;
+ }
auto* sheet = new SpreadsheetWidget(name, max_row, max_col, sheet_tabs_);
@@ -231,6 +354,7 @@ void ExcelScreen::on_import() {
}
sheet->set_data(cells);
sheet_tabs_->addTab(sheet, name);
+ connect(sheet, &SpreadsheetWidget::data_changed, this, &ExcelScreen::mark_dirty);
}
// Update file info
@@ -240,12 +364,19 @@ void ExcelScreen::on_import() {
if (fname)
fname->setText(file_name_);
- sheet_counter_ = sheet_names.size() + 1;
+ dirty_ = false;
update_status();
LOG_INFO("ExcelScreen", QString("Imported %1 sheets from %2").arg(sheet_names.size()).arg(file_name_));
// Register with File Manager so it appears in the Files tab
services::FileManagerService::instance().import_file(path, "excel");
+
+ if (truncated)
+ QMessageBox::information(this, tr("Import truncated"),
+ tr("This workbook is larger than the %1 × %2 import window; "
+ "only that region was loaded.")
+ .arg(kMaxImportRows)
+ .arg(kMaxImportCols));
#else
QMessageBox::information(this, tr("Excel Import"),
tr("Excel (.xlsx) import requires Qt6 private headers.\n"
@@ -263,6 +394,9 @@ void ExcelScreen::on_export() {
QString path = QFileDialog::getSaveFileName(this, tr("Export as XLSX"), file_name_, tr("Excel Files (*.xlsx)"));
if (path.isEmpty())
return;
+ // QFileDialog on Linux/macOS does not always append the filter suffix.
+ if (!path.endsWith(QLatin1String(".xlsx"), Qt::CaseInsensitive))
+ path += QLatin1String(".xlsx");
QXlsx::Document xlsx;
@@ -306,12 +440,20 @@ void ExcelScreen::on_export() {
auto* fname = findChild<QLabel*>("excelFileName");
if (fname)
fname->setText(file_name_);
+ dirty_ = false;
+ update_status();
LOG_INFO("ExcelScreen", QString("Exported to %1").arg(path));
// Register with File Manager so it appears in the Files tab
services::FileManagerService::instance().import_file(path, "excel");
} else {
LOG_ERROR("ExcelScreen", "Failed to save XLSX file");
+ // Silently logging a failed save is the worst possible outcome — the
+ // user believes their workbook is on disk when it isn't.
+ QMessageBox::warning(this, tr("Export failed"),
+ tr("Could not write the workbook to:\n%1\n\nCheck that the file is not "
+ "open in another application and that you have write permission.")
+ .arg(path));
}
#else
QMessageBox::information(this, tr("Excel Export"),
@@ -382,10 +524,36 @@ void ExcelScreen::on_add_sheet() {
QString name = generate_sheet_name();
auto* sheet = new SpreadsheetWidget(name, 100, 26, sheet_tabs_);
sheet_tabs_->addTab(sheet, name);
+ watch_sheet(sheet);
sheet_tabs_->setCurrentIndex(sheet_tabs_->count() - 1);
+ mark_dirty();
update_status();
}
+// ── Dirty tracking ───────────────────────────────────────────────────────────
+
+void ExcelScreen::watch_sheet(SpreadsheetWidget* sheet) {
+ if (sheet)
+ connect(sheet, &SpreadsheetWidget::data_changed, this, &ExcelScreen::mark_dirty);
+}
+
+void ExcelScreen::mark_dirty() {
+ if (dirty_)
+ return;
+ dirty_ = true;
+ update_status();
+}
+
+bool ExcelScreen::confirm_discard(const QString& action) {
+ if (!dirty_)
+ return true;
+ const auto reply =
+ QMessageBox::warning(this, tr("Unsaved changes"),
+ tr("\"%1\" has unsaved changes.\n\n%2 will discard them.").arg(file_name_, action),
+ QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
+ return reply == QMessageBox::Discard;
+}
+
void ExcelScreen::on_delete_sheet() {
if (sheet_tabs_->count() <= 1) {
QMessageBox::warning(this, tr("Cannot Delete"), tr("Cannot delete the last sheet."));
@@ -402,6 +570,7 @@ void ExcelScreen::on_delete_sheet() {
auto* w = sheet_tabs_->widget(idx);
sheet_tabs_->removeTab(idx);
w->deleteLater();
+ mark_dirty();
update_status();
}
}
@@ -415,13 +584,24 @@ void ExcelScreen::on_rename_sheet() {
QString current = sheet_tabs_->tabText(idx);
QString name = QInputDialog::getText(this, tr("Rename Sheet"), tr("New name:"), QLineEdit::Normal, current, &ok);
- if (ok && !name.trimmed().isEmpty()) {
- sheet_tabs_->setTabText(idx, name.trimmed());
- auto* sheet = qobject_cast<SpreadsheetWidget*>(sheet_tabs_->widget(idx));
- if (sheet)
- sheet->set_sheet_name(name.trimmed());
- update_status();
+ if (!ok || name.trimmed().isEmpty())
+ return;
+ name = name.trimmed();
+
+ // Sheet names must be unique — QXlsx::addSheet() fails on a duplicate, which
+ // used to silently drop a sheet on export.
+ for (int i = 0; i < sheet_tabs_->count(); ++i) {
+ if (i != idx && sheet_tabs_->tabText(i).compare(name, Qt::CaseInsensitive) == 0) {
+ QMessageBox::warning(this, tr("Rename Sheet"), tr("A sheet named \"%1\" already exists.").arg(name));
+ return;
+ }
}
+
+ sheet_tabs_->setTabText(idx, name);
+ if (auto* sheet = qobject_cast<SpreadsheetWidget*>(sheet_tabs_->widget(idx)))
+ sheet->set_sheet_name(name);
+ mark_dirty();
+ update_status();
}
void ExcelScreen::on_tab_changed(int index) {
@@ -439,17 +619,29 @@ SpreadsheetWidget* ExcelScreen::current_sheet() const {
}
QString ExcelScreen::generate_sheet_name() const {
- int n = sheet_tabs_->count() + 1;
- QString name;
- do {
- name = QString("Sheet%1").arg(n++);
- } while (sheet_tabs_->indexOf(sheet_tabs_->findChild<QWidget*>(name)) >= 0 || n > 999);
- return name;
+ // Compare against the TAB TEXT. The old loop asked findChild<QWidget*>(name)
+ // — sheets never have an objectName, so it always returned nullptr and the
+ // uniqueness check was a no-op: deleting "Sheet2" from Sheet1/2/3 and adding
+ // a sheet produced a duplicate "Sheet3".
+ auto taken = [this](const QString& n) {
+ for (int i = 0; i < sheet_tabs_->count(); ++i)
+ if (sheet_tabs_->tabText(i).compare(n, Qt::CaseInsensitive) == 0)
+ return true;
+ return false;
+ };
+ for (int n = sheet_tabs_->count() + 1; n <= 999; ++n) {
+ const QString name = QString("Sheet%1").arg(n);
+ if (!taken(name))
+ return name;
+ }
+ return QString("Sheet%1").arg(QDateTime::currentMSecsSinceEpoch());
}
void ExcelScreen::update_status() {
auto* sheet = current_sheet();
- QString info = tr("File: %1 | Sheets: %2").arg(file_name_).arg(sheet_tabs_->count());
+ QString info = tr("File: %1%2 | Sheets: %3")
+ .arg(file_name_, dirty_ ? QStringLiteral(" *") : QString())
+ .arg(sheet_tabs_->count());
if (sheet) {
info += tr(" | Active: %1 | %2 rows x %3 cols")
.arg(sheet->sheet_name())
diff --git a/fincept-qt/src/screens/excel/ExcelScreen.h b/fincept-qt/src/screens/excel/ExcelScreen.h
index 5180498ba..cda9e575d 100644
--- a/fincept-qt/src/screens/excel/ExcelScreen.h
+++ b/fincept-qt/src/screens/excel/ExcelScreen.h
@@ -50,11 +50,21 @@ class ExcelScreen : public QWidget, public IStatefulScreen {
SpreadsheetWidget* current_sheet() const;
QString generate_sheet_name() const;
+ /// Load a .csv into a single new sheet, replacing the current workbook.
+ bool import_csv(const QString& path);
+ /// Track edits so we can warn before discarding them.
+ void mark_dirty();
+ /// Returns true if it is safe to proceed (nothing unsaved, or the user
+ /// confirmed discarding). `action` names what is about to happen.
+ bool confirm_discard(const QString& action);
+ /// Attach a new sheet's data_changed to mark_dirty().
+ void watch_sheet(SpreadsheetWidget* sheet);
+
QTabWidget* sheet_tabs_ = nullptr;
QLabel* status_label_ = nullptr;
QString file_name_ = "Untitled.xlsx";
QString file_path_;
- int sheet_counter_ = 1;
+ bool dirty_ = false;
// Toolbar text widgets (cached for retranslateUi)
QLabel* toolbar_title_ = nullptr;
diff --git a/fincept-qt/src/screens/excel/SpreadsheetWidget.cpp b/fincept-qt/src/screens/excel/SpreadsheetWidget.cpp
index 70f652242..0f90add5b 100644
--- a/fincept-qt/src/screens/excel/SpreadsheetWidget.cpp
+++ b/fincept-qt/src/screens/excel/SpreadsheetWidget.cpp
@@ -7,15 +7,20 @@
#include <QClipboard>
#include <QHBoxLayout>
#include <QHeaderView>
+#include <QInputDialog>
+#include <QKeySequence>
#include <QLabel>
#include <QMenu>
#include <QMimeData>
#include <QRegularExpression>
#include <QSet>
+#include <QShortcut>
#include <QVBoxLayout>
#include <algorithm>
+#include <climits>
#include <cmath>
+#include <functional>
#include <numeric>
namespace fincept::screens {
@@ -211,9 +216,16 @@ QVariant SpreadsheetItem::evaluate_formula() const {
return true;
};
- auto apply_op = [&]() {
+ // Returns false when the expression is malformed (an operator with no
+ // operands, e.g. "=1++2" or "=3*-5"). The old version returned void and
+ // silently did NOT pop the operator, so the `while (precedence(...) >=
+ // ...) apply_op();` loops below spun forever and HUNG the whole UI
+ // thread on any double-operator formula. Signalling failure lets the
+ // caller bail out with #ERR instead.
+ bool div_zero = false;
+ auto apply_op = [&]() -> bool {
if (ops.isEmpty() || nums.size() < 2)
- return;
+ return false;
double b = nums.takeLast();
double a = nums.takeLast();
QChar op = ops.takeLast();
@@ -223,8 +235,16 @@ QVariant SpreadsheetItem::evaluate_formula() const {
nums.append(a - b);
else if (op == '*')
nums.append(a * b);
- else if (op == '/')
- nums.append(b != 0 ? a / b : 0);
+ else if (op == '/') {
+ if (b == 0.0) {
+ div_zero = true;
+ return false;
+ }
+ nums.append(a / b);
+ } else {
+ return false; // stray '(' — unbalanced parentheses
+ }
+ return true;
};
auto precedence = [](QChar op) -> int {
@@ -237,14 +257,19 @@ QVariant SpreadsheetItem::evaluate_formula() const {
for (int i = 0; i < eval_expr.length(); ++i) {
QChar ch = eval_expr[i];
- if (ch.isDigit() || ch == '.' || ch == 'e' || ch == 'E' ||
- (ch == '-' && (i == 0 || eval_expr[i - 1] == '('))) {
+ // A '-' is unary (part of the number) at the start of the expression,
+ // right after '(', or right after another operator — "3*-5", "2^-1".
+ const bool unary_minus =
+ ch == '-' && (i == 0 || eval_expr[i - 1] == '(' || eval_expr[i - 1] == '+' ||
+ eval_expr[i - 1] == '-' || eval_expr[i - 1] == '*' || eval_expr[i - 1] == '/');
+ if (ch.isDigit() || ch == '.' || ch == 'e' || ch == 'E' || unary_minus) {
num_buf += ch;
} else if (ch == '+' || ch == '-' || ch == '*' || ch == '/') {
if (!flush_num())
return QVariant("#ERR");
- while (!ops.isEmpty() && precedence(ops.last()) >= precedence(ch)) {
- apply_op();
+ while (!ops.isEmpty() && ops.last() != '(' && precedence(ops.last()) >= precedence(ch)) {
+ if (!apply_op())
+ return QVariant(div_zero ? "#DIV/0!" : "#ERR");
}
ops.append(ch);
} else if (ch == '(') {
@@ -253,23 +278,30 @@ QVariant SpreadsheetItem::evaluate_formula() const {
if (!flush_num())
return QVariant("#ERR");
while (!ops.isEmpty() && ops.last() != '(') {
- apply_op();
+ if (!apply_op())
+ return QVariant(div_zero ? "#DIV/0!" : "#ERR");
}
- if (!ops.isEmpty())
- ops.removeLast(); // remove '('
+ if (ops.isEmpty())
+ return QVariant("#ERR"); // ')' with no matching '('
+ ops.removeLast(); // remove '('
}
}
if (!flush_num())
return QVariant("#ERR");
while (!ops.isEmpty()) {
- apply_op();
+ if (!apply_op())
+ return QVariant(div_zero ? "#DIV/0!" : "#ERR");
}
if (nums.size() == 1) {
double result = nums.first();
+ if (!std::isfinite(result))
+ return QVariant("#NUM!");
if (std::floor(result) == result && std::abs(result) < 1e15)
return static_cast<qlonglong>(result);
- return QString::number(result, 'f', 6);
+ // 'g' with 12 significant digits: 2.5 renders as "2.5", not
+ // "2.500000", while still keeping precision on long decimals.
+ return QString::number(result, 'g', 12);
}
} catch (...) {
// fall through
@@ -371,6 +403,44 @@ void SpreadsheetWidget::build_ui(int rows, int cols) {
colors::TEXT_SECONDARY())); // %7 header text
root->addWidget(table_, 1);
+
+ table_->setAccessibleName(tr("Spreadsheet grid"));
+ formula_bar_->setAccessibleName(tr("Formula bar"));
+ cell_ref_label_->setAccessibleName(tr("Active cell reference"));
+ setTabOrder(formula_bar_, table_);
+
+ install_shortcuts();
+}
+
+// ── Keyboard shortcuts ───────────────────────────────────────────────────────
+// QTableWidget ships with no clipboard or find handling, so a spreadsheet
+// without these bindings feels broken: Ctrl+C did nothing and Delete did
+// nothing. Scoped to this widget so they don't collide with other screens.
+
+void SpreadsheetWidget::install_shortcuts() {
+ // WidgetWithChildrenShortcut also covers the in-place cell editor, so every
+ // grid-level binding must stand down while a cell is being edited —
+ // otherwise Delete would blank the whole selection mid-keystroke and Ctrl+C
+ // would copy cells instead of the selected characters.
+ auto add = [this](QKeySequence::StandardKey key, std::function<void()> fn) {
+ auto* sc = new QShortcut(QKeySequence(key), this);
+ sc->setContext(Qt::WidgetWithChildrenShortcut);
+ connect(sc, &QShortcut::activated, this, [this, fn = std::move(fn)]() {
+ // QAbstractItemView::state() is protected, so detect an open in-place
+ // editor via focus instead: the delegate's editor is a child widget of
+ // the table, and it (not the table) holds focus while editing.
+ const QWidget* fw = QApplication::focusWidget();
+ if (fw && fw != table_ && table_->isAncestorOf(fw))
+ return;
+ fn();
+ });
+ };
+ add(QKeySequence::Copy, [this]() { copy_selection(false); });
+ add(QKeySequence::Cut, [this]() { copy_selection(true); });
+ add(QKeySequence::Paste, [this]() { paste_clipboard(); });
+ add(QKeySequence::Delete, [this]() { clear_selection(); });
+ add(QKeySequence::Find, [this]() { find_next(true); });
+ add(QKeySequence::FindNext, [this]() { find_next(false); });
}
void SpreadsheetWidget::setup_headers(int cols) {
@@ -411,7 +481,11 @@ void SpreadsheetWidget::set_data(const QVector<QVector<QString>>& cells) {
table_->blockSignals(true);
int rows = cells.size();
- int cols = rows > 0 ? cells[0].size() : 26;
+ // Take the WIDEST row, not row 0 — a ragged import (CSV with a short header
+ // line) previously truncated every following row to the header's width.
+ int cols = 0;
+ for (const auto& row : cells)
+ cols = std::max<int>(cols, row.size());
// Ensure minimum size
rows = std::max(rows, 100);
@@ -517,26 +591,12 @@ void SpreadsheetWidget::on_context_menu(const QPoint& pos) {
.arg(colors::BORDER_MED(), colors::TEXT_PRIMARY(), colors::TEXT_DIM(), fonts::DATA_FAMILY,
colors::TEXT_DIM()));
- menu.addAction(tr("Cut"), this, [this]() {
- auto* item = table_->currentItem();
- if (!item)
- return;
- QApplication::clipboard()->setText(item->data(Qt::DisplayRole).toString());
- set_cell(table_->currentRow(), table_->currentColumn(), "");
- });
- menu.addAction(tr("Copy"), this, [this]() {
- auto* item = table_->currentItem();
- if (!item)
- return;
- QApplication::clipboard()->setText(item->data(Qt::DisplayRole).toString());
- });
- menu.addAction(tr("Paste"), this, [this]() {
- QString text = QApplication::clipboard()->text();
- if (text.isEmpty())
- return;
- set_cell(table_->currentRow(), table_->currentColumn(), text);
- recalculate();
- });
+ // Route the menu through the same range-aware clipboard the Ctrl+X/C/V
+ // shortcuts use — the old handlers only ever touched the single active cell
+ // and copied the *displayed* value, so copying a formula lost the formula.
+ menu.addAction(tr("Cut"), this, [this]() { copy_selection(true); });
+ menu.addAction(tr("Copy"), this, [this]() { copy_selection(false); });
+ menu.addAction(tr("Paste"), this, [this]() { paste_clipboard(); });
menu.addSeparator();
menu.addAction(tr("Insert Row Above"), this, &SpreadsheetWidget::insert_row_above);
menu.addAction(tr("Insert Row Below"), this, &SpreadsheetWidget::insert_row_below);
@@ -546,17 +606,9 @@ void SpreadsheetWidget::on_context_menu(const QPoint& pos) {
menu.addAction(tr("Delete Selected Rows"), this, &SpreadsheetWidget::delete_selected_rows);
menu.addAction(tr("Delete Selected Columns"), this, &SpreadsheetWidget::delete_selected_cols);
menu.addSeparator();
- menu.addAction(tr("Clear Cell"), this, [this]() {
- auto ranges = table_->selectedRanges();
- for (const auto& range : ranges) {
- for (int r = range.topRow(); r <= range.bottomRow(); ++r) {
- for (int c = range.leftColumn(); c <= range.rightColumn(); ++c) {
- set_cell(r, c, "");
- }
- }
- }
- recalculate();
- });
+ menu.addAction(tr("Clear Cell"), this, [this]() { clear_selection(); });
+ menu.addSeparator();
+ menu.addAction(tr("Find…"), this, [this]() { find_next(true); });
menu.exec(table_->viewport()->mapToGlobal(pos));
}
@@ -571,6 +623,7 @@ void SpreadsheetWidget::insert_row_above() {
for (int c = 0; c < table_->columnCount(); ++c) {
table_->setItem(row, c, new SpreadsheetItem());
}
+ emit data_changed(); // structure edits are edits — mark the sheet dirty
}
void SpreadsheetWidget::insert_row_below() {
@@ -579,6 +632,7 @@ void SpreadsheetWidget::insert_row_below() {
for (int c = 0; c < table_->columnCount(); ++c) {
table_->setItem(row, c, new SpreadsheetItem());
}
+ emit data_changed();
}
void SpreadsheetWidget::insert_col_left() {
@@ -590,6 +644,7 @@ void SpreadsheetWidget::insert_col_left() {
table_->setItem(r, col, new SpreadsheetItem());
}
setup_headers(table_->columnCount());
+ emit data_changed();
}
void SpreadsheetWidget::insert_col_right() {
@@ -599,6 +654,7 @@ void SpreadsheetWidget::insert_col_right() {
table_->setItem(r, col, new SpreadsheetItem());
}
setup_headers(table_->columnCount());
+ emit data_changed();
}
void SpreadsheetWidget::delete_selected_rows() {
@@ -610,10 +666,13 @@ void SpreadsheetWidget::delete_selected_rows() {
rows.append(r);
}
}
+ if (rows.isEmpty())
+ return;
std::sort(rows.begin(), rows.end(), std::greater<int>());
for (int r : rows) {
table_->removeRow(r);
}
+ emit data_changed();
}
void SpreadsheetWidget::delete_selected_cols() {
@@ -625,11 +684,154 @@ void SpreadsheetWidget::delete_selected_cols() {
cols.append(c);
}
}
+ if (cols.isEmpty())
+ return;
std::sort(cols.begin(), cols.end(), std::greater<int>());
for (int c : cols) {
table_->removeColumn(c);
}
setup_headers(table_->columnCount());
+ emit data_changed();
+}
+
+// ── Clipboard (TSV, Excel-compatible) ────────────────────────────────────────
+
+void SpreadsheetWidget::copy_selection(bool cut) {
+ const auto ranges = table_->selectedRanges();
+ if (ranges.isEmpty()) {
+ auto* item = table_->currentItem();
+ if (!item)
+ return;
+ QApplication::clipboard()->setText(cell_text(table_->currentRow(), table_->currentColumn()));
+ if (cut) {
+ set_cell(table_->currentRow(), table_->currentColumn(), QString());
+ recalculate();
+ emit data_changed();
+ }
+ return;
+ }
+
+ // Use the bounding box of the selection so a rectangular copy round-trips
+ // through Excel / Google Sheets unchanged.
+ int top = INT_MAX, left = INT_MAX, bottom = -1, right = -1;
+ for (const auto& r : ranges) {
+ top = std::min(top, r.topRow());
+ left = std::min(left, r.leftColumn());
+ bottom = std::max(bottom, r.bottomRow());
+ right = std::max(right, r.rightColumn());
+ }
+
+ QStringList lines;
+ lines.reserve(bottom - top + 1);
+ for (int r = top; r <= bottom; ++r) {
+ QStringList row;
+ row.reserve(right - left + 1);
+ for (int c = left; c <= right; ++c)
+ row << cell_text(r, c);
+ lines << row.join('\t');
+ }
+ QApplication::clipboard()->setText(lines.join('\n'));
+
+ if (cut) {
+ for (int r = top; r <= bottom; ++r)
+ for (int c = left; c <= right; ++c)
+ set_cell(r, c, QString());
+ recalculate();
+ emit data_changed();
+ }
+}
+
+void SpreadsheetWidget::paste_clipboard() {
+ const QString text = QApplication::clipboard()->text();
+ if (text.isEmpty())
+ return;
+ int row = table_->currentRow();
+ int col = table_->currentColumn();
+ if (row < 0)
+ row = 0;
+ if (col < 0)
+ col = 0;
+
+ // Split on \n but tolerate CRLF from Windows apps; a single value with no
+ // separators still pastes into the one active cell.
+ const QStringList lines = text.split('\n');
+ for (int i = 0; i < lines.size(); ++i) {
+ QString line = lines[i];
+ if (line.endsWith('\r'))
+ line.chop(1);
+ // A trailing newline shouldn't create a phantom blank row.
+ if (line.isEmpty() && i == lines.size() - 1)
+ break;
+ const QStringList cells = line.split('\t');
+ const int target_row = row + i;
+ if (target_row >= table_->rowCount())
+ table_->setRowCount(target_row + 1);
+ for (int j = 0; j < cells.size(); ++j) {
+ const int target_col = col + j;
+ if (target_col >= table_->columnCount()) {
+ table_->setColumnCount(target_col + 1);
+ setup_headers(table_->columnCount());
+ }
+ set_cell(target_row, target_col, cells[j]);
+ }
+ }
+ recalculate();
+ emit data_changed();
+}
+
+void SpreadsheetWidget::clear_selection() {
+ const auto ranges = table_->selectedRanges();
+ if (ranges.isEmpty()) {
+ if (table_->currentRow() < 0)
+ return;
+ set_cell(table_->currentRow(), table_->currentColumn(), QString());
+ } else {
+ for (const auto& range : ranges)
+ for (int r = range.topRow(); r <= range.bottomRow(); ++r)
+ for (int c = range.leftColumn(); c <= range.rightColumn(); ++c)
+ set_cell(r, c, QString());
+ }
+ recalculate();
+ emit data_changed();
+}
+
+// ── Find ─────────────────────────────────────────────────────────────────────
+
+void SpreadsheetWidget::find_next(bool prompt) {
+ if (prompt || last_find_.isEmpty()) {
+ bool ok = false;
+ const QString term =
+ QInputDialog::getText(this, tr("Find"), tr("Find text:"), QLineEdit::Normal, last_find_, &ok);
+ if (!ok || term.isEmpty())
+ return;
+ last_find_ = term;
+ }
+
+ const int rows = table_->rowCount();
+ const int cols = table_->columnCount();
+ if (rows == 0 || cols == 0)
+ return;
+
+ // Start just after the active cell so repeated F3 walks the sheet, wrapping
+ // once back to the origin.
+ const int start = std::max(0, table_->currentRow()) * cols + std::max(0, table_->currentColumn()) + 1;
+ const int total = rows * cols;
+ for (int n = 0; n < total; ++n) {
+ const int idx = (start + n) % total;
+ const int r = idx / cols;
+ const int c = idx % cols;
+ auto* item = table_->item(r, c);
+ if (!item)
+ continue;
+ // Match on what the user SEES (the evaluated value) as well as the raw
+ // formula text, so searching "1500" finds a cell showing =SUM(A1:A9).
+ if (item->data(Qt::DisplayRole).toString().contains(last_find_, Qt::CaseInsensitive) ||
+ cell_text(r, c).contains(last_find_, Qt::CaseInsensitive)) {
+ table_->setCurrentCell(r, c);
+ table_->scrollToItem(item, QAbstractItemView::PositionAtCenter);
+ return;
+ }
+ }
}
} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/excel/SpreadsheetWidget.h b/fincept-qt/src/screens/excel/SpreadsheetWidget.h
index 60e6874a5..6745f44f4 100644
--- a/fincept-qt/src/screens/excel/SpreadsheetWidget.h
+++ b/fincept-qt/src/screens/excel/SpreadsheetWidget.h
@@ -74,7 +74,19 @@ class SpreadsheetWidget : public QWidget {
void delete_selected_rows();
void delete_selected_cols();
+ /// Clipboard over the whole selected range (TSV, Excel-compatible).
+ /// Copies the RAW cell text (formulas included), matching Excel semantics.
+ void copy_selection(bool cut = false);
+ void paste_clipboard();
+ /// Blank every cell in the selection (Delete key).
+ void clear_selection();
+ /// Prompt for text and select the next matching cell (Ctrl+F / F3).
+ void find_next(bool prompt = true);
+
signals:
+ /// Emitted on any mutation of sheet content or structure — cell edits,
+ /// paste, clear, and row/column insert/delete. ExcelScreen uses it to drive
+ /// the dirty marker and the unsaved-changes guard.
void data_changed();
private slots:
@@ -86,6 +98,7 @@ class SpreadsheetWidget : public QWidget {
private:
void build_ui(int rows, int cols);
void setup_headers(int cols);
+ void install_shortcuts();
static QString column_label(int col);
QTableWidget* table_ = nullptr;
@@ -94,6 +107,7 @@ class SpreadsheetWidget : public QWidget {
QString sheet_name_;
bool updating_formula_bar_ = false;
+ QString last_find_; // remembered Ctrl+F term so F3 can repeat it
};
} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/file_manager/FileManagerScreen.cpp b/fincept-qt/src/screens/file_manager/FileManagerScreen.cpp
index 777a4765e..f3a235363 100644
--- a/fincept-qt/src/screens/file_manager/FileManagerScreen.cpp
+++ b/fincept-qt/src/screens/file_manager/FileManagerScreen.cpp
@@ -16,10 +16,14 @@
#include <QHeaderView>
#include <QJsonDocument>
#include <QMessageBox>
+#include <QMouseEvent>
+#include <QPalette>
#include <QScrollArea>
+#include <QScrollBar>
#include <QShowEvent>
#include <QSplitter>
#include <QTextStream>
+#include <QTimer>
#include <QVBoxLayout>
namespace fincept::screens {
@@ -80,6 +84,9 @@ void FileManagerScreen::build_ui() {
refresh_btn_ = new QPushButton(tr("REFRESH"));
refresh_btn_->setCursor(Qt::PointingHandCursor);
+ // No F5 shortcut here — KeyConfigManager owns F5 as the global Refresh
+ // action (Qt::ApplicationShortcut); a second binding makes both ambiguous.
+ refresh_btn_->setAccessibleName(tr("Refresh the file list"));
refresh_btn_->setStyleSheet(
QString("QPushButton{background:transparent;color:%1;border:1px solid %2;"
"padding:4px 12px;font-size:11px;%3}"
@@ -93,6 +100,7 @@ void FileManagerScreen::build_ui() {
upload_btn_ = new QPushButton(tr("UPLOAD FILES"));
upload_btn_->setCursor(Qt::PointingHandCursor);
+ upload_btn_->setAccessibleName(tr("Copy files into terminal storage"));
upload_btn_->setStyleSheet(QString("QPushButton{background:rgba(217,119,6,0.1);color:%1;border:1px solid %3;"
"padding:4px 12px;font-size:11px;font-weight:700;%2}"
"QPushButton:hover{background:%1;color:%4;}")
@@ -122,6 +130,7 @@ void FileManagerScreen::build_ui() {
bulk_delete_btn_ = new QPushButton(tr("DELETE SELECTED"));
bulk_delete_btn_->setCursor(Qt::PointingHandCursor);
+ bulk_delete_btn_->setAccessibleName(tr("Delete the selected files"));
bulk_delete_btn_->setStyleSheet(QString("QPushButton{background:transparent;color:%1;border:1px solid #7f1d1d;"
"padding:3px 12px;font-size:11px;font-weight:700;%2}"
"QPushButton:hover{background:%1;color:%3;}")
@@ -136,9 +145,11 @@ void FileManagerScreen::build_ui() {
"padding:3px 12px;font-size:11px;%3}"
"QPushButton:hover{color:%4;}")
.arg(colors::TEXT_DIM(), colors::BORDER_DIM(), MF, colors::TEXT_PRIMARY()));
+ bulk_clear_btn_->setAccessibleName(tr("Clear the file selection"));
connect(bulk_clear_btn_, &QPushButton::clicked, this, [this]() {
for (auto* btn : check_btns_)
btn->setChecked(false);
+ checked_ids_.clear();
update_bulk_bar();
});
bbl->addWidget(bulk_clear_btn_);
@@ -150,22 +161,51 @@ void FileManagerScreen::build_ui() {
splitter_->setChildrenCollapsible(false);
// Left: scroll area with file cards
- auto* scroll = new QScrollArea;
- scroll->setWidgetResizable(true);
- scroll->setStyleSheet("QScrollArea{border:none;background:transparent;}"
- "QScrollBar:vertical{background:transparent;width:6px;}" +
- QString("QScrollBar::handle:vertical{background:%1;}"
- "QScrollBar::add-line:vertical,QScrollBar::sub-line:vertical{height:0;}")
- .arg(colors::BORDER_MED()));
+ file_scroll_ = new QScrollArea;
+ file_scroll_->setWidgetResizable(true);
+ file_scroll_->setStyleSheet("QScrollArea{border:none;background:transparent;}"
+ "QScrollBar:vertical{background:transparent;width:6px;}" +
+ QString("QScrollBar::handle:vertical{background:%1;}"
+ "QScrollBar::add-line:vertical,QScrollBar::sub-line:vertical{height:0;}")
+ .arg(colors::BORDER_MED()));
file_container_ = new QWidget(this);
- file_container_->setStyleSheet(QString("background:%1;").arg(colors::BG_BASE()));
+ file_container_->setObjectName("FMFileList"); // must precede setStyleSheet so #FMFileList resolves
+ // One stylesheet for the whole card list, keyed on object names. render_files()
+ // used to call setStyleSheet() ~10x per card, i.e. a full CSS reparse per
+ // widget per refresh; with a few hundred files that dominated the render.
+ file_container_->setStyleSheet(
+ QString("QWidget#FMFileList{background:%1;}"
+ "QWidget#FMCard{background:%2;border:1px solid %3;border-radius:2px;}"
+ "QWidget#FMCardInfo{background:transparent;}"
+ "QLabel#FMGroupLabel{color:%4;font-size:10px;font-weight:700;letter-spacing:1px;"
+ " background:transparent;padding:8px 0 2px 0;%9}"
+ "QLabel#FMFileName{color:%5;font-size:12px;font-weight:600;background:transparent;%9}"
+ "QLabel#FMFileMeta{color:%4;font-size:10px;background:transparent;%9}"
+ "QLabel#FMTypeBadge{font-size:10px;font-weight:700;background:transparent;%9}"
+ "QPushButton#FMCheck{background:transparent;color:%4;border:none;font-size:14px;}"
+ "QPushButton#FMCheck:checked{color:%6;}"
+ "QPushButton#FMPreview{background:transparent;color:%4;border:1px solid %3;"
+ " font-size:10px;font-weight:700;padding:0 8px;%9}"
+ "QPushButton#FMPreview:hover{color:%6;border-color:%6;}"
+ "QPushButton#FMOpenWith{background:transparent;color:%6;border:1px solid %3;"
+ " font-size:10px;font-weight:700;padding:0 8px;%9}"
+ "QPushButton#FMOpenWith:hover{background:rgba(217,119,6,0.15);}"
+ "QPushButton#FMSave{background:transparent;color:%7;border:1px solid %3;"
+ " font-size:10px;font-weight:700;%9}"
+ "QPushButton#FMSave:hover{color:#38bdf8;background:%8;}"
+ "QPushButton#FMDelete{background:transparent;color:%4;border:1px solid %3;"
+ " font-size:10px;font-weight:700;%9}"
+ "QPushButton#FMDelete:hover{color:%10;background:rgba(239,68,68,0.1);}")
+ .arg(colors::BG_BASE(), colors::BG_SURFACE(), colors::BORDER_DIM(), colors::TEXT_DIM(),
+ colors::TEXT_PRIMARY(), colors::AMBER(), colors::CYAN(), colors::BG_RAISED(), QString(MF))
+ .arg(colors::NEGATIVE()));
file_layout_ = new QVBoxLayout(file_container_);
file_layout_->setContentsMargins(14, 8, 14, 8);
file_layout_->setSpacing(6);
file_layout_->addStretch();
- scroll->setWidget(file_container_);
- splitter_->addWidget(scroll);
+ file_scroll_->setWidget(file_container_);
+ splitter_->addWidget(file_scroll_);
// Right: preview panel (initially hidden)
splitter_->addWidget(build_preview_panel());
@@ -220,6 +260,8 @@ void FileManagerScreen::build_filter_bar(QVBoxLayout* root) {
search_input_ = new QLineEdit;
search_input_->setPlaceholderText(tr("Search files by name, type, or source..."));
+ search_input_->setClearButtonEnabled(true);
+ search_input_->setAccessibleName(tr("Search files"));
search_input_->setStyleSheet(
QString("QLineEdit{background:%1;color:%2;border:1px solid %3;"
"padding:5px 10px;font-size:12px;%4}"
@@ -238,6 +280,7 @@ void FileManagerScreen::build_filter_bar(QVBoxLayout* root) {
sort_combo_ = new QComboBox;
for (int i = 0; i < 7; ++i)
sort_combo_->addItem(QString());
+ sort_combo_->setAccessibleName(tr("Sort order"));
sort_combo_->setStyleSheet(
QString("QComboBox{background:%1;color:%2;border:1px solid %3;"
"padding:4px 8px;font-size:11px;%4}"
@@ -269,15 +312,22 @@ void FileManagerScreen::build_filter_bar(QVBoxLayout* root) {
"algo_trading", "ai_quant_lab", "notes", "code_editor", "report_builder",
"data_sources", "excel"};
for (const QString& s : screens) {
- QString label = (s == "All") ? "All" : QString(s).replace('_', ' ').toUpper();
+ const QString filter_val = (s == "All") ? QString() : s;
+ QString label = (s == "All") ? tr("All") : QString(s).replace('_', ' ').toUpper();
auto* chip = new QPushButton(label);
chip->setCheckable(true);
chip->setStyleSheet(chip_ss);
+ // Carry the raw screen key as a property. restore_state() used to
+ // compare against the chip's *display* text ("EQUITY RESEARCH"), which
+ // never matched the stored key ("equity_research"), so a restored
+ // filter silently fell back to All.
+ chip->setProperty("screenFilter", filter_val);
+ chip->setAccessibleName(s == "All" ? tr("Show files from all screens")
+ : tr("Show files from %1").arg(label));
if (s == "All")
chip->setChecked(true);
chip_group_->addButton(chip);
cl->addWidget(chip);
- QString filter_val = (s == "All") ? "" : s;
connect(chip, &QPushButton::toggled, this, [this, filter_val](bool checked) {
if (checked) {
active_screen_filter_ = filter_val;
@@ -389,6 +439,22 @@ void FileManagerScreen::showEvent(QShowEvent* event) {
}
}
+bool FileManagerScreen::eventFilter(QObject* watched, QEvent* event) {
+ // Card bodies carry the file id in a dynamic property; a left-click on any
+ // non-button part of a card opens the preview.
+ if (event->type() == QEvent::MouseButtonRelease) {
+ auto* me = static_cast<QMouseEvent*>(event);
+ if (me->button() == Qt::LeftButton) {
+ const QVariant fid = watched->property("fileId");
+ if (fid.isValid() && !fid.toString().isEmpty()) {
+ show_preview(fid.toString());
+ return true;
+ }
+ }
+ }
+ return QWidget::eventFilter(watched, event);
+}
+
// ── File operations ───────────────────────────────────────────────────────────
void FileManagerScreen::upload_files() {
@@ -406,13 +472,40 @@ void FileManagerScreen::download_file(const QString& file_id) {
QString dest = QFileDialog::getSaveFileName(this, tr("Save File As"), f.original_name);
if (dest.isEmpty())
return;
- QString src = FileManagerService::instance().full_path(f.name);
- if (QFile::exists(dest))
- QFile::remove(dest);
- if (!QFile::copy(src, dest))
- QMessageBox::warning(this, tr("Download Failed"), tr("Could not save file to selected location."));
- else
- LOG_INFO("FileManager", "Downloaded: " + f.original_name);
+
+ const QString src = FileManagerService::instance().full_path(f.name);
+ if (!QFile::exists(src)) {
+ QMessageBox::warning(this, tr("Save Failed"),
+ tr("The stored file is missing from disk:\n%1\n\n"
+ "Its index entry is stale — delete it and re-import.")
+ .arg(src));
+ return;
+ }
+
+ // Write to a sibling temp file first. The old code removed the destination
+ // and *then* copied: a failure at that point destroyed whatever the user
+ // had chosen to overwrite.
+ const QString staging = dest + QStringLiteral(".fincept-partial");
+ QFile::remove(staging);
+ if (!QFile::copy(src, staging)) {
+ QMessageBox::warning(this, tr("Save Failed"),
+ tr("Could not write to:\n%1\n\nCheck that the folder exists and is writable.")
+ .arg(dest));
+ return;
+ }
+ if (QFile::exists(dest) && !QFile::remove(dest)) {
+ QFile::remove(staging);
+ QMessageBox::warning(this, tr("Save Failed"),
+ tr("Could not replace the existing file:\n%1\n\nIt may be open in another program.")
+ .arg(dest));
+ return;
+ }
+ if (!QFile::rename(staging, dest)) {
+ QFile::remove(staging);
+ QMessageBox::warning(this, tr("Save Failed"), tr("Could not finish writing:\n%1").arg(dest));
+ return;
+ }
+ LOG_INFO("FileManager", "Downloaded: " + f.original_name);
}
void FileManagerScreen::delete_file(const QString& file_id) {
@@ -421,26 +514,60 @@ void FileManagerScreen::delete_file(const QString& file_id) {
return;
auto reply =
QMessageBox::question(this, tr("Delete File"), tr("Delete \"%1\"? This cannot be undone.").arg(f.original_name),
- QMessageBox::Yes | QMessageBox::No);
- if (reply == QMessageBox::Yes)
- FileManagerService::instance().remove_file(file_id);
+ QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
+ if (reply != QMessageBox::Yes)
+ return;
+ checked_ids_.remove(file_id);
+ if (!FileManagerService::instance().remove_file(file_id)) {
+ QMessageBox::warning(this, tr("Delete File"),
+ tr("Could not delete \"%1\" — it may be open in another program.").arg(f.original_name));
+ }
}
void FileManagerScreen::delete_selected() {
QStringList to_delete;
+ QStringList names;
for (int i = 0; i < check_btns_.size(); ++i) {
- if (check_btns_[i]->isChecked())
+ if (check_btns_[i]->isChecked()) {
to_delete << check_ids_[i];
+ const auto f = FileManagerService::instance().find_by_id(check_ids_[i]);
+ if (!f.original_name.isEmpty() && names.size() < 12)
+ names << f.original_name;
+ }
}
if (to_delete.isEmpty())
return;
- auto reply = QMessageBox::question(this, tr("Delete Files"),
- tr("Delete %n selected file(s)? This cannot be undone.", "", to_delete.size()),
- QMessageBox::Yes | QMessageBox::No);
- if (reply != QMessageBox::Yes)
+
+ // Name what is about to be destroyed — a bare count is not enough
+ // confirmation for an irreversible multi-file delete.
+ QMessageBox box(this);
+ box.setIcon(QMessageBox::Warning);
+ box.setWindowTitle(tr("Delete Files"));
+ box.setText(tr("Delete %n selected file(s)?", "", static_cast<int>(to_delete.size())));
+ box.setInformativeText(tr("This cannot be undone."));
+ if (!names.isEmpty()) {
+ box.setDetailedText(names.join('\n') +
+ (to_delete.size() > names.size()
+ ? tr("\n… and %n more", "", static_cast<int>(to_delete.size() - names.size()))
+ : QString()));
+ }
+ box.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
+ box.setDefaultButton(QMessageBox::No);
+ if (box.exec() != QMessageBox::Yes)
return;
- for (const QString& id : to_delete)
- FileManagerService::instance().remove_file(id);
+
+ int failed = 0;
+ for (const QString& id : to_delete) {
+ if (FileManagerService::instance().remove_file(id))
+ checked_ids_.remove(id);
+ else
+ ++failed;
+ }
+ if (failed > 0) {
+ QMessageBox::warning(this, tr("Delete Files"),
+ tr("%n file(s) could not be deleted — they may be open in another program.", "", failed));
+ }
+ update_bulk_bar();
}
void FileManagerScreen::open_with(const QString& file_id) {
@@ -571,6 +698,11 @@ void FileManagerScreen::update_bulk_bar() {
// ── Rendering ─────────────────────────────────────────────────────────────────
void FileManagerScreen::render_files() {
+ // Preserve where the user was — this is a full teardown and the service's
+ // files_changed signal calls it on every import/delete from any screen.
+ const int scroll_pos =
+ (file_scroll_ && file_scroll_->verticalScrollBar()) ? file_scroll_->verticalScrollBar()->value() : 0;
+
check_btns_.clear();
check_ids_.clear();
@@ -584,6 +716,17 @@ void FileManagerScreen::render_files() {
int sort_idx = sort_combo_ ? sort_combo_->currentIndex() : 0;
QJsonArray all = FileManagerService::instance().all_files();
+ // Drop checked ids for files that no longer exist, so the bulk bar can't
+ // claim a selection that points at nothing.
+ if (!checked_ids_.isEmpty()) {
+ QSet<QString> live_ids;
+ for (const auto& v : all) {
+ if (v.isObject())
+ live_ids.insert(v.toObject()["id"].toString());
+ }
+ checked_ids_.intersect(live_ids);
+ }
+
// Filter
QVector<QJsonObject> files;
for (const auto& v : all) {
@@ -666,21 +809,26 @@ void FileManagerScreen::render_files() {
.arg(colors::TEXT_DIM(), MF));
skl->addWidget(sources_lbl);
+ // tr() must see literals at extraction time — the previous version
+ // called tr(runtime_qstring.toUtf8().constData()), which lupdate
+ // cannot extract, so none of these ever had a translation.
struct SI {
- QString icon, name, desc;
+ const char* icon;
+ QString name;
+ QString desc;
};
- static const SI sources[] = {
- {"RPT", "Report Builder", "Saved reports and exported PDFs"},
- {"NTB", "Code Editor", "Saved Jupyter notebooks (.ipynb)"},
- {"XLS", "Excel", "Imported/exported spreadsheets & CSV"},
- {"NOTE", "Notes", "Exported markdown note files"},
- {"PFL", "Portfolio", "Portfolio CSV & JSON exports"},
- {"DS", "Data Sources", "Connector configuration JSON"},
- {"ALG", "Algo Trading", "Saved strategy definitions"},
- {"BT", "Backtesting", "Backtest result JSON exports"},
- {"AQL", "AI Quant Lab", "Module result exports"},
- {"NEWS", "News", "Saved article text files"},
- {"EQR", "Equity Research", "Financial statement CSV exports"},
+ const SI sources[] = {
+ {"RPT", tr("Report Builder"), tr("Saved reports and exported PDFs")},
+ {"NTB", tr("Code Editor"), tr("Saved Jupyter notebooks (.ipynb)")},
+ {"XLS", tr("Excel"), tr("Imported/exported spreadsheets & CSV")},
+ {"NOTE", tr("Notes"), tr("Exported markdown note files")},
+ {"PFL", tr("Portfolio"), tr("Portfolio CSV & JSON exports")},
+ {"DS", tr("Data Sources"), tr("Connector configuration JSON")},
+ {"ALG", tr("Algo Trading"), tr("Saved strategy definitions")},
+ {"BT", tr("Backtesting"), tr("Backtest result JSON exports")},
+ {"AQL", tr("AI Quant Lab"), tr("Module result exports")},
+ {"NEWS", tr("News"), tr("Saved article text files")},
+ {"EQR", tr("Equity Research"), tr("Financial statement CSV exports")},
};
auto* grid_w = new QWidget(this);
@@ -709,11 +857,11 @@ void FileManagerScreen::render_files() {
auto* tl = new QVBoxLayout(txt);
tl->setContentsMargins(0, 0, 0, 0);
tl->setSpacing(1);
- auto* nl = new QLabel(tr(s.name.toUtf8().constData()));
+ auto* nl = new QLabel(s.name);
nl->setStyleSheet(QString("color:%1;font-size:11px;font-weight:600;background:transparent;%2")
.arg(colors::TEXT_PRIMARY(), MF));
tl->addWidget(nl);
- auto* dl = new QLabel(tr(s.desc.toUtf8().constData()));
+ auto* dl = new QLabel(s.desc);
dl->setStyleSheet(
QString("color:%1;font-size:10px;background:transparent;%2").arg(colors::TEXT_DIM(), MF));
tl->addWidget(dl);
@@ -759,83 +907,94 @@ void FileManagerScreen::render_files() {
return;
}
- // Group by source screen
+ // Group by source screen. Every widget below is styled by object name via
+ // the single container stylesheet installed in build_ui() — no per-row
+ // setStyleSheet() calls, which is what made a large file list slow.
QString current_group;
for (const QJsonObject& file : files) {
QString source = file["sourceScreen"].toString();
if (active_screen_filter_.isEmpty() && source != current_group) {
current_group = source;
auto* grp_lbl = new QLabel(source.toUpper().replace('_', ' '));
- grp_lbl->setStyleSheet(QString("color:%1;font-size:10px;font-weight:700;letter-spacing:1px;"
- "background:transparent;padding:8px 0 2px 0;%2")
- .arg(colors::TEXT_DIM(), MF));
+ grp_lbl->setObjectName("FMGroupLabel");
file_layout_->addWidget(grp_lbl);
}
+ const QString fid = file["id"].toString();
+ const QString display_name = file["originalName"].toString();
+
// ── Card ─────────────────────────────────────────────────────────────
auto* card = new QWidget(this);
- card->setStyleSheet(panel_ss());
+ card->setObjectName("FMCard");
card->setCursor(Qt::PointingHandCursor);
auto* hl = new QHBoxLayout(card);
hl->setContentsMargins(8, 8, 12, 8);
hl->setSpacing(8);
- // Checkbox
- auto* chk = new QPushButton("☐");
+ // Checkbox — restore its state from checked_ids_ so a refresh (which
+ // the files_changed signal triggers) doesn't silently drop a pending
+ // bulk selection.
+ auto* chk = new QPushButton(checked_ids_.contains(fid) ? "☑" : "☐");
+ chk->setObjectName("FMCheck");
chk->setCheckable(true);
+ chk->setChecked(checked_ids_.contains(fid));
chk->setFixedSize(22, 22);
- chk->setStyleSheet(QString("QPushButton{background:transparent;color:%1;border:none;font-size:14px;}"
- "QPushButton:checked{color:%2;}")
- .arg(colors::TEXT_DIM(), colors::AMBER()));
- connect(chk, &QPushButton::toggled, this, [this, chk](bool checked) {
+ chk->setAccessibleName(tr("Select %1").arg(display_name));
+ connect(chk, &QPushButton::toggled, this, [this, chk, fid](bool checked) {
chk->setText(checked ? "☑" : "☐");
+ if (checked)
+ checked_ids_.insert(fid);
+ else
+ checked_ids_.remove(fid);
update_bulk_bar();
});
check_btns_.append(chk);
- check_ids_.append(file["id"].toString());
+ check_ids_.append(fid);
hl->addWidget(chk);
- // Type badge
+ // Type badge — the colour is per-mime so it stays a (cheap) palette
+ // lookup on the label's own foreground rather than a CSS reparse.
QString type = file["type"].toString();
auto* type_dot = new QLabel("[" + type.section('/', 1, 1).left(4).toUpper() + "]");
+ type_dot->setObjectName("FMTypeBadge");
type_dot->setFixedWidth(46);
- type_dot->setStyleSheet(QString("color:%1;font-size:10px;font-weight:700;background:transparent;%2")
- .arg(file_type_color(type), MF));
+ QPalette badge_pal = type_dot->palette();
+ badge_pal.setColor(QPalette::WindowText, QColor(file_type_color(type)));
+ type_dot->setPalette(badge_pal);
hl->addWidget(type_dot);
- // Name + meta (clickable for preview)
+ // Name + meta (clickable for preview — see eventFilter)
auto* info = new QWidget(this);
- info->setStyleSheet("background:transparent;");
+ info->setObjectName("FMCardInfo");
info->setCursor(Qt::PointingHandCursor);
auto* info_vl = new QVBoxLayout(info);
info_vl->setContentsMargins(0, 0, 0, 0);
info_vl->setSpacing(1);
- auto* name_lbl = new QLabel(file["originalName"].toString());
- name_lbl->setStyleSheet(QString("color:%1;font-size:12px;font-weight:600;background:transparent;%2")
- .arg(colors::TEXT_PRIMARY(), MF));
+ auto* name_lbl = new QLabel(display_name);
+ name_lbl->setObjectName("FMFileName");
info_vl->addWidget(name_lbl);
QString date_str = QDateTime::fromString(file["uploadedAt"].toString(), Qt::ISODate)
.toLocalTime()
.toString("yyyy-MM-dd HH:mm");
auto* meta_lbl = new QLabel(format_size(file["size"].toInteger()) + " | " + date_str);
- meta_lbl->setStyleSheet(
- QString("color:%1;font-size:10px;background:transparent;%2").arg(colors::TEXT_DIM(), MF));
+ meta_lbl->setObjectName("FMFileMeta");
info_vl->addWidget(meta_lbl);
- QString fid = file["id"].toString();
- // Click card body → preview
+ // Clicking the card body previews the file. eventFilter() reads the
+ // file id back off this property.
+ info->setProperty("fileId", fid);
info->installEventFilter(this);
- connect(name_lbl, &QLabel::linkActivated, this, [this, fid]() { show_preview(fid); });
- // Use a transparent button overlay trick — simpler: connect via QPushButton
+ card->setProperty("fileId", fid);
+ card->installEventFilter(this);
+ card->setToolTip(tr("Click to preview %1").arg(display_name));
+
auto* preview_btn = new QPushButton(tr("PREVIEW"));
+ preview_btn->setObjectName("FMPreview");
preview_btn->setCursor(Qt::PointingHandCursor);
preview_btn->setFixedHeight(26);
- preview_btn->setStyleSheet(QString("QPushButton{background:transparent;color:%1;border:1px solid %2;"
- "font-size:10px;font-weight:700;padding:0 8px;%3}"
- "QPushButton:hover{color:%4;border-color:%4;}")
- .arg(colors::TEXT_DIM(), colors::BORDER_DIM(), MF, colors::AMBER()));
+ preview_btn->setAccessibleName(tr("Preview %1").arg(display_name));
connect(preview_btn, &QPushButton::clicked, this, [this, fid]() { show_preview(fid); });
hl->addWidget(info, 1);
hl->addWidget(preview_btn);
@@ -844,35 +1003,29 @@ void FileManagerScreen::render_files() {
QString route = route_for_mime(type);
if (!route.isEmpty()) {
auto* open_btn = new QPushButton(open_with_label(type));
+ open_btn->setObjectName("FMOpenWith");
open_btn->setCursor(Qt::PointingHandCursor);
open_btn->setFixedHeight(26);
- open_btn->setStyleSheet(QString("QPushButton{background:transparent;color:%1;border:1px solid %2;"
- "font-size:10px;font-weight:700;padding:0 8px;%3}"
- "QPushButton:hover{color:%1;background:rgba(217,119,6,0.15);}")
- .arg(colors::AMBER(), colors::BORDER_DIM(), MF));
+ open_btn->setAccessibleName(tr("Open %1 in the matching screen").arg(display_name));
connect(open_btn, &QPushButton::clicked, this, [this, fid]() { open_with(fid); });
hl->addWidget(open_btn);
}
// Save button
auto* dl_btn = new QPushButton(tr("SAVE"));
+ dl_btn->setObjectName("FMSave");
dl_btn->setCursor(Qt::PointingHandCursor);
dl_btn->setFixedSize(54, 26);
- dl_btn->setStyleSheet(QString("QPushButton{background:transparent;color:%1;border:1px solid %2;"
- "font-size:10px;font-weight:700;%3}"
- "QPushButton:hover{color:#38bdf8;background:%4;}")
- .arg(colors::CYAN(), colors::BORDER_DIM(), MF, colors::BG_RAISED()));
+ dl_btn->setAccessibleName(tr("Save a copy of %1").arg(display_name));
connect(dl_btn, &QPushButton::clicked, this, [this, fid]() { download_file(fid); });
hl->addWidget(dl_btn);
// Delete button
auto* del_btn = new QPushButton(tr("DEL"));
+ del_btn->setObjectName("FMDelete");
del_btn->setCursor(Qt::PointingHandCursor);
del_btn->setFixedSize(44, 26);
- del_btn->setStyleSheet(QString("QPushButton{background:transparent;color:%1;border:1px solid %2;"
- "font-size:10px;font-weight:700;%3}"
- "QPushButton:hover{color:%4;background:rgba(239,68,68,0.1);}")
- .arg(colors::TEXT_DIM(), colors::BORDER_DIM(), MF, colors::NEGATIVE()));
+ del_btn->setAccessibleName(tr("Delete %1").arg(display_name));
connect(del_btn, &QPushButton::clicked, this, [this, fid]() { delete_file(fid); });
hl->addWidget(del_btn);
@@ -881,6 +1034,17 @@ void FileManagerScreen::render_files() {
file_layout_->addStretch();
update_bulk_bar();
+
+ // Restore the scroll position after the layout has settled — the cards are
+ // built synchronously but their geometry isn't final until the event loop
+ // spins, so setValue() now would clamp against a stale range.
+ if (file_scroll_ && file_scroll_->verticalScrollBar() && scroll_pos > 0) {
+ QScrollBar* sb = file_scroll_->verticalScrollBar();
+ QTimer::singleShot(0, this, [sb, scroll_pos]() {
+ if (sb)
+ sb->setValue(scroll_pos);
+ });
+ }
}
void FileManagerScreen::update_stats() {
@@ -1017,16 +1181,12 @@ void FileManagerScreen::restore_state(const QVariantMap& state) {
const QString filter = state.value("screen_filter").toString();
if (filter != active_screen_filter_) {
active_screen_filter_ = filter;
- // Find and check the matching chip
+ // Match on the "screenFilter" property, not the localized button text.
if (chip_group_) {
for (auto* btn : chip_group_->buttons()) {
- auto* chip = qobject_cast<QPushButton*>(btn);
- if (!chip)
- continue;
- QString chip_filter = chip->text() == "All" ? "" : chip->text();
- if (chip_filter == filter) {
- chip->setChecked(true);
- break;
+ if (btn->property("screenFilter").toString() == filter) {
+ btn->setChecked(true); // toggled() re-renders and re-sets the filter
+ return;
}
}
}
diff --git a/fincept-qt/src/screens/file_manager/FileManagerScreen.h b/fincept-qt/src/screens/file_manager/FileManagerScreen.h
index a1dbd041f..54800d14e 100644
--- a/fincept-qt/src/screens/file_manager/FileManagerScreen.h
+++ b/fincept-qt/src/screens/file_manager/FileManagerScreen.h
@@ -11,6 +11,7 @@
#include <QProgressBar>
#include <QPushButton>
#include <QScrollArea>
+#include <QSet>
#include <QSplitter>
#include <QTableWidget>
#include <QTextEdit>
@@ -37,6 +38,9 @@ class FileManagerScreen : public QWidget, public IStatefulScreen {
protected:
void showEvent(QShowEvent* event) override;
void changeEvent(QEvent* event) override;
+ /// Turns a click anywhere on a file card into a preview. The card body had
+ /// installEventFilter(this) but no override, so clicking a card did nothing.
+ bool eventFilter(QObject* watched, QEvent* event) override;
private:
void build_ui();
@@ -78,8 +82,10 @@ class FileManagerScreen : public QWidget, public IStatefulScreen {
// ── File list ────────────────────────────────────────────────────────
QWidget* file_container_ = nullptr;
QVBoxLayout* file_layout_ = nullptr;
- QVector<QPushButton*> check_btns_; // per-card checkbox buttons
- QVector<QString> check_ids_; // parallel file IDs
+ QScrollArea* file_scroll_ = nullptr; // owns the scroll position preserved across re-renders
+ QVector<QPushButton*> check_btns_; // per-card checkbox buttons
+ QVector<QString> check_ids_; // parallel file IDs
+ QSet<QString> checked_ids_; // survives render_files() teardown
QPushButton* bulk_delete_btn_ = nullptr;
QWidget* bulk_bar_ = nullptr;
QLabel* bulk_sel_label_ = nullptr; // "Selected files:" (cached for retranslateUi)
diff --git a/fincept-qt/src/screens/fno/BuilderSubTab.cpp b/fincept-qt/src/screens/fno/BuilderSubTab.cpp
index dc4598efa..648e20e56 100644
--- a/fincept-qt/src/screens/fno/BuilderSubTab.cpp
+++ b/fincept-qt/src/screens/fno/BuilderSubTab.cpp
@@ -14,6 +14,7 @@
#include "storage/repositories/StrategiesRepository.h"
#include "trading/AccountManager.h"
#include "trading/UnifiedTrading.h"
+#include "trading/instruments/InstrumentService.h"
#include "ui/theme/StyleSheets.h"
#include "ui/theme/Theme.h"
@@ -34,6 +35,70 @@
namespace fincept::screens::fno {
+namespace {
+
+/// ATM implied vol (decimal) for a chain snapshot, averaging the CE/PE pair on
+/// the ATM row. Returns 0 when the Greeks worker hasn't solved the row yet.
+///
+/// PayoffComputeOptions::fallback_iv defaults to a hard-coded 0.20 — leaving it
+/// there prices every leg that has no captured IV, *and* the whole probability-
+/// of-profit integral, at 20% vol regardless of the underlying. That is wildly
+/// wrong for BANKNIFTY (typically 2×) and equally wrong the other way for a
+/// low-vol index. Seed it from the live chain instead.
+double atm_iv_of(const fincept::services::options::OptionChain& chain) {
+ for (const auto& row : chain.rows) {
+ if (!row.is_atm)
+ continue;
+ if (row.ce_iv > 0 && row.pe_iv > 0)
+ return 0.5 * (row.ce_iv + row.pe_iv);
+ if (row.ce_iv > 0)
+ return row.ce_iv;
+ return row.pe_iv;
+ }
+ return 0.0;
+}
+
+/// Fill in any leg whose lot size the chain didn't carry (Fyers' options-chain
+/// endpoint omits it entirely, so `StrategyTemplates::instantiate` copies a 0).
+/// Without this a template-built strategy is un-tradable, and — before the
+/// Builder's pre-flight check existed — would have dispatched one *unit* per
+/// lot. All contracts on one underlying/expiry share a lot size, so a sibling
+/// lookup is authoritative.
+void backfill_lot_sizes(QVector<fincept::services::options::StrategyLeg>& legs,
+ const fincept::services::options::OptionChain& chain) {
+ bool any_missing = false;
+ for (const auto& leg : legs)
+ if (leg.lot_size <= 0)
+ any_missing = true;
+ if (!any_missing || chain.broker_id.isEmpty())
+ return;
+
+ auto& insts = fincept::trading::InstrumentService::instance();
+ int shared_lot = 0;
+ const auto siblings =
+ insts.find_options_for_underlying(chain.broker_id, chain.underlying, chain.expiry, QStringLiteral("NFO"));
+ for (const auto& in : siblings) {
+ if (in.lot_size > 0) {
+ shared_lot = in.lot_size;
+ break;
+ }
+ }
+ for (auto& leg : legs) {
+ if (leg.lot_size > 0)
+ continue;
+ if (!leg.symbol.isEmpty()) {
+ if (auto inst = insts.find(leg.symbol, QStringLiteral("NFO"), chain.broker_id); inst && inst->lot_size > 0) {
+ leg.lot_size = inst->lot_size;
+ continue;
+ }
+ }
+ if (shared_lot > 0)
+ leg.lot_size = shared_lot;
+ }
+}
+
+} // namespace
+
using fincept::services::options::OptionChain;
using fincept::services::options::OptionChainService;
using fincept::services::options::Strategy;
@@ -65,7 +130,12 @@ BuilderSubTab::BuilderSubTab(QWidget* parent) : QWidget(parent) {
StrategyLeg blank;
blank.type = fincept::trading::InstrumentType::CE;
blank.lots = 1;
- blank.lot_size = 1;
+ // lot_size stays 0 — a hand-added scratch row has no contract behind it.
+ // It used to default to 1, which made the row look tradable and would
+ // have dispatched a ONE UNIT order for "1 lot". The Builder's pre-flight
+ // check refuses to trade a basket containing it; the user has to add the
+ // leg from the Chain tab (or a template) to get a real contract.
+ blank.lot_size = 0;
legs_view_->leg_model()->append_leg(blank);
});
connect(legs_view_->leg_model(), &LegEditorModel::legs_changed, this, &BuilderSubTab::on_legs_changed);
@@ -190,6 +260,17 @@ void BuilderSubTab::setup_ui() {
trade_btn_->setCursor(Qt::PointingHandCursor);
foot_lay->addWidget(trade_btn_);
root->addWidget(footer);
+
+ // ── Accessibility + keyboard traversal ────────────────────────────────
+ save_btn_->setAccessibleName(tr("Save strategy"));
+ load_btn_->setAccessibleName(tr("Load or delete a saved strategy"));
+ days_to_target_spin_->setAccessibleName(tr("Days to target date"));
+ trade_btn_->setAccessibleName(tr("Trade all active legs as paper orders"));
+ setTabOrder(toolbar_, legs_view_);
+ setTabOrder(legs_view_, save_btn_);
+ setTabOrder(save_btn_, load_btn_);
+ setTabOrder(load_btn_, days_to_target_spin_);
+ setTabOrder(days_to_target_spin_, trade_btn_);
}
QVariantMap BuilderSubTab::save_state() const {
@@ -203,6 +284,11 @@ void BuilderSubTab::restore_state(const QVariantMap& state) {
void BuilderSubTab::showEvent(QShowEvent* e) {
QWidget::showEvent(e);
+ is_visible_ = true;
+ if (analytics_dirty_) {
+ analytics_dirty_ = false;
+ refresh_analytics();
+ }
if (chain_subscribed_)
return;
auto& hub = fincept::datahub::DataHub::instance();
@@ -217,6 +303,7 @@ void BuilderSubTab::showEvent(QShowEvent* e) {
void BuilderSubTab::hideEvent(QHideEvent* e) {
QWidget::hideEvent(e);
+ is_visible_ = false;
}
void BuilderSubTab::changeEvent(QEvent* event) {
@@ -277,7 +364,9 @@ void BuilderSubTab::on_template_chosen(const QString& template_id, const Strateg
QMessageBox::warning(this, tr("Could not build strategy"), QString::fromStdString(r.error()));
return;
}
- legs_view_->leg_model()->set_legs(r.value().legs);
+ auto legs = r.value().legs;
+ backfill_lot_sizes(legs, last_chain_);
+ legs_view_->leg_model()->set_legs(legs);
loaded_strategy_id_ = 0;
loaded_strategy_name_.clear();
refresh_analytics();
@@ -299,6 +388,13 @@ Strategy BuilderSubTab::current_strategy() const {
}
void BuilderSubTab::refresh_analytics() {
+ // Deferred while hidden — showEvent replays it. Keeps a background tab from
+ // running the full payoff + POP integral on every chain publish.
+ if (!is_visible_) {
+ analytics_dirty_ = true;
+ update_trade_button_state();
+ return;
+ }
const auto& legs = legs_view_->leg_model()->legs();
if (legs.isEmpty() || last_chain_.rows.isEmpty()) {
ribbon_->clear();
@@ -311,6 +407,8 @@ void BuilderSubTab::refresh_analytics() {
PayoffComputeOptions opts;
opts.current_spot = last_chain_.spot;
opts.days_to_target = days_to_target_spin_ ? days_to_target_spin_->value() : 0;
+ if (const double atm_iv = atm_iv_of(last_chain_); atm_iv > 0)
+ opts.fallback_iv = atm_iv;
auto curve = fincept::services::options::analytics::compute_payoff(s, opts);
auto bes = fincept::services::options::analytics::compute_breakevens(curve);
@@ -355,10 +453,65 @@ void BuilderSubTab::on_trade_clicked() {
return;
Strategy s = current_strategy();
+ // ── Pre-flight contract validation (money-loss guard) ────────────────────
+ // A leg reaches the basket from three places: the chain's left-click (fully
+ // resolved), a template instantiation, and TemplateToolbar's "+ ADD LEG"
+ // (a blank leg with lot_size = 1 and no symbol). Submitting the blank one
+ // sends quantity = |lots| × 1 — a ONE UNIT order where the user asked for
+ // one lot — and an empty symbol the broker will either reject or, worse,
+ // mis-route. Refuse the whole basket instead of silently placing part of it.
+ QStringList invalid;
+ int placeable = 0;
+ for (const auto& leg : legs) {
+ if (!leg.is_active || leg.lots == 0)
+ continue;
+ ++placeable;
+ const QString label = leg.symbol.isEmpty()
+ ? tr("row %1 (%2)").arg(placeable).arg(leg.strike, 0, 'f', 0)
+ : leg.symbol;
+ if (leg.symbol.isEmpty())
+ invalid.append(tr("%1 — no contract symbol").arg(label));
+ else if (leg.lot_size <= 0)
+ invalid.append(tr("%1 — lot size not resolved").arg(label));
+ else if (leg.type != fincept::trading::InstrumentType::CE &&
+ leg.type != fincept::trading::InstrumentType::PE && leg.type != fincept::trading::InstrumentType::FUT)
+ invalid.append(tr("%1 — instrument type not set").arg(label));
+ }
+ if (placeable == 0) {
+ QMessageBox::information(this, tr("Nothing to trade"),
+ tr("Switch on at least one leg with a non-zero lot count."));
+ return;
+ }
+ if (!invalid.isEmpty()) {
+ QMessageBox::warning(
+ this, tr("Cannot trade this strategy"),
+ tr("These legs are not fully resolved, so the order quantity would be wrong:\n\n%1\n\n"
+ "Add legs by clicking a premium in the Chain tab (or use a template) so the contract "
+ "symbol and lot size come from the live chain.")
+ .arg(invalid.join("\n")));
+ return;
+ }
+
fincept::services::options::analytics::PayoffComputeOptions opts;
opts.current_spot = last_chain_.spot;
+ if (const double atm_iv = atm_iv_of(last_chain_); atm_iv > 0)
+ opts.fallback_iv = atm_iv;
auto a = fincept::services::options::analytics::compute_all(s, last_chain_, opts);
+ // Double-submit guard: the dispatch loop below is synchronous, but the
+ // confirm dialog spins a nested event loop and the button stays live under
+ // it on some styles. Disable for the whole ticket lifetime.
+ if (trade_btn_)
+ trade_btn_->setEnabled(false);
+ struct ReenableGuard {
+ QPushButton* btn;
+ BuilderSubTab* owner;
+ ~ReenableGuard() {
+ if (btn && owner)
+ owner->update_trade_button_state();
+ }
+ } reenable{trade_btn_, this};
+
OrderConfirmDialog dlg(s, last_chain_, a.premium_paid, a.max_profit, a.max_loss, this);
if (dlg.exec() != QDialog::Accepted)
return;
@@ -502,7 +655,12 @@ void BuilderSubTab::on_load_clicked() {
QMessageBox::warning(this, tr("Load failed"), QString::fromStdString(r.error()));
return;
}
- legs_view_->leg_model()->set_legs(r.value().strategy.legs);
+ // A strategy saved in an earlier session can carry lot_size 0 if
+ // the provider omitted it then. Re-resolve against today's
+ // instrument master before it reaches the leg table.
+ auto loaded_legs = r.value().strategy.legs;
+ backfill_lot_sizes(loaded_legs, last_chain_);
+ legs_view_->leg_model()->set_legs(loaded_legs);
loaded_strategy_id_ = id;
loaded_strategy_name_ = name_for_msg;
refresh_analytics();
diff --git a/fincept-qt/src/screens/fno/BuilderSubTab.h b/fincept-qt/src/screens/fno/BuilderSubTab.h
index 4d8604d13..535e2ad37 100644
--- a/fincept-qt/src/screens/fno/BuilderSubTab.h
+++ b/fincept-qt/src/screens/fno/BuilderSubTab.h
@@ -85,6 +85,13 @@ class BuilderSubTab : public QWidget {
fincept::services::options::OptionChain last_chain_;
bool chain_subscribed_ = false;
+ /// P3: chain publishes keep arriving while the Builder tab is hidden (the
+ /// service signal is connected for the widget's lifetime). Cache the
+ /// snapshot but defer the payoff/POP/Greeks recompute until the tab is
+ /// actually visible — compute_pop alone samples 1001 points per publish.
+ bool is_visible_ = false;
+ bool analytics_dirty_ = false;
+
qint64 loaded_strategy_id_ = 0;
QString loaded_strategy_name_;
};
diff --git a/fincept-qt/src/screens/fno/ChainSubTab.cpp b/fincept-qt/src/screens/fno/ChainSubTab.cpp
index d13f0ffcf..866227746 100644
--- a/fincept-qt/src/screens/fno/ChainSubTab.cpp
+++ b/fincept-qt/src/screens/fno/ChainSubTab.cpp
@@ -32,6 +32,8 @@
#include <QVBoxLayout>
#include <QtConcurrent/QtConcurrent>
+#include <cmath>
+
namespace fincept::screens::fno {
using namespace fincept::ui;
@@ -418,7 +420,14 @@ void ChainSubTab::resubscribe() {
show_empty_state(tr("Pick a broker, underlying, and expiry."));
return;
}
- hide_empty_state();
+ // Loading state: hide_empty_state() used to flip straight to the table, so
+ // between subscribing and the first publish the user stared at an empty grid
+ // with no indication anything was in flight. Keep the message visible until
+ // rows actually arrive (or an existing snapshot is already rendered).
+ if (table_ && table_->chain_model()->rowCount() > 0)
+ hide_empty_state();
+ else
+ show_empty_state(tr("Loading %1 %2 chain…").arg(header_->underlying(), header_->expiry()));
active_topic_ = topic;
QPointer<ChainSubTab> self = this;
@@ -488,7 +497,6 @@ QString ChainSubTab::current_topic() const {
void ChainSubTab::on_order_requested(qint64 token, double strike, bool is_call, bool is_buy) {
using namespace fincept::trading;
- Q_UNUSED(strike);
const QString broker = header_->broker_id();
if (broker.isEmpty() || broker == QStringLiteral("databento")) {
@@ -507,17 +515,20 @@ void ChainSubTab::on_order_requested(qint64 token, double strike, bool is_call,
QString sym;
int lot = 0;
double ltp = 0;
+ double resolved_strike = 0;
for (const auto& r : chain.rows) {
if (is_call && r.ce_token == token) {
sym = r.ce_symbol;
lot = r.lot_size;
ltp = r.ce_quote.ltp;
+ resolved_strike = r.strike;
break;
}
if (!is_call && r.pe_token == token) {
sym = r.pe_symbol;
lot = r.lot_size;
ltp = r.pe_quote.ltp;
+ resolved_strike = r.strike;
break;
}
}
@@ -525,6 +536,19 @@ void ChainSubTab::on_order_requested(qint64 token, double strike, bool is_call,
QMessageBox::warning(this, tr("Place Order"), tr("Could not resolve the contract for this strike."));
return;
}
+ // Cross-check: the strike the user right-clicked must be the strike the
+ // token resolves to. They can only disagree if the chain republished with a
+ // different ladder between the click and this handler, or if the provider
+ // reused a token — either way, placing the order would trade a strike the
+ // user never selected.
+ if (std::abs(resolved_strike - strike) > 1e-6) {
+ QMessageBox::warning(this, tr("Place Order"),
+ tr("The chain changed while the order was being prepared "
+ "(you picked %1, the contract now resolves to %2). Nothing was sent — "
+ "please pick the strike again.")
+ .arg(QString::number(strike, 'f', 2), QString::number(resolved_strike, 'f', 2)));
+ return;
+ }
// Broker-native symbol/exchange. Fyers chain symbols are already native
// ("NSE:...CE") and pass straight through place_order's to_fyers_sym; other
@@ -588,11 +612,16 @@ void ChainSubTab::on_order_requested(qint64 token, double strike, bool is_call,
auto* type_combo = new QComboBox(&dlg);
type_combo->addItems({tr("Market"), tr("Limit")});
+ type_combo->setAccessibleName(tr("Order type"));
form->addRow(tr("Type"), type_combo);
auto* lots_spin = new QSpinBox(&dlg);
- lots_spin->setRange(1, 100000);
+ // 10 000 lots is already far past any retail F&O limit; the old 100 000
+ // ceiling let one keypress build a basket two orders of magnitude larger
+ // than intended.
+ lots_spin->setRange(1, 10000);
lots_spin->setValue(1);
+ lots_spin->setAccessibleName(tr("Quantity in lots"));
form->addRow(tr("Qty (lots)"), lots_spin);
auto* qty_label = new QLabel(&dlg);
@@ -608,10 +637,12 @@ void ChainSubTab::on_order_requested(qint64 token, double strike, bool is_call,
px_spin->setRange(0.05, 1.0e8);
px_spin->setDecimals(2);
px_spin->setValue(ltp > 0 ? ltp : 0.05);
+ px_spin->setAccessibleName(tr("Limit price per share"));
form->addRow(tr("Limit price"), px_spin);
auto* product_combo = new QComboBox(&dlg);
product_combo->addItems({tr("NRML (positional)"), tr("MIS (intraday)")});
+ product_combo->setAccessibleName(tr("Product type"));
form->addRow(tr("Product"), product_combo);
// Market needs no price — hide the limit row unless Limit is selected.
@@ -619,24 +650,61 @@ void ChainSubTab::on_order_requested(qint64 token, double strike, bool is_call,
connect(type_combo, qOverload<int>(&QComboBox::currentIndexChanged), &dlg, sync_type);
sync_type(type_combo->currentIndex());
- auto* ctx = new QLabel(QStringLiteral("%1 · LTP %2 · [%3]")
+ auto* ctx = new QLabel(QStringLiteral("%1 · %2 · [%3]")
.arg(acct_name)
- .arg(ltp, 0, 'f', 2)
+ .arg(tr("LTP %1 at ticket open").arg(QString::number(ltp, 'f', 2)))
.arg(is_paper ? tr("PAPER") : tr("LIVE")),
&dlg);
- ctx->setStyleSheet(QStringLiteral("color:%1;font-size:11px;").arg(colors::TEXT_SECONDARY()));
+ // A live F&O order is real leveraged money — the mode must not read as
+ // secondary text the way the paper case can.
+ ctx->setStyleSheet(is_paper ? QStringLiteral("color:%1;font-size:11px;").arg(colors::TEXT_SECONDARY())
+ : QStringLiteral("color:%1;font-size:11px;font-weight:700;").arg(colors::NEGATIVE()));
form->addRow(ctx);
auto* buttons = new QDialogButtonBox(QDialogButtonBox::Cancel, &dlg);
QPushButton* ok = buttons->addButton(is_buy ? tr("Place Buy") : tr("Place Sell"), QDialogButtonBox::AcceptRole);
- ok->setDefault(true);
+ ok->setAccessibleName(is_buy ? tr("Place buy order") : tr("Place sell order"));
+ // Live orders require a deliberate click; paper keeps Return as a shortcut.
+ if (is_paper) {
+ ok->setDefault(true);
+ } else if (auto* cancel = buttons->button(QDialogButtonBox::Cancel)) {
+ cancel->setDefault(true);
+ ok->setAutoDefault(false);
+ }
connect(buttons, &QDialogButtonBox::accepted, &dlg, &QDialog::accept);
connect(buttons, &QDialogButtonBox::rejected, &dlg, &QDialog::reject);
form->addRow(buttons);
+ // Keyboard traversal through the ticket in reading order.
+ dlg.setTabOrder(type_combo, lots_spin);
+ dlg.setTabOrder(lots_spin, px_spin);
+ dlg.setTabOrder(px_spin, product_combo);
+ dlg.setTabOrder(product_combo, buttons);
+
if (dlg.exec() != QDialog::Accepted)
return;
+ // Re-read the premium from the live chain at SUBMIT time. `ltp` was captured
+ // when the ticket opened; an option quote goes stale in seconds, and for a
+ // paper market order that value *is* the fill price. Filling a ticket the
+ // user left open for a minute at the old premium books a fictitious P&L.
+ double fill_ltp = ltp;
+ {
+ const auto& live = table_->chain_model()->chain();
+ for (const auto& r : live.rows) {
+ if (is_call && r.ce_token == token) {
+ if (r.ce_quote.ltp > 0)
+ fill_ltp = r.ce_quote.ltp;
+ break;
+ }
+ if (!is_call && r.pe_token == token) {
+ if (r.pe_quote.ltp > 0)
+ fill_ltp = r.pe_quote.ltp;
+ break;
+ }
+ }
+ }
+
const bool is_market = (type_combo->currentIndex() == 0);
UnifiedOrder order;
// Live placement needs the broker-native symbol; paper stores the bare symbol
@@ -646,7 +714,8 @@ void ChainSubTab::on_order_requested(qint64 token, double strike, bool is_call,
order.side = is_buy ? OrderSide::Buy : OrderSide::Sell;
order.order_type = is_market ? OrderType::Market : OrderType::Limit;
order.quantity = double(lots_spin->value()) * double(lot);
- order.price = is_market ? ltp : px_spin->value(); // ltp lets paper fill a market order; live ignores it
+ // fill_ltp lets paper fill a market order at the current premium; live ignores it.
+ order.price = is_market ? fill_ltp : px_spin->value();
order.product_type = (product_combo->currentIndex() == 1) ? ProductType::Intraday : ProductType::Margin;
order.validity = QStringLiteral("DAY");
order.instrument_token = QString::number(token);
diff --git a/fincept-qt/src/screens/fno/FnoHeaderBar.cpp b/fincept-qt/src/screens/fno/FnoHeaderBar.cpp
index e1695a93d..e0ea8853c 100644
--- a/fincept-qt/src/screens/fno/FnoHeaderBar.cpp
+++ b/fincept-qt/src/screens/fno/FnoHeaderBar.cpp
@@ -6,9 +6,12 @@
#include <QDate>
#include <QDateTime>
#include <QHBoxLayout>
+#include <QHideEvent>
#include <QLocale>
+#include <QShowEvent>
#include <QSignalBlocker>
#include <QStyle>
+#include <QTimer>
#include <QVBoxLayout>
#include <algorithm>
@@ -130,6 +133,16 @@ void FnoHeaderBar::setup_ui() {
lbl_status_->setObjectName("fnoHdrStatus");
root->addWidget(lbl_status_, 0, Qt::AlignVCenter);
+ // ── Accessibility + keyboard traversal ────────────────────────────────
+ broker_combo_->setAccessibleName(tr("Broker"));
+ under_combo_->setAccessibleName(tr("Underlying"));
+ expiry_combo_->setAccessibleName(tr("Expiry"));
+ refresh_btn_->setAccessibleName(tr("Refresh option chain"));
+ lbl_status_->setAccessibleName(tr("Chain freshness"));
+ setTabOrder(broker_combo_, under_combo_);
+ setTabOrder(under_combo_, expiry_combo_);
+ setTabOrder(expiry_combo_, refresh_btn_);
+
// ── Wire signals ──────────────────────────────────────────────────────
connect(broker_combo_, &QComboBox::currentTextChanged, this, &FnoHeaderBar::broker_changed);
connect(under_combo_, &QComboBox::currentTextChanged, this, &FnoHeaderBar::underlying_changed);
@@ -221,6 +234,11 @@ void FnoHeaderBar::update_from_chain(const OptionChain& chain) {
// Compute today's ATM IV from the chain's ATM row, then percentile-rank
// it against the trailing 90-day history in `iv_history_daily`. Needs
// ≥30 days of accumulated data — empty/dim until then.
+ //
+ // P1/P11: get_window() is a synchronous SQLite read and this function runs
+ // on every chain publish (seconds apart, on the UI thread). The percentile
+ // only changes when the day rolls or the underlying changes, so the result
+ // is memoised on (underlying, date) and the query runs once per day.
if (lbl_iv_pctile_) {
double atm_iv = 0;
for (const auto& row : chain.rows) {
@@ -235,38 +253,104 @@ void FnoHeaderBar::update_from_chain(const OptionChain& chain) {
break;
}
if (atm_iv > 0 && !chain.underlying.isEmpty()) {
- const QString since = QDate::currentDate().addDays(-90).toString(Qt::ISODate);
- auto r = fincept::IvHistoryRepository::instance().get_window(chain.underlying, since);
- if (r.is_ok()) {
- const auto& hist = r.value();
- if (hist.size() >= 30) {
- int below = 0;
- for (const auto& row : hist)
- if (row.atm_iv < atm_iv)
- ++below;
- const double pctile = 100.0 * double(below) / double(hist.size());
- lbl_iv_pctile_->setText(QString::number(pctile, 'f', 0) + "%");
- lbl_iv_pctile_->setToolTip(tr("Current ATM IV %1 ranks at %2th percentile of %3 days of history.")
+ const QDate today = QDate::currentDate();
+ const QString key = chain.underlying + QLatin1Char('|') + today.toString(Qt::ISODate);
+ if (key != iv_pctile_cache_key_) {
+ iv_pctile_cache_key_ = key;
+ iv_pctile_cache_tip_.clear();
+ const QString since = today.addDays(-90).toString(Qt::ISODate);
+ auto r = fincept::IvHistoryRepository::instance().get_window(chain.underlying, since);
+ if (r.is_ok()) {
+ const auto& hist = r.value();
+ if (hist.size() >= 30) {
+ int below = 0;
+ for (const auto& row : hist)
+ if (row.atm_iv < atm_iv)
+ ++below;
+ const double pctile = 100.0 * double(below) / double(hist.size());
+ iv_pctile_cache_text_ = QString::number(pctile, 'f', 0) + "%";
+ iv_pctile_cache_tip_ = tr("Current ATM IV %1 ranks at %2th percentile of %3 days of history.")
.arg(atm_iv * 100.0, 0, 'f', 1)
.arg(pctile, 0, 'f', 0)
- .arg(hist.size()));
+ .arg(hist.size());
+ } else {
+ // Not enough history yet — show accumulation progress instead
+ // of a blank dash so it's clear it's building, not broken.
+ iv_pctile_cache_text_ = tr("…%1/30").arg(hist.size());
+ iv_pctile_cache_tip_ =
+ tr("Building IV history — %1 of 30 days needed for a percentile.").arg(hist.size());
+ }
} else {
- // Not enough history yet — show accumulation progress instead
- // of a blank dash so it's clear it's building, not broken.
- lbl_iv_pctile_->setText(tr("…%1/30").arg(hist.size()));
- lbl_iv_pctile_->setToolTip(
- tr("Building IV history — %1 of 30 days needed for a percentile.").arg(hist.size()));
+ iv_pctile_cache_text_ = QStringLiteral("—");
}
- } else {
- lbl_iv_pctile_->setText("—");
}
+ lbl_iv_pctile_->setText(iv_pctile_cache_text_);
+ lbl_iv_pctile_->setToolTip(iv_pctile_cache_tip_);
} else {
lbl_iv_pctile_->setText("—");
+ lbl_iv_pctile_->setToolTip(QString());
}
}
- const QDateTime ts = QDateTime::fromMSecsSinceEpoch(chain.timestamp_ms);
- lbl_status_->setText(tr("Updated %1").arg(ts.toString("hh:mm:ss")));
+ last_chain_ts_ms_ = chain.timestamp_ms;
+ update_freshness();
+}
+
+void FnoHeaderBar::update_freshness() {
+ if (!lbl_status_)
+ return;
+ if (last_chain_ts_ms_ <= 0) {
+ lbl_status_->setText(QString());
+ lbl_status_->setToolTip(QString());
+ return;
+ }
+ const qint64 age_ms = QDateTime::currentMSecsSinceEpoch() - last_chain_ts_ms_;
+ const qint64 age_s = age_ms / 1000;
+ const QString stamp = QDateTime::fromMSecsSinceEpoch(last_chain_ts_ms_).toString("hh:mm:ss");
+
+ // Thresholds: an option quote is meaningfully stale within ~15 s during
+ // market hours and outright unusable past a minute. The label never claims
+ // freshness it can't back with a timestamp.
+ QString colour = colors::TEXT_SECONDARY();
+ QString text = tr("Updated %1").arg(stamp);
+ QString tip = tr("Last chain snapshot at %1 (%2 s ago).").arg(stamp).arg(age_s);
+ if (age_s >= 60) {
+ colour = colors::NEGATIVE();
+ text = tr("STALE · %1 (%2m old)").arg(stamp).arg(age_s / 60);
+ tip = tr("No chain update for %1 seconds. The market may be closed, or the feed may be down — "
+ "press REFRESH to re-request.")
+ .arg(age_s);
+ } else if (age_s >= 15) {
+ colour = colors::AMBER();
+ text = tr("Updated %1 (%2s)").arg(stamp).arg(age_s);
+ }
+ // P7: this runs once a second while the tab is visible — only touch the
+ // widget when something actually changed, so we don't reparse the sheet or
+ // schedule a repaint on every tick.
+ if (lbl_status_->text() != text)
+ lbl_status_->setText(text);
+ if (lbl_status_->toolTip() != tip)
+ lbl_status_->setToolTip(tip);
+ const QString sheet = QStringLiteral("color:%1;font-size:9px;background:transparent;").arg(colour);
+ if (lbl_status_->styleSheet() != sheet)
+ lbl_status_->setStyleSheet(sheet);
+}
+
+void FnoHeaderBar::showEvent(QShowEvent* event) {
+ QWidget::showEvent(event);
+ if (!freshness_timer_) {
+ freshness_timer_ = new QTimer(this);
+ freshness_timer_->setInterval(1000);
+ connect(freshness_timer_, &QTimer::timeout, this, &FnoHeaderBar::update_freshness);
+ }
+ update_freshness();
+ freshness_timer_->start();
+}
+
+void FnoHeaderBar::hideEvent(QHideEvent* event) {
+ QWidget::hideEvent(event);
+ if (freshness_timer_)
+ freshness_timer_->stop();
}
void FnoHeaderBar::clear_ribbon() {
@@ -274,8 +358,12 @@ void FnoHeaderBar::clear_ribbon() {
{lbl_spot_, lbl_change_, lbl_atm_, lbl_pcr_, lbl_max_pain_, lbl_ce_oi_, lbl_pe_oi_, lbl_iv_pctile_})
if (l)
l->setText("--");
- if (lbl_status_)
+ last_chain_ts_ms_ = 0;
+ if (lbl_status_) {
lbl_status_->setText("");
+ lbl_status_->setToolTip(QString());
+ lbl_status_->setStyleSheet(QString());
+ }
}
void FnoHeaderBar::changeEvent(QEvent* event) {
diff --git a/fincept-qt/src/screens/fno/FnoHeaderBar.h b/fincept-qt/src/screens/fno/FnoHeaderBar.h
index 8dbbfd5e1..d0c7374e0 100644
--- a/fincept-qt/src/screens/fno/FnoHeaderBar.h
+++ b/fincept-qt/src/screens/fno/FnoHeaderBar.h
@@ -15,6 +15,8 @@
#include <QString>
#include <QWidget>
+class QTimer;
+
namespace fincept::screens::fno {
class FnoHeaderBar : public QWidget {
@@ -53,11 +55,18 @@ class FnoHeaderBar : public QWidget {
protected:
void changeEvent(QEvent* event) override;
+ void showEvent(QShowEvent* event) override;
+ void hideEvent(QHideEvent* event) override;
private:
void setup_ui();
void retranslateUi();
+ /// Re-render the "Updated hh:mm:ss" status with an age-based freshness
+ /// state (live / stale / no feed). Driven by `freshness_timer_`, which is a
+ /// pure display timer — it never requests data (D3).
+ void update_freshness();
+
QComboBox* broker_combo_ = nullptr;
QComboBox* under_combo_ = nullptr;
QComboBox* expiry_combo_ = nullptr;
@@ -88,6 +97,19 @@ class FnoHeaderBar : public QWidget {
QLabel* key_ce_oi_ = nullptr;
QLabel* key_pe_oi_ = nullptr;
QLabel* key_iv_pctile_ = nullptr;
+
+ /// Timestamp of the last chain snapshot rendered (0 = none yet). Drives the
+ /// stale-quote indicator — an option quote is worthless within seconds, so
+ /// "when did this last tick" has to be on screen, not inferable.
+ qint64 last_chain_ts_ms_ = 0;
+ QTimer* freshness_timer_ = nullptr;
+
+ /// One-entry memo for the IV-percentile query. `update_from_chain` runs on
+ /// every publish and the percentile only moves once per trading day, so the
+ /// synchronous SQLite window read is done once per (underlying, day).
+ QString iv_pctile_cache_key_;
+ QString iv_pctile_cache_text_;
+ QString iv_pctile_cache_tip_;
};
} // namespace fincept::screens::fno
diff --git a/fincept-qt/src/screens/fno/FnoScreen.cpp b/fincept-qt/src/screens/fno/FnoScreen.cpp
index 1a88f59ec..e92dc0091 100644
--- a/fincept-qt/src/screens/fno/FnoScreen.cpp
+++ b/fincept-qt/src/screens/fno/FnoScreen.cpp
@@ -11,6 +11,7 @@
#include "screens/fno/OptionChainTable.h"
#include "screens/fno/ScreenerSubTab.h"
#include "services/options/OptionChainService.h"
+#include "trading/instruments/InstrumentService.h"
#include "ui/theme/Theme.h"
#include <QHBoxLayout>
@@ -66,19 +67,23 @@ QString FnoScreen::tab_label_for(int index) {
}
QString FnoScreen::tab_detail_for(int index) {
+ // Sub-title shown on a slot's placeholder. Every sub-tab is implemented, so
+ // the placeholder is replaced before it can be shown — these strings only
+ // surface if construction of a sub-tab ever fails. They describe what the
+ // tab does; the old "(Phase N)" roadmap markers were stale build notes.
switch (index) {
case TabChain:
- return tr("Live option chain (Phase 2)");
+ return tr("Live option chain");
case TabBuilder:
- return tr("Strategy builder + payoff (Phase 5)");
+ return tr("Strategy builder + payoff");
case TabOI:
- return tr("Open Interest analytics (Phase 7)");
+ return tr("Open Interest analytics");
case TabMultiStraddle:
- return tr("Multi straddle / strangle charts (Phase 9)");
+ return tr("Multi straddle / strangle charts");
case TabFiiDii:
- return tr("Institutional flows (Phase 8)");
+ return tr("Institutional flows");
case TabScreener:
- return tr("Chain screener (Phase 9)");
+ return tr("Chain screener");
case TabPositions:
return tr("Paper positions, orders & square-off");
default:
@@ -185,17 +190,47 @@ void FnoScreen::ensure_tab_built(SubTab which) {
leg.type =
is_call ? fincept::trading::InstrumentType::CE : fincept::trading::InstrumentType::PE;
leg.lots = lots;
+ leg.expiry = chain.expiry;
for (const auto& row : chain.rows) {
if (std::abs(row.strike - strike) < 1e-6) {
const auto& q = is_call ? row.ce_quote : row.pe_quote;
leg.entry_price = q.ltp;
leg.iv_at_entry = is_call ? row.ce_iv : row.pe_iv;
- leg.lot_size = row.lot_size > 0 ? row.lot_size : 1;
+ // ORDER SAFETY: never invent a lot size. This used
+ // to fall back to 1 when the provider omitted it
+ // (Fyers' options-chain-v3 always does), which made
+ // "1 lot" dispatch as ONE UNIT and understated every
+ // payoff/Greek by the lot multiplier. Resolve it from
+ // the instrument master instead, and leave it at 0 —
+ // which the Builder's pre-flight check refuses to
+ // trade — when it genuinely can't be determined.
+ leg.lot_size = row.lot_size;
leg.instrument_token = is_call ? row.ce_token : row.pe_token;
leg.symbol = is_call ? row.ce_symbol : row.pe_symbol;
break;
}
}
+ if (leg.lot_size <= 0 && !leg.symbol.isEmpty()) {
+ auto& insts = fincept::trading::InstrumentService::instance();
+ if (auto inst = insts.find(leg.symbol, QStringLiteral("NFO"), chain.broker_id))
+ leg.lot_size = inst->lot_size;
+ if (leg.lot_size <= 0) {
+ // All options on one underlying/expiry share a lot
+ // size — borrow it from any sibling contract.
+ const auto siblings = insts.find_options_for_underlying(
+ chain.broker_id, chain.underlying, chain.expiry, QStringLiteral("NFO"));
+ for (const auto& in : siblings) {
+ if (in.lot_size > 0) {
+ leg.lot_size = in.lot_size;
+ break;
+ }
+ }
+ }
+ }
+ if (leg.lot_size <= 0)
+ LOG_WARN("FnoScreen", QString("Leg %1 has no resolvable lot size — it will be blocked "
+ "from the Builder's Trade All.")
+ .arg(leg.symbol));
builder_tab_->legs_view()->leg_model()->append_leg(leg);
});
}
diff --git a/fincept-qt/src/screens/fno/FnoScreen.h b/fincept-qt/src/screens/fno/FnoScreen.h
index 670fa124a..cfedb2e88 100644
--- a/fincept-qt/src/screens/fno/FnoScreen.h
+++ b/fincept-qt/src/screens/fno/FnoScreen.h
@@ -1,19 +1,15 @@
#pragma once
// FnoScreen — Sensibull-style F&O analytics tab.
//
-// Top-level shell. Six sub-tabs hosted in a QStackedWidget; each sub-tab
+// Top-level shell. Seven sub-tabs hosted in a QStackedWidget; each sub-tab
// is lazy-constructed on first reveal (P2 spirit — chain assembly + WS
// subscriptions for the OI sub-tab don't fire until the user navigates
-// there).
+// there). Only Chain is built eagerly, so the screen shows data immediately.
//
-// Phase 2 ships the Chain sub-tab fully wired. The other five render a
-// ComingSoon placeholder until their phase lands:
-// - Chain (Phase 2) ✅
-// - Builder (Phase 5)
-// - OI Analytics (Phase 7)
-// - Multi-Stra (Phase 9)
-// - FII / DII (Phase 8)
-// - Screener (Phase 9)
+// All seven are implemented: Chain, Builder, OI Analytics, Multi-Straddle,
+// FII/DII, Screener, Positions. The QStackedWidget is seeded with placeholder
+// widgets purely so slot indices map 1:1 onto SubTab values; each is swapped
+// for the real widget before it can ever be shown.
#include "core/symbol/IGroupLinked.h"
#include "screens/common/IStatefulScreen.h"
diff --git a/fincept-qt/src/screens/fno/LegEditorTable.cpp b/fincept-qt/src/screens/fno/LegEditorTable.cpp
index 0186c2fa7..1d14ed86b 100644
--- a/fincept-qt/src/screens/fno/LegEditorTable.cpp
+++ b/fincept-qt/src/screens/fno/LegEditorTable.cpp
@@ -6,6 +6,7 @@
#include <QHeaderView>
#include <QMouseEvent>
+#include <algorithm>
#include <cmath>
namespace fincept::screens::fno {
@@ -66,7 +67,16 @@ double LegEditorModel::resolve_ltp(const StrategyLeg& leg) const {
}
double LegEditorModel::resolve_delta(const StrategyLeg& leg) const {
- return lookup_delta(leg, chain_);
+ // POSITION delta, not per-share delta. The chain publishes per-share Greeks
+ // (see OptionChainTypes.h); a sold call has a *negative* position delta even
+ // though its per-share delta is positive. Showing the raw per-share number
+ // here contradicted the Builder ribbon's "Delta" (which is
+ // Σ delta × lots × lot_size) and read as long-delta on a short leg.
+ const double per_share = lookup_delta(leg, chain_);
+ if (per_share == 0)
+ return 0;
+ const int lot_size = leg.lot_size > 0 ? leg.lot_size : 1;
+ return per_share * double(leg.lots) * double(lot_size);
}
double LegEditorModel::resolve_pnl(const StrategyLeg& leg) const {
@@ -179,7 +189,13 @@ bool LegEditorModel::setData(const QModelIndex& index, const QVariant& value, in
}
} else if (role == Qt::EditRole) {
if (col == ColLots) {
- const int v = value.toInt();
+ // Signed: + buy, - sell. Zero is rejected (a zero-lot leg is never
+ // submitted, so allowing it would only desync the preview from the
+ // order). Clamped so a fat-finger paste can't build a basket that
+ // would be rejected — or worse, accepted — at the broker.
+ constexpr int kMaxLots = 10000;
+ int v = value.toInt();
+ v = std::clamp(v, -kMaxLots, kMaxLots);
if (v != 0 && v != leg.lots) {
leg.lots = v;
mutated = true;
@@ -215,13 +231,33 @@ Qt::ItemFlags LegEditorModel::flags(const QModelIndex& index) const {
}
QVariant LegEditorModel::headerData(int section, Qt::Orientation orient, int role) const {
- if (orient != Qt::Horizontal || role != Qt::DisplayRole)
+ if (orient != Qt::Horizontal)
+ return {};
+ if (section < 0 || section >= ColCount)
+ return {};
+ if (role == Qt::ToolTipRole) {
+ // Units are the single biggest source of misreading on an options
+ // blotter — spell them out rather than leaving "Delta" ambiguous.
+ const QString tips[ColCount] = {
+ tr("Include this leg in analytics and in the order basket."),
+ tr("Buy when Lots is positive, Sell when negative."),
+ tr("CE = call, PE = put."),
+ tr("Strike price."),
+ tr("Signed lots: positive = buy, negative = sell. Quantity = lots × lot size."),
+ tr("Entry premium per share (not per lot)."),
+ tr("Implied volatility captured when the leg was added."),
+ tr("Live premium per share from the option chain."),
+ tr("Position delta = per-share delta × lots × lot size (signed)."),
+ tr("Mark-to-market P&L = (LTP − entry) × lots × lot size."),
+ QString(),
+ };
+ return tips[section];
+ }
+ if (role != Qt::DisplayRole)
return {};
// tr() per-call — owning QHeaderView re-polls on QEvent::LanguageChange.
const QString headers[ColCount] = {tr("On"), tr("B/S"), tr("Type"), tr("Strike"), tr("Lots"), tr("Entry"),
tr("IV"), tr("LTP"), tr("Delta"), tr("P&L"), QString()};
- if (section < 0 || section >= ColCount)
- return {};
return headers[section];
}
@@ -263,6 +299,10 @@ LegEditorTable::LegEditorTable(QWidget* parent) : QTableView(parent) {
model_ = new LegEditorModel(this);
setModel(model_);
+ setAccessibleName(tr("Strategy legs"));
+ setAccessibleDescription(
+ tr("Editable list of option legs. Space toggles a leg on or off; edit Lots (signed) and Entry premium."));
+
setShowGrid(false);
setAlternatingRowColors(true);
setSelectionBehavior(QAbstractItemView::SelectRows);
diff --git a/fincept-qt/src/screens/fno/MaxPainChart.cpp b/fincept-qt/src/screens/fno/MaxPainChart.cpp
index 41e3de1a1..2aea9aaa2 100644
--- a/fincept-qt/src/screens/fno/MaxPainChart.cpp
+++ b/fincept-qt/src/screens/fno/MaxPainChart.cpp
@@ -9,6 +9,7 @@
#include <QValueAxis>
#include <algorithm>
+#include <cmath>
#include <limits>
namespace fincept::screens::fno {
@@ -97,9 +98,14 @@ void MaxPainChart::set_chain(const OptionChain& chain) {
categories.reserve(hi - lo + 1);
pain_vals.reserve(hi - lo + 1);
- // Per-strike pain — O(N²) on the windowed slice. Cheap for 20 strikes.
+ // Per-strike pain — total intrinsic value writers would owe if the
+ // underlying expired at S:
+ // pain(S) = Σ_{K<S} (S−K)·CE_OI(K) + Σ_{K>S} (K−S)·PE_OI(K)
+ // summed over the WHOLE chain (not just the drawn window), so the profile
+ // is correct even though only ±strike_window_ bars are rendered.
double min_pain = std::numeric_limits<double>::infinity();
int min_idx = 0;
+ int chain_max_pain_idx = -1;
for (int i = lo; i <= hi; ++i) {
const double S = chain.rows[i].strike;
double pain = 0;
@@ -115,7 +121,15 @@ void MaxPainChart::set_chain(const OptionChain& chain) {
min_pain = pain;
min_idx = i - lo;
}
+ if (chain.max_pain > 0 && std::abs(S - chain.max_pain) < 1e-6)
+ chain_max_pain_idx = i - lo;
}
+ // Highlight the chain's own max-pain strike when it falls inside the drawn
+ // window. The local minimum of a clipped window can be a different strike
+ // from the producer's full-chain answer, which is what the header ribbon
+ // shows — two different "max pain" numbers on one screen is worse than one.
+ if (chain_max_pain_idx >= 0)
+ min_idx = chain_max_pain_idx;
// Stack the two sets so each strike has a value in exactly one of them.
for (int i = 0; i < pain_vals.size(); ++i) {
diff --git a/fincept-qt/src/screens/fno/MultiStraddleSubTab.cpp b/fincept-qt/src/screens/fno/MultiStraddleSubTab.cpp
index dc510e53b..97922c0a4 100644
--- a/fincept-qt/src/screens/fno/MultiStraddleSubTab.cpp
+++ b/fincept-qt/src/screens/fno/MultiStraddleSubTab.cpp
@@ -23,6 +23,7 @@
#include <QVBoxLayout>
#include <algorithm>
+#include <cmath>
namespace fincept::screens::fno {
@@ -145,6 +146,11 @@ void MultiStraddleSubTab::setup_ui() {
add_btn_->setObjectName("fnoMSAdd");
add_btn_->setCursor(Qt::PointingHandCursor);
add_btn_->setEnabled(false);
+ type_combo_->setAccessibleName(tr("Straddle or strangle type"));
+ strike_combo_->setAccessibleName(tr("Anchor strike"));
+ add_btn_->setAccessibleName(tr("Add this straddle to the chart"));
+ setTabOrder(type_combo_, strike_combo_);
+ setTabOrder(strike_combo_, add_btn_);
hlay->addWidget(add_btn_);
hlay->addStretch(1);
root->addWidget(header);
@@ -224,51 +230,72 @@ void MultiStraddleSubTab::retranslateUi() {
type_combo_->setCurrentIndex(keep);
}
// Rebuild the strike combo so the "(ATM)" suffix re-translates.
- if (strike_combo_ && strike_combo_->count() > 0 && !last_chain_.rows.isEmpty()) {
- const int keep = strike_combo_->currentIndex();
+ // rebuild_strike_combo re-selects by strike value, so the anchor sticks.
+ if (strike_combo_ && strike_combo_->count() > 0 && !last_chain_.rows.isEmpty())
rebuild_strike_combo(last_chain_);
- if (keep >= 0 && keep < strike_combo_->count())
- strike_combo_->setCurrentIndex(keep);
- }
}
void MultiStraddleSubTab::on_chain_published(const QVariant& v) {
if (!v.canConvert<OptionChain>())
return;
last_chain_ = v.value<OptionChain>();
- if (last_chain_.underlying != current_underlying_) {
+ const bool series_changed =
+ last_chain_.underlying != current_underlying_ || last_chain_.expiry != current_expiry_;
+ if (series_changed) {
current_underlying_ = last_chain_.underlying;
+ current_expiry_ = last_chain_.expiry;
rebuild_strike_combo(last_chain_);
- // Drop existing selections — they're stale for the new underlying.
+ // Drop existing selections — their tokens belong to the previous series.
for (int i = selections_.size() - 1; i >= 0; --i)
remove_selection(i);
- }
- if (strike_combo_->count() == 0)
+ } else if (strike_combo_->count() != last_chain_.rows.size()) {
+ // Same series, resized ladder (the chain window slides with the ATM).
+ // Rebuild so the anchor list matches the rows we index into; existing
+ // selections are token-keyed and stay valid.
rebuild_strike_combo(last_chain_);
+ }
add_btn_->setEnabled(strike_combo_->count() > 0);
}
void MultiStraddleSubTab::rebuild_strike_combo(const OptionChain& chain) {
QSignalBlocker block(strike_combo_);
+ // Preserve the user's anchor by STRIKE across rebuilds; a row index would
+ // point at a different strike as soon as the ladder window shifts.
+ const double keep_strike = strike_combo_->count() > 0 ? strike_combo_->currentData().toDouble() : 0.0;
strike_combo_->clear();
int atm_idx = 0;
+ int keep_idx = -1;
for (int i = 0; i < chain.rows.size(); ++i) {
const auto& r = chain.rows[i];
- strike_combo_->addItem(strike_label(r), QVariant(int(i)));
+ strike_combo_->addItem(strike_label(r), QVariant(r.strike));
if (r.is_atm)
atm_idx = i;
+ if (keep_strike > 0 && std::abs(r.strike - keep_strike) < 1e-6)
+ keep_idx = i;
}
if (chain.rows.isEmpty())
return;
- strike_combo_->setCurrentIndex(atm_idx);
+ strike_combo_->setCurrentIndex(keep_idx >= 0 ? keep_idx : atm_idx);
}
void MultiStraddleSubTab::on_add_clicked() {
if (last_chain_.rows.isEmpty())
return;
- const int anchor_idx = strike_combo_->currentData().toInt();
- if (anchor_idx < 0 || anchor_idx >= last_chain_.rows.size())
+ // Resolve the anchor by strike value, then derive the wings from its
+ // position in the *current* ladder.
+ const double anchor_strike = strike_combo_->currentData().toDouble();
+ int anchor_idx = -1;
+ for (int i = 0; i < last_chain_.rows.size(); ++i) {
+ if (std::abs(last_chain_.rows[i].strike - anchor_strike) < 1e-6) {
+ anchor_idx = i;
+ break;
+ }
+ }
+ if (anchor_idx < 0) {
+ LOG_WARN("FnoMultiStraddle", "Anchor strike is no longer in the chain — reselect it.");
+ selection_list_->setToolTip(tr("That anchor strike is no longer in the chain. Pick another."));
return;
+ }
const int type_idx = type_combo_->currentIndex();
if (type_idx < 0 || type_idx >= int(sizeof(kTypeDefs) / sizeof(kTypeDefs[0])))
return;
@@ -278,6 +305,10 @@ void MultiStraddleSubTab::on_add_clicked() {
const int pe_idx = anchor_idx - wing;
if (ce_idx < 0 || ce_idx >= last_chain_.rows.size() || pe_idx < 0 || pe_idx >= last_chain_.rows.size()) {
LOG_WARN("FnoMultiStraddle", "Selected wings fall outside the chain — pick a closer anchor or smaller wing.");
+ // Surface it — a silent no-op on a button press reads as a broken UI.
+ add_btn_->setToolTip(tr("The ±%1 wings fall outside the loaded strike range. "
+ "Pick a strike nearer the middle of the chain, or a narrower strangle.")
+ .arg(wing));
return;
}
@@ -287,8 +318,11 @@ void MultiStraddleSubTab::on_add_clicked() {
sel.pe_token = last_chain_.rows[pe_idx].pe_token;
if (sel.ce_token == 0 || sel.pe_token == 0) {
LOG_WARN("FnoMultiStraddle", "Anchor row missing CE or PE token — pick a different strike.");
+ add_btn_->setToolTip(tr("This provider published no instrument token for one side of that strike, "
+ "so its intraday history can't be fetched. Pick another strike."));
return;
}
+ add_btn_->setToolTip(QString());
if (wing == 0) {
sel.label = tr("Straddle %1").arg(last_chain_.rows[anchor_idx].strike, 0, 'f', 0);
} else {
diff --git a/fincept-qt/src/screens/fno/MultiStraddleSubTab.h b/fincept-qt/src/screens/fno/MultiStraddleSubTab.h
index 62b0dffac..d801dccf3 100644
--- a/fincept-qt/src/screens/fno/MultiStraddleSubTab.h
+++ b/fincept-qt/src/screens/fno/MultiStraddleSubTab.h
@@ -88,6 +88,9 @@ class MultiStraddleSubTab : public QWidget {
QVector<Selection> selections_;
fincept::services::options::OptionChain last_chain_;
QString current_underlying_;
+ /// Expiry the anchor combo was last built for — a new expiry means a new
+ /// strike ladder even when the underlying is unchanged.
+ QString current_expiry_;
bool chain_subscribed_ = false;
/// Per-token sample cache populated by oi:history subscription callbacks.
diff --git a/fincept-qt/src/screens/fno/OISubTab.cpp b/fincept-qt/src/screens/fno/OISubTab.cpp
index 720c73f91..24b564cb5 100644
--- a/fincept-qt/src/screens/fno/OISubTab.cpp
+++ b/fincept-qt/src/screens/fno/OISubTab.cpp
@@ -108,6 +108,7 @@ void OISubTab::setup_ui() {
picker_lbl_ = new QLabel(tr("STRIKE"), intraday_wrap);
picker_lbl_->setObjectName("fnoOIPickerLabel");
strike_combo_ = new QComboBox(intraday_wrap);
+ strike_combo_->setAccessibleName(tr("Strike for intraday open-interest chart"));
picker_row->addWidget(picker_lbl_);
picker_row->addWidget(strike_combo_);
picker_row->addStretch(1);
@@ -133,14 +134,22 @@ void OISubTab::setup_ui() {
QVariantMap OISubTab::save_state() const {
QVariantMap m;
- m["strike_index"] = strike_combo_ ? strike_combo_->currentIndex() : -1;
+ // Persist the strike VALUE, not the combo index: the index means nothing
+ // across sessions (different ladder, different ATM) and restoring it would
+ // silently chart a different strike than the one the user was watching.
+ m["strike"] = selected_strike_;
return m;
}
void OISubTab::restore_state(const QVariantMap& state) {
- Q_UNUSED(state);
- // Strike combo content is rebuilt from chain on first publish — restore
- // happens implicitly when the user re-navigates and the chain arrives.
+ const double strike = state.value("strike", 0.0).toDouble();
+ if (strike <= 0)
+ return;
+ selected_strike_ = strike;
+ // Applied when the next chain publish rebuilds the combo; if the chain is
+ // already here, apply it immediately.
+ if (!last_chain_.rows.isEmpty())
+ rebuild_strike_combo(last_chain_);
}
void OISubTab::showEvent(QShowEvent* e) {
@@ -170,14 +179,13 @@ void OISubTab::changeEvent(QEvent* event) {
void OISubTab::retranslateUi() {
if (picker_lbl_)
picker_lbl_->setText(tr("STRIKE"));
- // Rebuild the combo so the "(ATM)" suffix picks up the new language,
- // preserving the current selection.
- if (strike_combo_ && strike_combo_->count() > 0 && !last_chain_.rows.isEmpty()) {
- const int keep = strike_combo_->currentIndex();
+ if (strike_combo_)
+ strike_combo_->setAccessibleName(tr("Strike for intraday open-interest chart"));
+ // Rebuild the combo so the "(ATM)" suffix picks up the new language.
+ // rebuild_strike_combo re-selects by strike value, so the user's pick is
+ // preserved without touching indices.
+ if (strike_combo_ && strike_combo_->count() > 0 && !last_chain_.rows.isEmpty())
rebuild_strike_combo(last_chain_);
- if (keep >= 0 && keep < strike_combo_->count())
- strike_combo_->setCurrentIndex(keep);
- }
}
void OISubTab::on_chain_published(const QString& topic, const QVariant& v) {
@@ -190,49 +198,69 @@ void OISubTab::on_chain_published(const QString& topic, const QVariant& v) {
pain_chart_->set_chain(last_chain_);
buildup_->buildup_model()->set_chain(last_chain_);
- // Rebuild strike combo whenever the underlying changes (different strike
- // ladder). For chain refreshes on the same underlying, leave the combo
- // alone so the user's selection sticks.
- if (last_chain_.underlying != current_underlying_) {
+ // Rebuild the strike combo whenever the ladder itself can have changed:
+ // a new underlying OR a new expiry (each expiry has its own strike set),
+ // or a differently-sized ladder on the same series (the chain window slides
+ // as the ATM moves). On a plain refresh the combo is left alone so the
+ // user's selection sticks.
+ const bool ladder_changed = last_chain_.underlying != current_underlying_ ||
+ last_chain_.expiry != current_expiry_ ||
+ strike_combo_->count() != last_chain_.rows.size();
+ if (ladder_changed) {
current_underlying_ = last_chain_.underlying;
+ current_expiry_ = last_chain_.expiry;
rebuild_strike_combo(last_chain_);
}
- // Strike list might be empty if the publish came in with rows but combo
- // hadn't been seeded yet (e.g. underlying just changed mid-publish).
- if (strike_combo_->count() == 0)
- rebuild_strike_combo(last_chain_);
}
void OISubTab::rebuild_strike_combo(const OptionChain& chain) {
QSignalBlocker block(strike_combo_);
strike_combo_->clear();
+ // The item's userData is the STRIKE, not the row index. A row index goes
+ // stale the moment the chain republishes with a shifted window, which would
+ // silently point the intraday OI chart at a different strike than the combo
+ // label claims.
int atm_idx = 0;
+ int keep_idx = -1;
for (int i = 0; i < chain.rows.size(); ++i) {
const auto& r = chain.rows[i];
- strike_combo_->addItem(strike_label(r), QVariant(int(i)));
+ strike_combo_->addItem(strike_label(r), QVariant(r.strike));
if (r.is_atm)
atm_idx = i;
+ if (selected_strike_ > 0 && std::abs(r.strike - selected_strike_) < 1e-6)
+ keep_idx = i;
}
- if (chain.rows.isEmpty())
+ if (chain.rows.isEmpty()) {
+ intraday_->clear_subscription();
return;
- strike_combo_->setCurrentIndex(atm_idx);
+ }
+ strike_combo_->setCurrentIndex(keep_idx >= 0 ? keep_idx : atm_idx);
+ selected_strike_ = strike_combo_->currentData().toDouble();
apply_strike_subscription();
}
void OISubTab::on_strike_combo_changed(int /*index*/) {
+ if (strike_combo_)
+ selected_strike_ = strike_combo_->currentData().toDouble();
apply_strike_subscription();
}
void OISubTab::apply_strike_subscription() {
if (last_chain_.rows.isEmpty() || !strike_combo_)
return;
- const int row_idx = strike_combo_->currentData().toInt();
- if (row_idx < 0 || row_idx >= last_chain_.rows.size()) {
+ const double strike = strike_combo_->currentData().toDouble();
+ const fincept::services::options::OptionChainRow* row = nullptr;
+ for (const auto& r : last_chain_.rows) {
+ if (std::abs(r.strike - strike) < 1e-6) {
+ row = &r;
+ break;
+ }
+ }
+ if (!row) {
intraday_->clear_subscription();
return;
}
- const auto& row = last_chain_.rows.at(row_idx);
- intraday_->set_subscription(last_chain_.broker_id, row.ce_token, row.pe_token, QStringLiteral("1d"));
+ intraday_->set_subscription(last_chain_.broker_id, row->ce_token, row->pe_token, QStringLiteral("1d"));
}
} // namespace fincept::screens::fno
diff --git a/fincept-qt/src/screens/fno/OISubTab.h b/fincept-qt/src/screens/fno/OISubTab.h
index 2c51472d1..32ee30df6 100644
--- a/fincept-qt/src/screens/fno/OISubTab.h
+++ b/fincept-qt/src/screens/fno/OISubTab.h
@@ -66,6 +66,14 @@ class OISubTab : public QWidget {
fincept::services::options::OptionChain last_chain_;
QString current_underlying_;
+ /// Expiry the strike combo was last built for. A new expiry has a different
+ /// strike ladder, so the combo must be rebuilt even when the underlying is
+ /// unchanged.
+ QString current_expiry_;
+ /// Strike the user picked (0 = none). Carried across combo rebuilds and
+ /// session restore. Selection is keyed on the strike VALUE, never on a row
+ /// index — the ladder shifts as the ATM moves.
+ double selected_strike_ = 0.0;
bool subscribed_ = false;
};
diff --git a/fincept-qt/src/screens/fno/OptionChainModel.cpp b/fincept-qt/src/screens/fno/OptionChainModel.cpp
index a0af6af72..64fa8f976 100644
--- a/fincept-qt/src/screens/fno/OptionChainModel.cpp
+++ b/fincept-qt/src/screens/fno/OptionChainModel.cpp
@@ -150,11 +150,19 @@ void OptionChainModel::set_chain(const OptionChain& chain) {
// e.g. a WS-driven live re-publish or a periodic reconcile), merge in place
// and repaint instead of resetting the model. A full reset would drop the
// user's scroll position and selection on every refresh; this keeps them.
+ //
+ // SAFETY: the strike ladder is compared too, not just the tokens. Some
+ // providers (Databento, Fyers' chain-v3) publish rows with token == 0 for
+ // every strike — comparing tokens alone would then call a *shifted* ladder
+ // "the same structure", leaving the user's selected row pointing at a
+ // different strike after a refresh. Row identity for this table is
+ // (strike, ce_token, pe_token); any change to any of them forces a reset.
bool same_structure = chain.rows.size() == chain_.rows.size() && !chain_.rows.isEmpty();
if (same_structure) {
for (int i = 0; i < chain.rows.size(); ++i) {
if (chain.rows[i].ce_token != chain_.rows[i].ce_token ||
- chain.rows[i].pe_token != chain_.rows[i].pe_token) {
+ chain.rows[i].pe_token != chain_.rows[i].pe_token ||
+ std::abs(chain.rows[i].strike - chain_.rows[i].strike) > 1e-6) {
same_structure = false;
break;
}
diff --git a/fincept-qt/src/screens/fno/OptionChainTable.cpp b/fincept-qt/src/screens/fno/OptionChainTable.cpp
index 8f7d1dc16..44928b8b0 100644
--- a/fincept-qt/src/screens/fno/OptionChainTable.cpp
+++ b/fincept-qt/src/screens/fno/OptionChainTable.cpp
@@ -5,6 +5,7 @@
#include <QContextMenuEvent>
#include <QHeaderView>
+#include <QKeyEvent>
#include <QMenu>
#include <QMouseEvent>
#include <QPainter>
@@ -111,7 +112,13 @@ OptionChainTable::OptionChainTable(QWidget* parent) : QTableView(parent) {
setSelectionBehavior(QAbstractItemView::SelectRows);
setSelectionMode(QAbstractItemView::SingleSelection);
setEditTriggers(QAbstractItemView::NoEditTriggers);
- setFocusPolicy(Qt::NoFocus);
+ // Focusable so a trader can arrow between strikes, Return to add a leg to
+ // the Builder, and Menu-key to open Buy/Sell — the chain was mouse-only.
+ setFocusPolicy(Qt::StrongFocus);
+ setAccessibleName(tr("Option chain"));
+ setAccessibleDescription(tr("Strikes with call data on the left and put data on the right. "
+ "Arrow keys move between strikes, Return adds the focused leg to the "
+ "strategy builder, and the context-menu key offers Buy and Sell."));
setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
@@ -141,45 +148,68 @@ OptionChainTable::OptionChainTable(QWidget* parent) : QTableView(parent) {
colors::BG_RAISED(), colors::TEXT_SECONDARY()));
}
+bool OptionChainTable::leg_at(const QModelIndex& idx, qint64& token, double& strike, bool& is_call) const {
+ if (!idx.isValid() || !model_)
+ return false;
+ if (idx.row() < 0 || idx.row() >= model_->rowCount())
+ return false;
+ const int col = idx.column();
+ const bool ce_side = (col >= OptionChainModel::ColCeOi && col <= OptionChainModel::ColCeLtp);
+ const bool pe_side = (col >= OptionChainModel::ColPeLtp && col <= OptionChainModel::ColPeOi);
+ if (!ce_side && !pe_side)
+ return false; // strike pivot — nothing to trade
+ is_call = ce_side;
+ token = idx.data(is_call ? OptionChainModel::CeTokenRole : OptionChainModel::PeTokenRole).toLongLong();
+ strike = idx.data(OptionChainModel::StrikeRole).toDouble();
+ // A zero token means the provider gave us no instrument identity for this
+ // leg. Every downstream consumer resolves the contract *by token*, so a
+ // zero would match the first zero-token row in the chain — a completely
+ // different strike. Refuse rather than guess.
+ return token != 0;
+}
+
void OptionChainTable::mousePressEvent(QMouseEvent* e) {
// Left-click an LTP cell adds the leg to the strategy builder. Right-click
// is handled by contextMenuEvent (Buy/Sell/Add-to-Builder), so it must NOT
// also fire leg_clicked here.
if (e->button() == Qt::LeftButton) {
- QModelIndex idx = indexAt(e->pos());
- if (idx.isValid()) {
- const int col = idx.column();
- const bool is_ce_ltp = (col == OptionChainModel::ColCeLtp);
- const bool is_pe_ltp = (col == OptionChainModel::ColPeLtp);
- if (is_ce_ltp || is_pe_ltp) {
- const qint64 token = is_ce_ltp ? idx.data(OptionChainModel::CeTokenRole).toLongLong()
- : idx.data(OptionChainModel::PeTokenRole).toLongLong();
- const double strike = idx.data(OptionChainModel::StrikeRole).toDouble();
- if (token != 0)
- emit leg_clicked(token, strike, is_ce_ltp, 1);
- }
+ const QModelIndex idx = indexAt(e->pos());
+ const int col = idx.column();
+ if (col == OptionChainModel::ColCeLtp || col == OptionChainModel::ColPeLtp) {
+ qint64 token = 0;
+ double strike = 0;
+ bool is_call = false;
+ if (leg_at(idx, token, strike, is_call))
+ emit leg_clicked(token, strike, is_call, 1);
}
}
QTableView::mousePressEvent(e);
}
-void OptionChainTable::contextMenuEvent(QContextMenuEvent* e) {
- const QModelIndex idx = indexAt(e->pos());
- if (!idx.isValid() || !model_) {
- QTableView::contextMenuEvent(e);
- return;
- }
- const int col = idx.column();
- const bool ce_side = (col >= OptionChainModel::ColCeOi && col <= OptionChainModel::ColCeLtp);
- const bool pe_side = (col >= OptionChainModel::ColPeLtp && col <= OptionChainModel::ColPeOi);
- if (!ce_side && !pe_side) { // strike pivot — nothing to trade
- QTableView::contextMenuEvent(e);
- return;
+void OptionChainTable::keyPressEvent(QKeyEvent* e) {
+ if (e->key() == Qt::Key_Return || e->key() == Qt::Key_Enter) {
+ qint64 token = 0;
+ double strike = 0;
+ bool is_call = false;
+ if (leg_at(currentIndex(), token, strike, is_call)) {
+ emit leg_clicked(token, strike, is_call, 1);
+ e->accept();
+ return;
+ }
}
- const bool is_call = ce_side;
- const qint64 token = idx.data(is_call ? OptionChainModel::CeTokenRole : OptionChainModel::PeTokenRole).toLongLong();
- const double strike = idx.data(OptionChainModel::StrikeRole).toDouble();
- if (token == 0) {
+ QTableView::keyPressEvent(e);
+}
+
+void OptionChainTable::contextMenuEvent(QContextMenuEvent* e) {
+ // A keyboard-triggered context menu carries no meaningful pos(), so resolve
+ // from the focused cell instead — otherwise the Menu key would open a
+ // Buy/Sell menu for whatever strike happens to sit under the widget centre.
+ const QModelIndex idx =
+ (e->reason() == QContextMenuEvent::Keyboard) ? currentIndex() : indexAt(e->pos());
+ qint64 token = 0;
+ double strike = 0;
+ bool is_call = false;
+ if (!leg_at(idx, token, strike, is_call)) {
QTableView::contextMenuEvent(e);
return;
}
@@ -198,7 +228,11 @@ void OptionChainTable::contextMenuEvent(QContextMenuEvent* e) {
QAction* sell = menu.addAction(tr("Sell %1").arg(label));
menu.addSeparator();
QAction* to_builder = menu.addAction(tr("Add to Builder"));
- QAction* chosen = menu.exec(e->globalPos());
+ // Keyboard invocation has no cursor position — anchor the menu on the cell.
+ const QPoint anchor = (e->reason() == QContextMenuEvent::Keyboard)
+ ? viewport()->mapToGlobal(visualRect(idx).bottomLeft())
+ : e->globalPos();
+ QAction* chosen = menu.exec(anchor);
if (chosen == buy)
emit order_requested(token, strike, is_call, /*is_buy=*/true);
else if (chosen == sell)
diff --git a/fincept-qt/src/screens/fno/OptionChainTable.h b/fincept-qt/src/screens/fno/OptionChainTable.h
index 5ec3e9150..2e6da220b 100644
--- a/fincept-qt/src/screens/fno/OptionChainTable.h
+++ b/fincept-qt/src/screens/fno/OptionChainTable.h
@@ -33,8 +33,17 @@ class OptionChainTable : public QTableView {
protected:
void mousePressEvent(QMouseEvent* e) override;
void contextMenuEvent(QContextMenuEvent* e) override;
+ /// Arrow keys traverse strikes (QTableView default); Return/Enter on a CE or
+ /// PE cell adds that leg to the Builder, so the chain is usable without a
+ /// mouse. Placing an order still requires the explicit context menu.
+ void keyPressEvent(QKeyEvent* e) override;
private:
+ /// Resolve (token, strike, is_call) for a cell. Returns false when the cell
+ /// is the strike pivot, is out of range, or carries no instrument token —
+ /// the single gate every trade entry point goes through.
+ bool leg_at(const QModelIndex& idx, qint64& token, double& strike, bool& is_call) const;
+
OptionChainModel* model_ = nullptr;
};
diff --git a/fincept-qt/src/screens/fno/OrderConfirmDialog.cpp b/fincept-qt/src/screens/fno/OrderConfirmDialog.cpp
index f295faaa5..9e8817e98 100644
--- a/fincept-qt/src/screens/fno/OrderConfirmDialog.cpp
+++ b/fincept-qt/src/screens/fno/OrderConfirmDialog.cpp
@@ -117,18 +117,24 @@ void OrderConfirmDialog::setup_ui(double premium, double max_profit, double max_
// ── Leg table ─────────────────────────────────────────────────────────
legs_table_ = new QTableWidget(this);
- legs_table_->setColumnCount(5);
- legs_table_->setHorizontalHeaderLabels({tr("Symbol"), tr("B/S"), tr("Qty"), tr("Type"), tr("Entry")});
+ legs_table_->setColumnCount(6);
+ legs_table_->setHorizontalHeaderLabels(
+ {tr("Symbol"), tr("B/S"), tr("Lots"), tr("Qty"), tr("Type"), tr("Entry")});
legs_table_->verticalHeader()->setVisible(false);
legs_table_->setSelectionMode(QAbstractItemView::NoSelection);
legs_table_->setEditTriggers(QAbstractItemView::NoEditTriggers);
legs_table_->setShowGrid(false);
legs_table_->setFocusPolicy(Qt::NoFocus);
+ legs_table_->setAccessibleName(tr("Order legs"));
legs_table_->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
legs_table_->horizontalHeader()->setSectionResizeMode(0, QHeaderView::ResizeToContents);
legs_table_->verticalHeader()->setDefaultSectionSize(24);
root->addWidget(legs_table_, 1);
+ legs_note_ = new QLabel(this);
+ legs_note_->setObjectName("confirmSub");
+ root->addWidget(legs_note_);
+
// ── Summary block ─────────────────────────────────────────────────────
auto add_kv = [this](QHBoxLayout* lay, QLabel*& v_out, QLabel*& k_out, const QString& key) {
auto* wrap = new QWidget(this);
@@ -168,34 +174,70 @@ void OrderConfirmDialog::setup_ui(double premium, double max_profit, double max_
cancel_btn_ = new QPushButton(tr("CANCEL"), this);
cancel_btn_->setObjectName("confirmCancel");
cancel_btn_->setCursor(Qt::PointingHandCursor);
+ cancel_btn_->setAccessibleName(tr("Cancel without placing orders"));
place_btn_ = new QPushButton(tr("PLACE PAPER ORDERS"), this);
place_btn_->setObjectName("confirmPlace");
place_btn_->setCursor(Qt::PointingHandCursor);
+ place_btn_->setAccessibleName(tr("Place the listed legs as paper orders"));
btn_row->addWidget(cancel_btn_);
btn_row->addWidget(place_btn_);
root->addLayout(btn_row);
+ // Cancel is the default: a stray Return on a modal that dispatches a
+ // leveraged multi-leg basket must not place it. Placing takes a click
+ // (or an explicit Tab to the button, then Space).
+ cancel_btn_->setDefault(true);
+ cancel_btn_->setAutoDefault(true);
+ place_btn_->setAutoDefault(false);
+ setTabOrder(cancel_btn_, place_btn_);
+
connect(cancel_btn_, &QPushButton::clicked, this, &QDialog::reject);
connect(place_btn_, &QPushButton::clicked, this, &QDialog::accept);
}
void OrderConfirmDialog::populate_legs() {
+ // Every leg the strategy carries is listed, but a leg that will NOT be
+ // submitted (toggled off, or zero lots) is rendered dim and explicitly
+ // tagged so the preview can never claim more than the dispatcher places.
+ // The caller's submit loop uses exactly the same predicate.
legs_table_->setRowCount(strategy_.legs.size());
+ int placeable = 0;
for (int i = 0; i < strategy_.legs.size(); ++i) {
const StrategyLeg& leg = strategy_.legs.at(i);
+ const bool will_place = leg.is_active && leg.lots != 0;
+ if (will_place)
+ ++placeable;
+ const QColor dim(colors::TEXT_DIM());
auto set_cell = [&](int col, const QString& txt, const QColor& fg = QColor()) {
auto* item = new QTableWidgetItem(txt);
item->setFlags(item->flags() & ~Qt::ItemIsEditable);
- if (fg.isValid())
+ if (!will_place)
+ item->setForeground(dim);
+ else if (fg.isValid())
item->setForeground(fg);
+ if (!will_place)
+ item->setToolTip(tr("Not submitted — leg is switched off or has zero lots."));
legs_table_->setItem(i, col, item);
};
- set_cell(0, leg.symbol);
+ const int lot_size = leg.lot_size > 0 ? leg.lot_size : 0;
+ const qint64 qty = qint64(std::abs(leg.lots)) * qint64(lot_size);
const bool buy = leg.lots >= 0;
+ set_cell(0, will_place ? leg.symbol : tr("%1 (skipped)").arg(leg.symbol));
set_cell(1, buy ? tr("BUY") : tr("SELL"), buy ? QColor(colors::POSITIVE()) : QColor(colors::NEGATIVE()));
- set_cell(2, QString::number(std::abs(leg.lots) * leg.lot_size));
- set_cell(3, leg.type == InstrumentType::CE ? "CE" : leg.type == InstrumentType::PE ? "PE" : "FUT");
- set_cell(4, QString::number(leg.entry_price, 'f', 2));
+ set_cell(2, QString::number(std::abs(leg.lots)));
+ // Lot size is spelled out: an F&O quantity is meaningless without it,
+ // and a leg whose lot size never resolved (0) must be visibly broken
+ // rather than quietly submitted as a 1-unit order.
+ set_cell(3, lot_size > 0 ? tr("%1 (×%2)").arg(QString::number(qty), QString::number(lot_size))
+ : tr("— lot size unknown"),
+ lot_size > 0 ? QColor() : QColor(colors::NEGATIVE()));
+ set_cell(4, leg.type == InstrumentType::CE ? "CE" : leg.type == InstrumentType::PE ? "PE" : "FUT");
+ set_cell(5, QString::number(leg.entry_price, 'f', 2));
+ }
+ if (legs_note_) {
+ legs_note_->setText(tr("%1 of %2 legs will be placed as market orders at the shown entry premium.")
+ .arg(placeable)
+ .arg(strategy_.legs.size()));
}
}
@@ -210,7 +252,9 @@ void OrderConfirmDialog::start_margin_fetch() {
QVector<UnifiedOrder> orders;
orders.reserve(strategy_.legs.size());
for (const auto& leg : strategy_.legs) {
- if (!leg.is_active)
+ // Same predicate the dispatcher uses — margin must be quoted for the
+ // basket that is actually going to be sent, not for the full leg list.
+ if (!leg.is_active || leg.lots == 0)
continue;
orders.append(leg_to_unified(leg));
}
@@ -275,8 +319,11 @@ void OrderConfirmDialog::retranslateUi() {
.arg(strategy_.underlying)
.arg(strategy_.expiry)
.arg(chain_.spot, 0, 'f', 2));
- if (legs_table_)
- legs_table_->setHorizontalHeaderLabels({tr("Symbol"), tr("B/S"), tr("Qty"), tr("Type"), tr("Entry")});
+ if (legs_table_) {
+ legs_table_->setHorizontalHeaderLabels(
+ {tr("Symbol"), tr("B/S"), tr("Lots"), tr("Qty"), tr("Type"), tr("Entry")});
+ populate_legs(); // re-renders the per-row "(skipped)" / lot-size strings
+ }
if (key_premium_)
key_premium_->setText(tr("Net Premium").toUpper());
if (key_max_pnl_)
diff --git a/fincept-qt/src/screens/fno/OrderConfirmDialog.h b/fincept-qt/src/screens/fno/OrderConfirmDialog.h
index bfe25cc28..eb8cfd5a8 100644
--- a/fincept-qt/src/screens/fno/OrderConfirmDialog.h
+++ b/fincept-qt/src/screens/fno/OrderConfirmDialog.h
@@ -54,6 +54,9 @@ class OrderConfirmDialog : public QDialog {
QTableWidget* legs_table_ = nullptr;
QLabel* title_label_ = nullptr;
QLabel* sub_label_ = nullptr;
+ /// "N of M legs will be placed" — makes preview/submission divergence
+ /// impossible to miss when some legs are toggled off or have zero lots.
+ QLabel* legs_note_ = nullptr;
QLabel* lbl_premium_ = nullptr;
QLabel* lbl_max_pnl_ = nullptr;
QLabel* lbl_margin_ = nullptr;
diff --git a/fincept-qt/src/screens/fno/PayoffStripWidget.cpp b/fincept-qt/src/screens/fno/PayoffStripWidget.cpp
index f959893e7..e270aca53 100644
--- a/fincept-qt/src/screens/fno/PayoffStripWidget.cpp
+++ b/fincept-qt/src/screens/fno/PayoffStripWidget.cpp
@@ -18,6 +18,12 @@ using namespace fincept::ui;
PayoffStripWidget::PayoffStripWidget(QWidget* parent) : QWidget(parent) {
setFixedHeight(80);
setObjectName("fnoPayoffStrip");
+ setAccessibleName(tr("Payoff at expiry"));
+ setAccessibleDescription(tr("Profit and loss across underlying prices. Solid line is P/L at expiry; "
+ "the dashed line is P/L on the selected target date. Vertical markers show "
+ "the current spot and each breakeven."));
+ setToolTip(tr("Solid: P/L at expiry. Dashed: P/L at the TARGET date. "
+ "Amber vertical: spot. Dotted verticals: breakevens."));
}
void PayoffStripWidget::set_payoff(const QVector<fincept::services::options::PayoffPoint>& curve, double spot,
@@ -57,7 +63,11 @@ void PayoffStripWidget::rebuild_pixmap() {
cached_ = QPixmap();
return;
}
- cached_ = QPixmap(sz);
+ // HiDPI: without a DPR-scaled backing store the strip renders at 1× and is
+ // visibly soft next to the rest of the UI on a 150%/200% display.
+ const qreal dpr = devicePixelRatioF();
+ cached_ = QPixmap(QSize(int(sz.width() * dpr), int(sz.height() * dpr)));
+ cached_.setDevicePixelRatio(dpr);
cached_.fill(QColor(colors::BG_BASE()));
if (curve_.size() < 2)
@@ -75,6 +85,11 @@ void PayoffStripWidget::rebuild_pixmap() {
if (spot_range < 1e-6)
spot_range = 1.0;
+ // The target-day curve is bounded too — the TARGET +N d control drives it,
+ // and before this it was computed but never drawn, so the spin box looked
+ // like it did nothing. Its range has to be inside the y-window or it would
+ // be clipped away.
+ bool has_target = false;
double y_min = std::numeric_limits<double>::max();
double y_max = std::numeric_limits<double>::lowest();
for (const auto& pt : curve_) {
@@ -82,6 +97,12 @@ void PayoffStripWidget::rebuild_pixmap() {
y_min = std::min(y_min, pt.pnl_expiry);
y_max = std::max(y_max, pt.pnl_expiry);
}
+ if (std::isfinite(pt.pnl_target)) {
+ y_min = std::min(y_min, pt.pnl_target);
+ y_max = std::max(y_max, pt.pnl_target);
+ if (std::abs(pt.pnl_target - pt.pnl_expiry) > 1e-9)
+ has_target = true;
+ }
}
if (y_min >= y_max) {
y_min = -1.0;
@@ -133,6 +154,20 @@ void PayoffStripWidget::rebuild_pixmap() {
}
}
+ // Target-day (mark-to-market) curve — dashed amber, drawn under the expiry
+ // line so the payoff at expiry stays the dominant read.
+ if (has_target) {
+ QPen target_pen(QColor(colors::AMBER()), 1, Qt::DashLine);
+ p.setPen(target_pen);
+ p.setBrush(Qt::NoBrush);
+ for (int i = 0; i < curve_.size() - 1; ++i) {
+ if (!std::isfinite(curve_[i].pnl_target) || !std::isfinite(curve_[i + 1].pnl_target))
+ continue;
+ p.drawLine(QPointF(to_x(curve_[i].spot), to_y(curve_[i].pnl_target)),
+ QPointF(to_x(curve_[i + 1].spot), to_y(curve_[i + 1].pnl_target)));
+ }
+ }
+
// PnL expiry curve
p.setPen(QPen(QColor(colors::TEXT_PRIMARY()), 1));
p.setBrush(Qt::NoBrush);
diff --git a/fincept-qt/src/screens/fno/ScreenerSubTab.cpp b/fincept-qt/src/screens/fno/ScreenerSubTab.cpp
index 931e9347a..0b47c84df 100644
--- a/fincept-qt/src/screens/fno/ScreenerSubTab.cpp
+++ b/fincept-qt/src/screens/fno/ScreenerSubTab.cpp
@@ -14,6 +14,7 @@
#include <QLabel>
#include <QLocale>
#include <QPointer>
+#include <QScrollBar>
#include <QShowEvent>
#include <QSpinBox>
#include <QTableView>
@@ -89,6 +90,9 @@ QVariant ScreenedChainModel::data(const QModelIndex& index, int role) const {
const OptionChainRow& r = rows_.at(index.row());
const int col = index.column();
+ if (role == StrikeRole)
+ return r.strike;
+
if (role == Qt::TextAlignmentRole) {
if (col == ColStrike)
return int(Qt::AlignCenter | Qt::AlignVCenter);
@@ -139,6 +143,25 @@ QVariant ScreenedChainModel::headerData(int section, Qt::Orientation orient, int
}
void ScreenedChainModel::set_rows(const QVector<OptionChainRow>& rows) {
+ // Fast path: same strike set (the overwhelmingly common case — a chain
+ // republish with unchanged filters). A full model reset on every publish
+ // yanks the user's scroll position back to the top and drops the selected
+ // row several times a minute, which makes the screener unusable as a live
+ // monitor. Merge in place and repaint instead.
+ bool same_rows = rows.size() == rows_.size() && !rows_.isEmpty();
+ if (same_rows) {
+ for (int i = 0; i < rows.size(); ++i) {
+ if (std::abs(rows[i].strike - rows_[i].strike) > 1e-6) {
+ same_rows = false;
+ break;
+ }
+ }
+ }
+ if (same_rows) {
+ rows_ = rows;
+ emit dataChanged(index(0, 0), index(rows_.size() - 1, ColCount - 1));
+ return;
+ }
beginResetModel();
rows_ = rows;
endResetModel();
@@ -231,11 +254,22 @@ void ScreenerSubTab::setup_ui() {
pe_oi_min_->setValue(0);
add_kv(tr("PE OI ≥"), pe_oi_label_, pe_oi_min_);
+ iv_min_->setAccessibleName(tr("Minimum implied volatility"));
+ iv_max_->setAccessibleName(tr("Maximum implied volatility"));
+ distance_->setAccessibleName(tr("Maximum strikes away from at-the-money"));
+ ce_oi_min_->setAccessibleName(tr("Minimum call open interest in lakhs"));
+ pe_oi_min_->setAccessibleName(tr("Minimum put open interest in lakhs"));
+ setTabOrder(iv_min_, iv_max_);
+ setTabOrder(iv_max_, distance_);
+ setTabOrder(distance_, ce_oi_min_);
+ setTabOrder(ce_oi_min_, pe_oi_min_);
+
hlay->addStretch(1);
root->addWidget(header);
// ── Body: table ───────────────────────────────────────────────────────
table_ = new QTableView(this);
+ table_->setAccessibleName(tr("Screened strikes"));
model_ = new ScreenedChainModel(this);
table_->setModel(model_);
table_->setShowGrid(false);
@@ -343,7 +377,10 @@ void ScreenerSubTab::on_filter_changed() {
void ScreenerSubTab::apply_filters() {
if (last_chain_.rows.isEmpty()) {
model_->set_rows({});
- count_label_->setText(tr("0 of 0 strikes match"));
+ // Distinguish "no chain loaded yet" from "chain loaded, nothing passes
+ // your filters" — they need completely different user actions.
+ count_label_->setText(tr("No chain loaded — open the Chain tab and pick a broker, "
+ "underlying and expiry first."));
return;
}
int atm = 0;
@@ -378,8 +415,39 @@ void ScreenerSubTab::apply_filters() {
continue;
filtered.append(r);
}
+
+ // Preserve the user's place across a filter change (which does force a
+ // model reset). Selection is remembered by STRIKE, not row index — the
+ // filtered set is a different length every time the thresholds move.
+ double keep_strike = 0;
+ if (const QModelIndex cur = table_->currentIndex(); cur.isValid() && cur.row() < model_->rowCount())
+ keep_strike = cur.data(ScreenedChainModel::StrikeRole).toDouble();
+ const int keep_scroll = table_->verticalScrollBar() ? table_->verticalScrollBar()->value() : 0;
+
model_->set_rows(filtered);
- count_label_->setText(tr("%1 of %2 strikes match").arg(filtered.size()).arg(last_chain_.rows.size()));
+
+ bool reselected = false;
+ if (keep_strike > 0) {
+ for (int i = 0; i < filtered.size(); ++i) {
+ if (std::abs(filtered[i].strike - keep_strike) < 1e-6) {
+ table_->selectRow(i);
+ table_->scrollTo(model_->index(i, 0), QAbstractItemView::PositionAtCenter);
+ reselected = true;
+ break;
+ }
+ }
+ }
+ // Nothing to re-centre on — hold the scroll position instead of snapping
+ // back to the top on every republish.
+ if (!reselected && table_->verticalScrollBar())
+ table_->verticalScrollBar()->setValue(qMin(keep_scroll, table_->verticalScrollBar()->maximum()));
+
+ if (filtered.isEmpty())
+ count_label_->setText(tr("No strikes match — widen the IV band, the ± strike range, "
+ "or lower the OI floors. (%1 strikes in the chain.)")
+ .arg(last_chain_.rows.size()));
+ else
+ count_label_->setText(tr("%1 of %2 strikes match").arg(filtered.size()).arg(last_chain_.rows.size()));
}
} // namespace fincept::screens::fno
diff --git a/fincept-qt/src/screens/fno/ScreenerSubTab.h b/fincept-qt/src/screens/fno/ScreenerSubTab.h
index daf8922b1..2b9d293f4 100644
--- a/fincept-qt/src/screens/fno/ScreenerSubTab.h
+++ b/fincept-qt/src/screens/fno/ScreenerSubTab.h
@@ -44,6 +44,11 @@ class ScreenedChainModel : public QAbstractTableModel {
ColCount,
};
+ /// Raw strike of a row. Lets the view remember "which strike was selected"
+ /// instead of "which row index", which is meaningless once the filter set
+ /// changes length.
+ enum Role : int { StrikeRole = Qt::UserRole + 1 };
+
explicit ScreenedChainModel(QObject* parent = nullptr);
int rowCount(const QModelIndex& parent = {}) const override;
diff --git a/fincept-qt/src/screens/forum/ForumFeedPanel.cpp b/fincept-qt/src/screens/forum/ForumFeedPanel.cpp
index b9a614f87..2e91f3b5b 100644
--- a/fincept-qt/src/screens/forum/ForumFeedPanel.cpp
+++ b/fincept-qt/src/screens/forum/ForumFeedPanel.cpp
@@ -214,6 +214,21 @@ void ForumFeedPanel::set_loading(bool on) {
}
}
+// P3: a request that never returns used to leave the 350 ms skeleton animation
+// (a setStyleSheet storm across ~18 widgets per tick) running forever behind a
+// hidden screen.
+void ForumFeedPanel::showEvent(QShowEvent* e) {
+ QWidget::showEvent(e);
+ if (skeleton_w_ && skeleton_timer_)
+ skeleton_timer_->start();
+}
+
+void ForumFeedPanel::hideEvent(QHideEvent* e) {
+ QWidget::hideEvent(e);
+ if (skeleton_timer_)
+ skeleton_timer_->stop();
+}
+
void ForumFeedPanel::clear_active() {
active_uuid_.clear();
}
@@ -505,10 +520,12 @@ void ForumFeedPanel::rebuild_posts() {
posts_vl_->addWidget(grid);
- // ── Load more button ──────────────────────────────────────────────────────
+ // ── Next-page button ──────────────────────────────────────────────────────
+ // This is pagination, not infinite scroll: load_more_requested() re-fetches
+ // and REPLACES the feed with the next page. The old "Load N more posts"
+ // label promised appending and reported a bogus N (total minus one page).
if (page_.page < page_.pages) {
- int remaining = page_.total - page_.posts.size();
- auto* more = new QPushButton(tr("Load %1 more posts").arg(remaining));
+ auto* more = new QPushButton(tr("Next page (%1 of %2)").arg(page_.page + 1).arg(page_.pages));
more->setFixedHeight(36);
more->setCursor(Qt::PointingHandCursor);
more->setStyleSheet(QString("QPushButton{background:%1;color:%2;"
diff --git a/fincept-qt/src/screens/forum/ForumFeedPanel.h b/fincept-qt/src/screens/forum/ForumFeedPanel.h
index 106979b37..6da44590d 100644
--- a/fincept-qt/src/screens/forum/ForumFeedPanel.h
+++ b/fincept-qt/src/screens/forum/ForumFeedPanel.h
@@ -4,9 +4,11 @@
#include <QEvent>
#include <QHBoxLayout>
+#include <QHideEvent>
#include <QLabel>
#include <QPushButton>
#include <QScrollArea>
+#include <QShowEvent>
#include <QTimer>
#include <QVBoxLayout>
#include <QWidget>
@@ -39,6 +41,8 @@ class ForumFeedPanel : public QWidget {
protected:
void changeEvent(QEvent* event) override;
+ void showEvent(QShowEvent* event) override;
+ void hideEvent(QHideEvent* event) override;
private:
void build_ui();
diff --git a/fincept-qt/src/screens/forum/ForumScreen.cpp b/fincept-qt/src/screens/forum/ForumScreen.cpp
index 682ab4ffa..a796f97c5 100644
--- a/fincept-qt/src/screens/forum/ForumScreen.cpp
+++ b/fincept-qt/src/screens/forum/ForumScreen.cpp
@@ -88,33 +88,41 @@ void ForumScreen::build_ui() {
connect(feed_, &ForumFeedPanel::category_clicked, this, &ForumScreen::on_category_selected);
+ // NOTE on lambda captures below: ForumService callbacks are plain
+ // std::functions with no QObject context, so they are NOT auto-disconnected
+ // when this screen is destroyed. Every one of them must hold a QPointer
+ // guard, or a reply that lands after the screen closes dereferences a dead
+ // `this`. (Several of these previously captured a raw [this].)
connect(feed_, &ForumFeedPanel::load_more_requested, this, [this](int page) {
- if (active_category_id_ > 0) {
- feed_->set_loading(true);
- services::ForumService::instance().fetch_posts(active_category_id_, page, "latest",
- [this](bool ok, services::ForumPostsPage p) {
- if (ok)
- feed_->set_posts(p, active_category_color_);
- else
- feed_->set_loading(false);
- });
- }
+ if (active_category_id_ <= 0)
+ return;
+ feed_->set_loading(true);
+ QPointer<ForumScreen> self = this;
+ services::ForumService::instance().fetch_posts(active_category_id_, page, "latest",
+ [self](bool ok, services::ForumPostsPage p) {
+ if (!self)
+ return;
+ if (ok)
+ self->feed_->set_posts(p, self->active_category_color_);
+ else
+ self->feed_->set_loading(false);
+ });
});
connect(feed_, &ForumFeedPanel::new_post_clicked, this, [this]() { on_new_post_requested(); });
connect(feed_, &ForumFeedPanel::vote_post_requested, this, [this](const QString& uuid, const QString& vtype) {
- LOG_INFO("ForumScreen", "Feed vote: " + uuid + " type=" + vtype);
- services::ForumService::instance().vote_post(uuid, vtype, [this](bool ok, const QString&) {
- LOG_INFO("ForumScreen", QString("Feed vote result: ok=%1").arg(ok));
- if (ok && active_category_id_ > 0) {
- // Refresh current feed to show updated vote
- services::ForumService::instance().fetch_posts(active_category_id_, 1, "latest",
- [this](bool ok2, services::ForumPostsPage p) {
- if (ok2)
- feed_->set_posts(p, active_category_color_);
- });
- }
+ QPointer<ForumScreen> self = this;
+ services::ForumService::instance().vote_post(uuid, vtype, [self](bool ok, const QString&) {
+ if (!self || !ok || self->active_category_id_ <= 0)
+ return;
+ // Refresh current feed to show updated vote
+ services::ForumService::instance().fetch_posts(self->active_category_id_, 1, "latest",
+ [self](bool ok2, services::ForumPostsPage p) {
+ if (self && ok2)
+ self->feed_->set_posts(p,
+ self->active_category_color_);
+ });
});
});
@@ -147,36 +155,43 @@ void ForumScreen::build_ui() {
});
connect(thread_, &ForumThreadPanel::vote_post, this, [this](const QString& uuid, const QString& vtype) {
- LOG_INFO("ForumScreen", "Vote post: " + uuid + " type=" + vtype);
- services::ForumService::instance().vote_post(uuid, vtype, [this, uuid](bool ok, const QString& msg) {
- LOG_INFO("ForumScreen", QString("Vote result: ok=%1 msg=%2").arg(ok).arg(msg));
- if (ok) {
- services::ForumService::instance().fetch_post(uuid, [this](bool ok2, services::ForumPostDetail d) {
- if (ok2)
- thread_->show_post(d);
- });
+ QPointer<ForumScreen> self = this;
+ services::ForumService::instance().vote_post(uuid, vtype, [self, uuid](bool ok, const QString& msg) {
+ if (!self)
+ return;
+ if (!ok) {
+ LOG_WARN("ForumScreen", "Vote failed: " + msg);
+ return;
}
+ services::ForumService::instance().fetch_post(uuid, [self](bool ok2, services::ForumPostDetail d) {
+ if (self && ok2)
+ self->thread_->show_post(d);
+ });
});
});
connect(thread_, &ForumThreadPanel::vote_comment, this, [this](const QString& uuid, const QString& vtype) {
- services::ForumService::instance().vote_comment(uuid, vtype, [this](bool, const QString&) {
- if (!current_detail_uuid_.isEmpty()) {
- services::ForumService::instance().fetch_post(current_detail_uuid_,
- [this](bool ok, services::ForumPostDetail d) {
- if (ok)
- thread_->show_post(d);
- });
- }
+ QPointer<ForumScreen> self = this;
+ services::ForumService::instance().vote_comment(uuid, vtype, [self](bool, const QString&) {
+ if (!self || self->current_detail_uuid_.isEmpty())
+ return;
+ services::ForumService::instance().fetch_post(self->current_detail_uuid_,
+ [self](bool ok, services::ForumPostDetail d) {
+ if (self && ok)
+ self->thread_->show_post(d);
+ });
});
});
connect(thread_, &ForumThreadPanel::author_clicked, this, [this](const QString& username) {
- services::ForumService::instance().fetch_profile(username, [this](bool ok, services::ForumProfile profile) {
- if (!ok)
+ QPointer<ForumScreen> outer = this;
+ services::ForumService::instance().fetch_profile(username, [outer](bool ok, services::ForumProfile profile) {
+ if (!ok || !outer)
return;
- // Profile popup
- auto* dlg = new QDialog(this);
+ ForumScreen* self = outer.data();
+ // Profile popup. Freed after exec() returns — the previous version
+ // leaked one QDialog per profile view for the screen's lifetime.
+ auto* dlg = new QDialog(self);
dlg->setWindowTitle(tr("USER PROFILE"));
dlg->setFixedSize(380, 340);
dlg->setStyleSheet(QString("QDialog{background:%1;border:1px solid %2;}"
@@ -188,7 +203,7 @@ void ForumScreen::build_ui() {
vl->setSpacing(10);
// Profile header with gradient accent
- auto* hdr = new QWidget(this);
+ auto* hdr = new QWidget(self);
hdr->setFixedHeight(4);
QString avc = profile.avatar_color.isEmpty() ? ui::colors::AMBER() : profile.avatar_color;
hdr->setStyleSheet(QString("background:qlineargradient(x1:0,y1:0,x2:1,y2:0,"
@@ -197,7 +212,7 @@ void ForumScreen::build_ui() {
vl->addWidget(hdr);
// Avatar + name
- auto* top = new QWidget(this);
+ auto* top = new QWidget(self);
top->setStyleSheet("background:transparent;");
auto* th = new QHBoxLayout(top);
th->setContentsMargins(0, 0, 0, 0);
@@ -236,14 +251,14 @@ void ForumScreen::build_ui() {
vl->addWidget(sep);
// Stats grid
- auto* grid = new QWidget(this);
+ auto* grid = new QWidget(self);
grid->setStyleSheet("background:transparent;");
auto* gh = new QHBoxLayout(grid);
gh->setContentsMargins(0, 0, 0, 0);
gh->setSpacing(0);
auto mk_stat = [&](const QString& val, const QString& lbl, const QString& col) {
- auto* cell = new QWidget(this);
+ auto* cell = new QWidget(self);
cell->setStyleSheet("background:transparent;");
auto* cv = new QVBoxLayout(cell);
cv->setContentsMargins(0, 8, 0, 8);
@@ -279,9 +294,10 @@ void ForumScreen::build_ui() {
"border-color:rgba(217,119,6,0.5);"
"background:rgba(217,119,6,0.15);}")
.arg(ui::colors::TEXT_TERTIARY(), ui::colors::BORDER_DIM(), M(11), ui::colors::AMBER()));
- connect(edit_btn, &QPushButton::clicked, this, [this, dlg, profile]() {
+ QObject::connect(edit_btn, &QPushButton::clicked, self, [outer, dlg, profile]() {
dlg->accept();
- show_edit_profile_dialog(profile);
+ if (outer)
+ outer->show_edit_profile_dialog(profile);
});
vl->addStretch();
vl->addWidget(edit_btn);
@@ -289,6 +305,7 @@ void ForumScreen::build_ui() {
vl->addStretch();
}
dlg->exec();
+ dlg->deleteLater(); // exec() returns on accept/reject; free the dialog
});
});
}
@@ -311,28 +328,38 @@ void ForumScreen::load_initial_data() {
feed_->set_loading(true);
// Stats
- services::ForumService::instance().fetch_stats([this](bool ok, services::ForumStats s) {
- if (!ok)
+ QPointer<ForumScreen> self1 = this;
+ services::ForumService::instance().fetch_stats([self1](bool ok, services::ForumStats s) {
+ if (!ok || !self1)
return;
- sidebar_->set_stats(s);
- feed_->set_stats(s);
+ self1->sidebar_->set_stats(s);
+ self1->feed_->set_stats(s);
});
// My profile
- services::ForumService::instance().fetch_my_profile([this](bool ok, services::ForumProfile p) {
- if (!ok)
+ QPointer<ForumScreen> self2 = this;
+ services::ForumService::instance().fetch_my_profile([self2](bool ok, services::ForumProfile p) {
+ if (!ok || !self2)
return;
- sidebar_->set_my_profile(p);
- feed_->set_profile(p);
+ self2->sidebar_->set_my_profile(p);
+ self2->feed_->set_profile(p);
});
// Categories
+ QPointer<ForumScreen> self3 = this;
services::ForumService::instance().fetch_categories(
- [this](bool ok, QVector<services::ForumCategory> cats, services::ForumPermissions) {
- if (!ok || cats.isEmpty())
+ [self3](bool ok, QVector<services::ForumCategory> cats, services::ForumPermissions) {
+ if (!self3)
+ return;
+ if (!ok || cats.isEmpty()) {
+ // The feed sat on an animated skeleton forever when the forum
+ // API was unreachable. Stop it and show the empty state.
+ self3->feed_->set_loading(false);
+ self3->feed_->set_posts({}, ui::colors::TEXT_TERTIARY());
return;
- categories_ = cats;
- sidebar_->set_categories(cats);
+ }
+ self3->categories_ = cats;
+ self3->sidebar_->set_categories(cats);
// Auto-select first category with posts
int sel_idx = 0;
@@ -343,19 +370,21 @@ void ForumScreen::load_initial_data() {
}
}
const auto& first = cats[sel_idx];
- active_category_id_ = first.id;
- active_category_name_ = first.name;
- active_category_color_ = first.color;
- sidebar_->set_active_category(first.id);
- feed_->set_header(first.name);
- feed_->set_categories(cats, first.id);
+ self3->active_category_id_ = first.id;
+ self3->active_category_name_ = first.name;
+ self3->active_category_color_ = first.color;
+ self3->sidebar_->set_active_category(first.id);
+ self3->feed_->set_header(first.name);
+ self3->feed_->set_categories(cats, first.id);
services::ForumService::instance().fetch_posts(first.id, 1, "latest",
- [this, first](bool ok2, services::ForumPostsPage p) {
+ [self3, first](bool ok2, services::ForumPostsPage p) {
+ if (!self3)
+ return;
if (ok2)
- feed_->set_posts(p, first.color);
+ self3->feed_->set_posts(p, first.color);
else
- feed_->set_loading(false);
+ self3->feed_->set_loading(false);
});
});
}
@@ -380,11 +409,14 @@ void ForumScreen::on_category_selected(int id, const QString& name, const QStrin
sidebar_->set_active_category(id);
main_stack_->setCurrentIndex(0);
- services::ForumService::instance().fetch_posts(id, 1, "latest", [this, color](bool ok, services::ForumPostsPage p) {
+ QPointer<ForumScreen> self = this;
+ services::ForumService::instance().fetch_posts(id, 1, "latest", [self, color](bool ok, services::ForumPostsPage p) {
+ if (!self)
+ return;
if (ok)
- feed_->set_posts(p, color);
+ self->feed_->set_posts(p, color);
else
- feed_->set_loading(false);
+ self->feed_->set_loading(false);
});
}
@@ -395,11 +427,14 @@ void ForumScreen::on_post_selected(const services::ForumPost& post) {
thread_->set_loading(true);
main_stack_->setCurrentIndex(1);
- services::ForumService::instance().fetch_post(post.post_uuid, [this](bool ok, services::ForumPostDetail d) {
+ QPointer<ForumScreen> self = this;
+ services::ForumService::instance().fetch_post(post.post_uuid, [self](bool ok, services::ForumPostDetail d) {
+ if (!self)
+ return;
if (ok)
- thread_->show_post(d);
+ self->thread_->show_post(d);
else
- thread_->set_loading(false);
+ self->thread_->set_loading(false);
});
}
@@ -413,11 +448,14 @@ void ForumScreen::on_search(const QString& query) {
feed_->clear_active();
main_stack_->setCurrentIndex(0);
- services::ForumService::instance().search(query, 1, [this](bool ok, services::ForumPostsPage p) {
+ QPointer<ForumScreen> self = this;
+ services::ForumService::instance().search(query, 1, [self](bool ok, services::ForumPostsPage p) {
+ if (!self)
+ return;
if (ok)
- feed_->set_posts(p, ui::colors::CYAN());
+ self->feed_->set_posts(p, ui::colors::CYAN());
else
- feed_->set_loading(false);
+ self->feed_->set_loading(false);
});
}
@@ -429,11 +467,14 @@ void ForumScreen::on_trending() {
feed_->clear_active();
main_stack_->setCurrentIndex(0);
- services::ForumService::instance().fetch_trending([this](bool ok, services::ForumPostsPage p) {
+ QPointer<ForumScreen> self = this;
+ services::ForumService::instance().fetch_trending([self](bool ok, services::ForumPostsPage p) {
+ if (!self)
+ return;
if (ok)
- feed_->set_posts(p, ui::colors::AMBER());
+ self->feed_->set_posts(p, ui::colors::AMBER());
else
- feed_->set_loading(false);
+ self->feed_->set_loading(false);
});
}
@@ -528,8 +569,17 @@ void ForumScreen::show_new_post_dialog(int category_id) {
connect(submit, &QPushButton::clicked, this, [this, dlg, title_edit, body_edit, submit, category_id]() {
QString title = title_edit->text().trimmed();
QString content = body_edit->toPlainText().trimmed();
- if (title.isEmpty() || content.isEmpty())
+ // Silently doing nothing made PUBLISH look broken; say what's missing.
+ if (title.isEmpty()) {
+ QMessageBox::information(dlg, tr("Title required"), tr("Give your post a title."));
+ title_edit->setFocus();
+ return;
+ }
+ if (content.isEmpty()) {
+ QMessageBox::information(dlg, tr("Content required"), tr("Write something in the body of your post."));
+ body_edit->setFocus();
return;
+ }
// Keep the dialog (and the user's typed post) open until the async call
// returns. Only close on success; on failure re-enable Publish and show
// the error so the text isn't lost. The old code accept()ed (discarding
@@ -565,7 +615,16 @@ void ForumScreen::show_new_post_dialog(int category_id) {
btn_hl->addWidget(cancel);
btn_hl->addWidget(submit);
vl->addWidget(btn_row);
+
+ title_edit->setAccessibleName(tr("Post title"));
+ body_edit->setAccessibleName(tr("Post content"));
+ dlg->setTabOrder(title_edit, body_edit);
+ dlg->setTabOrder(body_edit, submit);
+ dlg->setTabOrder(submit, cancel);
+ title_edit->setFocus();
+
dlg->exec();
+ dlg->deleteLater(); // otherwise one QDialog leaks per new-post attempt
}
void ForumScreen::show_edit_profile_dialog(const services::ForumProfile& profile) {
@@ -642,16 +701,26 @@ void ForumScreen::show_edit_profile_dialog(const services::ForumProfile& profile
.arg(ui::colors::TEXT_SECONDARY(), M(11), ui::colors::AMBER()));
connect(sc, &QPushButton::clicked, this, [this, dlg, name_e, bio_e, sig_e, col_e]() {
dlg->accept();
+ QPointer<ForumScreen> self = this;
services::ForumService::instance().update_profile(
name_e->text().trimmed(), bio_e->text().trimmed(), sig_e->text().trimmed(), col_e->text().trimmed(),
- [this](bool ok, const QString&) {
- if (ok) {
- services::ForumService::instance().fetch_my_profile([this](bool ok2, services::ForumProfile p) {
- if (!ok2)
- return;
- sidebar_->set_my_profile(p);
- });
+ [self](bool ok, const QString& msg) {
+ if (!self)
+ return;
+ if (!ok) {
+ // Previously the failure path was completely silent — the
+ // dialog closed and the user assumed the edit had saved.
+ QMessageBox::warning(self, ForumScreen::tr("Profile not saved"),
+ msg.isEmpty() ? ForumScreen::tr("Your profile changes could not be saved.")
+ : ForumScreen::tr("Your profile changes could not be "
+ "saved:\n%1")
+ .arg(msg));
+ return;
}
+ services::ForumService::instance().fetch_my_profile([self](bool ok2, services::ForumProfile p) {
+ if (self && ok2)
+ self->sidebar_->set_my_profile(p);
+ });
});
});
@@ -661,6 +730,7 @@ void ForumScreen::show_edit_profile_dialog(const services::ForumProfile& profile
vl->addStretch();
vl->addWidget(btn_row);
dlg->exec();
+ dlg->deleteLater(); // otherwise one QDialog leaks per profile edit
}
// ── IStatefulScreen ───────────────────────────────────────────────────────────
diff --git a/fincept-qt/src/screens/forum/ForumSidebarPanel.cpp b/fincept-qt/src/screens/forum/ForumSidebarPanel.cpp
index 28ef1dbea..8ddffed40 100644
--- a/fincept-qt/src/screens/forum/ForumSidebarPanel.cpp
+++ b/fincept-qt/src/screens/forum/ForumSidebarPanel.cpp
@@ -143,6 +143,8 @@ void ForumSidebarPanel::build_ui() {
ui::colors::BORDER_BRIGHT(), ui::colors::TEXT_PRIMARY(),
ui::colors::TEXT_DIM()));
+ search_input_->setClearButtonEnabled(true);
+ search_input_->setAccessibleName(tr("Search discussions"));
connect(search_input_, &QLineEdit::returnPressed, this,
[this]() { emit search_requested(search_input_->text().trimmed()); });
@@ -350,7 +352,21 @@ void ForumSidebarPanel::set_active_category(int id) {
}
void ForumSidebarPanel::set_loading(bool on) {
- Q_UNUSED(on)
+ // The sidebar has no spinner of its own; the only thing that reads as
+ // "loading" here is the leaderboard placeholder. Previously this was an
+ // empty body, so the call site had no effect at all.
+ if (!on || !contrib_layout_ || !contributors_.isEmpty())
+ return;
+ while (contrib_layout_->count() > 0) {
+ auto* item = contrib_layout_->takeAt(0);
+ if (item->widget())
+ item->widget()->deleteLater();
+ delete item;
+ }
+ auto* ph = new QLabel(tr(" loading…"));
+ ph->setFixedHeight(28);
+ ph->setStyleSheet(QString("color:%1;font-size:10px;background:transparent;%2").arg(ui::colors::TEXT_DIM(), M(10)));
+ contrib_layout_->addWidget(ph);
}
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
diff --git a/fincept-qt/src/screens/forum/ForumThreadPanel.cpp b/fincept-qt/src/screens/forum/ForumThreadPanel.cpp
index 4c5b4d188..23658f851 100644
--- a/fincept-qt/src/screens/forum/ForumThreadPanel.cpp
+++ b/fincept-qt/src/screens/forum/ForumThreadPanel.cpp
@@ -196,7 +196,9 @@ void ForumThreadPanel::build_ui() {
t_author_lbl_->setStyleSheet(
QString("color:%1;font-size:12px;background:transparent;%2").arg(ui::colors::TEXT_TERTIARY(), M(12)));
connect(t_author_lbl_, &QLabel::linkActivated, this, [this](const QString& link) {
- if (link.startsWith("author:"))
+ // Only ever act on our own scheme — never hand an arbitrary href from
+ // forum content to the shell.
+ if (link.startsWith(QLatin1String("author:")))
emit author_clicked(link.mid(7));
});
hdr_vl->addWidget(t_author_lbl_);
@@ -459,7 +461,10 @@ void ForumThreadPanel::show_post(const services::ForumPostDetail& detail) {
t_meta_lbl_->setText(rel_time(detail.post.created_at));
t_title_lbl_->setText(detail.post.title);
- // Author with circular avatar
+ // Author with circular avatar.
+ // The label is RichText, so every interpolated value must be escaped —
+ // a display name containing '<' or a quote previously broke the markup
+ // (and let arbitrary forum-supplied HTML into the view).
QString avc = det_color(detail.post.author_display_name);
QString ini = detail.post.author_display_name.isEmpty() ? "?" : detail.post.author_display_name.left(2).toUpper();
t_author_lbl_->setText(QString("<span style='background:%1;color:%2;font-size:10px;"
@@ -468,8 +473,9 @@ void ForumThreadPanel::show_post(const services::ForumPostDetail& detail) {
"&nbsp;&nbsp;"
"<a href='author:%4' style='color:%5;text-decoration:none;"
"font-family:Consolas;font-size:12px;font-weight:600;'>%6</a>")
- .arg(avc, ui::colors::BG_BASE(), ini, detail.post.author_name,
- ui::colors::TEXT_SECONDARY(), detail.post.author_display_name));
+ .arg(avc, ui::colors::BG_BASE(), ini.toHtmlEscaped(),
+ QString(detail.post.author_name).toHtmlEscaped(), ui::colors::TEXT_SECONDARY(),
+ detail.post.author_display_name.toHtmlEscaped()));
t_body_lbl_->setText(detail.post.content);
diff --git a/fincept-qt/src/screens/geopolitics/ConflictMonitorPanel.cpp b/fincept-qt/src/screens/geopolitics/ConflictMonitorPanel.cpp
index 01e0efa95..76ea31308 100644
--- a/fincept-qt/src/screens/geopolitics/ConflictMonitorPanel.cpp
+++ b/fincept-qt/src/screens/geopolitics/ConflictMonitorPanel.cpp
@@ -10,7 +10,6 @@
#include <QGridLayout>
#include <QHBoxLayout>
#include <QHeaderView>
-#include <QRandomGenerator>
#include <QScrollArea>
#include <QSet>
#include <QSplitter>
@@ -146,6 +145,21 @@ void ConflictMonitorPanel::build_ui() {
events_table_->setColumnHidden(5, true);
events_table_->setColumnHidden(6, true);
events_table_->verticalHeader()->setDefaultSectionSize(26);
+ events_table_->setAccessibleName(tr("Conflict events"));
+ events_table_->setAccessibleDescription(
+ tr("Geopolitical events from the news-events API. Arrow keys move between events; the detail panel and the "
+ "map selection follow the highlighted row."));
+ // Enter/double-click on a row opens the underlying source article, matching
+ // the OPEN SOURCE button in the detail panel.
+ connect(events_table_, &QTableWidget::cellActivated, this, [this](int row, int) {
+ if (row < 0)
+ return;
+ if (auto* it = events_table_->item(row, 3)) {
+ const QString url = it->data(Qt::UserRole + 1).toString();
+ if (!url.isEmpty())
+ QDesktopServices::openUrl(QUrl(url));
+ }
+ });
events_table_->setStyleSheet(
QString("QTableWidget { background:%1; color:%2; gridline-color:%3;"
diff --git a/fincept-qt/src/screens/geopolitics/GeopoliticsScreen.cpp b/fincept-qt/src/screens/geopolitics/GeopoliticsScreen.cpp
index 8cc37a7f1..322d5e023 100644
--- a/fincept-qt/src/screens/geopolitics/GeopoliticsScreen.cpp
+++ b/fincept-qt/src/screens/geopolitics/GeopoliticsScreen.cpp
@@ -272,6 +272,8 @@ QWidget* GeopoliticsScreen::build_filter_panel() {
country_edit_ = new QLineEdit(panel);
country_edit_->setPlaceholderText(tr("e.g. Ukraine"));
country_edit_->setStyleSheet(input_style);
+ country_edit_->setAccessibleName(tr("Filter by country"));
+ country_edit_->setClearButtonEnabled(true);
connect(country_edit_, &QLineEdit::returnPressed, this, &GeopoliticsScreen::on_apply_filters);
vl->addWidget(country_edit_);
@@ -281,6 +283,8 @@ QWidget* GeopoliticsScreen::build_filter_panel() {
city_edit_ = new QLineEdit(panel);
city_edit_->setPlaceholderText(tr("e.g. Kyiv"));
city_edit_->setStyleSheet(input_style);
+ city_edit_->setAccessibleName(tr("Filter by city"));
+ city_edit_->setClearButtonEnabled(true);
connect(city_edit_, &QLineEdit::returnPressed, this, &GeopoliticsScreen::on_apply_filters);
vl->addWidget(city_edit_);
@@ -289,11 +293,16 @@ QWidget* GeopoliticsScreen::build_filter_panel() {
vl->addWidget(category_lbl_);
category_combo_ = new QComboBox(panel);
category_combo_->setStyleSheet(input_style);
+ category_combo_->setAccessibleName(tr("Filter by event category"));
// Populated from API once categories_loaded fires — start with a single
// "All" entry so the combo renders before the network round-trip.
category_combo_->addItem(tr("All Categories"), "");
vl->addWidget(category_combo_);
+ // Keyboard order across the filter column.
+ QWidget::setTabOrder(country_edit_, city_edit_);
+ QWidget::setTabOrder(city_edit_, category_combo_);
+
vl->addSpacing(4);
apply_btn_ = new QPushButton(tr("APPLY FILTERS"), panel);
@@ -528,6 +537,7 @@ void GeopoliticsScreen::on_events_loaded(services::geo::EventsPage page) {
}
status_label_->setText(tr("READY"));
+ status_label_->setToolTip(QString()); // clear any stale error detail
status_label_->setStyleSheet(QString("color:%1; font-size:%2px; font-weight:700; font-family:%3;")
.arg(ui::colors::POSITIVE())
.arg(ui::fonts::TINY)
@@ -615,7 +625,12 @@ void GeopoliticsScreen::rebuild_legend(const QVector<services::geo::UniqueCatego
}
void GeopoliticsScreen::on_error(const QString& context, const QString& message) {
- status_label_->setText(tr("ERROR"));
+ // "ERROR" alone told the user nothing and left the real cause in a log
+ // file they can't see. Surface a short reason inline, the full text on
+ // hover, and point at the retry that actually exists (APPLY FILTERS).
+ const QString brief = message.simplified().left(72);
+ status_label_->setText(brief.isEmpty() ? tr("ERROR") : tr("ERROR: %1").arg(brief));
+ status_label_->setToolTip(tr("%1\n\n%2\n\nClick APPLY FILTERS to retry.").arg(context, message));
status_label_->setStyleSheet(QString("color:%1; font-size:%2px; font-weight:700; font-family:%3;")
.arg(ui::colors::NEGATIVE())
.arg(ui::fonts::TINY)
diff --git a/fincept-qt/src/screens/geopolitics/HDXDataPanel.cpp b/fincept-qt/src/screens/geopolitics/HDXDataPanel.cpp
index 71f05d79d..eafee7f60 100644
--- a/fincept-qt/src/screens/geopolitics/HDXDataPanel.cpp
+++ b/fincept-qt/src/screens/geopolitics/HDXDataPanel.cpp
@@ -4,9 +4,11 @@
#include "services/geopolitics/GeopoliticsService.h"
#include "ui/theme/Theme.h"
+#include <QDesktopServices>
#include <QHBoxLayout>
#include <QHeaderView>
#include <QScrollArea>
+#include <QUrl>
namespace fincept::screens {
@@ -32,16 +34,28 @@ void HDXDataPanel::connect_service() {
}
void HDXDataPanel::on_error(const QString& context, const QString& message) {
- Q_UNUSED(context);
+ // GeopoliticsService::error_occurred is a shared channel — an events or
+ // categories failure used to blank this table and replace it with an "HDX
+ // failed" message that had nothing to do with HDX. Only react to our own
+ // contexts.
+ static const QStringList kHdxContexts = {QStringLiteral("conflicts"), QStringLiteral("humanitarian"),
+ QStringLiteral("search"), QStringLiteral("topic"),
+ QStringLiteral("country")};
+ if (!kHdxContexts.contains(context) && !context.startsWith(QStringLiteral("hdx")))
+ return;
+
// Stop the perpetual spinner and surface the failure in its place.
if (datasets_table_)
datasets_table_->setRowCount(0);
if (dataset_count_)
dataset_count_->setText(QStringLiteral("0"));
if (loading_label_) {
- loading_label_->setText(tr("Failed to load HDX data:\n%1").arg(message));
+ loading_label_->setText(tr("Failed to load HDX data (%1):\n%2\n\nAdjust the query and search again.")
+ .arg(context, message));
loading_label_->show();
}
+ if (datasets_table_)
+ datasets_table_->setVisible(false);
}
void HDXDataPanel::build_ui() {
@@ -158,6 +172,22 @@ void HDXDataPanel::build_ui() {
.arg(ui::colors::TEXT_SECONDARY())
.arg(ui::colors::ROW_ALT()));
+ datasets_table_->setAccessibleName(tr("HDX datasets"));
+ datasets_table_->setAccessibleDescription(
+ tr("Humanitarian Data Exchange datasets. Press Enter on a row to open it on data.humdata.org."));
+ // Open the dataset's HDX page. Every CKAN dataset is addressable by its
+ // name/id, so a row is actionable rather than a dead end.
+ connect(datasets_table_, &QTableWidget::cellActivated, this, [this](int row, int) {
+ if (row < 0)
+ return;
+ auto* it = datasets_table_->item(row, 0);
+ if (!it)
+ return;
+ const QString url = it->data(Qt::UserRole).toString();
+ if (!url.isEmpty())
+ QDesktopServices::openUrl(QUrl(url));
+ });
+
// Loading overlay
loading_label_ = new QLabel(tr("Loading HDX data..."), this);
loading_label_->setAlignment(Qt::AlignCenter);
@@ -241,6 +271,26 @@ void HDXDataPanel::build_ui() {
ehl->addStretch();
root->addWidget(explorer_bar_);
+
+ // Source + licence attribution. HDX redistribution terms require the
+ // source and the per-dataset licence to travel with the data; the panel
+ // previously showed dataset rows with neither.
+ attribution_lbl_ = new QLabel(this);
+ attribution_lbl_->setTextFormat(Qt::RichText);
+ attribution_lbl_->setOpenExternalLinks(true);
+ attribution_lbl_->setWordWrap(true);
+ attribution_lbl_->setText(tr("Source: <a href=\"https://data.humdata.org\">Humanitarian Data Exchange (HDX)</a>, "
+ "OCHA. Each dataset carries its own licence and attribution — open the dataset page "
+ "before redistributing or citing it."));
+ attribution_lbl_->setStyleSheet(QString("color:%1; font-size:%2px; font-family:%3; padding:4px 16px;"
+ "background:%4; border-top:1px solid %5;")
+ .arg(ui::colors::TEXT_TERTIARY())
+ .arg(ui::fonts::TINY)
+ .arg(ui::fonts::DATA_FAMILY())
+ .arg(ui::colors::BG_SURFACE())
+ .arg(ui::colors::BORDER_DIM()));
+ root->addWidget(attribution_lbl_);
+
on_view_changed(0);
}
@@ -335,9 +385,28 @@ void HDXDataPanel::populate_table(const QVector<HDXDataset>& datasets) {
for (int i = 0; i < datasets.size(); ++i) {
const auto& d = datasets[i];
auto* title_item = new QTableWidgetItem(d.title);
- title_item->setToolTip(d.notes);
+ // Per-dataset licence + link. HDX carries licence metadata on the CKAN
+ // record; surface whatever the payload has so the user can see the
+ // terms without leaving the terminal, and stash the dataset URL for
+ // the row-activation handler.
+ const QString licence = d.raw.value(QStringLiteral("license_title")).toString();
+ const QString name = d.raw.value(QStringLiteral("name")).toString();
+ const QString url = !name.isEmpty() ? QStringLiteral("https://data.humdata.org/dataset/") + name
+ : !d.id.isEmpty() ? QStringLiteral("https://data.humdata.org/dataset/") + d.id
+ : QString();
+ title_item->setData(Qt::UserRole, url);
+ QString tip = d.notes;
+ if (!licence.isEmpty())
+ tip += (tip.isEmpty() ? QString() : QStringLiteral("\n\n")) + tr("Licence: %1").arg(licence);
+ if (!url.isEmpty())
+ tip += (tip.isEmpty() ? QString() : QStringLiteral("\n")) + url;
+ title_item->setToolTip(tip);
datasets_table_->setItem(i, 0, title_item);
- datasets_table_->setItem(i, 1, new QTableWidgetItem(d.organization));
+
+ auto* org_item = new QTableWidgetItem(d.organization);
+ if (!licence.isEmpty())
+ org_item->setToolTip(tr("Licence: %1").arg(licence));
+ datasets_table_->setItem(i, 1, org_item);
datasets_table_->setItem(i, 2, new QTableWidgetItem(d.date));
auto* res_item = new QTableWidgetItem(QString::number(d.num_resources));
@@ -349,6 +418,13 @@ void HDXDataPanel::populate_table(const QVector<HDXDataset>& datasets) {
datasets_table_->setSortingEnabled(true);
dataset_count_->setText(tr("%1 datasets").arg(datasets.size()));
+
+ // Empty result is a state, not a silent blank grid.
+ if (datasets.isEmpty() && loading_label_) {
+ loading_label_->setText(tr("No HDX datasets matched this query.\nTry a broader term or a different country."));
+ loading_label_->show();
+ datasets_table_->setVisible(false);
+ }
}
void HDXDataPanel::changeEvent(QEvent* event) {
@@ -387,6 +463,12 @@ void HDXDataPanel::retranslateUi() {
datasets_table_->setHorizontalHeaderLabels(
{tr("Title"), tr("Organization"), tr("Date"), tr("Resources"), tr("Tags")});
+ if (attribution_lbl_)
+ attribution_lbl_->setText(
+ tr("Source: <a href=\"https://data.humdata.org\">Humanitarian Data Exchange (HDX)</a>, "
+ "OCHA. Each dataset carries its own licence and attribution — open the dataset page "
+ "before redistributing or citing it."));
+
// dataset_count_ reflects the last populate_table() and refreshes on next load.
}
diff --git a/fincept-qt/src/screens/geopolitics/HDXDataPanel.h b/fincept-qt/src/screens/geopolitics/HDXDataPanel.h
index 05967daad..82c82fb74 100644
--- a/fincept-qt/src/screens/geopolitics/HDXDataPanel.h
+++ b/fincept-qt/src/screens/geopolitics/HDXDataPanel.h
@@ -59,6 +59,8 @@ class HDXDataPanel : public QWidget {
QLabel* country_lbl_ = nullptr;
QLabel* topic_lbl_ = nullptr;
QPushButton* explore_btn_ = nullptr;
+ /// HDX source + licence attribution footer (required by HDX terms).
+ QLabel* attribution_lbl_ = nullptr;
// Fixed English view-tab labels, re-applied in retranslateUi (upper-cased).
QStringList view_labels_;
diff --git a/fincept-qt/src/screens/geopolitics/TradeAnalysisPanel.cpp b/fincept-qt/src/screens/geopolitics/TradeAnalysisPanel.cpp
index 8160486cf..c0fedfd84 100644
--- a/fincept-qt/src/screens/geopolitics/TradeAnalysisPanel.cpp
+++ b/fincept-qt/src/screens/geopolitics/TradeAnalysisPanel.cpp
@@ -58,6 +58,37 @@ static QString spin_style() {
.arg(ui::colors::WARNING());
}
+// ── Backend-routing honesty notice ───────────────────────────────────────────
+//
+// The "Trading Blocs" and "Barrier Removal" tabs collect their own parameters
+// but the service only exposes analyze_trade_benefits / analyze_trade_restrictions
+// today, so both are routed to the benefits/costs mode and their inputs are
+// dropped. That was documented only in a code comment; the user saw plausible
+// numbers that did not respond to what they typed. Say so on-screen.
+QString TradeAnalysisPanel::kBlocsNotice() {
+ return tr("Note: results come from the benefits/costs model. The dedicated trading-blocs mode is not exposed by "
+ "the service yet, so the integration type, trade-creation and trade-diversion inputs below are not sent "
+ "to the backend — read the output as a general welfare estimate, not a bloc-specific one.");
+}
+
+QString TradeAnalysisPanel::kBarrierNotice() {
+ return tr("Note: results come from the benefits/costs model. The dedicated barrier-removal mode is not exposed by "
+ "the service yet, so the liberalization scope, tariff-reduction and GDP inputs below are not sent to "
+ "the backend — read the output as a general welfare estimate, not a liberalization-specific one.");
+}
+
+QLabel* TradeAnalysisPanel::make_routing_notice(QWidget* parent) {
+ auto* lbl = new QLabel(parent);
+ lbl->setWordWrap(true);
+ lbl->setStyleSheet(QString("color:%1; font-size:%2px; font-family:%3; padding:6px 8px;"
+ "background:rgba(%4,0.10); border:1px solid %1;")
+ .arg(ui::colors::WARNING())
+ .arg(ui::fonts::TINY)
+ .arg(ui::fonts::DATA_FAMILY())
+ .arg(warn_rgb()));
+ return lbl;
+}
+
static QWidget* make_field(const QString& label_text, QWidget* input, QWidget* parent, const QString& hint = {}) {
auto* group = new QWidget(parent);
auto* vl = new QVBoxLayout(group);
@@ -317,6 +348,9 @@ void TradeAnalysisPanel::build_ui() {
{hint2, QStringLiteral(
"Analyzes trade creation vs. diversion effects for regional trade blocs and economic unions.")});
p2l->addWidget(hint2);
+ blocs_notice_ = make_routing_notice(p2);
+ blocs_notice_->setText(kBlocsNotice());
+ p2l->addWidget(blocs_notice_);
auto* bloc_combo = new QComboBox;
bloc_combo->setStyleSheet(combo_style());
@@ -387,6 +421,9 @@ void TradeAnalysisPanel::build_ui() {
i18n_labels_.append(
{hint3, QStringLiteral("Assesses FDI, employment, wage, and GDP impact of removing trade barriers.")});
p3l->addWidget(hint3);
+ barrier_notice_ = make_routing_notice(p3);
+ barrier_notice_->setText(kBarrierNotice());
+ p3l->addWidget(barrier_notice_);
auto* lib_combo = new QComboBox;
lib_combo->setStyleSheet(combo_style());
@@ -593,6 +630,12 @@ void TradeAnalysisPanel::retranslateUi() {
tabs_->setTabText(3, tr("Barrier Removal"));
}
+ // Backend-routing notices.
+ if (blocs_notice_)
+ blocs_notice_->setText(kBlocsNotice());
+ if (barrier_notice_)
+ barrier_notice_->setText(kBarrierNotice());
+
// Run buttons
for (auto* btn : run_buttons_)
if (btn)
diff --git a/fincept-qt/src/screens/geopolitics/TradeAnalysisPanel.h b/fincept-qt/src/screens/geopolitics/TradeAnalysisPanel.h
index 01d3394f2..943ebfdc3 100644
--- a/fincept-qt/src/screens/geopolitics/TradeAnalysisPanel.h
+++ b/fincept-qt/src/screens/geopolitics/TradeAnalysisPanel.h
@@ -35,6 +35,14 @@ class TradeAnalysisPanel : public QWidget {
void display_result(const QJsonObject& data);
void retranslateUi();
+ /// Amber "this tab's inputs are not sent to the backend" banner. The
+ /// Trading Blocs / Barrier Removal tabs both route to the benefits/costs
+ /// service mode, so their own parameters are dropped — say so on screen
+ /// rather than only in a code comment.
+ static QLabel* make_routing_notice(QWidget* parent);
+ static QString kBlocsNotice();
+ static QString kBarrierNotice();
+
QTabWidget* tabs_ = nullptr;
QVBoxLayout* results_layout_ = nullptr;
QWidget* results_container_ = nullptr;
@@ -43,6 +51,8 @@ class TradeAnalysisPanel : public QWidget {
// Static text widgets (cached for retranslateUi).
QLabel* title_lbl_ = nullptr;
QComboBox* type_combo_ = nullptr;
+ QLabel* blocs_notice_ = nullptr;
+ QLabel* barrier_notice_ = nullptr;
QList<QPushButton*> run_buttons_;
// Page-level hint labels paired with their English source string so
// retranslateUi can re-apply them. (Per-field captions built via make_field
diff --git a/fincept-qt/src/screens/gov_data/GovDataProviderPanel.cpp b/fincept-qt/src/screens/gov_data/GovDataProviderPanel.cpp
index 6c31b91b7..aadb803d5 100644
--- a/fincept-qt/src/screens/gov_data/GovDataProviderPanel.cpp
+++ b/fincept-qt/src/screens/gov_data/GovDataProviderPanel.cpp
@@ -67,6 +67,15 @@ QString make_gov_panel_style(const QString& color, const QString& extra_qss) {
.arg(t.text_secondary, t.border_dim);
s += QString("#govCsvBtn:hover { color:%1; background:%2; }").arg(t.text_primary, t.bg_hover);
+ // Per-row "OPEN" link button in the resources table. Hoisted here so
+ // populate_resources() only has to setObjectName() — the old code called
+ // setStyleSheet() once per row, forcing a full CSS reparse + repolish for
+ // every resource in a dataset.
+ s += QString("#govOpenBtn { color:%1; font-size:10px; font-weight:700;"
+ " background:transparent; border:none; padding:2px 6px; }"
+ "#govOpenBtn:hover { color:%1; text-decoration:underline; }")
+ .arg(color);
+
// Search
s += QString("#govSearch { background:%1; color:%2; border:none;"
" border-bottom:1px solid %3; padding:4px 10px; font-size:11px; }")
@@ -331,11 +340,14 @@ QWidget* GovDataProviderPanel::build_toolbar() {
search_input_->setObjectName("govSearch");
search_input_->setFixedWidth(210);
search_input_->setFixedHeight(24);
+ search_input_->setAccessibleName(tr("Search datasets"));
+ search_input_->setClearButtonEnabled(true);
connect(search_input_, &QLineEdit::returnPressed, this, &GovDataProviderPanel::on_search);
hl->addWidget(search_input_);
fetch_btn_ = new QPushButton;
fetch_btn_->setObjectName("govFetchBtn");
+ fetch_btn_->setAccessibleName(tr("Fetch"));
fetch_btn_->setCursor(Qt::PointingHandCursor);
connect(fetch_btn_, &QPushButton::clicked, this, [this]() {
if (!search_input_->text().trimmed().isEmpty())
@@ -349,10 +361,17 @@ QWidget* GovDataProviderPanel::build_toolbar() {
export_btn_ = new QPushButton;
export_btn_->setObjectName("govCsvBtn");
+ export_btn_->setAccessibleName(tr("Export current view as CSV"));
export_btn_->setCursor(Qt::PointingHandCursor);
connect(export_btn_, &QPushButton::clicked, this, &GovDataProviderPanel::on_export_csv);
hl->addWidget(export_btn_);
+ // Explicit keyboard traversal: tabs → search → FETCH → CSV.
+ QWidget::setTabOrder(orgs_btn_, datasets_btn_);
+ QWidget::setTabOrder(datasets_btn_, search_input_);
+ QWidget::setTabOrder(search_input_, fetch_btn_);
+ QWidget::setTabOrder(fetch_btn_, export_btn_);
+
return bar;
}
@@ -609,12 +628,11 @@ void GovDataProviderPanel::populate_resources(const QJsonArray& json) {
resources_table_->setItem(i, 4, no_url);
} else {
auto* open_btn = new QPushButton(tr("↗ OPEN"));
+ open_btn->setObjectName("govOpenBtn"); // styled once via make_gov_panel_style()
open_btn->setCursor(Qt::PointingHandCursor);
open_btn->setFlat(true);
- open_btn->setStyleSheet(QString("QPushButton { color:%1; font-size:10px; font-weight:700;"
- " background:transparent; border:none; padding:2px 6px; }"
- "QPushButton:hover { color:%1; text-decoration:underline; }")
- .arg(color_));
+ open_btn->setAccessibleName(tr("Open resource %1 in browser").arg(name));
+ open_btn->setToolTip(url);
connect(open_btn, &QPushButton::clicked, this, [url]() { QDesktopServices::openUrl(QUrl(url)); });
resources_table_->setCellWidget(i, 4, open_btn);
}
diff --git a/fincept-qt/src/screens/gov_data/GovDataScreen.cpp b/fincept-qt/src/screens/gov_data/GovDataScreen.cpp
index f060d5083..acdc0bfed 100644
--- a/fincept-qt/src/screens/gov_data/GovDataScreen.cpp
+++ b/fincept-qt/src/screens/gov_data/GovDataScreen.cpp
@@ -99,9 +99,12 @@ void GovDataScreen::showEvent(QShowEvent* event) {
QWidget::showEvent(event);
if (!initial_load_done_) {
initial_load_done_ = true;
+ // Honour a provider already chosen by restore_state(); the old code
+ // unconditionally forced row 0 and discarded the restored selection.
+ const int row = (active_index_ >= 0 && active_index_ < provider_list_->count()) ? active_index_ : 0;
if (provider_list_->count() > 0) {
- provider_list_->setCurrentRow(0);
- activate_provider(0);
+ provider_list_->setCurrentRow(row);
+ activate_provider(row);
}
}
LOG_INFO("GovDataScreen", "shown");
@@ -136,11 +139,28 @@ void GovDataScreen::build_ui() {
content_hl->addWidget(build_sidebar());
panel_stack_ = new QStackedWidget;
- const auto& providers = services::GovDataService::providers();
- for (int i = 0; i < providers.size(); ++i) {
- const auto& prov = providers[i];
- QWidget* panel = nullptr;
+ // P2 — panels are lazy-constructed on first activation (see make_panel()).
+ // Eagerly building all provider panels here created every sub-widget tree,
+ // stylesheet and QTimer for portals the user never opens. Stack index 0 is
+ // a blank placeholder shown before any provider has been selected.
+ panel_stack_->addWidget(new QWidget(panel_stack_));
+ panels_.resize(services::GovDataService::providers().size());
+ panels_.fill(nullptr);
+ content_hl->addWidget(panel_stack_, 1);
+ root->addWidget(content, 1);
+ root->addWidget(build_status_bar());
+}
+
+// ── Lazy panel factory ───────────────────────────────────────────────────────
+
+QWidget* GovDataScreen::make_panel(int index) {
+ const auto& providers = services::GovDataService::providers();
+ if (index < 0 || index >= providers.size())
+ return nullptr;
+ const auto& prov = providers[index];
+ QWidget* panel = nullptr;
+ {
if (prov.id == "us-treasury") {
panel = new GovDataTreasuryPanel(panel_stack_);
} else if (prov.id == "us-congress") {
@@ -167,12 +187,13 @@ void GovDataScreen::build_ui() {
// openafrica, spain — still use generic until dedicated scripts exist
panel = new GovDataProviderPanel(prov.script, prov.color, "Organizations", {}, panel_stack_);
}
+ }
+ if (panel) {
panel_stack_->addWidget(panel);
+ panels_[index] = panel;
+ LOG_INFO("GovDataScreen", "Created panel for: " + prov.id);
}
-
- content_hl->addWidget(panel_stack_, 1);
- root->addWidget(content, 1);
- root->addWidget(build_status_bar());
+ return panel;
}
// ── Toolbar ──────────────────────────────────────────────────────────────────
@@ -245,12 +266,16 @@ QWidget* GovDataScreen::build_sidebar() {
// Provider list
provider_list_ = new QListWidget;
provider_list_->setObjectName("govProviderList");
+ provider_list_->setAccessibleName(tr("Sovereign open-data portals"));
for (const auto& prov : providers) {
auto* item = new QListWidgetItem(provider_list_);
// Flag + name on first line, country on tooltip
item->setText(QString("%1 %2").arg(prov.flag, prov.name));
item->setToolTip(prov.description + "\n" + prov.country);
+ // Screen readers can't announce the flag emoji usefully — give the row
+ // a plain-text accessible label.
+ item->setData(Qt::AccessibleTextRole, QString("%1 — %2").arg(prov.name, prov.country));
item->setData(Qt::UserRole, prov.id);
item->setData(Qt::UserRole + 1, prov.color);
}
@@ -411,14 +436,29 @@ void GovDataScreen::activate_provider(int index) {
if (status_country_)
status_country_->setText(prov.country);
- // Switch panel
- panel_stack_->setCurrentIndex(index);
+ // Keep the sidebar highlight in step — restore_state()/programmatic
+ // activation used to switch the panel without moving the list selection.
+ if (provider_list_ && provider_list_->currentRow() != index) {
+ QSignalBlocker block(provider_list_);
+ provider_list_->setCurrentRow(index);
+ }
+
+ // Switch panel (lazy-constructing it on first use)
+ QWidget* panel = (index < panels_.size()) ? panels_[index] : nullptr;
+ const bool first_open = (panel == nullptr);
+ if (!panel)
+ panel = make_panel(index);
+ if (panel)
+ panel_stack_->setCurrentWidget(panel);
// Re-apply theme so provider-color accents on toolbar/badge reflect new selection
refresh_theme();
- // Trigger initial load — all panel types expose load_initial_data() as a public slot
- QMetaObject::invokeMethod(panel_stack_->currentWidget(), "load_initial_data");
+ // Trigger the initial load only the first time a panel is opened — all
+ // panel types expose load_initial_data() as a public slot. Re-invoking it
+ // on every revisit threw away whatever the user had drilled into.
+ if (panel && first_open)
+ QMetaObject::invokeMethod(panel, "load_initial_data");
LOG_INFO("GovDataScreen", "Activated: " + prov.id);
}
diff --git a/fincept-qt/src/screens/gov_data/GovDataScreen.h b/fincept-qt/src/screens/gov_data/GovDataScreen.h
index 6a8898d79..68bd69e37 100644
--- a/fincept-qt/src/screens/gov_data/GovDataScreen.h
+++ b/fincept-qt/src/screens/gov_data/GovDataScreen.h
@@ -8,7 +8,9 @@
#include <QLabel>
#include <QListWidget>
#include <QShowEvent>
+#include <QSignalBlocker>
#include <QStackedWidget>
+#include <QVector>
#include <QWidget>
namespace fincept::screens {
@@ -37,17 +39,21 @@ class GovDataScreen : public QWidget, public IStatefulScreen {
QWidget* build_sidebar();
QWidget* build_toolbar();
QWidget* build_status_bar();
+ /// Construct (and register in panel_stack_) the panel for provider `index`.
+ /// Called lazily on first activation — see P2 in CLAUDE.md.
+ QWidget* make_panel(int index);
void activate_provider(int index);
void retranslateUi();
QListWidget* provider_list_ = nullptr;
QStackedWidget* panel_stack_ = nullptr;
+ /// provider index → panel widget, nullptr until first activation.
+ QVector<QWidget*> panels_;
QLabel* header_title_ = nullptr;
QLabel* header_subtitle_ = nullptr;
QWidget* header_bar_ = nullptr;
QLabel* status_portal_ = nullptr;
QLabel* status_country_ = nullptr;
- QLabel* status_datasets_ = nullptr;
QLabel* provider_badge_ = nullptr;
QLabel* sidebar_count_ = nullptr;
QLabel* sidebar_title_ = nullptr;
diff --git a/fincept-qt/src/screens/info/ContactScreen.cpp b/fincept-qt/src/screens/info/ContactScreen.cpp
index 20b1f2f86..668287c16 100644
--- a/fincept-qt/src/screens/info/ContactScreen.cpp
+++ b/fincept-qt/src/screens/info/ContactScreen.cpp
@@ -136,13 +136,25 @@ QWidget* ContactScreen::build_page() {
grid->setContentsMargins(14, 12, 14, 12);
grid->setSpacing(10);
- // Brand/contact values (email, phone, company name) are shown verbatim — not translated.
- grid->addWidget(make_contact_card(tr("EMAIL SUPPORT"), "[email protected]", tr("Response within 4-6 hours")),
- 0, 0);
- grid->addWidget(make_contact_card(tr("PHONE SUPPORT"), "+1-800-FINCEPT", tr("Mon-Fri, 9AM-6PM EST")), 0, 1);
- grid->addWidget(make_contact_card(tr("SUPPORT HOURS"), tr("Mon-Fri 9AM-6PM EST"), tr("Saturday 10AM-4PM EST")),
+ // Brand/contact values (email, handles, company name) are shown verbatim
+ // — not translated.
+ //
+ // Only channels that actually exist are listed. The previous version
+ // advertised a "+1-800-FINCEPT" phone line, staffed weekend support
+ // hours, a "response within 4-6 hours" SLA and a New York office —
+ // none of which are documented anywhere in this project. Publishing
+ // unreachable contact details on a contact page is worse than
+ // publishing none.
+ grid->addWidget(
+ make_contact_card(tr("EMAIL SUPPORT"), "[email protected]", tr("Primary support channel")), 0, 0);
+ grid->addWidget(make_contact_card(tr("COMMUNITY"), "discord.gg/ae87a8ygbN", tr("Discussion and peer help")), 0,
+ 1);
+ grid->addWidget(make_contact_card(tr("ISSUE TRACKER"), "github.com/Fincept-Corporation/FinceptTerminal",
+ tr("Bug reports and feature requests")),
1, 0);
- grid->addWidget(make_contact_card(tr("OFFICE"), "Fincept Corporation", tr("New York, United States")), 1, 1);
+ grid->addWidget(make_contact_card(tr("IN-APP TICKETS"), tr("Support tab"),
+ tr("Open a tracked ticket from inside the terminal")),
+ 1, 1);
pvl->addWidget(body);
vl->addWidget(panel);
@@ -177,22 +189,27 @@ QWidget* ContactScreen::build_page() {
};
auto* email_btn = make_action(tr("Send Email"));
+ email_btn->setAccessibleName(tr("Send an email to support"));
connect(email_btn, &QPushButton::clicked, this,
[]() { QDesktopServices::openUrl(QUrl("mailto:[email protected]")); });
hl->addWidget(email_btn);
auto* discord_btn = make_action(tr("Join Discord"));
+ discord_btn->setAccessibleName(tr("Open the Fincept Discord server"));
connect(discord_btn, &QPushButton::clicked, this,
[]() { QDesktopServices::openUrl(QUrl("https://discord.gg/ae87a8ygbN")); });
hl->addWidget(discord_btn);
auto* github_btn = make_action(tr("GitHub Issues"));
+ github_btn->setAccessibleName(tr("Open the GitHub issue tracker"));
connect(github_btn, &QPushButton::clicked, this, []() {
QDesktopServices::openUrl(QUrl("https://github.com/Fincept-Corporation/FinceptTerminal/issues"));
});
hl->addWidget(github_btn);
hl->addStretch();
+ setTabOrder(email_btn, discord_btn);
+ setTabOrder(discord_btn, github_btn);
pvl->addWidget(body);
vl->addWidget(panel);
}
diff --git a/fincept-qt/src/screens/info/HelpScreen.cpp b/fincept-qt/src/screens/info/HelpScreen.cpp
index 711aa6c3d..9f3a45d34 100644
--- a/fincept-qt/src/screens/info/HelpScreen.cpp
+++ b/fincept-qt/src/screens/info/HelpScreen.cpp
@@ -27,9 +27,18 @@ static QWidget* make_faq(const QString& question, const QString& answer, const Q
vl->setContentsMargins(0, 0, 0, 0);
vl->setSpacing(0);
- auto* q_btn =
- new QPushButton(icon.isEmpty() ? QString(" %1").arg(question) : QString(" %1 %2").arg(icon, question));
+ // The disclosure arrow is part of the label: the previous version computed
+ // an arrow into a local and then Q_UNUSED'd it, so the button text never
+ // showed whether the answer was open or closed.
+ auto btn_text = [question, icon](bool open) {
+ const QString arrow = open ? QStringLiteral("▾") : QStringLiteral("▸");
+ return icon.isEmpty() ? QString(" %1 %2").arg(arrow, question)
+ : QString(" %1 %2 %3").arg(arrow, icon, question);
+ };
+
+ auto* q_btn = new QPushButton(btn_text(false));
q_btn->setCursor(Qt::PointingHandCursor);
+ q_btn->setAccessibleName(question);
q_btn->setStyleSheet(QString("QPushButton { color: %1; background: %2; border: 1px solid %3;"
" padding: 11px 14px; text-align: left;"
" font-size: 12px; font-weight: 600; %4 }"
@@ -47,11 +56,10 @@ static QWidget* make_faq(const QString& question, const QString& answer, const Q
.arg(colors::TEXT_SECONDARY(), colors::BG_SURFACE(), colors::BORDER_DIM(), colors::AMBER(), MF));
a_lbl->setVisible(false);
- QObject::connect(q_btn, &QPushButton::clicked, a_lbl, [a_lbl, q_btn, question, icon]() {
+ QObject::connect(q_btn, &QPushButton::clicked, a_lbl, [a_lbl, q_btn, btn_text]() {
bool show = !a_lbl->isVisible();
a_lbl->setVisible(show);
- QString arrow = show ? "▾" : "▸";
- q_btn->setText(icon.isEmpty() ? QString(" %1").arg(question) : QString(" %1 %2").arg(icon, question));
+ q_btn->setText(btn_text(show));
// tint open state
q_btn->setStyleSheet(
QString("QPushButton { color: %1; background: %2; border: 1px solid %3;"
@@ -61,7 +69,6 @@ static QWidget* make_faq(const QString& question, const QString& answer, const Q
"QPushButton:hover { background: %4; }")
.arg(show ? colors::AMBER() : colors::TEXT_PRIMARY(), show ? colors::BG_RAISED() : colors::BG_SURFACE(),
show ? colors::AMBER() : colors::BORDER_DIM(), colors::BG_RAISED()));
- Q_UNUSED(arrow);
});
vl->addWidget(q_btn);
@@ -188,7 +195,11 @@ QWidget* HelpScreen::build_page() {
// Business-hours label IS translated.
chips_vl->addWidget(make_chip("✉", "[email protected]", colors::CYAN, "mailto:[email protected]"));
chips_vl->addWidget(make_chip("", "discord.gg/ae87a8ygbN", colors::POSITIVE, "https://discord.gg/ae87a8ygbN"));
- chips_vl->addWidget(make_chip("", tr("Mon-Fri 9AM–6PM EST"), colors::TEXT_TERTIARY));
+ // No staffed-hours claim: the project has no published support roster,
+ // and the previous "Mon-Fri 9AM-6PM EST" line implied one.
+ chips_vl->addWidget(
+ make_chip("", "github.com/Fincept-Corporation/FinceptTerminal", colors::TEXT_TERTIARY,
+ "https://github.com/Fincept-Corporation/FinceptTerminal/issues"));
hl->addLayout(chips_vl);
vl->addWidget(hero);
@@ -216,9 +227,9 @@ QWidget* HelpScreen::build_page() {
{"", "create_account", tr("Create Account"), tr("Register for full access")},
{"", "reset_password", tr("Reset Password"), tr("Recover your account")},
{"", "documentation", tr("Documentation"), tr("Guides, tutorials & API ref")},
- {"", "report_bug", tr("Report a Bug"), tr("Open a bug report ticket")},
+ {"", "report_bug", tr("Report a Bug"), tr("Open a GitHub issue")},
{"", "join_discord", tr("Join Discord"), tr("Community & live support")},
- {"", "support_tickets", tr("Support Tickets"), tr("View or open a support ticket")},
+ {"", "support_tickets", tr("Email Support"), tr("Or open a ticket in the Support tab")},
};
int col = 0, row = 0;
@@ -261,13 +272,31 @@ QWidget* HelpScreen::build_page() {
++row;
}
grid->addWidget(btn, row, col++);
+ btn->setAccessibleName(a.label);
+ btn->setToolTip(a.desc);
// Wire known actions by stable English key (label is localized).
+ // Four of these six buttons had no connect() at all — clicking
+ // Documentation / Report a Bug / Join Discord / Support Tickets did
+ // nothing. The three that map to a public URL now open it; the
+ // in-app ticket view is reachable from the Support tab, which the
+ // description now says.
const QString key = QString::fromLatin1(a.key);
+ auto open = [btn](const QString& url) {
+ QObject::connect(btn, &QPushButton::clicked, btn, [url]() { QDesktopServices::openUrl(QUrl(url)); });
+ };
if (key == "create_account")
connect(btn, &QPushButton::clicked, this, &HelpScreen::navigate_register);
- if (key == "reset_password")
+ else if (key == "reset_password")
connect(btn, &QPushButton::clicked, this, &HelpScreen::navigate_forgot_password);
+ else if (key == "documentation")
+ open(QStringLiteral("https://github.com/Fincept-Corporation/FinceptTerminal/tree/main/docs"));
+ else if (key == "report_bug")
+ open(QStringLiteral("https://github.com/Fincept-Corporation/FinceptTerminal/issues/new"));
+ else if (key == "join_discord")
+ open(QStringLiteral("https://discord.gg/ae87a8ygbN"));
+ else if (key == "support_tickets")
+ open(QStringLiteral("mailto:[email protected]"));
}
vl->addLayout(grid);
@@ -302,13 +331,13 @@ QWidget* HelpScreen::build_page() {
{"", tr("How do I connect a broker?"),
tr("Navigate to Settings → Brokers, select your broker from the list, and enter your "
- "API key and secret. Fincept supports 18+ brokers including Zerodha, Angel One, "
+ "API key and secret. Fincept supports 16 brokers including Zerodha, Angel One, "
"Upstox, Interactive Brokers, and more.")},
{"", tr("Why does Python install at first launch?"),
- tr("Fincept embeds Python for 1300+ analytics scripts covering equity, "
- "portfolio, derivatives, and quant analysis. The one-time install is ~150 MB and "
- "happens automatically in the background.")},
+ tr("Fincept embeds Python 3.11 for its analytics scripts covering equity, "
+ "portfolio, derivatives, and quant analysis. The one-time install happens "
+ "automatically in the background.")},
{"", tr("What are the system requirements?"),
tr("Windows 10+ (x64), macOS 12+, or Linux (glibc 2.31+). 8 GB RAM recommended. "
@@ -321,9 +350,9 @@ QWidget* HelpScreen::build_page() {
"direct broker connections from your machine.")},
{"", tr("How do I report a bug?"),
- tr("Open a support ticket with category \"bug report\" (Help → Support Tickets → "
- "+ New Ticket). Include your OS, version, steps to reproduce, and any error "
- "messages you see. Screenshots are helpful.")},
+ tr("Open a ticket in the Support tab with category \"Bug Report\", or file a GitHub "
+ "issue. Include your OS, version, steps to reproduce, and any error messages you "
+ "see. If the app crashed, attach the dump from About → Diagnostics.")},
};
for (const auto& f : faqs)
diff --git a/fincept-qt/src/screens/info/TrademarksScreen.cpp b/fincept-qt/src/screens/info/TrademarksScreen.cpp
index c44ef4c45..338f58fab 100644
--- a/fincept-qt/src/screens/info/TrademarksScreen.cpp
+++ b/fincept-qt/src/screens/info/TrademarksScreen.cpp
@@ -141,11 +141,26 @@ QWidget* TrademarksScreen::build_page() {
pvl->addWidget(bullet(tr("News data from licensed news aggregation services")));
pvl->addWidget(bullet(tr("Geopolitical data from HDX and public sources")));
pvl->addWidget(bullet(tr("Crypto data from exchange APIs (Kraken, HyperLiquid, etc.)")));
-
- pvl->addWidget(heading("6", tr("REPORTING INFRINGEMENT")));
+ // OpenStreetMap tiles carry a mandatory ODbL attribution requirement and the
+ // terminal renders them (QGeoView / maritime + relationship maps) — this was
+ // missing entirely.
+ pvl->addWidget(bullet(tr("Map data © OpenStreetMap contributors, available under the Open "
+ "Database License (ODbL)")));
+
+ pvl->addWidget(heading("6", tr("THIRD-PARTY SOFTWARE")));
+ pvl->addWidget(body(tr("Fincept Terminal is built on the following open source components, "
+ "used under their respective licenses:")));
+ // Component/license names are proper nouns — shown verbatim.
+ pvl->addWidget(bullet("Qt 6 — The Qt Company (LGPL-3.0)"));
+ pvl->addWidget(bullet("CPython 3.11 — Python Software Foundation (PSF License)"));
+ pvl->addWidget(bullet("QXlsx — QtExcel (MIT)"));
+ pvl->addWidget(bullet("QGeoView — AmonRaNet (LGPL-3.0)"));
+ pvl->addWidget(bullet("SQLite — public domain"));
+
+ pvl->addWidget(heading("7", tr("REPORTING INFRINGEMENT")));
pvl->addWidget(body(tr("To report trademark infringement, contact: [email protected]")));
- pvl->addWidget(heading("7", tr("LEGAL DEPARTMENT")));
+ pvl->addWidget(heading("8", tr("LEGAL DEPARTMENT")));
pvl->addWidget(body(tr("Fincept Corporation — Legal Department")));
pvl->addWidget(body(tr("Email: [email protected]")));
diff --git a/fincept-qt/src/screens/launchpad/LaunchpadScreen.cpp b/fincept-qt/src/screens/launchpad/LaunchpadScreen.cpp
index 3f9f293c1..1e05671ef 100644
--- a/fincept-qt/src/screens/launchpad/LaunchpadScreen.cpp
+++ b/fincept-qt/src/screens/launchpad/LaunchpadScreen.cpp
@@ -14,6 +14,7 @@
#include "storage/repositories/SettingsRepository.h"
#include "storage/workspace/WorkspaceDb.h"
#include "storage/workspace/WorkspaceSnapshotRing.h"
+#include "ui/theme/Theme.h"
#include <QApplication>
#include <QCloseEvent>
@@ -32,8 +33,10 @@
#include <QLineEdit>
#include <QListWidget>
#include <QListWidgetItem>
+#include <QMessageBox>
#include <QProcess>
#include <QPushButton>
+#include <QRegularExpression>
#include <QScreen>
#include <QVBoxLayout>
#include <QWidget>
@@ -42,6 +45,46 @@ namespace fincept::screens {
namespace {
constexpr const char* kLaunchpadTag = "Launchpad";
+
+// The Launchpad was styled with a hand-rolled Tailwind-ish palette (#111827,
+// #374151, #e5e7eb, #9ca3af …) that appears nowhere else in the terminal, plus
+// 4px radii that DESIGN_SYSTEM.md forbids outright. Everything below reads the
+// live Obsidian tokens instead so the portal window matches the product.
+QString lp_greeting_ss() {
+ return QString("color:%1;font-weight:700;letter-spacing:0.5px;background:transparent;").arg(ui::colors::AMBER());
+}
+QString lp_muted_ss() {
+ return QString("color:%1;background:transparent;").arg(ui::colors::TEXT_SECONDARY());
+}
+QString lp_banner_ss() {
+ return QString("QLabel#launchpadCrashBanner{background:%1;color:%2;border:1px solid %3;"
+ "padding:8px 10px;font-weight:600;}")
+ .arg(ui::colors::BG_RAISED(), ui::colors::WARNING(), ui::colors::AMBER_DIM());
+}
+QString lp_primary_btn_ss() {
+ return QString("QPushButton#launchpadContinueBtn{background:%1;color:%2;font-weight:700;border:none;}"
+ "QPushButton#launchpadContinueBtn:hover{background:%3;}")
+ .arg(ui::colors::AMBER(), ui::colors::BG_BASE(), ui::colors::AMBER_DIM());
+}
+QString lp_input_ss() {
+ return QString("QLineEdit{background:%1;border:1px solid %2;color:%3;padding:4px 6px;}"
+ "QLineEdit:focus{border-color:%4;}")
+ .arg(ui::colors::BG_SURFACE(), ui::colors::BORDER_MED(), ui::colors::TEXT_PRIMARY(), ui::colors::AMBER());
+}
+QString lp_list_ss() {
+ return QString("QListWidget{background:%1;border:1px solid %2;color:%3;}"
+ "QListWidget::item{padding:6px 8px;}"
+ "QListWidget::item:hover{background:%4;}"
+ "QListWidget::item:selected{background:%4;color:%5;}")
+ .arg(ui::colors::BG_SURFACE(), ui::colors::BORDER_MED(), ui::colors::TEXT_PRIMARY(), ui::colors::BG_HOVER(),
+ ui::colors::AMBER());
+}
+QString lp_card_ss() {
+ return QString("QPushButton{background:%1;border:1px solid %2;color:%3;padding:10px;text-align:left;"
+ "font-weight:600;}"
+ "QPushButton:hover{border-color:%4;color:%4;}")
+ .arg(ui::colors::BG_SURFACE(), ui::colors::BORDER_MED(), ui::colors::TEXT_PRIMARY(), ui::colors::AMBER());
+}
} // namespace
LaunchpadScreen* LaunchpadScreen::instance() {
@@ -61,14 +104,19 @@ LaunchpadScreen::LaunchpadScreen(QWidget* parent) : QMainWindow(parent) {
vl->setContentsMargins(24, 24, 24, 24);
vl->setSpacing(16);
+ // Window chrome only — deliberately not a blanket `QWidget{}` rule, which
+ // would flatten every child that currently relies on its own style.
+ central->setObjectName(QStringLiteral("launchpadCentral"));
+ central->setStyleSheet(QString("QWidget#launchpadCentral{background:%1;}").arg(ui::colors::BG_BASE()));
+
// Greeting text is set by retranslateUi() — it interpolates the active
// profile name, which can also change at runtime via surface().
greeting_ = new QLabel;
- greeting_->setStyleSheet("font-size: 14px; color: #d97706; font-weight: 600;");
+ greeting_->setStyleSheet(lp_greeting_ss());
vl->addWidget(greeting_);
sub_label_ = new QLabel;
- sub_label_->setStyleSheet("font-size: 11px; color: #9ca3af;");
+ sub_label_->setStyleSheet(lp_muted_ss());
sub_label_->setWordWrap(true);
vl->addWidget(sub_label_);
@@ -80,11 +128,7 @@ LaunchpadScreen::LaunchpadScreen(QWidget* parent) : QMainWindow(parent) {
crash_banner_->setVisible(false);
crash_banner_->setWordWrap(true);
crash_banner_->setObjectName("launchpadCrashBanner");
- crash_banner_->setStyleSheet("QLabel#launchpadCrashBanner {"
- " background: #422006; color: #fbbf24;"
- " border: 1px solid #d97706; border-radius: 4px;"
- " padding: 8px 10px; font-size: 11px; font-weight: 600;"
- "}");
+ crash_banner_->setStyleSheet(lp_banner_ss());
vl->addWidget(crash_banner_);
// "Continue from last session" — the most-common user intent on relaunch.
@@ -93,22 +137,27 @@ LaunchpadScreen::LaunchpadScreen(QWidget* parent) : QMainWindow(parent) {
btn_continue_ = new QPushButton;
btn_continue_->setMinimumHeight(48);
btn_continue_->setObjectName("launchpadContinueBtn");
- btn_continue_->setStyleSheet("QPushButton#launchpadContinueBtn {"
- " background: #d97706; color: #fff;"
- " font-weight: 700; font-size: 13px;"
- " border: none; border-radius: 4px;"
- "}"
- "QPushButton#launchpadContinueBtn:hover { background: #b45309; }");
+ btn_continue_->setStyleSheet(lp_primary_btn_ss());
connect(btn_continue_, &QPushButton::clicked, this, &LaunchpadScreen::on_continue);
vl->addWidget(btn_continue_);
+ // Secondary buttons were left unstyled (native chrome on a dark window).
+ const QString secondary_ss =
+ QString("QPushButton{background:%1;color:%2;border:1px solid %3;font-weight:600;}"
+ "QPushButton:hover{background:%4;color:%5;}"
+ "QPushButton:disabled{color:%6;border-color:%3;}")
+ .arg(ui::colors::BG_RAISED(), ui::colors::TEXT_SECONDARY(), ui::colors::BORDER_MED(),
+ ui::colors::BG_HOVER(), ui::colors::TEXT_PRIMARY(), ui::colors::TEXT_DIM());
+
btn_new_window_ = new QPushButton;
btn_new_window_->setMinimumHeight(36);
+ btn_new_window_->setStyleSheet(secondary_ss);
connect(btn_new_window_, &QPushButton::clicked, this, &LaunchpadScreen::on_new_window);
vl->addWidget(btn_new_window_);
btn_open_layout_ = new QPushButton;
btn_open_layout_->setMinimumHeight(36);
+ btn_open_layout_->setStyleSheet(secondary_ss);
// Enabled state is driven by refresh_recent_layouts() based on whether
// any saved layouts exist.
btn_open_layout_->setEnabled(false);
@@ -117,11 +166,12 @@ LaunchpadScreen::LaunchpadScreen(QWidget* parent) : QMainWindow(parent) {
btn_switch_profile_ = new QPushButton;
btn_switch_profile_->setMinimumHeight(36);
+ btn_switch_profile_->setStyleSheet(secondary_ss);
connect(btn_switch_profile_, &QPushButton::clicked, this, &LaunchpadScreen::on_switch_profile);
vl->addWidget(btn_switch_profile_);
recent_label_ = new QLabel;
- recent_label_->setStyleSheet("font-size: 11px; color: #9ca3af; margin-top: 8px;");
+ recent_label_->setStyleSheet(lp_muted_ss() + "margin-top:8px;");
vl->addWidget(recent_label_);
// Phase L6: keyboard-first filter. Up/Down/Enter/Esc are intercepted
@@ -130,9 +180,8 @@ LaunchpadScreen::LaunchpadScreen(QWidget* parent) : QMainWindow(parent) {
filter_edit_ = new QLineEdit;
filter_edit_->setPlaceholderText(tr("Type to filter layouts…"));
filter_edit_->setClearButtonEnabled(true);
- filter_edit_->setStyleSheet("QLineEdit { background: #111827; border: 1px solid #374151;"
- " color: #e5e7eb; padding: 4px 6px; }"
- "QLineEdit:focus { border-color: #d97706; }");
+ filter_edit_->setStyleSheet(lp_input_ss());
+ filter_edit_->setAccessibleName(tr("Filter saved layouts"));
filter_edit_->installEventFilter(this);
connect(filter_edit_, &QLineEdit::textChanged, this, [this](const QString& q) {
if (!recent_layouts_)
@@ -153,10 +202,8 @@ LaunchpadScreen::LaunchpadScreen(QWidget* parent) : QMainWindow(parent) {
vl->addWidget(filter_edit_);
recent_layouts_ = new QListWidget;
- recent_layouts_->setStyleSheet("QListWidget { background: #111827; border: 1px solid #374151; color: #e5e7eb; }"
- "QListWidget::item { padding: 6px 8px; }"
- "QListWidget::item:hover { background: #1f2937; }"
- "QListWidget::item:selected { background: #1f2937; color: #d97706; }");
+ recent_layouts_->setStyleSheet(lp_list_ss());
+ recent_layouts_->setAccessibleName(tr("Recent layouts"));
vl->addWidget(recent_layouts_, /*stretch=*/1);
refresh_recent_layouts();
@@ -170,7 +217,7 @@ LaunchpadScreen::LaunchpadScreen(QWidget* parent) : QMainWindow(parent) {
picker_root->setSpacing(8);
template_picker_label_ = new QLabel;
- template_picker_label_->setStyleSheet("font-size: 11px; color: #9ca3af; margin-top: 8px;");
+ template_picker_label_->setStyleSheet(lp_muted_ss() + "margin-top:8px;");
picker_root->addWidget(template_picker_label_);
auto* grid = new QGridLayout;
@@ -183,10 +230,9 @@ LaunchpadScreen::LaunchpadScreen(QWidget* parent) : QMainWindow(parent) {
auto* card = new QPushButton;
card->setText(QString("%1\n\n%2").arg(p.display_name, p.description));
card->setMinimumHeight(80);
- card->setStyleSheet("QPushButton { background: #111827; border: 1px solid #374151;"
- " color: #e5e7eb; padding: 10px; text-align: left;"
- " font-size: 12px; font-weight: 600; }"
- "QPushButton:hover { border-color: #d97706; color: #d97706; }");
+ card->setStyleSheet(lp_card_ss());
+ card->setAccessibleName(p.display_name);
+ card->setAccessibleDescription(p.description);
const QString persona_id = p.id;
connect(card, &QPushButton::clicked, this, [this, persona_id]() { on_template_picked(persona_id); });
grid->addWidget(card, i / 2, i % 2);
@@ -246,6 +292,21 @@ void LaunchpadScreen::retranslateUi() {
if (btn_switch_profile_)
btn_switch_profile_->setText(tr("Switch Profile…"));
+ // Accessible names track the visible label, so refresh them here rather
+ // than only at construction.
+ if (btn_continue_)
+ btn_continue_->setAccessibleName(btn_continue_->text());
+ if (btn_new_window_)
+ btn_new_window_->setAccessibleName(btn_new_window_->text());
+ if (btn_open_layout_)
+ btn_open_layout_->setAccessibleName(btn_open_layout_->text());
+ if (btn_switch_profile_)
+ btn_switch_profile_->setAccessibleName(btn_switch_profile_->text());
+ if (filter_edit_)
+ filter_edit_->setAccessibleName(tr("Filter saved layouts"));
+ if (recent_layouts_)
+ recent_layouts_->setAccessibleName(tr("Recent layouts"));
+
if (recent_label_)
recent_label_->setText(tr("Recent Layouts"));
if (filter_edit_)
@@ -373,9 +434,19 @@ void LaunchpadScreen::on_switch_profile() {
bool name_ok = false;
target = QInputDialog::getText(this, tr("Create Profile"), tr("New profile name:"), QLineEdit::Normal,
QString(), &name_ok)
- .trimmed();
+ .trimmed()
+ .toLower();
if (!name_ok || target.isEmpty())
return;
+ // ProfileManager sanitises the name into a directory name, so an
+ // unchecked value silently lands the user in a differently-named
+ // profile than the one they typed.
+ static const QRegularExpression kValidName(QStringLiteral("^[a-z0-9_-]{1,32}$"));
+ if (!kValidName.match(target).hasMatch()) {
+ QMessageBox::warning(this, tr("Invalid Profile Name"),
+ tr("Use 1-32 characters: lowercase letters, digits, hyphen or underscore."));
+ return;
+ }
}
if (target == current) {
@@ -383,6 +454,15 @@ void LaunchpadScreen::on_switch_profile() {
return;
}
+ // Relaunching quits this process. Confirm first — it used to happen the
+ // instant the picker was dismissed with OK.
+ const auto reply = QMessageBox::question(
+ this, tr("Switch Profile"),
+ tr("Switch to profile \"%1\"?\n\nFincept Terminal will restart.").arg(target),
+ QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
+ if (reply != QMessageBox::Yes)
+ return;
+
// Process-level switch today (set_active + relaunch). In-process switch
// lands with Phase 1b's auth lift.
const QString exe = QCoreApplication::applicationFilePath();
@@ -406,6 +486,9 @@ void LaunchpadScreen::on_open_layout() {
auto r = LayoutCatalog::instance().load_workspace(id);
if (r.is_err()) {
LOG_WARN(kLaunchpadTag, QString("Open Layout failed: %1").arg(QString::fromStdString(r.error())));
+ // Was log-only: the row simply did nothing when double-clicked.
+ QMessageBox::warning(this, tr("Cannot open layout"),
+ tr("That layout could not be loaded:\n%1").arg(QString::fromStdString(r.error())));
return;
}
const layout::Workspace ws = r.value();
@@ -494,6 +577,10 @@ void LaunchpadScreen::on_template_picked(const QString& persona_id) {
if (sr.is_err()) {
LOG_WARN(kLaunchpadTag,
QString("Failed to save template '%1': %2").arg(persona_id, QString::fromStdString(sr.error())));
+ // First-run path: a silent return here left the user clicking a card
+ // that appeared to do nothing at all.
+ QMessageBox::warning(this, tr("Cannot start from this template"),
+ tr("The template could not be saved:\n%1").arg(QString::fromStdString(sr.error())));
return;
}
// save_workspace mints a fresh id if one wasn't set; pull the saved id
diff --git a/fincept-qt/src/screens/ma_analytics/MAAnalyticsScreen.cpp b/fincept-qt/src/screens/ma_analytics/MAAnalyticsScreen.cpp
index 49286bcea..aff5c24d0 100644
--- a/fincept-qt/src/screens/ma_analytics/MAAnalyticsScreen.cpp
+++ b/fincept-qt/src/screens/ma_analytics/MAAnalyticsScreen.cpp
@@ -9,6 +9,7 @@
#include <QHBoxLayout>
#include <QScrollArea>
+#include <QSet>
#include <QSplitter>
namespace fincept::screens {
@@ -70,11 +71,11 @@ void MAAnalyticsScreen::retranslateUi() {
if (stat_total_modules_lbl_)
stat_total_modules_lbl_->setText(tr("Total Modules"));
if (stat_valuation_methods_lbl_)
- stat_valuation_methods_lbl_->setText(tr("Valuation Methods"));
+ stat_valuation_methods_lbl_->setText(tr("Categories"));
if (stat_python_scripts_lbl_)
- stat_python_scripts_lbl_->setText(tr("Python Scripts"));
+ stat_python_scripts_lbl_->setText(tr("Capabilities"));
if (stat_analysis_tools_lbl_)
- stat_analysis_tools_lbl_->setText(tr("Analysis Tools"));
+ stat_analysis_tools_lbl_->setText(tr("Engine"));
if (tips_label_)
tips_label_->setText(tr("Click sidebar modules to switch views. "
@@ -160,6 +161,7 @@ QWidget* MAAnalyticsScreen::build_top_bar() {
const auto& mod = modules_[i];
auto* btn = new QPushButton(mod.short_label, bar);
btn->setToolTip(mod.label);
+ btn->setAccessibleName(mod.label);
btn->setCursor(Qt::PointingHandCursor);
btn->setFixedHeight(22);
connect(btn, &QPushButton::clicked, this, [this, i]() { on_module_selected(i); });
@@ -226,6 +228,7 @@ QWidget* MAAnalyticsScreen::build_left_sidebar() {
// Module button
auto* btn = new QPushButton(mod.label, list_widget);
btn->setCursor(Qt::PointingHandCursor);
+ btn->setAccessibleName(tr("%1 module").arg(mod.label));
connect(btn, &QPushButton::clicked, this, [this, i]() { on_module_selected(i); });
left_items_layout_->addWidget(btn);
module_buttons_.append(btn);
@@ -317,10 +320,19 @@ QWidget* MAAnalyticsScreen::build_right_sidebar() {
rl->addWidget(val);
sl->addWidget(row);
};
- add_stat(tr("Total Modules"), "8", stat_total_modules_lbl_);
- add_stat(tr("Valuation Methods"), "15+", stat_valuation_methods_lbl_);
- add_stat(tr("Python Scripts"), "30+", stat_python_scripts_lbl_);
- add_stat(tr("Analysis Tools"), "60+", stat_analysis_tools_lbl_);
+ // These were hardcoded to "8 / 15+ / 30+ / 60+" — invented figures that
+ // drifted from the module registry and could not be verified. Everything
+ // shown here is now counted from the registry that drives the UI.
+ QSet<QString> categories;
+ int total_caps = 0;
+ for (const auto& m : modules_) {
+ categories.insert(m.category);
+ total_caps += static_cast<int>(module_capabilities(m.id).size());
+ }
+ add_stat(tr("Total Modules"), QString::number(modules_.size()), stat_total_modules_lbl_);
+ add_stat(tr("Categories"), QString::number(categories.size()), stat_valuation_methods_lbl_);
+ add_stat(tr("Capabilities"), QString::number(total_caps), stat_python_scripts_lbl_);
+ add_stat(tr("Engine"), QStringLiteral("Python + C++"), stat_analysis_tools_lbl_);
cl->addWidget(stats_card_);
// Tips
@@ -375,6 +387,11 @@ void MAAnalyticsScreen::on_module_selected(int index) {
content_stack_->setCurrentIndex(index);
update_sidebar_selection();
update_right_panel();
+ // The status bar's MODULE: value was created as an em-dash and then never
+ // written to — it stayed "—" no matter which module was open.
+ if (status_bar_)
+ if (auto* mod_val = status_bar_->findChild<QLabel*>("maStatusModule"))
+ mod_val->setText(modules_[index].label.toUpper());
LOG_INFO("MAAnalytics", QString("Switched to module: %1").arg(modules_[index].label));
ScreenStateManager::instance().notify_changed(this);
}
diff --git a/fincept-qt/src/screens/ma_analytics/MAAnalyticsScreen.h b/fincept-qt/src/screens/ma_analytics/MAAnalyticsScreen.h
index 7702c6a74..72a4acc02 100644
--- a/fincept-qt/src/screens/ma_analytics/MAAnalyticsScreen.h
+++ b/fincept-qt/src/screens/ma_analytics/MAAnalyticsScreen.h
@@ -92,8 +92,6 @@ class MAAnalyticsScreen : public QWidget, public IStatefulScreen {
QLabel* status_status_lbl_ = nullptr;
QLabel* status_ready_val_ = nullptr;
- bool left_open_ = true;
- bool right_open_ = true;
bool first_show_ = true;
};
diff --git a/fincept-qt/src/screens/maritime/MaritimeScreen_Handlers.cpp b/fincept-qt/src/screens/maritime/MaritimeScreen_Handlers.cpp
index cc36588c0..36797ab8a 100644
--- a/fincept-qt/src/screens/maritime/MaritimeScreen_Handlers.cpp
+++ b/fincept-qt/src/screens/maritime/MaritimeScreen_Handlers.cpp
@@ -19,6 +19,8 @@
#include "ui/widgets/LoadingOverlay.h"
#include "ui/widgets/WorldMapWidget.h"
+#include <QCoreApplication>
+#include <QDateTime>
#include <QGridLayout>
#include <QHBoxLayout>
#include <QHash>
@@ -30,12 +32,58 @@
#include <QSplitter>
#include <QTabWidget>
#include <QTime>
+#include <QTimeZone>
namespace fincept::screens {
using namespace fincept::services::maritime;
using namespace fincept::screens::maritime_internal;
+namespace {
+
+/// Parse the API's `last_updated` stamp and describe how stale it is. AIS
+/// positions are frequently hours or days old; rendering a lat/lng with no age
+/// invites reading a stale fix as a live one.
+struct PositionAge {
+ bool known = false;
+ qint64 minutes = 0;
+ QDateTime when;
+};
+
+PositionAge position_age(const QString& last_updated) {
+ PositionAge a;
+ if (last_updated.trimmed().isEmpty())
+ return a;
+ QDateTime dt = QDateTime::fromString(last_updated, Qt::ISODate);
+ if (!dt.isValid())
+ dt = QDateTime::fromString(last_updated, QStringLiteral("yyyy-MM-dd HH:mm:ss"));
+ if (!dt.isValid())
+ return a;
+ if (dt.timeSpec() == Qt::LocalTime)
+ dt.setTimeZone(QTimeZone::UTC); // API stamps are UTC when unqualified
+ a.known = true;
+ a.when = dt;
+ a.minutes = dt.secsTo(QDateTime::currentDateTimeUtc()) / 60;
+ return a;
+}
+
+QString age_text(const PositionAge& a) {
+ if (!a.known)
+ return QCoreApplication::translate("MaritimeScreen", "position age unknown");
+ if (a.minutes < 0)
+ return QCoreApplication::translate("MaritimeScreen", "just now");
+ if (a.minutes < 60)
+ return QCoreApplication::translate("MaritimeScreen", "%n min old", "", static_cast<int>(a.minutes));
+ if (a.minutes < 60 * 48)
+ return QCoreApplication::translate("MaritimeScreen", "%n hour(s) old", "", static_cast<int>(a.minutes / 60));
+ return QCoreApplication::translate("MaritimeScreen", "%n day(s) old", "", static_cast<int>(a.minutes / 1440));
+}
+
+/// Anything older than this is flagged so the user doesn't trust the fix.
+constexpr qint64 kStaleMinutes = 6 * 60;
+
+} // namespace
+
void MaritimeScreen::load_global_sample() {
// World bbox — the API caps at ±90 lat / ±180 lng, but stays well-behaved
// with these slightly inset values. Worldwide this matches ~45k vessels;
@@ -252,13 +300,23 @@ void MaritimeScreen::on_vessels_loaded(VesselsPage page) {
for (int i = 0; i < render_n; ++i) {
const auto& v = page.vessels[i];
+ const PositionAge age = position_age(v.last_updated);
+ const bool stale = !age.known || age.minutes >= kStaleMinutes;
+
+ // Flag stale fixes by colouring the name amber (plus an age tooltip) so
+ // a days-old AIS position can't be mistaken for a live one. Deliberately
+ // no text prefix — that would corrupt sorting on the Name column.
auto* name_item = new QTableWidgetItem(v.name);
- name_item->setForeground(QBrush(QColor(ui::colors::TEXT_PRIMARY.get())));
+ name_item->setForeground(QBrush(QColor(stale ? ui::colors::AMBER.get() : ui::colors::TEXT_PRIMARY.get())));
+ name_item->setToolTip(
+ tr("%1\nIMO %2\nPosition reported: %3 (%4)")
+ .arg(v.name, v.imo, age.known ? age.when.toString(Qt::ISODate) : tr("unknown"), age_text(age)));
vessels_table_->setItem(i, 0, name_item);
vessels_table_->setItem(i, 1, new QTableWidgetItem(v.imo));
auto* lat = new QTableWidgetItem(QString::number(v.latitude, 'f', 4));
lat->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ lat->setToolTip(age_text(age));
vessels_table_->setItem(i, 2, lat);
auto* lng = new QTableWidgetItem(QString::number(v.longitude, 'f', 4));
@@ -319,7 +377,14 @@ void MaritimeScreen::on_vessel_found(VesselData vessel) {
search_result_label_->setVisible(false);
sr_name_->setText(vessel.name);
sr_imo_->setText(tr("IMO: %1").arg(vessel.imo));
- sr_position_->setText(tr("Position: %1, %2").arg(vessel.latitude, 0, 'f', 4).arg(vessel.longitude, 0, 'f', 4));
+ // Always state the age of the fix next to the coordinates.
+ const PositionAge age = position_age(vessel.last_updated);
+ sr_position_->setText(tr("Position: %1, %2 · %3")
+ .arg(vessel.latitude, 0, 'f', 4)
+ .arg(vessel.longitude, 0, 'f', 4)
+ .arg(age_text(age)));
+ sr_position_->setToolTip(age.known ? tr("Reported %1 UTC").arg(age.when.toString(Qt::ISODate))
+ : tr("The API did not report a position timestamp for this vessel."));
sr_speed_->setText(tr("Speed: %1 kn").arg(vessel.speed, 0, 'f', 1));
sr_from_->setText(tr("From: %1").arg(vessel.from_port.isEmpty() ? QStringLiteral("—") : vessel.from_port));
sr_to_->setText(tr("To: %1").arg(vessel.to_port.isEmpty() ? QStringLiteral("—") : vessel.to_port));
@@ -508,7 +573,12 @@ void MaritimeScreen::update_map(const QVector<VesselData>& vessels) {
// detail card.
const int id = rendered_vessels_.size();
rendered_vessels_.append(v);
- pins.append({v.latitude, v.longitude, QString("%1 (%2)").arg(v.name, v.imo), ui::colors::POSITIVE, 5.5, id});
+ // Pin label carries the fix age so hovering a pin tells the user how
+ // old the position is; stale fixes are drawn amber instead of green.
+ const PositionAge age = position_age(v.last_updated);
+ const bool stale = !age.known || age.minutes >= kStaleMinutes;
+ pins.append({v.latitude, v.longitude, QString("%1 (%2) — %3").arg(v.name, v.imo, age_text(age)),
+ QColor(stale ? ui::colors::AMBER.get() : ui::colors::POSITIVE.get()), 5.5, id});
// Track unique destination ports for the DEST PORTS stat.
if (!v.to_port.isEmpty())
port_seen.insert(v.to_port);
diff --git a/fincept-qt/src/screens/maritime/MaritimeScreen_Layout.cpp b/fincept-qt/src/screens/maritime/MaritimeScreen_Layout.cpp
index 67b8d1169..375a8e766 100644
--- a/fincept-qt/src/screens/maritime/MaritimeScreen_Layout.cpp
+++ b/fincept-qt/src/screens/maritime/MaritimeScreen_Layout.cpp
@@ -582,13 +582,20 @@ QWidget* MaritimeScreen::build_right_panel() {
place_table_->horizontalHeader()->setStretchLastSection(true);
place_table_->setMinimumHeight(120);
place_table_->setStyleSheet(table_ss());
- // Click a suggestion → fill bbox + load vessels in that area.
- connect(place_table_, &QTableWidget::currentCellChanged, this, [this](int row, int, int, int) {
+ place_table_->setAccessibleName(tr("Place search results"));
+ place_table_->setAccessibleDescription(tr("Click or press Enter on a place to load vessels in its bounding box."));
+ // Click (or Enter) a suggestion → fill bbox + load vessels in that area.
+ // This was wired to currentCellChanged, which also fires on every arrow-key
+ // move — walking the list with the keyboard issued a metered vessel
+ // area-search per row.
+ auto pick_place = [this](int row, int) {
if (row < 0 || row >= place_results_.size())
return;
const auto& p = place_results_[row];
run_area_search(p.min_lat, p.max_lat, p.min_lng, p.max_lng);
- });
+ };
+ connect(place_table_, &QTableWidget::cellClicked, this, pick_place);
+ connect(place_table_, &QTableWidget::cellActivated, this, pick_place);
vl->addWidget(place_table_);
// ── Area Search (Advanced — raw lat/long) ───────────────────────────────
@@ -764,9 +771,12 @@ QWidget* MaritimeScreen::build_right_panel() {
ports_table_->horizontalHeader()->setStretchLastSection(true);
ports_table_->setMinimumHeight(160);
ports_table_->setStyleSheet(table_ss());
- // Click → drop an AMBER pin on the existing world map to distinguish from
- // the green vessel pins, then re-fit the camera.
- connect(ports_table_, &QTableWidget::currentCellChanged, this, [this](int row, int, int, int) {
+ ports_table_->setAccessibleName(tr("Port search results"));
+ ports_table_->setAccessibleDescription(tr("Click or press Enter on a port to plot it on the map."));
+ // Click (or Enter) → drop an AMBER pin on the existing world map to
+ // distinguish from the green vessel pins, then re-fit the camera. Was on
+ // currentCellChanged, so arrow-keying the list flew the map on every row.
+ auto pick_port = [this](int row, int) {
if (row < 0 || row >= port_results_.size() || !map_widget_)
return;
const auto& p = port_results_[row];
@@ -781,7 +791,9 @@ QWidget* MaritimeScreen::build_right_panel() {
pin.id = -1;
map_widget_->add_pin(pin);
map_widget_->fly_to(p.latitude, p.longitude);
- });
+ };
+ connect(ports_table_, &QTableWidget::cellClicked, this, pick_port);
+ connect(ports_table_, &QTableWidget::cellActivated, this, pick_port);
vl->addWidget(ports_table_);
// ── Route Detail ───────────────────────────────────────────────────────
@@ -830,13 +842,8 @@ QWidget* MaritimeScreen::build_right_panel() {
// Suppressed: hardcoded "system status" placeholders (AIS Transponders /
// Satellite Imagery / 10 corridors / 13 SATs / 6 ports) — none of these
- // figures come from the API. Restore once a real backend exposes them.
- QVector<QPair<QString, QString>> statuses;
- for (const auto& [text, color] : statuses) {
- auto* lbl = new QLabel(QString::fromUtf8("\u25CF ") + text, content);
- lbl->setStyleSheet(QString("color:%1; font-size:8px; font-family:%2;").arg(color).arg(ui::fonts::DATA_FAMILY));
- vl->addWidget(lbl);
- }
+ // figures come from the API. The empty vector + dead loop that replaced
+ // them has been removed; restore a real block once a backend exposes it.
classified_footer_ = new QLabel(tr("CLASSIFIED — AUTHORIZED PERSONNEL ONLY"), content);
classified_footer_->setWordWrap(true);
diff --git a/fincept-qt/src/screens/markets/MarketPanel.cpp b/fincept-qt/src/screens/markets/MarketPanel.cpp
index de1a6242c..c4ccfccde 100644
--- a/fincept-qt/src/screens/markets/MarketPanel.cpp
+++ b/fincept-qt/src/screens/markets/MarketPanel.cpp
@@ -53,6 +53,7 @@ void MarketPanel::build_ui() {
title_label_ = new QLabel(config_.title.toUpper());
hhl->addWidget(title_label_);
hhl->addStretch();
+ setAccessibleName(config_.title);
auto make_hdr_btn = [](const QString& text) -> QPushButton* {
auto* b = new QPushButton(text);
@@ -66,6 +67,15 @@ void MarketPanel::build_ui() {
edit_btn_ = make_hdr_btn(tr("[EDIT]"));
delete_btn_ = make_hdr_btn(tr("[DEL]"));
+ cols_btn_->setAccessibleName(tr("Choose columns"));
+ cols_btn_->setToolTip(tr("Choose which columns this panel shows"));
+ edit_btn_->setAccessibleName(tr("Edit panel"));
+ edit_btn_->setToolTip(tr("Edit this panel's title and symbols"));
+ delete_btn_->setAccessibleName(tr("Remove panel"));
+ delete_btn_->setToolTip(tr("Remove this panel"));
+ setTabOrder(cols_btn_, edit_btn_);
+ setTabOrder(edit_btn_, delete_btn_);
+
hhl->addWidget(cols_btn_);
hhl->addWidget(edit_btn_);
hhl->addWidget(delete_btn_);
@@ -116,6 +126,7 @@ void MarketPanel::build_ui() {
error_label_->setWordWrap(true); // narrow panels — wrap the failure message
retry_btn_ = new QPushButton(tr("[RETRY]"));
retry_btn_->setCursor(Qt::PointingHandCursor);
+ retry_btn_->setAccessibleName(tr("Retry loading this panel"));
retry_btn_->setFlat(true);
connect(retry_btn_, &QPushButton::clicked, this, &MarketPanel::refresh);
el->addWidget(error_label_);
@@ -173,6 +184,9 @@ QString MarketPanel::column_label(const QString& code) const {
void MarketPanel::setup_table_columns() {
const QStringList& cols = config_.column_order;
+ // Column set changed → the next populate() must run even if the row count
+ // is unchanged.
+ last_populated_rows_ = -1;
table_->setColumnCount(cols.size());
// Set header labels with alignment matching cell alignment.
@@ -260,6 +274,7 @@ void MarketPanel::update_config(const MarketPanelConfig& cfg) {
if (config_.column_order.isEmpty())
config_.column_order = default_market_columns();
title_label_->setText(cfg.title.toUpper());
+ setAccessibleName(cfg.title);
setup_table_columns();
if (has_data_)
populate(cached_quotes_);
@@ -270,7 +285,6 @@ void MarketPanel::update_config(const MarketPanelConfig& cfg) {
// ---------------------------------------------------------------------------
void MarketPanel::refresh() {
- fetch_failed_ = false;
title_label_->setText(config_.title.toUpper() + " ...");
if (!has_data_)
@@ -279,6 +293,39 @@ void MarketPanel::refresh() {
hub_resubscribe();
}
+void MarketPanel::showEvent(QShowEvent* event) {
+ QWidget::showEvent(event);
+ // MarketsScreen::showEvent only calls refresh_all() when the last refresh
+ // is older than 5 minutes, so re-subscribing has to happen here or a
+ // hide/show inside that window would leave the panel permanently detached
+ // from the hub.
+ if (!hub_active_ && !config_.symbols.isEmpty())
+ hub_resubscribe();
+}
+
+void MarketPanel::hideEvent(QHideEvent* event) {
+ QWidget::hideEvent(event);
+ hub_unsubscribe_all();
+ if (loading_timer_)
+ loading_timer_->stop();
+}
+
+void MarketPanel::schedule_populate() {
+ if (populate_scheduled_)
+ return;
+ populate_scheduled_ = true;
+ QPointer<MarketPanel> self = this;
+ QMetaObject::invokeMethod(
+ this,
+ [self]() {
+ if (!self)
+ return;
+ self->populate_scheduled_ = false;
+ self->populate(self->cached_quotes_);
+ },
+ Qt::QueuedConnection);
+}
+
void MarketPanel::rebuild_from_cache() {
cached_quotes_.clear();
cached_quotes_.reserve(config_.symbols.size());
@@ -302,6 +349,10 @@ void MarketPanel::hub_resubscribe() {
if (config_.symbols.isEmpty()) {
hub.unsubscribe(this);
hub_active_ = false;
+ // refresh() already switched on the LOADING overlay; with no symbols
+ // nothing will ever arrive to turn it off, so the panel span forever.
+ // Show an actionable empty state instead.
+ show_error(tr("No symbols in this panel — use [EDIT] to add some."));
emit refresh_finished();
return;
}
@@ -362,7 +413,6 @@ void MarketPanel::hub_resubscribe() {
emit refresh_finished();
}
if (!has_data_ && pending_initial_.isEmpty()) {
- fetch_failed_ = true;
show_error(err.trimmed().isEmpty() ? tr("Failed to load market data")
: tr("Load failed: %1").arg(err.trimmed()));
}
@@ -409,19 +459,17 @@ void MarketPanel::tick_loading_anim() {
void MarketPanel::show_data() {
error_widget_->setVisible(false);
table_->setVisible(true);
- // Defer populate until after the splitter has performed layout so body_->height() is valid
- QPointer<MarketPanel> self = this;
- QMetaObject::invokeMethod(
- this,
- [self]() {
- if (self)
- self->populate(self->cached_quotes_);
- },
- Qt::QueuedConnection);
+ // Defer populate until after the splitter has performed layout so
+ // body_->height() is valid — and coalesce, because rebuild_from_cache()
+ // lands once per arriving symbol and each populate() rebuilds every cell.
+ schedule_populate();
}
void MarketPanel::show_error(const QString& msg) {
hide_loading(); // stop the spinner + hide the LOADING overlay
+ // refresh() appends " ..." to the title; without this it stays there for
+ // good once a fetch fails.
+ title_label_->setText(config_.title.toUpper());
table_->setVisible(false);
error_widget_->setVisible(true);
error_label_->setText(msg);
@@ -431,7 +479,8 @@ void MarketPanel::populate(const QVector<services::QuoteData>& quotes) {
const int body_h = body_->height();
// Use actual visible rows if laid out, otherwise show all quotes (resizeEvent will trim)
const int visible = (body_h > kColHeaderH + kRowH) ? (body_h - kColHeaderH) / kRowH : quotes.size();
- const int count = qMin(quotes.size(), qMax(visible, 0));
+ const int count = static_cast<int>(qMin(quotes.size(), static_cast<qsizetype>(qMax(visible, 0))));
+ last_populated_rows_ = count;
table_->setRowCount(count);
for (int row = 0; row < count; ++row) {
@@ -525,10 +574,19 @@ QSize MarketPanel::minimumSizeHint() const {
void MarketPanel::resizeEvent(QResizeEvent* event) {
QWidget::resizeEvent(event);
- if (has_data_)
- populate(cached_quotes_);
- else
+ if (has_data_) {
+ // A splitter drag fires resizeEvent per pixel. Only rebuild the cells
+ // when the number of rows that actually fit has changed — otherwise
+ // the columns just re-stretch and the existing items stay valid.
+ const int body_h = body_->height();
+ const int visible = (body_h > kColHeaderH + kRowH) ? (body_h - kColHeaderH) / kRowH
+ : static_cast<int>(cached_quotes_.size());
+ const int want = static_cast<int>(qMin(cached_quotes_.size(), static_cast<qsizetype>(qMax(visible, 0))));
+ if (want != last_populated_rows_)
+ schedule_populate();
+ } else {
update_visible_rows();
+ }
}
// ---------------------------------------------------------------------------
diff --git a/fincept-qt/src/screens/markets/MarketPanel.h b/fincept-qt/src/screens/markets/MarketPanel.h
index 2f8d5d5c5..4db3f2b7a 100644
--- a/fincept-qt/src/screens/markets/MarketPanel.h
+++ b/fincept-qt/src/screens/markets/MarketPanel.h
@@ -4,9 +4,11 @@
#include <QEvent>
#include <QHash>
+#include <QHideEvent>
#include <QLabel>
#include <QPushButton>
#include <QSet>
+#include <QShowEvent>
#include <QTableWidget>
#include <QTimer>
#include <QWidget>
@@ -46,6 +48,11 @@ class MarketPanel : public QWidget {
protected:
void resizeEvent(QResizeEvent* event) override;
void changeEvent(QEvent* event) override;
+ /// Visibility-driven hub lifecycle (CLAUDE.md P3 / D3). Without these the
+ /// panel stayed subscribed — and kept its loading spinner ticking — for as
+ /// long as the app ran, even with the Markets tab closed.
+ void showEvent(QShowEvent* event) override;
+ void hideEvent(QHideEvent* event) override;
private slots:
void show_row_context_menu(const QPoint& pos);
@@ -75,7 +82,12 @@ class MarketPanel : public QWidget {
MarketPanelConfig config_;
QVector<services::QuoteData> cached_quotes_; // all fetched data; display subset shown
bool has_data_ = false;
- bool fetch_failed_ = false;
+ /// Coalesces the per-symbol re-render burst into a single populate().
+ bool populate_scheduled_ = false;
+ /// Row count the table was last laid out for — lets resizeEvent skip a
+ /// full repopulate when the visible row count hasn't actually changed.
+ int last_populated_rows_ = -1;
+ void schedule_populate();
QHash<QString, services::QuoteData> row_cache_;
QHash<QString, QString> names_; // symbol → human-readable display name (yfinance, cached)
diff --git a/fincept-qt/src/screens/markets/MarketPanelEditor.cpp b/fincept-qt/src/screens/markets/MarketPanelEditor.cpp
index f5449d69d..ec16c6f10 100644
--- a/fincept-qt/src/screens/markets/MarketPanelEditor.cpp
+++ b/fincept-qt/src/screens/markets/MarketPanelEditor.cpp
@@ -67,6 +67,10 @@ void MarketPanelEditor::build_ui() {
title_edit_ = new QLineEdit(config_.title);
title_edit_->setPlaceholderText(tr("e.g. My Tech Stocks"));
title_edit_->setStyleSheet(input_ss());
+ connect(title_edit_, &QLineEdit::textChanged, this, [this](const QString&) {
+ if (error_lbl_)
+ error_lbl_->setVisible(false);
+ });
root->addWidget(title_edit_);
auto make_sep = [&]() {
@@ -145,7 +149,21 @@ void MarketPanelEditor::build_ui() {
"QPushButton:hover{border-color:%4;color:%4;}")
.arg(ui::colors::BG_RAISED(), ui::colors::TEXT_SECONDARY(), ui::colors::BORDER_MED(), ui::colors::AMBER()));
connect(btns, &QDialogButtonBox::accepted, this, [this]() {
- config_.title = title_edit_->text().trimmed();
+ const QString title = title_edit_->text().trimmed();
+ // MarketPanelStore::load() drops any config with an empty title, so a
+ // panel saved without one vanished at the next restart with no warning.
+ // Block it at the source instead.
+ if (title.isEmpty()) {
+ show_validation_error(tr("Enter a panel title."));
+ title_edit_->setFocus();
+ return;
+ }
+ if (ticker_list_->count() == 0) {
+ show_validation_error(tr("Add at least one ticker."));
+ search_edit_->setFocus();
+ return;
+ }
+ config_.title = title;
config_.symbols.clear();
for (int i = 0; i < ticker_list_->count(); ++i)
config_.symbols << ticker_list_->item(i)->text();
@@ -158,11 +176,39 @@ void MarketPanelEditor::build_ui() {
hide_dropdown();
reject();
});
+ // Inline validation message (hidden until something is wrong) — a modal
+ // QMessageBox for "you forgot a title" is heavier than the problem.
+ error_lbl_ = new QLabel;
+ error_lbl_->setWordWrap(true);
+ error_lbl_->setVisible(false);
+ error_lbl_->setStyleSheet(
+ QString("color:%1;background:transparent;font-size:11px;font-weight:bold;").arg(ui::colors::NEGATIVE()));
+ root->addWidget(error_lbl_);
+
root->addWidget(btns);
+ // ── Accessibility + keyboard ──
+ title_edit_->setAccessibleName(tr("Panel title"));
+ search_edit_->setAccessibleName(tr("Search for a ticker to add"));
+ ticker_list_->setAccessibleName(tr("Tickers in this panel"));
+ remove_btn_->setAccessibleName(tr("Remove the selected ticker"));
+ dropdown_->setAccessibleName(tr("Ticker search results"));
+ setTabOrder(title_edit_, ticker_list_);
+ setTabOrder(ticker_list_, remove_btn_);
+ setTabOrder(remove_btn_, search_edit_);
+ setTabOrder(search_edit_, btns);
+ title_edit_->setFocus();
+
refresh_ticker_list();
}
+void MarketPanelEditor::show_validation_error(const QString& message) {
+ if (!error_lbl_)
+ return;
+ error_lbl_->setText(message);
+ error_lbl_->setVisible(true);
+}
+
void MarketPanelEditor::reposition_dropdown() {
if (!search_edit_ || !dropdown_)
return;
@@ -277,6 +323,8 @@ void MarketPanelEditor::on_add_symbol(const QString& symbol) {
if (sym.isEmpty() || config_.symbols.contains(sym))
return;
config_.symbols << sym;
+ if (error_lbl_)
+ error_lbl_->setVisible(false);
refresh_ticker_list();
search_edit_->clear();
hide_dropdown();
diff --git a/fincept-qt/src/screens/markets/MarketPanelEditor.h b/fincept-qt/src/screens/markets/MarketPanelEditor.h
index a1e75550d..1051f8b08 100644
--- a/fincept-qt/src/screens/markets/MarketPanelEditor.h
+++ b/fincept-qt/src/screens/markets/MarketPanelEditor.h
@@ -44,9 +44,12 @@ class MarketPanelEditor : public QDialog {
void refresh_ticker_list();
void reposition_dropdown();
void hide_dropdown();
+ /// Shows an inline validation message above the OK/Cancel row.
+ void show_validation_error(const QString& message);
MarketPanelConfig config_;
+ QLabel* error_lbl_ = nullptr;
QLabel* title_lbl_ = nullptr;
QLabel* tickers_lbl_ = nullptr;
QLabel* search_lbl_ = nullptr;
diff --git a/fincept-qt/src/screens/markets/MarketsScreen.cpp b/fincept-qt/src/screens/markets/MarketsScreen.cpp
index 64f41092f..05cbd4705 100644
--- a/fincept-qt/src/screens/markets/MarketsScreen.cpp
+++ b/fincept-qt/src/screens/markets/MarketsScreen.cpp
@@ -17,10 +17,12 @@
#include <QMenu>
#include <QMessageBox>
#include <QPushButton>
+#include <QShortcut>
#include <QShowEvent>
#include <QSplitter>
#include <QTimeZone>
#include <QVBoxLayout>
+#include <QtConcurrent/QtConcurrent>
namespace fincept::screens {
@@ -64,8 +66,11 @@ MarketsScreen::MarketsScreen(QWidget* parent) : QWidget(parent) {
connect(refresh_timeout_, &QTimer::timeout, this, [this]() {
if (!refresh_in_progress_)
return;
- refresh_in_progress_ = false;
- pending_refreshes_ = 0;
+ // Tear the cycle's connections down. Without this, a late
+ // refresh_finished() from the timed-out cycle still decremented
+ // pending_refreshes_ — which by then belonged to the NEXT cycle — and
+ // flipped the badge to READY before that cycle's data had arrived.
+ abort_refresh_cycle();
status_state_ = StatusState::Timeout;
if (status_label_) {
status_label_->setText(tr("● TIMEOUT"));
@@ -73,6 +78,19 @@ MarketsScreen::MarketsScreen(QWidget* parent) : QWidget(parent) {
}
});
+ // F5 / F9 — the header buttons are literally labelled "[F5] REFRESH" and
+ // "[F9] AUTO", but no shortcut was ever registered for either.
+ auto* f5 = new QShortcut(QKeySequence(Qt::Key_F5), this);
+ f5->setContext(Qt::WindowShortcut);
+ connect(f5, &QShortcut::activated, this, &MarketsScreen::refresh_all);
+
+ auto* f9 = new QShortcut(QKeySequence(Qt::Key_F9), this);
+ f9->setContext(Qt::WindowShortcut);
+ connect(f9, &QShortcut::activated, this, [this]() {
+ if (auto_btn_)
+ auto_btn_->click();
+ });
+
connect(&ui::ThemeManager::instance(), &ui::ThemeManager::theme_changed, this,
[this](const ui::ThemeTokens&) { refresh_theme(); });
refresh_theme();
@@ -119,6 +137,17 @@ void MarketsScreen::build_splitter_layout() {
if (!has_panel) {
auto* placeholder = new QWidget;
placeholder->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
+ // Empty state: with every panel deleted the screen was three blank
+ // columns and no hint about how to get anything back.
+ if (panels_.isEmpty() && col == 0) {
+ auto* pl = new QVBoxLayout(placeholder);
+ pl->setAlignment(Qt::AlignCenter);
+ auto* hint = new QLabel(tr("No market panels.\nUse [+] PANEL to add one, or RESET for the defaults."));
+ hint->setAlignment(Qt::AlignCenter);
+ hint->setWordWrap(true);
+ hint->setStyleSheet(lbl_ss(ui::colors::TEXT_DIM(), false, 12));
+ pl->addWidget(hint);
+ }
col_splitters_[col]->addWidget(placeholder);
}
}
@@ -184,7 +213,9 @@ void MarketsScreen::save_splitter_state() {
// Save only horizontal splitter state (column widths).
// Vertical row heights are always equal-distributed on build.
const QString state = QString::fromLatin1(h_splitter_->saveState().toBase64());
- SettingsRepository::instance().set("markets_splitter_state", state);
+ // hideEvent() runs on every tab switch — keep the sqlite write off the UI
+ // thread so leaving the Markets tab never stalls the frame (P1).
+ (void)QtConcurrent::run([state]() { SettingsRepository::instance().set("markets_splitter_state", state); });
}
void MarketsScreen::restore_splitter_state() {
@@ -461,6 +492,25 @@ QWidget* MarketsScreen::build_header_bar() {
status_label_->setStyleSheet(lbl_ss(ui::colors::POSITIVE(), true));
h->addWidget(status_label_);
+ // ── Accessibility ──
+ // The terminal shipped with no accessible names anywhere; screen readers
+ // announced every one of these as an unnamed button.
+ refresh_btn_->setAccessibleName(tr("Refresh all market panels"));
+ refresh_btn_->setToolTip(tr("Refresh all market panels (F5)"));
+ auto_btn_->setAccessibleName(tr("Toggle auto-refresh"));
+ auto_btn_->setToolTip(tr("Toggle auto-refresh (F9)"));
+ interval_combo_->setAccessibleName(tr("Auto-refresh interval"));
+ interval_combo_->setToolTip(tr("Auto-refresh interval"));
+ add_panel_btn_->setAccessibleName(tr("Add a market panel"));
+ reset_btn_->setAccessibleName(tr("Reset all panels to defaults"));
+ status_label_->setAccessibleName(tr("Refresh status"));
+ last_upd_label_->setAccessibleName(tr("Last update time"));
+ session_label_->setAccessibleName(tr("US market session"));
+
+ QWidget* chain[] = {refresh_btn_, auto_btn_, interval_combo_, add_panel_btn_, reset_btn_};
+ for (int i = 1; i < 5; ++i)
+ setTabOrder(chain[i - 1], chain[i]);
+
return w;
}
@@ -582,13 +632,29 @@ void MarketsScreen::hideEvent(QHideEvent* event) {
// Refresh
// ---------------------------------------------------------------------------
+void MarketsScreen::abort_refresh_cycle() {
+ refresh_in_progress_ = false;
+ pending_refreshes_ = 0;
+ refresh_timeout_->stop();
+ if (refresh_counter_) {
+ // Dropping the context object retires this cycle. The
+ // `counter != refresh_counter_` guard in the slot makes any callback
+ // that lands before deleteLater() runs a no-op (P13: never `delete`
+ // a QObject from inside signal delivery).
+ refresh_counter_->deleteLater();
+ refresh_counter_ = nullptr;
+ }
+}
+
void MarketsScreen::refresh_all() {
if (refresh_in_progress_)
return;
if (panels_.isEmpty())
return;
+
+ abort_refresh_cycle(); // clear any leftovers from a previous cycle
refresh_in_progress_ = true;
- pending_refreshes_ = panels_.size();
+ pending_refreshes_ = static_cast<int>(panels_.size());
status_state_ = StatusState::Loading;
if (status_label_) {
@@ -598,17 +664,24 @@ void MarketsScreen::refresh_all() {
refresh_timeout_->start();
- auto* counter = new QObject(this);
+ refresh_counter_ = new QObject(this);
+ QObject* counter = refresh_counter_;
+ // Wire every panel BEFORE kicking any of them: MarketPanel::refresh()
+ // emits refresh_finished() synchronously for a symbol-less panel, and
+ // with connect-after-refresh that signal was missed — the counter then
+ // never drained and the badge sat on LOADING until the 10 s timeout.
for (auto* p : panels_) {
- p->refresh();
connect(
p, &MarketPanel::refresh_finished, counter,
[this, counter]() {
+ if (counter != refresh_counter_)
+ return; // stale cycle
if (--pending_refreshes_ > 0)
return;
refresh_timeout_->stop();
refresh_in_progress_ = false;
last_refresh_time_ = QDateTime::currentDateTime();
+ refresh_counter_ = nullptr;
counter->deleteLater();
status_state_ = StatusState::Ready;
if (status_label_) {
@@ -623,6 +696,8 @@ void MarketsScreen::refresh_all() {
},
Qt::SingleShotConnection);
}
+ for (auto* p : panels_)
+ p->refresh();
}
// ---------------------------------------------------------------------------
diff --git a/fincept-qt/src/screens/markets/MarketsScreen.h b/fincept-qt/src/screens/markets/MarketsScreen.h
index bbf77d2c0..fa70db79e 100644
--- a/fincept-qt/src/screens/markets/MarketsScreen.h
+++ b/fincept-qt/src/screens/markets/MarketsScreen.h
@@ -94,6 +94,12 @@ class MarketsScreen : public QWidget {
QTimer* clock_timer_ = nullptr;
QTimer* refresh_timeout_ = nullptr;
+ /// Lifetime guard for the per-refresh `refresh_finished` connections.
+ /// Destroying it disconnects every in-flight panel callback, so a cycle
+ /// that timed out cannot decrement the *next* cycle's counter.
+ QObject* refresh_counter_ = nullptr;
+ void abort_refresh_cycle();
+
// State
bool refresh_in_progress_ = false;
bool auto_update_ = true;
diff --git a/fincept-qt/src/screens/mcp_servers/McpServersScreen.h b/fincept-qt/src/screens/mcp_servers/McpServersScreen.h
index ab0213eba..374e842ae 100644
--- a/fincept-qt/src/screens/mcp_servers/McpServersScreen.h
+++ b/fincept-qt/src/screens/mcp_servers/McpServersScreen.h
@@ -7,6 +7,7 @@
#include <QLineEdit>
#include <QListWidget>
#include <QPushButton>
+#include <QSet>
#include <QStackedWidget>
#include <QTableWidget>
#include <QVBoxLayout>
@@ -32,14 +33,8 @@ class McpServersScreen : public QWidget, public IStatefulScreen {
private slots:
void on_view_changed(int view);
void on_install_server(int index); // from marketplace catalog
- void on_start_server();
- void on_stop_server();
- void on_remove_server();
- void on_toggle_autostart();
- void on_server_selected(QListWidgetItem* item); // kept for compat
void on_refresh();
void on_search_changed(const QString& text);
- void on_view_logs();
void on_add_server();
void on_tool_enabled_changed(int row, int col);
@@ -65,10 +60,18 @@ class McpServersScreen : public QWidget, public IStatefulScreen {
/// Builds a self-contained server card for the Installed view.
QWidget* build_server_card(const fincept::mcp::McpServerConfig& s);
+ /// Show the exact command line a server will execute and ask for consent.
+ /// Returns true if the launch may proceed. Asked once per server per
+ /// session — an MCP server is an arbitrary local process that the AI can
+ /// then call, so the first launch is an explicit decision, not a side
+ /// effect of clicking a toggle.
+ bool confirm_server_launch(const fincept::mcp::McpServerConfig& s);
+
// State
int active_view_ = 0;
bool loaded_ = false;
- QString selected_server_id_;
+ /// Server ids whose command line the user has already approved this session.
+ QSet<QString> launch_approved_;
// Header
QLabel* header_title_ = nullptr;
diff --git a/fincept-qt/src/screens/mcp_servers/McpServersScreen_Actions.cpp b/fincept-qt/src/screens/mcp_servers/McpServersScreen_Actions.cpp
index d7949a63c..c07a39d7c 100644
--- a/fincept-qt/src/screens/mcp_servers/McpServersScreen_Actions.cpp
+++ b/fincept-qt/src/screens/mcp_servers/McpServersScreen_Actions.cpp
@@ -45,125 +45,9 @@ using namespace fincept::ui;
static const QList<fincept::mcp::MarketplaceEntry>& g_catalog = fincept::mcp::marketplace_catalog();
-[[maybe_unused]] inline QString kStyle() {
- return QString(
-
- // Screen / header
- "#mcpScreen { background: %1; }"
- "#mcpHeader { background: %2; border-bottom: 2px solid %3; }"
- "#mcpHeaderTitle { color:%4; font-weight:700; background:transparent; }"
-
- // Tab buttons
- "#mcpViewBtn { background:transparent; color:%5; border:1px solid %8; "
- " font-weight:700; padding:4px 14px; }"
- "#mcpViewBtn:hover { color:%4; border-color:%9; }"
- "#mcpViewBtn[active=\"true\"] { background:%3; color:%1; border-color:%3; }"
-
- // Search / refresh
- "#mcpSearchInput { background:%1; color:%4; border:1px solid %8; "
- " padding:4px 8px; min-width:200px; }"
- "#mcpSearchInput:focus { border-color:%9; }"
- "#mcpRefreshBtn { background:%7; color:%5; border:1px solid %8; "
- " padding:4px 10px; font-weight:700; }"
- "#mcpRefreshBtn:hover { color:%4; }"
-
- // ── Marketplace cards ──
- "#mktCard { background:%7; border:1px solid %8; min-height:130px; }"
- "#mktCard:hover { border-color:%9; }"
- "#mktCardName { color:%4; font-weight:700; background:transparent; }"
- "#mktCardDesc { color:%5; background:transparent; }"
- "#mktCardCmd { color:%13; font-family:monospace; background:transparent; }"
- "#mktCardEnv { color:%3; background:transparent; }"
- "#mktCatBadge { color:%3; font-weight:700; "
- " background:rgba(217,119,6,0.12); padding:1px 6px; border:1px solid rgba(217,119,6,0.3); }"
- "#mktAddBtn { background:%3; color:%1; border:none; padding:5px 16px; "
- " font-weight:700; }"
- "#mktAddBtn:hover { background:%10; }"
- "#mktInstalledBadge { color:%6; font-weight:700; "
- " background:rgba(22,163,74,0.12); padding:5px 12px; border:1px solid rgba(22,163,74,0.3); }"
-
- // Category filter sidebar
- "#catList { background:%2; border:none; outline:none; }"
- "#catList::item { color:%5; font-weight:700; padding:6px 12px; }"
- "#catList::item:hover { color:%4; background:%12; }"
- "#catList::item:selected { color:%3; background:rgba(217,119,6,0.1); "
- " border-left:2px solid %3; }"
-
- // ── Installed server cards ──
- "#srvCard { background:%7; border:1px solid %8; margin:4px 0px; }"
- "#srvCard:hover { border-color:%9; }"
- "#srvCardName { color:%4; font-weight:700; background:transparent; }"
- "#srvCardDesc { color:%5; background:transparent; }"
- "#srvCardCmd { color:%13; font-family:monospace; background:transparent; }"
- "#srvCardCat { color:%5; background:transparent; }"
- "#pillRunning { color:%6; font-weight:700; "
- " background:rgba(22,163,74,0.15); padding:2px 10px; "
- " border:1px solid rgba(22,163,74,0.4); }"
- "#pillStopped { color:%14; font-weight:700; "
- " background:rgba(220,38,38,0.10); padding:2px 10px; "
- " border:1px solid rgba(220,38,38,0.4); }"
- "#pillError { color:%14; font-weight:700; "
- " background:rgba(220,38,38,0.10); padding:2px 10px; "
- " border:1px solid rgba(220,38,38,0.4); }"
- "#pillAutoOn { color:%6; background:transparent; }"
- "#pillAutoOff { color:%11; background:transparent; }"
-
- // Inline card buttons
- "#cardToggleOn { background:rgba(22,163,74,0.15); color:%6; "
- " border:1px solid rgba(22,163,74,0.5); "
- " padding:4px 12px; font-weight:700; }"
- "#cardToggleOn:hover { background:rgba(22,163,74,0.25); }"
- "#cardToggleOff { background:%7; color:%5; border:1px solid %8; "
- " padding:4px 12px; font-weight:700; }"
- "#cardToggleOff:hover { color:%4; border-color:%9; }"
- "#cardLogsBtn { background:transparent; color:%5; border:1px solid %8; "
- " padding:4px 12px; font-weight:700; }"
- "#cardLogsBtn:hover { color:%4; }"
- "#cardRemoveBtn { background:transparent; color:%14; border:1px solid %14; "
- " padding:4px 12px; font-weight:700; }"
- "#cardRemoveBtn:hover { background:rgba(220,38,38,0.12); }"
-
- // Add server button (full-width sticky)
- "#addSrvBtn { background:%3; color:%1; border:none; "
- " padding:8px; font-weight:700; }"
- "#addSrvBtn:hover { background:%10; }"
-
- // Log expander inside card
- "QTextEdit { background:%1; color:%13; border:none; font-family:monospace; }"
-
- // Tools table
- "QTableWidget { background:%1; color:%4; border:none; gridline-color:%8; }"
- "QTableWidget::item { padding:2px 6px; border-bottom:1px solid %8; }"
- "QHeaderView::section { background:%2; color:%5; border:none; "
- " border-bottom:1px solid %8; border-right:1px solid %8; "
- " padding:4px 6px; font-weight:700; }"
-
- // Status bar
- "#mcpStatusBar { background:%2; border-top:1px solid %8; }"
- "#mcpStatusText { color:%5; background:transparent; }"
- "#mcpStatusHighlight { color:%13; background:transparent; }"
-
- // Scroll
- "QScrollBar:vertical { background:%1; width:6px; }"
- "QScrollBar::handle:vertical { background:%8; min-height:20px; }"
- "QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical { height:0; }"
- "QScrollArea { border:none; background:transparent; }")
- .arg(colors::BG_BASE()) // %1
- .arg(colors::BG_RAISED()) // %2
- .arg(colors::AMBER()) // %3
- .arg(colors::TEXT_PRIMARY()) // %4
- .arg(colors::TEXT_SECONDARY()) // %5
- .arg(colors::POSITIVE()) // %6
- .arg(colors::BG_SURFACE()) // %7
- .arg(colors::BORDER_DIM()) // %8
- .arg(colors::BORDER_BRIGHT()) // %9
- .arg(colors::AMBER_DIM()) // %10
- .arg(colors::TEXT_DIM()) // %11
- .arg(colors::BG_HOVER()) // %12
- .arg(colors::CYAN()) // %13
- .arg(colors::NEGATIVE()) // %14
- ;
-}
+// NOTE: the screen stylesheet (kStyle) lives in McpServersScreen.cpp and is
+// applied once to the whole screen. This translation unit used to carry a
+// byte-identical [[maybe_unused]] copy (~120 lines) that nothing referenced.
} // namespace
@@ -172,6 +56,56 @@ namespace fincept::screens {
using namespace fincept::mcp;
using namespace fincept::ui;
+namespace {
+
+/// Split a command-line argument string the way a shell would: whitespace
+/// separates, single/double quotes group. `args_edit->text().split(' ')` broke
+/// every path containing a space (e.g. --dir "C:\Program Files\x").
+QStringList split_args(const QString& text) {
+ QStringList out;
+ QString current;
+ QChar quote;
+ bool in_token = false;
+ for (const QChar c : text) {
+ if (!quote.isNull()) {
+ if (c == quote)
+ quote = QChar();
+ else
+ current += c;
+ continue;
+ }
+ if (c == QLatin1Char('"') || c == QLatin1Char('\'')) {
+ quote = c;
+ in_token = true;
+ continue;
+ }
+ if (c.isSpace()) {
+ if (in_token) {
+ out << current;
+ current.clear();
+ in_token = false;
+ }
+ continue;
+ }
+ current += c;
+ in_token = true;
+ }
+ if (in_token)
+ out << current;
+ return out;
+}
+
+/// Environment variable names that should never be echoed on screen.
+bool env_key_is_secret(const QString& key) {
+ const QString k = key.toUpper();
+ return k.contains(QLatin1String("KEY")) || k.contains(QLatin1String("TOKEN")) ||
+ k.contains(QLatin1String("SECRET")) || k.contains(QLatin1String("PASSWORD")) ||
+ k.contains(QLatin1String("CREDENTIAL")) || k.contains(QLatin1String("AUTH")) ||
+ k.contains(QLatin1String("DSN")) || k.contains(QLatin1String("CONNECTION_STRING"));
+}
+
+} // namespace
+
void McpServersScreen::on_view_changed(int view) {
active_view_ = view;
view_stack_->setCurrentIndex(view);
@@ -225,17 +159,47 @@ void McpServersScreen::on_install_server(int index) {
for (int ki = 0; ki < e.env_keys.size(); ++ki) {
const QString& key = e.env_keys[ki];
auto* field = new QLineEdit;
- if (ki < e.env_placeholders.size()) {
+ const bool secret = env_key_is_secret(key);
+ if (secret) {
+ // These are almost always API keys; don't render them in the
+ // clear over the user's shoulder. Toggle reveals on demand.
+ field->setEchoMode(QLineEdit::Password);
+ field->setPlaceholderText(tr("Enter %1").arg(key));
+ } else if (ki < e.env_placeholders.size()) {
// Pre-fill with sample so user edits in-place rather than typing blind
field->setText(e.env_placeholders[ki]);
field->selectAll(); // highlight so first keystroke replaces it
} else {
field->setPlaceholderText(tr("Enter %1").arg(key));
}
+ field->setAccessibleName(key);
// env-var key (e.g. "OPENAI_API_KEY") is the API contract — pass through verbatim.
- form->addRow(key, field);
+ if (secret) {
+ auto* row = new QWidget(dlg);
+ auto* rl = new QHBoxLayout(row);
+ rl->setContentsMargins(0, 0, 0, 0);
+ rl->setSpacing(6);
+ rl->addWidget(field, 1);
+ auto* reveal = new QPushButton(tr("SHOW"), row);
+ reveal->setCheckable(true);
+ reveal->setCursor(Qt::PointingHandCursor);
+ reveal->setAccessibleName(tr("Reveal %1").arg(key));
+ QObject::connect(reveal, &QPushButton::toggled, field, [field, reveal](bool on) {
+ field->setEchoMode(on ? QLineEdit::Normal : QLineEdit::Password);
+ reveal->setText(on ? QObject::tr("HIDE") : QObject::tr("SHOW"));
+ });
+ rl->addWidget(reveal);
+ form->addRow(key, row);
+ } else {
+ form->addRow(key, field);
+ }
env_fields.append({key, field});
}
+ auto* env_note = new QLabel(tr("Values are stored locally and handed to the server process as environment "
+ "variables."));
+ env_note->setWordWrap(true);
+ env_note->setStyleSheet(QString("color:%1;font-size:9px;").arg(colors::TEXT_DIM()));
+ form->addRow(env_note);
}
// Combo items stay as API keys (saved to McpServerConfig.category).
@@ -268,7 +232,7 @@ void McpServersScreen::on_install_server(int index) {
cfg.name = name;
cfg.description = desc_edit->text().trimmed();
cfg.command = cmd_edit->text().trimmed();
- cfg.args = args_edit->text().trimmed().split(' ', Qt::SkipEmptyParts);
+ cfg.args = split_args(args_edit->text().trimmed());
cfg.category = cat_combo->currentText();
cfg.enabled = true;
cfg.auto_start = autostart_check->isChecked();
@@ -278,95 +242,39 @@ void McpServersScreen::on_install_server(int index) {
cfg.env[key] = val;
}
+ // save_server() upserts on id, and the id is derived from the name — a
+ // second server called the same thing silently replaced the first one.
+ for (const auto& existing : McpManager::instance().get_servers()) {
+ if (existing.id != cfg.id)
+ continue;
+ if (QMessageBox::question(
+ this, tr("Replace Server"),
+ tr("A server named \"%1\" already exists and will be overwritten.\n\nContinue?").arg(existing.name),
+ QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel) != QMessageBox::Yes) {
+ dlg->deleteLater();
+ return;
+ }
+ break;
+ }
+
const auto r = McpManager::instance().save_server(cfg);
if (r.is_ok()) {
LOG_INFO("McpServers", "Added from catalog: " + name);
populate_marketplace();
on_view_changed(1);
} else {
- LOG_ERROR("McpServers", "Add failed: " + QString::fromStdString(r.error()));
+ const QString err = QString::fromStdString(r.error());
+ LOG_ERROR("McpServers", "Add failed: " + err);
+ QMessageBox::warning(this, tr("Add Server"), tr("Could not save \"%1\":\n\n%2").arg(name, err));
}
dlg->deleteLater();
}
-void McpServersScreen::on_start_server() {
- if (selected_server_id_.isEmpty())
- return;
- const QString id = selected_server_id_;
- QPointer<McpServersScreen> self = this;
- (void)QtConcurrent::run([id, self]() {
- const auto result = McpManager::instance().start_server(id);
- QMetaObject::invokeMethod(
- self,
- [self, result]() {
- if (!self)
- return;
- if (result.is_err())
- LOG_ERROR("McpServers", "Start failed: " + QString::fromStdString(result.error()));
- self->refresh_installed();
- self->update_status_bar();
- },
- Qt::QueuedConnection);
- });
-}
-
-void McpServersScreen::on_stop_server() {
- if (selected_server_id_.isEmpty())
- return;
- const QString id = selected_server_id_;
- QPointer<McpServersScreen> self = this;
- (void)QtConcurrent::run([id, self]() {
- McpManager::instance().stop_server(id);
- QMetaObject::invokeMethod(
- self,
- [self]() {
- if (!self)
- return;
- self->refresh_installed();
- self->update_status_bar();
- },
- Qt::QueuedConnection);
- });
-}
-
-void McpServersScreen::on_remove_server() {
- if (selected_server_id_.isEmpty())
- return;
- const QString id = selected_server_id_;
- QString name;
- for (const auto& s : McpManager::instance().get_servers())
- if (s.id == id) {
- name = s.name;
- break;
- }
-
- QMessageBox mb(QMessageBox::Question, tr("Remove Server"), tr("Remove \"%1\"?\nThis cannot be undone.").arg(name),
- QMessageBox::Yes | QMessageBox::Cancel, this);
- if (mb.exec() != QMessageBox::Yes)
- return;
-
- McpManager::instance().stop_server(id);
- McpManager::instance().remove_server(id);
- selected_server_id_.clear();
- refresh_installed();
- update_status_bar();
-}
-
-void McpServersScreen::on_toggle_autostart() {
- if (selected_server_id_.isEmpty())
- return;
- auto servers = McpManager::instance().get_servers();
- for (auto& s : servers) {
- if (s.id != selected_server_id_)
- continue;
- s.auto_start = !s.auto_start;
- McpManager::instance().save_server(s);
- refresh_installed();
- break;
- }
-}
-
-void McpServersScreen::on_server_selected(QListWidgetItem*) {} // unused — cards are self-contained
+// NOTE: start / stop / remove / autostart are driven from the per-server card
+// (see build_server_card in McpServersScreen_Layout.cpp), which owns its own
+// server id. The screen-level variants of those slots were never connected and
+// keyed off a `selected_server_id_` that nothing ever assigned, so they have
+// been removed rather than left as decoys.
void McpServersScreen::on_refresh() {
if (active_view_ == 0)
@@ -398,10 +306,6 @@ void McpServersScreen::on_search_changed(const QString& text) {
refresh_installed();
}
-void McpServersScreen::on_view_logs() {
- // Handled inline per card — this slot kept for compat
-}
-
void McpServersScreen::on_add_server() {
auto* dlg = new QDialog(this);
dlg->setWindowTitle(tr("Add Custom MCP Server"));
@@ -429,15 +333,29 @@ void McpServersScreen::on_add_server() {
auto* env_edit = new QLineEdit;
// "KEY=value" is shell-syntax sample — keep ASCII so user knows the literal format.
env_edit->setPlaceholderText(tr("KEY=value KEY2=value2"));
+ env_edit->setEchoMode(QLineEdit::Password); // this field routinely holds API keys
+ env_edit->setAccessibleName(tr("Environment variables"));
form->addRow(tr("Env Vars"), env_edit);
+ auto* env_reveal = new QCheckBox(tr("Show env values"));
+ connect(env_reveal, &QCheckBox::toggled, env_edit,
+ [env_edit](bool on) { env_edit->setEchoMode(on ? QLineEdit::Normal : QLineEdit::Password); });
+ form->addRow("", env_reveal);
+
auto* cat_combo = new QComboBox;
cat_combo->addItems({"utilities", "developer", "database"});
form->addRow(tr("Category"), cat_combo);
auto* autostart_check = new QCheckBox(tr("Auto-start on launch"));
+ autostart_check->setToolTip(tr("Launches this server at terminal startup without asking for confirmation."));
form->addRow("", autostart_check);
+ auto* warn = new QLabel(tr("This runs a program on your machine and exposes its tools to the assistant. "
+ "Only add servers you trust."));
+ warn->setWordWrap(true);
+ warn->setStyleSheet(QString("color:%1;font-size:9px;").arg(colors::WARNING()));
+ form->addRow(warn);
+
auto* btns = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
connect(btns, &QDialogButtonBox::accepted, dlg, &QDialog::accept);
connect(btns, &QDialogButtonBox::rejected, dlg, &QDialog::reject);
@@ -459,24 +377,46 @@ void McpServersScreen::on_add_server() {
cfg.name = name;
cfg.description = desc_edit->text().trimmed();
cfg.command = cmd_edit->text().trimmed();
- cfg.args = args_edit->text().trimmed().split(' ', Qt::SkipEmptyParts);
+ cfg.args = split_args(args_edit->text().trimmed());
cfg.category = cat_combo->currentText();
cfg.enabled = true;
cfg.auto_start = autostart_check->isChecked();
- for (const auto& pair : env_edit->text().trimmed().split(' ', Qt::SkipEmptyParts)) {
+ if (cfg.command.isEmpty()) {
+ QMessageBox::warning(this, tr("Add Server"), tr("A command is required — this is the program to run."));
+ dlg->deleteLater();
+ return;
+ }
+
+ // Quote-aware so a value containing spaces survives (KEY="a b c").
+ for (const auto& pair : split_args(env_edit->text().trimmed())) {
const int eq = pair.indexOf('=');
if (eq > 0)
cfg.env[pair.left(eq)] = pair.mid(eq + 1);
}
+ for (const auto& existing : McpManager::instance().get_servers()) {
+ if (existing.id != cfg.id)
+ continue;
+ if (QMessageBox::question(
+ this, tr("Replace Server"),
+ tr("A server named \"%1\" already exists and will be overwritten.\n\nContinue?").arg(existing.name),
+ QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel) != QMessageBox::Yes) {
+ dlg->deleteLater();
+ return;
+ }
+ break;
+ }
+
const auto r = McpManager::instance().save_server(cfg);
if (r.is_ok()) {
LOG_INFO("McpServers", "Added custom server: " + name);
refresh_installed();
update_status_bar();
} else {
- LOG_ERROR("McpServers", "Failed: " + QString::fromStdString(r.error()));
+ const QString err = QString::fromStdString(r.error());
+ LOG_ERROR("McpServers", "Failed: " + err);
+ QMessageBox::warning(this, tr("Add Server"), tr("Could not save \"%1\":\n\n%2").arg(name, err));
}
dlg->deleteLater();
}
diff --git a/fincept-qt/src/screens/mcp_servers/McpServersScreen_Layout.cpp b/fincept-qt/src/screens/mcp_servers/McpServersScreen_Layout.cpp
index 17961495d..cd5f2f3be 100644
--- a/fincept-qt/src/screens/mcp_servers/McpServersScreen_Layout.cpp
+++ b/fincept-qt/src/screens/mcp_servers/McpServersScreen_Layout.cpp
@@ -27,8 +27,10 @@
#include <QListWidget>
#include <QListWidgetItem>
#include <QMessageBox>
+#include <QPointer>
#include <QPushButton>
#include <QScrollArea>
+#include <QScrollBar>
#include <QSplitter>
#include <QStackedWidget>
#include <QStringList>
@@ -37,131 +39,16 @@
#include <QTextEdit>
#include <QToolButton>
#include <QVBoxLayout>
+#include <QtConcurrent/QtConcurrent>
namespace {
using namespace fincept::ui;
static const QList<fincept::mcp::MarketplaceEntry>& g_catalog = fincept::mcp::marketplace_catalog();
-[[maybe_unused]] inline QString kStyle() {
- return QString(
-
- // Screen / header
- "#mcpScreen { background: %1; }"
- "#mcpHeader { background: %2; border-bottom: 2px solid %3; }"
- "#mcpHeaderTitle { color:%4; font-weight:700; background:transparent; }"
-
- // Tab buttons
- "#mcpViewBtn { background:transparent; color:%5; border:1px solid %8; "
- " font-weight:700; padding:4px 14px; }"
- "#mcpViewBtn:hover { color:%4; border-color:%9; }"
- "#mcpViewBtn[active=\"true\"] { background:%3; color:%1; border-color:%3; }"
-
- // Search / refresh
- "#mcpSearchInput { background:%1; color:%4; border:1px solid %8; "
- " padding:4px 8px; min-width:200px; }"
- "#mcpSearchInput:focus { border-color:%9; }"
- "#mcpRefreshBtn { background:%7; color:%5; border:1px solid %8; "
- " padding:4px 10px; font-weight:700; }"
- "#mcpRefreshBtn:hover { color:%4; }"
-
- // ── Marketplace cards ──
- "#mktCard { background:%7; border:1px solid %8; min-height:130px; }"
- "#mktCard:hover { border-color:%9; }"
- "#mktCardName { color:%4; font-weight:700; background:transparent; }"
- "#mktCardDesc { color:%5; background:transparent; }"
- "#mktCardCmd { color:%13; font-family:monospace; background:transparent; }"
- "#mktCardEnv { color:%3; background:transparent; }"
- "#mktCatBadge { color:%3; font-weight:700; "
- " background:rgba(217,119,6,0.12); padding:1px 6px; border:1px solid rgba(217,119,6,0.3); }"
- "#mktAddBtn { background:%3; color:%1; border:none; padding:5px 16px; "
- " font-weight:700; }"
- "#mktAddBtn:hover { background:%10; }"
- "#mktInstalledBadge { color:%6; font-weight:700; "
- " background:rgba(22,163,74,0.12); padding:5px 12px; border:1px solid rgba(22,163,74,0.3); }"
-
- // Category filter sidebar
- "#catList { background:%2; border:none; outline:none; }"
- "#catList::item { color:%5; font-weight:700; padding:6px 12px; }"
- "#catList::item:hover { color:%4; background:%12; }"
- "#catList::item:selected { color:%3; background:rgba(217,119,6,0.1); "
- " border-left:2px solid %3; }"
-
- // ── Installed server cards ──
- "#srvCard { background:%7; border:1px solid %8; margin:4px 0px; }"
- "#srvCard:hover { border-color:%9; }"
- "#srvCardName { color:%4; font-weight:700; background:transparent; }"
- "#srvCardDesc { color:%5; background:transparent; }"
- "#srvCardCmd { color:%13; font-family:monospace; background:transparent; }"
- "#srvCardCat { color:%5; background:transparent; }"
- "#pillRunning { color:%6; font-weight:700; "
- " background:rgba(22,163,74,0.15); padding:2px 10px; "
- " border:1px solid rgba(22,163,74,0.4); }"
- "#pillStopped { color:%14; font-weight:700; "
- " background:rgba(220,38,38,0.10); padding:2px 10px; "
- " border:1px solid rgba(220,38,38,0.4); }"
- "#pillError { color:%14; font-weight:700; "
- " background:rgba(220,38,38,0.10); padding:2px 10px; "
- " border:1px solid rgba(220,38,38,0.4); }"
- "#pillAutoOn { color:%6; background:transparent; }"
- "#pillAutoOff { color:%11; background:transparent; }"
-
- // Inline card buttons
- "#cardToggleOn { background:rgba(22,163,74,0.15); color:%6; "
- " border:1px solid rgba(22,163,74,0.5); "
- " padding:4px 12px; font-weight:700; }"
- "#cardToggleOn:hover { background:rgba(22,163,74,0.25); }"
- "#cardToggleOff { background:%7; color:%5; border:1px solid %8; "
- " padding:4px 12px; font-weight:700; }"
- "#cardToggleOff:hover { color:%4; border-color:%9; }"
- "#cardLogsBtn { background:transparent; color:%5; border:1px solid %8; "
- " padding:4px 12px; font-weight:700; }"
- "#cardLogsBtn:hover { color:%4; }"
- "#cardRemoveBtn { background:transparent; color:%14; border:1px solid %14; "
- " padding:4px 12px; font-weight:700; }"
- "#cardRemoveBtn:hover { background:rgba(220,38,38,0.12); }"
-
- // Add server button (full-width sticky)
- "#addSrvBtn { background:%3; color:%1; border:none; "
- " padding:8px; font-weight:700; }"
- "#addSrvBtn:hover { background:%10; }"
-
- // Log expander inside card
- "QTextEdit { background:%1; color:%13; border:none; font-family:monospace; }"
-
- // Tools table
- "QTableWidget { background:%1; color:%4; border:none; gridline-color:%8; }"
- "QTableWidget::item { padding:2px 6px; border-bottom:1px solid %8; }"
- "QHeaderView::section { background:%2; color:%5; border:none; "
- " border-bottom:1px solid %8; border-right:1px solid %8; "
- " padding:4px 6px; font-weight:700; }"
-
- // Status bar
- "#mcpStatusBar { background:%2; border-top:1px solid %8; }"
- "#mcpStatusText { color:%5; background:transparent; }"
- "#mcpStatusHighlight { color:%13; background:transparent; }"
-
- // Scroll
- "QScrollBar:vertical { background:%1; width:6px; }"
- "QScrollBar::handle:vertical { background:%8; min-height:20px; }"
- "QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical { height:0; }"
- "QScrollArea { border:none; background:transparent; }")
- .arg(colors::BG_BASE()) // %1
- .arg(colors::BG_RAISED()) // %2
- .arg(colors::AMBER()) // %3
- .arg(colors::TEXT_PRIMARY()) // %4
- .arg(colors::TEXT_SECONDARY()) // %5
- .arg(colors::POSITIVE()) // %6
- .arg(colors::BG_SURFACE()) // %7
- .arg(colors::BORDER_DIM()) // %8
- .arg(colors::BORDER_BRIGHT()) // %9
- .arg(colors::AMBER_DIM()) // %10
- .arg(colors::TEXT_DIM()) // %11
- .arg(colors::BG_HOVER()) // %12
- .arg(colors::CYAN()) // %13
- .arg(colors::NEGATIVE()) // %14
- ;
-}
+// NOTE: the screen stylesheet (kStyle) lives in McpServersScreen.cpp and is
+// applied once to the whole screen. This translation unit used to carry a
+// byte-identical [[maybe_unused]] copy (~120 lines) that nothing referenced.
} // namespace
@@ -202,6 +89,8 @@ QWidget* McpServersScreen::create_header() {
search_input_ = new QLineEdit;
search_input_->setObjectName("mcpSearchInput");
+ search_input_->setClearButtonEnabled(true);
+ search_input_->setAccessibleName(tr("Search servers and tools"));
connect(search_input_, &QLineEdit::textChanged, this, &McpServersScreen::on_search_changed);
hl->addWidget(search_input_);
@@ -210,6 +99,8 @@ QWidget* McpServersScreen::create_header() {
refresh_btn_ = new QPushButton;
refresh_btn_->setObjectName("mcpRefreshBtn");
refresh_btn_->setCursor(Qt::PointingHandCursor);
+ // No F5 shortcut — KeyConfigManager owns F5 globally (Qt::ApplicationShortcut).
+ refresh_btn_->setAccessibleName(tr("Refresh"));
connect(refresh_btn_, &QPushButton::clicked, this, &McpServersScreen::on_refresh);
hl->addWidget(refresh_btn_);
@@ -308,6 +199,7 @@ QWidget* McpServersScreen::create_installed_view() {
add_server_btn_->setObjectName("addSrvBtn");
add_server_btn_->setCursor(Qt::PointingHandCursor);
add_server_btn_->setFixedHeight(38);
+ add_server_btn_->setAccessibleName(tr("Add a custom MCP server"));
connect(add_server_btn_, &QPushButton::clicked, this, &McpServersScreen::on_add_server);
vl->addWidget(add_server_btn_);
@@ -509,6 +401,7 @@ void McpServersScreen::populate_marketplace() {
add_btn->setObjectName("mktAddBtn");
add_btn->setCursor(Qt::PointingHandCursor);
add_btn->setFixedWidth(56);
+ add_btn->setAccessibleName(tr("Add %1").arg(e.name));
connect(add_btn, &QPushButton::clicked, this, [this, i]() { on_install_server(i); });
bottom->addWidget(add_btn);
}
@@ -521,6 +414,43 @@ void McpServersScreen::populate_marketplace() {
}
}
+// ── Launch consent ────────────────────────────────────────────────────────────
+// Enabling a server spawns an arbitrary local process that the assistant can
+// then invoke as a tool. Show the exact command line (and the names — never the
+// values — of the environment variables it will receive) before the first
+// launch of each server in a session.
+
+bool McpServersScreen::confirm_server_launch(const McpServerConfig& s) {
+ if (launch_approved_.contains(s.id))
+ return true;
+
+ QString detail = s.command;
+ if (!s.args.isEmpty())
+ detail += QLatin1Char(' ') + s.args.join(QLatin1Char(' '));
+
+ QMessageBox box(this);
+ box.setIcon(QMessageBox::Warning);
+ box.setWindowTitle(tr("Start MCP Server"));
+ box.setText(tr("Start \"%1\"?").arg(s.name));
+ QString info = tr("This runs a program on your machine and exposes its tools to the assistant, "
+ "which can then call them without asking again.\n\nCommand:\n%1")
+ .arg(detail);
+ if (!s.env.isEmpty()) {
+ // Names only — never the values, which are usually API keys.
+ QStringList keys(s.env.keys());
+ keys.sort();
+ info += tr("\n\nEnvironment passed to it: %1").arg(keys.join(QStringLiteral(", ")));
+ }
+ box.setInformativeText(info);
+ box.setStandardButtons(QMessageBox::Yes | QMessageBox::Cancel);
+ box.setDefaultButton(QMessageBox::Cancel);
+ if (box.exec() != QMessageBox::Yes)
+ return false;
+
+ launch_approved_.insert(s.id);
+ return true;
+}
+
// ── build_server_card ─────────────────────────────────────────────────────────
// Enable toggle IS start/stop — no manual start/stop buttons.
// Any part of the app can call McpManager::call_external_tool() on enabled servers.
@@ -561,9 +491,11 @@ QWidget* McpServersScreen::build_server_card(const McpServerConfig& s) {
toggle_btn->setObjectName(running ? "cardToggleOn" : "cardToggleOff");
toggle_btn->setCursor(Qt::PointingHandCursor);
toggle_btn->setFixedWidth(110);
+ toggle_btn->setAccessibleName(running ? tr("Stop %1").arg(s.name) : tr("Start %1").arg(s.name));
if (starting)
toggle_btn->setEnabled(false);
- connect(toggle_btn, &QPushButton::clicked, this, [sid, self, running, toggle_btn]() {
+ const McpServerConfig cfg_copy = s; // for the launch-consent prompt
+ connect(toggle_btn, &QPushButton::clicked, this, [sid, self, running, toggle_btn, cfg_copy]() {
if (!self)
return;
if (running) {
@@ -572,6 +504,8 @@ QWidget* McpServersScreen::build_server_card(const McpServerConfig& s) {
self->refresh_installed();
self->update_status_bar();
} else {
+ if (!self->confirm_server_launch(cfg_copy))
+ return;
// Enable — start on background thread to avoid freezing the UI.
// start_server() blocks for process launch + handshake (can take 60s+).
toggle_btn->setText(tr("⟳ STARTING..."));
@@ -644,6 +578,7 @@ QWidget* McpServersScreen::build_server_card(const McpServerConfig& s) {
auto* logs_btn = new QPushButton(tr("LOGS"));
logs_btn->setObjectName("cardLogsBtn");
logs_btn->setCursor(Qt::PointingHandCursor);
+ logs_btn->setAccessibleName(tr("Show logs for %1").arg(s.name));
// Capture the "no output" message at click time via QPointer<this> so we
// can resolve it through this->tr() — log_view is a plain QTextEdit and
// doesn't carry McpServersScreen's translation context.
@@ -674,12 +609,47 @@ QWidget* McpServersScreen::build_server_card(const McpServerConfig& s) {
});
btns->addWidget(logs_btn);
+ // AUTO-START — previously only settable at Add time; the screen-level
+ // on_toggle_autostart() slot existed but was never connected to anything.
+ const bool auto_on = s.auto_start;
+ auto* auto_btn = new QPushButton(auto_on ? tr("AUTO-START: ON") : tr("AUTO-START: OFF"));
+ auto_btn->setObjectName(auto_on ? "cardToggleOn" : "cardToggleOff");
+ auto_btn->setCursor(Qt::PointingHandCursor);
+ auto_btn->setAccessibleName(tr("Toggle auto-start for %1").arg(s.name));
+ auto_btn->setToolTip(tr("When on, this server is launched automatically at terminal startup — without the "
+ "confirmation prompt."));
+ connect(auto_btn, &QPushButton::clicked, this, [sid, self, auto_on]() {
+ if (!self)
+ return;
+ if (!auto_on) {
+ // Turning it ON means the process starts unattended next launch.
+ if (QMessageBox::question(self, self->tr("Auto-start Server"),
+ self->tr("Launch this server automatically every time the terminal starts?\n\n"
+ "It will run without asking for confirmation."),
+ QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel) != QMessageBox::Yes)
+ return;
+ }
+ auto servers = McpManager::instance().get_servers();
+ for (auto& srv : servers) {
+ if (srv.id != sid)
+ continue;
+ srv.auto_start = !srv.auto_start;
+ const auto r = McpManager::instance().save_server(srv);
+ if (r.is_err())
+ LOG_ERROR("McpServers", "Autostart update failed: " + QString::fromStdString(r.error()));
+ break;
+ }
+ self->refresh_installed();
+ });
+ btns->addWidget(auto_btn);
+
btns->addStretch(1);
// REMOVE
auto* remove_btn = new QPushButton(tr("REMOVE"));
remove_btn->setObjectName("cardRemoveBtn");
remove_btn->setCursor(Qt::PointingHandCursor);
+ remove_btn->setAccessibleName(tr("Remove %1").arg(s.name));
connect(remove_btn, &QPushButton::clicked, this, [sid, self]() {
if (!self)
return;
diff --git a/fincept-qt/src/screens/news/NewsCommandBar.cpp b/fincept-qt/src/screens/news/NewsCommandBar.cpp
index 1899a8f3f..742529b09 100644
--- a/fincept-qt/src/screens/news/NewsCommandBar.cpp
+++ b/fincept-qt/src/screens/news/NewsCommandBar.cpp
@@ -7,7 +7,7 @@ namespace fincept::screens {
NewsCommandBar::NewsCommandBar(QWidget* parent) : QWidget(parent) {
setObjectName("newsCommandBar");
- setFixedHeight(60); // 32px command row + 28px intel strip
+ setFixedHeight(kBaseHeight); // 32px command row + 28px intel strip
auto* root = new QVBoxLayout(this);
root->setContentsMargins(0, 0, 0, 0);
@@ -16,11 +16,36 @@ NewsCommandBar::NewsCommandBar(QWidget* parent) : QWidget(parent) {
build_command_row(root);
build_intel_row(root);
- // Summary display label (hidden, shown below command bar)
- summary_label_ = new QLabel(this);
+ // AI-brief summary row. This used to be a bare child QLabel that was never
+ // added to a layout, so show_summary() painted it at (0,0) on top of the
+ // command row inside a widget with a hard 60px height — i.e. the AI brief
+ // was unreadable and undismissable. It now lives in the layout, with a
+ // close button, and the bar grows to fit while it is shown.
+ summary_row_ = new QWidget(this);
+ summary_row_->setObjectName("newsSummaryRow");
+ auto* srl = new QHBoxLayout(summary_row_);
+ srl->setContentsMargins(8, 4, 6, 4);
+ srl->setSpacing(6);
+
+ summary_label_ = new QLabel(summary_row_);
summary_label_->setObjectName("newsDetailAiSummary");
summary_label_->setWordWrap(true);
- summary_label_->hide();
+ summary_label_->setTextFormat(Qt::PlainText); // model output is untrusted text
+ summary_label_->setTextInteractionFlags(Qt::TextSelectableByMouse);
+ summary_label_->setAccessibleName(tr("AI headline brief"));
+ srl->addWidget(summary_label_, 1);
+
+ summary_close_btn_ = new QPushButton("x", summary_row_);
+ summary_close_btn_->setObjectName("newsDetailCloseBtn");
+ summary_close_btn_->setFixedSize(18, 18);
+ summary_close_btn_->setCursor(Qt::PointingHandCursor);
+ summary_close_btn_->setToolTip(tr("Dismiss the AI brief"));
+ summary_close_btn_->setAccessibleName(tr("Dismiss AI brief"));
+ connect(summary_close_btn_, &QPushButton::clicked, this, &NewsCommandBar::hide_summary);
+ srl->addWidget(summary_close_btn_, 0, Qt::AlignTop);
+
+ summary_row_->hide();
+ root->addWidget(summary_row_);
}
void NewsCommandBar::changeEvent(QEvent* event) {
@@ -41,6 +66,12 @@ void NewsCommandBar::retranslateUi() {
sources_btn_->setToolTip(tr("Manage RSS feed sources"));
if (summarize_btn_)
summarize_btn_->setToolTip(tr("AI Brief — summarize headlines"));
+ if (summary_close_btn_) {
+ summary_close_btn_->setToolTip(tr("Dismiss the AI brief"));
+ summary_close_btn_->setAccessibleName(tr("Dismiss AI brief"));
+ }
+ if (summary_label_)
+ summary_label_->setAccessibleName(tr("AI headline brief"));
// Pills (category/time/sort/view) and combo entries carry logical code
// values used in filter logic — intentionally not retranslated.
@@ -108,6 +139,8 @@ void NewsCommandBar::build_command_row(QVBoxLayout* root) {
search_input_->setPlaceholderText(tr("Search..."));
search_input_->setFixedWidth(120);
search_input_->setFixedHeight(20);
+ search_input_->setAccessibleName(tr("Search headlines"));
+ search_input_->setClearButtonEnabled(true);
hl->addWidget(search_input_);
connect(search_input_, &QLineEdit::textChanged, this, [this](const QString& text) { emit search_changed(text); });
@@ -118,6 +151,7 @@ void NewsCommandBar::build_command_row(QVBoxLayout* root) {
QStringList categories = {"ALL", "MKT", "EARN", "ECO", "TECH", "NRG", "CRPT", "GEO", "DEF"};
for (const auto& cat : categories) {
auto* btn = make_pill(cat, cat, hl);
+ btn->setAccessibleName(tr("Category %1").arg(cat));
category_btns_.append(btn);
connect(btn, &QPushButton::clicked, this, [this, cat]() {
active_category_ = cat;
@@ -136,15 +170,18 @@ void NewsCommandBar::build_command_row(QVBoxLayout* root) {
hl->addSpacing(2);
- // Time range pills
+ // Time range pills. NOTE: the loop variable was previously named `tr`,
+ // which shadows QObject::tr() inside the loop body — any tr("…") added
+ // there would have failed to compile in a confusing way.
QStringList time_ranges = {"1H", "6H", "24H", "48H", "7D", "30D"};
- for (const auto& tr : time_ranges) {
- auto* btn = make_pill(tr, tr, hl);
+ for (const auto& range : time_ranges) {
+ auto* btn = make_pill(range, range, hl);
+ btn->setAccessibleName(tr("Time range %1").arg(range));
time_btns_.append(btn);
- connect(btn, &QPushButton::clicked, this, [this, tr]() {
- active_time_ = tr;
+ connect(btn, &QPushButton::clicked, this, [this, range]() {
+ active_time_ = range;
update_pill_group(time_btns_, active_time_);
- emit time_range_changed(tr);
+ emit time_range_changed(range);
});
}
update_pill_group(time_btns_, active_time_);
@@ -276,9 +313,33 @@ void NewsCommandBar::build_command_row(QVBoxLayout* root) {
refresh_btn_ = new QPushButton(tr("REFRESH"), row);
refresh_btn_->setObjectName("newsCommandBarRefresh");
refresh_btn_->setFixedHeight(20);
+ refresh_btn_->setAccessibleName(tr("Refresh news feed"));
hl->addWidget(refresh_btn_);
connect(refresh_btn_, &QPushButton::clicked, this, &NewsCommandBar::refresh_clicked);
+ // Keyboard order across the bar: search → category pills → time pills →
+ // sort → view → controls. Without this, tab order followed construction
+ // order through the invisible scroll-area viewport.
+ QWidget* prev = search_input_;
+ for (auto* b : category_btns_) {
+ QWidget::setTabOrder(prev, b);
+ prev = b;
+ }
+ for (auto* b : time_btns_) {
+ QWidget::setTabOrder(prev, b);
+ prev = b;
+ }
+ for (QWidget* w : {static_cast<QWidget*>(sort_relevance_), static_cast<QWidget*>(sort_newest_),
+ static_cast<QWidget*>(view_wire_), static_cast<QWidget*>(view_clusters_),
+ static_cast<QWidget*>(lang_filter_combo_), static_cast<QWidget*>(variant_combo_),
+ static_cast<QWidget*>(summarize_btn_), static_cast<QWidget*>(refresh_combo_),
+ static_cast<QWidget*>(sources_btn_), static_cast<QWidget*>(refresh_btn_)}) {
+ if (w) {
+ QWidget::setTabOrder(prev, w);
+ prev = w;
+ }
+ }
+
scroll->setWidget(row);
root->addWidget(scroll);
}
@@ -470,14 +531,25 @@ void NewsCommandBar::set_unseen_count(int count) {
}
void NewsCommandBar::show_summary(const QString& summary) {
+ if (summary.trimmed().isEmpty()) {
+ hide_summary();
+ return;
+ }
summary_label_->setText(summary);
- summary_label_->show();
+ summary_row_->show();
+ // Grow the bar to fit the wrapped brief (capped so a long summary can't
+ // swallow the feed), then restore the fixed height on dismiss.
+ const int text_w = qMax(120, width() - 40);
+ const int text_h = summary_label_->heightForWidth(text_w);
+ setFixedHeight(kBaseHeight + qBound(20, text_h + 10, 140));
summarize_btn_->setText(tr("AI"));
summarize_btn_->setEnabled(true);
}
void NewsCommandBar::hide_summary() {
- summary_label_->hide();
+ if (summary_row_)
+ summary_row_->hide();
+ setFixedHeight(kBaseHeight);
}
void NewsCommandBar::set_summarizing(bool busy) {
diff --git a/fincept-qt/src/screens/news/NewsCommandBar.h b/fincept-qt/src/screens/news/NewsCommandBar.h
index 157467ab1..fa9ac2a3d 100644
--- a/fincept-qt/src/screens/news/NewsCommandBar.h
+++ b/fincept-qt/src/screens/news/NewsCommandBar.h
@@ -95,7 +95,12 @@ class NewsCommandBar : public QWidget {
QPushButton* drawer_btn_ = nullptr;
QPushButton* sources_btn_ = nullptr;
QPushButton* rtl_btn_ = nullptr;
+ // AI-brief row (label + dismiss button) — laid out under the intel strip.
+ QWidget* summary_row_ = nullptr;
QLabel* summary_label_ = nullptr;
+ QPushButton* summary_close_btn_ = nullptr;
+ /// Height with the summary row hidden: 32px command row + 28px intel strip.
+ static constexpr int kBaseHeight = 60;
QLabel* count_label_ = nullptr;
QLabel* alert_label_ = nullptr;
QLabel* unseen_label_ = nullptr;
diff --git a/fincept-qt/src/screens/news/NewsDetailPanel.cpp b/fincept-qt/src/screens/news/NewsDetailPanel.cpp
index 2de62c5b1..72696ba9b 100644
--- a/fincept-qt/src/screens/news/NewsDetailPanel.cpp
+++ b/fincept-qt/src/screens/news/NewsDetailPanel.cpp
@@ -13,12 +13,14 @@
#include <QFile>
#include <QFileInfo>
#include <QGridLayout>
+#include <QPointer>
#include <QRegularExpression>
#include <QScrollArea>
#include <QSizePolicy>
#include <QTextStream>
#include <QTimer>
#include <QUrl>
+#include <QtConcurrent>
namespace fincept::screens {
@@ -106,10 +108,14 @@ QWidget* NewsDetailPanel::build_content_view() {
layout->setContentsMargins(12, 10, 12, 10);
layout->setSpacing(8);
- // Headline
+ // Headline. Feed-supplied text is untrusted: QLabel's default Qt::AutoText
+ // renders anything that looks like markup as rich text, so a publisher (or
+ // an injected item) could restyle/mangle the panel or hide content behind
+ // tags. Every label that carries feed or model text is pinned to PlainText.
headline_label_ = new QLabel(content);
headline_label_->setObjectName("newsDetailHeadline");
headline_label_->setWordWrap(true);
+ headline_label_->setTextFormat(Qt::PlainText);
layout->addWidget(headline_label_);
// Badge row
@@ -148,10 +154,11 @@ QWidget* NewsDetailPanel::build_content_view() {
source_layout->addStretch();
layout->addWidget(source_row);
- // Summary
+ // Summary (untrusted feed text — see the headline note).
summary_label_ = new QLabel(content);
summary_label_->setObjectName("newsDetailSummary");
summary_label_->setWordWrap(true);
+ summary_label_->setTextFormat(Qt::PlainText);
layout->addWidget(summary_label_);
// Impact
@@ -273,14 +280,23 @@ QWidget* NewsDetailPanel::build_content_view() {
return;
translate_btn_->setText(tr("..."));
translate_btn_->setEnabled(false);
+ // The service callback is not lifetime-bound to this widget, so a raw
+ // [this] capture would dangle if the panel is destroyed while the
+ // translation is in flight (P8). Guard with QPointer, and pin the
+ // article id so a late result can't overwrite a different article.
+ QPointer<NewsDetailPanel> self = this;
+ const QString for_article = current_article_.id;
services::NewsNlpService::instance().translate_text(
current_article_.headline + "\n\n" + current_article_.summary, "en",
- [this](bool ok, QString translated, QString detected_lang) {
- translate_btn_->setText(tr("TRANSLATE"));
- translate_btn_->setEnabled(true);
- if (ok && !translated.isEmpty()) {
- summary_label_->setText(tr("[%1 -> EN] %2").arg(detected_lang, translated));
- }
+ [self, for_article](bool ok, QString translated, QString detected_lang) {
+ if (!self)
+ return;
+ self->translate_btn_->setText(self->tr("TRANSLATE"));
+ self->translate_btn_->setEnabled(true);
+ if (self->current_article_.id != for_article)
+ return; // user moved on to another article
+ if (ok && !translated.isEmpty())
+ self->summary_label_->setText(self->tr("[%1 -> EN] %2").arg(detected_lang, translated));
});
});
@@ -313,6 +329,7 @@ QWidget* NewsDetailPanel::build_content_view() {
ai_summary_ = new QLabel(analysis_section_);
ai_summary_->setObjectName("newsDetailAiSummary");
ai_summary_->setWordWrap(true);
+ ai_summary_->setTextFormat(Qt::PlainText); // model output is untrusted text
analysis_layout->addWidget(ai_summary_);
// Metric pills — laid out in a wrapping 2-column grid so a long urgency /
@@ -560,20 +577,38 @@ void NewsDetailPanel::show_article(const services::NewsArticle& article) {
analyze_btn_->setEnabled(true);
analyze_timeout_->stop();
- // Reflect saved state from DB
+ // Reflect saved state from DB. load_saved() is a SQLite read; running it
+ // synchronously here stuttered the UI on every article click (P1). Run it
+ // on a worker and post the answer back, guarded so a late result can't
+ // stamp the wrong article's bookmark state (P8).
+ bookmark_btn_->setChecked(false);
+ bookmark_btn_->setText(tr("BOOKMARK"));
{
- auto r = fincept::NewsArticleRepository::instance().load_saved();
- bool is_saved = false;
- if (r.is_ok()) {
- for (const auto& a : r.value()) {
- if (a.id == article.id) {
- is_saved = true;
- break;
+ QPointer<NewsDetailPanel> self = this;
+ const QString article_id = article.id;
+ (void)QtConcurrent::run([self, article_id]() {
+ auto r = fincept::NewsArticleRepository::instance().load_saved();
+ bool is_saved = false;
+ if (r.is_ok()) {
+ for (const auto& a : r.value()) {
+ if (a.id == article_id) {
+ is_saved = true;
+ break;
+ }
}
}
- }
- bookmark_btn_->setChecked(is_saved);
- bookmark_btn_->setText(is_saved ? tr("BOOKMARKED") : tr("BOOKMARK"));
+ if (!self)
+ return;
+ QMetaObject::invokeMethod(
+ self,
+ [self, article_id, is_saved]() {
+ if (!self || self->current_article_.id != article_id)
+ return;
+ self->bookmark_btn_->setChecked(is_saved);
+ self->bookmark_btn_->setText(is_saved ? self->tr("BOOKMARKED") : self->tr("BOOKMARK"));
+ },
+ Qt::QueuedConnection);
+ });
}
// Clear related and monitors
@@ -582,7 +617,7 @@ void NewsDetailPanel::show_article(const services::NewsArticle& article) {
}
void NewsDetailPanel::show_analysis(const services::NewsAnalysis& analysis) {
- analyze_btn_->setText("ANALYZE");
+ analyze_btn_->setText(tr("ANALYZE"));
analyze_btn_->setEnabled(true);
analyze_timeout_->stop();
@@ -635,6 +670,7 @@ void NewsDetailPanel::show_analysis(const services::NewsAnalysis& analysis) {
auto* lbl = new QLabel(QString("• %1").arg(point), analysis_section_);
lbl->setObjectName("newsDetailKeyPoint");
lbl->setWordWrap(true);
+ lbl->setTextFormat(Qt::PlainText);
key_points_layout_->addWidget(lbl);
}
// Hide the heading + container entirely when there's nothing to show, so
@@ -676,6 +712,7 @@ void NewsDetailPanel::show_analysis(const services::NewsAnalysis& analysis) {
auto* det = new QLabel(sig.details, row);
det->setObjectName("newsDetailRiskDetail");
det->setWordWrap(true);
+ det->setTextFormat(Qt::PlainText);
rl->addWidget(det);
}
risk_layout_->addWidget(row);
@@ -735,6 +772,7 @@ void NewsDetailPanel::show_analysis(const services::NewsAnalysis& analysis) {
auto* lbl = new QLabel(text, analysis_section_);
lbl->setObjectName("newsDetailEntity");
lbl->setWordWrap(true);
+ lbl->setTextFormat(Qt::PlainText);
ai_entities_layout_->addWidget(lbl);
};
for (const auto& o : analysis.organizations)
@@ -794,8 +832,11 @@ void NewsDetailPanel::show_related(const QVector<services::NewsArticle>& related
auto* btn = new QPushButton(related_section_);
btn->setObjectName("newsRelatedBtn");
btn->setCursor(Qt::PointingHandCursor);
- btn->setText(QString("%1 - %2").arg(article.source, article.headline.left(55)));
+ // Strip '&' so a headline containing one doesn't render as an
+ // accidental mnemonic underline (and swallow the character).
+ btn->setText(QString("%1 - %2").arg(article.source, article.headline.left(55)).replace('&', "&&"));
btn->setToolTip(article.headline);
+ btn->setAccessibleName(tr("Related article: %1").arg(article.headline.left(80)));
connect(btn, &QPushButton::clicked, this, [this, article]() { emit related_article_clicked(article); });
diff --git a/fincept-qt/src/screens/news/NewsFeedPanel.cpp b/fincept-qt/src/screens/news/NewsFeedPanel.cpp
index 48c57de9b..a726252e4 100644
--- a/fincept-qt/src/screens/news/NewsFeedPanel.cpp
+++ b/fincept-qt/src/screens/news/NewsFeedPanel.cpp
@@ -73,8 +73,23 @@ NewsFeedPanel::NewsFeedPanel(QWidget* parent) : QWidget(parent) {
root->addWidget(stack, 1);
+ // Accessibility — a news reader is exactly the surface a screen reader
+ // user needs named, and the list must be reachable by keyboard.
+ list_view_->setAccessibleName(tr("News feed"));
+ list_view_->setAccessibleDescription(
+ tr("Article list. Use the arrow keys to move, Enter to open the article in a browser."));
+ list_view_->setFocusPolicy(Qt::StrongFocus);
+ empty_state_->setAccessibleName(tr("Empty news feed"));
+ banner_widget_->setAccessibleName(tr("Breaking news banner"));
+
// Connect clicks
connect(list_view_, &QListView::clicked, this, &NewsFeedPanel::on_item_clicked);
+ // Keyboard: Enter/Return on the highlighted row opens it, same as a click.
+ connect(list_view_, &QListView::activated, this, &NewsFeedPanel::on_item_clicked);
+
+ // Preserve the reading position across model resets (see the header note).
+ connect(model_, &QAbstractItemModel::modelAboutToBeReset, this, &NewsFeedPanel::capture_scroll_anchor);
+ connect(model_, &QAbstractItemModel::modelReset, this, &NewsFeedPanel::restore_scroll_anchor);
// Scroll-to-bottom detection for lazy loading
connect(list_view_->verticalScrollBar(), &QScrollBar::valueChanged, this, &NewsFeedPanel::check_scroll_position);
@@ -241,6 +256,45 @@ void NewsFeedPanel::set_empty_state(bool empty) {
}
}
+void NewsFeedPanel::capture_scroll_anchor() {
+ anchor_article_id_.clear();
+ current_article_id_.clear();
+ anchor_was_at_top_ = true;
+ if (!list_view_ || !model_)
+ return;
+ auto* sb = list_view_->verticalScrollBar();
+ anchor_was_at_top_ = !sb || sb->value() <= 0;
+
+ // Anchor on whatever row is currently at the top of the viewport. Doing
+ // this by article id (not pixel offset) keeps the anchor correct even when
+ // rows are inserted above it by the refresh.
+ const QModelIndex top = list_view_->indexAt(QPoint(4, 4));
+ if (top.isValid())
+ anchor_article_id_ = model_->article_at(top.row()).id;
+
+ const QModelIndex cur = list_view_->currentIndex();
+ if (cur.isValid())
+ current_article_id_ = model_->article_at(cur.row()).id;
+}
+
+void NewsFeedPanel::restore_scroll_anchor() {
+ if (!list_view_ || !model_)
+ return;
+ // Restore the keyboard cursor first — setCurrentIndex() ensure-visible
+ // scrolls, so doing it after the anchor scroll would undo it.
+ if (!current_article_id_.isEmpty()) {
+ const auto cur = model_->index_for_article(current_article_id_);
+ if (cur.isValid())
+ list_view_->setCurrentIndex(cur);
+ }
+ // At the very top the user wants to see the newest items — leave it there.
+ if (anchor_was_at_top_ || anchor_article_id_.isEmpty())
+ return;
+ const auto anchor = model_->index_for_article(anchor_article_id_);
+ if (anchor.isValid())
+ list_view_->scrollTo(anchor, QAbstractItemView::PositionAtTop);
+}
+
void NewsFeedPanel::scroll_to(const QString& article_id) {
auto idx = model_->index_for_article(article_id);
if (idx.isValid())
diff --git a/fincept-qt/src/screens/news/NewsFeedPanel.h b/fincept-qt/src/screens/news/NewsFeedPanel.h
index f6b3bb487..b97a4e9ec 100644
--- a/fincept-qt/src/screens/news/NewsFeedPanel.h
+++ b/fincept-qt/src/screens/news/NewsFeedPanel.h
@@ -52,6 +52,14 @@ class NewsFeedPanel : public QWidget {
void remove_skeleton();
bool is_banner_duplicate(const QString& headline) const;
+ /// Capture / restore the reading position across a model reset. A feed
+ /// refresh (auto-refresh, live WS article, filter re-apply) resets the
+ /// model, which drops the QListView back to row 0 — scrolling a user away
+ /// from the item they were reading. We anchor on the article that was at
+ /// the top of the viewport and re-scroll to it once the reset completes.
+ void capture_scroll_anchor();
+ void restore_scroll_anchor();
+
/// Re-apply tr() lookups to every widget whose text we keep a handle to.
/// Called from changeEvent() on QEvent::LanguageChange.
void retranslateUi();
@@ -89,6 +97,11 @@ class NewsFeedPanel : public QWidget {
QWidget* empty_state_ = nullptr;
QLabel* empty_state_title_ = nullptr;
QLabel* empty_state_hint_ = nullptr;
+
+ // Scroll/selection preservation across model resets.
+ QString anchor_article_id_; // article at the top of the viewport
+ QString current_article_id_; // article under the keyboard cursor
+ bool anchor_was_at_top_ = true;
};
} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/news/NewsSidePanel.cpp b/fincept-qt/src/screens/news/NewsSidePanel.cpp
index 4d7f8f019..ba34ad41e 100644
--- a/fincept-qt/src/screens/news/NewsSidePanel.cpp
+++ b/fincept-qt/src/screens/news/NewsSidePanel.cpp
@@ -456,12 +456,14 @@ void NewsSidePanel::update_signals(const QVector<services::CorrelationSignal>& s
for (int i = 0; i < std::min(8, static_cast<int>(sigs.size())); ++i) {
const auto& sig = sigs[i];
- QString color = sig.severity == "critical"
- ? "" + QString(ui::colors::NEGATIVE()) + ""
- : (sig.severity == "high" ? "" + QString(ui::colors::WARNING()) + ""
- : "" + QString(ui::colors::WARNING()) + "");
+ // "critical" is red, everything else amber. The previous nested
+ // ternary had identical "high" and default branches wrapped in
+ // no-op "" + … + "" concatenations.
+ const QString color =
+ sig.severity == QLatin1String("critical") ? ui::colors::NEGATIVE() : ui::colors::WARNING();
auto* lbl = new QLabel(sig.detail.left(40), this);
lbl->setObjectName("newsDeviationCategory");
+ lbl->setTextFormat(Qt::PlainText);
lbl->setStyleSheet(QString("color: %1; background: transparent;").arg(color));
lbl->setToolTip(sig.detail);
signals_layout_->addWidget(lbl);
@@ -471,32 +473,32 @@ void NewsSidePanel::update_signals(const QVector<services::CorrelationSignal>& s
void NewsSidePanel::update_instability(const QString& country, const services::InstabilityScore& score) {
cii_section_->show();
+ // CRITICAL → red, HIGH/ELEVATED → amber, otherwise green. Was a four-way
+ // nested ternary with two identical branches and no-op string concats.
+ auto level_color = [](const QString& level) -> QString {
+ if (level == QLatin1String("CRITICAL"))
+ return ui::colors::NEGATIVE();
+ if (level == QLatin1String("HIGH") || level == QLatin1String("ELEVATED"))
+ return ui::colors::WARNING();
+ return ui::colors::POSITIVE();
+ };
+
// Check if already exists
for (int i = 0; i < cii_layout_->count(); ++i) {
auto* w = cii_layout_->itemAt(i)->widget();
if (w && w->property("country").toString() == country) {
auto* lbl = qobject_cast<QLabel*>(w);
if (lbl) {
- QString color = score.level == "CRITICAL"
- ? "" + QString(ui::colors::NEGATIVE()) + ""
- : (score.level == "HIGH"
- ? "" + QString(ui::colors::WARNING()) + ""
- : (score.level == "ELEVATED" ? "" + QString(ui::colors::WARNING()) + ""
- : "" + QString(ui::colors::POSITIVE()) + ""));
lbl->setText(QString("%1 %2 %3").arg(country, -4).arg(score.cii_score, 3).arg(score.level));
- lbl->setStyleSheet(QString("color: %1; font-weight: 700; background: transparent;").arg(color));
+ lbl->setStyleSheet(
+ QString("color: %1; font-weight: 700; background: transparent;").arg(level_color(score.level)));
}
return;
}
}
// New entry
- QString color =
- score.level == "CRITICAL"
- ? "" + QString(ui::colors::NEGATIVE()) + ""
- : (score.level == "HIGH" ? "" + QString(ui::colors::WARNING()) + ""
- : (score.level == "ELEVATED" ? "" + QString(ui::colors::WARNING()) + ""
- : "" + QString(ui::colors::POSITIVE()) + ""));
+ const QString color = level_color(score.level);
auto* lbl = new QLabel(QString("%1 %2 %3").arg(country, -4).arg(score.cii_score, 3).arg(score.level), this);
lbl->setObjectName("newsDeviationScore");
lbl->setProperty("country", country);
@@ -520,12 +522,12 @@ void NewsSidePanel::update_predictions(const QVector<services::PredictionMarket>
for (int i = 0; i < std::min(6, static_cast<int>(predictions.size())); ++i) {
const auto& pm = predictions[i];
- int pct = static_cast<int>(pm.yes_price * 100);
- QString color = pct >= 70 ? "" + QString(ui::colors::POSITIVE()) + ""
- : (pct <= 30 ? "" + QString(ui::colors::NEGATIVE()) + ""
- : "" + QString(ui::colors::WARNING()) + "");
+ const int pct = static_cast<int>(pm.yes_price * 100);
+ const QString color =
+ pct >= 70 ? ui::colors::POSITIVE() : (pct <= 30 ? ui::colors::NEGATIVE() : ui::colors::WARNING());
auto* lbl = new QLabel(QString("%1% %2").arg(pct).arg(pm.question.left(32)), this);
lbl->setObjectName("newsMonitorLabel");
+ lbl->setTextFormat(Qt::PlainText);
lbl->setStyleSheet(QString("color: %1; background: transparent;").arg(color));
lbl->setToolTip(pm.question);
predictions_layout_->addWidget(lbl);
diff --git a/fincept-qt/src/screens/news/NewsTickerStrip.cpp b/fincept-qt/src/screens/news/NewsTickerStrip.cpp
index 54d451252..9d99306bb 100644
--- a/fincept-qt/src/screens/news/NewsTickerStrip.cpp
+++ b/fincept-qt/src/screens/news/NewsTickerStrip.cpp
@@ -53,6 +53,19 @@ void NewsTickerStrip::set_articles(const QVector<services::NewsArticle>& breakin
}
offset_ = 0;
+ // resume() is called from the screen's showEvent, before any articles have
+ // arrived — with an empty entries_ it left the timer stopped, so the strip
+ // never scrolled for the whole session. Re-evaluate the timer whenever the
+ // content changes.
+ if (!paused_ && !entries_.isEmpty())
+ scroll_timer_.start();
+ else if (entries_.isEmpty())
+ scroll_timer_.stop();
+ setAccessibleName(tr("Breaking news ticker"));
+ setAccessibleDescription(
+ entries_.isEmpty()
+ ? tr("No breaking headlines")
+ : tr("%n breaking headline(s); click to open one", "", static_cast<int>(entries_.size())));
update();
}
diff --git a/fincept-qt/src/screens/news/dialogs/RssFeedEditDialog.cpp b/fincept-qt/src/screens/news/dialogs/RssFeedEditDialog.cpp
index b068cb36b..370cfb602 100644
--- a/fincept-qt/src/screens/news/dialogs/RssFeedEditDialog.cpp
+++ b/fincept-qt/src/screens/news/dialogs/RssFeedEditDialog.cpp
@@ -83,6 +83,23 @@ void RssFeedEditDialog::retranslateUi() {
// test_status_ reflects the last async test result — refreshed on next test.
}
+QNetworkAccessManager* RssFeedEditDialog::nam() {
+ // P10 — one manager per dialog, not one per request. Parented to the
+ // dialog so it dies with it.
+ if (!nam_)
+ nam_ = new QNetworkAccessManager(this);
+ return nam_;
+}
+
+QNetworkRequest RssFeedEditDialog::probe_request(const QString& url) const {
+ QNetworkRequest req((QUrl(url)));
+ req.setHeader(QNetworkRequest::UserAgentHeader, kBrowserUserAgent);
+ req.setRawHeader("Accept", "application/rss+xml, application/xml, text/xml, */*");
+ req.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy);
+ req.setTransferTimeout(kTestTimeoutMs);
+ return req;
+}
+
void RssFeedEditDialog::build_ui() {
auto* root = new QVBoxLayout(this);
root->setContentsMargins(16, 16, 16, 12);
@@ -118,6 +135,15 @@ void RssFeedEditDialog::build_ui() {
url_input_ = new QLineEdit(initial_.url, this);
url_input_->setPlaceholderText("https://example.com/rss.xml");
+ // Editing the URL invalidates any earlier probe. Without this, testing one
+ // URL, then typing a different one, and saving reused the *previous* URL's
+ // pass/fail verdict — so a broken feed could be saved as "validated".
+ connect(url_input_, &QLineEdit::textEdited, this, [this](const QString&) {
+ test_run_ = false;
+ last_test_ok_ = false;
+ if (test_status_)
+ test_status_->hide();
+ });
form->addRow(tr("URL"), url_input_);
category_combo_ = new QComboBox(this);
@@ -205,18 +231,10 @@ void RssFeedEditDialog::on_test() {
test_status_->setStyleSheet("color:#6b7280;");
test_status_->show();
- auto* nam = new QNetworkAccessManager(this);
- QNetworkRequest req((QUrl(url)));
- req.setHeader(QNetworkRequest::UserAgentHeader, kBrowserUserAgent);
- req.setRawHeader("Accept", "application/rss+xml, application/xml, text/xml, */*");
- req.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy);
- req.setTransferTimeout(kTestTimeoutMs);
-
QPointer<RssFeedEditDialog> self = this;
- auto* reply = nam->get(req);
- connect(reply, &QNetworkReply::finished, this, [self, reply, nam]() {
+ auto* reply = nam()->get(probe_request(url));
+ connect(reply, &QNetworkReply::finished, this, [self, reply]() {
reply->deleteLater();
- nam->deleteLater();
if (!self)
return;
@@ -284,17 +302,10 @@ void RssFeedEditDialog::try_accept() {
test_status_->setStyleSheet("color:#6b7280;");
test_status_->show();
- auto* nam = new QNetworkAccessManager(this);
- QNetworkRequest req((QUrl(f.url)));
- req.setHeader(QNetworkRequest::UserAgentHeader, kBrowserUserAgent);
- req.setRawHeader("Accept", "application/rss+xml, application/xml, text/xml, */*");
- req.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy);
- req.setTransferTimeout(kTestTimeoutMs);
QPointer<RssFeedEditDialog> self = this;
- auto* reply = nam->get(req);
- connect(reply, &QNetworkReply::finished, this, [self, reply, nam]() {
+ auto* reply = nam()->get(probe_request(f.url));
+ connect(reply, &QNetworkReply::finished, this, [self, reply]() {
reply->deleteLater();
- nam->deleteLater();
if (!self)
return;
self->test_btn_->setEnabled(true);
diff --git a/fincept-qt/src/screens/news/dialogs/RssFeedEditDialog.h b/fincept-qt/src/screens/news/dialogs/RssFeedEditDialog.h
index a35a6b55f..69fd7e966 100644
--- a/fincept-qt/src/screens/news/dialogs/RssFeedEditDialog.h
+++ b/fincept-qt/src/screens/news/dialogs/RssFeedEditDialog.h
@@ -7,6 +7,8 @@
#include <QFormLayout>
#include <QLabel>
#include <QLineEdit>
+#include <QNetworkAccessManager>
+#include <QNetworkRequest>
#include <QPushButton>
#include <QSpinBox>
@@ -39,6 +41,14 @@ class RssFeedEditDialog : public QDialog {
/// Called from changeEvent() on QEvent::LanguageChange.
void retranslateUi();
+ /// One QNetworkAccessManager for the whole dialog (P10) instead of a fresh
+ /// one per test request. Created lazily on first use.
+ QNetworkAccessManager* nam();
+ /// Build the shared feed-probe request for `url`.
+ QNetworkRequest probe_request(const QString& url) const;
+
+ QNetworkAccessManager* nam_ = nullptr;
+
services::RSSFeed initial_;
bool is_builtin_id_;
diff --git a/fincept-qt/src/screens/news/dialogs/RssFeedManagerDialog.cpp b/fincept-qt/src/screens/news/dialogs/RssFeedManagerDialog.cpp
index 83003a88e..c921afb5c 100644
--- a/fincept-qt/src/screens/news/dialogs/RssFeedManagerDialog.cpp
+++ b/fincept-qt/src/screens/news/dialogs/RssFeedManagerDialog.cpp
@@ -269,6 +269,13 @@ void RssFeedManagerDialog::on_toggle_enabled() {
reload_table();
}
+QNetworkAccessManager* RssFeedManagerDialog::nam() {
+ // P10 — one manager per dialog, not one per test click.
+ if (!nam_)
+ nam_ = new QNetworkAccessManager(this);
+ return nam_;
+}
+
void RssFeedManagerDialog::on_test_url() {
const int row = selected_row();
if (row < 0)
@@ -282,7 +289,6 @@ void RssFeedManagerDialog::on_test_url() {
test_btn_->setEnabled(false);
status_label_->setText(tr("Testing %1...").arg(rows_[row].feed.source));
- auto* nam = new QNetworkAccessManager(this);
QNetworkRequest req((QUrl(url)));
req.setHeader(QNetworkRequest::UserAgentHeader, kBrowserUserAgent);
req.setRawHeader("Accept", "application/rss+xml, application/xml, text/xml, */*");
@@ -290,10 +296,9 @@ void RssFeedManagerDialog::on_test_url() {
req.setTransferTimeout(6000);
QPointer<RssFeedManagerDialog> self = this;
- auto* reply = nam->get(req);
- connect(reply, &QNetworkReply::finished, this, [self, reply, nam]() {
+ auto* reply = nam()->get(req);
+ connect(reply, &QNetworkReply::finished, this, [self, reply]() {
reply->deleteLater();
- nam->deleteLater();
if (!self)
return;
self->test_btn_->setEnabled(true);
diff --git a/fincept-qt/src/screens/news/dialogs/RssFeedManagerDialog.h b/fincept-qt/src/screens/news/dialogs/RssFeedManagerDialog.h
index e7132d8bc..71fa9129e 100644
--- a/fincept-qt/src/screens/news/dialogs/RssFeedManagerDialog.h
+++ b/fincept-qt/src/screens/news/dialogs/RssFeedManagerDialog.h
@@ -4,6 +4,7 @@
#include <QDialog>
#include <QEvent>
#include <QLabel>
+#include <QNetworkAccessManager>
#include <QPushButton>
#include <QTableWidget>
#include <QVector>
@@ -58,6 +59,11 @@ class RssFeedManagerDialog : public QDialog {
QPushButton* close_btn_ = nullptr;
QLabel* status_label_ = nullptr;
+ /// One QNetworkAccessManager for the dialog's URL probes (P10) rather than
+ /// a fresh one per test click. Created lazily, parented to the dialog.
+ QNetworkAccessManager* nam();
+ QNetworkAccessManager* nam_ = nullptr;
+
QVector<services::NewsService::EditorFeed> rows_;
bool dirty_ = false;
};
diff --git a/fincept-qt/src/screens/node_editor/NodeEditorCommands.h b/fincept-qt/src/screens/node_editor/NodeEditorCommands.h
new file mode 100644
index 000000000..503dc5a61
--- /dev/null
+++ b/fincept-qt/src/screens/node_editor/NodeEditorCommands.h
@@ -0,0 +1,228 @@
+#pragma once
+//
+// NodeEditorCommands.h — QUndoCommand set for the node editor canvas.
+//
+// Header-only on purpose: it is included from NodeEditorScreen.cpp only, so it
+// needs no entry in the build's source list.
+//
+// ── Coverage contract ────────────────────────────────────────────────────────
+// The UNDO/REDO buttons and Ctrl+Z / Ctrl+Y cover every *structural* mutation of
+// the graph:
+//
+// • add node (palette drag, canvas context menu, paste, duplicate,
+// template load)
+// • remove node (Delete key, node context menu, properties DEL button)
+// • add edge (drag-to-connect, paste)
+// • remove edge (edge context menu, Delete on a selected edge)
+// • move node(s) (one command per drag, multi-select aware)
+// • replace graph (CLEAR, template load)
+//
+// Deliberately NOT on the stack: per-keystroke parameter and node-name edits
+// from the properties panel. Those fire on every character typed; putting them
+// on the stack would either flood it or require rebuilding the properties
+// editor on each merge, stealing focus mid-typing. Text edits are undone with
+// the field's own Ctrl+Z while it has focus.
+//
+// Every command holds value types (NodeDef / EdgeDef / WorkflowDef) plus a bare
+// NodeScene*. The scene outlives the stack: both are children of
+// NodeEditorScreen and the stack is constructed first, so it is destroyed first.
+
+#include "screens/node_editor/NodeEditorTypes.h"
+#include "screens/node_editor/canvas/NodeItem.h"
+#include "screens/node_editor/canvas/NodeScene.h"
+#include "services/workflow/NodeRegistry.h"
+
+#include <QCoreApplication>
+#include <QHash>
+#include <QPointF>
+#include <QSet>
+#include <QString>
+#include <QUndoCommand>
+#include <QVector>
+
+#include <utility>
+
+namespace fincept::workflow {
+
+namespace commands {
+
+/// Re-add a set of nodes (resolving their type from the registry) and then the
+/// edges between them. Shared by add/remove/undo paths.
+inline void apply_nodes(NodeScene* scene, const QVector<NodeDef>& nodes, const QVector<EdgeDef>& edges) {
+ if (!scene)
+ return;
+ auto& reg = NodeRegistry::instance();
+ for (const auto& nd : nodes) {
+ const auto* td = reg.find(nd.type);
+ if (td)
+ scene->add_node(nd, *td);
+ }
+ // Edges last: both endpoints must exist.
+ for (const auto& ed : edges)
+ scene->add_edge(ed);
+}
+
+inline void drop_nodes(NodeScene* scene, const QVector<NodeDef>& nodes) {
+ if (!scene)
+ return;
+ for (const auto& nd : nodes)
+ scene->remove_node(nd.id); // cascades its edges
+}
+
+/// Collect the edges that touch any node in `ids` (so a delete can be undone
+/// with its wiring intact).
+inline QVector<EdgeDef> edges_touching(NodeScene* scene, const QSet<QString>& ids) {
+ QVector<EdgeDef> out;
+ if (!scene)
+ return out;
+ const WorkflowDef wf = scene->serialize();
+ for (const auto& ed : wf.edges)
+ if (ids.contains(ed.source_node) || ids.contains(ed.target_node))
+ out.append(ed);
+ return out;
+}
+
+// ── Add nodes (+ their internal edges) ───────────────────────────────────────
+
+class AddNodesCommand : public QUndoCommand {
+ Q_DECLARE_TR_FUNCTIONS(AddNodesCommand)
+ public:
+ AddNodesCommand(NodeScene* scene, QVector<NodeDef> nodes, QVector<EdgeDef> edges, const QString& label)
+ : scene_(scene), nodes_(std::move(nodes)), edges_(std::move(edges)) {
+ setText(label);
+ }
+
+ void redo() override { apply_nodes(scene_, nodes_, edges_); }
+ void undo() override { drop_nodes(scene_, nodes_); }
+
+ private:
+ NodeScene* scene_ = nullptr;
+ QVector<NodeDef> nodes_;
+ QVector<EdgeDef> edges_;
+};
+
+// ── Remove nodes (+ every edge that touched them) ────────────────────────────
+
+class RemoveNodesCommand : public QUndoCommand {
+ Q_DECLARE_TR_FUNCTIONS(RemoveNodesCommand)
+ public:
+ RemoveNodesCommand(NodeScene* scene, QVector<NodeDef> nodes, QVector<EdgeDef> edges, const QString& label)
+ : scene_(scene), nodes_(std::move(nodes)), edges_(std::move(edges)) {
+ setText(label);
+ }
+
+ void redo() override { drop_nodes(scene_, nodes_); }
+ void undo() override { apply_nodes(scene_, nodes_, edges_); }
+
+ private:
+ NodeScene* scene_ = nullptr;
+ QVector<NodeDef> nodes_;
+ QVector<EdgeDef> edges_;
+};
+
+// ── Single edge add / remove ─────────────────────────────────────────────────
+
+class AddEdgeCommand : public QUndoCommand {
+ Q_DECLARE_TR_FUNCTIONS(AddEdgeCommand)
+ public:
+ AddEdgeCommand(NodeScene* scene, EdgeDef edge) : scene_(scene), edge_(std::move(edge)) {
+ setText(tr("Connect nodes"));
+ }
+ void redo() override {
+ if (scene_)
+ scene_->add_edge(edge_);
+ }
+ void undo() override {
+ if (scene_)
+ scene_->remove_edge(edge_.id);
+ }
+
+ private:
+ NodeScene* scene_ = nullptr;
+ EdgeDef edge_;
+};
+
+class RemoveEdgeCommand : public QUndoCommand {
+ Q_DECLARE_TR_FUNCTIONS(RemoveEdgeCommand)
+ public:
+ RemoveEdgeCommand(NodeScene* scene, EdgeDef edge) : scene_(scene), edge_(std::move(edge)) {
+ setText(tr("Delete connection"));
+ }
+ void redo() override {
+ if (scene_)
+ scene_->remove_edge(edge_.id);
+ }
+ void undo() override {
+ if (scene_)
+ scene_->add_edge(edge_);
+ }
+
+ private:
+ NodeScene* scene_ = nullptr;
+ EdgeDef edge_;
+};
+
+// ── Move node(s) ─────────────────────────────────────────────────────────────
+// One command per drag gesture, covering every node the drag moved (a
+// multi-select drag moves several items but only one receives the mouse events,
+// so the screen diffs a whole-scene position snapshot).
+
+class MoveNodesCommand : public QUndoCommand {
+ Q_DECLARE_TR_FUNCTIONS(MoveNodesCommand)
+ public:
+ MoveNodesCommand(NodeScene* scene, QHash<QString, QPointF> before, QHash<QString, QPointF> after)
+ : scene_(scene), before_(std::move(before)), after_(std::move(after)) {
+ setText(after_.size() > 1 ? tr("Move %1 nodes").arg(after_.size()) : tr("Move node"));
+ }
+
+ // The drag already left the nodes at `after_`, so the push-time redo() is a
+ // harmless re-assert of the same positions.
+ void redo() override { apply(after_); }
+ void undo() override { apply(before_); }
+
+ private:
+ void apply(const QHash<QString, QPointF>& positions) {
+ if (!scene_)
+ return;
+ for (auto it = positions.constBegin(); it != positions.constEnd(); ++it) {
+ if (auto* item = scene_->find_node(it.key()))
+ item->setPos(it.value()); // itemChange keeps NodeDef x/y and edges in sync
+ }
+ }
+
+ NodeScene* scene_ = nullptr;
+ QHash<QString, QPointF> before_;
+ QHash<QString, QPointF> after_;
+};
+
+// ── Whole-graph replacement (CLEAR, template load) ───────────────────────────
+
+class ReplaceGraphCommand : public QUndoCommand {
+ Q_DECLARE_TR_FUNCTIONS(ReplaceGraphCommand)
+ public:
+ ReplaceGraphCommand(NodeScene* scene, WorkflowDef before, WorkflowDef after, const QString& label)
+ : scene_(scene), before_(std::move(before)), after_(std::move(after)) {
+ setText(label);
+ }
+
+ // For the template path the scene already holds `after_`; deserializing it
+ // again rebuilds an identical graph, so push()'s implicit redo() is a no-op
+ // in effect.
+ void redo() override {
+ if (scene_)
+ scene_->deserialize(after_);
+ }
+ void undo() override {
+ if (scene_)
+ scene_->deserialize(before_);
+ }
+
+ private:
+ NodeScene* scene_ = nullptr;
+ WorkflowDef before_;
+ WorkflowDef after_;
+};
+
+} // namespace commands
+
+} // namespace fincept::workflow
diff --git a/fincept-qt/src/screens/node_editor/NodeEditorScreen.cpp b/fincept-qt/src/screens/node_editor/NodeEditorScreen.cpp
index 3cc4aa8f2..e8018c4c8 100644
--- a/fincept-qt/src/screens/node_editor/NodeEditorScreen.cpp
+++ b/fincept-qt/src/screens/node_editor/NodeEditorScreen.cpp
@@ -2,6 +2,8 @@
#include "core/logging/Logger.h"
#include "core/session/ScreenStateManager.h"
+#include "screens/node_editor/NodeEditorCommands.h"
+#include "screens/node_editor/canvas/EdgeItem.h"
#include "screens/node_editor/canvas/MiniMap.h"
#include "screens/node_editor/canvas/NodeCanvas.h"
#include "screens/node_editor/canvas/NodeItem.h"
@@ -114,30 +116,49 @@ void NodeEditorScreen::keyPressEvent(QKeyEvent* event) {
undo_stack_->redo();
event->accept();
} else if (event->key() == Qt::Key_Delete || event->key() == Qt::Key_Backspace) {
- // Delete selected nodes
+ // Delete selected nodes. Now undoable (RemoveNodesCommand restores the
+ // nodes AND every edge that touched them), so no confirmation prompt —
+ // Ctrl+Z is the recovery path.
QStringList ids;
for (auto* item : scene_->selectedItems()) {
if (auto* node = dynamic_cast<NodeItem*>(item))
ids.append(node->node_def().id);
}
- if (ids.isEmpty()) {
+ if (!ids.isEmpty()) {
+ push_remove_nodes(ids, ids.size() > 1 ? tr("Delete %1 nodes").arg(ids.size()) : tr("Delete node"));
event->accept();
return;
}
- // Confirm: deletion is NOT undoable (no QUndoCommand is pushed for it)
- // and the 30s autosave persists it, so an accidental Delete/Backspace
- // would silently and permanently lose the nodes and their connections.
- const auto ans = QMessageBox::question(
- this, tr("Delete Nodes"),
- tr("Delete %1 selected node(s) and their connections? This cannot be undone.").arg(ids.size()),
- QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
- if (ans != QMessageBox::Yes) {
- event->accept();
- return;
+ // Nothing but edges selected → delete those instead.
+ QStringList edge_ids;
+ for (auto* item : scene_->selectedItems()) {
+ if (auto* edge = dynamic_cast<EdgeItem*>(item))
+ edge_ids.append(edge->edge_id());
+ }
+ for (const auto& eid : edge_ids) {
+ const EdgeDef ed = scene_->edge_def(eid);
+ if (!ed.id.isEmpty())
+ undo_stack_->push(new commands::RemoveEdgeCommand(scene_, ed));
}
- for (const auto& id : ids)
- scene_->remove_node(id);
- properties_->clear();
+ event->accept();
+ } else if (event->matches(QKeySequence::Save)) {
+ on_save_workflow();
+ event->accept();
+ } else if (event->key() == Qt::Key_D && (event->modifiers() & Qt::ControlModifier)) {
+ // Ctrl+D — duplicate the selection (same offset/rename as the context menu).
+ QVector<NodeDef> copies;
+ for (auto* item : scene_->selectedItems()) {
+ auto* node = dynamic_cast<NodeItem*>(item);
+ if (!node)
+ continue;
+ NodeDef copy = node->node_def();
+ copy.id = QUuid::createUuid().toString(QUuid::WithoutBraces);
+ copy.x += 40;
+ copy.y += 40;
+ copy.name += " (copy)";
+ copies.append(copy);
+ }
+ push_add_nodes(copies, {}, tr("Duplicate %1 node(s)").arg(copies.size()));
event->accept();
} else if (event->matches(QKeySequence::SelectAll)) {
// Ctrl+A — select all nodes
@@ -171,6 +192,8 @@ void NodeEditorScreen::keyPressEvent(QKeyEvent* event) {
}
QMap<QString, QString> id_remap;
+ QVector<NodeDef> pasted_nodes;
+ QVector<EdgeDef> pasted_edges;
for (const auto& nd : clipboard_nodes_) {
NodeDef copy = nd;
QString new_id = QUuid::createUuid().toString(QUuid::WithoutBraces);
@@ -179,11 +202,7 @@ void NodeEditorScreen::keyPressEvent(QKeyEvent* event) {
copy.x += 40;
copy.y += 40;
copy.name = nd.name + " (copy)";
-
- auto& reg = NodeRegistry::instance();
- const auto* td = reg.find(copy.type);
- if (td)
- scene_->add_node(copy, *td);
+ pasted_nodes.append(copy);
}
for (const auto& ed : clipboard_edges_) {
EdgeDef copy = ed;
@@ -191,9 +210,11 @@ void NodeEditorScreen::keyPressEvent(QKeyEvent* event) {
copy.source_node = id_remap.value(ed.source_node);
copy.target_node = id_remap.value(ed.target_node);
if (!copy.source_node.isEmpty() && !copy.target_node.isEmpty())
- scene_->add_edge(copy);
+ pasted_edges.append(copy);
}
- LOG_INFO("NodeEditor", QString("Pasted %1 nodes").arg(clipboard_nodes_.size()));
+ // Single undoable step for the whole paste, wiring included.
+ push_add_nodes(pasted_nodes, pasted_edges, tr("Paste %1 node(s)").arg(pasted_nodes.size()));
+ LOG_INFO("NodeEditor", QString("Pasted %1 nodes").arg(pasted_nodes.size()));
event->accept();
} else {
QWidget::keyPressEvent(event);
@@ -269,11 +290,37 @@ void NodeEditorScreen::wire_signals() {
copy.x += 40;
copy.y += 40;
copy.name += " (copy)";
- auto& reg = NodeRegistry::instance();
- const auto* td = reg.find(copy.type);
- if (td)
- scene_->add_node(copy, *td);
+ push_add_nodes({copy}, {}, tr("Duplicate %1").arg(item->node_def().name));
});
+
+ // ── Undoable-intent signals from the canvas ────────────────────────────
+ // NodeScene announces user-initiated deletes/connects instead of applying
+ // them, so every structural mutation lands on the QUndoStack.
+ connect(scene_, &NodeScene::node_delete_requested, this, &NodeEditorScreen::on_delete_node);
+ connect(scene_, &NodeScene::edge_delete_requested, this, [this](const QString& edge_id) {
+ const EdgeDef ed = scene_->edge_def(edge_id);
+ if (ed.id.isEmpty()) {
+ scene_->remove_edge(edge_id); // dangling edge — drop it without history
+ return;
+ }
+ undo_stack_->push(new commands::RemoveEdgeCommand(scene_, ed));
+ });
+ connect(scene_, &NodeScene::edge_create_requested, this,
+ [this](const EdgeDef& ed) { undo_stack_->push(new commands::AddEdgeCommand(scene_, ed)); });
+ connect(scene_, &NodeScene::node_move_started, this, &NodeEditorScreen::begin_move_snapshot);
+ connect(scene_, &NodeScene::node_move_finished, this, &NodeEditorScreen::commit_move_snapshot);
+
+ // ── Node execution flags (SETTINGS block in the properties panel) ──────
+ connect(properties_, &NodePropertiesPanel::node_flag_changed, this,
+ [this](const QString& node_id, const QString& flag, bool value) {
+ auto* item = scene_->find_node(node_id);
+ if (!item)
+ return;
+ if (flag == QLatin1String("disabled"))
+ item->set_disabled(value);
+ else if (flag == QLatin1String("continue_on_fail"))
+ item->set_continue_on_fail(value);
+ });
connect(scene_, &NodeScene::node_execute_from_requested, this, [this](const QString& node_id) {
WorkflowDef wf = scene_->serialize();
if (wf.nodes.isEmpty())
@@ -327,6 +374,9 @@ void NodeEditorScreen::wire_signals() {
toolbar_->set_workflow_name(wf.name);
current_workflow_id_ = wf.id;
properties_->clear();
+ // The stack's commands reference nodes from the previous graph — undoing
+ // into them after a load would resurrect foreign nodes / drop live ones.
+ reset_undo_history();
LOG_INFO("NodeEditor", QString("Workflow loaded: %1").arg(wf.name));
});
connect(&svc, &WorkflowService::workflow_load_failed, this,
@@ -361,6 +411,72 @@ void NodeEditorScreen::wire_signals() {
});
}
+// ── Undo plumbing ──────────────────────────────────────────────────────
+
+void NodeEditorScreen::push_add_nodes(const QVector<NodeDef>& nodes, const QVector<EdgeDef>& edges,
+ const QString& label) {
+ if (nodes.isEmpty())
+ return;
+ undo_stack_->push(new commands::AddNodesCommand(scene_, nodes, edges, label));
+}
+
+void NodeEditorScreen::push_remove_nodes(const QStringList& ids, const QString& label) {
+ if (ids.isEmpty())
+ return;
+ QVector<NodeDef> defs;
+ QSet<QString> id_set;
+ defs.reserve(ids.size());
+ for (const auto& id : ids) {
+ if (auto* item = scene_->find_node(id)) {
+ defs.append(item->node_def()); // carries the live x/y (itemChange keeps it current)
+ id_set.insert(id);
+ }
+ }
+ if (defs.isEmpty())
+ return;
+ const QVector<EdgeDef> edges = commands::edges_touching(scene_, id_set);
+ undo_stack_->push(new commands::RemoveNodesCommand(scene_, defs, edges, label));
+ properties_->clear();
+}
+
+void NodeEditorScreen::begin_move_snapshot() {
+ // A QGraphicsScene delivers the press to exactly one item, so a press always
+ // starts a fresh gesture — no nesting to reconcile. Snapshotting every node
+ // (not just the pressed one) is what makes a multi-select drag undoable as a
+ // single step.
+ move_snapshot_.clear();
+ for (auto* item : scene_->node_items())
+ move_snapshot_.insert(item->node_def().id, item->pos());
+}
+
+void NodeEditorScreen::commit_move_snapshot() {
+ if (move_snapshot_.isEmpty())
+ return;
+
+ QHash<QString, QPointF> before;
+ QHash<QString, QPointF> after;
+ for (auto* item : scene_->node_items()) {
+ const QString id = item->node_def().id;
+ auto it = move_snapshot_.constFind(id);
+ if (it == move_snapshot_.constEnd())
+ continue;
+ if (it.value() != item->pos()) {
+ before.insert(id, it.value());
+ after.insert(id, item->pos());
+ }
+ }
+ move_snapshot_.clear();
+ if (after.isEmpty())
+ return; // a click, not a drag
+ undo_stack_->push(new commands::MoveNodesCommand(scene_, before, after));
+}
+
+void NodeEditorScreen::reset_undo_history() {
+ if (undo_stack_)
+ undo_stack_->clear();
+ move_snapshot_.clear();
+}
+
// ── Action handlers ────────────────────────────────────────────────────
void NodeEditorScreen::on_node_drop(const QString& type_id, const QPointF& scene_pos) {
@@ -385,7 +501,7 @@ void NodeEditorScreen::on_node_drop(const QString& type_id, const QPointF& scene
def.parameters[param.key] = param.default_value;
}
- scene_->add_node(def, *type_def);
+ push_add_nodes({def}, {}, tr("Add %1").arg(type_def->display_name));
}
void NodeEditorScreen::on_node_selected(const QString& node_id) {
@@ -416,23 +532,39 @@ void NodeEditorScreen::on_name_changed(const QString& node_id, const QString& ne
}
void NodeEditorScreen::on_delete_node(const QString& node_id) {
- scene_->remove_node(node_id);
- properties_->clear();
+ auto* item = scene_->find_node(node_id);
+ push_remove_nodes({node_id}, item ? tr("Delete %1").arg(item->node_def().name) : tr("Delete node"));
}
void NodeEditorScreen::on_clear_workflow() {
- auto result =
- QMessageBox::question(this, tr("Clear Workflow"), tr("Are you sure you want to clear all nodes and edges?"),
- QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
+ if (scene_->is_empty())
+ return;
+ auto result = QMessageBox::question(
+ this, tr("Clear Workflow"),
+ tr("Clear all %1 node(s) and their connections?\n\nThis can be undone with Ctrl+Z.")
+ .arg(scene_->node_items().size()),
+ QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
if (result == QMessageBox::Yes) {
- scene_->clear_all();
+ undo_stack_->push(
+ new commands::ReplaceGraphCommand(scene_, scene_->serialize(), WorkflowDef{}, tr("Clear workflow")));
properties_->clear();
LOG_INFO("NodeEditor", "Workflow cleared");
}
}
void NodeEditorScreen::on_import_workflow() {
+ // Importing replaces the whole canvas — guard the work already on it.
+ if (!scene_->is_empty()) {
+ const auto ans = QMessageBox::question(
+ this, tr("Import Workflow"),
+ tr("Importing replaces the %1 node(s) currently on the canvas.\n\nContinue?")
+ .arg(scene_->node_items().size()),
+ QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
+ if (ans != QMessageBox::Yes)
+ return;
+ }
+
QString path =
QFileDialog::getOpenFileName(this, tr("Import Workflow"), {}, tr("JSON Files (*.json);;All Files (*)"));
if (path.isEmpty())
@@ -485,6 +617,8 @@ void NodeEditorScreen::on_import_workflow() {
scene_->deserialize(wf);
toolbar_->set_workflow_name(wf.name);
+ properties_->clear();
+ reset_undo_history(); // the previous graph's commands no longer apply
LOG_INFO("NodeEditor", QString("Imported workflow: %1").arg(wf.name));
}
@@ -612,6 +746,16 @@ void NodeEditorScreen::on_execute() {
wf.name = toolbar_->workflow_name();
+ // A workflow is not just a computation — trading.* nodes place, modify and
+ // cancel REAL orders. The algo tab gates live deployment behind an explicit
+ // confirmation; this path had none, so pressing EXECUTE on a graph
+ // containing a live order node sent it straight to the broker. Several
+ // shipped templates (Price Alert Trading, Mean Reversion, Portfolio
+ // Rebalancer, Pre-Trade Compliance) contain order nodes, so this is
+ // reachable by loading a template and pressing one button.
+ if (!confirm_live_order_nodes(wf, tr("Execute Workflow")))
+ return;
+
// Reset all node states to idle before execution
for (auto* item : scene_->node_items())
item->set_execution_state("idle");
@@ -619,6 +763,69 @@ void NodeEditorScreen::on_execute() {
WorkflowService::instance().execute_workflow(wf);
}
+bool NodeEditorScreen::confirm_live_order_nodes(const WorkflowDef& wf, const QString& action) {
+ // Only MUTATING trading nodes matter. Read-only ones (get_quote,
+ // get_positions, get_balance, …) are safe and must not nag, or the warning
+ // becomes noise people click through — which is worse than no warning.
+ static const QSet<QString> kMutatingTradingTypes = {
+ QStringLiteral("trading.place_order"), QStringLiteral("trading.cancel_order"),
+ QStringLiteral("trading.modify_order"), QStringLiteral("trading.close_position"),
+ QStringLiteral("trading.bracket_order"), QStringLiteral("trading.trailing_stop"),
+ QStringLiteral("trading.scale_in"),
+ };
+
+ QStringList live_rows;
+ for (const auto& nd : wf.nodes) {
+ if (nd.disabled || !kMutatingTradingTypes.contains(nd.type))
+ continue;
+ // `mode` is declared on the order nodes as select{paper,live}, default
+ // "paper". Treat anything that is not explicitly "paper" as live: a
+ // missing or unexpected value must fail toward asking, not toward
+ // sending an order silently.
+ const QString mode = nd.parameters.value(QStringLiteral("mode")).toString(QStringLiteral("paper"));
+ if (mode.compare(QLatin1String("paper"), Qt::CaseInsensitive) == 0)
+ continue;
+
+ const QString broker = nd.parameters.value(QStringLiteral("broker")).toString();
+ const QString symbol = nd.parameters.value(QStringLiteral("symbol")).toString();
+ const QString side = nd.parameters.value(QStringLiteral("action")).toString();
+ const QString qty = nd.parameters.value(QStringLiteral("quantity")).toVariant().toString();
+
+ QString row = QStringLiteral(" • %1 [%2]").arg(nd.name.isEmpty() ? nd.type : nd.name, nd.type);
+ if (!symbol.isEmpty())
+ row += QStringLiteral(" %1").arg(symbol);
+ if (!side.isEmpty())
+ row += QStringLiteral(" %1").arg(side.toUpper());
+ if (!qty.isEmpty())
+ row += QStringLiteral(" x%1").arg(qty);
+ if (!broker.isEmpty())
+ row += QStringLiteral(" → %1").arg(broker);
+ live_rows << row;
+ }
+
+ if (live_rows.isEmpty())
+ return true; // nothing live — proceed silently
+
+ QMessageBox box(this);
+ box.setIcon(QMessageBox::Warning);
+ box.setWindowTitle(action);
+ box.setText(tr("This workflow contains %n LIVE order node(s).", "", live_rows.size()));
+ box.setInformativeText(tr("Running it will place REAL orders with REAL money at your broker:\n\n%1\n\n"
+ "Set each node's Mode to \"paper\" if you only meant to simulate.")
+ .arg(live_rows.join(QLatin1Char('\n'))));
+ auto* proceed = box.addButton(tr("Run with LIVE orders"), QMessageBox::AcceptRole);
+ box.addButton(QMessageBox::Cancel);
+ box.setDefaultButton(QMessageBox::Cancel); // Enter must not fire live orders
+ box.exec();
+
+ const bool go = (box.clickedButton() == proceed);
+ LOG_WARN("NodeEditor", QString("%1: %2 live order node(s) — user %3")
+ .arg(action)
+ .arg(live_rows.size())
+ .arg(go ? "CONFIRMED" : "cancelled"));
+ return go;
+}
+
void NodeEditorScreen::on_show_templates() {
QStringList templates = {
// Beginner
@@ -650,6 +857,19 @@ void NodeEditorScreen::on_show_templates() {
if (!ok)
return;
+ // Loading a template wipes the canvas. Confirm, and capture the current graph
+ // so the whole swap is a single Ctrl+Z.
+ const WorkflowDef before = scene_->serialize();
+ if (!before.nodes.isEmpty()) {
+ const auto ans = QMessageBox::question(
+ this, tr("Workflow Templates"),
+ tr("Loading a template replaces the %1 node(s) on the canvas.\n\nThis can be undone with Ctrl+Z. Continue?")
+ .arg(before.nodes.size()),
+ QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
+ if (ans != QMessageBox::Yes)
+ return;
+ }
+
int idx = templates.indexOf(chosen);
scene_->clear_all();
properties_->clear();
@@ -1047,6 +1267,10 @@ void NodeEditorScreen::on_show_templates() {
}
current_workflow_id_.clear();
+ // The scene already holds the template; record the swap so Ctrl+Z restores
+ // whatever was on the canvas before. (push() re-applies `after`, which
+ // rebuilds an identical graph.)
+ undo_stack_->push(new commands::ReplaceGraphCommand(scene_, before, scene_->serialize(), tr("Load template")));
LOG_INFO("NodeEditor", QString("Loaded template: %1").arg(chosen));
}
diff --git a/fincept-qt/src/screens/node_editor/NodeEditorScreen.h b/fincept-qt/src/screens/node_editor/NodeEditorScreen.h
index 2fadd31d5..23a288e0b 100644
--- a/fincept-qt/src/screens/node_editor/NodeEditorScreen.h
+++ b/fincept-qt/src/screens/node_editor/NodeEditorScreen.h
@@ -3,6 +3,9 @@
#include "screens/common/IStatefulScreen.h"
#include "screens/node_editor/NodeEditorTypes.h"
+#include <QHash>
+#include <QPointF>
+#include <QStringList>
#include <QTimer>
#include <QUndoStack>
#include <QWidget>
@@ -38,6 +41,12 @@ class NodeEditorScreen : public QWidget, public fincept::screens::IStatefulScree
void build_ui();
void wire_signals();
+ /// Ask before running a graph that contains LIVE (non-paper) trading nodes.
+ /// Returns true to proceed. Cancel is the default button so Enter cannot
+ /// fire real orders. Read-only trading.get_* nodes are deliberately ignored
+ /// — warning on those would make the prompt noise people click through.
+ bool confirm_live_order_nodes(const WorkflowDef& wf, const QString& action);
+
// Actions
void on_node_drop(const QString& type_id, const QPointF& scene_pos);
void on_node_selected(const QString& node_id);
@@ -54,6 +63,20 @@ class NodeEditorScreen : public QWidget, public fincept::screens::IStatefulScree
void on_show_templates();
void on_deploy();
+ // ── Undo plumbing ────────────────────────────────────────────────────────
+ /// Push an AddNodesCommand for `nodes` (+ the edges among them).
+ void push_add_nodes(const QVector<NodeDef>& nodes, const QVector<EdgeDef>& edges, const QString& label);
+ /// Push a RemoveNodesCommand for `ids`, capturing their current defs and
+ /// every edge that touches them so undo restores the wiring too.
+ void push_remove_nodes(const QStringList& ids, const QString& label);
+ /// Snapshot every node position (drag start) / diff against it (drag end).
+ void begin_move_snapshot();
+ void commit_move_snapshot();
+ /// Discard undo history — mandatory whenever the graph is replaced wholesale
+ /// from outside the editor (load / import / restore), because the queued
+ /// commands refer to nodes that no longer exist.
+ void reset_undo_history();
+
// Components
NodeEditorToolbar* toolbar_ = nullptr;
NodePalette* palette_ = nullptr;
@@ -70,6 +93,9 @@ class NodeEditorScreen : public QWidget, public fincept::screens::IStatefulScree
// Clipboard for copy/paste
QVector<NodeDef> clipboard_nodes_;
QVector<EdgeDef> clipboard_edges_;
+
+ // Positions captured at drag start, diffed at drag end into one undoable move.
+ QHash<QString, QPointF> move_snapshot_;
};
} // namespace fincept::workflow
diff --git a/fincept-qt/src/screens/node_editor/canvas/MiniMap.cpp b/fincept-qt/src/screens/node_editor/canvas/MiniMap.cpp
index 309c38c8d..b8fa1d823 100644
--- a/fincept-qt/src/screens/node_editor/canvas/MiniMap.cpp
+++ b/fincept-qt/src/screens/node_editor/canvas/MiniMap.cpp
@@ -44,7 +44,14 @@ void MiniMap::update_viewport_rect() {
// Add margin
items_rect.adjust(-100, -100, 100, 100);
- fitInView(items_rect, Qt::KeepAspectRatio);
+
+ // P9: fitInView resets the transform and forces a full re-render of the whole
+ // scene into this 200x150 view. At 5 Hz with a static graph that was pure
+ // waste — only re-fit when the graph's extent actually moved.
+ if (items_rect != fitted_rect_) {
+ fitted_rect_ = items_rect;
+ fitInView(items_rect, Qt::KeepAspectRatio);
+ }
viewport()->update();
}
diff --git a/fincept-qt/src/screens/node_editor/canvas/MiniMap.h b/fincept-qt/src/screens/node_editor/canvas/MiniMap.h
index 8acc61b58..0dc950ea2 100644
--- a/fincept-qt/src/screens/node_editor/canvas/MiniMap.h
+++ b/fincept-qt/src/screens/node_editor/canvas/MiniMap.h
@@ -1,6 +1,7 @@
#pragma once
#include <QGraphicsView>
+#include <QRectF>
#include <QTimer>
namespace fincept::workflow {
@@ -37,6 +38,9 @@ class MiniMap : public QGraphicsView {
QGraphicsView* main_view_ = nullptr;
QTimer* update_timer_ = nullptr;
+ /// Extent the minimap is currently fitted to — re-fitting is skipped while
+ /// the graph's bounding rect is unchanged (see update_viewport_rect()).
+ QRectF fitted_rect_;
};
} // namespace fincept::workflow
diff --git a/fincept-qt/src/screens/node_editor/canvas/NodeCanvas.cpp b/fincept-qt/src/screens/node_editor/canvas/NodeCanvas.cpp
index 2c84bf572..d3a27fe53 100644
--- a/fincept-qt/src/screens/node_editor/canvas/NodeCanvas.cpp
+++ b/fincept-qt/src/screens/node_editor/canvas/NodeCanvas.cpp
@@ -193,7 +193,12 @@ PortItem* NodeCanvas::port_at(const QPoint& view_pos) const {
void NodeCanvas::drawForeground(QPainter* painter, const QRectF& rect) {
Q_UNUSED(rect);
- if (!node_scene_ || !node_scene_->items().isEmpty())
+ // P9: this runs on every canvas repaint. items() materialises a QList of
+ // EVERY graphics item (each node plus all of its ports plus every edge), so
+ // at a few hundred nodes it allocated and populated a multi-thousand-entry
+ // list per frame just to ask "is the canvas empty?". is_empty() is a hash
+ // lookup on the node map.
+ if (!node_scene_ || !node_scene_->is_empty())
return;
painter->save();
diff --git a/fincept-qt/src/screens/node_editor/canvas/NodeItem.cpp b/fincept-qt/src/screens/node_editor/canvas/NodeItem.cpp
index 4fcca50bb..b9c59c742 100644
--- a/fincept-qt/src/screens/node_editor/canvas/NodeItem.cpp
+++ b/fincept-qt/src/screens/node_editor/canvas/NodeItem.cpp
@@ -46,6 +46,17 @@ void NodeItem::set_execution_state(const QString& state) {
invalidate_cache();
}
+void NodeItem::set_disabled(bool disabled) {
+ if (def_.disabled == disabled)
+ return;
+ def_.disabled = disabled;
+ invalidate_cache(); // border + dim overlay are disabled-dependent
+}
+
+void NodeItem::set_continue_on_fail(bool value) {
+ def_.continue_on_fail = value; // no visual, but must reach serialize()
+}
+
PortItem* NodeItem::find_port(const QString& port_id) const {
for (auto* p : input_ports_)
if (p->def().id == port_id)
@@ -94,7 +105,12 @@ QRectF NodeItem::boundingRect() const {
void NodeItem::paint(QPainter* painter, const QStyleOptionGraphicsItem*, QWidget*) {
QRectF rect = boundingRect();
- if (cache_dirty_ || cache_.size() != rect.size().toSize()) {
+ // The cache is allocated at 2x device pixels, so QPixmap::size() is 2x the
+ // logical rect. Comparing it against the *logical* size was therefore always
+ // unequal — the "cache" was rebuilt (allocate + full repaint into a pixmap +
+ // blit) on EVERY paint event, for every node, making it strictly slower than
+ // painting directly. Compare against the same 2x size we allocate.
+ if (cache_dirty_ || cache_.size() != rect.size().toSize() * 2) {
cache_ = QPixmap(rect.size().toSize() * 2); // 2x for retina
cache_.setDevicePixelRatio(2.0);
cache_.fill(Qt::transparent);
@@ -233,6 +249,22 @@ void NodeItem::keyPressEvent(QKeyEvent* event) {
}
}
+void NodeItem::mousePressEvent(QGraphicsSceneMouseEvent* event) {
+ if (event->button() == Qt::LeftButton) {
+ dragging_ = true;
+ emit move_started();
+ }
+ QGraphicsObject::mousePressEvent(event);
+}
+
+void NodeItem::mouseReleaseEvent(QGraphicsSceneMouseEvent* event) {
+ QGraphicsObject::mouseReleaseEvent(event);
+ if (dragging_ && event->button() == Qt::LeftButton) {
+ dragging_ = false;
+ emit move_finished();
+ }
+}
+
void NodeItem::mouseDoubleClickEvent(QGraphicsSceneMouseEvent* event) {
// Reserved for future inline editing
QGraphicsObject::mouseDoubleClickEvent(event);
@@ -263,8 +295,7 @@ void NodeItem::contextMenuEvent(QGraphicsSceneContextMenuEvent* event) {
if (chosen == duplicate_action) {
emit duplicate_requested(def_.id);
} else if (chosen == disable_action) {
- def_.disabled = !def_.disabled;
- invalidate_cache();
+ set_disabled(!def_.disabled);
} else if (chosen == exec_from_action) {
emit execute_from_requested(def_.id);
} else if (chosen == delete_action) {
diff --git a/fincept-qt/src/screens/node_editor/canvas/NodeItem.h b/fincept-qt/src/screens/node_editor/canvas/NodeItem.h
index a4f2de7a0..e26005557 100644
--- a/fincept-qt/src/screens/node_editor/canvas/NodeItem.h
+++ b/fincept-qt/src/screens/node_editor/canvas/NodeItem.h
@@ -23,6 +23,9 @@ class NodeItem : public QGraphicsObject {
void set_name(const QString& name);
void set_parameter(const QString& key, const QJsonValue& value);
void set_execution_state(const QString& state); // "idle", "running", "completed", "error"
+ /// Node-level execution flags edited from the properties panel / context menu.
+ void set_disabled(bool disabled);
+ void set_continue_on_fail(bool value);
PortItem* find_port(const QString& port_id) const;
QVector<PortItem*> input_ports() const { return input_ports_; }
@@ -38,10 +41,16 @@ class NodeItem : public QGraphicsObject {
void delete_requested(const QString& id);
void duplicate_requested(const QString& id);
void execute_from_requested(const QString& id);
+ /// Drag gesture boundaries, so the editor can record one undoable move per
+ /// drag instead of one per pixel of ItemPositionHasChanged.
+ void move_started();
+ void move_finished();
protected:
QVariant itemChange(GraphicsItemChange change, const QVariant& value) override;
void keyPressEvent(QKeyEvent* event) override;
+ void mousePressEvent(QGraphicsSceneMouseEvent* event) override;
+ void mouseReleaseEvent(QGraphicsSceneMouseEvent* event) override;
void mouseDoubleClickEvent(QGraphicsSceneMouseEvent* event) override;
void contextMenuEvent(QGraphicsSceneContextMenuEvent* event) override;
void hoverEnterEvent(QGraphicsSceneHoverEvent* event) override;
@@ -58,6 +67,7 @@ class NodeItem : public QGraphicsObject {
QString execution_state_ = "idle";
bool hovered_ = false;
+ bool dragging_ = false;
// Paint cache (P9)
QPixmap cache_;
diff --git a/fincept-qt/src/screens/node_editor/canvas/NodeScene.cpp b/fincept-qt/src/screens/node_editor/canvas/NodeScene.cpp
index 40f5cfd3e..1c36114c6 100644
--- a/fincept-qt/src/screens/node_editor/canvas/NodeScene.cpp
+++ b/fincept-qt/src/screens/node_editor/canvas/NodeScene.cpp
@@ -30,9 +30,13 @@ NodeItem* NodeScene::add_node(const NodeDef& def, const NodeTypeDef& type_def) {
adjust_edges_for_node(id);
emit node_position_changed(id, x, y);
});
- connect(item, &NodeItem::delete_requested, this, &NodeScene::remove_node);
+ // Deletes/moves are announced, not applied: NodeEditorScreen wraps them in
+ // QUndoCommands so Ctrl+Z can put the node (and its wiring) back.
+ connect(item, &NodeItem::delete_requested, this, &NodeScene::node_delete_requested);
connect(item, &NodeItem::duplicate_requested, this, &NodeScene::node_duplicate_requested);
connect(item, &NodeItem::execute_from_requested, this, &NodeScene::node_execute_from_requested);
+ connect(item, &NodeItem::move_started, this, &NodeScene::node_move_started);
+ connect(item, &NodeItem::move_finished, this, &NodeScene::node_move_finished);
// Wire port connection signals
for (auto* port : item->input_ports()) {
@@ -63,7 +67,7 @@ EdgeItem* NodeScene::add_edge(const EdgeDef& def) {
edges_.insert(def.id, edge);
connect(edge, &EdgeItem::edge_selected, this, [](const QString& id) { Q_UNUSED(id); });
- connect(edge, &EdgeItem::delete_requested, this, &NodeScene::remove_edge);
+ connect(edge, &EdgeItem::delete_requested, this, &NodeScene::edge_delete_requested);
emit edge_added(def.id);
return edge;
@@ -191,12 +195,30 @@ void NodeScene::finish_temp_edge(PortItem* target) {
ed.target_node = in_port->parent_node()->node_def().id;
ed.source_port = out_port->def().id;
ed.target_port = in_port->def().id;
- add_edge(ed);
+ // Announce rather than add — NodeEditorScreen pushes an AddEdgeCommand so
+ // a mis-drag is one Ctrl+Z away.
+ emit edge_create_requested(ed);
}
cancel_temp_edge();
}
+EdgeDef NodeScene::edge_def(const QString& edge_id) const {
+ EdgeDef out;
+ auto it = edges_.constFind(edge_id);
+ if (it == edges_.constEnd())
+ return out;
+ auto* edge = it.value();
+ if (!edge->source_port() || !edge->target_port())
+ return out;
+ out.id = edge->edge_id();
+ out.source_node = edge->source_port()->parent_node()->node_def().id;
+ out.target_node = edge->target_port()->parent_node()->node_def().id;
+ out.source_port = edge->source_port()->def().id;
+ out.target_port = edge->target_port()->def().id;
+ return out;
+}
+
void NodeScene::cancel_temp_edge() {
if (temp_edge_) {
removeItem(temp_edge_);
diff --git a/fincept-qt/src/screens/node_editor/canvas/NodeScene.h b/fincept-qt/src/screens/node_editor/canvas/NodeScene.h
index 2ba4d77e7..c12349533 100644
--- a/fincept-qt/src/screens/node_editor/canvas/NodeScene.h
+++ b/fincept-qt/src/screens/node_editor/canvas/NodeScene.h
@@ -46,6 +46,15 @@ class NodeScene : public QGraphicsScene {
/// All node items.
QVector<NodeItem*> node_items() const;
+ /// True when no nodes are placed. Cheap — unlike items().isEmpty(), which
+ /// materialises a QList of every item (nodes, ports, edges) on each call and
+ /// was being invoked from drawForeground() on every canvas repaint.
+ bool is_empty() const { return nodes_.isEmpty(); }
+
+ /// Look up an edge's definition by id. Returns an EdgeDef with an empty id
+ /// when not found. Used to capture undo state before a delete.
+ EdgeDef edge_def(const QString& edge_id) const;
+
/// Begin temporary edge from a port (during drag-to-connect).
void start_temp_edge(PortItem* from);
@@ -68,6 +77,19 @@ class NodeScene : public QGraphicsScene {
void node_duplicate_requested(const QString& id);
void node_execute_from_requested(const QString& id);
+ // ── Undoable-intent signals ──────────────────────────────────────────────
+ // User-initiated mutations are announced rather than applied here, so
+ // NodeEditorScreen can route them through the QUndoStack. Applying them
+ // directly is what left the undo stack permanently empty (and the UNDO /
+ // REDO buttons permanently disabled).
+ void node_delete_requested(const QString& id);
+ void edge_delete_requested(const QString& id);
+ void edge_create_requested(const fincept::workflow::EdgeDef& edge);
+ /// A node drag began / ended (multi-select drags report from the item under
+ /// the cursor only — the screen diffs a whole-scene position snapshot).
+ void node_move_started();
+ void node_move_finished();
+
public:
/// Animate edges connected to a node (during execution).
void set_edges_animated(const QString& node_id, bool animated);
diff --git a/fincept-qt/src/screens/node_editor/palette/NodePalette.cpp b/fincept-qt/src/screens/node_editor/palette/NodePalette.cpp
index 0d88222ca..e2f5414c6 100644
--- a/fincept-qt/src/screens/node_editor/palette/NodePalette.cpp
+++ b/fincept-qt/src/screens/node_editor/palette/NodePalette.cpp
@@ -84,6 +84,22 @@ void NodePalette::build_ui() {
.arg(ui::colors::BG_SURFACE(), ui::colors::TEXT_DIM()));
categories_container_ = new QWidget(this);
+ // P7: rebuild_categories() runs on every keystroke in the search box and
+ // recreates a button + icon + name label per node type. The button and name
+ // skins are constant, so they live here (one parse, at construction) and the
+ // rows only set an objectName. Only the icon keeps an inline stylesheet —
+ // its colour is the per-category accent.
+ categories_container_->setStyleSheet(
+ QString("QPushButton#npNodeBtn {"
+ " background: %1; color: %2; border: none;"
+ " border-bottom: 1px solid %3; font-family: Consolas;"
+ " font-size: 11px; text-align: left; padding: 0 10px;"
+ "}"
+ "QPushButton#npNodeBtn:hover { background: %3; color: %2; }"
+ "QLabel#npNodeName { color: %2; font-family: Consolas; font-size: 11px; background: transparent; }"
+ "QLabel#npCatCount { color: %4; font-family: Consolas; font-size: 10px; background: transparent; }")
+ .arg(ui::colors::BG_SURFACE(), ui::colors::TEXT_PRIMARY(), ui::colors::BG_HOVER(),
+ ui::colors::TEXT_TERTIARY()));
categories_layout_ = new QVBoxLayout(categories_container_);
categories_layout_->setContentsMargins(0, 0, 0, 0);
categories_layout_->setSpacing(0);
@@ -138,8 +154,7 @@ void NodePalette::rebuild_categories(const QString& filter) {
chl->addWidget(cat_label);
auto* count_label = new QLabel(QString::number(filtered.size()));
- count_label->setStyleSheet(
- QString("color: %1; font-family: Consolas; font-size: 10px;").arg(ui::colors::TEXT_TERTIARY()));
+ count_label->setObjectName(QStringLiteral("npCatCount"));
chl->addStretch();
chl->addWidget(count_label);
@@ -149,20 +164,11 @@ void NodePalette::rebuild_categories(const QString& filter) {
// Node buttons
for (const auto& n : filtered) {
auto* btn = new QPushButton;
+ btn->setObjectName(QStringLiteral("npNodeBtn"));
btn->setFixedHeight(32);
btn->setCursor(Qt::OpenHandCursor);
- btn->setStyleSheet(QString("QPushButton {"
- " background: %1; color: %2; border: none;"
- " border-bottom: 1px solid %3; font-family: Consolas;"
- " font-size: 11px; text-align: left; padding: 0 10px;"
- "}"
- "QPushButton:hover {"
- " background: %4; color: %2;"
- "}")
- .arg(ui::colors::BG_SURFACE(), ui::colors::TEXT_PRIMARY(), ui::colors::BG_HOVER(),
- ui::colors::BG_HOVER()));
-
btn->setToolTip(n.description);
+ btn->setAccessibleName(tr("Add %1 node — drag onto the canvas").arg(n.display_name));
// Layout inside button: icon + name
auto* bl = new QHBoxLayout(btn);
@@ -178,8 +184,7 @@ void NodePalette::rebuild_categories(const QString& filter) {
bl->addWidget(icon);
auto* name = new QLabel(n.display_name);
- name->setStyleSheet(
- QString("color: %1; font-family: Consolas; font-size: 11px;").arg(ui::colors::TEXT_PRIMARY()));
+ name->setObjectName(QStringLiteral("npNodeName"));
name->setAttribute(Qt::WA_TransparentForMouseEvents);
bl->addWidget(name, 1);
diff --git a/fincept-qt/src/screens/node_editor/properties/NodePropertiesPanel.cpp b/fincept-qt/src/screens/node_editor/properties/NodePropertiesPanel.cpp
index c6fcdd1b5..8e1e4daea 100644
--- a/fincept-qt/src/screens/node_editor/properties/NodePropertiesPanel.cpp
+++ b/fincept-qt/src/screens/node_editor/properties/NodePropertiesPanel.cpp
@@ -215,12 +215,22 @@ void NodePropertiesPanel::build_editor(const NodeDef& node, const NodeTypeDef& t
"QCheckBox::indicator { width: 14px; height: 14px; background: %2; border: 1px solid %3; }"
"QCheckBox::indicator:checked { background: %4; }")
.arg(ui::colors::TEXT_PRIMARY(), ui::colors::BG_HOVER(), ui::colors::BORDER_MED(), ui::colors::AMBER()));
+ disabled_check_->setToolTip(tr("Skip this node during execution"));
+ connect(disabled_check_, &QCheckBox::toggled, this, [this](bool on) {
+ if (!current_node_id_.isEmpty())
+ emit node_flag_changed(current_node_id_, QStringLiteral("disabled"), on);
+ });
editor_layout_->insertWidget(pos++, disabled_check_);
// Continue on fail toggle
cof_check_ = new QCheckBox(tr("Continue on Fail"));
cof_check_->setChecked(node.continue_on_fail);
cof_check_->setStyleSheet(disabled_check_->styleSheet());
+ cof_check_->setToolTip(tr("Keep running the workflow if this node errors"));
+ connect(cof_check_, &QCheckBox::toggled, this, [this](bool on) {
+ if (!current_node_id_.isEmpty())
+ emit node_flag_changed(current_node_id_, QStringLiteral("continue_on_fail"), on);
+ });
editor_layout_->insertWidget(pos++, cof_check_);
}
diff --git a/fincept-qt/src/screens/node_editor/properties/NodePropertiesPanel.h b/fincept-qt/src/screens/node_editor/properties/NodePropertiesPanel.h
index 6ff2679af..cda19aead 100644
--- a/fincept-qt/src/screens/node_editor/properties/NodePropertiesPanel.h
+++ b/fincept-qt/src/screens/node_editor/properties/NodePropertiesPanel.h
@@ -32,6 +32,11 @@ class NodePropertiesPanel : public QWidget {
void param_changed(const QString& node_id, const QString& key, QJsonValue value);
void name_changed(const QString& node_id, const QString& new_name);
void delete_requested(const QString& node_id);
+ /// Node-level execution flags from the SETTINGS block. `flag` is "disabled"
+ /// or "continue_on_fail". Previously these two checkboxes were rendered but
+ /// never connected, so toggling "Disabled" silently did nothing and the node
+ /// still executed.
+ void node_flag_changed(const QString& node_id, const QString& flag, bool value);
private:
void build_ui();
diff --git a/fincept-qt/src/screens/node_editor/toolbar/NodeEditorToolbar.cpp b/fincept-qt/src/screens/node_editor/toolbar/NodeEditorToolbar.cpp
index ad63340be..e17b25bf8 100644
--- a/fincept-qt/src/screens/node_editor/toolbar/NodeEditorToolbar.cpp
+++ b/fincept-qt/src/screens/node_editor/toolbar/NodeEditorToolbar.cpp
@@ -2,6 +2,7 @@
#include "ui/theme/Theme.h"
+#include <QCoreApplication>
#include <QFrame>
#include <QHBoxLayout>
#include <QLabel>
@@ -21,6 +22,19 @@ static QString btn_style() {
ui::colors::BG_HOVER(), ui::colors::TEXT_DIM());
}
+// Undo/redo cover structural graph edits only (add / delete / connect / move /
+// clear / template). Text typed into a properties field is undone with that
+// field's own Ctrl+Z — say so, rather than letting the user assume otherwise.
+static QString undo_tooltip() {
+ return QCoreApplication::translate("NodeEditorToolbar",
+ "Undo last graph change — add, delete, connect, move, clear (Ctrl+Z).\n"
+ "Text typed in the properties panel is undone in that field.");
+}
+
+static QString redo_tooltip() {
+ return QCoreApplication::translate("NodeEditorToolbar", "Redo last undone graph change (Ctrl+Y)");
+}
+
static QString accent_btn_style() {
return QString("QPushButton {"
" background: %1; color: %2;"
@@ -93,11 +107,11 @@ void NodeEditorToolbar::retranslateUi() {
status_badge_->setText(tr("DRAFT"));
if (undo_btn_) {
undo_btn_->setText(tr("UNDO"));
- undo_btn_->setToolTip(tr("Undo last action (Ctrl+Z)"));
+ undo_btn_->setToolTip(undo_tooltip());
}
if (redo_btn_) {
redo_btn_->setText(tr("REDO"));
- redo_btn_->setToolTip(tr("Redo last action (Ctrl+Y)"));
+ redo_btn_->setToolTip(redo_tooltip());
}
if (save_btn_) {
save_btn_->setText(tr("SAVE"));
@@ -156,14 +170,16 @@ void NodeEditorToolbar::build_ui() {
undo_btn_ = new QPushButton(tr("UNDO"));
undo_btn_->setStyleSheet(btn_style());
undo_btn_->setEnabled(false);
- undo_btn_->setToolTip(tr("Undo last action (Ctrl+Z)"));
+ undo_btn_->setToolTip(undo_tooltip());
+ undo_btn_->setAccessibleName(tr("Undo last graph change"));
layout->addWidget(undo_btn_);
connect(undo_btn_, &QPushButton::clicked, this, &NodeEditorToolbar::undo_clicked);
redo_btn_ = new QPushButton(tr("REDO"));
redo_btn_->setStyleSheet(btn_style());
redo_btn_->setEnabled(false);
- redo_btn_->setToolTip(tr("Redo last action (Ctrl+Y)"));
+ redo_btn_->setToolTip(redo_tooltip());
+ redo_btn_->setAccessibleName(tr("Redo last undone graph change"));
layout->addWidget(redo_btn_);
connect(redo_btn_, &QPushButton::clicked, this, &NodeEditorToolbar::redo_clicked);
@@ -188,6 +204,8 @@ void NodeEditorToolbar::build_ui() {
clear_btn_ = new QPushButton(tr("CLEAR"));
clear_btn_->setStyleSheet(btn_style());
+ clear_btn_->setToolTip(tr("Remove every node and connection (undoable)"));
+ clear_btn_->setAccessibleName(tr("Clear the whole workflow"));
layout->addWidget(clear_btn_);
connect(clear_btn_, &QPushButton::clicked, this, &NodeEditorToolbar::clear_clicked);
@@ -235,6 +253,8 @@ void NodeEditorToolbar::build_ui() {
// ── Execute ────────────────────────────────────────────────────
execute_btn_ = new QPushButton(tr("EXECUTE"));
execute_btn_->setStyleSheet(accent_btn_style());
+ execute_btn_->setToolTip(tr("Run this workflow once now. Nodes that place orders WILL place them."));
+ execute_btn_->setAccessibleName(tr("Run the workflow"));
layout->addWidget(execute_btn_);
connect(execute_btn_, &QPushButton::clicked, this, &NodeEditorToolbar::execute_clicked);
}
diff --git a/fincept-qt/src/screens/notes/NotesScreen.cpp b/fincept-qt/src/screens/notes/NotesScreen.cpp
index 365a8b171..a4f46cf40 100644
--- a/fincept-qt/src/screens/notes/NotesScreen.cpp
+++ b/fincept-qt/src/screens/notes/NotesScreen.cpp
@@ -14,10 +14,13 @@
#include <QFileInfo>
#include <QFrame>
#include <QHBoxLayout>
+#include <QKeySequence>
#include <QMessageBox>
#include <QPointer>
#include <QRegularExpression>
#include <QScrollArea>
+#include <QShortcut>
+#include <QSignalBlocker>
#include <QSplitter>
#include <QTextStream>
#include <QVBoxLayout>
@@ -173,6 +176,44 @@ void NotesScreen::build_ui() {
root->addWidget(splitter);
+ // ── Keyboard shortcuts ────────────────────────────────────────────────────
+ // A notes editor with no Ctrl+S is a data-loss trap. Scoped to this screen
+ // so they don't leak into other tabs.
+ auto add_sc = [this](const QKeySequence& seq, auto fn) {
+ auto* sc = new QShortcut(seq, this);
+ sc->setContext(Qt::WidgetWithChildrenShortcut);
+ connect(sc, &QShortcut::activated, this, fn);
+ };
+ add_sc(QKeySequence(QKeySequence::Save), [this]() {
+ if (right_stack_ && right_stack_->currentIndex() == 2)
+ on_save_note();
+ });
+ add_sc(QKeySequence(QKeySequence::New), [this]() { on_new_note(); });
+ add_sc(QKeySequence(QKeySequence::Find), [this]() {
+ if (search_input_) {
+ search_input_->setFocus();
+ search_input_->selectAll();
+ }
+ });
+
+ // ── Accessibility ─────────────────────────────────────────────────────────
+ category_list_->setAccessibleName(tr("Note categories"));
+ notes_list_->setAccessibleName(tr("Notes"));
+ search_input_->setAccessibleName(tr("Search notes"));
+ edit_title_->setAccessibleName(tr("Note title"));
+ edit_content_->setAccessibleName(tr("Note content"));
+ edit_category_->setAccessibleName(tr("Note category"));
+ edit_priority_->setAccessibleName(tr("Note priority"));
+ edit_sentiment_->setAccessibleName(tr("Note sentiment"));
+ edit_tags_->setAccessibleName(tr("Note tags"));
+ edit_tickers_->setAccessibleName(tr("Note tickers"));
+ setTabOrder(edit_title_, edit_category_);
+ setTabOrder(edit_category_, edit_priority_);
+ setTabOrder(edit_priority_, edit_sentiment_);
+ setTabOrder(edit_sentiment_, edit_tags_);
+ setTabOrder(edit_tags_, edit_tickers_);
+ setTabOrder(edit_tickers_, edit_content_);
+
// Populate empty-display combos/lists and apply all translatable text.
retranslateUi();
}
@@ -369,6 +410,12 @@ QWidget* NotesScreen::build_editor_panel() {
edit_cancel_btn_ = new QPushButton(tr("CANCEL"));
edit_cancel_btn_->setStyleSheet(kSecondaryBtn());
connect(edit_cancel_btn_, &QPushButton::clicked, this, [this]() {
+ if (has_unsaved_edits() &&
+ QMessageBox::question(this, tr("Discard changes"), tr("Discard the changes to this note?"),
+ QMessageBox::Discard | QMessageBox::Cancel,
+ QMessageBox::Cancel) != QMessageBox::Discard)
+ return;
+ editor_baseline_ = editor_fingerprint();
if (selected_note_id_ > 0) {
enter_view_mode();
} else {
@@ -527,12 +574,63 @@ void NotesScreen::update_notes_list() {
// ── Slots ────────────────────────────────────────────────────────────────────
+// ── Unsaved-edit protection ──────────────────────────────────────────────────
+// Every navigation path out of the editor (picking another note, switching
+// category, starting a new note) used to silently throw away whatever the user
+// had typed. Compare a fingerprint of the editor fields against the values that
+// were loaded into it and confirm before discarding.
+
+QString NotesScreen::editor_fingerprint() const {
+ if (!edit_title_)
+ return QString();
+ return edit_title_->text() + QLatin1Char('\x1f') + edit_content_->toPlainText() + QLatin1Char('\x1f') +
+ edit_category_->currentData().toString() + QLatin1Char('\x1f') + edit_priority_->currentText() +
+ QLatin1Char('\x1f') + edit_sentiment_->currentText() + QLatin1Char('\x1f') + edit_tags_->text() +
+ QLatin1Char('\x1f') + edit_tickers_->text();
+}
+
+bool NotesScreen::has_unsaved_edits() const {
+ if (!is_editing_ || !right_stack_ || right_stack_->currentIndex() != 2)
+ return false;
+ return editor_fingerprint() != editor_baseline_;
+}
+
+bool NotesScreen::confirm_leave_editor() {
+ if (!has_unsaved_edits())
+ return true;
+ const auto reply = QMessageBox::warning(
+ this, tr("Unsaved note"), tr("This note has unsaved changes.\n\nSave them before leaving?"),
+ QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Save);
+ if (reply == QMessageBox::Cancel)
+ return false;
+ if (reply == QMessageBox::Save) {
+ on_save_note();
+ // on_save_note() refuses an empty title; if it did, stay in the editor.
+ return !edit_title_->text().trimmed().isEmpty();
+ }
+ editor_baseline_ = editor_fingerprint(); // discarded — stop re-asking
+ return true;
+}
+
void NotesScreen::on_category_selected(int row) {
if (row < 0 || row >= kCategories.size())
return;
+ if (!confirm_leave_editor()) {
+ // Put the sidebar selection back where it was.
+ if (category_list_) {
+ QSignalBlocker block(category_list_);
+ for (int i = 0; i < kCategories.size(); ++i)
+ if (kCategories[i].id == current_category_) {
+ category_list_->setCurrentRow(i);
+ break;
+ }
+ }
+ return;
+ }
current_category_ = kCategories[row].id;
update_notes_list();
right_stack_->setCurrentIndex(0);
+ is_editing_ = false;
selected_note_id_ = -1;
ScreenStateManager::instance().notify_changed(this);
}
@@ -540,6 +638,8 @@ void NotesScreen::on_category_selected(int row) {
void NotesScreen::on_note_selected(int row) {
if (row < 0 || row >= filtered_notes_.size())
return;
+ if (!confirm_leave_editor())
+ return;
const auto& note = filtered_notes_[row];
selected_note_id_ = note.id;
show_note(note);
@@ -548,6 +648,8 @@ void NotesScreen::on_note_selected(int row) {
}
void NotesScreen::on_new_note() {
+ if (!confirm_leave_editor())
+ return;
selected_note_id_ = -1;
clear_editor();
@@ -560,11 +662,16 @@ void NotesScreen::on_new_note() {
is_editing_ = true;
right_stack_->setCurrentIndex(2);
+ editor_baseline_ = editor_fingerprint();
+ edit_title_->setFocus();
}
void NotesScreen::on_save_note() {
QString title = edit_title_->text().trimmed();
if (title.isEmpty()) {
+ // Previously this just moved focus with no explanation, so SAVE looked
+ // like a dead button.
+ QMessageBox::information(this, tr("Title required"), tr("Give the note a title before saving."));
edit_title_->setFocus();
return;
}
@@ -581,12 +688,14 @@ void NotesScreen::on_save_note() {
auto& repo = fincept::NotesRepository::instance();
+ bool ok = true;
if (selected_note_id_ > 0) {
// Update existing
note.id = selected_note_id_;
auto r = repo.update(note);
if (r.is_err()) {
LOG_ERROR("Notes", "Failed to update note");
+ ok = false;
}
} else {
// Create new
@@ -595,18 +704,38 @@ void NotesScreen::on_save_note() {
selected_note_id_ = static_cast<int>(r.value());
} else {
LOG_ERROR("Notes", "Failed to create note");
+ ok = false;
}
}
+ if (!ok) {
+ // Never silently lose the user's writing — keep them in the editor.
+ QMessageBox::warning(this, tr("Save failed"),
+ tr("The note could not be written to the local database. "
+ "Your text is still in the editor."));
+ return;
+ }
+
+ // The editor now matches what is on disk.
+ editor_baseline_ = editor_fingerprint();
+
load_notes();
// Select the saved note
- for (int i = 0; i < filtered_notes_.size(); ++i) {
- if (filtered_notes_[i].id == selected_note_id_) {
- notes_list_->setCurrentRow(i);
- break;
+ {
+ QSignalBlocker block(notes_list_); // don't re-enter on_note_selected
+ for (int i = 0; i < filtered_notes_.size(); ++i) {
+ if (filtered_notes_[i].id == selected_note_id_) {
+ notes_list_->setCurrentRow(i);
+ break;
+ }
}
}
+ for (const auto& n : notes_)
+ if (n.id == selected_note_id_) {
+ show_note(n);
+ break;
+ }
enter_view_mode();
}
@@ -675,10 +804,13 @@ void NotesScreen::on_export_note() {
QFile f(dest);
if (!f.open(QIODevice::WriteOnly | QIODevice::Text)) {
LOG_ERROR("Notes", "Failed to export note: " + dest);
+ // The button previously appeared to do nothing at all on failure.
+ QMessageBox::warning(this, tr("Export failed"), tr("Could not write the note to:\n%1").arg(dest));
return;
}
QTextStream out(&f);
+ out.setEncoding(QStringConverter::Utf8); // non-ASCII note bodies must survive
out << "# " << title << "\n\n" << content << "\n";
f.close();
@@ -686,6 +818,8 @@ void NotesScreen::on_export_note() {
svc.register_file(stored_name, title + ".md", info.size(), "text/markdown", "notes");
LOG_INFO("Notes", "Exported note to File Manager: " + stored_name);
+ QMessageBox::information(this, tr("Note exported"),
+ tr("Saved as \"%1\" — it is now available in the File Manager.").arg(stored_name));
}
// ── Helpers ──────────────────────────────────────────────────────────────────
@@ -719,7 +853,10 @@ void NotesScreen::clear_editor() {
void NotesScreen::enter_edit_mode() {
is_editing_ = true;
- // Find the note and populate editor
+ // Find the note and populate editor. If it isn't in notes_ (stale id after
+ // a delete elsewhere) start from a clean editor rather than leaving the
+ // previous note's text in the fields.
+ bool found = false;
for (const auto& n : notes_) {
if (n.id == selected_note_id_) {
edit_title_->setText(n.title);
@@ -731,10 +868,14 @@ void NotesScreen::enter_edit_mode() {
edit_sentiment_->setCurrentText(n.sentiment);
edit_tags_->setText(n.tags);
edit_tickers_->setText(n.tickers);
+ found = true;
break;
}
}
+ if (!found)
+ clear_editor();
right_stack_->setCurrentIndex(2);
+ editor_baseline_ = editor_fingerprint();
}
void NotesScreen::enter_view_mode() {
diff --git a/fincept-qt/src/screens/notes/NotesScreen.h b/fincept-qt/src/screens/notes/NotesScreen.h
index e560a83f2..96ff618f5 100644
--- a/fincept-qt/src/screens/notes/NotesScreen.h
+++ b/fincept-qt/src/screens/notes/NotesScreen.h
@@ -59,12 +59,24 @@ class NotesScreen : public QWidget, public IStatefulScreen {
void enter_edit_mode();
void enter_view_mode();
+ /// Snapshot the editor fields into one comparable string. Used to detect
+ /// unsaved edits without tracking every widget's changed() signal.
+ QString editor_fingerprint() const;
+ /// True when the editor is open and its contents differ from what was
+ /// loaded into it.
+ bool has_unsaved_edits() const;
+ /// Ask before throwing away an in-progress edit. Returns true if the caller
+ /// may proceed (nothing pending, or the user chose to discard/save).
+ bool confirm_leave_editor();
+
// Data
QVector<fincept::FinancialNote> notes_;
QVector<fincept::FinancialNote> filtered_notes_;
QString current_category_ = "ALL";
int selected_note_id_ = -1;
bool is_editing_ = false;
+ /// editor_fingerprint() as of the last load/save into the editor.
+ QString editor_baseline_;
// Category sidebar
QListWidget* category_list_ = nullptr;
diff --git a/fincept-qt/src/screens/polymarket/PolymarketBrowsePanel.cpp b/fincept-qt/src/screens/polymarket/PolymarketBrowsePanel.cpp
index 368dbfc8f..af4df9961 100644
--- a/fincept-qt/src/screens/polymarket/PolymarketBrowsePanel.cpp
+++ b/fincept-qt/src/screens/polymarket/PolymarketBrowsePanel.cpp
@@ -62,7 +62,11 @@ PolymarketBrowsePanel::PolymarketBrowsePanel(QWidget* parent) : QWidget(parent)
"}"
"QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical { height: 0; }")
.arg(colors::BG_BASE(), colors::BG_SURFACE(), colors::BORDER_BRIGHT()));
+ list_view_->setAccessibleName(tr("Market list"));
connect(list_view_, &QListView::clicked, this, &PolymarketBrowsePanel::on_item_clicked);
+ // Keyboard: Enter/Return on the highlighted card opens it, matching the
+ // click path. Without this the list was mouse-only.
+ connect(list_view_, &QListView::activated, this, &PolymarketBrowsePanel::on_item_clicked);
vl->addWidget(list_view_, 1);
// ── Pagination bar ────────────────────────────────────────────────────
@@ -92,6 +96,8 @@ PolymarketBrowsePanel::PolymarketBrowsePanel(QWidget* parent) : QWidget(parent)
prev_btn_->setStyleSheet(nav_btn_css);
prev_btn_->setFixedSize(30, 22);
prev_btn_->setCursor(Qt::PointingHandCursor);
+ prev_btn_->setToolTip(tr("Previous page"));
+ prev_btn_->setAccessibleName(tr("Previous page"));
connect(prev_btn_, &QPushButton::clicked, this, &PolymarketBrowsePanel::on_prev);
page_label_ = new QLabel("1 / 1");
@@ -103,6 +109,8 @@ PolymarketBrowsePanel::PolymarketBrowsePanel(QWidget* parent) : QWidget(parent)
next_btn_->setStyleSheet(nav_btn_css);
next_btn_->setFixedSize(30, 22);
next_btn_->setCursor(Qt::PointingHandCursor);
+ next_btn_->setToolTip(tr("Next page"));
+ next_btn_->setAccessibleName(tr("Next page"));
connect(next_btn_, &QPushButton::clicked, this, &PolymarketBrowsePanel::on_next);
phl->addWidget(prev_btn_);
@@ -192,9 +200,20 @@ void PolymarketBrowsePanel::on_next() {
void PolymarketBrowsePanel::update_page() {
int total = model_->rowCount();
int pages = qMax(1, (total + PAGE_SIZE - 1) / PAGE_SIZE);
+ if (current_page_ >= pages)
+ current_page_ = pages - 1;
page_label_->setText(QString("%1 / %2").arg(current_page_ + 1).arg(pages));
prev_btn_->setEnabled(current_page_ > 0);
next_btn_->setEnabled(current_page_ + 1 < pages);
+ // The ◀ / ▶ buttons previously only relabelled themselves — the list view
+ // never moved, so paging was a no-op control. Scroll the view to the first
+ // row of the page so the buttons actually navigate.
+ if (list_view_ && total > 0) {
+ const int row = qBound(0, current_page_ * PAGE_SIZE, total - 1);
+ const auto idx = model_->index(row, 0);
+ if (idx.isValid())
+ list_view_->scrollTo(idx, QAbstractItemView::PositionAtTop);
+ }
}
void PolymarketBrowsePanel::changeEvent(QEvent* event) {
diff --git a/fincept-qt/src/screens/polymarket/PolymarketDetailPanel.cpp b/fincept-qt/src/screens/polymarket/PolymarketDetailPanel.cpp
index acfed6cf0..cf4fe7529 100644
--- a/fincept-qt/src/screens/polymarket/PolymarketDetailPanel.cpp
+++ b/fincept-qt/src/screens/polymarket/PolymarketDetailPanel.cpp
@@ -5,15 +5,22 @@
#include "screens/polymarket/PolymarketPriceChart.h"
#include "ui/theme/Theme.h"
+#include <QAbstractButton>
#include <QComboBox>
#include <QDateTime>
+#include <QDoubleValidator>
#include <QHBoxLayout>
#include <QHeaderView>
#include <QLineEdit>
+#include <QLocale>
+#include <QMessageBox>
#include <QScrollArea>
+#include <QSignalBlocker>
#include <QTimeZone>
#include <QVBoxLayout>
+#include <cmath>
+
namespace fincept::screens::polymarket {
using namespace fincept::ui;
@@ -49,6 +56,8 @@ void PolymarketDetailPanel::build_ui() {
auto* btn = new QPushButton(tab_names[i]);
btn->setCursor(Qt::PointingHandCursor);
btn->setProperty("active", i == 0);
+ btn->setAccessibleName(tab_names[i]);
+ btn->setAccessibleDescription(tr("Show the %1 panel for the selected market").arg(tab_names[i]));
connect(btn, &QPushButton::clicked, this, [this, i]() { set_active_tab(i); });
thl->addWidget(btn);
tab_btns_.append(btn);
@@ -62,6 +71,10 @@ void PolymarketDetailPanel::build_ui() {
stack_->addWidget(create_overview_page()); // 0
orderbook_ = new PolymarketOrderBook;
+ // Click-to-price: a level click loads that price into the trade ticket.
+ // Without this connection the order book's price_clicked signal had no
+ // receiver, so clicking a level did nothing at all.
+ connect(orderbook_, &PolymarketOrderBook::price_clicked, this, &PolymarketDetailPanel::on_book_price_clicked);
stack_->addWidget(orderbook_); // 1
price_chart_ = new PolymarketPriceChart;
@@ -102,6 +115,9 @@ QWidget* PolymarketDetailPanel::create_overview_page() {
"line-height: 1.4;")
.arg(colors::TEXT_PRIMARY()));
question_label_->setWordWrap(true);
+ // Exchange-supplied text. QLabel's default Qt::AutoText renders anything
+ // markup-shaped as rich text, so pin the untrusted fields to PlainText.
+ question_label_->setTextFormat(Qt::PlainText);
question_label_->setMinimumHeight(36);
vl->addWidget(question_label_);
@@ -203,6 +219,7 @@ QWidget* PolymarketDetailPanel::create_overview_page() {
"border-top: 1px solid %2; padding-top: 12px;")
.arg(colors::TEXT_SECONDARY(), colors::BORDER_DIM()));
description_label_->setWordWrap(true);
+ description_label_->setTextFormat(Qt::PlainText); // untrusted market copy
vl->addWidget(description_label_);
vl->addStretch(1);
@@ -290,13 +307,17 @@ QWidget* PolymarketDetailPanel::create_trade_page() {
b->setCursor(Qt::PointingHandCursor);
b->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
}
+ ticket_buy_btn_->setAccessibleName(tr("Buy side"));
+ ticket_sell_btn_->setAccessibleName(tr("Sell side"));
connect(ticket_buy_btn_, &QPushButton::clicked, this, [this]() {
ticket_side_ = "BUY";
refresh_ticket_side_style();
+ refresh_ticket_cost();
});
connect(ticket_sell_btn_, &QPushButton::clicked, this, [this]() {
ticket_side_ = "SELL";
refresh_ticket_side_style();
+ refresh_ticket_cost();
});
srl->addWidget(ticket_buy_btn_);
srl->addWidget(ticket_sell_btn_);
@@ -326,6 +347,7 @@ QWidget* PolymarketDetailPanel::create_trade_page() {
fl->addWidget(make_label(tr("OUTCOME")));
ticket_outcome_cb_ = new QComboBox;
ticket_outcome_cb_->setStyleSheet(input_ss);
+ ticket_outcome_cb_->setAccessibleName(tr("Order outcome"));
fl->addWidget(ticket_outcome_cb_);
// Price + Size row
@@ -341,6 +363,15 @@ QWidget* PolymarketDetailPanel::create_trade_page() {
ticket_price_edit_ = new QLineEdit;
ticket_price_edit_->setPlaceholderText("0.50");
ticket_price_edit_->setStyleSheet(input_ss);
+ ticket_price_edit_->setAccessibleName(tr("Limit price between 0 and 1"));
+ // Reject non-numeric / out-of-range keystrokes up front — the submit path
+ // still re-validates, but this stops a fat-finger "5" ever reaching it.
+ {
+ auto* pv = new QDoubleValidator(0.0, 1.0, 6, ticket_price_edit_);
+ pv->setNotation(QDoubleValidator::StandardNotation);
+ pv->setLocale(QLocale::c());
+ ticket_price_edit_->setValidator(pv);
+ }
price_col->addWidget(ticket_price_edit_);
auto* size_col = new QVBoxLayout;
@@ -349,12 +380,29 @@ QWidget* PolymarketDetailPanel::create_trade_page() {
ticket_size_edit_ = new QLineEdit;
ticket_size_edit_->setPlaceholderText("10");
ticket_size_edit_->setStyleSheet(input_ss);
+ ticket_size_edit_->setAccessibleName(tr("Order size in shares"));
+ {
+ auto* sv = new QDoubleValidator(0.0, 1e9, 4, ticket_size_edit_);
+ sv->setNotation(QDoubleValidator::StandardNotation);
+ sv->setLocale(QLocale::c());
+ ticket_size_edit_->setValidator(sv);
+ }
size_col->addWidget(ticket_size_edit_);
psl->addLayout(price_col);
psl->addLayout(size_col);
fl->addWidget(ps_row);
+ // Live notional readout — a prediction-market order's worst-case cost is
+ // price × size, and without it the user is doing mental arithmetic before
+ // committing real funds.
+ ticket_cost_lbl_ = new QLabel(QStringLiteral("—"));
+ ticket_cost_lbl_->setStyleSheet(
+ QString("color: %1; font-size: 10px; font-weight: 700; background: transparent;").arg(colors::TEXT_SECONDARY()));
+ fl->addWidget(ticket_cost_lbl_);
+ connect(ticket_price_edit_, &QLineEdit::textChanged, this, [this]() { refresh_ticket_cost(); });
+ connect(ticket_size_edit_, &QLineEdit::textChanged, this, [this]() { refresh_ticket_cost(); });
+
// Order type
fl->addWidget(make_label(tr("ORDER TYPE")));
ticket_type_cb_ = new QComboBox;
@@ -362,15 +410,25 @@ QWidget* PolymarketDetailPanel::create_trade_page() {
// not translated.
ticket_type_cb_->addItems({"GTC", "FOK", "FAK"});
ticket_type_cb_->setStyleSheet(input_ss);
+ ticket_type_cb_->setAccessibleName(tr("Order type"));
fl->addWidget(ticket_type_cb_);
// Submit button
ticket_submit_btn_ = new QPushButton(tr("PLACE ORDER"));
ticket_submit_btn_->setFixedHeight(34);
ticket_submit_btn_->setCursor(Qt::PointingHandCursor);
+ ticket_submit_btn_->setAccessibleName(tr("Place order"));
connect(ticket_submit_btn_, &QPushButton::clicked, this, &PolymarketDetailPanel::on_submit_clicked);
fl->addWidget(ticket_submit_btn_);
+ // Tab order across the ticket so the form is fully keyboard-drivable.
+ QWidget::setTabOrder(ticket_buy_btn_, ticket_sell_btn_);
+ QWidget::setTabOrder(ticket_sell_btn_, ticket_outcome_cb_);
+ QWidget::setTabOrder(ticket_outcome_cb_, ticket_price_edit_);
+ QWidget::setTabOrder(ticket_price_edit_, ticket_size_edit_);
+ QWidget::setTabOrder(ticket_size_edit_, ticket_type_cb_);
+ QWidget::setTabOrder(ticket_type_cb_, ticket_submit_btn_);
+
// Status label (feedback)
ticket_status_lbl_ = new QLabel;
ticket_status_lbl_->setAlignment(Qt::AlignCenter);
@@ -411,33 +469,133 @@ void PolymarketDetailPanel::refresh_ticket_side_style() {
colors::BG_RAISED(), colors::TEXT_DIM()));
}
+void PolymarketDetailPanel::refresh_ticket_cost() {
+ if (!ticket_cost_lbl_)
+ return;
+ bool price_ok = false, size_ok = false;
+ const double price = ticket_price_edit_ ? ticket_price_edit_->text().toDouble(&price_ok) : 0.0;
+ const double size = ticket_size_edit_ ? ticket_size_edit_->text().toDouble(&size_ok) : 0.0;
+ if (!price_ok || !size_ok || price <= 0.0 || size <= 0.0) {
+ ticket_cost_lbl_->setText(QStringLiteral("—"));
+ return;
+ }
+ const QString ccy = presentation_.currency_symbol.isEmpty() ? QStringLiteral("USD") : presentation_.currency_symbol;
+ // BUY costs price × size up front; SELL of held shares releases that
+ // notional. Either way it's the amount at stake on this ticket.
+ ticket_cost_lbl_->setText(ticket_side_ == QStringLiteral("BUY")
+ ? tr("≈ %1 %2 cost").arg(price * size, 0, 'f', 2).arg(ccy)
+ : tr("≈ %1 %2 proceeds").arg(price * size, 0, 'f', 2).arg(ccy));
+}
+
+void PolymarketDetailPanel::on_book_price_clicked(double price) {
+ if (!ticket_price_edit_ || !ticket_stack_)
+ return;
+ if (ticket_stack_->currentIndex() != 1)
+ return; // trading disabled — nothing to fill
+ if (price <= 0.0 || price >= 1.0)
+ return;
+ ticket_price_edit_->setText(QString::number(price, 'f', 4));
+ set_active_tab(kTabTrade);
+ ticket_price_edit_->setFocus();
+}
+
void PolymarketDetailPanel::on_submit_clicked() {
if (!has_last_market_)
return;
+ // Hard double-submit guard — the button is also disabled while in flight,
+ // but a queued click (or a market refresh racing the disable) could still
+ // land here.
+ if (submit_in_flight_)
+ return;
+
+ auto reject = [this](const QString& msg) {
+ ticket_status_lbl_->setStyleSheet(
+ QString("color: %1; font-size: 10px; background: transparent;").arg(colors::NEGATIVE()));
+ ticket_status_lbl_->setText(msg);
+ };
+
bool price_ok = false, size_ok = false;
const double price = ticket_price_edit_->text().toDouble(&price_ok);
const double size = ticket_size_edit_->text().toDouble(&size_ok);
if (!price_ok || price <= 0.0 || price >= 1.0) {
- ticket_status_lbl_->setStyleSheet(
- QString("color: %1; font-size: 10px; background: transparent;").arg(colors::NEGATIVE()));
- ticket_status_lbl_->setText(tr("Invalid price — enter a value between 0 and 1"));
+ reject(tr("Invalid price — enter a value between 0 and 1"));
return;
}
if (!size_ok || size <= 0.0) {
- ticket_status_lbl_->setStyleSheet(
- QString("color: %1; font-size: 10px; background: transparent;").arg(colors::NEGATIVE()));
- ticket_status_lbl_->setText(tr("Invalid size — must be > 0"));
+ reject(tr("Invalid size — must be > 0"));
return;
}
+ if (book_min_size_ > 0.0 && size < book_min_size_) {
+ reject(tr("Size below the exchange minimum of %1").arg(book_min_size_, 0, 'f', 2));
+ return;
+ }
+ // Tick alignment — an off-tick limit price is rejected by the CLOB after
+ // the round-trip, so catch it here and say exactly what's wrong.
+ if (book_tick_size_ > 0.0) {
+ const double ticks = price / book_tick_size_;
+ if (std::abs(ticks - std::round(ticks)) > 1e-6) {
+ const double snapped = std::round(ticks) * book_tick_size_;
+ reject(tr("Price must be a multiple of the %1 tick — try %2")
+ .arg(book_tick_size_, 0, 'f', 4)
+ .arg(snapped, 0, 'f', 4));
+ return;
+ }
+ }
const int outcome_idx = ticket_outcome_cb_->currentIndex();
- const QString asset_id = (outcome_idx >= 0 && outcome_idx < last_market_.outcomes.size())
- ? last_market_.outcomes[outcome_idx].asset_id
- : QString{};
+ if (outcome_idx < 0 || outcome_idx >= last_market_.outcomes.size()) {
+ reject(tr("Select an outcome before placing an order"));
+ return;
+ }
+ const auto& outcome = last_market_.outcomes[outcome_idx];
+ if (outcome.asset_id.isEmpty()) {
+ // Without an asset id the exchange cannot know *which* side of the
+ // market this order is for — refuse rather than send an ambiguous one.
+ reject(tr("This outcome has no tradable asset id — cannot place order"));
+ return;
+ }
+ if (last_market_.closed) {
+ reject(tr("Market is closed — no further trading"));
+ return;
+ }
+
+ // Explicit confirmation. This is a real-money order on a real exchange;
+ // the previous flow fired straight from the button with no read-back of
+ // what was about to be sent.
+ const QString ccy = presentation_.currency_symbol.isEmpty() ? QStringLiteral("USD") : presentation_.currency_symbol;
+ // Built line by line rather than one chained arg() chain: exchange-supplied
+ // text (the question, the outcome name) can itself contain "%n", and a
+ // later .arg() would happily substitute into it.
+ QStringList lines;
+ lines << tr("%1 %2 × %3 shares @ %4")
+ .arg(ticket_side_, outcome.name, QString::number(size, 'f', 2),
+ presentation_.format_price(price));
+ lines << QString();
+ lines << tr("Market: %1").arg(last_market_.question.left(120));
+ lines << tr("Order type: %1").arg(ticket_type_cb_->currentText());
+ lines << (ticket_side_ == QStringLiteral("BUY")
+ ? tr("Cost: %1 %2").arg(QString::number(price * size, 'f', 2), ccy)
+ : tr("Proceeds: %1 %2").arg(QString::number(price * size, 'f', 2), ccy));
+ const QString summary = lines.join(QLatin1Char('\n'));
+ QMessageBox confirm(this);
+ confirm.setWindowTitle(tr("Confirm order"));
+ confirm.setIcon(QMessageBox::Warning);
+ confirm.setText(tr("Place this order on %1?").arg(presentation_.display_name));
+ confirm.setInformativeText(summary);
+ confirm.setStandardButtons(QMessageBox::Cancel | QMessageBox::Ok);
+ confirm.setDefaultButton(QMessageBox::Cancel);
+ if (auto* ok_btn = confirm.button(QMessageBox::Ok))
+ ok_btn->setText(tr("Place order"));
+ if (confirm.exec() != QMessageBox::Ok) {
+ ticket_status_lbl_->setStyleSheet(
+ QString("color: %1; font-size: 10px; background: transparent;").arg(colors::TEXT_DIM()));
+ ticket_status_lbl_->setText(tr("Cancelled — no order sent"));
+ return;
+ }
OrderRequest req;
req.key = last_market_.key;
- req.asset_id = asset_id;
+ req.asset_id = outcome.asset_id;
req.side = ticket_side_;
req.order_type = ticket_type_cb_->currentText();
req.price = price;
@@ -446,6 +604,7 @@ void PolymarketDetailPanel::on_submit_clicked() {
ticket_status_lbl_->setStyleSheet(
QString("color: %1; font-size: 10px; background: transparent;").arg(colors::TEXT_DIM()));
ticket_status_lbl_->setText(tr("Submitting…"));
+ submit_in_flight_ = true;
ticket_submit_btn_->setEnabled(false);
emit place_order(req);
}
@@ -459,18 +618,48 @@ void PolymarketDetailPanel::set_balance(const AccountBalance& balance) {
void PolymarketDetailPanel::set_positions(const QVector<PredictionPosition>& positions) {
if (!ticket_position_lbl_ || !has_last_market_)
return;
- // Find the position matching the currently-displayed market.
- double total_size = 0.0;
+ // Positions are per-outcome on a binary market. Summing YES and NO into a
+ // single "N shares" figure told the user they were long something they may
+ // in fact be flat on — break it out by outcome, and prefer the outcome
+ // currently selected in the ticket.
+ const int sel = ticket_outcome_cb_ ? ticket_outcome_cb_->currentIndex() : -1;
+ const QString sel_asset =
+ (sel >= 0 && sel < last_market_.outcomes.size()) ? last_market_.outcomes[sel].asset_id : QString();
+
+ double selected_size = 0.0;
+ double selected_avg = 0.0;
+ QStringList others;
for (const auto& p : positions) {
- if (p.market_id == last_market_.key.market_id)
- total_size += p.size;
+ if (p.market_id != last_market_.key.market_id)
+ continue;
+ if (p.size <= 0.0)
+ continue;
+ if (!sel_asset.isEmpty() && p.asset_id == sel_asset) {
+ selected_size += p.size;
+ selected_avg = p.avg_price;
+ } else {
+ others << tr("%1 %2").arg(p.size, 0, 'f', 2).arg(p.outcome.isEmpty() ? tr("other") : p.outcome);
+ }
+ }
+
+ QString text;
+ if (selected_size > 0.0) {
+ text = selected_avg > 0.0 ? tr("%1 @ %2").arg(selected_size, 0, 'f', 2).arg(presentation_.format_price(
+ selected_avg))
+ : tr("%1 shares").arg(selected_size, 0, 'f', 2);
+ } else {
+ text = tr("No position");
}
- ticket_position_lbl_->setText(total_size > 0.0 ? tr("%1 shares").arg(total_size, 0, 'f', 2) : tr("No position"));
+ if (!others.isEmpty())
+ text += QStringLiteral(" (") + others.join(QStringLiteral(", ")) + QStringLiteral(")");
+ ticket_position_lbl_->setText(text);
+ ticket_position_lbl_->setToolTip(tr("Position in the outcome selected in the ticket; other outcomes in brackets."));
}
void PolymarketDetailPanel::on_order_result(const OrderResult& result) {
if (!ticket_status_lbl_ || !ticket_submit_btn_)
return;
+ submit_in_flight_ = false;
ticket_submit_btn_->setEnabled(true);
if (result.ok) {
ticket_status_lbl_->setStyleSheet(
@@ -478,6 +667,7 @@ void PolymarketDetailPanel::on_order_result(const OrderResult& result) {
ticket_status_lbl_->setText(tr("Order placed ✓ ID: %1").arg(result.order_id.left(12)));
ticket_price_edit_->clear();
ticket_size_edit_->clear();
+ refresh_ticket_cost();
} else {
ticket_status_lbl_->setStyleSheet(
QString("color: %1; font-size: 10px; background: transparent;").arg(colors::NEGATIVE()));
@@ -572,7 +762,41 @@ void PolymarketDetailPanel::set_active_tab(int tab) {
// ── Data setters ────────────────────────────────────────────────────────────
+void PolymarketDetailPanel::sync_ticket_outcomes(const PredictionMarket& market, bool same_market) {
+ if (!ticket_outcome_cb_)
+ return;
+ // Preserve the user's outcome choice across a same-market refresh. A naive
+ // clear()+addItem() silently snapped the selection back to index 0, which
+ // on a binary market turns a pending "buy NO" ticket into "buy YES".
+ const QString prev = same_market ? ticket_outcome_cb_->currentText() : QString();
+ QStringList names;
+ names.reserve(market.outcomes.size());
+ for (const auto& o : market.outcomes)
+ names << o.name;
+ if (same_market && names == ticket_outcome_names_)
+ return; // nothing changed — leave the widget (and selection) alone
+
+ const QSignalBlocker block(ticket_outcome_cb_);
+ ticket_outcome_cb_->clear();
+ ticket_outcome_cb_->addItems(names);
+ ticket_outcome_names_ = names;
+ if (!prev.isEmpty()) {
+ const int idx = ticket_outcome_cb_->findText(prev);
+ if (idx >= 0)
+ ticket_outcome_cb_->setCurrentIndex(idx);
+ }
+}
+
void PolymarketDetailPanel::set_market(const PredictionMarket& market) {
+ // A live WS price tick re-enters here with the *same* market. Treat that
+ // as a price refresh, not a fresh selection: keep the trade ticket, the
+ // active tab, and any in-flight submit intact.
+ // Require a non-empty id: two different markets that both lack an id must
+ // never be treated as the same one (that would carry a stale ticket over).
+ const bool same_market = has_last_market_ && !market.key.market_id.isEmpty() &&
+ market.key.market_id == last_market_.key.market_id &&
+ market.key.exchange_id == last_market_.key.exchange_id;
+
last_market_ = market;
has_last_market_ = true;
@@ -580,25 +804,35 @@ void PolymarketDetailPanel::set_market(const PredictionMarket& market) {
volume_label_->setText(presentation_.format_volume(market.volume));
liquidity_label_->setText(presentation_.format_liquidity(market.liquidity));
end_date_label_->setText(market.end_date_iso.left(10));
- midpoint_label_->setText("—");
- spread_label_->setText("—");
- last_trade_label_->setText("—");
- oi_label_->setText("—");
+ if (!same_market) {
+ midpoint_label_->setText("—");
+ spread_label_->setText("—");
+ last_trade_label_->setText("—");
+ oi_label_->setText("—");
+ }
render_status_badge(market);
// ── Populate ticket outcome combo ─────────────────────────────────────
- if (ticket_outcome_cb_) {
- ticket_outcome_cb_->clear();
- for (const auto& o : market.outcomes)
- ticket_outcome_cb_->addItem(o.name);
+ sync_ticket_outcomes(market, same_market);
+ if (!same_market) {
+ if (ticket_status_lbl_)
+ ticket_status_lbl_->clear();
+ if (ticket_submit_btn_)
+ ticket_submit_btn_->setEnabled(true);
+ submit_in_flight_ = false;
+ if (ticket_position_lbl_)
+ ticket_position_lbl_->setText("—");
+ // Constraints belong to the previous market's book — drop them until
+ // the new market's book arrives.
+ book_tick_size_ = 0.0;
+ book_min_size_ = 0.0;
+ if (ticket_price_edit_)
+ ticket_price_edit_->clear();
+ if (ticket_size_edit_)
+ ticket_size_edit_->clear();
+ refresh_ticket_cost();
}
- if (ticket_status_lbl_)
- ticket_status_lbl_->clear();
- if (ticket_submit_btn_)
- ticket_submit_btn_->setEnabled(true);
- if (ticket_position_lbl_)
- ticket_position_lbl_->setText("—");
// ── Rebuild outcome probability bars ──────────────────────────────────
auto* layout = qobject_cast<QVBoxLayout*>(outcome_container_->layout());
@@ -685,9 +919,16 @@ void PolymarketDetailPanel::set_market(const PredictionMarket& market) {
labels.reserve(market.outcomes.size());
for (const auto& o : market.outcomes)
labels.append(o.name);
- price_chart_->set_outcome_labels(labels);
-
- set_active_tab(0);
+ // set_outcome_labels() resets the chart's outcome combo to index 0, which
+ // on a same-market refresh would silently pull the chart back to the first
+ // outcome while the user is looking at another one.
+ if (!same_market)
+ price_chart_->set_outcome_labels(labels);
+
+ // Only jump back to OVERVIEW on an actual market change — a WS price tick
+ // used to yank the user out of the TRADE / ORDER BOOK tab mid-entry.
+ if (!same_market)
+ set_active_tab(0);
}
void PolymarketDetailPanel::set_price_summary(const pmx::PriceSummary& summary) {
@@ -698,6 +939,12 @@ void PolymarketDetailPanel::set_price_summary(const pmx::PriceSummary& summary)
void PolymarketDetailPanel::set_order_book(const PredictionOrderBook& book) {
orderbook_->set_data(book);
+ // Capture the exchange's price/size constraints so the ticket can reject
+ // an off-tick or sub-minimum order locally instead of after a round-trip.
+ if (book.tick_size > 0.0)
+ book_tick_size_ = book.tick_size;
+ if (book.min_order_size > 0.0)
+ book_min_size_ = book.min_order_size;
}
void PolymarketDetailPanel::set_price_history(const PriceHistory& history) {
@@ -757,11 +1004,16 @@ void PolymarketDetailPanel::set_comments(const QVector<pmx::Comment>& comments)
cvl->setContentsMargins(10, 8, 10, 8);
cvl->setSpacing(4);
+ // Comments are arbitrary user-generated text from the exchange —
+ // the single most hostile input on this screen. Render as plain
+ // text so markup can't restyle or spoof the panel.
auto* author = new QLabel(c.author.isEmpty() ? c.author_address.left(12) + "…" : c.author);
+ author->setTextFormat(Qt::PlainText);
author->setStyleSheet(
QString("color: %1; font-size: 9px; font-weight: 700; background: transparent;").arg(colors::AMBER()));
auto* body = new QLabel(c.body.left(280));
+ body->setTextFormat(Qt::PlainText);
body->setStyleSheet(QString("color: %1; font-size: 10px; background: transparent; line-height: 1.4;")
.arg(colors::TEXT_PRIMARY()));
body->setWordWrap(true);
@@ -809,7 +1061,11 @@ void PolymarketDetailPanel::set_related_markets(const QVector<PredictionMarket>&
"QPushButton:hover { background: %4; color: %5; border-color: %6; }")
.arg(colors::BG_SURFACE(), colors::TEXT_SECONDARY(), colors::BORDER_DIM(),
colors::BG_HOVER(), colors::TEXT_PRIMARY(), colors::BORDER_BRIGHT()));
- card->setText(m.question.left(70) + (m.question.size() > 70 ? "…" : ""));
+ // Escape '&' so a question containing one doesn't turn into a
+ // button mnemonic (and lose the character).
+ card->setText(QString(m.question.left(70) + (m.question.size() > 70 ? "…" : "")).replace('&', "&&"));
+ card->setToolTip(m.question);
+ card->setAccessibleName(tr("Related market: %1").arg(m.question.left(80)));
card->setCursor(Qt::PointingHandCursor);
connect(card, &QPushButton::clicked, this, [this, m]() { emit related_market_clicked(m); });
vl->addWidget(card);
@@ -868,6 +1124,21 @@ void PolymarketDetailPanel::set_polymarket_extras_enabled(bool enabled) {
void PolymarketDetailPanel::clear() {
has_last_market_ = false;
last_market_ = {};
+ submit_in_flight_ = false;
+ book_tick_size_ = 0.0;
+ book_min_size_ = 0.0;
+ ticket_outcome_names_.clear();
+ if (ticket_outcome_cb_)
+ ticket_outcome_cb_->clear();
+ if (ticket_submit_btn_)
+ ticket_submit_btn_->setEnabled(true);
+ if (ticket_status_lbl_)
+ ticket_status_lbl_->clear();
+ if (ticket_price_edit_)
+ ticket_price_edit_->clear();
+ if (ticket_size_edit_)
+ ticket_size_edit_->clear();
+ refresh_ticket_cost();
question_label_->setText(tr("Select a market to view details"));
volume_label_->setText("—");
liquidity_label_->setText("—");
diff --git a/fincept-qt/src/screens/polymarket/PolymarketDetailPanel.h b/fincept-qt/src/screens/polymarket/PolymarketDetailPanel.h
index 01e853bb3..61220f41a 100644
--- a/fincept-qt/src/screens/polymarket/PolymarketDetailPanel.h
+++ b/fincept-qt/src/screens/polymarket/PolymarketDetailPanel.h
@@ -11,6 +11,7 @@
#include <QList>
#include <QPushButton>
#include <QStackedWidget>
+#include <QStringList>
#include <QTableWidget>
#include <QWidget>
@@ -98,6 +99,16 @@ class PolymarketDetailPanel : public QWidget {
void on_submit_clicked();
void retranslateUi();
+ /// Recompute the "≈ COST" readout under the ticket from the current
+ /// price × size. Shows "—" when either field is blank/invalid.
+ void refresh_ticket_cost();
+ /// Fill the ticket price from an order-book level click and surface the
+ /// TRADE tab so the effect is visible. No-op when trading is disabled.
+ void on_book_price_clicked(double price);
+ /// Repopulate the ticket outcome combo for `market`, preserving the
+ /// user's current choice by outcome name when the market is unchanged.
+ void sync_ticket_outcomes(const fincept::services::prediction::PredictionMarket& market, bool same_market);
+
QList<QPushButton*> tab_btns_;
QStackedWidget* stack_ = nullptr;
@@ -139,7 +150,20 @@ class PolymarketDetailPanel : public QWidget {
QComboBox* ticket_type_cb_ = nullptr;
QPushButton* ticket_submit_btn_ = nullptr;
QLabel* ticket_status_lbl_ = nullptr;
+ QLabel* ticket_cost_lbl_ = nullptr; // "≈ $12.50 max cost" readout
QString ticket_side_ = "BUY";
+ /// Outcome names currently loaded into ticket_outcome_cb_. Lets a
+ /// same-market refresh skip the rebuild (and so keep the selection).
+ QStringList ticket_outcome_names_;
+ /// True between emit place_order() and the matching on_order_result().
+ /// Guards against double-submit and stops an incoming price refresh from
+ /// re-enabling the submit button mid-flight.
+ bool submit_in_flight_ = false;
+ /// Exchange constraints captured from the last order book for the
+ /// selected market. Used to validate/round the ticket price and size so
+ /// the exchange doesn't silently reject the order.
+ double book_tick_size_ = 0.0;
+ double book_min_size_ = 0.0;
// Holders
QTableWidget* holders_table_ = nullptr;
diff --git a/fincept-qt/src/screens/polymarket/PolymarketLeaderboard.cpp b/fincept-qt/src/screens/polymarket/PolymarketLeaderboard.cpp
index 01805c432..ec0581de9 100644
--- a/fincept-qt/src/screens/polymarket/PolymarketLeaderboard.cpp
+++ b/fincept-qt/src/screens/polymarket/PolymarketLeaderboard.cpp
@@ -60,10 +60,34 @@ PolymarketLeaderboard::PolymarketLeaderboard(QWidget* parent) : QWidget(parent)
"QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical { height: 0; }")
.arg(colors::BG_BASE(), colors::TEXT_PRIMARY(), colors::BORDER_DIM(), colors::BG_HOVER(),
colors::BG_RAISED(), colors::TEXT_SECONDARY()));
+ table_->setAccessibleName(tr("Trader leaderboard"));
vl->addWidget(table_, 1);
+
+ // The panel is shown whenever the adapter advertises has_leaderboard, but
+ // nothing populates it yet — render an explicit empty state instead of a
+ // blank grid that reads as a broken widget.
+ show_empty_state(tr("Leaderboard data not available"));
+}
+
+void PolymarketLeaderboard::show_empty_state(const QString& message) {
+ if (!table_)
+ return;
+ table_->setSortingEnabled(false);
+ table_->setRowCount(1);
+ auto* item = new QTableWidgetItem(message);
+ item->setTextAlignment(Qt::AlignCenter);
+ item->setForeground(QColor(colors::TEXT_DIM()));
+ item->setFlags(Qt::ItemIsEnabled);
+ table_->setItem(0, 0, item);
+ table_->setSpan(0, 0, 1, table_->columnCount());
}
void PolymarketLeaderboard::set_entries(const QVector<LeaderboardEntry>& entries) {
+ table_->clearSpans();
+ if (entries.isEmpty()) {
+ show_empty_state(tr("No leaderboard entries"));
+ return;
+ }
table_->setSortingEnabled(false);
table_->setRowCount(entries.size());
@@ -96,7 +120,9 @@ void PolymarketLeaderboard::set_entries(const QVector<LeaderboardEntry>& entries
void PolymarketLeaderboard::set_loading(bool loading) {
if (loading) {
+ table_->clearSpans();
table_->setRowCount(0);
+ show_empty_state(tr("Loading…"));
}
}
diff --git a/fincept-qt/src/screens/polymarket/PolymarketLeaderboard.h b/fincept-qt/src/screens/polymarket/PolymarketLeaderboard.h
index d65935283..900306e5f 100644
--- a/fincept-qt/src/screens/polymarket/PolymarketLeaderboard.h
+++ b/fincept-qt/src/screens/polymarket/PolymarketLeaderboard.h
@@ -26,6 +26,9 @@ class PolymarketLeaderboard : public QWidget {
private:
void retranslateUi();
+ /// Render a single full-width row carrying `message`. Used when no
+ /// leaderboard data is available so the panel never shows a bare grid.
+ void show_empty_state(const QString& message);
QLabel* header_ = nullptr;
QTableWidget* table_ = nullptr;
diff --git a/fincept-qt/src/screens/polymarket/PolymarketOrderBlotter.cpp b/fincept-qt/src/screens/polymarket/PolymarketOrderBlotter.cpp
index 803d0a637..4a69de0a0 100644
--- a/fincept-qt/src/screens/polymarket/PolymarketOrderBlotter.cpp
+++ b/fincept-qt/src/screens/polymarket/PolymarketOrderBlotter.cpp
@@ -3,10 +3,12 @@
#include "ui/theme/Theme.h"
#include <QCoreApplication>
+#include <QDateTime>
#include <QHBoxLayout>
#include <QHeaderView>
#include <QInputDialog>
#include <QLabel>
+#include <QMessageBox>
#include <QPushButton>
#include <QVBoxLayout>
@@ -112,21 +114,39 @@ PolymarketOrderBlotter::PolymarketOrderBlotter(QWidget* parent) : QWidget(parent
table_->horizontalHeader()->setStretchLastSection(false);
table_->horizontalHeader()->setSectionResizeMode(ColMarket, QHeaderView::Stretch);
table_->setShowGrid(false);
- table_->setStyleSheet(QString("QTableWidget { background: %1; color: %2; border: none; font-size: 10px; }"
- "QTableWidget::item { padding: 3px 8px; border-bottom: 1px solid %3; }"
- "QTableWidget::item:selected { background: %4; color: %2; }"
- "QHeaderView::section { background: %5; color: %6; border: none;"
- " border-bottom: 1px solid %3; padding: 5px 8px;"
- " font-size: 8px; font-weight: 700; letter-spacing: 0.5px; }"
- "QScrollBar:vertical { background: %1; width: 4px; border: none; }"
- "QScrollBar::handle:vertical { background: %3; min-height: 20px; }"
- "QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical { height: 0; }")
- .arg(colors::BG_BASE(), colors::TEXT_PRIMARY(), colors::BORDER_DIM(), colors::BG_HOVER(),
- colors::BG_RAISED(), colors::TEXT_SECONDARY()));
+ table_->setAccessibleName(tr("Open orders"));
+ apply_table_style();
connect(table_, &QTableWidget::cellDoubleClicked, this, &PolymarketOrderBlotter::on_cell_double_clicked);
vl->addWidget(table_, 1);
}
+void PolymarketOrderBlotter::apply_table_style() {
+ if (!table_)
+ return;
+ // One stylesheet for the table AND its per-row action buttons. The row
+ // controls are children of the table's viewport, so object-name selectors
+ // here reach them — that replaces two setStyleSheet() calls per row (a
+ // full CSS reparse each) on every set_orders()/update_order() rebuild.
+ table_->setStyleSheet(
+ QString("QTableWidget { background: %1; color: %2; border: none; font-size: 10px; }"
+ "QTableWidget::item { padding: 3px 8px; border-bottom: 1px solid %3; }"
+ "QTableWidget::item:selected { background: %4; color: %2; }"
+ "QHeaderView::section { background: %5; color: %6; border: none;"
+ " border-bottom: 1px solid %3; padding: 5px 8px;"
+ " font-size: 8px; font-weight: 700; letter-spacing: 0.5px; }"
+ "QScrollBar:vertical { background: %1; width: 4px; border: none; }"
+ "QScrollBar::handle:vertical { background: %3; min-height: 20px; }"
+ "QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical { height: 0; }"
+ "QPushButton#blotterRowRefresh { background: transparent; color: %6; border: 1px solid %3;"
+ " font-size: 11px; }"
+ "QPushButton#blotterRowRefresh:hover { color: %7; border-color: %7; }"
+ "QPushButton#blotterRowCancel { background: transparent; color: %8; border: 1px solid %8;"
+ " font-size: 11px; }"
+ "QPushButton#blotterRowCancel:hover { background: rgba(239,68,68,0.15); }")
+ .arg(colors::BG_BASE(), colors::TEXT_PRIMARY(), colors::BORDER_DIM(), colors::BG_HOVER(),
+ colors::BG_RAISED(), colors::TEXT_SECONDARY(), presentation_.accent.name(), colors::NEGATIVE()));
+}
+
void PolymarketOrderBlotter::set_orders(const QVector<OpenOrder>& orders) {
orders_ = orders;
rebuild_rows();
@@ -151,6 +171,7 @@ void PolymarketOrderBlotter::clear() {
void PolymarketOrderBlotter::set_presentation(const ExchangePresentation& p) {
presentation_ = p;
+ apply_table_style(); // accent drives the row refresh-button hover colour
rebuild_rows();
}
@@ -167,9 +188,24 @@ void PolymarketOrderBlotter::rebuild_rows() {
for (int i = 0; i < orders_.size(); ++i) {
const auto& o = orders_[i];
- table_->setItem(i, ColTime,
- new QTableWidgetItem(QString::number(o.expires_ms))); // placeholder: expiry
- table_->setItem(i, ColMarket, new QTableWidgetItem(o.market_id));
+ // The TIME column used to render `expires_ms` as a raw 13-digit epoch
+ // integer — unreadable, and the wrong field for the heading. Show the
+ // order's creation time formatted, with the expiry in the tooltip.
+ auto* time_item = new QTableWidgetItem(
+ o.created_ms > 0 ? QDateTime::fromMSecsSinceEpoch(o.created_ms).toString(QStringLiteral("MM-dd HH:mm:ss"))
+ : QStringLiteral("—"));
+ time_item->setData(Qt::UserRole, QVariant::fromValue(o.created_ms));
+ time_item->setToolTip(o.expires_ms > 0
+ ? tr("Expires %1").arg(QDateTime::fromMSecsSinceEpoch(o.expires_ms).toString(
+ QStringLiteral("yyyy-MM-dd HH:mm:ss")))
+ : tr("No expiry (good-till-cancelled)"));
+ table_->setItem(i, ColTime, time_item);
+
+ auto* market_item = new QTableWidgetItem(o.market_id);
+ // The cancel button targets order_id — surface it so the user can
+ // verify which order a row's ✕ will actually cancel.
+ market_item->setToolTip(tr("Order ID: %1").arg(o.order_id));
+ table_->setItem(i, ColMarket, market_item);
auto* side_item = new QTableWidgetItem(o.side);
side_item->setForeground(
@@ -220,24 +256,29 @@ void PolymarketOrderBlotter::install_row_controls(int row, const OpenOrder& orde
rhl->setContentsMargins(4, 0, 4, 0);
rhl->setSpacing(4);
+ // Styling comes from the table-level stylesheet (see apply_table_style)
+ // via these object names — no per-row setStyleSheet.
auto* refresh_btn = new QPushButton(QStringLiteral("↻"), host);
+ refresh_btn->setObjectName(QStringLiteral("blotterRowRefresh"));
refresh_btn->setFixedSize(22, 20);
refresh_btn->setCursor(Qt::PointingHandCursor);
refresh_btn->setToolTip(tr("Refresh order state"));
- refresh_btn->setStyleSheet(QString("QPushButton { background: transparent; color: %1; border: 1px solid %2; "
- "font-size: 11px; } QPushButton:hover { color: %3; border-color: %3; }")
- .arg(colors::TEXT_SECONDARY(), colors::BORDER_DIM(), presentation_.accent.name()));
+ refresh_btn->setAccessibleName(tr("Refresh order %1").arg(order.order_id));
const QString oid = order.order_id;
connect(refresh_btn, &QPushButton::clicked, this, [this, oid]() { emit refresh_order(oid); });
rhl->addWidget(refresh_btn);
auto* cancel_btn = new QPushButton(QStringLiteral("✕"), host);
+ cancel_btn->setObjectName(QStringLiteral("blotterRowCancel"));
cancel_btn->setFixedSize(22, 20);
cancel_btn->setCursor(Qt::PointingHandCursor);
- cancel_btn->setToolTip(tr("Cancel order"));
- cancel_btn->setStyleSheet(QString("QPushButton { background: transparent; color: %1; border: 1px solid %1; "
- "font-size: 11px; } QPushButton:hover { background: rgba(239,68,68,0.15); }")
- .arg(colors::NEGATIVE()));
+ // Spell out exactly which order the ✕ targets — the row's own id, not the
+ // selected row's.
+ cancel_btn->setToolTip(tr("Cancel %1 %2 @ %3 (id %4)")
+ .arg(order.side, order.outcome)
+ .arg(order.price, 0, 'f', qBound(0, presentation_.price_decimal_places, 6))
+ .arg(order.order_id));
+ cancel_btn->setAccessibleName(tr("Cancel order %1").arg(order.order_id));
connect(cancel_btn, &QPushButton::clicked, this, [this, oid]() { emit cancel_order(oid); });
rhl->addWidget(cancel_btn);
@@ -270,8 +311,19 @@ void PolymarketOrderBlotter::on_cancel_all_clicked() {
for (const auto& o : orders_)
if (!o.order_id.isEmpty())
ids.push_back(o.order_id);
- if (!ids.isEmpty())
- emit cancel_all(ids);
+ if (ids.isEmpty())
+ return;
+ // Pulling every resting order off the book is destructive and was a
+ // single unguarded click. Confirm, and say how many.
+ const auto choice = QMessageBox::warning(
+ this, tr("Cancel all orders?"),
+ tr("Cancel all %1 open order(s) on %2?\n\nThis cannot be undone — any partially filled quantity stays filled.")
+ .arg(ids.size())
+ .arg(presentation_.display_name.isEmpty() ? tr("this exchange") : presentation_.display_name),
+ QMessageBox::Cancel | QMessageBox::Yes, QMessageBox::Cancel);
+ if (choice != QMessageBox::Yes)
+ return;
+ emit cancel_all(ids);
}
void PolymarketOrderBlotter::changeEvent(QEvent* event) {
diff --git a/fincept-qt/src/screens/polymarket/PolymarketOrderBlotter.h b/fincept-qt/src/screens/polymarket/PolymarketOrderBlotter.h
index 3c27d2d83..f6dcdc742 100644
--- a/fincept-qt/src/screens/polymarket/PolymarketOrderBlotter.h
+++ b/fincept-qt/src/screens/polymarket/PolymarketOrderBlotter.h
@@ -60,6 +60,9 @@ class PolymarketOrderBlotter : public QWidget {
private:
void rebuild_rows();
void install_row_controls(int row, const fincept::services::prediction::OpenOrder& order);
+ /// Compose the table stylesheet, including object-name rules for the
+ /// per-row action buttons so those never need their own setStyleSheet.
+ void apply_table_style();
void retranslateUi();
QLabel* title_label_ = nullptr;
diff --git a/fincept-qt/src/screens/polymarket/PolymarketOrderBook.cpp b/fincept-qt/src/screens/polymarket/PolymarketOrderBook.cpp
index d7cd55235..168d304a3 100644
--- a/fincept-qt/src/screens/polymarket/PolymarketOrderBook.cpp
+++ b/fincept-qt/src/screens/polymarket/PolymarketOrderBook.cpp
@@ -16,6 +16,8 @@ using namespace fincept::services::prediction;
PolymarketOrderBook::PolymarketOrderBook(QWidget* parent) : QWidget(parent) {
setMinimumHeight(200);
+ setAccessibleName(tr("Order book"));
+ setToolTip(tr("Click a price level to load it into the trade ticket."));
connect(&ui::ThemeManager::instance(), &ui::ThemeManager::theme_changed, this, [this](const ui::ThemeTokens&) {
cache_dirty_ = true;
diff --git a/fincept-qt/src/screens/polymarket/PolymarketScreen.cpp b/fincept-qt/src/screens/polymarket/PolymarketScreen.cpp
index d2511b749..0585c5631 100644
--- a/fincept-qt/src/screens/polymarket/PolymarketScreen.cpp
+++ b/fincept-qt/src/screens/polymarket/PolymarketScreen.cpp
@@ -19,10 +19,13 @@
#include "services/prediction/polymarket/PolymarketAdapter.h"
#include "ui/theme/Theme.h"
+#include <QDateTime>
+#include <QPointer>
#include <QSplitter>
#include <QVBoxLayout>
#include <cmath>
+#include <memory>
namespace fincept::screens {
@@ -231,10 +234,15 @@ void PolymarketScreen::build_ui() {
command_bar_->set_account_status(any, label);
LOG_INFO("PredictionMarkets", "Credentials saved for " + id);
});
- connect(dlg, &PredictionAccountDialog::test_requested, this, [](const QString& id) {
+ QPointer<PredictionAccountDialog> dlg_guard = dlg;
+ connect(dlg, &PredictionAccountDialog::test_requested, this, [dlg_guard](const QString& id) {
auto* adapter = pred::PredictionExchangeRegistry::instance().adapter(id);
- if (!adapter)
+ if (!adapter) {
+ if (dlg_guard)
+ dlg_guard->set_test_result(id, false,
+ PolymarketScreen::tr("No adapter registered for %1").arg(id));
return;
+ }
if (id == kPolymarketId()) {
if (auto* pm = dynamic_cast<pred::polymarket_ns::PolymarketAdapter*>(adapter))
pm->reload_credentials();
@@ -244,6 +252,32 @@ void PolymarketScreen::build_ui() {
ks->set_credentials(*creds);
}
}
+ // Report the round-trip back into the dialog. Previously the Test
+ // button fired fetch_balance() and the user saw nothing at all.
+ // Both connections are scoped to the dialog and one-shot.
+ if (dlg_guard) {
+ auto ok_conn = std::make_shared<QMetaObject::Connection>();
+ auto err_conn = std::make_shared<QMetaObject::Connection>();
+ *ok_conn = QObject::connect(
+ adapter, &pred::PredictionExchangeAdapter::balance_ready, dlg_guard.data(),
+ [dlg_guard, id, ok_conn, err_conn](const pred::AccountBalance& b) {
+ QObject::disconnect(*ok_conn);
+ QObject::disconnect(*err_conn);
+ if (dlg_guard)
+ dlg_guard->set_test_result(
+ id, true, QStringLiteral("%1 %2").arg(b.available, 0, 'f', 2).arg(b.currency));
+ });
+ *err_conn = QObject::connect(
+ adapter, &pred::PredictionExchangeAdapter::error_occurred, dlg_guard.data(),
+ [dlg_guard, id, ok_conn, err_conn](const QString& ctx, const QString& msg) {
+ if (!ctx.contains(QStringLiteral("balance"), Qt::CaseInsensitive))
+ return; // unrelated adapter error — keep waiting
+ QObject::disconnect(*ok_conn);
+ QObject::disconnect(*err_conn);
+ if (dlg_guard)
+ dlg_guard->set_test_result(id, false, msg);
+ });
+ }
adapter->fetch_balance();
});
dlg->setAttribute(Qt::WA_DeleteOnClose);
diff --git a/fincept-qt/src/screens/polymarket/PredictionAccountDialog.cpp b/fincept-qt/src/screens/polymarket/PredictionAccountDialog.cpp
index 03811f68d..b527952c9 100644
--- a/fincept-qt/src/screens/polymarket/PredictionAccountDialog.cpp
+++ b/fincept-qt/src/screens/polymarket/PredictionAccountDialog.cpp
@@ -44,6 +44,23 @@ void PredictionAccountDialog::set_active_exchange(const QString& exchange_id) {
tabs_->setCurrentIndex(0);
}
+void PredictionAccountDialog::set_test_result(const QString& exchange_id, bool ok, const QString& message) {
+ QLabel* target = (exchange_id == QStringLiteral("kalshi")) ? ks_status_ : pm_status_;
+ if (!target)
+ return;
+ const QString color = ok ? QStringLiteral("#16a34a") : QStringLiteral("#dc2626");
+ const QString head = ok ? tr("Connection OK") : tr("Connection failed");
+ target->setText(QStringLiteral("<span style='color:%1'>%2%3</span>")
+ .arg(color, head, message.isEmpty() ? QString() : QStringLiteral(" — ") + message.toHtmlEscaped()));
+ // Re-enable the button so the user can retry.
+ if (exchange_id == QStringLiteral("kalshi")) {
+ if (ks_test_btn_)
+ ks_test_btn_->setEnabled(true);
+ } else if (pm_test_btn_) {
+ pm_test_btn_->setEnabled(true);
+ }
+}
+
// ── UI ──────────────────────────────────────────────────────────────────────
void PredictionAccountDialog::build_ui() {
diff --git a/fincept-qt/src/screens/polymarket/PredictionAccountDialog.h b/fincept-qt/src/screens/polymarket/PredictionAccountDialog.h
index 34d8f3414..608b501d4 100644
--- a/fincept-qt/src/screens/polymarket/PredictionAccountDialog.h
+++ b/fincept-qt/src/screens/polymarket/PredictionAccountDialog.h
@@ -32,6 +32,11 @@ class PredictionAccountDialog : public QDialog {
/// Select which tab is shown initially.
void set_active_exchange(const QString& exchange_id);
+ /// Report the outcome of a "Test Connection" round-trip back into the
+ /// dialog's per-exchange status line. Without this the Test button gave
+ /// no visible feedback at all.
+ void set_test_result(const QString& exchange_id, bool ok, const QString& message);
+
signals:
/// Emitted after the user clicks Save and credentials are persisted.
/// `exchange_id` is "polymarket" or "kalshi". Screens should reload
diff --git a/fincept-qt/src/screens/portfolio/PortfolioBlotter.cpp b/fincept-qt/src/screens/portfolio/PortfolioBlotter.cpp
index 6bd25c682..c377b69ab 100644
--- a/fincept-qt/src/screens/portfolio/PortfolioBlotter.cpp
+++ b/fincept-qt/src/screens/portfolio/PortfolioBlotter.cpp
@@ -17,12 +17,15 @@
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
+#include <QLocale>
#include <QMenu>
#include <QMetaObject>
+#include <QScrollBar>
#include <QVBoxLayout>
#include <algorithm>
#include <cmath>
+#include <utility>
namespace fincept::screens {
@@ -43,6 +46,25 @@ static const char* const kColumnKeys[] = {
};
static constexpr int kColumnCount = sizeof(kColumnKeys) / sizeof(kColumnKeys[0]);
+// Named column indices — the layout was previously spelled out as bare
+// integers in five places (populate_table, update_row_price,
+// repaint_sparkline_cells, on_header_clicked), which is exactly how the live
+// broker tick ended up writing the last price into the AVG COST column.
+enum Column {
+ kColSymbol = 0,
+ kColQty = 1,
+ kColLast = 2,
+ kColAvgCost = 3,
+ kColMktVal = 4,
+ kColCostBasis = 5,
+ kColPnl = 6,
+ kColPnlPct = 7,
+ kColChgPct = 8,
+ kColTrend = 9,
+ kColWeight = 10,
+};
+static_assert(kColWeight + 1 == kColumnCount, "Column enum and kColumnKeys are out of sync");
+
PortfolioBlotter::PortfolioBlotter(QWidget* parent) : QWidget(parent) {
// Restore persisted page size before building the UI so the combo and
// populate_table see the right value on first paint.
@@ -87,16 +109,18 @@ void PortfolioBlotter::build_ui() {
hdr->setSortIndicatorShown(false);
hdr->setSectionResizeMode(QHeaderView::Stretch);
+ // Markers must be contiguous and match the args 1:1 — QString::arg fills the
+ // LOWEST marker present, so the old %5-less numbering pushed AMBER onto
+ // :hover and dropped BG_HOVER with an "Argument missing" warning.
table_->setStyleSheet(QString("QTableWidget { background:%1; color:%2; border:none;"
" font-size:11px; font-family:%3; gridline-color:transparent; }"
"QTableWidget::item { padding:5px 8px; border-bottom:1px solid %4; }"
- "QTableWidget::item:selected { background:rgba(217,119,6,0.10); color:%6; }"
- "QTableWidget::item:hover { background:%7; }"
+ "QTableWidget::item:selected { background:rgba(217,119,6,0.10); color:%5; }"
+ "QTableWidget::item:hover { background:%6; }"
"QScrollBar:vertical { width:5px; background:%1; }"
"QScrollBar::handle:vertical { background:%4; min-height:20px; }")
.arg(ui::colors::BG_BASE(), ui::colors::TEXT_PRIMARY(), ui::fonts::DATA_FAMILY,
- ui::colors::BORDER_DIM(), ui::colors::AMBER_DIM(), ui::colors::AMBER(),
- ui::colors::BG_HOVER()));
+ ui::colors::BORDER_DIM(), ui::colors::AMBER(), ui::colors::BG_HOVER()));
// Apply the header rule directly on the header widget — the global qApp
// stylesheet (ThemeManager.cpp) defines QHeaderView::section with
@@ -165,6 +189,9 @@ void PortfolioBlotter::build_pagination_footer() {
btn_first_ = make_nav_btn(QStringLiteral("«"), tr("First page"));
btn_prev_ = make_nav_btn(QStringLiteral("‹"), tr("Previous page"));
+ // Glyph-only buttons are opaque to screen readers.
+ btn_first_->setAccessibleName(tr("First page"));
+ btn_prev_->setAccessibleName(tr("Previous page"));
h->addWidget(btn_first_);
h->addWidget(btn_prev_);
@@ -177,6 +204,8 @@ void PortfolioBlotter::build_pagination_footer() {
btn_next_ = make_nav_btn(QStringLiteral("›"), tr("Next page"));
btn_last_ = make_nav_btn(QStringLiteral("»"), tr("Last page"));
+ btn_next_->setAccessibleName(tr("Next page"));
+ btn_last_->setAccessibleName(tr("Last page"));
h->addWidget(btn_next_);
h->addWidget(btn_last_);
@@ -255,6 +284,7 @@ void PortfolioBlotter::build_pagination_footer() {
void PortfolioBlotter::set_holdings(const QVector<portfolio::HoldingWithQuote>& holdings) {
holdings_ = holdings;
+ invalidate_view_cache();
populate_table();
fetch_sparklines(); // async — repaints sparkline cells when data arrives
}
@@ -272,11 +302,14 @@ void PortfolioBlotter::fetch_sparklines() {
void PortfolioBlotter::repaint_sparkline_cells() {
for (int r = 0; r < table_->rowCount(); ++r) {
- auto* item = table_->item(r, 0);
+ auto* item = table_->item(r, kColSymbol);
if (!item)
continue;
- const QString sym = item->text();
- auto* w = qobject_cast<PortfolioSparkline*>(table_->cellWidget(r, 9));
+ // Use the stashed raw symbol, not the cell text — the two are the same
+ // today but the text is a display string and may gain decoration.
+ const QString sym = item->data(Qt::UserRole).toString().isEmpty() ? item->text()
+ : item->data(Qt::UserRole).toString();
+ auto* w = qobject_cast<PortfolioSparkline*>(table_->cellWidget(r, kColTrend));
if (!w)
continue;
@@ -363,31 +396,37 @@ void PortfolioBlotter::hub_resubscribe_broker_quotes(const QString& broker_accou
void PortfolioBlotter::update_row_price(const QString& symbol, double ltp, double change_pct) {
for (int r = 0; r < table_->rowCount(); ++r) {
- auto* item = table_->item(r, 0);
+ auto* item = table_->item(r, kColSymbol);
if (!item || item->data(Qt::UserRole).toString() != symbol)
continue;
- // Column layout: SYMBOL(0), QTY(1), LAST(2), AVG COST(3), MKT VAL(4), COST BASIS(5), P&L(6), P&L%(7),
- // CHG%(8), TREND(9), WT%(10). LAST is column 2 — the old code wrote the
- // live price into column 3 (AVG COST), corrupting the displayed cost.
- if (auto* last_item = table_->item(r, 2))
+ if (auto* last_item = table_->item(r, kColLast))
last_item->setText(format_value(ltp));
// Recalculate market value & P&L from holdings data
const int idx = r + (current_page_ - 1) * page_size_;
- auto view = visible_view();
+ const auto& view = visible_view();
if (idx >= 0 && idx < view.size()) {
- auto& h = view[idx];
- double mkt_val = ltp * h.quantity;
- double pnl = mkt_val - h.cost_basis;
- double pnl_pct = h.cost_basis > 0 ? (pnl / h.cost_basis) * 100.0 : 0.0;
- if (auto* mv = table_->item(r, 4))
+ const auto& h = view[idx];
+ const double mkt_val = ltp * h.quantity;
+ const double pnl = mkt_val - h.cost_basis;
+ const double pnl_pct = h.cost_basis > 0 ? (pnl / h.cost_basis) * 100.0 : 0.0;
+ const char* pnl_color = pnl >= 0 ? ui::colors::POSITIVE : ui::colors::NEGATIVE;
+ if (auto* mv = table_->item(r, kColMktVal))
mv->setText(format_value(mkt_val));
- if (auto* pnl_item = table_->item(r, 6))
- pnl_item->setText(format_value(pnl));
- if (auto* pnl_pct_item = table_->item(r, 7))
- pnl_pct_item->setText(QString("%1%").arg(pnl_pct, 0, 'f', 2));
+ if (auto* pnl_item = table_->item(r, kColPnl)) {
+ pnl_item->setText(QString("%1%2").arg(pnl >= 0 ? "+" : "").arg(format_value(pnl)));
+ // Recolour too: a tick that flipped a position from green to
+ // red kept the stale green foreground until the next full poll.
+ pnl_item->setForeground(QColor(pnl_color));
+ }
+ if (auto* pnl_pct_item = table_->item(r, kColPnlPct)) {
+ pnl_pct_item->setText(
+ QString("%1%2%").arg(pnl_pct >= 0 ? "+" : "").arg(format_value(pnl_pct)));
+ pnl_pct_item->setForeground(QColor(pnl_color));
+ }
}
- if (auto* chg = table_->item(r, 8)) {
- chg->setText(QString("%1%").arg(change_pct, 0, 'f', 2));
+ if (auto* chg = table_->item(r, kColChgPct)) {
+ // Signed, matching how populate_table renders the same column.
+ chg->setText(QString("%1%2%").arg(change_pct >= 0 ? "+" : "").arg(format_value(change_pct)));
chg->setForeground(QColor(change_pct >= 0 ? ui::colors::POSITIVE() : ui::colors::NEGATIVE()));
}
break;
@@ -397,37 +436,42 @@ void PortfolioBlotter::update_row_price(const QString& symbol, double ltp, doubl
void PortfolioBlotter::set_selected_symbol(const QString& symbol) {
selected_symbol_ = symbol;
for (int r = 0; r < table_->rowCount(); ++r) {
- auto* item = table_->item(r, 0);
- if (item && item->text() == symbol) {
+ auto* item = table_->item(r, kColSymbol);
+ // Match on the stashed raw symbol (see populate_table) so this keeps
+ // working if the symbol cell ever gains display decoration.
+ if (item && item->data(Qt::UserRole).toString() == symbol) {
table_->selectRow(r);
return;
}
}
+ // Not on this page: clear the highlight instead of leaving the previous
+ // row looking selected while the selection actually lives elsewhere.
+ table_->clearSelection();
}
void PortfolioBlotter::on_header_clicked(int section) {
// Map column index to SortColumn
portfolio::SortColumn col;
switch (section) {
- case 0:
+ case kColSymbol:
col = portfolio::SortColumn::Symbol;
break;
- case 2:
+ case kColLast:
col = portfolio::SortColumn::Price;
break;
- case 4:
+ case kColMktVal:
col = portfolio::SortColumn::MarketValue;
break;
- case 6:
+ case kColPnl:
col = portfolio::SortColumn::Pnl;
break;
- case 7:
+ case kColPnlPct:
col = portfolio::SortColumn::PnlPct;
break;
- case 8:
+ case kColChgPct:
col = portfolio::SortColumn::Change;
break;
- case 10:
+ case kColWeight:
col = portfolio::SortColumn::Weight;
break;
default:
@@ -461,10 +505,16 @@ void PortfolioBlotter::on_row_clicked(int row, int) {
// ── Pagination helpers ──────────────────────────────────────────────────────
-QVector<portfolio::HoldingWithQuote> PortfolioBlotter::visible_view() const {
+void PortfolioBlotter::invalidate_view_cache() {
+ view_cache_valid_ = false;
+ view_cache_.clear();
+}
+
+const QVector<portfolio::HoldingWithQuote>& PortfolioBlotter::visible_view() const {
+ if (view_cache_valid_)
+ return view_cache_;
+
// Apply text filter + sector filter on top of the already-sorted set.
- // We rebuild this every populate_table — the dataset is bounded (a few
- // hundred holdings at most for a real portfolio).
QVector<portfolio::HoldingWithQuote> out;
out.reserve(sorted_.size());
const QString needle = filter_text_.toLower();
@@ -483,11 +533,14 @@ QVector<portfolio::HoldingWithQuote> PortfolioBlotter::visible_view() const {
continue;
out.append(h);
}
- return out;
+
+ view_cache_ = std::move(out);
+ view_cache_valid_ = true;
+ return view_cache_;
}
QVector<portfolio::HoldingWithQuote> PortfolioBlotter::paged_view() const {
- const auto all = visible_view();
+ const auto& all = visible_view();
if (page_size_ <= 0)
return all;
const int start = (current_page_ - 1) * page_size_;
@@ -536,16 +589,12 @@ void PortfolioBlotter::update_pagination_controls() {
}
void PortfolioBlotter::populate_table() {
- // Clean up old sparkline cell widgets before repopulating (prevents memory leak)
- for (int r = 0; r < table_->rowCount(); ++r) {
- auto* w = table_->cellWidget(r, 9);
- if (w) {
- table_->removeCellWidget(r, 9);
- w->deleteLater();
- }
- }
+ // Remember the scroll offset so a background refresh does not yank the
+ // table back to the top while the user is reading a row further down.
+ const int prev_scroll = table_->verticalScrollBar() ? table_->verticalScrollBar()->value() : 0;
sorted_ = holdings_;
+ invalidate_view_cache();
// Sort
bool asc = (sort_dir_ == portfolio::SortDirection::Asc);
@@ -588,6 +637,16 @@ void PortfolioBlotter::populate_table() {
// a filter/sort change shrinks the view below the current page index.
clamp_current_page();
const auto page_rows = paged_view();
+
+ // Sparklines are pooled per row: they own a cached QPixmap and re-creating
+ // one per row on every 60 s poll threw that cache away. Only rows that are
+ // disappearing release their widget.
+ for (int r = page_rows.size(); r < table_->rowCount(); ++r) {
+ if (auto* w = table_->cellWidget(r, kColTrend)) {
+ table_->removeCellWidget(r, kColTrend);
+ w->deleteLater();
+ }
+ }
table_->setRowCount(page_rows.size());
for (int r = 0; r < page_rows.size(); ++r) {
@@ -606,47 +665,53 @@ void PortfolioBlotter::populate_table() {
};
// SYMBOL
- set_cell(0, h.symbol, ui::colors::CYAN, Qt::AlignLeft | Qt::AlignVCenter);
+ set_cell(kColSymbol, h.symbol, ui::colors::CYAN, Qt::AlignLeft | Qt::AlignVCenter);
// Stash the raw symbol on the cell so live broker-price ticks
// (update_row_price) can locate this row — its guard matches col-0
// Qt::UserRole, which was never set, so live prices never updated.
- if (auto* sym_item = table_->item(r, 0))
+ if (auto* sym_item = table_->item(r, kColSymbol))
sym_item->setData(Qt::UserRole, h.symbol);
// QTY
- set_cell(1, format_value(h.quantity, h.quantity == std::floor(h.quantity) ? 0 : 2));
+ set_cell(kColQty, format_value(h.quantity, h.quantity == std::floor(h.quantity) ? 0 : 2));
// LAST (price)
- set_cell(2, format_value(h.current_price));
+ set_cell(kColLast, format_value(h.current_price));
// AVG COST
- set_cell(3, format_value(h.avg_buy_price));
+ set_cell(kColAvgCost, format_value(h.avg_buy_price));
// MKT VAL
- set_cell(4, format_value(h.market_value), ui::colors::WARNING);
+ set_cell(kColMktVal, format_value(h.market_value), ui::colors::WARNING);
// COST BASIS
- set_cell(5, format_value(h.cost_basis));
+ set_cell(kColCostBasis, format_value(h.cost_basis));
// P&L
const char* pnl_color = h.unrealized_pnl >= 0 ? ui::colors::POSITIVE : ui::colors::NEGATIVE;
- set_cell(6, QString("%1%2").arg(h.unrealized_pnl >= 0 ? "+" : "").arg(format_value(h.unrealized_pnl)),
+ set_cell(kColPnl, QString("%1%2").arg(h.unrealized_pnl >= 0 ? "+" : "").arg(format_value(h.unrealized_pnl)),
pnl_color);
// P&L%
set_cell(
- 7,
+ kColPnlPct,
QString("%1%2%").arg(h.unrealized_pnl_percent >= 0 ? "+" : "").arg(format_value(h.unrealized_pnl_percent)),
pnl_color);
// CHG%
const char* chg_color = h.day_change_percent >= 0 ? ui::colors::POSITIVE : ui::colors::NEGATIVE;
- set_cell(8, QString("%1%2%").arg(h.day_change_percent >= 0 ? "+" : "").arg(format_value(h.day_change_percent)),
+ set_cell(kColChgPct,
+ QString("%1%2%").arg(h.day_change_percent >= 0 ? "+" : "").arg(format_value(h.day_change_percent)),
chg_color);
- // TREND — show loaded data, a pending shimmer, or a failure dash
- auto* sparkline = new PortfolioSparkline(0, 0);
- sparkline->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
+ // TREND — show loaded data, a pending shimmer, or a failure dash.
+ // Reuse the row's existing sparkline widget when there is one.
+ auto* sparkline = qobject_cast<PortfolioSparkline*>(table_->cellWidget(r, kColTrend));
+ if (!sparkline) {
+ sparkline = new PortfolioSparkline(0, 0);
+ sparkline->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
+ table_->setCellWidget(r, kColTrend, sparkline);
+ }
const auto state = sparkline_state_.value(h.symbol, SparklineState::Pending);
if (state == SparklineState::Loaded && sparkline_cache_.contains(h.symbol)) {
const auto& prices = sparkline_cache_[h.symbol];
@@ -664,10 +729,9 @@ void PortfolioBlotter::populate_table() {
sparkline->set_data(pending);
sparkline->set_color(QColor(ui::colors::TEXT_TERTIARY()));
}
- table_->setCellWidget(r, 9, sparkline);
// WT%
- set_cell(10, QString("%1%").arg(format_value(h.weight, 1)));
+ set_cell(kColWeight, QString("%1%").arg(format_value(h.weight, 1)));
// Highlight selected row
if (h.symbol == selected_symbol_) {
@@ -675,21 +739,51 @@ void PortfolioBlotter::populate_table() {
}
}
+ // Empty state — an unexplained blank grid reads as a bug. Distinguish
+ // "portfolio has nothing in it" from "your filter hid everything".
+ table_->clearSpans();
+ if (page_rows.isEmpty()) {
+ table_->setRowCount(1);
+ table_->setRowHeight(0, 40);
+ const bool filtered = !filter_text_.isEmpty() || !sector_symbols_.isEmpty();
+ auto* msg = new QTableWidgetItem(filtered ? tr("No positions match the current filter.")
+ : tr("No positions yet — use BUY to add your first holding."));
+ msg->setTextAlignment(Qt::AlignCenter);
+ msg->setForeground(QColor(ui::colors::TEXT_TERTIARY()));
+ msg->setFlags(Qt::ItemIsEnabled); // informational, not selectable
+ table_->setItem(0, kColSymbol, msg);
+ table_->setSpan(0, 0, 1, kColumnCount);
+ }
+
+ // Restore the scroll offset (clamped by the scrollbar itself when the row
+ // count shrank).
+ if (table_->verticalScrollBar())
+ table_->verticalScrollBar()->setValue(prev_scroll);
+
// Footer status + nav button enabled-state must reflect what we just rendered.
update_pagination_controls();
}
QString PortfolioBlotter::format_value(double v, int dp) const {
- return QString::number(v, 'f', dp);
+ // Locale-aware: groups thousands so a six-figure market value is readable
+ // and matches PortfolioStatsRibbon / PortfolioStatusBar.
+ return QLocale().toString(v, 'f', dp);
}
void PortfolioBlotter::set_filter(const QString& text) {
- filter_text_ = text.trimmed().toLower();
+ const QString needle = text.trimmed().toLower();
+ if (needle == filter_text_)
+ return;
+ filter_text_ = needle;
+ invalidate_view_cache();
apply_filter();
}
void PortfolioBlotter::set_sector_filter(const QStringList& symbols) {
+ if (sector_symbols_ == symbols)
+ return;
sector_symbols_ = symbols;
+ invalidate_view_cache();
apply_filter();
}
@@ -731,13 +825,16 @@ void PortfolioBlotter::on_context_menu(const QPoint& pos) {
auto* edit_act = menu.addAction(tr("Edit Transaction"));
auto* delete_act = menu.addAction(tr("Close / Delete Position"));
- edit_act->setIcon(QIcon());
- delete_act->setIcon(QIcon());
-
- // Style delete action in red
- delete_act->setData("danger");
- menu.setStyleSheet(menu.styleSheet() +
- QString("QMenu::item[data='danger'] { color:%1; }").arg(ui::colors::NEGATIVE()));
+ // Mark the destructive item so it does not read as a peer of "Edit".
+ // The previous attempt used `QMenu::item[data='danger']` — QSS attribute
+ // selectors match Q_PROPERTYs on the styled *widget*, not QAction::setData,
+ // so it matched nothing and the item rendered in the default colour. Two
+ // setIcon(QIcon()) calls next to it were pure no-ops and are gone.
+ delete_act->setFont([&] {
+ QFont f = menu.font();
+ f.setBold(true);
+ return f;
+ }());
connect(edit_act, &QAction::triggered, this, [this, symbol]() { emit edit_transaction_requested(symbol); });
connect(delete_act, &QAction::triggered, this, [this, symbol]() { emit delete_position_requested(symbol); });
@@ -753,13 +850,12 @@ void PortfolioBlotter::refresh_theme() {
bsz +
"px; font-family:%3; gridline-color:transparent; }"
"QTableWidget::item { padding:5px 8px; border-bottom:1px solid %4; }"
- "QTableWidget::item:selected { background:rgba(217,119,6,0.10); color:%6; }"
- "QTableWidget::item:hover { background:%7; }"
+ "QTableWidget::item:selected { background:rgba(217,119,6,0.10); color:%5; }"
+ "QTableWidget::item:hover { background:%6; }"
"QScrollBar:vertical { width:5px; background:%1; }"
"QScrollBar::handle:vertical { background:%4; min-height:20px; }")
.arg(ui::colors::BG_BASE(), ui::colors::TEXT_PRIMARY(), ui::fonts::DATA_FAMILY,
- ui::colors::BORDER_DIM(), ui::colors::AMBER_DIM(), ui::colors::AMBER(),
- ui::colors::BG_HOVER()));
+ ui::colors::BORDER_DIM(), ui::colors::AMBER(), ui::colors::BG_HOVER()));
// See note in build constructor — header rule must live on the header
// widget itself or the global qApp stylesheet wins.
table_->horizontalHeader()->setStyleSheet(QString("QHeaderView::section { background:%1; color:%2; border:none;"
@@ -787,14 +883,24 @@ void PortfolioBlotter::retranslateUi() {
table_->setHorizontalHeaderLabels(headers);
}
- if (btn_first_)
+ if (btn_first_) {
btn_first_->setToolTip(tr("First page"));
- if (btn_prev_)
+ btn_first_->setAccessibleName(tr("First page"));
+ }
+ if (btn_prev_) {
btn_prev_->setToolTip(tr("Previous page"));
- if (btn_next_)
+ btn_prev_->setAccessibleName(tr("Previous page"));
+ }
+ if (btn_next_) {
btn_next_->setToolTip(tr("Next page"));
- if (btn_last_)
+ btn_next_->setAccessibleName(tr("Next page"));
+ }
+ if (btn_last_) {
btn_last_->setToolTip(tr("Last page"));
+ btn_last_->setAccessibleName(tr("Last page"));
+ }
+ if (page_size_combo_)
+ page_size_combo_->setAccessibleName(tr("Rows per page"));
if (footer_rows_label_)
footer_rows_label_->setText(tr("Rows:"));
diff --git a/fincept-qt/src/screens/portfolio/PortfolioBlotter.h b/fincept-qt/src/screens/portfolio/PortfolioBlotter.h
index 6cfd2f7a9..1602e7921 100644
--- a/fincept-qt/src/screens/portfolio/PortfolioBlotter.h
+++ b/fincept-qt/src/screens/portfolio/PortfolioBlotter.h
@@ -51,8 +51,15 @@ class PortfolioBlotter : public QWidget {
// ── Pagination ──────────────────────────────────────────────────────────
/// Filtered + sorted view (after filter/sector trim) used as the source
- /// of truth for pagination math. Recomputed every populate_table().
- QVector<portfolio::HoldingWithQuote> visible_view() const;
+ /// of truth for pagination math.
+ ///
+ /// Memoised: a single populate_table() used to call this five times (clamp
+ /// → total_pages → paged_view → update_pagination_controls → total_pages),
+ /// each one re-filtering and deep-copying the whole holdings vector, and
+ /// every live broker tick called it again per row.
+ const QVector<portfolio::HoldingWithQuote>& visible_view() const;
+ /// Drop the memoised view. Call whenever holdings/filter/sort change.
+ void invalidate_view_cache();
/// Rows for the current page only — what actually goes into table_.
QVector<portfolio::HoldingWithQuote> paged_view() const;
/// Update footer labels + button enabled-states from current state.
@@ -85,6 +92,8 @@ class PortfolioBlotter : public QWidget {
QVector<portfolio::HoldingWithQuote> holdings_;
QVector<portfolio::HoldingWithQuote> sorted_;
+ mutable QVector<portfolio::HoldingWithQuote> view_cache_;
+ mutable bool view_cache_valid_ = false;
QString selected_symbol_;
QString filter_text_;
QStringList sector_symbols_; // empty = no sector filter
diff --git a/fincept-qt/src/screens/portfolio/PortfolioCommandBar.cpp b/fincept-qt/src/screens/portfolio/PortfolioCommandBar.cpp
index e8d383adf..c1db96651 100644
--- a/fincept-qt/src/screens/portfolio/PortfolioCommandBar.cpp
+++ b/fincept-qt/src/screens/portfolio/PortfolioCommandBar.cpp
@@ -8,6 +8,7 @@
#include <QEvent>
#include <QFrame>
#include <QHBoxLayout>
+#include <QKeySequence>
#include <QMenu>
#include <QScrollArea>
#include <QToolButton>
@@ -97,8 +98,10 @@ void PortfolioCommandBar::build_row1(QHBoxLayout* layout) {
refresh_btn_ = new QPushButton("\u21BB");
refresh_btn_->setFixedSize(24, 22);
refresh_btn_->setCursor(Qt::PointingHandCursor);
- refresh_btn_->setToolTip(tr("Refresh portfolio data"));
+ refresh_btn_->setToolTip(tr("Refresh portfolio data (F5)"));
+ refresh_btn_->setAccessibleName(tr("Refresh portfolio data"));
refresh_btn_->setObjectName("pfIconBtn");
+ refresh_btn_->setShortcut(QKeySequence(QKeySequence::Refresh)); // F5 / Ctrl+R
connect(refresh_btn_, &QPushButton::clicked, this, &PortfolioCommandBar::refresh_requested);
layout->addWidget(refresh_btn_);
@@ -310,6 +313,17 @@ void PortfolioCommandBar::build_trade_cluster(QHBoxLayout* layout) {
make_trade_btn(buy_btn_, tr("BUY"), ui::colors::POSITIVE(), &PortfolioCommandBar::buy_requested);
make_trade_btn(sell_btn_, tr("SELL"), ui::colors::NEGATIVE(), &PortfolioCommandBar::sell_requested);
make_trade_btn(div_btn_, tr("DIV"), ui::colors::CYAN(), &PortfolioCommandBar::dividend_requested);
+
+ // Power-user keys. "DIV" in particular is unguessable from the label alone.
+ buy_btn_->setShortcut(QKeySequence(QStringLiteral("Ctrl+B")));
+ buy_btn_->setToolTip(tr("Buy / add to a position (Ctrl+B)"));
+ buy_btn_->setAccessibleName(tr("Buy or add to a position"));
+ sell_btn_->setShortcut(QKeySequence(QStringLiteral("Ctrl+S")));
+ sell_btn_->setToolTip(tr("Sell / trim a position (Ctrl+S)"));
+ sell_btn_->setAccessibleName(tr("Sell or trim a position"));
+ div_btn_->setShortcut(QKeySequence(QStringLiteral("Ctrl+D")));
+ div_btn_->setToolTip(tr("Record a dividend payment (Ctrl+D)"));
+ div_btn_->setAccessibleName(tr("Record a dividend payment"));
}
void PortfolioCommandBar::build_detail_tabs(QHBoxLayout* layout) {
@@ -346,6 +360,11 @@ void PortfolioCommandBar::build_tools_cluster(QHBoxLayout* layout) {
// colour discipline — only AMBER/CYAN/POSITIVE/NEGATIVE/WARNING are allowed.
make_tool_btn(ai_btn_, tr("AI"), ui::colors::AMBER(), &PortfolioCommandBar::ai_analyze_requested);
make_tool_btn(agent_btn_, tr("AGENT"), ui::colors::CYAN(), &PortfolioCommandBar::agent_run_requested);
+
+ ai_btn_->setToolTip(tr("Open AI analysis of this portfolio"));
+ ai_btn_->setAccessibleName(ai_btn_->toolTip());
+ agent_btn_->setToolTip(tr("Run a configured research agent against this portfolio"));
+ agent_btn_->setAccessibleName(agent_btn_->toolTip());
}
// ── Styling ──────────────────────────────────────────────────────────────────
@@ -417,13 +436,18 @@ void PortfolioCommandBar::apply_row2_styles() {
// ── Dropdown ─────────────────────────────────────────────────────────────────
void PortfolioCommandBar::toggle_dropdown() {
- dropdown_visible_ = !dropdown_visible_;
+ // Track the popup's *actual* visibility rather than a local flag. The
+ // dropdown is a Qt::Popup: clicking outside it closes it and swallows the
+ // click, so the flag stayed true and the next click on the selector merely
+ // flipped it back to false — the user had to click twice to reopen.
+ const bool currently_visible = dropdown_->isVisible();
+ dropdown_visible_ = !currently_visible;
if (dropdown_visible_) {
QPoint pos = selector_btn_->mapToGlobal(QPoint(0, selector_btn_->height()));
dropdown_->move(pos);
dropdown_->show();
+ search_edit_->clear(); // resets the row filter from the previous open
search_edit_->setFocus();
- search_edit_->clear();
} else {
dropdown_->hide();
}
@@ -436,7 +460,7 @@ void PortfolioCommandBar::update_selector_label() {
return;
}
}
- selector_btn_->setText(tr("SELECT PORTFOLIO \u25BE"));
+ selector_btn_->setText(tr("SELECT PORTFOLIO \u25BE"));
}
// ── Public setters ───────────────────────────────────────────────────────────
@@ -484,7 +508,7 @@ void PortfolioCommandBar::set_has_portfolios(bool has) {
tabs_container_->setVisible(false);
tools_cluster_->setVisible(false);
if (!has) {
- selector_btn_->setText(tr("NO PORTFOLIOS \u2014 CREATE ONE \u25BE"));
+ selector_btn_->setText(tr("NO PORTFOLIOS \u2014 CREATE ONE \u25BE"));
}
}
@@ -506,12 +530,15 @@ void PortfolioCommandBar::changeEvent(QEvent* event) {
void PortfolioCommandBar::retranslateUi() {
// Row 1 — selector label depends on portfolio state.
+ // NOTE: the source strings must match build_portfolio_selector() /
+ // update_selector_label() byte-for-byte, otherwise lupdate emits a second
+ // near-duplicate entry and one of the two is left untranslated.
if (has_portfolios_ && !selected_id_.isEmpty()) {
update_selector_label(); // re-emits "%1 (%2) ▾" with the current portfolio
} else if (has_portfolios_) {
- selector_btn_->setText(tr("SELECT PORTFOLIO ▾"));
+ selector_btn_->setText(tr("SELECT PORTFOLIO ▾"));
} else if (selector_btn_) {
- selector_btn_->setText(tr("NO PORTFOLIOS — CREATE ONE ▾"));
+ selector_btn_->setText(tr("NO PORTFOLIOS — CREATE ONE ▾"));
}
if (search_edit_)
@@ -520,8 +547,10 @@ void PortfolioCommandBar::retranslateUi() {
create_btn_->setText(tr("+ CREATE NEW"));
if (delete_btn_)
delete_btn_->setText(tr("DELETE"));
- if (refresh_btn_)
- refresh_btn_->setToolTip(tr("Refresh portfolio data"));
+ if (refresh_btn_) {
+ refresh_btn_->setToolTip(tr("Refresh portfolio data (F5)"));
+ refresh_btn_->setAccessibleName(tr("Refresh portfolio data"));
+ }
if (interval_cb_)
interval_cb_->setToolTip(tr("Auto-refresh interval"));
if (overflow_btn_)
@@ -535,18 +564,35 @@ void PortfolioCommandBar::retranslateUi() {
import_action_->setText(tr("Import JSON…"));
if (ffn_action_)
ffn_action_->setText(tr("FFN Analysis"));
+ if (backtest_action_) // was omitted — stayed English after a language switch
+ backtest_action_->setText(tr("Backtest Portfolio"));
// Row 2 trade cluster
- if (buy_btn_)
+ if (buy_btn_) {
buy_btn_->setText(tr("BUY"));
- if (sell_btn_)
+ buy_btn_->setToolTip(tr("Buy / add to a position (Ctrl+B)"));
+ buy_btn_->setAccessibleName(tr("Buy or add to a position"));
+ }
+ if (sell_btn_) {
sell_btn_->setText(tr("SELL"));
- if (div_btn_)
+ sell_btn_->setToolTip(tr("Sell / trim a position (Ctrl+S)"));
+ sell_btn_->setAccessibleName(tr("Sell or trim a position"));
+ }
+ if (div_btn_) {
div_btn_->setText(tr("DIV"));
- if (ai_btn_)
+ div_btn_->setToolTip(tr("Record a dividend payment (Ctrl+D)"));
+ div_btn_->setAccessibleName(tr("Record a dividend payment"));
+ }
+ if (ai_btn_) {
ai_btn_->setText(tr("AI"));
- if (agent_btn_)
+ ai_btn_->setToolTip(tr("Open AI analysis of this portfolio"));
+ ai_btn_->setAccessibleName(ai_btn_->toolTip());
+ }
+ if (agent_btn_) {
agent_btn_->setText(tr("AGENT"));
+ agent_btn_->setToolTip(tr("Run a configured research agent against this portfolio"));
+ agent_btn_->setAccessibleName(agent_btn_->toolTip());
+ }
// Row 2 detail tabs — populated in kDetailButtons order, so iterate by index.
constexpr int kDetailCount = static_cast<int>(sizeof(kDetailButtons) / sizeof(kDetailButtons[0]));
diff --git a/fincept-qt/src/screens/portfolio/PortfolioDetailWrapper.cpp b/fincept-qt/src/screens/portfolio/PortfolioDetailWrapper.cpp
index bad3d2bc9..4074b7e6b 100644
--- a/fincept-qt/src/screens/portfolio/PortfolioDetailWrapper.cpp
+++ b/fincept-qt/src/screens/portfolio/PortfolioDetailWrapper.cpp
@@ -14,6 +14,7 @@
#include <QEvent>
#include <QHBoxLayout>
+#include <QKeySequence>
#include <QVBoxLayout>
namespace fincept::screens {
@@ -30,9 +31,10 @@ void PortfolioDetailWrapper::build_ui() {
// ── Header bar (36px) ────────────────────────────────────────────────────
auto* header = new QWidget(this);
header->setFixedHeight(36);
- header->setStyleSheet(QString("background: qlineargradient(x1:0,x2:1, stop:0 %1, stop:1 %2);"
- "border-bottom:1px solid %3;")
- .arg(ui::colors::BG_RAISED(), ui::colors::BG_SURFACE(), ui::colors::AMBER()));
+ // Flat fill — DESIGN_SYSTEM §9 forbids gradients ("depth comes from
+ // background layering only").
+ header->setStyleSheet(QString("background:%1; border-bottom:1px solid %2;")
+ .arg(ui::colors::BG_RAISED(), ui::colors::AMBER()));
auto* h_layout = new QHBoxLayout(header);
h_layout->setContentsMargins(8, 0, 8, 0);
@@ -46,6 +48,11 @@ void PortfolioDetailWrapper::build_ui() {
" padding:0 10px; font-size:9px; font-weight:700; letter-spacing:0.5px; }"
"QPushButton:hover { background:%1; color:#000; }")
.arg(ui::colors::AMBER()));
+ // Esc leaves the detail view. Owned by the button, so it is inert while
+ // this page is not the visible one in PortfolioScreen's stack.
+ back_btn_->setShortcut(QKeySequence(Qt::Key_Escape));
+ back_btn_->setToolTip(tr("Back to the portfolio workspace (Esc)"));
+ back_btn_->setAccessibleName(tr("Back to the portfolio workspace"));
connect(back_btn_, &QPushButton::clicked, this, &PortfolioDetailWrapper::back_requested);
h_layout->addWidget(back_btn_);
@@ -237,8 +244,11 @@ void PortfolioDetailWrapper::changeEvent(QEvent* event) {
}
void PortfolioDetailWrapper::retranslateUi() {
- if (back_btn_)
+ if (back_btn_) {
back_btn_->setText(tr("← BACK"));
+ back_btn_->setToolTip(tr("Back to the portfolio workspace (Esc)"));
+ back_btn_->setAccessibleName(tr("Back to the portfolio workspace"));
+ }
if (title_label_)
title_label_->setText(view_title(current_view_));
// portfolio_label_ holds "NAME | CURRENCY" — pure portfolio data, no
diff --git a/fincept-qt/src/screens/portfolio/PortfolioDetailWrapper.h b/fincept-qt/src/screens/portfolio/PortfolioDetailWrapper.h
index 075d694d8..3bb834084 100644
--- a/fincept-qt/src/screens/portfolio/PortfolioDetailWrapper.h
+++ b/fincept-qt/src/screens/portfolio/PortfolioDetailWrapper.h
@@ -7,8 +7,6 @@
#include <QStackedWidget>
#include <QWidget>
-#include <functional>
-
namespace fincept::screens {
/// Container for full-screen detail views with a 36px header bar (back button + title).
diff --git a/fincept-qt/src/screens/portfolio/PortfolioDialogs.cpp b/fincept-qt/src/screens/portfolio/PortfolioDialogs.cpp
index 69d2a3333..c317b0bec 100644
--- a/fincept-qt/src/screens/portfolio/PortfolioDialogs.cpp
+++ b/fincept-qt/src/screens/portfolio/PortfolioDialogs.cpp
@@ -19,6 +19,7 @@
#include <QKeyEvent>
#include <QLabel>
#include <QListWidgetItem>
+#include <QLocale>
#include <QMessageBox>
#include <QPointer>
#include <QPushButton>
@@ -107,13 +108,32 @@ CreatePortfolioDialog::CreatePortfolioDialog(QWidget* parent) : QDialog(parent)
"QPushButton:hover { background:%2; }")
.arg(ui::colors::AMBER(), ui::colors::WARNING(), ui::colors::BG_BASE()));
connect(create_btn_, &QPushButton::clicked, this, [this]() {
- if (!name_edit_->text().trimmed().isEmpty())
- accept();
+ // Was a silent no-op on an empty name — the button simply did nothing
+ // and the user had no idea why.
+ if (name_edit_->text().trimmed().isEmpty()) {
+ name_edit_->setPlaceholderText(tr("A portfolio name is required"));
+ name_edit_->setStyleSheet(QString("border:1px solid %1;").arg(ui::colors::NEGATIVE()));
+ name_edit_->setFocus();
+ return;
+ }
+ accept();
});
btn_layout->addWidget(create_btn_);
layout->addLayout(btn_layout);
+ // Explicit tab order — the default order follows construction, which puts
+ // the buttons before the combo here.
+ setTabOrder(name_edit_, owner_edit_);
+ setTabOrder(owner_edit_, currency_cb_);
+ setTabOrder(currency_cb_, create_btn_);
+ setTabOrder(create_btn_, cancel_btn_);
+
+ name_edit_->setAccessibleName(tr("Portfolio name"));
+ owner_edit_->setAccessibleName(tr("Portfolio owner"));
+ currency_cb_->setAccessibleName(tr("Reporting currency"));
+
+ create_btn_->setDefault(true); // Enter creates
name_edit_->setFocus();
}
@@ -204,6 +224,12 @@ ConfirmDeleteDialog::ConfirmDeleteDialog(const QString& portfolio_name, QWidget*
btn_layout->addWidget(delete_btn_);
layout->addLayout(btn_layout);
+
+ // CANCEL is the default on a destructive dialog: Enter must not delete.
+ setTabOrder(cancel_btn_, delete_btn_);
+ cancel_btn_->setDefault(true);
+ cancel_btn_->setFocus();
+ delete_btn_->setAccessibleName(tr("Confirm deletion"));
}
void ConfirmDeleteDialog::changeEvent(QEvent* event) {
@@ -300,8 +326,27 @@ AddAssetDialog::AddAssetDialog(QWidget* parent) : QDialog(parent) {
"QPushButton:hover { background:%1; }")
.arg(ui::colors::POSITIVE(), ui::colors::BG_BASE()));
connect(add_btn_, &QPushButton::clicked, this, [this]() {
- if (!symbol_edit_->text().trimmed().isEmpty() && quantity() > 0 && price() > 0)
- accept();
+ // Point at the offending field instead of doing nothing.
+ const QString err_style = QString("border:1px solid %1;").arg(ui::colors::NEGATIVE());
+ if (symbol_edit_->text().trimmed().isEmpty()) {
+ symbol_edit_->setStyleSheet(err_style);
+ symbol_edit_->setPlaceholderText(tr("A ticker is required"));
+ symbol_edit_->setFocus();
+ return;
+ }
+ if (quantity() <= 0) {
+ quantity_edit_->setStyleSheet(err_style);
+ quantity_edit_->setPlaceholderText(tr("Quantity must be greater than 0"));
+ quantity_edit_->setFocus();
+ return;
+ }
+ if (price() <= 0) {
+ price_edit_->setStyleSheet(err_style);
+ price_edit_->setPlaceholderText(tr("Price must be greater than 0"));
+ price_edit_->setFocus();
+ return;
+ }
+ accept();
});
btn_layout->addWidget(add_btn_);
@@ -334,7 +379,7 @@ AddAssetDialog::AddAssetDialog(QWidget* parent) : QDialog(parent) {
"QListWidget::item { padding:0; border:none; background:transparent; }"
"QListWidget::item:selected { background:%2; border-left:3px solid %3; }"
"QScrollBar:vertical { background:%1; width:6px; margin:0; }"
- "QScrollBar::handle:vertical { background:%2; border-radius:3px; min-height:15px; }"
+ "QScrollBar::handle:vertical { background:%2; min-height:15px; }"
"QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical { height:0; }")
.arg(ui::colors::BG_SURFACE(), ui::colors::BORDER_DIM(), ui::colors::AMBER()));
search_list_->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
@@ -354,9 +399,20 @@ AddAssetDialog::AddAssetDialog(QWidget* parent) : QDialog(parent) {
fire_search(pending_query_);
});
+ setTabOrder(symbol_edit_, quantity_edit_);
+ setTabOrder(quantity_edit_, price_edit_);
+ setTabOrder(price_edit_, add_btn_);
+ setTabOrder(add_btn_, cancel_btn_);
+ symbol_edit_->setAccessibleName(tr("Ticker symbol"));
+ quantity_edit_->setAccessibleName(tr("Quantity to buy"));
+ price_edit_->setAccessibleName(tr("Purchase price per share"));
+ add_btn_->setDefault(true);
+
connect(symbol_edit_, &QLineEdit::textChanged, this, [this](const QString& text) {
if (selecting_)
return;
+ // Clear any validation highlight as soon as the user edits the field.
+ symbol_edit_->setStyleSheet(QString());
const QString q = text.trimmed();
if (q.length() < 2) {
search_debounce_->stop();
@@ -470,7 +526,7 @@ void AddAssetDialog::show_results(const QList<fincept::services::MarketSearchSer
auto* type_lbl = new QLabel(type.toUpper());
type_lbl->setStyleSheet(QString("color:%1; font-size:9px; font-weight:700;"
"font-family:'Consolas',monospace; background:%2;"
- "padding:1px 4px; border-radius:2px;")
+ "padding:1px 4px;")
.arg(ui::colors::AMBER(), ui::colors::BORDER_DIM()));
hl->addWidget(type_lbl);
@@ -486,6 +542,22 @@ void AddAssetDialog::show_results(const QList<fincept::services::MarketSearchSer
search_frame_->raise();
}
+void AddAssetDialog::preset(const QString& symbol, double price) {
+ if (symbol.isEmpty())
+ return;
+ // selecting_ suppresses the textChanged handler so setting the field does
+ // not immediately fire a search for a ticker we already resolved.
+ selecting_ = true;
+ symbol_edit_->setText(symbol);
+ selecting_ = false;
+ search_debounce_->stop();
+ search_frame_->hide();
+ if (price > 0.0)
+ price_edit_->setText(QString::number(price, 'f', 2));
+ quantity_edit_->setFocus();
+ quantity_edit_->selectAll();
+}
+
void AddAssetDialog::select_result(const QString& sym) {
selecting_ = true;
symbol_edit_->setText(sym);
@@ -605,7 +677,7 @@ SellAssetDialog::SellAssetDialog(const QString& symbol, double held_qty, QWidget
QString("color:%1; font-size:13px; font-weight:700; letter-spacing:1px;").arg(ui::colors::NEGATIVE()));
layout->addWidget(title_label_);
- held_label_ = new QLabel(tr("Currently holding: %1 shares").arg(held_qty_));
+ held_label_ = new QLabel(tr("Currently holding: %1 shares").arg(QLocale().toString(held_qty_, 'f', 2)));
held_label_->setStyleSheet(QString("color:%1; font-size:10px;").arg(ui::colors::TEXT_TERTIARY()));
layout->addWidget(held_label_);
@@ -613,7 +685,7 @@ SellAssetDialog::SellAssetDialog(const QString& symbol, double held_qty, QWidget
form->setSpacing(8);
quantity_edit_ = new QLineEdit;
- quantity_edit_->setPlaceholderText(tr("Max %1").arg(held_qty_));
+ quantity_edit_->setPlaceholderText(tr("Max %1").arg(QLocale().toString(held_qty_, 'f', 2)));
quantity_row_label_ = new QLabel(tr("Quantity:"));
form->addRow(quantity_row_label_, quantity_edit_);
@@ -647,12 +719,46 @@ SellAssetDialog::SellAssetDialog(const QString& symbol, double held_qty, QWidget
"QPushButton:hover { background:%1; }")
.arg(ui::colors::NEGATIVE(), ui::colors::TEXT_PRIMARY()));
connect(sell_btn_, &QPushButton::clicked, this, [this]() {
- if (quantity() > 0 && quantity() <= held_qty_ && price() > 0)
- accept();
+ // Silent no-op previously — in particular, over-selling looked like a
+ // dead button rather than a rejected input.
+ const QString err_style = QString("border:1px solid %1;").arg(ui::colors::NEGATIVE());
+ if (quantity() <= 0) {
+ quantity_edit_->setStyleSheet(err_style);
+ quantity_edit_->setPlaceholderText(tr("Quantity must be greater than 0"));
+ quantity_edit_->setFocus();
+ return;
+ }
+ if (quantity() > held_qty_) {
+ quantity_edit_->setStyleSheet(err_style);
+ quantity_edit_->clear();
+ quantity_edit_->setPlaceholderText(tr("You only hold %1").arg(QLocale().toString(held_qty_, 'f', 2)));
+ quantity_edit_->setFocus();
+ return;
+ }
+ if (price() <= 0) {
+ price_edit_->setStyleSheet(err_style);
+ price_edit_->setPlaceholderText(tr("Price must be greater than 0"));
+ price_edit_->setFocus();
+ return;
+ }
+ accept();
});
btn_layout->addWidget(sell_btn_);
layout->addLayout(btn_layout);
+
+ setTabOrder(quantity_edit_, price_edit_);
+ setTabOrder(price_edit_, sell_btn_);
+ setTabOrder(sell_btn_, cancel_btn_);
+ quantity_edit_->setAccessibleName(tr("Quantity to sell"));
+ price_edit_->setAccessibleName(tr("Sale price per share"));
+ sell_btn_->setDefault(true);
+
+ connect(quantity_edit_, &QLineEdit::textEdited, this,
+ [this](const QString&) { quantity_edit_->setStyleSheet(QString()); });
+ connect(price_edit_, &QLineEdit::textEdited, this,
+ [this](const QString&) { price_edit_->setStyleSheet(QString()); });
+
quantity_edit_->setFocus();
}
@@ -667,13 +773,13 @@ void SellAssetDialog::retranslateUi() {
if (title_label_)
title_label_->setText(tr("SELL %1").arg(symbol_));
if (held_label_)
- held_label_->setText(tr("Currently holding: %1 shares").arg(held_qty_));
+ held_label_->setText(tr("Currently holding: %1 shares").arg(QLocale().toString(held_qty_, 'f', 2)));
if (quantity_row_label_)
quantity_row_label_->setText(tr("Quantity:"));
if (price_row_label_)
price_row_label_->setText(tr("Price:"));
if (quantity_edit_)
- quantity_edit_->setPlaceholderText(tr("Max %1").arg(held_qty_));
+ quantity_edit_->setPlaceholderText(tr("Max %1").arg(QLocale().toString(held_qty_, 'f', 2)));
if (price_edit_)
price_edit_->setPlaceholderText(tr("Sell price"));
if (cancel_btn_)
@@ -857,12 +963,31 @@ ImportPortfolioDialog::ImportPortfolioDialog(const QVector<portfolio::Portfolio>
"QPushButton:hover { background:%1; }")
.arg(ui::colors::CYAN(), ui::colors::BG_BASE()));
connect(import_btn_, &QPushButton::clicked, this, [this]() {
- if (!file_edit_->text().isEmpty())
- accept();
+ if (file_edit_->text().isEmpty()) {
+ status_label_->setText(tr("Choose a JSON file first — press BROWSE."));
+ status_label_->setStyleSheet(QString("color:%1; font-size:9px;").arg(ui::colors::NEGATIVE()));
+ return;
+ }
+ if (merge_radio_->isChecked() && target_cb_->count() == 0) {
+ status_label_->setText(tr("No existing portfolio to merge into. Choose 'Create new' instead."));
+ status_label_->setStyleSheet(QString("color:%1; font-size:9px;").arg(ui::colors::NEGATIVE()));
+ return;
+ }
+ accept();
});
btn_layout->addWidget(import_btn_);
layout->addLayout(btn_layout);
+
+ setTabOrder(browse_btn_, demo_dl_btn_);
+ setTabOrder(demo_dl_btn_, new_radio_);
+ setTabOrder(new_radio_, merge_radio_);
+ setTabOrder(merge_radio_, target_cb_);
+ setTabOrder(target_cb_, import_btn_);
+ setTabOrder(import_btn_, cancel_btn_);
+ browse_btn_->setAccessibleName(tr("Choose a portfolio JSON file"));
+ target_cb_->setAccessibleName(tr("Portfolio to merge into"));
+ import_btn_->setDefault(true);
}
void ImportPortfolioDialog::changeEvent(QEvent* event) {
@@ -997,12 +1122,37 @@ EditTransactionDialog::EditTransactionDialog(const portfolio::Transaction& txn,
"QPushButton:hover { background:%2; }")
.arg(ui::colors::AMBER(), ui::colors::WARNING(), ui::colors::BG_BASE()));
connect(save_btn_, &QPushButton::clicked, this, [this]() {
- if (quantity() > 0 && price() > 0)
- accept();
+ const QString err_style = QString("border:1px solid %1;").arg(ui::colors::NEGATIVE());
+ if (quantity() <= 0) {
+ quantity_edit_->setStyleSheet(err_style);
+ quantity_edit_->setFocus();
+ return;
+ }
+ if (price() <= 0) {
+ price_edit_->setStyleSheet(err_style);
+ price_edit_->setFocus();
+ return;
+ }
+ accept();
});
+ connect(quantity_edit_, &QLineEdit::textEdited, this,
+ [this](const QString&) { quantity_edit_->setStyleSheet(QString()); });
+ connect(price_edit_, &QLineEdit::textEdited, this,
+ [this](const QString&) { price_edit_->setStyleSheet(QString()); });
btn_layout->addWidget(save_btn_);
layout->addLayout(btn_layout);
+
+ setTabOrder(quantity_edit_, price_edit_);
+ setTabOrder(price_edit_, date_edit_);
+ setTabOrder(date_edit_, notes_edit_);
+ setTabOrder(notes_edit_, save_btn_);
+ setTabOrder(save_btn_, cancel_btn_);
+ quantity_edit_->setAccessibleName(tr("Transaction quantity"));
+ price_edit_->setAccessibleName(tr("Transaction price"));
+ date_edit_->setAccessibleName(tr("Transaction date"));
+ save_btn_->setDefault(true);
+
quantity_edit_->setFocus();
}
@@ -1094,8 +1244,14 @@ SectorMappingDialog::SectorMappingDialog(const QVector<portfolio::HoldingWithQuo
for (const auto& h : holdings) {
auto* cb = new QComboBox;
cb->addItems(kSectors);
- // Try to pre-select based on simple heuristic
- cb->setCurrentText("Other");
+ // Pre-select the sector we already know for this holding (from the
+ // import payload or SectorResolver). The comment here used to promise
+ // a "simple heuristic" while the code unconditionally reset every row
+ // to "Other", so opening the dialog and pressing SAVE would have wiped
+ // the existing classification of every position.
+ const int known = h.sector.isEmpty() ? -1 : cb->findText(h.sector, Qt::MatchFixedString);
+ cb->setCurrentIndex(known >= 0 ? known : cb->findText(QStringLiteral("Other")));
+ cb->setAccessibleName(tr("Sector for %1").arg(h.symbol));
combos_[h.symbol] = cb;
auto* sym_label = new QLabel(h.symbol);
@@ -1238,15 +1394,33 @@ AddDividendDialog::AddDividendDialog(const QStringList& symbols, QWidget* parent
"QPushButton:hover { background:%2; }")
.arg(ui::colors::CYAN(), ui::colors::TEXT_PRIMARY(), ui::colors::BG_BASE()));
connect(record_btn_, &QPushButton::clicked, this, [this]() {
- if (amount_edit_->text().trimmed().isEmpty()) {
- amount_edit_->setPlaceholderText(tr("Required!"));
+ // Also reject 0 / non-numeric input — "abc" parsed to 0.0 and recorded
+ // a zero-value dividend transaction.
+ if (amount_per_share() <= 0.0) {
+ amount_edit_->clear();
+ amount_edit_->setPlaceholderText(tr("Enter an amount greater than 0"));
+ amount_edit_->setStyleSheet(QString("border:1px solid %1;").arg(ui::colors::NEGATIVE()));
+ amount_edit_->setFocus();
return;
}
accept();
});
+ connect(amount_edit_, &QLineEdit::textEdited, this,
+ [this](const QString&) { amount_edit_->setStyleSheet(QString()); });
btn_row->addWidget(record_btn_);
layout->addLayout(btn_row);
+
+ setTabOrder(symbol_cb_, amount_edit_);
+ setTabOrder(amount_edit_, date_edit_);
+ setTabOrder(date_edit_, notes_edit_);
+ setTabOrder(notes_edit_, record_btn_);
+ setTabOrder(record_btn_, cancel_btn_);
+ symbol_cb_->setAccessibleName(tr("Holding that paid the dividend"));
+ amount_edit_->setAccessibleName(tr("Dividend amount per share"));
+ date_edit_->setAccessibleName(tr("Ex-dividend date"));
+ record_btn_->setDefault(true);
+ amount_edit_->setFocus();
}
void AddDividendDialog::changeEvent(QEvent* event) {
diff --git a/fincept-qt/src/screens/portfolio/PortfolioDialogs.h b/fincept-qt/src/screens/portfolio/PortfolioDialogs.h
index b99873e92..6dd4ab64a 100644
--- a/fincept-qt/src/screens/portfolio/PortfolioDialogs.h
+++ b/fincept-qt/src/screens/portfolio/PortfolioDialogs.h
@@ -78,6 +78,12 @@ class AddAssetDialog : public QDialog {
double quantity() const;
double price() const;
+ /// Pre-fill the ticker (and optionally the last price) and jump focus to
+ /// the quantity field. Used when BUY is invoked with a position already
+ /// selected — the user should not have to retype a symbol the terminal
+ /// already knows.
+ void preset(const QString& symbol, double price = 0.0);
+
protected:
bool eventFilter(QObject* obj, QEvent* event) override;
void changeEvent(QEvent* event) override;
diff --git a/fincept-qt/src/screens/portfolio/PortfolioFFNView.cpp b/fincept-qt/src/screens/portfolio/PortfolioFFNView.cpp
index 5c6979f92..87748cf9b 100644
--- a/fincept-qt/src/screens/portfolio/PortfolioFFNView.cpp
+++ b/fincept-qt/src/screens/portfolio/PortfolioFFNView.cpp
@@ -13,6 +13,7 @@
#include <QHBoxLayout>
#include <QHeaderView>
#include <QJsonObject>
+#include <QKeySequence>
#include <QLineSeries>
#include <QStackedWidget>
#include <QTabBar>
@@ -139,6 +140,12 @@ void PortfolioFFNView::build_ui() {
" padding:0 10px; font-size:9px; font-weight:700; }"
"QPushButton:hover { background:%1; color:%2; }")
.arg(ui::colors::AMBER(), ui::colors::BG_BASE()));
+ // Esc is the expected "leave this full-screen view" key. The shortcut is
+ // owned by the button, so it is inert while this page is not the visible
+ // one in PortfolioScreen's stack.
+ back_btn_->setShortcut(QKeySequence(Qt::Key_Escape));
+ back_btn_->setToolTip(tr("Back to the portfolio workspace (Esc)"));
+ back_btn_->setAccessibleName(tr("Back to the portfolio workspace"));
connect(back_btn_, &QPushButton::clicked, this, &PortfolioFFNView::back_requested);
h_layout->addWidget(back_btn_);
@@ -684,15 +691,18 @@ void PortfolioFFNView::update_optimization() {
auto s = stats_obj[key].toObject();
opt_stats_table_->setRowHeight(r, 28);
- double tr = s["total_return"].toDouble();
+ // Named `total_ret`, not `tr` — a local called `tr` shadows QObject::tr()
+ // for the rest of the scope, so any future tr("…") added here would fail
+ // to compile with a baffling error.
+ double total_ret = s["total_return"].toDouble();
double vol = s["volatility"].toDouble();
double sh = s["sharpe"].toDouble();
double dd = s["max_drawdown"].toDouble();
opt_stats_table_->setItem(r, 0, make_item(name, Qt::AlignLeft | Qt::AlignVCenter, QColor(ui::colors::AMBER())));
opt_stats_table_->setItem(r, 1,
- make_item(pct_str(tr), Qt::AlignRight | Qt::AlignVCenter,
- QColor(tr >= 0 ? ui::colors::POSITIVE() : ui::colors::NEGATIVE())));
+ make_item(pct_str(total_ret), Qt::AlignRight | Qt::AlignVCenter,
+ QColor(total_ret >= 0 ? ui::colors::POSITIVE() : ui::colors::NEGATIVE())));
opt_stats_table_->setItem(
r, 2, make_item(pct_str(vol), Qt::AlignRight | Qt::AlignVCenter, QColor(ui::colors::CYAN())));
opt_stats_table_->setItem(r, 3,
@@ -718,19 +728,23 @@ void PortfolioFFNView::update_rebased() {
chart->removeAllSeries();
// Remove old axes
const auto old_axes = chart->axes();
- for (auto* ax : old_axes)
+ for (auto* ax : old_axes) {
+ // removeAxis() only detaches — the axis stays heap-allocated and
+ // leaked one QDateTimeAxis + one QValueAxis per re-run.
chart->removeAxis(ax);
+ delete ax;
+ }
auto* x_axis = new QDateTimeAxis;
x_axis->setFormat("MMM yy");
- x_axis->setTitleText("Date");
+ x_axis->setTitleText(tr("Date"));
x_axis->setLabelsColor(QColor(ui::colors::TEXT_SECONDARY()));
x_axis->setTitleBrush(QBrush(QColor(ui::colors::TEXT_TERTIARY())));
x_axis->setGridLineColor(QColor(ui::colors::BORDER_DIM()));
x_axis->setLinePenColor(QColor(ui::colors::BORDER_MED()));
auto* y_axis = new QValueAxis;
- y_axis->setTitleText("Value (Base = 100)");
+ y_axis->setTitleText(tr("Value (Base = 100)"));
y_axis->setLabelsColor(QColor(ui::colors::TEXT_SECONDARY()));
y_axis->setTitleBrush(QBrush(QColor(ui::colors::TEXT_TERTIARY())));
y_axis->setGridLineColor(QColor(ui::colors::BORDER_DIM()));
@@ -801,8 +815,12 @@ void PortfolioFFNView::update_drawdowns() {
QChart* chart = drawdowns_chart_view_->chart();
chart->removeAllSeries();
const auto old_axes = chart->axes();
- for (auto* ax : old_axes)
+ for (auto* ax : old_axes) {
+ // removeAxis() only detaches — the axis stays heap-allocated and
+ // leaked one QDateTimeAxis + one QValueAxis per re-run.
chart->removeAxis(ax);
+ delete ax;
+ }
auto* x_axis = new QDateTimeAxis;
x_axis->setFormat("MMM yy");
@@ -812,15 +830,12 @@ void PortfolioFFNView::update_drawdowns() {
x_axis->setLinePenColor(QColor(ui::colors::BORDER_MED()));
auto* y_axis = new QValueAxis;
- y_axis->setTitleText("Drawdown");
+ y_axis->setTitleText(tr("Drawdown %"));
y_axis->setLabelsColor(QColor(ui::colors::TEXT_SECONDARY()));
y_axis->setTitleBrush(QBrush(QColor(ui::colors::TEXT_TERTIARY())));
y_axis->setGridLineColor(QColor(ui::colors::BORDER_DIM()));
y_axis->setLinePenColor(QColor(ui::colors::BORDER_MED()));
- auto* label_format_axis = y_axis;
- Q_UNUSED(label_format_axis);
-
chart->addAxis(x_axis, Qt::AlignBottom);
chart->addAxis(y_axis, Qt::AlignLeft);
@@ -893,8 +908,12 @@ void PortfolioFFNView::update_rolling() {
QChart* chart = rolling_chart_view_->chart();
chart->removeAllSeries();
const auto old_axes = chart->axes();
- for (auto* ax : old_axes)
+ for (auto* ax : old_axes) {
+ // removeAxis() only detaches — the axis stays heap-allocated and
+ // leaked one QDateTimeAxis + one QValueAxis per re-run.
chart->removeAxis(ax);
+ delete ax;
+ }
auto* x_axis = new QDateTimeAxis;
x_axis->setFormat("MMM yy");
@@ -904,7 +923,7 @@ void PortfolioFFNView::update_rolling() {
x_axis->setLinePenColor(QColor(ui::colors::BORDER_MED()));
auto* y_axis = new QValueAxis;
- y_axis->setTitleText("Correlation");
+ y_axis->setTitleText(tr("Correlation"));
y_axis->setRange(-1.0, 1.0);
y_axis->setLabelsColor(QColor(ui::colors::TEXT_SECONDARY()));
y_axis->setTitleBrush(QBrush(QColor(ui::colors::TEXT_TERTIARY())));
@@ -1026,8 +1045,11 @@ void PortfolioFFNView::changeEvent(QEvent* event) {
}
void PortfolioFFNView::retranslateUi() {
- if (back_btn_)
+ if (back_btn_) {
back_btn_->setText(tr("← BACK"));
+ back_btn_->setToolTip(tr("Back to the portfolio workspace (Esc)"));
+ back_btn_->setAccessibleName(tr("Back to the portfolio workspace"));
+ }
if (title_label_)
title_label_->setText(tr("FFN ANALYTICS"));
if (run_btn_)
diff --git a/fincept-qt/src/screens/portfolio/PortfolioHeatmap.cpp b/fincept-qt/src/screens/portfolio/PortfolioHeatmap.cpp
index 462896018..4243e3a25 100644
--- a/fincept-qt/src/screens/portfolio/PortfolioHeatmap.cpp
+++ b/fincept-qt/src/screens/portfolio/PortfolioHeatmap.cpp
@@ -57,6 +57,14 @@ void PortfolioHeatmap::build_ui() {
day_btn_ = make_mode_btn(tr("DAY"));
pnl_btn_->setChecked(true);
+ // Two-letter labels are meaningless to a screen reader / new user.
+ pnl_btn_->setAccessibleName(tr("Colour blocks by unrealized profit and loss"));
+ pnl_btn_->setToolTip(pnl_btn_->accessibleName());
+ weight_btn_->setAccessibleName(tr("Colour blocks by portfolio weight"));
+ weight_btn_->setToolTip(weight_btn_->accessibleName());
+ day_btn_->setAccessibleName(tr("Colour blocks by today's change"));
+ day_btn_->setToolTip(day_btn_->accessibleName());
+
auto set_mode = [this](portfolio::HeatmapMode m) {
mode_ = m;
pnl_btn_->setChecked(m == portfolio::HeatmapMode::Pnl);
@@ -143,7 +151,12 @@ void PortfolioHeatmap::set_selected_symbol(const QString& symbol) {
}
void PortfolioHeatmap::set_currency(const QString& currency) {
+ if (currency_ == currency)
+ return;
currency_ = currency;
+ // Block tooltips carry the currency — refresh them when the selected
+ // portfolio switches to a different denomination.
+ rebuild_blocks();
}
QColor PortfolioHeatmap::block_color(const portfolio::HoldingWithQuote& h) const {
@@ -184,69 +197,100 @@ QColor PortfolioHeatmap::block_color(const portfolio::HoldingWithQuote& h) const
}
void PortfolioHeatmap::rebuild_blocks() {
- // Clear existing blocks — delete children first, then layout
- if (auto* old_layout = blocks_container_->layout()) {
- QLayoutItem* item;
- while ((item = old_layout->takeAt(0)) != nullptr) {
- if (item->widget())
- item->widget()->deleteLater();
- delete item;
- }
- delete old_layout;
+ // Blocks are pooled: a refresh reuses the existing buttons and only touches
+ // the ones whose rendered state actually changed. Each setStyleSheet is a
+ // full CSS reparse + repolish, and this function runs on every 60 s poll,
+ // every selection change and every mode toggle — allocating and restyling
+ // one button per holding each time was the hot spot in this panel.
+ if (!blocks_container_)
+ return; // retranslate/theme events can arrive before build_ui() ran
+ if (!blocks_grid_) {
+ blocks_grid_ = new QGridLayout(blocks_container_);
+ blocks_grid_->setContentsMargins(0, 0, 0, 0);
+ blocks_grid_->setSpacing(2);
}
- auto* grid = new QGridLayout(blocks_container_);
- grid->setContentsMargins(0, 0, 0, 0);
- grid->setSpacing(2);
+ const int n = static_cast<int>(holdings_.size());
+
+ for (int i = 0; i < n; ++i) {
+ const auto& h = holdings_[i];
+ const bool selected = (h.symbol == selected_symbol_);
+
+ QPushButton* block = nullptr;
+ if (i < blocks_.size()) {
+ block = blocks_[i];
+ } else {
+ block = new QPushButton(blocks_container_);
+ block->setCursor(Qt::PointingHandCursor);
+ // The symbol lives on the widget so the (single) connection stays
+ // valid when the block is recycled for a different holding.
+ connect(block, &QPushButton::clicked, this, [this, block]() {
+ const QString sym = block->property("symbol").toString();
+ if (sym.isEmpty())
+ return;
+ selected_symbol_ = sym;
+ rebuild_blocks();
+ emit symbol_selected(sym);
+ });
+ blocks_.append(block);
+ blocks_grid_->addWidget(block, i / 2, i % 2);
+ }
- int col = 0, row = 0;
- for (const auto& h : holdings_) {
- auto* block = new QPushButton;
- bool selected = (h.symbol == selected_symbol_);
+ block->setProperty("symbol", h.symbol);
+ block->show();
- int min_h = static_cast<int>(std::max(40.0, 40.0 + h.weight * 0.8));
+ const int min_h = static_cast<int>(std::max(40.0, 40.0 + h.weight * 0.8));
block->setFixedHeight(std::min(min_h, 70));
- block->setCursor(Qt::PointingHandCursor);
- QColor bg = block_color(h);
- QString border_style = selected ? QString("border:2px solid %1;").arg(ui::colors::AMBER())
- : QString("border:1px solid %1;").arg(ui::colors::BORDER_DIM());
+ const QColor bg = block_color(h);
+ const QString border_style = selected ? QString("border:2px solid %1;").arg(ui::colors::AMBER())
+ : QString("border:1px solid %1;").arg(ui::colors::BORDER_DIM());
// Square corners (was border-radius:2px). Block label 11px (was 10px).
- block->setStyleSheet(QString("QPushButton { background:rgb(%1,%2,%3); %4"
- " text-align:left; padding:4px 6px;"
- " color:%6; font-size:11px; font-weight:700; }"
- "QPushButton:hover { border-color:%5; }")
- .arg(bg.red())
- .arg(bg.green())
- .arg(bg.blue())
- .arg(border_style, ui::colors::AMBER(), ui::colors::TEXT_PRIMARY()));
+ const QString qss = QString("QPushButton { background:rgb(%1,%2,%3); %4"
+ " text-align:left; padding:4px 6px;"
+ " color:%6; font-size:11px; font-weight:700; }"
+ "QPushButton:hover { border-color:%5; }")
+ .arg(bg.red())
+ .arg(bg.green())
+ .arg(bg.blue())
+ .arg(border_style, ui::colors::AMBER(), ui::colors::TEXT_PRIMARY());
+ if (block->property("qss").toString() != qss) {
+ block->setStyleSheet(qss);
+ block->setProperty("qss", qss);
+ }
// Content
- double chg_val = mode_ == portfolio::HeatmapMode::DayChange ? h.day_change_percent
- : mode_ == portfolio::HeatmapMode::Pnl ? h.unrealized_pnl_percent
- : h.weight;
- QString chg_str = mode_ == portfolio::HeatmapMode::Weight
- ? QString("%1%").arg(QString::number(chg_val, 'f', 1))
- : QString("%1%2%").arg(chg_val >= 0 ? "+" : "").arg(QString::number(chg_val, 'f', 1));
+ const double chg_val = mode_ == portfolio::HeatmapMode::DayChange ? h.day_change_percent
+ : mode_ == portfolio::HeatmapMode::Pnl ? h.unrealized_pnl_percent
+ : h.weight;
+ const QString chg_str =
+ mode_ == portfolio::HeatmapMode::Weight
+ ? QString("%1%").arg(QString::number(chg_val, 'f', 1))
+ : QString("%1%2%").arg(chg_val >= 0 ? "+" : "").arg(QString::number(chg_val, 'f', 1));
block->setText(QString("%1\n%2").arg(h.symbol, chg_str));
-
- connect(block, &QPushButton::clicked, this, [this, sym = h.symbol]() {
- selected_symbol_ = sym;
- rebuild_blocks();
- emit symbol_selected(sym);
- });
-
- grid->addWidget(block, row, col);
- col++;
- if (col >= 2) {
- col = 0;
- row++;
- }
+ // Market value is the one number the compact block cannot show —
+ // surface it (and the portfolio currency) on hover.
+ block->setToolTip(tr("%1 — %2 %3 • %4% of portfolio")
+ .arg(h.symbol, currency_, QString::number(h.market_value, 'f', 2),
+ QString::number(h.weight, 'f', 1)));
+ block->setAccessibleName(h.symbol);
+ block->setAccessibleDescription(block->toolTip());
}
- grid->setRowStretch(row + 1, 1); // push blocks up
+ // Surplus blocks from a previously larger portfolio: hide (a hidden widget
+ // is skipped by QGridLayout so the rows collapse) and keep them pooled.
+ for (int i = n; i < blocks_.size(); ++i)
+ blocks_[i]->hide();
+
+ // Push blocks up. Reset the previous stretch row first or a shrinking
+ // portfolio leaves a stretched empty row mid-grid.
+ const int last_row = n > 0 ? ((n - 1) / 2) : 0;
+ if (stretch_row_ >= 0 && stretch_row_ != last_row + 1)
+ blocks_grid_->setRowStretch(stretch_row_, 0);
+ stretch_row_ = last_row + 1;
+ blocks_grid_->setRowStretch(stretch_row_, 1);
}
void PortfolioHeatmap::update_top_movers() {
@@ -289,8 +333,23 @@ void PortfolioHeatmap::retranslateUi() {
weight_btn_->setText(tr("WT"));
if (day_btn_)
day_btn_->setText(tr("DAY"));
+ if (pnl_btn_) {
+ pnl_btn_->setAccessibleName(tr("Colour blocks by unrealized profit and loss"));
+ pnl_btn_->setToolTip(pnl_btn_->accessibleName());
+ }
+ if (weight_btn_) {
+ weight_btn_->setAccessibleName(tr("Colour blocks by portfolio weight"));
+ weight_btn_->setToolTip(weight_btn_->accessibleName());
+ }
+ if (day_btn_) {
+ day_btn_->setAccessibleName(tr("Colour blocks by today's change"));
+ day_btn_->setToolTip(day_btn_->accessibleName());
+ }
if (movers_header_)
movers_header_->setText(tr("TOP MOVERS"));
+ // Block labels/tooltips are formatted from data — re-render so the
+ // localized tooltip template picks up the new locale.
+ rebuild_blocks();
// Block text is "SYMBOL\n+x.xx%" — pure data, no tr() needed.
// top_gainer_/top_loser_ contents likewise are formatted from data; no
// change on language switch.
diff --git a/fincept-qt/src/screens/portfolio/PortfolioHeatmap.h b/fincept-qt/src/screens/portfolio/PortfolioHeatmap.h
index ace911970..15d831a9a 100644
--- a/fincept-qt/src/screens/portfolio/PortfolioHeatmap.h
+++ b/fincept-qt/src/screens/portfolio/PortfolioHeatmap.h
@@ -5,8 +5,11 @@
#include <QLabel>
#include <QPushButton>
#include <QScrollArea>
+#include <QVector>
#include <QWidget>
+class QGridLayout;
+
namespace fincept::screens {
/// 220px left sidebar with color-coded holding blocks, risk gauge, and top movers.
@@ -44,8 +47,14 @@ class PortfolioHeatmap : public QWidget {
QPushButton* weight_btn_ = nullptr;
QPushButton* day_btn_ = nullptr;
- // Blocks container
+ // Blocks container. Blocks are allocated once and reused across refreshes —
+ // rebuilding them (and re-running setStyleSheet on every one) fired on every
+ // 60 s poll AND on every selection change, which is a full CSS reparse per
+ // holding for data that usually has not changed.
QWidget* blocks_container_ = nullptr;
+ QGridLayout* blocks_grid_ = nullptr;
+ QVector<QPushButton*> blocks_;
+ int stretch_row_ = -1;
// Top movers footer
QLabel* top_gainer_ = nullptr;
diff --git a/fincept-qt/src/screens/portfolio/PortfolioOrderPanel.cpp b/fincept-qt/src/screens/portfolio/PortfolioOrderPanel.cpp
index 44abe55f6..573851aad 100644
--- a/fincept-qt/src/screens/portfolio/PortfolioOrderPanel.cpp
+++ b/fincept-qt/src/screens/portfolio/PortfolioOrderPanel.cpp
@@ -4,8 +4,11 @@
#include "ui/theme/Theme.h"
#include <QEvent>
+#include <QHBoxLayout>
#include <QVBoxLayout>
+#include <cmath>
+
namespace fincept::screens {
PortfolioOrderPanel::PortfolioOrderPanel(QWidget* parent) : QWidget(parent) {
@@ -57,39 +60,17 @@ void PortfolioOrderPanel::build_ui() {
sell_tab_->setCheckable(true);
side_row->addWidget(sell_tab_);
- auto update_tabs = [this]() {
- bool is_buy = (side_ == "BUY");
- const char* active_color = is_buy ? ui::colors::POSITIVE : ui::colors::NEGATIVE;
- const char* inactive_color = ui::colors::TEXT_TERTIARY;
-
- buy_tab_->setChecked(is_buy);
- sell_tab_->setChecked(!is_buy);
-
- buy_tab_->setStyleSheet(
- QString("QPushButton { background:%1; color:%2; border:none;"
- " font-size:10px; font-weight:700; }")
- .arg(is_buy ? ui::colors::POSITIVE() : ui::colors::BG_RAISED(), is_buy ? "#000" : inactive_color));
- sell_tab_->setStyleSheet(
- QString("QPushButton { background:%1; color:%2; border:none;"
- " font-size:10px; font-weight:700; }")
- .arg(!is_buy ? ui::colors::NEGATIVE() : ui::colors::BG_RAISED(), !is_buy ? "#fff" : inactive_color));
-
- // Update header and border color
- setStyleSheet(QString("background:%1; border-left:2px solid %2;").arg(ui::colors::BG_SURFACE(), active_color));
- auto* title_w = findChild<QLabel*>();
- if (title_w && title_w->text() == "ORDER ENTRY") {
- // skip — the title might have been found differently
- }
- };
+ buy_tab_->setAccessibleName(tr("Buy side"));
+ sell_tab_->setAccessibleName(tr("Sell side"));
- connect(buy_tab_, &QPushButton::clicked, this, [this, update_tabs]() {
+ connect(buy_tab_, &QPushButton::clicked, this, [this]() {
side_ = "BUY";
- update_tabs();
+ apply_side_styles();
update_display(); // refresh the submit button label/colour for the new side
});
- connect(sell_tab_, &QPushButton::clicked, this, [this, update_tabs]() {
+ connect(sell_tab_, &QPushButton::clicked, this, [this]() {
side_ = "SELL";
- update_tabs();
+ apply_side_styles();
update_display();
});
@@ -142,26 +123,56 @@ void PortfolioOrderPanel::build_ui() {
note_label_->setStyleSheet(QString("color:%1; font-size:8px;").arg(ui::colors::TEXT_TERTIARY()));
layout->addWidget(note_label_);
- update_tabs();
+ apply_side_styles();
+}
+
+void PortfolioOrderPanel::apply_side_styles() {
+ const bool is_buy = (side_ == "BUY");
+ const char* active_color = is_buy ? ui::colors::POSITIVE : ui::colors::NEGATIVE;
+ const char* inactive_color = ui::colors::TEXT_TERTIARY;
+
+ buy_tab_->setChecked(is_buy);
+ sell_tab_->setChecked(!is_buy);
+
+ buy_tab_->setStyleSheet(
+ QString("QPushButton { background:%1; color:%2; border:none;"
+ " font-size:10px; font-weight:700; }")
+ .arg(is_buy ? ui::colors::POSITIVE() : ui::colors::BG_RAISED(), is_buy ? "#000" : inactive_color));
+ sell_tab_->setStyleSheet(
+ QString("QPushButton { background:%1; color:%2; border:none;"
+ " font-size:10px; font-weight:700; }")
+ .arg(!is_buy ? ui::colors::NEGATIVE() : ui::colors::BG_RAISED(), !is_buy ? "#fff" : inactive_color));
+
+ // Panel edge + panel title both follow the active side. The title was
+ // previously stuck on POSITIVE green even while the SELL tab was active.
+ setStyleSheet(QString("background:%1; border-left:2px solid %2;").arg(ui::colors::BG_SURFACE(), active_color));
+ if (title_label_)
+ title_label_->setStyleSheet(
+ QString("color:%1; font-size:10px; font-weight:700; letter-spacing:1px;").arg(active_color));
}
void PortfolioOrderPanel::set_holding(const portfolio::HoldingWithQuote* holding) {
- holding_ = holding;
+ if (holding)
+ holding_ = *holding; // copy — see the note on holding_ in the header
+ else
+ holding_.reset();
update_display();
}
void PortfolioOrderPanel::set_currency(const QString& currency) {
+ if (currency_ == currency)
+ return;
currency_ = currency;
+ update_display(); // MKT VAL is currency-prefixed
}
void PortfolioOrderPanel::set_side(const QString& side) {
- side_ = side;
- // Trigger tab update
- buy_tab_->setChecked(side == "BUY");
- sell_tab_->setChecked(side == "SELL");
- buy_tab_->click(); // Will trigger the lambda and update styling
- if (side == "SELL")
- sell_tab_->click();
+ // Assign directly instead of synthesising clicks. The old implementation
+ // always click()ed the BUY tab first — even when opening the SELL panel —
+ // which emitted a spurious clicked() and flashed the panel green->red.
+ side_ = (side == "SELL") ? QStringLiteral("SELL") : QStringLiteral("BUY");
+ apply_side_styles();
+ update_display();
}
void PortfolioOrderPanel::update_display() {
@@ -170,8 +181,13 @@ void PortfolioOrderPanel::update_display() {
price_label_->setText("--");
qty_label_->setText("--");
mv_label_->setText("--");
+ // Keep the submit button honest about the current side even with no
+ // selection — it used to keep the previous side's label and colour.
+ submit_btn_->setText(side_ == "BUY" ? tr("OPEN BUY ORDER") : tr("OPEN SELL ORDER"));
+ submit_btn_->setEnabled(side_ == "BUY"); // nothing to sell without a holding
return;
}
+ submit_btn_->setEnabled(true);
symbol_label_->setText(holding_->symbol);
price_label_->setText(QString::number(holding_->current_price, 'f', 2));
@@ -198,10 +214,14 @@ void PortfolioOrderPanel::changeEvent(QEvent* event) {
void PortfolioOrderPanel::retranslateUi() {
if (title_label_)
title_label_->setText(tr("ORDER ENTRY"));
- if (buy_tab_)
+ if (buy_tab_) {
buy_tab_->setText(tr("BUY"));
- if (sell_tab_)
+ buy_tab_->setAccessibleName(tr("Buy side"));
+ }
+ if (sell_tab_) {
sell_tab_->setText(tr("SELL"));
+ sell_tab_->setAccessibleName(tr("Sell side"));
+ }
if (price_prefix_)
price_prefix_->setText(tr("PRICE"));
if (qty_prefix_)
diff --git a/fincept-qt/src/screens/portfolio/PortfolioOrderPanel.h b/fincept-qt/src/screens/portfolio/PortfolioOrderPanel.h
index 35ed86cb4..a65c06d53 100644
--- a/fincept-qt/src/screens/portfolio/PortfolioOrderPanel.h
+++ b/fincept-qt/src/screens/portfolio/PortfolioOrderPanel.h
@@ -6,6 +6,8 @@
#include <QPushButton>
#include <QWidget>
+#include <optional>
+
namespace fincept::screens {
/// 200px right sidebar for BUY/SELL order entry.
@@ -29,6 +31,7 @@ class PortfolioOrderPanel : public QWidget {
private:
void build_ui();
void update_display();
+ void apply_side_styles();
void retranslateUi();
QLabel* title_label_ = nullptr;
@@ -49,7 +52,13 @@ class PortfolioOrderPanel : public QWidget {
QString side_ = "BUY";
QString currency_ = "USD";
- const portfolio::HoldingWithQuote* holding_ = nullptr;
+ /// Value copy, deliberately NOT the caller's pointer. set_holding() used to
+ /// store the raw `HoldingWithQuote*` returned by PortfolioScreen::
+ /// find_holding(), which points into PortfolioSummary::holdings — that
+ /// QVector is reassigned wholesale on every summary refresh, so the stored
+ /// pointer dangled whenever a refresh did not immediately re-select
+ /// (e.g. the portfolio went to zero positions).
+ std::optional<portfolio::HoldingWithQuote> holding_;
};
} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/portfolio/PortfolioPerfChart.cpp b/fincept-qt/src/screens/portfolio/PortfolioPerfChart.cpp
index 167813224..eceaec07e 100644
--- a/fincept-qt/src/screens/portfolio/PortfolioPerfChart.cpp
+++ b/fincept-qt/src/screens/portfolio/PortfolioPerfChart.cpp
@@ -153,6 +153,8 @@ void PortfolioPerfChart::build_ui() {
if (p == current_period_)
btn->setChecked(true);
+ btn->setAccessibleName(tr("Show %1 of performance history").arg(p));
+
connect(btn, &QPushButton::clicked, this, [this, period = p]() { set_period(period); });
slot->addWidget(btn);
@@ -166,6 +168,7 @@ void PortfolioPerfChart::build_ui() {
benchmark_btn_->setCheckable(true);
benchmark_btn_->setCursor(Qt::PointingHandCursor);
benchmark_btn_->setToolTip(tr("Overlay benchmark index (auto-selected by portfolio currency)"));
+ benchmark_btn_->setAccessibleName(tr("Toggle benchmark overlay"));
benchmark_btn_->setStyleSheet(
QString("QPushButton { background:transparent; color:%1; border:1px solid %1;"
" font-size:11px; font-weight:700; }"
@@ -188,6 +191,7 @@ void PortfolioPerfChart::build_ui() {
indexed_btn_->setCursor(Qt::PointingHandCursor);
indexed_btn_->setToolTip(tr("Indexed view: rebase portfolio and benchmark to 100 at the start of\n"
"the selected period. Use when comparing different currencies."));
+ indexed_btn_->setAccessibleName(tr("Toggle base-100 indexed view"));
indexed_btn_->setStyleSheet(
QString("QPushButton { background:transparent; color:%1; border:1px solid %1;"
" font-size:11px; font-weight:700; }"
@@ -269,7 +273,13 @@ void PortfolioPerfChart::set_snapshots(const QVector<portfolio::PortfolioSnapsho
}
void PortfolioPerfChart::set_currency(const QString& currency) {
+ if (currency_ == currency)
+ return;
currency_ = currency;
+ // NAV / COST labels and the crosshair tooltip are currency-prefixed. The
+ // owner calls set_summary() before set_currency(), so without this the
+ // labels kept the previous portfolio's currency until the next poll.
+ update_chart();
}
void PortfolioPerfChart::set_spy_history(const QStringList& dates, const QVector<double>& closes) {
@@ -548,9 +558,13 @@ void PortfolioPerfChart::update_chart() {
chart_view_->set_series_data(nav_line->points(), indexed_mode_ ? QStringLiteral("idx") : currency_);
// ── Benchmark overlay ─────────────────────────────────────────────────────
+ // Set below, after the info labels are written — appending to nav_label_
+ // here was dead code because nav_label_->setText() further down overwrote
+ // it, so the user never saw the "loading…" hint.
+ QString benchmark_note;
if (show_benchmark_ && nav_line->count() >= 2) {
if (spy_dates_.isEmpty() || spy_closes_.isEmpty()) {
- nav_label_->setText(nav_label_->text() + tr(" | %1: loading…").arg(benchmark_symbol_));
+ benchmark_note = tr(" | %1: loading…").arg(benchmark_symbol_);
} else {
const QDate start_date =
QDateTime::fromMSecsSinceEpoch(static_cast<qint64>(nav_line->at(0).x()), QTimeZone::UTC).date();
@@ -622,7 +636,7 @@ void PortfolioPerfChart::update_chart() {
tr("TOTAL %1%2%").arg(total_pnl_pct >= 0 ? "+" : "").arg(QString::number(total_pnl_pct, 'f', 2)));
total_return_label_->setStyleSheet(QString("color:%1; font-size:14px; font-weight:700;").arg(total_color));
- nav_label_->setText(tr("NAV %1 %2").arg(currency_).arg(QString::number(live_nav, 'f', 2)));
+ nav_label_->setText(tr("NAV %1 %2").arg(currency_).arg(QString::number(live_nav, 'f', 2)) + benchmark_note);
if (cost_basis_label_) {
if (cost_basis > 0)
cost_basis_label_->setText(tr("COST %1 %2").arg(currency_).arg(QString::number(cost_basis, 'f', 2)));
diff --git a/fincept-qt/src/screens/portfolio/PortfolioScreen_Handlers.cpp b/fincept-qt/src/screens/portfolio/PortfolioScreen_Handlers.cpp
index 1cf8d1320..d635f4ded 100644
--- a/fincept-qt/src/screens/portfolio/PortfolioScreen_Handlers.cpp
+++ b/fincept-qt/src/screens/portfolio/PortfolioScreen_Handlers.cpp
@@ -75,6 +75,12 @@ void PortfolioScreen::on_portfolio_selected(const QString& id) {
selected_id_ = id;
ScreenStateManager::instance().notify_changed(this);
summary_loaded_ = false;
+ // Drop any error caption left over from a previous failed load.
+ if (loading_label_) {
+ loading_label_->setText(tr("Loading portfolio data…"));
+ loading_label_->setStyleSheet(
+ QString("color:%1; font-size:11px; font-weight:600; letter-spacing:0.8px;").arg(ui::colors::AMBER()));
+ }
active_detail_ = std::nullopt;
command_bar_->set_detail_view(std::nullopt);
if (txn_panel_)
@@ -105,6 +111,7 @@ void PortfolioScreen::on_summary_loaded(portfolio::PortfolioSummary summary) {
command_bar_->set_refreshing(false);
stats_ribbon_->set_summary(summary);
status_bar_->set_summary(summary);
+ status_bar_->set_feed_state(true);
update_main_view_data();
update_content_state();
@@ -156,11 +163,37 @@ void PortfolioScreen::on_summary_loaded(portfolio::PortfolioSummary summary) {
services::PortfolioService::instance().fetch_risk_free_rate();
}
-void PortfolioScreen::on_summary_error(QString portfolio_id, QString /*error*/) {
+void PortfolioScreen::on_summary_error(QString portfolio_id, QString error) {
if (portfolio_id != selected_id_)
return;
- // Show empty state with error — for now just revert to empty
+
+ // Always clear the spinner — it used to spin forever after a failed
+ // refresh because only the success path called set_refreshing(false).
+ command_bar_->set_refreshing(false);
+
+ if (summary_loaded_) {
+ // We already have data on screen. Keep showing it (P11: never blank a
+ // populated view) and flag the feed as stale instead.
+ status_bar_->set_feed_state(
+ false, error.isEmpty() ? tr("The last refresh failed — values shown may be out of date.")
+ : tr("The last refresh failed — values shown may be out of date.\n%1").arg(error));
+ return;
+ }
+
+ // Nothing rendered yet. update_content_state() parks on the loading
+ // skeleton whenever a portfolio is selected but no summary has arrived, so
+ // a first-load failure used to shimmer "Loading portfolio data…" forever
+ // with no way to tell that it had already given up. Turn the skeleton
+ // caption into an error + retry hint instead.
summary_loaded_ = false;
+ status_bar_->set_feed_state(false, error);
+ if (loading_label_) {
+ loading_label_->setText(error.isEmpty()
+ ? tr("Could not load this portfolio. Press ↻ (F5) to retry.")
+ : tr("Could not load this portfolio: %1\nPress ↻ (F5) to retry.").arg(error));
+ loading_label_->setStyleSheet(
+ QString("color:%1; font-size:11px; font-weight:600; letter-spacing:0.8px;").arg(ui::colors::NEGATIVE()));
+ }
update_content_state();
}
diff --git a/fincept-qt/src/screens/portfolio/PortfolioScreen_Layout.cpp b/fincept-qt/src/screens/portfolio/PortfolioScreen_Layout.cpp
index 2bed21840..373a1f786 100644
--- a/fincept-qt/src/screens/portfolio/PortfolioScreen_Layout.cpp
+++ b/fincept-qt/src/screens/portfolio/PortfolioScreen_Layout.cpp
@@ -702,6 +702,11 @@ QWidget* PortfolioScreen::build_main_view() {
connect(order_panel_, &PortfolioOrderPanel::close_requested, this, &PortfolioScreen::on_order_panel_close);
connect(order_panel_, &PortfolioOrderPanel::buy_submitted, this, [this]() {
AddAssetDialog dlg(this);
+ // The order panel always opens against a selected position — carry that
+ // ticker (and its live price) into the dialog instead of making the user
+ // retype a symbol the terminal is already showing.
+ if (const auto* h = find_holding(selected_symbol_))
+ dlg.preset(h->symbol, h->current_price);
if (dlg.exec() == QDialog::Accepted) {
services::PortfolioService::instance().add_asset(selected_id_, dlg.symbol(), dlg.quantity(), dlg.price());
}
@@ -744,11 +749,18 @@ void PortfolioScreen::update_main_view_data() {
order_panel_->set_currency(currency);
- // Re-select the current symbol
+ // Re-select the current symbol. find_holding() returns nullptr once the
+ // position is gone (sold out, portfolio emptied) — always push the result
+ // through so the order panel drops its stale copy instead of keeping a row
+ // that no longer exists.
if (!selected_symbol_.isEmpty()) {
heatmap_->set_selected_symbol(selected_symbol_);
blotter_->set_selected_symbol(selected_symbol_);
order_panel_->set_holding(find_holding(selected_symbol_));
+ if (!find_holding(selected_symbol_))
+ selected_symbol_.clear();
+ } else {
+ order_panel_->set_holding(nullptr);
}
}
diff --git a/fincept-qt/src/screens/portfolio/PortfolioSectorPanel.cpp b/fincept-qt/src/screens/portfolio/PortfolioSectorPanel.cpp
index 666acea6f..f2c718dcb 100644
--- a/fincept-qt/src/screens/portfolio/PortfolioSectorPanel.cpp
+++ b/fincept-qt/src/screens/portfolio/PortfolioSectorPanel.cpp
@@ -10,6 +10,7 @@
#include <QHBoxLayout>
#include <QMouseEvent>
#include <QPieSeries>
+#include <QStringList>
#include <QVBoxLayout>
#include <algorithm>
@@ -125,8 +126,30 @@ void PortfolioSectorPanel::build_ui() {
void PortfolioSectorPanel::set_holdings(const QVector<portfolio::HoldingWithQuote>& holdings) {
holdings_ = holdings;
- selected_sector_.clear(); // reset filter on fresh data
- corr_matrix_.clear(); // invalidate stale correlation data
+
+ // Keep the active sector filter across a refresh as long as that sector
+ // still exists. Clearing it unconditionally desynced this panel from the
+ // blotter: the highlight disappeared here every 60 s while the blotter
+ // stayed filtered, with no visible way to tell why rows were missing.
+ if (!selected_sector_.isEmpty()) {
+ bool still_present = false;
+ for (const auto& h : holdings_) {
+ const QString sec = h.sector.isEmpty() ? tr("Unclassified") : h.sector;
+ if (sec == selected_sector_) {
+ still_present = true;
+ break;
+ }
+ }
+ if (!still_present) {
+ selected_sector_.clear();
+ emit sector_selected({}); // tell the blotter to drop the filter too
+ }
+ }
+
+ // Correlation is deliberately NOT cleared: it is keyed by symbol pair, so
+ // stale entries stay valid and entries for removed symbols are simply never
+ // looked up. Wiping it made the whole matrix flash back to "…" on every
+ // poll while the async refetch was in flight (violates P11).
update_donut();
update_correlation();
}
@@ -254,6 +277,37 @@ void PortfolioSectorPanel::update_donut() {
}
void PortfolioSectorPanel::update_correlation() {
+ // ── Early-out fingerprint ────────────────────────────────────────────────
+ // Rebuilding this grid destroys and recreates one stylesheet-carrying
+ // QLabel per cell. The inputs (top-6 symbols by weight + the matrix) only
+ // change when a new correlation fetch lands, so skip the rebuild when the
+ // rendered content would be byte-identical.
+ {
+ auto probe = holdings_;
+ std::sort(probe.begin(), probe.end(), [](const auto& a, const auto& b) { return a.weight > b.weight; });
+ const int pn = static_cast<int>(std::min(qsizetype{6}, probe.size()));
+ QStringList parts;
+ parts.reserve(pn * pn + 1);
+ for (int i = 0; i < pn; ++i)
+ parts << probe[i].symbol;
+ for (int i = 0; i < pn; ++i) {
+ for (int j = 0; j < pn; ++j) {
+ const QString ab = probe[i].symbol + "|" + probe[j].symbol;
+ const QString ba = probe[j].symbol + "|" + probe[i].symbol;
+ if (corr_matrix_.contains(ab))
+ parts << QString::number(corr_matrix_.value(ab), 'f', 2);
+ else if (corr_matrix_.contains(ba))
+ parts << QString::number(corr_matrix_.value(ba), 'f', 2);
+ else
+ parts << QStringLiteral("-");
+ }
+ }
+ const QString sig = QString::number(holdings_.size()) + "|" + parts.join(',');
+ if (sig == corr_signature_ && corr_widget_->layout())
+ return;
+ corr_signature_ = sig;
+ }
+
if (auto* old = corr_widget_->layout()) {
QLayoutItem* item;
while ((item = old->takeAt(0)) != nullptr) {
@@ -368,7 +422,9 @@ void PortfolioSectorPanel::retranslateUi() {
// Donut legend uses translated "Unclassified" + sector data; matrix shows
// "Need 2+ holdings for correlation" or a grid. Re-run both so the strings
- // pick up the new locale.
+ // pick up the new locale — the fingerprint must be dropped first or the
+ // correlation grid would short-circuit and keep the old language.
+ corr_signature_.clear();
update_donut();
update_correlation();
}
diff --git a/fincept-qt/src/screens/portfolio/PortfolioSectorPanel.h b/fincept-qt/src/screens/portfolio/PortfolioSectorPanel.h
index 3d6d739b3..94153cf42 100644
--- a/fincept-qt/src/screens/portfolio/PortfolioSectorPanel.h
+++ b/fincept-qt/src/screens/portfolio/PortfolioSectorPanel.h
@@ -57,6 +57,12 @@ class PortfolioSectorPanel : public QWidget {
QString currency_ = "USD";
QString selected_sector_; // empty = no filter active
QHash<QString, double> corr_matrix_; // real Pearson matrix, key="SYM1|SYM2"
+
+ /// Fingerprint of what the correlation grid currently renders (symbols +
+ /// values). update_correlation() rebuilds ~49 stylesheet-carrying QLabels,
+ /// so it bails out early when the fingerprint is unchanged — correlation
+ /// only moves when a new matrix lands, not on every price poll.
+ QString corr_signature_;
};
} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/portfolio/PortfolioStatsRibbon.cpp b/fincept-qt/src/screens/portfolio/PortfolioStatsRibbon.cpp
index 2c4f7afda..4fe01855d 100644
--- a/fincept-qt/src/screens/portfolio/PortfolioStatsRibbon.cpp
+++ b/fincept-qt/src/screens/portfolio/PortfolioStatsRibbon.cpp
@@ -82,6 +82,12 @@ QWidget* PortfolioStatsRibbon::build_hero(HeroCell& c, const QString& label_text
}
void PortfolioStatsRibbon::apply_hero_value_color(HeroCell& c, const char* color, int value_px) {
+ // Skip the restyle when the colour has not flipped. This runs on every
+ // poll and each setStyleSheet is a CSS reparse + repolish of the label.
+ const QString color_str = QString::fromLatin1(color);
+ if (c.value->property("colorTok").toString() == color_str)
+ return;
+ c.value->setProperty("colorTok", color_str);
c.value->setStyleSheet(QString("color:%1; font-size:%2px; font-weight:700;"
" letter-spacing:0.2px; background:transparent;")
.arg(color)
@@ -116,11 +122,34 @@ QWidget* PortfolioStatsRibbon::build_risk_grid() {
mdd_ = add_grid_chip(g, 2, 0, tr("MDD"));
risk_ = add_grid_chip(g, 2, 1, tr("RISK"));
+ apply_chip_tooltips();
+
outer->addLayout(g, 1);
return risk_cell_;
}
+void PortfolioStatsRibbon::apply_chip_tooltips() {
+ // Six four-letter labels with no explanation of window, benchmark or
+ // scale. Say what each number actually is.
+ auto set = [](GridChip& c, const QString& text) {
+ if (c.label)
+ c.label->setToolTip(text);
+ if (c.value) {
+ c.value->setToolTip(text);
+ c.value->setAccessibleDescription(text);
+ }
+ };
+ set(sharpe_, tr("Sharpe ratio — annualised excess return per unit of volatility, "
+ "from daily portfolio snapshots against the live risk-free rate."));
+ set(conc_, tr("Concentration — combined weight of your three largest positions."));
+ set(beta_, tr("Beta — OLS regression of portfolio returns against the benchmark index. "
+ "1.0 means it moves with the market."));
+ set(vol_, tr("Volatility — annualised standard deviation of the last 30 days of returns."));
+ set(mdd_, tr("Maximum drawdown — worst peak-to-trough decline in the snapshot history."));
+ set(risk_, tr("Composite risk score, 0–100. Lower is calmer; above 60 is aggressive."));
+}
+
PortfolioStatsRibbon::GridChip PortfolioStatsRibbon::add_grid_chip(QGridLayout* g, int row, int col,
const QString& label_text) {
GridChip c;
@@ -267,6 +296,8 @@ void PortfolioStatsRibbon::retranslateUi() {
if (risk_.label)
risk_.label->setText(tr("RISK"));
+ apply_chip_tooltips();
+
if (last_summary_.has_value()) {
// Re-render the "▲ %1 positions" sub-line under PORTFOLIO VALUE.
if (value_cell_.sub)
@@ -277,6 +308,13 @@ void PortfolioStatsRibbon::retranslateUi() {
void PortfolioStatsRibbon::refresh_theme() {
setStyleSheet(QString("#portfolioStatsRibbon { background:%1; border-bottom:1px solid %2; }")
.arg(ui::colors::BG_SURFACE(), ui::colors::BORDER_DIM()));
+
+ // Drop the "already this colour" memo in apply_hero_value_color(), or the
+ // hero values would keep the previous theme's palette.
+ for (HeroCell* c : {&value_cell_, &pnl_cell_, &day_cell_}) {
+ if (c->value)
+ c->value->setProperty("colorTok", QString());
+ }
// Hero label/sub colors and chip label colors are static per-style; the
// value colors get re-applied on the next set_summary/set_metrics call,
// which always fires after a theme switch via PortfolioScreen's
diff --git a/fincept-qt/src/screens/portfolio/PortfolioStatsRibbon.h b/fincept-qt/src/screens/portfolio/PortfolioStatsRibbon.h
index eef2296db..38f6be464 100644
--- a/fincept-qt/src/screens/portfolio/PortfolioStatsRibbon.h
+++ b/fincept-qt/src/screens/portfolio/PortfolioStatsRibbon.h
@@ -54,6 +54,8 @@ class PortfolioStatsRibbon : public QWidget {
QWidget* build_risk_grid();
GridChip add_grid_chip(QGridLayout* g, int row, int col, const QString& label_text);
void apply_hero_value_color(HeroCell& c, const char* color, int value_px);
+ /// Explains what SHARPE/CONC/BETA/VOL/MDD/RISK actually measure.
+ void apply_chip_tooltips();
// Cells
HeroCell value_cell_; // PORTFOLIO VALUE
diff --git a/fincept-qt/src/screens/portfolio/PortfolioStatusBar.cpp b/fincept-qt/src/screens/portfolio/PortfolioStatusBar.cpp
index d51b98454..cf50be0a0 100644
--- a/fincept-qt/src/screens/portfolio/PortfolioStatusBar.cpp
+++ b/fincept-qt/src/screens/portfolio/PortfolioStatusBar.cpp
@@ -6,6 +6,7 @@
#include <QDateTime>
#include <QEvent>
#include <QHBoxLayout>
+#include <QLocale>
#include <QTimeZone>
namespace fincept::screens {
@@ -93,7 +94,26 @@ void PortfolioStatusBar::stop_clock() {
void PortfolioStatusBar::update_clock() {
auto now = QDateTime::currentDateTime();
time_label_->setText(now.toString("hh:mm:ss"));
- tz_label_->setText(QString(" %1").arg(now.timeZone().abbreviation(now)));
+ // The timezone abbreviation is an expensive lookup and changes at most
+ // twice a year — do not recompute + re-set it every single second.
+ const QString abbrev = now.timeZone().abbreviation(now);
+ if (abbrev != tz_abbrev_) {
+ tz_abbrev_ = abbrev;
+ tz_label_->setText(QString(" %1").arg(abbrev));
+ }
+}
+
+void PortfolioStatusBar::set_feed_state(bool live, const QString& detail) {
+ feed_live_ = live;
+ if (!live_label_)
+ return;
+ live_label_->setText(QString("● ") + (live ? tr("LIVE") : tr("STALE")));
+ live_label_->setStyleSheet(QString("color:%1; font-size:10px; font-weight:700; letter-spacing:0.3px;")
+ .arg(live ? ui::colors::POSITIVE() : ui::colors::NEGATIVE()));
+ live_label_->setToolTip(detail.isEmpty()
+ ? (live ? tr("Market data refreshed successfully.")
+ : tr("The last refresh failed — values shown may be out of date."))
+ : detail);
}
void PortfolioStatusBar::set_portfolio_name(const QString& name) {
@@ -102,7 +122,10 @@ void PortfolioStatusBar::set_portfolio_name(const QString& name) {
void PortfolioStatusBar::set_summary(const portfolio::PortfolioSummary& s) {
last_summary_ = s;
- auto fmt = [](double v) { return QString::number(v, 'f', 2); };
+ // Thousands separators, matching PortfolioStatsRibbon. A bare
+ // QString::number rendered the NAV as "1234567.89" right next to the
+ // ribbon's "1,234,567.89".
+ auto fmt = [](double v) { return QLocale().toString(v, 'f', 2); };
set_portfolio_name(s.portfolio.name);
positions_label_->setText(tr("%1 positions").arg(s.total_positions));
@@ -124,8 +147,7 @@ void PortfolioStatusBar::changeEvent(QEvent* event) {
void PortfolioStatusBar::retranslateUi() {
if (version_label_)
version_label_->setText(tr("PORTFOLIO TERMINAL v4.0"));
- if (live_label_)
- live_label_->setText("● " + tr("LIVE"));
+ set_feed_state(feed_live_); // re-renders LIVE/STALE + its tooltip
if (last_summary_.has_value()) {
// Re-render dynamic strings from cached summary.
diff --git a/fincept-qt/src/screens/portfolio/PortfolioStatusBar.h b/fincept-qt/src/screens/portfolio/PortfolioStatusBar.h
index b09eba91e..35f0bcafa 100644
--- a/fincept-qt/src/screens/portfolio/PortfolioStatusBar.h
+++ b/fincept-qt/src/screens/portfolio/PortfolioStatusBar.h
@@ -18,6 +18,12 @@ class PortfolioStatusBar : public QWidget {
void set_summary(const portfolio::PortfolioSummary& summary);
void set_portfolio_name(const QString& name);
+ /// Drive the ●LIVE / ●STALE indicator from what actually happened.
+ /// It used to be a hard-coded green "LIVE" that stayed lit even when the
+ /// last refresh had failed — a status light that never reports a problem is
+ /// worse than no status light.
+ void set_feed_state(bool live, const QString& detail = {});
+
void start_clock();
void stop_clock();
@@ -39,6 +45,8 @@ class PortfolioStatusBar : public QWidget {
QLabel* tz_label_ = nullptr;
QTimer* clock_timer_ = nullptr;
+ QString tz_abbrev_; // cached — recomputed only when it actually changes
+ bool feed_live_ = true;
std::optional<portfolio::PortfolioSummary> last_summary_;
};
diff --git a/fincept-qt/src/screens/portfolio/PortfolioTxnPanel.cpp b/fincept-qt/src/screens/portfolio/PortfolioTxnPanel.cpp
index 4d684bb53..0869aa0b4 100644
--- a/fincept-qt/src/screens/portfolio/PortfolioTxnPanel.cpp
+++ b/fincept-qt/src/screens/portfolio/PortfolioTxnPanel.cpp
@@ -8,6 +8,7 @@
#include <QEvent>
#include <QHBoxLayout>
#include <QHeaderView>
+#include <QScrollBar>
#include <QTableWidgetItem>
#include <QVBoxLayout>
@@ -102,6 +103,7 @@ void PortfolioTxnPanel::set_transactions(const QVector<portfolio::Transaction>&
void PortfolioTxnPanel::clear() {
txns_.clear();
+ table_->clearSpans(); // drop the empty-state span before reuse
table_->setRowCount(0);
count_label_->clear();
}
@@ -115,6 +117,18 @@ void PortfolioTxnPanel::apply_collapsed_state() {
}
void PortfolioTxnPanel::populate() {
+ // The whole table is rebuilt on every 60 s poll. Remember where the user
+ // was (selected transaction id + scroll offset) and put them back, instead
+ // of yanking the view to the top mid-read.
+ QString prev_key;
+ if (const int prev_row = table_->currentRow(); prev_row >= 0) {
+ const auto* date_item = table_->item(prev_row, 0);
+ const auto* sym_item = table_->item(prev_row, 1);
+ if (date_item && sym_item)
+ prev_key = date_item->text() + '|' + sym_item->text();
+ }
+ const int prev_scroll = table_->verticalScrollBar() ? table_->verticalScrollBar()->value() : 0;
+
table_->setSortingEnabled(false);
table_->setRowCount(0);
@@ -177,7 +191,35 @@ void PortfolioTxnPanel::populate() {
}
table_->setSortingEnabled(true);
- count_label_->setText(tr("%1 transactions").arg(txns_.size()));
+ count_label_->setText(tr("%n transaction(s)", "", static_cast<int>(txns_.size())));
+
+ // Restore selection + scroll position after the rebuild.
+ if (!prev_key.isEmpty()) {
+ for (int r = 0; r < table_->rowCount(); ++r) {
+ const auto* date_item = table_->item(r, 0);
+ const auto* sym_item = table_->item(r, 1);
+ if (date_item && sym_item && (date_item->text() + '|' + sym_item->text()) == prev_key) {
+ table_->selectRow(r);
+ break;
+ }
+ }
+ }
+ if (table_->verticalScrollBar())
+ table_->verticalScrollBar()->setValue(prev_scroll);
+
+ // Empty state — a blank grid reads as "broken", not as "nothing here yet".
+ if (txns_.isEmpty()) {
+ table_->setRowCount(1);
+ auto* msg = new QTableWidgetItem(tr("No transactions recorded for this portfolio yet."));
+ msg->setForeground(QColor(ui::colors::TEXT_TERTIARY()));
+ msg->setTextAlignment(Qt::AlignCenter);
+ msg->setFlags(Qt::ItemIsEnabled); // not selectable — it is not data
+ table_->setItem(0, 0, msg);
+ table_->setSpan(0, 0, 1, table_->columnCount());
+ } else {
+ // Drop a span left over from a previous empty render.
+ table_->clearSpans();
+ }
}
void PortfolioTxnPanel::refresh_theme() {
@@ -227,8 +269,8 @@ void PortfolioTxnPanel::retranslateUi() {
tr("Price"), tr("Total"), tr("Notes")};
table_->setHorizontalHeaderLabels(headers);
}
- if (count_label_ && !txns_.isEmpty())
- count_label_->setText(tr("%1 transactions").arg(txns_.size()));
+ // Row content carries a translated empty-state message, so re-render.
+ populate();
}
} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/portfolio/views/AnalyticsSectorsView.cpp b/fincept-qt/src/screens/portfolio/views/AnalyticsSectorsView.cpp
index f149f2222..a4a9c68b6 100644
--- a/fincept-qt/src/screens/portfolio/views/AnalyticsSectorsView.cpp
+++ b/fincept-qt/src/screens/portfolio/views/AnalyticsSectorsView.cpp
@@ -12,6 +12,7 @@
#include <QHeaderView>
#include <QLabel>
#include <QLocale>
+#include <QMouseEvent>
#include <QPainter>
#include <QPieSeries>
#include <QScrollArea>
@@ -65,16 +66,16 @@ class SectorCardClickForwarder : public QObject {
QString sector_;
};
-// English source keys returned by verdict_for_*. Translated to display strings
-// in the rendering code below (kept English here so verdict_color can pattern-
-// match without depending on the active locale).
-[[maybe_unused]] constexpr const char* kVerdictDiversified = "Diversified";
-[[maybe_unused]] constexpr const char* kVerdictBalanced = "Balanced";
-[[maybe_unused]] constexpr const char* kVerdictConcentrated = "Concentrated";
+// verdict_for_* return English source keys so verdict_color() can pattern-match
+// without depending on the active locale; the render code translates them for
+// display. (Three unused `kVerdict*` constants that duplicated these literals
+// were removed — they were dead and had to be kept in sync by hand.)
QString verdict_for_hhi(double hhi) {
- // HHI convention uses fractions of 10,000; we use percent-squared so
- // divide by 100 to get the standard range. 1500-2500 = moderate, 2500+ = concentrated.
+ // Σ(weight%)² over sectors — already the standard 0…10 000 HHI scale, so
+ // the DOJ/FTC thresholds apply directly: <1500 unconcentrated,
+ // 1500–2500 moderate, >2500 concentrated. (The previous comment claimed a
+ // ÷100 rescale that the code never performed.)
if (hhi < 1500)
return QStringLiteral("Diversified");
if (hhi < 2500)
@@ -550,6 +551,15 @@ void AnalyticsSectorsView::update_donut(const QVector<SectorInfo>& sectors) {
}
void AnalyticsSectorsView::update_sector_table(const QVector<SectorInfo>& sectors) {
+ // Preserve the highlighted sector across the (60 s) rebuild — an
+ // unconditional clearSelection() dropped it every poll even though the
+ // blotter stayed filtered by that sector.
+ QString prev_sector;
+ if (const int prev_row = sector_table_->currentRow(); prev_row >= 0) {
+ if (const auto* item = sector_table_->item(prev_row, 1))
+ prev_sector = item->text();
+ }
+
sector_table_->setRowCount(sectors.size());
sector_table_->clearSelection();
@@ -577,6 +587,9 @@ void AnalyticsSectorsView::update_sector_table(const QVector<SectorInfo>& sector
(s.pnl >= 0 ? QStringLiteral("+") : QString()) + QLocale::system().toString(s.pnl, 'f', 2);
set_text(5, pnl_text, pnl_color, Qt::AlignRight);
set_text(6, format_pct(s.pnl_percent, true), pnl_color, Qt::AlignRight);
+
+ if (!prev_sector.isEmpty() && s.name == prev_sector)
+ sector_table_->selectRow(r);
}
}
@@ -898,8 +911,12 @@ void AnalyticsSectorsView::update_correlation() {
}
bool SectorCardClickForwarder::eventFilter(QObject* obj, QEvent* ev) {
- if (ev->type() == QEvent::MouseButtonRelease && owner_)
- emit owner_->sector_selected(sector_);
+ // Left button only — a right-click (context menu) or a middle-click used to
+ // silently re-filter the blotter.
+ if (ev->type() == QEvent::MouseButtonRelease && owner_) {
+ if (auto* me = static_cast<QMouseEvent*>(ev); me->button() == Qt::LeftButton)
+ emit owner_->sector_selected(sector_);
+ }
return QObject::eventFilter(obj, ev);
}
diff --git a/fincept-qt/src/screens/portfolio/views/CustomIndexView.cpp b/fincept-qt/src/screens/portfolio/views/CustomIndexView.cpp
index d83430079..d92b4583d 100644
--- a/fincept-qt/src/screens/portfolio/views/CustomIndexView.cpp
+++ b/fincept-qt/src/screens/portfolio/views/CustomIndexView.cpp
@@ -302,18 +302,30 @@ void CustomIndexView::set_data(const portfolio::PortfolioSummary& summary, const
}
void CustomIndexView::update_constituents() {
+ // set_data() runs on every portfolio poll, so this table is rebuilt while
+ // the user is still ticking constituents. Snapshot their choices first and
+ // put them back \u2014 otherwise every unticked row silently re-ticked itself
+ // roughly once a minute.
+ QHash<QString, Qt::CheckState> prev_checks;
+ for (int r = 0; r < const_table_->rowCount(); ++r) {
+ const auto* sym_item = const_table_->item(r, 1);
+ const auto* chk = const_table_->item(r, 0);
+ if (sym_item && chk)
+ prev_checks.insert(sym_item->text(), chk->checkState());
+ }
+
const_table_->setRowCount(static_cast<int>(summary_.holdings.size()));
for (int r = 0; r < static_cast<int>(summary_.holdings.size()); ++r) {
const auto& h = summary_.holdings[r];
const_table_->setRowHeight(r, 28);
- // Check box (text-based, ticked by default)
+ // Check box (text-based, ticked by default for newly-seen symbols)
auto* check = new QTableWidgetItem("\u2611");
check->setTextAlignment(Qt::AlignCenter);
check->setForeground(QColor(ui::colors::POSITIVE()));
check->setFlags(check->flags() | Qt::ItemIsUserCheckable);
- check->setCheckState(Qt::Checked);
+ check->setCheckState(prev_checks.value(h.symbol, Qt::Checked));
const_table_->setItem(r, 0, check);
auto set_item = [&](int col, const QString& text, const char* color = nullptr) {
@@ -465,6 +477,16 @@ void CustomIndexView::delete_selected_index() {
const auto& idx = loaded_indices_[row];
+ // Destructive and irreversible (the index and its whole value history go),
+ // and it was one click away with no confirmation at all.
+ const auto answer = QMessageBox::question(
+ this, tr("Delete Custom Index"),
+ tr("Delete the index \"%1\"?\n\nIts entire recorded value history will be removed. This cannot be undone.")
+ .arg(idx.name),
+ QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
+ if (answer != QMessageBox::Yes)
+ return;
+
auto r = CustomIndexRepository::instance().remove(idx.id);
if (r.is_err()) {
LOG_ERROR("CustomIndex", "Delete failed: " + QString::fromStdString(r.error()));
@@ -506,8 +528,12 @@ void CustomIndexView::show_index_performance(const QString& index_id, const QStr
auto* chart = perf_chart_view_->chart();
chart->removeAllSeries();
const auto old_axes = chart->axes();
- for (auto* ax : old_axes)
+ for (auto* ax : old_axes) {
+ // removeAxis() only detaches — without the delete each re-render leaked
+ // a QDateTimeAxis + a QValueAxis.
chart->removeAxis(ax);
+ delete ax;
+ }
chart->addSeries(series);
chart->setTitle(QString());
diff --git a/fincept-qt/src/screens/portfolio/views/EconomicsView.cpp b/fincept-qt/src/screens/portfolio/views/EconomicsView.cpp
index 564cee021..797b0b5a3 100644
--- a/fincept-qt/src/screens/portfolio/views/EconomicsView.cpp
+++ b/fincept-qt/src/screens/portfolio/views/EconomicsView.cpp
@@ -196,12 +196,15 @@ struct MacroSeries {
const char* label;
const char* suffix;
};
+// Labels are marked with QT_TRANSLATE_NOOP so lupdate can extract them — a
+// bare tr(m.label) on a runtime const char* is invisible to the extractor and
+// these five strings never reached the .ts files.
const MacroSeries kMacroSeries[] = {
- {"DGS10", "10Y Treasury Yield", "%"},
- {"T10YIE", "Inflation (10Y breakeven)", "%"},
- {"A191RL1Q225SBEA", "Real GDP Growth (annualised)", "%"},
- {"DTWEXBGS", "USD Index (broad)", ""},
- {"DCOILWTICO", "WTI Crude Oil", " $/bbl"},
+ {"DGS10", QT_TRANSLATE_NOOP("fincept::screens::EconomicsView", "10Y Treasury Yield"), "%"},
+ {"T10YIE", QT_TRANSLATE_NOOP("fincept::screens::EconomicsView", "Inflation (10Y breakeven)"), "%"},
+ {"A191RL1Q225SBEA", QT_TRANSLATE_NOOP("fincept::screens::EconomicsView", "Real GDP Growth (annualised)"), "%"},
+ {"DTWEXBGS", QT_TRANSLATE_NOOP("fincept::screens::EconomicsView", "USD Index (broad)"), ""},
+ {"DCOILWTICO", QT_TRANSLATE_NOOP("fincept::screens::EconomicsView", "WTI Crude Oil"), " $/bbl"},
};
} // namespace
@@ -316,7 +319,14 @@ void EconomicsView::retranslateUi() {
}
}
-// ── Sector inference (mirrors PortfolioSectorPanel, kept local) ───────────────
+// ── Sector inference — FALLBACK ONLY ─────────────────────────────────────────
+//
+// Prefer HoldingWithQuote::sector (populated from the import payload or the
+// SectorResolver) via sector_of() below. This static table only covers ~120 US
+// large caps and is what every other portfolio surface would disagree with:
+// PortfolioSectorPanel and AnalyticsSectorsView both read h.sector, so an
+// imported holding tagged "Consumer Staples" showed up here as "Consumer
+// Defensive" — or, for anything off this list, as "Other".
static QString sector_for(const QString& sym) {
const QString s = sym.toUpper();
static const QHash<QString, QString> known = {
@@ -455,8 +465,60 @@ static QString sector_for(const QString& sym) {
return "Other";
}
+/// Resolved sector for a holding: the real one when we have it, the symbol
+/// heuristic otherwise.
+static QString sector_of(const portfolio::HoldingWithQuote& h) {
+ return h.sector.isEmpty() ? sector_for(h.symbol) : h.sector;
+}
+
+/// Maps the various sector vocabularies that can reach us (yfinance style,
+/// GICS style, import-file style) onto the keys used by the factor table in
+/// update_sensitivity(). Without this, a holding tagged "Financials" or
+/// "Consumer Discretionary" matched no row and its weight vanished from the
+/// exposure calculation entirely.
+static QString normalize_sector_key(const QString& sector) {
+ static const QHash<QString, QString> alias = {
+ {"financials", "Financial Services"},
+ {"financial", "Financial Services"},
+ {"consumer discretionary", "Consumer Cyclical"},
+ {"consumer staples", "Consumer Defensive"},
+ {"information technology", "Technology"},
+ {"tech", "Technology"},
+ {"health care", "Healthcare"},
+ {"communication services", "Communication"},
+ {"materials", "Basic Materials"},
+ {"industrial", "Industrials"},
+ {"etf", "ETF/Index"},
+ {"etf/index", "ETF/Index"},
+ {"index", "ETF/Index"},
+ {"us equity", "ETF/Index"},
+ {"crypto", "Cryptocurrency"},
+ {"bonds", "Other"},
+ {"fixed income", "Other"},
+ {"commodities", "Other"},
+ {"unclassified", "Other"},
+ };
+ const auto it = alias.find(sector.trimmed().toLower());
+ return it != alias.end() ? *it : sector;
+}
+
void EconomicsView::update_indicators() {
const auto& hv = summary_.holdings;
+
+ // Empty state — an empty grid gives the user nothing to act on.
+ indicators_table_->clearSpans();
+ if (hv.isEmpty()) {
+ indicators_table_->setRowCount(1);
+ indicators_table_->setRowHeight(0, 40);
+ auto* msg = new QTableWidgetItem(tr("No holdings in this portfolio yet."));
+ msg->setTextAlignment(Qt::AlignCenter);
+ msg->setForeground(QColor(ui::colors::TEXT_TERTIARY()));
+ msg->setFlags(Qt::ItemIsEnabled);
+ indicators_table_->setItem(0, 0, msg);
+ indicators_table_->setSpan(0, 0, 1, indicators_table_->columnCount());
+ return;
+ }
+
indicators_table_->setRowCount(hv.size());
// Sort by market value descending
@@ -481,7 +543,7 @@ void EconomicsView::update_indicators() {
const char* pnl_pct_color = h.unrealized_pnl_percent >= 0 ? ui::colors::POSITIVE : ui::colors::NEGATIVE;
set(0, h.symbol, ui::colors::CYAN);
- set(1, sector_for(h.symbol), ui::colors::TEXT_SECONDARY);
+ set(1, sector_of(h), ui::colors::TEXT_SECONDARY);
set(2, QString("%1%").arg(QString::number(h.weight, 'f', 1)), ui::colors::TEXT_PRIMARY);
set(3, QString("%1 %2").arg(currency_).arg(QString::number(h.cost_basis, 'f', 2)), ui::colors::TEXT_SECONDARY);
set(4, QString("%1 %2").arg(currency_).arg(QString::number(h.market_value, 'f', 2)), ui::colors::WARNING);
@@ -530,10 +592,36 @@ void EconomicsView::update_sensitivity() {
{"Other", -0.08, +0.06, -0.03, -0.02, +0.00},
};
- // Build sector weight map from actual holdings
+ // Build sector weight map from actual holdings. Uses the resolved sector so
+ // the factor exposures agree with the SECTOR column above and with the
+ // sector donut on the landing view.
QHash<QString, double> sector_weights;
- for (const auto& h : summary_.holdings)
- sector_weights[sector_for(h.symbol)] += h.weight / 100.0;
+ for (const auto& h : summary_.holdings) {
+ const QString key = normalize_sector_key(sector_of(h));
+ sector_weights[key] += h.weight / 100.0;
+ }
+
+ // Anything that still does not match a factor row is folded into "Other"
+ // so the exposures always sum over 100% of the book.
+ {
+ QHash<QString, double> matched;
+ double other = sector_weights.value("Other", 0.0);
+ for (auto it = sector_weights.begin(); it != sector_weights.end(); ++it) {
+ bool known = false;
+ for (const auto& sf : kSectorFactors) {
+ if (it.key() == QLatin1String(sf.sector)) {
+ known = true;
+ break;
+ }
+ }
+ if (known && it.key() != QLatin1String("Other"))
+ matched.insert(it.key(), it.value());
+ else if (it.key() != QLatin1String("Other"))
+ other += it.value();
+ }
+ matched.insert(QStringLiteral("Other"), other);
+ sector_weights = matched;
+ }
// Compute weighted portfolio sensitivities
double w_rate = 0, w_growth = 0, w_infl = 0, w_usd = 0, w_oil = 0;
diff --git a/fincept-qt/src/screens/portfolio/views/PlanningView.cpp b/fincept-qt/src/screens/portfolio/views/PlanningView.cpp
index a59d55fb4..9035fa77e 100644
--- a/fincept-qt/src/screens/portfolio/views/PlanningView.cpp
+++ b/fincept-qt/src/screens/portfolio/views/PlanningView.cpp
@@ -15,6 +15,7 @@
#include <QJsonDocument>
#include <QJsonObject>
#include <QLineEdit>
+#include <QMessageBox>
#include <QTabBar>
#include <QTableWidget>
#include <QTableWidgetItem>
@@ -702,7 +703,9 @@ void PlanningView::recalculate_goals() {
const char* pc = mc.success_prob >= 0.75 ? ui::colors::POSITIVE
: mc.success_prob >= 0.5 ? ui::colors::WARNING
: ui::colors::NEGATIVE;
- goal_mc_label_->setText(tr("Monte Carlo: <b><span style='color:%1'>%2%% chance</span></b> of reaching "
+ // NOTE: QString::arg() has no "%%" escape (that is printf/asprintf).
+ // "%2%%" rendered a literal double percent sign — use "%2%".
+ goal_mc_label_->setText(tr("Monte Carlo: <b><span style='color:%1'>%2% chance</span></b> of reaching "
"%3 %4 — likely %3 %5 – %3 %6.")
.arg(pc)
.arg(QString::number(mc.success_prob * 100, 'f', 0))
@@ -1027,9 +1030,17 @@ void PlanningView::remove_selected_goal() {
const int row = goals_list_->currentRow();
if (row < 0 || row >= goals_.size())
return;
+ // Goals are persisted immediately and there is no undo — confirm first.
+ const QString name = goals_[row].name.isEmpty() ? tr("(unnamed)") : goals_[row].name;
+ const auto answer =
+ QMessageBox::question(this, tr("Remove Goal"), tr("Remove the goal \"%1\"? This cannot be undone.").arg(name),
+ QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
+ if (answer != QMessageBox::Yes)
+ return;
goals_.removeAt(row);
save_goals();
refresh_goals_list();
+ recalculate_goals();
}
void PlanningView::changeEvent(QEvent* event) {
@@ -1175,7 +1186,15 @@ void PlanningView::recalculate() {
.arg(QString::number(gap, 'f', 0)));
status_label_->setStyleSheet(QString("color:%1; font-size:12px; padding:12px;").arg(ui::colors::POSITIVE()));
} else {
- double needed_monthly = (-gap) / ((std::pow(1.0 + monthly_rate, months) - 1.0) / monthly_rate);
+ // Annuity factor. Guard both degenerate inputs: a zero real return
+ // (expected return == inflation, a perfectly plausible entry) made the
+ // divisor 0/0 and printed "nan"; a zero horizon (retire age ==
+ // current age) made it 0 as well.
+ const double annuity_factor = (months <= 0) ? 0.0
+ : (std::abs(monthly_rate) > 1e-9)
+ ? ((std::pow(1.0 + monthly_rate, months) - 1.0) / monthly_rate)
+ : static_cast<double>(months);
+ const double needed_monthly = annuity_factor > 1e-9 ? (-gap) / annuity_factor : 0.0;
status_label_->setText(tr("\u26A0 Shortfall of %1 %2. Consider increasing monthly savings "
"by %1 %3 to close the gap.")
.arg(currency_)
@@ -1194,7 +1213,7 @@ void PlanningView::recalculate() {
: mc.success_prob >= 0.5 ? ui::colors::WARNING
: ui::colors::NEGATIVE;
retire_mc_label_->setText(
- tr("Monte Carlo (2000 runs, %1% vol): <b><span style='color:%2'>%3%% chance</span></b> "
+ tr("Monte Carlo (2000 runs, %1% vol): <b><span style='color:%2'>%3% chance</span></b> "
"of reaching your target. Likely range %4 %5 \u2013 %6 %7 (median %4 %8).")
.arg(QString::number(vol * 100, 'f', 0))
.arg(pc)
@@ -1215,8 +1234,8 @@ void PlanningView::recalculate() {
const double shocked = projected * (1.0 - dd_pct / 100.0);
const double shocked_funded = (target > 1e-6) ? (shocked / target * 100.0) : 0.0;
retire_stress_label_->setText(
- tr("Stress: a %1%% drawdown (your historical max) near retirement would cut the projection to "
- "%2 %3 \u2014 %4%% of target.")
+ tr("Stress: a %1% drawdown (your historical max) near retirement would cut the projection to "
+ "%2 %3 \u2014 %4% of target.")
.arg(QString::number(dd_pct, 'f', 0))
.arg(currency_)
.arg(QString::number(shocked, 'f', 0))
diff --git a/fincept-qt/src/screens/portfolio/views/PortfolioOptimizationView.cpp b/fincept-qt/src/screens/portfolio/views/PortfolioOptimizationView.cpp
index ae4697f43..b0fb3f494 100644
--- a/fincept-qt/src/screens/portfolio/views/PortfolioOptimizationView.cpp
+++ b/fincept-qt/src/screens/portfolio/views/PortfolioOptimizationView.cpp
@@ -735,7 +735,7 @@ void PortfolioOptimizationView::run_optimization() {
const double ret = root["expected_annual_return"].toDouble();
const double vol = root["annual_volatility"].toDouble();
const double sharpe = root["sharpe_ratio"].toDouble();
- self->status_label_->setText(QString("Done — %1 | Exp. Return: %2% Vol: %3% Sharpe: %4 (cached)")
+ self->status_label_->setText(tr("Done — %1 | Exp. Return: %2% Vol: %3% Sharpe: %4 (cached)")
.arg(self->method_cb_->currentText())
.arg(ret * 100.0, 0, 'f', 1)
.arg(vol * 100.0, 0, 'f', 1)
@@ -795,7 +795,7 @@ void PortfolioOptimizationView::run_optimization() {
self->run_btn_->setEnabled(true);
if (!r.success) {
- self->status_label_->setText(QString("Optimization: %1").arg(r.error));
+ self->status_label_->setText(tr("Optimization: %1").arg(r.error));
self->status_label_->setStyleSheet(
QString("color:%1; font-size:10px;").arg(ui::colors::NEGATIVE()));
return;
@@ -808,7 +808,7 @@ void PortfolioOptimizationView::run_optimization() {
const double sharpe = root["sharpe_ratio"].toDouble();
// ── Status label ──────────────────────────────────────────
- self->status_label_->setText(QString("Done — %1 | Exp. Return: %2% Vol: %3% Sharpe: %4")
+ self->status_label_->setText(tr("Done — %1 | Exp. Return: %2% Vol: %3% Sharpe: %4")
.arg(self->method_cb_->currentText())
.arg(ret * 100.0, 0, 'f', 1)
.arg(vol * 100.0, 0, 'f', 1)
@@ -925,8 +925,12 @@ void PortfolioOptimizationView::update_frontier(const QJsonArray& pts) {
auto* chart = frontier_chart_->chart();
chart->removeAllSeries();
const auto old_axes = chart->axes();
- for (auto* ax : old_axes)
+ for (auto* ax : old_axes) {
+ // removeAxis() only detaches — without the delete every re-run leaked
+ // both axes.
chart->removeAxis(ax);
+ delete ax;
+ }
// Frontier line
auto* frontier_series = new QLineSeries;
diff --git a/fincept-qt/src/screens/portfolio/views/ReportsView.cpp b/fincept-qt/src/screens/portfolio/views/ReportsView.cpp
index 70c9ce174..f39f815f7 100644
--- a/fincept-qt/src/screens/portfolio/views/ReportsView.cpp
+++ b/fincept-qt/src/screens/portfolio/views/ReportsView.cpp
@@ -16,6 +16,34 @@
namespace fincept::screens {
+namespace {
+
+/// Recursively empties a layout, destroying the widgets it owns.
+///
+/// `delete panel->layout()` alone does NOT destroy child widgets — they stay
+/// parented to the panel, keep their last geometry and keep painting, so every
+/// rebuild stacked another full set of cards + tables on top of the previous
+/// one (a visible artefact and an unbounded leak). Always drain the layout
+/// first.
+void clear_layout(QLayout* layout) {
+ if (!layout)
+ return;
+ QLayoutItem* item = nullptr;
+ while ((item = layout->takeAt(0)) != nullptr) {
+ if (auto* w = item->widget()) {
+ w->hide();
+ w->deleteLater();
+ } else if (auto* child = item->layout()) {
+ clear_layout(child);
+ }
+ // `item` IS the nested layout when item->layout() is non-null, so a
+ // single delete covers both cases — never delete both.
+ delete item;
+ }
+}
+
+} // namespace
+
ReportsView::ReportsView(QWidget* parent) : QWidget(parent) {
build_ui();
}
@@ -155,8 +183,10 @@ void ReportsView::retranslateUi() {
}
void ReportsView::update_summary() {
- if (summary_panel_->layout())
- delete summary_panel_->layout();
+ if (auto* old = summary_panel_->layout()) {
+ clear_layout(old);
+ delete old;
+ }
auto* layout = new QVBoxLayout(summary_panel_);
layout->setContentsMargins(16, 12, 16, 12);
diff --git a/fincept-qt/src/screens/portfolio/views/RiskManagementView.cpp b/fincept-qt/src/screens/portfolio/views/RiskManagementView.cpp
index 6645e5586..0e9e0a703 100644
--- a/fincept-qt/src/screens/portfolio/views/RiskManagementView.cpp
+++ b/fincept-qt/src/screens/portfolio/views/RiskManagementView.cpp
@@ -16,6 +16,33 @@
namespace fincept::screens {
+namespace {
+
+/// Recursively empties a layout, destroying the widgets it owns.
+///
+/// `delete panel->layout()` alone does NOT destroy child widgets — they stay
+/// parented to the panel, keep their last geometry and keep painting, so every
+/// rebuild stacked another full set of metric cards on top of the previous one
+/// (a visible artefact and an unbounded leak). Always drain the layout first.
+void clear_layout(QLayout* layout) {
+ if (!layout)
+ return;
+ QLayoutItem* item = nullptr;
+ while ((item = layout->takeAt(0)) != nullptr) {
+ if (auto* w = item->widget()) {
+ w->hide();
+ w->deleteLater();
+ } else if (auto* child = item->layout()) {
+ clear_layout(child);
+ }
+ // `item` IS the nested layout when item->layout() is non-null, so a
+ // single delete covers both cases — never delete both.
+ delete item;
+ }
+}
+
+} // namespace
+
// Pre-defined stress test scenarios
struct StressScenario {
const char* name;
@@ -88,7 +115,7 @@ void RiskManagementView::build_ui() {
stress_table_ = new QTableWidget;
stress_table_->setColumnCount(5);
stress_table_->setHorizontalHeaderLabels(
- {tr("SCENARIO"), tr("DESCRIPTION"), tr("EQUITY SHOCK"), tr("PORTFOLIO IMPACT"), tr("LOSS")});
+ {tr("SCENARIO"), tr("DESCRIPTION"), tr("EQUITY SHOCK"), tr("PORTFOLIO IMPACT"), tr("P&L IMPACT")});
stress_table_->setSelectionMode(QAbstractItemView::NoSelection);
stress_table_->setEditTriggers(QAbstractItemView::NoEditTriggers);
stress_table_->setShowGrid(false);
@@ -174,7 +201,7 @@ void RiskManagementView::retranslateUi() {
if (stress_table_)
stress_table_->setHorizontalHeaderLabels(
- {tr("SCENARIO"), tr("DESCRIPTION"), tr("EQUITY SHOCK"), tr("PORTFOLIO IMPACT"), tr("LOSS")});
+ {tr("SCENARIO"), tr("DESCRIPTION"), tr("EQUITY SHOCK"), tr("PORTFOLIO IMPACT"), tr("P&L IMPACT")});
if (contrib_table_)
contrib_table_->setHorizontalHeaderLabels(
{tr("SYMBOL"), tr("WEIGHT"), tr("VOL PROXY"), tr("RISK CONTRIB"), tr("VAR CONTRIB"), tr("CONCENTRATION")});
@@ -193,8 +220,10 @@ void RiskManagementView::set_metrics(const portfolio::ComputedMetrics& metrics)
}
void RiskManagementView::update_overview() {
- if (overview_panel_->layout())
- delete overview_panel_->layout();
+ if (auto* old = overview_panel_->layout()) {
+ clear_layout(old);
+ delete old;
+ }
auto* layout = new QVBoxLayout(overview_panel_);
layout->setContentsMargins(16, 12, 16, 12);
@@ -278,8 +307,11 @@ void RiskManagementView::update_overview() {
add_card(0, 0, tr("PORTFOLIO VALUE"), QString("%1 %2").arg(currency_, fmt(total_mv)), ui::colors::WARNING,
tr("Total market value"));
+ // Be honest about which of the two sources produced the number — the card
+ // previously always claimed "day-change proxy" even when the real 30-day
+ // realized volatility from ComputedMetrics was used.
add_card(0, 1, tr("ANNUALIZED VOLATILITY"), QString("%1%").arg(fmt(ann_vol, 1)), ui::colors::AMBER,
- tr("Based on day-change proxy"));
+ metrics_.volatility.has_value() ? tr("30-day realized") : tr("Based on day-change proxy"));
add_card(0, 2, tr("VALUE AT RISK (95%)"), QString("%1 %2").arg(currency_, fmt(var95)), ui::colors::NEGATIVE,
tr("1-day parametric"));
add_card(0, 3, tr("CONDITIONAL VaR"), QString("%1 %2").arg(currency_, fmt(cvar95)), ui::colors::NEGATIVE,
@@ -361,7 +393,10 @@ void RiskManagementView::update_stress_test() {
impact_pct = equity_impact + other_impact;
}
- double loss = total_mv * std::abs(impact_pct) / 100.0;
+ // Signed currency delta. The column used to hard-code a leading "-"
+ // even for scenarios the portfolio profits from (e.g. Inflation Surge
+ // on a commodity-heavy book), reporting a gain as a loss.
+ const double delta = total_mv * impact_pct / 100.0;
set_cell(0, tr(s.name), ui::colors::TEXT_PRIMARY);
set_cell(1, tr(s.description), ui::colors::TEXT_SECONDARY);
@@ -369,8 +404,12 @@ void RiskManagementView::update_stress_test() {
s.equity_shock < 0 ? ui::colors::NEGATIVE : ui::colors::POSITIVE, Qt::AlignRight | Qt::AlignVCenter);
set_cell(3, QString("%1%2%").arg(impact_pct < 0 ? "" : "+").arg(QString::number(impact_pct, 'f', 1)),
impact_pct < 0 ? ui::colors::NEGATIVE : ui::colors::POSITIVE, Qt::AlignRight | Qt::AlignVCenter);
- set_cell(4, QString("-%1 %2").arg(currency_, QString::number(loss, 'f', 0)), ui::colors::NEGATIVE,
- Qt::AlignRight | Qt::AlignVCenter);
+ set_cell(4,
+ QString("%1%2 %3")
+ .arg(delta < 0 ? "-" : "+")
+ .arg(currency_)
+ .arg(QString::number(std::abs(delta), 'f', 0)),
+ delta < 0 ? ui::colors::NEGATIVE : ui::colors::POSITIVE, Qt::AlignRight | Qt::AlignVCenter);
}
}
diff --git a/fincept-qt/src/screens/profile/ProfileScreen.cpp b/fincept-qt/src/screens/profile/ProfileScreen.cpp
index 16cdc681f..74e3facb0 100644
--- a/fincept-qt/src/screens/profile/ProfileScreen.cpp
+++ b/fincept-qt/src/screens/profile/ProfileScreen.cpp
@@ -16,6 +16,7 @@
#include <QHeaderView>
#include <QJsonArray>
#include <QMessageBox>
+#include <QPointer>
#include <QScrollArea>
#include <QTimer>
@@ -421,7 +422,22 @@ QWidget* ProfileScreen::build_security() {
sb->setText(api_key_visible_ ? tr("HIDE") : tr("SHOW"));
sec_api_key_->setText(api_key_visible_ ? auth::AuthManager::instance().session().api_key
: QString(20, QChar(0x2022)));
+ // Auto re-mask. A revealed key otherwise stays on screen for the rest
+ // of the session — through screen shares, shoulder-surfing, and the
+ // terminal's own auto-lock, which does not repaint this panel.
+ if (api_key_visible_) {
+ QPointer<ProfileScreen> self = this;
+ QTimer::singleShot(30000, sb, [self, sb]() {
+ if (!self || !self->api_key_visible_)
+ return;
+ self->api_key_visible_ = false;
+ sb->setText(tr("SHOW"));
+ if (self->sec_api_key_)
+ self->sec_api_key_->setText(QString(20, QChar(0x2022)));
+ });
+ }
});
+ sb->setAccessibleName(tr("Show or hide the API key"));
krl->addWidget(sb);
auto* cb = new QPushButton(tr("COPY"));
cb->setFixedHeight(22);
@@ -432,12 +448,25 @@ QWidget* ProfileScreen::build_security() {
ui::colors::TEXT_PRIMARY()));
connect(cb, &QPushButton::clicked, this, [cb]() {
auto key = auth::AuthManager::instance().session().api_key;
- if (!key.isEmpty()) {
- QApplication::clipboard()->setText(key);
- cb->setText(tr("COPIED"));
- QTimer::singleShot(1500, cb, [cb]() { cb->setText(tr("COPY")); });
- }
+ if (key.isEmpty())
+ return;
+ QApplication::clipboard()->setText(key);
+ cb->setText(tr("COPIED"));
+ QTimer::singleShot(1500, cb, [cb]() { cb->setText(tr("CLEARS 60s")); });
+ // The API key is a bearer credential. Leaving it on the system
+ // clipboard indefinitely puts it in Windows clipboard history and in
+ // reach of every other process on the machine, so drop it once the
+ // user has had time to paste it. Only clear if the clipboard still
+ // holds exactly this key — never stomp on something the user copied
+ // afterwards.
+ QTimer::singleShot(60000, cb, [cb, key]() {
+ auto* clip = QApplication::clipboard();
+ if (clip && clip->text() == key)
+ clip->clear();
+ cb->setText(tr("COPY"));
+ });
});
+ cb->setAccessibleName(tr("Copy the API key to the clipboard"));
krl->addWidget(cb);
auto* rg = new QPushButton(tr("REGENERATE"));
rg->setFixedHeight(22);
@@ -796,6 +825,11 @@ void ProfileScreen::show_edit_profile_dialog() {
data["phone"] = ph->text().trimmed();
if (!co->text().trimmed().isEmpty())
data["country"] = co->text().trimmed();
+ if (data.isEmpty()) {
+ QMessageBox::information(dlg_ptr ? static_cast<QWidget*>(dlg_ptr) : nullptr, tr("Edit Profile"),
+ tr("Nothing to save — change at least one field."));
+ return;
+ }
auth::UserApi::instance().update_user_profile(data, [self, dlg_ptr](auth::ApiResponse r) {
if (!self)
return;
@@ -803,7 +837,15 @@ void ProfileScreen::show_edit_profile_dialog() {
auth::AuthManager::instance().refresh_user_data();
if (dlg_ptr)
dlg_ptr->accept();
+ return;
}
+ // The failure branch was empty: a rejected update (duplicate
+ // username, invalid phone) left the dialog sitting there as if
+ // the click had never happened.
+ LOG_WARN("Profile", "Profile update failed: " + r.error);
+ QMessageBox::warning(dlg_ptr ? static_cast<QWidget*>(dlg_ptr) : static_cast<QWidget*>(self),
+ tr("Update Failed"),
+ r.error.isEmpty() ? tr("Could not update your profile. Please try again.") : r.error);
});
});
brl->addWidget(sv);
@@ -819,16 +861,35 @@ void ProfileScreen::show_logout_confirm() {
}
void ProfileScreen::show_regen_confirm() {
- if (QMessageBox::warning(this, tr("Regenerate API Key"), tr("Your current API key will be invalidated. Continue?"),
- QMessageBox::Yes | QMessageBox::No, QMessageBox::No) == QMessageBox::Yes) {
- auth::UserApi::instance().regenerate_api_key([this](auth::ApiResponse r) {
- if (r.success) {
- auth::AuthManager::instance().refresh_user_data();
- api_key_visible_ = false;
- sec_api_key_->setText(QString(20, QChar(0x2022)));
- }
- });
- }
+ if (QMessageBox::warning(this, tr("Regenerate API Key"),
+ tr("Your current API key will be invalidated immediately. Anything using it — scripts, "
+ "integrations, other machines — stops working until you paste the new key.\n\n"
+ "Continue?"),
+ QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes)
+ return;
+
+ QPointer<ProfileScreen> self = this;
+ auth::UserApi::instance().regenerate_api_key([self](auth::ApiResponse r) {
+ // Guarded: regeneration is a network round trip and the screen can be
+ // rebuilt (language change) or destroyed while it is in flight.
+ if (!self)
+ return;
+ if (r.success) {
+ auth::AuthManager::instance().refresh_user_data();
+ self->api_key_visible_ = false;
+ if (self->sec_api_key_)
+ self->sec_api_key_->setText(QString(20, QChar(0x2022)));
+ LOG_INFO("Profile", "API key regenerated");
+ return;
+ }
+ // Previously a silent no-op — the user could not tell whether their
+ // key had been rotated or not.
+ LOG_ERROR("Profile", "API key regeneration failed: " + r.error);
+ QMessageBox::warning(self, tr("Regeneration Failed"),
+ r.error.isEmpty() ? tr("Could not regenerate your API key. Your existing key is "
+ "still valid.")
+ : r.error);
+ });
}
void ProfileScreen::show_delete_account_dialog() {
diff --git a/fincept-qt/src/screens/quantlib/QuantLibScreen.cpp b/fincept-qt/src/screens/quantlib/QuantLibScreen.cpp
index e1737aa61..adcc6d8b5 100644
--- a/fincept-qt/src/screens/quantlib/QuantLibScreen.cpp
+++ b/fincept-qt/src/screens/quantlib/QuantLibScreen.cpp
@@ -16,11 +16,17 @@
#include <QHeaderView>
#include <QJsonArray>
#include <QJsonDocument>
+#include <QJsonParseError>
+#include <QKeySequence>
#include <QPointer>
#include <QScrollArea>
+#include <QShortcut>
+#include <QSignalBlocker>
#include <QSplitter>
#include <QVBoxLayout>
+#include <algorithm>
+
namespace {
using namespace fincept::ui;
@@ -102,10 +108,22 @@ namespace fincept::screens {
using namespace fincept::ui;
+// MODULE_ENDPOINTS catalog + endpoint_examples() live in
+// QuantLibScreen_Data.cpp. Forward-declared here (not just above
+// populate_panels) because build_modules() derives its per-module endpoint
+// counts from the catalog rather than hard-coding them.
+const QHash<QString, QStringList>& module_endpoints();
+
// ── Module definitions ──────────────────────────────────────────────────────
+//
+// The third field is a *fallback* endpoint count. The real count is taken from
+// module_endpoints() in build_modules() — the hard-coded numbers had drifted
+// away from the catalog (e.g. "analysis" advertised 122 endpoints while the
+// catalog lists 46), so the sidebar was quoting figures the screen could not
+// deliver.
static QList<QuantModule> build_modules() {
- return {
+ QList<QuantModule> mods = {
{"core",
"Core",
51,
@@ -136,6 +154,47 @@ static QList<QuantModule> build_modules() {
{"stochastic", "Stochastic", 36, {"Processes", "Exact", "Simulation", "Sampling", "Theory"}},
{"volatility", "Volatility", 14, {"Surface", "SABR", "Local Vol"}},
};
+
+ // Replace the declared counts with what the catalog actually exposes.
+ const auto& catalog = module_endpoints();
+ for (auto& m : mods) {
+ const auto it = catalog.find(m.id);
+ m.endpoint_count = (it != catalog.end()) ? int(it.value().size()) : 0;
+ }
+ return mods;
+}
+
+// Map a sidebar sub-panel name onto the path segment that identifies it, so
+// clicking a panel narrows the endpoint list instead of only relabelling the
+// header. Panels with no entry (and any panel whose filter matches nothing)
+// fall back to showing every endpoint in the module — never an empty combo.
+static QStringList panel_path_tokens(const QString& panel) {
+ static const QHash<QString, QStringList> kOverrides = {
+ {"Operations", {"/ops/"}},
+ {"Black-Scholes", {"/bs/"}},
+ {"Black76", {"/black76"}},
+ {"Bachelier", {"/bachelier"}},
+ {"Build & Query", {"/build", "/query", "/discount", "/forward", "/zero"}},
+ {"NS/NSS Fitting", {"/ns", "/nss", "/fit"}},
+ {"Day Count", {"/day-count", "/daycount"}},
+ {"Short Rate", {"/vasicek", "/cir", "/short-rate"}},
+ {"Hull-White", {"/hull-white", "/hw"}},
+ {"Jump Diffusion", {"/jump", "/merton", "/kou"}},
+ {"Dupire/SVI", {"/dupire", "/svi"}},
+ {"Risk Metrics", {"/var", "/cvar", "/risk", "/drawdown"}},
+ {"Local Vol", {"/local-vol", "/localvol", "/dupire"}},
+ {"Time Series", {"/timeseries", "/time-series", "/ts/", "/arima", "/garch"}},
+ };
+ const auto ov = kOverrides.constFind(panel);
+ if (ov != kOverrides.constEnd())
+ return ov.value();
+
+ // Default: the panel name lower-cased with spaces → hyphens, e.g.
+ // "Risk Metrics" → "/risk-metrics/", "Distributions" → "/distributions/".
+ QString token = panel.toLower();
+ token.replace(' ', '-');
+ token.replace('/', '-');
+ return {"/" + token + "/", "/" + token};
}
// ── Constructor ─────────────────────────────────────────────────────────────
@@ -147,7 +206,12 @@ QuantLibScreen::QuantLibScreen(QWidget* parent) : QWidget(parent) {
setup_ui();
connect(&ThemeManager::instance(), &ThemeManager::theme_changed, this,
[this](const ThemeTokens&) { setStyleSheet(kStyle()); });
- LOG_INFO("QuantLib", "Screen constructed — 18 modules, 590+ endpoints");
+ int total_endpoints = 0;
+ for (const auto& m : modules_)
+ total_endpoints += m.endpoint_count;
+ LOG_INFO("QuantLib", QString("Screen constructed — %1 modules, %2 endpoints")
+ .arg(modules_.size())
+ .arg(total_endpoints));
}
// ── UI Setup ────────────────────────────────────────────────────────────────
@@ -180,8 +244,21 @@ void QuantLibScreen::setup_ui() {
root->addWidget(splitter, 1);
root->addWidget(create_status_bar());
+ // Explicit keyboard path: modules → endpoint → request body → execute.
+ // Done here (not in the create_* helpers) because setTabOrder only holds
+ // once the widgets sit in their final parents.
+ module_tree_->setAccessibleName(tr("QuantLib modules"));
+ setTabOrder(module_tree_, endpoint_combo_);
+ setTabOrder(endpoint_combo_, param_input1_);
+ setTabOrder(param_input1_, exec_btn_);
+ setTabOrder(exec_btn_, result_table_);
+
// Select first module
on_module_changed(0);
+
+ // Populates the data-derived chrome (header module/endpoint counts) that
+ // used to be a hard-coded literal. Must run after the widgets exist.
+ retranslateUi();
}
QWidget* QuantLibScreen::create_header() {
@@ -196,7 +273,9 @@ QWidget* QuantLibScreen::create_header() {
title_col->setSpacing(0);
header_title_ = new QLabel(tr("QUANTLIB SUITE"));
header_title_->setObjectName("qlHeaderTitle");
- header_sub_ = new QLabel(tr("18 MODULES | 590+ QUANTITATIVE ENDPOINTS"));
+ // Derived, not hard-coded: the old "590+" was the sum of the stale
+ // per-module counts and overstated the catalog by ~75 endpoints.
+ header_sub_ = new QLabel;
header_sub_->setObjectName("qlHeaderSub");
title_col->addWidget(header_title_);
title_col->addWidget(header_sub_);
@@ -246,15 +325,21 @@ QWidget* QuantLibScreen::create_sidebar() {
connect(module_tree_, &QTreeWidget::itemClicked, this, [this](QTreeWidgetItem* item) {
if (!item)
return;
- // Check if it's a module (top level) or panel (child)
if (!item->parent()) {
- int idx = item->data(0, Qt::UserRole).toInt();
- on_module_changed(idx);
+ // Module header — clear any sub-panel filter carried over from the
+ // previously selected module.
+ active_panel_.clear();
+ status_panel_->clear();
+ on_module_changed(item->data(0, Qt::UserRole).toInt());
} else {
- // Panel clicked
- int mod_idx = item->parent()->data(0, Qt::UserRole).toInt();
- on_module_changed(mod_idx);
+ const int mod_idx = item->parent()->data(0, Qt::UserRole).toInt();
+ if (mod_idx < 0 || mod_idx >= modules_.size())
+ return;
+ // Set the panel BEFORE on_module_changed() so populate_panels()
+ // applies the filter — previously the panel was only a label and the
+ // endpoint list never narrowed.
active_panel_ = item->data(0, Qt::UserRole + 1).toString();
+ on_module_changed(mod_idx);
status_panel_->setText(active_panel_);
center_title_->setText(modules_[mod_idx].name.toUpper() + " / " + active_panel_.toUpper());
}
@@ -341,21 +426,31 @@ QWidget* QuantLibScreen::create_center_panel() {
helpers->addStretch(1);
ebl->addLayout(helpers);
- // Hide unused inputs
- param_input2_ = new QLineEdit;
- param_input2_->hide();
- param_input3_ = new QLineEdit;
- param_input3_->hide();
- param_input4_ = new QLineEdit;
- param_input4_->hide();
+ // (param_input2_ / 3_ / 4_ removed — they were parentless, hidden, never
+ // added to a layout and never read: three leaked QLineEdits per screen.)
exec_btn_ = new QPushButton(tr("EXECUTE COMPUTATION"));
exec_btn_->setObjectName("qlExecBtn");
exec_btn_->setCursor(Qt::PointingHandCursor);
exec_btn_->setFixedHeight(34);
+ exec_btn_->setToolTip(tr("Send the request body to the selected endpoint (Ctrl+Enter)"));
connect(exec_btn_, &QPushButton::clicked, this, &QuantLibScreen::on_execute);
ebl->addWidget(exec_btn_);
+ // Ctrl+Enter executes from anywhere in the screen — the request body is a
+ // single-line QLineEdit, so Return alone would be ambiguous with editing.
+ auto* exec_sc = new QShortcut(QKeySequence(QStringLiteral("Ctrl+Return")), this);
+ exec_sc->setContext(Qt::WidgetWithChildrenShortcut);
+ connect(exec_sc, &QShortcut::activated, this, &QuantLibScreen::on_execute);
+
+ // Accessibility: none of these controls had names, so a screen reader
+ // announced "tree"/"combo box"/"edit"/"button".
+ // (Tab order is set at the end of setup_ui(), once every widget has been
+ // re-parented into its final place — setTabOrder is order-sensitive.)
+ endpoint_combo_->setAccessibleName(tr("Endpoint"));
+ param_input1_->setAccessibleName(tr("Request body (JSON)"));
+ exec_btn_->setAccessibleName(tr("Execute computation"));
+
epvl->addWidget(ep_body);
vl->addWidget(ep_panel);
@@ -448,14 +543,20 @@ void QuantLibScreen::retranslateUi() {
// intentionally not translated.
if (header_title_)
header_title_->setText(tr("QUANTLIB SUITE"));
- if (header_sub_)
- header_sub_->setText(tr("18 MODULES | 590+ QUANTITATIVE ENDPOINTS"));
+ if (header_sub_) {
+ int total = 0;
+ for (const auto& m : modules_)
+ total += m.endpoint_count;
+ header_sub_->setText(tr("%1 MODULES | %2 QUANTITATIVE ENDPOINTS").arg(modules_.size()).arg(total));
+ }
if (header_badge_)
header_badge_->setText(tr("API POWERED"));
if (sidebar_title_)
sidebar_title_->setText(tr("MODULES"));
+ // endpoint_panel_title_ carries the live "(n of m)" counts — repopulating
+ // rebuilds it in the new language and preserves the current selection.
if (endpoint_panel_title_)
- endpoint_panel_title_->setText(tr("ENDPOINT"));
+ populate_panels(active_module_);
if (json_body_label_)
json_body_label_->setText(tr("REQUEST BODY (JSON)"));
if (results_title_)
@@ -486,82 +587,131 @@ void QuantLibScreen::on_module_changed(int index) {
ScreenStateManager::instance().notify_changed(this);
}
-void QuantLibScreen::on_panel_changed(QListWidgetItem* item) {
- if (!item)
- return;
- active_panel_ = item->text();
- status_panel_->setText(active_panel_);
- ScreenStateManager::instance().notify_changed(this);
-}
-
void QuantLibScreen::on_endpoint_changed(int index) {
if (index < 0)
return;
const QString ep = endpoint_combo_->currentText();
status_endpoint_->setText(ep);
- // Auto-fill example body if user hasn't typed anything
- if (param_input1_->text().trimmed().isEmpty()) {
- const auto& examples = endpoint_examples();
- auto it = examples.find(ep);
- if (it != examples.end())
- param_input1_->setText(it.value());
- else
- param_input1_->clear();
- }
+ // Auto-fill the example body when the field is empty OR still holds an
+ // example we injected ourselves. Previously the body was only filled once,
+ // so switching endpoints left the previous endpoint's payload behind and
+ // the request failed with a confusing schema error.
+ const auto& examples = endpoint_examples();
+ const QString current = param_input1_->text().trimmed();
+ const bool is_stale_example =
+ !current.isEmpty() && std::any_of(examples.cbegin(), examples.cend(),
+ [&current](const QString& ex) { return ex.trimmed() == current; });
+ if (!current.isEmpty() && !is_stale_example)
+ return; // user-authored body — never clobber it
+
+ const auto it = examples.constFind(ep);
+ if (it != examples.constEnd())
+ param_input1_->setText(it.value());
+ else
+ param_input1_->clear();
}
void QuantLibScreen::on_execute() {
if (loading_)
return;
- QString endpoint = endpoint_combo_->currentText();
- if (endpoint.isEmpty())
+ const QString endpoint = endpoint_combo_->currentText();
+ if (endpoint.isEmpty()) {
+ // Used to return silently — the button appeared dead.
+ display_error(tr("Select an endpoint first."));
return;
+ }
// Parse JSON body from input
QJsonObject params;
- QString body_text = param_input1_->text().trimmed();
+ const QString body_text = param_input1_->text().trimmed();
if (!body_text.isEmpty()) {
- auto doc = QJsonDocument::fromJson(body_text.toUtf8());
- if (doc.isObject()) {
- params = doc.object();
- } else {
- result_view_->setPlainText(tr("ERROR: Invalid JSON in request body.\n\n"
+ QJsonParseError perr{};
+ const auto doc = QJsonDocument::fromJson(body_text.toUtf8(), &perr);
+ if (perr.error != QJsonParseError::NoError || !doc.isObject()) {
+ result_view_->setPlainText(tr("ERROR: Invalid JSON in request body — %1 (offset %2)\n\n"
"Expected format: {\"key\": value, ...}\n"
- "Example: {\"spot\": 100, \"strike\": 105, \"risk_free_rate\": 0.05}"));
+ "Example: {\"spot\": 100, \"strike\": 105, \"risk_free_rate\": 0.05}")
+ .arg(perr.errorString())
+ .arg(perr.offset));
result_stack_->setCurrentIndex(0);
+ result_status_->setText(tr("Invalid JSON"));
return;
}
+ params = doc.object();
}
execute_api(endpoint, params);
}
// ── Data ────────────────────────────────────────────────────────────────────
-
-// Real API endpoint paths per module (from api.fincept.in OpenAPI spec)
-
-// MODULE_ENDPOINTS catalog + endpoint_examples() definition live in
-// QuantLibScreen_Data.cpp. module_endpoints() is the free-function accessor
-// used by populate_panels(); endpoint_examples() is a static member.
-// Forward declaration — we're already inside `namespace fincept::screens` (opened
-// at line 100), so no extra namespace wrapping.
-const QHash<QString, QStringList>& module_endpoints();
+//
+// module_endpoints() (the real api.fincept.in endpoint paths) and
+// endpoint_examples() live in QuantLibScreen_Data.cpp; module_endpoints() is
+// forward-declared near build_modules() above.
void QuantLibScreen::populate_panels(int module_index) {
- endpoint_combo_->clear();
-
+ if (module_index < 0 || module_index >= modules_.size())
+ return;
const auto& m = modules_[module_index];
- auto it = module_endpoints().find(m.id);
- if (it != module_endpoints().end()) {
- for (const auto& ep : it.value()) {
- endpoint_combo_->addItem(ep);
+
+ const auto it = module_endpoints().constFind(m.id);
+ const QStringList all = (it != module_endpoints().constEnd()) ? it.value() : QStringList{};
+
+ // Narrow to the active sub-panel when it maps onto a path segment. Falls
+ // back to the full list when the panel has no match, so a filter miss can
+ // never leave the user staring at an empty endpoint combo.
+ QStringList shown = all;
+ bool filtered = false;
+ if (!active_panel_.isEmpty()) {
+ const QStringList tokens = panel_path_tokens(active_panel_);
+ QStringList hits;
+ for (const auto& ep : all) {
+ for (const auto& t : tokens) {
+ if (ep.contains(t, Qt::CaseInsensitive)) {
+ hits << ep;
+ break;
+ }
+ }
}
+ if (!hits.isEmpty()) {
+ shown = hits;
+ filtered = true;
+ }
+ }
+
+ // Rebuild without firing on_endpoint_changed() for every intermediate state,
+ // and keep the user's endpoint selected when it survives the new filter.
+ const QString previous = endpoint_combo_->currentText();
+ {
+ const QSignalBlocker block(endpoint_combo_);
+ endpoint_combo_->clear();
+ endpoint_combo_->addItems(shown);
+ const int keep = previous.isEmpty() ? -1 : endpoint_combo_->findText(previous);
+ if (keep >= 0)
+ endpoint_combo_->setCurrentIndex(keep);
+ }
+
+ if (endpoint_panel_title_) {
+ endpoint_panel_title_->setText(filtered
+ ? tr("ENDPOINT — %1 (%2 of %3)")
+ .arg(active_panel_.toUpper())
+ .arg(shown.size())
+ .arg(all.size())
+ : tr("ENDPOINT (%1)").arg(all.size()));
}
connect(endpoint_combo_, QOverload<int>::of(&QComboBox::currentIndexChanged), this,
&QuantLibScreen::on_endpoint_changed, Qt::UniqueConnection);
+
+ // The signal blocker above suppressed the initial index change, so drive the
+ // first selection explicitly. Previously the status bar showed no endpoint
+ // and no example body was pre-filled until the user touched the combo.
+ if (endpoint_combo_->count() > 0)
+ on_endpoint_changed(endpoint_combo_->currentIndex());
+ else if (status_endpoint_)
+ status_endpoint_->clear();
}
void QuantLibScreen::execute_api(const QString& endpoint, const QJsonObject& params) {
@@ -663,52 +813,48 @@ void QuantLibScreen::display_result(const QJsonObject& result) {
return;
}
- { // flat object → Key/Value table
- // Flat object result (e.g. {"price": 8.02, "delta": 0.45, ...}) → two-column table: Key | Value
- auto obj = result;
- if (!obj.isEmpty()) {
- result_table_->setSortingEnabled(false);
- result_table_->setColumnCount(2);
- result_table_->setHorizontalHeaderLabels({tr("Field"), tr("Value")});
- result_table_->setRowCount(obj.size());
- int r = 0;
- for (auto it = obj.begin(); it != obj.end(); ++it, ++r) {
- auto* key_item = new QTableWidgetItem(it.key());
- key_item->setForeground(QColor(colors::TEXT_SECONDARY()));
- result_table_->setItem(r, 0, key_item);
-
- QString text;
- auto val = it.value();
- if (val.isDouble())
- text = QString::number(val.toDouble(), 'g', 10);
- else if (val.isBool())
- text = val.toBool() ? "true" : "false";
- else if (val.isNull() || val.isUndefined())
- text = "--";
- else if (val.isArray() || val.isObject())
- text = QJsonDocument(val.isArray() ? QJsonDocument(val.toArray()) : QJsonDocument(val.toObject()))
- .toJson(QJsonDocument::Compact);
- else
- text = val.toString();
-
- auto* val_item = new QTableWidgetItem(text);
- val_item->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
- if (val.isDouble())
- val_item->setForeground(QColor(val.toDouble() < 0 ? colors::NEGATIVE() : colors::CYAN()));
- result_table_->setItem(r, 1, val_item);
- }
- result_table_->resizeColumnsToContents();
- result_table_->setSortingEnabled(true);
- result_stack_->setCurrentIndex(1);
- result_status_->setText(tr("%1 fields").arg(obj.size()));
- return;
- }
+ // Flat object result (e.g. {"price": 8.02, "delta": 0.45, ...}) → Field/Value
+ // table. `result` is non-empty here (the early return above covers the empty
+ // case), so the old post-block "raw JSON fallback" was unreachable.
+ result_table_->setSortingEnabled(false);
+ result_table_->setColumnCount(2);
+ result_table_->setHorizontalHeaderLabels({tr("Field"), tr("Value")});
+ result_table_->setRowCount(result.size());
+ int r = 0;
+ for (auto it = result.begin(); it != result.end(); ++it, ++r) {
+ auto* key_item = new QTableWidgetItem(it.key());
+ key_item->setForeground(QColor(colors::TEXT_SECONDARY()));
+ result_table_->setItem(r, 0, key_item);
+
+ QString text;
+ const auto val = it.value();
+ if (val.isDouble())
+ text = QString::number(val.toDouble(), 'g', 10);
+ else if (val.isBool())
+ text = val.toBool() ? QStringLiteral("true") : QStringLiteral("false");
+ else if (val.isNull() || val.isUndefined())
+ text = QStringLiteral("--");
+ else if (val.isArray())
+ text = QString::fromUtf8(QJsonDocument(val.toArray()).toJson(QJsonDocument::Compact));
+ else if (val.isObject())
+ text = QString::fromUtf8(QJsonDocument(val.toObject()).toJson(QJsonDocument::Compact));
+ else
+ text = val.toString();
+
+ auto* val_item = new QTableWidgetItem(text);
+ // Nested payloads are compacted onto one line — expose the full text on
+ // hover so a long path/vector isn't silently elided.
+ if (val.isArray() || val.isObject())
+ val_item->setToolTip(text);
+ val_item->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ if (val.isDouble())
+ val_item->setForeground(QColor(val.toDouble() < 0 ? colors::NEGATIVE() : colors::CYAN()));
+ result_table_->setItem(r, 1, val_item);
}
-
- // Fallback: raw JSON
- result_view_->setPlainText(QJsonDocument(result).toJson(QJsonDocument::Indented));
- result_stack_->setCurrentIndex(0);
- result_status_->setText(tr("OK"));
+ result_table_->resizeColumnsToContents();
+ result_table_->setSortingEnabled(true);
+ result_stack_->setCurrentIndex(1);
+ result_status_->setText(tr("%1 fields").arg(result.size()));
}
void QuantLibScreen::display_error(const QString& error) {
@@ -744,9 +890,10 @@ void QuantLibScreen::restore_state(const QVariantMap& state) {
auto items = module_tree_->findItems(panel, Qt::MatchExactly | Qt::MatchRecursive);
if (!items.isEmpty()) {
module_tree_->setCurrentItem(items.first());
- // on_panel_changed expects QListWidgetItem* — extract text directly
active_panel_ = items.first()->text(0);
status_panel_->setText(active_panel_);
+ // Re-apply the endpoint filter for the restored panel.
+ populate_panels(active_module_);
ScreenStateManager::instance().notify_changed(this);
}
}
diff --git a/fincept-qt/src/screens/quantlib/QuantLibScreen.h b/fincept-qt/src/screens/quantlib/QuantLibScreen.h
index 09fe9582f..0ee23a6bf 100644
--- a/fincept-qt/src/screens/quantlib/QuantLibScreen.h
+++ b/fincept-qt/src/screens/quantlib/QuantLibScreen.h
@@ -7,7 +7,6 @@
#include <QJsonObject>
#include <QLabel>
#include <QLineEdit>
-#include <QListWidget>
#include <QPushButton>
#include <QStackedWidget>
#include <QTableWidget>
@@ -21,14 +20,18 @@ namespace fincept::screens {
struct QuantModule {
QString id;
QString name;
+ /// Number of REST endpoints exposed by this module. Populated from the
+ /// module_endpoints() catalog at construction time -- the literal in
+ /// build_modules() is only a fallback.
int endpoint_count;
QStringList panels; // sub-panel names
};
-/// QuantLib Suite — 18 quantitative analysis modules with 590+ endpoints.
+/// QuantLib Suite -- 18 quantitative analysis modules.
/// Modules: Core, Analysis, Curves, Economics, Instruments, ML, Models,
/// Numerical, Physics, Portfolio, Pricing, Regulatory, Risk, Scheduling,
/// Solver, Statistics, Stochastic, Volatility.
+/// Endpoint counts are derived from the catalog in QuantLibScreen_Data.cpp.
/// All computations via api.fincept.in REST API.
class QuantLibScreen : public QWidget, public IStatefulScreen {
Q_OBJECT
@@ -45,7 +48,6 @@ class QuantLibScreen : public QWidget, public IStatefulScreen {
private slots:
void on_module_changed(int index);
- void on_panel_changed(QListWidgetItem* item);
void on_endpoint_changed(int index);
void on_execute();
@@ -58,6 +60,8 @@ class QuantLibScreen : public QWidget, public IStatefulScreen {
QWidget* create_right_panel();
QWidget* create_status_bar();
+ /// Refill endpoint_combo_ for the active module, restricted to the active
+ /// sub-panel when that panel maps onto a recognisable path segment.
void populate_panels(int module_index);
void execute_api(const QString& endpoint, const QJsonObject& params);
void display_result(const QJsonObject& result);
@@ -91,9 +95,6 @@ class QuantLibScreen : public QWidget, public IStatefulScreen {
QLabel* center_title_ = nullptr;
QComboBox* endpoint_combo_ = nullptr;
QLineEdit* param_input1_ = nullptr;
- QLineEdit* param_input2_ = nullptr;
- QLineEdit* param_input3_ = nullptr;
- QLineEdit* param_input4_ = nullptr;
QPushButton* exec_btn_ = nullptr;
// Right (results)
diff --git a/fincept-qt/src/screens/recovery/CrashRecoveryDialog.cpp b/fincept-qt/src/screens/recovery/CrashRecoveryDialog.cpp
index 9ea04173c..c1868eaa4 100644
--- a/fincept-qt/src/screens/recovery/CrashRecoveryDialog.cpp
+++ b/fincept-qt/src/screens/recovery/CrashRecoveryDialog.cpp
@@ -534,18 +534,30 @@ void CrashRecoveryDialog::on_restore_clicked() {
}
const qint64 id = item->data(Qt::UserRole).toLongLong();
+
+ // Every failure below used to be a silent `return` that only greyed the row
+ // out: clicking RESTORE on a corrupt snapshot looked like a dead button.
+ // Tell the user what happened and why the entry is now disabled.
+ auto reject_snapshot = [this, item](const QString& reason) {
+ item->setFlags(item->flags() & ~Qt::ItemIsEnabled);
+ QMessageBox::warning(this, tr("Cannot restore this session"),
+ tr("%1\n\nThis snapshot has been disabled. Pick another one, or Skip to start "
+ "with a fresh workspace.")
+ .arg(reason));
+ };
+
auto payload_r = ring_->load_payload(id);
if (payload_r.is_err()) {
LOG_ERROR(kRecoveryTag,
QString("load_payload(%1) failed: %2").arg(id).arg(QString::fromStdString(payload_r.error())));
- item->setFlags(item->flags() & ~Qt::ItemIsEnabled);
+ reject_snapshot(tr("The snapshot could not be read: %1").arg(QString::fromStdString(payload_r.error())));
return;
}
const QByteArray payload = payload_r.value();
if (payload.isEmpty()) {
LOG_WARN(kRecoveryTag, QString("snapshot %1 has empty payload — skipping").arg(id));
- item->setFlags(item->flags() & ~Qt::ItemIsEnabled);
+ reject_snapshot(tr("The snapshot is empty."));
return;
}
@@ -553,14 +565,14 @@ void CrashRecoveryDialog::on_restore_clicked() {
const auto doc = QJsonDocument::fromJson(payload, &err);
if (err.error != QJsonParseError::NoError || !doc.isObject()) {
LOG_ERROR(kRecoveryTag, QString("snapshot %1 JSON parse error: %2").arg(id).arg(err.errorString()));
- item->setFlags(item->flags() & ~Qt::ItemIsEnabled);
+ reject_snapshot(tr("The snapshot is corrupt: %1").arg(err.errorString()));
return;
}
layout::Workspace ws = layout::Workspace::from_json(doc.object());
if (ws.frames.isEmpty()) {
LOG_WARN(kRecoveryTag, QString("snapshot %1 decoded with zero frames — nothing to restore").arg(id));
- item->setFlags(item->flags() & ~Qt::ItemIsEnabled);
+ reject_snapshot(tr("The snapshot contains no windows to restore."));
return;
}
@@ -572,7 +584,15 @@ void CrashRecoveryDialog::on_restore_clicked() {
const int applied = layout::WorkspaceShell::apply(ws);
LOG_INFO(kRecoveryTag, QString("WorkspaceShell::apply returned %1/%2 frames").arg(applied).arg(ws.frames.size()));
- restored_ = (applied > 0);
+ if (applied == 0) {
+ // apply() reporting zero frames means nothing was restored; closing the
+ // dialog with was_restored() == false silently drops the user into an
+ // empty workspace with no explanation.
+ reject_snapshot(tr("The workspace could not be applied — no windows were restored."));
+ return;
+ }
+
+ restored_ = true;
accept();
}
diff --git a/fincept-qt/src/screens/relationship_map/RelationshipGraphScene.cpp b/fincept-qt/src/screens/relationship_map/RelationshipGraphScene.cpp
index 7b4fb069c..098599f51 100644
--- a/fincept-qt/src/screens/relationship_map/RelationshipGraphScene.cpp
+++ b/fincept-qt/src/screens/relationship_map/RelationshipGraphScene.cpp
@@ -433,8 +433,8 @@ void RelationshipGraphScene::build_graph(const RelationshipData& data, const Fil
push_right(tr("Holders (%1/%2)").arg(lv.size()).arg(data.institutional_holders.size()), cInst, std::move(lv));
}
- // MUTUAL FUNDS → right
- if (filters.show_institutional && !data.mutualfund_holders.isEmpty()) {
+ // MUTUAL FUNDS → right (own filter flag; used to share show_institutional)
+ if (filters.show_mutual_funds && !data.mutualfund_holders.isEmpty()) {
QVector<LeafInfo> lv;
for (const auto& h : data.mutualfund_holders) {
if (lv.size() >= 8)
diff --git a/fincept-qt/src/screens/relationship_map/RelationshipMapScreen.cpp b/fincept-qt/src/screens/relationship_map/RelationshipMapScreen.cpp
index 8a403df5c..e2210b942 100644
--- a/fincept-qt/src/screens/relationship_map/RelationshipMapScreen.cpp
+++ b/fincept-qt/src/screens/relationship_map/RelationshipMapScreen.cpp
@@ -109,6 +109,8 @@ void RelationshipMapScreen::build_ui() {
// Search with autocomplete
search_input_ = new QLineEdit;
search_input_->setPlaceholderText(tr("Search assets (AAPL, Tesla, RELIANCE...)"));
+ search_input_->setAccessibleName(tr("Search assets"));
+ search_input_->setClearButtonEnabled(true);
search_input_->setFixedWidth(320);
search_input_->setStyleSheet(
QString("QLineEdit { background: %1; color: %2; border: 1px solid %3; "
@@ -123,15 +125,29 @@ void RelationshipMapScreen::build_ui() {
// Autocomplete dropdown — child widget, no window flags that steal focus
search_dropdown_ = new QListWidget(this);
+ search_dropdown_->setAccessibleName(tr("Asset suggestions"));
search_dropdown_->setFocusPolicy(Qt::NoFocus);
search_dropdown_->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
search_dropdown_->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
+ // One stylesheet for the dropdown AND its per-row item widgets. Item
+ // widgets are descendants of the list, so object-name rules here replace
+ // four setStyleSheet() calls per row (i.e. ~40 full CSS reparses on every
+ // debounced keystroke of the search box).
search_dropdown_->setStyleSheet(
QString("QListWidget { background: %1; border: 1px solid %2; font-size: 11px; %3 }"
"QListWidget::item { padding: 4px 8px; border-bottom: 1px solid %4; }"
"QListWidget::item:selected { background: %5; }"
- "QListWidget::item:hover { background: %5; }")
- .arg(colors::BG_SURFACE(), colors::AMBER_DIM(), MF(), colors::BORDER_DIM(), colors::BG_RAISED()));
+ "QListWidget::item:hover { background: %5; }"
+ "QWidget#relmapRow { background: transparent; }"
+ "QLabel { background: transparent; %3 }"
+ "QLabel#relmapSym { color: %6; font-size: 12px; font-weight: 700; }"
+ "QLabel#relmapName { color: %7; font-size: 11px; }"
+ "QLabel#relmapExch { color: %8; font-size: 9px; }"
+ "QLabel#relmapType { color: %6; font-size: 8px; font-weight: 700;"
+ " background: %5; padding: 1px 4px; border-radius: 2px; }"
+ "QLabel#relmapEmpty { color: %8; font-size: 11px; }")
+ .arg(colors::BG_SURFACE(), colors::AMBER_DIM(), MF(), colors::BORDER_DIM(), colors::BG_RAISED(),
+ colors::AMBER(), colors::TEXT_SECONDARY(), colors::TEXT_TERTIARY()));
search_dropdown_->setFixedWidth(420);
search_dropdown_->setMaximumHeight(320);
search_dropdown_->hide();
@@ -357,7 +373,9 @@ QWidget* RelationshipMapScreen::build_filter_panel() {
make_check(tr("Peers"), filters_.show_peers, NodeCategory::Peer);
make_check(tr("Institutional"), filters_.show_institutional, NodeCategory::Institutional);
- make_check(tr("Mutual Funds"), filters_.show_institutional, NodeCategory::MutualFund);
+ // Was bound to show_institutional — the same flag as the row above, so the
+ // two checkboxes fought each other and neither reflected the graph.
+ make_check(tr("Mutual Funds"), filters_.show_mutual_funds, NodeCategory::MutualFund);
make_check(tr("Insiders"), filters_.show_insiders, NodeCategory::Insider);
make_check(tr("Officers"), filters_.show_officers, NodeCategory::Officer);
make_check(tr("Analysts"), filters_.show_analysts, NodeCategory::Analyst);
@@ -563,12 +581,11 @@ void RelationshipMapScreen::on_asset_results(const QList<fincept::services::Mark
auto* item = new QListWidgetItem(search_dropdown_);
item->setFlags(item->flags() & ~Qt::ItemIsSelectable);
auto* row = new QWidget;
- row->setStyleSheet("background:transparent;");
+ row->setObjectName(QStringLiteral("relmapRow"));
auto* rl = new QHBoxLayout(row);
rl->setContentsMargins(8, 4, 8, 4);
auto* lbl = new QLabel(tr("No results found"));
- lbl->setStyleSheet(
- QString("color:%1;font-size:11px;%2;background:transparent;").arg(ui::colors::TEXT_TERTIARY.get(), MF()));
+ lbl->setObjectName(QStringLiteral("relmapEmpty"));
rl->addWidget(lbl);
item->setSizeHint(QSize(0, 28));
search_dropdown_->setItemWidget(item, row);
@@ -591,38 +608,40 @@ void RelationshipMapScreen::on_asset_results(const QList<fincept::services::Mark
auto* item = new QListWidgetItem(search_dropdown_);
item->setData(Qt::UserRole, yf_symbol);
+ // Styling comes from the dropdown-level stylesheet via object names —
+ // no per-label setStyleSheet in this loop.
auto* row = new QWidget;
- row->setStyleSheet("background:transparent;");
+ row->setObjectName(QStringLiteral("relmapRow"));
auto* hl = new QHBoxLayout(row);
hl->setContentsMargins(8, 3, 8, 3);
hl->setSpacing(8);
auto* sym_lbl = new QLabel(yf_symbol);
- sym_lbl->setStyleSheet(QString("color:%1;font-size:12px;font-weight:700;%2;background:transparent;")
- .arg(ui::colors::AMBER.get(), MF()));
+ sym_lbl->setObjectName(QStringLiteral("relmapSym"));
sym_lbl->setFixedWidth(100);
hl->addWidget(sym_lbl);
auto* name_lbl = new QLabel(name);
- name_lbl->setStyleSheet(
- QString("color:%1;font-size:11px;%2;background:transparent;").arg(ui::colors::TEXT_SECONDARY.get(), MF()));
+ name_lbl->setObjectName(QStringLiteral("relmapName"));
+ name_lbl->setTextFormat(Qt::PlainText); // provider-supplied text
name_lbl->setMaximumWidth(180);
hl->addWidget(name_lbl, 1);
if (!exchange.isEmpty()) {
auto* exch_lbl = new QLabel(exchange);
- exch_lbl->setStyleSheet(QString("color:%1;font-size:9px;%2;background:transparent;")
- .arg(ui::colors::TEXT_TERTIARY.get(), MF()));
+ exch_lbl->setObjectName(QStringLiteral("relmapExch"));
hl->addWidget(exch_lbl);
}
auto* type_lbl = new QLabel(type.toUpper());
- type_lbl->setStyleSheet(QString("color:%1;font-size:8px;font-weight:700;%2;"
- "background:%3;padding:1px 4px;border-radius:2px;")
- .arg(ui::colors::AMBER.get(), MF(), ui::colors::BG_RAISED.get()));
+ type_lbl->setObjectName(QStringLiteral("relmapType"));
hl->addWidget(type_lbl);
item->setSizeHint(QSize(0, 30));
+ // Accessible text only — the row's visuals come from the item widget,
+ // so this must not be setText() (that would paint underneath it).
+ item->setData(Qt::AccessibleTextRole, QStringLiteral("%1 — %2").arg(yf_symbol, name));
+ item->setToolTip(QStringLiteral("%1 — %2").arg(yf_symbol, name));
search_dropdown_->setItemWidget(item, row);
}
@@ -654,6 +673,9 @@ void RelationshipMapScreen::hide_dropdown() {
void RelationshipMapScreen::on_progress(int percent, const QString& message) {
progress_bar_->setValue(percent);
progress_label_->setText(message);
+ // on_fetch_failed() paints this label red; without resetting it here every
+ // subsequent successful fetch still reported progress in error red.
+ progress_label_->setStyleSheet(QString("color: %1; font-size: 9px; %2").arg(colors::TEXT_DIM(), MF()));
if (percent >= 100) {
progress_bar_->hide();
@@ -682,8 +704,13 @@ void RelationshipMapScreen::on_data_ready(const RelationshipData& payload) {
void RelationshipMapScreen::on_fetch_failed(const QString& error) {
progress_bar_->hide();
- progress_label_->setText(tr("Error: %1").arg(error));
+ progress_label_->setText(tr("Error: %1 — press ANALYZE to retry").arg(error.simplified().left(90)));
+ progress_label_->setToolTip(error);
progress_label_->setStyleSheet(QString("color: %1; font-size: 9px; %2").arg(colors::NEGATIVE(), MF()));
+ // Leave the previous graph up rather than a blank canvas; the status bar
+ // still reports what is on screen.
+ if (status_nodes_ && !has_data_)
+ status_nodes_->setText(tr("NO DATA"));
}
void RelationshipMapScreen::rebuild_graph() {
diff --git a/fincept-qt/src/screens/relationship_map/RelationshipMapTypes.h b/fincept-qt/src/screens/relationship_map/RelationshipMapTypes.h
index 65f9ea74d..b2dc1adb5 100644
--- a/fincept-qt/src/screens/relationship_map/RelationshipMapTypes.h
+++ b/fincept-qt/src/screens/relationship_map/RelationshipMapTypes.h
@@ -378,6 +378,10 @@ struct RelationshipData {
struct FilterState {
bool show_peers = true;
bool show_institutional = true;
+ /// Mutual-fund holders. Previously the "Mutual Funds" checkbox was bound to
+ /// show_institutional, so the two filters were the same switch under two
+ /// labels — toggling one silently moved the other.
+ bool show_mutual_funds = true;
bool show_insiders = true;
bool show_officers = true;
bool show_analysts = true;
diff --git a/fincept-qt/src/screens/report_builder/ReportBuilderScreen.cpp b/fincept-qt/src/screens/report_builder/ReportBuilderScreen.cpp
index 283d46ece..988aa8df4 100644
--- a/fincept-qt/src/screens/report_builder/ReportBuilderScreen.cpp
+++ b/fincept-qt/src/screens/report_builder/ReportBuilderScreen.cpp
@@ -29,6 +29,7 @@
#include <QFormLayout>
#include <QFrame>
#include <QHBoxLayout>
+#include <QKeySequence>
#include <QLabel>
#include <QLineEdit>
#include <QListWidget>
@@ -41,6 +42,7 @@
#include <QPrintPreviewDialog>
#include <QPrinter>
#include <QPushButton>
+#include <QShortcut>
#include <QTextDocument>
#include <QTextFrame>
#include <QVBoxLayout>
@@ -465,6 +467,38 @@ QWidget* ReportBuilderScreen::build_toolbar() {
right_toggle_btn_ = make_panel_toggle("›", tr("Collapse properties panel (Ctrl+Shift+B)"), "Ctrl+Shift+B");
connect(right_toggle_btn_, &QPushButton::clicked, this, &ReportBuilderScreen::on_toggle_right);
+ // ── Standard document shortcuts ───────────────────────────────────────────
+ // Undo/Redo were toolbar-only; Save/Open/New/Print had no key bindings at
+ // all, which is surprising for a document editor.
+ auto add_sc = [this](QKeySequence::StandardKey key, auto fn) {
+ auto* sc = new QShortcut(QKeySequence(key), this);
+ sc->setContext(Qt::WidgetWithChildrenShortcut);
+ connect(sc, &QShortcut::activated, this, fn);
+ };
+ add_sc(QKeySequence::Save, [this]() { on_save(); });
+ add_sc(QKeySequence::Open, [this]() { on_open(); });
+ add_sc(QKeySequence::New, [this]() { on_new(); });
+ add_sc(QKeySequence::Print, [this]() { on_preview(); });
+ {
+ auto* undo_sc = new QShortcut(QKeySequence(QKeySequence::Undo), this);
+ undo_sc->setContext(Qt::WidgetWithChildrenShortcut);
+ connect(undo_sc, &QShortcut::activated, undo_stack, &QUndoStack::undo);
+ auto* redo_sc = new QShortcut(QKeySequence(QKeySequence::Redo), this);
+ redo_sc->setContext(Qt::WidgetWithChildrenShortcut);
+ connect(redo_sc, &QShortcut::activated, undo_stack, &QUndoStack::redo);
+ }
+
+ // ── Accessibility ─────────────────────────────────────────────────────────
+ undo_btn_->setAccessibleName(tr("Undo last change"));
+ redo_btn_->setAccessibleName(tr("Redo last change"));
+ open_btn_->setAccessibleName(tr("Open a saved report"));
+ save_btn_->setAccessibleName(tr("Save this report"));
+ pdf_btn_->setAccessibleName(tr("Export this report as PDF"));
+ preview_btn_->setAccessibleName(tr("Print preview"));
+ save_btn_->setToolTip(tr("Save (Ctrl+S)"));
+ open_btn_->setToolTip(tr("Open (Ctrl+O)"));
+ preview_btn_->setToolTip(tr("Preview (Ctrl+P)"));
+
return bar;
}
diff --git a/fincept-qt/src/screens/report_builder/ReportBuilderScreen.h b/fincept-qt/src/screens/report_builder/ReportBuilderScreen.h
index 76cf2707c..ff5d2a67f 100644
--- a/fincept-qt/src/screens/report_builder/ReportBuilderScreen.h
+++ b/fincept-qt/src/screens/report_builder/ReportBuilderScreen.h
@@ -54,6 +54,10 @@ class ReportBuilderScreen : public QWidget, public IStatefulScreen {
void show_theme_dialog();
void show_metadata_dialog();
+ /// Ask before replacing the in-memory document (New / Open / Recent).
+ /// Returns true if the caller may proceed.
+ bool confirm_replace_document(const QString& title);
+
// User-driven operations — all go through the service
void add_component(const QString& type);
void select_component(int index);
diff --git a/fincept-qt/src/screens/report_builder/ReportBuilderScreen_Dialogs.cpp b/fincept-qt/src/screens/report_builder/ReportBuilderScreen_Dialogs.cpp
index d2df379c8..6d1cd0a43 100644
--- a/fincept-qt/src/screens/report_builder/ReportBuilderScreen_Dialogs.cpp
+++ b/fincept-qt/src/screens/report_builder/ReportBuilderScreen_Dialogs.cpp
@@ -48,6 +48,9 @@ namespace rep = ::fincept::report;
using Service = ::fincept::services::ReportBuilderService;
void ReportBuilderScreen::show_recent_dialog() {
+ // Opening a recent report replaces the document, same as File → Open.
+ if (!confirm_replace_document(tr("Recent Reports")))
+ return;
QStringList recent = Service::instance().recent_files();
auto* dlg = new QDialog(this);
@@ -402,11 +405,22 @@ void ReportBuilderScreen::show_metadata_dialog() {
// ── File operations ──────────────────────────────────────────────────────────
+// Guard every document-replacing action behind one confirmation. The undo
+// stack's clean state is the closest thing the service exposes to a dirty flag:
+// non-clean means there are edits that have not been written to disk.
+bool ReportBuilderScreen::confirm_replace_document(const QString& title) {
+ auto* stack = Service::instance().undo_stack();
+ const bool dirty = stack && !stack->isClean() && stack->count() > 0;
+ if (!dirty && Service::instance().components().isEmpty())
+ return true; // nothing to lose
+ const auto answer =
+ QMessageBox::question(this, title, tr("The current report has unsaved changes.\n\nDiscard them?"),
+ QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
+ return answer == QMessageBox::Discard;
+}
+
void ReportBuilderScreen::on_new() {
- auto answer =
- QMessageBox::question(this, tr("New Report"), tr("Create a new report? Unsaved changes will be lost."),
- QMessageBox::Yes | QMessageBox::No);
- if (answer != QMessageBox::Yes)
+ if (!confirm_replace_document(tr("New Report")))
return;
Service::instance().clear_document();
selected_id_ = 0;
@@ -414,6 +428,10 @@ void ReportBuilderScreen::on_new() {
}
void ReportBuilderScreen::on_open() {
+ // on_new() confirmed before wiping the document but Open did not — it
+ // replaced unsaved work with no warning at all.
+ if (!confirm_replace_document(tr("Open Report")))
+ return;
QString path =
QFileDialog::getOpenFileName(this, tr("Open Report"), "", tr("Fincept Report (*.fincept);;JSON (*.json)"));
if (path.isEmpty())
@@ -432,6 +450,11 @@ void ReportBuilderScreen::on_save() {
tr("Fincept Report (*.fincept);;JSON (*.json)"));
if (path.isEmpty())
return;
+ // QFileDialog does not append the filter suffix on every platform; a
+ // report saved without one won't reopen through the *.fincept filter.
+ if (!path.endsWith(QLatin1String(".fincept"), Qt::CaseInsensitive) &&
+ !path.endsWith(QLatin1String(".json"), Qt::CaseInsensitive))
+ path += QLatin1String(".fincept");
}
auto r = svc.save_to(path);
if (r.is_err()) {
@@ -439,6 +462,8 @@ void ReportBuilderScreen::on_save() {
tr("Could not save to:\n%1\n\n%2").arg(path, QString::fromStdString(r.error())));
return;
}
+ if (auto* stack = svc.undo_stack())
+ stack->setClean(); // saved state == clean state, so Open/New stop nagging
services::FileManagerService::instance().import_file(path, "report_builder");
}
@@ -447,6 +472,8 @@ void ReportBuilderScreen::on_export_pdf() {
QString path = QFileDialog::getSaveFileName(this, tr("Export PDF"), m.title, tr("PDF (*.pdf)"));
if (path.isEmpty())
return;
+ if (!path.endsWith(QLatin1String(".pdf"), Qt::CaseInsensitive))
+ path += QLatin1String(".pdf");
export_pdf_to(path);
// export_pdf_to can fail without throwing (painter-begin failure, unwritable
// path, disk full) — verify a non-empty PDF actually landed before claiming
@@ -509,6 +536,12 @@ void ReportBuilderScreen::export_pdf_to(const QString& path) {
center = replace_tokens(center);
right = replace_tokens(right);
+ // "Show page numbers" only reserved footer space before: unless the
+ // user happened to type "{page}" into a footer field, ticking the
+ // box produced an empty footer band and no page numbers.
+ if (!is_header && m.show_page_numbers && left.isEmpty() && center.isEmpty() && right.isEmpty())
+ center = QStringLiteral("%1 / %2").arg(page).arg(total_pages);
+
double y = is_header ? 4 : page_rect.height() - 16;
QFont hf_font;
hf_font.setPointSizeF(7);
diff --git a/fincept-qt/src/screens/screener/ScreenerScreen.cpp b/fincept-qt/src/screens/screener/ScreenerScreen.cpp
index f0b8bd721..1d99f5a8b 100644
--- a/fincept-qt/src/screens/screener/ScreenerScreen.cpp
+++ b/fincept-qt/src/screens/screener/ScreenerScreen.cpp
@@ -11,8 +11,10 @@
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
+#include <QScrollBar>
#include <QTableWidget>
#include <QTableWidgetItem>
+#include <QTimer>
#include <QVBoxLayout>
#include <algorithm>
@@ -144,10 +146,16 @@ void ScreenerScreen::retranslate() {
search_->setPlaceholderText(tr("Search symbol or name…"));
refresh_btn_->setText(tr("REFRESH"));
+ search_->setAccessibleName(tr("Filter by symbol or company name"));
+ sort_combo_->setAccessibleName(tr("Sort order"));
+ refresh_btn_->setAccessibleName(tr("Refresh all quotes now"));
+
const int prev = sort_combo_->currentIndex();
QSignalBlocker block(sort_combo_);
sort_combo_->clear();
- sort_combo_->addItems({tr("% CHANGE ↑"), tr("% CHANGE ↓"), tr("VOLUME ↓"), tr("PRICE ↓"), tr("PRICE ↑")});
+ // Index 0/1 sort by change but the old "% CHANGE ↑ / ↓" labels read as sort
+ // direction while actually meaning gainers/losers — name the intent instead.
+ sort_combo_->addItems({tr("TOP GAINERS"), tr("TOP LOSERS"), tr("VOLUME ↓"), tr("PRICE ↓"), tr("PRICE ↑")});
sort_combo_->setCurrentIndex(prev < 0 ? 0 : prev);
table_->setHorizontalHeaderLabels(
@@ -172,10 +180,26 @@ void ScreenerScreen::changeEvent(QEvent* e) {
QWidget::changeEvent(e);
if (!e)
return;
- if (e->type() == QEvent::StyleChange || e->type() == QEvent::PaletteChange)
+ if (e->type() == QEvent::StyleChange || e->type() == QEvent::PaletteChange) {
+ // Re-entrancy guard — WITHOUT THIS THE PROCESS DIES WITH A STACK
+ // OVERFLOW (0xC00000FD).
+ //
+ // apply_styles() calls setStyleSheet() on header_bar_ and table_.
+ // setStyleSheet re-polishes the widget, which posts a fresh StyleChange
+ // — straight back into this handler, which calls apply_styles() again.
+ // Nothing breaks the loop, so it recurses until the stack is exhausted.
+ //
+ // Found by --smoke-test, which aborted deterministically while
+ // constructing this screen (the constructor calls apply_styles()
+ // directly). Reproduced across runs with different walk orders.
+ if (restyling_)
+ return;
+ restyling_ = true;
apply_styles();
- else if (e->type() == QEvent::LanguageChange)
+ restyling_ = false;
+ } else if (e->type() == QEvent::LanguageChange) {
retranslate();
+ }
}
void ScreenerScreen::hub_subscribe_all() {
@@ -186,12 +210,29 @@ void ScreenerScreen::hub_subscribe_all() {
if (!v.canConvert<services::QuoteData>())
return;
row_cache_.insert(sym, v.value<services::QuoteData>());
- rebuild_from_cache();
+ schedule_rebuild();
});
}
hub_active_ = true;
}
+void ScreenerScreen::schedule_rebuild() {
+ // 62 topics deliver 62 separate callbacks per refresh sweep. Rebuilding the
+ // whole table on each one meant ~62 full sorts and ~19,000 QTableWidgetItem
+ // allocations per sweep, and reset the scroll position 62 times. Coalesce
+ // into one rebuild on the next event-loop turn.
+ //
+ // This is a render coalescer, not a data-refresh timer (D3): it is a
+ // zero-delay single shot armed by an incoming hub delivery, never a cadence.
+ if (rebuild_pending_)
+ return;
+ rebuild_pending_ = true;
+ QTimer::singleShot(0, this, [this]() {
+ rebuild_pending_ = false;
+ rebuild_from_cache();
+ });
+}
+
void ScreenerScreen::hub_unsubscribe_all() {
datahub::DataHub::instance().unsubscribe(this);
hub_active_ = false;
@@ -258,6 +299,15 @@ void ScreenerScreen::apply_filter() {
}
void ScreenerScreen::render_rows(const QVector<services::QuoteData>& rows) {
+ // Rebuilding every item drops the scroll offset and the selected row. Quotes
+ // arrive continuously, so without this the list jumps back to the top under
+ // the user's cursor on every sweep.
+ const int scroll_pos = table_->verticalScrollBar() ? table_->verticalScrollBar()->value() : 0;
+ const QString selected_symbol =
+ table_->currentRow() >= 0 && table_->item(table_->currentRow(), 0)
+ ? table_->item(table_->currentRow(), 0)->text()
+ : QString();
+
table_->setRowCount(rows.size());
for (int r = 0; r < rows.size(); ++r) {
const auto& q = rows[r];
@@ -288,6 +338,17 @@ void ScreenerScreen::render_rows(const QVector<services::QuoteData>& rows) {
vol->setForeground(QColor(ui::colors::TEXT_SECONDARY()));
table_->setItem(r, 4, vol);
}
+
+ if (!selected_symbol.isEmpty()) {
+ for (int r = 0; r < rows.size(); ++r) {
+ if (rows[r].symbol == selected_symbol) {
+ table_->selectRow(r);
+ break;
+ }
+ }
+ }
+ if (table_->verticalScrollBar())
+ table_->verticalScrollBar()->setValue(scroll_pos);
}
} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/screener/ScreenerScreen.h b/fincept-qt/src/screens/screener/ScreenerScreen.h
index dbe9c06f6..eeb7bd4f5 100644
--- a/fincept-qt/src/screens/screener/ScreenerScreen.h
+++ b/fincept-qt/src/screens/screener/ScreenerScreen.h
@@ -39,6 +39,9 @@ class ScreenerScreen : public QWidget {
void hub_subscribe_all();
void hub_unsubscribe_all();
+ /// Coalesce the ~62 per-symbol hub deliveries of a refresh sweep into one
+ /// table rebuild on the next event-loop turn.
+ void schedule_rebuild();
/// Recompute `all_quotes_` from `row_cache_` (in basket order) then filter.
void rebuild_from_cache();
void apply_filter();
@@ -57,6 +60,10 @@ class ScreenerScreen : public QWidget {
QHash<QString, services::QuoteData> row_cache_;
QVector<services::QuoteData> all_quotes_;
bool hub_active_ = false;
+ bool rebuild_pending_ = false;
+ /// Guards changeEvent(StyleChange) -> apply_styles() -> setStyleSheet() ->
+ /// StyleChange -> ... which recursed until the stack was exhausted.
+ bool restyling_ = false;
};
} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/settings/AppearanceSection.cpp b/fincept-qt/src/screens/settings/AppearanceSection.cpp
index cd9e9bfec..5012ab75f 100644
--- a/fincept-qt/src/screens/settings/AppearanceSection.cpp
+++ b/fincept-qt/src/screens/settings/AppearanceSection.cpp
@@ -228,8 +228,18 @@ void AppearanceSection::build_ui() {
vl->addSpacing(16);
// ── SAVE ──────────────────────────────────────────────────────────────────
+ // Accessibility: every control here is a bare combo/checkbox next to a
+ // separate QLabel, which screen readers do not associate automatically.
+ app_font_size_->setAccessibleName(tr("Font size"));
+ app_font_family_->setAccessibleName(tr("Font family"));
+ app_density_->setAccessibleName(tr("Content density"));
+ chat_bubble_toggle_->setAccessibleName(tr("Show AI chat bubble"));
+ ticker_bar_toggle_->setAccessibleName(tr("Show ticker bar"));
+ animations_toggle_->setAccessibleName(tr("Enable animations"));
+
save_btn_ = new QPushButton(tr("Save Settings"));
save_btn_->setFixedWidth(160);
+ save_btn_->setAccessibleName(tr("Save appearance settings"));
save_btn_->setStyleSheet(btn_primary_ss());
connect(save_btn_, &QPushButton::clicked, this, [this]() {
auto& repo = SettingsRepository::instance();
diff --git a/fincept-qt/src/screens/settings/CredentialsSection.cpp b/fincept-qt/src/screens/settings/CredentialsSection.cpp
index 334c536c6..c9ea462bd 100644
--- a/fincept-qt/src/screens/settings/CredentialsSection.cpp
+++ b/fincept-qt/src/screens/settings/CredentialsSection.cpp
@@ -13,6 +13,7 @@
#include <QLabel>
#include <QLineEdit>
#include <QList>
+#include <QMessageBox>
#include <QPair>
#include <QPushButton>
#include <QScrollArea>
@@ -96,26 +97,41 @@ void CredentialsSection::build_ui() {
vl->addWidget(make_sep());
vl->addSpacing(16);
+ // One page-level stylesheet keyed by objectName instead of ~6 inline
+ // setStyleSheet() calls per credential card. With 60+ providers in
+ // CRED_KEYS that was 350+ CSS parses every time this section is built —
+ // and SettingsScreen builds all 16 sections eagerly. Only the per-key
+ // status label keeps an inline style, because its colour is state-driven.
+ page->setStyleSheet(QString("QFrame#credCard{background:%1;border:1px solid %2;}"
+ "QWidget#credHdr{background:%3;border-bottom:1px solid %2;}"
+ "QLabel#credName{color:%4;font-weight:600;background:transparent;}"
+ "QWidget#credBody{background:transparent;}"
+ "QLineEdit#credField{background:%3;color:%4;border:1px solid %5;padding:6px;}"
+ "QLineEdit#credField:focus{border:1px solid %6;}"
+ "QPushButton#credSave{background:%6;color:%7;border:none;font-weight:700;"
+ "padding:0 16px;}"
+ "QPushButton#credSave:hover{background:%8;}")
+ .arg(ui::colors::BG_SURFACE(), ui::colors::BORDER_DIM(), ui::colors::BG_RAISED(),
+ ui::colors::TEXT_PRIMARY(), ui::colors::BORDER_MED(), ui::colors::AMBER(),
+ ui::colors::BG_BASE(), ui::colors::AMBER_DIM()));
+
for (const auto& def : CRED_KEYS) {
const QString& key = def.first;
const QString& name = def.second;
auto* card = new QFrame;
- card->setStyleSheet(QString("QFrame{background:%1;border:1px solid %2;border-radius:4px;}")
- .arg(ui::colors::BG_SURFACE(), ui::colors::BORDER_DIM()));
+ card->setObjectName(QStringLiteral("credCard"));
auto* cvl = new QVBoxLayout(card);
cvl->setContentsMargins(0, 0, 0, 0);
cvl->setSpacing(0);
auto* hdr = new QWidget(this);
+ hdr->setObjectName(QStringLiteral("credHdr"));
hdr->setFixedHeight(34);
- hdr->setStyleSheet(QString("background:%1;border-bottom:1px solid %2;")
- .arg(ui::colors::BG_RAISED(), ui::colors::BORDER_DIM()));
auto* hhl = new QHBoxLayout(hdr);
hhl->setContentsMargins(12, 0, 12, 0);
auto* name_lbl = new QLabel(name);
- name_lbl->setStyleSheet(
- QString("color:%1;font-weight:600;background:transparent;").arg(ui::colors::TEXT_PRIMARY()));
+ name_lbl->setObjectName(QStringLiteral("credName"));
hhl->addWidget(name_lbl);
hhl->addStretch();
@@ -127,28 +143,54 @@ void CredentialsSection::build_ui() {
cvl->addWidget(hdr);
auto* body = new QWidget(this);
- body->setStyleSheet("background: transparent;");
+ body->setObjectName(QStringLiteral("credBody"));
auto* bhl = new QHBoxLayout(body);
bhl->setContentsMargins(12, 10, 12, 10);
bhl->setSpacing(8);
auto* field = new QLineEdit;
+ field->setObjectName(QStringLiteral("credField"));
field->setEchoMode(QLineEdit::Password);
field->setPlaceholderText(tr("Not configured"));
- field->setStyleSheet(input_ss());
+ // Never let an API key end up in an IME candidate list, a predictive
+ // dictionary, or a drag-and-drop payload.
+ field->setInputMethodHints(Qt::ImhSensitiveData | Qt::ImhNoPredictiveText | Qt::ImhNoAutoUppercase);
+ field->setDragEnabled(false);
+ field->setAcceptDrops(false);
+ field->setAccessibleName(tr("%1 API key").arg(name));
cred_fields_[key] = field;
bhl->addWidget(field, 1);
auto* save_btn = new QPushButton(tr("Save"));
+ save_btn->setObjectName(QStringLiteral("credSave"));
save_btn->setFixedHeight(30);
save_btn->setFixedWidth(70);
- save_btn->setStyleSheet(btn_primary_ss());
+ save_btn->setAccessibleName(tr("Save %1 API key").arg(name));
bhl->addWidget(save_btn);
cred_save_btns_[key] = save_btn;
- connect(save_btn, &QPushButton::clicked, this, [key, field, status_lbl]() {
+ // Enter in the field is the same as clicking Save.
+ connect(field, &QLineEdit::returnPressed, save_btn, &QPushButton::click);
+ setTabOrder(field, save_btn);
+
+ connect(save_btn, &QPushButton::clicked, this, [this, key, name, field, status_lbl]() {
QString val = field->text().trimmed();
if (val.isEmpty()) {
+ // Saving an empty field deletes the stored key. That is a
+ // destructive, silent action when a key is already configured —
+ // confirm it rather than shredding a credential on a stray click.
+ const auto existing = SecureStorage::instance().retrieve(key);
+ const bool had_key = existing.is_ok() && !existing.value().isEmpty();
+ if (had_key) {
+ const auto reply = QMessageBox::question(
+ this, tr("Remove Credential"),
+ tr("Remove the stored %1 key from the OS keychain?\n\nYou will need to paste it "
+ "again to restore access.")
+ .arg(name),
+ QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
+ if (reply != QMessageBox::Yes)
+ return;
+ }
SecureStorage::instance().remove(key);
field->setPlaceholderText(tr("Not configured"));
status_lbl->setText(tr("Cleared"));
diff --git a/fincept-qt/src/screens/settings/GeneralSection.cpp b/fincept-qt/src/screens/settings/GeneralSection.cpp
index 4aa4b1c74..a608716d8 100644
--- a/fincept-qt/src/screens/settings/GeneralSection.cpp
+++ b/fincept-qt/src/screens/settings/GeneralSection.cpp
@@ -151,6 +151,12 @@ void GeneralSection::build_ui() {
currency::CurrencyManager::instance().set_currency(code);
});
+ // Accessibility: the row label is a sibling QLabel, not a buddy, so the
+ // combos read as anonymous without an explicit accessible name.
+ on_close_combo_->setAccessibleName(tr("On last window close"));
+ language_combo_->setAccessibleName(tr("Interface language"));
+ currency_combo_->setAccessibleName(tr("Display currency"));
+
vl->addStretch();
scroll->setWidget(page);
diff --git a/fincept-qt/src/screens/settings/KeybindingsSection.cpp b/fincept-qt/src/screens/settings/KeybindingsSection.cpp
index 42820819e..14bea04bd 100644
--- a/fincept-qt/src/screens/settings/KeybindingsSection.cpp
+++ b/fincept-qt/src/screens/settings/KeybindingsSection.cpp
@@ -11,6 +11,7 @@
#include <QKeyEvent>
#include <QLabel>
#include <QMap>
+#include <QMessageBox>
#include <QMouseEvent>
#include <QPushButton>
#include <QScrollArea>
@@ -123,6 +124,8 @@ void KeybindingsSection::build_ui() {
// Search bar
search_input_ = new QLineEdit;
search_input_->setPlaceholderText(tr("Search actions..."));
+ search_input_->setAccessibleName(tr("Search keyboard actions"));
+ search_input_->setClearButtonEnabled(true);
search_input_->setStyleSheet(
QString("QLineEdit{background:%1;color:%2;border:1px solid %3;padding:6px;}"
"QLineEdit:focus{border:1px solid %4;}")
@@ -149,7 +152,18 @@ void KeybindingsSection::build_ui() {
"QPushButton:hover{background:%4;}")
.arg(ui::colors::BG_RAISED(), ui::colors::TEXT_PRIMARY(), ui::colors::BORDER_MED(),
ui::colors::BG_HOVER()));
- connect(reset_all_btn_, &QPushButton::clicked, this, []() { KeyConfigManager::instance().reset_all(); });
+ reset_all_btn_->setAccessibleName(tr("Reset all keybindings to defaults"));
+ connect(reset_all_btn_, &QPushButton::clicked, this, [this]() {
+ // Wipes every custom binding the user has made, with no undo — the one
+ // destructive action on this page and it had no confirmation.
+ const auto reply = QMessageBox::question(
+ this, tr("Reset Keybindings"),
+ tr("Reset every keyboard shortcut to its default?\n\nAll of your custom bindings will be lost."),
+ QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
+ if (reply != QMessageBox::Yes)
+ return;
+ KeyConfigManager::instance().reset_all();
+ });
root->addWidget(search_input_);
root->addWidget(scroll, 1);
diff --git a/fincept-qt/src/screens/settings/LlmConfigSection.cpp b/fincept-qt/src/screens/settings/LlmConfigSection.cpp
index 715fcf467..faa84298b 100644
--- a/fincept-qt/src/screens/settings/LlmConfigSection.cpp
+++ b/fincept-qt/src/screens/settings/LlmConfigSection.cpp
@@ -81,6 +81,11 @@ void LlmConfigSection::reload() {
load_profiles();
}
+void LlmConfigSection::showEvent(QShowEvent* e) {
+ QWidget::showEvent(e);
+ reload();
+}
+
void LlmConfigSection::build_ui() {
auto* root = new QVBoxLayout(this);
root->setContentsMargins(0, 0, 0, 0);
diff --git a/fincept-qt/src/screens/settings/LlmConfigSection.h b/fincept-qt/src/screens/settings/LlmConfigSection.h
index 91ba03329..43316a0f4 100644
--- a/fincept-qt/src/screens/settings/LlmConfigSection.h
+++ b/fincept-qt/src/screens/settings/LlmConfigSection.h
@@ -13,6 +13,7 @@
#include <QListWidget>
#include <QPlainTextEdit>
#include <QPushButton>
+#include <QShowEvent>
#include <QSpinBox>
#include <QStackedWidget>
#include <QStringList>
@@ -33,6 +34,11 @@ class LlmConfigSection : public QWidget {
protected:
void changeEvent(QEvent* event) override;
+ /// Re-reads providers + profiles every time the section becomes visible.
+ /// SettingsScreen's MCP-driven sync works by hiding and re-showing the
+ /// current section, so without this override an `llm.provider_changed`
+ /// event left this panel showing stale rows.
+ void showEvent(QShowEvent* e) override;
private slots:
// Provider tab
diff --git a/fincept-qt/src/screens/settings/LlmConfigSection_Profiles.cpp b/fincept-qt/src/screens/settings/LlmConfigSection_Profiles.cpp
index f2b175018..a2a4b371c 100644
--- a/fincept-qt/src/screens/settings/LlmConfigSection_Profiles.cpp
+++ b/fincept-qt/src/screens/settings/LlmConfigSection_Profiles.cpp
@@ -455,6 +455,21 @@ void LlmConfigSection::on_save_profile() {
void LlmConfigSection::on_delete_profile() {
if (editing_profile_id_.isEmpty())
return;
+
+ // Deleting a profile is irreversible and silently detaches every agent /
+ // team assigned to it — the only destructive action on this tab that had
+ // no confirmation step (the provider Remove button already has one).
+ const QString name = profile_name_edit_ ? profile_name_edit_->text().trimmed() : QString();
+ const auto reply = QMessageBox::question(
+ this, tr("Delete Profile"),
+ name.isEmpty() ? tr("Delete this LLM profile?\n\nThis cannot be undone.")
+ : tr("Delete the LLM profile \"%1\"?\n\nAgents assigned to it fall back to the "
+ "default profile. This cannot be undone.")
+ .arg(name),
+ QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
+ if (reply != QMessageBox::Yes)
+ return;
+
auto r = LlmProfileRepository::instance().delete_profile(editing_profile_id_);
if (r.is_ok()) {
clear_profile_form();
diff --git a/fincept-qt/src/screens/settings/LlmConfigSection_Providers.cpp b/fincept-qt/src/screens/settings/LlmConfigSection_Providers.cpp
index 542028ab2..f861bd5bb 100644
--- a/fincept-qt/src/screens/settings/LlmConfigSection_Providers.cpp
+++ b/fincept-qt/src/screens/settings/LlmConfigSection_Providers.cpp
@@ -564,8 +564,12 @@ void LlmConfigSection::populate_form(const QString& provider) {
api_key_edit_->clear();
const QString stored = fincept::auth::AuthManager::instance().fincept_api_key();
if (!stored.isEmpty()) {
- QString masked = stored.left(8) + "...";
- api_key_edit_->setPlaceholderText(tr("Linked to your Fincept account: %1").arg(masked));
+ // Show only the trailing 4 characters. The previous preview
+ // printed the first 8, which for a prefixed key format gives
+ // away a meaningful slice of the secret in a field that is
+ // always visible (placeholders ignore Password echo mode).
+ api_key_edit_->setPlaceholderText(
+ tr("Linked to your Fincept account: ••••%1").arg(stored.right(4)));
} else {
api_key_edit_->setPlaceholderText(tr("Login to your Fincept account to enable"));
}
@@ -610,7 +614,7 @@ void LlmConfigSection::populate_form(const QString& provider) {
if (is_fincept) {
const QString stored = fincept::auth::AuthManager::instance().fincept_api_key();
if (!stored.isEmpty())
- api_key_edit_->setPlaceholderText(tr("Linked to your Fincept account: %1").arg(stored.left(8) + "..."));
+ api_key_edit_->setPlaceholderText(tr("Linked to your Fincept account: ••••%1").arg(stored.right(4)));
else
api_key_edit_->setPlaceholderText(tr("Login to your Fincept account to enable"));
model_combo_->setVisible(false);
diff --git a/fincept-qt/src/screens/settings/LoggingSection.cpp b/fincept-qt/src/screens/settings/LoggingSection.cpp
index 0d4690b42..d3ac3f69c 100644
--- a/fincept-qt/src/screens/settings/LoggingSection.cpp
+++ b/fincept-qt/src/screens/settings/LoggingSection.cpp
@@ -22,6 +22,7 @@
#include <QScrollArea>
#include <QString>
#include <QStringList>
+#include <QTimer>
#include <QUrl>
#include <QVBoxLayout>
@@ -94,6 +95,7 @@ void LoggingSection::build_ui() {
vl->addWidget(fmt_desc_);
log_json_mode_ = new QCheckBox(tr("Emit structured JSON lines"));
+ log_json_mode_->setStyleSheet(check_ss()); // was the only unstyled control on this page
log_json_mode_->setChecked(AppConfig::instance().get("log/json_mode", false).toBool());
vl->addWidget(log_json_mode_);
vl->addWidget(make_sep());
@@ -154,7 +156,12 @@ void LoggingSection::build_ui() {
auto& cfg = AppConfig::instance();
const int count = cfg.get("log/tag_count", 0).toInt();
- auto add_tag_row = [this, &level_to_idx](const QString& tag, const QString& level) {
+ // level_to_idx is captured BY VALUE: add_tag_row is copied into the
+ // "+ Add Tag Override" click handler, which runs long after build_ui() has
+ // returned. Capturing by reference left that copy holding a dangling
+ // reference to a destroyed stack lambda — undefined behaviour on every
+ // click of the Add button.
+ auto add_tag_row = [this, level_to_idx](const QString& tag, const QString& level) {
using namespace settings_styles;
auto* row = new QWidget(this);
auto* rl = new QHBoxLayout(row);
@@ -241,6 +248,13 @@ void LoggingSection::build_ui() {
}
cfg.set("log/tag_count", saved);
+ // Saving previously produced no on-screen acknowledgement at all.
+ save_btn_->setText(tr("Saved ✓"));
+ QTimer::singleShot(2000, save_btn_, [this]() {
+ if (save_btn_)
+ save_btn_->setText(tr("Apply & Save"));
+ });
+
LOG_INFO("Settings", QString("Logging config saved: global=%1, tags=%2").arg(gl).arg(saved));
});
diff --git a/fincept-qt/src/screens/settings/McpServersSection.cpp b/fincept-qt/src/screens/settings/McpServersSection.cpp
index 384cd49a0..f245b8553 100644
--- a/fincept-qt/src/screens/settings/McpServersSection.cpp
+++ b/fincept-qt/src/screens/settings/McpServersSection.cpp
@@ -51,9 +51,18 @@ McpServersSection::McpServersSection(QWidget* parent) : QWidget(parent) {
}
void McpServersSection::reload() {
+ if (!tab_stack_)
+ return;
load_servers();
if (tab_stack_->currentIndex() == 1)
load_tools();
+ if (tools_badge_)
+ tools_badge_->setText(tr("%1 internal tools active").arg(McpService::instance().tool_count()));
+}
+
+void McpServersSection::showEvent(QShowEvent* e) {
+ QWidget::showEvent(e);
+ reload();
}
void McpServersSection::build_ui() {
@@ -241,13 +250,16 @@ QWidget* McpServersSection::build_servers_tab() {
stop_btn_ = new QPushButton(tr("■ Stop"));
stop_btn_->setEnabled(false);
stop_btn_->setFixedHeight(32);
+ // Was red text on a red background — the label was invisible in the enabled
+ // state. Now the Obsidian danger-button spec: tinted surface, red label,
+ // solid red on hover.
stop_btn_->setStyleSheet(
- "QPushButton{background:" + QString(ui::colors::NEGATIVE()) + ";color:" + QString(ui::colors::NEGATIVE()) +
- ";border:1px solid " + QString(ui::colors::NEGATIVE()) +
+ "QPushButton{background:rgba(220,38,38,0.1);color:" + QString(ui::colors::NEGATIVE()) + ";border:1px solid " +
+ QString(ui::colors::NEGATIVE_DIM()) +
";"
"border-radius:4px;font-weight:600;padding:0 16px;}"
"QPushButton:hover{background:" +
- QString(ui::colors::BG_RAISED()) +
+ QString(ui::colors::NEGATIVE()) + ";color:" + QString(ui::colors::TEXT_PRIMARY()) +
";}"
"QPushButton:disabled{color:" +
QString(ui::colors::BORDER_BRIGHT()) + ";border-color:" + QString(ui::colors::BORDER_MED()) +
@@ -544,8 +556,12 @@ void McpServersSection::refresh_server_detail(const QString& server_id) {
"</span><br>"
"<span style='color:" +
QString(ui::colors::TEXT_TERTIARY()) + ";'>" + tr("Auto-start: %6") + "</span>")
- .arg(cfg.name, status_str, cfg.command, cfg.args.join(' '),
- cfg.category.isEmpty() ? "-" : cfg.category,
+ // Server name / command / args are user-supplied and land in a
+ // rich-text QLabel — escape them so a stray '<' doesn't swallow
+ // the rest of the detail panel.
+ .arg(cfg.name.toHtmlEscaped(), status_str, cfg.command.toHtmlEscaped(),
+ cfg.args.join(' ').toHtmlEscaped(),
+ cfg.category.isEmpty() ? QStringLiteral("-") : cfg.category.toHtmlEscaped(),
cfg.auto_start ? tr("Yes") : tr("No")));
bool running = (cfg.status == ServerStatus::Running);
@@ -624,18 +640,13 @@ void McpServersSection::on_tab_changed(int idx) {
if (idx == 1)
load_tools();
- // Update tab button states
- QList<QPushButton*> btns = findChildren<QPushButton*>();
- // The tab bar buttons are the first two checkable buttons
- int checked_count = 0;
- for (auto* btn : btns) {
- if (btn->isCheckable()) {
- btn->setChecked(checked_count == idx);
- ++checked_count;
- if (checked_count > 1)
- break;
- }
- }
+ // Drive the two tab buttons directly. The previous version walked every
+ // QPushButton in the subtree and checked the first two checkable ones,
+ // which silently breaks the moment any other checkable button is added.
+ if (servers_tab_btn_)
+ servers_tab_btn_->setChecked(idx == 0);
+ if (tools_tab_btn_)
+ tools_tab_btn_->setChecked(idx == 1);
}
void McpServersSection::show_status(const QString& msg, bool error) {
diff --git a/fincept-qt/src/screens/settings/McpServersSection.h b/fincept-qt/src/screens/settings/McpServersSection.h
index 4471b4223..414d6efa7 100644
--- a/fincept-qt/src/screens/settings/McpServersSection.h
+++ b/fincept-qt/src/screens/settings/McpServersSection.h
@@ -5,6 +5,7 @@
#include <QLabel>
#include <QListWidget>
#include <QPushButton>
+#include <QShowEvent>
#include <QStackedWidget>
#include <QTableWidget>
#include <QWidget>
@@ -20,6 +21,11 @@ class McpServersSection : public QWidget {
protected:
void changeEvent(QEvent* event) override;
+ /// Refresh the server list (and, on the Tools tab, the tool table) each
+ /// time the section becomes visible. SettingsScreen's MCP event sync
+ /// re-shows the current section to trigger exactly this; reload() was
+ /// previously public but had no caller, so the panel never refreshed.
+ void showEvent(QShowEvent* e) override;
private slots:
void on_server_selected(int row);
@@ -57,7 +63,6 @@ class McpServersSection : public QWidget {
void build_ui();
QWidget* build_servers_tab();
QWidget* build_tools_tab();
- QWidget* build_add_server_form();
void load_servers();
void load_tools();
diff --git a/fincept-qt/src/screens/settings/NotificationsSection.cpp b/fincept-qt/src/screens/settings/NotificationsSection.cpp
index 9fff259a2..155937a23 100644
--- a/fincept-qt/src/screens/settings/NotificationsSection.cpp
+++ b/fincept-qt/src/screens/settings/NotificationsSection.cpp
@@ -211,8 +211,15 @@ void NotificationsSection::build_ui() {
// numbers) — left untranslated. Field labels are UI text.
field->setPlaceholderText(fd.placeholder);
field->setStyleSheet(input_ss());
- if (fd.is_password)
+ field->setAccessibleName(QString("%1 — %2").arg(def.name, fd.label));
+ if (fd.is_password) {
field->setEchoMode(QLineEdit::Password);
+ // Bot tokens / SMTP passwords / Twilio auth tokens must not be
+ // harvested by predictive text or an IME candidate window.
+ field->setInputMethodHints(Qt::ImhSensitiveData | Qt::ImhNoPredictiveText | Qt::ImhNoAutoUppercase);
+ field->setDragEnabled(false);
+ field->setAcceptDrops(false);
+ }
pw.fields[fd.key] = field;
auto* field_row = make_row(tr(fd.label.toUtf8().constData()), field);
QLabel* row_lbl = nullptr;
diff --git a/fincept-qt/src/screens/settings/ProfilesSection.cpp b/fincept-qt/src/screens/settings/ProfilesSection.cpp
index 6a5de700f..6c3dfadbf 100644
--- a/fincept-qt/src/screens/settings/ProfilesSection.cpp
+++ b/fincept-qt/src/screens/settings/ProfilesSection.cpp
@@ -12,8 +12,10 @@
#include <QHBoxLayout>
#include <QLabel>
#include <QLineEdit>
+#include <QMessageBox>
#include <QProcess>
#include <QPushButton>
+#include <QRegularExpression>
#include <QScrollArea>
#include <QString>
#include <QStringList>
@@ -106,7 +108,19 @@ QWidget* ProfilesSection::build_content() {
auto* switch_btn = new QPushButton(tr("Switch"));
switch_btn->setFixedWidth(72);
switch_btn->setStyleSheet(btn_secondary_ss());
- connect(switch_btn, &QPushButton::clicked, this, [name]() {
+ switch_btn->setAccessibleName(tr("Switch to profile %1").arg(name));
+ connect(switch_btn, &QPushButton::clicked, this, [this, name]() {
+ // Switching relaunches the process and quits this one. That is
+ // as destructive as closing the terminal, and it used to happen
+ // on a single unconfirmed click.
+ const auto reply = QMessageBox::question(
+ this, tr("Switch Profile"),
+ tr("Switch to profile \"%1\"?\n\nFincept Terminal will restart. Unsaved work in the "
+ "current session may be lost.")
+ .arg(name),
+ QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
+ if (reply != QMessageBox::Yes)
+ return;
const QString exe = QCoreApplication::applicationFilePath();
QProcess::startDetached(exe, {"--profile", name});
QCoreApplication::quit();
@@ -130,14 +144,39 @@ QWidget* ProfilesSection::build_content() {
auto* name_input = new QLineEdit;
name_input->setPlaceholderText(tr("profile-name (alphanumeric, - and _ only)"));
name_input->setStyleSheet(input_ss());
+ name_input->setMaxLength(32);
+ name_input->setAccessibleName(tr("New profile name"));
new_hl->addWidget(name_input, 1);
auto* create_btn = new QPushButton(tr("Create & Switch"));
create_btn->setStyleSheet(btn_primary_ss());
- connect(create_btn, &QPushButton::clicked, this, [name_input]() {
+ create_btn->setAccessibleName(tr("Create profile and switch to it"));
+ connect(name_input, &QLineEdit::returnPressed, create_btn, &QPushButton::click);
+ connect(create_btn, &QPushButton::clicked, this, [this, name_input]() {
const QString name = name_input->text().trimmed().toLower();
- if (name.isEmpty())
+ // The placeholder advertised a character set that nothing enforced.
+ // ProfileManager sanitises the name before using it as a directory, so
+ // an unsanitised value silently landed the user in a *differently
+ // named* profile than the one they typed.
+ static const QRegularExpression kValidName(QStringLiteral("^[a-z0-9_-]{1,32}$"));
+ if (name.isEmpty() || !kValidName.match(name).hasMatch()) {
+ QMessageBox::warning(this, tr("Invalid Profile Name"),
+ tr("Use 1-32 characters: lowercase letters, digits, hyphen or underscore."));
return;
+ }
+ if (ProfileManager::instance().list_profiles().contains(name)) {
+ QMessageBox::warning(this, tr("Profile Exists"), tr("A profile named \"%1\" already exists.").arg(name));
+ return;
+ }
+ const auto reply =
+ QMessageBox::question(this, tr("Create Profile"),
+ tr("Create profile \"%1\" and switch to it?\n\nFincept Terminal will restart. "
+ "Unsaved work in the current session may be lost.")
+ .arg(name),
+ QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
+ if (reply != QMessageBox::Yes)
+ return;
+
ProfileManager::instance().create_profile(name);
const QString exe = QCoreApplication::applicationFilePath();
QProcess::startDetached(exe, {"--profile", name});
diff --git a/fincept-qt/src/screens/settings/PythonEnvSection.cpp b/fincept-qt/src/screens/settings/PythonEnvSection.cpp
index bf4178588..9109bf8b1 100644
--- a/fincept-qt/src/screens/settings/PythonEnvSection.cpp
+++ b/fincept-qt/src/screens/settings/PythonEnvSection.cpp
@@ -196,7 +196,21 @@ void PythonEnvSection::build_ui() {
pkg_table_ = new QTableWidget(0, 7, this);
pkg_table_->setHorizontalHeaderLabels(
{"", tr("Package"), tr("Venv"), tr("Required"), tr("Installed"), tr("Status"), tr("Action")});
- pkg_table_->setStyleSheet(table_ss());
+ // Per-row cell-widget styling lives here, keyed by objectName, instead of
+ // two setStyleSheet() calls per row in merge_and_populate_table(). With
+ // ~300 requirement entries that was ~600 CSS reparses on every refresh.
+ pkg_table_->setStyleSheet(
+ table_ss() +
+ QString("QCheckBox#pkgChk{background:transparent;}"
+ "QCheckBox#pkgChk::indicator{width:13px;height:13px;}"
+ "QCheckBox#pkgChk::indicator:unchecked{border:1px solid %1;background:%2;}"
+ "QCheckBox#pkgChk::indicator:checked{border:1px solid %3;background:%3;}"
+ "QPushButton#pkgInstall{background:%3;color:%4;border:none;font-size:10px;font-weight:700;}"
+ "QPushButton#pkgInstall:hover{background:%5;}"
+ "QPushButton#pkgUpgrade{background:transparent;color:%6;border:1px solid %7;font-size:10px;}"
+ "QPushButton#pkgUpgrade:hover{background:%2;}")
+ .arg(ui::colors::BORDER_BRIGHT(), ui::colors::BG_RAISED(), ui::colors::AMBER(), ui::colors::BG_BASE(),
+ ui::colors::AMBER_DIM(), ui::colors::TEXT_SECONDARY(), ui::colors::BORDER_DIM()));
pkg_table_->setSelectionMode(QAbstractItemView::NoSelection);
pkg_table_->setEditTriggers(QAbstractItemView::NoEditTriggers);
pkg_table_->setAlternatingRowColors(false);
@@ -523,13 +537,10 @@ void PythonEnvSection::merge_and_populate_table() {
pkg_table_->insertRow(i);
pkg_table_->setRowHeight(i, 28);
- // Col 0: checkbox
+ // Col 0: checkbox (styling comes from the table-level stylesheet)
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()));
+ chk->setObjectName(QStringLiteral("pkgChk"));
+ chk->setAccessibleName(tr("Select %1").arg(row.display_name));
auto* chk_cell = new QWidget(this);
auto* chk_hl = new QHBoxLayout(chk_cell);
chk_hl->setContentsMargins(4, 0, 4, 0);
@@ -568,18 +579,10 @@ void PythonEnvSection::merge_and_populate_table() {
status_item->setTextAlignment(Qt::AlignCenter);
pkg_table_->setItem(i, 5, status_item);
- // Col 6: action button
+ // Col 6: action button (styling comes from the table-level stylesheet)
auto* btn = new QPushButton(row.missing ? tr("Install") : tr("Upgrade"), this);
+ btn->setObjectName(row.missing ? QStringLiteral("pkgInstall") : QStringLiteral("pkgUpgrade"));
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);
@@ -612,11 +615,16 @@ void PythonEnvSection::on_row_action_clicked(int row) {
// ── 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;
+ // Four buckets, not two: `upgrade` is a property of the uv invocation, so a
+ // selection mixing an installed and a missing package inside one venv used
+ // to have its --upgrade flag decided by whichever row happened to come
+ // last. Missing packages then got force-upgraded (or installed packages
+ // silently not upgraded), depending on row order.
+ ActionBatch install1, install2, upgrade1, upgrade2;
+ install1.venv = upgrade1.venv = QStringLiteral("venv-numpy1");
+ install2.venv = upgrade2.venv = QStringLiteral("venv-numpy2");
+ install1.upgrade = install2.upgrade = false;
+ upgrade1.upgrade = upgrade2.upgrade = true;
for (int i = 0; i < pkg_table_->rowCount(); ++i) {
if (pkg_table_->isRowHidden(i))
@@ -631,21 +639,23 @@ QList<PythonEnvSection::ActionBatch> PythonEnvSection::build_batches_for_selecte
if (i >= all_packages_.size())
continue;
const PackageRow& row = all_packages_[i];
+ const bool v1 = (row.venv == QLatin1String("venv-numpy1"));
- if (row.venv == "venv-numpy1") {
- b1.packages << row.required_spec;
- b1.upgrade = !row.missing;
- } else {
- b2.packages << row.required_spec;
- b2.upgrade = !row.missing;
- }
+ if (row.missing)
+ (v1 ? install1 : install2).packages << row.required_spec;
+ else
+ (v1 ? upgrade1 : upgrade2).packages << row.required_spec;
}
QList<ActionBatch> result;
- if (!b1.packages.isEmpty())
- result << b1;
- if (!b2.packages.isEmpty())
- result << b2;
+ if (!install1.packages.isEmpty())
+ result << install1;
+ if (!install2.packages.isEmpty())
+ result << install2;
+ if (!upgrade1.packages.isEmpty())
+ result << upgrade1;
+ if (!upgrade2.packages.isEmpty())
+ result << upgrade2;
return result;
}
diff --git a/fincept-qt/src/screens/settings/SecuritySection.cpp b/fincept-qt/src/screens/settings/SecuritySection.cpp
index e73a3784c..2eb76db3b 100644
--- a/fincept-qt/src/screens/settings/SecuritySection.cpp
+++ b/fincept-qt/src/screens/settings/SecuritySection.cpp
@@ -19,6 +19,7 @@
#include <QShowEvent>
#include <QSignalBlocker>
#include <QString>
+#include <QTimer>
#include <QVBoxLayout>
namespace fincept::screens {
@@ -45,6 +46,27 @@ void SecuritySection::showEvent(QShowEvent* e) {
reload();
}
+void SecuritySection::hideEvent(QHideEvent* e) {
+ QWidget::hideEvent(e);
+ // Spontaneous hides are window-manager events (minimise / workspace
+ // switch); the user has not left the form.
+ if (e && e->spontaneous())
+ return;
+
+ for (QLineEdit* f : {sec_current_pin_, sec_new_pin_, sec_confirm_pin_}) {
+ if (f)
+ f->clear();
+ }
+ if (sec_pin_error_)
+ sec_pin_error_->hide();
+ if (sec_pin_success_)
+ sec_pin_success_->hide();
+ if (sec_change_pin_form_)
+ sec_change_pin_form_->setVisible(false);
+ if (sec_change_pin_btn_)
+ sec_change_pin_btn_->setText(tr("Change PIN"));
+}
+
void SecuritySection::build_ui() {
using namespace settings_styles;
using namespace settings_helpers;
@@ -115,6 +137,12 @@ void SecuritySection::build_ui() {
input->setEchoMode(QLineEdit::Password);
input->setFixedWidth(200);
input->setStyleSheet(input_ss());
+ // Match the lock screen's hardening: digits only, no predictive text,
+ // no IME candidate window, no context menu (paste-based scripting).
+ input->setInputMethodHints(Qt::ImhDigitsOnly | Qt::ImhSensitiveData | Qt::ImhNoPredictiveText |
+ Qt::ImhNoAutoUppercase | Qt::ImhHiddenText);
+ input->setContextMenuPolicy(Qt::NoContextMenu);
+ input->setAccessibleName(placeholder);
return input;
};
@@ -154,6 +182,16 @@ void SecuritySection::build_ui() {
save_pin_btn_->setStyleSheet(btn_primary_ss());
cpfl->addWidget(save_pin_btn_);
+ // Enter anywhere in the change-PIN form submits it; explicit tab order so
+ // the three fields chain into the Update button.
+ for (QLineEdit* f : {sec_current_pin_, sec_new_pin_, sec_confirm_pin_})
+ connect(f, &QLineEdit::returnPressed, save_pin_btn_, &QPushButton::click);
+ setTabOrder(sec_current_pin_, sec_new_pin_);
+ setTabOrder(sec_new_pin_, sec_confirm_pin_);
+ setTabOrder(sec_confirm_pin_, save_pin_btn_);
+ save_pin_btn_->setAccessibleName(tr("Update PIN"));
+ sec_change_pin_btn_->setAccessibleName(tr("Change PIN"));
+
sec_change_pin_form_->hide();
vl->addWidget(sec_change_pin_form_);
@@ -294,6 +332,20 @@ void SecuritySection::build_ui() {
guard.set_timeout_minutes(minutes);
guard.set_enabled(autolock && pm.has_pin());
+ if (save_status_) {
+ if (autolock && !pm.has_pin()) {
+ save_status_->setText(tr("Saved — but auto-lock stays off until you set a PIN."));
+ save_status_->setStyleSheet(
+ QString("color:%1;background:transparent;").arg(ui::colors::WARNING()));
+ } else {
+ save_status_->setText(tr("Security settings saved."));
+ save_status_->setStyleSheet(
+ QString("color:%1;background:transparent;").arg(ui::colors::POSITIVE()));
+ }
+ save_status_->show();
+ QTimer::singleShot(4000, save_status_, &QLabel::hide);
+ }
+
LOG_INFO("Settings", QString("Security settings saved: autolock=%1, timeout=%2min, has_pin=%3")
.arg(autolock)
.arg(minutes)
@@ -301,6 +353,11 @@ void SecuritySection::build_ui() {
});
vl->addWidget(save_btn_);
+ save_status_ = new QLabel;
+ save_status_->setWordWrap(true);
+ save_status_->hide();
+ vl->addWidget(save_status_);
+
// ── AUDIT LOG ─────────────────────────────────────────────────────────────
vl->addSpacing(16);
title_audit_ = new QLabel(tr("AUDIT LOG"));
diff --git a/fincept-qt/src/screens/settings/SecuritySection.h b/fincept-qt/src/screens/settings/SecuritySection.h
index 28e2dea96..81cf97b01 100644
--- a/fincept-qt/src/screens/settings/SecuritySection.h
+++ b/fincept-qt/src/screens/settings/SecuritySection.h
@@ -5,10 +5,12 @@
#include <QCheckBox>
#include <QComboBox>
#include <QEvent>
+#include <QHideEvent>
#include <QLabel>
#include <QLineEdit>
#include <QListWidget>
#include <QPushButton>
+#include <QShowEvent>
#include <QWidget>
namespace fincept::screens {
@@ -23,6 +25,10 @@ class SecuritySection : public QWidget {
protected:
void showEvent(QShowEvent* e) override;
+ /// Wipe the three PIN entry fields and collapse the change-PIN form when
+ /// the section leaves view — a typed-but-unsubmitted PIN must not sit in a
+ /// QLineEdit for the rest of the session.
+ void hideEvent(QHideEvent* e) override;
void changeEvent(QEvent* event) override;
private:
@@ -57,6 +63,10 @@ class SecuritySection : public QWidget {
QLabel* audit_note_ = nullptr;
QPushButton* save_pin_btn_ = nullptr;
QPushButton* save_btn_ = nullptr;
+ /// Inline confirmation / warning for the "Save Security Settings" button.
+ /// Saving previously produced no visible feedback at all, and enabling
+ /// auto-lock without a configured PIN silently did nothing.
+ QLabel* save_status_ = nullptr;
QPushButton* refresh_audit_btn_ = nullptr;
QLabel* row_pin_status_lbl_ = nullptr;
diff --git a/fincept-qt/src/screens/settings/SettingsScreen.cpp b/fincept-qt/src/screens/settings/SettingsScreen.cpp
index e4ab47468..8fc64d7c2 100644
--- a/fincept-qt/src/screens/settings/SettingsScreen.cpp
+++ b/fincept-qt/src/screens/settings/SettingsScreen.cpp
@@ -57,7 +57,16 @@ SettingsScreen::SettingsScreen(QWidget* parent) : QWidget(parent) {
nav_title_ = new QLabel;
nav_title_->setStyleSheet(section_title_ss());
nvl->addWidget(nav_title_);
- nvl->addSpacing(12);
+ nvl->addSpacing(6);
+
+ nav_filter_ = new QLineEdit;
+ nav_filter_->setFixedHeight(26);
+ nav_filter_->setClearButtonEnabled(true);
+ nav_filter_->setStyleSheet(input_ss());
+ nav_filter_->setAccessibleName(tr("Search settings"));
+ connect(nav_filter_, &QLineEdit::textChanged, this, &SettingsScreen::apply_nav_filter);
+ nvl->addWidget(nav_filter_);
+ nvl->addSpacing(6);
// ── Section factories ────────────────────────────────────────────────────
// One factory per stack index. Used at construction AND by the language-
@@ -85,7 +94,7 @@ SettingsScreen::SettingsScreen(QWidget* parent) : QWidget(parent) {
for (const auto& factory : section_factories_)
sections_->addWidget(factory());
- auto make_btn = [&](const QString& source_key, int idx) {
+ auto make_btn = [&](const QString& source_key, int idx, const QString& keywords = {}) {
auto* btn = new QPushButton;
btn->setFixedHeight(32);
btn->setCheckable(true);
@@ -101,7 +110,7 @@ SettingsScreen::SettingsScreen(QWidget* parent) : QWidget(parent) {
ScreenStateManager::instance().notify_changed(this);
});
nvl->addWidget(btn);
- nav_buttons_.append({btn, source_key});
+ nav_buttons_.append({btn, source_key, keywords});
return btn;
};
@@ -115,25 +124,38 @@ SettingsScreen::SettingsScreen(QWidget* parent) : QWidget(parent) {
scope_header_keys_.append(key);
};
+ // The keyword strings are search aliases only — never displayed, so they
+ // stay in English (the filter also matches the translated label text).
add_scope_header(QStringLiteral("SHELL"));
- auto* first = make_btn(QStringLiteral("General"), 14);
- make_btn(QStringLiteral("Appearance"), 1);
- make_btn(QStringLiteral("Notifications"), 2);
- make_btn(QStringLiteral("Keybindings"), 10);
- make_btn(QStringLiteral("Voice"), 13);
- make_btn(QStringLiteral("Logging"), 7);
- make_btn(QStringLiteral("Developer"), 12);
+ auto* first = make_btn(QStringLiteral("General"), 14,
+ QStringLiteral("language locale currency window close launchpad quit"));
+ make_btn(QStringLiteral("Appearance"), 1, QStringLiteral("theme font size family density ticker chat bubble "
+ "animation typography interface"));
+ make_btn(QStringLiteral("Notifications"), 2,
+ QStringLiteral("telegram discord slack email smtp whatsapp twilio pushover ntfy pushbullet gotify "
+ "mattermost teams webhook pagerduty opsgenie sms alerts price news order fill"));
+ make_btn(QStringLiteral("Keybindings"), 10, QStringLiteral("shortcut hotkey keyboard rebind keys"));
+ make_btn(QStringLiteral("Voice"), 13,
+ QStringLiteral("speech stt tts deepgram microphone mic clap wake trigger aura pyttsx3"));
+ make_btn(QStringLiteral("Logging"), 7, QStringLiteral("log level debug trace json log file tags diagnostics"));
+ make_btn(QStringLiteral("Developer"), 12, QStringLiteral("datahub inspector agentic experimental devtools"));
add_scope_header(QStringLiteral("PROFILE"));
- make_btn(QStringLiteral("Profiles"), 9);
- make_btn(QStringLiteral("Credentials"), 0);
- make_btn(QStringLiteral("Security"), 8);
- make_btn(QStringLiteral("Data Sources"), 4);
- make_btn(QStringLiteral("LLM Config"), 5);
- make_btn(QStringLiteral("MCP Servers"), 6);
- make_btn(QStringLiteral("Python Env"), 11);
- make_btn(QStringLiteral("Storage & Cache"), 3);
- make_btn(QStringLiteral("Cloud Sync"), 15);
+ make_btn(QStringLiteral("Profiles"), 9, QStringLiteral("account switch multi profile workspace isolation"));
+ make_btn(QStringLiteral("Credentials"), 0,
+ QStringLiteral("api key secret token keychain alpha vantage polygon fred binance kraken finnhub "
+ "polymarket tiingo quandl databento newsapi iex"));
+ make_btn(QStringLiteral("Security"), 8,
+ QStringLiteral("pin lock auto-lock timeout inactivity audit log attempts lockout minimize"));
+ make_btn(QStringLiteral("Data Sources"), 4, QStringLiteral("connections connectors websocket rest sql providers"));
+ make_btn(QStringLiteral("LLM Config"), 5,
+ QStringLiteral("ai model openai anthropic ollama groq provider profile temperature tokens system "
+ "prompt tool rounds mcp tools"));
+ make_btn(QStringLiteral("MCP Servers"), 6, QStringLiteral("model context protocol tools external server"));
+ make_btn(QStringLiteral("Python Env"), 11, QStringLiteral("packages venv pip uv numpy libraries install upgrade"));
+ make_btn(QStringLiteral("Storage & Cache"), 3,
+ QStringLiteral("disk database sqlite sql console cache clear delete data danger zone workspaces"));
+ make_btn(QStringLiteral("Cloud Sync"), 15, QStringLiteral("backup sync account devices domains credits"));
first->setChecked(true);
sections_->setCurrentIndex(14);
@@ -162,9 +184,29 @@ void SettingsScreen::changeEvent(QEvent* e) {
QWidget::changeEvent(e);
}
+void SettingsScreen::apply_nav_filter(const QString& text) {
+ const QString needle = text.trimmed();
+ const bool filtering = !needle.isEmpty();
+
+ for (const auto& nb : nav_buttons_) {
+ if (!nb.btn)
+ continue;
+ const bool match = !filtering || nb.btn->text().contains(needle, Qt::CaseInsensitive) ||
+ nb.source_key.contains(needle, Qt::CaseInsensitive) ||
+ nb.keywords.contains(needle, Qt::CaseInsensitive);
+ nb.btn->setVisible(match);
+ }
+ for (auto* h : scope_headers_) {
+ if (h)
+ h->setVisible(!filtering);
+ }
+}
+
void SettingsScreen::retranslateUi() {
if (nav_title_)
nav_title_->setText(tr("SETTINGS"));
+ if (nav_filter_)
+ nav_filter_->setPlaceholderText(tr("Search settings…"));
for (const auto& nb : nav_buttons_) {
if (nb.btn)
nb.btn->setText(tr(nb.source_key.toUtf8().constData()));
@@ -226,8 +268,15 @@ void SettingsScreen::refresh_theme() {
if (nav_) {
nav_->setStyleSheet(QString("background:%1;border-right:1px solid %2;")
.arg(ui::colors::BG_SURFACE(), ui::colors::BORDER_DIM()));
- for (auto* btn : nav_->findChildren<QPushButton*>())
- btn->setStyleSheet(nav_btn_ss());
+ // Walk our own list rather than every QPushButton descendant, so the
+ // nav style is never applied to embedded controls (e.g. the filter
+ // box's clear button).
+ for (const auto& nb : nav_buttons_) {
+ if (nb.btn)
+ nb.btn->setStyleSheet(nav_btn_ss());
+ }
+ if (nav_filter_)
+ nav_filter_->setStyleSheet(input_ss());
// Re-apply scope-header colour. Walk our explicit list rather than
// text-matching, so the headers' style survives translation to
// languages where the source label no longer literally reads "SHELL".
diff --git a/fincept-qt/src/screens/settings/SettingsScreen.h b/fincept-qt/src/screens/settings/SettingsScreen.h
index 833f6dd9e..dd0081b78 100644
--- a/fincept-qt/src/screens/settings/SettingsScreen.h
+++ b/fincept-qt/src/screens/settings/SettingsScreen.h
@@ -11,6 +11,7 @@
#include <QHideEvent>
#include <QLabel>
+#include <QLineEdit>
#include <QList>
#include <QPushButton>
#include <QShowEvent>
@@ -56,11 +57,23 @@ class SettingsScreen : public QWidget, public IStatefulScreen {
/// Nav button → source key map used to retranslate button labels and
/// scope headers without rebuilding the nav.
+ ///
+ /// `keywords` is a space-separated list of terms the section covers but
+ /// does not have in its label ("pin" → Security, "api key" → Credentials).
+ /// It backs the nav filter box: 16 sections spread over ~38 files are not
+ /// discoverable by reading a nav list alone.
struct NavButton {
QPushButton* btn;
QString source_key;
+ QString keywords;
};
QList<NavButton> nav_buttons_;
+
+ QLineEdit* nav_filter_ = nullptr;
+ /// Show only nav entries matching `text` (label or keywords). Scope
+ /// headers are hidden while a filter is active — with a partial list they
+ /// no longer describe what sits under them.
+ void apply_nav_filter(const QString& text);
QList<QLabel*> scope_headers_; // entries align with scope_header_keys_
QList<QString> scope_header_keys_;
diff --git a/fincept-qt/src/screens/settings/StorageSection.cpp b/fincept-qt/src/screens/settings/StorageSection.cpp
index 323f55fb3..2046484a4 100644
--- a/fincept-qt/src/screens/settings/StorageSection.cpp
+++ b/fincept-qt/src/screens/settings/StorageSection.cpp
@@ -555,7 +555,22 @@ void StorageSection::build_ui() {
.arg(ui::colors::BORDER_DIM(), ui::colors::BG_BASE(), ui::colors::BORDER_MED()));
auto* results_widget = new QWidget(this);
- results_widget->setStyleSheet("background:transparent;");
+ results_widget->setObjectName(QStringLiteral("sqlResults"));
+ // One stylesheet for the whole result grid, keyed by objectName. The
+ // previous code called setStyleSheet() on every header cell and every
+ // data cell — a 100-row × 10-column SELECT meant ~1100 CSS reparses per
+ // query execution. Every rule is selector-qualified (including the one
+ // for the container) because Qt does not accept a mix of bare
+ // declarations and rules in one sheet.
+ results_widget->setStyleSheet(QString("QWidget#sqlResults{background:transparent;}"
+ "QWidget#sqlHdrRow{background:%1;border-bottom:1px solid %2;}"
+ "QWidget#sqlRow{background:transparent;border-bottom:1px solid %2;}"
+ "QWidget#sqlRowAlt{background:%3;border-bottom:1px solid %2;}"
+ "QLabel#sqlHdrCell{color:%4;font-weight:700;background:transparent;}"
+ "QLabel#sqlCell{color:%5;background:transparent;}")
+ .arg(ui::colors::BG_RAISED(), ui::colors::BORDER_DIM(),
+ ui::colors::ROW_ALT(), ui::colors::TEXT_DIM(),
+ ui::colors::TEXT_PRIMARY()));
sql_results_layout_ = new QVBoxLayout(results_widget);
sql_results_layout_->setContentsMargins(0, 0, 0, 0);
sql_results_layout_->setSpacing(0);
@@ -648,18 +663,16 @@ void StorageSection::build_ui() {
return;
}
- // Column header
+ // Column header — styling comes from the results-widget stylesheet.
auto* hdr_row = new QWidget(this);
+ hdr_row->setObjectName(QStringLiteral("sqlHdrRow"));
hdr_row->setFixedHeight(22);
- hdr_row->setStyleSheet(QString("background:%1;border-bottom:1px solid %2;")
- .arg(ui::colors::BG_RAISED(), ui::colors::BORDER_DIM()));
auto* hhl = new QHBoxLayout(hdr_row);
hhl->setContentsMargins(6, 0, 6, 0);
hhl->setSpacing(4);
for (int c = 0; c < cols; ++c) {
auto* cl = new QLabel(rec.fieldName(c));
- cl->setStyleSheet(
- QString("color:%1;font-weight:700;background:transparent;").arg(ui::colors::TEXT_DIM()));
+ cl->setObjectName(QStringLiteral("sqlHdrCell"));
hhl->addWidget(cl, 1);
}
sql_results_layout_->addWidget(hdr_row);
@@ -667,10 +680,8 @@ void StorageSection::build_ui() {
int row_count = 0;
while (query.next() && row_count < 100) {
auto* dr = new QWidget(this);
+ dr->setObjectName((row_count % 2) ? QStringLiteral("sqlRowAlt") : QStringLiteral("sqlRow"));
dr->setFixedHeight(20);
- dr->setStyleSheet(
- QString("background:%1;border-bottom:1px solid %2;")
- .arg((row_count % 2) ? ui::colors::ROW_ALT() : "transparent", ui::colors::BORDER_DIM()));
auto* dhl = new QHBoxLayout(dr);
dhl->setContentsMargins(6, 0, 6, 0);
dhl->setSpacing(4);
@@ -679,7 +690,7 @@ void StorageSection::build_ui() {
if (val.length() > 60)
val = val.left(57) + "...";
auto* vl2 = new QLabel(val);
- vl2->setStyleSheet(QString("color:%1;background:transparent;").arg(ui::colors::TEXT_PRIMARY()));
+ vl2->setObjectName(QStringLiteral("sqlCell"));
dhl->addWidget(vl2, 1);
}
sql_results_layout_->addWidget(dr);
diff --git a/fincept-qt/src/screens/settings/VoiceConfigSection.cpp b/fincept-qt/src/screens/settings/VoiceConfigSection.cpp
index 1166b1351..e6dd3b60c 100644
--- a/fincept-qt/src/screens/settings/VoiceConfigSection.cpp
+++ b/fincept-qt/src/screens/settings/VoiceConfigSection.cpp
@@ -233,9 +233,14 @@ void VoiceConfigSection::build_ui() {
api_key_edit_->setPlaceholderText(tr("Paste your Deepgram API key"));
api_key_edit_->setStyleSheet(input_ss());
api_key_edit_->setMinimumWidth(320);
+ api_key_edit_->setInputMethodHints(Qt::ImhSensitiveData | Qt::ImhNoPredictiveText | Qt::ImhNoAutoUppercase);
+ api_key_edit_->setDragEnabled(false);
+ api_key_edit_->setAcceptDrops(false);
+ api_key_edit_->setAccessibleName(tr("Deepgram API key"));
show_key_btn_ = new QPushButton(tr("Show"));
show_key_btn_->setStyleSheet(btn_secondary_ss());
show_key_btn_->setCheckable(true);
+ show_key_btn_->setAccessibleName(tr("Show or hide the Deepgram API key"));
key_hl->addWidget(key_lbl_);
key_hl->addStretch();
key_hl->addWidget(api_key_edit_);
@@ -354,6 +359,23 @@ void VoiceConfigSection::reload() {
set_status({}, false);
}
+void VoiceConfigSection::showEvent(QShowEvent* e) {
+ QWidget::showEvent(e);
+ reload();
+}
+
+void VoiceConfigSection::hideEvent(QHideEvent* e) {
+ QWidget::hideEvent(e);
+ if (e && e->spontaneous())
+ return;
+ if (show_key_btn_ && show_key_btn_->isChecked()) {
+ show_key_btn_->setChecked(false);
+ show_key_btn_->setText(tr("Show"));
+ }
+ if (api_key_edit_)
+ api_key_edit_->setEchoMode(QLineEdit::Password);
+}
+
void VoiceConfigSection::apply_provider_visibility() {
const QString stt = stt_provider_combo_->currentData().toString();
const QString tts = tts_provider_combo_->currentData().toString();
@@ -461,6 +483,9 @@ void VoiceConfigSection::on_test() {
QNetworkRequest req(QUrl("https://api.deepgram.com/v1/projects"));
req.setRawHeader("Authorization", ("Token " + api_key).toUtf8());
req.setRawHeader("Accept", "application/json");
+ // Without a timeout a stalled connection leaves the Test button disabled
+ // for the rest of the session with no way to retry.
+ req.setTransferTimeout(15000);
QPointer<VoiceConfigSection> self = this;
QNetworkReply* reply = nam->get(req);
diff --git a/fincept-qt/src/screens/settings/VoiceConfigSection.h b/fincept-qt/src/screens/settings/VoiceConfigSection.h
index 6bc11f5a1..cf328acea 100644
--- a/fincept-qt/src/screens/settings/VoiceConfigSection.h
+++ b/fincept-qt/src/screens/settings/VoiceConfigSection.h
@@ -12,9 +12,11 @@
#include <QComboBox>
#include <QDoubleSpinBox>
#include <QEvent>
+#include <QHideEvent>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
+#include <QShowEvent>
#include <QWidget>
namespace fincept::screens {
@@ -34,6 +36,12 @@ class VoiceConfigSection : public QWidget {
protected:
void changeEvent(QEvent* event) override;
+ /// Re-read AppConfig + SecureStorage each time the section is shown, so a
+ /// key rotated elsewhere (or by an MCP tool) is reflected here.
+ void showEvent(QShowEvent* e) override;
+ /// Re-mask the API key when the section leaves view — pressing "Show" used
+ /// to leave the secret rendered in plaintext for the rest of the session.
+ void hideEvent(QHideEvent* e) override;
private slots:
void on_provider_changed();
diff --git a/fincept-qt/src/screens/setup/SetupScreen.cpp b/fincept-qt/src/screens/setup/SetupScreen.cpp
index 2ee1d07e5..6fefb0966 100644
--- a/fincept-qt/src/screens/setup/SetupScreen.cpp
+++ b/fincept-qt/src/screens/setup/SetupScreen.cpp
@@ -495,6 +495,16 @@ void SetupScreen::mark_step_active(const QString& key) {
// ─────────────────────────────────────────────────────────────────────────────
void SetupScreen::on_begin_setup() {
+ // When the environment is already fully installed the button is the exit,
+ // not the installer. Previously this state disabled the button entirely,
+ // leaving the user stranded on the setup screen until the 45-second Skip
+ // link appeared.
+ if (begin_btn_state_ == BeginBtnState::Launch || begin_btn_state_ == BeginBtnState::AlreadyComplete) {
+ LOG_INFO("SetupScreen", "Environment already complete — launching");
+ emit setup_complete();
+ return;
+ }
+
begin_btn_->setEnabled(false);
begin_btn_state_ = BeginBtnState::SettingUp;
update_begin_button();
@@ -644,6 +654,11 @@ void SetupScreen::prefill_completed_steps() {
QPointer<SetupScreen> self = this;
(void)QtConcurrent::run([self]() {
const auto status = python::PythonSetupManager::instance().check_status();
+ // check_status() can take ~15s; the screen may already be gone. Passing
+ // a null context to invokeMethod is undefined behaviour, so re-check the
+ // guard before dispatching, not just inside the posted lambda.
+ if (!self)
+ return;
QMetaObject::invokeMethod(
self,
[self, status]() {
@@ -671,8 +686,10 @@ void SetupScreen::prefill_completed_steps() {
if (all_done) {
self->subtitle_state_ = SubtitleState::AlreadyConfigured;
- self->begin_btn_state_ = BeginBtnState::AlreadyComplete;
- self->begin_btn_->setEnabled(false);
+ // Offer LAUNCH rather than a disabled "ALREADY COMPLETE" —
+ // on_begin_setup() short-circuits to setup_complete() here.
+ self->begin_btn_state_ = BeginBtnState::Launch;
+ self->begin_btn_->setEnabled(true);
self->status_state_ = StatusState::Custom;
self->status_detail_ = self->tr("Everything is installed and ready to go.");
} else if (any_done) {
diff --git a/fincept-qt/src/screens/support/SupportScreen.h b/fincept-qt/src/screens/support/SupportScreen.h
index 85f20fde8..20fdb1add 100644
--- a/fincept-qt/src/screens/support/SupportScreen.h
+++ b/fincept-qt/src/screens/support/SupportScreen.h
@@ -1,5 +1,6 @@
#pragma once
#include <QComboBox>
+#include <QJsonArray>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
@@ -85,6 +86,12 @@ class SupportScreen : public QWidget {
bool selected_is_closed_ = false;
QPushButton* active_row_btn_ = nullptr; // currently highlighted sidebar row
+ /// Last successfully-fetched ticket set (plus the demo row). Cached so the
+ /// search box and status filter can re-render the sidebar without a network
+ /// round-trip.
+ QJsonArray all_tickets_;
+ bool load_failed_ = false;
+
// ── Builders ─────────────────────────────────────────────────────────────
QWidget* build_sidebar();
QWidget* build_empty_state();
@@ -100,6 +107,11 @@ class SupportScreen : public QWidget {
static QString priority_color(const QString& p);
static QString status_label(const QString& s);
+ /// Re-render the sidebar rows from all_tickets_, honouring the search box
+ /// and the status filter combo. Called by load_tickets() and whenever
+ /// either control changes — no refetch.
+ void rebuild_ticket_rows();
+
// ── Slots ─────────────────────────────────────────────────────────────────
void load_tickets();
void on_create_ticket();
diff --git a/fincept-qt/src/screens/support/SupportScreen_Actions.cpp b/fincept-qt/src/screens/support/SupportScreen_Actions.cpp
index 7320930f3..6f8f4a792 100644
--- a/fincept-qt/src/screens/support/SupportScreen_Actions.cpp
+++ b/fincept-qt/src/screens/support/SupportScreen_Actions.cpp
@@ -16,6 +16,8 @@
#include <QHBoxLayout>
#include <QJsonArray>
#include <QJsonObject>
+#include <QMessageBox>
+#include <QPointer>
#include <QScrollArea>
#include <QScrollBar>
#include <QSplitter>
@@ -30,15 +32,11 @@ using namespace fincept::screens::support_internal;
void SupportScreen::load_tickets() {
set_busy(true);
- auth::UserApi::instance().get_tickets([this](auth::ApiResponse r) {
- set_busy(false);
-
- auto* lay = qobject_cast<QVBoxLayout*>(ticket_container_->layout());
- if (!lay)
- return;
- while (lay->count() > 1)
- delete lay->takeAt(0)->widget();
- active_row_btn_ = nullptr;
+ QPointer<SupportScreen> self(this);
+ auth::UserApi::instance().get_tickets([self](auth::ApiResponse r) {
+ if (!self)
+ return; // screen closed while the request was in flight
+ self->set_busy(false);
// Robust response unwrap:
// API may return: {"tickets":[...]} or {"data":{"tickets":[...]}}
@@ -92,19 +90,70 @@ void SupportScreen::load_tickets() {
else if (st == "resolved" || st == "closed")
++done_c;
}
- stat_total_->setText(QString::number(all.size()));
- stat_open_->setText(QString::number(open_c));
- stat_resolved_->setText(QString::number(done_c));
-
- if (all.isEmpty()) {
- auto* empty = lbl(tr("No tickets yet"), ui::colors::TEXT_TERTIARY(), 12);
- empty->setAlignment(Qt::AlignCenter);
- empty->setContentsMargins(0, 40, 0, 0);
- lay->insertWidget(0, empty);
- return;
+ self->stat_total_->setText(QString::number(all.size()));
+ self->stat_open_->setText(QString::number(open_c));
+ self->stat_resolved_->setText(QString::number(done_c));
+
+ self->all_tickets_ = all;
+ self->load_failed_ = !r.success;
+ self->rebuild_ticket_rows();
+ });
+}
+
+// ── rebuild_ticket_rows ───────────────────────────────────────────────────────
+// Renders all_tickets_ into the sidebar, applying the search box and the status
+// filter combo. Both of those controls previously existed but were never
+// connected to anything — typing in the box or changing the filter did nothing.
+
+void SupportScreen::rebuild_ticket_rows() {
+ auto* lay = qobject_cast<QVBoxLayout*>(ticket_container_->layout());
+ if (!lay)
+ return;
+ while (lay->count() > 1)
+ delete lay->takeAt(0)->widget();
+ active_row_btn_ = nullptr;
+
+ const QString needle = search_input_ ? search_input_->text().trimmed().toLower() : QString();
+ // Combo order matches retranslateUi(): All / Open / In Progress / Pending /
+ // Resolved / Closed. Index 0 means "no status filter".
+ static const char* kFilterStatus[] = {"", "open", "in_progress", "pending", "resolved", "closed"};
+ const int fi = filter_combo_ ? filter_combo_->currentIndex() : 0;
+ const QString want_status = (fi > 0 && fi < static_cast<int>(sizeof(kFilterStatus) / sizeof(kFilterStatus[0])))
+ ? QString::fromLatin1(kFilterStatus[fi])
+ : QString();
+
+ QJsonArray all;
+ for (const auto& v : all_tickets_) {
+ const auto obj = v.toObject();
+ if (!want_status.isEmpty() && obj["status"].toString().toLower() != want_status)
+ continue;
+ if (!needle.isEmpty()) {
+ const QString hay = (obj["subject"].toString() + ' ' + obj["category"].toString() + ' ' +
+ obj["description"].toString() + ' ' + obj["id"].toVariant().toString())
+ .toLower();
+ if (!hay.contains(needle))
+ continue;
}
+ all.append(v);
+ }
+
+ if (all.isEmpty()) {
+ QString msg;
+ if (load_failed_)
+ msg = tr("Could not load tickets.\nCheck your connection and press ↻ to retry.");
+ else if (!needle.isEmpty() || !want_status.isEmpty())
+ msg = tr("No tickets match this search or filter.");
+ else
+ msg = tr("No tickets yet");
+ auto* empty = lbl(msg, ui::colors::TEXT_TERTIARY(), 12, false, true);
+ empty->setAlignment(Qt::AlignCenter);
+ empty->setContentsMargins(0, 40, 0, 0);
+ lay->insertWidget(0, empty);
+ return;
+ }
- // Build sidebar rows
+ // Build sidebar rows
+ {
for (const auto& v : all) {
auto obj = v.toObject();
QString id = obj["id"].toVariant().toString();
@@ -233,10 +282,19 @@ void SupportScreen::load_tickets() {
mcl2->insertWidget(mcl2->count() - 1, m);
} else {
set_busy(true);
- auth::UserApi::instance().get_ticket_details(id_int, [this](auth::ApiResponse dr) {
+ QPointer<SupportScreen> guard(this);
+ auth::UserApi::instance().get_ticket_details(id_int, [this, guard](auth::ApiResponse dr) {
+ if (!guard)
+ return;
set_busy(false);
- if (!dr.success)
+ if (!dr.success) {
+ auto* mcl_err = qobject_cast<QVBoxLayout*>(messages_container_->layout());
+ if (mcl_err)
+ mcl_err->insertWidget(0, lbl(tr("Could not load this conversation. "
+ "Press ↻ to retry."),
+ ui::colors::NEGATIVE(), 11, false, true));
return;
+ }
// Robust message unwrap — try all known shapes
auto dr_data = dr.data;
@@ -309,7 +367,7 @@ void SupportScreen::load_tickets() {
lay->insertWidget(lay->count() - 1, btn);
}
- });
+ }
}
// ── on_create_ticket ──────────────────────────────────────────────────────────
@@ -317,8 +375,24 @@ void SupportScreen::load_tickets() {
void SupportScreen::on_create_ticket() {
QString subject = subject_input_->text().trimmed();
QString desc = desc_input_->toPlainText().trimmed();
- if (subject.isEmpty() || desc.isEmpty())
+ // Silently doing nothing when a required field is blank looks like a broken
+ // button — tell the user which field is missing and focus it.
+ if (subject.isEmpty()) {
+ QMessageBox::information(this, tr("Subject required"), tr("Please enter a short subject for your ticket."));
+ subject_input_->setFocus();
+ return;
+ }
+ if (desc.isEmpty()) {
+ QMessageBox::information(this, tr("Description required"), tr("Please describe the issue you are reporting."));
+ desc_input_->setFocus();
return;
+ }
+ if (desc.length() > 2000) {
+ QMessageBox::information(this, tr("Description too long"),
+ tr("Descriptions are limited to 2000 characters (currently %1).").arg(desc.length()));
+ desc_input_->setFocus();
+ return;
+ }
set_busy(true);
create_btn_->setText(tr("Submitting…"));
@@ -328,14 +402,24 @@ void SupportScreen::on_create_ticket() {
const QString cat_key = category_combo_->currentData().toString();
const QString pri_key = priority_combo_->currentData().toString();
- auth::UserApi::instance().create_ticket(subject, desc, cat_key, pri_key, [this](auth::ApiResponse r) {
- set_busy(false);
- create_btn_->setText(tr("Submit Ticket →"));
+ QPointer<SupportScreen> self(this);
+ auth::UserApi::instance().create_ticket(subject, desc, cat_key, pri_key, [self](auth::ApiResponse r) {
+ if (!self)
+ return;
+ self->set_busy(false);
+ self->create_btn_->setText(tr("Submit Ticket →"));
if (r.success) {
- subject_input_->clear();
- desc_input_->clear();
- content_stack_->setCurrentIndex(0);
- load_tickets();
+ self->subject_input_->clear();
+ self->desc_input_->clear();
+ self->content_stack_->setCurrentIndex(0);
+ self->load_tickets();
+ } else {
+ // The old code just returned — the ticket text stayed on screen with
+ // no indication that submission had failed.
+ QMessageBox::warning(self, tr("Could not create ticket"),
+ r.error.isEmpty() ? tr("The ticket could not be submitted. Please check your "
+ "connection and try again — your text has been kept.")
+ : tr("The ticket could not be submitted:\n%1").arg(r.error));
}
});
}
@@ -352,11 +436,19 @@ void SupportScreen::on_send_message() {
set_busy(true);
send_btn_->setText(tr("Sending…"));
- auth::UserApi::instance().add_ticket_message(selected_ticket_id_, msg, [this, msg](auth::ApiResponse r) {
+ QPointer<SupportScreen> self(this);
+ auth::UserApi::instance().add_ticket_message(selected_ticket_id_, msg, [this, self, msg](auth::ApiResponse r) {
+ if (!self)
+ return;
set_busy(false);
send_btn_->setText(tr("Send Reply →"));
- if (!r.success)
+ if (!r.success) {
+ QMessageBox::warning(this, tr("Reply not sent"),
+ r.error.isEmpty() ? tr("Your reply could not be sent. It has been kept in the "
+ "box so you can try again.")
+ : tr("Your reply could not be sent:\n%1").arg(r.error));
return;
+ }
msg_input_->clear();
auto* mcl = qobject_cast<QVBoxLayout*>(messages_container_->layout());
@@ -390,11 +482,25 @@ void SupportScreen::on_send_message() {
void SupportScreen::on_close_ticket() {
if (selected_ticket_id_ < 0)
return;
+ // Closing a ticket is destructive from the user's point of view (the reply
+ // box disappears) — confirm first.
+ if (QMessageBox::question(this, tr("Close ticket"),
+ tr("Close ticket #%1? You can reopen it later.").arg(selected_ticket_id_),
+ QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes)
+ return;
+
set_busy(true);
- auth::UserApi::instance().update_ticket_status(selected_ticket_id_, "closed", [this](auth::ApiResponse r) {
+ QPointer<SupportScreen> self(this);
+ auth::UserApi::instance().update_ticket_status(selected_ticket_id_, "closed", [this, self](auth::ApiResponse r) {
+ if (!self)
+ return;
set_busy(false);
- if (!r.success)
+ if (!r.success) {
+ QMessageBox::warning(this, tr("Could not close ticket"),
+ r.error.isEmpty() ? tr("The ticket status could not be updated.")
+ : tr("The ticket status could not be updated:\n%1").arg(r.error));
return;
+ }
selected_is_closed_ = true;
close_btn_->hide();
reopen_btn_->show();
@@ -408,10 +514,17 @@ void SupportScreen::on_reopen_ticket() {
if (selected_ticket_id_ < 0)
return;
set_busy(true);
- auth::UserApi::instance().update_ticket_status(selected_ticket_id_, "open", [this](auth::ApiResponse r) {
+ QPointer<SupportScreen> self(this);
+ auth::UserApi::instance().update_ticket_status(selected_ticket_id_, "open", [this, self](auth::ApiResponse r) {
+ if (!self)
+ return;
set_busy(false);
- if (!r.success)
+ if (!r.success) {
+ QMessageBox::warning(this, tr("Could not reopen ticket"),
+ r.error.isEmpty() ? tr("The ticket status could not be updated.")
+ : tr("The ticket status could not be updated:\n%1").arg(r.error));
return;
+ }
selected_is_closed_ = false;
reopen_btn_->hide();
close_btn_->show();
diff --git a/fincept-qt/src/screens/support/SupportScreen_Layout.cpp b/fincept-qt/src/screens/support/SupportScreen_Layout.cpp
index 0a8766d64..5431da7cd 100644
--- a/fincept-qt/src/screens/support/SupportScreen_Layout.cpp
+++ b/fincept-qt/src/screens/support/SupportScreen_Layout.cpp
@@ -16,8 +16,10 @@
#include <QHBoxLayout>
#include <QJsonArray>
#include <QJsonObject>
+#include <QKeySequence>
#include <QScrollArea>
#include <QScrollBar>
+#include <QShortcut>
#include <QSplitter>
#include <QTimer>
#include <QUrl>
@@ -54,18 +56,28 @@ QWidget* SupportScreen::build_sidebar() {
connect(new_ticket_btn_, &QPushButton::clicked, this, [this]() { content_stack_->setCurrentIndex(1); });
hl->addWidget(new_ticket_btn_);
- // Search — placeholder set in retranslateUi
+ // Search — placeholder set in retranslateUi.
+ // Previously created but never connected to anything: typing in the box
+ // did nothing at all. It now filters the cached ticket list live.
search_input_ = new QLineEdit;
search_input_->setFixedHeight(30);
search_input_->setStyleSheet(SS_INPUT());
+ search_input_->setClearButtonEnabled(true);
+ search_input_->setAccessibleName(tr("Search tickets"));
+ connect(search_input_, &QLineEdit::textChanged, this, [this]() { rebuild_ticket_rows(); });
hl->addWidget(search_input_);
- // Filter — items populated in retranslateUi
+ // Filter — items populated in retranslateUi. Also previously inert.
filter_combo_ = new QComboBox;
filter_combo_->setFixedHeight(28);
filter_combo_->setStyleSheet(SS_INPUT());
+ filter_combo_->setAccessibleName(tr("Filter tickets by status"));
+ connect(filter_combo_, &QComboBox::currentIndexChanged, this, [this]() { rebuild_ticket_rows(); });
hl->addWidget(filter_combo_);
+ setTabOrder(new_ticket_btn_, search_input_);
+ setTabOrder(search_input_, filter_combo_);
+
vl->addWidget(hdr);
}
@@ -220,6 +232,7 @@ QWidget* SupportScreen::build_create_page() {
subject_input_->setPlaceholderText(tr("Brief summary of your issue"));
subject_input_->setFixedHeight(38);
subject_input_->setStyleSheet(SS_INPUT());
+ subject_input_->setAccessibleName(tr("Ticket subject"));
add_field(tr("Subject"), subject_input_, true);
// Category + Priority side by side
@@ -285,8 +298,15 @@ QWidget* SupportScreen::build_create_page() {
desc_input_->setMinimumHeight(160);
desc_input_->setMaximumHeight(280);
desc_input_->setStyleSheet(SS_INPUT());
+ desc_input_->setAccessibleName(tr("Ticket description"));
cl->addWidget(desc_input_);
+ // Explicit tab order across the form — the default order follows widget
+ // construction, which interleaves the two side-by-side combos oddly.
+ setTabOrder(subject_input_, category_combo_);
+ setTabOrder(category_combo_, priority_combo_);
+ setTabOrder(priority_combo_, desc_input_);
+
connect(desc_input_, &QTextEdit::textChanged, this, [this]() {
int n = desc_input_->toPlainText().length();
char_count_lbl_->setText(tr("%1 / 2000").arg(n));
@@ -337,7 +357,9 @@ QWidget* SupportScreen::build_create_page() {
tr("✓ One issue per ticket — easier to track and resolve"),
tr("✓ Include your OS, version, and any error messages"),
tr("✓ Describe steps to reproduce if it's a bug"),
- tr("✓ Billing questions resolved within 4 hours"),
+ // No stated turnaround here: the previous "resolved within 4 hours"
+ // was an unbacked SLA promise on a support surface.
+ tr("✓ Attach the crash-dump path from About → Diagnostics if the app crashed"),
};
for (const auto& t : tip_items) {
auto* tl = lbl(t, ui::colors::TEXT_SECONDARY(), 11, false, true);
@@ -494,14 +516,25 @@ QWidget* SupportScreen::build_detail_page() {
msg_input_->setPlaceholderText(tr("Type your reply…"));
msg_input_->setFixedHeight(80);
msg_input_->setStyleSheet(SS_INPUT());
+ msg_input_->setAccessibleName(tr("Reply message"));
rbl->addWidget(msg_input_);
+ // The header above advertises "Ctrl+Enter to send" but no such shortcut
+ // existed — pressing it did nothing. Scope it to the reply box so it
+ // can't fire while the user is elsewhere on the screen.
+ for (auto seq : {QKeySequence(Qt::CTRL | Qt::Key_Return), QKeySequence(Qt::CTRL | Qt::Key_Enter)}) {
+ auto* sc = new QShortcut(seq, msg_input_);
+ sc->setContext(Qt::WidgetShortcut);
+ connect(sc, &QShortcut::activated, this, &SupportScreen::on_send_message);
+ }
+
auto* send_row = new QHBoxLayout;
send_row->addStretch();
send_btn_ = new QPushButton(tr("Send Reply →"));
send_btn_->setFixedHeight(34);
send_btn_->setMinimumWidth(140);
send_btn_->setStyleSheet(SS_BTN_SUCCESS());
+ send_btn_->setAccessibleName(tr("Send reply"));
connect(send_btn_, &QPushButton::clicked, this, &SupportScreen::on_send_message);
send_row->addWidget(send_btn_);
rbl->addLayout(send_row);
diff --git a/fincept-qt/src/screens/surface_analytics/SurfaceAnalyticsScreen.cpp b/fincept-qt/src/screens/surface_analytics/SurfaceAnalyticsScreen.cpp
index 16ae71e09..ee589edee 100644
--- a/fincept-qt/src/screens/surface_analytics/SurfaceAnalyticsScreen.cpp
+++ b/fincept-qt/src/screens/surface_analytics/SurfaceAnalyticsScreen.cpp
@@ -73,6 +73,19 @@ float SurfaceAnalyticsScreen::spot_for(const QString& sym) const {
return 100.0f;
}
+void SurfaceAnalyticsScreen::mark_chart_real(ChartType type) {
+ real_data_charts_.insert(static_cast<int>(type));
+ sync_synthetic_badge();
+}
+
+void SurfaceAnalyticsScreen::sync_synthetic_badge() {
+ const bool synthetic = !real_data_charts_.contains(static_cast<int>(active_chart_));
+ if (control_panel_)
+ control_panel_->mark_synthetic(synthetic);
+ if (demo_banner_)
+ demo_banner_->setVisible(synthetic);
+}
+
void SurfaceAnalyticsScreen::refresh_provider_status() {
if (!control_panel_)
return;
@@ -149,6 +162,9 @@ void SurfaceAnalyticsScreen::retranslateUi() {
btn_table_->setText(tr("TABLE"));
if (btn_line_)
btn_line_->setText(tr("LINE"));
+ if (demo_banner_)
+ demo_banner_->setText(tr("SAMPLE DATA — synthetic values, not a live market surface. "
+ "Do not trade or quote from this."));
}
// ── IStatefulScreen ───────────────────────────────────────────────────────────
diff --git a/fincept-qt/src/screens/surface_analytics/SurfaceAnalyticsScreen.h b/fincept-qt/src/screens/surface_analytics/SurfaceAnalyticsScreen.h
index 571698c99..f7a5c3508 100644
--- a/fincept-qt/src/screens/surface_analytics/SurfaceAnalyticsScreen.h
+++ b/fincept-qt/src/screens/surface_analytics/SurfaceAnalyticsScreen.h
@@ -14,6 +14,7 @@
#include <QLabel>
#include <QPushButton>
#include <QScrollArea>
+#include <QSet>
#include <QSplitter>
#include <QStackedWidget>
#include <QString>
@@ -92,6 +93,16 @@ class SurfaceAnalyticsScreen : public QWidget, public fincept::screens::IStatefu
void refresh_provider_status();
void load_dataset_range_for_active_capability();
+ /// Mark `type`'s z-grid as holding genuine (fetched or imported) data and
+ /// refresh the tier badge. Called only from a provider/CSV path that
+ /// actually wrote the grid.
+ void mark_chart_real(ChartType type);
+ /// Re-apply the control panel's DEMO badge for whatever surface is on
+ /// screen. Every surface starts synthetic; the badge is per-surface, not
+ /// per-screen, so switching from a fetched surface to an un-fetched one has
+ /// to put DEMO back.
+ void sync_synthetic_badge();
+
QString current_symbol_or_default() const;
float spot_for(const QString& sym) const;
const std::vector<std::vector<float>>* active_z_grid() const;
@@ -112,6 +123,13 @@ class SurfaceAnalyticsScreen : public QWidget, public fincept::screens::IStatefu
SurfaceTableWidget* surface_table_ = nullptr;
SurfaceLineWidget* surface_line_ = nullptr;
QStackedWidget* view_stack_ = nullptr;
+ /// Always-visible banner directly above the chart, shown whenever the
+ /// surface on screen is SurfaceDemoData's rand() output. The control
+ /// panel's DEMO badge lives inside the ASSET group box, which
+ /// apply_capability_visibility() *hides* for the 12 surfaces that need no
+ /// underlying — precisely the always-synthetic ones. Those users saw
+ /// fabricated curves with no marking at all.
+ QLabel* demo_banner_ = nullptr;
// State
int active_category_ = 0;
@@ -152,6 +170,11 @@ class SurfaceAnalyticsScreen : public QWidget, public fincept::screens::IStatefu
InflationExpData inflation_data_;
MonetaryPolicyData monetary_data_;
+ /// ChartTypes (as int) whose z-grid currently holds real fetched/imported
+ /// data rather than SurfaceDemoData's rand() output. Everything not in here
+ /// is synthetic and must be badged DEMO. Cleared by load_demo_data().
+ QSet<int> real_data_charts_;
+
// Symbol group link — SymbolGroup::None when unlinked.
fincept::SymbolGroup link_group_ = fincept::SymbolGroup::None;
diff --git a/fincept-qt/src/screens/surface_analytics/SurfaceAnalyticsScreen_Handlers.cpp b/fincept-qt/src/screens/surface_analytics/SurfaceAnalyticsScreen_Handlers.cpp
index e63540fb4..dcabdf58e 100644
--- a/fincept-qt/src/screens/surface_analytics/SurfaceAnalyticsScreen_Handlers.cpp
+++ b/fincept-qt/src/screens/surface_analytics/SurfaceAnalyticsScreen_Handlers.cpp
@@ -23,6 +23,7 @@
#include "ui/theme/Theme.h"
#include <QFileDialog>
+#include <QFileInfo>
#include <QFrame>
#include <QHBoxLayout>
#include <QLabel>
@@ -63,8 +64,12 @@ void SurfaceAnalyticsScreen::on_category_clicked(int index) {
}
}
- if (control_panel_)
+ if (control_panel_) {
+ // Badge first: set_capability renders the tier, and it must render DEMO
+ // when this surface has never been fetched.
+ sync_synthetic_badge();
control_panel_->set_capability(active_chart_);
+ }
load_dataset_range_for_active_capability();
update_chart();
update_metrics();
@@ -77,8 +82,10 @@ void SurfaceAnalyticsScreen::on_surface_clicked(int cat, int surf_index) {
if (cat < (int)cats.size() && surf_index < (int)cats[cat].types.size())
active_chart_ = cats[cat].types[surf_index];
refresh_surface_bar();
- if (control_panel_)
+ if (control_panel_) {
+ sync_synthetic_badge();
control_panel_->set_capability(active_chart_);
+ }
load_dataset_range_for_active_capability();
update_chart();
update_metrics();
@@ -110,10 +117,27 @@ void SurfaceAnalyticsScreen::on_import_csv() {
}
void SurfaceAnalyticsScreen::on_refresh() {
+ // REFRESH used to *always* re-roll SurfaceDemoData's rand() output, so on a
+ // Databento-backed surface it silently replaced real fetched data with new
+ // fabricated numbers under an unchanged badge. Route it to a real re-fetch
+ // whenever one is possible; only fall back to regenerating sample data for
+ // surfaces that genuinely have no source, and say so.
+ const auto& cap = capability_for(active_chart_);
+ const bool fetchable = cap.tier != SurfaceTier::DEMO && DatabentoService::instance().has_api_key();
+ if (fetchable) {
+ on_fetch_requested();
+ return;
+ }
load_demo_data();
update_chart();
update_metrics();
update_inspector_lineage();
+ if (data_inspector_) {
+ data_inspector_->set_status(cap.tier == SurfaceTier::DEMO
+ ? tr("Regenerated synthetic sample data — this surface has no live source.")
+ : tr("Regenerated synthetic sample data — no Databento API key configured."),
+ false);
+ }
}
void SurfaceAnalyticsScreen::on_controls_changed() {
@@ -204,44 +228,60 @@ void SurfaceAnalyticsScreen::on_fetch_requested() {
}
void SurfaceAnalyticsScreen::dispatch_csv(const QString& path) {
+ // Every failure path here used to `return` silently, so a malformed file, an
+ // unreadable path, or an unsupported surface all looked identical to a
+ // successful import that changed nothing.
+ auto report = [this](const QString& message, bool ok) {
+ if (!data_inspector_)
+ return;
+ data_inspector_->set_status(message, ok);
+ if (!ok)
+ data_inspector_->set_error(message);
+ };
+
std::string err;
auto rows = parse_csv_file(path, err);
- if (rows.empty())
+ if (rows.empty()) {
+ const QString detail = err.empty() ? tr("no data rows found") : QString::fromStdString(err);
+ report(tr("CSV import failed: %1").arg(detail), false);
return;
+ }
+
+ bool loaded = false;
switch (active_chart_) {
case ChartType::Volatility:
- if (load_vol_surface(rows, vol_data_, err)) {
- update_chart();
- update_metrics();
- }
+ loaded = load_vol_surface(rows, vol_data_, err);
break;
case ChartType::DeltaSurface:
- if (load_greeks_surface(rows, delta_data_, err, "Delta")) {
- update_chart();
- update_metrics();
- }
+ loaded = load_greeks_surface(rows, delta_data_, err, "Delta");
break;
case ChartType::GammaSurface:
- if (load_greeks_surface(rows, gamma_data_, err, "Gamma")) {
- update_chart();
- update_metrics();
- }
+ loaded = load_greeks_surface(rows, gamma_data_, err, "Gamma");
break;
case ChartType::VegaSurface:
- if (load_greeks_surface(rows, vega_data_, err, "Vega")) {
- update_chart();
- update_metrics();
- }
+ loaded = load_greeks_surface(rows, vega_data_, err, "Vega");
break;
case ChartType::ThetaSurface:
- if (load_greeks_surface(rows, theta_data_, err, "Theta")) {
- update_chart();
- update_metrics();
- }
+ loaded = load_greeks_surface(rows, theta_data_, err, "Theta");
break;
default:
- break;
+ report(tr("CSV import is only implemented for the Vol / Delta / Gamma / Vega / Theta surfaces. "
+ "Switch to one of those first."),
+ false);
+ return;
+ }
+
+ if (!loaded) {
+ report(tr("CSV import failed: %1").arg(QString::fromStdString(err)), false);
+ return;
}
+
+ // Imported data is real data — the surface must stop claiming DEMO.
+ mark_chart_real(active_chart_);
+ update_chart();
+ update_metrics();
+ update_inspector_lineage();
+ report(tr("Imported %1 rows from %2").arg(qint64(rows.size())).arg(QFileInfo(path).fileName()), true);
}
// ── Databento slots ───────────────────────────────────────────────────────────
diff --git a/fincept-qt/src/screens/surface_analytics/SurfaceAnalyticsScreen_Layout.cpp b/fincept-qt/src/screens/surface_analytics/SurfaceAnalyticsScreen_Layout.cpp
index 6d5b5eb45..ad8cbe7df 100644
--- a/fincept-qt/src/screens/surface_analytics/SurfaceAnalyticsScreen_Layout.cpp
+++ b/fincept-qt/src/screens/surface_analytics/SurfaceAnalyticsScreen_Layout.cpp
@@ -131,6 +131,18 @@ void SurfaceAnalyticsScreen::setup_ui() {
rvl->setContentsMargins(0, 0, 0, 0);
rvl->setSpacing(0);
+ demo_banner_ = new QLabel(tr("SAMPLE DATA — synthetic values, not a live market surface. "
+ "Do not trade or quote from this."),
+ right);
+ demo_banner_->setWordWrap(true);
+ demo_banner_->setAlignment(Qt::AlignCenter);
+ demo_banner_->setAccessibleName(tr("Synthetic data warning"));
+ demo_banner_->setStyleSheet(QString("background:rgba(217,119,6,0.18); color:%1; border-bottom:1px solid %2;"
+ " font-size:10px; font-weight:bold; letter-spacing:0.4px; padding:5px 8px;")
+ .arg(colors::AMBER())
+ .arg(colors::AMBER_DIM()));
+ rvl->addWidget(demo_banner_);
+
view_stack_ = new QStackedWidget(right);
surface_3d_ = new Surface3DWidget(view_stack_);
surface_table_ = new SurfaceTableWidget(view_stack_);
diff --git a/fincept-qt/src/screens/surface_analytics/SurfaceAnalyticsScreen_Providers.cpp b/fincept-qt/src/screens/surface_analytics/SurfaceAnalyticsScreen_Providers.cpp
index 0d7e17267..4a033b836 100644
--- a/fincept-qt/src/screens/surface_analytics/SurfaceAnalyticsScreen_Providers.cpp
+++ b/fincept-qt/src/screens/surface_analytics/SurfaceAnalyticsScreen_Providers.cpp
@@ -38,8 +38,6 @@ namespace fincept::surface {
using namespace fincept::ui;
void SurfaceAnalyticsScreen::on_vol_surface_received(const fincept::DatabentoVolSurfaceResult& r) {
- if (r.success && control_panel_)
- control_panel_->mark_synthetic(false); // real Databento data replaced the demo surface
if (data_inspector_)
data_inspector_->set_status(r.success ? tr("Vol surface loaded") : tr("Vol fetch failed"), r.success);
if (!r.success) {
@@ -53,35 +51,56 @@ void SurfaceAnalyticsScreen::on_vol_surface_received(const fincept::DatabentoVol
std::string sym_std = sym.toStdString();
float spot = spot_for(sym);
+ // SAFETY: the DEMO badge may only be cleared for grids that were genuinely
+ // replaced. A "successful" response can still carry an empty grid for some
+ // (or every) surface — clearing the badge unconditionally would relabel
+ // untouched rand() sample data as live market data.
+ bool replaced_active = false;
+ auto note_replaced = [&](ChartType t) {
+ real_data_charts_.insert(static_cast<int>(t));
+ if (active_chart_ == t)
+ replaced_active = true;
+ };
+
if (!r.vol.z.empty()) {
vol_data_ = r.vol;
vol_data_.underlying = sym_std;
vol_data_.spot_price = spot;
+ note_replaced(ChartType::Volatility);
}
if (!r.delta.z.empty()) {
delta_data_ = r.delta;
delta_data_.underlying = sym_std;
delta_data_.spot_price = spot;
+ note_replaced(ChartType::DeltaSurface);
}
if (!r.gamma.z.empty()) {
gamma_data_ = r.gamma;
gamma_data_.underlying = sym_std;
gamma_data_.spot_price = spot;
+ note_replaced(ChartType::GammaSurface);
}
if (!r.vega.z.empty()) {
vega_data_ = r.vega;
vega_data_.underlying = sym_std;
vega_data_.spot_price = spot;
+ note_replaced(ChartType::VegaSurface);
}
if (!r.theta.z.empty()) {
theta_data_ = r.theta;
theta_data_.underlying = sym_std;
theta_data_.spot_price = spot;
+ note_replaced(ChartType::ThetaSurface);
}
if (!r.skew.z.empty()) {
skew_data_ = r.skew;
skew_data_.underlying = sym_std;
+ note_replaced(ChartType::SkewSurface);
}
+ sync_synthetic_badge();
+ if (!replaced_active && data_inspector_)
+ data_inspector_->set_error(
+ tr("The response carried no grid for the surface on screen — it is still showing sample data."));
if (data_inspector_) {
QStringList headers = {"strike", "expiration", "iv"};
@@ -104,8 +123,9 @@ void SurfaceAnalyticsScreen::on_vol_surface_received(const fincept::DatabentoVol
}
void SurfaceAnalyticsScreen::on_ohlcv_received(const fincept::DatabentoOhlcvResult& r) {
- if (r.success && control_panel_)
- control_panel_->mark_synthetic(false); // real data replaced the demo surface
+ // Deliberately does NOT clear the DEMO badge. An OHLCV response populates
+ // the inspector's raw table only — it replaces no surface z-grid, so every
+ // rendered surface is still the rand() sample data and must keep saying so.
if (data_inspector_) {
data_inspector_->set_status(r.success ? tr("OHLCV loaded") : tr("OHLCV fetch failed"), r.success);
if (!r.success)
@@ -132,18 +152,23 @@ void SurfaceAnalyticsScreen::on_ohlcv_received(const fincept::DatabentoOhlcvResu
}
void SurfaceAnalyticsScreen::on_futures_received(const fincept::DatabentoFuturesResult& r) {
- if (r.success && control_panel_)
- control_panel_->mark_synthetic(false); // real data replaced the demo surface
if (data_inspector_) {
data_inspector_->set_status(r.success ? tr("Futures curve loaded") : tr("Futures fetch failed"), r.success);
if (!r.success)
data_inspector_->set_error(r.error);
}
if (r.success) {
+ // Only the two grids below come from this response — anything else on
+ // screen is still sample data and keeps its DEMO badge.
+ if (!r.forward.z.empty())
+ real_data_charts_.insert(static_cast<int>(ChartType::CommodityForward));
+ if (!r.contango.z.empty())
+ real_data_charts_.insert(static_cast<int>(ChartType::ContangoBackwardation));
if (!r.forward.z.empty())
cmdty_fwd_data_ = r.forward;
if (!r.contango.z.empty())
contango_data_ = r.contango;
+ sync_synthetic_badge();
}
update_chart();
update_metrics();
@@ -151,8 +176,6 @@ void SurfaceAnalyticsScreen::on_futures_received(const fincept::DatabentoFutures
}
void SurfaceAnalyticsScreen::on_surface_received(const fincept::DatabentoSurfaceResult& r) {
- if (r.success && control_panel_)
- control_panel_->mark_synthetic(false); // real data replaced the demo surface
if (data_inspector_) {
data_inspector_->set_status(r.success ? tr("Surface loaded") : tr("Surface fetch failed"), r.success);
if (!r.success)
@@ -167,37 +190,62 @@ void SurfaceAnalyticsScreen::on_surface_received(const fincept::DatabentoSurface
std::string sym_std = sym.toStdString();
float spot = spot_for(sym);
+ // Track which surface (if any) this payload actually replaced. `type` can be
+ // a value we don't handle, or arrive with an empty grid — in either case
+ // nothing on screen changed and the DEMO badge must stay on.
+ ChartType replaced = active_chart_;
+ bool did_replace = false;
if (type == "local_vol" && !r.z.empty()) {
local_vol_data_.strikes.assign(r.x_axis.begin(), r.x_axis.end());
local_vol_data_.expirations.assign(r.y_axis.begin(), r.y_axis.end());
local_vol_data_.z = r.z;
local_vol_data_.underlying = sym_std;
local_vol_data_.spot_price = spot;
+ replaced = ChartType::LocalVolSurface;
+ did_replace = true;
} else if (type == "implied_dividend" && !r.z.empty()) {
impl_div_data_.strikes.assign(r.x_axis.begin(), r.x_axis.end());
impl_div_data_.expirations.assign(r.y_axis.begin(), r.y_axis.end());
impl_div_data_.z = r.z;
impl_div_data_.underlying = sym_std;
+ replaced = ChartType::ImpliedDividend;
+ did_replace = true;
} else if (type == "liquidity" && !r.z.empty()) {
liquidity_data_.strikes.assign(r.x_axis.begin(), r.x_axis.end());
liquidity_data_.expirations.assign(r.y_axis.begin(), r.y_axis.end());
liquidity_data_.z = r.z;
liquidity_data_.underlying = sym_std;
+ replaced = ChartType::LiquidityHeatmap;
+ did_replace = true;
} else if (type == "commodity_vol" && !r.z.empty()) {
cmdty_vol_data_.strikes.assign(r.x_axis.begin(), r.x_axis.end());
cmdty_vol_data_.expirations.assign(r.y_axis.begin(), r.y_axis.end());
cmdty_vol_data_.z = r.z;
cmdty_vol_data_.commodity = sym_std;
+ replaced = ChartType::CommodityVol;
+ did_replace = true;
} else if (type == "crack_spread" && !r.z.empty()) {
crack_data_.spread_types = r.x_labels;
crack_data_.contract_months.assign(r.y_axis.begin(), r.y_axis.end());
crack_data_.z = r.z;
+ replaced = ChartType::CrackSpread;
+ did_replace = true;
} else if (type == "stress_test" && !r.z.empty()) {
stress_data_.scenarios = r.x_labels;
stress_data_.portfolios = r.y_labels;
stress_data_.z = r.z;
+ replaced = ChartType::StressTestPnL;
+ did_replace = true;
}
+ if (did_replace)
+ real_data_charts_.insert(static_cast<int>(replaced));
+ const bool active_is_real = did_replace && replaced == active_chart_;
+ sync_synthetic_badge();
+ if (!active_is_real && data_inspector_)
+ data_inspector_->set_error(
+ tr("The response replaced no grid for the surface on screen — it is still showing sample data."));
+
update_chart();
update_metrics();
update_inspector_lineage();
diff --git a/fincept-qt/src/screens/surface_analytics/SurfaceAnalyticsScreen_Views.cpp b/fincept-qt/src/screens/surface_analytics/SurfaceAnalyticsScreen_Views.cpp
index ae9e7c38e..39a6b6f3b 100644
--- a/fincept-qt/src/screens/surface_analytics/SurfaceAnalyticsScreen_Views.cpp
+++ b/fincept-qt/src/screens/surface_analytics/SurfaceAnalyticsScreen_Views.cpp
@@ -53,10 +53,13 @@ void SurfaceAnalyticsScreen::refresh_surface_bar() {
// ── Data loading ─────────────────────────────────────────────────────────────
void SurfaceAnalyticsScreen::load_demo_data() {
- // This fills every surface with rand() sample data — tell the badge so it shows
- // DEMO instead of the surface's LIVE/COMPUTED capability tier.
- if (control_panel_)
- control_panel_->mark_synthetic(true);
+ // This overwrites EVERY surface with rand() sample data, so every prior
+ // fetch/import is discarded and every surface is synthetic again. The badge
+ // is driven off `real_data_charts_` rather than a single screen-wide flag,
+ // because a fetch only ever replaces one or two grids — the rest stay fake
+ // and must keep saying DEMO when the user clicks over to them.
+ real_data_charts_.clear();
+ sync_synthetic_badge();
QString qsym = current_symbol_or_default();
std::string sym = qsym.toStdString();
float spot = spot_for(qsym);
@@ -495,13 +498,23 @@ void SurfaceAnalyticsScreen::update_chart() {
break;
}
case ChartType::Correlation: {
- int n = (int)corr_data_.assets.size();
- if (corr_data_.z.empty() || (int)corr_data_.z.size() < n)
+ // CorrelationMatrixData::z is [time_slice][n*n] — one FLATTENED n×n
+ // matrix per observation window (see generate_correlation, and the
+ // table view's show_correlation which already reads it that way).
+ // Indexing it as z[row][col] pulled the first n entries of the first
+ // n *time slices*, i.e. row 0 of the matrix sampled at n different
+ // times, and rendered that as a correlation matrix. Take the most
+ // recent slice and unflatten it, matching the table view exactly.
+ const int n = (int)corr_data_.assets.size();
+ if (n <= 0 || corr_data_.z.empty())
+ break;
+ const auto& last = corr_data_.z.back();
+ if ((int)last.size() < n * n)
break;
std::vector<std::vector<float>> slice(n, std::vector<float>(n));
for (int r = 0; r < n; r++)
for (int c = 0; c < n; c++)
- slice[r][c] = corr_data_.z[r][c];
+ slice[r][c] = last[r * n + c];
surface_3d_->set_surface(slice, "ASSET", "CORR", "ASSET", -1.f, 1.f, true);
break;
}
@@ -596,6 +609,9 @@ void SurfaceAnalyticsScreen::update_metrics() {
control_panel_->update_metrics(*z);
else
control_panel_->update_metrics({});
+ // The panel's "Spot:" readout had no writer at all — it always showed a
+ // dash. Fill it from the same resolver the fetch path uses.
+ control_panel_->set_spot(double(spot_for(current_symbol_or_default())));
}
const std::vector<std::vector<float>>* SurfaceAnalyticsScreen::active_z_grid() const {
diff --git a/fincept-qt/src/screens/surface_analytics/SurfaceControlPanel.cpp b/fincept-qt/src/screens/surface_analytics/SurfaceControlPanel.cpp
index 526995c0b..4f992e602 100644
--- a/fincept-qt/src/screens/surface_analytics/SurfaceControlPanel.cpp
+++ b/fincept-qt/src/screens/surface_analytics/SurfaceControlPanel.cpp
@@ -172,7 +172,7 @@ void SurfaceControlPanel::setup_ui() {
name_lbl->setStyleSheet(QString("color:%1; font-size:10px; font-family:Consolas;").arg(colors::TEXT_PRIMARY()));
name_lbl->setMinimumWidth(80);
row->addWidget(name_lbl);
- auto* state_lbl = new QLabel("not configured", providers_box_);
+ auto* state_lbl = new QLabel(tr("not configured"), providers_box_);
state_lbl->setStyleSheet(QString("color:%1; font-size:9px;").arg(colors::TEXT_DIM()));
row->addWidget(state_lbl, 1);
auto* detail_lbl = new QLabel("", providers_box_);
@@ -219,6 +219,7 @@ void SurfaceControlPanel::setup_ui() {
fetch_btn_ = new QPushButton(tr("FETCH"), footer);
fetch_btn_->setStyleSheet(fetch_btn_qss(true));
fetch_btn_->setMinimumHeight(34);
+ fetch_btn_->setAccessibleName(tr("Fetch this surface from Databento"));
connect(fetch_btn_, &QPushButton::clicked, this, &SurfaceControlPanel::on_fetch_clicked);
footer_layout->addWidget(fetch_btn_);
outer->addWidget(footer);
@@ -272,7 +273,12 @@ QGroupBox* SurfaceControlPanel::build_asset_section() {
spot_label_->setStyleSheet(QString("color:%1; font-size:9px;").arg(colors::TEXT_DIM()));
l->addWidget(spot_label_);
+ symbol_edit_->setAccessibleName(tr("Underlying symbol"));
+ dataset_combo_->setAccessibleName(tr("Databento dataset"));
+ spot_label_->setAccessibleName(tr("Spot price"));
+
tier_badge_ = new QLabel("DEMO", gb);
+ tier_badge_->setAccessibleName(tr("Data tier"));
tier_badge_->setAlignment(Qt::AlignCenter);
tier_badge_->setStyleSheet(QString("background:%1; color:#000; font-size:9px; font-weight:bold; "
"padding:2px 6px; border-radius:2px; max-width:80px;")
@@ -561,7 +567,8 @@ void SurfaceControlPanel::update_metrics(const std::vector<std::vector<float>>&
return;
}
std::sort(flat.begin(), flat.end());
- double n = (double)flat.size();
+ const size_t count = flat.size();
+ double n = (double)count;
double sum = 0;
for (float v : flat)
sum += v;
@@ -577,7 +584,11 @@ void SurfaceControlPanel::update_metrics(const std::vector<std::vector<float>>&
double std_dev = std::sqrt(var);
double skew = (std_dev > 0) ? (m3 / n) / std::pow(std_dev, 3) : 0.0;
double kurt = (std_dev > 0) ? (m4 / n) / std::pow(std_dev, 4) - 3.0 : 0.0;
- double median = flat[flat.size() / 2];
+ // Even-sized samples take the mean of the two central values; the old
+ // flat[size/2] silently reported the upper middle as "median".
+ const double median = (count % 2 == 0)
+ ? 0.5 * (double(flat[count / 2 - 1]) + double(flat[count / 2]))
+ : double(flat[count / 2]);
QString suffix = units.isEmpty() ? QString() : QStringLiteral(" ") + units;
set_metric(metrics_count_, QString::number((qint64)n));
@@ -595,6 +606,13 @@ void SurfaceControlPanel::update_lineage(const QString& line) {
lineage_label_->setText(line.isEmpty() ? "—" : line);
}
+void SurfaceControlPanel::set_spot(double spot) {
+ last_spot_ = spot;
+ if (!spot_label_)
+ return;
+ spot_label_->setText(spot > 0 ? tr("Spot: %1").arg(spot, 0, 'f', 2) : tr("Spot: —"));
+}
+
void SurfaceControlPanel::apply_state(const SurfaceControlsState& s) {
state_ = s;
if (symbol_edit_)
@@ -770,14 +788,25 @@ void SurfaceControlPanel::set_provider_status(const QString& provider_name, cons
auto* dt = provider_detail_.value(provider_name, nullptr);
if (!dot || !lbl)
return;
+ // `provider_state` is a protocol token from the caller; the pill shows a
+ // translated rendering of it rather than the raw token.
QString color = colors::TEXT_DIM();
QString text = provider_state;
- if (provider_state == "connected")
+ if (provider_state == "connected") {
color = colors::POSITIVE();
- else if (provider_state == "disconnected" || provider_state == "error")
+ text = tr("connected");
+ } else if (provider_state == "disconnected") {
+ color = colors::NEGATIVE();
+ text = tr("disconnected");
+ } else if (provider_state == "error") {
color = colors::NEGATIVE();
- else if (provider_state == "configured")
+ text = tr("error");
+ } else if (provider_state == "configured") {
color = QString("rgb(217,164,6)"); // amber, key set but not yet tested
+ text = tr("configured");
+ } else if (provider_state == "not configured") {
+ text = tr("not configured");
+ }
dot->setStyleSheet(QString("color:%1; font-size:11px;").arg(color));
lbl->setText(text);
lbl->setStyleSheet(QString("color:%1; font-size:9px;").arg(color));
@@ -817,8 +846,8 @@ void SurfaceControlPanel::retranslateUi() {
symbol_edit_->setPlaceholderText(tr("Underlying / parent symbol"));
if (dataset_lbl_)
dataset_lbl_->setText(tr("Dataset:"));
- if (spot_label_)
- spot_label_->setText(tr("Spot: —"));
+ // Re-render the live value rather than blanking it back to a dash.
+ set_spot(last_spot_);
// Date + option field labels
if (start_lbl_)
diff --git a/fincept-qt/src/screens/surface_analytics/SurfaceControlPanel.h b/fincept-qt/src/screens/surface_analytics/SurfaceControlPanel.h
index 819cb168f..4cee10a30 100644
--- a/fincept-qt/src/screens/surface_analytics/SurfaceControlPanel.h
+++ b/fincept-qt/src/screens/surface_analytics/SurfaceControlPanel.h
@@ -65,6 +65,11 @@ class SurfaceControlPanel : public QWidget {
// Show a one-line lineage string from the active capability + state.
void update_lineage(const QString& line);
+ /// Fill in the "Spot:" readout under the symbol field. The label existed
+ /// but nothing ever wrote to it, so it read "Spot: —" forever even though
+ /// the screen resolves a spot for every fetch. Pass <= 0 to clear.
+ void set_spot(double spot);
+
SurfaceControlsState state() const { return state_; }
void apply_state(const SurfaceControlsState& s);
@@ -131,6 +136,7 @@ class SurfaceControlPanel : public QWidget {
QComboBox* dataset_combo_ = nullptr;
QLabel* dataset_lbl_ = nullptr; // "Dataset:" (cached for retranslateUi)
QLabel* spot_label_ = nullptr;
+ double last_spot_ = 0.0; // last value pushed to spot_label_, for retranslate
QLabel* tier_badge_ = nullptr;
bool synthetic_ = false; // true while the displayed surface is demo/sample data
diff --git a/fincept-qt/src/screens/surface_analytics/SurfaceTableWidget.cpp b/fincept-qt/src/screens/surface_analytics/SurfaceTableWidget.cpp
index f54e31cdb..8cee68f93 100644
--- a/fincept-qt/src/screens/surface_analytics/SurfaceTableWidget.cpp
+++ b/fincept-qt/src/screens/surface_analytics/SurfaceTableWidget.cpp
@@ -179,9 +179,13 @@ void SurfaceTableWidget::show_greeks(const GreeksSurfaceData& d) {
void SurfaceTableWidget::show_correlation(const CorrelationMatrixData& d) {
if (d.z.empty())
return;
- int n = (int)d.assets.size();
- // Last time slice is most recent
+ const int n = (int)d.assets.size();
+ // z rows are FLATTENED n×n matrices, one per time slice; the last is most
+ // recent. Guard the size — a truncated slice (basket edited between the
+ // generate and the render) would otherwise read past the end of the vector.
const auto& last = d.z.back();
+ if (n <= 0 || (int)last.size() < n * n)
+ return;
std::vector<std::vector<float>> mat(n, std::vector<float>(n));
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
diff --git a/fincept-qt/src/screens/trade_viz/TradeVizScreen.cpp b/fincept-qt/src/screens/trade_viz/TradeVizScreen.cpp
index 173292757..7cc77c0e6 100644
--- a/fincept-qt/src/screens/trade_viz/TradeVizScreen.cpp
+++ b/fincept-qt/src/screens/trade_viz/TradeVizScreen.cpp
@@ -304,11 +304,14 @@ QWidget* TradeVizScreen::build_tab_bar() {
const char* label;
bool active;
};
+ // QT_TR_NOOP marks the literals for extraction; tr(t.label) below does the
+ // runtime lookup. Without it lupdate never sees these strings and the tab
+ // labels stayed English in every locale.
Tab tabs[] = {
- {"21)", "Table", false},
- {"22)", "Settings", false},
- {"23)", "Export", false},
- {"24)", "Notes", false},
+ {"21)", QT_TR_NOOP("Table"), false},
+ {"22)", QT_TR_NOOP("Settings"), false},
+ {"23)", QT_TR_NOOP("Export"), false},
+ {"24)", QT_TR_NOOP("Notes"), false},
};
for (const auto& t : tabs) {
diff --git a/fincept-qt/src/screens/watchlist/WatchlistScreen.cpp b/fincept-qt/src/screens/watchlist/WatchlistScreen.cpp
index ba519ada0..f3674b21e 100644
--- a/fincept-qt/src/screens/watchlist/WatchlistScreen.cpp
+++ b/fincept-qt/src/screens/watchlist/WatchlistScreen.cpp
@@ -18,9 +18,13 @@
#include <QHBoxLayout>
#include <QHideEvent>
#include <QInputDialog>
+#include <QJsonArray>
+#include <QJsonObject>
+#include <QKeySequence>
#include <QMessageBox>
#include <QPointer>
#include <QSet>
+#include <QShortcut>
#include <QShowEvent>
#include <QSplitter>
#include <QTextStream>
@@ -138,6 +142,8 @@ void WatchlistScreen::hideEvent(QHideEvent* event) {
QWidget::hideEvent(event);
hub_unsubscribe_all();
unsubscribe_mcp_events();
+ if (rebuild_timer_)
+ rebuild_timer_->stop(); // P3: no work while hidden
}
void WatchlistScreen::changeEvent(QEvent* event) {
@@ -386,17 +392,39 @@ QWidget* WatchlistScreen::build_main_panel() {
table_->setSelectionBehavior(QAbstractItemView::SelectRows);
table_->setSelectionMode(QAbstractItemView::SingleSelection);
+ table_->setAccessibleName(tr("Watchlist quotes"));
+
// When the user selects a row, publish its symbol into the linked group.
// Use itemSelectionChanged rather than cellClicked so keyboard navigation
// also propagates.
connect(table_, &QTableWidget::itemSelectionChanged, this, &WatchlistScreen::publish_selection_to_group);
+ // Delete on a selected row removes the symbol (with the same confirmation
+ // as the REMOVE SELECTED button). Scoped to the table so it can't fire
+ // while the user is typing in the ADD box.
+ auto* del_sc = new QShortcut(QKeySequence::Delete, table_);
+ del_sc->setContext(Qt::WidgetShortcut);
+ connect(del_sc, &QShortcut::activated, this, &WatchlistScreen::on_remove_stock);
+
// Drag-out: hold-and-drag a symbol row to broadcast the ticker to any
// panel. The provider callback reads the current row at drag-start so
// keyboard row-changes are reflected without reinstalling the filter.
symbol_dnd::installDragSource(table_->viewport(), [this]() { return current_symbol(); }, link_group_);
- lay->addWidget(table_, 1);
+ // Table + empty-state guidance share one slot; only one is visible.
+ auto* table_stack = new QWidget(main_panel_);
+ auto* ts_lay = new QVBoxLayout(table_stack);
+ ts_lay->setContentsMargins(0, 0, 0, 0);
+ ts_lay->setSpacing(0);
+ ts_lay->addWidget(table_, 1);
+
+ empty_label_ = new QLabel(table_stack);
+ empty_label_->setAlignment(Qt::AlignCenter);
+ empty_label_->setWordWrap(true);
+ empty_label_->setVisible(false);
+ ts_lay->addWidget(empty_label_, 1);
+
+ lay->addWidget(table_stack, 1);
// Drop: dropping a symbol onto the watchlist body adds it to the current
// watchlist. Happens on the main_panel_ so the drop target is generous
@@ -505,6 +533,12 @@ void WatchlistScreen::refresh_theme() {
if (remove_btn_)
remove_btn_->setStyleSheet(danger_btn_style());
+
+ if (empty_label_)
+ empty_label_->setStyleSheet(QString("color:%1; font-size:%2px; font-family:%3; background:transparent;")
+ .arg(colors::TEXT_TERTIARY())
+ .arg(fonts::SMALL)
+ .arg(fonts::DATA_FAMILY()));
}
// ── Data Loading ─────────────────────────────────────────────────────────────
@@ -538,10 +572,26 @@ void WatchlistScreen::load_watchlists() {
wl_count_->setText(tr("%1 lists").arg(watchlists_.size()));
- // Select first watchlist
- if (!watchlists_.isEmpty()) {
- wl_list_->setCurrentRow(0);
+ if (watchlists_.isEmpty())
+ return;
+
+ // Keep the user on the list they were viewing. This is reloaded from a
+ // cloud pull and from every MCP watchlist.* event, and the old code always
+ // jumped back to row 0 — so an LLM adding a symbol yanked the user out of
+ // whichever list they had open.
+ int row = 0;
+ if (!current_wl_id_.isEmpty()) {
+ for (int i = 0; i < watchlists_.size(); ++i) {
+ if (watchlists_[i].id == current_wl_id_) {
+ row = i;
+ break;
+ }
+ }
}
+ if (wl_list_->currentRow() == row)
+ on_watchlist_selected(row); // same row → currentRowChanged won't fire
+ else
+ wl_list_->setCurrentRow(row);
}
void WatchlistScreen::load_stocks() {
@@ -563,6 +613,7 @@ void WatchlistScreen::fetch_quotes() {
if (stocks_.isEmpty()) {
table_->clear_data();
hub_unsubscribe_all();
+ update_empty_state();
return;
}
@@ -573,6 +624,17 @@ void WatchlistScreen::fetch_quotes() {
rebuild_from_cache();
}
+void WatchlistScreen::schedule_table_rebuild() {
+ if (!rebuild_timer_) {
+ rebuild_timer_ = new QTimer(this);
+ rebuild_timer_->setSingleShot(true);
+ rebuild_timer_->setInterval(60); // one frame-ish; absorbs a whole hub burst
+ connect(rebuild_timer_, &QTimer::timeout, this, &WatchlistScreen::rebuild_from_cache);
+ }
+ if (!rebuild_timer_->isActive())
+ rebuild_timer_->start();
+}
+
void WatchlistScreen::rebuild_from_cache() {
QVector<services::QuoteData> quotes;
quotes.reserve(stocks_.size());
@@ -588,9 +650,26 @@ void WatchlistScreen::rebuild_from_cache() {
table_->add_row({s.symbol, s.name, "--", "--", "--", "--", "--", "--"});
}
table_->setSortingEnabled(true);
+ update_empty_state();
return;
}
populate_table(quotes);
+ update_empty_state();
+}
+
+void WatchlistScreen::update_empty_state() {
+ if (!empty_label_ || !table_)
+ return;
+ // An empty watchlist used to render as a blank grid with no explanation.
+ const bool show = current_wl_id_.isEmpty() || stocks_.isEmpty();
+ empty_label_->setVisible(show);
+ table_->setVisible(!show);
+ if (!show)
+ return;
+ empty_label_->setText(current_wl_id_.isEmpty()
+ ? tr("Select a watchlist on the left, or press + to create one.")
+ : tr("This watchlist is empty.\n\nType one or more tickers in the ADD box above\n"
+ "(comma-separated), or drag a symbol in from another panel."));
}
void WatchlistScreen::hub_resubscribe_stocks() {
@@ -611,16 +690,18 @@ void WatchlistScreen::hub_resubscribe_stocks() {
const QString topic = QStringLiteral("market:quote:") + sym;
topics.append(topic);
hub.subscribe(this, topic, [this, sym](const QVariant& v) {
- LOG_INFO(
- "Watchlist",
- QString("hub callback fired for %1 (canConvert=%2)").arg(sym).arg(v.canConvert<services::QuoteData>()));
if (!v.canConvert<services::QuoteData>())
return;
row_cache_.insert(sym, v.value<services::QuoteData>());
- rebuild_from_cache();
+ // Do NOT rebuild the whole table here. A hub delivery burst fans out
+ // one callback per symbol, so a 50-symbol watchlist used to run 50
+ // full clear_data()+50-row repopulations back-to-back (2500 row
+ // constructions) and lose the user's sort/selection each time.
+ // Coalesce into a single rebuild at the end of the burst.
+ schedule_table_rebuild();
});
}
- LOG_INFO("Watchlist", QString("subscribed + requesting %1 topics: %2").arg(topics.size()).arg(topics.join(", ")));
+ LOG_DEBUG("Watchlist", QString("subscribed + requesting %1 quote topics").arg(topics.size()));
// force=true: watchlist symbols change on user edit; bypass min_interval
// so newly-added tickers resolve immediately instead of waiting for the
// scheduler tick.
@@ -725,7 +806,9 @@ void WatchlistScreen::on_delete_watchlist() {
fincept::WatchlistRepository::instance().remove(current_wl_id_);
current_wl_id_.clear();
+ stocks_.clear();
table_->clear_data();
+ update_empty_state();
panel_title_->setText(tr("Select a watchlist"));
stock_count_->clear();
if (del_wl_btn_)
@@ -767,11 +850,17 @@ void WatchlistScreen::on_remove_stock() {
// remove the WRONG symbol from the watchlist.
const int row = table_->currentRow();
auto* sym_item = (row >= 0) ? table_->item(row, 0) : nullptr;
- if (!sym_item)
+ if (!sym_item) {
+ QMessageBox::information(this, tr("Remove symbol"), tr("Select a row in the table first."));
return;
+ }
const QString symbol = sym_item->text();
if (symbol.isEmpty())
return;
+ // Destructive and previously one misclick away with no confirmation.
+ if (QMessageBox::question(this, tr("Remove symbol"), tr("Remove %1 from this watchlist?").arg(symbol),
+ QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes)
+ return;
fincept::WatchlistRepository::instance().remove_stock(current_wl_id_, symbol);
load_stocks();
}
diff --git a/fincept-qt/src/screens/watchlist/WatchlistScreen.h b/fincept-qt/src/screens/watchlist/WatchlistScreen.h
index fda6b9499..07fb56486 100644
--- a/fincept-qt/src/screens/watchlist/WatchlistScreen.h
+++ b/fincept-qt/src/screens/watchlist/WatchlistScreen.h
@@ -71,6 +71,9 @@ class WatchlistScreen : public QWidget, public IStatefulScreen, public IGroupLin
void hub_resubscribe_stocks();
void hub_unsubscribe_all();
void rebuild_from_cache();
+ /// Coalesce a burst of per-symbol hub callbacks into ONE table rebuild.
+ void schedule_table_rebuild();
+ QTimer* rebuild_timer_ = nullptr;
// Data
QVector<fincept::Watchlist> watchlists_;
@@ -100,8 +103,12 @@ class WatchlistScreen : public QWidget, public IStatefulScreen, public IGroupLin
QPushButton* add_btn_ = nullptr;
QPushButton* remove_btn_ = nullptr;
ui::DataTable* table_ = nullptr;
+ QLabel* empty_label_ = nullptr; // guidance shown in place of a blank grid
QSplitter* splitter_ = nullptr;
+ /// Show/hide the empty-state guidance based on the current selection.
+ void update_empty_state();
+
QHash<QString, services::QuoteData> row_cache_;
bool hub_active_ = false;
diff --git a/fincept-qt/src/services/ai_quant_lab/AIQuantLabService.cpp b/fincept-qt/src/services/ai_quant_lab/AIQuantLabService.cpp
index 00f46ad8d..ffa4c0920 100644
--- a/fincept-qt/src/services/ai_quant_lab/AIQuantLabService.cpp
+++ b/fincept-qt/src/services/ai_quant_lab/AIQuantLabService.cpp
@@ -576,6 +576,14 @@ void AIQuantLabService::run_deep_agent(const QJsonObject& params) {
payload["agent_type"] = params.contains("agent_type") ? params["agent_type"] : QJsonValue("general");
if (params.contains("thread_id"))
payload["thread_id"] = params["thread_id"];
+ // The LLM credentials block MUST be forwarded. deepagents/cli.py reads
+ // `params.get("config", {})` in execute_task and hands it to create_model();
+ // dropping it here meant the agent always ran with an empty config even
+ // though the Deep Analysis panel refuses to start until the user picks an
+ // LLM profile. Symptom was a provider/credential error that looked like a
+ // Python fault rather than a plumbing bug.
+ if (params.contains("config"))
+ payload["config"] = params["config"];
auto json = QJsonDocument(payload).toJson(QJsonDocument::Compact);
run_python("agents/deepagents/cli.py", {"execute_task", json}, "deep_agent", "execute_task");
diff --git a/fincept-qt/src/services/ai_quant_lab/AIQuantLabTypes.h b/fincept-qt/src/services/ai_quant_lab/AIQuantLabTypes.h
index d70996dce..e3d9b7667 100644
--- a/fincept-qt/src/services/ai_quant_lab/AIQuantLabTypes.h
+++ b/fincept-qt/src/services/ai_quant_lab/AIQuantLabTypes.h
@@ -40,8 +40,29 @@ inline QVector<QuantModule> all_quant_modules() {
"ai_quant_lab/qlib_online_learning.py", "Incremental learning with concept drift detection"},
{"meta_learning", "Meta Learning", "META", "AI_ML", QColor("#E040FB"), "ai_quant_lab/qlib_meta_learning.py",
"Few-shot learning, model selection, AutoML"},
- {"pattern_intelligence", "Pattern Intelligence", "PATTERN", "AI_ML", QColor("#FF9100"),
- "Analytics/technical_indicators.py", "Technical pattern recognition and scoring"},
+ // REMOVED: {"pattern_intelligence", …, "Analytics/technical_indicators.py"}
+ //
+ // The module was registered — so it appeared in the AI Quant Lab sidebar
+ // and could be opened and run — but it could not work, in two
+ // independent ways:
+ //
+ // 1. No panel or result display is wired for it (see the note at the
+ // top of QuantModulePanel_AIMLDisplays.cpp), so it fell through to
+ // build_generic_panel().
+ // 2. Its target, scripts/Analytics/technical_indicators.py, is a
+ // LIBRARY. Its main() accepts exactly one command — "test" — which
+ // fabricates prices with np.random.seed(42) and returns indicators
+ // computed over that synthetic series. Every other command returns
+ // {"error": "Unknown command: …"}.
+ //
+ // So the module either errored or, on the one command it accepts,
+ // returned indicators derived from random numbers with no indication
+ // they were synthetic. Removed rather than left shipping.
+ //
+ // To restore it properly: give technical_indicators.py a real command
+ // surface over user-supplied OHLCV (the uniform
+ // `python <script> <command> [args…] → JSON` ABI the other 21 modules
+ // use), then add a panel + display and re-register here.
// ADVANCED
{"hft", "High Frequency Trading", "HFT", "ADVANCED", QColor("#F44336"), "ai_quant_lab/qlib_high_frequency.py",
diff --git a/fincept-qt/src/services/llm/LlmFinceptAsync.cpp b/fincept-qt/src/services/llm/LlmFinceptAsync.cpp
index f4f3f7e8a..107e5c903 100644
--- a/fincept-qt/src/services/llm/LlmFinceptAsync.cpp
+++ b/fincept-qt/src/services/llm/LlmFinceptAsync.cpp
@@ -136,10 +136,11 @@ LlmResponse LlmService::fincept_async_request(const QString& user_message,
const QString async_url = fincept_base + "/research/llm/async";
const QString status_base = fincept_base + "/research/llm/status/";
- LOG_INFO(kLlmFinceptTag, QString("Fincept async: submitting to %1 (api_key=%2, prompt_len=%3)")
- .arg(async_url)
- .arg(api_key_.isEmpty() ? "EMPTY" : api_key_.left(12) + "...")
- .arg(prompt.length()));
+ LOG_INFO(kLlmFinceptTag,
+ QString("Fincept async: submitting to %1 (api_key=%2, prompt_len=%3)")
+ .arg(async_url)
+ .arg(api_key_.isEmpty() ? QStringLiteral("EMPTY") : QStringLiteral("len=%1").arg(api_key_.size()))
+ .arg(prompt.length()));
QByteArray json_data = QJsonDocument(submit_body).toJson(QJsonDocument::Compact);
auto submit = eventloop_request("POST", async_url, json_data, hdr, 30000);
diff --git a/fincept-qt/src/services/llm/LlmRequestPolicy.h b/fincept-qt/src/services/llm/LlmRequestPolicy.h
index 7c25bf2cc..b9a283a9d 100644
--- a/fincept-qt/src/services/llm/LlmRequestPolicy.h
+++ b/fincept-qt/src/services/llm/LlmRequestPolicy.h
@@ -16,14 +16,19 @@
// redirecting the user's active screen).
// ToolPolicy::None — attach no tools at all (legacy use_tools=false).
+#include "core/config/AppConfig.h"
+#include "core/logging/Logger.h"
#include "mcp/McpTypes.h"
+#include "mcp/ResultStore.h"
#include "services/llm/LlmService.h"
#include <QJsonArray>
+#include <QJsonDocument>
#include <QJsonObject>
#include <QSet>
#include <QString>
+#include <algorithm>
#include <functional>
namespace fincept::ai_chat::detail {
@@ -117,26 +122,135 @@ inline bool is_openai_family_model(const QString& model_lower) {
// model surfaces (via tool_list) or commits to (via tool_describe) across the
// turn, and feed them back into format_tools_for_openai so they become real,
// callable functions on the next round.
+// ── Tool-result size discipline ───────────────────────────────────────────
+//
+// Tool results used to be spliced into the transcript verbatim, with no cap on
+// any of the four provider paths (OpenAI first round, OpenAI tool loop,
+// Anthropic tool loop, Gemini tool loop). Because every round re-posts the
+// whole message array, one oversized result is re-billed as input on every
+// remaining round of the turn — up to 200 of them (the `max_tool_rounds`
+// clamp). A single unshaped `edgar_get_filing` could dominate a turn's cost.
+//
+// The cap is a budget, not a guillotine: whatever doesn't fit is parked in the
+// ResultStore and the envelope tells the model how to page it back with
+// `result_fetch`. Detail is available on demand instead of by default.
+
+/// Byte ceiling for a single tool result in the transcript. 8 KB carries a
+/// realistic table or article list intact; beyond that the overflow store
+/// takes over. Overridable via `mcp/tool_result_max_chars`.
+inline int tool_result_budget_bytes() {
+ return std::clamp(AppConfig::instance().get("mcp/tool_result_max_chars", QVariant(8000)).toInt(), 512, 200000);
+}
+
+/// Shrink `payload` to the budget if needed, parking the original in the
+/// ResultStore and annotating the envelope with `result_id` + retrieval note.
+/// No-op when the payload already fits.
+inline void fit_llm_payload(const QString& tool_name, QJsonObject& payload) {
+ const QByteArray compact = QJsonDocument(payload).toJson(QJsonDocument::Compact);
+ const int budget = tool_result_budget_bytes();
+ if (compact.size() <= budget)
+ return;
+
+ const QString result_id = mcp::ResultStore::instance().put(tool_name, payload);
+
+ // Shrink the whole envelope rather than just `data`: some tools carry their
+ // bulk in `message` instead, and shaping only one leaves the other free to
+ // blow the budget. Reserve headroom for the keys added below.
+ QJsonValue shaped = QJsonValue(payload);
+ const mcp::ShrinkStats st = mcp::shrink_json(shaped, std::max(512, budget - 600));
+
+ payload = shaped.isObject() ? shaped.toObject() : QJsonObject{{"data", shaped}};
+ payload["truncated"] = true;
+ payload["result_id"] = result_id;
+ payload["full_bytes"] = st.original_bytes;
+ payload["note"] = QStringLiteral("Result truncated to fit context (%1 → %2 bytes). Call "
+ "result_fetch(result_id='%3', offset=0, limit=6000) to page the full payload.")
+ .arg(st.original_bytes)
+ .arg(st.final_bytes)
+ .arg(result_id);
+
+ LOG_INFO("LlmService", QString("Tool '%1' returned %2 KB — shaped to %3 B, full payload parked as %4")
+ .arg(tool_name)
+ .arg(st.original_bytes / 1024)
+ .arg(st.final_bytes)
+ .arg(result_id));
+}
+
+/// Envelope for a tool result, shaped to the transcript budget.
+inline QJsonObject shape_tool_result_for_llm(const QString& tool_name, const mcp::ToolResult& tr) {
+ QJsonObject envelope = tr.to_json();
+ fit_llm_payload(tool_name, envelope);
+ return envelope;
+}
+
+/// Same, serialised — for the providers whose tool messages take a string.
+inline QString encode_tool_result_for_llm(const QString& tool_name, const mcp::ToolResult& tr) {
+ return QString::fromUtf8(QJsonDocument(shape_tool_result_for_llm(tool_name, tr)).toJson(QJsonDocument::Compact));
+}
+
+// Ceiling on how many discovered tools stay declared at once.
+//
+// Every activated tool re-enters the `tools` array on every subsequent round,
+// at full schema size. Left unbounded (the previous behaviour), a turn that
+// makes eight tool_list calls has ~40 extra schemas riding along by mid-turn —
+// which is roughly the whole catalogue Tier-0 exists to avoid sending, so the
+// ~85% saving quietly evaporates exactly when the turn is longest.
+//
+// 24 is comfortably above what any single turn genuinely juggles (top_k is
+// capped at 20 and defaults to 5) while keeping the tail bounded.
+inline constexpr int kMaxActivatedTools = 24;
+
+/// Insertion-ordered, capped set of tools the model has discovered this turn.
+/// Evicts least-recently-activated first, so a tool the model keeps coming back
+/// to survives while stale candidates from an early search age out.
+class ActivationTracker {
+ public:
+ ActivationTracker() = default;
+ explicit ActivationTracker(const QSet<QString>& seed) {
+ for (const auto& n : seed)
+ add(n);
+ }
+
+ void add(const QString& name) {
+ if (name.isEmpty())
+ return;
+ if (set_.contains(name)) {
+ order_.removeOne(name); // re-activation refreshes recency
+ order_.append(name);
+ return;
+ }
+ set_.insert(name);
+ order_.append(name);
+ while (order_.size() > kMaxActivatedTools)
+ set_.remove(order_.takeFirst());
+ }
+
+ const QSet<QString>& names() const { return set_; }
+ int size() const { return set_.size(); }
+
+ private:
+ QStringList order_; // least-recently-activated at the front
+ QSet<QString> set_;
+};
+
inline void note_tool_activations(const QString& bare_tool_name, const QJsonObject& args, const mcp::ToolResult& result,
- QSet<QString>& activated) {
+ ActivationTracker& activated) {
if (!result.success)
return;
if (bare_tool_name == QLatin1String("tool_list")) {
// Activate every candidate the search surfaced — the model may pick any.
const QJsonArray rows = result.data.toObject().value("tools").toArray();
- for (const auto& row : rows) {
- const QString name = row.toObject().value("name").toString();
- if (!name.isEmpty())
- activated.insert(name);
- }
+ for (const auto& row : rows)
+ activated.add(row.toObject().value("name").toString());
} else if (bare_tool_name == QLatin1String("tool_describe")) {
// The model committed to one tool — prefer the canonical name echoed in
- // the result, fall back to the name it asked about.
+ // the result, fall back to the name it asked about. Adding it last also
+ // makes it the most-recently-used entry, so it outlives the rest of the
+ // search batch it came from.
QString name = result.data.toObject().value("name").toString();
if (name.isEmpty())
name = args.value("name").toString();
- if (!name.isEmpty())
- activated.insert(name);
+ activated.add(name);
}
}
diff --git a/fincept-qt/src/services/llm/LlmService.cpp b/fincept-qt/src/services/llm/LlmService.cpp
index b61c1d387..7c99f2025 100644
--- a/fincept-qt/src/services/llm/LlmService.cpp
+++ b/fincept-qt/src/services/llm/LlmService.cpp
@@ -497,11 +497,11 @@ LlmResponse LlmService::do_request(const QString& user_message, const std::vecto
QJsonObject input = block["input"].toObject();
LOG_INFO(kLlmSvcTag, "Executing Anthropic tool: " + tool_name);
- auto tr = mcp::McpService::instance().execute_openai_function(tool_name, input);
- tool_results.append(QJsonObject{
- {"type", "tool_result"},
- {"tool_use_id", tool_id},
- {"content", QString::fromUtf8(QJsonDocument(tr.to_json()).toJson(QJsonDocument::Compact))}});
+ auto tr = mcp::McpService::instance().execute_openai_function(tool_name, input, /*allow_defer=*/true);
+ tool_results.append(
+ QJsonObject{{"type", "tool_result"},
+ {"tool_use_id", tool_id},
+ {"content", detail::encode_tool_result_for_llm(tool_name, tr)}});
}
loop_msgs.append(QJsonObject{{"role", "user"}, {"content", tool_results}});
@@ -555,11 +555,11 @@ LlmResponse LlmService::do_request(const QString& user_message, const std::vecto
const QString tid = block["id"].toString();
const QString tname = block["name"].toString();
LOG_INFO(kLlmSvcTag, QString("Anthropic tool loop r%1: %2").arg(round).arg(tname));
- auto tr = mcp::McpService::instance().execute_openai_function(tname, block["input"].toObject());
- more_results.append(QJsonObject{
- {"type", "tool_result"},
- {"tool_use_id", tid},
- {"content", QString::fromUtf8(QJsonDocument(tr.to_json()).toJson(QJsonDocument::Compact))}});
+ auto tr = mcp::McpService::instance().execute_openai_function(tname, block["input"].toObject(),
+ /*allow_defer=*/true);
+ more_results.append(QJsonObject{{"type", "tool_result"},
+ {"tool_use_id", tid},
+ {"content", detail::encode_tool_result_for_llm(tname, tr)}});
}
loop_msgs.append(QJsonObject{{"role", "user"}, {"content", more_results}});
}
@@ -620,7 +620,8 @@ LlmResponse LlmService::do_request(const QString& user_message, const std::vecto
const QJsonObject fc = part["functionCall"].toObject();
const QString fn_name = fc["name"].toString();
LOG_INFO(kLlmSvcTag, QString("Gemini tool loop r%1: %2").arg(round).arg(fn_name));
- auto tr = mcp::McpService::instance().execute_openai_function(fn_name, fc["args"].toObject());
+ auto tr = mcp::McpService::instance().execute_openai_function(fn_name, fc["args"].toObject(),
+ /*allow_defer=*/true);
// Gemini requires response to be an object — wrap strings under "result".
QJsonObject response_obj;
if (!tr.data.isNull() && !tr.data.isUndefined() && tr.data.isObject())
@@ -629,6 +630,9 @@ LlmResponse LlmService::do_request(const QString& user_message, const std::vecto
response_obj["result"] = tr.message;
else
response_obj = tr.to_json();
+ // Same transcript budget as the other providers — this
+ // path re-posts `fu_contents` wholesale every round too.
+ detail::fit_llm_payload(fn_name, response_obj);
fn_response_parts.append(QJsonObject{
{"functionResponse", QJsonObject{{"name", fn_name}, {"response", response_obj}}}});
}
@@ -731,7 +735,7 @@ LlmResponse LlmService::do_request(const QString& user_message, const std::vecto
// Tools the model has discovered this turn — seeded from this
// first round so the loop can re-declare them on the next turn
// (Tool RAG only ships Tier-0 otherwise; see note_tool_activations).
- QSet<QString> activated;
+ detail::ActivationTracker activated;
for (const auto& tc_val : tcs) {
QJsonObject tc = tc_val.toObject();
@@ -746,19 +750,19 @@ LlmResponse LlmService::do_request(const QString& user_message, const std::vecto
QString("Executing tool: %1 args=%2")
.arg(fn_name,
QString::fromUtf8(QJsonDocument(fn_args).toJson(QJsonDocument::Compact)).left(200)));
- auto tr = mcp::McpService::instance().execute_openai_function(fn_name, fn_args);
+ auto tr =
+ mcp::McpService::instance().execute_openai_function(fn_name, fn_args, /*allow_defer=*/true);
LOG_INFO(kLlmSvcTag,
QString("Tool %1 -> %2 (msg=%3 err=%4)")
.arg(fn_name, tr.success ? "OK" : "FAIL", tr.message.left(120), tr.error.left(120)));
const QString bare = mcp::McpProvider::parse_openai_function_name(fn_name).second;
detail::note_tool_activations(bare, fn_args, tr, activated);
- loop_msgs.append(QJsonObject{
- {"role", "tool"},
- {"tool_call_id", call_id},
- {"content", QString::fromUtf8(QJsonDocument(tr.to_json()).toJson(QJsonDocument::Compact))}});
+ loop_msgs.append(QJsonObject{{"role", "tool"},
+ {"tool_call_id", call_id},
+ {"content", detail::encode_tool_result_for_llm(bare, tr)}});
}
- resp = do_tool_loop(loop_msgs, url, hdr, activated);
+ resp = do_tool_loop(loop_msgs, url, hdr, activated.names());
parse_usage(resp, rj, provider_);
return resp;
diff --git a/fincept-qt/src/services/llm/LlmToolLoop.cpp b/fincept-qt/src/services/llm/LlmToolLoop.cpp
index ea850a80e..a4d809c21 100644
--- a/fincept-qt/src/services/llm/LlmToolLoop.cpp
+++ b/fincept-qt/src/services/llm/LlmToolLoop.cpp
@@ -7,9 +7,11 @@
// emitted by models that don't support structured tool_calls (minimax,
// some OpenRouter models). Executes them and asks the LLM to summarise.
+#include "core/config/AppConfig.h"
#include "core/logging/Logger.h"
#include "mcp/McpProvider.h"
#include "mcp/McpService.h"
+#include "mcp/ResultStore.h"
#include "services/llm/LlmContentExtractors.h"
#include "services/llm/LlmRequestPolicy.h"
#include "services/llm/LlmService.h"
@@ -20,17 +22,21 @@
#include <QRegularExpression>
#include <QString>
+#include <algorithm>
#include <vector>
namespace fincept::ai_chat {
namespace {
constexpr const char* kLlmToolLoopTag = "LlmService";
-}
+} // namespace
LlmResponse LlmService::do_tool_loop(QJsonArray loop_messages, const QString& url,
const QMap<QString, QString>& headers, QSet<QString> activated_tools) {
LlmResponse resp;
+ // Bounded, LRU-evicting view over the discovered-tool set — see
+ // ActivationTracker for why an unbounded set defeats Tier-0.
+ detail::ActivationTracker activated(activated_tools);
// MiniMax-style models spend 3 rounds per action (tool_list → tool_describe
// → actual call), so the default 40 gives ~13 real actions — enough for a
// full report template fill. Below ~12 silently cripples report-builder flows.
@@ -45,7 +51,7 @@ LlmResponse LlmService::do_tool_loop(QJsonArray loop_messages, const QString& ur
fu["max_tokens"] = resolved_max_tokens();
QJsonArray tools = mcp::McpService::instance().format_tools_for_openai(
- detail::apply_request_policy(tool_filter_), activated_tools);
+ detail::apply_request_policy(tool_filter_), activated.names());
if (!tools.isEmpty())
fu["tools"] = tools;
@@ -93,18 +99,20 @@ LlmResponse LlmService::do_tool_loop(QJsonArray loop_messages, const QString& ur
display = display.mid(sep + 2);
display.replace(QStringLiteral("-dot-"), QStringLiteral("."));
detail::emit_progress(QStringLiteral("• ") + display + QStringLiteral("\n"));
- auto tr = mcp::McpService::instance().execute_openai_function(fname, fa);
+ // allow_defer: this is the one call site that knows about the
+ // job_* tools, so it is the one allowed to receive a receipt
+ // instead of a result for a long-running tool.
+ auto tr = mcp::McpService::instance().execute_openai_function(fname, fa, /*allow_defer=*/true);
LOG_INFO(kLlmToolLoopTag,
QString("TOOL LOOP r%1: %2 -> %3 (msg=%4 err=%5)")
.arg(round)
.arg(fname, tr.success ? "OK" : "FAIL", tr.message.left(120), tr.error.left(120)));
// If this was a discovery call (tool_list / tool_describe), declare
// what it surfaced so the model can actually call it next round.
- detail::note_tool_activations(display, fa, tr, activated_tools);
- loop_messages.append(QJsonObject{
- {"role", "tool"},
- {"tool_call_id", cid},
- {"content", QString::fromUtf8(QJsonDocument(tr.to_json()).toJson(QJsonDocument::Compact))}});
+ detail::note_tool_activations(display, fa, tr, activated);
+ loop_messages.append(QJsonObject{{"role", "tool"},
+ {"tool_call_id", cid},
+ {"content", detail::encode_tool_result_for_llm(display, tr)}});
}
continue;
}
@@ -161,7 +169,7 @@ LlmResponse LlmService::do_tool_loop(QJsonArray loop_messages, const QString& ur
// which leaked into the chat bubble. Carry the activated set so a
// last-ditch tool call can still reference a discovered tool.
QJsonArray tools = mcp::McpService::instance().format_tools_for_openai(
- detail::apply_request_policy(tool_filter_), activated_tools);
+ detail::apply_request_policy(tool_filter_), activated.names());
if (!tools.isEmpty())
fu["tools"] = tools;
@@ -400,14 +408,28 @@ std::optional<LlmResponse> LlmService::try_extract_and_execute_text_tool_calls(c
detail::emit_progress(QStringLiteral("Using `") + display + QStringLiteral("` …\n"));
auto tr = mcp::McpService::instance().execute_openai_function(tc.name, tc.args);
+ // Shaped rather than clipped at a byte offset. Two reasons: `.left(4000)`
+ // cut the JSON mid-token, leaving the model to interpret a malformed
+ // fragment; and `tr.data.toObject()` silently rendered array payloads as
+ // "{}" — a whole result vanishing without a trace. shrink_json keeps the
+ // JSON valid and marks in-place what it dropped.
+ //
+ // No result_id handoff here: the follow-up request on this path attaches
+ // no tools, so pointing the model at result_fetch would be a dead
+ // instruction. This path is the fallback for models without structured
+ // tool calls; the structured loop above is where the overflow store applies.
QString result_content;
- if (!tr.message.isEmpty())
+ if (!tr.message.isEmpty()) {
result_content = tr.message;
- else if (!tr.data.isNull() && !tr.data.isUndefined())
- result_content =
- QString::fromUtf8(QJsonDocument(tr.data.toObject()).toJson(QJsonDocument::Compact)).left(4000);
- else
- result_content = QString::fromUtf8(QJsonDocument(tr.to_json()).toJson(QJsonDocument::Compact)).left(4000);
+ } else {
+ QJsonValue payload = (!tr.data.isNull() && !tr.data.isUndefined()) ? tr.data : QJsonValue(tr.to_json());
+ mcp::shrink_json(payload, 4000);
+ result_content = payload.isObject()
+ ? QString::fromUtf8(QJsonDocument(payload.toObject()).toJson(QJsonDocument::Compact))
+ : payload.isArray()
+ ? QString::fromUtf8(QJsonDocument(payload.toArray()).toJson(QJsonDocument::Compact))
+ : payload.toVariant().toString();
+ }
int sep = tc.name.indexOf("__");
QString short_name = (sep >= 0) ? tc.name.mid(sep + 2) : tc.name;
diff --git a/fincept-qt/src/services/notifications/providers/BaseProvider.h b/fincept-qt/src/services/notifications/providers/BaseProvider.h
index f3746983c..d3425ed0a 100644
--- a/fincept-qt/src/services/notifications/providers/BaseProvider.h
+++ b/fincept-qt/src/services/notifications/providers/BaseProvider.h
@@ -1,6 +1,7 @@
#pragma once
#include "services/notifications/NotificationService.h"
#include "storage/repositories/SettingsRepository.h"
+#include "storage/secure/SecureStorage.h"
namespace fincept::notifications {
@@ -41,6 +42,37 @@ class BaseProvider : public INotificationProvider {
return res.is_ok() ? res.value() : QString{};
}
+ // ── Secret fields ────────────────────────────────────────────────────────
+ // SMTP passwords, bot tokens, API keys and webhook URLs must NOT sit in the
+ // plaintext `settings` SQLite table — Settings ▸ Storage ships a SQL console
+ // with a one-click `SELECT * FROM settings` that would render them on screen.
+ // These mirror the proven LlmConfigRepository pattern: read prefers
+ // SecureStorage (AES-256-GCM, machine-bound) and falls back to the legacy
+ // plaintext column so no existing credential is ever lost; write moves the
+ // value into SecureStorage and blanks the column, but ONLY if the encrypted
+ // store succeeded — a failure keeps the plaintext rather than losing the key.
+
+ static QString secret_handle(const QString& key) { return QStringLiteral("notif:secret:") + key; }
+
+ static QString get_secret(SettingsRepository& r, const QString& key) {
+ auto sr = SecureStorage::instance().retrieve(secret_handle(key));
+ if (sr.is_ok() && !sr.value().isEmpty())
+ return sr.value();
+ return get_str(r, key); // legacy plaintext row, migrated on next save
+ }
+
+ static void set_secret(SettingsRepository& r, const QString& key, const QString& value, const QString& cat) {
+ if (value.isEmpty()) {
+ SecureStorage::instance().remove(secret_handle(key));
+ r.set(key, QString{}, cat);
+ return;
+ }
+ if (SecureStorage::instance().store(secret_handle(key), value).is_ok())
+ r.set(key, QString{}, cat); // encrypted copy is authoritative
+ else
+ r.set(key, value, cat); // keychain unavailable — don't drop the credential
+ }
+
/// Subclasses load their specific credential fields here.
virtual void load_fields(SettingsRepository& r, const QString& cat) = 0;
/// Subclasses persist their specific credential fields here.
diff --git a/fincept-qt/src/services/notifications/providers/DiscordProvider.cpp b/fincept-qt/src/services/notifications/providers/DiscordProvider.cpp
index 78934fe86..86dc37375 100644
--- a/fincept-qt/src/services/notifications/providers/DiscordProvider.cpp
+++ b/fincept-qt/src/services/notifications/providers/DiscordProvider.cpp
@@ -1,4 +1,4 @@
-#include "services/notifications/providers/DiscordProvider.h"
+#include "services/notifications/providers/DiscordProvider.h"
#include "network/http/HttpClient.h"
@@ -8,11 +8,11 @@
namespace fincept::notifications {
void DiscordProvider::load_fields(SettingsRepository& r, const QString& cat) {
- webhook_url_ = get_str(r, cat + ".webhook_url");
+ webhook_url_ = get_secret(r, cat + ".webhook_url");
}
void DiscordProvider::save_fields(SettingsRepository& r, const QString& cat) {
- r.set(cat + ".webhook_url", webhook_url_, cat);
+ set_secret(r, cat + ".webhook_url", webhook_url_, cat);
}
void DiscordProvider::send(const NotificationRequest& req, std::function<void(bool, QString)> cb) {
@@ -47,7 +47,7 @@ void DiscordProvider::send(const NotificationRequest& req, std::function<void(bo
body["embeds"] = embeds;
HttpClient::instance().post(webhook_url_, body, [cb](Result<QJsonDocument> res) {
- // Discord returns 204 No Content on success — HttpClient may return empty body
+ // Discord returns 204 No Content on success — HttpClient may return empty body
if (res.is_err()) {
const auto& err = res.error();
// "HTTP_204" is a successful empty response
diff --git a/fincept-qt/src/services/notifications/providers/EmailProvider.cpp b/fincept-qt/src/services/notifications/providers/EmailProvider.cpp
index b72f6f1e8..e7440b978 100644
--- a/fincept-qt/src/services/notifications/providers/EmailProvider.cpp
+++ b/fincept-qt/src/services/notifications/providers/EmailProvider.cpp
@@ -1,4 +1,4 @@
-#include "services/notifications/providers/EmailProvider.h"
+#include "services/notifications/providers/EmailProvider.h"
#include "network/http/HttpClient.h"
@@ -10,7 +10,7 @@ void EmailProvider::load_fields(SettingsRepository& r, const QString& cat) {
smtp_host_ = get_str(r, cat + ".smtp_host");
smtp_port_ = get_str(r, cat + ".smtp_port");
smtp_user_ = get_str(r, cat + ".smtp_user");
- smtp_pass_ = get_str(r, cat + ".smtp_pass");
+ smtp_pass_ = get_secret(r, cat + ".smtp_pass");
to_addr_ = get_str(r, cat + ".to_addr");
from_addr_ = get_str(r, cat + ".from_addr");
}
@@ -19,7 +19,7 @@ void EmailProvider::save_fields(SettingsRepository& r, const QString& cat) {
r.set(cat + ".smtp_host", smtp_host_, cat);
r.set(cat + ".smtp_port", smtp_port_, cat);
r.set(cat + ".smtp_user", smtp_user_, cat);
- r.set(cat + ".smtp_pass", smtp_pass_, cat);
+ set_secret(r, cat + ".smtp_pass", smtp_pass_, cat);
r.set(cat + ".to_addr", to_addr_, cat);
r.set(cat + ".from_addr", from_addr_, cat);
}
diff --git a/fincept-qt/src/services/notifications/providers/GotifyProvider.cpp b/fincept-qt/src/services/notifications/providers/GotifyProvider.cpp
index d7758a137..1983bf2eb 100644
--- a/fincept-qt/src/services/notifications/providers/GotifyProvider.cpp
+++ b/fincept-qt/src/services/notifications/providers/GotifyProvider.cpp
@@ -1,4 +1,4 @@
-#include "services/notifications/providers/GotifyProvider.h"
+#include "services/notifications/providers/GotifyProvider.h"
#include "network/http/HttpClient.h"
@@ -8,12 +8,12 @@ namespace fincept::notifications {
void GotifyProvider::load_fields(SettingsRepository& r, const QString& cat) {
server_url_ = get_str(r, cat + ".server_url");
- app_token_ = get_str(r, cat + ".app_token");
+ app_token_ = get_secret(r, cat + ".app_token");
}
void GotifyProvider::save_fields(SettingsRepository& r, const QString& cat) {
r.set(cat + ".server_url", server_url_, cat);
- r.set(cat + ".app_token", app_token_, cat);
+ set_secret(r, cat + ".app_token", app_token_, cat);
}
void GotifyProvider::send(const NotificationRequest& req, std::function<void(bool, QString)> cb) {
diff --git a/fincept-qt/src/services/notifications/providers/MattermostProvider.cpp b/fincept-qt/src/services/notifications/providers/MattermostProvider.cpp
index a87e7bd8d..7afc9f5b9 100644
--- a/fincept-qt/src/services/notifications/providers/MattermostProvider.cpp
+++ b/fincept-qt/src/services/notifications/providers/MattermostProvider.cpp
@@ -1,4 +1,4 @@
-#include "services/notifications/providers/MattermostProvider.h"
+#include "services/notifications/providers/MattermostProvider.h"
#include "network/http/HttpClient.h"
@@ -7,13 +7,13 @@
namespace fincept::notifications {
void MattermostProvider::load_fields(SettingsRepository& r, const QString& cat) {
- webhook_url_ = get_str(r, cat + ".webhook_url");
+ webhook_url_ = get_secret(r, cat + ".webhook_url");
channel_ = get_str(r, cat + ".channel");
username_ = get_str(r, cat + ".username");
}
void MattermostProvider::save_fields(SettingsRepository& r, const QString& cat) {
- r.set(cat + ".webhook_url", webhook_url_, cat);
+ set_secret(r, cat + ".webhook_url", webhook_url_, cat);
r.set(cat + ".channel", channel_, cat);
r.set(cat + ".username", username_, cat);
}
diff --git a/fincept-qt/src/services/notifications/providers/NtfyProvider.cpp b/fincept-qt/src/services/notifications/providers/NtfyProvider.cpp
index 3e0901c11..96c03b5e3 100644
--- a/fincept-qt/src/services/notifications/providers/NtfyProvider.cpp
+++ b/fincept-qt/src/services/notifications/providers/NtfyProvider.cpp
@@ -1,4 +1,4 @@
-#include "services/notifications/providers/NtfyProvider.h"
+#include "services/notifications/providers/NtfyProvider.h"
#include "network/http/HttpClient.h"
@@ -9,13 +9,13 @@ namespace fincept::notifications {
void NtfyProvider::load_fields(SettingsRepository& r, const QString& cat) {
server_url_ = get_str(r, cat + ".server_url");
topic_ = get_str(r, cat + ".topic");
- token_ = get_str(r, cat + ".token");
+ token_ = get_secret(r, cat + ".token");
}
void NtfyProvider::save_fields(SettingsRepository& r, const QString& cat) {
r.set(cat + ".server_url", server_url_, cat);
r.set(cat + ".topic", topic_, cat);
- r.set(cat + ".token", token_, cat);
+ set_secret(r, cat + ".token", token_, cat);
}
void NtfyProvider::send(const NotificationRequest& req, std::function<void(bool, QString)> cb) {
diff --git a/fincept-qt/src/services/notifications/providers/OpsgenieProvider.cpp b/fincept-qt/src/services/notifications/providers/OpsgenieProvider.cpp
index 69bd5ce30..8a18fe0e3 100644
--- a/fincept-qt/src/services/notifications/providers/OpsgenieProvider.cpp
+++ b/fincept-qt/src/services/notifications/providers/OpsgenieProvider.cpp
@@ -1,4 +1,4 @@
-#include "services/notifications/providers/OpsgenieProvider.h"
+#include "services/notifications/providers/OpsgenieProvider.h"
#include "network/http/HttpClient.h"
@@ -7,11 +7,11 @@
namespace fincept::notifications {
void OpsgenieProvider::load_fields(SettingsRepository& r, const QString& cat) {
- api_key_ = get_str(r, cat + ".api_key");
+ api_key_ = get_secret(r, cat + ".api_key");
}
void OpsgenieProvider::save_fields(SettingsRepository& r, const QString& cat) {
- r.set(cat + ".api_key", api_key_, cat);
+ set_secret(r, cat + ".api_key", api_key_, cat);
}
void OpsgenieProvider::send(const NotificationRequest& req, std::function<void(bool, QString)> cb) {
diff --git a/fincept-qt/src/services/notifications/providers/PagerDutyProvider.cpp b/fincept-qt/src/services/notifications/providers/PagerDutyProvider.cpp
index e0f3eef42..c4a5c9819 100644
--- a/fincept-qt/src/services/notifications/providers/PagerDutyProvider.cpp
+++ b/fincept-qt/src/services/notifications/providers/PagerDutyProvider.cpp
@@ -1,4 +1,4 @@
-#include "services/notifications/providers/PagerDutyProvider.h"
+#include "services/notifications/providers/PagerDutyProvider.h"
#include "network/http/HttpClient.h"
@@ -8,11 +8,11 @@
namespace fincept::notifications {
void PagerDutyProvider::load_fields(SettingsRepository& r, const QString& cat) {
- routing_key_ = get_str(r, cat + ".routing_key");
+ routing_key_ = get_secret(r, cat + ".routing_key");
}
void PagerDutyProvider::save_fields(SettingsRepository& r, const QString& cat) {
- r.set(cat + ".routing_key", routing_key_, cat);
+ set_secret(r, cat + ".routing_key", routing_key_, cat);
}
void PagerDutyProvider::send(const NotificationRequest& req, std::function<void(bool, QString)> cb) {
diff --git a/fincept-qt/src/services/notifications/providers/PushbulletProvider.cpp b/fincept-qt/src/services/notifications/providers/PushbulletProvider.cpp
index 0b0193c57..67a4032bb 100644
--- a/fincept-qt/src/services/notifications/providers/PushbulletProvider.cpp
+++ b/fincept-qt/src/services/notifications/providers/PushbulletProvider.cpp
@@ -1,4 +1,4 @@
-#include "services/notifications/providers/PushbulletProvider.h"
+#include "services/notifications/providers/PushbulletProvider.h"
#include "network/http/HttpClient.h"
@@ -7,12 +7,12 @@
namespace fincept::notifications {
void PushbulletProvider::load_fields(SettingsRepository& r, const QString& cat) {
- api_key_ = get_str(r, cat + ".api_key");
+ api_key_ = get_secret(r, cat + ".api_key");
channel_tag_ = get_str(r, cat + ".channel_tag");
}
void PushbulletProvider::save_fields(SettingsRepository& r, const QString& cat) {
- r.set(cat + ".api_key", api_key_, cat);
+ set_secret(r, cat + ".api_key", api_key_, cat);
r.set(cat + ".channel_tag", channel_tag_, cat);
}
diff --git a/fincept-qt/src/services/notifications/providers/PushoverProvider.cpp b/fincept-qt/src/services/notifications/providers/PushoverProvider.cpp
index 8cedcd00d..4a7ab6afc 100644
--- a/fincept-qt/src/services/notifications/providers/PushoverProvider.cpp
+++ b/fincept-qt/src/services/notifications/providers/PushoverProvider.cpp
@@ -1,4 +1,4 @@
-#include "services/notifications/providers/PushoverProvider.h"
+#include "services/notifications/providers/PushoverProvider.h"
#include "network/http/HttpClient.h"
@@ -7,13 +7,13 @@
namespace fincept::notifications {
void PushoverProvider::load_fields(SettingsRepository& r, const QString& cat) {
- api_token_ = get_str(r, cat + ".api_token");
- user_key_ = get_str(r, cat + ".user_key");
+ api_token_ = get_secret(r, cat + ".api_token");
+ user_key_ = get_secret(r, cat + ".user_key");
}
void PushoverProvider::save_fields(SettingsRepository& r, const QString& cat) {
- r.set(cat + ".api_token", api_token_, cat);
- r.set(cat + ".user_key", user_key_, cat);
+ set_secret(r, cat + ".api_token", api_token_, cat);
+ set_secret(r, cat + ".user_key", user_key_, cat);
}
void PushoverProvider::send(const NotificationRequest& req, std::function<void(bool, QString)> cb) {
diff --git a/fincept-qt/src/services/notifications/providers/SMSProvider.cpp b/fincept-qt/src/services/notifications/providers/SMSProvider.cpp
index 75fe653ea..7cd5cf7c4 100644
--- a/fincept-qt/src/services/notifications/providers/SMSProvider.cpp
+++ b/fincept-qt/src/services/notifications/providers/SMSProvider.cpp
@@ -1,4 +1,4 @@
-#include "services/notifications/providers/SMSProvider.h"
+#include "services/notifications/providers/SMSProvider.h"
#include "network/http/HttpClient.h"
@@ -8,14 +8,14 @@ namespace fincept::notifications {
void SMSProvider::load_fields(SettingsRepository& r, const QString& cat) {
account_sid_ = get_str(r, cat + ".account_sid");
- auth_token_ = get_str(r, cat + ".auth_token");
+ auth_token_ = get_secret(r, cat + ".auth_token");
from_number_ = get_str(r, cat + ".from_number");
to_number_ = get_str(r, cat + ".to_number");
}
void SMSProvider::save_fields(SettingsRepository& r, const QString& cat) {
r.set(cat + ".account_sid", account_sid_, cat);
- r.set(cat + ".auth_token", auth_token_, cat);
+ set_secret(r, cat + ".auth_token", auth_token_, cat);
r.set(cat + ".from_number", from_number_, cat);
r.set(cat + ".to_number", to_number_, cat);
}
diff --git a/fincept-qt/src/services/notifications/providers/SlackProvider.cpp b/fincept-qt/src/services/notifications/providers/SlackProvider.cpp
index ed07bfc98..bf3ca4eb4 100644
--- a/fincept-qt/src/services/notifications/providers/SlackProvider.cpp
+++ b/fincept-qt/src/services/notifications/providers/SlackProvider.cpp
@@ -1,4 +1,4 @@
-#include "services/notifications/providers/SlackProvider.h"
+#include "services/notifications/providers/SlackProvider.h"
#include "network/http/HttpClient.h"
@@ -7,12 +7,12 @@
namespace fincept::notifications {
void SlackProvider::load_fields(SettingsRepository& r, const QString& cat) {
- webhook_url_ = get_str(r, cat + ".webhook_url");
+ webhook_url_ = get_secret(r, cat + ".webhook_url");
channel_ = get_str(r, cat + ".channel");
}
void SlackProvider::save_fields(SettingsRepository& r, const QString& cat) {
- r.set(cat + ".webhook_url", webhook_url_, cat);
+ set_secret(r, cat + ".webhook_url", webhook_url_, cat);
r.set(cat + ".channel", channel_, cat);
}
diff --git a/fincept-qt/src/services/notifications/providers/TeamsProvider.cpp b/fincept-qt/src/services/notifications/providers/TeamsProvider.cpp
index 09c4ff1ed..ab9f9fc2d 100644
--- a/fincept-qt/src/services/notifications/providers/TeamsProvider.cpp
+++ b/fincept-qt/src/services/notifications/providers/TeamsProvider.cpp
@@ -1,4 +1,4 @@
-#include "services/notifications/providers/TeamsProvider.h"
+#include "services/notifications/providers/TeamsProvider.h"
#include "network/http/HttpClient.h"
@@ -8,11 +8,11 @@
namespace fincept::notifications {
void TeamsProvider::load_fields(SettingsRepository& r, const QString& cat) {
- webhook_url_ = get_str(r, cat + ".webhook_url");
+ webhook_url_ = get_secret(r, cat + ".webhook_url");
}
void TeamsProvider::save_fields(SettingsRepository& r, const QString& cat) {
- r.set(cat + ".webhook_url", webhook_url_, cat);
+ set_secret(r, cat + ".webhook_url", webhook_url_, cat);
}
void TeamsProvider::send(const NotificationRequest& req, std::function<void(bool, QString)> cb) {
diff --git a/fincept-qt/src/services/notifications/providers/TelegramProvider.cpp b/fincept-qt/src/services/notifications/providers/TelegramProvider.cpp
index f40c02fe9..d78f7c15b 100644
--- a/fincept-qt/src/services/notifications/providers/TelegramProvider.cpp
+++ b/fincept-qt/src/services/notifications/providers/TelegramProvider.cpp
@@ -1,4 +1,4 @@
-#include "services/notifications/providers/TelegramProvider.h"
+#include "services/notifications/providers/TelegramProvider.h"
#include "network/http/HttpClient.h"
@@ -7,12 +7,12 @@
namespace fincept::notifications {
void TelegramProvider::load_fields(SettingsRepository& r, const QString& cat) {
- bot_token_ = get_str(r, cat + ".bot_token");
+ bot_token_ = get_secret(r, cat + ".bot_token");
chat_id_ = get_str(r, cat + ".chat_id");
}
void TelegramProvider::save_fields(SettingsRepository& r, const QString& cat) {
- r.set(cat + ".bot_token", bot_token_, cat);
+ set_secret(r, cat + ".bot_token", bot_token_, cat);
r.set(cat + ".chat_id", chat_id_, cat);
}
@@ -27,13 +27,13 @@ void TelegramProvider::send(const NotificationRequest& req, std::function<void(b
const QString level_tag = [&]() -> QString {
switch (req.level) {
case NotifLevel::Warning:
- return "⚠️ ";
+ return "⚠️ ";
case NotifLevel::Alert:
- return "🔔 ";
+ return "🔔 ";
case NotifLevel::Critical:
- return "🚨 ";
+ return "🚨 ";
default:
- return "ℹ️ ";
+ return "ℹ️ ";
}
}();
diff --git a/fincept-qt/src/services/notifications/providers/WebhookProvider.cpp b/fincept-qt/src/services/notifications/providers/WebhookProvider.cpp
index d44ca1044..e78e1e62d 100644
--- a/fincept-qt/src/services/notifications/providers/WebhookProvider.cpp
+++ b/fincept-qt/src/services/notifications/providers/WebhookProvider.cpp
@@ -1,4 +1,4 @@
-#include "services/notifications/providers/WebhookProvider.h"
+#include "services/notifications/providers/WebhookProvider.h"
#include "network/http/HttpClient.h"
@@ -7,14 +7,14 @@
namespace fincept::notifications {
void WebhookProvider::load_fields(SettingsRepository& r, const QString& cat) {
- url_ = get_str(r, cat + ".url");
+ url_ = get_secret(r, cat + ".url");
method_ = get_str(r, cat + ".method");
if (method_.isEmpty())
method_ = "POST";
}
void WebhookProvider::save_fields(SettingsRepository& r, const QString& cat) {
- r.set(cat + ".url", url_, cat);
+ set_secret(r, cat + ".url", url_, cat);
r.set(cat + ".method", method_, cat);
}
diff --git a/fincept-qt/src/services/notifications/providers/WhatsAppProvider.cpp b/fincept-qt/src/services/notifications/providers/WhatsAppProvider.cpp
index 57f26cdcc..4c9872700 100644
--- a/fincept-qt/src/services/notifications/providers/WhatsAppProvider.cpp
+++ b/fincept-qt/src/services/notifications/providers/WhatsAppProvider.cpp
@@ -1,4 +1,4 @@
-#include "services/notifications/providers/WhatsAppProvider.h"
+#include "services/notifications/providers/WhatsAppProvider.h"
#include "network/http/HttpClient.h"
@@ -9,14 +9,14 @@ namespace fincept::notifications {
void WhatsAppProvider::load_fields(SettingsRepository& r, const QString& cat) {
account_sid_ = get_str(r, cat + ".account_sid");
- auth_token_ = get_str(r, cat + ".auth_token");
+ auth_token_ = get_secret(r, cat + ".auth_token");
from_number_ = get_str(r, cat + ".from_number");
to_number_ = get_str(r, cat + ".to_number");
}
void WhatsAppProvider::save_fields(SettingsRepository& r, const QString& cat) {
r.set(cat + ".account_sid", account_sid_, cat);
- r.set(cat + ".auth_token", auth_token_, cat);
+ set_secret(r, cat + ".auth_token", auth_token_, cat);
r.set(cat + ".from_number", from_number_, cat);
r.set(cat + ".to_number", to_number_, cat);
}
@@ -32,7 +32,7 @@ void WhatsAppProvider::send(const NotificationRequest& req, std::function<void(b
const QString msg = QString("[Fincept] %1\n%2").arg(req.title, req.message);
- // Twilio accepts form-encoded POST — encode as JSON fields for our HttpClient
+ // Twilio accepts form-encoded POST — encode as JSON fields for our HttpClient
// Note: Twilio's API actually needs application/x-www-form-urlencoded;
// we send JSON and the server-side relay handles encoding, or use a proxy.
QJsonObject body;
diff --git a/fincept-qt/src/services/options/StrategyAnalytics.cpp b/fincept-qt/src/services/options/StrategyAnalytics.cpp
index 8707c71cf..d7ac11331 100644
--- a/fincept-qt/src/services/options/StrategyAnalytics.cpp
+++ b/fincept-qt/src/services/options/StrategyAnalytics.cpp
@@ -15,8 +15,14 @@ using fincept::trading::InstrumentType;
namespace {
-/// Days-to-expiry for a leg, actual/365. Floors at 1 day so expiry-day
-/// strategies don't collapse the target curve into intrinsic immediately.
+/// Days-to-expiry for a leg, actual/365.
+///
+/// Returns 0 for an expiry that is today or already past — on expiry day the
+/// target curve SHOULD collapse to intrinsic, because that is what the position
+/// is actually worth. (An earlier comment here claimed a 1-day floor; no such
+/// floor was ever implemented, and adding one would overstate the remaining
+/// time value of a 0-DTE position.) The literal 1 below is only the
+/// unparseable-date fallback, where assuming "expires today" would be worse.
int days_to_expiry(const QString& expiry) {
QDate exp = QDate::fromString(expiry, "dd-MMM-yy");
if (!exp.isValid())
@@ -118,12 +124,21 @@ QVector<PayoffPoint> compute_payoff(const Strategy& s, const PayoffComputeOption
// Pick the strategy's nearest-expiry leg as the BSM time-to-expiry anchor.
// All single-expiry templates share a date; for hand-edited mixed-expiry
// strategies we use the leg-specific expiry inside leg_pnl_target.
- int dte_strategy = 0;
+ // Plain minimum over the ACTIVE legs. The previous form
+ // if (dte_strategy == 0 || (d > 0 && d < dte_strategy))
+ // skipped any leg with d == 0 unless it happened to come first, so a
+ // 0-DTE leg in a multi-expiry strategy failed to clamp days_to_target —
+ // the target curve then priced an already-expired leg as if it still had
+ // time value. Inactive legs are excluded so a toggled-off leg can't drag
+ // the whole strategy's time anchor.
+ int dte_strategy = std::numeric_limits<int>::max();
for (const auto& leg : s.legs) {
- const int d = days_to_expiry(leg.expiry);
- if (dte_strategy == 0 || (d > 0 && d < dte_strategy))
- dte_strategy = d;
+ if (!leg.is_active)
+ continue;
+ dte_strategy = std::min(dte_strategy, days_to_expiry(leg.expiry));
}
+ if (dte_strategy == std::numeric_limits<int>::max())
+ dte_strategy = 0; // no active legs — nothing to project forward
const int days_target_capped = std::clamp(opts.days_to_target, 0, dte_strategy);
out.reserve(n);
@@ -181,14 +196,35 @@ MaxPnL compute_max_pnl(const QVector<PayoffPoint>& curve, const Strategy& s) {
if (p.pnl_expiry < m.max_loss)
m.max_loss = p.pnl_expiry;
}
+ // Downside tail: the sampled curve only spans roughly spot ±30%, but the
+ // true worst case for any position with net-short puts sits at S = 0, far
+ // outside that window. Reporting the value at 0.7*spot as "Max Loss"
+ // understates a short put badly — a trader sizing off the ribbon or the
+ // order-confirm dialog under-reserves margin. The expiry payoff is
+ // piecewise-linear and, below the lowest strike, monotonically decreasing
+ // in S for a net-short-put book, so S = 0 IS the minimum. Evaluating it
+ // exactly is cheap and correct, so do it unconditionally and let it
+ // compete with the sampled minimum.
+ double pnl_at_zero = 0.0;
+ for (const auto& leg : s.legs) {
+ if (!leg.is_active || leg.lots == 0)
+ continue;
+ pnl_at_zero += leg_pnl_expiry(leg, 0.0);
+ }
+ if (pnl_at_zero < m.max_loss)
+ m.max_loss = pnl_at_zero;
+
const double net_calls = net_call_lots(s);
if (net_calls > 0) {
m.profit_unbounded = true;
m.max_profit = std::numeric_limits<double>::infinity();
} else if (net_calls < 0) {
+ // Short calls: loss grows without bound as S -> infinity.
m.loss_unbounded = true;
m.max_loss = -std::numeric_limits<double>::infinity();
}
+ // Note: net-short PUTS do NOT make the loss unbounded — the payoff floors
+ // at S = 0, which is exactly what pnl_at_zero above now captures.
return m;
}
diff --git a/fincept-qt/src/services/options/StrategyTemplates.cpp b/fincept-qt/src/services/options/StrategyTemplates.cpp
index 1fdbd837e..c5452faff 100644
--- a/fincept-qt/src/services/options/StrategyTemplates.cpp
+++ b/fincept-qt/src/services/options/StrategyTemplates.cpp
@@ -322,6 +322,14 @@ Result<Strategy> instantiate(const StrategyTemplate& tpl, const OptionChain& cha
leg.type = recipe.type;
leg.strike = row.strike;
leg.expiry = chain.expiry;
+ // CONTRACT: this can legitimately be 0. Several providers omit lot size
+ // from the chain payload entirely (Fyers options-chain-v3 always does),
+ // and 0 is propagated deliberately rather than defaulted to 1 — a
+ // fabricated lot size of 1 silently dispatches "1 lot" as "1 unit" and
+ // understates every payoff and Greek by the real multiplier.
+ // CALLERS MUST BACKFILL before dispatch or analytics (see
+ // BuilderSubTab::backfill_lot_sizes, which resolves via InstrumentService).
+ // Resolving here would drag a trading/ dependency into services/options.
leg.lot_size = row.lot_size;
leg.lots = recipe.lots * lot_mul;
leg.is_active = true;
diff --git a/fincept-qt/src/storage/secure/SecureStorage.cpp b/fincept-qt/src/storage/secure/SecureStorage.cpp
index 536145ca8..9b6f3b208 100644
--- a/fincept-qt/src/storage/secure/SecureStorage.cpp
+++ b/fincept-qt/src/storage/secure/SecureStorage.cpp
@@ -7,71 +7,110 @@
#include <QCryptographicHash>
#include <QMutex>
#include <QMutexLocker>
-#include <QRandomGenerator>
+#include <QSqlDatabase>
#include <QSqlError>
#include <QSqlQuery>
#include <QSysInfo>
+#include <QVector>
#include <openssl/err.h>
#include <openssl/evp.h>
+#include <openssl/rand.h>
+
+#ifdef Q_OS_WIN
+# ifndef WIN32_LEAN_AND_MEAN
+# define WIN32_LEAN_AND_MEAN
+# endif
+# ifndef NOMINMAX
+# define NOMINMAX
+# endif
+# include <windows.h>
+// dpapi.h must follow windows.h — it depends on its typedefs.
+# include <dpapi.h>
+#endif
// ── SQLite-backed credential store ───────────────────────────────────────────
//
-// Values live in `secure_credentials` (created by migration v025) encrypted
-// with AES-256-GCM. The 256-bit key is derived once per process from a
-// machine-local seed and cached in static storage; rotating the seed (e.g.
-// after copying the profile to another machine) makes the existing rows
-// undecryptable, which is the desired behaviour.
+// Values live in `secure_credentials` (created by migration v029) encrypted
+// with AES-256-GCM under a per-install random *data encryption key* (DEK).
+// The DEK itself is stored in the same table under a reserved key, wrapped by
+// a platform key-encryption key (KEK):
//
-// Crypto is OpenSSL EVP — already linked transitively for Google Sheets JWT
-// signing, so no new dependency. All EVP allocations are stack-bounded and
-// freed on every exit path; no heap thrash on the hot path.
+// Windows — DPAPI (CryptProtectData, user scope). The wrapping key lives in
+// the user's Windows profile and is itself protected by their
+// logon credentials. This is the meaningful control: the DB file
+// alone is useless, and *another local user cannot decrypt it*.
+// Other — PBKDF2-HMAC-SHA256 over the machine-local seed with a random
+// per-install salt. Note honestly that the seed (machine ID) is
+// readable by any local process, so the iteration count is a
+// speed bump against offline DB theft, not a defence against a
+// local attacker. Wiring macOS Keychain / libsecret in here is
+// the real fix on those platforms.
+//
+// Why the indirection: it decouples "what encrypts the rows" from "what the
+// platform can protect", so the KEK can be rotated (or upgraded to Keychain)
+// by rewrapping 32 bytes instead of re-encrypting every credential.
+//
+// Migration is automatic and lossless. Installs predating the DEK derived the
+// row key directly as SHA-256(machine seed); on first access we derive that
+// legacy key, re-encrypt every row under a fresh DEK, and store the wrapped
+// DEK — inside one transaction, so a crash mid-migration rolls back.
+//
+// Crypto is OpenSSL EVP — already linked for Google Sheets JWT signing, so no
+// new dependency. All EVP allocations are stack-bounded and freed on every
+// exit path; no heap thrash on the hot path.
static constexpr auto TAG = "SecureStorage";
namespace fincept {
namespace {
-constexpr int kKeyLen = 32; // AES-256
-constexpr int kIvLen = 12; // GCM-recommended nonce size (RFC 5116 §5)
-constexpr int kTagLen = 16; // GCM authentication tag (128 bits)
+constexpr int kKeyLen = 32; // AES-256
+constexpr int kIvLen = 12; // GCM-recommended nonce size (RFC 5116 §5)
+constexpr int kTagLen = 16; // GCM authentication tag (128 bits)
+constexpr int kSaltLen = 16; // PBKDF2 salt
+constexpr int kPbkdf2Iterations = 200000;
// Stable per-app salt mixed into the machine-ID hash so a different app
// on the same machine derives a different key. Bumping this rotates
// every key — only do that with a fresh DB.
constexpr const char* kAppSalt = "fincept-terminal/secure-storage/v1";
-// Derive the AES-256 key once and cache. Called via QMutex so the first
-// caller wins; subsequent calls return the cached buffer without rehashing.
-const QByteArray& master_key() {
- static QMutex m;
- static QByteArray cached;
- QMutexLocker lock(&m);
- if (!cached.isEmpty())
- return cached;
+// Reserved rows holding the wrapped DEK. Never returned to callers.
+constexpr const char* kDekPrefix = "__fincept_dek_v2";
+constexpr const char* kDekDpapi = "__fincept_dek_v2_dpapi";
+constexpr const char* kDekPbkdf2 = "__fincept_dek_v2_pbkdf2";
+
+bool is_reserved_key(const QString& key) {
+ return key.startsWith(QLatin1String(kDekPrefix));
+}
+
+QByteArray random_bytes(int n) {
+ QByteArray out(n, '\0');
+ if (RAND_bytes(reinterpret_cast<unsigned char*>(out.data()), n) != 1) {
+ LOG_ERROR(TAG, "RAND_bytes failed — refusing to produce weak key material");
+ return {};
+ }
+ return out;
+}
- // Two stable inputs: the platform-provided machine ID (per-user on
- // macOS, per-machine on Windows/Linux) and the OS product type. The
- // app salt suffix prevents collisions with other apps that hash the
- // same identifiers.
+// The machine-local seed. Two stable inputs: the platform-provided machine ID
+// (per-user on macOS, per-machine on Windows/Linux) and the OS product type.
+// The app salt suffix prevents collisions with other apps hashing the same
+// identifiers.
+QByteArray machine_seed() {
QByteArray seed;
seed.append(QSysInfo::machineUniqueId());
seed.append('\x1f');
seed.append(QSysInfo::productType().toUtf8());
seed.append('\x1f');
seed.append(kAppSalt);
-
- cached = QCryptographicHash::hash(seed, QCryptographicHash::Sha256);
- Q_ASSERT(cached.size() == kKeyLen);
- return cached;
+ return seed;
}
-QByteArray random_iv() {
- QByteArray iv(kIvLen, '\0');
- QRandomGenerator* rng = QRandomGenerator::system();
- for (int i = 0; i < kIvLen; ++i)
- iv[i] = static_cast<char>(rng->bounded(256));
- return iv;
+// Pre-DEK key derivation. Only used to read rows written by older installs.
+QByteArray legacy_key() {
+ return QCryptographicHash::hash(machine_seed(), QCryptographicHash::Sha256);
}
// AES-256-GCM encrypt. Returns ciphertext + the GCM tag through `tag_out`.
@@ -132,7 +171,7 @@ QByteArray aes_gcm_encrypt(const QByteArray& key, const QByteArray& iv, const QB
QByteArray aes_gcm_decrypt(const QByteArray& key, const QByteArray& iv, const QByteArray& ciphertext,
const QByteArray& tag, bool& ok_out) {
ok_out = false;
- if (iv.size() != kIvLen || tag.size() != kTagLen)
+ if (key.size() != kKeyLen || iv.size() != kIvLen || tag.size() != kTagLen)
return {};
EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new();
@@ -172,6 +211,321 @@ QByteArray aes_gcm_decrypt(const QByteArray& key, const QByteArray& iv, const QB
return out;
}
+// ── DEK wrapping ────────────────────────────────────────────────────────────
+// A wrapped DEK is stored in the (ciphertext, iv, tag) columns of its reserved
+// row. Layout differs per scheme; the row key names the scheme so a reader
+// always knows how to interpret the blobs.
+
+#ifdef Q_OS_WIN
+// DPAPI: ciphertext = the opaque DPAPI blob, iv/tag unused (empty).
+bool dpapi_wrap(const QByteArray& dek, QByteArray& blob_out) {
+ QByteArray entropy(kAppSalt);
+ DATA_BLOB in{static_cast<DWORD>(dek.size()), reinterpret_cast<BYTE*>(const_cast<char*>(dek.constData()))};
+ DATA_BLOB ent{static_cast<DWORD>(entropy.size()), reinterpret_cast<BYTE*>(const_cast<char*>(entropy.constData()))};
+ DATA_BLOB out{};
+ if (!CryptProtectData(&in, L"Fincept Terminal credential key", &ent, nullptr, nullptr, CRYPTPROTECT_UI_FORBIDDEN,
+ &out)) {
+ LOG_WARN(TAG, QString("CryptProtectData failed (err %1)").arg(GetLastError()));
+ return false;
+ }
+ blob_out = QByteArray(reinterpret_cast<const char*>(out.pbData), static_cast<int>(out.cbData));
+ LocalFree(out.pbData);
+ return true;
+}
+
+bool dpapi_unwrap(const QByteArray& blob, QByteArray& dek_out) {
+ QByteArray entropy(kAppSalt);
+ DATA_BLOB in{static_cast<DWORD>(blob.size()), reinterpret_cast<BYTE*>(const_cast<char*>(blob.constData()))};
+ DATA_BLOB ent{static_cast<DWORD>(entropy.size()), reinterpret_cast<BYTE*>(const_cast<char*>(entropy.constData()))};
+ DATA_BLOB out{};
+ if (!CryptUnprotectData(&in, nullptr, &ent, nullptr, nullptr, CRYPTPROTECT_UI_FORBIDDEN, &out)) {
+ LOG_WARN(TAG, QString("CryptUnprotectData failed (err %1)").arg(GetLastError()));
+ return false;
+ }
+ dek_out = QByteArray(reinterpret_cast<const char*>(out.pbData), static_cast<int>(out.cbData));
+ SecureZeroMemory(out.pbData, out.cbData);
+ LocalFree(out.pbData);
+ return true;
+}
+#endif
+
+// PBKDF2 KEK over the machine seed.
+QByteArray pbkdf2_kek(const QByteArray& salt) {
+ const QByteArray seed = machine_seed();
+ QByteArray kek(kKeyLen, '\0');
+ if (1 != PKCS5_PBKDF2_HMAC(seed.constData(), seed.size(), reinterpret_cast<const unsigned char*>(salt.constData()),
+ salt.size(), kPbkdf2Iterations, EVP_sha256(), kKeyLen,
+ reinterpret_cast<unsigned char*>(kek.data()))) {
+ LOG_ERROR(TAG, "PBKDF2 derivation failed");
+ return {};
+ }
+ return kek;
+}
+
+struct WrappedRow {
+ QString key;
+ QByteArray ciphertext;
+ QByteArray iv;
+ QByteArray tag;
+};
+
+// Placeholders for schemes that carry their own integrity (DPAPI) and so have
+// no separate iv/tag. The columns are declared NOT NULL and a *default
+// constructed* QByteArray binds as SQL NULL — which fails the insert and
+// silently demotes us to the weaker wrapping scheme. Always bind real bytes.
+QByteArray unused_iv() {
+ return QByteArray(kIvLen, '\0');
+}
+QByteArray unused_tag() {
+ return QByteArray(kTagLen, '\0');
+}
+
+// PBKDF2 scheme: ciphertext = salt(16) || wrapped_dek, iv = GCM nonce, tag = GCM tag.
+bool pbkdf2_wrap(const QByteArray& dek, WrappedRow& out) {
+ const QByteArray salt = random_bytes(kSaltLen);
+ const QByteArray iv = random_bytes(kIvLen);
+ if (salt.isEmpty() || iv.isEmpty())
+ return false;
+ const QByteArray kek = pbkdf2_kek(salt);
+ if (kek.size() != kKeyLen)
+ return false;
+
+ QByteArray tag;
+ const QByteArray wrapped = aes_gcm_encrypt(kek, iv, dek, tag);
+ if (tag.size() != kTagLen)
+ return false;
+
+ out.key = QString::fromLatin1(kDekPbkdf2);
+ out.ciphertext = salt + wrapped;
+ out.iv = iv;
+ out.tag = tag;
+ return true;
+}
+
+bool pbkdf2_unwrap(const WrappedRow& row, QByteArray& dek_out) {
+ if (row.ciphertext.size() <= kSaltLen)
+ return false;
+ const QByteArray salt = row.ciphertext.left(kSaltLen);
+ const QByteArray wrapped = row.ciphertext.mid(kSaltLen);
+ const QByteArray kek = pbkdf2_kek(salt);
+ if (kek.size() != kKeyLen)
+ return false;
+
+ bool ok = false;
+ dek_out = aes_gcm_decrypt(kek, row.iv, wrapped, row.tag, ok);
+ return ok && dek_out.size() == kKeyLen;
+}
+
+// ── DEK load / create / migrate ─────────────────────────────────────────────
+
+bool read_wrapped_row(QSqlDatabase conn, const char* key, WrappedRow& out) {
+ QSqlQuery q(conn);
+ q.prepare("SELECT ciphertext, iv, tag FROM secure_credentials WHERE key = ?");
+ q.addBindValue(QString::fromLatin1(key));
+ if (!q.exec() || !q.next())
+ return false;
+ out.key = QString::fromLatin1(key);
+ out.ciphertext = q.value(0).toByteArray();
+ out.iv = q.value(1).toByteArray();
+ out.tag = q.value(2).toByteArray();
+ return true;
+}
+
+bool write_wrapped_row(QSqlDatabase conn, const WrappedRow& row) {
+ QSqlQuery q(conn);
+ q.prepare(R"sql(
+ INSERT INTO secure_credentials (key, ciphertext, iv, tag, updated_at)
+ VALUES (?, ?, ?, ?, datetime('now'))
+ ON CONFLICT(key) DO UPDATE SET
+ ciphertext = excluded.ciphertext,
+ iv = excluded.iv,
+ tag = excluded.tag,
+ updated_at = excluded.updated_at
+ )sql");
+ q.addBindValue(row.key);
+ q.addBindValue(row.ciphertext);
+ q.addBindValue(row.iv);
+ q.addBindValue(row.tag);
+ if (!q.exec()) {
+ LOG_ERROR(TAG, QString("Failed to persist wrapped DEK: %1").arg(q.lastError().text()));
+ return false;
+ }
+ return true;
+}
+
+bool drop_row(QSqlDatabase conn, const char* key) {
+ QSqlQuery q(conn);
+ q.prepare("DELETE FROM secure_credentials WHERE key = ?");
+ q.addBindValue(QString::fromLatin1(key));
+ return q.exec();
+}
+
+#ifdef Q_OS_WIN
+// Re-wrap an existing DEK under DPAPI and retire the PBKDF2 copy. This is the
+// payoff of wrapping a DEK rather than deriving the row key directly: upgrading
+// the protection scheme rewrites 32 bytes and leaves every credential row
+// untouched. Best-effort — on failure the PBKDF2 row stays authoritative and we
+// retry next launch. Order matters: write the new row *before* dropping the old
+// one, so an interrupt can never leave the DEK unrecoverable.
+void upgrade_wrapping_to_dpapi(QSqlDatabase conn, const QByteArray& dek) {
+ QByteArray blob;
+ if (!dpapi_wrap(dek, blob))
+ return;
+ if (!write_wrapped_row(conn, {QString::fromLatin1(kDekDpapi), blob, unused_iv(), unused_tag()}))
+ return;
+ if (!drop_row(conn, kDekPbkdf2)) {
+ LOG_WARN(TAG, "Wrote the DPAPI-wrapped key but could not drop the PBKDF2 row");
+ return;
+ }
+ LOG_INFO(TAG, "Upgraded credential key wrapping from PBKDF2 to DPAPI");
+}
+#endif
+
+// Re-encrypt every credential row from `from_key` to `to_key`. Rows that fail
+// to decrypt are left untouched — they were already unreadable (profile copied
+// from another machine), and destroying them would lose nothing but would make
+// the failure harder to diagnose.
+bool reencrypt_rows(QSqlDatabase conn, const QByteArray& from_key, const QByteArray& to_key, int& migrated_out) {
+ QVector<WrappedRow> rows;
+ {
+ QSqlQuery sel(conn);
+ if (!sel.exec("SELECT key, ciphertext, iv, tag FROM secure_credentials")) {
+ LOG_ERROR(TAG, QString("Migration select failed: %1").arg(sel.lastError().text()));
+ return false;
+ }
+ while (sel.next()) {
+ const QString k = sel.value(0).toString();
+ if (is_reserved_key(k))
+ continue;
+ rows.push_back({k, sel.value(1).toByteArray(), sel.value(2).toByteArray(), sel.value(3).toByteArray()});
+ }
+ }
+
+ migrated_out = 0;
+ for (const WrappedRow& r : rows) {
+ bool ok = false;
+ const QByteArray plaintext = aes_gcm_decrypt(from_key, r.iv, r.ciphertext, r.tag, ok);
+ if (!ok)
+ continue;
+
+ const QByteArray iv = random_bytes(kIvLen);
+ if (iv.isEmpty())
+ return false;
+ QByteArray tag;
+ const QByteArray ct = aes_gcm_encrypt(to_key, iv, plaintext, tag);
+ if (tag.size() != kTagLen)
+ return false;
+
+ QSqlQuery up(conn);
+ up.prepare("UPDATE secure_credentials SET ciphertext = ?, iv = ?, tag = ? WHERE key = ?");
+ up.addBindValue(ct);
+ up.addBindValue(iv);
+ up.addBindValue(tag);
+ up.addBindValue(r.key);
+ if (!up.exec()) {
+ LOG_ERROR(TAG, QString("Migration update failed for %1: %2").arg(r.key, up.lastError().text()));
+ return false;
+ }
+ ++migrated_out;
+ }
+ return true;
+}
+
+// Load the DEK, creating (and migrating to) one on first run. Returns an empty
+// QByteArray if the store is unusable; callers must treat that as an error.
+QByteArray load_or_create_dek() {
+ auto& db = Database::instance();
+ QSqlDatabase conn = db.connection();
+
+ // 1. Try the platform-preferred wrapped DEK.
+#ifdef Q_OS_WIN
+ {
+ WrappedRow row;
+ if (read_wrapped_row(conn, kDekDpapi, row)) {
+ QByteArray dek;
+ if (dpapi_unwrap(row.ciphertext, dek) && dek.size() == kKeyLen) {
+ // A PBKDF2 row alongside the DPAPI one is a second, weaker copy
+ // of the same key — retire it.
+ (void)drop_row(conn, kDekPbkdf2);
+ return dek;
+ }
+ LOG_ERROR(TAG, "Stored DEK could not be unwrapped by DPAPI — stored credentials are "
+ "unreadable on this account and must be re-entered");
+ }
+ }
+#endif
+ {
+ WrappedRow row;
+ if (read_wrapped_row(conn, kDekPbkdf2, row)) {
+ QByteArray dek;
+ if (pbkdf2_unwrap(row, dek)) {
+#ifdef Q_OS_WIN
+ upgrade_wrapping_to_dpapi(conn, dek);
+#endif
+ return dek;
+ }
+ LOG_ERROR(TAG, "Stored DEK failed PBKDF2 unwrap — stored credentials are unreadable "
+ "on this machine and must be re-entered");
+ }
+ }
+
+ // 2. No usable DEK — create one and migrate any legacy rows under it.
+ const QByteArray dek = random_bytes(kKeyLen);
+ if (dek.isEmpty())
+ return {};
+
+ if (db.begin_transaction().is_err()) {
+ LOG_ERROR(TAG, "Could not open a transaction for DEK creation");
+ return {};
+ }
+
+ int migrated = 0;
+ bool ok = reencrypt_rows(conn, legacy_key(), dek, migrated);
+ if (ok) {
+ bool wrote = false;
+#ifdef Q_OS_WIN
+ QByteArray blob;
+ if (dpapi_wrap(dek, blob))
+ wrote = write_wrapped_row(conn, {QString::fromLatin1(kDekDpapi), blob, unused_iv(), unused_tag()});
+ if (!wrote)
+ LOG_WARN(TAG, "DPAPI wrap unavailable — falling back to PBKDF2-wrapped DEK");
+#endif
+ if (!wrote) {
+ WrappedRow row;
+ wrote = pbkdf2_wrap(dek, row) && write_wrapped_row(conn, row);
+ }
+ ok = wrote;
+ }
+
+ if (!ok) {
+ (void)db.rollback();
+ LOG_ERROR(TAG, "DEK creation failed — credential store left unchanged");
+ return {};
+ }
+ if (db.commit().is_err()) {
+ (void)db.rollback();
+ LOG_ERROR(TAG, "DEK creation could not be committed");
+ return {};
+ }
+
+ LOG_INFO(TAG, QString("Initialised wrapped credential key (%1 legacy row(s) re-encrypted)").arg(migrated));
+ return dek;
+}
+
+// Derive once and cache. Called under QMutex so the first caller wins;
+// subsequent calls return the cached buffer without touching the DB.
+const QByteArray& data_key() {
+ static QMutex m;
+ static QByteArray cached;
+ static bool attempted = false;
+ QMutexLocker lock(&m);
+ if (!cached.isEmpty() || attempted)
+ return cached;
+ attempted = true;
+ cached = load_or_create_dek();
+ return cached;
+}
+
} // anonymous namespace
SecureStorage& SecureStorage::instance() {
@@ -185,11 +539,19 @@ Result<void> SecureStorage::store(const QString& key, const QString& value) {
LOG_ERROR(TAG, "SecureStorage::store called before Database::open()");
return Result<void>::err("Database not open");
}
+ if (is_reserved_key(key))
+ return Result<void>::err("Reserved key");
+
+ const QByteArray key_material = data_key();
+ if (key_material.size() != kKeyLen)
+ return Result<void>::err("Credential key unavailable");
const QByteArray plaintext = value.toUtf8();
- const QByteArray iv = random_iv();
+ const QByteArray iv = random_bytes(kIvLen);
+ if (iv.isEmpty())
+ return Result<void>::err("Encryption failed");
QByteArray tag;
- const QByteArray ciphertext = aes_gcm_encrypt(master_key(), iv, plaintext, tag);
+ const QByteArray ciphertext = aes_gcm_encrypt(key_material, iv, plaintext, tag);
if (tag.size() != kTagLen) {
// aes_gcm_encrypt already logged the OpenSSL error.
return Result<void>::err("Encryption failed");
@@ -220,6 +582,12 @@ Result<QString> SecureStorage::retrieve(const QString& key) {
auto& db = Database::instance();
if (!db.is_open())
return Result<QString>::err("Database not open");
+ if (is_reserved_key(key))
+ return Result<QString>::err("Not found");
+
+ const QByteArray key_material = data_key();
+ if (key_material.size() != kKeyLen)
+ return Result<QString>::err("Credential key unavailable");
// Use the per-thread connection, NOT the shared raw_db(): credential reads run
// on worker threads (algo quote polling, candle warm-up, order placement), and
@@ -239,7 +607,7 @@ Result<QString> SecureStorage::retrieve(const QString& key) {
const QByteArray tag = q.value(2).toByteArray();
bool ok = false;
- const QByteArray plaintext = aes_gcm_decrypt(master_key(), iv, ciphertext, tag, ok);
+ const QByteArray plaintext = aes_gcm_decrypt(key_material, iv, ciphertext, tag, ok);
if (!ok) {
// Tag mismatch — either the row is corrupted, the ciphertext was
// tampered with, or the profile was copied from another machine.
@@ -256,6 +624,8 @@ Result<void> SecureStorage::remove(const QString& key) {
auto& db = Database::instance();
if (!db.is_open())
return Result<void>::err("Database not open");
+ if (is_reserved_key(key))
+ return Result<void>::err("Reserved key");
QSqlQuery q(db.connection()); // per-thread connection (see retrieve) — thread-safe
q.prepare("DELETE FROM secure_credentials WHERE key = ?");
diff --git a/fincept-qt/src/trading/ActionCenter.cpp b/fincept-qt/src/trading/ActionCenter.cpp
index b062f07be..58b707b51 100644
--- a/fincept-qt/src/trading/ActionCenter.cpp
+++ b/fincept-qt/src/trading/ActionCenter.cpp
@@ -430,6 +430,22 @@ QString ActionCenter::execute_pending(const PendingOrder& po, bool& ok, QString&
return {};
}
+qint64 ActionCenter::age_secs(const PendingOrder& po) {
+ if (!po.created_at.isValid())
+ return -1;
+ return po.created_at.secsTo(QDateTime::currentDateTime());
+}
+
+bool ActionCenter::is_expired(const PendingOrder& po) {
+ // Only a still-pending order can expire; approved/rejected rows are history.
+ if (po.status != QLatin1String("pending"))
+ return false;
+ const qint64 age = age_secs(po);
+ if (age < 0)
+ return false; // unparseable timestamp — don't block on a data defect
+ return age > static_cast<qint64>(kPendingOrderTtlMinutes) * 60;
+}
+
void ActionCenter::approve_order(const QString& pending_id) {
auto po_opt = get_order(pending_id);
if (!po_opt) {
@@ -442,6 +458,28 @@ void ActionCenter::approve_order(const QString& pending_id) {
return;
}
+ // Refuse a stale order outright. The UI flags these, but enforcing it here
+ // means no caller — the approval panel, a bulk approve, or a future
+ // automation path — can execute one by taking a different route.
+ if (is_expired(po)) {
+ const qint64 mins = age_secs(po) / 60;
+ const QString reason =
+ QString("Expired: queued %1 minutes ago (limit %2). The market has moved since this order was "
+ "created — re-place it if you still want the trade.")
+ .arg(mins)
+ .arg(kPendingOrderTtlMinutes);
+ LOG_WARN(kLog, QString("approve_order: refusing expired order %1 (age %2m)").arg(pending_id).arg(mins));
+
+ auto r = Database::instance().execute(
+ "UPDATE pending_orders SET status = ?, rejected_at = ?, rejection_reason = ? WHERE id = ?",
+ {"rejected", iso(QDateTime::currentDateTime()), reason, pending_id});
+ if (r.is_err())
+ LOG_ERROR(kLog, QString("approve_order expiry update failed: %1").arg(QString::fromStdString(r.error())));
+
+ emit order_rejected(pending_id, reason);
+ return;
+ }
+
bool ok = false;
QString err;
const QString broker_order_id = execute_pending(po, ok, err);
diff --git a/fincept-qt/src/trading/ActionCenter.h b/fincept-qt/src/trading/ActionCenter.h
index 103619979..2905cb1bf 100644
--- a/fincept-qt/src/trading/ActionCenter.h
+++ b/fincept-qt/src/trading/ActionCenter.h
@@ -81,7 +81,31 @@ class ActionCenter : public QObject {
// `order_data` should NOT contain credentials. Emits pending_order_created.
QString queue_order(const QString& account_id, const QString& order_type, const QJsonObject& order_data);
+ // ── Expiry ──────────────────────────────────────────────────────────────
+ // A queued order carries a price and a market view that both decay. An
+ // order queued before lunch and approved after the close would execute at
+ // a market the user never saw and never intended to trade — the approval
+ // dialog would show the original details while the fill happens at the
+ // current price.
+ //
+ // Expiry is DERIVED from created_at rather than stored as a column. That is
+ // deliberate: a migration adding `expires_at` would default existing rows
+ // to NULL, so every order already sitting in the queue — precisely the
+ // stale ones this protects against — would never expire. Deriving applies
+ // the policy retroactively and cannot be set wrong by a caller.
+ static constexpr int kPendingOrderTtlMinutes = 15;
+
+ /// True when this order is too old to be safely executed. Callers should
+ /// use this to grey out or annotate the row; approve_order() enforces it
+ /// regardless, so the UI cannot be the only line of defence.
+ static bool is_expired(const PendingOrder& po);
+
+ /// Seconds since the order was queued (-1 if created_at is invalid).
+ static qint64 age_secs(const PendingOrder& po);
+
// User actions.
+ // approve_order refuses an expired order and emits order_rejected with an
+ // explanatory reason rather than silently executing it.
void approve_order(const QString& pending_id);
void reject_order(const QString& pending_id, const QString& reason);
void approve_all_pending(const QString& account_id = {});
diff --git a/fincept-qt/src/trading/brokers/BrokerLogRedact.h b/fincept-qt/src/trading/brokers/BrokerLogRedact.h
new file mode 100644
index 000000000..c4ffbc5b7
--- /dev/null
+++ b/fincept-qt/src/trading/brokers/BrokerLogRedact.h
@@ -0,0 +1,112 @@
+#pragma once
+// BrokerLogRedact — strip credentials out of broker HTTP bodies before logging.
+//
+// Several broker auth/profile endpoints answer with the very secret we just
+// asked for: Kite's /session/token returns access_token + public_token, ICICI
+// Breeze's /customerdetails returns session_token, and most of them also carry
+// the account holder's email. Logging those bodies verbatim writes a live
+// trading credential into fincept.log in plaintext — a file users routinely
+// attach to bug reports and support tickets.
+//
+// Dropping the log line instead would cost real diagnostic value: response
+// shape and status are how a broken session actually gets debugged. So redact
+// by key rather than by line — secret-named fields become "<redacted:N>"
+// (N = original length, enough to distinguish "broker returned an empty token"
+// from "token present but rejected"), and everything else survives intact.
+
+#include <QJsonArray>
+#include <QJsonDocument>
+#include <QJsonObject>
+#include <QLatin1String>
+#include <QSet>
+#include <QString>
+
+namespace fincept::trading {
+
+namespace redact_detail {
+
+// True when a JSON key names something that must never reach the log file.
+inline bool is_secret_key(const QString& key) {
+ const QString k = key.toLower();
+
+ // Non-secret metadata that merely mentions a credential. These are the
+ // fields you need when debugging an expiry bug, so keep them readable.
+ static const QSet<QString> kKeep = {
+ QStringLiteral("tokenvalidity"),
+ QStringLiteral("token_expires_at"),
+ QStringLiteral("token_type"),
+ QStringLiteral("expires_in"),
+ };
+ if (kKeep.contains(k))
+ return false;
+
+ // Direct PII — not a credential, but still not log material.
+ static const QSet<QString> kExact = {
+ QStringLiteral("email"), QStringLiteral("emailid"), QStringLiteral("email_id"), QStringLiteral("phone"),
+ QStringLiteral("mobile"), QStringLiteral("mobileno"), QStringLiteral("mobile_no"), QStringLiteral("pan"),
+ QStringLiteral("otp"), QStringLiteral("sid"),
+ };
+ if (kExact.contains(k))
+ return true;
+
+ for (const char* frag : {"token", "secret", "password", "passwd", "apikey", "api_key", "appkey", "app_key",
+ "private", "session", "auth", "signature", "checksum"}) {
+ if (k.contains(QLatin1String(frag)))
+ return true;
+ }
+ return false;
+}
+
+inline QJsonValue redact_value(const QJsonValue& v);
+
+inline QJsonObject redact_object(const QJsonObject& in) {
+ QJsonObject out;
+ for (auto it = in.constBegin(); it != in.constEnd(); ++it) {
+ if (is_secret_key(it.key())) {
+ if (it.value().isString())
+ out.insert(it.key(), QStringLiteral("<redacted:%1>").arg(it.value().toString().size()));
+ else
+ out.insert(it.key(), QStringLiteral("<redacted>"));
+ } else {
+ out.insert(it.key(), redact_value(it.value()));
+ }
+ }
+ return out;
+}
+
+inline QJsonValue redact_value(const QJsonValue& v) {
+ if (v.isObject())
+ return redact_object(v.toObject());
+ if (v.isArray()) {
+ QJsonArray out;
+ for (const QJsonValue& e : v.toArray())
+ out.append(redact_value(e));
+ return out;
+ }
+ return v;
+}
+
+} // namespace redact_detail
+
+// Redact a broker response body for logging. JSON bodies keep their structure
+// with secret-named fields masked; non-JSON bodies are reported by length only,
+// because without a parse we cannot tell which bytes are sensitive.
+inline QString redact_body(const QString& raw_body, int max_chars = 500) {
+ if (raw_body.isEmpty())
+ return QStringLiteral("<empty>");
+
+ const QJsonDocument doc = QJsonDocument::fromJson(raw_body.toUtf8());
+ if (doc.isObject()) {
+ return QString::fromUtf8(
+ QJsonDocument(redact_detail::redact_object(doc.object())).toJson(QJsonDocument::Compact))
+ .left(max_chars);
+ }
+ if (doc.isArray()) {
+ return QString::fromUtf8(
+ QJsonDocument(redact_detail::redact_value(doc.array()).toArray()).toJson(QJsonDocument::Compact))
+ .left(max_chars);
+ }
+ return QStringLiteral("<non-JSON body, %1 bytes>").arg(raw_body.size());
+}
+
+} // namespace fincept::trading
diff --git a/fincept-qt/src/trading/brokers/dhan/DhanBroker.cpp b/fincept-qt/src/trading/brokers/dhan/DhanBroker.cpp
index 86f1e7262..8024c11a1 100644
--- a/fincept-qt/src/trading/brokers/dhan/DhanBroker.cpp
+++ b/fincept-qt/src/trading/brokers/dhan/DhanBroker.cpp
@@ -16,6 +16,7 @@
#include "core/logging/Logger.h"
#include "trading/adapter/BrokerEnumMap.h"
#include "trading/brokers/BrokerHttp.h"
+#include "trading/brokers/BrokerLogRedact.h"
#include "trading/brokers/BrokerTokenUtil.h"
#include "trading/instruments/InstrumentService.h"
@@ -143,10 +144,12 @@ QString DhanBroker::checked_error(const BrokerHttpResponse& resp, const QString&
// and it logs the raw response so any disconnect is fully diagnosable.
SessionCheck DhanBroker::validate_session(const BrokerCredentials& creds) {
auto resp = BrokerHttp::instance().get(BASE + "/v2/profile", auth_headers(creds));
+ // Redacted: /v2/profile carries the client id/name and account PII.
+ // tokenValidity survives redaction — it is the field expiry bugs need.
LOG_INFO(TAG, QString("validate_session GET /v2/profile → status=%1 success=%2 body=%3")
.arg(resp.status_code)
.arg(resp.success)
- .arg(resp.raw_body.left(300)));
+ .arg(redact_body(resp.raw_body, 300)));
// A 200 carrying the client id means the token is live. Parse the real
// tokenValidity ("DD/MM/YYYY HH:mm", IST) so the persisted expiry hint is
diff --git a/fincept-qt/src/trading/brokers/icicidirect/IciciDirectBroker.cpp b/fincept-qt/src/trading/brokers/icicidirect/IciciDirectBroker.cpp
index 612dac4fe..6be407c73 100644
--- a/fincept-qt/src/trading/brokers/icicidirect/IciciDirectBroker.cpp
+++ b/fincept-qt/src/trading/brokers/icicidirect/IciciDirectBroker.cpp
@@ -2,6 +2,7 @@
#include "core/logging/Logger.h"
#include "trading/brokers/BrokerHttp.h"
+#include "trading/brokers/BrokerLogRedact.h"
#include "trading/brokers/BrokerTokenUtil.h"
#include "trading/instruments/InstrumentService.h"
@@ -184,10 +185,12 @@ TokenExchangeResponse IciciDirectBroker::exchange_token(const QString& api_key,
auto resp = BrokerHttp::instance().send("GET", QString(base_url()) + "/customerdetails", body_bytes,
"application/json", headers);
+ // Redacted: the Success block of this response *is* the session_token
+ // (read below at `session_token`), alongside customer PII.
LOG_INFO("IciciDirect", QString("customerdetails HTTP %1 success=%2 body=%3")
.arg(resp.status_code)
.arg(resp.success)
- .arg(resp.raw_body.left(300)));
+ .arg(redact_body(resp.raw_body, 300)));
if (!resp.success) {
result.error = resp.json.value("Error").toString(resp.error.isEmpty() ? QString("HTTP %1").arg(resp.status_code)
diff --git a/fincept-qt/src/trading/brokers/motilal/MotilalBroker.cpp b/fincept-qt/src/trading/brokers/motilal/MotilalBroker.cpp
index 01bfbd2b5..edc36c1de 100644
--- a/fincept-qt/src/trading/brokers/motilal/MotilalBroker.cpp
+++ b/fincept-qt/src/trading/brokers/motilal/MotilalBroker.cpp
@@ -15,6 +15,14 @@ namespace fincept::trading {
static constexpr const char* BASE = "https://openapi.motilaloswal.com";
+// Motilal's client-info block reports the *host application's* version
+// (alongside productname "FinceptTerminal") — it is not a Motilal API version.
+// Injected by CMake from CMAKE_PROJECT_VERSION so it can't drift from the
+// project version the way the previously hardcoded literal did.
+#ifndef FINCEPT_VERSION_STRING
+# define FINCEPT_VERSION_STRING "0.0.0-dev"
+#endif
+
static int64_t now_ts() {
return QDateTime::currentSecsSinceEpoch();
}
@@ -120,7 +128,7 @@ QMap<QString, QString> MotilalBroker::auth_headers(const BrokerCredentials& cred
{"devicemodel", "PC"},
{"manufacturer", "Generic"},
{"productname", "FinceptTerminal"},
- {"productversion", "4.2.0"},
+ {"productversion", FINCEPT_VERSION_STRING},
{"browsername", "Chrome"},
{"browserversion", "120.0"},
};
@@ -163,7 +171,7 @@ TokenExchangeResponse MotilalBroker::exchange_token(const QString& api_key, cons
{"devicemodel", "PC"},
{"manufacturer", "Generic"},
{"productname", "FinceptTerminal"},
- {"productversion", "4.2.0"},
+ {"productversion", FINCEPT_VERSION_STRING},
{"browsername", "Chrome"},
{"browserversion", "120.0"},
};
diff --git a/fincept-qt/src/trading/brokers/zerodha/ZerodhaBroker.cpp b/fincept-qt/src/trading/brokers/zerodha/ZerodhaBroker.cpp
index 305096cdd..dbbed175e 100644
--- a/fincept-qt/src/trading/brokers/zerodha/ZerodhaBroker.cpp
+++ b/fincept-qt/src/trading/brokers/zerodha/ZerodhaBroker.cpp
@@ -3,6 +3,7 @@
#include "core/logging/Logger.h"
#include "trading/adapter/BrokerEnumMap.h"
#include "trading/brokers/BrokerHttp.h"
+#include "trading/brokers/BrokerLogRedact.h"
#include "trading/brokers/BrokerTokenUtil.h"
#include "trading/brokers/zerodha/ZerodhaAutoLogin.h"
#include "trading/instruments/InstrumentService.h"
@@ -160,10 +161,12 @@ TokenExchangeResponse ZerodhaBroker::exchange_token(const QString& api_key, cons
QMap<QString, QString> headers = {{"X-Kite-Version", kite_api_version}};
auto resp = BrokerHttp::instance().post_form(QString(base_url()) + "/session/token", params, headers);
+ // Redacted: a successful /session/token body carries access_token,
+ // public_token and the account email — never log it verbatim.
LOG_INFO("Zerodha", QString("exchange_token HTTP %1 success=%2 body=%3")
.arg(resp.status_code)
.arg(resp.success)
- .arg(resp.raw_body.left(500)));
+ .arg(redact_body(resp.raw_body)));
TokenExchangeResponse result;
if (!resp.success) {
diff --git a/fincept-qt/src/ui/charts/KLineChartWidget.cpp b/fincept-qt/src/ui/charts/KLineChartWidget.cpp
index 5b497af08..efc9824e6 100644
--- a/fincept-qt/src/ui/charts/KLineChartWidget.cpp
+++ b/fincept-qt/src/ui/charts/KLineChartWidget.cpp
@@ -13,6 +13,7 @@
#include <QCoreApplication>
#include <QDateTime>
#include <QFileInfo>
+#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QLabel>
@@ -223,22 +224,37 @@ void KLineChartWidget::update_candle(const QJsonObject& candle) {
run_js(QStringLiteral("window.updateCandle(%1)").arg(json));
}
+namespace {
+// Build `fn.apply(null,[...])` with every argument JSON-encoded. Interpolating
+// values straight into '%1' quotes lets any value containing a quote terminate
+// the literal and append arbitrary script — and this page runs with
+// JavascriptEnabled + LocalContentCanAccessFileUrls, so injected script reads
+// local files. Callers currently pass trusted values (theme colours, formatted
+// numbers, fixed indicator names), but the chart takes indicator/pane names
+// from callers that may one day be symbol- or config-derived; encoding here
+// makes that safe by construction rather than by convention.
+QString js_call(const QString& fn, const QJsonArray& args) {
+ const QString json = QString::fromUtf8(QJsonDocument(args).toJson(QJsonDocument::Compact));
+ return QStringLiteral("%1.apply(null,%2)").arg(fn, json);
+}
+} // namespace
+
void KLineChartWidget::add_indicator(const QString& name, const QString& pane_id) {
if (pane_id.isEmpty())
- run_js(QStringLiteral("window.addIndicator('%1')").arg(name));
+ run_js(js_call(QStringLiteral("window.addIndicator"), {name}));
else
- run_js(QStringLiteral("window.addIndicator('%1','%2')").arg(name, pane_id));
+ run_js(js_call(QStringLiteral("window.addIndicator"), {name, pane_id}));
}
void KLineChartWidget::remove_indicator(const QString& name, const QString& pane_id) {
if (pane_id.isEmpty())
- run_js(QStringLiteral("window.removeIndicator('%1')").arg(name));
+ run_js(js_call(QStringLiteral("window.removeIndicator"), {name}));
else
- run_js(QStringLiteral("window.removeIndicator('%1','%2')").arg(name, pane_id));
+ run_js(js_call(QStringLiteral("window.removeIndicator"), {name, pane_id}));
}
void KLineChartWidget::set_position_line(double price, const QString& label, const QString& color_hex) {
- run_js(QStringLiteral("window.setPositionLine(%1,'%2','%3')").arg(price, 0, 'f', 6).arg(label, color_hex));
+ run_js(js_call(QStringLiteral("window.setPositionLine"), {price, label, color_hex}));
}
void KLineChartWidget::clear_position_line() {
diff --git a/fincept-qt/src/ui/tables/LiveTableDelegate.h b/fincept-qt/src/ui/tables/LiveTableDelegate.h
new file mode 100644
index 000000000..b81604769
--- /dev/null
+++ b/fincept-qt/src/ui/tables/LiveTableDelegate.h
@@ -0,0 +1,175 @@
+#pragma once
+// LiveTableDelegate — paints P&L colouring, side badges and a per-row action
+// button WITHOUT allocating a widget or reparsing CSS per row.
+//
+// WHY THIS EXISTS
+// ---------------
+// The dominant per-tick cost in this codebase's blotters is not the data — it
+// is the row chrome. The idiom being replaced is:
+//
+// auto* exit_btn = new QPushButton(tr("Exit")); // heap alloc/row
+// exit_btn->setStyleSheet("QPushButton { background:...; border:1px ... }");
+// table->setCellWidget(r, 9, exit_btn); // + layout churn
+//
+// Every setStyleSheet() is a full CSS parse. At 200 rows that is 200 parses and
+// 200 widget allocations on every refresh, and the buttons are destroyed and
+// rebuilt seconds later. Painting the button instead costs one drawRect plus one
+// drawText per visible row — and only visible rows are ever painted, so a
+// 5,000-row blotter costs the same as a 30-row one.
+//
+// Deliberately NOT a QObject: click notification goes through a std::function
+// rather than a signal, so this stays header-only with no moc participation and
+// no CMakeLists entry.
+//
+// USAGE
+// auto* d = new ui::LiveTableDelegate(view);
+// d->set_action_column(9, tr("EXIT"), ui::LiveTableDelegate::Danger);
+// d->set_on_action([this](const QModelIndex& i) { square_off(i); });
+// view->setItemDelegate(d);
+//
+// The model supplies colour through Qt::ForegroundRole as usual; this delegate
+// only adds the action button and the badge treatment.
+
+#include "ui/theme/Theme.h"
+
+#include <QAbstractItemView>
+#include <QApplication>
+#include <QColor>
+#include <QEvent>
+#include <QModelIndex>
+#include <QMouseEvent>
+#include <QPainter>
+#include <QRect>
+#include <QStyledItemDelegate>
+#include <QToolTip>
+
+#include <functional>
+
+namespace fincept::ui {
+
+class LiveTableDelegate : public QStyledItemDelegate {
+ public:
+ enum ActionStyle { Neutral, Danger, Positive };
+
+ explicit LiveTableDelegate(QObject* parent = nullptr) : QStyledItemDelegate(parent) {}
+
+ /// Turn one column into a painted action button.
+ void set_action_column(int column, const QString& label, ActionStyle style = Neutral) {
+ action_col_ = column;
+ action_label_ = label;
+ action_style_ = style;
+ }
+
+ /// Called with the row's index when the painted button is clicked.
+ void set_on_action(std::function<void(const QModelIndex&)> fn) { on_action_ = std::move(fn); }
+
+ /// Rows for which this returns false render no button (e.g. an order that is
+ /// already filled cannot be cancelled). Without this, a disabled-looking row
+ /// still accepts the click.
+ void set_action_enabled(std::function<bool(const QModelIndex&)> fn) { action_enabled_ = std::move(fn); }
+
+ void paint(QPainter* p, const QStyleOptionViewItem& opt, const QModelIndex& idx) const override {
+ if (idx.column() != action_col_ || action_col_ < 0) {
+ QStyledItemDelegate::paint(p, opt, idx);
+ return;
+ }
+ if (action_enabled_ && !action_enabled_(idx)) {
+ QStyledItemDelegate::paint(p, opt, idx); // leave the cell blank/plain
+ return;
+ }
+
+ // Background + selection are still the style's job, so a themed row
+ // highlight keeps working under the button.
+ QStyleOptionViewItem o(opt);
+ initStyleOption(&o, idx);
+ o.text.clear();
+ const QWidget* w = o.widget;
+ QStyle* style = w ? w->style() : QApplication::style();
+ style->drawControl(QStyle::CE_ItemViewItem, &o, p, w);
+
+ const QRect r = button_rect(opt.rect);
+ const bool hot = (idx == hover_);
+
+ QColor accent;
+ switch (action_style_) {
+ case Danger:
+ accent = QColor(colors::NEGATIVE());
+ break;
+ case Positive:
+ accent = QColor(colors::POSITIVE());
+ break;
+ default:
+ accent = QColor(colors::TEXT_SECONDARY());
+ break;
+ }
+
+ p->save();
+ // Obsidian: square corners, no gradients (DESIGN_SYSTEM §8/§9).
+ if (hot) {
+ p->fillRect(r, accent);
+ p->setPen(QColor(Qt::white));
+ } else {
+ p->setPen(accent);
+ p->drawRect(r.adjusted(0, 0, -1, -1));
+ }
+ QFont f = opt.font;
+ f.setBold(true);
+ f.setPointSizeF(f.pointSizeF() - 1.0);
+ p->setFont(f);
+ if (!hot)
+ p->setPen(accent);
+ p->drawText(r, Qt::AlignCenter, action_label_);
+ p->restore();
+ }
+
+ QSize sizeHint(const QStyleOptionViewItem& opt, const QModelIndex& idx) const override {
+ QSize s = QStyledItemDelegate::sizeHint(opt, idx);
+ if (idx.column() == action_col_ && action_col_ >= 0)
+ s.setWidth(qMax(s.width(), opt.fontMetrics.horizontalAdvance(action_label_) + 22));
+ return s;
+ }
+
+ bool editorEvent(QEvent* e, QAbstractItemModel*, const QStyleOptionViewItem& opt, const QModelIndex& idx) override {
+ if (action_col_ < 0 || idx.column() != action_col_)
+ return false;
+ if (action_enabled_ && !action_enabled_(idx))
+ return false;
+
+ if (e->type() == QEvent::MouseMove) {
+ // Repaint only the two cells whose hover state actually changed.
+ const QModelIndex prev = hover_;
+ hover_ = button_rect(opt.rect).contains(static_cast<QMouseEvent*>(e)->pos()) ? idx : QModelIndex();
+ if (prev != hover_) {
+ if (auto* v = qobject_cast<QAbstractItemView*>(const_cast<QWidget*>(opt.widget))) {
+ if (prev.isValid())
+ v->update(prev);
+ if (hover_.isValid())
+ v->update(hover_);
+ }
+ }
+ return false; // let the view keep its own hover handling
+ }
+
+ if (e->type() == QEvent::MouseButtonRelease) {
+ auto* me = static_cast<QMouseEvent*>(e);
+ if (me->button() == Qt::LeftButton && button_rect(opt.rect).contains(me->pos())) {
+ if (on_action_)
+ on_action_(idx);
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private:
+ static QRect button_rect(const QRect& cell) { return cell.adjusted(3, 3, -3, -3); }
+
+ int action_col_ = -1;
+ QString action_label_;
+ ActionStyle action_style_ = Neutral;
+ std::function<void(const QModelIndex&)> on_action_;
+ std::function<bool(const QModelIndex&)> action_enabled_;
+ mutable QModelIndex hover_;
+};
+
+} // namespace fincept::ui
diff --git a/fincept-qt/src/ui/tables/LiveTableModel.h b/fincept-qt/src/ui/tables/LiveTableModel.h
new file mode 100644
index 000000000..0d91882fd
--- /dev/null
+++ b/fincept-qt/src/ui/tables/LiveTableModel.h
@@ -0,0 +1,249 @@
+#pragma once
+// LiveTableModel — a reusable QAbstractTableModel for streaming financial rows.
+//
+// WHY THIS EXISTS
+// ---------------
+// The terminal has ~2,000 uses of QTableWidget/QTreeWidget/QListWidget against
+// 16 uses of model/view. The item-widget idiom forces a specific anti-pattern on
+// every live blotter:
+//
+// table->setRowCount(0); // destroy every cell
+// for (const auto& p : positions) { // rebuild all of them
+// table->setItem(r, 0, new QTableWidgetItem(...)); // ~10 heap allocs/row
+// auto* btn = new QPushButton(tr("Exit")); // + a widget
+// btn->setStyleSheet("..."); // + a CSS reparse
+// }
+//
+// A 200-row blotter therefore costs ~2,000 allocations and ~200 full CSS
+// reparses *per tick*, and — because the rows are destroyed — the user's
+// selection, scroll position and sort order are thrown away every refresh. A
+// trader mid-click on a position loses it; a trader scrolled to a strike gets
+// yanked back to the top.
+//
+// This model fixes the structural cause rather than the symptom:
+// • rows are keyed, so an update mutates a row in place instead of recreating it
+// • dataChanged() is emitted ONLY for cells whose value actually changed, so
+// Qt repaints the two cells that ticked rather than the whole viewport
+// • row identity is stable, so selection/scroll/sort survive for free
+// • it composes with QSortFilterProxyModel, so sorting and filtering stop
+// being hand-rolled per screen
+//
+// TEMPLATE + moc
+// --------------
+// moc cannot process a template class carrying Q_OBJECT. This class therefore
+// declares NO new signals or slots — it only overrides QAbstractTableModel's
+// virtuals and reuses its (already moc'd) signals. That is why there is no
+// Q_OBJECT macro here and why user-visible strings must be translated by the
+// owner and passed in, rather than via tr() inside the template.
+//
+// USAGE
+// ui::LiveTableModel<Position> model;
+// model.set_headers({tr("SYMBOL"), tr("QTY"), tr("P&L")});
+// model.set_key([](const Position& p) { return p.account + "|" + p.symbol; });
+// model.set_cell([](const Position& p, int col, int role) -> QVariant {
+// if (role == Qt::DisplayRole) switch (col) { ... }
+// if (role == ui::LiveTableModel<Position>::SortRole) ... // numeric key
+// return {};
+// });
+// view->setModel(&model);
+// model.upsert(rows); // call this on every tick
+
+#include <QAbstractTableModel>
+#include <QHash>
+#include <QModelIndex>
+#include <QString>
+#include <QStringList>
+#include <QVariant>
+#include <QVector>
+
+#include <functional>
+#include <utility>
+
+namespace fincept::ui {
+
+template <typename Row>
+class LiveTableModel : public QAbstractTableModel {
+ public:
+ /// Stable identity for a row. Two rows with the same key are the same row.
+ using KeyFn = std::function<QString(const Row&)>;
+ /// Value for (row, column, role). Return an invalid QVariant for roles you
+ /// do not handle — the model supplies no defaults of its own.
+ using CellFn = std::function<QVariant(const Row&, int column, int role)>;
+
+ /// Role carrying a sortable (usually numeric) key. Point a
+ /// QSortFilterProxyModel at this via setSortRole() so that "1,234.50" sorts
+ /// as a number rather than as text — sorting numeric columns lexically is a
+ /// long-standing defect class in item-widget tables.
+ static constexpr int SortRole = Qt::UserRole + 1;
+ /// Role carrying the row's stable key, for callers that need to map a
+ /// QModelIndex back to a domain object (context menus, per-row actions).
+ static constexpr int KeyRole = Qt::UserRole + 2;
+
+ explicit LiveTableModel(QObject* parent = nullptr) : QAbstractTableModel(parent) {}
+
+ // ── Configuration (call once, before the first upsert) ──────────────────
+
+ void set_headers(const QStringList& headers) {
+ const bool count_changed = headers.size() != headers_.size();
+ if (count_changed)
+ beginResetModel();
+ headers_ = headers;
+ if (count_changed)
+ endResetModel();
+ else if (!headers_.isEmpty())
+ emit headerDataChanged(Qt::Horizontal, 0, headers_.size() - 1);
+ }
+
+ void set_key(KeyFn fn) { key_fn_ = std::move(fn); }
+ void set_cell(CellFn fn) { cell_fn_ = std::move(fn); }
+
+ /// Optional: rows for which this returns false are dropped by upsert().
+ /// Prefer this over filtering at the call site so the model stays the single
+ /// source of truth for what is displayed.
+ void set_filter(std::function<bool(const Row&)> fn) { filter_fn_ = std::move(fn); }
+
+ // ── Streaming update ────────────────────────────────────────────────────
+
+ /// Merge `incoming` into the model.
+ ///
+ /// Rows present in both are updated in place and emit dataChanged only for
+ /// the columns whose displayed value actually changed. Rows only in the
+ /// model are removed; rows only in `incoming` are appended. Order follows
+ /// `incoming`, so a caller that sorts upstream keeps its ordering — but
+ /// prefer a QSortFilterProxyModel and let the user sort.
+ ///
+ /// Safe to call at tick rate: in the steady state (same rows, one price
+ /// moved) this performs zero allocations and emits one dataChanged.
+ void upsert(const QVector<Row>& incoming) {
+ QVector<Row> next;
+ next.reserve(incoming.size());
+ for (const Row& r : incoming) {
+ if (filter_fn_ && !filter_fn_(r))
+ continue;
+ next.push_back(r);
+ }
+
+ // Structural change (rows added/removed/reordered) → one reset. Doing a
+ // reset only when the KEY SEQUENCE changes is the whole point: a pure
+ // value tick, which is the overwhelmingly common case, takes the cheap
+ // path below and leaves selection and scroll untouched.
+ const bool structural = !same_key_sequence(next);
+ if (structural) {
+ beginResetModel();
+ rows_ = std::move(next);
+ rebuild_key_index();
+ endResetModel();
+ return;
+ }
+
+ // Same rows, same order — diff cell by cell and repaint only what moved.
+ const int cols = column_count();
+ for (int r = 0; r < rows_.size(); ++r) {
+ int first_changed = -1;
+ int last_changed = -1;
+ for (int c = 0; c < cols; ++c) {
+ if (cell(rows_[r], c, Qt::DisplayRole) != cell(next[r], c, Qt::DisplayRole)) {
+ if (first_changed < 0)
+ first_changed = c;
+ last_changed = c;
+ }
+ }
+ rows_[r] = next[r]; // adopt the new values regardless
+ if (first_changed >= 0) {
+ emit dataChanged(index(r, first_changed), index(r, last_changed),
+ {Qt::DisplayRole, Qt::ForegroundRole, Qt::ToolTipRole, SortRole});
+ }
+ }
+ }
+
+ /// Drop every row (e.g. on account switch). Prefer upsert({}) when you want
+ /// the empty state to go through the same path as a normal update.
+ void clear() {
+ if (rows_.isEmpty())
+ return;
+ beginResetModel();
+ rows_.clear();
+ key_to_row_.clear();
+ endResetModel();
+ }
+
+ // ── Lookup ──────────────────────────────────────────────────────────────
+
+ const QVector<Row>& rows() const { return rows_; }
+
+ /// Domain object behind an index, or nullptr. Use this in context menus and
+ /// per-row buttons instead of re-parsing the displayed text — recovering a
+ /// quantity by parsing a rounded display string silently loses precision.
+ const Row* row_at(const QModelIndex& idx) const {
+ if (!idx.isValid() || idx.row() < 0 || idx.row() >= rows_.size())
+ return nullptr;
+ return &rows_[idx.row()];
+ }
+
+ const Row* row_for_key(const QString& key) const {
+ const auto it = key_to_row_.constFind(key);
+ return it == key_to_row_.constEnd() ? nullptr : &rows_[it.value()];
+ }
+
+ /// Model row index for a key, or -1. Lets a caller restore a selection by
+ /// identity after a structural change.
+ int index_of_key(const QString& key) const { return key_to_row_.value(key, -1); }
+
+ // ── QAbstractTableModel ─────────────────────────────────────────────────
+
+ int rowCount(const QModelIndex& parent = QModelIndex()) const override {
+ return parent.isValid() ? 0 : static_cast<int>(rows_.size());
+ }
+
+ int columnCount(const QModelIndex& parent = QModelIndex()) const override {
+ return parent.isValid() ? 0 : column_count();
+ }
+
+ QVariant data(const QModelIndex& idx, int role = Qt::DisplayRole) const override {
+ if (!idx.isValid() || idx.row() < 0 || idx.row() >= rows_.size())
+ return {};
+ const Row& r = rows_[idx.row()];
+ if (role == KeyRole)
+ return key_fn_ ? key_fn_(r) : QVariant{};
+ return cell(r, idx.column(), role);
+ }
+
+ QVariant headerData(int section, Qt::Orientation o, int role = Qt::DisplayRole) const override {
+ if (o != Qt::Horizontal || role != Qt::DisplayRole)
+ return {};
+ return (section >= 0 && section < headers_.size()) ? QVariant(headers_.at(section)) : QVariant{};
+ }
+
+ private:
+ int column_count() const { return static_cast<int>(headers_.size()); }
+
+ QVariant cell(const Row& r, int col, int role) const { return cell_fn_ ? cell_fn_(r, col, role) : QVariant{}; }
+
+ bool same_key_sequence(const QVector<Row>& next) const {
+ if (!key_fn_ || next.size() != rows_.size())
+ return false;
+ for (int i = 0; i < next.size(); ++i) {
+ if (key_fn_(next[i]) != key_fn_(rows_[i]))
+ return false;
+ }
+ return true;
+ }
+
+ void rebuild_key_index() {
+ key_to_row_.clear();
+ if (!key_fn_)
+ return;
+ key_to_row_.reserve(rows_.size());
+ for (int i = 0; i < rows_.size(); ++i)
+ key_to_row_.insert(key_fn_(rows_[i]), i);
+ }
+
+ QStringList headers_;
+ QVector<Row> rows_;
+ QHash<QString, int> key_to_row_;
+ KeyFn key_fn_;
+ CellFn cell_fn_;
+ std::function<bool(const Row&)> filter_fn_;
+};
+
+} // namespace fincept::ui
diff --git a/fincept-qt/src/ui/tables/LiveTableSelftest.cpp b/fincept-qt/src/ui/tables/LiveTableSelftest.cpp
new file mode 100644
index 000000000..e6672c3a1
--- /dev/null
+++ b/fincept-qt/src/ui/tables/LiveTableSelftest.cpp
@@ -0,0 +1,204 @@
+// LiveTableSelftest — headless verification of ui::LiveTableModel.
+//
+// Also serves as the compile check for LiveTableModel.h and LiveTableDelegate.h:
+// both are header-only, so without a TU that includes them they would never be
+// compiled and a defect could sit there indefinitely looking finished.
+//
+// Run: FinceptTerminal.exe --selftest-live-table
+
+#include "ui/tables/LiveTableSelftest.h"
+
+#include "ui/tables/LiveTableDelegate.h" // compile-only: proves the delegate builds
+#include "ui/tables/LiveTableModel.h"
+
+// NOTE: deliberately no <QAbstractItemModelTester> and no <QSignalSpy> — both
+// live in Qt6::Test, which the shipping binary does not link (see the
+// find_package COMPONENTS list in CMakeLists.txt). Pulling a Qt module into the
+// whole application for test-only conveniences is the wrong trade, so the model
+// invariants are asserted by hand and signals are counted with plain connects.
+#include <QStringList>
+#include <QTextStream>
+#include <QVector>
+
+namespace fincept::ui {
+namespace {
+
+struct Pos {
+ QString account;
+ QString symbol;
+ double qty = 0;
+ double pnl = 0;
+};
+
+int g_failures = 0;
+
+void check(bool ok, const QString& what) {
+ QTextStream out(stdout);
+ out << (ok ? " PASS " : " FAIL ") << what << "\n";
+ if (!ok)
+ ++g_failures;
+}
+
+using Model = LiveTableModel<Pos>;
+
+void configure(Model& m) {
+ m.set_headers({QStringLiteral("ACCOUNT"), QStringLiteral("SYMBOL"), QStringLiteral("QTY"),
+ QStringLiteral("PNL")});
+ m.set_key([](const Pos& p) { return p.account + QLatin1Char('|') + p.symbol; });
+ m.set_cell([](const Pos& p, int col, int role) -> QVariant {
+ if (role == Qt::DisplayRole) {
+ switch (col) {
+ case 0:
+ return p.account;
+ case 1:
+ return p.symbol;
+ case 2:
+ return QString::number(p.qty, 'f', 0);
+ case 3:
+ return QString::number(p.pnl, 'f', 2);
+ default:
+ break;
+ }
+ }
+ if (role == Model::SortRole) {
+ if (col == 2)
+ return p.qty;
+ if (col == 3)
+ return p.pnl;
+ }
+ return {};
+ });
+}
+
+QVector<Pos> book() {
+ return {{"A1", "AAPL", 100, 250.0}, {"A1", "MSFT", 50, -75.5}, {"A2", "NVDA", 10, 1200.0}};
+}
+
+/// Minimal stand-in for QSignalSpy (Qt6::Test is not linked — see the include
+/// note at the top). Records reset counts and the extent of each dataChanged.
+struct SignalCounter {
+ int resets = 0;
+ int changes = 0;
+ int last_top_row = -1, last_bottom_row = -1, last_left_col = -1, last_right_col = -1;
+
+ explicit SignalCounter(QAbstractItemModel* m) {
+ QObject::connect(m, &QAbstractItemModel::modelReset, [this]() { ++resets; });
+ QObject::connect(m, &QAbstractItemModel::dataChanged,
+ [this](const QModelIndex& tl, const QModelIndex& br, const QList<int>&) {
+ ++changes;
+ last_top_row = tl.row();
+ last_bottom_row = br.row();
+ last_left_col = tl.column();
+ last_right_col = br.column();
+ });
+ }
+};
+
+} // namespace
+
+int run_live_table_selftest() {
+ QTextStream out(stdout);
+ out << "=== LiveTableModel selftest ===\n";
+
+ // ── Shape ───────────────────────────────────────────────────────────────
+ {
+ Model m;
+ configure(m);
+ m.upsert(book());
+ check(m.rowCount() == 3, "rowCount reflects upserted rows");
+ check(m.columnCount() == 4, "columnCount follows headers");
+ check(m.headerData(1, Qt::Horizontal, Qt::DisplayRole).toString() == QLatin1String("SYMBOL"),
+ "headerData returns the configured header");
+ check(m.data(m.index(0, 1), Qt::DisplayRole).toString() == QLatin1String("AAPL"),
+ "data() routes through the cell functor");
+ check(m.data(m.index(2, 3), Model::SortRole).toDouble() == 1200.0, "SortRole carries the numeric key");
+ check(m.data(m.index(0, 0), Model::KeyRole).toString() == QLatin1String("A1|AAPL"),
+ "KeyRole exposes the stable row key");
+ // Model invariants, asserted by hand (see the include note above).
+ check(!m.index(0, 0).parent().isValid(), "a table model reports no parent");
+ check(m.rowCount(m.index(0, 0)) == 0, "child rowCount under a valid index is 0");
+ check(!m.data(m.index(99, 0), Qt::DisplayRole).isValid(), "out-of-range row yields an invalid QVariant");
+ check(!m.data(QModelIndex(), Qt::DisplayRole).isValid(), "invalid index yields an invalid QVariant");
+ check(!m.headerData(0, Qt::Vertical, Qt::DisplayRole).isValid(), "no vertical header is claimed");
+ }
+
+ // ── The point of the class: a value tick must NOT reset the model ───────
+ {
+ Model m;
+ configure(m);
+ m.upsert(book());
+
+ SignalCounter spy(&m);
+
+ auto ticked = book();
+ ticked[1].pnl = -80.0; // one cell moves
+ m.upsert(ticked);
+
+ check(spy.resets == 0, "same key sequence does NOT reset the model (selection/scroll survive)");
+ check(spy.changes == 1, "exactly one dataChanged for a single moved row");
+ check(spy.last_top_row == 1 && spy.last_bottom_row == 1, "dataChanged targets only the row that moved");
+ check(spy.last_left_col == 3 && spy.last_right_col == 3, "dataChanged spans only the column that moved");
+ check(m.data(m.index(1, 3), Qt::DisplayRole).toString() == QLatin1String("-80.00"),
+ "new value is adopted");
+ }
+
+ // ── An unchanged tick must emit nothing at all ──────────────────────────
+ {
+ Model m;
+ configure(m);
+ m.upsert(book());
+ SignalCounter spy(&m);
+ m.upsert(book()); // identical payload — the common idle case
+ check(spy.changes == 0 && spy.resets == 0, "identical payload emits no signals (idle costs nothing)");
+ }
+
+ // ── Structural changes still reset, and the key index stays correct ─────
+ {
+ Model m;
+ configure(m);
+ m.upsert(book());
+ SignalCounter spy(&m);
+
+ auto smaller = book();
+ smaller.removeAt(1); // position closed
+ m.upsert(smaller);
+ check(spy.resets == 1, "row removal resets the model");
+ check(m.rowCount() == 2, "removed row is gone");
+ check(m.index_of_key(QStringLiteral("A1|MSFT")) == -1, "key index drops the removed row");
+ check(m.index_of_key(QStringLiteral("A2|NVDA")) == 1, "key index is rebuilt with correct positions");
+
+ const Pos* p = m.row_for_key(QStringLiteral("A2|NVDA"));
+ check(p != nullptr && p->qty == 10, "row_for_key returns the domain object, not parsed display text");
+ check(m.row_at(m.index(0, 0)) != nullptr, "row_at resolves a valid index");
+ check(m.row_at(QModelIndex()) == nullptr, "row_at rejects an invalid index");
+ }
+
+ // ── Filter ──────────────────────────────────────────────────────────────
+ {
+ Model m;
+ configure(m);
+ m.set_filter([](const Pos& p) { return p.qty != 0; });
+ auto with_flat = book();
+ with_flat.push_back({"A2", "FLAT", 0, 0});
+ m.upsert(with_flat);
+ check(m.rowCount() == 3, "filter drops rows before they reach the view");
+ }
+
+ // ── clear() ─────────────────────────────────────────────────────────────
+ {
+ Model m;
+ configure(m);
+ m.upsert(book());
+ m.clear();
+ check(m.rowCount() == 0, "clear empties the model");
+ SignalCounter spy(&m);
+ m.clear();
+ check(spy.resets == 0, "clear on an empty model is a no-op");
+ }
+
+ out << (g_failures == 0 ? "=== LiveTableModel: ALL PASS ===\n"
+ : QStringLiteral("=== LiveTableModel: %1 FAILURE(S) ===\n").arg(g_failures));
+ return g_failures == 0 ? 0 : 1;
+}
+
+} // namespace fincept::ui
diff --git a/fincept-qt/src/ui/tables/LiveTableSelftest.h b/fincept-qt/src/ui/tables/LiveTableSelftest.h
new file mode 100644
index 000000000..cd93d27ae
--- /dev/null
+++ b/fincept-qt/src/ui/tables/LiveTableSelftest.h
@@ -0,0 +1,9 @@
+#pragma once
+// Headless selftest for ui::LiveTableModel / ui::LiveTableDelegate.
+// Invoked from main.cpp via --selftest-live-table. Returns 0 on success.
+
+namespace fincept::ui {
+
+int run_live_table_selftest();
+
+} // namespace fincept::ui
diff --git a/updates.json b/updates.json
index 916ef4d79..39227d87f 100644
--- a/updates.json
+++ b/updates.json
@@ -3,25 +3,25 @@
"schema-version": 2,
"updates": {
"windows-x64": {
- "latest-version": "4.2.0",
- "download-url": "https://github.com/Fincept-Corporation/FinceptTerminal/releases/download/v4.2.0/FinceptTerminal-4.2.0-windows-x64-setup.exe",
+ "latest-version": "4.3.0",
+ "download-url": "https://github.com/Fincept-Corporation/FinceptTerminal/releases/download/v4.3.0/FinceptTerminal-4.3.0-windows-x64-setup.exe",
"sha256": "ff40a7d2b3674b955d9a113a934c36f06f175e048c3fc4dc383ede830da45abb",
- "open-url": "https://github.com/Fincept-Corporation/FinceptTerminal/releases/tag/v4.2.0",
- "changelog": "Fincept Terminal v4.2.0 \u2014 see release notes at https://github.com/Fincept-Corporation/FinceptTerminal/releases/tag/v4.2.0"
+ "open-url": "https://github.com/Fincept-Corporation/FinceptTerminal/releases/tag/v4.3.0",
+ "changelog": "Fincept Terminal v4.3.0 \u2014 see release notes at https://github.com/Fincept-Corporation/FinceptTerminal/releases/tag/v4.3.0"
},
"linux-x64": {
- "latest-version": "4.2.0",
- "download-url": "https://github.com/Fincept-Corporation/FinceptTerminal/releases/download/v4.2.0/FinceptTerminal-4.2.0-linux-x64-setup.run",
+ "latest-version": "4.3.0",
+ "download-url": "https://github.com/Fincept-Corporation/FinceptTerminal/releases/download/v4.3.0/FinceptTerminal-4.3.0-linux-x64-setup.run",
"sha256": "5209d8318c2bbce6edb72296da631c0b0fff09690edb482bfb6ddf8cfe0a37ed",
- "open-url": "https://github.com/Fincept-Corporation/FinceptTerminal/releases/tag/v4.2.0",
- "changelog": "Fincept Terminal v4.2.0 \u2014 see release notes at https://github.com/Fincept-Corporation/FinceptTerminal/releases/tag/v4.2.0"
+ "open-url": "https://github.com/Fincept-Corporation/FinceptTerminal/releases/tag/v4.3.0",
+ "changelog": "Fincept Terminal v4.3.0 \u2014 see release notes at https://github.com/Fincept-Corporation/FinceptTerminal/releases/tag/v4.3.0"
},
"macos-arm64": {
- "latest-version": "4.2.0",
- "download-url": "https://github.com/Fincept-Corporation/FinceptTerminal/releases/download/v4.2.0/FinceptTerminal-4.2.0-macos-arm64-setup.dmg",
+ "latest-version": "4.3.0",
+ "download-url": "https://github.com/Fincept-Corporation/FinceptTerminal/releases/download/v4.3.0/FinceptTerminal-4.3.0-macos-arm64-setup.dmg",
"sha256": "776f524b186555b22e983da6750a35120e59c36d834dd74db9f06b6e51d7cccb",
- "open-url": "https://github.com/Fincept-Corporation/FinceptTerminal/releases/tag/v4.2.0",
- "changelog": "Fincept Terminal v4.2.0 \u2014 see release notes at https://github.com/Fincept-Corporation/FinceptTerminal/releases/tag/v4.2.0"
+ "open-url": "https://github.com/Fincept-Corporation/FinceptTerminal/releases/tag/v4.3.0",
+ "changelog": "Fincept Terminal v4.3.0 \u2014 see release notes at https://github.com/Fincept-Corporation/FinceptTerminal/releases/tag/v4.3.0"
}
}
}