Skip to content

SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.

feat: AI Assistant UI (#10992)

Yunus Mac5ccbf1864b
diff --git a/frontend/.oxlintrc.json b/frontend/.oxlintrc.json
index 7903ab2559..af386774b4 100644
--- a/frontend/.oxlintrc.json
+++ b/frontend/.oxlintrc.json
@@ -497,7 +497,8 @@
"overrides": [
{
"files": [
- "src/api/generated/**/*.ts"
+ "src/api/generated/**/*.ts",
+ "src/api/ai-assistant/**/*.ts"
],
"rules": {
"@typescript-eslint/explicit-function-return-type": "off",
diff --git a/frontend/package.json b/frontend/package.json
index 3061fdab30..95f0b89172 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -135,6 +135,7 @@
"redux": "^4.0.5",
"redux-thunk": "^2.3.0",
"rehype-raw": "7.0.0",
+ "remark-gfm": "^3.0.1",
"rollup-plugin-visualizer": "7.0.0",
"rrule": "2.8.1",
"stream": "^0.0.2",
@@ -173,18 +174,18 @@
"@commitlint/config-conventional": "20.4.4",
"@faker-js/faker": "9.3.0",
"@jest/globals": "30.2.0",
+ "@jest/types": "30.2.0",
"@testing-library/jest-dom": "5.16.5",
"@testing-library/react": "13.4.0",
"@testing-library/user-event": "14.4.3",
"@types/color": "^3.0.3",
"@types/crypto-js": "4.2.2",
+ "@types/d3-hierarchy": "1.1.11",
"@types/dompurify": "^2.4.0",
"@types/event-source-polyfill": "^1.0.0",
- "@types/d3-hierarchy": "1.1.11",
"@types/fontfaceobserver": "2.1.0",
"@types/history": "4.7.11",
"@types/jest": "30.0.0",
- "@jest/types": "30.2.0",
"@types/lodash-es": "^4.17.4",
"@types/mini-css-extract-plugin": "^2.5.1",
"@types/node": "^16.10.3",
diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yaml
index d1163026f3..ee02a643f8 100644
--- a/frontend/pnpm-lock.yaml
+++ b/frontend/pnpm-lock.yaml
@@ -340,6 +340,9 @@ importers:
rehype-raw:
specifier: 7.0.0
version: 7.0.0
+ remark-gfm:
+ specifier: ^3.0.1
+ version: 3.0.1
rollup-plugin-visualizer:
specifier: 7.0.0
version: 7.0.0([email protected])
@@ -1904,105 +1907,89 @@ packages:
resolution: {integrity: sha512-excjX8DfsIcJ10x1Kzr4RcWe1edC9PquDRRPx3YVCvQv+U5p7Yin2s32ftzikXojb1PIFc/9Mt28/y+iRklkrw==}
cpu: [arm64]
os: [linux]
- libc: [glibc]
resolution: {integrity: sha512-bFI7xcKFELdiNCVov8e44Ia4u2byA+l3XtsAj+Q8tfCwO6BQ8iDojYdvoPMqsKDkuoOo+X6HZA0s0q11ANMQ8A==}
cpu: [arm]
os: [linux]
- libc: [glibc]
resolution: {integrity: sha512-FMuvGijLDYG6lW+b/UvyilUWu5Ayu+3r2d1S8notiGCIyYU/76eig1UfMmkZ7vwgOrzKzlQbFSuQfgm7GYUPpA==}
cpu: [ppc64]
os: [linux]
- libc: [glibc]
resolution: {integrity: sha512-oVDbcR4zUC0ce82teubSm+x6ETixtKZBh/qbREIOcI3cULzDyb18Sr/Wcyx7NRQeQzOiHTNbZFF1UwPS2scyGA==}
cpu: [riscv64]
os: [linux]
- libc: [glibc]
resolution: {integrity: sha512-qmp9VrzgPgMoGZyPvrQHqk02uyjA0/QrTO26Tqk6l4ZV0MPWIW6LTkqOIov+J1yEu7MbFQaDpwdwJKhbJvuRxQ==}
cpu: [s390x]
os: [linux]
- libc: [glibc]
resolution: {integrity: sha512-tJxiiLsmHc9Ax1bz3oaOYBURTXGIRDODBqhveVHonrHJ9/+k89qbLl0bcJns+e4t4rvaNBxaEZsFtSfAdquPrw==}
cpu: [x64]
os: [linux]
- libc: [glibc]
resolution: {integrity: sha512-FVQHuwx1IIuNow9QAbYUzJ+En8KcVm9Lk5+uGUQJHaZmMECZmOlix9HnH7n1TRkXMS0pGxIJokIVB9SuqZGGXw==}
cpu: [arm64]
os: [linux]
- libc: [musl]
resolution: {integrity: sha512-+LpyBk7L44ZIXwz/VYfglaX/okxezESc6UxDSoyo2Ks6Jxc4Y7sGjpgU9s4PMgqgjj1gZCylTieNamqA1MF7Dg==}
cpu: [x64]
os: [linux]
- libc: [musl]
resolution: {integrity: sha512-bKQzaJRY/bkPOXyKx5EVup7qkaojECG6NLYswgktOZjaXecSAeCWiZwwiFf3/Y+O1HrauiE3FVsGxFg8c24rZg==}
engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
cpu: [arm64]
os: [linux]
- libc: [glibc]
resolution: {integrity: sha512-9dLqsvwtg1uuXBGZKsxem9595+ujv0sJ6Vi8wcTANSFpwV/GONat5eCkzQo/1O6zRIkh0m/8+5BjrRr7jDUSZw==}
engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
cpu: [arm]
os: [linux]
- libc: [glibc]
resolution: {integrity: sha512-7zznwNaqW6YtsfrGGDA6BRkISKAAE1Jo0QdpNYXNMHu2+0dTrPflTLNkpc8l7MUP5M16ZJcUvysVWWrMefZquA==}
engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
cpu: [ppc64]
os: [linux]
- libc: [glibc]
resolution: {integrity: sha512-51gJuLPTKa7piYPaVs8GmByo7/U7/7TZOq+cnXJIHZKavIRHAP77e3N2HEl3dgiqdD/w0yUfiJnII77PuDDFdw==}
engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
cpu: [riscv64]
os: [linux]
- libc: [glibc]
resolution: {integrity: sha512-nQtCk0PdKfho3eC5MrbQoigJ2gd1CgddUMkabUj+rBevs8tZ2cULOx46E7oyX+04WGfABgIwmMC0VqieTiR4jg==}
engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
cpu: [s390x]
os: [linux]
- libc: [glibc]
resolution: {integrity: sha512-MEzd8HPKxVxVenwAa+JRPwEC7QFjoPWuS5NZnBt6B3pu7EG2Ge0id1oLHZpPJdn3OQK+BQDiw9zStiHBTJQQQQ==}
engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
cpu: [x64]
os: [linux]
- libc: [glibc]
resolution: {integrity: sha512-fprJR6GtRsMt6Kyfq44IsChVZeGN97gTD331weR1ex1c1rypDEABN6Tm2xa1wE6lYb5DdEnk03NZPqA7Id21yg==}
engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
cpu: [arm64]
os: [linux]
- libc: [musl]
resolution: {integrity: sha512-Jg8wNT1MUzIvhBFxViqrEhWDGzqymo3sV7z7ZsaWbZNDLXRJZoRGrjulp60YYtV4wfY8VIKcWidjojlLcWrd8Q==}
engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
cpu: [x64]
os: [linux]
- libc: [musl]
resolution: {integrity: sha512-OdWTEiVkY2PHwqkbBI8frFxQQFekHaSSkUIJkwzclWZe64O1X4UlUjqqqLaPbUpMOQk6FBu/HtlGXNblIs0huw==}
@@ -2357,56 +2344,48 @@ packages:
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
- libc: [glibc]
resolution: {integrity: sha512-IxtQC/sbBi4ubbY+MdwdanRWrG9InQJVZqyMsBa5IUaQcnSg86gQme574HxXMC1p4bo4YhV99zQ+wNnGCvEgzw==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
- libc: [musl]
resolution: {integrity: sha512-EWXEhOMbWO0q6eJSbu0QLkU8cKi0ljlYLngeDs2Ocu/pm1rrLwyQiYzlFbdnMRURI4w9ndr1sI9rSbhlJ5o23Q==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [ppc64]
os: [linux]
- libc: [glibc]
resolution: {integrity: sha512-tZrjS11TUiDuEpRaqdk8K9F9xETRyKXfuZKmdeW+Gj7coBnm7+8sBEfyt033EAFEQSlkniAXvBLh+Qja2ioGBQ==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [riscv64]
os: [linux]
- libc: [glibc]
resolution: {integrity: sha512-KBFy+2CFKUCZzYwX2ZOPQKck1vjQbz+hextuc19G4r0WRJwadfAeuQMQRQvB+Ivc8brlbOVg7et8K7E467440g==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [riscv64]
os: [linux]
- libc: [musl]
resolution: {integrity: sha512-REUPFKVGSiK99B+9eaPhluEVglzaoj/SMykNC5SUiV2RSsBfV5lWN7Y0iCIc251Wz3GaeAGZsJ/zj3gjarxdFg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [s390x]
os: [linux]
- libc: [glibc]
resolution: {integrity: sha512-KVftVSVEDeIfRW3TIeLe3aNI/iY4m1fu5mDwHcisKMZSCMKLkrhFsjowC7o9RoqNPxbbglm2+/6KAKBIts2t0Q==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
- libc: [glibc]
resolution: {integrity: sha512-DTsmGEaA2860Aq5VUyDO8/MT9NFxwVL93RnRYmpMwK6DsSkThmvEpqoUDDljziEpAedMRG19SCogrNbINSbLUQ==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
- libc: [musl]
resolution: {integrity: sha512-8r5BDro7fLOBoq1JXHLVSs55OlrxQhEso4HVo0TcY7OXJUPYfjPoOaYL5us+yIwqyP9rQwN+rxuiNFSmaxSuOQ==}
@@ -2509,56 +2488,48 @@ packages:
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
- libc: [glibc]
'@oxlint/[email protected]':
resolution: {integrity: sha512-8eCy3FCDuWUM5hWujAv6heMvfZPbcCOU3SdQUAkixZLu5bSzOkNfirJiLGoQFO943xceOKkiQRMQNzH++jM3WA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
- libc: [musl]
'@oxlint/[email protected]':
resolution: {integrity: sha512-NjQ7K7tpTPDe9J+yq8p/s/J0E7lRCkK2uDBDqvT4XIT6f4Z0tlnr59OBg/WcrmVHER1AbrcfyxhGTXgcG8ytWg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [ppc64]
os: [linux]
- libc: [glibc]
'@oxlint/[email protected]':
resolution: {integrity: sha512-oKZed9gmSwze29dEt3/Wnsv6l/Ygw/FUst+8Kfpv2SGeS/glEoTGZAMQw37SVyzFV76UTHJN2snGgxK2t2+8ow==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [riscv64]
os: [linux]
- libc: [glibc]
'@oxlint/[email protected]':
resolution: {integrity: sha512-gBjBxQ+9lGpAYq+ELqw0w8QXsBnkZclFc7GRX2r0LnEVn3ZTEqeIKpKcGjucmp76Q53bvJD0i4qBWBhcfhSfGA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [riscv64]
os: [linux]
- libc: [musl]
'@oxlint/[email protected]':
resolution: {integrity: sha512-Ew2Kxs9EQ9/mbAIJ2hvocMC0wsOu6YKzStI2eFBDt+Td5O8seVC/oxgRIHqCcl5sf5ratA1nozQBAuv7tphkHg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [s390x]
os: [linux]
- libc: [glibc]
'@oxlint/[email protected]':
resolution: {integrity: sha512-5z25jcAA0gfKyVwz71A0VXgaPlocPoTAxhlv/hgoK6tlCrfoNuw7haWbDHvGMfjXhdic4EqVXGRv5XsTqFnbRQ==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
- libc: [glibc]
'@oxlint/[email protected]':
resolution: {integrity: sha512-IWpHmMB6ZDllPvqWDkG6AmXrN7JF5e/c4g/0PuURsmlK+vHoYZPB70rr4u1bn3I4LsKCSpqqfveyx6UCOC8wdg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
- libc: [musl]
'@oxlint/[email protected]':
resolution: {integrity: sha512-fjlSxxrD5pA594vkyikCS9MnPRjQawW6/BLgyTYkO+73wwPlYjkcZ7LSd974l0Q2zkHQmu4DPvJFLYA7o8xrxQ==}
@@ -2613,42 +2584,36 @@ packages:
engines: {node: '>= 10.0.0'}
cpu: [arm]
os: [linux]
- libc: [glibc]
'@parcel/[email protected]':
resolution: {integrity: sha512-6E+m/Mm1t1yhB8X412stiKFG3XykmgdIOqhjWj+VL8oHkKABfu/gjFj8DvLrYVHSBNC+/u5PeNrujiSQ1zwd1Q==}
engines: {node: '>= 10.0.0'}
cpu: [arm]
os: [linux]
- libc: [musl]
'@parcel/[email protected]':
resolution: {integrity: sha512-LrGp+f02yU3BN9A+DGuY3v3bmnFUggAITBGriZHUREfNEzZh/GO06FF5u2kx8x+GBEUYfyTGamol4j3m9ANe8w==}
engines: {node: '>= 10.0.0'}
cpu: [arm64]
os: [linux]
- libc: [glibc]
'@parcel/[email protected]':
resolution: {integrity: sha512-cFOjABi92pMYRXS7AcQv9/M1YuKRw8SZniCDw0ssQb/noPkRzA+HBDkwmyOJYp5wXcsTrhxO0zq1U11cK9jsFg==}
engines: {node: '>= 10.0.0'}
cpu: [arm64]
os: [linux]
- libc: [musl]
'@parcel/[email protected]':
resolution: {integrity: sha512-GcESn8NZySmfwlTsIur+49yDqSny2IhPeZfXunQi48DMugKeZ7uy1FX83pO0X22sHntJ4Ub+9k34XQCX+oHt2A==}
engines: {node: '>= 10.0.0'}
cpu: [x64]
os: [linux]
- libc: [glibc]
'@parcel/[email protected]':
resolution: {integrity: sha512-n0E2EQbatQ3bXhcH2D1XIAANAcTZkQICBPVaxMeaCVBtOpBZpWJuf7LwyWPSBDITb7In8mqQgJ7gH8CILCURXg==}
engines: {node: '>= 10.0.0'}
cpu: [x64]
os: [linux]
- libc: [musl]
'@parcel/[email protected]':
resolution: {integrity: sha512-RFzklRvmc3PkjKjry3hLF9wD7ppR4AKcWNzH7kXR7GUe0Igb3Nz8fyPwtZCSquGrhU5HhUNDr/mKBqj7tqA2Vw==}
@@ -3509,28 +3474,24 @@ packages:
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
- libc: [glibc]
'@rolldown/[email protected]':
resolution: {integrity: sha512-bGe5EBB8FVjHBR1mOLOPEFg1Lp3//7geqWkU5NIhxe+yH0W8FVrQ6WRYOap4SUTKdklD/dC4qPLREkMMQ855FA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
- libc: [musl]
'@rolldown/[email protected]':
resolution: {integrity: sha512-qL+63WKVQs1CMvFedlPt0U9PiEKJOAL/bsHMKUDS6Vp2Q+YAv/QLPu8rcvkfIMvQ0FPU2WL0aX4eWwF6e/GAnA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
- libc: [glibc]
'@rolldown/[email protected]':
resolution: {integrity: sha512-VGl9JIGjoJh3H8Mb+7xnVqODajBmrdOOb9lxWXdcmxyI+zjB2sux69br0hZJDTyLJfvBoYm439zPACYbCjGRmw==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
- libc: [musl]
'@rolldown/[email protected]':
resolution: {integrity: sha512-B4iIserJXuSnNzA5xBLFUIjTfhNy7d9sq4FUMQY3GhQWGVhS2RWWzzDnkSU6MUt7/aHUrep0CdQfXUJI9D3W7A==}
@@ -4305,49 +4266,41 @@ packages:
resolution: {integrity: sha512-34gw7PjDGB9JgePJEmhEqBhWvCiiWCuXsL9hYphDF7crW7UgI05gyBAi6MF58uGcMOiOqSJ2ybEeCvHcq0BCmQ==}
cpu: [arm64]
os: [linux]
- libc: [glibc]
resolution: {integrity: sha512-RyMIx6Uf53hhOtJDIamSbTskA99sPHS96wxVE/bJtePJJtpdKGXO1wY90oRdXuYOGOTuqjT8ACccMc4K6QmT3w==}
cpu: [arm64]
os: [linux]
- libc: [musl]
resolution: {integrity: sha512-D8Vae74A4/a+mZH0FbOkFJL9DSK2R6TFPC9M+jCWYia/q2einCubX10pecpDiTmkJVUH+y8K3BZClycD8nCShA==}
cpu: [ppc64]
os: [linux]
- libc: [glibc]
resolution: {integrity: sha512-frxL4OrzOWVVsOc96+V3aqTIQl1O2TjgExV4EKgRY09AJ9leZpEg8Ak9phadbuX0BA4k8U5qtvMSQQGGmaJqcQ==}
cpu: [riscv64]
os: [linux]
- libc: [glibc]
resolution: {integrity: sha512-mJ5vuDaIZ+l/acv01sHoXfpnyrNKOk/3aDoEdLO/Xtn9HuZlDD6jKxHlkN8ZhWyLJsRBxfv9GYM2utQ1SChKew==}
cpu: [riscv64]
os: [linux]
- libc: [musl]
resolution: {integrity: sha512-kELo8ebBVtb9sA7rMe1Cph4QHreByhaZ2QEADd9NzIQsYNQpt9UkM9iqr2lhGr5afh885d/cB5QeTXSbZHTYPg==}
cpu: [s390x]
os: [linux]
- libc: [glibc]
resolution: {integrity: sha512-C3ZAHugKgovV5YvAMsxhq0gtXuwESUKc5MhEtjBpLoHPLYM+iuwSj3lflFwK3DPm68660rZ7G8BMcwSro7hD5w==}
cpu: [x64]
os: [linux]
- libc: [glibc]
resolution: {integrity: sha512-rV0YSoyhK2nZ4vEswT/QwqzqQXw5I6CjoaYMOX0TqBlWhojUf8P94mvI7nuJTeaCkkds3QE4+zS8Ko+GdXuZtA==}
cpu: [x64]
os: [linux]
- libc: [musl]
resolution: {integrity: sha512-5u4RkfxJm+Ng7IWgkzi3qrFOvLvQYnPBmjmZQ8+szTK/b31fQCnleNl1GgEt7nIsZRIf5PLhPwT0WM+q45x/UQ==}
@@ -4414,7 +4367,7 @@ packages:
resolution: {integrity: sha512-VIcFLdRi/VYRU8OL/puL7QXMYafHmqOnwTZY50U1JPlCNj30PxCMx65c494b1K9be9hX83KVt0+gTEwTWLqToA==}
engines: {node: ^20.19.0 || >=22.12.0}
peerDependencies:
- vite: ^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0
+ vite: npm:[email protected]
'@webassemblyjs/[email protected]':
resolution: {integrity: sha512-nuBEDgQfm1ccRp/8bCQrx1frohyufl4JlbMMZ4P1wpeOfDhF6FQkxZJ1b/e+PLwr6X1Nhw6OLme5usuBWYBvuQ==}
@@ -7241,28 +7194,24 @@ packages:
engines: {node: '>= 12.0.0'}
cpu: [arm64]
os: [linux]
- libc: [glibc]
resolution: {integrity: sha512-mVZ7Pg2zIbe3XlNbZJdjs86YViQFoJSpc41CbVmKBPiGmC4YrfeOyz65ms2qpAobVd7WQsbW4PdsSJEMymyIMg==}
engines: {node: '>= 12.0.0'}
cpu: [arm64]
os: [linux]
- libc: [musl]
resolution: {integrity: sha512-xGlFWRMl+0KvUhgySdIaReQdB4FNudfUTARn7q0hh/V67PVGCs3ADFjw+6++kG1RNd0zdGRlEKa+T13/tQjPMA==}
engines: {node: '>= 12.0.0'}
cpu: [x64]
os: [linux]
- libc: [glibc]
resolution: {integrity: sha512-eowF8PrKHw9LpoZii5tdZwnBcYDxRw2rRCyvAXLi34iyeYfqCQNA9rmUM0ce62NlPhCvof1+9ivRaTY6pSKDaA==}
engines: {node: '>= 12.0.0'}
cpu: [x64]
os: [linux]
- libc: [musl]
resolution: {integrity: sha512-aJReEbSEQzx1uBlQizAOBSjcmr9dCdL3XuC/6HLXAxmtErsj2ICo5yYggg1qOODQMtnjNQv2UHb9NpOuFtYe4w==}
@@ -10290,7 +10239,7 @@ packages:
oxlint: '>=1'
stylelint: '>=16'
typescript: '*'
- vite: '>=5.4.21'
+ vite: npm:[email protected]
vls: '*'
vti: '*'
vue-tsc: ~2.2.10 || ^3.0.0
@@ -10319,12 +10268,12 @@ packages:
resolution: {integrity: sha512-5QJKBDc+gNYVqL/skgFAP81Yuzo9R+EAf19d+EtsMF/i8kFUpNi3J/H01QD3Oo8zBQn+NzoCIFkpPLynoOzaJg==}
peerDependencies:
- vite: '>=2.0.0'
+ vite: npm:[email protected]
resolution: {integrity: sha512-vb9C9kcdzcIo/Oc3CLZVS03dL5pDlOFuhGlZYDCJ840BhWl/0nGeZWf3Qy7NlOayscY4Cm/QRgULCQkEZige5Q==}
peerDependencies:
- vite: '>=2.0.0'
+ vite: npm:[email protected]
resolution: {integrity: sha512-1vrFOTcpSvv6DCY7h8UXab4wqMAjTJB/ndOzG/Kmj1oDOuPF6mbjkNQoGzzCEYeWGe7qU93jc8oQqvoJ57al3A==}
@@ -10332,7 +10281,7 @@ packages:
peerDependencies:
sharp: '>=0.34.0'
svgo: '>=4'
- vite: '>=5'
+ vite: npm:[email protected]
peerDependenciesMeta:
sharp:
optional: true
@@ -10342,7 +10291,7 @@ packages:
resolution: {integrity: sha512-2cihq7zliibCCZ8P9cKJrQBkfgdvcFkOOc3Y02o3GWUDLgqjWsZudaoiuOwO/gzTzy17cS5F7ZPo4bsnS4DGkg==}
peerDependencies:
- vite: '*'
+ vite: npm:[email protected]
resolution: {integrity: sha512-Dhxzh5HZuiHQhbvTW9AMetFfBHDMYpo23Uo9btPXgdYP+3T5S+p+jgNy7spra+veYhBP2dCSgxR/i2Y02h5/6w==}
diff --git a/frontend/scripts/validate-md-languages.sh b/frontend/scripts/validate-md-languages.sh
index 59330e71ed..e8e6f1fe20 100755
--- a/frontend/scripts/validate-md-languages.sh
+++ b/frontend/scripts/validate-md-languages.sh
@@ -17,6 +17,12 @@ registered_languages=$(grep -oP "registerLanguage\('\K[^']+" "$SYNTAX_HIGHLIGHTE
missing_languages=()
for lang in $md_languages; do
+ # Skip ai-* block markers — these are custom AI block types rendered by
+ # RichCodeBlock as React components (e.g. ActionBlock, LineChartBlock),
+ # not real syntax languages, so they don't need highlighter registration.
+ if [[ "$lang" == ai-* ]]; then
+ continue
+ fi
if ! echo "$registered_languages" | grep -qx "$lang"; then
missing_languages+=("$lang")
fi
diff --git a/frontend/src/AppRoutes/Private.tsx b/frontend/src/AppRoutes/Private.tsx
index 6caa83a658..7e08ef3e80 100644
--- a/frontend/src/AppRoutes/Private.tsx
+++ b/frontend/src/AppRoutes/Private.tsx
@@ -8,6 +8,7 @@ import { LOCALSTORAGE } from 'constants/localStorage';
import { ORG_PREFERENCES } from 'constants/orgPreferences';
import ROUTES from 'constants/routes';
import { useGetTenantLicense } from 'hooks/useGetTenantLicense';
+import { useIsAIAssistantEnabled } from 'hooks/useIsAIAssistantEnabled';
import { isEmpty } from 'lodash-es';
import { useAppContext } from 'providers/App/App';
import { LicensePlatform, LicenseState } from 'types/api/licensesV3/getActive';
@@ -40,6 +41,8 @@ function PrivateRoute({ children }: PrivateRouteProps): JSX.Element {
} = useAppContext();
const isAdmin = user.role === USER_ROLES.ADMIN;
+ const isAIAssistantEnabled = useIsAIAssistantEnabled();
+
const mapRoutes = useMemo(
() =>
new Map(
@@ -99,6 +102,10 @@ function PrivateRoute({ children }: PrivateRouteProps): JSX.Element {
return <>{children}</>;
}
+ if (pathname.startsWith('/ai-assistant/') && !isAIAssistantEnabled) {
+ return <Redirect to={ROUTES.HOME} />;
+ }
+
// Check for workspace access restriction (cloud only)
const isCloudPlatform = activeLicense?.platform === LicensePlatform.CLOUD;
diff --git a/frontend/src/AppRoutes/__tests__/Private.test.tsx b/frontend/src/AppRoutes/__tests__/Private.test.tsx
index 9e31871be5..a4a6f9e2db 100644
--- a/frontend/src/AppRoutes/__tests__/Private.test.tsx
+++ b/frontend/src/AppRoutes/__tests__/Private.test.tsx
@@ -164,14 +164,17 @@ function createMockAppContext(
featureFlags: [],
orgPreferences: createMockOrgPreferences(),
userPreferences: [],
+ hostsData: null,
isLoggedIn: true,
org: [{ createdAt: 0, id: 'org-id', displayName: 'Test Org' }],
isFetchingUser: false,
isFetchingActiveLicense: false,
+ isFetchingHosts: false,
isFetchingFeatureFlags: false,
isFetchingOrgPreferences: false,
userFetchError: null,
activeLicenseFetchError: null,
+ hostsFetchError: null,
featureFlagsFetchError: null,
orgPreferencesFetchError: null,
changelog: null,
diff --git a/frontend/src/AppRoutes/index.tsx b/frontend/src/AppRoutes/index.tsx
index c4107b6cd0..a0d0fa73d0 100644
--- a/frontend/src/AppRoutes/index.tsx
+++ b/frontend/src/AppRoutes/index.tsx
@@ -18,6 +18,7 @@ import AppLayout from 'container/AppLayout';
import Hex from 'crypto-js/enc-hex';
import HmacSHA256 from 'crypto-js/hmac-sha256';
import { KeyboardHotkeysProvider } from 'hooks/hotkeys/useKeyboardHotkeys';
+import { useIsAIAssistantEnabled } from 'hooks/useIsAIAssistantEnabled';
import { useIsDarkMode, useThemeConfig } from 'hooks/useDarkMode';
import { useGetTenantLicense } from 'hooks/useGetTenantLicense';
import { NotificationProvider } from 'hooks/useNotifications';
@@ -60,13 +61,21 @@ function App(): JSX.Element {
org,
} = useAppContext();
const [routes, setRoutes] = useState<AppRoutes[]>(defaultRoutes);
+ const isAIAssistantEnabled = useIsAIAssistantEnabled();
- const { hostname, pathname } = window.location;
+ const { hostname } = window.location;
+ const [pathname, setPathname] = useState(history.location.pathname);
const { isCloudUser, isEnterpriseSelfHostedUser } = useGetTenantLicense();
const [isSentryInitialized, setIsSentryInitialized] = useState(false);
+ useEffect(() => {
+ return history.listen((location) => {
+ setPathname(location.pathname);
+ });
+ }, []);
+
const enableAnalytics = useCallback(
(user: IUser): void => {
// wait for the required data to be loaded before doing init for anything!
@@ -212,6 +221,27 @@ function App(): JSX.Element {
activeLicenseFetchError,
]);
+ useEffect(() => {
+ if (!isLoggedInState) {
+ return;
+ }
+
+ setRoutes((prev) => {
+ const hasAi = prev.some((r) => r.path === ROUTES.AI_ASSISTANT);
+ if (isAIAssistantEnabled === hasAi) {
+ return prev;
+ }
+ if (isAIAssistantEnabled) {
+ const aiRoute = defaultRoutes.find((r) => r.path === ROUTES.AI_ASSISTANT);
+ if (!aiRoute) {
+ return prev;
+ }
+ return [...prev.filter((r) => r.path !== ROUTES.AI_ASSISTANT), aiRoute];
+ }
+ return prev.filter((r) => r.path !== ROUTES.AI_ASSISTANT);
+ });
+ }, [isLoggedInState, isAIAssistantEnabled]);
+
const isDarkMode = useIsDarkMode();
useEffect(() => {
@@ -221,7 +251,8 @@ function App(): JSX.Element {
useEffect(() => {
if (
pathname === ROUTES.ONBOARDING ||
- pathname.startsWith('/public/dashboard/')
+ pathname.startsWith('/public/dashboard/') ||
+ pathname.startsWith('/ai-assistant/')
) {
window.Pylon?.('hideChatBubble');
} else {
diff --git a/frontend/src/AppRoutes/pageComponents.ts b/frontend/src/AppRoutes/pageComponents.ts
index 763230ad35..b9b30a5b3b 100644
--- a/frontend/src/AppRoutes/pageComponents.ts
+++ b/frontend/src/AppRoutes/pageComponents.ts
@@ -324,3 +324,10 @@ export const MeterExplorerPage = Loadable(
() =>
import(/* webpackChunkName: "Meter Explorer Page" */ 'pages/MeterExplorer'),
);
+
+export const AIAssistantPage = Loadable(
+ () =>
+ import(
+ /* webpackChunkName: "AI Assistant Page" */ 'pages/AIAssistantPage/AIAssistantPage'
+ ),
+);
diff --git a/frontend/src/AppRoutes/routes.ts b/frontend/src/AppRoutes/routes.ts
index 6f73399ef8..155adf29dd 100644
--- a/frontend/src/AppRoutes/routes.ts
+++ b/frontend/src/AppRoutes/routes.ts
@@ -2,6 +2,7 @@ import { RouteProps } from 'react-router-dom';
import ROUTES from 'constants/routes';
import {
+ AIAssistantPage,
AlertHistory,
AlertOverview,
AlertTypeSelectionPage,
@@ -507,6 +508,13 @@ const routes: AppRoutes[] = [
key: 'API_MONITORING',
isPrivate: true,
},
+ {
+ path: ROUTES.AI_ASSISTANT,
+ exact: true,
+ component: AIAssistantPage,
+ key: 'AI_ASSISTANT',
+ isPrivate: true,
+ },
];
export const SUPPORT_ROUTE: AppRoutes = {
diff --git a/frontend/src/api/AIAPIInstance.ts b/frontend/src/api/AIAPIInstance.ts
new file mode 100644
index 0000000000..ace5a0bb7a
--- /dev/null
+++ b/frontend/src/api/AIAPIInstance.ts
@@ -0,0 +1,80 @@
+import axios, { InternalAxiosRequestConfig } from 'axios';
+
+import {
+ interceptorRejected,
+ interceptorsRequestBasePath,
+ interceptorsRequestResponse,
+ interceptorsResponse,
+} from 'api';
+import { getSigNozInstanceUrl } from 'utils/signozInstanceUrl';
+
+/** Path-only base for the AI Assistant API. */
+export const AI_API_PATH = '/api/v1/assistant';
+
+/** Header that tells the AI backend which SigNoz instance to query against. */
+export const SIGNOZ_URL_HEADER = 'X-SigNoz-URL';
+
+/**
+ * Sets `X-SigNoz-URL` on every outgoing AI Assistant request. The backend
+ * needs the originating SigNoz instance URL for multi-tenant deployments;
+ * when omitted it falls back to its `SIGNOZ_API_URL` env var.
+ */
+export const interceptorsRequestSigNozUrl = (
+ value: InternalAxiosRequestConfig,
+): InternalAxiosRequestConfig => {
+ if (value.headers) {
+ value.headers[SIGNOZ_URL_HEADER] = getSigNozInstanceUrl();
+ }
+ return value;
+};
+
+/**
+ * AI backend URL — sourced from the global config's `ai_assistant_url` field
+ * at runtime. `useIsAIAssistantEnabled` keeps this in sync via `setAIBackendUrl`
+ * whenever the config response changes; consumers (the axios instance and the
+ * SSE fetch path) read it lazily so they always see the current value.
+ */
+let aiBackendUrl: string | null = null;
+
+export function setAIBackendUrl(url: string | null): void {
+ if (aiBackendUrl === url) {
+ return;
+ }
+ aiBackendUrl = url;
+ AIAssistantInstance.defaults.baseURL = url ? `${url}${AI_API_PATH}` : '';
+}
+
+/**
+ * Full base URL for the AI Assistant API (host + path). Throws when the
+ * config hasn't yet provided a URL — should never happen in practice
+ * because `useIsAIAssistantEnabled` gates every consumer surface.
+ */
+export function getAIBaseUrl(): string {
+ if (!aiBackendUrl) {
+ throw new Error('AI assistant URL is not configured.');
+ }
+ return `${aiBackendUrl}${AI_API_PATH}`;
+}
+
+/**
+ * Dedicated axios instance for the AI Assistant.
+ *
+ * Mirrors the request/response interceptor stack of the main SigNoz axios
+ * instance — most importantly `interceptorRejected`, which transparently
+ * rotates the access token via `/sessions/rotate` on a 401 and replays the
+ * original request. That's why we don't need any AI-specific 401 handling
+ * for REST calls: this instance inherits the same flow as the rest of the
+ * app for free.
+ *
+ * Only the SSE stream (`streamEvents`) still needs raw fetch since axios
+ * doesn't expose `ReadableStream` — that path keeps its own auth wrapper.
+ */
+export const AIAssistantInstance = axios.create({});
+
+AIAssistantInstance.interceptors.request.use(interceptorsRequestResponse);
+AIAssistantInstance.interceptors.request.use(interceptorsRequestBasePath);
+AIAssistantInstance.interceptors.request.use(interceptorsRequestSigNozUrl);
+AIAssistantInstance.interceptors.response.use(
+ interceptorsResponse,
+ interceptorRejected,
+);
diff --git a/frontend/src/api/ai-assistant/chat.ts b/frontend/src/api/ai-assistant/chat.ts
new file mode 100644
index 0000000000..6be69a652a
--- /dev/null
+++ b/frontend/src/api/ai-assistant/chat.ts
@@ -0,0 +1,543 @@
+/**
+ * AI Assistant API client.
+ *
+ * Flow:
+ * 1. POST /api/v1/assistant/threads → { threadId }
+ * 2. POST /api/v1/assistant/threads/{threadId}/messages → { executionId }
+ * 3. GET /api/v1/assistant/executions/{executionId}/events → SSE stream (closes on 'done')
+ *
+ * For subsequent messages in the same thread, repeat steps 2–3.
+ * Approval/clarification events pause the stream; use approveExecution/clarifyExecution
+ * to resume, which each return a new executionId to open a fresh SSE stream.
+ *
+ * Types in this file re-use the OpenAPI-generated DTOs in
+ * `src/api/ai-assistant/sigNozAIAssistantAPI.schemas.ts`.
+ * Local types are defined only when the UI needs a different shape — for
+ * example, the SSE event union adds a literal `type` discriminator that the
+ * generated event DTOs leave loose.
+ *
+ * REST calls go through `AIAssistantInstance` (an axios instance configured
+ * with the same interceptor stack as the rest of the app) — that gives them
+ * automatic 401-then-rotate behaviour for free. Only the SSE call is still
+ * a raw `fetch` because axios doesn't expose `ReadableStream`; that one
+ * path gets its own small auth wrapper.
+ */
+
+import axios from 'axios';
+import getLocalStorageApi from 'api/browser/localstorage/get';
+import { Logout } from 'api/utils';
+import rotateSession from 'api/v2/sessions/rotate/post';
+import afterLogin from 'AppRoutes/utils';
+import type {
+ ActionResultResponseDTO,
+ ApprovalEventDTO,
+ ApproveResponseDTO,
+ CancelResponseDTO,
+ ClarificationEventDTO,
+ ClarifyResponseDTO,
+ ConversationEventDTO,
+ CreateMessageResponseDTO,
+ CreateThreadResponseDTO,
+ DoneEventDTO,
+ ErrorEventDTO,
+ ExecutionStateDTO,
+ FeedbackRatingDTO,
+ ListThreadsApiV1AssistantThreadsGetArchived,
+ ListThreadsApiV1AssistantThreadsGetParams,
+ MessageContextDTO,
+ MessageContextDTOSource,
+ MessageContextDTOType,
+ MessageEventDTO,
+ MessageSummaryDTO,
+ RegenerateResponseDTO,
+ StatusEventDTO,
+ ThinkingEventDTO,
+ ThreadDetailResponseDTO,
+ ThreadListResponseDTO,
+ ThreadSummaryDTO,
+ ToolCallEventDTO,
+ ToolResultEventDTO,
+} from './sigNozAIAssistantAPI.schemas';
+import { LOCALSTORAGE } from 'constants/localStorage';
+
+import {
+ AIAssistantInstance,
+ getAIBaseUrl,
+ SIGNOZ_URL_HEADER,
+} from '../AIAPIInstance';
+import { getSigNozInstanceUrl } from 'utils/signozInstanceUrl';
+
+// ---------------------------------------------------------------------------
+// SSE-only auth wrapper.
+//
+// REST calls go through `AIAssistantInstance` (axios) and get refresh-token
+// behaviour from the shared `interceptorRejected`. The SSE call has to use
+// raw `fetch` (axios can't stream a `ReadableStream`), so it can't ride that
+// interceptor — this small wrapper handles 401 at SSE open time by hitting
+// the same rotate endpoint and replaying the request once.
+//
+// In typical use a REST call (e.g. sendMessage / loadThread) precedes every
+// stream open, so axios will already have refreshed the token and `fetch`
+// just reads the fresh one from localStorage. The wrapper exists for the
+// edge case where SSE is the first call to encounter a 401.
+// ---------------------------------------------------------------------------
+
+let pendingRotate: Promise<string | null> | null = null;
+
+async function rotateAccessToken(): Promise<string | null> {
+ if (pendingRotate) {
+ return pendingRotate;
+ }
+ const refreshToken = getLocalStorageApi(LOCALSTORAGE.REFRESH_AUTH_TOKEN) || '';
+ if (!refreshToken) {
+ return null;
+ }
+ pendingRotate = (async (): Promise<string | null> => {
+ try {
+ const response = await rotateSession({ refreshToken });
+ afterLogin(response.data.accessToken, response.data.refreshToken, true);
+ return response.data.accessToken;
+ } catch {
+ Logout();
+ return null;
+ } finally {
+ pendingRotate = null;
+ }
+ })();
+ return pendingRotate;
+}
+
+// Backoff schedule for 429 retries on SSE open. Three attempts is enough to
+// absorb the brief window between cancel→send→stream when the backend is
+// rate-limiting the burst, without making real "you're saturated" errors
+// take forever to surface.
+const SSE_429_BACKOFF_MS = [400, 1200, 2500];
+
+function parseRetryAfterMs(value: string | null): number | null {
+ if (!value) {
+ return null;
+ }
+ const seconds = Number(value);
+ if (Number.isFinite(seconds)) {
+ return Math.max(0, seconds * 1000);
+ }
+ const date = Date.parse(value);
+ if (Number.isFinite(date)) {
+ return Math.max(0, date - Date.now());
+ }
+ return null;
+}
+
+async function fetchSSEWithAuth(
+ url: string,
+ signal?: AbortSignal,
+): Promise<Response> {
+ const send = async (token: string | null): Promise<Response> => {
+ const headers: Record<string, string> = {
+ [SIGNOZ_URL_HEADER]: getSigNozInstanceUrl(),
+ };
+ if (token) {
+ headers.Authorization = `Bearer ${token}`;
+ }
+ return fetch(url, { headers, signal });
+ };
+
+ const sendWithAuth = async (): Promise<Response> => {
+ const initialToken = getLocalStorageApi(LOCALSTORAGE.AUTH_TOKEN) || '';
+ const res = await send(initialToken);
+ if (res.status !== 401) {
+ return res;
+ }
+ const refreshed = await rotateAccessToken();
+ if (!refreshed) {
+ return res;
+ }
+ return send(refreshed);
+ };
+
+ let res = await sendWithAuth();
+ for (const baseDelay of SSE_429_BACKOFF_MS) {
+ if (res.status !== 429 || signal?.aborted) {
+ return res;
+ }
+ const retryAfter = parseRetryAfterMs(res.headers.get('Retry-After'));
+ const delay = retryAfter ?? baseDelay;
+ // eslint-disable-next-line no-await-in-loop
+ await new Promise<void>((resolve, reject) => {
+ const timer = setTimeout(resolve, delay);
+ signal?.addEventListener(
+ 'abort',
+ () => {
+ clearTimeout(timer);
+ reject(new DOMException('SSE 429 backoff aborted', 'AbortError'));
+ },
+ { once: true },
+ );
+ });
+ // eslint-disable-next-line no-await-in-loop
+ res = await sendWithAuth();
+ }
+ return res;
+}
+
+// ---------------------------------------------------------------------------
+// SSE event types
+//
+// The generated event DTOs each declare `type?: string` (loose). The UI needs
+// a discriminated union, so we intersect each variant with a string-literal
+// `type` to enable narrowing via `event.type === 'status'`.
+// ---------------------------------------------------------------------------
+
+export type SSEEvent =
+ | (StatusEventDTO & { type: 'status' })
+ | (MessageEventDTO & { type: 'message' })
+ | (ThinkingEventDTO & { type: 'thinking' })
+ | (ToolCallEventDTO & { type: 'tool_call' })
+ | (ToolResultEventDTO & { type: 'tool_result' })
+ | (ApprovalEventDTO & { type: 'approval' })
+ | (ClarificationEventDTO & { type: 'clarification' })
+ | (ErrorEventDTO & { type: 'error' })
+ | (ConversationEventDTO & { type: 'conversation' })
+ | (DoneEventDTO & { type: 'done' });
+
+/** String-literal view of `ExecutionStateDTO` for ergonomic comparisons. */
+export type ExecutionState = `${ExecutionStateDTO}`;
+
+// ---------------------------------------------------------------------------
+// Re-exported DTOs — the wire shape, used directly without remapping.
+// ---------------------------------------------------------------------------
+
+export type ThreadSummary = ThreadSummaryDTO;
+export type ThreadListResponse = ThreadListResponseDTO;
+export type ThreadDetailResponse = ThreadDetailResponseDTO;
+export type MessageSummary = MessageSummaryDTO;
+export type CancelResponse = CancelResponseDTO;
+
+/**
+ * Construction-friendly view of `MessageContextDTO`: enum fields are widened
+ * to their string-literal unions so call-sites can pass `'mention'` instead
+ * of `MessageContextDTOSource.mention`.
+ */
+export type MessageContext = Omit<MessageContextDTO, 'source' | 'type'> & {
+ source: `${MessageContextDTOSource}`;
+ type: `${MessageContextDTOType}`;
+};
+
+/** Construction-friendly view of `ListThreadsApiV1AssistantThreadsGetParams`. */
+export type ListThreadsOptions = Omit<
+ ListThreadsApiV1AssistantThreadsGetParams,
+ 'archived'
+> & {
+ archived?: `${ListThreadsApiV1AssistantThreadsGetArchived}`;
+};
+
+/** String-literal view of `FeedbackRatingDTO` so call-sites can pass `'positive'`/`'negative'`. */
+export type FeedbackRating = `${FeedbackRatingDTO}`;
+
+// ---------------------------------------------------------------------------
+// Thread listing & detail
+// ---------------------------------------------------------------------------
+
+export async function listThreads(
+ options: ListThreadsOptions = {},
+): Promise<ThreadListResponse> {
+ const {
+ archived = 'false',
+ limit = 20,
+ cursor = null,
+ sort = 'updated_desc',
+ } = options;
+ const response = await AIAssistantInstance.get<ThreadListResponse>(
+ '/threads',
+ {
+ params: {
+ archived,
+ limit,
+ sort,
+ ...(cursor ? { cursor } : {}),
+ },
+ },
+ );
+ return response.data;
+}
+
+export async function updateThread(
+ threadId: string,
+ update: { title?: string | null; archived?: boolean | null },
+): Promise<ThreadSummary> {
+ const response = await AIAssistantInstance.patch<ThreadSummary>(
+ `/threads/${threadId}`,
+ update,
+ );
+ return response.data;
+}
+
+export async function getThreadDetail(
+ threadId: string,
+): Promise<ThreadDetailResponse> {
+ const response = await AIAssistantInstance.get<ThreadDetailResponse>(
+ `/threads/${threadId}`,
+ );
+ return response.data;
+}
+
+// ---------------------------------------------------------------------------
+// Step 1 — Create thread
+// POST /api/v1/assistant/threads → { threadId }
+// ---------------------------------------------------------------------------
+
+export async function createThread(signal?: AbortSignal): Promise<string> {
+ const response = await AIAssistantInstance.post<CreateThreadResponseDTO>(
+ '/threads',
+ {},
+ { signal },
+ );
+ return response.data.threadId;
+}
+
+// ---------------------------------------------------------------------------
+// Step 2 — Send message
+// POST /api/v1/assistant/threads/{threadId}/messages → { executionId }
+// ---------------------------------------------------------------------------
+
+/** Fetches the thread's active executionId for reconnect on thread_busy (409). */
+async function getActiveExecutionId(threadId: string): Promise<string | null> {
+ try {
+ const response = await AIAssistantInstance.get<ThreadDetailResponseDTO>(
+ `/threads/${threadId}`,
+ );
+ return response.data.activeExecutionId ?? null;
+ } catch {
+ return null;
+ }
+}
+
+export async function sendMessage(
+ threadId: string,
+ content: string,
+ contexts?: MessageContext[],
+ signal?: AbortSignal,
+): Promise<string> {
+ try {
+ const response = await AIAssistantInstance.post<CreateMessageResponseDTO>(
+ `/threads/${threadId}/messages`,
+ {
+ content,
+ ...(contexts && contexts.length > 0 ? { contexts } : {}),
+ },
+ { signal },
+ );
+ return response.data.executionId;
+ } catch (err) {
+ // Thread already has an active execution — reconnect to it instead of
+ // failing the user's send.
+ if (axios.isAxiosError(err) && err.response?.status === 409) {
+ const executionId = await getActiveExecutionId(threadId);
+ if (executionId) {
+ return executionId;
+ }
+ }
+ throw err;
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Step 3 — Stream execution events
+// GET /api/v1/assistant/executions/{executionId}/events → SSE
+// ---------------------------------------------------------------------------
+
+function parseSSELine(line: string): SSEEvent | null {
+ if (!line.startsWith('data: ')) {
+ return null;
+ }
+ const json = line.slice('data: '.length).trim();
+ if (!json || json === '[DONE]') {
+ return null;
+ }
+ try {
+ return JSON.parse(json) as SSEEvent;
+ } catch {
+ return null;
+ }
+}
+
+function parseSSEChunk(chunk: string): SSEEvent[] {
+ return chunk
+ .split('\n\n')
+ .map((part) => part.split('\n').find((l) => l.startsWith('data: ')) ?? '')
+ .map(parseSSELine)
+ .filter((e): e is SSEEvent => e !== null);
+}
+
+async function* readSSEReader(
+ reader: ReadableStreamDefaultReader<Uint8Array>,
+): AsyncGenerator<SSEEvent> {
+ const decoder = new TextDecoder();
+ let lineBuffer = '';
+ try {
+ // eslint-disable-next-line no-constant-condition
+ while (true) {
+ // eslint-disable-next-line no-await-in-loop
+ const { done, value } = await reader.read();
+ if (done) {
+ break;
+ }
+ lineBuffer += decoder.decode(value, { stream: true });
+ const parts = lineBuffer.split('\n\n');
+ lineBuffer = parts.pop() ?? '';
+ yield* parts.flatMap(parseSSEChunk);
+ }
+ yield* parseSSEChunk(lineBuffer);
+ } finally {
+ reader.releaseLock();
+ }
+}
+
+/**
+ * Thrown by `streamEvents` when the SSE open returns a non-2xx response.
+ * Carries the HTTP status so callers can branch on rate-limit vs. other
+ * failures (e.g. show a "please wait a moment" message on 429).
+ */
+export class SSEStreamError extends Error {
+ status: number;
+
+ constructor(status: number, statusText: string) {
+ super(`SSE stream failed: ${status} ${statusText}`);
+ this.name = 'SSEStreamError';
+ this.status = status;
+ }
+}
+
+export async function* streamEvents(
+ executionId: string,
+ signal?: AbortSignal,
+): AsyncGenerator<SSEEvent> {
+ const res = await fetchSSEWithAuth(
+ `${getAIBaseUrl()}/executions/${executionId}/events`,
+ signal,
+ );
+ if (!res.ok || !res.body) {
+ throw new SSEStreamError(res.status, res.statusText);
+ }
+ yield* readSSEReader(res.body.getReader());
+}
+
+// ---------------------------------------------------------------------------
+// Approval / Clarification / Cancel actions
+// ---------------------------------------------------------------------------
+
+/** Approve a pending action. Returns a new executionId — open a fresh SSE stream for it. */
+export async function approveExecution(
+ approvalId: string,
+ signal?: AbortSignal,
+): Promise<string> {
+ const response = await AIAssistantInstance.post<ApproveResponseDTO>(
+ '/approve',
+ { approvalId },
+ { signal },
+ );
+ return response.data.executionId;
+}
+
+/** Reject a pending action. */
+export async function rejectExecution(
+ approvalId: string,
+ signal?: AbortSignal,
+): Promise<void> {
+ await AIAssistantInstance.post('/reject', { approvalId }, { signal });
+}
+
+/** Submit clarification answers. Returns a new executionId — open a fresh SSE stream for it. */
+export async function clarifyExecution(
+ clarificationId: string,
+ answers: Record<string, unknown>,
+ signal?: AbortSignal,
+): Promise<string> {
+ const response = await AIAssistantInstance.post<ClarifyResponseDTO>(
+ '/clarify',
+ { clarificationId, answers },
+ { signal },
+ );
+ return response.data.executionId;
+}
+
+/**
+ * Clean-slate regeneration of an assistant response. The backend rewinds the
+ * conversation up to (excluding) the supplied messageId and starts a fresh
+ * execution. Returns the new executionId — open an SSE stream for it the
+ * same way `sendMessage` and `approve` do.
+ */
+export async function regenerateMessage(
+ messageId: string,
+ signal?: AbortSignal,
+): Promise<string> {
+ const response = await AIAssistantInstance.post<RegenerateResponseDTO>(
+ `/messages/${messageId}/regenerate`,
+ undefined,
+ { signal },
+ );
+ return response.data.executionId;
+}
+
+export async function cancelExecution(
+ threadId: string,
+ signal?: AbortSignal,
+): Promise<CancelResponse> {
+ const response = await AIAssistantInstance.post<CancelResponse>(
+ '/cancel',
+ { threadId },
+ { signal },
+ );
+ return response.data;
+}
+
+// ---------------------------------------------------------------------------
+// Rollback actions — undo / revert / restore
+// All three POST `{ actionMetadataId }` and return `ActionResultResponseDTO`.
+// ---------------------------------------------------------------------------
+
+async function postRollback(
+ endpoint: 'undo' | 'revert' | 'restore',
+ actionMetadataId: string,
+ signal?: AbortSignal,
+): Promise<ActionResultResponseDTO> {
+ const response = await AIAssistantInstance.post<ActionResultResponseDTO>(
+ `/${endpoint}`,
+ { actionMetadataId },
+ { signal },
+ );
+ return response.data;
+}
+
+export const undoExecution = (
+ actionMetadataId: string,
+ signal?: AbortSignal,
+): Promise<ActionResultResponseDTO> =>
+ postRollback('undo', actionMetadataId, signal);
+
+export const revertExecution = (
+ actionMetadataId: string,
+ signal?: AbortSignal,
+): Promise<ActionResultResponseDTO> =>
+ postRollback('revert', actionMetadataId, signal);
+
+export const restoreExecution = (
+ actionMetadataId: string,
+ signal?: AbortSignal,
+): Promise<ActionResultResponseDTO> =>
+ postRollback('restore', actionMetadataId, signal);
+
+// ---------------------------------------------------------------------------
+// Feedback
+// ---------------------------------------------------------------------------
+
+export async function submitFeedback(
+ messageId: string,
+ rating: FeedbackRating,
+ comment?: string,
+): Promise<void> {
+ await AIAssistantInstance.post(`/messages/${messageId}/feedback`, {
+ rating,
+ comment: comment ?? null,
+ });
+}
diff --git a/frontend/src/api/ai-assistant/index.ts b/frontend/src/api/ai-assistant/index.ts
new file mode 100644
index 0000000000..9e5b19c78b
--- /dev/null
+++ b/frontend/src/api/ai-assistant/index.ts
@@ -0,0 +1,1820 @@
+/**
+ * ! Do not edit manually
+ * * The file has been auto-generated using Orval for SigNoz AI Assistant
+ * * regenerate with 'yarn generate:api'
+ * SigNoz AI Assistant API
+ * OpenAPI spec version: 0.1.0
+ */
+import { useMutation, useQuery } from 'react-query';
+import type {
+ InvalidateOptions,
+ MutationFunction,
+ QueryClient,
+ QueryFunction,
+ QueryKey,
+ UseMutationOptions,
+ UseMutationResult,
+ UseQueryOptions,
+ UseQueryResult,
+} from 'react-query';
+
+import type {
+ ActionResultResponseDTO,
+ ApproveApiV1AssistantApprovePostHeaders,
+ ApproveRequestDTO,
+ ApproveResponseDTO,
+ CancelApiV1AssistantCancelPostHeaders,
+ CancelRequestDTO,
+ CancelResponseDTO,
+ ClarifyApiV1AssistantClarifyPostHeaders,
+ ClarifyRequestDTO,
+ ClarifyResponseDTO,
+ CreateMessageApiV1AssistantThreadsThreadIdMessagesPostHeaders,
+ CreateMessageApiV1AssistantThreadsThreadIdMessagesPostPathParameters,
+ CreateMessageRequestDTO,
+ CreateMessageResponseDTO,
+ CreateThreadApiV1AssistantThreadsPostBody,
+ CreateThreadApiV1AssistantThreadsPostHeaders,
+ CreateThreadResponseDTO,
+ ErrorResponseDTO,
+ FeedbackRequestDTO,
+ FeedbackResponseDTO,
+ GetThreadApiV1AssistantThreadsThreadIdGetHeaders,
+ GetThreadApiV1AssistantThreadsThreadIdGetPathParameters,
+ HTTPValidationErrorDTO,
+ HealthResponseDTO,
+ ListThreadsApiV1AssistantThreadsGetHeaders,
+ ListThreadsApiV1AssistantThreadsGetParams,
+ ReadinessResponseDTO,
+ RegenerateMessageApiV1AssistantMessagesMessageIdRegeneratePostHeaders,
+ RegenerateMessageApiV1AssistantMessagesMessageIdRegeneratePostPathParameters,
+ RegenerateResponseDTO,
+ RejectApiV1AssistantRejectPostHeaders,
+ RejectRequestDTO,
+ RestoreApiV1AssistantRestorePostHeaders,
+ RestoreRequestDTO,
+ RevertApiV1AssistantRevertPostHeaders,
+ RevertRequestDTO,
+ SubmitFeedbackApiV1AssistantMessagesMessageIdFeedbackPostHeaders,
+ SubmitFeedbackApiV1AssistantMessagesMessageIdFeedbackPostPathParameters,
+ ThreadDetailResponseDTO,
+ ThreadListResponseDTO,
+ ThreadSummaryDTO,
+ UndoApiV1AssistantUndoPostHeaders,
+ UndoRequestDTO,
+ UpdateThreadApiV1AssistantThreadsThreadIdPatchHeaders,
+ UpdateThreadApiV1AssistantThreadsThreadIdPatchPathParameters,
+ UpdateThreadRequestDTO,
+} from './sigNozAIAssistantAPI.schemas';
+
+import {
+ GeneratedAPIInstance,
+ getGeneratedAPIQueryKeyHeaders,
+} from '../generatedAPIInstance';
+import type { ErrorType, BodyType } from '../generatedAPIInstance';
+
+/**
+ * @summary Health
+ */
+export const healthHealthGet = (signal?: AbortSignal) => {
+ return GeneratedAPIInstance<HealthResponseDTO>({
+ url: `/health`,
+ method: 'GET',
+ signal,
+ });
+};
+
+export const getHealthHealthGetQueryKey = () => {
+ return [`/health`] as const;
+};
+
+export const getHealthHealthGetQueryOptions = <
+ TData = Awaited<ReturnType<typeof healthHealthGet>>,
+ TError = ErrorType<unknown>,
+>(options?: {
+ query?: UseQueryOptions<
+ Awaited<ReturnType<typeof healthHealthGet>>,
+ TError,
+ TData
+ >;
+}) => {
+ const { query: queryOptions } = options ?? {};
+
+ const queryKey = queryOptions?.queryKey ?? getHealthHealthGetQueryKey();
+
+ const queryFn: QueryFunction<Awaited<ReturnType<typeof healthHealthGet>>> = ({
+ signal,
+ }) => healthHealthGet(signal);
+
+ return { queryKey, queryFn, ...queryOptions } as UseQueryOptions<
+ Awaited<ReturnType<typeof healthHealthGet>>,
+ TError,
+ TData
+ > & { queryKey: QueryKey };
+};
+
+export type HealthHealthGetQueryResult = NonNullable<
+ Awaited<ReturnType<typeof healthHealthGet>>
+>;
+export type HealthHealthGetQueryError = ErrorType<unknown>;
+
+/**
+ * @summary Health
+ */
+
+export function useHealthHealthGet<
+ TData = Awaited<ReturnType<typeof healthHealthGet>>,
+ TError = ErrorType<unknown>,
+>(options?: {
+ query?: UseQueryOptions<
+ Awaited<ReturnType<typeof healthHealthGet>>,
+ TError,
+ TData
+ >;
+}): UseQueryResult<TData, TError> & { queryKey: QueryKey } {
+ const queryOptions = getHealthHealthGetQueryOptions(options);
+
+ const query = useQuery(queryOptions) as UseQueryResult<TData, TError> & {
+ queryKey: QueryKey;
+ };
+
+ query.queryKey = queryOptions.queryKey;
+
+ return query;
+}
+
+/**
+ * @summary Health
+ */
+export const invalidateHealthHealthGet = async (
+ queryClient: QueryClient,
+ options?: InvalidateOptions,
+): Promise<QueryClient> => {
+ await queryClient.invalidateQueries(
+ { queryKey: getHealthHealthGetQueryKey() },
+ options,
+ );
+
+ return queryClient;
+};
+
+/**
+ * @summary Ready
+ */
+export const readyReadyGet = (signal?: AbortSignal) => {
+ return GeneratedAPIInstance<ReadinessResponseDTO>({
+ url: `/ready`,
+ method: 'GET',
+ signal,
+ });
+};
+
+export const getReadyReadyGetQueryKey = () => {
+ return [`/ready`] as const;
+};
+
+export const getReadyReadyGetQueryOptions = <
+ TData = Awaited<ReturnType<typeof readyReadyGet>>,
+ TError = ErrorType<ReadinessResponseDTO>,
+>(options?: {
+ query?: UseQueryOptions<
+ Awaited<ReturnType<typeof readyReadyGet>>,
+ TError,
+ TData
+ >;
+}) => {
+ const { query: queryOptions } = options ?? {};
+
+ const queryKey = queryOptions?.queryKey ?? getReadyReadyGetQueryKey();
+
+ const queryFn: QueryFunction<Awaited<ReturnType<typeof readyReadyGet>>> = ({
+ signal,
+ }) => readyReadyGet(signal);
+
+ return { queryKey, queryFn, ...queryOptions } as UseQueryOptions<
+ Awaited<ReturnType<typeof readyReadyGet>>,
+ TError,
+ TData
+ > & { queryKey: QueryKey };
+};
+
+export type ReadyReadyGetQueryResult = NonNullable<
+ Awaited<ReturnType<typeof readyReadyGet>>
+>;
+export type ReadyReadyGetQueryError = ErrorType<ReadinessResponseDTO>;
+
+/**
+ * @summary Ready
+ */
+
+export function useReadyReadyGet<
+ TData = Awaited<ReturnType<typeof readyReadyGet>>,
+ TError = ErrorType<ReadinessResponseDTO>,
+>(options?: {
+ query?: UseQueryOptions<
+ Awaited<ReturnType<typeof readyReadyGet>>,
+ TError,
+ TData
+ >;
+}): UseQueryResult<TData, TError> & { queryKey: QueryKey } {
+ const queryOptions = getReadyReadyGetQueryOptions(options);
+
+ const query = useQuery(queryOptions) as UseQueryResult<TData, TError> & {
+ queryKey: QueryKey;
+ };
+
+ query.queryKey = queryOptions.queryKey;
+
+ return query;
+}
+
+/**
+ * @summary Ready
+ */
+export const invalidateReadyReadyGet = async (
+ queryClient: QueryClient,
+ options?: InvalidateOptions,
+): Promise<QueryClient> => {
+ await queryClient.invalidateQueries(
+ { queryKey: getReadyReadyGetQueryKey() },
+ options,
+ );
+
+ return queryClient;
+};
+
+/**
+ * @summary Create a new thread
+ */
+export const createThreadApiV1AssistantThreadsPost = (
+ createThreadApiV1AssistantThreadsPostBody: BodyType<CreateThreadApiV1AssistantThreadsPostBody>,
+ headers?: CreateThreadApiV1AssistantThreadsPostHeaders,
+ signal?: AbortSignal,
+) => {
+ return GeneratedAPIInstance<CreateThreadResponseDTO>({
+ url: `/api/v1/assistant/threads`,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...headers },
+ data: createThreadApiV1AssistantThreadsPostBody,
+ signal,
+ });
+};
+
+export const getCreateThreadApiV1AssistantThreadsPostMutationOptions = <
+ TError = ErrorType<ErrorResponseDTO | HTTPValidationErrorDTO>,
+ TContext = unknown,
+>(options?: {
+ mutation?: UseMutationOptions<
+ Awaited<ReturnType<typeof createThreadApiV1AssistantThreadsPost>>,
+ TError,
+ {
+ data: BodyType<CreateThreadApiV1AssistantThreadsPostBody>;
+ headers?: CreateThreadApiV1AssistantThreadsPostHeaders;
+ },
+ TContext
+ >;
+}): UseMutationOptions<
+ Awaited<ReturnType<typeof createThreadApiV1AssistantThreadsPost>>,
+ TError,
+ {
+ data: BodyType<CreateThreadApiV1AssistantThreadsPostBody>;
+ headers?: CreateThreadApiV1AssistantThreadsPostHeaders;
+ },
+ TContext
+> => {
+ const mutationKey = ['createThreadApiV1AssistantThreadsPost'];
+ const { mutation: mutationOptions } = options
+ ? options.mutation &&
+ 'mutationKey' in options.mutation &&
+ options.mutation.mutationKey
+ ? options
+ : { ...options, mutation: { ...options.mutation, mutationKey } }
+ : { mutation: { mutationKey } };
+
+ const mutationFn: MutationFunction<
+ Awaited<ReturnType<typeof createThreadApiV1AssistantThreadsPost>>,
+ {
+ data: BodyType<CreateThreadApiV1AssistantThreadsPostBody>;
+ headers?: CreateThreadApiV1AssistantThreadsPostHeaders;
+ }
+ > = (props) => {
+ const { data, headers } = props ?? {};
+
+ return createThreadApiV1AssistantThreadsPost(data, headers);
+ };
+
+ return { mutationFn, ...mutationOptions };
+};
+
+export type CreateThreadApiV1AssistantThreadsPostMutationResult = NonNullable<
+ Awaited<ReturnType<typeof createThreadApiV1AssistantThreadsPost>>
+>;
+export type CreateThreadApiV1AssistantThreadsPostMutationBody =
+ BodyType<CreateThreadApiV1AssistantThreadsPostBody>;
+export type CreateThreadApiV1AssistantThreadsPostMutationError = ErrorType<
+ ErrorResponseDTO | HTTPValidationErrorDTO
+>;
+
+/**
+ * @summary Create a new thread
+ */
+export const useCreateThreadApiV1AssistantThreadsPost = <
+ TError = ErrorType<ErrorResponseDTO | HTTPValidationErrorDTO>,
+ TContext = unknown,
+>(options?: {
+ mutation?: UseMutationOptions<
+ Awaited<ReturnType<typeof createThreadApiV1AssistantThreadsPost>>,
+ TError,
+ {
+ data: BodyType<CreateThreadApiV1AssistantThreadsPostBody>;
+ headers?: CreateThreadApiV1AssistantThreadsPostHeaders;
+ },
+ TContext
+ >;
+}): UseMutationResult<
+ Awaited<ReturnType<typeof createThreadApiV1AssistantThreadsPost>>,
+ TError,
+ {
+ data: BodyType<CreateThreadApiV1AssistantThreadsPostBody>;
+ headers?: CreateThreadApiV1AssistantThreadsPostHeaders;
+ },
+ TContext
+> => {
+ const mutationOptions =
+ getCreateThreadApiV1AssistantThreadsPostMutationOptions(options);
+
+ return useMutation(mutationOptions);
+};
+/**
+ * Cursor-based pagination, sorted by updatedAt desc. Use `archived=true|false|all` to filter.
+ * @summary List threads
+ */
+export const listThreadsApiV1AssistantThreadsGet = (
+ params?: ListThreadsApiV1AssistantThreadsGetParams,
+ headers?: ListThreadsApiV1AssistantThreadsGetHeaders,
+ signal?: AbortSignal,
+) => {
+ return GeneratedAPIInstance<ThreadListResponseDTO>({
+ url: `/api/v1/assistant/threads`,
+ method: 'GET',
+ headers,
+ params,
+ signal,
+ });
+};
+
+export const getListThreadsApiV1AssistantThreadsGetQueryKey = (
+ params?: ListThreadsApiV1AssistantThreadsGetParams,
+ headers?: ListThreadsApiV1AssistantThreadsGetHeaders,
+) => {
+ return [
+ `/api/v1/assistant/threads`,
+ ...(params ? [params] : []),
+ ...getGeneratedAPIQueryKeyHeaders(headers),
+ ] as const;
+};
+
+export const getListThreadsApiV1AssistantThreadsGetQueryOptions = <
+ TData = Awaited<ReturnType<typeof listThreadsApiV1AssistantThreadsGet>>,
+ TError = ErrorType<ErrorResponseDTO | HTTPValidationErrorDTO>,
+>(
+ params?: ListThreadsApiV1AssistantThreadsGetParams,
+ headers?: ListThreadsApiV1AssistantThreadsGetHeaders,
+ options?: {
+ query?: UseQueryOptions<
+ Awaited<ReturnType<typeof listThreadsApiV1AssistantThreadsGet>>,
+ TError,
+ TData
+ >;
+ },
+) => {
+ const { query: queryOptions } = options ?? {};
+
+ const queryKey =
+ queryOptions?.queryKey ??
+ getListThreadsApiV1AssistantThreadsGetQueryKey(params, headers);
+
+ const queryFn: QueryFunction<
+ Awaited<ReturnType<typeof listThreadsApiV1AssistantThreadsGet>>
+ > = ({ signal }) =>
+ listThreadsApiV1AssistantThreadsGet(params, headers, signal);
+
+ return { queryKey, queryFn, ...queryOptions } as UseQueryOptions<
+ Awaited<ReturnType<typeof listThreadsApiV1AssistantThreadsGet>>,
+ TError,
+ TData
+ > & { queryKey: QueryKey };
+};
+
+export type ListThreadsApiV1AssistantThreadsGetQueryResult = NonNullable<
+ Awaited<ReturnType<typeof listThreadsApiV1AssistantThreadsGet>>
+>;
+export type ListThreadsApiV1AssistantThreadsGetQueryError = ErrorType<
+ ErrorResponseDTO | HTTPValidationErrorDTO
+>;
+
+/**
+ * @summary List threads
+ */
+
+export function useListThreadsApiV1AssistantThreadsGet<
+ TData = Awaited<ReturnType<typeof listThreadsApiV1AssistantThreadsGet>>,
+ TError = ErrorType<ErrorResponseDTO | HTTPValidationErrorDTO>,
+>(
+ params?: ListThreadsApiV1AssistantThreadsGetParams,
+ headers?: ListThreadsApiV1AssistantThreadsGetHeaders,
+ options?: {
+ query?: UseQueryOptions<
+ Awaited<ReturnType<typeof listThreadsApiV1AssistantThreadsGet>>,
+ TError,
+ TData
+ >;
+ },
+): UseQueryResult<TData, TError> & { queryKey: QueryKey } {
+ const queryOptions = getListThreadsApiV1AssistantThreadsGetQueryOptions(
+ params,
+ headers,
+ options,
+ );
+
+ const query = useQuery(queryOptions) as UseQueryResult<TData, TError> & {
+ queryKey: QueryKey;
+ };
+
+ query.queryKey = queryOptions.queryKey;
+
+ return query;
+}
+
+/**
+ * @summary List threads
+ */
+export const invalidateListThreadsApiV1AssistantThreadsGet = async (
+ queryClient: QueryClient,
+ params?: ListThreadsApiV1AssistantThreadsGetParams,
+ headers?: ListThreadsApiV1AssistantThreadsGetHeaders,
+ options?: InvalidateOptions,
+): Promise<QueryClient> => {
+ await queryClient.invalidateQueries(
+ { queryKey: getListThreadsApiV1AssistantThreadsGetQueryKey(params, headers) },
+ options,
+ );
+
+ return queryClient;
+};
+
+/**
+ * Cold-start reconstruction path. Returns all messages, pending approval/clarification, and active execution.
+ * @summary Get thread with full conversation state
+ */
+export const getThreadApiV1AssistantThreadsThreadIdGet = (
+ { threadId }: GetThreadApiV1AssistantThreadsThreadIdGetPathParameters,
+ headers?: GetThreadApiV1AssistantThreadsThreadIdGetHeaders,
+ signal?: AbortSignal,
+) => {
+ return GeneratedAPIInstance<ThreadDetailResponseDTO>({
+ url: `/api/v1/assistant/threads/${threadId}`,
+ method: 'GET',
+ headers,
+ signal,
+ });
+};
+
+export const getGetThreadApiV1AssistantThreadsThreadIdGetQueryKey = (
+ { threadId }: GetThreadApiV1AssistantThreadsThreadIdGetPathParameters,
+ headers?: GetThreadApiV1AssistantThreadsThreadIdGetHeaders,
+) => {
+ return [
+ `/api/v1/assistant/threads/${threadId}`,
+ ...getGeneratedAPIQueryKeyHeaders(headers),
+ ] as const;
+};
+
+export const getGetThreadApiV1AssistantThreadsThreadIdGetQueryOptions = <
+ TData = Awaited<ReturnType<typeof getThreadApiV1AssistantThreadsThreadIdGet>>,
+ TError = ErrorType<ErrorResponseDTO | HTTPValidationErrorDTO>,
+>(
+ { threadId }: GetThreadApiV1AssistantThreadsThreadIdGetPathParameters,
+ headers?: GetThreadApiV1AssistantThreadsThreadIdGetHeaders,
+ options?: {
+ query?: UseQueryOptions<
+ Awaited<ReturnType<typeof getThreadApiV1AssistantThreadsThreadIdGet>>,
+ TError,
+ TData
+ >;
+ },
+) => {
+ const { query: queryOptions } = options ?? {};
+
+ const queryKey =
+ queryOptions?.queryKey ??
+ getGetThreadApiV1AssistantThreadsThreadIdGetQueryKey({ threadId }, headers);
+
+ const queryFn: QueryFunction<
+ Awaited<ReturnType<typeof getThreadApiV1AssistantThreadsThreadIdGet>>
+ > = ({ signal }) =>
+ getThreadApiV1AssistantThreadsThreadIdGet({ threadId }, headers, signal);
+
+ return {
+ queryKey,
+ queryFn,
+ enabled: !!threadId,
+ ...queryOptions,
+ } as UseQueryOptions<
+ Awaited<ReturnType<typeof getThreadApiV1AssistantThreadsThreadIdGet>>,
+ TError,
+ TData
+ > & { queryKey: QueryKey };
+};
+
+export type GetThreadApiV1AssistantThreadsThreadIdGetQueryResult = NonNullable<
+ Awaited<ReturnType<typeof getThreadApiV1AssistantThreadsThreadIdGet>>
+>;
+export type GetThreadApiV1AssistantThreadsThreadIdGetQueryError = ErrorType<
+ ErrorResponseDTO | HTTPValidationErrorDTO
+>;
+
+/**
+ * @summary Get thread with full conversation state
+ */
+
+export function useGetThreadApiV1AssistantThreadsThreadIdGet<
+ TData = Awaited<ReturnType<typeof getThreadApiV1AssistantThreadsThreadIdGet>>,
+ TError = ErrorType<ErrorResponseDTO | HTTPValidationErrorDTO>,
+>(
+ { threadId }: GetThreadApiV1AssistantThreadsThreadIdGetPathParameters,
+ headers?: GetThreadApiV1AssistantThreadsThreadIdGetHeaders,
+ options?: {
+ query?: UseQueryOptions<
+ Awaited<ReturnType<typeof getThreadApiV1AssistantThreadsThreadIdGet>>,
+ TError,
+ TData
+ >;
+ },
+): UseQueryResult<TData, TError> & { queryKey: QueryKey } {
+ const queryOptions = getGetThreadApiV1AssistantThreadsThreadIdGetQueryOptions(
+ { threadId },
+ headers,
+ options,
+ );
+
+ const query = useQuery(queryOptions) as UseQueryResult<TData, TError> & {
+ queryKey: QueryKey;
+ };
+
+ query.queryKey = queryOptions.queryKey;
+
+ return query;
+}
+
+/**
+ * @summary Get thread with full conversation state
+ */
+export const invalidateGetThreadApiV1AssistantThreadsThreadIdGet = async (
+ queryClient: QueryClient,
+ { threadId }: GetThreadApiV1AssistantThreadsThreadIdGetPathParameters,
+ headers?: GetThreadApiV1AssistantThreadsThreadIdGetHeaders,
+ options?: InvalidateOptions,
+): Promise<QueryClient> => {
+ await queryClient.invalidateQueries(
+ {
+ queryKey: getGetThreadApiV1AssistantThreadsThreadIdGetQueryKey(
+ { threadId },
+ headers,
+ ),
+ },
+ options,
+ );
+
+ return queryClient;
+};
+
+/**
+ * @summary Update thread (rename or archive/unarchive)
+ */
+export const updateThreadApiV1AssistantThreadsThreadIdPatch = (
+ { threadId }: UpdateThreadApiV1AssistantThreadsThreadIdPatchPathParameters,
+ updateThreadRequestDTO: BodyType<UpdateThreadRequestDTO>,
+ headers?: UpdateThreadApiV1AssistantThreadsThreadIdPatchHeaders,
+) => {
+ return GeneratedAPIInstance<ThreadSummaryDTO>({
+ url: `/api/v1/assistant/threads/${threadId}`,
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json', ...headers },
+ data: updateThreadRequestDTO,
+ });
+};
+
+export const getUpdateThreadApiV1AssistantThreadsThreadIdPatchMutationOptions =
+ <
+ TError = ErrorType<ErrorResponseDTO | HTTPValidationErrorDTO>,
+ TContext = unknown,
+ >(options?: {
+ mutation?: UseMutationOptions<
+ Awaited<ReturnType<typeof updateThreadApiV1AssistantThreadsThreadIdPatch>>,
+ TError,
+ {
+ pathParams: UpdateThreadApiV1AssistantThreadsThreadIdPatchPathParameters;
+ data: BodyType<UpdateThreadRequestDTO>;
+ headers?: UpdateThreadApiV1AssistantThreadsThreadIdPatchHeaders;
+ },
+ TContext
+ >;
+ }): UseMutationOptions<
+ Awaited<ReturnType<typeof updateThreadApiV1AssistantThreadsThreadIdPatch>>,
+ TError,
+ {
+ pathParams: UpdateThreadApiV1AssistantThreadsThreadIdPatchPathParameters;
+ data: BodyType<UpdateThreadRequestDTO>;
+ headers?: UpdateThreadApiV1AssistantThreadsThreadIdPatchHeaders;
+ },
+ TContext
+ > => {
+ const mutationKey = ['updateThreadApiV1AssistantThreadsThreadIdPatch'];
+ const { mutation: mutationOptions } = options
+ ? options.mutation &&
+ 'mutationKey' in options.mutation &&
+ options.mutation.mutationKey
+ ? options
+ : { ...options, mutation: { ...options.mutation, mutationKey } }
+ : { mutation: { mutationKey } };
+
+ const mutationFn: MutationFunction<
+ Awaited<ReturnType<typeof updateThreadApiV1AssistantThreadsThreadIdPatch>>,
+ {
+ pathParams: UpdateThreadApiV1AssistantThreadsThreadIdPatchPathParameters;
+ data: BodyType<UpdateThreadRequestDTO>;
+ headers?: UpdateThreadApiV1AssistantThreadsThreadIdPatchHeaders;
+ }
+ > = (props) => {
+ const { pathParams, data, headers } = props ?? {};
+
+ return updateThreadApiV1AssistantThreadsThreadIdPatch(
+ pathParams,
+ data,
+ headers,
+ );
+ };
+
+ return { mutationFn, ...mutationOptions };
+ };
+
+export type UpdateThreadApiV1AssistantThreadsThreadIdPatchMutationResult =
+ NonNullable<
+ Awaited<ReturnType<typeof updateThreadApiV1AssistantThreadsThreadIdPatch>>
+ >;
+export type UpdateThreadApiV1AssistantThreadsThreadIdPatchMutationBody =
+ BodyType<UpdateThreadRequestDTO>;
+export type UpdateThreadApiV1AssistantThreadsThreadIdPatchMutationError =
+ ErrorType<ErrorResponseDTO | HTTPValidationErrorDTO>;
+
+/**
+ * @summary Update thread (rename or archive/unarchive)
+ */
+export const useUpdateThreadApiV1AssistantThreadsThreadIdPatch = <
+ TError = ErrorType<ErrorResponseDTO | HTTPValidationErrorDTO>,
+ TContext = unknown,
+>(options?: {
+ mutation?: UseMutationOptions<
+ Awaited<ReturnType<typeof updateThreadApiV1AssistantThreadsThreadIdPatch>>,
+ TError,
+ {
+ pathParams: UpdateThreadApiV1AssistantThreadsThreadIdPatchPathParameters;
+ data: BodyType<UpdateThreadRequestDTO>;
+ headers?: UpdateThreadApiV1AssistantThreadsThreadIdPatchHeaders;
+ },
+ TContext
+ >;
+}): UseMutationResult<
+ Awaited<ReturnType<typeof updateThreadApiV1AssistantThreadsThreadIdPatch>>,
+ TError,
+ {
+ pathParams: UpdateThreadApiV1AssistantThreadsThreadIdPatchPathParameters;
+ data: BodyType<UpdateThreadRequestDTO>;
+ headers?: UpdateThreadApiV1AssistantThreadsThreadIdPatchHeaders;
+ },
+ TContext
+> => {
+ const mutationOptions =
+ getUpdateThreadApiV1AssistantThreadsThreadIdPatchMutationOptions(options);
+
+ return useMutation(mutationOptions);
+};
+/**
+ * Persists the user message, creates an execution (state: queued), kicks off the agent loop asynchronously, and returns immediately. Open `GET /executions/{executionId}/events` for the SSE stream.
+ * @summary Send a message and start execution
+ */
+export const createMessageApiV1AssistantThreadsThreadIdMessagesPost = (
+ {
+ threadId,
+ }: CreateMessageApiV1AssistantThreadsThreadIdMessagesPostPathParameters,
+ createMessageRequestDTO: BodyType<CreateMessageRequestDTO>,
+ headers?: CreateMessageApiV1AssistantThreadsThreadIdMessagesPostHeaders,
+ signal?: AbortSignal,
+) => {
+ return GeneratedAPIInstance<CreateMessageResponseDTO>({
+ url: `/api/v1/assistant/threads/${threadId}/messages`,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...headers },
+ data: createMessageRequestDTO,
+ signal,
+ });
+};
+
+export const getCreateMessageApiV1AssistantThreadsThreadIdMessagesPostMutationOptions =
+ <
+ TError = ErrorType<ErrorResponseDTO | HTTPValidationErrorDTO>,
+ TContext = unknown,
+ >(options?: {
+ mutation?: UseMutationOptions<
+ Awaited<
+ ReturnType<typeof createMessageApiV1AssistantThreadsThreadIdMessagesPost>
+ >,
+ TError,
+ {
+ pathParams: CreateMessageApiV1AssistantThreadsThreadIdMessagesPostPathParameters;
+ data: BodyType<CreateMessageRequestDTO>;
+ headers?: CreateMessageApiV1AssistantThreadsThreadIdMessagesPostHeaders;
+ },
+ TContext
+ >;
+ }): UseMutationOptions<
+ Awaited<
+ ReturnType<typeof createMessageApiV1AssistantThreadsThreadIdMessagesPost>
+ >,
+ TError,
+ {
+ pathParams: CreateMessageApiV1AssistantThreadsThreadIdMessagesPostPathParameters;
+ data: BodyType<CreateMessageRequestDTO>;
+ headers?: CreateMessageApiV1AssistantThreadsThreadIdMessagesPostHeaders;
+ },
+ TContext
+ > => {
+ const mutationKey = [
+ 'createMessageApiV1AssistantThreadsThreadIdMessagesPost',
+ ];
+ const { mutation: mutationOptions } = options
+ ? options.mutation &&
+ 'mutationKey' in options.mutation &&
+ options.mutation.mutationKey
+ ? options
+ : { ...options, mutation: { ...options.mutation, mutationKey } }
+ : { mutation: { mutationKey } };
+
+ const mutationFn: MutationFunction<
+ Awaited<
+ ReturnType<typeof createMessageApiV1AssistantThreadsThreadIdMessagesPost>
+ >,
+ {
+ pathParams: CreateMessageApiV1AssistantThreadsThreadIdMessagesPostPathParameters;
+ data: BodyType<CreateMessageRequestDTO>;
+ headers?: CreateMessageApiV1AssistantThreadsThreadIdMessagesPostHeaders;
+ }
+ > = (props) => {
+ const { pathParams, data, headers } = props ?? {};
+
+ return createMessageApiV1AssistantThreadsThreadIdMessagesPost(
+ pathParams,
+ data,
+ headers,
+ );
+ };
+
+ return { mutationFn, ...mutationOptions };
+ };
+
+export type CreateMessageApiV1AssistantThreadsThreadIdMessagesPostMutationResult =
+ NonNullable<
+ Awaited<
+ ReturnType<typeof createMessageApiV1AssistantThreadsThreadIdMessagesPost>
+ >
+ >;
+export type CreateMessageApiV1AssistantThreadsThreadIdMessagesPostMutationBody =
+ BodyType<CreateMessageRequestDTO>;
+export type CreateMessageApiV1AssistantThreadsThreadIdMessagesPostMutationError =
+ ErrorType<ErrorResponseDTO | HTTPValidationErrorDTO>;
+
+/**
+ * @summary Send a message and start execution
+ */
+export const useCreateMessageApiV1AssistantThreadsThreadIdMessagesPost = <
+ TError = ErrorType<ErrorResponseDTO | HTTPValidationErrorDTO>,
+ TContext = unknown,
+>(options?: {
+ mutation?: UseMutationOptions<
+ Awaited<
+ ReturnType<typeof createMessageApiV1AssistantThreadsThreadIdMessagesPost>
+ >,
+ TError,
+ {
+ pathParams: CreateMessageApiV1AssistantThreadsThreadIdMessagesPostPathParameters;
+ data: BodyType<CreateMessageRequestDTO>;
+ headers?: CreateMessageApiV1AssistantThreadsThreadIdMessagesPostHeaders;
+ },
+ TContext
+ >;
+}): UseMutationResult<
+ Awaited<
+ ReturnType<typeof createMessageApiV1AssistantThreadsThreadIdMessagesPost>
+ >,
+ TError,
+ {
+ pathParams: CreateMessageApiV1AssistantThreadsThreadIdMessagesPostPathParameters;
+ data: BodyType<CreateMessageRequestDTO>;
+ headers?: CreateMessageApiV1AssistantThreadsThreadIdMessagesPostHeaders;
+ },
+ TContext
+> => {
+ const mutationOptions =
+ getCreateMessageApiV1AssistantThreadsThreadIdMessagesPostMutationOptions(
+ options,
+ );
+
+ return useMutation(mutationOptions);
+};
+/**
+ * Clean-slate regeneration. Starts a fresh execution with conversation history up to (excluding) the original assistant response.
+ * @summary Regenerate assistant response
+ */
+export const regenerateMessageApiV1AssistantMessagesMessageIdRegeneratePost = (
+ {
+ messageId,
+ }: RegenerateMessageApiV1AssistantMessagesMessageIdRegeneratePostPathParameters,
+ headers?: RegenerateMessageApiV1AssistantMessagesMessageIdRegeneratePostHeaders,
+ signal?: AbortSignal,
+) => {
+ return GeneratedAPIInstance<RegenerateResponseDTO>({
+ url: `/api/v1/assistant/messages/${messageId}/regenerate`,
+ method: 'POST',
+ headers,
+ signal,
+ });
+};
+
+export const getRegenerateMessageApiV1AssistantMessagesMessageIdRegeneratePostMutationOptions =
+ <
+ TError = ErrorType<ErrorResponseDTO | HTTPValidationErrorDTO>,
+ TContext = unknown,
+ >(options?: {
+ mutation?: UseMutationOptions<
+ Awaited<
+ ReturnType<
+ typeof regenerateMessageApiV1AssistantMessagesMessageIdRegeneratePost
+ >
+ >,
+ TError,
+ {
+ pathParams: RegenerateMessageApiV1AssistantMessagesMessageIdRegeneratePostPathParameters;
+ headers?: RegenerateMessageApiV1AssistantMessagesMessageIdRegeneratePostHeaders;
+ },
+ TContext
+ >;
+ }): UseMutationOptions<
+ Awaited<
+ ReturnType<
+ typeof regenerateMessageApiV1AssistantMessagesMessageIdRegeneratePost
+ >
+ >,
+ TError,
+ {
+ pathParams: RegenerateMessageApiV1AssistantMessagesMessageIdRegeneratePostPathParameters;
+ headers?: RegenerateMessageApiV1AssistantMessagesMessageIdRegeneratePostHeaders;
+ },
+ TContext
+ > => {
+ const mutationKey = [
+ 'regenerateMessageApiV1AssistantMessagesMessageIdRegeneratePost',
+ ];
+ const { mutation: mutationOptions } = options
+ ? options.mutation &&
+ 'mutationKey' in options.mutation &&
+ options.mutation.mutationKey
+ ? options
+ : { ...options, mutation: { ...options.mutation, mutationKey } }
+ : { mutation: { mutationKey } };
+
+ const mutationFn: MutationFunction<
+ Awaited<
+ ReturnType<
+ typeof regenerateMessageApiV1AssistantMessagesMessageIdRegeneratePost
+ >
+ >,
+ {
+ pathParams: RegenerateMessageApiV1AssistantMessagesMessageIdRegeneratePostPathParameters;
+ headers?: RegenerateMessageApiV1AssistantMessagesMessageIdRegeneratePostHeaders;
+ }
+ > = (props) => {
+ const { pathParams, headers } = props ?? {};
+
+ return regenerateMessageApiV1AssistantMessagesMessageIdRegeneratePost(
+ pathParams,
+ headers,
+ );
+ };
+
+ return { mutationFn, ...mutationOptions };
+ };
+
+export type RegenerateMessageApiV1AssistantMessagesMessageIdRegeneratePostMutationResult =
+ NonNullable<
+ Awaited<
+ ReturnType<
+ typeof regenerateMessageApiV1AssistantMessagesMessageIdRegeneratePost
+ >
+ >
+ >;
+
+export type RegenerateMessageApiV1AssistantMessagesMessageIdRegeneratePostMutationError =
+ ErrorType<ErrorResponseDTO | HTTPValidationErrorDTO>;
+
+/**
+ * @summary Regenerate assistant response
+ */
+export const useRegenerateMessageApiV1AssistantMessagesMessageIdRegeneratePost =
+ <
+ TError = ErrorType<ErrorResponseDTO | HTTPValidationErrorDTO>,
+ TContext = unknown,
+ >(options?: {
+ mutation?: UseMutationOptions<
+ Awaited<
+ ReturnType<
+ typeof regenerateMessageApiV1AssistantMessagesMessageIdRegeneratePost
+ >
+ >,
+ TError,
+ {
+ pathParams: RegenerateMessageApiV1AssistantMessagesMessageIdRegeneratePostPathParameters;
+ headers?: RegenerateMessageApiV1AssistantMessagesMessageIdRegeneratePostHeaders;
+ },
+ TContext
+ >;
+ }): UseMutationResult<
+ Awaited<
+ ReturnType<
+ typeof regenerateMessageApiV1AssistantMessagesMessageIdRegeneratePost
+ >
+ >,
+ TError,
+ {
+ pathParams: RegenerateMessageApiV1AssistantMessagesMessageIdRegeneratePostPathParameters;
+ headers?: RegenerateMessageApiV1AssistantMessagesMessageIdRegeneratePostHeaders;
+ },
+ TContext
+ > => {
+ const mutationOptions =
+ getRegenerateMessageApiV1AssistantMessagesMessageIdRegeneratePostMutationOptions(
+ options,
+ );
+
+ return useMutation(mutationOptions);
+ };
+/**
+ * Triggers a replay execution that runs the stored tool call with exact params. Returns a new executionId — open SSE for that execution.
+ * @summary Approve a pending action
+ */
+export const approveApiV1AssistantApprovePost = (
+ approveRequestDTO: BodyType<ApproveRequestDTO>,
+ headers?: ApproveApiV1AssistantApprovePostHeaders,
+ signal?: AbortSignal,
+) => {
+ return GeneratedAPIInstance<ApproveResponseDTO>({
+ url: `/api/v1/assistant/approve`,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...headers },
+ data: approveRequestDTO,
+ signal,
+ });
+};
+
+export const getApproveApiV1AssistantApprovePostMutationOptions = <
+ TError = ErrorType<ErrorResponseDTO | HTTPValidationErrorDTO>,
+ TContext = unknown,
+>(options?: {
+ mutation?: UseMutationOptions<
+ Awaited<ReturnType<typeof approveApiV1AssistantApprovePost>>,
+ TError,
+ {
+ data: BodyType<ApproveRequestDTO>;
+ headers?: ApproveApiV1AssistantApprovePostHeaders;
+ },
+ TContext
+ >;
+}): UseMutationOptions<
+ Awaited<ReturnType<typeof approveApiV1AssistantApprovePost>>,
+ TError,
+ {
+ data: BodyType<ApproveRequestDTO>;
+ headers?: ApproveApiV1AssistantApprovePostHeaders;
+ },
+ TContext
+> => {
+ const mutationKey = ['approveApiV1AssistantApprovePost'];
+ const { mutation: mutationOptions } = options
+ ? options.mutation &&
+ 'mutationKey' in options.mutation &&
+ options.mutation.mutationKey
+ ? options
+ : { ...options, mutation: { ...options.mutation, mutationKey } }
+ : { mutation: { mutationKey } };
+
+ const mutationFn: MutationFunction<
+ Awaited<ReturnType<typeof approveApiV1AssistantApprovePost>>,
+ {
+ data: BodyType<ApproveRequestDTO>;
+ headers?: ApproveApiV1AssistantApprovePostHeaders;
+ }
+ > = (props) => {
+ const { data, headers } = props ?? {};
+
+ return approveApiV1AssistantApprovePost(data, headers);
+ };
+
+ return { mutationFn, ...mutationOptions };
+};
+
+export type ApproveApiV1AssistantApprovePostMutationResult = NonNullable<
+ Awaited<ReturnType<typeof approveApiV1AssistantApprovePost>>
+>;
+export type ApproveApiV1AssistantApprovePostMutationBody =
+ BodyType<ApproveRequestDTO>;
+export type ApproveApiV1AssistantApprovePostMutationError = ErrorType<
+ ErrorResponseDTO | HTTPValidationErrorDTO
+>;
+
+/**
+ * @summary Approve a pending action
+ */
+export const useApproveApiV1AssistantApprovePost = <
+ TError = ErrorType<ErrorResponseDTO | HTTPValidationErrorDTO>,
+ TContext = unknown,
+>(options?: {
+ mutation?: UseMutationOptions<
+ Awaited<ReturnType<typeof approveApiV1AssistantApprovePost>>,
+ TError,
+ {
+ data: BodyType<ApproveRequestDTO>;
+ headers?: ApproveApiV1AssistantApprovePostHeaders;
+ },
+ TContext
+ >;
+}): UseMutationResult<
+ Awaited<ReturnType<typeof approveApiV1AssistantApprovePost>>,
+ TError,
+ {
+ data: BodyType<ApproveRequestDTO>;
+ headers?: ApproveApiV1AssistantApprovePostHeaders;
+ },
+ TContext
+> => {
+ const mutationOptions =
+ getApproveApiV1AssistantApprovePostMutationOptions(options);
+
+ return useMutation(mutationOptions);
+};
+/**
+ * Marks the approval as rejected. The execution completes with no tool execution.
+ * @summary Reject a pending action
+ */
+export const rejectApiV1AssistantRejectPost = (
+ rejectRequestDTO: BodyType<RejectRequestDTO>,
+ headers?: RejectApiV1AssistantRejectPostHeaders,
+ signal?: AbortSignal,
+) => {
+ return GeneratedAPIInstance<void>({
+ url: `/api/v1/assistant/reject`,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...headers },
+ data: rejectRequestDTO,
+ signal,
+ });
+};
+
+export const getRejectApiV1AssistantRejectPostMutationOptions = <
+ TError = ErrorType<ErrorResponseDTO | HTTPValidationErrorDTO>,
+ TContext = unknown,
+>(options?: {
+ mutation?: UseMutationOptions<
+ Awaited<ReturnType<typeof rejectApiV1AssistantRejectPost>>,
+ TError,
+ {
+ data: BodyType<RejectRequestDTO>;
+ headers?: RejectApiV1AssistantRejectPostHeaders;
+ },
+ TContext
+ >;
+}): UseMutationOptions<
+ Awaited<ReturnType<typeof rejectApiV1AssistantRejectPost>>,
+ TError,
+ {
+ data: BodyType<RejectRequestDTO>;
+ headers?: RejectApiV1AssistantRejectPostHeaders;
+ },
+ TContext
+> => {
+ const mutationKey = ['rejectApiV1AssistantRejectPost'];
+ const { mutation: mutationOptions } = options
+ ? options.mutation &&
+ 'mutationKey' in options.mutation &&
+ options.mutation.mutationKey
+ ? options
+ : { ...options, mutation: { ...options.mutation, mutationKey } }
+ : { mutation: { mutationKey } };
+
+ const mutationFn: MutationFunction<
+ Awaited<ReturnType<typeof rejectApiV1AssistantRejectPost>>,
+ {
+ data: BodyType<RejectRequestDTO>;
+ headers?: RejectApiV1AssistantRejectPostHeaders;
+ }
+ > = (props) => {
+ const { data, headers } = props ?? {};
+
+ return rejectApiV1AssistantRejectPost(data, headers);
+ };
+
+ return { mutationFn, ...mutationOptions };
+};
+
+export type RejectApiV1AssistantRejectPostMutationResult = NonNullable<
+ Awaited<ReturnType<typeof rejectApiV1AssistantRejectPost>>
+>;
+export type RejectApiV1AssistantRejectPostMutationBody =
+ BodyType<RejectRequestDTO>;
+export type RejectApiV1AssistantRejectPostMutationError = ErrorType<
+ ErrorResponseDTO | HTTPValidationErrorDTO
+>;
+
+/**
+ * @summary Reject a pending action
+ */
+export const useRejectApiV1AssistantRejectPost = <
+ TError = ErrorType<ErrorResponseDTO | HTTPValidationErrorDTO>,
+ TContext = unknown,
+>(options?: {
+ mutation?: UseMutationOptions<
+ Awaited<ReturnType<typeof rejectApiV1AssistantRejectPost>>,
+ TError,
+ {
+ data: BodyType<RejectRequestDTO>;
+ headers?: RejectApiV1AssistantRejectPostHeaders;
+ },
+ TContext
+ >;
+}): UseMutationResult<
+ Awaited<ReturnType<typeof rejectApiV1AssistantRejectPost>>,
+ TError,
+ {
+ data: BodyType<RejectRequestDTO>;
+ headers?: RejectApiV1AssistantRejectPostHeaders;
+ },
+ TContext
+> => {
+ const mutationOptions =
+ getRejectApiV1AssistantRejectPostMutationOptions(options);
+
+ return useMutation(mutationOptions);
+};
+/**
+ * Provides structured answers to a clarification request. Persists the answers as a user transcript message, emits `user_message` as the first replayable event on the new execution stream, and resumes the agent with the answers as tool results.
+ * @summary Submit clarification answers
+ */
+export const clarifyApiV1AssistantClarifyPost = (
+ clarifyRequestDTO: BodyType<ClarifyRequestDTO>,
+ headers?: ClarifyApiV1AssistantClarifyPostHeaders,
+ signal?: AbortSignal,
+) => {
+ return GeneratedAPIInstance<ClarifyResponseDTO>({
+ url: `/api/v1/assistant/clarify`,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...headers },
+ data: clarifyRequestDTO,
+ signal,
+ });
+};
+
+export const getClarifyApiV1AssistantClarifyPostMutationOptions = <
+ TError = ErrorType<ErrorResponseDTO | HTTPValidationErrorDTO>,
+ TContext = unknown,
+>(options?: {
+ mutation?: UseMutationOptions<
+ Awaited<ReturnType<typeof clarifyApiV1AssistantClarifyPost>>,
+ TError,
+ {
+ data: BodyType<ClarifyRequestDTO>;
+ headers?: ClarifyApiV1AssistantClarifyPostHeaders;
+ },
+ TContext
+ >;
+}): UseMutationOptions<
+ Awaited<ReturnType<typeof clarifyApiV1AssistantClarifyPost>>,
+ TError,
+ {
+ data: BodyType<ClarifyRequestDTO>;
+ headers?: ClarifyApiV1AssistantClarifyPostHeaders;
+ },
+ TContext
+> => {
+ const mutationKey = ['clarifyApiV1AssistantClarifyPost'];
+ const { mutation: mutationOptions } = options
+ ? options.mutation &&
+ 'mutationKey' in options.mutation &&
+ options.mutation.mutationKey
+ ? options
+ : { ...options, mutation: { ...options.mutation, mutationKey } }
+ : { mutation: { mutationKey } };
+
+ const mutationFn: MutationFunction<
+ Awaited<ReturnType<typeof clarifyApiV1AssistantClarifyPost>>,
+ {
+ data: BodyType<ClarifyRequestDTO>;
+ headers?: ClarifyApiV1AssistantClarifyPostHeaders;
+ }
+ > = (props) => {
+ const { data, headers } = props ?? {};
+
+ return clarifyApiV1AssistantClarifyPost(data, headers);
+ };
+
+ return { mutationFn, ...mutationOptions };
+};
+
+export type ClarifyApiV1AssistantClarifyPostMutationResult = NonNullable<
+ Awaited<ReturnType<typeof clarifyApiV1AssistantClarifyPost>>
+>;
+export type ClarifyApiV1AssistantClarifyPostMutationBody =
+ BodyType<ClarifyRequestDTO>;
+export type ClarifyApiV1AssistantClarifyPostMutationError = ErrorType<
+ ErrorResponseDTO | HTTPValidationErrorDTO
+>;
+
+/**
+ * @summary Submit clarification answers
+ */
+export const useClarifyApiV1AssistantClarifyPost = <
+ TError = ErrorType<ErrorResponseDTO | HTTPValidationErrorDTO>,
+ TContext = unknown,
+>(options?: {
+ mutation?: UseMutationOptions<
+ Awaited<ReturnType<typeof clarifyApiV1AssistantClarifyPost>>,
+ TError,
+ {
+ data: BodyType<ClarifyRequestDTO>;
+ headers?: ClarifyApiV1AssistantClarifyPostHeaders;
+ },
+ TContext
+ >;
+}): UseMutationResult<
+ Awaited<ReturnType<typeof clarifyApiV1AssistantClarifyPost>>,
+ TError,
+ {
+ data: BodyType<ClarifyRequestDTO>;
+ headers?: ClarifyApiV1AssistantClarifyPostHeaders;
+ },
+ TContext
+> => {
+ const mutationOptions =
+ getClarifyApiV1AssistantClarifyPostMutationOptions(options);
+
+ return useMutation(mutationOptions);
+};
+/**
+ * Cooperative cancel. The agent loop finishes its current step, emits a truncated message if streaming, and transitions to canceled.
+ * @summary Cancel the active execution on a thread
+ */
+export const cancelApiV1AssistantCancelPost = (
+ cancelRequestDTO: BodyType<CancelRequestDTO>,
+ headers?: CancelApiV1AssistantCancelPostHeaders,
+ signal?: AbortSignal,
+) => {
+ return GeneratedAPIInstance<CancelResponseDTO>({
+ url: `/api/v1/assistant/cancel`,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...headers },
+ data: cancelRequestDTO,
+ signal,
+ });
+};
+
+export const getCancelApiV1AssistantCancelPostMutationOptions = <
+ TError = ErrorType<ErrorResponseDTO | HTTPValidationErrorDTO>,
+ TContext = unknown,
+>(options?: {
+ mutation?: UseMutationOptions<
+ Awaited<ReturnType<typeof cancelApiV1AssistantCancelPost>>,
+ TError,
+ {
+ data: BodyType<CancelRequestDTO>;
+ headers?: CancelApiV1AssistantCancelPostHeaders;
+ },
+ TContext
+ >;
+}): UseMutationOptions<
+ Awaited<ReturnType<typeof cancelApiV1AssistantCancelPost>>,
+ TError,
+ {
+ data: BodyType<CancelRequestDTO>;
+ headers?: CancelApiV1AssistantCancelPostHeaders;
+ },
+ TContext
+> => {
+ const mutationKey = ['cancelApiV1AssistantCancelPost'];
+ const { mutation: mutationOptions } = options
+ ? options.mutation &&
+ 'mutationKey' in options.mutation &&
+ options.mutation.mutationKey
+ ? options
+ : { ...options, mutation: { ...options.mutation, mutationKey } }
+ : { mutation: { mutationKey } };
+
+ const mutationFn: MutationFunction<
+ Awaited<ReturnType<typeof cancelApiV1AssistantCancelPost>>,
+ {
+ data: BodyType<CancelRequestDTO>;
+ headers?: CancelApiV1AssistantCancelPostHeaders;
+ }
+ > = (props) => {
+ const { data, headers } = props ?? {};
+
+ return cancelApiV1AssistantCancelPost(data, headers);
+ };
+
+ return { mutationFn, ...mutationOptions };
+};
+
+export type CancelApiV1AssistantCancelPostMutationResult = NonNullable<
+ Awaited<ReturnType<typeof cancelApiV1AssistantCancelPost>>
+>;
+export type CancelApiV1AssistantCancelPostMutationBody =
+ BodyType<CancelRequestDTO>;
+export type CancelApiV1AssistantCancelPostMutationError = ErrorType<
+ ErrorResponseDTO | HTTPValidationErrorDTO
+>;
+
+/**
+ * @summary Cancel the active execution on a thread
+ */
+export const useCancelApiV1AssistantCancelPost = <
+ TError = ErrorType<ErrorResponseDTO | HTTPValidationErrorDTO>,
+ TContext = unknown,
+>(options?: {
+ mutation?: UseMutationOptions<
+ Awaited<ReturnType<typeof cancelApiV1AssistantCancelPost>>,
+ TError,
+ {
+ data: BodyType<CancelRequestDTO>;
+ headers?: CancelApiV1AssistantCancelPostHeaders;
+ },
+ TContext
+ >;
+}): UseMutationResult<
+ Awaited<ReturnType<typeof cancelApiV1AssistantCancelPost>>,
+ TError,
+ {
+ data: BodyType<CancelRequestDTO>;
+ headers?: CancelApiV1AssistantCancelPostHeaders;
+ },
+ TContext
+> => {
+ const mutationOptions =
+ getCancelApiV1AssistantCancelPostMutationOptions(options);
+
+ return useMutation(mutationOptions);
+};
+/**
+ * Deletes the resource that was created by the assistant.
+ * @summary Undo a create action
+ */
+export const undoApiV1AssistantUndoPost = (
+ undoRequestDTO: BodyType<UndoRequestDTO>,
+ headers?: UndoApiV1AssistantUndoPostHeaders,
+ signal?: AbortSignal,
+) => {
+ return GeneratedAPIInstance<ActionResultResponseDTO>({
+ url: `/api/v1/assistant/undo`,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...headers },
+ data: undoRequestDTO,
+ signal,
+ });
+};
+
+export const getUndoApiV1AssistantUndoPostMutationOptions = <
+ TError = ErrorType<ErrorResponseDTO | HTTPValidationErrorDTO>,
+ TContext = unknown,
+>(options?: {
+ mutation?: UseMutationOptions<
+ Awaited<ReturnType<typeof undoApiV1AssistantUndoPost>>,
+ TError,
+ {
+ data: BodyType<UndoRequestDTO>;
+ headers?: UndoApiV1AssistantUndoPostHeaders;
+ },
+ TContext
+ >;
+}): UseMutationOptions<
+ Awaited<ReturnType<typeof undoApiV1AssistantUndoPost>>,
+ TError,
+ {
+ data: BodyType<UndoRequestDTO>;
+ headers?: UndoApiV1AssistantUndoPostHeaders;
+ },
+ TContext
+> => {
+ const mutationKey = ['undoApiV1AssistantUndoPost'];
+ const { mutation: mutationOptions } = options
+ ? options.mutation &&
+ 'mutationKey' in options.mutation &&
+ options.mutation.mutationKey
+ ? options
+ : { ...options, mutation: { ...options.mutation, mutationKey } }
+ : { mutation: { mutationKey } };
+
+ const mutationFn: MutationFunction<
+ Awaited<ReturnType<typeof undoApiV1AssistantUndoPost>>,
+ {
+ data: BodyType<UndoRequestDTO>;
+ headers?: UndoApiV1AssistantUndoPostHeaders;
+ }
+ > = (props) => {
+ const { data, headers } = props ?? {};
+
+ return undoApiV1AssistantUndoPost(data, headers);
+ };
+
+ return { mutationFn, ...mutationOptions };
+};
+
+export type UndoApiV1AssistantUndoPostMutationResult = NonNullable<
+ Awaited<ReturnType<typeof undoApiV1AssistantUndoPost>>
+>;
+export type UndoApiV1AssistantUndoPostMutationBody = BodyType<UndoRequestDTO>;
+export type UndoApiV1AssistantUndoPostMutationError = ErrorType<
+ ErrorResponseDTO | HTTPValidationErrorDTO
+>;
+
+/**
+ * @summary Undo a create action
+ */
+export const useUndoApiV1AssistantUndoPost = <
+ TError = ErrorType<ErrorResponseDTO | HTTPValidationErrorDTO>,
+ TContext = unknown,
+>(options?: {
+ mutation?: UseMutationOptions<
+ Awaited<ReturnType<typeof undoApiV1AssistantUndoPost>>,
+ TError,
+ {
+ data: BodyType<UndoRequestDTO>;
+ headers?: UndoApiV1AssistantUndoPostHeaders;
+ },
+ TContext
+ >;
+}): UseMutationResult<
+ Awaited<ReturnType<typeof undoApiV1AssistantUndoPost>>,
+ TError,
+ {
+ data: BodyType<UndoRequestDTO>;
+ headers?: UndoApiV1AssistantUndoPostHeaders;
+ },
+ TContext
+> => {
+ const mutationOptions = getUndoApiV1AssistantUndoPostMutationOptions(options);
+
+ return useMutation(mutationOptions);
+};
+/**
+ * Rolls back the resource to its pre-change snapshot.
+ * @summary Revert a modify action
+ */
+export const revertApiV1AssistantRevertPost = (
+ revertRequestDTO: BodyType<RevertRequestDTO>,
+ headers?: RevertApiV1AssistantRevertPostHeaders,
+ signal?: AbortSignal,
+) => {
+ return GeneratedAPIInstance<ActionResultResponseDTO>({
+ url: `/api/v1/assistant/revert`,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...headers },
+ data: revertRequestDTO,
+ signal,
+ });
+};
+
+export const getRevertApiV1AssistantRevertPostMutationOptions = <
+ TError = ErrorType<ErrorResponseDTO | HTTPValidationErrorDTO>,
+ TContext = unknown,
+>(options?: {
+ mutation?: UseMutationOptions<
+ Awaited<ReturnType<typeof revertApiV1AssistantRevertPost>>,
+ TError,
+ {
+ data: BodyType<RevertRequestDTO>;
+ headers?: RevertApiV1AssistantRevertPostHeaders;
+ },
+ TContext
+ >;
+}): UseMutationOptions<
+ Awaited<ReturnType<typeof revertApiV1AssistantRevertPost>>,
+ TError,
+ {
+ data: BodyType<RevertRequestDTO>;
+ headers?: RevertApiV1AssistantRevertPostHeaders;
+ },
+ TContext
+> => {
+ const mutationKey = ['revertApiV1AssistantRevertPost'];
+ const { mutation: mutationOptions } = options
+ ? options.mutation &&
+ 'mutationKey' in options.mutation &&
+ options.mutation.mutationKey
+ ? options
+ : { ...options, mutation: { ...options.mutation, mutationKey } }
+ : { mutation: { mutationKey } };
+
+ const mutationFn: MutationFunction<
+ Awaited<ReturnType<typeof revertApiV1AssistantRevertPost>>,
+ {
+ data: BodyType<RevertRequestDTO>;
+ headers?: RevertApiV1AssistantRevertPostHeaders;
+ }
+ > = (props) => {
+ const { data, headers } = props ?? {};
+
+ return revertApiV1AssistantRevertPost(data, headers);
+ };
+
+ return { mutationFn, ...mutationOptions };
+};
+
+export type RevertApiV1AssistantRevertPostMutationResult = NonNullable<
+ Awaited<ReturnType<typeof revertApiV1AssistantRevertPost>>
+>;
+export type RevertApiV1AssistantRevertPostMutationBody =
+ BodyType<RevertRequestDTO>;
+export type RevertApiV1AssistantRevertPostMutationError = ErrorType<
+ ErrorResponseDTO | HTTPValidationErrorDTO
+>;
+
+/**
+ * @summary Revert a modify action
+ */
+export const useRevertApiV1AssistantRevertPost = <
+ TError = ErrorType<ErrorResponseDTO | HTTPValidationErrorDTO>,
+ TContext = unknown,
+>(options?: {
+ mutation?: UseMutationOptions<
+ Awaited<ReturnType<typeof revertApiV1AssistantRevertPost>>,
+ TError,
+ {
+ data: BodyType<RevertRequestDTO>;
+ headers?: RevertApiV1AssistantRevertPostHeaders;
+ },
+ TContext
+ >;
+}): UseMutationResult<
+ Awaited<ReturnType<typeof revertApiV1AssistantRevertPost>>,
+ TError,
+ {
+ data: BodyType<RevertRequestDTO>;
+ headers?: RevertApiV1AssistantRevertPostHeaders;
+ },
+ TContext
+> => {
+ const mutationOptions =
+ getRevertApiV1AssistantRevertPostMutationOptions(options);
+
+ return useMutation(mutationOptions);
+};
+/**
+ * Recreates the resource from its pre-delete snapshot.
+ * @summary Restore a deleted resource
+ */
+export const restoreApiV1AssistantRestorePost = (
+ restoreRequestDTO: BodyType<RestoreRequestDTO>,
+ headers?: RestoreApiV1AssistantRestorePostHeaders,
+ signal?: AbortSignal,
+) => {
+ return GeneratedAPIInstance<ActionResultResponseDTO>({
+ url: `/api/v1/assistant/restore`,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...headers },
+ data: restoreRequestDTO,
+ signal,
+ });
+};
+
+export const getRestoreApiV1AssistantRestorePostMutationOptions = <
+ TError = ErrorType<ErrorResponseDTO | HTTPValidationErrorDTO>,
+ TContext = unknown,
+>(options?: {
+ mutation?: UseMutationOptions<
+ Awaited<ReturnType<typeof restoreApiV1AssistantRestorePost>>,
+ TError,
+ {
+ data: BodyType<RestoreRequestDTO>;
+ headers?: RestoreApiV1AssistantRestorePostHeaders;
+ },
+ TContext
+ >;
+}): UseMutationOptions<
+ Awaited<ReturnType<typeof restoreApiV1AssistantRestorePost>>,
+ TError,
+ {
+ data: BodyType<RestoreRequestDTO>;
+ headers?: RestoreApiV1AssistantRestorePostHeaders;
+ },
+ TContext
+> => {
+ const mutationKey = ['restoreApiV1AssistantRestorePost'];
+ const { mutation: mutationOptions } = options
+ ? options.mutation &&
+ 'mutationKey' in options.mutation &&
+ options.mutation.mutationKey
+ ? options
+ : { ...options, mutation: { ...options.mutation, mutationKey } }
+ : { mutation: { mutationKey } };
+
+ const mutationFn: MutationFunction<
+ Awaited<ReturnType<typeof restoreApiV1AssistantRestorePost>>,
+ {
+ data: BodyType<RestoreRequestDTO>;
+ headers?: RestoreApiV1AssistantRestorePostHeaders;
+ }
+ > = (props) => {
+ const { data, headers } = props ?? {};
+
+ return restoreApiV1AssistantRestorePost(data, headers);
+ };
+
+ return { mutationFn, ...mutationOptions };
+};
+
+export type RestoreApiV1AssistantRestorePostMutationResult = NonNullable<
+ Awaited<ReturnType<typeof restoreApiV1AssistantRestorePost>>
+>;
+export type RestoreApiV1AssistantRestorePostMutationBody =
+ BodyType<RestoreRequestDTO>;
+export type RestoreApiV1AssistantRestorePostMutationError = ErrorType<
+ ErrorResponseDTO | HTTPValidationErrorDTO
+>;
+
+/**
+ * @summary Restore a deleted resource
+ */
+export const useRestoreApiV1AssistantRestorePost = <
+ TError = ErrorType<ErrorResponseDTO | HTTPValidationErrorDTO>,
+ TContext = unknown,
+>(options?: {
+ mutation?: UseMutationOptions<
+ Awaited<ReturnType<typeof restoreApiV1AssistantRestorePost>>,
+ TError,
+ {
+ data: BodyType<RestoreRequestDTO>;
+ headers?: RestoreApiV1AssistantRestorePostHeaders;
+ },
+ TContext
+ >;
+}): UseMutationResult<
+ Awaited<ReturnType<typeof restoreApiV1AssistantRestorePost>>,
+ TError,
+ {
+ data: BodyType<RestoreRequestDTO>;
+ headers?: RestoreApiV1AssistantRestorePostHeaders;
+ },
+ TContext
+> => {
+ const mutationOptions =
+ getRestoreApiV1AssistantRestorePostMutationOptions(options);
+
+ return useMutation(mutationOptions);
+};
+/**
+ * @summary Submit feedback on an assistant message
+ */
+export const submitFeedbackApiV1AssistantMessagesMessageIdFeedbackPost = (
+ {
+ messageId,
+ }: SubmitFeedbackApiV1AssistantMessagesMessageIdFeedbackPostPathParameters,
+ feedbackRequestDTO: BodyType<FeedbackRequestDTO>,
+ headers?: SubmitFeedbackApiV1AssistantMessagesMessageIdFeedbackPostHeaders,
+ signal?: AbortSignal,
+) => {
+ return GeneratedAPIInstance<FeedbackResponseDTO>({
+ url: `/api/v1/assistant/messages/${messageId}/feedback`,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...headers },
+ data: feedbackRequestDTO,
+ signal,
+ });
+};
+
+export const getSubmitFeedbackApiV1AssistantMessagesMessageIdFeedbackPostMutationOptions =
+ <
+ TError = ErrorType<ErrorResponseDTO | HTTPValidationErrorDTO>,
+ TContext = unknown,
+ >(options?: {
+ mutation?: UseMutationOptions<
+ Awaited<
+ ReturnType<typeof submitFeedbackApiV1AssistantMessagesMessageIdFeedbackPost>
+ >,
+ TError,
+ {
+ pathParams: SubmitFeedbackApiV1AssistantMessagesMessageIdFeedbackPostPathParameters;
+ data: BodyType<FeedbackRequestDTO>;
+ headers?: SubmitFeedbackApiV1AssistantMessagesMessageIdFeedbackPostHeaders;
+ },
+ TContext
+ >;
+ }): UseMutationOptions<
+ Awaited<
+ ReturnType<typeof submitFeedbackApiV1AssistantMessagesMessageIdFeedbackPost>
+ >,
+ TError,
+ {
+ pathParams: SubmitFeedbackApiV1AssistantMessagesMessageIdFeedbackPostPathParameters;
+ data: BodyType<FeedbackRequestDTO>;
+ headers?: SubmitFeedbackApiV1AssistantMessagesMessageIdFeedbackPostHeaders;
+ },
+ TContext
+ > => {
+ const mutationKey = [
+ 'submitFeedbackApiV1AssistantMessagesMessageIdFeedbackPost',
+ ];
+ const { mutation: mutationOptions } = options
+ ? options.mutation &&
+ 'mutationKey' in options.mutation &&
+ options.mutation.mutationKey
+ ? options
+ : { ...options, mutation: { ...options.mutation, mutationKey } }
+ : { mutation: { mutationKey } };
+
+ const mutationFn: MutationFunction<
+ Awaited<
+ ReturnType<typeof submitFeedbackApiV1AssistantMessagesMessageIdFeedbackPost>
+ >,
+ {
+ pathParams: SubmitFeedbackApiV1AssistantMessagesMessageIdFeedbackPostPathParameters;
+ data: BodyType<FeedbackRequestDTO>;
+ headers?: SubmitFeedbackApiV1AssistantMessagesMessageIdFeedbackPostHeaders;
+ }
+ > = (props) => {
+ const { pathParams, data, headers } = props ?? {};
+
+ return submitFeedbackApiV1AssistantMessagesMessageIdFeedbackPost(
+ pathParams,
+ data,
+ headers,
+ );
+ };
+
+ return { mutationFn, ...mutationOptions };
+ };
+
+export type SubmitFeedbackApiV1AssistantMessagesMessageIdFeedbackPostMutationResult =
+ NonNullable<
+ Awaited<
+ ReturnType<typeof submitFeedbackApiV1AssistantMessagesMessageIdFeedbackPost>
+ >
+ >;
+export type SubmitFeedbackApiV1AssistantMessagesMessageIdFeedbackPostMutationBody =
+ BodyType<FeedbackRequestDTO>;
+export type SubmitFeedbackApiV1AssistantMessagesMessageIdFeedbackPostMutationError =
+ ErrorType<ErrorResponseDTO | HTTPValidationErrorDTO>;
+
+/**
+ * @summary Submit feedback on an assistant message
+ */
+export const useSubmitFeedbackApiV1AssistantMessagesMessageIdFeedbackPost = <
+ TError = ErrorType<ErrorResponseDTO | HTTPValidationErrorDTO>,
+ TContext = unknown,
+>(options?: {
+ mutation?: UseMutationOptions<
+ Awaited<
+ ReturnType<typeof submitFeedbackApiV1AssistantMessagesMessageIdFeedbackPost>
+ >,
+ TError,
+ {
+ pathParams: SubmitFeedbackApiV1AssistantMessagesMessageIdFeedbackPostPathParameters;
+ data: BodyType<FeedbackRequestDTO>;
+ headers?: SubmitFeedbackApiV1AssistantMessagesMessageIdFeedbackPostHeaders;
+ },
+ TContext
+ >;
+}): UseMutationResult<
+ Awaited<
+ ReturnType<typeof submitFeedbackApiV1AssistantMessagesMessageIdFeedbackPost>
+ >,
+ TError,
+ {
+ pathParams: SubmitFeedbackApiV1AssistantMessagesMessageIdFeedbackPostPathParameters;
+ data: BodyType<FeedbackRequestDTO>;
+ headers?: SubmitFeedbackApiV1AssistantMessagesMessageIdFeedbackPostHeaders;
+ },
+ TContext
+> => {
+ const mutationOptions =
+ getSubmitFeedbackApiV1AssistantMessagesMessageIdFeedbackPostMutationOptions(
+ options,
+ );
+
+ return useMutation(mutationOptions);
+};
diff --git a/frontend/src/api/ai-assistant/sigNozAIAssistantAPI.schemas.ts b/frontend/src/api/ai-assistant/sigNozAIAssistantAPI.schemas.ts
new file mode 100644
index 0000000000..baeb39533f
--- /dev/null
+++ b/frontend/src/api/ai-assistant/sigNozAIAssistantAPI.schemas.ts
@@ -0,0 +1,1317 @@
+/**
+ * ! Do not edit manually
+ * * The file has been auto-generated using Orval for SigNoz AI Assistant
+ * * regenerate with 'yarn generate:api'
+ * SigNoz AI Assistant API
+ * OpenAPI spec version: 0.1.0
+ */
+/**
+ * Result of an undo/revert/restore operation as reported to the client.
+ */
+export enum ActionLifecycleResultDTO {
+ deleted = 'deleted',
+ reverted = 'reverted',
+ restored = 'restored',
+}
+/**
+ * Shared response for undo, revert, restore.
+ */
+export interface ActionResultResponseDTO {
+ /**
+ * @type boolean
+ */
+ success?: boolean;
+ /**
+ * @type string
+ */
+ resourceType: string;
+ /**
+ * @type string
+ */
+ resourceId: string;
+ action: ActionLifecycleResultDTO;
+}
+
+export enum ApplyFilterSignalDTO {
+ logs = 'logs',
+ traces = 'traces',
+ metrics = 'metrics',
+}
+/**
+ * Resolved approval (approved/rejected/superseded) anchored on the assistant message that proposed it. Pending approvals never appear here - they live at the top-level pendingApproval slot.
+ */
+export interface ApprovalActionSummaryDTO {
+ /**
+ * @type string
+ * @format uuid
+ */
+ approvalId: string;
+ state: ApprovalStateDTO;
+ actionType: ApprovalActionTypeDTO;
+ /**
+ * @type string
+ */
+ resourceType: string;
+ /**
+ * @type string
+ */
+ summary: string;
+ /**
+ * @type string
+ * @format date-time
+ */
+ resolvedAt: string;
+}
+
+export enum ApprovalActionTypeDTO {
+ modify = 'modify',
+ delete = 'delete',
+}
+export enum ApprovalStateDTO {
+ pending = 'pending',
+ approved = 'approved',
+ rejected = 'rejected',
+ superseded = 'superseded',
+}
+export type ApprovalSummaryDTODiff = { [key: string]: unknown };
+
+export interface ApprovalSummaryDTO {
+ /**
+ * @type string
+ * @format uuid
+ */
+ approvalId: string;
+ /**
+ * @type string
+ * @format uuid
+ */
+ executionId: string;
+ /**
+ * @type string
+ * @format uuid
+ */
+ sourceMessageId: string;
+ state: ApprovalStateDTO;
+ actionType: ApprovalActionTypeDTO;
+ /**
+ * @type string
+ */
+ resourceType: string;
+ /**
+ * @type string
+ */
+ summary: string;
+ /**
+ * @type object
+ */
+ diff?: ApprovalSummaryDTODiff;
+ /**
+ * @type string
+ * @format date-time
+ */
+ createdAt: string;
+}
+
+export interface ApproveRequestDTO {
+ /**
+ * @type string
+ * @format uuid
+ */
+ approvalId: string;
+}
+
+/**
+ * Approve starts a new execution for the replay.
+ */
+export interface ApproveResponseDTO {
+ /**
+ * @type string
+ * @format uuid
+ */
+ executionId: string;
+}
+
+export interface CancelRequestDTO {
+ /**
+ * @type string
+ * @format uuid
+ */
+ threadId: string;
+}
+
+export interface CancelResponseDTO {
+ /**
+ * @type string
+ * @format uuid
+ */
+ executionId: string;
+ previousState: ExecutionStateDTO;
+ state: ExecutionStateDTO;
+}
+
+export type ClarificationFieldDTOOptions = string[] | null;
+
+export type ClarificationFieldDTODefault = string | string[] | null;
+
+export interface ClarificationFieldDTO {
+ /**
+ * @type string
+ */
+ id: string;
+ type: ClarificationFieldTypeDTO;
+ /**
+ * @type string
+ */
+ label: string;
+ /**
+ * @type boolean
+ */
+ required?: boolean;
+ options?: ClarificationFieldDTOOptions;
+ /**
+ * @type boolean
+ */
+ allowCustom?: boolean;
+ default?: ClarificationFieldDTODefault;
+}
+
+export enum ClarificationFieldTypeDTO {
+ text = 'text',
+ number = 'number',
+ select = 'select',
+ multi_select = 'multi_select',
+ boolean = 'boolean',
+}
+export enum ClarificationStateDTO {
+ pending = 'pending',
+ submitted = 'submitted',
+ superseded = 'superseded',
+}
+export type ClarificationSummaryDTODiscoveredContextAnyOf = {
+ [key: string]: unknown;
+};
+
+export type ClarificationSummaryDTODiscoveredContext =
+ ClarificationSummaryDTODiscoveredContextAnyOf | null;
+
+export interface ClarificationSummaryDTO {
+ /**
+ * @type string
+ * @format uuid
+ */
+ clarificationId: string;
+ /**
+ * @type string
+ * @format uuid
+ */
+ executionId: string;
+ /**
+ * @type string
+ * @format uuid
+ */
+ sourceMessageId: string;
+ state: ClarificationStateDTO;
+ /**
+ * @type string
+ */
+ message: string;
+ discoveredContext?: ClarificationSummaryDTODiscoveredContext;
+ /**
+ * @type array
+ */
+ fields?: ClarificationFieldDTO[];
+ /**
+ * @type string
+ * @format date-time
+ */
+ createdAt: string;
+}
+
+export type ClarifyRequestDTOAnswers = { [key: string]: unknown };
+
+export interface ClarifyRequestDTO {
+ /**
+ * @type string
+ * @format uuid
+ */
+ clarificationId: string;
+ /**
+ * @type object
+ */
+ answers: ClarifyRequestDTOAnswers;
+}
+
+/**
+ * Clarify starts a new execution for the continuation.
+ */
+export interface ClarifyResponseDTO {
+ /**
+ * @type string
+ * @format uuid
+ */
+ executionId: string;
+}
+
+export type CreateMessageRequestDTOContexts = MessageContextDTO[] | null;
+
+export type CreateMessageRequestDTOForkFromMessageId = string | null;
+
+export interface CreateMessageRequestDTO {
+ /**
+ * @type string
+ * @maxLength 20000
+ * @minLength 1
+ */
+ content: string;
+ contexts?: CreateMessageRequestDTOContexts;
+ forkFromMessageId?: CreateMessageRequestDTOForkFromMessageId;
+}
+
+export interface CreateMessageResponseDTO {
+ /**
+ * @type string
+ * @format uuid
+ */
+ executionId: string;
+}
+
+export type CreateThreadRequestDTOTitle = string | null;
+
+export interface CreateThreadRequestDTO {
+ title?: CreateThreadRequestDTOTitle;
+}
+
+export interface CreateThreadResponseDTO {
+ /**
+ * @type string
+ * @format uuid
+ */
+ threadId: string;
+}
+
+export type ErrorBodyDTOErrors = ErrorResponseAdditionalDTO[] | null;
+
+export type ErrorBodyDTOUrl = string | null;
+
+/**
+ * Inner error object — matches Go ErrorsJSON.
+ */
+export interface ErrorBodyDTO {
+ /**
+ * @type string
+ * @pattern ^[a-z_]+$
+ */
+ code: string;
+ /**
+ * @type string
+ */
+ message: string;
+ errors?: ErrorBodyDTOErrors;
+ url?: ErrorBodyDTOUrl;
+}
+
+/**
+ * Top-level error envelope — matches Go RenderErrorResponse.
+ */
+export interface ErrorResponseDTO {
+ /**
+ * @type string
+ */
+ status?: string;
+ error: ErrorBodyDTO;
+}
+
+/**
+ * Single sub-error entry — matches Go ErrorsResponseerroradditional.
+ */
+export interface ErrorResponseAdditionalDTO {
+ /**
+ * @type string
+ */
+ message: string;
+}
+
+export enum ExecutionStateDTO {
+ queued = 'queued',
+ running = 'running',
+ awaiting_approval = 'awaiting_approval',
+ awaiting_clarification = 'awaiting_clarification',
+ resumed = 'resumed',
+ completed = 'completed',
+ failed = 'failed',
+ canceled = 'canceled',
+}
+export enum FeedbackRatingDTO {
+ positive = 'positive',
+ negative = 'negative',
+}
+export type FeedbackRequestDTOComment = string | null;
+
+export interface FeedbackRequestDTO {
+ rating: FeedbackRatingDTO;
+ comment?: FeedbackRequestDTOComment;
+}
+
+export interface FeedbackResponseDTO {
+ [key: string]: unknown;
+}
+
+export interface HTTPValidationErrorDTO {
+ /**
+ * @type array
+ */
+ detail?: ValidationErrorDTO[];
+}
+
+export const HealthResponseDTOValue = {
+ /**
+ * @type string
+ */
+ status: 'ok',
+} as const;
+export type HealthResponseDTO = typeof HealthResponseDTOValue;
+
+export type MessageActionDTOActionMetadataId = string | null;
+
+export type MessageActionDTOResourceType = string | null;
+
+export type MessageActionDTOResourceId = string | null;
+
+export type MessageActionDTOState = string | null;
+
+export type MessageActionDTOInputAnyOf = { [key: string]: unknown };
+
+export type MessageActionDTOInput = MessageActionDTOInputAnyOf | null;
+
+export type MessageActionDTOTooltip = string | null;
+
+export type MessageActionDTOSignal = ApplyFilterSignalDTO | null;
+
+export type MessageActionDTOQueryAnyOf = { [key: string]: unknown };
+
+export type MessageActionDTOQuery = MessageActionDTOQueryAnyOf | null;
+
+export type MessageActionDTOUrl = string | null;
+
+/**
+ * Assistant action. Kind-specific requirements: rollback actions require actionMetadataId/resourceType/resourceId; follow_up requires input.intent; open_resource requires resourceType/resourceId; apply_filter requires signal and query; open_docs requires a SigNoz docs url.
+ */
+export interface MessageActionDTO {
+ kind: MessageActionKindDTO;
+ /**
+ * @type string
+ */
+ label: string;
+ actionMetadataId?: MessageActionDTOActionMetadataId;
+ resourceType?: MessageActionDTOResourceType;
+ resourceId?: MessageActionDTOResourceId;
+ state?: MessageActionDTOState;
+ input?: MessageActionDTOInput;
+ tooltip?: MessageActionDTOTooltip;
+ signal?: MessageActionDTOSignal;
+ query?: MessageActionDTOQuery;
+ url?: MessageActionDTOUrl;
+}
+
+export enum MessageActionKindDTO {
+ undo = 'undo',
+ revert = 'revert',
+ restore = 'restore',
+ follow_up = 'follow_up',
+ open_resource = 'open_resource',
+ open_docs = 'open_docs',
+ apply_filter = 'apply_filter',
+}
+export enum MessageContentTypeDTO {
+ markdown = 'markdown',
+}
+/**
+ * "auto" if derived from current page; "mention" if explicitly @-picked.
+ */
+export enum MessageContextDTOSource {
+ auto = 'auto',
+ mention = 'mention',
+}
+/**
+ * Resource taxonomy. Use metadata.page for concrete page identity.
+ */
+export enum MessageContextDTOType {
+ dashboard = 'dashboard',
+ alert = 'alert',
+ saved_view = 'saved_view',
+ logs_explorer = 'logs_explorer',
+ traces_explorer = 'traces_explorer',
+ metrics_explorer = 'metrics_explorer',
+ service = 'service',
+}
+/**
+ * Required for resource-detail pages: dashboard_detail, panel_edit, panel_fullscreen, alert_edit, service_detail. Always required for saved_view (mention-only — no list page in V1). Must be null for list/index/draft/detail-as-metadata pages such as dashboard_list, alert_list, alert_new, alerts_triggered, services_list, log_detail, and trace_detail.
+ */
+export type MessageContextDTOResourceId = string | null;
+
+export type MessageContextDTOResourceName = string | null;
+
+export type MessageContextDTOMetadataAnyOf = { [key: string]: unknown };
+
+/**
+ * Page-specific extras. metadata.page identifies list/draft pages and detail-as-metadata pages. Required non-empty metadata keys: panel_edit.widgetId, panel_fullscreen.widgetId, trace_detail.traceId. timeRange.{start,end} use Unix milliseconds.
+ */
+export type MessageContextDTOMetadata = MessageContextDTOMetadataAnyOf | null;
+
+export interface MessageContextDTO {
+ /**
+ * @enum auto,mention
+ * @type string
+ * @description "auto" if derived from current page; "mention" if explicitly @-picked.
+ */
+ source: MessageContextDTOSource;
+ /**
+ * @enum dashboard,alert,saved_view,logs_explorer,traces_explorer,metrics_explorer,service
+ * @type string
+ * @description Resource taxonomy. Use metadata.page for concrete page identity.
+ */
+ type: MessageContextDTOType;
+ /**
+ * @description Required for resource-detail pages: dashboard_detail, panel_edit, panel_fullscreen, alert_edit, service_detail. Always required for saved_view (mention-only — no list page in V1). Must be null for list/index/draft/detail-as-metadata pages such as dashboard_list, alert_list, alert_new, alerts_triggered, services_list, log_detail, and trace_detail.
+ */
+ resourceId?: MessageContextDTOResourceId;
+ resourceName?: MessageContextDTOResourceName;
+ /**
+ * @description Page-specific extras. metadata.page identifies list/draft pages and detail-as-metadata pages. Required non-empty metadata keys: panel_edit.widgetId, panel_fullscreen.widgetId, trace_detail.traceId. timeRange.{start,end} use Unix milliseconds.
+ */
+ metadata?: MessageContextDTOMetadata;
+}
+
+export enum MessageRoleDTO {
+ user = 'user',
+ assistant = 'assistant',
+ system = 'system',
+}
+export type MessageSummaryDTOContent = string | null;
+
+export type MessageSummaryDTOToolCallsAnyOfItem = { [key: string]: unknown };
+
+export type MessageSummaryDTOToolCalls =
+ | MessageSummaryDTOToolCallsAnyOfItem[]
+ | null;
+
+export type MessageSummaryDTOBlocksAnyOfItem = { [key: string]: unknown };
+
+export type MessageSummaryDTOBlocks = MessageSummaryDTOBlocksAnyOfItem[] | null;
+
+export type MessageSummaryDTOContexts = MessageContextDTO[] | null;
+
+export type MessageSummaryDTOActions = MessageActionDTO[] | null;
+
+/**
+ * Resolved approvals (approved/rejected/superseded) anchored to this assistant message. Pending approvals appear only at top-level pendingApproval, never here.
+ */
+export type MessageSummaryDTOApprovals = ApprovalActionSummaryDTO[] | null;
+
+export type MessageSummaryDTOFeedbackRating = FeedbackRatingDTO | null;
+
+export type MessageSummaryDTOFeedbackComment = string | null;
+
+export type MessageSummaryDTOExecutionId = string | null;
+
+export interface MessageSummaryDTO {
+ /**
+ * @type string
+ * @format uuid
+ */
+ messageId: string;
+ role: MessageRoleDTO;
+ contentType?: MessageContentTypeDTO;
+ content?: MessageSummaryDTOContent;
+ /**
+ * @type boolean
+ */
+ complete?: boolean;
+ toolCalls?: MessageSummaryDTOToolCalls;
+ blocks?: MessageSummaryDTOBlocks;
+ contexts?: MessageSummaryDTOContexts;
+ actions?: MessageSummaryDTOActions;
+ /**
+ * @description Resolved approvals (approved/rejected/superseded) anchored to this assistant message. Pending approvals appear only at top-level pendingApproval, never here.
+ */
+ approvals?: MessageSummaryDTOApprovals;
+ feedbackRating?: MessageSummaryDTOFeedbackRating;
+ feedbackComment?: MessageSummaryDTOFeedbackComment;
+ executionId?: MessageSummaryDTOExecutionId;
+ /**
+ * @type string
+ * @format date-time
+ */
+ createdAt: string;
+ /**
+ * @type string
+ * @format date-time
+ */
+ updatedAt: string;
+}
+
+export enum ReadinessChecksDTODatabase {
+ ok = 'ok',
+ failed = 'failed',
+}
+export enum ReadinessChecksDTORedis {
+ ok = 'ok',
+ failed = 'failed',
+}
+export interface ReadinessChecksDTO {
+ /**
+ * @type string
+ * @enum ok,failed
+ */
+ database: ReadinessChecksDTODatabase;
+ /**
+ * @type string
+ * @enum ok,failed
+ */
+ redis: ReadinessChecksDTORedis;
+}
+
+export enum ReadinessResponseDTOStatus {
+ ok = 'ok',
+ degraded = 'degraded',
+}
+export interface ReadinessResponseDTO {
+ /**
+ * @type string
+ * @enum ok,degraded
+ */
+ status: ReadinessResponseDTOStatus;
+ checks: ReadinessChecksDTO;
+}
+
+export interface RegenerateResponseDTO {
+ /**
+ * @type string
+ * @format uuid
+ */
+ executionId: string;
+}
+
+export interface RejectRequestDTO {
+ /**
+ * @type string
+ * @format uuid
+ */
+ approvalId: string;
+}
+
+export interface RestoreRequestDTO {
+ /**
+ * @type string
+ * @format uuid
+ */
+ actionMetadataId: string;
+}
+
+export interface RevertRequestDTO {
+ /**
+ * @type string
+ * @format uuid
+ */
+ actionMetadataId: string;
+}
+
+export type ThreadDetailResponseDTOTitle = string | null;
+
+export type ThreadDetailResponseDTOState = ExecutionStateDTO | null;
+
+export type ThreadDetailResponseDTOActiveExecutionId = string | null;
+
+export type ThreadDetailResponseDTOPendingApproval = ApprovalSummaryDTO | null;
+
+export type ThreadDetailResponseDTOPendingClarification =
+ ClarificationSummaryDTO | null;
+
+/**
+ * Full thread state for cold-start reconstruction (GET /threads/{id}).
+ */
+export interface ThreadDetailResponseDTO {
+ /**
+ * @type string
+ * @format uuid
+ */
+ threadId: string;
+ title?: ThreadDetailResponseDTOTitle;
+ state?: ThreadDetailResponseDTOState;
+ activeExecutionId?: ThreadDetailResponseDTOActiveExecutionId;
+ /**
+ * @type boolean
+ */
+ archived?: boolean;
+ /**
+ * @type string
+ * @format date-time
+ */
+ createdAt: string;
+ /**
+ * @type string
+ * @format date-time
+ */
+ updatedAt: string;
+ /**
+ * @type array
+ */
+ messages?: MessageSummaryDTO[];
+ pendingApproval?: ThreadDetailResponseDTOPendingApproval;
+ pendingClarification?: ThreadDetailResponseDTOPendingClarification;
+}
+
+export type ThreadListResponseDTONextCursor = string | null;
+
+export interface ThreadListResponseDTO {
+ /**
+ * @type array
+ */
+ threads: ThreadSummaryDTO[];
+ nextCursor?: ThreadListResponseDTONextCursor;
+ /**
+ * @type boolean
+ */
+ hasMore?: boolean;
+}
+
+export type ThreadSummaryDTOTitle = string | null;
+
+export type ThreadSummaryDTOState = ExecutionStateDTO | null;
+
+export type ThreadSummaryDTOActiveExecutionId = string | null;
+
+/**
+ * Thread list item.
+ */
+export interface ThreadSummaryDTO {
+ /**
+ * @type string
+ * @format uuid
+ */
+ threadId: string;
+ title?: ThreadSummaryDTOTitle;
+ state?: ThreadSummaryDTOState;
+ activeExecutionId?: ThreadSummaryDTOActiveExecutionId;
+ /**
+ * @type boolean
+ */
+ archived?: boolean;
+ /**
+ * @type string
+ * @format date-time
+ */
+ createdAt: string;
+ /**
+ * @type string
+ * @format date-time
+ */
+ updatedAt: string;
+}
+
+export interface UndoRequestDTO {
+ /**
+ * @type string
+ * @format uuid
+ */
+ actionMetadataId: string;
+}
+
+export type UpdateThreadRequestDTOTitle = string | null;
+
+export type UpdateThreadRequestDTOArchived = boolean | null;
+
+export interface UpdateThreadRequestDTO {
+ title?: UpdateThreadRequestDTOTitle;
+ archived?: UpdateThreadRequestDTOArchived;
+}
+
+export type ValidationErrorDTOLocItem = string | number;
+
+export type ValidationErrorDTOCtx = { [key: string]: unknown };
+
+export interface ValidationErrorDTO {
+ /**
+ * @type array
+ */
+ loc: ValidationErrorDTOLocItem[];
+ /**
+ * @type string
+ */
+ msg: string;
+ /**
+ * @type string
+ */
+ type: string;
+ input?: unknown;
+ /**
+ * @type object
+ */
+ ctx?: ValidationErrorDTOCtx;
+}
+
+export type ApprovalEventDTODiff = { [key: string]: unknown };
+
+export interface ApprovalEventDTO {
+ /**
+ * @type string
+ */
+ type?: string;
+ /**
+ * @type string
+ */
+ executionId: string;
+ /**
+ * @type integer
+ */
+ eventId?: number;
+ /**
+ * @type string
+ */
+ approvalId: string;
+ actionType: ApprovalActionTypeDTO;
+ /**
+ * @type string
+ */
+ resourceType: string;
+ /**
+ * @type string
+ */
+ summary: string;
+ /**
+ * @type object
+ */
+ diff?: ApprovalEventDTODiff;
+}
+
+export type ClarificationFieldEventDTOOptions = string[] | null;
+
+export type ClarificationFieldEventDTODefault = string | string[] | null;
+
+export interface ClarificationFieldEventDTO {
+ /**
+ * @type string
+ */
+ id: string;
+ type: ClarificationFieldTypeDTO;
+ /**
+ * @type string
+ */
+ label: string;
+ /**
+ * @type boolean
+ */
+ required?: boolean;
+ options?: ClarificationFieldEventDTOOptions;
+ /**
+ * @type boolean
+ */
+ allowCustom?: boolean;
+ default?: ClarificationFieldEventDTODefault;
+}
+
+export type ClarificationEventDTODiscoveredContextAnyOf = {
+ [key: string]: unknown;
+};
+
+export type ClarificationEventDTODiscoveredContext =
+ ClarificationEventDTODiscoveredContextAnyOf | null;
+
+export interface ClarificationEventDTO {
+ /**
+ * @type string
+ */
+ type?: string;
+ /**
+ * @type string
+ */
+ executionId: string;
+ /**
+ * @type integer
+ */
+ eventId?: number;
+ /**
+ * @type string
+ */
+ clarificationId: string;
+ /**
+ * @type string
+ */
+ message: string;
+ discoveredContext?: ClarificationEventDTODiscoveredContext;
+ /**
+ * @type array
+ */
+ fields?: ClarificationFieldEventDTO[];
+}
+
+export interface ConversationEventDTO {
+ /**
+ * @type string
+ */
+ type?: string;
+ /**
+ * @type string
+ */
+ threadId: string;
+ /**
+ * @type string
+ */
+ title: string;
+}
+
+export interface DoneEventDTO {
+ /**
+ * @type string
+ */
+ type?: string;
+ /**
+ * @type string
+ */
+ executionId: string;
+ /**
+ * @type integer
+ */
+ eventId?: number;
+ /**
+ * @type integer
+ */
+ tokenInput: number;
+ /**
+ * @type integer
+ */
+ tokenOutput: number;
+ /**
+ * @type integer
+ */
+ latencyMs: number;
+}
+
+export enum RetryActionDTO {
+ auto = 'auto',
+ manual = 'manual',
+ none = 'none',
+}
+export interface ErrorEventDTO {
+ /**
+ * @type string
+ */
+ type?: string;
+ /**
+ * @type string
+ */
+ executionId: string;
+ /**
+ * @type integer
+ */
+ eventId?: number;
+ error: ErrorBodyDTO;
+ retryAction?: RetryActionDTO;
+}
+
+export type MessageActionEventDTOActionMetadataId = string | null;
+
+export type MessageActionEventDTOResourceType = string | null;
+
+export type MessageActionEventDTOResourceId = string | null;
+
+export type MessageActionEventDTOState = string | null;
+
+export type MessageActionEventDTOInputAnyOf = { [key: string]: unknown };
+
+export type MessageActionEventDTOInput = MessageActionEventDTOInputAnyOf | null;
+
+export type MessageActionEventDTOTooltip = string | null;
+
+export type MessageActionEventDTOSignal = ApplyFilterSignalDTO | null;
+
+export type MessageActionEventDTOQueryAnyOf = { [key: string]: unknown };
+
+export type MessageActionEventDTOQuery = MessageActionEventDTOQueryAnyOf | null;
+
+export type MessageActionEventDTOUrl = string | null;
+
+/**
+ * Assistant action. Kind-specific requirements: rollback actions require actionMetadataId/resourceType/resourceId; follow_up requires input.intent; open_resource requires resourceType/resourceId; apply_filter requires signal and query; open_docs requires a SigNoz docs url.
+ */
+export interface MessageActionEventDTO {
+ kind: MessageActionKindDTO;
+ /**
+ * @type string
+ */
+ label: string;
+ actionMetadataId?: MessageActionEventDTOActionMetadataId;
+ resourceType?: MessageActionEventDTOResourceType;
+ resourceId?: MessageActionEventDTOResourceId;
+ state?: MessageActionEventDTOState;
+ input?: MessageActionEventDTOInput;
+ tooltip?: MessageActionEventDTOTooltip;
+ signal?: MessageActionEventDTOSignal;
+ query?: MessageActionEventDTOQuery;
+ url?: MessageActionEventDTOUrl;
+}
+
+export type MessageEventDTOActions = MessageActionEventDTO[] | null;
+
+export interface MessageEventDTO {
+ /**
+ * @type string
+ */
+ type?: string;
+ /**
+ * @type string
+ */
+ executionId: string;
+ /**
+ * @type integer
+ */
+ eventId?: number;
+ /**
+ * @type string
+ */
+ messageId: string;
+ /**
+ * @type string
+ */
+ delta: string;
+ /**
+ * @type boolean
+ */
+ done?: boolean;
+ actions?: MessageEventDTOActions;
+}
+
+export interface StatusEventDTO {
+ /**
+ * @type string
+ */
+ type?: string;
+ /**
+ * @type string
+ */
+ executionId: string;
+ /**
+ * @type integer
+ */
+ eventId?: number;
+ state: ExecutionStateDTO;
+}
+
+export interface ThinkingEventDTO {
+ /**
+ * @type string
+ */
+ type?: string;
+ /**
+ * @type string
+ */
+ executionId: string;
+ /**
+ * @type integer
+ */
+ eventId?: number;
+ /**
+ * @type string
+ */
+ content: string;
+}
+
+export type ToolCallEventDTOMessageId = string | null;
+
+export type ToolCallEventDTOToolCallId = string | null;
+
+export type ToolCallEventDTOToolInput = { [key: string]: unknown };
+
+export type ToolCallEventDTODisplayText = string | null;
+
+export type ToolCallEventDTOIconKey = string | null;
+
+export interface ToolCallEventDTO {
+ /**
+ * @type string
+ */
+ type?: string;
+ /**
+ * @type string
+ */
+ executionId: string;
+ /**
+ * @type integer
+ */
+ eventId?: number;
+ messageId?: ToolCallEventDTOMessageId;
+ toolCallId?: ToolCallEventDTOToolCallId;
+ /**
+ * @type string
+ */
+ toolName: string;
+ /**
+ * @type object
+ */
+ toolInput: ToolCallEventDTOToolInput;
+ displayText?: ToolCallEventDTODisplayText;
+ iconKey?: ToolCallEventDTOIconKey;
+}
+
+export type ToolResultEventDTOMessageId = string | null;
+
+export type ToolResultEventDTOToolCallId = string | null;
+
+export type ToolResultEventDTOResult = { [key: string]: unknown };
+
+export type ToolResultEventDTODisplayText = string | null;
+
+export type ToolResultEventDTOIconKey = string | null;
+
+export interface ToolResultEventDTO {
+ /**
+ * @type string
+ */
+ type?: string;
+ /**
+ * @type string
+ */
+ executionId: string;
+ /**
+ * @type integer
+ */
+ eventId?: number;
+ messageId?: ToolResultEventDTOMessageId;
+ toolCallId?: ToolResultEventDTOToolCallId;
+ /**
+ * @type boolean
+ */
+ success?: boolean;
+ /**
+ * @type string
+ */
+ toolName: string;
+ /**
+ * @type object
+ */
+ result: ToolResultEventDTOResult;
+ displayText?: ToolResultEventDTODisplayText;
+ iconKey?: ToolResultEventDTOIconKey;
+}
+
+export interface UserMessageEventDTO {
+ /**
+ * @type string
+ */
+ type?: string;
+ /**
+ * @type string
+ */
+ executionId: string;
+ /**
+ * @type integer
+ */
+ eventId?: number;
+ message: MessageSummaryDTO;
+}
+
+export type CreateThreadApiV1AssistantThreadsPostHeaders = {
+ /**
+ * @description SigNoz auth token (Bearer or raw JWT)
+ */
+ authorization?: string | null;
+ /**
+ * @description SigNoz instance base URL for multi-tenant deployments. Falls back to SIGNOZ_API_URL env var when omitted.
+ */
+ 'X-SigNoz-URL'?: string | null;
+};
+
+export type CreateThreadApiV1AssistantThreadsPostBody =
+ CreateThreadRequestDTO | null;
+
+export type ListThreadsApiV1AssistantThreadsGetParams = {
+ /**
+ * @enum true,false,all
+ * @type string
+ * @description Filter: true, false, or all
+ */
+ archived?: ListThreadsApiV1AssistantThreadsGetArchived;
+ /**
+ * @type integer
+ * @maximum 50
+ * @minimum 1
+ * @description undefined
+ */
+ limit?: number;
+ /**
+ * @description Opaque cursor from previous response's nextCursor
+ */
+ cursor?: string | null;
+ /**
+ * @type string
+ * @description Sort order. V1: updated_desc only
+ */
+ sort?: 'updated_desc';
+};
+
+export enum ListThreadsApiV1AssistantThreadsGetArchived {
+ true = 'true',
+ false = 'false',
+ all = 'all',
+}
+export type ListThreadsApiV1AssistantThreadsGetHeaders = {
+ /**
+ * @description SigNoz auth token (Bearer or raw JWT)
+ */
+ authorization?: string | null;
+ /**
+ * @description SigNoz instance base URL for multi-tenant deployments. Falls back to SIGNOZ_API_URL env var when omitted.
+ */
+ 'X-SigNoz-URL'?: string | null;
+};
+
+export type GetThreadApiV1AssistantThreadsThreadIdGetPathParameters = {
+ threadId: string;
+};
+export type GetThreadApiV1AssistantThreadsThreadIdGetHeaders = {
+ /**
+ * @description SigNoz auth token (Bearer or raw JWT)
+ */
+ authorization?: string | null;
+ /**
+ * @description SigNoz instance base URL for multi-tenant deployments. Falls back to SIGNOZ_API_URL env var when omitted.
+ */
+ 'X-SigNoz-URL'?: string | null;
+};
+
+export type UpdateThreadApiV1AssistantThreadsThreadIdPatchPathParameters = {
+ threadId: string;
+};
+export type UpdateThreadApiV1AssistantThreadsThreadIdPatchHeaders = {
+ /**
+ * @description SigNoz auth token (Bearer or raw JWT)
+ */
+ authorization?: string | null;
+ /**
+ * @description SigNoz instance base URL for multi-tenant deployments. Falls back to SIGNOZ_API_URL env var when omitted.
+ */
+ 'X-SigNoz-URL'?: string | null;
+};
+
+export type CreateMessageApiV1AssistantThreadsThreadIdMessagesPostPathParameters =
+ {
+ threadId: string;
+ };
+export type CreateMessageApiV1AssistantThreadsThreadIdMessagesPostHeaders = {
+ /**
+ * @description SigNoz auth token (Bearer or raw JWT)
+ */
+ authorization?: string | null;
+ /**
+ * @description SigNoz instance base URL for multi-tenant deployments. Falls back to SIGNOZ_API_URL env var when omitted.
+ */
+ 'X-SigNoz-URL'?: string | null;
+};
+
+export type RegenerateMessageApiV1AssistantMessagesMessageIdRegeneratePostPathParameters =
+ {
+ messageId: string;
+ };
+export type RegenerateMessageApiV1AssistantMessagesMessageIdRegeneratePostHeaders =
+ {
+ /**
+ * @description SigNoz auth token (Bearer or raw JWT)
+ */
+ authorization?: string | null;
+ /**
+ * @description SigNoz instance base URL for multi-tenant deployments. Falls back to SIGNOZ_API_URL env var when omitted.
+ */
+ 'X-SigNoz-URL'?: string | null;
+ };
+
+export type ApproveApiV1AssistantApprovePostHeaders = {
+ /**
+ * @description SigNoz auth token (Bearer or raw JWT)
+ */
+ authorization?: string | null;
+ /**
+ * @description SigNoz instance base URL for multi-tenant deployments. Falls back to SIGNOZ_API_URL env var when omitted.
+ */
+ 'X-SigNoz-URL'?: string | null;
+};
+
+export type RejectApiV1AssistantRejectPostHeaders = {
+ /**
+ * @description SigNoz auth token (Bearer or raw JWT)
+ */
+ authorization?: string | null;
+ /**
+ * @description SigNoz instance base URL for multi-tenant deployments. Falls back to SIGNOZ_API_URL env var when omitted.
+ */
+ 'X-SigNoz-URL'?: string | null;
+};
+
+export type ClarifyApiV1AssistantClarifyPostHeaders = {
+ /**
+ * @description SigNoz auth token (Bearer or raw JWT)
+ */
+ authorization?: string | null;
+ /**
+ * @description SigNoz instance base URL for multi-tenant deployments. Falls back to SIGNOZ_API_URL env var when omitted.
+ */
+ 'X-SigNoz-URL'?: string | null;
+};
+
+export type CancelApiV1AssistantCancelPostHeaders = {
+ /**
+ * @description SigNoz auth token (Bearer or raw JWT)
+ */
+ authorization?: string | null;
+ /**
+ * @description SigNoz instance base URL for multi-tenant deployments. Falls back to SIGNOZ_API_URL env var when omitted.
+ */
+ 'X-SigNoz-URL'?: string | null;
+};
+
+export type UndoApiV1AssistantUndoPostHeaders = {
+ /**
+ * @description SigNoz auth token (Bearer or raw JWT)
+ */
+ authorization?: string | null;
+ /**
+ * @description SigNoz instance base URL for multi-tenant deployments. Falls back to SIGNOZ_API_URL env var when omitted.
+ */
+ 'X-SigNoz-URL'?: string | null;
+};
+
+export type RevertApiV1AssistantRevertPostHeaders = {
+ /**
+ * @description SigNoz auth token (Bearer or raw JWT)
+ */
+ authorization?: string | null;
+ /**
+ * @description SigNoz instance base URL for multi-tenant deployments. Falls back to SIGNOZ_API_URL env var when omitted.
+ */
+ 'X-SigNoz-URL'?: string | null;
+};
+
+export type RestoreApiV1AssistantRestorePostHeaders = {
+ /**
+ * @description SigNoz auth token (Bearer or raw JWT)
+ */
+ authorization?: string | null;
+ /**
+ * @description SigNoz instance base URL for multi-tenant deployments. Falls back to SIGNOZ_API_URL env var when omitted.
+ */
+ 'X-SigNoz-URL'?: string | null;
+};
+
+export type SubmitFeedbackApiV1AssistantMessagesMessageIdFeedbackPostPathParameters =
+ {
+ messageId: string;
+ };
+export type SubmitFeedbackApiV1AssistantMessagesMessageIdFeedbackPostHeaders = {
+ /**
+ * @description SigNoz auth token (Bearer or raw JWT)
+ */
+ authorization?: string | null;
+ /**
+ * @description SigNoz instance base URL for multi-tenant deployments. Falls back to SIGNOZ_API_URL env var when omitted.
+ */
+ 'X-SigNoz-URL'?: string | null;
+};
diff --git a/frontend/src/api/generatedAPIInstance.ts b/frontend/src/api/generatedAPIInstance.ts
index d996b74308..03464d6eee 100644
--- a/frontend/src/api/generatedAPIInstance.ts
+++ b/frontend/src/api/generatedAPIInstance.ts
@@ -4,14 +4,46 @@ import {
interceptorsRequestResponse,
interceptorsResponse,
} from 'api';
-import axios, { AxiosError, AxiosRequestConfig } from 'axios';
import { ENVIRONMENT } from 'constants/env';
+import axios, { AxiosError, AxiosRequestConfig } from 'axios';
+
// generated API Instance
const generatedAPIAxiosInstance = axios.create({
baseURL: ENVIRONMENT.baseURL,
});
+let generatedAPIQueryKeyHeaderContext: Record<string, unknown> | undefined;
+
+export const setGeneratedAPIQueryKeyHeaderContext = <THeaders extends object>(
+ headers?: THeaders,
+): void => {
+ generatedAPIQueryKeyHeaderContext = headers
+ ? { ...(headers as Record<string, unknown>) }
+ : undefined;
+};
+
+const hashHeaderValue = (value: string): string => {
+ let hash = 0;
+
+ for (let index = 0; index < value.length; index += 1) {
+ hash = (hash * 31 + value.charCodeAt(index)) >>> 0;
+ }
+
+ return hash.toString(16);
+};
+
+const mergeHeaderRecord = (
+ target: Record<string, unknown>,
+ source: unknown,
+): Record<string, unknown> => {
+ if (!source || typeof source !== 'object') {
+ return target;
+ }
+
+ return Object.assign(target, source as Record<string, unknown>);
+};
+
export const GeneratedAPIInstance = <T>(
config: AxiosRequestConfig,
): Promise<T> => {
@@ -26,5 +58,59 @@ generatedAPIAxiosInstance.interceptors.response.use(
interceptorRejected,
);
+const getDefaultQueryKeyHeaders = (): Record<string, unknown> => {
+ const defaults = generatedAPIAxiosInstance.defaults
+ .headers as unknown as Record<string, unknown>;
+ const headers: Record<string, unknown> = {};
+ const methodKeys = new Set([
+ 'common',
+ 'delete',
+ 'get',
+ 'head',
+ 'options',
+ 'patch',
+ 'post',
+ 'put',
+ ]);
+
+ mergeHeaderRecord(headers, defaults?.common);
+ mergeHeaderRecord(headers, defaults?.get);
+
+ for (const [key, value] of Object.entries(defaults ?? {})) {
+ if (!methodKeys.has(key)) {
+ headers[key] = value;
+ }
+ }
+
+ return headers;
+};
+
+export const getGeneratedAPIQueryKeyHeaders = <THeaders extends object>(
+ headers?: THeaders,
+): [{ headers: Record<string, unknown> }] | [] => {
+ const mergedHeaders = {
+ ...getDefaultQueryKeyHeaders(),
+ ...generatedAPIQueryKeyHeaderContext,
+ ...(headers as Record<string, unknown> | undefined),
+ };
+
+ const queryKeyHeaders = Object.fromEntries(
+ Object.entries(mergedHeaders)
+ .filter(([, value]) => value !== undefined)
+ .sort(([left], [right]) => left.localeCompare(right))
+ .map(([key, value]) => {
+ if (key.toLowerCase() === 'authorization' && typeof value === 'string') {
+ return [key, hashHeaderValue(value)];
+ }
+
+ return [key, value];
+ }),
+ );
+
+ return Object.keys(queryKeyHeaders).length
+ ? [{ headers: queryKeyHeaders }]
+ : [];
+};
+
export type ErrorType<Error> = AxiosError<Error>;
export type BodyType<BodyData> = BodyData;
diff --git a/frontend/src/components/HeaderRightSection/HeaderRightSection.styles.scss b/frontend/src/components/HeaderRightSection/HeaderRightSection.styles.scss
index 913479ca63..e9e1b9058b 100644
--- a/frontend/src/components/HeaderRightSection/HeaderRightSection.styles.scss
+++ b/frontend/src/components/HeaderRightSection/HeaderRightSection.styles.scss
@@ -4,6 +4,49 @@
gap: 8px;
}
+.header-ai-assistant-btn-container {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+}
+
+.header-ai-assistant-btn__prefix {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+}
+
+.header-ai-assistant-btn__badge {
+ flex-shrink: 0;
+ display: inline-flex;
+ line-height: 0;
+ color: var(--accent-primary);
+}
+
+.header-ai-assistant-btn__pulse-dot {
+ position: relative;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ line-height: 0;
+ animation: header-ai-assistant-dot-pulse 1.5s ease-in-out infinite;
+ transform: scale(0.8);
+ margin-right: -12px;
+}
+
+@keyframes header-ai-assistant-dot-pulse {
+ 0%,
+ 100% {
+ opacity: 1;
+ transform: scale(1);
+ }
+
+ 50% {
+ opacity: 0.35;
+ transform: scale(0.82);
+ }
+}
+
.share-modal-content,
.feedback-modal-container {
display: flex;
diff --git a/frontend/src/components/HeaderRightSection/HeaderRightSection.tsx b/frontend/src/components/HeaderRightSection/HeaderRightSection.tsx
index 7bc0da5cf4..004bf3ffa3 100644
--- a/frontend/src/components/HeaderRightSection/HeaderRightSection.tsx
+++ b/frontend/src/components/HeaderRightSection/HeaderRightSection.tsx
@@ -1,8 +1,17 @@
import { useCallback, useState } from 'react';
import { useLocation } from 'react-router-dom';
-import { Button, Popover } from 'antd';
+import { Dot, Sparkles } from '@signozhq/icons';
+import { Button } from '@signozhq/ui/button';
+import { Tooltip } from '@signozhq/ui/tooltip';
+import { Popover } from 'antd';
import logEvent from 'api/common/logEvent';
+import {
+ openAIAssistant,
+ useAIAssistantStore,
+} from 'container/AIAssistant/store/useAIAssistantStore';
+import { selectPendingUserInputStreamCount } from 'container/AIAssistant/store/pendingInputSelectors';
import { useGetTenantLicense } from 'hooks/useGetTenantLicense';
+import { useIsAIAssistantEnabled } from 'hooks/useIsAIAssistantEnabled';
import { Globe, Inbox, SquarePen } from '@signozhq/icons';
import AnnouncementsModal from './AnnouncementsModal';
@@ -29,6 +38,7 @@ function HeaderRightSection({
const [openAnnouncementsModal, setOpenAnnouncementsModal] = useState(false);
const { isCloudUser, isEnterpriseSelfHostedUser } = useGetTenantLicense();
+ const isAIAssistantEnabled = useIsAIAssistantEnabled();
const handleOpenFeedbackModal = useCallback((): void => {
logEvent('Feedback: Clicked', {
@@ -67,9 +77,46 @@ function HeaderRightSection({
};
const isLicenseEnabled = isEnterpriseSelfHostedUser || isCloudUser;
+ const isDrawerOpen = useAIAssistantStore((s) => s.isDrawerOpen);
+ const isModalOpen = useAIAssistantStore((s) => s.isModalOpen);
+ const pendingUserInputCount: number = useAIAssistantStore(
+ selectPendingUserInputStreamCount,
+ );
+ const showHeaderPendingBadge =
+ pendingUserInputCount > 0 && !isDrawerOpen && !isModalOpen;
return (
<div className="header-right-section-container">
+ {isAIAssistantEnabled && !isDrawerOpen && (
+ <div className="header-ai-assistant-btn-container">
+ {showHeaderPendingBadge ? (
+ <span className="header-ai-assistant-btn__badge" aria-hidden>
+ <span className="header-ai-assistant-btn__pulse-dot">
+ <Dot size={36} />
+ </span>
+ </span>
+ ) : null}
+
+ <Tooltip title="AI Assistant">
+ <Button
+ variant="solid"
+ color="secondary"
+ onClick={openAIAssistant}
+ aria-label={
+ showHeaderPendingBadge
+ ? pendingUserInputCount === 1
+ ? 'Open AI Assistant, 1 action needs your response'
+ : `Open AI Assistant, ${pendingUserInputCount} actions need your response`
+ : 'Open AI Assistant'
+ }
+ prefix={<Sparkles size={14} color="var(--primary)" />}
+ >
+ AI Assistant
+ </Button>
+ </Tooltip>
+ </div>
+ )}
+
{enableFeedback && isLicenseEnabled && (
<Popover
rootClassName="header-section-popover-root"
@@ -83,12 +130,13 @@ function HeaderRightSection({
onOpenChange={handleOpenFeedbackModalChange}
>
<Button
- className="share-feedback-btn periscope-btn ghost"
- icon={<SquarePen size={14} />}
+ variant="ghost"
+ size="icon"
+ className="share-feedback-btn"
+ aria-label="Feedback"
+ prefix={<SquarePen size={14} />}
onClick={handleOpenFeedbackModal}
- >
- Feedback
- </Button>
+ />
</Popover>
)}
@@ -105,9 +153,10 @@ function HeaderRightSection({
onOpenChange={handleOpenAnnouncementsModalChange}
>
<Button
+ variant="ghost"
+ size="icon"
aria-label="Announcements"
- icon={<Inbox size={14} />}
- className="periscope-btn ghost announcements-btn"
+ prefix={<Inbox size={14} />}
onClick={(): void => {
logEvent('Announcements: Clicked', {
page: location.pathname,
@@ -130,12 +179,12 @@ function HeaderRightSection({
onOpenChange={handleOpenShareURLModalChange}
>
<Button
- className="share-link-btn periscope-btn ghost"
- icon={<Globe size={14} />}
+ variant="ghost"
+ size="icon"
+ aria-label="Share"
+ prefix={<Globe size={14} />}
onClick={handleOpenShareURLModal}
- >
- Share
- </Button>
+ />
</Popover>
)}
</div>
diff --git a/frontend/src/components/HeaderRightSection/__tests__/HeaderRightSection.test.tsx b/frontend/src/components/HeaderRightSection/__tests__/HeaderRightSection.test.tsx
index 3eaba4e7c8..312d3ab2e3 100644
--- a/frontend/src/components/HeaderRightSection/__tests__/HeaderRightSection.test.tsx
+++ b/frontend/src/components/HeaderRightSection/__tests__/HeaderRightSection.test.tsx
@@ -46,6 +46,10 @@ jest.mock('hooks/useGetTenantLicense', () => ({
useGetTenantLicense: jest.fn(),
}));
+jest.mock('hooks/useIsAIAssistantEnabled', () => ({
+ useIsAIAssistantEnabled: (): boolean => false,
+}));
+
const mockLogEvent = logEvent as jest.Mock;
const mockUseLocation = useLocation as jest.Mock;
const mockUseGetTenantLicense = useGetTenantLicense as jest.Mock;
diff --git a/frontend/src/components/MarkdownRenderer/syntaxHighlighter.ts b/frontend/src/components/MarkdownRenderer/syntaxHighlighter.ts
index 33609ee26a..ba44dca245 100644
--- a/frontend/src/components/MarkdownRenderer/syntaxHighlighter.ts
+++ b/frontend/src/components/MarkdownRenderer/syntaxHighlighter.ts
@@ -12,6 +12,7 @@ import tsx from 'react-syntax-highlighter/dist/esm/languages/prism/tsx';
import typescript from 'react-syntax-highlighter/dist/esm/languages/prism/typescript';
import yaml from 'react-syntax-highlighter/dist/esm/languages/prism/yaml';
import a11yDark from 'react-syntax-highlighter/dist/esm/styles/prism/a11y-dark';
+import oneLight from 'react-syntax-highlighter/dist/esm/styles/prism/one-light';
SyntaxHighlighter.registerLanguage('bash', bash);
SyntaxHighlighter.registerLanguage('docker', docker);
@@ -31,4 +32,4 @@ SyntaxHighlighter.registerLanguage('yaml', yaml);
SyntaxHighlighter.registerLanguage('yml', yaml);
export default SyntaxHighlighter;
-export { a11yDark };
+export { a11yDark, oneLight };
diff --git a/frontend/src/constants/localStorage.ts b/frontend/src/constants/localStorage.ts
index 22cb9f8074..72fbe627c8 100644
--- a/frontend/src/constants/localStorage.ts
+++ b/frontend/src/constants/localStorage.ts
@@ -41,4 +41,5 @@ export enum LOCALSTORAGE {
TRACE_DETAILS_PREFER_OLD_VIEW = 'TRACE_DETAILS_PREFER_OLD_VIEW',
LICENSE_KEY_CALLOUT_DISMISSED = 'LICENSE_KEY_CALLOUT_DISMISSED',
DASHBOARD_PREFERENCES = 'DASHBOARD_PREFERENCES',
+ ACTIVE_SIGNOZ_INSTANCE_URL = 'ACTIVE_SIGNOZ_INSTANCE_URL',
}
diff --git a/frontend/src/constants/routes.ts b/frontend/src/constants/routes.ts
index 9671dde01d..8b77f43591 100644
--- a/frontend/src/constants/routes.ts
+++ b/frontend/src/constants/routes.ts
@@ -88,6 +88,8 @@ const ROUTES = {
HOME_PAGE: '/',
PUBLIC_DASHBOARD: '/public/dashboard/:dashboardId',
SERVICE_ACCOUNTS_SETTINGS: '/settings/service-accounts',
+ AI_ASSISTANT: '/ai-assistant/:conversationId',
+ AI_ASSISTANT_ICON_PREVIEW: '/ai-assistant-icon-preview',
MCP_SERVER: '/settings/mcp-server',
} as const;
diff --git a/frontend/src/container/AIAssistant/AIAssistantDrawer/AIAssistantDrawer.tsx b/frontend/src/container/AIAssistant/AIAssistantDrawer/AIAssistantDrawer.tsx
new file mode 100644
index 0000000000..d11a1b9d47
--- /dev/null
+++ b/frontend/src/container/AIAssistant/AIAssistantDrawer/AIAssistantDrawer.tsx
@@ -0,0 +1,102 @@
+import { useCallback } from 'react';
+import { useHistory } from 'react-router-dom';
+import { Button } from '@signozhq/ui/button';
+import { Tooltip } from '@signozhq/ui/tooltip';
+import { Drawer } from 'antd';
+import ROUTES from 'constants/routes';
+import { Maximize2, MessageSquare, Plus, X } from '@signozhq/icons';
+
+import ConversationView from '../ConversationView';
+import { useAIAssistantStore } from '../store/useAIAssistantStore';
+import { VariantContext } from '../VariantContext';
+
+export default function AIAssistantDrawer(): JSX.Element {
+ const history = useHistory();
+
+ const isDrawerOpen = useAIAssistantStore((s) => s.isDrawerOpen);
+ const activeConversationId = useAIAssistantStore(
+ (s) => s.activeConversationId,
+ );
+ const closeDrawer = useAIAssistantStore((s) => s.closeDrawer);
+ const startNewConversation = useAIAssistantStore(
+ (s) => s.startNewConversation,
+ );
+
+ const handleExpand = useCallback(() => {
+ if (!activeConversationId) {
+ return;
+ }
+ closeDrawer();
+ history.push(
+ ROUTES.AI_ASSISTANT.replace(':conversationId', activeConversationId),
+ );
+ }, [activeConversationId, closeDrawer, history]);
+
+ const handleNewConversation = useCallback(() => {
+ startNewConversation();
+ }, [startNewConversation]);
+
+ return (
+ <Drawer
+ open={isDrawerOpen}
+ onClose={closeDrawer}
+ placement="right"
+ width={420}
+ // Suppress default close button — we render our own header
+ closeIcon={null}
+ title={
+ <div>
+ <div>
+ <MessageSquare size={16} />
+ <span>AI Assistant</span>
+ </div>
+
+ <div>
+ <Tooltip title="New conversation">
+ <Button
+ variant="ghost"
+ size="icon"
+ color="secondary"
+ onClick={handleNewConversation}
+ aria-label="New conversation"
+ >
+ <Plus size={16} />
+ </Button>
+ </Tooltip>
+
+ <Tooltip title="Open full screen">
+ <Button
+ variant="ghost"
+ size="icon"
+ color="secondary"
+ onClick={handleExpand}
+ disabled={!activeConversationId}
+ aria-label="Open full screen"
+ >
+ <Maximize2 size={16} />
+ </Button>
+ </Tooltip>
+
+ <Tooltip title="Close">
+ <Button
+ variant="ghost"
+ size="icon"
+ color="secondary"
+ onClick={closeDrawer}
+ aria-label="Close drawer"
+ >
+ <X size={16} />
+ </Button>
+ </Tooltip>
+ </div>
+ </div>
+ }
+ >
+ <VariantContext.Provider value="panel">
+ {activeConversationId ? (
+ <ConversationView conversationId={activeConversationId} />
+ ) : null}
+ </VariantContext.Provider>
+ </Drawer>
+ );
+}
diff --git a/frontend/src/container/AIAssistant/AIAssistantDrawer/index.ts b/frontend/src/container/AIAssistant/AIAssistantDrawer/index.ts
new file mode 100644
index 0000000000..cdc0c6d135
--- /dev/null
+++ b/frontend/src/container/AIAssistant/AIAssistantDrawer/index.ts
@@ -0,0 +1,2 @@
+export * from './AIAssistantDrawer';
+export { default } from './AIAssistantDrawer';
diff --git a/frontend/src/container/AIAssistant/AIAssistantModal/AIAssistantModal.module.scss b/frontend/src/container/AIAssistant/AIAssistantModal/AIAssistantModal.module.scss
new file mode 100644
index 0000000000..95d8085b09
--- /dev/null
+++ b/frontend/src/container/AIAssistant/AIAssistantModal/AIAssistantModal.module.scss
@@ -0,0 +1,98 @@
+.backdrop {
+ position: fixed;
+ inset: 0;
+ z-index: 1050;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ background: rgba(0, 0, 0, 0.45);
+ backdrop-filter: blur(2px);
+ animation: backdropIn 0.15s ease;
+}
+
+@keyframes backdropIn {
+ from {
+ opacity: 0;
+ }
+ to {
+ opacity: 1;
+ }
+}
+
+.modal {
+ display: flex;
+ flex-direction: column;
+ width: 70vw;
+ height: 80vh;
+ background: var(--l1-background);
+ border: 1px solid var(--l1-border);
+ border-radius: var(--radius-2);
+ overflow: hidden;
+ box-shadow: 0 24px 64px rgba(0, 0, 0, 0.35);
+ animation: modalIn 0.18s cubic-bezier(0.16, 1, 0.3, 1);
+}
+
+@keyframes modalIn {
+ from {
+ opacity: 0;
+ transform: scale(0.96) translateY(-6px);
+ }
+ to {
+ opacity: 1;
+ transform: scale(1) translateY(0);
+ }
+}
+
+.header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 10px 12px;
+ border-bottom: 1px solid var(--l1-border);
+ flex-shrink: 0;
+ background: var(--l1-background);
+}
+
+.title {
+ display: flex;
+ align-items: center;
+ gap: 7px;
+ font-size: 13px;
+ font-weight: 600;
+ color: var(--l1-foreground);
+}
+
+.shortcut {
+ font-size: 10px;
+ font-family: var(--font-mono, monospace);
+ font-weight: 500;
+ color: var(--l3-foreground);
+ background: var(--l2-background);
+ border: 1px solid var(--l2-border);
+ border-radius: var(--radius-2);
+ padding: 1px 5px;
+ letter-spacing: 0;
+ line-height: 1.6;
+
+ display: flex;
+ align-items: center;
+ gap: 4px;
+}
+
+.actions {
+ display: flex;
+ align-items: center;
+ gap: 2px;
+}
+
+.body {
+ flex: 1;
+ overflow: hidden;
+ display: flex;
+ flex-direction: column;
+}
+
+.toggleBtnActive {
+ background: var(--l2-background) !important;
+ color: var(--accent-primary) !important;
+}
diff --git a/frontend/src/container/AIAssistant/AIAssistantModal/AIAssistantModal.tsx b/frontend/src/container/AIAssistant/AIAssistantModal/AIAssistantModal.tsx
new file mode 100644
index 0000000000..f7078b852a
--- /dev/null
+++ b/frontend/src/container/AIAssistant/AIAssistantModal/AIAssistantModal.tsx
@@ -0,0 +1,209 @@
+import { useCallback, useEffect, useState } from 'react';
+import { createPortal } from 'react-dom';
+import { useHistory } from 'react-router-dom';
+import { Button } from '@signozhq/ui/button';
+import { Tooltip } from '@signozhq/ui/tooltip';
+import ROUTES from 'constants/routes';
+import { History, Maximize2, Minus, Plus, Sparkles, X } from '@signozhq/icons';
+
+import HistorySidebar from '../components/ConversationsList';
+import ConversationView from '../ConversationView';
+import { useAIAssistantStore } from '../store/useAIAssistantStore';
+import { VariantContext } from '../VariantContext';
+
+import styles from './AIAssistantModal.module.scss';
+
+/**
+ * Global floating modal for the AI Assistant.
+ *
+ * - Triggered by Cmd+J (Mac) / Ctrl+J (Windows/Linux)
+ * - Escape or the × button fully closes it
+ * - The − (minimize) button collapses to the side panel
+ * - Mounted once in AppLayout; always in the DOM, conditionally visible
+ */
+// eslint-disable-next-line sonarjs/cognitive-complexity
+export default function AIAssistantModal(): JSX.Element | null {
+ const history = useHistory();
+ const [showHistory, setShowHistory] = useState(false);
+
+ const isOpen = useAIAssistantStore((s) => s.isModalOpen);
+ const activeConversationId = useAIAssistantStore(
+ (s) => s.activeConversationId,
+ );
+ const openModal = useAIAssistantStore((s) => s.openModal);
+ const closeModal = useAIAssistantStore((s) => s.closeModal);
+ const minimizeModal = useAIAssistantStore((s) => s.minimizeModal);
+ const startNewConversation = useAIAssistantStore(
+ (s) => s.startNewConversation,
+ );
+
+ useEffect(() => {
+ const handleKeyDown = (e: KeyboardEvent): void => {
+ // Cmd+J (Mac) / Ctrl+J (Win/Linux) — toggle modal. Opening
+ // always starts a brand-new conversation; resuming earlier
+ // threads is done via the in-modal history sidebar.
+ if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'j') {
+ // Don't intercept Cmd+J inside input/textarea — those are for the user
+ const tag = (e.target as HTMLElement).tagName;
+ if (tag === 'INPUT' || tag === 'TEXTAREA') {
+ return;
+ }
+
+ e.preventDefault();
+ if (isOpen) {
+ closeModal();
+ } else {
+ startNewConversation();
+ setShowHistory(false);
+ openModal();
+ }
+ return;
+ }
+
+ // Escape — close modal
+ if (e.key === 'Escape' && isOpen) {
+ closeModal();
+ }
+ };
+
+ window.addEventListener('keydown', handleKeyDown);
+ return (): void => window.removeEventListener('keydown', handleKeyDown);
+ }, [isOpen, openModal, closeModal, startNewConversation]);
+
+ // ── Handlers ────────────────────────────────────────────────────────────────
+
+ const handleExpand = useCallback(() => {
+ if (!activeConversationId) {
+ return;
+ }
+ closeModal();
+ history.push(
+ ROUTES.AI_ASSISTANT.replace(':conversationId', activeConversationId),
+ );
+ }, [activeConversationId, closeModal, history]);
+
+ const handleNew = useCallback(() => {
+ startNewConversation();
+ setShowHistory(false);
+ }, [startNewConversation]);
+
+ const handleHistorySelect = useCallback(() => {
+ setShowHistory(false);
+ }, []);
+
+ const handleMinimize = useCallback(() => {
+ minimizeModal();
+ setShowHistory(false);
+ }, [minimizeModal]);
+
+ const handleBackdropClick = useCallback(
+ (e: React.MouseEvent<HTMLDivElement>) => {
+ // Only close when clicking the backdrop itself, not the modal card
+ if (e.target === e.currentTarget) {
+ closeModal();
+ }
+ },
+ [closeModal],
+ );
+
+ if (!isOpen) {
+ return null;
+ }
+
+ return createPortal(
+ <VariantContext.Provider value="modal">
+ <div
+ className={styles.backdrop}
+ role="dialog"
+ aria-modal="true"
+ aria-label="AI Assistant"
+ onClick={handleBackdropClick}
+ >
+ <div className={styles.modal}>
+ {/* Header */}
+ <div className={styles.header}>
+ <div className={styles.title}>
+ <Sparkles size={16} color="var(--primary)" />
+ <span>AI Assistant</span>
+ <kbd className={styles.shortcut}>
+ <span>⌘</span>
+ <span>J</span>
+ </kbd>
+ </div>
+
+ <div className={styles.actions}>
+ <Tooltip title={showHistory ? 'Back to chat' : 'Conversations'}>
+ <Button
+ variant="ghost"
+ size="icon"
+ onClick={(): void => setShowHistory((v) => !v)}
+ aria-label="Toggle conversations"
+ className={showHistory ? styles.toggleBtnActive : ''}
+ >
+ <History size={14} />
+ </Button>
+ </Tooltip>
+
+ <Tooltip title="New conversation">
+ <Button
+ variant="ghost"
+ size="icon"
+ onClick={handleNew}
+ aria-label="New conversation"
+ >
+ <Plus size={14} />
+ </Button>
+ </Tooltip>
+
+ <Tooltip title="Open full screen">
+ <Button
+ variant="ghost"
+ size="icon"
+ onClick={handleExpand}
+ disabled={!activeConversationId}
+ aria-label="Open full screen"
+ >
+ <Maximize2 size={14} />
+ </Button>
+ </Tooltip>
+
+ <Tooltip title="Minimize to side panel">
+ <Button
+ variant="ghost"
+ size="icon"
+ onClick={handleMinimize}
+ aria-label="Minimize to side panel"
+ >
+ <Minus size={14} />
+ </Button>
+ </Tooltip>
+
+ <Tooltip title="Close">
+ <Button
+ variant="ghost"
+ size="icon"
+ onClick={closeModal}
+ aria-label="Close"
+ >
+ <X size={14} />
+ </Button>
+ </Tooltip>
+ </div>
+ </div>
+
+ {/* Body */}
+ <div className={styles.body}>
+ {showHistory ? (
+ <HistorySidebar onSelect={handleHistorySelect} />
+ ) : (
+ activeConversationId && (
+ <ConversationView conversationId={activeConversationId} />
+ )
+ )}
+ </div>
+ </div>
+ </div>
+ </VariantContext.Provider>,
+ document.body,
+ );
+}
diff --git a/frontend/src/container/AIAssistant/AIAssistantModal/index.ts b/frontend/src/container/AIAssistant/AIAssistantModal/index.ts
new file mode 100644
index 0000000000..33853f07ae
--- /dev/null
+++ b/frontend/src/container/AIAssistant/AIAssistantModal/index.ts
@@ -0,0 +1,2 @@
+export * from './AIAssistantModal';
+export { default } from './AIAssistantModal';
diff --git a/frontend/src/container/AIAssistant/AIAssistantPanel/AIAssistantPanel.module.scss b/frontend/src/container/AIAssistant/AIAssistantPanel/AIAssistantPanel.module.scss
new file mode 100644
index 0000000000..5265aaa5de
--- /dev/null
+++ b/frontend/src/container/AIAssistant/AIAssistantPanel/AIAssistantPanel.module.scss
@@ -0,0 +1,60 @@
+.panel {
+ display: flex;
+ flex-direction: column;
+ flex-shrink: 0;
+ height: 100%;
+ border-left: 1px solid var(--l1-border);
+ background: var(--l1-background);
+ overflow: hidden;
+ position: relative;
+}
+
+.resizeHandle {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 4px;
+ height: 100%;
+ cursor: col-resize;
+ z-index: 10;
+
+ &::after {
+ content: '';
+ position: absolute;
+ top: 0;
+ left: 1px;
+ width: 2px;
+ height: 100%;
+ background: transparent;
+ transition: background 0.15s ease;
+ }
+
+ &:hover::after {
+ background: var(--accent-primary);
+ }
+}
+
+.header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 8px;
+ border-bottom: 1px solid var(--l1-border);
+ flex-shrink: 0;
+ background: var(--l1-background);
+}
+
+.title {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ font-size: 13px;
+ font-weight: 600;
+ color: var(--l1-foreground);
+}
+
+.actions {
+ display: flex;
+ align-items: center;
+ gap: 2px;
+}
diff --git a/frontend/src/container/AIAssistant/AIAssistantPanel/AIAssistantPanel.tsx b/frontend/src/container/AIAssistant/AIAssistantPanel/AIAssistantPanel.tsx
new file mode 100644
index 0000000000..b81a59cb15
--- /dev/null
+++ b/frontend/src/container/AIAssistant/AIAssistantPanel/AIAssistantPanel.tsx
@@ -0,0 +1,189 @@
+import { useCallback, useLayoutEffect, useRef, useState } from 'react';
+import { matchPath, useHistory, useLocation } from 'react-router-dom';
+import { Button } from '@signozhq/ui/button';
+import { Tooltip } from '@signozhq/ui/tooltip';
+import ROUTES from 'constants/routes';
+import { History, Maximize2, Plus, Sparkles, X } from '@signozhq/icons';
+
+import ConversationsList from '../components/ConversationsList';
+import ConversationView from '../ConversationView';
+import { useAIAssistantStore } from '../store/useAIAssistantStore';
+import { VariantContext } from '../VariantContext';
+
+import styles from './AIAssistantPanel.module.scss';
+
+const AI_ASSISTANT_PANEL_OPEN_CLASS = 'ai-assistant-panel-open';
+const AI_ASSISTANT_PANEL_WIDTH_VAR = '--ai-assistant-panel-width';
+
+export default function AIAssistantPanel(): JSX.Element | null {
+ const history = useHistory();
+ const { pathname } = useLocation();
+ const [showHistory, setShowHistory] = useState(false);
+
+ const isOpen = useAIAssistantStore((s) => s.isDrawerOpen);
+ const isFullScreenPage = !!matchPath(pathname, {
+ path: ROUTES.AI_ASSISTANT,
+ exact: true,
+ });
+ const activeConversationId = useAIAssistantStore(
+ (s) => s.activeConversationId,
+ );
+ const closeDrawer = useAIAssistantStore((s) => s.closeDrawer);
+ const startNewConversation = useAIAssistantStore(
+ (s) => s.startNewConversation,
+ );
+
+ const handleExpand = useCallback(() => {
+ if (!activeConversationId) {
+ return;
+ }
+ closeDrawer();
+ history.push(
+ ROUTES.AI_ASSISTANT.replace(':conversationId', activeConversationId),
+ );
+ }, [activeConversationId, closeDrawer, history]);
+
+ const handleNew = useCallback(() => {
+ startNewConversation();
+ setShowHistory(false);
+ }, [startNewConversation]);
+
+ // When user picks a conversation from the list, close the sidebar
+ const handleHistorySelect = useCallback(() => {
+ setShowHistory(false);
+ }, []);
+
+ // ── Resize logic ──────────────────────────────────────────────────────────
+ const [panelWidth, setPanelWidth] = useState(380);
+ const dragStartX = useRef(0);
+ const dragStartWidth = useRef(0);
+
+ useLayoutEffect(() => {
+ const shouldOffsetChatSupport = isOpen && !isFullScreenPage;
+
+ document.body.classList.toggle(
+ AI_ASSISTANT_PANEL_OPEN_CLASS,
+ shouldOffsetChatSupport,
+ );
+
+ if (shouldOffsetChatSupport) {
+ document.body.style.setProperty(
+ AI_ASSISTANT_PANEL_WIDTH_VAR,
+ `${panelWidth}px`,
+ );
+ } else {
+ document.body.style.removeProperty(AI_ASSISTANT_PANEL_WIDTH_VAR);
+ }
+
+ return (): void => {
+ document.body.classList.remove(AI_ASSISTANT_PANEL_OPEN_CLASS);
+ document.body.style.removeProperty(AI_ASSISTANT_PANEL_WIDTH_VAR);
+ };
+ }, [isFullScreenPage, isOpen, panelWidth]);
+
+ const handleResizeMouseDown = useCallback(
+ (e: React.MouseEvent) => {
+ e.preventDefault();
+ dragStartX.current = e.clientX;
+ dragStartWidth.current = panelWidth;
+
+ const onMouseMove = (ev: MouseEvent): void => {
+ // Panel is on the right; dragging left (lower clientX) increases width
+ const delta = dragStartX.current - ev.clientX;
+ const next = Math.min(Math.max(dragStartWidth.current + delta, 380), 800);
+ setPanelWidth(next);
+ };
+
+ const onMouseUp = (): void => {
+ document.removeEventListener('mousemove', onMouseMove);
+ document.removeEventListener('mouseup', onMouseUp);
+ document.body.style.cursor = '';
+ document.body.style.userSelect = '';
+ };
+
+ document.body.style.cursor = 'col-resize';
+ document.body.style.userSelect = 'none';
+ document.addEventListener('mousemove', onMouseMove);
+ document.addEventListener('mouseup', onMouseUp);
+ },
+ [panelWidth],
+ );
+
+ if (!isOpen || isFullScreenPage) {
+ return null;
+ }
+
+ return (
+ <VariantContext.Provider value="panel">
+ <div className={styles.panel} style={{ width: panelWidth }}>
+ {/* eslint-disable-next-line jsx-a11y/no-static-element-interactions */}
+ <div className={styles.resizeHandle} onMouseDown={handleResizeMouseDown} />
+ <div className={styles.header}>
+ <div className={styles.title}>
+ <Sparkles size={18} color="var(--primary)" />
+ <span>AI Assistant</span>
+ </div>
+
+ <div className={styles.actions}>
+ <Tooltip title={showHistory ? 'Back to chat' : 'Conversations'}>
+ <Button
+ variant="ghost"
+ size="icon"
+ color="secondary"
+ onClick={(): void => setShowHistory((v) => !v)}
+ aria-label="Toggle conversations"
+ >
+ <History size={14} />
+ </Button>
+ </Tooltip>
+
+ <Tooltip title="New conversation">
+ <Button
+ variant="ghost"
+ size="icon"
+ color="secondary"
+ onClick={handleNew}
+ aria-label="New conversation"
+ >
+ <Plus size={14} />
+ </Button>
+ </Tooltip>
+
+ <Tooltip title="Open full screen">
+ <Button
+ variant="ghost"
+ size="icon"
+ color="secondary"
+ onClick={handleExpand}
+ disabled={!activeConversationId}
+ aria-label="Open full screen"
+ >
+ <Maximize2 size={14} />
+ </Button>
+ </Tooltip>
+
+ <Tooltip title="Close">
+ <Button
+ variant="ghost"
+ size="icon"
+ color="secondary"
+ onClick={closeDrawer}
+ aria-label="Close panel"
+ >
+ <X size={14} />
+ </Button>
+ </Tooltip>
+ </div>
+ </div>
+
+ {showHistory ? (
+ <ConversationsList onSelect={handleHistorySelect} />
+ ) : (
+ activeConversationId && (
+ <ConversationView conversationId={activeConversationId} />
+ )
+ )}
+ </div>
+ </VariantContext.Provider>
+ );
+}
diff --git a/frontend/src/container/AIAssistant/AIAssistantPanel/index.ts b/frontend/src/container/AIAssistant/AIAssistantPanel/index.ts
new file mode 100644
index 0000000000..aa92bf1601
--- /dev/null
+++ b/frontend/src/container/AIAssistant/AIAssistantPanel/index.ts
@@ -0,0 +1,2 @@
+export * from './AIAssistantPanel';
+export { default } from './AIAssistantPanel';
diff --git a/frontend/src/container/AIAssistant/AIAssistantTrigger/AIAssistantTrigger.module.scss b/frontend/src/container/AIAssistant/AIAssistantTrigger/AIAssistantTrigger.module.scss
new file mode 100644
index 0000000000..5162f1e3d6
--- /dev/null
+++ b/frontend/src/container/AIAssistant/AIAssistantTrigger/AIAssistantTrigger.module.scss
@@ -0,0 +1,32 @@
+.trigger {
+ position: absolute;
+ bottom: 24px;
+ right: 24px;
+ z-index: 10;
+
+ width: 44px;
+ height: 44px;
+ border-radius: 50%;
+ border: none;
+ cursor: pointer;
+
+ display: flex;
+ align-items: center;
+ justify-content: center;
+
+ background: var(--accent-primary);
+ color: var(--accent-primary-foreground);
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.25);
+ transition:
+ transform 0.15s,
+ box-shadow 0.15s;
+
+ &:hover {
+ transform: scale(1.08);
+ box-shadow: 0 6px 18px rgba(0, 0, 0, 0.32);
+ }
+
+ &:active {
+ transform: scale(0.96);
+ }
+}
diff --git a/frontend/src/container/AIAssistant/AIAssistantTrigger/AIAssistantTrigger.tsx b/frontend/src/container/AIAssistant/AIAssistantTrigger/AIAssistantTrigger.tsx
new file mode 100644
index 0000000000..fdf2f1f254
--- /dev/null
+++ b/frontend/src/container/AIAssistant/AIAssistantTrigger/AIAssistantTrigger.tsx
@@ -0,0 +1,45 @@
+import { matchPath, useLocation } from 'react-router-dom';
+import { Button } from '@signozhq/ui/button';
+import { Tooltip } from '@signozhq/ui/tooltip';
+import ROUTES from 'constants/routes';
+import { Bot } from '@signozhq/icons';
+
+import {
+ openAIAssistant,
+ useAIAssistantStore,
+} from '../store/useAIAssistantStore';
+
+import styles from './AIAssistantTrigger.module.scss';
+
+/**
+ * Floating action button anchored to the bottom-right of the content area.
+ * Hidden when the panel is already open or when on the full-screen AI Assistant page.
+ */
+export default function AIAssistantTrigger(): JSX.Element | null {
+ const { pathname } = useLocation();
+ const isDrawerOpen = useAIAssistantStore((s) => s.isDrawerOpen);
+ const isModalOpen = useAIAssistantStore((s) => s.isModalOpen);
+
+ const isFullScreenPage = !!matchPath(pathname, {
+ path: ROUTES.AI_ASSISTANT,
+ exact: true,
+ });
+
+ if (isDrawerOpen || isModalOpen || isFullScreenPage) {
+ return null;
+ }
+
+ return (
+ <Tooltip title="AI Assistant">
+ <Button
+ variant="solid"
+ color="primary"
+ className={styles.trigger}
+ onClick={openAIAssistant}
+ aria-label="Open AI Assistant"
+ >
+ <Bot size={20} />
+ </Button>
+ </Tooltip>
+ );
+}
diff --git a/frontend/src/container/AIAssistant/AIAssistantTrigger/index.ts b/frontend/src/container/AIAssistant/AIAssistantTrigger/index.ts
new file mode 100644
index 0000000000..9acfdd4625
--- /dev/null
+++ b/frontend/src/container/AIAssistant/AIAssistantTrigger/index.ts
@@ -0,0 +1,2 @@
+export * from './AIAssistantTrigger';
+export { default } from './AIAssistantTrigger';
diff --git a/frontend/src/container/AIAssistant/ConversationView/ConversationView.module.scss b/frontend/src/container/AIAssistant/ConversationView/ConversationView.module.scss
new file mode 100644
index 0000000000..871c7c97ac
--- /dev/null
+++ b/frontend/src/container/AIAssistant/ConversationView/ConversationView.module.scss
@@ -0,0 +1,53 @@
+.conversation {
+ display: flex;
+ flex-direction: column;
+ height: 100%;
+ overflow: hidden;
+}
+
+.loading {
+ flex: 1;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 8px;
+ font-size: 13px;
+ color: var(--l3-foreground);
+}
+
+.spinner {
+ animation: spin 0.8s linear infinite;
+}
+
+@keyframes spin {
+ from {
+ transform: rotate(0deg);
+ }
+ to {
+ transform: rotate(360deg);
+ }
+}
+
+.inputWrapper {
+ flex-shrink: 0;
+ padding: 12px;
+ border-top: 1px solid var(--l1-border);
+
+ &.compact {
+ padding: 8px;
+ }
+}
+
+.disclaimer {
+ flex-shrink: 0;
+ padding: 8px 16px;
+ font-size: 10px;
+ line-height: 1.4;
+ margin-top: 4px;
+ color: var(--l3-foreground);
+ text-align: center;
+
+ &.compact {
+ padding: 8px 12px;
+ }
+}
diff --git a/frontend/src/container/AIAssistant/ConversationView/ConversationView.tsx b/frontend/src/container/AIAssistant/ConversationView/ConversationView.tsx
new file mode 100644
index 0000000000..d521529e21
--- /dev/null
+++ b/frontend/src/container/AIAssistant/ConversationView/ConversationView.tsx
@@ -0,0 +1,155 @@
+import { useCallback, useEffect, useMemo, useState } from 'react';
+import { useLocation } from 'react-router-dom';
+import cx from 'classnames';
+
+import ChatInput, { autoContextKey } from '../components/ChatInput';
+import ConversationSkeleton from '../components/ConversationSkeleton';
+import VirtualizedMessages from '../components/VirtualizedMessages';
+import { getAutoContexts } from '../getAutoContexts';
+import { useAIAssistantStore } from '../store/useAIAssistantStore';
+import { MessageAttachment } from '../types';
+import { MessageContext } from '../../../api/ai-assistant/chat';
+import { useVariant } from '../VariantContext';
+
+import styles from './ConversationView.module.scss';
+
+interface ConversationViewProps {
+ conversationId: string;
+}
+
+export default function ConversationView({
+ conversationId,
+}: ConversationViewProps): JSX.Element {
+ const variant = useVariant();
+ const isCompact = variant === 'panel';
+ const location = useLocation();
+
+ const conversation = useAIAssistantStore(
+ (s) => s.conversations[conversationId],
+ );
+ const isStreamingHere = useAIAssistantStore(
+ (s) => s.streams[conversationId]?.isStreaming ?? false,
+ );
+ const isLoadingThread = useAIAssistantStore((s) => s.isLoadingThread);
+ const pendingApprovalHere = useAIAssistantStore(
+ (s) => s.streams[conversationId]?.pendingApproval ?? null,
+ );
+ const pendingClarificationHere = useAIAssistantStore(
+ (s) => s.streams[conversationId]?.pendingClarification ?? null,
+ );
+ const sendMessage = useAIAssistantStore((s) => s.sendMessage);
+ const cancelStream = useAIAssistantStore((s) => s.cancelStream);
+
+ // Auto-derived contexts come from the route the user is currently looking
+ // at (dashboard detail, service metrics, an explorer, …). Skip when the
+ // user is on the standalone AI Assistant page — there's no "underlying"
+ // page context to attach. ChatInput renders these as chips and merges
+ // them with the user's `@`-mention picks before invoking onSend.
+ const allAutoContexts = useMemo(
+ () =>
+ variant === 'page'
+ ? []
+ : getAutoContexts(location.pathname, location.search),
+ [variant, location.pathname, location.search],
+ );
+
+ // User-dismissed auto-context entries. Reset whenever the URL changes —
+ // dismissals are scoped to "this page", not the whole conversation.
+ const [dismissedAutoKeys, setDismissedAutoKeys] = useState<Set<string>>(
+ () => new Set(),
+ );
+ useEffect(() => {
+ setDismissedAutoKeys(new Set());
+ }, [location.pathname, location.search]);
+
+ const autoContexts = useMemo(
+ () =>
+ allAutoContexts.filter((ctx) => !dismissedAutoKeys.has(autoContextKey(ctx))),
+ [allAutoContexts, dismissedAutoKeys],
+ );
+
+ const handleDismissAutoContext = useCallback((key: string): void => {
+ setDismissedAutoKeys((prev) => {
+ const next = new Set(prev);
+ next.add(key);
+ return next;
+ });
+ }, []);
+
+ const handleSend = useCallback(
+ (
+ text: string,
+ attachments?: MessageAttachment[],
+ contexts?: MessageContext[],
+ ) => {
+ void sendMessage(text, attachments, contexts);
+ },
+ [sendMessage],
+ );
+
+ const handleCancel = useCallback(() => {
+ cancelStream(conversationId);
+ }, [cancelStream, conversationId]);
+
+ const messages = conversation?.messages ?? [];
+ const showDisclaimer = messages.length > 0;
+ const inputDisabled =
+ isStreamingHere ||
+ isLoadingThread ||
+ Boolean(pendingApprovalHere) ||
+ Boolean(pendingClarificationHere);
+
+ const inputWrapperClass = cx(styles.inputWrapper, {
+ [styles.compact]: isCompact,
+ });
+ const disclaimerClass = cx(styles.disclaimer, {
+ [styles.compact]: isCompact,
+ });
+
+ // Cover the gap between rehydrate (empty primed entry) and the first
+ // loadThread response. `isHydrating` is set on the rehydrated conversation
+ // and cleared once fetchThreads resolves; `isLoadingThread` covers the
+ // per-thread fetch that follows. Together they keep the skeleton visible
+ // for persisted chats without flashing it on freshly-created ones.
+ const isHydrating = Boolean(conversation?.isHydrating);
+ if ((isLoadingThread || isHydrating) && messages.length === 0) {
+ return (
+ <div className={styles.conversation}>
+ <ConversationSkeleton />
+ <div className={inputWrapperClass}>
+ <ChatInput
+ onSend={handleSend}
+ disabled
+ autoContexts={autoContexts}
+ onDismissAutoContext={handleDismissAutoContext}
+ />
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <div className={styles.conversation}>
+ <VirtualizedMessages
+ conversationId={conversationId}
+ messages={messages}
+ isStreaming={isStreamingHere}
+ />
+ {showDisclaimer && (
+ <div className={disclaimerClass} role="note" aria-live="polite">
+ SigNoz AI can make mistakes. Please double-check responses.
+ </div>
+ )}
+ <div className={inputWrapperClass}>
+ <ChatInput
+ onSend={handleSend}
+ onCancel={handleCancel}
+ disabled={inputDisabled}
+ isStreaming={isStreamingHere}
+ autoContexts={autoContexts}
+ onDismissAutoContext={handleDismissAutoContext}
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/frontend/src/container/AIAssistant/ConversationView/index.ts b/frontend/src/container/AIAssistant/ConversationView/index.ts
new file mode 100644
index 0000000000..4f0b6da8e7
--- /dev/null
+++ b/frontend/src/container/AIAssistant/ConversationView/index.ts
@@ -0,0 +1,2 @@
+export * from './ConversationView';
+export { default } from './ConversationView';
diff --git a/frontend/src/container/AIAssistant/VariantContext.ts b/frontend/src/container/AIAssistant/VariantContext.ts
new file mode 100644
index 0000000000..a65b88c1b5
--- /dev/null
+++ b/frontend/src/container/AIAssistant/VariantContext.ts
@@ -0,0 +1,8 @@
+// eslint-disable-next-line no-restricted-imports
+import { createContext, useContext } from 'react';
+
+export type AIAssistantVariant = 'panel' | 'page' | 'modal';
+
+export const VariantContext = createContext<AIAssistantVariant>('page');
+
+export const useVariant = (): AIAssistantVariant => useContext(VariantContext);
diff --git a/frontend/src/container/AIAssistant/_scrollbar.scss b/frontend/src/container/AIAssistant/_scrollbar.scss
new file mode 100644
index 0000000000..3df602682e
--- /dev/null
+++ b/frontend/src/container/AIAssistant/_scrollbar.scss
@@ -0,0 +1,32 @@
+@mixin scrollbar($width: 0.3rem) {
+ scrollbar-width: thin;
+ scrollbar-color: transparent transparent;
+ transition: scrollbar-color 0.2s;
+
+ &:hover {
+ scrollbar-color: var(--l3-border) transparent;
+ }
+
+ &::-webkit-scrollbar {
+ width: $width;
+ height: $width;
+ }
+
+ &::-webkit-scrollbar-track {
+ background: transparent;
+ }
+
+ &::-webkit-scrollbar-thumb {
+ background: transparent;
+ border-radius: 999px;
+ transition: background 0.2s;
+ }
+
+ &:hover::-webkit-scrollbar-thumb {
+ background: var(--l3-border);
+ }
+
+ &::-webkit-scrollbar-thumb:hover {
+ background: var(--l3-foreground);
+ }
+}
diff --git a/frontend/src/container/AIAssistant/components/ActionsSection/ActionsSection.module.scss b/frontend/src/container/AIAssistant/components/ActionsSection/ActionsSection.module.scss
new file mode 100644
index 0000000000..6551e91c02
--- /dev/null
+++ b/frontend/src/container/AIAssistant/components/ActionsSection/ActionsSection.module.scss
@@ -0,0 +1,116 @@
+.section {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ flex-shrink: 0;
+ width: 100%;
+ padding: 8px;
+ margin-top: 16px;
+ border: 1px solid var(--l2-border);
+ border-radius: var(--radius-2);
+
+ // Background, padding-x, and rounding are inherited from the parent
+ // bubble — the section sits inside the assistant bubble as its last
+ // block, so it matches the bubble's width by definition.
+}
+
+.heading {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ font-size: 10px;
+ font-weight: 600;
+ text-transform: uppercase;
+ letter-spacing: 0.06em;
+ color: var(--l3-foreground);
+}
+
+.headingIcon {
+ color: var(--primary);
+ flex-shrink: 0;
+}
+
+.list {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px;
+}
+
+.chip {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ padding: 5px 10px;
+ border: 1px solid var(--l2-border);
+ border-radius: var(--radius-2);
+ background: var(--l1-background);
+ color: var(--l1-foreground);
+ font-size: 11px;
+ font-style: normal;
+ font-weight: 400;
+ line-height: 18px; /* 163.636% */
+ letter-spacing: -0.055px;
+ cursor: pointer;
+ transition:
+ background 0.12s ease,
+ border-color 0.12s ease,
+ color 0.12s ease;
+
+ &:hover:not(:disabled) {
+ background: var(--l2-background);
+ border-color: var(--l3-border);
+ }
+
+ &:disabled {
+ cursor: default;
+ opacity: 0.55;
+ }
+
+ &.error {
+ border-color: var(--accent-cherry);
+ color: var(--accent-cherry);
+ }
+
+ svg {
+ flex-shrink: 0;
+ color: var(--l3-foreground);
+ }
+
+ &:hover:not(:disabled) svg {
+ color: var(--accent-primary);
+ }
+
+ &.error svg {
+ color: var(--accent-cherry);
+ }
+}
+
+.spin {
+ color: var(--accent-primary) !important;
+ animation: spin 0.8s linear infinite;
+}
+
+@keyframes spin {
+ to {
+ transform: rotate(360deg);
+ }
+}
+
+.chipLabel {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ max-width: 220px;
+}
+
+.chipState {
+ font-size: 10px;
+ font-weight: 500;
+ color: var(--l3-foreground);
+ text-transform: uppercase;
+ letter-spacing: 0.04em;
+ padding: 1px 5px;
+ border: 1px solid var(--l2-border);
+ border-radius: 999px;
+ margin-left: 2px;
+}
diff --git a/frontend/src/container/AIAssistant/components/ActionsSection/ActionsSection.tsx b/frontend/src/container/AIAssistant/components/ActionsSection/ActionsSection.tsx
new file mode 100644
index 0000000000..1f426647c0
--- /dev/null
+++ b/frontend/src/container/AIAssistant/components/ActionsSection/ActionsSection.tsx
@@ -0,0 +1,537 @@
+import { useEffect, useState } from 'react';
+import { matchPath, useHistory, useLocation } from 'react-router-dom';
+import { convertFiltersToExpression } from 'components/QueryBuilderV2/utils';
+import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
+import { mapQueryDataFromApi } from 'lib/newQueryBuilder/queryBuilderMappers/mapQueryDataFromApi';
+import { ICompositeMetricQuery } from 'types/api/alerts/compositeQuery';
+import {
+ IBuilderQuery,
+ Query,
+ TagFilter,
+} from 'types/api/queryBuilder/queryBuilderData';
+import cx from 'classnames';
+import { v4 as uuidv4 } from 'uuid';
+import { Button } from '@signozhq/ui/button';
+import { Tooltip } from '@signozhq/ui/tooltip';
+import type { MessageActionDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
+import {
+ ApplyFilterSignalDTO,
+ MessageActionKindDTO,
+} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
+import {
+ restoreExecution,
+ revertExecution,
+ undoExecution,
+} from 'api/ai-assistant/chat';
+import ROUTES from 'constants/routes';
+import { QueryParams } from 'constants/query';
+import { openInNewTab } from 'utils/navigation';
+import {
+ ArchiveRestore,
+ BookOpen,
+ Check,
+ ExternalLink,
+ Eye,
+ Filter,
+ LoaderCircle,
+ MessageCircle,
+ RotateCcw,
+ Sparkles,
+ TriangleAlert,
+ Undo,
+} from '@signozhq/icons';
+
+import { useAIAssistantStore } from '../../store/useAIAssistantStore';
+
+import styles from './ActionsSection.module.scss';
+
+interface ActionsSectionProps {
+ actions: MessageActionDTO[];
+}
+
+type ChipState = 'idle' | 'loading' | 'success' | 'error';
+
+interface ChipResult {
+ state: ChipState;
+ error?: string;
+}
+
+/** Maps each MessageActionKindDTO to its display icon. */
+function ActionIcon({
+ kind,
+ size = 12,
+}: {
+ kind: MessageActionDTO['kind'];
+ size?: number;
+}): JSX.Element {
+ switch (kind) {
+ case MessageActionKindDTO.undo:
+ return <Undo size={size} />;
+ case MessageActionKindDTO.revert:
+ return <RotateCcw size={size} />;
+ case MessageActionKindDTO.restore:
+ return <ArchiveRestore size={size} />;
+ case MessageActionKindDTO.follow_up:
+ return <MessageCircle size={size} />;
+ case MessageActionKindDTO.open_resource:
+ return <Eye size={size} />;
+ case MessageActionKindDTO.open_docs:
+ return <BookOpen size={size} />;
+ case MessageActionKindDTO.apply_filter:
+ return <Filter size={size} />;
+ default:
+ return <ExternalLink size={size} />;
+ }
+}
+
+/**
+ * Resolves an `open_resource` action to an in-app route.
+ * Resource taxonomy mirrors `MessageContextDTOType`: dashboard, alert,
+ * saved_view, service, and the *_explorer signals.
+ */
+function resourceRoute(
+ resourceType: string,
+ resourceId: string,
+): string | null {
+ switch (resourceType) {
+ case 'dashboard':
+ return ROUTES.DASHBOARD.replace(':dashboardId', resourceId);
+ case 'alert': {
+ const params = new URLSearchParams({ [QueryParams.ruleId]: resourceId });
+ return `${ROUTES.EDIT_ALERTS}?${params.toString()}`;
+ }
+ case 'service':
+ return ROUTES.SERVICE_METRICS.replace(':servicename', resourceId);
+ case 'saved_view':
+ // No detail route — saved views land on the list page.
+ // Caller may provide signal-aware metadata in future; default to logs.
+ return ROUTES.LOGS_SAVE_VIEWS;
+ case 'logs_explorer':
+ return ROUTES.LOGS_EXPLORER;
+ case 'traces_explorer':
+ return ROUTES.TRACES_EXPLORER;
+ case 'metrics_explorer':
+ return ROUTES.METRICS_EXPLORER_EXPLORER;
+ default:
+ return null;
+ }
+}
+
+/**
+ * The agent emits `action.query` as the SigNoz REST query-range request body:
+ *
+ * - V5 (current backend): `{ ..., compositeQuery: { queries: [{ type, spec }] } }`
+ * — each `spec` already carries `filter.expression` directly.
+ * - V3 (legacy): `{ ..., compositeQuery: { builderQueries: { A: {...} } } }`
+ *
+ * The URL's `compositeQuery` param expects the in-app shape
+ * (`{ queryType, builder: { queryData: [...], queryFormulas, queryTraceOperator }, ... }`).
+ * `mapQueryDataFromApi` already handles both API shapes for query-range
+ * responses, so we delegate to it instead of maintaining a parallel translator.
+ *
+ * Defensive: if the agent ever sends the URL shape directly (top-level
+ * `builder.queryData`), we pass it through unchanged.
+ */
+function toUrlCompositeQuery(
+ actionQuery: Record<string, unknown>,
+): Record<string, unknown> | null {
+ // Already in URL shape — use as-is (with envelope defaults filled in).
+ if (
+ actionQuery.builder &&
+ typeof actionQuery.builder === 'object' &&
+ Array.isArray((actionQuery.builder as Record<string, unknown>).queryData)
+ ) {
+ return {
+ queryType: actionQuery.queryType ?? 'builder',
+ promql: actionQuery.promql ?? [],
+ clickhouse_sql: actionQuery.clickhouse_sql ?? [],
+ id: uuidv4(),
+ unit: actionQuery.unit ?? '',
+ ...actionQuery,
+ };
+ }
+
+ // API shape: extract the inner compositeQuery and let the shared mapper
+ // normalise V3/V5 spec → IBuilderQuery for us.
+ const composite = (actionQuery.compositeQuery ?? actionQuery) as
+ | Record<string, unknown>
+ | undefined;
+ if (!composite) {
+ return null;
+ }
+ try {
+ const mapped = mapQueryDataFromApi(
+ composite as unknown as ICompositeMetricQuery,
+ );
+ // `mapQueryDataFromApi` falls back to `initialQueryState.builder` when
+ // neither `queries` nor `builderQueries` is present — detect that and
+ // signal "unrecognised payload" instead of silently navigating to an
+ // empty query.
+ if (mapped.builder.queryData.length === 0) {
+ return null;
+ }
+ return mapped as unknown as Record<string, unknown>;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Tracks apply_filter action keys that have already been auto-applied so we
+ * don't re-fire on re-renders / re-mounts. Module-level (intentionally) — it's
+ * not state we'd ever want to reset on a component unmount; the action's
+ * filters are already on the URL after the first auto-apply.
+ */
+const autoAppliedFilterKeys = new Set<string>();
+
+/**
+ * True when the user is currently on the explorer that an apply_filter
+ * action targets — i.e. when auto-applying makes sense (the page is mounted
+ * and ready to react to a URL change without a route transition).
+ */
+function signalMatchesPathname(
+ signal: ApplyFilterSignalDTO,
+ pathname: string,
+): boolean {
+ switch (signal) {
+ case ApplyFilterSignalDTO.logs:
+ return Boolean(
+ matchPath(pathname, { path: ROUTES.LOGS_EXPLORER, exact: false }),
+ );
+ case ApplyFilterSignalDTO.traces:
+ return Boolean(
+ matchPath(pathname, { path: ROUTES.TRACES_EXPLORER, exact: false }),
+ );
+ case ApplyFilterSignalDTO.metrics:
+ return Boolean(
+ matchPath(pathname, {
+ path: ROUTES.METRICS_EXPLORER_EXPLORER,
+ exact: false,
+ }),
+ );
+ default:
+ return false;
+ }
+}
+
+/**
+ * Stable per-action key used both to dedupe auto-applies and as the React key
+ * for the chip. Mirrors the same construction we do in the render loop below.
+ */
+function actionKey(action: MessageActionDTO, index: number): string {
+ return action.actionMetadataId
+ ? `${action.kind}:${action.actionMetadataId}`
+ : `${action.kind}:${action.label}:${index}`;
+}
+
+/** Maps a signal to its target explorer route. */
+function explorerRouteForSignal(signal: ApplyFilterSignalDTO): string | null {
+ switch (signal) {
+ case ApplyFilterSignalDTO.logs:
+ return ROUTES.LOGS_EXPLORER;
+ case ApplyFilterSignalDTO.traces:
+ return ROUTES.TRACES_EXPLORER;
+ case ApplyFilterSignalDTO.metrics:
+ return ROUTES.METRICS_EXPLORER_EXPLORER;
+ default:
+ return null;
+ }
+}
+
+interface ApplyFilterDeps {
+ history: ReturnType<typeof useHistory>;
+ pathname: string;
+ redirectWithQueryBuilderData: ReturnType<
+ typeof useQueryBuilder
+ >['redirectWithQueryBuilderData'];
+ handleSetQueryData: ReturnType<typeof useQueryBuilder>['handleSetQueryData'];
+}
+
+/**
+ * The V5 query-builder UI binds the WHERE clause CodeMirror editor to
+ * `builder.queryData[i].filter.expression`. The agent normally only sends
+ * `filters.items`, so we derive the expression per query before pushing
+ * state. Same recipe as `pages/<X>/aiActions.ts` — keeps the immediate
+ * UI update consistent with what the URL parser would produce on reload.
+ */
+function withDerivedFilterExpressions(query: Query): Query {
+ const queryData = query.builder.queryData.map((q): IBuilderQuery => {
+ const items = q.filters?.items ?? [];
+ if (items.length === 0) {
+ return q;
+ }
+ const filters: TagFilter = { items, op: q.filters?.op || 'AND' };
+ return {
+ ...q,
+ filters,
+ filter: convertFiltersToExpression(filters),
+ };
+ });
+ return { ...query, builder: { ...query.builder, queryData } };
+}
+
+/**
+ * Single entry point for an apply_filter action — used by both the auto-apply
+ * effect (fired once when the user is already on the matching explorer) and
+ * the manual chip-click handler.
+ *
+ * - On-page: push each builder query into the QueryBuilder provider via
+ * `handleSetQueryData` so the WHERE clause re-renders immediately, then
+ * `redirectWithQueryBuilderData` to persist it on the URL. Mirrors the
+ * page-action recipe — calling redirect alone is not sufficient because
+ * the URL→state effect runs after the next render and the editor binds
+ * to `filter.expression`, not `filters.items`.
+ * - Off-page: use `history.push` so the landing explorer initializes from
+ * the new URL on mount.
+ */
+function applyFilter(action: MessageActionDTO, deps: ApplyFilterDeps): void {
+ // eslint-disable-next-line no-console
+ console.log('[apply_filter] enter', {
+ signal: action.signal,
+ query: action.query,
+ pathname: deps.pathname,
+ });
+ if (!action.signal || !action.query) {
+ // eslint-disable-next-line no-console
+ console.warn('[apply_filter] bail: missing signal or query', action);
+ return;
+ }
+ const urlQuery = toUrlCompositeQuery(action.query as Record<string, unknown>);
+ if (!urlQuery) {
+ // eslint-disable-next-line no-console
+ console.warn(
+ '[apply_filter] bail: toUrlCompositeQuery returned null — agent payload shape unrecognized',
+ action.query,
+ );
+ return;
+ }
+ const normalized = withDerivedFilterExpressions(urlQuery as unknown as Query);
+ // eslint-disable-next-line no-console
+ console.log('[apply_filter] normalized', normalized);
+ if (signalMatchesPathname(action.signal, deps.pathname)) {
+ // eslint-disable-next-line no-console
+ console.log('[apply_filter] on-page → handleSetQueryData + redirect');
+ normalized.builder.queryData.forEach((q, i) => {
+ deps.handleSetQueryData(i, q);
+ });
+ deps.redirectWithQueryBuilderData(normalized);
+ return;
+ }
+ const base = explorerRouteForSignal(action.signal);
+ if (!base) {
+ // eslint-disable-next-line no-console
+ console.warn('[apply_filter] bail: no route for signal', action.signal);
+ return;
+ }
+ // eslint-disable-next-line no-console
+ console.log('[apply_filter] off-page → history.push', base);
+ const encoded = encodeURIComponent(JSON.stringify(normalized));
+ deps.history.push(`${base}?${QueryParams.compositeQuery}=${encoded}`);
+}
+
+/** Picks the right rollback API call for a given action kind. */
+function rollbackCall(
+ kind: MessageActionDTO['kind'],
+): ((id: string) => Promise<unknown>) | null {
+ switch (kind) {
+ case MessageActionKindDTO.undo:
+ return undoExecution;
+ case MessageActionKindDTO.revert:
+ return revertExecution;
+ case MessageActionKindDTO.restore:
+ return restoreExecution;
+ default:
+ return null;
+ }
+}
+
+/**
+ * Renders the actions attached to a single assistant message.
+ *
+ * Hidden when the message has no actions. Rendered inside `MessageBubble`
+ * between the message body and the feedback bar.
+ */
+export default function ActionsSection({
+ actions,
+}: ActionsSectionProps): JSX.Element | null {
+ const history = useHistory();
+ const { pathname } = useLocation();
+ const sendMessage = useAIAssistantStore((s) => s.sendMessage);
+ const { redirectWithQueryBuilderData, handleSetQueryData } = useQueryBuilder();
+
+ // Per-chip click state, keyed by chip key (see `key` below). Persists
+ // loading/success/error so the chip reflects the rollback outcome until
+ // the underlying action.state catches up via a fresh thread fetch.
+ const [results, setResults] = useState<Record<string, ChipResult>>({});
+
+ // Auto-apply any apply_filter action whose signal matches the page the
+ // user is currently on (logs/traces/metrics explorer). Same code path as
+ // the manual click below — just fired automatically once. The chip stays
+ // clickable as a fallback for the off-page case. Dedupes via a module-
+ // level set so re-renders / re-mounts don't re-fire.
+ useEffect(() => {
+ actions.forEach((action, i) => {
+ if (action.kind !== MessageActionKindDTO.apply_filter) {
+ return;
+ }
+ if (!action.signal || !action.query) {
+ return;
+ }
+ if (!signalMatchesPathname(action.signal, pathname)) {
+ return;
+ }
+ const key = actionKey(action, i);
+ if (autoAppliedFilterKeys.has(key)) {
+ return;
+ }
+ autoAppliedFilterKeys.add(key);
+ applyFilter(action, {
+ history,
+ pathname,
+ redirectWithQueryBuilderData,
+ handleSetQueryData,
+ });
+ });
+ }, [
+ actions,
+ pathname,
+ history,
+ redirectWithQueryBuilderData,
+ handleSetQueryData,
+ ]);
+
+ if (actions.length === 0) {
+ return null;
+ }
+
+ const setResult = (key: string, result: ChipResult): void => {
+ setResults((prev) => ({ ...prev, [key]: result }));
+ };
+
+ const runRollback = async (
+ key: string,
+ action: MessageActionDTO,
+ ): Promise<void> => {
+ const call = rollbackCall(action.kind);
+ if (!call || !action.actionMetadataId) {
+ return;
+ }
+ setResult(key, { state: 'loading' });
+ try {
+ await call(action.actionMetadataId);
+ setResult(key, { state: 'success' });
+ } catch (err) {
+ const message = err instanceof Error ? err.message : 'Failed';
+ setResult(key, { state: 'error', error: message });
+ }
+ };
+
+ const handleClick = (key: string, action: MessageActionDTO): void => {
+ switch (action.kind) {
+ case MessageActionKindDTO.open_docs: {
+ if (action.url) {
+ openInNewTab(action.url);
+ }
+ break;
+ }
+ case MessageActionKindDTO.follow_up: {
+ if (action.label) {
+ void sendMessage(action.label);
+ }
+ break;
+ }
+ case MessageActionKindDTO.open_resource: {
+ if (action.resourceType && action.resourceId) {
+ const path = resourceRoute(action.resourceType, action.resourceId);
+ if (path) {
+ history.push(path);
+ }
+ }
+ break;
+ }
+ case MessageActionKindDTO.undo:
+ case MessageActionKindDTO.revert:
+ case MessageActionKindDTO.restore: {
+ void runRollback(key, action);
+ break;
+ }
+ case MessageActionKindDTO.apply_filter: {
+ applyFilter(action, {
+ history,
+ pathname,
+ redirectWithQueryBuilderData,
+ handleSetQueryData,
+ });
+ break;
+ }
+ default:
+ break;
+ }
+ };
+
+ return (
+ <div className={styles.section}>
+ <div className={styles.heading}>
+ <Sparkles size={12} className={styles.headingIcon} />
+ <span className={styles.headingText}>Suggested actions</span>
+ </div>
+
+ <div className={styles.list}>
+ {actions.map((action, i) => {
+ // Stable per-action key (shared with the auto-apply dedupe set).
+ // `actionMetadataId` alone isn't unique — the server can attach
+ // the same id to multiple kinds (e.g. an `undo` and `revert` chip
+ // for the same operation), so we always include the kind. Falls
+ // back to label + index when the id is missing (e.g. follow_up /
+ // open_docs).
+ const key = actionKey(action, i);
+ const result = results[key];
+ const isLoading = result?.state === 'loading';
+ const isSuccess = result?.state === 'success';
+ const isError = result?.state === 'error';
+ // `action.state` is a free-form string from the server (e.g. "active",
+ // "applied"). Without a documented terminal vocabulary we don't auto-
+ // disable on it — only the local in-flight click result does. The state
+ // is still surfaced visually via the suffix pill below.
+ const isDisabled = isLoading || isSuccess;
+
+ const tooltip = isError ? result.error : (action.tooltip ?? undefined);
+
+ let icon: JSX.Element;
+ if (isLoading) {
+ icon = <LoaderCircle size={12} className={styles.spin} />;
+ } else if (isSuccess) {
+ icon = <Check size={12} />;
+ } else if (isError) {
+ icon = <TriangleAlert size={12} />;
+ } else {
+ icon = <ActionIcon kind={action.kind} />;
+ }
+
+ const chip = (
+ <Button
+ variant="outlined"
+ color="secondary"
+ size="sm"
+ className={cx(styles.chip, { [styles.error]: isError })}
+ onClick={(): void => handleClick(key, action)}
+ disabled={isDisabled}
+ aria-label={action.label}
+ prefix={icon}
+ >
+ <span className={styles.chipLabel}>{action.label}</span>
+ </Button>
+ );
+
+ return tooltip ? (
+ <Tooltip key={key} title={tooltip}>
+ {chip}
+ </Tooltip>
+ ) : (
+ <span key={key}>{chip}</span>
+ );
+ })}
+ </div>
+ </div>
+ );
+}
diff --git a/frontend/src/container/AIAssistant/components/ActionsSection/index.ts b/frontend/src/container/AIAssistant/components/ActionsSection/index.ts
new file mode 100644
index 0000000000..06c49d4f02
--- /dev/null
+++ b/frontend/src/container/AIAssistant/components/ActionsSection/index.ts
@@ -0,0 +1,2 @@
+export * from './ActionsSection';
+export { default } from './ActionsSection';
diff --git a/frontend/src/container/AIAssistant/components/ApprovalCard/ApprovalCard.module.scss b/frontend/src/container/AIAssistant/components/ApprovalCard/ApprovalCard.module.scss
new file mode 100644
index 0000000000..041ef4bf91
--- /dev/null
+++ b/frontend/src/container/AIAssistant/components/ApprovalCard/ApprovalCard.module.scss
@@ -0,0 +1,282 @@
+@use '../../_scrollbar' as *;
+
+.card {
+ border: 1px solid var(--l1-border);
+ border-radius: var(--radius-2);
+ padding: 12px;
+ background: var(--l1-background);
+ display: flex;
+ flex-direction: column;
+ gap: 16px;
+ width: 100%;
+
+ &.decided {
+ border-color: var(--l2-border);
+ background: transparent;
+ flex-direction: row;
+ align-items: center;
+ gap: 6px;
+ padding: 6px 10px;
+ }
+}
+
+.header {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+}
+
+.shieldIcon {
+ flex-shrink: 0;
+ color: var(--primary);
+}
+
+.headerLabel {
+ font-size: 12px;
+ font-weight: 600;
+ color: var(--l1-foreground);
+}
+
+.resourceBadge {
+ margin-left: auto;
+ font-size: 10px;
+ font-family: var(--font-mono, monospace);
+ background: var(--l2-background);
+ border: 1px solid var(--l2-border);
+ border-radius: var(--radius-2);
+ padding: 1px 5px;
+ color: var(--l2-foreground);
+}
+
+.summary {
+ font-size: 13px;
+ color: var(--l1-foreground);
+ margin: 0;
+ line-height: 1.5;
+}
+
+.diffSection {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+}
+
+.diffHeader {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px;
+}
+
+.diffHeaderLabel {
+ font-size: 10px;
+ font-weight: 600;
+ text-transform: uppercase;
+ letter-spacing: 0.05em;
+ color: var(--l2-foreground);
+}
+
+.diff {
+ display: flex;
+ gap: 8px;
+
+ // Fixed-height dialog (70vh) — let the diff fill the body and the
+ // JSON panes scroll internally rather than pushing the dialog taller.
+ &.expanded {
+ flex: 1;
+ min-height: 0;
+
+ .diffBlock {
+ min-height: 0;
+ }
+
+ .diffJson {
+ flex: 1;
+ max-height: none;
+ overflow: auto;
+ font-size: 12px;
+ }
+ }
+
+ // Unified view: a single column instead of two side-by-side blocks.
+ // The block-level flex switches to column so the diff pane fills.
+ &.unified {
+ flex-direction: column;
+ }
+}
+
+.diffHeaderActions {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+}
+
+// Container for line-by-line diff output. Mirrors `.diffJson` for scroll
+// + monospace styling but renders an inner stack of `.diffLine` rows
+// instead of a single `<pre>` so individual lines can be colored.
+.diffPane {
+ font-family: var(--font-mono, monospace);
+ font-size: 12px;
+ background: var(--l2-background);
+ border-radius: var(--radius-2);
+ margin: 0;
+ overflow: auto;
+ color: var(--l2-foreground);
+ flex: 1;
+ min-height: 0;
+ @include scrollbar(0.4rem);
+
+ &.wrapped .diffLineText {
+ white-space: pre-wrap;
+ word-break: break-word;
+ }
+}
+
+.diffLine {
+ display: flex;
+ align-items: flex-start;
+ gap: 6px;
+ padding: 0 8px;
+ min-height: 18px;
+ line-height: 1.5;
+}
+
+.diffLineAdd {
+ background: color-mix(in srgb, var(--accent-forest), transparent 88%);
+ color: var(--l1-foreground);
+
+ .diffGutter {
+ color: var(--accent-forest);
+ }
+}
+
+.diffLineRemove {
+ background: color-mix(in srgb, var(--accent-cherry), transparent 88%);
+ color: var(--l1-foreground);
+
+ .diffGutter {
+ color: var(--accent-cherry);
+ }
+}
+
+// Empty filler row in split view to keep before/after columns aligned
+// when one side has an added/removed line. Visible as a faint band so
+// the eye still tracks the row.
+.diffLinePlaceholder {
+ background: color-mix(in srgb, var(--l3-foreground), transparent 94%);
+ min-height: 18px;
+}
+
+.diffGutter {
+ flex-shrink: 0;
+ width: 12px;
+ text-align: center;
+ font-weight: 600;
+ user-select: none;
+ color: var(--l3-foreground);
+}
+
+.diffLineText {
+ white-space: pre;
+ flex: 1;
+ min-width: 0;
+}
+
+.diffBlock {
+ flex: 1;
+ display: flex;
+ flex-direction: column;
+ gap: 3px;
+ min-width: 0;
+
+ &.before .diffLabel {
+ color: var(--accent-cherry);
+ }
+ &.after .diffLabel {
+ color: var(--accent-forest);
+ }
+}
+
+.diffBlockHeader {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px;
+ min-height: 18px;
+}
+
+.diffLabel {
+ font-size: 10px;
+ font-weight: 600;
+ text-transform: uppercase;
+ letter-spacing: 0.05em;
+}
+
+.diffJson {
+ font-family: var(--font-mono, monospace);
+ font-size: 11px;
+ background: var(--l2-background);
+ border-radius: var(--radius-2);
+ padding: 5px 7px;
+ margin: 0;
+ overflow: auto;
+ white-space: pre;
+ max-height: 140px;
+ color: var(--l2-foreground);
+ @include scrollbar(0.4rem);
+
+ // Wrap long lines instead of horizontal scrolling. Used in the
+ // expanded modal when the user toggles the "Wrap text" button.
+ &.wrapped {
+ white-space: pre-wrap;
+ word-break: break-word;
+ overflow-x: hidden;
+ }
+}
+
+.diffModalBody {
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+ flex: 1;
+ min-height: 0;
+ padding: 16px;
+ overflow: hidden;
+}
+
+.diffToolbarRow {
+ display: flex;
+ justify-content: flex-end;
+ align-items: center;
+ gap: 8px;
+ flex-shrink: 0;
+}
+
+.diffModalSummary {
+ font-size: 13px;
+ color: var(--l2-foreground);
+ margin: 0;
+ line-height: 1.5;
+ flex-shrink: 0;
+}
+
+.actions {
+ display: flex;
+ gap: 6px;
+}
+
+.statusIcon {
+ flex-shrink: 0;
+
+ &.ok {
+ color: var(--accent-forest);
+ }
+ &.no {
+ color: var(--l3-foreground);
+ }
+}
+
+.statusText {
+ font-size: 13px;
+ color: var(--l2-foreground);
+}
diff --git a/frontend/src/container/AIAssistant/components/ApprovalCard/ApprovalCard.tsx b/frontend/src/container/AIAssistant/components/ApprovalCard/ApprovalCard.tsx
new file mode 100644
index 0000000000..6465c2d0bc
--- /dev/null
+++ b/frontend/src/container/AIAssistant/components/ApprovalCard/ApprovalCard.tsx
@@ -0,0 +1,471 @@
+import { useEffect, useRef, useState } from 'react';
+import { useCopyToClipboard } from 'react-use';
+import cx from 'classnames';
+import { Button } from '@signozhq/ui/button';
+import {
+ Dialog,
+ DialogCloseButton,
+ DialogContent,
+ DialogHeader,
+ DialogSubtitle,
+ DialogTitle,
+} from '@signozhq/ui/dialog';
+import { ToggleGroup, ToggleGroupItem } from '@signozhq/ui/toggle-group';
+import type {
+ ApprovalEventDTO,
+ ApprovalEventDTODiff,
+} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
+import {
+ Check,
+ Columns2,
+ Copy,
+ List,
+ Maximize2,
+ Shield,
+ WrapText,
+ X,
+} from '@signozhq/icons';
+
+import { useAIAssistantStore } from '../../store/useAIAssistantStore';
+
+import styles from './ApprovalCard.module.scss';
+
+interface ApprovalCardProps {
+ conversationId: string;
+ approval: ApprovalEventDTO;
+}
+
+/**
+ * Rendered when the agent emits an `approval` SSE event.
+ * The agent has paused execution; the user must approve or reject
+ * before the stream resumes on a new execution.
+ */
+export default function ApprovalCard({
+ conversationId,
+ approval,
+}: ApprovalCardProps): JSX.Element {
+ const approveAction = useAIAssistantStore((s) => s.approveAction);
+ const rejectAction = useAIAssistantStore((s) => s.rejectAction);
+ const isStreaming = useAIAssistantStore(
+ (s) => s.streams[conversationId]?.isStreaming ?? false,
+ );
+
+ const [decided, setDecided] = useState<'approved' | 'rejected' | null>(null);
+ const [diffExpanded, setDiffExpanded] = useState(false);
+ const [wrapText, setWrapText] = useState(false);
+ const [viewMode, setViewMode] = useState<DiffViewMode>('split');
+
+ const handleApprove = async (): Promise<void> => {
+ setDecided('approved');
+ await approveAction(conversationId, approval.approvalId);
+ };
+
+ const handleReject = async (): Promise<void> => {
+ setDecided('rejected');
+ await rejectAction(conversationId, approval.approvalId);
+ };
+
+ // After decision the card shows a compact confirmation row
+ if (decided === 'approved') {
+ return (
+ <div className={cx(styles.card, styles.decided)}>
+ <Check size={13} className={cx(styles.statusIcon, styles.ok)} />
+ <span className={styles.statusText}>Approved — resuming…</span>
+ </div>
+ );
+ }
+
+ if (decided === 'rejected') {
+ return (
+ <div className={cx(styles.card, styles.decided)}>
+ <X size={13} className={cx(styles.statusIcon, styles.no)} />
+ <span className={styles.statusText}>Rejected.</span>
+ </div>
+ );
+ }
+
+ return (
+ <div className={styles.card}>
+ <div className={styles.header}>
+ <Shield size={13} className={styles.shieldIcon} />
+ <span className={styles.headerLabel}>Action requires approval</span>
+ <span className={styles.resourceBadge}>
+ {approval.actionType} · {approval.resourceType}
+ </span>
+ </div>
+
+ <p className={styles.summary}>{approval.summary}</p>
+
+ {approval.diff && (
+ <div className={styles.diffSection}>
+ <div className={styles.diffHeader}>
+ <span className={styles.diffHeaderLabel}>Diff</span>
+ <Button
+ variant="link"
+ size="sm"
+ color="secondary"
+ onClick={(): void => setDiffExpanded(true)}
+ title="Expand diff"
+ aria-label="Expand diff"
+ >
+ <Maximize2 size={12} />
+ </Button>
+ </div>
+ <DiffView diff={approval.diff} />
+ </div>
+ )}
+
+ <Dialog open={diffExpanded} onOpenChange={setDiffExpanded}>
+ <DialogContent
+ className={styles.diffDialog}
+ style={{ width: '80vw', maxWidth: '80vw', height: '70vh' }}
+ >
+ <DialogHeader>
+ <DialogTitle>Approval diff</DialogTitle>
+ <DialogSubtitle>
+ {approval.actionType} · {approval.resourceType}
+ </DialogSubtitle>
+ </DialogHeader>
+ <div className={styles.diffModalBody}>
+ <p className={styles.diffModalSummary}>{approval.summary}</p>
+ <div className={styles.diffToolbarRow}>
+ <ToggleGroup
+ type="single"
+ size="sm"
+ value={viewMode}
+ onChange={(next): void => {
+ // Radix `single` group can emit '' when the active item
+ // is clicked again — preserve the current mode.
+ if (next === 'split' || next === 'unified') {
+ setViewMode(next);
+ }
+ }}
+ >
+ <ToggleGroupItem value="split" aria-label="Split view">
+ <Columns2 size={12} />
+ </ToggleGroupItem>
+ <ToggleGroupItem value="unified" aria-label="Unified view">
+ <List size={12} />
+ </ToggleGroupItem>
+ </ToggleGroup>
+ <ToggleGroup
+ type="multiple"
+ size="sm"
+ value={wrapText ? ['wrap'] : []}
+ onChange={(next): void => setWrapText(next.includes('wrap'))}
+ >
+ <ToggleGroupItem
+ value="wrap"
+ aria-label={wrapText ? 'Disable text wrap' : 'Wrap long lines'}
+ >
+ <WrapText size={12} />
+ </ToggleGroupItem>
+ </ToggleGroup>
+ </div>
+ {approval.diff && (
+ <DiffView
+ diff={approval.diff}
+ expanded
+ wrapText={wrapText}
+ viewMode={viewMode}
+ />
+ )}
+ </div>
+ <DialogCloseButton onClick={(): void => setDiffExpanded(false)} />
+ </DialogContent>
+ </Dialog>
+
+ <div className={styles.actions}>
+ <Button
+ variant="solid"
+ size="sm"
+ onClick={handleApprove}
+ disabled={isStreaming}
+ prefix={<Check />}
+ >
+ Approve
+ </Button>
+ <Button
+ variant="outlined"
+ size="sm"
+ color="secondary"
+ onClick={handleReject}
+ disabled={isStreaming}
+ prefix={<X />}
+ >
+ Reject
+ </Button>
+ </div>
+ </div>
+ );
+}
+
+type DiffViewMode = 'split' | 'unified';
+
+interface DiffViewProps {
+ diff: ApprovalEventDTODiff;
+ expanded?: boolean;
+ /** When true, long lines wrap instead of horizontally scrolling. */
+ wrapText?: boolean;
+ /** Side-by-side ('split') vs single-column ('unified'). Only honored when expanded. */
+ viewMode?: DiffViewMode;
+}
+
+function DiffView({
+ diff,
+ expanded = false,
+ wrapText = false,
+ viewMode = 'split',
+}: DiffViewProps): JSX.Element {
+ const beforeText =
+ diff.before !== undefined ? JSON.stringify(diff.before, null, 2) : '';
+ const afterText =
+ diff.after !== undefined ? JSON.stringify(diff.after, null, 2) : '';
+
+ // In the inline (collapsed) preview keep the original two-pane layout
+ // without diff highlighting — diffing is opt-in via the expanded modal.
+ if (!expanded) {
+ const jsonClass = cx(styles.diffJson, { [styles.wrapped]: wrapText });
+ return (
+ <div className={styles.diff}>
+ {diff.before !== undefined && (
+ <div className={cx(styles.diffBlock, styles.before)}>
+ <div className={styles.diffBlockHeader}>
+ <span className={styles.diffLabel}>Before</span>
+ </div>
+ <pre className={jsonClass}>{beforeText}</pre>
+ </div>
+ )}
+ {diff.after !== undefined && (
+ <div className={cx(styles.diffBlock, styles.after)}>
+ <div className={styles.diffBlockHeader}>
+ <span className={styles.diffLabel}>After</span>
+ </div>
+ <pre className={jsonClass}>{afterText}</pre>
+ </div>
+ )}
+ </div>
+ );
+ }
+
+ const lines = computeLineDiff(beforeText, afterText);
+
+ if (viewMode === 'unified') {
+ // Build the same +/-/space-prefixed text that's on screen so Copy
+ // gives the user exactly what they see.
+ const unifiedText = lines
+ .map((line) => `${prefixFor(line.op)} ${line.text}`)
+ .join('\n');
+ return (
+ <div className={cx(styles.diff, styles.expanded, styles.unified)}>
+ <div className={styles.diffBlockHeader}>
+ <span className={styles.diffLabel}>Diff</span>
+ <div className={styles.diffHeaderActions}>
+ <CopyButton text={unifiedText} label="diff" />
+ </div>
+ </div>
+ <div className={cx(styles.diffPane, { [styles.wrapped]: wrapText })}>
+ {lines.map((line, idx) => (
+ <DiffLine
+ // stable enough — input strings are immutable for the view's lifetime
+ // eslint-disable-next-line react/no-array-index-key
+ key={idx}
+ op={line.op}
+ text={line.text}
+ prefix={prefixFor(line.op)}
+ />
+ ))}
+ </div>
+ </div>
+ );
+ }
+
+ // Split view: align side-by-side using the LCS result. `equal` lines
+ // appear on both sides; `remove` only on the left, `add` only on the
+ // right (with an empty placeholder on the missing side so rows stay
+ // aligned vertically).
+ return (
+ <div className={cx(styles.diff, styles.expanded)}>
+ <div className={cx(styles.diffBlock, styles.before)}>
+ <div className={styles.diffBlockHeader}>
+ <span className={styles.diffLabel}>Before</span>
+ <CopyButton text={beforeText} label="before" />
+ </div>
+ <div className={cx(styles.diffPane, { [styles.wrapped]: wrapText })}>
+ {lines.map((line, idx) => {
+ const op = line.op === 'add' ? 'placeholder' : line.op;
+ const text = line.op === 'add' ? '' : line.text;
+ // eslint-disable-next-line react/no-array-index-key
+ return <DiffLine key={idx} op={op} text={text} />;
+ })}
+ </div>
+ </div>
+ <div className={cx(styles.diffBlock, styles.after)}>
+ <div className={styles.diffBlockHeader}>
+ <span className={styles.diffLabel}>After</span>
+ <CopyButton text={afterText} label="after" />
+ </div>
+ <div className={cx(styles.diffPane, { [styles.wrapped]: wrapText })}>
+ {lines.map((line, idx) => {
+ const op = line.op === 'remove' ? 'placeholder' : line.op;
+ const text = line.op === 'remove' ? '' : line.text;
+ // eslint-disable-next-line react/no-array-index-key
+ return <DiffLine key={idx} op={op} text={text} />;
+ })}
+ </div>
+ </div>
+ </div>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Line diff — small LCS-based implementation. Avoids pulling in `diff`
+// since the inputs are JSON.stringify output (line-oriented, typically
+// well under a few hundred lines for resource diffs).
+// ---------------------------------------------------------------------------
+
+type LineOp = 'equal' | 'add' | 'remove';
+type RenderOp = LineOp | 'placeholder';
+interface DiffLineEntry {
+ op: LineOp;
+ text: string;
+}
+
+// eslint-disable-next-line sonarjs/cognitive-complexity
+function computeLineDiff(before: string, after: string): DiffLineEntry[] {
+ if (before === after) {
+ return splitLines(before).map((text) => ({ op: 'equal', text }));
+ }
+ const a = splitLines(before);
+ const b = splitLines(after);
+ const m = a.length;
+ const n = b.length;
+
+ // dp[i][j] = length of LCS between a[0..i] and b[0..j]
+ const dp: number[][] = Array.from({ length: m + 1 }, () =>
+ new Array<number>(n + 1).fill(0),
+ );
+ for (let i = 1; i <= m; i += 1) {
+ for (let j = 1; j <= n; j += 1) {
+ if (a[i - 1] === b[j - 1]) {
+ dp[i][j] = dp[i - 1][j - 1] + 1;
+ } else {
+ dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
+ }
+ }
+ }
+
+ // Backtrack to produce the diff
+ const result: DiffLineEntry[] = [];
+ let i = m;
+ let j = n;
+ while (i > 0 && j > 0) {
+ if (a[i - 1] === b[j - 1]) {
+ result.push({ op: 'equal', text: a[i - 1] });
+ i -= 1;
+ j -= 1;
+ } else if (dp[i - 1][j] >= dp[i][j - 1]) {
+ result.push({ op: 'remove', text: a[i - 1] });
+ i -= 1;
+ } else {
+ result.push({ op: 'add', text: b[j - 1] });
+ j -= 1;
+ }
+ }
+ while (i > 0) {
+ result.push({ op: 'remove', text: a[i - 1] });
+ i -= 1;
+ }
+ while (j > 0) {
+ result.push({ op: 'add', text: b[j - 1] });
+ j -= 1;
+ }
+ result.reverse();
+ return result;
+}
+
+function splitLines(text: string): string[] {
+ if (text === '') {
+ return [];
+ }
+ return text.split('\n');
+}
+
+function prefixFor(op: LineOp): string {
+ if (op === 'add') {
+ return '+';
+ }
+ if (op === 'remove') {
+ return '-';
+ }
+ return ' ';
+}
+
+interface DiffLineProps {
+ op: RenderOp;
+ text: string;
+ /** Optional gutter prefix used in unified view (`+` / `-` / ` `). */
+ prefix?: string;
+}
+
+function DiffLine({ op, text, prefix }: DiffLineProps): JSX.Element {
+ const cls = cx(styles.diffLine, {
+ [styles.diffLineAdd]: op === 'add',
+ [styles.diffLineRemove]: op === 'remove',
+ [styles.diffLinePlaceholder]: op === 'placeholder',
+ });
+ return (
+ <div className={cls}>
+ {prefix !== undefined && (
+ <span className={styles.diffGutter} aria-hidden="true">
+ {prefix}
+ </span>
+ )}
+ <span className={styles.diffLineText}>{text || ' '}</span>
+ </div>
+ );
+}
+
+interface CopyButtonProps {
+ text: string;
+ label: string;
+}
+
+function CopyButton({ text, label }: CopyButtonProps): JSX.Element {
+ const [copied, setCopied] = useState(false);
+ const [, copyToClipboard] = useCopyToClipboard();
+ // Track the timeout so an unmount mid-flight doesn't try to setState on
+ // a dead component (and so a rapid re-click resets the 1.5s window).
+ const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+
+ useEffect(
+ () => (): void => {
+ if (timeoutRef.current) {
+ clearTimeout(timeoutRef.current);
+ }
+ },
+ [],
+ );
+
+ const handleCopy = (): void => {
+ copyToClipboard(text);
+ setCopied(true);
+ if (timeoutRef.current) {
+ clearTimeout(timeoutRef.current);
+ }
+ timeoutRef.current = setTimeout(() => setCopied(false), 1500);
+ };
+
+ return (
+ <Button
+ variant="ghost"
+ size="sm"
+ color="secondary"
+ onClick={handleCopy}
+ title={copied ? `Copied ${label}` : `Copy ${label}`}
+ aria-label={copied ? `Copied ${label}` : `Copy ${label}`}
+ >
+ {copied ? <Check size={12} /> : <Copy size={12} />}
+ </Button>
+ );
+}
diff --git a/frontend/src/container/AIAssistant/components/ApprovalCard/index.ts b/frontend/src/container/AIAssistant/components/ApprovalCard/index.ts
new file mode 100644
index 0000000000..eab6668b7b
--- /dev/null
+++ b/frontend/src/container/AIAssistant/components/ApprovalCard/index.ts
@@ -0,0 +1,2 @@
+export * from './ApprovalCard';
+export { default } from './ApprovalCard';
diff --git a/frontend/src/container/AIAssistant/components/ChatInput/ChatInput.module.scss b/frontend/src/container/AIAssistant/components/ChatInput/ChatInput.module.scss
new file mode 100644
index 0000000000..eb15699000
--- /dev/null
+++ b/frontend/src/container/AIAssistant/components/ChatInput/ChatInput.module.scss
@@ -0,0 +1,462 @@
+@use '../../_scrollbar' as *;
+
+.input {
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+ background: var(--l1-background);
+ border-radius: var(--radius-2);
+ padding: 8px;
+ border: 1px solid var(--l1-border);
+ transition: border-color 0.15s;
+ position: relative;
+
+ &:focus-within {
+ border-color: var(--l1-border);
+ }
+}
+
+.attachments {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px;
+}
+
+.contextTags {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px;
+}
+
+.contextTag {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ font-size: 11px;
+ background: var(--l2-background);
+ border: 1px solid var(--l1-border);
+ border-radius: var(--radius-2);
+ padding: 4px 6px 4px 8px;
+ color: var(--l1-foreground);
+
+ button {
+ height: auto !important;
+ min-height: 0 !important;
+ width: auto !important;
+ }
+
+ // `auto` chips are derived from the URL (current page) — visually
+ // distinguished by a dashed border + slightly muted text so the user
+ // can tell them apart from explicit @-mentions. Tighter padding /
+ // font-size keeps them visually subordinate to user `@`-picks.
+ &.auto {
+ border-style: dashed;
+ color: var(--l2-foreground);
+ background: transparent;
+ font-size: 10px;
+ padding: 2px 4px 2px 6px;
+ gap: 3px;
+ }
+}
+
+.contextTagContent {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ max-width: 220px;
+
+ .contextTagCategory {
+ flex-shrink: 0;
+ }
+
+ .contextTagLabel {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+}
+
+.contextTagCategory {
+ flex-shrink: 0;
+}
+
+.contextTagLabel {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.contextTagRemove {
+ flex-shrink: 0;
+ padding: 0 !important;
+ height: auto !important;
+ min-height: 0 !important;
+}
+
+.attachmentChip {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ font-size: 11px;
+ background: var(--l3-background);
+ border-radius: var(--radius-2);
+ padding: 2px 6px 2px 8px;
+ color: var(--l2-foreground);
+ max-width: 180px;
+}
+
+.attachmentName {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.attachmentRemove {
+ flex-shrink: 0;
+ padding: 0 !important;
+ height: auto !important;
+ min-height: 0 !important;
+}
+
+.row {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+}
+
+.composer {
+ background: var(--l2-background);
+ border: 1px solid var(--l2-border);
+ border-radius: var(--radius-2);
+ padding: 4px;
+}
+
+.footer {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px;
+}
+
+.leftActions,
+.rightActions {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+}
+
+.attachBtn {
+ color: var(--l3-foreground);
+}
+
+.contextBtn {
+ flex-shrink: 0;
+ gap: 6px;
+ border-style: dashed !important;
+ padding-inline: 12px !important;
+}
+
+.textarea {
+ display: block;
+ width: 100%;
+ background: transparent;
+ border: none;
+ outline: none;
+ resize: none;
+ color: var(--l1-foreground);
+ font-size: 12px;
+ line-height: 1.5;
+ overflow-y: auto;
+ font-family: inherit;
+ @include scrollbar(0.2rem);
+
+ &::placeholder {
+ color: var(--l3-foreground);
+ opacity: 0.6;
+ }
+
+ &:disabled {
+ opacity: 0.2;
+ cursor: not-allowed;
+ }
+}
+
+.charWarning {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ width: 100%;
+ padding: 6px 8px;
+ font-size: 11px;
+ font-weight: 500;
+ color: var(--accent-sienna);
+ background: color-mix(in srgb, var(--accent-sienna), transparent 90%);
+ border: 1px solid color-mix(in srgb, var(--accent-sienna), transparent 65%);
+ border-radius: var(--radius-2);
+}
+
+.sendBtn {
+ flex-shrink: 0;
+ border-radius: var(--radius-2);
+
+ &.stop {
+ background: var(--accent-cherry) !important;
+ border-color: var(--accent-cherry) !important;
+
+ &:hover {
+ opacity: 0.85;
+ }
+ }
+}
+
+.contextPopover {
+ width: 480px !important;
+ max-width: min(92vw, 480px);
+ margin-left: 16px;
+ border: 1px solid var(--l2-border);
+ border-radius: var(--radius-2);
+ background: var(--l1-background);
+ box-shadow: 0 16px 36px rgba(0, 0, 0, 0.3);
+ padding: 8px;
+ // Clip horizontal overflow so long entity titles can't poke past the
+ // popover's right edge. Vertical overflow is handled inside
+ // `.contextPopoverEntities`.
+ overflow-x: hidden;
+
+ --popover-padding: 0;
+
+ z-index: 1000;
+}
+
+.contextPopoverContent {
+ display: grid;
+ grid-template-columns: 180px 1fr;
+ min-height: 250px;
+ min-width: 0;
+}
+
+.contextPopoverCategories {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ padding: 8px;
+ border-right: 1px solid var(--l2-border);
+}
+
+.contextPopoverCategoryItem {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ height: 32px;
+ padding: 0 8px;
+ border: 1px solid color-mix(in srgb, var(--l1-foreground), transparent 96%);
+ border-radius: var(--radius-2);
+ font-size: 12px;
+ font-weight: 550;
+ text-align: left;
+ cursor: pointer;
+ transition:
+ background 0.15s ease,
+ border-color 0.15s ease,
+ color 0.15s ease;
+
+ &:hover {
+ background: var(--l2-background);
+ color: var(--l1-foreground);
+ border-color: var(--l2-border);
+ }
+
+ &.active {
+ background: color-mix(in srgb, var(--accent-primary), transparent 86%);
+ color: var(--l1-foreground);
+ border-color: color-mix(in srgb, var(--accent-primary), transparent 64%);
+ }
+}
+
+.contextPopoverRight {
+ display: flex;
+ flex-direction: column;
+ min-width: 0;
+ min-height: 0;
+ // Match the previous fixed entity-list height so the inner search +
+ // scrolling list have a definite container to size against.
+ height: 320px;
+}
+
+.contextPopoverSearch {
+ padding: 8px;
+ flex-shrink: 0;
+ position: relative;
+ width: 90%;
+}
+
+.contextPopoverSearchInput {
+ width: 100%;
+ box-sizing: border-box;
+}
+
+.contextPopoverEntities {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ flex: 1;
+ min-height: 0;
+ overflow-y: auto;
+ overflow-x: hidden;
+ padding: 8px;
+ min-width: 0;
+ @include scrollbar(0.2rem);
+}
+
+.contextPopoverEntityItem {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 8px;
+ border: 1px solid color-mix(in srgb, var(--l1-foreground), transparent 96%);
+ border-radius: var(--radius-2);
+ color: var(--l1-foreground);
+ font-size: 12px;
+ font-weight: 500;
+ line-height: 1.35;
+ text-align: left;
+ cursor: pointer;
+ // Required for the inner span's `text-overflow: ellipsis` to engage —
+ // flex items default to `min-width: auto` (intrinsic width) and would
+ // otherwise grow past their parent's width to fit long titles.
+ min-width: 0;
+
+ transition:
+ background 0.15s ease,
+ border-color 0.15s ease,
+ transform 0.15s ease;
+
+ &:hover {
+ background: var(--l2-background);
+ border-color: var(--l2-border);
+ transform: translateY(-1px);
+ }
+
+ &.selected {
+ background: color-mix(in srgb, var(--accent-primary), transparent 86%);
+ border-color: color-mix(in srgb, var(--accent-primary), transparent 64%);
+
+ span {
+ color: var(--l1-foreground);
+ font-weight: 600;
+ }
+ }
+}
+
+.contextPopoverEntityItemText {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.contextPopoverEmpty {
+ font-size: 12px;
+ color: var(--l3-foreground);
+ padding: 10px 8px;
+}
+
+.micBtn {
+ flex-shrink: 0;
+}
+
+.micRecording {
+ display: flex;
+ align-items: center;
+ background: var(--l2-background);
+ border-radius: 999px;
+ padding: 2px;
+ gap: 0;
+ flex-shrink: 0;
+}
+
+.micDiscard,
+.micStop {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ flex-shrink: 0;
+ width: 24px;
+ height: 24px;
+ border-radius: 50%;
+ border: none;
+ cursor: pointer;
+}
+
+.micDiscard {
+ background: var(--l2-background);
+ color: var(--l2-foreground);
+ transition: color 0.12s;
+
+ &:hover {
+ color: var(--l1-foreground);
+ }
+}
+
+.micWaves {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 2px;
+ height: 20px;
+ padding: 0 6px;
+
+ span {
+ display: block;
+ width: 2px;
+ border-radius: 2px;
+ background: var(--l1-foreground);
+ animation: voiceWave 0.9s ease-in-out infinite;
+
+ &:nth-child(1) {
+ animation-delay: 0s;
+ }
+ &:nth-child(2) {
+ animation-delay: 0.1s;
+ }
+ &:nth-child(3) {
+ animation-delay: 0.2s;
+ }
+ &:nth-child(4) {
+ animation-delay: 0.3s;
+ }
+ &:nth-child(5) {
+ animation-delay: 0.4s;
+ }
+ &:nth-child(6) {
+ animation-delay: 0.3s;
+ }
+ &:nth-child(7) {
+ animation-delay: 0.2s;
+ }
+ &:nth-child(8) {
+ animation-delay: 0.1s;
+ }
+ }
+}
+
+@keyframes voiceWave {
+ 0%,
+ 100% {
+ height: 2px;
+ opacity: 0.4;
+ }
+ 50% {
+ height: 12px;
+ opacity: 1;
+ }
+}
+
+.micStop {
+ background: var(--accent-cherry);
+ color: var(--accent-cherry-foreground);
+ transition: opacity 0.12s;
+
+ &:hover {
+ opacity: 0.85;
+ }
+}
diff --git a/frontend/src/container/AIAssistant/components/ChatInput/ChatInput.tsx b/frontend/src/container/AIAssistant/components/ChatInput/ChatInput.tsx
new file mode 100644
index 0000000000..921f3deced
--- /dev/null
+++ b/frontend/src/container/AIAssistant/components/ChatInput/ChatInput.tsx
@@ -0,0 +1,944 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+import { useQueryClient } from 'react-query';
+import cx from 'classnames';
+import { Badge } from '@signozhq/ui/badge';
+import { Button } from '@signozhq/ui/button';
+import { Input } from '@signozhq/ui/input';
+import { Popover, PopoverContent, PopoverTrigger } from '@signozhq/ui/popover';
+import { Tooltip } from '@signozhq/ui/tooltip';
+import type { UploadFile } from 'antd';
+import {
+ getListRulesQueryKey,
+ useListRules,
+} from 'api/generated/services/rules';
+import type { ListRules200 } from 'api/generated/services/sigNoz.schemas';
+import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
+import { useGetAllDashboard } from 'hooks/dashboard/useGetAllDashboard';
+import { useQueryService } from 'hooks/useQueryService';
+import type { SuccessResponseV2 } from 'types/api';
+import type { Dashboard } from 'types/api/dashboard/getAll';
+// eslint-disable-next-line
+import { useSelector } from 'react-redux';
+import { AppState } from 'store/reducers';
+import { GlobalReducer } from 'types/reducer/globalTime';
+
+import { useSpeechRecognition } from '../../hooks/useSpeechRecognition';
+import { MessageAttachment } from '../../types';
+import { MessageContext } from '../../../../api/ai-assistant/chat';
+import {
+ Bell,
+ LayoutDashboard,
+ Mic,
+ Plus,
+ Search,
+ Send,
+ ShieldCheck,
+ Square,
+ TriangleAlert,
+ X,
+} from '@signozhq/icons';
+
+import styles from './ChatInput.module.scss';
+
+interface ChatInputProps {
+ onSend: (
+ text: string,
+ attachments?: MessageAttachment[],
+ contexts?: MessageContext[],
+ ) => void;
+ onCancel?: () => void;
+ disabled?: boolean;
+ isStreaming?: boolean;
+ /**
+ * URL-derived `source: 'auto'` contexts representing the page the user is
+ * currently looking at. Rendered as chips alongside the user's `@`-mention
+ * picks and merged into the outgoing `contexts` array.
+ */
+ autoContexts?: MessageContext[];
+ /**
+ * Called when the user dismisses an auto-context chip. The parent owns
+ * the dismissed set and is responsible for filtering the next render's
+ * `autoContexts` to exclude the key.
+ */
+ onDismissAutoContext?: (key: string) => void;
+}
+
+/** Stable identity for an auto-context entry — used as React key + dismissal id. */
+export function autoContextKey(ctx: MessageContext): string {
+ const page = (ctx.metadata as { page?: string } | null | undefined)?.page;
+ return `auto:${ctx.type}:${ctx.resourceId ?? ''}:${page ?? ''}`;
+}
+
+/**
+ * Friendly label for an auto-derived context chip. We don't fetch resource
+ * names from the URL alone, so we lean on the page identity that already
+ * lives in `metadata.page`, falling back to the resource type.
+ */
+function autoContextLabel(ctx: MessageContext): string {
+ const page = (ctx.metadata as { page?: string } | null | undefined)?.page;
+ switch (page) {
+ case 'dashboard_detail':
+ return 'Current dashboard';
+ case 'panel_edit':
+ return 'Editing panel';
+ case 'panel_fullscreen':
+ return 'Panel (fullscreen)';
+ case 'dashboard_list':
+ return 'Dashboards';
+ case 'alert_edit':
+ return 'Editing alert';
+ case 'alert_new':
+ return 'New alert';
+ case 'alerts_triggered':
+ return 'Triggered alerts';
+ case 'alert_list':
+ return 'Alerts';
+ case 'service_detail':
+ return 'Current service';
+ case 'services_list':
+ return 'Services';
+ case 'logs_explorer':
+ return 'Logs explorer';
+ case 'log_detail':
+ return 'Log details';
+ case 'traces_explorer':
+ return 'Traces explorer';
+ case 'trace_detail':
+ return 'Trace details';
+ case 'metrics_explorer':
+ return 'Metrics explorer';
+ default:
+ return ctx.type;
+ }
+}
+
+/** Capitalised category badge text — e.g. "Dashboard", "Logs explorer". */
+function autoContextCategory(ctx: MessageContext): string {
+ switch (ctx.type) {
+ case 'dashboard':
+ return 'Dashboard';
+ case 'alert':
+ return 'Alert';
+ case 'service':
+ return 'Service';
+ case 'logs_explorer':
+ return 'Logs';
+ case 'traces_explorer':
+ return 'Traces';
+ case 'metrics_explorer':
+ return 'Metrics';
+ case 'saved_view':
+ return 'Saved view';
+ default:
+ return ctx.type;
+ }
+}
+
+const MAX_INPUT_LENGTH = 20000;
+const WARNING_THRESHOLD = 15000;
+const HOME_SERVICES_INTERVAL = 30 * 60 * 1000;
+
+const CONTEXT_CATEGORIES = ['Dashboards', 'Alerts', 'Services'] as const;
+
+type ContextCategory = (typeof CONTEXT_CATEGORIES)[number];
+
+interface SelectedContextItem {
+ category: ContextCategory;
+ entityId: string;
+ value: string;
+}
+
+function toMessageContext(item: SelectedContextItem): MessageContext | null {
+ switch (item.category) {
+ case 'Dashboards':
+ return {
+ source: 'mention',
+ type: 'dashboard',
+ resourceId: item.entityId,
+ resourceName: item.value,
+ };
+ case 'Alerts':
+ return {
+ source: 'mention',
+ type: 'alert',
+ resourceId: item.entityId,
+ resourceName: item.value,
+ };
+ case 'Services':
+ return {
+ source: 'mention',
+ type: 'service',
+ resourceId: item.entityId,
+ resourceName: item.value,
+ };
+ default:
+ return null;
+ }
+}
+
+interface ContextEntityItem {
+ id: string;
+ value: string;
+}
+
+const CONTEXT_CATEGORY_ICONS = {
+ Dashboards: LayoutDashboard,
+ Alerts: Bell,
+ Services: ShieldCheck,
+} satisfies Record<ContextCategory, unknown>;
+
+function fileToDataUrl(file: File): Promise<string> {
+ return new Promise((resolve, reject) => {
+ const reader = new FileReader();
+ reader.onload = (): void => resolve(reader.result as string);
+ reader.onerror = reject;
+ reader.readAsDataURL(file);
+ });
+}
+
+export default function ChatInput({
+ onSend,
+ onCancel,
+ disabled,
+ isStreaming = false,
+ autoContexts,
+ onDismissAutoContext,
+}: ChatInputProps): JSX.Element {
+ const { selectedTime } = useSelector<AppState, GlobalReducer>(
+ (state) => state.globalTime,
+ );
+ const [text, setText] = useState('');
+ const [pendingFiles, setPendingFiles] = useState<UploadFile[]>([]);
+ const [selectedContexts, setSelectedContexts] = useState<
+ SelectedContextItem[]
+ >([]);
+ const [isContextPickerOpen, setIsContextPickerOpen] = useState(false);
+ const [activeContextCategory, setActiveContextCategory] =
+ useState<ContextCategory>('Dashboards');
+ const [pickerSearchQuery, setPickerSearchQuery] = useState('');
+ const queryClient = useQueryClient();
+
+ // When the picker was opened by typing `@` in the textarea, this holds the
+ // span of `@<query>` (start / end indices into `text`). Used both for live
+ // filtering of the entity list and for splicing the trigger out of the
+ // text once the user picks an item. `null` when the picker is opened via
+ // the "Add Context" button (no trigger to strip, no query to filter).
+ const [mentionRange, setMentionRange] = useState<{
+ start: number;
+ end: number;
+ } | null>(null);
+ const [servicesTimeRange] = useState(() => {
+ const now = Date.now();
+ return {
+ startTime: now - HOME_SERVICES_INTERVAL,
+ endTime: now,
+ };
+ });
+ // Stores the already-committed final text so interim results don't overwrite it
+ const committedTextRef = useRef('');
+ const textareaRef = useRef<HTMLTextAreaElement>(null);
+ const inputRootRef = useRef<HTMLDivElement>(null);
+
+ const capText = useCallback(
+ (value: string) => value.slice(0, MAX_INPUT_LENGTH),
+ [],
+ );
+
+ const syncContextPickerFromText = useCallback(
+ (value: string, caret: number) => {
+ const beforeCaret = value.slice(0, caret);
+ const atIndex = beforeCaret.lastIndexOf('@');
+ if (atIndex < 0) {
+ setIsContextPickerOpen(false);
+ setMentionRange(null);
+ return;
+ }
+ const query = beforeCaret.slice(atIndex + 1);
+ if (/\s/.test(query)) {
+ setIsContextPickerOpen(false);
+ setMentionRange(null);
+ return;
+ }
+ setIsContextPickerOpen(true);
+ setMentionRange({ start: atIndex, end: caret });
+ },
+ [],
+ );
+
+ const toggleContextSelection = useCallback(
+ (category: ContextCategory, entityId: string, contextValue: string) => {
+ const wasSelected = selectedContexts.some(
+ (item) => item.category === category && item.entityId === entityId,
+ );
+
+ setSelectedContexts((prev) => {
+ if (wasSelected) {
+ return prev.filter(
+ (item) => !(item.category === category && item.entityId === entityId),
+ );
+ }
+ return [...prev, { category, entityId, value: contextValue }];
+ });
+
+ // When the user picks an item via the `@` trigger, splice the
+ // `@<query>` span out of the textarea so their prose stays clean.
+ // Skip on remove (no trigger to strip) and when the picker was
+ // opened from the "Add Context" button (no mention range tracked).
+ if (!wasSelected && mentionRange) {
+ const next =
+ text.slice(0, mentionRange.start) + text.slice(mentionRange.end);
+ setText(next);
+ committedTextRef.current = next;
+ setMentionRange(null);
+ }
+ },
+ [mentionRange, selectedContexts, text],
+ );
+
+ // Focus the textarea when this component mounts (panel/modal open)
+ useEffect(() => {
+ textareaRef.current?.focus();
+ }, []);
+
+ const handleSend = useCallback(async () => {
+ const trimmed = text.trim();
+ if (!trimmed && pendingFiles.length === 0) {
+ return;
+ }
+
+ const attachments: MessageAttachment[] = await Promise.all(
+ pendingFiles.map(async (f) => {
+ const dataUrl = f.originFileObj ? await fileToDataUrl(f.originFileObj) : '';
+ return {
+ name: f.name,
+ type: f.type ?? 'application/octet-stream',
+ dataUrl,
+ };
+ }),
+ );
+
+ const userContexts = selectedContexts
+ .map(toMessageContext)
+ .filter((context): context is MessageContext => context !== null);
+ // Auto contexts come first so the agent reads "current page" before
+ // any explicit @-mentions when both are present.
+ const contexts = [...(autoContexts ?? []), ...userContexts];
+ const payload = capText(trimmed);
+
+ onSend(
+ payload,
+ attachments.length > 0 ? attachments : undefined,
+ contexts.length > 0 ? contexts : undefined,
+ );
+ setText('');
+ committedTextRef.current = '';
+ setPendingFiles([]);
+ setSelectedContexts([]);
+ textareaRef.current?.focus();
+ }, [text, pendingFiles, onSend, selectedContexts, autoContexts, capText]);
+
+ const handleKeyDown = useCallback(
+ (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
+ if (e.key === 'Escape' && isContextPickerOpen) {
+ setIsContextPickerOpen(false);
+ return;
+ }
+ if (e.key === 'Enter' && !e.shiftKey) {
+ e.preventDefault();
+ void handleSend();
+ }
+ },
+ [handleSend, isContextPickerOpen],
+ );
+
+ const removeFile = useCallback((uid: string) => {
+ setPendingFiles((prev) => prev.filter((f) => f.uid !== uid));
+ }, []);
+
+ const removeContext = useCallback(
+ (category: ContextCategory, entityId: string) => {
+ setSelectedContexts((prev) =>
+ prev.filter(
+ (item) => !(item.category === category && item.entityId === entityId),
+ ),
+ );
+ },
+ [],
+ );
+
+ // ── Voice input ────────────────────────────────────────────────────────────
+
+ const {
+ isListening,
+ isSupported,
+ permission: micPermission,
+ start,
+ discard,
+ } = useSpeechRecognition({
+ onTranscript: (transcriptText, isFinal) => {
+ if (isFinal) {
+ // Commit: append to whatever the user has already typed
+ const separator = committedTextRef.current ? ' ' : '';
+ const next = capText(committedTextRef.current + separator + transcriptText);
+ committedTextRef.current = next;
+ setText(next);
+ } else {
+ // Interim: live preview appended to committed text, not yet persisted
+ const separator = committedTextRef.current ? ' ' : '';
+ setText(capText(committedTextRef.current + separator + transcriptText));
+ }
+ },
+ });
+
+ const showMic = isSupported && micPermission !== 'denied';
+
+ // Stop recording and immediately send whatever is in the textarea.
+ const handleStopAndSend = useCallback(async () => {
+ // Promote the displayed text (interim included) to committed so handleSend sees it.
+ committedTextRef.current = capText(text);
+ // Stop recognition without triggering onTranscript again (would double-append).
+ discard();
+ await handleSend();
+ }, [text, discard, handleSend, capText]);
+
+ // Stop recording and revert the textarea to what it was before voice started.
+ const handleDiscard = useCallback(() => {
+ discard();
+ setText(committedTextRef.current);
+ textareaRef.current?.focus();
+ }, [discard]);
+
+ // ── Push-to-talk (Cmd/Ctrl + Shift + Space) ────────────────────────────────
+ // Hold the combo to record; release Space to submit. We track which key
+ // triggered PTT in a ref so a late-released modifier (Cmd/Shift) doesn't
+ // accidentally stop the session. Auto-repeat is suppressed via a
+ // "session active" ref so a held key only calls `start()` once.
+ const pttActiveRef = useRef(false);
+ useEffect(() => {
+ if (!isSupported || micPermission === 'denied') {
+ return undefined;
+ }
+
+ const handleKeyDown = (e: KeyboardEvent): void => {
+ const isComboKey =
+ (e.metaKey || e.ctrlKey) &&
+ e.shiftKey &&
+ (e.code === 'Space' || e.key === ' ');
+ if (!isComboKey || disabled || isStreaming) {
+ return;
+ }
+ e.preventDefault();
+ if (pttActiveRef.current) {
+ return; // ignore auto-repeat
+ }
+ pttActiveRef.current = true;
+ start();
+ };
+
+ const handleKeyUp = (e: KeyboardEvent): void => {
+ if (!pttActiveRef.current) {
+ return;
+ }
+ // End on the *first* released key in the combo. macOS browsers
+ // frequently swallow keyup of regular keys (incl. Space) while
+ // Cmd is held, so we can't rely on Space-up alone — releasing
+ // Cmd/Ctrl/Shift must also stop the session.
+ const isComboKey =
+ e.code === 'Space' ||
+ e.key === ' ' ||
+ e.key === 'Meta' ||
+ e.key === 'Control' ||
+ e.key === 'Shift';
+ if (!isComboKey) {
+ return;
+ }
+ pttActiveRef.current = false;
+ e.preventDefault();
+ void handleStopAndSend();
+ };
+
+ window.addEventListener('keydown', handleKeyDown);
+ window.addEventListener('keyup', handleKeyUp);
+ return (): void => {
+ window.removeEventListener('keydown', handleKeyDown);
+ window.removeEventListener('keyup', handleKeyUp);
+ };
+ }, [
+ isSupported,
+ micPermission,
+ disabled,
+ isStreaming,
+ start,
+ handleStopAndSend,
+ ]);
+
+ // Each list hook fetches only when its picker tab is actively shown,
+ // AND treats already-cached data as never stale (`staleTime: Infinity`)
+ // so an open with a populated cache doesn't trigger a background
+ // refetch. Net effect: assistant-driven fetches happen exactly once
+ // per resource list per session, on the first cache miss. Gating on
+ // `isContextPickerOpen` (not just `activeContextCategory`) is important
+ // — the latter defaults to 'Dashboards' on every mount, so without the
+ // picker-open check the dashboards list refetches on every new
+ // conversation.
+ const {
+ data: dashboardsResponse,
+ isLoading: isDashboardsLoading,
+ isError: isDashboardsError,
+ } = useGetAllDashboard({
+ enabled: isContextPickerOpen && activeContextCategory === 'Dashboards',
+ staleTime: Infinity,
+ });
+
+ const {
+ data: alertsResponse,
+ isLoading: isAlertsLoading,
+ isError: isAlertsError,
+ } = useListRules({
+ query: {
+ enabled: isContextPickerOpen && activeContextCategory === 'Alerts',
+ staleTime: Infinity,
+ },
+ });
+
+ const {
+ data: servicesResponse,
+ isLoading: isServicesLoading,
+ isFetching: isServicesFetching,
+ isError: isServicesError,
+ } = useQueryService({
+ minTime: servicesTimeRange.startTime * 1e6,
+ maxTime: servicesTimeRange.endTime * 1e6,
+ selectedTime,
+ selectedTags: [],
+ options: {
+ enabled: isContextPickerOpen && activeContextCategory === 'Services',
+ staleTime: Infinity,
+ },
+ });
+
+ /**
+ * Resolves an auto-context to a human label: dashboard title, alert name,
+ * service name (the service `resourceId` IS the name), or a generic page
+ * label as fallback while the lookup data is still loading.
+ *
+ * Reads passively from the React Query cache via `getQueryData` —
+ * never triggers a fetch. If the cache is empty (e.g. assistant opened
+ * on a page that hasn't loaded the resource list yet), the chip falls
+ * back to a generic label and resolves once the cache fills via the
+ * picker or another page.
+ */
+ const resolveAutoContextName = useCallback(
+ (ctx: MessageContext): string => {
+ if (ctx.type === 'service' && ctx.resourceId) {
+ return ctx.resourceId;
+ }
+ if (ctx.type === 'dashboard' && ctx.resourceId) {
+ const cached = queryClient.getQueryData<SuccessResponseV2<Dashboard[]>>(
+ REACT_QUERY_KEY.GET_ALL_DASHBOARDS,
+ );
+ const dash = cached?.data?.find((d) => d.id === ctx.resourceId);
+ if (dash?.data.title) {
+ return dash.data.title;
+ }
+ }
+ if (ctx.type === 'alert' && ctx.resourceId) {
+ const cached = queryClient.getQueryData<ListRules200>(
+ getListRulesQueryKey(),
+ );
+ const rule = cached?.data?.find((r) => r.id === ctx.resourceId);
+ if (rule?.alert) {
+ return rule.alert;
+ }
+ }
+ const page = (
+ ctx.metadata as { page?: string; traceId?: string } | null | undefined
+ )?.page;
+ if (page === 'trace_detail') {
+ const traceId = (ctx.metadata as { traceId?: string } | null | undefined)
+ ?.traceId;
+ if (traceId) {
+ return `${traceId.slice(0, 8)}…`;
+ }
+ }
+ return autoContextLabel(ctx);
+ },
+ [queryClient],
+ );
+
+ const contextEntitiesByCategory: Record<ContextCategory, ContextEntityItem[]> =
+ {
+ Dashboards:
+ dashboardsResponse?.data?.map((dashboard) => ({
+ id: dashboard.id,
+ value: dashboard.data.title ?? 'Untitled',
+ })) ?? [],
+ Alerts:
+ alertsResponse?.data
+ ?.filter((alertRule) => Boolean(alertRule.alert))
+ .map((alertRule) => ({
+ id: alertRule.id,
+ value: alertRule.alert,
+ })) ?? [],
+ Services:
+ servicesResponse
+ ?.filter((serviceItem) => Boolean(serviceItem.serviceName))
+ .map((serviceItem, index) => ({
+ id: serviceItem.serviceName || `service-${index}`,
+ value: serviceItem.serviceName,
+ })) ?? [],
+ };
+
+ const contextCategoryStateByCategory: Record<
+ ContextCategory,
+ { isLoading: boolean; isError: boolean }
+ > = {
+ Dashboards: {
+ isLoading: isDashboardsLoading,
+ isError: isDashboardsError,
+ },
+ Alerts: {
+ isLoading: isAlertsLoading,
+ isError: isAlertsError,
+ },
+ Services: {
+ isLoading: isServicesLoading || isServicesFetching,
+ isError: isServicesError,
+ },
+ };
+
+ // Type-ahead filter against the `@<query>` typed in the textarea. When
+ // the picker was opened from the "Add Context" button there's no
+ // mention query, so fall back to the in-popover search input.
+ const mentionQuery = mentionRange
+ ? text.slice(mentionRange.start + 1, mentionRange.end).toLowerCase()
+ : '';
+ const activeQuery = mentionQuery || pickerSearchQuery.trim().toLowerCase();
+ const filteredContextOptions = activeQuery
+ ? contextEntitiesByCategory[activeContextCategory].filter((entity) =>
+ entity.value.toLowerCase().includes(activeQuery),
+ )
+ : contextEntitiesByCategory[activeContextCategory];
+ const { isLoading: isActiveContextLoading, isError: isActiveContextError } =
+ contextCategoryStateByCategory[activeContextCategory];
+ const currentLength = text.length;
+ const showTextWarning = currentLength >= WARNING_THRESHOLD;
+
+ return (
+ <div className={styles.input} ref={inputRootRef}>
+ {pendingFiles.length > 0 && (
+ <div className={styles.attachments}>
+ {pendingFiles.map((f) => (
+ <div key={f.uid} className={styles.attachmentChip}>
+ <span className={styles.attachmentName}>{f.name}</span>
+ <Button
+ variant="ghost"
+ size="icon"
+ className={styles.attachmentRemove}
+ onClick={(): void => removeFile(f.uid)}
+ aria-label={`Remove ${f.name}`}
+ >
+ <X size={11} />
+ </Button>
+ </div>
+ ))}
+ </div>
+ )}
+
+ {(selectedContexts.length > 0 ||
+ (autoContexts && autoContexts.length > 0)) && (
+ <div className={styles.contextTags}>
+ {autoContexts?.map((ctx) => {
+ const key = autoContextKey(ctx);
+ const label = resolveAutoContextName(ctx);
+ const category = autoContextCategory(ctx);
+ return (
+ <div key={key} className={cx(styles.contextTag, styles.auto)}>
+ <div className={styles.contextTagContent}>
+ <Badge
+ color="secondary"
+ variant="outline"
+ className={styles.contextTagCategory}
+ >
+ {category}
+ </Badge>
+ <span className={styles.contextTagLabel}>{label}</span>
+ </div>
+ {onDismissAutoContext && (
+ <Button
+ variant="link"
+ size="icon"
+ color="secondary"
+ className={styles.contextTagRemove}
+ onClick={(): void => onDismissAutoContext(key)}
+ aria-label={`Remove ${category}: ${label} context`}
+ prefix={<X size={10} />}
+ ></Button>
+ )}
+ </div>
+ );
+ })}
+ {selectedContexts.map((contextItem) => (
+ <div
+ key={`${contextItem.category}:${contextItem.entityId}`}
+ className={styles.contextTag}
+ >
+ <div className={styles.contextTagContent}>
+ <Badge
+ color="primary"
+ variant="outline"
+ className={styles.contextTagCategory}
+ >
+ {contextItem.category}
+ </Badge>
+ <span className={styles.contextTagLabel}>{contextItem.value}</span>
+ </div>
+ <Button
+ variant="link"
+ size="icon"
+ color="secondary"
+ className={styles.contextTagRemove}
+ onClick={(): void =>
+ removeContext(contextItem.category, contextItem.entityId)
+ }
+ aria-label={`Remove ${contextItem.category}: ${contextItem.value} context`}
+ prefix={<X size={10} />}
+ ></Button>
+ </div>
+ ))}
+ </div>
+ )}
+
+ <div className={styles.composer}>
+ <textarea
+ ref={textareaRef}
+ className={styles.textarea}
+ placeholder="Ask anything… (Shift+Enter for new line)"
+ value={text}
+ onChange={(e): void => {
+ const next = capText(e.target.value);
+ setText(next);
+ // Keep committed text in sync when the user edits manually
+ committedTextRef.current = next;
+ syncContextPickerFromText(next, e.target.selectionStart ?? next.length);
+ }}
+ onKeyDown={handleKeyDown}
+ disabled={disabled}
+ maxLength={MAX_INPUT_LENGTH}
+ rows={2}
+ />
+ </div>
+ {showTextWarning && (
+ <div className={styles.charWarning} role="status">
+ <TriangleAlert size={12} />
+ <span>
+ {currentLength}/{MAX_INPUT_LENGTH} characters. Limit is {MAX_INPUT_LENGTH}
+ .
+ </span>
+ </div>
+ )}
+
+ <div className={styles.footer}>
+ <div className={styles.leftActions}>
+ <Popover
+ open={isContextPickerOpen}
+ onOpenChange={(open): void => {
+ setIsContextPickerOpen(open);
+ if (!open) {
+ setActiveContextCategory('Dashboards');
+ setPickerSearchQuery('');
+ }
+ }}
+ >
+ <PopoverTrigger asChild>
+ <Button
+ variant="solid"
+ color="secondary"
+ size="sm"
+ disabled={disabled}
+ onClick={(): void => {
+ setActiveContextCategory('Dashboards');
+ setPickerSearchQuery('');
+ }}
+ prefix={<Plus size={10} />}
+ >
+ Add Context
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent
+ className={styles.contextPopover}
+ side="top"
+ align="end"
+ sideOffset={8}
+ >
+ <div className={styles.contextPopoverContent}>
+ <div className={styles.contextPopoverCategories}>
+ {CONTEXT_CATEGORIES.map((category) => {
+ const CategoryIcon = CONTEXT_CATEGORY_ICONS[category];
+ const isActive = activeContextCategory === category;
+ return (
+ <div
+ key={category}
+ role="tab"
+ tabIndex={0}
+ aria-selected={isActive}
+ className={cx(styles.contextPopoverCategoryItem, {
+ [styles.active]: isActive,
+ })}
+ onClick={(): void => {
+ setActiveContextCategory(category);
+ setPickerSearchQuery('');
+ }}
+ onKeyDown={(e): void => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ setActiveContextCategory(category);
+ setPickerSearchQuery('');
+ }
+ }}
+ >
+ <CategoryIcon size={13} />
+ <span>{category}</span>
+ </div>
+ );
+ })}
+ </div>
+
+ <div className={styles.contextPopoverRight}>
+ <div className={styles.contextPopoverSearch}>
+ <Input
+ type="text"
+ placeholder={`Search ${activeContextCategory.toLowerCase()}…`}
+ className={styles.contextPopoverSearchInput}
+ value={pickerSearchQuery}
+ onChange={(e): void => setPickerSearchQuery(e.target.value)}
+ prefix={<Search size={12} />}
+ // Skip the picker's roving keyboard focus — typing here
+ // shouldn't move category selection.
+ onKeyDown={(e): void => {
+ e.stopPropagation();
+ }}
+ />
+ </div>
+ <div className={styles.contextPopoverEntities}>
+ {isActiveContextLoading ? (
+ <div className={styles.contextPopoverEmpty}>
+ Loading {activeContextCategory.toLowerCase()}...
+ </div>
+ ) : isActiveContextError ? (
+ <div className={styles.contextPopoverEmpty}>
+ Failed to load {activeContextCategory.toLowerCase()}.
+ </div>
+ ) : filteredContextOptions.length === 0 ? (
+ <div className={styles.contextPopoverEmpty}>
+ No matching entities
+ </div>
+ ) : (
+ filteredContextOptions.map((option) => {
+ const isSelected = selectedContexts.some(
+ (item) =>
+ item.category === activeContextCategory &&
+ item.entityId === option.id,
+ );
+
+ return (
+ <div
+ key={option.id}
+ className={cx(styles.contextPopoverEntityItem, {
+ [styles.selected]: isSelected,
+ })}
+ onClick={(): void =>
+ toggleContextSelection(
+ activeContextCategory,
+ option.id,
+ option.value,
+ )
+ }
+ >
+ <span className={styles.contextPopoverEntityItemText}>
+ {option.value}
+ </span>
+ </div>
+ );
+ })
+ )}
+ </div>
+ </div>
+ </div>
+ </PopoverContent>
+ </Popover>
+ </div>
+
+ <div className={styles.rightActions}>
+ {showMic &&
+ (isListening ? (
+ <div className={styles.micRecording}>
+ <div
+ className={cx(styles.micDiscard, styles.secondary)}
+ onClick={handleDiscard}
+ aria-label="Discard recording"
+ >
+ <X size={12} />
+ </div>
+ <span className={styles.micWaves} aria-hidden="true">
+ <span />
+ <span />
+ <span />
+ <span />
+ <span />
+ <span />
+ <span />
+ <span />
+ </span>
+ <div
+ className={cx(styles.micStop, styles.destructive)}
+ onClick={handleStopAndSend}
+ aria-label="Stop and send"
+ >
+ <Square size={9} fill="currentColor" strokeWidth={0} />
+ </div>
+ </div>
+ ) : (
+ <Tooltip title="Voice input">
+ <Button
+ variant="ghost"
+ size="icon"
+ onClick={start}
+ disabled={disabled}
+ aria-label="Start voice input"
+ className={styles.micBtn}
+ >
+ <Mic size={14} />
+ </Button>
+ </Tooltip>
+ ))}
+
+ {isStreaming && onCancel ? (
+ <Tooltip title="Stop generating">
+ <Button
+ variant="solid"
+ size="icon"
+ color="destructive"
+ onClick={onCancel}
+ aria-label="Stop generating"
+ >
+ <Square size={10} fill="currentColor" strokeWidth={0} />
+ </Button>
+ </Tooltip>
+ ) : (
+ <Button
+ variant="solid"
+ size="icon"
+ color="primary"
+ onClick={isListening ? handleStopAndSend : handleSend}
+ disabled={disabled || (!text.trim() && pendingFiles.length === 0)}
+ aria-label="Send message"
+ >
+ <Send size={14} />
+ </Button>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/frontend/src/container/AIAssistant/components/ChatInput/index.ts b/frontend/src/container/AIAssistant/components/ChatInput/index.ts
new file mode 100644
index 0000000000..e44855ff58
--- /dev/null
+++ b/frontend/src/container/AIAssistant/components/ChatInput/index.ts
@@ -0,0 +1,2 @@
+export * from './ChatInput';
+export { default } from './ChatInput';
diff --git a/frontend/src/container/AIAssistant/components/ClarificationForm/ClarificationForm.module.scss b/frontend/src/container/AIAssistant/components/ClarificationForm/ClarificationForm.module.scss
new file mode 100644
index 0000000000..060415007e
--- /dev/null
+++ b/frontend/src/container/AIAssistant/components/ClarificationForm/ClarificationForm.module.scss
@@ -0,0 +1,133 @@
+.clarification {
+ border: 1px solid var(--l2-border);
+ border-radius: var(--radius-2);
+ padding: 10px 12px;
+ background: var(--l2-background);
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+ width: 100%;
+
+ &.submitted {
+ border-color: var(--l2-border);
+ background: transparent;
+ flex-direction: row;
+ align-items: center;
+ gap: 6px;
+ padding: 6px 10px;
+ }
+}
+
+.header {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+}
+
+.headerIcon {
+ flex-shrink: 0;
+ color: var(--accent-primary);
+}
+
+.headerLabel {
+ font-size: 12px;
+ font-weight: 600;
+ color: var(--l1-foreground);
+}
+
+.message {
+ font-size: 13px;
+ color: var(--l1-foreground);
+ margin: 0;
+ line-height: 1.5;
+}
+
+.icon {
+ color: var(--accent-forest);
+ flex-shrink: 0;
+}
+
+.statusText {
+ font-size: 13px;
+ color: var(--l2-foreground);
+}
+
+.fields {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+}
+
+.field {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+}
+
+.label {
+ font-size: 12px;
+ font-weight: 500;
+ color: var(--l2-foreground);
+}
+
+.required {
+ color: var(--accent-cherry);
+ margin-left: 2px;
+}
+
+.input,
+.select {
+ background: var(--l2-background);
+ border: 1px solid var(--l2-border);
+ border-radius: var(--radius-2);
+ padding: 5px 8px;
+ font-size: 13px;
+ color: var(--l1-foreground);
+ outline: none;
+ transition: border-color 0.12s;
+
+ &:focus {
+ border-color: var(--accent-primary);
+ }
+}
+
+.select {
+ cursor: pointer;
+}
+
+// Constrain the Radix-based SelectContent popover so it never grows wider
+// than the trigger button. `--radix-select-trigger-width` is set by Radix
+// at the popper layer when `position: 'popper'` (the default).
+.selectContent {
+ width: var(--radix-select-trigger-width);
+ min-width: var(--radix-select-trigger-width);
+}
+
+.radioGroup,
+.checkboxGroup {
+ display: flex;
+ flex-direction: column;
+ gap: 5px;
+}
+
+.radioLabel,
+.checkboxLabel {
+ display: flex;
+ align-items: center;
+ gap: 7px;
+ font-size: 13px;
+ color: var(--l1-foreground);
+ cursor: pointer;
+}
+
+.radio,
+.checkbox {
+ accent-color: var(--accent-primary);
+ cursor: pointer;
+}
+
+.actions {
+ display: flex;
+ gap: 6px;
+ margin-top: 16px;
+}
diff --git a/frontend/src/container/AIAssistant/components/ClarificationForm/ClarificationForm.tsx b/frontend/src/container/AIAssistant/components/ClarificationForm/ClarificationForm.tsx
new file mode 100644
index 0000000000..e1d8e94add
--- /dev/null
+++ b/frontend/src/container/AIAssistant/components/ClarificationForm/ClarificationForm.tsx
@@ -0,0 +1,352 @@
+import { useState } from 'react';
+import cx from 'classnames';
+import { Button } from '@signozhq/ui/button';
+import { Checkbox } from '@signozhq/ui/checkbox';
+import { Input } from '@signozhq/ui/input';
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+} from '@signozhq/ui/select';
+import { ClarificationFieldTypeDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
+import type {
+ ClarificationEventDTO,
+ ClarificationFieldEventDTO,
+} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
+import { CircleHelp, Send, X } from '@signozhq/icons';
+
+import { useAIAssistantStore } from '../../store/useAIAssistantStore';
+
+import styles from './ClarificationForm.module.scss';
+
+/** Sentinel emitted by the select dropdown when the user picks the custom slot. */
+const CUSTOM_OPTION_SENTINEL = '__signoz_ai_custom__';
+/** User-facing label for the synthetic "type your own answer" option. */
+const CUSTOM_OPTION_LABEL = 'Other (type your own)';
+
+interface ClarificationFormProps {
+ conversationId: string;
+ clarification: ClarificationEventDTO;
+}
+
+/**
+ * Rendered when the agent emits a `clarification` SSE event.
+ * Dynamically renders form fields based on the `fields` array and
+ * submits answers to resume the agent on a new execution.
+ */
+export default function ClarificationForm({
+ conversationId,
+ clarification,
+}: ClarificationFormProps): JSX.Element {
+ const submitClarification = useAIAssistantStore((s) => s.submitClarification);
+ const cancelStream = useAIAssistantStore((s) => s.cancelStream);
+ const isStreaming = useAIAssistantStore(
+ (s) => s.streams[conversationId]?.isStreaming ?? false,
+ );
+
+ const fields = clarification.fields ?? [];
+ const initialAnswers = Object.fromEntries(
+ fields.map((f) => [f.id, initialAnswerFor(f)]),
+ );
+ const [answers, setAnswers] =
+ useState<Record<string, unknown>>(initialAnswers);
+ const [submitted, setSubmitted] = useState(false);
+ const [cancelled, setCancelled] = useState(false);
+
+ const setField = (id: string, value: unknown): void => {
+ setAnswers((prev) => ({ ...prev, [id]: value }));
+ };
+
+ const handleSubmit = async (): Promise<void> => {
+ setSubmitted(true);
+ await submitClarification(
+ conversationId,
+ clarification.clarificationId,
+ answers,
+ );
+ };
+
+ const handleCancel = (): void => {
+ setCancelled(true);
+ cancelStream(conversationId);
+ };
+
+ if (submitted) {
+ return (
+ <div className={cx(styles.clarification, styles.submitted)}>
+ <Send size={13} className={styles.icon} />
+ <span className={styles.statusText}>Answers submitted — resuming…</span>
+ </div>
+ );
+ }
+
+ if (cancelled) {
+ return (
+ <div className={cx(styles.clarification, styles.submitted)}>
+ <X size={13} className={styles.icon} />
+ <span className={styles.statusText}>Request cancelled.</span>
+ </div>
+ );
+ }
+
+ return (
+ <div className={styles.clarification}>
+ <div className={styles.header}>
+ <CircleHelp size={13} className={styles.headerIcon} />
+ <span className={styles.headerLabel}>A few details needed</span>
+ </div>
+
+ <p className={styles.message}>{clarification.message}</p>
+
+ <div className={styles.fields}>
+ {fields.map((field) => (
+ <FieldInput
+ key={field.id}
+ field={field}
+ value={answers[field.id]}
+ onChange={(val): void => setField(field.id, val)}
+ />
+ ))}
+ </div>
+
+ <div className={styles.actions}>
+ <Button
+ variant="solid"
+ color="primary"
+ onClick={handleSubmit}
+ disabled={isStreaming}
+ prefix={<Send />}
+ >
+ Submit
+ </Button>
+ <Button
+ variant="outlined"
+ color="secondary"
+ onClick={handleCancel}
+ disabled={isStreaming}
+ prefix={<X />}
+ >
+ Cancel request
+ </Button>
+ </div>
+ </div>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Field renderer — covers every variant of ClarificationFieldTypeDTO:
+// text, number, select, multi_select, boolean.
+// ---------------------------------------------------------------------------
+
+/**
+ * Per-type seed value. The DTO's `default` is `string | string[] | null`,
+ * which doesn't fit boolean fields cleanly — we coerce 'true'/'false' strings
+ * for them, fall back to `[]` for multi_select, and the raw string otherwise.
+ */
+function initialAnswerFor(f: ClarificationFieldEventDTO): unknown {
+ const raw = f.default;
+ if (f.type === ClarificationFieldTypeDTO.boolean) {
+ // `default` is typed string | string[] | null; backend sends
+ // 'true'/'false' as strings for boolean fields.
+ return raw === 'true';
+ }
+ if (f.type === ClarificationFieldTypeDTO.multi_select) {
+ return Array.isArray(raw) ? raw : [];
+ }
+ return raw ?? '';
+}
+
+interface FieldInputProps {
+ field: ClarificationFieldEventDTO;
+ value: unknown;
+ onChange: (value: unknown) => void;
+}
+
+function FieldInput({ field, value, onChange }: FieldInputProps): JSX.Element {
+ const { id, type, label, required, options, allowCustom } = field;
+
+ // Local UI state for the synthetic "custom" option on select /
+ // multi_select fields with `allowCustom`. The free-text input only renders
+ // when this is true; the typed value is what's actually sent up via
+ // `onChange` (never the sentinel / "Other" label).
+ const [isCustom, setIsCustom] = useState(false);
+ const [customValue, setCustomValue] = useState('');
+
+ // Render the select if the field has options OR if the server marked it
+ // `allowCustom` (in which case the dropdown still appears with just the
+ // "Other (type your own)" entry — a plain `options: null` would
+ // otherwise fall through to the bare text-input renderer).
+ if (type === ClarificationFieldTypeDTO.select && (options || allowCustom)) {
+ const handleSelectChange = (next: string | string[]): void => {
+ // `multiple` is off → callback receives a single string. The wider
+ // `string | string[]` typing comes from the shared Select root.
+ const picked = Array.isArray(next) ? (next[0] ?? '') : next;
+ if (picked === CUSTOM_OPTION_SENTINEL) {
+ setIsCustom(true);
+ onChange(customValue);
+ } else {
+ setIsCustom(false);
+ onChange(picked);
+ }
+ };
+
+ return (
+ <div className={styles.field}>
+ <label className={styles.label} htmlFor={id}>
+ {label}
+ {required && <span className={styles.required}>*</span>}
+ </label>
+ <Select
+ value={isCustom ? CUSTOM_OPTION_SENTINEL : String(value ?? '')}
+ onChange={handleSelectChange}
+ >
+ <SelectTrigger id={id} placeholder="Select…" />
+ {/* Pin the dropdown width to the trigger via Radix's
+ `--radix-select-trigger-width`; otherwise the popover
+ sizes to its widest item and looks misaligned. */}
+ <SelectContent className={styles.selectContent}>
+ {options?.map((opt) => (
+ <SelectItem key={opt} value={opt}>
+ {opt}
+ </SelectItem>
+ ))}
+ {allowCustom && (
+ <SelectItem value={CUSTOM_OPTION_SENTINEL}>
+ {CUSTOM_OPTION_LABEL}
+ </SelectItem>
+ )}
+ </SelectContent>
+ </Select>
+ {isCustom && (
+ <Input
+ type="text"
+ className={styles.input}
+ placeholder="Enter a custom value"
+ value={customValue}
+ onChange={(e): void => {
+ setCustomValue(e.target.value);
+ onChange(e.target.value);
+ }}
+ />
+ )}
+ </div>
+ );
+ }
+
+ // Boolean — single yes/no checkbox. The label sits inside the checkbox
+ // so the click target covers both, matching how multi_select rows render.
+ if (type === ClarificationFieldTypeDTO.boolean) {
+ const checked = value === true;
+ return (
+ <div className={styles.field}>
+ <Checkbox
+ className={styles.checkboxLabel}
+ value={checked}
+ onChange={(): void => onChange(!checked)}
+ >
+ {label}
+ {required && <span className={styles.required}>*</span>}
+ </Checkbox>
+ </div>
+ );
+ }
+
+ // Same fallback logic as the select branch — render the checkbox group
+ // when there are options OR when the field is `allowCustom` only.
+ if (
+ type === ClarificationFieldTypeDTO.multi_select &&
+ (options || allowCustom)
+ ) {
+ const selected = Array.isArray(value) ? (value as string[]) : [];
+ // Anything in the value array that isn't one of the predefined options
+ // is treated as a custom entry — we keep at most one custom entry,
+ // driven by the local `customValue` + `isCustom` state below.
+ const regularSelected = selected.filter((v) => options?.includes(v));
+
+ const toggleRegular = (opt: string): void => {
+ const nextRegular = regularSelected.includes(opt)
+ ? regularSelected.filter((v) => v !== opt)
+ : [...regularSelected, opt];
+ onChange(
+ isCustom && customValue ? [...nextRegular, customValue] : nextRegular,
+ );
+ };
+
+ const toggleCustom = (): void => {
+ if (isCustom) {
+ setIsCustom(false);
+ onChange(regularSelected);
+ } else {
+ setIsCustom(true);
+ onChange(customValue ? [...regularSelected, customValue] : regularSelected);
+ }
+ };
+
+ const updateCustomValue = (next: string): void => {
+ setCustomValue(next);
+ if (isCustom) {
+ onChange(next ? [...regularSelected, next] : regularSelected);
+ }
+ };
+
+ return (
+ <div className={styles.field}>
+ <span className={styles.label}>
+ {label}
+ {required && <span className={styles.required}>*</span>}
+ </span>
+ <div className={styles.checkboxGroup}>
+ {options?.map((opt) => (
+ <Checkbox
+ key={opt}
+ className={styles.checkboxLabel}
+ value={regularSelected.includes(opt)}
+ onChange={(): void => toggleRegular(opt)}
+ >
+ {opt}
+ </Checkbox>
+ ))}
+ {allowCustom && (
+ <Checkbox
+ className={styles.checkboxLabel}
+ value={isCustom}
+ onChange={toggleCustom}
+ >
+ {CUSTOM_OPTION_LABEL}
+ </Checkbox>
+ )}
+ </div>
+ {isCustom && (
+ <Input
+ type="text"
+ className={styles.input}
+ placeholder="Enter a custom value"
+ value={customValue}
+ onChange={(e): void => updateCustomValue(e.target.value)}
+ />
+ )}
+ </div>
+ );
+ }
+
+ // text / number (default)
+ return (
+ <div className={styles.field}>
+ <label className={styles.label} htmlFor={id}>
+ {label}
+ {required && <span className={styles.required}>*</span>}
+ </label>
+ <Input
+ id={id}
+ type={type === 'number' ? 'number' : 'text'}
+ className={styles.input}
+ value={String(value ?? '')}
+ onChange={(e): void =>
+ onChange(type === 'number' ? Number(e.target.value) : e.target.value)
+ }
+ placeholder={label}
+ />
+ </div>
+ );
+}
diff --git a/frontend/src/container/AIAssistant/components/ClarificationForm/index.ts b/frontend/src/container/AIAssistant/components/ClarificationForm/index.ts
new file mode 100644
index 0000000000..05dabd8349
--- /dev/null
+++ b/frontend/src/container/AIAssistant/components/ClarificationForm/index.ts
@@ -0,0 +1,2 @@
+export * from './ClarificationForm';
+export { default } from './ClarificationForm';
diff --git a/frontend/src/container/AIAssistant/components/ConversationItem/ConversationItem.module.scss b/frontend/src/container/AIAssistant/components/ConversationItem/ConversationItem.module.scss
new file mode 100644
index 0000000000..4d02864911
--- /dev/null
+++ b/frontend/src/container/AIAssistant/components/ConversationItem/ConversationItem.module.scss
@@ -0,0 +1,145 @@
+.item {
+ display: flex;
+ align-items: center;
+ gap: 7px;
+ padding: 6px 8px;
+ border-radius: var(--radius-2);
+ cursor: pointer;
+ min-width: 0;
+ position: relative;
+ // Driven below: hover and active reveal the action buttons.
+ --actions-opacity: 0;
+
+ &:hover {
+ background: var(--l2-background);
+ --actions-opacity: 1;
+ }
+
+ &.active {
+ background: var(--l2-background);
+ --actions-opacity: 1;
+
+ .title {
+ color: var(--l1-foreground);
+ font-weight: 500;
+ }
+ }
+
+ &.archived {
+ opacity: 0.92;
+
+ .title {
+ color: var(--l3-foreground);
+ }
+ }
+}
+
+.icon {
+ flex-shrink: 0;
+ color: var(--l3-foreground);
+}
+
+.body {
+ flex: 1;
+ min-width: 0;
+ display: flex;
+ flex-direction: column;
+ gap: 1px;
+}
+
+.title {
+ font-size: 12px;
+ color: var(--l2-foreground);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ line-height: 1.4;
+}
+
+.time {
+ font-size: 10px;
+ color: var(--l3-foreground);
+ opacity: 0.7;
+}
+
+.input {
+ width: 100%;
+ background: transparent;
+ border: none;
+ border-bottom: 1px solid var(--accent-primary);
+ outline: none;
+ color: var(--l1-foreground);
+ font-size: 12px;
+ font-family: inherit;
+ padding: 1px 0;
+}
+
+.actions {
+ display: flex;
+ align-items: center;
+ gap: 1px;
+ flex-shrink: 0;
+ opacity: var(--actions-opacity, 0);
+ transition: opacity 0.12s;
+ // Float over the right edge of the item so the title can keep using
+ // the full width while the buttons are hidden — no layout shift +
+ // no premature truncation. The `background` matches the hover/active
+ // state so the buttons visually mask any title text underneath.
+ position: absolute;
+ top: 50%;
+ right: 4px;
+ transform: translateY(-50%);
+ background: var(--l2-background);
+ padding: 1px 2px;
+ border-radius: var(--radius-2);
+ pointer-events: var(--actions-pointer, none);
+}
+
+.item:hover,
+.item.active {
+ --actions-pointer: auto;
+}
+
+.btn {
+ padding: 2px !important;
+ height: auto !important;
+ min-height: 0 !important;
+
+ &.danger:hover {
+ color: var(--accent-cherry) !important;
+ }
+}
+
+// Compact menu — narrower than the design-system default so the
+// content (Rename / Copy link / Archive) doesn't dwarf the row.
+.menu {
+ min-width: 160px !important;
+ width: 160px !important;
+}
+
+// Shared sizing for every dropdown item so the menu reads compact —
+// matches the row's own 12px label scale.
+.menuItem {
+ font-size: 12px !important;
+ cursor: pointer !important;
+}
+
+// Amber treatment for the destructive-but-recoverable Archive action —
+// less alarming than red since the conversation can be restored later.
+// Targets both the label text and the leading icon (icons inherit color
+// via `currentColor`).
+.archiveItem {
+ color: var(--accent-amber) !important;
+
+ svg {
+ color: inherit !important;
+ }
+}
+
+.restoreItem {
+ color: var(--primary) !important;
+
+ svg {
+ color: inherit !important;
+ }
+}
diff --git a/frontend/src/container/AIAssistant/components/ConversationItem/ConversationItem.tsx b/frontend/src/container/AIAssistant/components/ConversationItem/ConversationItem.tsx
new file mode 100644
index 0000000000..49dc29b2b5
--- /dev/null
+++ b/frontend/src/container/AIAssistant/components/ConversationItem/ConversationItem.tsx
@@ -0,0 +1,226 @@
+import { KeyboardEvent, useCallback, useEffect, useRef, useState } from 'react';
+import { useCopyToClipboard } from 'react-use';
+import cx from 'classnames';
+import ROUTES from 'constants/routes';
+import { getAbsoluteUrl } from 'utils/basePath';
+import { Button } from '@signozhq/ui/button';
+import { Input } from '@signozhq/ui/input';
+import { toast } from '@signozhq/ui/sonner';
+import { DropdownMenuSimple } from '@signozhq/ui/dropdown-menu';
+
+import {
+ Archive,
+ ArchiveRestore,
+ EllipsisVertical,
+ Link,
+ MessageSquare,
+ Pencil,
+} from '@signozhq/icons';
+
+import { Conversation } from '../../types';
+
+import styles from './ConversationItem.module.scss';
+
+interface ConversationItemProps {
+ conversation: Conversation;
+ isActive: boolean;
+ onSelect: (id: string) => void;
+ onRename: (id: string, title: string) => void;
+ onArchive: (id: string) => void;
+ onRestore: (id: string) => void;
+}
+
+function formatRelativeTime(ts: number): string {
+ if (!Number.isFinite(ts)) {
+ return '';
+ }
+ const diff = Date.now() - ts;
+ const mins = Math.floor(diff / 60_000);
+ if (mins < 1) {
+ return 'just now';
+ }
+ if (mins < 60) {
+ return `${mins}m ago`;
+ }
+ const hrs = Math.floor(mins / 60);
+ if (hrs < 24) {
+ return `${hrs}h ago`;
+ }
+ const days = Math.floor(hrs / 24);
+ if (days < 7) {
+ return `${days}d ago`;
+ }
+ return new Date(ts).toLocaleDateString(undefined, {
+ month: 'short',
+ day: 'numeric',
+ });
+}
+
+export default function ConversationItem({
+ conversation,
+ isActive,
+ onSelect,
+ onRename,
+ onArchive,
+ onRestore,
+}: ConversationItemProps): JSX.Element {
+ const [isEditing, setIsEditing] = useState(false);
+ const [editValue, setEditValue] = useState('');
+ const inputRef = useRef<HTMLInputElement>(null);
+ const [, copyToClipboard] = useCopyToClipboard();
+
+ const isArchived = Boolean(conversation.archived);
+ const displayTitle = conversation.title ?? 'New conversation';
+ const ts = conversation.updatedAt ?? conversation.createdAt;
+
+ const handleCopyLink = useCallback((): void => {
+ // Prefer the server-side `threadId` so the link resolves for anyone
+ // with access to this conversation. Fall back to the local id for
+ // drafts that haven't synced yet — useful for the current session
+ // even if the URL won't reload elsewhere.
+ const id = conversation.threadId ?? conversation.id;
+ const path = ROUTES.AI_ASSISTANT.replace(':conversationId', id);
+ copyToClipboard(getAbsoluteUrl(path));
+ toast.success('Conversation link copied to clipboard');
+ }, [conversation.threadId, conversation.id, copyToClipboard]);
+
+ const startEditing = useCallback((): void => {
+ setEditValue(conversation.title ?? '');
+ setIsEditing(true);
+ }, [conversation.title]);
+
+ useEffect(() => {
+ if (isEditing) {
+ inputRef.current?.focus();
+ inputRef.current?.select();
+ }
+ }, [isEditing]);
+
+ const commitEdit = useCallback(() => {
+ onRename(conversation.id, editValue);
+ setIsEditing(false);
+ }, [conversation.id, editValue, onRename]);
+
+ const handleKeyDown = useCallback(
+ (e: KeyboardEvent<HTMLInputElement>) => {
+ if (e.key === 'Enter') {
+ commitEdit();
+ }
+ if (e.key === 'Escape') {
+ setIsEditing(false);
+ }
+ },
+ [commitEdit],
+ );
+
+ const itemClass = cx(styles.item, {
+ [styles.active]: isActive,
+ [styles.archived]: isArchived,
+ });
+
+ // Dropdown items mirror the previous inline buttons but live in a single
+ // trigger so the row stays compact. Archive/Restore swap based on the
+ // archived state — same handler wiring as before.
+ const baseItems = [
+ {
+ key: 'rename',
+ label: 'Rename',
+ icon: <Pencil size={12} />,
+ className: styles.menuItem,
+ onClick: (): void => startEditing(),
+ },
+ {
+ key: 'copy-link',
+ label: 'Copy link',
+ icon: <Link size={12} />,
+ className: styles.menuItem,
+ onClick: handleCopyLink,
+ },
+ { type: 'divider' as const, key: 'divider' },
+ ];
+ const menuItems = isArchived
+ ? [
+ ...baseItems,
+ {
+ key: 'restore',
+ label: 'Restore',
+ icon: <ArchiveRestore size={12} />,
+ className: cx(styles.menuItem, styles.restoreItem),
+ onClick: (): void => onRestore(conversation.id),
+ },
+ ]
+ : [
+ ...baseItems,
+ {
+ key: 'archive',
+ label: 'Archive',
+ icon: <Archive size={12} />,
+ className: cx(styles.menuItem, styles.archiveItem),
+ onClick: (): void => onArchive(conversation.id),
+ },
+ ];
+
+ return (
+ <div
+ className={itemClass}
+ onClick={(): void => onSelect(conversation.id)}
+ role="button"
+ tabIndex={0}
+ onKeyDown={(e): void => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ onSelect(conversation.id);
+ }
+ }}
+ >
+ <MessageSquare size={12} className={styles.icon} />
+
+ <div className={styles.body}>
+ {isEditing ? (
+ <Input
+ ref={inputRef}
+ className={styles.input}
+ value={editValue}
+ onChange={(e): void => setEditValue(e.target.value)}
+ onKeyDown={handleKeyDown}
+ onBlur={commitEdit}
+ onClick={(e): void => e.stopPropagation()}
+ maxLength={80}
+ />
+ ) : (
+ <>
+ <span className={styles.title} title={displayTitle}>
+ {displayTitle}
+ </span>
+ <span className={styles.time}>{formatRelativeTime(ts)}</span>
+ </>
+ )}
+ </div>
+
+ {!isEditing && (
+ <div
+ className={styles.actions}
+ // Stop the row's onSelect from firing when the user opens the
+ // menu or clicks an item — the menu lives in a portal so its
+ // own clicks don't bubble, but the trigger button does.
+ onClick={(e): void => e.stopPropagation()}
+ >
+ <DropdownMenuSimple
+ menu={{ items: menuItems }}
+ align="end"
+ sideOffset={4}
+ className={styles.menu}
+ >
+ <Button
+ variant="link"
+ size="icon"
+ color="none"
+ className={styles.btn}
+ aria-label="Conversation actions"
+ prefix={<EllipsisVertical size={12} />}
+ />
+ </DropdownMenuSimple>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/frontend/src/container/AIAssistant/components/ConversationItem/index.ts b/frontend/src/container/AIAssistant/components/ConversationItem/index.ts
new file mode 100644
index 0000000000..9768b1294c
--- /dev/null
+++ b/frontend/src/container/AIAssistant/components/ConversationItem/index.ts
@@ -0,0 +1,2 @@
+export * from './ConversationItem';
+export { default } from './ConversationItem';
diff --git a/frontend/src/container/AIAssistant/components/ConversationSkeleton/ConversationSkeleton.module.scss b/frontend/src/container/AIAssistant/components/ConversationSkeleton/ConversationSkeleton.module.scss
new file mode 100644
index 0000000000..b8ebfe02c3
--- /dev/null
+++ b/frontend/src/container/AIAssistant/components/ConversationSkeleton/ConversationSkeleton.module.scss
@@ -0,0 +1,84 @@
+.thread {
+ flex: 1;
+ overflow-y: auto;
+ display: flex;
+ flex-direction: column;
+ padding: 16px 0;
+ gap: 14px;
+}
+
+.message {
+ display: flex;
+ padding: 0 16px;
+
+ &.compact {
+ padding: 0 12px;
+ }
+}
+
+.user {
+ justify-content: flex-end;
+}
+
+.assistant {
+ justify-content: flex-start;
+}
+
+.bubble {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ // `width: 100%` (capped by per-role max-width below) forces the bubble
+ // to fill its allotted slot rather than collapsing to the longest line —
+ // otherwise the lines' percent widths cascade into a tiny bubble.
+ width: 100%;
+ border-radius: var(--radius-2);
+ padding: 12px 14px;
+
+ &.user {
+ // Narrower than the assistant bubble so the alternating chat-thread
+ // asymmetry is preserved — but wider than the previous 80% so the
+ // shimmer lines have room to read as a real-looking message.
+ max-width: 75%;
+ // Subtle primary tint so the right-side bubble reads as the user's
+ // message without committing to the full saturated brand color.
+ background: color-mix(in srgb, var(--accent-primary) 18%, transparent);
+ border-bottom-right-radius: var(--radius-2);
+ color: var(--l1-foreground);
+ }
+
+ &.assistant {
+ max-width: 95%;
+ background: var(--l2-background);
+ border-bottom-left-radius: var(--radius-2);
+ }
+}
+
+.line {
+ height: 9px;
+ border-radius: 3px;
+ position: relative;
+ overflow: hidden;
+ background: color-mix(in srgb, var(--l1-foreground) 10%, transparent);
+
+ // Shimmer sweep — same pattern used by HistorySidebar's skeleton rows.
+ &::after {
+ content: '';
+ position: absolute;
+ inset: 0;
+ transform: translateX(-100%);
+ background: linear-gradient(
+ 90deg,
+ transparent,
+ color-mix(in srgb, var(--l1-foreground) 10%, transparent),
+ transparent
+ );
+ animation: shimmer 1.15s ease-in-out infinite;
+ }
+}
+
+@keyframes shimmer {
+ 100% {
+ transform: translateX(100%);
+ }
+}
diff --git a/frontend/src/container/AIAssistant/components/ConversationSkeleton/ConversationSkeleton.tsx b/frontend/src/container/AIAssistant/components/ConversationSkeleton/ConversationSkeleton.tsx
new file mode 100644
index 0000000000..a54ec56c7a
--- /dev/null
+++ b/frontend/src/container/AIAssistant/components/ConversationSkeleton/ConversationSkeleton.tsx
@@ -0,0 +1,53 @@
+import cx from 'classnames';
+
+import { useVariant } from '../../VariantContext';
+
+import styles from './ConversationSkeleton.module.scss';
+
+/**
+ * Each entry is one bubble in the placeholder thread:
+ * role: who "sent" the bubble — drives left/right alignment + colour
+ * lines: list of widths (as % of the bubble) for the shimmer lines inside
+ *
+ * Mixed widths and varying line counts produce something that scans as a real
+ * back-and-forth conversation rather than a uniform grid.
+ */
+const ROWS: { role: 'user' | 'assistant'; lines: number[] }[] = [
+ { role: 'user', lines: [62] },
+ { role: 'assistant', lines: [85, 92, 70] },
+ { role: 'user', lines: [55, 40] },
+ { role: 'assistant', lines: [90, 78, 95, 60] },
+ { role: 'user', lines: [48] },
+ { role: 'assistant', lines: [80, 88] },
+];
+
+/** Skeleton chat thread shown while a single conversation is being loaded. */
+export default function ConversationSkeleton(): JSX.Element {
+ const variant = useVariant();
+ const isCompact = variant === 'panel';
+
+ return (
+ <div className={styles.thread} aria-busy aria-label="Loading conversation">
+ {ROWS.map((row, idx) => (
+ <div
+ // eslint-disable-next-line react/no-array-index-key
+ key={idx}
+ className={cx(styles.message, styles[row.role], {
+ [styles.compact]: isCompact,
+ })}
+ >
+ <div className={cx(styles.bubble, styles[row.role])}>
+ {row.lines.map((width, lineIdx) => (
+ <div
+ // eslint-disable-next-line react/no-array-index-key
+ key={lineIdx}
+ className={styles.line}
+ style={{ width: `${width}%` }}
+ />
+ ))}
+ </div>
+ </div>
+ ))}
+ </div>
+ );
+}
diff --git a/frontend/src/container/AIAssistant/components/ConversationSkeleton/index.ts b/frontend/src/container/AIAssistant/components/ConversationSkeleton/index.ts
new file mode 100644
index 0000000000..a6a41d1d2e
--- /dev/null
+++ b/frontend/src/container/AIAssistant/components/ConversationSkeleton/index.ts
@@ -0,0 +1,2 @@
+export * from './ConversationSkeleton';
+export { default } from './ConversationSkeleton';
diff --git a/frontend/src/container/AIAssistant/components/ConversationsList/ConversationsList.module.scss b/frontend/src/container/AIAssistant/components/ConversationsList/ConversationsList.module.scss
new file mode 100644
index 0000000000..135f3863bf
--- /dev/null
+++ b/frontend/src/container/AIAssistant/components/ConversationsList/ConversationsList.module.scss
@@ -0,0 +1,136 @@
+@use '../../_scrollbar' as *;
+
+.conversationsList {
+ display: flex;
+ flex-direction: column;
+ height: 100%;
+ overflow: hidden;
+
+ // Page variant: fixed-width left column.
+ &.variantPage {
+ width: 280px;
+ flex-shrink: 0;
+ border-right: 1px solid var(--l1-border);
+ }
+
+ // Panel variant: full-width overlay (replaces conversation view).
+ &.variantPanel {
+ width: 100%;
+ flex: 1;
+ }
+}
+
+.header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 8px 12px;
+ flex-shrink: 0;
+}
+
+.heading {
+ font-size: 11px;
+ font-weight: 600;
+ text-transform: uppercase;
+ letter-spacing: 0.06em;
+ color: var(--l2-foreground);
+ // Collapse the line-box to the glyph height so the loading dots
+ // (centered against the line-box) line up with the cap-height of the
+ // uppercase text instead of sitting visually low.
+ line-height: 24px;
+}
+
+.searchBar {
+ padding: 0px 8px 12px;
+ flex-shrink: 0;
+}
+
+.search {
+ width: 100%;
+ font-size: 12px;
+}
+
+.list {
+ position: relative;
+ flex: 1;
+ overflow-y: auto;
+ padding: 0 6px 12px;
+ @include scrollbar(0.25rem);
+}
+
+.empty {
+ margin: 20px 8px 0;
+ font-size: 12px;
+ color: var(--l3-foreground);
+ text-align: center;
+}
+
+.srOnly {
+ position: absolute;
+ width: 1px;
+ height: 1px;
+ padding: 0;
+ margin: -1px;
+ overflow: hidden;
+ clip: rect(0, 0, 0, 0);
+ white-space: nowrap;
+ border: 0;
+}
+
+.loadingDots {
+ display: inline-flex;
+ align-items: center;
+ gap: 3px;
+}
+
+.loadingDot {
+ width: 4px;
+ height: 4px;
+ border-radius: 50%;
+ background: var(--l3-foreground);
+ opacity: 0.4;
+ animation: historyLoadingDot 1.1s ease-in-out infinite;
+
+ &:nth-child(2) {
+ animation-delay: 0.18s;
+ }
+
+ &:nth-child(3) {
+ animation-delay: 0.36s;
+ }
+}
+
+@keyframes historyLoadingDot {
+ 0%,
+ 100% {
+ opacity: 0.25;
+ transform: translateY(0);
+ }
+ 50% {
+ opacity: 1;
+ transform: translateY(-1px);
+ }
+}
+
+.group {
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ margin-bottom: 8px;
+
+ &.archived {
+ margin-top: 4px;
+ padding-top: 10px;
+ border-top: 1px solid var(--l2-border);
+ }
+}
+
+.groupLabel {
+ display: block;
+ padding: 8px;
+ font-size: 10px;
+ font-weight: 600;
+ text-transform: uppercase;
+ letter-spacing: 0.07em;
+ color: var(--l3-foreground);
+}
diff --git a/frontend/src/container/AIAssistant/components/ConversationsList/ConversationsList.tsx b/frontend/src/container/AIAssistant/components/ConversationsList/ConversationsList.tsx
new file mode 100644
index 0000000000..5c045c3dbb
--- /dev/null
+++ b/frontend/src/container/AIAssistant/components/ConversationsList/ConversationsList.tsx
@@ -0,0 +1,234 @@
+import { useEffect, useMemo, useState } from 'react';
+import cx from 'classnames';
+import { Button } from '@signozhq/ui/button';
+import { Input } from '@signozhq/ui/input';
+import { Tooltip } from '@signozhq/ui/tooltip';
+import { Plus, Search } from '@signozhq/icons';
+
+import { useAIAssistantStore } from '../../store/useAIAssistantStore';
+import { Conversation } from '../../types';
+import { useVariant } from '../../VariantContext';
+import ConversationItem from '../ConversationItem';
+
+import styles from './ConversationsList.module.scss';
+
+interface ConversationsListProps {
+ /** Called when a conversation is selected — lets the parent navigate if needed */
+ onSelect?: (id: string) => void;
+ onNewConversation?: () => void;
+ showAddNewConversation?: boolean;
+}
+
+function groupByDate(
+ conversations: Conversation[],
+): { label: string; items: Conversation[] }[] {
+ const now = Date.now();
+ const DAY = 86_400_000;
+
+ const groups: Record<string, Conversation[]> = {
+ Today: [],
+ Yesterday: [],
+ 'Last 7 days': [],
+ 'Last 30 days': [],
+ Older: [],
+ };
+
+ for (const conv of conversations) {
+ const age = now - (conv.updatedAt ?? conv.createdAt);
+ if (age < DAY) {
+ groups.Today.push(conv);
+ } else if (age < 2 * DAY) {
+ groups.Yesterday.push(conv);
+ } else if (age < 7 * DAY) {
+ groups['Last 7 days'].push(conv);
+ } else if (age < 30 * DAY) {
+ groups['Last 30 days'].push(conv);
+ } else {
+ groups.Older.push(conv);
+ }
+ }
+
+ return Object.entries(groups)
+ .filter(([, items]) => items.length > 0)
+ .map(([label, items]) => ({ label, items }));
+}
+
+/**
+ * Three-dot loading indicator. Sits inside the sidebar header so the
+ * conversation list is never bumped down by a skeleton row when threads
+ * load — visible signal of in-flight work without any layout shift.
+ */
+function HeaderLoadingDots(): JSX.Element {
+ return (
+ <span className={styles.loadingDots} role="status" aria-label="Loading">
+ <span className={styles.loadingDot} />
+ <span className={styles.loadingDot} />
+ <span className={styles.loadingDot} />
+ </span>
+ );
+}
+
+export default function ConversationsList({
+ onSelect,
+ onNewConversation,
+ showAddNewConversation = false,
+}: ConversationsListProps): JSX.Element {
+ const variant = useVariant();
+ const conversations = useAIAssistantStore((s) => s.conversations);
+ const activeConversationId = useAIAssistantStore(
+ (s) => s.activeConversationId,
+ );
+ const isLoadingThreads = useAIAssistantStore((s) => s.isLoadingThreads);
+ const setActiveConversation = useAIAssistantStore(
+ (s) => s.setActiveConversation,
+ );
+ const loadThread = useAIAssistantStore((s) => s.loadThread);
+ const fetchThreads = useAIAssistantStore((s) => s.fetchThreads);
+ const archiveConversation = useAIAssistantStore((s) => s.archiveConversation);
+ const restoreConversation = useAIAssistantStore((s) => s.restoreConversation);
+ const renameConversation = useAIAssistantStore((s) => s.renameConversation);
+
+ const [searchQuery, setSearchQuery] = useState('');
+
+ // Fetch threads from backend on mount
+ useEffect(() => {
+ void fetchThreads();
+ }, [fetchThreads]);
+
+ // Case-insensitive substring match against the conversation title.
+ // Untitled conversations match the literal placeholder so users
+ // searching for "new" can still find them.
+ const trimmedQuery = searchQuery.trim().toLowerCase();
+ const matchesQuery = (c: Conversation): boolean => {
+ if (!trimmedQuery) {
+ return true;
+ }
+ const title = (c.title ?? 'New conversation').toLowerCase();
+ return title.includes(trimmedQuery);
+ };
+
+ const sortedActive = useMemo(
+ () =>
+ Object.values(conversations)
+ .filter((c) => !c.archived && matchesQuery(c))
+ .sort(
+ (a, b) => (b.updatedAt ?? b.createdAt) - (a.updatedAt ?? a.createdAt),
+ ),
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [conversations, trimmedQuery],
+ );
+
+ const sortedArchived = useMemo(
+ () =>
+ Object.values(conversations)
+ .filter((c) => Boolean(c.archived) && c.threadId && matchesQuery(c))
+ .sort(
+ (a, b) => (b.updatedAt ?? b.createdAt) - (a.updatedAt ?? a.createdAt),
+ ),
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [conversations, trimmedQuery],
+ );
+
+ const groups = useMemo(() => groupByDate(sortedActive), [sortedActive]);
+
+ const hasAnySidebarRows = groups.length > 0 || sortedArchived.length > 0;
+ const isSearching = trimmedQuery.length > 0;
+
+ const handleSelect = (id: string): void => {
+ const conv = conversations[id];
+ if (conv?.threadId) {
+ // Always load from backend — refreshes messages and reconnects
+ // to active execution if the thread is still busy.
+ void loadThread(conv.threadId);
+ } else {
+ // Local-only conversation (no backend thread yet)
+ setActiveConversation(id);
+ }
+ onSelect?.(id);
+ };
+
+ const variantClass =
+ variant === 'page' ? styles.variantPage : styles.variantPanel;
+
+ return (
+ <div className={cx(styles.conversationsList, variantClass)}>
+ <div className={styles.header}>
+ <span className={styles.heading}>Conversations</span>
+ {isLoadingThreads && <HeaderLoadingDots />}
+
+ {!isLoadingThreads && showAddNewConversation && (
+ <Tooltip title="New conversation">
+ <Button
+ variant="solid"
+ size="sm"
+ color="secondary"
+ onClick={onNewConversation}
+ aria-label="New conversation"
+ >
+ <Plus size={12} />
+ </Button>
+ </Tooltip>
+ )}
+ </div>
+
+ <div className={styles.searchBar}>
+ <Input
+ type="text"
+ value={searchQuery}
+ onChange={(e): void => setSearchQuery(e.target.value)}
+ placeholder="Search conversations…"
+ prefix={<Search size={12} />}
+ className={styles.search}
+ />
+ </div>
+
+ <div className={styles.list} aria-busy={isLoadingThreads}>
+ {isLoadingThreads && (
+ <span className={styles.srOnly} role="status">
+ Loading conversations
+ </span>
+ )}
+
+ {!isLoadingThreads && !hasAnySidebarRows && (
+ <p className={styles.empty}>
+ {isSearching ? 'No matching conversations.' : 'No conversations yet.'}
+ </p>
+ )}
+
+ {groups.map(({ label, items }) => (
+ <div key={label} className={styles.group}>
+ <span className={styles.groupLabel}>{label}</span>
+ {items.map((conv) => (
+ <ConversationItem
+ key={conv.id}
+ conversation={conv}
+ isActive={conv.id === activeConversationId}
+ onSelect={handleSelect}
+ onRename={renameConversation}
+ onArchive={archiveConversation}
+ onRestore={restoreConversation}
+ />
+ ))}
+ </div>
+ ))}
+
+ {sortedArchived.length > 0 && (
+ <div className={cx(styles.group, styles.archived)}>
+ <span className={styles.groupLabel}>Archived Conversations</span>
+ {sortedArchived.map((conv) => (
+ <ConversationItem
+ key={conv.id}
+ conversation={conv}
+ isActive={conv.id === activeConversationId}
+ onSelect={handleSelect}
+ onRename={renameConversation}
+ onArchive={archiveConversation}
+ onRestore={restoreConversation}
+ />
+ ))}
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/frontend/src/container/AIAssistant/components/ConversationsList/index.ts b/frontend/src/container/AIAssistant/components/ConversationsList/index.ts
new file mode 100644
index 0000000000..0483d1d96e
--- /dev/null
+++ b/frontend/src/container/AIAssistant/components/ConversationsList/index.ts
@@ -0,0 +1,2 @@
+export * from './ConversationsList';
+export { default } from './ConversationsList';
diff --git a/frontend/src/container/AIAssistant/components/MessageBubble/MessageBubble.module.scss b/frontend/src/container/AIAssistant/components/MessageBubble/MessageBubble.module.scss
new file mode 100644
index 0000000000..a0f1d24938
--- /dev/null
+++ b/frontend/src/container/AIAssistant/components/MessageBubble/MessageBubble.module.scss
@@ -0,0 +1,327 @@
+.message {
+ display: flex;
+ padding: 8px 16px;
+ // CSS variable consumed by MessageFeedback to fade in on hover.
+ --feedback-opacity: 0;
+
+ &:hover {
+ --feedback-opacity: 1;
+ }
+
+ &.compact {
+ padding: 6px;
+ }
+}
+
+.user {
+ justify-content: flex-end;
+}
+
+.assistant {
+ justify-content: flex-start;
+}
+
+.body {
+ display: flex;
+ flex-direction: column;
+ max-width: 80%;
+
+ &.compact {
+ max-width: 90%;
+ }
+
+ .user & {
+ align-items: flex-end;
+ }
+
+ .assistant & {
+ align-items: flex-start;
+ }
+}
+
+.bubble {
+ border-radius: var(--radius-2);
+ padding: 8px;
+ font-size: 12px;
+ font-style: normal;
+ font-weight: 400;
+ line-height: 20px; /* 153.846% */
+ letter-spacing: -0.065px;
+ max-width: 100%;
+
+ .user & {
+ background: var(--accent-primary);
+ color: var(--primary-foreground);
+ border-bottom-right-radius: var(--radius-2);
+ }
+
+ .assistant & {
+ // Flex column for text blocks, tool steps and cards. No parent
+ // gap — auxiliary blocks (Thinking / ToolCall / actions) stack
+ // flush, and the prose `.markdown` block adds its own 24px top
+ // and bottom margins to mark itself as the message's focal point.
+ display: flex;
+ flex-direction: column;
+ align-items: flex-start;
+ background: var(--l2-background);
+ color: var(--l1-foreground);
+ border-bottom-left-radius: var(--radius-2);
+ }
+}
+
+.text {
+ margin: 0;
+ white-space: pre-wrap;
+ word-break: break-word;
+}
+
+// User-bubble row: pencil button sits to the LEFT of the bubble within
+// the right-aligned message line, so it visually "ends" at the bubble's
+// right edge while keeping the bubble in its original position.
+.bubbleRow {
+ display: flex;
+ align-items: center;
+ gap: 2px;
+ max-width: 100%;
+}
+
+.markdown {
+ width: 100%;
+ word-break: break-word;
+ // Anchor the prose block apart from any auxiliary rows (Thinking /
+ // ToolCall / Suggested actions) above and below it. Reset when this
+ // is the only / first / last child so the bubble doesn't grow taller
+ // than its content.
+ margin: 12px 0;
+
+ &:first-child {
+ margin-top: 0;
+ }
+
+ &:last-child {
+ margin-bottom: 0;
+ }
+
+ p {
+ margin: 0 0 0.65em;
+
+ &:last-child {
+ margin-bottom: 0;
+ }
+ }
+
+ ul,
+ ol {
+ margin: 0 0 0.65em;
+ padding-left: 1.5em;
+
+ &:last-child {
+ margin-bottom: 0;
+ }
+ }
+
+ li {
+ margin-bottom: 0.3em;
+
+ &:last-child {
+ margin-bottom: 0;
+ }
+
+ ul,
+ ol {
+ margin-top: 0.25em;
+ margin-bottom: 0;
+ }
+ }
+
+ h1,
+ h2,
+ h3,
+ h4,
+ h5,
+ h6 {
+ font-weight: 600;
+ line-height: 1.35;
+ margin: 0.9em 0 0.4em;
+ color: var(--l1-foreground);
+
+ &:first-child {
+ margin-top: 0;
+ }
+
+ &:last-child {
+ margin-bottom: 0;
+ }
+ }
+
+ h1 {
+ font-size: 1.15em;
+ }
+ h2 {
+ font-size: 1.08em;
+ }
+ h3 {
+ font-size: 1em;
+ }
+ h4,
+ h5,
+ h6 {
+ font-size: 0.95em;
+ }
+
+ strong {
+ font-weight: 600;
+ }
+ em {
+ font-style: italic;
+ }
+
+ a {
+ color: var(--accent-primary);
+ text-decoration: underline;
+ text-underline-offset: 2px;
+ text-decoration-thickness: 1px;
+
+ &:hover {
+ opacity: 0.8;
+ }
+ }
+
+ blockquote {
+ border-left: 3px solid var(--l2-border);
+ padding: 0.1em 0 0.1em 0.8em;
+ color: var(--l2-foreground);
+ font-style: italic;
+ margin: 0 0 0.65em;
+
+ &:last-child {
+ margin-bottom: 0;
+ }
+
+ p {
+ margin-bottom: 0;
+ }
+ }
+
+ hr {
+ border: none;
+ border-top: 1px solid var(--l2-border);
+ margin: 0.75em 0;
+ }
+
+ code {
+ font-family: 'Geist Mono', 'Fira Code', monospace;
+ font-size: 11.5px;
+ border-radius: var(--radius-2);
+ padding: 1px 4px;
+ background: var(--l3-background);
+ color: var(--l1-foreground);
+ }
+
+ pre {
+ margin: 0 0 0.65em;
+
+ &:last-child {
+ margin-bottom: 0;
+ }
+ }
+
+ pre code {
+ display: block;
+ padding: 10px;
+ overflow-x: auto;
+ border-radius: var(--radius-2);
+ white-space: pre;
+ }
+
+ table {
+ border-collapse: collapse;
+ font-size: 12px;
+ margin: 0 0 0.65em;
+ width: 100%;
+
+ &:last-child {
+ margin-bottom: 0;
+ }
+
+ th,
+ td {
+ padding: 5px 10px;
+ border: 1px solid var(--l2-border);
+ text-align: left;
+ }
+
+ th {
+ background: var(--l2-background);
+ color: var(--l1-foreground);
+ font-weight: 600;
+ }
+
+ td {
+ color: var(--l1-foreground);
+ }
+ }
+}
+
+.attachments {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 8px;
+ margin-bottom: 8px;
+}
+
+.attachmentImage {
+ max-width: 200px;
+ max-height: 160px;
+ border-radius: var(--radius-2);
+ object-fit: cover;
+}
+
+.attachmentFile {
+ font-size: 11px;
+ padding: 3px 8px;
+ border-radius: var(--radius-2);
+ background: var(--l3-background);
+ color: var(--l2-foreground);
+ max-width: 180px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.typingIndicator {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ padding: 4px 0;
+ height: 20px;
+
+ span {
+ display: inline-block;
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+ background: var(--l2-foreground);
+ animation: bounce 1.2s infinite ease-in-out;
+
+ &:nth-child(2) {
+ animation-delay: 0.2s;
+ }
+ &:nth-child(3) {
+ animation-delay: 0.4s;
+ }
+ }
+}
+
+@keyframes bounce {
+ 0%,
+ 80%,
+ 100% {
+ transform: scale(0.7);
+ opacity: 0.5;
+ }
+ 40% {
+ transform: scale(1);
+ opacity: 1;
+ }
+}
diff --git a/frontend/src/container/AIAssistant/components/MessageBubble/MessageBubble.tsx b/frontend/src/container/AIAssistant/components/MessageBubble/MessageBubble.tsx
new file mode 100644
index 0000000000..cc6c41ec69
--- /dev/null
+++ b/frontend/src/container/AIAssistant/components/MessageBubble/MessageBubble.tsx
@@ -0,0 +1,164 @@
+import React from 'react';
+import cx from 'classnames';
+import ReactMarkdown from 'react-markdown';
+import remarkGfm from 'remark-gfm';
+
+// Side-effect: registers all built-in block types into the BlockRegistry
+import '../blocks';
+
+import { useVariant } from '../../VariantContext';
+import { Message, MessageBlock } from '../../types';
+import ActionsSection from '../ActionsSection';
+import { RichCodeBlock } from '../blocks';
+import { MessageContext } from '../MessageContext';
+import MessageFeedback from '../MessageFeedback';
+import ThinkingStep from '../ThinkingStep';
+import ToolCallStep from '../ToolCallStep';
+import UserMessageActions from '../UserMessageActions';
+
+import styles from './MessageBubble.module.scss';
+
+/**
+ * react-markdown renders fenced code blocks as <pre><code>...</code></pre>.
+ * When RichCodeBlock replaces <code> with a custom AI block component, the
+ * block ends up wrapped in <pre> which forces monospace font and white-space:pre.
+ * This renderer detects that case and unwraps the <pre>.
+ */
+function SmartPre({ children }: { children?: React.ReactNode }): JSX.Element {
+ const childArr = React.Children.toArray(children);
+ if (childArr.length === 1) {
+ const child = childArr[0];
+ // If the code component returned something other than a <code> element
+ // (i.e. a custom AI block), render without the <pre> wrapper.
+ if (React.isValidElement(child) && child.type !== 'code') {
+ return <>{child}</>;
+ }
+ }
+ return <pre>{children}</pre>;
+}
+
+const MD_PLUGINS = [remarkGfm];
+const MD_COMPONENTS = { code: RichCodeBlock, pre: SmartPre };
+
+/** Renders a single MessageBlock by type. */
+function renderBlock(block: MessageBlock, index: number): JSX.Element {
+ switch (block.type) {
+ case 'thinking':
+ return <ThinkingStep key={index} content={block.content} />;
+ case 'tool_call':
+ // Blocks in a persisted message are always complete — done is always true.
+ return (
+ <ToolCallStep
+ key={index}
+ toolCall={{
+ toolName: block.toolName,
+ input: block.toolInput,
+ result: block.result,
+ done: true,
+ displayText: block.displayText,
+ }}
+ />
+ );
+ case 'text':
+ default:
+ return (
+ <ReactMarkdown
+ key={index}
+ className={styles.markdown}
+ remarkPlugins={MD_PLUGINS}
+ components={MD_COMPONENTS}
+ >
+ {block.content}
+ </ReactMarkdown>
+ );
+ }
+}
+
+interface MessageBubbleProps {
+ message: Message;
+ onRegenerate?: () => void;
+ isLastAssistant?: boolean;
+}
+
+export default function MessageBubble({
+ message,
+ onRegenerate,
+ isLastAssistant = false,
+}: MessageBubbleProps): JSX.Element {
+ const variant = useVariant();
+ const isCompact = variant === 'panel';
+ const isUser = message.role === 'user';
+ const hasBlocks = !isUser && message.blocks && message.blocks.length > 0;
+
+ const messageClass = cx(
+ styles.message,
+ isUser ? styles.user : styles.assistant,
+ {
+ [styles.compact]: isCompact,
+ },
+ );
+ const bodyClass = cx(styles.body, { [styles.compact]: isCompact });
+
+ return (
+ <div className={messageClass} data-testid={`ai-message-${message.id}`}>
+ <div className={bodyClass}>
+ <div className={styles.bubbleRow}>
+ <div className={styles.bubble}>
+ {message.attachments && message.attachments.length > 0 && (
+ <div className={styles.attachments}>
+ {message.attachments.map((att) => {
+ const isImage = att.type.startsWith('image/');
+ return isImage ? (
+ <img
+ key={att.name}
+ src={att.dataUrl}
+ alt={att.name}
+ className={styles.attachmentImage}
+ />
+ ) : (
+ <div key={att.name} className={styles.attachmentFile}>
+ {att.name}
+ </div>
+ );
+ })}
+ </div>
+ )}
+
+ {isUser ? (
+ <p className={styles.text}>{message.content}</p>
+ ) : hasBlocks ? (
+ <MessageContext.Provider value={{ messageId: message.id }}>
+ {/* eslint-disable-next-line react/no-array-index-key */}
+ {message.blocks!.map((block, i) => renderBlock(block, i))}
+ </MessageContext.Provider>
+ ) : (
+ <MessageContext.Provider value={{ messageId: message.id }}>
+ <ReactMarkdown
+ className={styles.markdown}
+ remarkPlugins={MD_PLUGINS}
+ components={MD_COMPONENTS}
+ >
+ {message.content}
+ </ReactMarkdown>
+ </MessageContext.Provider>
+ )}
+
+ {!isUser && message.actions && message.actions.length > 0 && (
+ <ActionsSection actions={message.actions} />
+ )}
+ </div>
+ </div>
+
+ {!isUser && (
+ <MessageFeedback
+ message={message}
+ onRegenerate={onRegenerate}
+ isLastAssistant={isLastAssistant}
+ />
+ )}
+
+ {isUser && <UserMessageActions message={message} />}
+ </div>
+ </div>
+ );
+}
diff --git a/frontend/src/container/AIAssistant/components/MessageBubble/index.ts b/frontend/src/container/AIAssistant/components/MessageBubble/index.ts
new file mode 100644
index 0000000000..86f9e13421
--- /dev/null
+++ b/frontend/src/container/AIAssistant/components/MessageBubble/index.ts
@@ -0,0 +1,2 @@
+export * from './MessageBubble';
+export { default } from './MessageBubble';
diff --git a/frontend/src/container/AIAssistant/components/MessageContext.ts b/frontend/src/container/AIAssistant/components/MessageContext.ts
new file mode 100644
index 0000000000..c48fdfb11b
--- /dev/null
+++ b/frontend/src/container/AIAssistant/components/MessageContext.ts
@@ -0,0 +1,13 @@
+// eslint-disable-next-line no-restricted-imports
+import { createContext, useContext } from 'react';
+
+interface MessageContextValue {
+ messageId: string;
+}
+
+export const MessageContext = createContext<MessageContextValue>({
+ messageId: '',
+});
+
+export const useMessageContext = (): MessageContextValue =>
+ useContext(MessageContext);
diff --git a/frontend/src/container/AIAssistant/components/MessageFeedback/MessageFeedback.module.scss b/frontend/src/container/AIAssistant/components/MessageFeedback/MessageFeedback.module.scss
new file mode 100644
index 0000000000..ea75c2a4eb
--- /dev/null
+++ b/frontend/src/container/AIAssistant/components/MessageFeedback/MessageFeedback.module.scss
@@ -0,0 +1,89 @@
+.feedback {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ padding: 4px 2px 0;
+ // Driven by MessageBubble's --feedback-opacity (0 normally, 1 on hover/visible).
+ opacity: var(--feedback-opacity, 0);
+ transition: opacity 0.15s ease;
+
+ &.visible {
+ --feedback-opacity: 1;
+ opacity: 1;
+ }
+}
+
+.actions {
+ display: flex;
+ align-items: center;
+ gap: 2px;
+}
+
+.btn {
+ width: 24px !important;
+ height: 24px !important;
+ min-height: 0 !important;
+ padding: 0 !important;
+ display: inline-flex !important;
+ align-items: center !important;
+ justify-content: center !important;
+ color: var(--l3-foreground) !important;
+
+ &:hover {
+ color: var(--l1-foreground) !important;
+ }
+
+ &.active {
+ color: var(--accent-forest) !important;
+ }
+
+ &.votedUp {
+ color: var(--accent-primary) !important;
+ }
+
+ &.votedDown {
+ color: var(--accent-cherry) !important;
+ }
+}
+
+.time {
+ font-size: 10px;
+ color: var(--l3-foreground);
+ white-space: nowrap;
+ padding-left: 2px;
+ border-left: 1px solid var(--l2-border);
+}
+
+.feedbackTextarea {
+ width: 100%;
+ min-height: 96px;
+ padding: 10px 12px;
+ resize: vertical;
+ font: inherit;
+ font-size: 13px;
+ line-height: 1.5;
+ color: var(--l1-foreground);
+ background: var(--l2-background);
+ border: 1px solid var(--l2-border);
+ border-radius: 6px;
+ outline: none;
+ transition:
+ border-color 0.15s ease,
+ box-shadow 0.15s ease;
+ box-sizing: border-box;
+
+ &::placeholder {
+ color: var(--l3-foreground);
+ }
+
+ &:focus {
+ border-color: var(--accent-primary);
+ box-shadow: 0 0 0 1px var(--accent-primary);
+ }
+}
+
+.feedbackDialogFooter {
+ display: flex;
+ justify-content: flex-end;
+ gap: 8px;
+}
diff --git a/frontend/src/container/AIAssistant/components/MessageFeedback/MessageFeedback.tsx b/frontend/src/container/AIAssistant/components/MessageFeedback/MessageFeedback.tsx
new file mode 100644
index 0000000000..5c181706c7
--- /dev/null
+++ b/frontend/src/container/AIAssistant/components/MessageFeedback/MessageFeedback.tsx
@@ -0,0 +1,220 @@
+import { useCallback, useEffect, useMemo, useState } from 'react';
+import cx from 'classnames';
+import { useCopyToClipboard } from 'react-use';
+import { Button } from '@signozhq/ui/button';
+import { DialogWrapper } from '@signozhq/ui/dialog';
+import { Tooltip } from '@signozhq/ui/tooltip';
+import { DATE_TIME_FORMATS } from 'constants/dateTimeFormats';
+import { Check, Copy, RefreshCw, ThumbsDown, ThumbsUp } from '@signozhq/icons';
+import { useTimezone } from 'providers/Timezone';
+
+import { useAIAssistantStore } from '../../store/useAIAssistantStore';
+import { FeedbackRating, Message } from '../../types';
+
+import styles from './MessageFeedback.module.scss';
+
+interface MessageFeedbackProps {
+ message: Message;
+ onRegenerate?: () => void;
+ isLastAssistant?: boolean;
+}
+
+function formatRelativeTime(timestamp: number): string {
+ const diffMs = Date.now() - timestamp;
+ const diffSec = Math.floor(diffMs / 1000);
+
+ if (diffSec < 10) {
+ return 'just now';
+ }
+ if (diffSec < 60) {
+ return `${diffSec}s ago`;
+ }
+
+ const diffMin = Math.floor(diffSec / 60);
+ if (diffMin < 60) {
+ return `${diffMin} min${diffMin === 1 ? '' : 's'} ago`;
+ }
+
+ const diffHr = Math.floor(diffMin / 60);
+ if (diffHr < 24) {
+ return `${diffHr} hr${diffHr === 1 ? '' : 's'} ago`;
+ }
+
+ const diffDay = Math.floor(diffHr / 24);
+ return `${diffDay} day${diffDay === 1 ? '' : 's'} ago`;
+}
+
+export default function MessageFeedback({
+ message,
+ onRegenerate,
+ isLastAssistant = false,
+}: MessageFeedbackProps): JSX.Element {
+ const [copied, setCopied] = useState(false);
+ const [, copyToClipboard] = useCopyToClipboard();
+ const submitMessageFeedback = useAIAssistantStore(
+ (s) => s.submitMessageFeedback,
+ );
+
+ const { formatTimezoneAdjustedTimestamp } = useTimezone();
+
+ // Local vote state — initialised from persisted feedbackRating, updated
+ // immediately on click so the UI responds without waiting for the API.
+ const [vote, setVote] = useState<FeedbackRating | null>(
+ message.feedbackRating ?? null,
+ );
+
+ // Negative-feedback dialog: collects an optional comment from the user.
+ // Positive feedback is one-click; negative requires explicit Submit so
+ // users can describe what was wrong.
+ const [isNegativeDialogOpen, setIsNegativeDialogOpen] = useState(false);
+ const [negativeComment, setNegativeComment] = useState('');
+
+ const [relativeTime, setRelativeTime] = useState(() =>
+ formatRelativeTime(message.createdAt),
+ );
+
+ const absoluteTime = useMemo(
+ () =>
+ formatTimezoneAdjustedTimestamp(
+ message.createdAt,
+ DATE_TIME_FORMATS.DD_MMM_YYYY_HH_MM_SS,
+ ),
+ [message.createdAt, formatTimezoneAdjustedTimestamp],
+ );
+
+ // Tick relative time every 30 s
+ useEffect(() => {
+ const id = setInterval(() => {
+ setRelativeTime(formatRelativeTime(message.createdAt));
+ }, 30_000);
+ return (): void => clearInterval(id);
+ }, [message.createdAt]);
+
+ const handleCopy = useCallback((): void => {
+ copyToClipboard(message.content);
+ setCopied(true);
+ setTimeout(() => setCopied(false), 1500);
+ }, [copyToClipboard, message.content]);
+
+ const handleVote = useCallback(
+ (rating: FeedbackRating): void => {
+ if (vote === rating) {
+ return;
+ }
+ if (rating === 'negative') {
+ setNegativeComment('');
+ setIsNegativeDialogOpen(true);
+ return;
+ }
+ setVote(rating);
+ submitMessageFeedback(message.id, rating);
+ },
+ [vote, message.id, submitMessageFeedback],
+ );
+
+ const handleSubmitNegative = useCallback((): void => {
+ setVote('negative');
+ setIsNegativeDialogOpen(false);
+ submitMessageFeedback(
+ message.id,
+ 'negative',
+ negativeComment.trim() || undefined,
+ );
+ }, [message.id, negativeComment, submitMessageFeedback]);
+
+ return (
+ <>
+ <div className={cx(styles.feedback, { [styles.visible]: isLastAssistant })}>
+ <div className={styles.actions}>
+ <Tooltip title={copied ? 'Copied!' : 'Copy'}>
+ <Button
+ className={styles.btn}
+ size="icon"
+ variant="ghost"
+ onClick={handleCopy}
+ color="secondary"
+ >
+ {copied ? <Check size={12} /> : <Copy size={12} />}
+ </Button>
+ </Tooltip>
+
+ <Tooltip title="Good response">
+ <Button
+ className={cx(styles.btn, { [styles.votedUp]: vote === 'positive' })}
+ size="icon"
+ variant="ghost"
+ color="secondary"
+ onClick={(): void => handleVote('positive')}
+ >
+ <ThumbsUp size={12} />
+ </Button>
+ </Tooltip>
+
+ <Tooltip title="Bad response">
+ <Button
+ className={cx(styles.btn, {
+ [styles.votedDown]: vote === 'negative',
+ })}
+ size="icon"
+ variant="ghost"
+ color="secondary"
+ onClick={(): void => handleVote('negative')}
+ >
+ <ThumbsDown size={12} />
+ </Button>
+ </Tooltip>
+
+ {onRegenerate && (
+ <Tooltip title="Regenerate">
+ <Button
+ className={styles.btn}
+ size="icon"
+ variant="ghost"
+ color="secondary"
+ onClick={onRegenerate}
+ >
+ <RefreshCw size={12} />
+ </Button>
+ </Tooltip>
+ )}
+ </div>
+
+ <span className={styles.time}>
+ {relativeTime} · {absoluteTime}
+ </span>
+ </div>
+
+ <DialogWrapper
+ open={isNegativeDialogOpen}
+ onOpenChange={setIsNegativeDialogOpen}
+ title="What went wrong?"
+ subTitle="Your feedback helps us improve the assistant. Comments are optional."
+ width="base"
+ footer={
+ <div className={styles.feedbackDialogFooter}>
+ <Button
+ variant="solid"
+ color="secondary"
+ onClick={(): void => setIsNegativeDialogOpen(false)}
+ >
+ Cancel
+ </Button>
+ <Button variant="solid" color="primary" onClick={handleSubmitNegative}>
+ Send feedback
+ </Button>
+ </div>
+ }
+ >
+ <textarea
+ className={styles.feedbackTextarea}
+ placeholder="Tell us what was unhelpful, inaccurate, or unsafe…"
+ value={negativeComment}
+ onChange={(e): void => setNegativeComment(e.target.value)}
+ rows={5}
+ autoFocus
+ maxLength={2000}
+ />
+ </DialogWrapper>
+ </>
+ );
+}
diff --git a/frontend/src/container/AIAssistant/components/MessageFeedback/index.ts b/frontend/src/container/AIAssistant/components/MessageFeedback/index.ts
new file mode 100644
index 0000000000..1159cf8e37
--- /dev/null
+++ b/frontend/src/container/AIAssistant/components/MessageFeedback/index.ts
@@ -0,0 +1,2 @@
+export * from './MessageFeedback';
+export { default } from './MessageFeedback';
diff --git a/frontend/src/container/AIAssistant/components/StreamingMessage/StreamingMessage.module.scss b/frontend/src/container/AIAssistant/components/StreamingMessage/StreamingMessage.module.scss
new file mode 100644
index 0000000000..e80d13880b
--- /dev/null
+++ b/frontend/src/container/AIAssistant/components/StreamingMessage/StreamingMessage.module.scss
@@ -0,0 +1,9 @@
+.streamingStatus {
+ display: inline-flex;
+ align-items: center;
+ gap: 5px;
+ font-size: 12px;
+ font-style: italic;
+ color: var(--l3-foreground);
+ margin-bottom: 6px;
+}
diff --git a/frontend/src/container/AIAssistant/components/StreamingMessage/StreamingMessage.tsx b/frontend/src/container/AIAssistant/components/StreamingMessage/StreamingMessage.tsx
new file mode 100644
index 0000000000..4738b4c638
--- /dev/null
+++ b/frontend/src/container/AIAssistant/components/StreamingMessage/StreamingMessage.tsx
@@ -0,0 +1,132 @@
+import React from 'react';
+import cx from 'classnames';
+import ReactMarkdown from 'react-markdown';
+import remarkGfm from 'remark-gfm';
+
+import type {
+ ApprovalEventDTO,
+ ClarificationEventDTO,
+} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
+
+import { useVariant } from '../../VariantContext';
+import { StreamingEventItem } from '../../types';
+import ApprovalCard from '../ApprovalCard';
+import { RichCodeBlock } from '../blocks';
+import ClarificationForm from '../ClarificationForm';
+import ThinkingStep from '../ThinkingStep';
+import ToolCallStep from '../ToolCallStep';
+
+import messageStyles from '../MessageBubble/MessageBubble.module.scss';
+import styles from './StreamingMessage.module.scss';
+
+function SmartPre({ children }: { children?: React.ReactNode }): JSX.Element {
+ const childArr = React.Children.toArray(children);
+ if (childArr.length === 1) {
+ const child = childArr[0];
+ if (React.isValidElement(child) && child.type !== 'code') {
+ return <>{child}</>;
+ }
+ }
+ return <pre>{children}</pre>;
+}
+
+const MD_PLUGINS = [remarkGfm];
+const MD_COMPONENTS = { code: RichCodeBlock, pre: SmartPre };
+
+/** Human-readable labels for execution status codes shown before any events arrive. */
+const STATUS_LABEL: Record<string, string> = {
+ queued: 'Queued…',
+ running: 'Thinking…',
+ awaiting_approval: 'Waiting for your approval…',
+ awaiting_clarification: 'Waiting for your input…',
+ resumed: 'Resumed…',
+};
+
+function TypingDots(): JSX.Element {
+ return (
+ <span className={messageStyles.typingIndicator}>
+ <span />
+ <span />
+ <span />
+ </span>
+ );
+}
+
+interface StreamingMessageProps {
+ conversationId: string;
+ /** Ordered timeline of text and tool-call events in arrival order. */
+ events: StreamingEventItem[];
+ status?: string;
+ pendingApproval?: ApprovalEventDTO | null;
+ pendingClarification?: ClarificationEventDTO | null;
+}
+
+export default function StreamingMessage({
+ conversationId,
+ events,
+ status = '',
+ pendingApproval = null,
+ pendingClarification = null,
+}: StreamingMessageProps): JSX.Element {
+ const variant = useVariant();
+ const isCompact = variant === 'panel';
+ const statusLabel = STATUS_LABEL[status] ?? '';
+ const isEmpty =
+ events.length === 0 && !pendingApproval && !pendingClarification;
+ const isWaitingOnUser = Boolean(pendingApproval || pendingClarification);
+
+ const messageClass = cx(messageStyles.message, messageStyles.assistant, {
+ [messageStyles.compact]: isCompact,
+ });
+
+ return (
+ <div className={messageClass}>
+ <div className={messageStyles.bubble}>
+ {/* Pre-output indicator — only before any events arrive. */}
+ {isEmpty && statusLabel && (
+ <span className={styles.streamingStatus}>{statusLabel}</span>
+ )}
+ {isEmpty && !statusLabel && <TypingDots />}
+
+ {/* eslint-disable react/no-array-index-key */}
+ {/* Events rendered in arrival order: text, thinking, and tool calls interleaved */}
+ {events.map((event, i) => {
+ if (event.kind === 'tool') {
+ return <ToolCallStep key={i} toolCall={event.toolCall} />;
+ }
+ if (event.kind === 'thinking') {
+ return <ThinkingStep key={i} content={event.content} />;
+ }
+ return (
+ <ReactMarkdown
+ key={i}
+ className={messageStyles.markdown}
+ remarkPlugins={MD_PLUGINS}
+ components={MD_COMPONENTS}
+ >
+ {event.content}
+ </ReactMarkdown>
+ );
+ })}
+ {/* eslint-enable react/no-array-index-key */}
+
+ {/* While events are still streaming, append the typing dots so the
+ user has a clear "more is coming" signal. Hidden when the agent
+ is waiting on the user's input (an approval or clarification
+ card already conveys that state). */}
+ {!isEmpty && !isWaitingOnUser && <TypingDots />}
+
+ {/* Approval / clarification cards appended after any streamed text */}
+ {pendingApproval && (
+ <ApprovalCard conversationId={conversationId} approval={pendingApproval} />
+ )}
+ {pendingClarification && (
+ <ClarificationForm
+ conversationId={conversationId}
+ clarification={pendingClarification}
+ />
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/frontend/src/container/AIAssistant/components/StreamingMessage/index.ts b/frontend/src/container/AIAssistant/components/StreamingMessage/index.ts
new file mode 100644
index 0000000000..e27923336d
--- /dev/null
+++ b/frontend/src/container/AIAssistant/components/StreamingMessage/index.ts
@@ -0,0 +1,2 @@
+export * from './StreamingMessage';
+export { default } from './StreamingMessage';
diff --git a/frontend/src/container/AIAssistant/components/ThinkingStep/ThinkingStep.module.scss b/frontend/src/container/AIAssistant/components/ThinkingStep/ThinkingStep.module.scss
new file mode 100644
index 0000000000..cf18746c3e
--- /dev/null
+++ b/frontend/src/container/AIAssistant/components/ThinkingStep/ThinkingStep.module.scss
@@ -0,0 +1,45 @@
+// Minimal expandable row — chevron + label, no icon, no left rail.
+// Matches the tool-call row treatment so consecutive thinking + tool
+// activity reads as one quiet "what the agent did" log.
+.row {
+ width: 100%;
+ font-size: 12px;
+}
+
+.header {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 4px 0;
+ background: transparent;
+ border: none;
+ cursor: pointer;
+ color: var(--l3-foreground);
+ transition: color 0.12s ease;
+
+ &:hover {
+ color: var(--l1-foreground);
+ }
+}
+
+.chevron {
+ flex-shrink: 0;
+ color: inherit;
+}
+
+.label {
+ font-weight: 400;
+}
+
+.body {
+ padding: 4px 0 4px 22px;
+}
+
+.content {
+ font-size: 12px;
+ color: var(--l3-foreground);
+ font-style: italic;
+ margin: 0;
+ white-space: pre-wrap;
+ line-height: 1.5;
+}
diff --git a/frontend/src/container/AIAssistant/components/ThinkingStep/ThinkingStep.tsx b/frontend/src/container/AIAssistant/components/ThinkingStep/ThinkingStep.tsx
new file mode 100644
index 0000000000..67deb984f2
--- /dev/null
+++ b/frontend/src/container/AIAssistant/components/ThinkingStep/ThinkingStep.tsx
@@ -0,0 +1,36 @@
+import { useState } from 'react';
+import { ChevronDown, ChevronRight } from '@signozhq/icons';
+
+import styles from './ThinkingStep.module.scss';
+
+interface ThinkingStepProps {
+ content: string;
+}
+
+/** Collapsible thinking row — chevron + label, content in the expanded body. */
+export default function ThinkingStep({
+ content,
+}: ThinkingStepProps): JSX.Element {
+ const [expanded, setExpanded] = useState(false);
+
+ const toggle = (): void => setExpanded((v) => !v);
+
+ return (
+ <div className={styles.row}>
+ <div className={styles.header} onClick={toggle}>
+ {expanded ? (
+ <ChevronDown size={12} className={styles.chevron} />
+ ) : (
+ <ChevronRight size={12} className={styles.chevron} />
+ )}
+ <span className={styles.label}>Thinking</span>
+ </div>
+
+ {expanded && (
+ <div className={styles.body}>
+ <p className={styles.content}>{content}</p>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/frontend/src/container/AIAssistant/components/ThinkingStep/index.ts b/frontend/src/container/AIAssistant/components/ThinkingStep/index.ts
new file mode 100644
index 0000000000..ca18610eb7
--- /dev/null
+++ b/frontend/src/container/AIAssistant/components/ThinkingStep/index.ts
@@ -0,0 +1,2 @@
+export * from './ThinkingStep';
+export { default } from './ThinkingStep';
diff --git a/frontend/src/container/AIAssistant/components/ToolCallStep/ToolCallStep.module.scss b/frontend/src/container/AIAssistant/components/ToolCallStep/ToolCallStep.module.scss
new file mode 100644
index 0000000000..54903a9848
--- /dev/null
+++ b/frontend/src/container/AIAssistant/components/ToolCallStep/ToolCallStep.module.scss
@@ -0,0 +1,99 @@
+// Minimal expandable row — chevron + label, no icon, no left rail.
+// While the tool is running we swap the chevron for a spinner in the
+// same slot so the row alignment doesn't shift when it completes.
+.row {
+ width: 100%;
+ font-size: 12px;
+
+ &.running {
+ opacity: 0.85;
+ }
+}
+
+.header {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 4px 0;
+ background: transparent;
+ border: none;
+ cursor: pointer;
+ color: var(--l3-foreground);
+ user-select: none;
+ transition: color 0.12s ease;
+
+ &:hover {
+ color: var(--l1-foreground);
+ }
+}
+
+.chevron {
+ flex-shrink: 0;
+ color: inherit;
+
+ &.spin {
+ color: var(--accent-primary);
+ animation: spin 1s linear infinite;
+ }
+}
+
+@keyframes spin {
+ from {
+ transform: rotate(0deg);
+ }
+ to {
+ transform: rotate(360deg);
+ }
+}
+
+.label {
+ font-weight: 400;
+ flex: 1;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.body {
+ padding: 4px 0 4px 22px;
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+}
+
+.section {
+ display: flex;
+ flex-direction: column;
+ gap: 3px;
+}
+
+.sectionLabel {
+ font-size: 9px;
+ font-weight: 600;
+ text-transform: uppercase;
+ letter-spacing: 0.06em;
+ color: var(--l3-foreground);
+}
+
+.toolName {
+ font-family: var(--font-mono, monospace);
+ font-size: 10px;
+ color: var(--l2-foreground);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.json {
+ font-family: var(--font-mono, monospace);
+ font-size: 11px;
+ color: var(--l2-foreground);
+ background: var(--l1-background);
+ border: 1px solid var(--l2-border);
+ border-radius: var(--radius-2);
+ padding: 5px 7px;
+ margin: 0;
+ overflow-x: auto;
+ white-space: pre;
+ max-height: 160px;
+}
diff --git a/frontend/src/container/AIAssistant/components/ToolCallStep/ToolCallStep.tsx b/frontend/src/container/AIAssistant/components/ToolCallStep/ToolCallStep.tsx
new file mode 100644
index 0000000000..5049f4bb1f
--- /dev/null
+++ b/frontend/src/container/AIAssistant/components/ToolCallStep/ToolCallStep.tsx
@@ -0,0 +1,69 @@
+import { useState } from 'react';
+import cx from 'classnames';
+import { ChevronDown, ChevronRight, LoaderCircle } from '@signozhq/icons';
+
+import { StreamingToolCall } from '../../types';
+
+import styles from './ToolCallStep.module.scss';
+
+interface ToolCallStepProps {
+ toolCall: StreamingToolCall;
+}
+
+/** Collapsible tool-call row — chevron + label, in/out detail in the body. */
+export default function ToolCallStep({
+ toolCall,
+}: ToolCallStepProps): JSX.Element {
+ const [expanded, setExpanded] = useState(false);
+ const { toolName, input, result, done, displayText } = toolCall;
+
+ // Prefer the server-supplied `displayText` from `ToolCallEventDTO` —
+ // it's the human-friendly title the backend wants surfaced. Fall back
+ // to a derived label ("signoz_get_dashboard" → "Get Dashboard") when
+ // the field is empty / null / missing.
+ const label =
+ displayText && displayText.trim().length > 0
+ ? displayText
+ : toolName
+ .replace(/^[a-z]+_/, '') // strip prefix like "signoz_"
+ .replace(/_/g, ' ')
+ .replace(/\b\w/g, (c) => c.toUpperCase());
+
+ const toggle = (): void => setExpanded((v) => !v);
+
+ return (
+ <div className={cx(styles.row, { [styles.running]: !done })}>
+ <div className={styles.header} onClick={toggle}>
+ {!done ? (
+ <LoaderCircle size={12} className={cx(styles.chevron, styles.spin)} />
+ ) : expanded ? (
+ <ChevronDown size={12} className={styles.chevron} />
+ ) : (
+ <ChevronRight size={12} className={styles.chevron} />
+ )}
+ <span className={styles.label}>{label}</span>
+ </div>
+
+ {expanded && (
+ <div className={styles.body}>
+ <div className={styles.section}>
+ <span className={styles.sectionLabel}>Tool</span>
+ <span className={styles.toolName}>{toolName}</span>
+ </div>
+ <div className={styles.section}>
+ <span className={styles.sectionLabel}>Input</span>
+ <pre className={styles.json}>{JSON.stringify(input, null, 2)}</pre>
+ </div>
+ {done && result !== undefined && (
+ <div className={styles.section}>
+ <span className={styles.sectionLabel}>Output</span>
+ <pre className={styles.json}>
+ {typeof result === 'string' ? result : JSON.stringify(result, null, 2)}
+ </pre>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/frontend/src/container/AIAssistant/components/ToolCallStep/index.ts b/frontend/src/container/AIAssistant/components/ToolCallStep/index.ts
new file mode 100644
index 0000000000..b419b2f4fc
--- /dev/null
+++ b/frontend/src/container/AIAssistant/components/ToolCallStep/index.ts
@@ -0,0 +1,2 @@
+export * from './ToolCallStep';
+export { default } from './ToolCallStep';
diff --git a/frontend/src/container/AIAssistant/components/UserMessageActions/UserMessageActions.module.scss b/frontend/src/container/AIAssistant/components/UserMessageActions/UserMessageActions.module.scss
new file mode 100644
index 0000000000..6d28e45ef7
--- /dev/null
+++ b/frontend/src/container/AIAssistant/components/UserMessageActions/UserMessageActions.module.scss
@@ -0,0 +1,31 @@
+.actions {
+ display: flex;
+ align-items: center;
+ gap: 2px;
+ padding: 4px 2px 0;
+ // User bubbles are right-aligned; mirror the alignment so the chips
+ // hug the bubble's right edge.
+ align-self: flex-end;
+ // Driven by MessageBubble's --feedback-opacity (0 normally, 1 on hover).
+ opacity: var(--feedback-opacity, 0);
+ transition: opacity 0.15s ease;
+}
+
+.btn {
+ width: 24px !important;
+ height: 24px !important;
+ min-height: 0 !important;
+ padding: 0 !important;
+ display: inline-flex !important;
+ align-items: center !important;
+ justify-content: center !important;
+ color: var(--l3-foreground) !important;
+
+ &:hover {
+ color: var(--l1-foreground) !important;
+ }
+
+ &.active {
+ color: var(--accent-forest) !important;
+ }
+}
diff --git a/frontend/src/container/AIAssistant/components/UserMessageActions/UserMessageActions.tsx b/frontend/src/container/AIAssistant/components/UserMessageActions/UserMessageActions.tsx
new file mode 100644
index 0000000000..96ea46791c
--- /dev/null
+++ b/frontend/src/container/AIAssistant/components/UserMessageActions/UserMessageActions.tsx
@@ -0,0 +1,48 @@
+import { useCallback, useState } from 'react';
+import { useCopyToClipboard } from 'react-use';
+import { Button } from '@signozhq/ui/button';
+import { Tooltip } from '@signozhq/ui/tooltip';
+import { Check, Copy } from '@signozhq/icons';
+
+import { Message } from '../../types';
+
+import styles from './UserMessageActions.module.scss';
+
+interface UserMessageActionsProps {
+ message: Message;
+}
+
+/**
+ * Action row rendered under user message bubbles. Mirrors the assistant
+ * feedback strip's hover-reveal treatment via the bubble's
+ * `--feedback-opacity` CSS variable; intentionally minimal for now —
+ * additional actions (edit, share, …) can slot in alongside the copy chip.
+ */
+export default function UserMessageActions({
+ message,
+}: UserMessageActionsProps): JSX.Element {
+ const [copied, setCopied] = useState(false);
+ const [, copyToClipboard] = useCopyToClipboard();
+
+ const handleCopy = useCallback((): void => {
+ copyToClipboard(message.content);
+ setCopied(true);
+ setTimeout(() => setCopied(false), 1500);
+ }, [copyToClipboard, message.content]);
+
+ return (
+ <div className={styles.actions}>
+ <Tooltip title={copied ? 'Copied!' : 'Copy'}>
+ <Button
+ className={styles.btn}
+ size="icon"
+ variant="ghost"
+ color="secondary"
+ onClick={handleCopy}
+ >
+ {copied ? <Check size={12} /> : <Copy size={12} />}
+ </Button>
+ </Tooltip>
+ </div>
+ );
+}
diff --git a/frontend/src/container/AIAssistant/components/UserMessageActions/index.ts b/frontend/src/container/AIAssistant/components/UserMessageActions/index.ts
new file mode 100644
index 0000000000..b2a931b32c
--- /dev/null
+++ b/frontend/src/container/AIAssistant/components/UserMessageActions/index.ts
@@ -0,0 +1 @@
+export { default } from './UserMessageActions';
diff --git a/frontend/src/container/AIAssistant/components/VirtualizedMessages/VirtualizedMessages.module.scss b/frontend/src/container/AIAssistant/components/VirtualizedMessages/VirtualizedMessages.module.scss
new file mode 100644
index 0000000000..bfb62f5b34
--- /dev/null
+++ b/frontend/src/container/AIAssistant/components/VirtualizedMessages/VirtualizedMessages.module.scss
@@ -0,0 +1,87 @@
+@use '../../_scrollbar' as *;
+
+.messages {
+ flex: 1;
+ overflow: auto;
+ @include scrollbar;
+
+ // 64px bottom padding leaves breathing room between the last bubble and
+ // the scroll viewport's edge so the bubble doesn't sit flush against the
+ // disclaimer / input bar. The scroll-to-bottom effect uses the scroller
+ // ref to scroll past this padding (Virtuoso's `align: 'end'` would only
+ // reach the last item's bottom and leave the padding hidden below).
+ & > div {
+ padding: 16px 0 64px;
+ }
+}
+
+.empty {
+ flex: 1;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ padding: 32px 24px;
+ gap: 8px;
+ text-align: center;
+}
+
+.emptyIcon {
+ margin-bottom: 4px;
+ opacity: 0.85;
+}
+
+.emptyTitle {
+ font-size: 16px;
+ font-weight: 600;
+ color: var(--l1-foreground);
+ margin: 0;
+}
+
+.emptySubtitle {
+ font-size: 13px;
+ color: var(--l3-foreground);
+ margin: 0 0 12px;
+ max-width: 320px;
+ line-height: 1.45;
+}
+
+.emptySuggestions {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ width: 100%;
+ max-width: 360px;
+}
+
+.emptyChip {
+ display: flex;
+ align-items: center;
+ justify-content: flex-start !important;
+ gap: 8px;
+ padding: 10px 14px;
+ border: 1px solid var(--l2-border);
+ border-radius: var(--radius-2);
+ background: var(--l1-background);
+ color: var(--l2-foreground);
+ font-size: 12.5px;
+ text-align: left;
+ cursor: pointer;
+ transition: all 0.15s ease;
+ line-height: 1.35;
+
+ &:hover {
+ background: var(--l2-background);
+ border-color: var(--l3-border);
+ color: var(--l1-foreground);
+ }
+
+ svg {
+ flex-shrink: 0;
+ color: var(--l3-foreground);
+ }
+
+ &:hover svg {
+ color: var(--accent-primary);
+ }
+}
diff --git a/frontend/src/container/AIAssistant/components/VirtualizedMessages/VirtualizedMessages.tsx b/frontend/src/container/AIAssistant/components/VirtualizedMessages/VirtualizedMessages.tsx
new file mode 100644
index 0000000000..47b5abbe85
--- /dev/null
+++ b/frontend/src/container/AIAssistant/components/VirtualizedMessages/VirtualizedMessages.tsx
@@ -0,0 +1,203 @@
+import { useCallback, useEffect, useRef } from 'react';
+import { Button } from '@signozhq/ui/button';
+import { Virtuoso, VirtuosoHandle } from 'react-virtuoso';
+import {
+ Activity,
+ TriangleAlert,
+ ChartBar,
+ Search,
+ Zap,
+ Sparkles,
+} from '@signozhq/icons';
+
+import { useAIAssistantStore } from '../../store/useAIAssistantStore';
+import { Message, StreamingEventItem } from '../../types';
+import MessageBubble from '../MessageBubble';
+import StreamingMessage from '../StreamingMessage';
+
+import styles from './VirtualizedMessages.module.scss';
+
+const SUGGESTIONS = [
+ {
+ icon: TriangleAlert,
+ text: 'Show me the top errors in the last hour',
+ },
+ {
+ icon: Activity,
+ text: 'What services have the highest latency?',
+ },
+ {
+ icon: ChartBar,
+ text: 'Give me an overview of system health',
+ },
+ {
+ icon: Search,
+ text: 'Find slow database queries',
+ },
+ {
+ icon: Zap,
+ text: 'Which endpoints have the most 5xx errors?',
+ },
+];
+
+const EMPTY_EVENTS: StreamingEventItem[] = [];
+
+interface VirtualizedMessagesProps {
+ conversationId: string;
+ messages: Message[];
+ isStreaming: boolean;
+}
+
+export default function VirtualizedMessages({
+ conversationId,
+ messages,
+ isStreaming,
+}: VirtualizedMessagesProps): JSX.Element {
+ const sendMessage = useAIAssistantStore((s) => s.sendMessage);
+ const regenerateAssistantMessage = useAIAssistantStore(
+ (s) => s.regenerateAssistantMessage,
+ );
+ const streamingStatus = useAIAssistantStore(
+ (s) => s.streams[conversationId]?.streamingStatus ?? '',
+ );
+ const streamingEvents = useAIAssistantStore(
+ (s) => s.streams[conversationId]?.streamingEvents ?? EMPTY_EVENTS,
+ );
+ // Text deltas append into the last `streamingEvents` entry rather than
+ // pushing a new one, so `streamingEvents.length` doesn't grow as the
+ // assistant streams text. Tracking the content length gives us a per-chunk
+ // scroll trigger.
+ const streamingContentLength = useAIAssistantStore(
+ (s) => s.streams[conversationId]?.streamingContent.length ?? 0,
+ );
+ const pendingApproval = useAIAssistantStore(
+ (s) => s.streams[conversationId]?.pendingApproval ?? null,
+ );
+ const pendingClarification = useAIAssistantStore(
+ (s) => s.streams[conversationId]?.pendingClarification ?? null,
+ );
+
+ const virtuosoRef = useRef<VirtuosoHandle>(null);
+ const scrollerRef = useRef<HTMLElement | Window | null>(null);
+
+ const handleRegenerate = useCallback(
+ (messageId: string): void => {
+ if (isStreaming) {
+ return;
+ }
+ void regenerateAssistantMessage(conversationId, messageId);
+ },
+ [conversationId, isStreaming, regenerateAssistantMessage],
+ );
+
+ // Scroll all the way to the actual bottom — including the 64px of bottom
+ // padding on the scroller — so the last bubble has visible breathing room
+ // above the disclaimer / input bar. Virtuoso's `scrollToIndex(LAST,
+ // align: 'end')` would only reach the last item's bottom and leave the
+ // padding hidden below the fold. Use `auto` while streaming so the bottom
+ // stays glued as text deltas arrive; `smooth` lags when triggered every
+ // few ms.
+ useEffect(() => {
+ const scroller = scrollerRef.current;
+ if (!(scroller instanceof HTMLElement)) {
+ return;
+ }
+ scroller.scrollTo({
+ top: scroller.scrollHeight,
+ behavior: isStreaming ? 'auto' : 'smooth',
+ });
+ }, [
+ messages.length,
+ streamingEvents.length,
+ streamingContentLength,
+ isStreaming,
+ pendingApproval,
+ pendingClarification,
+ ]);
+
+ const followOutput = useCallback(
+ (atBottom: boolean): false | 'auto' | 'smooth' => {
+ if (isStreaming) {
+ return 'auto';
+ }
+ return atBottom ? 'smooth' : false;
+ },
+ [isStreaming],
+ );
+
+ const showStreamingSlot =
+ isStreaming || Boolean(pendingApproval) || Boolean(pendingClarification);
+
+ if (messages.length === 0 && !showStreamingSlot) {
+ return (
+ <div className={styles.empty}>
+ <div className={styles.emptyIcon}>
+ <Sparkles size={24} color="var(--primary)" />
+ </div>
+ <h3 className={styles.emptyTitle}>SigNoz AI Assistant</h3>
+ <p className={styles.emptySubtitle}>
+ Ask questions about your traces, logs, metrics, and infrastructure.
+ </p>
+ <div className={styles.emptySuggestions}>
+ {SUGGESTIONS.map((s) => (
+ <Button
+ key={s.text}
+ variant="outlined"
+ color="secondary"
+ className={styles.emptyChip}
+ onClick={(): void => {
+ sendMessage(s.text);
+ }}
+ prefix={<s.icon size={14} />}
+ >
+ {s.text}
+ </Button>
+ ))}
+ </div>
+ </div>
+ );
+ }
+
+ const totalCount = messages.length + (showStreamingSlot ? 1 : 0);
+
+ return (
+ <Virtuoso
+ ref={virtuosoRef}
+ scrollerRef={(ref): void => {
+ scrollerRef.current = ref;
+ }}
+ className={styles.messages}
+ totalCount={totalCount}
+ followOutput={followOutput}
+ initialTopMostItemIndex={Math.max(0, totalCount - 1)}
+ itemContent={(index): JSX.Element => {
+ if (index < messages.length) {
+ const msg = messages[index];
+ const isLastAssistant =
+ msg.role === 'assistant' &&
+ messages.slice(index + 1).every((m) => m.role !== 'assistant');
+ return (
+ <MessageBubble
+ message={msg}
+ onRegenerate={
+ isLastAssistant && !showStreamingSlot
+ ? (): void => handleRegenerate(msg.id)
+ : undefined
+ }
+ isLastAssistant={isLastAssistant}
+ />
+ );
+ }
+ return (
+ <StreamingMessage
+ conversationId={conversationId}
+ events={streamingEvents}
+ status={streamingStatus}
+ pendingApproval={pendingApproval}
+ pendingClarification={pendingClarification}
+ />
+ );
+ }}
+ />
+ );
+}
diff --git a/frontend/src/container/AIAssistant/components/VirtualizedMessages/index.ts b/frontend/src/container/AIAssistant/components/VirtualizedMessages/index.ts
new file mode 100644
index 0000000000..8cdee03fc1
--- /dev/null
+++ b/frontend/src/container/AIAssistant/components/VirtualizedMessages/index.ts
@@ -0,0 +1,2 @@
+export * from './VirtualizedMessages';
+export { default } from './VirtualizedMessages';
diff --git a/frontend/src/container/AIAssistant/components/blocks/ActionBlock/ActionBlock.module.scss b/frontend/src/container/AIAssistant/components/blocks/ActionBlock/ActionBlock.module.scss
new file mode 100644
index 0000000000..c77d2bf51e
--- /dev/null
+++ b/frontend/src/container/AIAssistant/components/blocks/ActionBlock/ActionBlock.module.scss
@@ -0,0 +1,104 @@
+.header {
+ display: flex;
+ align-items: center;
+ gap: 5px;
+ margin-bottom: 6px;
+}
+
+.zapIcon {
+ color: var(--accent-amber);
+ flex-shrink: 0;
+}
+
+.headerLabel {
+ font-size: 11px;
+ font-weight: 600;
+ text-transform: uppercase;
+ letter-spacing: 0.05em;
+ color: var(--l2-foreground);
+}
+
+.description {
+ margin: 0 0 10px;
+ font-size: 13px;
+ color: var(--l1-foreground);
+ line-height: 1.5;
+}
+
+.params {
+ list-style: none;
+ margin: 0 0 10px;
+ padding: 0;
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+}
+
+.param {
+ display: flex;
+ gap: 6px;
+ font-size: 12px;
+ line-height: 1.4;
+}
+
+.paramKey {
+ color: var(--l3-foreground);
+ flex-shrink: 0;
+
+ &::after {
+ content: ':';
+ }
+}
+
+.paramVal {
+ color: var(--l1-foreground);
+ font-family: var(--font-mono, monospace);
+ word-break: break-all;
+}
+
+.actions {
+ display: flex;
+ gap: 8px;
+ flex-wrap: wrap;
+}
+
+.spinner {
+ animation: spin 0.8s linear infinite;
+}
+
+@keyframes spin {
+ to {
+ transform: rotate(360deg);
+ }
+}
+
+// Answered / terminal state container layout (composed with .block from Block.module.scss).
+.applied,
+.dismissed,
+.loading,
+.error {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ padding: 6px 10px;
+ opacity: 0.8;
+}
+
+.statusIcon {
+ flex-shrink: 0;
+
+ &.ok {
+ color: var(--accent-forest);
+ }
+ &.no {
+ color: var(--l3-foreground);
+ }
+ &.err {
+ color: var(--accent-cherry);
+ }
+}
+
+.statusText {
+ font-size: 13px;
+ color: var(--l1-foreground);
+}
diff --git a/frontend/src/container/AIAssistant/components/blocks/ActionBlock/ActionBlock.tsx b/frontend/src/container/AIAssistant/components/blocks/ActionBlock/ActionBlock.tsx
new file mode 100644
index 0000000000..220d3e9e29
--- /dev/null
+++ b/frontend/src/container/AIAssistant/components/blocks/ActionBlock/ActionBlock.tsx
@@ -0,0 +1,203 @@
+import { useEffect, useRef, useState } from 'react';
+import cx from 'classnames';
+import { Button } from '@signozhq/ui/button';
+import { Check, LoaderCircle, TriangleAlert, X, Zap } from '@signozhq/icons';
+
+import { PageActionRegistry } from '../../../pageActions/PageActionRegistry';
+import { AIActionBlock } from '../../../pageActions/types';
+import { useAIAssistantStore } from '../../../store/useAIAssistantStore';
+import { useMessageContext } from '../../MessageContext';
+
+import blockStyles from '../Block.module.scss';
+import styles from './ActionBlock.module.scss';
+
+type BlockState = 'pending' | 'loading' | 'applied' | 'dismissed' | 'error';
+
+/**
+ * Renders an AI-suggested page action.
+ *
+ * Two modes based on the registered PageAction.autoApply flag:
+ *
+ * autoApply = false (default)
+ * Shows a confirmation card with Accept / Dismiss. The user must
+ * explicitly approve before execute() is called. Use for destructive or
+ * hard-to-reverse actions (create dashboard, delete alert, etc.).
+ *
+ * autoApply = true
+ * Executes immediately on mount — no card shown, just the result summary.
+ * Use for low-risk, reversible actions where the user explicitly asked for
+ * the change (e.g. "filter logs for errors"). Avoids unnecessary friction.
+ *
+ * Persists answered state via answeredBlocks so re-mounts don't reset UI.
+ */
+export default function ActionBlock({
+ data,
+}: {
+ data: AIActionBlock;
+}): JSX.Element {
+ const { messageId } = useMessageContext();
+ const answeredBlocks = useAIAssistantStore((s) => s.answeredBlocks);
+ const markBlockAnswered = useAIAssistantStore((s) => s.markBlockAnswered);
+
+ const [localState, setLocalState] = useState<BlockState>(() => {
+ if (!messageId) {
+ return 'pending';
+ }
+ const saved = answeredBlocks[messageId];
+ if (!saved) {
+ return 'pending';
+ }
+ if (saved === 'dismissed') {
+ return 'dismissed';
+ }
+ if (saved.startsWith('error:')) {
+ return 'error';
+ }
+ return 'applied';
+ });
+ const [resultSummary, setResultSummary] = useState<string>('');
+ const [errorMessage, setErrorMessage] = useState<string>('');
+
+ const { actionId, description, parameters } = data;
+
+ // ── Shared execute logic ─────────────────────────────────────────────────────
+
+ const execute = async (): Promise<void> => {
+ const action = PageActionRegistry.get(actionId);
+
+ if (!action) {
+ const msg = `Action "${actionId}" is not available on the current page.`;
+ setErrorMessage(msg);
+ setLocalState('error');
+ if (messageId) {
+ markBlockAnswered(messageId, `error:${msg}`);
+ }
+ return;
+ }
+
+ setLocalState('loading');
+
+ try {
+ const result = await action.execute(parameters as never);
+ setResultSummary(result.summary);
+ setLocalState('applied');
+ if (messageId) {
+ markBlockAnswered(messageId, `applied:${result.summary}`);
+ }
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : 'Unknown error';
+ setErrorMessage(msg);
+ setLocalState('error');
+ if (messageId) {
+ markBlockAnswered(messageId, `error:${msg}`);
+ }
+ }
+ };
+
+ // ── Auto-apply: fire immediately on mount if the action opts in ──────────────
+
+ const autoApplyFired = useRef(false);
+
+ useEffect(() => {
+ // Only auto-apply once, and only when the block hasn't been answered yet
+ // (i.e. this is a fresh render, not a remount of an already-answered block).
+ if (autoApplyFired.current || localState !== 'pending') {
+ return;
+ }
+
+ const action = PageActionRegistry.get(actionId);
+ if (!action?.autoApply) {
+ return;
+ }
+
+ autoApplyFired.current = true;
+ execute();
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
+ const handleDismiss = (): void => {
+ setLocalState('dismissed');
+ if (messageId) {
+ markBlockAnswered(messageId, 'dismissed');
+ }
+ };
+
+ // ── Terminal states ──────────────────────────────────────────────────────────
+
+ if (localState === 'applied') {
+ return (
+ <div className={cx(blockStyles.block, styles.applied)}>
+ <Check size={13} className={cx(styles.statusIcon, styles.ok)} />
+ <span className={styles.statusText}>{resultSummary || 'Applied.'}</span>
+ </div>
+ );
+ }
+
+ if (localState === 'dismissed') {
+ return (
+ <div className={cx(blockStyles.block, styles.dismissed)}>
+ <X size={13} className={cx(styles.statusIcon, styles.no)} />
+ <span className={styles.statusText}>Dismissed.</span>
+ </div>
+ );
+ }
+
+ if (localState === 'error') {
+ return (
+ <div className={cx(blockStyles.block, styles.error)}>
+ <TriangleAlert size={13} className={cx(styles.statusIcon, styles.err)} />
+ <span className={styles.statusText}>{errorMessage}</span>
+ </div>
+ );
+ }
+
+ // ── Loading (autoApply in progress) ─────────────────────────────────────────
+
+ if (localState === 'loading') {
+ return (
+ <div className={cx(blockStyles.block, styles.loading)}>
+ <LoaderCircle size={13} className={cx(styles.spinner, styles.statusIcon)} />
+ <span className={styles.statusText}>{description}</span>
+ </div>
+ );
+ }
+
+ // ── Pending: manual confirmation card ────────────────────────────────────────
+
+ const paramEntries = Object.entries(parameters ?? {});
+
+ return (
+ <div className={blockStyles.block}>
+ <div className={styles.header}>
+ <Zap size={13} className={styles.zapIcon} />
+ <span className={styles.headerLabel}>Suggested Action</span>
+ </div>
+
+ <p className={styles.description}>{description}</p>
+
+ {paramEntries.length > 0 && (
+ <ul className={styles.params}>
+ {paramEntries.map(([key, val]) => (
+ <li key={key} className={styles.param}>
+ <span className={styles.paramKey}>{key}</span>
+ <span className={styles.paramVal}>
+ {typeof val === 'object' ? JSON.stringify(val) : String(val)}
+ </span>
+ </li>
+ ))}
+ </ul>
+ )}
+
+ <div className={styles.actions}>
+ <Button variant="solid" size="sm" onClick={execute}>
+ <Check size={12} />
+ Apply
+ </Button>
+ <Button variant="outlined" size="sm" onClick={handleDismiss}>
+ <X size={12} />
+ Dismiss
+ </Button>
+ </div>
+ </div>
+ );
+}
diff --git a/frontend/src/container/AIAssistant/components/blocks/ActionBlock/index.ts b/frontend/src/container/AIAssistant/components/blocks/ActionBlock/index.ts
new file mode 100644
index 0000000000..1cf1544b03
--- /dev/null
+++ b/frontend/src/container/AIAssistant/components/blocks/ActionBlock/index.ts
@@ -0,0 +1,2 @@
+export * from './ActionBlock';
+export { default } from './ActionBlock';
diff --git a/frontend/src/container/AIAssistant/components/blocks/Block.module.scss b/frontend/src/container/AIAssistant/components/blocks/Block.module.scss
new file mode 100644
index 0000000000..d6534a479b
--- /dev/null
+++ b/frontend/src/container/AIAssistant/components/blocks/Block.module.scss
@@ -0,0 +1,35 @@
+.block {
+ background: var(--l2-background);
+ border: 1px solid var(--l2-border);
+ border-radius: var(--radius-2);
+ padding: 12px 14px;
+ margin: 8px 0;
+
+ &:first-child {
+ margin-top: 0;
+ }
+ &:last-child {
+ margin-bottom: 0;
+ }
+}
+
+.title {
+ margin: 0 0 12px;
+ font-size: 11px;
+ font-weight: 600;
+ text-transform: uppercase;
+ letter-spacing: 0.05em;
+ color: var(--l2-foreground);
+}
+
+.unit {
+ font-weight: 400;
+ text-transform: none;
+ letter-spacing: 0;
+}
+
+.empty {
+ margin: 0;
+ font-size: 12px;
+ color: var(--l3-foreground);
+}
diff --git a/frontend/src/container/AIAssistant/components/blocks/BlockRegistry.ts b/frontend/src/container/AIAssistant/components/blocks/BlockRegistry.ts
new file mode 100644
index 0000000000..d7a7edca5c
--- /dev/null
+++ b/frontend/src/container/AIAssistant/components/blocks/BlockRegistry.ts
@@ -0,0 +1,36 @@
+import React from 'react';
+
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+export type BlockComponent<T = any> = React.ComponentType<{ data: T }>;
+
+/**
+ * Global registry for AI response block renderers.
+ *
+ * Any part of the application can register a custom block type:
+ *
+ * import { BlockRegistry } from 'container/AIAssistant/components/blocks';
+ * BlockRegistry.register('my-panel', MyPanelComponent);
+ *
+ * The AI can then emit fenced code blocks with the prefix `ai-<type>` and a
+ * JSON payload, and the registered component will be rendered in-place:
+ *
+ * ```ai-my-panel
+ * { "foo": "bar" }
+ * ```
+ */
+const _registry = new Map<string, BlockComponent>();
+
+export const BlockRegistry = {
+ register<T>(type: string, component: BlockComponent<T>): void {
+ _registry.set(type, component as BlockComponent);
+ },
+
+ get(type: string): BlockComponent | undefined {
+ return _registry.get(type);
+ },
+
+ /** Returns all registered type names (useful for debugging). */
+ types(): string[] {
+ return Array.from(_registry.keys());
+ },
+};
diff --git a/frontend/src/container/AIAssistant/components/blocks/ConfirmBlock/ConfirmBlock.module.scss b/frontend/src/container/AIAssistant/components/blocks/ConfirmBlock/ConfirmBlock.module.scss
new file mode 100644
index 0000000000..0ee7df58ee
--- /dev/null
+++ b/frontend/src/container/AIAssistant/components/blocks/ConfirmBlock/ConfirmBlock.module.scss
@@ -0,0 +1,36 @@
+.message {
+ margin: 0 0 10px;
+ font-size: 13px;
+ color: var(--l1-foreground);
+ line-height: 1.5;
+}
+
+.actions {
+ display: flex;
+ gap: 8px;
+ flex-wrap: wrap;
+}
+
+.answered {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ padding: 6px 10px;
+ opacity: 0.7;
+}
+
+.icon {
+ flex-shrink: 0;
+
+ &.ok {
+ color: var(--accent-forest);
+ }
+ &.no {
+ color: var(--accent-cherry);
+ }
+}
+
+.answerText {
+ font-size: 13px;
+ color: var(--l1-foreground);
+}
diff --git a/frontend/src/container/AIAssistant/components/blocks/ConfirmBlock/ConfirmBlock.tsx b/frontend/src/container/AIAssistant/components/blocks/ConfirmBlock/ConfirmBlock.tsx
new file mode 100644
index 0000000000..edd02098ca
--- /dev/null
+++ b/frontend/src/container/AIAssistant/components/blocks/ConfirmBlock/ConfirmBlock.tsx
@@ -0,0 +1,89 @@
+import cx from 'classnames';
+import { Button } from '@signozhq/ui/button';
+import { Check, X } from '@signozhq/icons';
+
+import { useAIAssistantStore } from '../../../store/useAIAssistantStore';
+import { useMessageContext } from '../../MessageContext';
+
+import blockStyles from '../Block.module.scss';
+import styles from './ConfirmBlock.module.scss';
+
+export interface ConfirmData {
+ message?: string;
+ /** Text sent back when accepted. Defaults to "Yes, proceed." */
+ acceptText?: string;
+ /** Text sent back when rejected. Defaults to "No, cancel." */
+ rejectText?: string;
+ /** Label shown on Accept button. Defaults to "Accept" */
+ acceptLabel?: string;
+ /** Label shown on Reject button. Defaults to "Reject" */
+ rejectLabel?: string;
+}
+
+export default function ConfirmBlock({
+ data,
+}: {
+ data: ConfirmData;
+}): JSX.Element {
+ const {
+ message,
+ acceptText = 'Yes, proceed.',
+ rejectText = 'No, cancel.',
+ acceptLabel = 'Accept',
+ rejectLabel = 'Reject',
+ } = data;
+
+ const { messageId } = useMessageContext();
+ const answeredBlocks = useAIAssistantStore((s) => s.answeredBlocks);
+ const markBlockAnswered = useAIAssistantStore((s) => s.markBlockAnswered);
+ const sendMessage = useAIAssistantStore((s) => s.sendMessage);
+
+ // Durable answered state — survives re-renders/remounts
+ const answeredChoice = messageId ? answeredBlocks[messageId] : undefined;
+ const isAnswered = answeredChoice !== undefined;
+
+ const handle = (choice: 'accepted' | 'rejected'): void => {
+ const responseText = choice === 'accepted' ? acceptText : rejectText;
+ if (messageId) {
+ markBlockAnswered(messageId, choice);
+ }
+ sendMessage(responseText);
+ };
+
+ if (isAnswered) {
+ const wasAccepted = answeredChoice === 'accepted';
+ const icon = wasAccepted ? (
+ <Check size={13} className={cx(styles.icon, styles.ok)} />
+ ) : (
+ <X size={13} className={cx(styles.icon, styles.no)} />
+ );
+ return (
+ <div className={cx(blockStyles.block, styles.answered)}>
+ {icon}
+ <span className={styles.answerText}>
+ {wasAccepted ? acceptText : rejectText}
+ </span>
+ </div>
+ );
+ }
+
+ return (
+ <div className={blockStyles.block}>
+ {message && <p className={styles.message}>{message}</p>}
+ <div className={styles.actions}>
+ <Button variant="solid" size="sm" onClick={(): void => handle('accepted')}>
+ <Check size={12} />
+ {acceptLabel}
+ </Button>
+ <Button
+ variant="outlined"
+ size="sm"
+ onClick={(): void => handle('rejected')}
+ >
+ <X size={12} />
+ {rejectLabel}
+ </Button>
+ </div>
+ </div>
+ );
+}
diff --git a/frontend/src/container/AIAssistant/components/blocks/ConfirmBlock/index.ts b/frontend/src/container/AIAssistant/components/blocks/ConfirmBlock/index.ts
new file mode 100644
index 0000000000..70a0ba23fd
--- /dev/null
+++ b/frontend/src/container/AIAssistant/components/blocks/ConfirmBlock/index.ts
@@ -0,0 +1,2 @@
+export * from './ConfirmBlock';
+export { default } from './ConfirmBlock';
diff --git a/frontend/src/container/AIAssistant/components/blocks/InteractiveQuestion/InteractiveQuestion.module.scss b/frontend/src/container/AIAssistant/components/blocks/InteractiveQuestion/InteractiveQuestion.module.scss
new file mode 100644
index 0000000000..5e3a1916e3
--- /dev/null
+++ b/frontend/src/container/AIAssistant/components/blocks/InteractiveQuestion/InteractiveQuestion.module.scss
@@ -0,0 +1,43 @@
+.options {
+ // Antd Radio.Group / Checkbox.Group renders inline-block by default.
+ // Override so the className we apply fills the block and stacks options vertically.
+ display: flex !important;
+ flex-direction: column !important;
+ gap: 6px;
+ width: 100%;
+
+ &.checkbox {
+ margin-bottom: 10px;
+ }
+}
+
+.option {
+ color: var(--l1-foreground) !important;
+ font-size: 13px !important;
+ white-space: normal !important;
+ word-break: break-word;
+ display: flex !important;
+ align-items: flex-start !important;
+}
+
+.submit {
+ margin-top: 2px;
+}
+
+.answered {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ padding: 8px 12px;
+ opacity: 0.7;
+}
+
+.check {
+ color: var(--accent-forest);
+ font-size: 13px;
+}
+
+.answerText {
+ font-size: 13px;
+ color: var(--l1-foreground);
+}
diff --git a/frontend/src/container/AIAssistant/components/blocks/InteractiveQuestion/InteractiveQuestion.tsx b/frontend/src/container/AIAssistant/components/blocks/InteractiveQuestion/InteractiveQuestion.tsx
new file mode 100644
index 0000000000..cbfd6bf5b0
--- /dev/null
+++ b/frontend/src/container/AIAssistant/components/blocks/InteractiveQuestion/InteractiveQuestion.tsx
@@ -0,0 +1,110 @@
+import { useState } from 'react';
+import cx from 'classnames';
+import { Button } from '@signozhq/ui/button';
+import { Checkbox, Radio } from 'antd';
+
+import { useAIAssistantStore } from '../../../store/useAIAssistantStore';
+import { useMessageContext } from '../../MessageContext';
+
+import blockStyles from '../Block.module.scss';
+import styles from './InteractiveQuestion.module.scss';
+
+interface Option {
+ value: string;
+ label: string;
+}
+
+export interface QuestionData {
+ question?: string;
+ type?: 'radio' | 'checkbox';
+ options: (string | Option)[];
+}
+
+function normalizeOption(opt: string | Option): Option {
+ return typeof opt === 'string' ? { value: opt, label: opt } : opt;
+}
+
+export default function InteractiveQuestion({
+ data,
+}: {
+ data: QuestionData;
+}): JSX.Element {
+ const { question, type = 'radio', options } = data;
+ const normalized = options.map(normalizeOption);
+
+ const { messageId } = useMessageContext();
+ const answeredBlocks = useAIAssistantStore((s) => s.answeredBlocks);
+ const markBlockAnswered = useAIAssistantStore((s) => s.markBlockAnswered);
+ const sendMessage = useAIAssistantStore((s) => s.sendMessage);
+
+ // Persist selected state locally only for the pending (not-yet-submitted) case
+ const [selected, setSelected] = useState<string[]>([]);
+
+ // Durable answered state from the store — survives re-renders/remounts
+ const answeredText = messageId ? answeredBlocks[messageId] : undefined;
+ const isAnswered = answeredText !== undefined;
+
+ const handleSubmit = (values: string[]): void => {
+ if (values.length === 0) {
+ return;
+ }
+ const answer = values.join(', ');
+ if (messageId) {
+ markBlockAnswered(messageId, answer);
+ }
+ sendMessage(answer);
+ };
+
+ if (isAnswered) {
+ return (
+ <div className={cx(blockStyles.block, styles.answered)}>
+ <span className={styles.check}>✓</span>
+ <span className={styles.answerText}>{answeredText}</span>
+ </div>
+ );
+ }
+
+ return (
+ <div className={blockStyles.block}>
+ {question && <p className={blockStyles.title}>{question}</p>}
+
+ {type === 'radio' ? (
+ <Radio.Group
+ className={styles.options}
+ onChange={(e): void => {
+ setSelected([e.target.value]);
+ handleSubmit([e.target.value]);
+ }}
+ >
+ {normalized.map((opt) => (
+ <Radio key={opt.value} value={opt.value} className={styles.option}>
+ {opt.label}
+ </Radio>
+ ))}
+ </Radio.Group>
+ ) : (
+ <>
+ <Checkbox.Group
+ className={cx(styles.options, styles.checkbox)}
+ onChange={(vals): void => setSelected(vals as string[])}
+ >
+ {normalized.map((opt) => (
+ <Checkbox key={opt.value} value={opt.value} className={styles.option}>
+ {opt.label}
+ </Checkbox>
+ ))}
+ </Checkbox.Group>
+ <Button
+ variant="solid"
+ size="sm"
+ className={styles.submit}
+ disabled={selected.length === 0}
+ onClick={(): void => handleSubmit(selected)}
+ >
+ Confirm
+ </Button>
+ </>
+ )}
+ </div>
+ );
+}
diff --git a/frontend/src/container/AIAssistant/components/blocks/InteractiveQuestion/index.ts b/frontend/src/container/AIAssistant/components/blocks/InteractiveQuestion/index.ts
new file mode 100644
index 0000000000..86f1a248d6
--- /dev/null
+++ b/frontend/src/container/AIAssistant/components/blocks/InteractiveQuestion/index.ts
@@ -0,0 +1,2 @@
+export * from './InteractiveQuestion';
+export { default } from './InteractiveQuestion';
diff --git a/frontend/src/container/AIAssistant/components/blocks/RichCodeBlock/RichCodeBlock.module.scss b/frontend/src/container/AIAssistant/components/blocks/RichCodeBlock/RichCodeBlock.module.scss
new file mode 100644
index 0000000000..b8b0c15401
--- /dev/null
+++ b/frontend/src/container/AIAssistant/components/blocks/RichCodeBlock/RichCodeBlock.module.scss
@@ -0,0 +1,33 @@
+@use '../../../_scrollbar' as *;
+
+.codeBlock {
+ position: relative;
+ background: var(--l3-background);
+ border: 1px solid color-mix(in srgb, var(--l1-foreground) 8%, transparent);
+ border-radius: 4px;
+ overflow: hidden;
+ margin: 8px 0;
+
+ // Themed horizontal scrollbar for long lines — uses the same slate
+ // tokens as the rest of the AI Assistant chrome and stays hidden until
+ // hover to keep the block visually quiet at rest.
+ pre {
+ @include scrollbar();
+ }
+}
+
+.copyBtn {
+ position: absolute;
+ top: 6px;
+ right: 6px;
+ z-index: 1;
+ opacity: 0;
+ transition: opacity 0.15s ease;
+}
+
+// Reveal on hover or when the button itself takes focus, so the affordance
+// stays out of the way during normal reading.
+.codeBlock:hover .copyBtn,
+.codeBlock:focus-within .copyBtn {
+ opacity: 1;
+}
diff --git a/frontend/src/container/AIAssistant/components/blocks/RichCodeBlock/RichCodeBlock.tsx b/frontend/src/container/AIAssistant/components/blocks/RichCodeBlock/RichCodeBlock.tsx
new file mode 100644
index 0000000000..314b371707
--- /dev/null
+++ b/frontend/src/container/AIAssistant/components/blocks/RichCodeBlock/RichCodeBlock.tsx
@@ -0,0 +1,141 @@
+import React, { useEffect, useRef, useState } from 'react';
+import { useCopyToClipboard } from 'react-use';
+import { Button } from '@signozhq/ui/button';
+import { Check, Copy } from '@signozhq/icons';
+import SyntaxHighlighter, {
+ a11yDark,
+ oneLight,
+} from 'components/MarkdownRenderer/syntaxHighlighter';
+import { useIsDarkMode } from 'hooks/useDarkMode';
+
+import { BlockRegistry } from '../BlockRegistry';
+
+import styles from './RichCodeBlock.module.scss';
+
+interface CodeProps {
+ className?: string;
+ children?: React.ReactNode;
+ // react-markdown passes `node` — accept and ignore it
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ node?: any;
+}
+
+/**
+ * Drop-in replacement for react-markdown's `code` renderer.
+ *
+ * - ```ai-<type>``` blocks resolve to a registered block component.
+ * - Other fenced blocks with a language tag get Prism syntax highlighting via
+ * the shared `react-syntax-highlighter` setup (a11y-dark theme). Languages
+ * outside the registered set fall through to plain text — same behaviour as
+ * the rest of the app.
+ * - Inline code (no `language-X` class) stays as a bare <code>.
+ *
+ * The wrapping <pre> that react-markdown emits for fenced blocks is unwrapped
+ * by `SmartPre` whenever this returns something other than a literal <code>,
+ * so we don't end up with nested <pre><pre>.
+ */
+export default function RichCodeBlock({
+ className,
+ children,
+}: CodeProps): JSX.Element {
+ const lang = /language-(\S+)/.exec(className ?? '')?.[1];
+
+ if (lang?.startsWith('ai-')) {
+ const blockType = lang.slice(3); // strip the 'ai-' prefix
+ const BlockComp = BlockRegistry.get(blockType);
+
+ if (BlockComp) {
+ const raw = String(children ?? '').trim();
+ try {
+ const parsedData = JSON.parse(raw);
+ return <BlockComp data={parsedData} />;
+ } catch {
+ // Invalid JSON — fall through and render as a code block
+ }
+ }
+ }
+
+ return <FencedCode lang={lang}>{children}</FencedCode>;
+}
+
+interface FencedCodeProps {
+ lang: string | undefined;
+ children: React.ReactNode;
+ className?: string;
+}
+
+function FencedCode({
+ lang,
+ children,
+ className,
+}: FencedCodeProps): JSX.Element {
+ const isDark = useIsDarkMode();
+
+ if (!lang) {
+ return <code className={className}>{children}</code>;
+ }
+
+ const code = String(children ?? '').replace(/\n$/, '');
+ return (
+ <div className={styles.codeBlock}>
+ <CopyButton text={code} />
+ <SyntaxHighlighter
+ language={lang}
+ // Theme tokens (foreground colors for keywords, strings, etc.)
+ // flip with the app theme so they remain readable.
+ style={isDark ? a11yDark : oneLight}
+ // Defer the background to our theme tokens via SCSS so the block
+ // blends with the surrounding chat surface in both modes; also
+ // trim the default padding (Prism themes ship with 1em).
+ customStyle={{
+ margin: 0,
+ padding: 0,
+ background: 'transparent',
+ fontSize: '12px',
+ }}
+ >
+ {code}
+ </SyntaxHighlighter>
+ </div>
+ );
+}
+
+function CopyButton({ text }: { text: string }): JSX.Element {
+ const [copied, setCopied] = useState(false);
+ const [, copyToClipboard] = useCopyToClipboard();
+ // Track the timeout so a rapid re-click resets the 1.5s window and an
+ // unmount mid-flight doesn't try to setState on a dead component.
+ const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+
+ useEffect(
+ () => (): void => {
+ if (timeoutRef.current) {
+ clearTimeout(timeoutRef.current);
+ }
+ },
+ [],
+ );
+
+ const handleCopy = (): void => {
+ copyToClipboard(text);
+ setCopied(true);
+ if (timeoutRef.current) {
+ clearTimeout(timeoutRef.current);
+ }
+ timeoutRef.current = setTimeout(() => setCopied(false), 1500);
+ };
+
+ return (
+ <Button
+ variant="ghost"
+ size="sm"
+ color="secondary"
+ className={styles.copyBtn}
+ onClick={handleCopy}
+ title={copied ? 'Copied' : 'Copy code'}
+ aria-label={copied ? 'Copied' : 'Copy code'}
+ >
+ {copied ? <Check size={12} /> : <Copy size={12} />}
+ </Button>
+ );
+}
diff --git a/frontend/src/container/AIAssistant/components/blocks/RichCodeBlock/index.ts b/frontend/src/container/AIAssistant/components/blocks/RichCodeBlock/index.ts
new file mode 100644
index 0000000000..394e15177e
--- /dev/null
+++ b/frontend/src/container/AIAssistant/components/blocks/RichCodeBlock/index.ts
@@ -0,0 +1,2 @@
+export * from './RichCodeBlock';
+export { default } from './RichCodeBlock';
diff --git a/frontend/src/container/AIAssistant/components/blocks/index.ts b/frontend/src/container/AIAssistant/components/blocks/index.ts
new file mode 100644
index 0000000000..94220b2c26
--- /dev/null
+++ b/frontend/src/container/AIAssistant/components/blocks/index.ts
@@ -0,0 +1,27 @@
+/**
+ * AI response block system.
+ *
+ * Import this module once (e.g. in MessageBubble / StreamingMessage) to
+ * register all built-in block types. External modules can extend the registry
+ * at any time:
+ *
+ * import { BlockRegistry } from 'container/AIAssistant/components/blocks';
+ * BlockRegistry.register('my-panel', MyPanelComponent);
+ */
+
+import ActionBlock from './ActionBlock';
+import { BlockRegistry } from './BlockRegistry';
+import ConfirmBlock from './ConfirmBlock';
+import InteractiveQuestion from './InteractiveQuestion';
+
+// ─── Register built-in block types ───────────────────────────────────────────
+
+BlockRegistry.register('question', InteractiveQuestion);
+BlockRegistry.register('confirm', ConfirmBlock);
+// Page-aware action block
+BlockRegistry.register('action', ActionBlock);
+
+// ─── Public exports ───────────────────────────────────────────────────────────
+
+export { BlockRegistry } from './BlockRegistry';
+export { default as RichCodeBlock } from './RichCodeBlock';
diff --git a/frontend/src/container/AIAssistant/getAutoContexts.ts b/frontend/src/container/AIAssistant/getAutoContexts.ts
new file mode 100644
index 0000000000..97a4bd1512
--- /dev/null
+++ b/frontend/src/container/AIAssistant/getAutoContexts.ts
@@ -0,0 +1,333 @@
+import type { MessageContext } from 'api/ai-assistant/chat';
+import { QueryParams } from 'constants/query';
+import ROUTES from 'constants/routes';
+import { matchPath } from 'react-router-dom';
+
+/**
+ * Resolves the page the user is currently on into structured `MessageContext`
+ * entries with `source: 'auto'`. The agent uses these as implicit context
+ * (e.g. "the user is currently looking at dashboard X with this time range
+ * and this query").
+ *
+ * **URL-only.** All inputs come from `pathname` + `search`; we never reach
+ * into Redux / context. SigNoz already encodes most page state into the URL
+ * (`compositeQuery`, `startTime`/`endTime`, `viewName`/`viewKey`,
+ * `variables`, `expandedWidgetId`, `activeLogId`, …), so URL parsing is
+ * sufficient. Anything not in the URL is simply omitted from `metadata` —
+ * the server applies its own defaults.
+ *
+ * Returns `[]` when no mapping exists, so callers can spread the result
+ * unconditionally before user-picked contexts.
+ */
+// eslint-disable-next-line sonarjs/cognitive-complexity
+export function getAutoContexts(
+ pathname: string,
+ search: string,
+): MessageContext[] {
+ const params = new URLSearchParams(search);
+ const sharedMetadata = collectSharedMetadata(params);
+
+ // ── Dashboards ────────────────────────────────────────────────────────────
+
+ // Widget edit (panel_edit) — `/dashboard/:dashboardId/:widgetId`.
+ const widgetMatch = matchPath<{ dashboardId: string; widgetId: string }>(
+ pathname,
+ { path: ROUTES.DASHBOARD_WIDGET, exact: true },
+ );
+ if (widgetMatch) {
+ return [
+ {
+ source: 'auto',
+ type: 'dashboard',
+ resourceId: widgetMatch.params.dashboardId,
+ metadata: {
+ page: 'panel_edit',
+ widgetId: widgetMatch.params.widgetId,
+ ...sharedMetadata,
+ },
+ },
+ ];
+ }
+
+ // Dashboard detail — `/dashboard/:dashboardId`. The `expandedWidgetId`
+ // query param signals the panel-fullscreen overlay; otherwise it's the
+ // plain dashboard view.
+ const dashboardMatch = matchPath<{ dashboardId: string }>(pathname, {
+ path: ROUTES.DASHBOARD,
+ exact: true,
+ });
+ if (dashboardMatch) {
+ const expandedWidgetId = params.get(QueryParams.expandedWidgetId);
+ if (expandedWidgetId) {
+ return [
+ {
+ source: 'auto',
+ type: 'dashboard',
+ resourceId: dashboardMatch.params.dashboardId,
+ metadata: {
+ page: 'panel_fullscreen',
+ widgetId: expandedWidgetId,
+ ...sharedMetadata,
+ },
+ },
+ ];
+ }
+ return [
+ {
+ source: 'auto',
+ type: 'dashboard',
+ resourceId: dashboardMatch.params.dashboardId,
+ metadata: {
+ page: 'dashboard_detail',
+ ...sharedMetadata,
+ },
+ },
+ ];
+ }
+
+ // Dashboard list — `/dashboard`.
+ if (matchPath(pathname, { path: ROUTES.ALL_DASHBOARD, exact: true })) {
+ return [
+ {
+ source: 'auto',
+ type: 'dashboard',
+ resourceId: null,
+ metadata: { page: 'dashboard_list' },
+ },
+ ];
+ }
+
+ // ── Alerts ────────────────────────────────────────────────────────────────
+
+ // Alert edit — `/alerts/edit?ruleId=…`.
+ if (matchPath(pathname, { path: ROUTES.EDIT_ALERTS, exact: true })) {
+ const ruleId = params.get(QueryParams.ruleId);
+ if (ruleId) {
+ return [
+ {
+ source: 'auto',
+ type: 'alert',
+ resourceId: ruleId,
+ metadata: { page: 'alert_edit' },
+ },
+ ];
+ }
+ }
+
+ if (matchPath(pathname, { path: ROUTES.ALERTS_NEW, exact: true })) {
+ return [
+ {
+ source: 'auto',
+ type: 'alert',
+ resourceId: null,
+ metadata: { page: 'alert_new' },
+ },
+ ];
+ }
+
+ if (matchPath(pathname, { path: ROUTES.ALERT_HISTORY, exact: true })) {
+ return [
+ {
+ source: 'auto',
+ type: 'alert',
+ resourceId: null,
+ metadata: {
+ page: 'alerts_triggered',
+ ...sharedMetadata,
+ },
+ },
+ ];
+ }
+
+ if (matchPath(pathname, { path: ROUTES.LIST_ALL_ALERT, exact: true })) {
+ return [
+ {
+ source: 'auto',
+ type: 'alert',
+ resourceId: null,
+ metadata: { page: 'alert_list' },
+ },
+ ];
+ }
+
+ // ── Services ──────────────────────────────────────────────────────────────
+
+ // Service detail (covers sub-routes like top-level-operations) —
+ // `/services/:servicename[/...]`.
+ const serviceMatch = matchPath<{ servicename: string }>(pathname, {
+ path: ROUTES.SERVICE_METRICS,
+ exact: false,
+ });
+ if (serviceMatch?.params.servicename) {
+ return [
+ {
+ source: 'auto',
+ type: 'service',
+ resourceId: serviceMatch.params.servicename,
+ metadata: {
+ page: 'service_detail',
+ ...sharedMetadata,
+ },
+ },
+ ];
+ }
+
+ // Services list — `/services`.
+ if (matchPath(pathname, { path: ROUTES.APPLICATION, exact: true })) {
+ return [
+ {
+ source: 'auto',
+ type: 'service',
+ resourceId: null,
+ metadata: {
+ page: 'services_list',
+ ...sharedMetadata,
+ },
+ },
+ ];
+ }
+
+ // ── Logs ──────────────────────────────────────────────────────────────────
+
+ if (matchPath(pathname, { path: ROUTES.LOGS_EXPLORER, exact: false })) {
+ const activeLogId = params.get(QueryParams.activeLogId);
+ // `?activeLogId=…` indicates a log-detail panel is open. Per the
+ // schema, log_detail requires payload fields (timestamp, service,
+ // body) we can't recover from the URL alone, so we still emit the
+ // surrounding logs_explorer page context — the panel registry can
+ // layer richer log_detail context on top in a follow-up.
+ return [
+ {
+ source: 'auto',
+ type: 'logs_explorer',
+ resourceId: null,
+ metadata: {
+ page: 'logs_explorer',
+ ...sharedMetadata,
+ ...(activeLogId ? { activeLogId } : {}),
+ },
+ },
+ ];
+ }
+
+ // ── Traces ────────────────────────────────────────────────────────────────
+
+ // Trace detail — `/trace/:id`. Treated as a detail-as-metadata page
+ // (resourceId null, `traceId` lives in metadata).
+ const traceMatch = matchPath<{ id: string }>(pathname, {
+ path: ROUTES.TRACE_DETAIL,
+ exact: true,
+ });
+ if (traceMatch?.params.id) {
+ const spanId = params.get(QueryParams.selectedTimelineQuery);
+ return [
+ {
+ source: 'auto',
+ type: 'traces_explorer',
+ resourceId: null,
+ metadata: {
+ page: 'trace_detail',
+ traceId: traceMatch.params.id,
+ ...(spanId ? { spanId } : {}),
+ ...sharedMetadata,
+ },
+ },
+ ];
+ }
+
+ if (matchPath(pathname, { path: ROUTES.TRACES_EXPLORER, exact: false })) {
+ return [
+ {
+ source: 'auto',
+ type: 'traces_explorer',
+ resourceId: null,
+ metadata: {
+ page: 'traces_explorer',
+ ...sharedMetadata,
+ },
+ },
+ ];
+ }
+
+ // ── Metrics ───────────────────────────────────────────────────────────────
+
+ if (
+ matchPath(pathname, { path: ROUTES.METRICS_EXPLORER_EXPLORER, exact: false })
+ ) {
+ return [
+ {
+ source: 'auto',
+ type: 'metrics_explorer',
+ resourceId: null,
+ metadata: {
+ page: 'metrics_explorer',
+ ...sharedMetadata,
+ },
+ },
+ ];
+ }
+
+ return [];
+}
+
+/**
+ * Pulls metadata fields that any page may carry in its query string —
+ * `timeRange`, `query`, saved-view selectors, dashboard variables. Each
+ * piece is omitted when the URL doesn't carry it (rather than being filled
+ * in with a stale default).
+ */
+function collectSharedMetadata(
+ params: URLSearchParams,
+): Record<string, unknown> {
+ const out: Record<string, unknown> = {};
+
+ // Time range — emit only when both bounds are explicit. SigNoz writes
+ // `startTime` / `endTime` in milliseconds when the user picks a custom
+ // range; relative ranges (`relativeTime=15m`) are left out because the
+ // server applies its own freshly-anchored window.
+ const startTime = numericParam(params, QueryParams.startTime);
+ const endTime = numericParam(params, QueryParams.endTime);
+ if (startTime !== null && endTime !== null) {
+ out.timeRange = { start: startTime, end: endTime };
+ }
+
+ // Query Builder state — URL-encoded JSON written by `QueryBuilderProvider`.
+ const compositeQueryRaw = params.get(QueryParams.compositeQuery);
+ if (compositeQueryRaw) {
+ try {
+ out.query = JSON.parse(decodeURIComponent(compositeQueryRaw));
+ } catch {
+ // Malformed JSON in the URL — drop silently rather than throw
+ // inside a context-collection helper.
+ }
+ }
+
+ // Saved view selectors (logs / traces explorer) and dashboard variables.
+ const viewKey = params.get(QueryParams.viewKey);
+ if (viewKey) {
+ out.savedViewId = viewKey;
+ }
+ const viewName = params.get(QueryParams.viewName);
+ if (viewName) {
+ out.savedViewName = viewName;
+ }
+ const variablesRaw = params.get(QueryParams.variables);
+ if (variablesRaw) {
+ try {
+ out.variables = JSON.parse(decodeURIComponent(variablesRaw));
+ } catch {
+ // Same fallback as compositeQuery — keep silent on malformed JSON.
+ }
+ }
+
+ return out;
+}
+
+function numericParam(params: URLSearchParams, key: string): number | null {
+ const raw = params.get(key);
+ if (raw === null) {
+ return null;
+ }
+ const value = Number(raw);
+ return Number.isFinite(value) ? value : null;
+}
diff --git a/frontend/src/container/AIAssistant/hooks/useSpeechRecognition.ts b/frontend/src/container/AIAssistant/hooks/useSpeechRecognition.ts
new file mode 100644
index 0000000000..e6562861de
--- /dev/null
+++ b/frontend/src/container/AIAssistant/hooks/useSpeechRecognition.ts
@@ -0,0 +1,250 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+
+// ── Web Speech API types (not yet in lib.dom.d.ts) ────────────────────────────
+
+interface SpeechRecognitionResult {
+ readonly length: number;
+ readonly isFinal: boolean;
+ [index: number]: { transcript: string; confidence: number };
+}
+
+interface SpeechRecognitionResultList {
+ readonly length: number;
+ [index: number]: SpeechRecognitionResult;
+}
+
+interface SpeechRecognitionEvent extends Event {
+ readonly resultIndex: number;
+ readonly results: SpeechRecognitionResultList;
+}
+
+interface SpeechRecognitionErrorEvent extends Event {
+ readonly error: string;
+ readonly message: string;
+}
+
+interface ISpeechRecognition extends EventTarget {
+ lang: string;
+ continuous: boolean;
+ interimResults: boolean;
+ onstart: (() => void) | null;
+ onend: (() => void) | null;
+ onresult: ((event: SpeechRecognitionEvent) => void) | null;
+ onerror: ((event: SpeechRecognitionErrorEvent) => void) | null;
+ start(): void;
+ stop(): void;
+ abort(): void;
+}
+
+type SpeechRecognitionConstructor = new () => ISpeechRecognition;
+
+// ── Vendor-prefix shim for Safari / older browsers ────────────────────────────
+
+const SpeechRecognitionAPI: SpeechRecognitionConstructor | null =
+ typeof window !== 'undefined'
+ ? // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ ((window as any).SpeechRecognition ??
+ (window as any).webkitSpeechRecognition ??
+ null)
+ : null;
+
+export type SpeechRecognitionError =
+ | 'not-supported'
+ | 'not-allowed'
+ | 'no-speech'
+ | 'network'
+ | 'unknown';
+
+export type MicrophonePermission = 'prompt' | 'granted' | 'denied';
+
+interface UseSpeechRecognitionOptions {
+ onError?: (error: SpeechRecognitionError) => void;
+ /**
+ * Called directly from browser recognition events — no React state intermediary.
+ * `isFinal=false` → interim (live preview), `isFinal=true` → committed text.
+ */
+ onTranscript?: (text: string, isFinal: boolean) => void;
+ lang?: string;
+}
+
+interface UseSpeechRecognitionReturn {
+ isListening: boolean;
+ isSupported: boolean;
+ /**
+ * Browser microphone permission. Starts as `'prompt'` (or whatever the
+ * Permissions API reports on mount), flips to `'granted'` once a session
+ * successfully starts, and to `'denied'` if the user blocks access.
+ */
+ permission: MicrophonePermission;
+ start: () => void;
+ stop: () => void;
+ /** Stop recognition and discard any pending interim text (no onTranscript call). */
+ discard: () => void;
+}
+
+export function useSpeechRecognition({
+ onError,
+ onTranscript,
+ lang = 'en-US',
+}: UseSpeechRecognitionOptions = {}): UseSpeechRecognitionReturn {
+ const [isListening, setIsListening] = useState(false);
+ const [permission, setPermission] = useState<MicrophonePermission>('prompt');
+ const recognitionRef = useRef<ISpeechRecognition | null>(null);
+ const isDiscardingRef = useRef(false);
+ const isSupported = SpeechRecognitionAPI !== null;
+
+ // Seed `permission` from the Permissions API and keep it in sync with
+ // external changes (e.g. user resets the site permission in browser
+ // settings). Falls back silently if the API is unavailable (Safari) —
+ // the recognition lifecycle below will still flip the state on grant
+ // or deny.
+ useEffect(() => {
+ if (typeof navigator === 'undefined' || !navigator.permissions?.query) {
+ return undefined;
+ }
+ let status: PermissionStatus | null = null;
+ let cancelled = false;
+ const handleChange = (): void => {
+ if (status) {
+ setPermission(status.state as MicrophonePermission);
+ }
+ };
+ navigator.permissions
+ .query({ name: 'microphone' as PermissionName })
+ .then((permStatus) => {
+ if (cancelled) {
+ return;
+ }
+ status = permStatus;
+ setPermission(permStatus.state as MicrophonePermission);
+ permStatus.addEventListener('change', handleChange);
+ })
+ .catch(() => {
+ // Permissions API rejected (some browsers don't recognise the
+ // 'microphone' descriptor) — leave permission as 'prompt'.
+ });
+ return (): void => {
+ cancelled = true;
+ status?.removeEventListener('change', handleChange);
+ };
+ }, []);
+
+ // Always-current refs — updated synchronously on every render so closures
+ // inside recognition event handlers always call the latest version.
+ const onErrorRef = useRef(onError);
+ onErrorRef.current = onError;
+
+ const onTranscriptRef = useRef(onTranscript);
+ onTranscriptRef.current = onTranscript;
+
+ const stop = useCallback(() => {
+ recognitionRef.current?.stop();
+ }, []);
+
+ const discard = useCallback(() => {
+ isDiscardingRef.current = true;
+ recognitionRef.current?.stop();
+ }, []);
+
+ // eslint-disable-next-line sonarjs/cognitive-complexity
+ const start = useCallback(() => {
+ if (!isSupported) {
+ onErrorRef.current?.('not-supported');
+ return;
+ }
+
+ // If already listening, stop
+ if (recognitionRef.current) {
+ recognitionRef.current.stop();
+ return;
+ }
+
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
+ const recognition = new SpeechRecognitionAPI!();
+ recognition.lang = lang;
+ recognition.continuous = true; // keep listening until user clicks stop
+ recognition.interimResults = true; // live updates while speaking
+
+ // Track the last interim text so we can commit it as final in onend —
+ // Chrome often skips the isFinal result when stop() is called manually.
+ let pendingInterim = '';
+
+ recognition.onstart = (): void => {
+ setIsListening(true);
+ setPermission('granted');
+ };
+
+ recognition.onresult = (event): void => {
+ // Browser fires a final `onresult` after `recognition.stop()` —
+ // when the caller invoked `discard()` (e.g. stop-and-send) the
+ // React state has already been cleared / the message has
+ // already been dispatched, so a late transcript would
+ // repopulate the textarea. Drop these events while discarding.
+ if (isDiscardingRef.current) {
+ pendingInterim = '';
+ return;
+ }
+
+ let interim = '';
+ let finalText = '';
+
+ for (let i = event.resultIndex; i < event.results.length; i++) {
+ const text = event.results[i][0].transcript;
+ if (event.results[i].isFinal) {
+ finalText += text;
+ } else {
+ interim += text;
+ }
+ }
+
+ if (finalText) {
+ pendingInterim = '';
+ onTranscriptRef.current?.(finalText, true);
+ } else if (interim) {
+ pendingInterim = interim;
+ onTranscriptRef.current?.(interim, false);
+ }
+ };
+
+ recognition.onerror = (event): void => {
+ pendingInterim = '';
+ let mapped: SpeechRecognitionError = 'unknown';
+ if (event.error === 'not-allowed' || event.error === 'service-not-allowed') {
+ mapped = 'not-allowed';
+ setPermission('denied');
+ } else if (event.error === 'no-speech') {
+ mapped = 'no-speech';
+ } else if (event.error === 'network') {
+ mapped = 'network';
+ }
+ onErrorRef.current?.(mapped);
+ };
+
+ recognition.onend = (): void => {
+ // Commit any interim text that never received a final result,
+ // unless the session was explicitly discarded.
+ if (!isDiscardingRef.current && pendingInterim) {
+ const committed = pendingInterim;
+ pendingInterim = '';
+ onTranscriptRef.current?.(committed, true);
+ }
+ isDiscardingRef.current = false;
+ pendingInterim = '';
+ setIsListening(false);
+ recognitionRef.current = null;
+ };
+
+ recognitionRef.current = recognition;
+ recognition.start();
+ }, [isSupported, lang]);
+
+ // Clean up on unmount
+ useEffect(
+ () => (): void => {
+ recognitionRef.current?.abort();
+ },
+ [],
+ );
+
+ return { isListening, isSupported, permission, start, stop, discard };
+}
diff --git a/frontend/src/container/AIAssistant/pageActions/PageActionRegistry.ts b/frontend/src/container/AIAssistant/pageActions/PageActionRegistry.ts
new file mode 100644
index 0000000000..e97fca99fd
--- /dev/null
+++ b/frontend/src/container/AIAssistant/pageActions/PageActionRegistry.ts
@@ -0,0 +1,62 @@
+import { PageAction, PageActionDescriptor } from './types';
+
+/**
+ * Module-level singleton (mirrors BlockRegistry) that maps action IDs to their
+ * PageAction descriptors. Pages register their actions on mount and unregister
+ * on unmount via `usePageActions`.
+ *
+ * Internal structure:
+ * _byPage: pageId → PageAction[] (for batch unregister)
+ * _byId: actionId → PageAction (O(1) lookup at execute time)
+ */
+
+// pageId → actions[]
+const _byPage = new Map<string, PageAction[]>();
+
+// actionId → action (flat, for O(1) lookup)
+const _byId = new Map<string, PageAction>();
+
+export const PageActionRegistry = {
+ /**
+ * Register a set of actions under a page scope key.
+ * Calling register() again with the same pageId replaces the previous set.
+ */
+ register(pageId: string, actions: PageAction[]): void {
+ // Remove any previously registered actions for this page
+ const prev = _byPage.get(pageId) ?? [];
+ prev.forEach((a) => _byId.delete(a.id));
+
+ _byPage.set(pageId, actions);
+ actions.forEach((a) => _byId.set(a.id, a));
+ },
+
+ /** Remove all actions registered under a page scope key. */
+ unregister(pageId: string): void {
+ const prev = _byPage.get(pageId) ?? [];
+ prev.forEach((a) => _byId.delete(a.id));
+ _byPage.delete(pageId);
+ },
+
+ /** Look up a single action by its dot-namespaced id. */
+ get(actionId: string): PageAction | undefined {
+ return _byId.get(actionId);
+ },
+
+ /**
+ * Returns serialisable descriptors for all currently registered actions,
+ * with context snapshots already collected. Safe to embed in API payload.
+ */
+ snapshot(): PageActionDescriptor[] {
+ return Array.from(_byId.values()).map((action) => ({
+ id: action.id,
+ description: action.description,
+ parameters: action.parameters,
+ context: action.getContext?.(),
+ }));
+ },
+
+ /** Returns all registered action IDs (useful for debugging). */
+ ids(): string[] {
+ return Array.from(_byId.keys());
+ },
+};
diff --git a/frontend/src/container/AIAssistant/pageActions/builderQueryHelpers.ts b/frontend/src/container/AIAssistant/pageActions/builderQueryHelpers.ts
new file mode 100644
index 0000000000..13fb89f093
--- /dev/null
+++ b/frontend/src/container/AIAssistant/pageActions/builderQueryHelpers.ts
@@ -0,0 +1,86 @@
+/**
+ * Shared helpers for AI-Assistant page actions that mutate the QueryBuilder
+ * state on logs/traces/metrics explorers. These keep the per-page action
+ * factories thin so they only need to declare ids, descriptions, and schemas.
+ */
+
+import {
+ BaseAutocompleteData,
+ DataTypes,
+} from 'types/api/queryBuilder/queryAutocompleteResponse';
+import {
+ IBuilderQuery,
+ Query,
+ TagFilterItem,
+} from 'types/api/queryBuilder/queryBuilderData';
+import { v4 as uuidv4 } from 'uuid';
+
+/** Param shape emitted by the AI for every filter-touching action. */
+export interface AIFilter {
+ key: string;
+ op: string;
+ value: string;
+}
+
+/**
+ * IN / NOT_IN operators expect an array of values, not a single string. The
+ * AI is asked to pass comma-separated values for these ops via the schema's
+ * `value: string` field, so we split here. Other ops keep the raw string —
+ * matches how the query-builder UI itself stores them.
+ */
+export function valueForOp(op: string, value: string): TagFilterItem['value'] {
+ if (op === 'IN' || op === 'NOT_IN') {
+ return value
+ .split(',')
+ .map((v) => v.trim())
+ .filter((v) => v.length > 0);
+ }
+ return value;
+}
+
+export function aiFilterToTagFilterItem(f: AIFilter): TagFilterItem {
+ // Defaults for `type` (autocomplete category) and `dataType` mirror what
+ // the query-builder writes when a user types a free-form filter the
+ // autocomplete hasn't seen yet — without them the filter chip can fail
+ // to render in the WHERE clause.
+ const key: BaseAutocompleteData = {
+ key: f.key,
+ type: '',
+ dataType: DataTypes.String,
+ };
+ return { id: uuidv4(), key, op: f.op, value: valueForOp(f.op, f.value) };
+}
+
+/** Return a new Query with the first builder queryData entry replaced. */
+export function replaceFirstQueryData(
+ query: Query,
+ updated: IBuilderQuery,
+): Query {
+ const queryData = [...query.builder.queryData];
+ queryData[0] = updated;
+ return {
+ ...query,
+ builder: { ...query.builder, queryData },
+ };
+}
+
+/** Page-state deps required by the runQuery / addFilter actions. */
+export interface FilterDeps {
+ currentQuery: Query;
+ handleSetQueryData: (index: number, newQueryData: IBuilderQuery) => void;
+ redirectWithQueryBuilderData: (query: Query) => void;
+}
+
+/** JSON-Schema enum of operators the AI is allowed to emit. */
+export const FILTER_OP_ENUM = [
+ '=',
+ '!=',
+ 'IN',
+ 'NOT_IN',
+ 'CONTAINS',
+ 'NOT_CONTAINS',
+] as const;
+
+/** Description shared across action schemas for the `value` field. */
+export const FILTER_VALUE_DESCRIPTION =
+ 'For IN / NOT_IN, comma-separated values (e.g. "ERROR,FATAL"). Otherwise a single value.';
diff --git a/frontend/src/container/AIAssistant/pageActions/types.ts b/frontend/src/container/AIAssistant/pageActions/types.ts
new file mode 100644
index 0000000000..f6528e656f
--- /dev/null
+++ b/frontend/src/container/AIAssistant/pageActions/types.ts
@@ -0,0 +1,98 @@
+export type JSONSchemaProperty =
+ | { type: 'string'; description?: string; enum?: string[] }
+ | { type: 'number'; description?: string }
+ | { type: 'boolean'; description?: string }
+ | {
+ type: 'array';
+ description?: string;
+ items: JSONSchemaProperty | JSONSchemaObject;
+ }
+ | {
+ type: 'object';
+ description?: string;
+ properties?: Record<string, JSONSchemaProperty>;
+ required?: string[];
+ };
+
+export type JSONSchemaObject = {
+ type: 'object';
+ properties: Record<string, JSONSchemaProperty>;
+ required?: string[];
+};
+
+export interface ActionResult {
+ /** Short human-readable outcome shown after the action completes. */
+ summary: string;
+ /** Optional structured data the block can display. */
+ data?: Record<string, unknown>;
+}
+
+/**
+ * Describes a single action a page exposes to the AI Assistant.
+ * Pages register these via `usePageActions`.
+ */
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+export interface PageAction<TParams = Record<string, any>> {
+ /**
+ * Stable dot-namespaced identifier — e.g. "logs.runQuery", "dashboard.create".
+ * The AI uses this to target the correct action.
+ */
+ id: string;
+
+ /**
+ * Natural-language description sent in the PAGE_CONTEXT block.
+ * The AI uses this to decide which action to invoke.
+ */
+ description: string;
+
+ /**
+ * JSON Schema (draft-07) describing the parameters accepted by this action.
+ * Sent to the AI so it can generate structurally valid calls.
+ */
+ parameters: JSONSchemaObject;
+
+ /**
+ * Executes the action. Resolves with a result summary on success.
+ * Rejects with an Error if the action cannot be completed.
+ */
+ execute: (params: TParams) => Promise<ActionResult>;
+
+ /**
+ * When true, ActionBlock executes the action immediately on mount without
+ * showing a confirmation card. Use for low-risk, reversible actions where
+ * the user explicitly requested the change (e.g. updating a query filter).
+ * Default: false (shows Accept / Dismiss card).
+ */
+ autoApply?: boolean;
+
+ /**
+ * Optional: returns a snapshot of the current page state to include in
+ * the PAGE_CONTEXT block. Called fresh at message-send time.
+ */
+ getContext?: () => unknown;
+}
+
+/**
+ * Serialisable version of PageAction (no function references).
+ * Safe to embed in the API payload.
+ */
+export interface PageActionDescriptor {
+ id: string;
+ description: string;
+ parameters: JSONSchemaObject;
+ /** Context snapshot returned by PageAction.getContext() */
+ context?: unknown;
+}
+
+/**
+ * The JSON payload the AI emits inside an ```ai-action``` fenced block
+ * when it wants to invoke an action.
+ */
+export interface AIActionBlock {
+ /** Must match a registered PageAction.id */
+ actionId: string;
+ /** One-sentence explanation shown in the confirmation card. */
+ description: string;
+ /** Parameters chosen by the AI — validated against the action's JSON Schema. */
+ parameters: Record<string, unknown>;
+}
diff --git a/frontend/src/container/AIAssistant/pageActions/usePageActions.ts b/frontend/src/container/AIAssistant/pageActions/usePageActions.ts
new file mode 100644
index 0000000000..02262201d3
--- /dev/null
+++ b/frontend/src/container/AIAssistant/pageActions/usePageActions.ts
@@ -0,0 +1,33 @@
+import { useEffect } from 'react';
+
+import { PageActionRegistry } from './PageActionRegistry';
+import { PageAction } from './types';
+
+/**
+ * Registers page-specific actions into the PageActionRegistry for the lifetime
+ * of the calling component. Cleanup (unregister) happens automatically on unmount.
+ *
+ * Usage:
+ * const actions = useMemo(() => [
+ * logsRunQueryAction({ handleRunQuery, ... }),
+ * ], [handleRunQuery, ...]);
+ *
+ * usePageActions('logs-explorer', actions);
+ *
+ * IMPORTANT: memoize the `actions` array with useMemo so that the reference
+ * stays stable and we don't re-register on every render.
+ */
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+export function usePageActions(
+ pageId: string,
+ actions: PageAction<any>[],
+): void {
+ useEffect(() => {
+ PageActionRegistry.register(pageId, actions);
+ return (): void => {
+ PageActionRegistry.unregister(pageId);
+ };
+ // Re-register when actions reference changes (e.g. new callbacks after store update)
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [pageId, actions]);
+}
diff --git a/frontend/src/container/AIAssistant/store/pendingInputSelectors.ts b/frontend/src/container/AIAssistant/store/pendingInputSelectors.ts
new file mode 100644
index 0000000000..17af8d96dc
--- /dev/null
+++ b/frontend/src/container/AIAssistant/store/pendingInputSelectors.ts
@@ -0,0 +1,23 @@
+import type { AIAssistantStore } from './useAIAssistantStore';
+
+export type AIAssistantStoreState = AIAssistantStore;
+
+/**
+ * Number of conversations whose execution is waiting on the user (approval or
+ * clarification). Used for header badges when the side panel is closed.
+ */
+export function selectPendingUserInputStreamCount(
+ state: AIAssistantStoreState,
+): number {
+ let n = 0;
+ for (const st of Object.values(state.streams)) {
+ const { streamingStatus } = st;
+ if (
+ streamingStatus === 'awaiting_approval' ||
+ streamingStatus === 'awaiting_clarification'
+ ) {
+ n += 1;
+ }
+ }
+ return n;
+}
diff --git a/frontend/src/container/AIAssistant/store/useAIAssistantStore.ts b/frontend/src/container/AIAssistant/store/useAIAssistantStore.ts
new file mode 100644
index 0000000000..ca838c19d8
--- /dev/null
+++ b/frontend/src/container/AIAssistant/store/useAIAssistantStore.ts
@@ -0,0 +1,1338 @@
+/* eslint-disable sonarjs/cognitive-complexity */
+import { v4 as uuidv4 } from 'uuid';
+import { create } from 'zustand';
+import { persist } from 'zustand/middleware';
+import { immer } from 'zustand/middleware/immer';
+
+import type {
+ MessageActionDTO,
+ MessageSummaryDTOBlocksAnyOfItem,
+} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
+
+import {
+ approveExecution,
+ cancelExecution,
+ clarifyExecution,
+ createThread,
+ getThreadDetail,
+ listThreads,
+ MessageContext,
+ MessageSummary,
+ regenerateMessage,
+ rejectExecution,
+ sendMessage as sendMessageToThread,
+ SSEStreamError,
+ streamEvents,
+ submitFeedback,
+ ThreadSummary,
+ updateThread,
+} from '../../../api/ai-assistant/chat';
+import {
+ Conversation,
+ ConversationStreamState,
+ FeedbackRating,
+ Message,
+ MessageAttachment,
+ MessageBlock,
+ MessageRole,
+} from '../types';
+
+// ---------------------------------------------------------------------------
+// Types used by module-level helpers
+// ---------------------------------------------------------------------------
+
+type StoreSetter = (fn: (s: AIAssistantStore) => void) => void;
+type StoreGetter = () => AIAssistantStore;
+
+interface SSEStreamCtx {
+ conversationId: string;
+ set: StoreSetter;
+ signal?: AbortSignal;
+}
+
+// ---------------------------------------------------------------------------
+// Per-conversation AbortControllers
+// ---------------------------------------------------------------------------
+
+const streamControllers = new Map<string, AbortController>();
+
+function abortStream(conversationId: string): void {
+ const ctrl = streamControllers.get(conversationId);
+ if (ctrl) {
+ ctrl.abort();
+ streamControllers.delete(conversationId);
+ }
+}
+
+function newStreamController(conversationId: string): AbortController {
+ abortStream(conversationId);
+ const ctrl = new AbortController();
+ streamControllers.set(conversationId, ctrl);
+ return ctrl;
+}
+
+/**
+ * Gracefully disconnects from a conversation's SSE stream:
+ * 1. Aborts the HTTP connection (backend execution keeps running).
+ * 2. Commits any buffered text as a message so it's not lost.
+ * 3. Removes the stream entry.
+ *
+ * Safe to call even if the conversation is not currently streaming.
+ */
+async function fetchAllThreadSummaries(
+ archived: 'true' | 'false',
+): Promise<ThreadSummary[]> {
+ const allThreads: ThreadSummary[] = [];
+ let cursor: string | null = null;
+ do {
+ // eslint-disable-next-line no-await-in-loop
+ const page = await listThreads({
+ archived,
+ limit: 50,
+ cursor,
+ sort: 'updated_desc',
+ });
+ allThreads.push(...page.threads);
+ cursor = page.hasMore ? (page.nextCursor ?? null) : null;
+ } while (cursor);
+ return allThreads;
+}
+
+function disconnectAndCommit(
+ conversationId: string,
+ set: StoreSetter,
+ get: StoreGetter,
+): void {
+ abortStream(conversationId);
+
+ const stream = get().streams[conversationId];
+ if (!stream) {
+ return;
+ }
+
+ set((s) => {
+ const st = s.streams[conversationId];
+ if (!st) {
+ return;
+ }
+ const conv = s.conversations[conversationId];
+ if (conv && st.streamingContent.trim()) {
+ const blocks = streamEventsToBlocks(st.streamingEvents);
+ conv.messages.push({
+ id: st.streamingMessageId ?? uuidv4(),
+ role: 'assistant',
+ content: st.streamingContent,
+ blocks: blocks.length > 0 ? blocks : undefined,
+ createdAt: Date.now(),
+ });
+ conv.updatedAt = Date.now();
+ }
+ delete s.streams[conversationId];
+ });
+}
+
+// ---------------------------------------------------------------------------
+// Module-level helpers
+// ---------------------------------------------------------------------------
+
+/**
+ * Drips a text chunk word-by-word with small random delays to produce a
+ * smooth typing effect when large SSE deltas arrive all at once.
+ */
+async function animateDelta(
+ delta: string,
+ onWord: (word: string) => void,
+): Promise<void> {
+ const words = delta.split(/(?<=\s)/);
+ for (const word of words) {
+ // eslint-disable-next-line no-await-in-loop
+ await new Promise<void>((resolve) => {
+ setTimeout(resolve, 12 + Math.random() * 18);
+ });
+ onWord(word);
+ }
+}
+
+/**
+ * Appends one text chunk to a conversation's stream state.
+ * Operates on the per-conversation ConversationStreamState.
+ */
+function appendTextToStream(
+ stream: ConversationStreamState,
+ messageId: string,
+ chunk: string,
+): void {
+ if (!stream.streamingMessageId) {
+ stream.streamingMessageId = messageId;
+ }
+ stream.streamingContent += chunk;
+ const last = stream.streamingEvents[stream.streamingEvents.length - 1];
+ if (last?.kind === 'text') {
+ last.content += chunk;
+ } else {
+ stream.streamingEvents.push({ kind: 'text', content: chunk });
+ }
+}
+
+/**
+ * Creates a fresh stream entry for a conversation.
+ */
+function resetStreamingState(
+ s: AIAssistantStore,
+ conversationId: string,
+): void {
+ s.streams[conversationId] = {
+ isStreaming: true,
+ streamingContent: '',
+ streamingStatus: '',
+ streamingEvents: [],
+ streamingMessageId: null,
+ streamingActions: null,
+ pendingApproval: null,
+ pendingClarification: null,
+ };
+}
+
+/**
+ * Runs one SSE execution stream, updating the per-conversation stream state.
+ *
+ * Breaks early and sets pendingApproval / pendingClarification when the
+ * agent needs user input before it can continue.
+ *
+ * Throws on `error` events — the caller's catch block handles UI feedback.
+ */
+// eslint-disable-next-line sonarjs/cognitive-complexity
+async function runStreamingLoop(
+ executionId: string,
+ ctx: SSEStreamCtx,
+): Promise<void> {
+ const { conversationId, set, signal } = ctx;
+
+ for await (const event of streamEvents(executionId, signal)) {
+ if (signal?.aborted) {
+ return;
+ }
+
+ if (event.type === 'status') {
+ set((s) => {
+ const st = s.streams[conversationId];
+ if (st) {
+ st.streamingStatus = event.state;
+ }
+ });
+ } else if (event.type === 'message') {
+ if (event.delta) {
+ // eslint-disable-next-line no-await-in-loop
+ await animateDelta(event.delta, (word) => {
+ set((s) => {
+ const st = s.streams[conversationId];
+ if (st) {
+ appendTextToStream(st, event.messageId, word);
+ }
+ });
+ });
+ }
+ if (event.done) {
+ set((s) => {
+ const st = s.streams[conversationId];
+ if (st && event.actions && event.actions.length > 0) {
+ // MessageActionEventDTO is structurally identical to MessageActionDTO.
+ st.streamingActions = event.actions as MessageActionDTO[];
+ }
+ });
+ // Don't break here — `message.done` marks the end of this
+ // message, not the stream. A clarification/approval event may
+ // follow in the same stream. The loop ends on the explicit
+ // `done` event type (or `approval`/`clarification`, which
+ // pause the stream).
+ }
+ } else if (event.type === 'thinking') {
+ set((s) => {
+ const st = s.streams[conversationId];
+ if (!st) {
+ return;
+ }
+ const last = st.streamingEvents[st.streamingEvents.length - 1];
+ if (last?.kind === 'thinking') {
+ last.content += event.content;
+ } else {
+ st.streamingEvents.push({
+ kind: 'thinking',
+ content: event.content,
+ });
+ }
+ });
+ } else if (event.type === 'tool_call') {
+ set((s) => {
+ const st = s.streams[conversationId];
+ if (st) {
+ st.streamingEvents.push({
+ kind: 'tool',
+ toolCall: {
+ toolName: event.toolName,
+ input: event.toolInput,
+ done: false,
+ displayText: event.displayText,
+ },
+ });
+ }
+ });
+ } else if (event.type === 'tool_result') {
+ set((s) => {
+ const st = s.streams[conversationId];
+ if (!st) {
+ return;
+ }
+ const toolEvent = [...st.streamingEvents]
+ .reverse()
+ .find(
+ (e) =>
+ e.kind === 'tool' &&
+ e.toolCall.toolName === event.toolName &&
+ !e.toolCall.done,
+ );
+ if (toolEvent?.kind === 'tool') {
+ toolEvent.toolCall.result = event.result;
+ toolEvent.toolCall.done = true;
+ }
+ });
+ } else if (event.type === 'approval') {
+ set((s) => {
+ const st = s.streams[conversationId];
+ if (st) {
+ // The SSE event is already an `ApprovalEventDTO`, the same
+ // shape the slot is typed against — pass through verbatim
+ // rather than re-projecting (which previously dropped any
+ // fields the projection didn't enumerate explicitly).
+ st.pendingApproval = event;
+ st.streamingStatus = 'awaiting_approval';
+ st.isStreaming = false;
+ }
+ });
+ break;
+ } else if (event.type === 'clarification') {
+ set((s) => {
+ const st = s.streams[conversationId];
+ if (st) {
+ // Same rationale as the approval branch — `event` is a
+ // `ClarificationEventDTO` whose `fields` already carry
+ // `allowCustom` (which the previous manual projection
+ // silently stripped).
+ st.pendingClarification = event;
+ st.streamingStatus = 'awaiting_clarification';
+ st.isStreaming = false;
+ }
+ });
+ break;
+ } else if (event.type === 'error') {
+ throw Object.assign(new Error(event.error.message), {
+ retryAction: event.retryAction,
+ });
+ } else if (event.type === 'conversation' && event.title) {
+ set((s) => {
+ if (s.conversations[conversationId]) {
+ s.conversations[conversationId].title = event.title;
+ }
+ });
+ } else if (event.type === 'done') {
+ break;
+ }
+ }
+}
+
+/**
+ * Converts streaming event items into persisted MessageBlocks.
+ */
+function streamEventsToBlocks(
+ events: ConversationStreamState['streamingEvents'],
+): MessageBlock[] {
+ return events
+ .map((e): MessageBlock | null => {
+ if (e.kind === 'text') {
+ return { type: 'text', content: e.content };
+ }
+ if (e.kind === 'thinking') {
+ return { type: 'thinking', content: e.content };
+ }
+ if (e.kind === 'tool') {
+ return {
+ type: 'tool_call',
+ toolCallId: e.toolCall.toolName, // best available id during streaming
+ toolName: e.toolCall.toolName,
+ toolInput: e.toolCall.input,
+ result: e.toolCall.result,
+ success: e.toolCall.done,
+ displayText: e.toolCall.displayText,
+ };
+ }
+ return null;
+ })
+ .filter((b): b is MessageBlock => b !== null);
+}
+
+/**
+ * Commits accumulated streaming text as a message and removes the stream entry.
+ */
+function finalizeStreamingMessage(
+ conversationId: string,
+ set: StoreSetter,
+ get: StoreGetter,
+): void {
+ const stream = get().streams[conversationId];
+ if (!stream) {
+ return;
+ }
+ const {
+ streamingMessageId,
+ streamingContent,
+ streamingEvents,
+ streamingActions,
+ } = stream;
+
+ set((s) => {
+ const conv = s.conversations[conversationId];
+ if (conv && streamingContent.trim()) {
+ const blocks = streamEventsToBlocks(streamingEvents);
+ conv.messages.push({
+ id: streamingMessageId ?? uuidv4(),
+ role: 'assistant',
+ content: streamingContent,
+ blocks: blocks.length > 0 ? blocks : undefined,
+ actions: streamingActions ?? undefined,
+ createdAt: Date.now(),
+ });
+ conv.updatedAt = Date.now();
+ }
+ delete s.streams[conversationId];
+ });
+}
+
+function hasPendingInput(conversationId: string, get: StoreGetter): boolean {
+ const stream = get().streams[conversationId];
+ return Boolean(stream?.pendingApproval || stream?.pendingClarification);
+}
+
+/**
+ * Commits an error message and removes the stream entry.
+ */
+function finalizeStreamingError(
+ conversationId: string,
+ errorContent: string,
+ set: StoreSetter,
+): void {
+ set((s) => {
+ const conv = s.conversations[conversationId];
+ if (conv) {
+ conv.messages.push({
+ id: uuidv4(),
+ role: 'assistant',
+ content: errorContent,
+ createdAt: Date.now(),
+ });
+ conv.updatedAt = Date.now();
+ }
+ delete s.streams[conversationId];
+ });
+}
+
+// ---------------------------------------------------------------------------
+// Store interface
+// ---------------------------------------------------------------------------
+
+export interface AIAssistantStore {
+ // UI state
+ isDrawerOpen: boolean;
+ isModalOpen: boolean;
+ activeConversationId: string | null;
+
+ // Data
+ conversations: Record<string, Conversation>;
+
+ // Per-conversation streaming state
+ streams: Record<string, ConversationStreamState>;
+
+ /**
+ * Persists answered state for interactive blocks (ai-question, ai-confirm)
+ * so re-renders/remounts don't reset the answered UI.
+ */
+ answeredBlocks: Record<string, string>;
+
+ // Loading state
+ isLoadingThreads: boolean;
+ isLoadingThread: boolean;
+
+ // Actions
+ openDrawer: () => void;
+ closeDrawer: () => void;
+ openModal: () => void;
+ closeModal: () => void;
+ minimizeModal: () => void;
+ fetchThreads: () => Promise<void>;
+ loadThread: (threadId: string) => Promise<void>;
+ startNewConversation: () => string;
+ setActiveConversation: (id: string) => void;
+ clearConversation: (id: string) => void;
+ archiveConversation: (id: string) => void;
+ restoreConversation: (id: string) => void;
+ renameConversation: (id: string, title: string) => Promise<void>;
+ markBlockAnswered: (messageId: string, answer: string) => void;
+ sendMessage: (
+ text: string,
+ attachments?: MessageAttachment[],
+ contexts?: MessageContext[],
+ ) => Promise<void>;
+ approveAction: (conversationId: string, approvalId: string) => Promise<void>;
+ rejectAction: (conversationId: string, approvalId: string) => Promise<void>;
+ submitClarification: (
+ conversationId: string,
+ clarificationId: string,
+ answers: Record<string, unknown>,
+ ) => Promise<void>;
+ cancelStream: (conversationId: string) => void;
+ regenerateAssistantMessage: (
+ conversationId: string,
+ messageId: string,
+ ) => Promise<void>;
+ submitMessageFeedback: (
+ messageId: string,
+ rating: FeedbackRating,
+ comment?: string,
+ ) => Promise<void>;
+}
+
+// ---------------------------------------------------------------------------
+// Server → client converters
+// ---------------------------------------------------------------------------
+
+/**
+ * The DTO models a persisted block as `{ [key: string]: unknown }`. This
+ * helper narrows each entry to the typed `MessageBlock` discriminated union
+ * the UI renders against.
+ */
+function toBlocks(
+ raw: MessageSummaryDTOBlocksAnyOfItem[] | null | undefined,
+): MessageBlock[] | undefined {
+ if (!raw || raw.length === 0) {
+ return undefined;
+ }
+ return raw
+ .map((b): MessageBlock | null => {
+ if (b.type === 'text') {
+ return {
+ type: 'text',
+ content: typeof b.content === 'string' ? b.content : '',
+ };
+ }
+ if (b.type === 'thinking') {
+ return {
+ type: 'thinking',
+ content: typeof b.content === 'string' ? b.content : '',
+ };
+ }
+ if (b.type === 'tool_call' && typeof b.toolName === 'string') {
+ return {
+ type: 'tool_call',
+ toolCallId: typeof b.toolCallId === 'string' ? b.toolCallId : '',
+ toolName: b.toolName,
+ toolInput: b.toolInput,
+ result: b.result,
+ success: typeof b.success === 'boolean' ? b.success : undefined,
+ displayText: typeof b.displayText === 'string' ? b.displayText : undefined,
+ };
+ }
+ return null;
+ })
+ .filter((b): b is MessageBlock => b !== null);
+}
+
+/**
+ * `sendMessage` prepends a `[PAGE_CONTEXT]…[/PAGE_CONTEXT]` block to the user's
+ * text so the agent has the available page actions + state. The backend stores
+ * and returns the full string, which would otherwise leak into the user's
+ * bubble on reload. Strip it once here so every consumer of the store sees
+ * just the original prompt.
+ */
+const PAGE_CONTEXT_PREFIX_RE = /^\[PAGE_CONTEXT\][\s\S]*?\[\/PAGE_CONTEXT\]\n?/;
+
+function stripPageContextPrefix(content: string): string {
+ return content.replace(PAGE_CONTEXT_PREFIX_RE, '');
+}
+
+/**
+ * Parse a backend ISO timestamp into ms epoch, falling back to `now()` when the
+ * value is missing or unparseable. Without this guard, a null/invalid date from
+ * the API turns into NaN and surfaces in the UI as "Invalid Date".
+ */
+function toMs(value: string | null | undefined): number {
+ const t = value ? new Date(value).getTime() : NaN;
+ return Number.isFinite(t) ? t : Date.now();
+}
+
+function toMessage(m: MessageSummary): Message {
+ const rawContent = m.content ?? '';
+ const content =
+ m.role === 'user' ? stripPageContextPrefix(rawContent) : rawContent;
+ return {
+ id: m.messageId,
+ role: m.role as MessageRole,
+ content,
+ blocks: toBlocks(m.blocks),
+ actions: m.actions ?? undefined,
+ feedbackRating: m.feedbackRating ?? undefined,
+ createdAt: toMs(m.createdAt),
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Misc store helpers
+// ---------------------------------------------------------------------------
+
+function deriveTitle(text: string): string {
+ const trimmed = text.trim().replace(/\s+/g, ' ');
+ return trimmed.length > 60 ? `${trimmed.slice(0, 60)}…` : trimmed;
+}
+
+// ---------------------------------------------------------------------------
+// Store
+// ---------------------------------------------------------------------------
+
+export const useAIAssistantStore = create<AIAssistantStore>()(
+ persist(
+ immer<AIAssistantStore>((set, get) => ({
+ isDrawerOpen: false,
+ isModalOpen: false,
+ activeConversationId: null,
+ conversations: {},
+ streams: {},
+ isLoadingThreads: false,
+ isLoadingThread: false,
+ answeredBlocks: {},
+
+ openDrawer: (): void => {
+ set((state) => {
+ state.isDrawerOpen = true;
+ if (!state.activeConversationId) {
+ const id = uuidv4();
+ state.conversations[id] = {
+ id,
+ messages: [],
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ };
+ state.activeConversationId = id;
+ }
+ });
+ },
+
+ closeDrawer: (): void => {
+ set((state) => {
+ state.isDrawerOpen = false;
+ });
+ },
+
+ openModal: (): void => {
+ set((state) => {
+ state.isModalOpen = true;
+ if (!state.activeConversationId) {
+ const id = uuidv4();
+ state.conversations[id] = {
+ id,
+ messages: [],
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ };
+ state.activeConversationId = id;
+ }
+ });
+ },
+
+ closeModal: (): void => {
+ set((state) => {
+ state.isModalOpen = false;
+ });
+ },
+
+ minimizeModal: (): void => {
+ set((state) => {
+ state.isModalOpen = false;
+ state.isDrawerOpen = true;
+ if (!state.activeConversationId) {
+ const id = uuidv4();
+ state.conversations[id] = {
+ id,
+ messages: [],
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ };
+ state.activeConversationId = id;
+ }
+ });
+ },
+
+ fetchThreads: async (): Promise<void> => {
+ set((s) => {
+ s.isLoadingThreads = true;
+ });
+ try {
+ const [activeThreads, archivedThreads] = await Promise.all([
+ fetchAllThreadSummaries('false'),
+ fetchAllThreadSummaries('true'),
+ ]);
+ const allThreads = [...activeThreads, ...archivedThreads];
+
+ let activeThreadIdToLoad: string | null = null;
+
+ set((s) => {
+ const serverThreadIds = new Set(
+ allThreads.map((thread) => thread.threadId),
+ );
+
+ for (const [id, conv] of Object.entries(s.conversations)) {
+ if (conv.threadId && !serverThreadIds.has(conv.threadId)) {
+ delete s.conversations[id];
+ }
+ }
+
+ for (const thread of allThreads) {
+ const existingEntry = Object.entries(s.conversations).find(
+ ([, conv]) => conv.threadId === thread.threadId,
+ );
+ const mapped = {
+ id: thread.threadId,
+ threadId: thread.threadId,
+ title: thread.title ?? undefined,
+ messages: existingEntry?.[1].messages ?? [],
+ createdAt: toMs(thread.createdAt),
+ updatedAt: toMs(thread.updatedAt),
+ archived: thread.archived,
+ };
+
+ if (existingEntry && existingEntry[0] !== thread.threadId) {
+ delete s.conversations[existingEntry[0]];
+ }
+
+ s.conversations[thread.threadId] = mapped;
+ }
+
+ s.isLoadingThreads = false;
+
+ // Clear the rehydrate-time hydration flag on any entries
+ // the server didn't claim — those are local-only chats
+ // the user started but never sent. Server-mapped entries
+ // were already replaced above and don't carry the flag.
+ for (const conv of Object.values(s.conversations)) {
+ if (conv.isHydrating) {
+ delete conv.isHydrating;
+ }
+ }
+
+ // If the active conversation matches a known thread but
+ // has no messages yet (typical on refresh), flip to the
+ // per-thread loading flag in the same set() so the
+ // skeleton stays visible without a flicker.
+ const id = s.activeConversationId;
+ if (id) {
+ const conv = s.conversations[id];
+ if (conv?.threadId && conv.messages.length === 0) {
+ activeThreadIdToLoad = conv.threadId;
+ s.isLoadingThread = true;
+ }
+ }
+ });
+
+ // Hydrate the active conversation's messages on reload. The
+ // rehydrate-time loadThread used to do this, but it ran at
+ // module-load — before the AI base URL was configured — so
+ // it always failed. Now that fetchThreads has populated
+ // `threadId`s, we can confidently load the right one.
+ if (activeThreadIdToLoad) {
+ void get().loadThread(activeThreadIdToLoad);
+ }
+ } catch (err) {
+ console.error('[AIAssistant] fetchThreads failed:', err);
+ set((s) => {
+ s.isLoadingThreads = false;
+ for (const conv of Object.values(s.conversations)) {
+ if (conv.isHydrating) {
+ delete conv.isHydrating;
+ }
+ }
+ });
+ }
+ },
+
+ // eslint-disable-next-line sonarjs/cognitive-complexity
+ loadThread: async (threadId: string): Promise<void> => {
+ set((s) => {
+ s.isLoadingThread = true;
+ s.activeConversationId = threadId;
+ });
+ try {
+ const detail = await getThreadDetail(threadId);
+ set((s) => {
+ s.conversations[threadId] = {
+ id: threadId,
+ threadId: detail.threadId,
+ title: detail.title ?? undefined,
+ messages: (detail.messages ?? [])
+ .filter((m) => m.content != null && m.content.trim() !== '')
+ .map(toMessage),
+ createdAt: toMs(detail.createdAt),
+ updatedAt: toMs(detail.updatedAt),
+ archived: detail.archived,
+ };
+ if (detail.pendingApproval || detail.pendingClarification) {
+ s.streams[threadId] = {
+ isStreaming: false,
+ streamingContent: '',
+ streamingStatus: detail.pendingApproval
+ ? 'awaiting_approval'
+ : 'awaiting_clarification',
+ streamingEvents: [],
+ streamingMessageId: null,
+ streamingActions: null,
+ // ApprovalSummaryDTO / ClarificationSummaryDTO are structurally
+ // compatible with the SSE event DTOs used by ConversationStreamState.
+ pendingApproval: detail.pendingApproval ?? null,
+ pendingClarification: detail.pendingClarification ?? null,
+ };
+ }
+ s.isLoadingThread = false;
+ });
+
+ // Reconnect to SSE if backend execution is still running
+ // and we don't already have an active SSE reader for this thread
+ if (
+ detail.activeExecutionId &&
+ !streamControllers.has(threadId) &&
+ !detail.pendingApproval &&
+ !detail.pendingClarification
+ ) {
+ set((s) => {
+ resetStreamingState(s, threadId);
+ });
+ const ctrl = newStreamController(threadId);
+ try {
+ await runStreamingLoop(detail.activeExecutionId, {
+ conversationId: threadId,
+ set,
+ signal: ctrl.signal,
+ });
+ } finally {
+ streamControllers.delete(threadId);
+ }
+ if (!hasPendingInput(threadId, get)) {
+ finalizeStreamingMessage(threadId, set, get);
+ }
+ }
+ } catch (err) {
+ if (err instanceof DOMException && err.name === 'AbortError') {
+ return;
+ }
+ console.error('[AIAssistant] loadThread failed:', err);
+ set((s) => {
+ s.isLoadingThread = false;
+ });
+ }
+ },
+
+ startNewConversation: (): string => {
+ const id = uuidv4();
+ set((state) => {
+ state.conversations[id] = {
+ id,
+ messages: [],
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ };
+ state.activeConversationId = id;
+ });
+ return id;
+ },
+
+ setActiveConversation: (id: string): void => {
+ set((state) => {
+ state.activeConversationId = id;
+ });
+ },
+
+ clearConversation: (id: string): void => {
+ disconnectAndCommit(id, set, get);
+ set((state) => {
+ if (state.conversations[id]) {
+ state.conversations[id].messages
+ .map((m) => m.id)
+ .forEach((mid) => {
+ delete state.answeredBlocks[mid];
+ });
+ state.conversations[id].messages = [];
+ state.conversations[id].title = undefined;
+ state.conversations[id].threadId = undefined;
+ state.conversations[id].archived = false;
+ state.conversations[id].updatedAt = Date.now();
+ }
+ });
+ },
+
+ archiveConversation: (id: string): void => {
+ const conv = get().conversations[id];
+ if (!conv) {
+ return;
+ }
+ disconnectAndCommit(id, set, get);
+ if (conv.threadId) {
+ updateThread(conv.threadId, { archived: true }).catch((err) => {
+ console.error('[AIAssistant] archiveThread failed:', err);
+ });
+ set((state) => {
+ const c = state.conversations[id];
+ if (c) {
+ c.archived = true;
+ }
+ if (state.activeConversationId === id) {
+ const remaining = Object.values(state.conversations)
+ .filter((a) => !a.archived)
+ .sort(
+ (a, b) => (b.updatedAt ?? b.createdAt) - (a.updatedAt ?? a.createdAt),
+ );
+ state.activeConversationId = remaining[0]?.id ?? null;
+ }
+ });
+ } else {
+ set((state) => {
+ delete state.conversations[id];
+ if (state.activeConversationId === id) {
+ const remaining = Object.values(state.conversations).sort(
+ (a, b) => (b.updatedAt ?? b.createdAt) - (a.updatedAt ?? a.createdAt),
+ );
+ state.activeConversationId = remaining[0]?.id ?? null;
+ }
+ });
+ }
+ },
+
+ restoreConversation: (id: string): void => {
+ const conv = get().conversations[id];
+ if (!conv?.threadId) {
+ return;
+ }
+ updateThread(conv.threadId, { archived: false })
+ .then(() => {
+ set((state) => {
+ const c = state.conversations[id];
+ if (c) {
+ c.archived = false;
+ }
+ });
+ })
+ .catch((err) => {
+ console.error('[AIAssistant] restoreThread failed:', err);
+ });
+ },
+
+ renameConversation: async (id: string, title: string): Promise<void> => {
+ const trimmed = title.trim() || undefined;
+ const conv = get().conversations[id];
+ if (!conv) {
+ return;
+ }
+ const previousTitle = conv.title;
+
+ // Optimistic local update so the sidebar reflects the rename
+ // immediately. Reconciled or reverted below once the backend
+ // responds — without that, an in-flight `loadThread` /
+ // `fetchThreads` can resolve with the pre-rename title and
+ // clobber the optimistic value.
+ set((state) => {
+ if (state.conversations[id]) {
+ state.conversations[id].title = trimmed;
+ }
+ });
+
+ if (!conv.threadId) {
+ return;
+ }
+
+ try {
+ const updated = await updateThread(conv.threadId, {
+ title: trimmed ?? null,
+ });
+ set((state) => {
+ if (state.conversations[id]) {
+ state.conversations[id].title = updated.title ?? undefined;
+ }
+ });
+ } catch (err) {
+ console.error('[AIAssistant] renameThread failed:', err);
+ set((state) => {
+ if (state.conversations[id]) {
+ state.conversations[id].title = previousTitle;
+ }
+ });
+ }
+ },
+
+ markBlockAnswered: (messageId: string, answer: string): void => {
+ set((state) => {
+ state.answeredBlocks[messageId] = answer;
+ });
+ },
+
+ // eslint-disable-next-line sonarjs/cognitive-complexity
+ sendMessage: async (
+ text: string,
+ attachments?: MessageAttachment[],
+ contexts?: MessageContext[],
+ ): Promise<void> => {
+ let convId = get().activeConversationId;
+ if (!convId || !get().conversations[convId]) {
+ return;
+ }
+
+ // If a previous reply is still streaming (typical when the user
+ // clicks a suggested-action button before the assistant has
+ // finished), tear it down before we queue the new one. We commit
+ // any partial text as a message so it's not lost, then await
+ // the backend cancel so `sendMessageToThread` doesn't race a
+ // 409 "thread busy" against the still-active execution.
+ const inFlight = get().streams[convId];
+ if (inFlight?.isStreaming) {
+ const existingThreadId = get().conversations[convId]?.threadId;
+ disconnectAndCommit(convId, set, get);
+ if (existingThreadId) {
+ try {
+ await cancelExecution(existingThreadId);
+ } catch (err) {
+ console.error('[AIAssistant] cancelExecution failed:', err);
+ }
+ }
+ }
+
+ const userMessage: Message = {
+ id: uuidv4(),
+ role: 'user',
+ content: text,
+ attachments,
+ createdAt: Date.now(),
+ };
+
+ set((state) => {
+ const conv = state.conversations[convId!];
+ conv.messages.push(userMessage);
+ conv.updatedAt = Date.now();
+ if (!conv.title && text.trim()) {
+ conv.title = deriveTitle(text);
+ }
+ resetStreamingState(state, convId!);
+ });
+
+ try {
+ let { threadId } = get().conversations[convId];
+ if (!threadId) {
+ threadId = await createThread();
+ // Re-key the conversation from client UUID to backend threadId
+ // so fetchThreads won't create a duplicate entry later.
+ const oldId = convId;
+ convId = threadId;
+ set((s) => {
+ const conv = s.conversations[oldId];
+ if (conv) {
+ conv.id = convId!;
+ conv.threadId = convId!;
+ s.conversations[convId!] = conv;
+ delete s.conversations[oldId];
+ if (s.activeConversationId === oldId) {
+ s.activeConversationId = convId!;
+ }
+ const stream = s.streams[oldId];
+ if (stream) {
+ s.streams[convId!] = stream;
+ delete s.streams[oldId];
+ }
+ }
+ });
+ }
+ const executionId = await sendMessageToThread(threadId, text, contexts);
+ const ctrl = newStreamController(convId);
+ await runStreamingLoop(executionId, {
+ conversationId: convId,
+ set,
+ signal: ctrl.signal,
+ });
+ streamControllers.delete(convId);
+
+ if (!hasPendingInput(convId, get)) {
+ finalizeStreamingMessage(convId, set, get);
+ }
+ } catch (err) {
+ // Abort errors are expected when the user cancels — not a failure
+ if (err instanceof DOMException && err.name === 'AbortError') {
+ return;
+ }
+ console.error('[AIAssistant] sendMessage failed:', err);
+ const message =
+ err instanceof SSEStreamError && err.status === 429
+ ? 'You sent that a bit too quickly. Please wait a moment and try again.'
+ : 'Something went wrong while fetching the response. Please try again.';
+ finalizeStreamingError(convId, message, set);
+ }
+ },
+
+ approveAction: async (
+ conversationId: string,
+ approvalId: string,
+ ): Promise<void> => {
+ set((s) => {
+ const st = s.streams[conversationId];
+ if (st) {
+ st.pendingApproval = null;
+ st.isStreaming = true;
+ st.streamingStatus = 'resumed';
+ } else {
+ resetStreamingState(s, conversationId);
+ }
+ });
+
+ try {
+ const executionId = await approveExecution(approvalId);
+ const ctrl = newStreamController(conversationId);
+ await runStreamingLoop(executionId, {
+ conversationId,
+ set,
+ signal: ctrl.signal,
+ });
+ streamControllers.delete(conversationId);
+ if (!hasPendingInput(conversationId, get)) {
+ finalizeStreamingMessage(conversationId, set, get);
+ }
+ } catch (err) {
+ if (err instanceof DOMException && err.name === 'AbortError') {
+ return;
+ }
+ console.error('[AIAssistant] approveAction failed:', err);
+ finalizeStreamingError(
+ conversationId,
+ 'Something went wrong while processing the approval. Please try again.',
+ set,
+ );
+ }
+ },
+
+ rejectAction: async (
+ conversationId: string,
+ approvalId: string,
+ ): Promise<void> => {
+ try {
+ await rejectExecution(approvalId);
+ } catch (err) {
+ console.error('[AIAssistant] rejectAction failed:', err);
+ }
+ set((s) => {
+ const st = s.streams[conversationId];
+ if (st) {
+ st.pendingApproval = null;
+ st.streamingStatus = '';
+ st.isStreaming = false;
+ }
+ });
+ },
+
+ cancelStream: (conversationId: string): void => {
+ // 1. Abort the client-side SSE reader
+ disconnectAndCommit(conversationId, set, get);
+
+ // 2. Cancel the backend execution (fire-and-forget)
+ const conv = get().conversations[conversationId];
+ if (conv?.threadId) {
+ cancelExecution(conv.threadId).catch((err) => {
+ console.error('[AIAssistant] cancelExecution failed:', err);
+ });
+ }
+ },
+
+ regenerateAssistantMessage: async (
+ conversationId: string,
+ messageId: string,
+ ): Promise<void> => {
+ const conv = get().conversations[conversationId];
+ if (!conv) {
+ return;
+ }
+ const targetIndex = conv.messages.findIndex((m) => m.id === messageId);
+ if (targetIndex < 0) {
+ return;
+ }
+
+ // The backend rewinds history up to (excluding) `messageId` and
+ // kicks off a fresh execution. Mirror that locally so the
+ // streaming bubble doesn't render alongside the stale reply
+ // that's about to be replaced.
+ set((s) => {
+ const c = s.conversations[conversationId];
+ if (c) {
+ c.messages = c.messages.slice(0, targetIndex);
+ }
+ resetStreamingState(s, conversationId);
+ });
+
+ try {
+ const executionId = await regenerateMessage(messageId);
+ const ctrl = newStreamController(conversationId);
+ await runStreamingLoop(executionId, {
+ conversationId,
+ set,
+ signal: ctrl.signal,
+ });
+ streamControllers.delete(conversationId);
+ if (!hasPendingInput(conversationId, get)) {
+ finalizeStreamingMessage(conversationId, set, get);
+ }
+ } catch (err) {
+ if (err instanceof DOMException && err.name === 'AbortError') {
+ return;
+ }
+ console.error('[AIAssistant] regenerateAssistantMessage failed:', err);
+ finalizeStreamingError(
+ conversationId,
+ 'Something went wrong while regenerating the response. Please try again.',
+ set,
+ );
+ }
+ },
+
+ submitMessageFeedback: async (
+ messageId: string,
+ rating: FeedbackRating,
+ comment?: string,
+ ): Promise<void> => {
+ const { activeConversationId } = get();
+ if (!activeConversationId) {
+ return;
+ }
+
+ set((s) => {
+ const conv = s.conversations[activeConversationId];
+ if (!conv) {
+ return;
+ }
+ const msg = conv.messages.find((m) => m.id === messageId);
+ if (msg) {
+ msg.feedbackRating = rating;
+ }
+ });
+
+ try {
+ await submitFeedback(messageId, rating, comment);
+ } catch (err) {
+ console.error('[AIAssistant] submitMessageFeedback failed:', err);
+ }
+ },
+
+ submitClarification: async (
+ conversationId: string,
+ clarificationId: string,
+ answers: Record<string, unknown>,
+ ): Promise<void> => {
+ set((s) => {
+ const st = s.streams[conversationId];
+ if (st) {
+ st.pendingClarification = null;
+ st.isStreaming = true;
+ st.streamingStatus = 'resumed';
+ } else {
+ resetStreamingState(s, conversationId);
+ }
+ });
+
+ try {
+ const executionId = await clarifyExecution(clarificationId, answers);
+ const ctrl = newStreamController(conversationId);
+ await runStreamingLoop(executionId, {
+ conversationId,
+ set,
+ signal: ctrl.signal,
+ });
+ streamControllers.delete(conversationId);
+ if (!hasPendingInput(conversationId, get)) {
+ finalizeStreamingMessage(conversationId, set, get);
+ }
+ } catch (err) {
+ if (err instanceof DOMException && err.name === 'AbortError') {
+ return;
+ }
+ console.error('[AIAssistant] submitClarification failed:', err);
+ finalizeStreamingError(
+ conversationId,
+ 'Something went wrong while processing your answers. Please try again.',
+ set,
+ );
+ }
+ },
+ })),
+ {
+ name: 'ai-assistant-store',
+ version: 3,
+ partialize: (state) => ({
+ isDrawerOpen: state.isDrawerOpen,
+ answeredBlocks: state.answeredBlocks,
+ // Persist the active conversation so a page reload returns the
+ // user to the same thread instead of dumping them into a new one.
+ activeConversationId: state.activeConversationId,
+ }),
+ migrate: () => ({
+ isDrawerOpen: false,
+ answeredBlocks: {},
+ activeConversationId: null,
+ }),
+ onRehydrateStorage:
+ () =>
+ (state: any): void => {
+ if (!state) {
+ return;
+ }
+
+ // Restored an active conversation id: prime an empty entry so
+ // the UI has something to render immediately, and flag the
+ // store as loading so ConversationView shows a skeleton —
+ // not an empty thread — while AppLayout's fetchThreads
+ // catches up. Without this flag the user sees a flicker of
+ // "empty conversation" before the skeleton appears.
+ //
+ // We can't call loadThread here — rehydrate fires at module
+ // load, long before useIsAIAssistantEnabled has set the URL.
+ if (state.activeConversationId) {
+ const id = state.activeConversationId;
+ if (!state.conversations[id]) {
+ state.conversations[id] = {
+ id,
+ messages: [],
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ isHydrating: true,
+ };
+ } else {
+ state.conversations[id].isHydrating = true;
+ }
+ state.isLoadingThreads = true;
+ return;
+ }
+
+ if (state.isDrawerOpen || state.isModalOpen) {
+ state.startNewConversation();
+ }
+ },
+ },
+ ),
+);
+
+// Standalone imperative accessors
+export const openAIAssistant = (): void =>
+ useAIAssistantStore.getState().openDrawer();
+export const closeAIAssistant = (): void =>
+ useAIAssistantStore.getState().closeDrawer();
+export const openAIAssistantModal = (): void =>
+ useAIAssistantStore.getState().openModal();
+export const closeAIAssistantModal = (): void =>
+ useAIAssistantStore.getState().closeModal();
+export const minimizeAIAssistantModal = (): void =>
+ useAIAssistantStore.getState().minimizeModal();
diff --git a/frontend/src/container/AIAssistant/types.ts b/frontend/src/container/AIAssistant/types.ts
new file mode 100644
index 0000000000..57eae04a48
--- /dev/null
+++ b/frontend/src/container/AIAssistant/types.ts
@@ -0,0 +1,167 @@
+/**
+ * UI types for the AI Assistant.
+ *
+ * Wherever the OpenAPI-generated DTOs in
+ * `src/api/ai-assistant/sigNozAIAssistantAPI.schemas.ts`
+ * already capture the right shape, this module re-exports them.
+ *
+ * A type is defined locally only when the UI needs a different shape than
+ * the API — typically because:
+ * • the DTO is too loose to render against (e.g. `blocks` is `unknown[]`)
+ * • the UI uses numeric millisecond timestamps instead of ISO strings
+ * • the UI mints a synthetic `id` before the server has assigned a `threadId`
+ * • client-only state (attachments, streaming aggregations) has no API form
+ */
+import type {
+ ApprovalEventDTO,
+ ClarificationEventDTO,
+ FeedbackRatingDTO,
+ MessageActionDTO,
+ MessageActionKindDTO,
+} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
+
+/** Client-only file attachment — no API equivalent (uploads happen via data URLs). */
+export interface MessageAttachment {
+ name: string;
+ type: string;
+ /** data URI for images, or a download URL for other files */
+ dataUrl: string;
+}
+
+/** Narrowed from DTO `MessageSummaryDTO.role: string`. The UI only cares about user/assistant. */
+export type MessageRole = 'user' | 'assistant';
+
+/** String-literal view of `MessageActionKindDTO` for ergonomic comparisons in switch statements. */
+export type ActionKind = `${MessageActionKindDTO}`;
+
+/** String-literal view of `FeedbackRatingDTO` so call-sites can pass `'positive'`/`'negative'` directly. */
+export type FeedbackRating = `${FeedbackRatingDTO}`;
+
+// ---------------------------------------------------------------------------
+// Message blocks — the DTO models blocks as `unknown[]`. The UI needs a
+// typed discriminated union to render each block kind.
+// ---------------------------------------------------------------------------
+
+export interface TextBlock {
+ type: 'text';
+ content: string;
+}
+
+export interface ThinkingBlock {
+ type: 'thinking';
+ content: string;
+}
+
+export interface ToolCallBlock {
+ type: 'tool_call';
+ toolCallId: string;
+ toolName: string;
+ toolInput: unknown;
+ result?: unknown;
+ success?: boolean;
+ /**
+ * Optional human-friendly title from the `ToolCallEventDTO`. When present
+ * the UI prefers it over a derived label built from `toolName`.
+ */
+ displayText?: string | null;
+}
+
+export type MessageBlock = TextBlock | ThinkingBlock | ToolCallBlock;
+
+/**
+ * UI shape for an assistant or user message. Differs from `MessageSummaryDTO`:
+ * • `id` instead of `messageId`
+ * • `createdAt` is a millisecond epoch instead of ISO string
+ * • `blocks` is the typed discriminated union above
+ * • streaming-only fields are excluded (those live in `ConversationStreamState`)
+ */
+export interface Message {
+ id: string;
+ role: MessageRole;
+ content: string;
+ attachments?: MessageAttachment[];
+ /** Ordered content blocks for structured rendering of assistant replies. */
+ blocks?: MessageBlock[];
+ /** Suggested follow-up actions returned by the assistant (final message only). */
+ actions?: MessageActionDTO[];
+ /** Persisted feedback rating — set after user votes and the API confirms. */
+ feedbackRating?: FeedbackRating | null;
+ createdAt: number;
+}
+
+/**
+ * UI shape for a conversation. Differs from `ThreadDetailResponseDTO`:
+ * • UI-minted `id` (assigned before the server returns a `threadId`)
+ * • `createdAt`/`updatedAt` are ms epochs
+ * • `messages` is the typed `Message[]` above
+ */
+export interface Conversation {
+ id: string;
+ /** Opaque thread ID assigned by the backend after first message. */
+ threadId?: string;
+ messages: Message[];
+ createdAt: number;
+ updatedAt?: number;
+ title?: string;
+ /** When true, thread is hidden from the main list and shown under Archived. */
+ archived?: boolean;
+ /**
+ * Set transiently on rehydrate when we restore an empty entry for the
+ * persisted active conversation. Cleared once `fetchThreads` resolves —
+ * either by the entry being overwritten with the server-mapped one, or
+ * by an explicit cleanup pass for ids the server doesn't know. Lets the
+ * UI distinguish "loading the previous thread" from "fresh new chat" so
+ * the skeleton is shown only in the former case.
+ */
+ isHydrating?: boolean;
+}
+
+// ---------------------------------------------------------------------------
+// Streaming-only types — live during an active SSE stream, never persisted.
+// No DTO equivalents: these aggregate multiple SSE event DTOs into UI-friendly
+// records (e.g. one StreamingToolCall combines a `tool_call` + `tool_result`).
+// ---------------------------------------------------------------------------
+
+/** A single tool invocation tracked during streaming. */
+export interface StreamingToolCall {
+ /** Matches the toolName field in SSE tool_call / tool_result events. */
+ toolName: string;
+ input: unknown;
+ result?: unknown;
+ /** True once the corresponding tool_result event has been received. */
+ done: boolean;
+ /**
+ * Optional human-friendly title from the `ToolCallEventDTO`. When present
+ * the UI prefers it over a derived label built from `toolName`.
+ */
+ displayText?: string | null;
+}
+
+/**
+ * An ordered item in the streaming event timeline.
+ * Text and tool calls are interleaved in arrival order so the UI renders
+ * them chronologically rather than grouping all tools above all text.
+ */
+export type StreamingEventItem =
+ | { kind: 'text'; content: string }
+ | { kind: 'thinking'; content: string }
+ | { kind: 'tool'; toolCall: StreamingToolCall };
+
+/**
+ * Per-conversation streaming state. Present in the store's `streams` map only
+ * while active. `pendingApproval`/`pendingClarification` are the SSE event
+ * DTOs straight from the wire; the persisted summary DTOs (returned by
+ * `GET /threads/{id}`) are structurally compatible and are assigned in
+ * verbatim during cold-start.
+ */
+export interface ConversationStreamState {
+ isStreaming: boolean;
+ streamingContent: string;
+ streamingStatus: string;
+ streamingEvents: StreamingEventItem[];
+ streamingMessageId: string | null;
+ /** Actions sent on the final SSE `message` event (`done: true`). */
+ streamingActions: MessageActionDTO[] | null;
+ pendingApproval: ApprovalEventDTO | null;
+ pendingClarification: ClarificationEventDTO | null;
+}
diff --git a/frontend/src/container/AppLayout/AppLayout.styles.scss b/frontend/src/container/AppLayout/AppLayout.styles.scss
index fdad36fcfb..a474a9f066 100644
--- a/frontend/src/container/AppLayout/AppLayout.styles.scss
+++ b/frontend/src/container/AppLayout/AppLayout.styles.scss
@@ -48,14 +48,13 @@
}
.app-content {
- width: calc(100% - 54px); // width of the sidebar
+ flex: 1;
+ min-width: 0; // allow shrinking below natural width when AI panel is open
z-index: 0;
background: var(--l1-background);
- margin: 0 auto;
-
&.full-screen-content {
- width: 100% !important;
+ width: 100%;
}
.content-container {
@@ -67,12 +66,6 @@
width: 100%;
}
}
-
- &.side-nav-pinned {
- .app-content {
- width: calc(100% - 240px);
- }
- }
}
.chat-support-gateway {
diff --git a/frontend/src/container/AppLayout/index.tsx b/frontend/src/container/AppLayout/index.tsx
index 12d50f7f3d..6beaf8e971 100644
--- a/frontend/src/container/AppLayout/index.tsx
+++ b/frontend/src/container/AppLayout/index.tsx
@@ -14,6 +14,7 @@ import { useDispatch, useSelector } from 'react-redux';
import { useLocation } from 'react-router-dom';
import * as Sentry from '@sentry/react';
import { Toaster } from '@signozhq/ui/sonner';
+import { TooltipProvider } from '@signozhq/ui/tooltip';
import { Flex } from 'antd';
import getLocalStorageApi from 'api/browser/localstorage/get';
import setLocalStorageApi from 'api/browser/localstorage/set';
@@ -36,12 +37,16 @@ import { LOCALSTORAGE } from 'constants/localStorage';
import ROUTES from 'constants/routes';
import { GlobalShortcuts } from 'constants/shortcuts/globalShortcuts';
import { USER_PREFERENCES } from 'constants/userPreferences';
+import AIAssistantModal from 'container/AIAssistant/AIAssistantModal';
+import AIAssistantPanel from 'container/AIAssistant/AIAssistantPanel';
+import { useAIAssistantStore } from 'container/AIAssistant/store/useAIAssistantStore';
import SideNav from 'container/SideNav';
import TopNav from 'container/TopNav';
import dayjs from 'dayjs';
import { useKeyboardHotkeys } from 'hooks/hotkeys/useKeyboardHotkeys';
import { useIsDarkMode } from 'hooks/useDarkMode';
import { useGetTenantLicense } from 'hooks/useGetTenantLicense';
+import { useIsAIAssistantEnabled } from 'hooks/useIsAIAssistantEnabled';
import { useNotifications } from 'hooks/useNotifications';
import useTabVisibility from 'hooks/useTabFocus';
import history from 'lib/history';
@@ -105,6 +110,19 @@ function AppLayout(props: AppLayoutProps): JSX.Element {
changelog,
} = useAppContext();
+ const isAIAssistantEnabled = useIsAIAssistantEnabled();
+ const fetchAIThreads = useAIAssistantStore((s) => s.fetchThreads);
+
+ // Bootstrap the AI Assistant thread list once the base URL is configured.
+ // Centralizing this here (rather than per-view) means the persisted active
+ // thread's messages reload reliably on refresh — `fetchThreads` itself
+ // hydrates the active conversation's messages after populating threadIds.
+ useEffect(() => {
+ if (isAIAssistantEnabled) {
+ void fetchAIThreads();
+ }
+ }, [isAIAssistantEnabled, fetchAIThreads]);
+
const { notifications } = useNotifications();
const [showPaymentFailedWarning, setShowPaymentFailedWarning] =
@@ -389,6 +407,7 @@ function AppLayout(props: AppLayoutProps): JSX.Element {
const pageTitle = t(routeKey);
const isPublicDashboard = pathname.startsWith('/public/dashboard/');
+ const isAIAssistantPage = pathname.startsWith('/ai-assistant/');
const renderFullScreen =
pathname === ROUTES.GET_STARTED ||
@@ -764,110 +783,121 @@ function AppLayout(props: AppLayoutProps): JSX.Element {
!showTrialExpiryBanner && showPaymentFailedWarning;
return (
- <Layout className={cx(isDarkMode ? 'darkMode dark' : 'lightMode')}>
- <Helmet>
- <title>{pageTitle}</title>
- </Helmet>
-
- {isLoggedIn && (
- <div className={cx('app-banner-wrapper')}>
- {SHOW_TRIAL_EXPIRY_BANNER && (
- <div className="trial-expiry-banner">
- You are in free trial period. Your free trial will end on{' '}
- <span>{getFormattedDate(trialInfo?.trialEnd || Date.now())}.</span>
- {user.role === USER_ROLES.ADMIN ? (
- <span>
- {' '}
- Please{' '}
- <a className="upgrade-link" onClick={handleUpgrade}>
- upgrade
- </a>
- to continue using SigNoz features.
- <span className="refresh-payment-status">
+ <TooltipProvider>
+ <Layout className={cx(isDarkMode ? 'darkMode dark' : 'lightMode')}>
+ <Helmet>
+ <title>{pageTitle}</title>
+ </Helmet>
+
+ {isLoggedIn && (
+ <div className={cx('app-banner-wrapper')}>
+ {SHOW_TRIAL_EXPIRY_BANNER && (
+ <div className="trial-expiry-banner">
+ You are in free trial period. Your free trial will end on{' '}
+ <span>{getFormattedDate(trialInfo?.trialEnd || Date.now())}.</span>
+ {user.role === USER_ROLES.ADMIN ? (
+ <span>
{' '}
- | Already upgraded? <RefreshPaymentStatus type="text" />
+ Please{' '}
+ <a className="upgrade-link" onClick={handleUpgrade}>
+ upgrade
+ </a>
+ to continue using SigNoz features.
+ <span className="refresh-payment-status">
+ {' '}
+ | Already upgraded? <RefreshPaymentStatus type="text" />
+ </span>
</span>
- </span>
- ) : (
- 'Please contact your administrator for upgrading to a paid plan.'
- )}
- </div>
- )}
+ ) : (
+ 'Please contact your administrator for upgrading to a paid plan.'
+ )}
+ </div>
+ )}
- {SHOW_WORKSPACE_RESTRICTED_BANNER && renderWorkspaceRestrictedBanner()}
+ {SHOW_WORKSPACE_RESTRICTED_BANNER && renderWorkspaceRestrictedBanner()}
- {SHOW_PAYMENT_FAILED_BANNER && (
- <div className="payment-failed-banner">
- Your bill payment has failed. Your workspace will get suspended on{' '}
- <span>
- {getFormattedDateWithMinutes(
- dayjs(activeLicense?.event_queue?.scheduled_at).unix() || Date.now(),
- )}
- .
- </span>
- {user.role === USER_ROLES.ADMIN ? (
+ {SHOW_PAYMENT_FAILED_BANNER && (
+ <div className="payment-failed-banner">
+ Your bill payment has failed. Your workspace will get suspended on{' '}
<span>
- {' '}
- Please{' '}
- <a className="upgrade-link" onClick={handleFailedPayment}>
- pay the bill
- </a>
- to continue using SigNoz features.
- <span className="refresh-payment-status">
+ {getFormattedDateWithMinutes(
+ dayjs(activeLicense?.event_queue?.scheduled_at).unix() || Date.now(),
+ )}
+ .
+ </span>
+ {user.role === USER_ROLES.ADMIN ? (
+ <span>
{' '}
- | Already paid? <RefreshPaymentStatus type="text" />
+ Please{' '}
+ <a className="upgrade-link" onClick={handleFailedPayment}>
+ pay the bill
+ </a>
+ to continue using SigNoz features.
+ <span className="refresh-payment-status">
+ {' '}
+ | Already paid? <RefreshPaymentStatus type="text" />
+ </span>
</span>
- </span>
- ) : (
- ' Please contact your administrator to pay the bill.'
- )}
- </div>
- )}
- </div>
- )}
-
- <Flex
- className={cx(
- 'app-layout',
- isDarkMode ? 'darkMode dark' : 'lightMode',
- isSideNavPinned ? 'side-nav-pinned' : '',
- SHOW_WORKSPACE_RESTRICTED_BANNER ? 'isWorkspaceRestricted' : '',
- SHOW_TRIAL_EXPIRY_BANNER ? 'isTrialExpired' : '',
- SHOW_PAYMENT_FAILED_BANNER ? 'isPaymentFailed' : '',
- )}
- >
- {isToDisplayLayout && !renderFullScreen && (
- <SideNav isPinned={isSideNavPinned} />
+ ) : (
+ ' Please contact your administrator to pay the bill.'
+ )}
+ </div>
+ )}
+ </div>
)}
- <div
- className={cx('app-content', {
- 'full-screen-content': renderFullScreen,
- })}
- data-overlayscrollbars-initialize
+
+ <Flex
+ className={cx(
+ 'app-layout',
+ isDarkMode ? 'darkMode dark' : 'lightMode',
+ isSideNavPinned ? 'side-nav-pinned' : '',
+ SHOW_WORKSPACE_RESTRICTED_BANNER ? 'isWorkspaceRestricted' : '',
+ SHOW_TRIAL_EXPIRY_BANNER ? 'isTrialExpired' : '',
+ SHOW_PAYMENT_FAILED_BANNER ? 'isPaymentFailed' : '',
+ )}
>
- <Sentry.ErrorBoundary
- fallback={<ErrorBoundaryFallback />}
- ref={errorBoundaryRef}
+ {isToDisplayLayout && !renderFullScreen && (
+ <SideNav isPinned={isSideNavPinned} />
+ )}
+ <div
+ className={cx('app-content', {
+ 'full-screen-content': renderFullScreen,
+ })}
+ data-overlayscrollbars-initialize
>
- <LayoutContent data-overlayscrollbars-initialize>
- <OverlayScrollbar>
- <ChildrenContainer>
- {isToDisplayLayout && !renderFullScreen && <TopNav />}
- {children}
- </ChildrenContainer>
- </OverlayScrollbar>
- </LayoutContent>
- </Sentry.ErrorBoundary>
- </div>
- </Flex>
-
- {showAddCreditCardModal && <ChatSupportGateway />}
- {showChangelogModal && changelog && (
- <ChangelogModal changelog={changelog} onClose={toggleChangelogModal} />
- )}
+ <Sentry.ErrorBoundary
+ fallback={<ErrorBoundaryFallback />}
+ ref={errorBoundaryRef}
+ >
+ <LayoutContent data-overlayscrollbars-initialize>
+ <OverlayScrollbar>
+ <ChildrenContainer>
+ {isToDisplayLayout && !renderFullScreen && !isAIAssistantPage && (
+ <TopNav />
+ )}
+ {children}
+ </ChildrenContainer>
+ </OverlayScrollbar>
+ </LayoutContent>
+ </Sentry.ErrorBoundary>
+ </div>
+
+ {isLoggedIn && isAIAssistantEnabled && (
+ <>
+ <AIAssistantPanel />
+ <AIAssistantModal />
+ </>
+ )}
+ </Flex>
+
+ {showAddCreditCardModal && <ChatSupportGateway />}
+ {showChangelogModal && changelog && (
+ <ChangelogModal changelog={changelog} onClose={toggleChangelogModal} />
+ )}
- <Toaster />
- </Layout>
+ <Toaster />
+ </Layout>
+ </TooltipProvider>
);
}
diff --git a/frontend/src/container/Home/Home.styles.scss b/frontend/src/container/Home/Home.styles.scss
index f55ec9cdc1..aea30a5084 100644
--- a/frontend/src/container/Home/Home.styles.scss
+++ b/frontend/src/container/Home/Home.styles.scss
@@ -39,6 +39,10 @@
}
.home-header-right {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+
.welcome-checklist-btn {
color: var(--l1-foreground);
diff --git a/frontend/src/container/Home/Home.tsx b/frontend/src/container/Home/Home.tsx
index 51b14dee1a..a540d92761 100644
--- a/frontend/src/container/Home/Home.tsx
+++ b/frontend/src/container/Home/Home.tsx
@@ -2,7 +2,14 @@
import React, { useCallback, useEffect, useState } from 'react';
import { useMutation, useQuery } from 'react-query';
import { Color } from '@signozhq/design-tokens';
-import { Compass, Dot, House, Plus, Wrench } from '@signozhq/icons';
+import {
+ ClipboardList,
+ Compass,
+ Dot,
+ House,
+ Plus,
+ Wrench,
+} from '@signozhq/icons';
import { Button } from '@signozhq/ui/button';
import { Popover } from 'antd';
import logEvent from 'api/common/logEvent';
@@ -10,6 +17,7 @@ import { useGetMetricsOnboardingStatus } from 'api/generated/services/metrics';
import listUserPreferences from 'api/v1/user/preferences/list';
import updateUserPreferenceAPI from 'api/v1/user/preferences/name/update';
import Header from 'components/Header/Header';
+import HeaderRightSection from 'components/HeaderRightSection/HeaderRightSection';
import { ENTITY_VERSION_V5 } from 'constants/app';
import { ORG_PREFERENCES } from 'constants/orgPreferences';
import { initialQueriesMap, PANEL_TYPES } from 'constants/queryBuilder';
@@ -34,11 +42,9 @@ import { popupContainer } from 'utils/selectPopupContainer';
import crackerUrl from '@/assets/Icons/cracker.svg';
import dashboardUrl from '@/assets/Icons/dashboard.svg';
-import spinnerHalfBlueUrl from '@/assets/Icons/spinner-half-blue.svg';
import wrenchUrl from '@/assets/Icons/wrench.svg';
import allInOneUrl from '@/assets/Images/allInOne.svg';
import allInOneLightModeUrl from '@/assets/Images/allInOneLightMode.svg';
-import dottedDividerUrl from '@/assets/Images/dotted-divider.svg';
import perilianBackgroundUrl from '@/assets/Images/perilianBackground.svg';
import AlertRules from './AlertRules/AlertRules';
@@ -279,6 +285,11 @@ export default function Home(): JSX.Element {
}
rightComponent={
<div className="home-header-right">
+ <HeaderRightSection
+ enableAnnouncements={false}
+ enableFeedback={false}
+ enableShare={false}
+ />
{isWelcomeChecklistSkipped && (
<Popover
placement="bottomRight"
@@ -299,17 +310,9 @@ export default function Home(): JSX.Element {
<Button
variant="solid"
color="secondary"
- size="sm"
- className="periscope-btn secondary welcome-checklist-btn"
+ prefix={<ClipboardList size={14} />}
>
- <img
- src={spinnerHalfBlueUrl}
- alt="spinner-half-blue"
- width={16}
- height={16}
- className="welcome-checklist-icon"
- />
- &nbsp; Welcome checklist
+ Welcome checklist
</Button>
</Popover>
)}
@@ -329,10 +332,6 @@ export default function Home(): JSX.Element {
isLoading={isLogsLoading || isTracesLoading}
/>
- <div className="divider">
- <img src={dottedDividerUrl} alt="divider" />
- </div>
-
<div className="active-ingestions-container">
{isLogsIngestionActive && (
<Card className="active-ingestion-card" size="small">
diff --git a/frontend/src/container/Integrations/Integrations.styles.scss b/frontend/src/container/Integrations/Integrations.styles.scss
index 54be5f2b72..3605c05c90 100644
--- a/frontend/src/container/Integrations/Integrations.styles.scss
+++ b/frontend/src/container/Integrations/Integrations.styles.scss
@@ -45,6 +45,7 @@
display: flex;
flex-direction: row;
justify-content: space-between;
+ flex-wrap: wrap;
align-items: center;
border-radius: 4px;
diff --git a/frontend/src/container/MetricsExplorer/Explorer/Explorer.tsx b/frontend/src/container/MetricsExplorer/Explorer/Explorer.tsx
index 0778c2cfbb..1cd27feef4 100644
--- a/frontend/src/container/MetricsExplorer/Explorer/Explorer.tsx
+++ b/frontend/src/container/MetricsExplorer/Explorer/Explorer.tsx
@@ -8,6 +8,7 @@ import { QueryBuilderV2 } from 'components/QueryBuilderV2/QueryBuilderV2';
import WarningPopover from 'components/WarningPopover/WarningPopover';
import { initialQueriesMap, PANEL_TYPES } from 'constants/queryBuilder';
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
+import { usePageActions } from 'container/AIAssistant/pageActions/usePageActions';
import ExplorerOptionWrapper from 'container/ExplorerOptions/ExplorerOptionWrapper';
import RightToolbarActions from 'container/QueryBuilder/components/ToolbarActions/RightToolbarActions';
import { QueryBuilderProps } from 'container/QueryBuilder/QueryBuilder.interfaces';
@@ -18,9 +19,15 @@ import {
ICurrentQueryData,
useHandleExplorerTabChange,
} from 'hooks/useHandleExplorerTabChange';
+import { useIsAIAssistantEnabled } from 'hooks/useIsAIAssistantEnabled';
import { useSafeNavigate } from 'hooks/useSafeNavigate';
import { isEmpty } from 'lodash-es';
import ErrorBoundaryFallback from 'pages/ErrorBoundaryFallback/ErrorBoundaryFallback';
+import {
+ metricsAddFilterAction,
+ metricsRunQueryAction,
+ metricsSaveViewAction,
+} from 'pages/MetricsExplorer/aiActions';
import { ExplorerViews } from 'pages/LogsExplorer/utils';
import { Warning } from 'types/api';
import { Dashboard } from 'types/api/dashboard/getAll';
@@ -51,9 +58,12 @@ function Explorer(): JSX.Element {
updateAllQueriesOperators,
currentQuery,
handleSetConfig,
+ handleSetQueryData,
+ redirectWithQueryBuilderData,
} = useQueryBuilder();
const { safeNavigate } = useSafeNavigate();
const { handleExplorerTabChange } = useHandleExplorerTabChange();
+ const isAIAssistantEnabled = useIsAIAssistantEnabled();
const [isMetricDetailsOpen, setIsMetricDetailsOpen] = useState(false);
const queryClient = useQueryClient();
@@ -212,6 +222,41 @@ function Explorer(): JSX.Element {
[handleSetConfig, handleExplorerTabChange],
);
+ // ─── AI Assistant page actions (only when license feature is on) ───────────
+ const aiActions = useMemo(
+ () =>
+ isAIAssistantEnabled
+ ? [
+ metricsRunQueryAction({
+ currentQuery,
+ handleSetQueryData,
+ redirectWithQueryBuilderData,
+ }),
+ metricsAddFilterAction({
+ currentQuery,
+ handleSetQueryData,
+ redirectWithQueryBuilderData,
+ }),
+ metricsSaveViewAction({
+ // POC stub — logs a save request; wire to real API when available
+ onSaveView: async (name) => {
+ // eslint-disable-next-line no-console
+ console.info('[AI Assistant] Save view requested:', name);
+ },
+ }),
+ ]
+ : [],
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [
+ isAIAssistantEnabled,
+ currentQuery,
+ handleSetQueryData,
+ redirectWithQueryBuilderData,
+ ],
+ );
+ usePageActions('metrics-explorer', aiActions);
+ // ───────────────────────────────────────────────────────────────────────────
+
const handleExport = useCallback(
(
dashboard: Dashboard | null,
diff --git a/frontend/src/container/RoutingPolicies/__tests__/testUtils.ts b/frontend/src/container/RoutingPolicies/__tests__/testUtils.ts
index 39b54de7d0..69657470f5 100644
--- a/frontend/src/container/RoutingPolicies/__tests__/testUtils.ts
+++ b/frontend/src/container/RoutingPolicies/__tests__/testUtils.ts
@@ -99,14 +99,17 @@ export function getAppContextMockState(
featureFlags: null,
orgPreferences: null,
userPreferences: null,
+ hostsData: null,
isLoggedIn: false,
org: null,
isFetchingUser: false,
isFetchingActiveLicense: false,
+ isFetchingHosts: false,
isFetchingFeatureFlags: false,
isFetchingOrgPreferences: false,
userFetchError: undefined,
activeLicenseFetchError: null,
+ hostsFetchError: undefined,
featureFlagsFetchError: undefined,
orgPreferencesFetchError: undefined,
changelog: null,
diff --git a/frontend/src/container/SideNav/SideNav.styles.scss b/frontend/src/container/SideNav/SideNav.styles.scss
index e842d14703..81e01e8de7 100644
--- a/frontend/src/container/SideNav/SideNav.styles.scss
+++ b/frontend/src/container/SideNav/SideNav.styles.scss
@@ -16,7 +16,7 @@
min-width: 54px;
width: 54px;
border-right: 1px solid var(--l1-border);
- background: var(--l1-background);
+ background: var(--l2-background);
padding-bottom: 48px;
transition:
@@ -472,7 +472,7 @@
background: linear-gradient(
180deg,
transparent 0%,
- var(--l1-background) 27.11%
+ var(--l2-background) 27.11%
);
&::-webkit-scrollbar {
@@ -569,6 +569,11 @@
}
}
+ // add sparkle animation to the ai assistant icon
+ .ai-assistant-icon {
+ color: var(--primary);
+ }
+
.nav-item-label {
display: none;
}
@@ -848,7 +853,6 @@
position: absolute;
height: 100%;
z-index: 10;
- background: var(--l1-background);
.brand-container {
padding: 8px 15px;
diff --git a/frontend/src/container/SideNav/SideNav.tsx b/frontend/src/container/SideNav/SideNav.tsx
index cb433f2bde..f7f80ee67d 100644
--- a/frontend/src/container/SideNav/SideNav.tsx
+++ b/frontend/src/container/SideNav/SideNav.tsx
@@ -34,9 +34,11 @@ import { FeatureKeys } from 'constants/features';
import ROUTES from 'constants/routes';
import { GlobalShortcuts } from 'constants/shortcuts/globalShortcuts';
import { USER_PREFERENCES } from 'constants/userPreferences';
+import { useAIAssistantStore } from 'container/AIAssistant/store/useAIAssistantStore';
import { useKeyboardHotkeys } from 'hooks/hotkeys/useKeyboardHotkeys';
import useComponentPermission from 'hooks/useComponentPermission';
import { useGetTenantLicense } from 'hooks/useGetTenantLicense';
+import { useIsAIAssistantEnabled } from 'hooks/useIsAIAssistantEnabled';
import { useNotifications } from 'hooks/useNotifications';
import history from 'lib/history';
import { isArray } from 'lodash-es';
@@ -77,6 +79,7 @@ import {
helpSupportDropdownMenuItems as DefaultHelpSupportDropdownMenuItems,
helpSupportMenuItem,
primaryMenuItems,
+ aiAssistantMenuItem,
} from './menuItems';
import NavItem from './NavItem/NavItem';
import {
@@ -221,6 +224,10 @@ function SideNav({ isPinned }: { isPinned: boolean }): JSX.Element {
const [licenseTag, setLicenseTag] = useState('');
const isAdmin = user.role === USER_ROLES.ADMIN;
const isEditor = user.role === USER_ROLES.EDITOR;
+ const isAIAssistantEnabled = useIsAIAssistantEnabled();
+ const aiAssistantActiveConversationId = useAIAssistantStore(
+ (s) => s.activeConversationId,
+ );
// Compute initial pinned items and secondary menu items synchronously to avoid flash
const computedPinnedMenuItems = useMemo(() => {
@@ -625,6 +632,22 @@ function SideNav({ isPinned }: { isPinned: boolean }): JSX.Element {
}
} else if (item.key === 'quick-search') {
openCmdK();
+ } else if (item.key === aiAssistantMenuItem.key) {
+ // Resume the active conversation when one exists — without this
+ // every sidenav click hits `/ai-assistant/new` which the page
+ // resolves by spawning a fresh thread. Only fall back to /new
+ // when there's no active conversation to resume.
+ const aiPath = aiAssistantActiveConversationId
+ ? ROUTES.AI_ASSISTANT.replace(
+ ':conversationId',
+ aiAssistantActiveConversationId,
+ )
+ : aiAssistantMenuItem.key;
+ if (isModifierKeyPressed(event)) {
+ openInNewTab(aiPath);
+ } else {
+ history.push(aiPath);
+ }
} else if (item) {
onClickHandler(item?.key as string, event);
}
@@ -1156,6 +1179,8 @@ function SideNav({ isPinned }: { isPinned: boolean }): JSX.Element {
<div className="nav-bottom-section">
<div className="secondary-nav-items">
+ {isAIAssistantEnabled && renderNavItems([aiAssistantMenuItem], false)}
+
<div className="nav-dropdown-item">
<Dropdown
menu={{
diff --git a/frontend/src/container/SideNav/menuItems.tsx b/frontend/src/container/SideNav/menuItems.tsx
index d9afa05730..ea50f25f2b 100644
--- a/frontend/src/container/SideNav/menuItems.tsx
+++ b/frontend/src/container/SideNav/menuItems.tsx
@@ -81,6 +81,22 @@ export const helpSupportMenuItem = {
icon: <MessageSquareText size={16} />,
};
+// The AI Assistant route is parameterized as `/ai-assistant/:conversationId`.
+// Sending the user to `/ai-assistant/new` triggers the page's fallback that
+// spawns a fresh conversation and replaces the URL with the real id, so
+// every sidenav click starts a new chat (the in-page history sidebar lets
+// the user resume earlier ones). Using a stable concrete path also lets
+// the active-highlight map below resolve `/ai-assistant/<any id>` back to
+// this menu key.
+const AI_ASSISTANT_NAV_KEY = '/ai-assistant/new';
+
+export const aiAssistantMenuItem = {
+ key: AI_ASSISTANT_NAV_KEY,
+ label: 'AI Assistant',
+ icon: <Sparkles size={16} className="ai-assistant-icon" />,
+ itemKey: 'ai-assistant',
+};
+
export const shortcutMenuItem = {
key: ROUTES.SHORTCUTS,
label: 'Keyboard Shortcuts',
@@ -547,6 +563,10 @@ export const NEW_ROUTES_MENU_ITEM_KEY_MAP: Record<string, string> = {
ROUTES.INFRASTRUCTURE_MONITORING_HOSTS,
[ROUTES.API_MONITORING_BASE]: ROUTES.API_MONITORING,
[ROUTES.MESSAGING_QUEUES_BASE]: ROUTES.MESSAGING_QUEUES_OVERVIEW,
+ // `getActiveMenuKeyFromPath` strips the URL down to its first segment;
+ // `/ai-assistant/<id>` reduces to `/ai-assistant`, which we point back
+ // to the AI Assistant menu item's concrete key.
+ '/ai-assistant': AI_ASSISTANT_NAV_KEY,
};
export default menuItems;
diff --git a/frontend/src/container/Toolbar/Toolbar.styles.scss b/frontend/src/container/Toolbar/Toolbar.styles.scss
index 8bfef11b10..408962060d 100644
--- a/frontend/src/container/Toolbar/Toolbar.styles.scss
+++ b/frontend/src/container/Toolbar/Toolbar.styles.scss
@@ -7,7 +7,7 @@
gap: 8px;
.rightActions {
- margin: 4px 0;
+ margin: 8px 0;
display: flex;
align-items: center;
gap: 4px;
diff --git a/frontend/src/hooks/dashboard/useGetAllDashboard.tsx b/frontend/src/hooks/dashboard/useGetAllDashboard.tsx
index 5ea3e01d6a..dfa753add0 100644
--- a/frontend/src/hooks/dashboard/useGetAllDashboard.tsx
+++ b/frontend/src/hooks/dashboard/useGetAllDashboard.tsx
@@ -6,10 +6,25 @@ import { SuccessResponseV2 } from 'types/api';
import { Dashboard } from 'types/api/dashboard/getAll';
import APIError from 'types/api/error';
-export const useGetAllDashboard = (): UseQueryResult<
- SuccessResponseV2<Dashboard[]>,
- APIError
-> => {
+interface UseGetAllDashboardOptions {
+ /**
+ * When false, the hook still subscribes to the React Query cache (so
+ * `data` reflects values populated by other callers and re-renders
+ * reactively) but does not trigger its own fetch on mount. Defaults to
+ * `true` to preserve the always-fetch behavior of the original hook.
+ */
+ enabled?: boolean;
+ /**
+ * Forwarded to the underlying `useQuery`. Pass `Infinity` (or a long
+ * duration) when the caller only wants to fetch on cache miss and not
+ * trigger a background refetch when fresh data is already cached.
+ */
+ staleTime?: number;
+}
+
+export const useGetAllDashboard = (
+ options?: UseGetAllDashboardOptions,
+): UseQueryResult<SuccessResponseV2<Dashboard[]>, APIError> => {
const { showErrorModal } = useErrorModal();
return useQuery<SuccessResponseV2<Dashboard[]>, APIError>({
@@ -18,5 +33,7 @@ export const useGetAllDashboard = (): UseQueryResult<
showErrorModal(error);
},
queryKey: REACT_QUERY_KEY.GET_ALL_DASHBOARDS,
+ enabled: options?.enabled ?? true,
+ ...(options?.staleTime !== undefined ? { staleTime: options.staleTime } : {}),
});
};
diff --git a/frontend/src/hooks/useIsAIAssistantEnabled.ts b/frontend/src/hooks/useIsAIAssistantEnabled.ts
new file mode 100644
index 0000000000..72c46bfd61
--- /dev/null
+++ b/frontend/src/hooks/useIsAIAssistantEnabled.ts
@@ -0,0 +1,48 @@
+import { setAIBackendUrl } from 'api/AIAPIInstance';
+import { useGetGlobalConfig } from 'api/generated/services/global';
+import { useAppContext } from 'providers/App/App';
+
+/** Returns the parsed URL string when valid, otherwise null. */
+function validUrl(value: string | null | undefined): string | null {
+ if (!value) {
+ return null;
+ }
+ try {
+ // eslint-disable-next-line no-new
+ new URL(value);
+ return value;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Treats `ai_assistant_url` from the global config as the on/off switch for
+ * AI assistant routes, header entry point, layout chrome, and the explorer
+ * page actions. Enabled iff the backend ships a URL that parses cleanly via
+ * the `URL` constructor — empty/null/garbage strings disable the feature.
+ *
+ * The global config fetch is gated on login state so we don't hit an
+ * authenticated endpoint while logged out. The hook itself is always
+ * called — gating happens inside the underlying query.
+ *
+ * Side-effect: pushes the URL into the shared AI axios instance during render.
+ * Done synchronously (not in a `useEffect`) because child components dispatch
+ * AI requests in their own mount effects, which fire before parent effects in
+ * React. A `useEffect` here would set the URL too late and the first
+ * fetchThreads/loadThread on refresh would race with an empty baseURL.
+ */
+export function useIsAIAssistantEnabled(): boolean {
+ const { isLoggedIn } = useAppContext();
+ const { data, isLoading, isError } = useGetGlobalConfig({
+ query: { enabled: isLoggedIn },
+ });
+ const url =
+ isLoggedIn && !isLoading && !isError
+ ? validUrl(data?.data?.ai_assistant_url)
+ : null;
+
+ setAIBackendUrl(url);
+
+ return !!url;
+}
diff --git a/frontend/src/pages/AIAssistantPage/AIAssistantPage.module.scss b/frontend/src/pages/AIAssistantPage/AIAssistantPage.module.scss
new file mode 100644
index 0000000000..87ca8eea4f
--- /dev/null
+++ b/frontend/src/pages/AIAssistantPage/AIAssistantPage.module.scss
@@ -0,0 +1,47 @@
+.page {
+ display: flex;
+ flex-direction: column;
+ height: 100%;
+ background: var(--l1-background);
+}
+
+.header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 12px;
+ border-bottom: 1px solid var(--l1-border);
+ flex-shrink: 0;
+ background: var(--l1-background);
+}
+
+.title {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ font-size: 16px;
+ font-weight: 600;
+ color: var(--l1-foreground);
+}
+
+.actions {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+}
+
+.body {
+ flex: 1;
+ display: flex;
+ flex-direction: row;
+ overflow: hidden;
+ width: 100%;
+}
+
+.chat {
+ flex: 1;
+ min-width: 0;
+ display: flex;
+ flex-direction: column;
+ overflow: hidden;
+}
diff --git a/frontend/src/pages/AIAssistantPage/AIAssistantPage.tsx b/frontend/src/pages/AIAssistantPage/AIAssistantPage.tsx
new file mode 100644
index 0000000000..2422e71d49
--- /dev/null
+++ b/frontend/src/pages/AIAssistantPage/AIAssistantPage.tsx
@@ -0,0 +1,112 @@
+import { useCallback, useEffect, useRef } from 'react';
+import { useHistory, useParams } from 'react-router-dom';
+
+import ROUTES from 'constants/routes';
+
+import ConversationView from 'container/AIAssistant/ConversationView';
+import { useAIAssistantStore } from 'container/AIAssistant/store/useAIAssistantStore';
+import { VariantContext } from 'container/AIAssistant/VariantContext';
+import { Sparkles } from '@signozhq/icons';
+
+import styles from './AIAssistantPage.module.scss';
+import ConversationsList from 'container/AIAssistant/components/ConversationsList';
+
+interface RouteParams {
+ conversationId: string;
+}
+
+export default function AIAssistantPage(): JSX.Element {
+ const history = useHistory();
+ const { conversationId } = useParams<RouteParams>();
+
+ const conversations = useAIAssistantStore((s) => s.conversations);
+ const activeConversationId = useAIAssistantStore(
+ (s) => s.activeConversationId,
+ );
+ const setActiveConversation = useAIAssistantStore(
+ (s) => s.setActiveConversation,
+ );
+ const startNewConversation = useAIAssistantStore(
+ (s) => s.startNewConversation,
+ );
+
+ // Keep a ref so the effect can read latest conversations without re-firing
+ // when startNewConversation mutates the store mid-effect.
+ const conversationsRef = useRef(conversations);
+ conversationsRef.current = conversations;
+
+ useEffect(() => {
+ if (conversationsRef.current[conversationId]) {
+ setActiveConversation(conversationId);
+ } else {
+ const newId = startNewConversation();
+ history.replace(ROUTES.AI_ASSISTANT.replace(':conversationId', newId));
+ }
+ // Only re-run when the URL param changes, not when conversations mutates.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [conversationId]);
+
+ // Keep the URL in lock-step with `activeConversationId`. The first send on a
+ // new conversation re-keys the store entry from the local client UUID to the
+ // backend threadId; without this sync the URL would still point at the now-
+ // deleted client UUID, leaving `<ConversationView>` unmounted until reload.
+ useEffect(() => {
+ if (
+ activeConversationId &&
+ activeConversationId !== conversationId &&
+ conversations[activeConversationId]
+ ) {
+ history.replace(
+ ROUTES.AI_ASSISTANT.replace(':conversationId', activeConversationId),
+ );
+ }
+ }, [activeConversationId, conversationId, conversations, history]);
+
+ // When conversations sidebar selects a thread, navigate to it
+ const handleHistorySelect = useCallback(
+ (id: string) => {
+ history.push(ROUTES.AI_ASSISTANT.replace(':conversationId', id));
+ },
+ [history],
+ );
+
+ const handleNewConversation = useCallback(() => {
+ const newId = startNewConversation();
+ history.push(ROUTES.AI_ASSISTANT.replace(':conversationId', newId));
+ }, [startNewConversation, history]);
+
+ // Prefer the URL param, but fall back to the store's `activeConversationId`
+ // for the brief render after a re-key (client UUID → backend threadId), so
+ // the chat doesn't unmount while the URL sync effect catches up.
+ let activeId: string | null = null;
+ if (conversations[conversationId]) {
+ activeId = conversationId;
+ } else if (activeConversationId && conversations[activeConversationId]) {
+ activeId = activeConversationId;
+ }
+
+ return (
+ <VariantContext.Provider value="page">
+ <div className={styles.page}>
+ <div className={styles.header}>
+ <div className={styles.title}>
+ <Sparkles size={16} color="var(--primary)" />
+ <span>AI Assistant</span>
+ </div>
+ </div>
+
+ <div className={styles.body}>
+ <ConversationsList
+ onSelect={handleHistorySelect}
+ onNewConversation={handleNewConversation}
+ showAddNewConversation
+ />
+
+ <div className={styles.chat}>
+ {activeId && <ConversationView conversationId={activeId} />}
+ </div>
+ </div>
+ </div>
+ </VariantContext.Provider>
+ );
+}
diff --git a/frontend/src/pages/LogsExplorer/aiActions.ts b/frontend/src/pages/LogsExplorer/aiActions.ts
new file mode 100644
index 0000000000..2db897f710
--- /dev/null
+++ b/frontend/src/pages/LogsExplorer/aiActions.ts
@@ -0,0 +1,239 @@
+/**
+ * AI Assistant page-action factories for the Logs Explorer.
+ *
+ * Each factory closes over live page state/callbacks so that `execute()`
+ * always operates on the current query. The page component instantiates these
+ * with `useMemo` and passes them to `usePageActions`.
+ *
+ * Filter flow: the V5 query-builder UI binds the WHERE clause CodeMirror
+ * editor to `currentQuery.builder.queryData[0].filter.expression`. So we
+ * derive the expression from our items via `convertFiltersToExpression`
+ * (the same helper `useGetCompositeQueryParam` uses on URL parse) and push
+ * BOTH `filters.items` and `filter.expression` into the QueryBuilder
+ * provider via `handleSetQueryData`. We then call `redirectWithQueryBuilderData`
+ * so the change persists in the URL — and because the items + expression we
+ * write match what the URL parser would derive from items alone, the post-
+ * navigate state stays consistent with the immediate UI update.
+ */
+
+import { convertFiltersToExpression } from 'components/QueryBuilderV2/utils';
+import {
+ aiFilterToTagFilterItem,
+ FILTER_OP_ENUM,
+ FILTER_VALUE_DESCRIPTION,
+ FilterDeps,
+ replaceFirstQueryData,
+} from 'container/AIAssistant/pageActions/builderQueryHelpers';
+import {
+ ActionResult,
+ PageAction,
+} from 'container/AIAssistant/pageActions/types';
+import {
+ IBuilderQuery,
+ TagFilterItem,
+} from 'types/api/queryBuilder/queryBuilderData';
+
+interface AIFilter {
+ key: string;
+ op: string;
+ value: string;
+}
+
+interface RunQueryParams {
+ filters: AIFilter[];
+}
+
+interface AddFilterParams {
+ key: string;
+ op: string;
+ value: string;
+}
+
+interface ChangeViewParams {
+ view: 'list' | 'timeseries' | 'table';
+}
+
+interface SaveViewParams {
+ name: string;
+}
+
+/**
+ * Replace all active filters and navigate to the updated query URL
+ * (which makes the WHERE clause reflect the new filters and triggers a re-run).
+ */
+export function logsRunQueryAction(
+ deps: FilterDeps,
+): PageAction<RunQueryParams> {
+ return {
+ id: 'logs.runQuery',
+ description: 'Replace the active log filters and re-run the query',
+ parameters: {
+ type: 'object',
+ properties: {
+ filters: {
+ type: 'array',
+ description: 'Replacement filter list',
+ items: {
+ type: 'object',
+ properties: {
+ key: {
+ type: 'string',
+ description: 'Attribute key, e.g. severity_text',
+ },
+ op: {
+ type: 'string',
+ enum: [...FILTER_OP_ENUM],
+ },
+ value: {
+ type: 'string',
+ description: FILTER_VALUE_DESCRIPTION,
+ },
+ },
+ required: ['key', 'op', 'value'],
+ },
+ },
+ },
+ required: ['filters'],
+ },
+ autoApply: true,
+ execute: async ({ filters }): Promise<ActionResult> => {
+ const baseQuery = deps.currentQuery.builder.queryData[0];
+ if (!baseQuery) {
+ throw new Error('No active query found in Logs Explorer.');
+ }
+
+ const tagItems = filters.map(aiFilterToTagFilterItem);
+ const newFilters = { items: tagItems, op: 'AND' };
+ const updatedBuilderQuery: IBuilderQuery = {
+ ...baseQuery,
+ filters: newFilters,
+ filter: convertFiltersToExpression(newFilters),
+ };
+
+ // Push to in-memory state first so the WHERE clause re-renders without
+ // waiting on a URL round-trip. Then sync URL for persistence/sharing.
+ deps.handleSetQueryData(0, updatedBuilderQuery);
+ deps.redirectWithQueryBuilderData(
+ replaceFirstQueryData(deps.currentQuery, updatedBuilderQuery),
+ );
+
+ return {
+ summary: `Query updated with ${filters.length} filter(s) and re-run.`,
+ };
+ },
+ getContext: (): Record<string, unknown> => ({
+ filters:
+ deps.currentQuery.builder.queryData[0]?.filters?.items?.map(
+ (f: TagFilterItem) => ({
+ key: f.key?.key,
+ op: f.op,
+ value: f.value,
+ }),
+ ) ?? [],
+ }),
+ };
+}
+
+/**
+ * Append a single filter to the existing query and navigate to the updated URL.
+ */
+export function logsAddFilterAction(
+ deps: FilterDeps,
+): PageAction<AddFilterParams> {
+ return {
+ id: 'logs.addFilter',
+ description: 'Add a single filter to the current log query and re-run',
+ parameters: {
+ type: 'object',
+ properties: {
+ key: {
+ type: 'string',
+ description: 'Attribute key, e.g. severity_text',
+ },
+ op: {
+ type: 'string',
+ enum: [...FILTER_OP_ENUM],
+ },
+ value: {
+ type: 'string',
+ description: FILTER_VALUE_DESCRIPTION,
+ },
+ },
+ required: ['key', 'op', 'value'],
+ },
+ autoApply: true,
+ execute: async ({ key, op, value }): Promise<ActionResult> => {
+ const baseQuery = deps.currentQuery.builder.queryData[0];
+ if (!baseQuery) {
+ throw new Error('No active query found in Logs Explorer.');
+ }
+
+ const existing = baseQuery.filters?.items ?? [];
+ const newItem = aiFilterToTagFilterItem({ key, op, value });
+ const newFilters = { items: [...existing, newItem], op: 'AND' };
+ const updatedBuilderQuery: IBuilderQuery = {
+ ...baseQuery,
+ filters: newFilters,
+ filter: convertFiltersToExpression(newFilters),
+ };
+
+ deps.handleSetQueryData(0, updatedBuilderQuery);
+ deps.redirectWithQueryBuilderData(
+ replaceFirstQueryData(deps.currentQuery, updatedBuilderQuery),
+ );
+
+ return { summary: `Filter added: ${key} ${op} "${value}". Query re-run.` };
+ },
+ };
+}
+
+/**
+ * Switch the explorer between list / timeseries / table views.
+ */
+export function logsChangeViewAction(deps: {
+ onChangeView: (view: 'list' | 'timeseries' | 'table') => void;
+}): PageAction<ChangeViewParams> {
+ return {
+ id: 'logs.changeView',
+ description:
+ 'Switch the Logs Explorer between list, timeseries, and table views',
+ parameters: {
+ type: 'object',
+ properties: {
+ view: {
+ type: 'string',
+ enum: ['list', 'timeseries', 'table'],
+ description: 'The panel view to switch to',
+ },
+ },
+ required: ['view'],
+ },
+ execute: async ({ view }): Promise<ActionResult> => {
+ deps.onChangeView(view);
+ return { summary: `Switched to the "${view}" view.` };
+ },
+ };
+}
+
+/**
+ * Save the current query as a named view (stub — wires to real API when available).
+ */
+export function logsSaveViewAction(deps: {
+ onSaveView: (name: string) => Promise<void>;
+}): PageAction<SaveViewParams> {
+ return {
+ id: 'logs.saveView',
+ description: 'Save the current log query as a named view',
+ parameters: {
+ type: 'object',
+ properties: {
+ name: { type: 'string', description: 'Name for the saved view' },
+ },
+ required: ['name'],
+ },
+ execute: async ({ name }): Promise<ActionResult> => {
+ await deps.onSaveView(name);
+ return { summary: `View "${name}" saved.` };
+ },
+ };
+}
diff --git a/frontend/src/pages/LogsExplorer/index.tsx b/frontend/src/pages/LogsExplorer/index.tsx
index ad14e34d62..415b7eeccd 100644
--- a/frontend/src/pages/LogsExplorer/index.tsx
+++ b/frontend/src/pages/LogsExplorer/index.tsx
@@ -12,6 +12,7 @@ import { QuickFiltersSource, SignalType } from 'components/QuickFilters/types';
import WarningPopover from 'components/WarningPopover/WarningPopover';
import { LOCALSTORAGE } from 'constants/localStorage';
import { PANEL_TYPES } from 'constants/queryBuilder';
+import { usePageActions } from 'container/AIAssistant/pageActions/usePageActions';
import LogExplorerQuerySection from 'container/LogExplorerQuerySection';
import LogsExplorerViewsContainer from 'container/LogsExplorerViews';
import {
@@ -29,6 +30,7 @@ import {
ICurrentQueryData,
useHandleExplorerTabChange,
} from 'hooks/useHandleExplorerTabChange';
+import { useIsAIAssistantEnabled } from 'hooks/useIsAIAssistantEnabled';
import useUrlQueryData from 'hooks/useUrlQueryData';
import { defaultTo, isEmpty, isEqual, isNull } from 'lodash-es';
import ErrorBoundaryFallback from 'pages/ErrorBoundaryFallback/ErrorBoundaryFallback';
@@ -41,6 +43,12 @@ import {
panelTypeToExplorerView,
} from 'utils/explorerUtils';
+import {
+ logsAddFilterAction,
+ logsChangeViewAction,
+ logsRunQueryAction,
+ logsSaveViewAction,
+} from './aiActions';
import { ExplorerViews } from './utils';
import './LogsExplorer.styles.scss';
@@ -67,10 +75,18 @@ function LogsExplorer(): JSX.Element {
return true;
});
- const { handleRunQuery, handleSetConfig } = useQueryBuilder();
+ const {
+ handleRunQuery,
+ handleSetConfig,
+ currentQuery,
+ handleSetQueryData,
+ redirectWithQueryBuilderData,
+ } = useQueryBuilder();
const { handleExplorerTabChange } = useHandleExplorerTabChange();
+ const isAIAssistantEnabled = useIsAIAssistantEnabled();
+
const listQueryKeyRef = useRef<any>();
const chartQueryKeyRef = useRef<any>();
@@ -119,6 +135,45 @@ function LogsExplorer(): JSX.Element {
[handleSetConfig, handleExplorerTabChange, setSelectedView],
);
+ // ─── AI Assistant page actions (only when license feature is on) ───────────
+ const aiActions = useMemo(
+ () =>
+ isAIAssistantEnabled
+ ? [
+ logsRunQueryAction({
+ currentQuery,
+ handleSetQueryData,
+ redirectWithQueryBuilderData,
+ }),
+ logsAddFilterAction({
+ currentQuery,
+ handleSetQueryData,
+ redirectWithQueryBuilderData,
+ }),
+ logsChangeViewAction({
+ onChangeView: (view) => handleChangeSelectedView(view as ExplorerViews),
+ }),
+ logsSaveViewAction({
+ // POC stub — logs a save request; wire to real API when available
+ onSaveView: async (name) => {
+ // eslint-disable-next-line no-console
+ console.info('[AI Assistant] Save view requested:', name);
+ },
+ }),
+ ]
+ : [],
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [
+ isAIAssistantEnabled,
+ currentQuery,
+ handleSetQueryData,
+ redirectWithQueryBuilderData,
+ handleChangeSelectedView,
+ ],
+ );
+ usePageActions('logs-explorer', aiActions);
+ // ───────────────────────────────────────────────────────────────────────────
+
const handleFilterVisibilityChange = (): void => {
setLocalStorageApi(
LOCALSTORAGE.SHOW_LOGS_QUICK_FILTERS,
diff --git a/frontend/src/pages/MetricsExplorer/aiActions.ts b/frontend/src/pages/MetricsExplorer/aiActions.ts
new file mode 100644
index 0000000000..5bec1d134f
--- /dev/null
+++ b/frontend/src/pages/MetricsExplorer/aiActions.ts
@@ -0,0 +1,201 @@
+/**
+ * AI Assistant page-action factories for the Metrics Explorer.
+ *
+ * The metrics explorer renders a single timeseries view via QueryBuilderV2,
+ * so it exposes only filter-mutating actions (no `changeView`). Saving a
+ * view is included as a stub for parity with the logs/traces actions.
+ *
+ * See `pages/LogsExplorer/aiActions.ts` for the rationale behind writing
+ * BOTH `filters.items` and `filter.expression` and then re-using the same
+ * URL parser shape via `redirectWithQueryBuilderData`.
+ */
+
+import { convertFiltersToExpression } from 'components/QueryBuilderV2/utils';
+import {
+ aiFilterToTagFilterItem,
+ FILTER_OP_ENUM,
+ FILTER_VALUE_DESCRIPTION,
+ FilterDeps,
+ replaceFirstQueryData,
+} from 'container/AIAssistant/pageActions/builderQueryHelpers';
+import {
+ ActionResult,
+ PageAction,
+} from 'container/AIAssistant/pageActions/types';
+import {
+ IBuilderQuery,
+ TagFilterItem,
+} from 'types/api/queryBuilder/queryBuilderData';
+
+interface AIFilter {
+ key: string;
+ op: string;
+ value: string;
+}
+
+interface RunQueryParams {
+ filters: AIFilter[];
+}
+
+interface AddFilterParams {
+ key: string;
+ op: string;
+ value: string;
+}
+
+interface SaveViewParams {
+ name: string;
+}
+
+/**
+ * Replace all active label filters and navigate to the updated query URL
+ * (which makes the WHERE clause reflect the new filters and triggers a re-run).
+ */
+export function metricsRunQueryAction(
+ deps: FilterDeps,
+): PageAction<RunQueryParams> {
+ return {
+ id: 'metrics.runQuery',
+ description: 'Replace the active metric filters and re-run the query',
+ parameters: {
+ type: 'object',
+ properties: {
+ filters: {
+ type: 'array',
+ description: 'Replacement filter list',
+ items: {
+ type: 'object',
+ properties: {
+ key: {
+ type: 'string',
+ description: 'Label key, e.g. service_name, deployment_environment',
+ },
+ op: {
+ type: 'string',
+ enum: [...FILTER_OP_ENUM],
+ },
+ value: {
+ type: 'string',
+ description: FILTER_VALUE_DESCRIPTION,
+ },
+ },
+ required: ['key', 'op', 'value'],
+ },
+ },
+ },
+ required: ['filters'],
+ },
+ autoApply: true,
+ execute: async ({ filters }): Promise<ActionResult> => {
+ const baseQuery = deps.currentQuery.builder.queryData[0];
+ if (!baseQuery) {
+ throw new Error('No active query found in Metrics Explorer.');
+ }
+
+ const tagItems = filters.map(aiFilterToTagFilterItem);
+ const newFilters = { items: tagItems, op: 'AND' };
+ const updatedBuilderQuery: IBuilderQuery = {
+ ...baseQuery,
+ filters: newFilters,
+ filter: convertFiltersToExpression(newFilters),
+ };
+
+ deps.handleSetQueryData(0, updatedBuilderQuery);
+ deps.redirectWithQueryBuilderData(
+ replaceFirstQueryData(deps.currentQuery, updatedBuilderQuery),
+ );
+
+ return {
+ summary: `Query updated with ${filters.length} filter(s) and re-run.`,
+ };
+ },
+ getContext: (): Record<string, unknown> => ({
+ filters:
+ deps.currentQuery.builder.queryData[0]?.filters?.items?.map(
+ (f: TagFilterItem) => ({
+ key: f.key?.key,
+ op: f.op,
+ value: f.value,
+ }),
+ ) ?? [],
+ }),
+ };
+}
+
+/**
+ * Append a single label filter to the existing metric query and navigate
+ * to the updated URL.
+ */
+export function metricsAddFilterAction(
+ deps: FilterDeps,
+): PageAction<AddFilterParams> {
+ return {
+ id: 'metrics.addFilter',
+ description: 'Add a single filter to the current metric query and re-run',
+ parameters: {
+ type: 'object',
+ properties: {
+ key: {
+ type: 'string',
+ description: 'Label key, e.g. service_name, deployment_environment',
+ },
+ op: {
+ type: 'string',
+ enum: [...FILTER_OP_ENUM],
+ },
+ value: {
+ type: 'string',
+ description: FILTER_VALUE_DESCRIPTION,
+ },
+ },
+ required: ['key', 'op', 'value'],
+ },
+ autoApply: true,
+ execute: async ({ key, op, value }): Promise<ActionResult> => {
+ const baseQuery = deps.currentQuery.builder.queryData[0];
+ if (!baseQuery) {
+ throw new Error('No active query found in Metrics Explorer.');
+ }
+
+ const existing = baseQuery.filters?.items ?? [];
+ const newItem = aiFilterToTagFilterItem({ key, op, value });
+ const newFilters = { items: [...existing, newItem], op: 'AND' };
+ const updatedBuilderQuery: IBuilderQuery = {
+ ...baseQuery,
+ filters: newFilters,
+ filter: convertFiltersToExpression(newFilters),
+ };
+
+ deps.handleSetQueryData(0, updatedBuilderQuery);
+ deps.redirectWithQueryBuilderData(
+ replaceFirstQueryData(deps.currentQuery, updatedBuilderQuery),
+ );
+
+ return { summary: `Filter added: ${key} ${op} "${value}". Query re-run.` };
+ },
+ };
+}
+
+/**
+ * Save the current metric query as a named view (stub — wires to real API
+ * when available).
+ */
+export function metricsSaveViewAction(deps: {
+ onSaveView: (name: string) => Promise<void>;
+}): PageAction<SaveViewParams> {
+ return {
+ id: 'metrics.saveView',
+ description: 'Save the current metric query as a named view',
+ parameters: {
+ type: 'object',
+ properties: {
+ name: { type: 'string', description: 'Name for the saved view' },
+ },
+ required: ['name'],
+ },
+ execute: async ({ name }): Promise<ActionResult> => {
+ await deps.onSaveView(name);
+ return { summary: `View "${name}" saved.` };
+ },
+ };
+}
diff --git a/frontend/src/pages/TraceDetailV2/TraceDetailV2.styles.scss b/frontend/src/pages/TraceDetailV2/TraceDetailV2.styles.scss
index 30a983a8a6..31a0e9736d 100644
--- a/frontend/src/pages/TraceDetailV2/TraceDetailV2.styles.scss
+++ b/frontend/src/pages/TraceDetailV2/TraceDetailV2.styles.scss
@@ -2,6 +2,13 @@
.funnel-icon {
transform: rotate(180deg);
}
+
+ .trace-detail-header-actions {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding-right: 16px;
+ }
.trace-module {
.ant-tabs-tab {
.tab-item {
diff --git a/frontend/src/pages/TraceDetailV2/index.tsx b/frontend/src/pages/TraceDetailV2/index.tsx
index 9cf559db02..5bf3c9e849 100644
--- a/frontend/src/pages/TraceDetailV2/index.tsx
+++ b/frontend/src/pages/TraceDetailV2/index.tsx
@@ -1,5 +1,6 @@
import { Tabs } from 'antd';
import logEvent from 'api/common/logEvent';
+import HeaderRightSection from 'components/HeaderRightSection/HeaderRightSection';
import ROUTES from 'constants/routes';
import history from 'lib/history';
import { Compass, Cone, TowerControl } from '@signozhq/icons';
@@ -24,6 +25,17 @@ function NewTraceDetail(props: INewTraceDetailProps): JSX.Element {
items={items}
animated
className="trace-module"
+ tabBarExtraContent={{
+ right: (
+ <div className="trace-detail-header-actions">
+ <HeaderRightSection
+ enableShare
+ enableFeedback
+ enableAnnouncements={false}
+ />
+ </div>
+ ),
+ }}
onTabClick={(activeKey): void => {
if (activeKey === 'saved-views') {
history.push(ROUTES.TRACES_SAVE_VIEWS);
diff --git a/frontend/src/pages/TracesExplorer/aiActions.ts b/frontend/src/pages/TracesExplorer/aiActions.ts
new file mode 100644
index 0000000000..806f1cca10
--- /dev/null
+++ b/frontend/src/pages/TracesExplorer/aiActions.ts
@@ -0,0 +1,235 @@
+/**
+ * AI Assistant page-action factories for the Traces Explorer.
+ *
+ * Mirrors the logs equivalents — each factory closes over live page
+ * state/callbacks so `execute()` always operates on the current query, and
+ * the page component instantiates them via `useMemo` + `usePageActions`.
+ *
+ * See `pages/LogsExplorer/aiActions.ts` for the rationale behind writing
+ * BOTH `filters.items` and `filter.expression` and then re-using the same
+ * URL parser shape via `redirectWithQueryBuilderData`.
+ */
+
+import { convertFiltersToExpression } from 'components/QueryBuilderV2/utils';
+import {
+ aiFilterToTagFilterItem,
+ FILTER_OP_ENUM,
+ FILTER_VALUE_DESCRIPTION,
+ FilterDeps,
+ replaceFirstQueryData,
+} from 'container/AIAssistant/pageActions/builderQueryHelpers';
+import {
+ ActionResult,
+ PageAction,
+} from 'container/AIAssistant/pageActions/types';
+import {
+ IBuilderQuery,
+ TagFilterItem,
+} from 'types/api/queryBuilder/queryBuilderData';
+
+interface AIFilter {
+ key: string;
+ op: string;
+ value: string;
+}
+
+interface RunQueryParams {
+ filters: AIFilter[];
+}
+
+interface AddFilterParams {
+ key: string;
+ op: string;
+ value: string;
+}
+
+type TracesView = 'list' | 'timeseries' | 'table' | 'trace';
+
+interface ChangeViewParams {
+ view: TracesView;
+}
+
+interface SaveViewParams {
+ name: string;
+}
+
+/**
+ * Replace all active span filters and navigate to the updated query URL
+ * (which makes the WHERE clause reflect the new filters and triggers a re-run).
+ */
+export function tracesRunQueryAction(
+ deps: FilterDeps,
+): PageAction<RunQueryParams> {
+ return {
+ id: 'traces.runQuery',
+ description: 'Replace the active trace filters and re-run the query',
+ parameters: {
+ type: 'object',
+ properties: {
+ filters: {
+ type: 'array',
+ description: 'Replacement filter list',
+ items: {
+ type: 'object',
+ properties: {
+ key: {
+ type: 'string',
+ description: 'Attribute key, e.g. service.name, http.status_code',
+ },
+ op: {
+ type: 'string',
+ enum: [...FILTER_OP_ENUM],
+ },
+ value: {
+ type: 'string',
+ description: FILTER_VALUE_DESCRIPTION,
+ },
+ },
+ required: ['key', 'op', 'value'],
+ },
+ },
+ },
+ required: ['filters'],
+ },
+ autoApply: true,
+ execute: async ({ filters }): Promise<ActionResult> => {
+ const baseQuery = deps.currentQuery.builder.queryData[0];
+ if (!baseQuery) {
+ throw new Error('No active query found in Traces Explorer.');
+ }
+
+ const tagItems = filters.map(aiFilterToTagFilterItem);
+ const newFilters = { items: tagItems, op: 'AND' };
+ const updatedBuilderQuery: IBuilderQuery = {
+ ...baseQuery,
+ filters: newFilters,
+ filter: convertFiltersToExpression(newFilters),
+ };
+
+ deps.handleSetQueryData(0, updatedBuilderQuery);
+ deps.redirectWithQueryBuilderData(
+ replaceFirstQueryData(deps.currentQuery, updatedBuilderQuery),
+ );
+
+ return {
+ summary: `Query updated with ${filters.length} filter(s) and re-run.`,
+ };
+ },
+ getContext: (): Record<string, unknown> => ({
+ filters:
+ deps.currentQuery.builder.queryData[0]?.filters?.items?.map(
+ (f: TagFilterItem) => ({
+ key: f.key?.key,
+ op: f.op,
+ value: f.value,
+ }),
+ ) ?? [],
+ }),
+ };
+}
+
+/**
+ * Append a single filter to the existing trace query and navigate to the
+ * updated URL.
+ */
+export function tracesAddFilterAction(
+ deps: FilterDeps,
+): PageAction<AddFilterParams> {
+ return {
+ id: 'traces.addFilter',
+ description: 'Add a single filter to the current trace query and re-run',
+ parameters: {
+ type: 'object',
+ properties: {
+ key: {
+ type: 'string',
+ description: 'Attribute key, e.g. service.name, http.status_code',
+ },
+ op: {
+ type: 'string',
+ enum: [...FILTER_OP_ENUM],
+ },
+ value: {
+ type: 'string',
+ description: FILTER_VALUE_DESCRIPTION,
+ },
+ },
+ required: ['key', 'op', 'value'],
+ },
+ autoApply: true,
+ execute: async ({ key, op, value }): Promise<ActionResult> => {
+ const baseQuery = deps.currentQuery.builder.queryData[0];
+ if (!baseQuery) {
+ throw new Error('No active query found in Traces Explorer.');
+ }
+
+ const existing = baseQuery.filters?.items ?? [];
+ const newItem = aiFilterToTagFilterItem({ key, op, value });
+ const newFilters = { items: [...existing, newItem], op: 'AND' };
+ const updatedBuilderQuery: IBuilderQuery = {
+ ...baseQuery,
+ filters: newFilters,
+ filter: convertFiltersToExpression(newFilters),
+ };
+
+ deps.handleSetQueryData(0, updatedBuilderQuery);
+ deps.redirectWithQueryBuilderData(
+ replaceFirstQueryData(deps.currentQuery, updatedBuilderQuery),
+ );
+
+ return { summary: `Filter added: ${key} ${op} "${value}". Query re-run.` };
+ },
+ };
+}
+
+/**
+ * Switch the traces explorer between list / timeseries / table / trace views.
+ */
+export function tracesChangeViewAction(deps: {
+ onChangeView: (view: TracesView) => void;
+}): PageAction<ChangeViewParams> {
+ return {
+ id: 'traces.changeView',
+ description:
+ 'Switch the Traces Explorer between list, timeseries, table, and trace views',
+ parameters: {
+ type: 'object',
+ properties: {
+ view: {
+ type: 'string',
+ enum: ['list', 'timeseries', 'table', 'trace'],
+ description: 'The panel view to switch to',
+ },
+ },
+ required: ['view'],
+ },
+ execute: async ({ view }): Promise<ActionResult> => {
+ deps.onChangeView(view);
+ return { summary: `Switched to the "${view}" view.` };
+ },
+ };
+}
+
+/**
+ * Save the current trace query as a named view (stub — wires to real API
+ * when available).
+ */
+export function tracesSaveViewAction(deps: {
+ onSaveView: (name: string) => Promise<void>;
+}): PageAction<SaveViewParams> {
+ return {
+ id: 'traces.saveView',
+ description: 'Save the current trace query as a named view',
+ parameters: {
+ type: 'object',
+ properties: {
+ name: { type: 'string', description: 'Name for the saved view' },
+ },
+ required: ['name'],
+ },
+ execute: async ({ name }): Promise<ActionResult> => {
+ await deps.onSaveView(name);
+ return { summary: `View "${name}" saved.` };
+ },
+ };
+}
diff --git a/frontend/src/pages/TracesExplorer/index.tsx b/frontend/src/pages/TracesExplorer/index.tsx
index b0c3f74e83..761db83d3c 100644
--- a/frontend/src/pages/TracesExplorer/index.tsx
+++ b/frontend/src/pages/TracesExplorer/index.tsx
@@ -13,6 +13,7 @@ import WarningPopover from 'components/WarningPopover/WarningPopover';
import { LOCALSTORAGE } from 'constants/localStorage';
import { AVAILABLE_EXPORT_PANEL_TYPES } from 'constants/panelTypes';
import { initialQueriesMap, PANEL_TYPES } from 'constants/queryBuilder';
+import { usePageActions } from 'container/AIAssistant/pageActions/usePageActions';
import ExplorerOptionWrapper from 'container/ExplorerOptions/ExplorerOptionWrapper';
import { useOptionsMenu } from 'container/OptionsMenu';
import LeftToolbarActions from 'container/QueryBuilder/components/ToolbarActions/LeftToolbarActions';
@@ -34,6 +35,7 @@ import {
ICurrentQueryData,
useHandleExplorerTabChange,
} from 'hooks/useHandleExplorerTabChange';
+import { useIsAIAssistantEnabled } from 'hooks/useIsAIAssistantEnabled';
import { useSafeNavigate } from 'hooks/useSafeNavigate';
import { isEmpty } from 'lodash-es';
import ErrorBoundaryFallback from 'pages/ErrorBoundaryFallback/ErrorBoundaryFallback';
@@ -50,6 +52,12 @@ import {
} from 'utils/explorerUtils';
import { v4 } from 'uuid';
+import {
+ tracesAddFilterAction,
+ tracesChangeViewAction,
+ tracesRunQueryAction,
+ tracesSaveViewAction,
+} from './aiActions';
import TimeSeriesView from './TimeSeriesView';
import './TracesExplorer.styles.scss';
@@ -61,8 +69,13 @@ function TracesExplorer(): JSX.Element {
handleRunQuery,
stagedQuery,
handleSetConfig,
+ currentQuery,
+ handleSetQueryData,
+ redirectWithQueryBuilderData,
} = useQueryBuilder();
+ const isAIAssistantEnabled = useIsAIAssistantEnabled();
+
const { options } = useOptionsMenu({
storageKey: LOCALSTORAGE.TRACES_LIST_OPTIONS,
dataSource: DataSource.TRACES,
@@ -131,6 +144,45 @@ function TracesExplorer(): JSX.Element {
[handleExplorerTabChange, handleSetConfig],
);
+ // ─── AI Assistant page actions (only when license feature is on) ───────────
+ const aiActions = useMemo(
+ () =>
+ isAIAssistantEnabled
+ ? [
+ tracesRunQueryAction({
+ currentQuery,
+ handleSetQueryData,
+ redirectWithQueryBuilderData,
+ }),
+ tracesAddFilterAction({
+ currentQuery,
+ handleSetQueryData,
+ redirectWithQueryBuilderData,
+ }),
+ tracesChangeViewAction({
+ onChangeView: (view) => handleChangeSelectedView(view as ExplorerViews),
+ }),
+ tracesSaveViewAction({
+ // POC stub — logs a save request; wire to real API when available
+ onSaveView: async (name) => {
+ // eslint-disable-next-line no-console
+ console.info('[AI Assistant] Save view requested:', name);
+ },
+ }),
+ ]
+ : [],
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [
+ isAIAssistantEnabled,
+ currentQuery,
+ handleSetQueryData,
+ redirectWithQueryBuilderData,
+ handleChangeSelectedView,
+ ],
+ );
+ usePageActions('traces-explorer', aiActions);
+ // ───────────────────────────────────────────────────────────────────────────
+
const exportDefaultQuery = useMemo(
() =>
getQueryByPanelType(
diff --git a/frontend/src/providers/App/App.tsx b/frontend/src/providers/App/App.tsx
index 47509a488e..925915d518 100644
--- a/frontend/src/providers/App/App.tsx
+++ b/frontend/src/providers/App/App.tsx
@@ -12,6 +12,7 @@ import {
import { useQuery } from 'react-query';
import getLocalStorageApi from 'api/browser/localstorage/get';
import setLocalStorageApi from 'api/browser/localstorage/set';
+import { useGetHosts } from 'api/generated/services/zeus';
import { useGetMyUser } from 'api/generated/services/users';
import listOrgPreferences from 'api/v1/org/preferences/list';
import listUserPreferences from 'api/v1/user/preferences/list';
@@ -43,6 +44,7 @@ import { Organization } from 'types/api/user/getOrganization';
import { UserResponse } from 'types/api/user/getUser';
import { ROLES, USER_ROLES } from 'types/roles';
import { toISOString } from 'utils/app';
+import { setSigNozInstanceUrl } from 'utils/signozInstanceUrl';
import { IAppContext, IUser } from './types';
import { getUserDefaults } from './utils';
@@ -204,6 +206,28 @@ export function AppProvider({ children }: PropsWithChildren): JSX.Element {
}
}, [activeLicenseData, isFetchingActiveLicense]);
+ const isCloudUser = activeLicense?.platform === LicensePlatform.CLOUD;
+
+ const {
+ data: hostsResponse,
+ isFetching: isFetchingHosts,
+ error: hostsFetchError,
+ } = useGetHosts({
+ query: { enabled: isLoggedIn && isCloudUser },
+ });
+
+ const hostsData = useMemo(() => hostsResponse ?? null, [hostsResponse]);
+
+ useEffect(() => {
+ const hosts = hostsData?.data?.hosts ?? [];
+ if (hosts.length === 0) {
+ return;
+ }
+ const activeHost =
+ hosts.find((h) => !h.is_default) ?? hosts.find((h) => h.is_default);
+ setSigNozInstanceUrl(activeHost?.url);
+ }, [hostsData]);
+
// fetcher for feature flags
const { isFetching: isFetchingFeatureFlags, error: featureFlagsFetchError } =
useGetFeatureFlag((allFlags: FeatureFlags[]) => {
@@ -359,14 +383,17 @@ export function AppProvider({ children }: PropsWithChildren): JSX.Element {
featureFlags,
trialInfo,
orgPreferences,
+ hostsData,
isLoggedIn,
org,
isFetchingUser,
isFetchingActiveLicense,
+ isFetchingHosts,
isFetchingFeatureFlags,
isFetchingOrgPreferences,
userFetchError,
activeLicenseFetchError,
+ hostsFetchError,
featureFlagsFetchError,
orgPreferencesFetchError,
activeLicense,
@@ -391,10 +418,13 @@ export function AppProvider({ children }: PropsWithChildren): JSX.Element {
featureFlags,
featureFlagsFetchError,
isFetchingActiveLicense,
+ isFetchingHosts,
isFetchingFeatureFlags,
isFetchingOrgPreferences,
isFetchingUser,
isLoggedIn,
+ hostsData,
+ hostsFetchError,
org,
orgPreferences,
activeLicenseRefetch,
diff --git a/frontend/src/providers/App/types.ts b/frontend/src/providers/App/types.ts
index 3ab26b8608..614ec78b38 100644
--- a/frontend/src/providers/App/types.ts
+++ b/frontend/src/providers/App/types.ts
@@ -9,6 +9,7 @@ import {
import { Organization } from 'types/api/user/getOrganization';
import { UserResponse as User } from 'types/api/user/getUser';
import { Info } from 'types/api/v1/version/get';
+import { GetHosts200 } from 'api/generated/services/sigNoz.schemas';
export interface IAppContext {
user: IUser;
@@ -17,14 +18,17 @@ export interface IAppContext {
featureFlags: FeatureFlags[] | null;
orgPreferences: OrgPreference[] | null;
userPreferences: UserPreference[] | null;
+ hostsData: GetHosts200 | null;
isLoggedIn: boolean;
org: Organization[] | null;
isFetchingUser: boolean;
isFetchingActiveLicense: boolean;
+ isFetchingHosts: boolean;
isFetchingFeatureFlags: boolean;
isFetchingOrgPreferences: boolean;
userFetchError: unknown;
activeLicenseFetchError: APIError | null;
+ hostsFetchError: unknown;
featureFlagsFetchError: unknown;
orgPreferencesFetchError: unknown;
changelog: ChangelogSchema | null;
diff --git a/frontend/src/styles.scss b/frontend/src/styles.scss
index e266eae33f..60d9d8d7a1 100644
--- a/frontend/src/styles.scss
+++ b/frontend/src/styles.scss
@@ -794,6 +794,14 @@ notifications - 2050
background: color-mix(in srgb, var(--l3-background) 20%, transparent);
}
+body.ai-assistant-panel-open {
+ .PylonChat-bubbleFrameContainer,
+ .PylonChat-chatWindowFrameContainer {
+ right: calc(var(--ai-assistant-panel-width, 380px) + 8px) !important;
+ left: auto !important;
+ }
+}
+
[role='tab'] {
color: var(--foreground) !important;
}
diff --git a/frontend/src/tests/test-utils.tsx b/frontend/src/tests/test-utils.tsx
index e26096a2a9..3ea8ecc5e4 100644
--- a/frontend/src/tests/test-utils.tsx
+++ b/frontend/src/tests/test-utils.tsx
@@ -221,6 +221,9 @@ export function getAppContextMock(
],
isFetchingFeatureFlags: false,
featureFlagsFetchError: null,
+ hostsData: null,
+ isFetchingHosts: false,
+ hostsFetchError: null,
orgPreferences: [
{
name: ORG_PREFERENCES.ORG_ONBOARDING,
@@ -282,14 +285,14 @@ export function AllTheProviders({
<QueryBuilderProvider>{children}</QueryBuilderProvider>
);
+ const appContextValue = getAppContextMock(roleValue, appContextOverridesValue);
+
return (
<MemoryRouter initialEntries={[initialRouteValue]}>
<NuqsAdapter>
<QueryClientProvider client={queryClient}>
<Provider store={mockStored(roleValue)}>
- <AppContext.Provider
- value={getAppContextMock(roleValue, appContextOverridesValue)}
- >
+ <AppContext.Provider value={appContextValue}>
<ResourceProvider>
<ErrorModalProvider>
<TimezoneProvider>
diff --git a/frontend/src/utils/permission/index.ts b/frontend/src/utils/permission/index.ts
index 75ee1e79ef..84d0a679cd 100644
--- a/frontend/src/utils/permission/index.ts
+++ b/frontend/src/utils/permission/index.ts
@@ -133,5 +133,7 @@ export const routePermission: Record<keyof typeof ROUTES, ROLES[]> = {
METER_EXPLORER_VIEWS: ['ADMIN', 'EDITOR', 'VIEWER'],
PUBLIC_DASHBOARD: ['ADMIN', 'EDITOR', 'VIEWER'],
ALERT_TYPE_SELECTION: ['ADMIN', 'EDITOR'],
+ AI_ASSISTANT: ['ADMIN', 'EDITOR', 'VIEWER'],
+ AI_ASSISTANT_ICON_PREVIEW: ['ADMIN', 'EDITOR', 'VIEWER'],
MCP_SERVER: ['ADMIN', 'EDITOR', 'VIEWER'],
};
diff --git a/frontend/src/utils/signozInstanceUrl.ts b/frontend/src/utils/signozInstanceUrl.ts
new file mode 100644
index 0000000000..b45111714f
--- /dev/null
+++ b/frontend/src/utils/signozInstanceUrl.ts
@@ -0,0 +1,26 @@
+import getLocalStorageApi from 'api/browser/localstorage/get';
+import setLocalStorageApi from 'api/browser/localstorage/set';
+import { LOCALSTORAGE } from 'constants/localStorage';
+import { ENVIRONMENT } from 'constants/env';
+
+export function getSigNozInstanceUrl(): string {
+ const fromStorage = getLocalStorageApi(
+ LOCALSTORAGE.ACTIVE_SIGNOZ_INSTANCE_URL,
+ );
+
+ if (typeof fromStorage === 'string' && fromStorage.trim().length > 0) {
+ return fromStorage;
+ }
+
+ return ENVIRONMENT.baseURL;
+}
+
+export function setSigNozInstanceUrl(url: string | null | undefined): void {
+ const next = (url ?? '').trim();
+
+ if (!next) {
+ return;
+ }
+
+ setLocalStorageApi(LOCALSTORAGE.ACTIVE_SIGNOZ_INSTANCE_URL, next);
+}