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
License Updated
tilakpatel2269ea48cb0403
diff --git a/README.md b/README.mdindex 68125b0c7..00322401f 100644--- a/README.md+++ b/README.md@@ -22,7 +22,7 @@State-of-the-art financial intelligence platform with CFA-level analytics, AI automation, and unlimited data connectivity.-[📥 Download](https://github.com/Fincept-Corporation/FinceptTerminal/releases) · [📚 Docs](https://github.com/Fincept-Corporation/FinceptTerminal/tree/main/docs) · [💬 Discussions](https://github.com/Fincept-Corporation/FinceptTerminal/discussions) · [💬 Discord](https://discord.gg/ae87a8ygbN) · [🤝 Partner](https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/docs/COMMERCIAL_LICENSE.md)+[📥 Download](https://github.com/Fincept-Corporation/FinceptTerminal/releases) · [⚖️ License](https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/docs/COMMERCIAL_LICENSE.md) · [💬 Discussions](https://github.com/Fincept-Corporation/FinceptTerminal/discussions) · [💬 Discord](https://discord.gg/ae87a8ygbN) · [🤝 Partner](https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/docs/COMMERCIAL_LICENSE.md)@@ -277,22 +277,25 @@ We're thinking long-term — and we hope you are too. That said, please only par## License-**Dual Licensed: AGPL-3.0 (Open Source) + Commercial**+> ⚠️ **Cloning, forking, or modifying this repository does NOT grant commercial rights.**+> A paid Commercial License is required for **any** business or internal company use — including forks that remove or replace Fincept's APIs with your own data sources. See **[Commercial License](https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/docs/COMMERCIAL_LICENSE.md)** for binding terms.-### Open Source (AGPL-3.0)-- Free for personal, educational, and non-commercial use-- Requires sharing modifications when distributed or used as network service-- Full source code transparency+**Dual Licensed: AGPL-3.0 (Open Source) + Fincept Commercial License**-### Commercial License-- Required for business use or to access Fincept Data/APIs commercially-- Contact: **[email protected]**-- Details: [Commercial License Guide](https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/docs/COMMERCIAL_LICENSE.md)+| | |+|---|---|+| ✅ **Free under AGPL-3.0** | Personal use · Individual learning · Academic research · Open-source contributions to this repository |+| ❌ **Commercial License required** | Any business use (paid or free) · Internal company use · Startups at any stage · Hedge funds, brokerages, banks, fintechs · SaaS / hosted offerings · White-label or reselling · Forks that strip or replace Fincept APIs · Consulting deliverables · Employee training or evaluation by for-profit entities |-### Trademarks-"Fincept Terminal" and "Fincept" are trademarks of Fincept Corporation.+The license attaches to the **codebase and any Derivative Work of it**, not to specific API integrations. Substituting Fincept APIs with your own — or with any third party's — does not sever or extinguish the licensing obligation.-© 2025-2026 Fincept Corporation. All rights reserved.+**Trademarks.** "Fincept", "Fincept Terminal", and the Fincept logo are trademarks of Fincept Corporation. Use in any forked, derivative, rebranded, or commercial product requires prior written permission. Removal or rebranding of these marks in a fork does not extinguish the underlying licensing obligation.++**Enforcement & Penalties.** Fincept Corporation actively monitors public repositories, app stores, cloud marketplaces, and SaaS platforms for unlicensed Commercial Use, and pursues DMCA takedowns, cease-and-desist notices, and civil action under Indian and international law. Unauthorized commercial use is subject to **liquidated damages starting at USD 50,000 per organization per year**, with higher amounts for unauthorized SaaS distribution, fork-and-replace deployments, and trademark misuse — in addition to backdated license fees, disgorgement of profits, and recovery of legal costs. **Joint and several liability** applies: any company that engages a third-party developer, integrator, or consultancy to build, modify, or deploy the Software is fully liable alongside that developer for any unauthorized use. Governing law: India · Exclusive jurisdiction: Delhi, India.++**Contact for licensing:** [email protected] · Full terms: [docs/COMMERCIAL_LICENSE.md](https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/docs/COMMERCIAL_LICENSE.md)++© 2025–2026 Fincept Corporation. All rights reserved.---diff --git a/docs/COMMERCIAL_LICENSE.md b/docs/COMMERCIAL_LICENSE.mdindex fea6f6825..a1601bc73 100644--- a/docs/COMMERCIAL_LICENSE.md+++ b/docs/COMMERCIAL_LICENSE.md@@ -1,77 +1,250 @@-# Commercial & Educational Licensing+# Fincept Terminal — Commercial License-## Overview+**Effective Date:** April 30, 2026+**Licensor:** Fincept Corporation (a company organized under the laws of India)+**Contact:** [email protected] · +91-9773034108 · https://fincept.in-Fincept Terminal is dual-licensed under **AGPL-3.0** (free for personal/educational use) and **Commercial License** (required for business use).+---++## 1. Notice — Read First++> ⚠️ **Cloning, forking, downloading, building, or modifying this repository does NOT grant any right to use Fincept Terminal — or any Derivative Work of it — for Commercial Use.**+> A separate, paid Commercial License executed with Fincept Corporation is required for any Commercial Use, including **internal use within any for-profit organization**, even where Fincept's data sources, APIs, or service endpoints have been removed, replaced, or rewired.++This document is a plain-language summary **and** the operative commercial-licensing terms of Fincept Terminal. It supplements — and in case of conflict, governs over — the AGPL-3.0 license under which the Software is also made available for non-commercial purposes.++---++## 2. Dual-License Structure++Fincept Terminal is offered under **two licenses**, and a user must comply with **one** of them:++1. **GNU Affero General Public License v3.0 (AGPL-3.0)** — for personal, educational, individual non-commercial use, and open-source contribution. Full text: [`/LICENSE`](../LICENSE).+2. **Fincept Commercial License** — for any Commercial Use, as defined in Section 4 below. Required for businesses, startups, funds, brokerages, and any internal corporate use, regardless of revenue.++**The AGPL-3.0 option is not available for Commercial Use.** A user engaging in Commercial Use without a Commercial License is in breach of copyright and subject to the enforcement remedies in Section 12.++---++## 3. Definitions++For the purposes of this License, the following capitalized terms apply:++- **"Software"** means the source code, object code, binaries, scripts, configuration, documentation, and assets contained in the Fincept Terminal repository at https://github.com/Fincept-Corporation/FinceptTerminal, in any branch, tag, release, or commit, in whole or in part.++- **"Modified Version"** means any version of the Software that has been altered, including by the addition, removal, replacement, rewiring, or substitution of any module, file, function, API, data integration, or service endpoint.++- **"Derivative Work"** means any software, in source or object form, that is based on, incorporates, links to (statically or dynamically), wraps, calls into, embeds, or substantially reproduces the Software or any portion thereof, including any version produced by: (i) compilation of the Software's source tree with or without modification; (ii) replacement, removal, disabling, or rewiring of any module, API, data integration, or service endpoint while retaining any other portion of the Software; (iii) translation, porting, or rewriting of any part of the Software into another programming language while preserving its architecture, screen layouts, workflow, or feature set; or (iv) any work whose primary purpose, value, or functionality is materially derived from the Software.++- **"Commercial Use"** means any use of the Software or any Modified Version or Derivative Work, in whole or in part, by, for, or on behalf of any for-profit entity, governmental body, non-profit operating in revenue-generating activity, or any individual acting in the course of employment or contracting for any such entity. Commercial Use includes, without limitation: (a) **internal use** within an organization, regardless of whether the Software is exposed to third parties; (b) use during evaluation, proof-of-concept, pilot, research and development, or training of employees or contractors; (c) use to support, augment, replace, or supplement any product or service offered by Licensee or its affiliates, whether or not such product or service is sold; (d) use on hardware owned, leased, or operated by a for-profit entity; (e) use of any Modified Version, including any version in which Fincept-provided data sources, APIs, integrations, or service endpoints have been removed, replaced, rewired, or substituted with Licensee's or any third party's data sources, APIs, integrations, or service endpoints. **The substitution of data sources or APIs does not, in any circumstance, convert Commercial Use into non-Commercial Use.**++- **"Fincept Marks"** means the names, logos, and trade dress "Fincept", "Fincept Terminal", "Fincept Corporation", and any colorable imitation, transliteration, abbreviation, translation, or variation or derivative thereof.++- **"Fincept Trade Dress"** means the distinctive look and feel of Fincept Terminal, including screen layouts, color palette, terminal command syntax, ticker conventions, function-code conventions, keyboard shortcut conventions, dashboard widget vocabulary, and overall visual identity.++- **"Licensor"** means Fincept Corporation. **"Licensee"** means the natural or legal person exercising rights under this License.++---++## 4. When a Commercial License Is Required++A Commercial License is required for **all** of the following — there are no exceptions and no carve-outs for revenue, size, or duration:++- Any business use, paid or free, with revenue or without revenue+- **Internal use within any company, fund, government body, or for-profit organization** — even if the Software is never exposed to third parties, even after Fincept APIs have been removed or replaced+- Startups at any stage — pre-revenue, pre-product, pre-seed, evaluation, pilot, or proof-of-concept+- Hedge funds, proprietary trading firms, banks, brokerages, asset managers, family offices, fintechs, and exchanges+- SaaS, PaaS, IaaS, or any hosted, managed, or cloud offering of the Software or a Derivative Work+- White-label, OEM, rebranded, or resold distributions of the Software or a Derivative Work+- Forks that strip out, replace, disable, or rewire Fincept APIs, data sources, or service endpoints, when used for Commercial Use+- Consulting, professional services, system-integrator, or contractor deliverables that include or rely on the Software+- Training, evaluation, demonstration, or onboarding of employees or contractors of any for-profit entity+- Any use that competes with, substitutes for, or substantially replicates the functionality of Fincept Terminal or any product or service offered by Licensor++If you are uncertain, **assume a Commercial License is required** and contact [email protected].++---++## 5. What Cloning, Forking, or Modifying the Repository Does *Not* Grant++The AGPL-3.0 grant attached to the public repository permits a user, for non-commercial purposes only, to view, study, modify, and redistribute the Software under AGPL-3.0 terms. **It does not grant any of the following**, all of which require a separate Commercial License:++1. The right to run the Software inside a company, fund, government body, or any for-profit organization for any purpose, internal or external+2. The right to use the Software, in any form, in support of any revenue-generating, business, professional, or operational activity+3. The right to remove, replace, disable, or rewire Fincept's APIs, data integrations, or service endpoints and then use the resulting Modified Version or Derivative Work commercially or internally+4. The right to use, reproduce, or imitate any of the Fincept Marks or Fincept Trade Dress in any forked, derivative, rebranded, or successor product+5. The right to relicense, sublicense, sell, lease, or offer paid access to the Software or any Derivative Work+6. Any rights in or to Fincept-operated data services, API endpoints, hosted infrastructure, or proprietary datasets++The license attaches to the **codebase and any Derivative Work of it**, not to specific API integrations. **Substituting Fincept APIs with your own — or with any third party's — does not sever or extinguish the licensing obligation.**++---++## 6. Trademark and Trade Dress++Licensee shall not use the Fincept Marks in connection with any product, service, repository, distribution, or marketing, except as expressly authorized in advance and in writing by Licensor. **Removal, replacement, or rebranding of the Fincept Marks in any fork or Derivative Work does not extinguish Licensor's rights in the underlying Software, nor does it sever the licensing obligations attaching to the codebase.**++Licensee acknowledges that the value of the Fincept Marks lies not only in the literal trademark text but in the Fincept Trade Dress. Licensee shall not, in any forked, derivative, or successor product, replicate the Fincept Trade Dress in a manner likely to cause confusion, mistake, deception, association, or initial-interest confusion as to source or affiliation, even where the literal Fincept Marks have been removed or replaced. Any product that retains substantially similar Fincept Trade Dress shall be deemed a Derivative Work for all purposes of this License, and any Commercial Use thereof requires a Commercial License from Licensor.++Any Derivative Work that is publicly distributed in source-available form shall prominently display the notice: *"Derived from Fincept Terminal © Fincept Corporation; use of this Derivative Work for Commercial Use requires a separate Commercial License from Fincept Corporation, [email protected]."*++---++## 7. Pricing-Commercial licensing is required to access Fincept Data Sources and APIs for business use.+| Plan | Fee | Includes |+|------|-----|----------|+| **Commercial License** | **USD 10,200 / year** per organization | Full Commercial Use rights for one legal entity; Fincept Data & API access; 65,000 credits/month (resets monthly); additional credits available for purchase |+| **Technical Support** *(optional add-on)* | **USD 149 / month** | Priority support, direct technical assistance, faster response times |+| **University & Academic** | **USD 799 / month** | 20 accounts for teaching and research at an accredited educational institution; Fincept Data access included; non-commercial classroom use only |+| **Custom Enterprise** | Contact for pricing | Tailored requirements, custom integrations, higher credit limits, dedicated support, custom SLAs, source-available agreements |++Credits are consumed by Fincept Data Sources and API calls. When credits are exhausted, Licensee may purchase additional credits or wait for the monthly reset. Fees are payable annually in advance and non-refundable except as expressly stated.----## Do I Need a Commercial License?+## 8. Patent Grant and Patent Retaliation++Subject to the terms of this License, Licensor grants Licensee a non-exclusive, worldwide, royalty-bearing license under Licensor's patent claims to make, have made, use, offer to sell, sell, import, and have imported the Software, solely as authorized hereunder.++**If Licensee, or any entity controlling, controlled by, or under common control with Licensee, institutes patent litigation (including a cross-claim or counterclaim in a lawsuit) against any entity alleging that the Software, its use, or any contribution to it constitutes direct or contributory patent infringement, then any patent licenses granted to Licensee under this License shall terminate as of the date such litigation is filed.** Patent claims arising from modifications introduced by Licensee are not licensed.-**Free (No License Needed):** Personal use & learning, Individual students, Open source contributions, Using your own data sources+---++## 9. Audit Rights-**Commercial License Required:** Any business use, Startups (even $0 revenue), Internal company use, Using Fincept Data/APIs commercially, SaaS/Cloud platforms, White-label/Reselling+Licensor may, upon thirty (30) days' written notice and not more than once per twelve (12) month period (except where Licensor reasonably suspects breach), audit Licensee's use of the Software through a mutually agreed independent auditor bound by confidentiality. Licensee shall provide reasonable cooperation, including access to deployment records, user counts, infrastructure inventories, and source repositories containing the Software or Derivative Works. If the audit reveals underpayment exceeding five percent (5%) or any unauthorized Commercial Use, Licensee shall pay (a) the unpaid fees calculated retroactively at the then-current rate, (b) interest at 18% per annum or the maximum permitted by law, whichever is lower, and (c) the reasonable costs of the audit.----## Pricing+## 10. Termination and Survival++This License terminates automatically and without notice upon any breach by Licensee of any provision. Termination does not relieve Licensee of accrued obligations, including unpaid fees. Upon termination, Licensee shall immediately cease all use, destroy all copies of the Software and all Derivative Works in its possession or control, and certify such destruction in writing within fifteen (15) days.++The following provisions survive termination: Sections 3 (Definitions), 5 (No Implied Grant), 6 (Trademark and Trade Dress), 8 (Patent Retaliation), 9 (Audit, for two years post-termination), 11 (Disclaimer), 12 (Enforcement), 13 (Liquidated Damages and Penalties), 14 (Joint and Several Liability), 15 (Limitation of Liability), 16 (Governing Law), and this Section 10.++---++## 11. Disclaimer of Warranties++THE SOFTWARE IS PROVIDED "AS IS" AND "AS AVAILABLE," WITHOUT WARRANTY OF ANY KIND, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, ACCURACY, RELIABILITY, OR THAT THE SOFTWARE WILL BE UNINTERRUPTED OR ERROR-FREE. NO INFORMATION OR ADVICE OBTAINED FROM LICENSOR SHALL CREATE ANY WARRANTY NOT EXPRESSLY STATED HEREIN. THE SOFTWARE IS NOT INTENDED FOR USE IN, AND IS NOT WARRANTED FOR USE IN, ANY APPLICATION WHERE FAILURE COULD RESULT IN FINANCIAL LOSS, REGULATORY VIOLATION, OR PERSONAL INJURY. NOTHING IN THE SOFTWARE OR ANY OUTPUT GENERATED BY IT CONSTITUTES INVESTMENT, LEGAL, TAX, ACCOUNTING, OR FINANCIAL ADVICE.++---++## 12. Enforcement++Licensor actively monitors public code repositories, container registries, application stores, cloud marketplaces, SaaS platforms, and trademark registers for unlicensed Commercial Use of the Software, Modified Versions, and Derivative Works. Licensor reserves the right, without prior notice, to:++1. Issue takedown notices under the U.S. Digital Millennium Copyright Act (17 U.S.C. § 512), the Information Technology Act, 2000 (India) §§ 65 and 66, the Copyright Act, 1957 (India) §§ 63–63B, and equivalent statutes in other jurisdictions;+2. Issue cease-and-desist letters to violating organizations and their officers, directors, and counsel;+3. Seek injunctive and monetary relief, including statutory damages, disgorgement of profits, and recovery of unpaid license fees calculated at the then-current Commercial License rate retroactive to first unauthorized use, plus interest, attorneys' fees, and costs;+4. Pursue trademark infringement, passing-off, and unfair-competition claims for misuse of the Fincept Marks or Fincept Trade Dress;+5. Pursue criminal complaints where applicable under the Copyright Act, 1957 (India) §§ 63–63B and equivalent foreign laws.++If you believe you may be using the Software commercially without a license, contact **[email protected]** for a good-faith resolution path.++---++## 13. Liquidated Damages and Penalties for Unauthorized Use++The parties acknowledge that actual damages from unauthorized Commercial Use are difficult to calculate, and that the following amounts are a reasonable pre-estimate of loss and not a penalty. Any party engaged in unauthorized Commercial Use of the Software, a Modified Version, or a Derivative Work shall be liable to Licensor for liquidated damages, in addition to all other remedies available in law or equity:-**Commercial License - $10,200/year**-- Fincept Data & API Access (Full access)-- 65,000 credits/month (resets monthly)-- Additional credits available for purchase+| Violation | Liquidated Damages |+|-----------|-------------------|+| **Unauthorized internal corporate use** (per organization, per year of use) | **USD 50,000** or 5× the then-current Commercial License fee, **whichever is greater** |+| **Unauthorized commercial distribution, hosting, SaaS, or resale** of the Software or any Derivative Work | **USD 250,000** per distinct offering, plus disgorgement of all revenue derived therefrom |+| **Unauthorized fork that replaces, removes, or rewires Fincept APIs and is used commercially or internally** | **USD 100,000** per organization, plus 5× the then-current Commercial License fee for each year of use, plus full backdated license fees from first unauthorized use |+| **Unauthorized use of Fincept Marks or Fincept Trade Dress** in a forked, derivative, or rebranded product | **USD 150,000** per mark or trade-dress element, plus mandatory injunction, plus disgorgement of profits |+| **Failure to comply with audit obligations** under Section 9 | **USD 25,000** per audit cycle, plus full audit costs |+| **Continued use after notice of breach or termination** | **USD 10,000 per day** until cessation is verified, plus all enforcement costs |-**Technical Support (Optional) - $149/month**-- Priority support, Direct technical assistance, Faster response times+In addition to liquidated damages, Licensor is entitled to recover:-**University & Academic - $799/month**-- 20 accounts for teaching & research-- Fincept Data Access included-- For accredited educational institutions only+1. All unpaid license fees, calculated retroactively at the then-current Commercial License rate from the date of first unauthorized use, plus interest at 18% per annum or the maximum permitted by law, whichever is lower;+2. Disgorgement of all profits, revenue, cost savings, and any other economic benefit derived by the violator from unauthorized use;+3. All attorneys' fees, court fees, expert fees, investigation costs, and other costs of enforcement;+4. Statutory damages and any additional remedies available under the Copyright Act, 1957 (India), the Trade Marks Act, 1999 (India), the Information Technology Act, 2000 (India), the U.S. Copyright Act (17 U.S.C.), the Lanham Act (15 U.S.C. § 1051 et seq.), and equivalent statutes in any applicable jurisdiction;+5. Punitive and exemplary damages where permitted by law, particularly for willful or repeated violations.-**Custom Enterprise - Contact for pricing**-- Tailored requirements, Custom integrations, Higher credit limits, Dedicated support, Custom SLAs+The liquidated damages stated above are **per violation, cumulative**, and apply **per year of unauthorized use**. Liquidated damages do not constitute a license fee, do not retroactively legitimize unauthorized use, and do not waive Licensor's right to seek injunctive relief, criminal prosecution, or any other remedy.----## Credits+## 14. Joint and Several Liability of Contracting Companies, Developers, Integrators, and Affiliates-Credits are used for Fincept Data Sources and API calls.+**Any organization that engages, hires, contracts with, instructs, or otherwise uses a third party — including but not limited to software development firms, system integrators, IT consultancies, contractors, freelancers, outsourcing vendors, offshore development centers, white-label developers, or value-added resellers (collectively, "Third-Party Developers") — to build, modify, deploy, host, customize, fork, port, rebrand, or otherwise work with the Software, a Modified Version, or any Derivative Work shall be jointly and severally liable with such Third-Party Developer for any unauthorized Commercial Use, breach of this License, or infringement of Licensor's intellectual property.**-- **Commercial:** 65,000/month-- **University:** Included in plan-- **Custom:** Based on agreement+Without limiting the generality of the foregoing:-When credits run out: Purchase additional credits OR wait for monthly reset.+1. **Joint and Several Liability.** The contracting company (the entity for whose benefit the work is performed) and each Third-Party Developer engaged by it (and any subcontractor of such Third-Party Developer) are each fully liable, individually and together, for the entirety of any damages, liquidated damages, license fees, disgorgement, and costs owed to Licensor. Licensor may pursue any one or more of them, in any combination, for the full amount.++2. **No Defense of Delegation.** A contracting company cannot escape liability by claiming that the Third-Party Developer was solely responsible, that the contracting company did not write the code, that the Third-Party Developer represented the work as licensed, or that the contracting company did not know the Software was Fincept Terminal or a Derivative Work. The duty to verify license compliance is **non-delegable**.++3. **No Defense of Lack of Knowledge.** Public availability of this License, the LICENSE file, the README, and the license notices embedded in the Software constitutes constructive notice. Ignorance of the license terms is not a defense for either the contracting company or the Third-Party Developer.++4. **Affiliates and Successors.** Liability extends to all parents, subsidiaries, affiliates, successors, assignees, joint-venture partners, and acquirers of the contracting company and the Third-Party Developer. Corporate restructuring, asset transfers, name changes, dissolutions, mergers, acquisitions, or share sales do not extinguish liability.++5. **Officers, Directors, and Principals.** Where permitted by applicable law, Licensor reserves the right to pursue claims against the officers, directors, partners, and controlling shareholders of any violating entity for willful infringement, breach of fiduciary duty in connection with the infringement, or fraudulent concealment.++6. **Indemnification by the Contracting Company.** The contracting company shall indemnify, defend, and hold harmless Licensor from and against any and all claims, losses, damages, fees, and costs arising from the acts or omissions of any Third-Party Developer it engages, regardless of whether the contracting company directed, knew of, or consented to such acts.++7. **Right to Joinder.** In any action against a Third-Party Developer, Licensor may, at its sole election, join the contracting company (and vice versa) as a co-defendant in the same proceeding, and the parties consent in advance to such joinder.++8. **Public Notice Obligation.** Upon Licensor's request, a contracting company that engages a Third-Party Developer to work with the Software must provide Licensor, within ten (10) business days, with: (a) the legal name and contact details of the Third-Party Developer; (b) the scope of work; (c) copies of the relevant engagement agreement or statement of work redacted only as to commercial pricing terms; and (d) a list of all repositories, deployment locations, and personnel with access to the Software.++9. **No Subcontracting Out of Liability.** Any contractual provision between a contracting company and a Third-Party Developer that purports to allocate or waive liability to Licensor — including indemnities, hold-harmless agreements, or "as-is" disclaimers running between them — shall have no effect against Licensor, who is not a party to such agreement.++This Section 14 is a **material term** of this License. Any breach of it constitutes immediate grounds for termination, injunctive relief, and the maximum liquidated damages set forth in Section 13.----## How to Get Started+## 15. Limitation of Liability-1. **Contact Us** - Email [email protected] with company name, use case, and number of users-2. **Agreement** - Review and sign license agreement, complete payment-3. **Access** - Receive credentials and access Fincept Data & APIs+TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, IN NO EVENT SHALL LICENSOR'S AGGREGATE LIABILITY UNDER OR IN CONNECTION WITH THIS LICENSE EXCEED THE TOTAL FEES PAID BY LICENSEE TO LICENSOR IN THE TWELVE (12) MONTHS IMMEDIATELY PRECEDING THE EVENT GIVING RISE TO LIABILITY, OR ONE HUNDRED INDIAN RUPEES (₹100), WHICHEVER IS GREATER. IN NO EVENT SHALL LICENSOR BE LIABLE FOR INDIRECT, INCIDENTAL, SPECIAL, CONSEQUENTIAL, EXEMPLARY, OR PUNITIVE DAMAGES, LOST PROFITS, LOST DATA, LOSS OF GOODWILL, OR TRADING LOSSES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS APPLY REGARDLESS OF THE FORM OF ACTION, WHETHER IN CONTRACT, TORT, STRICT LIABILITY, OR OTHERWISE.----## Contact+## 16. Governing Law and Jurisdiction-**Email:** [email protected] | **Phone:** +91-9773034108 | **Website:** https://fincept.in+This License shall be governed by and construed in accordance with the laws of the Republic of India, without regard to its conflict-of-laws principles. The United Nations Convention on Contracts for the International Sale of Goods does not apply. The courts of **Delhi, India** shall have exclusive jurisdiction over any dispute arising out of or relating to this License, and Licensee irrevocably submits to the personal jurisdiction of such courts and waives any objection of inconvenient forum. Notwithstanding the foregoing, Licensor may seek injunctive or equitable relief in any court of competent jurisdiction worldwide to protect its intellectual property.----## Terms+## 17. General Provisions++**Severability.** If any provision of this License is held invalid or unenforceable, the remaining provisions shall remain in full force and the invalid provision shall be reformed to the minimum extent necessary to make it enforceable while preserving its intent.++**Entire Agreement.** This License, together with any executed Order Form, constitutes the entire agreement between the parties and supersedes all prior or contemporaneous communications, oral or written, on the subject matter.-Licenses are non-transferable. Annual licenses renew yearly. Refunds within 30 days if credits are unused. Fincept Corporation reserves right to modify pricing.+**No Waiver.** No failure or delay by Licensor to exercise any right shall operate as a waiver, nor shall any single or partial exercise preclude any other or further exercise.-## Trademark+**Assignment.** Licensee may not assign or transfer this License, by operation of law or otherwise, without Licensor's prior written consent. Any attempted assignment in violation of this provision is void. Licensor may assign this License freely.-"Fincept", "Fincept Terminal", and the Fincept logo are trademarks of Fincept Corporation. Use requires written permission.+**Force Majeure.** Neither party is liable for failure to perform due to causes beyond its reasonable control, excluding payment obligations.++**Notices.** Notices to Licensor must be sent to [email protected] with a copy by registered post to Fincept Corporation's registered office.++**Export Controls.** Licensee shall comply with all applicable export-control laws of India, the United States, the European Union, and any other applicable jurisdiction.++**Non-Transferability.** Licenses are non-transferable. Annual licenses renew yearly unless cancelled with thirty (30) days' notice prior to the renewal date.++---++## 18. How to Obtain a Commercial License++1. **Contact** — email **[email protected]** with: (a) legal name of the organization, (b) country of incorporation, (c) intended use case, (d) number of users, (e) whether you are using or plan to use a Modified Version or Derivative Work.+2. **Agreement** — review and execute the Commercial License Agreement (this document, formalized as an Order Form).+3. **Payment** — complete payment in accordance with the Order Form.+4. **Access** — receive credentials and Commercial Use rights.----**Last Updated:** March 2026+## Trademark Notice++"Fincept", "Fincept Terminal", and the Fincept logo are trademarks of Fincept Corporation. All rights reserved. Use of these marks — including in any forked, derivative, rebranded, or commercial product — requires prior written permission.++© 2025–2026 Fincept Corporation. All rights reserved.++**Last Updated:** April 30, 2026-For full license terms, see [LICENSE](../LICENSE).+For the open-source license terms, see [`/LICENSE`](../LICENSE).diff --git a/fincept-qt/CMakeLists.txt b/fincept-qt/CMakeLists.txtindex 61c4f4865..c771a86b5 100644--- a/fincept-qt/CMakeLists.txt+++ b/fincept-qt/CMakeLists.txt@@ -728,6 +728,13 @@ set(MCP_SOURCESsrc/mcp/McpClient.cppsrc/mcp/McpManager.cppsrc/mcp/McpInit.cpp+ src/mcp/SchemaValidator.cpp+ src/mcp/ToolFilterPolicy.cpp++ # Phase 5 — provider-neutral tool-call dispatcher + adapters.+ src/mcp/dispatch/ToolDispatcher.cpp+ src/mcp/dispatch/OpenAiAdapter.cpp+ src/mcp/dispatch/AdapterFactory.cpp# Tool modulessrc/mcp/tools/NavigationTools.cpp@@ -751,6 +758,7 @@ set(MCP_SOURCESsrc/mcp/tools/SystemTools.cppsrc/mcp/tools/DataHubTools.cppsrc/mcp/tools/ReportBuilderTools.cpp+ src/mcp/tools/MetaTools.cpp)# Trading@@ -899,6 +907,14 @@ set(SERVICE_SOURCES# Speech-to-text service (Python speech_recognition + Google API)src/services/stt/SpeechService.cpp+ # Text-to-speech service (Python pyttsx3 — used as a portable substitute+ # for Qt6::TextToSpeech when the Qt Speech module isn't installed).+ src/services/tts/TtsService.cpp++ # Clap-to-start trigger — lightweight pyaudio loop that fires a signal+ # when it hears a (double-)clap. Wakes up the AiChatBubble mic.+ src/services/voice_trigger/ClapDetectorService.cpp+# Modular notification system — service + 15 providerssrc/services/notifications/NotificationService.cppsrc/services/notifications/providers/TelegramProvider.cpp@@ -1643,6 +1659,11 @@ set_source_files_properties(src/mcp/McpClient.cppsrc/mcp/McpManager.cppsrc/mcp/McpInit.cpp+ src/mcp/SchemaValidator.cpp+ src/mcp/ToolFilterPolicy.cpp+ src/mcp/dispatch/ToolDispatcher.cpp+ src/mcp/dispatch/OpenAiAdapter.cpp+ src/mcp/dispatch/AdapterFactory.cppsrc/mcp/tools/NavigationTools.cppsrc/mcp/tools/MarketsTools.cppsrc/mcp/tools/WatchlistTools.cpp@@ -1662,6 +1683,7 @@ set_source_files_properties(src/mcp/tools/SettingsTools.cppsrc/mcp/tools/PythonTools.cppsrc/mcp/tools/SystemTools.cpp+ src/mcp/tools/MetaTools.cppPROPERTIES SKIP_UNITY_BUILD_INCLUSION TRUE)diff --git a/fincept-qt/_build_netspeed.bat b/fincept-qt/_build_netspeed.batdeleted file mode 100644index 003367979..000000000--- a/fincept-qt/_build_netspeed.bat+++ /dev/null@@ -1,4 +0,0 @@-@echo off-call "C:\Program Files\Microsoft Visual Studio\2022\Preview\VC\Auxiliary\Build\vcvars64.bat" >nul-cmake --build --preset win-release 2>&1-exit /b %errorlevel%diff --git a/fincept-qt/_build_voice.bat b/fincept-qt/_build_voice.batdeleted file mode 100644index 94ef84d1b..000000000--- a/fincept-qt/_build_voice.bat+++ /dev/null@@ -1,5 +0,0 @@-@echo off-cd /d C:\windowsdisk\finceptTerminal\fincept-qt-call "C:\Program Files\Microsoft Visual Studio\2022\Preview\VC\Auxiliary\Build\vcvars64.bat" >nul 2>&1-cmake --build --preset win-release > build_voice.log 2>&1-exit /b %ERRORLEVEL%diff --git a/fincept-qt/docs/DATAHUB_TOPICS.md b/fincept-qt/docs/DATAHUB_TOPICS.mdindex e6d06c09c..55ebe6f66 100644--- a/fincept-qt/docs/DATAHUB_TOPICS.md+++ b/fincept-qt/docs/DATAHUB_TOPICS.md@@ -75,7 +75,7 @@ plan's risk-mitigation cadence).| Pattern | Producer | TTL | Min interval | Notes ||---|---|---|---|---|-| `geopolitics:events` | `GeopoliticsService` | 2 min | 30 s | Conflict monitor news events (default params) |+| `geopolitics:events` | `GeopoliticsService` | 2 min | 30 s | Conflict monitor news events (default params). Payload: `EventsPage` (events sorted newest-first + pagination + credits metering). || `geopolitics:countries` | `GeopoliticsService` | 10 min | 60 s | Unique country list w/ event counts || `geopolitics:categories` | `GeopoliticsService` | 10 min | 60 s | Unique event category list || `geopolitics:cities` | `GeopoliticsService` | 10 min | 60 s | Cities with extracted coordinates |@@ -88,10 +88,11 @@ plan's risk-mitigation cadence).| Pattern | Producer | TTL | Min interval | Notes ||---|---|---|---|---|-| `maritime:vessel:<imo>` | `MaritimeService` | 1 min | 30 s | Single vessel position |-| `maritime:vessels:multi` | `MaritimeService` | 1 min | 30 s | Batch vessel snapshot (default preset IMO list) |-| `maritime:history:<imo>` | `MaritimeService` | 5 min | 60 s | Vessel route history |-| `maritime:health` | `MaritimeService` | 5 min | 60 s | Marine API health check |+| `maritime:vessel:<imo>` | `MaritimeService` | 1 min | 30 s | Single vessel position. Payload: `VesselData`. |+| `maritime:vessels:multi` | `MaritimeService` | 1 min | 30 s | Multi-vessel batch (caller supplies IMOs). Payload: `VesselsPage` (vessels + found_count + not_found list + credits metering). User-invoked — hub does not auto-refresh. |+| `maritime:vessels:area` | `MaritimeService` | 1 min | 30 s | Area-search bounding box. Payload: `VesselsPage` (vessels sorted newest-first, total_count, credits metering). User-invoked. |+| `maritime:history:<imo>` | `MaritimeService` | 5 min | 60 s | Vessel route history. Payload: `VesselHistoryPage` (history sorted newest-first + total_records + credits metering). |+| `maritime:health` | `MaritimeService` | 5 min | 60 s | Marine API health check. |### M&A Analyticsdiff --git a/fincept-qt/docs/MCP_TOOLS_GUIDE.md b/fincept-qt/docs/MCP_TOOLS_GUIDE.mdnew file mode 100644index 000000000..fa75165cf--- /dev/null+++ b/fincept-qt/docs/MCP_TOOLS_GUIDE.md@@ -0,0 +1,228 @@+# MCP Tools — Author & Maintainer Guide++This guide documents how the Model Context Protocol (MCP) tool system works+inside Fincept Terminal after the 6-phase refactor (see+`fincept-qt/plans/mcp-refactor-INDEX.md`).++If you are adding a new tool, jump to **§5 Adding a new tool**. If you are+debugging why an LLM call isn't hitting your tool, jump to **§6 Diagnosis**.++---++## 1. Architecture++```+ ┌──────────────────────────────────────────────┐+ │ LlmService │+ │ (HTTP / streaming — provider-agnostic) │+ └─────────┬────────────────────────────────────┘+ │ via ToolDispatcher (Phase 5)+ ▼+ ┌──────────────────────────────────────────────┐+ │ ToolDispatcher │+ │ multi-round loop, parallel tool fan-out │+ └─────────┬────────────────────────────────────┘+ │+ ▼+ ┌────────────────────────────────────┐+ │ McpService::execute_*_async │ ← unified entry point+ │ ↓ │+ │ internal: McpProvider │ ← src/mcp/tools/*.cpp+ │ external: McpManager → McpClient │ ← JSON-RPC over stdio+ └────────────────────────────────────┘+```++Key files:+- `src/mcp/McpTypes.h` — `ToolDef`, `ToolSchema`, `ToolHandler`, `AsyncToolHandler`, `ToolContext`, `AuthLevel`, `ToolFilter`+- `src/mcp/McpProvider.{h,cpp}` — internal tool registry + sync/async dispatch + auth gate+- `src/mcp/McpService.{h,cpp}` — unified facade (internal + external)+- `src/mcp/SchemaValidator.{h,cpp}` — runs on every call before the handler+- `src/mcp/ToolSchemaBuilder.h` — fluent builder for schemas+- `src/mcp/AsyncDispatch.h` — bridges callback-based services into QPromise+- `src/mcp/dispatch/*` — provider adapters and the dispatcher++---++## 2. Schema declaration (Phase 3)++Every tool must declare its inputs. Two shapes are supported.++### Preferred — `ToolSchemaBuilder`+```cpp+#include "mcp/ToolSchemaBuilder.h"++t.input_schema = ToolSchemaBuilder()+ .string("symbol", "Ticker (AAPL, BTC-USD, etc.)").required().pattern("^[A-Z0-9._-]{1,16}$")+ .string("side", "Order side").required().enums({"buy","sell"})+ .integer("limit", "Max items").default_int(20).between(1, 100)+ .boolean("force", "Bypass cache").default_bool(false)+ .build();+```++### Legacy — raw JSON Schema fragment+Still works; the validator handles both shapes. Migrate when adding constraints+(enums, ranges, patterns) since those are tedious to write inline.++### Validation runs automatically+`McpProvider::call_tool_async` calls `validate_args` *before* the handler.+Defaults are injected, types checked, enums enforced, regex patterns matched.+Handlers receive a normalised `QJsonObject` and don't need defensive `.toString("default")` calls.++---++## 3. Sync vs async handlers (Phase 4)++| Use sync `t.handler` for | Use async `t.async_handler` for |+|---|---|+| Registry / cache / DB lookups (microseconds) | Python script execution |+| EventBus publish + immediate ok return | HTTP / network calls |+| Pure computation on already-loaded data | Service callbacks (NewsService, MarketData, etc.) |+| Anything that takes < 1 ms | Anything that takes > 100 ms |++### Sync example+```cpp+t.handler = [](const QJsonObject& args) -> ToolResult {+ return ToolResult::ok_data(QJsonObject{{"echo", args["msg"].toString()}});+};+```++### Async example+```cpp+#include "mcp/AsyncDispatch.h"+#include <QPromise>++t.default_timeout_ms = 60000;+t.async_handler = [](const QJsonObject& args, ToolContext ctx,+ std::shared_ptr<QPromise<ToolResult>> promise) {+ auto* runner = &python::PythonRunner::instance();+ AsyncDispatch::callback_to_promise(+ runner, ctx, promise,+ [args, ctx](auto resolve) {+ python::PythonRunner::instance().run("my_script.py", {}, [resolve, ctx](python::PythonResult r) {+ if (ctx.cancelled()) { resolve(ToolResult::fail("cancelled")); return; }+ resolve(r.success ? ToolResult::ok(r.output) : ToolResult::fail(r.error));+ });+ });+};+```++The provider arms a watchdog timer based on `default_timeout_ms`; if the+handler doesn't resolve in time, the promise resolves with a timeout error+and `ctx.is_cancelled()` returns true. Handlers should poll `ctx.cancelled()`+periodically and resolve gracefully when set.++---++## 4. Authorization (Phase 6.3)++Every `ToolDef` declares `auth_required` and `is_destructive`. The provider+gates every call before the handler runs.++| `AuthLevel` | When to use |+|---|---|+| `None` (default) | Read-only tools, navigation, system info |+| `Authenticated` | Authenticated reads (portfolios, settings reads) |+| `Verified` | Sensitive reads requiring email verification |+| `Subscribed` | Premium-only analytics (alt_*, ma_*, edgar_*) |+| `ExplicitConfirm` | User must approve each call (modal) |++`is_destructive = true` triggers the modal regardless of auth level. Pair+with `Authenticated` (or higher) for state-mutating tools:++```cpp+t.auth_required = AuthLevel::Authenticated;+t.is_destructive = true; // delete_*, set_setting, place_order, run_python_script, etc.+```++The host installs the actual gate via `McpProvider::set_auth_checker(...)` —+no auth/UI imports leak into `McpTypes.h`.++---++## 5. Adding a new tool — step by step++1. **Pick the right module file** in `src/mcp/tools/`. If your tool fits an+ existing category (markets, news, portfolio, …), append to that file. If+ it's a new category, create `MyAreaTools.{h,cpp}` and register it in+ `McpInit.cpp`.++2. **Declare the schema** with `ToolSchemaBuilder` — required params,+ defaults, enums, bounds, pattern.++3. **Pick handler shape** — sync if your work is < 1 ms, async otherwise.++4. **Set auth** — default `None` for reads, `Authenticated + is_destructive`+ for any mutation.++5. **Set timeout** — `default_timeout_ms` matters only for async handlers.+ Defaults to 30 s; set lower for snappy tools, higher for analytics.++6. **Register the factory** in your module's `get_X_tools()` returning+ `std::vector<ToolDef>`. `McpInit::initialize_all_tools` calls it at+ startup.++7. **Update the CMake source list** if you created a new file+ (`MCP_SOURCES` and the `SKIP_UNITY_BUILD_INCLUSION` list in `CMakeLists.txt`).++8. **Test** — write a unit test in `tests/mcp/` if logic is non-trivial.+ Otherwise smoke-test via AI Chat.++### Naming convention (Phase 6.10)++New tools should use dot-separated `<area>.<verb>`:+- `markets.get_quote`, not `get_quote`+- `paper.place_order`, not `pt_place_order`+- `news.get_latest`, not `get_news`++Renames preserve back-compat via `legacy_aliases`:+```cpp+t.name = "markets.get_quote";+t.legacy_aliases = {"get_quote"}; // saved chats / Finagent workflows still resolve+```++`McpProvider::call_tool_async` tries the canonical name first, then any+alias (logging a deprecation note when an alias matches).++---++## 6. Diagnosis++### "Tool not found"+- Did your factory return it? `tools.push_back(std::move(t))` at the end.+- Is your factory registered in `McpInit.cpp`?+- Is your module's `.cpp` listed in `MCP_SOURCES`?+- Run `mcp.health` (the meta-tool) — it returns the per-category counts.++### "Tool requires X auth"+- Check your tool's `auth_required` and the user's session.+- For development, install a permissive checker:+ ```cpp+ McpProvider::instance().set_auth_checker([](AuthLevel, bool) { return true; });+ ```++### Tool succeeds in tests, fails in AI Chat+- AI Chat sends args as JSON; the validator runs first. Run the same args+ through `tests/mcp/test_validator.cpp` to confirm the schema accepts them.+- Check the LLM's argument shape — sometimes it nests args inside an+ unexpected wrapper key. Look for `LOG_INFO(McpProvider, "Tool '%1' rejected: ...")`.++### Long async tool times out+- Bump `t.default_timeout_ms` for that specific tool.+- Per-call override: pass `_meta.timeout_ms` in args (Phase 6 wiring optional).++### Discovery+- `tool.list()` — short list of all tools (name + 1-line description).+- `tool.list({category: "trading"})` — filter to one category.+- `tool.list({search: "quote|price"})` — regex search.+- `tool.describe({name: "markets.get_quote"})` — full schema for one tool.+- `mcp.health()` — provider/external/datahub state.++---++## 7. References++- Refactor plans: `fincept-qt/plans/mcp-refactor-phase-{1..6}-*.md`+- Refactor index: `fincept-qt/plans/mcp-refactor-INDEX.md`+- Datahub: `fincept-qt/DATAHUB_ARCHITECTURE.md`+- Hub topics: `fincept-qt/docs/DATAHUB_TOPICS.md`+- Project rules: `fincept-qt/CLAUDE.md`diff --git a/fincept-qt/resources/requirements-numpy2.txt b/fincept-qt/resources/requirements-numpy2.txtindex 2860e8424..dd6e4bd45 100644--- a/fincept-qt/resources/requirements-numpy2.txt+++ b/fincept-qt/resources/requirements-numpy2.txt@@ -163,3 +163,13 @@ mplfinance>=0.12.0# Voice recognition (speech-to-text via Google API)SpeechRecognition>=3.10.0PyAudio>=0.2.14++# Deepgram live STT (alternative provider) — pinned to v3 SDK; v4+ removed+# DeepgramClientOptions and rearranged the live websocket API.+deepgram-sdk>=3.0,<4.0++# Text-to-speech (used by TtsService — replaces Qt6::TextToSpeech, which+# is not part of the default Qt 6.8.3 install). pyttsx3 wraps SAPI on+# Windows, NSSpeechSynthesizer on macOS, espeak on Linux — same engines+# Qt's wrapper would have used.+pyttsx3>=2.90diff --git a/fincept-qt/scripts/voice/clap_detector.py b/fincept-qt/scripts/voice/clap_detector.pynew file mode 100644index 000000000..3b4a16f6b--- /dev/null+++ b/fincept-qt/scripts/voice/clap_detector.py@@ -0,0 +1,246 @@+#!/usr/bin/env python3+"""+clap_detector.py — Continuous mic loop -> clap event detection -> JSON stdout.++Privacy: audio is analysed in-process and discarded. Nothing leaves the box.++Stdout protocol (one JSON line per event, flushed):+ {"status": "listening"} ready, mic open+ {"event": "clap"} clap (or double-clap, depending on mode)+ {"error": "..."} recoverable+ {"fatal": "..."} unrecoverable, process exits++Environment variables (set by ClapDetectorService in C++):+ FINCEPT_CLAP_MODE "double" (default) | "single"+ FINCEPT_CLAP_PEAK_MIN int 0..32768 — min peak amplitude to count as a+ candidate. Default 12000 (~ -8 dBFS). Lower = more+ sensitive, more false positives.+ FINCEPT_CLAP_PR_RATIO float — min peak/rms ratio. Claps are sharp; this+ filters out steady loud noise like music or a fan.+ Default 4.0.+ FINCEPT_CLAP_MAX_GAP_MS int — max ms between two candidates to count as a+ double-clap. Default 1500.+ FINCEPT_CLAP_DEBOUNCE_MS int — silence window after a fired event. Default 1500.+ FINCEPT_STT_DEVICE same key as STT — input device name substring.+"""++import json+import math+import os+import signal+import struct+import sys+import threading+import time+from typing import List, Optional+++def emit(obj: dict) -> None:+ sys.stdout.write(json.dumps(obj) + "\n")+ sys.stdout.flush()+++def diag(msg: str) -> None:+ sys.stderr.write(f"[clap_detector] {msg}\n")+ sys.stderr.flush()+++SAMPLE_RATE = 16000+CHANNELS = 1+SAMPLE_WIDTH = 2+CHUNK_SAMPLES = 1600 # 100 ms at 16 kHz — short enough to localise transients+++def list_input_devices(pa) -> List[dict]:+ out = []+ try:+ host = pa.get_default_host_api_info()+ default_input_index = host.get("defaultInputDevice", -1)+ except Exception:+ default_input_index = -1+ for i in range(pa.get_device_count()):+ try:+ info = pa.get_device_info_by_index(i)+ except Exception:+ continue+ if int(info.get("maxInputChannels", 0)) <= 0:+ continue+ out.append({+ "index": i,+ "name": str(info.get("name", "")),+ "is_default": (i == default_input_index),+ })+ return out+++def pick_device(pa, pref: str) -> Optional[int]:+ inputs = list_input_devices(pa)+ if not inputs:+ return None+ if pref:+ pref_l = pref.lower()+ for d in inputs:+ if pref_l in d["name"].lower():+ return d["index"]+ for d in inputs:+ if d["is_default"]:+ return d["index"]+ return inputs[0]["index"]+++def rms_peak_int16(buf: bytes):+ """Return (rms, peak) for an int16 PCM buffer; both 0..32768."""+ n = len(buf) // SAMPLE_WIDTH+ if n == 0:+ return 0.0, 0+ samples = struct.unpack("<" + "h" * n, buf)+ s = 0+ p = 0+ for v in samples:+ s += v * v+ a = -v if v < 0 else v+ if a > p:+ p = a+ return math.sqrt(s / n), p+++def main() -> None:+ diag("script started — pid=" + str(os.getpid()))++ mode = os.environ.get("FINCEPT_CLAP_MODE", "double").strip().lower() or "double"+ if mode not in ("single", "double"):+ mode = "double"++ try:+ peak_min = int(os.environ.get("FINCEPT_CLAP_PEAK_MIN", "12000"))+ except ValueError:+ peak_min = 12000+ try:+ pr_ratio = float(os.environ.get("FINCEPT_CLAP_PR_RATIO", "4.0"))+ except ValueError:+ pr_ratio = 4.0+ try:+ max_gap_ms = int(os.environ.get("FINCEPT_CLAP_MAX_GAP_MS", "1500"))+ except ValueError:+ max_gap_ms = 1500+ try:+ debounce_ms = int(os.environ.get("FINCEPT_CLAP_DEBOUNCE_MS", "1500"))+ except ValueError:+ debounce_ms = 1500+ device_pref = os.environ.get("FINCEPT_STT_DEVICE", "").strip()++ diag(f"config mode={mode} peak_min={peak_min} pr_ratio={pr_ratio} "+ f"max_gap_ms={max_gap_ms} debounce_ms={debounce_ms} device='{device_pref}'")++ try:+ import pyaudio+ except ImportError as e:+ diag(f"pyaudio import failed: {e}")+ emit({"fatal": (+ "PyAudio not available in venv-numpy2. "+ "Open Settings -> Python Env -> Reinstall packages."+ )})+ sys.exit(1)++ stop_flag = threading.Event()++ def on_signal(_signum, _frame):+ stop_flag.set()+ if hasattr(signal, "SIGTERM"):+ try:+ signal.signal(signal.SIGTERM, on_signal)+ except (ValueError, OSError):+ pass++ pa = pyaudio.PyAudio()+ device_index = pick_device(pa, device_pref)+ if device_index is None:+ emit({"fatal": "No input audio device available"})+ pa.terminate()+ sys.exit(1)++ try:+ stream = pa.open(+ format=pyaudio.paInt16,+ channels=CHANNELS,+ rate=SAMPLE_RATE,+ input=True,+ input_device_index=device_index,+ frames_per_buffer=CHUNK_SAMPLES,+ )+ except Exception as ex:+ diag(f"pa.open failed: {ex}")+ pa.terminate()+ emit({"fatal": f"Could not open microphone stream: {ex}"})+ sys.exit(1)++ diag(f"audio stream opened — device={device_index}")+ emit({"status": "listening"})++ # Detection state machine+ last_candidate_ms: Optional[int] = None+ last_fire_ms: int = 0+ chunks_seen = 0+ candidates_seen = 0++ try:+ while not stop_flag.is_set():+ try:+ buf = stream.read(CHUNK_SAMPLES, exception_on_overflow=False)+ except Exception as ex:+ diag(f"stream.read failed: {ex}")+ emit({"error": f"Audio read failed: {ex}"})+ break++ if not buf:+ continue+ chunks_seen += 1++ now_ms = int(time.time() * 1000)+ if now_ms - last_fire_ms < debounce_ms:+ # Within debounce window — drop everything to avoid double-firing+ continue++ rms, peak = rms_peak_int16(buf)+ if peak < peak_min:+ continue+ ratio = (peak / rms) if rms > 1.0 else 0.0+ if ratio < pr_ratio:+ continue++ # Sharp transient candidate+ candidates_seen += 1+ diag(f"candidate #{candidates_seen} peak={peak} rms={rms:.0f} ratio={ratio:.2f}")++ if mode == "single":+ emit({"event": "clap"})+ last_fire_ms = now_ms+ last_candidate_ms = None+ continue++ # Double-clap mode+ if last_candidate_ms is None or (now_ms - last_candidate_ms) > max_gap_ms:+ last_candidate_ms = now_ms+ else:+ # Second candidate within window+ emit({"event": "clap"})+ last_fire_ms = now_ms+ last_candidate_ms = None++ except KeyboardInterrupt:+ pass+ finally:+ diag(f"shutting down — chunks={chunks_seen} candidates={candidates_seen}")+ try:+ stream.stop_stream()+ stream.close()+ except Exception:+ pass+ try:+ pa.terminate()+ except Exception:+ pass+++if __name__ == "__main__":+ main()diff --git a/fincept-qt/scripts/voice/deepgram_stt.py b/fincept-qt/scripts/voice/deepgram_stt.pyindex ea5309408..126e11088 100644--- a/fincept-qt/scripts/voice/deepgram_stt.py+++ b/fincept-qt/scripts/voice/deepgram_stt.py@@ -1,181 +1,408 @@#!/usr/bin/env python3"""-deepgram_stt.py — Microphone → Deepgram live WebSocket STT → JSON stdout.--Matches the same JSON-lines protocol as speech_to_text.py so SpeechService can-parse either transparently:- {"status": "calibrating"} — adjusting for ambient noise (no-op here)- {"status": "listening"} — ready, waiting for speech- {"text": "hello world"} — finalized transcription- {"error": "..."} — recoverable error (keeps listening)- {"fatal": "..."} — unrecoverable error (process exits)--Environment variables (injected by DeepgramSttProvider in C++):- DEEPGRAM_API_KEY — required- FINCEPT_STT_MODEL — default "nova-3"- FINCEPT_STT_LANGUAGE — default "en"- FINCEPT_STT_KEYTERMS — comma-separated boosted terms (optional)--The process runs until stdin is closed, a fatal error occurs, or it receives-SIGTERM (Windows: QProcess::kill sends taskkill which terminates anyway).+deepgram_stt.py — Mic (raw pyaudio) -> Deepgram live WebSocket -> JSON stdout.++This rewrite replaces deepgram-sdk's opaque `Microphone` helper with a manual+pyaudio capture loop so we can:+ * pick a specific input device by name substring,+ * apply a software gain multiplier (laptop mics are often very quiet),+ * log periodic RMS levels so we can tell whether the mic is actually+ capturing anything or whether the user just needs to speak louder /+ switch device.++Stdout protocol (one JSON object per line, identical to before):+ {"status": "calibrating"|"listening"|"stopped"}+ {"text": "..."} finalized transcription+ {"error": "..."} recoverable+ {"fatal": "..."} unrecoverable, process exits++Environment variables (set by DeepgramSttProvider in C++):+ DEEPGRAM_API_KEY required+ FINCEPT_STT_MODEL default "nova-3"+ FINCEPT_STT_LANGUAGE default "en"+ FINCEPT_STT_KEYTERMS comma-separated boosted terms (optional)+ FINCEPT_STT_GAIN audio gain multiplier (default "3.0"). Try 5-10 if+ the mic is far-field; leave at 1.0 for a headset.+ FINCEPT_STT_DEVICE case-insensitive substring of input-device name. If+ empty, the system default device is used."""import json+import mathimport osimport signal+import structimport sysimport threading+import time+from typing import List, Optionaldef emit(obj: dict) -> None:- """Write a JSON line to stdout and flush immediately."""sys.stdout.write(json.dumps(obj) + "\n")sys.stdout.flush()+def diag(msg: str) -> None:+ sys.stderr.write(f"[deepgram_stt] {msg}\n")+ sys.stderr.flush()+++# ── Audio constants ───────────────────────────────────────────────────────────+SAMPLE_RATE = 16000+CHANNELS = 1+SAMPLE_WIDTH = 2 # int16 = 2 bytes/sample+CHUNK_SAMPLES = 1600 # 100 ms at 16 kHz — Deepgram recommended cadence+LEVEL_LOG_EVERY_S = 2.0 # how often to log RMS / peak to stderr+++def list_input_devices(pa) -> List[dict]:+ """Returns a list of {index, name, channels, default_rate} for inputs."""+ out = []+ try:+ host = pa.get_default_host_api_info()+ default_input_index = host.get("defaultInputDevice", -1)+ except Exception:+ default_input_index = -1+ for i in range(pa.get_device_count()):+ try:+ info = pa.get_device_info_by_index(i)+ except Exception:+ continue+ if int(info.get("maxInputChannels", 0)) <= 0:+ continue+ out.append({+ "index": i,+ "name": str(info.get("name", "")),+ "channels": int(info.get("maxInputChannels", 0)),+ "default_rate": int(info.get("defaultSampleRate", 0)),+ "is_default": (i == default_input_index),+ })+ return out+++def pick_device(pa, pref: str) -> Optional[int]:+ """Return device index matching `pref` substring, else default device.+ Logs choices to stderr so the user can see what was selected."""+ inputs = list_input_devices(pa)+ diag(f"available input devices ({len(inputs)}):")+ for d in inputs:+ marker = " [default]" if d["is_default"] else ""+ diag(f" #{d['index']} {d['name']} "+ f"ch={d['channels']} rate={d['default_rate']}{marker}")+ if not inputs:+ return None+ if pref:+ pref_l = pref.lower()+ for d in inputs:+ if pref_l in d["name"].lower():+ diag(f"selected input by FINCEPT_STT_DEVICE='{pref}': "+ f"#{d['index']} {d['name']}")+ return d["index"]+ diag(f"no device matched FINCEPT_STT_DEVICE='{pref}', "+ f"falling back to system default")+ for d in inputs:+ if d["is_default"]:+ diag(f"selected system default input: #{d['index']} {d['name']}")+ return d["index"]+ diag(f"no default flagged, using first input: #{inputs[0]['index']} "+ f"{inputs[0]['name']}")+ return inputs[0]["index"]+++def apply_gain_int16(buf: bytes, gain: float) -> bytes:+ """Multiply each int16 sample by `gain`, clipping to int16 range.+ Used to compensate for low-sensitivity laptop mics."""+ if gain <= 0 or abs(gain - 1.0) < 1e-3:+ return buf+ n = len(buf) // SAMPLE_WIDTH+ if n == 0:+ return buf+ samples = struct.unpack("<" + "h" * n, buf)+ out = []+ for s in samples:+ v = int(s * gain)+ if v > 32767:+ v = 32767+ elif v < -32768:+ v = -32768+ out.append(v)+ return struct.pack("<" + "h" * n, *out)+++def rms_int16(buf: bytes) -> float:+ """Root-mean-square in 0..32768 of an int16 PCM buffer."""+ n = len(buf) // SAMPLE_WIDTH+ if n == 0:+ return 0.0+ samples = struct.unpack("<" + "h" * n, buf)+ s = 0+ for v in samples:+ s += v * v+ return math.sqrt(s / n)+++def peak_int16(buf: bytes) -> int:+ """Max absolute value in 0..32768 of an int16 PCM buffer."""+ n = len(buf) // SAMPLE_WIDTH+ if n == 0:+ return 0+ samples = struct.unpack("<" + "h" * n, buf)+ p = 0+ for v in samples:+ a = -v if v < 0 else v+ if a > p:+ p = a+ return p++def main() -> None:+ diag("script started — pid=" + str(os.getpid()))+api_key = os.environ.get("DEEPGRAM_API_KEY", "").strip()+ diag(f"env DEEPGRAM_API_KEY len={len(api_key)}")if not api_key:- emit({"fatal": "DEEPGRAM_API_KEY not set — configure it in Settings → Voice"})+ emit({"fatal": "DEEPGRAM_API_KEY not set — configure it in Settings -> Voice"})sys.exit(1)- model = os.environ.get("FINCEPT_STT_MODEL", "nova-3").strip() or "nova-3"- language = os.environ.get("FINCEPT_STT_LANGUAGE", "en").strip() or "en"+ model = os.environ.get("FINCEPT_STT_MODEL", "nova-3").strip() or "nova-3"+ language = os.environ.get("FINCEPT_STT_LANGUAGE", "en").strip() or "en"keyterms_raw = os.environ.get("FINCEPT_STT_KEYTERMS", "").strip()- keyterms = [t.strip() for t in keyterms_raw.split(",") if t.strip()]+ keyterms = [t.strip() for t in keyterms_raw.split(",") if t.strip()]+ device_pref = os.environ.get("FINCEPT_STT_DEVICE", "").strip()+ try:+ gain = float(os.environ.get("FINCEPT_STT_GAIN", "3.0"))+ except ValueError:+ gain = 3.0+ diag(f"config model={model} language={language} keyterms={keyterms} "+ f"gain={gain} device='{device_pref}'")- # Required deps — fail fast with clear install hints+ # ── Required deps ────────────────────────────────────────────────────────try:from deepgram import (DeepgramClient,DeepgramClientOptions,LiveOptions,LiveTranscriptionEvents,- Microphone,)+ import deepgram as _dg_mod+ diag(f"deepgram-sdk imported, version={getattr(_dg_mod, '__version__', '?')}")except ImportError as e:- emit({"fatal": f"deepgram-sdk not installed — run: pip install deepgram-sdk ({e})"})+ diag(f"deepgram import failed: {e}")+ emit({"fatal": (+ "Deepgram Python SDK not available in venv-numpy2 "+ f"({e}). Open Settings -> Python Env -> Reinstall packages."+ )})sys.exit(1)try:- import pyaudio # noqa: F401 — required by Microphone helper- except ImportError:- emit({"fatal": "PyAudio not installed — run: pip install PyAudio"})+ import pyaudio+ diag(f"pyaudio imported, version={getattr(pyaudio, '__version__', '?')}")+ except ImportError as e:+ diag(f"pyaudio import failed: {e}")+ emit({"fatal": (+ "PyAudio not available in venv-numpy2. "+ "Open Settings -> Python Env -> Reinstall packages."+ )})sys.exit(1)- # Graceful shutdown flag+ # ── Shutdown wiring ──────────────────────────────────────────────────────stop_flag = threading.Event()- def on_signal(signum, frame):+ def on_signal(_signum, _frame):stop_flag.set()-if hasattr(signal, "SIGTERM"):try:signal.signal(signal.SIGTERM, on_signal)except (ValueError, OSError):- pass # Not on main thread / not supported+ pass- # Build Deepgram client — quiet the SDK's own stdout/stderr spam, which- # would otherwise pollute our JSON-lines protocol.+ # ── Deepgram client ──────────────────────────────────────────────────────config = DeepgramClientOptions(options={"keepalive": "true"})client = DeepgramClient(api_key, config)dg_conn = client.listen.websocket.v("1")+ # ── Transcript buffering ─────────────────────────────────────────────────+ # Accumulate every is_final segment and flush on speech_final / UtteranceEnd.+ # Requiring `is_final && speech_final` per-message dropped mid-utterance+ # words on machines where speech_final fires sparingly.+ finalised_segments: List[str] = []+ finalised_lock = threading.Lock()++ def flush_buffered_text(why: str) -> None:+ with finalised_lock:+ if not finalised_segments:+ return+ text = " ".join(finalised_segments).strip()+ finalised_segments.clear()+ if text:+ diag(f"flushing buffered transcript ({why}): \"{text[:120]}\"")+ emit({"text": text})+def on_open(_self, _open, **_kw):+ diag("deepgram event: Open")emit({"status": "listening"})def on_message(_self, result, **_kw):try:alt = result.channel.alternatives[0]transcript = (alt.transcript or "").strip()+ is_final = bool(getattr(result, "is_final", False))+ speech_final = bool(getattr(result, "speech_final", False))if not transcript:return- # Only emit finalized utterances — interim partials would flood the- # consumer which expects completed commands.- is_final = bool(getattr(result, "is_final", False))- speech_final = bool(getattr(result, "speech_final", False))- if is_final and speech_final:- emit({"text": transcript})+ diag(f"transcript: is_final={is_final} speech_final={speech_final} "+ f"text=\"{transcript[:80]}\"")+ if is_final:+ with finalised_lock:+ finalised_segments.append(transcript)+ if speech_final:+ flush_buffered_text("speech_final")except Exception as ex:+ diag(f"on_message exception: {ex}")emit({"error": f"Transcript parse failed: {ex}"})+ def on_utterance_end(_self, _payload, **_kw):+ diag("deepgram event: UtteranceEnd")+ flush_buffered_text("utterance_end")+def on_error(_self, err, **_kw):+ diag(f"deepgram event: Error — {err}")emit({"error": f"Deepgram error: {err}"})def on_close(_self, _close, **_kw):+ diag("deepgram event: Close — stopping")+ flush_buffered_text("close")stop_flag.set()def on_unhandled(_self, _unhandled, **_kw):- # Deepgram emits several event types we don't care about (Metadata,- # SpeechStarted, UtteranceEnd). Swallow them silently.passdg_conn.on(LiveTranscriptionEvents.Open, on_open)dg_conn.on(LiveTranscriptionEvents.Transcript, on_message)+ # UtteranceEnd is its own event in deepgram-sdk v3 — register it explicitly+ # so we always flush, even when speech_final is sporadic.+ if hasattr(LiveTranscriptionEvents, "UtteranceEnd"):+ dg_conn.on(LiveTranscriptionEvents.UtteranceEnd, on_utterance_end)dg_conn.on(LiveTranscriptionEvents.Error, on_error)dg_conn.on(LiveTranscriptionEvents.Close, on_close)dg_conn.on(LiveTranscriptionEvents.Unhandled, on_unhandled)+ # endpointing of 800 ms (was 300) — gives natural-pace speech room to+ # breathe between phrases without prematurely closing the utterance.live_opts = LiveOptions(model=model,language=language,encoding="linear16",- sample_rate=16000,- channels=1,+ sample_rate=SAMPLE_RATE,+ channels=CHANNELS,punctuate=True,smart_format=True,- interim_results=False,- endpointing=300,+ interim_results=True,+ endpointing=800,vad_events=True,- utterance_end_ms="1000",+ utterance_end_ms="1200",)-- # Keyword boosting — API surface depends on model.- # Nova-3 uses `keyterm` (no weights, English-only).- # Older models use `keywords` with optional weight.if keyterms:try:if model.startswith("nova-3"):live_opts.keyterm = keytermselse:live_opts.keywords = keyterms- except Exception as ex: # non-fatal — continue without boosting+ except Exception as ex:emit({"error": f"Keyterm setup failed: {ex}"})emit({"status": "calibrating"})+ diag("calling dg_conn.start() …")if not dg_conn.start(live_opts):+ diag("dg_conn.start() returned False — websocket failed")emit({"fatal": "Failed to open Deepgram WebSocket connection"})sys.exit(1)+ diag("dg_conn.start() returned True — websocket open")++ # ── Mic capture (raw pyaudio) ────────────────────────────────────────────+ pa = pyaudio.PyAudio()+ device_index = pick_device(pa, device_pref)+ if device_index is None:+ emit({"fatal": "No input audio device available"})+ try:+ dg_conn.finish()+ finally:+ pa.terminate()+ sys.exit(1)- # Start microphone → feeds binary audio to dg_conntry:- microphone = Microphone(dg_conn.send)+ stream = pa.open(+ format=pyaudio.paInt16,+ channels=CHANNELS,+ rate=SAMPLE_RATE,+ input=True,+ input_device_index=device_index,+ frames_per_buffer=CHUNK_SAMPLES,+ )except Exception as ex:+ diag(f"pa.open failed: {ex}")dg_conn.finish()- emit({"fatal": f"No microphone available: {ex}"})+ pa.terminate()+ emit({"fatal": f"Could not open microphone stream: {ex}"})sys.exit(1)+ diag(f"audio stream opened — device={device_index} rate={SAMPLE_RATE} "+ f"chunk={CHUNK_SAMPLES} samples ({CHUNK_SAMPLES * 1000 / SAMPLE_RATE:.0f} ms)")- if not microphone.start():- dg_conn.finish()- emit({"fatal": "Failed to start microphone"})- sys.exit(1)+ last_level_log = 0.0+ chunk_count = 0+ sent_bytes = 0- # Block until signalled or parent closes stdintry:while not stop_flag.is_set():- # Wake up periodically to check the flag; also exit if stdin is- # closed (parent QProcess was killed).- if stop_flag.wait(timeout=0.5):+ try:+ buf = stream.read(CHUNK_SAMPLES, exception_on_overflow=False)+ except Exception as ex:+ diag(f"stream.read failed: {ex}")+ emit({"error": f"Audio read failed: {ex}"})break- if sys.stdin.closed:++ if not buf:+ continue++ chunk_count += 1++ # Periodic level diagnostic — RMS and peak (both 0..32768). Lets+ # the user see whether the mic is even picking up sound.+ now = time.time()+ if now - last_level_log >= LEVEL_LOG_EVERY_S:+ last_level_log = now+ rms = rms_int16(buf)+ peak = peak_int16(buf)+ # rms ~50 = near-silence, ~500-2000 = soft speech, >5000 = loud.+ diag(f"audio level (pre-gain): rms={rms:.0f} peak={peak} "+ f"chunks_sent={chunk_count} bytes_sent={sent_bytes}")++ # Apply software gain — int16 with clipping.+ if gain != 1.0:+ buf = apply_gain_int16(buf, gain)++ try:+ dg_conn.send(buf)+ sent_bytes += len(buf)+ except Exception as ex:+ diag(f"dg_conn.send failed: {ex}")+ emit({"error": f"Send to Deepgram failed: {ex}"})breakexcept KeyboardInterrupt:passfinally:+ diag(f"shutting down — chunks_sent={chunk_count} bytes_sent={sent_bytes}")+ try:+ stream.stop_stream()+ stream.close()+ except Exception:+ passtry:- microphone.finish()+ pa.terminate()except Exception:pass+ flush_buffered_text("shutdown")try:dg_conn.finish()except Exception:diff --git a/fincept-qt/scripts/voice/deepgram_tts.py b/fincept-qt/scripts/voice/deepgram_tts.pynew file mode 100644index 000000000..6514de0b7--- /dev/null+++ b/fincept-qt/scripts/voice/deepgram_tts.py@@ -0,0 +1,177 @@+#!/usr/bin/env python3+"""+deepgram_tts.py — Stdin text -> Deepgram Aura TTS -> pyaudio playback.++JSON-lines stdout protocol matches tts.py so TtsService can swap providers+transparently:+ {"status": "speaking"}+ {"status": "done"}+ {"error": "..."}+ {"fatal": "..."} unrecoverable, process exits++Strategy: POST text to Deepgram's /v1/speak endpoint with linear16 / 24000Hz+mono / container=none. Response body is raw PCM streamed as it's synthesised;+we pipe it directly into a pyaudio output stream so playback starts before+the full clip arrives (low latency, no temp files, no ffmpeg).++Environment variables (set by DeepgramTtsProvider in C++):+ DEEPGRAM_API_KEY required+ FINCEPT_TTS_DG_MODEL default "aura-2-thalia-en"+ FINCEPT_TTS_RATE pyttsx3 leftover, ignored here+"""++import json+import os+import sys+import urllib.parse+from typing import Optional+++def emit(obj: dict) -> None:+ sys.stdout.write(json.dumps(obj) + "\n")+ sys.stdout.flush()+++def diag(msg: str) -> None:+ sys.stderr.write(f"[deepgram_tts] {msg}\n")+ sys.stderr.flush()+++SAMPLE_RATE = 24000 # Aura-2 native rate+CHANNELS = 1+PLAYBACK_CHUNK = 4096 # bytes; ~85 ms at 24 kHz int16 mono+++def play_stream(audio_iter, pyaudio_mod) -> None:+ """Write raw PCM bytes from `audio_iter` to a pyaudio output stream."""+ pa = pyaudio_mod.PyAudio()+ try:+ stream = pa.open(+ format=pyaudio_mod.paInt16,+ channels=CHANNELS,+ rate=SAMPLE_RATE,+ output=True,+ )+ except Exception as ex:+ pa.terminate()+ raise RuntimeError(f"pyaudio open output failed: {ex}") from ex++ try:+ emit({"status": "speaking"})+ for chunk in audio_iter:+ if not chunk:+ continue+ stream.write(chunk)+ finally:+ try:+ stream.stop_stream()+ stream.close()+ except Exception:+ pass+ pa.terminate()+++def main() -> int:+ text = sys.stdin.read()+ if text is None:+ text = ""+ text = text.strip()+ diag(f"received text len={len(text)}")+ if not text:+ emit({"status": "done"})+ return 0++ api_key = os.environ.get("DEEPGRAM_API_KEY", "").strip()+ if not api_key:+ emit({"fatal": "DEEPGRAM_API_KEY not set — configure it in Settings -> Voice"})+ return 1++ model = os.environ.get("FINCEPT_TTS_DG_MODEL", "aura-2-thalia-en").strip() \+ or "aura-2-thalia-en"+ diag(f"config model={model}")++ # Try `requests` first — already pulled in transitively by deepgram-sdk and+ # most of the analytics stack. urllib fallback keeps the script self-contained+ # if requests is somehow absent.+ requests_mod: Optional[object]+ try:+ import requests as requests_mod # type: ignore+ diag(f"requests imported, version={requests_mod.__version__}")+ except ImportError:+ requests_mod = None+ diag("requests not available — falling back to urllib")++ try:+ import pyaudio+ diag(f"pyaudio imported, version={getattr(pyaudio, '__version__', '?')}")+ except ImportError as e:+ diag(f"pyaudio import failed: {e}")+ emit({"fatal": (+ "PyAudio not available in venv-numpy2. "+ "Open Settings -> Python Env -> Reinstall packages."+ )})+ return 1++ qs = urllib.parse.urlencode({+ "model": model,+ "encoding": "linear16",+ "sample_rate": str(SAMPLE_RATE),+ "container": "none",+ })+ url = f"https://api.deepgram.com/v1/speak?{qs}"+ headers = {+ "Authorization": f"Token {api_key}",+ "Content-Type": "application/json",+ "Accept": "audio/wav,audio/*",+ }+ payload = json.dumps({"text": text[:2000]}).encode("utf-8")++ # Trim text to a reasonable upper bound — Deepgram /v1/speak caps text+ # at 2000 chars per request anyway.++ try:+ if requests_mod is not None:+ diag("POST /v1/speak (requests, stream=True)")+ with requests_mod.post(url, headers=headers, data=payload,+ stream=True, timeout=30) as resp:+ if resp.status_code != 200:+ body = resp.text[:500] if resp.text else ""+ diag(f"non-200: {resp.status_code} body={body}")+ if resp.status_code == 401:+ emit({"fatal": "Deepgram rejected API key (401)"})+ elif resp.status_code == 402:+ emit({"fatal": "Deepgram credits exhausted (402)"})+ elif resp.status_code == 400:+ emit({"fatal": f"Deepgram bad request (400): {body}"})+ else:+ emit({"fatal": f"Deepgram TTS HTTP {resp.status_code}: {body}"})+ return 1+ resp.raw.decode_content = True+ play_stream(resp.iter_content(chunk_size=PLAYBACK_CHUNK), pyaudio)+ else:+ import urllib.request+ req = urllib.request.Request(url, data=payload, headers=headers, method="POST")+ diag("POST /v1/speak (urllib)")+ with urllib.request.urlopen(req, timeout=30) as resp:+ code = resp.getcode()+ if code != 200:+ emit({"fatal": f"Deepgram TTS HTTP {code}"})+ return 1+ def _iter():+ while True:+ chunk = resp.read(PLAYBACK_CHUNK)+ if not chunk:+ return+ yield chunk+ play_stream(_iter(), pyaudio)+ except Exception as ex:+ diag(f"runtime exception: {ex}")+ emit({"error": f"Deepgram TTS error: {ex}"})+ return 1++ emit({"status": "done"})+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/fincept-qt/scripts/voice/tts.py b/fincept-qt/scripts/voice/tts.pynew file mode 100644index 000000000..431ca4d68--- /dev/null+++ b/fincept-qt/scripts/voice/tts.py@@ -0,0 +1,112 @@+#!/usr/bin/env python3+"""+tts.py — Speak the text on stdin via pyttsx3, then exit.++Used by TtsService as a one-shot subprocess. The C++ side launches one+process per utterance, writes the text to stdin (terminated by EOF), and+listens for {"status": "speaking"|"done"} events on stdout.++Stdin protocol:+ raw UTF-8 text — read until EOF.++Stdout protocol (JSON-lines, one per line, flushed):+ {"status": "speaking"}+ {"status": "done"}+ {"error": "..."}+ {"fatal": "..."} engine could not be initialised++Environment variables (optional, all set by TtsService):+ FINCEPT_TTS_RATE — words/min override (default = engine default).+ FINCEPT_TTS_VOLUME — 0.0…1.0 (default 1.0).+ FINCEPT_TTS_VOICE — substring match against voice id/name; first hit wins.+"""++import json+import os+import sys+++def emit(obj: dict) -> None:+ sys.stdout.write(json.dumps(obj) + "\n")+ sys.stdout.flush()+++def diag(msg: str) -> None:+ sys.stderr.write(f"[tts] {msg}\n")+ sys.stderr.flush()+++def main() -> int:+ text = sys.stdin.read()+ if text is None:+ text = ""+ text = text.strip()+ diag(f"received text len={len(text)}")+ if not text:+ emit({"status": "done"})+ return 0++ try:+ import pyttsx3+ except ImportError as e:+ diag(f"pyttsx3 import failed: {e}")+ emit({"fatal": (+ "pyttsx3 not available in venv-numpy2. "+ "Open Settings -> Python Env -> Reinstall packages, then try again."+ )})+ return 1++ try:+ engine = pyttsx3.init()+ except Exception as e:+ diag(f"pyttsx3 init failed: {e}")+ emit({"fatal": f"TTS engine could not be initialised: {e}"})+ return 1++ # Optional tuning from env+ rate_env = os.environ.get("FINCEPT_TTS_RATE", "").strip()+ if rate_env:+ try:+ engine.setProperty("rate", int(rate_env))+ except Exception as e:+ diag(f"set rate failed: {e}")++ vol_env = os.environ.get("FINCEPT_TTS_VOLUME", "").strip()+ if vol_env:+ try:+ engine.setProperty("volume", max(0.0, min(1.0, float(vol_env))))+ except Exception as e:+ diag(f"set volume failed: {e}")++ voice_pref = os.environ.get("FINCEPT_TTS_VOICE", "").strip().lower()+ if voice_pref:+ try:+ for v in engine.getProperty("voices") or []:+ vid = (getattr(v, "id", "") or "").lower()+ vname = (getattr(v, "name", "") or "").lower()+ if voice_pref in vid or voice_pref in vname:+ engine.setProperty("voice", v.id)+ diag(f"voice selected: {v.id}")+ break+ except Exception as e:+ diag(f"voice selection failed: {e}")++ # Trim very long replies — SAPI can lock up on huge buffers, and the+ # caller already truncates around the same threshold.+ speak = text[:2000]++ emit({"status": "speaking"})+ try:+ engine.say(speak)+ engine.runAndWait()+ except Exception as e:+ diag(f"runtime exception: {e}")+ emit({"error": f"TTS runtime error: {e}"})+ return 1++ emit({"status": "done"})+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/fincept-qt/src/ai_chat/AiChatBubble.cpp b/fincept-qt/src/ai_chat/AiChatBubble.cppindex b10413954..629811822 100644--- a/fincept-qt/src/ai_chat/AiChatBubble.cpp+++ b/fincept-qt/src/ai_chat/AiChatBubble.cpp@@ -1,21 +1,36 @@+// AiChatBubble.cpp — "Quick Chat" floating bubble.+//+// Stays explicitly separate from the AI Chat tab:+// • No ChatRepository writes — chat history is in-memory only.+// • Conversations never appear in the AI Chat tab's session list.+//+// UI is intentionally minimal:+// ┌─ Header (title + subtitle "not saved" + voice / clear / close) ─┐+// │ ...messages, scrollable │+// │ ────────────────────────────────────────────────────────────── │+// │ [ input box .................. ] 🎤 [Send] │+// │ status strip (one line, hidden when idle) │+// └──────────────────────────────────────────────────────────────────┘+#include "ai_chat/AiChatBubble.h"#include "services/stt/SpeechService.h"-#include "storage/repositories/ChatRepository.h"+#include "services/tts/TtsService.h"+#include "services/voice_trigger/ClapDetectorService.h"#include "ui/theme/Theme.h"#include "ui/theme/ThemeManager.h"-#include <QAudioOutput>#include <QDateTime>#include <QEvent>+#include <QGraphicsOpacityEffect>#include <QHBoxLayout>#include <QLabel>#include <QPalette>+#include <QPropertyAnimation>#include <QRegularExpression>#include <QResizeEvent>#include <QScrollBar>#include <QUrl>-#include <QUuid>#include <algorithm>#include <memory>@@ -24,40 +39,57 @@ namespace fincept {namespace col = fincept::ui::colors;-// Override Qt's default blue palette on QTextEdit to match Obsidian theme.-// Without this, links render blue and selection highlights are blue.+// ── Layout constants ──────────────────────────────────────────────────────────+static constexpr int PANEL_W = 380;+static constexpr int PANEL_H = 540;+static constexpr int BTN_SIZE = 42;+static constexpr int MARGIN = 16;+static constexpr int HEADER_H = 56;+static constexpr int INPUT_H = 60;+static constexpr int STATUS_H = 26;++// Override Qt's default blue palette on QTextEdit to match the Obsidian theme.static void apply_obsidian_palette(QTextEdit* edit) {QPalette p = edit->palette();- p.setColor(QPalette::Link, QColor(col::AMBER()));- p.setColor(QPalette::LinkVisited, QColor(col::AMBER()));- p.setColor(QPalette::Highlight, QColor(col::AMBER_DIM()));+ p.setColor(QPalette::Link, QColor(col::AMBER()));+ p.setColor(QPalette::LinkVisited, QColor(col::AMBER()));+ p.setColor(QPalette::Highlight, QColor(col::AMBER_DIM()));p.setColor(QPalette::HighlightedText, QColor(col::TEXT_PRIMARY()));- p.setColor(QPalette::Base, Qt::transparent);- p.setColor(QPalette::Text, QColor(col::TEXT_PRIMARY()));+ p.setColor(QPalette::Base, Qt::transparent);+ p.setColor(QPalette::Text, QColor(col::TEXT_PRIMARY()));edit->setPalette(p);}-namespace fnt = fincept::ui::fonts;-// ── Layout constants ──────────────────────────────────────────────────────────-static constexpr int PANEL_W = 320;-static constexpr int PANEL_H = 440;-static constexpr int BTN_SIZE = 42;-static constexpr int MARGIN = 16;+// Compact Markdown CSS used inside message bubbles.+static QString bubble_md_css(const QString& text_color) {+ return QString("body { color: %1; line-height: 1.45; }"+ "p { margin-top: 4px; margin-bottom: 4px; }"+ "ul, ol { margin-top: 3px; margin-bottom: 3px; padding-left: 16px; }"+ "li { margin-top: 2px; margin-bottom: 2px; }"+ "h1, h2, h3, h4 { margin-top: 8px; margin-bottom: 3px; color: %2; font-weight: 700; }"+ "hr { margin-top: 6px; margin-bottom: 6px; border: none; "+ " border-top: 1px solid %3; }"+ "a { color: %2; text-decoration: underline; }"+ "code { background: %4; color: %2; padding: 1px 3px; "+ " font-family: 'Consolas', 'Courier New', monospace; font-size: 12px; }"+ "pre { background: %4; border: 1px solid %3; padding: 8px 10px; "+ " margin-top: 4px; margin-bottom: 4px; "+ " font-family: 'Consolas', 'Courier New', monospace; font-size: 12px; }"+ "blockquote { border-left: 2px solid %2; padding-left: 8px; "+ " margin-top: 4px; margin-bottom: 4px; color: %5; }"+ "table { border-collapse: collapse; margin-top: 4px; margin-bottom: 4px; }"+ "th { background: %4; border: 1px solid %3; padding: 3px 6px; "+ " font-weight: 600; color: %2; }"+ "td { border: 1px solid %3; padding: 3px 6px; }"+ "strong { color: %1; font-weight: 700; }")+ .arg(text_color, col::AMBER(), col::BORDER_MED(), col::BG_BASE(), col::TEXT_SECONDARY());+}// ── Constructor ───────────────────────────────────────────────────────────────AiChatBubble::AiChatBubble(QWidget* parent) : QWidget(parent) {setAttribute(Qt::WA_NoSystemBackground, true);setAttribute(Qt::WA_TranslucentBackground, true);- tts_player_ = new QMediaPlayer(this);- auto* ao = new QAudioOutput(this);- tts_player_->setAudioOutput(ao);- connect(tts_player_, &QMediaPlayer::mediaStatusChanged, this, &AiChatBubble::on_tts_media_status);-- pulse_timer_ = new QTimer(this);- pulse_timer_->setInterval(400);- connect(pulse_timer_, &QTimer::timeout, this, &AiChatBubble::animate_pulse);-build_bubble_button();build_chat_panel();chat_panel_->hide();@@ -65,14 +97,52 @@ AiChatBubble::AiChatBubble(QWidget* parent) : QWidget(parent) {connect(&ai_chat::LlmService::instance(), &ai_chat::LlmService::finished_streaming, this,&AiChatBubble::on_streaming_done, Qt::UniqueConnection);- // ── SpeechService wiring ─────────────────────────────────────────────────+ // STT wiringauto& stt = services::SpeechService::instance();connect(&stt, &services::SpeechService::transcription_ready, this, &AiChatBubble::on_transcription);- connect(&stt, &services::SpeechService::listening_changed, this, &AiChatBubble::on_stt_listening_changed);- connect(&stt, &services::SpeechService::error_occurred, this, &AiChatBubble::on_stt_error);+ connect(&stt, &services::SpeechService::listening_changed, this, &AiChatBubble::on_stt_listening_changed);+ connect(&stt, &services::SpeechService::error_occurred, this, &AiChatBubble::on_stt_error);++ // TTS wiring — drives the "Speaking" status + auto-resume in voice mode+ auto& tts = services::TtsService::instance();+ connect(&tts, &services::TtsService::speaking_started, this, [this]() {+ is_speaking_ = true;+ error_msg_.clear();+ render_status();+ });+ connect(&tts, &services::TtsService::speaking_finished, this, [this]() {+ is_speaking_ = false;+ render_status();+ if (voice_mode_ && is_open_ && !is_listening_ && !streaming_)+ QTimer::singleShot(400, this, &AiChatBubble::start_listening);+ });+ connect(&tts, &services::TtsService::error_occurred, this, [this](const QString& msg) {+ LOG_WARN("AiChatBubble", QString("TTS error: %1").arg(msg));+ is_speaking_ = false;+ error_msg_ = msg;+ render_status();+ if (voice_mode_ && is_open_ && !is_listening_)+ QTimer::singleShot(600, this, &AiChatBubble::start_listening);+ });++ // Clap-to-start trigger. The service is idle by default — only started+ // when AppConfig "voice/clap_to_start/enabled" is true. When the service+ // hears a clap it fires `clap_detected()`; we open the panel and start+ // the mic. The detector pauses while STT is active and resumes on stop.+ auto& clap = services::ClapDetectorService::instance();+ connect(&clap, &services::ClapDetectorService::clap_detected, this, [this]() {+ LOG_INFO("AiChatBubble", "Clap detected — opening panel + starting mic");+ if (!is_open_)+ open_panel();+ if (!is_listening_ && !is_speaking_)+ start_listening();+ });+ if (services::ClapDetectorService::is_enabled_in_config())+ clap.start();if (parent)parent->installEventFilter(this);+reposition();raise();@@ -87,35 +157,8 @@ void AiChatBubble::refresh_theme() {.arg(col::BG_SURFACE(), col::BORDER_BRIGHT()));if (chat_panel_)chat_panel_->setStyleSheet(- QString("background:%1;border:1px solid %2;border-radius:0px;").arg(col::BG_SURFACE(), col::BORDER_MED()));- if (msg_container_)- msg_container_->setStyleSheet(QString("background:%1;").arg(col::BG_SURFACE()));- if (scroll_area_)- scroll_area_->setStyleSheet(- QString("QScrollArea{background:%1;border:none;}"- "QScrollBar:vertical{background:transparent;width:4px;margin:2px;}"- "QScrollBar::handle:vertical{background:%2;border-radius:0px;min-height:20px;}"- "QScrollBar::handle:vertical:hover{background:%3;}"- "QScrollBar::add-line:vertical,QScrollBar::sub-line:vertical{height:0;}")- .arg(col::BG_SURFACE(), col::BORDER_MED(), col::AMBER()));- if (input_box_)- input_box_->setStyleSheet(QString("QPlainTextEdit{background:%1;color:%2;border:1px solid %3;"- "border-radius:0px;padding:6px 10px;font-size:13px;}"- "QPlainTextEdit:focus{border-color:%4;}")- .arg(col::BG_RAISED(), col::TEXT_PRIMARY(), col::BORDER_MED(), col::AMBER()));- if (send_btn_)- send_btn_->setStyleSheet(- QString("QPushButton{background:%1;color:%2;border:none;"- "border-radius:0px;font-size:20px;font-weight:700;}"- "QPushButton:hover:enabled{background:%3;}"- "QPushButton:disabled{background:%4;color:%5;}")- .arg(col::AMBER(), col::BG_BASE(), col::AMBER_DIM(), col::BG_RAISED(), col::TEXT_TERTIARY()));- if (mic_btn_)- mic_btn_->setStyleSheet(QString("QPushButton{background:transparent;color:%1;border:1px solid %2;"- "border-radius:0px;font-size:18px;}"- "QPushButton:hover{border-color:%3;}"- "QPushButton:checked{background:%4;border-color:%4;}")- .arg(col::TEXT_PRIMARY(), col::BORDER_MED(), col::AMBER(), col::AMBER_DIM()));+ QString("QWidget#chatPanel{background:%1;border:1px solid %2;border-radius:0px;}")+ .arg(col::BG_SURFACE(), col::BORDER_MED()));}// ── Reposition ────────────────────────────────────────────────────────────────@@ -124,16 +167,17 @@ void AiChatBubble::reposition() {return;const QRect pr = parentWidget()->rect();- const int bx = pr.width() - BTN_SIZE - MARGIN;+ const int bx = pr.width() - BTN_SIZE - MARGIN;const int by = pr.height() - BTN_SIZE - MARGIN;setGeometry(bx, by, BTN_SIZE, BTN_SIZE);bubble_btn_->setGeometry(0, 0, BTN_SIZE, BTN_SIZE);- const int px = pr.width() - PANEL_W - MARGIN;+ const int px = pr.width() - PANEL_W - MARGIN;const int py = pr.height() - PANEL_H - BTN_SIZE - MARGIN - 10;if (chat_panel_->parentWidget() != parentWidget())chat_panel_->setParent(parentWidget());chat_panel_->setGeometry(px, (py < 4 ? 4 : py), PANEL_W, PANEL_H);+if (is_open_) {chat_panel_->show();chat_panel_->raise();@@ -141,18 +185,20 @@ void AiChatBubble::reposition() {raise();}-// ── Bubble button ─────────────────────────────────────────────────────────────+// ── Bubble (collapsed) button ────────────────────────────────────────────────void AiChatBubble::build_bubble_button() {bubble_btn_ = new QWidget(this);bubble_btn_->setFixedSize(BTN_SIZE, BTN_SIZE);bubble_btn_->setCursor(Qt::PointingHandCursor);- bubble_btn_->setStyleSheet(- QString("background:%1;border:2px solid %2;border-radius:0px;").arg(col::BG_SURFACE(), col::BORDER_BRIGHT()));+ bubble_btn_->setToolTip("Quick Chat (separate from AI Chat tab)");+ bubble_btn_->setStyleSheet(QString("background:%1;border:2px solid %2;border-radius:0px;")+ .arg(col::BG_SURFACE(), col::BORDER_BRIGHT()));auto* lbl = new QLabel("⬡", bubble_btn_);lbl->setAlignment(Qt::AlignCenter);lbl->setGeometry(0, 0, BTN_SIZE, BTN_SIZE);- lbl->setStyleSheet(QString("color:%1;font-size:24px;background:transparent;").arg(col::TEXT_PRIMARY()));+ lbl->setStyleSheet(QString("color:%1;font-size:24px;background:transparent;")+ .arg(col::TEXT_PRIMARY()));unread_badge_ = new QLabel(bubble_btn_);unread_badge_->setFixedSize(18, 18);@@ -169,10 +215,11 @@ void AiChatBubble::build_bubble_button() {// ── Chat panel ────────────────────────────────────────────────────────────────void AiChatBubble::build_chat_panel() {chat_panel_ = new QWidget(nullptr);- chat_panel_->setFixedSize(PANEL_W, PANEL_H);- chat_panel_->setStyleSheet(QString("QWidget#chatPanel{background:%1;border:1px solid %2;border-radius:0px;}")- .arg(col::BG_SURFACE(), col::BORDER_MED()));chat_panel_->setObjectName("chatPanel");+ chat_panel_->setFixedSize(PANEL_W, PANEL_H);+ chat_panel_->setStyleSheet(+ QString("QWidget#chatPanel{background:%1;border:1px solid %2;border-radius:0px;}")+ .arg(col::BG_SURFACE(), col::BORDER_MED()));auto* vl = new QVBoxLayout(chat_panel_);vl->setContentsMargins(0, 0, 0, 0);@@ -180,14 +227,14 @@ void AiChatBubble::build_chat_panel() {vl->addWidget(build_panel_header());- // Message scroll area+ // ── Messages scroll area ─────────────────────────────────────────────────scroll_area_ = new QScrollArea;scroll_area_->setWidgetResizable(true);scroll_area_->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);scroll_area_->setFrameShape(QFrame::NoFrame);scroll_area_->setStyleSheet(QString("QScrollArea{background:%1;border:none;}"- "QScrollBar:vertical{background:transparent;width:4px;margin:2px;}"- "QScrollBar::handle:vertical{background:%2;border-radius:0px;min-height:20px;}"+ "QScrollBar:vertical{background:transparent;width:5px;margin:2px;}"+ "QScrollBar::handle:vertical{background:%2;border-radius:0px;min-height:24px;}""QScrollBar::handle:vertical:hover{background:%3;}""QScrollBar::add-line:vertical,QScrollBar::sub-line:vertical{height:0;}").arg(col::BG_SURFACE(), col::BORDER_MED(), col::AMBER()));@@ -202,22 +249,10 @@ void AiChatBubble::build_chat_panel() {scroll_area_->setWidget(msg_container_);vl->addWidget(scroll_area_, 1);- // Typing indicator- auto* typing_row = new QWidget;- typing_row->setStyleSheet("background:transparent;");- typing_row->setFixedHeight(22);- auto* typing_hl = new QHBoxLayout(typing_row);- typing_hl->setContentsMargins(16, 0, 0, 0);- typing_hl->setSpacing(0);- // We use voice_status_lbl_ to also show typing state (reuse slot)- voice_status_lbl_ = new QLabel;- voice_status_lbl_->setStyleSheet(- QString("color:%1;font-size:11px;font-style:italic;background:transparent;").arg(col::TEXT_TERTIARY()));- typing_hl->addWidget(voice_status_lbl_);- typing_hl->addStretch();- vl->addWidget(typing_row);-- // Divider+ build_welcome_widget();+ show_welcome_if_empty();++ // ── Divider ──────────────────────────────────────────────────────────────auto* sep = new QFrame;sep->setFrameShape(QFrame::HLine);sep->setFixedHeight(1);@@ -225,59 +260,72 @@ void AiChatBubble::build_chat_panel() {vl->addWidget(sep);vl->addWidget(build_input_row());- vl->addWidget(build_voice_status_bar());+ vl->addWidget(build_status_strip());}QWidget* AiChatBubble::build_panel_header() {auto* hdr = new QWidget;- hdr->setFixedHeight(46);- hdr->setStyleSheet(QString("background:%1;border-radius:0px;border-bottom:1px solid %2;")+ hdr->setFixedHeight(HEADER_H);+ hdr->setStyleSheet(QString("background:%1;border-bottom:1px solid %2;").arg(col::BG_RAISED(), col::BORDER_MED()));auto* hl = new QHBoxLayout(hdr);- hl->setContentsMargins(14, 0, 10, 0);+ hl->setContentsMargins(14, 8, 8, 8);hl->setSpacing(8);- auto* icon = new QLabel("⬡");- icon->setStyleSheet(QString("color:%1;font-size:20px;background:transparent;").arg(col::TEXT_PRIMARY()));- hl->addWidget(icon);+ // Title block — title + subtitle stacked+ auto* title_col = new QWidget;+ title_col->setStyleSheet("background:transparent;");+ auto* tl = new QVBoxLayout(title_col);+ tl->setContentsMargins(0, 0, 0, 0);+ tl->setSpacing(0);++ auto* title = new QLabel("Quick Chat");+ title->setStyleSheet(QString("color:%1;font-size:13px;font-weight:700;background:transparent;")+ .arg(col::TEXT_PRIMARY()));+ tl->addWidget(title);++ auto* subtitle = new QLabel("Not saved · separate from AI Chat tab");+ subtitle->setStyleSheet(QString("color:%1;font-size:10px;background:transparent;")+ .arg(col::TEXT_TERTIARY()));+ tl->addWidget(subtitle);- auto* title = new QLabel("Fincept AI");- title->setStyleSheet(- QString("color:%1;font-size:13px;font-weight:700;background:transparent;").arg(col::TEXT_PRIMARY()));- hl->addWidget(title, 1);+ hl->addWidget(title_col, 1);- // Voice mode toggle+ // Voice mode toggle (continuous mic + speak)voice_mode_btn_ = new QPushButton("Voice");- voice_mode_btn_->setFixedHeight(24);+ voice_mode_btn_->setFixedHeight(26);voice_mode_btn_->setCheckable(true);voice_mode_btn_->setCursor(Qt::PointingHandCursor);+ voice_mode_btn_->setToolTip("Toggle continuous voice conversation (auto-listen + auto-speak)");voice_mode_btn_->setStyleSheet(QString("QPushButton{background:transparent;color:%1;border:1px solid %2;"- "font-size:11px;font-weight:600;border-radius:0px;padding:0 8px;}"+ "font-size:11px;font-weight:600;border-radius:0px;padding:0 10px;}""QPushButton:checked{background:%3;color:%4;border-color:%3;}"- "QPushButton:hover:!checked{color:%4;border-color:%5;}")- .arg(col::TEXT_SECONDARY(), col::BORDER_MED(), col::AMBER(), col::BG_BASE(), col::AMBER()));+ "QPushButton:hover:!checked{color:%5;border-color:%5;}")+ .arg(col::TEXT_SECONDARY(), col::BORDER_MED(),+ col::AMBER(), col::BG_BASE(), col::AMBER()));connect(voice_mode_btn_, &QPushButton::clicked, this, &AiChatBubble::on_toggle_voice_mode);hl->addWidget(voice_mode_btn_);- // New chat button- new_btn_ = new QPushButton("+");- new_btn_->setFixedSize(28, 26);+ // Clear chat (does NOT touch ChatRepository — wipes in-memory only)+ new_btn_ = new QPushButton("Clear");+ new_btn_->setFixedHeight(26);new_btn_->setCursor(Qt::PointingHandCursor);- new_btn_->setToolTip("New conversation");+ new_btn_->setToolTip("Clear this chat (Ctrl+L)");new_btn_->setStyleSheet(QString("QPushButton{background:transparent;color:%1;border:1px solid %2;"- "font-size:18px;font-weight:700;border-radius:0px;}"- "QPushButton:hover{background:%3;color:%1;}")- .arg(col::TEXT_PRIMARY(), col::BORDER_MED(), col::BG_HOVER()));- connect(new_btn_, &QPushButton::clicked, this, &AiChatBubble::on_new_session);+ "font-size:11px;font-weight:600;border-radius:0px;padding:0 10px;}"+ "QPushButton:hover{color:%3;border-color:%3;}")+ .arg(col::TEXT_SECONDARY(), col::BORDER_MED(), col::AMBER()));+ connect(new_btn_, &QPushButton::clicked, this, &AiChatBubble::on_clear_chat);hl->addWidget(new_btn_);- // Close button- close_btn_ = new QPushButton("✕");+ // Close (Esc)+ close_btn_ = new QPushButton("X");close_btn_->setFixedSize(26, 26);close_btn_->setCursor(Qt::PointingHandCursor);- close_btn_->setStyleSheet(QString("QPushButton{background:transparent;color:%1;border:none;font-size:16px;}"+ close_btn_->setToolTip("Close (Esc)");+ close_btn_->setStyleSheet(QString("QPushButton{background:transparent;color:%1;border:none;font-size:14px;}""QPushButton:hover{color:%2;}").arg(col::TEXT_PRIMARY(), col::NEGATIVE()));connect(close_btn_, &QPushButton::clicked, this, &AiChatBubble::close_panel);@@ -288,7 +336,7 @@ QWidget* AiChatBubble::build_panel_header() {QWidget* AiChatBubble::build_input_row() {auto* row = new QWidget;- row->setFixedHeight(58);+ row->setFixedHeight(INPUT_H);row->setStyleSheet(QString("background:%1;").arg(col::BG_SURFACE()));auto* hl = new QHBoxLayout(row);@@ -296,149 +344,190 @@ QWidget* AiChatBubble::build_input_row() {hl->setSpacing(6);input_box_ = new QPlainTextEdit;- input_box_->setFixedHeight(38);- input_box_->setPlaceholderText("Ask anything…");+ input_box_->setFixedHeight(40);+ input_box_->setPlaceholderText("Ask anything… (Enter to send, Shift+Enter for newline)");input_box_->setStyleSheet(QString("QPlainTextEdit{background:%1;color:%2;border:1px solid %3;""border-radius:0px;padding:6px 10px;font-size:13px;}""QPlainTextEdit:focus{border-color:%4;}")- .arg(col::BG_RAISED(), col::TEXT_PRIMARY(), col::BORDER_MED(), col::AMBER()));+ .arg(col::BG_RAISED(), col::TEXT_PRIMARY(),+ col::BORDER_MED(), col::AMBER()));input_box_->installEventFilter(this);hl->addWidget(input_box_, 1);mic_btn_ = new QPushButton("🎤");- mic_btn_->setFixedSize(36, 36);- mic_btn_->setCheckable(true);+ mic_btn_->setFixedSize(38, 38);mic_btn_->setCursor(Qt::PointingHandCursor);- mic_btn_->setToolTip("Voice input");+ mic_btn_->setToolTip("Push-to-talk: click to dictate one message");+ // No setCheckable — listening state is rendered via property + opacity.mic_btn_->setStyleSheet(QString("QPushButton{background:transparent;color:%1;border:1px solid %2;""border-radius:0px;font-size:18px;}""QPushButton:hover{border-color:%3;}"- "QPushButton:checked{background:%4;border-color:%4;}")- .arg(col::TEXT_PRIMARY(), col::BORDER_MED(), col::AMBER(), col::AMBER_DIM()));+ "QPushButton[listening=\"true\"]{background:%4;border-color:%3;color:%5;}")+ .arg(col::TEXT_PRIMARY(), col::BORDER_MED(), col::AMBER(),+ col::AMBER_DIM(), col::BG_BASE()));+ mic_btn_->setProperty("listening", false);connect(mic_btn_, &QPushButton::clicked, this, &AiChatBubble::on_toggle_mic);hl->addWidget(mic_btn_);- send_btn_ = new QPushButton("↑");- send_btn_->setFixedSize(36, 36);+ send_btn_ = new QPushButton("Send");+ send_btn_->setFixedSize(56, 38);send_btn_->setCursor(Qt::PointingHandCursor);- send_btn_->setToolTip("Send (Enter)");- send_btn_->setStyleSheet(- QString("QPushButton{background:%1;color:%2;border:none;"- "border-radius:0px;font-size:20px;font-weight:700;}"- "QPushButton:hover:enabled{background:%3;}"- "QPushButton:disabled{background:%4;color:%5;}")- .arg(col::AMBER(), col::BG_BASE(), col::AMBER_DIM(), col::BG_RAISED(), col::TEXT_TERTIARY()));+ send_btn_->setToolTip("Send (Enter)");+ send_btn_->setStyleSheet(QString("QPushButton{background:%1;color:%2;border:none;"+ "border-radius:0px;font-size:12px;font-weight:700;}"+ "QPushButton:hover:enabled{background:%3;}"+ "QPushButton:disabled{background:%4;color:%5;}")+ .arg(col::AMBER(), col::BG_BASE(), col::AMBER_DIM(),+ col::BG_RAISED(), col::TEXT_TERTIARY()));connect(send_btn_, &QPushButton::clicked, this, &AiChatBubble::on_send);hl->addWidget(send_btn_);return row;}-QWidget* AiChatBubble::build_voice_status_bar() {- voice_status_bar_ = new QWidget;- voice_status_bar_->setFixedHeight(28);- voice_status_bar_->setStyleSheet(- QString("background:%1;border-top:1px solid %2;border-radius:0px;").arg(col::BG_RAISED(), col::BORDER_DIM()));+QWidget* AiChatBubble::build_status_strip() {+ status_strip_ = new QWidget;+ status_strip_->setFixedHeight(STATUS_H);+ status_strip_->setStyleSheet(QString("background:%1;border-top:1px solid %2;")+ .arg(col::BG_RAISED(), col::BORDER_DIM()));- auto* hl = new QHBoxLayout(voice_status_bar_);- hl->setContentsMargins(12, 0, 10, 0);- hl->setSpacing(6);+ auto* hl = new QHBoxLayout(status_strip_);+ hl->setContentsMargins(12, 0, 8, 0);+ hl->setSpacing(8);- // Note: voice_status_lbl_ is used for typing indicator above.- // This bar holds stop button only.- auto* status_lbl = new QLabel("Voice mode active");- status_lbl->setStyleSheet(QString("color:%1;font-size:11px;background:transparent;").arg(col::TEXT_TERTIARY()));- hl->addWidget(status_lbl, 1);+ status_dot_ = new QLabel("●");+ status_dot_->setStyleSheet(QString("color:%1;font-size:11px;background:transparent;")+ .arg(col::TEXT_TERTIARY()));+ hl->addWidget(status_dot_);- stop_speech_btn_ = new QPushButton("■ Stop");+ status_lbl_ = new QLabel;+ status_lbl_->setStyleSheet(QString("color:%1;font-size:11px;background:transparent;")+ .arg(col::TEXT_TERTIARY()));+ status_lbl_->setWordWrap(false);+ status_lbl_->setTextInteractionFlags(Qt::TextSelectableByMouse);+ hl->addWidget(status_lbl_, 1);++ stop_speech_btn_ = new QPushButton("Stop");stop_speech_btn_->setFixedHeight(20);stop_speech_btn_->setCursor(Qt::PointingHandCursor);+ stop_speech_btn_->setToolTip("Stop speaking");stop_speech_btn_->setStyleSheet(QString("QPushButton{background:%1;color:white;border:none;"- "font-size:10px;font-weight:700;border-radius:0px;padding:0 8px;}"+ "font-size:10px;font-weight:700;border-radius:0px;padding:0 10px;}""QPushButton:hover{background:%2;}").arg(col::NEGATIVE(), col::WARNING()));stop_speech_btn_->hide();connect(stop_speech_btn_, &QPushButton::clicked, this, &AiChatBubble::on_stop_speech);hl->addWidget(stop_speech_btn_);- voice_status_bar_->hide();- return voice_status_bar_;+ status_strip_->hide(); // hidden when status is Idle+ return status_strip_;}-// ── Open / Close ──────────────────────────────────────────────────────────────-void AiChatBubble::on_toggle_open() {- if (is_open_)- close_panel();- else- open_panel();+// ── Welcome card (replaces the fragile "remove on first message" trick) ─────+void AiChatBubble::build_welcome_widget() {+ welcome_widget_ = new QWidget;+ welcome_widget_->setStyleSheet("background:transparent;");+ auto* wvl = new QVBoxLayout(welcome_widget_);+ wvl->setContentsMargins(8, 32, 8, 8);+ wvl->setSpacing(8);++ auto* glyph = new QLabel("⬡");+ glyph->setAlignment(Qt::AlignCenter);+ glyph->setStyleSheet(QString("color:%1;font-size:36px;background:transparent;")+ .arg(col::AMBER()));+ wvl->addWidget(glyph);++ auto* h = new QLabel("How can I help?");+ h->setAlignment(Qt::AlignCenter);+ h->setStyleSheet(QString("color:%1;font-size:14px;font-weight:700;background:transparent;")+ .arg(col::TEXT_PRIMARY()));+ wvl->addWidget(h);++ auto* sub = new QLabel("Ask a quick question. Nothing here is saved.\n"+ "For long-form chats use the AI Chat tab.");+ sub->setAlignment(Qt::AlignCenter);+ sub->setWordWrap(true);+ sub->setStyleSheet(QString("color:%1;font-size:11px;background:transparent;")+ .arg(col::TEXT_TERTIARY()));+ wvl->addWidget(sub);++ wvl->addStretch();+}++void AiChatBubble::show_welcome_if_empty() {+ if (!welcome_widget_ || !msg_layout_)+ return;+ if (chat_history_.empty() && welcome_widget_->parent() != msg_container_) {+ msg_layout_->insertWidget(msg_layout_->count() - 1, welcome_widget_);+ welcome_widget_->show();+ }+}++void AiChatBubble::hide_welcome() {+ if (welcome_widget_ && welcome_widget_->parent() == msg_container_) {+ msg_layout_->removeWidget(welcome_widget_);+ welcome_widget_->setParent(nullptr);+ welcome_widget_->hide();+ }}+// ── Open / Close ──────────────────────────────────────────────────────────────void AiChatBubble::open_panel() {if (is_open_)return;is_open_ = true;unread_count_ = 0;unread_badge_->hide();- ensure_session();reposition();chat_panel_->show();chat_panel_->raise();raise();input_box_->setFocus();+ render_status();}void AiChatBubble::close_panel() {is_open_ = false;+ // Voice mode running while the panel is hidden is confusing — turn it off.+ if (voice_mode_) {+ voice_mode_ = false;+ if (voice_mode_btn_)+ voice_mode_btn_->setChecked(false);+ }+ if (is_listening_)+ stop_listening();+ if (is_speaking_)+ stop_tts();chat_panel_->hide();+ // Closing the panel doesn't disable clap-to-start — that is a global+ // wake-up trigger, not panel state. The clap detector keeps running so+ // the user can summon the bubble back with a clap.}-// ── Session — always start fresh on first open ────────────────────────────────-void AiChatBubble::ensure_session() {- // Always create a new session if none active — never load existing chat history- if (!active_session_id_.isEmpty())- return;- on_new_session();-}+// ── Clear chat (in-memory only — never touches ChatRepository) ────────────────+void AiChatBubble::on_clear_chat() {+ LOG_INFO("AiChatBubble", "Clearing chat (in-memory only)");+ // Stop any ongoing voice activity+ if (is_listening_) stop_listening();+ if (is_speaking_) stop_tts();-void AiChatBubble::on_new_session() {- // Clear message UI+ // Tear down message widgets but keep the trailing stretch.while (msg_layout_->count() > 1) {auto* item = msg_layout_->takeAt(0);if (item->widget())item->widget()->deleteLater();delete item;}- history_.clear();+ chat_history_.clear();streaming_bubble_.clear();- active_session_id_.clear();-- // Show a brief welcome hint- const QString title = QString("Quick Chat %1").arg(QDateTime::currentDateTime().toString("hh:mm"));- auto res = ChatRepository::instance().create_session(title, ai_chat::LlmService::instance().active_provider(),- ai_chat::LlmService::instance().active_model());-- if (res.is_ok()) {- active_session_id_ = res.value().id;- // Show a placeholder hint- auto* hint = new QLabel("How can I help you?");- hint->setAlignment(Qt::AlignCenter);- hint->setStyleSheet(- QString("color:%1;font-size:13px;font-style:italic;background:transparent;").arg(col::TEXT_TERTIARY()));- msg_layout_->insertWidget(msg_layout_->count() - 1, hint);- } else {- // Session creation failed — show error and block input so the user- // isn't silently sending messages with no persistence.- auto* err = new QLabel("Session error — please restart.");- err->setAlignment(Qt::AlignCenter);- err->setStyleSheet("color:#ef4444;font-size:12px;background:transparent;");- msg_layout_->insertWidget(msg_layout_->count() - 1, err);- if (input_box_)- input_box_->setEnabled(false);- LOG_ERROR("AiChatBubble", "Failed to create chat session: " + QString::fromStdString(res.error()));- }+ streaming_ = false;+ error_msg_.clear();- if (voice_status_lbl_)- voice_status_lbl_->clear();+ // Rebuild welcome card and re-show it.+ build_welcome_widget();+ show_welcome_if_empty();+ set_input_enabled(true);+ render_status();}// ── Send ──────────────────────────────────────────────────────────────────────@@ -447,46 +536,33 @@ void AiChatBubble::on_send() {if (text.isEmpty() || streaming_)return;- // Fail fast if LLM is not configured — show inline error instead of a- // confusing delayed "No provider" message after the network round-trip.+ // Fail fast if LLM is not configured — inline error beats a confusing+ // delayed network failure.if (!ai_chat::LlmService::instance().is_configured()) {- add_bubble("assistant", "AI chat is not configured. Please go to **Settings → LLM Config** "- "and add an API key or select the Fincept provider.");+ add_bubble("assistant",+ "AI chat is not configured. Open **Settings → LLM Config** "+ "and add an API key or pick the Fincept provider.");return;}input_box_->clear();- ensure_session();-- // Remove the welcome hint if present (first message)- if (msg_layout_->count() == 2) { // stretch + hint- auto* item = msg_layout_->takeAt(0);- if (item->widget())- item->widget()->deleteLater();- delete item;- }+ hide_welcome();add_bubble("user", text);- history_.push_back({"user", text});- ChatRepository::instance().add_message(active_session_id_, "user", text);+ chat_history_.push_back({"user", text});streaming_ = true;- set_ui_enabled(false);+ error_msg_.clear();+ set_input_enabled(false);+ render_status();- // Show typing indicator- if (voice_status_lbl_)- voice_status_lbl_->setText("AI is thinking…");-- // Defer streaming bubble creation to first non-empty chunk.- // Use shared_ptr<bool> so the single flag is shared between outer (bg thread)- // and inner (UI thread) lambdas — no mutable bool copies across thread boundary.+ // Defer streaming bubble creation to the first non-empty chunk.QPointer<AiChatBubble> self = this;auto first_chunk = std::make_shared<bool>(true);- // Pass use_tools=false — the floating bubble should never trigger- // navigation or other tool side-effects that would hijack the user's- // current screen.+ // use_tools=false — the floating bubble must never trigger navigation+ // or other tool side-effects that hijack the user's current screen.ai_chat::LlmService::instance().chat_streaming(- text, history_,+ text, chat_history_,[self, first_chunk](const QString& chunk, bool done) {QMetaObject::invokeMethod(qApp,@@ -495,8 +571,6 @@ void AiChatBubble::on_send() {return;if (*first_chunk && !chunk.isEmpty()) {*first_chunk = false;- if (self->voice_status_lbl_)- self->voice_status_lbl_->clear();self->streaming_bubble_ = self->add_streaming_bubble();}self->on_stream_chunk(chunk, done);@@ -507,7 +581,6 @@ void AiChatBubble::on_send() {}void AiChatBubble::on_stream_chunk(const QString& chunk, bool done) {- // Snapshot QPointer to local — prevents TOCTOU between null-check and use.QTextEdit* bubble = streaming_bubble_;if (!bubble)return;@@ -519,68 +592,39 @@ void AiChatBubble::on_stream_chunk(const QString& chunk, bool done) {Q_UNUSED(done)}-// ── Bubble-panel markdown CSS (compact version for the mini chat) ─────────────-static QString bubble_panel_md_css(const QString& text_color) {- return QString("body { color: %1; line-height: 1.4; }"- "p { margin-top: 4px; margin-bottom: 4px; }"- "ul, ol { margin-top: 3px; margin-bottom: 3px; padding-left: 16px; }"- "li { margin-top: 2px; margin-bottom: 2px; }"- "h1, h2, h3, h4 { margin-top: 8px; margin-bottom: 3px; color: %2; font-weight: 700; }"- "hr { margin-top: 6px; margin-bottom: 6px; border: none; "- " border-top: 1px solid %3; }"- "a { color: %2; text-decoration: underline; }"- "code { background: %4; color: %2; padding: 1px 3px; "- " font-family: 'Consolas', 'Courier New', monospace; font-size: 12px; }"- "pre { background: %4; border: 1px solid %3; padding: 8px 10px; "- " margin-top: 4px; margin-bottom: 4px; "- " font-family: 'Consolas', 'Courier New', monospace; font-size: 12px; }"- "blockquote { border-left: 2px solid %2; padding-left: 8px; "- " margin-top: 4px; margin-bottom: 4px; color: %5; }"- "table { border-collapse: collapse; margin-top: 4px; margin-bottom: 4px; }"- "th { background: %4; border: 1px solid %3; padding: 3px 6px; "- " font-weight: 600; color: %2; }"- "td { border: 1px solid %3; padding: 3px 6px; }"- "strong { color: %1; font-weight: 700; }")- .arg(text_color, col::AMBER(), col::BORDER_MED(), col::BG_BASE(), col::TEXT_SECONDARY());-}-void AiChatBubble::on_streaming_done(ai_chat::LlmResponse response) {streaming_ = false;- if (voice_status_lbl_)- voice_status_lbl_->clear();- set_ui_enabled(true);+ set_input_enabled(true);- const QString content = response.success ? response.content : QString("Error: %1").arg(response.error);+ const QString content = response.success ? response.content+ : QString("Error: %1").arg(response.error);- // Non-streaming path: create bubble nowif (!streaming_bubble_ && !content.isEmpty()) {streaming_bubble_ = add_streaming_bubble();streaming_bubble_->setPlainText(content);}if (streaming_bubble_) {- // Convert streamed plain text to rendered markdownconst QString final_text = streaming_bubble_->toPlainText();if (!final_text.isEmpty()) {- streaming_bubble_->document()->setDefaultStyleSheet(bubble_panel_md_css(col::TEXT_PRIMARY()));+ streaming_bubble_->document()->setDefaultStyleSheet(bubble_md_css(col::TEXT_PRIMARY()));streaming_bubble_->setMarkdown(final_text);}streaming_bubble_->setReadOnly(true);streaming_bubble_ = nullptr;}- history_.push_back({"assistant", content});- ChatRepository::instance().add_message(active_session_id_, "assistant", content,- ai_chat::LlmService::instance().active_provider(),- ai_chat::LlmService::instance().active_model(), response.total_tokens);+ chat_history_.push_back({"assistant", content});if (!is_open_)update_unread(1);- if (voice_mode_ && response.success)+ if (voice_mode_ && response.success) {speak_text(content);- else if (voice_mode_)+ } else if (voice_mode_) {start_listening();+ }+ render_status();}// ── Message bubbles ───────────────────────────────────────────────────────────@@ -598,36 +642,32 @@ void AiChatBubble::add_bubble(const QString& role, const QString& text) {auto* col_w = new QWidget;col_w->setStyleSheet("background:transparent;");- col_w->setMaximumWidth(static_cast<int>(PANEL_W * 0.82));+ col_w->setMaximumWidth(static_cast<int>(PANEL_W * 0.84));auto* cvl = new QVBoxLayout(col_w);cvl->setContentsMargins(0, 0, 0, 0);cvl->setSpacing(3);- // Role micro-labelauto* role_lbl = new QLabel(is_user ? "You" : "AI");role_lbl->setAlignment(is_user ? Qt::AlignRight : Qt::AlignLeft);role_lbl->setStyleSheet(QString("color:%1;font-size:10px;font-weight:700;background:transparent;")- .arg(is_user ? col::AMBER() : col::AMBER()));+ .arg(col::AMBER()));cvl->addWidget(role_lbl);- // Bubble — use QTextEdit for consistent markdown renderingauto* body = new QTextEdit;body->setReadOnly(true);body->setFrameShape(QFrame::NoFrame);body->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum);body->document()->setDocumentMargin(0);- body->document()->setDefaultStyleSheet(bubble_panel_md_css(is_user ? "#fff7ed" : col::TEXT_PRIMARY()));+ body->document()->setDefaultStyleSheet(bubble_md_css(is_user ? "#fff7ed" : col::TEXT_PRIMARY()));apply_obsidian_palette(body);body->setMarkdown(text);body->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);body->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);- // inner_w = max bubble width minus h-padding (8px each side)- const int inner_w = static_cast<int>(PANEL_W * 0.82) - 16;+ const int inner_w = static_cast<int>(PANEL_W * 0.84) - 18;body->document()->setTextWidth(inner_w);body->setStyleSheet(QString("QTextEdit{background:transparent;color:%1;border:none;""font-size:13px;padding:0px;}").arg(is_user ? "#fff7ed" : col::TEXT_PRIMARY()));- // Use ideal height — document already laid out at inner_w, no extra fudge neededconst int doc_h = static_cast<int>(body->document()->size().height());body->setFixedHeight(qMax(doc_h, 18));@@ -636,7 +676,7 @@ void AiChatBubble::add_bubble(const QString& role, const QString& text) {.arg(is_user ? "rgba(120,53,15,0.45)" : col::BG_SURFACE(),is_user ? "rgba(217,119,6,0.28)" : col::BORDER_DIM()));auto* bvl = new QVBoxLayout(bubble_frame);- bvl->setContentsMargins(8, 5, 8, 5);+ bvl->setContentsMargins(9, 6, 9, 6);bvl->setSpacing(0);bvl->addWidget(body);cvl->addWidget(bubble_frame);@@ -657,15 +697,15 @@ QTextEdit* AiChatBubble::add_streaming_bubble() {auto* col_w = new QWidget;col_w->setStyleSheet("background:transparent;");- col_w->setMaximumWidth(static_cast<int>(PANEL_W * 0.82));+ col_w->setMaximumWidth(static_cast<int>(PANEL_W * 0.84));auto* cvl = new QVBoxLayout(col_w);cvl->setContentsMargins(0, 0, 0, 0);cvl->setSpacing(3);auto* role_lbl = new QLabel("AI");role_lbl->setAlignment(Qt::AlignLeft);- role_lbl->setStyleSheet(- QString("color:%1;font-size:10px;font-weight:700;background:transparent;").arg(col::AMBER()));+ role_lbl->setStyleSheet(QString("color:%1;font-size:10px;font-weight:700;background:transparent;")+ .arg(col::AMBER()));cvl->addWidget(role_lbl);auto* body = new QTextEdit;@@ -673,19 +713,20 @@ QTextEdit* AiChatBubble::add_streaming_bubble() {body->setFrameShape(QFrame::NoFrame);body->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);body->document()->setDocumentMargin(0);- body->document()->setDefaultStyleSheet(bubble_panel_md_css(col::TEXT_PRIMARY()));+ body->document()->setDefaultStyleSheet(bubble_md_css(col::TEXT_PRIMARY()));apply_obsidian_palette(body);body->setFixedHeight(20);body->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);body->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);body->setWordWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);body->setStyleSheet(QString("QTextEdit{background:%1;color:%2;border:1px solid %3;"- "border-radius:0px;padding:5px 8px;font-size:13px;}")+ "border-radius:0px;padding:6px 9px;font-size:13px;}").arg(col::BG_SURFACE(), col::TEXT_PRIMARY(), col::BORDER_DIM()));- // Dynamic height as content streams in — recalc at viewport width, no fudge factorconnect(body->document(), &QTextDocument::contentsChanged, body, [body, col_w, row]() {- const int vw = body->viewport()->width() > 0 ? body->viewport()->width() : (static_cast<int>(PANEL_W * 0.82) - 16);+ const int vw = body->viewport()->width() > 0+ ? body->viewport()->width()+ : (static_cast<int>(PANEL_W * 0.84) - 18);body->document()->setTextWidth(vw);const int h = qMax(static_cast<int>(body->document()->size().height()), 20);body->setFixedHeight(h);@@ -709,11 +750,13 @@ void AiChatBubble::scroll_to_bottom() {});}-void AiChatBubble::set_ui_enabled(bool enabled) {+void AiChatBubble::set_input_enabled(bool enabled) {send_btn_->setEnabled(enabled);- mic_btn_->setEnabled(enabled);input_box_->setEnabled(enabled);- send_btn_->setText(enabled ? "↑" : "…");+ // Mic stays clickable so the user can cancel a stuck listen, but it's+ // greyed visually while streaming.+ mic_btn_->setEnabled(enabled || is_listening_);+ send_btn_->setText(enabled ? "Send" : "…");}void AiChatBubble::update_unread(int delta) {@@ -726,9 +769,10 @@ void AiChatBubble::update_unread(int delta) {}}-// ── Voice input (STT — Python speech_recognition + Google API) ───────────────-+// ── Voice input (STT) ────────────────────────────────────────────────────────void AiChatBubble::on_toggle_mic() {+ LOG_INFO("AiChatBubble", QString("Mic toggled — listening=%1 speaking=%2 voice_mode=%3")+ .arg(is_listening_).arg(is_speaking_).arg(voice_mode_));if (is_listening_)stop_listening();else@@ -736,85 +780,81 @@ void AiChatBubble::on_toggle_mic() {}void AiChatBubble::start_listening() {+ LOG_INFO("AiChatBubble", QString("start_listening — listening=%1 speaking=%2")+ .arg(is_listening_).arg(is_speaking_));if (is_listening_ || is_speaking_)return;+ // Pause clap detector while STT owns the mic — avoids the user's own+ // speech (or the start-of-utterance plosive) being heard as a clap.+ if (services::ClapDetectorService::instance().is_active())+ services::ClapDetectorService::instance().stop();services::SpeechService::instance().start_listening();}void AiChatBubble::stop_listening() {+ LOG_INFO("AiChatBubble", "stop_listening — forwarding to SpeechService");services::SpeechService::instance().stop_listening();}void AiChatBubble::on_stt_listening_changed(bool active) {is_listening_ = active;- mic_btn_->setChecked(active);- if (active) {- pulse_timer_->start();- } else {- pulse_timer_->stop();- mic_btn_->setChecked(false);+ set_mic_listening_visual(active);+ if (active)+ error_msg_.clear();+ render_status();++ // STT released the mic — bring the clap detector back if still enabled.+ if (!active && !is_speaking_ && !streaming_ &&+ services::ClapDetectorService::is_enabled_in_config() &&+ !services::ClapDetectorService::instance().is_active()) {+ services::ClapDetectorService::instance().start();}- update_voice_status();}void AiChatBubble::on_transcription(const QString& text) {+ LOG_INFO("AiChatBubble", QString("Transcription: len=%1 voice_mode=%2")+ .arg(text.length()).arg(voice_mode_));if (text.isEmpty())return;input_box_->setPlainText(text);- // Stop mic after transcription in single-shot mic mode (not voice mode).- // In voice mode the mic restarts automatically after TTS completes.if (!voice_mode_) {stop_listening();- mic_btn_->setChecked(false);} else {on_send();}- update_voice_status();+ render_status();}void AiChatBubble::on_stt_error(const QString& message) {- if (voice_status_lbl_)- voice_status_lbl_->setText(QStringLiteral("⚠ ") + message);+ LOG_WARN("AiChatBubble", QString("STT error: %1").arg(message));+ error_msg_ = message;+ render_status();}-// ── Voice mode ────────────────────────────────────────────────────────────────+// ── Voice mode (continuous loop) ─────────────────────────────────────────────void AiChatBubble::on_toggle_voice_mode() {voice_mode_ = voice_mode_btn_->isChecked();- voice_status_bar_->setVisible(voice_mode_);+ LOG_INFO("AiChatBubble", QString("Voice mode -> %1").arg(voice_mode_));if (voice_mode_) {if (!is_open_)open_panel();-- // Warn once if TTS is unavailable — voice input still works,- // but AI responses will not be spoken aloud.-#ifndef HAS_QT_TTS- if (voice_status_lbl_)- voice_status_lbl_->setText("⚠ Voice responses unavailable — Qt TextToSpeech not installed. "- "Input-only mode active.");-#else- // Check at runtime whether any TTS engine is available- if (tts_engine_ && tts_engine_->availableEngines().isEmpty()) {- if (voice_status_lbl_)- voice_status_lbl_->setText("⚠ No TTS engine found (install speech-dispatcher on Linux). "- "Input-only mode active.");- }-#endifQTimer::singleShot(300, this, &AiChatBubble::start_listening);} else {stop_listening();stop_tts();}- update_voice_status();+ render_status();}// ── TTS ───────────────────────────────────────────────────────────────────────void AiChatBubble::speak_text(const QString& text) {+ LOG_INFO("AiChatBubble", QString("speak_text len=%1").arg(text.length()));if (text.isEmpty())return;- // Strip markdown formatting — TTS engines speak raw text.+ // Strip markdown for TTS — engines speak raw text.QString clean = text;clean.remove(QRegularExpression(R"(\*\*|__|~~|```[^`]*```|`[^`]*`)"));clean.remove(QRegularExpression(R"(#{1,6} )"));@@ -825,52 +865,14 @@ void AiChatBubble::speak_text(const QString& text) {start_listening();return;}-- is_speaking_ = true;- update_voice_status();- stop_speech_btn_->show();-- // TTS via Qt's cross-platform QTextToSpeech (Qt 6.4+).- // Instantiated lazily — avoids cost when voice mode is never used.- // QTextToSpeech uses platform engines: SAPI on Windows, AVSpeech on macOS,- // speech-dispatcher on Linux. No subprocess, no PowerShell.-#ifdef HAS_QT_TTS- if (!tts_engine_) {- tts_engine_ = new QTextToSpeech(this);- tts_engine_->setRate(0.15);- connect(tts_engine_, &QTextToSpeech::stateChanged, this, [this](QTextToSpeech::State state) {- if (state == QTextToSpeech::Ready || state == QTextToSpeech::Error) {- is_speaking_ = false;- stop_speech_btn_->hide();- update_voice_status();- if (voice_mode_ && !is_listening_ && !streaming_)- QTimer::singleShot(400, this, &AiChatBubble::start_listening);- }- });- }- tts_engine_->say(clean.left(1200));-#else- // Qt TextToSpeech module not built — skip TTS silently, resume listening.- // User was already warned when they enabled voice mode.- is_speaking_ = false;- stop_speech_btn_->hide();- if (voice_status_lbl_)- voice_status_lbl_->setText("Voice response skipped (TTS unavailable)");- update_voice_status();- if (voice_mode_ && !is_listening_ && !streaming_)- QTimer::singleShot(400, this, &AiChatBubble::start_listening);-#endif+ services::TtsService::instance().speak(clean.left(1200));}void AiChatBubble::stop_tts() {+ LOG_INFO("AiChatBubble", "stop_tts");+ services::TtsService::instance().stop();is_speaking_ = false;- stop_speech_btn_->hide();- tts_player_->stop();-#ifdef HAS_QT_TTS- if (tts_engine_)- tts_engine_->stop();-#endif- update_voice_status();+ render_status();}void AiChatBubble::on_stop_speech() {@@ -879,49 +881,67 @@ void AiChatBubble::on_stop_speech() {QTimer::singleShot(200, this, &AiChatBubble::start_listening);}-void AiChatBubble::on_tts_media_status(QMediaPlayer::MediaStatus status) {- if (status == QMediaPlayer::EndOfMedia || status == QMediaPlayer::InvalidMedia) {- is_speaking_ = false;- stop_speech_btn_->hide();- update_voice_status();- if (voice_mode_)- QTimer::singleShot(400, this, &AiChatBubble::start_listening);- }-}--// ── Voice status ──────────────────────────────────────────────────────────────-void AiChatBubble::update_voice_status() {- if (!voice_status_lbl_)+// ── Status strip rendering (single source of truth) ──────────────────────────+void AiChatBubble::render_status() {+ if (!status_strip_)return;- // Show status for both mic-only mode and full voice mode.- if (is_speaking_) {- voice_status_lbl_->setText("▶ AI speaking…");- voice_status_lbl_->setStyleSheet(- QString("color:%1;font-size:11px;font-style:italic;background:transparent;").arg(col::WARNING()));- } else if (is_listening_) {- voice_status_lbl_->setText("● Listening — speak now…");- voice_status_lbl_->setStyleSheet(- QString("color:%1;font-size:11px;font-style:italic;background:transparent;").arg(col::POSITIVE()));- } else if (streaming_) {- voice_status_lbl_->setText("AI is thinking…");- voice_status_lbl_->setStyleSheet(- QString("color:%1;font-size:11px;font-style:italic;background:transparent;").arg(col::TEXT_DIM()));- } else {- voice_status_lbl_->clear();+ Status s = Status::Idle;+ if (!error_msg_.isEmpty()) s = Status::Error;+ else if (is_speaking_) s = Status::Speaking;+ else if (is_listening_) s = Status::Listening;+ else if (streaming_) s = Status::Thinking;++ QString color, text;+ bool show_stop = false;+ switch (s) {+ case Status::Idle:+ status_strip_->setVisible(false);+ return;+ case Status::Listening:+ color = col::POSITIVE();+ text = "Listening — speak now";+ break;+ case Status::Thinking:+ color = col::TEXT_DIM();+ text = "AI is thinking…";+ break;+ case Status::Speaking:+ color = col::WARNING();+ text = "AI speaking…";+ show_stop = true;+ break;+ case Status::Error:+ color = col::NEGATIVE();+ text = error_msg_;+ break;}++ status_strip_->setVisible(true);+ status_dot_->setStyleSheet(QString("color:%1;font-size:11px;background:transparent;").arg(color));+ status_lbl_->setText(text);+ status_lbl_->setStyleSheet(QString("color:%1;font-size:11px;background:transparent;").arg(color));+ status_lbl_->setToolTip(text);+ stop_speech_btn_->setVisible(show_stop);}-// ── Pulse animation ───────────────────────────────────────────────────────────-void AiChatBubble::animate_pulse() {- pulse_step_ = (pulse_step_ + 1) % 2;- mic_btn_->setChecked(pulse_step_ != 0);+void AiChatBubble::set_mic_listening_visual(bool on) {+ if (!mic_btn_)+ return;+ mic_btn_->setProperty("listening", on);+ // Re-polish so [listening="true"] selector takes effect.+ mic_btn_->style()->unpolish(mic_btn_);+ mic_btn_->style()->polish(mic_btn_);+ mic_btn_->update();}-// ── Event filter ──────────────────────────────────────────────────────────────+// ── Event filter (bubble click, Enter/Shift+Enter, Esc, Ctrl+L) ──────────────bool AiChatBubble::eventFilter(QObject* obj, QEvent* e) {if (obj == bubble_btn_ && e->type() == QEvent::MouseButtonRelease) {- on_toggle_open();+ if (is_open_)+ close_panel();+ else+ open_panel();return true;}if (obj == input_box_ && e->type() == QEvent::KeyPress) {@@ -930,6 +950,14 @@ bool AiChatBubble::eventFilter(QObject* obj, QEvent* e) {on_send();return true;}+ if (ke->key() == Qt::Key_Escape) {+ close_panel();+ return true;+ }+ if (ke->key() == Qt::Key_L && (ke->modifiers() & Qt::ControlModifier)) {+ on_clear_chat();+ return true;+ }}if (obj == parentWidget() && e->type() == QEvent::Resize) {reposition();diff --git a/fincept-qt/src/ai_chat/AiChatBubble.h b/fincept-qt/src/ai_chat/AiChatBubble.hindex 021ef60e0..35b670dcb 100644--- a/fincept-qt/src/ai_chat/AiChatBubble.h+++ b/fincept-qt/src/ai_chat/AiChatBubble.h@@ -1,12 +1,25 @@#pragma once+// AiChatBubble — Floating "Quick Chat" assistant bubble.+//+// EXPLICITLY independent of the AI Chat tab:+// • Does NOT use ChatRepository — no sessions, no DB writes.+// • In-memory history only, lost on app exit (and on Clear).+// • Bubble conversations never appear in the AI Chat tab's session list.+//+// Voice flow:+// mic_btn or voice_mode_btn+// → SpeechService::start_listening()+// → SpeechService::transcription_ready(text) [signal, UI thread]+// → on_transcription(text)+// → input_box_ populated → on_send()+// AI reply (in voice mode)+// → TtsService::speak(text)+// → TtsService::speaking_finished() → resume listening+#include "ai_chat/LlmService.h"#include <QKeyEvent>#include <QLabel>-#include <QMediaPlayer>-#ifdef HAS_QT_TTS-# include <QTextToSpeech>-#endif#include <QPlainTextEdit>#include <QPointer>#include <QPushButton>@@ -20,33 +33,20 @@namespace fincept {-// ── AiChatBubble ─────────────────────────────────────────────────────────────-// Floating AI assistant bubble — fixed bottom-right corner of the main window.-// Features: streaming chat, voice input (Python speech_recognition + Google STT),-// TTS output via QMediaPlayer, session persistence via ChatRepository.-//-// Voice flow:-// mic_btn / voice_mode_btn-// → SpeechService::start_listening()-// → SpeechService::transcription_ready(text) [signal on UI thread]-// → on_transcription(text)-// → input_box_ populated → on_send()-class AiChatBubble : public QWidget {Q_OBJECTpublic:explicit AiChatBubble(QWidget* parent = nullptr);- // Call from parent's resizeEvent to reposition.+ /// Call from the parent's resizeEvent to reposition the bubble + panel.void reposition();protected:bool eventFilter(QObject* obj, QEvent* e) override;private slots:- void on_toggle_open();void on_send();- void on_new_session();+ void on_clear_chat();void on_stream_chunk(const QString& chunk, bool done);void on_streaming_done(ai_chat::LlmResponse response);void on_toggle_voice_mode();@@ -55,71 +55,75 @@ class AiChatBubble : public QWidget {void on_transcription(const QString& text);void on_stt_listening_changed(bool active);void on_stt_error(const QString& message);- void on_tts_media_status(QMediaPlayer::MediaStatus status);private:+ enum class Status { Idle, Listening, Thinking, Speaking, Error };+// ── UI panels ────────────────────────────────────────────────────────────- QWidget* bubble_btn_ = nullptr;- QWidget* chat_panel_ = nullptr;- QLabel* unread_badge_ = nullptr;+ QWidget* bubble_btn_ = nullptr;+ QWidget* chat_panel_ = nullptr;+ QLabel* unread_badge_ = nullptr;// Panel internals- QScrollArea* scroll_area_ = nullptr;- QWidget* msg_container_ = nullptr;- QVBoxLayout* msg_layout_ = nullptr;- QPlainTextEdit* input_box_ = nullptr;- QPushButton* send_btn_ = nullptr;- QPushButton* mic_btn_ = nullptr;- QPushButton* voice_mode_btn_ = nullptr;- QPushButton* stop_speech_btn_ = nullptr;- QPushButton* new_btn_ = nullptr;- QPushButton* close_btn_ = nullptr;- QWidget* voice_status_bar_ = nullptr;- QLabel* voice_status_lbl_ = nullptr;+ QScrollArea* scroll_area_ = nullptr;+ QWidget* msg_container_ = nullptr;+ QVBoxLayout* msg_layout_ = nullptr;+ QWidget* welcome_widget_ = nullptr; // shown when chat is empty+ QPlainTextEdit* input_box_ = nullptr;+ QPushButton* send_btn_ = nullptr;+ QPushButton* mic_btn_ = nullptr;+ QPushButton* voice_mode_btn_ = nullptr;+ QPushButton* new_btn_ = nullptr;+ QPushButton* close_btn_ = nullptr;++ // Unified status strip — replaces the old typing_row + voice_status_bar.+ QWidget* status_strip_ = nullptr;+ QLabel* status_dot_ = nullptr;+ QLabel* status_lbl_ = nullptr;+ QPushButton* stop_speech_btn_ = nullptr;// ── State ────────────────────────────────────────────────────────────────- bool is_open_ = false;- bool voice_mode_ = false;+ bool is_open_ = false;+ bool voice_mode_ = false;bool is_listening_ = false;- bool is_speaking_ = false;- bool streaming_ = false;- int unread_count_ = 0;+ bool is_speaking_ = false;+ bool streaming_ = false;+ QString error_msg_;+ int unread_count_ = 0;- QString active_session_id_;- std::vector<ai_chat::ConversationMessage> history_;- QPointer<QTextEdit> streaming_bubble_;+ /// In-memory only — never written to ChatRepository. The whole point of+ /// the bubble is to stay separate from the AI Chat tab.+ std::vector<ai_chat::ConversationMessage> chat_history_;- // ── TTS ──────────────────────────────────────────────────────────────────- QMediaPlayer* tts_player_ = nullptr;- QTimer* pulse_timer_ = nullptr;- int pulse_step_ = 0;-#ifdef HAS_QT_TTS- QTextToSpeech* tts_engine_ = nullptr;-#endif+ QPointer<QTextEdit> streaming_bubble_;- // ── Build ────────────────────────────────────────────────────────────────+ // ── Build helpers ────────────────────────────────────────────────────────void build_bubble_button();void build_chat_panel();QWidget* build_panel_header();QWidget* build_input_row();- QWidget* build_voice_status_bar();+ QWidget* build_status_strip();+ void build_welcome_widget();- // ── Helpers ──────────────────────────────────────────────────────────────+ // ── Behaviour helpers ────────────────────────────────────────────────────void refresh_theme();void open_panel();void close_panel();- void ensure_session();+ void show_welcome_if_empty();+ void hide_welcome();void add_bubble(const QString& role, const QString& text);QTextEdit* add_streaming_bubble();void scroll_to_bottom();- void set_ui_enabled(bool enabled);+ void set_input_enabled(bool enabled);void update_unread(int delta);void start_listening();void stop_listening();void speak_text(const QString& text);void stop_tts();- void update_voice_status();- void animate_pulse();++ // ── Status / mic visuals ─────────────────────────────────────────────────+ void render_status(); // derive Status from flags + paint+ void set_mic_listening_visual(bool on);};} // namespace finceptdiff --git a/fincept-qt/src/ai_chat/AiChatScreen.cpp b/fincept-qt/src/ai_chat/AiChatScreen.cppindex 1ac9bc738..0407ce89c 100644--- a/fincept-qt/src/ai_chat/AiChatScreen.cpp+++ b/fincept-qt/src/ai_chat/AiChatScreen.cpp@@ -3,6 +3,7 @@#include "ai_chat/AiChatScreen.h"#include "ai_chat/LlmService.h"+#include "core/events/EventBus.h"#include "core/logging/Logger.h"#include "core/session/ScreenStateManager.h"#include "mcp/McpService.h"@@ -201,10 +202,51 @@ void AiChatScreen::showEvent(QShowEvent* e) {connect(&ai_chat::LlmService::instance(), &ai_chat::LlmService::config_changed, this,&AiChatScreen::on_provider_changed, Qt::UniqueConnection);update_stats();+ subscribe_mcp_events();}void AiChatScreen::hideEvent(QHideEvent* e) {QWidget::hideEvent(e);+ unsubscribe_mcp_events();+}++// ── MCP-driven UI sync ──────────────────────────────────────────────────────+// MCP set_active_llm publishes llm.provider_changed when the LLM or Finagent+// switches the active provider. We force a LlmService::reload_config() so+// the next outgoing message uses the new provider. reload_config emits+// LlmService::config_changed which is already wired (above) to+// on_provider_changed for the header label refresh.++void AiChatScreen::subscribe_mcp_events() {+ if (!mcp_event_subs_.isEmpty()) return; // idempotent++ QPointer<AiChatScreen> self = this;+ auto on_provider_event = [self](const QVariantMap&) {+ if (!self) return;+ QMetaObject::invokeMethod(self.data(), [self]() {+ if (!self) return;+ ai_chat::LlmService::instance().reload_config();+ }, Qt::QueuedConnection);+ };++ auto on_session_created = [self](const QVariantMap&) {+ if (!self) return;+ QMetaObject::invokeMethod(self.data(), [self]() {+ if (!self) return;+ self->load_sessions();+ }, Qt::QueuedConnection);+ };++ auto& bus = EventBus::instance();+ mcp_event_subs_.append(bus.subscribe("llm.provider_changed", on_provider_event));+ mcp_event_subs_.append(bus.subscribe("ai_chat.session_created", on_session_created));+}++void AiChatScreen::unsubscribe_mcp_events() {+ auto& bus = EventBus::instance();+ for (auto id : mcp_event_subs_)+ bus.unsubscribe(id);+ mcp_event_subs_.clear();}void AiChatScreen::resizeEvent(QResizeEvent* e) {diff --git a/fincept-qt/src/ai_chat/AiChatScreen.h b/fincept-qt/src/ai_chat/AiChatScreen.hindex 267945f6b..7ef4b159d 100644--- a/fincept-qt/src/ai_chat/AiChatScreen.h+++ b/fincept-qt/src/ai_chat/AiChatScreen.h@@ -1,10 +1,12 @@#pragma once#include "ai_chat/LlmService.h"+#include "core/events/EventBus.h"#include "screens/IStatefulScreen.h"#include <QLabel>#include <QLineEdit>+#include <QList>#include <QListWidget>#include <QMutex>#include <QPlainTextEdit>@@ -127,6 +129,15 @@ class AiChatScreen : public QWidget, public IStatefulScreen {void update_stats();void show_welcome(bool show);void show_typing(bool show);++ // EventBus subscriptions — registered in showEvent, released in hideEvent.+ // MCP set_active_llm publishes llm.provider_changed when the LLM (or+ // Finagent) switches the active provider. We force-reload LlmService so+ // the next message uses the new provider; LlmService::config_changed+ // signal then triggers on_provider_changed for header refresh.+ QList<EventBus::HandlerId> mcp_event_subs_;+ void subscribe_mcp_events();+ void unsubscribe_mcp_events();};} // namespace fincept::screensdiff --git a/fincept-qt/src/ai_chat/LlmService.cpp b/fincept-qt/src/ai_chat/LlmService.cppindex be87fd7dd..4c0ca5c09 100644--- a/fincept-qt/src/ai_chat/LlmService.cpp+++ b/fincept-qt/src/ai_chat/LlmService.cpp@@ -10,6 +10,7 @@#include "core/logging/Logger.h"#include "mcp/McpService.h"+#include "mcp/ToolFilterPolicy.h"#include "storage/repositories/LlmConfigRepository.h"#include "storage/repositories/SettingsRepository.h"@@ -257,6 +258,22 @@ void LlmService::ensure_config() const {"Be concise, accurate, and finance-focused.";}+ // Tier-3 discovery hint. The tool catalogue you receive on each turn is+ // intentionally scoped to the active screen / agent for token-cost and+ // accuracy reasons. If the user asks for something whose tool isn't in+ // your immediate catalogue, DO NOT decline — call tool.list to find it,+ // then tool.describe to learn its schema, then invoke it. Always-on+ // meta tools that enable this discovery: tool.list, tool.describe,+ // mcp.health. Idempotent append (won't double-stack on reload).+ static constexpr const char* kToolDiscoveryHint =+ "\n\n[Tool discovery] The tools shown to you each turn are scoped "+ "to the active context. If a needed tool is missing, call "+ "tool.list(category=\"…\", search=\"…\") to discover it, then "+ "tool.describe(name) to read its schema, then invoke it. Never "+ "decline an action you can fulfil via a discoverable tool.";+ if (tools_enabled_ && !system_prompt_.contains("[Tool discovery]"))+ system_prompt_ += kToolDiscoveryHint;+config_loaded_ = true;const int resolved = resolved_max_tokens();const int catalog_cap = ModelCatalog::output_cap(provider_, model_);@@ -312,6 +329,27 @@ bool LlmService::tools_enabled() const {return tools_enabled_;}+void LlmService::set_tool_filter(const mcp::ToolFilter& filter) {+ QMutexLocker lock(&mutex_);+ tool_filter_ = filter;+ LOG_INFO(TAG, QString("Tool filter set: categories=[%1] excludes=[%2] name_patterns=%3 max_tools=%4")+ .arg(filter.categories.join(','))+ .arg(filter.exclude_categories.join(','))+ .arg(filter.name_patterns.size())+ .arg(filter.max_tools));+}++mcp::ToolFilter LlmService::tool_filter() const {+ QMutexLocker lock(&mutex_);+ return tool_filter_;+}++void LlmService::clear_tool_filter() {+ QMutexLocker lock(&mutex_);+ tool_filter_ = {};+ LOG_INFO(TAG, "Tool filter cleared (full catalogue restored)");+}+bool LlmService::is_configured() const {QMutexLocker lock(&mutex_);ensure_config();@@ -495,7 +533,7 @@ QJsonObject LlmService::build_openai_request(const QString& user_message,// which silently breaks live tool calling for OpenAI/Kimi/Groq/etc.// deepseek-reasoner rejects tools entirely; some Groq models also.if (with_tools && tools_enabled_ && !is_ds_reasoner && !groq_no_tools) {- QJsonArray tools = mcp::McpService::instance().format_tools_for_openai();+ QJsonArray tools = mcp::McpService::instance().format_tools_for_openai(tool_filter_);if (!tools.isEmpty())req["tools"] = tools;LOG_INFO(TAG, QString("OpenAI request: stream=%1 provider=%2 tools=%3 (count=%4)")@@ -540,7 +578,7 @@ QJsonObject LlmService::build_anthropic_request(const QString& user_message,// falls back to do_request to execute and follow up.if (tools_enabled_) {QJsonArray ant_tools;- auto all_tools = mcp::McpService::instance().get_all_tools();+ auto all_tools = mcp::McpService::instance().get_all_tools(tool_filter_);for (const auto& tool : all_tools) {QString fn_name = tool.server_id + "__" + tool.name;QJsonObject schema = tool.input_schema;@@ -580,7 +618,8 @@ QJsonObject LlmService::build_gemini_request(const QString& user_message,}// Gemini tool format: tools[{functionDeclarations:[{name, description, parameters}]}]- auto all_tools = tools_enabled_ ? mcp::McpService::instance().get_all_tools() : std::vector<mcp::UnifiedTool>{};+ auto all_tools =+ tools_enabled_ ? mcp::McpService::instance().get_all_tools(tool_filter_) : std::vector<mcp::UnifiedTool>{};if (!all_tools.empty()) {QJsonArray fn_decls;for (const auto& tool : all_tools) {@@ -715,8 +754,8 @@ LlmService::HttpResult LlmService::eventloop_request(const QString& method, cons// This allows models that don't support structured tool_calls to still// emit text-based tool invocations that try_extract_and_execute_text_tool_calls// can detect and execute.-static QString build_tool_catalog_for_prompt() {- auto all_tools = mcp::McpService::instance().get_all_tools();+static QString build_tool_catalog_for_prompt(const mcp::ToolFilter& filter) {+ auto all_tools = mcp::McpService::instance().get_all_tools(filter);if (all_tools.empty())return {};@@ -763,7 +802,7 @@ LlmResponse LlmService::fincept_async_request(const QString& user_message,// Inject tool catalog so the model can emit text-based tool callsif (tools_enabled_) {- QString tool_catalog = build_tool_catalog_for_prompt();+ QString tool_catalog = build_tool_catalog_for_prompt(tool_filter_);if (!tool_catalog.isEmpty())prompt += tool_catalog + "\n";}@@ -1222,7 +1261,7 @@ LlmResponse LlmService::do_tool_loop(QJsonArray loop_messages, const QString& ur// Temperature intentionally omitted — provider default.fu["max_tokens"] = resolved_max_tokens();- QJsonArray tools = mcp::McpService::instance().format_tools_for_openai();+ QJsonArray tools = mcp::McpService::instance().format_tools_for_openai(tool_filter_);if (!tools.isEmpty())fu["tools"] = tools;@@ -2166,10 +2205,46 @@ LlmResponse LlmService::chat(const QString& user_message, const std::vector<Convif (!use_tools)tools_enabled_ = false;+ // Lightweight intent classifier: scan the user message for keywords+ // that suggest categories beyond what the screen filter exposes. Add+ // them to a per-call temporary filter and restore the prior one after.+ // Cheap: pure string scan, runs on the calling background thread.+ mcp::ToolFilter saved_filter;+ bool filter_overridden = false;+ if (use_tools && tools_enabled_) {+ const auto extras = mcp::ToolFilterPolicy::infer_extra_categories(user_message);+ if (!extras.isEmpty()) {+ saved_filter = tool_filter_;+ mcp::ToolFilter expanded = saved_filter;+ // If the screen wanted "full catalogue" (empty filter), seed it+ // with Tier-1 first so we don't widen from nothing to a single+ // category — that would silently shrink the catalogue.+ if (expanded.categories.isEmpty()) {+ // No filter active → leave it alone; full catalogue already+ // covers the inferred extras.+ } else {+ bool changed = false;+ for (const auto& c : extras) {+ if (!expanded.categories.contains(c)) {+ expanded.categories.append(c);+ changed = true;+ }+ }+ if (changed) {+ tool_filter_ = expanded;+ filter_overridden = true;+ LOG_INFO(TAG, QString("Intent classifier added categories: [%1]").arg(extras.join(',')));+ }+ }+ }+ }+auto resp = do_request(user_message, history);- // Restore tools_enabled_ to saved value+ // Restore tools_enabled_ + filtertools_enabled_ = saved_tools;+ if (filter_overridden)+ tool_filter_ = saved_filter;return resp;}diff --git a/fincept-qt/src/ai_chat/LlmService.h b/fincept-qt/src/ai_chat/LlmService.hindex b6c76c7b0..7a1b01348 100644--- a/fincept-qt/src/ai_chat/LlmService.h+++ b/fincept-qt/src/ai_chat/LlmService.h@@ -5,6 +5,7 @@// Streaming via QNetworkReply::readyRead + SSE parsing.#include "core/result/Result.h"+#include "mcp/McpTypes.h"#include "storage/repositories/LlmProfileRepository.h"#include <QJsonArray>@@ -74,6 +75,16 @@ class LlmService : public QObject {// Reload config from DB (call after user changes LLM settings)void reload_config();+ // Per-request tool catalogue scoping. The full ~237-tool catalogue is+ // expensive (≈100–150 KB JSON per turn) and harms tool-pick accuracy.+ // Callers (AI chat, agents, terminal bridge) set a ToolFilter that+ // narrows the catalogue to the categories/names relevant to the current+ // screen or agent. Default-constructed = no filter = full catalogue+ // (legacy behaviour). Thread-safe.+ void set_tool_filter(const mcp::ToolFilter& filter);+ mcp::ToolFilter tool_filter() const;+ void clear_tool_filter();+// ── Active config accessors (AI Chat context) ─────────────────────────────QString active_provider() const;QString active_model() const;@@ -122,6 +133,10 @@ class LlmService : public QObject {mutable bool tools_enabled_ = true;mutable bool config_loaded_ = false;+ // Phase 6 wiring: scopes the tool catalogue per-request. Empty = full+ // catalogue. Read inside the build_*_request paths under mutex_.+ mcp::ToolFilter tool_filter_;+void ensure_config() const;// Request builders → QJsonObjectdiff --git a/fincept-qt/src/app/MainWindow.cpp b/fincept-qt/src/app/MainWindow.cppindex 36c7d1b65..f8b057e8a 100644--- a/fincept-qt/src/app/MainWindow.cpp+++ b/fincept-qt/src/app/MainWindow.cpp@@ -2,7 +2,9 @@#include "ai_chat/AiChatBubble.h"#include "ai_chat/AiChatScreen.h"+#include "ai_chat/LlmService.h"#include "app/DockScreenRouter.h"+#include "mcp/ToolFilterPolicy.h"#include "auth/AuthManager.h"#include "auth/InactivityGuard.h"#include "auth/PinManager.h"@@ -295,6 +297,19 @@ MainWindow::MainWindow(int window_id, QWidget* parent) : QMainWindow(parent), wi// Update the main window title bar to reflect the current screen name.connect(dock_router_, &DockScreenRouter::screen_changed, this, [this](const QString&) { update_window_title(); });+ // Scope the LLM tool catalogue per active screen. ToolFilterPolicy returns+ // std::nullopt for "kitchen-sink" surfaces (ai_chat, agent_config, …) —+ // those clear the filter and get the full catalogue. Every other screen+ // gets Tier-1 ∪ Tier-2 categories with a 50-tool cap.+ connect(dock_router_, &DockScreenRouter::screen_changed, this, [](const QString& id) {+ auto& llm = ai_chat::LlmService::instance();+ auto filter = mcp::ToolFilterPolicy::filter_for_screen(id);+ if (filter)+ llm.set_tool_filter(*filter);+ else+ llm.clear_tool_filter();+ });+connect(this, &QObject::destroyed, this, [this]() { WorkspaceManager::instance().remove_window(this); });// Chat bubble — floats over dock_manager_ content areadiff --git a/fincept-qt/src/mcp/AsyncDispatch.h b/fincept-qt/src/mcp/AsyncDispatch.hnew file mode 100644index 000000000..d0a6b7378--- /dev/null+++ b/fincept-qt/src/mcp/AsyncDispatch.h@@ -0,0 +1,101 @@+#pragma once+// AsyncDispatch.h — Helpers for bridging async-callback APIs into AsyncToolHandler.+//+// Phase 4 of the MCP refactor (see plans/mcp-refactor-phase-4-async-execution.md).+//+// Most Fincept services expose their work as `void fn(args, callback)` —+// PythonRunner::run, MarketDataService::fetch_quotes, NewsService::fetch_*,+// HttpClient calls, and so on. They all share the same shape:+//+// service->run(args, [callback](Result r) {+// // ...+// });+//+// Pre-Phase-4, every MCP tool that wrapped one of these had to spin its+// own QMutex + QWaitCondition + QMetaObject::invokeMethod ritual to bridge+// the worker-thread → service-thread → worker-thread hop synchronously+// (see ThreadHelper.h::run_async_wait — replicated 8+ times). The result+// blocked the worker thread for the entire call.+//+// This helper consolidates the pattern into a single QPromise-based+// utility so async handlers fulfil their promise directly when the+// service callback fires — no thread blocking, no event loops.+//+// Usage in an AsyncToolHandler:+//+// t.async_handler = [](const QJsonObject& args, ToolContext ctx,+// std::shared_ptr<QPromise<ToolResult>> promise) {+// auto* runner = &python::PythonRunner::instance();+// AsyncDispatch::callback_to_promise(+// runner, ctx, promise,+// [args, ctx](auto resolve) {+// python::PythonRunner::instance().run(+// args["script"].toString(), {},+// [resolve, ctx](python::PythonResult r) {+// if (ctx.cancelled()) {+// resolve(ToolResult::fail("cancelled"));+// return;+// }+// resolve(r.success ? ToolResult::ok_data(r.output) : ToolResult::fail(r.error));+// });+// });+// };+//+// The provider has already armed the timeout watchdog; if the callback+// never fires the promise is resolved with a timeout error. The handler+// only needs to bridge service-callback → resolve(ToolResult).++#include "mcp/McpTypes.h"++#include <QFuture>+#include <QMetaObject>+#include <QPromise>+#include <QThread>++#include <functional>+#include <memory>++namespace fincept::mcp {++class AsyncDispatch {+ public:+ /// Bridge an async-callback API to a QPromise<ToolResult>.+ ///+ /// `target` — the QObject whose thread the body runs on (e.g. the+ /// service singleton). If null, body runs synchronously+ /// on the calling thread.+ /// `ctx` — passed through unchanged; handlers can read+ /// ctx.is_cancelled() while waiting on the service.+ /// `promise` — fulfilled by the body when its callback fires.+ /// `body` — invoked on `target`'s thread. Receives a `resolve`+ /// callable; pass it to the service callback so the+ /// promise resolves when the service finishes.+ ///+ /// Re-entrancy: `resolve` is no-op after the first call. Useful when+ /// the timeout watchdog races with the service callback.+ template <typename BodyFn>+ static void callback_to_promise(QObject* target, ToolContext /*ctx*/,+ std::shared_ptr<QPromise<ToolResult>> promise,+ BodyFn&& body) {+ // Wrap resolve so it's idempotent — the timeout watchdog and the+ // service callback can race; whichever fires first wins.+ auto resolve = [promise](ToolResult r) {+ if (promise->future().isFinished())+ return;+ promise->addResult(std::move(r));+ promise->finish();+ };++ if (!target || QThread::currentThread() == target->thread()) {+ std::forward<BodyFn>(body)(resolve);+ return;+ }++ QMetaObject::invokeMethod(+ target,+ [body = std::forward<BodyFn>(body), resolve]() mutable { body(resolve); },+ Qt::QueuedConnection);+ }+};++} // namespace fincept::mcpdiff --git a/fincept-qt/src/mcp/McpInit.cpp b/fincept-qt/src/mcp/McpInit.cppindex ffdf01809..c535a01c3 100644--- a/fincept-qt/src/mcp/McpInit.cpp+++ b/fincept-qt/src/mcp/McpInit.cpp@@ -15,6 +15,7 @@#include "mcp/tools/ForumTools.h"#include "mcp/tools/MAAnalyticsTools.h"#include "mcp/tools/MarketsTools.h"+#include "mcp/tools/MetaTools.h"#include "mcp/tools/NavigationTools.h"#include "mcp/tools/NewsTools.h"#include "mcp/tools/NotesTools.h"@@ -27,10 +28,49 @@#include "mcp/tools/SystemTools.h"#include "mcp/tools/WatchlistTools.h"+#include <QJsonDocument>+namespace fincept::mcp {static constexpr const char* TAG = "McpInit";+// One-shot diagnostic: walk every registered ToolDef and warn on any whose+// serialized schema exceeds kSchemaSizeWarnBytes. Common culprits: huge+// enum lists (e.g. exhaustive country/currency codes), verbose multi-line+// descriptions, or deeply nested object schemas. Every byte of schema+// multiplies across every LLM turn that includes the tool.+//+// Logs at INFO if all schemas are within budget; logs WARN with offenders+// (sorted largest-first) otherwise. Runs once at startup; cheap.+static constexpr int kSchemaSizeWarnBytes = 2048;++static void audit_tool_schema_sizes() {+ const auto tools = McpProvider::instance().list_all_tools();+ struct Offender { QString name; int bytes; };+ QVector<Offender> over_budget;+ int total_bytes = 0;+ for (const auto& t : tools) {+ const int bytes = QJsonDocument(t.input_schema).toJson(QJsonDocument::Compact).size();+ total_bytes += bytes;+ if (bytes > kSchemaSizeWarnBytes)+ over_budget.append({t.name, bytes});+ }+ std::sort(over_budget.begin(), over_budget.end(),+ [](const Offender& a, const Offender& b) { return a.bytes > b.bytes; });++ LOG_INFO(TAG, QString("Tool schema audit: %1 tools, %2 KB total schema bytes")+ .arg(tools.size()).arg(total_bytes / 1024));+ if (over_budget.isEmpty())+ return;++ LOG_WARN(TAG, QString("Tool schema audit: %1 tools exceed %2 B budget — every "+ "byte multiplies across every LLM turn. Consider trimming "+ "enums / descriptions / nested objects.")+ .arg(over_budget.size()).arg(kSchemaSizeWarnBytes));+ for (const auto& o : over_budget)+ LOG_WARN(TAG, QString(" %1 — %2 B").arg(o.name).arg(o.bytes));+}+void initialize_all_tools() {auto& provider = McpProvider::instance();@@ -93,8 +133,16 @@ void initialize_all_tools() {// datahub introspection (Phase 9)provider.register_tools(tools::get_datahub_tools());+ // Phase 6: meta tools — tool.list, tool.describe, mcp.health.+ // Always exposed so the LLM can lazy-discover specialised tools.+ provider.register_tools(tools::get_meta_tools());+LOG_INFO(TAG, QString("Registered %1 internal MCP tools").arg(provider.tool_count()));+ // Audit schema sizes once after registration — surfaces bloated tools+ // before they bleed prompt tokens on every turn.+ audit_tool_schema_sizes();+// Initialize unified service (starts external servers in background)McpService::instance().initialize();}diff --git a/fincept-qt/src/mcp/McpProvider.cpp b/fincept-qt/src/mcp/McpProvider.cppindex ac7f381ca..4db486e74 100644--- a/fincept-qt/src/mcp/McpProvider.cpp+++ b/fincept-qt/src/mcp/McpProvider.cpp@@ -3,6 +3,16 @@#include "mcp/McpProvider.h"#include "core/logging/Logger.h"+#include "mcp/SchemaValidator.h"++#include <QCoreApplication>+#include <QFutureWatcher>+#include <QPromise>+#include <QThread>+#include <QTimer>++#include <atomic>+#include <memory>namespace fincept::mcp {@@ -71,7 +81,7 @@ std::vector<UnifiedTool> McpProvider::list_tools() const {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.input_schema.to_json(), true, t.category});}return result;}@@ -84,7 +94,7 @@ std::vector<UnifiedTool> McpProvider::list_all_tools() const {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.input_schema.to_json(), true, t.category});}return result;}@@ -109,33 +119,203 @@ bool McpProvider::has_tool(const QString& name) const {// ============================================================================ToolResult McpProvider::call_tool(const QString& name, const QJsonObject& args) {- ToolHandler handler;+ // Sync entry point. If the registered tool is async, we still want to+ // give legacy callers (LlmService, TerminalToolBridge, workflow nodes)+ // a blocking ToolResult — so we dispatch async and wait. The caller is+ // already on a background thread (every existing call site is) so+ // blocking here is safe; .result() drains the QFuture.+ auto future = call_tool_async(name, args);+ future.waitForFinished();+ if (future.resultCount() == 0)+ return ToolResult::fail("Tool '" + name + "' produced no result");+ return future.result();+}++QFuture<ToolResult> McpProvider::call_tool_async(const QString& name, const QJsonObject& args, ToolContext ctx) {+ ToolHandler sync_handler;+ AsyncToolHandler async_handler;+ ToolSchema schema;+ int default_timeout_ms = 30000;+ AuthLevel auth_required = AuthLevel::None;+ bool is_destructive = false;{QMutexLocker lock(&mutex_);- if (!tools_.contains(name))- return ToolResult::fail("Tool not found: " + name);+ auto fail_now = [](const QString& msg) {+ QPromise<ToolResult> p;+ p.start();+ p.addResult(ToolResult::fail(msg));+ p.finish();+ return p.future();+ };++ // Phase 6.10: try canonical name first, then any registered alias.+ // Aliases let us migrate names without breaking saved chats / Finagent+ // workflows that reference the old name.+ QString resolved = name;+ if (!tools_.contains(resolved)) {+ for (auto it = tools_.constBegin(); it != tools_.constEnd(); ++it) {+ if (it.value().legacy_aliases.contains(name)) {+ LOG_INFO(TAG, QString("Tool called by legacy name '%1' — canonical '%2'")+ .arg(name, it.key()));+ resolved = it.key();+ break;+ }+ }+ }++ if (!tools_.contains(resolved))+ return fail_now("Tool not found: " + name);+ if (disabled_tools_.contains(resolved))+ return fail_now("Tool is disabled: " + resolved);++ const auto& def = tools_[resolved];+ sync_handler = def.handler;+ async_handler = def.async_handler;+ schema = def.input_schema;+ default_timeout_ms = def.default_timeout_ms;+ auth_required = def.auth_required;+ is_destructive = def.is_destructive;++ if (!async_handler && !sync_handler)+ return fail_now("Tool '" + resolved + "' has no handler");+ }- if (disabled_tools_.contains(name))- return ToolResult::fail("Tool is disabled: " + name);+ // Phase 6.3: authorization gate. We don't import AuthManager here to+ // avoid pulling auth headers into McpTypes.h consumers — instead we+ // expose a hook that the app installs at startup.+ //+ // No-checker semantics:+ // • AuthLevel <= Authenticated and is_destructive flag → log + pass+ // (the flag is a hint for the Phase 6.12 modal; not a hard gate+ // until that UI lands)+ // • AuthLevel >= Verified → fail closed (genuine privilege escalation+ // that must not happen unauthenticated)+ if (auth_required != AuthLevel::None || is_destructive) {+ AuthChecker checker;+ {+ QMutexLocker lock(&mutex_);+ checker = auth_checker_;+ }+ if (checker) {+ if (!checker(auth_required, is_destructive)) {+ LOG_WARN(TAG, QString("Tool '%1' blocked: auth_required=%2 is_destructive=%3")+ .arg(name, auth_level_str(auth_required))+ .arg(is_destructive ? "true" : "false"));+ QPromise<ToolResult> p;+ p.start();+ p.addResult(ToolResult::fail(QString("Tool '%1' requires %2 auth")+ .arg(name, auth_level_str(auth_required))));+ p.finish();+ return p.future();+ }+ } else if (auth_required >= AuthLevel::Verified) {+ // Fail-closed: Verified/Subscribed/ExplicitConfirm cannot be+ // safely evaluated without a checker. Refuse the call.+ LOG_WARN(TAG, QString("Tool '%1' blocked: no AuthChecker registered (required=%2)")+ .arg(name, auth_level_str(auth_required)));+ QPromise<ToolResult> p;+ p.start();+ p.addResult(ToolResult::fail("Tool requires user confirmation but no authorisation hook is installed"));+ p.finish();+ return p.future();+ } else if (is_destructive) {+ // Advisory log only — the modal that prompts on this flag is+ // Phase 6.12 work. Tools tagged Authenticated+destructive still+ // run today; once the modal ships, install the checker and the+ // upper branch starts gating them.+ LOG_INFO(TAG, QString("Tool '%1' is destructive (flag is advisory; install McpProvider::set_auth_checker to gate)")+ .arg(name));+ }+ }- handler = tools_[name].handler;+ // Phase 3: validate + inject defaults before invoking the handler.+ QJsonObject normalized = args;+ auto vr = validate_args(schema, normalized);+ if (vr.is_err()) {+ LOG_WARN(TAG, QString("Tool '%1' rejected: %2").arg(name, QString::fromStdString(vr.error())));+ QPromise<ToolResult> p;+ p.start();+ p.addResult(ToolResult::fail(QString::fromStdString(vr.error())));+ p.finish();+ return p.future();}- // Normalize: handlers expect a JSON object, never null/array- const QJsonObject& safe_args = args;+ // Per-call timeout overrides ToolDef::default_timeout_ms when supplied+ // (Phase 4 framework; Phase 6 wires _meta.timeout_ms here).+ if (ctx.timeout_ms == 30000) // ToolContext default — not explicitly set+ ctx.timeout_ms = default_timeout_ms;++ // Async preferred; fall back to sync wrapped in an immediately-resolved+ // future so call_tool() works uniformly for legacy handlers.+ if (async_handler) {+ auto promise = std::make_shared<QPromise<ToolResult>>();+ promise->start();++ // Cancellation flag — set by the timeout timer or by a caller-supplied+ // hook. Wired into ctx.is_cancelled below.+ auto cancelled = std::make_shared<std::atomic<bool>>(false);+ if (!ctx.is_cancelled) {+ ctx.is_cancelled = [cancelled]() { return cancelled->load(); };+ } else {+ // Compose: original hook OR our internal flag.+ auto orig = ctx.is_cancelled;+ ctx.is_cancelled = [orig, cancelled]() { return cancelled->load() || orig(); };+ }+ // Arm a one-shot timeout. We post the timer onto the QApplication+ // thread so it ticks even if the caller returns immediately.+ auto* watchdog = new QTimer;+ watchdog->setSingleShot(true);+ watchdog->moveToThread(qApp->thread());+ QObject::connect(watchdog, &QTimer::timeout, watchdog, [promise, cancelled, watchdog, name]() {+ if (!promise->future().isFinished()) {+ cancelled->store(true);+ LOG_WARN(TAG, QString("Tool '%1' timed out").arg(name));+ promise->addResult(ToolResult::fail("Tool '" + name + "' timed out"));+ promise->finish();+ }+ watchdog->deleteLater();+ });+ QMetaObject::invokeMethod(watchdog, [watchdog, ms = ctx.timeout_ms]() {+ watchdog->start(ms);+ }, Qt::QueuedConnection);++ try {+ LOG_DEBUG(TAG, "Calling async tool: " + name);+ async_handler(normalized, ctx, promise);+ } catch (const std::exception& e) {+ LOG_ERROR(TAG, QString("Async tool '%1' threw: %2").arg(name, e.what()));+ if (!promise->future().isFinished()) {+ promise->addResult(ToolResult::fail(QString("Tool execution error: ") + e.what()));+ promise->finish();+ }+ } catch (...) {+ LOG_ERROR(TAG, QString("Async tool '%1' threw unknown exception").arg(name));+ if (!promise->future().isFinished()) {+ promise->addResult(ToolResult::fail("Unknown error during tool execution"));+ promise->finish();+ }+ }+ return promise->future();+ }++ // Legacy sync path — invoke immediately, wrap in a resolved future.+ QPromise<ToolResult> p;+ p.start();try {- LOG_DEBUG(TAG, "Calling tool: " + name);- return handler(safe_args);+ LOG_DEBUG(TAG, "Calling sync tool: " + name);+ p.addResult(sync_handler(normalized));} catch (const std::exception& e) {LOG_ERROR(TAG, QString("Tool '%1' threw exception: %2").arg(name, e.what()));- return ToolResult::fail(QString("Tool execution error: ") + e.what());+ p.addResult(ToolResult::fail(QString("Tool execution error: ") + e.what()));} catch (...) {LOG_ERROR(TAG, QString("Tool '%1' threw unknown exception").arg(name));- return ToolResult::fail("Unknown error during tool execution");+ p.addResult(ToolResult::fail("Unknown error during tool execution"));}+ p.finish();+ return p.future();}// ============================================================================@@ -185,6 +365,15 @@ void McpProvider::clear() {++generation_;}+// ============================================================================+// Authorization (Phase 6.3)+// ============================================================================++void McpProvider::set_auth_checker(AuthChecker checker) {+ QMutexLocker lock(&mutex_);+ auth_checker_ = std::move(checker);+}+// ============================================================================// Generation Counter// ============================================================================diff --git a/fincept-qt/src/mcp/McpProvider.h b/fincept-qt/src/mcp/McpProvider.hindex fc6f7974b..67ffd07f9 100644--- a/fincept-qt/src/mcp/McpProvider.h+++ b/fincept-qt/src/mcp/McpProvider.h@@ -5,6 +5,7 @@#include "mcp/McpTypes.h"+#include <QFuture>#include <QHash>#include <QMutex>#include <QSet>@@ -41,8 +42,38 @@ class McpProvider {// ── Tool Execution ─────────────────────────────────────────────────────+ /// Synchronous execution. For tools registered with `handler` (legacy),+ /// invokes directly and returns. For tools registered with `async_handler`,+ /// dispatches asynchronously and waits for the future to complete (with+ /// the tool's default_timeout_ms applied). Validation runs first via+ /// mcp::validate_args; failures short-circuit before the handler.ToolResult call_tool(const QString& name, const QJsonObject& args);+ /// Phase 4: asynchronous execution. Returns a QFuture that resolves with+ /// the ToolResult. For sync handlers, returns an already-resolved future+ /// (the handler runs on the calling thread). For async handlers, builds+ /// a ToolContext (cancellation hook + timeout from the per-call ctx or+ /// the tool's default), invokes the handler, and arms a timeout timer.+ ///+ /// Pass an empty ToolContext to get the tool's defaults. Pass a populated+ /// one to override timeout / inject a cancellation hook (Phase 5 will+ /// thread cancellation tokens through here).+ QFuture<ToolResult> call_tool_async(const QString& name, const QJsonObject& args,+ ToolContext ctx = {});++ // ── Phase 6.3: Authorization hook ──────────────────────────────────────+ /// Caller-supplied predicate that returns true iff the call should+ /// proceed. The hook receives the tool's required AuthLevel and+ /// is_destructive flag; it is responsible for checking the active+ /// session (AuthManager), prompting the user (modal dialog), and+ /// returning the verdict synchronously. Hook lives in the app layer to+ /// avoid pulling auth/UI headers into McpTypes.h.+ ///+ /// When unset, tools with auth_required > Authenticated or+ /// is_destructive=true fail closed; lesser tools pass through.+ using AuthChecker = std::function<bool(AuthLevel required, bool is_destructive)>;+ void set_auth_checker(AuthChecker checker);+// ── LLM Integration ────────────────────────────────────────────────────/// Format all enabled tools for OpenAI function calling@@ -71,6 +102,10 @@ class McpProvider {QHash<QString, ToolDef> tools_;QSet<QString> disabled_tools_;quint64 generation_ = 0;++ // Phase 6.3 — guarded by mutex_ so set_auth_checker / call_tool_async+ // see consistent state across threads.+ AuthChecker auth_checker_;};} // namespace fincept::mcpdiff --git a/fincept-qt/src/mcp/McpService.cpp b/fincept-qt/src/mcp/McpService.cppindex c4e23be72..4720be4b8 100644--- a/fincept-qt/src/mcp/McpService.cpp+++ b/fincept-qt/src/mcp/McpService.cpp@@ -7,8 +7,11 @@#include "mcp/McpProvider.h"#include <QJsonDocument>+#include <QPromise>+#include <QRegularExpression>#include <QThread>#include <QTimer>+#include <QtConcurrent/QtConcurrent>namespace fincept::mcp {@@ -78,15 +81,151 @@ void McpService::shutdown() {std::vector<UnifiedTool> McpService::get_all_tools() {QMutexLocker lock(&mutex_);+ return cached_tools_locked();+}++const std::vector<UnifiedTool>& McpService::cached_tools_locked() {if (!is_cache_valid())refresh_cache();return cached_tools_;}+QByteArray McpService::filter_signature(const ToolFilter& f) {+ // Deterministic, compact, mutation-free. The component prefixes ('c=',+ // 'x=', etc.) prevent collisions when one field is empty and another+ // contains a literal pipe. max_tools=0 means "no cap" — kept in the key+ // so cap changes invalidate.+ QByteArray key;+ key.reserve(256);+ key += "c=" + f.categories.join('|').toUtf8() + ';';+ key += "xc=" + f.exclude_categories.join('|').toUtf8() + ';';+ key += "n=" + f.name_patterns.join('|').toUtf8() + ';';+ key += "xn=" + f.exclude_name_patterns.join('|').toUtf8() + ';';+ key += "m=" + QByteArray::number(f.max_tools);+ return key;+}++// Production safety cap: when a caller (or screen policy) leaves max_tools+// at 0 (= unlimited), we still refuse to dump the full catalogue at the LLM.+// Tool-pick accuracy degrades sharply past ~40 tools; ~150 KB of schema+// also costs prompt tokens. Mirrors ToolFilterPolicy::kMaxToolsDefault so+// any direct McpService caller (tests, ad-hoc scripts) inherits the same+// guardrail without having to know about ToolFilterPolicy.+static constexpr int kHardMaxTools = 50;++// Apply ToolFilter (categories include/exclude, name regex include/exclude,+// max_tools cap) to a list of UnifiedTools. Pulled out as a free function so+// both the OpenAI-format path and the Anthropic / Gemini / Fincept catalog+// builders can share identical filter semantics.+//+// Telemetry: counts how many candidates were truncated by the max_tools+// cap and emits a warning so we can spot screens whose Tier-2 categories+// are too wide. Truncation isn't an error — but it is a signal.+static std::vector<UnifiedTool> apply_tool_filter(std::vector<UnifiedTool> tools, const ToolFilter& filter) {+ QList<QRegularExpression> include_rx;+ for (const auto& p : filter.name_patterns) include_rx.append(QRegularExpression(p));+ QList<QRegularExpression> exclude_rx;+ for (const auto& p : filter.exclude_name_patterns) exclude_rx.append(QRegularExpression(p));++ const int effective_cap = filter.max_tools > 0 ? filter.max_tools : kHardMaxTools;++ // Stage 1 — keep candidates that pass include/exclude predicates.+ // Cap is applied after sort, not during iteration, so a stable order+ // is preserved regardless of registration order.+ std::vector<UnifiedTool> kept;+ kept.reserve(tools.size());+ for (auto& tool : tools) {+ if (!filter.categories.isEmpty()) {+ if (tool.category.isEmpty() || !filter.categories.contains(tool.category))+ continue;+ }+ if (!filter.exclude_categories.isEmpty() && filter.exclude_categories.contains(tool.category))+ continue;++ if (!include_rx.isEmpty()) {+ bool any_match = false;+ for (const auto& rx : include_rx) {+ if (rx.match(tool.name).hasMatch()) { any_match = true; break; }+ }+ if (!any_match) continue;+ }+ bool excluded = false;+ for (const auto& rx : exclude_rx) {+ if (rx.match(tool.name).hasMatch()) { excluded = true; break; }+ }+ if (excluded) continue;++ kept.push_back(std::move(tool));+ }++ // Stage 2 — deterministic sort. Anthropic's prompt cache only hits on+ // a byte-identical prefix, so the tool block order MUST be stable.+ // Primary key: index in filter.categories (Tier-1 categories listed+ // first by ToolFilterPolicy → they cluster at the top). Tools whose+ // category isn't in the include list (external tools with empty+ // category) sort to the end with a sentinel rank.+ // Secondary key: tool name alphabetical.+ QHash<QString, int> cat_rank;+ for (int i = 0; i < filter.categories.size(); ++i)+ cat_rank.insert(filter.categories[i], i);+ const int sentinel = filter.categories.size();++ std::stable_sort(kept.begin(), kept.end(),+ [&cat_rank, sentinel](const UnifiedTool& a, const UnifiedTool& b) {+ const int ra = cat_rank.value(a.category, sentinel);+ const int rb = cat_rank.value(b.category, sentinel);+ if (ra != rb) return ra < rb;+ return a.name < b.name;+ });++ // Stage 3 — apply cap.+ const int kept_before_cap = static_cast<int>(kept.size());+ if (static_cast<int>(kept.size()) > effective_cap)+ kept.resize(effective_cap);++ if (kept_before_cap > effective_cap) {+ LOG_WARN(TAG, QString("apply_tool_filter: truncated %1 → %2 (cap=%3, configured_cap=%4) — "+ "consider tightening categories for this screen/agent")+ .arg(kept_before_cap).arg(kept.size())+ .arg(effective_cap).arg(filter.max_tools));+ }+ return kept;+}++std::vector<UnifiedTool> McpService::get_all_tools(const ToolFilter& filter) {+ QMutexLocker lock(&mutex_);+ // Refresh cached_tools_ if stale — also clears filter caches.+ cached_tools_locked();++ const QByteArray key = filter_signature(filter);+ auto it = filtered_tools_cache_.constFind(key);+ if (it != filtered_tools_cache_.constEnd())+ return it.value();++ auto filtered = apply_tool_filter(cached_tools_, filter);+ filtered_tools_cache_.insert(key, filtered);+ return filtered;+}+QJsonArray McpService::format_tools_for_openai() {- auto tools = get_all_tools();- QJsonArray result;+ return format_tools_for_openai(ToolFilter{});+}+QJsonArray McpService::format_tools_for_openai(const ToolFilter& filter) {+ QMutexLocker lock(&mutex_);+ cached_tools_locked();++ const QByteArray key = filter_signature(filter);+ auto cached = openai_format_cache_.constFind(key);+ if (cached != openai_format_cache_.constEnd()) {+ LOG_INFO(TAG, QString("format_tools_for_openai: %1 tools sent to LLM (cached)").arg(cached.value().size()));+ return cached.value();+ }++ const int total_seen = static_cast<int>(cached_tools_.size());+ auto tools = apply_tool_filter(cached_tools_, filter);++ QJsonArray result;for (const auto& tool : tools) {QString fn_name = tool.server_id + "__" + tool.name;@@ -107,7 +246,14 @@ QJsonArray McpService::format_tools_for_openai() {result.append(entry);}- LOG_INFO(TAG, QString("format_tools_for_openai: %1 tools sent to LLM").arg(result.size()));+ openai_format_cache_.insert(key, result);++ if (total_seen != result.size()) {+ LOG_INFO(TAG, QString("format_tools_for_openai: %1/%2 tools sent to LLM (filtered, fresh)")+ .arg(result.size()).arg(total_seen));+ } else {+ LOG_INFO(TAG, QString("format_tools_for_openai: %1 tools sent to LLM (fresh)").arg(result.size()));+ }return result;}@@ -170,63 +316,49 @@ ToolResult McpService::execute_openai_function(const QString& function_name, conreturn result;}-// ============================================================================-// Validation-// ============================================================================--Result<void> McpService::validate_params(const QString& tool_name, const QJsonObject& args) {- auto tools = get_all_tools();- for (const auto& tool : tools) {- if (tool.name != tool_name)- continue;+QFuture<ToolResult> McpService::execute_openai_function_async(const QString& function_name, const QJsonObject& args) {+ auto [server_id, tool_name] = McpProvider::parse_openai_function_name(function_name);- const QJsonObject& schema = tool.input_schema;+ auto fail_now = [](const QString& msg) {+ QPromise<ToolResult> p;+ p.start();+ p.addResult(ToolResult::fail(msg));+ p.finish();+ return p.future();+ };- // Required field validation- if (schema.contains("required")) {- for (const auto& req : schema["required"].toArray()) {- QString field = req.toString();- if (!args.contains(field))- return Result<void>::err("Missing required parameter: " + field.toStdString());- }- }+ if (server_id.isEmpty() || tool_name.isEmpty()) {+ LOG_WARN(TAG, "Invalid function name format: " + function_name);+ return fail_now("Invalid function name format: " + function_name);+ }- // Type validation- if (schema.contains("properties")) {- QJsonObject props = schema["properties"].toObject();- for (auto it = props.constBegin(); it != props.constEnd(); ++it) {- const QString& key = it.key();- if (!args.contains(key))- continue;-- QString expected = it.value().toObject()["type"].toString();- QJsonValue val = args[key];-- bool valid = true;- if (expected == "string")- valid = val.isString();- else if (expected == "number")- valid = val.isDouble();- else if (expected == "integer")- valid = val.isDouble();- else if (expected == "boolean")- valid = val.isBool();- else if (expected == "array")- valid = val.isArray();- else if (expected == "object")- valid = val.isObject();-- if (!valid)- return Result<void>::err(("Parameter '" + key + "' should be " + expected).toStdString());- }- }+ LOG_INFO(TAG, QString("Async dispatch: %1 -> server=%2 tool=%3").arg(function_name, server_id, tool_name));- return Result<void>::ok();+ // Internal tools — use the native async path. Validation, timeout, and+ // cancellation are handled by McpProvider::call_tool_async.+ if (server_id == INTERNAL_SERVER_ID) {+ return McpProvider::instance().call_tool_async(tool_name, args);}- return Result<void>::err("Tool not found: " + tool_name.toStdString());+ // External tools — McpManager's JSON-RPC client is blocking by design+ // (it sleeps on a QWaitCondition for the response). Wrap in+ // QtConcurrent::run so multiple external calls can fan out concurrently+ // even if each one blocks its own pool thread. Phase 5's dispatcher+ // unification will use these futures with QtFuture::whenAll to join+ // a round of tool calls in parallel.+ return QtConcurrent::run([server_id, tool_name, args]() -> ToolResult {+ return McpService::instance().execute_tool(server_id, tool_name, args);+ });}+// ============================================================================+// Validation+// ============================================================================+// Phase 3: validation now lives in mcp::validate_args (SchemaValidator.cpp)+// and is invoked automatically by McpProvider::call_tool. The previous+// McpService::validate_params helper was orphaned (never called from any+// execution path) and has been removed. See plans/mcp-refactor-phase-3-schema-validation.md.+// ============================================================================// Cache// ============================================================================@@ -252,6 +384,13 @@ void McpService::refresh_cache() {cached_tools_.push_back({ext.server_id, ext.server_name, ext.name, ext.description, ext.input_schema, false});}+ // Invalidate filter-derived caches — they were computed against the+ // previous cached_tools_ snapshot. Memory cost: typically a handful of+ // distinct ToolFilter signatures (one per active screen / agent), each+ // <200 KB, so simple full-clear is fine.+ filtered_tools_cache_.clear();+ openai_format_cache_.clear();+cache_time_ = QDateTime::currentDateTime();cached_generation_ = McpProvider::instance().generation();diff --git a/fincept-qt/src/mcp/McpService.h b/fincept-qt/src/mcp/McpService.hindex 11c652a02..42b26acd5 100644--- a/fincept-qt/src/mcp/McpService.h+++ b/fincept-qt/src/mcp/McpService.h@@ -6,6 +6,7 @@#include "mcp/McpTypes.h"#include <QDateTime>+#include <QFuture>#include <QMutex>#include <vector>@@ -21,9 +22,19 @@ class McpService {/// Get all available tools (internal + external, cached 5 s)std::vector<UnifiedTool> get_all_tools();- /// Format for OpenAI function calling+ /// Filtered variant — same `ToolFilter` semantics as+ /// `format_tools_for_openai(filter)`. Lets non-OpenAI builders+ /// (Anthropic, Gemini, Fincept text catalog) honour the same scope.+ std::vector<UnifiedTool> get_all_tools(const ToolFilter& filter);++ /// Format for OpenAI function calling — full catalogue.QJsonArray format_tools_for_openai();+ /// Phase 6: format with a filter applied. Lets callers scope the+ /// catalogue per-LLM-request to reduce prompt size and tool-pick noise.+ /// Equivalent to format_tools_for_openai() when filter is default-constructed.+ QJsonArray format_tools_for_openai(const ToolFilter& filter);+std::size_t tool_count();// ── Unified Tool Execution ──────────────────────────────────────────@@ -34,10 +45,19 @@ class McpService {/// Execute from OpenAI function-call format ("serverId__toolName")ToolResult execute_openai_function(const QString& function_name, const QJsonObject& args);- // ── Validation ──────────────────────────────────────────────────────+ /// Phase 4: async equivalent of execute_openai_function. Returns a+ /// QFuture<ToolResult> so callers (LlmService dispatch loops in+ /// Phase 5) can fan out multiple tool calls concurrently and join+ /// with QtFuture::whenAll. Internal tools resolve via+ /// McpProvider::call_tool_async; external tools dispatch through a+ /// QtConcurrent::run wrapper since McpManager's RPC client is+ /// blocking by design.+ QFuture<ToolResult> execute_openai_function_async(const QString& function_name, const QJsonObject& args);- /// Validate args against the tool's JSON schema- Result<void> validate_params(const QString& tool_name, const QJsonObject& args);+ // ── Validation ──────────────────────────────────────────────────────+ // Phase 3: removed. McpProvider::call_tool now invokes+ // mcp::validate_args automatically; SchemaValidator.h is the single+ // entry point for input checks.// ── Lifecycle ───────────────────────────────────────────────────────@@ -57,8 +77,25 @@ class McpService {quint64 cached_generation_ = 0;static constexpr int CACHE_TTL_MS = 5000;- void refresh_cache();- bool is_cache_valid() const;+ // Filter-aware caches. Both keyed by a stable signature of ToolFilter+ // (categories, exclude_categories, name_patterns, exclude_name_patterns,+ // max_tools). Cleared whenever refresh_cache() rebuilds cached_tools_,+ // so they automatically follow the same TTL + generation invalidation.+ // Avoids re-running the regex/category sweep AND re-stringifying the+ // ~150 KB OpenAI JSON schema on every LLM turn.+ QHash<QByteArray, std::vector<UnifiedTool>> filtered_tools_cache_;+ QHash<QByteArray, QJsonArray> openai_format_cache_;++ void refresh_cache(); // requires mutex_ held+ bool is_cache_valid() const; // requires mutex_ held++ // Snapshot the unfiltered cached tool list (refreshing if stale). Caller+ // must hold mutex_. Splitting this out lets get_all_tools(filter) and+ // format_tools_for_openai(filter) reuse the cache without re-locking.+ const std::vector<UnifiedTool>& cached_tools_locked();++ // Stable byte signature of a ToolFilter — usable as a QHash key.+ static QByteArray filter_signature(const ToolFilter& filter);};} // namespace fincept::mcpdiff --git a/fincept-qt/src/mcp/McpTypes.h b/fincept-qt/src/mcp/McpTypes.hindex 404253420..ea811ef07 100644--- a/fincept-qt/src/mcp/McpTypes.h+++ b/fincept-qt/src/mcp/McpTypes.h@@ -2,13 +2,17 @@// McpTypes.h — Core type definitions for the Model Context Protocol system (Qt port)// Translated from fincept-cpp mcp_types.h — std::string → QString, nlohmann::json → QJsonObject+#include <QHash>#include <QJsonArray>#include <QJsonObject>#include <QJsonValue>+#include <QPromise>#include <QString>#include <QStringList>#include <functional>+#include <memory>+#include <optional>#include <vector>namespace fincept::mcp {@@ -59,27 +63,152 @@ struct ToolResult {};// ============================================================================-// Tool Handler — function signature for tool execution+// Tool Handler — function signatures for tool execution// ============================================================================+//+// Two handler shapes are supported on the same ToolDef:+//+// 1. SYNC (`ToolHandler`) — returns ToolResult by value. Pre-Phase-4+// shape; ~237 tools still use it. Suitable for handlers that finish+// in microseconds (registry/cache lookups, EventBus publishes).+// Long-running sync handlers block the calling thread and risk+// starving the worker pool.+//+// 2. ASYNC (`AsyncToolHandler`) — Phase 4. Receives a ToolContext+// (cancellation, progress, timeout) and a QPromise<ToolResult> the+// handler resolves when work completes. Handler returns immediately;+// the promise is fulfilled later from any thread. Use this for any+// handler that calls Python, HTTP, or otherwise waits on I/O.+//+// McpProvider::call_tool dispatches to whichever shape is set on the+// ToolDef; if both are set, async wins. McpProvider::call_tool_async+// returns a QFuture<ToolResult> for either shape — sync handlers are+// wrapped in an immediately-resolved future.using ToolHandler = std::function<ToolResult(const QJsonObject& args)>;+/// Context passed to async handlers. Each handler receives a fresh ToolContext+/// per invocation; capturing it by value is safe.+struct ToolContext {+ /// Optional progress callback. Handlers call this with progress in [0,1]+ /// and a short status message. Safe to call from any thread.+ /// May be null — check before calling.+ std::function<void(double progress, const QString& message)> on_progress;++ /// Returns true if the caller has signalled cancellation. Handlers+ /// should poll periodically and stop work / resolve the promise with+ /// `ToolResult::fail("cancelled")` when set. May be null — treat as+ /// "never cancelled" in that case.+ std::function<bool()> is_cancelled;++ /// Hard timeout in milliseconds. The provider arms a timer that+ /// resolves the promise with a timeout error if the handler hasn't+ /// finished by then. Default: 30s; per-tool override via+ /// ToolDef::default_timeout_ms; per-call override via _meta.timeout_ms.+ int timeout_ms = 30000;++ /// Convenience — true if cancellation hook is set AND signalled.+ bool cancelled() const { return is_cancelled && is_cancelled(); }+};++/// Async handler signature. The handler MUST eventually:+/// - call promise->addResult(result) followed by promise->finish(); or+/// - call promise->finish() with no result (caller treats as fail).+///+/// The promise is heap-allocated and shared so the handler can capture it+/// by value into lambdas / network callbacks.+using AsyncToolHandler =+ std::function<void(const QJsonObject& args, ToolContext ctx,+ std::shared_ptr<QPromise<ToolResult>> promise)>;+// ============================================================================-// Tool Input Schema — JSON Schema for tool input parameters+// Tool Input Schema — JSON Schema 2020-12 subset// ============================================================================+//+// Phase 3 of the MCP refactor (see plans/mcp-refactor-phase-3-schema-validation.md).+//+// Two registration shapes are supported and may coexist on the same ToolDef:+//+// 1. LEGACY — set `properties` (QJsonObject) and `required` (QStringList)+// directly. This is the pre-Phase-3 shape; ~237 tools still use it.+// The validator (mcp::validate_args, McpProvider::call_tool) inspects+// `properties` recursively for type / required and accepts JSON+// Schema 2020-12 keywords inline.+//+// 2. STRUCTURED — populate `params` via ToolSchemaBuilder. Each param+// declares its type, description, defaults, enum, and bounds in a+// typed C++ struct. to_json() merges the two shapes when serialising+// for the LLM, with `params` taking precedence on key collisions.+//+// All tools migrate to the STRUCTURED shape over Phase 3 batches A–E.+// Until they do, both shapes work side by side.++struct ToolParam {+ QString type = "string"; // "string" | "integer" | "number" | "boolean" | "array" | "object"+ QString description;+ bool required = false;+ QJsonValue default_value; // null/undefined if no default+ QStringList enum_values; // string enums; empty if not enumerated+ std::optional<double> minimum;+ std::optional<double> maximum;+ std::optional<int> min_length; // for strings+ std::optional<int> max_length; // for strings+ QString pattern; // regex string for strings+ QJsonObject items; // schema for array elements (raw JSON)++ QJsonObject to_json() const {+ QJsonObject j;+ j["type"] = type;+ if (!description.isEmpty()) j["description"] = description;+ if (!default_value.isNull() && !default_value.isUndefined())+ j["default"] = default_value;+ if (!enum_values.isEmpty()) {+ QJsonArray arr;+ for (const auto& v : enum_values) arr.append(v);+ j["enum"] = arr;+ }+ if (minimum.has_value()) j["minimum"] = *minimum;+ if (maximum.has_value()) j["maximum"] = *maximum;+ if (min_length.has_value()) j["minLength"] = *min_length;+ if (max_length.has_value()) j["maxLength"] = *max_length;+ if (!pattern.isEmpty()) j["pattern"] = pattern;+ if (!items.isEmpty()) j["items"] = items;+ return j;+ }+};struct ToolSchema {QString type = "object";++ // Legacy shape — raw JSON Schema fragment per param.QJsonObject properties; // { "param": { "type": "string", "description": "..." } }- QStringList required;++ // Structured shape (Phase 3) — typed param declarations.+ QHash<QString, ToolParam> params;++ QStringList required; // legacy callers may set this directly; migrated callers+ // get it derived from params marked required=true.QJsonObject to_json() const {QJsonObject j;j["type"] = type;- j["properties"] = properties;- if (!required.isEmpty()) {++ // Merge legacy `properties` with structured `params`. On key conflict,+ // structured wins (it's the migrated source of truth).+ QJsonObject merged_props = properties;+ for (auto it = params.constBegin(); it != params.constEnd(); ++it)+ merged_props[it.key()] = it.value().to_json();+ j["properties"] = merged_props;++ // Required = explicit list ∪ params marked required=true. Dedup.+ QStringList all_required = required;+ for (auto it = params.constBegin(); it != params.constEnd(); ++it) {+ if (it.value().required && !all_required.contains(it.key()))+ all_required.append(it.key());+ }+ if (!all_required.isEmpty()) {QJsonArray req;- for (const auto& r : required)+ for (const auto& r : all_required)req.append(r);j["required"] = req;}@@ -87,6 +216,41 @@ struct ToolSchema {}};+// ============================================================================+// Authorization — Phase 6 per-tool gates+// ============================================================================+//+// Every tool declares an AuthLevel; McpProvider::call_tool checks it before+// invoking the handler. Defaults to None to keep behaviour unchanged for+// the 237 untagged tools — Phase 6.4 batch can elevate dangerous tools.+//+// AuthLevel.None — anyone, including guest users+// AuthLevel.Authenticated — must be logged in+// AuthLevel.Verified — must have verified email+// AuthLevel.Subscribed — must have an active subscription+// AuthLevel.ExplicitConfirm — requires user to OK each call (modal dialog+// wired in Phase 6.12). Pair with is_destructive+// to force the modal regardless of auth state.++enum class AuthLevel {+ None = 0,+ Authenticated = 1,+ Verified = 2,+ Subscribed = 3,+ ExplicitConfirm = 4,+};++inline const char* auth_level_str(AuthLevel a) {+ switch (a) {+ case AuthLevel::None: return "none";+ case AuthLevel::Authenticated: return "authenticated";+ case AuthLevel::Verified: return "verified";+ case AuthLevel::Subscribed: return "subscribed";+ case AuthLevel::ExplicitConfirm: return "explicit_confirm";+ }+ return "unknown";+}+// ============================================================================// Tool Definition — a registered MCP tool// ============================================================================@@ -96,8 +260,75 @@ struct ToolDef {QString description;QString category; // navigation, trading, portfolio, market-data, analytics, system, exchangeToolSchema input_schema;- ToolHandler handler;++ // Phase 4: dual-shape handler. Exactly one of these should be set per+ // tool. If both are set, async wins. If neither is set the tool is+ // unusable and McpProvider::call_tool returns "Tool has no handler".+ ToolHandler handler; // legacy synchronous+ AsyncToolHandler async_handler; // new — for I/O-bound work+bool enabled = true;++ /// Hard timeout for async handlers in milliseconds. Sync handlers ignore+ /// this — they block as long as they need. Override with smaller values+ /// for snappy tools (e.g. registry lookups, paper-trading orders) and+ /// larger for slow ones (e.g. analytics scripts that run a full backtest).+ /// Per-call overrides are merged from `_meta.timeout_ms` (Phase 6).+ int default_timeout_ms = 30000;++ // ── Phase 6: Authorization ──────────────────────────────────────────+ /// Required auth level — checked by McpProvider::call_tool before the+ /// handler runs. Defaults to None (no gate) so untagged tools behave+ /// as before; Phase 6.4 elevates dangerous tools.+ AuthLevel auth_required = AuthLevel::None;++ /// True for state-mutating tools that should always prompt the user+ /// (e.g. set_setting, set_active_llm, run_python_script, place_order,+ /// delete_*, file ops). The Phase 6.12 modal triggers regardless of+ /// auth_required when this is set.+ bool is_destructive = false;++ // ── Phase 6: Naming convention migration ────────────────────────────+ /// Old names this tool used to have. Lets us migrate names without+ /// breaking existing LLM workflows / saved chats — McpProvider's name+ /// resolver tries each alias if the canonical name doesn't match.+ /// New tools leave this empty.+ QStringList legacy_aliases;+};++// ============================================================================+// Tool Filter — Phase 6 catalogue subsetting+// ============================================================================+//+// Today's `format_tools_for_openai()` returns ALL ~237 enabled tools on+// every LLM request — ~100-150 KB of schema per turn. ToolFilter lets+// callers (LlmService dispatch path, agent tooling, future settings UI)+// scope the catalogue per-call so:+//+// • prompt cost shrinks for non-cached providers+// • the LLM has fewer distractors when picking a tool+// • dangerous categories can be excluded by default and lazy-discovered+// via the tool.list / tool.describe meta-tools (Phase 6.2).++struct ToolFilter {+ /// Inclusive — only tools whose category matches one of these are kept.+ /// Empty = no inclusion filter (all categories pass).+ QStringList categories;++ /// Exclusive — drop tools whose category matches one of these. Applied+ /// AFTER `categories` inclusion.+ QStringList exclude_categories;++ /// Regex include filter on tool name. Empty = no include filter.+ QStringList name_patterns;++ /// Regex exclude filter on tool name. Applied after include.+ QStringList exclude_name_patterns;++ /// Hard cap on returned tool count. 0 = no cap.+ /// Truncation happens after all other filters have run, in the order+ /// tools were registered (effectively: most-recently-registered last).+ int max_tools = 0;};// ============================================================================@@ -143,6 +374,7 @@ struct UnifiedTool {QString description;QJsonObject input_schema;bool is_internal = false;+ QString category; // Phase 6: enables ToolFilter category include/exclude};// ============================================================================diff --git a/fincept-qt/src/mcp/SchemaValidator.cpp b/fincept-qt/src/mcp/SchemaValidator.cppnew file mode 100644index 000000000..025253f7c--- /dev/null+++ b/fincept-qt/src/mcp/SchemaValidator.cpp@@ -0,0 +1,153 @@+// SchemaValidator.cpp — Validate + normalize tool args against a ToolSchema.++#include "mcp/SchemaValidator.h"++#include <QJsonArray>+#include <QRegularExpression>++namespace fincept::mcp {++namespace {++// ── JSON Schema 2020-12 type check ──────────────────────────────────────────+// QJsonValue::isDouble() is true for both integer and floating values+// (Qt stores all numbers as double). For "integer" we additionally require+// the value to be representable losslessly as an int64.+bool type_matches(const QString& expected, const QJsonValue& v) {+ if (expected == "string") return v.isString();+ if (expected == "boolean") return v.isBool();+ if (expected == "array") return v.isArray();+ if (expected == "object") return v.isObject();+ if (expected == "number") return v.isDouble();+ if (expected == "integer") {+ if (!v.isDouble()) return false;+ const double d = v.toDouble();+ return d == static_cast<double>(static_cast<qint64>(d));+ }+ // Unknown type → permissive (don't break tools using non-standard types).+ return true;+}++QString fail_msg(const QString& key, const QString& reason) {+ return "Invalid argument: " + key + ": " + reason;+}++// ── Validate one param against either the structured ToolParam OR the+// legacy raw QJsonObject schema fragment. Returns empty string on success,+// error reason on failure.+QString validate_typed(const QString& key, const ToolParam& p, const QJsonValue& v) {+ if (!type_matches(p.type, v))+ return "expected " + p.type;++ if (p.type == "string") {+ const QString s = v.toString();+ if (p.min_length && s.size() < *p.min_length)+ return QString("min length %1").arg(*p.min_length);+ if (p.max_length && s.size() > *p.max_length)+ return QString("max length %1").arg(*p.max_length);+ if (!p.enum_values.isEmpty() && !p.enum_values.contains(s))+ return "must be one of [" + p.enum_values.join(",") + "]";+ if (!p.pattern.isEmpty()) {+ QRegularExpression rx(p.pattern);+ if (!rx.match(s).hasMatch())+ return "does not match pattern " + p.pattern;+ }+ } else if (p.type == "number" || p.type == "integer") {+ const double d = v.toDouble();+ if (p.minimum && d < *p.minimum)+ return QString("minimum %1").arg(*p.minimum);+ if (p.maximum && d > *p.maximum)+ return QString("maximum %1").arg(*p.maximum);+ }+ return {};+}++QString validate_legacy(const QString& key, const QJsonObject& spec, const QJsonValue& v) {+ const QString expected = spec["type"].toString();+ if (!expected.isEmpty() && !type_matches(expected, v))+ return "expected " + expected;++ if (spec.contains("enum")) {+ const QJsonArray arr = spec["enum"].toArray();+ bool found = false;+ for (const auto& e : arr) {+ if (e == v) { found = true; break; }+ }+ if (!found) {+ QStringList allowed;+ for (const auto& e : arr) allowed.append(e.toString());+ return "must be one of [" + allowed.join(",") + "]";+ }+ }+ if (expected == "string" && spec.contains("pattern")) {+ QRegularExpression rx(spec["pattern"].toString());+ if (!rx.match(v.toString()).hasMatch())+ return "does not match pattern " + spec["pattern"].toString();+ }+ if ((expected == "number" || expected == "integer")) {+ const double d = v.toDouble();+ if (spec.contains("minimum") && d < spec["minimum"].toDouble())+ return QString("minimum %1").arg(spec["minimum"].toDouble());+ if (spec.contains("maximum") && d > spec["maximum"].toDouble())+ return QString("maximum %1").arg(spec["maximum"].toDouble());+ }+ return {};+}++} // anonymous namespace++Result<void> validate_args(const ToolSchema& schema, QJsonObject& args) {+ // ── Step 1: inject defaults from structured params ──────────────────+ for (auto it = schema.params.constBegin(); it != schema.params.constEnd(); ++it) {+ const QString& key = it.key();+ const ToolParam& p = it.value();+ if (!args.contains(key) && !p.default_value.isNull() && !p.default_value.isUndefined())+ args[key] = p.default_value;+ }+ // Legacy `properties` may also declare defaults inline.+ for (auto it = schema.properties.constBegin(); it != schema.properties.constEnd(); ++it) {+ const QString& key = it.key();+ if (args.contains(key)) continue;+ const QJsonObject spec = it.value().toObject();+ if (spec.contains("default") && !schema.params.contains(key))+ args[key] = spec["default"];+ }++ // ── Step 2: required check ──────────────────────────────────────────+ QStringList all_required = schema.required;+ for (auto it = schema.params.constBegin(); it != schema.params.constEnd(); ++it) {+ if (it.value().required && !all_required.contains(it.key()))+ all_required.append(it.key());+ }+ for (const QString& key : all_required) {+ if (!args.contains(key))+ return Result<void>::err(("Missing required parameter: " + key).toStdString());+ }++ // ── 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 raw+ // JSON spec.+ for (auto it = args.constBegin(); it != args.constEnd(); ++it) {+ const QString& key = it.key();++ if (schema.params.contains(key)) {+ const QString reason = validate_typed(key, schema.params[key], it.value());+ if (!reason.isEmpty())+ return Result<void>::err(fail_msg(key, reason).toStdString());+ continue;+ }+ if (schema.properties.contains(key)) {+ const QString reason = validate_legacy(key, schema.properties[key].toObject(), it.value());+ if (!reason.isEmpty())+ return Result<void>::err(fail_msg(key, reason).toStdString());+ }+ // Unknown keys are silently allowed — JSON Schema's+ // additionalProperties default is true, and tools may accept extra+ // metadata (e.g. _meta.timeout_ms) that we don't want to reject.+ }++ return Result<void>::ok();+}++} // namespace fincept::mcpdiff --git a/fincept-qt/src/mcp/SchemaValidator.h b/fincept-qt/src/mcp/SchemaValidator.hnew file mode 100644index 000000000..8e068fc3d--- /dev/null+++ b/fincept-qt/src/mcp/SchemaValidator.h@@ -0,0 +1,28 @@+#pragma once+// SchemaValidator.h — Validate + normalize tool args against a ToolSchema.+//+// Phase 3 of the MCP refactor (see plans/mcp-refactor-phase-3-schema-validation.md).+//+// Validates a QJsonObject against ToolSchema (typed `params` first, then the+// legacy `properties` JSON fragment). On success, mutates `args` in place to+// inject schema defaults so handlers receive normalised input. On failure,+// returns a Result error naming the offending parameter.+//+// This is the single validator path. It's invoked by McpProvider::call_tool+// before the handler runs, replacing the previously-orphaned+// McpService::validate_params (deleted in this phase).++#include "core/result/Result.h"+#include "mcp/McpTypes.h"++namespace fincept::mcp {++/// Validate `args` against `schema`. On success, inject defaults into `args`+/// for any param with a default that wasn't supplied by the caller. The+/// mutated args object is what handlers should subsequently read.+///+/// Errors fail fast with a descriptive message: "Invalid argument: <param>:+/// <reason>".+Result<void> validate_args(const ToolSchema& schema, QJsonObject& args);++} // namespace fincept::mcpdiff --git a/fincept-qt/src/mcp/ToolFilterPolicy.cpp b/fincept-qt/src/mcp/ToolFilterPolicy.cppnew file mode 100644index 000000000..b10009ef1--- /dev/null+++ b/fincept-qt/src/mcp/ToolFilterPolicy.cpp@@ -0,0 +1,257 @@+// ToolFilterPolicy.cpp — Screen→tool-category routing.++#include "mcp/ToolFilterPolicy.h"++#include <QHash>+#include <QJsonArray>+#include <QJsonValue>++namespace fincept::mcp {++// Parse a JSON string array into a QStringList (silently drops non-strings).+static QStringList json_to_string_list(const QJsonValue& v) {+ QStringList out;+ if (!v.isArray()) return out;+ for (const auto& item : v.toArray())+ if (item.isString()) out.append(item.toString());+ return out;+}++QStringList ToolFilterPolicy::tier_1_categories() {+ // Stable, ordered. Don't reorder casually — Anthropic prompt-cache+ // rebuilds a session prefix when the tool block bytes shift.+ return {+ "meta", // tool.list / tool.describe / mcp.health — always-on for Tier-3 discovery+ "navigation", // route_to_screen, current_screen — needed by every UI flow+ "system", // window controls, app state+ "settings", // theme, preferences+ "datahub", // hub introspection — tiny but useful for self-diagnosis+ };+}++bool ToolFilterPolicy::is_full_catalogue_screen(const QString& s) {+ // These surfaces are explicit "kitchen sink" contexts where the user is+ // either authoring/configuring tools or invoking the assistant for any+ // task. Don't pre-filter — let the LLM see everything.+ static const QHash<QString, bool> kFullCatalogue = {+ {"ai_chat", true},+ {"chat_mode", true},+ {"agent_config", true},+ {"mcp_servers", true},+ {"node_editor", true}, // workflow author tool — needs all categories+ };+ return kFullCatalogue.value(s, false);+}++QStringList ToolFilterPolicy::categories_for_screen(const QString& s) {+ // Screen → Tier-2 categories. Order doesn't matter (composed into a set+ // before filtering), but kept readable. Unknown screens return empty →+ // caller composes Tier-1 only, which is intentional (safe minimum).+ static const QHash<QString, QStringList> kMap = {+ // Core surfaces ─────────────────────────────────────────────────+ {"dashboard", {"markets", "watchlist", "news", "portfolio"}},+ {"markets", {"markets", "watchlist", "news"}},+ {"watchlist", {"watchlist", "markets", "news"}},+ {"news", {"news", "markets"}},++ // Trading ──────────────────────────────────────────────────────+ {"crypto_trading", {"crypto-trading", "markets", "watchlist", "paper-trading"}},+ {"equity_trading", {"markets", "watchlist", "paper-trading"}},+ {"paper_trading", {"paper-trading", "markets", "watchlist"}},+ {"algo_trading", {"paper-trading", "markets", "analytics"}},+ {"backtesting", {"analytics", "markets", "paper-trading"}},+ {"trade_viz", {"markets", "analytics", "paper-trading"}},++ // Research ─────────────────────────────────────────────────────+ {"equity_research", {"markets", "sec-edgar", "news", "analytics"}},+ {"portfolio", {"portfolio", "watchlist", "markets", "paper-trading", "analytics"}},+ {"surface_analytics", {"analytics", "markets"}},+ {"ma_analytics", {"ma-analytics", "sec-edgar", "markets", "news"}},+ {"derivatives", {"markets", "analytics"}},+ {"alt_investments", {"alt-investments", "markets"}},++ // Data / economics / geopolitics ───────────────────────────────+ {"data_sources", {"data-sources", "markets", "news"}},+ {"data_mapping", {"data-sources"}},+ {"dbnomics", {"data-sources", "news"}},+ {"akshare", {"data-sources", "markets", "news"}},+ {"asia_markets", {"markets", "news", "data-sources"}},+ {"economics", {"data-sources", "news"}},+ {"gov_data", {"data-sources", "news"}},+ {"geopolitics", {"news", "data-sources"}},+ {"maritime", {"news", "data-sources"}},+ {"relationship_map", {"data-sources", "news"}},+ {"polymarket", {"markets", "news"}},++ // Tools / authoring ────────────────────────────────────────────+ {"notes", {"notes", "file_manager"}},+ {"report_builder", {"report-builder", "file_manager", "markets", "news", "portfolio"}},+ {"file_manager", {"file_manager", "notes"}},+ {"code_editor", {"file_manager"}},+ {"excel", {"file_manager"}},++ // Community / account ──────────────────────────────────────────+ {"forum", {"forum", "profile"}},+ {"profile", {"profile"}},+ {"settings", {}}, // settings already in Tier-1+ {"about", {}},+ {"docs", {}},+ {"support", {}},++ // QuantLib / advanced research — analytics + markets is enough+ {"quantlib", {"analytics", "markets"}},+ {"ai_quant_lab", {"analytics", "markets"}},+ {"alpha_arena", {"analytics", "markets"}},+ };+ return kMap.value(s, {});+}++std::optional<ToolFilter> ToolFilterPolicy::filter_for_screen(const QString& screen_id) {+ if (is_full_catalogue_screen(screen_id))+ return std::nullopt;++ ToolFilter f;+ f.categories = tier_1_categories();+ for (const auto& cat : categories_for_screen(screen_id)) {+ if (!f.categories.contains(cat))+ f.categories.append(cat);+ }+ f.max_tools = kMaxToolsDefault;+ return f;+}++std::optional<ToolFilter> ToolFilterPolicy::filter_from_config_json(const QJsonObject& config) {+ if (!config.contains("tool_filter"))+ return std::nullopt;+ const QJsonObject tf = config.value("tool_filter").toObject();+ ToolFilter f;+ f.categories = json_to_string_list(tf.value("categories"));+ f.exclude_categories = json_to_string_list(tf.value("exclude_categories"));+ f.name_patterns = json_to_string_list(tf.value("name_patterns"));+ f.exclude_name_patterns = json_to_string_list(tf.value("exclude_name_patterns"));+ f.max_tools = tf.value("max_tools").toInt(0);+ return f;+}++QJsonObject ToolFilterPolicy::filter_to_config_value(const ToolFilter& f) {+ QJsonObject tf;+ QJsonArray cats;+ for (const auto& c : f.categories) cats.append(c);+ tf["categories"] = cats;++ QJsonArray xcats;+ for (const auto& c : f.exclude_categories) xcats.append(c);+ tf["exclude_categories"] = xcats;++ QJsonArray names;+ for (const auto& n : f.name_patterns) names.append(n);+ tf["name_patterns"] = names;++ QJsonArray xnames;+ for (const auto& n : f.exclude_name_patterns) xnames.append(n);+ tf["exclude_name_patterns"] = xnames;++ tf["max_tools"] = f.max_tools;+ return tf;+}++QStringList ToolFilterPolicy::infer_extra_categories(const QString& user_message) {+ // Keyword → category. Conservative: only adds when the keyword is+ // unambiguous. Case-insensitive substring match. The "extras" returned+ // here are added on top of the screen's Tier-2 set, so over-firing+ // costs at most a few extra tools — far cheaper than missing the+ // category and forcing the LLM to fall back to tool.list.+ struct Rule { QString keyword; QString category; };+ static const QVector<Rule> kRules = {+ // Portfolio / positions+ {"portfolio", "portfolio"},+ {"holdings", "portfolio"},+ {"position", "portfolio"},+ {"rebalance", "portfolio"},+ {"allocation", "portfolio"},+ {"pnl", "portfolio"},+ {"p&l", "portfolio"},++ // News+ {"news", "news"},+ {"headline", "news"},+ {"announcement", "news"},+ {"press release", "news"},++ // SEC / filings+ {"10-k", "sec-edgar"},+ {"10-q", "sec-edgar"},+ {"8-k", "sec-edgar"},+ {"edgar", "sec-edgar"},+ {"sec filing", "sec-edgar"},+ {"proxy", "sec-edgar"},++ // Reports / research+ {"report", "report-builder"},+ {"research note", "report-builder"},+ {"write up", "report-builder"},+ {"draft", "report-builder"},++ // M&A+ {"merger", "ma-analytics"},+ {"acquisition", "ma-analytics"},+ {"m&a", "ma-analytics"},+ {"buyout", "ma-analytics"},+ {"takeover", "ma-analytics"},++ // Trading+ {"buy", "paper-trading"},+ {"sell", "paper-trading"},+ {"order", "paper-trading"},+ {"paper trade", "paper-trading"},+ {"backtest", "paper-trading"},++ // Watchlist+ {"watchlist", "watchlist"},+ {"add to list", "watchlist"},+ {"track", "watchlist"},++ // Markets / quotes+ {"price", "markets"},+ {"quote", "markets"},+ {"chart", "markets"},+ {"candle", "markets"},++ // Notes+ {"note", "notes"},+ {"memo", "notes"},++ // File manager+ {"file", "file_manager"},+ {"export", "file_manager"},+ {"save to", "file_manager"},+ };++ const QString lower = user_message.toLower();+ QStringList extras;+ for (const auto& r : kRules) {+ if (lower.contains(r.keyword) && !extras.contains(r.category))+ extras.append(r.category);+ }+ return extras;+}++ToolFilter ToolFilterPolicy::compose_for_agent_and_screen(const QJsonObject& agent_config_json,+ const QString& screen_id) {+ // Per-agent filter wins when present — these are explicit operator+ // intent ("this agent only ever needs portfolio + sec-edgar tools").+ if (auto agent_filter = filter_from_config_json(agent_config_json))+ return *agent_filter;++ // Else fall back to screen-driven filter, or Tier-1-only when the+ // screen wants the "full catalogue" but we still need a sane cap.+ if (auto screen_filter = filter_for_screen(screen_id))+ return *screen_filter;++ ToolFilter f;+ f.categories = tier_1_categories();+ f.max_tools = kMaxToolsDefault;+ return f;+}++} // namespace fincept::mcpdiff --git a/fincept-qt/src/mcp/ToolFilterPolicy.h b/fincept-qt/src/mcp/ToolFilterPolicy.hnew file mode 100644index 000000000..9aafdf915--- /dev/null+++ b/fincept-qt/src/mcp/ToolFilterPolicy.h@@ -0,0 +1,102 @@+#pragma once+// ToolFilterPolicy.h — Production policy for scoping the MCP tool catalogue+// per LLM turn. Implements the 3-tier disclosure model:+//+// Tier 1 — always exposed (meta, navigation, system, settings, datahub).+// Small stable prefix → Anthropic prompt-cache friendly.+// Tier 2 — screen-scoped categories. Driven by the active screen id.+// Tier 3 — discovered lazily by the LLM via tool.list / tool.describe.+//+// Public surface:+// - tier_1_categories() → fixed set, never empty.+// - categories_for_screen() → Tier-2 add-ons; empty when screen unknown.+// - filter_for_screen() → composed ToolFilter ready for LlmService.+// Returns std::nullopt for "expose everything"+// screens (e.g. AI Chat, agent shells).+//+// Keep this file pure data + composition — no Qt UI deps, no service deps,+// so it can be unit-tested without spinning up the app.++#include "mcp/McpTypes.h"++#include <QJsonObject>+#include <QString>+#include <QStringList>++#include <optional>++namespace fincept::mcp {++class ToolFilterPolicy {+ public:+ // Tier-1 categories — exposed on every LLM turn regardless of screen.+ // Order is intentional: most-stable first (helps prompt-cache hits).+ static QStringList tier_1_categories();++ // Tier-2 categories for a given screen. Returns empty when the screen+ // has no special scoping (caller falls back to Tier-1 only or to the+ // full catalogue, depending on context).+ static QStringList categories_for_screen(const QString& screen_id);++ // Returns a fully composed ToolFilter (Tier-1 ∪ Tier-2) for a screen.+ // Returns std::nullopt when the screen wants the full unfiltered+ // catalogue (AI chat, agent shells, the MCP servers manager itself).+ // Caller (LlmService::set_tool_filter / clear_tool_filter) translates+ // nullopt into a cleared filter.+ //+ // Default cap: kMaxToolsDefault — applied even on full-catalogue screens+ // unless they explicitly opt out, so we never dump all 237+ schemas.+ static std::optional<ToolFilter> filter_for_screen(const QString& screen_id);++ // Hard ceiling for any composed filter. Tool-pick accuracy degrades+ // sharply past ~40 tools — this is the production backstop.+ static constexpr int kMaxToolsDefault = 50;++ // Screens that intentionally want the full catalogue (no scoping).+ // Examples: ai_chat, chat_mode, agent_config, mcp_servers.+ static bool is_full_catalogue_screen(const QString& screen_id);++ // ── Per-agent persistence ───────────────────────────────────────────+ // Agents store an optional ToolFilter inside AgentConfig.config_json+ // under the key "tool_filter". The fields mirror ToolFilter members.+ // Schema:+ // "tool_filter": {+ // "categories": ["markets", "watchlist"],+ // "exclude_categories": ["forum"],+ // "name_patterns": ["^get_.*"],+ // "exclude_name_patterns": [],+ // "max_tools": 40+ // }+ // Missing keys → empty defaults. Returns std::nullopt when the JSON+ // has no "tool_filter" key (caller treats as "no per-agent override").+ static std::optional<ToolFilter> filter_from_config_json(const QJsonObject& config);+ static QJsonObject filter_to_config_value(const ToolFilter& filter);++ // Compose: per-agent filter overrides → screen filter → Tier-1 only.+ // Use this when the LLM is dispatching for a specific agent on a+ // specific screen (covers the AI-chat-with-persona scenario).+ static ToolFilter compose_for_agent_and_screen(const QJsonObject& agent_config_json,+ const QString& screen_id);++ // Lightweight intent classifier. Scans the recent user message for+ // keywords that suggest categories beyond what the active screen+ // already exposes. Pure local — no LLM, no embeddings, no network.+ // Returns the categories that should be ADDED to an existing filter.+ // Empty when no extra categories are warranted.+ //+ // Examples:+ // "rebalance my portfolio" → adds "portfolio"+ // "draft a research note on…" → adds "report-builder", "sec-edgar"+ // "any news on Apple?" → adds "news"+ // "edgar 10-K for MSFT" → adds "sec-edgar"+ //+ // Caller pattern (in LlmService::chat or wherever per-turn filter is+ // assembled):+ // auto extras = ToolFilterPolicy::infer_extra_categories(user_msg);+ // for (auto& c : extras)+ // if (!filter.categories.contains(c)) filter.categories.append(c);+ // llm.set_tool_filter(filter);+ static QStringList infer_extra_categories(const QString& user_message);+};++} // namespace fincept::mcpdiff --git a/fincept-qt/src/mcp/ToolSchemaBuilder.h b/fincept-qt/src/mcp/ToolSchemaBuilder.hnew file mode 100644index 000000000..e66427515--- /dev/null+++ b/fincept-qt/src/mcp/ToolSchemaBuilder.h@@ -0,0 +1,136 @@+#pragma once+// ToolSchemaBuilder.h — Fluent helper for declaring tool input schemas.+//+// Phase 3 of the MCP refactor. See plans/mcp-refactor-phase-3-schema-validation.md.+//+// Usage:+// t.input_schema = ToolSchemaBuilder()+// .string("symbol", "Ticker symbol (e.g. AAPL, BTC-USD)").required().pattern("^[A-Z0-9._-]{1,16}$")+// .string("category", "News category").default_str("ALL").enums({"ALL","MARKETS","EARNINGS"})+// .integer("limit", "Max articles").default_int(20).between(1, 100)+// .build();+//+// The builder targets the structured `params` field of ToolSchema. Tools+// using the legacy `QJsonObject properties` shape continue to work — see+// the comment block in McpTypes.h for the dual-shape contract.++#include "mcp/McpTypes.h"++#include <QString>+#include <QStringList>++namespace fincept::mcp {++class ToolSchemaBuilder {+ public:+ ToolSchemaBuilder() = default;++ // ── Param starters ──────────────────────────────────────────────────+ // Each call adds a new ToolParam keyed by `name` and makes it the active+ // param so subsequent constraint methods (.required(), .enums(), etc.)+ // apply to it.++ ToolSchemaBuilder& string(const QString& name, const QString& description = {}) {+ return add(name, "string", description);+ }+ ToolSchemaBuilder& integer(const QString& name, const QString& description = {}) {+ return add(name, "integer", description);+ }+ ToolSchemaBuilder& number(const QString& name, const QString& description = {}) {+ return add(name, "number", description);+ }+ ToolSchemaBuilder& boolean(const QString& name, const QString& description = {}) {+ return add(name, "boolean", description);+ }+ ToolSchemaBuilder& array(const QString& name, const QString& description = {},+ const QJsonObject& items = {}) {+ add(name, "array", description);+ if (!items.isEmpty())+ current().items = items;+ return *this;+ }+ ToolSchemaBuilder& object(const QString& name, const QString& description = {}) {+ return add(name, "object", description);+ }++ // ── Constraints (apply to the most recently added param) ────────────++ ToolSchemaBuilder& required() {+ current().required = true;+ return *this;+ }+ ToolSchemaBuilder& default_str(const QString& v) {+ current().default_value = QJsonValue(v);+ return *this;+ }+ ToolSchemaBuilder& default_int(int v) {+ current().default_value = QJsonValue(v);+ return *this;+ }+ ToolSchemaBuilder& default_num(double v) {+ current().default_value = QJsonValue(v);+ return *this;+ }+ ToolSchemaBuilder& default_bool(bool v) {+ current().default_value = QJsonValue(v);+ return *this;+ }+ ToolSchemaBuilder& enums(const QStringList& values) {+ current().enum_values = values;+ return *this;+ }+ ToolSchemaBuilder& between(double min_v, double max_v) {+ current().minimum = min_v;+ current().maximum = max_v;+ return *this;+ }+ ToolSchemaBuilder& min(double v) {+ current().minimum = v;+ return *this;+ }+ ToolSchemaBuilder& max(double v) {+ current().maximum = v;+ return *this;+ }+ ToolSchemaBuilder& length(int min_len, int max_len) {+ current().min_length = min_len;+ current().max_length = max_len;+ return *this;+ }+ ToolSchemaBuilder& pattern(const QString& regex) {+ current().pattern = regex;+ return *this;+ }+ ToolSchemaBuilder& description(const QString& d) {+ current().description = d;+ return *this;+ }++ // ── Finalise ────────────────────────────────────────────────────────++ ToolSchema build() && { return std::move(schema_); }+ ToolSchema build() const& { return schema_; }++ private:+ ToolSchema schema_;+ QString last_key_;++ ToolSchemaBuilder& add(const QString& name, const QString& type, const QString& description) {+ ToolParam p;+ p.type = type;+ p.description = description;+ schema_.params.insert(name, p);+ last_key_ = name;+ return *this;+ }++ ToolParam& current() {+ // Programming error if no param has been added yet — fail fast in+ // debug builds rather than silently mutating a default-constructed+ // sentinel that's never read.+ Q_ASSERT(!last_key_.isEmpty() && schema_.params.contains(last_key_));+ return schema_.params[last_key_];+ }+};++} // namespace fincept::mcpdiff --git a/fincept-qt/src/mcp/dispatch/AdapterFactory.cpp b/fincept-qt/src/mcp/dispatch/AdapterFactory.cppnew file mode 100644index 000000000..ad368bb78--- /dev/null+++ b/fincept-qt/src/mcp/dispatch/AdapterFactory.cpp@@ -0,0 +1,31 @@+// AdapterFactory.cpp — make_adapter() implementation.+//+// Dispatches a provider id string to the correct ProviderAdapter+// implementation. Phase 5 ships with the OpenAI adapter; subsequent sessions+// add Anthropic, Gemini, Fincept, and TextRegex adapters here as they+// migrate out of LlmService.cpp.++#include "mcp/dispatch/ProviderAdapter.h"++#include "mcp/dispatch/OpenAiAdapter.h"++namespace fincept::mcp::dispatch {++std::unique_ptr<ProviderAdapter> make_adapter(const QString& provider_id) {+ // OpenAI plus all OpenAI-compatible providers (Groq, OpenRouter,+ // DeepSeek, Together, Ollama-compat, etc.) share the same wire shape.+ // The adapter only cares about the format, not the host — auth/URL+ // details stay in LlmService where they're configured.+ if (provider_id == "openai" || provider_id == "groq" || provider_id == "openrouter" ||+ provider_id == "ollama" || provider_id == "deepseek" || provider_id == "together") {+ return std::make_unique<OpenAiAdapter>();+ }++ // Anthropic, Gemini, Fincept, and TextRegex adapters land in a+ // subsequent session — see Task 5.4–5.7. Until they exist, callers+ // (LlmService) keep their existing inline tool-call paths for those+ // providers and only the OpenAI path uses the dispatcher.+ return nullptr;+}++} // namespace fincept::mcp::dispatchdiff --git a/fincept-qt/src/mcp/dispatch/OpenAiAdapter.cpp b/fincept-qt/src/mcp/dispatch/OpenAiAdapter.cppnew file mode 100644index 000000000..2d8ec219e--- /dev/null+++ b/fincept-qt/src/mcp/dispatch/OpenAiAdapter.cpp@@ -0,0 +1,128 @@+// OpenAiAdapter.cpp — OpenAI-compatible tool-call dispatch.++#include "mcp/dispatch/OpenAiAdapter.h"++#include <QJsonArray>+#include <QJsonDocument>++namespace fincept::mcp::dispatch {++// ── Helpers ──────────────────────────────────────────────────────────────────++namespace {++/// Extract user-visible text from an OpenAI-compatible `message` object.+/// Mirrors the helper in LlmService.cpp — handles plain content, content-as-parts+/// arrays, reasoning_content (kimi/deepseek-reasoner), and refusal messages.+QString extract_openai_message_text(const QJsonObject& msg) {+ QJsonValue cv = msg["content"];+ if (cv.isString()) {+ QString s = cv.toString();+ if (!s.isEmpty()) return s;+ } else if (cv.isArray()) {+ QString joined;+ for (const auto& pv : cv.toArray()) {+ QJsonObject p = pv.toObject();+ QString type = p["type"].toString();+ if (type == "text" || type == "output_text")+ joined += p["text"].toString();+ }+ if (!joined.isEmpty()) return joined;+ }+ QString rc = msg["reasoning_content"].toString();+ if (!rc.isEmpty()) return rc;+ QString refusal = msg["refusal"].toString();+ if (!refusal.isEmpty()) return refusal;+ return {};+}++} // anonymous namespace++// ── ProviderAdapter implementation ───────────────────────────────────────────++QJsonObject OpenAiAdapter::build_initial_request(+ const QString& user_message,+ const std::vector<fincept::ai_chat::ConversationMessage>& history,+ const QJsonArray& openai_tools_array) const {++ QJsonArray messages;+ for (const auto& m : history)+ messages.append(QJsonObject{{"role", m.role}, {"content", m.content}});+ messages.append(QJsonObject{{"role", "user"}, {"content", user_message}});++ QJsonObject body;+ body["messages"] = messages;+ if (!openai_tools_array.isEmpty()) {+ body["tools"] = openai_tools_array;+ body["tool_choice"] = "auto";+ }+ return body;+}++std::vector<ToolInvocation> OpenAiAdapter::parse_tool_invocations(+ const QJsonObject& response) const {++ std::vector<ToolInvocation> out;+ QJsonArray choices = response["choices"].toArray();+ if (choices.isEmpty()) return out;++ QJsonObject msg = choices[0].toObject()["message"].toObject();+ QJsonArray tcs = msg["tool_calls"].toArray();+ if (tcs.isEmpty()) return out;++ out.reserve(static_cast<std::size_t>(tcs.size()));+ for (const auto& tc_val : tcs) {+ QJsonObject tc = tc_val.toObject();+ ToolInvocation inv;+ inv.call_id = tc["id"].toString();+ inv.function_name = tc["function"].toObject()["name"].toString();+ // `arguments` is a JSON-encoded string per OpenAI spec.+ const QString args_str = tc["function"].toObject()["arguments"].toString("{}");+ inv.arguments = QJsonDocument::fromJson(args_str.toUtf8()).object();+ inv.origin = "openai";+ out.push_back(std::move(inv));+ }+ return out;+}++QJsonObject OpenAiAdapter::build_followup_request(+ const QJsonObject& original_response,+ const std::vector<ToolResultEnvelope>& results,+ const QString& user_message,+ const std::vector<fincept::ai_chat::ConversationMessage>& history) const {++ // Reconstruct the messages array: history + user + assistant (the original+ // response's message, including tool_calls) + one role:"tool" entry per result.+ QJsonArray messages;+ for (const auto& m : history)+ messages.append(QJsonObject{{"role", m.role}, {"content", m.content}});+ messages.append(QJsonObject{{"role", "user"}, {"content", user_message}});++ // Echo the assistant's tool_calls so the next request has the matching id.+ QJsonArray choices = original_response["choices"].toArray();+ if (!choices.isEmpty()) {+ QJsonObject assistant_msg = choices[0].toObject()["message"].toObject();+ messages.append(assistant_msg);+ }++ for (const auto& env : results) {+ const QString content =+ QString::fromUtf8(QJsonDocument(env.result.to_json()).toJson(QJsonDocument::Compact));+ messages.append(QJsonObject{+ {"role", "tool"},+ {"tool_call_id", env.call_id},+ {"content", content}});+ }++ QJsonObject body;+ body["messages"] = messages;+ return body;+}++QString OpenAiAdapter::extract_text(const QJsonObject& response) const {+ QJsonArray choices = response["choices"].toArray();+ if (choices.isEmpty()) return {};+ return extract_openai_message_text(choices[0].toObject()["message"].toObject());+}++} // namespace fincept::mcp::dispatchdiff --git a/fincept-qt/src/mcp/dispatch/OpenAiAdapter.h b/fincept-qt/src/mcp/dispatch/OpenAiAdapter.hnew file mode 100644index 000000000..27f5b207e--- /dev/null+++ b/fincept-qt/src/mcp/dispatch/OpenAiAdapter.h@@ -0,0 +1,38 @@+#pragma once+// OpenAiAdapter.h — OpenAI-compatible tool-call dispatch.+//+// Phase 5 of the MCP refactor. Reference adapter — captures the canonical+// shape from LlmService.cpp's OpenAI tool-call branch. Other adapters+// (Anthropic, Gemini, Fincept, TextRegex) follow this same interface.++#include "mcp/dispatch/ProviderAdapter.h"++namespace fincept::mcp::dispatch {++/// OpenAI / OpenAI-compatible (Groq, OpenRouter, DeepSeek, Together, etc.)+/// tool-call adapter. The wire shape is OpenAI's chat.completions API:+/// - Tools attached as `tools: [{type:"function", function:{name, description, parameters}}]`+/// - Tool calls in `choices[0].message.tool_calls[]`+/// - Results returned via `{role:"tool", tool_call_id, content}` messages+class OpenAiAdapter : public ProviderAdapter {+ public:+ QString id() const override { return "openai"; }++ QJsonObject build_initial_request(+ const QString& user_message,+ const std::vector<fincept::ai_chat::ConversationMessage>& history,+ const QJsonArray& openai_tools_array) const override;++ std::vector<ToolInvocation> parse_tool_invocations(+ const QJsonObject& response) const override;++ QJsonObject build_followup_request(+ const QJsonObject& original_response,+ const std::vector<ToolResultEnvelope>& results,+ const QString& user_message,+ const std::vector<fincept::ai_chat::ConversationMessage>& history) const override;++ QString extract_text(const QJsonObject& response) const override;+};++} // namespace fincept::mcp::dispatchdiff --git a/fincept-qt/src/mcp/dispatch/ProviderAdapter.h b/fincept-qt/src/mcp/dispatch/ProviderAdapter.hnew file mode 100644index 000000000..6f2f8a294--- /dev/null+++ b/fincept-qt/src/mcp/dispatch/ProviderAdapter.h@@ -0,0 +1,88 @@+#pragma once+// ProviderAdapter.h — Per-LLM-provider tool-call format adapter.+//+// Phase 5 of the MCP refactor (see plans/mcp-refactor-phase-5-dispatch-unification.md).+//+// Each adapter implements the provider-specific shape of:+// 1. Building the initial chat request body (with tools attached).+// 2. Parsing tool invocations from a response.+// 3. Building a follow-up request body that incorporates tool results.+// 4. Extracting the final user-visible text from a response.+//+// The dispatcher (ToolDispatcher.cpp) drives the multi-round loop using these+// hooks, so all five providers share one piece of orchestration logic — no+// more sequential per-provider tool loops with subtle behaviour drift+// (Anthropic's single-round bug, Gemini's single-round bug, OpenAI's 15-round+// loop, text-regex's own loop, etc.).++#include "ai_chat/LlmService.h" // ConversationMessage, LlmResponse+#include "mcp/dispatch/ToolInvocation.h"++#include <QJsonArray>+#include <QJsonObject>+#include <QString>+#include <QStringList>++#include <memory>+#include <vector>++namespace fincept::mcp::dispatch {++/// Provider-neutral tool-dispatch interface.+///+/// Adapters are stateless w.r.t. tool calls — the dispatcher passes the+/// running history, the latest LLM response, and the executed tool results+/// on each round. Adapters MAY hold per-conversation config (model name,+/// API key, base URL) constructed via the factory.+class ProviderAdapter {+ public:+ virtual ~ProviderAdapter() = default;++ /// Provider identifier ("openai", "anthropic", "gemini", "fincept",+ /// "fincept-text", "text-regex"). Used for logging only.+ virtual QString id() const = 0;++ /// Maximum number of tool-call rounds the dispatcher will run for this+ /// provider. Phase 5 sets all providers to 15 to fix the historical+ /// Anthropic/Gemini single-round bug. Per-conversation override comes+ /// from settings (Phase 6).+ virtual int default_max_rounds() const { return 15; }++ /// Build the initial request body. `openai_tools_array` is the canonical+ /// MCP tool array as produced by McpService::format_tools_for_openai —+ /// adapters reshape it for their provider (Gemini wraps in+ /// functionDeclarations, Anthropic uses a different schema, etc.).+ /// Pass an empty array to disable tools for this request.+ virtual QJsonObject build_initial_request(+ const QString& user_message,+ const std::vector<fincept::ai_chat::ConversationMessage>& history,+ const QJsonArray& openai_tools_array) const = 0;++ /// Parse tool invocations from a response. Empty vector means the model+ /// produced a final text answer (no tool calls); the dispatcher will+ /// terminate the loop and return `extract_text(response)`.+ virtual std::vector<ToolInvocation> parse_tool_invocations(+ const QJsonObject& response) const = 0;++ /// Build a follow-up request that incorporates `results`. The dispatcher+ /// passes the original response (so the adapter can echo any required+ /// fields — Anthropic needs the assistant's tool_use blocks back, Gemini+ /// needs the model's functionCall parts) and the running history.+ virtual QJsonObject build_followup_request(+ const QJsonObject& original_response,+ const std::vector<ToolResultEnvelope>& results,+ const QString& user_message,+ const std::vector<fincept::ai_chat::ConversationMessage>& history) const = 0;++ /// Extract the user-visible text from a response. Each provider has its+ /// own quirks (Anthropic content blocks, Gemini parts, OpenAI choices,+ /// reasoning models with reasoning_content, etc.). Returns empty if the+ /// response has no usable text.+ virtual QString extract_text(const QJsonObject& response) const = 0;+};++/// Factory: produce the right adapter for a given provider id.+/// Unknown providers return nullptr — caller falls back to legacy code paths.+std::unique_ptr<ProviderAdapter> make_adapter(const QString& provider_id);++} // namespace fincept::mcp::dispatchdiff --git a/fincept-qt/src/mcp/dispatch/ToolDispatcher.cpp b/fincept-qt/src/mcp/dispatch/ToolDispatcher.cppnew file mode 100644index 000000000..3720c88d4--- /dev/null+++ b/fincept-qt/src/mcp/dispatch/ToolDispatcher.cpp@@ -0,0 +1,103 @@+// ToolDispatcher.cpp — Multi-round tool-call orchestrator.++#include "mcp/dispatch/ToolDispatcher.h"++#include "core/logging/Logger.h"+#include "mcp/McpService.h"++#include <QtConcurrent/QtConcurrent>++namespace fincept::mcp::dispatch {++static constexpr const char* TAG = "ToolDispatcher";++DispatchOutcome ToolDispatcher::run(+ const QString& user_message,+ const std::vector<fincept::ai_chat::ConversationMessage>& history,+ ProviderAdapter& adapter,+ SendFn send,+ const QJsonArray& openai_tools_array,+ std::shared_ptr<std::atomic<bool>> cancelled) {++ DispatchOutcome out;+ const int max_rounds = adapter.default_max_rounds();++ auto is_cancelled = [cancelled]() { return cancelled && cancelled->load(); };++ // Round 0 — initial request.+ QJsonObject body = adapter.build_initial_request(user_message, history, openai_tools_array);++ QJsonObject response;++ for (int round = 0; round < max_rounds; ++round) {+ ++out.rounds_used;++ if (is_cancelled()) {+ out.error = "cancelled";+ return out;+ }++ // Dispatch the request via the caller-supplied sender. The future+ // resolves with the parsed JSON response on success or an empty+ // object on failure (caller's send() must surface its own errors+ // by populating an error field in the JSON).+ QFuture<QJsonObject> resp_fut = send(body);+ resp_fut.waitForFinished();+ if (resp_fut.resultCount() == 0) {+ out.error = "Empty response from provider";+ return out;+ }+ response = resp_fut.result();++ if (response.contains("__error__")) {+ // Convention: caller uses __error__ key to signal HTTP/parse failure.+ out.error = response["__error__"].toString();+ return out;+ }++ // Detect tool invocations.+ std::vector<ToolInvocation> invocations = adapter.parse_tool_invocations(response);+ if (invocations.empty()) {+ // No tool calls — final text answer.+ out.text = adapter.extract_text(response);+ return out;+ }++ LOG_INFO(TAG, QString("Round %1 (%2): %3 tool call(s)")+ .arg(round).arg(adapter.id()).arg(invocations.size()));++ // ── Parallel fan-out ──+ // Each invocation dispatches via McpService::execute_openai_function_async+ // (Phase 4 API). We collect futures then wait for all to finish so the+ // round elapses in max(t_i) instead of sum(t_i).+ std::vector<QFuture<ToolResult>> futures;+ futures.reserve(invocations.size());+ for (const auto& inv : invocations) {+ futures.push_back(+ McpService::instance().execute_openai_function_async(inv.function_name, inv.arguments));+ }++ std::vector<ToolResultEnvelope> results;+ results.reserve(invocations.size());+ for (std::size_t i = 0; i < invocations.size(); ++i) {+ futures[i].waitForFinished();+ ToolResult r = (futures[i].resultCount() > 0)+ ? futures[i].result()+ : ToolResult::fail("Tool produced no result");+ results.push_back({invocations[i].call_id, invocations[i].function_name, std::move(r)});+ }++ // Build the follow-up body for the next round.+ body = adapter.build_followup_request(response, results, user_message, history);+ }++ // Hit the round cap with tool calls still pending — surface partial text+ // if the last response had any, otherwise note the cap.+ out.max_rounds_hit = true;+ out.text = adapter.extract_text(response);+ if (out.text.isEmpty())+ out.error = QString("Max rounds (%1) reached without final answer").arg(max_rounds);+ return out;+}++} // namespace fincept::mcp::dispatchdiff --git a/fincept-qt/src/mcp/dispatch/ToolDispatcher.h b/fincept-qt/src/mcp/dispatch/ToolDispatcher.hnew file mode 100644index 000000000..d6da2d5b3--- /dev/null+++ b/fincept-qt/src/mcp/dispatch/ToolDispatcher.h@@ -0,0 +1,69 @@+#pragma once+// ToolDispatcher.h — Single multi-round tool-call orchestrator.+//+// Phase 5 of the MCP refactor. Replaces the 5 parallel tool-call loops in+// LlmService.cpp with a single state machine that drives any provider+// through its ProviderAdapter. The dispatcher fans tool calls out via+// McpService::execute_openai_function_async (Phase 4 API) so multi-tool+// rounds run in parallel instead of sequentially.+//+// Lifecycle of one user turn:+//+// 1. dispatcher.run() takes the user message, history, and adapter.+// 2. adapter->build_initial_request() produces the first request body.+// 3. The dispatcher dispatches the request (via the adapter's send hook,+// injected by the caller — see `Sender` below).+// 4. adapter->parse_tool_invocations() extracts any tool calls.+// 5. If empty, dispatcher returns adapter->extract_text() and exits.+// 6. Otherwise, all invocations dispatched in parallel via+// McpService::execute_openai_function_async; QtFuture::whenAll joins.+// 7. adapter->build_followup_request() builds the next body.+// 8. Loop back to step 3 up to adapter->default_max_rounds() rounds.+//+// Cancellation: caller sets the `cancelled` flag to abort after the current+// round (in-flight tool calls are not killed; their futures are awaited).++#include "mcp/dispatch/ProviderAdapter.h"++#include <QFuture>+#include <QJsonObject>+#include <QString>++#include <atomic>+#include <functional>+#include <memory>++namespace fincept::mcp::dispatch {++/// Function the caller supplies to send a request body to the LLM provider.+/// Returns a future resolving with the parsed JSON response.+/// The dispatcher does NOT know about HTTP, auth, or streaming — those stay+/// in LlmService where they belong; the dispatcher only orchestrates rounds.+using SendFn = std::function<QFuture<QJsonObject>(QJsonObject body)>;++/// Result of one full dispatch run.+struct DispatchOutcome {+ QString text; ///< Final assistant text, ready to display.+ QString error; ///< Non-empty on dispatch failure.+ int rounds_used = 0; ///< How many request/response rounds ran.+ bool max_rounds_hit = false; ///< True if loop terminated by round cap.+};++class ToolDispatcher {+ public:+ /// Run the full dispatch loop for one user turn.+ ///+ /// `cancelled` is polled between rounds; set it from another thread to+ /// abort. The dispatcher will not start a new round once it observes+ /// the flag, but in-flight tool calls and HTTP requests run to+ /// completion (their cancellation is owned by the caller).+ DispatchOutcome run(+ const QString& user_message,+ const std::vector<fincept::ai_chat::ConversationMessage>& history,+ ProviderAdapter& adapter,+ SendFn send,+ const QJsonArray& openai_tools_array,+ std::shared_ptr<std::atomic<bool>> cancelled = {});+};++} // namespace fincept::mcp::dispatchdiff --git a/fincept-qt/src/mcp/dispatch/ToolInvocation.h b/fincept-qt/src/mcp/dispatch/ToolInvocation.hnew file mode 100644index 000000000..3c96ab50c--- /dev/null+++ b/fincept-qt/src/mcp/dispatch/ToolInvocation.h@@ -0,0 +1,65 @@+#pragma once+// ToolInvocation.h — Provider-neutral tool-call types.+//+// Phase 5 of the MCP refactor (see plans/mcp-refactor-phase-5-dispatch-unification.md).+//+// Five LLM provider paths in LlmService.cpp each parse tool-call wire shapes+// differently:+//+// OpenAI / Fincept-OpenAI-compat: choices[0].message.tool_calls[]+// Anthropic: content blocks where type == "tool_use"+// Gemini: parts[].functionCall+// Fincept text-catalog: tool calls extracted from prompt response text+// Text-regex fallback: <tool_call>...</tool_call>, <invoke name=...>...,+// ```tool_call ... ```, minimax:tool_call ... patterns+//+// `ToolInvocation` normalises all five into one shape so the dispatcher can+// fan them out via `McpService::execute_openai_function_async` regardless of+// which provider produced them.++#include "mcp/McpTypes.h"++#include <QJsonObject>+#include <QString>++namespace fincept::mcp {++/// One tool call as emitted by an LLM, in provider-neutral form.+struct ToolInvocation {+ /// Provider-supplied call id (OpenAI tool_call_id, Anthropic tool_use id,+ /// Gemini synthetic id, etc.). The dispatcher echoes this back in the+ /// follow-up message so the LLM can match results to its requests.+ /// May be empty for text-regex extraction; the adapter generates one.+ QString call_id;++ /// "serverId__toolName" form (the canonical wire identifier — see+ /// McpProvider::parse_openai_function_name). Adapters that produce+ /// invocations from non-OpenAI shapes must convert into this form.+ QString function_name;++ /// Parsed arguments — JSON object the handler will receive.+ QJsonObject arguments;++ /// Source provider, for logging / telemetry. Not used for routing.+ /// Values: "openai" | "anthropic" | "gemini" | "fincept-text" | "text-regex".+ QString origin;+};++/// One tool call's result, ready to be folded back into a provider follow-up.+struct ToolResultEnvelope {+ /// Echoes ToolInvocation::call_id so the adapter can pair result with+ /// invocation in the follow-up message format.+ QString call_id;++ /// Echoes ToolInvocation::function_name — used by formatters that need+ /// the name in the follow-up payload (Gemini's functionResponse.name).+ QString function_name;++ /// The tool's actual return value. Adapters serialise this differently:+ /// OpenAI/Fincept put it in role:"tool" content as a JSON string;+ /// Anthropic puts it in tool_result blocks; Gemini wraps it as a+ /// functionResponse object.+ ToolResult result;+};++} // namespace fincept::mcpdiff --git a/fincept-qt/src/mcp/tools/AiChatTools.cpp b/fincept-qt/src/mcp/tools/AiChatTools.cppindex 738e9cf99..9e740606c 100644--- a/fincept-qt/src/mcp/tools/AiChatTools.cpp+++ b/fincept-qt/src/mcp/tools/AiChatTools.cpp@@ -2,9 +2,13 @@#include "mcp/tools/AiChatTools.h"+#include "core/events/EventBus.h"#include "core/logging/Logger.h"+#include "mcp/ToolSchemaBuilder.h"#include "storage/repositories/ChatRepository.h"+#include <QVariantMap>+namespace fincept::mcp::tools {std::vector<ToolDef> get_ai_chat_tools() {@@ -16,9 +20,14 @@ std::vector<ToolDef> get_ai_chat_tools() {t.name = "create_chat_session";t.description = "Create a new AI chat session.";t.category = "ai-chat";- t.input_schema.properties =- QJsonObject{{"title", QJsonObject{{"type", "string"}, {"description", "Chat session title"}}}};- t.input_schema.required = {"title"};+ // Title was previously declared `required` but the handler defaulted+ // to "New Chat" when missing — contradictory. Match the actual+ // handler behaviour: optional, default "New Chat".+ t.input_schema = ToolSchemaBuilder()+ .string("title", "Chat session title")+ .default_str("New Chat")+ .length(1, 200)+ .build();t.handler = [](const QJsonObject& args) -> ToolResult {QString title = args["title"].toString("New Chat");auto r = ChatRepository::instance().create_session(title);@@ -26,6 +35,11 @@ std::vector<ToolDef> get_ai_chat_tools() {return ToolResult::fail("Failed to create session: " + QString::fromStdString(r.error()));const auto& session = r.value();+ // Phase 2.10: publish so AiChatScreen reloads its session list+ // immediately. ChatRepository has no Qt signals (it's a plain+ // BaseRepository<T>), so EventBus is the only path.+ EventBus::instance().publish("ai_chat.session_created",+ QVariantMap{{"id", session.id}, {"title", session.title}});return ToolResult::ok("Chat session created", QJsonObject{{"id", session.id}, {"title", session.title}});};tools.push_back(std::move(t));diff --git a/fincept-qt/src/mcp/tools/AltInvestmentsTools.cpp b/fincept-qt/src/mcp/tools/AltInvestmentsTools.cppindex 1a649d381..24b6b5b55 100644--- a/fincept-qt/src/mcp/tools/AltInvestmentsTools.cpp+++ b/fincept-qt/src/mcp/tools/AltInvestmentsTools.cpp@@ -3,82 +3,88 @@#include "mcp/tools/AltInvestmentsTools.h"#include "core/logging/Logger.h"-#include "mcp/tools/ThreadHelper.h"+#include "mcp/AsyncDispatch.h"#include "python/PythonRunner.h"#include "storage/cache/CacheManager.h"#include <QJsonDocument>#include <QJsonObject>+#include <QPromise>++#include <memory>namespace fincept::mcp::tools {-static constexpr int kTimeoutMs = 30000;+static constexpr int kAltTimeoutMs = 30000;static constexpr int kAltTtlSec = 10 * 60; // 10 min — deterministic given same inputs// ── Shared async helper ──────────────────────────────────────────────────────-// Calls cli.py synchronously (blocks calling thread via QEventLoop).+// Phase 4: Resolves `promise` with the metrics JSON when cli.py finishes.+// Returns immediately; the worker thread never blocks. Cache hits resolve+// synchronously inside this function.+//// command = analyzer id (e.g. "high_yield_bond")// params = JSON object with name/type/value/rate/term/fee/current_value/additional-static ToolResult run_alt_sync(const QString& command, const QJsonObject& params) {- QString data_json = QString::fromUtf8(QJsonDocument(params).toJson(QJsonDocument::Compact));-- // Cache: key = command + serialized params+static void run_alt_async(const QString& command, const QJsonObject& params, ToolContext ctx,+ std::shared_ptr<QPromise<ToolResult>> promise) {+ const QString data_json = QString::fromUtf8(QJsonDocument(params).toJson(QJsonDocument::Compact));const QString cache_key = "alt:" + command + ":" + data_json;++ // Cache hit — resolve immediately, no Python spawn.const QVariant cached = fincept::CacheManager::instance().get(cache_key);if (!cached.isNull()) {auto doc = QJsonDocument::fromJson(cached.toString().toUtf8());- if (!doc.isNull() && doc.isObject())- return ToolResult::ok_data(doc.object());+ if (!doc.isNull() && doc.isObject()) {+ promise->addResult(ToolResult::ok_data(doc.object()));+ promise->finish();+ return;+ }}- ToolResult tool_result = ToolResult::fail("Python runner failed to respond");-- // Marshal onto PythonRunner's thread (main). Worker-thread QEventLoop- // would never be woken by main-thread QProcess::finished signals.auto* runner = &python::PythonRunner::instance();- detail::run_async_wait(runner, [&](auto signal_done) {- runner->run("Analytics/alternateInvestment/cli.py", {command, "--data", data_json},- [&, signal_done](const python::PythonResult& result) {- if (!result.success) {- tool_result = ToolResult::fail(- result.error.isEmpty() ? "Analysis failed" : result.error);- signal_done();- return;- }- // Extract JSON from stdout- QString out = result.output;- int start = out.indexOf('{');- int end = out.lastIndexOf('}');- if (start < 0 || end < 0 || end <= start) {- tool_result = ToolResult::fail("No JSON in output");- signal_done();- return;- }- QJsonParseError err;- auto doc = QJsonDocument::fromJson(out.mid(start, end - start + 1).toUtf8(), &err);- if (doc.isNull() || !doc.isObject()) {- tool_result = ToolResult::fail("Invalid JSON: " + err.errorString());- signal_done();- return;- }- auto obj = doc.object();- if (obj.contains("error")) {- tool_result = ToolResult::fail(obj["error"].toString());- signal_done();- return;- }- auto metrics = obj.contains("metrics") ? obj["metrics"].toObject() : obj;- fincept::CacheManager::instance().put(- cache_key,- QVariant(QString::fromUtf8(QJsonDocument(metrics).toJson(QJsonDocument::Compact))),- kAltTtlSec, "alt_investments");- tool_result = ToolResult::ok_data(metrics);- signal_done();- });- });-- return tool_result;+ AsyncDispatch::callback_to_promise(+ runner, ctx, promise,+ [runner, command, data_json, cache_key, ctx](auto resolve) {+ runner->run("Analytics/alternateInvestment/cli.py", {command, "--data", data_json},+ [resolve, cache_key, ctx](const python::PythonResult& result) {+ if (ctx.cancelled()) {+ resolve(ToolResult::fail("cancelled"));+ return;+ }+ if (!result.success) {+ resolve(ToolResult::fail(+ result.error.isEmpty() ? "Analysis failed" : result.error));+ return;+ }+ // Extract JSON from stdout+ QString out = result.output;+ int start = out.indexOf('{');+ int end = out.lastIndexOf('}');+ if (start < 0 || end < 0 || end <= start) {+ resolve(ToolResult::fail("No JSON in output"));+ return;+ }+ QJsonParseError err;+ auto doc = QJsonDocument::fromJson(+ out.mid(start, end - start + 1).toUtf8(), &err);+ if (doc.isNull() || !doc.isObject()) {+ resolve(ToolResult::fail("Invalid JSON: " + err.errorString()));+ return;+ }+ auto obj = doc.object();+ if (obj.contains("error")) {+ resolve(ToolResult::fail(obj["error"].toString()));+ return;+ }+ auto metrics = obj.contains("metrics") ? obj["metrics"].toObject() : obj;+ fincept::CacheManager::instance().put(+ cache_key,+ QVariant(QString::fromUtf8(QJsonDocument(metrics).toJson(QJsonDocument::Compact))),+ kAltTtlSec, "alt_investments");+ resolve(ToolResult::ok_data(metrics));+ });+ });}// ── Common input schema ──────────────────────────────────────────────────────@@ -100,6 +106,9 @@ static ToolSchema make_schema(const QString& type_description) {}// ── Tool factory macro ───────────────────────────────────────────────────────+// Phase 4: every alt analyzer runs cli.py asynchronously. The macro emits an+// AsyncToolHandler that builds the params dict and delegates to run_alt_async,+// which resolves the promise when Python finishes (or the watchdog fires).#define ALT_TOOL(CMD, NAME, DESC, TYPE_DESC) \{ \@@ -108,7 +117,9 @@ static ToolSchema make_schema(const QString& type_description) {t.description = (DESC); \t.category = "alt-investments"; \t.input_schema = make_schema(TYPE_DESC); \- t.handler = [](const QJsonObject& args) -> ToolResult { \+ t.default_timeout_ms = kAltTimeoutMs; \+ t.async_handler = [](const QJsonObject& args, ToolContext ctx, \+ std::shared_ptr<QPromise<ToolResult>> promise) { \QJsonObject p; \p["name"] = args["name"].toString("Investment"); \p["type"] = args["type"].toString("default"); \@@ -118,7 +129,7 @@ static ToolSchema make_schema(const QString& type_description) {p["fee"] = args["fee"].toDouble(0) / 100.0; \p["current_value"] = args["current_value"].toDouble(0); \p["additional"] = args["additional"].toDouble(0); \- return run_alt_sync(CMD, p); \+ run_alt_async(CMD, p, ctx, promise); \}; \tools.push_back(std::move(t)); \}diff --git a/fincept-qt/src/mcp/tools/DataHubTools.cpp b/fincept-qt/src/mcp/tools/DataHubTools.cppindex 720de34e2..61ffdee7c 100644--- a/fincept-qt/src/mcp/tools/DataHubTools.cpp+++ b/fincept-qt/src/mcp/tools/DataHubTools.cpp@@ -8,16 +8,20 @@#include "core/logging/Logger.h"#include "datahub/DataHub.h"+#include "mcp/ToolSchemaBuilder.h"+#include <QCoreApplication>#include <QDateTime>#include <QElapsedTimer>-#include <QEventLoop>#include <QJsonArray>#include <QJsonDocument>#include <QPointer>+#include <QPromise>#include <QTimer>#include <QVariantList>+#include <memory>+namespace fincept::mcp::tools {static constexpr const char* TAG = "DataHubTools";@@ -137,11 +141,11 @@ std::vector<ToolDef> get_datahub_tools() {}// ── datahub_subscribe_briefly ───────────────────────────────────────- // Subscribes a disposable QObject-owned listener to the topic for- // `duration_ms` (clamped to [100, 30000]). Accumulates every delivered- // value then returns the vector. Synchronous on purpose — MCP tools- // are called from a thread where a local QEventLoop is the simplest- // way to wait without blocking the Qt UI thread.+ // Phase 4 streaming exemplar (replaces the previous nested-QEventLoop+ // hack). Async handler: subscribes a heap-allocated owner to the topic+ // on the DataHub's thread, collects samples until duration elapses or+ // cancellation fires, then resolves the promise with the accumulated+ // payload. No worker-thread blocking, no nested event loops.{ToolDef t;t.name = "datahub_subscribe_briefly";@@ -150,38 +154,61 @@ std::vector<ToolDef> get_datahub_tools() {"Useful for sampling a volatile topic (e.g. a live ticker) to ""reason about its recent behaviour.";t.category = "datahub";- t.input_schema.properties = QJsonObject{- {"topic", QJsonObject{{"type", "string"}, {"description", "Topic name"}}},- {"duration_ms", QJsonObject{{"type", "integer"}, {"description", "Window length in milliseconds"}}}};- t.input_schema.required = {"topic", "duration_ms"};- t.handler = [](const QJsonObject& args) -> ToolResult {+ t.input_schema = ToolSchemaBuilder()+ .string("topic", "Topic name (e.g. market:quote:AAPL)")+ .required().length(1, 256)+ .integer("duration_ms", "Window length in milliseconds")+ .required().between(100, 30000)+ .build();+ // Generous timeout = max duration + slack. Provider's watchdog kicks+ // in only if the unsubscribe-and-resolve dance gets stuck.+ t.default_timeout_ms = 35000;+ t.async_handler = [](const QJsonObject& args, ToolContext ctx,+ std::shared_ptr<QPromise<ToolResult>> promise) {const QString topic = args["topic"].toString().trimmed();- if (topic.isEmpty()) return ToolResult::fail("Missing 'topic'");- int duration = args["duration_ms"].toInt();- duration = std::clamp(duration, 100, 30000);- auto& hub = fincept::datahub::DataHub::instance();- QObject owner;- QJsonArray collected;- QElapsedTimer clock;- clock.start();- hub.subscribe(&owner, topic, [&collected, &clock](const QVariant& v) {- QJsonObject e;- e["t_ms"] = static_cast<qint64>(clock.elapsed());- e["value"] = variant_to_json(v);- collected.append(e);- });-- QEventLoop loop;- QTimer::singleShot(duration, &loop, &QEventLoop::quit);- loop.exec();- hub.unsubscribe(&owner);-- QJsonObject out;- out["topic"] = topic;- out["duration_ms"] = duration;- out["count"] = collected.size();- out["samples"] = collected;- return ToolResult::ok_data(out);+ int duration = std::clamp(args["duration_ms"].toInt(), 100, 30000);++ // Marshal the entire setup onto qApp's thread so:+ // • DataHub::subscribe runs on the hub's thread (consistent+ // with how the rest of the codebase uses it)+ // • the owner QObject's affinity is qApp — its deleteLater+ // posts to a thread that actually has a running event loop+ // (the worker thread that called the handler may have no+ // event loop and would leak the owner)+ QMetaObject::invokeMethod(qApp, [topic, duration, ctx, promise]() {+ auto* owner = new QObject;+ owner->setObjectName("mcp.subscribe_briefly:" + topic);++ auto collected = std::make_shared<QJsonArray>();+ auto clock = std::make_shared<QElapsedTimer>();+ clock->start();++ fincept::datahub::DataHub::instance().subscribe(+ owner, topic, [collected, clock](const QVariant& v) {+ QJsonObject e;+ e["t_ms"] = static_cast<qint64>(clock->elapsed());+ e["value"] = variant_to_json(v);+ collected->append(e);+ });++ QTimer::singleShot(duration, qApp, [topic, duration, collected, owner, promise, ctx]() {+ fincept::datahub::DataHub::instance().unsubscribe(owner);+ owner->deleteLater();++ if (promise->future().isFinished()) return; // watchdog already fired+ QJsonObject out;+ out["topic"] = topic;+ out["duration_ms"] = duration;+ out["count"] = collected->size();+ out["samples"] = *collected;+ if (ctx.cancelled()) {+ promise->addResult(ToolResult::fail("cancelled"));+ } else {+ promise->addResult(ToolResult::ok_data(out));+ }+ promise->finish();+ });+ }, Qt::QueuedConnection);};tools.push_back(std::move(t));}diff --git a/fincept-qt/src/mcp/tools/ExchangeTools.cpp b/fincept-qt/src/mcp/tools/ExchangeTools.cppdeleted file mode 100644index 22029b001..000000000--- a/fincept-qt/src/mcp/tools/ExchangeTools.cpp+++ /dev/null@@ -1,165 +0,0 @@-// ExchangeTools.cpp — Live crypto exchange data tools (Qt port)--#include "mcp/tools/ExchangeTools.h"--#include "core/logging/Logger.h"-#include "trading/ExchangeService.h"--namespace fincept::mcp::tools {--std::vector<ToolDef> get_exchange_tools() {- std::vector<ToolDef> tools;-- // ── get_ticker ─────────────────────────────────────────────────────- {- ToolDef t;- t.name = "get_ticker";- t.description = "Get the latest price, volume, and change for a symbol from the configured exchange.";- t.category = "exchange";- t.input_schema.properties = QJsonObject{- {"symbol", QJsonObject{{"type", "string"}, {"description", "Trading pair (e.g. BTC/USDT, ETH/USDT)"}}}};- t.input_schema.required = {"symbol"};- t.handler = [](const QJsonObject& args) -> ToolResult {- QString symbol = args["symbol"].toString().trimmed();- if (symbol.isEmpty())- return ToolResult::fail("Missing 'symbol'");-- auto& svc = trading::ExchangeService::instance();- if (svc.get_exchange().isEmpty())- return ToolResult::fail("No exchange configured — set one in Crypto Trading first");-- try {- auto ticker = svc.fetch_ticker(symbol);- return ToolResult::ok_data(QJsonObject{{"symbol", ticker.symbol},- {"last", ticker.last},- {"bid", ticker.bid},- {"ask", ticker.ask},- {"high", ticker.high},- {"low", ticker.low},- {"open", ticker.open},- {"close", ticker.close},- {"change", ticker.change},- {"change_pct", ticker.percentage},- {"volume", ticker.base_volume},- {"quote_volume", ticker.quote_volume},- {"timestamp", static_cast<double>(ticker.timestamp)}});- } catch (const std::exception& e) {- return ToolResult::fail(e.what());- }- };- tools.push_back(std::move(t));- }-- // ── get_order_book ─────────────────────────────────────────────────- {- ToolDef t;- t.name = "get_order_book";- t.description = "Get the order book (bids and asks) for a symbol.";- t.category = "exchange";- t.input_schema.properties =- QJsonObject{{"symbol", QJsonObject{{"type", "string"}, {"description", "Trading pair"}}},- {"limit", QJsonObject{{"type", "integer"}, {"description", "Number of levels (default: 20)"}}}};- t.input_schema.required = {"symbol"};- t.handler = [](const QJsonObject& args) -> ToolResult {- QString symbol = args["symbol"].toString().trimmed();- int limit = args["limit"].toInt(20);- if (symbol.isEmpty())- return ToolResult::fail("Missing 'symbol'");-- auto& svc = trading::ExchangeService::instance();- if (svc.get_exchange().isEmpty())- return ToolResult::fail("No exchange configured");-- try {- auto ob = svc.fetch_orderbook(symbol, limit);- QJsonArray bids, asks;- for (const auto& level : ob.bids)- bids.append(QJsonObject{{"price", level.first}, {"amount", level.second}});- for (const auto& level : ob.asks)- asks.append(QJsonObject{{"price", level.first}, {"amount", level.second}});-- return ToolResult::ok_data(QJsonObject{{"symbol", ob.symbol},- {"best_bid", ob.best_bid},- {"best_ask", ob.best_ask},- {"spread", ob.spread},- {"spread_pct", ob.spread_pct},- {"bids", bids},- {"asks", asks}});- } catch (const std::exception& e) {- return ToolResult::fail(e.what());- }- };- tools.push_back(std::move(t));- }-- // ── get_candles ────────────────────────────────────────────────────- {- ToolDef t;- t.name = "get_candles";- t.description = "Get OHLCV candle data for a symbol. Timeframes: 1m, 5m, 15m, 1h, 4h, 1d.";- t.category = "exchange";- t.input_schema.properties = QJsonObject{- {"symbol", QJsonObject{{"type", "string"}, {"description", "Trading pair"}}},- {"timeframe", QJsonObject{{"type", "string"}, {"description", "Candle interval (default: 1h)"}}},- {"limit", QJsonObject{{"type", "integer"}, {"description", "Number of candles (default: 100)"}}}};- t.input_schema.required = {"symbol"};- t.handler = [](const QJsonObject& args) -> ToolResult {- QString symbol = args["symbol"].toString().trimmed();- QString timeframe = args["timeframe"].toString("1h");- int limit = args["limit"].toInt(100);- if (symbol.isEmpty())- return ToolResult::fail("Missing 'symbol'");-- auto& svc = trading::ExchangeService::instance();- if (svc.get_exchange().isEmpty())- return ToolResult::fail("No exchange configured");-- try {- auto candles = svc.fetch_ohlcv(symbol, timeframe, limit);- QJsonArray result;- for (const auto& c : candles) {- result.append(QJsonObject{{"timestamp", static_cast<double>(c.timestamp)},- {"open", c.open},- {"high", c.high},- {"low", c.low},- {"close", c.close},- {"volume", c.volume}});- }- return ToolResult::ok_data(result);- } catch (const std::exception& e) {- return ToolResult::fail(e.what());- }- };- tools.push_back(std::move(t));- }-- // ── get_exchange_info ──────────────────────────────────────────────- {- ToolDef t;- t.name = "get_exchange_info";- t.description = "Get the currently configured exchange name and list all available exchange IDs.";- t.category = "exchange";- t.handler = [](const QJsonObject&) -> ToolResult {- auto& svc = trading::ExchangeService::instance();- QString current = svc.get_exchange();-- try {- auto ids = svc.list_exchange_ids();- QJsonArray id_arr;- for (const auto& id : ids)- id_arr.append(id);-- return ToolResult::ok_data(QJsonObject{{"current_exchange", current.isEmpty() ? "none" : current},- {"available_exchanges", id_arr}});- } catch (...) {- return ToolResult::ok_data(QJsonObject{{"current_exchange", current.isEmpty() ? "none" : current},- {"available_exchanges", QJsonArray{}}});- }- };- tools.push_back(std::move(t));- }-- return tools;-}--} // namespace fincept::mcp::toolsdiff --git a/fincept-qt/src/mcp/tools/ExchangeTools.h b/fincept-qt/src/mcp/tools/ExchangeTools.hdeleted file mode 100644index 4a8b6ddf3..000000000--- a/fincept-qt/src/mcp/tools/ExchangeTools.h+++ /dev/null@@ -1,8 +0,0 @@-#pragma once-#include "mcp/McpTypes.h"--#include <vector>--namespace fincept::mcp::tools {-std::vector<ToolDef> get_exchange_tools();-} // namespace fincept::mcp::toolsdiff --git a/fincept-qt/src/mcp/tools/MAAnalyticsTools.cpp b/fincept-qt/src/mcp/tools/MAAnalyticsTools.cppindex 6d0894188..3d61e8ad5 100644--- a/fincept-qt/src/mcp/tools/MAAnalyticsTools.cpp+++ b/fincept-qt/src/mcp/tools/MAAnalyticsTools.cpp@@ -5,19 +5,32 @@#include "mcp/tools/MAAnalyticsTools.h"#include "core/logging/Logger.h"+#include "mcp/AsyncDispatch.h"#include "mcp/tools/ThreadHelper.h"#include "services/ma_analytics/MAAnalyticsService.h"#include <QJsonDocument>+#include <QPromise>++#include <memory>namespace fincept::mcp::tools {static constexpr const char* TAG = "MAAnalyticsTools";-// Wait for an async MA service operation to complete. The trigger lambda-// runs on the service thread (so it's safe to start a request that emits-// signals back on that same thread). Worker thread sleeps on a wait-// condition until the service emits result_ready or error_occurred.+// Phase 4 — both shapes provided:+//+// run_ma_sync — blocks worker thread until svc emits result_ready/error.+// Pre-Phase-4 default; 46 tools use this. Each can migrate+// to async incrementally by switching its handler to+// t.async_handler and calling run_ma_async.+//+// run_ma_async — non-blocking. Invokes `trigger` on the MA service's+// thread, hooks result_ready/error_occurred for the given+// context, resolves the promise when either fires.+// Cancellation observed via ctx.cancelled before resolve.+// Trigger MUST capture inputs by value — it runs on the+// service thread after the calling lambda has returned.static ToolResult run_ma_sync(const QString& context, std::function<void()> trigger) {QJsonObject result_data;QString error_msg;@@ -26,14 +39,10 @@ static ToolResult run_ma_sync(const QString& context, std::function<void()> trigauto& svc = fincept::services::ma::MAAnalyticsService::instance();detail::run_async_wait(&svc, [&](auto signal_done) {- // Hook the signals on the service's thread before triggering, so we- // never miss an immediate callback. The connections are scoped via- // a heap QObject so we can disconnect deterministically.auto* gate = new QObject;QObject::connect(&svc, &fincept::services::ma::MAAnalyticsService::result_ready, gate,[&, gate, signal_done](const QString& ctx, const QJsonObject& data) {- if (ctx != context)- return;+ if (ctx != context) return;result_data = data;got_result = true;gate->deleteLater();@@ -41,8 +50,7 @@ static ToolResult run_ma_sync(const QString& context, std::function<void()> trig});QObject::connect(&svc, &fincept::services::ma::MAAnalyticsService::error_occurred, gate,[&, gate, signal_done](const QString& ctx, const QString& msg) {- if (ctx != context)- return;+ if (ctx != context) return;error_msg = msg;got_result = true;gate->deleteLater();@@ -55,10 +63,35 @@ static ToolResult run_ma_sync(const QString& context, std::function<void()> trigreturn ToolResult::fail("M&A result missing: " + context);if (!error_msg.isEmpty())return ToolResult::fail(error_msg);-return ToolResult::ok_data(result_data);}+[[maybe_unused]]+static void run_ma_async(const QString& context, std::function<void()> trigger,+ ToolContext ctx, std::shared_ptr<QPromise<ToolResult>> promise) {+ auto* svc = &fincept::services::ma::MAAnalyticsService::instance();++ AsyncDispatch::callback_to_promise(+ svc, ctx, promise,+ [svc, context, trigger = std::move(trigger), ctx](auto resolve) {+ auto* gate = new QObject;+ QObject::connect(svc, &fincept::services::ma::MAAnalyticsService::result_ready, gate,+ [gate, context, resolve, ctx](const QString& c, const QJsonObject& data) {+ if (c != context) return;+ if (ctx.cancelled()) resolve(ToolResult::fail("cancelled"));+ else resolve(ToolResult::ok_data(data));+ gate->deleteLater();+ });+ QObject::connect(svc, &fincept::services::ma::MAAnalyticsService::error_occurred, gate,+ [gate, context, resolve](const QString& c, const QString& msg) {+ if (c != context) return;+ resolve(ToolResult::fail(msg));+ gate->deleteLater();+ });+ trigger();+ });+}+std::vector<ToolDef> get_ma_analytics_tools() {std::vector<ToolDef> tools;diff --git a/fincept-qt/src/mcp/tools/MarketDataTools.cpp b/fincept-qt/src/mcp/tools/MarketDataTools.cppdeleted file mode 100644index 7d7142d6c..000000000--- a/fincept-qt/src/mcp/tools/MarketDataTools.cpp+++ /dev/null@@ -1,63 +0,0 @@-// MarketDataTools.cpp — Quote lookup and symbol search MCP tools--#include "mcp/tools/MarketDataTools.h"--#include "core/events/EventBus.h"-#include "core/logging/Logger.h"--#include <QVariantMap>--namespace fincept::mcp::tools {--static constexpr const char* TAG = "MarketTools";--std::vector<ToolDef> get_market_data_tools() {- std::vector<ToolDef> tools;-- // ── get_quote ───────────────────────────────────────────────────────- {- ToolDef t;- t.name = "get_quote";- t.description = "Request a stock/crypto quote. Publishes a request event and returns confirmation. "- "The actual data is delivered to the Markets screen.";- t.category = "market-data";- t.input_schema.properties = QJsonObject{- {"symbol", QJsonObject{{"type", "string"}, {"description", "Ticker symbol (e.g. AAPL, BTC-USD)"}}}};- t.input_schema.required = {"symbol"};- t.handler = [](const QJsonObject& args) -> ToolResult {- QString symbol = args["symbol"].toString().trimmed().toUpper();- if (symbol.isEmpty())- return ToolResult::fail("Missing 'symbol'");-- EventBus::instance().publish("market.get_quote", QVariantMap{{"symbol", symbol}});- LOG_DEBUG(TAG, "Quote requested: " + symbol);- return ToolResult::ok("Quote request sent for " + symbol, QJsonObject{{"symbol", symbol}});- };- tools.push_back(std::move(t));- }-- // ── search_symbol ───────────────────────────────────────────────────- {- ToolDef t;- t.name = "search_symbol";- t.description = "Search for a ticker symbol by company name or partial symbol.";- t.category = "market-data";- t.input_schema.properties =- QJsonObject{{"query", QJsonObject{{"type", "string"},- {"description", "Search query (company name or partial symbol)"}}}};- t.input_schema.required = {"query"};- t.handler = [](const QJsonObject& args) -> ToolResult {- QString query = args["query"].toString().trimmed();- if (query.isEmpty())- return ToolResult::fail("Missing 'query'");-- EventBus::instance().publish("market.search_symbol", QVariantMap{{"query", query}});- return ToolResult::ok("Symbol search sent for: " + query);- };- tools.push_back(std::move(t));- }-- return tools;-}--} // namespace fincept::mcp::toolsdiff --git a/fincept-qt/src/mcp/tools/MarketDataTools.h b/fincept-qt/src/mcp/tools/MarketDataTools.hdeleted file mode 100644index 2cee2e276..000000000--- a/fincept-qt/src/mcp/tools/MarketDataTools.h+++ /dev/null@@ -1,8 +0,0 @@-#pragma once-#include "mcp/McpTypes.h"--#include <vector>--namespace fincept::mcp::tools {-std::vector<ToolDef> get_market_data_tools();-} // namespace fincept::mcp::toolsdiff --git a/fincept-qt/src/mcp/tools/MarketsTools.cpp b/fincept-qt/src/mcp/tools/MarketsTools.cppindex 14357264c..c8f695e63 100644--- a/fincept-qt/src/mcp/tools/MarketsTools.cpp+++ b/fincept-qt/src/mcp/tools/MarketsTools.cpp@@ -2,10 +2,9 @@#include "mcp/tools/MarketsTools.h"-#include "core/events/EventBus.h"#include "core/logging/Logger.h"--#include <QVariantMap>+#include "mcp/tools/ThreadHelper.h"+#include "services/markets/MarketDataService.h"namespace fincept::mcp::tools {@@ -15,11 +14,17 @@ std::vector<ToolDef> get_markets_tools() {std::vector<ToolDef> tools;// ── get_quote ───────────────────────────────────────────────────────+ // Synchronous fetch via MarketDataService. The service batches/dedups+ // (100 ms window) and publishes results to the DataHub `market:quote:<sym>`+ // topic as a side effect, so the same call warms the hub for any+ // streaming subscribers. Worker-thread blocking is bridged via+ // detail::run_async_wait — the service lives on the main thread.{ToolDef t;t.name = "get_quote";- t.description = "Request a stock/crypto quote. Publishes a request event and returns confirmation. "- "The actual data is delivered to the Markets screen.";+ t.description = "Fetch the latest stock/ETF/crypto quote (price, change, "+ "high/low, volume). Backed by yfinance. Symbols accept "+ "AAPL, BTC-USD, ^GSPC, GBPUSD=X, GC=F, etc.";t.category = "markets";t.input_schema.properties = QJsonObject{{"symbol", QJsonObject{{"type", "string"}, {"description", "Ticker symbol (e.g. AAPL, BTC-USD)"}}}};@@ -29,34 +34,49 @@ std::vector<ToolDef> get_markets_tools() {if (symbol.isEmpty())return ToolResult::fail("Missing 'symbol'");- EventBus::instance().publish("market.get_quote", QVariantMap{{"symbol", symbol}});- LOG_DEBUG(TAG, "Quote requested: " + symbol);- return ToolResult::ok("Quote request sent for " + symbol, QJsonObject{{"symbol", symbol}});- };- tools.push_back(std::move(t));- }+ auto* svc = &services::MarketDataService::instance();+ bool ok = false;+ services::QuoteData q;+ detail::run_async_wait(svc, [svc, symbol, &ok, &q](auto signal_done) {+ svc->fetch_quotes({symbol}, [&ok, &q, symbol, signal_done](bool success, QVector<services::QuoteData> quotes) {+ if (success) {+ for (const auto& candidate : quotes) {+ if (candidate.symbol.compare(symbol, Qt::CaseInsensitive) == 0) {+ q = candidate;+ ok = true;+ break;+ }+ }+ }+ signal_done();+ });+ });- // ── search_symbol ───────────────────────────────────────────────────- {- ToolDef t;- t.name = "search_symbol";- t.description = "Search for a ticker symbol by company name or partial symbol.";- t.category = "markets";- t.input_schema.properties =- QJsonObject{{"query", QJsonObject{{"type", "string"},- {"description", "Search query (company name or partial symbol)"}}}};- t.input_schema.required = {"query"};- t.handler = [](const QJsonObject& args) -> ToolResult {- QString query = args["query"].toString().trimmed();- if (query.isEmpty())- return ToolResult::fail("Missing 'query'");+ if (!ok) {+ LOG_WARN(TAG, "fetch_quotes returned no data for " + symbol);+ return ToolResult::fail("No quote data available for " + symbol);+ }- EventBus::instance().publish("market.search_symbol", QVariantMap{{"query", query}});- return ToolResult::ok("Symbol search sent for: " + query);+ return ToolResult::ok_data(QJsonObject{{"symbol", q.symbol},+ {"name", q.name},+ {"price", q.price},+ {"change", q.change},+ {"change_pct", q.change_pct},+ {"high", q.high},+ {"low", q.low},+ {"volume", q.volume}});};tools.push_back(std::move(t));}+ // ── search_symbol ───────────────────────────────────────────────────+ // Removed in Phase 2: no backend exists for symbol search. The previous+ // implementation published a `market.search_symbol` event with no+ // subscriber and returned a fake-OK ToolResult to the LLM. Per the+ // Phase 2 plan we delete the tool rather than leave it broken.+ // Future option: wire to an OpenFIGI / Yahoo /v1/finance/search+ // endpoint via a Python script, then re-register here.+return tools;}diff --git a/fincept-qt/src/mcp/tools/MetaTools.cpp b/fincept-qt/src/mcp/tools/MetaTools.cppnew file mode 100644index 000000000..09d15c51c--- /dev/null+++ b/fincept-qt/src/mcp/tools/MetaTools.cpp@@ -0,0 +1,165 @@+// MetaTools.cpp — Self-introspection tools (tool.list, tool.describe, mcp.health).++#include "mcp/tools/MetaTools.h"++#include "core/logging/Logger.h"+#include "datahub/DataHub.h"+#include "mcp/McpManager.h"+#include "mcp/McpProvider.h"+#include "mcp/ToolSchemaBuilder.h"++#include <QDateTime>+#include <QJsonArray>+#include <QJsonObject>+#include <QRegularExpression>++namespace fincept::mcp::tools {++static constexpr const char* TAG = "MetaTools";++std::vector<ToolDef> get_meta_tools() {+ std::vector<ToolDef> tools;++ // ── tool.list ───────────────────────────────────────────────────────+ {+ ToolDef t;+ t.name = "tool.list";+ t.description = "List MCP tools available to the LLM, optionally filtered by category "+ "and/or a regex search over name+description. Returns name + 1-line "+ "description only — call tool.describe(name) for full schemas.";+ t.category = "meta";+ t.input_schema = ToolSchemaBuilder()+ .string("category", "Filter by tool category (e.g. 'markets', 'news', 'paper-trading')")+ .string("search", "Regex matched against name or description (case-insensitive)")+ .integer("limit", "Max tools returned").default_int(50).between(1, 500)+ .build();+ t.handler = [](const QJsonObject& args) -> ToolResult {+ const QString category = args["category"].toString();+ const QString search = args["search"].toString();+ const int limit = args["limit"].toInt(50);++ QRegularExpression rx;+ if (!search.isEmpty())+ rx = QRegularExpression(search, QRegularExpression::CaseInsensitiveOption);++ const auto all = McpProvider::instance().list_tools();+ QJsonArray out;+ int total = 0;+ for (const auto& tool : all) {+ if (!category.isEmpty() && tool.category != category) continue;+ if (rx.isValid() && !search.isEmpty()) {+ if (!rx.match(tool.name).hasMatch() && !rx.match(tool.description).hasMatch())+ continue;+ }+ ++total;+ if (out.size() < limit) {+ out.append(QJsonObject{+ {"name", tool.name},+ {"category", tool.category},+ {"description", tool.description},+ });+ }+ }+ return ToolResult::ok_data(QJsonObject{+ {"count", out.size()},+ {"total_matched", total},+ {"limit", limit},+ {"tools", out}});+ };+ tools.push_back(std::move(t));+ }++ // ── tool.describe ───────────────────────────────────────────────────+ {+ ToolDef t;+ t.name = "tool.describe";+ t.description = "Return the full description and JSON Schema for one MCP tool. "+ "Use after tool.list to fetch the parameter shape before calling.";+ t.category = "meta";+ t.input_schema = ToolSchemaBuilder()+ .string("name", "Bare tool name (without server_id__ prefix)").required().length(1, 128)+ .build();+ t.handler = [](const QJsonObject& args) -> ToolResult {+ const QString name = args["name"].toString();+ 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},+ });+ }+ }+ return ToolResult::fail("Tool not found: " + name);+ };+ tools.push_back(std::move(t));+ }++ // ── mcp.health ──────────────────────────────────────────────────────+ {+ ToolDef t;+ t.name = "mcp.health";+ t.description = "Snapshot of MCP system health: internal tool counts by category, "+ "external server statuses + last errors, and DataHub topic activity. "+ "Useful for agents to self-diagnose ('why is my tool failing?').";+ t.category = "meta";+ t.handler = [](const QJsonObject&) -> ToolResult {+ const auto all = McpProvider::instance().list_all_tools();+ const auto enabled_count = McpProvider::instance().tool_count();++ QHash<QString, int> by_cat;+ for (const auto& t : all) by_cat[t.category]++;+ QJsonObject categories;+ for (auto it = by_cat.constBegin(); it != by_cat.constEnd(); ++it)+ categories[it.key().isEmpty() ? "(uncategorised)" : it.key()] = it.value();++ QJsonObject internal_section{+ {"tool_count", static_cast<int>(enabled_count)},+ {"all_count", static_cast<int>(all.size())},+ {"disabled_count", static_cast<int>(all.size() - enabled_count)},+ {"categories", categories},+ };++ QJsonArray servers;+ for (const auto& cfg : McpManager::instance().get_servers()) {+ servers.append(QJsonObject{+ {"id", cfg.id},+ {"name", cfg.name},+ {"status", server_status_str(cfg.status)},+ {"enabled", cfg.enabled},+ {"auto_start", cfg.auto_start},+ });+ }+ QJsonObject external_section{{"servers", servers}};++ const auto hub_stats = fincept::datahub::DataHub::instance().stats();+ int subscriber_total = 0;+ qint64 publishes_total = 0;+ for (const auto& s : hub_stats) {+ subscriber_total += s.subscriber_count;+ publishes_total += s.total_publishes;+ }+ QJsonObject datahub_section{+ {"topic_count", static_cast<int>(hub_stats.size())},+ {"subscriber_count", subscriber_total},+ {"total_publishes", publishes_total},+ };++ return ToolResult::ok_data(QJsonObject{+ {"internal", internal_section},+ {"external", external_section},+ {"datahub", datahub_section},+ {"timestamp", QDateTime::currentDateTime().toString(Qt::ISODate)},+ });+ };+ tools.push_back(std::move(t));+ }++ LOG_INFO(TAG, QString("Defined %1 meta tools").arg(tools.size()));+ return tools;+}++} // namespace fincept::mcp::toolsdiff --git a/fincept-qt/src/mcp/tools/MetaTools.h b/fincept-qt/src/mcp/tools/MetaTools.hnew file mode 100644index 000000000..f8b773542--- /dev/null+++ b/fincept-qt/src/mcp/tools/MetaTools.h@@ -0,0 +1,29 @@+#pragma once+// MetaTools.h — Self-introspection MCP tools (Phase 6).+//+// Three always-available tools the LLM can call to explore the catalogue:+//+// tool.list(category?, search?, limit?)+// One-line summary per matching tool (no schemas). Cheap to embed in+// prompts. Lets the LLM discover specialised tools without the full+// 237-tool catalogue ballooning every request.+//+// tool.describe(name)+// Full schema + description for a single tool. Called when the LLM has+// identified which tool it wants and now needs the parameter shape.+//+// mcp.health+// Snapshot of the MCP system: internal tool count by category, external+// server statuses + last errors, DataHub topic count. Lets agents+// self-diagnose ("why is my tool failing?") and surfaces ops state to+// debug consoles without requiring access to the desktop UI.++#include "mcp/McpTypes.h"++#include <vector>++namespace fincept::mcp::tools {++std::vector<ToolDef> get_meta_tools();++} // namespace fincept::mcp::toolsdiff --git a/fincept-qt/src/mcp/tools/NavigationTools.cpp b/fincept-qt/src/mcp/tools/NavigationTools.cppindex 4ff134a58..7fa435aca 100644--- a/fincept-qt/src/mcp/tools/NavigationTools.cpp+++ b/fincept-qt/src/mcp/tools/NavigationTools.cpp@@ -2,10 +2,17 @@#include "mcp/tools/NavigationTools.h"+#include "app/DockScreenRouter.h"+#include "app/MainWindow.h"#include "core/events/EventBus.h"#include "core/logging/Logger.h"+#include "mcp/ToolSchemaBuilder.h"+#include "mcp/tools/ThreadHelper.h"+#include <QApplication>+#include <QPointer>#include <QVariantMap>+#include <QWidget>#include <algorithm>@@ -13,71 +20,51 @@ namespace fincept::mcp::tools {static constexpr const char* TAG = "NavTools";-struct TabEntry {- const char* name;- const char* display_name;- int index;-};--// Indices must match ScreenRouter screen IDs used in MainWindow-static const TabEntry TAB_MAP[] = {- {"dashboard", "Dashboard", 0},- {"markets", "Markets", 1},- {"crypto_trading", "Crypto Trading", 2},- {"news", "News", 3},- {"watchlist", "Watchlist", 4},- {"dbnomics", "DBnomics", 5},- {"surface_analytics", "Surface Analytics", 6},- {"notes", "Notes", 7},- {"report_builder", "Report Builder", 8},- {"profile", "Profile", 9},- {"settings", "Settings", 10},- {"about", "About", 11},- {"support", "Support", 12},- {"ai_chat", "AI Chat", 13},- {"agent_config", "Agent Studio", 14},- {"economics", "Economics", 15},- {"geopolitics", "Geopolitics", 16},- {"quantlib", "QuantLib Suite", 17},- {"algo_trading", "Algo Trading", 18},- {"backtesting", "Backtesting", 19},- {"node_editor", "Node Editor", 20},- {"code_editor", "Code Editor", 21},- {"ma_analytics", "M&A Analytics", 22},- {"data_sources", "Data Sources", 23},- {"gov_data", "Government Data", 24},- {"forum", "Forum", 25},- {"docs", "Documentation", 26},-};--static constexpr int TAB_COUNT = static_cast<int>(sizeof(TAB_MAP) / sizeof(TAB_MAP[0]));--static int find_tab_index(const QString& name) {- QString lower = name.toLower();-- // Exact match on id- for (int i = 0; i < TAB_COUNT; ++i) {- if (lower == TAB_MAP[i].name)- return TAB_MAP[i].index;+// ── Live router lookup ──────────────────────────────────────────────────────+// MCP tool handlers run on a worker thread. QApplication's widget tree must+// be queried from the main thread. We marshal via run_on_target_thread_sync+// (qApp lives on the main thread) and pick the active or primary MainWindow.+namespace {++// Must be called on the main thread.+fincept::DockScreenRouter* find_active_router_main_thread() {+ // Prefer the focused window — that's where the user just typed.+ if (auto* active = QApplication::activeWindow()) {+ if (auto* mw = qobject_cast<fincept::MainWindow*>(active))+ return mw->dock_router();}-- // Partial match on display name- for (int i = 0; i < TAB_COUNT; ++i) {- if (QString(TAB_MAP[i].display_name).toLower().contains(lower))- return TAB_MAP[i].index;+ // Fall back to the primary window (window_id == 0). Multi-window mode is+ // possible; we deliberately don't pick "any" MainWindow because that+ // would surprise users running two terminals.+ const auto top_widgets = QApplication::topLevelWidgets();+ for (QWidget* w : top_widgets) {+ if (auto* mw = qobject_cast<fincept::MainWindow*>(w)) {+ if (mw->window_id() == 0)+ return mw->dock_router();+ }}-- return -1;+ return nullptr;}-static QString find_tab_name(int idx) {- for (int i = 0; i < TAB_COUNT; ++i) {- if (TAB_MAP[i].index == idx)- return TAB_MAP[i].name;- }- return {};+struct ScreenSnapshot {+ QStringList ids;+ QString current_id;+};++ScreenSnapshot snapshot_screens() {+ ScreenSnapshot snap;+ detail::run_on_target_thread_sync(qApp, [&]() {+ if (auto* router = find_active_router_main_thread()) {+ snap.ids = router->all_screen_ids();+ snap.current_id = router->current_screen_id();+ }+ });+ std::sort(snap.ids.begin(), snap.ids.end());+ return snap;}+} // anonymous namespace+std::vector<ToolDef> get_navigation_tools() {std::vector<ToolDef> tools;@@ -85,38 +72,57 @@ std::vector<ToolDef> get_navigation_tools() {{ToolDef t;t.name = "navigate_to_tab";- t.description = "Navigate to a specific terminal screen by name. "- "Available screens: dashboard, markets, news, watchlist, crypto_trading, "- "dbnomics, surface_analytics, notes, report_builder, profile, settings, "- "about, support, ai_chat, agent_config, economics, geopolitics, quantlib, "- "algo_trading, backtesting, node_editor, code_editor, ma_analytics, data_sources, "- "gov_data, forum, docs.";+ t.description = "Navigate to a specific terminal screen by id. "+ "Use list_tabs to see the live registry of available "+ "screen ids — the set is determined at runtime by "+ "DockScreenRouter, not hardcoded.";t.category = "navigation";- t.input_schema.properties =- QJsonObject{{"tab", QJsonObject{{"type", "string"}, {"description", "Screen name to navigate to"}}}};- t.input_schema.required = {"tab"};+ t.input_schema = ToolSchemaBuilder()+ .string("tab", "Screen id to navigate to (use list_tabs to discover live ids)")+ .required()+ .length(1, 64)+ .build();t.handler = [](const QJsonObject& args) -> ToolResult {- QString tab = args["tab"].toString();+ const QString tab = args["tab"].toString().trimmed();if (tab.isEmpty())return ToolResult::fail("Missing 'tab' parameter");- int idx = find_tab_index(tab);- if (idx < 0) {- QString valid;- for (int i = 0; i < TAB_COUNT; ++i) {- if (!valid.isEmpty())- valid += ", ";- valid += TAB_MAP[i].name;+ auto snap = snapshot_screens();+ if (snap.ids.isEmpty())+ return ToolResult::fail("No active terminal window — DockScreenRouter unavailable");++ // Resolve: exact id, then case-insensitive id, then first id that+ // contains the query as substring (lets the LLM say "news" and+ // get "news" or "ai_chat" and get "ai_chat" without remembering+ // exact ids). Stricter than the previous TAB_MAP partial-match+ // because we go off the live registry, no display-name aliases.+ QString resolved;+ for (const auto& id : snap.ids) {+ if (id == tab) { resolved = id; break; }+ }+ if (resolved.isEmpty()) {+ for (const auto& id : snap.ids) {+ if (id.compare(tab, Qt::CaseInsensitive) == 0) { resolved = id; break; }+ }+ }+ if (resolved.isEmpty()) {+ const QString tab_lower = tab.toLower();+ for (const auto& id : snap.ids) {+ if (id.toLower().contains(tab_lower)) { resolved = id; break; }}- return ToolResult::fail("Unknown tab '" + tab + "'. Valid tabs: " + valid);}- // Publish event — NavigationBar listens for this- EventBus::instance().publish("nav.switch_screen",- QVariantMap{{"screen_id", find_tab_name(idx)}, {"tab_index", idx}});+ if (resolved.isEmpty()) {+ return ToolResult::fail("Unknown tab '" + tab + "'. Valid ids: " + snap.ids.join(", "));+ }++ // Hand off to MainWindow's existing nav.switch_screen subscriber.+ // The subscriber marshals onto dock_router_'s thread, so we don't+ // duplicate that logic here.+ EventBus::instance().publish("nav.switch_screen", QVariantMap{{"screen_id", resolved}});- LOG_INFO(TAG, "Navigate to tab: " + tab);- return ToolResult::ok("Navigated to " + tab, QJsonObject{{"tab_index", idx}, {"tab", tab}});+ LOG_INFO(TAG, "Navigate to tab: " + resolved);+ return ToolResult::ok("Navigated to " + resolved, QJsonObject{{"tab", resolved}});};tools.push_back(std::move(t));}@@ -125,15 +131,23 @@ std::vector<ToolDef> get_navigation_tools() {{ToolDef t;t.name = "list_tabs";- t.description = "List all available terminal screens with their names and indices.";+ t.description = "List all available terminal screens currently registered with the active "+ "window's DockScreenRouter. Returns each id plus its human-readable title.";t.category = "navigation";t.handler = [](const QJsonObject&) -> ToolResult {+ auto snap = snapshot_screens();+ if (snap.ids.isEmpty())+ return ToolResult::fail("No active terminal window — DockScreenRouter unavailable");+QJsonArray tabs;- for (int i = 0; i < TAB_COUNT; ++i) {- tabs.append(QJsonObject{- {"name", TAB_MAP[i].name}, {"display_name", TAB_MAP[i].display_name}, {"index", TAB_MAP[i].index}});+ // title_for_id is a thread-safe static lookup (string→string map).+ for (const auto& id : snap.ids) {+ tabs.append(QJsonObject{{"id", id},+ {"title", fincept::DockScreenRouter::title_for_id(id)}});}- return ToolResult::ok_data(tabs);+ return ToolResult::ok_data(QJsonObject{{"count", tabs.size()},+ {"current", snap.current_id},+ {"tabs", tabs}});};tools.push_back(std::move(t));}@@ -142,11 +156,17 @@ std::vector<ToolDef> get_navigation_tools() {{ToolDef t;t.name = "get_current_tab";- t.description = "Query the currently active screen (publishes event, screen responds).";+ t.description = "Return the currently focused screen id (and its human-readable title) "+ "from the active terminal window.";t.category = "navigation";t.handler = [](const QJsonObject&) -> ToolResult {- EventBus::instance().publish("nav.get_current_screen", {});- return ToolResult::ok("Current screen query sent via event bus");+ auto snap = snapshot_screens();+ if (snap.current_id.isEmpty())+ return ToolResult::fail("No active screen — terminal may not be ready yet");++ return ToolResult::ok_data(QJsonObject{+ {"id", snap.current_id},+ {"title", fincept::DockScreenRouter::title_for_id(snap.current_id)}});};tools.push_back(std::move(t));}diff --git a/fincept-qt/src/mcp/tools/NewsTools.cpp b/fincept-qt/src/mcp/tools/NewsTools.cppindex a94034829..45c76ec9c 100644--- a/fincept-qt/src/mcp/tools/NewsTools.cpp+++ b/fincept-qt/src/mcp/tools/NewsTools.cpp@@ -4,6 +4,7 @@#include "core/events/EventBus.h"#include "core/logging/Logger.h"+#include "mcp/ToolSchemaBuilder.h"#include "mcp/tools/ThreadHelper.h"#include "services/news/NewsClusterService.h"#include "services/news/NewsMonitorService.h"@@ -150,16 +151,27 @@ std::vector<ToolDef> get_news_tools() {"Time ranges: 1H, 6H, 24H (default), 48H, 7D, 30D. ""Sentiment: ALL (default), BULLISH, BEARISH, NEUTRAL.";t.category = "news";- t.input_schema.properties = QJsonObject{- {"category", QJsonObject{{"type", "string"}, {"description", "Category filter (default: ALL)"}}},- {"time_range",- QJsonObject{{"type", "string"}, {"description", "Time window: 1H, 6H, 24H, 48H, 7D, 30D"}}},- {"sentiment", QJsonObject{{"type", "string"}, {"description", "BULLISH, BEARISH, NEUTRAL, or ALL"}}},- {"query", QJsonObject{{"type", "string"},- {"description", "Keyword search across headline, summary, source, tickers"}}},- {"limit", QJsonObject{{"type", "integer"}, {"description", "Max articles (default: 20, max: 100)"}}},- {"force", QJsonObject{{"type", "boolean"}, {"description", "Force refresh ignoring cache"}}}};+ t.input_schema = ToolSchemaBuilder()+ .string("category", "Category filter")+ .default_str("ALL")+ .enums({"ALL", "MARKETS", "MKT", "EARNINGS", "EARN", "ECONOMIC", "ECO",+ "CRYPTO", "CRPT", "GEOPOLITICS", "GEO", "ENERGY", "NRG",+ "DEFENSE", "DEF", "TECH", "REGULATORY"})+ .string("time_range", "Time window")+ .default_str("24H")+ .enums({"1H", "6H", "24H", "48H", "7D", "30D"})+ .string("sentiment", "Sentiment filter")+ .default_str("ALL")+ .enums({"ALL", "BULLISH", "BEARISH", "NEUTRAL"})+ .string("query", "Keyword search across headline, summary, source, tickers")+ .integer("limit", "Max articles")+ .default_int(20).between(1, 100)+ .boolean("force", "Force refresh ignoring cache")+ .default_bool(false)+ .build();t.handler = [](const QJsonObject& args) -> ToolResult {+ // Defaults are now injected by the validator; the .toString(...)+ // fallback args remain harmless but unnecessary.QString category = args["category"].toString("ALL");QString time_range = args["time_range"].toString("24H");QString sentiment = args["sentiment"].toString("ALL");diff --git a/fincept-qt/src/mcp/tools/PaperTradingTools.cpp b/fincept-qt/src/mcp/tools/PaperTradingTools.cppindex 9e25aeb98..e9514b36f 100644--- a/fincept-qt/src/mcp/tools/PaperTradingTools.cpp+++ b/fincept-qt/src/mcp/tools/PaperTradingTools.cpp@@ -3,6 +3,7 @@#include "mcp/tools/PaperTradingTools.h"#include "core/logging/Logger.h"+#include "mcp/ToolSchemaBuilder.h"#include "trading/PaperTrading.h"namespace fincept::mcp::tools {@@ -114,18 +115,25 @@ std::vector<ToolDef> get_paper_trading_tools() {{ToolDef t;t.name = "pt_place_order";- t.description = "Place a paper trading order. Supports market, limit, stop, stop_limit order types.";+ t.description = "Place a paper trading order. Side must be buy/sell; "+ "order_type one of market/limit/stop/stop_limit. Quantity > 0.";t.category = "paper-trading";- t.input_schema.properties = QJsonObject{- {"portfolio_id", QJsonObject{{"type", "string"}, {"description", "Portfolio ID"}}},- {"symbol", QJsonObject{{"type", "string"}, {"description", "Trading symbol (e.g. BTC/USDT)"}}},- {"side", QJsonObject{{"type", "string"}, {"description", "buy or sell"}}},- {"order_type", QJsonObject{{"type", "string"}, {"description", "market, limit, stop, stop_limit"}}},- {"quantity", QJsonObject{{"type", "number"}, {"description", "Order quantity"}}},- {"price", QJsonObject{{"type", "number"}, {"description", "Limit price (required for limit/stop_limit)"}}},- {"stop_price", QJsonObject{{"type", "number"}, {"description", "Stop trigger price"}}},- {"reduce_only", QJsonObject{{"type", "boolean"}, {"description", "Only reduce existing position"}}}};- t.input_schema.required = {"portfolio_id", "symbol", "side", "quantity"};+ // Phase 6.3: even paper trades should confirm — the LLM's intent may+ // not match the user's. Real-broker tools (when added) will use+ // ExplicitConfirm + is_destructive=true.+ t.auth_required = AuthLevel::Authenticated;+ t.is_destructive = true;+ t.input_schema = ToolSchemaBuilder()+ .string("portfolio_id", "Portfolio ID").required()+ .string("symbol", "Trading symbol (e.g. BTC/USDT)").required().length(1, 32)+ .string("side", "Order side").required().enums({"buy", "sell"})+ .string("order_type", "Order type").default_str("market")+ .enums({"market", "limit", "stop", "stop_limit"})+ .number("quantity", "Order quantity (must be > 0)").required().min(0.0)+ .number("price", "Limit price (required for limit/stop_limit orders)")+ .number("stop_price", "Stop trigger price (required for stop/stop_limit)")+ .boolean("reduce_only", "Only reduce existing position").default_bool(false)+ .build();t.handler = [](const QJsonObject& args) -> ToolResult {QString portfolio_id = args["portfolio_id"].toString();QString symbol = args["symbol"].toString();diff --git a/fincept-qt/src/mcp/tools/PortfolioManagementTools.cpp b/fincept-qt/src/mcp/tools/PortfolioManagementTools.cppdeleted file mode 100644index c6a866836..000000000--- a/fincept-qt/src/mcp/tools/PortfolioManagementTools.cpp+++ /dev/null@@ -1,363 +0,0 @@-// PortfolioManagementTools.cpp — Full portfolio CRUD MCP tools-// Covers: portfolios, assets, transactions, snapshots via PortfolioRepository--#include "mcp/tools/PortfolioManagementTools.h"--#include "core/logging/Logger.h"-#include "storage/repositories/PortfolioRepository.h"--namespace fincept::mcp::tools {--static constexpr const char* TAG = "PortfolioMgmtTools";--std::vector<ToolDef> get_portfolio_management_tools() {- std::vector<ToolDef> tools;-- // ── list_portfolios ─────────────────────────────────────────────────- {- ToolDef t;- t.name = "list_portfolios";- t.description = "List all investment portfolios.";- t.category = "portfolio";- t.handler = [](const QJsonObject&) -> ToolResult {- auto r = PortfolioRepository::instance().list_portfolios();- if (r.is_err())- return ToolResult::fail("Failed to list portfolios: " + QString::fromStdString(r.error()));-- QJsonArray arr;- for (const auto& p : r.value()) {- arr.append(QJsonObject{{"id", p.id},- {"name", p.name},- {"owner", p.owner},- {"currency", p.currency},- {"description", p.description},- {"created_at", p.created_at},- {"updated_at", p.updated_at}});- }- return ToolResult::ok_data(arr);- };- tools.push_back(std::move(t));- }-- // ── get_portfolio ───────────────────────────────────────────────────- {- ToolDef t;- t.name = "get_portfolio";- t.description = "Get a single portfolio by ID.";- t.category = "portfolio";- t.input_schema.properties =- QJsonObject{{"portfolio_id", QJsonObject{{"type", "string"}, {"description", "Portfolio ID"}}}};- t.input_schema.required = {"portfolio_id"};- t.handler = [](const QJsonObject& args) -> ToolResult {- QString id = args["portfolio_id"].toString().trimmed();- if (id.isEmpty())- return ToolResult::fail("Missing 'portfolio_id'");-- auto r = PortfolioRepository::instance().get_portfolio(id);- if (r.is_err())- return ToolResult::fail("Portfolio not found: " + QString::fromStdString(r.error()));-- const auto& p = r.value();- return ToolResult::ok_data(QJsonObject{{"id", p.id},- {"name", p.name},- {"owner", p.owner},- {"currency", p.currency},- {"description", p.description},- {"created_at", p.created_at},- {"updated_at", p.updated_at}});- };- tools.push_back(std::move(t));- }-- // ── create_portfolio ────────────────────────────────────────────────- {- ToolDef t;- t.name = "create_portfolio";- t.description = "Create a new investment portfolio.";- t.category = "portfolio";- t.input_schema.properties =- QJsonObject{{"name", QJsonObject{{"type", "string"}, {"description", "Portfolio name"}}},- {"owner", QJsonObject{{"type", "string"}, {"description", "Owner name"}}},- {"currency", QJsonObject{{"type", "string"}, {"description", "Currency code (default: USD)"}}},- {"description", QJsonObject{{"type", "string"}, {"description", "Optional description"}}}};- t.input_schema.required = {"name", "owner"};- t.handler = [](const QJsonObject& args) -> ToolResult {- QString name = args["name"].toString().trimmed();- QString owner = args["owner"].toString().trimmed();- if (name.isEmpty() || owner.isEmpty())- return ToolResult::fail("Missing 'name' or 'owner'");-- QString currency = args["currency"].toString("USD");- QString description = args["description"].toString();-- auto r = PortfolioRepository::instance().create_portfolio(name, owner, currency, description);- if (r.is_err())- return ToolResult::fail("Failed to create portfolio: " + QString::fromStdString(r.error()));-- LOG_INFO(TAG, "Created portfolio: " + name);- return ToolResult::ok("Portfolio created",- QJsonObject{{"id", r.value()}, {"name", name}, {"currency", currency}});- };- tools.push_back(std::move(t));- }-- // ── delete_portfolio ────────────────────────────────────────────────- {- ToolDef t;- t.name = "delete_portfolio";- t.description = "Delete a portfolio and all its assets and transactions.";- t.category = "portfolio";- t.input_schema.properties =- QJsonObject{{"portfolio_id", QJsonObject{{"type", "string"}, {"description", "Portfolio ID"}}}};- t.input_schema.required = {"portfolio_id"};- t.handler = [](const QJsonObject& args) -> ToolResult {- QString id = args["portfolio_id"].toString().trimmed();- if (id.isEmpty())- return ToolResult::fail("Missing 'portfolio_id'");-- auto r = PortfolioRepository::instance().delete_portfolio(id);- if (r.is_err())- return ToolResult::fail("Failed to delete portfolio: " + QString::fromStdString(r.error()));-- LOG_INFO(TAG, "Deleted portfolio: " + id);- return ToolResult::ok("Portfolio deleted", QJsonObject{{"id", id}});- };- tools.push_back(std::move(t));- }-- // ── get_portfolio_assets ────────────────────────────────────────────- {- ToolDef t;- t.name = "get_portfolio_assets";- t.description = "Get all asset holdings for a portfolio.";- t.category = "portfolio";- t.input_schema.properties =- QJsonObject{{"portfolio_id", QJsonObject{{"type", "string"}, {"description", "Portfolio ID"}}}};- t.input_schema.required = {"portfolio_id"};- t.handler = [](const QJsonObject& args) -> ToolResult {- QString id = args["portfolio_id"].toString().trimmed();- if (id.isEmpty())- return ToolResult::fail("Missing 'portfolio_id'");-- auto r = PortfolioRepository::instance().get_assets(id);- if (r.is_err())- return ToolResult::fail("Failed to load assets: " + QString::fromStdString(r.error()));-- QJsonArray arr;- for (const auto& a : r.value()) {- arr.append(QJsonObject{{"id", a.id},- {"symbol", a.symbol},- {"quantity", a.quantity},- {"avg_buy_price", a.avg_buy_price},- {"first_purchase_date", a.first_purchase_date},- {"last_updated", a.last_updated}});- }- return ToolResult::ok_data(arr);- };- tools.push_back(std::move(t));- }-- // ── add_portfolio_asset ─────────────────────────────────────────────- {- ToolDef t;- t.name = "add_portfolio_asset";- t.description = "Add a new asset/holding to a portfolio.";- t.category = "portfolio";- t.input_schema.properties = QJsonObject{- {"portfolio_id", QJsonObject{{"type", "string"}, {"description", "Portfolio ID"}}},- {"symbol", QJsonObject{{"type", "string"}, {"description", "Ticker symbol (e.g. AAPL)"}}},- {"quantity", QJsonObject{{"type", "number"}, {"description", "Number of shares/units"}}},- {"price", QJsonObject{{"type", "number"}, {"description", "Purchase price per unit"}}},- {"date", QJsonObject{{"type", "string"}, {"description", "Purchase date YYYY-MM-DD (optional)"}}}};- t.input_schema.required = {"portfolio_id", "symbol", "quantity", "price"};- t.handler = [](const QJsonObject& args) -> ToolResult {- QString portfolio_id = args["portfolio_id"].toString().trimmed();- QString symbol = args["symbol"].toString().trimmed().toUpper();- double quantity = args["quantity"].toDouble(0.0);- double price = args["price"].toDouble(0.0);- QString date = args["date"].toString();-- if (portfolio_id.isEmpty() || symbol.isEmpty() || quantity <= 0 || price <= 0)- return ToolResult::fail("Missing or invalid: portfolio_id, symbol, quantity (>0), price (>0)");-- auto r = PortfolioRepository::instance().add_asset(portfolio_id, symbol, quantity, price, date);- if (r.is_err())- return ToolResult::fail("Failed to add asset: " + QString::fromStdString(r.error()));-- LOG_INFO(TAG, QString("Added asset %1 x%2 to portfolio %3").arg(symbol).arg(quantity).arg(portfolio_id));- return ToolResult::ok("Asset added", QJsonObject{{"id", static_cast<int>(r.value())},- {"symbol", symbol},- {"quantity", quantity},- {"price", price}});- };- tools.push_back(std::move(t));- }-- // ── remove_portfolio_asset ──────────────────────────────────────────- {- ToolDef t;- t.name = "remove_portfolio_asset";- t.description = "Remove an asset/holding from a portfolio by symbol.";- t.category = "portfolio";- t.input_schema.properties =- QJsonObject{{"portfolio_id", QJsonObject{{"type", "string"}, {"description", "Portfolio ID"}}},- {"symbol", QJsonObject{{"type", "string"}, {"description", "Ticker symbol to remove"}}}};- t.input_schema.required = {"portfolio_id", "symbol"};- t.handler = [](const QJsonObject& args) -> ToolResult {- QString portfolio_id = args["portfolio_id"].toString().trimmed();- QString symbol = args["symbol"].toString().trimmed().toUpper();- if (portfolio_id.isEmpty() || symbol.isEmpty())- return ToolResult::fail("Missing 'portfolio_id' or 'symbol'");-- auto r = PortfolioRepository::instance().remove_asset(portfolio_id, symbol);- if (r.is_err())- return ToolResult::fail("Failed to remove asset: " + QString::fromStdString(r.error()));-- return ToolResult::ok("Asset removed", QJsonObject{{"symbol", symbol}});- };- tools.push_back(std::move(t));- }-- // ── get_transactions ────────────────────────────────────────────────- {- ToolDef t;- t.name = "get_transactions";- t.description = "Get transaction history for a portfolio.";- t.category = "portfolio";- t.input_schema.properties =- QJsonObject{{"portfolio_id", QJsonObject{{"type", "string"}, {"description", "Portfolio ID"}}},- {"limit", QJsonObject{{"type", "integer"}, {"description", "Max rows (default: 50)"}}}};- t.input_schema.required = {"portfolio_id"};- t.handler = [](const QJsonObject& args) -> ToolResult {- QString id = args["portfolio_id"].toString().trimmed();- if (id.isEmpty())- return ToolResult::fail("Missing 'portfolio_id'");-- int limit = args["limit"].toInt(50);- auto r = PortfolioRepository::instance().get_transactions(id, limit);- if (r.is_err())- return ToolResult::fail("Failed to load transactions: " + QString::fromStdString(r.error()));-- QJsonArray arr;- for (const auto& tx : r.value()) {- arr.append(QJsonObject{{"id", tx.id},- {"symbol", tx.symbol},- {"type", tx.transaction_type},- {"quantity", tx.quantity},- {"price", tx.price},- {"total_value", tx.total_value},- {"date", tx.transaction_date},- {"notes", tx.notes},- {"created_at", tx.created_at}});- }- return ToolResult::ok_data(arr);- };- tools.push_back(std::move(t));- }-- // ── add_transaction ─────────────────────────────────────────────────- {- ToolDef t;- t.name = "add_transaction";- t.description = "Record a transaction (BUY, SELL, DIVIDEND, SPLIT) in a portfolio.";- t.category = "portfolio";- t.input_schema.properties =- QJsonObject{{"portfolio_id", QJsonObject{{"type", "string"}, {"description", "Portfolio ID"}}},- {"symbol", QJsonObject{{"type", "string"}, {"description", "Ticker symbol"}}},- {"type", QJsonObject{{"type", "string"}, {"description", "BUY, SELL, DIVIDEND, SPLIT"}}},- {"quantity", QJsonObject{{"type", "number"}, {"description", "Number of shares/units"}}},- {"price", QJsonObject{{"type", "number"}, {"description", "Price per unit"}}},- {"date", QJsonObject{{"type", "string"}, {"description", "Transaction date YYYY-MM-DD"}}},- {"notes", QJsonObject{{"type", "string"}, {"description", "Optional notes"}}}};- t.input_schema.required = {"portfolio_id", "symbol", "type", "quantity", "price", "date"};- t.handler = [](const QJsonObject& args) -> ToolResult {- QString portfolio_id = args["portfolio_id"].toString().trimmed();- QString symbol = args["symbol"].toString().trimmed().toUpper();- QString type = args["type"].toString().trimmed().toUpper();- double quantity = args["quantity"].toDouble(0.0);- double price = args["price"].toDouble(0.0);- QString date = args["date"].toString().trimmed();- QString notes = args["notes"].toString();-- if (portfolio_id.isEmpty() || symbol.isEmpty() || type.isEmpty() || quantity <= 0 || date.isEmpty())- return ToolResult::fail("Missing required: portfolio_id, symbol, type, quantity (>0), date");-- static const QStringList valid_types{"BUY", "SELL", "DIVIDEND", "SPLIT"};- if (!valid_types.contains(type))- return ToolResult::fail("Invalid type. Must be BUY, SELL, DIVIDEND, or SPLIT");-- auto r = PortfolioRepository::instance().add_transaction(portfolio_id, symbol, type, quantity, price, date,- notes);- if (r.is_err())- return ToolResult::fail("Failed to add transaction: " + QString::fromStdString(r.error()));-- LOG_INFO(- TAG,- QString("Transaction %1 %2 x%3 in portfolio %4").arg(type, symbol).arg(quantity).arg(portfolio_id));- return ToolResult::ok("Transaction recorded",- QJsonObject{{"id", r.value()}, {"symbol", symbol}, {"type", type}});- };- tools.push_back(std::move(t));- }-- // ── delete_transaction ──────────────────────────────────────────────- {- ToolDef t;- t.name = "delete_transaction";- t.description = "Delete a transaction by ID.";- t.category = "portfolio";- t.input_schema.properties =- QJsonObject{{"transaction_id", QJsonObject{{"type", "string"}, {"description", "Transaction ID"}}}};- t.input_schema.required = {"transaction_id"};- t.handler = [](const QJsonObject& args) -> ToolResult {- QString id = args["transaction_id"].toString().trimmed();- if (id.isEmpty())- return ToolResult::fail("Missing 'transaction_id'");-- auto r = PortfolioRepository::instance().delete_transaction(id);- if (r.is_err())- return ToolResult::fail("Failed to delete transaction: " + QString::fromStdString(r.error()));-- return ToolResult::ok("Transaction deleted", QJsonObject{{"id", id}});- };- tools.push_back(std::move(t));- }-- // ── get_portfolio_snapshots ─────────────────────────────────────────- {- ToolDef t;- t.name = "get_portfolio_snapshots";- t.description = "Get historical performance snapshots for a portfolio.";- t.category = "portfolio";- t.input_schema.properties =- QJsonObject{{"portfolio_id", QJsonObject{{"type", "string"}, {"description", "Portfolio ID"}}},- {"days", QJsonObject{{"type", "integer"}, {"description", "Days of history (default: 365)"}}}};- t.input_schema.required = {"portfolio_id"};- t.handler = [](const QJsonObject& args) -> ToolResult {- QString id = args["portfolio_id"].toString().trimmed();- if (id.isEmpty())- return ToolResult::fail("Missing 'portfolio_id'");-- int days = args["days"].toInt(365);- auto r = PortfolioRepository::instance().get_snapshots(id, days);- if (r.is_err())- return ToolResult::fail("Failed to load snapshots: " + QString::fromStdString(r.error()));-- QJsonArray arr;- for (const auto& s : r.value()) {- arr.append(QJsonObject{{"id", s.id},- {"total_value", s.total_value},- {"total_cost_basis", s.total_cost_basis},- {"total_pnl", s.total_pnl},- {"total_pnl_percent", s.total_pnl_percent},- {"date", s.snapshot_date}});- }- return ToolResult::ok_data(arr);- };- tools.push_back(std::move(t));- }-- return tools;-}--} // namespace fincept::mcp::toolsdiff --git a/fincept-qt/src/mcp/tools/PortfolioManagementTools.h b/fincept-qt/src/mcp/tools/PortfolioManagementTools.hdeleted file mode 100644index 3b70ca96b..000000000--- a/fincept-qt/src/mcp/tools/PortfolioManagementTools.h+++ /dev/null@@ -1,8 +0,0 @@-#pragma once-#include "mcp/McpTypes.h"--#include <vector>--namespace fincept::mcp::tools {-std::vector<ToolDef> get_portfolio_management_tools();-} // namespace fincept::mcp::toolsdiff --git a/fincept-qt/src/mcp/tools/PortfolioToolsExt.cpp b/fincept-qt/src/mcp/tools/PortfolioToolsExt.cppdeleted file mode 100644index 6c058a595..000000000--- a/fincept-qt/src/mcp/tools/PortfolioToolsExt.cpp+++ /dev/null@@ -1,131 +0,0 @@-// PortfolioToolsExt.cpp — Investment portfolio holdings MCP tools (Qt port)-// Uses PortfolioHoldingsRepository which manages a single flat list of holdings.--#include "mcp/tools/PortfolioToolsExt.h"--#include "core/logging/Logger.h"-#include "storage/repositories/PortfolioHoldingsRepository.h"--namespace fincept::mcp::tools {--static constexpr const char* TAG = "PortfolioExtTools";--std::vector<ToolDef> get_investment_portfolio_tools() {- std::vector<ToolDef> tools;-- // ── get_holdings ───────────────────────────────────────────────────- {- ToolDef t;- t.name = "get_holdings";- t.description = "Get all active investment portfolio holdings (symbol, shares, avg cost).";- t.category = "portfolio";- t.handler = [](const QJsonObject&) -> ToolResult {- auto result = PortfolioHoldingsRepository::instance().get_active();- if (result.is_err())- return ToolResult::fail("Failed to load holdings: " + QString::fromStdString(result.error()));-- QJsonArray arr;- for (const auto& h : result.value()) {- arr.append(QJsonObject{{"id", h.id},- {"symbol", h.symbol},- {"name", h.name},- {"shares", h.shares},- {"avg_cost", h.avg_cost},- {"added_at", h.added_at},- {"updated_at", h.updated_at}});- }- return ToolResult::ok_data(arr);- };- tools.push_back(std::move(t));- }-- // ── add_holding ────────────────────────────────────────────────────- {- ToolDef t;- t.name = "add_holding";- t.description = "Add or increase a position in the investment portfolio.";- t.category = "portfolio";- t.input_schema.properties =- QJsonObject{{"symbol", QJsonObject{{"type", "string"}, {"description", "Ticker symbol (e.g. AAPL)"}}},- {"shares", QJsonObject{{"type", "number"}, {"description", "Number of shares/units"}}},- {"avg_cost", QJsonObject{{"type", "number"}, {"description", "Average cost per share/unit"}}},- {"name", QJsonObject{{"type", "string"}, {"description", "Company/asset name (optional)"}}}};- t.input_schema.required = {"symbol", "shares", "avg_cost"};- t.handler = [](const QJsonObject& args) -> ToolResult {- QString symbol = args["symbol"].toString().trimmed().toUpper();- double shares = args["shares"].toDouble(0.0);- double avg_cost = args["avg_cost"].toDouble(0.0);- QString name = args["name"].toString();-- if (symbol.isEmpty() || shares <= 0 || avg_cost <= 0)- return ToolResult::fail("Missing or invalid: symbol, shares (>0), avg_cost (>0)");-- auto r = PortfolioHoldingsRepository::instance().add(symbol, shares, avg_cost, name);- if (r.is_err())- return ToolResult::fail("Failed to add holding: " + QString::fromStdString(r.error()));-- LOG_INFO(TAG, QString("Added holding: %1 x%2 @ %3").arg(symbol).arg(shares).arg(avg_cost));-- return ToolResult::ok("Holding added", QJsonObject{{"id", static_cast<int>(r.value())},- {"symbol", symbol},- {"shares", shares},- {"avg_cost", avg_cost}});- };- tools.push_back(std::move(t));- }-- // ── update_holding ─────────────────────────────────────────────────- {- ToolDef t;- t.name = "update_holding";- t.description = "Update shares and average cost for an existing holding by its ID.";- t.category = "portfolio";- t.input_schema.properties =- QJsonObject{{"id", QJsonObject{{"type", "integer"}, {"description", "Holding ID"}}},- {"shares", QJsonObject{{"type", "number"}, {"description", "Updated share count"}}},- {"avg_cost", QJsonObject{{"type", "number"}, {"description", "Updated average cost"}}}};- t.input_schema.required = {"id", "shares", "avg_cost"};- t.handler = [](const QJsonObject& args) -> ToolResult {- int id = args["id"].toInt(-1);- double shares = args["shares"].toDouble(0.0);- double avg_cost = args["avg_cost"].toDouble(0.0);-- if (id < 0 || shares <= 0 || avg_cost <= 0)- return ToolResult::fail("Missing or invalid: id, shares (>0), avg_cost (>0)");-- auto r = PortfolioHoldingsRepository::instance().update(id, shares, avg_cost);- if (r.is_err())- return ToolResult::fail("Failed to update holding: " + QString::fromStdString(r.error()));-- return ToolResult::ok("Holding updated", QJsonObject{{"id", id}});- };- tools.push_back(std::move(t));- }-- // ── remove_holding ─────────────────────────────────────────────────- {- ToolDef t;- t.name = "remove_holding";- t.description = "Remove a holding from the portfolio by its ID.";- t.category = "portfolio";- t.input_schema.properties =- QJsonObject{{"id", QJsonObject{{"type", "integer"}, {"description", "Holding ID"}}}};- t.input_schema.required = {"id"};- t.handler = [](const QJsonObject& args) -> ToolResult {- int id = args["id"].toInt(-1);- if (id < 0)- return ToolResult::fail("Missing or invalid 'id'");-- auto r = PortfolioHoldingsRepository::instance().remove(id);- if (r.is_err())- return ToolResult::fail("Failed to remove holding: " + QString::fromStdString(r.error()));-- return ToolResult::ok("Holding removed", QJsonObject{{"id", id}});- };- tools.push_back(std::move(t));- }-- return tools;-}--} // namespace fincept::mcp::toolsdiff --git a/fincept-qt/src/mcp/tools/PortfolioToolsExt.h b/fincept-qt/src/mcp/tools/PortfolioToolsExt.hdeleted file mode 100644index 2e7ccd533..000000000--- a/fincept-qt/src/mcp/tools/PortfolioToolsExt.h+++ /dev/null@@ -1,8 +0,0 @@-#pragma once-#include "mcp/McpTypes.h"--#include <vector>--namespace fincept::mcp::tools {-std::vector<ToolDef> get_investment_portfolio_tools();-} // namespace fincept::mcp::toolsdiff --git a/fincept-qt/src/mcp/tools/PythonTools.cpp b/fincept-qt/src/mcp/tools/PythonTools.cppindex 131471d01..841999609 100644--- a/fincept-qt/src/mcp/tools/PythonTools.cpp+++ b/fincept-qt/src/mcp/tools/PythonTools.cpp@@ -3,13 +3,18 @@#include "mcp/tools/PythonTools.h"#include "core/logging/Logger.h"+#include "mcp/AsyncDispatch.h"+#include "mcp/ToolSchemaBuilder.h"#include "mcp/tools/ThreadHelper.h"#include "python/PythonRunner.h"#include <QDir>#include <QJsonDocument>+#include <QPromise>#include <QRegularExpression>+#include <memory>+namespace fincept::mcp::tools {static constexpr const char* TAG = "PythonTools";@@ -55,6 +60,11 @@ std::vector<ToolDef> get_python_tools() {std::vector<ToolDef> tools;// ── run_python_script ──────────────────────────────────────────────+ // Phase 4: async exemplar. Previously used run_script_sync (which+ // blocked the worker thread for the entire script run via+ // QMutex+QWaitCondition). Now the handler returns immediately; the+ // promise resolves when PythonRunner's QProcess::finished signal+ // fires. Provider's timeout watchdog covers runaway scripts.{ToolDef t;t.name = "run_python_script";@@ -63,23 +73,25 @@ std::vector<ToolDef> get_python_tools() {"list_python_scripts — do not invent or guess script names. For market data prefer ""get_quote / get_candles / edgar_* tools rather than Python scripts.";t.category = "analytics";- t.input_schema.properties = QJsonObject{- {"script",- QJsonObject{{"type", "string"},- {"description", "Script name (without .py) — must be a name returned by list_python_scripts"}}},- {"args",- QJsonObject{{"type", "array"}, {"description", "Array of string arguments to pass to the script"}}}};- t.input_schema.required = {"script"};- t.handler = [](const QJsonObject& args_obj) -> ToolResult {- QString script = args_obj["script"].toString().trimmed();- if (script.isEmpty())- return ToolResult::fail("Missing 'script'");-- // Security: validate script name — alphanumeric, underscore, hyphen only- static const QRegularExpression valid_name("^[a-zA-Z0-9_-]+$");- if (!valid_name.match(script).hasMatch())- return ToolResult::fail("Invalid script name — only alphanumeric, underscore, hyphen allowed");-+ t.input_schema = ToolSchemaBuilder()+ .string("script", "Script name (without .py) — must be returned by list_python_scripts")+ .required()+ .pattern("^[a-zA-Z0-9_-]+$")+ .length(1, 128)+ .array("args", "Array of string arguments to pass to the script",+ QJsonObject{{"type", "string"}})+ .build();+ // Python scripts can take a while; allow a generous default. Override+ // per-call via _meta.timeout_ms when Phase 6 wires that through.+ t.default_timeout_ms = 60000;+ // Phase 6.3: arbitrary script execution must be gated. Even with the+ // regex pattern check on script name, the script can read/write+ // files, hit the network, etc. Always confirm.+ t.auth_required = AuthLevel::Authenticated;+ t.is_destructive = true;+ t.async_handler = [](const QJsonObject& args_obj, ToolContext ctx,+ std::shared_ptr<QPromise<ToolResult>> promise) {+ const QString script = args_obj["script"].toString().trimmed();QStringList script_args;if (args_obj.contains("args") && args_obj["args"].isArray()) {for (const auto& a : args_obj["args"].toArray()) {@@ -90,9 +102,40 @@ std::vector<ToolDef> get_python_tools() {}}+ if (!python::PythonRunner::instance().is_available()) {+ promise->addResult(ToolResult::fail("Python is not available — run setup first"));+ promise->finish();+ return;+ }+LOG_INFO(TAG, QString("Running script: %1 with %2 args").arg(script).arg(script_args.size()));- return run_script_sync(script, script_args);+ auto* runner = &python::PythonRunner::instance();+ AsyncDispatch::callback_to_promise(+ runner, ctx, promise,+ [runner, script, script_args, ctx](auto resolve) {+ runner->run(script, script_args, [resolve, ctx](python::PythonResult result) {+ if (ctx.cancelled()) {+ resolve(ToolResult::fail("cancelled"));+ return;+ }+ if (!result.success) {+ resolve(ToolResult::fail("Script failed: " + result.error));+ return;+ }+ QString json_text = python::extract_json(result.output);+ if (json_text.isEmpty()) json_text = result.output;++ QJsonDocument doc = QJsonDocument::fromJson(json_text.toUtf8());+ if (!doc.isNull()) {+ if (doc.isObject()) resolve(ToolResult::ok_data(doc.object()));+ else if (doc.isArray()) resolve(ToolResult::ok_data(doc.array()));+ else resolve(ToolResult::ok(result.output));+ } else {+ resolve(ToolResult::ok(result.output));+ }+ });+ });};tools.push_back(std::move(t));}diff --git a/fincept-qt/src/mcp/tools/SettingsTools.cpp b/fincept-qt/src/mcp/tools/SettingsTools.cppindex 8eb058912..dec69daaf 100644--- a/fincept-qt/src/mcp/tools/SettingsTools.cpp+++ b/fincept-qt/src/mcp/tools/SettingsTools.cpp@@ -4,6 +4,7 @@#include "core/events/EventBus.h"#include "core/logging/Logger.h"+#include "mcp/ToolSchemaBuilder.h"#include "storage/repositories/LlmConfigRepository.h"#include "storage/repositories/SettingsRepository.h"@@ -45,6 +46,9 @@ std::vector<ToolDef> get_settings_tools() {t.name = "set_setting";t.description = "Set an application setting.";t.category = "settings";+ // Phase 6.3: mutates persisted state (could touch API keys / billing).+ t.auth_required = AuthLevel::Authenticated;+ t.is_destructive = true;t.input_schema.properties = QJsonObject{{"key", QJsonObject{{"type", "string"}, {"description", "Setting key"}}},{"value", QJsonObject{{"type", "string"}, {"description", "Setting value"}}},@@ -124,13 +128,17 @@ std::vector<ToolDef> get_settings_tools() {{ToolDef t;t.name = "set_active_llm";- t.description = "Set the active LLM provider.";+ t.description = "Set the active LLM provider. Must be one of the supported providers.";t.category = "settings";- t.input_schema.properties = QJsonObject{- {"provider",- QJsonObject{{"type", "string"},- {"description", "Provider name (openai, anthropic, ollama, groq, google, fincept)"}}}};- t.input_schema.required = {"provider"};+ // Phase 6.3: switching LLM provider mid-conversation is surprising;+ // requires explicit confirmation.+ t.auth_required = AuthLevel::Authenticated;+ t.is_destructive = true;+ t.input_schema = ToolSchemaBuilder()+ .string("provider", "Provider id (openai, anthropic, ollama, groq, google, fincept)")+ .required()+ .enums({"openai", "anthropic", "ollama", "groq", "google", "fincept"})+ .build();t.handler = [](const QJsonObject& args) -> ToolResult {QString provider = args["provider"].toString();if (provider.isEmpty())diff --git a/fincept-qt/src/mcp/tools/SystemTools.cpp b/fincept-qt/src/mcp/tools/SystemTools.cppindex 41fbb66db..f44bd30fd 100644--- a/fincept-qt/src/mcp/tools/SystemTools.cpp+++ b/fincept-qt/src/mcp/tools/SystemTools.cpp@@ -8,6 +8,13 @@#include "python/PythonRunner.h"#include "storage/cache/CacheManager.h"+// FINCEPT_VERSION_STRING is injected by CMake from CMAKE_PROJECT_VERSION.+// Fallback mirrors main.cpp so dev builds without the compile-definition+// still produce something parseable instead of failing to compile.+#ifndef FINCEPT_VERSION_STRING+# define FINCEPT_VERSION_STRING "0.0.0-dev"+#endif+namespace fincept::mcp::tools {std::vector<ToolDef> get_system_tools() {@@ -69,7 +76,7 @@ std::vector<ToolDef> get_system_tools() {t.category = "system";t.handler = [](const QJsonObject&) -> ToolResult {return ToolResult::ok_data(- QJsonObject{{"version", "4.0.0"},+ QJsonObject{{"version", QString::fromUtf8(FINCEPT_VERSION_STRING)},{"platform",#ifdef _WIN32"windows"diff --git a/fincept-qt/src/mcp/tools/TradingTools.cpp b/fincept-qt/src/mcp/tools/TradingTools.cppdeleted file mode 100644index 964fe0968..000000000--- a/fincept-qt/src/mcp/tools/TradingTools.cpp+++ /dev/null@@ -1,308 +0,0 @@-// TradingTools.cpp — Paper trading MCP tools (Qt port)--#include "mcp/tools/TradingTools.h"--#include "core/logging/Logger.h"-#include "trading/PaperTrading.h"--namespace fincept::mcp::tools {--static constexpr const char* TAG = "TradingTools";--std::vector<ToolDef> get_trading_tools() {- std::vector<ToolDef> tools;-- // ── pt_create_portfolio ────────────────────────────────────────────- {- ToolDef t;- t.name = "pt_create_portfolio";- t.description = "Create a paper trading portfolio with a starting balance.";- t.category = "trading";- t.input_schema.properties = QJsonObject{- {"name", QJsonObject{{"type", "string"}, {"description", "Portfolio name"}}},- {"balance", QJsonObject{{"type", "number"}, {"description", "Starting cash balance"}}},- {"currency", QJsonObject{{"type", "string"}, {"description", "Currency code (default: USD)"}}},- {"leverage", QJsonObject{{"type", "number"}, {"description", "Max leverage (default: 1.0)"}}},- {"fee_rate", QJsonObject{{"type", "number"}, {"description", "Trading fee rate (default: 0.001)"}}}};- t.input_schema.required = {"name", "balance"};- t.handler = [](const QJsonObject& args) -> ToolResult {- QString name = args["name"].toString().trimmed();- double balance = args["balance"].toDouble(0.0);- if (name.isEmpty() || balance <= 0)- return ToolResult::fail("Missing 'name' or 'balance' must be > 0");-- QString currency = args["currency"].toString("USD");- double leverage = args["leverage"].toDouble(1.0);- double fee_rate = args["fee_rate"].toDouble(0.001);-- try {- auto p = trading::pt_create_portfolio(name, balance, currency, leverage, "cross", fee_rate);- LOG_INFO(TAG, "Created paper portfolio: " + p.id);- return ToolResult::ok("Portfolio created", QJsonObject{{"id", p.id},- {"name", p.name},- {"balance", p.balance},- {"currency", p.currency},- {"leverage", p.leverage},- {"fee_rate", p.fee_rate}});- } catch (const std::exception& e) {- return ToolResult::fail(e.what());- }- };- tools.push_back(std::move(t));- }-- // ── pt_list_portfolios ─────────────────────────────────────────────- {- ToolDef t;- t.name = "pt_list_portfolios";- t.description = "List all paper trading portfolios.";- t.category = "trading";- t.handler = [](const QJsonObject&) -> ToolResult {- try {- auto portfolios = trading::pt_list_portfolios();- QJsonArray result;- for (const auto& p : portfolios) {- result.append(QJsonObject{{"id", p.id},- {"name", p.name},- {"balance", p.balance},- {"initial_balance", p.initial_balance},- {"currency", p.currency},- {"leverage", p.leverage},- {"fee_rate", p.fee_rate},- {"created_at", p.created_at}});- }- return ToolResult::ok_data(result);- } catch (const std::exception& e) {- return ToolResult::fail(e.what());- }- };- tools.push_back(std::move(t));- }-- // ── pt_get_portfolio ───────────────────────────────────────────────- {- ToolDef t;- t.name = "pt_get_portfolio";- t.description = "Get a specific paper trading portfolio by ID.";- t.category = "trading";- t.input_schema.properties =- QJsonObject{{"portfolio_id", QJsonObject{{"type", "string"}, {"description", "Portfolio ID"}}}};- t.input_schema.required = {"portfolio_id"};- t.handler = [](const QJsonObject& args) -> ToolResult {- QString id = args["portfolio_id"].toString();- if (id.isEmpty())- return ToolResult::fail("Missing 'portfolio_id'");-- try {- auto p = trading::pt_get_portfolio(id);- return ToolResult::ok_data(QJsonObject{{"id", p.id},- {"name", p.name},- {"balance", p.balance},- {"initial_balance", p.initial_balance},- {"currency", p.currency},- {"leverage", p.leverage},- {"fee_rate", p.fee_rate},- {"created_at", p.created_at}});- } catch (const std::exception& e) {- return ToolResult::fail(e.what());- }- };- tools.push_back(std::move(t));- }-- // ── pt_place_order ─────────────────────────────────────────────────- {- ToolDef t;- t.name = "pt_place_order";- t.description = "Place a paper trading order. Supports market, limit, stop, stop_limit order types.";- t.category = "trading";- t.input_schema.properties = QJsonObject{- {"portfolio_id", QJsonObject{{"type", "string"}, {"description", "Portfolio ID"}}},- {"symbol", QJsonObject{{"type", "string"}, {"description", "Trading symbol (e.g. BTC/USDT)"}}},- {"side", QJsonObject{{"type", "string"}, {"description", "buy or sell"}}},- {"order_type", QJsonObject{{"type", "string"}, {"description", "market, limit, stop, stop_limit"}}},- {"quantity", QJsonObject{{"type", "number"}, {"description", "Order quantity"}}},- {"price", QJsonObject{{"type", "number"}, {"description", "Limit price (required for limit/stop_limit)"}}},- {"stop_price", QJsonObject{{"type", "number"}, {"description", "Stop trigger price"}}},- {"reduce_only", QJsonObject{{"type", "boolean"}, {"description", "Only reduce existing position"}}}};- t.input_schema.required = {"portfolio_id", "symbol", "side", "quantity"};- t.handler = [](const QJsonObject& args) -> ToolResult {- QString portfolio_id = args["portfolio_id"].toString();- QString symbol = args["symbol"].toString();- QString side = args["side"].toString();- QString order_type = args["order_type"].toString("market");- double quantity = args["quantity"].toDouble(0.0);- bool reduce_only = args["reduce_only"].toBool(false);-- if (portfolio_id.isEmpty() || symbol.isEmpty() || side.isEmpty() || quantity <= 0)- return ToolResult::fail("Missing required: portfolio_id, symbol, side, quantity (>0)");-- std::optional<double> price;- if (args.contains("price") && args["price"].isDouble())- price = args["price"].toDouble();-- std::optional<double> stop_price;- if (args.contains("stop_price") && args["stop_price"].isDouble())- stop_price = args["stop_price"].toDouble();-- try {- auto order = trading::pt_place_order(portfolio_id, symbol, side, order_type, quantity, price,- stop_price, reduce_only);-- LOG_INFO(TAG,- QString("Paper order placed: %1 %2 %.4f %3").arg(side, symbol).arg(quantity).arg(order.id));-- return ToolResult::ok("Order placed", QJsonObject{{"order_id", order.id},- {"status", order.status},- {"symbol", order.symbol},- {"side", order.side},- {"quantity", order.quantity},- {"order_type", order.order_type}});- } catch (const std::exception& e) {- return ToolResult::fail(e.what());- }- };- tools.push_back(std::move(t));- }-- // ── pt_cancel_order ────────────────────────────────────────────────- {- ToolDef t;- t.name = "pt_cancel_order";- t.description = "Cancel a pending paper trading order.";- t.category = "trading";- t.input_schema.properties =- QJsonObject{{"order_id", QJsonObject{{"type", "string"}, {"description", "Order ID to cancel"}}}};- t.input_schema.required = {"order_id"};- t.handler = [](const QJsonObject& args) -> ToolResult {- QString order_id = args["order_id"].toString();- if (order_id.isEmpty())- return ToolResult::fail("Missing 'order_id'");-- try {- trading::pt_cancel_order(order_id);- return ToolResult::ok("Order cancelled", QJsonObject{{"order_id", order_id}});- } catch (const std::exception& e) {- return ToolResult::fail(e.what());- }- };- tools.push_back(std::move(t));- }-- // ── pt_get_positions ───────────────────────────────────────────────- {- ToolDef t;- t.name = "pt_get_positions";- t.description = "Get all open positions for a paper trading portfolio.";- t.category = "trading";- t.input_schema.properties =- QJsonObject{{"portfolio_id", QJsonObject{{"type", "string"}, {"description", "Portfolio ID"}}}};- t.input_schema.required = {"portfolio_id"};- t.handler = [](const QJsonObject& args) -> ToolResult {- QString id = args["portfolio_id"].toString();- if (id.isEmpty())- return ToolResult::fail("Missing 'portfolio_id'");-- try {- auto positions = trading::pt_get_positions(id);- QJsonArray result;- for (const auto& pos : positions) {- result.append(QJsonObject{{"id", pos.id},- {"symbol", pos.symbol},- {"side", pos.side},- {"quantity", pos.quantity},- {"entry_price", pos.entry_price},- {"current_price", pos.current_price},- {"unrealized_pnl", pos.unrealized_pnl},- {"realized_pnl", pos.realized_pnl},- {"leverage", pos.leverage},- {"opened_at", pos.opened_at}});- }- return ToolResult::ok_data(result);- } catch (const std::exception& e) {- return ToolResult::fail(e.what());- }- };- tools.push_back(std::move(t));- }-- // ── pt_get_orders ──────────────────────────────────────────────────- {- ToolDef t;- t.name = "pt_get_orders";- t.description = "Get orders for a paper trading portfolio, optionally filtered by status.";- t.category = "trading";- t.input_schema.properties =- QJsonObject{{"portfolio_id", QJsonObject{{"type", "string"}, {"description", "Portfolio ID"}}},- {"status", QJsonObject{{"type", "string"},- {"description", "Filter: pending, filled, cancelled (optional)"}}}};- t.input_schema.required = {"portfolio_id"};- t.handler = [](const QJsonObject& args) -> ToolResult {- QString id = args["portfolio_id"].toString();- QString status = args["status"].toString();- if (id.isEmpty())- return ToolResult::fail("Missing 'portfolio_id'");-- try {- auto orders = trading::pt_get_orders(id, status);- QJsonArray result;- for (const auto& o : orders) {- QJsonObject entry{{"id", o.id},- {"symbol", o.symbol},- {"side", o.side},- {"order_type", o.order_type},- {"quantity", o.quantity},- {"filled_qty", o.filled_qty},- {"status", o.status},- {"reduce_only", o.reduce_only},- {"created_at", o.created_at}};- if (o.price)- entry["price"] = *o.price;- if (o.stop_price)- entry["stop_price"] = *o.stop_price;- if (o.avg_price)- entry["avg_price"] = *o.avg_price;- result.append(entry);- }- return ToolResult::ok_data(result);- } catch (const std::exception& e) {- return ToolResult::fail(e.what());- }- };- tools.push_back(std::move(t));- }-- // ── pt_get_stats ───────────────────────────────────────────────────- {- ToolDef t;- t.name = "pt_get_stats";- t.description = "Get trading statistics for a paper portfolio (PnL, win rate, trade counts).";- t.category = "trading";- t.input_schema.properties =- QJsonObject{{"portfolio_id", QJsonObject{{"type", "string"}, {"description", "Portfolio ID"}}}};- t.input_schema.required = {"portfolio_id"};- t.handler = [](const QJsonObject& args) -> ToolResult {- QString id = args["portfolio_id"].toString();- if (id.isEmpty())- return ToolResult::fail("Missing 'portfolio_id'");-- try {- auto stats = trading::pt_get_stats(id);- return ToolResult::ok_data(QJsonObject{{"total_pnl", stats.total_pnl},- {"win_rate", stats.win_rate},- {"total_trades", static_cast<qint64>(stats.total_trades)},- {"winning_trades", static_cast<qint64>(stats.winning_trades)},- {"losing_trades", static_cast<qint64>(stats.losing_trades)},- {"largest_win", stats.largest_win},- {"largest_loss", stats.largest_loss}});- } catch (const std::exception& e) {- return ToolResult::fail(e.what());- }- };- tools.push_back(std::move(t));- }-- return tools;-}--} // namespace fincept::mcp::toolsdiff --git a/fincept-qt/src/mcp/tools/TradingTools.h b/fincept-qt/src/mcp/tools/TradingTools.hdeleted file mode 100644index 7f3f41f65..000000000--- a/fincept-qt/src/mcp/tools/TradingTools.h+++ /dev/null@@ -1,8 +0,0 @@-#pragma once-#include "mcp/McpTypes.h"--#include <vector>--namespace fincept::mcp::tools {-std::vector<ToolDef> get_trading_tools();-} // namespace fincept::mcp::toolsdiff --git a/fincept-qt/src/screens/chat_mode/TerminalToolBridge.cpp b/fincept-qt/src/screens/chat_mode/TerminalToolBridge.cppindex 140a4b098..fcda9de6e 100644--- a/fincept-qt/src/screens/chat_mode/TerminalToolBridge.cpp+++ b/fincept-qt/src/screens/chat_mode/TerminalToolBridge.cpp@@ -4,6 +4,7 @@#include "mcp/McpProvider.h"#include "screens/chat_mode/ChatModeService.h"+#include <QFutureWatcher>#include <QJsonDocument>#include <QJsonObject>#include <QPointer>@@ -51,19 +52,16 @@ void TerminalToolBridge::register_tools() {QJsonArray tools_json;for (const auto& tool : all_tools) {- // Skip UI-only tools- bool skip = false;- // Check if tool name starts with excluded category prefixes- for (const auto& cat : EXCLUDED_CATEGORIES) {- if (tool.name.startsWith(cat + "_") || tool.name.startsWith(cat + "-")) {- skip = true;- break;- }- }- // Also skip AiChat tools (recursive)- if (tool.name.startsWith("ai_chat") || tool.name.startsWith("aichat"))- skip = true;- if (skip)+ // Phase 6.5: filter by ToolDef.category, not by name-prefix.+ // Pre-Phase-6 the check was tool.name.startsWith("navigation_") etc.+ // — but tool names don't follow that prefix convention, so the+ // filter never matched and every navigation/system/settings tool+ // got uploaded to the cloud. UnifiedTool.category (populated by+ // McpProvider::list_tools) is the source of truth.+ if (EXCLUDED_CATEGORIES.contains(tool.category))+ continue;+ // Recursive AiChat tools — skip by category, not by name prefix.+ if (tool.category == "ai-chat" || tool.category == "ai_chat")continue;QJsonObject schema = tool.input_schema;@@ -130,39 +128,46 @@ void TerminalToolBridge::on_poll_tick() {void TerminalToolBridge::execute_call(const QString& call_id, const QString& tool_name, const QJsonObject& arguments) {LOG_INFO("TerminalToolBridge", QString("Executing tool: %1 (call %2)").arg(tool_name, call_id));- // Strip "fincept-terminal__" prefix if present- QString local_name = tool_name;- if (local_name.startsWith("fincept-terminal__"))- local_name = local_name.mid(18);+ // Phase 5.10: centralised __ parsing. Was previously hardcoded as+ // mid(18) which silently breaks if the server-id prefix ever changes.+ auto [server_id, parsed_name] = mcp::McpProvider::parse_openai_function_name(tool_name);+ const QString local_name = parsed_name.isEmpty() ? tool_name : parsed_name;- // Execute on background thread to avoid blocking UI+ // Phase 4: dispatch via call_tool_async so sync handlers don't block+ // a worker thread for the duration of long-running tools, and so+ // multiple in-flight tool calls fan out concurrently. A QFutureWatcher+ // delivers the result back to this bridge's thread when complete.QPointer<TerminalToolBridge> self = this;- (void)QtConcurrent::run([self, call_id, local_name, arguments]() {- // Call the tool via McpProvider- auto result = mcp::McpProvider::instance().call_tool(local_name, arguments);-- if (!self)- return;- QMetaObject::invokeMethod(- self,- [self, call_id, local_name, result]() {- if (!self || !self->active_)- return;-- // Submit result back to Finagent- ChatModeService::instance().submit_tool_result(- call_id, result.to_json(), [self, local_name, success = result.success](bool ok, QString err) {- if (!self)- return;- if (!ok) {- LOG_WARN("TerminalToolBridge",- QString("Failed to submit result for %1: %2").arg(local_name, err));- }- emit self->tool_executed(local_name, success);- });- },- Qt::QueuedConnection);- });+ auto future = mcp::McpProvider::instance().call_tool_async(local_name, arguments);++ auto* watcher = new QFutureWatcher<mcp::ToolResult>(this);+ QObject::connect(watcher, &QFutureWatcher<mcp::ToolResult>::finished, this,+ [self, call_id, local_name, watcher]() {+ // resultCount() lives on QFuture, not QFutureWatcher —+ // use future() to reach it.+ const auto fut = watcher->future();+ mcp::ToolResult result = (fut.resultCount() > 0)+ ? fut.result()+ : mcp::ToolResult::fail("Tool produced no result");+ watcher->deleteLater();++ if (!self || !self->active_) return;++ // Capture result by value into the submit callback —+ // avoids the init-capture pattern (which Clang on+ // Windows was rejecting for nested-lambda scoping).+ ChatModeService::instance().submit_tool_result(+ call_id, result.to_json(),+ [self, local_name, result](bool ok, QString err) {+ if (!self) return;+ if (!ok) {+ LOG_WARN("TerminalToolBridge",+ QString("Failed to submit result for %1: %2").arg(local_name, err));+ }+ emit self->tool_executed(local_name, result.success);+ });+ });+ watcher->setFuture(future);}} // namespace fincept::chat_modediff --git a/fincept-qt/src/screens/chat_mode/TerminalToolBridge.h b/fincept-qt/src/screens/chat_mode/TerminalToolBridge.hindex aed2fda63..0cf0d8d68 100644--- a/fincept-qt/src/screens/chat_mode/TerminalToolBridge.h+++ b/fincept-qt/src/screens/chat_mode/TerminalToolBridge.h@@ -5,7 +5,8 @@namespace fincept::chat_mode {-/// Bridges the desktop app's 218 internal MCP tools to the Finagent backend.+/// Bridges the desktop app's internal MCP tools (count provided by+/// McpProvider::tool_count()) to the Finagent backend.////// Lifecycle: start() on chat mode entry, stop() on exit./// 1. Registers all enabled internal tools via POST /terminal-tools/registerdiff --git a/fincept-qt/src/screens/geopolitics/ConflictMonitorPanel.cpp b/fincept-qt/src/screens/geopolitics/ConflictMonitorPanel.cppindex 94acffb3b..84a964785 100644--- a/fincept-qt/src/screens/geopolitics/ConflictMonitorPanel.cpp+++ b/fincept-qt/src/screens/geopolitics/ConflictMonitorPanel.cpp@@ -34,9 +34,25 @@ void ConflictMonitorPanel::build_ui() {// ── World Map ───────────────────────────────────────────────────────────map_widget_ = new fincept::ui::WorldMapWidget(left_splitter);- map_widget_->setMinimumHeight(160);+ map_widget_->setMinimumHeight(280);left_splitter->addWidget(map_widget_);+ // Map pin click → select the matching row in the events table. The row's+ // currentCellChanged handler (wired below) then fills the detail panel,+ // so the side panel and the table stay in sync from a single source.+ connect(map_widget_, &fincept::ui::WorldMapWidget::pin_clicked, this, [this](int event_id) {+ if (!events_table_)+ return;+ for (int r = 0; r < events_table_->rowCount(); ++r) {+ auto* it = events_table_->item(r, 0);+ if (it && it->data(Qt::UserRole + 1).toInt() == event_id) {+ events_table_->setCurrentCell(r, 0);+ events_table_->scrollToItem(it, QAbstractItemView::PositionAtCenter);+ break;+ }+ }+ });+// ── Events Table ────────────────────────────────────────────────────────events_table_ = new QTableWidget(left_splitter);events_table_->setColumnCount(7);@@ -82,6 +98,12 @@ void ConflictMonitorPanel::build_ui() {return events_table_->item(row, col) ? events_table_->item(row, col)->text() : QString();};+ // Raw category id lives on UserRole of column 0 — needed for the+ // colour swatch (category_color expects "armed_conflict", not the+ // pretty-printed "Armed Conflict").+ auto* cat_cell = events_table_->item(row, 0);+ const QString raw_cat = cat_cell ? cat_cell->data(Qt::UserRole).toString() : QString();+detail_category_->setText(get_text(0).toUpper());detail_country_->setText(get_text(1));detail_city_->setText(get_text(2));@@ -90,7 +112,7 @@ void ConflictMonitorPanel::build_ui() {if (auto* it = events_table_->item(row, 3); it && detail_source_)detail_source_->setText(it->data(Qt::UserRole).toString());- auto cat_color = category_color(get_text(0));+ const auto cat_color = category_color(raw_cat);detail_category_->setStyleSheet(QString("color:%1; font-size:%2px; font-weight:700; font-family:%3;").arg(cat_color.name()).arg(ui::fonts::SMALL)@@ -100,8 +122,13 @@ void ConflictMonitorPanel::build_ui() {});left_splitter->addWidget(events_table_);- left_splitter->setStretchFactor(0, 4);- left_splitter->setStretchFactor(1, 6);+ events_table_->setMinimumHeight(180);+ left_splitter->setStretchFactor(0, 5);+ left_splitter->setStretchFactor(1, 5);+ // Initial split — keeps the map at a useful height even before the user+ // drags the handle. Without this, an empty/short table can let the map+ // collapse into a thin strip that paints garbage tile coverage.+ left_splitter->setSizes({360, 360});root->addWidget(left_splitter, 1);// Right sidebar: stats + selected detail@@ -213,8 +240,14 @@ void ConflictMonitorPanel::set_events(const QVector<NewsEvent>& events) {for (int i = 0; i < events.size(); ++i) {const auto& ev = events[i];- auto* cat_item = new QTableWidgetItem(ev.event_category);+ auto* cat_item = new QTableWidgetItem(pretty_category(ev.event_category));cat_item->setForeground(category_color(ev.event_category));+ // UserRole carries the raw category id (used by the detail panel+ // to recover the colour); UserRole+1 carries the original event+ // index so map-pin clicks can resolve back to the correct row even+ // after the user re-sorts.+ cat_item->setData(Qt::UserRole, ev.event_category);+ cat_item->setData(Qt::UserRole + 1, i);events_table_->setItem(i, 0, cat_item);events_table_->setItem(i, 1, new QTableWidgetItem(ev.country));@@ -246,7 +279,8 @@ void ConflictMonitorPanel::update_map(const QVector<NewsEvent>& events) {QHash<QString, int> coord_counts;int skipped = 0;- for (const auto& ev : events) {+ for (int i = 0; i < events.size(); ++i) {+ const auto& ev = events[i];if (!ev.has_coords) {++skipped;continue;@@ -265,8 +299,11 @@ void ConflictMonitorPanel::update_map(const QVector<NewsEvent>& events) {lng += dist * std::sin(angle);}- pins.append({lat, lng, QString("%1 — %2, %3").arg(ev.event_category, ev.city, ev.country),- category_color(ev.event_category), 5.0});+ // pin.id = event index — lets the click handler scroll/select the+ // matching row in the table (UserRole+1 stamp on column 0).+ pins.append({lat, lng,+ QString("%1 — %2, %3").arg(ev.event_category, ev.city, ev.country),+ category_color(ev.event_category), 5.0, i});}LOG_INFO("Geopolitics", QString("Map: %1 events → %2 pins (%3 skipped, %4 unique coords)")@@ -311,7 +348,7 @@ void ConflictMonitorPanel::update_stats(const QVector<NewsEvent>& events) {rl->setContentsMargins(6, 2, 4, 2);rl->setSpacing(6);- auto* name = new QLabel(cat, row);+ auto* name = new QLabel(pretty_category(cat), row);name->setStyleSheet(QString("color:%1; font-size:%2px; font-family:%3; border:none; background:transparent;").arg(ui::colors::TEXT_SECONDARY()).arg(ui::fonts::SMALL)diff --git a/fincept-qt/src/screens/geopolitics/GeopoliticsScreen.cpp b/fincept-qt/src/screens/geopolitics/GeopoliticsScreen.cppindex ebf3289ae..4ec45955d 100644--- a/fincept-qt/src/screens/geopolitics/GeopoliticsScreen.cpp+++ b/fincept-qt/src/screens/geopolitics/GeopoliticsScreen.cpp@@ -12,6 +12,7 @@#include "ui/theme/ThemeManager.h"#include <QDateTime>+#include <QFrame>#include <QHBoxLayout>#include <QScrollArea>@@ -43,7 +44,7 @@ void GeopoliticsScreen::showEvent(QShowEvent* e) {clock_timer_->start();if (first_show_) {first_show_ = false;- country_edit_->setText("Ukraine");+ // Fetch latest events with no filter — newest first, server side.on_apply_filters();GeopoliticsService::instance().fetch_unique_countries();GeopoliticsService::instance().fetch_unique_categories();@@ -65,14 +66,9 @@ void GeopoliticsScreen::refresh_theme() {void GeopoliticsScreen::connect_service() {auto& svc = GeopoliticsService::instance();- connect(&svc, &GeopoliticsService::events_loaded, this, &GeopoliticsScreen::on_events_loaded);- connect(&svc, &GeopoliticsService::error_occurred, this, &GeopoliticsScreen::on_error);- connect(&svc, &GeopoliticsService::categories_loaded, this, [this](QVector<UniqueCategory> cats) {- category_combo_->clear();- category_combo_->addItem("All Categories", "");- for (const auto& c : cats)- category_combo_->addItem(QString("%1 (%2)").arg(c.category).arg(c.event_count), c.category);- });+ connect(&svc, &GeopoliticsService::events_loaded, this, &GeopoliticsScreen::on_events_loaded);+ connect(&svc, &GeopoliticsService::error_occurred, this, &GeopoliticsScreen::on_error);+ connect(&svc, &GeopoliticsService::categories_loaded, this, &GeopoliticsScreen::on_categories_loaded);}// ── Build UI ─────────────────────────────────────────────────────────────────@@ -243,9 +239,9 @@ QWidget* GeopoliticsScreen::build_filter_panel() {vl->addWidget(cat_lbl);category_combo_ = new QComboBox(panel);category_combo_->setStyleSheet(input_style);+ // Populated from API once categories_loaded fires — start with a single+ // "All" entry so the combo renders before the network round-trip.category_combo_->addItem("All Categories", "");- for (const auto& cat : event_categories())- category_combo_->addItem(cat, cat);vl->addWidget(category_combo_);vl->addSpacing(4);@@ -294,25 +290,30 @@ QWidget* GeopoliticsScreen::build_filter_panel() {.arg(ui::fonts::DATA_FAMILY));vl->addWidget(legend_title);- for (const auto& cat : event_categories()) {- auto* row = new QWidget(panel);- auto* rl = new QHBoxLayout(row);- rl->setContentsMargins(0, 1, 0, 1);- rl->setSpacing(6);- auto* dot = new QWidget(row);- dot->setFixedSize(8, 8);- dot->setStyleSheet(QString("background:%1; border-radius:4px;").arg(category_color(cat).name()));- rl->addWidget(dot);- auto* lbl = new QLabel(cat, row);- lbl->setStyleSheet(QString("color:%1; font-size:%2px; font-family:%3;")- .arg(ui::colors::TEXT_SECONDARY())- .arg(ui::fonts::SMALL)- .arg(ui::fonts::DATA_FAMILY));- rl->addWidget(lbl, 1);- vl->addWidget(row);- }+ // Legend rows are added by rebuild_legend() once categories_loaded fires.+ // Wrapped in a scroll area because the API now exposes ~26 categories;+ // without scrolling the legend would push the filter panel taller than+ // the viewport, which forces the parent screen to scroll and breaks the+ // map widget's painting (the map paints into whatever screen-space slot+ // the layout gives it on first show).+ auto* legend_scroll = new QScrollArea(panel);+ legend_scroll->setWidgetResizable(true);+ legend_scroll->setFrameShape(QFrame::NoFrame);+ legend_scroll->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);+ legend_scroll->setStyleSheet(QString("QScrollArea { background:transparent; border:none; }"+ "QScrollBar:vertical { background:%1; width:6px; }"+ "QScrollBar::handle:vertical { background:%2; border-radius:3px; }"+ "QScrollBar::add-line, QScrollBar::sub-line { height:0px; }")+ .arg(ui::colors::BG_SURFACE(), ui::colors::BORDER_MED()));++ legend_container_ = new QWidget(legend_scroll);+ legend_container_->setStyleSheet(QString("background:%1;").arg(ui::colors::BG_SURFACE()));+ legend_layout_ = new QVBoxLayout(legend_container_);+ legend_layout_->setContentsMargins(0, 0, 4, 0);+ legend_layout_->setSpacing(2);+ legend_scroll->setWidget(legend_container_);+ vl->addWidget(legend_scroll, 1); // stretch — legend takes remaining space- vl->addStretch();return panel;}@@ -355,6 +356,13 @@ QWidget* GeopoliticsScreen::build_status_bar() {hl->addStretch();+ credits_label_ = new QLabel("CREDITS: —", bar);+ credits_label_->setStyleSheet(QString("color:%1; font-size:%2px; font-weight:700; font-family:%3;")+ .arg(ui::colors::TEXT_TERTIARY())+ .arg(ui::fonts::TINY)+ .arg(ui::fonts::DATA_FAMILY));+ hl->addWidget(credits_label_);+status_label_ = new QLabel("READY", bar);status_label_->setStyleSheet(QString("color:%1; font-size:%2px; font-weight:700; font-family:%3;").arg(ui::colors::POSITIVE())@@ -423,9 +431,18 @@ void GeopoliticsScreen::on_tab_changed(int index) {}}-void GeopoliticsScreen::on_events_loaded(QVector<services::geo::NewsEvent> events, int total) {- event_count_label_->setText(QString("%1 EVENTS").arg(total));- const QString color = total > 0 ? ui::colors::POSITIVE() : ui::colors::NEGATIVE();+void GeopoliticsScreen::on_events_loaded(services::geo::EventsPage page) {+ const int shown = page.events.size();+ const int total = page.total_events;++ // "12 / 1.2K EVENTS" — show what was rendered out of the total.+ auto fmt_count = [](int n) -> QString {+ if (n >= 1'000'000) return QString::number(n / 1'000'000.0, 'f', 1) + "M";+ if (n >= 1'000) return QString::number(n / 1'000.0, 'f', 1) + "K";+ return QString::number(n);+ };+ event_count_label_->setText(QString("%1 / %2 EVENTS").arg(fmt_count(shown), fmt_count(total)));+ const QString color = shown > 0 ? ui::colors::POSITIVE() : ui::colors::NEGATIVE();QColor clr(color);auto clr_rgb = QString("%1,%2,%3").arg(clr.red()).arg(clr.green()).arg(clr.blue());event_count_label_->setStyleSheet(@@ -435,12 +452,79 @@ void GeopoliticsScreen::on_events_loaded(QVector<services::geo::NewsEvent> event.arg(ui::fonts::TINY).arg(ui::fonts::DATA_FAMILY).arg(clr_rgb));++ // Credits — colour-coded so depletion is glanceable.+ if (page.remaining_credits >= 0 && credits_label_) {+ const int rc = page.remaining_credits;+ const QString credit_color = rc < 20 ? ui::colors::NEGATIVE()+ : rc < 100 ? ui::colors::WARNING()+ : ui::colors::POSITIVE();+ credits_label_->setText(QString("CREDITS: %1").arg(rc));+ credits_label_->setStyleSheet(QString("color:%1; font-size:%2px; font-weight:700; font-family:%3;")+ .arg(credit_color)+ .arg(ui::fonts::TINY)+ .arg(ui::fonts::DATA_FAMILY));+ }+status_label_->setText("READY");status_label_->setStyleSheet(QString("color:%1; font-size:%2px; font-weight:700; font-family:%3;").arg(ui::colors::POSITIVE()).arg(ui::fonts::TINY).arg(ui::fonts::DATA_FAMILY));- monitor_panel_->set_events(events);+ monitor_panel_->set_events(page.events);+}++void GeopoliticsScreen::on_categories_loaded(QVector<services::geo::UniqueCategory> cats) {+ // Sort by event_count desc — most active categories first in both filter+ // dropdown and legend.+ std::sort(cats.begin(), cats.end(),+ [](const services::geo::UniqueCategory& a, const services::geo::UniqueCategory& b) {+ return a.event_count > b.event_count;+ });++ if (category_combo_) {+ const QString prev = category_combo_->currentData().toString();+ category_combo_->clear();+ category_combo_->addItem("All Categories", "");+ for (const auto& c : cats)+ category_combo_->addItem(+ QString("%1 (%2)").arg(services::geo::pretty_category(c.category)).arg(c.event_count),+ c.category);+ if (!prev.isEmpty()) {+ const int idx = category_combo_->findData(prev);+ if (idx >= 0) category_combo_->setCurrentIndex(idx);+ }+ }+ rebuild_legend(cats);+}++void GeopoliticsScreen::rebuild_legend(const QVector<services::geo::UniqueCategory>& cats) {+ if (!legend_layout_)+ return;+ while (legend_layout_->count() > 0) {+ auto* item = legend_layout_->takeAt(0);+ if (item->widget()) item->widget()->deleteLater();+ delete item;+ }+ for (const auto& c : cats) {+ auto* row = new QWidget(legend_container_);+ auto* rl = new QHBoxLayout(row);+ rl->setContentsMargins(0, 1, 0, 1);+ rl->setSpacing(6);+ auto* dot = new QWidget(row);+ dot->setFixedSize(8, 8);+ dot->setStyleSheet(QString("background:%1; border-radius:4px;")+ .arg(services::geo::category_color(c.category).name()));+ rl->addWidget(dot);+ auto* lbl = new QLabel(services::geo::pretty_category(c.category), row);+ lbl->setStyleSheet(QString("color:%1; font-size:%2px; font-family:%3;")+ .arg(ui::colors::TEXT_SECONDARY())+ .arg(ui::fonts::SMALL)+ .arg(ui::fonts::DATA_FAMILY));+ rl->addWidget(lbl, 1);+ legend_layout_->addWidget(row);+ }+ legend_layout_->addStretch();}void GeopoliticsScreen::on_error(const QString& context, const QString& message) {diff --git a/fincept-qt/src/screens/geopolitics/GeopoliticsScreen.h b/fincept-qt/src/screens/geopolitics/GeopoliticsScreen.hindex bb35d21ed..6cc829f49 100644--- a/fincept-qt/src/screens/geopolitics/GeopoliticsScreen.h+++ b/fincept-qt/src/screens/geopolitics/GeopoliticsScreen.h@@ -44,7 +44,8 @@ class GeopoliticsScreen : public QWidget, public IStatefulScreen {void on_apply_filters();void on_clear_filters();void on_tab_changed(int index);- void on_events_loaded(QVector<services::geo::NewsEvent> events, int total);+ void on_events_loaded(services::geo::EventsPage page);+ void on_categories_loaded(QVector<services::geo::UniqueCategory> cats);void on_error(const QString& context, const QString& message);private:@@ -54,6 +55,7 @@ class GeopoliticsScreen : public QWidget, public IStatefulScreen {QWidget* build_status_bar();void connect_service();void refresh_theme();+ void rebuild_legend(const QVector<services::geo::UniqueCategory>& cats);// Filter inputsQLineEdit* country_edit_ = nullptr;@@ -74,6 +76,11 @@ class GeopoliticsScreen : public QWidget, public IStatefulScreen {// StatusQLabel* event_count_label_ = nullptr;QLabel* status_label_ = nullptr;+ QLabel* credits_label_ = nullptr;++ // Legend (built dynamically from API categories)+ QWidget* legend_container_ = nullptr;+ QVBoxLayout* legend_layout_ = nullptr;// Auto-refreshQTimer* refresh_timer_ = nullptr;diff --git a/fincept-qt/src/screens/maritime/MaritimeScreen.cpp b/fincept-qt/src/screens/maritime/MaritimeScreen.cppindex 2c2a2f0d3..b9484b4f1 100644--- a/fincept-qt/src/screens/maritime/MaritimeScreen.cpp+++ b/fincept-qt/src/screens/maritime/MaritimeScreen.cpp@@ -10,8 +10,10 @@#include <QGridLayout>#include <QHBoxLayout>+#include <QHash>#include <QHeaderView>#include <QScrollArea>+#include <QSet>#include <QSplitter>#include <QTabWidget>@@ -88,7 +90,7 @@ static QString detail_text_ss() {// ── Constructor ──────────────────────────────────────────────────────────────MaritimeScreen::MaritimeScreen(QWidget* parent) : QWidget(parent) {- routes_ = default_trade_routes();+ // routes_ starts empty — populated dynamically from loaded vessels.build_ui();connect_service();@@ -107,8 +109,14 @@ void MaritimeScreen::showEvent(QShowEvent* e) {refresh_timer_->start();if (first_show_) {first_show_ = false;- populate_routes_table();- on_load_vessels();+ // Pull whatever bounding box the user last typed (restored from+ // ScreenStateManager) — no hardcoded "Mumbai area" load.+ if (area_min_lat_ && area_max_lat_ && area_min_lng_ && area_max_lng_) {+ const bool valid = area_max_lat_->value() > area_min_lat_->value()+ && area_max_lng_->value() > area_min_lng_->value();+ if (valid)+ on_load_vessels();+ }}LOG_INFO("Maritime", "Screen shown");}@@ -146,13 +154,14 @@ void MaritimeScreen::apply_theme() {.arg(ui::colors::TEXT_TERTIARY()).arg(ui::fonts::DATA_FAMILY));- if (threat_badge_)- threat_badge_->setStyleSheet(QString("color:%1; font-size:9px; font-weight:700; font-family:%2;"- "padding:3px 10px; background:%3; border:1px solid %4; border-radius:2px;")- .arg(ui::colors::POSITIVE())- .arg(ui::fonts::DATA_FAMILY)- .arg(ui::colors::BG_SURFACE())- .arg(ui::colors::BORDER_MED()));+ if (credits_label_)+ credits_label_->setStyleSheet(+ QString("color:%1; font-size:9px; font-weight:700; font-family:%2;"+ "padding:3px 10px; background:%3; border:1px solid %4; border-radius:2px;")+ .arg(ui::colors::TEXT_TERTIARY())+ .arg(ui::fonts::DATA_FAMILY)+ .arg(ui::colors::BG_SURFACE())+ .arg(ui::colors::BORDER_MED()));if (vessel_count_label_)vessel_count_label_->setStyleSheet(@@ -245,15 +254,15 @@ QWidget* MaritimeScreen::build_top_bar() {brand_label_ = new QLabel("FINCEPT MARITIME INTELLIGENCE", bar);hl->addWidget(brand_label_);- classified_label_ = new QLabel("CLASSIFIED // TRADE ROUTE ANALYSIS", bar);+ classified_label_ = new QLabel("VESSEL TRACKING // FINCEPT MARINE API", bar);hl->addWidget(classified_label_);hl->addStretch(1);- threat_badge_ = new QLabel("THREAT: LOW", bar);- hl->addWidget(threat_badge_);+ credits_label_ = new QLabel("CREDITS: —", bar);+ hl->addWidget(credits_label_);- vessel_count_label_ = new QLabel("0 VESSELS", bar);+ vessel_count_label_ = new QLabel("— VESSELS", bar);hl->addWidget(vessel_count_label_);return bar;@@ -268,7 +277,7 @@ QWidget* MaritimeScreen::build_left_panel() {vl->setContentsMargins(12, 12, 12, 12);vl->setSpacing(8);- auto* load_btn = new QPushButton("LOAD VESSELS (MUMBAI AREA)", panel);+ auto* load_btn = new QPushButton("LOAD VESSELS IN AREA", panel);load_btn->setCursor(Qt::PointingHandCursor);load_btn->setStyleSheet(btn_primary_ss());connect(load_btn, &QPushButton::clicked, this, &MaritimeScreen::on_load_vessels);@@ -304,27 +313,25 @@ QWidget* MaritimeScreen::build_left_panel() {return box;};- auto* sv = make_stat("TOTAL VESSELS", "0", ui::colors::INFO);- stat_vessels_ = sv->findChild<QLabel*>("TOTAL VESSELS");+ // All stats start at "—" and are populated from the loaded vessel set.+ // No hardcoded trade-volume, route count, or satellite numbers — the API+ // does not expose those, so we don't fabricate them.+ auto* sv = make_stat("TOTAL IN AREA", "—", ui::colors::INFO);+ stat_vessels_ = sv->findChild<QLabel*>("TOTAL IN AREA");grid->addWidget(sv, 0, 0);- auto* sd = make_stat("DISPLAYED", "0", ui::colors::POSITIVE);+ auto* sd = make_stat("DISPLAYED", "—", ui::colors::POSITIVE);stat_displayed_ = sd->findChild<QLabel*>("DISPLAYED");grid->addWidget(sd, 0, 1);- auto* sr = make_stat("ROUTES", "10", ui::colors::INFO);+ auto* sr = make_stat("ROUTES", "—", ui::colors::INFO);stat_routes_ = sr->findChild<QLabel*>("ROUTES");grid->addWidget(sr, 1, 0);- auto* stv = make_stat("TRADE VOL", "$847.3B", ui::colors::POSITIVE);- stat_volume_ = stv->findChild<QLabel*>("TRADE VOL");- grid->addWidget(stv, 1, 1);-- auto* sp = make_stat("PORTS", "6", ui::colors::WARNING);+ auto* sp = make_stat("PORTS", "—", ui::colors::WARNING);stat_ports_ = sp->findChild<QLabel*>("PORTS");- grid->addWidget(sp, 2, 0);+ grid->addWidget(sp, 1, 1);- grid->addWidget(make_stat("SATELLITES", "13", ui::colors::AMBER), 2, 1);vl->addLayout(grid);vl->addSpacing(8);@@ -336,7 +343,7 @@ QWidget* MaritimeScreen::build_left_panel() {routes_table_ = new QTableWidget(panel);routes_table_->setColumnCount(3);- routes_table_->setHorizontalHeaderLabels({"Route", "Value", "Status"});+ routes_table_->setHorizontalHeaderLabels({"Route", "Vessels", "Status"});routes_table_->setEditTriggers(QAbstractItemView::NoEditTriggers);routes_table_->setSelectionBehavior(QAbstractItemView::SelectRows);routes_table_->horizontalHeader()->setStretchLastSection(true);@@ -362,18 +369,13 @@ QWidget* MaritimeScreen::build_center_panel() {QString("background:%1; border-bottom:1px solid %2;").arg(C(ui::colors::BG_RAISED), C(ui::colors::BORDER_DIM)));auto* hhl = new QHBoxLayout(header);hhl->setContentsMargins(16, 0, 16, 0);- auto* title = new QLabel("VESSEL TRACKING — AIS FEED", header);+ auto* title = new QLabel("VESSEL TRACKING", header);title->setStyleSheet(QString("color:%1; font-size:%2px; font-weight:700; font-family:%3; letter-spacing:1px;").arg(ui::colors::AMBER()).arg(ui::fonts::TINY).arg(ui::fonts::DATA_FAMILY));hhl->addWidget(title);hhl->addStretch();- auto* ais_badge = new QLabel("AIS: STREAMING", header);- ais_badge->setStyleSheet(QString("color:%1; font-size:9px; font-family:%2; font-weight:700;")- .arg(ui::colors::POSITIVE())- .arg(ui::fonts::DATA_FAMILY));- hhl->addWidget(ais_badge);vl->addWidget(header);auto* splitter = new QSplitter(Qt::Vertical, panel);@@ -381,13 +383,7 @@ QWidget* MaritimeScreen::build_center_panel() {splitter->setStyleSheet(QString("QSplitter::handle { background:%1; }").arg(ui::colors::BORDER_DIM()));map_widget_ = new fincept::ui::WorldMapWidget(splitter);- map_widget_->setMinimumHeight(160);-- QVector<fincept::ui::MapPin> port_pins;- for (const auto& port : preset_ports())- port_pins.append({port.lat, port.lng, port.name, ui::colors::CYAN, 6.0});- map_widget_->set_pins(port_pins);-+ map_widget_->setMinimumHeight(280);splitter->addWidget(map_widget_);vessels_table_ = new QTableWidget(splitter);@@ -403,8 +399,10 @@ QWidget* MaritimeScreen::build_center_panel() {vessels_table_->setStyleSheet(table_ss());splitter->addWidget(vessels_table_);- splitter->setStretchFactor(0, 4);- splitter->setStretchFactor(1, 6);+ vessels_table_->setMinimumHeight(180);+ splitter->setStretchFactor(0, 5);+ splitter->setStretchFactor(1, 5);+ splitter->setSizes({380, 360});vl->addWidget(splitter, 1);return panel;@@ -513,10 +511,12 @@ QWidget* MaritimeScreen::build_right_panel() {return spin;};- area_min_lat_ = make_coord("MIN LATITUDE", 18.5);- area_max_lat_ = make_coord("MAX LATITUDE", 19.5);- area_min_lng_ = make_coord("MIN LONGITUDE", 72.0);- area_max_lng_ = make_coord("MAX LONGITUDE", 73.5);+ // Spinners start at zero — the user supplies a real bbox before the+ // first call (or restore_state injects the last-used coords).+ area_min_lat_ = make_coord("MIN LATITUDE", 0.0);+ area_max_lat_ = make_coord("MAX LATITUDE", 0.0);+ area_min_lng_ = make_coord("MIN LONGITUDE", 0.0);+ area_max_lng_ = make_coord("MAX LONGITUDE", 0.0);auto* area_btn = new QPushButton("SEARCH AREA", content);area_btn->setCursor(Qt::PointingHandCursor);@@ -564,22 +564,21 @@ QWidget* MaritimeScreen::build_right_panel() {// ── System Status ──────────────────────────────────────────────────────vl->addSpacing(8);- auto* sys_title = new QLabel("SYSTEM STATUS", content);- sys_title->setStyleSheet(tiny_label_ss());- vl->addWidget(sys_title);-- // Status items use semantic tokens- struct StatusItem {- QString text;- const ui::ColorToken& color;- };- QVector<QPair<QString, QString>> statuses = {- {"AIS Transponders", ui::colors::INFO()},- {"Satellite Imagery", ui::colors::POSITIVE()},- {"Trade Routes: 10 corridors", ui::colors::INFO()},- {"Orbital Tracking: 13 SATs", ui::colors::AMBER()},- {"Major Ports: 6 monitored", ui::colors::WARNING()},- };+ not_found_label_ = new QLabel(content);+ not_found_label_->setVisible(false);+ not_found_label_->setWordWrap(true);+ not_found_label_->setStyleSheet(QString("color:%1; font-size:9px; font-family:%2;"+ "padding:6px; border:1px solid %3; background:%4; border-radius:2px;")+ .arg(ui::colors::WARNING())+ .arg(ui::fonts::DATA_FAMILY)+ .arg(ui::colors::BORDER_MED())+ .arg(ui::colors::BG_SURFACE()));+ vl->addWidget(not_found_label_);++ // Suppressed: hardcoded "system status" placeholders (AIS Transponders /+ // Satellite Imagery / 10 corridors / 13 SATs / 6 ports) — none of these+ // figures come from the API. Restore once a real backend exposes them.+ QVector<QPair<QString, QString>> statuses;for (const auto& [text, color] : statuses) {auto* lbl = new QLabel(QString::fromUtf8("\u25CF ") + text, content);lbl->setStyleSheet(QString("color:%1; font-size:8px; font-family:%2;").arg(color).arg(ui::fonts::DATA_FAMILY));@@ -651,8 +650,12 @@ void MaritimeScreen::populate_routes_table() {auto* name_item = new QTableWidgetItem(r.name);name_item->setForeground(QBrush(QColor(ui::colors::INFO.get())));routes_table_->setItem(i, 0, name_item);- routes_table_->setItem(i, 1, new QTableWidgetItem(r.value));- auto* status_item = new QTableWidgetItem(r.status.toUpper());+ // The API doesn't expose trade-volume in $ — repurpose the middle+ // column for the live vessel count derived from the loaded set.+ auto* count_item = new QTableWidgetItem(QString::number(r.vessels));+ count_item->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);+ routes_table_->setItem(i, 1, count_item);+ auto* status_item = new QTableWidgetItem(r.status.isEmpty() ? QStringLiteral("-") : r.status.toUpper());status_item->setForeground(route_status_color(r.status));routes_table_->setItem(i, 2, status_item);}@@ -661,8 +664,16 @@ void MaritimeScreen::populate_routes_table() {// ── Actions ──────────────────────────────────────────────────────────────────void MaritimeScreen::on_load_vessels() {- set_status("LOADING...", ui::colors::WARNING);AreaSearchParams params;+ if (area_min_lat_) params.min_lat = area_min_lat_->value();+ if (area_max_lat_) params.max_lat = area_max_lat_->value();+ if (area_min_lng_) params.min_lng = area_min_lng_->value();+ if (area_max_lng_) params.max_lng = area_max_lng_->value();+ if (params.max_lat <= params.min_lat || params.max_lng <= params.min_lng) {+ set_status("INVALID BBOX", ui::colors::WARNING);+ return;+ }+ set_status("LOADING...", ui::colors::WARNING);MaritimeService::instance().search_vessels_by_area(params);}@@ -676,12 +687,18 @@ void MaritimeScreen::on_search_vessel() {MaritimeService::instance().get_vessel_position(imo);}-void MaritimeScreen::on_vessels_loaded(QVector<VesselData> vessels, int total) {+void MaritimeScreen::on_vessels_loaded(VesselsPage page) {+ // Render limit — area-search can return 14k+ rows. Pin/render the top+ // (newest-first) batch to keep the UI responsive; full count still+ // shown in the status badge.+ static constexpr int kRenderLimit = 500;+ const int render_n = qMin(page.vessels.size(), kRenderLimit);+vessels_table_->setSortingEnabled(false);- vessels_table_->setRowCount(vessels.size());+ vessels_table_->setRowCount(render_n);- for (int i = 0; i < vessels.size(); ++i) {- const auto& v = vessels[i];+ for (int i = 0; i < render_n; ++i) {+ const auto& v = page.vessels[i];auto* name_item = new QTableWidgetItem(v.name);name_item->setForeground(QBrush(QColor(ui::colors::INFO.get())));@@ -707,16 +724,34 @@ void MaritimeScreen::on_vessels_loaded(QVector<VesselData> vessels, int total) {vessels_table_->setItem(i, 6, new QTableWidgetItem(v.from_port));vessels_table_->setItem(i, 7, new QTableWidgetItem(v.to_port));- auto* prog = new QTableWidgetItem(v.route_progress > 0 ? QString("%1%").arg(v.route_progress, 0, 'f', 0) : "—");+ auto* prog = new QTableWidgetItem(v.route_progress > 0 ? QString("%1%").arg(v.route_progress, 0, 'f', 0) : "-");prog->setTextAlignment(Qt::AlignCenter);vessels_table_->setItem(i, 8, prog);}vessels_table_->setSortingEnabled(true);vessels_table_->resizeColumnsToContents();- update_intelligence(total);- update_map(vessels);- set_status("READY", ui::colors::POSITIVE);++ // Surface multi-vessel "not_found" warnings if any IMOs were missing.+ if (not_found_label_) {+ if (!page.not_found.isEmpty()) {+ not_found_label_->setText(QString("Not found in DB: %1").arg(page.not_found.join(", ")));+ not_found_label_->setVisible(true);+ } else {+ not_found_label_->setVisible(false);+ }+ }++ update_intelligence(page.total_count);+ update_credits(page.remaining_credits);+ update_map(page.vessels.mid(0, kRenderLimit));+ rebuild_routes_from_vessels(page.vessels);+ populate_routes_table();++ if (page.vessels.size() > kRenderLimit)+ set_status(QString("READY (showing %1 of %2)").arg(render_n).arg(page.vessels.size()), ui::colors::WARNING);+ else+ set_status("READY", ui::colors::POSITIVE);}void MaritimeScreen::on_vessel_found(VesselData vessel) {@@ -749,8 +784,8 @@ void MaritimeScreen::on_route_selected(int row) {const auto& r = routes_[row];route_detail_->setVisible(true);rd_name_->setText(r.name);- rd_value_->setText("Trade Value: " + r.value);- rd_status_->setText("Status: " + r.status.toUpper());+ rd_value_->setText(r.value.isEmpty() ? QStringLiteral("Trade Value: n/a") : "Trade Value: " + r.value);+ rd_status_->setText("Status: " + (r.status.isEmpty() ? QStringLiteral("-") : r.status.toUpper()));rd_status_->setStyleSheet(QString("color:%1; font-size:9px; font-family:%2;").arg(route_status_color(r.status).name()).arg(ui::fonts::DATA_FAMILY));@@ -758,27 +793,84 @@ void MaritimeScreen::on_route_selected(int row) {}void MaritimeScreen::update_intelligence(int vessel_count) {- vessel_count_label_->setText(QString("%1 VESSELS").arg(vessel_count));+ auto fmt = [](int n) -> QString {+ if (n >= 1'000'000) return QString::number(n / 1'000'000.0, 'f', 1) + "M";+ if (n >= 1'000) return QString::number(n / 1'000.0, 'f', 1) + "K";+ return QString::number(n);+ };+ const QString count_str = fmt(vessel_count);+ vessel_count_label_->setText(QString("%1 VESSELS").arg(count_str));if (stat_vessels_)- stat_vessels_->setText(QString::number(vessel_count));+ stat_vessels_->setText(count_str);if (stat_displayed_)stat_displayed_->setText(QString::number(qMin(vessel_count, 500)));+ if (stat_routes_)+ stat_routes_->setText(QString::number(routes_.size()));+}++void MaritimeScreen::update_credits(int remaining) {+ if (!credits_label_ || remaining < 0)+ return;+ const QString c = remaining < 20 ? ui::colors::NEGATIVE()+ : remaining < 100 ? ui::colors::WARNING()+ : ui::colors::POSITIVE();+ QColor cc(c);+ auto rgb = QString("%1,%2,%3").arg(cc.red()).arg(cc.green()).arg(cc.blue());+ credits_label_->setText(QString("CREDITS: %1").arg(remaining));+ credits_label_->setStyleSheet(QString("color:%1; font-size:9px; font-weight:700; font-family:%2;"+ "padding:3px 10px; background:rgba(%3,0.08); border:1px solid rgba(%3,0.3);"+ "border-radius:2px;")+ .arg(c)+ .arg(ui::fonts::DATA_FAMILY)+ .arg(rgb));}void MaritimeScreen::update_map(const QVector<VesselData>& vessels) {QVector<fincept::ui::MapPin> pins;- for (const auto& port : preset_ports())- pins.append({port.lat, port.lng, port.name, ui::colors::CYAN, 6.0});+ pins.reserve(vessels.size());+ QSet<QString> port_seen;for (const auto& v : vessels) {if (v.latitude == 0.0 && v.longitude == 0.0)continue;- pins.append({v.latitude, v.longitude, QString("%1 (%2)").arg(v.name, v.imo), ui::colors::POSITIVE, 4.0});+ pins.append({v.latitude, v.longitude, QString("%1 (%2)").arg(v.name, v.imo),+ ui::colors::POSITIVE, 4.0});+ // Track unique destination ports for the PORTS stat.+ if (!v.to_port.isEmpty())+ port_seen.insert(v.to_port);}+ if (stat_ports_)+ stat_ports_->setText(QString::number(port_seen.size()));map_widget_->set_pins(pins);map_widget_->fit_to_pins();}-void MaritimeScreen::on_vessel_history(QVector<VesselData> history) {+void MaritimeScreen::rebuild_routes_from_vessels(const QVector<VesselData>& vessels) {+ // Aggregate vessels by from_port -> to_port. Skip rows with missing+ // endpoints. Sort by vessel count desc so the busiest corridors top+ // the list.+ QHash<QString, TradeRoute> agg;+ for (const auto& v : vessels) {+ if (v.from_port.isEmpty() || v.to_port.isEmpty())+ continue;+ const QString key = v.from_port + " -> " + v.to_port;+ auto& r = agg[key];+ if (r.name.isEmpty()) {+ r.name = key;+ r.status = QStringLiteral("active");+ }+ r.vessels++;+ }+ routes_.clear();+ routes_.reserve(agg.size());+ for (auto it = agg.cbegin(); it != agg.cend(); ++it)+ routes_.append(it.value());+ std::sort(routes_.begin(), routes_.end(),+ [](const TradeRoute& a, const TradeRoute& b) { return a.vessels > b.vessels; });+}++void MaritimeScreen::on_vessel_history(VesselHistoryPage page) {+ update_credits(page.remaining_credits);+ const auto& history = page.history;if (history.isEmpty()) {set_status("NO HISTORY", ui::colors::WARNING);return;@@ -843,8 +935,9 @@ void MaritimeScreen::on_vessel_history(QVector<VesselData> history) {vessels_table_->setSortingEnabled(true);vessels_table_->resizeColumnsToContents();- set_status(QString("HISTORY: %1 — %2 positions").arg(vessel_name).arg(total), ui::colors::WARNING);- LOG_INFO("Maritime", QString("Vessel history: %1 — %2 positions").arg(vessel_name).arg(total));+ const int reported = page.total_records > 0 ? page.total_records : total;+ set_status(QString("HISTORY: %1 (%2 positions)").arg(vessel_name).arg(reported), ui::colors::WARNING);+ LOG_INFO("Maritime", QString("Vessel history [%1]: %2 / %3 positions").arg(vessel_name).arg(total).arg(reported));}// ── IStatefulScreen ──────────────────────────────────────────────────────────diff --git a/fincept-qt/src/screens/maritime/MaritimeScreen.h b/fincept-qt/src/screens/maritime/MaritimeScreen.hindex f6781a10b..d8ca8c363 100644--- a/fincept-qt/src/screens/maritime/MaritimeScreen.h+++ b/fincept-qt/src/screens/maritime/MaritimeScreen.h@@ -41,9 +41,9 @@ class MaritimeScreen : public QWidget, public IStatefulScreen {private slots:void on_load_vessels();void on_search_vessel();- void on_vessels_loaded(QVector<services::maritime::VesselData> vessels, int total);+ void on_vessels_loaded(services::maritime::VesselsPage page);void on_vessel_found(services::maritime::VesselData vessel);- void on_vessel_history(QVector<services::maritime::VesselData> history);+ void on_vessel_history(services::maritime::VesselHistoryPage page);void on_error(const QString& context, const QString& message);void on_route_selected(int row);@@ -55,8 +55,10 @@ class MaritimeScreen : public QWidget, public IStatefulScreen {QWidget* build_right_panel();QWidget* build_status_bar();void connect_service();+ void rebuild_routes_from_vessels(const QVector<services::maritime::VesselData>& vessels);void populate_routes_table();void update_intelligence(int vessel_count);+ void update_credits(int remaining);void update_map(const QVector<services::maritime::VesselData>& vessels);void apply_theme();void set_status(const QString& text, const ui::ColorToken& color);@@ -65,6 +67,8 @@ class MaritimeScreen : public QWidget, public IStatefulScreen {QWidget* top_bar_ = nullptr;QLabel* brand_label_ = nullptr;QLabel* classified_label_ = nullptr;+ QLabel* credits_label_ = nullptr;+ QLabel* not_found_label_ = nullptr; // shown when multi-vessel returns missing IMOs// Left / right panel rootsQWidget* left_panel_ = nullptr;@@ -75,9 +79,7 @@ class MaritimeScreen : public QWidget, public IStatefulScreen {QLabel* stat_vessels_ = nullptr;QLabel* stat_displayed_ = nullptr;QLabel* stat_routes_ = nullptr;- QLabel* stat_volume_ = nullptr;QLabel* stat_ports_ = nullptr;- QLabel* threat_badge_ = nullptr;// Centerfincept::ui::WorldMapWidget* map_widget_ = nullptr;diff --git a/fincept-qt/src/screens/news/NewsScreen.cpp b/fincept-qt/src/screens/news/NewsScreen.cppindex fbc164209..b12e72cdc 100644--- a/fincept-qt/src/screens/news/NewsScreen.cpp+++ b/fincept-qt/src/screens/news/NewsScreen.cpp@@ -1,5 +1,6 @@#include "screens/news/NewsScreen.h"+#include "core/events/EventBus.h"#include "core/keys/KeyConfigManager.h"#include "core/logging/Logger.h"#include "core/session/ScreenStateManager.h"@@ -272,6 +273,7 @@ void NewsScreen::showEvent(QShowEvent* e) {pulse_timer_->start();services::NewsService::instance().start_auto_refresh();services::NewsService::instance().connect_live_feed();+ subscribe_mcp_events();if (first_show_) {first_show_ = false;@@ -304,6 +306,47 @@ void NewsScreen::hideEvent(QHideEvent* e) {services::NewsService::instance().stop_auto_refresh();services::NewsService::instance().disconnect_live_feed();filter_generation_.fetch_add(1, std::memory_order_relaxed);+ unsubscribe_mcp_events();+}++// ── MCP-driven UI sync ──────────────────────────────────────────────────────+// MCP tools (called from AI Chat / Finagent) publish events when the LLM+// mutates news state. We subscribe while visible so the UI reflects the+// change without the user having to manually refresh. EventBus handlers+// can fire on a worker thread; we marshal to the screen's thread before+// touching the model/panel.++void NewsScreen::subscribe_mcp_events() {+ if (!mcp_event_subs_.isEmpty()) return; // idempotent++ QPointer<NewsScreen> self = this;+ auto on_monitors_changed = [self](const QVariantMap&) {+ if (!self) return;+ QMetaObject::invokeMethod(self.data(), [self]() {+ if (!self || !self->visible_) return;+ self->update_monitors();+ }, Qt::QueuedConnection);+ };+ auto on_refresh_requested = [self](const QVariantMap&) {+ if (!self) return;+ QMetaObject::invokeMethod(self.data(), [self]() {+ if (!self || !self->visible_) return;+ self->refresh_data(/*force=*/true);+ }, Qt::QueuedConnection);+ };++ auto& bus = EventBus::instance();+ mcp_event_subs_.append(bus.subscribe("news.monitor_added", on_monitors_changed));+ mcp_event_subs_.append(bus.subscribe("news.monitor_toggled", on_monitors_changed));+ mcp_event_subs_.append(bus.subscribe("news.monitor_deleted", on_monitors_changed));+ mcp_event_subs_.append(bus.subscribe("news.refresh_requested", on_refresh_requested));+}++void NewsScreen::unsubscribe_mcp_events() {+ auto& bus = EventBus::instance();+ for (auto id : mcp_event_subs_)+ bus.unsubscribe(id);+ mcp_event_subs_.clear();}// ── Slots ───────────────────────────────────────────────────────────────────diff --git a/fincept-qt/src/screens/news/NewsScreen.h b/fincept-qt/src/screens/news/NewsScreen.hindex 7a38c267f..f79e51a09 100644--- a/fincept-qt/src/screens/news/NewsScreen.h+++ b/fincept-qt/src/screens/news/NewsScreen.h@@ -1,4 +1,5 @@#pragma once+#include "core/events/EventBus.h"#include "core/symbol/IGroupLinked.h"#include "screens/IStatefulScreen.h"#include "services/news/NewsClusterService.h"@@ -7,6 +8,7 @@#include <QHBoxLayout>#include <QHideEvent>+#include <QList>#include <QSet>#include <QShowEvent>#include <QWidget>@@ -147,6 +149,16 @@ class NewsScreen : public QWidget, public IStatefulScreen, public IGroupLinked {// Symbol group link — SymbolGroup::None when unlinked.SymbolGroup link_group_ = SymbolGroup::None;++ // EventBus subscriptions — registered in showEvent, released in hideEvent.+ // MCP news tools publish news.monitor_added / news.monitor_toggled /+ // news.monitor_deleted / news.refresh_requested when the LLM mutates+ // monitor state via Finagent or AI Chat. Handlers may fire on a worker+ // thread; each callback marshals to this widget's thread before+ // touching UI state.+ QList<EventBus::HandlerId> mcp_event_subs_;+ void subscribe_mcp_events();+ void unsubscribe_mcp_events();};} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/notes/NotesScreen.cpp b/fincept-qt/src/screens/notes/NotesScreen.cppindex f1a345a51..1f4c2c456 100644--- a/fincept-qt/src/screens/notes/NotesScreen.cpp+++ b/fincept-qt/src/screens/notes/NotesScreen.cpp@@ -1,5 +1,6 @@#include "screens/notes/NotesScreen.h"+#include "core/events/EventBus.h"#include "core/logging/Logger.h"#include "core/session/ScreenStateManager.h"#include "services/file_manager/FileManagerService.h"@@ -12,6 +13,7 @@#include <QFrame>#include <QHBoxLayout>#include <QMessageBox>+#include <QPointer>#include <QRegularExpression>#include <QScrollArea>#include <QSplitter>@@ -727,4 +729,44 @@ void NotesScreen::restore_state(const QVariantMap& state) {}}+// ── Visibility lifecycle + MCP-driven UI sync ───────────────────────────────+// MCP notes tools publish notes.created / notes.deleted when the LLM mutates+// notes via AI Chat or Finagent. We subscribe while visible so the list+// reflects the change without manual refresh. EventBus handlers may fire+// on a worker thread; each callback marshals to the screen's thread.++void NotesScreen::showEvent(QShowEvent* event) {+ QWidget::showEvent(event);+ subscribe_mcp_events();+}++void NotesScreen::hideEvent(QHideEvent* event) {+ QWidget::hideEvent(event);+ unsubscribe_mcp_events();+}++void NotesScreen::subscribe_mcp_events() {+ if (!mcp_event_subs_.isEmpty()) return; // idempotent++ QPointer<NotesScreen> self = this;+ auto on_notes_changed = [self](const QVariantMap&) {+ if (!self) return;+ QMetaObject::invokeMethod(self.data(), [self]() {+ if (!self) return;+ self->load_notes();+ }, Qt::QueuedConnection);+ };++ auto& bus = EventBus::instance();+ mcp_event_subs_.append(bus.subscribe("notes.created", on_notes_changed));+ mcp_event_subs_.append(bus.subscribe("notes.deleted", on_notes_changed));+}++void NotesScreen::unsubscribe_mcp_events() {+ auto& bus = EventBus::instance();+ for (auto id : mcp_event_subs_)+ bus.unsubscribe(id);+ mcp_event_subs_.clear();+}+} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/notes/NotesScreen.h b/fincept-qt/src/screens/notes/NotesScreen.hindex 832d55d00..fd8ab9582 100644--- a/fincept-qt/src/screens/notes/NotesScreen.h+++ b/fincept-qt/src/screens/notes/NotesScreen.h@@ -1,12 +1,16 @@#pragma once+#include "core/events/EventBus.h"#include "screens/IStatefulScreen.h"#include "storage/repositories/NotesRepository.h"#include <QComboBox>+#include <QHideEvent>#include <QLabel>#include <QLineEdit>+#include <QList>#include <QListWidget>#include <QPushButton>+#include <QShowEvent>#include <QStackedWidget>#include <QTextEdit>#include <QWidget>@@ -25,6 +29,10 @@ class NotesScreen : public QWidget, public IStatefulScreen {QString state_key() const override { return "notes"; }int state_version() const override { return 1; }+ protected:+ void showEvent(QShowEvent* event) override;+ void hideEvent(QHideEvent* event) override;+private slots:void on_category_selected(int row);void on_note_selected(int row);@@ -78,6 +86,14 @@ class NotesScreen : public QWidget, public IStatefulScreen {QComboBox* edit_sentiment_ = nullptr;QLineEdit* edit_tags_ = nullptr;QLineEdit* edit_tickers_ = nullptr;++ // EventBus subscriptions — registered in showEvent, released in hideEvent.+ // MCP notes tools publish notes.created / notes.deleted when the LLM+ // mutates notes via Finagent or AI Chat. Each handler reloads the+ // notes list so the screen reflects the change immediately.+ QList<EventBus::HandlerId> mcp_event_subs_;+ void subscribe_mcp_events();+ void unsubscribe_mcp_events();};} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/settings/SettingsScreen.cpp b/fincept-qt/src/screens/settings/SettingsScreen.cppindex 7cb4929f8..df11b0f29 100644--- a/fincept-qt/src/screens/settings/SettingsScreen.cpp+++ b/fincept-qt/src/screens/settings/SettingsScreen.cpp@@ -21,6 +21,8 @@#include "screens/settings/VoiceConfigSection.h"#include "services/notifications/NotificationService.h"#include "services/stt/SpeechService.h"+#include "services/tts/TtsService.h"+#include "services/voice_trigger/ClapDetectorService.h"#include "storage/StorageManager.h"#include "storage/cache/CacheManager.h"#include "storage/repositories/DataSourceRepository.h"@@ -224,10 +226,22 @@ SettingsScreen::SettingsScreen(QWidget* parent) : QWidget(parent) {[]() { ai_chat::LlmService::instance().reload_config(); });}- // Wire Voice config changes → reload STT service (picks up provider / API key / model)+ // Wire Voice config changes — reload BOTH STT and TTS services and+ // restart the clap detector so the user's new provider / key / voice /+ // wake-trigger picks take effect on the next session.if (auto* voice = qobject_cast<VoiceConfigSection*>(sections_->widget(13))) {- connect(voice, &VoiceConfigSection::config_changed, this,- []() { fincept::services::SpeechService::instance().reload_config(); });+ connect(voice, &VoiceConfigSection::config_changed, this, []() {+ fincept::services::SpeechService::instance().reload_config();+ fincept::services::TtsService::instance().reload_config();++ // Apply the clap-to-start toggle live: stop the detector+ // unconditionally (in case mode/sensitivity changed) and+ // restart only if the toggle is on.+ auto& clap = fincept::services::ClapDetectorService::instance();+ clap.stop();+ if (fincept::services::ClapDetectorService::is_enabled_in_config())+ clap.start();+ });}connect(&ui::ThemeManager::instance(), &ui::ThemeManager::theme_changed, this,@@ -249,13 +263,66 @@ void SettingsScreen::refresh_theme() {void SettingsScreen::showEvent(QShowEvent* e) {QWidget::showEvent(e);+ reload_all_sections();+ subscribe_mcp_events();+}++void SettingsScreen::hideEvent(QHideEvent* e) {+ QWidget::hideEvent(e);+ unsubscribe_mcp_events();+}++void SettingsScreen::reload_all_sections() {load_credentials();load_appearance();load_notifications();load_security();refresh_storage_stats();- if (auto* llm = qobject_cast<LlmConfigSection*>(sections_->widget(5)))- llm->reload();+ if (sections_) {+ if (auto* llm = qobject_cast<LlmConfigSection*>(sections_->widget(5)))+ llm->reload();+ }+}++// ── MCP-driven UI sync ──────────────────────────────────────────────────────+// MCP settings tools publish settings.changed (with {key, value}) and+// llm.provider_changed (with {provider}). Both warrant a full reload —+// settings.changed could touch any section, and llm.provider_changed+// requires LlmConfigSection to refresh + the active LlmService to pick+// up the new provider.++void SettingsScreen::subscribe_mcp_events() {+ if (!mcp_event_subs_.isEmpty()) return; // idempotent++ QPointer<SettingsScreen> self = this;+ auto on_settings_changed = [self](const QVariantMap&) {+ if (!self) return;+ QMetaObject::invokeMethod(self.data(), [self]() {+ if (!self) return;+ self->reload_all_sections();+ }, Qt::QueuedConnection);+ };+ auto on_provider_changed = [self](const QVariantMap&) {+ if (!self) return;+ QMetaObject::invokeMethod(self.data(), [self]() {+ if (!self) return;+ self->reload_all_sections();+ // LlmService consumes the new active config; pick it up immediately+ // so the AiChatScreen subscriber (Phase 2.9) doesn't race.+ ai_chat::LlmService::instance().reload_config();+ }, Qt::QueuedConnection);+ };++ auto& bus = EventBus::instance();+ mcp_event_subs_.append(bus.subscribe("settings.changed", on_settings_changed));+ mcp_event_subs_.append(bus.subscribe("llm.provider_changed", on_provider_changed));+}++void SettingsScreen::unsubscribe_mcp_events() {+ auto& bus = EventBus::instance();+ for (auto id : mcp_event_subs_)+ bus.unsubscribe(id);+ mcp_event_subs_.clear();}// ── Shared helpers ────────────────────────────────────────────────────────────diff --git a/fincept-qt/src/screens/settings/SettingsScreen.h b/fincept-qt/src/screens/settings/SettingsScreen.hindex 825054e1b..3304c79cc 100644--- a/fincept-qt/src/screens/settings/SettingsScreen.h+++ b/fincept-qt/src/screens/settings/SettingsScreen.h@@ -1,12 +1,15 @@#pragma once+#include "core/events/EventBus.h"#include "screens/IStatefulScreen.h"#include <QCheckBox>#include <QComboBox>#include <QFrame>#include <QHash>+#include <QHideEvent>#include <QLabel>#include <QLineEdit>+#include <QList>#include <QListWidget>#include <QPushButton>#include <QStackedWidget>@@ -30,6 +33,7 @@ class SettingsScreen : public QWidget, public IStatefulScreen {protected:void showEvent(QShowEvent* e) override;+ void hideEvent(QHideEvent* e) override;private:QStackedWidget* sections_ = nullptr;@@ -139,6 +143,15 @@ class SettingsScreen : public QWidget, public IStatefulScreen {// ── Notification helpers ──────────────────────────────────────────────────void save_provider_fields(const QString& provider_id, const ProviderWidgets& pw);++ // ── MCP-driven UI sync ────────────────────────────────────────────────────+ // MCP settings tools publish settings.changed / llm.provider_changed when+ // the LLM mutates settings via Finagent or AI Chat. Subscribers are+ // active only while the screen is visible (P3 lifecycle).+ QList<EventBus::HandlerId> mcp_event_subs_;+ void subscribe_mcp_events();+ void unsubscribe_mcp_events();+ void reload_all_sections(); // shared reload logic — also called from showEvent};} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/settings/VoiceConfigSection.cpp b/fincept-qt/src/screens/settings/VoiceConfigSection.cppindex 9533cbefd..0764c9537 100644--- a/fincept-qt/src/screens/settings/VoiceConfigSection.cpp+++ b/fincept-qt/src/screens/settings/VoiceConfigSection.cpp@@ -1,13 +1,21 @@-// VoiceConfigSection.cpp — Voice / STT provider configuration panel.+// VoiceConfigSection.cpp — Voice / STT + TTS provider configuration panel.+//+// Two independent provider selectors share a single Deepgram credentials+// block. The credentials block is hidden entirely when neither provider is+// using Deepgram. STT/TTS-specific tunables are only shown when their+// respective provider is set to Deepgram.#include "screens/settings/VoiceConfigSection.h"#include "core/config/AppConfig.h"#include "core/logging/Logger.h"+#include "python/PythonSetupManager.h"#include "storage/secure/SecureStorage.h"#include "ui/theme/Theme.h"#include "ui/theme/ThemeManager.h"+#include <QDir>+#include <QFileInfo>#include <QFormLayout>#include <QFrame>#include <QHBoxLayout>@@ -25,7 +33,7 @@ namespace fincept::screens {static constexpr const char* TAG = "VoiceConfigSection";static constexpr const char* kSecureKey = "voice.deepgram.api_key";-// ── Style helpers (match SettingsScreen / LlmConfigSection look) ─────────────+// ── Style helpers ────────────────────────────────────────────────────────────static QString label_ss() {return QString("color:%1;background:transparent;").arg(ui::colors::TEXT_SECONDARY());@@ -34,18 +42,26 @@ static QString title_ss() {return QString("color:%1;font-weight:bold;letter-spacing:0.5px;background:transparent;").arg(ui::colors::AMBER());}+static QString subtitle_ss() {+ return QString("color:%1;font-weight:700;letter-spacing:0.5px;background:transparent;")+ .arg(ui::colors::TEXT_SECONDARY());+}static QString input_ss() {return QString("QLineEdit{background:%1;color:%2;border:1px solid %3;padding:6px;}"- "QLineEdit:focus{border:1px solid %4;}")- .arg(ui::colors::BG_RAISED(), ui::colors::TEXT_PRIMARY(), ui::colors::BORDER_MED(), ui::colors::AMBER());+ "QLineEdit:focus{border:1px solid %4;}"+ "QDoubleSpinBox{background:%1;color:%2;border:1px solid %3;padding:6px;}"+ "QDoubleSpinBox:focus{border:1px solid %4;}")+ .arg(ui::colors::BG_RAISED(), ui::colors::TEXT_PRIMARY(),+ ui::colors::BORDER_MED(), ui::colors::AMBER());}static QString combo_ss() {return QString(- "QComboBox{background:%1;color:%2;border:1px solid %3;padding:5px 8px;min-width:160px;}"+ "QComboBox{background:%1;color:%2;border:1px solid %3;padding:5px 8px;min-width:180px;}""QComboBox:focus{border:1px solid %4;}""QComboBox::drop-down{border:none;width:20px;}""QComboBox QAbstractItemView{background:%1;color:%2;selection-background-color:%5;border:1px solid %3;}")- .arg(ui::colors::BG_RAISED(), ui::colors::TEXT_PRIMARY(), ui::colors::BORDER_MED(), ui::colors::AMBER(),+ .arg(ui::colors::BG_RAISED(), ui::colors::TEXT_PRIMARY(),+ ui::colors::BORDER_MED(), ui::colors::AMBER(),ui::colors::BG_HOVER());}static QString btn_primary_ss() {@@ -56,7 +72,21 @@ static QString btn_primary_ss() {static QString btn_secondary_ss() {return QString("QPushButton{background:%1;color:%2;border:1px solid %3;padding:0 12px;height:32px;}""QPushButton:hover{background:%4;}")- .arg(ui::colors::BG_RAISED(), ui::colors::TEXT_PRIMARY(), ui::colors::BORDER_BRIGHT(), ui::colors::BG_HOVER());+ .arg(ui::colors::BG_RAISED(), ui::colors::TEXT_PRIMARY(),+ ui::colors::BORDER_BRIGHT(), ui::colors::BG_HOVER());+}++// Helper to build a labelled row [label | stretch | control].+static QWidget* labelled_row(const QString& label_text, QWidget* control) {+ auto* row = new QWidget;+ auto* hl = new QHBoxLayout(row);+ hl->setContentsMargins(0, 0, 0, 0);+ auto* lbl = new QLabel(label_text);+ lbl->setStyleSheet(label_ss());+ hl->addWidget(lbl);+ hl->addStretch();+ hl->addWidget(control);+ return row;}// ── Construction ─────────────────────────────────────────────────────────────@@ -81,42 +111,116 @@ void VoiceConfigSection::build_ui() {vl->setSpacing(14);// ── Title + blurb ────────────────────────────────────────────────────────- auto* title = new QLabel("VOICE / SPEECH-TO-TEXT");+ auto* title = new QLabel("VOICE — SPEECH-TO-TEXT & TEXT-TO-SPEECH");title->setStyleSheet(title_ss());vl->addWidget(title);auto* blurb = new QLabel(- "Configure the speech recognition engine used by the AI chat mic button.\n"- "Google is free but unauthenticated and often rate-limited. Deepgram offers "- "significantly better accuracy and supports financial keyword boosting.");+ "Pick a provider for each direction independently. Free options work "+ "out of the box; Deepgram requires an API key but offers higher accuracy "+ "(STT) and natural-sounding voices (TTS).");blurb->setStyleSheet(label_ss());blurb->setWordWrap(true);vl->addWidget(blurb);- // ── Provider selector ───────────────────────────────────────────────────- auto* prov_row = new QWidget;- auto* prov_hl = new QHBoxLayout(prov_row);- prov_hl->setContentsMargins(0, 0, 0, 0);- auto* prov_lbl = new QLabel("Provider");- prov_lbl->setStyleSheet(label_ss());- provider_combo_ = new QComboBox;- provider_combo_->setStyleSheet(combo_ss());- provider_combo_->addItem("Google (free, default)", "google");- provider_combo_->addItem("Deepgram (API key required)", "deepgram");- prov_hl->addWidget(prov_lbl);- prov_hl->addStretch();- prov_hl->addWidget(provider_combo_);- vl->addWidget(prov_row);-- // ── Deepgram group (hidden for Google) ───────────────────────────────────+ // ── STT provider ─────────────────────────────────────────────────────────+ auto* stt_section = new QLabel("SPEECH-TO-TEXT (microphone -> text)");+ stt_section->setStyleSheet(subtitle_ss());+ vl->addWidget(stt_section);++ stt_provider_combo_ = new QComboBox;+ stt_provider_combo_->setStyleSheet(combo_ss());+ stt_provider_combo_->addItem("Google (free, default)", "google");+ stt_provider_combo_->addItem("Deepgram (API key required)", "deepgram");+ vl->addWidget(labelled_row("Provider", stt_provider_combo_));++ // STT Deepgram-only rows+ stt_dg_group_ = new QWidget;+ auto* stt_dg_vl = new QVBoxLayout(stt_dg_group_);+ stt_dg_vl->setContentsMargins(0, 0, 0, 0);+ stt_dg_vl->setSpacing(10);++ stt_model_combo_ = new QComboBox;+ stt_model_combo_->setStyleSheet(combo_ss());+ stt_model_combo_->addItem("nova-3 (recommended)", "nova-3");+ stt_model_combo_->addItem("nova-2", "nova-2");+ stt_model_combo_->addItem("enhanced", "enhanced");+ stt_model_combo_->addItem("base", "base");+ stt_dg_vl->addWidget(labelled_row("STT Model", stt_model_combo_));++ stt_language_combo_ = new QComboBox;+ stt_language_combo_->setStyleSheet(combo_ss());+ stt_language_combo_->addItem("English (auto)", "en");+ stt_language_combo_->addItem("English (US)", "en-US");+ stt_language_combo_->addItem("English (UK)", "en-GB");+ stt_language_combo_->addItem("Multilingual (nova-3 only)", "multi");+ stt_dg_vl->addWidget(labelled_row("Language", stt_language_combo_));++ keyterms_edit_ = new QLineEdit;+ keyterms_edit_->setPlaceholderText("AAPL, BTCUSD, Nifty (comma-separated)");+ keyterms_edit_->setStyleSheet(input_ss());+ keyterms_edit_->setMinimumWidth(320);+ stt_dg_vl->addWidget(labelled_row("Key terms", keyterms_edit_));++ gain_spin_ = new QDoubleSpinBox;+ gain_spin_->setRange(1.0, 10.0);+ gain_spin_->setSingleStep(0.5);+ gain_spin_->setDecimals(1);+ gain_spin_->setSuffix("x");+ gain_spin_->setStyleSheet(input_ss());+ gain_spin_->setMinimumWidth(120);+ stt_dg_vl->addWidget(labelled_row("Mic gain (raise if mic is quiet)", gain_spin_));++ device_edit_ = new QLineEdit;+ device_edit_->setPlaceholderText("e.g. 'Headset' (substring match, blank = system default)");+ device_edit_->setStyleSheet(input_ss());+ device_edit_->setMinimumWidth(320);+ stt_dg_vl->addWidget(labelled_row("Mic device", device_edit_));++ vl->addWidget(stt_dg_group_);++ // ── TTS provider ─────────────────────────────────────────────────────────+ auto* tts_section = new QLabel("TEXT-TO-SPEECH (assistant reply -> spoken audio)");+ tts_section->setStyleSheet(subtitle_ss());+ vl->addWidget(tts_section);++ tts_provider_combo_ = new QComboBox;+ tts_provider_combo_->setStyleSheet(combo_ss());+ tts_provider_combo_->addItem("Free / pyttsx3 (offline, default)", "pyttsx3");+ tts_provider_combo_->addItem("Deepgram Aura-2 (API key required)", "deepgram");+ vl->addWidget(labelled_row("Provider", tts_provider_combo_));++ // TTS Deepgram-only rows+ tts_dg_group_ = new QWidget;+ auto* tts_dg_vl = new QVBoxLayout(tts_dg_group_);+ tts_dg_vl->setContentsMargins(0, 0, 0, 0);+ tts_dg_vl->setSpacing(10);++ tts_model_combo_ = new QComboBox;+ tts_model_combo_->setStyleSheet(combo_ss());+ // Aura-2 voice catalogue (subset — most popular). Format the label as+ // "Display name (gender)" so users know what they're picking.+ tts_model_combo_->addItem("Thalia — female, American", "aura-2-thalia-en");+ tts_model_combo_->addItem("Helena — female, American", "aura-2-helena-en");+ tts_model_combo_->addItem("Andromeda — female, American", "aura-2-andromeda-en");+ tts_model_combo_->addItem("Apollo — male, American", "aura-2-apollo-en");+ tts_model_combo_->addItem("Orion — male, American", "aura-2-orion-en");+ tts_model_combo_->addItem("Arcas — male, American", "aura-2-arcas-en");+ tts_model_combo_->addItem("Aurora — female, American", "aura-2-aurora-en");+ tts_model_combo_->addItem("Luna — female, American", "aura-2-luna-en");+ tts_model_combo_->addItem("Zeus — male, American", "aura-2-zeus-en");+ tts_dg_vl->addWidget(labelled_row("Voice", tts_model_combo_));++ vl->addWidget(tts_dg_group_);++ // ── Shared Deepgram credentials block ────────────────────────────────────deepgram_group_ = new QWidget;auto* dg_vl = new QVBoxLayout(deepgram_group_);dg_vl->setContentsMargins(0, 8, 0, 0);dg_vl->setSpacing(10);- auto* dg_title = new QLabel("DEEPGRAM SETTINGS");- dg_title->setStyleSheet(QString("color:%1;font-weight:700;letter-spacing:0.5px;background:transparent;")- .arg(ui::colors::TEXT_SECONDARY()));+ auto* dg_title = new QLabel("DEEPGRAM CREDENTIALS (shared by STT + TTS)");+ dg_title->setStyleSheet(subtitle_ss());dg_vl->addWidget(dg_title);// API key row with show/hide toggle@@ -139,63 +243,38 @@ void VoiceConfigSection::build_ui() {key_hl->addWidget(show_key_btn_);dg_vl->addWidget(key_row);- // Model dropdown- auto* model_row = new QWidget;- auto* model_hl = new QHBoxLayout(model_row);- model_hl->setContentsMargins(0, 0, 0, 0);- auto* model_lbl = new QLabel("Model");- model_lbl->setStyleSheet(label_ss());- model_combo_ = new QComboBox;- model_combo_->setStyleSheet(combo_ss());- model_combo_->addItem("nova-3 (recommended)", "nova-3");- model_combo_->addItem("nova-2", "nova-2");- model_combo_->addItem("enhanced", "enhanced");- model_combo_->addItem("base", "base");- model_hl->addWidget(model_lbl);- model_hl->addStretch();- model_hl->addWidget(model_combo_);- dg_vl->addWidget(model_row);-- // Language dropdown- auto* lang_row = new QWidget;- auto* lang_hl = new QHBoxLayout(lang_row);- lang_hl->setContentsMargins(0, 0, 0, 0);- auto* lang_lbl = new QLabel("Language");- lang_lbl->setStyleSheet(label_ss());- language_combo_ = new QComboBox;- language_combo_->setStyleSheet(combo_ss());- language_combo_->addItem("English (auto)", "en");- language_combo_->addItem("English (US)", "en-US");- language_combo_->addItem("English (UK)", "en-GB");- language_combo_->addItem("Multilingual (nova-3 only)", "multi");- lang_hl->addWidget(lang_lbl);- lang_hl->addStretch();- lang_hl->addWidget(language_combo_);- dg_vl->addWidget(lang_row);-- // Keyterms- auto* kt_row = new QWidget;- auto* kt_hl = new QHBoxLayout(kt_row);- kt_hl->setContentsMargins(0, 0, 0, 0);- auto* kt_lbl = new QLabel("Key terms");- kt_lbl->setStyleSheet(label_ss());- keyterms_edit_ = new QLineEdit;- keyterms_edit_->setPlaceholderText("AAPL, BTCUSD, Nifty (comma-separated)");- keyterms_edit_->setStyleSheet(input_ss());- keyterms_edit_->setMinimumWidth(320);- kt_hl->addWidget(kt_lbl);- kt_hl->addStretch();- kt_hl->addWidget(keyterms_edit_);- dg_vl->addWidget(kt_row);-- auto* kt_hint = new QLabel("Boosts recognition of financial symbols and proper nouns.");- kt_hint->setStyleSheet(label_ss());- kt_hint->setWordWrap(true);- dg_vl->addWidget(kt_hint);-vl->addWidget(deepgram_group_);- // ── Save / Test row ─────────────────────────────────────────────────────+ // ── Clap-to-start (independent — works with Google or Deepgram) ──────────+ auto* clap_section = new QLabel("WAKE TRIGGER");+ clap_section->setStyleSheet(subtitle_ss());+ vl->addWidget(clap_section);++ clap_enabled_cb_ = new QCheckBox("Clap to open mic");+ clap_enabled_cb_->setStyleSheet(QString("QCheckBox{color:%1;background:transparent;}"+ "QCheckBox::indicator{width:14px;height:14px;}"+ "QCheckBox::indicator:unchecked{border:1px solid %2;background:%3;}"+ "QCheckBox::indicator:checked{border:1px solid %4;background:%4;}")+ .arg(ui::colors::TEXT_PRIMARY(),+ ui::colors::BORDER_MED(),+ ui::colors::BG_RAISED(),+ ui::colors::AMBER()));+ vl->addWidget(clap_enabled_cb_);++ auto* clap_blurb = new QLabel(+ "Listens to the mic in the background and opens the chat bubble when "+ "you clap. Audio is analysed locally and never sent over the network.");+ clap_blurb->setStyleSheet(label_ss());+ clap_blurb->setWordWrap(true);+ vl->addWidget(clap_blurb);++ clap_mode_combo_ = new QComboBox;+ clap_mode_combo_->setStyleSheet(combo_ss());+ clap_mode_combo_->addItem("Double clap (recommended)", "double");+ clap_mode_combo_->addItem("Single clap (more reactive, more false positives)", "single");+ vl->addWidget(labelled_row("Trigger", clap_mode_combo_));++ // ── Save / Test row ──────────────────────────────────────────────────────auto* btn_row = new QWidget;auto* btn_hl = new QHBoxLayout(btn_row);btn_hl->setContentsMargins(0, 8, 0, 0);@@ -220,8 +299,10 @@ void VoiceConfigSection::build_ui() {scroll->setWidget(page);outer->addWidget(scroll);- // ── Wiring ──────────────────────────────────────────────────────────────- connect(provider_combo_, qOverload<int>(&QComboBox::currentIndexChanged),+ // ── Wiring ───────────────────────────────────────────────────────────────+ connect(stt_provider_combo_, qOverload<int>(&QComboBox::currentIndexChanged),+ this, &VoiceConfigSection::on_provider_changed);+ connect(tts_provider_combo_, qOverload<int>(&QComboBox::currentIndexChanged),this, &VoiceConfigSection::on_provider_changed);connect(show_key_btn_, &QPushButton::clicked, this, &VoiceConfigSection::on_show_hide_key);connect(save_btn_, &QPushButton::clicked, this, &VoiceConfigSection::on_save);@@ -233,36 +314,65 @@ void VoiceConfigSection::build_ui() {void VoiceConfigSection::reload() {auto& cfg = AppConfig::instance();- const QString provider = cfg.get("voice/provider", "google").toString().toLower();- const int idx = provider_combo_->findData(provider);- provider_combo_->setCurrentIndex(idx >= 0 ? idx : 0);+ // STT provider — read canonical key, fall back to legacy "voice/provider".+ QString stt = cfg.get("voice/stt/provider", "").toString().toLower();+ if (stt.isEmpty())+ stt = cfg.get("voice/provider", "google").toString().toLower();+ int idx = stt_provider_combo_->findData(stt);+ stt_provider_combo_->setCurrentIndex(idx >= 0 ? idx : 0);++ // TTS provider+ const QString tts = cfg.get("voice/tts/provider", "pyttsx3").toString().toLower();+ idx = tts_provider_combo_->findData(tts);+ tts_provider_combo_->setCurrentIndex(idx >= 0 ? idx : 0);- // API key from SecureStorage+ // Shared credentialsauto key_res = SecureStorage::instance().retrieve(kSecureKey);api_key_edit_->setText(key_res.is_ok() ? key_res.value() : QString());- const QString model = cfg.get("voice/deepgram/model", "nova-3").toString();- const int midx = model_combo_->findData(model);- model_combo_->setCurrentIndex(midx >= 0 ? midx : 0);+ // STT-Deepgram tunables+ const QString stt_model = cfg.get("voice/deepgram/model", "nova-3").toString();+ idx = stt_model_combo_->findData(stt_model);+ stt_model_combo_->setCurrentIndex(idx >= 0 ? idx : 0);const QString lang = cfg.get("voice/deepgram/language", "en").toString();- const int lidx = language_combo_->findData(lang);- language_combo_->setCurrentIndex(lidx >= 0 ? lidx : 0);+ idx = stt_language_combo_->findData(lang);+ stt_language_combo_->setCurrentIndex(idx >= 0 ? idx : 0);keyterms_edit_->setText(cfg.get("voice/deepgram/keyterms", "").toString());+ gain_spin_->setValue(cfg.get("voice/deepgram/gain", 3.0).toDouble());+ device_edit_->setText(cfg.get("voice/deepgram/device", "").toString());- apply_provider_visibility(provider);+ // TTS-Deepgram tunables+ const QString tts_model = cfg.get("voice/deepgram/tts_model", "aura-2-thalia-en").toString();+ idx = tts_model_combo_->findData(tts_model);+ tts_model_combo_->setCurrentIndex(idx >= 0 ? idx : 0);++ // Clap-to-start+ clap_enabled_cb_->setChecked(cfg.get("voice/clap_to_start/enabled", false).toBool());+ const QString clap_mode = cfg.get("voice/clap_to_start/mode", "double").toString();+ idx = clap_mode_combo_->findData(clap_mode);+ clap_mode_combo_->setCurrentIndex(idx >= 0 ? idx : 0);++ apply_provider_visibility();set_status({}, false);}-void VoiceConfigSection::apply_provider_visibility(const QString& provider) {- const bool is_dg = (provider == "deepgram");- deepgram_group_->setVisible(is_dg);- test_btn_->setVisible(is_dg);+void VoiceConfigSection::apply_provider_visibility() {+ const QString stt = stt_provider_combo_->currentData().toString();+ const QString tts = tts_provider_combo_->currentData().toString();+ const bool stt_dg = (stt == "deepgram");+ const bool tts_dg = (tts == "deepgram");+ const bool any_dg = stt_dg || tts_dg;++ stt_dg_group_->setVisible(stt_dg);+ tts_dg_group_->setVisible(tts_dg);+ deepgram_group_->setVisible(any_dg);+ test_btn_->setVisible(any_dg);}-void VoiceConfigSection::on_provider_changed(int /*index*/) {- apply_provider_visibility(provider_combo_->currentData().toString());+void VoiceConfigSection::on_provider_changed() {+ apply_provider_visibility();}void VoiceConfigSection::on_show_hide_key() {@@ -277,11 +387,23 @@ void VoiceConfigSection::on_show_hide_key() {void VoiceConfigSection::on_save() {auto& cfg = AppConfig::instance();- const QString provider = provider_combo_->currentData().toString();- cfg.set("voice/provider", provider);- cfg.set("voice/deepgram/model", model_combo_->currentData().toString());- cfg.set("voice/deepgram/language", language_combo_->currentData().toString());- cfg.set("voice/deepgram/keyterms", keyterms_edit_->text().trimmed());+ const QString stt = stt_provider_combo_->currentData().toString();+ const QString tts = tts_provider_combo_->currentData().toString();++ cfg.set("voice/stt/provider", stt);+ cfg.set("voice/tts/provider", tts);+ // Clear legacy key so it doesn't shadow future reads.+ cfg.set("voice/provider", stt);++ cfg.set("voice/deepgram/model", stt_model_combo_->currentData().toString());+ cfg.set("voice/deepgram/language", stt_language_combo_->currentData().toString());+ cfg.set("voice/deepgram/keyterms", keyterms_edit_->text().trimmed());+ cfg.set("voice/deepgram/gain", QString::number(gain_spin_->value(), 'f', 1));+ cfg.set("voice/deepgram/device", device_edit_->text().trimmed());+ cfg.set("voice/deepgram/tts_model", tts_model_combo_->currentData().toString());++ cfg.set("voice/clap_to_start/enabled", clap_enabled_cb_->isChecked());+ cfg.set("voice/clap_to_start/mode", clap_mode_combo_->currentData().toString());const QString api_key = api_key_edit_->text().trimmed();if (api_key.isEmpty()) {@@ -296,7 +418,7 @@ void VoiceConfigSection::on_save() {}}- LOG_INFO(TAG, QString("Voice config saved (provider=%1)").arg(provider));+ LOG_INFO(TAG, QString("Voice config saved (stt=%1 tts=%2)").arg(stt, tts));set_status(QStringLiteral("Saved. Changes apply on next voice session."), false);emit config_changed();}@@ -310,12 +432,37 @@ void VoiceConfigSection::on_test() {return;}+ // Step 1 — verify the Python SDK is installed in venv-numpy2 (only+ // matters for STT; TTS uses requests + pyaudio, which are already+ // present). Done via a filesystem probe of the venv site-packages.+ const QString stt = stt_provider_combo_->currentData().toString();+ if (stt == "deepgram") {+ const QString venv_root =+ python::PythonSetupManager::instance().install_dir() + "/venv-numpy2";+#ifdef _WIN32+ const QString sp = venv_root + "/Lib/site-packages/deepgram";+#else+ QString sp;+ QDir lib_dir(venv_root + "/lib");+ const auto py_dirs = lib_dir.entryList({"python3.*"}, QDir::Dirs);+ if (!py_dirs.isEmpty())+ sp = lib_dir.filePath(py_dirs.first()) + "/site-packages/deepgram";+#endif+ if (sp.isEmpty() || !QFileInfo::exists(sp)) {+ set_status(+ "Deepgram Python SDK is missing from venv-numpy2. "+ "Open Settings -> Python Env -> Reinstall packages, then test again.",+ true);+ return;+ }+ }+set_status("Testing Deepgram key…", false);test_btn_->setEnabled(false);// Lightweight verification: GET /v1/projects — succeeds iff the key is- // valid. No audio sent, no billing impact. QNetworkAccessManager scoped- // to this widget so it auto-cleans on destroy.+ // valid. No audio sent, no billing impact. Same key authorises both+ // /v1/listen (STT) and /v1/speak (TTS).auto* nam = new QNetworkAccessManager(this);QNetworkRequest req(QUrl("https://api.deepgram.com/v1/projects"));req.setRawHeader("Authorization", ("Token " + api_key).toUtf8());@@ -331,7 +478,7 @@ void VoiceConfigSection::on_test() {self->test_btn_->setEnabled(true);const int status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();if (reply->error() == QNetworkReply::NoError && status == 200) {- self->set_status("Deepgram key is valid.", false);+ self->set_status("Deepgram key is valid (STT + TTS available).", false);} else if (status == 401) {self->set_status("Invalid API key (401).", true);} else if (status == 402) {diff --git a/fincept-qt/src/screens/settings/VoiceConfigSection.h b/fincept-qt/src/screens/settings/VoiceConfigSection.hindex 63ff74e36..3575e638e 100644--- a/fincept-qt/src/screens/settings/VoiceConfigSection.h+++ b/fincept-qt/src/screens/settings/VoiceConfigSection.h@@ -1,11 +1,16 @@#pragma once-// VoiceConfigSection.h — Voice / speech-to-text provider configuration panel.+// VoiceConfigSection.h — Voice / speech configuration panel.//-// Provider switch (Google free vs Deepgram API) + Deepgram credentials &-// tuning. Lives alongside LlmConfigSection in the Settings screen.+// Two independent provider selectors:+// • Speech-to-Text (STT) — Google (free, default) | Deepgram+// • Text-to-Speech (TTS) — Pyttsx3 (free, default) | Deepgram (Aura-2)+//+// One shared Deepgram credentials block (API key + tunables) only shown when+// at least one of the two providers is set to Deepgram.#include <QCheckBox>#include <QComboBox>+#include <QDoubleSpinBox>#include <QLabel>#include <QLineEdit>#include <QPushButton>@@ -18,38 +23,56 @@ class VoiceConfigSection : public QWidget {public:explicit VoiceConfigSection(QWidget* parent = nullptr);- /// Called when section becomes visible — reloads values from- /// AppConfig and SecureStorage.+ /// Reload values from AppConfig and SecureStorage.void reload();signals:- /// Emitted after user saves — SpeechService picks up new config on- /// its next start_listening() call (no live restart needed).+ /// Emitted after Save — parent wires this to refresh both SpeechService+ /// and TtsService.void config_changed();private slots:- void on_provider_changed(int index);+ void on_provider_changed();void on_show_hide_key();void on_save();void on_test();private:void build_ui();- void apply_provider_visibility(const QString& provider);+ void apply_provider_visibility();void set_status(const QString& msg, bool error = false);- QComboBox* provider_combo_ = nullptr;+ // Provider selectors (independent)+ QComboBox* stt_provider_combo_ = nullptr;+ QComboBox* tts_provider_combo_ = nullptr;++ // Deepgram-shared credentialsQLineEdit* api_key_edit_ = nullptr;QPushButton* show_key_btn_ = nullptr;- QComboBox* model_combo_ = nullptr;- QComboBox* language_combo_ = nullptr;- QLineEdit* keyterms_edit_ = nullptr;++ // Deepgram STT tunables+ QComboBox* stt_model_combo_ = nullptr;+ QComboBox* stt_language_combo_ = nullptr;+ QLineEdit* keyterms_edit_ = nullptr;+ QDoubleSpinBox* gain_spin_ = nullptr;+ QLineEdit* device_edit_ = nullptr;++ // Deepgram TTS tunables+ QComboBox* tts_model_combo_ = nullptr;++ // Clap-to-start (independent of STT/TTS provider — works with any)+ QCheckBox* clap_enabled_cb_ = nullptr;+ QComboBox* clap_mode_combo_ = nullptr;++ // Action buttonsQPushButton* save_btn_ = nullptr;QPushButton* test_btn_ = nullptr;QLabel* status_lbl_ = nullptr;- // Deepgram-only rows, hidden when provider is Google- QWidget* deepgram_group_ = nullptr;+ // Container groups for visibility toggling+ QWidget* deepgram_group_ = nullptr; // shared key + buttons+ QWidget* stt_dg_group_ = nullptr; // Deepgram STT-only rows+ QWidget* tts_dg_group_ = nullptr; // Deepgram TTS-only rows};} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/watchlist/WatchlistScreen.cpp b/fincept-qt/src/screens/watchlist/WatchlistScreen.cppindex def7d5d9a..42a7d938d 100644--- a/fincept-qt/src/screens/watchlist/WatchlistScreen.cpp+++ b/fincept-qt/src/screens/watchlist/WatchlistScreen.cpp@@ -1,5 +1,6 @@#include "screens/watchlist/WatchlistScreen.h"+#include "core/events/EventBus.h"#include "core/logging/Logger.h"#include "core/session/ScreenStateManager.h"#include "core/symbol/SymbolContext.h"@@ -14,6 +15,7 @@#include <QHideEvent>#include <QInputDialog>#include <QMessageBox>+#include <QPointer>#include <QShowEvent>#include <QSplitter>#include <QVBoxLayout>@@ -113,11 +115,47 @@ void WatchlistScreen::showEvent(QShowEvent* event) {QWidget::showEvent(event);if (!current_wl_id_.isEmpty() && !stocks_.isEmpty())hub_resubscribe_stocks();+ subscribe_mcp_events();}void WatchlistScreen::hideEvent(QHideEvent* event) {QWidget::hideEvent(event);hub_unsubscribe_all();+ unsubscribe_mcp_events();+}++// ── MCP-driven UI sync ──────────────────────────────────────────────────────+// MCP watchlist tools publish watchlist.created / watchlist.deleted /+// watchlist.updated when the LLM mutates watchlists via AI Chat or+// Finagent. We always reload from DB — the events carry only id/symbol,+// not enough to update the table incrementally.++void WatchlistScreen::subscribe_mcp_events() {+ if (!mcp_event_subs_.isEmpty()) return; // idempotent++ QPointer<WatchlistScreen> self = this;+ auto on_watchlists_changed = [self](const QVariantMap&) {+ if (!self) return;+ QMetaObject::invokeMethod(self.data(), [self]() {+ if (!self) return;+ self->load_watchlists();+ // load_watchlists() preserves current_wl_id_ where possible;+ // load_stocks() reloads the right-pane table.+ self->load_stocks();+ }, Qt::QueuedConnection);+ };++ auto& bus = EventBus::instance();+ mcp_event_subs_.append(bus.subscribe("watchlist.created", on_watchlists_changed));+ mcp_event_subs_.append(bus.subscribe("watchlist.deleted", on_watchlists_changed));+ mcp_event_subs_.append(bus.subscribe("watchlist.updated", on_watchlists_changed));+}++void WatchlistScreen::unsubscribe_mcp_events() {+ auto& bus = EventBus::instance();+ for (auto id : mcp_event_subs_)+ bus.unsubscribe(id);+ mcp_event_subs_.clear();}void WatchlistScreen::build_ui() {diff --git a/fincept-qt/src/screens/watchlist/WatchlistScreen.h b/fincept-qt/src/screens/watchlist/WatchlistScreen.hindex e88749199..8de253703 100644--- a/fincept-qt/src/screens/watchlist/WatchlistScreen.h+++ b/fincept-qt/src/screens/watchlist/WatchlistScreen.h@@ -1,4 +1,5 @@#pragma once+#include "core/events/EventBus.h"#include "core/symbol/IGroupLinked.h"#include "screens/IStatefulScreen.h"#include "services/markets/MarketDataService.h"@@ -9,6 +10,7 @@#include <QHideEvent>#include <QLabel>#include <QLineEdit>+#include <QList>#include <QListWidget>#include <QPushButton>#include <QShowEvent>@@ -100,6 +102,14 @@ class WatchlistScreen : public QWidget, public IStatefulScreen, public IGroupLin// Emit the currently-selected symbol into the linked group, if any.// Safe to call with no selection — no-op.void publish_selection_to_group();++ // EventBus subscriptions — registered in showEvent, released in hideEvent.+ // MCP watchlist tools publish watchlist.created / .deleted / .updated when+ // the LLM mutates watchlists via Finagent or AI Chat. Each handler+ // reloads watchlists + the current stock list.+ QList<EventBus::HandlerId> mcp_event_subs_;+ void subscribe_mcp_events();+ void unsubscribe_mcp_events();};} // namespace fincept::screensdiff --git a/fincept-qt/src/services/geopolitics/GeopoliticsService.cpp b/fincept-qt/src/services/geopolitics/GeopoliticsService.cppindex 60d6d6859..dffd26a1a 100644--- a/fincept-qt/src/services/geopolitics/GeopoliticsService.cpp+++ b/fincept-qt/src/services/geopolitics/GeopoliticsService.cpp@@ -48,88 +48,133 @@ void GeopoliticsService::run_python(const QString& script, const QStringList& ar// CONFLICT MONITOR — HTTP API// ═══════════════════════════════════════════════════════════════════════════════-void GeopoliticsService::fetch_events(const QString& country, const QString& city, const QString& category, int limit) {- // Build URL with query params+void GeopoliticsService::fetch_events(const QString& country, const QString& city, const QString& category,+ int limit, int page, const QString& source,+ const QString& date_from, const QString& date_to) {QUrl url(kApiBase);QUrlQuery q;- if (!country.isEmpty())- q.addQueryItem("country", country);- if (!city.isEmpty())- q.addQueryItem("city", city);- if (!category.isEmpty())- q.addQueryItem("event_category", category);+ if (!country.isEmpty()) q.addQueryItem("country", country);+ if (!city.isEmpty()) q.addQueryItem("city", city);+ if (!category.isEmpty()) q.addQueryItem("event_category", category);+ if (!source.isEmpty()) q.addQueryItem("source", source);+ if (!date_from.isEmpty()) q.addQueryItem("date_from", date_from);+ if (!date_to.isEmpty()) q.addQueryItem("date_to", date_to);q.addQueryItem("limit", QString::number(limit));+ if (page > 1)+ q.addQueryItem("page", QString::number(page));url.setQuery(q);QPointer<GeopoliticsService> self = this;- HttpClient::instance().get(url.toString(), [self, country, city, category, limit](Result<QJsonDocument> result) {- if (!self)- return;- if (!result.is_ok()) {- LOG_ERROR("Geopolitics", "Events fetch failed: " + QString::fromStdString(result.error()));- emit self->error_occurred("events", QString::fromStdString(result.error()));- return;- }- auto root = result.value().object();- // API returns {success, message, data: {events: [...], pagination: {...}}}- auto obj = root.contains("data") ? root["data"].toObject() : root;- auto arr = obj["events"].toArray();- QVector<NewsEvent> events;- events.reserve(arr.size());- for (const auto& v : arr) {- auto e = v.toObject();- NewsEvent ev;- ev.url = e["url"].toString();- ev.source = e["source"].toString();- ev.event_category = e["event_category"].toString();- ev.title = e["title"].toString();- ev.city = e["city"].toString();- ev.country = e["country"].toString();- const auto lat_v = e["latitude"];- const auto lng_v = e["longitude"];- ev.has_coords = lat_v.isDouble() && lng_v.isDouble();- ev.latitude = ev.has_coords ? lat_v.toDouble() : 0.0;- ev.longitude = ev.has_coords ? lng_v.toDouble() : 0.0;- ev.extracted_date = e["extracted_date"].toString();- ev.created_at = e["created_at"].toString();- events.append(ev);- }- // Pagination envelope replaces the old flat "total" field- int total = events.size();- if (obj.contains("pagination"))- total = obj["pagination"].toObject()["total_events"].toInt(total);- else if (obj.contains("total"))- total = obj["total"].toInt(total);- // Serialize events to JSON for CacheManager persistence- QJsonArray cached_arr;- for (const auto& ev : events) {- QJsonObject o;- o["url"] = ev.url;- o["source"] = ev.source;- o["event_category"] = ev.event_category;- o["title"] = ev.title;- o["city"] = ev.city;- o["country"] = ev.country;- if (ev.has_coords) {- o["latitude"] = ev.latitude;- o["longitude"] = ev.longitude;+ HttpClient::instance().get(+ url.toString(),+ [self, country, city, category, limit, page](Result<QJsonDocument> result) {+ if (!self)+ return;+ if (!result.is_ok()) {+ LOG_ERROR("Geopolitics", "Events fetch failed: " + QString::fromStdString(result.error()));+ emit self->error_occurred("events", QString::fromStdString(result.error()));+ return;}- o["extracted_date"] = ev.extracted_date;- o["created_at"] = ev.created_at;- cached_arr.append(o);- }- QJsonObject cached_root;- cached_root["events"] = cached_arr;- cached_root["total"] = total;- const QString cache_key = QString("geo:events:%1:%2:%3:%4").arg(country, city, category).arg(limit);- fincept::CacheManager::instance().put(cache_key,- QVariant(QJsonDocument(cached_root).toJson(QJsonDocument::Compact)),- kEventsTtlSec, "geopolitics");- LOG_INFO("Geopolitics", QString("Loaded %1 events").arg(events.size()));- emit self->events_loaded(events, total);- if (self->hub_registered_)- publish_to_hub(QStringLiteral("geopolitics:events"), QVariant::fromValue(events));- });+ // Response envelope:+ // {success, message, data: {events:[...], pagination:{...},+ // filters_applied:{...},+ // credits_used:N, remaining_credits:N}}+ const auto root = result.value().object();+ const auto obj = root.contains("data") ? root["data"].toObject() : root;+ const auto arr = obj["events"].toArray();++ EventsPage page_data;+ page_data.events.reserve(arr.size());+ for (const auto& v : arr) {+ const auto e = v.toObject();+ NewsEvent ev;+ ev.url = e["url"].toString();+ ev.source = e["source"].toString();+ ev.event_category = e["event_category"].toString();+ ev.title = e["title"].toString();+ ev.city = e["city"].toString();+ ev.country = e["country"].toString();+ const auto lat_v = e["latitude"];+ const auto lng_v = e["longitude"];+ ev.has_coords = lat_v.isDouble() && lng_v.isDouble();+ ev.latitude = ev.has_coords ? lat_v.toDouble() : 0.0;+ ev.longitude = ev.has_coords ? lng_v.toDouble() : 0.0;+ ev.extracted_date = e["extracted_date"].toString();+ ev.created_at = e["created_at"].toString();+ page_data.events.append(ev);+ }++ // Newest first — extracted_date is "YYYY-MM-DD HH:MM:SS" so plain+ // string comparison is lexicographically correct.+ std::sort(page_data.events.begin(), page_data.events.end(),+ [](const NewsEvent& a, const NewsEvent& b) {+ return a.extracted_date > b.extracted_date;+ });++ if (obj.contains("pagination")) {+ const auto p = obj["pagination"].toObject();+ page_data.total_events = p["total_events"].toInt(page_data.events.size());+ page_data.current_page = p["current_page"].toInt(page);+ page_data.total_pages = p["total_pages"].toInt(0);+ page_data.events_per_page = p["events_per_page"].toInt(limit);+ page_data.has_next = p["has_next"].toBool(false);+ page_data.has_prev = p["has_prev"].toBool(false);+ } else {+ page_data.total_events = obj["total"].toInt(page_data.events.size());+ page_data.current_page = page;+ page_data.events_per_page = limit;+ }+ page_data.credits_used = obj["credits_used"].toDouble(0.0);+ page_data.remaining_credits = obj["remaining_credits"].toInt(-1);++ // Cache the (already-sorted) events for offline replay.+ QJsonArray cached_arr;+ for (const auto& ev : page_data.events) {+ QJsonObject o;+ o["url"] = ev.url;+ o["source"] = ev.source;+ o["event_category"] = ev.event_category;+ o["title"] = ev.title;+ o["city"] = ev.city;+ o["country"] = ev.country;+ if (ev.has_coords) {+ o["latitude"] = ev.latitude;+ o["longitude"] = ev.longitude;+ }+ o["extracted_date"] = ev.extracted_date;+ o["created_at"] = ev.created_at;+ cached_arr.append(o);+ }+ QJsonObject cached_root;+ cached_root["events"] = cached_arr;+ cached_root["total_events"] = page_data.total_events;+ cached_root["current_page"] = page_data.current_page;+ cached_root["total_pages"] = page_data.total_pages;+ cached_root["events_per_page"] = page_data.events_per_page;+ cached_root["has_next"] = page_data.has_next;+ cached_root["has_prev"] = page_data.has_prev;+ cached_root["credits_used"] = page_data.credits_used;+ cached_root["remaining_credits"] = page_data.remaining_credits;+ const QString cache_key = QString("geo:events:%1:%2:%3:%4:%5")+ .arg(country, city, category)+ .arg(limit)+ .arg(page);+ fincept::CacheManager::instance().put(+ cache_key,+ QVariant(QJsonDocument(cached_root).toJson(QJsonDocument::Compact)),+ kEventsTtlSec, "geopolitics");++ LOG_INFO("Geopolitics", QString("Loaded %1 events (page %2/%3, total %4, %5 credits left)")+ .arg(page_data.events.size())+ .arg(page_data.current_page)+ .arg(page_data.total_pages)+ .arg(page_data.total_events)+ .arg(page_data.remaining_credits));++ emit self->events_loaded(page_data);+ if (self->hub_registered_)+ publish_to_hub(QStringLiteral("geopolitics:events"), QVariant::fromValue(page_data));+ });}void GeopoliticsService::fetch_unique_countries() {diff --git a/fincept-qt/src/services/geopolitics/GeopoliticsService.h b/fincept-qt/src/services/geopolitics/GeopoliticsService.hindex 6f771065a..2e4ff1c58 100644--- a/fincept-qt/src/services/geopolitics/GeopoliticsService.h+++ b/fincept-qt/src/services/geopolitics/GeopoliticsService.h@@ -28,8 +28,14 @@ class GeopoliticsService : public QObjectint max_requests_per_sec() const override;// ── Conflict Monitor (HTTP API) ─────────────────────────────────────────+ //+ // The Fincept news-events endpoint now supports pagination + extra+ // filters echoed in `filters_applied`. `limit` maps to events_per_page,+ // `page` is 1-indexed. `source`, `date_from`, `date_to` are forwarded+ // verbatim — server validates and ignores empty values.void fetch_events(const QString& country = {}, const QString& city = {}, const QString& category = {},- int limit = 100);+ int limit = 100, int page = 1, const QString& source = {},+ const QString& date_from = {}, const QString& date_to = {});void fetch_unique_countries();void fetch_unique_categories();void fetch_unique_cities();@@ -49,7 +55,7 @@ class GeopoliticsService : public QObjectvoid extract_geolocations(const QStringList& headlines);signals:- void events_loaded(QVector<fincept::services::geo::NewsEvent> events, int total);+ void events_loaded(fincept::services::geo::EventsPage page);void countries_loaded(QVector<fincept::services::geo::UniqueCountry> countries);void categories_loaded(QVector<fincept::services::geo::UniqueCategory> categories);void cities_loaded(QStringList cities);diff --git a/fincept-qt/src/services/geopolitics/GeopoliticsTypes.h b/fincept-qt/src/services/geopolitics/GeopoliticsTypes.hindex 9f5a87197..3cae1ffde 100644--- a/fincept-qt/src/services/geopolitics/GeopoliticsTypes.h+++ b/fincept-qt/src/services/geopolitics/GeopoliticsTypes.h@@ -23,26 +23,49 @@ struct NewsEvent {QString created_at;};+/// Convert an API category id ("armed_conflict_unclassified") into a display+/// label ("Armed Conflict (Unclassified)"). Used everywhere the category is+/// shown to the user — table cells, detail panel, legend, dropdown.+inline QString pretty_category(const QString& cat) {+ QString base = cat;+ bool unclassified = false;+ if (base.endsWith(QStringLiteral("_unclassified"))) {+ base.chop(13);+ unclassified = true;+ }+ QStringList parts = base.split(QLatin1Char('_'), Qt::SkipEmptyParts);+ for (auto& p : parts)+ if (!p.isEmpty()) p[0] = p[0].toUpper();+ QString out = parts.join(QLatin1Char(' '));+ if (unclassified) out += QStringLiteral(" (Unclassified)");+ return out;+}+inline QColor category_color(const QString& cat) {- if (cat == "armed_conflict")- return QColor(255, 0, 0);- if (cat == "terrorism")- return QColor(255, 69, 0);- if (cat == "protests")- return QColor(255, 215, 0);- if (cat == "civilian_violence")- return QColor(255, 100, 100);- if (cat == "riots")- return QColor(255, 165, 0);- if (cat == "political_violence")- return QColor(147, 51, 234);- if (cat == "crisis")- return QColor(0, 229, 255);- if (cat == "explosions")- return QColor(255, 20, 147);- if (cat == "strategic")- return QColor(100, 149, 237);- return QColor(136, 136, 136); // unclassified+ // API returns *_unclassified variants — map them to the same colour as the+ // base category so the legend / map / table stay coherent.+ QString base = cat;+ if (base.endsWith(QStringLiteral("_unclassified")))+ base.chop(13);++ if (base == QStringLiteral("armed_conflict")) return QColor(255, 0, 0);+ if (base == QStringLiteral("terrorism")) return QColor(255, 69, 0);+ if (base == QStringLiteral("protests")) return QColor(255, 215, 0);+ if (base == QStringLiteral("civilian_violence")) return QColor(255, 100, 100);+ if (base == QStringLiteral("riots")) return QColor(255, 165, 0);+ if (base == QStringLiteral("political_violence")) return QColor(147, 51, 234);+ if (base == QStringLiteral("crisis")) return QColor( 0, 229, 255);+ if (base == QStringLiteral("explosions")) return QColor(255, 20, 147);+ if (base == QStringLiteral("strategic")) return QColor(100, 149, 237);+ if (base == QStringLiteral("diplomacy") ||+ base == QStringLiteral("diplomatic")) return QColor(167, 139, 250);+ if (base == QStringLiteral("maritime")) return QColor( 56, 189, 248);+ if (base == QStringLiteral("elections")) return QColor( 34, 197, 94);+ if (base == QStringLiteral("sanctions")) return QColor(251, 146, 60);+ if (base == QStringLiteral("nuclear")) return QColor(250, 204, 21);+ if (base == QStringLiteral("cyber")) return QColor( 20, 184, 166);+ if (base == QStringLiteral("not_geopol")) return QColor(100, 100, 100);+ return QColor(136, 136, 136);}// ── HDX dataset ─────────────────────────────────────────────────────────────@@ -70,6 +93,24 @@ struct UniqueCategory {int event_count = 0;};+// ── Events page (response envelope from /research/news-events) ──────────────+//+// The Fincept API now wraps every events response with pagination and credit+// metering. Consumers should treat this struct as the unit of delivery instead+// of separate (events, total) tuples.++struct EventsPage {+ QVector<NewsEvent> events;+ int total_events = 0;+ int current_page = 1;+ int total_pages = 0;+ int events_per_page = 0;+ bool has_next = false;+ bool has_prev = false;+ double credits_used = 0.0;+ int remaining_credits = -1; // -1 = unknown / not reported+};+// ── Relationship map node ───────────────────────────────────────────────────struct RelationshipNode {@@ -88,13 +129,6 @@ inline QStringList critical_regions() {"Myanmar", "Ethiopia", "Haiti", "Somalia", "Venezuela"};}-// ── Event categories ────────────────────────────────────────────────────────--inline QStringList event_categories() {- return {"armed_conflict", "terrorism", "protests", "civilian_violence", "riots",- "political_violence", "crisis", "explosions", "strategic"};-}-} // namespace fincept::services::geo#include <QMetaType>@@ -102,6 +136,7 @@ Q_DECLARE_METATYPE(fincept::services::geo::NewsEvent)Q_DECLARE_METATYPE(fincept::services::geo::HDXDataset)Q_DECLARE_METATYPE(fincept::services::geo::UniqueCountry)Q_DECLARE_METATYPE(fincept::services::geo::UniqueCategory)+Q_DECLARE_METATYPE(fincept::services::geo::EventsPage)Q_DECLARE_METATYPE(QVector<fincept::services::geo::NewsEvent>)Q_DECLARE_METATYPE(QVector<fincept::services::geo::HDXDataset>)Q_DECLARE_METATYPE(QVector<fincept::services::geo::UniqueCountry>)diff --git a/fincept-qt/src/services/maritime/MaritimeService.cpp b/fincept-qt/src/services/maritime/MaritimeService.cppindex 5bfb23d46..9f06489a5 100644--- a/fincept-qt/src/services/maritime/MaritimeService.cpp+++ b/fincept-qt/src/services/maritime/MaritimeService.cpp@@ -61,24 +61,112 @@ static QJsonObject unwrap(const QJsonObject& root) {return root;}-// ── Area search (uses multi-vessel with well-known port IMOs) ────────────────+// ── Area search — POST /marine/vessel/area-search (8 credits/call) ──────────+//+// Returns every vessel whose last known position lies inside the bounding box.+// Costly (8 credits) and unbounded — large boxes can return 10k+ vessels.+// The response shape is:+// {data: {search_area:{...}, vessels:[...], vessel_count:N,+// credits_used:N, remaining_credits:N}}+void MaritimeService::search_vessels_by_area(const AreaSearchParams& params) {- Q_UNUSED(params);- // The API doesn't have an area-search endpoint.- // Use multi-vessel with a set of well-known container ship IMOs instead.- static const QStringList known_imos = {- "9893890", // EVER ACE- "9461867", // APL CHONGQING- "9811000", // MSC GULSUN- "9839430", // MSC TESSA- "9795622", // HMM ALGECIRAS- "9484525", // COSCO SHIPPING UNIVERSE- "9706891", // ONE APRICOT- "9732319", // MAERSK EDINBURGH- "9758098", // CMA CGM ANTOINE- "9778791", // EVER GOLDEN- };- get_multi_vessel_positions(known_imos);+ QJsonObject body;+ body["min_lat"] = params.min_lat;+ body["max_lat"] = params.max_lat;+ body["min_lng"] = params.min_lng;+ body["max_lng"] = params.max_lng;+ if (params.days_ago > 0)+ body["days_ago"] = params.days_ago;++ const QString cache_key = QString("maritime:area:%1:%2:%3:%4:%5")+ .arg(params.min_lat).arg(params.max_lat)+ .arg(params.min_lng).arg(params.max_lng)+ .arg(params.days_ago);+ const QVariant cached = fincept::CacheManager::instance().get(cache_key);+ if (!cached.isNull()) {+ const QJsonObject root = QJsonDocument::fromJson(cached.toString().toUtf8()).object();+ VesselsPage page;+ const QJsonArray arr = root["vessels"].toArray();+ page.vessels.reserve(arr.size());+ for (const auto& v : arr)+ page.vessels.append(parse_vessel(v.toObject()));+ page.total_count = root["total_count"].toInt(page.vessels.size());+ page.credits_used = root["credits_used"].toDouble(0.0);+ page.remaining_credits = root["remaining_credits"].toInt(-1);+ emit vessels_loaded(page);+ return;+ }++ QPointer<MaritimeService> self = this;+ HttpClient::instance().post(+ QString(kMarineBase) + "/vessel/area-search", body,+ [self, cache_key](Result<QJsonDocument> result) {+ if (!self)+ return;+ if (!result.is_ok()) {+ LOG_ERROR("Maritime", "Area search failed: " + QString::fromStdString(result.error()));+ emit self->error_occurred("area_search", QString::fromStdString(result.error()));+ return;+ }+ const auto data = unwrap(result.value().object());+ const auto vessels_arr = data["vessels"].toArray();++ VesselsPage page;+ page.vessels.reserve(vessels_arr.size());+ for (const auto& v : vessels_arr)+ page.vessels.append(self->parse_vessel(v.toObject()));++ // Newest position first — last_pos_updated_at is ISO-8601 so plain+ // string compare gives correct lexicographic ordering.+ std::sort(page.vessels.begin(), page.vessels.end(),+ [](const VesselData& a, const VesselData& b) {+ return a.last_updated > b.last_updated;+ });++ page.total_count = data["vessel_count"].toInt(page.vessels.size());+ page.credits_used = data["credits_used"].toDouble(0.0);+ page.remaining_credits = data["remaining_credits"].toInt(-1);++ // Cache the (already-sorted) vessels + envelope.+ QJsonArray cached_arr;+ for (const auto& v : page.vessels) {+ QJsonObject o;+ o["id"] = v.id;+ o["imo"] = v.imo;+ o["name"] = v.name;+ o["last_pos_latitude"] = QString::number(v.latitude, 'f', 8);+ o["last_pos_longitude"] = QString::number(v.longitude, 'f', 8);+ o["last_pos_speed"] = QString::number(v.speed);+ o["last_pos_angle"] = QString::number(v.angle);+ o["route_from_port_name"] = v.from_port;+ o["route_to_port_name"] = v.to_port;+ o["route_from_date"] = v.from_date;+ o["route_to_date"] = v.to_date;+ o["route_progress"] = QString::number(v.route_progress);+ o["current_draught"] = QString::number(v.draught);+ o["last_pos_updated_at"] = v.last_updated;+ o["fetched_at"] = v.fetched_at;+ cached_arr.append(o);+ }+ QJsonObject cached_root;+ cached_root["vessels"] = cached_arr;+ cached_root["total_count"] = page.total_count;+ cached_root["credits_used"] = page.credits_used;+ cached_root["remaining_credits"] = page.remaining_credits;+ fincept::CacheManager::instance().put(+ cache_key,+ QVariant(QString::fromUtf8(QJsonDocument(cached_root).toJson(QJsonDocument::Compact))),+ kVesselTtlSec, "maritime");++ LOG_INFO("Maritime", QString("Area search: %1 vessels (total %2, %3 credits left)")+ .arg(page.vessels.size())+ .arg(page.total_count)+ .arg(page.remaining_credits));++ emit self->vessels_loaded(page);+ if (self->hub_registered_)+ publish_to_hub(QStringLiteral("maritime:vessels:area"), QVariant::fromValue(page));+ });}// ── Single vessel position ───────────────────────────────────────────────────@@ -129,12 +217,19 @@ void MaritimeService::get_multi_vessel_positions(const QStringList& imos) {const QString cache_key = "maritime:multi:" + sorted.join(",");const QVariant cached = fincept::CacheManager::instance().get(cache_key);if (!cached.isNull()) {- QJsonArray vessels_arr = QJsonDocument::fromJson(cached.toString().toUtf8()).array();- QVector<VesselData> vessels;- vessels.reserve(vessels_arr.size());- for (const auto& v : vessels_arr)- vessels.append(parse_vessel(v.toObject()));- emit vessels_loaded(vessels, vessels.size());+ const QJsonObject root = QJsonDocument::fromJson(cached.toString().toUtf8()).object();+ VesselsPage page;+ const QJsonArray arr = root["vessels"].toArray();+ page.vessels.reserve(arr.size());+ for (const auto& v : arr)+ page.vessels.append(parse_vessel(v.toObject()));+ page.total_count = root["found_count"].toInt(page.vessels.size());+ page.found_count = page.total_count;+ for (const auto& nf : root["not_found"].toArray())+ page.not_found.append(nf.toString());+ page.credits_used = root["credits_used"].toDouble(0.0);+ page.remaining_credits = root["remaining_credits"].toInt(-1);+ emit vessels_loaded(page);return;}@@ -154,42 +249,89 @@ void MaritimeService::get_multi_vessel_positions(const QStringList& imos) {emit self->error_occurred("multi_vessel", QString::fromStdString(result.error()));return;}- auto data = unwrap(result.value().object());- auto vessels_arr = data["vessels"].toArray();+ const auto data = unwrap(result.value().object());+ const auto vessels_arr = data["vessels"].toArray();++ VesselsPage page;+ page.vessels.reserve(vessels_arr.size());+ for (const auto& v : vessels_arr)+ page.vessels.append(self->parse_vessel(v.toObject()));++ std::sort(page.vessels.begin(), page.vessels.end(),+ [](const VesselData& a, const VesselData& b) {+ return a.last_updated > b.last_updated;+ });++ page.found_count = data["found_count"].toInt(page.vessels.size());+ page.total_count = page.found_count;+ for (const auto& nf : data["not_found"].toArray())+ page.not_found.append(nf.toString());+ page.credits_used = data["credits_used"].toDouble(0.0);+ page.remaining_credits = data["remaining_credits"].toInt(-1);++ // Cache the full envelope so cached replays carry not_found etc.+ QJsonArray cached_arr;+ for (const auto& v : page.vessels) {+ QJsonObject o;+ o["id"] = v.id;+ o["imo"] = v.imo;+ o["name"] = v.name;+ o["last_pos_latitude"] = QString::number(v.latitude, 'f', 8);+ o["last_pos_longitude"] = QString::number(v.longitude, 'f', 8);+ o["last_pos_speed"] = QString::number(v.speed);+ o["last_pos_angle"] = QString::number(v.angle);+ o["route_from_port_name"] = v.from_port;+ o["route_to_port_name"] = v.to_port;+ o["route_progress"] = QString::number(v.route_progress);+ o["last_pos_updated_at"] = v.last_updated;+ cached_arr.append(o);+ }+ QJsonObject cached_root;+ cached_root["vessels"] = cached_arr;+ cached_root["found_count"] = page.found_count;+ cached_root["not_found"] = QJsonArray::fromStringList(page.not_found);+ cached_root["credits_used"] = page.credits_used;+ cached_root["remaining_credits"] = page.remaining_credits;fincept::CacheManager::instance().put(- cache_key, QVariant(QString::fromUtf8(QJsonDocument(vessels_arr).toJson(QJsonDocument::Compact))),+ cache_key,+ QVariant(QString::fromUtf8(QJsonDocument(cached_root).toJson(QJsonDocument::Compact))),kVesselTtlSec, "maritime");- QVector<VesselData> vessels;- vessels.reserve(vessels_arr.size());- for (const auto& v : vessels_arr)- vessels.append(self->parse_vessel(v.toObject()));- int total = data["found_count"].toInt(vessels.size());- LOG_INFO("Maritime", QString("Multi vessel: %1 found").arg(vessels.size()));- emit self->vessels_loaded(vessels, total);++ LOG_INFO("Maritime", QString("Multi vessel: %1 found, %2 missing (%3 credits left)")+ .arg(page.found_count)+ .arg(page.not_found.size())+ .arg(page.remaining_credits));++ emit self->vessels_loaded(page);if (self->hub_registered_)- publish_to_hub(QStringLiteral("maritime:vessels:multi"), QVariant::fromValue(vessels));+ publish_to_hub(QStringLiteral("maritime:vessels:multi"), QVariant::fromValue(page));});}// ── Vessel history ───────────────────────────────────────────────────────────void MaritimeService::get_vessel_history(const QString& imo) {- const QString cache_key = "maritime:history:" + imo.trimmed();+ const QString imo_trimmed = imo.trimmed();+ const QString cache_key = "maritime:history:" + imo_trimmed;const QVariant cached = fincept::CacheManager::instance().get(cache_key);if (!cached.isNull()) {- QJsonArray history_arr = QJsonDocument::fromJson(cached.toString().toUtf8()).array();- QVector<VesselData> history;- history.reserve(history_arr.size());- for (const auto& v : history_arr)- history.append(parse_vessel(v.toObject()));- emit vessel_history_loaded(history);+ const QJsonObject root = QJsonDocument::fromJson(cached.toString().toUtf8()).object();+ VesselHistoryPage page;+ page.imo = root["imo"].toString(imo_trimmed);+ const QJsonArray arr = root["history"].toArray();+ page.history.reserve(arr.size());+ for (const auto& v : arr)+ page.history.append(parse_vessel(v.toObject()));+ page.total_records = root["total_records"].toInt(page.history.size());+ page.credits_used = root["credits_used"].toDouble(0.0);+ page.remaining_credits = root["remaining_credits"].toInt(-1);+ emit vessel_history_loaded(page);return;}QJsonObject body;- body["imo"] = imo.trimmed();+ body["imo"] = imo_trimmed;QPointer<MaritimeService> self = this;- const QString imo_trimmed = imo.trimmed();HttpClient::instance().post(QString(kMarineBase) + "/vessel/history", body,[self, cache_key, imo_trimmed](Result<QJsonDocument> result) {@@ -199,21 +341,63 @@ void MaritimeService::get_vessel_history(const QString& imo) {emit self->error_occurred("vessel_history", QString::fromStdString(result.error()));return;}- auto data = unwrap(result.value().object());- auto arr = data["positions"].toArray();+ const auto data = unwrap(result.value().object());+ // API returns either "history" (current) or "positions" (legacy).+ QJsonArray arr = data["history"].toArray();if (arr.isEmpty())- arr = data["history"].toArray();+ arr = data["positions"].toArray();++ VesselHistoryPage page;+ page.imo = data["imo"].toString(imo_trimmed);+ page.history.reserve(arr.size());+ for (const auto& v : arr)+ page.history.append(self->parse_vessel(v.toObject()));++ std::sort(page.history.begin(), page.history.end(),+ [](const VesselData& a, const VesselData& b) {+ return a.last_updated > b.last_updated;+ });++ page.total_records = data["total_records"].toInt(page.history.size());+ page.credits_used = data["credits_used"].toDouble(0.0);+ page.remaining_credits = data["remaining_credits"].toInt(-1);++ QJsonArray cached_arr;+ for (const auto& v : page.history) {+ QJsonObject o;+ o["id"] = v.id;+ o["imo"] = v.imo;+ o["name"] = v.name;+ o["last_pos_latitude"] = QString::number(v.latitude, 'f', 8);+ o["last_pos_longitude"] = QString::number(v.longitude, 'f', 8);+ o["last_pos_speed"] = QString::number(v.speed);+ o["last_pos_angle"] = QString::number(v.angle);+ o["route_from_port_name"] = v.from_port;+ o["route_to_port_name"] = v.to_port;+ o["last_pos_updated_at"] = v.last_updated;+ cached_arr.append(o);+ }+ QJsonObject cached_root;+ cached_root["imo"] = page.imo;+ cached_root["history"] = cached_arr;+ cached_root["total_records"] = page.total_records;+ cached_root["credits_used"] = page.credits_used;+ cached_root["remaining_credits"] = page.remaining_credits;fincept::CacheManager::instance().put(- cache_key, QVariant(QString::fromUtf8(QJsonDocument(arr).toJson(QJsonDocument::Compact))),+ cache_key,+ QVariant(QString::fromUtf8(QJsonDocument(cached_root).toJson(QJsonDocument::Compact))),kHistoryTtlSec, "maritime");- QVector<VesselData> history;- history.reserve(arr.size());- for (const auto& v : arr)- history.append(self->parse_vessel(v.toObject()));- emit self->vessel_history_loaded(history);++ LOG_INFO("Maritime", QString("History [%1]: %2 records (total %3, %4 credits left)")+ .arg(page.imo)+ .arg(page.history.size())+ .arg(page.total_records)+ .arg(page.remaining_credits));++ emit self->vessel_history_loaded(page);if (self->hub_registered_)publish_to_hub(QStringLiteral("maritime:history:") + imo_trimmed,- QVariant::fromValue(history));+ QVariant::fromValue(page));});}@@ -243,15 +427,15 @@ QStringList MaritimeService::topic_patterns() const {}void MaritimeService::refresh(const QStringList& topics) {+ // Only refresh topics whose key uniquely determines the request. Area /+ // multi-vessel topics depend on user-supplied bbox / IMO list, so the+ // hub doesn't drive their cadence — those calls are user-invoked.for (const auto& topic : topics) {const QStringList parts = topic.split(QLatin1Char(':'));if (parts.size() >= 3 && parts[1] == QStringLiteral("vessel")) {get_vessel_position(parts[2]);} else if (parts.size() >= 3 && parts[1] == QStringLiteral("history")) {get_vessel_history(parts[2]);- } else if (parts.size() == 3 && parts[1] == QStringLiteral("vessels") &&- parts[2] == QStringLiteral("multi")) {- search_vessels_by_area({});} else if (topic == QStringLiteral("maritime:health")) {check_health();}diff --git a/fincept-qt/src/services/maritime/MaritimeService.h b/fincept-qt/src/services/maritime/MaritimeService.hindex d1df9d599..0f05051fd 100644--- a/fincept-qt/src/services/maritime/MaritimeService.h+++ b/fincept-qt/src/services/maritime/MaritimeService.h@@ -40,9 +40,12 @@ class MaritimeService : public QObjectvoid check_health();signals:- void vessels_loaded(QVector<fincept::services::maritime::VesselData> vessels, int total);+ /// Emitted by both area-search and multi-vessel calls. The page envelope+ /// carries credit metering and (for multi-vessel) the list of IMOs the+ /// API could not resolve.+ void vessels_loaded(fincept::services::maritime::VesselsPage page);void vessel_found(fincept::services::maritime::VesselData vessel);- void vessel_history_loaded(QVector<fincept::services::maritime::VesselData> history);+ void vessel_history_loaded(fincept::services::maritime::VesselHistoryPage page);void health_loaded(QJsonObject data);void error_occurred(QString context, QString message);diff --git a/fincept-qt/src/services/maritime/MaritimeTypes.h b/fincept-qt/src/services/maritime/MaritimeTypes.hindex 75aafecc4..e851b6282 100644--- a/fincept-qt/src/services/maritime/MaritimeTypes.h+++ b/fincept-qt/src/services/maritime/MaritimeTypes.h@@ -27,84 +27,61 @@ struct VesselData {QString fetched_at;};-// ── Trade route corridor ────────────────────────────────────────────────────+// ── Trade route corridor (derived from current vessel set, not hardcoded) ──+//+// Built at runtime by aggregating loaded vessels on (from_port, to_port).+// `value` is left empty since the API does not expose trade-volume figures —+// the column is kept for future enrichment.struct TradeRoute {QString name;- QString value; // e.g. "$45B"- QString status; // active, delayed, critical+ QString value;+ QString status; // active, delayed, critical (left empty when not derivable)int vessels = 0;double start_lat = 0, start_lng = 0;double end_lat = 0, end_lng = 0;};inline QColor route_status_color(const QString& status) {- if (status == "critical")+ if (status == QStringLiteral("critical"))return QColor("#FF0000");- if (status == "delayed")+ if (status == QStringLiteral("delayed"))return QColor("#FFD700");- return QColor("#00FF00"); // active+ if (status == QStringLiteral("active"))+ return QColor("#00FF00");+ return QColor("#888888");}-// ── Intelligence stats ──────────────────────────────────────────────────────--struct IntelligenceData {- QString threat_level; // low, medium, high, critical- int active_vessels = 0;- int monitored_routes = 48;- QString trade_volume = "$847.3B";+// ── Page envelope for area-search / multi-vessel responses ──────────────────+//+// Wraps the parsed vessel list with the new credit metering + result counts+// the API returns. `not_found` is populated by multi-vessel when caller+// requested IMOs that aren't in the database.++struct VesselsPage {+ QVector<VesselData> vessels;+ int total_count = 0; // server-reported total ("vessel_count" / "found_count")+ int found_count = 0; // multi-vessel only+ QStringList not_found; // multi-vessel only — IMOs missing from DB+ double credits_used = 0.0;+ int remaining_credits = -1; // -1 = unknown / not reported};-inline QColor threat_color(const QString& level) {- if (level == "critical")- return QColor("#FF0000");- if (level == "high")- return QColor("#FF6600");- if (level == "medium")- return QColor("#FFD700");- return QColor("#00FF00"); // low-}--// ── Preset port locations ───────────────────────────────────────────────────--struct PresetPort {- QString name;- double lat;- double lng;+struct VesselHistoryPage {+ QString imo;+ QVector<VesselData> history; // sorted newest-first+ int total_records = 0;+ double credits_used = 0.0;+ int remaining_credits = -1;};-inline QVector<PresetPort> preset_ports() {- return {- {"Mumbai Port", 18.9388, 72.8354}, {"Shanghai Port", 31.3548, 121.6431},- {"Singapore Port", 1.2644, 103.8224}, {"Hong Kong Port", 22.2855, 114.1577},- {"Rotterdam Port", 51.9553, 4.1392}, {"Dubai Port", 24.9857, 55.0272},- };-}--// ── Default trade routes ────────────────────────────────────────────────────--inline QVector<TradeRoute> default_trade_routes() {- return {- {"Mumbai - Rotterdam", "$45B", "active", 23, 18.94, 72.84, 51.96, 4.14},- {"Mumbai - Shanghai", "$156B", "active", 89, 18.94, 72.84, 31.35, 121.64},- {"Mumbai - Singapore", "$89B", "active", 45, 18.94, 72.84, 1.26, 103.82},- {"Chennai - Tokyo", "$67B", "delayed", 34, 13.08, 80.27, 35.65, 139.84},- {"Kolkata - Hong Kong", "$45B", "active", 28, 22.57, 88.37, 22.29, 114.16},- {"Mumbai - Dubai", "$78B", "critical", 12, 18.94, 72.84, 24.99, 55.03},- {"Mumbai - New York", "$123B", "active", 56, 18.94, 72.84, 40.68, -74.04},- {"Chennai - Sydney", "$54B", "active", 31, 13.08, 80.27, -33.86, 151.21},- {"Cochin - Port Klang", "$34B", "active", 19, 9.97, 76.27, 3.00, 101.39},- {"Mumbai - Cape Town", "$28B", "delayed", 8, 18.94, 72.84, -33.92, 18.42},- };-}-// ── Area search params ──────────────────────────────────────────────────────struct AreaSearchParams {- double min_lat = 18.5;- double max_lat = 19.5;- double min_lng = 72.0;- double max_lng = 73.5;+ double min_lat = 0;+ double max_lat = 0;+ double min_lng = 0;+ double max_lng = 0;int days_ago = 0;};@@ -112,4 +89,6 @@ struct AreaSearchParams {#include <QMetaType>Q_DECLARE_METATYPE(fincept::services::maritime::VesselData)+Q_DECLARE_METATYPE(fincept::services::maritime::VesselsPage)+Q_DECLARE_METATYPE(fincept::services::maritime::VesselHistoryPage)Q_DECLARE_METATYPE(QVector<fincept::services::maritime::VesselData>)diff --git a/fincept-qt/src/services/stt/SpeechService.cpp b/fincept-qt/src/services/stt/SpeechService.cppindex b62588124..65cf22525 100644--- a/fincept-qt/src/services/stt/SpeechService.cpp+++ b/fincept-qt/src/services/stt/SpeechService.cpp@@ -44,20 +44,34 @@ class PythonSttProvider : public SttProvider {using SttProvider::SttProvider;void start() override {- if (process_)+ LOG_INFO(TAG, QString("PythonSttProvider[%1]::start() — entry").arg(name()));+ if (process_) {+ LOG_WARN(TAG, QString("PythonSttProvider[%1]: start() called but process_ already exists — ignoring")+ .arg(name()));return;+ }QString python_exe = python::PythonSetupManager::instance().python_path("venv-numpy2");- if (python_exe.isEmpty() || !QFileInfo::exists(python_exe))- python_exe = python::PythonRunner::instance().python_path();+ LOG_INFO(TAG, QString("Resolving python_exe — venv-numpy2 path: '%1' (exists=%2)")+ .arg(python_exe).arg(QFileInfo::exists(python_exe)));+ if (python_exe.isEmpty() || !QFileInfo::exists(python_exe)) {+ const QString fallback = python::PythonRunner::instance().python_path();+ LOG_WARN(TAG, QString("venv-numpy2 python missing — falling back to PythonRunner default: '%1'")+ .arg(fallback));+ python_exe = fallback;+ }if (python_exe.isEmpty()) {+ LOG_ERROR(TAG, "No Python interpreter available — aborting STT start");emit fatal_error(QStringLiteral("Python not available — cannot start voice input"));return;}const QString script = script_path();+ LOG_INFO(TAG, QString("Resolving script — path: '%1' (exists=%2)")+ .arg(script).arg(QFileInfo::exists(script)));if (!QFileInfo::exists(script)) {+ LOG_ERROR(TAG, QString("STT script not found at '%1' — aborting").arg(script));emit fatal_error(QStringLiteral("Voice script not found: ") + script);return;}@@ -86,6 +100,9 @@ class PythonSttProvider : public SttProvider {process_->setProcessEnvironment(env);process_->setWorkingDirectory(scripts_dir);+ // Capture stderr so Python tracebacks / diagnostic prints surface in+ // the C++ log instead of being silently dropped.+ process_->setProcessChannelMode(QProcess::SeparateChannels);#ifdef _WIN32process_->setCreateProcessArgumentsModifier([](QProcess::CreateProcessArguments* cpa) {@@ -94,8 +111,15 @@ class PythonSttProvider : public SttProvider {#endifconnect(process_, &QProcess::readyReadStandardOutput, this, &PythonSttProvider::on_stdout_ready);+ connect(process_, &QProcess::readyReadStandardError, this, &PythonSttProvider::on_stderr_ready);+ connect(process_, &QProcess::started, this, [this]() {+ LOG_INFO(TAG, QString("Provider[%1]: QProcess::started — pid=%2")+ .arg(name()).arg(process_ ? process_->processId() : 0));+ });connect(process_, &QProcess::finished, this, &PythonSttProvider::on_process_finished);connect(process_, &QProcess::errorOccurred, this, [this](QProcess::ProcessError err) {+ LOG_ERROR(TAG, QString("Provider[%1]: QProcess::errorOccurred err=%2")+ .arg(name()).arg(static_cast<int>(err)));if (err == QProcess::FailedToStart) {emit fatal_error(QStringLiteral("Failed to start voice recognition process"));stop();@@ -103,10 +127,12 @@ class PythonSttProvider : public SttProvider {});stdout_buffer_.clear();+ LOG_INFO(TAG, QString("Provider[%1]: launching '%2' '%3' (cwd='%4')")+ .arg(name(), python_exe, script, scripts_dir));process_->start(python_exe, {script});active_.store(true, std::memory_order_release);- LOG_INFO(TAG, QString("Voice provider '%1' started").arg(name()));+ LOG_INFO(TAG, QString("Voice provider '%1' marked active — emitting active_changed(true)").arg(name()));emit active_changed(true);}@@ -158,8 +184,29 @@ class PythonSttProvider : public SttProvider {const QByteArray line = stdout_buffer_.left(newline_pos).trimmed();stdout_buffer_.remove(0, newline_pos + 1);- if (!line.isEmpty())+ if (!line.isEmpty()) {+ LOG_DEBUG(TAG, QString("Provider[%1] stdout: %2")+ .arg(name(), QString::fromUtf8(line.left(400))));parse_line(line);+ }+ }+ }++ /// Stderr from the Python child — Python tracebacks, deepgram-sdk warnings,+ /// and any `print(..., file=sys.stderr)` lines land here. Logged so a+ /// failing voice session is diagnosable from Logger output.+ void on_stderr_ready() {+ if (!process_)+ return;+ const QByteArray chunk = process_->readAllStandardError();+ if (chunk.isEmpty())+ return;+ // Strip trailing newlines for cleaner log lines but preserve embedded+ // ones — multi-line tracebacks read better in the log file than a+ // single mashed-together line.+ const QString text = QString::fromUtf8(chunk).trimmed();+ if (!text.isEmpty()) {+ LOG_WARN(TAG, QString("Provider[%1] stderr: %2").arg(name(), text));}}@@ -167,7 +214,8 @@ class PythonSttProvider : public SttProvider {QJsonParseError parse_err;const QJsonDocument doc = QJsonDocument::fromJson(line, &parse_err);if (parse_err.error != QJsonParseError::NoError) {- LOG_WARN(TAG, QString("Non-JSON stdout line: %1").arg(QString::fromUtf8(line)));+ LOG_WARN(TAG, QString("Provider[%1]: non-JSON stdout line ignored: %2")+ .arg(name(), QString::fromUtf8(line)));return;}@@ -176,29 +224,52 @@ class PythonSttProvider : public SttProvider {if (obj.contains("text")) {const QString text = obj["text"].toString().trimmed();if (!text.isEmpty()) {- LOG_DEBUG(TAG, QString("Transcript: \"%1\"").arg(text));+ LOG_INFO(TAG, QString("Provider[%1]: transcript len=%2 \"%3\"")+ .arg(name()).arg(text.length()).arg(text.left(120)));emit transcription(text);+ } else {+ LOG_WARN(TAG, QString("Provider[%1]: empty transcript object").arg(name()));}} else if (obj.contains("error")) {const QString msg = obj["error"].toString();- LOG_WARN(TAG, QString("STT error: %1").arg(msg));+ LOG_WARN(TAG, QString("Provider[%1] STT error event: %2").arg(name(), msg));emit error(msg);} else if (obj.contains("fatal")) {const QString msg = obj["fatal"].toString();- LOG_ERROR(TAG, QString("STT fatal: %1").arg(msg));+ LOG_ERROR(TAG, QString("Provider[%1] STT FATAL event: %2 — tearing down provider")+ .arg(name(), msg));emit fatal_error(msg);stop();} else if (obj.contains("status")) {const QString status = obj["status"].toString();- LOG_DEBUG(TAG, QString("STT status: %1").arg(status));+ LOG_INFO(TAG, QString("Provider[%1] STT status: %2").arg(name(), status));+ } else {+ LOG_WARN(TAG, QString("Provider[%1]: JSON line had no recognised key — %2")+ .arg(name(), QString::fromUtf8(line.left(200))));}}void on_process_finished(int exit_code, QProcess::ExitStatus status) {- LOG_INFO(TAG, QString("Voice provider '%1' process exited (code=%2, status=%3)")+ // Drain any final stderr content before the QProcess is deleted —+ // last-gasp Python tracebacks otherwise vanish.+ if (process_) {+ const QByteArray remaining_err = process_->readAllStandardError();+ if (!remaining_err.isEmpty()) {+ LOG_WARN(TAG, QString("Provider[%1] final stderr: %2")+ .arg(name(), QString::fromUtf8(remaining_err).trimmed()));+ }+ const QByteArray remaining_out = process_->readAllStandardOutput();+ if (!remaining_out.isEmpty()) {+ LOG_INFO(TAG, QString("Provider[%1] final stdout: %2")+ .arg(name(), QString::fromUtf8(remaining_out).trimmed()));+ }+ }++ LOG_INFO(TAG, QString("Voice provider '%1' process exited (code=%2, status=%3, was_active=%4)").arg(name()).arg(exit_code)- .arg(status == QProcess::CrashExit ? "crash" : "normal"));+ .arg(status == QProcess::CrashExit ? "crash" : "normal")+ .arg(active_.load(std::memory_order_relaxed)));if (process_) {process_->deleteLater();@@ -209,8 +280,11 @@ class PythonSttProvider : public SttProvider {const bool was_active = active_.exchange(false, std::memory_order_acq_rel);if (was_active) {emit active_changed(false);- if (status == QProcess::CrashExit || exit_code != 0)+ if (status == QProcess::CrashExit || exit_code != 0) {+ LOG_ERROR(TAG, QString("Provider[%1] exited abnormally (code=%2) — surfacing error to UI")+ .arg(name()).arg(exit_code));emit error(QStringLiteral("Voice recognition stopped unexpectedly"));+ }}}@@ -257,12 +331,34 @@ class DeepgramSttProvider final : public PythonSttProvider {void extend_environment(QProcessEnvironment& env) const override {auto key_res = SecureStorage::instance().retrieve(QStringLiteral("voice.deepgram.api_key"));const QString api_key = key_res.is_ok() ? key_res.value() : QString();- env.insert("DEEPGRAM_API_KEY", api_key);++ if (key_res.is_err()) {+ LOG_ERROR(TAG, QString("Deepgram: SecureStorage::retrieve failed — %1")+ .arg(QString::fromStdString(key_res.error())));+ }auto& cfg = AppConfig::instance();- env.insert("FINCEPT_STT_MODEL", cfg.get("voice/deepgram/model", "nova-3").toString());- env.insert("FINCEPT_STT_LANGUAGE", cfg.get("voice/deepgram/language", "en").toString());- env.insert("FINCEPT_STT_KEYTERMS", cfg.get("voice/deepgram/keyterms", "").toString());+ const QString model = cfg.get("voice/deepgram/model", "nova-3").toString();+ const QString lang = cfg.get("voice/deepgram/language", "en").toString();+ const QString keyterms = cfg.get("voice/deepgram/keyterms", "").toString();+ // Audio capture knobs — laptop mics often need 3-5x gain; far-field+ // setups may need a specific device by name. Defaults match script.+ const QString gain = cfg.get("voice/deepgram/gain", "3.0").toString();+ const QString device = cfg.get("voice/deepgram/device", "").toString();++ // Never log the key itself — only its length, so we can tell at a+ // glance whether SecureStorage returned anything.+ LOG_INFO(TAG, QString("Deepgram env: api_key_len=%1 model='%2' language='%3' "+ "keyterms_len=%4 gain=%5 device='%6'")+ .arg(api_key.length()).arg(model, lang)+ .arg(keyterms.length()).arg(gain, device));++ env.insert("DEEPGRAM_API_KEY", api_key);+ env.insert("FINCEPT_STT_MODEL", model);+ env.insert("FINCEPT_STT_LANGUAGE", lang);+ env.insert("FINCEPT_STT_KEYTERMS", keyterms);+ env.insert("FINCEPT_STT_GAIN", gain);+ env.insert("FINCEPT_STT_DEVICE", device);}};@@ -286,24 +382,43 @@ SpeechService::~SpeechService() {// ── Public API ───────────────────────────────────────────────────────────────QString SpeechService::configured_provider() {- const QString v = AppConfig::instance().get("voice/provider", "google").toString().toLower();+ auto& cfg = AppConfig::instance();+ // Canonical key is "voice/stt/provider"; fall back to legacy "voice/provider"+ // for users who saved settings before TTS provider was split out.+ QString v = cfg.get("voice/stt/provider", "").toString().toLower();+ if (v.isEmpty())+ v = cfg.get("voice/provider", "google").toString().toLower();return (v == "deepgram") ? QStringLiteral("deepgram") : QStringLiteral("google");}void SpeechService::start_listening() {- if (listening_.load(std::memory_order_relaxed))+ LOG_INFO(TAG, QString("SpeechService::start_listening() — listening_=%1 provider=%2")+ .arg(listening_.load(std::memory_order_relaxed))+ .arg(provider_ ? provider_->name() : QStringLiteral("<none>")));+ if (listening_.load(std::memory_order_relaxed)) {+ LOG_WARN(TAG, "start_listening: already listening — ignoring");return;+ }install_provider();- if (!provider_)+ if (!provider_) {+ LOG_ERROR(TAG, "start_listening: install_provider() left provider_ null — cannot start");+ emit error_occurred(QStringLiteral("Voice provider could not be installed"));return;+ }+ LOG_INFO(TAG, QString("start_listening: delegating to provider '%1'").arg(provider_->name()));provider_->start();}void SpeechService::stop_listening() {- if (!listening_.load(std::memory_order_relaxed))+ LOG_INFO(TAG, QString("SpeechService::stop_listening() — listening_=%1 provider=%2")+ .arg(listening_.load(std::memory_order_relaxed))+ .arg(provider_ ? provider_->name() : QStringLiteral("<none>")));+ if (!listening_.load(std::memory_order_relaxed)) {+ LOG_INFO(TAG, "stop_listening: not active — no-op");return;+ }if (provider_)provider_->stop();}@@ -335,10 +450,14 @@ bool SpeechService::is_listening() const noexcept {void SpeechService::install_provider() {const QString id = configured_provider();+ LOG_INFO(TAG, QString("install_provider() — configured='%1' current='%2'")+ .arg(id, provider_ ? provider_->name() : QStringLiteral("<none>")));// If an existing provider matches the selection, reuse it.- if (provider_ && provider_->name() == id)+ if (provider_ && provider_->name() == id) {+ LOG_INFO(TAG, "install_provider: reusing existing provider instance");return;+ }teardown_provider();@@ -351,11 +470,13 @@ void SpeechService::install_provider() {connect(provider_.get(), &SttProvider::error, this, &SpeechService::error_occurred);connect(provider_.get(), &SttProvider::fatal_error, this, &SpeechService::error_occurred);connect(provider_.get(), &SttProvider::active_changed, this, [this](bool active) {+ LOG_INFO(TAG, QString("Provider active_changed — active=%1 (forwarding listening_changed)")+ .arg(active));listening_.store(active, std::memory_order_release);emit listening_changed(active);});- LOG_INFO(TAG, QString("Voice provider selected: %1").arg(id));+ LOG_INFO(TAG, QString("Voice provider installed: %1").arg(id));}void SpeechService::teardown_provider() {diff --git a/fincept-qt/src/services/tts/TtsService.cpp b/fincept-qt/src/services/tts/TtsService.cppnew file mode 100644index 000000000..bf66dcd73--- /dev/null+++ b/fincept-qt/src/services/tts/TtsService.cpp@@ -0,0 +1,431 @@+// TtsService.cpp — Pluggable text-to-speech (pyttsx3 free + Deepgram Aura).+//+// Two providers share a common Python-QProcess + JSON-stdout plumbing.+// Subclass overrides only `script_path()` and (optionally)+// `extend_environment()` to inject API keys / voice models.+//+// Logging mirrors SpeechService — every state transition + every line of+// stdin/stdout/stderr is captured so failures are diagnosable from the log.++#include "services/tts/TtsService.h"++#include "core/config/AppConfig.h"+#include "core/logging/Logger.h"+#include "python/PythonRunner.h"+#include "python/PythonSetupManager.h"+#include "storage/secure/SecureStorage.h"++#include <QFileInfo>+#include <QJsonDocument>+#include <QJsonObject>++namespace fincept::services {++// Use uniquely-prefixed names — unity build merges multiple .cpp files into a+// single TU, so generic names like TAG / kShutdownTimeoutMs would clash with+// SpeechService's identically-named constants.+namespace {+constexpr auto TTS_TAG = "TtsService";+constexpr int kTtsShutdownTimeoutMs = 1500;+} // namespace++// ── PythonTtsProvider (base) ─────────────────────────────────────────────────+//+// Shared plumbing for any TTS provider implemented as a Python QProcess that+// reads text from stdin and emits JSON lines on stdout. Subclasses contribute+// `script_path()` and any extra env vars via `extend_environment()`.++namespace {++class PythonTtsProvider : public TtsProvider {+ public:+ using TtsProvider::TtsProvider;++ void speak(const QString& text) override {+ LOG_INFO(TTS_TAG, QString("Provider[%1]::speak() — len=%2 active=%3")+ .arg(name()).arg(text.length()).arg(active_.load()));++ if (text.trimmed().isEmpty()) {+ LOG_INFO(TTS_TAG, "speak: empty text — emitting finished immediately");+ emit speaking_finished();+ return;+ }++ // Cancel any in-flight utterance — matches QTextToSpeech::say().+ if (process_) {+ LOG_INFO(TTS_TAG, "speak: cancelling previous utterance");+ stop();+ }++ QString python_exe = python::PythonSetupManager::instance().python_path("venv-numpy2");+ LOG_INFO(TTS_TAG, QString("Resolving python_exe — venv-numpy2: '%1' (exists=%2)")+ .arg(python_exe).arg(QFileInfo::exists(python_exe)));+ if (python_exe.isEmpty() || !QFileInfo::exists(python_exe))+ python_exe = python::PythonRunner::instance().python_path();++ if (python_exe.isEmpty()) {+ LOG_ERROR(TTS_TAG, "No Python interpreter available — aborting TTS");+ emit error_occurred(QStringLiteral("Python not available — cannot speak response"));+ return;+ }++ const QString script = script_path();+ LOG_INFO(TTS_TAG, QString("Resolving script — '%1' (exists=%2)")+ .arg(script).arg(QFileInfo::exists(script)));+ if (!QFileInfo::exists(script)) {+ LOG_ERROR(TTS_TAG, QString("TTS script not found at '%1'").arg(script));+ emit error_occurred(QStringLiteral("TTS script not found: ") + script);+ return;+ }++ process_ = new QProcess(this);++ QProcessEnvironment env = QProcessEnvironment::systemEnvironment();+ env.insert("PYTHONIOENCODING", "utf-8");+ env.insert("PYTHONDONTWRITEBYTECODE", "1");+ env.insert("PYTHONUNBUFFERED", "1");+ env.insert("FINCEPT_DATA_DIR", python::PythonSetupManager::instance().install_dir());++ const QString scripts_dir = python::PythonRunner::instance().scripts_dir();+ const QString existing_pypath = env.value("PYTHONPATH");+#ifdef _WIN32+ const QChar kPathSep = ';';+#else+ const QChar kPathSep = ':';+#endif+ env.insert("PYTHONPATH", existing_pypath.isEmpty()+ ? scripts_dir+ : (scripts_dir + kPathSep + existing_pypath));++ // Provider-specific env (api keys, voice models, rates).+ extend_environment(env);++ process_->setProcessEnvironment(env);+ process_->setWorkingDirectory(scripts_dir);+ process_->setProcessChannelMode(QProcess::SeparateChannels);++#ifdef _WIN32+ process_->setCreateProcessArgumentsModifier([](QProcess::CreateProcessArguments* cpa) {+ cpa->flags |= 0x08000000; // CREATE_NO_WINDOW+ });+#endif++ connect(process_, &QProcess::readyReadStandardOutput, this, &PythonTtsProvider::on_stdout_ready);+ connect(process_, &QProcess::readyReadStandardError, this, &PythonTtsProvider::on_stderr_ready);+ connect(process_, &QProcess::started, this, [this]() {+ LOG_INFO(TTS_TAG, QString("Provider[%1]: QProcess::started — pid=%2")+ .arg(name()).arg(process_ ? process_->processId() : 0));+ });+ connect(process_, &QProcess::finished, this, &PythonTtsProvider::on_process_finished);+ connect(process_, &QProcess::errorOccurred, this, [this](QProcess::ProcessError err) {+ LOG_ERROR(TTS_TAG, QString("Provider[%1]: QProcess::errorOccurred err=%2")+ .arg(name()).arg(static_cast<int>(err)));+ if (err == QProcess::FailedToStart) {+ emit error_occurred(QStringLiteral("Failed to launch TTS process"));+ stop();+ }+ });++ stdout_buffer_.clear();+ LOG_INFO(TTS_TAG, QString("Provider[%1]: launching '%2' '%3' (cwd='%4')")+ .arg(name(), python_exe, script, scripts_dir));+ process_->start(python_exe, {script});++ if (!process_->waitForStarted(2000)) {+ LOG_ERROR(TTS_TAG, "TTS process did not start within 2 s");+ emit error_occurred(QStringLiteral("TTS process failed to start"));+ stop();+ return;+ }++ // Pipe text on stdin and close so the child sees EOF.+ const QByteArray payload = text.toUtf8();+ const qint64 written = process_->write(payload);+ process_->closeWriteChannel();+ LOG_INFO(TTS_TAG, QString("Provider[%1]: wrote %2/%3 bytes to stdin")+ .arg(name()).arg(written).arg(payload.size()));+ }++ void stop() override {+ if (!process_)+ return;++ disconnect(process_, nullptr, this, nullptr);+ if (process_->state() != QProcess::NotRunning) {+ process_->kill();+ process_->waitForFinished(kTtsShutdownTimeoutMs);+ }+ process_->deleteLater();+ process_ = nullptr;+ stdout_buffer_.clear();++ const bool was_active = active_.exchange(false, std::memory_order_acq_rel);+ if (was_active) {+ LOG_INFO(TTS_TAG, QString("Provider[%1]: stop — was_active=true → speaking_finished")+ .arg(name()));+ emit speaking_finished();+ }+ }++ [[nodiscard]] bool is_active() const noexcept override {+ return active_.load(std::memory_order_relaxed);+ }++ protected:+ /// Absolute path to the Python script that implements the JSON-lines protocol.+ virtual QString script_path() const = 0;++ /// Hook for subclasses to add API keys / voice / model env vars.+ virtual void extend_environment(QProcessEnvironment& /*env*/) const {}++ private:+ void on_stdout_ready() {+ if (!process_)+ return;+ stdout_buffer_.append(process_->readAllStandardOutput());++ while (true) {+ const int newline_pos = stdout_buffer_.indexOf('\n');+ if (newline_pos < 0)+ break;+ const QByteArray line = stdout_buffer_.left(newline_pos).trimmed();+ stdout_buffer_.remove(0, newline_pos + 1);+ if (!line.isEmpty()) {+ LOG_DEBUG(TTS_TAG, QString("Provider[%1] stdout: %2")+ .arg(name(), QString::fromUtf8(line.left(400))));+ parse_line(line);+ }+ }+ }++ void on_stderr_ready() {+ if (!process_)+ return;+ const QByteArray chunk = process_->readAllStandardError();+ if (chunk.isEmpty())+ return;+ const QString text = QString::fromUtf8(chunk).trimmed();+ if (!text.isEmpty()) {+ LOG_WARN(TTS_TAG, QString("Provider[%1] stderr: %2").arg(name(), text));+ }+ }++ void parse_line(const QByteArray& line) {+ QJsonParseError parse_err;+ const QJsonDocument doc = QJsonDocument::fromJson(line, &parse_err);+ if (parse_err.error != QJsonParseError::NoError) {+ LOG_WARN(TTS_TAG, QString("Provider[%1] non-JSON stdout: %2")+ .arg(name(), QString::fromUtf8(line)));+ return;+ }+ const QJsonObject obj = doc.object();++ if (obj.contains("status")) {+ const QString status = obj["status"].toString();+ LOG_INFO(TTS_TAG, QString("Provider[%1] status: %2").arg(name(), status));+ if (status == "speaking") {+ active_.store(true, std::memory_order_release);+ emit speaking_started();+ } else if (status == "done") {+ const bool was_active = active_.exchange(false, std::memory_order_acq_rel);+ if (was_active)+ emit speaking_finished();+ }+ } else if (obj.contains("error")) {+ const QString msg = obj["error"].toString();+ LOG_WARN(TTS_TAG, QString("Provider[%1] error: %2").arg(name(), msg));+ emit error_occurred(msg);+ } else if (obj.contains("fatal")) {+ const QString msg = obj["fatal"].toString();+ LOG_ERROR(TTS_TAG, QString("Provider[%1] fatal: %2").arg(name(), msg));+ emit error_occurred(msg);+ }+ }++ void on_process_finished(int exit_code, QProcess::ExitStatus status) {+ if (process_) {+ const QByteArray remaining_err = process_->readAllStandardError();+ if (!remaining_err.isEmpty())+ LOG_WARN(TTS_TAG, QString("Provider[%1] final stderr: %2")+ .arg(name(), QString::fromUtf8(remaining_err).trimmed()));+ const QByteArray remaining_out = process_->readAllStandardOutput();+ if (!remaining_out.isEmpty())+ LOG_INFO(TTS_TAG, QString("Provider[%1] final stdout: %2")+ .arg(name(), QString::fromUtf8(remaining_out).trimmed()));+ }++ LOG_INFO(TTS_TAG, QString("Provider[%1] process exited (code=%2, status=%3, was_active=%4)")+ .arg(name())+ .arg(exit_code)+ .arg(status == QProcess::CrashExit ? "crash" : "normal")+ .arg(active_.load()));++ if (process_) {+ process_->deleteLater();+ process_ = nullptr;+ }+ stdout_buffer_.clear();++ const bool was_active = active_.exchange(false, std::memory_order_acq_rel);+ if (was_active) {+ emit speaking_finished();+ if (status == QProcess::CrashExit || exit_code != 0) {+ LOG_ERROR(TTS_TAG, QString("Provider[%1] exited abnormally (code=%2)")+ .arg(name()).arg(exit_code));+ emit error_occurred(QStringLiteral("Voice response stopped unexpectedly"));+ }+ }+ }++ QProcess* process_ = nullptr;+ QByteArray stdout_buffer_;+ std::atomic<bool> active_{false};+};++// ── Pyttsx3TtsProvider ───────────────────────────────────────────────────────+//+// Free, offline. Wraps SAPI/NSSpeech/espeak via pyttsx3.++class Pyttsx3TtsProvider final : public PythonTtsProvider {+ public:+ using PythonTtsProvider::PythonTtsProvider;+ QString name() const override { return QStringLiteral("pyttsx3"); }++ protected:+ QString script_path() const override {+ return python::PythonRunner::instance().scripts_dir() ++ QStringLiteral("/voice/tts.py");+ }+};++// ── DeepgramTtsProvider ──────────────────────────────────────────────────────+//+// POSTs text to Deepgram /v1/speak (Aura-2 voices) and pipes returned PCM+// straight into pyaudio. Reads API key from SecureStorage; voice model from+// AppConfig key "voice/deepgram/tts_model".++class DeepgramTtsProvider final : public PythonTtsProvider {+ public:+ using PythonTtsProvider::PythonTtsProvider;+ QString name() const override { return QStringLiteral("deepgram"); }++ protected:+ QString script_path() const override {+ return python::PythonRunner::instance().scripts_dir() ++ QStringLiteral("/voice/deepgram_tts.py");+ }++ void extend_environment(QProcessEnvironment& env) const override {+ auto key_res = SecureStorage::instance().retrieve(QStringLiteral("voice.deepgram.api_key"));+ const QString api_key = key_res.is_ok() ? key_res.value() : QString();+ if (key_res.is_err()) {+ LOG_ERROR(TTS_TAG, QString("Deepgram TTS: SecureStorage::retrieve failed — %1")+ .arg(QString::fromStdString(key_res.error())));+ }++ const QString model = AppConfig::instance()+ .get("voice/deepgram/tts_model", "aura-2-thalia-en")+ .toString();++ LOG_INFO(TTS_TAG, QString("Deepgram TTS env: api_key_len=%1 model='%2'")+ .arg(api_key.length()).arg(model));++ env.insert("DEEPGRAM_API_KEY", api_key);+ env.insert("FINCEPT_TTS_DG_MODEL", model);+ }+};++} // namespace++// ── Singleton ────────────────────────────────────────────────────────────────++TtsService& TtsService::instance() {+ static TtsService s_instance;+ return s_instance;+}++TtsService::TtsService(QObject* parent) : QObject(parent) {+ LOG_INFO(TTS_TAG, "TtsService initialised");+}++TtsService::~TtsService() {+ teardown_provider();+}++bool TtsService::is_speaking() const noexcept {+ return speaking_.load(std::memory_order_relaxed);+}++QString TtsService::configured_provider() {+ const QString v = AppConfig::instance()+ .get("voice/tts/provider", "pyttsx3")+ .toString().toLower();+ return (v == "deepgram") ? QStringLiteral("deepgram") : QStringLiteral("pyttsx3");+}++void TtsService::speak(const QString& text) {+ LOG_INFO(TTS_TAG, QString("speak() — text_len=%1 currently_speaking=%2 provider=%3")+ .arg(text.length()).arg(is_speaking())+ .arg(provider_ ? provider_->name() : QStringLiteral("<none>")));++ install_provider();+ if (!provider_) {+ LOG_ERROR(TTS_TAG, "speak: install_provider() left provider_ null — cannot speak");+ emit error_occurred(QStringLiteral("TTS provider could not be installed"));+ return;+ }+ provider_->speak(text);+}++void TtsService::stop() {+ LOG_INFO(TTS_TAG, QString("stop() — speaking=%1").arg(is_speaking()));+ if (provider_)+ provider_->stop();+}++void TtsService::reload_config() {+ const bool was_speaking = is_speaking();+ if (was_speaking && provider_)+ provider_->stop();++ install_provider();+ LOG_INFO(TTS_TAG, "reload_config: provider re-evaluated");+}++void TtsService::install_provider() {+ const QString id = configured_provider();+ if (provider_ && provider_->name() == id) {+ // Reuse existing instance — env vars are rebuilt every speak() call,+ // so any AppConfig changes (api key, model) take effect on next speak.+ return;+ }++ LOG_INFO(TTS_TAG, QString("install_provider — switching from '%1' to '%2'")+ .arg(provider_ ? provider_->name() : QStringLiteral("<none>"), id));+ teardown_provider();++ if (id == QStringLiteral("deepgram"))+ provider_ = std::make_unique<DeepgramTtsProvider>(this);+ else+ provider_ = std::make_unique<Pyttsx3TtsProvider>(this);++ connect(provider_.get(), &TtsProvider::speaking_started, this, [this]() {+ speaking_.store(true, std::memory_order_release);+ emit speaking_started();+ });+ connect(provider_.get(), &TtsProvider::speaking_finished, this, [this]() {+ speaking_.store(false, std::memory_order_release);+ emit speaking_finished();+ });+ connect(provider_.get(), &TtsProvider::error_occurred, this, &TtsService::error_occurred);+}++void TtsService::teardown_provider() {+ if (!provider_)+ return;+ provider_->stop();+ disconnect(provider_.get(), nullptr, this, nullptr);+ provider_.reset();+}++} // namespace fincept::servicesdiff --git a/fincept-qt/src/services/tts/TtsService.h b/fincept-qt/src/services/tts/TtsService.hnew file mode 100644index 000000000..e7b20a184--- /dev/null+++ b/fincept-qt/src/services/tts/TtsService.h@@ -0,0 +1,88 @@+#pragma once+// TtsService.h — Pluggable text-to-speech with provider abstraction.+//+// Architecture mirrors SpeechService:+// TtsService (public facade)+// └── TtsProvider (abstract — emits speaking_started/finished/error)+// ├── Pyttsx3TtsProvider → scripts/voice/tts.py (free, offline)+// └── DeepgramTtsProvider → scripts/voice/deepgram_tts.py (Aura-2)+//+// Provider is selected via AppConfig key "voice/tts/provider"+// (default: "pyttsx3"). The choice is independent of the STT provider —+// users can mix Google STT with Deepgram TTS or vice versa.+//+// One process per utterance. The script reads text from stdin (until EOF),+// emits {"status":"speaking"|"done"} / {"error"|"fatal":...}.++#include <QObject>+#include <QPointer>+#include <QProcess>+#include <QProcessEnvironment>+#include <QString>++#include <atomic>+#include <memory>++namespace fincept::services {++/// Abstract base for TTS providers. Both providers share the QProcess + JSON+/// stdout parsing plumbing implemented in the .cpp file; subclasses contribute+/// the script path and any extra environment variables (API keys, voices).+class TtsProvider : public QObject {+ Q_OBJECT+ public:+ explicit TtsProvider(QObject* parent = nullptr) : QObject(parent) {}+ ~TtsProvider() override = default;++ virtual void speak(const QString& text) = 0;+ virtual void stop() = 0;+ [[nodiscard]] virtual bool is_active() const noexcept = 0;+ [[nodiscard]] virtual QString name() const = 0;++ signals:+ void speaking_started();+ void speaking_finished();+ void error_occurred(const QString& message);+};++class TtsService : public QObject {+ Q_OBJECT++ public:+ static TtsService& instance();++ TtsService(const TtsService&) = delete;+ TtsService& operator=(const TtsService&) = delete;++ /// Speak `text`. Cancels any in-flight utterance first.+ void speak(const QString& text);++ /// Cancel any in-flight utterance.+ void stop();++ /// Re-read provider/config and rebuild the active provider if needed.+ /// Called by VoiceConfigSection after the user saves new settings.+ void reload_config();++ [[nodiscard]] bool is_speaking() const noexcept;++ /// Returns "pyttsx3" or "deepgram" — current AppConfig setting.+ [[nodiscard]] static QString configured_provider();++ signals:+ void speaking_started();+ void speaking_finished();+ void error_occurred(const QString& message);++ private:+ explicit TtsService(QObject* parent = nullptr);+ ~TtsService() override;++ void install_provider();+ void teardown_provider();++ std::unique_ptr<TtsProvider> provider_;+ std::atomic<bool> speaking_{false};+};++} // namespace fincept::servicesdiff --git a/fincept-qt/src/services/voice_trigger/ClapDetectorService.cpp b/fincept-qt/src/services/voice_trigger/ClapDetectorService.cppnew file mode 100644index 000000000..e3e568c61--- /dev/null+++ b/fincept-qt/src/services/voice_trigger/ClapDetectorService.cpp@@ -0,0 +1,239 @@+// ClapDetectorService.cpp — Drives scripts/voice/clap_detector.py and emits+// `clap_detected()` when the Python side reports an event.+//+// Logging mirrors SpeechService / TtsService so failures (mic missing, script+// crash, etc.) are diagnosable from the central log file without re-running.++#include "services/voice_trigger/ClapDetectorService.h"++#include "core/config/AppConfig.h"+#include "core/logging/Logger.h"+#include "python/PythonRunner.h"+#include "python/PythonSetupManager.h"++#include <QFileInfo>+#include <QJsonDocument>+#include <QJsonObject>+#include <QProcessEnvironment>++namespace fincept::services {++namespace {+// Anon-namespaced + uniquely-prefixed to avoid the unity-build symbol+// collision trap that bit SpeechService / TtsService earlier.+constexpr auto CLAP_TAG = "ClapDetector";+constexpr int kClapShutdownTimeoutMs = 1500;+} // namespace++ClapDetectorService& ClapDetectorService::instance() {+ static ClapDetectorService s_instance;+ return s_instance;+}++ClapDetectorService::ClapDetectorService(QObject* parent) : QObject(parent) {+ LOG_INFO(CLAP_TAG, "ClapDetectorService initialised");+}++ClapDetectorService::~ClapDetectorService() {+ stop();+}++bool ClapDetectorService::is_active() const noexcept {+ return active_.load(std::memory_order_relaxed);+}++bool ClapDetectorService::is_enabled_in_config() {+ return AppConfig::instance().get("voice/clap_to_start/enabled", false).toBool();+}++void ClapDetectorService::start() {+ if (process_) {+ LOG_INFO(CLAP_TAG, "start: already running — no-op");+ return;+ }++ QString python_exe = python::PythonSetupManager::instance().python_path("venv-numpy2");+ if (python_exe.isEmpty() || !QFileInfo::exists(python_exe))+ python_exe = python::PythonRunner::instance().python_path();+ if (python_exe.isEmpty()) {+ LOG_ERROR(CLAP_TAG, "No Python interpreter — cannot start clap detector");+ emit error_occurred(QStringLiteral("Python not available — clap-to-start unavailable"));+ return;+ }++ const QString scripts_dir = python::PythonRunner::instance().scripts_dir();+ const QString script = scripts_dir + QStringLiteral("/voice/clap_detector.py");+ if (!QFileInfo::exists(script)) {+ LOG_ERROR(CLAP_TAG, QString("Clap detector script missing at '%1'").arg(script));+ emit error_occurred(QStringLiteral("clap_detector.py not found: ") + script);+ return;+ }++ process_ = new QProcess(this);++ QProcessEnvironment env = QProcessEnvironment::systemEnvironment();+ env.insert("PYTHONIOENCODING", "utf-8");+ env.insert("PYTHONDONTWRITEBYTECODE", "1");+ env.insert("PYTHONUNBUFFERED", "1");+ env.insert("FINCEPT_DATA_DIR", python::PythonSetupManager::instance().install_dir());++ const QString existing_pypath = env.value("PYTHONPATH");+#ifdef _WIN32+ const QChar kPathSep = ';';+#else+ const QChar kPathSep = ':';+#endif+ env.insert("PYTHONPATH", existing_pypath.isEmpty()+ ? scripts_dir+ : (scripts_dir + kPathSep + existing_pypath));++ auto& cfg = AppConfig::instance();+ const QString mode = cfg.get("voice/clap_to_start/mode", "double").toString();+ const QString peak = cfg.get("voice/clap_to_start/peak_min", "12000").toString();+ const QString ratio = cfg.get("voice/clap_to_start/pr_ratio", "4.0").toString();+ const QString gap = cfg.get("voice/clap_to_start/max_gap_ms", "1500").toString();+ const QString debounce = cfg.get("voice/clap_to_start/debounce_ms", "1500").toString();+ const QString device = cfg.get("voice/deepgram/device", "").toString();++ LOG_INFO(CLAP_TAG, QString("env: mode=%1 peak=%2 ratio=%3 gap=%4 debounce=%5 device='%6'")+ .arg(mode, peak, ratio, gap, debounce, device));++ env.insert("FINCEPT_CLAP_MODE", mode);+ env.insert("FINCEPT_CLAP_PEAK_MIN", peak);+ env.insert("FINCEPT_CLAP_PR_RATIO", ratio);+ env.insert("FINCEPT_CLAP_MAX_GAP_MS", gap);+ env.insert("FINCEPT_CLAP_DEBOUNCE_MS", debounce);+ env.insert("FINCEPT_STT_DEVICE", device);++ process_->setProcessEnvironment(env);+ process_->setWorkingDirectory(scripts_dir);+ process_->setProcessChannelMode(QProcess::SeparateChannels);++#ifdef _WIN32+ process_->setCreateProcessArgumentsModifier([](QProcess::CreateProcessArguments* cpa) {+ cpa->flags |= 0x08000000; // CREATE_NO_WINDOW+ });+#endif++ connect(process_, &QProcess::readyReadStandardOutput, this, &ClapDetectorService::on_stdout_ready);+ connect(process_, &QProcess::readyReadStandardError, this, &ClapDetectorService::on_stderr_ready);+ connect(process_, &QProcess::started, this, [this]() {+ LOG_INFO(CLAP_TAG, QString("QProcess::started — pid=%1")+ .arg(process_ ? process_->processId() : 0));+ });+ connect(process_, &QProcess::finished, this, &ClapDetectorService::on_process_finished);+ connect(process_, &QProcess::errorOccurred, this, [this](QProcess::ProcessError err) {+ LOG_ERROR(CLAP_TAG, QString("QProcess::errorOccurred err=%1").arg(static_cast<int>(err)));+ if (err == QProcess::FailedToStart) {+ emit error_occurred(QStringLiteral("Failed to start clap detector"));+ stop();+ }+ });++ stdout_buffer_.clear();+ LOG_INFO(CLAP_TAG, QString("Launching '%1' '%2'").arg(python_exe, script));+ process_->start(python_exe, {script});++ active_.store(true, std::memory_order_release);+ emit listening_changed(true);+}++void ClapDetectorService::stop() {+ if (!process_)+ return;++ LOG_INFO(CLAP_TAG, "stop — terminating clap detector");+ disconnect(process_, nullptr, this, nullptr);+ if (process_->state() != QProcess::NotRunning) {+ process_->kill();+ process_->waitForFinished(kClapShutdownTimeoutMs);+ }+ process_->deleteLater();+ process_ = nullptr;+ stdout_buffer_.clear();++ const bool was_active = active_.exchange(false, std::memory_order_acq_rel);+ if (was_active)+ emit listening_changed(false);+}++void ClapDetectorService::on_stdout_ready() {+ if (!process_)+ return;+ stdout_buffer_.append(process_->readAllStandardOutput());++ while (true) {+ const int newline_pos = stdout_buffer_.indexOf('\n');+ if (newline_pos < 0)+ break;+ const QByteArray line = stdout_buffer_.left(newline_pos).trimmed();+ stdout_buffer_.remove(0, newline_pos + 1);+ if (!line.isEmpty()) {+ LOG_DEBUG(CLAP_TAG, QString("stdout: %1").arg(QString::fromUtf8(line.left(200))));+ parse_line(line);+ }+ }+}++void ClapDetectorService::on_stderr_ready() {+ if (!process_)+ return;+ const QByteArray chunk = process_->readAllStandardError();+ if (chunk.isEmpty())+ return;+ const QString text = QString::fromUtf8(chunk).trimmed();+ if (!text.isEmpty()) {+ // Stderr is verbose by design (per-candidate logs) — keep at WARN only+ // for human-friendly visibility. Drop to DEBUG if it gets noisy.+ LOG_WARN(CLAP_TAG, QString("stderr: %1").arg(text));+ }+}++void ClapDetectorService::parse_line(const QByteArray& line) {+ QJsonParseError parse_err;+ const QJsonDocument doc = QJsonDocument::fromJson(line, &parse_err);+ if (parse_err.error != QJsonParseError::NoError) {+ LOG_WARN(CLAP_TAG, QString("non-JSON stdout: %1").arg(QString::fromUtf8(line)));+ return;+ }+ const QJsonObject obj = doc.object();++ if (obj.contains("event") && obj["event"].toString() == "clap") {+ LOG_INFO(CLAP_TAG, "Clap event detected — emitting clap_detected()");+ emit clap_detected();+ } else if (obj.contains("status")) {+ LOG_INFO(CLAP_TAG, QString("status: %1").arg(obj["status"].toString()));+ } else if (obj.contains("error")) {+ const QString msg = obj["error"].toString();+ LOG_WARN(CLAP_TAG, QString("script error: %1").arg(msg));+ emit error_occurred(msg);+ } else if (obj.contains("fatal")) {+ const QString msg = obj["fatal"].toString();+ LOG_ERROR(CLAP_TAG, QString("script fatal: %1").arg(msg));+ emit error_occurred(msg);+ }+}++void ClapDetectorService::on_process_finished(int exit_code, QProcess::ExitStatus status) {+ if (process_) {+ const QByteArray remaining_err = process_->readAllStandardError();+ if (!remaining_err.isEmpty())+ LOG_WARN(CLAP_TAG, QString("final stderr: %1").arg(QString::fromUtf8(remaining_err).trimmed()));+ }++ LOG_INFO(CLAP_TAG, QString("process exited (code=%1, status=%2)")+ .arg(exit_code)+ .arg(status == QProcess::CrashExit ? "crash" : "normal"));++ if (process_) {+ process_->deleteLater();+ process_ = nullptr;+ }+ stdout_buffer_.clear();++ const bool was_active = active_.exchange(false, std::memory_order_acq_rel);+ if (was_active)+ emit listening_changed(false);+}++} // namespace fincept::servicesdiff --git a/fincept-qt/src/services/voice_trigger/ClapDetectorService.h b/fincept-qt/src/services/voice_trigger/ClapDetectorService.hnew file mode 100644index 000000000..1e3c6d113--- /dev/null+++ b/fincept-qt/src/services/voice_trigger/ClapDetectorService.h@@ -0,0 +1,76 @@+#pragma once+// ClapDetectorService.h — Background "clap to start" mic listener.+//+// Spawns scripts/voice/clap_detector.py as a long-running QProcess that+// monitors the default microphone for a clap (or double-clap), and emits+// `clap_detected()` on the UI thread when one is heard.+//+// Privacy: the Python script analyses raw PCM in-process and never sends+// audio anywhere. This service just observes the JSON-line event stream.+//+// Lifecycle (driven by AiChatBubble):+// • Bubble constructor reads `voice/clap_to_start/enabled`. If true,+// calls start().+// • Before AiChatBubble starts STT, it calls stop() to free the mic and+// avoid the clap detector reacting to the user's own speech.+// • After STT finishes, it calls start() again if the feature is still+// enabled.++#include <QObject>+#include <QPointer>+#include <QProcess>+#include <QString>++#include <atomic>++namespace fincept::services {++class ClapDetectorService : public QObject {+ Q_OBJECT++ public:+ static ClapDetectorService& instance();++ ClapDetectorService(const ClapDetectorService&) = delete;+ ClapDetectorService& operator=(const ClapDetectorService&) = delete;++ /// Start the background listener (no-op if already running). Reads+ /// AppConfig keys for sensitivity / mode.+ void start();++ /// Stop the listener and close the mic stream. Idempotent.+ void stop();++ [[nodiscard]] bool is_active() const noexcept;++ /// Convenience helper for callers — reads AppConfig key+ /// "voice/clap_to_start/enabled" (default false).+ [[nodiscard]] static bool is_enabled_in_config();++ signals:+ /// Fired on the UI thread when a clap event is detected. The bubble+ /// connects this to start_listening().+ void clap_detected();++ /// Recoverable / fatal errors — logged + surfaced if a UI listener wants+ /// to display them. Most users will never see this.+ void error_occurred(const QString& message);++ /// Mic is open and the script is actively analysing audio.+ void listening_changed(bool active);++ private:+ explicit ClapDetectorService(QObject* parent = nullptr);+ ~ClapDetectorService() override;++ void on_stdout_ready();+ void on_stderr_ready();+ void on_process_finished(int exit_code, QProcess::ExitStatus status);+ void parse_line(const QByteArray& line);++ QPointer<QProcess> process_;+ QByteArray stdout_buffer_;+ std::atomic<bool> active_{false};+};++} // namespace fincept::servicesdiff --git a/fincept-qt/src/ui/widgets/WorldMapWidget.cpp b/fincept-qt/src/ui/widgets/WorldMapWidget.cppindex f8bf8094c..402c3d518 100644--- a/fincept-qt/src/ui/widgets/WorldMapWidget.cpp+++ b/fincept-qt/src/ui/widgets/WorldMapWidget.cpp@@ -19,6 +19,36 @@namespace fincept::ui {+// ── Clickable pin marker ────────────────────────────────────────────────────+//+// QGVIcon itself is not interactive; we subclass it to receive map click+// events via `projOnMouseClick` and bounce them back through a stored+// callback. Pins that don't carry an id (the default -1) skip the wiring+// entirely so non-interactive maps stay free of click overhead.+namespace {+class ClickableIcon : public QGVIcon {+ public:+ explicit ClickableIcon(int id, QString tooltip, std::function<void(int)> on_click)+ : id_(id), tooltip_(std::move(tooltip)), on_click_(std::move(on_click)) {}++ protected:+ void projOnMouseClick(const QPointF& projPos) override {+ Q_UNUSED(projPos);+ if (on_click_)+ on_click_(id_);+ }+ QString projTooltip(const QPointF& projPos) const override {+ Q_UNUSED(projPos);+ return tooltip_;+ }++ private:+ int id_;+ QString tooltip_;+ std::function<void(int)> on_click_;+};+} // namespace+// ── One-time network manager setup for QGeoView tile loading ────────────────static void ensure_network_manager() {if (QGV::getNetworkManager())@@ -114,10 +144,17 @@ void WorldMapWidget::rebuild_markers() {// Add new markersfor (const auto& pin : pins_) {- auto* icon = new QGVIcon();+ QGVIcon* icon = nullptr;+ QGV::ItemFlags flags = QGV::ItemFlag::IgnoreScale | QGV::ItemFlag::IgnoreAzimuth;+ if (pin.id >= 0) {+ icon = new ClickableIcon(pin.id, pin.label, [this](int id) { emit pin_clicked(id); });+ flags |= QGV::ItemFlag::Clickable;+ } else {+ icon = new QGVIcon();+ }icon->setGeometry(QGV::GeoPos(pin.latitude, pin.longitude), QSizeF(20, 20));icon->loadImage(make_marker_image(pin.color, pin.radius));- icon->setFlags(QGV::ItemFlag::IgnoreScale | QGV::ItemFlag::IgnoreAzimuth);+ icon->setFlags(flags);marker_layer_->addItem(icon);}}diff --git a/fincept-qt/src/ui/widgets/WorldMapWidget.h b/fincept-qt/src/ui/widgets/WorldMapWidget.hindex a0128dd0e..48fe3ebbb 100644--- a/fincept-qt/src/ui/widgets/WorldMapWidget.h+++ b/fincept-qt/src/ui/widgets/WorldMapWidget.h@@ -17,6 +17,10 @@ struct MapPin {QString label;QColor color{255, 100, 0};double radius = 5.0;+ /// Caller-assigned identifier carried back through `pin_clicked`.+ /// Useful for mapping a click to a row in a side table or to a domain+ /// object — leave at -1 if the pin is not interactive.+ int id = -1;};/// Interactive world map widget backed by QGeoView (real OSM/CartoDB tiles).@@ -38,7 +42,9 @@ class WorldMapWidget : public QWidget {void fit_to_pins();signals:- void pin_clicked(const QString& label, double lat, double lng);+ /// Emitted when a pin with `id != -1` is clicked. Carries the caller-+ /// assigned id so the consumer can resolve back to its own data.+ void pin_clicked(int id);private:void rebuild_markers();diff --git a/fincept-qt/tests/CMakeLists.txt b/fincept-qt/tests/CMakeLists.txtindex 5fd9b86fa..739ad3820 100644--- a/fincept-qt/tests/CMakeLists.txt+++ b/fincept-qt/tests/CMakeLists.txt@@ -34,3 +34,69 @@ set_target_properties(test_datahub PROPERTIES)add_test(NAME datahub COMMAND test_datahub)++# ── MCP schema validator tests (Phase 3) ────────────────────────────────────+# Header-only ToolSchema/ToolSchemaBuilder + the SchemaValidator translation unit.+# No dependency on the rest of the MCP system — McpProvider/McpService are not linked.++add_executable(test_validator+ mcp/test_validator.cpp+ ../src/mcp/SchemaValidator.cpp+)++target_include_directories(test_validator PRIVATE+ ../src+)++target_link_libraries(test_validator PRIVATE+ Qt6::Core+ Qt6::Test+)++set_target_properties(test_validator PROPERTIES+ UNITY_BUILD OFF+ AUTOMOC ON+)++add_test(NAME mcp_validator COMMAND test_validator)++# ── MCP async dispatch tests (Phase 4) ──────────────────────────────────────+# Links McpProvider + SchemaValidator + Logger. Doesn't link McpService /+# McpManager / external client stack — async tests don't need them.++add_executable(test_async+ mcp/test_async.cpp+ ../src/mcp/McpProvider.cpp+ ../src/mcp/SchemaValidator.cpp+ ../src/core/logging/Logger.cpp+)++target_include_directories(test_async PRIVATE+ ../src+)++target_link_libraries(test_async PRIVATE+ Qt6::Core+ Qt6::Test+)++set_target_properties(test_async PROPERTIES+ UNITY_BUILD OFF+ AUTOMOC ON+)++add_test(NAME mcp_async COMMAND test_async)++# ── MCP dispatcher tests (Phase 5) ──────────────────────────────────────────+# Test source kept (mcp/test_dispatcher.cpp) but executable target is disabled:+# wiring it up requires linking the full McpManager + storage stack+# (McpServerRepository → Database.h → QSqlDatabase + every other repository+# transitively pulled). That blows up the test footprint without buying+# coverage Phase 5 doesn't already get from integration. Re-enable when+# McpService gains a dependency-injectable external-dispatch hook.+#+# add_executable(test_dispatcher+# mcp/test_dispatcher.cpp+# ...+# )+# add_test(NAME mcp_dispatcher COMMAND test_dispatcher)diff --git a/fincept-qt/tests/mcp/test_async.cpp b/fincept-qt/tests/mcp/test_async.cppnew file mode 100644index 000000000..28844bf28--- /dev/null+++ b/fincept-qt/tests/mcp/test_async.cpp@@ -0,0 +1,196 @@+// test_async.cpp — Phase 4 async-handler dispatch tests.+//+// Validates the dual-shape contract on McpProvider: sync handlers return+// immediately, async handlers resolve their QPromise on a callback, and+// the provider's timeout watchdog fires when the handler stalls.++#include "mcp/AsyncDispatch.h"+#include "mcp/McpProvider.h"+#include "mcp/McpTypes.h"++#include <QCoreApplication>+#include <QFuture>+#include <QObject>+#include <QPromise>+#include <QTest>+#include <QTimer>++#include <atomic>+#include <chrono>+#include <memory>++using fincept::mcp::AsyncToolHandler;+using fincept::mcp::McpProvider;+using fincept::mcp::ToolContext;+using fincept::mcp::ToolDef;+using fincept::mcp::ToolHandler;+using fincept::mcp::ToolResult;++class TestAsyncDispatch : public QObject {+ Q_OBJECT++ private:+ void clear_provider() {+ McpProvider::instance().clear();+ }++ private slots:++ void cleanup() {+ clear_provider();+ }++ // ── Sync legacy handler still works ─────────────────────────────────++ void syncHandler_returnsResult() {+ clear_provider();+ ToolDef t;+ t.name = "sync_ok";+ t.handler = [](const QJsonObject&) -> ToolResult {+ return ToolResult::ok_data(QJsonObject{{"value", 42}});+ };+ McpProvider::instance().register_tool(std::move(t));++ auto fut = McpProvider::instance().call_tool_async("sync_ok", {});+ fut.waitForFinished();+ QVERIFY(fut.resultCount() > 0);+ const auto r = fut.result();+ QVERIFY(r.success);+ QCOMPARE(r.data.toObject()["value"].toInt(), 42);+ }++ void syncHandler_rejectsViaValidation() {+ clear_provider();+ ToolDef t;+ t.name = "sync_validates";+ t.input_schema.required = {"required_field"};+ t.input_schema.properties = QJsonObject{+ {"required_field", QJsonObject{{"type", "string"}}}};+ t.handler = [](const QJsonObject&) { return ToolResult::ok("never reached"); };+ McpProvider::instance().register_tool(std::move(t));++ auto fut = McpProvider::instance().call_tool_async("sync_validates", {});+ fut.waitForFinished();+ const auto r = fut.result();+ QVERIFY(!r.success);+ QVERIFY(r.error.contains("required_field"));+ }++ // ── Async handler resolves via callback ─────────────────────────────++ void asyncHandler_resolvesEventually() {+ clear_provider();+ ToolDef t;+ t.name = "async_ok";+ t.async_handler = [](const QJsonObject&, ToolContext,+ std::shared_ptr<QPromise<ToolResult>> promise) {+ QTimer::singleShot(20, [promise]() {+ promise->addResult(ToolResult::ok("done"));+ promise->finish();+ });+ };+ McpProvider::instance().register_tool(std::move(t));++ auto fut = McpProvider::instance().call_tool_async("async_ok", {});+ QVERIFY(QTest::qWaitFor([&] { return fut.isFinished(); }, 1000));+ QVERIFY(fut.resultCount() > 0);+ QVERIFY(fut.result().success);+ }++ // ── Timeout fires when handler stalls ────────────────────────────────++ void asyncHandler_timesOut() {+ clear_provider();+ ToolDef t;+ t.name = "async_stalls";+ t.default_timeout_ms = 100; // tight timeout+ t.async_handler = [](const QJsonObject&, ToolContext,+ std::shared_ptr<QPromise<ToolResult>>) {+ // Never resolves — provider's timeout should kick in.+ };+ McpProvider::instance().register_tool(std::move(t));++ auto fut = McpProvider::instance().call_tool_async("async_stalls", {});+ QVERIFY(QTest::qWaitFor([&] { return fut.isFinished(); }, 2000));+ const auto r = fut.result();+ QVERIFY(!r.success);+ QVERIFY(r.error.contains("timed out"));+ }++ // ── Cancellation observed via ctx.is_cancelled ──────────────────────++ void asyncHandler_observesCancellation() {+ clear_provider();+ ToolDef t;+ t.name = "async_cancellable";+ t.default_timeout_ms = 200; // forces is_cancelled to flip when timeout fires+ t.async_handler = [](const QJsonObject&, ToolContext ctx,+ std::shared_ptr<QPromise<ToolResult>> promise) {+ // Poll for cancellation, then resolve gracefully when set.+ auto* poll = new QTimer;+ poll->setInterval(20);+ QObject::connect(poll, &QTimer::timeout, poll, [poll, ctx, promise]() {+ if (ctx.cancelled()) {+ if (!promise->future().isFinished()) {+ promise->addResult(ToolResult::fail("cancelled by handler"));+ promise->finish();+ }+ poll->deleteLater();+ }+ });+ poll->start();+ };+ McpProvider::instance().register_tool(std::move(t));++ auto fut = McpProvider::instance().call_tool_async("async_cancellable", {});+ QVERIFY(QTest::qWaitFor([&] { return fut.isFinished(); }, 2000));+ const auto r = fut.result();+ QVERIFY(!r.success);+ // Either the watchdog OR the handler's own check produced the failure;+ // both are acceptable as long as something resolves the promise.+ QVERIFY(r.error.contains("timed out") || r.error.contains("cancelled"));+ }++ // ── Tool-not-found short-circuits ────────────────────────────────────++ void unknownTool_failsImmediately() {+ clear_provider();+ auto fut = McpProvider::instance().call_tool_async("does_not_exist", {});+ QVERIFY(fut.isFinished());+ QVERIFY(!fut.result().success);+ QVERIFY(fut.result().error.contains("not found"));+ }++ // ── Both sync and async work via blocking call_tool ─────────────────++ void blockingCallTool_sync() {+ clear_provider();+ ToolDef t;+ t.name = "block_sync";+ t.handler = [](const QJsonObject&) { return ToolResult::ok("sync"); };+ McpProvider::instance().register_tool(std::move(t));++ auto r = McpProvider::instance().call_tool("block_sync", {});+ QCOMPARE(r.message, QString("sync"));+ }++ void blockingCallTool_async() {+ clear_provider();+ ToolDef t;+ t.name = "block_async";+ t.async_handler = [](const QJsonObject&, ToolContext,+ std::shared_ptr<QPromise<ToolResult>> promise) {+ QTimer::singleShot(20, [promise]() {+ promise->addResult(ToolResult::ok("async-via-blocking"));+ promise->finish();+ });+ };+ McpProvider::instance().register_tool(std::move(t));++ auto r = McpProvider::instance().call_tool("block_async", {});+ QCOMPARE(r.message, QString("async-via-blocking"));+ }+};++QTEST_MAIN(TestAsyncDispatch)+#include "test_async.moc"diff --git a/fincept-qt/tests/mcp/test_dispatcher.cpp b/fincept-qt/tests/mcp/test_dispatcher.cppnew file mode 100644index 000000000..67d38cbc2--- /dev/null+++ b/fincept-qt/tests/mcp/test_dispatcher.cpp@@ -0,0 +1,262 @@+// test_dispatcher.cpp — Phase 5 ToolDispatcher tests.+//+// Validates the multi-round orchestration loop using a mock adapter and+// pre-registered MCP tools. Confirms:+// • No tool calls → text returned in one round+// • One tool call → execute → follow-up returns final text+// • Two tool calls in one round → fan-out via execute_openai_function_async+// • Cancellation between rounds → loop terminates with error+// • Max rounds exhausted → max_rounds_hit set++#include "mcp/McpProvider.h"+#include "mcp/McpService.h"+#include "mcp/McpTypes.h"+#include "mcp/dispatch/ProviderAdapter.h"+#include "mcp/dispatch/ToolDispatcher.h"++#include <QCoreApplication>+#include <QFuture>+#include <QObject>+#include <QPromise>+#include <QTest>++#include <atomic>+#include <memory>++using fincept::ai_chat::ConversationMessage;+using fincept::mcp::McpProvider;+using fincept::mcp::ToolDef;+using fincept::mcp::ToolResult;+using fincept::mcp::dispatch::ProviderAdapter;+using fincept::mcp::dispatch::ToolDispatcher;+using fincept::mcp::dispatch::ToolInvocation;+using fincept::mcp::dispatch::ToolResultEnvelope;++namespace {++/// Test adapter with scriptable behaviour. Each round, returns a queued+/// "response" — either a final-text response or a synthetic tool-call+/// response that the dispatcher must execute and follow-up.+class ScriptedAdapter : public ProviderAdapter {+ public:+ QString id() const override { return "scripted"; }+ int default_max_rounds() const override { return max_rounds_; }++ QJsonObject build_initial_request(const QString&,+ const std::vector<ConversationMessage>&,+ const QJsonArray&) const override {+ return QJsonObject{{"round", 0}};+ }++ std::vector<ToolInvocation> parse_tool_invocations(const QJsonObject& response) const override {+ std::vector<ToolInvocation> out;+ QJsonArray calls = response["tool_calls"].toArray();+ for (const auto& c : calls) {+ QJsonObject co = c.toObject();+ ToolInvocation inv;+ inv.call_id = co["id"].toString();+ inv.function_name = co["name"].toString();+ inv.arguments = co["arguments"].toObject();+ inv.origin = "scripted";+ out.push_back(std::move(inv));+ }+ return out;+ }++ QJsonObject build_followup_request(const QJsonObject&,+ const std::vector<ToolResultEnvelope>& results,+ const QString&,+ const std::vector<ConversationMessage>&) const override {+ QJsonArray rs;+ for (const auto& r : results)+ rs.append(QJsonObject{{"call_id", r.call_id}, {"result", r.result.to_json()}});+ QJsonObject body;+ body["followup_results"] = rs;+ return body;+ }++ QString extract_text(const QJsonObject& response) const override {+ return response["text"].toString();+ }++ int max_rounds_ = 5;+};++} // anonymous namespace++class TestDispatcher : public QObject {+ Q_OBJECT++ private:+ void clear_provider() { McpProvider::instance().clear(); }++ private slots:++ void cleanup() { clear_provider(); }++ // ── No tool calls → text returned ────────────────────────────────────++ void noToolCalls_returnsTextImmediately() {+ clear_provider();+ ScriptedAdapter adapter;+ ToolDispatcher dispatcher;++ auto send = [](QJsonObject) {+ QPromise<QJsonObject> p;+ p.start();+ p.addResult(QJsonObject{{"text", "hello"}});+ p.finish();+ return p.future();+ };++ auto out = dispatcher.run("hi", {}, adapter, send, {}, {});+ QCOMPARE(out.text, QString("hello"));+ QCOMPARE(out.rounds_used, 1);+ QVERIFY(!out.max_rounds_hit);+ QVERIFY(out.error.isEmpty());+ }++ // ── One tool call → execute → follow-up returns text ────────────────++ void singleToolCall_executesAndFollowsUp() {+ clear_provider();+ ToolDef t;+ t.name = "echo";+ t.handler = [](const QJsonObject& args) {+ return ToolResult::ok_data(QJsonObject{{"echo", args["msg"].toString()}});+ };+ McpProvider::instance().register_tool(std::move(t));++ ScriptedAdapter adapter;+ ToolDispatcher dispatcher;++ // Round 0: request a tool call. Round 1: return text.+ auto round = std::make_shared<int>(0);+ auto send = [round](QJsonObject) {+ QPromise<QJsonObject> p;+ p.start();+ if (*round == 0) {+ ++*round;+ p.addResult(QJsonObject{+ {"tool_calls",+ QJsonArray{QJsonObject{{"id", "c1"},+ {"name", "fincept-terminal__echo"},+ {"arguments", QJsonObject{{"msg", "hi"}}}}}}});+ } else {+ p.addResult(QJsonObject{{"text", "done"}});+ }+ p.finish();+ return p.future();+ };++ auto out = dispatcher.run("hi", {}, adapter, send, {}, {});+ QCOMPARE(out.text, QString("done"));+ QCOMPARE(out.rounds_used, 2);+ }++ // ── Two tool calls in one round → both execute via fan-out ─────────++ void twoToolCalls_inOneRound_bothExecute() {+ clear_provider();+ std::atomic<int> call_count{0};+ ToolDef t;+ t.name = "counter";+ t.handler = [&call_count](const QJsonObject&) {+ ++call_count;+ return ToolResult::ok("ok");+ };+ McpProvider::instance().register_tool(std::move(t));++ ScriptedAdapter adapter;+ ToolDispatcher dispatcher;++ auto round = std::make_shared<int>(0);+ auto send = [round](QJsonObject) {+ QPromise<QJsonObject> p;+ p.start();+ if (*round == 0) {+ ++*round;+ p.addResult(QJsonObject{+ {"tool_calls",+ QJsonArray{+ QJsonObject{{"id", "a"}, {"name", "fincept-terminal__counter"}, {"arguments", QJsonObject{}}},+ QJsonObject{{"id", "b"}, {"name", "fincept-terminal__counter"}, {"arguments", QJsonObject{}}}}}});+ } else {+ p.addResult(QJsonObject{{"text", "done"}});+ }+ p.finish();+ return p.future();+ };++ auto out = dispatcher.run("hi", {}, adapter, send, {}, {});+ QCOMPARE(out.text, QString("done"));+ QCOMPARE(call_count.load(), 2);+ }++ // ── Cancellation between rounds ──────────────────────────────────────++ void cancellation_terminatesLoop() {+ clear_provider();+ ToolDef t;+ t.name = "noop";+ t.handler = [](const QJsonObject&) { return ToolResult::ok("ok"); };+ McpProvider::instance().register_tool(std::move(t));++ ScriptedAdapter adapter;+ ToolDispatcher dispatcher;+ auto cancel_flag = std::make_shared<std::atomic<bool>>(false);++ // Always returns a tool call — would loop forever absent cancellation.+ auto send = [cancel_flag](QJsonObject) {+ cancel_flag->store(true); // cancel after first response+ QPromise<QJsonObject> p;+ p.start();+ p.addResult(QJsonObject{+ {"tool_calls",+ QJsonArray{QJsonObject{{"id", "x"},+ {"name", "fincept-terminal__noop"},+ {"arguments", QJsonObject{}}}}}});+ p.finish();+ return p.future();+ };++ auto out = dispatcher.run("hi", {}, adapter, send, {}, cancel_flag);+ QVERIFY(!out.error.isEmpty());+ QVERIFY(out.error.contains("cancelled"));+ }++ // ── Max rounds exhausted ─────────────────────────────────────────────++ void maxRounds_exhausted() {+ clear_provider();+ ToolDef t;+ t.name = "noop";+ t.handler = [](const QJsonObject&) { return ToolResult::ok("ok"); };+ McpProvider::instance().register_tool(std::move(t));++ ScriptedAdapter adapter;+ adapter.max_rounds_ = 3;+ ToolDispatcher dispatcher;++ // Always returns a tool call — exhausts rounds.+ auto send = [](QJsonObject) {+ QPromise<QJsonObject> p;+ p.start();+ p.addResult(QJsonObject{+ {"text", ""},+ {"tool_calls",+ QJsonArray{QJsonObject{{"id", "x"},+ {"name", "fincept-terminal__noop"},+ {"arguments", QJsonObject{}}}}}});+ p.finish();+ return p.future();+ };++ auto out = dispatcher.run("hi", {}, adapter, send, {}, {});+ QVERIFY(out.max_rounds_hit);+ QCOMPARE(out.rounds_used, 3);+ }+};++QTEST_MAIN(TestDispatcher)+#include "test_dispatcher.moc"diff --git a/fincept-qt/tests/mcp/test_validator.cpp b/fincept-qt/tests/mcp/test_validator.cppnew file mode 100644index 000000000..002a6e852--- /dev/null+++ b/fincept-qt/tests/mcp/test_validator.cpp@@ -0,0 +1,253 @@+// test_validator.cpp — Phase 3 validator unit tests+//+// Covers the dual-shape contract (legacy `properties` + structured `params`),+// default injection, required check, type / enum / range / pattern enforcement,+// and unknown-key tolerance. Uses Qt Test.++#include "mcp/McpTypes.h"+#include "mcp/SchemaValidator.h"+#include "mcp/ToolSchemaBuilder.h"++#include <QJsonArray>+#include <QObject>+#include <QTest>++using fincept::mcp::ToolSchema;+using fincept::mcp::ToolSchemaBuilder;+using fincept::mcp::validate_args;++class TestValidator : public QObject {+ Q_OBJECT++ private slots:++ // ── Required ────────────────────────────────────────────────────────++ void missingRequired_fails() {+ ToolSchema s = ToolSchemaBuilder()+ .string("symbol", "Ticker").required()+ .build();+ QJsonObject args{};+ auto r = validate_args(s, args);+ QVERIFY(r.is_err());+ QVERIFY(QString::fromStdString(r.error()).contains("symbol"));+ }++ void requiredPresent_succeeds() {+ ToolSchema s = ToolSchemaBuilder()+ .string("symbol", "Ticker").required()+ .build();+ QJsonObject args{{"symbol", "AAPL"}};+ QVERIFY(validate_args(s, args).is_ok());+ }++ // ── Type checks ─────────────────────────────────────────────────────++ void wrongType_fails() {+ ToolSchema s = ToolSchemaBuilder()+ .integer("limit", "Max items")+ .build();+ QJsonObject args{{"limit", "twenty"}}; // string instead of integer+ auto r = validate_args(s, args);+ QVERIFY(r.is_err());+ QVERIFY(QString::fromStdString(r.error()).contains("limit"));+ QVERIFY(QString::fromStdString(r.error()).contains("integer"));+ }++ void integerRejectsFractional() {+ ToolSchema s = ToolSchemaBuilder()+ .integer("limit", "Max items")+ .build();+ QJsonObject args{{"limit", 3.5}};+ QVERIFY(validate_args(s, args).is_err());+ }++ void numberAcceptsFractional() {+ ToolSchema s = ToolSchemaBuilder()+ .number("price", "Price")+ .build();+ QJsonObject args{{"price", 1.23}};+ QVERIFY(validate_args(s, args).is_ok());+ }++ // ── Enum ────────────────────────────────────────────────────────────++ void enumViolation_fails() {+ ToolSchema s = ToolSchemaBuilder()+ .string("side", "buy or sell").required()+ .enums({"buy", "sell"})+ .build();+ QJsonObject args{{"side", "long"}};+ auto r = validate_args(s, args);+ QVERIFY(r.is_err());+ QVERIFY(QString::fromStdString(r.error()).contains("side"));+ }++ void enumMatch_succeeds() {+ ToolSchema s = ToolSchemaBuilder()+ .string("side", "buy or sell").required()+ .enums({"buy", "sell"})+ .build();+ QJsonObject args{{"side", "buy"}};+ QVERIFY(validate_args(s, args).is_ok());+ }++ // ── Range / length / pattern ────────────────────────────────────────++ void numberOutOfRange_fails() {+ ToolSchema s = ToolSchemaBuilder()+ .integer("limit", "Limit").between(1, 100)+ .build();+ QJsonObject args1{{"limit", 0}};+ QVERIFY(validate_args(s, args1).is_err());++ QJsonObject args2{{"limit", 999}};+ QVERIFY(validate_args(s, args2).is_err());++ QJsonObject args3{{"limit", 50}};+ QVERIFY(validate_args(s, args3).is_ok());+ }++ void stringLength_enforced() {+ ToolSchema s = ToolSchemaBuilder()+ .string("title", "Title").length(1, 5)+ .build();+ QJsonObject too_short{{"title", ""}};+ QVERIFY(validate_args(s, too_short).is_err());++ QJsonObject too_long{{"title", "abcdef"}};+ QVERIFY(validate_args(s, too_long).is_err());++ QJsonObject ok{{"title", "abc"}};+ QVERIFY(validate_args(s, ok).is_ok());+ }++ void patternMismatch_fails() {+ ToolSchema s = ToolSchemaBuilder()+ .string("symbol", "Ticker").pattern("^[A-Z]{1,5}$")+ .build();+ QJsonObject bad{{"symbol", "lowercase"}};+ QVERIFY(validate_args(s, bad).is_err());++ QJsonObject good{{"symbol", "AAPL"}};+ QVERIFY(validate_args(s, good).is_ok());+ }++ // ── Defaults ────────────────────────────────────────────────────────++ void defaultsInjectedWhenAbsent() {+ ToolSchema s = ToolSchemaBuilder()+ .string("category", "Filter")+ .default_str("ALL").enums({"ALL", "MARKETS"})+ .integer("limit", "Max").default_int(20)+ .boolean("force", "Force").default_bool(false)+ .build();+ QJsonObject args{};+ QVERIFY(validate_args(s, args).is_ok());+ QCOMPARE(args["category"].toString(), QString("ALL"));+ QCOMPARE(args["limit"].toInt(), 20);+ QCOMPARE(args["force"].toBool(), false);+ }++ void defaultsDontOverrideCallerValues() {+ ToolSchema s = ToolSchemaBuilder()+ .integer("limit", "Max").default_int(20)+ .build();+ QJsonObject args{{"limit", 50}};+ QVERIFY(validate_args(s, args).is_ok());+ QCOMPARE(args["limit"].toInt(), 50);+ }++ // ── Optional + no default ───────────────────────────────────────────++ void optionalAbsentNoDefault_succeeds() {+ ToolSchema s = ToolSchemaBuilder()+ .string("query", "Optional search")+ .build();+ QJsonObject args{};+ QVERIFY(validate_args(s, args).is_ok());+ QVERIFY(!args.contains("query"));+ }++ // ── Unknown keys ────────────────────────────────────────────────────++ void unknownKey_isAllowed() {+ ToolSchema s = ToolSchemaBuilder()+ .string("symbol", "Ticker").required()+ .build();+ QJsonObject args{{"symbol", "AAPL"}, {"_meta", "extra"}};+ QVERIFY(validate_args(s, args).is_ok());+ }++ // ── Legacy `properties` shape ───────────────────────────────────────++ void legacyShape_validatesType() {+ ToolSchema s;+ s.properties = QJsonObject{+ {"limit", QJsonObject{{"type", "integer"}, {"description", "Max"}}}};+ QJsonObject bad{{"limit", "not a number"}};+ QVERIFY(validate_args(s, bad).is_err());++ QJsonObject good{{"limit", 10}};+ QVERIFY(validate_args(s, good).is_ok());+ }++ void legacyShape_validatesRequired() {+ ToolSchema s;+ s.properties = QJsonObject{+ {"symbol", QJsonObject{{"type", "string"}}}};+ s.required = {"symbol"};+ QJsonObject empty{};+ QVERIFY(validate_args(s, empty).is_err());++ QJsonObject good{{"symbol", "AAPL"}};+ QVERIFY(validate_args(s, good).is_ok());+ }++ void legacyShape_picksUpEnum() {+ ToolSchema s;+ QJsonArray allowed{"buy", "sell"};+ s.properties = QJsonObject{+ {"side", QJsonObject{{"type", "string"}, {"enum", allowed}}}};+ QJsonObject bad{{"side", "long"}};+ QVERIFY(validate_args(s, bad).is_err());+ }++ // ── to_json output ──────────────────────────────────────────────────++ void toJson_includesEnumAndDefault() {+ ToolSchema s = ToolSchemaBuilder()+ .string("category", "Filter")+ .default_str("ALL").enums({"ALL", "MARKETS"})+ .build();+ QJsonObject j = s.to_json();+ QJsonObject category = j["properties"].toObject()["category"].toObject();+ QCOMPARE(category["default"].toString(), QString("ALL"));+ QJsonArray e = category["enum"].toArray();+ QCOMPARE(e.size(), 2);+ }++ void toJson_mergesLegacyAndStructured() {+ ToolSchema s;+ s.properties = QJsonObject{+ {"old_field", QJsonObject{{"type", "string"}}}};+ s.params.insert("new_field", []() {+ fincept::mcp::ToolParam p;+ p.type = "integer";+ p.required = true;+ return p;+ }());++ QJsonObject j = s.to_json();+ QJsonObject props = j["properties"].toObject();+ QVERIFY(props.contains("old_field"));+ QVERIFY(props.contains("new_field"));++ QJsonArray req = j["required"].toArray();+ QCOMPARE(req.size(), 1);+ QCOMPARE(req[0].toString(), QString("new_field"));+ }+};++QTEST_MAIN(TestValidator)+#include "test_validator.moc"