Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
refactor(dashboard): split the Chats god component into per-section components
Yudhi Armyndharisd42f880a28c1
diff --git a/dashboard/package-lock.json b/dashboard/package-lock.jsonindex e55ca584e..a77e2a2aa 100644--- a/dashboard/package-lock.json+++ b/dashboard/package-lock.json@@ -26,6 +26,8 @@},"devDependencies": {"@eslint/js": "^10.0.1",+ "@testing-library/dom": "^10.4.1",+ "@testing-library/react": "^16.3.2","@types/node": "^26.1.1","@types/react": "^19.2.17","@types/react-dom": "^19.2.3",@@ -34,11 +36,63 @@"eslint-plugin-react-hooks": "^7.1.1","eslint-plugin-react-refresh": "^0.5.3","globals": "^17.8.0",+ "jsdom": "^29.1.1","typescript": "~6.0.3","typescript-eslint": "^8.65.0","vite": "^8.1.5"}},+ "node_modules/@asamuzakjp/css-color": {+ "version": "5.1.11",+ "resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-5.1.11.tgz",+ "integrity": "sha512-KVw6qIiCTUQhByfTd78h2yD1/00waTmm9uy/R7Ck/ctUyAPj+AEDLkQIdJW0T8+qGgj3j5bpNKK7Q3G+LedJWg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@asamuzakjp/generational-cache": "^1.0.1",+ "@csstools/css-calc": "^3.2.0",+ "@csstools/css-color-parser": "^4.1.0",+ "@csstools/css-parser-algorithms": "^4.0.0",+ "@csstools/css-tokenizer": "^4.0.0"+ },+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"+ }+ },+ "node_modules/@asamuzakjp/dom-selector": {+ "version": "7.1.1",+ "resolved": "https://registry.npmjs.org/@asamuzakjp/dom-selector/-/dom-selector-7.1.1.tgz",+ "integrity": "sha512-67RZDnYRc8H/8MLDgQCDE//zoqVFwajkepHZgmXrbwybzXOEwOWGPYGmALYl9J2DOLfFPPs6kKCqmbzV895hTQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@asamuzakjp/generational-cache": "^1.0.1",+ "@asamuzakjp/nwsapi": "^2.3.9",+ "bidi-js": "^1.0.3",+ "css-tree": "^3.2.1",+ "is-potential-custom-element-name": "^1.0.1"+ },+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"+ }+ },+ "node_modules/@asamuzakjp/generational-cache": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/@asamuzakjp/generational-cache/-/generational-cache-1.0.1.tgz",+ "integrity": "sha512-wajfB8KqzMCN2KGNFdLkReeHncd0AslUSrvHVvvYWuU8ghncRJoA50kT3zP9MVL0+9g4/67H+cdvBskj9THPzg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"+ }+ },+ "node_modules/@asamuzakjp/nwsapi": {+ "version": "2.3.9",+ "resolved": "https://registry.npmjs.org/@asamuzakjp/nwsapi/-/nwsapi-2.3.9.tgz",+ "integrity": "sha512-n8GuYSrI9bF7FFZ/SjhwevlHc8xaVlb/7HmHelnc/PZXBD2ZR49NnN9sMMuDdEGPeeRQ5d0hqlSlEpgCX3Wl0Q==",+ "dev": true,+ "license": "MIT"+ },"node_modules/@babel/code-frame": {"version": "7.29.7","resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz",@@ -288,6 +342,159 @@"node": ">=6.9.0"}},+ "node_modules/@bramus/specificity": {+ "version": "2.4.2",+ "resolved": "https://registry.npmjs.org/@bramus/specificity/-/specificity-2.4.2.tgz",+ "integrity": "sha512-ctxtJ/eA+t+6q2++vj5j7FYX3nRu311q1wfYH3xjlLOsczhlhxAg2FWNUXhpGvAw3BWo1xBcvOV6/YLc2r5FJw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "css-tree": "^3.0.0"+ },+ "bin": {+ "specificity": "bin/cli.js"+ }+ },+ "node_modules/@csstools/color-helpers": {+ "version": "6.1.0",+ "resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-6.1.0.tgz",+ "integrity": "sha512-064IFJdjTfUqnjpCVpMOdbr8FLQBhinbZj6yRv2An2E41O/pLEXqfFRWqGq/SxlE5PEUYTlvWsG2r8MswAVvkg==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/csstools"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/csstools"+ }+ ],+ "license": "MIT-0",+ "engines": {+ "node": ">=20.19.0"+ }+ },+ "node_modules/@csstools/css-calc": {+ "version": "3.3.0",+ "resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-3.3.0.tgz",+ "integrity": "sha512-c5ihYsPkdG6JCkU2zTMm4+k6r7RXuGxtWYhu5DHMIiF1FHzrfmHL5so11AoFpUv/tu61xfcmT4AmKoFfMPoqdQ==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/csstools"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/csstools"+ }+ ],+ "license": "MIT",+ "engines": {+ "node": ">=20.19.0"+ },+ "peerDependencies": {+ "@csstools/css-parser-algorithms": "^4.0.0",+ "@csstools/css-tokenizer": "^4.0.0"+ }+ },+ "node_modules/@csstools/css-color-parser": {+ "version": "4.1.10",+ "resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-4.1.10.tgz",+ "integrity": "sha512-UZhQLIUyJaaMepqehrCODwCg2KW25vFvLWBmqYFaPclYvvxzj/sG8LBOhBFCp11i9uE7t1EyS+RAoV9tztPFyw==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/csstools"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/csstools"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "@csstools/color-helpers": "^6.1.0",+ "@csstools/css-calc": "^3.3.0"+ },+ "engines": {+ "node": ">=20.19.0"+ },+ "peerDependencies": {+ "@csstools/css-parser-algorithms": "^4.0.0",+ "@csstools/css-tokenizer": "^4.0.0"+ }+ },+ "node_modules/@csstools/css-parser-algorithms": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-4.0.0.tgz",+ "integrity": "sha512-+B87qS7fIG3L5h3qwJ/IFbjoVoOe/bpOdh9hAjXbvx0o8ImEmUsGXN0inFOnk2ChCFgqkkGFQ+TpM5rbhkKe4w==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/csstools"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/csstools"+ }+ ],+ "license": "MIT",+ "engines": {+ "node": ">=20.19.0"+ },+ "peerDependencies": {+ "@csstools/css-tokenizer": "^4.0.0"+ }+ },+ "node_modules/@csstools/css-syntax-patches-for-csstree": {+ "version": "1.1.7",+ "resolved": "https://registry.npmjs.org/@csstools/css-syntax-patches-for-csstree/-/css-syntax-patches-for-csstree-1.1.7.tgz",+ "integrity": "sha512-fQ+05118eQS1cofO3aJpB5efgpBZMvIzwr/sbC8kDLVA5XLG8q1kJV5yzrUAI1f7lvhPnm8fgIjzFB8/O/5Dig==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/csstools"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/csstools"+ }+ ],+ "license": "MIT-0",+ "peerDependencies": {+ "css-tree": "^3.2.1"+ },+ "peerDependenciesMeta": {+ "css-tree": {+ "optional": true+ }+ }+ },+ "node_modules/@csstools/css-tokenizer": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-4.0.0.tgz",+ "integrity": "sha512-QxULHAm7cNu72w97JUNCBFODFaXpbDg+dP8b/oWFAZ2MTRppA3U00Y2L1HqaS4J6yBqxwa/Y3nMBaxVKbB/NsA==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/csstools"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/csstools"+ }+ ],+ "license": "MIT",+ "engines": {+ "node": ">=20.19.0"+ }+ },"node_modules/@emnapi/core": {"version": "1.11.1","resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.11.1.tgz",@@ -450,6 +657,24 @@"node": "^20.19.0 || ^22.13.0 || >=24"}},+ "node_modules/@exodus/bytes": {+ "version": "1.15.1",+ "resolved": "https://registry.npmjs.org/@exodus/bytes/-/bytes-1.15.1.tgz",+ "integrity": "sha512-S6mL0yNB/Abt9Ei4tq8gDhcczc4S3+vQ4ra7vxnAf+YHC02srtqxKKZghx2Dq6p0e66THKwR6r8N6P95wEty7Q==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"+ },+ "peerDependencies": {+ "@noble/hashes": "^1.8.0 || ^2.0.0"+ },+ "peerDependenciesMeta": {+ "@noble/hashes": {+ "optional": true+ }+ }+ },"node_modules/@humanfs/core": {"version": "0.19.1","resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.1.tgz",@@ -700,9 +925,6 @@"arm64"],"dev": true,- "libc": [- "glibc"- ],"license": "MIT","optional": true,"os": [@@ -720,9 +942,6 @@"arm64"],"dev": true,- "libc": [- "musl"- ],"license": "MIT","optional": true,"os": [@@ -740,9 +959,6 @@"ppc64"],"dev": true,- "libc": [- "glibc"- ],"license": "MIT","optional": true,"os": [@@ -760,9 +976,6 @@"s390x"],"dev": true,- "libc": [- "glibc"- ],"license": "MIT","optional": true,"os": [@@ -780,9 +993,6 @@"x64"],"dev": true,- "libc": [- "glibc"- ],"license": "MIT","optional": true,"os": [@@ -800,9 +1010,6 @@"x64"],"dev": true,- "libc": [- "musl"- ],"license": "MIT","optional": true,"os": [@@ -966,6 +1173,54 @@"url": "https://github.com/sponsors/tannerlinsley"}},+ "node_modules/@testing-library/dom": {+ "version": "10.4.1",+ "resolved": "https://registry.npmjs.org/@testing-library/dom/-/dom-10.4.1.tgz",+ "integrity": "sha512-o4PXJQidqJl82ckFaXUeoAW+XysPLauYI43Abki5hABd853iMhitooc6znOnczgbTYmEP6U6/y1ZyKAIsvMKGg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@babel/code-frame": "^7.10.4",+ "@babel/runtime": "^7.12.5",+ "@types/aria-query": "^5.0.1",+ "aria-query": "5.3.0",+ "dom-accessibility-api": "^0.5.9",+ "lz-string": "^1.5.0",+ "picocolors": "1.1.1",+ "pretty-format": "^27.0.2"+ },+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@testing-library/react": {+ "version": "16.3.2",+ "resolved": "https://registry.npmjs.org/@testing-library/react/-/react-16.3.2.tgz",+ "integrity": "sha512-XU5/SytQM+ykqMnAnvB2umaJNIOsLF3PVv//1Ew4CTcpz0/BRyy/af40qqrt7SjKpDdT1saBMc42CUok5gaw+g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.12.5"+ },+ "engines": {+ "node": ">=18"+ },+ "peerDependencies": {+ "@testing-library/dom": "^10.0.0",+ "@types/react": "^18.0.0 || ^19.0.0",+ "@types/react-dom": "^18.0.0 || ^19.0.0",+ "react": "^18.0.0 || ^19.0.0",+ "react-dom": "^18.0.0 || ^19.0.0"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },"node_modules/@tybys/wasm-util": {"version": "0.10.3","resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.3.tgz",@@ -977,6 +1232,13 @@"tslib": "^2.4.0"}},+ "node_modules/@types/aria-query": {+ "version": "5.0.4",+ "resolved": "https://registry.npmjs.org/@types/aria-query/-/aria-query-5.0.4.tgz",+ "integrity": "sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==",+ "dev": true,+ "license": "MIT"+ },"node_modules/@types/d3-array": {"version": "3.2.2","resolved": "https://registry.npmjs.org/@types/d3-array/-/d3-array-3.2.2.tgz",@@ -1406,6 +1668,39 @@"url": "https://github.com/sponsors/epoberezkin"}},+ "node_modules/ansi-regex": {+ "version": "5.0.1",+ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",+ "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/ansi-styles": {+ "version": "5.2.0",+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz",+ "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/chalk/ansi-styles?sponsor=1"+ }+ },+ "node_modules/aria-query": {+ "version": "5.3.0",+ "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.3.0.tgz",+ "integrity": "sha512-b0P0sZPKtyu8HkeRAfCq0IfURZK+SuwMjY1UXGBU27wpAiTwQAIlq56IbIO+ytk/JjS1fMR14ee5WBBfKi5J6A==",+ "dev": true,+ "license": "Apache-2.0",+ "dependencies": {+ "dequal": "^2.0.3"+ }+ },"node_modules/balanced-match": {"version": "4.0.4","resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz",@@ -1429,6 +1724,16 @@"node": ">=6.0.0"}},+ "node_modules/bidi-js": {+ "version": "1.0.3",+ "resolved": "https://registry.npmjs.org/bidi-js/-/bidi-js-1.0.3.tgz",+ "integrity": "sha512-RKshQI1R3YQ+n9YJz2QQ147P66ELpa1FQEg20Dk8oW9t2KgLbpDLLp9aGZ7y8WHSshDknG0bknqGw5/tyCs5tw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "require-from-string": "^2.0.2"+ }+ },"node_modules/brace-expansion": {"version": "5.0.8","resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.8.tgz",@@ -1541,6 +1846,20 @@"node": ">= 8"}},+ "node_modules/css-tree": {+ "version": "3.2.1",+ "resolved": "https://registry.npmjs.org/css-tree/-/css-tree-3.2.1.tgz",+ "integrity": "sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "mdn-data": "2.27.1",+ "source-map-js": "^1.2.1"+ },+ "engines": {+ "node": "^10 || ^12.20.0 || ^14.13.0 || >=15.0.0"+ }+ },"node_modules/csstype": {"version": "3.2.3","resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",@@ -1669,6 +1988,20 @@"node": ">=12"}},+ "node_modules/data-urls": {+ "version": "7.0.0",+ "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-7.0.0.tgz",+ "integrity": "sha512-23XHcCF+coGYevirZceTVD7NdJOqVn+49IHyxgszm+JIiHLoB2TkmPtsYkNWT1pvRSGkc35L6NHs0yHkN2SumA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "whatwg-mimetype": "^5.0.0",+ "whatwg-url": "^16.0.0"+ },+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"+ }+ },"node_modules/debug": {"version": "4.4.3","resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",@@ -1686,6 +2019,13 @@}}},+ "node_modules/decimal.js": {+ "version": "10.6.0",+ "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.6.0.tgz",+ "integrity": "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==",+ "dev": true,+ "license": "MIT"+ },"node_modules/decimal.js-light": {"version": "2.5.1","resolved": "https://registry.npmjs.org/decimal.js-light/-/decimal.js-light-2.5.1.tgz",@@ -1699,6 +2039,16 @@"dev": true,"license": "MIT"},+ "node_modules/dequal": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz",+ "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },"node_modules/detect-libc": {"version": "2.1.2","resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",@@ -1709,6 +2059,13 @@"node": ">=8"}},+ "node_modules/dom-accessibility-api": {+ "version": "0.5.16",+ "resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.5.16.tgz",+ "integrity": "sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==",+ "dev": true,+ "license": "MIT"+ },"node_modules/electron-to-chromium": {"version": "1.5.375","resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.375.tgz",@@ -1738,6 +2095,19 @@"node": ">=10.0.0"}},+ "node_modules/entities": {+ "version": "8.0.0",+ "resolved": "https://registry.npmjs.org/entities/-/entities-8.0.0.tgz",+ "integrity": "sha512-zwfzJecQ/Uej6tusMqwAqU/6KL2XaB2VZ2Jg54Je6ahNBGNH6Ek6g3jjNCF0fG9EWQKGZNddNjU5F1ZQn/sBnA==",+ "dev": true,+ "license": "BSD-2-Clause",+ "engines": {+ "node": ">=20.19.0"+ },+ "funding": {+ "url": "https://github.com/fb55/entities?sponsor=1"+ }+ },"node_modules/es-toolkit": {"version": "1.48.1","resolved": "https://registry.npmjs.org/es-toolkit/-/es-toolkit-1.48.1.tgz",@@ -2120,6 +2490,19 @@"hermes-estree": "0.25.1"}},+ "node_modules/html-encoding-sniffer": {+ "version": "6.0.0",+ "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-6.0.0.tgz",+ "integrity": "sha512-CV9TW3Y3f8/wT0BRFc1/KAVQ3TUHiXmaAb6VW9vtiMFf7SLoMd1PdAc4W3KFOFETBJUb90KatHqlsZMWV+R9Gg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@exodus/bytes": "^1.6.0"+ },+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"+ }+ },"node_modules/html-parse-stringify": {"version": "4.0.1","resolved": "https://registry.npmjs.org/html-parse-stringify/-/html-parse-stringify-4.0.1.tgz",@@ -2228,6 +2611,13 @@"node": ">=0.10.0"}},+ "node_modules/is-potential-custom-element-name": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz",+ "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==",+ "dev": true,+ "license": "MIT"+ },"node_modules/isexe": {"version": "2.0.0","resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",@@ -2242,6 +2632,57 @@"dev": true,"license": "MIT"},+ "node_modules/jsdom": {+ "version": "29.1.1",+ "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-29.1.1.tgz",+ "integrity": "sha512-ECi4Fi2f7BdJtUKTflYRTiaMxIB0O6zfR1fX0GXpUrf6flp8QIYn1UT20YQqdSOfk2dfkCwS8LAFoJDEppNK5Q==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@asamuzakjp/css-color": "^5.1.11",+ "@asamuzakjp/dom-selector": "^7.1.1",+ "@bramus/specificity": "^2.4.2",+ "@csstools/css-syntax-patches-for-csstree": "^1.1.3",+ "@exodus/bytes": "^1.15.0",+ "css-tree": "^3.2.1",+ "data-urls": "^7.0.0",+ "decimal.js": "^10.6.0",+ "html-encoding-sniffer": "^6.0.0",+ "is-potential-custom-element-name": "^1.0.1",+ "lru-cache": "^11.3.5",+ "parse5": "^8.0.1",+ "saxes": "^6.0.0",+ "symbol-tree": "^3.2.4",+ "tough-cookie": "^6.0.1",+ "undici": "^7.25.0",+ "w3c-xmlserializer": "^5.0.0",+ "webidl-conversions": "^8.0.1",+ "whatwg-mimetype": "^5.0.0",+ "whatwg-url": "^16.0.1",+ "xml-name-validator": "^5.0.0"+ },+ "engines": {+ "node": "^20.19.0 || ^22.13.0 || >=24.0.0"+ },+ "peerDependencies": {+ "canvas": "^3.0.0"+ },+ "peerDependenciesMeta": {+ "canvas": {+ "optional": true+ }+ }+ },+ "node_modules/jsdom/node_modules/lru-cache": {+ "version": "11.5.2",+ "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.2.tgz",+ "integrity": "sha512-4pfM1Ff0x50o0tQwb5ucw/RzNyD0/YJME6IVcStalZuMWxdt3sR3huStTtxz4PUmvZfRguvDejasvQ2kifR11g==",+ "dev": true,+ "license": "BlueOak-1.0.0",+ "engines": {+ "node": "20 || >=22"+ }+ },"node_modules/jsesc": {"version": "3.1.0","resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz",@@ -2625,6 +3066,23 @@"react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0"}},+ "node_modules/lz-string": {+ "version": "1.5.0",+ "resolved": "https://registry.npmjs.org/lz-string/-/lz-string-1.5.0.tgz",+ "integrity": "sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==",+ "dev": true,+ "license": "MIT",+ "bin": {+ "lz-string": "bin/bin.js"+ }+ },+ "node_modules/mdn-data": {+ "version": "2.27.1",+ "resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.27.1.tgz",+ "integrity": "sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==",+ "dev": true,+ "license": "CC0-1.0"+ },"node_modules/minimatch": {"version": "10.2.5","resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.5.tgz",@@ -2733,6 +3191,19 @@"url": "https://github.com/sponsors/sindresorhus"}},+ "node_modules/parse5": {+ "version": "8.0.1",+ "resolved": "https://registry.npmjs.org/parse5/-/parse5-8.0.1.tgz",+ "integrity": "sha512-z1e/HMG90obSGeidlli3hj7cbocou0/wa5HacvI3ASx34PecNjNQeaHNo5WIZpWofN9kgkqV1q5YvXe3F0FoPw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "entities": "^8.0.0"+ },+ "funding": {+ "url": "https://github.com/inikulin/parse5?sponsor=1"+ }+ },"node_modules/path-exists": {"version": "4.0.0","resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz",@@ -2812,6 +3283,28 @@"node": ">= 0.8.0"}},+ "node_modules/pretty-format": {+ "version": "27.5.1",+ "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-27.5.1.tgz",+ "integrity": "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "ansi-regex": "^5.0.1",+ "ansi-styles": "^5.0.0",+ "react-is": "^17.0.1"+ },+ "engines": {+ "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0"+ }+ },+ "node_modules/pretty-format/node_modules/react-is": {+ "version": "17.0.2",+ "resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz",+ "integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==",+ "dev": true,+ "license": "MIT"+ },"node_modules/punycode": {"version": "2.3.1","resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",@@ -2982,6 +3475,16 @@"redux": "^5.0.0"}},+ "node_modules/require-from-string": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz",+ "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },"node_modules/reselect": {"version": "5.2.0","resolved": "https://registry.npmjs.org/reselect/-/reselect-5.2.0.tgz",@@ -3022,6 +3525,19 @@"@rolldown/binding-win32-x64-msvc": "1.1.5"}},+ "node_modules/saxes": {+ "version": "6.0.0",+ "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz",+ "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==",+ "dev": true,+ "license": "ISC",+ "dependencies": {+ "xmlchars": "^2.2.0"+ },+ "engines": {+ "node": ">=v12.22.7"+ }+ },"node_modules/scheduler": {"version": "0.27.0","resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.27.0.tgz",@@ -3105,6 +3621,13 @@"node": ">=0.10.0"}},+ "node_modules/symbol-tree": {+ "version": "3.2.4",+ "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz",+ "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==",+ "dev": true,+ "license": "MIT"+ },"node_modules/tiny-invariant": {"version": "1.3.3","resolved": "https://registry.npmjs.org/tiny-invariant/-/tiny-invariant-1.3.3.tgz",@@ -3128,6 +3651,52 @@"url": "https://github.com/sponsors/SuperchupuDev"}},+ "node_modules/tldts": {+ "version": "7.4.10",+ "resolved": "https://registry.npmjs.org/tldts/-/tldts-7.4.10.tgz",+ "integrity": "sha512-GgouD1B+sWwvkaEq8vXC15DjQitxbvs12oIXELpconwm+Tg3zfcEv4jgzq3vtKverDXsg3VI8aRgNL2Nra0Iog==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "tldts-core": "^7.4.10"+ },+ "bin": {+ "tldts": "bin/cli.js"+ }+ },+ "node_modules/tldts-core": {+ "version": "7.4.10",+ "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-7.4.10.tgz",+ "integrity": "sha512-KnQjp53ZekKgm/r3l+u8kJGGzYgrWdP8+Mql7a4vijh2WE0IrZWspQj/TpTxDho/YxO+AnOZnIjQcCD+q6iJsw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/tough-cookie": {+ "version": "6.0.2",+ "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-6.0.2.tgz",+ "integrity": "sha512-exgYmnmL/sJpR3upZfXG5PoatXQii55xAiXGXzY+sROLZ/Y+SLcp9PgJNI9Vz37HpQ74WvDcLT8eqm+kV3FzrA==",+ "dev": true,+ "license": "BSD-3-Clause",+ "dependencies": {+ "tldts": "^7.0.5"+ },+ "engines": {+ "node": ">=16"+ }+ },+ "node_modules/tr46": {+ "version": "6.0.0",+ "resolved": "https://registry.npmjs.org/tr46/-/tr46-6.0.0.tgz",+ "integrity": "sha512-bLVMLPtstlZ4iMQHpFHTR7GAGj2jxi8Dg0s2h2MafAE4uSWF98FC/3MomU51iQAMf8/qDUbKWf5GxuvvVcXEhw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "punycode": "^2.3.1"+ },+ "engines": {+ "node": ">=20"+ }+ },"node_modules/ts-api-utils": {"version": "2.5.0","resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.5.0.tgz",@@ -3200,6 +3769,16 @@"typescript": ">=4.8.4 <6.1.0"}},+ "node_modules/undici": {+ "version": "7.29.0",+ "resolved": "https://registry.npmjs.org/undici/-/undici-7.29.0.tgz",+ "integrity": "sha512-IDxfleLmmbSskfWSUATiN1nfn2rDuvnMOqb5CWR92iIfojA0Ud+ulOAAEQ57LPr9rWmsreUyf5lwyao+7GNNVw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=20.18.1"+ }+ },"node_modules/undici-types": {"version": "8.3.0","resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.3.0.tgz",@@ -3357,6 +3936,54 @@}}},+ "node_modules/w3c-xmlserializer": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz",+ "integrity": "sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "xml-name-validator": "^5.0.0"+ },+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/webidl-conversions": {+ "version": "8.0.1",+ "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-8.0.1.tgz",+ "integrity": "sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ==",+ "dev": true,+ "license": "BSD-2-Clause",+ "engines": {+ "node": ">=20"+ }+ },+ "node_modules/whatwg-mimetype": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-5.0.0.tgz",+ "integrity": "sha512-sXcNcHOC51uPGF0P/D4NVtrkjSU2fNsm9iog4ZvZJsL3rjoDAzXZhkm2MWt1y+PUdggKAYVoMAIYcs78wJ51Cw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=20"+ }+ },+ "node_modules/whatwg-url": {+ "version": "16.0.1",+ "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-16.0.1.tgz",+ "integrity": "sha512-1to4zXBxmXHV3IiSSEInrreIlu02vUOvrhxJJH5vcxYTBDAx51cqZiKdyTxlecdKNSjj8EcxGBxNf6Vg+945gw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@exodus/bytes": "^1.11.0",+ "tr46": "^6.0.0",+ "webidl-conversions": "^8.0.1"+ },+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"+ }+ },"node_modules/which": {"version": "2.0.2","resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",@@ -3404,6 +4031,23 @@}}},+ "node_modules/xml-name-validator": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz",+ "integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==",+ "dev": true,+ "license": "Apache-2.0",+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/xmlchars": {+ "version": "2.2.0",+ "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz",+ "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==",+ "dev": true,+ "license": "MIT"+ },"node_modules/xmlhttprequest-ssl": {"version": "2.1.2","resolved": "https://registry.npmjs.org/xmlhttprequest-ssl/-/xmlhttprequest-ssl-2.1.2.tgz",diff --git a/dashboard/package.json b/dashboard/package.jsonindex 504b89011..af2083e43 100644--- a/dashboard/package.json+++ b/dashboard/package.json@@ -32,6 +32,8 @@},"devDependencies": {"@eslint/js": "^10.0.1",+ "@testing-library/dom": "^10.4.1",+ "@testing-library/react": "^16.3.2","@types/node": "^26.1.1","@types/react": "^19.2.17","@types/react-dom": "^19.2.3",@@ -40,6 +42,7 @@"eslint-plugin-react-hooks": "^7.1.1","eslint-plugin-react-refresh": "^0.5.3","globals": "^17.8.0",+ "jsdom": "^29.1.1","typescript": "~6.0.3","typescript-eslint": "^8.65.0","vite": "^8.1.5"@@ -47,4 +50,4 @@"overrides": {"brace-expansion": "^5.0.8"}-}\ No newline at end of file+}diff --git a/dashboard/src/components/chats/ChatAvatar.tsx b/dashboard/src/components/chats/ChatAvatar.tsxnew file mode 100644index 000000000..b0741bfd4--- /dev/null+++ b/dashboard/src/components/chats/ChatAvatar.tsx@@ -0,0 +1,22 @@+import type { ChatKind } from '../../services/api';+import KindIcon from './KindIcon';++// Chat list avatar. Renders from the sidebar's ONE batch request (useProfilePictures) — firing a+// query per row burst the per-IP throttle into 429s. The generic icon stays while the batch loads+// or when the contact hides their picture.+function ChatAvatar({ pictureUrl, kind }: { pictureUrl?: string | null; kind: ChatKind }) {+ if (pictureUrl) {+ return (+ <div className="chat-avatar">+ <img src={pictureUrl} alt="" />+ </div>+ );+ }+ return (+ <div className="chat-avatar">+ <KindIcon kind={kind} />+ </div>+ );+}++export default ChatAvatar;diff --git a/dashboard/src/components/chats/ChatComposer.tsx b/dashboard/src/components/chats/ChatComposer.tsxnew file mode 100644index 000000000..b81f210c9--- /dev/null+++ b/dashboard/src/components/chats/ChatComposer.tsx@@ -0,0 +1,370 @@+import { useEffect, useRef, useState, type Dispatch, type SetStateAction } from 'react';+import { useQueryClient } from '@tanstack/react-query';+import { useTranslation } from 'react-i18next';+import { Loader2, Paperclip, Send, Smile, X } from 'lucide-react';+import { messageApi, type Chat, type MessageType } from '../../services/api';+import { mergeOrAppend, type ChatMessageView } from '../../utils/chatMessages';+import { promoteChatWithSnippet } from '../../utils/chatList';+import { messagesQueryKey, useChatMessagesActions } from '../../hooks/useChatMessages';+import { useRole } from '../../hooks/useRole';+import { useToast } from '../Toast';+import type { ScrollDirection } from '../../utils/scrollDecision';++// Map an attachment MIME type to the neutral MessageType for the optimistic outgoing bubble, so the+// placeholder matches what the backend will persist (e.g. a PDF is `document`, not `application`).+const messageTypeFromMime = (mimetype: string): MessageType => {+ if (mimetype.startsWith('image/')) return 'image';+ if (mimetype.startsWith('video/')) return 'video';+ if (mimetype.startsWith('audio/')) return 'audio';+ return 'document';+};++interface ChatComposerProps {+ selectedSessionId: string;+ activeChat: Chat;+ replyingTo: ChatMessageView | null;+ setReplyingTo: Dispatch<SetStateAction<ChatMessageView | null>>;+ onMessageAppended: (direction: ScrollDirection) => void;+ setChats: Dispatch<SetStateAction<Chat[]>>;+}++// The composer half of the chat room: attachment preview, emoji panel, reply banner, and the input+// bar with the whole optimistic-send flow. `replyingTo` is shared with the thread (its reply action+// sets it), so it lives in the page and is handed down; everything else is local.+function ChatComposer({+ selectedSessionId,+ activeChat,+ replyingTo,+ setReplyingTo,+ onMessageAppended,+ setChats,+}: ChatComposerProps) {+ const { t } = useTranslation();+ const { canWrite } = useRole();+ const { error: showErrorToast } = useToast();+ const { appendMessage, updateMessage } = useChatMessagesActions();+ const queryClient = useQueryClient();++ const [messageInput, setMessageInput] = useState<string>('');+ const [sending, setSending] = useState<boolean>(false);++ // File attachments+ const [attachment, setAttachment] = useState<{+ file: File;+ base64: string;+ mimetype: string;+ filename: string;+ } | null>(null);+ const [previewUrl, setPreviewUrl] = useState<string | null>(null);+ const [showEmojiPicker, setShowEmojiPicker] = useState<boolean>(false);+ // Monotonic token invalidating an in-flight attachment FileReader: picking a second file (or+ // removing the attachment) before `onload` fires must win over the late-arriving bytes —+ // otherwise the slower read overwrites the newer pick. Same pattern as composeImageReadSeq.+ const attachmentReadSeq = useRef(0);++ // Unmounting with a read still in flight: invalidate the reader so its late+ // onload handler drops the bytes instead of setting state on a dead component.+ useEffect(() => {+ return () => {+ attachmentReadSeq.current += 1;+ };+ }, []);++ // References+ const fileInputRef = useRef<HTMLInputElement | null>(null);++ // Popular emojis+ const popularEmojis = [+ '😀',+ '😂',+ '👍',+ '❤️',+ '🔥',+ '👏',+ '🙏',+ '🎉',+ '💡',+ '🤔',+ '😅',+ '😍',+ '😊',+ '😭',+ '😎',+ '😜',+ '🚀',+ '✨',+ ];++ // Revoke the object URL created for an image-attachment preview once it is replaced, cleared, or+ // the component unmounts. The cleanup runs with the previous value on every change, so this single+ // effect covers all paths (new file, remove, session switch) — otherwise each preview leaks a+ // blob held for the lifetime of the document.+ useEffect(() => {+ if (!previewUrl) return;+ return () => URL.revokeObjectURL(previewUrl);+ }, [previewUrl]);++ // 5. Handle file selection & base64 conversion+ const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {+ const file = e.target.files?.[0];+ if (!file) return;++ if (file.type.startsWith('image/')) {+ setPreviewUrl(URL.createObjectURL(file));+ } else {+ setPreviewUrl(null);+ }++ const myRead = ++attachmentReadSeq.current;+ const reader = new FileReader();+ reader.onload = event => {+ // A newer pick, a removal, or an unmount since the read started supersedes these bytes.+ if (attachmentReadSeq.current !== myRead) return;+ const dataUrl = event.target?.result as string;+ const base64Data = dataUrl.split(',')[1];+ setAttachment({ file, base64: base64Data, mimetype: file.type, filename: file.name });+ };+ reader.readAsDataURL(file);+ };++ const handleRemoveAttachment = () => {+ attachmentReadSeq.current += 1; // an in-flight read must not resurrect the removed attachment+ setAttachment(null);+ setPreviewUrl(null);+ if (fileInputRef.current) fileInputRef.current.value = '';+ };++ const triggerFileSelect = () => {+ fileInputRef.current?.click();+ };++ const handleEmojiClick = (emoji: string) => {+ setMessageInput(prev => prev + emoji);+ setShowEmojiPicker(false);+ };++ // 7. Handle sending a message / media+ const handleSend = async (e?: React.FormEvent) => {+ if (e) e.preventDefault();+ if (!selectedSessionId || !activeChat || sending) return;++ const textToSend = messageInput.trim();+ if (!textToSend && !attachment) return;++ setMessageInput('');+ setSending(true);++ const tempId = `temp_${Date.now()}`;+ const tempMessage: ChatMessageView = {+ id: tempId,+ chatId: activeChat.id,+ from: 'me',+ to: activeChat.id,+ body: attachment+ ? attachment.mimetype.startsWith('image/') ||+ attachment.mimetype.startsWith('video/') ||+ attachment.mimetype.startsWith('audio/')+ ? textToSend+ : attachment.filename+ : textToSend,+ type: attachment ? messageTypeFromMime(attachment.mimetype) : 'text',+ direction: 'outgoing',+ status: 'pending',+ createdAt: new Date().toISOString(),+ metadata: attachment+ ? {+ media: {+ mimetype: attachment.mimetype,+ filename: attachment.filename,+ data: attachment.base64,+ },+ }+ : replyingTo+ ? {+ quotedMessage: {+ id: replyingTo.waMessageId || replyingTo.id,+ body: replyingTo.type !== 'text' ? `[${replyingTo.type}]` : replyingTo.body,+ },+ }+ : undefined,+ };++ appendMessage(selectedSessionId, activeChat.id, tempMessage);+ onMessageAppended('outgoing');++ const currentAttachment = attachment;+ const currentReplyingTo = replyingTo;+ handleRemoveAttachment();+ setReplyingTo(null);++ try {+ let result;++ if (currentAttachment) {+ let mediaType: 'image' | 'video' | 'audio' | 'document' = 'document';+ const mime = currentAttachment.mimetype;+ if (mime.startsWith('image/')) mediaType = 'image';+ else if (mime.startsWith('video/')) mediaType = 'video';+ else if (mime.startsWith('audio/')) mediaType = 'audio';++ result = await messageApi.sendMedia(selectedSessionId, activeChat.id, mediaType, {+ base64: currentAttachment.base64,+ mimetype: currentAttachment.mimetype,+ filename: currentAttachment.filename,+ caption: mediaType !== 'audio' ? textToSend : undefined,+ });+ } else if (currentReplyingTo) {+ result = await messageApi.reply(selectedSessionId, {+ chatId: activeChat.id,+ quotedMessageId: currentReplyingTo.waMessageId || currentReplyingTo.id,+ text: textToSend,+ });+ } else {+ result = await messageApi.sendText(selectedSessionId, activeChat.id, textToSend);+ }++ // Race guard: the realtime `message.sent` echo can arrive before this response and already+ // append the message by its real WA id (the dedup at receive time misses because the+ // optimistic placeholder still carries the temp id). If so, fold the placeholder INTO the+ // echo's row via mergeOrAppend instead of just dropping it — the echo carries no media+ // payload (engine parity marker), so dropping the placeholder would erase the attachment's+ // base64 and leave a bare "📎 Media" bubble until the next refetch.+ const sendKey = messagesQueryKey(selectedSessionId, activeChat.id);+ queryClient.setQueryData<ChatMessageView[]>(sendKey, (prev = []) => {+ const reconciled: ChatMessageView = {+ ...tempMessage,+ id: result.messageId,+ waMessageId: result.messageId,+ status: 'sent',+ };+ const echoAlreadyAdded = prev.some(m => m.id === result.messageId || m.waMessageId === result.messageId);+ if (echoAlreadyAdded) {+ return mergeOrAppend(+ prev.filter(m => m.id !== tempId),+ reconciled,+ );+ }+ return prev.map(m => (m.id === tempId ? reconciled : m));+ });++ // Update sidebar chat list (move active chat to the top with the new snippet)+ const snippet = currentAttachment ? `[${currentAttachment.mimetype.split('/')[0]}]` : textToSend;+ const sentAt = Math.floor(Date.now() / 1000);+ setChats(prevChats => promoteChatWithSnippet(prevChats, activeChat.id, snippet, sentAt));+ } catch (err) {+ showErrorToast(t('chats.errors.send'), err instanceof Error ? err.message : undefined);+ updateMessage(selectedSessionId, activeChat.id, tempId, { status: 'failed' });+ } finally {+ setSending(false);+ }+ };++ return (+ <>+ {/* Attachment preview banner */}+ {attachment && (+ <div className="attachment-preview-banner">+ {previewUrl ? (+ <img src={previewUrl} alt={attachment.filename} className="preview-thumbnail" />+ ) : (+ <div className="preview-file-icon">📎</div>+ )}+ <div className="preview-file-info">+ <span className="preview-filename">{attachment.filename}</span>+ <span className="preview-filesize">({(attachment.file.size / 1024).toFixed(1)} KB)</span>+ </div>+ <button className="btn-remove-attachment" onClick={handleRemoveAttachment}>+ <X size={18} />+ </button>+ </div>+ )}++ {/* Popular emojis panel */}+ {showEmojiPicker && (+ <div className="chats-emoji-picker">+ <div className="emoji-grid">+ {popularEmojis.map(emoji => (+ <button key={emoji} type="button" className="emoji-btn" onClick={() => handleEmojiClick(emoji)}>+ {emoji}+ </button>+ ))}+ </div>+ </div>+ )}++ {/* Replying preview banner */}+ {replyingTo && (+ <div className="replying-preview-banner">+ <div className="replying-preview-content">+ <div className="replying-to-title">+ {t('chats.replyingTo', {+ name:+ replyingTo.direction === 'outgoing'+ ? t('chats.you')+ : activeChat.name || activeChat.id.split('@')[0],+ })}+ </div>+ <div className="replying-to-body">+ {replyingTo.type !== 'text' ? `[${replyingTo.type}]` : replyingTo.body}+ </div>+ </div>+ <button className="btn-close-reply" onClick={() => setReplyingTo(null)}>+ <X size={18} />+ </button>+ </div>+ )}++ {/* Message input bar */}+ <footer className="room-input-footer">+ <form onSubmit={handleSend} className="input-form">+ <input type="file" ref={fileInputRef} onChange={handleFileChange} style={{ display: 'none' }} />++ <button+ type="button"+ onClick={triggerFileSelect}+ disabled={!canWrite || sending}+ className="btn-input-accessory"+ title={t('chats.attachTitle')}+ >+ <Paperclip size={20} />+ </button>++ <button+ type="button"+ onClick={() => setShowEmojiPicker(!showEmojiPicker)}+ disabled={!canWrite || sending}+ className={`btn-input-accessory ${showEmojiPicker ? 'active' : ''}`}+ title={t('chats.emojiTitle')}+ >+ <Smile size={20} />+ </button>++ <input+ type="text"+ placeholder={+ canWrite+ ? attachment+ ? t('chats.captionPlaceholder')+ : t('chats.messagePlaceholder')+ : t('chats.noPermission')+ }+ value={messageInput}+ onChange={e => setMessageInput(e.target.value)}+ disabled={!canWrite || sending}+ className="message-text-input"+ />+ <button+ type="submit"+ disabled={!canWrite || (!messageInput.trim() && !attachment) || sending}+ className="btn-send-message"+ aria-label={t('chats.send')}+ >+ {sending ? <Loader2 className="animate-spin" size={24} /> : <Send size={28} strokeWidth={2.5} />}+ </button>+ </form>+ </footer>+ </>+ );+}++export default ChatComposer;diff --git a/dashboard/src/components/chats/ChatSidebar.tsx b/dashboard/src/components/chats/ChatSidebar.tsxnew file mode 100644index 000000000..070284780--- /dev/null+++ b/dashboard/src/components/chats/ChatSidebar.tsx@@ -0,0 +1,282 @@+import { useTranslation } from 'react-i18next';+import { AlertCircle, CircleDashed, Loader2, Megaphone, Plus, Search } from 'lucide-react';+import type { UseQueryResult } from '@tanstack/react-query';+import type { Channel, Chat, ContactStatusGroup, Session } from '../../services/api';+import ChatAvatar from './ChatAvatar';++export type ChatsTab = 'chats' | 'channels' | 'status';++interface ChatSidebarProps {+ sessions: Session[];+ selectedSessionId: string;+ onSelectSession: (sessionId: string) => void;+ activeTab: ChatsTab;+ onSwitchTab: (tab: ChatsTab) => void;+ searchQuery: string;+ onSearchQueryChange: (query: string) => void;+ onComposeStatus: () => void;+ formatChatTime: (timestamp?: number) => string;+ chatsTab: {+ loading: boolean;+ chats: Chat[];+ activeChatId?: string;+ pictures?: Record<string, string | null>;+ onSelectChat: (chat: Chat) => void;+ };+ channelsTab: {+ engineLoading: boolean;+ supported: boolean;+ query: UseQueryResult<Channel[], Error>;+ channels: Channel[];+ activeChannelId?: string;+ onSelectChannel: (channel: Channel) => void;+ };+ statusTab: {+ loading: boolean;+ error: boolean;+ groups: ContactStatusGroup[];+ activeContactId: string | null;+ onSelectContact: (contactId: string) => void;+ };+}++// LEFT SIDEBAR: session selector, Chats/Channels/Status tab bar, search, and the per-tab lists.+// The page owns all queries/state; this component renders them and reports interactions up.+function ChatSidebar({+ sessions,+ selectedSessionId,+ onSelectSession,+ activeTab,+ onSwitchTab,+ searchQuery,+ onSearchQueryChange,+ onComposeStatus,+ formatChatTime,+ chatsTab,+ channelsTab,+ statusTab,+}: ChatSidebarProps) {+ const { t } = useTranslation();++ const formatLastMessageSnippet = (chat: Chat) => chat.lastMessage || '';++ // Shared row markup for the Chats and Status lists — a plain function (not memoized) since it+ // closes over render-scoped props (chatsTab.activeChatId, chatsTab.pictures) that already+ // change every render.+ const renderChatRow = (chat: Chat) => {+ const isActive = chatsTab.activeChatId === chat.id;+ return (+ <div key={chat.id} className={`chat-item-card ${isActive ? 'active' : ''}`} onClick={() => chatsTab.onSelectChat(chat)}>+ <ChatAvatar pictureUrl={chatsTab.pictures?.[chat.id]} kind={chat.kind} />++ <div className="chat-item-info">+ <div className="chat-item-top">+ <span className="chat-item-name" title={chat.name || chat.id}>+ {chat.name || chat.id.split('@')[0]}+ </span>+ {chat.kind !== 'individual' && chat.kind !== 'unknown' && (+ <span className={`chat-kind-badge kind-${chat.kind}`}>{t(`chats.kind.${chat.kind}`)}</span>+ )}+ {/* Ternary, not `&&`: a chat with no messages carries timestamp 0, and React+ renders the number 0 as text — so `0 && <span/>` painted a literal "0"+ where the time belongs, on every such row. */}+ {chat.timestamp ? <span className="chat-item-time">{formatChatTime(chat.timestamp)}</span> : null}+ </div>+ <div className="chat-item-bottom">+ <span className="chat-item-snippet" title={formatLastMessageSnippet(chat)}>+ {formatLastMessageSnippet(chat) || <span className="no-message">{t('chats.noMessageYet')}</span>}+ </span>+ {chat.unreadCount > 0 && (+ <span+ className="chat-unread-badge"+ title={t('chats.unreadBadge', { count: chat.unreadCount })}+ aria-label={t('chats.unreadBadge', { count: chat.unreadCount })}+ >+ {chat.unreadCount > 99 ? '99+' : chat.unreadCount}+ </span>+ )}+ </div>+ </div>+ </div>+ );+ };++ return (+ <aside className="chats-sidebar">+ <div className="sidebar-header-box">+ {/* Session selector */}+ <div className="session-select-group">+ <label className="form-label">{t('chats.sessionLabel')}</label>+ <select+ value={selectedSessionId}+ onChange={e => onSelectSession(e.target.value)}+ className="session-selector"+ >+ {sessions.map(s => (+ <option key={s.id} value={s.id}>+ {s.name} ({s.phone || t('chats.noPhone')})+ </option>+ ))}+ </select>+ </div>++ {/* Chats / Channels / Status tabs */}+ <div className="chats-tabs" role="tablist">+ {(['chats', 'channels', 'status'] as const).map(tab => (+ <button+ key={tab}+ type="button"+ role="tab"+ aria-selected={activeTab === tab}+ className={`chats-tab ${activeTab === tab ? 'active' : ''}`}+ onClick={() => onSwitchTab(tab)}+ >+ {t(`chats.tab.${tab}`)}+ </button>+ ))}+ </div>++ {/* Search bar */}+ <div className="chat-search-input">+ <Search size={18} />+ <input+ type="text"+ placeholder={t('chats.searchPlaceholder')}+ value={searchQuery}+ onChange={e => onSearchQueryChange(e.target.value)}+ />+ </div>++ {/* Compose a new status — only meaningful on the Status tab. */}+ {activeTab === 'status' && (+ <button type="button" className="btn-primary status-compose-trigger" onClick={onComposeStatus}>+ <Plus size={16} />+ {t('chats.status.compose')}+ </button>+ )}+ </div>++ {/* Chat list */}+ {activeTab === 'chats' && (+ <div className="chats-list">+ {chatsTab.loading ? (+ <div className="chats-list-loading">+ <Loader2 className="animate-spin" size={24} />+ <span>{t('chats.loadingChats')}</span>+ </div>+ ) : chatsTab.chats.length === 0 ? (+ <div className="chats-list-empty">+ <span>{t('chats.empty')}</span>+ </div>+ ) : (+ chatsTab.chats.map(renderChatRow)+ )}+ </div>+ )}++ {/* Channels list — wwjs-only (newsletter/channel API isn't implemented on Baileys, which+ throws 501 for both listing and reading). channelsQuery is gated off entirely on that+ engine, so the branch order below never depends on a request having actually run. */}+ {activeTab === 'channels' && (+ <div className="chats-list">+ {channelsTab.engineLoading ? (+ <div className="chats-list-loading">+ <Loader2 className="animate-spin" size={24} />+ </div>+ ) : !channelsTab.supported ? (+ <div className="chats-list-empty">+ <span>{t('chats.channels.notSupported')}</span>+ </div>+ ) : channelsTab.query.isLoading ? (+ <div className="chats-list-loading">+ <Loader2 className="animate-spin" size={24} />+ </div>+ ) : channelsTab.query.error ? (+ <div className="chats-list-empty">+ <AlertCircle size={24} className="text-warn" />+ <span>{t('chats.channels.notReady')}</span>+ </div>+ ) : (channelsTab.query.data?.length ?? 0) === 0 ? (+ <div className="chats-list-empty">+ <span>{t('chats.channels.empty')}</span>+ </div>+ ) : (+ channelsTab.channels.map(ch => (+ <div+ key={ch.id}+ className={`chat-item-card ${channelsTab.activeChannelId === ch.id ? 'active' : ''}`}+ onClick={() => channelsTab.onSelectChannel(ch)}+ >+ <div className="chat-avatar">+ <Megaphone size={20} />+ </div>+ <div className="chat-item-info">+ <div className="chat-item-top">+ <span className="chat-item-name">{ch.name}</span>+ </div>+ {ch.subscriberCount != null && (+ <div className="chat-item-bottom">+ <span className="chat-item-snippet">+ {t('chats.channels.subscribers', { count: ch.subscriberCount })}+ </span>+ </div>+ )}+ </div>+ </div>+ ))+ )}+ </div>+ )}++ {/* Status list — per-contact status groups read from the 24h store. Not engine-gated:+ both engines now have status content. */}+ {activeTab === 'status' && (+ <div className="chats-list">+ {statusTab.loading ? (+ <div className="chats-list-loading">+ <Loader2 className="animate-spin" size={24} />+ </div>+ ) : statusTab.error ? (+ <div className="chats-list-empty">+ <AlertCircle size={24} className="text-warn" />+ <span>{t('chats.status.loadError')}</span>+ </div>+ ) : statusTab.groups.length === 0 ? (+ <div className="chats-list-empty">+ <span>{t('chats.status.empty')}</span>+ </div>+ ) : (+ statusTab.groups.map(group => (+ <div+ key={group.contact.id}+ className={`chat-item-card ${statusTab.activeContactId === group.contact.id ? 'active' : ''}`}+ onClick={() => statusTab.onSelectContact(group.contact.id)}+ >+ <div className="chat-avatar">+ <CircleDashed size={20} />+ </div>+ <div className="chat-item-info">+ <div className="chat-item-top">+ <span className="chat-item-name">+ {group.contact.name ?? group.contact.pushName ?? group.contact.id}+ </span>+ <span className="chat-item-time">+ {formatChatTime(Math.floor(new Date(group.latest).getTime() / 1000))}+ </span>+ </div>+ <div className="chat-item-bottom">+ <span className="chat-item-snippet">+ {t('chats.status.itemCount', { count: group.items.length })}+ </span>+ </div>+ </div>+ </div>+ ))+ )}+ </div>+ )}+ </aside>+ );+}++export default ChatSidebar;diff --git a/dashboard/src/components/chats/ChatThread.tsx b/dashboard/src/components/chats/ChatThread.tsxnew file mode 100644index 000000000..f830a3669--- /dev/null+++ b/dashboard/src/components/chats/ChatThread.tsx@@ -0,0 +1,356 @@+import { useCallback, useEffect, useState, type RefObject } from 'react';+import { useTranslation } from 'react-i18next';+import { ChevronDown, CornerUpLeft, Loader2, MessageSquare, Smile, Trash2 } from 'lucide-react';+import type { Chat } from '../../services/api';+import { getMediaSrc, senderKey, type ChatMessageView } from '../../utils/chatMessages';+import MessageBody from './MessageBody';++// Stable per-sender colour for group message labels, like WhatsApp gives each participant a colour.+// Hashed from the sender's name so the same person keeps the same colour across a session. The palette+// is tuned to stay legible on both the light and dark incoming-bubble backgrounds.+const SENDER_COLORS = ['#d1416f', '#7c5cff', '#0a86c4', '#1a8f5c', '#c26a00', '#c0392b', '#0e7c86', '#8e44ad'];+const senderColor = (name: string): string => {+ let hash = 0;+ for (let i = 0; i < name.length; i++) hash = (hash * 31 + name.charCodeAt(i)) | 0;+ return SENDER_COLORS[Math.abs(hash) % SENDER_COLORS.length];+};++interface ChatThreadProps {+ activeChat: Chat;+ messages: ChatMessageView[];+ loadingMessages: boolean;+ messagesError: boolean;+ messagesContainerRef: RefObject<HTMLDivElement | null>;+ onMediaLoad: () => void;+ onOpenImage: (messageId: string) => void;+ onReply: (message: ChatMessageView) => void;+ onReact: (message: ChatMessageView, emoji: string) => void;+ onDelete: (message: ChatMessageView) => void;+}++// The messages area of the active chat room: the bubble list (media, quotes, reactions, hover+// actions) plus the floating scroll-to-bottom button. The page owns the message query and the+// scroll-position hook (its containerRef is handed down); reply/react/delete/lightbox intents go+// back up as callbacks.+function ChatThread({+ activeChat,+ messages,+ loadingMessages,+ messagesError,+ messagesContainerRef,+ onMediaLoad,+ onOpenImage,+ onReply,+ onReact,+ onDelete,+}: ChatThreadProps) {+ const { t } = useTranslation();++ // Scroll-to-bottom button visibility. The main scroll-position memory is owned by+ // useChatScrollPosition, which doesn't expose its pin state (intentionally — that would re-render+ // the whole room on every scroll). This small listener tracks only the boolean "user is far from+ // the bottom" so we can float the jump button.+ const [showJumpToBottom, setShowJumpToBottom] = useState(false);+ useEffect(() => {+ const el = messagesContainerRef.current;+ if (!el) return undefined;+ const onScroll = () => {+ // 120px gap = a couple of message bubbles before counting as "scrolled up".+ setShowJumpToBottom(el.scrollHeight - el.scrollTop - el.clientHeight > 120);+ };+ onScroll(); // sync initial position (e.g. saved restore landed above the bottom)+ el.addEventListener('scroll', onScroll, { passive: true });+ return () => el.removeEventListener('scroll', onScroll);+ });++ const handleJumpToBottom = useCallback(() => {+ const el = messagesContainerRef.current;+ if (!el) return;+ el.scrollTo({ top: el.scrollHeight, behavior: 'smooth' });+ }, [messagesContainerRef]);++ // Reset the jump button whenever the active chat changes: the new chat's content is restored by+ // useChatScrollPosition and our listener will resync on its first scroll tick.+ useEffect(() => {+ setShowJumpToBottom(false);+ }, [activeChat?.id]);++ // Helper formats+ const formatTime = (timestamp?: number) => {+ if (!timestamp) return '';+ return new Date(timestamp * 1000).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });+ };++ // position:relative so the scroll-to-bottom button can float inside.+ return (+ <div className="room-messages" ref={messagesContainerRef}>+ {/* Floating scroll-to-bottom button. Hidden while loading (no height to measure yet)+ and when the user is already at/near the bottom. */}+ {showJumpToBottom && !loadingMessages && (+ <button+ type="button"+ className="scroll-to-bottom-btn"+ onClick={handleJumpToBottom}+ aria-label={t('chats.scrollToBottom')}+ title={t('chats.scrollToBottom')}+ >+ <ChevronDown size={22} />+ </button>+ )}+ {loadingMessages ? (+ <div className="messages-loading">+ <Loader2 className="animate-spin" size={32} />+ <span>{t('chats.loadingMessages')}</span>+ </div>+ ) : messagesError ? (+ <div className="messages-empty">+ <MessageSquare size={32} />+ <span>{t('chats.loadMessagesError')}</span>+ </div>+ ) : messages.length === 0 ? (+ <div className="messages-empty">+ <MessageSquare size={32} />+ <span>{t('chats.noMessagesInChat')}</span>+ </div>+ ) : (+ messages.map((msg, index) => {+ const isMe = msg.direction === 'outgoing';+ const formattedTime = formatTime(+ msg.timestamp || Math.floor(new Date(msg.createdAt).getTime() / 1000),+ );++ // Label who posted, WhatsApp-style: only in groups, only on incoming messages,+ // and only on the first of a consecutive run from the same sender (so a burst+ // from one person isn't repeated on every bubble).+ const prev = messages[index - 1];+ const showSender = Boolean(+ activeChat?.isGroup &&+ !isMe &&+ msg.chatName &&+ // Key the run on the stable sender id (participant JID), not the display+ // name — two participants who share a pushName must still start a new run.+ (!prev || prev.direction === 'outgoing' || senderKey(prev) !== senderKey(msg)),+ );++ const isMediaMessage = msg.type !== 'text';+ const mediaInfo = msg.metadata?.media;++ const renderMedia = () => {+ if (msg.type === 'revoked') return null;+ // location/call have no downloadable media payload — render them before the+ // mediaInfo gate. The raw body (a base64 thumbnail / empty token) is suppressed below.+ if (msg.type === 'location') {+ // WhatsApp location messages carry a base64 JPEG map-preview thumbnail in `body`.+ const thumb = msg.body && msg.body.length > 100 ? `data:image/jpeg;base64,${msg.body}` : '';+ return (+ <div className="message-location">+ {thumb && (+ <img+ src={thumb}+ alt=""+ onLoad={onMediaLoad}+ style={{ maxWidth: 220, borderRadius: 8, display: 'block', marginBottom: 4 }}+ />+ )}+ <span className="message-media-omitted">📍 {t('chats.media.location')}</span>+ </div>+ );+ }+ if (msg.type === 'call') {+ const call = msg.metadata?.call;+ const callKey = call?.video+ ? call.missed+ ? 'callVideoMissed'+ : 'callVideo'+ : call?.missed+ ? 'callMissed'+ : 'call';+ return (+ <div className="message-media-omitted">+ {`${call?.video ? '📹' : '📞'} ${t(`chats.media.${callKey}`)}`}+ </div>+ );+ }+ if (!mediaInfo) return null;+ if (mediaInfo.omitted) {+ return <div className="message-media-omitted">📎 {t('chats.media.omitted')}</div>;+ }+ const mediaSrc = getMediaSrc(mediaInfo);+ if (!mediaSrc) return null;++ switch (msg.type) {+ case 'image':+ case 'sticker':+ return (+ <div className="message-media-image">+ <img+ src={mediaSrc}+ alt={mediaInfo.filename || t('chats.media.image')}+ className="chat-image-media"+ onLoad={onMediaLoad}+ onClick={() => onOpenImage(msg.id)}+ />+ </div>+ );+ case 'video':+ return (+ <div className="message-media-video">+ <video+ src={mediaSrc}+ controls+ className="chat-video-media"+ onLoadedData={onMediaLoad}+ />+ </div>+ );+ case 'audio':+ case 'voice':+ return (+ <div className="message-media-audio">+ <audio src={mediaSrc} controls className="chat-audio-media" />+ </div>+ );+ case 'document':+ default:+ return (+ <div className="message-media-document">+ <a+ href={mediaSrc}+ download={mediaInfo.filename || 'document'}+ className="chat-document-media"+ >+ 📎 {mediaInfo.filename || t('chats.downloadDocument')}+ </a>+ </div>+ );+ }+ };++ const reactions = msg.metadata?.reactions || {};+ const hasReactions = Object.keys(reactions).length > 0;+ const isRevoked = msg.type === 'revoked';+ const isMasked = msg.type === 'masked';++ return (+ <div+ key={msg.id}+ className={`message-bubble-wrapper ${isMe ? 'outgoing' : 'incoming'}`}+ data-wa-message-id={msg.waMessageId}+ >+ <div className="message-bubble-container">+ <div+ className={`message-bubble ${isMe ? 'outgoing' : 'incoming'} ${msg.status} ${+ isMediaMessage ? 'media-type' : ''+ } ${isRevoked ? 'revoked-type' : ''}`}+ >+ {/* Group sender label (WhatsApp-style: coloured name atop the bubble) */}+ {/* Group sender label (WhatsApp-style: coloured name atop the bubble).+ Colour keys on the stable sender id, so same-named participants+ still get distinct colours; the label shows the human name. */}+ {showSender && (+ <div className="message-sender" style={{ color: senderColor(senderKey(msg)!) }}>+ {msg.chatName}+ </div>+ )}++ {/* Quoted message display */}+ {msg.metadata?.quotedMessage && (+ <div className="message-quote-box">+ <MessageBody text={msg.metadata.quotedMessage.body} className="quote-body" />+ </div>+ )}++ {renderMedia()}++ {isRevoked ? (+ <div className="message-text">{t('chats.messageDeleted')}</div>+ ) : isMasked ? (+ <div className="message-text message-masked">{t('chats.messageMasked')}</div>+ ) : (+ msg.body &&+ (!mediaInfo || msg.body !== mediaInfo.filename) &&+ msg.type !== 'location' &&+ msg.type !== 'call' && <MessageBody text={msg.body} className="message-text" />+ )}++ <div className="message-meta">+ <span className="message-time">{formattedTime}</span>+ {isMe && (+ <span className={`message-status-icon ${msg.status}`}>+ {msg.status === 'pending' && '🕒'}+ {msg.status === 'sent' && '✓'}+ {msg.status === 'delivered' && '✓✓'}+ {msg.status === 'read' && '✓✓'}+ {msg.status === 'failed' && '⚠️'}+ </span>+ )}+ </div>++ {/* Reactions display */}+ {hasReactions && (+ <div className="message-reactions-badge">+ {Object.values(reactions)+ .slice(0, 3)+ .map((emoji, idx) => (+ <span key={idx} className="reaction-emoji-span">+ {emoji}+ </span>+ ))}+ {Object.keys(reactions).length > 1 && (+ <span className="reactions-count-span">{Object.keys(reactions).length}</span>+ )}+ </div>+ )}+ </div>++ {/* Message actions menu (hover) */}+ {!isRevoked && (+ <div className="message-actions-menu">+ <button+ type="button"+ className="action-btn"+ onClick={() => onReply(msg)}+ title={t('chats.actions.reply')}+ >+ <CornerUpLeft size={14} />+ </button>++ <div className="reaction-trigger-wrapper">+ <button+ type="button"+ className="action-btn reaction-btn"+ title={t('chats.actions.react')}+ >+ <Smile size={14} />+ </button>+ <div className="reaction-quick-popover">+ {['👍', '❤️', '😂', '😮', '😢', '🙏'].map(emoji => (+ <button key={emoji} type="button" onClick={() => onReact(msg, emoji)}>+ {emoji}+ </button>+ ))}+ </div>+ </div>++ {isMe && msg.status !== 'pending' && (+ <button+ type="button"+ className="action-btn delete-btn"+ onClick={() => onDelete(msg)}+ title={t('chats.actions.delete')}+ >+ <Trash2 size={14} />+ </button>+ )}+ </div>+ )}+ </div>+ </div>+ );+ })+ )}+ </div>+ );+}++export default ChatThread;diff --git a/dashboard/src/components/chats/KindIcon.tsx b/dashboard/src/components/chats/KindIcon.tsxnew file mode 100644index 000000000..a39e2c323--- /dev/null+++ b/dashboard/src/components/chats/KindIcon.tsx@@ -0,0 +1,11 @@+import { User, Users, Megaphone, CircleDashed } from 'lucide-react';+import type { ChatKind } from '../../services/api';++function KindIcon({ kind }: { kind: ChatKind }) {+ if (kind === 'group' || kind === 'broadcast') return <Users size={20} />;+ if (kind === 'channel') return <Megaphone size={20} />;+ if (kind === 'status') return <CircleDashed size={20} />;+ return <User size={20} />;+}++export default KindIcon;diff --git a/dashboard/src/components/chats/StatusComposeModal.tsx b/dashboard/src/components/chats/StatusComposeModal.tsxnew file mode 100644index 000000000..ab578c693--- /dev/null+++ b/dashboard/src/components/chats/StatusComposeModal.tsx@@ -0,0 +1,294 @@+import { useCallback, useEffect, useRef, useState } from 'react';+import { useQuery } from '@tanstack/react-query';+import { useTranslation } from 'react-i18next';+import { Loader2 } from 'lucide-react';+import { contactApi, sessionApi } from '../../services/api';+import { useCurrentEngineQuery } from '../../hooks/queries';+import { useToast } from '../Toast';+import { Modal } from '../Modal';++// Mirrors @ArrayMaxSize(256) on the send-status DTOs — the picker caps selection client-side so the+// user can't build a list the backend is guaranteed to reject.+const STATUS_RECIPIENTS_MAX = 256;++interface Props {+ sessionId: string;+ onClose: () => void;+ onPosted: () => void;+}++function StatusComposeModal({ sessionId, onClose, onPosted }: Props) {+ const { t } = useTranslation();+ const { success: showSuccessToast, error: showErrorToast } = useToast();+ const currentEngine = useCurrentEngineQuery();++ // Baileys targets a status post to an explicit allow-list (statusJidList); whatsapp-web.js has no+ // per-recipient concept and broadcasts to the account's status-privacy audience instead, so the+ // recipient picker is Baileys-only.+ const isBaileysEngine = currentEngine.data?.engineType === 'baileys';++ const [composeType, setComposeType] = useState<'text' | 'image'>('text');+ const [composeText, setComposeText] = useState<string>('');+ const [composeBgColor, setComposeBgColor] = useState<string>('');+ const [composeFont, setComposeFont] = useState<string>('');+ const [composeImageUrl, setComposeImageUrl] = useState<string>('');+ const [composeImageBase64, setComposeImageBase64] = useState<string | null>(null);+ const [composeCaption, setComposeCaption] = useState<string>('');+ const [composeRecipients, setComposeRecipients] = useState<string[]>([]);+ const [composeRecipientSearch, setComposeRecipientSearch] = useState<string>('');+ const [composePosting, setComposePosting] = useState<boolean>(false);+ const composeFileInputRef = useRef<HTMLInputElement | null>(null);+ // Monotonic token invalidating an in-flight FileReader: picking a file reads asynchronously, and+ // a URL edit (or form reset) before `onload` fires must win over the late-arriving file bytes.+ const composeImageReadSeq = useRef(0);++ // Unmounting the modal with a read still in flight: invalidate the reader so its late+ // onload handler drops the bytes instead of setting state on a dead component.+ useEffect(() => {+ return () => {+ composeImageReadSeq.current += 1;+ };+ }, []);++ // Sourced only while the modal is actually open on Baileys — no reason to fetch the full contact+ // list on wwjs (no picker) or before the user has opened compose. The page only mounts this+ // component while the modal is open, so being mounted implies "open".+ const composeContactsQuery = useQuery({+ queryKey: ['status-compose-contacts', sessionId],+ queryFn: () => contactApi.list(sessionId!),+ enabled: isBaileysEngine && Boolean(sessionId),+ });+ const composeContacts = composeContactsQuery.data ?? [];+ const composeRecipientSearchLower = composeRecipientSearch.toLowerCase();+ const filteredComposeContacts = composeContacts.filter(c =>+ // Match against every identity field — a named contact must still be findable by number/JID.+ [c.name, c.pushName, c.number, c.id].some(v => v?.toLowerCase().includes(composeRecipientSearchLower)),+ );++ const resetComposeForm = useCallback(() => {+ composeImageReadSeq.current += 1;+ setComposeType('text');+ setComposeText('');+ setComposeBgColor('');+ setComposeFont('');+ setComposeImageUrl('');+ setComposeImageBase64(null);+ setComposeCaption('');+ setComposeRecipients([]);+ setComposeRecipientSearch('');+ if (composeFileInputRef.current) composeFileInputRef.current.value = '';+ }, []);++ const closeComposeModal = useCallback(() => {+ onClose();+ resetComposeForm();+ }, [onClose, resetComposeForm]);++ const toggleComposeRecipient = (id: string) => {+ setComposeRecipients(prev =>+ prev.includes(id)+ ? prev.filter(r => r !== id)+ : prev.length >= STATUS_RECIPIENTS_MAX+ ? prev+ : [...prev, id],+ );+ };++ const handleComposeImageUrlChange = (value: string) => {+ composeImageReadSeq.current += 1;+ setComposeImageUrl(value);+ if (value) {+ setComposeImageBase64(null);+ if (composeFileInputRef.current) composeFileInputRef.current.value = '';+ }+ };++ const handleComposeImageFile = (e: React.ChangeEvent<HTMLInputElement>) => {+ const file = e.target.files?.[0];+ if (!file) return;+ setComposeImageUrl('');+ const myRead = ++composeImageReadSeq.current;+ const reader = new FileReader();+ reader.onload = event => {+ // A URL edit or form reset since the read started supersedes these bytes — drop them.+ if (composeImageReadSeq.current !== myRead) return;+ // The backend's stripBase64DataUri unwraps a `data:...;base64,` prefix, so passing the raw+ // data URL through as `base64` is safe — no need to slice it ourselves.+ setComposeImageBase64(event.target?.result as string);+ };+ reader.readAsDataURL(file);+ };++ const composeCanSubmit =+ Boolean(sessionId) &&+ !composePosting &&+ // The engine type decides whether recipients are required (Baileys) or omitted (wwjs) — while+ // it's still unknown, a Baileys submit would go out with no recipients and 400.+ Boolean(currentEngine.data) &&+ (composeType === 'text' ? composeText.trim().length > 0 : Boolean(composeImageBase64 || composeImageUrl.trim())) &&+ (!isBaileysEngine || composeRecipients.length > 0);++ const handleComposeSubmit = async () => {+ if (!sessionId || !composeCanSubmit) return;+ setComposePosting(true);+ try {+ // whatsapp-web.js ignores `recipients` entirely (it broadcasts to status@broadcast), so none+ // are sent — the backend DTO treats the list as optional and only the Baileys engine requires+ // (and honors) it. The picker is hidden on wwjs since it has no effect there.+ const recipients = isBaileysEngine ? composeRecipients : undefined;+ if (composeType === 'text') {+ await sessionApi.postTextStatus(sessionId, composeText.trim(), recipients, {+ backgroundColor: composeBgColor || undefined,+ font: composeFont === '' ? undefined : Number(composeFont),+ });+ } else {+ const image = composeImageBase64 ? { base64: composeImageBase64 } : { url: composeImageUrl.trim() };+ await sessionApi.postImageStatus(sessionId, image, recipients, composeCaption.trim() || undefined);+ }+ showSuccessToast(t('chats.status.posted'));+ closeComposeModal();+ onPosted();+ } catch (err) {+ showErrorToast(t('chats.status.postFailed'), err instanceof Error ? err.message : undefined);+ } finally {+ setComposePosting(false);+ }+ };++ return (+ <Modal+ open+ onClose={closeComposeModal}+ title={t('chats.status.compose')}+ closeLabel={t('common.close')}+ className="status-compose-modal"+ footer={+ <>+ <button className="btn-secondary" onClick={closeComposeModal} disabled={composePosting}>+ {t('common.cancel')}+ </button>+ <button className="btn-primary" onClick={handleComposeSubmit} disabled={!composeCanSubmit}>+ {composePosting ? <Loader2 className="animate-spin" size={16} /> : t('chats.status.post')}+ </button>+ </>+ }+ >+ <div className="compose-type-toggle">+ <button type="button" className={composeType === 'text' ? 'active' : ''} onClick={() => setComposeType('text')}>+ {t('chats.status.composeText')}+ </button>+ <button+ type="button"+ className={composeType === 'image' ? 'active' : ''}+ onClick={() => setComposeType('image')}+ >+ {t('chats.status.composeImage')}+ </button>+ </div>++ {composeType === 'text' ? (+ <>+ <div className="compose-field">+ <label>{t('chats.status.composeText')}</label>+ <textarea+ value={composeText}+ onChange={e => setComposeText(e.target.value)}+ maxLength={4096}+ placeholder={t('chats.status.composeText')}+ />+ </div>+ <div className="compose-row">+ <div className="compose-field">+ <label>{t('chats.status.backgroundColor')}</label>+ <input+ type="color"+ value={composeBgColor || '#000000'}+ onChange={e => setComposeBgColor(e.target.value)}+ />+ </div>+ <div className="compose-field">+ <label>{t('chats.status.font')}</label>+ <select value={composeFont} onChange={e => setComposeFont(e.target.value)}>+ <option value="">{t('chats.status.fontDefault')}</option>+ {/* The WhatsApp status font enum: 6 is the bold system face; 3–5 don't exist on+ the wire and the backend rejects them. */}+ {[0, 1, 2, 6, 7, 8, 9, 10].map(f => (+ <option key={f} value={f}>+ {f}+ </option>+ ))}+ </select>+ </div>+ </div>+ </>+ ) : (+ <>+ <div className="compose-field">+ <label>{t('chats.status.composeImage')}</label>+ <input+ type="url"+ placeholder="https://example.com/image.jpg"+ value={composeImageUrl}+ onChange={e => handleComposeImageUrlChange(e.target.value)}+ />+ </div>+ <p className="compose-image-or">{t('chats.status.orLabel')}</p>+ <div className="compose-field">+ <input+ type="file"+ accept="image/*"+ ref={composeFileInputRef}+ onChange={handleComposeImageFile}+ />+ </div>+ <div className="compose-field">+ <label>{t('chats.status.caption')}</label>+ <input+ type="text"+ placeholder={t('chats.captionPlaceholder')}+ value={composeCaption}+ onChange={e => setComposeCaption(e.target.value)}+ maxLength={1024}+ />+ </div>+ </>+ )}++ {isBaileysEngine && (+ <div className="compose-field">+ <label>{t('chats.status.recipients')}</label>+ <input+ type="text"+ placeholder={t('common.search')}+ value={composeRecipientSearch}+ onChange={e => setComposeRecipientSearch(e.target.value)}+ />+ <div className="compose-recipients">+ {composeContactsQuery.isLoading ? (+ <div className="compose-recipients-empty">+ <Loader2 className="animate-spin" size={16} />+ </div>+ ) : filteredComposeContacts.length === 0 ? (+ <div className="compose-recipients-empty">{t('chats.status.noContacts')}</div>+ ) : (+ filteredComposeContacts.map(c => (+ <label key={c.id} className="compose-recipient-row">+ <input+ type="checkbox"+ checked={composeRecipients.includes(c.id)}+ disabled={!composeRecipients.includes(c.id) && composeRecipients.length >= STATUS_RECIPIENTS_MAX}+ onChange={() => toggleComposeRecipient(c.id)}+ />+ <span>{c.name || c.pushName || c.number || c.id}</span>+ </label>+ ))+ )}+ </div>+ <p className="input-hint">{t('chats.status.recipientsHint')}</p>+ </div>+ )}+ </Modal>+ );+}++export default StatusComposeModal;diff --git a/dashboard/src/components/chats/StatusMedia.tsx b/dashboard/src/components/chats/StatusMedia.tsxnew file mode 100644index 000000000..364d732bc--- /dev/null+++ b/dashboard/src/components/chats/StatusMedia.tsx@@ -0,0 +1,49 @@+import { useEffect, useState } from 'react';+import { useTranslation } from 'react-i18next';+import { sessionApi } from '../../services/api';++// Status image item. <img src="/api/..."> can't carry the X-API-Key header, so the bytes are+// fetched via sessionApi (which does) and re-exposed as a local object URL. The URL is revoked on+// unmount/statusId change to avoid leaking blob memory as the viewer browses items.+function StatusMedia({+ sessionId,+ statusId,+ type,+}: {+ sessionId: string | null;+ statusId: string;+ type: 'image' | 'video';+}) {+ const { t } = useTranslation();+ const [src, setSrc] = useState<string | null>(null);+ const [error, setError] = useState<boolean>(false);++ useEffect(() => {+ if (!sessionId) return undefined;+ let objectUrl: string | null = null;+ let cancelled = false;+ setSrc(null);+ setError(false);+ sessionApi+ .getStatusMediaBlob(sessionId, statusId)+ .then(blob => {+ if (cancelled) return;+ objectUrl = URL.createObjectURL(blob);+ setSrc(objectUrl);+ })+ .catch(() => {+ if (!cancelled) setError(true);+ });+ return () => {+ cancelled = true;+ if (objectUrl) URL.revokeObjectURL(objectUrl);+ };+ }, [sessionId, statusId]);++ if (error) return <span className="status-media-placeholder">{t('chats.status.mediaUnavailable')}</span>;+ if (!src) return null;+ if (type === 'video') return <video className="channel-media" src={src} controls />;+ return <img className="channel-media" src={src} alt="" />;+}++export default StatusMedia;diff --git a/dashboard/src/pages/Chats.test.ts b/dashboard/src/pages/Chats.test.tsnew file mode 100644index 000000000..1f187de0c--- /dev/null+++ b/dashboard/src/pages/Chats.test.ts@@ -0,0 +1,182 @@+// Render smoke test for the Chats page under the bare `node --test` runner (no vitest/jest).+// It exists to catch the classic god-component extraction bugs: a missing prop that crashes the+// render, or a lost provider (QueryClient / Role / Toast / i18n). The page is wrapped in the+// same providers App.tsx uses (QueryClientProvider → RoleProvider → ToastProvider; i18n via the+// side-effect import; Chats uses no router hooks, so no Router is needed) and the backend is+// stubbed at the fetch layer with canned JSON for every endpoint the page hits on mount,+// on chat open, and on send.+//+// Runner constraints honored here: plain .ts with React.createElement (the runner cannot parse+// JSX), loader hooks registered before any app-module import (see test-helpers/register-hooks),+// and JSDOM installed before importing modules that read `window` at import time.+import '../test-helpers/register-hooks.ts';+import { test, before, afterEach } from 'node:test';+import assert from 'node:assert/strict';+import { createElement } from 'react';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import type { Session, Chat, ChatMessage } from '../services/api';+import type { installJsdomGlobals as installJsdomGlobalsFn } from '../test-helpers/jsdom.ts';++// ── Fixtures + fetch stub ────────────────────────────────────────────────────++const SESSION: Session = {+ id: 'session-1',+ name: 'Main',+ status: 'ready',+ phone: '15551234567',+ createdAt: '2026-01-01T00:00:00.000Z',+ updatedAt: '2026-01-01T00:00:00.000Z',+};++const CHAT: Chat = {+ id: '[email protected]',+ name: 'Alice',+ isGroup: false,+ kind: 'individual',+ unreadCount: 2,+ timestamp: 1_700_000_000,+ lastMessage: 'hello from alice',+};++const DB_MESSAGE: ChatMessage = {+ id: 'db-1',+ waMessageId: 'wamid.1',+ chatId: CHAT.id,+ from: CHAT.id,+ to: 'me',+ body: 'hello from alice',+ type: 'text',+ direction: 'incoming',+ status: 'delivered',+ timestamp: 1_700_000_000,+ createdAt: new Date(1_700_000_000_000).toISOString(),+};++function jsonResponse(data: unknown, status = 200): Response {+ return new Response(JSON.stringify(data), {+ status,+ headers: { 'Content-Type': 'application/json' },+ });+}++// URL router for every endpoint the page (and the hooks/components under it) can hit during the+// smoke flow below. Anything else gets a 404 so an unexpected request fails loudly in the test+// output instead of resolving into a confusing downstream crash.+function installFetchStub(): void {+ const chatId = encodeURIComponent(CHAT.id);+ globalThis.fetch = (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {+ const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;+ const method = init?.method ?? 'GET';+ const path = url.replace(/^https?:\/\/[^/]+/, '');++ if (method === 'GET' && path === '/api/sessions') return Promise.resolve(jsonResponse([SESSION]));+ if (method === 'GET' && path === '/api/infra/engines/current') {+ return Promise.resolve(jsonResponse({ engineType: 'baileys' }));+ }+ if (method === 'GET' && path === `/api/sessions/${SESSION.id}/chats`) {+ return Promise.resolve(jsonResponse([CHAT]));+ }+ if (method === 'GET' && path.startsWith(`/api/sessions/${SESSION.id}/contacts/profile-pictures`)) {+ return Promise.resolve(jsonResponse({ pictures: {} }));+ }+ if (method === 'GET' && path === `/api/sessions/${SESSION.id}/contacts/${chatId}/profile-picture`) {+ return Promise.resolve(jsonResponse({ url: null }));+ }+ if (method === 'GET' && path.startsWith(`/api/sessions/${SESSION.id}/messages?`)) {+ return Promise.resolve(jsonResponse({ messages: [DB_MESSAGE], total: 1 }));+ }+ if (method === 'GET' && path.startsWith(`/api/sessions/${SESSION.id}/messages/${chatId}/history`)) {+ return Promise.resolve(jsonResponse([]));+ }+ if (method === 'POST' && path === `/api/sessions/${SESSION.id}/chats/read`) {+ return Promise.resolve(jsonResponse({ success: true }));+ }+ if (method === 'POST' && path === `/api/sessions/${SESSION.id}/messages/send-text`) {+ return Promise.resolve(jsonResponse({ messageId: 'wamid.out.1', timestamp: 1_700_000_100 }));+ }+ return Promise.resolve(jsonResponse({ message: `unstubbed ${method} ${path}` }, 404));+ };+}++// ── Harness bootstrap ────────────────────────────────────────────────────────++type RTL = typeof import('@testing-library/react');+type ChatsModule = typeof import('./Chats.tsx');+type RoleModule = typeof import('../hooks/useRole.tsx');+type ToastModule = typeof import('../components/Toast.tsx');++let rtl: RTL;+let Chats: ChatsModule['Chats'];+let RoleProvider: RoleModule['RoleProvider'];+let ToastProvider: ToastModule['ToastProvider'];+let installJsdomGlobals: typeof installJsdomGlobalsFn;+let queryClient: QueryClient | undefined;++before(async () => {+ ({ installJsdomGlobals } = await import('../test-helpers/jsdom.ts'));+ await installJsdomGlobals();+ installFetchStub();+ // RoleProvider initializes from localStorage; 'admin' makes canWrite true so the composer+ // controls render enabled.+ window.localStorage.setItem('openwa_user_role', 'admin');+ // Side-effect import: initializes the real i18n instance with all locales (JSON modules are+ // handled by the registered loader hooks).+ await import('../i18n/index.ts');+ rtl = await import('@testing-library/react');+ ({ RoleProvider } = await import('../hooks/useRole.tsx'));+ ({ ToastProvider } = await import('../components/Toast.tsx'));+ ({ Chats } = await import('./Chats.tsx'));+});++afterEach(() => {+ rtl.cleanup();+ queryClient?.clear();+ queryClient = undefined;+});++function renderChats(): { container: HTMLElement } {+ // Small gcTime so the QueryClient's garbage-collection timers don't hold the test process open.+ queryClient = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 1_000 } } });+ return rtl.render(+ createElement(+ QueryClientProvider,+ { client: queryClient },+ createElement(+ RoleProvider,+ null,+ createElement(ToastProvider, null, createElement(Chats)),+ ),+ ),+ );+}++// ── Smoke test ───────────────────────────────────────────────────────────────++test('Chats renders: session/chat list loads, a chat opens, and a message sends', async () => {+ const { screen, fireEvent, within } = rtl;+ const { container } = renderChats();++ // Sidebar: the session selector shows the stubbed ready session, and the chat list row+ // appears once /sessions and /sessions/:id/chats have resolved.+ await screen.findByText('Main (15551234567)');+ const chatRow = await screen.findByText('Alice');++ // Open the chat: the message thread renders the stubbed DB message (both the DB and the+ // engine-history fetches went through the stub). Scoped to the thread container: the sidebar+ // snippet carries the same lastMessage text, so an unscoped query is a timing coin-flip.+ fireEvent.click(chatRow);+ const thread = container.querySelector('.room-messages') as HTMLElement;+ await within(thread).findByText('hello from alice');++ // Composer: the send button (aria-label = chats.send) and message input are the stable markers.+ const sendButton = screen.getByRole('button', { name: 'Send' }) as HTMLButtonElement;+ const input = screen.getByPlaceholderText('Type a message...') as HTMLInputElement;+ assert.equal(sendButton.disabled, true); // empty input → disabled++ // Type and send: the optimistic bubble appears, then reconciles with the stubbed response+ // (scoped again — the send also promotes the sidebar row to the same snippet text).+ fireEvent.change(input, { target: { value: 'hello back' } });+ assert.equal(sendButton.disabled, false);+ fireEvent.click(sendButton);+ await within(thread).findByText('hello back');+});diff --git a/dashboard/src/pages/Chats.tsx b/dashboard/src/pages/Chats.tsxindex a72d42f68..879bc2c7d 100644--- a/dashboard/src/pages/Chats.tsx+++ b/dashboard/src/pages/Chats.tsx@@ -2,26 +2,15 @@ import { useState, useEffect, useCallback, useRef, useMemo, useLayoutEffect } frimport { useQuery, useQueryClient } from '@tanstack/react-query';import { Trans, useTranslation } from 'react-i18next';import { nextReconnectState } from '../utils/reconnectState';-import { applyIncomingToChatList, promoteChatWithSnippet } from '../utils/chatList';+import { applyIncomingToChatList } from '../utils/chatList';import { filterChats, filterChannels, groupStatusesByContact } from '../utils/chatFilters';import {- Search,- Send,ArrowLeft,Loader2,- User,- Users,Megaphone,CircleDashed,AlertCircle,MessageSquare,- Paperclip,- Smile,- X,- CornerUpLeft,- Trash2,- ChevronDown,- Plus,} from 'lucide-react';import { useProfilePicture } from '../hooks/useProfilePicture';import { useProfilePictures } from '../hooks/useProfilePictures';@@ -30,29 +19,25 @@ import { formatPhoneForDisplay } from '../utils/formatPhone';import {sessionApi,messageApi,- contactApi,asMessageType,type Session,type Chat,type ChatKind,type Channel,- type MessageType,type SearchHit,type ContactStatusGroup,} from '../services/api';import {applyMessageEdit,mergeDeliveryStatus,- mergeOrAppend,findRevokedIndex,- senderKey,+ getMediaSrc,type ChatMessageView,+ type MessageMedia,} from '../utils/chatMessages';import { useWebSocket } from '../hooks/useWebSocket';import { useDocumentTitle } from '../hooks/useDocumentTitle';-import { useRole } from '../hooks/useRole';import { useToast } from '../components/Toast';-import { Modal } from '../components/Modal';import { PageHeader } from '../components/PageHeader';import { GlobalSearch } from '../components/GlobalSearch';import { useChatMessages, useChatMessagesActions, messagesQueryKey } from '../hooks/useChatMessages';@@ -63,13 +48,17 @@ import { useCurrentEngineQuery } from '../hooks/queries';import { createTrailingCoalescer } from '../utils/trailingCoalescer';import MessageBody from '../components/chats/MessageBody';import MediaLightbox, { type LightboxItem } from '../components/chats/MediaLightbox';+import KindIcon from '../components/chats/KindIcon';+import ChatSidebar from '../components/chats/ChatSidebar';+import ChatThread from '../components/chats/ChatThread';+import ChatComposer from '../components/chats/ChatComposer';+import StatusMedia from '../components/chats/StatusMedia';+import StatusComposeModal from '../components/chats/StatusComposeModal';import './Chats.css';// Quiet window for coalescing mark-as-read RPCs (see markReadCoalescer below).const MARK_READ_DEBOUNCE_MS = 750;-type MessageMedia = { mimetype: string; filename?: string; data?: string; omitted?: boolean; sizeBytes?: number };-// mergeDeliveryStatus (forward-only delivery-tick merge) is shared with mergeOrAppend in utils/chatMessages// so the WS append path and the ack path apply the exact same rule.@@ -94,106 +83,6 @@ interface IncomingWsMessage {author?: string;}-// Stable per-sender colour for group message labels, like WhatsApp gives each participant a colour.-// Hashed from the sender's name so the same person keeps the same colour across a session. The palette-// is tuned to stay legible on both the light and dark incoming-bubble backgrounds.-const SENDER_COLORS = ['#d1416f', '#7c5cff', '#0a86c4', '#1a8f5c', '#c26a00', '#c0392b', '#0e7c86', '#8e44ad'];-const senderColor = (name: string): string => {- let hash = 0;- for (let i = 0; i < name.length; i++) hash = (hash * 31 + name.charCodeAt(i)) | 0;- return SENDER_COLORS[Math.abs(hash) % SENDER_COLORS.length];-};--// Map an attachment MIME type to the neutral MessageType for the optimistic outgoing bubble, so the-// placeholder matches what the backend will persist (e.g. a PDF is `document`, not `application`).-const messageTypeFromMime = (mimetype: string): MessageType => {- if (mimetype.startsWith('image/')) return 'image';- if (mimetype.startsWith('video/')) return 'video';- if (mimetype.startsWith('audio/')) return 'audio';- return 'document';-};--const getMediaSrc = (media?: MessageMedia): string => {- if (!media || !media.data) return '';- if (media.data.startsWith('data:') || media.data.startsWith('http://') || media.data.startsWith('https://')) {- return media.data;- }- return `data:${media.mimetype};base64,${media.data}`;-};--// Chat list avatar. Renders from the sidebar's ONE batch request (useProfilePictures) — firing a-// query per row burst the per-IP throttle into 429s. The generic icon stays while the batch loads-// or when the contact hides their picture.-function KindIcon({ kind }: { kind: ChatKind }) {- if (kind === 'group' || kind === 'broadcast') return <Users size={20} />;- if (kind === 'channel') return <Megaphone size={20} />;- if (kind === 'status') return <CircleDashed size={20} />;- return <User size={20} />;-}--function ChatAvatar({ pictureUrl, kind }: { pictureUrl?: string | null; kind: ChatKind }) {- if (pictureUrl) {- return (- <div className="chat-avatar">- <img src={pictureUrl} alt="" />- </div>- );- }- return (- <div className="chat-avatar">- <KindIcon kind={kind} />- </div>- );-}--// Status image item. <img src="/api/..."> can't carry the X-API-Key header, so the bytes are-// fetched via sessionApi (which does) and re-exposed as a local object URL. The URL is revoked on-// unmount/statusId change to avoid leaking blob memory as the viewer browses items.-function StatusMedia({- sessionId,- statusId,- type,-}: {- sessionId: string | null;- statusId: string;- type: 'image' | 'video';-}) {- const { t } = useTranslation();- const [src, setSrc] = useState<string | null>(null);- const [error, setError] = useState<boolean>(false);-- useEffect(() => {- if (!sessionId) return undefined;- let objectUrl: string | null = null;- let cancelled = false;- setSrc(null);- setError(false);- sessionApi- .getStatusMediaBlob(sessionId, statusId)- .then(blob => {- if (cancelled) return;- objectUrl = URL.createObjectURL(blob);- setSrc(objectUrl);- })- .catch(() => {- if (!cancelled) setError(true);- });- return () => {- cancelled = true;- if (objectUrl) URL.revokeObjectURL(objectUrl);- };- }, [sessionId, statusId]);-- if (error) return <span className="status-media-placeholder">{t('chats.status.mediaUnavailable')}</span>;- if (!src) return null;- if (type === 'video') return <video className="channel-media" src={src} controls />;- return <img className="channel-media" src={src} alt="" />;-}--// Mirrors @ArrayMaxSize(256) on the send-status DTOs — the picker caps selection client-side so the-// user can't build a list the backend is guaranteed to reject.-const STATUS_RECIPIENTS_MAX = 256;-// WhatsApp's text-status font slots — the current wire enum is {0,1,2,6,7,8,9,10} (6 is the bold// system face); 3–5 are legacy slots older clients still emit. Approximated with generic// families/weights since the actual faces are proprietary; slot 0 and unknown slots keep the UI@@ -225,8 +114,7 @@ const statusFontStyle = (font?: number): { fontFamily?: string; fontWeight?: numexport function Chats() {const { t } = useTranslation();useDocumentTitle(t('nav.chats'));- const { canWrite } = useRole();- const { success: showSuccessToast, error: showErrorToast, warning: showWarningToast } = useToast();+ const { error: showErrorToast, warning: showWarningToast } = useToast();// Sessions list & active sessionconst [sessions, setSessions] = useState<Session[]>([]);@@ -283,130 +171,9 @@ export function Chats() {}, [activeChannel?.id, channelMessages.data]);// --- Status compose modal ---- // Baileys targets a status post to an explicit allow-list (statusJidList); whatsapp-web.js has no- // per-recipient concept and broadcasts to the account's status-privacy audience instead, so the- // recipient picker is Baileys-only.- const isBaileysEngine = currentEngine.data?.engineType === 'baileys';-+ // The page owns only the open flag (its trigger sits in the sidebar header below); the form+ // itself — state, contacts query, submit — is components/chats/StatusComposeModal.const [composeOpen, setComposeOpen] = useState<boolean>(false);- const [composeType, setComposeType] = useState<'text' | 'image'>('text');- const [composeText, setComposeText] = useState<string>('');- const [composeBgColor, setComposeBgColor] = useState<string>('');- const [composeFont, setComposeFont] = useState<string>('');- const [composeImageUrl, setComposeImageUrl] = useState<string>('');- const [composeImageBase64, setComposeImageBase64] = useState<string | null>(null);- const [composeCaption, setComposeCaption] = useState<string>('');- const [composeRecipients, setComposeRecipients] = useState<string[]>([]);- const [composeRecipientSearch, setComposeRecipientSearch] = useState<string>('');- const [composePosting, setComposePosting] = useState<boolean>(false);- const composeFileInputRef = useRef<HTMLInputElement | null>(null);- // Monotonic token invalidating an in-flight FileReader: picking a file reads asynchronously, and- // a URL edit (or form reset) before `onload` fires must win over the late-arriving file bytes.- const composeImageReadSeq = useRef(0);-- // Sourced only while the modal is actually open on Baileys — no reason to fetch the full contact- // list on wwjs (no picker) or before the user has opened compose.- const composeContactsQuery = useQuery({- queryKey: ['status-compose-contacts', selectedSessionId],- queryFn: () => contactApi.list(selectedSessionId!),- enabled: composeOpen && isBaileysEngine && Boolean(selectedSessionId),- });- const composeContacts = composeContactsQuery.data ?? [];- const composeRecipientSearchLower = composeRecipientSearch.toLowerCase();- const filteredComposeContacts = composeContacts.filter(c =>- // Match against every identity field — a named contact must still be findable by number/JID.- [c.name, c.pushName, c.number, c.id].some(v => v?.toLowerCase().includes(composeRecipientSearchLower)),- );-- const resetComposeForm = useCallback(() => {- composeImageReadSeq.current += 1;- setComposeType('text');- setComposeText('');- setComposeBgColor('');- setComposeFont('');- setComposeImageUrl('');- setComposeImageBase64(null);- setComposeCaption('');- setComposeRecipients([]);- setComposeRecipientSearch('');- if (composeFileInputRef.current) composeFileInputRef.current.value = '';- }, []);-- const closeComposeModal = useCallback(() => {- setComposeOpen(false);- resetComposeForm();- }, [resetComposeForm]);-- const toggleComposeRecipient = (id: string) => {- setComposeRecipients(prev =>- prev.includes(id)- ? prev.filter(r => r !== id)- : prev.length >= STATUS_RECIPIENTS_MAX- ? prev- : [...prev, id],- );- };-- const handleComposeImageUrlChange = (value: string) => {- composeImageReadSeq.current += 1;- setComposeImageUrl(value);- if (value) {- setComposeImageBase64(null);- if (composeFileInputRef.current) composeFileInputRef.current.value = '';- }- };-- const handleComposeImageFile = (e: React.ChangeEvent<HTMLInputElement>) => {- const file = e.target.files?.[0];- if (!file) return;- setComposeImageUrl('');- const myRead = ++composeImageReadSeq.current;- const reader = new FileReader();- reader.onload = event => {- // A URL edit or form reset since the read started supersedes these bytes — drop them.- if (composeImageReadSeq.current !== myRead) return;- // The backend's stripBase64DataUri unwraps a `data:...;base64,` prefix, so passing the raw- // data URL through as `base64` is safe — no need to slice it ourselves.- setComposeImageBase64(event.target?.result as string);- };- reader.readAsDataURL(file);- };-- const composeCanSubmit =- Boolean(selectedSessionId) &&- !composePosting &&- // The engine type decides whether recipients are required (Baileys) or omitted (wwjs) — while- // it's still unknown, a Baileys submit would go out with no recipients and 400.- Boolean(currentEngine.data) &&- (composeType === 'text' ? composeText.trim().length > 0 : Boolean(composeImageBase64 || composeImageUrl.trim())) &&- (!isBaileysEngine || composeRecipients.length > 0);-- const handleComposeSubmit = async () => {- if (!selectedSessionId || !composeCanSubmit) return;- setComposePosting(true);- try {- // whatsapp-web.js ignores `recipients` entirely (it broadcasts to status@broadcast), so none- // are sent — the backend DTO treats the list as optional and only the Baileys engine requires- // (and honors) it. The picker is hidden on wwjs since it has no effect there.- const recipients = isBaileysEngine ? composeRecipients : undefined;- if (composeType === 'text') {- await sessionApi.postTextStatus(selectedSessionId, composeText.trim(), recipients, {- backgroundColor: composeBgColor || undefined,- font: composeFont === '' ? undefined : Number(composeFont),- });- } else {- const image = composeImageBase64 ? { base64: composeImageBase64 } : { url: composeImageUrl.trim() };- await sessionApi.postImageStatus(selectedSessionId, image, recipients, composeCaption.trim() || undefined);- }- showSuccessToast(t('chats.status.posted'));- closeComposeModal();- statusesQuery.refetch();- } catch (err) {- showErrorToast(t('chats.status.postFailed'), err instanceof Error ? err.message : undefined);- } finally {- setComposePosting(false);- }- };const {data: messages = [],@@ -415,37 +182,10 @@ export function Chats() {} = useChatMessages(selectedSessionId, activeChat?.id ?? null);const { appendMessage, updateMessage } = useChatMessagesActions();const queryClient = useQueryClient();- const [messageInput, setMessageInput] = useState<string>('');- const [sending, setSending] = useState<boolean>(false);// Lightbox state for media viewerconst [lightboxIndex, setLightboxIndex] = useState<number | null>(null);- // File attachments- const [attachment, setAttachment] = useState<{- file: File;- base64: string;- mimetype: string;- filename: string;- } | null>(null);- const [previewUrl, setPreviewUrl] = useState<string | null>(null);- const [showEmojiPicker, setShowEmojiPicker] = useState<boolean>(false);- // Monotonic token invalidating an in-flight attachment FileReader: picking a second file (or- // removing the attachment) before `onload` fires must win over the late-arriving bytes —- // otherwise the slower read overwrites the newer pick. Same pattern as composeImageReadSeq.- const attachmentReadSeq = useRef(0);-- // Unmounting the page with a read still in flight: invalidate both readers so their late- // onload handlers drop the bytes instead of setting state on a dead component.- useEffect(() => {- return () => {- attachmentReadSeq.current += 1;- composeImageReadSeq.current += 1;- };- }, []);-- // References- const fileInputRef = useRef<HTMLInputElement | null>(null);const [replyingTo, setReplyingTo] = useState<ChatMessageView | null>(null);// Per-chat scroll-position memory + auto-scroll heuristic.@@ -481,57 +221,6 @@ export function Chats() {const activePhoneText =activePhoneDisplay ?? (resolvedPhoneQ.data ? formatPhoneForDisplay(resolvedPhoneQ.data) : null);- // Scroll-to-bottom button visibility. The main scroll-position memory is owned by- // useChatScrollPosition, which doesn't expose its pin state (intentionally — that would re-render- // the whole room on every scroll). This small listener tracks only the boolean "user is far from- // the bottom" so we can float the jump button.- const [showJumpToBottom, setShowJumpToBottom] = useState(false);- useEffect(() => {- const el = messagesContainerRef.current;- if (!el) return undefined;- const onScroll = () => {- // 120px gap = a couple of message bubbles before counting as "scrolled up".- setShowJumpToBottom(el.scrollHeight - el.scrollTop - el.clientHeight > 120);- };- onScroll(); // sync initial position (e.g. saved restore landed above the bottom)- el.addEventListener('scroll', onScroll, { passive: true });- return () => el.removeEventListener('scroll', onScroll);- });-- const handleJumpToBottom = useCallback(() => {- const el = messagesContainerRef.current;- if (!el) return;- el.scrollTo({ top: el.scrollHeight, behavior: 'smooth' });- }, [messagesContainerRef]);-- // Reset the jump button whenever the active chat changes: the new chat's content is restored by- // useChatScrollPosition and our listener will resync on its first scroll tick.- useEffect(() => {- setShowJumpToBottom(false);- }, [activeChat?.id]);-- // Popular emojis- const popularEmojis = [- '😀',- '😂',- '👍',- '❤️',- '🔥',- '👏',- '🙏',- '🎉',- '💡',- '🤔',- '😅',- '😍',- '😊',- '😭',- '😎',- '😜',- '🚀',- '✨',- ];-// 1. Fetch available connected sessions on mountuseEffect(() => {const loadSessions = async () => {@@ -577,20 +266,11 @@ export function Chats() {setActiveChat(null);setActiveChannel(null);setActiveStatusContactId(null);- setAttachment(null);- setPreviewUrl(null);+ // The composer unmounts with the closed room, dropping its attachment/preview state and+ // running its own cleanups (object-URL revoke, FileReader invalidation).}}, [selectedSessionId, loadChats]);- // Revoke the object URL created for an image-attachment preview once it is replaced, cleared, or- // the page unmounts. The cleanup runs with the previous value on every change, so this single- // effect covers all paths (new file, remove, session switch) — otherwise each preview leaks a- // blob held for the lifetime of the document.- useEffect(() => {- if (!previewUrl) return;- return () => URL.revokeObjectURL(previewUrl);- }, [previewUrl]);-// Coalesce mark-as-read RPCs per chat: every incoming message in the visible chat raises a// read event, and a per-event POST sprays the gateway into 429s. One trailing call per chat// after a quiet window carries the same effect.@@ -1010,169 +690,7 @@ export function Chats() {pendingHitRef.current = null;}, [activeChat, loadingMessages, messages, messagesContainerRef]);- // 5. Handle file selection & base64 conversion- const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {- const file = e.target.files?.[0];- if (!file) return;-- if (file.type.startsWith('image/')) {- setPreviewUrl(URL.createObjectURL(file));- } else {- setPreviewUrl(null);- }-- const myRead = ++attachmentReadSeq.current;- const reader = new FileReader();- reader.onload = event => {- // A newer pick, a removal, or an unmount since the read started supersedes these bytes.- if (attachmentReadSeq.current !== myRead) return;- const dataUrl = event.target?.result as string;- const base64Data = dataUrl.split(',')[1];- setAttachment({ file, base64: base64Data, mimetype: file.type, filename: file.name });- };- reader.readAsDataURL(file);- };-- const handleRemoveAttachment = () => {- attachmentReadSeq.current += 1; // an in-flight read must not resurrect the removed attachment- setAttachment(null);- setPreviewUrl(null);- if (fileInputRef.current) fileInputRef.current.value = '';- };-- const triggerFileSelect = () => {- fileInputRef.current?.click();- };-- const handleEmojiClick = (emoji: string) => {- setMessageInput(prev => prev + emoji);- setShowEmojiPicker(false);- };-- // 7. Handle sending a message / media- const handleSend = async (e?: React.FormEvent) => {- if (e) e.preventDefault();- if (!selectedSessionId || !activeChat || sending) return;-- const textToSend = messageInput.trim();- if (!textToSend && !attachment) return;-- setMessageInput('');- setSending(true);-- const tempId = `temp_${Date.now()}`;- const tempMessage: ChatMessageView = {- id: tempId,- chatId: activeChat.id,- from: 'me',- to: activeChat.id,- body: attachment- ? attachment.mimetype.startsWith('image/') ||- attachment.mimetype.startsWith('video/') ||- attachment.mimetype.startsWith('audio/')- ? textToSend- : attachment.filename- : textToSend,- type: attachment ? messageTypeFromMime(attachment.mimetype) : 'text',- direction: 'outgoing',- status: 'pending',- createdAt: new Date().toISOString(),- metadata: attachment- ? {- media: {- mimetype: attachment.mimetype,- filename: attachment.filename,- data: attachment.base64,- },- }- : replyingTo- ? {- quotedMessage: {- id: replyingTo.waMessageId || replyingTo.id,- body: replyingTo.type !== 'text' ? `[${replyingTo.type}]` : replyingTo.body,- },- }- : undefined,- };-- appendMessage(selectedSessionId, activeChat.id, tempMessage);- onMessageAppended('outgoing');-- const currentAttachment = attachment;- const currentReplyingTo = replyingTo;- handleRemoveAttachment();- setReplyingTo(null);-- try {- let result;-- if (currentAttachment) {- let mediaType: 'image' | 'video' | 'audio' | 'document' = 'document';- const mime = currentAttachment.mimetype;- if (mime.startsWith('image/')) mediaType = 'image';- else if (mime.startsWith('video/')) mediaType = 'video';- else if (mime.startsWith('audio/')) mediaType = 'audio';-- result = await messageApi.sendMedia(selectedSessionId, activeChat.id, mediaType, {- base64: currentAttachment.base64,- mimetype: currentAttachment.mimetype,- filename: currentAttachment.filename,- caption: mediaType !== 'audio' ? textToSend : undefined,- });- } else if (currentReplyingTo) {- result = await messageApi.reply(selectedSessionId, {- chatId: activeChat.id,- quotedMessageId: currentReplyingTo.waMessageId || currentReplyingTo.id,- text: textToSend,- });- } else {- result = await messageApi.sendText(selectedSessionId, activeChat.id, textToSend);- }-- // Race guard: the realtime `message.sent` echo can arrive before this response and already- // append the message by its real WA id (the dedup at receive time misses because the- // optimistic placeholder still carries the temp id). If so, fold the placeholder INTO the- // echo's row via mergeOrAppend instead of just dropping it — the echo carries no media- // payload (engine parity marker), so dropping the placeholder would erase the attachment's- // base64 and leave a bare "📎 Media" bubble until the next refetch.- const sendKey = messagesQueryKey(selectedSessionId, activeChat.id);- queryClient.setQueryData<ChatMessageView[]>(sendKey, (prev = []) => {- const reconciled: ChatMessageView = {- ...tempMessage,- id: result.messageId,- waMessageId: result.messageId,- status: 'sent',- };- const echoAlreadyAdded = prev.some(m => m.id === result.messageId || m.waMessageId === result.messageId);- if (echoAlreadyAdded) {- return mergeOrAppend(- prev.filter(m => m.id !== tempId),- reconciled,- );- }- return prev.map(m => (m.id === tempId ? reconciled : m));- });-- // Update sidebar chat list (move active chat to the top with the new snippet)- const snippet = currentAttachment ? `[${currentAttachment.mimetype.split('/')[0]}]` : textToSend;- const sentAt = Math.floor(Date.now() / 1000);- setChats(prevChats => promoteChatWithSnippet(prevChats, activeChat.id, snippet, sentAt));- } catch (err) {- showErrorToast(t('chats.errors.send'), err instanceof Error ? err.message : undefined);- updateMessage(selectedSessionId, activeChat.id, tempId, { status: 'failed' });- } finally {- setSending(false);- }- };-// Helper formats- const formatTime = (timestamp?: number) => {- if (!timestamp) return '';- return new Date(timestamp * 1000).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });- };-- const formatLastMessageSnippet = (chat: Chat) => chat.lastMessage || '';-const formatChatTime = useCallback((timestamp?: number) => {if (!timestamp) return '';@@ -1214,46 +732,6 @@ export function Chats() {if (el) el.scrollTop = el.scrollHeight;}, [activeStatusGroup?.contact.id, activeStatusGroup?.items]);- // Shared row markup for the Chats and Status lists — a plain function (not memoized) since it- // closes over render-scoped state (activeChat, listPics) that already changes every render.- const renderChatRow = (chat: Chat) => {- const isActive = activeChat?.id === chat.id;- return (- <div key={chat.id} className={`chat-item-card ${isActive ? 'active' : ''}`} onClick={() => setActiveChat(chat)}>- <ChatAvatar pictureUrl={listPics.data?.[chat.id]} kind={chat.kind} />-- <div className="chat-item-info">- <div className="chat-item-top">- <span className="chat-item-name" title={chat.name || chat.id}>- {chat.name || chat.id.split('@')[0]}- </span>- {chat.kind !== 'individual' && chat.kind !== 'unknown' && (- <span className={`chat-kind-badge kind-${chat.kind}`}>{t(`chats.kind.${chat.kind}`)}</span>- )}- {/* Ternary, not `&&`: a chat with no messages carries timestamp 0, and React- renders the number 0 as text — so `0 && <span/>` painted a literal "0"- where the time belongs, on every such row. */}- {chat.timestamp ? <span className="chat-item-time">{formatChatTime(chat.timestamp)}</span> : null}- </div>- <div className="chat-item-bottom">- <span className="chat-item-snippet" title={formatLastMessageSnippet(chat)}>- {formatLastMessageSnippet(chat) || <span className="no-message">{t('chats.noMessageYet')}</span>}- </span>- {chat.unreadCount > 0 && (- <span- className="chat-unread-badge"- title={t('chats.unreadBadge', { count: chat.unreadCount })}- aria-label={t('chats.unreadBadge', { count: chat.unreadCount })}- >- {chat.unreadCount > 99 ? '99+' : chat.unreadCount}- </span>- )}- </div>- </div>- </div>- );- };-// Image media items for the lightbox, in render order. `getMediaSrc` reconstructs a usable src// from either a base64 payload or a URL — the ChatMessageView shape stores both in `data`.const imageMedia = useMemo<LightboxItem[]>(@@ -1308,180 +786,39 @@ export function Chats() {) : (<div className={`chats-layout ${activeChat || activeChannel || activeStatusGroup ? 'has-active-chat' : ''}`}>{/* LEFT SIDEBAR: session & chat rooms */}- <aside className="chats-sidebar">- <div className="sidebar-header-box">- {/* Session selector */}- <div className="session-select-group">- <label className="form-label">{t('chats.sessionLabel')}</label>- <select- value={selectedSessionId}- onChange={e => setSelectedSessionId(e.target.value)}- className="session-selector"- >- {sessions.map(s => (- <option key={s.id} value={s.id}>- {s.name} ({s.phone || t('chats.noPhone')})- </option>- ))}- </select>- </div>-- {/* Chats / Channels / Status tabs */}- <div className="chats-tabs" role="tablist">- {(['chats', 'channels', 'status'] as const).map(tab => (- <button- key={tab}- type="button"- role="tab"- aria-selected={activeTab === tab}- className={`chats-tab ${activeTab === tab ? 'active' : ''}`}- onClick={() => switchTab(tab)}- >- {t(`chats.tab.${tab}`)}- </button>- ))}- </div>-- {/* Search bar */}- <div className="chat-search-input">- <Search size={18} />- <input- type="text"- placeholder={t('chats.searchPlaceholder')}- value={searchQuery}- onChange={e => setSearchQuery(e.target.value)}- />- </div>-- {/* Compose a new status — only meaningful on the Status tab. */}- {activeTab === 'status' && (- <button type="button" className="btn-primary status-compose-trigger" onClick={() => setComposeOpen(true)}>- <Plus size={16} />- {t('chats.status.compose')}- </button>- )}- </div>-- {/* Chat list */}- {activeTab === 'chats' && (- <div className="chats-list">- {loadingChats ? (- <div className="chats-list-loading">- <Loader2 className="animate-spin" size={24} />- <span>{t('chats.loadingChats')}</span>- </div>- ) : filteredChats.length === 0 ? (- <div className="chats-list-empty">- <span>{t('chats.empty')}</span>- </div>- ) : (- filteredChats.map(renderChatRow)- )}- </div>- )}-- {/* Channels list — wwjs-only (newsletter/channel API isn't implemented on Baileys, which- throws 501 for both listing and reading). channelsQuery is gated off entirely on that- engine, so the branch order below never depends on a request having actually run. */}- {activeTab === 'channels' && (- <div className="chats-list">- {currentEngine.isLoading ? (- <div className="chats-list-loading">- <Loader2 className="animate-spin" size={24} />- </div>- ) : !channelsSupported ? (- <div className="chats-list-empty">- <span>{t('chats.channels.notSupported')}</span>- </div>- ) : channelsQuery.isLoading ? (- <div className="chats-list-loading">- <Loader2 className="animate-spin" size={24} />- </div>- ) : channelsQuery.error ? (- <div className="chats-list-empty">- <AlertCircle size={24} className="text-warn" />- <span>{t('chats.channels.notReady')}</span>- </div>- ) : (channelsQuery.data?.length ?? 0) === 0 ? (- <div className="chats-list-empty">- <span>{t('chats.channels.empty')}</span>- </div>- ) : (- filteredChannels.map(ch => (- <div- key={ch.id}- className={`chat-item-card ${activeChannel?.id === ch.id ? 'active' : ''}`}- onClick={() => setActiveChannel(ch)}- >- <div className="chat-avatar">- <Megaphone size={20} />- </div>- <div className="chat-item-info">- <div className="chat-item-top">- <span className="chat-item-name">{ch.name}</span>- </div>- {ch.subscriberCount != null && (- <div className="chat-item-bottom">- <span className="chat-item-snippet">- {t('chats.channels.subscribers', { count: ch.subscriberCount })}- </span>- </div>- )}- </div>- </div>- ))- )}- </div>- )}-- {/* Status list — per-contact status groups read from the 24h store. Not engine-gated:- both engines now have status content. */}- {activeTab === 'status' && (- <div className="chats-list">- {statusesQuery.isLoading ? (- <div className="chats-list-loading">- <Loader2 className="animate-spin" size={24} />- </div>- ) : statusesQuery.isError ? (- <div className="chats-list-empty">- <AlertCircle size={24} className="text-warn" />- <span>{t('chats.status.loadError')}</span>- </div>- ) : groupedStatuses.length === 0 ? (- <div className="chats-list-empty">- <span>{t('chats.status.empty')}</span>- </div>- ) : (- groupedStatuses.map(group => (- <div- key={group.contact.id}- className={`chat-item-card ${activeStatusContactId === group.contact.id ? 'active' : ''}`}- onClick={() => setActiveStatusContactId(group.contact.id)}- >- <div className="chat-avatar">- <CircleDashed size={20} />- </div>- <div className="chat-item-info">- <div className="chat-item-top">- <span className="chat-item-name">- {group.contact.name ?? group.contact.pushName ?? group.contact.id}- </span>- <span className="chat-item-time">- {formatChatTime(Math.floor(new Date(group.latest).getTime() / 1000))}- </span>- </div>- <div className="chat-item-bottom">- <span className="chat-item-snippet">- {t('chats.status.itemCount', { count: group.items.length })}- </span>- </div>- </div>- </div>- ))- )}- </div>- )}- </aside>+ <ChatSidebar+ sessions={sessions}+ selectedSessionId={selectedSessionId}+ onSelectSession={setSelectedSessionId}+ activeTab={activeTab}+ onSwitchTab={switchTab}+ searchQuery={searchQuery}+ onSearchQueryChange={setSearchQuery}+ onComposeStatus={() => setComposeOpen(true)}+ formatChatTime={formatChatTime}+ chatsTab={{+ loading: loadingChats,+ chats: filteredChats,+ activeChatId: activeChat?.id,+ pictures: listPics.data,+ onSelectChat: setActiveChat,+ }}+ channelsTab={{+ engineLoading: currentEngine.isLoading,+ supported: channelsSupported,+ query: channelsQuery,+ channels: filteredChannels,+ activeChannelId: activeChannel?.id,+ onSelectChannel: setActiveChannel,+ }}+ statusTab={{+ loading: statusesQuery.isLoading,+ error: statusesQuery.isError,+ groups: groupedStatuses,+ activeContactId: activeStatusContactId,+ onSelectContact: setActiveStatusContactId,+ }}+ />{/* RIGHT VIEW: active chat room */}<main className="chats-room">@@ -1523,380 +860,33 @@ export function Chats() {</div></header>- {/* Messages body. position:relative so the scroll-to-bottom button can float inside. */}- <div className="room-messages" ref={messagesContainerRef}>- {/* Floating scroll-to-bottom button. Hidden while loading (no height to measure yet)- and when the user is already at/near the bottom. */}- {showJumpToBottom && !loadingMessages && (- <button- type="button"- className="scroll-to-bottom-btn"- onClick={handleJumpToBottom}- aria-label={t('chats.scrollToBottom')}- title={t('chats.scrollToBottom')}- >- <ChevronDown size={22} />- </button>- )}- {loadingMessages ? (- <div className="messages-loading">- <Loader2 className="animate-spin" size={32} />- <span>{t('chats.loadingMessages')}</span>- </div>- ) : messagesError ? (- <div className="messages-empty">- <MessageSquare size={32} />- <span>{t('chats.loadMessagesError')}</span>- </div>- ) : messages.length === 0 ? (- <div className="messages-empty">- <MessageSquare size={32} />- <span>{t('chats.noMessagesInChat')}</span>- </div>- ) : (- messages.map((msg, index) => {- const isMe = msg.direction === 'outgoing';- const formattedTime = formatTime(- msg.timestamp || Math.floor(new Date(msg.createdAt).getTime() / 1000),- );-- // Label who posted, WhatsApp-style: only in groups, only on incoming messages,- // and only on the first of a consecutive run from the same sender (so a burst- // from one person isn't repeated on every bubble).- const prev = messages[index - 1];- const showSender = Boolean(- activeChat?.isGroup &&- !isMe &&- msg.chatName &&- // Key the run on the stable sender id (participant JID), not the display- // name — two participants who share a pushName must still start a new run.- (!prev || prev.direction === 'outgoing' || senderKey(prev) !== senderKey(msg)),- );-- const isMediaMessage = msg.type !== 'text';- const mediaInfo = msg.metadata?.media;-- const renderMedia = () => {- if (msg.type === 'revoked') return null;- // location/call have no downloadable media payload — render them before the- // mediaInfo gate. The raw body (a base64 thumbnail / empty token) is suppressed below.- if (msg.type === 'location') {- // WhatsApp location messages carry a base64 JPEG map-preview thumbnail in `body`.- const thumb = msg.body && msg.body.length > 100 ? `data:image/jpeg;base64,${msg.body}` : '';- return (- <div className="message-location">- {thumb && (- <img- src={thumb}- alt=""- onLoad={onMediaLoad}- style={{ maxWidth: 220, borderRadius: 8, display: 'block', marginBottom: 4 }}- />- )}- <span className="message-media-omitted">📍 {t('chats.media.location')}</span>- </div>- );- }- if (msg.type === 'call') {- const call = msg.metadata?.call;- const callKey = call?.video- ? call.missed- ? 'callVideoMissed'- : 'callVideo'- : call?.missed- ? 'callMissed'- : 'call';- return (- <div className="message-media-omitted">- {`${call?.video ? '📹' : '📞'} ${t(`chats.media.${callKey}`)}`}- </div>- );- }- if (!mediaInfo) return null;- if (mediaInfo.omitted) {- return <div className="message-media-omitted">📎 {t('chats.media.omitted')}</div>;- }- const mediaSrc = getMediaSrc(mediaInfo);- if (!mediaSrc) return null;-- switch (msg.type) {- case 'image':- case 'sticker':- return (- <div className="message-media-image">- <img- src={mediaSrc}- alt={mediaInfo.filename || t('chats.media.image')}- className="chat-image-media"- onLoad={onMediaLoad}- onClick={() => {- const idx = imageMedia.findIndex(x => x.id === msg.id);- if (idx >= 0) setLightboxIndex(idx);- }}- />- </div>- );- case 'video':- return (- <div className="message-media-video">- <video- src={mediaSrc}- controls- className="chat-video-media"- onLoadedData={onMediaLoad}- />- </div>- );- case 'audio':- case 'voice':- return (- <div className="message-media-audio">- <audio src={mediaSrc} controls className="chat-audio-media" />- </div>- );- case 'document':- default:- return (- <div className="message-media-document">- <a- href={mediaSrc}- download={mediaInfo.filename || 'document'}- className="chat-document-media"- >- 📎 {mediaInfo.filename || t('chats.downloadDocument')}- </a>- </div>- );- }- };-- const reactions = msg.metadata?.reactions || {};- const hasReactions = Object.keys(reactions).length > 0;- const isRevoked = msg.type === 'revoked';- const isMasked = msg.type === 'masked';-- return (- <div- key={msg.id}- className={`message-bubble-wrapper ${isMe ? 'outgoing' : 'incoming'}`}- data-wa-message-id={msg.waMessageId}- >- <div className="message-bubble-container">- <div- className={`message-bubble ${isMe ? 'outgoing' : 'incoming'} ${msg.status} ${- isMediaMessage ? 'media-type' : ''- } ${isRevoked ? 'revoked-type' : ''}`}- >- {/* Group sender label (WhatsApp-style: coloured name atop the bubble) */}- {/* Group sender label (WhatsApp-style: coloured name atop the bubble).- Colour keys on the stable sender id, so same-named participants- still get distinct colours; the label shows the human name. */}- {showSender && (- <div className="message-sender" style={{ color: senderColor(senderKey(msg)!) }}>- {msg.chatName}- </div>- )}-- {/* Quoted message display */}- {msg.metadata?.quotedMessage && (- <div className="message-quote-box">- <MessageBody text={msg.metadata.quotedMessage.body} className="quote-body" />- </div>- )}-- {renderMedia()}-- {isRevoked ? (- <div className="message-text">{t('chats.messageDeleted')}</div>- ) : isMasked ? (- <div className="message-text message-masked">{t('chats.messageMasked')}</div>- ) : (- msg.body &&- (!mediaInfo || msg.body !== mediaInfo.filename) &&- msg.type !== 'location' &&- msg.type !== 'call' && <MessageBody text={msg.body} className="message-text" />- )}-- <div className="message-meta">- <span className="message-time">{formattedTime}</span>- {isMe && (- <span className={`message-status-icon ${msg.status}`}>- {msg.status === 'pending' && '🕒'}- {msg.status === 'sent' && '✓'}- {msg.status === 'delivered' && '✓✓'}- {msg.status === 'read' && '✓✓'}- {msg.status === 'failed' && '⚠️'}- </span>- )}- </div>-- {/* Reactions display */}- {hasReactions && (- <div className="message-reactions-badge">- {Object.values(reactions)- .slice(0, 3)- .map((emoji, idx) => (- <span key={idx} className="reaction-emoji-span">- {emoji}- </span>- ))}- {Object.keys(reactions).length > 1 && (- <span className="reactions-count-span">{Object.keys(reactions).length}</span>- )}- </div>- )}- </div>-- {/* Message actions menu (hover) */}- {!isRevoked && (- <div className="message-actions-menu">- <button- type="button"- className="action-btn"- onClick={() => setReplyingTo(msg)}- title={t('chats.actions.reply')}- >- <CornerUpLeft size={14} />- </button>-- <div className="reaction-trigger-wrapper">- <button- type="button"- className="action-btn reaction-btn"- title={t('chats.actions.react')}- >- <Smile size={14} />- </button>- <div className="reaction-quick-popover">- {['👍', '❤️', '😂', '😮', '😢', '🙏'].map(emoji => (- <button key={emoji} type="button" onClick={() => handleReactMessage(msg, emoji)}>- {emoji}- </button>- ))}- </div>- </div>-- {isMe && msg.status !== 'pending' && (- <button- type="button"- className="action-btn delete-btn"- onClick={() => handleDeleteMessage(msg)}- title={t('chats.actions.delete')}- >- <Trash2 size={14} />- </button>- )}- </div>- )}- </div>- </div>- );- })- )}- </div>+ {/* Messages body (list, media, reactions, scroll-to-bottom) — components/chats/ChatThread. */}+ <ChatThread+ activeChat={activeChat}+ messages={messages}+ loadingMessages={loadingMessages}+ messagesError={messagesError}+ messagesContainerRef={messagesContainerRef}+ onMediaLoad={onMediaLoad}+ onOpenImage={messageId => {+ const idx = imageMedia.findIndex(x => x.id === messageId);+ if (idx >= 0) setLightboxIndex(idx);+ }}+ onReply={setReplyingTo}+ onReact={handleReactMessage}+ onDelete={handleDeleteMessage}+ />- {/* Attachment preview banner */}- {attachment && (- <div className="attachment-preview-banner">- {previewUrl ? (- <img src={previewUrl} alt={attachment.filename} className="preview-thumbnail" />- ) : (- <div className="preview-file-icon">📎</div>- )}- <div className="preview-file-info">- <span className="preview-filename">{attachment.filename}</span>- <span className="preview-filesize">({(attachment.file.size / 1024).toFixed(1)} KB)</span>- </div>- <button className="btn-remove-attachment" onClick={handleRemoveAttachment}>- <X size={18} />- </button>- </div>- )}-- {/* Popular emojis panel */}- {showEmojiPicker && (- <div className="chats-emoji-picker">- <div className="emoji-grid">- {popularEmojis.map(emoji => (- <button key={emoji} type="button" className="emoji-btn" onClick={() => handleEmojiClick(emoji)}>- {emoji}- </button>- ))}- </div>- </div>- )}-- {/* Replying preview banner */}- {replyingTo && (- <div className="replying-preview-banner">- <div className="replying-preview-content">- <div className="replying-to-title">- {t('chats.replyingTo', {- name:- replyingTo.direction === 'outgoing'- ? t('chats.you')- : activeChat.name || activeChat.id.split('@')[0],- })}- </div>- <div className="replying-to-body">- {replyingTo.type !== 'text' ? `[${replyingTo.type}]` : replyingTo.body}- </div>- </div>- <button className="btn-close-reply" onClick={() => setReplyingTo(null)}>- <X size={18} />- </button>- </div>- )}-- {/* Message input bar */}- <footer className="room-input-footer">- <form onSubmit={handleSend} className="input-form">- <input type="file" ref={fileInputRef} onChange={handleFileChange} style={{ display: 'none' }} />-- <button- type="button"- onClick={triggerFileSelect}- disabled={!canWrite || sending}- className="btn-input-accessory"- title={t('chats.attachTitle')}- >- <Paperclip size={20} />- </button>-- <button- type="button"- onClick={() => setShowEmojiPicker(!showEmojiPicker)}- disabled={!canWrite || sending}- className={`btn-input-accessory ${showEmojiPicker ? 'active' : ''}`}- title={t('chats.emojiTitle')}- >- <Smile size={20} />- </button>-- <input- type="text"- placeholder={- canWrite- ? attachment- ? t('chats.captionPlaceholder')- : t('chats.messagePlaceholder')- : t('chats.noPermission')- }- value={messageInput}- onChange={e => setMessageInput(e.target.value)}- disabled={!canWrite || sending}- className="message-text-input"- />- <button- type="submit"- disabled={!canWrite || (!messageInput.trim() && !attachment) || sending}- className="btn-send-message"- aria-label={t('chats.send')}- >- {sending ? <Loader2 className="animate-spin" size={24} /> : <Send size={28} strokeWidth={2.5} />}- </button>- </form>- </footer>+ {/* Composer: attachment preview, emoji panel, reply banner, input bar —+ components/chats/ChatComposer. */}+ <ChatComposer+ selectedSessionId={selectedSessionId}+ activeChat={activeChat}+ replyingTo={replyingTo}+ setReplyingTo={setReplyingTo}+ onMessageAppended={onMessageAppended}+ setChats={setChats}+ /></div>) : activeChannel ? (// Read-only channel pane: no send footer, reactions, delete, reply, or markChatRead —@@ -2008,138 +998,11 @@ export function Chats() {/>{composeOpen && (- <Modal- open- onClose={closeComposeModal}- title={t('chats.status.compose')}- closeLabel={t('common.close')}- className="status-compose-modal"- footer={- <>- <button className="btn-secondary" onClick={closeComposeModal} disabled={composePosting}>- {t('common.cancel')}- </button>- <button className="btn-primary" onClick={handleComposeSubmit} disabled={!composeCanSubmit}>- {composePosting ? <Loader2 className="animate-spin" size={16} /> : t('chats.status.post')}- </button>- </>- }- >- <div className="compose-type-toggle">- <button type="button" className={composeType === 'text' ? 'active' : ''} onClick={() => setComposeType('text')}>- {t('chats.status.composeText')}- </button>- <button- type="button"- className={composeType === 'image' ? 'active' : ''}- onClick={() => setComposeType('image')}- >- {t('chats.status.composeImage')}- </button>- </div>-- {composeType === 'text' ? (- <>- <div className="compose-field">- <label>{t('chats.status.composeText')}</label>- <textarea- value={composeText}- onChange={e => setComposeText(e.target.value)}- maxLength={4096}- placeholder={t('chats.status.composeText')}- />- </div>- <div className="compose-row">- <div className="compose-field">- <label>{t('chats.status.backgroundColor')}</label>- <input- type="color"- value={composeBgColor || '#000000'}- onChange={e => setComposeBgColor(e.target.value)}- />- </div>- <div className="compose-field">- <label>{t('chats.status.font')}</label>- <select value={composeFont} onChange={e => setComposeFont(e.target.value)}>- <option value="">{t('chats.status.fontDefault')}</option>- {/* The WhatsApp status font enum: 6 is the bold system face; 3–5 don't exist on- the wire and the backend rejects them. */}- {[0, 1, 2, 6, 7, 8, 9, 10].map(f => (- <option key={f} value={f}>- {f}- </option>- ))}- </select>- </div>- </div>- </>- ) : (- <>- <div className="compose-field">- <label>{t('chats.status.composeImage')}</label>- <input- type="url"- placeholder="https://example.com/image.jpg"- value={composeImageUrl}- onChange={e => handleComposeImageUrlChange(e.target.value)}- />- </div>- <p className="compose-image-or">{t('chats.status.orLabel')}</p>- <div className="compose-field">- <input- type="file"- accept="image/*"- ref={composeFileInputRef}- onChange={handleComposeImageFile}- />- </div>- <div className="compose-field">- <label>{t('chats.status.caption')}</label>- <input- type="text"- placeholder={t('chats.captionPlaceholder')}- value={composeCaption}- onChange={e => setComposeCaption(e.target.value)}- maxLength={1024}- />- </div>- </>- )}-- {isBaileysEngine && (- <div className="compose-field">- <label>{t('chats.status.recipients')}</label>- <input- type="text"- placeholder={t('common.search')}- value={composeRecipientSearch}- onChange={e => setComposeRecipientSearch(e.target.value)}- />- <div className="compose-recipients">- {composeContactsQuery.isLoading ? (- <div className="compose-recipients-empty">- <Loader2 className="animate-spin" size={16} />- </div>- ) : filteredComposeContacts.length === 0 ? (- <div className="compose-recipients-empty">{t('chats.status.noContacts')}</div>- ) : (- filteredComposeContacts.map(c => (- <label key={c.id} className="compose-recipient-row">- <input- type="checkbox"- checked={composeRecipients.includes(c.id)}- disabled={!composeRecipients.includes(c.id) && composeRecipients.length >= STATUS_RECIPIENTS_MAX}- onChange={() => toggleComposeRecipient(c.id)}- />- <span>{c.name || c.pushName || c.number || c.id}</span>- </label>- ))- )}- </div>- <p className="input-hint">{t('chats.status.recipientsHint')}</p>- </div>- )}- </Modal>+ <StatusComposeModal+ sessionId={selectedSessionId}+ onClose={() => setComposeOpen(false)}+ onPosted={() => statusesQuery.refetch()}+ />)}</div>);diff --git a/dashboard/src/test-helpers/jsdom.ts b/dashboard/src/test-helpers/jsdom.tsnew file mode 100644index 000000000..c5223b5ed--- /dev/null+++ b/dashboard/src/test-helpers/jsdom.ts@@ -0,0 +1,53 @@+// JSDOM bootstrap for component smoke tests under the bare `node --test` runner (no vitest/jest).+// Installs a JSDOM window/document (+ the globals React DOM and Testing Library need) onto+// globalThis. Call once, from a test file's `before()`, BEFORE dynamically importing any app+// module — some modules read `window.location.origin` at import time (useWebSocket).++/**+ * Installs JSDOM globals on globalThis. Idempotent: later calls replace the window with a fresh+ * one, which is what a second test file in the same process would want anyway.+ */+export async function installJsdomGlobals(url = 'http://localhost/'): Promise<void> {+ // jsdom ships no bundled types and @types/jsdom is not installed; import it untyped and narrow+ // to the one member this helper uses.+ // @ts-expect-error -- Could not find a declaration file for module 'jsdom'+ const { JSDOM } = await import('jsdom');+ const dom = new JSDOM('<!doctype html><html><body></body></html>', {+ url,+ // Gives the window requestAnimationFrame/cancelAnimationFrame (the scroll-position hook uses+ // them) and makes timers in jsdom behave like a visible tab.+ pretendToBeVisual: true,+ }) as { window: Window & typeof globalThis };+ const { window } = dom;++ const g = globalThis as Record<string, unknown>;+ const define = (key: string, value: unknown): void => {+ // Some globals are getter-only on Node's globalThis (navigator) — plain assignment throws.+ Object.defineProperty(globalThis, key, { value, configurable: true, writable: true });+ };+ define('window', window);+ define('document', window.document);+ define('navigator', window.navigator);+ // IDL accessors on the jsdom window brand-check `this`, so they can't be copied as descriptors+ // (calling them with this === globalThis throws "Illegal invocation"). Install them as values:+ // the storage/location objects themselves work with any receiver.+ define('localStorage', window.localStorage);+ define('sessionStorage', window.sessionStorage);+ define('location', window.location);+ define('getComputedStyle', window.getComputedStyle.bind(window));+ define('requestAnimationFrame', window.requestAnimationFrame.bind(window));+ define('cancelAnimationFrame', window.cancelAnimationFrame.bind(window));+ // Constructors and plain functions (HTMLElement, Node, Event, CustomEvent, MutationObserver,+ // FileReader, ...) — needed by React DOM's instanceof checks and Testing Library's queries.+ // Node's own globals (fetch, Response, crypto, Blob, ...) win by being skipped, not replaced.+ for (const key of Object.getOwnPropertyNames(window)) {+ if (key in globalThis) continue;+ const descriptor = Object.getOwnPropertyDescriptor(window, key);+ if (descriptor && 'value' in descriptor) {+ Object.defineProperty(globalThis, key, descriptor);+ }+ }+ // React 19 only runs act() when this flag is set; Testing Library drives act through it.+ g.IS_REACT_ACT_ENVIRONMENT = true;+ (window as unknown as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = true;+}diff --git a/dashboard/src/test-helpers/register-hooks.ts b/dashboard/src/test-helpers/register-hooks.tsnew file mode 100644index 000000000..7bbf4390e--- /dev/null+++ b/dashboard/src/test-helpers/register-hooks.ts@@ -0,0 +1,9 @@+/// <reference types="node" />+// Registers the ESM customization hooks that let the bare node:test runner load the dashboard's+// Vite-style sources (TSX, extensionless imports, CSS, JSON — see vite-shim-hooks.mjs). A test+// file must import this module for its side effect BEFORE any dynamic import of app modules:+// Node resolves+loads the entry file's static imports before user code runs, so app modules can+// only be pulled in dynamically after registration.+import { register } from 'node:module';++register('./vite-shim-hooks.mjs', import.meta.url);diff --git a/dashboard/src/test-helpers/vite-shim-hooks.mjs b/dashboard/src/test-helpers/vite-shim-hooks.mjsnew file mode 100644index 000000000..7121880b0--- /dev/null+++ b/dashboard/src/test-helpers/vite-shim-hooks.mjs@@ -0,0 +1,77 @@+// ESM customization hooks letting the bare `node --experimental-strip-types --test` runner load+// the dashboard's Vite-style sources:+// - .tsx → transpiled with the project's own TypeScript (jsx: react-jsx)+// - extensionless relative imports → resolved by trying .tsx/.ts/.js/.mjs/.json (and /index.*)+// - .json → wrapped as `export default` (Node would demand import attributes)+// - .css → stubbed as an empty module+// - .ts files reading import.meta.env → transpiled with a shim (import.meta.env is a Vite+// global Node does not provide); every other .ts falls through to --experimental-strip-types+//+// Registered via test-helpers/register-hooks.ts. node:test runs each test file in its own child+// process, so these hooks only ever affect the component smoke-test process — the 261 pure-logic+// tests never register them.+import { readFile } from 'node:fs/promises';+import { existsSync } from 'node:fs';+import path from 'node:path';+import { fileURLToPath, pathToFileURL } from 'node:url';+import { createRequire } from 'node:module';++const require = createRequire(import.meta.url);+const ts = require('typescript');++const RESOLVE_EXTENSIONS = ['.tsx', '.ts', '.js', '.mjs', '.json'];++export async function resolve(specifier, context, nextResolve) {+ try {+ return await nextResolve(specifier, context);+ } catch (error) {+ // Only patch up relative specifiers (Vite resolves these extensionless; Node does not).+ if (!specifier.startsWith('./') && !specifier.startsWith('../')) throw error;+ const base = path.resolve(path.dirname(fileURLToPath(context.parentURL)), specifier);+ for (const ext of RESOLVE_EXTENSIONS) {+ const candidate = base + ext;+ if (existsSync(candidate)) return { url: pathToFileURL(candidate).href, shortCircuit: true };+ }+ for (const ext of RESOLVE_EXTENSIONS) {+ const candidate = path.join(base, `index${ext}`);+ if (existsSync(candidate)) return { url: pathToFileURL(candidate).href, shortCircuit: true };+ }+ throw error;+ }+}++export async function load(url, context, nextLoad) {+ if (url.endsWith('.css')) {+ return { format: 'module', source: 'export default {};', shortCircuit: true };+ }+ if (url.endsWith('.json')) {+ const source = await readFile(fileURLToPath(url), 'utf8');+ return { format: 'module', source: `export default ${source};`, shortCircuit: true };+ }+ if (url.endsWith('.tsx')) {+ return { format: 'module', source: await transpile(url), shortCircuit: true };+ }+ if (url.endsWith('.ts')) {+ const source = await readFile(fileURLToPath(url), 'utf8');+ if (!source.includes('import.meta.env')) return nextLoad(url, context);+ return { format: 'module', source: await transpile(url, source), shortCircuit: true };+ }+ return nextLoad(url, context);+}++async function transpile(url, presetSource) {+ const fileName = fileURLToPath(url);+ const source = presetSource ?? (await readFile(fileName, 'utf8'));+ const { outputText } = ts.transpileModule(source, {+ compilerOptions: {+ target: ts.ScriptTarget.ES2022,+ module: ts.ModuleKind.ESNext,+ jsx: ts.JsxEmit.ReactJSX,+ esModuleInterop: true,+ },+ fileName,+ });+ // import.meta is extensible; seeding `env` keeps Vite-style `import.meta.env.X` reads working.+ const shim = source.includes('import.meta.env') ? 'import.meta.env ??= {};\n' : '';+ return shim + outputText;+}diff --git a/dashboard/src/utils/chatMessages.ts b/dashboard/src/utils/chatMessages.tsindex f1b778c6f..3add29aad 100644--- a/dashboard/src/utils/chatMessages.ts+++ b/dashboard/src/utils/chatMessages.ts@@ -105,7 +105,15 @@ export const senderKey = (m: Pick<ChatMessage, 'author' | 'chatName'>): string |// ChatMessageView extends ChatMessage with the view-only fields the chat page renders.// Lifted from Chats.tsx so hooks/utils can share the same shape.-type MessageMedia = { mimetype: string; filename?: string; data?: string; omitted?: boolean; sizeBytes?: number };+export type MessageMedia = { mimetype: string; filename?: string; data?: string; omitted?: boolean; sizeBytes?: number };++export const getMediaSrc = (media?: MessageMedia): string => {+ if (!media || !media.data) return '';+ if (media.data.startsWith('data:') || media.data.startsWith('http://') || media.data.startsWith('https://')) {+ return media.data;+ }+ return `data:${media.mimetype};base64,${media.data}`;+};export interface ChatMessageView extends ChatMessage {metadata?: {