Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(dashboard): chat media, engine→Infrastructure, dashboard analytics, and config-modal polish
Yudhi Armyndharis4b6bdc1c32c3
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ab483aa63..a20a99940 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,26 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Added++- Dashboard: a **Message Analytics** section — a period selector (24h / 7d / 30d) with messages-over-time, messages-by-type, and top-chats charts, sourced from the existing statistics endpoints. The charting bundle is code-split so it loads only with the Dashboard, not on the login screen.+- Infrastructure: an **Engine Configuration** tile to pick and configure the active WhatsApp engine (whatsapp-web.js / Baileys), mirroring the Database tile. Selecting an engine persists the choice and applies on restart.++### Changed++- Dashboard: the **Messages Today** card is now populated from real data, and the previously-empty **API Calls** card is replaced with a **Total Messages** metric. The sidebar version is now read live from the backend, so a stale-built bundle no longer shows the wrong version.+- Plugins: the WhatsApp engine adapters are no longer listed as plugin cards — they are configured under **Infrastructure → Engine**. The Plugins page is now extensions-only.+- Plugins config dialog: the Configuration/Sessions and install tabs use a cleaner segmented control; the modal caps its height and scrolls its body with a pinned header and footer (Save is always reachable) and is wider for config-heavy plugins.+- ⚠️ **Deployment:** the bundled docker-compose files no longer pin `ENGINE_TYPE`, so the active engine can be chosen from **Infrastructure → Engine** (persisted to `data/.env.generated`). A real container/host `ENGINE_TYPE` env still takes precedence; leave it unset to let the dashboard control the engine.++### Fixed++- Chats: voice notes and videos now play — the Content-Security-Policy was missing a `media-src` for `data:` URIs, so the browser blocked inline audio/video.+- Chats: stickers, images, videos and documents loaded from history now render instead of collapsing to an empty timestamp-only bubble (history is fetched with its media payload).+- Chats: on small screens the conversation back-button icon is now visible (inherited button padding had squeezed it to zero width).+- Plugins config dialog: radio buttons on the Sessions tab no longer stretch to full width and strand their labels.+- Infrastructure: the engine status and the engine config form now reflect the real saved headless / session-path / browser-argument values instead of always showing defaults.+## [0.7.0] - 2026-06-23> **v0.7 — plugin-contract expansion.** Richer plugin config (declarative + sandboxed-iframe editors),diff --git a/dashboard/package-lock.json b/dashboard/package-lock.jsonindex 6ef355e67..988762a38 100644--- a/dashboard/package-lock.json+++ b/dashboard/package-lock.json@@ -16,7 +16,9 @@"react": "^19.2.7","react-dom": "^19.2.7","react-i18next": "^17.0.8",+ "react-is": "^19.2.7","react-router-dom": "^7.18.0",+ "recharts": "^3.9.0","socket.io-client": "^4.8.3"},"devDependencies": {@@ -576,6 +578,42 @@"url": "https://github.com/sponsors/Boshen"}},+ "node_modules/@reduxjs/toolkit": {+ "version": "2.12.0",+ "resolved": "https://registry.npmjs.org/@reduxjs/toolkit/-/toolkit-2.12.0.tgz",+ "integrity": "sha512-KiT+RzZbp6mQET+Mg+h2c97+9j1sNflUxQkIHI7Yuzf6Peu+OYpmkn6nbHWmLLWj+1ZODUJFwGZ7gx3L9R9EOw==",+ "license": "MIT",+ "dependencies": {+ "@standard-schema/spec": "^1.0.0",+ "@standard-schema/utils": "^0.3.0",+ "immer": "^11.0.0",+ "redux": "^5.0.1",+ "redux-thunk": "^3.1.0",+ "reselect": "^5.1.0"+ },+ "peerDependencies": {+ "react": "^16.9.0 || ^17.0.0 || ^18 || ^19",+ "react-redux": "^7.2.1 || ^8.1.3 || ^9.0.0"+ },+ "peerDependenciesMeta": {+ "react": {+ "optional": true+ },+ "react-redux": {+ "optional": true+ }+ }+ },+ "node_modules/@reduxjs/toolkit/node_modules/immer": {+ "version": "11.1.8",+ "resolved": "https://registry.npmjs.org/immer/-/immer-11.1.8.tgz",+ "integrity": "sha512-/tbkHMW7y10Lx6i1crLjD4/OhNkRG+Fo7byZHtah0547nIeXYcpIXaUh0IAQY6gO5459qpGGYapcEOHtFXkIuA==",+ "license": "MIT",+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/immer"+ }+ },"node_modules/@rolldown/binding-android-arm64": {"version": "1.0.3","resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.0.3.tgz",@@ -846,6 +884,18 @@"integrity": "sha512-9BCxFwvbGg/RsZK9tjXd8s4UcwR0MWeFQ1XEKIQVVvAGJyINdrqKMcTRyLoK8Rse1GjzLV9cwjWV1olXRWEXVA==","license": "MIT"},+ "node_modules/@standard-schema/spec": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz",+ "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==",+ "license": "MIT"+ },+ "node_modules/@standard-schema/utils": {+ "version": "0.3.0",+ "resolved": "https://registry.npmjs.org/@standard-schema/utils/-/utils-0.3.0.tgz",+ "integrity": "sha512-e7Mew686owMaPJVNNLs55PUvgz371nKgwsc4vxE49zsODpJEnxgxRo2y/OKrqueavXgZNMDVj3DdHFlaSAeU8g==",+ "license": "MIT"+ },"node_modules/@tanstack/query-core": {"version": "5.101.0","resolved": "https://registry.npmjs.org/@tanstack/query-core/-/query-core-5.101.0.tgz",@@ -916,6 +966,69 @@"tslib": "^2.4.0"}},+ "node_modules/@types/d3-array": {+ "version": "3.2.2",+ "resolved": "https://registry.npmjs.org/@types/d3-array/-/d3-array-3.2.2.tgz",+ "integrity": "sha512-hOLWVbm7uRza0BYXpIIW5pxfrKe0W+D5lrFiAEYR+pb6w3N2SwSMaJbXdUfSEv+dT4MfHBLtn5js0LAWaO6otw==",+ "license": "MIT"+ },+ "node_modules/@types/d3-color": {+ "version": "3.1.3",+ "resolved": "https://registry.npmjs.org/@types/d3-color/-/d3-color-3.1.3.tgz",+ "integrity": "sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A==",+ "license": "MIT"+ },+ "node_modules/@types/d3-ease": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/@types/d3-ease/-/d3-ease-3.0.2.tgz",+ "integrity": "sha512-NcV1JjO5oDzoK26oMzbILE6HW7uVXOHLQvHshBUW4UMdZGfiY6v5BeQwh9a9tCzv+CeefZQHJt5SRgK154RtiA==",+ "license": "MIT"+ },+ "node_modules/@types/d3-interpolate": {+ "version": "3.0.4",+ "resolved": "https://registry.npmjs.org/@types/d3-interpolate/-/d3-interpolate-3.0.4.tgz",+ "integrity": "sha512-mgLPETlrpVV1YRJIglr4Ez47g7Yxjl1lj7YKsiMCb27VJH9W8NVM6Bb9d8kkpG/uAQS5AmbA48q2IAolKKo1MA==",+ "license": "MIT",+ "dependencies": {+ "@types/d3-color": "*"+ }+ },+ "node_modules/@types/d3-path": {+ "version": "3.1.1",+ "resolved": "https://registry.npmjs.org/@types/d3-path/-/d3-path-3.1.1.tgz",+ "integrity": "sha512-VMZBYyQvbGmWyWVea0EHs/BwLgxc+MKi1zLDCONksozI4YJMcTt8ZEuIR4Sb1MMTE8MMW49v0IwI5+b7RmfWlg==",+ "license": "MIT"+ },+ "node_modules/@types/d3-scale": {+ "version": "4.0.9",+ "resolved": "https://registry.npmjs.org/@types/d3-scale/-/d3-scale-4.0.9.tgz",+ "integrity": "sha512-dLmtwB8zkAeO/juAMfnV+sItKjlsw2lKdZVVy6LRr0cBmegxSABiLEpGVmSJJ8O08i4+sGR6qQtb6WtuwJdvVw==",+ "license": "MIT",+ "dependencies": {+ "@types/d3-time": "*"+ }+ },+ "node_modules/@types/d3-shape": {+ "version": "3.1.8",+ "resolved": "https://registry.npmjs.org/@types/d3-shape/-/d3-shape-3.1.8.tgz",+ "integrity": "sha512-lae0iWfcDeR7qt7rA88BNiqdvPS5pFVPpo5OfjElwNaT2yyekbM0C9vK+yqBqEmHr6lDkRnYNoTBYlAgJa7a4w==",+ "license": "MIT",+ "dependencies": {+ "@types/d3-path": "*"+ }+ },+ "node_modules/@types/d3-time": {+ "version": "3.0.4",+ "resolved": "https://registry.npmjs.org/@types/d3-time/-/d3-time-3.0.4.tgz",+ "integrity": "sha512-yuzZug1nkAAaBlBBikKZTgzCeA+k1uy4ZFwWANOfKw5z5LRhV0gNA7gNkKm7HoK+HRN0wX3EkxGk0fpbWhmB7g==",+ "license": "MIT"+ },+ "node_modules/@types/d3-timer": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/@types/d3-timer/-/d3-timer-3.0.2.tgz",+ "integrity": "sha512-Ps3T8E8dZDam6fUyNiMkekK3XUsaUEik+idO9/YjPtfj2qruF8tFBXS7XhtE4iIXBLxhmLjP3SXpLhVf21I9Lw==",+ "license": "MIT"+ },"node_modules/@types/esrecurse": {"version": "4.3.1","resolved": "https://registry.npmjs.org/@types/esrecurse/-/esrecurse-4.3.1.tgz",@@ -967,6 +1080,12 @@"@types/react": "^19.2.0"}},+ "node_modules/@types/use-sync-external-store": {+ "version": "0.0.6",+ "resolved": "https://registry.npmjs.org/@types/use-sync-external-store/-/use-sync-external-store-0.0.6.tgz",+ "integrity": "sha512-zFDAD+tlpf2r4asuHEj0XH6pY6i0g5NeAHPn+15wk3BV6JA69eERFXC1gyGThDkVa1zCyKr5jox1+2LbV/AMLg==",+ "license": "MIT"+ },"node_modules/@typescript-eslint/eslint-plugin": {"version": "8.61.1","resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.61.1.tgz",@@ -1367,6 +1486,15 @@],"license": "CC-BY-4.0"},+ "node_modules/clsx": {+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz",+ "integrity": "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==",+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },"node_modules/convert-source-map": {"version": "2.0.0","resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz",@@ -1409,6 +1537,127 @@"dev": true,"license": "MIT"},+ "node_modules/d3-array": {+ "version": "3.2.4",+ "resolved": "https://registry.npmjs.org/d3-array/-/d3-array-3.2.4.tgz",+ "integrity": "sha512-tdQAmyA18i4J7wprpYq8ClcxZy3SC31QMeByyCFyRt7BVHdREQZ5lpzoe5mFEYZUWe+oq8HBvk9JjpibyEV4Jg==",+ "license": "ISC",+ "dependencies": {+ "internmap": "1 - 2"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-color": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/d3-color/-/d3-color-3.1.0.tgz",+ "integrity": "sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA==",+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-ease": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/d3-ease/-/d3-ease-3.0.1.tgz",+ "integrity": "sha512-wR/XK3D3XcLIZwpbvQwQ5fK+8Ykds1ip7A2Txe0yxncXSdq1L9skcG7blcedkOX+ZcgxGAmLX1FrRGbADwzi0w==",+ "license": "BSD-3-Clause",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-format": {+ "version": "3.1.2",+ "resolved": "https://registry.npmjs.org/d3-format/-/d3-format-3.1.2.tgz",+ "integrity": "sha512-AJDdYOdnyRDV5b6ArilzCPPwc1ejkHcoyFarqlPqT7zRYjhavcT3uSrqcMvsgh2CgoPbK3RCwyHaVyxYcP2Arg==",+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-interpolate": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/d3-interpolate/-/d3-interpolate-3.0.1.tgz",+ "integrity": "sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g==",+ "license": "ISC",+ "dependencies": {+ "d3-color": "1 - 3"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-path": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/d3-path/-/d3-path-3.1.0.tgz",+ "integrity": "sha512-p3KP5HCf/bvjBSSKuXid6Zqijx7wIfNW+J/maPs+iwR35at5JCbLUT0LzF1cnjbCHWhqzQTIN2Jpe8pRebIEFQ==",+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-scale": {+ "version": "4.0.2",+ "resolved": "https://registry.npmjs.org/d3-scale/-/d3-scale-4.0.2.tgz",+ "integrity": "sha512-GZW464g1SH7ag3Y7hXjf8RoUuAFIqklOAq3MRl4OaWabTFJY9PN/E1YklhXLh+OQ3fM9yS2nOkCoS+WLZ6kvxQ==",+ "license": "ISC",+ "dependencies": {+ "d3-array": "2.10.0 - 3",+ "d3-format": "1 - 3",+ "d3-interpolate": "1.2.0 - 3",+ "d3-time": "2.1.1 - 3",+ "d3-time-format": "2 - 4"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-shape": {+ "version": "3.2.0",+ "resolved": "https://registry.npmjs.org/d3-shape/-/d3-shape-3.2.0.tgz",+ "integrity": "sha512-SaLBuwGm3MOViRq2ABk3eLoxwZELpH6zhl3FbAoJ7Vm1gofKx6El1Ib5z23NUEhF9AsGl7y+dzLe5Cw2AArGTA==",+ "license": "ISC",+ "dependencies": {+ "d3-path": "^3.1.0"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-time": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/d3-time/-/d3-time-3.1.0.tgz",+ "integrity": "sha512-VqKjzBLejbSMT4IgbmVgDjpkYrNWUYJnbCGo874u7MMKIWsILRX+OpX/gTk8MqjpT1A/c6HY2dCA77ZN0lkQ2Q==",+ "license": "ISC",+ "dependencies": {+ "d3-array": "2 - 3"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-time-format": {+ "version": "4.1.0",+ "resolved": "https://registry.npmjs.org/d3-time-format/-/d3-time-format-4.1.0.tgz",+ "integrity": "sha512-dJxPBlzC7NugB2PDLwo9Q8JiTR3M3e4/XANkreKSUxF8vvXKqm1Yfq4Q5dl8budlunRVlUUaDUgFt7eA8D6NLg==",+ "license": "ISC",+ "dependencies": {+ "d3-time": "1 - 3"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-timer": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/d3-timer/-/d3-timer-3.0.1.tgz",+ "integrity": "sha512-ndfJ/JxxMd3nw31uyKoY2naivF+r29V+Lc0svZxe1JvvIRmi8hUsrMvdOwgS1o6uBHmiz91geQ0ylPP0aj1VUA==",+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },"node_modules/debug": {"version": "4.4.3","resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",@@ -1426,6 +1675,12 @@}}},+ "node_modules/decimal.js-light": {+ "version": "2.5.1",+ "resolved": "https://registry.npmjs.org/decimal.js-light/-/decimal.js-light-2.5.1.tgz",+ "integrity": "sha512-qIMFpTMZmny+MMIitAB6D7iVPEorVw6YQRWkvarTkT4tBeSLLiHzcwj6q0MmYSFCiVpiqPJTJEYIrpcPzVEIvg==",+ "license": "MIT"+ },"node_modules/deep-is": {"version": "0.1.4","resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz",@@ -1472,6 +1727,16 @@"node": ">=10.0.0"}},+ "node_modules/es-toolkit": {+ "version": "1.48.1",+ "resolved": "https://registry.npmjs.org/es-toolkit/-/es-toolkit-1.48.1.tgz",+ "integrity": "sha512-wfnXlwd5I75eXRtdD2vuEs50xHHESECDsGD7yiQnfFVNoa5522NwXEbmgo98LfiukSQHs+mBM7/YG3qKJB9/mQ==",+ "license": "MIT",+ "workspaces": [+ "docs",+ "benchmarks"+ ]+ },"node_modules/escalade": {"version": "3.2.0","resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",@@ -1680,6 +1945,12 @@"node": ">=0.10.0"}},+ "node_modules/eventemitter3": {+ "version": "5.0.4",+ "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.4.tgz",+ "integrity": "sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==",+ "license": "MIT"+ },"node_modules/fast-deep-equal": {"version": "3.1.3","resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",@@ -1894,6 +2165,16 @@"node": ">= 4"}},+ "node_modules/immer": {+ "version": "10.2.0",+ "resolved": "https://registry.npmjs.org/immer/-/immer-10.2.0.tgz",+ "integrity": "sha512-d/+XTN3zfODyjr89gM3mPq1WNX2B8pYsu7eORitdwyA2sBubnTl3laYlBk4sXY5FUa5qTZGBDPJICVbvqzjlbw==",+ "license": "MIT",+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/immer"+ }+ },"node_modules/imurmurhash": {"version": "0.1.4","resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz",@@ -1904,6 +2185,15 @@"node": ">=0.8.19"}},+ "node_modules/internmap": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/internmap/-/internmap-2.0.3.tgz",+ "integrity": "sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg==",+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },"node_modules/is-extglob": {"version": "2.1.1","resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz",@@ -2553,6 +2843,35 @@}}},+ "node_modules/react-is": {+ "version": "19.2.7",+ "resolved": "https://registry.npmjs.org/react-is/-/react-is-19.2.7.tgz",+ "integrity": "sha512-kZFnouyVv7eP/Phmrlo9FK+zcAdriZJvzxXHF1Sl1P377WSGe2G/JxVolhTrB/jeV47lKImhNUsijjHAAbcl/A==",+ "license": "MIT"+ },+ "node_modules/react-redux": {+ "version": "9.3.0",+ "resolved": "https://registry.npmjs.org/react-redux/-/react-redux-9.3.0.tgz",+ "integrity": "sha512-KQopgqFo/p/fgmAs5qz6p5RWaNAzq40WAu7fJIXnQpYxFPbJYtsJPWvGeF2rOBaY/kEuV77AVsX8TsQzKm+A/g==",+ "license": "MIT",+ "dependencies": {+ "@types/use-sync-external-store": "^0.0.6",+ "use-sync-external-store": "^1.4.0"+ },+ "peerDependencies": {+ "@types/react": "^18.2.25 || ^19",+ "react": "^18.0 || ^19",+ "redux": "^5.0.0"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "redux": {+ "optional": true+ }+ }+ },"node_modules/react-router": {"version": "7.18.0","resolved": "https://registry.npmjs.org/react-router/-/react-router-7.18.0.tgz",@@ -2591,6 +2910,57 @@"react-dom": ">=18"}},+ "node_modules/recharts": {+ "version": "3.9.0",+ "resolved": "https://registry.npmjs.org/recharts/-/recharts-3.9.0.tgz",+ "integrity": "sha512-dCEcE9y20c8H2tkVeByrAXhhnBJk6/QLbxKmn+dJUptOfc5NMjwRh1jo0vZPRLD+5dMrHrP+hPEsfbGBMfnf5Q==",+ "license": "MIT",+ "workspaces": [+ "www"+ ],+ "dependencies": {+ "@reduxjs/toolkit": "^1.9.0 || 2.x.x",+ "clsx": "^2.1.1",+ "decimal.js-light": "^2.5.1",+ "es-toolkit": "^1.39.3",+ "eventemitter3": "^5.0.1",+ "immer": "^10.1.1",+ "react-redux": "8.x.x || 9.x.x",+ "reselect": "5.2.0",+ "tiny-invariant": "^1.3.3",+ "use-sync-external-store": "^1.2.2",+ "victory-vendor": "^37.0.2"+ },+ "engines": {+ "node": ">=18"+ },+ "peerDependencies": {+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",+ "react-dom": "^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",+ "react-is": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"+ }+ },+ "node_modules/redux": {+ "version": "5.0.1",+ "resolved": "https://registry.npmjs.org/redux/-/redux-5.0.1.tgz",+ "integrity": "sha512-M9/ELqF6fy8FwmkpnF0S3YKOqMyoWJ4+CS5Efg2ct3oY9daQvd/Pc71FpGZsVsbl3Cpb+IIcjBDUnnyBdQbq4w==",+ "license": "MIT"+ },+ "node_modules/redux-thunk": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/redux-thunk/-/redux-thunk-3.1.0.tgz",+ "integrity": "sha512-NW2r5T6ksUKXCabzhL9z+h206HQw/NJkcLm1GPImRQ8IzfXwRGqjVhKJGauHirT0DAuyy6hjdnMZaRoAcy0Klw==",+ "license": "MIT",+ "peerDependencies": {+ "redux": "^5.0.0"+ }+ },+ "node_modules/reselect": {+ "version": "5.2.0",+ "resolved": "https://registry.npmjs.org/reselect/-/reselect-5.2.0.tgz",+ "integrity": "sha512-AgZ3UOZm3YndfrJ4OYjgrT7bmCm/1iqkjvEfH/oYjzh6PD2qw4QuT3jjnXIrpdt4MTpMXclMT3lXbmRY+XRakw==",+ "license": "MIT"+ },"node_modules/rolldown": {"version": "1.0.3","resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.0.3.tgz",@@ -2708,6 +3078,12 @@"node": ">=0.10.0"}},+ "node_modules/tiny-invariant": {+ "version": "1.3.3",+ "resolved": "https://registry.npmjs.org/tiny-invariant/-/tiny-invariant-1.3.3.tgz",+ "integrity": "sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg==",+ "license": "MIT"+ },"node_modules/tinyglobby": {"version": "0.2.17","resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",@@ -2854,6 +3230,28 @@"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"}},+ "node_modules/victory-vendor": {+ "version": "37.3.6",+ "resolved": "https://registry.npmjs.org/victory-vendor/-/victory-vendor-37.3.6.tgz",+ "integrity": "sha512-SbPDPdDBYp+5MJHhBCAyI7wKM3d5ivekigc2Dk2s7pgbZ9wIgIBYGVw4zGHBml/qTFbexrofXW6Gu4noGxrOwQ==",+ "license": "MIT AND ISC",+ "dependencies": {+ "@types/d3-array": "^3.0.3",+ "@types/d3-ease": "^3.0.0",+ "@types/d3-interpolate": "^3.0.1",+ "@types/d3-scale": "^4.0.2",+ "@types/d3-shape": "^3.1.0",+ "@types/d3-time": "^3.0.0",+ "@types/d3-timer": "^3.0.0",+ "d3-array": "^3.1.6",+ "d3-ease": "^3.0.1",+ "d3-interpolate": "^3.0.1",+ "d3-scale": "^4.0.2",+ "d3-shape": "^3.1.0",+ "d3-time": "^3.0.0",+ "d3-timer": "^3.0.1"+ }+ },"node_modules/vite": {"version": "8.0.16","resolved": "https://registry.npmjs.org/vite/-/vite-8.0.16.tgz",diff --git a/dashboard/package.json b/dashboard/package.jsonindex 56f3e04c4..480c05d41 100644--- a/dashboard/package.json+++ b/dashboard/package.json@@ -20,7 +20,9 @@"react": "^19.2.7","react-dom": "^19.2.7","react-i18next": "^17.0.8",+ "react-is": "^19.2.7","react-router-dom": "^7.18.0",+ "recharts": "^3.9.0","socket.io-client": "^4.8.3"},"devDependencies": {diff --git a/dashboard/src/components/DashboardCharts.css b/dashboard/src/components/DashboardCharts.cssnew file mode 100644index 000000000..b178a033a--- /dev/null+++ b/dashboard/src/components/DashboardCharts.css@@ -0,0 +1,103 @@+/* Dashboard analytics — all rules scoped under .dashboard-charts to avoid global collisions. */+.dashboard-charts {+ margin-bottom: 2rem;+}++.dashboard-charts .charts-header {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 1rem;+ flex-wrap: wrap;+ margin-bottom: 1rem;+}++.dashboard-charts .charts-title {+ display: flex;+ align-items: center;+ gap: 0.5rem;+ color: var(--text-primary);+}++.dashboard-charts .charts-title h2 {+ font-size: 1.125rem;+ font-weight: 700;+ margin: 0;+}++/* Segmented pill period selector (matches the plugin/install tab control). */+.dashboard-charts .period-toggle {+ display: inline-flex;+ gap: 2px;+ padding: 3px;+ background: var(--bg-light);+ border: 1px solid var(--border);+ border-radius: 10px;+}++.dashboard-charts .period-tab {+ padding: 0.35rem 0.85rem;+ background: none;+ border: none;+ border-radius: 7px;+ color: var(--text-secondary);+ font-size: 0.8125rem;+ font-weight: 600;+ cursor: pointer;+ transition: background 0.15s ease, color 0.15s ease;+}++.dashboard-charts .period-tab.active {+ background: var(--bg-white);+ color: var(--text-primary);+ box-shadow: 0 1px 2px rgba(0, 0, 0, 0.06);+}++.dashboard-charts .charts-grid {+ display: grid;+ grid-template-columns: 1fr 1fr;+ gap: 1rem;+}++.dashboard-charts .chart-card {+ background: var(--bg-white);+ border: 1px solid var(--border);+ border-radius: 12px;+ padding: 1.25rem;+ min-width: 0; /* let recharts ResponsiveContainer shrink inside the grid track */+}++.dashboard-charts .chart-wide {+ grid-column: 1 / -1;+}++.dashboard-charts .chart-card h3 {+ font-size: 0.9375rem;+ font-weight: 600;+ color: var(--text-primary);+ margin: 0 0 1rem;+}++.dashboard-charts .charts-empty {+ background: var(--bg-white);+ border: 1px dashed var(--border);+ border-radius: 12px;+ padding: 2.5rem 1rem;+ text-align: center;+ color: var(--text-muted);+ font-size: 0.875rem;+}++.dashboard-charts .charts-empty.small {+ border: none;+ padding: 2rem 1rem;+}++@media (max-width: 768px) {+ .dashboard-charts .charts-grid {+ grid-template-columns: 1fr;+ }+ .dashboard-charts .chart-wide {+ grid-column: auto;+ }+}diff --git a/dashboard/src/components/DashboardCharts.tsx b/dashboard/src/components/DashboardCharts.tsxnew file mode 100644index 000000000..fbd7c9deb--- /dev/null+++ b/dashboard/src/components/DashboardCharts.tsx@@ -0,0 +1,164 @@+import { useState } from 'react';+import { useTranslation } from 'react-i18next';+import {+ ResponsiveContainer,+ AreaChart,+ Area,+ XAxis,+ YAxis,+ CartesianGrid,+ Tooltip,+ Legend,+ PieChart,+ Pie,+ Cell,+ BarChart,+ Bar,+} from 'recharts';+import { BarChart3 } from 'lucide-react';+import { useStatsMessagesQuery } from '../hooks/queries';+import type { StatsPeriod } from '../services/api';+import './DashboardCharts.css';++const PERIODS: StatsPeriod[] = ['24h', '7d', '30d'];++// Distinct, theme-agnostic palette for the donut slices (recharts needs literal colors).+const TYPE_COLORS = ['#25d366', '#3b82f6', '#a855f7', '#f59e0b', '#ef4444', '#06b6d4', '#ec4899', '#64748b'];++// '2026-06-24 14:00:00' (hour buckets) → '14:00'; '2026-06-24' (day buckets) → '06-24'.+function formatTick(ts: string, period: StatsPeriod): string {+ return period === '24h' ? ts.slice(11, 16) : ts.slice(5);+}++// WhatsApp ids look like '[email protected]' / '[email protected]' / '...@lid' — show just the local part.+function shortChat(chatId: string): string {+ return chatId.split('@')[0] || chatId;+}++export function DashboardCharts() {+ const { t } = useTranslation();+ const [period, setPeriod] = useState<StatsPeriod>('7d');+ const { data, isLoading, isError } = useStatsMessagesQuery(period);++ // Non-admin keys 403 on /stats/messages; hide the section rather than show a broken card.+ if (isError) return null;++ const timeSeries = (data?.timeSeries ?? []).map(p => ({ ...p, label: formatTick(p.timestamp, period) }));+ const byType = Object.entries(data?.byType ?? {})+ .map(([name, value]) => ({ name, value }))+ .sort((a, b) => b.value - a.value);+ const topChats = (data?.topChats ?? []).slice(0, 8).map(c => ({ name: shortChat(c.chatId), count: c.messageCount }));+ const hasData = timeSeries.length > 0 || byType.length > 0 || topChats.length > 0;++ return (+ <section className="dashboard-charts">+ <div className="charts-header">+ <div className="charts-title">+ <BarChart3 size={18} />+ <h2>{t('dashboard.charts.title')}</h2>+ </div>+ <div className="period-toggle" role="group" aria-label={t('dashboard.charts.title')}>+ {PERIODS.map(p => (+ <button+ key={p}+ type="button"+ aria-pressed={period === p}+ className={`period-tab ${period === p ? 'active' : ''}`}+ onClick={() => setPeriod(p)}+ >+ {t(`dashboard.charts.period.${p}`)}+ </button>+ ))}+ </div>+ </div>++ {isLoading ? (+ <div className="charts-empty">{t('common.loading')}</div>+ ) : !hasData ? (+ <div className="charts-empty">{t('dashboard.charts.empty')}</div>+ ) : (+ <div className="charts-grid">+ <div className="chart-card chart-wide">+ <h3>{t('dashboard.charts.overTime')}</h3>+ <ResponsiveContainer width="100%" height={260}>+ <AreaChart data={timeSeries} margin={{ top: 8, right: 12, left: -12, bottom: 0 }}>+ <defs>+ <linearGradient id="gSent" x1="0" y1="0" x2="0" y2="1">+ <stop offset="5%" stopColor="#25d366" stopOpacity={0.4} />+ <stop offset="95%" stopColor="#25d366" stopOpacity={0} />+ </linearGradient>+ <linearGradient id="gReceived" x1="0" y1="0" x2="0" y2="1">+ <stop offset="5%" stopColor="#3b82f6" stopOpacity={0.4} />+ <stop offset="95%" stopColor="#3b82f6" stopOpacity={0} />+ </linearGradient>+ </defs>+ <CartesianGrid strokeDasharray="3 3" stroke="var(--border)" />+ <XAxis dataKey="label" tick={{ fontSize: 12, fill: 'var(--text-secondary)' }} />+ <YAxis allowDecimals={false} tick={{ fontSize: 12, fill: 'var(--text-secondary)' }} />+ <Tooltip />+ <Legend />+ <Area+ type="monotone"+ dataKey="sent"+ name={t('dashboard.charts.sent')}+ stroke="#25d366"+ fill="url(#gSent)"+ strokeWidth={2}+ />+ <Area+ type="monotone"+ dataKey="received"+ name={t('dashboard.charts.received')}+ stroke="#3b82f6"+ fill="url(#gReceived)"+ strokeWidth={2}+ />+ </AreaChart>+ </ResponsiveContainer>+ </div>++ <div className="chart-card">+ <h3>{t('dashboard.charts.byType')}</h3>+ {byType.length === 0 ? (+ <div className="charts-empty small">{t('dashboard.charts.empty')}</div>+ ) : (+ <ResponsiveContainer width="100%" height={260}>+ <PieChart>+ <Pie data={byType} dataKey="value" nameKey="name" innerRadius={55} outerRadius={90} paddingAngle={2}>+ {byType.map((entry, i) => (+ <Cell key={entry.name} fill={TYPE_COLORS[i % TYPE_COLORS.length]} />+ ))}+ </Pie>+ <Tooltip />+ <Legend />+ </PieChart>+ </ResponsiveContainer>+ )}+ </div>++ <div className="chart-card">+ <h3>{t('dashboard.charts.topChats')}</h3>+ {topChats.length === 0 ? (+ <div className="charts-empty small">{t('dashboard.charts.empty')}</div>+ ) : (+ <ResponsiveContainer width="100%" height={260}>+ <BarChart data={topChats} layout="vertical" margin={{ top: 4, right: 16, left: 8, bottom: 4 }}>+ <CartesianGrid strokeDasharray="3 3" stroke="var(--border)" horizontal={false} />+ <XAxis type="number" allowDecimals={false} tick={{ fontSize: 12, fill: 'var(--text-secondary)' }} />+ <YAxis+ type="category"+ dataKey="name"+ width={120}+ tick={{ fontSize: 12, fill: 'var(--text-secondary)' }}+ />+ <Tooltip />+ <Bar dataKey="count" name={t('dashboard.charts.messages')} fill="#25d366" radius={[0, 4, 4, 0]} />+ </BarChart>+ </ResponsiveContainer>+ )}+ </div>+ </div>+ )}+ </section>+ );+}diff --git a/dashboard/src/components/Layout.tsx b/dashboard/src/components/Layout.tsxindex 191e5a9a4..221758431 100644--- a/dashboard/src/components/Layout.tsx+++ b/dashboard/src/components/Layout.tsx@@ -25,6 +25,7 @@ import {import { useTheme } from '../hooks/useTheme';import { type UserRole } from '../hooks/useRole';import { languageOptions, resolveSupportedLanguage, rtlLanguages, type SupportedLanguage } from '../i18n';+import { healthApi } from '../services/api';import './Layout.css';interface LayoutProps {@@ -60,6 +61,9 @@ export function Layout({ onLogout, userRole }: LayoutProps) {const [isCollapsed, setIsCollapsed] = useState(false);const [isMobileOpen, setIsMobileOpen] = useState(false);const [isMobile, setIsMobile] = useState(window.innerWidth < 768);+ // Show the build-time version immediately, then replace it with the live running version from the+ // backend so a stale-built bundle can't display the wrong number. Falls back silently on error.+ const [version, setVersion] = useState(__APP_VERSION__);const [isLanguageMenuOpen, setIsLanguageMenuOpen] = useState(false);const [isAppearanceMenuOpen, setIsAppearanceMenuOpen] = useState(false);const languageMenuRef = useRef<HTMLDivElement>(null);@@ -75,6 +79,21 @@ export function Layout({ onLogout, userRole }: LayoutProps) {return () => window.removeEventListener('resize', handleResize);}, []);+ useEffect(() => {+ let active = true;+ healthApi+ .check()+ .then(info => {+ if (active && info?.version) setVersion(info.version);+ })+ .catch(() => {+ /* keep the build-time fallback */+ });+ return () => {+ active = false;+ };+ }, []);+const handleNavClick = () => {if (isMobile) setIsMobileOpen(false);};@@ -162,7 +181,7 @@ export function Layout({ onLogout, userRole }: LayoutProps) {{!isCollapsed && (<div className="sidebar-brand"><span className="brand-name">{t('common.appName')}</span>- <span className="brand-version">v{__APP_VERSION__}</span>+ <span className="brand-version">v{version}</span></div>)}</div>diff --git a/dashboard/src/hooks/queries.ts b/dashboard/src/hooks/queries.tsindex e7714ced8..f0b538fc8 100644--- a/dashboard/src/hooks/queries.ts+++ b/dashboard/src/hooks/queries.ts@@ -7,9 +7,11 @@ import {auditApi,infraApi,pluginsApi,+ statsApi,type Webhook,type WebhookFilters,type TemplatePayload,+ type StatsPeriod,} from '../services/api';// ── Query Keys ────────────────────────────────────────────────────────@@ -28,6 +30,8 @@ export const queryKeys = {plugins: ['plugins'] as const,engines: ['engines'] as const,currentEngine: ['engines', 'current'] as const,+ statsOverview: ['stats', 'overview'] as const,+ statsMessages: (period: string) => ['stats', 'messages', period] as const,};// ── Session Queries ───────────────────────────────────────────────────@@ -266,3 +270,24 @@ export function useCurrentEngineQuery() {staleTime: 60_000,});}++// ── Stats Queries ─────────────────────────────────────────────────────+// /stats/* is ADMIN-only; a non-admin key gets 403 → don't retry, let the UI fall back gracefully.++export function useStatsOverviewQuery() {+ return useQuery({+ queryKey: queryKeys.statsOverview,+ queryFn: statsApi.getOverview,+ staleTime: 30_000,+ retry: false,+ });+}++export function useStatsMessagesQuery(period: StatsPeriod) {+ return useQuery({+ queryKey: queryKeys.statsMessages(period),+ queryFn: () => statsApi.getMessages(period),+ staleTime: 30_000,+ retry: false,+ });+}diff --git a/dashboard/src/i18n/locales/ar.json b/dashboard/src/i18n/locales/ar.jsonindex 0157f0ef6..5b8ef478c 100644--- a/dashboard/src/i18n/locales/ar.json+++ b/dashboard/src/i18n/locales/ar.json@@ -143,7 +143,8 @@"activeSessions": "الجلسات النشطة","messagesToday": "رسائل اليوم","webhooksConfigured": "الويب هوك المُهيّأة",- "apiCalls": "استدعاءات API (24 ساعة)"+ "apiCalls": "استدعاءات API (24 ساعة)",+ "totalMessages": "إجمالي الرسائل"},"sessionsOverview": "نظرة عامة على الجلسات","showingSessions": "عرض {{shown}} من {{total}} جلسة",@@ -158,7 +159,22 @@"view": "عرض","disconnect": "قطع الاتصال","errorPrefix": "خطأ: {{message}}",- "loadError": "فشل تحميل البيانات"+ "loadError": "فشل تحميل البيانات",+ "charts": {+ "title": "تحليلات الرسائل",+ "period": {+ "24h": "24 ساعة",+ "7d": "7 أيام",+ "30d": "30 يومًا"+ },+ "overTime": "الرسائل عبر الزمن",+ "byType": "الرسائل حسب النوع",+ "topChats": "أبرز المحادثات",+ "sent": "المُرسَلة",+ "received": "المُستلَمة",+ "messages": "الرسائل",+ "empty": "لا يوجد نشاط رسائل في هذه الفترة."+ }},"sessionStatus": {"created": "جديد",@@ -552,6 +568,17 @@"migrationsStatus": "يتم مزامنة المخطط تلقائياً مع TypeORM","migrationsHint": "تُدار عمليات الترحيل تلقائياً. استخدم CLI للترحيل اليدوي."},+ "engine": {+ "title": "محرك واتساب",+ "subtitle": "اختر محرك اتصال واتساب وقم بتهيئته.",+ "builtIn": "مدمج",+ "headless": "الوضع بدون واجهة",+ "headlessDesc": "تشغيل المتصفح بدون واجهة مرئية (موصى به للإنتاج).",+ "sessionDataPath": "مسار بيانات الجلسة",+ "browserArgs": "وسائط المتصفح",+ "noBrowser": "يتصل هذا المحرك عبر WebSocket — لا يحتوي على متصفح، لذلك لا توجد إعدادات للوضع بدون واجهة أو وسائط المتصفح. يُطبَّق المحرك النشط بعد إعادة التشغيل.",+ "restartNote": "يسري تغيير المحرك بعد إعادة تشغيل الخادم."+ },"redis": {"title": "Redis","enable": "تفعيل Redis",@@ -615,7 +642,7 @@},"plugins": {"title": "الإضافات",- "subtitle": "إدارة المحركات وواجهات التخزين والامتدادات",+ "subtitle": "ثبّت الإضافات وكوّنها وأدِرها","refresh": "تحديث","engineCard": "محرك واتساب النشط","running": "يعمل",diff --git a/dashboard/src/i18n/locales/en.json b/dashboard/src/i18n/locales/en.jsonindex a88b5ca1b..d42e3479c 100644--- a/dashboard/src/i18n/locales/en.json+++ b/dashboard/src/i18n/locales/en.json@@ -143,7 +143,8 @@"activeSessions": "Active Sessions","messagesToday": "Messages Today","webhooksConfigured": "Webhooks Configured",- "apiCalls": "API Calls (24h)"+ "apiCalls": "API Calls (24h)",+ "totalMessages": "Total Messages"},"sessionsOverview": "Sessions Overview","showingSessions": "Showing {{shown}} of {{total}} sessions",@@ -158,7 +159,22 @@"view": "View","disconnect": "Disconnect","errorPrefix": "Error: {{message}}",- "loadError": "Failed to load data"+ "loadError": "Failed to load data",+ "charts": {+ "title": "Message Analytics",+ "period": {+ "24h": "24h",+ "7d": "7d",+ "30d": "30d"+ },+ "overTime": "Messages over time",+ "byType": "Messages by type",+ "topChats": "Top chats",+ "sent": "Sent",+ "received": "Received",+ "messages": "Messages",+ "empty": "No message activity in this period."+ }},"sessionStatus": {"created": "New",@@ -552,6 +568,17 @@"migrationsStatus": "Schema is auto-synchronized with TypeORM","migrationsHint": "Migrations are managed automatically. Use CLI for manual migrations."},+ "engine": {+ "title": "WhatsApp Engine",+ "subtitle": "Choose and configure the WhatsApp connection engine.",+ "builtIn": "Built-in",+ "headless": "Headless Mode",+ "headlessDesc": "Run the browser without a visible UI (recommended for production).",+ "sessionDataPath": "Session Data Path",+ "browserArgs": "Browser Arguments",+ "noBrowser": "This engine connects over WebSocket — it has no browser, so there are no headless or browser-argument settings. The active engine is applied after a restart.",+ "restartNote": "Switching the engine takes effect after a server restart."+ },"redis": {"title": "Redis","enable": "Enable Redis",@@ -615,7 +642,7 @@},"plugins": {"title": "Plugins",- "subtitle": "Manage engines, storage backends, and extensions",+ "subtitle": "Install, configure, and manage extensions","refresh": "Refresh","engineCard": "Active WhatsApp Engine","running": "Running",diff --git a/dashboard/src/i18n/locales/es.json b/dashboard/src/i18n/locales/es.jsonindex 8411fdc8c..81e8d3fc3 100644--- a/dashboard/src/i18n/locales/es.json+++ b/dashboard/src/i18n/locales/es.json@@ -143,7 +143,8 @@"activeSessions": "Sesiones activas","messagesToday": "Mensajes hoy","webhooksConfigured": "Webhooks configurados",- "apiCalls": "Llamadas API (24h)"+ "apiCalls": "Llamadas API (24h)",+ "totalMessages": "Mensajes totales"},"sessionsOverview": "Resumen de sesiones","showingSessions": "Mostrando {{shown}} de {{total}} sesiones",@@ -158,7 +159,22 @@"view": "Ver","disconnect": "Desconectar","errorPrefix": "Error: {{message}}",- "loadError": "Error al cargar los datos"+ "loadError": "Error al cargar los datos",+ "charts": {+ "title": "Analíticas de mensajes",+ "period": {+ "24h": "24 h",+ "7d": "7 d",+ "30d": "30 d"+ },+ "overTime": "Mensajes a lo largo del tiempo",+ "byType": "Mensajes por tipo",+ "topChats": "Chats principales",+ "sent": "Enviados",+ "received": "Recibidos",+ "messages": "Mensajes",+ "empty": "Sin actividad de mensajes en este período."+ }},"sessionStatus": {"created": "Nueva",@@ -552,6 +568,17 @@"migrationsStatus": "El esquema se sincroniza automáticamente con TypeORM","migrationsHint": "Las migraciones se gestionan automáticamente. Usa la CLI para migraciones manuales."},+ "engine": {+ "title": "Motor de WhatsApp",+ "subtitle": "Elige y configura el motor de conexión de WhatsApp.",+ "builtIn": "Integrado",+ "headless": "Modo headless",+ "headlessDesc": "Ejecuta el navegador sin interfaz visible (recomendado para producción).",+ "sessionDataPath": "Ruta de datos de sesión",+ "browserArgs": "Argumentos del navegador",+ "noBrowser": "Este motor se conecta por WebSocket: no tiene navegador, por lo que no hay ajustes de modo headless ni de argumentos del navegador. El motor activo se aplica tras reiniciar.",+ "restartNote": "Cambiar el motor surte efecto tras reiniciar el servidor."+ },"redis": {"title": "Redis","enable": "Habilitar Redis",@@ -615,7 +642,7 @@},"plugins": {"title": "Plugins",- "subtitle": "Gestiona motores, backends de almacenamiento y extensiones",+ "subtitle": "Instala, configura y gestiona extensiones","refresh": "Actualizar","engineCard": "Motor de WhatsApp activo","running": "En ejecución",diff --git a/dashboard/src/i18n/locales/fr.json b/dashboard/src/i18n/locales/fr.jsonindex c5c064946..a3b493196 100644--- a/dashboard/src/i18n/locales/fr.json+++ b/dashboard/src/i18n/locales/fr.json@@ -143,7 +143,8 @@"activeSessions": "Sessions actives","messagesToday": "Messages aujourd'hui","webhooksConfigured": "Webhooks configurés",- "apiCalls": "Appels API (24h)"+ "apiCalls": "Appels API (24h)",+ "totalMessages": "Messages totaux"},"sessionsOverview": "Aperçu des sessions","showingSessions": "Affichage de {{shown}} sur {{total}} sessions",@@ -158,7 +159,22 @@"view": "Voir","disconnect": "Déconnecter","errorPrefix": "Erreur : {{message}}",- "loadError": "Échec du chargement des données"+ "loadError": "Échec du chargement des données",+ "charts": {+ "title": "Analyses des messages",+ "period": {+ "24h": "24 h",+ "7d": "7 j",+ "30d": "30 j"+ },+ "overTime": "Messages au fil du temps",+ "byType": "Messages par type",+ "topChats": "Discussions principales",+ "sent": "Envoyés",+ "received": "Reçus",+ "messages": "Messages",+ "empty": "Aucune activité de message sur cette période."+ }},"sessionStatus": {"created": "Nouveau",@@ -552,6 +568,17 @@"migrationsStatus": "Le schéma est auto-synchronisé avec TypeORM","migrationsHint": "Les migrations sont gérées automatiquement. Utilisez la CLI pour les migrations manuelles."},+ "engine": {+ "title": "Moteur WhatsApp",+ "subtitle": "Choisissez et configurez le moteur de connexion WhatsApp.",+ "builtIn": "Intégré",+ "headless": "Mode headless",+ "headlessDesc": "Exécuter le navigateur sans interface visible (recommandé en production).",+ "sessionDataPath": "Chemin des données de session",+ "browserArgs": "Arguments du navigateur",+ "noBrowser": "Ce moteur se connecte via WebSocket : il n'a pas de navigateur, il n'y a donc pas de réglages de mode headless ni d'arguments de navigateur. Le moteur actif est appliqué après un redémarrage.",+ "restartNote": "Le changement de moteur prend effet après le redémarrage du serveur."+ },"redis": {"title": "Redis","enable": "Activer Redis",@@ -615,7 +642,7 @@},"plugins": {"title": "Plugins",- "subtitle": "Gérez les moteurs, les backends de stockage et les extensions",+ "subtitle": "Installez, configurez et gérez les extensions","refresh": "Actualiser","engineCard": "Moteur WhatsApp actif","running": "En cours d'exécution",diff --git a/dashboard/src/i18n/locales/he.json b/dashboard/src/i18n/locales/he.jsonindex 4dcd14ba4..06f343f7b 100644--- a/dashboard/src/i18n/locales/he.json+++ b/dashboard/src/i18n/locales/he.json@@ -143,7 +143,8 @@"activeSessions": "Sessions פעילים","messagesToday": "הודעות היום","webhooksConfigured": "Webhooks מוגדרים",- "apiCalls": "קריאות API (24 שעות)"+ "apiCalls": "קריאות API (24 שעות)",+ "totalMessages": "סה\"כ הודעות"},"sessionsOverview": "סקירת Sessions","showingSessions": "מוצגים {{shown}} מתוך {{total}} Sessions",@@ -158,7 +159,22 @@"view": "צפייה","disconnect": "ניתוק","errorPrefix": "שגיאה: {{message}}",- "loadError": "טעינת הנתונים נכשלה"+ "loadError": "טעינת הנתונים נכשלה",+ "charts": {+ "title": "ניתוח הודעות",+ "period": {+ "24h": "24 ש'",+ "7d": "7 ימים",+ "30d": "30 יום"+ },+ "overTime": "הודעות לאורך זמן",+ "byType": "הודעות לפי סוג",+ "topChats": "צ'אטים מובילים",+ "sent": "נשלחו",+ "received": "התקבלו",+ "messages": "הודעות",+ "empty": "אין פעילות הודעות בתקופה זו."+ }},"sessionStatus": {"created": "חדש",@@ -552,6 +568,17 @@"migrationsStatus": "הסכמה מסונכרנת אוטומטית עם TypeORM","migrationsHint": "ה-Migrations מנוהלים אוטומטית. ניתן להשתמש ב-CLI ל-Migrations ידניים."},+ "engine": {+ "title": "מנוע WhatsApp",+ "subtitle": "בחר והגדר את מנוע החיבור של WhatsApp.",+ "builtIn": "מובנה",+ "headless": "מצב ללא ממשק",+ "headlessDesc": "הרצת הדפדפן ללא ממשק גלוי (מומלץ לסביבת ייצור).",+ "sessionDataPath": "נתיב נתוני הפעלה",+ "browserArgs": "ארגומנטים של הדפדפן",+ "noBrowser": "מנוע זה מתחבר באמצעות WebSocket — אין לו דפדפן, ולכן אין הגדרות למצב ללא ממשק או לארגומנטים של הדפדפן. המנוע הפעיל מוחל לאחר הפעלה מחדש.",+ "restartNote": "החלפת המנוע נכנסת לתוקף לאחר הפעלה מחדש של השרת."+ },"redis": {"title": "Redis","enable": "הפעלת Redis",@@ -615,7 +642,7 @@},"plugins": {"title": "תוספים",- "subtitle": "ניהול מנועים, יעדי אחסון והרחבות",+ "subtitle": "התקנה, הגדרה וניהול של הרחבות","refresh": "רענון","engineCard": "מנוע WhatsApp פעיל","running": "פועל",diff --git a/dashboard/src/i18n/locales/it.json b/dashboard/src/i18n/locales/it.jsonindex 73478cb16..a0c3b78ae 100644--- a/dashboard/src/i18n/locales/it.json+++ b/dashboard/src/i18n/locales/it.json@@ -143,7 +143,8 @@"activeSessions": "Sessioni Attive","messagesToday": "Messaggi di Oggi","webhooksConfigured": "Webhook Configurati",- "apiCalls": "Chiamate API (24h)"+ "apiCalls": "Chiamate API (24h)",+ "totalMessages": "Messaggi totali"},"sessionsOverview": "Panoramica Sessioni","showingSessions": "Visualizzazione di {{shown}} di {{total}} sessioni",@@ -158,7 +159,22 @@"view": "Visualizza","disconnect": "Disconnetti","errorPrefix": "Errore: {{message}}",- "loadError": "Impossibile caricare i dati"+ "loadError": "Impossibile caricare i dati",+ "charts": {+ "title": "Analisi messaggi",+ "period": {+ "24h": "24 h",+ "7d": "7 g",+ "30d": "30 g"+ },+ "overTime": "Messaggi nel tempo",+ "byType": "Messaggi per tipo",+ "topChats": "Chat principali",+ "sent": "Inviati",+ "received": "Ricevuti",+ "messages": "Messaggi",+ "empty": "Nessuna attività di messaggi in questo periodo."+ }},"sessionStatus": {"created": "Nuova",@@ -552,6 +568,17 @@"migrationsStatus": "Lo schema è sincronizzato automaticamente con TypeORM","migrationsHint": "Le migrazioni sono gestite automaticamente. Usa la CLI per le migrazioni manuali."},+ "engine": {+ "title": "Motore WhatsApp",+ "subtitle": "Scegli e configura il motore di connessione di WhatsApp.",+ "builtIn": "Integrato",+ "headless": "Modalità headless",+ "headlessDesc": "Esegui il browser senza interfaccia visibile (consigliato per la produzione).",+ "sessionDataPath": "Percorso dati sessione",+ "browserArgs": "Argomenti del browser",+ "noBrowser": "Questo motore si connette tramite WebSocket: non ha un browser, quindi non ci sono impostazioni per la modalità headless o gli argomenti del browser. Il motore attivo viene applicato dopo un riavvio.",+ "restartNote": "Il cambio di motore ha effetto dopo il riavvio del server."+ },"redis": {"title": "Redis","enable": "Abilita Redis",@@ -615,7 +642,7 @@},"plugins": {"title": "Plugin",- "subtitle": "Gestisci i motori, i backend di storage e le estensioni",+ "subtitle": "Installa, configura e gestisci le estensioni","refresh": "Aggiorna","engineCard": "Motore WhatsApp Attivo","running": "In esecuzione",diff --git a/dashboard/src/i18n/locales/te.json b/dashboard/src/i18n/locales/te.jsonindex a12dfa69d..09d5ed4dd 100644--- a/dashboard/src/i18n/locales/te.json+++ b/dashboard/src/i18n/locales/te.json@@ -143,7 +143,8 @@"activeSessions": "యాక్టివ్ సెషన్స్","messagesToday": "ఈరోజు సందేశాలు","webhooksConfigured": "కాన్ఫిగర్ చేసిన వెబ్హుక్స్",- "apiCalls": "API కాల్స్ (24 గంటలు)"+ "apiCalls": "API కాల్స్ (24 గంటలు)",+ "totalMessages": "మొత్తం సందేశాలు"},"sessionsOverview": "సెషన్ల అవలోకనం","showingSessions": "{{total}} సెషన్లలో {{shown}} చూపిస్తోంది",@@ -158,7 +159,22 @@"view": "చూడు","disconnect": "డిస్కనెక్ట్ చేయి","errorPrefix": "లోపం: {{message}}",- "loadError": "డేటాను లోడ్ చేయడం విఫలమైంది"+ "loadError": "డేటాను లోడ్ చేయడం విఫలమైంది",+ "charts": {+ "title": "సందేశ విశ్లేషణలు",+ "period": {+ "24h": "24 గం",+ "7d": "7 రో",+ "30d": "30 రో"+ },+ "overTime": "కాలక్రమంలో సందేశాలు",+ "byType": "రకం వారీగా సందేశాలు",+ "topChats": "టాప్ చాట్లు",+ "sent": "పంపినవి",+ "received": "స్వీకరించినవి",+ "messages": "సందేశాలు",+ "empty": "ఈ వ్యవధిలో సందేశ కార్యకలాపం లేదు."+ }},"sessionStatus": {"created": "కొత్తది",@@ -552,6 +568,17 @@"migrationsStatus": "స్కీమా TypeORM తో స్వయంచాలకంగా సమకాలీకరించబడింది","migrationsHint": "మైగ్రేషన్స్ స్వయంచాలకంగా నిర్వహించబడతాయి. మాన్యువల్ మైగ్రేషన్స్ కోసం CLIని ఉపయోగించండి."},+ "engine": {+ "title": "WhatsApp ఇంజిన్",+ "subtitle": "WhatsApp కనెక్షన్ ఇంజిన్ను ఎంచుకొని కాన్ఫిగర్ చేయండి.",+ "builtIn": "అంతర్నిర్మితం",+ "headless": "హెడ్లెస్ మోడ్",+ "headlessDesc": "కనిపించే UI లేకుండా బ్రౌజర్ను అమలు చేయండి (ఉత్పత్తికి సిఫార్సు చేయబడింది).",+ "sessionDataPath": "సెషన్ డేటా పాత్",+ "browserArgs": "బ్రౌజర్ ఆర్గ్యుమెంట్లు",+ "noBrowser": "ఈ ఇంజిన్ WebSocket ద్వారా కనెక్ట్ అవుతుంది — దీనికి బ్రౌజర్ లేదు, కాబట్టి హెడ్లెస్ లేదా బ్రౌజర్-ఆర్గ్యుమెంట్ సెట్టింగ్లు లేవు. యాక్టివ్ ఇంజిన్ రీస్టార్ట్ తర్వాత వర్తిస్తుంది.",+ "restartNote": "ఇంజిన్ను మార్చడం సర్వర్ రీస్టార్ట్ తర్వాత అమలులోకి వస్తుంది."+ },"redis": {"title": "Redis","enable": "Redis ప్రారంభించండి",@@ -615,7 +642,7 @@},"plugins": {"title": "ప్లగిన్స్",- "subtitle": "ఇంజిన్లు, స్టోరేజ్ బ్యాకెండ్లు మరియు ఎక్స్టెన్షన్లను నిర్వహించండి",+ "subtitle": "ఎక్స్టెన్షన్లను ఇన్స్టాల్, కాన్ఫిగర్ మరియు నిర్వహించండి","refresh": "రిఫ్రెష్","engineCard": "యాక్టివ్ వాట్సాప్ ఇంజిన్","running": "నడుస్తోంది",diff --git a/dashboard/src/i18n/locales/zh-CN.json b/dashboard/src/i18n/locales/zh-CN.jsonindex 97bd9f2f2..d61729463 100644--- a/dashboard/src/i18n/locales/zh-CN.json+++ b/dashboard/src/i18n/locales/zh-CN.json@@ -143,7 +143,8 @@"activeSessions": "活跃会话","messagesToday": "今日消息","webhooksConfigured": "已配置 Webhook",- "apiCalls": "API 调用(24 小时)"+ "apiCalls": "API 调用(24 小时)",+ "totalMessages": "消息总数"},"sessionsOverview": "会话概览","showingSessions": "显示 {{shown}} / {{total}} 个会话",@@ -158,7 +159,22 @@"view": "查看","disconnect": "断开连接","errorPrefix": "错误:{{message}}",- "loadError": "加载数据失败"+ "loadError": "加载数据失败",+ "charts": {+ "title": "消息分析",+ "period": {+ "24h": "24小时",+ "7d": "7天",+ "30d": "30天"+ },+ "overTime": "消息趋势",+ "byType": "按类型分类的消息",+ "topChats": "热门聊天",+ "sent": "已发送",+ "received": "已接收",+ "messages": "消息",+ "empty": "此期间没有消息活动。"+ }},"sessionStatus": {"created": "新建",@@ -552,6 +568,17 @@"migrationsStatus": "架构会通过 TypeORM 自动同步","migrationsHint": "迁移会自动管理。手动迁移请使用 CLI。"},+ "engine": {+ "title": "WhatsApp 引擎",+ "subtitle": "选择并配置 WhatsApp 连接引擎。",+ "builtIn": "内置",+ "headless": "无头模式",+ "headlessDesc": "在没有可见界面的情况下运行浏览器(推荐用于生产环境)。",+ "sessionDataPath": "会话数据路径",+ "browserArgs": "浏览器参数",+ "noBrowser": "该引擎通过 WebSocket 连接——没有浏览器,因此没有无头模式或浏览器参数设置。活动引擎将在重启后生效。",+ "restartNote": "切换引擎将在服务器重启后生效。"+ },"redis": {"title": "Redis","enable": "启用 Redis",@@ -615,7 +642,7 @@},"plugins": {"title": "插件",- "subtitle": "管理引擎、存储后端和扩展",+ "subtitle": "安装、配置和管理扩展","refresh": "刷新","engineCard": "当前 WhatsApp 引擎","running": "运行中",diff --git a/dashboard/src/i18n/locales/zh-HK.json b/dashboard/src/i18n/locales/zh-HK.jsonindex dc951dd31..862f8f211 100644--- a/dashboard/src/i18n/locales/zh-HK.json+++ b/dashboard/src/i18n/locales/zh-HK.json@@ -143,7 +143,8 @@"activeSessions": "活躍工作階段","messagesToday": "今日訊息","webhooksConfigured": "已設定 Webhook",- "apiCalls": "API 呼叫(24 小時)"+ "apiCalls": "API 呼叫(24 小時)",+ "totalMessages": "訊息總數"},"sessionsOverview": "工作階段概覽","showingSessions": "顯示 {{shown}} / {{total}} 個工作階段",@@ -158,7 +159,22 @@"view": "查看","disconnect": "中斷連線","errorPrefix": "錯誤:{{message}}",- "loadError": "載入資料失敗"+ "loadError": "載入資料失敗",+ "charts": {+ "title": "訊息分析",+ "period": {+ "24h": "24小時",+ "7d": "7天",+ "30d": "30天"+ },+ "overTime": "訊息趨勢",+ "byType": "按類型分類的訊息",+ "topChats": "熱門聊天",+ "sent": "已傳送",+ "received": "已接收",+ "messages": "訊息",+ "empty": "此期間沒有訊息活動。"+ }},"sessionStatus": {"created": "新增",@@ -552,6 +568,17 @@"migrationsStatus": "結構會透過 TypeORM 自動同步","migrationsHint": "遷移會自動管理。手動遷移請使用 CLI。"},+ "engine": {+ "title": "WhatsApp 引擎",+ "subtitle": "選擇並設定 WhatsApp 連線引擎。",+ "builtIn": "內置",+ "headless": "無頭模式",+ "headlessDesc": "在沒有可見介面的情況下執行瀏覽器(建議用於生產環境)。",+ "sessionDataPath": "工作階段資料路徑",+ "browserArgs": "瀏覽器參數",+ "noBrowser": "此引擎透過 WebSocket 連線——沒有瀏覽器,因此沒有無頭模式或瀏覽器參數設定。使用中的引擎會在重新啟動後生效。",+ "restartNote": "切換引擎會在伺服器重新啟動後生效。"+ },"redis": {"title": "Redis","enable": "啟用 Redis",@@ -615,7 +642,7 @@},"plugins": {"title": "外掛",- "subtitle": "管理引擎、儲存後端和擴充功能",+ "subtitle": "安裝、設定和管理擴充功能","refresh": "重新整理","engineCard": "目前 WhatsApp 引擎","running": "執行中",diff --git a/dashboard/src/index.css b/dashboard/src/index.cssindex a18a136d3..1aa6f7732 100644--- a/dashboard/src/index.css+++ b/dashboard/src/index.css@@ -174,6 +174,11 @@ select:disabled {width: 90%;max-width: 480px;animation: slideUp 0.3s ease;+ /* Cap height and lay out as a flex column so the body scrolls while the header and footer stay+ pinned — config-heavy modals no longer push the title/Save button off-screen. */+ display: flex;+ flex-direction: column;+ max-height: 90vh;overflow: hidden;}@@ -194,6 +199,7 @@ select:disabled {align-items: center;padding: 1.5rem 1.5rem 1rem;border-bottom: 1px solid var(--border, #e2e8f0);+ flex-shrink: 0;}.modal-header h2 {@@ -207,6 +213,9 @@ select:disabled {.modal-body {padding: 1.5rem;+ /* Scroll the body (not the whole card) so the pinned header/footer stay visible. */+ overflow-y: auto;+ flex: 1 1 auto;}.modal-body > label {@@ -235,11 +244,27 @@ select:disabled {box-shadow: 0 0 0 3px rgba(37, 211, 102, 0.1);}+/* The rule above is meant for TEXT inputs. Radios/checkboxes would otherwise stretch to width:100%+ and shove their labels far to the right; reset them back to their native box. The :not() excludes+ the visually-hidden toggle-switch checkbox (it must stay width:0) so this never ties with the+ per-page `.toggle-switch input { width:0 }` rule on specificity. */+.modal-body input[type='radio']:not(.toggle-switch input),+.modal-body input[type='checkbox']:not(.toggle-switch input) {+ width: auto;+ padding: 0;+ border: none;+ border-radius: 0;+ background: none;+ box-shadow: none;+ flex: none;+}+.modal-footer {display: flex;justify-content: flex-end;gap: 0.75rem;padding: 1rem 1.5rem 1.5rem;+ flex-shrink: 0;}/* Icon Button (modal close X) */@@ -421,7 +446,7 @@ code {width: 100%;margin: 0;border-radius: 16px 16px 0 0;- max-height: 90vh;- overflow-y: auto;+ /* max-height + body scroll already come from the base .modal rule; the bottom-sheet only+ changes width/anchoring. (Scrolling lives on .modal-body to avoid a double scrollbar.) */}}diff --git a/dashboard/src/pages/Chats.css b/dashboard/src/pages/Chats.cssindex 0ef3c257e..54b4132e9 100644--- a/dashboard/src/pages/Chats.css+++ b/dashboard/src/pages/Chats.css@@ -288,6 +288,9 @@justify-content: center;width: 36px;height: 36px;+ /* Reset the global `button` padding (0.6em 1.2em): with box-sizing:border-box it would consume+ the whole 36px width and collapse the arrow icon to 0px wide, making the button look empty. */+ padding: 0;margin-left: -0.5rem;background: transparent;border: none;diff --git a/dashboard/src/pages/Chats.tsx b/dashboard/src/pages/Chats.tsxindex ce8b6092d..79028f0a4 100644--- a/dashboard/src/pages/Chats.tsx+++ b/dashboard/src/pages/Chats.tsx@@ -341,7 +341,7 @@ export function Chats() {// failing — only surface an error if both do.const [dbRes, historyRes] = await Promise.allSettled([sessionApi.getChatMessages(selectedSessionId, chatId, 100),- sessionApi.getChatHistory(selectedSessionId, chatId, 100),+ sessionApi.getChatHistory(selectedSessionId, chatId, 100, true),]);if (dbRes.status === 'rejected' && historyRes.status === 'rejected') throw dbRes.reason;const dbMessages = dbRes.status === 'fulfilled' ? dbRes.value.messages : [];diff --git a/dashboard/src/pages/Dashboard.tsx b/dashboard/src/pages/Dashboard.tsxindex b5d1ff339..634d40df8 100644--- a/dashboard/src/pages/Dashboard.tsx+++ b/dashboard/src/pages/Dashboard.tsx@@ -1,11 +1,22 @@+import { lazy, Suspense } from 'react';import { useNavigate } from 'react-router-dom';import { useTranslation } from 'react-i18next';import { MessageSquare, Send, Webhook, Activity, ArrowUpRight, ArrowDownRight, Loader2 } from 'lucide-react';import { useDocumentTitle } from '../hooks/useDocumentTitle';-import { useSessionsQuery, useSessionStatsQuery, useWebhooksQuery, useStopSessionMutation } from '../hooks/queries';+import {+ useSessionsQuery,+ useSessionStatsQuery,+ useWebhooksQuery,+ useStopSessionMutation,+ useStatsOverviewQuery,+} from '../hooks/queries';import { PageHeader } from '../components/PageHeader';import './Dashboard.css';+// recharts is heavy (~150kB gzip); load the analytics section on demand so it never bloats the+// main/login bundle and only ships when the dashboard actually renders.+const DashboardCharts = lazy(() => import('../components/DashboardCharts').then(m => ({ default: m.DashboardCharts })));+export function Dashboard() {const { t } = useTranslation();useDocumentTitle(t('dashboard.title'));@@ -13,7 +24,12 @@ export function Dashboard() {const { data: sessions = [], isLoading: loadingSessions, error: sessionsError } = useSessionsQuery();const { data: stats } = useSessionStatsQuery();const { data: webhooks = [] } = useWebhooksQuery();+ // /stats/overview is ADMIN-only; for a non-admin key it 403s → overview stays undefined and the+ // message cards fall back to '—' without breaking the (un-gated) session cards.+ const { data: overview } = useStatsOverviewQuery();const stopMutation = useStopSessionMutation();+ const messagesToday = overview ? overview.messages.today.sent + overview.messages.today.received : '—';+ const totalMessages = overview ? overview.messages.sent + overview.messages.received : '—';const loading = loadingSessions;const error = sessionsError instanceof Error? sessionsError.message@@ -38,9 +54,9 @@ export function Dashboard() {trend: `+${stats?.ready ?? 0}`,trendUp: true,},- { label: t('dashboard.stats.messagesToday'), value: '—', icon: Send, trend: '0', trendUp: null },+ { label: t('dashboard.stats.messagesToday'), value: messagesToday, icon: Send, trend: '0', trendUp: null },{ label: t('dashboard.stats.webhooksConfigured'), value: webhookCount, icon: Webhook, trend: '0', trendUp: null },- { label: t('dashboard.stats.apiCalls'), value: '—', icon: Activity, trend: '0', trendUp: null },+ { label: t('dashboard.stats.totalMessages'), value: totalMessages, icon: Activity, trend: '0', trendUp: null },];const formatLastActive = (date?: string) => {@@ -106,6 +122,10 @@ export function Dashboard() {))}</div>+ <Suspense fallback={null}>+ <DashboardCharts />+ </Suspense>+<section className="sessions-section"><div className="section-header"><h2>{t('dashboard.sessionsOverview')}</h2>diff --git a/dashboard/src/pages/Infrastructure.tsx b/dashboard/src/pages/Infrastructure.tsxindex bc8894c9a..6c99fbf7b 100644--- a/dashboard/src/pages/Infrastructure.tsx+++ b/dashboard/src/pages/Infrastructure.tsx@@ -12,10 +12,16 @@ import {Globe,Webhook,Gauge,+ Cpu,} from 'lucide-react';import { infraApi, API_BASE_URL } from '../services/api';import { useDocumentTitle } from '../hooks/useDocumentTitle';-import { useInfraStatusQuery, useInfraConfigQuery } from '../hooks/queries';+import {+ useInfraStatusQuery,+ useInfraConfigQuery,+ useEnginesQuery,+ useCurrentEngineQuery,+} from '../hooks/queries';import { PageHeader } from '../components/PageHeader';import { useToast } from '../components/Toast';import './Infrastructure.css';@@ -57,6 +63,13 @@ interface StorageConfig {s3Endpoint: string;}+interface EngineConfig {+ type: string;+ headless: boolean;+ sessionDataPath: string;+ browserArgs: string;+}+interface QueueStats {pending: number;completed: number;@@ -90,6 +103,9 @@ export function Infrastructure() {const toast = useToast();const { data: infraStatus, isLoading: loading } = useInfraStatusQuery();const { data: savedConfig } = useInfraConfigQuery();+ const { data: engines = [] } = useEnginesQuery();+ const { data: currentEngineData } = useCurrentEngineQuery();+ const currentEngine = currentEngineData?.engineType ?? '';const [saving, setSaving] = useState(false);const [showRestartModal, setShowRestartModal] = useState(false);const [restartCountdown, setRestartCountdown] = useState(0);@@ -132,6 +148,13 @@ export function Infrastructure() {webhooks: { pending: 0, completed: 0, failed: 0 } as QueueStats,});+ const [engineConfig, setEngineConfig] = useState<EngineConfig>({+ type: 'whatsapp-web.js',+ headless: true,+ sessionDataPath: './data/sessions',+ browserArgs: '--no-sandbox --disable-gpu',+ });+const [redisEnabled, setRedisEnabled] = useState(false);const [queueEnabled, setQueueEnabled] = useState(false);const [pendingProfiles, setPendingProfiles] = useState<string[]>([]);@@ -222,8 +245,20 @@ export function Infrastructure() {s3Region: savedConfig.storage.s3Region || prev.s3Region,s3Endpoint: savedConfig.storage.s3Endpoint || prev.s3Endpoint,}));+ setEngineConfig(prev => ({+ ...prev,+ headless: savedConfig.engine.headless,+ sessionDataPath: savedConfig.engine.sessionDataPath || prev.sessionDataPath,+ browserArgs: savedConfig.engine.browserArgs || prev.browserArgs,+ }));}, [savedConfig]);+ // The active engine reflects what's actually running (honours a real-env ENGINE_TYPE override),+ // so seed the selected radio from it rather than the saved .env.generated value.+ useEffect(() => {+ if (currentEngine) setEngineConfig(prev => ({ ...prev, type: currentEngine }));+ }, [currentEngine]);+if (loading) {return (<div@@ -241,6 +276,8 @@ export function Infrastructure() {setRedisConfig(prev => ({ ...prev, [key]: value }));const updateStorageConfig = (key: keyof StorageConfig, value: string | boolean) =>setStorageConfig(prev => ({ ...prev, [key]: value }));+ const updateEngineConfig = (key: keyof EngineConfig, value: string | boolean) =>+ setEngineConfig(prev => ({ ...prev, [key]: value }));const updateServerConfig = (key: keyof ServerConfig, value: string) =>setServerConfig(prev => ({ ...prev, [key]: value }));const updateWebhookConfig = (key: keyof WebhookConfig, value: number) =>@@ -256,6 +293,7 @@ export function Infrastructure() {redis: { enabled: redisEnabled, ...redisConfig },queue: { enabled: queueEnabled },storage: { ...storageConfig },+ engine: { ...engineConfig },server: { ...serverConfig },webhook: { ...webhookConfig },rateLimit: { ...rateLimitConfig },@@ -662,6 +700,81 @@ export function Infrastructure() {</div></section>+ {/* Engine */}+ <section className="infra-card">+ <div className="card-header">+ <div className="header-left">+ <Cpu size={20} />+ <h2>{t('infrastructure.engine.title')}</h2>+ </div>+ <span className="status-indicator connected">● {currentEngine || engineConfig.type}</span>+ </div>++ <div className="radio-group">+ {engines.map(engine => (+ <label key={engine.id} className={`radio-option ${engineConfig.type === engine.id ? 'selected' : ''}`}>+ <input+ type="radio"+ name="engineType"+ checked={engineConfig.type === engine.id}+ onChange={() => updateEngineConfig('type', engine.id)}+ />+ <Cpu className="watermark-icon" />+ <span>{engine.name}</span>+ <small>+ {engine.library+ ? `${engine.library.name} ${engine.library.version}`+ : t('infrastructure.engine.builtIn')}+ </small>+ </label>+ ))}+ </div>++ {engineConfig.type === 'whatsapp-web.js' ? (+ <div className="config-form">+ <div className="toggle-row">+ <div className="toggle-info">+ <span>{t('infrastructure.engine.headless')}</span>+ <small>{t('infrastructure.engine.headlessDesc')}</small>+ </div>+ <label className="toggle-switch">+ <input+ type="checkbox"+ checked={engineConfig.headless}+ onChange={e => updateEngineConfig('headless', e.target.checked)}+ />+ <span className="toggle-slider"></span>+ </label>+ </div>+ <div className="form-group">+ <label>{t('infrastructure.engine.sessionDataPath')}</label>+ <input+ type="text"+ value={engineConfig.sessionDataPath}+ onChange={e => updateEngineConfig('sessionDataPath', e.target.value)}+ />+ </div>+ <div className="form-group">+ <label>{t('infrastructure.engine.browserArgs')}</label>+ <input+ type="text"+ value={engineConfig.browserArgs}+ onChange={e => updateEngineConfig('browserArgs', e.target.value)}+ placeholder="--no-sandbox --disable-gpu"+ />+ </div>+ </div>+ ) : (+ <p style={{ margin: '0.5rem 0 0', color: '#64748B', fontSize: '0.8125rem', lineHeight: 1.5 }}>+ {t('infrastructure.engine.noBrowser')}+ </p>+ )}++ <p style={{ margin: '1rem 0 0', color: '#64748B', fontSize: '0.8125rem', lineHeight: 1.5 }}>+ {t('infrastructure.engine.restartNote')}+ </p>+ </section>+{/* Redis */}<section className="infra-card"><div className="card-header">diff --git a/dashboard/src/pages/Plugins.css b/dashboard/src/pages/Plugins.cssindex 8723b6ec1..e3048168d 100644--- a/dashboard/src/pages/Plugins.css+++ b/dashboard/src/pages/Plugins.css@@ -422,7 +422,7 @@/* Config Modal */.plugins-page .config-modal{- max-width: 500px;+ max-width: 640px;width: 90%;}@@ -928,53 +928,42 @@}/* ── Install modal: Upload / Catalog tabs + catalog list ─────────────────── */-.plugins-page .install-tabs{- display: flex;- gap: 4px;- padding: 0 20px;- border-bottom: 1px solid var(--border, #e5e7eb);+/* Segmented pill tab control — shared shape for the install (Upload/Catalog) and+ config (Configuration/Sessions) modal tabs. Replaces the old flat green underline. */+.plugins-page .install-tabs,+.plugins-page .config-modal .modal-tabs{+ display: inline-flex;+ align-self: center;+ gap: 2px;+ margin: 0 0 0.75rem;+ padding: 3px;+ background: var(--bg-light);+ border: 1px solid var(--border);+ border-radius: 10px;}-.plugins-page .install-tab{+.plugins-page .install-tab,+.plugins-page .config-modal .modal-tab{display: inline-flex;align-items: center;+ justify-content: center;gap: 6px;- padding: 10px 14px;+ padding: 0.4rem 0.9rem;background: none;border: none;- border-bottom: 2px solid transparent;- color: var(--text-secondary, #6b7280);- font-size: 0.875rem;- cursor: pointer;-}--.plugins-page .install-tab.active{- color: var(--text, #111827);- border-bottom-color: var(--primary, #25d366);-}--/* Config modal tabs (Configuration / Sessions) */-.plugins-page .config-modal .modal-tabs{- display: flex;- gap: 4px;- padding: 0 1.5rem;- border-bottom: 1px solid var(--border);-}--.plugins-page .config-modal .modal-tab{- padding: 0.625rem 0.9rem;- background: none;- border: none;- border-bottom: 2px solid transparent;+ border-radius: 7px;color: var(--text-secondary);font-size: 0.875rem;font-weight: 600;cursor: pointer;+ transition: background 0.15s ease, color 0.15s ease;}+.plugins-page .install-tab.active,.plugins-page .config-modal .modal-tab.active{+ background: var(--bg-white);color: var(--text-primary);- border-bottom-color: var(--primary);+ box-shadow: 0 1px 2px rgba(0, 0, 0, 0.06);}/* Sessions tab */diff --git a/dashboard/src/pages/Plugins.tsx b/dashboard/src/pages/Plugins.tsxindex a7c1ea4bf..3e2404b3e 100644--- a/dashboard/src/pages/Plugins.tsx+++ b/dashboard/src/pages/Plugins.tsx@@ -25,17 +25,10 @@ import {Plus,Search,} from 'lucide-react';-import { pluginsApi, infraApi } from '../services/api';+import { pluginsApi } from '../services/api';import type { Plugin, CatalogPlugin, PluginConfigField } from '../services/api';import { useDocumentTitle } from '../hooks/useDocumentTitle';-import {- usePluginsQuery,- useEnginesQuery,- useCurrentEngineQuery,- useInfraStatusQuery,- useSessionsQuery,- queryKeys,-} from '../hooks/queries';+import { usePluginsQuery, useSessionsQuery, queryKeys } from '../hooks/queries';import { PageHeader } from '../components/PageHeader';import { useToast } from '../components/Toast';import './Plugins.css';@@ -50,13 +43,6 @@ const pluginTypeIcons: Record<PluginType, typeof Puzzle> = {extension: Zap,};-interface EngineConfig {- type: string;- headless: boolean;- sessionDataPath: string;- browserArgs: string;-}-/*** Build a sparse per-session config override from a full edited config: include only non-secret keys* whose value differs from the Global base (so untouched keys keep inheriting Global), plus every@@ -534,10 +520,6 @@ export default function Plugins() {const toast = useToast();const queryClient = useQueryClient();const { data: plugins = [], isLoading: loadingPlugins, error: queryError } = usePluginsQuery();- const { data: engines = [] } = useEnginesQuery();- const { data: currentEngineData } = useCurrentEngineQuery();- const { data: infraStatus } = useInfraStatusQuery();- const currentEngine = currentEngineData?.engineType ?? '';const loading = loadingPlugins;const error = queryError instanceof Error ? queryError.message : null;const [actionLoading, setActionLoading] = useState<string | null>(null);@@ -549,12 +531,6 @@ export default function Plugins() {// latest activeSessions/sessionConfig after a save + invalidate — not a stale open-time snapshot.const configPlugin = configPluginId ? (plugins.find(p => p.id === configPluginId) ?? null) : null;const [configTab, setConfigTab] = useState<'config' | 'sessions'>('config');- const [engineConfig, setEngineConfig] = useState<EngineConfig>({- type: infraStatus?.engine?.type || 'whatsapp-web.js',- headless: infraStatus?.engine?.headless ?? true,- sessionDataPath: '/data/sessions',- browserArgs: '--no-sandbox --disable-gpu',- });const [savingConfig, setSavingConfig] = useState(false);// Values for a schema-driven (non-engine) plugin's config form, keyed by configSchema property.const [schemaConfig, setSchemaConfig] = useState<Record<string, unknown>>({});@@ -570,8 +546,6 @@ export default function Plugins() {const refetchAll = () => {void queryClient.invalidateQueries({ queryKey: queryKeys.plugins });- void queryClient.invalidateQueries({ queryKey: queryKeys.engines });- void queryClient.invalidateQueries({ queryKey: queryKeys.currentEngine });};const handleToggle = async (plugin: Plugin) => {@@ -640,28 +614,6 @@ export default function Plugins() {}};- const handleSaveConfig = async () => {- setSavingConfig(true);- try {- // Persist the engine section to the backend (.env.generated via PUT /infra/config).- // The engine `type` isn't a savable field (only whatsapp-web.js exists); the backend- // maps these to PUPPETEER_HEADLESS / SESSION_DATA_PATH / PUPPETEER_ARGS.- await infraApi.saveConfig({- engine: {- headless: engineConfig.headless,- sessionDataPath: engineConfig.sessionDataPath,- browserArgs: engineConfig.browserArgs,- },- });- toast.success(t('plugins.toasts.savedTitle'), t('plugins.toasts.savedDesc'));- setShowConfigModal(false);- } catch (err) {- toast.error(t('plugins.toasts.saveFailed'), err instanceof Error ? err.message : t('common.unknownError'));- } finally {- setSavingConfig(false);- }- };-const handleInstall = async () => {if (!installFile) return;if (installFile.size > 5 * 1024 * 1024) {@@ -772,9 +724,11 @@ export default function Plugins() {);}- const activeEngine = engines.find(e => e.id === currentEngine);- const enabledCount = plugins.filter(p => p.status === 'enabled').length;- const activePlugins = plugins.filter(p => p.status === 'enabled');+ // Engines are configured under Infrastructure (Engine Configuration tile), not here — keep them+ // out of the plugin grid, the counts and the rail so the Plugins page is extensions-only.+ const visiblePlugins = plugins.filter(p => p.type !== 'engine');+ const enabledCount = visiblePlugins.filter(p => p.status === 'enabled').length;+ const activePlugins = visiblePlugins.filter(p => p.status === 'enabled');return (<div className="plugins-page">@@ -804,31 +758,13 @@ export default function Plugins() {<div className="plugins-layout"><aside className="plugins-rail">- <div className="rail-section">- <p className="rail-label">{t('plugins.rail.engine', 'Active engine')}</p>- <div className="rail-engine">- <div className="rail-engine-icon">- <Cpu size={18} />- </div>- <div className="rail-engine-meta">- <span className="rail-engine-name">{currentEngine || '—'}</span>- {activeEngine?.library && (- <span className="rail-engine-lib">- {activeEngine.library.name} {activeEngine.library.version}- </span>- )}- </div>- <span className="status-badge connected">{t('plugins.running')}</span>- </div>- </div>-<div className="rail-stats"><div className="rail-stat"><span className="rail-stat-num">{enabledCount}</span><span className="rail-stat-label">{t('plugins.rail.enabled', 'enabled')}</span></div><div className="rail-stat">- <span className="rail-stat-num">{plugins.length}</span>+ <span className="rail-stat-num">{visiblePlugins.length}</span><span className="rail-stat-label">{t('plugins.rail.installed', 'installed')}</span></div></div>@@ -853,7 +789,7 @@ export default function Plugins() {<main className="plugins-main"><div className="plugins-grid">- {plugins.map(plugin => {+ {visiblePlugins.map(plugin => {const TypeIcon = pluginTypeIcons[plugin.type as PluginType] || Puzzle;const isLoading = actionLoading === plugin.id;const lz = localizePlugin(plugin, i18n.language);@@ -901,64 +837,25 @@ export default function Plugins() {)}<div className="plugin-actions">- {plugin.type === 'engine' ? (- (() => {- const enginePlugins = plugins.filter(p => p.type === 'engine');- const isOnlyEngine = enginePlugins.length === 1;- const isActive = plugin.status === 'enabled';-- if (isOnlyEngine && isActive) {- return (- <span className="btn-required">- <CheckCircle size={16} />- {t('plugins.required')}- </span>- );- } else if (isActive) {- return (- <span className="btn-active">- <CheckCircle size={16} />- {t('plugins.active')}- </span>- );- } else {- // Engines are pinned to engine.type and switched via Settings + restart, not at- // runtime — show "available" instead of a misleading "Activate" that the API rejects.- return (- <span- className="btn-available"- title={t(- 'plugins.engineSwitchHint',- 'Set as the active engine in Settings, then restart',- )}- >- <Cpu size={16} />- {t('plugins.available', 'Available')}- </span>- );- }- })()- ) : (- <button- onClick={() => handleToggle(plugin)}- disabled={isLoading}- className={`btn-toggle ${plugin.status === 'enabled' ? 'disable' : 'enable'}`}- >- {isLoading ? (- <Loader2 size={16} className="animate-spin" />- ) : plugin.status === 'enabled' ? (- <>- <PowerOff size={16} />- {t('plugins.disable')}- </>- ) : (- <>- <Power size={16} />- {t('plugins.enable')}- </>- )}- </button>- )}+ <button+ onClick={() => handleToggle(plugin)}+ disabled={isLoading}+ className={`btn-toggle ${plugin.status === 'enabled' ? 'disable' : 'enable'}`}+ >+ {isLoading ? (+ <Loader2 size={16} className="animate-spin" />+ ) : plugin.status === 'enabled' ? (+ <>+ <PowerOff size={16} />+ {t('plugins.disable')}+ </>+ ) : (+ <>+ <Power size={16} />+ {t('plugins.enable')}+ </>+ )}+ </button><buttononClick={() => handleHealthCheck(plugin.id)}@@ -996,7 +893,7 @@ export default function Plugins() {</main></div>- {plugins.length === 0 && !loading && (+ {visiblePlugins.length === 0 && !loading && (<div className="empty-state"><Puzzle size={64} /><h3>{t('plugins.empty.title')}</h3>@@ -1190,8 +1087,8 @@ export default function Plugins() {configPlugin &&(() => {const lz = localizePlugin(configPlugin, i18n.language);- // Session-scoped, non-engine plugins get a Configuration/Sessions tab split; others keep one body.- const showTabs = configPlugin.type !== 'engine' && configPlugin.sessionScoped !== false;+ // Session-scoped plugins get a Configuration/Sessions tab split; others keep one body.+ const showTabs = configPlugin.sessionScoped !== false;return (<div className="modal-overlay" onClick={() => setShowConfigModal(false)}><div className="modal config-modal" onClick={e => e.stopPropagation()}>@@ -1222,63 +1119,6 @@ export default function Plugins() {<div className="modal-body">{showTabs && configTab === 'sessions' ? (<SessionsTab plugin={configPlugin} />- ) : configPlugin.type === 'engine' ? (- <>- <div className="config-info-banner">- <AlertCircle size={16} />- <span>{t('plugins.config.restartNotice')}</span>- </div>-- {/* Only the browser engine (whatsapp-web.js) has Puppeteer settings. Baileys is a- WebSocket client with no browser, so headless/browser-args don't apply. */}- {configPlugin.id === 'whatsapp-web.js' ? (- <div className="config-form">- <div className="form-group toggle-group">- <div className="toggle-info">- <label>{t('plugins.config.headless')}</label>- <small>{t('plugins.config.headlessDesc')}</small>- </div>- <label className="toggle-switch">- <input- type="checkbox"- checked={engineConfig.headless}- onChange={e => setEngineConfig({ ...engineConfig, headless: e.target.checked })}- />- <span className="toggle-slider"></span>- </label>- </div>-- <div className="form-group">- <label>{t('plugins.config.sessionDataPath')}</label>- <input- type="text"- value={engineConfig.sessionDataPath}- onChange={e => setEngineConfig({ ...engineConfig, sessionDataPath: e.target.value })}- />- </div>-- <div className="form-group">- <label>{t('plugins.config.browserArgs')}</label>- <input- type="text"- value={engineConfig.browserArgs}- onChange={e => setEngineConfig({ ...engineConfig, browserArgs: e.target.value })}- placeholder="--no-sandbox --disable-gpu"- />- </div>- </div>- ) : (- <div className="no-config">- <Cpu size={48} style={{ opacity: 0.3 }} />- <p>- {t(- 'plugins.config.noBrowserEngine',- 'This engine connects over WebSocket — it has no browser, so there are no headless or browser-argument settings here. Its options are set via environment variables, and the active engine is selected with ENGINE_TYPE (a restart applies the change).',- )}- </p>- </div>- )}- </>) : configPlugin.configUi ? (<PluginConfigUi plugin={configPlugin} />) : lz.configSchema && Object.keys(lz.configSchema.properties).length > 0 ? (@@ -1305,15 +1145,8 @@ export default function Plugins() {<button className="btn-secondary" onClick={() => setShowConfigModal(false)}>{t('common.close')}</button>- {/* The Sessions tab has its own Save/Clear actions; the footer Save is config-tab only.- Only the browser engine has savable settings — Baileys shows an info panel, no Save. */}- {showTabs && configTab === 'sessions' ? null : configPlugin.type === 'engine' ? (- configPlugin.id === 'whatsapp-web.js' ? (- <button className="btn-primary" onClick={handleSaveConfig} disabled={savingConfig}>- {savingConfig ? <Loader2 size={16} className="animate-spin" /> : t('plugins.config.save')}- </button>- ) : null- ) : configPlugin.configUi ? null : lz.configSchema &&+ {/* The Sessions tab has its own Save/Clear actions; the footer Save is config-tab only. */}+ {showTabs && configTab === 'sessions' ? null : configPlugin.configUi ? null : lz.configSchema &&Object.keys(lz.configSchema.properties).length > 0 ? (<button className="btn-primary" onClick={handleSaveSchemaConfig} disabled={savingConfig}>{savingConfig ? <Loader2 size={16} className="animate-spin" /> : t('plugins.config.save')}diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.tsindex 61e21f326..713bfa4c3 100644--- a/dashboard/src/services/api.ts+++ b/dashboard/src/services/api.ts@@ -194,6 +194,8 @@ export interface SendMediaPayload {export interface HealthStatus {status: 'ok' | 'error';timestamp?: string;+ /** Running backend version (from package.json) — read live so the sidebar never shows a stale build. */+ version?: string;details?: {database?: { status: string };redis?: { status: string };@@ -239,7 +241,7 @@ export interface SavedConfig {s3Endpoint: string;s3CredentialsSet: boolean;};- engine: { headless: boolean; sessionDataPath: string; browserArgs: string };+ engine: { type: string; headless: boolean; sessionDataPath: string; browserArgs: string };}export interface SaveConfigPayload {@@ -276,6 +278,7 @@ export interface SaveConfigPayload {s3Endpoint?: string;};engine?: {+ type?: string;headless?: boolean;sessionDataPath?: string;browserArgs?: string;@@ -395,9 +398,13 @@ export const sessionApi = {),// Live history straight from WhatsApp (bypasses the DB) — backfills a thread the gateway never// captured, e.g. a freshly paired session whose persisted store is still empty.- getChatHistory: (id: string, chatId: string, limit = 100) =>+ // includeMedia downloads the media payload (base64) for history messages so stickers/images/+ // video/voice render instead of collapsing to an empty timestamp-only bubble.+ getChatHistory: (id: string, chatId: string, limit = 100, includeMedia = false) =>request<EngineHistoryMessage[]>(- `/sessions/${id}/messages/${encodeURIComponent(chatId)}/history?limit=${limit}`,+ `/sessions/${id}/messages/${encodeURIComponent(chatId)}/history?limit=${limit}${+ includeMedia ? '&includeMedia=true' : ''+ }`,),};@@ -758,3 +765,32 @@ export const pluginsApi = {getEngines: () => request<Engine[]>('/infra/engines'),getCurrentEngine: () => request<{ engineType: string }>('/infra/engines/current'),};++// =============================================================================+// Statistics API (mirrors src/modules/stats)+// =============================================================================++export type StatsPeriod = '24h' | '7d' | '30d';++export interface OverviewStats {+ sessions: { active: number; total: number; byStatus: Record<string, number> };+ messages: { sent: number; received: number; failed: number; today: { sent: number; received: number } };+}++export interface MessageTimeSeriesPoint {+ timestamp: string;+ sent: number;+ received: number;+}++export interface MessageStats {+ timeSeries: MessageTimeSeriesPoint[];+ byType: Record<string, number>;+ bySession: Array<{ sessionId: string; name: string; sent: number; received: number }>;+ topChats: Array<{ chatId: string; messageCount: number }>;+}++export const statsApi = {+ getOverview: () => request<OverviewStats>('/stats/overview'),+ getMessages: (period: StatsPeriod) => request<MessageStats>(`/stats/messages?period=${period}`),+};diff --git a/docker-compose.dev.yml b/docker-compose.dev.ymlindex 16ddd44cf..7228b5b3b 100644--- a/docker-compose.dev.yml+++ b/docker-compose.dev.yml@@ -45,7 +45,9 @@ services:- DATABASE_TYPE=sqlite- DATABASE_NAME=/app/data/openwa.sqlite- DATABASE_SYNCHRONIZE=true- - ENGINE_TYPE=whatsapp-web.js+ # ENGINE_TYPE not pinned: the dashboard (Infrastructure > Engine) selects the active engine via+ # data/.env.generated (default whatsapp-web.js). main.ts loads it with override:false, so a real+ # env here would override the dashboard choice.- SESSION_DATA_PATH=/app/data/sessions- PUPPETEER_HEADLESS=true- PUPPETEER_ARGS=--no-sandbox,--disable-setuid-sandbox,--disable-dev-shm-usage,--disable-gpudiff --git a/docker-compose.yml b/docker-compose.ymlindex ee5ee2156..1a6702287 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -88,8 +88,10 @@ services:# postgres service requires it (:?) when that profile is active.- DATABASE_PASSWORD=${DATABASE_PASSWORD:-}- DATABASE_SYNCHRONIZE=${DATABASE_SYNCHRONIZE:-false}- # Engine- - ENGINE_TYPE=${ENGINE_TYPE:-whatsapp-web.js}+ # Engine. ENGINE_TYPE is intentionally NOT pinned here so the dashboard+ # (Infrastructure > Engine) can select the active engine via data/.env.generated+ # (defaults to whatsapp-web.js). main.ts loads .env.generated with override:false, so a+ # real container env here would silently win over the dashboard selection.- SESSION_DATA_PATH=/app/data/sessions- PUPPETEER_HEADLESS=${PUPPETEER_HEADLESS:-true}- PUPPETEER_ARGS=${PUPPETEER_ARGS:---no-sandbox,--disable-setuid-sandbox,--disable-dev-shm-usage,--disable-gpu}diff --git a/src/main.ts b/src/main.tsindex 1e40267dd..e3e6e04ec 100644--- a/src/main.ts+++ b/src/main.ts@@ -155,6 +155,10 @@ async function bootstrap() {styleSrc: ["'self'", "'unsafe-inline'", 'https://fonts.googleapis.com'],scriptSrc: ["'self'"],imgSrc: ["'self'", 'data:', 'https:'],+ // Chat media (voice notes, video) is served to the dashboard as data: URIs. Without an+ // explicit media-src, <audio>/<video> fall back to default-src 'self' and are blocked.+ // Mirror imgSrc so audio/video render the same way images already do.+ mediaSrc: ["'self'", 'data:', 'blob:', 'https:'],connectSrc: ["'self'"],fontSrc: ["'self'", 'https://fonts.gstatic.com'],objectSrc: ["'none'"],diff --git a/src/modules/health/health.controller.spec.ts b/src/modules/health/health.controller.spec.tsindex cc3c2cfe5..f34e5d8ba 100644--- a/src/modules/health/health.controller.spec.ts+++ b/src/modules/health/health.controller.spec.ts@@ -39,6 +39,12 @@ describe('HealthController', () => {expect(result.status).toBe('ok');expect(result.timestamp).toBeDefined();});++ it('reports the running version (from package.json) so the dashboard reads it live', () => {+ // eslint-disable-next-line @typescript-eslint/no-require-imports+ const { version } = require('../../../package.json') as { version: string };+ expect(controller.check().version).toBe(version);+ });});describe('liveness', () => {diff --git a/src/modules/health/health.controller.ts b/src/modules/health/health.controller.tsindex 0bd97114d..1ccaa95c8 100644--- a/src/modules/health/health.controller.ts+++ b/src/modules/health/health.controller.ts@@ -18,6 +18,11 @@ interface HealthCheckResult {/** Bound each dependency probe so a hung connection can't stall the readiness check. */const READINESS_PROBE_TIMEOUT_MS = 3000;+// Source the running version from package.json (same pattern as swagger.config.ts) so the dashboard+// can read it live and never show a stale build-time-baked version. Read once at module load.+// eslint-disable-next-line @typescript-eslint/no-require-imports+const { version: APP_VERSION } = require('../../../package.json') as { version: string };+@ApiTags('health')@Controller('health')@Public()@@ -32,10 +37,11 @@ export class HealthController {@Get()@ApiOperation({ summary: 'Basic health check' })@ApiResponse({ status: 200, description: 'Application is healthy' })- check(): { status: string; timestamp: string } {+ check(): { status: string; timestamp: string; version: string } {return {status: 'ok',timestamp: new Date().toISOString(),+ version: APP_VERSION,};}diff --git a/src/modules/infra/infra.controller.spec.ts b/src/modules/infra/infra.controller.spec.tsindex 45ab3865a..a202e780c 100644--- a/src/modules/infra/infra.controller.spec.ts+++ b/src/modules/infra/infra.controller.spec.ts@@ -231,6 +231,53 @@ describe('InfraController.saveConfig env-name correctness and merge (#226)', ()});});+describe('InfraController.saveConfig engine selection (persist ENGINE_TYPE — Infrastructure tile)', () => {+ const engineFactory = {+ getAvailableEngines: () => [{ id: 'whatsapp-web.js' }, { id: 'baileys' }],+ };+ const newController = () =>+ new InfraController(+ {} as never,+ {} as never,+ {} as never,+ engineFactory as never,+ {} as never,+ {} as never,+ {} as never,+ {} as never,+ );++ function written(config: unknown, existing?: string): string {+ (fs.existsSync as jest.Mock).mockReturnValue(existing !== undefined);+ (fs.readFileSync as jest.Mock).mockReturnValue(existing ?? '');+ (fs.writeFileSync as jest.Mock).mockClear();+ newController().saveConfig(config as never);+ const content = ((fs.writeFileSync as jest.Mock).mock.calls as Array<[string, string]>)[0][1];+ (fs.existsSync as jest.Mock).mockReturnValue(false);+ (fs.readFileSync as jest.Mock).mockReturnValue('');+ return content;+ }++ it('persists ENGINE_TYPE when a valid engine is selected', () => {+ const env = written({ engine: { type: 'baileys', headless: true } });+ expect(env).toContain('ENGINE_TYPE=baileys');+ });++ it('does not write ENGINE_TYPE when no engine type is provided (avoids clobbering)', () => {+ const env = written({ engine: { headless: false } });+ expect(env).not.toContain('ENGINE_TYPE=');+ expect(env).toContain('PUPPETEER_HEADLESS=false');+ });++ it('rejects an unknown engine type and writes nothing', () => {+ (fs.writeFileSync as jest.Mock).mockClear();+ const res = newController().saveConfig({ engine: { type: 'bogus' } });+ expect(res.saved).toBe(false);+ expect(res.message).toMatch(/unknown engine/i);+ expect(fs.writeFileSync as jest.Mock).not.toHaveBeenCalled();+ });+});+describe('InfraController.importData round-trips export-data (no silent message/batch loss)', () => {let ds: DataSource;let controller: InfraController;@@ -373,7 +420,7 @@ describe('InfraController.getConfig (#226)', () => {it('returns the saved config shape without echoing secrets', () => {(fs.existsSync as jest.Mock).mockReturnValue(true);(fs.readFileSync as jest.Mock).mockReturnValue(- 'DATABASE_TYPE=postgres\nDATABASE_HOST=db\nDATABASE_PASSWORD=secret\nSESSION_DATA_PATH=./sess\nSTORAGE_TYPE=s3\nS3_ACCESS_KEY_ID=ak\nS3_SECRET_ACCESS_KEY=sk\n',+ 'DATABASE_TYPE=postgres\nDATABASE_HOST=db\nDATABASE_PASSWORD=secret\nSESSION_DATA_PATH=./sess\nENGINE_TYPE=baileys\nSTORAGE_TYPE=s3\nS3_ACCESS_KEY_ID=ak\nS3_SECRET_ACCESS_KEY=sk\n',);const controller = new InfraController({} as never,@@ -394,6 +441,7 @@ describe('InfraController.getConfig (#226)', () => {expect(cfg.database.host).toBe('db');expect(cfg.database.passwordSet).toBe(true);expect(cfg.engine.sessionDataPath).toBe('./sess');+ expect(cfg.engine.type).toBe('baileys');expect(cfg.storage.type).toBe('s3');expect(cfg.storage.s3CredentialsSet).toBe(true);// Secrets are never present on the returned object.@@ -402,6 +450,35 @@ describe('InfraController.getConfig (#226)', () => {});});+describe('InfraController.getStatus engine (F7 — reads the real engine.puppeteer.* keys)', () => {+ it('reports the saved headless/browserArgs instead of stale defaults from non-existent flat keys', async () => {+ const map: Record<string, unknown> = {+ 'engine.type': 'whatsapp-web.js',+ 'engine.puppeteer.headless': false,+ 'engine.puppeteer.args': ['--foo', '--bar'],+ 'engine.sessionDataPath': './sess',+ };+ const config = { get: (key: string, def?: unknown) => (key in map ? map[key] : def) };+ const cache = { isAvailable: () => Promise.resolve(false) };+ const ds = { isInitialized: true };+ const controller = new InfraController(+ config as never,+ ds as never,+ ds as never,+ {} as never,+ {} as never,+ cache as never,+ {} as never,+ {} as never,+ );++ const status = await controller.getStatus();+ expect(status.engine.headless).toBe(false);+ expect(status.engine.browserArgs).toBe('--foo --bar');+ expect(status.engine.sessionDataPath).toBe('./sess');+ });+});+describe('InfraController.exportStorage keeps the export import-able and sweeps it', () => {function buildController(storage: Partial<{ createExportStream: jest.Mock }>) {return new InfraController(diff --git a/src/modules/infra/infra.controller.ts b/src/modules/infra/infra.controller.tsindex 89353d2c1..59731c723 100644--- a/src/modules/infra/infra.controller.ts+++ b/src/modules/infra/infra.controller.ts@@ -64,6 +64,7 @@ interface SaveConfigDto {s3Endpoint?: string;};engine?: {+ type?: string;headless?: boolean;sessionDataPath?: string;browserArgs?: string;@@ -169,7 +170,7 @@ interface SavedConfigResponse {s3Endpoint: string;s3CredentialsSet: boolean;};- engine: { headless: boolean; sessionDataPath: string; browserArgs: string };+ engine: { type: string; headless: boolean; sessionDataPath: string; browserArgs: string };}@ApiTags('infrastructure')@@ -214,9 +215,12 @@ export class InfraController {const storagePath = this.configService.get<string>('storage.path', './uploads');const engineType = this.configService.get<string>('engine.type', 'whatsapp-web.js');- const engineHeadless = this.configService.get<boolean>('engine.headless', true);+ // configuration.ts nests these under engine.puppeteer.{headless,args}; the old flat+ // engine.headless / engine.browserArgs keys never existed, so status always reported defaults.+ const engineHeadless = this.configService.get<boolean>('engine.puppeteer.headless', true) ?? true;const sessionDataPath = this.configService.get<string>('engine.sessionDataPath', './data/sessions');- const browserArgs = this.configService.get<string>('engine.browserArgs', '--no-sandbox --disable-gpu');+ const browserArgs =+ this.configService.get<string[]>('engine.puppeteer.args')?.join(' ') || '--no-sandbox --disable-gpu';return {database: { connected: dbConnected, type: dbType, host: dbHost },@@ -289,6 +293,7 @@ export class InfraController {s3CredentialsSet: Boolean(saved.S3_ACCESS_KEY_ID && saved.S3_SECRET_ACCESS_KEY),},engine: {+ type: saved.ENGINE_TYPE || 'whatsapp-web.js',headless: saved.PUPPETEER_HEADLESS !== 'false',sessionDataPath: saved.SESSION_DATA_PATH || '',browserArgs: saved.PUPPETEER_ARGS || '',@@ -428,6 +433,15 @@ export class InfraController {// Engine. NOTE: PUPPETEER_HEADLESS / SESSION_DATA_PATH / PUPPETEER_ARGS are the names// configuration.ts reads (previously saved as ENGINE_* and silently ignored — #226).if (config.engine) {+ // Persist the selected engine so the Infrastructure tile can actually switch engines (the+ // active engine was previously only settable via the ENGINE_TYPE env, never from the UI).+ if (config.engine.type) {+ const validEngineIds = this.engineFactory.getAvailableEngines().map(e => e.id);+ if (!validEngineIds.includes(config.engine.type)) {+ throw new BadRequestException(`Unknown engine type: ${config.engine.type}`);+ }+ updates.ENGINE_TYPE = config.engine.type;+ }updates.PUPPETEER_HEADLESS = config.engine.headless !== false ? 'true' : 'false';updates.SESSION_DATA_PATH = config.engine.sessionDataPath || './data/sessions';updates.PUPPETEER_ARGS = config.engine.browserArgs || '--no-sandbox --disable-gpu';