Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat(sql-editor): AI Assistant (#14016)
Liu Jiff473e3684f2
diff --git a/frontend/package.json b/frontend/package.jsonindex bbc8754a78..215d2990e6 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -104,6 +104,7 @@"@types/jsdom": "21.1.7","@types/lodash-es": "4.17.12","@types/markdown-it": "^14.1.1",+ "@types/mdast": "^4.0.4","@types/node": "20.16.10","@types/normalize-wheel": "^1.0.4","@types/pouchdb": "^6.4.2",@@ -134,14 +135,19 @@"jquery": "3.7.1","jsdom": "25.0.1","long": "^5.2.3",+ "micromark": "^4.0.0",+ "micromark-util-sanitize-uri": "^2.0.0","postcss": "8.4.47","prettier": "3.3.3","protobufjs": "^7.2.5",+ "remark-gfm": "^4.0.0",+ "remark-parse": "^11.0.0","rollup": "4.24.0","tailwindcss": "3.4.13","ts-node": "^10.9.2","ts-proto": "^2.0.3","typescript": "5.5.4",+ "unified": "^11.0.5","unplugin-icons": "0.19.3","unplugin-vue-components": "0.27.4","vite": "5.4.8",diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yamlindex 2aac37a371..a302b99876 100644--- a/frontend/pnpm-lock.yaml+++ b/frontend/pnpm-lock.yaml@@ -255,6 +255,9 @@ importers:'@types/markdown-it':specifier: ^14.1.1version: 14.1.2+ '@types/mdast':+ specifier: ^4.0.4+ version: 4.0.4'@types/node':specifier: 20.16.10version: 20.16.10@@ -345,6 +348,12 @@ importers:long:specifier: ^5.2.3version: 5.2.3+ micromark:+ specifier: ^4.0.0+ version: 4.0.0+ micromark-util-sanitize-uri:+ specifier: ^2.0.0+ version: 2.0.0postcss:specifier: 8.4.47version: 8.4.47@@ -354,6 +363,12 @@ importers:protobufjs:specifier: ^7.2.5version: 7.4.0+ remark-gfm:+ specifier: ^4.0.0+ version: 4.0.0+ remark-parse:+ specifier: ^11.0.0+ version: 11.0.0rollup:specifier: 4.24.0version: 4.24.0@@ -369,6 +384,9 @@ importers:typescript:specifier: 5.5.4version: 5.5.4+ unified:+ specifier: ^11.0.5+ version: 11.0.5unplugin-icons:specifier: 0.19.3@@ -1251,6 +1269,9 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-promo4eFwuiW+TfGxhi+0x3czqTYJkG8qB17ZUJiVF10Xm7NLVRSLUsfRTU/6h1e24VvRnXCx+hG7li58lkzog==}+ '@types/[email protected]':+ resolution: {integrity: sha512-kGaNbPh1k7AFzgpud/gMdvIm5xuECykRR+JnWKQno9TAXVa6WIVCGTPvYGekIDL4uwCZQSYbUxNBSb1aUo79oA==}+'@types/[email protected]':resolution: {integrity: sha512-RGdgjQUZba5p6QEFAVx2OGb8rQDL/cPRG7GiedRzMcJ1tYnUANBncjbSB1NRGwbvjcPeikRABz2nshyPk1bhWg==}@@ -1341,6 +1362,9 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==}+ '@types/[email protected]':+ resolution: {integrity: sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==}+'@types/[email protected]':resolution: {integrity: sha512-7gqG38EyHgyP1S+7+xomFtL+ZNHcKv6DwNaCZmJmo1vgMugyF3TCnXVg4t1uk89mLNwnLtnY3TpOpCOyp1/xHQ==}@@ -1697,6 +1721,9 @@ packages:resolution: {integrity: sha512-S4kL7XrjgBmvdGut0sN3yJxqYzrDOnivkBiN0OFs6hLiUam3UPvswUo0kqGyhqUZGEOytHyumEdXsAkgCOUf3Q==}+ resolution: {integrity: sha512-0xO6mYd7JB2YesxDKplafRpsiOzPt9V02ddPCLbY1xYGPOX24NTyN50qnUxgCPcSoYMhKpAuBTjQoRZCAkUDRw==}+resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==}@@ -1778,6 +1805,9 @@ packages:resolution: {integrity: sha512-K7Qy8O9p76sL3/3m7/zLKbRkyOlSZAgzEaLhyj2mXS8PsCud2Eo4hAb8aLtZqHh0QGqLcb9dlJSu6lHRVENm1w==}engines: {node: '>=6'}+ resolution: {integrity: sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg==}+resolution: {integrity: sha512-pT1ZgP8rPNqUgieVaEY+ryQr6Q4HXNg8Ei9UnLUrjN4IA7dvQC5JB+/kxVcPNDHyBcc/26CXPkbNzq3qwrOEKA==}engines: {node: '>=12'}@@ -1794,6 +1824,9 @@ packages:resolution: {integrity: sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==}engines: {node: '>=10'}+ resolution: {integrity: sha512-shx7oQ0Awen/BRIdkjkvz54PnEEI/EjwXDSIZp86/KKdbafHh1Df/RYGBhn4hbe2+uKC9FnT5UCEdyPz3ai9hQ==}+resolution: {integrity: sha512-OAlb+T7V4Op9OwdkjmguYRqncdlx5JiofwOAUkmTF+jNdHwzTaTs4sRAGpzLF3oOz5xAyDGrPgeIDFQmDOTiJw==}engines: {node: '>= 16'}@@ -2095,6 +2128,9 @@ packages:resolution: {integrity: sha512-VBBaLc1MgL5XpzgIP7ny5Z6Nx3UrRkIViUkPUdtl9aya5amy3De1gsUUSB1g3+3sExYNjCAsAznmukyxCb1GRA==}+ resolution: {integrity: sha512-O8x12RzrUF8xyVcY0KJowWsmaJxQbmy0/EtnNtHRpsOcT7dFk5W598coHqBVpmWo1oQQfsCqfCmkZN5DJrZVdg==}+resolution: {integrity: sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==}engines: {node: '>=6'}@@ -2124,11 +2160,18 @@ packages:resolution: {integrity: sha512-IofjkYBZaZivn0V8nnsMJGBr4jVLxHDheKSW88PyxS5QC4Vo9ZbZVvhzlSxY87fVq3STR6r+4cGepyHkcWOQSw==}+ resolution: {integrity: sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==}+ engines: {node: '>=6'}+resolution: {integrity: sha512-pGjwhsmsp4kL2RTz08wcOlGN83otlqHeD/Z5T8GXZB+/YcpQ/dgo+lbU8ZsGxV0HIvqqxo9l7mqYwyYMD9bKDg==}engines: {node: '>=0.10'}hasBin: true+ resolution: {integrity: sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA==}+resolution: {integrity: sha512-gxtyfqMg7GKyhQmb056K7M3xszy/myH8w+B4RT+QXBQsvAOdc3XymqDDPHx1BgPgsdAA5SIifona89YtRATDzw==}@@ -2243,6 +2286,10 @@ packages:resolution: {integrity: sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==}engines: {node: '>=10'}+ resolution: {integrity: sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw==}+ engines: {node: '>=12'}+resolution: {integrity: sha512-2NlIDTwUWJN0mRPQOdtQBzbUHvdGY2P1VXSyU83Q3xKxM7WHX2Ql8dKq782Q9TgQUNOLEzEYu9bzLNj1q88I5w==}engines: {node: '>=6.0'}@@ -2345,6 +2392,9 @@ packages:resolution: {integrity: sha512-qaeGN5bx63s/AXgQo8gj6fBkxge+OoLddLniox5qtLAEY5HSnuSlISXVPxnSae1dWblvTh4/HoMIB+mbMsvZzw==}+ resolution: {integrity: sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==}+resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==}@@ -2623,6 +2673,10 @@ packages:resolution: {integrity: sha512-Fd4gABb+ycGAmKou8eMftCupSir5lRxqf4aD/vd0cD2qc4HL07OjCeuHMr8Ro4CoMaeCKDB0/ECBOVWjTwUvPQ==}engines: {node: '>=8'}+ resolution: {integrity: sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg==}+ engines: {node: '>=12'}+resolution: {integrity: sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==}@@ -2828,6 +2882,9 @@ packages:resolution: {integrity: sha512-lcHwpNoggQTObv5apGNCTdJrO69eHOZMi4BNC+rTLER8iHAqGrUVeLh/irVIM7zTw2bOXA8T6uNPeujwOLg/2Q==}+ resolution: {integrity: sha512-9Ri+o0JYgehTaVBBDoMqIl8GXtbWg711O3srftcHhZ0dqnETqLaoIK0x17fUw9rFSlK/0NlsKe0Ahhyl5pXE2g==}+resolution: {integrity: sha512-edNu/8D5MKVfGVFRhFf8aAxiTM6Wumfz5XsaatSxlD3w4R1d/WEKUTydCdPGbl9K7QG/Ca3GnDV2sIKIpXRQcw==}@@ -2862,9 +2919,45 @@ packages:resolution: {integrity: sha512-a54IwgWPaeBCAAsv13YgmALOF1elABB08FxO9i+r4VFk5Vl4pKokRPeX8u5TCgSsPi6ec1otfLjdOpVcgbpshg==}hasBin: true+ resolution: {integrity: sha512-Z1NL3Tb1M9wH4XESsCDEksWoKTdlUafKc4pt0GRwjUyXaCFZ+dc3g2erqB6zm3szA2IUSi7VnPI+o/9jnxh9hw==}+resolution: {integrity: sha512-jfZW7cWS5y/1xswZo8VBOdudUiSd9nifYRWphc9M5D/ee4w4AoXLgBEdRbgVaxbMuagBPeUC5y2Hi8DO6o9aDg==}+ resolution: {integrity: sha512-SG21kZHGC3XRTSUhtofZkBzZTJNM5ecCi0SK2IMKmSXR8vO3peL+kb1O0z7Zl83jKtutG4k5Wv/W7V3/YHvzPA==}++ resolution: {integrity: sha512-aJEUyzZ6TzlsX2s5B4Of7lN7EQtAxvtradMMglCQDyaTFgse6CmtmdJ15ElnVRlCg1vpNyVtbem0PWzlNieZsA==}++ resolution: {integrity: sha512-5HVP2MKaP6L+G6YaxPNjuL0BPrq9orG3TsrZ9YXbA3vDw/ACI4MEsnoDpn6ZNm7GnZgtAcONJyPhOP8tNJQavQ==}++ resolution: {integrity: sha512-5jOT2boTSVkMnQ7LTrd6n/18kqwjmuYqo7JUPe+tRCY6O7dAuTFMtTPauYYrMPpox9hlN0uOx/FL8XvEfG9/mQ==}++ resolution: {integrity: sha512-mKKb915TF+OC5ptj5bJ7WFRPdYtuHv0yTRxK2tJvi+BDqbkiG7h7u/9SI89nRAYcmap2xHQL9D+QG/6wSrTtXg==}++ resolution: {integrity: sha512-78UEvebzz/rJIxLvE7ZtDd/vIQ0RHv+3Mh5DR96p7cS7HsBhYIICDBCu8csTNWNO6tBWfqXPWekRuj2FNOGOZg==}++ resolution: {integrity: sha512-IrtvNvjxC1o06taBAVJznEnkiHxLFTzgonUdy8hzFVeDun0uTjxxrRGVaNFqkU1wJR3RBPEfsxmU6jDWPofrTQ==}++ resolution: {integrity: sha512-dgQEX5Amaq+DuUqf26jJqSK9qgixgd6rYDHAv4aTBuA92cTknZlKpPfa86Z/s8Dj8xsAQpFfBmPUHWJBWqS4Bw==}++ resolution: {integrity: sha512-TqICwyvJJpBwvGAMZjj4J2n0X8QWp21b9l0o7eXyVJ25YNWYbJDVIyD1bZXE6WtV6RmKJVYmQAKWa0zWOABz2w==}++ resolution: {integrity: sha512-SR2VnIEdVNCJbP6y7kVTJgPLifdr8WEU440fQec7qHoHOUz/oJ2jmNRqdDQ3rbiStOXb2mCDGTuwsK5OPUgYlQ==}++ resolution: {integrity: sha512-0H44vDimn51F0YwvxSJSm0eCDOJTRlmN0R1yBh4HLj9wiV1Dn0QoXGbvFAWj2hSItVTlCmBF1hqKlIyUBVFLPg==}+resolution: {integrity: sha512-Lf+9+2r+Tdp5wXDXC4PcIBjTDtq4UKjCPMQhKIuzpJNW0b96kVqSwW0bT7FhRSfmAiFYgP+SCRvdrDozfh0U5w==}@@ -2872,8 +2965,92 @@ packages:resolution: {integrity: sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==}engines: {node: '>= 8'}- resolution: {integrity: sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==}+ resolution: {integrity: sha512-CUQyKr1e///ZODyD1U3xit6zXwy1a8q2a1S1HKtIlmgvurrEpaw/Y9y6KSIbF8P59cn/NjzHyO+Q2fAyYLQrAA==}++ resolution: {integrity: sha512-oOg7knzhicgQ3t4QCjCWgTmfNhvQbDDnJeVu9v81r7NltNCVmhPy1fJRX27pISafdjL+SVc4d3l48Gb6pbRypw==}++ resolution: {integrity: sha512-/yPhxI1ntnDNsiHtzLKYnE3vf9JZ6cAisqVDauhp4CEHxlb4uoOTxOCJ+9s51bIB8U1N1FJ1RXOKTIlD5B/gqw==}++ resolution: {integrity: sha512-ADVjpOOkjz1hhkZLlBiYA9cR2Anf8F4HqZUO6e5eDcPQd0Txw5fxLzzxnEkSkfnD0wziSGiv7sYhk/ktvbf1uw==}++ resolution: {integrity: sha512-Ub2ncQv+fwD70/l4ou27b4YzfNaCJOvyX4HxXU15m7mpYY+rjuWzsLIPZHJL253Z643RpbcP1oeIJlQ/SKW67g==}++ resolution: {integrity: sha512-xHlTOmuCSotIA8TW1mDIM6X2O1SiX5P9IuDtqGonFhEK0qgRI4yeC6vMxEV2dgyr2TiD+2PQ10o+cOhdVAcwfg==}++ resolution: {integrity: sha512-qIBZhqxqI6fjLDYFTBIa4eivDMnP+OZqsNwmQ3xNLE4Cxwc+zfQEfbs6tzAo2Hjq+bh6q5F+Z8/cksrLFYWQQw==}++ resolution: {integrity: sha512-vsKArQsicm7t0z2GugkCKtZehqUm31oeGBV/KVSorWSy8ZlNAv7ytjFhvaryUiCUJYqs+NoE6AFhpQvBTM6Q4w==}++ resolution: {integrity: sha512-j9DGrQLm/Uhl2tCzcbLhy5kXsgkHUrjJHg4fFAeoMRwJmJerT9aw4FEhIbZStWN8A3qMwOp1uzHr4UL8AInxtA==}++ resolution: {integrity: sha512-RR3i96ohZGde//4WSe/dJsxOX6vxIg9TimLAS3i4EhBAFx8Sm5SmqVfR8E87DPSR31nEAjZfbt91OMZWcNgdZw==}++ resolution: {integrity: sha512-TKr+LIDX2pkBJXFLzpyPyljzYK3MtmllMUMODTQJIUfDGncESaqB90db9IAUcz4AZAJFdd8U9zOp9ty1458rxg==}++ resolution: {integrity: sha512-jY8CSxmpWLOxS+t8W+FG3Xigc0RDQA9bKMY/EwILvsesiRniiVMejYTE4wumNc2f4UbAa4WsHqe3J1QS1sli+A==}++ resolution: {integrity: sha512-28kbwaBjc5yAI1XadbdPYHX/eDnqaUFVikLwrO7FDnKG7lpgxnvk/XGRhX/PN0mOZ+dBSZ+LgunHS+6tYQAzhA==}++ resolution: {integrity: sha512-KvOVV+X1yLBfs9dCBSopq/+G1PcgT3lAK07mC4BzXi5E7ahzMAF8oIupDDJ6mievI6F+lAATkbQQlQixJfT3aQ==}++ resolution: {integrity: sha512-anK8SWmNphkXdaKgz5hJvGa7l00qmcaUQoMYsBwDlSKFKjc6gjGXPDw3FNL3Nbwq5L8gE+RCbGqTw49FK5Qyvg==}++ resolution: {integrity: sha512-S0ze2R9GH+fu41FA7pbSqNWObo/kzwf8rN/+IGlW/4tC6oACOs8B++bh+i9bVyNnwCcuksbFwsBme5OCKXCwIw==}++ resolution: {integrity: sha512-vZZio48k7ON0fVS3CUgFatWHoKbbLTK/rT7pzpJ4Bjp5JjkZeasRfrS9wsBdDJK2cJLHMckXZdzPSSr1B8a4oQ==}++ resolution: {integrity: sha512-bmkNc7z8Wn6kgjZmVHOX3SowGmVdhYS7yBpMnuMnPzDq/6xwVA604DuOXMZTO1lvq01g+Adfa0pE2UKGlxL1XQ==}++ resolution: {integrity: sha512-r4Sc6leeUTn3P6gk20aFMj2ntPwn6qpDZqWvYmAG6NgvFTIlj4WtrAudLi65qYoaGdXYViXYw2pkmn7QnIFasA==}++ resolution: {integrity: sha512-pS+ROfCXAGLWCOc8egcBvT0kf27GoWMqtdarNfDcjb6YLuV5cM3ioG45Ys2qOVqeqSbjaKg72vU+Wby3eddPsA==}++ resolution: {integrity: sha512-xNn4Pqkj2puRhKdKTm8t1YHC/BAjx6CEwRFXntTaRf/x16aqka6ouVoutm+QdkISTlT7e2zU7U4ZdlDLJd2Mcw==}++ resolution: {integrity: sha512-2xhYT0sfo85FMrUPtHcPo2rrp1lwbDEEzpx7jiH2xXJLqBuy4H0GgXk5ToU8IEwoROtXuL8ND0ttVa4rNqYK3w==}++ resolution: {integrity: sha512-6KU6qO7DZ7GJkaCgwBNtplXCvGkJToU86ybBAUdavvgsCiG8lSSvYxr9MhwmQ+udpzywHsl4RpGJsYWG1pDOcA==}++ resolution: {integrity: sha512-WhYv5UEcZrbAtlsnPuChHUAsu/iBPOVaEVsntLBIdpibO0ddy8OzavZz3iL2xVvBZOpolujSliP65Kq0/7KIYw==}++ resolution: {integrity: sha512-jZNtiFl/1aY73yS3UGQkutD0UbhTt68qnRpw2Pifmz5wV9h8gOVsN70v+Lq/f1rKaU/W8pxRe8y8Q9FX1AOe1Q==}++ resolution: {integrity: sha512-8JZt9ElZ5kyTnO94muPxIGS8oyElRJaiJO8EzV6ZSyGQ1Is8xwl4Q45qU5UOg+bGH4AikWziz0iN4sFLWs8PGw==}++ resolution: {integrity: sha512-oNh6S2WMHWRZrmutsRmDDfkzKtxF+bc2VxLC9dvtrDIRFln627VsFP6fLMgTryGDljgLPjkrzQSDcPrjPyDJ5w==}++ resolution: {integrity: sha512-o/sd0nMof8kYff+TqcDx3VSrgBTcZpSvYcAHIfHhv5VAuNmisCxjhx6YmxS8PFEpb9z5WKWKPdzf0jM23ro3RQ==}++ resolution: {integrity: sha512-LPP/3KorzCwBxfeUuZmaR6bG2kdeHSbe0P2tY3FLRU4vYrjYz5hI4QZwV0njUx3jeuKe67YukQ1LSPZBKDqO/Q==}engines: {node: '>=8.6'}@@ -3323,6 +3500,15 @@ packages:resolution: {integrity: sha512-dYnhHh0nJoMfnkZs6GmmhFknAGRrLznOu5nc9ML+EJxGvrx6H7teuevqVqCuPcPK//3eDrrjQhehXVx9cnkGdw==}+ resolution: {integrity: sha512-U92vJgBPkbw4Zfu/IiW2oTZLSL3Zpv+uI7My2eq8JxKgqraFdU8YUGicEJCEgSbeaG+QDFqIcwwfMTOEelPxuA==}++ resolution: {integrity: sha512-FCxlKLNGknS5ba/1lmpYijMUzX2esxW5xQqjWxw2eHFfS2MSdaHVINFmhjo+qN1WhZhNimq0dZATN9pH0IDrpA==}++ resolution: {integrity: sha512-1OSmLd3awB/t8qdoEOMazZkNsfVTeY4fTsgzcQFdXNq8ToTN4ZGwrMnlda4K6smTFKD+GRV6O48i6Z4iKgPPpw==}+resolution: {integrity: sha512-8g3/Otx1eJaVD12e31UbJj1YzdtVvzH85HV7t+9MJYk/u3XmkOUJ5Ys9wQrf9PCPK8+xn4ymzqYCiZl6QWKn+A==}@@ -3654,6 +3840,9 @@ packages:resolution: {integrity: sha512-M8RGFoKtZ8dF+iwJfAJTOH/SM4KluKOKRJpjCMhI8bG3qB74zrFoArKZ62ll0Fr3mqkMJiQOmWYkdYgDeITYQg==}+ resolution: {integrity: sha512-tmMpK00BjZiUyVyvrBK7knerNgmgvcV/KLVyuma/SC+TQN167GrMRciANTz09+k3zW8L8t60jWO1GpfkZdjTaw==}+resolution: {integrity: sha512-UQMIo7pb8WRomKR1/+MFVLTroIvDVtMX3K6OUir8ynLyzB8Jeriont2bTAtmNPa1ekAgN7YPDyf6V+ygrdU+eQ==}engines: {node: '>=16'}@@ -3715,6 +3904,21 @@ packages:resolution: {integrity: sha512-ve2KP6f/JnbPBFyobGHuerC9g1FYGn/F8n1LWTwNxCEzd6IfqTwUQcNXgEtmmQ6DlRrC1hrSrBnCZPokRrDHjw==}+ resolution: {integrity: sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA==}++ resolution: {integrity: sha512-2qCTHimwdxLfz+YzdGfkqNlH0tLi9xjTnHddPmJwtIG9MGsdbutfTc4P+haPD7l7Cjxf/WZj+we5qfVPvvxfYw==}++ resolution: {integrity: sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ==}++ resolution: {integrity: sha512-L/PqWzfTP9lzzEa6CKs0k2nARxTdZduw3zyh8d2NVBnsyvHjSX4TWse388YrrQKbvI8w20fGjGlhgT96WwKykw==}++ resolution: {integrity: sha512-MR04uvD+07cwl/yhVuVWAtw+3GOR/knlL55Nd/wAdblk27GCVt3lqpTivy/tkJcZoNPzTwS1Y+KMojlLDhoTzg==}+resolution: {integrity: sha512-CJ1QgKmNg3CwvAv/kOFmtnEN05f0D/cn9QntgNOQlQF9dgvVTHj3t+8JPdjqawCHk7V/KA+fbUqzZ9XWhcqPUg==}engines: {node: '>= 4.0.0'}@@ -3792,6 +3996,12 @@ packages:peerDependencies:vue: ^3.0.11+ resolution: {integrity: sha512-jRDZ1IMLttGj41KcZvlrYAaI3CfqpLpfpf+Mfig13viT6NKvRzWZ+lXz0Y5D60w6uJIBAOGq9mSHf0gktF0duw==}++ resolution: {integrity: sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q==}+resolution: {integrity: sha512-cwz/Pg6+95YbgIDp+RPwEToc4TKxfsFWSG/tsl2DSZd9YZicUag1tQXjJ5xcL7ydvEoaC2FOZeaXOU60t9BRXw==}engines: {node: ^18.19.0 || >=20.6.0}@@ -4120,6 +4330,9 @@ packages:resolution: {integrity: sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==}engines: {node: '>=10'}+ resolution: {integrity: sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==}+snapshots:'@alloc/[email protected]': {}@@ -4985,6 +5198,10 @@ snapshots:'@types/linkify-it': 5.0.0'@types/mdurl': 2.0.0+ '@types/[email protected]':+ dependencies:+ '@types/unist': 3.0.3+'@types/[email protected]': {}'@types/[email protected]': {}@@ -5112,6 +5329,8 @@ snapshots:'@types/[email protected]': {}+ '@types/[email protected]': {}+'@types/[email protected]': {}'@types/[email protected]': {}@@ -5556,6 +5775,8 @@ snapshots:transitivePeerDependencies:- debug+ [email protected]: {}+@@ -5626,6 +5847,8 @@ snapshots:+ [email protected]: {}+dependencies:assertion-error: 2.0.1@@ -5650,6 +5873,8 @@ snapshots:ansi-styles: 4.3.0supports-color: 7.2.0+ [email protected]: {}+@@ -5961,6 +6186,10 @@ snapshots:+ dependencies:+ character-entities: 2.0.2+@@ -5986,8 +6215,14 @@ snapshots:+ [email protected]: {}++ dependencies:+ dequal: 2.0.3+@@ -6104,6 +6339,8 @@ snapshots:+ [email protected]: {}+dependencies:esprima: 4.0.1@@ -6239,6 +6476,8 @@ snapshots:+ [email protected]: {}+@@ -6249,7 +6488,7 @@ snapshots:'@nodelib/fs.walk': 1.2.8glob-parent: 5.1.2merge2: 1.4.1- micromatch: 4.0.8+ micromatch: 4.0.7@@ -6480,6 +6719,8 @@ snapshots:+ [email protected]: {}+@@ -6698,6 +6939,8 @@ snapshots:+ [email protected]: {}+dependencies:get-func-name: 2.0.2@@ -6735,16 +6978,310 @@ snapshots:punycode.js: 2.3.1uc.micro: 2.1.0+ [email protected]: {}+dependencies:'@babel/runtime': 7.24.6remove-accents: 0.5.0+ dependencies:+ '@types/mdast': 4.0.4+ escape-string-regexp: 5.0.0+ unist-util-is: 6.0.0+ unist-util-visit-parents: 6.0.1++ dependencies:+ '@types/mdast': 4.0.4+ '@types/unist': 3.0.3+ decode-named-character-reference: 1.0.2+ devlop: 1.1.0+ mdast-util-to-string: 4.0.0+ micromark: 4.0.0+ micromark-util-decode-numeric-character-reference: 2.0.1+ micromark-util-decode-string: 2.0.0+ micromark-util-normalize-identifier: 2.0.0+ micromark-util-symbol: 2.0.0+ micromark-util-types: 2.0.0+ unist-util-stringify-position: 4.0.0+ transitivePeerDependencies:+ - supports-color++ dependencies:+ '@types/mdast': 4.0.4+ ccount: 2.0.1+ devlop: 1.1.0+ mdast-util-find-and-replace: 3.0.1+ micromark-util-character: 2.1.0++ dependencies:+ '@types/mdast': 4.0.4+ devlop: 1.1.0+ mdast-util-from-markdown: 2.0.1+ mdast-util-to-markdown: 2.1.0+ micromark-util-normalize-identifier: 2.0.0+ transitivePeerDependencies:+ - supports-color++ dependencies:+ '@types/mdast': 4.0.4+ mdast-util-from-markdown: 2.0.1+ mdast-util-to-markdown: 2.1.0+ transitivePeerDependencies:+ - supports-color++ dependencies:+ '@types/mdast': 4.0.4+ devlop: 1.1.0+ markdown-table: 3.0.3+ mdast-util-from-markdown: 2.0.1+ mdast-util-to-markdown: 2.1.0+ transitivePeerDependencies:+ - supports-color++ dependencies:+ '@types/mdast': 4.0.4+ devlop: 1.1.0+ mdast-util-from-markdown: 2.0.1+ mdast-util-to-markdown: 2.1.0+ transitivePeerDependencies:+ - supports-color++ dependencies:+ mdast-util-from-markdown: 2.0.1+ mdast-util-gfm-autolink-literal: 2.0.1+ mdast-util-gfm-footnote: 2.0.0+ mdast-util-gfm-strikethrough: 2.0.0+ mdast-util-gfm-table: 2.0.0+ mdast-util-gfm-task-list-item: 2.0.0+ mdast-util-to-markdown: 2.1.0+ transitivePeerDependencies:+ - supports-color++ dependencies:+ '@types/mdast': 4.0.4+ unist-util-is: 6.0.0++ dependencies:+ '@types/mdast': 4.0.4+ '@types/unist': 3.0.3+ longest-streak: 3.1.0+ mdast-util-phrasing: 4.1.0+ mdast-util-to-string: 4.0.0+ micromark-util-decode-string: 2.0.0+ unist-util-visit: 5.0.0+ zwitch: 2.0.4++ dependencies:+ '@types/mdast': 4.0.4++ dependencies:+ decode-named-character-reference: 1.0.2+ devlop: 1.1.0+ micromark-factory-destination: 2.0.0+ micromark-factory-label: 2.0.0+ micromark-factory-space: 2.0.0+ micromark-factory-title: 2.0.0+ micromark-factory-whitespace: 2.0.0+ micromark-util-character: 2.1.0+ micromark-util-chunked: 2.0.0+ micromark-util-classify-character: 2.0.0+ micromark-util-html-tag-name: 2.0.0+ micromark-util-normalize-identifier: 2.0.0+ micromark-util-resolve-all: 2.0.0+ micromark-util-subtokenize: 2.0.1+ micromark-util-symbol: 2.0.0+ micromark-util-types: 2.0.0++ dependencies:+ micromark-util-character: 2.1.0+ micromark-util-sanitize-uri: 2.0.0+ micromark-util-symbol: 2.0.0+ micromark-util-types: 2.0.0++ dependencies:+ devlop: 1.1.0+ micromark-core-commonmark: 2.0.1+ micromark-factory-space: 2.0.0+ micromark-util-character: 2.1.0+ micromark-util-normalize-identifier: 2.0.0+ micromark-util-sanitize-uri: 2.0.0+ micromark-util-symbol: 2.0.0+ micromark-util-types: 2.0.0++ dependencies:+ devlop: 1.1.0+ micromark-util-chunked: 2.0.0+ micromark-util-classify-character: 2.0.0+ micromark-util-resolve-all: 2.0.0+ micromark-util-symbol: 2.0.0+ micromark-util-types: 2.0.0++ dependencies:+ devlop: 1.1.0+ micromark-factory-space: 2.0.0+ micromark-util-character: 2.1.0+ micromark-util-symbol: 2.0.0+ micromark-util-types: 2.0.0++ dependencies:+ micromark-util-types: 2.0.0++ dependencies:+ devlop: 1.1.0+ micromark-factory-space: 2.0.0+ micromark-util-character: 2.1.0+ micromark-util-symbol: 2.0.0+ micromark-util-types: 2.0.0++ dependencies:+ micromark-extension-gfm-autolink-literal: 2.1.0+ micromark-extension-gfm-footnote: 2.1.0+ micromark-extension-gfm-strikethrough: 2.1.0+ micromark-extension-gfm-table: 2.1.0+ micromark-extension-gfm-tagfilter: 2.0.0+ micromark-extension-gfm-task-list-item: 2.1.0+ micromark-util-combine-extensions: 2.0.0+ micromark-util-types: 2.0.0++ dependencies:+ micromark-util-character: 2.1.0+ micromark-util-symbol: 2.0.0+ micromark-util-types: 2.0.0++ dependencies:+ devlop: 1.1.0+ micromark-util-character: 2.1.0+ micromark-util-symbol: 2.0.0+ micromark-util-types: 2.0.0++ dependencies:+ micromark-util-character: 2.1.0+ micromark-util-types: 2.0.0++ dependencies:+ micromark-factory-space: 2.0.0+ micromark-util-character: 2.1.0+ micromark-util-symbol: 2.0.0+ micromark-util-types: 2.0.0++ dependencies:+ micromark-factory-space: 2.0.0+ micromark-util-character: 2.1.0+ micromark-util-symbol: 2.0.0+ micromark-util-types: 2.0.0++ dependencies:+ micromark-util-symbol: 2.0.0+ micromark-util-types: 2.0.0++ dependencies:+ micromark-util-symbol: 2.0.0++ dependencies:+ micromark-util-character: 2.1.0+ micromark-util-symbol: 2.0.0+ micromark-util-types: 2.0.0++ dependencies:+ micromark-util-chunked: 2.0.0+ micromark-util-types: 2.0.0++ dependencies:+ micromark-util-symbol: 2.0.0++ dependencies:+ decode-named-character-reference: 1.0.2+ micromark-util-character: 2.1.0+ micromark-util-decode-numeric-character-reference: 2.0.1+ micromark-util-symbol: 2.0.0++ [email protected]: {}++ [email protected]: {}++ dependencies:+ micromark-util-symbol: 2.0.0++ dependencies:+ micromark-util-types: 2.0.0++ dependencies:+ micromark-util-character: 2.1.0+ micromark-util-encode: 2.0.0+ micromark-util-symbol: 2.0.0++ dependencies:+ devlop: 1.1.0+ micromark-util-chunked: 2.0.0+ micromark-util-symbol: 2.0.0+ micromark-util-types: 2.0.0++ [email protected]: {}++ [email protected]: {}++ dependencies:+ '@types/debug': 4.1.12+ debug: 4.3.7+ decode-named-character-reference: 1.0.2+ devlop: 1.1.0+ micromark-core-commonmark: 2.0.1+ micromark-factory-space: 2.0.0+ micromark-util-character: 2.1.0+ micromark-util-chunked: 2.0.0+ micromark-util-combine-extensions: 2.0.0+ micromark-util-decode-numeric-character-reference: 2.0.1+ micromark-util-encode: 2.0.0+ micromark-util-normalize-identifier: 2.0.0+ micromark-util-resolve-all: 2.0.0+ micromark-util-sanitize-uri: 2.0.0+ micromark-util-subtokenize: 2.0.1+ micromark-util-symbol: 2.0.0+ micromark-util-types: 2.0.0+ transitivePeerDependencies:+ - supports-color+dependencies:braces: 3.0.3picomatch: 2.3.1@@ -7257,6 +7794,32 @@ snapshots:+ dependencies:+ '@types/mdast': 4.0.4+ mdast-util-gfm: 3.0.0+ micromark-extension-gfm: 3.0.0+ remark-parse: 11.0.0+ remark-stringify: 11.0.0+ unified: 11.0.5+ transitivePeerDependencies:+ - supports-color++ dependencies:+ '@types/mdast': 4.0.4+ mdast-util-from-markdown: 2.0.1+ micromark-util-types: 2.0.0+ unified: 11.0.5+ transitivePeerDependencies:+ - supports-color++ dependencies:+ '@types/mdast': 4.0.4+ mdast-util-to-markdown: 2.1.0+ unified: 11.0.5+@@ -7497,7 +8060,7 @@ snapshots:is-glob: 4.0.3jiti: 1.21.0lilconfig: 2.1.0- micromatch: 4.0.8+ micromatch: 4.0.7normalize-path: 3.0.0object-hash: 3.0.0picocolors: 1.1.0@@ -7580,6 +8143,8 @@ snapshots:+ [email protected]: {}+dependencies:typescript: 5.5.4@@ -7637,6 +8202,35 @@ snapshots:+ dependencies:+ '@types/unist': 3.0.3+ bail: 2.0.2+ devlop: 1.1.0+ extend: 3.0.2+ is-plain-obj: 4.1.0+ trough: 2.2.0+ vfile: 6.0.3++ dependencies:+ '@types/unist': 3.0.3++ dependencies:+ '@types/unist': 3.0.3++ dependencies:+ '@types/unist': 3.0.3+ unist-util-is: 6.0.0++ dependencies:+ '@types/unist': 3.0.3+ unist-util-is: 6.0.0+ unist-util-visit-parents: 6.0.1+@@ -7710,6 +8304,16 @@ snapshots:evtd: 0.2.4vue: 3.4.31([email protected])+ dependencies:+ '@types/unist': 3.0.3+ unist-util-stringify-position: 4.0.0++ dependencies:+ '@types/unist': 3.0.3+ vfile-message: 4.0.2+dependencies:cac: 6.7.14@@ -8040,3 +8644,5 @@ snapshots:++ [email protected]: {}diff --git a/frontend/src/components/MonacoEditor/MonacoTextModelEditor.vue b/frontend/src/components/MonacoEditor/MonacoTextModelEditor.vueindex cd512a1ee7..0150eb4d52 100644--- a/frontend/src/components/MonacoEditor/MonacoTextModelEditor.vue+++ b/frontend/src/components/MonacoEditor/MonacoTextModelEditor.vue@@ -75,6 +75,7 @@ import {useLineHighlights,useLSPConnectionState,useOverrideSuggestIcons,+ type FormatContentOptions,} from "./composables";import monaco, { createMonacoEditor } from "./editor";import type {@@ -98,6 +99,7 @@ const props = withDefaults(advices?: AdviceOption[];lineHighlights?: LineHighlightOption[];options?: IStandaloneEditorConstructionOptions;+ formatContentOptions?: FormatContentOptions;placeholder?: string;}>(),{@@ -110,6 +112,7 @@ const props = withDefaults(advices: () => [],lineHighlights: () => [],options: undefined,+ formatContentOptions: undefined,placeholder: undefined,});@@ -181,7 +184,12 @@ onMounted(async () => {useOptions(monaco, editor, toRef(props, "options"));useModel(monaco, editor, toRef(props, "model"));useSuggestOptionByLanguage(monaco, editor);- useFormatContent(monaco, editor, toRef(props, "dialect"));+ useFormatContent(+ monaco,+ editor,+ toRef(props, "dialect"),+ toRef(props, "formatContentOptions")+ );const content = useContent(monaco, editor);const selectedContent = useSelectedContent(monaco, editor);const selection = useSelection(monaco, editor);diff --git a/frontend/src/components/MonacoEditor/composables/useFormatContent.ts b/frontend/src/components/MonacoEditor/composables/useFormatContent.tsindex 54f940cff9..76c2c7c772 100644--- a/frontend/src/components/MonacoEditor/composables/useFormatContent.ts+++ b/frontend/src/components/MonacoEditor/composables/useFormatContent.ts@@ -1,22 +1,47 @@import type monaco from "monaco-editor";import type { Ref } from "vue";-import { watchEffect } from "vue";+import { unref, watchEffect } from "vue";import type { SQLDialect } from "@/types";import type { MonacoModule } from "../types";import { formatEditorContent } from "../utils";import { useTextModelLanguage } from "./common";+export type FormatContentOptions = {+ disabled: boolean;+ callback?: (+ monaco: MonacoModule,+ editor: monaco.editor.IStandaloneCodeEditor+ ) => void;+};++const defaultOptions = (): FormatContentOptions => ({+ disabled: false,+});+export const useFormatContent = async (monaco: MonacoModule,editor: monaco.editor.IStandaloneCodeEditor,- dialect: Ref<SQLDialect | undefined>+ dialect: Ref<SQLDialect | undefined>,+ options: Ref<FormatContentOptions | undefined>) => {const language = useTextModelLanguage(editor);+ let action: monaco.IDisposable | undefined = undefined;++ watchEffect(() => {+ const opts = {+ ...defaultOptions(),+ ...unref(options),+ };++ if (action) {+ action.dispose();+ action = undefined;+ }+ if (opts.disabled) return;- watchEffect((onCleanup) => {if (language.value === "sql") {// add `Format SQL` action into context menu- const action = editor.addAction({+ action = editor.addAction({id: "format-sql",label: "Format SQL",keybindings: [@@ -25,6 +50,10 @@ export const useFormatContent = async (contextMenuGroupId: "operation",contextMenuOrder: 1,run: async () => {+ if (opts.callback) {+ opts.callback(monaco, editor);+ return;+ }const readonly = editor.getOption(monaco.editor.EditorOption.readOnly);@@ -32,9 +61,6 @@ export const useFormatContent = async (await formatEditorContent(editor, dialect.value);},});- onCleanup(() => {- action.dispose();- });} else {// When the language is "javascript", we can still use Alt+Shift+F to// format the document (the native feature of monaco-editor).diff --git a/frontend/src/components/ProvideSQLEditorContext.vue b/frontend/src/components/ProvideSQLEditorContext.vueindex c6e3e4e99b..5ae2e0bab9 100644--- a/frontend/src/components/ProvideSQLEditorContext.vue+++ b/frontend/src/components/ProvideSQLEditorContext.vue@@ -16,7 +16,9 @@</teleport><Suspense>- <router-view />+ <ProvideAIContext>+ <router-view />+ </ProvideAIContext></Suspense></template>@@ -26,6 +28,7 @@ import { debounce, head, omit } from "lodash-es";import { computed, nextTick, onMounted, watch } from "vue";import { useI18n } from "vue-i18n";import { useRoute, useRouter } from "vue-router";+import { ProvideAIContext } from "@/plugins/ai";import {SQL_EDITOR_HOME_MODULE,SQL_EDITOR_INSTANCE_MODULE,diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex 9170d61b3d..a422ca599d 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -291,7 +291,8 @@"override": "Override","encoding": "Encoding","finish": "Finish",- "title": "Title"+ "title": "Title",+ "hide": "Hide"},"error-page": {"go-back-home": "Go back home"@@ -3223,7 +3224,21 @@"dont-show-again": "Don't show again","text2sql": "Text2SQL","disable-text2sql": "Disable Text2SQL",- "enable-text2sql": "Enable Text2SQL"+ "enable-text2sql": "Enable Text2SQL",+ "actions": {+ "chat": "Chat",+ "explain-code": "Explain code",+ "find-problems": "Find problems",+ "new-chat": "New chat"+ },+ "send": "Send",+ "new-line": "New line",+ "ai-assistant": "AI Assistant",+ "not-configured": {+ "self": "AI Assistant is not configured.",+ "contact-admin-to-configure": "Please contact your org administrator.",+ "go-to-configure": "Go to configure"+ }}},"custom-approval": {diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex 9ce923112e..e4b2c07044 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -291,7 +291,8 @@"override": "Anular","encoding": "Codificación","finish": "Finalizar",- "title": "Título"+ "title": "Título",+ "hide": "Esconder"},"error-page": {"go-back-home": "Volver al inicio"@@ -3223,7 +3224,21 @@"dont-show-again": "No mostrar de nuevo","text2sql": "Text2SQL","disable-text2sql": "Deshabilitar Text2SQL",- "enable-text2sql": "Habilitar Text2SQL"+ "enable-text2sql": "Habilitar Text2SQL",+ "actions": {+ "chat": "Charlar",+ "explain-code": "Explicar el código",+ "find-problems": "encontrar problemas",+ "new-chat": "Nuevo chat"+ },+ "send": "Enviar",+ "new-line": "Nueva linea",+ "ai-assistant": "Asistente de IA",+ "not-configured": {+ "self": "El Asistente AI no está configurado.",+ "contact-admin-to-configure": "Comuníquese con el administrador de su organización.",+ "go-to-configure": "Ir a configurar"+ }}},"custom-approval": {@@ -3774,4 +3789,4 @@"setup": {"self": "Configuración"}-}\ No newline at end of file+}diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.jsonindex 177ce93961..18cdf9100c 100644--- a/frontend/src/locales/ja-JP.json+++ b/frontend/src/locales/ja-JP.json@@ -291,7 +291,8 @@"override": "オーバーライド","encoding": "エンコーディング","finish": "仕上げる",- "title": "タイトル"+ "title": "タイトル",+ "hide": "隠れる"},"error-page": {"go-back-home": "ホームページに戻る"@@ -3223,7 +3224,21 @@"dont-show-again": "再び表示しない","text2sql": "Text2SQL","disable-text2sql": "Text2SQLを閉じる",- "enable-text2sql": "Text2SQLを開く"+ "enable-text2sql": "Text2SQLを開く",+ "actions": {+ "chat": "チャット",+ "explain-code": "コードの説明",+ "find-problems": "問題を見つける",+ "new-chat": "新しいチャット"+ },+ "send": "送信",+ "new-line": "改行",+ "ai-assistant": "AI助手",+ "not-configured": {+ "self": "AI アシスタントが設定されていません。",+ "contact-admin-to-configure": "組織の管理者に問い合わせてください。",+ "go-to-configure": "設定に移動"+ }}},"custom-approval": {@@ -3774,4 +3789,4 @@"setup": {"self": "設定"}-}\ No newline at end of file+}diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex ea9f7ebde7..9e3dd8f169 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -291,7 +291,8 @@"override": "覆盖","encoding": "编码","finish": "完成",- "title": "标题"+ "title": "标题",+ "hide": "隐藏"},"error-page": {"go-back-home": "回到主页"@@ -3223,7 +3224,21 @@"dont-show-again": "不再显示","text2sql": "Text2SQL","disable-text2sql": "关闭 Text2SQL",- "enable-text2sql": "开启 Text2SQL"+ "enable-text2sql": "开启 Text2SQL",+ "actions": {+ "chat": "对话",+ "explain-code": "解释代码",+ "find-problems": "找出问题",+ "new-chat": "开启新对话"+ },+ "send": "发送",+ "new-line": "换行",+ "ai-assistant": "AI 助手",+ "not-configured": {+ "self": "AI 助手尚未配置。",+ "contact-admin-to-configure": "请联系您的组织管理员。",+ "go-to-configure": "前往配置"+ }}},"custom-approval": {@@ -3774,4 +3789,4 @@"setup": {"self": "设置"}-}\ No newline at end of file+}diff --git a/frontend/src/plugins/ai/components/AIChatToSQL.vue b/frontend/src/plugins/ai/components/AIChatToSQL.vueindex a9a55e5fd6..563269b8b4 100644--- a/frontend/src/plugins/ai/components/AIChatToSQL.vue+++ b/frontend/src/plugins/ai/components/AIChatToSQL.vue@@ -3,73 +3,8 @@</template><script lang="ts" setup>-import { useLocalStorage } from "@vueuse/core";-import Emittery from "emittery";-import { computed, reactive, toRef } from "vue";-import { useMetadata, useConnectionOfCurrentSQLEditorTab } from "@/store";-import { useSettingV1Store } from "@/store/modules/v1/setting";-import type { SQLEditorConnection } from "@/types";-import { DatabaseMetadataView } from "@/types/proto/v1/database_service";-import type { AIContextEvents } from "../types";+import { useAIContext } from "../logic";-const [{ useChatByTab, provideAIContext }, { default: ChatPanel }] =- await Promise.all([import("../logic"), import("./ChatPanel.vue")]);--type LocalState = {- showHistoryDialog: boolean;-};--const emit = defineEmits<{- (- event: "apply-statement",- statement: string,- conn: SQLEditorConnection,- run: boolean- ): void;-}>();--const state = reactive<LocalState>({- showHistoryDialog: false,-});--const settingV1Store = useSettingV1Store();-const openAIKeySetting = settingV1Store.getSettingByName(- "bb.plugin.openai.key"-);-const openAIEndpointSetting = settingV1Store.getSettingByName(- "bb.plugin.openai.endpoint"-);-const openAIKey = computed(() => openAIKeySetting?.value?.stringValue ?? "");-const openAIEndpoint = computed(- () => openAIEndpointSetting?.value?.stringValue ?? ""-);-const { connection, instance, database } = useConnectionOfCurrentSQLEditorTab();--const databaseMetadata = useMetadata(- computed(() => database.value.name),- false /* !skipCache */,- DatabaseMetadataView.DATABASE_METADATA_VIEW_FULL-);--const events: AIContextEvents = new Emittery();--events.on("apply-statement", ({ statement, run }) => {- emit("apply-statement", statement, connection.value, run);-});--const autoRun = useLocalStorage("bb.plugin.ai.auto-run", false);-autoRun.value = false;--const chat = useChatByTab();--provideAIContext({- openAIKey,- openAIEndpoint,- engine: computed(() => instance.value.engine),- databaseMetadata,- autoRun,- showHistoryDialog: toRef(state, "showHistoryDialog"),- chat,- events,-});+const [{ default: ChatPanel }] = await Promise.all([import("./ChatPanel.vue")]);+const { openAIKey } = useAIContext();</script>diff --git a/frontend/src/plugins/ai/components/ActionBar.vue b/frontend/src/plugins/ai/components/ActionBar.vueindex 2eb219e653..6aa1d4140b 100644--- a/frontend/src/plugins/ai/components/ActionBar.vue+++ b/frontend/src/plugins/ai/components/ActionBar.vue@@ -1,45 +1,77 @@<template><div- class="w-full flex flex-wrap gap-y-2 justify-between sm:items-center px-2 py-2 border-b bg-white"+ class="w-full flex flex-wrap gap-y-1 justify-between sm:items-center px-1 py-1 border-b bg-white"><div- class="action-left gap-x-2 flex overflow-x-auto sm:overflow-x-hidden items-center"+ class="action-left gap-x-2 flex overflow-x-auto sm:overflow-x-hidden items-center pl-1">- <NButton size="small" @click="tab!.editMode = 'SQL-EDITOR'">- <template #icon>- <heroicons:chevron-left />- </template>- <span>{{ $t("plugin.ai.conversation.exit-conversation-mode") }}</span>- </NButton>+ <h3>{{ $t("plugin.ai.ai-assistant") }}</h3></div><div- class="action-right gap-x-2 flex overflow-x-auto sm:overflow-x-hidden sm:justify-end items-center"+ class="action-right gap-x-1 flex overflow-x-auto sm:overflow-x-hidden sm:justify-end items-center">- <NButton size="small" @click="showHistoryDialog = true">- <template #icon>- <heroicons:clock />+ <NPopover placement="bottom">+ <template #trigger>+ <NButton+ size="small"+ quaternary+ style="--n-padding: 0 5px"+ @click="showHistoryDialog = true"+ >+ <template #icon>+ <ClockIcon class="w-4 h-4" />+ </template>+ </NButton>+ </template>+ <template #default>+ {{ $t("plugin.ai.conversation.view-history-conversations") }}+ </template>+ </NPopover>+ <NPopover placement="bottom">+ <template #trigger>+ <NButton+ size="small"+ quaternary+ style="--n-padding: 0 5px"+ @click="events.emit('new-conversation', { input: '' })"+ >+ <template #icon>+ <PlusIcon class="w-4 h-4" />+ </template>+ </NButton></template>- <span>{{- $t("plugin.ai.conversation.view-history-conversations")- }}</span>- </NButton>- <NButton size="small" @click="events.emit('new-conversation')">- <template #icon>- <heroicons:plus />+ <template #default>+ {{ $t("plugin.ai.conversation.new-conversation") }}</template>- <span>{{ $t("plugin.ai.conversation.new-conversation") }}</span>- </NButton>+ </NPopover>+ <NPopover placement="bottom">+ <template #trigger>+ <NButton+ size="small"+ quaternary+ style="--n-padding: 0 5px"+ @click="showAIPanel = false"+ >+ <template #icon>+ <XIcon class="w-4 h-4" />+ </template>+ </NButton>+ </template>+ <template #default>+ {{ $t("common.hide") }}+ </template>+ </NPopover></div></div></template><script lang="ts" setup>-import { NButton } from "naive-ui";-import { useCurrentSQLEditorTab } from "@/store";+import { ClockIcon, XIcon, PlusIcon } from "lucide-vue-next";+import { NButton, NPopover } from "naive-ui";+import { useSQLEditorContext } from "@/views/sql-editor/context";import { useAIContext } from "../logic";-const tab = useCurrentSQLEditorTab();-const { events, showHistoryDialog } = useAIContext();+const { showAIPanel } = useSQLEditorContext();</script>diff --git a/frontend/src/plugins/ai/components/ChatPanel.vue b/frontend/src/plugins/ai/components/ChatPanel.vueindex 7590c9e457..31d562c0c2 100644--- a/frontend/src/plugins/ai/components/ChatPanel.vue+++ b/frontend/src/plugins/ai/components/ChatPanel.vue@@ -1,31 +1,22 @@<template><divv-if="openAIKey"- class="w-full flex flex-col"- :class="[- !isChatMode && 'px-4 py-2 border-t',- isChatMode && 'flex-1 overflow-hidden',- ]"+ class="w-full h-full flex-1 flex flex-col overflow-hidden">- <template v-if="isChatMode">- <ActionBar />- <ChatView :conversation="selectedConversation" @enter="requestAI" />- </template>-- <div :class="[isChatMode && 'px-2 py-2 flex flex-col gap-2']">- <div v-if="isChatMode" class="flex items-center gap-2 w-full">- <DynamicSuggestions class="flex-1" @enter="requestAI" />- </div>- <PromptInput- v-if="tab"- @focus="tab.editMode = 'CHAT-TO-SQL'"- @enter="requestAI"- />+ <ActionBar />++ <ChatView+ :conversation="selectedConversation"+ class="pt-2"+ @enter="requestAI"+ />++ <div class="px-2 py-2 flex flex-col gap-2">+ <DynamicSuggestions class="flex-1 w-full" @enter="requestAI" />+ <PromptInput v-if="tab" @enter="requestAI" /></div>- <template v-if="isChatMode">- <HistoryPanel v-if="showHistoryDialog" />- </template>+ <HistoryPanel /></div></template>@@ -34,14 +25,11 @@ import type { AxiosResponse } from "axios";import { Axios } from "axios";import { head } from "lodash-es";import { storeToRefs } from "pinia";-import { computed, reactive, watch } from "vue";+import { reactive, watch } from "vue";import { useSQLEditorTabStore } from "@/store";-import {- databaseMetadataToText,- onConnectionChanged,- useAIContext,- useCurrentChat,-} from "../logic";+import { nextAnimationFrame } from "@/utils";+import { onConnectionChanged, useAIContext, useCurrentChat } from "../logic";+import * as promptUtils from "../logic/prompt";import { useConversationStore } from "../store";import type { OpenAIMessage, OpenAIResponse } from "../types";import ActionBar from "./ActionBar.vue";@@ -60,10 +48,9 @@ const state = reactive<LocalState>({const { currentTab: tab } = storeToRefs(useSQLEditorTabStore());const store = useConversationStore();-const isChatMode = computed(() => tab.value?.editMode === "CHAT-TO-SQL");const context = useAIContext();-const { events, openAIKey, openAIEndpoint, autoRun, showHistoryDialog } =+const { openAIKey, openAIEndpoint, showHistoryDialog, pendingSendChat } =context;const {list: conversationList,@@ -83,15 +70,10 @@ const requestAI = async (query: string) => {// add extra database schema metadata info if possibleconst engine = context.engine.value;const databaseMetadata = context.databaseMetadata.value;+const prompts: string[] = [];- prompts.push(`### You are a db and SQL expert.`);- prompts.push(- `### Your responses should be informative and terse. For example, "Find all the data in the table", you should only return query statements.`- );- prompts.push(databaseMetadataToText(databaseMetadata, engine));- prompts.push(`### Write a SQL statement to solve the question below`);- prompts.push(`### ${query}`);- prompts.push(`### PLEASE ADD NECESSARY QUOTES IN YOUR RESPONSE STATEMENT.`);+ prompts.push(promptUtils.declaration(databaseMetadata, engine));+ prompts.push(query);const prompt = prompts.join("\n");await store.createMessage({conversation_id: conversation.id,@@ -101,6 +83,7 @@ const requestAI = async (query: string) => {error: "",status: "DONE",});+ console.debug("[AI Assistant] init chat:", prompt);} else {await store.createMessage({conversation_id: conversation.id,@@ -166,6 +149,7 @@ const requestAI = async (query: string) => {}const text = head(data?.choices)?.message.content?.trim();+ console.debug("[AI Assistant] answer:", text);if (text) {answer.content = text;answer.prompt = text;@@ -181,18 +165,6 @@ const requestAI = async (query: string) => {if (conversation.id === conversation.id) {if (answer.status === "FAILED") {context.events.emit("error", answer.error);- } else {- if (- autoRun.value &&- t.id === tab.value.id &&- conversation.id === selectedConversation.value?.id- ) {- // If the chat is still active, emit 'apply-statement' event- context.events.emit("apply-statement", {- statement: answer.content,- run: autoRun.value,- });- }}}}@@ -202,16 +174,6 @@ onConnectionChanged(() => {showHistoryDialog.value = false;});-events.on("new-conversation", async () => {- if (!tab.value) return;- showHistoryDialog.value = false;- const c = await store.createConversation({- name: "",- ...tab.value.connection,- });- selectedConversation.value = c;-});-watch([ready, conversationList],async ([ready, list]) => {@@ -225,4 +187,20 @@ watch(},{ immediate: true });++watch(+ [ready, pendingSendChat],+ async ([ready]) => {+ if (!ready) return;++ await nextAnimationFrame();+ if (!pendingSendChat.value) return;+ requestAI(pendingSendChat.value.content);+ pendingSendChat.value = undefined;+ },+ {+ immediate: true,+ flush: "post",+ }+);</script>diff --git a/frontend/src/plugins/ai/components/ChatView/AIMessageView.vue b/frontend/src/plugins/ai/components/ChatView/AIMessageView.vueindex 26cb8a7729..3251152f55 100644--- a/frontend/src/plugins/ai/components/ChatView/AIMessageView.vue+++ b/frontend/src/plugins/ai/components/ChatView/AIMessageView.vue@@ -1,23 +1,21 @@<template><div- class="border rounded shadow py-1 px-1 bg-gray-100 border-gray-400"+ class="border rounded shadow py-1 px-1 bg-gray-50 border-gray-400":class="[message.status === 'DONE'- ? 'w-[80%]'+ ? 'w-[60%] min-w-[9rem]': message.status === 'FAILED'- ? 'max-w-[60%]'+ ? 'max-w-[40%] min-w-[9rem]': 'w-auto',]">- <CodeView v-if="message.status === 'DONE'" :message="message" />- <template v-else-if="message.status === 'LOADING'">- <BBSpin class="mx-1" />- </template>+ <Markdown v-if="message.status === 'DONE'" :content="message.content" />+ <div v-else-if="message.status === 'LOADING'" class="flex items-center">+ <BBSpin class="mx-1" :size="18" />+ </div><template v-else><div class="text-warning flex items-center gap-x-1">- <heroicons-outline:exclaimation-triangle- class="inline-block w-4 h-4 shrink-0"- />+ <TriangleAlertIcon class="inline-block w-4 h-4 shrink-0" /><span class="text-sm">{{ message.error }}</span>@@ -27,9 +25,10 @@</template><script lang="ts" setup>+import { TriangleAlertIcon } from "lucide-vue-next";import { BBSpin } from "@/bbkit";import type { Message } from "../../types";-import CodeView from "./CodeView.vue";+import Markdown from "./Markdown";defineProps<{message: Message;diff --git a/frontend/src/plugins/ai/components/ChatView/ChatView.vue b/frontend/src/plugins/ai/components/ChatView/ChatView.vueindex f22e6c77a5..0671a89537 100644--- a/frontend/src/plugins/ai/components/ChatView/ChatView.vue+++ b/frontend/src/plugins/ai/components/ChatView/ChatView.vue@@ -1,5 +1,5 @@<template>- <div ref="scrollerRef" class="flex-1 py-4 overflow-y-auto">+ <div ref="scrollerRef" class="flex-1 overflow-y-auto"><template v-if="conversation"><template v-if="conversation.messageList.length === 0"><EmptyView v-if="mode === 'VIEW'" />@@ -7,12 +7,12 @@<divv-elseref="containerRef"- class="flex flex-col justify-end px-4 gap-y-8"+ class="flex flex-col justify-end px-2 gap-y-4"><divv-for="message in conversation?.messageList":key="message.id"- class="flex"+ class="flex message":class="[message.author === 'AI' ? 'justify-start' : 'justify-end']"><UserMessageView@@ -35,7 +35,7 @@<template #create><buttonclass="normal-link"- @click="events.emit('new-conversation')"+ @click="events.emit('new-conversation', { input: '' })">{{ $t("common.create") }}</button>diff --git a/frontend/src/plugins/ai/components/ChatView/CodeView.vue b/frontend/src/plugins/ai/components/ChatView/CodeView.vuedeleted file mode 100644index d099d8cd9e..0000000000--- a/frontend/src/plugins/ai/components/ChatView/CodeView.vue+++ /dev/null@@ -1,168 +0,0 @@-<template>- <div class="flex items-start w-full">- <div class="flex-1 overflow-x-hidden">- <MonacoEditor- v-model:content="state.code"- class="border h-auto"- :readonly="!state.editing"- :auto-focus="false"- :auto-height="{- min: 48,- max: 120,- padding: 2,- }"- :options="{- automaticLayout: true,- fontSize: 12,- lineHeight: 14,- lineNumbers: 'off',- wordWrap: 'off',- scrollbar: {- vertical: 'hidden',- horizontal: 'hidden',- useShadows: false,- verticalScrollbarSize: 0,- horizontalScrollbarSize: 0,- alwaysConsumeMouseWheel: false,- },- }"- />- </div>- <div class="flex flex-col gap-y-2 ml-0.5 mt-1">- <NTooltip placement="right">- <template #trigger>- <button- class="inline-flex items-center justify-center hover:text-accent cursor-pointer"- @click="handleExecute"- >- <heroicons:play-circle class="w-4 h-4" />- </button>- </template>- <div class="whitespace-nowrap">- {{ $t("common.run") }}- </div>- </NTooltip>- <NTooltip placement="right">- <template #trigger>- <button- class="inline-flex items-center justify-center hover:text-accent cursor-pointer"- @click="handleCopy"- >- <heroicons:clipboard class="w-4 h-4" />- </button>- </template>- <div class="whitespace-nowrap">- {{ $t("common.copy") }}- </div>- </NTooltip>- <template v-if="!state.editing">- <NTooltip placement="right">- <template #trigger>- <button- class="inline-flex items-center justify-center hover:text-accent cursor-pointer"- @click="state.editing = true"- >- <heroicons:pencil class="w-4 h-4" />- </button>- </template>- <div class="whitespace-nowrap">- {{ $t("common.edit") }}- </div>- </NTooltip>- </template>- <template v-if="state.editing">- <NTooltip placement="right">- <template #trigger>- <button- class="inline-flex items-center justify-center hover:text-accent cursor-pointer"- @click="finishEditing(false)"- >- <heroicons:arrow-uturn-left class="w-4 h-4" />- </button>- </template>- <div class="whitespace-nowrap">- {{ $t("common.cancel") }}- </div>- </NTooltip>- <NTooltip placement="right">- <template #trigger>- <button- class="inline-flex items-center justify-center hover:text-accent cursor-pointer"- @click="finishEditing(true)"- >- <heroicons:check class="w-4 h-4" />- </button>- </template>- <div class="whitespace-nowrap">- {{ $t("common.save") }}- </div>- </NTooltip>- </template>- </div>- </div>-</template>--<script lang="ts" setup>-import { NTooltip } from "naive-ui";-import { reactive, watch } from "vue";-import { useI18n } from "vue-i18n";-import { MonacoEditor } from "@/components/MonacoEditor";-import { pushNotification } from "@/store";-import { toClipboard } from "@/utils";-import { useAIContext } from "../../logic";-import { useConversationStore } from "../../store";-import type { Message } from "../../types";--type LocalState = {- code: string;- editing: boolean;-};--const props = defineProps<{- message: Message;-}>();--const state = reactive<LocalState>({- code: props.message.content,- editing: false,-});-const { t } = useI18n();-const { events, showHistoryDialog } = useAIContext();--const handleExecute = () => {- events.emit("apply-statement", {- statement: props.message.content,- run: true,- });- showHistoryDialog.value = false;-};--const handleCopy = () => {- toClipboard(props.message.content).then(() => {- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t("plugin.ai.statement-copied"),- });- });-};--const finishEditing = async (update: boolean) => {- state.editing = false;- if (!update) {- state.code = props.message.content;- } else {- // eslint-disable-next-line vue/no-mutating-props- props.message.content = state.code;- await useConversationStore().updateMessage(props.message);- }-};--watch(- () => props.message.content,- (content) => {- state.code = content;- state.editing = false;- }-);-</script>diff --git a/frontend/src/plugins/ai/components/ChatView/Markdown/AstToVNode.vue b/frontend/src/plugins/ai/components/ChatView/Markdown/AstToVNode.vuenew file mode 100644index 0000000000..e91068e8e4--- /dev/null+++ b/frontend/src/plugins/ai/components/ChatView/Markdown/AstToVNode.vue@@ -0,0 +1,24 @@+<template>+ <AstToMarkdown />+</template>++<script setup lang="ts">+import type { Root } from "mdast";+import { mdastToVNode, type CustomRender, type State } from "./utils";++const props = defineProps<{+ ast: Root;+}>();++const slots = defineSlots<CustomRender>();++function AstToMarkdown() {+ const state: State = {+ slots,+ definitionById: new Map(),+ };+ const result = mdastToVNode[props.ast.type](props.ast, state);++ return result;+}+</script>diff --git a/frontend/src/plugins/ai/components/ChatView/Markdown/CodeBlock.vue b/frontend/src/plugins/ai/components/ChatView/Markdown/CodeBlock.vuenew file mode 100644index 0000000000..9a057a00d6--- /dev/null+++ b/frontend/src/plugins/ai/components/ChatView/Markdown/CodeBlock.vue@@ -0,0 +1,112 @@+<template>+ <div+ ref="containerRef"+ class="flex items-start"+ :data-message-wrapper-width="messageWrapperWidth"+ :style="`width: ${width}px`"+ >+ <div class="flex-1 overflow-x-hidden">+ <MonacoEditor+ :content="code"+ :readonly="true"+ :auto-focus="false"+ :auto-height="{+ min: 48,+ max: 120,+ padding: 2,+ }"+ :options="{+ automaticLayout: true,+ fontSize: 12,+ lineHeight: 14,+ lineNumbers: 'off',+ wordWrap: 'on',+ scrollbar: {+ vertical: 'hidden',+ horizontal: 'hidden',+ useShadows: false,+ verticalScrollbarSize: 0,+ horizontalScrollbarSize: 0,+ alwaysConsumeMouseWheel: false,+ },+ }"+ class="border h-auto bg-white"+ />+ </div>+ <div class="flex flex-col gap-y-2 ml-0.5 mt-1">+ <NPopover placement="right">+ <template #trigger>+ <button+ class="inline-flex items-center justify-center hover:text-accent cursor-pointer"+ @click="handleExecute"+ >+ <PlayIcon class="w-3.5 h-3.5" />+ </button>+ </template>+ <div class="whitespace-nowrap">+ {{ $t("common.run") }}+ </div>+ </NPopover>+ <NPopover placement="right">+ <template #trigger>+ <button+ class="inline-flex items-center justify-center hover:text-accent cursor-pointer"+ @click="handleCopy"+ >+ <ClipboardIcon class="w-3.5 h-3.5" />+ </button>+ </template>+ <div class="whitespace-nowrap">+ {{ $t("common.copy") }}+ </div>+ </NPopover>+ </div>+ </div>+</template>++<script lang="ts" setup>+import { useElementSize } from "@vueuse/core";+import { ClipboardIcon, PlayIcon } from "lucide-vue-next";+import { NPopover } from "naive-ui";+import { computed, ref } from "vue";+import { useI18n } from "vue-i18n";+import { MonacoEditor } from "@/components/MonacoEditor";+import { useAIContext } from "@/plugins/ai/logic";+import { pushNotification } from "@/store";+import { findAncestor, toClipboard } from "@/utils";++const props = defineProps<{+ code: string;+}>();++const { t } = useI18n();+const { events, showHistoryDialog } = useAIContext();+const containerRef = ref<HTMLElement>();+const messageWrapperRef = computed(() =>+ findAncestor(containerRef.value, ".message")+);+const { width: messageWrapperWidth } = useElementSize(messageWrapperRef);+const width = computed(() => {+ const PADDING = 8;+ const min = 8 * 16; /* 8rem */+ const auto = messageWrapperWidth.value * 0.6 - PADDING * 2;+ return Math.max(min, auto);+});++const handleExecute = () => {+ events.emit("run-statement", {+ statement: props.code,+ });+ showHistoryDialog.value = false;+};++const handleCopy = () => {+ toClipboard(props.code).then(() => {+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("plugin.ai.statement-copied"),+ });+ });+};+</script>diff --git a/frontend/src/plugins/ai/components/ChatView/Markdown/Markdown.vue b/frontend/src/plugins/ai/components/ChatView/Markdown/Markdown.vuenew file mode 100644index 0000000000..9ea2610dd2--- /dev/null+++ b/frontend/src/plugins/ai/components/ChatView/Markdown/Markdown.vue@@ -0,0 +1,34 @@+<template>+ <AstToMarkdown :ast="mdast" class="text-sm">+ <template #code="parsedAst">+ <CodeBlock :code="parsedAst.value" />+ </template>+ <template #inlineCode="parsedAst">+ <HighlightCodeBlock :code="parsedAst.value" class="inline-block bg-gray-200 px-0.5 mx-0.5" />+ </template>+ <template #image="parsedAst">+ <img :src="parsedAst.url" />+ </template>+ </AstToMarkdown>+</template>++<script lang="ts" setup>+import remarkGfm from "remark-gfm";+import remarkParse from "remark-parse";+import { unified } from "unified";+import { computed } from "vue";+import HighlightCodeBlock from "@/components/HighlightCodeBlock";+import AstToMarkdown from "./AstToVNode.vue";+import CodeBlock from "./CodeBlock.vue";++const props = defineProps<{+ content: string;+}>();++const processor = unified().use(remarkParse).use(remarkGfm);++const mdast = computed(() => {+ const tree = processor.parse(props.content ?? "");+ return tree;+});+</script>diff --git a/frontend/src/plugins/ai/components/ChatView/Markdown/index.ts b/frontend/src/plugins/ai/components/ChatView/Markdown/index.tsnew file mode 100644index 0000000000..9cf4ba582b--- /dev/null+++ b/frontend/src/plugins/ai/components/ChatView/Markdown/index.ts@@ -0,0 +1,3 @@+import Markdown from "./Markdown.vue";++export default Markdown;diff --git a/frontend/src/plugins/ai/components/ChatView/Markdown/utils.ts b/frontend/src/plugins/ai/components/ChatView/Markdown/utils.tsnew file mode 100644index 0000000000..bff7b7e8f3--- /dev/null+++ b/frontend/src/plugins/ai/components/ChatView/Markdown/utils.ts@@ -0,0 +1,603 @@+import type {+ Root,+ RootContent,+ RootContentMap,+ Text,+ Definition,+ AlignType,+} from "mdast";+import { normalizeUri } from "micromark-util-sanitize-uri";+import { h, type VNode } from "vue";++export type CustomRender = {+ blockquote(node: RootContentMap["blockquote"], state?: State): VNode | string;+ break(node: RootContentMap["break"], state?: State): VNode | string;+ code(node: RootContentMap["code"], state?: State): VNode | string;+ delete(node: RootContentMap["delete"], state?: State): VNode | string;+ emphasis(node: RootContentMap["emphasis"], state?: State): VNode | string;+ footnoteDefinition(+ node: RootContentMap["footnoteDefinition"],+ state?: State+ ): VNode | string;+ footnoteReference(+ node: RootContentMap["footnoteReference"],+ state?: State+ ): VNode | string;+ heading(node: RootContentMap["heading"], state?: State): VNode | string;+ html(node: RootContentMap["html"], state?: State): VNode | string;+ image(node: RootContentMap["image"], state?: State): VNode | string;+ definition(node: RootContentMap["definition"], state?: State): VNode | string;+ imageReference(+ node: RootContentMap["imageReference"],+ state?: State+ ): VNode | string;+ inlineCode(node: RootContentMap["inlineCode"], state?: State): VNode | string;+ link(node: RootContentMap["link"], state?: State): VNode | string;+ linkReference(+ node: RootContentMap["linkReference"],+ state?: State+ ): VNode | string;+ list(node: RootContentMap["list"], state?: State): VNode | string;+ listItem(node: RootContentMap["listItem"], state?: State): VNode | string;+ paragraph(node: RootContentMap["paragraph"], state?: State): VNode | string;+ strong(node: RootContentMap["strong"], state?: State): VNode | string;+ table(node: RootContentMap["table"], state?: State): VNode | string;+ text(node: RootContentMap["text"], state?: State): VNode | string;+ thematicBreak(+ node: RootContentMap["thematicBreak"],+ state?: State+ ): VNode | string;+};++export type State = {+ slots: CustomRender;+ definitionById: Map<string, Definition>;+};++type NodeKey = keyof CustomRender;++type NodeToVNodeKey = keyof typeof mdastToVNode;++function defaultMdNodeToVNode(node: RootContent, state?: State) {+ const type = node.type as NodeKey;++ if (state?.slots[type]) {+ return state.slots[type](node as any);+ }++ const handler: (typeof mdastToVNode)[NodeToVNodeKey] =+ type in mdastToVNode+ ? mdastToVNode[type as NodeToVNodeKey]+ : mdastToVNode.unknown;++ return handler(node as any, state);+}++function rootToVNode(node: Root, state?: State): VNode | string {+ const properties = {+ class: ["markdown"],+ };++ return h(+ "div",+ properties,+ node.children.map((child) => defaultMdNodeToVNode(child, state))+ );+}++function blockquoteToVNode(+ node: RootContentMap["blockquote"],+ state?: State+): VNode | string {+ return h(+ "blockquote",+ undefined,+ node.children.map((node) => defaultMdNodeToVNode(node, state))+ );+}++function breakToVNode(): VNode | string {+ // 貌似这货还需要多一个\n的字符……?不过看起来好像没必要……+ // {type: 'text', value: '\n'}+ return h("br");+}++function codeToVNode(node: RootContentMap["code"]): VNode | string {+ const value = node.value ? node.value + "\n" : "";+ const properties: Record<string, string> = {};++ if (node.lang) {+ properties.className = `language-${node.lang}`;+ }++ const result = h("code", properties, [value]);++ return h("pre", undefined, [result]);+}++function deleteToVNode(+ node: RootContentMap["delete"],+ state?: State+): VNode | string {+ return h(+ "del",+ undefined,+ node.children.map((node) => defaultMdNodeToVNode(node, state))+ );+}++function emphasisToVNode(+ node: RootContentMap["emphasis"],+ state?: State+): VNode | string {+ return h(+ "em",+ undefined,+ node.children.map((node) => defaultMdNodeToVNode(node, state))+ );+}++function footnoteDefinitionToVNode(+ node: RootContentMap["footnoteDefinition"],+ state?: State+): VNode | string {+ // footnoteDefinition的children只有一个child并且为text,这里强行转一下+ const text = node.children[0] as unknown as Text;+ return h("div", { class: "footnote-definition" }, [text.value]);++ // const clobberPrefix = "user-content-";+ // const id = String(node.identifier).toUpperCase();+ // const safeId = normalizeUri(id.toLowerCase());+ // const index = state?.footnoteOrder.indexOf(id) ?? 0;+ // let counter;++ // let reuseCounter = state?.footnoteCounts.get(id);++ // if (reuseCounter === undefined) {+ // reuseCounter = 0;+ // state?.footnoteOrder.push(id);+ // counter = state?.footnoteOrder.length;+ // } else {+ // counter = index + 1;+ // }++ // reuseCounter += 1;+ // state?.footnoteCounts.set(id, reuseCounter);++ // // footnoteDefinition的children只有一个child并且为text,这里强行转一下+ // const text = node.children[0] as unknown as Text;++ // return h("span", undefined, [+ // text.value,+ // h(+ // "a",+ // {+ // href: "#" + clobberPrefix + "fn-" + safeId,+ // id:+ // clobberPrefix ++ // "fnref-" ++ // safeId ++ // (reuseCounter > 1 ? "-" + reuseCounter : ""),+ // dataFootnoteRef: true,+ // ariaDescribedBy: ["footnote-label"],+ // },+ // [String(counter)]+ // ),+ // ]);+}++function footnoteReferenceToVNode(+ node: RootContentMap["footnoteReference"],+ state?: State+): VNode | string {+ return "";++ // const clobberPrefix = "user-content-";+ // const id = String(node.identifier).toUpperCase();+ // const safeId = normalizeUri(id.toLowerCase());+ // // TODO后面实验一下,现在LLM铁定进不到这个分支里+ // const index = state?.footnoteOrder.indexOf(id) ?? 0;+ // let counter;+ // let reuseCounter = state?.footnoteCounts.get(id);+ // if (reuseCounter === undefined) {+ // reuseCounter = 0;+ // state?.footnoteOrder.push(id);+ // counter = state?.footnoteOrder.length;+ // } else {+ // counter = index + 1;+ // }+ // reuseCounter += 1;+ // state?.footnoteCounts.set(id, reuseCounter);+ // return h("sup", undefined, [+ // h(+ // "a",+ // {+ // href: "#" + clobberPrefix + "fn-" + safeId,+ // id:+ // clobberPrefix ++ // "fnref-" ++ // safeId ++ // (reuseCounter > 1 ? "-" + reuseCounter : ""),+ // dataFootnoteRef: true,+ // ariaDescribedBy: ["footnote-label"],+ // },+ // [String(counter)]+ // ),+ // ]);+}++function headingToVNode(+ node: RootContentMap["heading"],+ state?: State+): VNode | string {+ const tagName = `h${node.depth}`;+ return h(+ tagName,+ undefined,+ node.children.map((node) => defaultMdNodeToVNode(node, state))+ );+}++function htmlToVNode(node: RootContentMap["html"]): VNode | string {+ return node.value;+}++type ImageProps = {+ src: string;+ alt?: string;+ title?: string;+};++function imageToVNode(node: RootContentMap["image"]): VNode | string {+ const properties: ImageProps = {+ src: normalizeUri(node.url),+ };++ if (node.alt !== null && node.alt !== undefined) {+ properties.alt = node.alt;+ }++ if (node.title !== null && node.title !== undefined) {+ properties.title = node.title;+ }++ return h("img", properties);+}++function definitionToVNode(+ node: RootContentMap["definition"],+ state?: State+): VNode | string {+ const id = String(node.identifier).toUpperCase();++ state?.definitionById.set(id, {+ url: node.url,+ type: "definition",+ identifier: node.identifier,+ });++ return "";+}++function referenceToText(+ node: RootContentMap["imageReference"] | RootContentMap["linkReference"],+ state?: State+) {+ if (node.type === "imageReference") {+ return `![${node.alt ?? ""}]`;+ }++ const children = node.children.map((node) =>+ defaultMdNodeToVNode(node, state)+ );++ const hasVnode = children.some((node) => typeof node !== "string");++ return hasVnode+ ? h("span", undefined, ["[", ...children, "]"])+ : `[${children.join("")}]`;+}++function imageReferenceToVNode(+ node: RootContentMap["imageReference"],+ state?: State+): VNode | string {+ const id = String(node.identifier).toUpperCase();+ const definition = state?.definitionById.get(id);++ if (!definition) {+ return referenceToText(node, state);+ }++ const properties: ImageProps = {+ src: normalizeUri(definition.url || ""),+ };+ if (node.alt) {+ properties.alt = node.alt;+ }++ if (definition.title !== null && definition.title !== undefined) {+ properties.title = definition.title;+ }++ return h("img", properties);+}++function inlineCodeToVNode(node: RootContentMap["inlineCode"]): VNode | string {+ const value = node.value.replace(/\r?\n|\r/g, " ");+ return h("code", undefined, [value]);+}++type LinkProps = {+ href: string;+ target: string;+ rel: string;+ title?: string;+};++function linkToVNode(+ node: RootContentMap["link"],+ state?: State+): VNode | string {+ const properties: LinkProps = {+ href: normalizeUri(node.url),+ target: "_blank",+ rel: "noreferrer nofollow noopener",+ };++ if (node.title !== null && node.title !== undefined) {+ properties.title = node.title;+ }++ return h(+ "a",+ properties,+ node.children.map((node) => defaultMdNodeToVNode(node, state))+ );+}++function linkReferenceToVNode(+ node: RootContentMap["linkReference"],+ state?: State+): VNode | string {+ const id = String(node.identifier).toUpperCase();+ const definition = state?.definitionById.get(id);++ if (!definition) {+ return referenceToText(node, state);+ }++ const properties: LinkProps = {+ href: normalizeUri(definition.url || ""),+ target: "_blank",+ rel: "noreferrer nofollow noopener",+ };++ if (definition.title !== null && definition.title !== undefined) {+ properties.title = definition.title;+ }++ return h(+ "a",+ properties,+ node.children.map((node) => defaultMdNodeToVNode(node, state))+ );+}++type ListProps = {+ start?: number;+};++function listToVNode(+ node: RootContentMap["list"],+ state?: State+): VNode | string {+ const properties: ListProps = {};++ const children = node.children.map((node) =>+ defaultMdNodeToVNode(node, state)+ );++ if (node.ordered) {+ if (typeof node.start === "number" && node.start !== 1) {+ properties.start = node.start;+ } else {+ properties.start = 1;+ }+ }++ return h(+ node.ordered ? "ol" : "ul",+ {+ style: `list-style: ${node.ordered ? "auto" : "initial"}; margin-left: 1rem;`,+ ...properties,+ },+ children+ );+}++type ListItemProps = {+ className?: string;+};++function listItemToVNode(+ node: RootContentMap["listItem"],+ state?: State+): VNode | string {+ const children = node.children.map((node) =>+ defaultMdNodeToVNode(node, state)+ );++ const properties: ListItemProps = {};++ if (typeof node.checked === "boolean") {+ const head = children[0];++ const checkedVNode = h("input", {+ type: "checkbox",+ checked: node.checked,+ disabled: true,+ });++ if (typeof head !== "string" && head?.type === "p") {+ head.children = [checkedVNode, ...((head.children as VNode[]) ?? [])];+ } else {+ children.unshift(h("p", undefined, [checkedVNode]));+ }++ // According to github-markdown-css, this class hides bullet.+ // See: <https://github.com/sindresorhus/github-markdown-css>.+ properties.className = "task-list-item";+ }++ return h("li", properties, children);+}++function paragraphToVNode(+ node: RootContentMap["paragraph"],+ state?: State+): VNode | string {+ return h(+ // 避免出现p套p的情况,尤其是各种扩展组件(比如mermaid)之类的会出现+ "div",+ { class: "paragraph" },+ node.children.map((node) => defaultMdNodeToVNode(node, state))+ );+}++function strongToVNode(+ node: RootContentMap["strong"],+ state?: State+): VNode | string {+ return h(+ "strong",+ undefined,+ node.children.map((node) => defaultMdNodeToVNode(node, state))+ );+}++function tableRowToVNode(+ node: RootContentMap["tableRow"],+ align: AlignType[],+ rowIndex: number,+ state?: State+): VNode | string {+ const tagName = rowIndex === 0 ? "th" : "td";++ const children = node.children.map((node, index) => {+ const alignInfo = align[index];+ const properties = alignInfo+ ? {+ align: alignInfo,+ }+ : undefined;++ return h(+ tagName,+ properties,+ node.children.map((node) => defaultMdNodeToVNode(node, state))+ );+ });++ return h("tr", undefined, children);+}++function tableToVNode(+ node: RootContentMap["table"],+ state?: State+): VNode | string {+ const tableHeadChildren: Array<VNode | string> = [];+ const tableContentChildren: Array<VNode | string> = [];++ const align = node.align ?? [];++ node.children.forEach((node, index) => {+ const vnode = tableRowToVNode(node, align, index, state);++ if (index === 0) {+ tableHeadChildren.push(vnode);+ } else {+ tableContentChildren.push(vnode);+ }+ });++ const children: Array<VNode | string> = [];+ if (tableHeadChildren.length > 0) {+ children.push(h("thead", undefined, tableHeadChildren));+ }++ if (tableContentChildren.length > 0) {+ children.push(h("tbody", undefined, tableContentChildren));+ }++ return h("table", undefined, children);+}++function textToVNode(node: RootContentMap["text"]): VNode | string {+ return node.value;+}++function thematicBreakToVNode(): VNode | string {+ return h("hr");+}++function defaultUnknownHandler(+ node: RootContent,+ state?: State+): VNode | string {+ if ("children" in node) {+ const properties = ("properties" in node ? node.properties : {}) as Record<+ string,+ any+ >;+ if ("className" in properties && Array.isArray(properties.className)) {+ // hast和vnode的结构不同导致的,JSX上的区别+ properties.className = properties.className.join(" ");+ }++ return h(+ "div",+ properties,+ node.children.map((node) => defaultMdNodeToVNode(node, state))+ );+ }++ if ("value" in node) {+ return node.value;+ }++ // empty node……???+ return "";+}++export const mdastToVNode = {+ root: rootToVNode,+ blockquote: blockquoteToVNode,+ break: breakToVNode,+ code: codeToVNode,+ delete: deleteToVNode,+ emphasis: emphasisToVNode,++ footnoteDefinition: footnoteDefinitionToVNode,+ footnoteReference: footnoteReferenceToVNode,++ heading: headingToVNode,+ html: htmlToVNode,+ image: imageToVNode,++ // TODO同上+ definition: definitionToVNode,+ imageReference: imageReferenceToVNode,++ inlineCode: inlineCodeToVNode,+ link: linkToVNode,+ linkReference: linkReferenceToVNode,+ list: listToVNode,+ listItem: listItemToVNode,+ paragraph: paragraphToVNode,+ strong: strongToVNode,+ table: tableToVNode,+ text: textToVNode,+ thematicBreak: thematicBreakToVNode,+ unknown: defaultUnknownHandler,+};diff --git a/frontend/src/plugins/ai/components/ChatView/UserMessageView.vue b/frontend/src/plugins/ai/components/ChatView/UserMessageView.vueindex 426955362c..4a4964a8d2 100644--- a/frontend/src/plugins/ai/components/ChatView/UserMessageView.vue+++ b/frontend/src/plugins/ai/components/ChatView/UserMessageView.vue@@ -1,13 +1,14 @@<template><div- class="max-w-[60%] border rounded shadow py-1 px-2 bg-indigo-100 border-indigo-400"+ class="user-message max-w-[60%] min-w-[9rem] border rounded shadow py-1 px-2 bg-indigo-100 border-indigo-400">- {{ message.content }}+ <Markdown :content="message.content" /></div></template><script lang="ts" setup>import type { Message } from "../../types";+import Markdown from "./Markdown";defineProps<{message: Message;diff --git a/frontend/src/plugins/ai/components/DynamicSuggestions.vue b/frontend/src/plugins/ai/components/DynamicSuggestions.vueindex 48b97b9581..3848f402d0 100644--- a/frontend/src/plugins/ai/components/DynamicSuggestions.vue+++ b/frontend/src/plugins/ai/components/DynamicSuggestions.vue@@ -1,5 +1,8 @@<template>- <div class="flex items-center overflow-hidden h-[22px]">+ <div+ v-if="!ready || suggestions.length > 0"+ class="flex items-center overflow-hidden h-[22px]"+ ><template v-if="dynamicSuggestions && !ready"><BBSpin :size="20" class="mr-2" /><span class="text-sm">{{@@ -18,21 +21,22 @@v-for="(sug, i) in suggestions":key="i"style="max-width: 20rem"- class="border shrink-0 py-0.5 px-2 cursor-pointer hover:bg-indigo-100 hover:border-indigo-500"+ class="border rounded-sm shrink-0 py-0.5 px-2 cursor-pointer hover:bg-indigo-100 hover:border-indigo-500"@click.capture="consume(sug)">{{ sug }}</NEllipsis><div class="shrink-0 flex items-center">- <BBSpin v-if="state === 'LOADING'" :size="20" />- <button+ <BBSpin v-if="state === 'LOADING'" :size="16" />+ <NButtonv-if="state === 'IDLE'"- class="text-gray-500 cursor-pointer py-0.5 px-1 rounded-md hover:bg-gray-200"+ size="tiny"+ quaternary@click="dynamicSuggestions?.fetch()">{{ $t("plugin.ai.conversation.tips.more") }}- </button>+ </NButton><span v-if="state === 'ENDED'" class="text-gray-500">{{ $t("plugin.ai.conversation.tips.no-more") }}</span>@@ -44,7 +48,7 @@</template><script lang="ts" setup>-import { NEllipsis } from "naive-ui";+import { NButton, NEllipsis } from "naive-ui";import { computed } from "vue";import { BBSpin } from "@/bbkit";import { useDynamicSuggestions } from "../logic";diff --git a/frontend/src/plugins/ai/components/HistoryPanel/ConversationList.vue b/frontend/src/plugins/ai/components/HistoryPanel/ConversationList.vueindex b13994988e..a5c8f49477 100644--- a/frontend/src/plugins/ai/components/HistoryPanel/ConversationList.vue+++ b/frontend/src/plugins/ai/components/HistoryPanel/ConversationList.vue@@ -30,7 +30,7 @@class="flex items-center p-0.5 border border-transparent rounded text-gray-500 hover:text-accent hover:bg-indigo-50 hover:border-accent cursor-pointer"@click.stop="state.rename = conversation">- <heroicons-outline:pencil class="w-3 h-3" />+ <PencilIcon class="w-3 h-3" /></button><NPopconfirm@positive-click="handleDeleteConversation(conversation)"@@ -40,7 +40,7 @@class="flex items-center p-0.5 border border-transparent rounded text-gray-500 hover:text-accent hover:bg-indigo-50 hover:border-accent cursor-pointer"@click.stop="">- <heroicons-outline:trash class="w-3 h-3" />+ <TrashIcon class="w-3 h-3" /></button></template><span>{{ $t("plugin.ai.conversation.delete") }}</span>@@ -50,12 +50,12 @@<divclass="sticky bottom-0 btn-normal items-center justify-center gap-x-1"- @click="events.emit('new-conversation')"+ @click="events.emit('new-conversation', { input: '' })">- <heroicons-outline:plus class="w-4 h-4" />- <span class="pr-2">{{- $t("plugin.ai.conversation.new-conversation")- }}</span>+ <PlusIcon class="w-4 h-4" />+ <span class="pr-2">+ {{ $t("plugin.ai.conversation.new-conversation") }}+ </span></div></template><template v-else>@@ -74,6 +74,7 @@<script lang="ts" setup>import { head } from "lodash-es";+import { PencilIcon, PlusIcon, TrashIcon } from "lucide-vue-next";import { NPopconfirm } from "naive-ui";import scrollIntoView from "scroll-into-view-if-needed";import { reactive, watch } from "vue";diff --git a/frontend/src/plugins/ai/components/HistoryPanel/HistoryPanel.vue b/frontend/src/plugins/ai/components/HistoryPanel/HistoryPanel.vueindex 5be3bdbf45..526f0d8996 100644--- a/frontend/src/plugins/ai/components/HistoryPanel/HistoryPanel.vue+++ b/frontend/src/plugins/ai/components/HistoryPanel/HistoryPanel.vue@@ -1,26 +1,25 @@<template>- <BBModal- :title="$t('plugin.ai.conversation.history-conversations')"- class="!pb-0"- container-class="!p-0"- @close="showHistoryDialog = false"- >- <div- class="h-[calc(100vh-10rem)] w-[calc(100vw-8rem)] max-w-[72rem] px-8 pb-4 flex"+ <Drawer v-model:show="showHistoryDialog">+ <DrawerContent+ :title="$t('plugin.ai.conversation.history-conversations')"+ class="w-[calc(100vw-8rem)] max-w-[72rem]"+ body-content-style="padding: 0">- <aside class="hidden lg:flex lg:flex-col w-[14em] border-l border-b">- <ConversationList />- </aside>+ <div class="flex h-full">+ <aside class="hidden lg:flex lg:flex-col w-[14em] border-l border-b">+ <ConversationList />+ </aside>- <div class="flex-1 flex flex-col bg-gray-100">- <ChatView mode="VIEW" :conversation="selected" />+ <div class="flex-1 flex flex-col bg-gray-100 overflow-hidden">+ <ChatView mode="VIEW" :conversation="selected" />+ </div></div>- </div>- </BBModal>+ </DrawerContent>+ </Drawer></template><script lang="ts" setup>-import { BBModal } from "@/bbkit";+import { Drawer, DrawerContent } from "@/components/v2";import { useAIContext, useCurrentChat } from "../../logic";import ChatView from "../ChatView";import ConversationList from "./ConversationList.vue";diff --git a/frontend/src/plugins/ai/components/MockInputPlaceholder.vue b/frontend/src/plugins/ai/components/MockInputPlaceholder.vuedeleted file mode 100644index 35087ca81e..0000000000--- a/frontend/src/plugins/ai/components/MockInputPlaceholder.vue+++ /dev/null@@ -1,60 +0,0 @@-<template>- <div v-if="!DISMISS_PLACEHOLDER" class="w-full px-4 py-2 border-t">- <NInputGroup>- <NInput- size="small"- class="bb-ai-mock-input !cursor-pointer"- :disabled="false"- :placeholder="$t('plugin.ai.text-to-sql-disabled-placeholder')"- @click.prevent.stop="handleClick"- >- <template #prefix>- <heroicons-outline:sparkles class="w-4 h-4 text-accent" />- </template>- <template #suffix>- <NTooltip>- <template #trigger>- <NButton- :quaternary="true"- type="primary"- size="small"- @click.prevent.stop="handleDismiss"- >- <heroicons:x-mark />- </NButton>- </template>- <div class="whitespace-nowrap">- {{ $t("plugin.ai.dont-show-again") }}- </div>- </NTooltip>- </template>- </NInput>- </NInputGroup>- </div>-</template>--<script lang="ts" setup>-import { NInput, NInputGroup, NButton, NTooltip } from "naive-ui";-import { useRouter } from "vue-router";-import { SETTING_ROUTE_WORKSPACE_GENERAL } from "@/router/dashboard/workspaceSetting";-import { DISMISS_PLACEHOLDER } from "./state";--const router = useRouter();--const handleClick = () => {- router.push({- name: SETTING_ROUTE_WORKSPACE_GENERAL,- hash: "#ai-assistant",- });-};--const handleDismiss = () => {- DISMISS_PLACEHOLDER.value = true;-};-</script>--<style lang="postcss">-.bb-ai-mock-input .n-input__input-el {- @apply !cursor-pointer !placeholder-current;-}-</style>diff --git a/frontend/src/plugins/ai/components/PromptInput.vue b/frontend/src/plugins/ai/components/PromptInput.vueindex 89f0466fc0..576278dc16 100644--- a/frontend/src/plugins/ai/components/PromptInput.vue+++ b/frontend/src/plugins/ai/components/PromptInput.vue@@ -1,30 +1,60 @@<template><NInput+ ref="inputRef"v-model:value="state.value":disabled="disabled":placeholder="$t('plugin.ai.text-to-sql-placeholder')"+ :autosize="{+ minRows: 1,+ maxRows: 10,+ }"+ :input-props="{+ style: 'box-shadow: none !important',+ }"+ size="small"+ type="textarea"+ style="--n-padding-left: 8px; --n-padding-right: 4px"@keypress.enter="handlePressEnter"><template #prefix>- <heroicons-outline:sparkles class="w-4 h-4 text-accent" />+ <heroicons-outline:sparkles class="w-3.5 h-3.5 text-accent" /></template><template #suffix>- <NButton- :quaternary="true"- :disabled="!state.value"- type="primary"- size="small"- @click="handlePressEnter"- >- ⏎- </NButton>+ <NPopover placement="bottom" style="--n-padding: 6px 8px">+ <template #trigger>+ <NButton+ :quaternary="true"+ :disabled="!state.value"+ type="primary"+ size="small"+ style="--n-padding: 0 6px"+ @click="handlePressEnter()"+ >+ ⏎+ </NButton>+ </template>+ <template #default>+ <div class="text-xs flex flex-col gap-1">+ <p class="flex items-center gap-1">+ <span>{{ $t("plugin.ai.send") }}</span>+ <span>({{ keyboardShortcutStr("⏎") }})</span>+ </p>+ <p class="flex items-center gap-1">+ <span>{{ $t("plugin.ai.new-line") }}</span>+ <span>({{ keyboardShortcutStr("shift+⏎") }})</span>+ </p>+ </div>+ </template>+ </NPopover></template></NInput></template><script lang="ts" setup>-import { NButton, NInput } from "naive-ui";-import { reactive } from "vue";+import { NButton, NInput, NPopover, type InputInst } from "naive-ui";+import { onMounted, reactive, ref, watch } from "vue";+import { keyboardShortcutStr, nextAnimationFrame } from "@/utils";+import { useAIContext } from "../logic";type LocalState = {value: string;@@ -47,12 +77,37 @@ const state = reactive<LocalState>({value: "",});+const { pendingPreInput } = useAIContext();+const inputRef = ref<InputInst>();+const applyValue = (value: string) => {state.value = "";emit("enter", value);};-const handlePressEnter = () => {+const handlePressEnter = (e?: KeyboardEvent) => {+ if (e?.shiftKey) {+ return;+ }applyValue(state.value);+ e?.preventDefault();};++onMounted(() => {+ inputRef.value?.focus();+});++watch(+ pendingPreInput,+ async () => {+ await nextAnimationFrame();+ if (!pendingPreInput.value) return;+ state.value = pendingPreInput.value;+ pendingPreInput.value = undefined;+ },+ {+ immediate: true,+ flush: "post",+ }+);</script>diff --git a/frontend/src/plugins/ai/components/ProvideAIContext.vue b/frontend/src/plugins/ai/components/ProvideAIContext.vuenew file mode 100644index 0000000000..b9506f73c1--- /dev/null+++ b/frontend/src/plugins/ai/components/ProvideAIContext.vue@@ -0,0 +1,112 @@+<template>+ <slot />+</template>++<script lang="ts" setup>+import Emittery from "emittery";+import { storeToRefs } from "pinia";+import { computed, reactive, ref, toRef } from "vue";+import { useEmitteryEventListener } from "@/composables/useEmitteryEventListener";+import {+ useConnectionOfCurrentSQLEditorTab,+ useMetadata,+ useSettingV1Store,+ useSQLEditorTabStore,+} from "@/store";+import { DatabaseMetadataView } from "@/types/proto/v1/database_service";+import { wrapRefAsPromise } from "@/utils";+import { provideAIContext, useChatByTab, useCurrentChat } from "../logic";+import { useConversationStore } from "../store";+import type { AIContext, AIContextEvents } from "../types";++type LocalState = {+ showHistoryDialog: boolean;+};++const state = reactive<LocalState>({+ showHistoryDialog: false,+});++const settingV1Store = useSettingV1Store();+const openAIKeySetting = settingV1Store.getSettingByName(+ "bb.plugin.openai.key"+);+const openAIEndpointSetting = settingV1Store.getSettingByName(+ "bb.plugin.openai.endpoint"+);+const openAIKey = computed(() => openAIKeySetting?.value?.stringValue ?? "");+const openAIEndpoint = computed(+ () => openAIEndpointSetting?.value?.stringValue ?? ""+);+const { instance, database } = useConnectionOfCurrentSQLEditorTab();++const databaseMetadata = useMetadata(+ computed(() => database.value.name),+ false /* !skipCache */,+ DatabaseMetadataView.DATABASE_METADATA_VIEW_FULL+);++const events: AIContextEvents = new Emittery();+const chat = useChatByTab();+const showHistoryDialog = toRef(state, "showHistoryDialog");+const pendingSendChat = ref<{ content: string }>();+const pendingPreInput = ref<string>();++const { currentTab: tab } = storeToRefs(useSQLEditorTabStore());+const store = useConversationStore();++const context: AIContext = {+ openAIKey,+ openAIEndpoint,+ engine: computed(() => instance.value.engine),+ databaseMetadata,+ showHistoryDialog,+ chat,+ pendingSendChat,+ pendingPreInput,+ events,+};+provideAIContext(context);++const { ready, selected: selectedConversation } = useCurrentChat(context);++useEmitteryEventListener(events, "new-conversation", async ({ input }) => {+ if (!tab.value) return;+ await wrapRefAsPromise(ready, /* expected */ true);+ showHistoryDialog.value = false;++ if (+ !selectedConversation.value ||+ selectedConversation.value.messageList.length !== 0+ ) {+ // reuse if current chat is empty+ // create new chat otherwise+ const c = await store.createConversation({+ name: "",+ ...tab.value.connection,+ });+ selectedConversation.value = c;+ }+ if (input) {+ requestAnimationFrame(() => {+ pendingPreInput.value = input;+ });+ }+});++useEmitteryEventListener(events, "send-chat", async ({ content, newChat }) => {+ if (!tab.value) return;+ await wrapRefAsPromise(ready, /* expected */ true);+ if (newChat) {+ showHistoryDialog.value = false;+ const c = await store.createConversation({+ name: "",+ ...tab.value.connection,+ });+ selectedConversation.value = c;+ }+ requestAnimationFrame(() => {+ pendingSendChat.value = { content };+ });+});+</script>diff --git a/frontend/src/plugins/ai/components/editor-actions.ts b/frontend/src/plugins/ai/components/editor-actions.tsnew file mode 100644index 0000000000..21ea3de2ee--- /dev/null+++ b/frontend/src/plugins/ai/components/editor-actions.ts@@ -0,0 +1,114 @@+import type monaco from "monaco-editor";+import type { MaybeRef } from "vue";+import { computed, shallowRef, unref, watchEffect } from "vue";+import type { MonacoModule } from "@/components/MonacoEditor";+import { useSelectedContent } from "@/components/MonacoEditor/composables";+import { useTextModelLanguage } from "@/components/MonacoEditor/composables/common";+import { useEditorContextKey } from "@/components/MonacoEditor/utils";+import type { AIContext, ChatAction } from "../types";++type AIActionsOptions = {+ actions: ChatAction[];+ callback: (+ action: ChatAction,+ monaco: MonacoModule,+ editor: monaco.editor.IStandaloneCodeEditor+ ) => void;+};++export const useAIActions = async (+ monaco: MonacoModule,+ editor: monaco.editor.IStandaloneCodeEditor,+ context: AIContext,+ options: MaybeRef<AIActionsOptions>+) => {+ const language = useTextModelLanguage(editor);+ const actions = shallowRef<monaco.IDisposable[]>([]);++ const checkContentEmpty = () => {+ const content = editor.getModel()?.getValue() ?? "";+ return content.length === 0;+ };+ const contentEmpty = useEditorContextKey(+ editor,+ "bb.ai.contentEmpty",+ checkContentEmpty()+ );+ editor.onDidChangeModelContent(() => {+ contentEmpty.set(checkContentEmpty());+ });++ const selectedContent = useSelectedContent(monaco, editor);+ useEditorContextKey(+ editor,+ "bb.ai.selectedContentEmpty",+ computed(() => selectedContent.value.length === 0)+ );++ watchEffect(() => {+ const opts = unref(options);+ actions.value.forEach((action) => {+ action.dispose();+ });+ actions.value = [];++ if (!context.openAIKey.value) {+ return;+ }++ if (language.value === "sql") {+ if (opts.actions.includes("explain-code")) {+ const action = editor.addAction({+ id: "explain-code",+ label: "Explain code",+ precondition: "!bb.ai.contentEmpty",+ contextMenuGroupId: "2_ai_assistant",+ contextMenuOrder: 1,+ run: async () => {+ opts.callback("explain-code", monaco, editor);+ },+ });+ actions.value.push(action);+ }+ if (opts.actions.includes("find-problems")) {+ const action = editor.addAction({+ id: "find-problems",+ label: "Find problems",+ precondition: "!bb.ai.contentEmpty",+ contextMenuGroupId: "2_ai_assistant",+ contextMenuOrder: 2,+ run: async () => {+ opts.callback("find-problems", monaco, editor);+ },+ });+ actions.value.push(action);+ }+ if (opts.actions.includes("new-chat")) {+ const action1 = editor.addAction({+ id: "new-chat",+ label: "New chat",+ precondition: "bb.ai.selectedContentEmpty",+ contextMenuGroupId: "2_ai_assistant",+ contextMenuOrder: 2,+ run: async () => {+ opts.callback("new-chat", monaco, editor);+ },+ });+ const action2 = editor.addAction({+ id: "new-chat-using-selection",+ label: "New chat using selection",+ precondition: "!bb.ai.selectedContentEmpty",+ contextMenuGroupId: "2_ai_assistant",+ contextMenuOrder: 2,+ run: async () => {+ opts.callback("new-chat", monaco, editor);+ },+ });+ actions.value.push(action1);+ actions.value.push(action2);+ }+ } else {+ // When the language is "javascript" we do not have AI Assistant actions+ }+ });+};diff --git a/frontend/src/plugins/ai/index.ts b/frontend/src/plugins/ai/index.tsindex d4ffae80b2..6311ba7852 100644--- a/frontend/src/plugins/ai/index.ts+++ b/frontend/src/plugins/ai/index.ts@@ -1,4 +1,6 @@import AIChatToSQL from "./components/AIChatToSQL.vue";+import ProvideAIContext from "./components/ProvideAIContext.vue";export * from "./types";-export { AIChatToSQL };+export * from "./components/editor-actions";+export { AIChatToSQL, ProvideAIContext };diff --git a/frontend/src/plugins/ai/logic/index.ts b/frontend/src/plugins/ai/logic/index.tsindex 86795c1120..053b526698 100644--- a/frontend/src/plugins/ai/logic/index.ts+++ b/frontend/src/plugins/ai/logic/index.ts@@ -2,3 +2,4 @@ export * from "./context";export * from "./useChatByTab";export * from "./useDynamicSuggestions";export * from "./utils";+export * from "./prompt";diff --git a/frontend/src/plugins/ai/logic/prompt.ts b/frontend/src/plugins/ai/logic/prompt.tsnew file mode 100644index 0000000000..ef461e407b--- /dev/null+++ b/frontend/src/plugins/ai/logic/prompt.ts@@ -0,0 +1,88 @@+import type { Engine } from "@/types/proto/v1/common";+import type { DatabaseMetadata } from "@/types/proto/v1/database_service";+import { engineNameV1 } from "@/utils";++export const databaseMetadataToText = (+ databaseMetadata: DatabaseMetadata | undefined,+ engine?: Engine+) => {+ const prompts: string[] = [];+ if (engine) {+ if (databaseMetadata) {+ prompts.push(+ `### ${engineNameV1(engine)} tables, with their properties:`+ );+ } else {+ prompts.push(`### ${engineNameV1(engine)} database`);+ }+ } else {+ if (databaseMetadata) {+ prompts.push(`### Giving a database`);+ }+ }+ if (databaseMetadata) {+ databaseMetadata.schemas.forEach((schema) => {+ schema.tables.forEach((table) => {+ const name = schema.name ? `${schema.name}.${table.name}` : table.name;+ const columns = table.columns+ .map((column) => {+ if (column.comment) {+ return `${column.name}(${column.comment})`;+ } else {+ return column.name;+ }+ })+ .join(", ");+ prompts.push(`# ${name}(${columns})`);+ });+ });+ }+ return prompts.join("\n");+};++export const declaration = (+ databaseMetadata?: DatabaseMetadata,+ engine?: Engine+) => {+ const prompts: string[] = [];+ if (engine) {+ prompts.push(`You are a ${engineNameV1(engine)} db and SQL expert.`);+ } else {+ prompts.push(`You are a db and SQL expert.`);+ }+ prompts.push(`When asked for your name, you must respond with "Bytebase".`);+ // prompts.push(`Your responses should be informative and terse.`);+ // prompts.push(+ // "Set the language to the markdown SQL block. e.g, `SELECT * FROM table`."+ // );++ prompts.push(databaseMetadataToText(databaseMetadata, engine));+ prompts.push("Answer the following questions about this schema:");++ return prompts.join("\n");+};++export const findProblems = (statement: string, engine?: Engine) => {+ const prompts: string[] = [];+ prompts.push(+ "Find potential problems in the following SQL code. Explain and try to give the correct statement."+ );+ prompts.push(wrapStatementMarkdown(statement, engine));+ return prompts.join("\n");+};++export const explainCode = (statement: string, engine?: Engine) => {+ const prompts: string[] = [];+ prompts.push("Explain the following SQL code");+ prompts.push(wrapStatementMarkdown(statement, engine));+ return prompts.join("\n");+};++export const wrapStatementMarkdown = (statement: string, engine?: Engine) => {+ let openTag = "```";+ if (engine) {+ openTag += engineNameV1(engine).toLowerCase();+ }+ const closeTag = "```";+ return [openTag, statement, closeTag].join("\n");+};diff --git a/frontend/src/plugins/ai/logic/useChatByTab.ts b/frontend/src/plugins/ai/logic/useChatByTab.tsindex abe36fa0ff..6c82d5f3e0 100644--- a/frontend/src/plugins/ai/logic/useChatByTab.ts+++ b/frontend/src/plugins/ai/logic/useChatByTab.ts@@ -55,8 +55,8 @@ export const useChatByTab = () => {});};-export const useCurrentChat = () => {- const { chat } = useAIContext();+export const useCurrentChat = (context = useAIContext()) => {+ const { chat } = context;const list = computed(() => chat.value.list.value);const ready = computed(() => chat.value.ready.value);const selected = computed({diff --git a/frontend/src/plugins/ai/logic/useDynamicSuggestions.ts b/frontend/src/plugins/ai/logic/useDynamicSuggestions.tsindex c03043368b..d1b0a6706a 100644--- a/frontend/src/plugins/ai/logic/useDynamicSuggestions.ts+++ b/frontend/src/plugins/ai/logic/useDynamicSuggestions.ts@@ -5,7 +5,7 @@ import { hashCode } from "@/bbkit/BBUtil";import { WebStorageHelper } from "@/utils";import type { OpenAIMessage, OpenAIResponse } from "../types";import { useAIContext } from "./context";-import { databaseMetadataToText } from "./utils";+import { databaseMetadataToText } from "./prompt";export type SuggestionContext = {schema: string; // schema textdiff --git a/frontend/src/plugins/ai/logic/utils.ts b/frontend/src/plugins/ai/logic/utils.tsindex d924a1c3a6..d479f35c87 100644--- a/frontend/src/plugins/ai/logic/utils.ts+++ b/frontend/src/plugins/ai/logic/utils.ts@@ -1,9 +1,6 @@import { watch } from "vue";import { useCurrentSQLEditorTab } from "@/store";import type { SQLEditorConnection } from "@/types";-import type { Engine } from "@/types/proto/v1/common";-import type { DatabaseMetadata } from "@/types/proto/v1/database_service";-import { engineNameV1 } from "@/utils";export const onConnectionChanged = (fn: (@@ -29,41 +26,3 @@ export const onConnectionChanged = ({ immediate });};--export const databaseMetadataToText = (- databaseMetadata: DatabaseMetadata | undefined,- engine?: Engine-) => {- const prompts: string[] = [];- if (engine) {- if (databaseMetadata) {- prompts.push(- `### ${engineNameV1(engine)} tables, with their properties:`- );- } else {- prompts.push(`### ${engineNameV1(engine)} database`);- }- } else {- if (databaseMetadata) {- prompts.push(`### Giving a database`);- }- }- if (databaseMetadata) {- databaseMetadata.schemas.forEach((schema) => {- schema.tables.forEach((table) => {- const name = schema.name ? `${schema.name}.${table.name}` : table.name;- const columns = table.columns- .map((column) => {- if (column.comment) {- return `${column.name}(${column.comment})`;- } else {- return column.name;- }- })- .join(", ");- prompts.push(`# ${name}(${columns})`);- });- });- }- return prompts.join("\n");-};diff --git a/frontend/src/plugins/ai/store/conversation.ts b/frontend/src/plugins/ai/store/conversation.tsindex 65212ec434..9f1c004ce9 100644--- a/frontend/src/plugins/ai/store/conversation.ts+++ b/frontend/src/plugins/ai/store/conversation.ts@@ -161,17 +161,35 @@ export const useConversationStore = defineStore("ai-conversation", () => {(m) => m.conversation_id);conversationEntityList.sort((a, b) => a.created_ts - b.created_ts);- const conversationList = conversationEntityList.map<Conversation>((c) => {- const conversation = convertConversation(c);- const messageEntityList = groupByConversationId[c._id] ?? [];- conversation.messageList = messageEntityList.map((m) =>- convertMessage(m, conversation)- );- conversation.messageList.sort((a, b) => a.created_ts - b.created_ts);- return conversation;+ const rawConversationList = conversationEntityList.map<Conversation>(+ (c) => {+ const conversation = convertConversation(c);+ const messageEntityList = groupByConversationId[c._id] ?? [];+ conversation.messageList = messageEntityList.map((m) =>+ convertMessage(m, conversation)+ );+ conversation.messageList.sort((a, b) => a.created_ts - b.created_ts);+ return conversation;+ }+ );+ await fixAbnormalMessages(+ rawConversationList.flatMap((c) => c.messageList)+ );+ // cleanup empty conversations+ const emptyConversationList: Conversation[] = [];+ rawConversationList.forEach((conversation) => {+ if (conversation.messageList.length === 0) {+ emptyConversationList.push(conversation);+ }});- await fixAbnormalMessages(conversationList.flatMap((c) => c.messageList));- return conversationList;+ await Promise.all(+ emptyConversationList.map((conversation) =>+ deleteConversation(conversation.id)+ )+ );+ return rawConversationList.filter(+ (conversation) => conversation.messageList.length > 0+ );};const createConversation = async (diff --git a/frontend/src/plugins/ai/types/context.ts b/frontend/src/plugins/ai/types/context.tsindex 71c753d28a..35109efd74 100644--- a/frontend/src/plugins/ai/types/context.ts+++ b/frontend/src/plugins/ai/types/context.ts@@ -5,9 +5,10 @@ import type { DatabaseMetadata } from "@/types/proto/v1/database_service";import type { Conversation } from "./conversation";export type AIContextEvents = Emittery<{- "apply-statement": { statement: string; run: boolean };+ "run-statement": { statement: string };error: string;- "new-conversation": any;+ "new-conversation": { input: string };+ "send-chat": { content: string; newChat?: boolean };}>;export type AIChatInfo = {@@ -21,10 +22,11 @@ export type AIContext = {openAIEndpoint: Ref<string>;engine: Ref<Engine | undefined>;databaseMetadata: Ref<DatabaseMetadata | undefined>;- autoRun: Ref<boolean>;showHistoryDialog: Ref<boolean>;chat: Ref<AIChatInfo>;+ pendingSendChat: Ref<{ content: string } | undefined>;+ pendingPreInput: Ref<string | undefined>;// Eventsevents: AIContextEvents;diff --git a/frontend/src/plugins/ai/types/index.ts b/frontend/src/plugins/ai/types/index.tsindex c0b5159840..e05e1f4278 100644--- a/frontend/src/plugins/ai/types/index.ts+++ b/frontend/src/plugins/ai/types/index.ts@@ -1,3 +1,5 @@export * from "./context";export * from "./conversation";export * from "./openai";++export type ChatAction = "explain-code" | "find-problems" | "new-chat";diff --git a/frontend/src/types/sqlEditor/tab.ts b/frontend/src/types/sqlEditor/tab.tsindex 767d0566c7..c7020037f6 100644--- a/frontend/src/types/sqlEditor/tab.ts+++ b/frontend/src/types/sqlEditor/tab.ts@@ -5,8 +5,6 @@ import type {import type { SQLResultSetV1 } from "../v1/sql";import type { SQLEditorConnection, SQLEditorQueryParams } from "./editor";-export type SQLEditorEditMode = "SQL-EDITOR" | "CHAT-TO-SQL";-export type SQLEditorTabStatus =| "NEW" // just created and untouched| "DIRTY" // edited@@ -40,7 +38,6 @@ export type SQLEditorTab = {statement: string; // local editing statement, might be out-of-sync to ref sheet's statementselectedStatement: string;mode: SQLEditorTabMode;- editMode: SQLEditorEditMode;// SQL query related fields// won't be saved to localStoragediff --git a/frontend/src/utils/sqlEditor.ts b/frontend/src/utils/sqlEditor.tsindex 9bec12d101..3c8929e517 100644--- a/frontend/src/utils/sqlEditor.ts+++ b/frontend/src/utils/sqlEditor.ts@@ -37,7 +37,6 @@ export const defaultSQLEditorTab = (): SQLEditorTab => {status: "NEW",mode: DEFAULT_SQL_EDITOR_TAB_MODE,worksheet: "",- editMode: "SQL-EDITOR",treeState: {database: UNKNOWN_DATABASE_NAME,keys: [],diff --git a/frontend/src/views/sql-editor/EditorCommon/EditorAction.vue b/frontend/src/views/sql-editor/EditorCommon/EditorAction.vueindex 51cecb3935..900c2bac16 100644--- a/frontend/src/views/sql-editor/EditorCommon/EditorAction.vue+++ b/frontend/src/views/sql-editor/EditorCommon/EditorAction.vue@@ -44,8 +44,6 @@/></NButtonGroup>- <OpenAIButton size="small" />-<NPopover placement="bottom"><template #trigger><AdminModeButton@@ -125,6 +123,11 @@<DatabaseChooser /><SchemaChooser /></NButtonGroup>++ <OpenAIButton+ size="small"+ :statement="currentTab?.selectedStatement || currentTab?.statement"+ /></div></div>@@ -165,7 +168,7 @@ import { useSQLEditorContext } from "../context";import AdminModeButton from "./AdminModeButton.vue";import BatchQueryDatabasesSelector from "./BatchQueryDatabasesSelector.vue";import DatabaseChooser from "./DatabaseChooser.vue";-import OpenAIButton from "./OpenAIButton.vue";+import OpenAIButton from "./OpenAIButton";import QueryContextSettingPopover from "./QueryContextSettingPopover.vue";import SchemaChooser from "./SchemaChooser.vue";import SharePopover from "./SharePopover.vue";diff --git a/frontend/src/views/sql-editor/EditorCommon/OpenAIButton.vue b/frontend/src/views/sql-editor/EditorCommon/OpenAIButton.vuedeleted file mode 100644index 6dcbb32a65..0000000000--- a/frontend/src/views/sql-editor/EditorCommon/OpenAIButton.vue+++ /dev/null@@ -1,79 +0,0 @@-<template>- <NPopover v-if="showButton" placement="bottom">- <template #trigger>- <NButton- :active="showAIChatBox"- v-bind="{- ...buttonProps,- ...$attrs,- }"- style="--n-icon-size: 16px; --n-padding: 0 6px"- @click="showAIChatBox = !showAIChatBox"- >- <template #icon>- <svg- xmlns="http://www.w3.org/2000/svg"- viewBox="0 0 320 320"- fill="currentColor"- stroke="none"- >- <path- xmlns="http://www.w3.org/2000/svg"- d="m297.06 130.97c7.26-21.79 4.76-45.66-6.85-65.48-17.46-30.4-52.56-46.04-86.84-38.68-15.25-17.18-37.16-26.95-60.13-26.81-35.04-.08-66.13 22.48-76.91 55.82-22.51 4.61-41.94 18.7-53.31 38.67-17.59 30.32-13.58 68.54 9.92 94.54-7.26 21.79-4.76 45.66 6.85 65.48 17.46 30.4 52.56 46.04 86.84 38.68 15.24 17.18 37.16 26.95 60.13 26.8 35.06.09 66.16-22.49 76.94-55.86 22.51-4.61 41.94-18.7 53.31-38.67 17.57-30.32 13.55-68.51-9.94-94.51zm-120.28 168.11c-14.03.02-27.62-4.89-38.39-13.88.49-.26 1.34-.73 1.89-1.07l63.72-36.8c3.26-1.85 5.26-5.32 5.24-9.07v-89.83l26.93 15.55c.29.14.48.42.52.74v74.39c-.04 33.08-26.83 59.9-59.91 59.97zm-128.84-55.03c-7.03-12.14-9.56-26.37-7.15-40.18.47.28 1.3.79 1.89 1.13l63.72 36.8c3.23 1.89 7.23 1.89 10.47 0l77.79-44.92v31.1c.02.32-.13.63-.38.83l-64.41 37.19c-28.69 16.52-65.33 6.7-81.92-21.95zm-16.77-139.09c7-12.16 18.05-21.46 31.21-26.29 0 .55-.03 1.52-.03 2.2v73.61c-.02 3.74 1.98 7.21 5.23 9.06l77.79 44.91-26.93 15.55c-.27.18-.61.21-.91.08l-64.42-37.22c-28.63-16.58-38.45-53.21-21.95-81.89zm221.26 51.49-77.79-44.92 26.93-15.54c.27-.18.61-.21.91-.08l64.42 37.19c28.68 16.57 38.51 53.26 21.94 81.94-7.01 12.14-18.05 21.44-31.2 26.28v-75.81c.03-3.74-1.96-7.2-5.2-9.06zm26.8-40.34c-.47-.29-1.3-.79-1.89-1.13l-63.72-36.8c-3.23-1.89-7.23-1.89-10.47 0l-77.79 44.92v-31.1c-.02-.32.13-.63.38-.83l64.41-37.16c28.69-16.55 65.37-6.7 81.91 22 6.99 12.12 9.52 26.31 7.15 40.1zm-168.51 55.43-26.94-15.55c-.29-.14-.48-.42-.52-.74v-74.39c.02-33.12 26.89-59.96 60.01-59.94 14.01 0 27.57 4.92 38.34 13.88-.49.26-1.33.73-1.89 1.07l-63.72 36.8c-3.26 1.85-5.26 5.31-5.24 9.06l-.04 89.79zm14.63-31.54 34.65-20.01 34.65 20v40.01l-34.65 20-34.65-20z"- />- </svg>- </template>- </NButton>- </template>- <template #default>- {{- showAIChatBox- ? $t("plugin.ai.disable-text2sql")- : $t("plugin.ai.enable-text2sql")- }}- </template>- </NPopover>-</template>--<script setup lang="ts">-import { NButton, NPopover, type ButtonProps } from "naive-ui";-import { computed } from "vue";-import { useSettingV1Store, useSQLEditorTabStore } from "@/store";-import { useSQLEditorContext } from "../context";--defineOptions({- inheritAttrs: false,-});--const tabStore = useSQLEditorTabStore();-const settingV1Store = useSettingV1Store();-const openAIKeySetting = computed(() =>- settingV1Store.getSettingByName("bb.plugin.openai.key")-);-const openAIKey = computed(- () => openAIKeySetting.value?.value?.stringValue ?? ""-);--const { showAIChatBox } = useSQLEditorContext();--const showButton = computed(() => {- return (- openAIKey.value &&- !tabStore.isDisconnected &&- tabStore.currentTab?.mode === "WORKSHEET"- );-});--const buttonProps = computed(() => {- const buttonProps: ButtonProps = {- tag: "div",- };- if (showAIChatBox.value) {- buttonProps.ghost = true;- buttonProps.type = "primary";- } else {- buttonProps.type = "default";- }- return buttonProps;-});-</script>diff --git a/frontend/src/views/sql-editor/EditorCommon/OpenAIButton/Button.vue b/frontend/src/views/sql-editor/EditorCommon/OpenAIButton/Button.vuenew file mode 100644index 0000000000..d69c5170a8--- /dev/null+++ b/frontend/src/views/sql-editor/EditorCommon/OpenAIButton/Button.vue@@ -0,0 +1,54 @@+<template>+ <NButton+ tag="div"+ v-bind="{+ ...buttonProps,+ ...$attrs,+ }"+ style="--n-icon-size: 16px; --n-padding: 0 6px"+ @click="$emit('click')"+ >+ <template #icon>+ <svg+ xmlns="http://www.w3.org/2000/svg"+ viewBox="0 0 320 320"+ fill="currentColor"+ stroke="none"+ >+ <path+ xmlns="http://www.w3.org/2000/svg"+ d="m297.06 130.97c7.26-21.79 4.76-45.66-6.85-65.48-17.46-30.4-52.56-46.04-86.84-38.68-15.25-17.18-37.16-26.95-60.13-26.81-35.04-.08-66.13 22.48-76.91 55.82-22.51 4.61-41.94 18.7-53.31 38.67-17.59 30.32-13.58 68.54 9.92 94.54-7.26 21.79-4.76 45.66 6.85 65.48 17.46 30.4 52.56 46.04 86.84 38.68 15.24 17.18 37.16 26.95 60.13 26.8 35.06.09 66.16-22.49 76.94-55.86 22.51-4.61 41.94-18.7 53.31-38.67 17.57-30.32 13.55-68.51-9.94-94.51zm-120.28 168.11c-14.03.02-27.62-4.89-38.39-13.88.49-.26 1.34-.73 1.89-1.07l63.72-36.8c3.26-1.85 5.26-5.32 5.24-9.07v-89.83l26.93 15.55c.29.14.48.42.52.74v74.39c-.04 33.08-26.83 59.9-59.91 59.97zm-128.84-55.03c-7.03-12.14-9.56-26.37-7.15-40.18.47.28 1.3.79 1.89 1.13l63.72 36.8c3.23 1.89 7.23 1.89 10.47 0l77.79-44.92v31.1c.02.32-.13.63-.38.83l-64.41 37.19c-28.69 16.52-65.33 6.7-81.92-21.95zm-16.77-139.09c7-12.16 18.05-21.46 31.21-26.29 0 .55-.03 1.52-.03 2.2v73.61c-.02 3.74 1.98 7.21 5.23 9.06l77.79 44.91-26.93 15.55c-.27.18-.61.21-.91.08l-64.42-37.22c-28.63-16.58-38.45-53.21-21.95-81.89zm221.26 51.49-77.79-44.92 26.93-15.54c.27-.18.61-.21.91-.08l64.42 37.19c28.68 16.57 38.51 53.26 21.94 81.94-7.01 12.14-18.05 21.44-31.2 26.28v-75.81c.03-3.74-1.96-7.2-5.2-9.06zm26.8-40.34c-.47-.29-1.3-.79-1.89-1.13l-63.72-36.8c-3.23-1.89-7.23-1.89-10.47 0l-77.79 44.92v-31.1c-.02-.32.13-.63.38-.83l64.41-37.16c28.69-16.55 65.37-6.7 81.91 22 6.99 12.12 9.52 26.31 7.15 40.1zm-168.51 55.43-26.94-15.55c-.29-.14-.48-.42-.52-.74v-74.39c.02-33.12 26.89-59.96 60.01-59.94 14.01 0 27.57 4.92 38.34 13.88-.49.26-1.33.73-1.89 1.07l-63.72 36.8c-3.26 1.85-5.26 5.31-5.24 9.06l-.04 89.79zm14.63-31.54 34.65-20.01 34.65 20v40.01l-34.65 20-34.65-20z"+ />+ </svg>+ </template>+ </NButton>+</template>++<script setup lang="ts">+import { NButton, type ButtonProps } from "naive-ui";+import { computed } from "vue";+import { useSQLEditorContext } from "../../context";++defineOptions({+ inheritAttrs: false,+});++defineEmits<{+ (event: "click"): void;+}>();++const { showAIPanel } = useSQLEditorContext();++const buttonProps = computed(() => {+ const buttonProps: ButtonProps = {+ tag: "div",+ };+ if (showAIPanel.value) {+ buttonProps.type = "primary";+ buttonProps.secondary = true;+ } else {+ buttonProps.type = "default";+ }+ return buttonProps;+});+</script>diff --git a/frontend/src/views/sql-editor/EditorCommon/OpenAIButton/OpenAIButton.vue b/frontend/src/views/sql-editor/EditorCommon/OpenAIButton/OpenAIButton.vuenew file mode 100644index 0000000000..1610c06236--- /dev/null+++ b/frontend/src/views/sql-editor/EditorCommon/OpenAIButton/OpenAIButton.vue@@ -0,0 +1,174 @@+<template>+ <template v-if="showButton">+ <template v-if="enabled">+ <NPopselect+ v-if="options.length > 0"+ placement="bottom-end"+ :options="options"+ @update:value="handleSelect"+ >+ <Button v-bind="$attrs" @click="handleClickButton" />+ <template #header>+ <span class="font-semibold">{{ $t("plugin.ai.ai-assistant") }}</span>+ </template>+ </NPopselect>+ <Button v-else v-bind="$attrs" @click="handleClickButton" />+ </template>+ <NPopover v-if="!enabled" placement="bottom-end">+ <template #trigger>+ <Button v-bind="$attrs" :disabled="true" />+ </template>+ <template #default>+ <div class="flex flex-col">+ <div class="pb-1 border-b">+ <span class="font-semibold">+ {{ $t("plugin.ai.ai-assistant") }}+ </span>+ </div>+ <div class="pt-2 max-w-[20rem] flex flex-col text-gray-500">+ <p>+ {{ $t("plugin.ai.not-configured.self") }}+ <NButton+ v-if="allowConfigure"+ size="small"+ text+ type="primary"+ class="inline-block"+ @click="goConfigure"+ >+ {{ $t("plugin.ai.not-configured.go-to-configure") }}+ </NButton>+ <template v-else>+ {{ $t("plugin.ai.not-configured.contact-admin-to-configure") }}+ </template>+ </p>+ </div>+ </div>+ </template>+ </NPopover>+ </template>+</template>++<script setup lang="ts">+import { NPopselect, NPopover, type SelectOption, NButton } from "naive-ui";+import { computed } from "vue";+import { useI18n } from "vue-i18n";+import { useRouter } from "vue-router";+import type { ChatAction } from "@/plugins/ai";+import { useAIContext } from "@/plugins/ai/logic";+import * as promptUtils from "@/plugins/ai/logic/prompt";+import { SETTING_ROUTE_WORKSPACE_GENERAL } from "@/router/dashboard/workspaceSetting";+import { SQL_EDITOR_SETTING_GENERAL_MODULE } from "@/router/sqlEditor";+import {+ useAppFeature,+ useConnectionOfCurrentSQLEditorTab,+ useSettingV1Store,+ useSQLEditorTabStore,+} from "@/store";+import { DatabaseChangeMode } from "@/types/proto/v1/setting_service";+import { hasWorkspacePermissionV2, nextAnimationFrame } from "@/utils";+import { useSQLEditorContext } from "../../context";+import Button from "./Button.vue";++defineOptions({+ inheritAttrs: false,+});++const props = defineProps<{+ actions?: ChatAction[];+ statement?: string;+}>();++const { t } = useI18n();+const router = useRouter();+const tabStore = useSQLEditorTabStore();+const settingV1Store = useSettingV1Store();+const databaseChangeMode = useAppFeature("bb.feature.database-change-mode");++const openAIKeySetting = computed(() =>+ settingV1Store.getSettingByName("bb.plugin.openai.key")+);+const openAIKey = computed(+ () => openAIKeySetting.value?.value?.stringValue ?? ""+);++const { showAIPanel } = useSQLEditorContext();+const { instance } = useConnectionOfCurrentSQLEditorTab();+const { events } = useAIContext();++const options = computed(() => {+ const { statement } = props;+ const options: (SelectOption & { value: ChatAction })[] = [+ {+ value: "explain-code",+ label: t("plugin.ai.actions.explain-code"),+ disabled: !statement,+ },+ {+ value: "find-problems",+ label: t("plugin.ai.actions.find-problems"),+ disabled: !statement,+ },+ { value: "new-chat", label: t("plugin.ai.actions.new-chat") },+ ];+ return options.filter((opt) => {+ if (props.actions && !props.actions.includes(opt.value)) return false;+ return true;+ });+});++const showButton = computed(() => {+ return !tabStore.isDisconnected && tabStore.currentTab?.mode === "WORKSHEET";+});++const enabled = computed(() => {+ return openAIKey.value;+});++const allowConfigure = computed((): boolean => {+ return hasWorkspacePermissionV2("bb.settings.set");+});++const handleSelect = async (action: ChatAction) => {+ // start new chat if AI panel is not open+ // continue current chat otherwise+ const newChat = !showAIPanel.value;++ showAIPanel.value = true;+ if (action === "explain-code" || action === "find-problems") {+ const { statement } = props;+ if (!statement) return;++ await nextAnimationFrame();+ if (action === "explain-code") {+ events.emit("send-chat", {+ content: promptUtils.explainCode(statement, instance.value.engine),+ newChat,+ });+ }+ if (action === "find-problems") {+ events.emit("send-chat", {+ content: promptUtils.findProblems(statement, instance.value.engine),+ newChat,+ });+ }+ }+ if (action === "new-chat") {+ events.emit("new-conversation", { input: "" });+ }+};++const handleClickButton = () => {+ showAIPanel.value = true;+};++const goConfigure = () => {+ router.push({+ name:+ databaseChangeMode.value === DatabaseChangeMode.EDITOR+ ? SQL_EDITOR_SETTING_GENERAL_MODULE+ : SETTING_ROUTE_WORKSPACE_GENERAL,+ hash: "#ai-assistant",+ });+};+</script>diff --git a/frontend/src/views/sql-editor/EditorCommon/OpenAIButton/index.ts b/frontend/src/views/sql-editor/EditorCommon/OpenAIButton/index.tsnew file mode 100644index 0000000000..f03377592e--- /dev/null+++ b/frontend/src/views/sql-editor/EditorCommon/OpenAIButton/index.ts@@ -0,0 +1,3 @@+import OpenAIButton from "./OpenAIButton.vue";++export default OpenAIButton;diff --git a/frontend/src/views/sql-editor/EditorCommon/index.ts b/frontend/src/views/sql-editor/EditorCommon/index.tsindex 69e9fbcc61..81061c049f 100644--- a/frontend/src/views/sql-editor/EditorCommon/index.ts+++ b/frontend/src/views/sql-editor/EditorCommon/index.ts@@ -3,6 +3,7 @@ import ConnectionPathBar from "./ConnectionPathBar.vue";import DisconnectedIcon from "./DisconnectedIcon.vue";import EditorAction from "./EditorAction.vue";import ExecutingHintModal from "./ExecutingHintModal.vue";+import OpenAIButton from "./OpenAIButton/OpenAIButton.vue";import { ResultViewV1 } from "./ResultView";import SaveSheetModal from "./SaveSheetModal.vue";import SharePopover from "./SharePopover.vue";@@ -18,6 +19,7 @@ export {ResultViewV1,DisconnectedIcon,SheetConnectionIcon,+ OpenAIButton,};export * from "./hover-state";diff --git a/frontend/src/views/sql-editor/EditorPanel/Panels/FunctionsPanel/FunctionsPanel.vue b/frontend/src/views/sql-editor/EditorPanel/Panels/FunctionsPanel/FunctionsPanel.vueindex d64d0217d5..4c9a13d14a 100644--- a/frontend/src/views/sql-editor/EditorPanel/Panels/FunctionsPanel/FunctionsPanel.vue+++ b/frontend/src/views/sql-editor/EditorPanel/Panels/FunctionsPanel/FunctionsPanel.vue@@ -1,11 +1,11 @@<template><divv-if="metadata?.schema"- class="px-2 py-2 gap-y-2 h-full overflow-hidden flex flex-col"+ class="h-full overflow-hidden flex flex-col"><divv-show="!metadata.func"- class="w-full flex flex-row gap-x-2 justify-between items-center"+ class="w-full h-[44px] py-2 px-2 border-b flex flex-row gap-x-2 justify-between items-center"><div class="flex items-center justify-start gap-2"><DatabaseChooser />diff --git a/frontend/src/views/sql-editor/EditorPanel/Panels/FunctionsPanel/FunctionsTable.vue b/frontend/src/views/sql-editor/EditorPanel/Panels/FunctionsPanel/FunctionsTable.vueindex 682658ccf2..54400d33eb 100644--- a/frontend/src/views/sql-editor/EditorPanel/Panels/FunctionsPanel/FunctionsTable.vue+++ b/frontend/src/views/sql-editor/EditorPanel/Panels/FunctionsPanel/FunctionsTable.vue@@ -1,5 +1,5 @@<template>- <div ref="containerElRef" class="w-full h-full overflow-x-auto">+ <div ref="containerElRef" class="w-full h-full px-2 py-2 overflow-x-auto"><NDataTablev-bind="$attrs"ref="dataTableRef"diff --git a/frontend/src/views/sql-editor/EditorPanel/Panels/Panels.vue b/frontend/src/views/sql-editor/EditorPanel/Panels/Panels.vueindex 5f9e75285c..6916a213f7 100644--- a/frontend/src/views/sql-editor/EditorPanel/Panels/Panels.vue+++ b/frontend/src/views/sql-editor/EditorPanel/Panels/Panels.vue@@ -29,14 +29,22 @@ import { computedAsync } from "@vueuse/core";import { first } from "lodash-es";import { storeToRefs } from "pinia";import { watch } from "vue";+import { useEmitteryEventListener } from "@/composables/useEmitteryEventListener";+import { useExecuteSQL } from "@/composables/useExecuteSQL";+import { useAIContext } from "@/plugins/ai/logic";import {useConnectionOfCurrentSQLEditorTab,+ useDatabaseV1Store,useDBSchemaV1Store,useSQLEditorTabStore,} from "@/store";import { isValidDatabaseName } from "@/types";import { DatabaseMetadataView } from "@/types/proto/v1/database_service";-import { extractDatabaseResourceName, type VueClass } from "@/utils";+import {+ extractDatabaseResourceName,+ nextAnimationFrame,+ type VueClass,+} from "@/utils";import GutterBar from "../GutterBar";import { useEditorPanelContext } from "../context";import DiagramPanel from "./DiagramPanel";@@ -53,8 +61,11 @@ defineProps<{}>();const { currentTab: tab } = storeToRefs(useSQLEditorTabStore());-const { viewState, selectedSchemaName } = useEditorPanelContext();+const { viewState, selectedSchemaName, updateViewState } =+ useEditorPanelContext();const { database } = useConnectionOfCurrentSQLEditorTab();+const { execute } = useExecuteSQL();+const { events: AIEvents } = useAIContext();const databaseMetadata = computedAsync(() => {if (!isValidDatabaseName(database.value.name)) {return undefined;@@ -82,4 +93,23 @@ watch(},{ immediate: true, flush: "post" });++useEmitteryEventListener(AIEvents, "run-statement", async ({ statement }) => {+ if (!tab.value) {+ return;+ }+ updateViewState({+ view: "CODE",+ });+ await nextAnimationFrame();+ const connection = tab.value.connection;+ const database = useDatabaseV1Store().getDatabaseByName(connection.database);+ execute({+ connection,+ statement,+ engine: database.instanceResource.engine,+ explain: false,+ selection: tab.value.editorState.selection,+ });+});</script>diff --git a/frontend/src/views/sql-editor/EditorPanel/Panels/ProceduresPanel/ProceduresPanel.vue b/frontend/src/views/sql-editor/EditorPanel/Panels/ProceduresPanel/ProceduresPanel.vueindex 3546320901..35ca45f3a9 100644--- a/frontend/src/views/sql-editor/EditorPanel/Panels/ProceduresPanel/ProceduresPanel.vue+++ b/frontend/src/views/sql-editor/EditorPanel/Panels/ProceduresPanel/ProceduresPanel.vue@@ -1,11 +1,8 @@<template>- <div- v-if="metadata?.schema"- class="px-2 py-2 gap-y-2 h-full overflow-hidden flex flex-col"- >+ <div v-if="metadata?.schema" class="h-full overflow-hidden flex flex-col"><divv-show="!metadata.procedure"- class="w-full flex flex-row gap-x-2 justify-between items-center"+ class="w-full h-[44px] py-2 px-2 border-b flex flex-row gap-x-2 justify-between items-center"><div class="flex items-center justify-start gap-2"><DatabaseChooser />diff --git a/frontend/src/views/sql-editor/EditorPanel/Panels/ProceduresPanel/ProceduresTable.vue b/frontend/src/views/sql-editor/EditorPanel/Panels/ProceduresPanel/ProceduresTable.vueindex b6c209d479..d47f0bf374 100644--- a/frontend/src/views/sql-editor/EditorPanel/Panels/ProceduresPanel/ProceduresTable.vue+++ b/frontend/src/views/sql-editor/EditorPanel/Panels/ProceduresPanel/ProceduresTable.vue@@ -1,5 +1,5 @@<template>- <div ref="containerElRef" class="w-full h-full overflow-x-auto">+ <div ref="containerElRef" class="w-full h-full px-2 py-2 overflow-x-auto"><NDataTablev-bind="$attrs"ref="dataTableRef"diff --git a/frontend/src/views/sql-editor/EditorPanel/Panels/ViewsPanel/ColumnsTable.vue b/frontend/src/views/sql-editor/EditorPanel/Panels/ViewsPanel/ColumnsTable.vueindex d5a32f8c64..0c8b7edb9b 100644--- a/frontend/src/views/sql-editor/EditorPanel/Panels/ViewsPanel/ColumnsTable.vue+++ b/frontend/src/views/sql-editor/EditorPanel/Panels/ViewsPanel/ColumnsTable.vue@@ -1,5 +1,5 @@<template>- <div ref="containerElRef" class="w-full h-full overflow-x-auto">+ <div ref="containerElRef" class="w-full h-full px-2 py-2 overflow-x-auto"><NDataTablev-bind="$attrs"ref="dataTableRef"diff --git a/frontend/src/views/sql-editor/EditorPanel/Panels/ViewsPanel/DefinitionViewer.vue b/frontend/src/views/sql-editor/EditorPanel/Panels/ViewsPanel/DefinitionViewer.vueindex 9460ac186d..032da69009 100644--- a/frontend/src/views/sql-editor/EditorPanel/Panels/ViewsPanel/DefinitionViewer.vue+++ b/frontend/src/views/sql-editor/EditorPanel/Panels/ViewsPanel/DefinitionViewer.vue@@ -1,16 +1,48 @@<template>- <div class="border w-full rounded flex-1 relative">- <MonacoEditor :content="content" :readonly="true" class="w-full h-full relative" />- </div>+ <Splitpanes+ class="default-theme flex flex-row items-stretch flex-1 w-full overflow-hidden"+ >+ <Pane>+ <MonacoEditor+ :content="content"+ :readonly="true"+ class="w-full h-full relative"+ @ready="handleEditorReady"+ />+ </Pane>+ <Pane v-if="showAIPanel" :size="30" class="overflow-hidden flex flex-col">+ <Suspense>+ <AIChatToSQL />+ <template #fallback>+ <div+ class="w-full h-full flex-grow flex flex-col items-center justify-center"+ >+ <BBSpin />+ </div>+ </template>+ </Suspense>+ </Pane>+ </Splitpanes></template><script setup lang="ts">import { computedAsync } from "@vueuse/core";+import { Pane, Splitpanes } from "splitpanes";import { computed } from "vue";-import { MonacoEditor } from "@/components/MonacoEditor";+import { BBSpin } from "@/bbkit";+import {+ MonacoEditor,+ type IStandaloneCodeEditor,+ type MonacoModule,+} from "@/components/MonacoEditor";import formatSQL from "@/components/MonacoEditor/sqlFormatter";+import { AIChatToSQL, useAIActions } from "@/plugins/ai";+import { useAIContext } from "@/plugins/ai/logic";+import * as promptUtils from "@/plugins/ai/logic/prompt";import type { ComposedDatabase } from "@/types";import { dialectOfEngineV1 } from "@/types";+import { nextAnimationFrame } from "@/utils";+import { useSQLEditorContext } from "@/views/sql-editor/context";const props = defineProps<{db: ComposedDatabase;@@ -22,7 +54,9 @@ defineEmits<{(event: "back"): void;}>();+const { showAIPanel } = useSQLEditorContext();const instanceEngine = computed(() => props.db.instanceResource.engine);+const AIContext = useAIContext();const formatted = computedAsync(async () => {@@ -51,4 +85,30 @@ const content = computed(() => {? formatted.value.data: props.code;});++const handleEditorReady = (+ monaco: MonacoModule,+ editor: IStandaloneCodeEditor+) => {+ useAIActions(monaco, editor, AIContext, {+ actions: ["explain-code"],+ callback: async (action) => {+ // start new chat if AI panel is not open+ // continue current chat otherwise+ const newChat = !showAIPanel.value;++ showAIPanel.value = true;+ if (action !== "explain-code") return;++ await nextAnimationFrame();+ AIContext.events.emit("send-chat", {+ content: promptUtils.explainCode(+ props.code,+ props.db.instanceResource.engine+ ),+ newChat,+ });+ },+ });+};</script>diff --git a/frontend/src/views/sql-editor/EditorPanel/Panels/ViewsPanel/DependentColumnsTable.vue b/frontend/src/views/sql-editor/EditorPanel/Panels/ViewsPanel/DependentColumnsTable.vueindex 4331f5a2af..f12c344ad4 100644--- a/frontend/src/views/sql-editor/EditorPanel/Panels/ViewsPanel/DependentColumnsTable.vue+++ b/frontend/src/views/sql-editor/EditorPanel/Panels/ViewsPanel/DependentColumnsTable.vue@@ -1,5 +1,5 @@<template>- <div ref="containerElRef" class="w-full h-full overflow-x-auto">+ <div ref="containerElRef" class="w-full h-full px-2 py-2 overflow-x-auto"><NDataTablev-bind="$attrs"ref="dataTableRef"diff --git a/frontend/src/views/sql-editor/EditorPanel/Panels/ViewsPanel/ViewDetail.vue b/frontend/src/views/sql-editor/EditorPanel/Panels/ViewsPanel/ViewDetail.vueindex e72ee72858..662d6aa876 100644--- a/frontend/src/views/sql-editor/EditorPanel/Panels/ViewsPanel/ViewDetail.vue+++ b/frontend/src/views/sql-editor/EditorPanel/Panels/ViewsPanel/ViewDetail.vue@@ -1,6 +1,6 @@<template><div- class="w-full h-[28px] flex flex-row gap-x-2 justify-between items-center"+ class="w-full h-[44px] px-2 py-2 border-b flex flex-row justify-between items-center"><NTabsv-model:value="state.mode"@@ -32,9 +32,19 @@style="width: 10rem"/>- <NCheckbox v-if="state.mode === 'DEFINITION'" v-model:checked="format">- {{ $t("sql-editor.format") }}- </NCheckbox>+ <div v-if="state.mode === 'DEFINITION'" class="flex items-center gap-2">+ <NCheckbox+ v-if="state.mode === 'DEFINITION'"+ v-model:checked="format"+ >+ {{ $t("sql-editor.format") }}+ </NCheckbox>+ <OpenAIButton+ size="small"+ :statement="view.definition"+ :actions="['explain-code']"+ />+ </div></template></NTabs></div>@@ -76,6 +86,7 @@ import type {SchemaMetadata,ViewMetadata,} from "@/types/proto/v1/database_service";+import { OpenAIButton } from "@/views/sql-editor/EditorCommon";import { useEditorPanelContext } from "../../context";import ColumnsTable from "./ColumnsTable.vue";import DefinitionViewer from "./DefinitionViewer.vue";diff --git a/frontend/src/views/sql-editor/EditorPanel/Panels/ViewsPanel/ViewsPanel.vue b/frontend/src/views/sql-editor/EditorPanel/Panels/ViewsPanel/ViewsPanel.vueindex 2dfebaaee0..86f9045026 100644--- a/frontend/src/views/sql-editor/EditorPanel/Panels/ViewsPanel/ViewsPanel.vue+++ b/frontend/src/views/sql-editor/EditorPanel/Panels/ViewsPanel/ViewsPanel.vue@@ -1,11 +1,11 @@<template><divv-if="metadata?.schema"- class="px-2 py-2 gap-y-2 h-full overflow-hidden flex flex-col"+ class="h-full overflow-hidden flex flex-col"><divv-show="!metadata.view"- class="w-full flex flex-row gap-x-2 justify-between items-center"+ class="w-full h-[44px] py-2 px-2 border-b flex flex-row gap-x-2 justify-between items-center"><div class="flex items-center justify-start gap-2"><DatabaseChooser />diff --git a/frontend/src/views/sql-editor/EditorPanel/Panels/ViewsPanel/ViewsTable.vue b/frontend/src/views/sql-editor/EditorPanel/Panels/ViewsPanel/ViewsTable.vueindex 339c3c058e..878e661ce9 100644--- a/frontend/src/views/sql-editor/EditorPanel/Panels/ViewsPanel/ViewsTable.vue+++ b/frontend/src/views/sql-editor/EditorPanel/Panels/ViewsPanel/ViewsTable.vue@@ -1,5 +1,5 @@<template>- <div ref="containerElRef" class="w-full h-full overflow-x-auto">+ <div ref="containerElRef" class="w-full h-full px-2 py-2 overflow-x-auto"><NDataTablev-bind="$attrs"ref="dataTableRef"diff --git a/frontend/src/views/sql-editor/EditorPanel/Panels/common/CodeViewer.vue b/frontend/src/views/sql-editor/EditorPanel/Panels/common/CodeViewer.vueindex c633bcfe75..fcc72b258e 100644--- a/frontend/src/views/sql-editor/EditorPanel/Panels/common/CodeViewer.vue+++ b/frontend/src/views/sql-editor/EditorPanel/Panels/common/CodeViewer.vue@@ -1,33 +1,79 @@<template>- <div class="w-full h-[28px] flex flex-row gap-4 justify-between items-center">- <NButton text @click="$emit('back')">- <ChevronLeftIcon class="w-5 h-5" />- <div class="flex items-center gap-1">- <slot name="title-icon" />- <span>{{ title }}</span>- </div>- </NButton>- <NCheckbox v-model:checked="format">- {{ $t("sql-editor.format") }}- </NCheckbox>+ <div+ class="w-full h-[44px] px-2 py-2 border-b flex flex-row justify-between items-center"+ >+ <div class="flex justify-start items-center gap-2">+ <NButton text @click="$emit('back')">+ <ChevronLeftIcon class="w-5 h-5" />+ <div class="flex items-center gap-1">+ <slot name="title-icon" />+ <span>{{ title }}</span>+ </div>+ </NButton>+ </div>+ <div class="flex justify-end items-center gap-2">+ <NCheckbox v-model:checked="format">+ {{ $t("sql-editor.format") }}+ </NCheckbox>+ <OpenAIButton+ size="small"+ :statement="code"+ :actions="['explain-code']"+ />+ </div></div>- <MonacoEditor- :content="content"- :readonly="true"- class="border w-full rounded flex-1 relative"- />+ <Splitpanes+ class="default-theme flex flex-row items-stretch flex-1 w-full overflow-hidden"+ >+ <Pane>+ <MonacoEditor+ :content="content"+ :readonly="true"+ :format-content-options="{+ disabled: format,+ callback: handleFormatContent,+ }"+ class="w-full h-full relative"+ @ready="handleEditorReady"+ />+ </Pane>+ <Pane v-if="showAIPanel" :size="30" class="overflow-hidden flex flex-col">+ <Suspense>+ <AIChatToSQL />+ <template #fallback>+ <div+ class="w-full h-full flex-grow flex flex-col items-center justify-center"+ >+ <BBSpin />+ </div>+ </template>+ </Suspense>+ </Pane>+ </Splitpanes></template><script setup lang="ts">import { computedAsync, useLocalStorage } from "@vueuse/core";import { ChevronLeftIcon } from "lucide-vue-next";import { NButton, NCheckbox } from "naive-ui";+import { Pane, Splitpanes } from "splitpanes";import { computed } from "vue";-import { MonacoEditor } from "@/components/MonacoEditor";+import { BBSpin } from "@/bbkit";+import {+ MonacoEditor,+ type IStandaloneCodeEditor,+ type MonacoModule,+} from "@/components/MonacoEditor";import formatSQL from "@/components/MonacoEditor/sqlFormatter";+import { AIChatToSQL, useAIActions } from "@/plugins/ai";+import { useAIContext } from "@/plugins/ai/logic";+import * as promptUtils from "@/plugins/ai/logic/prompt";import type { ComposedDatabase } from "@/types";import { dialectOfEngineV1 } from "@/types";+import { nextAnimationFrame } from "@/utils";+import { OpenAIButton } from "@/views/sql-editor/EditorCommon";+import { useSQLEditorContext } from "@/views/sql-editor/context";const props = defineProps<{db: ComposedDatabase;@@ -39,6 +85,8 @@ defineEmits<{(event: "back"): void;}>();+const { showAIPanel } = useSQLEditorContext();+const AIContext = useAIContext();const format = useLocalStorage<boolean>("bb.sql-editor.editor-panel.code-viewer.format",false@@ -72,4 +120,34 @@ const content = computed(() => {? formatted.value.data: props.code;});++const handleFormatContent = () => {+ format.value = true;+};++const handleEditorReady = (+ monaco: MonacoModule,+ editor: IStandaloneCodeEditor+) => {+ useAIActions(monaco, editor, AIContext, {+ actions: ["explain-code"],+ callback: async (action) => {+ // start new chat if AI panel is not open+ // continue current chat otherwise+ const newChat = !showAIPanel.value;++ showAIPanel.value = true;+ if (action !== "explain-code") return;++ await nextAnimationFrame();+ AIContext.events.emit("send-chat", {+ content: promptUtils.explainCode(+ props.code,+ props.db.instanceResource.engine+ ),+ newChat,+ });+ },+ });+};</script>diff --git a/frontend/src/views/sql-editor/EditorPanel/StandardPanel/SQLEditor.vue b/frontend/src/views/sql-editor/EditorPanel/StandardPanel/SQLEditor.vueindex 47ed3cf4f4..ba9277df5e 100644--- a/frontend/src/views/sql-editor/EditorPanel/StandardPanel/SQLEditor.vue+++ b/frontend/src/views/sql-editor/EditorPanel/StandardPanel/SQLEditor.vue@@ -1,6 +1,6 @@<template><div- class="w-full h-auto flex-grow flex flex-col justify-start items-start overflow-auto"+ class="w-full h-full flex-grow flex flex-col justify-start items-start overflow-auto"><MonacoEditorclass="w-full h-full"@@ -28,6 +28,7 @@import { storeToRefs } from "pinia";import { v1 as uuidv1 } from "uuid";import { computed, nextTick, ref, watch } from "vue";+import { useI18n } from "vue-i18n";import type {AdviceOption,IStandaloneCodeEditor,@@ -42,6 +43,9 @@ import {} from "@/components/MonacoEditor/utils";import { useEmitteryEventListener } from "@/composables/useEmitteryEventListener";import { useExecuteSQL } from "@/composables/useExecuteSQL";+import { useAIActions } from "@/plugins/ai";+import { useAIContext } from "@/plugins/ai/logic";+import * as promptUtils from "@/plugins/ai/logic/prompt";import {useUIStateStore,useWorkSheetAndTabStore,@@ -51,18 +55,20 @@ import {import type { SQLDialect, SQLEditorQueryParams, SQLEditorTab } from "@/types";import { dialectOfEngineV1 } from "@/types";import { Advice_Status, type Advice } from "@/types/proto/v1/sql_service";-import { useInstanceV1EditorLanguage } from "@/utils";+import { nextAnimationFrame, useInstanceV1EditorLanguage } from "@/utils";import { useSQLEditorContext } from "../../context";const emit = defineEmits<{(e: "execute", params: SQLEditorQueryParams): void;}>();+const { t } = useI18n();const tabStore = useSQLEditorTabStore();const sheetAndTabStore = useWorkSheetAndTabStore();const uiStateStore = useUIStateStore();-const { events: editorEvents } = useSQLEditorContext();+const { showAIPanel, events: editorEvents } = useSQLEditorContext();const { currentTab, isSwitchingTab } = storeToRefs(tabStore);+const AIContext = useAIContext();const pendingFormatContentCommand = ref(false);const pendingSetSelectionCommand = ref<{start: { line: number; column: number };@@ -184,6 +190,44 @@ const handleEditorReady = (editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyS, () => {handleSaveSheet();});+ useAIActions(monaco, editor, AIContext, {+ actions: ["explain-code", "find-problems", "new-chat"],+ callback: async (action) => {+ // start new chat if AI panel is not open+ // continue current chat otherwise+ const newChat = !showAIPanel.value;++ showAIPanel.value = true;+ const tab = tabStore.currentTab;+ const statement = tab?.selectedStatement || tab?.statement;+ if (!statement) return;++ await nextAnimationFrame();+ if (action === "explain-code") {+ AIContext.events.emit("send-chat", {+ content: promptUtils.explainCode(statement, instance.value.engine),+ newChat,+ });+ }+ if (action === "find-problems") {+ AIContext.events.emit("send-chat", {+ content: promptUtils.findProblems(statement, instance.value.engine),+ newChat,+ });+ }+ if (action === "new-chat") {+ const statement = tab?.selectedStatement ?? "";+ const inputs: string[] = [];+ if (statement) {+ inputs.push(`// ${t("plugin.ai.text-to-sql-placeholder")}`);+ inputs.push(promptUtils.wrapStatementMarkdown(statement));+ }+ AIContext.events.emit("new-conversation", {+ input: inputs.join("\n"),+ });+ }+ },+ });watch(pendingFormatContentCommand,diff --git a/frontend/src/views/sql-editor/EditorPanel/StandardPanel/StandardPanel.vue b/frontend/src/views/sql-editor/EditorPanel/StandardPanel/StandardPanel.vueindex 4604c508a2..44aaed6aab 100644--- a/frontend/src/views/sql-editor/EditorPanel/StandardPanel/StandardPanel.vue+++ b/frontend/src/views/sql-editor/EditorPanel/StandardPanel/StandardPanel.vue@@ -2,47 +2,51 @@<Splitpanesv-if="!tab || tab.mode === 'WORKSHEET'"horizontal- class="default-theme"+ class="default-theme overflow-hidden":dbl-click-splitter="false">- <Pane class="flex flex-col overflow-hidden">- <div- v-if="isDisconnected || allowReadonlyMode"- class="flex-1 h-full w-full flex flex-col justify-start items-stretch"- >- <template v-if="!tab || tab.editMode === 'SQL-EDITOR'">- <EditorAction @execute="handleExecute" />- <div- v-if="tab"- class="w-full flex-1 flex flex-row items-stretch overflow-hidden"- >+ <Pane class="flex flex-col overflow-hidden justify-start items-stretch">+ <template v-if="isDisconnected || allowReadonlyMode">+ <EditorAction @execute="handleExecute" />++ <Splitpanes v-if="tab" class="default-theme overflow-hidden">+ <Pane><Suspense><SQLEditor @execute="handleExecute" /><template #fallback><div- class="w-full h-auto flex-grow flex flex-col items-center justify-center"+ class="w-full h-full flex-grow flex flex-col items-center justify-center"+ >+ <BBSpin />+ </div>+ </template>+ </Suspense>+ </Pane>+ <Pane+ v-if="showAIPanel"+ :size="33"+ class="overflow-hidden flex flex-col"+ >+ <Suspense>+ <AIChatToSQL />+ <template #fallback>+ <div+ class="w-full h-full flex-grow flex flex-col items-center justify-center"><BBSpin /></div></template></Suspense>- </div>- <template v-else>- <Welcome />- </template>+ </Pane>+ </Splitpanes>+ <template v-else>+ <Welcome /></template>- <Suspense>- <AIChatToSQL- v-if="tab && !isDisconnected && showAIChatBox"- @apply-statement="handleApplyStatement"- />- </Suspense>-<ExecutingHintModal /><SaveSheetModal />- </div>+ </template><ReadonlyModeNotSupported v-else /></Pane>@@ -65,11 +69,10 @@ import { useExecuteSQL } from "@/composables/useExecuteSQL";import { AIChatToSQL } from "@/plugins/ai";import {useConnectionOfCurrentSQLEditorTab,- useDatabaseV1Store,useSQLEditorTabStore,} from "@/store";-import type { SQLEditorConnection, SQLEditorQueryParams } from "@/types";-import { instanceV1HasReadonlyMode, nextAnimationFrame } from "@/utils";+import type { SQLEditorQueryParams } from "@/types";+import { instanceV1HasReadonlyMode } from "@/utils";import {EditorAction,ExecutingHintModal,@@ -84,8 +87,8 @@ const SQLEditor = defineAsyncComponent(() => import("./SQLEditor.vue"));const tabStore = useSQLEditorTabStore();const { currentTab: tab, isDisconnected } = storeToRefs(tabStore);-const { showAIChatBox } = useSQLEditorContext();const { instance } = useConnectionOfCurrentSQLEditorTab();+const { showAIPanel } = useSQLEditorContext();const allowReadonlyMode = computed(() => {if (isDisconnected.value) return false;@@ -98,28 +101,4 @@ const { execute } = useExecuteSQL();const handleExecute = (params: SQLEditorQueryParams) => {execute(params);};--const handleApplyStatement = async (- statement: string,- connection: SQLEditorConnection,- run: boolean-) => {- if (!tab.value) {- return;- }- tab.value.statement = statement;- if (run) {- await nextAnimationFrame();- const database = useDatabaseV1Store().getDatabaseByName(- connection.database- );- handleExecute({- connection,- statement,- engine: database.instanceResource.engine,- explain: false,- selection: tab.value.editorState.selection,- });- }-};</script>diff --git a/frontend/src/views/sql-editor/context.ts b/frontend/src/views/sql-editor/context.tsindex b7bc746fd8..ab6b3f796e 100644--- a/frontend/src/views/sql-editor/context.ts+++ b/frontend/src/views/sql-editor/context.ts@@ -33,7 +33,7 @@ type SQLEditorEvents = Emittery<{export type SQLEditorContext = {asidePanelTab: Ref<AsidePanelTab>;showConnectionPanel: Ref<boolean>;- showAIChatBox: Ref<boolean>;+ showAIPanel: Ref<boolean>;schemaViewer: Ref<| {database: ComposedDatabase;@@ -61,7 +61,7 @@ export const provideSQLEditorContext = () => {const context: SQLEditorContext = {asidePanelTab: ref("WORKSHEET"),showConnectionPanel: ref(false),- showAIChatBox: ref(false),+ showAIPanel: ref(false),schemaViewer: ref(undefined),events: new Emittery(),