feat(monitoring): bot observability dashboards — Grafana + Persian RTL ERP page

Grafana (full use of the existing monitoring/ stack, per OSS policy):
- datasources.yml: BotPostgres (uid bot-postgres) over the shared network;
  grafana service joins 'shared' + carries the datasource env
- db_init.py: idempotent read-only role obs_reader (USAGE on schema public +
  SELECT on bot_traces/bot_trace_events; skipped when
  OBS_READER_PASSWORD empty; ALTER ROLE for rotation) + composite index
  ix_bot_trace_events_stage_time (stage, created_at DESC) — senior-engineer
  review applied with the column-name fix (event_type -> stage); (trace_id)
  already covered by the existing (trace_id, created_at) index
- dashboards/bot-observability.json: KPI row (real traffic, events, Jev/
  fallback errors, Jev p95, tokens, commits, archive guard), events/day,
  per-stage p50/p95, mention statuses (arbiter+fallback aggregates + legacy
  rows), DeepSeek arbiter actions, tokens/day, model-drift vs jev-1.13.0,
  user-choice A/B, STT + audio.enhance health, archive size guard
- dashboards/bot-trace-explorer.json: trace table + full event drill-down
  via the trace_id variable

ERP page (admin-only, Persian RTL, recharts@^3 for React 19):
- backend bot_metrics.py: read-only require_role('admin') endpoints
  (summary/routing/quality/jev/stt/traces + trace detail); aggregates count
  real traffic only (calibration/demo/chat_id=0 excluded)
- frontend BotMonitorPage at /bot-monitor (KPI cards, daily events,
  status donut, arbiter actions, user-choice A/B, STT/enhance tables,
  stage latency, tokens chart, traces table + detail drawer with payload
  viewer); entry link from the admin panel; MobileTabBar hidden there
- api.ts: typed botMetrics client section

Tooling/docs:
- tools/seed_observability_demo.py: deterministic demo traces (source='demo',
  every current pipeline stage incl. audio.enhance/jev.failure/arbitration/
  fallback/user choices) — excluded from real-traffic aggregates
- monitoring/README.md + bot/docs/DEPLOY-AND-MONITORING.md: setup, seed and
  rollback notes; alerts deliberately deferred (owner decision 2026-10-24)

Verified locally: obs_reader SELECT ok / INSERT denied; panels' SQL run as
obs_reader with data; datasource health OK; both dashboards survive a grafana
restart; endpoints 200 as admin and 403 without role; tsc + vite build clean;
page renders in-browser (admin session); bot startup provisions role+index.
This commit is contained in:
2026-10-24 15:09:01 +03:30
parent 787824a19e
commit 0adadd2cf8
19 changed files with 1912 additions and 11 deletions
+390
View File
@@ -28,6 +28,7 @@
"react-dom": "^19.2.8",
"react-hook-form": "^7.85.0",
"react-router-dom": "^7.18.2",
"recharts": "^3.8.0",
"sonner": "^2.0.8",
"tailwind-merge": "^3.6.0",
"tailwindcss": "^4.3.3",
@@ -1366,6 +1367,32 @@
"integrity": "sha512-JtyZR+mqgBibTo8xea3B6ZRmzZiM/YeVBtUkas6zMuXjAlfIFIW2FgqeM9eLyvEaYX66vr6DJMK+4U6LV0KhNw==",
"license": "MIT"
},
"node_modules/@reduxjs/toolkit": {
"version": "2.13.0",
"resolved": "https://registry.npmjs.org/@reduxjs/toolkit/-/toolkit-2.13.0.tgz",
"integrity": "sha512-f6jwVRfwW30+tnllz4YcsHHpPYYOE7abcHkyUCovD+P7DyhdAI5prz2Fh/8TLhakjpN+7aIEion1s5L/tvlYlA==",
"license": "MIT",
"dependencies": {
"@standard-schema/spec": "^1.0.0",
"@standard-schema/utils": "^0.3.0",
"immer": "^11.0.0",
"redux": "^5.0.1",
"redux-thunk": "^3.1.0",
"reselect": "^5.1.0"
},
"peerDependencies": {
"react": "^16.9.0 || ^17.0.0 || ^18 || ^19",
"react-redux": "^7.2.1 || ^8.1.3 || ^9.0.0"
},
"peerDependenciesMeta": {
"react": {
"optional": true
},
"react-redux": {
"optional": true
}
}
},
"node_modules/@rolldown/binding-android-arm64": {
"version": "1.2.3",
"resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.3.tgz",
@@ -1714,6 +1741,18 @@
"node": ">=18"
}
},
"node_modules/@standard-schema/spec": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz",
"integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==",
"license": "MIT"
},
"node_modules/@standard-schema/utils": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/@standard-schema/utils/-/utils-0.3.0.tgz",
"integrity": "sha512-e7Mew686owMaPJVNNLs55PUvgz371nKgwsc4vxE49zsODpJEnxgxRo2y/OKrqueavXgZNMDVj3DdHFlaSAeU8g==",
"license": "MIT"
},
"node_modules/@tailwindcss/node": {
"version": "4.3.3",
"resolved": "https://registry.npmjs.org/@tailwindcss/node/-/node-4.3.3.tgz",
@@ -2003,6 +2042,69 @@
"integrity": "sha512-nl09VhutdjINdWyXxHWN/w9zlNCfr60JUqJbd24YXUuCwgeL0TpFSdElCwb6cxfB6ybE19Gjj4g0jsgkXxKv1Q==",
"license": "MIT"
},
"node_modules/@types/d3-array": {
"version": "3.2.2",
"resolved": "https://registry.npmjs.org/@types/d3-array/-/d3-array-3.2.2.tgz",
"integrity": "sha512-hOLWVbm7uRza0BYXpIIW5pxfrKe0W+D5lrFiAEYR+pb6w3N2SwSMaJbXdUfSEv+dT4MfHBLtn5js0LAWaO6otw==",
"license": "MIT"
},
"node_modules/@types/d3-color": {
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/@types/d3-color/-/d3-color-3.1.3.tgz",
"integrity": "sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A==",
"license": "MIT"
},
"node_modules/@types/d3-ease": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/@types/d3-ease/-/d3-ease-3.0.2.tgz",
"integrity": "sha512-NcV1JjO5oDzoK26oMzbILE6HW7uVXOHLQvHshBUW4UMdZGfiY6v5BeQwh9a9tCzv+CeefZQHJt5SRgK154RtiA==",
"license": "MIT"
},
"node_modules/@types/d3-interpolate": {
"version": "3.0.4",
"resolved": "https://registry.npmjs.org/@types/d3-interpolate/-/d3-interpolate-3.0.4.tgz",
"integrity": "sha512-mgLPETlrpVV1YRJIglr4Ez47g7Yxjl1lj7YKsiMCb27VJH9W8NVM6Bb9d8kkpG/uAQS5AmbA48q2IAolKKo1MA==",
"license": "MIT",
"dependencies": {
"@types/d3-color": "*"
}
},
"node_modules/@types/d3-path": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/@types/d3-path/-/d3-path-3.1.1.tgz",
"integrity": "sha512-VMZBYyQvbGmWyWVea0EHs/BwLgxc+MKi1zLDCONksozI4YJMcTt8ZEuIR4Sb1MMTE8MMW49v0IwI5+b7RmfWlg==",
"license": "MIT"
},
"node_modules/@types/d3-scale": {
"version": "4.0.9",
"resolved": "https://registry.npmjs.org/@types/d3-scale/-/d3-scale-4.0.9.tgz",
"integrity": "sha512-dLmtwB8zkAeO/juAMfnV+sItKjlsw2lKdZVVy6LRr0cBmegxSABiLEpGVmSJJ8O08i4+sGR6qQtb6WtuwJdvVw==",
"license": "MIT",
"dependencies": {
"@types/d3-time": "*"
}
},
"node_modules/@types/d3-shape": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/@types/d3-shape/-/d3-shape-3.2.0.tgz",
"integrity": "sha512-kVd74ta9eof3eJOvbNd1vGKS/XERRyQbT26Og63hIsvDO84cjD5gEOhsXf26w3FSoNlPVz84DOFcKv/oou+fMw==",
"license": "MIT",
"dependencies": {
"@types/d3-path": "*"
}
},
"node_modules/@types/d3-time": {
"version": "3.0.4",
"resolved": "https://registry.npmjs.org/@types/d3-time/-/d3-time-3.0.4.tgz",
"integrity": "sha512-yuzZug1nkAAaBlBBikKZTgzCeA+k1uy4ZFwWANOfKw5z5LRhV0gNA7gNkKm7HoK+HRN0wX3EkxGk0fpbWhmB7g==",
"license": "MIT"
},
"node_modules/@types/d3-timer": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/@types/d3-timer/-/d3-timer-3.0.2.tgz",
"integrity": "sha512-Ps3T8E8dZDam6fUyNiMkekK3XUsaUEik+idO9/YjPtfj2qruF8tFBXS7XhtE4iIXBLxhmLjP3SXpLhVf21I9Lw==",
"license": "MIT"
},
"node_modules/@types/node": {
"version": "24.13.3",
"resolved": "https://registry.npmjs.org/@types/node/-/node-24.13.3.tgz",
@@ -2033,6 +2135,12 @@
"@types/react": "^19.2.0"
}
},
"node_modules/@types/use-sync-external-store": {
"version": "0.0.6",
"resolved": "https://registry.npmjs.org/@types/use-sync-external-store/-/use-sync-external-store-0.0.6.tgz",
"integrity": "sha512-zFDAD+tlpf2r4asuHEj0XH6pY6i0g5NeAHPn+15wk3BV6JA69eERFXC1gyGThDkVa1zCyKr5jox1+2LbV/AMLg==",
"license": "MIT"
},
"node_modules/@vitejs/plugin-react": {
"version": "6.0.5",
"resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-6.0.5.tgz",
@@ -2127,6 +2235,133 @@
"devOptional": true,
"license": "MIT"
},
"node_modules/d3-array": {
"version": "3.2.4",
"resolved": "https://registry.npmjs.org/d3-array/-/d3-array-3.2.4.tgz",
"integrity": "sha512-tdQAmyA18i4J7wprpYq8ClcxZy3SC31QMeByyCFyRt7BVHdREQZ5lpzoe5mFEYZUWe+oq8HBvk9JjpibyEV4Jg==",
"license": "ISC",
"dependencies": {
"internmap": "1 - 2"
},
"engines": {
"node": ">=12"
}
},
"node_modules/d3-color": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/d3-color/-/d3-color-3.1.0.tgz",
"integrity": "sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA==",
"license": "ISC",
"engines": {
"node": ">=12"
}
},
"node_modules/d3-ease": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/d3-ease/-/d3-ease-3.0.1.tgz",
"integrity": "sha512-wR/XK3D3XcLIZwpbvQwQ5fK+8Ykds1ip7A2Txe0yxncXSdq1L9skcG7blcedkOX+ZcgxGAmLX1FrRGbADwzi0w==",
"license": "BSD-3-Clause",
"engines": {
"node": ">=12"
}
},
"node_modules/d3-format": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/d3-format/-/d3-format-3.1.2.tgz",
"integrity": "sha512-AJDdYOdnyRDV5b6ArilzCPPwc1ejkHcoyFarqlPqT7zRYjhavcT3uSrqcMvsgh2CgoPbK3RCwyHaVyxYcP2Arg==",
"license": "ISC",
"engines": {
"node": ">=12"
}
},
"node_modules/d3-interpolate": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/d3-interpolate/-/d3-interpolate-3.0.1.tgz",
"integrity": "sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g==",
"license": "ISC",
"dependencies": {
"d3-color": "1 - 3"
},
"engines": {
"node": ">=12"
}
},
"node_modules/d3-path": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/d3-path/-/d3-path-3.1.0.tgz",
"integrity": "sha512-p3KP5HCf/bvjBSSKuXid6Zqijx7wIfNW+J/maPs+iwR35at5JCbLUT0LzF1cnjbCHWhqzQTIN2Jpe8pRebIEFQ==",
"license": "ISC",
"engines": {
"node": ">=12"
}
},
"node_modules/d3-scale": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/d3-scale/-/d3-scale-4.0.2.tgz",
"integrity": "sha512-GZW464g1SH7ag3Y7hXjf8RoUuAFIqklOAq3MRl4OaWabTFJY9PN/E1YklhXLh+OQ3fM9yS2nOkCoS+WLZ6kvxQ==",
"license": "ISC",
"dependencies": {
"d3-array": "2.10.0 - 3",
"d3-format": "1 - 3",
"d3-interpolate": "1.2.0 - 3",
"d3-time": "2.1.1 - 3",
"d3-time-format": "2 - 4"
},
"engines": {
"node": ">=12"
}
},
"node_modules/d3-shape": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/d3-shape/-/d3-shape-3.2.0.tgz",
"integrity": "sha512-SaLBuwGm3MOViRq2ABk3eLoxwZELpH6zhl3FbAoJ7Vm1gofKx6El1Ib5z23NUEhF9AsGl7y+dzLe5Cw2AArGTA==",
"license": "ISC",
"dependencies": {
"d3-path": "^3.1.0"
},
"engines": {
"node": ">=12"
}
},
"node_modules/d3-time": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/d3-time/-/d3-time-3.1.0.tgz",
"integrity": "sha512-VqKjzBLejbSMT4IgbmVgDjpkYrNWUYJnbCGo874u7MMKIWsILRX+OpX/gTk8MqjpT1A/c6HY2dCA77ZN0lkQ2Q==",
"license": "ISC",
"dependencies": {
"d3-array": "2 - 3"
},
"engines": {
"node": ">=12"
}
},
"node_modules/d3-time-format": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/d3-time-format/-/d3-time-format-4.1.0.tgz",
"integrity": "sha512-dJxPBlzC7NugB2PDLwo9Q8JiTR3M3e4/XANkreKSUxF8vvXKqm1Yfq4Q5dl8budlunRVlUUaDUgFt7eA8D6NLg==",
"license": "ISC",
"dependencies": {
"d3-time": "1 - 3"
},
"engines": {
"node": ">=12"
}
},
"node_modules/d3-timer": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/d3-timer/-/d3-timer-3.0.1.tgz",
"integrity": "sha512-ndfJ/JxxMd3nw31uyKoY2naivF+r29V+Lc0svZxe1JvvIRmi8hUsrMvdOwgS1o6uBHmiz91geQ0ylPP0aj1VUA==",
"license": "ISC",
"engines": {
"node": ">=12"
}
},
"node_modules/decimal.js-light": {
"version": "2.5.1",
"resolved": "https://registry.npmjs.org/decimal.js-light/-/decimal.js-light-2.5.1.tgz",
"integrity": "sha512-qIMFpTMZmny+MMIitAB6D7iVPEorVw6YQRWkvarTkT4tBeSLLiHzcwj6q0MmYSFCiVpiqPJTJEYIrpcPzVEIvg==",
"license": "MIT"
},
"node_modules/detect-libc": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
@@ -2155,6 +2390,24 @@
"node": ">=10.13.0"
}
},
"node_modules/es-toolkit": {
"version": "1.52.0",
"resolved": "https://registry.npmjs.org/es-toolkit/-/es-toolkit-1.52.0.tgz",
"integrity": "sha512-XTNEJQh1tY1ZJVcf6ayP/2n4ZPyaHlW2FWs7xvw5ddPuhUVjLD3olQVQS7kf58JbAB48iL0uL/jerTrjtV3lDA==",
"license": "MIT",
"workspaces": [
"docs",
"benchmarks",
"tests/types",
"tests/browser-compat"
]
},
"node_modules/eventemitter3": {
"version": "5.0.4",
"resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.4.tgz",
"integrity": "sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==",
"license": "MIT"
},
"node_modules/fdir": {
"version": "6.5.0",
"resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
@@ -2201,6 +2454,25 @@
"integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==",
"license": "ISC"
},
"node_modules/immer": {
"version": "11.2.9",
"resolved": "https://registry.npmjs.org/immer/-/immer-11.2.9.tgz",
"integrity": "sha512-IQ4UEtXjZjyefyWjtLEDXUSrF6T2hwjKPi6BIJl3bY/2XXW24d6cNGdXJSBOA/+KNnuiXkZY6DR0C3efolhitA==",
"license": "MIT",
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/immer"
}
},
"node_modules/internmap": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/internmap/-/internmap-2.0.3.tgz",
"integrity": "sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg==",
"license": "ISC",
"engines": {
"node": ">=12"
}
},
"node_modules/jiti": {
"version": "2.7.0",
"resolved": "https://registry.npmjs.org/jiti/-/jiti-2.7.0.tgz",
@@ -2645,6 +2917,36 @@
"react": "^16.8.0 || ^17 || ^18 || ^19"
}
},
"node_modules/react-is": {
"version": "19.3.1",
"resolved": "https://registry.npmjs.org/react-is/-/react-is-19.3.1.tgz",
"integrity": "sha512-RRieF6IyxQBkcK6pP8xOHprLTPW6QjRkbGdImtqNme+/hYVwCZkLQLdlZGOhUqXwkS9IEynaGvPJtv6XB/cz0Q==",
"license": "MIT",
"peer": true
},
"node_modules/react-redux": {
"version": "9.3.0",
"resolved": "https://registry.npmjs.org/react-redux/-/react-redux-9.3.0.tgz",
"integrity": "sha512-KQopgqFo/p/fgmAs5qz6p5RWaNAzq40WAu7fJIXnQpYxFPbJYtsJPWvGeF2rOBaY/kEuV77AVsX8TsQzKm+A/g==",
"license": "MIT",
"dependencies": {
"@types/use-sync-external-store": "^0.0.6",
"use-sync-external-store": "^1.4.0"
},
"peerDependencies": {
"@types/react": "^18.2.25 || ^19",
"react": "^18.0 || ^19",
"redux": "^5.0.0"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
},
"redux": {
"optional": true
}
}
},
"node_modules/react-remove-scroll": {
"version": "2.7.2",
"resolved": "https://registry.npmjs.org/react-remove-scroll/-/react-remove-scroll-2.7.2.tgz",
@@ -2752,6 +3054,57 @@
}
}
},
"node_modules/recharts": {
"version": "3.10.1",
"resolved": "https://registry.npmjs.org/recharts/-/recharts-3.10.1.tgz",
"integrity": "sha512-QXFrvt6IVcw7eeZCoyXTwkIJAX3Dv1nyVhMicXJ47GsGDDpcN8z6o644DibE9XjpBTThtsomLKnTV6lc+cVFUA==",
"license": "MIT",
"workspaces": [
"www"
],
"dependencies": {
"@reduxjs/toolkit": "^1.9.0 || 2.x.x",
"clsx": "^2.1.1",
"decimal.js-light": "^2.5.1",
"es-toolkit": "^1.39.3",
"eventemitter3": "^5.0.1",
"immer": "^11.1.8",
"react-redux": "8.x.x || 9.x.x",
"reselect": "5.2.0",
"tiny-invariant": "^1.3.3",
"use-sync-external-store": "^1.2.2",
"victory-vendor": "^37.0.2"
},
"engines": {
"node": ">=18"
},
"peerDependencies": {
"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",
"react-dom": "^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",
"react-is": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
}
},
"node_modules/redux": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/redux/-/redux-5.0.1.tgz",
"integrity": "sha512-M9/ELqF6fy8FwmkpnF0S3YKOqMyoWJ4+CS5Efg2ct3oY9daQvd/Pc71FpGZsVsbl3Cpb+IIcjBDUnnyBdQbq4w==",
"license": "MIT"
},
"node_modules/redux-thunk": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/redux-thunk/-/redux-thunk-3.1.0.tgz",
"integrity": "sha512-NW2r5T6ksUKXCabzhL9z+h206HQw/NJkcLm1GPImRQ8IzfXwRGqjVhKJGauHirT0DAuyy6hjdnMZaRoAcy0Klw==",
"license": "MIT",
"peerDependencies": {
"redux": "^5.0.0"
}
},
"node_modules/reselect": {
"version": "5.2.0",
"resolved": "https://registry.npmjs.org/reselect/-/reselect-5.2.0.tgz",
"integrity": "sha512-AgZ3UOZm3YndfrJ4OYjgrT7bmCm/1iqkjvEfH/oYjzh6PD2qw4QuT3jjnXIrpdt4MTpMXclMT3lXbmRY+XRakw==",
"license": "MIT"
},
"node_modules/rolldown": {
"version": "1.2.3",
"resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.3.tgz",
@@ -2884,6 +3237,12 @@
"url": "https://opencollective.com/webpack"
}
},
"node_modules/tiny-invariant": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/tiny-invariant/-/tiny-invariant-1.3.3.tgz",
"integrity": "sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg==",
"license": "MIT"
},
"node_modules/tinyglobby": {
"version": "0.2.17",
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",
@@ -2970,6 +3329,37 @@
}
}
},
"node_modules/use-sync-external-store": {
"version": "1.7.0",
"resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.7.0.tgz",
"integrity": "sha512-6L+EeigHMQhdaIPNIFUKwfWJSwWFQ8gJbJ2DLOs5sDIegTwR9fRxvnM3uciHKjIZhFz+KAv2emhWMRvDmMcY8A==",
"license": "MIT",
"peerDependencies": {
"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
}
},
"node_modules/victory-vendor": {
"version": "37.3.6",
"resolved": "https://registry.npmjs.org/victory-vendor/-/victory-vendor-37.3.6.tgz",
"integrity": "sha512-SbPDPdDBYp+5MJHhBCAyI7wKM3d5ivekigc2Dk2s7pgbZ9wIgIBYGVw4zGHBml/qTFbexrofXW6Gu4noGxrOwQ==",
"license": "MIT AND ISC",
"dependencies": {
"@types/d3-array": "^3.0.3",
"@types/d3-ease": "^3.0.0",
"@types/d3-interpolate": "^3.0.1",
"@types/d3-scale": "^4.0.2",
"@types/d3-shape": "^3.1.0",
"@types/d3-time": "^3.0.0",
"@types/d3-timer": "^3.0.0",
"d3-array": "^3.1.6",
"d3-ease": "^3.0.1",
"d3-interpolate": "^3.0.1",
"d3-scale": "^4.0.2",
"d3-shape": "^3.1.0",
"d3-time": "^3.0.0",
"d3-timer": "^3.0.1"
}
},
"node_modules/vite": {
"version": "8.2.1",
"resolved": "https://registry.npmjs.org/vite/-/vite-8.2.1.tgz",
+1
View File
@@ -30,6 +30,7 @@
"react-dom": "^19.2.8",
"react-hook-form": "^7.85.0",
"react-router-dom": "^7.18.2",
"recharts": "^3.8.0",
"sonner": "^2.0.8",
"tailwind-merge": "^3.6.0",
"tailwindcss": "^4.3.3",
+11
View File
@@ -43,6 +43,9 @@ const OrganizationPage = lazy(() =>
const AdminPanelPage = lazy(() =>
import("./pages/Admin/AdminPanel").then((m) => ({ default: m.AdminPanel })),
);
const BotMonitorPage = lazy(() =>
import("./pages/BotMonitor/BotMonitorPage").then((m) => ({ default: m.BotMonitorPage })),
);
function Loading() {
return (
@@ -220,6 +223,14 @@ export default function App() {
</RequireAuth>
}
/>
<Route
path="/bot-monitor"
element={
<RequireAuth>
<BotMonitorPage />
</RequireAuth>
}
/>
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>
</Suspense>
@@ -80,7 +80,7 @@ export function MobileTabBar() {
const role = useAuthStore((s) => s.user?.role);
const { pathname } = useLocation();
if (pathname === "/login" || pathname === "/admin") return null;
if (pathname === "/login" || pathname === "/admin" || pathname === "/bot-monitor") return null;
const isPM = role === "pm";
const isOffice = role === "admin" || role === "procurement_manager";
+99
View File
@@ -1604,6 +1604,79 @@ export interface UserRow {
created_at: string;
}
// ============================================================
// مانیتورینگ بات (bot-metrics) — شکل پاسخ‌های فقط-خواندنی
// ============================================================
export interface BotMetricsKpis {
traces: number;
events: number;
errors: number;
jev_p95_ms: number | null;
commits: number;
tokens_in: number;
tokens_out: number;
}
export interface BotMetricsSummary {
kpis: BotMetricsKpis;
daily: { day: string; events: number; traces: number }[];
days: number;
}
export interface BotMetricsRouting {
statuses: { metric: string; n: number }[];
actions: {
endorsed_jev: number;
vetoed_to_new: number;
demoted_to_ambiguity: number;
other: number;
invocations: number;
};
stages: { stage: string; n: number }[];
}
export interface BotMetricsQuality {
ambiguities: { action: string; arg: string; n: number }[];
picks: { pick: "top" | "other"; n: number }[];
drafts: { stage: string; n: number }[];
}
export interface BotMetricsJev {
models: { model: string; n: number; last_seen: string }[];
latency: { stage: string; p50: number; p95: number; n: number }[];
tokens_daily: { day: string; tokens_in: number; tokens_out: number }[];
}
export interface BotMetricsStt {
providers: { provider: string; ok: number; total: number; p50_ms: number }[];
enhance: { ok: number; total: number; p50_ms: number } | null;
}
export interface BotTraceRow {
id: string;
created_at: string;
source: string;
chat_id: string;
kind: string;
status: string;
events: number;
}
export interface BotTraceDetail {
trace: {
id: string;
created_at: string;
source: string;
chat_id: string;
kind: string;
status: string;
draft_id: string | null;
committed_quote_id: string | null;
} | null;
events: {
created_at: string;
stage: string;
ok: boolean;
latency_ms: number | null;
model: string | null;
field: string | null;
payload: Record<string, unknown>;
}[];
}
export const apiV26 = {
auth: {
// ورود درون‌صفحه‌ای: بک‌اند با grant_type=password از Casdoor توکن می‌گیرد
@@ -1796,4 +1869,30 @@ export const apiV26 = {
attributes: [],
}),
},
// مانیتورینگ بات بله — فقط-خواندنی از جدول‌های bot_traces/bot_trace_events
// (فقط ادمین؛ بک‌اند با require_role("admin") گارد می‌کند). آمار تجمیعی فقط
// ترافیک واقعی را می‌شمارد (calibration/demo/test حذف می‌شوند).
botMetrics: {
summary: (days: number) =>
getData<BotMetricsSummary>(`/bot-metrics/summary?days=${days}`),
routing: (days: number) =>
getData<BotMetricsRouting>(`/bot-metrics/routing?days=${days}`),
quality: (days: number) =>
getData<BotMetricsQuality>(`/bot-metrics/quality?days=${days}`),
jev: (days: number) =>
getData<BotMetricsJev>(`/bot-metrics/jev?days=${days}`),
stt: (days: number) =>
getData<BotMetricsStt>(`/bot-metrics/stt?days=${days}`),
traces: (opts?: { limit?: number; status?: string | null; include_synthetic?: boolean }) => {
const q = new URLSearchParams();
if (opts?.limit) q.set("limit", String(opts.limit));
if (opts?.status) q.set("status", opts.status);
if (opts?.include_synthetic) q.set("include_synthetic", "true");
const qs = q.toString();
return getData<BotTraceRow[]>(`/bot-metrics/traces${qs ? `?${qs}` : ""}`);
},
traceDetail: (traceId: string) =>
getData<BotTraceDetail>(`/bot-metrics/traces/${encodeURIComponent(traceId)}`),
},
};
+17 -8
View File
@@ -1,6 +1,6 @@
import { useCallback, useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { ShieldCheck, Warehouse as WarehouseIcon } from "lucide-react";
import { ShieldCheck, Warehouse as WarehouseIcon, Bot as BotIcon } from "lucide-react";
import { toast } from "sonner";
import { Header, PageLayout } from "../../components/layout/Header";
import { EmptyState } from "../../components/EmptyState";
@@ -170,13 +170,22 @@ export function AdminPanel() {
</div>
)}
<button
onClick={() => navigate("/inventory")}
className="flex w-fit cursor-pointer items-center gap-1.5 rounded-lg border border-line bg-panel px-3 py-1.5 text-[12px] text-muted hover:bg-slate-bg hover:text-ink"
>
<WarehouseIcon className="h-3.5 w-3.5" />
بازگشت به داشبورد انبار
</button>
<div className="flex flex-wrap gap-2">
<button
onClick={() => navigate("/bot-monitor")}
className="flex w-fit cursor-pointer items-center gap-1.5 rounded-lg border border-line bg-panel px-3 py-1.5 text-[12px] text-muted hover:bg-slate-bg hover:text-ink"
>
<BotIcon className="h-3.5 w-3.5" />
مانیتورینگ بات بله (Observability)
</button>
<button
onClick={() => navigate("/inventory")}
className="flex w-fit cursor-pointer items-center gap-1.5 rounded-lg border border-line bg-panel px-3 py-1.5 text-[12px] text-muted hover:bg-slate-bg hover:text-ink"
>
<WarehouseIcon className="h-3.5 w-3.5" />
بازگشت به داشبورد انبار
</button>
</div>
</PageLayout>
</div>
);
@@ -0,0 +1,592 @@
import { useState } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { Bot, X } from "lucide-react";
import {
ResponsiveContainer,
BarChart,
Bar,
XAxis,
YAxis,
Tooltip,
CartesianGrid,
PieChart,
Pie,
Cell,
} from "recharts";
import { Header, PageLayout } from "../../components/layout/Header";
import { EmptyState } from "../../components/EmptyState";
import { AppSwitcherMenu } from "../../components/AppSwitcherMenu";
import { inventorySubheader } from "../Inventory/panelMenu";
import { useAuthStore } from "../../store/auth";
import { apiV26, type BotTraceRow, type BotTraceDetail } from "../../lib/api";
import { faNum, fmtDateTime } from "../../lib/formatters";
// داشبورد مانیتورینگ بات بله (فقط ادمین) — خواندنی از bot-metrics.
// داده: همان جدول‌های Observability بات؛ گرفانا همان اطلاعات را بیرون از ERP
// نشان می‌دهد، این صفحه نسخه‌ی فارسی/RTL داخل خود سیستم است.
// آمار فقط ترافیک واقعی را می‌شمارد (calibration/demo/test حذف می‌شوند).
const DAY_OPTIONS = [1, 7, 30, 90] as const;
const STATUS_LABELS: Record<string, string> = {
exact: "اتصال دقیق",
ambiguity: "ابهام (پرسش از کاربر)",
new: "موجودیت جدید",
};
const STATUS_COLORS: Record<string, string> = {
exact: "#16a34a",
ambiguity: "#d97706",
new: "#64748b",
};
const STAGE_LABELS: Record<string, string> = {
"jev.request": "درخواست Jev",
"jev.result": "پاسخ Jev",
"jev.failure": "خطای Jev",
"matching.arbitration.result": "داور DeepSeek",
"matching.fallback.result": "فالبک بحرانی",
"draft.render": "نمایش پیش‌نویس",
"draft.commit": "ثبت نهایی",
"draft.cancel": "لغو",
"ambiguity.sent": "ارسال ابهام",
};
function Card({
label,
value,
hint,
tone = "default",
}: {
label: string;
value: string;
hint?: string;
tone?: "default" | "warn" | "good";
}) {
const toneCls =
tone === "warn"
? "border-red-500/25 bg-red-500/5"
: tone === "good"
? "border-emerald-500/25 bg-emerald-500/5"
: "border-line bg-panel";
return (
<div className={`rounded-xl border px-3.5 py-3 ${toneCls}`}>
<div className="text-[11px] text-muted">{label}</div>
<div className="mt-1 text-xl font-bold tabular-nums">{value}</div>
{hint ? <div className="mt-0.5 text-[10.5px] text-muted">{hint}</div> : null}
</div>
);
}
function Panel({
title,
children,
className = "",
}: {
title: string;
children: React.ReactNode;
className?: string;
}) {
return (
<section className={`rounded-xl border border-line bg-panel p-3.5 ${className}`}>
<h3 className="mb-3 text-[13px] font-bold">{title}</h3>
{children}
</section>
);
}
const tooltipStyle = {
backgroundColor: "var(--color-panel, #111827)",
border: "1px solid rgba(148,163,184,.25)",
borderRadius: 8,
fontSize: 12,
};
export function BotMonitorPage() {
const user = useAuthStore((s) => s.user);
const isAdmin = user?.role === "admin";
const [days, setDays] = useState<number>(7);
const [showSynthetic, setShowSynthetic] = useState(false);
const [openTrace, setOpenTrace] = useState<string | null>(null);
const qc = useQueryClient();
const summary = useQuery({
queryKey: ["bot-metrics", "summary", days],
queryFn: () => apiV26.botMetrics.summary(days),
enabled: isAdmin,
});
const routing = useQuery({
queryKey: ["bot-metrics", "routing", days],
queryFn: () => apiV26.botMetrics.routing(days),
enabled: isAdmin,
});
const quality = useQuery({
queryKey: ["bot-metrics", "quality", days],
queryFn: () => apiV26.botMetrics.quality(days),
enabled: isAdmin,
});
const jev = useQuery({
queryKey: ["bot-metrics", "jev", days],
queryFn: () => apiV26.botMetrics.jev(days),
enabled: isAdmin,
});
const stt = useQuery({
queryKey: ["bot-metrics", "stt", days],
queryFn: () => apiV26.botMetrics.stt(days),
enabled: isAdmin,
});
const traces = useQuery({
queryKey: ["bot-metrics", "traces", showSynthetic],
queryFn: () => apiV26.botMetrics.traces({ limit: 50, include_synthetic: showSynthetic }),
enabled: isAdmin,
});
const traceDetail = useQuery({
queryKey: ["bot-metrics", "trace", openTrace],
queryFn: () => apiV26.botMetrics.traceDetail(openTrace!),
enabled: isAdmin && !!openTrace,
});
if (!isAdmin) {
return (
<div className="min-h-screen">
<Header
title="مانیتورینگ بات"
backTo="/admin"
backLabel="بازگشت به پنل ادمین"
icon={<Bot className="h-4.5 w-4.5" strokeWidth={2} />}
menu={<AppSwitcherMenu activeModule="warehouse" />}
/>
<PageLayout>
<EmptyState emoji="🔒" text="این بخش فقط برای ادمین قابل مشاهده است." />
</PageLayout>
</div>
);
}
const k = summary.data?.kpis;
const pieData = (routing.data?.statuses ?? []).map((s) => ({
name: STATUS_LABELS[s.metric] ?? s.metric,
value: s.n,
key: s.metric,
}));
const actions = routing.data?.actions;
const top = quality.data?.picks.find((p) => p.pick === "top")?.n ?? 0;
const other = quality.data?.picks.find((p) => p.pick === "other")?.n ?? 0;
const pinnedModel = "jev-1.13.0";
const drifted = (jev.data?.models ?? []).some((m) => m.model !== "?" && m.model !== pinnedModel);
const loading = summary.isLoading || routing.isLoading;
return (
<div className="min-h-screen">
<Header
title="مانیتورینگ بات بله"
sub={inventorySubheader(user)}
backTo="/admin"
backLabel="بازگشت به پنل ادمین"
icon={<Bot className="h-4.5 w-4.5" strokeWidth={2} />}
menu={<AppSwitcherMenu activeModule="warehouse" />}
actions={
<div className="flex items-center gap-1.5">
{DAY_OPTIONS.map((d) => (
<button
key={d}
onClick={() => setDays(d)}
className={`cursor-pointer rounded-lg border px-2.5 py-1 text-[11.5px] ${
days === d
? "border-blue/40 bg-blue/10 font-bold"
: "border-line bg-panel text-muted hover:text-ink"
}`}
>
{faNum(d)} روز
</button>
))}
<button
onClick={() => void qc.invalidateQueries({ queryKey: ["bot-metrics"] })}
className="btn-line-file cursor-pointer"
>
🔄
</button>
</div>
}
/>
<PageLayout className="flex flex-col gap-3">
{loading ? (
<div className="py-6 text-center text-[12.5px] text-muted">در حال بارگذاری…</div>
) : (
<>
{/* ردیف KPI */}
<div className="grid grid-cols-2 gap-2.5 md:grid-cols-4 xl:grid-cols-7">
<Card label="روندها" value={faNum(k?.traces ?? 0)} hint="ترافیک واقعی" />
<Card label="رخدادها" value={faNum(k?.events ?? 0)} />
<Card
label="خطای Jev / فالبک"
value={faNum(k?.errors ?? 0)}
tone={(k?.errors ?? 0) > 0 ? "warn" : "good"}
/>
<Card label="p95 تأخیر Jev" value={`${faNum(k?.jev_p95_ms ?? 0)} ms`} />
<Card
label="توکن مصرفی"
value={faNum((k?.tokens_in ?? 0) + (k?.tokens_out ?? 0))}
hint={`ورودی ${faNum(k?.tokens_in ?? 0)} / خروجی ${faNum(k?.tokens_out ?? 0)}`}
/>
<Card label="ثبت نهایی" value={faNum(k?.commits ?? 0)} tone="good" />
<Card
label="نسخه مدل Jev"
value={drifted ? "⚠️ انحراف" : pinnedModel}
tone={drifted ? "warn" : "default"}
/>
</div>
{/* نمودارها */}
<div className="grid grid-cols-1 gap-3 lg:grid-cols-2">
<Panel title={`رخداد در روز (${faNum(days)} روز اخیر)`}>
{(summary.data?.daily ?? []).length === 0 ? (
<EmptyState emoji="📭" text="در این بازه траافیکی ثبت نشده است." />
) : (
<div className="h-56" dir="ltr">
<ResponsiveContainer width="100%" height="100%">
<BarChart data={summary.data!.daily}>
<CartesianGrid strokeDasharray="3 3" stroke="rgba(148,163,184,.15)" />
<XAxis dataKey="day" tick={{ fontSize: 10 }} />
<YAxis tick={{ fontSize: 10 }} width={38} />
<Tooltip contentStyle={tooltipStyle} />
<Bar dataKey="events" name="رخداد" fill="#3b82f6" radius={[4, 4, 0, 0]} />
</BarChart>
</ResponsiveContainer>
</div>
)}
</Panel>
<Panel title="وضعیت نهایی mentionها (تطبیق موجودیت)">
{pieData.length === 0 || pieData.every((p) => p.value === 0) ? (
<EmptyState emoji="🔍" text="هنوز داده‌ی تطبیقی ثبت نشده است." />
) : (
<div className="flex h-56 items-center gap-4">
<div className="h-full w-1/2" dir="ltr">
<ResponsiveContainer width="100%" height="100%">
<PieChart>
<Pie
data={pieData}
dataKey="value"
nameKey="name"
innerRadius="52%"
outerRadius="85%"
paddingAngle={2}
>
{pieData.map((d) => (
<Cell key={d.key} fill={STATUS_COLORS[d.key] ?? "#94a3b8"} />
))}
</Pie>
<Tooltip contentStyle={tooltipStyle} />
</PieChart>
</ResponsiveContainer>
</div>
<ul className="flex-1 space-y-1.5 text-[12px]">
{pieData.map((d) => (
<li key={d.key} className="flex items-center justify-between gap-2">
<span className="flex items-center gap-1.5">
<span
className="inline-block h-2.5 w-2.5 rounded-full"
style={{ background: STATUS_COLORS[d.key] ?? "#94a3b8" }}
/>
{d.name}
</span>
<span className="tabular-nums font-bold">{faNum(d.value)}</span>
</li>
))}
</ul>
</div>
)}
</Panel>
</div>
<div className="grid grid-cols-1 gap-3 lg:grid-cols-3">
{/* داور و کیفیت */}
<Panel title="داور DeepSeek روی پیشنهادهای Jev">
<table className="w-full text-[12px]">
<tbody className="[&_td]:py-1.5 [&_td:last-child]:text-left">
<tr className="border-b border-line">
<td>تأیید پیشنهاد Jev</td>
<td className="font-bold tabular-nums">{faNum(actions?.endorsed_jev ?? 0)}</td>
</tr>
<tr className="border-b border-line">
<td>وتو → ساخت جدید</td>
<td className="font-bold tabular-nums">{faNum(actions?.vetoed_to_new ?? 0)}</td>
</tr>
<tr className="border-b border-line">
<td>تنزل → ابهام</td>
<td className="font-bold tabular-nums">{faNum(actions?.demoted_to_ambiguity ?? 0)}</td>
</tr>
<tr>
<td>فراخوانی داور</td>
<td className="font-bold tabular-nums">{faNum(actions?.invocations ?? 0)}</td>
</tr>
</tbody>
</table>
</Panel>
<Panel title="انتخاب کاربر (A/B واقعی)">
<div className="space-y-2 text-[12px]">
<div className="flex items-center justify-between">
<span>گزینه‌ی اول (پیشنهاد مدل)</span>
<span className="font-bold tabular-nums text-emerald-500">{faNum(top)}</span>
</div>
<div className="flex items-center justify-between">
<span>گزینه‌ی غیراول</span>
<span className="font-bold tabular-nums text-amber-500">{faNum(other)}</span>
</div>
{(quality.data?.ambiguities ?? []).map((a, i) => (
<div
key={i}
className="flex items-center justify-between border-t border-line pt-1.5 text-muted"
>
<span>
{a.action === "pick" ? "انتخاب کاندیدا" : a.action === "new" ? "«هیچ‌کدام»" : a.action}
{a.arg !== "-" ? ` (${a.arg})` : ""}
</span>
<span className="tabular-nums">{faNum(a.n)}</span>
</div>
))}
</div>
</Panel>
<Panel title="سلامت STT و پیش‌پردازش صدا">
<table className="w-full text-[12px]">
<thead className="text-[11px] text-muted">
<tr className="border-b border-line">
<th className="pb-1 text-right">پرووایدر</th>
<th className="pb-1">موفق</th>
<th className="pb-1">p50</th>
</tr>
</thead>
<tbody className="[&_td]:py-1.5 [&_td:not(:first-child)]:tabular-nums [&_td:not(:first-child)]:text-left">
{(stt.data?.providers ?? []).map((p) => (
<tr key={p.provider} className="border-b border-line last:border-0">
<td>{p.provider}</td>
<td className={p.ok < p.total ? "text-amber-500" : ""}>
{faNum(p.ok)}/{faNum(p.total)}
</td>
<td>{p.p50_ms ? `${faNum(p.p50_ms)}ms` : "—"}</td>
</tr>
))}
{stt.data?.enhance ? (
<tr>
<td>پیش‌پردازش صدا</td>
<td className={stt.data.enhance.ok < stt.data.enhance.total ? "text-amber-500" : ""}>
{faNum(stt.data.enhance.ok)}/{faNum(stt.data.enhance.total)}
</td>
<td>{stt.data.enhance.p50_ms ? `${faNum(stt.data.enhance.p50_ms)}ms` : "—"}</td>
</tr>
) : null}
</tbody>
</table>
</Panel>
</div>
<div className="grid grid-cols-1 gap-3 lg:grid-cols-2">
<Panel title="تأخیر مراحل (p50 / p95 میلی‌ثانیه)">
<table className="w-full text-[12px]">
<tbody className="[&_td]:py-1.5 [&_td:not(:first-child)]:tabular-nums [&_td:not(:first-child)]:text-left">
{(jev.data?.latency ?? []).map((l) => (
<tr key={l.stage} className="border-b border-line last:border-0">
<td>{STAGE_LABELS[l.stage] ?? l.stage}</td>
<td>{faNum(l.p50)} / {faNum(l.p95)}</td>
<td className="text-muted">{faNum(l.n)}×</td>
</tr>
))}
{(jev.data?.latency ?? []).length === 0 ? (
<tr>
<td className="text-muted">داده‌ای ثبت نشده</td>
</tr>
) : null}
</tbody>
</table>
</Panel>
<Panel title={`توکن مصرفی در روز${drifted ? " — ⚠️ مدل متفاوت از پین دیده شده" : ""}`}>
{(jev.data?.tokens_daily ?? []).length === 0 ? (
<EmptyState emoji="🪙" text="هنوز مصرف توکنی ثبت نشده است." />
) : (
<div className="h-48" dir="ltr">
<ResponsiveContainer width="100%" height="100%">
<BarChart data={jev.data!.tokens_daily}>
<CartesianGrid strokeDasharray="3 3" stroke="rgba(148,163,184,.15)" />
<XAxis dataKey="day" tick={{ fontSize: 10 }} />
<YAxis tick={{ fontSize: 10 }} width={52} />
<Tooltip contentStyle={tooltipStyle} />
<Bar dataKey="tokens_in" name="ورودی" stackId="t" fill="#3b82f6" />
<Bar dataKey="tokens_out" name="خروجی" stackId="t" fill="#8b5cf6" radius={[4, 4, 0, 0]} />
</BarChart>
</ResponsiveContainer>
</div>
)}
</Panel>
</div>
{/* جدول ترس‌ها */}
<Panel title="آخرین ترس‌ها (برای جزئیات کلیک کنید)">
<label className="mb-2 flex cursor-pointer items-center gap-1.5 text-[11.5px] text-muted">
<input
type="checkbox"
checked={showSynthetic}
onChange={(e) => setShowSynthetic(e.target.checked)}
className="accent-blue-500"
/>
نمایش ترافیک آزمایشی (calibration/demo)
</label>
{traces.isLoading ? (
<div className="py-3 text-center text-[12px] text-muted">در حال بارگذاری…</div>
) : (traces.data ?? []).length === 0 ? (
<EmptyState emoji="🗂" text="تریسی ثبت نشده است." />
) : (
<div className="max-h-96 overflow-auto rounded-lg border border-line">
<table className="w-full text-[12px]">
<thead className="sticky top-0 bg-slate-bg text-[11px] text-muted">
<tr className="border-b border-line">
<th className="p-2 text-right">زمان</th>
<th className="p-2 text-right">منبع</th>
<th className="p-2">چت</th>
<th className="p-2">نوع</th>
<th className="p-2">وضعیت</th>
<th className="p-2">رخداد</th>
</tr>
</thead>
<tbody>
{(traces.data ?? []).map((t: BotTraceRow) => (
<tr
key={t.id}
onClick={() => setOpenTrace(t.id)}
className="cursor-pointer border-b border-line last:border-0 hover:bg-slate-bg"
title={t.id}
>
<td className="p-2 text-muted">{fmtDateTime(t.created_at)}</td>
<td className="p-2">{t.source}</td>
<td className="p-2 text-center tabular-nums">{t.chat_id}</td>
<td className="p-2 text-center">{t.kind}</td>
<td className="p-2 text-center">{t.status}</td>
<td className="p-2 text-center tabular-nums">{faNum(t.events)}</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</Panel>
</>
)}
</PageLayout>
{/* درایور جزئیات ترس */}
{openTrace ? (
<TraceDrawer
traceId={openTrace}
detail={traceDetail.data ?? null}
loading={traceDetail.isLoading}
onClose={() => {
setOpenTrace(null);
void qc.removeQueries({ queryKey: ["bot-metrics", "trace"] });
}}
/>
) : null}
</div>
);
}
function TraceDrawer({
traceId,
detail,
loading,
onClose,
}: {
traceId: string;
detail: BotTraceDetail | null;
loading: boolean;
onClose: () => void;
}) {
return (
<div className="fixed inset-0 z-50 flex" onClick={onClose}>
<div className="flex-1 bg-black/40" />
<aside
className="flex h-full w-full max-w-xl flex-col border-r border-line bg-bg shadow-2xl"
onClick={(e) => e.stopPropagation()}
>
<div className="flex items-center justify-between border-b border-line px-4 py-3">
<div>
<div className="text-[13px] font-bold">جزئیات ترس</div>
<div className="mt-0.5 font-mono text-[10px] text-muted" dir="ltr">
{traceId}
</div>
</div>
<button
onClick={onClose}
className="cursor-pointer rounded-lg border border-line bg-panel p-1.5 hover:bg-slate-bg"
aria-label="بستن"
>
<X className="h-4 w-4" />
</button>
</div>
<div className="flex-1 overflow-auto p-4">
{loading ? (
<div className="py-6 text-center text-[12.5px] text-muted">در حال بارگذاری…</div>
) : !detail?.trace ? (
<EmptyState emoji="❓" text="تریسی با این شناسه یافت نشد." />
) : (
<>
<div className="mb-3 grid grid-cols-2 gap-2 text-[12px] sm:grid-cols-4">
<Card label="زمان" value={fmtDateTime(detail.trace.created_at)} />
<Card label="منبع" value={detail.trace.source} />
<Card label="وضعیت" value={detail.trace.status} />
<Card label="رخدادها" value={faNum(detail.events.length)} />
</div>
{detail.trace.committed_quote_id ? (
<div className="mb-3 rounded-lg border border-emerald-500/25 bg-emerald-500/5 px-3 py-2 text-[11.5px]">
استعلام ثبت‌شده:{" "}
<span className="font-mono" dir="ltr">
{detail.trace.committed_quote_id}
</span>
</div>
) : null}
<ol className="space-y-1.5">
{detail.events.map((e, i) => (
<li
key={i}
className={`rounded-lg border px-3 py-2 text-[11.5px] ${
e.ok ? "border-line bg-panel" : "border-red-500/30 bg-red-500/5"
}`}
>
<div className="flex flex-wrap items-center gap-x-3 gap-y-1">
<span className="font-bold">{STAGE_LABELS[e.stage] ?? e.stage}</span>
<span className="font-mono text-[10px] text-muted" dir="ltr">
{e.stage}
</span>
{!e.ok ? <span className="text-red-400">✗ خطا</span> : null}
{e.latency_ms != null ? (
<span className="tabular-nums text-muted">{faNum(e.latency_ms)}ms</span>
) : null}
{e.model ? <span className="text-muted">{e.model}</span> : null}
{e.field ? <span className="text-muted">فیلد: {e.field}</span> : null}
<span className="mr-auto text-muted">{fmtDateTime(e.created_at)}</span>
</div>
{Object.keys(e.payload ?? {}).length > 0 ? (
<details className="mt-1.5">
<summary className="cursor-pointer text-[10.5px] text-muted">
نمایش جزئیات
</summary>
<pre
className="mt-1 max-h-56 overflow-auto rounded bg-slate-bg p-2 font-mono text-[10px] leading-5"
dir="ltr"
>
{JSON.stringify(e.payload, null, 2)}
</pre>
</details>
) : null}
</li>
))}
</ol>
</>
)}
</div>
</aside>
</div>
);
}