FinceptTerminal is a modern finance application offering advanced market analytics, investment research, and economic data tools, designed for interactive exploration and data-driven decision-making in a user-friendly environment.
C++ ai-agentsalgorithmic-tradingbloomberg-terminalcppfinancefinancial-marketsfintechgood-first-issueinvestmentinvestment-researchmachine-learningopensourcepythonqtquantitative-financestock-markettrading
local changes
tilakpatel2219e43cca1fd8
diff --git a/fincept-qt/scripts/yfinance_data.py b/fincept-qt/scripts/yfinance_data.pyindex 6959ddac1..2a20549db 100644--- a/fincept-qt/scripts/yfinance_data.py+++ b/fincept-qt/scripts/yfinance_data.py@@ -1246,26 +1246,47 @@ def _daemon_write_frame(stream, data_bytes):def _daemon_dispatch(action, payload):- """Run one action and return the raw result object (not wrapped)."""+ """Run one action and return the raw result object (not wrapped).++ Mirrors the CLI dispatch in main() — every action a C++ caller might pass+ through PythonRunner is wired here so the daemon can handle it without the+ ~3s subprocess + import cost.+ """+ p = payload or {}if action == "batch_all":- return get_batch_all(payload or {})+ return get_batch_all(p)if action == "batch_quotes":- syms = (payload or {}).get("symbols") or []- return get_batch_quotes(syms)+ return get_batch_quotes(p.get("symbols") or [])if action == "batch_sparklines":- syms = (payload or {}).get("symbols") or []- return get_batch_sparklines(syms)+ return get_batch_sparklines(p.get("symbols") or [])if action == "historical_period":- p = payload or {}return get_historical_period(p.get("symbol"), p.get("period", "6mo"), p.get("interval", "1d"))+ if action == "historical":+ return get_historical(+ p.get("symbol"), p.get("start_date"), p.get("end_date"), p.get("interval", "1d"))if action == "quote":- return get_quote((payload or {}).get("symbol"))+ return get_quote(p.get("symbol"))if action == "info":- return get_info((payload or {}).get("symbol"))+ return get_info(p.get("symbol"))if action == "news":- p = payload or {}return get_news(p.get("symbol"), p.get("count", 20))+ if action == "financials":+ return get_financials(p.get("symbol"))+ if action == "company_profile":+ return get_company_profile(p.get("symbol"))+ if action == "financial_ratios":+ return get_financial_ratios(p.get("symbol"))+ if action == "multiple_ratios":+ return get_multiple_ratios(p.get("symbols") or [])+ if action == "multiple_profiles":+ return get_multiple_profiles(p.get("symbols") or [])+ if action == "search":+ return search_symbols(p.get("query") or "", int(p.get("limit", 50)))+ if action == "portfolio_nav_history":+ return get_portfolio_nav_history(p.get("positions") or [], p.get("period", "1y"))+ if action == "portfolio_nav_history_replay":+ return get_portfolio_nav_history_replay(p.get("transactions") or [])return {"error": f"Unknown action: {action}"}diff --git a/fincept-qt/src/app/WindowFrame.cpp b/fincept-qt/src/app/WindowFrame.cppindex 1a4a8de17..fddadf7c7 100644--- a/fincept-qt/src/app/WindowFrame.cpp+++ b/fincept-qt/src/app/WindowFrame.cpp@@ -804,9 +804,21 @@ WindowFrame::WindowFrame(int window_id, QWidget* parent, const WindowId& adoptedset_shell_visible(true);stack_->setCurrentIndex(1);}- if (!dock_restored) {+ // Recovery / "Continue from last session" path: WorkspaceShell::apply+ // spawns this frame with a non-null adopted_uuid and will call+ // apply_layout(fl) immediately after construction returns. Skip the+ // default dashboard navigate so we don't (a) leave a stray dashboard+ // dock widget for ADS restoreState to flag-as-unassigned, and+ // (b) pay the cost of constructing DashboardScreen just to discard it.+ // If apply_layout subsequently fails, the caller is responsible for+ // falling back to a default screen.+ if (!dock_restored && adopted_uuid.is_null()) {dock_router_->navigate("dashboard");LOG_INFO("WindowFrame", "Applied clean default dock layout");+ } else if (!dock_restored) {+ LOG_INFO("WindowFrame",+ QString("Deferring default navigate — frame spawned with adopted uuid %1 "+ "(apply_layout will populate)").arg(adopted_uuid.to_string()));} else {// Restore last-active screen as the focused tab and sync tab bar.// Per-window key so multi-window users don't override each other.diff --git a/fincept-qt/src/app/WindowFrame_Layout.cpp b/fincept-qt/src/app/WindowFrame_Layout.cppindex 757d6c2ab..e55a40411 100644--- a/fincept-qt/src/app/WindowFrame_Layout.cpp+++ b/fincept-qt/src/app/WindowFrame_Layout.cpp@@ -126,6 +126,21 @@ bool WindowFrame::apply_layout(const layout::FrameLayout& fl) {// objectName), and a "screen factory" pass that runs deferred via// PanelMaterialiser so 50-panel workspaces don't freeze the UI.+ // Phase 0: pre-create EVERY factory-registered dock widget into a single+ // shared dock area. ADS's restoreState walks the blob and calls+ // findDockWidget(name); when a referenced widget is not registered, ADS+ // *silently skips it* (DockAreaWidget.cpp: `if (!DockWidget) continue;`)+ // and deletes any dock area that ends up empty as a result. That is the+ // recovery-bug path: closed-at-save tabs are in the dock_state blob but+ // absent from fl.panels, so they were never pre-created — restore drops+ // them and any tab group that contained only such widgets vanishes.+ //+ // ensure_all_registered is idempotent (skips widgets already in+ // dock_widgets_), groups everything as hidden tabs in one CenterDockArea+ // (vs. prepare_dock_widget's one-area-per-call), and is also what the+ // constructor calls on the QSettings-restore path — same protection here.+ dock_router_->ensure_all_registered();+// Track each panel's resolved string id alongside its FrameLayout// entry so the deferred pass doesn't have to recompute the// dup_index suffix.@@ -135,7 +150,8 @@ bool WindowFrame::apply_layout(const layout::FrameLayout& fl) {// Phase 1: pre-create dock widget shells (no screen factory call yet)// and adopt the saved instance UUIDs. The shells are what ADS's// restoreState matches by objectName; the heavy widget construction- // is deferred to Phase 5 below.+ // is deferred to Phase 5 below. Idempotent after Phase 0 for non-dup+ // ids; still needed for "<type>#dup<n>" panels not in factories_.for (const auto& ps : fl.panels) {QString id = ps.type_id;int dup_index = 0;diff --git a/fincept-qt/src/mcp/McpProvider.cpp b/fincept-qt/src/mcp/McpProvider.cppindex 4aaaa68b0..cf4380c49 100644--- a/fincept-qt/src/mcp/McpProvider.cpp+++ b/fincept-qt/src/mcp/McpProvider.cpp@@ -25,6 +25,17 @@ McpProvider& McpProvider::instance() {return s;}+// Build the LLM-facing snapshot for a tool. Serialises input_schema once —+// the QJsonObject copy is cheap (CoW), so list_tools() can hand out copies+// without re-walking the schema each call.+static UnifiedTool make_snapshot(const ToolDef& t) {+ return UnifiedTool{+ QString(INTERNAL_SERVER_ID), QString(INTERNAL_SERVER_NAME),+ t.name, t.description, t.input_schema.to_json(),+ /*is_internal=*/true, t.category, t.is_destructive,+ };+}+// ============================================================================// Registration// ============================================================================@@ -32,6 +43,7 @@ McpProvider& McpProvider::instance() {void McpProvider::register_tool(ToolDef tool) {QMutexLocker lock(&mutex_);QString name = tool.name;+ snapshots_.insert(name, make_snapshot(tool)); // serialise schema oncetools_.insert(name, std::move(tool));++generation_;}@@ -40,6 +52,7 @@ void McpProvider::register_tools(std::vector<ToolDef> tools) {QMutexLocker lock(&mutex_);for (auto& t : tools) {QString name = t.name;+ snapshots_.insert(name, make_snapshot(t));tools_.insert(name, std::move(t));}++generation_;@@ -48,6 +61,7 @@ void McpProvider::register_tools(std::vector<ToolDef> tools) {void McpProvider::unregister_tool(const QString& name) {QMutexLocker lock(&mutex_);tools_.remove(name);+ snapshots_.remove(name);++generation_;}@@ -76,14 +90,11 @@ bool McpProvider::is_tool_enabled(const QString& name) const {std::vector<UnifiedTool> McpProvider::list_tools() const {QMutexLocker lock(&mutex_);std::vector<UnifiedTool> result;- result.reserve(static_cast<std::size_t>(tools_.size()));-- for (auto it = tools_.cbegin(); it != tools_.cend(); ++it) {+ result.reserve(static_cast<std::size_t>(snapshots_.size()));+ for (auto it = snapshots_.cbegin(); it != snapshots_.cend(); ++it) {if (disabled_tools_.contains(it.key()))continue;- const auto& t = it.value();- result.push_back({QString(INTERNAL_SERVER_ID), QString(INTERNAL_SERVER_NAME), t.name, t.description,- t.input_schema.to_json(), true, t.category, t.is_destructive});+ result.push_back(it.value());}return result;}@@ -91,16 +102,22 @@ std::vector<UnifiedTool> McpProvider::list_tools() const {std::vector<UnifiedTool> McpProvider::list_all_tools() const {QMutexLocker lock(&mutex_);std::vector<UnifiedTool> result;- result.reserve(static_cast<std::size_t>(tools_.size()));-- for (auto it = tools_.cbegin(); it != tools_.cend(); ++it) {- const auto& t = it.value();- result.push_back({QString(INTERNAL_SERVER_ID), QString(INTERNAL_SERVER_NAME), t.name, t.description,- t.input_schema.to_json(), true, t.category, t.is_destructive});- }+ result.reserve(static_cast<std::size_t>(snapshots_.size()));+ for (auto it = snapshots_.cbegin(); it != snapshots_.cend(); ++it)+ result.push_back(it.value());return result;}+std::optional<UnifiedTool> McpProvider::find_tool(const QString& name) const {+ QMutexLocker lock(&mutex_);+ auto it = snapshots_.constFind(name);+ if (it == snapshots_.constEnd())+ return std::nullopt;+ if (disabled_tools_.contains(name))+ return std::nullopt;+ return it.value();+}+std::size_t McpProvider::tool_count() const {QMutexLocker lock(&mutex_);std::size_t count = 0;@@ -351,9 +368,22 @@ QJsonArray McpProvider::format_tools_for_openai() const {QPair<QString, QString> McpProvider::parse_openai_function_name(const QString& fn_name) {int pos = fn_name.indexOf("__");- if (pos <= 0 || pos >= fn_name.length() - 2)- return {"", ""};- return {fn_name.left(pos), decode_tool_name_from_wire(fn_name.mid(pos + 2))};+ if (pos > 0 && pos < fn_name.length() - 2)+ return {fn_name.left(pos), decode_tool_name_from_wire(fn_name.mid(pos + 2))};++ // Fallback: some models (minimax, certain OpenRouter routes) drop the+ // "<server>__" prefix and call the tool by its bare advertised name+ // (e.g. "tool.list" instead of "fincept-terminal__tool-dot-list").+ // Accept either the raw dotted form or the wire-encoded form if it+ // matches a known internal tool — anything else is still rejected.+ if (!fn_name.isEmpty()) {+ const QString decoded = decode_tool_name_from_wire(fn_name);+ if (instance().has_tool(decoded))+ return {QString(INTERNAL_SERVER_ID), decoded};+ if (instance().has_tool(fn_name))+ return {QString(INTERNAL_SERVER_ID), fn_name};+ }+ return {"", ""};}// Tightest common-subset regex for tool function names across every supported@@ -403,6 +433,7 @@ QString McpProvider::decode_tool_name_from_wire(const QString& wire_name) {void McpProvider::clear() {QMutexLocker lock(&mutex_);tools_.clear();+ snapshots_.clear();disabled_tools_.clear();++generation_;}diff --git a/fincept-qt/src/mcp/McpProvider.h b/fincept-qt/src/mcp/McpProvider.hindex a21db14d4..583c1b20b 100644--- a/fincept-qt/src/mcp/McpProvider.h+++ b/fincept-qt/src/mcp/McpProvider.h@@ -10,6 +10,7 @@#include <QMutex>#include <QSet>+#include <optional>#include <vector>namespace fincept::mcp {@@ -40,6 +41,12 @@ class McpProvider {std::size_t tool_count() const;bool has_tool(const QString& name) const;+ /// O(1) lookup of a single tool's UnifiedTool snapshot by canonical name.+ /// Returns `std::nullopt` if the name is unknown or disabled. Used by+ /// tool.describe so the hot tool-pick path doesn't pay the O(N) cost of+ /// list_tools()+linear-scan (was ~3 ms p95 across the 583-tool catalog).+ std::optional<UnifiedTool> find_tool(const QString& name) const;+// ── Tool Execution ─────────────────────────────────────────────────────/// Synchronous execution. For tools registered with `handler` (legacy),@@ -135,6 +142,10 @@ class McpProvider {mutable QMutex mutex_;QHash<QString, ToolDef> tools_;+ // Pre-serialised view of each tool, kept in lockstep with `tools_`. Built+ // once at registration so list_tools()/find_tool() never re-serialise the+ // input_schema. `disabled_tools_` is still consulted at read time.+ QHash<QString, UnifiedTool> snapshots_;QSet<QString> disabled_tools_;quint64 generation_ = 0;diff --git a/fincept-qt/src/mcp/McpService.cpp b/fincept-qt/src/mcp/McpService.cppindex 44176d11d..2cf1354ba 100644--- a/fincept-qt/src/mcp/McpService.cpp+++ b/fincept-qt/src/mcp/McpService.cpp@@ -236,6 +236,10 @@ static const QSet<QString>& tier_0_tool_names() {"list_tabs","get_current_tab","get_auth_status",+ // Always-visible so the model checks chat→report linkage before any+ // report-builder work — prevents new chats from accidentally appending+ // to the previous chat's report.+ "report_session_context",};return kTier0;}diff --git a/fincept-qt/src/mcp/SchemaValidator.cpp b/fincept-qt/src/mcp/SchemaValidator.cppindex fc9ada14d..15e889402 100644--- a/fincept-qt/src/mcp/SchemaValidator.cpp+++ b/fincept-qt/src/mcp/SchemaValidator.cpp@@ -3,6 +3,7 @@#include "mcp/SchemaValidator.h"#include <QJsonArray>+#include <QJsonDocument>#include <QRegularExpression>namespace fincept::mcp {@@ -124,6 +125,57 @@ Result<void> validate_args(const ToolSchema& schema, QJsonObject& args) {return Result<void>::err(("Missing required parameter: " + key).toStdString());}+ // ── Step 2.5: coerce stringified primitives, objects, arrays ─────────+ // Two common LLM mistakes:+ // - emit nested JSON as an escaped string ("config": "{\"a\":1}")+ // - emit numbers / booleans as strings from <parameter> XML bodies+ // ("id": "2", "enabled": "true") because text-tool extraction can't+ // tell scalars apart from prose without type hints.+ // Coerce based on the schema's expected type before rejection.+ auto expected_type = [&](const QString& key) -> QString {+ if (schema.params.contains(key))+ return schema.params[key].type;+ if (schema.properties.contains(key))+ return schema.properties[key].toObject()["type"].toString();+ return {};+ };+ const QStringList keys = args.keys();+ for (const QString& key : keys) {+ const QString want = expected_type(key);+ const QJsonValue cur = args.value(key);+ if (!cur.isString())+ continue;+ const QString s = cur.toString().trimmed();+ if (s.isEmpty())+ continue;++ if (want == "object" || want == "array") {+ const auto doc = QJsonDocument::fromJson(s.toUtf8());+ if (doc.isNull())+ continue;+ if (want == "object" && doc.isObject())+ args[key] = doc.object();+ else if (want == "array" && doc.isArray())+ args[key] = doc.array();+ } else if (want == "integer") {+ bool ok = false;+ const qint64 n = s.toLongLong(&ok);+ if (ok)+ args[key] = static_cast<double>(n);+ } else if (want == "number") {+ bool ok = false;+ const double d = s.toDouble(&ok);+ if (ok)+ args[key] = d;+ } else if (want == "boolean") {+ const QString lower = s.toLower();+ if (lower == "true" || lower == "1")+ args[key] = true;+ else if (lower == "false" || lower == "0")+ args[key] = false;+ }+ }+// ── Step 3: per-param type / range / enum / pattern ─────────────────// Structured params take precedence. For keys that exist only in the// legacy properties object (unmigrated tools), validate against the rawdiff --git a/fincept-qt/src/mcp/ToolRetriever.cpp b/fincept-qt/src/mcp/ToolRetriever.cppindex 5952b43da..0f97bcf85 100644--- a/fincept-qt/src/mcp/ToolRetriever.cpp+++ b/fincept-qt/src/mcp/ToolRetriever.cpp@@ -28,11 +28,13 @@ void ToolRetriever::invalidate() {// ── Stop words ──────────────────────────────────────────────────────────//-// Conservative list — common English function words plus a few generic-// command verbs that appear in nearly every tool description ("get", "set",-// "list") and so carry no discriminative signal under BM25's IDF term.-// Domain words ("price", "report", "trade", "news") are intentionally KEPT-// — those are the ones that matter for tool-pick.+// Conservative list — only common English function words. Generic command+// verbs ("get", "set", "list", "show", "run") WERE in this list, but the+// quality battery revealed that stripping them collapses verb-cued queries:+// "show me the watchlist" became indistinguishable from "watchlist", so all+// four watchlist tools tied and `delete_watchlist` won on alphabetical order.+// We now keep verb tokens; BM25's IDF naturally down-weights them since+// they appear across many tools.static const QSet<QString>& stop_word_set() {static const QSet<QString> kStop = {"a", "an", "and", "are", "as", "at", "be", "by", "for", "from",@@ -45,12 +47,102 @@ static const QSet<QString>& stop_word_set() {"all", "any", "both", "each", "few", "more", "most", "other", "some","such", "no", "not", "only", "own", "same", "than", "too", "very","just", "also", "now", "then", "here", "there",- // Generic verbs that carry no discriminative weight in tool descs- "get", "set", "list", "show", "give", "make", "use", "run",};return kStop;}+// ── Query-side synonyms ─────────────────────────────────────────────────+//+// Applied ONLY when tokenising the query, never the indexed docs. Expands+// natural-language phrasings into the vocabulary actually used in tool+// names ("price" → "quote", "buy/sell" → "order/trade", "tab/screen" →+// "navigate"). Each entry adds tokens; the original token stays in the+// stream so a literal match still scores.+//+// Keep this map small and audit-friendly — anything broader belongs in a+// proper embedding model. Domain words first; UI/navigation verbs second.+static const QHash<QString, QStringList>& query_synonyms() {+ static const QHash<QString, QStringList> kSyn = {+ // Markets / equity+ {"price", {"quote"}},+ {"prices", {"quote", "historical"}},+ {"ticker", {"symbol"}},+ {"company", {"symbol", "equity"}},+ {"chart", {"ohlc"}},+ // Trading+ {"buy", {"order", "trade", "place"}},+ {"sell", {"order", "trade", "place"}},+ {"order", {"trade"}},+ {"trade", {"order"}},+ // Navigation / UI+ {"tab", {"navigate", "screen"}},+ {"screen", {"navigate", "tab"}},+ {"page", {"navigate", "tab"}},+ {"open", {"navigate"}},+ {"switch", {"navigate"}},+ {"window", {"panel"}},+ // Portfolio+ {"pnl", {"profit", "portfolio"}},+ {"profit", {"portfolio", "pnl"}},+ {"holdings", {"portfolio", "holding"}},+ // Filings+ {"filings", {"edgar"}},+ {"filing", {"edgar"}},+ {"sec", {"edgar"}},+ {"earnings", {"financials"}},+ // Strategy / analytics+ {"strategy", {"backtest"}},+ {"sharpe", {"risk", "metrics"}},+ {"var", {"risk"}},+ };+ return kSyn;+}++// Read-style verbs vs mutate-style verbs. Used by the destructive-tool+// penalty: if the query reads like an inspection ("show me X", "list X")+// and contains no mutate verb, score destructive tools at half weight so+// `delete_watchlist` stops outranking `add_to_watchlist` for "show me the+// watchlist".+static const QSet<QString>& read_verbs() {+ static const QSet<QString> kRead = {+ "show", "list", "view", "find", "get", "fetch", "lookup",+ "describe", "search", "display", "see", "read", "inspect",+ "explore", "what", "which", "tell",+ };+ return kRead;+}+static const QSet<QString>& mutate_verbs() {+ static const QSet<QString> kMutate = {+ "delete", "remove", "drop", "clear",+ "add", "create", "insert", "append", "import",+ "place", "submit", "send", "post",+ "set", "update", "modify", "edit", "rename",+ "cancel", "stop", "kill",+ "save", "store", "export", "write",+ };+ return kMutate;+}++// Specialist categories — these have many tools that keyword-match generic+// queries (e.g. quant-lab's 100 tools mention "factor/risk/model") and+// drown out simpler tools. Each entry maps category → cue tokens that+// signal genuine intent for that specialist. If a query contains NO cue+// for a specialist, every tool in it is demoted at scoring time.+static const QHash<QString, QSet<QString>>& specialist_categories() {+ static const QHash<QString, QSet<QString>> kSpec = {+ {"quant-lab", {"quant", "factor", "backtest", "alpha", "ic",+ "rl", "ml", "ml-ops", "alphalens", "qlib"}},+ {"surface-analytics", {"surface", "vol", "volatility", "skew",+ "databento", "iv"}},+ {"alt-investments", {"alt", "junk", "convertible", "preferred",+ "private", "venture", "hedge", "yield"}},+ };+ return kSpec;+}+static constexpr double kSpecialistPenalty = 0.7;+static constexpr double kDestructivePenalty = 0.5;+static constexpr double kNameMatchBonus = 2.0;+bool ToolRetriever::is_stop_word(const QString& token) {return stop_word_set().contains(token);}@@ -108,6 +200,8 @@ void ToolRetriever::rebuild_index_locked() {const auto name_tok = tokenise(t.name);for (int i = 0; i < 3; ++i)tokens.append(name_tok);+ for (const auto& nt : name_tok)+ d.name_token_set.insert(nt);const QJsonObject props = t.input_schema["properties"].toObject();for (auto it = props.constBegin(); it != props.constEnd(); ++it) {@@ -171,10 +265,64 @@ std::vector<ToolMatch> ToolRetriever::search(const QString& query, int top_k,if (docs_.empty())return {};- const QStringList q_tokens = tokenise(q);+ QStringList q_tokens = tokenise(q);if (q_tokens.isEmpty())return {};+ // ── Query intent detection (before synonym expansion) ──────────────+ // Look for read-style verbs vs mutate-style verbs in the *raw* query+ // tokens. If the user clearly wants a read action ("show me X", "list+ // X", "find X") and never says delete/place/cancel/etc, we'll halve+ // the score of every destructive tool below — this stops things like+ // `delete_watchlist` outranking `add_to_watchlist` on "show watchlist".+ bool has_read_verb = false;+ bool has_mutate_verb = false;+ for (const auto& tok : q_tokens) {+ if (read_verbs().contains(tok)) has_read_verb = true;+ if (mutate_verbs().contains(tok)) has_mutate_verb = true;+ }+ const bool penalize_destructive = has_read_verb && !has_mutate_verb;++ // ── Specialist-category gating ─────────────────────────────────────+ // For each specialist category, decide whether ANY query token is a+ // genuine cue (e.g. "quant"/"backtest" for quant-lab). Categories with+ // no cue get demoted at scoring time. This stops the 100 quant_* tools+ // from drowning out a plain "compute Sharpe ratio" query.+ QSet<QString> demoted_categories;+ {+ const QSet<QString> q_set(q_tokens.begin(), q_tokens.end());+ for (auto it = specialist_categories().constBegin();+ it != specialist_categories().constEnd(); ++it) {+ bool has_cue = false;+ for (const auto& cue : it.value()) {+ if (q_set.contains(cue)) { has_cue = true; break; }+ }+ if (!has_cue)+ demoted_categories.insert(it.key());+ }+ }++ // ── Query expansion via synonyms ───────────────────────────────────+ // Append synonym tokens AFTER the BM25 vocabulary has been used to+ // measure IDF, so synonym hits contribute to scoring without inflating+ // term frequencies in the index. The original token stays in q_tokens.+ {+ QStringList expanded;+ expanded.reserve(q_tokens.size() * 2);+ const auto& syn = query_synonyms();+ for (const auto& tok : q_tokens) {+ expanded.append(tok);+ auto it = syn.constFind(tok);+ if (it != syn.constEnd()) {+ for (const auto& s : it.value()) {+ if (!expanded.contains(s))+ expanded.append(s);+ }+ }+ }+ q_tokens = std::move(expanded);+ }+const double N = static_cast<double>(docs_.size());// ── BM25 scoring loop ──────────────────────────────────────────────@@ -203,6 +351,7 @@ std::vector<ToolMatch> ToolRetriever::search(const QString& query, int top_k,continue;double s = 0.0;+ int name_hits = 0;for (const auto& q_term : q_tokens) {const int df = df_.value(q_term, 0);if (df == 0)@@ -223,10 +372,26 @@ std::vector<ToolMatch> ToolRetriever::search(const QString& query, int top_k,const double norm = 1.0 - kB + kB * (static_cast<double>(d.length) / avg_doc_length_);const double tf_part = (tf * (kK1 + 1.0)) / (tf + kK1 * norm);s += idf * tf_part;++ // Exact-name bonus: query token literally appears in the tool's+ // name (after tokenisation). Counted once per query token, not+ // per TF — we already weight name tokens 3× during indexing.+ if (d.name_token_set.contains(q_term))+ ++name_hits;}- if (s > 0.0)- scored.push_back({static_cast<int>(i), s});+ if (s <= 0.0)+ continue;++ // ── Adjustments (applied after the BM25 sum) ──────────────────+ if (name_hits > 0)+ s += kNameMatchBonus * name_hits;+ if (penalize_destructive && d.is_destructive)+ s *= kDestructivePenalty;+ if (demoted_categories.contains(d.category))+ s *= kSpecialistPenalty;++ scored.push_back({static_cast<int>(i), s});}// Top-K via partial sort — O(N log K) instead of O(N log N).diff --git a/fincept-qt/src/mcp/ToolRetriever.h b/fincept-qt/src/mcp/ToolRetriever.hindex 3b37e8c94..1d188b4d1 100644--- a/fincept-qt/src/mcp/ToolRetriever.h+++ b/fincept-qt/src/mcp/ToolRetriever.h@@ -26,6 +26,7 @@#include <QHash>#include <QMutex>+#include <QSet>#include <QString>#include <QStringList>#include <QVector>@@ -83,6 +84,11 @@ class ToolRetriever {// index build time so BM25 TF naturally accounts for it.QStringList all_tokens; // Concatenated weighted token streamint length = 0; // |D| in BM25 formula++ // Unique name-tokens — used by the exact-name-match bonus in search()+ // so a query token that literally appears in the tool's name beats+ // tools that merely mention the term in their description.+ QSet<QString> name_token_set;};// ── Index state — guarded by mutex_ ────────────────────────────────diff --git a/fincept-qt/src/mcp/tools/DataSourcesTools.cpp b/fincept-qt/src/mcp/tools/DataSourcesTools.cppindex fcebd494e..a138675bf 100644--- a/fincept-qt/src/mcp/tools/DataSourcesTools.cpp+++ b/fincept-qt/src/mcp/tools/DataSourcesTools.cpp@@ -257,6 +257,7 @@ std::vector<ToolDef> get_data_sources_tools() {t.name = "ds_delete_connection";t.description = "Delete a saved data source connection by ID.";t.category = "data-sources";+ t.is_destructive = true; // mutation tool — penalise on read-style queriest.input_schema.properties = QJsonObject{{"id", QJsonObject{{"type", "string"}, {"description", "Connection ID to delete"}}},};diff --git a/fincept-qt/src/mcp/tools/EquityResearchTools.cpp b/fincept-qt/src/mcp/tools/EquityResearchTools.cppindex eeaf200d8..1eecee716 100644--- a/fincept-qt/src/mcp/tools/EquityResearchTools.cpp+++ b/fincept-qt/src/mcp/tools/EquityResearchTools.cpp@@ -468,7 +468,15 @@ std::vector<ToolDef> get_equity_research_tools() {resolve(ToolResult::fail(msg));holder->deleteLater();});- svc->load_symbol(sym, period);+ // Fire only the slice this tool variant listens for —+ // load_symbol() would queue three daemon requests and+ // serialise behind two we don't even consume.+ if (which == 'q')+ svc->load_quote_only(sym);+ else if (which == 'i')+ svc->load_info_only(sym);+ else+ svc->load_historical_only(sym, period);});};return t;diff --git a/fincept-qt/src/mcp/tools/FileManagerTools.cpp b/fincept-qt/src/mcp/tools/FileManagerTools.cppindex 0ec166b9e..30a87f278 100644--- a/fincept-qt/src/mcp/tools/FileManagerTools.cpp+++ b/fincept-qt/src/mcp/tools/FileManagerTools.cpp@@ -100,6 +100,7 @@ std::vector<ToolDef> get_file_manager_tools() {t.description = "Delete a managed file by its ID. This removes it from the File Manager ""and deletes the stored copy from disk.";t.category = "file_manager";+ t.is_destructive = true; // mutation tool — penalise on read-style queriest.input_schema.properties =QJsonObject{{"id", QJsonObject{{"type", "string"}, {"description", "File ID to delete"}}}};t.input_schema.required = {"id"};diff --git a/fincept-qt/src/mcp/tools/MetaTools.cpp b/fincept-qt/src/mcp/tools/MetaTools.cppindex e7af65772..ce2b77ca0 100644--- a/fincept-qt/src/mcp/tools/MetaTools.cpp+++ b/fincept-qt/src/mcp/tools/MetaTools.cpp@@ -168,17 +168,16 @@ std::vector<ToolDef> get_meta_tools() {const QString name = args["name"].toString();telemetry::g_tool_describe_calls.fetch_add(1);- const auto all = McpProvider::instance().list_tools();- for (const auto& tool : all) {- if (tool.name == name) {- return ToolResult::ok_data(QJsonObject{- {"name", tool.name},- {"category", tool.category},- {"description", tool.description},- {"input_schema", tool.input_schema},- {"server_id", tool.server_id},- });- }+ // O(1) snapshot lookup — previously linear-scanned the full+ // catalog while re-serialising every input_schema (~3 ms p95).+ if (auto tool = McpProvider::instance().find_tool(name)) {+ return ToolResult::ok_data(QJsonObject{+ {"name", tool->name},+ {"category", tool->category},+ {"description", tool->description},+ {"input_schema", tool->input_schema},+ {"server_id", tool->server_id},+ });}telemetry::g_tool_describe_misses.fetch_add(1);return ToolResult::fail("Tool not found: " + name);diff --git a/fincept-qt/src/mcp/tools/NewsTools.cpp b/fincept-qt/src/mcp/tools/NewsTools.cppindex 45c76ec9c..33b2b32ae 100644--- a/fincept-qt/src/mcp/tools/NewsTools.cpp+++ b/fincept-qt/src/mcp/tools/NewsTools.cpp@@ -446,6 +446,7 @@ std::vector<ToolDef> get_news_tools() {t.name = "delete_news_monitor";t.description = "Permanently remove a news keyword monitor by id.";t.category = "news";+ t.is_destructive = true; // mutation tool — penalise on read-style queriest.input_schema.properties =QJsonObject{{"id", QJsonObject{{"type", "string"}, {"description", "Monitor id"}}}};t.input_schema.required = {"id"};diff --git a/fincept-qt/src/mcp/tools/NotesTools.cpp b/fincept-qt/src/mcp/tools/NotesTools.cppindex 41a69df81..abe772ed4 100644--- a/fincept-qt/src/mcp/tools/NotesTools.cpp+++ b/fincept-qt/src/mcp/tools/NotesTools.cpp@@ -118,6 +118,7 @@ std::vector<ToolDef> get_notes_tools() {t.name = "delete_note";t.description = "Delete a research note by ID.";t.category = "notes";+ t.is_destructive = true; // mutation tool — penalise on read-style queriest.input_schema.properties =QJsonObject{{"id", QJsonObject{{"type", "integer"}, {"description", "Note ID to delete"}}}};t.input_schema.required = {"id"};diff --git a/fincept-qt/src/mcp/tools/PaperTradingTools.cpp b/fincept-qt/src/mcp/tools/PaperTradingTools.cppindex e9514b36f..aa68adc5d 100644--- a/fincept-qt/src/mcp/tools/PaperTradingTools.cpp+++ b/fincept-qt/src/mcp/tools/PaperTradingTools.cpp@@ -177,6 +177,7 @@ std::vector<ToolDef> get_paper_trading_tools() {t.name = "pt_cancel_order";t.description = "Cancel a pending paper trading order.";t.category = "paper-trading";+ t.is_destructive = true; // mutation tool — penalise on read-style queriest.input_schema.properties =QJsonObject{{"order_id", QJsonObject{{"type", "string"}, {"description", "Order ID to cancel"}}}};t.input_schema.required = {"order_id"};diff --git a/fincept-qt/src/mcp/tools/PortfolioTools.cpp b/fincept-qt/src/mcp/tools/PortfolioTools.cppindex 62ef13909..1d041e23b 100644--- a/fincept-qt/src/mcp/tools/PortfolioTools.cpp+++ b/fincept-qt/src/mcp/tools/PortfolioTools.cpp@@ -112,6 +112,7 @@ std::vector<ToolDef> get_portfolio_tools() {t.name = "remove_holding";t.description = "Remove a holding from the portfolio by ID.";t.category = "portfolio";+ t.is_destructive = true; // mutation tool — penalise on read-style queriest.input_schema.properties =QJsonObject{{"id", QJsonObject{{"type", "integer"}, {"description", "Holding ID"}}}};t.input_schema.required = {"id"};@@ -227,6 +228,7 @@ std::vector<ToolDef> get_portfolio_tools() {t.name = "delete_portfolio";t.description = "Delete a portfolio and all its assets and transactions.";t.category = "portfolio";+ t.is_destructive = true; // mutation tool — penalise on read-style queriest.input_schema.properties =QJsonObject{{"portfolio_id", QJsonObject{{"type", "string"}, {"description", "Portfolio ID"}}}};t.input_schema.required = {"portfolio_id"};@@ -319,6 +321,7 @@ std::vector<ToolDef> get_portfolio_tools() {t.name = "remove_portfolio_asset";t.description = "Remove an asset from a named portfolio by symbol.";t.category = "portfolio";+ t.is_destructive = true; // mutation tool — penalise on read-style queriest.input_schema.properties =QJsonObject{{"portfolio_id", QJsonObject{{"type", "string"}, {"description", "Portfolio ID"}}},{"symbol", QJsonObject{{"type", "string"}, {"description", "Ticker symbol to remove"}}}};@@ -424,6 +427,7 @@ std::vector<ToolDef> get_portfolio_tools() {t.name = "delete_transaction";t.description = "Delete a transaction by ID.";t.category = "portfolio";+ t.is_destructive = true; // mutation tool — penalise on read-style queriest.input_schema.properties =QJsonObject{{"transaction_id", QJsonObject{{"type", "string"}, {"description", "Transaction ID"}}}};t.input_schema.required = {"transaction_id"};diff --git a/fincept-qt/src/mcp/tools/ReportBuilderTools.cpp b/fincept-qt/src/mcp/tools/ReportBuilderTools.cppindex c2fbbb1eb..55fd101f2 100644--- a/fincept-qt/src/mcp/tools/ReportBuilderTools.cpp+++ b/fincept-qt/src/mcp/tools/ReportBuilderTools.cpp@@ -17,7 +17,12 @@#include "core/events/EventBus.h"#include "core/logging/Logger.h"#include "core/report/ReportDocument.h"+#include "screens/report_builder/ReportBuilderScreen.h"+#include "services/llm/LlmRequestPolicy.h"#include "services/report_builder/ReportBuilderService.h"+#include "storage/repositories/SettingsRepository.h"++#include <QUndoStack>#include <QCoreApplication>#include <QDateTime>@@ -72,11 +77,54 @@ void maybe_request_navigation() {QVariantMap{{"screen_id", "report_builder"}, {"tab_index", 8}});}+// ── Chat → report linkage ────────────────────────────────────────────────────+//+// Each chat session "claims" the report it edits so that new chats start+// fresh while continuing chats keep editing the same canvas. The link key is+// the chat_session_id surfaced via the thread_local set by chat_streaming;+// the value is whatever feels stable about the current report (current_file+// if saved, otherwise a session-scoped placeholder).+//+// Persisted under settings keys "chat_report_link:<chat_session_id>" so the+// linkage survives restarts.++QString link_key_for(const QString& chat_id) {+ return QStringLiteral("chat_report_link:") + chat_id;+}++QString get_linked_report_for(const QString& chat_id) {+ if (chat_id.isEmpty())+ return {};+ auto r = SettingsRepository::instance().get(link_key_for(chat_id));+ return r.is_ok() ? r.value() : QString{};+}++void set_linked_report_for(const QString& chat_id, const QString& path_or_placeholder) {+ if (chat_id.isEmpty())+ return;+ SettingsRepository::instance().set(link_key_for(chat_id), path_or_placeholder, "report-builder");+}+// Helper: called at the top of every mutating tool.void on_llm_mutation_start() {maybe_request_navigation();auto* svc = &Service::instance();QMetaObject::invokeMethod(svc, [svc]() { svc->note_llm_mutation(); }, Qt::QueuedConnection);++ // Auto-link: the first mutation in a chat session claims the currently-open+ // report. If a real file path is set, that becomes the link target;+ // otherwise we use an "<unsaved>" placeholder so subsequent calls in the+ // same chat know "this chat has already started a report" and don't+ // accidentally clear it.+ const QString chat_id = fincept::ai_chat::detail::t_chat_session_id;+ if (chat_id.isEmpty())+ return;+ if (!get_linked_report_for(chat_id).isEmpty())+ return; // already linked+ QString current;+ QMetaObject::invokeMethod(svc, [svc, ¤t]() { current = svc->current_file(); },+ Qt::BlockingQueuedConnection);+ set_linked_report_for(chat_id, current.isEmpty() ? QStringLiteral("<unsaved>") : current);}// ── JSON helpers ─────────────────────────────────────────────────────────────@@ -191,8 +239,9 @@ std::vector<ToolDef> get_report_builder_tools() {"\n""Data-bearing components (use `config`):\n""• table: config={'csv':'Header1,Header2,Header3|Row1Col1,Row1Col2,Row1Col3|...'}. "- " Use | to separate rows, , to separate cells. First row is bolded as header. "- " Numeric cells right-align automatically. Example for financials:\n"+ " Rows are separated by `|` OR by newline `\\n` (both accepted — pick whichever is "+ " easier in your JSON). Cells separated by `,`. First row is bolded as header. "+ " Numeric cells right-align automatically. Example for financials (pipe form):\n"" 'Metric,FY22,FY23,FY24|Revenue ($M),81462,96773,97690|Gross Margin,25.6%,17.7%,17.9%'\n""• chart: config={'chart_type':'bar'|'line'|'pie','title':'Revenue','data':'10,20,30',"" 'labels':'Q1,Q2,Q3','width':'640'}. Data is CSV numbers, labels CSV strings.\n"@@ -313,6 +362,7 @@ std::vector<ToolDef> get_report_builder_tools() {t.name = "report_remove_component";t.description = "Remove a component by stable id.";t.category = "report-builder";+ t.is_destructive = true; // mutation tool — penalise on read-style queriest.input_schema.properties =QJsonObject{{"id", QJsonObject{{"type", "integer"}, {"description", "Stable component id"}}}};t.input_schema.required = {"id"};@@ -360,8 +410,16 @@ std::vector<ToolDef> get_report_builder_tools() {t.name = "report_clear";t.description = "Clear the entire report — remove all components and reset metadata to defaults.";t.category = "report-builder";+ t.is_destructive = true; // mutation tool — penalise on read-style queriest.input_schema.properties = QJsonObject{};t.handler = [](const QJsonObject&) -> ToolResult {+ // Drop the current chat's link before clearing — clear represents+ // "user wants a fresh report from this chat", so the next mutation+ // re-claims a blank canvas.+ const QString chat_id = fincept::ai_chat::detail::t_chat_session_id;+ if (!chat_id.isEmpty())+ set_linked_report_for(chat_id, QString{});+on_llm_mutation_start();run_on_service_thread([]() { Service::instance().clear_document(); });return ToolResult::ok("Report cleared");@@ -440,15 +498,23 @@ std::vector<ToolDef> get_report_builder_tools() {ToolDef t;t.name = "report_apply_template";t.description =- "Replace the report with a built-in template. Names: 'Blank Report', 'Meeting Notes', 'Investment Memo', "- "'Stock Research', 'Portfolio Review', 'Watchlist Report', 'Dividend Income Report', "- "'Daily Market Brief', 'Trade Journal', 'Technical Analysis', 'Pre-Market Checklist', "- "'Equity Research Report', 'Earnings Review', 'M&A Deal Summary', 'Sector Deep Dive', "- "'Macro Economic Summary', 'Country Risk Report', 'Central Bank Monitor', "- "'Crypto Research Report', 'DeFi Protocol Analysis', 'Crypto Portfolio Review', "- "'Bond Research Report', 'Yield Curve Analysis', 'Quant Strategy Report', "- "'Risk Management Report', 'Business Performance', 'Project Status Report', "- "'Financial Statement'.";+ "Replace the report with a generic built-in scaffold. **PREFER `report_add_component` for "+ "ticker- or topic-specific research** — templates are rigid skeletons designed for user-facing "+ "quick-starts, not for analyst-quality output. Each real research report should have a "+ "ticker-specific structure: a Tesla EV report differs from a JPM credit note differs from a "+ "TLT duration play. When the user asks for research on a specific name/sector, do NOT call "+ "this — call `report_set_metadata` then build the structure with `report_add_component` calls "+ "tailored to what actually matters for that subject. Use this tool only when (a) the user "+ "explicitly asks for a template, or (b) the user wants a generic scaffold (Meeting Notes, "+ "Trade Journal, Pre-Market Checklist) where uniformity is desirable. "+ "Available names: 'Blank Report', 'Meeting Notes', 'Investment Memo', 'Stock Research', "+ "'Portfolio Review', 'Watchlist Report', 'Dividend Income Report', 'Daily Market Brief', "+ "'Trade Journal', 'Technical Analysis', 'Pre-Market Checklist', 'Equity Research Report', "+ "'Earnings Review', 'M&A Deal Summary', 'Sector Deep Dive', 'Macro Economic Summary', "+ "'Country Risk Report', 'Central Bank Monitor', 'Crypto Research Report', "+ "'DeFi Protocol Analysis', 'Crypto Portfolio Review', 'Bond Research Report', "+ "'Yield Curve Analysis', 'Quant Strategy Report', 'Risk Management Report', "+ "'Business Performance', 'Project Status Report', 'Financial Statement'.";t.category = "report-builder";t.input_schema.properties = QJsonObject{{"name", QJsonObject{{"type", "string"}}}};t.input_schema.required = {"name"};@@ -492,6 +558,11 @@ std::vector<ToolDef> get_report_builder_tools() {});if (!err.isEmpty())return ToolResult::fail(err);+ // Promote the chat link from "<unsaved>" to the real path so the+ // next chat session can identify the file even after restart.+ const QString chat_id = fincept::ai_chat::detail::t_chat_session_id;+ if (!chat_id.isEmpty() && !resolved.isEmpty())+ set_linked_report_for(chat_id, resolved);return ToolResult::ok("Saved", QJsonObject{{"path", resolved}});};tools.push_back(std::move(t));@@ -524,6 +595,319 @@ std::vector<ToolDef> get_report_builder_tools() {tools.push_back(std::move(t));}+ // ── report_bulk_add_components ──────────────────────────────────────────+ // Designing a 10-section report previously took ~15 round-trips (one per+ // component). This collapses that into one tool call.+ {+ ToolDef t;+ t.name = "report_bulk_add_components";+ t.description =+ "Append many components in one atomic call. Provide a `components` array of "+ "{type, content?, config?} objects — same shape as report_add_component. Use this when "+ "designing the initial structure of a report so you don't burn one round-trip per section. "+ "All components are appended at the end in order. Returns the assigned ids in order.";+ t.category = "report-builder";+ t.input_schema.properties = QJsonObject{+ {"components",+ QJsonObject{{"type", "array"},+ {"description",+ "Array of {type, content, config} objects. type is required per element; "+ "content and config follow report_add_component semantics."}}},+ };+ t.input_schema.required = {"components"};+ t.handler = [](const QJsonObject& args) -> ToolResult {+ QJsonArray arr = args.value("components").toArray();+ if (arr.isEmpty())+ return ToolResult::fail("Missing or empty 'components' array");++ // Validate up front so we don't partially populate.+ for (int i = 0; i < arr.size(); ++i) {+ QJsonObject c = arr[i].toObject();+ const QString type = c.value("type").toString().trimmed();+ if (type.isEmpty())+ return ToolResult::fail(QString("components[%1]: missing 'type'").arg(i));+ if (!valid_component_type(type))+ return ToolResult::fail(QString("components[%1]: unknown type '%2'").arg(i).arg(type));+ }++ on_llm_mutation_start();++ QJsonArray ids;+ run_on_service_thread([&]() {+ auto& svc = Service::instance();+ svc.begin_macro("Bulk add components");+ for (const auto& v : arr) {+ QJsonObject c = v.toObject();+ rep::ReportComponent comp;+ comp.type = c.value("type").toString();+ comp.content = c.value("content").toString();+ comp.config = json_to_string_map(c.value("config").toObject());+ int id = svc.add_component(comp, -1);+ ids.append(id);+ }+ svc.end_macro();+ });++ return ToolResult::ok(QString("Added %1 components").arg(ids.size()),+ QJsonObject{{"ids", ids}, {"count", ids.size()}});+ };+ tools.push_back(std::move(t));+ }++ // ── report_list_component_types ─────────────────────────────────────────+ // Saves the LLM from calling tool.describe for every type variant.+ {+ ToolDef t;+ t.name = "report_list_component_types";+ t.description =+ "Enumerate every component type the report builder accepts, along with its content "+ "semantics and config keys. Returns: {types:[{name, accepts_content, content_format, "+ "config_keys:[…], example}]}. Call this once if you're unsure which type to use; the "+ "result is small and fully self-describing.";+ t.category = "report-builder";+ t.input_schema.properties = QJsonObject{};+ t.handler = [](const QJsonObject&) -> ToolResult {+ auto entry = [](const char* name, bool accepts_content, const char* fmt,+ QJsonArray keys, const char* example) {+ return QJsonObject{+ {"name", name},+ {"accepts_content", accepts_content},+ {"content_format", fmt},+ {"config_keys", std::move(keys)},+ {"example", example},+ };+ };+ QJsonArray types{+ entry("heading", true, "plain", {},+ "{type:'heading', content:'Investment Thesis'}"),+ entry("text", true, "markdown", {},+ "{type:'text', content:'Revenue grew **22% YoY**.'}"),+ entry("list", true, "markdown (one item per line)", {},+ "{type:'list', content:'EV scale\\nFSD optionality\\nEnergy storage'}"),+ entry("quote", true, "markdown", {},+ "{type:'quote', content:'For internal use only.'}"),+ entry("callout", true, "markdown",+ QJsonArray{"style", "heading"},+ "{type:'callout', content:'Margin compression risk', "+ "config:{style:'warning', heading:'Risk'}}"),+ entry("code", true, "plain", QJsonArray{"language"},+ "{type:'code', content:'SELECT * FROM holdings;'}"),+ entry("divider", false, "(none)", {}, "{type:'divider'}"),+ entry("page_break", false, "(none)", {}, "{type:'page_break'}"),+ entry("toc", false, "(auto-generated from headings)", {}, "{type:'toc'}"),+ entry("table", false, "(via config.csv)", QJsonArray{"csv"},+ "{type:'table', config:{csv:'Metric,FY23,FY24|Revenue,96.8B,97.7B'}}"),+ entry("chart", false, "(via config)",+ QJsonArray{"chart_type", "title", "data", "labels", "width"},+ "{type:'chart', config:{chart_type:'bar', title:'Revenue', "+ "data:'10,20,30', labels:'Q1,Q2,Q3'}}"),+ entry("sparkline", false, "(via config)",+ QJsonArray{"title", "data", "current", "change_pct"},+ "{type:'sparkline', config:{title:'TSLA', data:'10,12,11,15', "+ "current:'15.2', change_pct:'+8.4'}}"),+ entry("stats_block", false, "(via config.data: Label:Value lines)",+ QJsonArray{"title", "data"},+ "{type:'stats_block', config:{title:'Key Stats', "+ "data:'P/E:42.1\\nMkt Cap:$890B'}}"),+ entry("market_data", false, "(via config.symbol)", QJsonArray{"symbol"},+ "{type:'market_data', config:{symbol:'TSLA'}}"),+ entry("image", false, "(via config.path)",+ QJsonArray{"path", "width", "caption", "align"},+ "{type:'image', config:{path:'/abs/path.png', width:'400', "+ "caption:'Fig. 1', align:'center'}}"),+ };+ return ToolResult::ok(QString("%1 component types").arg(types.size()),+ QJsonObject{{"types", types}});+ };+ tools.push_back(std::move(t));+ }++ // ── report_list_templates ───────────────────────────────────────────────+ // Stops the LLM from hallucinating template names.+ {+ ToolDef t;+ t.name = "report_list_templates";+ t.description =+ "Return every built-in template name available to report_apply_template. "+ "REMEMBER: for ticker- or topic-specific research, prefer designing a unique structure "+ "with report_bulk_add_components instead of applying a generic template.";+ t.category = "report-builder";+ t.input_schema.properties = QJsonObject{};+ t.handler = [](const QJsonObject&) -> ToolResult {+ static const QStringList names = {+ "Blank Report",+ "Meeting Notes",+ "Investment Memo",+ "Stock Research",+ "Portfolio Review",+ "Watchlist Report",+ "Dividend Income Report",+ "Daily Market Brief",+ "Trade Journal",+ "Technical Analysis",+ "Pre-Market Checklist",+ "Equity Research Report",+ "Earnings Review",+ "M&A Deal Summary",+ "Sector Deep Dive",+ "Macro Economic Summary",+ "Country Risk Report",+ "Central Bank Monitor",+ "Crypto Research Report",+ "DeFi Protocol Analysis",+ "Crypto Portfolio Review",+ "Bond Research Report",+ "Yield Curve Analysis",+ "Quant Strategy Report",+ "Risk Management Report",+ "Business Performance",+ "Project Status Report",+ "Financial Statement",+ };+ return ToolResult::ok(QString("%1 templates").arg(names.size()),+ QJsonObject{{"templates", QJsonArray::fromStringList(names)}});+ };+ tools.push_back(std::move(t));+ }++ // ── report_export_pdf ───────────────────────────────────────────────────+ {+ ToolDef t;+ t.name = "report_export_pdf";+ t.description =+ "Export the current report to a PDF at the given absolute path. The Report Builder "+ "screen must be loaded (any prior mutation auto-navigates to it, so this normally just "+ "works). Uses A4, with headers/footers if metadata defines them.";+ t.category = "report-builder";+ t.input_schema.properties = QJsonObject{+ {"path", QJsonObject{{"type", "string"},+ {"description", "Absolute output path, e.g. /Users/x/Desktop/TSLA.pdf"}}},+ };+ t.input_schema.required = {"path"};+ t.handler = [](const QJsonObject& args) -> ToolResult {+ QString path = args.value("path").toString().trimmed();+ if (path.isEmpty())+ return ToolResult::fail("Missing 'path'");+ // Make sure the screen exists — nav.switch_screen lazy-constructs it.+ maybe_request_navigation();++ QString err;+ bool dispatched = false;+ QMetaObject::invokeMethod(QCoreApplication::instance(), [&]() {+ auto* scr = ::fincept::screens::ReportBuilderScreen::current();+ if (!scr) {+ err = "Report Builder screen not loaded — navigate to it first";+ return;+ }+ scr->export_pdf_to(path);+ dispatched = true;+ }, Qt::BlockingQueuedConnection);++ if (!err.isEmpty())+ return ToolResult::fail(err);+ if (!dispatched)+ return ToolResult::fail("Failed to dispatch PDF export");+ return ToolResult::ok("Exported PDF to " + path, QJsonObject{{"path", path}});+ };+ tools.push_back(std::move(t));+ }++ // ── report_undo / report_redo ───────────────────────────────────────────+ {+ ToolDef t;+ t.name = "report_undo";+ t.description = "Undo the last report mutation. Each LLM tool-call burst (≤400ms apart) "+ "counts as one undo step; standalone edits each count separately. Returns "+ "{undone:true|false, can_undo, can_redo}.";+ t.category = "report-builder";+ t.input_schema.properties = QJsonObject{};+ t.handler = [](const QJsonObject&) -> ToolResult {+ bool undone = false, can_u = false, can_r = false;+ run_on_service_thread([&]() {+ auto* stk = Service::instance().undo_stack();+ if (stk && stk->canUndo()) {+ stk->undo();+ undone = true;+ }+ can_u = stk && stk->canUndo();+ can_r = stk && stk->canRedo();+ });+ return ToolResult::ok(undone ? "Undid last action" : "Nothing to undo",+ QJsonObject{{"undone", undone}, {"can_undo", can_u},+ {"can_redo", can_r}});+ };+ tools.push_back(std::move(t));+ }+ {+ ToolDef t;+ t.name = "report_redo";+ t.description = "Redo the most recently undone report mutation.";+ t.category = "report-builder";+ t.input_schema.properties = QJsonObject{};+ t.handler = [](const QJsonObject&) -> ToolResult {+ bool redone = false, can_u = false, can_r = false;+ run_on_service_thread([&]() {+ auto* stk = Service::instance().undo_stack();+ if (stk && stk->canRedo()) {+ stk->redo();+ redone = true;+ }+ can_u = stk && stk->canUndo();+ can_r = stk && stk->canRedo();+ });+ return ToolResult::ok(redone ? "Redid last action" : "Nothing to redo",+ QJsonObject{{"redone", redone}, {"can_undo", can_u},+ {"can_redo", can_r}});+ };+ tools.push_back(std::move(t));+ }++ // ── report_session_context ──────────────────────────────────────────────+ // The model MUST call this at the start of any report task to decide+ // whether to clear the canvas and begin fresh, or continue editing the+ // report this chat has already been working on.+ {+ ToolDef t;+ t.name = "report_session_context";+ t.description =+ "Returns the chat→report linkage for the current chat session, plus a snapshot of "+ "what's already on the canvas. **Call this FIRST whenever the user asks you to build, "+ "edit, or work on a report**, then decide:\n"+ "• If `linked_report` is set and `component_count` > 0: this chat is already authoring "+ " this report — continue editing it. Do NOT call report_clear.\n"+ "• If `linked_report` is null and `component_count` > 0: a previous (different) chat "+ " left content on the canvas. Unless the user explicitly said 'add to this report' "+ " or 'edit this report', call report_clear before starting your new report.\n"+ "• If both are empty: blank canvas, just start adding.\n"+ "Returns: {chat_session_id, linked_report, current_file, component_count, title}.";+ t.category = "report-builder";+ t.input_schema.properties = QJsonObject{};+ t.handler = [](const QJsonObject&) -> ToolResult {+ const QString chat_id = fincept::ai_chat::detail::t_chat_session_id;+ const QString linked = get_linked_report_for(chat_id);+ auto& svc = Service::instance();+ int n = static_cast<int>(svc.components().size());+ QString cur = svc.current_file();+ QString title = svc.metadata().title;+ QJsonObject data{+ {"chat_session_id", chat_id.isEmpty() ? QJsonValue::Null : QJsonValue(chat_id)},+ {"linked_report", linked.isEmpty() ? QJsonValue::Null : QJsonValue(linked)},+ {"current_file", cur.isEmpty() ? QJsonValue::Null : QJsonValue(cur)},+ {"component_count", n},+ {"title", title.isEmpty() ? QJsonValue::Null : QJsonValue(title)},+ };+ QString msg = chat_id.isEmpty()+ ? QStringLiteral("No chat session bound; canvas has %1 components").arg(n)+ : (linked.isEmpty()+ ? QStringLiteral("New chat — canvas has %1 components from a prior session").arg(n)+ : QStringLiteral("Chat is editing %1 (canvas has %2 components)")+ .arg(linked == QLatin1String("<unsaved>") ? QStringLiteral("an unsaved report") : linked)+ .arg(n));+ return ToolResult::ok(msg, data);+ };+ tools.push_back(std::move(t));+ }+LOG_INFO(RB_TOOLS_TAG, QString("Built %1 report builder tools").arg(tools.size()));return tools;}diff --git a/fincept-qt/src/mcp/tools/SystemTools.cpp b/fincept-qt/src/mcp/tools/SystemTools.cppindex f44bd30fd..fdd527766 100644--- a/fincept-qt/src/mcp/tools/SystemTools.cpp+++ b/fincept-qt/src/mcp/tools/SystemTools.cpp@@ -61,6 +61,7 @@ std::vector<ToolDef> get_system_tools() {t.name = "clear_cache";t.description = "Clear all cache entries.";t.category = "system";+ t.is_destructive = true; // mutation tool — penalise on read-style queriest.handler = [](const QJsonObject&) -> ToolResult {CacheManager::instance().clear();return ToolResult::ok("Cache cleared");diff --git a/fincept-qt/src/mcp/tools/WatchlistTools.cpp b/fincept-qt/src/mcp/tools/WatchlistTools.cppindex f2d02b1c7..6f48ff056 100644--- a/fincept-qt/src/mcp/tools/WatchlistTools.cpp+++ b/fincept-qt/src/mcp/tools/WatchlistTools.cpp@@ -110,6 +110,7 @@ std::vector<ToolDef> get_watchlist_tools() {t.name = "delete_watchlist";t.description = "Delete a watchlist by ID.";t.category = "watchlist";+ t.is_destructive = true; // mutation tool — penalise on read-style queriest.input_schema.properties =QJsonObject{{"watchlist_id", QJsonObject{{"type", "string"}, {"description", "Watchlist ID"}}}};t.input_schema.required = {"watchlist_id"};@@ -210,6 +211,7 @@ std::vector<ToolDef> get_watchlist_tools() {t.name = "remove_from_watchlist";t.description = "Remove a symbol from a watchlist.";t.category = "watchlist";+ t.is_destructive = true; // mutation tool — penalise on read-style queriest.input_schema.properties = QJsonObject{{"symbol", QJsonObject{{"type", "string"}, {"description", "Ticker symbol to remove"}}},{"watchlist_id", QJsonObject{{"type", "string"},diff --git a/fincept-qt/src/python/PythonRunner.cpp b/fincept-qt/src/python/PythonRunner.cppindex 79c0ae96c..0d8d96a29 100644--- a/fincept-qt/src/python/PythonRunner.cpp+++ b/fincept-qt/src/python/PythonRunner.cpp@@ -2,6 +2,7 @@#include "core/logging/Logger.h"#include "python/PythonSetupManager.h"+#include "python/PythonWorker.h"#include "storage/secure/SecureStorage.h"#include <QCoreApplication>@@ -10,6 +11,9 @@#include <QFile>#include <QFileInfo>#include <QHash>+#include <QJsonArray>+#include <QJsonDocument>+#include <QJsonObject>#include <QLatin1String>#include <QProcessEnvironment>#include <QStandardPaths>@@ -18,6 +22,98 @@namespace fincept::python {+// ── yfinance_data.py CLI → daemon dispatch translation ───────────────────────+// Returns true if the CLI args were recognised and routed to the persistent+// PythonWorker daemon, avoiding the ~3s subprocess + yfinance/pandas import+// cost. Unrecognised actions return false so the caller falls through to the+// subprocess path (preserves correctness for future actions added to the CLI+// but not yet wired into the daemon dispatch table).+//+// Action names match scripts/yfinance_data.py::_daemon_dispatch.+static bool route_yfinance_to_daemon(const QStringList& args,+ std::function<void(PythonResult)> cb) {+ if (args.isEmpty())+ return false;+ const QString action = args[0];+ QJsonObject payload;++ auto sym = [&](int i) -> QString { return i < args.size() ? args[i] : QString(); };+ auto split_csv = [](const QString& s) {+ QJsonArray a;+ for (const QString& x : s.split(',', Qt::SkipEmptyParts))+ a.append(x.trimmed());+ return a;+ };++ if (action == "quote" || action == "info" || action == "financials" ||+ action == "company_profile" || action == "financial_ratios") {+ if (args.size() < 2)+ return false;+ payload["symbol"] = sym(1);+ } else if (action == "news") {+ if (args.size() < 2)+ return false;+ payload["symbol"] = sym(1);+ payload["count"] = args.size() > 2 ? args[2].toInt() : 20;+ } else if (action == "search") {+ if (args.size() < 2)+ return false;+ payload["query"] = sym(1);+ payload["limit"] = args.size() > 2 ? args[2].toInt() : 50;+ } else if (action == "historical_period") {+ if (args.size() < 2)+ return false;+ payload["symbol"] = sym(1);+ payload["period"] = args.size() > 2 ? args[2] : QStringLiteral("6mo");+ payload["interval"] = args.size() > 3 ? args[3] : QStringLiteral("1d");+ } else if (action == "historical") {+ if (args.size() < 4)+ return false;+ payload["symbol"] = sym(1);+ payload["start_date"] = sym(2);+ payload["end_date"] = sym(3);+ payload["interval"] = args.size() > 4 ? args[4] : QStringLiteral("1d");+ } else if (action == "multiple_ratios" || action == "multiple_profiles") {+ if (args.size() < 2)+ return false;+ payload["symbols"] = split_csv(args[1]);+ } else if (action == "batch_quotes" || action == "batch_sparklines") {+ if (args.size() < 2)+ return false;+ QJsonArray syms;+ for (int i = 1; i < args.size(); ++i)+ syms.append(args[i]);+ payload["symbols"] = syms;+ } else if (action == "batch_all") {+ // batch_all carries a JSON blob (or @file spill). Skip routing for @file+ // — daemon would need separate file-read support. Parse inline JSON.+ if (args.size() < 2 || args[1].startsWith('@'))+ return false;+ auto doc = QJsonDocument::fromJson(args[1].toUtf8());+ if (!doc.isObject())+ return false;+ payload = doc.object();+ } else {+ return false; // unknown action — let subprocess path handle it+ }++ PythonWorker::instance().submit(action, payload,+ [cb = std::move(cb), action](bool ok, QJsonObject result, QString error) {+ // Daemon may legitimately not know an action; fail cleanly so caller+ // sees a structured error instead of a silent hang.+ if (!ok) {+ cb({false, {}, error.isEmpty() ? ("daemon error for " + action) : error, -1});+ return;+ }+ PythonResult r;+ r.success = true;+ r.output = QString::fromUtf8(QJsonDocument(result).toJson(QJsonDocument::Compact));+ r.exit_code = 0;+ cb(r);+ });+ return true;+}+// ── Credential catalogue ─────────────────────────────────────────────────────// Env-var names that SettingsScreen lets the user configure and store in// SecureStorage (see SettingsScreen.cpp CRED_KEYS). build_python_env() pulls@@ -311,6 +407,17 @@ void PythonRunner::run(const QString& script, const QStringList& args, Callbackreturn;}+ // Daemon fast-path: yfinance_data.py runs as a long-lived worker+ // (PythonWorker). Routing single-shot calls through the daemon avoids the+ // ~3s subprocess + import cost and bypasses the max_concurrent_=3 queue+ // bottleneck. Only used when no stream callback is requested — the daemon+ // doesn't surface intermediate stdout lines. Falls through to subprocess+ // if the action isn't supported by the daemon dispatcher.+ if (!on_line && script == QLatin1String("yfinance_data.py")) {+ if (route_yfinance_to_daemon(args, cb))+ return;+ }+// Queue the request and start if under concurrency limitqueue_.enqueue({script, args, std::move(cb), std::move(on_line)});start_next();diff --git a/fincept-qt/src/python/PythonWorker.cpp b/fincept-qt/src/python/PythonWorker.cppindex 2c0299ac9..46fffb4cd 100644--- a/fincept-qt/src/python/PythonWorker.cpp+++ b/fincept-qt/src/python/PythonWorker.cpp@@ -53,6 +53,18 @@ PythonWorker::~PythonWorker() {}void PythonWorker::submit(const QString& action, const QJsonObject& payload, Callback cb) {+ // QProcess and our in_flight_/queue_ containers are owned by this+ // worker's thread (main thread in practice). MCP tool handlers call+ // submit() from QtConcurrent worker threads — touching proc_->write()+ // from there triggers `QSocketNotifier: cannot be enabled or disabled+ // from another thread` and the daemon stalls. Marshal back if needed.+ if (QThread::currentThread() != this->thread()) {+ QMetaObject::invokeMethod(this, [this, action, payload, cb = std::move(cb)]() mutable {+ submit(action, payload, std::move(cb));+ }, Qt::QueuedConnection);+ return;+ }+ensure_started();const int id = next_id_++;diff --git a/fincept-qt/src/screens/ai_chat/AiChatScreen.h b/fincept-qt/src/screens/ai_chat/AiChatScreen.hindex d1b803f7c..0e5bcb06f 100644--- a/fincept-qt/src/screens/ai_chat/AiChatScreen.h+++ b/fincept-qt/src/screens/ai_chat/AiChatScreen.h@@ -118,6 +118,7 @@ class AiChatScreen : public QWidget, public IStatefulScreen, public fincept::IGrmutable QMutex history_mutex_;std::vector<ai_chat::ConversationMessage> history_;bool streaming_ = false;+ bool scroll_pending_ = false;QPointer<QLabel> streaming_bubble_;int total_tokens_ = 0;int total_messages_ = 0;diff --git a/fincept-qt/src/screens/ai_chat/AiChatScreen_Messaging.cpp b/fincept-qt/src/screens/ai_chat/AiChatScreen_Messaging.cppindex bd6e2abec..b4a9fbae2 100644--- a/fincept-qt/src/screens/ai_chat/AiChatScreen_Messaging.cpp+++ b/fincept-qt/src/screens/ai_chat/AiChatScreen_Messaging.cpp@@ -170,7 +170,9 @@ void AiChatScreen::on_send() {self->on_stream_chunk(chunk, done);},Qt::QueuedConnection);- });+ },+ ai_chat::LlmService::ToolPolicy::All,+ active_session_id_);} else {QPointer<AiChatScreen> self = this;(void)QtConcurrent::run([self, text, hist_copy]() {@@ -312,7 +314,14 @@ void AiChatScreen::clear_messages() {}void AiChatScreen::scroll_to_bottom() {- QTimer::singleShot(50, this, [this]() {+ // Debounce: a single scroll lands at the end of the current event-loop batch.+ // Without this, a 100-chunk stream queued 100 independent 50ms timers, each+ // racing to setValue() and starving paint events.+ if (scroll_pending_)+ return;+ scroll_pending_ = true;+ QTimer::singleShot(0, this, [this]() {+ scroll_pending_ = false;if (scroll_area_ && scroll_area_->verticalScrollBar())scroll_area_->verticalScrollBar()->setValue(scroll_area_->verticalScrollBar()->maximum());});diff --git a/fincept-qt/src/screens/report_builder/DocumentCanvas.cpp b/fincept-qt/src/screens/report_builder/DocumentCanvas.cppindex 003520f27..4c58118f7 100644--- a/fincept-qt/src/screens/report_builder/DocumentCanvas.cpp+++ b/fincept-qt/src/screens/report_builder/DocumentCanvas.cpp@@ -474,19 +474,27 @@ void DocumentCanvas::render(const QVector<ReportComponent>& components, const Re} else if (comp.type == "table") {// Cell data sources, in priority order:- // 1. config["csv"] — pipe-separated rows, comma-separated cells:- // "Metric,FY22,FY23|Revenue,81462,96773|Net Income,12556,14997"- // This is the LLM-friendly format the MCP tool description- // recommends.+ // 1. config["csv"] — rows separated by `|` OR newline (LLMs+ // instinctively use newlines for CSV rows, so we accept+ // both). Cells separated by comma. The MCP tool description+ // recommends pipe; the parser is lenient.// 2. config["data"] — JSON map {"r_c":"value"} (legacy).// 3. fallback to "Header N" placeholders so the table at least// shows where data should go rather than empty cells.QVector<QStringList> rows_data;QString csv = comp.config.value("csv");if (!csv.isEmpty()) {- for (const QString& row_str : csv.split('|', Qt::SkipEmptyParts)) {+ // Normalise row separators: \r\n / \r / \n / | all mean "new row".+ QString normalised = csv;+ normalised.replace(QLatin1String("\r\n"), QLatin1String("|"));+ normalised.replace('\r', '|');+ normalised.replace('\n', '|');+ for (const QString& row_str : normalised.split('|', Qt::SkipEmptyParts)) {+ const QString trimmed_row = row_str.trimmed();+ if (trimmed_row.isEmpty())+ continue;QStringList row;- for (const QString& cell : row_str.split(',')) // keep empty cells+ for (const QString& cell : trimmed_row.split(',')) // keep empty cellsrow << cell.trimmed();rows_data.append(row);}diff --git a/fincept-qt/src/screens/report_builder/ReportBuilderScreen.cpp b/fincept-qt/src/screens/report_builder/ReportBuilderScreen.cppindex 576f4d571..1fa900264 100644--- a/fincept-qt/src/screens/report_builder/ReportBuilderScreen.cpp+++ b/fincept-qt/src/screens/report_builder/ReportBuilderScreen.cpp@@ -50,7 +50,17 @@ namespace fincept::screens {namespace rep = ::fincept::report;using Service = ::fincept::services::ReportBuilderService;+// Tracks the most recently constructed Report Builder screen so MCP tools+// can find a live instance without walking the widget tree. Cleared in the+// destructor. QPointer auto-nulls if Qt deletes the widget another way.+static QPointer<ReportBuilderScreen> s_current_screen;++ReportBuilderScreen* ReportBuilderScreen::current() {+ return s_current_screen.data();+}+ReportBuilderScreen::ReportBuilderScreen(QWidget* parent) : QWidget(parent) {+ s_current_screen = this;setStyleSheet(QString("background: %1;").arg(ui::colors::DARK()));auto* vl = new QVBoxLayout(this);@@ -366,7 +376,10 @@ ReportBuilderScreen::ReportBuilderScreen(QWidget* parent) : QWidget(parent) {rebind_from_service();}-ReportBuilderScreen::~ReportBuilderScreen() = default;+ReportBuilderScreen::~ReportBuilderScreen() {+ if (s_current_screen == this)+ s_current_screen.clear();+}// ── Top toolbar ──────────────────────────────────────────────────────────────diff --git a/fincept-qt/src/screens/report_builder/ReportBuilderScreen.h b/fincept-qt/src/screens/report_builder/ReportBuilderScreen.hindex ea5a63892..54fbbae48 100644--- a/fincept-qt/src/screens/report_builder/ReportBuilderScreen.h+++ b/fincept-qt/src/screens/report_builder/ReportBuilderScreen.h@@ -105,6 +105,17 @@ class ReportBuilderScreen : public QWidget, public IStatefulScreen {void on_export_pdf();void on_preview();+ public slots:+ /// MCP-invocable PDF export: skips the file dialog and writes directly to+ /// the given absolute path. Exposed for the `report_export_pdf` tool.+ void export_pdf_to(const QString& path);++ public:+ /// Returns the currently-constructed Report Builder screen (or nullptr if+ /// none). Used by MCP tools that need to invoke screen-owned operations+ /// (PDF export, preview, etc.) without going through the user-facing UI.+ static ReportBuilderScreen* current();+protected:void showEvent(QShowEvent* e) override;void hideEvent(QHideEvent* e) override;diff --git a/fincept-qt/src/screens/report_builder/ReportBuilderScreen_Dialogs.cpp b/fincept-qt/src/screens/report_builder/ReportBuilderScreen_Dialogs.cppindex 4d65133d7..dfd6cd359 100644--- a/fincept-qt/src/screens/report_builder/ReportBuilderScreen_Dialogs.cpp+++ b/fincept-qt/src/screens/report_builder/ReportBuilderScreen_Dialogs.cpp@@ -445,6 +445,14 @@ void ReportBuilderScreen::on_export_pdf() {QString path = QFileDialog::getSaveFileName(this, "Export PDF", m.title, "PDF (*.pdf)");if (path.isEmpty())return;+ export_pdf_to(path);+ QMessageBox::information(this, "Export PDF", "Report exported successfully to:\n" + path);+}++void ReportBuilderScreen::export_pdf_to(const QString& path) {+ if (path.isEmpty())+ return;+ auto m = Service::instance().metadata();QPrinter printer(QPrinter::HighResolution);printer.setOutputFormat(QPrinter::PdfFormat);@@ -531,7 +539,6 @@ void ReportBuilderScreen::on_export_pdf() {doc->deleteLater();}- QMessageBox::information(this, "Export PDF", "Report exported successfully to:\n" + path);services::FileManagerService::instance().import_file(path, "report_builder");}diff --git a/fincept-qt/src/services/equity/EquityResearchService.cpp b/fincept-qt/src/services/equity/EquityResearchService.cppindex 038f7d6b4..b7253d261 100644--- a/fincept-qt/src/services/equity/EquityResearchService.cpp+++ b/fincept-qt/src/services/equity/EquityResearchService.cpp@@ -73,77 +73,87 @@ void EquityResearchService::search_symbols(const QString& query) {}// ── Load symbol (quote + info + historical in parallel) ───────────────────────-void EquityResearchService::load_symbol(const QString& symbol, const QString& period) {+void EquityResearchService::load_quote_only(const QString& symbol) {if (symbol.isEmpty())return;-- // ── Quote ────────────────────────────────────────────────────────────────- {- const QVariant qcv = fincept::CacheManager::instance().get("equity:quote:" + symbol);- if (!qcv.isNull()) {- emit quote_loaded(parse_quote(QJsonDocument::fromJson(qcv.toString().toUtf8()).object()));- } else {- run_python("yfinance_data.py", {"quote", symbol}, [this, symbol](bool ok, const QString& out) {- if (!ok) {- emit error_occurred("Quote", "Failed to fetch quote for " + symbol);- return;- }- auto obj = QJsonDocument::fromJson(python::extract_json(out).toUtf8()).object();- if (obj.contains("error"))- return;- fincept::CacheManager::instance().put(- "equity:quote:" + symbol,- QVariant(QString::fromUtf8(QJsonDocument(obj).toJson(QJsonDocument::Compact))), kQuoteTtlSec,- "equity");- emit quote_loaded(parse_quote(obj));- });- }+ const QVariant qcv = fincept::CacheManager::instance().get("equity:quote:" + symbol);+ if (!qcv.isNull()) {+ emit quote_loaded(parse_quote(QJsonDocument::fromJson(qcv.toString().toUtf8()).object()));+ return;}-- // ── Info ─────────────────────────────────────────────────────────────────- {- const QVariant icv = fincept::CacheManager::instance().get("equity:info:" + symbol);- if (!icv.isNull()) {- emit info_loaded(parse_info(QJsonDocument::fromJson(icv.toString().toUtf8()).object()));- } else {- run_python("yfinance_data.py", {"info", symbol}, [this, symbol](bool ok, const QString& out) {- if (!ok) {- emit error_occurred("Info", "Failed to fetch info for " + symbol);- return;- }- auto obj = QJsonDocument::fromJson(python::extract_json(out).toUtf8()).object();- if (obj.contains("error"))- return;- fincept::CacheManager::instance().put(- "equity:info:" + symbol,- QVariant(QString::fromUtf8(QJsonDocument(obj).toJson(QJsonDocument::Compact))), kInfoTtlSec,- "equity");- emit info_loaded(parse_info(obj));- });+ run_python("yfinance_data.py", {"quote", symbol}, [this, symbol](bool ok, const QString& out) {+ if (!ok) {+ emit error_occurred("Quote", "Failed to fetch quote for " + symbol);+ return;}- }+ auto obj = QJsonDocument::fromJson(python::extract_json(out).toUtf8()).object();+ if (obj.contains("error")) {+ emit error_occurred("Quote", obj["error"].toString());+ return;+ }+ fincept::CacheManager::instance().put(+ "equity:quote:" + symbol,+ QVariant(QString::fromUtf8(QJsonDocument(obj).toJson(QJsonDocument::Compact))), kQuoteTtlSec,+ "equity");+ emit quote_loaded(parse_quote(obj));+ });+}- // ── Historical ───────────────────────────────────────────────────────────- {- const QVariant hcv = fincept::CacheManager::instance().get("equity:candles:" + symbol);- if (!hcv.isNull()) {- emit historical_loaded(symbol, parse_candles(QJsonDocument::fromJson(hcv.toString().toUtf8()).array()));- } else {- run_python("yfinance_data.py", {"historical_period", symbol, period, "1d"},- [this, symbol](bool ok, const QString& out) {- if (!ok) {- emit error_occurred("Historical", "Failed to fetch historical for " + symbol);- return;- }- auto arr = QJsonDocument::fromJson(python::extract_json(out).toUtf8()).array();- fincept::CacheManager::instance().put(- "equity:candles:" + symbol,- QVariant(QString::fromUtf8(QJsonDocument(arr).toJson(QJsonDocument::Compact))),- kHistoricalTtlSec, "equity");- emit historical_loaded(symbol, parse_candles(arr));- });+void EquityResearchService::load_info_only(const QString& symbol) {+ if (symbol.isEmpty())+ return;+ const QVariant icv = fincept::CacheManager::instance().get("equity:info:" + symbol);+ if (!icv.isNull()) {+ emit info_loaded(parse_info(QJsonDocument::fromJson(icv.toString().toUtf8()).object()));+ return;+ }+ run_python("yfinance_data.py", {"info", symbol}, [this, symbol](bool ok, const QString& out) {+ if (!ok) {+ emit error_occurred("Info", "Failed to fetch info for " + symbol);+ return;+ }+ auto obj = QJsonDocument::fromJson(python::extract_json(out).toUtf8()).object();+ if (obj.contains("error")) {+ emit error_occurred("Info", obj["error"].toString());+ return;}+ fincept::CacheManager::instance().put(+ "equity:info:" + symbol,+ QVariant(QString::fromUtf8(QJsonDocument(obj).toJson(QJsonDocument::Compact))), kInfoTtlSec,+ "equity");+ emit info_loaded(parse_info(obj));+ });+}++void EquityResearchService::load_historical_only(const QString& symbol, const QString& period) {+ if (symbol.isEmpty())+ return;+ const QVariant hcv = fincept::CacheManager::instance().get("equity:candles:" + symbol);+ if (!hcv.isNull()) {+ emit historical_loaded(symbol, parse_candles(QJsonDocument::fromJson(hcv.toString().toUtf8()).array()));+ return;}+ run_python("yfinance_data.py", {"historical_period", symbol, period, "1d"},+ [this, symbol](bool ok, const QString& out) {+ if (!ok) {+ emit error_occurred("Historical", "Failed to fetch historical for " + symbol);+ return;+ }+ auto arr = QJsonDocument::fromJson(python::extract_json(out).toUtf8()).array();+ fincept::CacheManager::instance().put(+ "equity:candles:" + symbol,+ QVariant(QString::fromUtf8(QJsonDocument(arr).toJson(QJsonDocument::Compact))),+ kHistoricalTtlSec, "equity");+ emit historical_loaded(symbol, parse_candles(arr));+ });+}++void EquityResearchService::load_symbol(const QString& symbol, const QString& period) {+ if (symbol.isEmpty())+ return;+ load_quote_only(symbol);+ load_info_only(symbol);+ load_historical_only(symbol, period);}// ── Financials ────────────────────────────────────────────────────────────────diff --git a/fincept-qt/src/services/equity/EquityResearchService.h b/fincept-qt/src/services/equity/EquityResearchService.hindex c46390447..95a2b8144 100644--- a/fincept-qt/src/services/equity/EquityResearchService.h+++ b/fincept-qt/src/services/equity/EquityResearchService.h@@ -18,9 +18,18 @@ class EquityResearchService : public QObject {void search_symbols(const QString& query);void schedule_search(const QString& query); // debounced entry point- /// Fetches quote + info + historical in parallel (three Python calls)+ /// Fetches quote + info + historical in parallel (three Python calls).+ /// Used by the UI panels that need all three. Tool handlers that only+ /// need one slice should use the per-data loaders below to avoid wasting+ /// daemon slots and Yahoo API calls.void load_symbol(const QString& symbol, const QString& period = "1y");+ /// Per-data loaders. Each fires exactly one Python call and emits the+ /// matching *_loaded signal. Cache-aware: re-emits immediately on hit.+ void load_quote_only(const QString& symbol);+ void load_info_only(const QString& symbol);+ void load_historical_only(const QString& symbol, const QString& period = "1y");+void fetch_financials(const QString& symbol);void fetch_technicals(const QString& symbol, const QString& period = "1y");void fetch_peers(const QString& symbol, const QStringList& peer_symbols);diff --git a/fincept-qt/src/services/llm/LlmContentExtractors.h b/fincept-qt/src/services/llm/LlmContentExtractors.hindex 4a5e4a443..9ec7fa8bb 100644--- a/fincept-qt/src/services/llm/LlmContentExtractors.h+++ b/fincept-qt/src/services/llm/LlmContentExtractors.h@@ -18,6 +18,13 @@ namespace fincept::ai_chat {/// can rely on `isEmpty()` meaning "no reply".QString extract_openai_message_text(const QJsonObject& msg);+/// Remove any <think>…</think> chain-of-thought blocks from a non-streamed+/// response. Used by tool-loop final synthesis and Gemini/Fincept fallbacks+/// where the entire reply arrives as one body — the streaming path has its+/// own incremental filter (do_streaming_request::filter_think) because tags+/// can straddle SSE chunk boundaries.+QString strip_think_blocks(QString content);+/// Extract user-visible text from an Anthropic /v1/messages content-blocks/// array. Concatenates multiple `text` blocks (Claude can emit several when a/// tool_use block sits between them) and falls back to `thinking` blocks onlydiff --git a/fincept-qt/src/services/llm/LlmHttpHelpers.cpp b/fincept-qt/src/services/llm/LlmHttpHelpers.cppindex 2bc62b1e5..6954b074e 100644--- a/fincept-qt/src/services/llm/LlmHttpHelpers.cpp+++ b/fincept-qt/src/services/llm/LlmHttpHelpers.cpp@@ -119,6 +119,25 @@ LlmService::HttpResult LlmService::eventloop_request(const QString& method, consreturn result;}+// ── <think> reasoning stripping ────────────────────────────────────────────+// Reasoning models (MiniMax M2.7, DeepSeek-R1, …) embed chain-of-thought in+// <think>…</think> blocks inside the visible content. Strip those so the chat+// bubble only shows the answer. Streaming uses a stateful filter inline in+// do_streaming_request; this helper is for non-streamed bodies (tool-loop+// final synthesis, Gemini/Fincept fallback).+QString strip_think_blocks(QString content) {+ static const QRegularExpression rx(+ QStringLiteral("<\\s*think\\s*>[\\s\\S]*?<\\s*/\\s*think\\s*>"),+ QRegularExpression::CaseInsensitiveOption);+ content.remove(rx);+ // Drop a dangling unmatched <think>…(no closing) — emit nothing past it.+ static const QRegularExpression rx_open(+ QStringLiteral("<\\s*think\\s*>[\\s\\S]*$"),+ QRegularExpression::CaseInsensitiveOption);+ content.remove(rx_open);+ return content.trimmed();+}+// ── SSE chunk → text ───────────────────────────────────────────────────────QString LlmService::parse_sse_chunk(const QString& data, const QString& provider) {auto doc = QJsonDocument::fromJson(data.toUtf8());diff --git a/fincept-qt/src/services/llm/LlmRequestPolicy.h b/fincept-qt/src/services/llm/LlmRequestPolicy.hindex 1a6a507c1..fc1aae7af 100644--- a/fincept-qt/src/services/llm/LlmRequestPolicy.h+++ b/fincept-qt/src/services/llm/LlmRequestPolicy.h@@ -20,11 +20,50 @@#include "mcp/McpTypes.h"#include <QString>+#include <functional>namespace fincept::ai_chat::detail {inline thread_local LlmService::ToolPolicy t_request_policy = LlmService::ToolPolicy::All;+// Optional progress emitter — when set, the tool loop pushes per-round status+// ("Using tool X...") through this so the chat bubble paints in real-time+// during the otherwise-silent multi-second tool execution phase. Set by+// do_streaming_request before falling back into the tool loop, cleared on exit.+using ProgressEmitter = std::function<void(const QString&)>;+inline thread_local ProgressEmitter t_progress_emitter;++struct ProgressEmitterGuard {+ ProgressEmitter prev;+ explicit ProgressEmitterGuard(ProgressEmitter p) : prev(std::move(t_progress_emitter)) {+ t_progress_emitter = std::move(p);+ }+ ~ProgressEmitterGuard() { t_progress_emitter = std::move(prev); }+ ProgressEmitterGuard(const ProgressEmitterGuard&) = delete;+ ProgressEmitterGuard& operator=(const ProgressEmitterGuard&) = delete;+};++inline void emit_progress(const QString& text) {+ if (t_progress_emitter)+ t_progress_emitter(text);+}++// Active chat session id for the in-flight LLM request. Set by the chat screen+// before calling chat_streaming(), read by MCP tools (e.g. report_session_context)+// to scope per-chat state — for example, "did this chat session already start a+// report?" so the model knows whether to continue or start fresh.+inline thread_local QString t_chat_session_id;++struct ChatSessionGuard {+ QString prev;+ explicit ChatSessionGuard(QString id) : prev(std::move(t_chat_session_id)) {+ t_chat_session_id = std::move(id);+ }+ ~ChatSessionGuard() { t_chat_session_id = std::move(prev); }+ ChatSessionGuard(const ChatSessionGuard&) = delete;+ ChatSessionGuard& operator=(const ChatSessionGuard&) = delete;+};+struct ToolPolicyGuard {LlmService::ToolPolicy prev;explicit ToolPolicyGuard(LlmService::ToolPolicy p) : prev(t_request_policy) { t_request_policy = p; }diff --git a/fincept-qt/src/services/llm/LlmService.cpp b/fincept-qt/src/services/llm/LlmService.cppindex d4e262c92..555a3fb51 100644--- a/fincept-qt/src/services/llm/LlmService.cpp+++ b/fincept-qt/src/services/llm/LlmService.cpp@@ -144,12 +144,29 @@ void LlmService::ensure_config() const {" exists for. Never tell the user you cannot navigate or open screens.\n""• Building a report (e.g. 'create an equity research report on TSLA'): your job is to "" WRITE THE REPORT INTO THE REPORT BUILDER USING TOOLS. Do not narrate the report into "- " the chat. The flow is: (1) optionally call report_apply_template with the closest match "- " for context, (2) call report_get_state to learn the current component ids, (3) gather "- " data with tools like get_quote, edgar_get_financials, edgar_10k_sections, "- " edgar_calc_multiples, get_news, search_news, (4) populate the report by calling "- " report_update_component or report_add_component for each section. Use stable component "- " ids returned by report_get_state / report_add_component — never indices.\n"+ " the chat. STEP 0 (mandatory): call report_session_context to see whether this chat "+ " is already authoring a report (linked_report set) or is starting fresh (linked_report "+ " null with stale components on the canvas). If linked, CONTINUE editing it. If unlinked "+ " and the canvas has components, call report_clear first UNLESS the user explicitly "+ " said 'edit this report' / 'add to this report' / 'continue the report' — in which "+ " case keep the canvas. The flow is: (1) DESIGN A UNIQUE STRUCTURE for the subject — every ticker, "+ " sector, or topic deserves its own outline. A Tesla EV-and-FSD memo, a JPM credit note, "+ " and a TLT duration play should NOT share the same skeleton. Decide which sections "+ " actually matter for THIS subject (could be Catalysts, Bear Case, Capital Structure, "+ " Unit Economics, Regulatory Overhang, Insider Activity, Optionality, etc.) — do NOT "+ " default to the generic Company Overview / Financials / Valuation / Thesis / Risks / "+ " Target template. Do NOT call report_apply_template unless the user explicitly asks "+ " for a template OR the request is for a generic non-research scaffold (Meeting Notes, "+ " Trade Journal, Pre-Market Checklist). (2) call report_set_metadata with a "+ " subject-specific title (e.g. 'Tesla: Margin Compression vs FSD Optionality' — not "+ " 'Stock Research'), author, company, date. (3) build the structure by calling "+ " report_add_component for each section you designed in step 1. (4) gather data with "+ " tools like get_equity_info, get_equity_quote, edgar_get_financials, "+ " edgar_10k_sections, edgar_calc_multiples, get_equity_news, search_news. "+ " (5) populate each section by calling report_update_component with the gathered data. "+ " Use stable component ids returned by report_add_component — never indices. "+ " COVERAGE: before declaring the report done, verify every section you added has "+ " real content (no placeholders like 'Describe the company…').\n""• Report formatting (CRITICAL for a polished result):\n"" - text/list/quote/callout content SUPPORTS MARKDOWN. Use **bold** to highlight key "" figures (e.g. 'Revenue grew **22% YoY** to **$96.8B**'). Use *italic* sparingly. "@@ -320,9 +337,17 @@ QString LlmService::get_endpoint_url() const {QString base = base_url_;if (base.endsWith('/'))base.chop(1);- if (p == "anthropic")- return base + "/v1/messages";- return base + "/v1/chat/completions";+ const QString suffix = (p == "anthropic") ? QStringLiteral("/messages")+ : QStringLiteral("/chat/completions");+ // If the base already includes the full endpoint, use it as-is.+ if (base.endsWith(suffix))+ return base;+ // If the base already includes an API version segment (e.g. ".../v1"),+ // append only the suffix; otherwise add "/v1" first.+ static const QRegularExpression versioned(QStringLiteral("/v\\d+(beta)?$"));+ if (versioned.match(base).hasMatch())+ return base + suffix;+ return base + "/v1" + suffix;}if (p == "openai")@@ -646,7 +671,7 @@ LlmResponse LlmService::do_request(const QString& user_message, const std::vecto} else {// Helper handles reasoning models, content-as-parts arrays, and refusal messages.- resp.content = extract_openai_message_text(msg);+ resp.content = strip_think_blocks(extract_openai_message_text(msg));}}}@@ -673,9 +698,10 @@ LlmResponse LlmService::do_request(const QString& user_message, const std::vectoLlmResponse LlmService::do_streaming_request(const QString& user_message,const std::vector<ConversationMessage>& history, StreamCallback on_chunk) {- // Streaming disabled globally — falls back to do_request so the tool-call/follow-up loop runs.- // Re-enable per-provider once each backend has SSE tool-call handling.- {+ // Gemini uses :streamGenerateContent, Fincept uses async submit/poll — neither+ // fits this OpenAI-compat SSE path. Fall back to do_request and emit as one chunk.+ if (provider_ == "gemini" || provider_ == "google" || provider_ == "fincept") {+ detail::ProgressEmitterGuard pg([on_chunk](const QString& s) { on_chunk(s, false); });auto resp = do_request(user_message, history);if (resp.success && !resp.content.isEmpty())on_chunk(resp.content, false);@@ -704,6 +730,11 @@ LlmResponse LlmService::do_streaming_request(const QString& user_message,QNetworkRequest req{QUrl(url)};req.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");req.setRawHeader("Accept", "text/event-stream");+ req.setRawHeader("Cache-Control", "no-cache");+ // Per Qt 6 network docs: HTTP/2 is enabled by default and batches frames,+ // which causes SSE chunks to arrive in bursts instead of as the server+ // flushes them. Force HTTP/1.1 so readyRead fires per TCP packet.+ req.setAttribute(QNetworkRequest::Http2AllowedAttribute, false);for (auto it = hdr.constBegin(); it != hdr.constEnd(); ++it)req.setRawHeader(it.key().toUtf8(), it.value().toUtf8());@@ -716,6 +747,48 @@ LlmResponse LlmService::do_streaming_request(const QString& user_message,bool done = false;bool tool_call_detected = false;+ // <think>…</think> reasoning filter. Reasoning models (MiniMax M2.7,+ // DeepSeek-R1 derivatives, …) stream their chain-of-thought inline in+ // `delta.content` wrapped in <think> tags. The user shouldn't see that —+ // only the answer. State persists across SSE chunks because tags can+ // straddle the chunk boundary ("<thi" + "nk>...").+ bool in_think = false;+ QString think_pending;+ auto filter_think = [&](const QString& chunk) -> QString {+ QString out;+ QString work = think_pending + chunk;+ think_pending.clear();+ qsizetype pos = 0;+ const qsizetype n = work.length();+ while (pos < n) {+ if (in_think) {+ qsizetype end = work.indexOf(QStringLiteral("</think>"), pos, Qt::CaseInsensitive);+ if (end < 0) {+ // Hold last 8 chars in case </think> straddles.+ qsizetype safe = std::max<qsizetype>(pos, n - 8);+ think_pending = work.mid(safe);+ return out;+ }+ in_think = false;+ pos = end + 8;+ } else {+ qsizetype start = work.indexOf(QStringLiteral("<think>"), pos, Qt::CaseInsensitive);+ if (start < 0) {+ // Emit everything except the last 7 chars (length of "<think>")+ // which might be a partial open tag.+ qsizetype safe = std::max<qsizetype>(pos, n - 7);+ out += work.mid(pos, safe - pos);+ think_pending = work.mid(safe);+ return out;+ }+ out += work.mid(pos, start - pos);+ in_think = true;+ pos = start + 7;+ }+ }+ return out;+ };+QEventLoop loop;QTimer timeout;timeout.setSingleShot(true);@@ -820,17 +893,27 @@ LlmResponse LlmService::do_streaming_request(const QString& user_message,if (!chunk.isEmpty()) {accumulated += chunk;- // Some providers stream tool calls as XML text — detect, suppress output, fall back to do_request.- if (!tool_call_detected &&- (accumulated.contains("<tool_call>") || accumulated.contains("<invoke name=") ||- accumulated.contains("tool_call>"))) {- tool_call_detected = true;- LOG_INFO(kLlmSvcTag, "Tool call XML detected in streamed text — falling back to non-streaming");- loop.quit();- return;+ // Some providers stream tool calls as XML/text markup — detect, suppress output, fall back to do_request.+ // Patterns covered: <tool_call>, </tool_call>, <minimax:tool_call>, <invoke name=,+ // ```tool_call code fences, and bare `minimax:tool_call ... /minimax:tool_call`.+ if (!tool_call_detected) {+ static const QRegularExpression rx_text_tool(+ QStringLiteral("<\\s*/?\\s*(?:\\w+\\s*:\\s*)?tool_call\\b"+ "|<\\s*invoke\\s+name="+ "|```\\s*tool_call\\b"+ "|\\b\\w+\\s*:\\s*tool_call\\b"),+ QRegularExpression::CaseInsensitiveOption);+ if (rx_text_tool.match(accumulated).hasMatch()) {+ tool_call_detected = true;+ LOG_INFO(kLlmSvcTag, "Tool call markup detected in streamed text — falling back to non-streaming");+ loop.quit();+ return;+ }}- on_chunk(chunk, false);+ const QString visible = filter_think(chunk);+ if (!visible.isEmpty())+ on_chunk(visible, false);}}});@@ -855,9 +938,12 @@ LlmResponse LlmService::do_streaming_request(const QString& user_message,// Sentinel tells the chat screen to reset the bubble before the real reply arrives.on_chunk("\x01__TOOL_CALL_CLEAR__", false);+ // Wire per-tool progress into the chat bubble so the user sees something+ // during the multi-second tool execution phase instead of a blank wait.+ detail::ProgressEmitterGuard pg([on_chunk](const QString& s) { on_chunk(s, false); });auto tool_resp = do_request(user_message, history);if (tool_resp.success && !tool_resp.content.isEmpty())- on_chunk(tool_resp.content, false);+ on_chunk(QStringLiteral("\n") + tool_resp.content, false);on_chunk("", true);return tool_resp;}@@ -890,26 +976,16 @@ LlmResponse LlmService::do_streaming_request(const QString& user_message,LlmResponse LlmService::chat(const QString& user_message, const std::vector<ConversationMessage>& history,bool use_tools) {- QMutexLocker lock(&mutex_);- ensure_config();-- if (provider_.isEmpty())- return LlmResponse{.content = {}, .error = "No LLM provider configured"};-- // Snapshot config; release lock before the blocking network call.- QString p = provider_, k = api_key_, b = base_url_, m = model_, sp = system_prompt_;- double t = temperature_;- int mx = max_tokens_;- lock.unlock();-- // Helpers read members directly. Safe because chat() runs on a background thread.- provider_ = p;- api_key_ = k;- base_url_ = b;- model_ = m;- system_prompt_ = sp;- temperature_ = t;- max_tokens_ = mx;+ {+ QMutexLocker lock(&mutex_);+ ensure_config();+ if (provider_.isEmpty())+ return LlmResponse{.content = {}, .error = "No LLM provider configured"};+ }+ // Helpers read members directly. ensure_config() already wrote them under+ // mutex; we release before the blocking network call to avoid serialising+ // concurrent chats. Reassigning a local snapshot back to the members after+ // unlocking would clobber any reload_config() that landed in the gap.// thread_local guard avoids racing with concurrent chat_streaming calls from the floating bubble.detail::ToolPolicyGuard guard(use_tools ? ToolPolicy::All : ToolPolicy::None);@@ -923,7 +999,8 @@ void LlmService::chat_streaming(const QString& user_message, const std::vector<C}void LlmService::chat_streaming(const QString& user_message, const std::vector<ConversationMessage>& history,- StreamCallback on_chunk, ToolPolicy policy) {+ StreamCallback on_chunk, ToolPolicy policy,+ const QString& chat_session_id) {QString p, k, b, m, sp;double t;int mx;@@ -982,7 +1059,8 @@ void LlmService::chat_streaming(const QString& user_message, const std::vector<C}};(void)QtConcurrent::run(- [self, p, k, b, m, sp, t, mx, user_message, history_copy, guarded_chunk, policy]() {+ [self, p, k, b, m, sp, t, mx, user_message, history_copy, guarded_chunk, policy,+ chat_session_id]() {if (!self)return;@@ -999,6 +1077,7 @@ void LlmService::chat_streaming(const QString& user_message, const std::vector<C}detail::ToolPolicyGuard guard(policy);+ detail::ChatSessionGuard session_guard(chat_session_id);auto resp = self->do_streaming_request(user_message, history_copy, guarded_chunk);if (self) {diff --git a/fincept-qt/src/services/llm/LlmService.h b/fincept-qt/src/services/llm/LlmService.hindex a3a357889..1b6f56e4e 100644--- a/fincept-qt/src/services/llm/LlmService.h+++ b/fincept-qt/src/services/llm/LlmService.h@@ -60,8 +60,11 @@ class LlmService : public QObject {enum class ToolPolicy { All, NoNavigation, None };/// Spawns a background thread. on_chunk runs on that thread; finished_streaming() lands on UI thread.+ /// `chat_session_id` lets per-chat MCP tools (e.g. report_session_context) scope state to+ /// the originating conversation — omit for non-chat callers.void chat_streaming(const QString& user_message, const std::vector<ConversationMessage>& history,- StreamCallback on_chunk, ToolPolicy policy = ToolPolicy::All);+ StreamCallback on_chunk, ToolPolicy policy = ToolPolicy::All,+ const QString& chat_session_id = {});/// Back-compat: false→None, true→All. Prefer the enum overload.void chat_streaming(const QString& user_message, const std::vector<ConversationMessage>& history,diff --git a/fincept-qt/src/services/llm/LlmToolLoop.cpp b/fincept-qt/src/services/llm/LlmToolLoop.cppindex a4b06bfb3..9349a70e4 100644--- a/fincept-qt/src/services/llm/LlmToolLoop.cpp+++ b/fincept-qt/src/services/llm/LlmToolLoop.cpp@@ -29,10 +29,11 @@ namespace { constexpr const char* kLlmToolLoopTag = "LlmService"; }LlmResponse LlmService::do_tool_loop(QJsonArray loop_messages, const QString& url,const QMap<QString, QString>& headers) {LlmResponse resp;- // 15 rounds covers complex agentic workflows (multi-step research →- // template → fill → polish). Each round can contain many parallel- // tool calls so this isn't 15 tool calls — it's 15 reasoning steps.- static constexpr int MAX_ROUNDS = 15;+ // 40 rounds. MiniMax-style models spend 3 rounds per action+ // (tool.list → tool.describe → actual call) so 15 rounds left almost+ // nothing for actual report mutations. 40 gives ~13 actions, enough+ // for a full template fill. Bump higher only if real workflows hit it.+ static constexpr int MAX_ROUNDS = 40;LOG_INFO(kLlmToolLoopTag, QString("TOOL LOOP: starting (max %1 rounds, model=%2)").arg(MAX_ROUNDS).arg(model_));for (int round = 0; round < MAX_ROUNDS; ++round) {@@ -80,6 +81,13 @@ LlmResponse LlmService::do_tool_loop(QJsonArray loop_messages, const QString& urLOG_INFO(kLlmToolLoopTag, QString("TOOL LOOP r%1: executing %2 args=%3").arg(round).arg(fname,QString::fromUtf8(QJsonDocument(fa).toJson(QJsonDocument::Compact)).left(200)));+ // Strip "<server>__" prefix for user-visible label; restore "tool.list" from wire form.+ QString display = fname;+ int sep = display.indexOf(QStringLiteral("__"));+ if (sep > 0)+ 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);LOG_INFO(kLlmToolLoopTag, QString("TOOL LOOP r%1: %2 -> %3 (msg=%4 err=%5)").arg(round).arg(fname,@@ -93,31 +101,56 @@ LlmResponse LlmService::do_tool_loop(QJsonArray loop_messages, const QString& ur}// Final text response- resp.content = extract_openai_message_text(msg);+ resp.content = strip_think_blocks(extract_openai_message_text(msg));parse_usage(resp, rj, provider_);resp.success = !resp.content.isEmpty();LOG_INFO(kLlmToolLoopTag, QString("TOOL LOOP: finished after %1 round(s) — %2 chars of text").arg(round + 1).arg(resp.content.length()));++ // The "final" text may actually contain text-based tool markup+ // (<minimax:tool_call>, <invoke name=…>, etc.) that the model emitted+ // in place of structured tool_calls. If so, route through the+ // text-extraction path so the markup gets executed instead of leaking+ // into the chat bubble as raw XML.+ static const QRegularExpression rx_has_text_markup(+ QStringLiteral("<\\s*/?\\s*(?:\\w+\\s*:\\s*)?tool_call\\b|<\\s*invoke\\s+name="),+ QRegularExpression::CaseInsensitiveOption);+ if (resp.success && rx_has_text_markup.match(resp.content).hasMatch()) {+ LOG_INFO(kLlmToolLoopTag, "TOOL LOOP: final content has text-tool markup — re-routing through text-extraction");+ QString user_msg;+ for (const auto& v : loop_messages) {+ QJsonObject o = v.toObject();+ if (o["role"].toString() == "user") {+ user_msg = o["content"].toString();+ break; // first user msg is the original prompt+ }+ }+ auto text_result = try_extract_and_execute_text_tool_calls(resp.content, user_msg, url, headers);+ if (text_result.has_value() && text_result->success)+ return text_result.value();+ }return resp;}- // Max rounds exhausted. The user would see an empty bubble. Force one- // final non-tool turn so the model summarizes whatever it accomplished- // so the chat doesn't go silent.- LOG_WARN(kLlmToolLoopTag, "TOOL LOOP: exceeded max rounds — forcing summary turn (no tools)");+ // Max rounds exhausted. Force one final turn so the chat doesn't go silent.+ LOG_WARN(kLlmToolLoopTag, "TOOL LOOP: exceeded max rounds — forcing summary turn");{- // Append a synthetic system nudge instructing the model to wrap up.loop_messages.append(QJsonObject{{"role", "system"},- {"content", "You have used your tool-call budget. Reply now with a final answer to the user "- "summarizing what you accomplished and what (if anything) is incomplete. Do not "- "request any more tools."}});+ {"content", "You have used your tool-call budget. Reply now with a final summary of what "+ "you accomplished and what (if anything) is incomplete. If there are critical "+ "remaining tool calls, you may make them, but prefer summarising."}});QJsonObject fu;fu["model"] = model_;fu["messages"] = loop_messages;fu["max_tokens"] = resolved_max_tokens();- // Deliberately omit the tools field so the model is forced to produce text.+ // Keep tools available so structured tool_calls still work. Stripping+ // them used to force text-markup mode (raw <minimax:tool_call> blobs)+ // which leaked into the chat bubble.+ QJsonArray tools = mcp::McpService::instance().format_tools_for_openai(detail::apply_request_policy(tool_filter_));+ if (!tools.isEmpty())+ fu["tools"] = tools;auto http = blocking_post(url, fu, headers);if (http.success) {@@ -127,11 +160,32 @@ LlmResponse LlmService::do_tool_loop(QJsonArray loop_messages, const QString& urQJsonArray choices = rj["choices"].toArray();if (!choices.isEmpty()) {QJsonObject msg = choices[0].toObject()["message"].toObject();- resp.content = extract_openai_message_text(msg);+ resp.content = strip_think_blocks(extract_openai_message_text(msg));parse_usage(resp, rj, provider_);resp.success = !resp.content.isEmpty();LOG_INFO(kLlmToolLoopTag, QString("TOOL LOOP: summary fallback produced %1 chars").arg(resp.content.length()));++ // If the model emitted text-tool markup instead of structured+ // tool_calls, run it through extraction so the markup is+ // executed instead of dumped raw into the chat bubble.+ static const QRegularExpression rx_has_text_markup(+ QStringLiteral("<\\s*/?\\s*(?:\\w+\\s*:\\s*)?tool_call\\b|<\\s*invoke\\s+name="),+ QRegularExpression::CaseInsensitiveOption);+ if (resp.success && rx_has_text_markup.match(resp.content).hasMatch()) {+ LOG_INFO(kLlmToolLoopTag, "TOOL LOOP: summary fallback has text-tool markup — re-routing");+ QString user_msg;+ for (const auto& v : loop_messages) {+ QJsonObject o = v.toObject();+ if (o["role"].toString() == "user") {+ user_msg = o["content"].toString();+ break;+ }+ }+ auto text_result = try_extract_and_execute_text_tool_calls(resp.content, user_msg, url, headers);+ if (text_result.has_value() && text_result->success)+ return text_result.value();+ }if (resp.success)return resp;}@@ -324,6 +378,10 @@ std::optional<LlmResponse> LlmService::try_extract_and_execute_text_tool_calls(cQString tool_results;for (const auto& tc : calls) {LOG_INFO(kLlmToolLoopTag, "Executing text-detected tool: " + tc.name);+ int sep_disp = tc.name.indexOf(QStringLiteral("__"));+ QString display = (sep_disp >= 0) ? tc.name.mid(sep_disp + 2) : tc.name;+ display.replace(QStringLiteral("-dot-"), QStringLiteral("."));+ detail::emit_progress(QStringLiteral("Using `") + display + QStringLiteral("` …\n"));auto tr = mcp::McpService::instance().execute_openai_function(tc.name, tc.args);QString result_content;