Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.
Python agentagentic-aiagentic-frameworkagentic-workflowaiautomationclaudedeepseekgenaigptllmlow-codemcpnextjsno-codeopenaipythonskillsworkflow
refactor(web): migrate Mermaid diagrams to Pele (#44293)
yyhbbfac7a93b6d
diff --git a/.github/workflows/web-tests.yml b/.github/workflows/web-tests.ymlindex fbe7ba5bc47..13e2701286b 100644--- a/.github/workflows/web-tests.yml+++ b/.github/workflows/web-tests.yml@@ -70,7 +70,18 @@ jobs:run: vp exec playwright install --with-deps --only-shell chromium- name: Run browser tests- run: vp test run --project browser --silent=passed-only+ run: vp test run --project browser --silent=passed-only --coverage++ - name: Report browser coverage+ uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 # v7.1.1+ with:+ files: web/coverage/coverage-final.json+ disable_search: true+ fail_ci_if_error: true+ flags: web+ name: web-browser+ env:+ CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}- name: Upload browser failure artifactsif: ${{ failure() && !cancelled() }}diff --git a/oxlint-suppressions.json b/oxlint-suppressions.jsonindex 61939d0ce07..9cc0bf14357 100644--- a/oxlint-suppressions.json+++ b/oxlint-suppressions.json@@ -692,22 +692,6 @@"count": 5}},- "web/app/components/base/mermaid/index.tsx": {- "jsx-a11y/click-events-have-key-events": {- "count": 1- },- "jsx-a11y/no-static-element-interactions": {- "count": 1- },- "regexp/no-super-linear-backtracking": {- "count": 3- }- },- "web/app/components/base/mermaid/utils.ts": {- "typescript/no-explicit-any": {- "count": 2- }- },"web/app/components/base/node-status/index.tsx": {"react/only-export-components": {"count": 1diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 5519219c5e0..f3a7cd8c55e 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -599,9 +599,6 @@ catalogs:mediabunny:specifier: 1.61.3version: 1.61.3- mermaid:- specifier: 11.17.2- version: 11.17.2mime:specifier: 4.1.0version: 4.1.0@@ -626,6 +623,9 @@ catalogs:open:specifier: 11.0.4version: 11.0.4+ pele:+ specifier: 1.6.0+ version: 1.6.0picocolors:specifier: 1.1.1version: 1.1.1@@ -1567,9 +1567,6 @@ importers:mediabunny:specifier: 'catalog:'version: 1.61.3- mermaid:- specifier: 'catalog:'- version: 11.17.2mime:specifier: 'catalog:'version: 4.1.0@@ -1591,6 +1588,9 @@ importers:nuqs:specifier: 'catalog:'version: 2.10.2([email protected](@babel/[email protected]([email protected]))(@playwright/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected]))([email protected])+ pele:+ specifier: 'catalog:'+ version: 1.6.0qrcode.react:specifier: 'catalog:'version: 4.2.0([email protected])@@ -2038,18 +2038,12 @@ packages:'@blazediff/[email protected]':resolution: {integrity: sha512-AOQff0zgR7cGsZL+4E7hVkmujoPUpm0J9xzWGWZj5wCjd3gmxESXAPfKyuzs93VdpQNFhHlBhfOjrcZ+XTERtQ==}- '@braintree/[email protected]':- resolution: {integrity: sha512-jigsZK+sMF/cuiB7sERuo9V7N9jx+dhmHHnQyDSVdpZwVutaBu7WvNYqMDLSgFgfB30n452TP3vjDAvFC973mA==}-'@cacheable/[email protected]':resolution: {integrity: sha512-CTLKqLItRCEixEAewD3/j9DB3/o96gpTPD4eJ1v+DGOlxZRZncRQkGYqqnAGCscYd6RNeXfGeiuCphsPtqyIfQ==}'@cacheable/[email protected]':resolution: {integrity: sha512-buipgOVDkkPXNR5+xBpDw7Zk2n1EvU7qBJCNUcL7rhQ//kfpOXPAvQ511Os0vpLYJ1pZnvudNytkQt2hst3wqA==}- '@chevrotain/[email protected]':- resolution: {integrity: sha512-U+HFai5+zmJCkK86QsaJtoITlboZHBqrVketcO2ROv865xfCMSFpELQoz1GkX5GzME8pTa+3kbKrZHQtI0gdbw==}-'@chromatic-com/[email protected]':resolution: {integrity: sha512-U4Rny8H6BBa8uiRMnL0CFZyqZ0MWogN/szlMugsInfSnX+PtrLCVp2kjrvaG9bv6X5xSgHpnmepOzLm8+QFseA==}engines: {node: '>=20.0.0', yarn: '>=1.22.18'}@@ -2981,9 +2975,6 @@ packages:peerDependencies:mediabunny: ^1.0.0- '@mermaid-js/[email protected]':- resolution: {integrity: sha512-n12NohV3mrUyUL2o93IgG/ifeW9FTyeJn3zDxkhwa8MJ9Fxg3HQMlA3RiGmD/3UnJvheztkjjQAjA2T4LmUcpw==}-'@monaco-editor/[email protected]':resolution: {integrity: sha512-gIwR1HrJrrx+vfyOhYmCZ0/JcWqG5kbfG7+d3f/C1LXk2EvzAbHSg3MQ5lO2sMlo9izoAZ04shohfKLVT6crVA==}@@ -5142,9 +5133,6 @@ packages:next:optional: true- '@upsetjs/[email protected]':- resolution: {integrity: sha512-WbBhLrooyePuQ1VZxrJjtLvTc4NVfpOyKx0sKqioq9bX1C1m7Jgykkn8gLrtwumBioXIqam8DLxp88Adbue6Hw==}-'@valibot/[email protected]':resolution: {integrity: sha512-3qkmU6KXWh8GIThEAW3kuRHPQBMjWkKy+Ppz3WkUucx53DTpOa6siMn4xDGSOhlVyMrDaJTCTMLYPZVAIk1P0A==}peerDependencies:@@ -5969,12 +5957,6 @@ packages:resolution: {integrity: sha512-gklSft7IuhriZKHKpuoA1fpJSLPNgvUMWMo5BlnzAJm0zNKnznoSv23IjtNqclx8eKi6ZcdvFFzYEER/+U1LoQ==}- resolution: {integrity: sha512-s9whTXInMSgAp/NVXVNuVxVKzGH2qck3aQlVHxDCdAEPgtMKwc4Wq6/QKhgdEdgbLSi9rBTAcPoRa6JpiG4ksg==}-- resolution: {integrity: sha512-AzlgcsCbUMymkADOJtQm3wO9S3ltPfYOFD5033keQn9NJzIbtnZj+UdBJe7DYml/8TdbtHJW3j58SOnKhWY/5g==}-resolution: {integrity: sha512-pKRrRagItwk9rGIStcUyMxFX34x56zoX3KDf9HJ4ttwkXIK1qxK63EvXvEDmlxI9AdPJ+Y7TEKRftRlW5eSS7A==}engines: {node: '>=18'}@@ -6047,51 +6029,10 @@ packages:resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==}- resolution: {integrity: sha512-wgQlVIUJF13Quxiv5e1gstZ08rnZj2XaLHGoFMYXz7SkNfCDOOteKBE6SYRfA9WxxI/iBc3ajfDoc6hb/MRAHQ==}- peerDependencies:- cytoscape: ^3.2.0-- resolution: {integrity: sha512-ki1/VuRIHFCzxWNrsshHYPs6L7TvLu3DL+TyIGEsRcvVERmxokbf5Gdk7mFxZnTdiGtnA4cfSmjZJMviqSuZrQ==}- peerDependencies:- cytoscape: ^3.2.0-- resolution: {integrity: sha512-62rNSrioXw93uliKFBwjukeQyeWwH2PqDrTac31r2P6464u3AUvTk0xS4LVvT251g7IgkFunrI48ZEZGjywSOg==}- engines: {node: '>=0.10'}-- resolution: {integrity: sha512-B0ErZK/66mHtEsR1TkPEEkwdy+WDesimkM5gpZr5Dsg54BiTA5RXtYW5qTLIAcekaS9xfZrzBLF/OAkB3Qn1YQ==}-- resolution: {integrity: sha512-tdQAmyA18i4J7wprpYq8ClcxZy3SC31QMeByyCFyRt7BVHdREQZ5lpzoe5mFEYZUWe+oq8HBvk9JjpibyEV4Jg==}- engines: {node: '>=12'}-- resolution: {integrity: sha512-IH5tgjV4jE/GhHkRV0HiVYPDtvfjHQlQfJHs0usq7M30XcSBvOotpmH1IgkcXsO/5gEQZD43B//fc7SRT5S+xw==}- engines: {node: '>=12'}-- resolution: {integrity: sha512-ALnjWlVYkXsVIGlOsuWH1+3udkYFI48Ljihfnh8FZPF2QS9o+PzGLBslO0PjzVoHLZ2KCVgAM8NVkXPJB2aNnQ==}- engines: {node: '>=12'}-- resolution: {integrity: sha512-VE5S6TNa+j8msksl7HwjxMHDM2yNK3XCkusIlpX5kwauBfXuyLAtNg9jCp/iHH61tgI4sb6R/EIMWCqEIdjT/g==}- engines: {node: '>=12'}-resolution: {integrity: sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA==}engines: {node: '>=12'}- resolution: {integrity: sha512-4EzFTRIikzs47RGmdxbeUvLWtGedDUNkTcmzoeyg4sP/dvCexO47AaQL7VKy/gul85TOxw+IBgA8US2xwbToNA==}- engines: {node: '>=12'}-- resolution: {integrity: sha512-mdjtIZ1XLAM8bm/hx3WwjfHt6Sggek7qH043O8KEjDXN40xi3vx/6pYSVTwLjEgiXQTbvaouWKynLBiUZ6SK6A==}- engines: {node: '>=12'}-resolution: {integrity: sha512-rzUyPU/S7rwUflMyLc1ETDeBj0NRuHKKAcvukozwhshr6g6c5d8zh4c2gQjY2bZ0dXeGLWc1PF174P2tVvKhfg==}engines: {node: '>=12'}@@ -6100,88 +6041,18 @@ packages:resolution: {integrity: sha512-pWbUJLdETVA8lQNJecMxoXfH6x+mO2UQo8rSmZ+QqxcbyA3hfeprFgIT//HW2nlHChWeIIMwS2Fq+gEARkhTkg==}engines: {node: '>=12'}- resolution: {integrity: sha512-UG6OvdI5afDIFP9w4G0mNq50dSOsXHJaRE8arAS5o9ApWnIElp8GZw1Dun8vP8OyHOZ/QJUKUJwxiiCCnUwm+Q==}- engines: {node: '>=12'}- hasBin: true-resolution: {integrity: sha512-wR/XK3D3XcLIZwpbvQwQ5fK+8Ykds1ip7A2Txe0yxncXSdq1L9skcG7blcedkOX+ZcgxGAmLX1FrRGbADwzi0w==}engines: {node: '>=12'}- resolution: {integrity: sha512-kpkQIM20n3oLVBKGg6oHrUchHM3xODkTzjMoj7aWQFq5QEM+R6E4WkzT5+tojDY7yjez8KgCBRoj4aEr99Fdqw==}- engines: {node: '>=12'}-- resolution: {integrity: sha512-zxV/SsA+U4yte8051P4ECydjD/S+qeYtnaIyAs9tgHCqfguma/aAQDjo85A9Z6EKhBirHRJHXIgJUlffT4wdLg==}- engines: {node: '>=12'}-- resolution: {integrity: sha512-AJDdYOdnyRDV5b6ArilzCPPwc1ejkHcoyFarqlPqT7zRYjhavcT3uSrqcMvsgh2CgoPbK3RCwyHaVyxYcP2Arg==}- engines: {node: '>=12'}-- resolution: {integrity: sha512-637ln3gXKXOwhalDzinUgY83KzNWZRKbYubaG+fGVuc/dxO64RRljtCTnf5ecMyE1RIdtqpkVcq0IbtU2S8j2Q==}- engines: {node: '>=12'}-- resolution: {integrity: sha512-FX/9frcub54beBdugHjDCdikxThEqjnR93Qt7PvQTOHxyiNCAlvMrHhclk3cD5VeAaq9fxmfRp+CnWw9rEMBuA==}- engines: {node: '>=12'}-resolution: {integrity: sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g==}engines: {node: '>=12'}- resolution: {integrity: sha512-VLaYcn81dtHVTjEHd8B+pbe9yHWpXKZUC87PzoFmsFrJqgFwDe/qxfp5MlfsfM1V5E/iVt0MmEbWQ7FVIXh/bg==}-- resolution: {integrity: sha512-p3KP5HCf/bvjBSSKuXid6Zqijx7wIfNW+J/maPs+iwR35at5JCbLUT0LzF1cnjbCHWhqzQTIN2Jpe8pRebIEFQ==}- engines: {node: '>=12'}-- resolution: {integrity: sha512-3vbA7vXYwfe1SYhED++fPUQlWSYTTGmFmQiany/gdbiWgU/iEyQzyymwL9SkJjFFuCS4902BSzewVGsHHmHtXg==}- engines: {node: '>=12'}-- resolution: {integrity: sha512-04xDrxQTDTCFwP5H6hRhsRcb9xxv2RzkcsygFzmkSIOJy3PeRJP7sNk3VRIbKXcog561P9oU0/rVH6vDROAgUw==}- engines: {node: '>=12'}-- resolution: {integrity: sha512-FXMe9GfxTxqd5D6jFsQ+DJ8BJS4E/fT5mqqdjovykEB2oFbTMDVdg1MGFxfQW+FBOGoB++k8swBrgwSHT1cUXQ==}- engines: {node: '>=12'}-- resolution: {integrity: sha512-nQhsBRmM19Ax5xEIPLMY9ZmJ/cDvd1BG3UVvt5h3WRxKg5zGRbvnteTyWAbzeSvlh3tW7ZEmq4VwR5mB3tutmQ==}-- resolution: {integrity: sha512-A3s5PWiZ9YCXFye1o246KoscMWqf8BsD9eRiJ3He7C9OBaxKhAd5TFCdEx/7VbKtxxTsu//1mMJFrEt572cEyQ==}- engines: {node: '>=12'}-- resolution: {integrity: sha512-GZW464g1SH7ag3Y7hXjf8RoUuAFIqklOAq3MRl4OaWabTFJY9PN/E1YklhXLh+OQ3fM9yS2nOkCoS+WLZ6kvxQ==}- engines: {node: '>=12'}-resolution: {integrity: sha512-fmTRWbNMmsmWq6xJV8D19U/gw/bwrHfNXxrIN+HfZgnzqTHp9jOmKMhsTUjXOJnZOdZY9Q28y4yebKzqDKlxlQ==}engines: {node: '>=12'}- resolution: {integrity: sha512-EUkvKjqPFUAZyOlhY5gzCxCeI0Aep04LwIRpsZ/mLFelJiUfnK56jo5JMDSE7yyP2kLSb6LtF+S5chMk7uqPqw==}-- resolution: {integrity: sha512-SaLBuwGm3MOViRq2ABk3eLoxwZELpH6zhl3FbAoJ7Vm1gofKx6El1Ib5z23NUEhF9AsGl7y+dzLe5Cw2AArGTA==}- engines: {node: '>=12'}-- resolution: {integrity: sha512-dJxPBlzC7NugB2PDLwo9Q8JiTR3M3e4/XANkreKSUxF8vvXKqm1Yfq4Q5dl8budlunRVlUUaDUgFt7eA8D6NLg==}- engines: {node: '>=12'}-- resolution: {integrity: sha512-VqKjzBLejbSMT4IgbmVgDjpkYrNWUYJnbCGo874u7MMKIWsILRX+OpX/gTk8MqjpT1A/c6HY2dCA77ZN0lkQ2Q==}- engines: {node: '>=12'}-resolution: {integrity: sha512-ndfJ/JxxMd3nw31uyKoY2naivF+r29V+Lc0svZxe1JvvIRmi8hUsrMvdOwgS1o6uBHmiz91geQ0ylPP0aj1VUA==}engines: {node: '>=12'}@@ -6196,13 +6067,6 @@ packages:resolution: {integrity: sha512-b8AmV3kfQaqWAuacbPuNbL6vahnOJflOhexLzMMNLga62+/nh0JzvJ0aO/5a5MVgUFGS7Hu1P9P03o3fJkDCyw==}engines: {node: '>=12'}- resolution: {integrity: sha512-e1U46jVP+w7Iut8Jt8ri1YsPOvFpg46k+K8TpCb0P+zjCkjkPnV7WzfDJzMHy1LnA+wj5pLT1wjO901gLXeEhA==}- engines: {node: '>=12'}-- resolution: {integrity: sha512-P4rFMVq9ESWqmOgK+dlXvOtLwYg0i7u0HBGJER0LZDJT2VHIPAMZ/riPxqJceWMStH5+E61QxFra9kIS3AqdMg==}-resolution: {integrity: sha512-+1UMbeh68lH1SegH83CGWwpb6OHHbpSgr3+s5Eww5M4CAgswBpoWS0AjTOfEJ33HiYKz1hdj/KTFprzXHmq/6w==}@@ -6270,9 +6134,6 @@ packages:resolution: {integrity: sha512-7z22QmUWiQ/2d0KkdYmANbRUVABpZ9SNYyH5vx6PZ+nE5bcC0l7uFvEfHlyld/HcGBFTL536ClDt3DEcSlEJAQ==}- resolution: {integrity: sha512-AGrQ4QSgssa1NGmWmLPqN5NY2KajF5MqxetNEO+o0n3ZwZZeTmt7bBnvzHWrmkZFxGgr4HdyFgelzgi06otLuQ==}-resolution: {integrity: sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==}engines: {node: '>=6'}@@ -6748,9 +6609,6 @@ packages:resolution: {integrity: sha512-GZMtZUTNRpOVIECoXwLNZS5xUGE+mVNbTB8h/7Rwh2TFWcBQiPzTgyZi05BF9UMZKkLJv8XBRJTlU7zg8+ZfMg==}- resolution: {integrity: sha512-LB+xjSTEbjHE1cWsxu+tN2Xqr1kpi+V9aADI7sVM5ZMaXyYGPHULQMzpJMYqOTULK/73pUkWVzzObFRBkPr+hg==}-resolution: {integrity: sha512-GGToxJ/w1x32s/D2EKND7kTil4n8OVk/9mycTc4VDza13lOvpUZTGX3mFSCtV9ksdGBVzvsyAVLM6mHFThxXxw==}@@ -6911,9 +6769,6 @@ packages:crossws:optional: true- resolution: {integrity: sha512-3GKBOn+m2LX9iq+JC1064cSFprJY4jL1jCXTcpnfER5HYE2l/4EfWSGzkPa/ZDBmYI0ZOEj5VHV/eKnPGkHuOg==}-resolution: {integrity: sha512-5DDsf4QmEIlRL6NkCv/fxSjYHHkZceL/IaYQdJc2h3G7DRTEai++VTjbfL0LB9geW2VrA3+vrjF3Efx+OTtX0Q==}engines: {node: '>=20.0.0'}@@ -7082,13 +6937,6 @@ packages:resolution: {integrity: sha512-Nb2ctOyNR8DqQoR0OwRG95uNWIC0C1lCgf5Naz5H6Ji72KZ8OcFZLz2P5sNgwlyoJ8Yif11oMuYs5pBQa86csA==}- resolution: {integrity: sha512-lDB5YccMydFBtasVtxnZ3MRBHuaoE8GKsppq+EchKL2U4nK/DmEpPHNH8MZe5HkMtpSiTSOZwfN0tzYjO/lJEw==}-- resolution: {integrity: sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg==}- engines: {node: '>=12'}-resolution: {integrity: sha512-9VGk3HGanVE6JoZXHiCpnGy5X0jYDnN4EA4lntFPj+1vIWlFhIylq2CrrCOJH9EAhc5CYhq18F2Av2tgoAPsYQ==}engines: {node: '>= 10'}@@ -7257,9 +7105,6 @@ packages:resolution: {integrity: sha512-CYDD3SOtsHtyXeEORYRx2qBtpDJFjRTGXUtmNEMGyzYOKj1TE3tycdlho7kA1Ufx9OYWZzg52QFBGALTirzDSw==}- resolution: {integrity: sha512-Ls993zuzfayK269Svk9hzpeGUKob/sIgZzyHYdjQoAdQetRKpOLj+k/QQQ/6Qi0Yz65mlROrfd+Ev+1+7dz9Kw==}-resolution: {integrity: sha512-5Lp/ANJu3AkW5f+J+2QG14z7xKZGi/ybb5MU1EWjeGdt6MpuIaLpLFiyBi0ZKryTiuTHiJqo/WKJRaWYimvavw==}engines: {node: ^20.19.0 || >=22.12.0}@@ -7278,12 +7123,6 @@ packages:resolution: {integrity: sha512-W7e4UPmJRwW/YgMn9n3dG5RyzHWGOf31Zb0SmG4pYyH5PiL2KlNZHRo9eUOvozYVY2oqglTfidNKWUiOK6PAJA==}- resolution: {integrity: sha512-8h2oVEZNktL4BH2JCOI90iD1yXwL6iNW7KcCKT2QZgQJR2vbqDsldCTPRU9NifTCqHZci57XvQQ15YTu+sTYPg==}-- resolution: {integrity: sha512-dp3s92+uNI1hWIpPGH3jK2kxE2lMjdXdr+DH8ynZHpd6PUlH6x6cbuXnoMmiNumznqaNO31xu9e79F0uuZ0JFg==}-resolution: {integrity: sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==}engines: {node: '>= 0.8.0'}@@ -7464,9 +7303,6 @@ packages:resolution: {integrity: sha512-cvbTwETRfsFh4nHsL1eGWapU1XFi5Ot9E85sWAwia7Y7EgB7vfqcZhTKZ+l7hCGxSPoushMv5GKhT5PdLv03WA==}- resolution: {integrity: sha512-J8xewKD/Gk22OZbhpOVSwcs60zhd95ESDwezOFuA3/099925PdHJ7OFHNTGtajL3AlZkykD32HykiMo+BIBI8A==}-resolution: {integrity: sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==}@@ -7519,11 +7355,6 @@ packages:resolution: {integrity: sha512-wiYz4+JrLyb/DqW2hkFJxP7Vd7JuTDm77fvbM8VfEQdmSMqcImWeeRbHwZjBjIFki/VaMK2BhFi7oUUZeM5bqw==}- resolution: {integrity: sha512-TI3V8YYWvkVf3KJe1dRkpnjs68JUPyEa5vjKrp1XEEJUAOaQc+Qj+L1qWbPd0SJuAdQkFU0h73sXXqwDYxsiDA==}- engines: {node: '>= 20'}- hasBin: true-resolution: {integrity: sha512-PamYXWWWg2nboG3oX5Ffzpy3EFZROqZJK9hSlMmUnekp7TxPs5DcT95vwd46m73/exfKCRVMtgXoPMI4FEJL6w==}engines: {node: '>= 20'}@@ -7605,9 +7436,6 @@ packages:resolution: {integrity: sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==}engines: {node: '>= 8'}- resolution: {integrity: sha512-V6K3C8EBdEsPFZXSKMJe6ppQOENxuHARr9GvHX4hh47lAbhMRD9qf4oEK7LoaRQxULMa80/qt5gHO73aCleBBg==}-resolution: {integrity: sha512-RDBrHEMSxVFLg6xvnXmb1Ayr2WzLAWjeSATAoxwKYJV94TeNavgoIdA0a9ytzDSVzBy2YKFK+emCPOEibLeCrg==}@@ -8152,9 +7980,6 @@ packages:resolution: {integrity: sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g==}- resolution: {integrity: sha512-NOnmBpt5Y2RWbuv0LMzsayp3lVylAHLPUTut412ZA3l+C4uw4ZVkQbjShYCQ8TCpUMdPapr4YjUqLYD6v68j+w==}-resolution: {integrity: sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==}engines: {node: '>=8'}@@ -8185,6 +8010,10 @@ packages:resolution: {integrity: sha512-MbkAjpwka/dMHaCfQ75RY1FXX3IewBVu6NGZOcxerRFlaBiIkZmUoR0jotX5VUzYZEXAGzSFtknWs5xRKliXPA==}engines: {node: '>=18'}+ resolution: {integrity: sha512-VfAiVItsOGlGhvnBfphdT28VCG7mXMZxQNOwAGsCtxI2ztbUsT39MraEOYjsapLxVETkdUZscm0DdotYDQMLdw==}+ engines: {node: '>=20'}+resolution: {integrity: sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg==}@@ -8228,12 +8057,6 @@ packages:resolution: {integrity: sha512-Xj/T2X6DNAWbtk/9UQ0/TJRswltiHZevmcMjqoL7WrpJi67lu3qaslU4+I+zJ8wtwqmuvAE0KkB8rbv2ZdogBg==}- resolution: {integrity: sha512-0mYKnYYe9ZcqMCWhUjItv/oHjvgEsfKvnUTg8sAtnHr3GVy7rGkXCb6d5cSyqrWqL4k81b9CPg3urd+T7aop3A==}-- resolution: {integrity: sha512-25ClnWWuw7JbWZcgqY/gJ4FQWadKxGWk+3kR/7kD0tCaDtPPMj7oHu2ToLaVhfpnHrZzYby2w6tUA0eOIuUg8g==}-resolution: {integrity: sha512-rEwq/ZHlJIKw++XtLAO8PPuOQA/zaPJOZJ37BVuN97nLpMJeuDVLVGRwbFoBgLudgdTMP2hdRJP++H+8QOA3vg==}engines: {node: '>= 10.12'}@@ -8545,15 +8368,9 @@ packages:resolution: {integrity: sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==}engines: {iojs: '>=1.0.0', node: '>=0.10.0'}- resolution: {integrity: sha512-NS3levdsRIUOmiJ8FZWCP7LG3QpJyrs/TE0Zpf1yvZu8cAJJ6QMW92H1c7kWpdIHo8RvmLxN/o2JXTKHp74lUA==}-resolution: {integrity: sha512-ePa+XGk00/3HuCqrEnK3LxJW7I0SdNg6EFzKUJG73hMAdDcOUC/i/aSz7LSDwLrGr33kal/rqOGydzwl6U7zBA==}- resolution: {integrity: sha512-ZUz/69+SYpFN/g/lUlo2FXcIjRkSu3nDarreVdGGndHEBJ6cXPdKguS8JGxwj5HA5xIbVKSmLgr5b3AWxtRfvQ==}-resolution: {integrity: sha512-DPe5pVFaAsinSaV6QjQ6gdiedWDcRCbUuiQfQa2wmWV7+xC9bGulGI8+TdRmoFkAPaBXk8CrAbnlY2ISniJ47Q==}engines: {node: '>=18'}@@ -8561,9 +8378,6 @@ packages:resolution: {integrity: sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==}- resolution: {integrity: sha512-PdhdWy89SiZogBLaw42zdeqtRJ//zFd2PgQavcICDUgJT5oW10QCRKbJ6bg4r0/UY2M6BWd5tkxuGFRvCkgfHQ==}-resolution: {integrity: sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA==}@@ -8744,9 +8558,6 @@ packages:react: ^18.0.0 || ^19.0.0react-dom: ^18.0.0 || ^19.0.0- resolution: {integrity: sha512-cEmp9QeXXRmjj/rVp9oyiqcvyocWab/HaoN4+bwFeZ7QzykJD6L3yD4v12K1x0tHpqRqVpJevN3gW7kyM39Bqg==}-resolution: {integrity: sha512-aqD2Q0144Z+/RqG52NeHEkZauTAUWJO8c6yTftGJKO3Tja5tUgIfmIl6kExvhtxSDP7fXB6DvzkfMpCd/F3G+Q==}engines: {node: '>=0.6.19'}@@ -8813,9 +8624,6 @@ packages:babel-plugin-macros:optional: true- resolution: {integrity: sha512-5Z9ZpRzfuH6l/UAvCPAPUo3665Nk2wLaZU3x+TLHKVzIz33+sbJqbtrYoC3KD4/uVOr2Zp+L0LySezP9OHV9yA==}-resolution: {integrity: sha512-SS+jx45GF1QjgEXQx4NJZV9ImqmO2NPz5FNsIHrsDjh2YsHnawpan7SNQ1o8NuhrbHZy9AZhIoCUiCeaW/C80g==}engines: {node: '>=18'}@@ -9801,8 +9609,6 @@ snapshots:'@blazediff/[email protected]': {}- '@braintree/[email protected]': {}-'@cacheable/[email protected]':dependencies:'@cacheable/utils': 2.5.0@@ -9815,8 +9621,6 @@ snapshots:hashery: 1.5.1keyv: 5.6.0- '@chevrotain/[email protected]': {}-'@chromatic-com/[email protected]([email protected](@types/[email protected])([email protected])([email protected](@types/[email protected])(@typescript/[email protected])(@vitest/[email protected])(@vitest/[email protected])(@vitest/[email protected])(@volar/[email protected](@typescript/[email protected]))([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])))':dependencies:'@neoconfetti/react': 1.0.0@@ -10816,10 +10620,6 @@ snapshots:dependencies:mediabunny: 1.61.3- '@mermaid-js/[email protected]':- dependencies:- '@chevrotain/types': 11.1.2-'@monaco-editor/[email protected]':dependencies:state-local: 1.0.7@@ -12485,11 +12285,6 @@ snapshots:optionalDependencies:next: 16.4.1(@babel/[email protected]([email protected]))(@playwright/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])- '@upsetjs/[email protected]':- optionalDependencies:- d3-selection: 3.0.0- d3-transition: 3.0.1([email protected])-dependencies:valibot: 1.4.2(@typescript/[email protected])@@ -13285,14 +13080,6 @@ snapshots:- dependencies:- layout-base: 1.0.2-- dependencies:- layout-base: 2.0.1-dependencies:luxon: 3.7.2@@ -13366,50 +13153,8 @@ snapshots:- dependencies:- cose-base: 1.0.3- cytoscape: 3.34.0-- dependencies:- cose-base: 2.2.0- cytoscape: 3.34.0-- [email protected]: {}-- dependencies:- internmap: 1.0.1-- dependencies:- internmap: 2.0.3-- [email protected]: {}-- dependencies:- d3-dispatch: 3.0.1- d3-drag: 3.0.0- d3-interpolate: 3.0.1- d3-selection: 3.0.0- d3-transition: 3.0.1([email protected])-- dependencies:- d3-path: 3.1.0-- dependencies:- d3-array: 3.2.4-- dependencies:- delaunator: 5.1.0-@@ -13417,82 +13162,14 @@ snapshots:d3-dispatch: 3.0.1d3-selection: 3.0.0- dependencies:- commander: 7.2.0- iconv-lite: 0.6.3- rw: 1.3.3-- dependencies:- d3-dsv: 3.0.1-- dependencies:- d3-dispatch: 3.0.1- d3-quadtree: 3.0.1- d3-timer: 3.0.1-- [email protected]: {}-- dependencies:- d3-array: 3.2.4-- [email protected]: {}-dependencies:d3-color: 3.1.0- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- dependencies:- d3-array: 2.12.1- d3-shape: 1.3.7-- dependencies:- d3-color: 3.1.0- d3-interpolate: 3.0.1-- dependencies:- d3-array: 3.2.4- d3-format: 3.1.2- d3-interpolate: 3.0.1- d3-time: 3.1.0- d3-time-format: 4.1.0-- dependencies:- d3-path: 1.0.9-- dependencies:- d3-path: 3.1.0-- dependencies:- d3-time: 3.1.0-- dependencies:- d3-array: 3.2.4-@@ -13512,44 +13189,6 @@ snapshots:d3-selection: 3.0.0d3-transition: 3.0.1([email protected])- dependencies:- d3-array: 3.2.4- d3-axis: 3.0.0- d3-brush: 3.0.0- d3-chord: 3.0.1- d3-color: 3.1.0- d3-contour: 4.0.2- d3-delaunay: 6.0.4- d3-dispatch: 3.0.1- d3-drag: 3.0.0- d3-dsv: 3.0.1- d3-ease: 3.0.1- d3-fetch: 3.0.1- d3-force: 3.0.0- d3-format: 3.1.2- d3-geo: 3.1.1- d3-hierarchy: 3.1.2- d3-interpolate: 3.0.1- d3-path: 3.1.0- d3-polygon: 3.0.1- d3-quadtree: 3.0.1- d3-random: 3.0.1- d3-scale: 4.0.2- d3-scale-chromatic: 3.1.0- d3-selection: 3.0.0- d3-shape: 3.2.0- d3-time: 3.1.0- d3-time-format: 4.1.0- d3-timer: 3.0.1- d3-transition: 3.0.1([email protected])- d3-zoom: 3.0.0-- dependencies:- d3: 7.9.0- lodash-es: 4.18.1-@@ -13601,10 +13240,6 @@ snapshots:- dependencies:- robust-predicates: 3.0.3-@@ -14209,10 +13844,6 @@ snapshots:- dependencies:- strictdom: 1.0.1-dependencies:reusify: 1.1.0@@ -14349,8 +13980,6 @@ snapshots:optionalDependencies:crossws: 0.4.10([email protected])- [email protected]: {}-dependencies:'@types/node': 25.9.9@@ -14593,10 +14222,6 @@ snapshots:- [email protected]: {}-- [email protected]: {}-@@ -14722,8 +14347,6 @@ snapshots:dependencies:'@keyv/serialize': 1.1.1- [email protected]: {}-dependencies:fdir: 6.5.0([email protected])@@ -14753,10 +14376,6 @@ snapshots:chalk: 4.1.1dotenv: 16.6.1- [email protected]: {}-- [email protected]: {}-dependencies:prelude-ls: 1.2.1@@ -14890,8 +14509,6 @@ snapshots:dependencies:signal-exit: 3.0.7- [email protected]: {}-@@ -14936,8 +14553,6 @@ snapshots:- [email protected]: {}-@@ -15150,31 +14765,6 @@ snapshots:- dependencies:- '@braintree/sanitize-url': 7.1.2- '@iconify/utils': 3.1.3- '@mermaid-js/parser': 1.2.1- '@types/d3': 7.4.3- '@upsetjs/venn.js': 2.0.0- cytoscape: 3.34.0- cytoscape-cose-bilkent: 4.1.0([email protected])- cytoscape-fcose: 2.2.0([email protected])- d3: 7.9.0- d3-sankey: 0.12.3- dagre-d3-es: 7.0.14- dayjs: 1.11.23- dompurify: 3.4.16- es-toolkit: 1.52.0- fastdom: 1.0.12- katex: 0.16.47- khroma: 2.1.0- marked: 16.4.2- roughjs: 4.6.6- stylis: 4.4.0- ts-dedent: 2.3.0- uuid: 14.0.2-dependencies:decode-named-character-reference: 1.3.0@@ -15889,8 +15479,6 @@ snapshots:- [email protected]: {}-@@ -15914,6 +15502,8 @@ snapshots:canvas: 3.2.3path2d: 0.2.2+ [email protected]: {}+@@ -15950,13 +15540,6 @@ snapshots:dependencies:yaml: 2.9.1- [email protected]: {}-- dependencies:- path-data-parser: 0.1.0- points-on-curve: 0.2.0-dependencies:async: 3.2.6@@ -16355,25 +15938,14 @@ snapshots:- [email protected]: {}-- dependencies:- hachure-fill: 0.5.2- path-data-parser: 0.1.0- points-on-curve: 0.2.0- points-on-path: 0.2.1-dependencies:queue-microtask: 1.2.3- [email protected]: {}-dependencies:tslib: 2.8.1@@ -16612,8 +16184,6 @@ snapshots:transitivePeerDependencies:- supports-color- [email protected]: {}-@@ -16671,8 +16241,6 @@ snapshots:optionalDependencies:'@babel/core': 7.29.7([email protected])- [email protected]: {}-@@ -17617,7 +17185,6 @@ time:[email protected]: '2018-04-17T00:36:12.565Z'[email protected]: '2026-09-30T10:08:12.794Z'[email protected]: '2026-10-05T13:36:03.906Z'- [email protected]: '2026-08-25T11:52:39.930Z'[email protected]: '2025-09-12T17:53:01.376Z'[email protected]: '2023-07-04T17:31:47.638Z'[email protected]: '2026-10-02T12:10:51.735Z'@@ -17626,6 +17193,7 @@ time:[email protected]: '2026-10-14T17:43:55.246Z'[email protected]: '2026-10-08T12:20:23.186Z'[email protected]: '2026-09-14T20:36:00.110Z'+ [email protected]: '2026-10-17T14:23:29.096Z'[email protected]: '2024-10-16T18:20:03.921Z'[email protected]: '2026-08-24T14:36:23.690Z'[email protected]: '2026-09-11T07:49:12.561Z'diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex aa406808a88..6102d9ffe49 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -214,7 +214,6 @@ catalog:lockfile: 1.0.4loro-crdt: 1.16.4mediabunny: 1.61.3- mermaid: 11.17.2mime: 4.1.0mitt: 3.0.1motion: 13.5.1@@ -223,6 +222,7 @@ catalog:next-themes: 0.4.6nuqs: 2.10.2open: 11.0.4+ pele: 1.6.0picocolors: 1.1.1picomatch: 4.0.7pinyin-pro: 3.29.4diff --git a/web/app/components/base/markdown-blocks/__tests__/code-block.spec.tsx b/web/app/components/base/markdown-blocks/__tests__/code-block.spec.tsxindex cb3058cbc49..aba81e2f23a 100644--- a/web/app/components/base/markdown-blocks/__tests__/code-block.spec.tsx+++ b/web/app/components/base/markdown-blocks/__tests__/code-block.spec.tsx@@ -128,10 +128,10 @@ vi.mock('echarts-for-react', async () => {}})-vi.mock('@/app/components/base/mermaid', () => ({+vi.mock('../mermaid-diagram', () => ({__esModule: true,- default: ({ PrimitiveCode }: { PrimitiveCode: string }) => (- <div data-testid="mock-mermaid">{PrimitiveCode}</div>+ MermaidDiagram: ({ source }: { source: string }) => (+ <div data-testid="mock-mermaid">{source}</div>),}))diff --git a/web/app/components/base/markdown-blocks/code-block.tsx b/web/app/components/base/markdown-blocks/code-block.tsxindex 0f2f3033cc9..22faea4b0b4 100644--- a/web/app/components/base/markdown-blocks/code-block.tsx+++ b/web/app/components/base/markdown-blocks/code-block.tsx@@ -23,7 +23,10 @@ import useTheme from '@/hooks/use-theme'import { Theme } from '@/types/app'import { highlightCode } from './shiki-highlight'-const Flowchart = dynamic(() => import('@/app/components/base/mermaid'), { ssr: false })+const MermaidDiagram = dynamic(+ () => import('./mermaid-diagram').then((module) => module.MermaidDiagram),+ { ssr: false },+)// React.lazy preserves the chart adapter's ref and loads each runtime only when rendered.const ReactEcharts = lazy(() => import('echarts-for-react'))const MarkdownMusic = lazy(() => import('./music'))@@ -364,7 +367,7 @@ export const CodeBlock: any = memo(({ inline, className, children = '', ...propsconst content = String(children).replace(/\n$/, '')switch (language) {case 'mermaid':- return <Flowchart PrimitiveCode={content} theme={theme as 'light' | 'dark'} />+ return <MermaidDiagram source={content} />case 'echarts': {// Loading state: show loading indicatorif (chartState === 'loading') {@@ -534,8 +537,6 @@ export const CodeBlock: any = memo(({ inline, className, children = '', ...propslanguage,isSVG,finalChartOption,- props,- theme,match,chartState,isDarkMode,diff --git a/web/app/components/base/markdown-blocks/mermaid-diagram/__tests__/diagram.browser.spec.tsx b/web/app/components/base/markdown-blocks/mermaid-diagram/__tests__/diagram.browser.spec.tsxnew file mode 100644index 00000000000..e551571adc1--- /dev/null+++ b/web/app/components/base/markdown-blocks/mermaid-diagram/__tests__/diagram.browser.spec.tsx@@ -0,0 +1,343 @@+import {+ Drawer,+ DrawerBackdrop,+ DrawerPopup,+ DrawerPortal,+ DrawerViewport,+} from '@langgenius/dify-ui/drawer'+import { page, userEvent } from 'vite-plus/test/browser'+import { render } from 'vitest-browser-react'+import { MermaidDiagram } from '..'++// Real font measurement, resize delivery and CSS inheritance are essential here:+// mount() used to raise ResizeObserver loop errors when the diagram changed height.+it('reflows a narrow diagram without resize errors and preserves its theme in the preview', async () => {+ const errors: string[] = []+ const onError = (event: ErrorEvent) => errors.push(event.message)+ window.addEventListener('error', onError)+ document.documentElement.dataset.theme = 'light'+ const source =+ 'flowchart LR\n subgraph Research\n direction TB\n A[User input and knowledge retrieval] --> B[Generate answer]\n end\n C[Tool call] --> Research'+ const view = await render(+ <div style={{ width: 800 }}>+ <MermaidDiagram source={source} />+ </div>,+ )+ try {+ await expect.element(view.getByText('Generate answer')).toBeVisible()+ const label = view.getByText('Generate answer').element()+ const lightColor = getComputedStyle(label).fill+ await view.rerender(+ <div style={{ width: 320 }}>+ <MermaidDiagram source={source} />+ </div>,+ )+ await expect+ .poll(+ () =>+ view.getByText('Generate answer').element().closest('svg')!.getBoundingClientRect().width,+ )+ .toBeLessThanOrEqual(296)+ document.documentElement.dataset.theme = 'dark'+ await expect+ .poll(() => getComputedStyle(view.getByText('Generate answer').element()).fill)+ .not.toBe(lightColor)+ const darkColor = getComputedStyle(view.getByText('Generate answer').element()).fill+ await userEvent.click(view.getByRole('button', { name: 'app.mermaid.preview' }).first())+ const dialog = page.getByRole('dialog', { name: 'Mermaid' })+ await expect.element(dialog.getByText('Generate answer')).toBeVisible()+ expect(getComputedStyle(dialog.getByText('Generate answer').element()).fill).toBe(darkColor)+ const diagram = dialog.getByText('Generate answer').element().closest('svg')!+ const fittedViewBox = diagram.getAttribute('viewBox')+ const fittedLabelWidth = dialog+ .getByText('Generate answer')+ .element()+ .getBoundingClientRect().width+ await userEvent.click(dialog.getByRole('button', { name: 'common.operation.zoomIn' }))+ expect(+ dialog.getByText('Generate answer').element().getBoundingClientRect().width,+ ).toBeGreaterThan(fittedLabelWidth)+ await userEvent.click(dialog.getByRole('button', { name: 'common.operation.reset' }))+ expect(diagram.getAttribute('viewBox')).toBe(fittedViewBox)+ expect(errors).toEqual([])+ await userEvent.click(dialog.getByRole('button', { name: 'common.operation.close' }))+ await expect.element(dialog).not.toBeInTheDocument()+ } finally {+ document.documentElement.dataset.theme = 'light'+ window.removeEventListener('error', onError)+ }+})++it('contains diagrams even when source configuration requests a fixed width', async () => {+ const source =+ '---\nconfig:\n usecase:\n useMaxWidth: false\n---\nusecase-beta\ndirection LR\nactor Customer\nBrowse("Browse catalog")\nCustomer --> Browse'+ const view = await render(+ <div style={{ width: 320 }}>+ <MermaidDiagram source={source} />+ </div>,+ )+ await expect.element(view.getByText('Browse catalog')).toBeVisible()+ const diagram = view.getByText('Browse catalog').element().closest('svg')!+ expect(diagram.getBoundingClientRect().width).toBeLessThanOrEqual(296)+ const controls = view.getByRole('button', { name: 'app.mermaid.preview' }).element()+ expect(controls.getBoundingClientRect().bottom).toBeLessThanOrEqual(+ diagram.getBoundingClientRect().top,+ )+})++it('supports keyboard zoom and preserves descriptive SVG names', async () => {+ const view = await render(+ <MermaidDiagram+ source={+ 'flowchart LR\n accTitle: Order processing\n accDescr: An order is validated before shipping.\n A[Order] --> B[Shipping]'+ }+ />,+ )+ const diagram = view.getByLabelText('Order processing')+ await expect.element(diagram).toBeVisible()+ await expect+ .element(diagram)+ .toHaveAccessibleDescription('An order is validated before shipping.')+ const svg = diagram.element()+ const initial = svg.getAttribute('viewBox')+ ;(svg as SVGSVGElement).focus()+ await userEvent.keyboard('+')+ expect(svg.getAttribute('viewBox')).not.toBe(initial)+ await userEvent.keyboard('0')+ expect(svg.getAttribute('viewBox')).toBe(initial)+})++it('keeps zoom independent between instances and preserves it across parent and theme updates', async () => {+ const source = 'flowchart LR\n A[Stable] --> B[Diagram]'+ const view = await render(+ <div>+ <MermaidDiagram source={source} />+ <MermaidDiagram source={source} />+ </div>,+ )+ await expect.element(view.getByText('Stable').nth(1)).toBeVisible()+ const diagrams = view+ .getByText('Stable')+ .elements()+ .map((label) => label.closest('svg')!)+ const initial = diagrams[1]!.getAttribute('viewBox')+ await userEvent.click(view.getByRole('button', { name: 'common.operation.zoomIn' }).first())+ expect(diagrams[1]!.getAttribute('viewBox')).toBe(initial)+ const zoomed = diagrams[0]!.getAttribute('viewBox')+ expect(zoomed).not.toBe(initial)+ await view.rerender(+ <div>+ <MermaidDiagram source={source} />+ <MermaidDiagram source={source} />+ </div>,+ )+ document.documentElement.dataset.theme = 'dark'+ await new Promise(requestAnimationFrame)+ expect(view.getByText('Stable').first().element().closest('svg')!.getAttribute('viewBox')).toBe(+ zoomed,+ )+ document.documentElement.dataset.theme = 'light'+})++it('preserves keyboard focus when a streaming update replaces the focused drawing', async () => {+ const view = await render(<MermaidDiagram source={'flowchart LR\n A[Before] --> B'} />)+ await expect.element(view.getByText('Before')).toBeVisible()+ const svg = view.getByText('Before').element().closest('svg')!+ svg.focus()+ await view.rerender(<MermaidDiagram source={'flowchart LR\n A[After] --> B'} />)+ await expect.element(view.getByText('After')).toBeVisible()+ expect(document.activeElement).toBe(view.getByText('After').element().closest('svg'))+})++it('keeps the preview snapshot through streaming updates and reads the latest source on reopen', async () => {+ const view = await render(<MermaidDiagram source={'flowchart TD\n A[Initial] --> B'} />)+ const trigger = view.getByRole('button', { name: 'app.mermaid.preview' })+ await expect.element(trigger).toBeEnabled()+ await userEvent.click(trigger)+ const dialog = page.getByRole('dialog', { name: 'Mermaid' })+ await expect.element(dialog.getByText('Initial')).toBeVisible()+ await view.rerender(<MermaidDiagram source={'flowchart TD\n A['} />)+ await expect.poll(() => view.container.querySelector('[role="status"]')).not.toBeNull()+ await expect.element(dialog.getByText('Initial')).toBeVisible()+ await view.rerender(<MermaidDiagram source={'flowchart TD\n A[Recovered] --> B'} />)+ await expect.element(dialog.getByText('Initial')).toBeVisible()+ await expect.poll(() => view.container.querySelector('[role="status"]')).toBeNull()+ await userEvent.click(dialog.getByRole('button', { name: 'common.operation.zoomIn' }))+ await userEvent.click(dialog.getByRole('button', { name: 'common.operation.close' }))+ await userEvent.click(trigger)+ await expect.element(dialog.getByText('Recovered')).toBeVisible()+ const reopened = dialog.getByText('Recovered').element().closest('svg')!+ expect(reopened.getAttribute('viewBox')).toBe(+ `0 0 ${reopened.getAttribute('width')} ${reopened.getAttribute('height')}`,+ )+})++it('keeps a tall preview and its close button inside a narrow viewport', async () => {+ await page.viewport(320, 568)+ const source = `flowchart TD\n${Array.from({ length: 15 }, (_, index) => `N${index}[Step ${index}] --> N${index + 1}`).join('\n')}`+ const view = await render(<MermaidDiagram source={source} />)+ const trigger = view.getByRole('button', { name: 'app.mermaid.preview' })+ await expect.element(trigger).toBeEnabled()+ await userEvent.click(trigger)+ const dialog = page.getByRole('dialog', { name: 'Mermaid' })+ await expect.element(dialog.getByText('Step 0')).toBeVisible()+ const bounds = dialog.element().getBoundingClientRect()+ expect(bounds.left).toBeGreaterThanOrEqual(0)+ expect(bounds.right).toBeLessThanOrEqual(320)+ expect(bounds.top).toBeGreaterThanOrEqual(0)+ expect(bounds.bottom).toBeLessThanOrEqual(568)+ const close = dialog.getByRole('button', { name: 'common.operation.close' })+ const buttonBounds = close.element().getBoundingClientRect()+ expect(buttonBounds.top).toBeGreaterThanOrEqual(0)+ expect(buttonBounds.bottom).toBeLessThanOrEqual(568)+ await userEvent.click(close)+ await expect.element(dialog).not.toBeInTheDocument()+})++it('keeps the preview canvas fixed while the first zoom step enlarges the drawing by 25 percent', async () => {+ await page.viewport(1440, 900)+ const view = await render(+ <MermaidDiagram+ source={+ 'flowchart TD\n A[Start] --> B{User message?}\n B -->|Tool| C[Call web search]\n B -->|Respond| D[Compose draft]'+ }+ />,+ )+ const trigger = view.getByRole('button', { name: 'app.mermaid.preview' })+ await expect.element(trigger).toBeEnabled()+ await userEvent.click(trigger)+ const dialog = page.getByRole('dialog', { name: 'Mermaid' })+ const label = dialog.getByText('Start')+ await expect.element(label).toBeVisible()+ const svg = label.element().closest('svg')!+ await Promise.all(+ dialog+ .element()+ .getAnimations()+ .map((animation) => animation.finished),+ )+ const initial = svg.getBoundingClientRect()+ const initialLabel = label.element().getBoundingClientRect().width+ expect(initial.height).toBeGreaterThan(700)+ await userEvent.click(dialog.getByRole('button', { name: 'common.operation.zoomIn' }))+ const enlarged = svg.getBoundingClientRect()+ expect(enlarged.width).toBeCloseTo(initial.width, 0)+ expect(enlarged.height).toBeCloseTo(initial.height, 0)+ expect(label.element().getBoundingClientRect().width / initialLabel).toBeCloseTo(1.25, 2)+ await userEvent.click(dialog.getByRole('button', { name: 'common.operation.zoomOut' }))+ expect(label.element().getBoundingClientRect().width).toBeCloseTo(initialLabel, 0)+ expect(svg.getBoundingClientRect().width).toBeCloseTo(initial.width, 0)+ await userEvent.click(dialog.getByRole('button', { name: 'common.operation.zoomIn' }))+ await userEvent.click(dialog.getByRole('button', { name: 'common.operation.reset' }))+ expect(label.element().getBoundingClientRect().width).toBeCloseTo(initialLabel, 0)+})++it('copies a complete PNG after zooming and resets the success feedback', async () => {+ let copied: Blob | undefined+ const write = vi.spyOn(navigator.clipboard, 'write').mockImplementation(async (items) => {+ copied = await items[0]!.getType('image/png')+ })+ try {+ const view = await render(<MermaidDiagram source={'flowchart TD\n A[Start] --> B[Finish]'} />)+ const trigger = view.getByRole('button', { name: 'app.mermaid.preview' })+ await expect.element(trigger).toBeEnabled()+ await userEvent.click(trigger)+ const dialog = page.getByRole('dialog', { name: 'Mermaid' })+ await expect.element(dialog.getByText('Start')).toBeVisible()+ await userEvent.click(dialog.getByRole('button', { name: 'common.operation.zoomIn' }))+ await userEvent.click(dialog.getByRole('button', { name: 'common.operation.copyImage' }))+ await expect+ .element(dialog.getByRole('button', { name: 'common.operation.imageCopied' }))+ .toBeEnabled()+ expect(copied?.type).toBe('image/png')+ const bitmap = await createImageBitmap(copied!)+ expect(bitmap.width).toBeGreaterThan(50)+ expect(bitmap.height).toBeGreaterThan(50)+ const canvas = document.createElement('canvas')+ canvas.width = bitmap.width+ canvas.height = bitmap.height+ const context = canvas.getContext('2d')!+ context.drawImage(bitmap, 0, 0)+ expect([...context.getImageData(0, 0, 1, 1).data]).toEqual([255, 255, 255, 255])+ bitmap.close()+ await expect+ .element(dialog.getByRole('button', { name: 'common.operation.copyImage' }))+ .toBeEnabled()+ await expect.element(dialog.getByRole('status')).toBeEmptyDOMElement()+ await userEvent.click(dialog.getByRole('button', { name: 'common.operation.copyImage' }))+ await expect+ .element(dialog.getByRole('button', { name: 'common.operation.imageCopied' }))+ .toBeEnabled()+ await userEvent.click(dialog.getByRole('button', { name: 'common.operation.close' }))+ await expect.element(dialog).not.toBeInTheDocument()+ await userEvent.click(trigger)+ await expect+ .element(dialog.getByRole('button', { name: 'common.operation.copyImage' }))+ .toBeEnabled()+ } finally {+ write.mockRestore()+ }+})++it('announces a failed image copy and allows retrying', async () => {+ const write = vi+ .spyOn(navigator.clipboard, 'write')+ .mockRejectedValue(new DOMException('Denied', 'NotAllowedError'))+ try {+ const view = await render(<MermaidDiagram source={'flowchart TD\n A --> B'} />)+ const trigger = view.getByRole('button', { name: 'app.mermaid.preview' })+ await expect.element(trigger).toBeEnabled()+ await userEvent.click(trigger)+ const dialog = page.getByRole('dialog', { name: 'Mermaid' })+ const copy = dialog.getByRole('button', { name: 'common.operation.copyImage' })+ await expect.element(copy).toBeEnabled()+ await userEvent.click(copy)+ await expect+ .element(dialog.getByRole('status'))+ .toHaveTextContent('common.operation.imageCopyFailed')+ await expect.element(dialog.getByRole('status')).toBeVisible()+ await expect.element(copy).toBeEnabled()+ write.mockResolvedValue(undefined)+ await userEvent.click(copy)+ await expect+ .element(dialog.getByRole('button', { name: 'common.operation.imageCopied' }))+ .toBeEnabled()+ } finally {+ write.mockRestore()+ }+})++it('shows a visual scrim when previewing from a transparent log-detail drawer and returns focus to it', async () => {+ await render(+ <Drawer defaultOpen swipeDirection="right">+ <DrawerPortal>+ <DrawerBackdrop className="bg-transparent" />+ <DrawerViewport>+ <DrawerPopup aria-label="Conversation details">+ <MermaidDiagram source={'flowchart TD\n A[Start] --> B[Finish]'} />+ </DrawerPopup>+ </DrawerViewport>+ </DrawerPortal>+ </Drawer>,+ )+ const parent = page.getByRole('dialog', { name: 'Conversation details' })+ const trigger = parent.getByRole('button', { name: 'app.mermaid.preview' })+ await expect.element(trigger).toBeEnabled()+ await userEvent.click(trigger)+ const preview = page.getByRole('dialog', { name: 'Mermaid' })+ await expect.element(preview.getByText('Start')).toBeVisible()+ // The visible scrim is distinct from Base UI's transparent interaction guard.+ const scrims = [...document.querySelectorAll<HTMLElement>('[role="presentation"]')].filter(+ (element) => getComputedStyle(element).backgroundColor !== 'rgba(0, 0, 0, 0)',+ )+ expect(scrims.length).toBe(1)+ const scrim = scrims[0]!+ await expect.poll(() => getComputedStyle(scrim).opacity).toBe('1')+ const bounds = scrim.getBoundingClientRect()+ expect(bounds.width).toBeGreaterThanOrEqual(window.innerWidth)+ expect(bounds.height).toBeGreaterThanOrEqual(window.innerHeight)+ await userEvent.click(preview.getByRole('button', { name: 'common.operation.close' }))+ await expect.element(preview).not.toBeInTheDocument()+ await expect.element(parent).toBeVisible()+ await expect.element(trigger).toHaveFocus()+})diff --git a/web/app/components/base/markdown-blocks/mermaid-diagram/__tests__/export.browser.spec.tsx b/web/app/components/base/markdown-blocks/mermaid-diagram/__tests__/export.browser.spec.tsxnew file mode 100644index 00000000000..e1d1c08beed--- /dev/null+++ b/web/app/components/base/markdown-blocks/mermaid-diagram/__tests__/export.browser.spec.tsx@@ -0,0 +1,39 @@+import { page, userEvent } from 'vite-plus/test/browser'+import { render } from 'vitest-browser-react'+import { downloadBlob } from '@/utils/download'+import { MermaidDiagram } from '..'++vi.mock('@/utils/download', () => ({ downloadBlob: vi.fn() }))++it('downloads the complete themed drawing independently of the preview zoom and stage padding', async () => {+ document.documentElement.dataset.theme = 'dark'+ try {+ const view = await render(<MermaidDiagram source={'flowchart TD\n A[Start] --> B[Finish]'} />)+ const trigger = view.getByRole('button', { name: 'app.mermaid.preview' })+ await expect.element(trigger).toBeEnabled()+ await userEvent.click(trigger)+ const dialog = page.getByRole('dialog', { name: 'Mermaid' })+ await expect.element(dialog.getByText('Finish')).toBeVisible()+ await userEvent.click(dialog.getByRole('button', { name: 'common.operation.zoomIn' }))+ await userEvent.click(dialog.getByRole('button', { name: 'common.operation.download' }))+ const { data, fileName } = vi.mocked(downloadBlob).mock.calls[0]![0]+ expect(fileName).toBe('mermaid.svg')+ expect(data.type).toBe('image/svg+xml')+ const document = new DOMParser().parseFromString(await data.text(), 'image/svg+xml')+ const svg = document.documentElement+ expect(svg.textContent).toContain('Start')+ expect(svg.textContent).toContain('Finish')+ expect(svg.getAttribute('viewBox')).toBe(+ `0 0 ${svg.getAttribute('width')} ${svg.getAttribute('height')}`,+ )+ expect(svg.getAttribute('style')).toContain('--pele-bg:')+ const image = new Image()+ image.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(await data.text())}`+ await image.decode()+ expect(image.naturalWidth).toBeGreaterThan(50)+ expect(image.naturalWidth).toBeLessThan(300)+ } finally {+ document.documentElement.dataset.theme = 'light'+ vi.mocked(downloadBlob).mockClear()+ }+})diff --git a/web/app/components/base/markdown-blocks/mermaid-diagram/__tests__/rendering.browser.spec.tsx b/web/app/components/base/markdown-blocks/mermaid-diagram/__tests__/rendering.browser.spec.tsxnew file mode 100644index 00000000000..42b98399ca4--- /dev/null+++ b/web/app/components/base/markdown-blocks/mermaid-diagram/__tests__/rendering.browser.spec.tsx@@ -0,0 +1,77 @@+import { page, userEvent } from 'vite-plus/test/browser'+import { render } from 'vitest-browser-react'+import { MermaidDiagram } from '..'++it.each([+ ['flowchart LR\n A[Start] --> B[Complete]', 'Complete'],+ ['sequenceDiagram\n Alice->>Bob: Hello', 'Hello'],+ ['mindmap\n root((Dify))\n Knowledge', 'Knowledge'],+ ['gantt\n dateFormat YYYY-MM-DD\n section Plan\n Build :2026-10-18, 2d', 'Build'],+ ['gitGraph\n commit id: "Initial"', 'Initial'],+ ['timeline\n title Releases\n 2026 : Pele migration', 'Pele migration'],+ ['---\ntitle: Deployment\n---\nflowchart TD\n A --> B', 'Deployment'],+])('renders Mermaid syntax with the real renderer: %s', async (source, label) => {+ const view = await render(<MermaidDiagram source={source} />)+ await expect.element(view.getByText(label).first()).toBeVisible()+ await expect.element(page.getByRole('button', { name: 'app.mermaid.preview' })).toBeEnabled()+})++it('coalesces source updates and keeps the last valid diagram through an incomplete update', async () => {+ const view = await render(<MermaidDiagram source={'flowchart LR\n A[First] --> B[Ready]'} />)+ await expect.element(view.getByText('Ready')).toBeVisible()+ await view.rerender(<MermaidDiagram source={'flowchart LR\n A['} />)+ await expect.element(view.getByRole('status')).toBeVisible()+ await expect.element(view.getByText('Ready')).toBeInTheDocument()+ await view.rerender(<MermaidDiagram source={'flowchart LR\n A[Obsolete] --> B'} />)+ await view.rerender(<MermaidDiagram source={'flowchart LR\n A[Latest] --> B'} />)+ await expect.element(view.getByText('Latest')).toBeInTheDocument()+ await expect.element(view.getByText('Obsolete')).not.toBeInTheDocument()+ await expect.element(view.getByText('Ready')).not.toBeInTheDocument()+})++it('recovers from invalid initial input and previews the last successful source', async () => {+ const view = await render(<MermaidDiagram source={'flowchart LR\n A['} />)+ await expect.element(page.getByRole('button', { name: 'app.mermaid.preview' })).toBeDisabled()+ await view.rerender(<MermaidDiagram source={'flowchart LR\n A[Recovered] --> B'} />)+ await expect.element(view.getByText('Recovered')).toBeVisible()+ await view.rerender(<MermaidDiagram source={'flowchart LR\n A['} />)+ await expect.element(view.getByRole('status')).toBeVisible()+ await userEvent.click(page.getByRole('button', { name: 'app.mermaid.preview' }))+ await expect+ .element(page.getByRole('dialog', { name: 'Mermaid' }).getByText('Recovered'))+ .toBeVisible()+ await userEvent.click(page.getByRole('button', { name: 'common.operation.close' }))+ await expect.element(page.getByRole('dialog')).not.toBeInTheDocument()+})++it('does not turn untrusted diagram links or HTML labels into active content', async () => {+ const view = await render(+ <MermaidDiagram+ source={+ 'flowchart TD\n A["<img src=x onerror=alert(1)>"] --> B[Safe]\n click B "https://example.com"'+ }+ />,+ )+ await expect.element(view.getByText('Safe')).toBeInTheDocument()+ expect(+ view.container.querySelector('a, image, img, script, foreignObject, [onerror], [onclick]'),+ ).not.toBeInTheDocument()+})++it('rejects an oversized source without leaving an enabled preview', async () => {+ const view = await render(<MermaidDiagram source={`flowchart TD\n A[${'x'.repeat(50_000)}]`} />)+ await expect.element(view.getByText(/longer than the limit/)).toBeInTheDocument()+ await expect.element(page.getByRole('button', { name: 'app.mermaid.preview' })).toBeDisabled()+})++it('blocks external image resources in diagram shapes', async () => {+ const view = await render(+ <MermaidDiagram+ source={+ 'flowchart LR\n A@{ img: "https://example.com/image.png", label: "Remote image" } --> B[Safe]'+ }+ />,+ )+ await expect.element(view.getByText('Safe')).toBeInTheDocument()+ expect(view.container.querySelector('image, img')).not.toBeInTheDocument()+})diff --git a/web/app/components/base/markdown-blocks/mermaid-diagram/diagram-canvas.tsx b/web/app/components/base/markdown-blocks/mermaid-diagram/diagram-canvas.tsxnew file mode 100644index 00000000000..582eaf3ff7d--- /dev/null+++ b/web/app/components/base/markdown-blocks/mermaid-diagram/diagram-canvas.tsx@@ -0,0 +1,33 @@+import type { ReactNode } from 'react'+import styles from './diagram.module.css'+import { useDiagram } from './use-diagram'+import { ZoomControls } from './zoom-controls'++type DiagramCanvasProps = {+ source: string+ actions: ReactNode+ onSourceRendered: (source: string) => void+}++export function DiagramCanvas({ source, actions, onSourceRendered }: DiagramCanvasProps) {+ const diagram = useDiagram({ source, mode: 'inline', onRendered: onSourceRendered })+ return (+ <div className={styles.diagram}>+ <div className="mb-2 flex items-center justify-end gap-1">+ <ZoomControls disabled={!diagram.ready} zoomBy={diagram.zoomBy} reset={diagram.reset} />+ {actions}+ </div>+ <div ref={diagram.stageRef}>+ <div ref={diagram.canvasRef} className={styles.canvas} />+ </div>+ {diagram.error && (+ <p+ role="status"+ className="mt-2 system-xs-regular whitespace-pre-wrap text-text-destructive"+ >+ {diagram.error}+ </p>+ )}+ </div>+ )+}diff --git a/web/app/components/base/markdown-blocks/mermaid-diagram/diagram.module.css b/web/app/components/base/markdown-blocks/mermaid-diagram/diagram.module.cssnew file mode 100644index 00000000000..d6be76dfa06--- /dev/null+++ b/web/app/components/base/markdown-blocks/mermaid-diagram/diagram.module.css@@ -0,0 +1,38 @@+.diagram {+ --pele-bg: var(--color-components-panel-bg);+ --pele-fg: var(--color-text-primary);+ --pele-muted: var(--color-text-tertiary);+ --pele-line: var(--color-text-secondary);+ --pele-surface: var(--color-background-section);+ --pele-surface-alt: var(--color-background-section-burn);+ --pele-border: var(--color-text-tertiary);+ --pele-accent: var(--color-text-accent);+ --pele-critical: var(--color-text-destructive);+ --pele-error: var(--color-text-destructive);++ width: 100%;+ min-width: 0;+ overflow-wrap: anywhere;+}++.diagram :global(svg:focus-visible) {+ outline: 2px solid var(--color-text-accent);+ outline-offset: 2px;+}++.canvas {+ min-width: 0;+ margin-inline: auto;+ flex-shrink: 0;+}++.canvas > :global(svg) {+ display: block;+ margin-inline: auto;+}++.previewActions {+ --color-text-tertiary: var(--color-text-primary-on-surface);+ --color-text-secondary: var(--color-text-primary-on-surface);+ --color-state-base-hover: var(--color-state-base-hover-alt);+}diff --git a/web/app/components/base/markdown-blocks/mermaid-diagram/export-actions.tsx b/web/app/components/base/markdown-blocks/mermaid-diagram/export-actions.tsxnew file mode 100644index 00000000000..02c66dc48a4--- /dev/null+++ b/web/app/components/base/markdown-blocks/mermaid-diagram/export-actions.tsx@@ -0,0 +1,118 @@+import { cn } from '@langgenius/dify-ui/cn'+import { IconButton } from '@langgenius/dify-ui/icon-button'+import { useEffect, useState } from 'react'+import { useTranslation } from 'react-i18next'+import { downloadBlob } from '@/utils/download'+import { diagramPng } from './export-diagram'++type ExportActionsProps = {+ exportSvg: () => string | null+ disabled: boolean+}++export function ExportActions({ exportSvg, disabled }: ExportActionsProps) {+ const { t } = useTranslation(['common'])+ const [copyState, setCopyState] = useState<'idle' | 'pending' | 'success' | 'error'>('idle')+ useEffect(() => {+ if (copyState !== 'success') return+ const timeout = setTimeout(() => setCopyState('idle'), 2000)+ return () => clearTimeout(timeout)+ }, [copyState])+ const copying = copyState === 'pending'+ const status =+ copyState === 'success'+ ? t(($) => $['operation.imageCopied'])+ : copyState === 'error'+ ? t(($) => $['operation.imageCopyFailed'])+ : ''++ const copy = async () => {+ const svg = exportSvg()+ if (!svg || copying) return+ setCopyState('pending')+ try {+ const png = diagramPng(svg)+ // Consume encoding failures even when the browser rejects clipboard access first.+ void png.catch(() => {})+ await navigator.clipboard.write([new ClipboardItem({ 'image/png': png })])+ setCopyState('success')+ } catch {+ setCopyState('error')+ }+ }++ const download = () => {+ const svg = exportSvg()+ if (!svg) return+ downloadBlob({+ data: new Blob([svg], { type: 'image/svg+xml' }),+ fileName: 'mermaid.svg',+ })+ }++ const open = () => {+ const svg = exportSvg()+ if (!svg) return+ const target = window.open()+ if (!target) return+ target.opener = null+ target.document.title = 'Mermaid'+ const image = target.document.createElement('img')+ image.alt = 'Mermaid'+ image.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`+ target.document.body.append(image)+ }++ return (+ <>+ <span+ role="status"+ className={cn(+ copyState === 'error'+ ? 'absolute top-full right-0 rounded-md bg-components-panel-bg px-2 py-1 system-xs-regular text-text-destructive'+ : 'sr-only',+ )}+ >+ {status}+ </span>+ <IconButton+ size="lg"+ aria-label={+ copyState === 'success'+ ? t(($) => $['operation.imageCopied'])+ : t(($) => $['operation.copyImage'])+ }+ disabled={disabled || copying}+ focusableWhenDisabled={copying}+ onClick={copy}+ >+ <span+ aria-hidden+ className={+ copying+ ? 'i-ri-loader-4-line size-4 animate-spin motion-reduce:animate-none'+ : copyState === 'success'+ ? 'i-ri-check-line size-4'+ : 'i-ri-file-copy-line size-4'+ }+ />+ </IconButton>+ <IconButton+ size="lg"+ aria-label={t(($) => $['operation.download'])}+ disabled={disabled}+ onClick={download}+ >+ <span aria-hidden className="i-ri-download-cloud-2-line size-4" />+ </IconButton>+ <IconButton+ size="lg"+ aria-label={t(($) => $['operation.openInNewTab'])}+ disabled={disabled}+ onClick={open}+ >+ <span aria-hidden className="i-ri-external-link-line size-4" />+ </IconButton>+ </>+ )+}diff --git a/web/app/components/base/markdown-blocks/mermaid-diagram/export-diagram.ts b/web/app/components/base/markdown-blocks/mermaid-diagram/export-diagram.tsnew file mode 100644index 00000000000..801ba6195a8--- /dev/null+++ b/web/app/components/base/markdown-blocks/mermaid-diagram/export-diagram.ts@@ -0,0 +1,45 @@+export function serializeDiagram(svg: SVGSVGElement, theme: Element = svg): string {+ const copy = svg.cloneNode(true) as SVGSVGElement+ const computed = getComputedStyle(theme)+ // Export the complete drawing, independent of the current pan/zoom viewport.+ const width = svg.getAttribute('width')!+ const height = svg.getAttribute('height')!+ copy.setAttribute('viewBox', `0 0 ${width} ${height}`)+ copy.style.width = `${width}px`+ copy.style.height = `${height}px`+ copy.style.maxWidth = 'none'+ copy.style.margin = '0'+ copy.style.backgroundColor = computed.getPropertyValue('--pele-bg')+ copy.removeAttribute('tabindex')+ // Standalone SVGs cannot inherit the host application's theme variables.+ for (const property of computed) {+ if (property.startsWith('--pele-'))+ copy.style.setProperty(property, computed.getPropertyValue(property))+ }+ return new XMLSerializer().serializeToString(copy)+}++export async function diagramPng(svg: string): Promise<Blob> {+ const image = new Image()+ image.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`+ await image.decode()+ // Bound bitmap allocation for large diagrams while preserving their aspect ratio.+ const scale = Math.min(+ 1,+ 8192 / image.naturalWidth,+ 8192 / image.naturalHeight,+ Math.sqrt(16_000_000 / (image.naturalWidth * image.naturalHeight)),+ )+ const canvas = document.createElement('canvas')+ canvas.width = Math.max(1, Math.round(image.naturalWidth * scale))+ canvas.height = Math.max(1, Math.round(image.naturalHeight * scale))+ const context = canvas.getContext('2d')+ if (!context) throw new Error('Canvas is unavailable')+ context.drawImage(image, 0, 0, canvas.width, canvas.height)+ return new Promise((resolve, reject) => {+ canvas.toBlob(+ (blob) => (blob ? resolve(blob) : reject(new Error('PNG encoding failed'))),+ 'image/png',+ )+ })+}diff --git a/web/app/components/base/markdown-blocks/mermaid-diagram/index.stories.tsx b/web/app/components/base/markdown-blocks/mermaid-diagram/index.stories.tsxnew file mode 100644index 00000000000..7e88310d96c--- /dev/null+++ b/web/app/components/base/markdown-blocks/mermaid-diagram/index.stories.tsx@@ -0,0 +1,40 @@+import type { Meta, StoryObj } from '@storybook/nextjs-vite'+import { MermaidDiagram } from '.'++const meta = {+ title: 'Base/Data Display/MermaidDiagram',+ component: MermaidDiagram,+ args: {+ source:+ 'flowchart LR\n A[用户输入] --> B{知识检索}\n B --> C[生成回答]\n B --> D[调用工具]\n D --> C',+ },+ decorators: [+ (Story) => (+ <div className="w-full max-w-3xl">+ <Story />+ </div>+ ),+ ],+ parameters: { layout: 'padded' },+} satisfies Meta<typeof MermaidDiagram>++export default meta+type Story = StoryObj<typeof meta>++export const Flowchart: Story = {}+export const Narrow: Story = {+ decorators: [+ (Story) => (+ <div className="w-80">+ <Story />+ </div>+ ),+ ],+}+export const Sequence: Story = {+ args: {+ source:+ 'sequenceDiagram\n participant User\n participant Agent\n participant Knowledge\n User->>Agent: Ask a question\n Agent->>Knowledge: Retrieve context\n Knowledge-->>Agent: Relevant documents\n Agent-->>User: Answer with citations',+ },+}+export const Invalid: Story = { args: { source: 'flowchart TD\n A[' } }diff --git a/web/app/components/base/markdown-blocks/mermaid-diagram/index.tsx b/web/app/components/base/markdown-blocks/mermaid-diagram/index.tsxnew file mode 100644index 00000000000..13170596237--- /dev/null+++ b/web/app/components/base/markdown-blocks/mermaid-diagram/index.tsx@@ -0,0 +1,102 @@+'use client'++import { Button } from '@langgenius/dify-ui/button'+import { cn } from '@langgenius/dify-ui/cn'+import {+ Dialog,+ DialogBackdrop,+ DialogClose,+ DialogPopup,+ DialogPortal,+ DialogTrigger,+ DialogViewport,+} from '@langgenius/dify-ui/dialog'+import { IconButton } from '@langgenius/dify-ui/icon-button'+import { useState } from 'react'+import { useTranslation } from 'react-i18next'+import { DiagramCanvas } from './diagram-canvas'+import styles from './diagram.module.css'+import { ExportActions } from './export-actions'+import { useDiagram } from './use-diagram'+import { ZoomControls } from './zoom-controls'++export function MermaidDiagram({ source }: { source: string }) {+ const { t } = useTranslation(['app'])+ const [previewSource, setPreviewSource] = useState('')++ return (+ <Dialog disablePointerDismissal>+ <div className="min-w-0 rounded-b-xl bg-components-panel-bg p-3">+ <DiagramCanvas+ source={source}+ onSourceRendered={setPreviewSource}+ actions={+ <DialogTrigger+ disabled={!previewSource}+ render={<Button size="small" variant="ghost" />}+ >+ <span aria-hidden className="i-ri-fullscreen-line size-4" />+ {t(($) => $['mermaid.preview'], { ns: 'app' })}+ </DialogTrigger>+ }+ />+ </div>+ <DialogPortal>+ <DiagramPreview source={previewSource} />+ </DialogPortal>+ </Dialog>+ )+}++function DiagramPreview({ source }: { source: string }) {+ const { t } = useTranslation(['common'])+ // A preview session keeps its drawing while the answer continues streaming.+ const [snapshot] = useState(source)+ const diagram = useDiagram({ source: snapshot, mode: 'preview' })+ return (+ <>+ {/* Full-screen previews need their own visual scrim inside transparent Drawers too. */}+ <DialogBackdrop forceRender />+ <DialogViewport className="p-4 sm:p-8">+ <DialogPopup+ aria-label="Mermaid"+ className={cn(+ styles.diagram,+ 'pointer-events-none flex h-full min-h-0 flex-col transition-opacity data-ending-style:scale-100 data-starting-style:scale-100',+ )}+ >+ <div+ className={cn(+ styles.previewActions,+ 'pointer-events-auto relative mb-2 flex shrink-0 items-center justify-end gap-1 self-end',+ )}+ >+ <ZoomControls disabled={!diagram.ready} zoomBy={diagram.zoomBy} reset={diagram.reset} />+ <ExportActions exportSvg={diagram.exportSvg} disabled={!diagram.ready} />+ <DialogClose+ render={+ <IconButton size="lg" aria-label={t(($) => $['operation.close'])}>+ <span aria-hidden className="i-ri-close-line size-4" />+ </IconButton>+ }+ />+ </div>+ <div ref={diagram.stageRef} className="flex min-h-0 flex-1 items-center">+ <div+ ref={diagram.canvasRef}+ className={cn(styles.canvas, 'pointer-events-auto bg-components-panel-bg')}+ />+ </div>+ {diagram.error && (+ <p+ role="status"+ className="pointer-events-auto mt-2 system-xs-regular text-text-destructive"+ >+ {diagram.error}+ </p>+ )}+ </DialogPopup>+ </DialogViewport>+ </>+ )+}diff --git a/web/app/components/base/markdown-blocks/mermaid-diagram/use-diagram.ts b/web/app/components/base/markdown-blocks/mermaid-diagram/use-diagram.tsnew file mode 100644index 00000000000..4b407fab461--- /dev/null+++ b/web/app/components/base/markdown-blocks/mermaid-diagram/use-diagram.ts@@ -0,0 +1,148 @@+import type { Zoom } from 'pele'+import DOMPurify from 'dompurify'+import { enableZoom, forgetTextWidths, parse, render } from 'pele'+import { useEffect, useEffectEvent, useId, useRef, useState } from 'react'+import { serializeDiagram } from './export-diagram'++type DiagramOptions = {+ source: string+ mode: 'inline' | 'preview'+ onRendered?: (source: string) => void+}++export function useDiagram({ source, mode, onRendered }: DiagramOptions) {+ const stageRef = useRef<HTMLDivElement>(null)+ const canvasRef = useRef<HTMLDivElement>(null)+ const zoomRef = useRef<Zoom | null>(null)+ const exportRef = useRef<SVGSVGElement | null>(null)+ const id = useId()+ const [result, setResult] = useState({ ready: false, error: '' })+ const reportSource = useEffectEvent((renderedSource: string) => onRendered?.(renderedSource))+ useEffect(() => {+ const container = canvasRef.current+ const stage = stageRef.current+ if (!container || !stage) return+ let frame = 0+ let width = -1+ let height = -1+ let disposed = false+ let model: ReturnType<typeof parse> | undefined++ const draw = () => {+ const availableWidth = stage.clientWidth+ if (!availableWidth) return+ width = availableWidth+ height = stage.clientHeight+ try {+ model ??= parse(source, { limit: 50_000, maxEdges: 500 })+ const result = render(model, {+ idPrefix: `diagram-${id.replaceAll(':', '')}`,+ fontFamily: getComputedStyle(container).fontFamily,+ maxWidth: availableWidth,+ autoDirection: false,+ responsive: true,+ links: false,+ images: false,+ outputLimit: 4_000_000,+ })+ const fragment = DOMPurify.sanitize(result.svg, {+ USE_PROFILES: { svg: true, svgFilters: true },+ RETURN_DOM_FRAGMENT: true,+ })+ const svg = fragment.querySelector('svg')+ if (!svg) throw new Error('The diagram has no SVG output')+ const fit = Math.min(+ availableWidth / result.width,+ mode === 'preview' ? height / result.height : 1,+ )+ const original = mode === 'preview' ? (svg.cloneNode(true) as SVGSVGElement) : null+ const fittedWidth = mode === 'preview' ? availableWidth : result.width * fit+ const fittedHeight = mode === 'preview' ? height : result.height * fit+ if (mode === 'preview') {+ // Give Pele a full-stage viewBox, including the centered drawing's empty margins.+ // Its fit/zoom math then has one consistent aspect ratio from the first frame.+ const frameWidth = fittedWidth / fit+ const frameHeight = fittedHeight / fit+ const drawing = document.createElementNS('http://www.w3.org/2000/svg', 'g')+ drawing.setAttribute(+ 'transform',+ `translate(${(frameWidth - result.width) / 2} ${(frameHeight - result.height) / 2})`,+ )+ drawing.append(...svg.childNodes)+ svg.append(drawing)+ svg.setAttribute('width', String(frameWidth))+ svg.setAttribute('height', String(frameHeight))+ svg.setAttribute('viewBox', `0 0 ${frameWidth} ${frameHeight}`)+ }+ svg.style.width = `${fittedWidth}px`+ svg.style.height = `${fittedHeight}px`+ const restoreFocus = container.contains(document.activeElement)+ zoomRef.current?.destroy()+ container.style.width = `${fittedWidth}px`+ container.style.height = `${fittedHeight}px`+ container.replaceChildren(fragment)+ exportRef.current = original+ zoomRef.current = enableZoom(container, {+ controls: false,+ always: true,+ maxScale: Math.max(3, fit * 3),+ })+ if (restoreFocus) container.querySelector('svg')?.focus({ preventScroll: true })+ setResult({ ready: true, error: '' })+ reportSource(source)+ } catch (failure) {+ setResult((previous) => ({+ ...previous,+ error: failure instanceof Error ? failure.message : String(failure),+ }))+ }+ }+ const schedule = () => {+ if (disposed) return+ cancelAnimationFrame(frame)+ frame = requestAnimationFrame(draw)+ }+ // Inline height follows the drawing; only the fixed preview stage observes both dimensions.+ const observer = new ResizeObserver(() => {+ if (stage.clientWidth !== width || (mode === 'preview' && stage.clientHeight !== height))+ schedule()+ })+ observer.observe(stage)+ schedule()+ const fontsLoaded = () => {+ if (disposed) return+ forgetTextWidths()+ schedule()+ }+ if (document.fonts?.status === 'loading') void document.fonts.ready.then(fontsLoaded)+ document.fonts?.addEventListener('loadingdone', fontsLoaded)++ return () => {+ disposed = true+ cancelAnimationFrame(frame)+ observer.disconnect()+ document.fonts?.removeEventListener('loadingdone', fontsLoaded)+ }+ }, [source, id, mode])++ useEffect(+ () => () => {+ zoomRef.current?.destroy()+ zoomRef.current = null+ },+ [],+ )++ return {+ stageRef,+ canvasRef,+ ...result,+ zoomBy: (factor: number) => zoomRef.current?.zoomBy(factor),+ reset: () => zoomRef.current?.reset(),+ exportSvg: () => {+ const svg = exportRef.current+ const theme = stageRef.current+ return svg && theme ? serializeDiagram(svg, theme) : null+ },+ }+}diff --git a/web/app/components/base/markdown-blocks/mermaid-diagram/zoom-controls.tsx b/web/app/components/base/markdown-blocks/mermaid-diagram/zoom-controls.tsxnew file mode 100644index 00000000000..4a0a2b34cc3--- /dev/null+++ b/web/app/components/base/markdown-blocks/mermaid-diagram/zoom-controls.tsx@@ -0,0 +1,40 @@+import { IconButton } from '@langgenius/dify-ui/icon-button'+import { useTranslation } from 'react-i18next'++type ZoomControlsProps = {+ disabled: boolean+ zoomBy: (factor: number) => void+ reset: () => void+}++export function ZoomControls({ disabled, zoomBy, reset }: ZoomControlsProps) {+ const { t } = useTranslation(['common'])+ return (+ <>+ <IconButton+ size="lg"+ aria-label={t(($) => $['operation.zoomIn'])}+ disabled={disabled}+ onClick={() => zoomBy(1.25)}+ >+ <span aria-hidden className="i-ri-add-line size-4" />+ </IconButton>+ <IconButton+ size="lg"+ aria-label={t(($) => $['operation.zoomOut'])}+ disabled={disabled}+ onClick={() => zoomBy(0.8)}+ >+ <span aria-hidden className="i-ri-subtract-line size-4" />+ </IconButton>+ <IconButton+ size="lg"+ aria-label={t(($) => $['operation.reset'])}+ disabled={disabled}+ onClick={reset}+ >+ <span aria-hidden className="i-ri-restart-line size-4" />+ </IconButton>+ </>+ )+}diff --git a/web/app/components/base/mermaid/__tests__/index.spec.tsx b/web/app/components/base/mermaid/__tests__/index.spec.tsxdeleted file mode 100644index 54e87b3f43f..00000000000--- a/web/app/components/base/mermaid/__tests__/index.spec.tsx+++ /dev/null@@ -1,194 +0,0 @@-import { act, render, screen, waitFor } from '@testing-library/react'-import userEvent from '@testing-library/user-event'-import mermaid from 'mermaid'-import Flowchart from '../index'--vi.mock('mermaid', () => ({- default: {- initialize: vi.fn(),- render: vi.fn(),- mermaidAPI: { render: vi.fn() },- },-}))--const svg = (label: string) => `<svg xmlns="http://www.w3.org/2000/svg"><text>${label}</text></svg>`-const flushRender = () =>- act(async () => {- await vi.advanceTimersByTimeAsync(700)- })-let sequence = 0-let code: string--beforeEach(() => {- vi.useFakeTimers({ shouldAdvanceTime: true })- code = `graph TD\n A${++sequence}-->B`- vi.mocked(mermaid.initialize).mockImplementation(() => {})- vi.mocked(mermaid.render).mockResolvedValue({- svg: svg('Classic diagram'),- diagramType: 'flowchart',- })- vi.mocked(mermaid.mermaidAPI.render).mockResolvedValue({- svg: svg('Hand drawn diagram'),- diagramType: 'flowchart',- })-})--afterEach(() => {- vi.clearAllTimers()- vi.useRealTimers()- vi.restoreAllMocks()-})--it('debounces streamed code and renders only the latest complete diagram', async () => {- const { rerender } = render(<Flowchart PrimitiveCode="graph" />)- await flushRender()- expect(mermaid.render).not.toHaveBeenCalled()- rerender(<Flowchart PrimitiveCode={code} />)- await act(async () => {- await vi.advanceTimersByTimeAsync(200)- })- const finalCode = `${code}\n B-->C`- rerender(<Flowchart PrimitiveCode={finalCode} />)- expect(mermaid.render).not.toHaveBeenCalled()- await flushRender()- expect(mermaid.render).toHaveBeenCalledTimes(1)- expect(mermaid.render).toHaveBeenCalledWith(expect.any(String), expect.stringContaining('B-->C'))- expect(screen.getByText('Classic diagram')).toBeInTheDocument()-})--it.each([- ['gantt\ntitle T\nTask :after task1, after task2', 'Task :after task1 task2'],- ['gantt\ntitle T\nTask :after task1, 2024-01-01, 1d', 'Task :after task1, 2024-01-01, 1d'],- ['mindmap\n root\n topic1', 'mindmap\n root\n topic1'],- ['sequenceDiagram\n A->>B: Hi', 'sequenceDiagram\n A->>B: Hi'],-])('passes the expected syntax to Mermaid for %s', async (input, expected) => {- render(<Flowchart PrimitiveCode={input} theme="light" />)- await flushRender()- expect(mermaid.render).toHaveBeenCalledWith(expect.any(String), expect.stringContaining(expected))- expect(screen.getByText('Classic diagram')).toBeInTheDocument()-})--it('switches look and theme through the displayed controls', async () => {- const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime })- render(<Flowchart PrimitiveCode={code} theme="light" />)- await flushRender()- await user.click(screen.getByRole('button', { name: 'app.mermaid.handDrawn' }))- await flushRender()- expect(screen.getByText('Hand drawn diagram')).toBeInTheDocument()- expect(screen.getByRole('button', { name: 'app.mermaid.handDrawn' })).toHaveAttribute(- 'aria-pressed',- 'true',- )- await user.click(screen.getByRole('button', { name: 'app.theme.switchDark' }))- await flushRender()- expect(mermaid.initialize).toHaveBeenLastCalledWith(- expect.objectContaining({- theme: 'default',- themeVariables: expect.objectContaining({ primaryBorderColor: '#60a5fa' }),- }),- )- await user.click(screen.getByRole('button', { name: 'app.mermaid.classic' }))- await flushRender()- expect(screen.getByText('Classic diagram')).toBeInTheDocument()- expect(mermaid.initialize).toHaveBeenLastCalledWith(expect.objectContaining({ theme: 'dark' }))-})--it('shows invalid code feedback without sending incomplete syntax to Mermaid', async () => {- render(<Flowchart PrimitiveCode="graph TD\nA -->" />)- await flushRender()- expect(screen.getByText('Diagram code is not complete or invalid.')).toBeInTheDocument()- expect(mermaid.render).not.toHaveBeenCalled()-})--it('shows a rendering failure and recovers when valid code arrives', async () => {- vi.spyOn(console, 'error').mockImplementation(() => {})- vi.mocked(mermaid.render).mockRejectedValue(new Error('Syntax error'))- const { rerender } = render(<Flowchart PrimitiveCode={code} />)- await flushRender()- expect(screen.getByText('Rendering failed: Syntax error')).toBeInTheDocument()- vi.mocked(mermaid.render).mockResolvedValue({- svg: svg('Recovered diagram'),- diagramType: 'flowchart',- })- rerender(<Flowchart PrimitiveCode={`${code}\nB-->C`} />)- await flushRender()- expect(screen.getByText('Recovered diagram')).toBeInTheDocument()- expect(screen.queryByText(/Rendering failed/)).not.toBeInTheDocument()-})--it('shows a configuration failure instead of waiting indefinitely', async () => {- vi.spyOn(console, 'error').mockImplementation(() => {})- const { rerender } = render(<Flowchart PrimitiveCode={code} />)- await flushRender()- vi.mocked(mermaid.initialize).mockImplementation(() => {- throw new Error('Config failed')- })- rerender(<Flowchart PrimitiveCode={`${code}\nB-->C`} />)- await flushRender()- expect(screen.getByText('common.api.actionFailed')).toBeInTheDocument()- expect(screen.queryByText('app.mermaid.waitForCompletion')).not.toBeInTheDocument()-})--it('restores the cached SVG when returning to a previously rendered diagram', async () => {- vi.mocked(mermaid.render)- .mockResolvedValueOnce({ svg: svg('First diagram'), diagramType: 'flowchart' })- .mockResolvedValueOnce({ svg: svg('Second diagram'), diagramType: 'flowchart' })- const { rerender } = render(<Flowchart PrimitiveCode={code} />)- await flushRender()- expect(screen.getByText('First diagram')).toBeInTheDocument()- rerender(<Flowchart PrimitiveCode={`${code}\nB-->C`} />)- await flushRender()- expect(screen.getByText('Second diagram')).toBeInTheDocument()- rerender(<Flowchart PrimitiveCode={code} />)- await flushRender()- expect(screen.getByText('First diagram')).toBeInTheDocument()- expect(screen.queryByText('Second diagram')).not.toBeInTheDocument()- expect(mermaid.render).toHaveBeenCalledTimes(2)-})--it('keeps the current SVG visible while loading and ignores an older render that finishes last', async () => {- let resolveOld!: (value: { svg: string; diagramType: string }) => void- const { rerender } = render(<Flowchart PrimitiveCode={code} />)- await flushRender()- vi.mocked(mermaid.render).mockReturnValueOnce(- new Promise((resolve) => {- resolveOld = resolve- }),- )- rerender(<Flowchart PrimitiveCode={`${code}\nB-->Old`} />)- await flushRender()- expect(screen.getByText('Classic diagram')).toBeInTheDocument()- vi.mocked(mermaid.render).mockResolvedValue({- svg: svg('Latest diagram'),- diagramType: 'flowchart',- })- rerender(<Flowchart PrimitiveCode={`${code}\nB-->Latest`} />)- await flushRender()- expect(screen.getByText('Latest diagram')).toBeInTheDocument()- await act(async () => {- resolveOld({ svg: svg('Obsolete diagram'), diagramType: 'flowchart' })- })- expect(screen.getByText('Latest diagram')).toBeInTheDocument()- expect(screen.queryByText('Obsolete diagram')).not.toBeInTheDocument()-})--it('opens a preview of the rendered SVG and closes it through the preview action', async () => {- render(<Flowchart PrimitiveCode={code} />)- await flushRender()- vi.useRealTimers()- const user = userEvent.setup()-- await user.click(screen.getByText('Classic diagram'))- expect(await screen.findByRole('dialog', { name: 'mermaid_chart' })).toBeInTheDocument()- await user.click(screen.getByRole('button', { name: 'common.operation.cancel' }))- await waitFor(() => {- expect(screen.queryByRole('dialog', { name: 'mermaid_chart' })).not.toBeInTheDocument()- })-})--it('cancels a scheduled render when unmounted', async () => {- const { unmount } = render(<Flowchart PrimitiveCode={code} />)- unmount()- await flushRender()- expect(mermaid.render).not.toHaveBeenCalled()-})diff --git a/web/app/components/base/mermaid/__tests__/utils.spec.ts b/web/app/components/base/mermaid/__tests__/utils.spec.tsdeleted file mode 100644index 00b094754d7..00000000000--- a/web/app/components/base/mermaid/__tests__/utils.spec.ts+++ /dev/null@@ -1,259 +0,0 @@-import {- cleanUpSvgCode,- isMermaidCodeComplete,- prepareMermaidCode,- processSvgForTheme,- sanitizeMermaidCode,- svgToBase64,- waitForDOMElement,-} from '../utils'--const FILL_HEX_RE = /fill="#[a-fA-F0-9]{6}"/g--describe('cleanUpSvgCode', () => {- it('should replace old-style <br> tags with self-closing <br/>', () => {- const result = cleanUpSvgCode('<br>test<br>')- expect(result).toEqual('<br/>test<br/>')- })-})--describe('sanitizeMermaidCode', () => {- describe('Edge Cases', () => {- it('should handle null/non-string input', () => {- // @ts-expect-error need to test null input- expect(sanitizeMermaidCode(null)).toBe('')- // @ts-expect-error need to test undefined input- expect(sanitizeMermaidCode(undefined)).toBe('')- // @ts-expect-error need to test non-string input- expect(sanitizeMermaidCode(123)).toBe('')- })- })-- describe('Security', () => {- it('should remove click directives to prevent link/callback injection', () => {- const unsafeProtocol = ['java', 'script:'].join('')- const input = [- 'gantt',- 'title Demo',- 'section S1',- 'Task 1 :a1, 2020-01-01, 1d',- `click A href "${unsafeProtocol}alert(location.href)"`,- 'click B call callback()',- ].join('\n')-- const result = sanitizeMermaidCode(input)-- expect(result).toContain('gantt')- expect(result).toContain('Task 1')- expect(result).not.toContain('click A')- expect(result).not.toContain('click B')- expect(result).not.toContain(unsafeProtocol)- })-- it('should remove Mermaid init directives to prevent config overrides', () => {- const input = ['%%{init: {"securityLevel":"loose"}}%%', 'graph TD', 'A-->B'].join('\n')-- const result = sanitizeMermaidCode(input)-- expect(result).toEqual(['graph TD', 'A-->B'].join('\n'))- })- })-})--describe('prepareMermaidCode', () => {- describe('Edge Cases', () => {- it('should handle null/non-string input', () => {- // @ts-expect-error need to test null input- expect(prepareMermaidCode(null, 'classic')).toBe('')- })- })-- describe('Sanitization', () => {- it('should sanitize click directives in flowcharts', () => {- const unsafeProtocol = ['java', 'script:'].join('')- const input = ['graph TD', 'A[Click]-->B', `click A href "${unsafeProtocol}alert(1)"`].join(- '\n',- )-- const result = prepareMermaidCode(input, 'classic')-- expect(result).toContain('graph TD')- expect(result).not.toContain('click ')- expect(result).not.toContain(unsafeProtocol)- })-- it('should replace <br> with newline', () => {- const input = 'graph TD\nA[Node<br>Line]-->B'- const result = prepareMermaidCode(input, 'classic')- expect(result).toContain('Node\nLine')- })- })-- describe('HandDrawn Style', () => {- it('should handle handDrawn style specifically', () => {- const input = 'flowchart TD\nstyle A fill:#fff\nlinkStyle 0 stroke:#000\nA-->B'- const result = prepareMermaidCode(input, 'handDrawn')- expect(result).toContain('graph TD')- expect(result).not.toContain('style ')- expect(result).not.toContain('linkStyle ')- expect(result).toContain('A-->B')- })-- it('should add TD fallback for handDrawn if missing', () => {- const input = 'A-->B'- const result = prepareMermaidCode(input, 'handDrawn')- expect(result).toBe('graph TD\nA-->B')- })- })-})--describe('svgToBase64', () => {- it.each(['', '<?xml version="1.0" encoding="UTF-8"?>'])(- 'preserves Unicode SVG content with declaration %s',- async (declaration) => {- const svg = '<svg xmlns="http://www.w3.org/2000/svg"><text>知识库 🧪</text></svg>'- const result = await svgToBase64(`${declaration}${svg}`)- expect(result).toMatch(/^data:image\/svg\+xml(?:;charset=utf-8)?;base64,/)- const decoded = new TextDecoder().decode(- Uint8Array.from(atob(result.split(',')[1]!), (char) => char.charCodeAt(0)),- )- expect(decoded).toContain(svg)- },- )-- describe('Rendering', () => {- it('should return empty string for empty input', async () => {- expect(await svgToBase64('')).toBe('')- })- })-})--describe('processSvgForTheme', () => {- const themes = {- light: {- nodeColors: [{ bg: '#fefefe' }, { bg: '#eeeeee' }],- connectionColor: '#cccccc',- },- dark: {- nodeColors: [{ bg: '#121212' }, { bg: '#222222' }],- connectionColor: '#333333',- },- }-- it.each([false, true])('preserves valid SVG geometry while recoloring dark=%s', (dark) => {- const svg =- '<svg xmlns="http://www.w3.org/2000/svg"><rect x="4" width="20" fill="#ffffff"/><path d="M0 0 L10 10" stroke="#ffffff" stroke-width="2"/><line x1="1" y1="2" x2="3" y2="4" stroke="#ffffff"/><polyline points="0,0 10,10" stroke="#ffffff"/></svg>'- const document = new DOMParser().parseFromString(- processSvgForTheme(svg, dark, false, themes),- 'image/svg+xml',- )- expect(document.querySelector('parsererror')).toBeNull()- expect(document.querySelectorAll('rect')).toHaveLength(1)- expect(document.querySelector('rect')).toHaveAttribute('width', '20')- expect(document.querySelector('rect')).toHaveAttribute('fill', dark ? '#1e293b' : '#ffffff')- expect(document.querySelector('path')).toHaveAttribute('d', 'M0 0 L10 10')- expect(document.querySelector('path')).toHaveAttribute('stroke-width', dark ? '1.5' : '2')- expect(document.querySelector('line')).toHaveAttribute('x2', '3')- expect(document.querySelector('polyline')).toHaveAttribute('points', '0,0 10,10')- for (const element of document.querySelectorAll('path, line, polyline'))- expect(element).toHaveAttribute('stroke', dark ? '#333333' : '#cccccc')- })-- describe('Light Theme', () => {- it('should process light theme node colors', () => {- const svg = '<rect fill="#ffffff" class="node-1"/>'- const result = processSvgForTheme(svg, false, false, themes)- expect(result).toContain('fill="#fefefe"')- })-- it('should process handDrawn style for light theme', () => {- const svg = '<path fill="#ffffff" stroke="#ffffff"/>'- const result = processSvgForTheme(svg, false, true, themes)- expect(result).toContain('fill="#fefefe"')- expect(result).toContain('stroke="#cccccc"')- })- })-- describe('Dark Theme', () => {- it('should process dark theme node colors and general elements', () => {- const svg =- '<rect fill="#ffffff" class="node-1"/><path stroke="#ffffff"/><rect fill="#ffffff" style="fill: #000000; stroke: #000000"/>'- const result = processSvgForTheme(svg, true, false, themes)- expect(result).toContain('fill="#121212"')- expect(result).toContain('fill="#1e293b"') // Generic rect replacement- expect(result).toContain('stroke="#333333"')- })-- it('should handle multiple node colors in cyclic manner', () => {- const svg =- '<rect fill="#ffffff" class="node-1"/><rect fill="#ffffff" class="node-2"/><rect fill="#ffffff" class="node-3"/>'- const result = processSvgForTheme(svg, true, false, themes)- const fillMatches = result.match(FILL_HEX_RE)- expect(fillMatches).toContain('fill="#121212"')- expect(fillMatches).toContain('fill="#222222"')- expect(fillMatches?.filter((f) => f === 'fill="#121212"').length).toBe(2)- })-- it('should process handDrawn style for dark theme', () => {- const svg = '<path fill="#ffffff" stroke="#ffffff"/>'- const result = processSvgForTheme(svg, true, true, themes)- expect(result).toContain('fill="#121212"')- expect(result).toContain('stroke="#333333"')- })- })-})--describe('isMermaidCodeComplete', () => {- describe('Edge Cases', () => {- it('should return false for empty input', () => {- expect(isMermaidCodeComplete('')).toBe(false)- expect(isMermaidCodeComplete(' ')).toBe(false)- })-- it('should detect common syntax errors', () => {- expect(isMermaidCodeComplete('graph TD\nA--> undefined')).toBe(false)- expect(isMermaidCodeComplete('graph TD\nA--> [object Object]')).toBe(false)- expect(isMermaidCodeComplete('graph TD\nA-->')).toBe(false)- })- })-- describe('Chart Types', () => {- it('should validate gantt charts', () => {- expect(isMermaidCodeComplete('gantt\ntitle T\nsection S\nTask')).toBe(true)- expect(isMermaidCodeComplete('gantt\ntitle T')).toBe(false)- })-- it('should validate mindmaps', () => {- expect(isMermaidCodeComplete('mindmap\nroot')).toBe(true)- expect(isMermaidCodeComplete('mindmap')).toBe(false)- })-- it('should validate other chart types', () => {- expect(isMermaidCodeComplete('graph TD\nA-->B')).toBe(true)- expect(isMermaidCodeComplete('pie title P\n"A": 10')).toBe(true)- expect(isMermaidCodeComplete('invalid chart')).toBe(false)- })- })-})--describe('waitForDOMElement', () => {- it('should resolve when callback resolves', async () => {- const cb = vi.fn().mockResolvedValue('success')- const result = await waitForDOMElement(cb)- expect(result).toBe('success')- expect(cb).toHaveBeenCalledTimes(1)- })-- it('should retry on failure', async () => {- const cb = vi.fn().mockRejectedValueOnce(new Error('fail')).mockResolvedValue('success')- const result = await waitForDOMElement(cb, 3, 10)- expect(result).toBe('success')- expect(cb).toHaveBeenCalledTimes(2)- })-- it('should reject after max attempts', async () => {- const cb = vi.fn().mockRejectedValue(new Error('fail'))- await expect(waitForDOMElement(cb, 2, 10)).rejects.toThrow('fail')- expect(cb).toHaveBeenCalledTimes(2)- })-})diff --git a/web/app/components/base/mermaid/index.stories.tsx b/web/app/components/base/mermaid/index.stories.tsxdeleted file mode 100644index 591ba8ff605..00000000000--- a/web/app/components/base/mermaid/index.stories.tsx+++ /dev/null@@ -1,61 +0,0 @@-import type { Meta, StoryObj } from '@storybook/nextjs-vite'-import { useState } from 'react'-import Flowchart from '.'--const SAMPLE = `-flowchart LR- A[User Message] --> B{Agent decides}- B -->|Needs tool| C[Search Tool]- C --> D[Combine result]- B -->|Direct answer| D- D --> E[Send response]-`--const MermaidDemo = ({ theme = 'light' }: { theme?: 'light' | 'dark' }) => {- const [currentTheme, setCurrentTheme] = useState<'light' | 'dark'>(theme)-- return (- <div className="flex w-full max-w-3xl flex-col gap-4 rounded-2xl border border-divider-subtle bg-components-panel-bg p-6">- <div className="flex items-center justify-between text-xs tracking-[0.18em] text-text-tertiary uppercase">- <span>Mermaid diagram</span>- <button- type="button"- className="rounded-md border border-divider-subtle bg-background-default px-3 py-1 text-xs font-medium text-text-secondary hover:bg-state-base-hover"- onClick={() => setCurrentTheme((prev) => (prev === 'light' ? 'dark' : 'light'))}- >- Toggle theme- </button>- </div>- <Flowchart PrimitiveCode={SAMPLE.trim()} theme={currentTheme} />- </div>- )-}--const meta = {- title: 'Base/Data Display/Mermaid',- component: MermaidDemo,- parameters: {- layout: 'centered',- docs: {- description: {- component:- 'Mermaid renderer with custom theme toggle and caching. Useful for visualizing agent flows.',- },- },- },- argTypes: {- theme: {- control: 'inline-radio',- options: ['light', 'dark'],- },- },- args: {- theme: 'light',- },- tags: ['autodocs'],-} satisfies Meta<typeof MermaidDemo>--export default meta-type Story = StoryObj<typeof meta>--export const Playground: Story = {}diff --git a/web/app/components/base/mermaid/index.tsx b/web/app/components/base/mermaid/index.tsxdeleted file mode 100644index 3ea5ea3d34b..00000000000--- a/web/app/components/base/mermaid/index.tsx+++ /dev/null@@ -1,621 +0,0 @@-import type { MermaidConfig } from 'mermaid'-import { Button } from '@langgenius/dify-ui/button'-import { cn } from '@langgenius/dify-ui/cn'-import mermaid from 'mermaid'-import * as React from 'react'-import { useCallback, useEffect, useRef, useState } from 'react'-import { useTranslation } from 'react-i18next'-import LoadingAnim from '@/app/components/base/chat/chat/loading-anim'-import ImagePreview from '@/app/components/base/image-uploader/image-preview'-import { Theme } from '@/types/app'-import {- cleanUpSvgCode,- isMermaidCodeComplete,- prepareMermaidCode,- processSvgForTheme,- sanitizeMermaidCode,- svgToBase64,- waitForDOMElement,-} from './utils'--// Global flags and cache for mermaid-let isMermaidInitialized = false-const diagramCache = new Map<string, string>()-let mermaidAPI: typeof mermaid.mermaidAPI | null = null--if (typeof window !== 'undefined') mermaidAPI = mermaid.mermaidAPI--// Theme configurations-const THEMES = {- light: {- name: 'Light Theme',- background: '#ffffff',- primaryColor: '#ffffff',- primaryBorderColor: '#000000',- primaryTextColor: '#000000',- secondaryColor: '#ffffff',- tertiaryColor: '#ffffff',- nodeColors: [- { bg: '#f0f9ff', color: '#0369a1' },- { bg: '#f0fdf4', color: '#166534' },- { bg: '#fef2f2', color: '#b91c1c' },- { bg: '#faf5ff', color: '#7e22ce' },- { bg: '#fffbeb', color: '#b45309' },- ],- connectionColor: '#74a0e0',- },- dark: {- name: 'Dark Theme',- background: '#1e293b',- primaryColor: '#334155',- primaryBorderColor: '#94a3b8',- primaryTextColor: '#e2e8f0',- secondaryColor: '#475569',- tertiaryColor: '#334155',- nodeColors: [- { bg: '#164e63', color: '#e0f2fe' },- { bg: '#14532d', color: '#dcfce7' },- { bg: '#7f1d1d', color: '#fee2e2' },- { bg: '#581c87', color: '#f3e8ff' },- { bg: '#78350f', color: '#fef3c7' },- ],- connectionColor: '#60a5fa',- },-}--/**- * Initializes mermaid library with default configuration- */-const initMermaid = () => {- if (typeof window !== 'undefined' && !isMermaidInitialized) {- try {- const config: MermaidConfig = {- startOnLoad: false,- fontFamily: 'sans-serif',- securityLevel: 'strict',- flowchart: {- htmlLabels: true,- useMaxWidth: true,- curve: 'basis',- nodeSpacing: 50,- rankSpacing: 70,- },- gantt: {- titleTopMargin: 25,- barHeight: 20,- barGap: 4,- topPadding: 50,- leftPadding: 75,- gridLineStartPadding: 35,- fontSize: 11,- numberSectionStyles: 4,- axisFormat: '%Y-%m-%d',- },- mindmap: {- useMaxWidth: true,- padding: 10,- },- maxTextSize: 50000,- }- mermaid.initialize(config)- isMermaidInitialized = true- } catch (error) {- console.error('Mermaid initialization error:', error)- return null- }- }- return isMermaidInitialized-}--type FlowchartProps = {- PrimitiveCode: string- theme?: 'light' | 'dark'- ref?: React.Ref<HTMLDivElement>-}--const Flowchart = (props: FlowchartProps) => {- const { t } = useTranslation(['app', 'common'])- const [svgString, setSvgString] = useState<string | null>(null)- const [look, setLook] = useState<'classic' | 'handDrawn'>('classic')- const [isInitialized, setIsInitialized] = useState(false)- const [currentTheme, setCurrentTheme] = useState<'light' | 'dark'>(props.theme || 'light')- const containerRef = useRef<HTMLDivElement>(null)- const chartId = useRef(`mermaid-chart-${Math.random().toString(36).slice(2, 11)}`).current- const [isLoading, setIsLoading] = useState(true)- const renderTimeoutRef = useRef<NodeJS.Timeout | undefined>(undefined)- const [errMsg, setErrMsg] = useState('')- const [imagePreviewUrl, setImagePreviewUrl] = useState('')-- /**- * Renders Mermaid chart- */- const renderMermaidChart = async (code: string, style: 'classic' | 'handDrawn') => {- if (style === 'handDrawn') {- // Special handling for hand-drawn style- /* v8 ignore next */- if (containerRef.current) containerRef.current.innerHTML = `<div id="${chartId}"></div>`- await new Promise((resolve) => setTimeout(resolve, 30))-- if (typeof window !== 'undefined' && mermaidAPI) {- // Prefer using mermaidAPI directly for hand-drawn style- return await mermaidAPI.render(chartId, code)- } else {- // Fall back to standard rendering if mermaidAPI is not available- const { svg } = await mermaid.render(chartId, code)- return { svg }- }- } else {- // Standard rendering for classic style - using the extracted waitForDOMElement function- const renderWithRetry = async () => {- /* v8 ignore next */- if (containerRef.current) containerRef.current.innerHTML = `<div id="${chartId}"></div>`- await new Promise((resolve) => setTimeout(resolve, 30))- const { svg } = await mermaid.render(chartId, code)- return { svg }- }- return await waitForDOMElement(renderWithRetry)- }- }-- /**- * Handle rendering errors- */- const handleRenderError = (error: unknown) => {- console.error('Mermaid rendering error:', error)-- // On any render error, assume the mermaid state is corrupted and force a re-initialization.- try {- diagramCache.clear() // Clear cache to prevent using potentially corrupted SVGs- isMermaidInitialized = false // <-- THE FIX: Force re-initialization- initMermaid() // Re-initialize with the default safe configuration- } catch (reinitError) {- console.error('Failed to re-initialize Mermaid after error:', reinitError)- }-- setErrMsg(- `Rendering failed: ${(error as Error).message || 'Unknown error. Please check the console.'}`,- )- setIsLoading(false)- }-- // Initialize mermaid- useEffect(() => {- const api = initMermaid()- // oxlint-disable-next-line eslint-react/set-state-in-effect -- Synchronize loading and error UI with the imperative Mermaid renderer initialization and debounced rendering lifecycle.- if (api) setIsInitialized(true)- else {- // oxlint-disable-next-line eslint-react/set-state-in-effect -- Synchronize loading and error UI with the imperative Mermaid renderer initialization and debounced rendering lifecycle.- setIsLoading(false)- // oxlint-disable-next-line eslint-react/set-state-in-effect -- Synchronize loading and error UI with the imperative Mermaid renderer initialization and debounced rendering lifecycle.- setErrMsg(t(($) => $['api.actionFailed'], { ns: 'common' }))- }- }, [])-- // Update theme when prop changes, but allow internal override.- const prevThemeRef = useRef<string | undefined>(undefined)- useEffect(() => {- // Only react if the theme prop from the outside has actually changed.- if (props.theme && props.theme !== prevThemeRef.current) {- // When the global theme prop changes, it should act as the source of truth,- // overriding any local theme selection.- diagramCache.clear()- setSvgString(null)- setCurrentTheme(props.theme)- // Reset look to classic for a consistent state after a global change.- setLook('classic')- }- // Update the ref to the current prop value for the next render.- prevThemeRef.current = props.theme- }, [props.theme])-- const renderFlowchart = useCallback(- async (primitiveCode: string, isCurrent: () => boolean) => {- /* v8 ignore next */- if (!isInitialized || !containerRef.current) {- /* v8 ignore next */- setIsLoading(false)- /* v8 ignore next */- setErrMsg(!isInitialized ? 'Mermaid initialization failed' : 'Container element not found')- return- }-- const cacheKey = `${primitiveCode}-${look}-${currentTheme}`-- setIsLoading(true)- setErrMsg('')-- try {- let finalCode: string-- const trimmedCode = primitiveCode.trim()- const isGantt = trimmedCode.startsWith('gantt')- const isMindMap = trimmedCode.startsWith('mindmap')- const isSequence = trimmedCode.startsWith('sequenceDiagram')-- if (isGantt || isMindMap || isSequence) {- if (isGantt) {- finalCode = trimmedCode- .split('\n')- .map((line) => {- // Gantt charts have specific syntax needs.- const taskMatch = /^\s*([^:]+?)\s*:\s*(.*)/.exec(line)- if (!taskMatch) return line // Not a task line, return as is.-- const taskName = taskMatch[1]!.trim()- let paramsStr = taskMatch[2]!.trim()-- // Rule 1: Correct multiple "after" dependencies ONLY if they exist.- // This is a common mistake, e.g., "..., after task1, after task2, ..."- paramsStr = paramsStr.replace(/,\s*after\s+/g, ' ')-- // Rule 2: Normalize spacing between parameters for consistency.- const finalParams = paramsStr.replace(/\s*,\s*/g, ', ').trim()- return `${taskName} :${finalParams}`- })- .join('\n')- } else {- // For mindmap and sequence charts, which are sensitive to syntax,- // pass the code through directly.- finalCode = trimmedCode- }- } else {- // Step 1: Clean and prepare Mermaid code using the extracted prepareMermaidCode function- // This function handles flowcharts appropriately.- finalCode = prepareMermaidCode(primitiveCode, look)- }-- finalCode = sanitizeMermaidCode(finalCode)-- // Step 2: Render chart- const svgGraph = await renderMermaidChart(finalCode, look)- if (!isCurrent()) return-- // Step 3: Apply theme to SVG using the extracted processSvgForTheme function- const processedSvg = processSvgForTheme(- svgGraph.svg,- currentTheme === Theme.dark,- look === 'handDrawn',- THEMES,- )-- // Step 4: Clean up SVG code- const cleanedSvg = cleanUpSvgCode(processedSvg)-- diagramCache.set(cacheKey, cleanedSvg)- setSvgString(cleanedSvg)-- setIsLoading(false)- } catch (error) {- // Error handling- if (isCurrent()) handleRenderError(error)- }- },- [chartId, isInitialized, look, currentTheme, t],- )-- const configureMermaid = useCallback(- (primitiveCode: string) => {- if (typeof window !== 'undefined' && isInitialized) {- const themeVars = THEMES[currentTheme]- const config: MermaidConfig = {- startOnLoad: false,- securityLevel: 'strict',- fontFamily: 'sans-serif',- maxTextSize: 50000,- gantt: {- titleTopMargin: 25,- barHeight: 20,- barGap: 4,- topPadding: 50,- leftPadding: 75,- gridLineStartPadding: 35,- fontSize: 11,- numberSectionStyles: 4,- axisFormat: '%Y-%m-%d',- },- mindmap: {- useMaxWidth: true,- padding: 10,- },- }-- const isFlowchart =- primitiveCode.trim().startsWith('graph') || primitiveCode.trim().startsWith('flowchart')-- if (look === 'classic') {- config.theme = currentTheme === 'dark' ? 'dark' : 'neutral'-- if (isFlowchart) {- type FlowchartConfigWithRanker = NonNullable<MermaidConfig['flowchart']> & {- ranker?: string- }- const flowchartConfig: FlowchartConfigWithRanker = {- htmlLabels: true,- useMaxWidth: true,- nodeSpacing: 60,- rankSpacing: 80,- curve: 'linear',- ranker: 'tight-tree',- }- config.flowchart = flowchartConfig as MermaidConfig['flowchart']- }-- if (currentTheme === 'dark') {- config.themeVariables = {- background: themeVars.background,- primaryColor: themeVars.primaryColor,- primaryBorderColor: themeVars.primaryBorderColor,- primaryTextColor: themeVars.primaryTextColor,- secondaryColor: themeVars.secondaryColor,- tertiaryColor: themeVars.tertiaryColor,- }- }- } else {- // look === 'handDrawn'- config.theme = 'default'- config.themeCSS = `- .node rect { fill-opacity: 0.85; }- .edgePath .path { stroke-width: 1.5px; }- .label { font-family: 'sans-serif'; }- .edgeLabel { font-family: 'sans-serif'; }- .cluster rect { rx: 5px; ry: 5px; }- `- config.themeVariables = {- fontSize: '14px',- fontFamily: 'sans-serif',- primaryBorderColor:- currentTheme === 'dark' ? THEMES.dark.connectionColor : THEMES.light.connectionColor,- }-- if (isFlowchart) {- config.flowchart = {- htmlLabels: true,- useMaxWidth: true,- nodeSpacing: 40,- rankSpacing: 60,- curve: 'basis',- }- }- }-- try {- mermaid.initialize(config)- return true- } catch (error) {- console.error('Config error:', error)- return false- }- }- return false- },- [currentTheme, isInitialized, look],- )-- // This is the main rendering effect.- // It triggers whenever the code, theme, or style changes.- useEffect(() => {- if (!isInitialized) return- let active = true-- // Don't render if code is too short- if (!props.PrimitiveCode || props.PrimitiveCode.length < 10) {- // oxlint-disable-next-line eslint-react/set-state-in-effect -- Synchronize loading and error UI with the imperative Mermaid renderer initialization and debounced rendering lifecycle.- setIsLoading(false)- // oxlint-disable-next-line eslint-react/set-state-in-effect -- Synchronize loading and error UI with the imperative Mermaid renderer initialization and debounced rendering lifecycle.- setSvgString(null)- return- }-- // Use a timeout to handle streaming code and debounce rendering- if (renderTimeoutRef.current) clearTimeout(renderTimeoutRef.current)-- // oxlint-disable-next-line eslint-react/set-state-in-effect -- Synchronize loading and error UI with the imperative Mermaid renderer initialization and debounced rendering lifecycle.- setIsLoading(true)-- renderTimeoutRef.current = setTimeout(() => {- // Final validation before rendering- if (!isMermaidCodeComplete(props.PrimitiveCode)) {- setIsLoading(false)- setErrMsg('Diagram code is not complete or invalid.')- return- }-- const cacheKey = `${props.PrimitiveCode}-${look}-${currentTheme}`- if (diagramCache.has(cacheKey)) {- setErrMsg('')- setSvgString(diagramCache.get(cacheKey)!)- setIsLoading(false)- return- }-- if (configureMermaid(props.PrimitiveCode)) renderFlowchart(props.PrimitiveCode, () => active)- else {- setIsLoading(false)- setErrMsg(t(($) => $['api.actionFailed'], { ns: 'common' }))- }- }, 300) // 300ms debounce-- return () => {- active = false- clearTimeout(renderTimeoutRef.current)- }- }, [props.PrimitiveCode, look, currentTheme, isInitialized, configureMermaid, renderFlowchart])-- // Cleanup on unmount- useEffect(() => {- return () => {- if (renderTimeoutRef.current) clearTimeout(renderTimeoutRef.current)- }- }, [])-- const handlePreviewClick = async () => {- if (!svgString) return- const base64 = await svgToBase64(svgString)- setImagePreviewUrl(base64)- }-- const toggleTheme = () => {- const newTheme = currentTheme === 'light' ? 'dark' : 'light'- // Ensure a full, clean re-render cycle, consistent with global theme change.- diagramCache.clear()- setSvgString(null)- setCurrentTheme(newTheme)- }-- // Style classes for theme-dependent elements- const themeClasses = {- container: cn('relative', {- 'bg-white': currentTheme === Theme.light,- 'bg-slate-900': currentTheme === Theme.dark,- }),- mermaidDiv: cn('mermaid relative h-auto w-full cursor-pointer', {- 'bg-white': currentTheme === Theme.light,- 'bg-slate-900': currentTheme === Theme.dark,- }),- errorMessage: cn('px-6.5 py-4', {- 'text-red-500': currentTheme === Theme.light,- 'text-red-400': currentTheme === Theme.dark,- }),- errorIcon: cn('size-6', {- 'text-red-500': currentTheme === Theme.light,- 'text-red-400': currentTheme === Theme.dark,- }),- segmented: cn('msh-segmented msh-segmented-sm css-23bs09 css-var-r1', {- 'text-gray-700': currentTheme === Theme.light,- 'text-gray-300': currentTheme === Theme.dark,- }),- themeToggle: cn(- 'flex size-10 items-center justify-center rounded-full shadow-md backdrop-blur-xs transition-all duration-300',- {- 'border border-gray-200 bg-white/80 text-gray-700 hover:bg-white hover:shadow-lg':- currentTheme === Theme.light,- 'border border-slate-600 bg-slate-800/80 text-yellow-300 hover:bg-slate-700 hover:shadow-lg':- currentTheme === Theme.dark,- },- ),- }-- // Style classes for look options- const getLookButtonClass = (lookType: 'classic' | 'handDrawn') => {- return cn(- 'mb-4 flex h-8 w-[calc((100%-8px)/2)] cursor-pointer items-center justify-center rounded-lg border border-components-option-card-option-border bg-components-option-card-option-bg system-sm-medium text-text-secondary',- look === lookType &&- 'border-[1.5px] border-components-option-card-option-selected-border bg-components-option-card-option-selected-bg text-text-primary',- currentTheme === Theme.dark && 'border-slate-600 bg-slate-800 text-slate-300',- look === lookType && currentTheme === Theme.dark && 'border-blue-500 bg-slate-700 text-white',- )- }- const themeToggleTitleByTheme = {- light: t(($) => $['theme.switchDark'], { ns: 'app' }),- dark: t(($) => $['theme.switchLight'], { ns: 'app' }),- } as const-- return (- <div ref={props.ref as React.RefObject<HTMLDivElement>} className={themeClasses.container}>- <div className={themeClasses.segmented}>- <div className="msh-segmented-group">- <div className="msh-segmented-item m-2 flex w-50 items-center space-x-1">- <Button- type="button"- aria-pressed={look === 'classic'}- key="classic"- className={getLookButtonClass('classic')}- onClick={() => {- if (look !== 'classic') {- diagramCache.clear()- setSvgString(null)- setLook('classic')- }- }}- >- <div className="msh-segmented-item-label">- {t(($) => $['mermaid.classic'], { ns: 'app' })}- </div>- </Button>- <Button- type="button"- aria-pressed={look === 'handDrawn'}- key="handDrawn"- className={getLookButtonClass('handDrawn')}- onClick={() => {- if (look !== 'handDrawn') {- diagramCache.clear()- setSvgString(null)- setLook('handDrawn')- }- }}- >- <div className="msh-segmented-item-label">- {t(($) => $['mermaid.handDrawn'], { ns: 'app' })}- </div>- </Button>- </div>- </div>- </div>-- <div- ref={containerRef}- style={{ position: 'absolute', visibility: 'hidden', height: 0, overflow: 'hidden' }}- />-- {isLoading && !svgString && (- <div className="px-6.5 py-4">- <LoadingAnim type="text" />- <div className="mt-2 text-sm text-gray-500">- {t(($) => $['mermaid.waitForCompletion'], { ns: 'app' })}- </div>- </div>- )}-- {svgString && (- <div- className={themeClasses.mermaidDiv}- style={{ objectFit: 'cover' }}- onClick={handlePreviewClick}- >- <div className="absolute bottom-2 left-2">- <button- type="button"- onClick={(e) => {- e.stopPropagation()- toggleTheme()- }}- className={themeClasses.themeToggle}- title={themeToggleTitleByTheme[currentTheme] || ''}- style={{ transform: 'translate3d(0, 0, 0)' }}- >- {currentTheme === Theme.light ? (- <span className="i-heroicons-moon-solid size-5" />- ) : (- <span className="i-heroicons-sun-solid size-5" />- )}- </button>- </div>-- <div style={{ maxWidth: '100%' }} dangerouslySetInnerHTML={{ __html: svgString }} />- </div>- )}-- {errMsg && (- <div className={themeClasses.errorMessage}>- <div className="flex items-center">- <span className={`i-heroicons-exclamation-triangle ${themeClasses.errorIcon}`} />- <span className="ml-2">{errMsg}</span>- </div>- </div>- )}-- {imagePreviewUrl && (- <ImagePreview- title="mermaid_chart"- url={imagePreviewUrl}- onCancel={() => setImagePreviewUrl('')}- />- )}- </div>- )-}--Flowchart.displayName = 'Flowchart'--export default Flowchartdiff --git a/web/app/components/base/mermaid/utils.ts b/web/app/components/base/mermaid/utils.tsdeleted file mode 100644index 49c4f03946e..00000000000--- a/web/app/components/base/mermaid/utils.ts+++ /dev/null@@ -1,200 +0,0 @@-export function cleanUpSvgCode(svgCode: string): string {- return svgCode.replaceAll('<br>', '<br/>')-}--export const sanitizeMermaidCode = (mermaidCode: string): string => {- if (!mermaidCode || typeof mermaidCode !== 'string') return ''-- return mermaidCode- .split('\n')- .filter((line) => {- const trimmed = line.trimStart()-- // Mermaid directives can override config; treat as untrusted in chat context.- if (trimmed.startsWith('%%{')) return false-- // Mermaid click directives can create JS callbacks/links inside rendered SVG.- if (trimmed.startsWith('click ')) return false-- return true- })- .join('\n')-}--/**- * Prepares mermaid code for rendering by sanitizing common syntax issues.- * @param {string} mermaidCode - The mermaid code to prepare- * @param {'classic' | 'handDrawn'} style - The rendering style- * @returns {string} - The prepared mermaid code- */-export const prepareMermaidCode = (mermaidCode: string, style: 'classic' | 'handDrawn'): string => {- if (!mermaidCode || typeof mermaidCode !== 'string') return ''-- let code = sanitizeMermaidCode(mermaidCode.trim())-- // Convenience: Basic BR replacement. This is a common and safe operation.- code = code.replace(/<br\s*\/?>/g, '\n')-- let finalCode = code-- // Hand-drawn style requires some specific clean-up.- if (style === 'handDrawn') {- finalCode = finalCode- .replace(/style\s+[^\n]+/g, '')- .replace(/linkStyle\s+[^\n]+/g, '')- .replace(/^flowchart/, 'graph')- .replace(/class="[^"]*"/g, '')- .replace(/fill="[^"]*"/g, '')- .replace(/stroke="[^"]*"/g, '')-- // Ensure hand-drawn style charts always start with graph- if (!finalCode.startsWith('graph') && !finalCode.startsWith('flowchart'))- finalCode = `graph TD\n${finalCode}`- }-- return finalCode-}--/**- * Converts SVG to base64 string for image rendering- */-export function svgToBase64(svgGraph: string): Promise<string> {- if (!svgGraph) return Promise.resolve('')-- try {- // Ensure SVG has correct XML declaration- if (!svgGraph.includes('<?xml')) svgGraph = `<?xml version="1.0" encoding="UTF-8"?>${svgGraph}`-- const blob = new Blob([new TextEncoder().encode(svgGraph)], {- type: 'image/svg+xml;charset=utf-8',- })- return new Promise((resolve, reject) => {- const reader = new FileReader()- reader.onloadend = () => resolve(reader.result as string)- reader.onerror = reject- reader.readAsDataURL(blob)- })- } catch {- return Promise.resolve('')- }-}--/**- * Processes SVG for theme styling- */-export function processSvgForTheme(- svg: string,- isDark: boolean,- isHandDrawn: boolean,- themes: {- light: any- dark: any- },-): string {- let processedSvg = svg- const theme = isDark ? themes.dark : themes.light- if (isDark) {- processedSvg = processedSvg- .replace(/style="fill: ?#000000"/g, 'style="fill: #e2e8f0"')- .replace(/style="stroke: ?#000000"/g, 'style="stroke: #94a3b8"')- .replace(/<rect\b[^>]*>/g, (element) => element.replace('fill="#ffffff"', 'fill="#1e293b"'))- }- if (isHandDrawn) {- return processedSvg- .replace(/fill="#[a-fA-F0-9]{6}"/g, `fill="${theme.nodeColors[0].bg}"`)- .replace(/stroke="#[a-fA-F0-9]{6}"/g, `stroke="${theme.connectionColor}"`)- .replace(/stroke-width="1"/g, 'stroke-width="1.5"')- }- let nodeIndex = 0- processedSvg = processedSvg.replace(- /fill="#[a-fA-F0-9]{6}"[^>]*class="node-[^"]*"/g,- (element) => {- const color = theme.nodeColors[nodeIndex % theme.nodeColors.length].bg- nodeIndex++- return element.replace(/fill="#[a-fA-F0-9]{6}"/, `fill="${color}"`)- },- )- return processedSvg.replace(/<(?:path|line|polyline)\b[^>]*>/g, (element) => {- if (!/stroke="#[a-fA-F0-9]{6}"/.test(element)) return element- const recolored = element.replace(- /stroke="#[a-fA-F0-9]{6}"/,- `stroke="${theme.connectionColor}"`,- )- if (!isDark) return recolored- return /stroke-width="[^"]*"/.test(recolored)- ? recolored.replace(/stroke-width="[^"]*"/, 'stroke-width="1.5"')- : recolored.replace(/(\s*\/?>)$/, ' stroke-width="1.5"$1')- })-}--/**- * Checks if mermaid code is complete and valid- */-export function isMermaidCodeComplete(code: string): boolean {- if (!code || code.trim().length === 0) return false-- try {- const trimmedCode = code.trim()-- // Special handling for gantt charts- if (trimmedCode.startsWith('gantt')) {- // For gantt charts, check if it has at least a title and one task- const lines = trimmedCode.split('\n').filter((line) => line.trim().length > 0)- return lines.length >= 3- }-- // Special handling for mindmaps- if (trimmedCode.startsWith('mindmap')) {- // For mindmaps, check if it has at least a root node- const lines = trimmedCode.split('\n').filter((line) => line.trim().length > 0)- return lines.length >= 2- }-- // Check for basic syntax structure- const hasValidStart =- /^(?:graph|flowchart|sequenceDiagram|classDiagram|classDef|class|stateDiagram|gantt|pie|er|journey|requirementDiagram|mindmap)/.test(- trimmedCode,- )-- // The balanced bracket check was too strict and produced false negatives for valid- // mermaid syntax like the asymmetric shape `A>B]`. Relying on Mermaid's own- // parser is more robust.- const isBalanced = true-- // Check for common syntax errors- const hasNoSyntaxErrors =- !trimmedCode.includes('undefined') &&- !trimmedCode.includes('[object Object]') &&- trimmedCode- .split('\n')- .every((line) => !(line.includes('-->') && !/\S+\s*-->\s*\S+/.exec(line)))-- return hasValidStart && isBalanced && hasNoSyntaxErrors- } catch (error) {- console.error('Mermaid code validation error:', error)- return false- }-}--/**- * Helper to wait for DOM element with retry mechanism- */-export function waitForDOMElement<T>(- callback: () => Promise<T>,- maxAttempts = 3,- delay = 100,-): Promise<T> {- return new Promise((resolve, reject) => {- let attempts = 0- const tryRender = async () => {- try {- resolve(await callback())- } catch (error) {- attempts++- if (attempts < maxAttempts) setTimeout(tryRender, delay)- else reject(error)- }- }- tryRender()- })-}diff --git a/web/app/components/datasets/create-from-pipeline/list/template-card/__tests__/focus.browser.spec.tsx b/web/app/components/datasets/create-from-pipeline/list/template-card/__tests__/focus.browser.spec.tsxindex 610e4ae650b..c18d1371074 100644--- a/web/app/components/datasets/create-from-pipeline/list/template-card/__tests__/focus.browser.spec.tsx+++ b/web/app/components/datasets/create-from-pipeline/list/template-card/__tests__/focus.browser.spec.tsx@@ -51,7 +51,13 @@ describe('Template card focus', () => {// Browser mode is required: display:none prevents native focus restoration,// and CSS hover/focus-within decides whether the returned button is visible.const queryClient = new QueryClient({- defaultOptions: { queries: { retry: false, staleTime: Infinity } },+ defaultOptions: {+ queries: {+ retry: false,+ refetchOnMount: false,+ refetchOnWindowFocus: false,+ },+ },})queryClient.setQueryData(consoleQuery.rag.pipeline.templates.byTemplateId.get.queryKey({diff --git a/web/docs/test.md b/web/docs/test.mdindex 8461915fcdb..36e295251cc 100644--- a/web/docs/test.md+++ b/web/docs/test.md@@ -23,7 +23,7 @@ Coverage is a diagnostic signal, not a quality target. This guide defines no reqThe unit coverage report includes authored JavaScript and TypeScript throughout `web/`, including runtime entry points, scripts, plugins, and files that no test imports. It excludes test infrastructure, stories, declarations, generated sources, tool configuration, build output, and vendored static code. TypeScript modules containing only erased types have no executable statements and are not meaningful zero-coverage findings. Local coverage runs also produce an HTML report at `coverage/index.html`.-Run the full `unit` project before using coverage to identify untested modules. A focused run measures only the selected tests. Zero unit coverage does not imply that Browser Mode or E2E never exercises the file; those suites do not contribute to this report. Anonymous VM scripts and subprocesses can also execute code without attributing coverage to its source file. Check existing tests and separate product modules from development tooling when prioritizing the findings.+Run the full `unit` project before using coverage to identify untested modules. A focused run measures only the selected tests. CI collects Browser Mode coverage separately and combines it with unit coverage under the same Codecov `web` flag. Zero unit coverage does not imply that Browser Mode or E2E never exercises the file; E2E does not contribute to the coverage report. Anonymous VM scripts and subprocesses can also execute code without attributing coverage to its source file. Check existing tests and separate product modules from development tooling when prioritizing the findings.## Choose the Right Boundarydiff --git a/web/i18n/locales/ar-TN/app.json b/web/i18n/locales/ar-TN/app.jsonindex 8f38ee4858d..a0cd86eb7d9 100644--- a/web/i18n/locales/ar-TN/app.json+++ b/web/i18n/locales/ar-TN/app.json@@ -162,9 +162,7 @@"maxActiveRequests": "أقصى عدد للطلبات المتزامنة","maxActiveRequestsPlaceholder": "أدخل 0 لغير محدود","maxActiveRequestsTip": "الحد الأقصى لعدد الطلبات النشطة المتزامنة لكل تطبيق (0 لغير محدود)",- "mermaid.classic": "كلاسيكي",- "mermaid.handDrawn": "رسم يدوي",- "mermaid.waitForCompletion": "جارٍ انتظار اكتمال رمز المخطط...",+ "mermaid.preview": "معاينة المخطط","newApp.Cancel": "إلغاء","newApp.Confirm": "تأكيد","newApp.Create": "إنشاء",@@ -246,8 +244,6 @@"switchTip": "غير مسموح","switchTipEnd": " بالعودة إلى Basic Orchestrate.","switchTipStart": "سيتم إنشاء نسخة تطبيق جديدة لك، وستنتقل النسخة الجديدة إلى Workflow Orchestrate. النسخة الجديدة ستكون ",- "theme.switchDark": "التبديل إلى الوضع الداكن",- "theme.switchLight": "التبديل إلى الوضع الفاتح","tracing.aliyun.description": "منصة المراقبة المدارة بالكامل والتي لا تحتاج إلى صيانة والمقدمة من Alibaba Cloud، تتيح المراقبة الجاهزة والتتبع وتقييم تطبيقات Dify.","tracing.aliyun.title": "Cloud Monitor","tracing.arize.description": "مراقبة LLM على مستوى المؤسسة، والتقييم عبر الإنترنت وغير المتصل بالإنترنت، والمراقبة، والتجريب - بدعم من OpenTelemetry. مصمم خصيصًا لتطبيقات LLM والتطبيقات التي تعتمد على الوكيل.",diff --git a/web/i18n/locales/az-AZ/app.json b/web/i18n/locales/az-AZ/app.jsonindex eb16ef0b5e7..4ff97acb8d7 100644--- a/web/i18n/locales/az-AZ/app.json+++ b/web/i18n/locales/az-AZ/app.json@@ -162,9 +162,7 @@"maxActiveRequests": "Maksimum eynivaxtlı sorğu sayı","maxActiveRequestsPlaceholder": "Məhdudiyyətsiz olması üçün 0 daxil edin","maxActiveRequestsTip": "Hər tətbiq üçün eynivaxtlı aktiv sorğuların maksimum sayı (məhdudiyyətsiz olması üçün 0)",- "mermaid.classic": "Klassik",- "mermaid.handDrawn": "Əl ilə çəkilmiş",- "mermaid.waitForCompletion": "Diaqram kodunun tamamlanması gözlənilir...",+ "mermaid.preview": "Diaqramın önizləməsi","newApp.Cancel": "Ləğv et","newApp.Confirm": "Təsdiqlə","newApp.Create": "Yarat",@@ -246,8 +244,6 @@"switchTip": "mümkün olmayacaq","switchTipEnd": ".","switchTipStart": "Sizin üçün yeni tətbiq nüsxəsi yaradılacaq və bu nüsxə iş axınının təşkili rejiminə keçəcək. Yeni nüsxədə əsas təşkil rejiminə geri keçmək ",- "theme.switchDark": "Tünd temaya keç",- "theme.switchLight": "Açıq temaya keç","tracing.aliyun.description": "Alibaba Cloud tərəfindən təqdim edilən, tam idarə olunan və texniki xidmət tələb etməyən müşahidə platforması Dify tətbiqlərinin hazır monitorinq, izləmə və qiymətləndirmə imkanlarını təmin edir.","tracing.aliyun.title": "Cloud Monitor","tracing.arize.description": "OpenTelemetry əsasında müəssisə səviyyəli LLM müşahidəsi, onlayn və oflayn qiymətləndirmə, monitorinq və təcrübələr. LLM və agent əsaslı tətbiqlər üçün xüsusi hazırlanıb.",diff --git a/web/i18n/locales/de-DE/app.json b/web/i18n/locales/de-DE/app.jsonindex 3dd89ee4721..d3d1cbdb361 100644--- a/web/i18n/locales/de-DE/app.json+++ b/web/i18n/locales/de-DE/app.json@@ -162,9 +162,7 @@"maxActiveRequests": "Maximale gleichzeitige Anfragen","maxActiveRequestsPlaceholder": "Geben Sie 0 für unbegrenzt ein","maxActiveRequestsTip": "Maximale Anzahl gleichzeitiger aktiver Anfragen pro App (0 für unbegrenzt)",- "mermaid.classic": "Klassisch",- "mermaid.handDrawn": "Handgezeichnet",- "mermaid.waitForCompletion": "Warten auf die Fertigstellung des Diagrammcodes...",+ "mermaid.preview": "Diagrammvorschau","newApp.Cancel": "Abbrechen","newApp.Confirm": "Bestätigen","newApp.Create": "Erstellen",@@ -246,8 +244,6 @@"switchTip": "nicht erlauben","switchTipEnd": " zur Basis-Orchestrierung zurückzuwechseln.","switchTipStart": "Eine neue App-Kopie wird für Sie erstellt, und die neue Kopie wird zur Workflow-Orchestrierung wechseln. Die neue Kopie wird ",- "theme.switchDark": "Zum dunklen Modus wechseln",- "theme.switchLight": "Zum hellen Thema wechseln","tracing.aliyun.description": "Die vollständig verwaltete und wartungsfreie Observability-Plattform von Alibaba Cloud ermöglicht eine sofortige Überwachung, Verfolgung und Bewertung von Dify-Anwendungen.","tracing.aliyun.title": "Cloud-Monitor","tracing.arize.description": "Unternehmensgerechte LLM-Observierbarkeit, Online- und Offline-Bewertung, Überwachung und Experimentierung—unterstützt durch OpenTelemetry. Speziell für LLM- und agentenbasierte Anwendungen entwickelt.",diff --git a/web/i18n/locales/en-US/app.json b/web/i18n/locales/en-US/app.jsonindex 0328b0d4fd6..dc231a931da 100644--- a/web/i18n/locales/en-US/app.json+++ b/web/i18n/locales/en-US/app.json@@ -162,9 +162,7 @@"maxActiveRequests": "Max concurrent requests","maxActiveRequestsPlaceholder": "Enter 0 for unlimited","maxActiveRequestsTip": "Maximum number of concurrent active requests per app (0 for unlimited)",- "mermaid.classic": "Classic",- "mermaid.handDrawn": "Hand Drawn",- "mermaid.waitForCompletion": "Waiting for diagram code to complete...",+ "mermaid.preview": "Preview diagram","newApp.Cancel": "Cancel","newApp.Confirm": "Confirm","newApp.Create": "Create",@@ -246,8 +244,6 @@"switchTip": "not allow","switchTipEnd": " switching back to Basic Orchestrate.","switchTipStart": "A new app copy will be created for you, and the new copy will switch to Workflow Orchestrate. The new copy will ",- "theme.switchDark": "Switch to dark theme",- "theme.switchLight": "Switch to light theme","tracing.aliyun.description": "The fully-managed and maintenance-free observability platform provided by Alibaba Cloud, enables out-of-the-box monitoring, tracing, and evaluation of Dify applications.","tracing.aliyun.title": "Cloud Monitor","tracing.arize.description": "Enterprise-grade LLM observability, online & offline evaluation, monitoring, and experimentation—powered by OpenTelemetry. Purpose-built for LLM & agent-driven applications.",diff --git a/web/i18n/locales/es-ES/app.json b/web/i18n/locales/es-ES/app.jsonindex b7e1743e677..b119ca8c326 100644--- a/web/i18n/locales/es-ES/app.json+++ b/web/i18n/locales/es-ES/app.json@@ -162,9 +162,7 @@"maxActiveRequests": "Máximas solicitudes concurrentes","maxActiveRequestsPlaceholder": "Introduce 0 para ilimitado","maxActiveRequestsTip": "Número máximo de solicitudes activas concurrentes por aplicación (0 para ilimitado)",- "mermaid.classic": "Clásico",- "mermaid.handDrawn": "Dibujado a mano",- "mermaid.waitForCompletion": "Esperando a que se complete el código del diagrama...",+ "mermaid.preview": "Vista previa del diagrama","newApp.Cancel": "Cancelar","newApp.Confirm": "Confirmar","newApp.Create": "Crear",@@ -246,8 +244,6 @@"switchTip": "volver","switchTipEnd": " a la Orquestación Básica.","switchTipStart": "Se creará una nueva copia de la app para ti y la nueva copia cambiará a Orquestación de Flujo de Trabajo. La nueva copia no permitirá",- "theme.switchDark": "Cambiar a tema oscuro",- "theme.switchLight": "Cambiar a tema claro","tracing.aliyun.description": "La plataforma de observabilidad totalmente gestionada y sin mantenimiento proporcionada por Alibaba Cloud, permite la monitorización, trazado y evaluación de aplicaciones Dify de manera inmediata.","tracing.aliyun.title": "Monitor de Nubes","tracing.arize.description": "Observabilidad de LLM de nivel empresarial, evaluación en línea y fuera de línea, monitoreo y experimentación—impulsada por OpenTelemetry. Diseñada específicamente para aplicaciones impulsadas por LLM y agentes.",diff --git a/web/i18n/locales/fa-IR/app.json b/web/i18n/locales/fa-IR/app.jsonindex 15196959f28..187cc20bee2 100644--- a/web/i18n/locales/fa-IR/app.json+++ b/web/i18n/locales/fa-IR/app.json@@ -162,9 +162,7 @@"maxActiveRequests": "بیشترین درخواستهای همزمان","maxActiveRequestsPlaceholder": "برای نامحدود، 0 را وارد کنید","maxActiveRequestsTip": "حداکثر تعداد درخواستهای فعال همزمان در هر برنامه (0 برای نامحدود)",- "mermaid.classic": "کلاسیک",- "mermaid.handDrawn": "دست کشیده شده",- "mermaid.waitForCompletion": "در انتظار تکمیل کد نمودار...",+ "mermaid.preview": "پیشنمایش نمودار","newApp.Cancel": "لغو","newApp.Confirm": "تایید","newApp.Create": "ایجاد",@@ -246,8 +244,6 @@"switchTip": "اجازه نمیدهد","switchTipEnd": " تغییر به سازماندهی اساسی بازگردد.","switchTipStart": "یک نسخه جدید از برنامه برای شما ایجاد خواهد شد و نسخه جدید به سازماندهی گردش کار تغییر خواهد کرد. نسخه جدید ",- "theme.switchDark": "تغییر به حالت تاریک",- "theme.switchLight": "تغییر به حالت روشن","tracing.aliyun.description": "پلتفرم مشاهدهپذیری کاملاً مدیریتشده و بدون نیاز به نگهداری که توسط Alibaba Cloud ارائه شده، امکان نظارت، ردیابی و ارزیابی برنامههای Dify را بهصورت آماده و با تنظیمات اولیه فراهم میکند.","tracing.aliyun.title": "نظارت بر ابر","tracing.arize.description": "قابلیت مشاهده LLM در سطح سازمانی، ارزیابی آنلاین و آفلاین، نظارت و آزمایش — با پشتیبانی از OpenTelemetry. طراحیشده مخصوص برنامههای مبتنی بر LLM و عاملها.",diff --git a/web/i18n/locales/fr-FR/app.json b/web/i18n/locales/fr-FR/app.jsonindex 3b5af969f3c..0248c93f7f3 100644--- a/web/i18n/locales/fr-FR/app.json+++ b/web/i18n/locales/fr-FR/app.json@@ -162,9 +162,7 @@"maxActiveRequests": "Nombre maximal de requêtes simultanées","maxActiveRequestsPlaceholder": "Entrez 0 pour illimité","maxActiveRequestsTip": "Nombre maximum de requêtes actives concurrentes par application (0 pour illimité)",- "mermaid.classic": "Classique",- "mermaid.handDrawn": "Dessiné à la main",- "mermaid.waitForCompletion": "En attente de la fin du code du diagramme...",+ "mermaid.preview": "Aperçu du diagramme","newApp.Cancel": "Annuler","newApp.Confirm": "Confirmer","newApp.Create": "Créer",@@ -246,8 +244,6 @@"switchTip": "retour","switchTipEnd": " à l'orchestration de base.","switchTipStart": "Une nouvelle copie de l'application sera créée pour vous, et la nouvelle copie passera à l'orchestration de flux de travail. La nouvelle copie ne permettra pas le ",- "theme.switchDark": "Passer au thème sombre",- "theme.switchLight": "Passer au thème clair","tracing.aliyun.description": "La plateforme d'observabilité entièrement gérée et sans maintenance fournie par Alibaba Cloud permet une surveillance, un traçage et une évaluation prêts à l'emploi des applications Dify.","tracing.aliyun.title": "Surveillance Cloud","tracing.arize.description": "Observabilité de LLM de niveau entreprise, évaluation en ligne et hors ligne, surveillance et expérimentation—alimentée par OpenTelemetry. Conçue spécialement pour les applications basées sur LLM et agents.",diff --git a/web/i18n/locales/hi-IN/app.json b/web/i18n/locales/hi-IN/app.jsonindex 2896365823a..779664fe865 100644--- a/web/i18n/locales/hi-IN/app.json+++ b/web/i18n/locales/hi-IN/app.json@@ -162,9 +162,7 @@"maxActiveRequests": "अधिकतम समवर्ती अनुरोध","maxActiveRequestsPlaceholder": "असीमित के लिए 0 दर्ज करें","maxActiveRequestsTip": "प्रति ऐप सक्रिय अनुरोधों की अधिकतम संख्या (असीमित के लिए 0)",- "mermaid.classic": "क्लासिक",- "mermaid.handDrawn": "हाथ खींचा",- "mermaid.waitForCompletion": "आरेख कोड के पूरा होने की प्रतीक्षा की जा रही है...",+ "mermaid.preview": "आरेख का पूर्वावलोकन","newApp.Cancel": "रद्द करें","newApp.Confirm": "सुदृढ़ करना","newApp.Create": "बनाएँ",@@ -246,8 +244,6 @@"switchTip": "की अनुमति नहीं देगा","switchTipEnd": " बेसिक ऑर्केस्ट्रेट में स्विच करना।","switchTipStart": "आपके लिए एक नई ऐप कॉपी बनाई जाएगी, और नई कॉपी वर्कफ़्लो ऑर्केस्ट्रेट में स्विच हो जाएगी। नई कॉपी ",- "theme.switchDark": "डार्क थीम में बदलें",- "theme.switchLight": "लाइट थीम में स्विच करें","tracing.aliyun.description": "अलीबाबा क्लाउड द्वारा प्रदान की गई पूरी तरह से प्रबंधित और रखरखाव-मुक्त अवलोकन प्लेटफ़ॉर्म, Dify अनुप्रयोगों की स्वचालित निगरानी, ट्रेसिंग और मूल्यांकन का सक्षम बनाता है।","tracing.aliyun.title": "क्लाउड मॉनिटर","tracing.arize.description": "एंटरप्राइज-स्तरीय LLM ऑब्ज़र्वेबिलिटी, ऑनलाइन और ऑफ़लाइन मूल्यांकन, मॉनिटरिंग और प्रयोग — OpenTelemetry द्वारा समर्थित। LLM और एजेंट-आधारित अनुप्रयोगों के लिए विशेष रूप से तैयार किया गया।",diff --git a/web/i18n/locales/id-ID/app.json b/web/i18n/locales/id-ID/app.jsonindex c9e091c8c58..64d144b50d0 100644--- a/web/i18n/locales/id-ID/app.json+++ b/web/i18n/locales/id-ID/app.json@@ -162,9 +162,7 @@"maxActiveRequests": "Permintaan bersamaan maksimum","maxActiveRequestsPlaceholder": "Masukkan 0 untuk tidak terbatas","maxActiveRequestsTip": "Jumlah maksimum permintaan aktif bersamaan per aplikasi (0 untuk tidak terbatas)",- "mermaid.classic": "Klasik",- "mermaid.handDrawn": "Digambar Tangan",- "mermaid.waitForCompletion": "Menunggu kode diagram selesai...",+ "mermaid.preview": "Pratinjau diagram","newApp.Cancel": "Batal","newApp.Confirm": "Konfirmasi","newApp.Create": "Buat",@@ -246,8 +244,6 @@"switchTip": "tidak mengizinkan","switchTipEnd": "beralih kembali ke Basic Orchestrate.","switchTipStart": "Salinan aplikasi baru akan dibuat untuk Anda, dan salinan baru akan beralih ke Workflow Orchestrate. Salinan baru akan",- "theme.switchDark": "Beralih ke tema gelap",- "theme.switchLight": "Beralih ke tema terang","tracing.aliyun.description": "Platform observabilitas yang dikelola sepenuhnya dan bebas perawatan yang disediakan oleh Alibaba Cloud, memungkinkan pemantauan, pelacakan, dan evaluasi aplikasi Dify yang out-of-the-box.","tracing.aliyun.title": "Monitor Awan","tracing.arize.description": "Observabilitas LLM tingkat perusahaan, evaluasi, pemantauan, dan eksperimen online & offline—didukung oleh OpenTelemetry. Dibuat khusus untuk LLM & aplikasi berbasis agen.",diff --git a/web/i18n/locales/it-IT/app.json b/web/i18n/locales/it-IT/app.jsonindex 7b38704ed9f..2cdc333e63e 100644--- a/web/i18n/locales/it-IT/app.json+++ b/web/i18n/locales/it-IT/app.json@@ -162,9 +162,7 @@"maxActiveRequests": "Massimo numero di richieste concorrenti","maxActiveRequestsPlaceholder": "Inserisci 0 per illimitato","maxActiveRequestsTip": "Numero massimo di richieste attive concorrenti per app (0 per illimitato)",- "mermaid.classic": "Classico",- "mermaid.handDrawn": "Disegnato a mano",- "mermaid.waitForCompletion": "In attesa del completamento del codice del diagramma...",+ "mermaid.preview": "Anteprima diagramma","newApp.Cancel": "Annulla","newApp.Confirm": "Confermare","newApp.Create": "Crea",@@ -246,8 +244,6 @@"switchTip": "non permetterà","switchTipEnd": " di tornare a Orchestrazione di base.","switchTipStart": "Verrà creata una nuova copia dell'app per te, e la nuova copia passerà a Orchestrazione del flusso di lavoro. La nuova copia ",- "theme.switchDark": "Passa al tema scuro",- "theme.switchLight": "Passa al tema chiaro","tracing.aliyun.description": "La piattaforma di osservabilità completamente gestita e senza manutenzione fornita da Alibaba Cloud consente il monitoraggio, il tracciamento e la valutazione delle applicazioni Dify fin da subito.","tracing.aliyun.title": "Monitoraggio Cloud","tracing.arize.description": "Osservabilità LLM di livello aziendale, valutazione online e offline, monitoraggio e sperimentazione—alimentata da OpenTelemetry. Progettata appositamente per applicazioni basate su LLM e agenti.",diff --git a/web/i18n/locales/ja-JP/app.json b/web/i18n/locales/ja-JP/app.jsonindex b701c7c5571..6c8d5491d19 100644--- a/web/i18n/locales/ja-JP/app.json+++ b/web/i18n/locales/ja-JP/app.json@@ -162,9 +162,7 @@"maxActiveRequests": "最大同時リクエスト数","maxActiveRequestsPlaceholder": "無制限のために0を入力してください","maxActiveRequestsTip": "アプリごとの同時アクティブリクエストの最大数(無制限の場合は0)",- "mermaid.classic": "クラシック",- "mermaid.handDrawn": "手描き",- "mermaid.waitForCompletion": "図表コードの生成完了を待っています...",+ "mermaid.preview": "図をプレビュー","newApp.Cancel": "キャンセル","newApp.Confirm": "確認する","newApp.Create": "作成する",@@ -246,8 +244,6 @@"switchTip": "切り替えを許可しません","switchTipEnd": " 基本的なオーケストレートに戻ることはできません。","switchTipStart": "新しいアプリのコピーが作成され、新しいコピーがワークフロー オーケストレートに切り替わります。新しいコピーは ",- "theme.switchDark": "ダークテーマに切り替え",- "theme.switchLight": "ライトテーマに切り替え","tracing.aliyun.description": "Alibaba Cloud が提供する完全管理型でメンテナンスフリーの可観測性プラットフォームは、Dify アプリケーションの即時監視、トレース、評価を可能にします。","tracing.aliyun.title": "クラウドモニター","tracing.arize.description": "エンタープライズグレードのLLM可観測性、オンラインおよびオフライン評価、モニタリング、実験—OpenTelemetryによって支えられています。LLMおよびエージェント駆動型アプリケーション向けに特別に設計されています。",diff --git a/web/i18n/locales/ko-KR/app.json b/web/i18n/locales/ko-KR/app.jsonindex f0b190f8fca..59ecb91bcef 100644--- a/web/i18n/locales/ko-KR/app.json+++ b/web/i18n/locales/ko-KR/app.json@@ -162,9 +162,7 @@"maxActiveRequests": "동시 최대 요청 수","maxActiveRequestsPlaceholder": "무제한 사용을 원하시면 0을 입력하세요.","maxActiveRequestsTip": "앱당 최대 동시 활성 요청 수(무제한은 0)",- "mermaid.classic": "클래식",- "mermaid.handDrawn": "손그림",- "mermaid.waitForCompletion": "다이어그램 코드가 완성되기를 기다리는 중...",+ "mermaid.preview": "다이어그램 미리보기","newApp.Cancel": "취소","newApp.Confirm": "확인","newApp.Create": "만들기",@@ -246,8 +244,6 @@"switchTip": "전환을 허용하지 않습니다","switchTipEnd": " 기본적인 오케스트레이션으로 되돌릴 수 없습니다.","switchTipStart": "새로운 앱의 복사본이 생성되어 새로운 복사본이 워크플로우 오케스트레이션으로 전환됩니다. 새로운 복사본은 ",- "theme.switchDark": "다크 모드로 전환",- "theme.switchLight": "라이트 테마로 전환","tracing.aliyun.description": "알리바바 클라우드에서 제공하는 완전 관리형 및 유지보수가 필요 없는 가시성 플랫폼은 Dify 애플리케이션의 모니터링, 추적 및 평가를 즉시 사용할 수 있도록 지원합니다.","tracing.aliyun.title": "클라우드 모니터","tracing.arize.description": "엔터프라이즈급 LLM 가시성, 온라인 및 오프라인 평가, 모니터링 및 실험—OpenTelemetry를 기반으로 합니다. LLM 및 에이전트 기반 애플리케이션을 위해 특별히 설계되었습니다.",diff --git a/web/i18n/locales/lo-LA/app.json b/web/i18n/locales/lo-LA/app.jsonindex 9c38d3f91f6..936cc9d959d 100644--- a/web/i18n/locales/lo-LA/app.json+++ b/web/i18n/locales/lo-LA/app.json@@ -162,9 +162,7 @@"maxActiveRequests": "ຈຳນວນການຮ້ອງຂໍພ້ອມກັນສູງສຸດ","maxActiveRequestsPlaceholder": "ປ້ອນ 0 ສຳລັບແບບບໍ່ຈຳກັດ","maxActiveRequestsTip": "ຈຳນວນສູງສຸດຂອງການຮ້ອງຂໍທີ່ເຮັດວຽກພ້ອມກັນຕໍ່ແອັບ (0 ແມ່ນບໍ່ຈຳກັດ)",- "mermaid.classic": "ແບບຄລາສສິກ",- "mermaid.handDrawn": "ແບບແຕ້ມດ້ວຍມື",- "mermaid.waitForCompletion": "ກຳລັງລໍຖ້າໃຫ້ລະຫັດໄດອະແກຣມສຳເລັດ...",+ "mermaid.preview": "ເບິ່ງແຜນວາດລ່ວງໜ້າ","newApp.Cancel": "ຍົກເລີກ","newApp.Confirm": "ຢືນຢັນ","newApp.Create": "ສ້າງ",@@ -246,8 +244,6 @@"switchTip": "ບໍ່ອະນຸຍາດ","switchTipEnd": " ກັບຄືນໄປຫາ Basic Orchestrate.","switchTipStart": "ແອັບສຳເນົາໃໝ່ຈະຖືກສ້າງຂຶ້ນສຳລັບທ່ານ, ແລະ ສຳເນົາໃໝ່ນັ້ນຈະປ່ຽນເປັນ Workflow Orchestrate. ແອັບສຳເນົາໃໝ່ຈະ ",- "theme.switchDark": "ປ່ຽນເປັນຮູບແບບມືດ",- "theme.switchLight": "ປ່ຽນເປັນຮູບແບບແຈ້ງ","tracing.aliyun.description": "ແພລັດຟອມການຕິດຕາມທີ່ຄຸ້ມຄອງແບບເບັດເສັດຈາກ Alibaba Cloud, ຊ່ວຍໃນການຕິດຕາມ ແລະ ປະເມີນຜົນແອັບ Dify ໄດ້ທັນທີ.","tracing.aliyun.title": "Cloud Monitor","tracing.arize.description": "ການຕິດຕາມ LLM ລະດັບອົງກອນ, ການປະເມີນແບບອອນລາຍ ແລະ ອອຟລາຍ—ຂັບເຄື່ອນໂດຍ OpenTelemetry. ອອກແບບມາເພື່ອແອັບ LLM ແລະ ເອເຈນໂດຍສະເພາະ.",diff --git a/web/i18n/locales/nl-NL/app.json b/web/i18n/locales/nl-NL/app.jsonindex 58b6dba1abd..afffd49743d 100644--- a/web/i18n/locales/nl-NL/app.json+++ b/web/i18n/locales/nl-NL/app.json@@ -162,9 +162,7 @@"maxActiveRequests": "Max concurrent requests","maxActiveRequestsPlaceholder": "Enter 0 for unlimited","maxActiveRequestsTip": "Maximum number of concurrent active requests per app (0 for unlimited)",- "mermaid.classic": "Classic",- "mermaid.handDrawn": "Hand Drawn",- "mermaid.waitForCompletion": "Wachten tot de diagramcode is voltooid...",+ "mermaid.preview": "Diagramvoorbeeld","newApp.Cancel": "Cancel","newApp.Confirm": "Confirm","newApp.Create": "Create",@@ -246,8 +244,6 @@"switchTip": "not allow","switchTipEnd": " switching back to Basic Orchestrate.","switchTipStart": "A new app copy will be created for you, and the new copy will switch to Workflow Orchestrate. The new copy will ",- "theme.switchDark": "Switch to dark theme",- "theme.switchLight": "Switch to light theme","tracing.aliyun.description": "The fully-managed and maintenance-free observability platform provided by Alibaba Cloud, enables out-of-the-box monitoring, tracing, and evaluation of Dify applications.","tracing.aliyun.title": "Cloud Monitor","tracing.arize.description": "Enterprise-grade LLM observability, online & offline evaluation, monitoring, and experimentation—powered by OpenTelemetry. Purpose-built for LLM & agent-driven applications.",diff --git a/web/i18n/locales/pl-PL/app.json b/web/i18n/locales/pl-PL/app.jsonindex d4b13ba04a5..88784e95844 100644--- a/web/i18n/locales/pl-PL/app.json+++ b/web/i18n/locales/pl-PL/app.json@@ -162,9 +162,7 @@"maxActiveRequests": "Maksymalne równoczesne żądania","maxActiveRequestsPlaceholder": "Wprowadź 0, aby uzyskać nielimitowane","maxActiveRequestsTip": "Maksymalna liczba jednoczesnych aktywnych żądań na aplikację (0 dla nieograniczonej)",- "mermaid.classic": "Klasyczny",- "mermaid.handDrawn": "Ręcznie rysowane",- "mermaid.waitForCompletion": "Oczekiwanie na ukończenie kodu diagramu...",+ "mermaid.preview": "Podgląd diagramu","newApp.Cancel": "Anuluj","newApp.Confirm": "Potwierdzić","newApp.Create": "Utwórz",@@ -246,8 +244,6 @@"switchTip": "nie pozwoli","switchTipEnd": " na powrót do Podstawowej Orkiestracji.","switchTipStart": "Dla ciebie zostanie utworzona nowa kopia aplikacji, a nowa kopia przełączy się na Orkiestrację Przepływu Pracy. Nowa kopia będzie ",- "theme.switchDark": "Przełącz na ciemny motyw",- "theme.switchLight": "Przełącz na jasny motyw","tracing.aliyun.description": "W pełni zarządzana i wolna od konserwacji platforma obserwowalności oferowana przez Alibaba Cloud umożliwia gotowe monitorowanie, śledzenie i oceny aplikacji Dify.","tracing.aliyun.title": "Monitor Chmury","tracing.arize.description": "Obserwowalność LLM klasy korporacyjnej, ocena online i offline, monitorowanie i eksperymentowanie — oparta na OpenTelemetry. Zaprojektowana specjalnie dla aplikacji opartych na LLM i agentach.",diff --git a/web/i18n/locales/pt-BR/app.json b/web/i18n/locales/pt-BR/app.jsonindex 1c929b5f139..705329bb04c 100644--- a/web/i18n/locales/pt-BR/app.json+++ b/web/i18n/locales/pt-BR/app.json@@ -162,9 +162,7 @@"maxActiveRequests": "Máximo de solicitações simultâneas","maxActiveRequestsPlaceholder": "Digite 0 para ilimitado","maxActiveRequestsTip": "Número máximo de solicitações ativas simultâneas por aplicativo (0 para ilimitado)",- "mermaid.classic": "Clássico",- "mermaid.handDrawn": "Mão desenhada",- "mermaid.waitForCompletion": "Aguardando a conclusão do código do diagrama...",+ "mermaid.preview": "Pré-visualizar diagrama","newApp.Cancel": "Cancelar","newApp.Confirm": "Confirmar","newApp.Create": "Criar",@@ -246,8 +244,6 @@"switchTip": "volta","switchTipEnd": " para Orquestração Básica.","switchTipStart": "Será criada uma nova cópia do aplicativo para você e a nova cópia mudará para Orquestração de Fluxo de Trabalho. A nova cópia não permitirá a ",- "theme.switchDark": "Mudar para o tema escuro",- "theme.switchLight": "Mudar para o tema claro","tracing.aliyun.description": "A plataforma de observabilidade totalmente gerenciada e sem manutenção fornecida pela Alibaba Cloud, permite monitoramento, rastreamento e avaliação prontos para uso de aplicações Dify.","tracing.aliyun.title": "Monitoramento em Nuvem","tracing.arize.description": "Observabilidade de LLM de nível empresarial, avaliação online e offline, monitoramento e experimentação—impulsionada pelo OpenTelemetry. Projetado especificamente para aplicações baseadas em LLM e agentes.",diff --git a/web/i18n/locales/ro-RO/app.json b/web/i18n/locales/ro-RO/app.jsonindex 2ec218b17bf..6c20f9e6902 100644--- a/web/i18n/locales/ro-RO/app.json+++ b/web/i18n/locales/ro-RO/app.json@@ -162,9 +162,7 @@"maxActiveRequests": "Maxime cereri simultane","maxActiveRequestsPlaceholder": "Introduceți 0 pentru nelimitat","maxActiveRequestsTip": "Numărul maxim de cereri active concurente pe aplicație (0 pentru nelimitat)",- "mermaid.classic": "Clasic",- "mermaid.handDrawn": "Desenat de mână",- "mermaid.waitForCompletion": "Se așteaptă finalizarea codului diagramei...",+ "mermaid.preview": "Previzualizare diagramă","newApp.Cancel": "Anulează","newApp.Confirm": "Confirma","newApp.Create": "Creează",@@ -246,8 +244,6 @@"switchTip": "nu va permite","switchTipEnd": " comutarea înapoi la Orchestrare de Bază.","switchTipStart": "O nouă copie a aplicației va fi creată pentru tine, iar noua copie va comuta la Orchestrare Flux de Lucru. Noua copie ",- "theme.switchDark": "Comută la tema închisă",- "theme.switchLight": "Comută la tema deschisă","tracing.aliyun.description": "Platforma de observabilitate SaaS oferită de Alibaba Cloud permite monitorizarea, urmărirea și evaluarea aplicațiilor Dify din cutie.","tracing.aliyun.title": "Monitorizarea Cloud","tracing.arize.description": "Observabilitate LLM de nivel enterprise, evaluare online și offline, monitorizare și experimentare—alimentată de OpenTelemetry. Proiectată special pentru aplicații bazate pe LLM și agenți.",diff --git a/web/i18n/locales/ru-RU/app.json b/web/i18n/locales/ru-RU/app.jsonindex 515f8930636..fe4f87cb39c 100644--- a/web/i18n/locales/ru-RU/app.json+++ b/web/i18n/locales/ru-RU/app.json@@ -162,9 +162,7 @@"maxActiveRequests": "Максимальное количество параллельных запросов","maxActiveRequestsPlaceholder": "Введите 0 для неограниченного количества","maxActiveRequestsTip": "Максимальное количество одновременно активных запросов на одно приложение (0 для неограниченного количества)",- "mermaid.classic": "Классический",- "mermaid.handDrawn": "Рисованный",- "mermaid.waitForCompletion": "Ожидание завершения кода диаграммы...",+ "mermaid.preview": "Предпросмотр диаграммы","newApp.Cancel": "Отмена","newApp.Confirm": "Подтверждать","newApp.Create": "Создать",@@ -246,8 +244,6 @@"switchTip": "не позволит","switchTipEnd": " переключиться обратно на базовую организацию.","switchTipStart": "Для вас будет создана новая копия Workflow. Новая копия ",- "theme.switchDark": "Переключиться на тёмную тему",- "theme.switchLight": "Переключиться на светлую тему","tracing.aliyun.description": "Полностью управляемая и не требующая обслуживания платформа наблюдения, предоставляемая Alibaba Cloud, обеспечивает мониторинг, трассировку и оценку приложений Dify из коробки.","tracing.aliyun.title": "Облачный монитор","tracing.arize.description": "Корпоративный уровень наблюдаемости LLM, онлайн и оффлайн оценка, мониторинг и эксперименты—на основе OpenTelemetry. Специально разработан для приложений на базе LLM и агентов.",diff --git a/web/i18n/locales/sl-SI/app.json b/web/i18n/locales/sl-SI/app.jsonindex b8400d51c2a..d53cf110063 100644--- a/web/i18n/locales/sl-SI/app.json+++ b/web/i18n/locales/sl-SI/app.json@@ -162,9 +162,7 @@"maxActiveRequests": "Maksimalno število hkratnih zahtevkov","maxActiveRequestsPlaceholder": "Vnesite 0 za neomejeno","maxActiveRequestsTip": "Največje število hkrati aktivnih zahtevkov na aplikacijo (0 za neomejeno)",- "mermaid.classic": "Klasičen",- "mermaid.handDrawn": "Ročno narisano",- "mermaid.waitForCompletion": "Čakanje na dokončanje kode diagrama...",+ "mermaid.preview": "Predogled diagrama","newApp.Cancel": "Prekliči","newApp.Confirm": "Potrditi","newApp.Create": "Ustvari",@@ -246,8 +244,6 @@"switchTip": "dovolila","switchTipEnd": " preklopa nazaj na Basic Orchestrate.","switchTipStart": "Za vas bo ustvarjena nova kopija aplikacije, ki bo preklopila na Workflow Orchestrate. Nova kopija ne bo ",- "theme.switchDark": "Preklopi na temno temo",- "theme.switchLight": "Preklopi na svetlo temo","tracing.aliyun.description": "Popolnoma upravljana in brez vzdrževanja platforma za opazovanje, ki jo zagotavlja Alibaba Cloud, omogoča takojšnje spremljanje, sledenje in ocenjevanje aplikacij Dify.","tracing.aliyun.title": "Oblačni nadzor","tracing.arize.description": "Podjetniško opazovanje LLM, spletno in nespletno vrednotenje, nadzorovanje in eksperimentiranje — s podporo OpenTelemetry. Namenjeno aplikacijam, ki temeljijo na LLM in agentih.",diff --git a/web/i18n/locales/th-TH/app.json b/web/i18n/locales/th-TH/app.jsonindex f3e8652ecf0..8008813dd34 100644--- a/web/i18n/locales/th-TH/app.json+++ b/web/i18n/locales/th-TH/app.json@@ -162,9 +162,7 @@"maxActiveRequests": "จำนวนคำขอพร้อมกันสูงสุด","maxActiveRequestsPlaceholder": "ใส่ 0 สำหรับไม่จำกัด","maxActiveRequestsTip": "จำนวนการร้องขอที่ใช้งานพร้อมกันสูงสุดต่อแอป (0 หมายถึงไม่จำกัด)",- "mermaid.classic": "คลาสสิก",- "mermaid.handDrawn": "วาดด้วยมือ",- "mermaid.waitForCompletion": "กำลังรอให้โค้ดไดอะแกรมเสร็จสมบูรณ์...",+ "mermaid.preview": "ดูตัวอย่างแผนภาพ","newApp.Cancel": "ยกเลิก","newApp.Confirm": "ยืนยัน","newApp.Create": "สร้าง",@@ -246,8 +244,6 @@"switchTip": "ไม่อนุญาต","switchTipEnd": "เปลี่ยนกลับเป็น Basic Orchestrate","switchTipStart": "สําเนาโปรเจกต์ใหม่จะถูกสร้างขึ้นสําหรับคุณ และสําเนาใหม่จะเปลี่ยนเป็น Workflow Orchestration",- "theme.switchDark": "เปลี่ยนเป็นธีมมืด",- "theme.switchLight": "เปลี่ยนเป็นธีมสว่าง","tracing.aliyun.description": "แพลตฟอร์มการสังเกตการณ์ที่จัดการโดย Alibaba Cloud ซึ่งไม่ต้องดูแลและบำรุงรักษา ช่วยให้สามารถติดตาม ตรวจสอบ และประเมินแอปพลิเคชัน Dify ได้ทันที","tracing.aliyun.title": "การตรวจสอบคลาวด์","tracing.arize.description": "การสังเกตการณ์ LLM ระดับองค์กร การประเมินออนไลน์และออฟไลน์ การตรวจสอบ และการทดลอง—ขับเคลื่อนโดย OpenTelemetry ออกแบบมาโดยเฉพาะสำหรับแอปพลิเคชันที่ขับเคลื่อนด้วย LLM และตัวแทน",diff --git a/web/i18n/locales/tr-TR/app.json b/web/i18n/locales/tr-TR/app.jsonindex 99c82efc8a5..da86d513f38 100644--- a/web/i18n/locales/tr-TR/app.json+++ b/web/i18n/locales/tr-TR/app.json@@ -162,9 +162,7 @@"maxActiveRequests": "Maksimum eş zamanlı istekler","maxActiveRequestsPlaceholder": "Sınırsız için 0 girin","maxActiveRequestsTip": "Her uygulama için maksimum eşzamanlı aktif istek sayısı (sınırsız için 0)",- "mermaid.classic": "Klasik",- "mermaid.handDrawn": "Elle çizilmiş",- "mermaid.waitForCompletion": "Diyagram kodunun tamamlanması bekleniyor...",+ "mermaid.preview": "Diyagramı önizle","newApp.Cancel": "İptal","newApp.Confirm": "Onayla","newApp.Create": "Oluştur",@@ -246,8 +244,6 @@"switchTip": "izin vermeyecek","switchTipEnd": " Temel Orkestrasyona geri dönmek.","switchTipStart": "Sizin için yeni bir uygulama kopyası oluşturulacak ve yeni kopya İş Akışı Orkestrasyonuna geçecektir. Yeni kopya ",- "theme.switchDark": "Koyu tema geçiş yap",- "theme.switchLight": "Aydınlık tema'ya geç","tracing.aliyun.description": "Alibaba Cloud tarafından sağlanan tamamen yönetilen ve bakım gerektirmeyen gözlemleme platformu, Dify uygulamalarının kutudan çıkar çıkmaz izlenmesi, takip edilmesi ve değerlendirilmesine olanak tanır.","tracing.aliyun.title": "Bulut İzleyici","tracing.arize.description": "Kurumsal düzeyde LLM gözlemlenebilirliği, çevrimiçi ve çevrimdışı değerlendirme, izleme ve deneyler — OpenTelemetry ile desteklenmektedir. LLM ve ajan tabanlı uygulamalar için özel olarak tasarlanmıştır.",diff --git a/web/i18n/locales/uk-UA/app.json b/web/i18n/locales/uk-UA/app.jsonindex 6e843a1e9a8..4a6570862b5 100644--- a/web/i18n/locales/uk-UA/app.json+++ b/web/i18n/locales/uk-UA/app.json@@ -162,9 +162,7 @@"maxActiveRequests": "Максимальна кількість одночасних запитів","maxActiveRequestsPlaceholder": "Введіть 0 для необмеженого","maxActiveRequestsTip": "Максимальна кількість одночасних активних запитів на додаток (0 для необмеженої кількості)",- "mermaid.classic": "Класичний",- "mermaid.handDrawn": "Намальовані від руки",- "mermaid.waitForCompletion": "Очікування завершення коду діаграми...",+ "mermaid.preview": "Попередній перегляд діаграми","newApp.Cancel": "Скасувати","newApp.Confirm": "Підтвердити","newApp.Create": "Створити",@@ -246,8 +244,6 @@"switchTip": "повернутися","switchTipEnd": " до базової оркестрації.","switchTipStart": "Для вас буде створена нова копія додатка, і нова копія перейде до оркестрації робочого процесу. Нова копія не дозволить ",- "theme.switchDark": "Переключитися на темну тему",- "theme.switchLight": "Переключитися на світлу тему","tracing.aliyun.description": "Повністю керовані та без обслуговування платформи спостереження, надані Alibaba Cloud, дозволяють миттєвий моніторинг, трасування та оцінку застосувань Dify.","tracing.aliyun.title": "Моніторинг Хмари","tracing.arize.description": "Спостережуваність LLM корпоративного рівня, онлайн та офлайн оцінювання, моніторинг та експерименти—на основі OpenTelemetry. Спеціально розроблено для застосунків на базі LLM та агентів.",diff --git a/web/i18n/locales/vi-VN/app.json b/web/i18n/locales/vi-VN/app.jsonindex e34ce52297c..c4e64b0bcc1 100644--- a/web/i18n/locales/vi-VN/app.json+++ b/web/i18n/locales/vi-VN/app.json@@ -162,9 +162,7 @@"maxActiveRequests": "Số yêu cầu đồng thời tối đa","maxActiveRequestsPlaceholder": "Nhập 0 để không giới hạn","maxActiveRequestsTip": "Số yêu cầu hoạt động đồng thời tối đa cho mỗi ứng dụng (0 để không giới hạn)",- "mermaid.classic": "Cổ điển",- "mermaid.handDrawn": "Vẽ tay",- "mermaid.waitForCompletion": "Đang chờ mã sơ đồ hoàn tất...",+ "mermaid.preview": "Xem trước sơ đồ","newApp.Cancel": "Hủy","newApp.Confirm": "Xác nhận","newApp.Create": "Tạo",@@ -246,8 +244,6 @@"switchTip": "không thể","switchTipEnd": " chuyển lại quản lý cơ bản.","switchTipStart": "Một bản sao ứng dụng mới sẽ được tạo và chuyển sang quản lý quy trình. Bản sao mới sẽ ",- "theme.switchDark": "Chuyển sang chế độ tối",- "theme.switchLight": "Chuyển sang giao diện sáng","tracing.aliyun.description": "Nền tảng quan sát được quản lý hoàn toàn và không cần bảo trì do Alibaba Cloud cung cấp, cho phép giám sát, theo dõi và đánh giá các ứng dụng Dify ngay lập tức.","tracing.aliyun.title": "Giám sát Đám mây","tracing.arize.description": "Khả năng quan sát LLM cấp doanh nghiệp, đánh giá trực tuyến và ngoại tuyến, giám sát và thử nghiệm—được hỗ trợ bởi OpenTelemetry. Được thiết kế đặc biệt cho các ứng dụng dựa trên LLM và tác nhân.",diff --git a/web/i18n/locales/zh-Hans/app.json b/web/i18n/locales/zh-Hans/app.jsonindex 4933b1f226a..4d858f3ef9f 100644--- a/web/i18n/locales/zh-Hans/app.json+++ b/web/i18n/locales/zh-Hans/app.json@@ -162,9 +162,7 @@"maxActiveRequests": "最大活跃请求数","maxActiveRequestsPlaceholder": "0 表示不限制","maxActiveRequestsTip": "当前应用的最大活跃请求数(0 表示不限制)",- "mermaid.classic": "经典",- "mermaid.handDrawn": "手绘",- "mermaid.waitForCompletion": "正在等待图表代码生成完成...",+ "mermaid.preview": "预览图表","newApp.Cancel": "取消","newApp.Confirm": "确认","newApp.Create": "创建",@@ -246,8 +244,6 @@"switchTip": "不能够","switchTipEnd": "迁移回基础编排","switchTipStart": "将为您创建一个使用工作流编排的新应用。新应用将",- "theme.switchDark": "切换至深色主题",- "theme.switchLight": "切换至浅色主题","tracing.aliyun.description": "阿里云提供的全托管免运维可观测平台,一键开启Dify应用的监控追踪和评估","tracing.aliyun.title": "云监控","tracing.arize.description": "企业级LLM可观测性、在线和离线评估、监控和实验平台,基于OpenTelemetry构建,专为LLM和代理驱动的应用程序设计。",diff --git a/web/i18n/locales/zh-Hant/app.json b/web/i18n/locales/zh-Hant/app.jsonindex c467b4c04da..aa01e4532f5 100644--- a/web/i18n/locales/zh-Hant/app.json+++ b/web/i18n/locales/zh-Hant/app.json@@ -162,9 +162,7 @@"maxActiveRequests": "同時最大請求數","maxActiveRequestsPlaceholder": "輸入 0 以表示無限","maxActiveRequestsTip": "每個應用程式可同時活躍請求的最大數量(0為無限制)",- "mermaid.classic": "經典",- "mermaid.handDrawn": "手繪",- "mermaid.waitForCompletion": "正在等待圖表程式碼生成完成...",+ "mermaid.preview": "預覽圖表","newApp.Cancel": "取消","newApp.Confirm": "確認","newApp.Create": "建立",@@ -246,8 +244,6 @@"switchTip": "不能夠","switchTipEnd": "遷移回基礎編排","switchTipStart": "將為您建立一個使用工作流編排的新應用。新應用將",- "theme.switchDark": "切換到深色主題",- "theme.switchLight": "切換到亮色主題","tracing.aliyun.description": "阿里雲提供的完全管理且無需維護的可觀察性平台,支持即時監控、追蹤和評估 Dify 應用程序。","tracing.aliyun.title": "雲端監控","tracing.arize.description": "企業級LLM可觀測性、線上與離線評估、監控和實驗平台,基於OpenTelemetry構建,專為LLM和代理驅動的應用程式設計。",diff --git a/web/i18n/resources.generated.d.ts b/web/i18n/resources.generated.d.tsindex bf7063d4c34..dffc27a9dd4 100644--- a/web/i18n/resources.generated.d.ts+++ b/web/i18n/resources.generated.d.ts@@ -691,9 +691,7 @@ export default interface Resources {maxActiveRequests: 'Max concurrent requests'maxActiveRequestsPlaceholder: 'Enter 0 for unlimited'maxActiveRequestsTip: 'Maximum number of concurrent active requests per app (0 for unlimited)'- 'mermaid.classic': 'Classic'- 'mermaid.handDrawn': 'Hand Drawn'- 'mermaid.waitForCompletion': 'Waiting for diagram code to complete...'+ 'mermaid.preview': 'Preview diagram''newApp.Cancel': 'Cancel''newApp.Confirm': 'Confirm''newApp.Create': 'Create'@@ -775,8 +773,6 @@ export default interface Resources {switchTip: 'not allow'switchTipEnd: ' switching back to Basic Orchestrate.'switchTipStart: 'A new app copy will be created for you, and the new copy will switch to Workflow Orchestrate. The new copy will '- 'theme.switchDark': 'Switch to dark theme'- 'theme.switchLight': 'Switch to light theme''tracing.aliyun.description': 'The fully-managed and maintenance-free observability platform provided by Alibaba Cloud, enables out-of-the-box monitoring, tracing, and evaluation of Dify applications.''tracing.aliyun.title': 'Cloud Monitor''tracing.arize.description': 'Enterprise-grade LLM observability, online & offline evaluation, monitoring, and experimentation—powered by OpenTelemetry. Purpose-built for LLM & agent-driven applications.'diff --git a/web/package.json b/web/package.jsonindex a1cfe85942b..e265710b38d 100644--- a/web/package.json+++ b/web/package.json@@ -106,7 +106,6 @@"lexical": "catalog:","loro-crdt": "catalog:","mediabunny": "catalog:",- "mermaid": "catalog:","mime": "catalog:","mitt": "catalog:","motion": "catalog:",@@ -114,6 +113,7 @@"next": "catalog:","next-themes": "catalog:","nuqs": "catalog:",+ "pele": "catalog:","qrcode.react": "catalog:","react": "catalog:","react-dom": "catalog:",