Skip to content

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

Comment cleanup pass on LlmService, PythonSetupManager, DataMappingScreen.

tilakpatel22fb1217f9b9d4
diff --git a/fincept-qt/src/ai_chat/LlmService.cpp b/fincept-qt/src/ai_chat/LlmService.cpp
index 31173dde6..5866c765f 100644
--- a/fincept-qt/src/ai_chat/LlmService.cpp
+++ b/fincept-qt/src/ai_chat/LlmService.cpp
@@ -1,8 +1,4 @@
-// LlmService.cpp — Multi-provider LLM API client (Qt port)
-// Translated from fincept-cpp llm_service.cpp:
-// libcurl → QNetworkAccessManager + QEventLoop (blocking on bg thread)
-// std::future → QtConcurrent::run + signal
-// nlohmann/json → QJsonObject/QJsonArray
+// Multi-provider LLM API client. Sync paths block on QEventLoop and must run on a worker thread.
#include "ai_chat/LlmService.h"
@@ -43,10 +39,6 @@ static constexpr const char* kLlmSvcTag = "LlmService";
-// ============================================================================
-// Singleton
-// ============================================================================
-
LlmService::LlmService() = default;
LlmService& LlmService::instance() {
@@ -64,14 +56,8 @@ void LlmService::reload_config() {
}
void LlmService::ensure_config() const {
- // Called with mutex_ held.
- //
- // Fincept credentials are refreshed on every call regardless of cache
- // state — the cache is a one-shot for everything else (tool-RAG hint
- // generation walks the entire MCP registry), but credentials track the
- // auth lifecycle. The user can authenticate AFTER the first
- // ensure_config() ran (e.g. AI chat opened before login completes), and
- // a stale cached empty key would 401 every subsequent request.
+ // Called with mutex_ held. Cache is one-shot except for Fincept credentials —
+ // those re-resolve every call so a login that happens after first ensure_config() doesn't 401 forever.
if (config_loaded_) {
if (provider_ == "fincept") {
const auto& sess = fincept::auth::AuthManager::instance().session();
@@ -88,11 +74,7 @@ void LlmService::ensure_config() const {
provider_ = model_ = api_key_ = base_url_ = system_prompt_ = {};
temperature_ = 0.7;
- // 0 = "no user override; use ModelCatalog::output_cap(provider, model)".
- // The DB still holds whatever the user picked (including the legacy
- // 2000-token default). A v15 migration resets historical 2000 values
- // to 0; users who deliberately picked 2000 will get the model default
- // — that's the right call given 2000 was never a meaningful user choice.
+ // 0 means "no user override → ModelCatalog::output_cap()". The v15 migration reset legacy 2000 defaults.
max_tokens_ = 0;
tools_enabled_ = true;
@@ -108,7 +90,7 @@ void LlmService::ensure_config() const {
break;
}
}
- // Fallback: first config if none active
+ // No active provider — pick the first one.
if (provider_.isEmpty() && !providers.value().isEmpty()) {
const auto& c = providers.value().first();
provider_ = c.provider.toLower();
@@ -119,7 +101,7 @@ void LlmService::ensure_config() const {
}
}
- // Fallback: if no provider configured, use Fincept with session API key
+ // Nothing configured — default to Fincept with the session key.
if (provider_.isEmpty()) {
provider_ = "fincept";
model_ = "MiniMax-M2.7";
@@ -127,10 +109,7 @@ void LlmService::ensure_config() const {
LOG_INFO(kLlmSvcTag, "No LLM provider configured — using Fincept default");
}
- // Fincept always resolves API key from the authenticated session, never
- // from llm_configs. Prefer AuthManager's in-memory session (authoritative
- // and live); fall back to SettingsRepository("fincept_api_key") which
- // AuthManager writes during auto_configure_fincept_llm (legacy path).
+ // Fincept key always comes from the live AuthManager session; SettingsRepository fallback is the legacy path.
if (provider_ == "fincept") {
const auto& sess = fincept::auth::AuthManager::instance().session();
if (!sess.api_key.isEmpty()) {
@@ -149,10 +128,7 @@ void LlmService::ensure_config() const {
system_prompt_ = gs.value().system_prompt;
}
- // Inject default system prompt when user hasn't configured one.
- // This tells the model it is running inside the Fincept Terminal and
- // should use the provided tools (navigation, market data, portfolio, etc.)
- // rather than declining requests it can actually fulfil via a tool call.
+ // Default system prompt — primes the model to actually use tools instead of declining tool-feasible requests.
if (system_prompt_.trimmed().isEmpty()) {
system_prompt_ =
"You are Fincept AI, the intelligent assistant embedded inside the Fincept Terminal — "
@@ -195,26 +171,10 @@ void LlmService::ensure_config() const {
"Be concise, accurate, and finance-focused.";
}
- // ── Tier-3 / Tool RAG discovery hint ─────────────────────────────────
- //
- // Tool RAG (Tool Search) ships only ~6 tools to the LLM each turn (the
- // Tier-0 set: tool.list, tool.describe, navigate, list_tabs,
- // get_current_tab, get_auth_status). Everything else is discovered on
- // demand via tool.list(query) — this fixes the 30-50-tool accuracy
- // collapse documented by Anthropic.
- //
- // For the LLM to form good queries it needs to know WHAT categories
- // exist. We enumerate them dynamically from the registered tools so the
- // hint stays accurate when categories are added/removed. Built once per
- // ensure_config() pass, cached statically across requests so the prompt
- // prefix is byte-stable for prompt-cache hits.
- //
- // Idempotent append (`[Tool discovery]` sentinel guards against
- // double-stacking on reload).
+ // Tool RAG discovery hint: lists categories dynamically so the model can form good tool.list() queries.
+ // The `[Tool discovery]` sentinel makes append idempotent across reloads. Cached static for prompt-cache stability.
if (tools_enabled_ && !system_prompt_.contains("[Tool discovery]")) {
- // Static cache — the tool registry is immutable after McpInit. Any
- // future runtime registrations will see a stale category list until
- // the next process restart, which is acceptable for a hint string.
+ // Tool registry is immutable after McpInit; runtime additions won't appear until restart (acceptable here).
static const QString kHint = []() -> QString {
const auto all = mcp::McpProvider::instance().list_all_tools();
QSet<QString> cats;
@@ -313,9 +273,8 @@ ResolvedLlmProfile LlmService::resolve_profile(const QString& context_type, cons
// static
QJsonObject LlmService::profile_to_json(const ResolvedLlmProfile& p) {
- // Only include fields the Python model constructor accepts.
- // profile_id / profile_name are internal metadata — never send them to Python
- // or they land in extra_model_kwargs and fail as unexpected kwargs (e.g. Claude(profile_id=...)).
+ // Only fields the Python model constructor accepts. profile_id / profile_name are internal metadata —
+ // sending them lands in extra_model_kwargs and fails as unexpected kwargs.
QJsonObject obj;
obj["provider"] = p.provider;
obj["model_id"] = p.model_id;
@@ -328,20 +287,13 @@ QJsonObject LlmService::profile_to_json(const ResolvedLlmProfile& p) {
return obj;
}
-// ============================================================================
-// Endpoint + headers
-// ============================================================================
-
int LlmService::resolved_max_tokens() const {
- // Called with mutex_ held by the caller (build_*_request paths).
+ // Called with mutex_ held.
constexpr int kFallback = 8192;
const int catalog_cap = ModelCatalog::output_cap(provider_, model_);
- // User-set value (loaded from llm_global_settings or per-profile).
- // Treat <=0 as "unset — use model default".
+ // <=0 = unset; clamp user values to the model's published cap to avoid a 400.
if (max_tokens_ > 0) {
- // User asked for a specific number — honour it but clamp to the
- // model's published cap so we don't get a 400 from the API.
if (catalog_cap > 0 && max_tokens_ > catalog_cap)
return catalog_cap;
return max_tokens_;
@@ -353,17 +305,15 @@ int LlmService::resolved_max_tokens() const {
}
QString LlmService::get_endpoint_url() const {
- // Called with mutex_ held
+ // Called with mutex_ held.
const QString& p = provider_;
- // Fincept: two endpoints — sync chat and async LLM
- // base_url_ stores the base domain; append path here.
+ // Fincept sync chat endpoint (async lives in fincept_async_request).
if (p == "fincept") {
- // sync endpoint for chat (short replies)
return "https://api.fincept.in/research/chat";
}
- // Custom base_url takes priority for other providers
+ // Custom base_url wins over hard-coded defaults.
if (!base_url_.isEmpty()) {
QString base = base_url_;
if (base.endsWith('/'))
@@ -397,7 +347,7 @@ QString LlmService::get_endpoint_url() const {
}
QMap<QString, QString> LlmService::get_headers() const {
- // Called with mutex_ held
+ // Called with mutex_ held.
QMap<QString, QString> h;
const QString& p = provider_;
@@ -409,24 +359,18 @@ QMap<QString, QString> LlmService::get_headers() const {
if (!api_key_.isEmpty())
h["x-goog-api-key"] = api_key_;
} else if (p == "fincept") {
- // api_key_ is refreshed from AuthManager on every ensure_config() call,
- // so it tracks the auth lifecycle even if it was empty when the cache
- // was first populated.
if (!api_key_.isEmpty())
h["X-API-Key"] = api_key_;
- // session_token lives only in AuthManager (never written to
- // SettingsRepository) — read it live so it's always current.
+ // session_token only lives in AuthManager — read live, never cached.
const auto& sess = fincept::auth::AuthManager::instance().session();
if (!sess.session_token.isEmpty())
h["X-Session-Token"] = sess.session_token;
- // Cloudflare requires a User-Agent header
- h["User-Agent"] = "FinceptTerminal/4.0";
+ h["User-Agent"] = "FinceptTerminal/4.0"; // Cloudflare requires it.
} else {
- // OpenAI-compatible
if (!api_key_.isEmpty())
h["Authorization"] = "Bearer " + api_key_;
if (p == "openrouter") {
- // Optional attribution — appears on openrouter.ai/rankings leaderboard
+ // Attribution for the openrouter.ai/rankings leaderboard.
h["HTTP-Referer"] = "https://fincept.in";
h["X-Title"] = "Fincept Terminal";
}
@@ -436,10 +380,6 @@ QMap<QString, QString> LlmService::get_headers() const {
-// ============================================================================
-// Non-streaming request
-// ============================================================================
-
LlmResponse LlmService::do_request(const QString& user_message, const std::vector<ConversationMessage>& history) {
LlmResponse resp;
@@ -456,8 +396,7 @@ LlmResponse LlmService::do_request(const QString& user_message, const std::vecto
req_body = build_anthropic_request(user_message, history, false);
} else if (provider_ == "gemini" || provider_ == "google") {
req_body = build_gemini_request(user_message, history);
- // Auth goes via x-goog-api-key header (set by get_headers()).
- // Do not append ?key= to URL — it leaks the key into access logs.
+ // Auth via x-goog-api-key header — do NOT append ?key= (would leak into access logs).
} else if (provider_ == "fincept") {
// Fincept uses two separate endpoints:
// Primary response → async (submit + poll, returns richer model output)
@@ -484,8 +423,6 @@ LlmResponse LlmService::do_request(const QString& user_message, const std::vecto
}
QJsonObject rj = doc.object();
- // ── Extract content by provider ──────────────────────────────────────
-
if (provider_ == "anthropic") {
QJsonArray content = rj["content"].toArray();
QString stop_reason = rj["stop_reason"].toString();
@@ -497,15 +434,13 @@ LlmResponse LlmService::do_request(const QString& user_message, const std::vecto
// Build follow-up messages: original + assistant turn + tool results
QJsonArray loop_msgs;
if (!system_prompt_.isEmpty()) {
- } // system is top-level in Anthropic, not in messages
+ } // Anthropic puts system at top level, not in messages.
for (const auto& h : history)
if (h.role != "system")
loop_msgs.append(QJsonObject{{"role", h.role}, {"content", h.content}});
loop_msgs.append(QJsonObject{{"role", "user"}, {"content", user_message}});
- // Assistant message with the tool_use content blocks
loop_msgs.append(QJsonObject{{"role", "assistant"}, {"content", content}});
- // Execute each tool_use block and collect results
QJsonArray tool_results;
for (const auto& block_val : content) {
QJsonObject block = block_val.toObject();
@@ -523,15 +458,13 @@ LlmResponse LlmService::do_request(const QString& user_message, const std::vecto
{"content", QString::fromUtf8(QJsonDocument(tr.to_json()).toJson(QJsonDocument::Compact))}});
}
- // Follow-up: user turn with tool_result blocks
loop_msgs.append(QJsonObject{{"role", "user"}, {"content", tool_results}});
- // Build follow-up request (no tools to avoid infinite loop)
+ // No tools in follow-up — prevents infinite loop.
QJsonObject fu;
fu["model"] = model_;
fu["messages"] = loop_msgs;
fu["max_tokens"] = resolved_max_tokens();
- // Temperature intentionally omitted — Anthropic default.
if (!system_prompt_.isEmpty())
fu["system"] = system_prompt_;
@@ -545,9 +478,6 @@ LlmResponse LlmService::do_request(const QString& user_message, const std::vecto
return resp;
}
} else {
- // Normal text response — concatenate all text blocks and fall back
- // to extended-thinking content if no text was emitted (e.g. when
- // max_tokens is exhausted mid-thinking).
resp.content = extract_anthropic_content_text(content);
}
@@ -556,7 +486,6 @@ LlmResponse LlmService::do_request(const QString& user_message, const std::vecto
if (!cands.isEmpty()) {
QJsonArray parts = cands[0].toObject()["content"].toObject()["parts"].toArray();
- // Check for functionCall parts (Gemini tool use)
bool has_function_calls = false;
for (const auto& part_val : parts) {
if (part_val.toObject().contains("functionCall")) {
@@ -582,8 +511,7 @@ LlmResponse LlmService::do_request(const QString& user_message, const std::vecto
LOG_INFO(kLlmSvcTag, "Executing Gemini tool: " + fn_name);
auto tr = mcp::McpService::instance().execute_openai_function(fn_name, fn_args);
- // Build a JSON response object. Gemini requires response to be an
- // object (string values are wrapped under a key).
+ // Gemini requires response to be an object — wrap strings under "result".
QJsonObject response_obj;
if (!tr.data.isNull() && !tr.data.isUndefined() && tr.data.isObject())
response_obj = tr.data.toObject();
@@ -598,7 +526,7 @@ LlmResponse LlmService::do_request(const QString& user_message, const std::vecto
}
if (!fn_response_parts.isEmpty()) {
- // Rebuild contents: prior history + original user + model(functionCall) + user(functionResponse)
+ // history + original user + model(functionCall) + user(functionResponse).
QJsonArray fu_contents;
for (const auto& m : history) {
if (m.role == "system")
@@ -613,7 +541,7 @@ LlmResponse LlmService::do_request(const QString& user_message, const std::vecto
{"parts", QJsonArray{QJsonObject{{"text", user_message}}}}});
fu_contents.append(QJsonObject{
{"role", "model"},
- {"parts", parts}}); // echo the functionCall parts verbatim
+ {"parts", parts}}); // echo functionCall parts verbatim
fu_contents.append(QJsonObject{
{"role", "user"},
{"parts", fn_response_parts}});
@@ -621,7 +549,6 @@ LlmResponse LlmService::do_request(const QString& user_message, const std::vecto
QJsonObject fu_body;
fu_body["contents"] = fu_contents;
QJsonObject gen_cfg;
- // Temperature intentionally omitted — Gemini default.
gen_cfg["maxOutputTokens"] = resolved_max_tokens();
fu_body["generationConfig"] = gen_cfg;
if (!system_prompt_.isEmpty())
@@ -639,7 +566,7 @@ LlmResponse LlmService::do_request(const QString& user_message, const std::vecto
}
}
if (resp.content.isEmpty()) {
- // Fallback: render function responses as readable text
+ // Render function responses as readable text.
QString fallback;
for (const auto& pv : fn_response_parts) {
QJsonObject fr = pv.toObject()["functionResponse"].toObject();
@@ -656,20 +583,17 @@ LlmResponse LlmService::do_request(const QString& user_message, const std::vecto
}
}
} else {
- // Normal text response — concatenate all text parts; fall back
- // to `thought:true` parts if no normal text was emitted.
resp.content = extract_gemini_parts_text(parts);
}
}
} else if (provider_ == "fincept") {
- // /research/chat returns OpenAI-compatible choices array:
- // {"success":true,"data":{"choices":[{"message":{"role":"assistant","content":"..."}}],...}}
+ // {"success":..., "data":{"choices":[{"message":{"content":...}}]}} or top-level shape.
QJsonObject data = rj.contains("data") ? rj["data"].toObject() : rj;
QJsonArray choices = data["choices"].toArray();
if (!choices.isEmpty())
resp.content = extract_openai_message_text(choices[0].toObject()["message"].toObject());
- // API returned success=true but empty response text — treat as soft error
+ // success=true with empty content is a soft error.
if (resp.content.isEmpty()) {
resp.error = "Fincept LLM returned an empty response. Please try again.";
LOG_WARN(kLlmSvcTag, "Fincept /research/chat returned empty choices or content");
@@ -677,7 +601,7 @@ LlmResponse LlmService::do_request(const QString& user_message, const std::vecto
}
} else {
- // OpenAI-compatible — check for tool calls
+ // OpenAI-compatible.
QJsonArray choices = rj["choices"].toArray();
if (!choices.isEmpty()) {
QJsonObject msg = choices[0].toObject()["message"].toObject();
@@ -686,16 +610,14 @@ LlmResponse LlmService::do_request(const QString& user_message, const std::vecto
if (!tcs.isEmpty()) {
LOG_INFO(kLlmSvcTag, QString("LLM requested %1 tool calls").arg(tcs.size()));
- // Build initial messages array for tool loop
QJsonArray loop_msgs;
if (!system_prompt_.isEmpty())
loop_msgs.append(QJsonObject{{"role", "system"}, {"content", system_prompt_}});
for (const auto& h : history)
loop_msgs.append(QJsonObject{{"role", h.role}, {"content", h.content}});
loop_msgs.append(QJsonObject{{"role", "user"}, {"content", user_message}});
- loop_msgs.append(msg); // assistant message with tool_calls
+ loop_msgs.append(msg); // assistant turn with tool_calls
- // Execute tool calls and append results
for (const auto& tc_val : tcs) {
QJsonObject tc = tc_val.toObject();
QString call_id = tc["id"].toString();
@@ -721,9 +643,7 @@ LlmResponse LlmService::do_request(const QString& user_message, const std::vecto
return resp;
} else {
- // Normal text response — helper handles plain content, reasoning
- // models (kimi-k2.x / deepseek-reasoner), content-as-parts arrays,
- // and refusal messages in one place.
+ // Helper handles reasoning models, content-as-parts arrays, and refusal messages.
resp.content = extract_openai_message_text(msg);
}
}
@@ -749,16 +669,10 @@ LlmResponse LlmService::do_request(const QString& user_message, const std::vecto
return resp;
}
-// ============================================================================
-// Streaming request (SSE)
-// ============================================================================
-
LlmResponse LlmService::do_streaming_request(const QString& user_message,
const std::vector<ConversationMessage>& history, StreamCallback on_chunk) {
- // All providers fall back to non-streaming do_request so the full tool-call /
- // follow-up loop runs correctly regardless of provider.
- // Streaming is disabled globally until per-provider SSE tool-call handling is
- // implemented for each backend.
+ // 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.
{
auto resp = do_request(user_message, history);
if (resp.success && !resp.content.isEmpty())
@@ -776,12 +690,10 @@ LlmResponse LlmService::do_streaming_request(const QString& user_message,
}
auto hdr = get_headers();
- // Send tools for OpenAI-compatible streaming; Anthropic streaming doesn't
- // support tool_choice in the same SSE flow so we handle that separately.
+ // Anthropic streaming handles tools out-of-band so it goes through a different request shape.
QJsonObject req_body = (provider_ == "anthropic") ? build_anthropic_request(user_message, history, true)
: build_openai_request(user_message, history, true, true);
- // Use dedicated NAM on this background thread
QNetworkAccessManager nam;
QNetworkRequest req{QUrl(url)};
req.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
@@ -809,7 +721,6 @@ LlmResponse LlmService::do_streaming_request(const QString& user_message,
loop.quit();
});
QObject::connect(reply, &QNetworkReply::readyRead, &loop, [&]() {
- // Drain all available data
partial_line += reply->readAll();
while (true) {
int nl = partial_line.indexOf('\n');
@@ -818,7 +729,6 @@ LlmResponse LlmService::do_streaming_request(const QString& user_message,
QByteArray raw_line = partial_line.left(nl);
partial_line.remove(0, nl + 1);
- // Remove \r
if (!raw_line.isEmpty() && raw_line.back() == '\r')
raw_line.chop(1);
@@ -826,7 +736,7 @@ LlmResponse LlmService::do_streaming_request(const QString& user_message,
if (line.isEmpty() || !line.startsWith("data: "))
continue;
- QString data = line.mid(6); // remove "data: "
+ QString data = line.mid(6); // strip "data: "
if (data == "[DONE]") {
if (!tool_call_detected)
on_chunk("", true);
@@ -835,8 +745,7 @@ LlmResponse LlmService::do_streaming_request(const QString& user_message,
return;
}
- // Capture usage chunk (OpenAI sends usage in a trailing chunk with
- // empty choices[] when stream_options.include_usage=true)
+ // OpenAI sends a trailing usage chunk (empty choices[]) when stream_options.include_usage=true.
{
auto usage_doc = QJsonDocument::fromJson(data.toUtf8());
if (!usage_doc.isNull() && usage_doc.isObject()) {
@@ -846,13 +755,11 @@ LlmResponse LlmService::do_streaming_request(const QString& user_message,
}
}
- // Detect tool calls in streaming SSE — all providers
if (!tool_call_detected) {
auto doc = QJsonDocument::fromJson(data.toUtf8());
if (!doc.isNull() && doc.isObject()) {
QJsonObject obj = doc.object();
- // Anthropic native SSE format
if (provider_ == "anthropic") {
const QString type = obj["type"].toString();
if (type == "content_block_start" &&
@@ -871,13 +778,9 @@ LlmResponse LlmService::do_streaming_request(const QString& user_message,
}
}
- // OpenAI-compatible format (used by fincept, openai, and others)
QJsonArray choices = obj["choices"].toArray();
if (!choices.isEmpty()) {
const QString finish = choices[0].toObject()["finish_reason"].toString();
- if (finish == "tool_calls" || finish == "stop") {
- // "stop" with accumulated tool XML → also check
- }
if (finish == "tool_calls") {
LOG_INFO(kLlmSvcTag,
QString("STREAM: OpenAI-compat finish_reason=tool_calls detected (%1)")
@@ -896,7 +799,7 @@ LlmResponse LlmService::do_streaming_request(const QString& user_message,
}
}
- // Fincept may also return tool_calls at top level
+ // Fincept can also surface tool_calls at top level.
if (!obj["tool_calls"].isUndefined() && !obj["tool_calls"].isNull() &&
obj["tool_calls"].toArray().size() > 0) {
LOG_INFO(kLlmSvcTag, "STREAM: top-level tool_calls detected (fincept)");
@@ -911,10 +814,7 @@ LlmResponse LlmService::do_streaming_request(const QString& user_message,
if (!chunk.isEmpty()) {
accumulated += chunk;
- // Detect tool calls embedded as XML in the streamed text.
- // Some APIs return tool calls as text XML rather than
- // structured JSON. Detect early, suppress output, fallback
- // to non-streaming path which handles tool execution.
+ // 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>"))) {
@@ -932,15 +832,12 @@ LlmResponse LlmService::do_streaming_request(const QString& user_message,
loop.exec();
timeout.stop();
- // If the model requested tool calls, fall back to non-streaming do_request
- // which already handles the full tool-call/follow-up loop correctly.
if (tool_call_detected) {
LOG_INFO(kLlmSvcTag, "Tool call detected in stream — falling back to tool loop");
reply->abort();
reply->deleteLater();
- // Clear any partial XML that was already streamed to the UI.
- // Send a special "clear" sentinel so the chat screen can reset the bubble.
+ // Sentinel tells the chat screen to reset the bubble before the real reply arrives.
on_chunk("\x01__TOOL_CALL_CLEAR__", false);
auto tool_resp = do_request(user_message, history);
@@ -968,7 +865,7 @@ LlmResponse LlmService::do_streaming_request(const QString& user_message,
reply->deleteLater();
if (!done)
- on_chunk("", true); // ensure done fires
+ on_chunk("", true);
return resp;
}
@@ -984,15 +881,13 @@ LlmResponse LlmService::chat(const QString& user_message, const std::vector<Conv
if (provider_.isEmpty())
return LlmResponse{.content = {}, .error = "No LLM provider configured"};
- // Take config snapshot — release lock before blocking network call
+ // 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();
- // Restore snapshot into members for use by helper methods
- // (helpers read member variables, so we need them set)
- // This is safe because chat() is always called from a background thread.
+ // Helpers read members directly. Safe because chat() runs on a background thread.
provider_ = p;
api_key_ = k;
base_url_ = b;
@@ -1001,19 +896,11 @@ LlmResponse LlmService::chat(const QString& user_message, const std::vector<Conv
temperature_ = t;
max_tokens_ = mx;
- // Per-message intent classifier removed. Tool RAG (tool.list) replaces
- // it — instead of guessing categories from keywords server-side, the LLM
- // now searches the catalog itself with a natural-language query. Higher
- // accuracy, no English-only keyword list to maintain.
-
- // Per-request tools-off override (thread_local). Replaces the old
- // pattern of mutating tools_enabled_ on the singleton, which raced with
- // concurrent chat_streaming calls from the floating bubble.
+ // thread_local guard avoids racing with concurrent chat_streaming calls from the floating bubble.
detail::ToolPolicyGuard guard(use_tools ? ToolPolicy::All : ToolPolicy::None);
return do_request(user_message, history);
}
-// Back-compat boolean overload — delegates to the enum form.
void LlmService::chat_streaming(const QString& user_message, const std::vector<ConversationMessage>& history,
StreamCallback on_chunk, bool use_tools) {
chat_streaming(user_message, history, std::move(on_chunk),
@@ -1022,7 +909,6 @@ 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) {
- // Snapshot config under lock
QString p, k, b, m, sp;
double t;
int mx;
@@ -1044,20 +930,13 @@ void LlmService::chat_streaming(const QString& user_message, const std::vector<C
return;
}
- // Copy history for lambda capture
std::vector<ConversationMessage> history_copy = history;
QPointer<LlmService> self = this;
- // Phase 9: shadow-publish every stream chunk to the DataHub under a
- // per-stream session id. Subscribers (future observer panels, LLM
- // diagnostics, agent MCP bridges) can tail `llm:session:*:stream`
- // without being wired into the original caller. Push-only, coalesced
- // at the policy layer so a token firehose doesn't spam subscribers.
+ // Shadow-publish every chunk to DataHub under a per-stream session id so observer panels
+ // can tail `llm:session:*:stream` without being wired in. Push-only, coalesced.
const QString stream_id = QUuid::createUuid().toString(QUuid::WithoutBraces);
const QString stream_topic = QStringLiteral("llm:session:") + stream_id + QStringLiteral(":stream");
- // One-shot pattern registration — LlmService is not a Producer (no
- // pull semantics), just a publisher. The policy caps cached state
- // and applies coalescing across the topic family.
[[maybe_unused]] static bool policy_once = []() {
auto& hub = fincept::datahub::DataHub::instance();
fincept::datahub::TopicPolicy policy;
@@ -1068,8 +947,7 @@ void LlmService::chat_streaming(const QString& user_message, const std::vector<C
LOG_INFO("LlmService", "Registered DataHub policy for llm:session:*");
return true;
}();
- // Guard on_chunk: if LlmService is destroyed before a chunk arrives,
- // skip the callback entirely rather than invoking into a dead context.
+ // Skip on_chunk if LlmService dies before the chunk arrives.
StreamCallback guarded_chunk = [self, on_chunk
, stream_id, stream_topic
](const QString& chunk, bool done) {
@@ -1084,8 +962,7 @@ void LlmService::chat_streaming(const QString& user_message, const std::vector<C
auto& hub = fincept::datahub::DataHub::instance();
hub.publish(stream_topic, QVariant(payload));
if (done) {
- // Retire the per-session topic; subscribers remain attached
- // but cached state is discarded. Phase 9.
+ // Subscribers stay attached but cached state is discarded.
hub.retire_topic(stream_topic);
}
};
@@ -1094,11 +971,7 @@ void LlmService::chat_streaming(const QString& user_message, const std::vector<C
if (!self)
return;
- // Apply the config snapshot under the mutex so do_request /
- // do_streaming_request see a consistent state and don't race with
- // reload_config() on the UI thread. We no longer mutate
- // tools_enabled_ — per-request opt-out is conveyed via the
- // thread_local detail::ToolPolicyGuard below.
+ // Snapshot under mutex so do_*_request see consistent state and don't race with reload_config().
{
QMutexLocker lock(&self->mutex_);
self->provider_ = p;
diff --git a/fincept-qt/src/python/PythonSetupManager.cpp b/fincept-qt/src/python/PythonSetupManager.cpp
index b76cb284f..f230557fa 100644
--- a/fincept-qt/src/python/PythonSetupManager.cpp
+++ b/fincept-qt/src/python/PythonSetupManager.cpp
@@ -1,7 +1,4 @@
-// src/python/PythonSetupManager.cpp
-//
-// UV-first Python setup: download one binary, UV does the rest.
-// Parallel venv creation + package installation.
+// UV-first Python setup with parallel venv creation + package installation.
#include "python/PythonSetupManager.h"
#include "core/config/AppPaths.h"
@@ -26,10 +23,6 @@
namespace fincept::python {
-// ─────────────────────────────────────────────────────────────────────────────
-// Singleton
-// ─────────────────────────────────────────────────────────────────────────────
-
PythonSetupManager& PythonSetupManager::instance() {
static PythonSetupManager s;
return s;
@@ -37,18 +30,10 @@ PythonSetupManager& PythonSetupManager::instance() {
PythonSetupManager::PythonSetupManager(QObject* parent) : QObject(parent) {}
-// ─────────────────────────────────────────────────────────────────────────────
-// Install directory — com.fincept.terminal
-// ─────────────────────────────────────────────────────────────────────────────
-
QString PythonSetupManager::install_dir() const {
return fincept::AppPaths::root();
}
-// ─────────────────────────────────────────────────────────────────────────────
-// Paths
-// ─────────────────────────────────────────────────────────────────────────────
-
QString PythonSetupManager::uv_path() const {
#ifdef _WIN32
return install_dir() + "/uv/uv.exe";
@@ -58,16 +43,14 @@ QString PythonSetupManager::uv_path() const {
}
QString PythonSetupManager::base_python_path() const {
- // Guard: this function may block up to 10s — must not be called from the UI thread.
- // Acceptable call sites: main() before exec(), background threads, QtConcurrent::run().
+ // May block up to 10s — never call from the UI thread. Background threads / pre-exec only.
Q_ASSERT(QCoreApplication::instance() == nullptr ||
QThread::currentThread() != QCoreApplication::instance()->thread());
- // Return cached result if already resolved this session.
if (!cached_python_path_.isEmpty())
return cached_python_path_;
- // Resolve via `uv python find` — spawns a process, so we only do this once.
+ // `uv python find` spawns a process — resolve once per session.
QProcess proc;
QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
env.insert("UV_PYTHON_INSTALL_DIR", install_dir() + "/python");
@@ -105,17 +88,8 @@ QString PythonSetupManager::python_path(const QString& venv_name) const {
#endif
}
-// Shared UV env — applied to every `uv` invocation so download/install behaviour
-// is consistent across platforms. See header for per-var rationale.
-//
-// Concurrency is clamped on both ends so the same defaults are safe on a 2-core
-// / 4 GB netbook and a 32-core workstation:
-// - installs: floor 2 (so single-core CPUs still parallelise I/O), ceiling 8
-// (more workers don't help — install is disk-bound — but they
-// do consume RAM unpacking torch/catboost wheels in parallel).
-// - downloads: ceiling 8 too. UV's own default is 50; capping prevents a
-// slow / metered connection on a low-end machine from opening
-// dozens of TLS sockets at once.
+/// Shared UV env. Concurrency clamped [2,8] for installs and [4,8] for downloads —
+/// safe on 2-core netbooks (RAM-bound wheel unpack) and metered/slow connections.
QStringList PythonSetupManager::uv_env_extra() const {
const QString root = install_dir();
const int cores = QThread::idealThreadCount();
@@ -132,18 +106,8 @@ QStringList PythonSetupManager::uv_env_extra() const {
};
}
-// ─────────────────────────────────────────────────────────────────────────────
-// Marker / hash helpers
-//
-// The .packages_installed marker now stores the SHA-256 hex of the requirements
-// file that was used for the last *successful* install. A venv is "ready" only
-// when this hash matches the current requirements file on disk.
-//
-// Old installs wrote "ok\n" — that never matches a 64-char hex string, so the
-// first launch after updating to this code transparently migrates via the slow
-// path (uv pip list check), then writes the real hash.
-// ─────────────────────────────────────────────────────────────────────────────
-
+/// .packages_installed stores the SHA-256 hex of the last successfully-installed requirements file.
+/// Legacy "ok\n" markers fall through to the slow `uv pip list` verify and are then rewritten as hashes.
static QString sentinel_path_for(const QString& install_dir) {
return install_dir + "/.setup_complete";
}
@@ -167,15 +131,7 @@ void PythonSetupManager::write_marker_hash(const QString& venv_name, const QStri
f.write((req_hash + "\n").toUtf8());
}
-// ─────────────────────────────────────────────────────────────────────────────
-// verify_packages_installed — slow-path cross-check via `uv pip list`
-//
-// Reads every package name from requirements_file, then asks UV what is
-// actually installed in the venv. Returns true only if every required package
-// is present. This runs on first launch, after marker deletion, or after a
-// partial install — never on the fast path.
-// ─────────────────────────────────────────────────────────────────────────────
-
+/// Slow-path verify via `uv pip list`. Runs on first launch / marker missing / partial install — never fast path.
bool PythonSetupManager::verify_packages_installed(const QString& venv_name,
const QString& requirements_file) const {
QString req_path = find_requirements_file(requirements_file);
@@ -200,19 +156,14 @@ bool PythonSetupManager::verify_packages_installed(const QString& venv_name,
});
#endif
proc.start(uv_path(), {"pip", "list", "--python", python_path(venv_name)});
- // 90s — generous headroom for large venvs (300+ packages) on slow disks or
- // when Windows Defender is scanning the venv directory. A false 30s timeout
- // previously marked a correctly-installed venv as broken, forcing a full reinstall.
+ // 90s — 300+-pkg venvs on slow disks / Defender-scanning overran the previous 30s and forced a full reinstall.
if (!proc.waitForFinished(90000) || proc.exitCode() != 0) {
LOG_WARN("PythonSetup",
QString("[%1] verify: uv pip list failed or timed out").arg(venv_name));
return false;
}
- // Build a normalised set of installed package names.
- // PEP 503: canonical name = lowercase, replace [-_.] with a single '-'.
- // We normalise both sides to lowercase + replace '-'/'.' with '_' for
- // a simple consistent comparison.
+ // PEP 503-ish normalisation: lowercase + collapse `-`/`.` to `_`.
auto normalise = [](const QString& name) -> QString {
QString n = name.toLower();
n.replace('-', '_');
@@ -254,17 +205,12 @@ bool PythonSetupManager::verify_packages_installed(const QString& venv_name,
return true;
}
-// ─────────────────────────────────────────────────────────────────────────────
-// check_status (fast, synchronous)
-// ─────────────────────────────────────────────────────────────────────────────
-
SetupStatus PythonSetupManager::check_status() const {
SetupStatus status;
status.install_dir = install_dir();
LOG_INFO("PythonSetup", "=== check_status BEGIN === install_dir: " + status.install_dir);
- // ── File-existence checks (always fast) ───────────────────────────────────
status.uv_installed = QFileInfo::exists(uv_path());
status.venv_numpy1_created = QFileInfo::exists(python_path("venv-numpy1"));
status.venv_numpy2_created = QFileInfo::exists(python_path("venv-numpy2"));
@@ -275,9 +221,7 @@ SetupStatus PythonSetupManager::check_status() const {
.arg(status.venv_numpy1_created ? "YES" : "NO", python_path("venv-numpy1"))
.arg(status.venv_numpy2_created ? "YES" : "NO", python_path("venv-numpy2")));
- // ── Compute current requirements hashes ───────────────────────────────────
- // If a file is not found the hash is empty — treated as "not current",
- // which forces reinstall (correct) rather than silently skipping.
+ // Empty hash = file missing → treat as not-current → forces reinstall.
const QString req_hash1 = compute_requirements_hash("requirements-numpy1.txt");
const QString req_hash2 = compute_requirements_hash("requirements-numpy2.txt");
@@ -295,9 +239,7 @@ SetupStatus PythonSetupManager::check_status() const {
"requirements-numpy2.txt NOT FOUND — find_requirements_file() returned empty. "
"Check that resources/ folder is deployed beside the exe.");
- // A venv is "ready" only when its marker content equals the current hash.
- // Empty stored hash → old "ok\n" marker or absent file → not current.
- // Empty req hash → requirements file missing → not current (will fail at install).
+ // A venv is ready only when its marker hash matches the current requirements hash.
const QString stored1 = read_marker_hash("venv-numpy1");
const QString stored2 = read_marker_hash("venv-numpy2");
const bool pkg1_current = !req_hash1.isEmpty() && (stored1 == req_hash1);
@@ -318,7 +260,7 @@ SetupStatus PythonSetupManager::check_status() const {
QString("Sentinel: %1 (%2)")
.arg(sentinel_exists ? "EXISTS" : "ABSENT", sentinel_path_for(install_dir())));
- // ── Fast path: sentinel + UV + both markers current ───────────────────────
+ // Fast path: sentinel + UV + both markers current.
if (sentinel_exists && status.uv_installed && status.venv_numpy1_ready && status.venv_numpy2_ready) {
status.python_installed = true;
status.needs_setup = false;
@@ -326,14 +268,7 @@ SetupStatus PythonSetupManager::check_status() const {
return status;
}
- // ── Package-sync sub-case: infra present but ≥1 venv hash is stale ────────
- // This sub-case is ONLY for a hash mismatch (requirements file updated after
- // a successful install). A missing marker (stored1/stored2 empty) means the
- // packages were never installed at all — that is needs_setup=true, not sync.
- //
- // Guard: skip this sub-case if either venv has an empty marker AND its venv
- // directory exists — that indicates an incomplete/empty venv that needs a
- // full package install, not just a background sync.
+ // Sync sub-case: hash-mismatch only. Empty marker on an existing venv means full install, not sync.
const bool venv1_marker_absent = stored1.isEmpty();
const bool venv2_marker_absent = stored2.isEmpty();
const bool venv1_needs_full_install = status.venv_numpy1_created && venv1_marker_absent;
@@ -341,7 +276,6 @@ SetupStatus PythonSetupManager::check_status() const {
if (sentinel_exists && status.uv_installed && status.venv_numpy1_created && status.venv_numpy2_created
&& !venv1_needs_full_install && !venv2_needs_full_install) {
- // Verify Python is present (cheap — just check the exe path).
QString py = base_python_path();
LOG_INFO("PythonSetup",
QString("Sync-check: base python = %1 exists = %2")
@@ -368,11 +302,10 @@ SetupStatus PythonSetupManager::check_status() const {
.arg(venv2_needs_full_install ? "YES" : "NO"));
}
- // ── Slow path: first run or broken install ────────────────────────────────
+ // Slow path: first run or broken install.
LOG_INFO("PythonSetup", "Slow path: running full status check (sentinel/markers absent or stale)");
- // Check Python is working (blocking — only runs on first launch or after
- // partial install when no window is visible yet).
+ // Blocking — only runs pre-window on first launch / partial install.
if (status.uv_installed) {
QString py = base_python_path();
LOG_INFO("PythonSetup",
@@ -404,14 +337,7 @@ SetupStatus PythonSetupManager::check_status() const {
LOG_WARN("PythonSetup", "UV not installed — skipping Python check");
}
- // ── Slow-path package verification ────────────────────────────────────────
- // The marker is absent OR stale (hash mismatch). Run `uv pip list` to
- // check whether every required package is actually present. This covers:
- // - First launch after updating the app (old "ok\n" marker)
- // - Manual marker deletion
- // - Partial install that failed to write the marker
- // If verification passes we write the current hash marker so future launches
- // use the fast path. If it fails we leave needs_setup=true → full install.
+ // Marker absent or stale → verify with `uv pip list`. On pass, write the hash so future launches go fast-path.
if (status.venv_numpy1_created && !pkg1_current) {
LOG_INFO("PythonSetup", "venv-numpy1: marker stale/absent — running uv pip list verification");
if (!req_hash1.isEmpty() && verify_packages_installed("venv-numpy1", "requirements-numpy1.txt")) {
@@ -460,10 +386,6 @@ SetupStatus PythonSetupManager::check_status() const {
return status;
}
-// ─────────────────────────────────────────────────────────────────────────────
-// Run full setup (background thread)
-// ─────────────────────────────────────────────────────────────────────────────
-
void PythonSetupManager::run_setup() {
LOG_INFO("PythonSetup", "=== run_setup START ===");
QPointer<PythonSetupManager> self = this;
@@ -629,10 +551,6 @@ void PythonSetupManager::run_setup() {
});
}
-// ─────────────────────────────────────────────────────────────────────────────
-// Step 1: Download UV standalone binary
-// ─────────────────────────────────────────────────────────────────────────────
-
bool PythonSetupManager::download_uv() {
QString dir = install_dir() + "/uv";
QDir().mkpath(dir);
@@ -727,10 +645,6 @@ bool PythonSetupManager::download_uv() {
return true;
}
-// ─────────────────────────────────────────────────────────────────────────────
-// Step 2: Install Python via UV (replaces manual download + get-pip.py)
-// ─────────────────────────────────────────────────────────────────────────────
-
bool PythonSetupManager::install_python_via_uv() {
emit_progress("python", 20, "UV is downloading Python 3.11...");
@@ -759,10 +673,6 @@ bool PythonSetupManager::install_python_via_uv() {
return true;
}
-// ─────────────────────────────────────────────────────────────────────────────
-// Step 3: Create venv (can run in parallel)
-// ─────────────────────────────────────────────────────────────────────────────
-
bool PythonSetupManager::create_venv(const QString& venv_name) {
QString venv_path = install_dir() + "/" + venv_name;
@@ -785,12 +695,8 @@ bool PythonSetupManager::create_venv(const QString& venv_name) {
return false;
}
-// ─────────────────────────────────────────────────────────────────────────────
-// Step 4: Install packages (can run in parallel, UV handles internal parallelism)
-// ─────────────────────────────────────────────────────────────────────────────
-
bool PythonSetupManager::install_packages(const QString& venv_name, const QString& requirements_file) {
- // Derive step key first — needed for all emit_progress calls including early returns
+ // step_key is needed for early-return progress events.
const QString step_key = venv_name.contains("numpy1") ? "packages-numpy1" : "packages-numpy2";
LOG_INFO("PythonSetup",
@@ -817,8 +723,7 @@ bool PythonSetupManager::install_packages(const QString& venv_name, const QStrin
const QString venv_python = python_path(venv_name);
- // Shared UV env + peewee build flags (peewee is a transitive dep that fails
- // to build its C extension under the embedded Python on some platforms).
+ // peewee build flags — its C extension fails to compile against the embedded Python on some platforms.
QStringList env = uv_env_extra();
env << "PEEWEE_NO_SQLITE_EXTENSIONS=1"
<< "PEEWEE_NO_C_EXTENSION=1";
@@ -884,11 +789,7 @@ bool PythonSetupManager::install_packages(const QString& venv_name, const QStrin
return false;
}
-// ─────────────────────────────────────────────────────────────────────────────
-// Read packages from a requirements file, stripping comments and blank lines.
-// Returns one entry per non-empty, non-comment line.
-// ─────────────────────────────────────────────────────────────────────────────
-
+/// Strips comments and blank lines from a requirements file.
QStringList PythonSetupManager::read_packages_from_file(const QString& req_path) const {
QFile file(req_path);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
@@ -910,11 +811,7 @@ QStringList PythonSetupManager::read_packages_from_file(const QString& req_path)
return packages;
}
-// ─────────────────────────────────────────────────────────────────────────────
-// Install packages one by one, skipping any that fail.
-// Returns the list of packages that failed (for logging).
-// ─────────────────────────────────────────────────────────────────────────────
-
+/// Install one-by-one, skipping failures. Returns the failure list for logging.
QStringList PythonSetupManager::install_packages_individually(const QString& venv_name, const QStringList& packages,
const QStringList& env_vars, const QString& step_key) {
QString venv_python = python_path(venv_name);
@@ -942,12 +839,8 @@ QStringList PythonSetupManager::install_packages_individually(const QString& ven
return failed;
}
-// ─────────────────────────────────────────────────────────────────────────────
-// Find requirements file
-// ─────────────────────────────────────────────────────────────────────────────
-
QString PythonSetupManager::find_requirements_file(const QString& filename) const {
- // Return cached path — requirements files never move at runtime.
+ // Cached — requirements files never move at runtime.
auto it = cached_req_paths_.find(filename);
if (it != cached_req_paths_.end()) {
LOG_DEBUG("PythonSetup", "find_requirements_file cache hit: " + filename + " → " + it.value());
@@ -997,13 +890,8 @@ QString PythonSetupManager::find_requirements_file(const QString& filename) cons
return {};
}
-// ─────────────────────────────────────────────────────────────────────────────
-// Internal: configure and run a QProcess synchronously (background threads only)
-//
-// Both run_command() and run_command_capture() delegate here.
-// Returns true on exit-code 0; populates stderr_out (may be nullptr to discard).
-// ─────────────────────────────────────────────────────────────────────────────
-
+/// Sync QProcess shared by run_command / run_command_capture. Background threads only.
+/// Returns true on exit 0; stderr_out may be nullptr.
static bool run_process(const QString& program, const QStringList& args,
const QStringList& env_vars, QString* stderr_out) {
QProcess proc;
@@ -1025,7 +913,7 @@ static bool run_process(const QString& program, const QStringList& args,
#endif
proc.start(program, args);
- constexpr int kTimeoutMs = 30 * 60 * 1000; // 30 minutes
+ constexpr int kTimeoutMs = 30 * 60 * 1000;
if (!proc.waitForFinished(kTimeoutMs)) {
proc.kill();
if (stderr_out)
@@ -1039,10 +927,6 @@ static bool run_process(const QString& program, const QStringList& args,
return proc.exitCode() == 0;
}
-// ─────────────────────────────────────────────────────────────────────────────
-// Helper: run command (synchronous, used on background threads)
-// ─────────────────────────────────────────────────────────────────────────────
-
bool PythonSetupManager::run_command(const QString& program, const QStringList& args,
const QStringList& env_vars) const {
LOG_INFO("PythonSetup", QString("Running: %1 %2").arg(program, args.join(' ')));
@@ -1056,27 +940,18 @@ bool PythonSetupManager::run_command(const QString& program, const QStringList&
return ok;
}
-// ─────────────────────────────────────────────────────────────────────────────
-// Helper: run command, capture stderr (used for per-package failure diagnosis)
-// ─────────────────────────────────────────────────────────────────────────────
-
+/// Captures stderr — used for per-package failure diagnosis.
bool PythonSetupManager::run_command_capture(const QString& program, const QStringList& args,
const QStringList& env_vars, QString& stderr_out) const {
return run_process(program, args, env_vars, &stderr_out);
}
-// ─────────────────────────────────────────────────────────────────────────────
-// Helper: download file
-// ─────────────────────────────────────────────────────────────────────────────
-
QString PythonSetupManager::download_file(const QString& url, const QString& dest_path) const {
#ifdef _WIN32
- // Windows 10 1803+ ships curl.exe in System32. Try it first — clear errors,
- // --retry support, and starts much faster than spawning PowerShell.
+ // Win10 1803+ ships curl.exe — preferred over PowerShell for clearer errors and faster startup.
bool downloaded = false;
{
- // Probe for curl.exe availability (3-second timeout)
QString unused;
if (run_process("curl.exe", {"--version"}, {}, &unused)) {
QString curl_err;
@@ -1090,7 +965,6 @@ QString PythonSetupManager::download_file(const QString& url, const QString& des
}
if (!downloaded) {
- // Fallback: PowerShell Invoke-WebRequest
QString ps_err;
const QString ps_cmd =
QString("[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; "
@@ -1135,14 +1009,9 @@ QString PythonSetupManager::download_file(const QString& url, const QString& des
return {};
}
-// ─────────────────────────────────────────────────────────────────────────────
-// Requirements hash tracking
-// Detects when requirements files change across app versions so packages
-// can be re-synced without a full reinstall.
-// ─────────────────────────────────────────────────────────────────────────────
-
+/// Detects requirements changes across app versions so packages re-sync without a full reinstall.
QString PythonSetupManager::compute_requirements_hash(const QString& filename) const {
- // Return cached hash — requirements files never change at runtime.
+ // Cached — requirements files never change at runtime.
auto it = cached_req_hashes_.find(filename);
if (it != cached_req_hashes_.end())
return it.value();
@@ -1161,10 +1030,6 @@ QString PythonSetupManager::compute_requirements_hash(const QString& filename) c
return hash;
}
-// ─────────────────────────────────────────────────────────────────────────────
-// Emit progress (thread-safe)
-// ─────────────────────────────────────────────────────────────────────────────
-
void PythonSetupManager::emit_progress(const QString& step, int pct, const QString& msg, bool err) {
SetupProgress p{step, pct, msg, err};
LOG_INFO("PythonSetup", QString("[%1 %2%] %3").arg(step).arg(pct).arg(msg));
diff --git a/fincept-qt/src/screens/data_mapping/DataMappingScreen.cpp b/fincept-qt/src/screens/data_mapping/DataMappingScreen.cpp
index 14650efde..90f4809c3 100644
--- a/fincept-qt/src/screens/data_mapping/DataMappingScreen.cpp
+++ b/fincept-qt/src/screens/data_mapping/DataMappingScreen.cpp
@@ -267,7 +267,6 @@ struct MappingTemplate {
QString schema;
QStringList tags;
bool verified;
- // Real API details
QString base_url;
QString endpoint;
QString method;
@@ -649,7 +648,6 @@ void DataMappingScreen::setup_ui() {
root->addWidget(create_status_bar());
- // Default to list view
on_view_changed(0);
}
@@ -672,7 +670,6 @@ QWidget* DataMappingScreen::create_header() {
hl->addLayout(title_col);
hl->addSpacing(24);
- // View buttons
const QStringList views = {"MAPPINGS", "TEMPLATES", "CREATE"};
for (int i = 0; i < views.size(); ++i) {
auto* btn = new QPushButton(views[i]);
@@ -722,24 +719,21 @@ QWidget* DataMappingScreen::create_main_area() {
auto* splitter = new QSplitter(Qt::Horizontal);
splitter->setHandleWidth(1);
- // Left panel
auto* left = create_left_panel();
left->setMinimumWidth(180);
left->setMaximumWidth(220);
- // Center: view stack
auto* center = new QWidget(this);
auto* cvl = new QVBoxLayout(center);
cvl->setContentsMargins(0, 0, 0, 0);
cvl->setSpacing(0);
view_stack_ = new QStackedWidget;
- // Stack order must match header button order: MAPPINGS=0, TEMPLATES=1, CREATE=2
+ // Stack order must match header buttons: MAPPINGS=0, TEMPLATES=1, CREATE=2.
view_stack_->addWidget(create_list_view());
view_stack_->addWidget(create_template_view());
- // Create view contains step stack
auto* create_scroll = new QScrollArea;
create_scroll->setWidgetResizable(true);
auto* create_content = new QWidget(this);
@@ -759,7 +753,6 @@ QWidget* DataMappingScreen::create_main_area() {
view_stack_->addWidget(create_scroll);
cvl->addWidget(view_stack_, 1);
- // Right panel
auto* right = create_right_panel();
right->setMinimumWidth(190);
right->setMaximumWidth(220);
@@ -786,7 +779,6 @@ QWidget* DataMappingScreen::create_left_panel() {
title->setObjectName("dmPanelTitle");
vl->addWidget(title);
- // Step navigation
const QStringList step_labels = {"API Configuration", "Schema Selection", "Field Mapping", "Cache Settings",
"Test & Save"};
const QStringList step_icons = {"1", "2", "3", "4", "5"};
@@ -805,7 +797,6 @@ QWidget* DataMappingScreen::create_left_panel() {
vl->addStretch(1);
- // Quick stats
auto* stats = new QWidget(this);
auto* sl = new QVBoxLayout(stats);
sl->setContentsMargins(10, 8, 10, 8);
@@ -847,7 +838,6 @@ QWidget* DataMappingScreen::create_right_panel() {
il->setContentsMargins(10, 8, 10, 8);
il->setSpacing(6);
- // Engine status
auto* eng_title = new QLabel("MAPPING ENGINE");
eng_title->setObjectName("dmLabel");
il->addWidget(eng_title);
@@ -858,7 +848,6 @@ QWidget* DataMappingScreen::create_right_panel() {
il->addSpacing(8);
- // Parser list
auto* par_title = new QLabel("PARSER ENGINES");
par_title->setObjectName("dmLabel");
il->addWidget(par_title);
@@ -882,7 +871,6 @@ QWidget* DataMappingScreen::create_right_panel() {
il->addSpacing(8);
- // Current info
auto* cur_title = new QLabel("CURRENT MAPPING");
cur_title->setObjectName("dmLabel");
il->addWidget(cur_title);
@@ -912,7 +900,6 @@ QWidget* DataMappingScreen::create_api_config_panel() {
vl->setContentsMargins(0, 0, 0, 0);
vl->setSpacing(0);
- // Header
auto* hdr = new QWidget(this);
hdr->setObjectName("dmPanelHeader");
hdr->setFixedHeight(34);
@@ -972,7 +959,6 @@ QWidget* DataMappingScreen::create_api_config_panel() {
api_timeout_->setSuffix(" sec");
bl->addWidget(create_form_row("TIMEOUT", api_timeout_));
- // Test button + status
auto* test_row = new QWidget(this);
auto* trl = new QHBoxLayout(test_row);
trl->setContentsMargins(0, 0, 0, 0);
@@ -1030,7 +1016,6 @@ QWidget* DataMappingScreen::create_schema_panel() {
connect(schema_select_, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [this](int idx) {
if (idx >= 0 && idx < g_schemas.size()) {
schema_desc_->setText(g_schemas[idx].description);
- // Populate fields table
const auto& fields = g_schemas[idx].fields;
schema_fields_table_->setRowCount(fields.size());
for (int i = 0; i < fields.size(); ++i) {
@@ -1052,7 +1037,6 @@ QWidget* DataMappingScreen::create_schema_panel() {
schema_desc_->setWordWrap(true);
bl->addWidget(schema_desc_);
- // Fields table
schema_fields_table_ = new QTableWidget;
schema_fields_table_->setColumnCount(4);
schema_fields_table_->setHorizontalHeaderLabels({"Field", "Type", "Required", "Description"});
@@ -1062,7 +1046,6 @@ QWidget* DataMappingScreen::create_schema_panel() {
schema_fields_table_->setSelectionBehavior(QAbstractItemView::SelectRows);
schema_fields_table_->setMinimumHeight(200);
- // Populate with first schema
if (!g_schemas.isEmpty()) {
schema_select_->setCurrentIndex(0);
emit schema_select_->currentIndexChanged(0);
@@ -1094,18 +1077,15 @@ QWidget* DataMappingScreen::create_field_mapping_panel() {
hl->addWidget(t);
hl->addStretch(1);
- // Parser engine selector
parser_engine_ = new QComboBox;
parser_engine_->addItems({"JSONPath", "JSONata", "JMESPath", "Direct", "JavaScript", "Regex"});
hl->addWidget(new QLabel("Parser:"));
hl->addWidget(parser_engine_);
vl->addWidget(hdr);
- // Split: JSON tree | mapping table
auto* split = new QSplitter(Qt::Horizontal);
split->setHandleWidth(1);
- // JSON explorer
json_tree_ = new QTreeWidget;
json_tree_->setHeaderLabels({"Key", "Value", "Type"});
json_tree_->setColumnWidth(0, 160);
@@ -1113,7 +1093,6 @@ QWidget* DataMappingScreen::create_field_mapping_panel() {
json_tree_->setMinimumWidth(250);
split->addWidget(json_tree_);
- // Mapping table
mapping_table_ = new QTableWidget;
mapping_table_->setColumnCount(4);
mapping_table_->setHorizontalHeaderLabels({"Target Field", "Expression", "Transform", "Default"});
@@ -1166,7 +1145,6 @@ QWidget* DataMappingScreen::create_cache_panel() {
cache_ttl_->setSuffix(" sec");
bl->addWidget(create_form_row("CACHE TTL", cache_ttl_));
- // Security info
auto* sec_box = new QWidget(this);
sec_box->setStyleSheet(
QString("background: rgba(22,163,74,0.05); border: 1px solid %1; padding: 8px;").arg(colors::BORDER_DIM()));
@@ -1214,7 +1192,6 @@ QWidget* DataMappingScreen::create_test_save_panel() {
bl->setContentsMargins(12, 12, 12, 12);
bl->setSpacing(10);
- // Test controls
auto* test_row = new QWidget(this);
auto* trl = new QHBoxLayout(test_row);
trl->setContentsMargins(0, 0, 0, 0);
@@ -1233,7 +1210,6 @@ QWidget* DataMappingScreen::create_test_save_panel() {
trl->addStretch(1);
bl->addWidget(test_row);
- // Test output
test_output_ = new QTextEdit;
test_output_->setObjectName("dmTestOutput");
test_output_->setReadOnly(true);
@@ -1241,7 +1217,6 @@ QWidget* DataMappingScreen::create_test_save_panel() {
test_output_->setPlaceholderText("Test results will appear here...");
bl->addWidget(test_output_);
- // Save button
save_btn_ = new QPushButton("SAVE MAPPING CONFIGURATION");
save_btn_->setObjectName("dmSaveBtn");
save_btn_->setCursor(Qt::PointingHandCursor);
@@ -1292,11 +1267,9 @@ QWidget* DataMappingScreen::create_list_view() {
tbl->addWidget(new_btn);
vl->addWidget(toolbar);
- // Mapping list
mapping_list_ = new QListWidget;
vl->addWidget(mapping_list_, 1);
- // Empty state
auto* empty = new QLabel("No mappings saved yet.\nClick CREATE to build your first data mapping.");
empty->setObjectName("dmEmptyState");
empty->setAlignment(Qt::AlignCenter);
@@ -1312,7 +1285,6 @@ QWidget* DataMappingScreen::create_template_view() {
auto* split = new QSplitter(Qt::Horizontal);
split->setHandleWidth(1);
- // Template list
template_list_ = new QListWidget;
for (int i = 0; i < g_templates.size(); ++i) {
auto* item = new QListWidgetItem(g_templates[i].name);
@@ -1323,7 +1295,6 @@ QWidget* DataMappingScreen::create_template_view() {
connect(template_list_, &QListWidget::currentRowChanged, this, &DataMappingScreen::on_template_selected);
split->addWidget(template_list_);
- // Template detail
auto* detail_scroll = new QScrollArea;
detail_scroll->setWidgetResizable(true);
auto* detail_content = new QWidget(this);
@@ -1345,7 +1316,6 @@ QWidget* DataMappingScreen::create_template_view() {
int row = template_list_->currentRow();
if (row >= 0 && row < g_templates.size()) {
const auto& tmpl = g_templates[row];
- // Pre-populate all form fields from template
api_name_->setText(tmpl.name);
api_base_url_->setText(tmpl.base_url);
api_endpoint_->setText(tmpl.endpoint);
@@ -1356,7 +1326,6 @@ QWidget* DataMappingScreen::create_template_view() {
schema_select_->setCurrentText(tmpl.schema);
parser_engine_->setCurrentText(tmpl.parser);
- // Pre-populate field mapping table
mapping_table_->setRowCount(tmpl.field_mappings.size());
for (int i = 0; i < tmpl.field_mappings.size(); ++i) {
const auto& fm = tmpl.field_mappings[i];
@@ -1457,7 +1426,6 @@ QWidget* DataMappingScreen::create_status_bar() {
return bar;
}
-// ── Helpers ─────────────────────────────────────────────────────────────────
QWidget* DataMappingScreen::create_form_row(const QString& label_text, QWidget* input) {
auto* w = new QWidget(this);
@@ -1531,7 +1499,6 @@ void DataMappingScreen::populate_json_tree(const QJsonValue& val, QTreeWidgetIte
}
void DataMappingScreen::populate_mapping_list() {
- // Populate the mapping table with schema fields
int schema_idx = schema_select_->currentIndex();
if (schema_idx < 0 || schema_idx >= g_schemas.size())
return;
@@ -1548,7 +1515,6 @@ void DataMappingScreen::populate_mapping_list() {
}
}
-// ── Slots ───────────────────────────────────────────────────────────────────
void DataMappingScreen::on_view_changed(int view) {
current_view_ = view;
@@ -1563,7 +1529,7 @@ void DataMappingScreen::on_view_changed(int view) {
const QStringList names = {"MAPPINGS", "TEMPLATES", "CREATE"};
status_view_->setText("VIEW: " + names[view]);
- // Show/hide step bar and nav footer — CREATE is index 2
+ // CREATE is index 2 — show step bar + nav footer only there.
nav_footer_->setVisible(view == 2); // only in create mode
if (view == 2) {
@@ -1581,10 +1547,8 @@ void DataMappingScreen::on_step_changed(int step) {
step_stack_->setCurrentIndex(step);
update_step_indicators();
- // Populate field mapping table when entering step 2
if (step == 2) {
populate_mapping_list();
- // Populate JSON tree if we have sample data
if (!sample_data_.isNull()) {
json_tree_->clear();
populate_json_tree(sample_data_.isObject() ? QJsonValue(sample_data_.object())
@@ -1619,7 +1583,6 @@ void DataMappingScreen::on_test_api() {
api_test_btn_->setEnabled(false);
api_test_status_->setText("Testing...");
- // Use HttpClient for the test request
auto callback = [this](Result<QJsonDocument> result) {
api_test_btn_->setEnabled(true);
if (result.is_ok()) {
@@ -1662,7 +1625,6 @@ void DataMappingScreen::on_test_mapping() {
test_btn_->setEnabled(false);
test_status_->setText("Running test...");
- // Build a summary of the mapping configuration
QJsonObject summary;
summary["name"] = api_name_->text();
summary["schema"] = schema_select_->currentText();
@@ -1670,7 +1632,6 @@ void DataMappingScreen::on_test_mapping() {
summary["cache_enabled"] = cache_enabled_->currentIndex() == 0;
summary["cache_ttl"] = cache_ttl_->value();
- // Collect field mappings from the table
QJsonArray mappings;
for (int r = 0; r < mapping_table_->rowCount(); ++r) {
auto* expr_item = mapping_table_->item(r, 1);
@@ -1690,7 +1651,6 @@ void DataMappingScreen::on_test_mapping() {
summary["field_mappings"] = mappings;
summary["mapping_count"] = mappings.size();
- // Display test result
QJsonObject result;
result["success"] = mappings.size() > 0;
result["config"] = summary;
@@ -1815,7 +1775,6 @@ void DataMappingScreen::on_template_selected(int index) {
}
void DataMappingScreen::on_new_mapping() {
- // Reset form
api_name_->clear();
api_base_url_->clear();
api_endpoint_->clear();
@@ -1899,7 +1858,6 @@ void DataMappingScreen::build_mapping_config(QJsonObject& config) {
config["field_mappings"] = mappings;
}
-// ── IStatefulScreen ───────────────────────────────────────────────────────────
QVariantMap DataMappingScreen::save_state() const {
return {
@@ -1909,7 +1867,7 @@ QVariantMap DataMappingScreen::save_state() const {
void DataMappingScreen::restore_state(const QVariantMap& state) {
const int view = state.value("view", 0).toInt();
- // Only restore the list/templates view — don't resume a partial wizard
+ // Restore list/templates view only — never resume a partial wizard.
if (view == 0 || view == 1)
on_view_changed(view);
}