Compare commits
979 Commits
task/pep-1
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 2bbeeab019 | |||
| 6b8e2d2892 | |||
| a1525081ab | |||
| b0674c1c2e | |||
| 5191f1e5fe | |||
| 3bef77100e | |||
| 69cebe9b22 | |||
| 3785562d51 | |||
| 73b4653e1f | |||
| 8052413375 | |||
| 978ccfdd3e | |||
| b664e6ad7c | |||
| d5bcec2f95 | |||
| 690d0d59a2 | |||
| 59ac4ddb28 | |||
| e9d1c68897 | |||
| 37cf2933c9 | |||
| e712ecbaff | |||
| efa7e4308c | |||
| ad6dd0a178 | |||
| 8a6e9234b8 | |||
| 664c9ef5e9 | |||
| 375ad25cd8 | |||
| 98eddf376b | |||
| eaca63aa0f | |||
| 43176fc15d | |||
| 650d4e649e | |||
| 265c1d6052 | |||
| 564c7a0217 | |||
| 7d0b3bcee8 | |||
| d6d5044e61 | |||
| bc14e5824c | |||
| d2124d8008 | |||
| 787cde39f2 | |||
| f9881ea43f | |||
| c44f2db3f4 | |||
| 5302e74fc8 | |||
| 1c5fc6e072 | |||
| 899570acf1 | |||
| d8b1fcfd5f | |||
| 9a87f92d87 | |||
| 4a15bcf551 | |||
| 7373ad013d | |||
| 22136ea160 | |||
| 9b38dab378 | |||
| 61261370bd | |||
| d059b4b50f | |||
| a60dc9c8df | |||
| 4ef53f2627 | |||
| 070574ce96 | |||
| 0bdb722f7c | |||
| a7223a7923 | |||
| 76b8efc78c | |||
| b52ccb4651 | |||
| 020886eb1c | |||
| c82eb083d4 | |||
| d38719e213 | |||
| 2a2405f588 | |||
| ac17f79cc4 | |||
| f870bc7b67 | |||
| e30b3371f9 | |||
| 206083d127 | |||
| c52ff4a4f1 | |||
| e2b06b5e80 | |||
| 8746d80ab3 | |||
| 11261e4483 | |||
| eac871eac4 | |||
| 71cac58cf9 | |||
| c3f552b500 | |||
| af218f76f5 | |||
| 8065c1936c | |||
| 0d539146ac | |||
| 31cdfad789 | |||
| 0873b087d8 | |||
| 1341d61a05 | |||
| d743b38f31 | |||
| 227c911baa | |||
| d2372c631b | |||
| a1717939da | |||
| 511e85661b | |||
| 76c40f7f40 | |||
| cd9147a7e5 | |||
| f117f7fb62 | |||
| 3999db7893 | |||
| 4c9a14fc11 | |||
| ce03df667c | |||
| fdc88d587c | |||
| f6ae77efe1 | |||
| 96fa6151ab | |||
| 4f0c414c31 | |||
| 8ed5e76bea | |||
| 004508557f | |||
| f540ea12ae | |||
| 24e624be1a | |||
| 2c064023f4 | |||
| 2c582e190d | |||
| 460da8bae2 | |||
| 3d35bbf2b6 | |||
| be7ce67078 | |||
| d45137203f | |||
| 7cf259b83a | |||
| 9794baf8ed | |||
| bae36b82b7 | |||
| d903b17770 | |||
| c6b44d9c44 | |||
| 1ef3bd7c98 | |||
| a1dcb10daf | |||
| 66020888c9 | |||
| 912ebcf813 | |||
| d198818996 | |||
| 63ef12a100 | |||
| 7d5adcdfe1 | |||
| 9e97fd531d | |||
| fb7d6e1b62 | |||
| 70de049164 | |||
| 0c50be58f6 | |||
| 420b4ae357 | |||
| 311aad4c90 | |||
| 223ef9f84f | |||
| fb1f316d9b | |||
| 1dc99c5b5a | |||
| 3b303c2a8d | |||
| 81f0269c40 | |||
| be58172bca | |||
| 1bd3a3e2f0 | |||
| 0ccf12b3a6 | |||
| 2dcb12f683 | |||
| 15c222534c | |||
| edac120990 | |||
| 307626f300 | |||
| 3e258f24df | |||
| 1656923958 | |||
| d857b15c11 | |||
| 8bc56de251 | |||
| 9b95023cb4 | |||
| e962779d37 | |||
| 580fbac015 | |||
| c5dae8d1e7 | |||
| 113de40b8e | |||
| 0a25e94591 | |||
| 64255e6550 | |||
| edf0abf7a1 | |||
| b1a2dd13eb | |||
| c8a95cc67f | |||
| c8d2450851 | |||
| 41bb8c8614 | |||
| 994010ca54 | |||
| bf426ceb70 | |||
| ad9f580519 | |||
| 5e85cf36eb | |||
| 4233f842b1 | |||
| efca6117a3 | |||
| 53aee41852 | |||
| fd4415ca92 | |||
| 7825899163 | |||
| ad2eb2bd36 | |||
| 9e467cc3e6 | |||
| e744f7873d | |||
| b8c2bf9076 | |||
| 59d3f6eb41 | |||
| dfe6f18234 | |||
| 4ba532afc8 | |||
| 1143d10fa8 | |||
| d564892364 | |||
| fe4c131aee | |||
| 2aac71ca38 | |||
| fd795afd7f | |||
| aa00444e74 | |||
| dde08970aa | |||
| 86ddf80920 | |||
| e1b81e14ca | |||
| 9a25e1dc86 | |||
| b00e9c1959 | |||
| 065768e0b6 | |||
| 4bb4d3d7a3 | |||
| fd56afdbf3 | |||
| 546027bb4e | |||
| 3e2a2b4333 | |||
| 1646f465f3 | |||
| 119bd97edc | |||
| dcec76f3d4 | |||
| e9cdd782ce | |||
| 16f2004cd4 | |||
| ad59289ae7 | |||
| d852aed15b | |||
| d81a767d2b | |||
| 5271a29237 | |||
| f31f321564 | |||
| 1f733a1d29 | |||
| 7ca11abb82 | |||
| 5019e1ad80 | |||
| ec1d042b0a | |||
| 468eefba3d | |||
| 550d74678b | |||
| 5433e970eb | |||
| 5fd5379f88 | |||
| b629cb0acf | |||
| cd9d9cd9e5 | |||
| 6fb083a064 | |||
| 5d7775cdb3 | |||
| 6a8d3bc008 | |||
| 020f1e08f4 | |||
| a827251ed9 | |||
| b106fba99f | |||
| 1e5f0f4b17 | |||
| c3e2381e3c | |||
| 0a29a3340b | |||
| 1bf8164b9e | |||
| 3f49568aaa | |||
| 0db37d2543 | |||
| 330c08b44d | |||
| 53536c8df7 | |||
| 2bb3d4f4b4 | |||
| 44f8d24e9d | |||
| b9db1ea739 | |||
| d20bfe496e | |||
| 23fc8e063a | |||
| a9a1eddd22 | |||
| b9cc11adb9 | |||
| 82d6ec0b73 | |||
| 1b1c87ff1c | |||
| 8a656ef1e7 | |||
| bd7c031a87 | |||
| c83454889c | |||
| a6f38e439c | |||
| a330ca575c | |||
| 5db9b11b1f | |||
| 14904b98a1 | |||
| 65041d2dc4 | |||
| 58abeef326 | |||
| 5f73cb7e11 | |||
| c9e36e50da | |||
| 5f45f32e1a | |||
| df327075c6 | |||
| c7c11a4120 | |||
| f421ea60c7 | |||
| 2d419f1f34 | |||
| 7948d83649 | |||
| 6a3074f86f | |||
| 91fe2a6277 | |||
| 323ec16417 | |||
| 88f5a8a6cf | |||
| 9f9fb8208c | |||
| cb75173562 | |||
| 336e63d82f | |||
| f99eed9ae3 | |||
| 274336779c | |||
| 0e38722e89 | |||
| 4e3dcc4461 | |||
| 179189c063 | |||
| 578542f8b3 | |||
| 6508321cf9 | |||
| 542ab656f8 | |||
| f035f94460 | |||
| a377a932b5 | |||
| ec45617e0f | |||
| b62e80635b | |||
| fb14af361a | |||
| f4b51c38e7 | |||
| ac64d2d0aa | |||
| 959abed1f4 | |||
| 00cb57cdd6 | |||
| 7ac68bdf68 | |||
| 82490e958e | |||
| 4844ea5e35 | |||
| 43d78dd060 | |||
| 071d833e69 | |||
| 8701fa3886 | |||
| 9713682640 | |||
| 7991a2e374 | |||
| b6d3921429 | |||
| 9b2b233e95 | |||
| 4bd220f20d | |||
| 01c25ab51d | |||
| 4d53a943b4 | |||
| eee9ab5c85 | |||
| 0130dc5098 | |||
| e758b17cf6 | |||
| 6b8a248d0c | |||
| 8769a75ae3 | |||
| e74cce689e | |||
| 9d09ba1914 | |||
| 13a912b7e5 | |||
| 14a6c9d4f1 | |||
| e2b75590cc | |||
| dcf21baf72 | |||
| b79983f5b0 | |||
| b79f84d966 | |||
| eecdbd542f | |||
| d325840f95 | |||
| ce70d764cb | |||
| 738495afc2 | |||
| 8e4afae099 | |||
| 2b16425669 | |||
| b2344302c5 | |||
| ce706efb18 | |||
| e8a651a3b8 | |||
| 54693f8c65 | |||
| 5598af84bf | |||
| 67b9af95ab | |||
| aeafc73dea | |||
| 8b3f7e9159 | |||
| 07f77e4167 | |||
| b7d8ec10e5 | |||
| 9a694c6627 | |||
| 432959dd9b | |||
| 04fb99b05a | |||
| 1829b2a934 | |||
| d3e7163b66 | |||
| 89b7fa4f17 | |||
| d1162e3acf | |||
| 156b24508a | |||
| 35f8695064 | |||
| 84f50b1c5b | |||
| cbb1c2aa4b | |||
| 4e0f7b163c | |||
| b331305f4a | |||
| 92ac94f5dc | |||
| 70a065138b | |||
| 842273f26a | |||
| d34aa3f4ea | |||
| 0c35980ec8 | |||
| 5e59f1c758 | |||
| ff35ccf774 | |||
| 79efbd5fe6 | |||
| 4825c5f8e1 | |||
| 07d17375fd | |||
| 36ef0f8559 | |||
| e007404134 | |||
| 01317c30ea | |||
| f51fce9164 | |||
| 04d9c60b3c | |||
| 6e83a392d5 | |||
| fa805e3303 | |||
| 9db1fa0b0a | |||
| 99f9cb9f0e | |||
| a5e4d49a97 | |||
| c8652e57ae | |||
| 8b4facba11 | |||
| 63ef6d6e04 | |||
| ef8878a4fe | |||
| f9415ff287 | |||
| 9c38952861 | |||
| 6c9d77fa35 | |||
| 0ed62b4940 | |||
| 4b90e619fc | |||
| ca3dbf29c0 | |||
| 9a04fee7e8 | |||
| 6c8cf27c93 | |||
| 4d1315bdcb | |||
| 198294e5a3 | |||
| 9e5cdc606f | |||
| c7eb820d36 | |||
| 2315ae7b86 | |||
| ce1cd1285d | |||
| 0638569a4b | |||
| 0a299dfcfe | |||
| cdf0e102fa | |||
| 18a838ee56 | |||
| ab0138f0be | |||
| fe5800a0bb | |||
| f183be31f5 | |||
| c58a004237 | |||
| 9b90996739 | |||
| 597be6c663 | |||
| 028f1183b4 | |||
| 2747deffe5 | |||
| 6da36b6da7 | |||
| a0c13d4311 | |||
| 7d4d33492b | |||
| 9a1f38c14d | |||
| 1bf8c913c0 | |||
| acb6e3fb81 | |||
| 3b53b3345e | |||
| ae279037c7 | |||
| bf37ebab24 | |||
| 1ce548b224 | |||
| 09ac951d4d | |||
| 6778b99161 | |||
| 1461fd9ffd | |||
| 5c95519e4d | |||
| 8ba72b0263 | |||
| 8fa203664f | |||
| 2365ec2fcc | |||
| f8f6d735e6 | |||
| 076e3c42cc | |||
| 7bedf9d342 | |||
| 44a00668c8 | |||
| 4fa58fa21d | |||
| dad7d80f03 | |||
| 073c47bb3e | |||
| 66f9de2732 | |||
| fea2c4b93a | |||
| e694f4c30f | |||
| 15668145e7 | |||
| 0e2eee38e8 | |||
| f3d10a4c25 | |||
| 06ad1362dc | |||
| c75b7c6f3d | |||
| f12281fe85 | |||
| 2d1b7f755a | |||
| 60077e5b2d | |||
| badad190eb | |||
| 2c01d3330d | |||
| caece35ad0 | |||
| 0b146776cf | |||
| 05a23bbe9d | |||
| 0cded8d4ad | |||
| 3532c62c18 | |||
| eb36844de3 | |||
| 447504564d | |||
| 61d45a58bd | |||
| b7bb890360 | |||
| fe65945cff | |||
| ac98817f95 | |||
| 0ccd38d284 | |||
| 1f1d4ea631 | |||
| 3ba5093b02 | |||
| b55f1494aa | |||
| 9656d10e36 | |||
| 3f11148ea3 | |||
| 43d691196c | |||
| 89745fc33f | |||
| 07292a2dfe | |||
| 0091d4deb2 | |||
| 9582d98a36 | |||
| 4d8295c91e | |||
| 0244715d8e | |||
| 3a964d60e4 | |||
| 52d10be6c5 | |||
| 6d68b7af47 | |||
| ba0b6ee542 | |||
| 3a64542236 | |||
| d300728996 | |||
| 90bbc62e5d | |||
| 7df41c6151 | |||
| 124e910511 | |||
| c09f6da5c4 | |||
| 3dfb59dbb4 | |||
| 8afc61fd91 | |||
| e83302c398 | |||
| 048235a72b | |||
| e52f06c5be | |||
| 6b105ce393 | |||
| 94292adb41 | |||
| cee0866904 | |||
| 5e18f326be | |||
| 9f62b76b00 | |||
| 9a50d1d6e2 | |||
| 52e1bbe56f | |||
| 44020548db | |||
| c41af2c60b | |||
| cfb619bbf9 | |||
| 930d4783f8 | |||
| d9fc21c426 | |||
| e46c83f3b3 | |||
| 524432b91b | |||
| 496db3999a | |||
| c750a8778c | |||
| 81730b63c4 | |||
| 0dceba0ff2 | |||
| a9e730f10f | |||
| 0af4024a07 | |||
| 2acfb8af27 | |||
| 714b002cf5 | |||
| c46e11f72f | |||
| 316eca7ede | |||
| af542c8167 | |||
| 379ae6a845 | |||
| 3d4a213caa | |||
| 0591785b67 | |||
| bd0e7984fb | |||
| f783873de7 | |||
| 8c21f54144 | |||
| cb513d4153 | |||
| 08b32b91ca | |||
| 293f627b0e | |||
| 49ad125bd3 | |||
| 34eb6c9f2b | |||
| 817ab41136 | |||
| 83a301d86f | |||
| cad5b3a2de | |||
| cfdd66a631 | |||
| 8bb7c687a8 | |||
| b4252cfe60 | |||
| 98ce49abaf | |||
| 33a830fe07 | |||
| 0d86b801ee | |||
| d3c29890f4 | |||
| 0b6a474c2b | |||
| b3a1b1f38e | |||
| 895ffb6180 | |||
| 31a8868b86 | |||
| 29388820bf | |||
| acafb97b04 | |||
| 32b5acb265 | |||
| 45d5598db0 | |||
| 909fb7b3a0 | |||
| e8c87ec04d | |||
| 8e01419e14 | |||
| 841a87ffd4 | |||
| f36e0f1a0e | |||
| 39f9269643 | |||
| 17bcf69f19 | |||
| 526803ccdf | |||
| 2e8aad7d10 | |||
| aff895db27 | |||
| 0832b270fa | |||
| c0a590623d | |||
| d7f7a9a72d | |||
| 7e9e45c274 | |||
| b82b01bf5e | |||
| d8a37833f3 | |||
| 1b7b85d1d3 | |||
| a9c40f04d2 | |||
| 228db9f133 | |||
| 01354a84cc | |||
| 65a5d15aae | |||
| 071aac4bef | |||
| 75024e1520 | |||
| 9d48bd9047 | |||
| 6274f2d4b3 | |||
| f266b681f7 | |||
| b170560cba | |||
| 7189fd2457 | |||
| b47e95f91f | |||
| 943d025759 | |||
| 1b18708a53 | |||
| fdc742bb91 | |||
| 8c651120ae | |||
|
|
43e1319c5f | ||
| 870bca5d19 | |||
| 1e74d186f9 | |||
| 03ea886782 | |||
| 7556c1fae6 | |||
| cdfc999e68 | |||
| 8275728395 | |||
|
|
c49866d356 | ||
|
|
4a30be42c4 | ||
|
|
3c09859cef | ||
| 2272c73f03 | |||
| 414164f1dc | |||
| 4156cdaa3f | |||
| 721d4324b0 | |||
| 401c64d2f0 | |||
| dd333161af | |||
|
|
aaca910ace | ||
| 9b8b558bf2 | |||
| 5e900ffe29 | |||
| 274d3a749e | |||
| b554f66d9c | |||
| 9d1c4f0de2 | |||
| b38adce510 | |||
| 7fb02db5f6 | |||
| 42c1269b69 | |||
| c572a25e38 | |||
| e8247924c6 | |||
| ce6fafd16e | |||
| dd91427496 | |||
| f0a55f9682 | |||
| 380b6fb5dc | |||
| e3ad0ac672 | |||
| 204c8e3388 | |||
| 462d52c612 | |||
| 890e802fcc | |||
| 597194a47b | |||
| 75a3deda21 | |||
| d1fcbb6ca7 | |||
| d85bf8b74e | |||
| 65501b3fb9 | |||
| 0c52383863 | |||
| 2a7457de98 | |||
| c3404822fc | |||
| ac2881a6a6 | |||
| bb33d3fcca | |||
| 575c31ac42 | |||
| 812e3c9341 | |||
| a0cda002c7 | |||
| 9569380143 | |||
| 40f4a3e0b5 | |||
| 024ee18982 | |||
| ffd4e4c171 | |||
| 7ffef5718f | |||
| 3ccf7739ec | |||
| aaf15d6909 | |||
| 0e59932a48 | |||
| c2b5a46ee6 | |||
| 49a8a4976e | |||
| 9cb03ae917 | |||
| c3c26d35af | |||
| 67bf91e9df | |||
| 061ae93a48 | |||
| aa3af0a76f | |||
| 9299407c72 | |||
| 2f6ee065cf | |||
| 7423b0e544 | |||
| 70f1c30d07 | |||
| 05a4dab2f4 | |||
| 3aa43334a4 | |||
| 156f1fbaaf | |||
| d8cedab5f0 | |||
| e29e95e13f | |||
| 218f35af86 | |||
| f83e9e00cc | |||
| 6167ec8231 | |||
| c6b81dc550 | |||
| a0e2523641 | |||
| cf51f01952 | |||
| 27e8de9e7e | |||
| 114fc3f495 | |||
| 1f38016170 | |||
|
|
23ef2e843e | ||
| db1dd78a9e | |||
|
|
329731f452 | ||
|
|
38da8ee85a | ||
|
|
1bce775b14 | ||
| 32c6179b86 | |||
| df7f39234c | |||
| bd6d964850 | |||
| 03fddf4829 | |||
| d894f2d7cb | |||
| 4619e197c9 | |||
| 3cf1b6477b | |||
| 324c2139b8 | |||
| 5e513e5047 | |||
| c092639a93 | |||
| 9ccd7e74a1 | |||
| 4e61cc9e78 | |||
| 768cb4eae6 | |||
| a06714c25f | |||
| 79d75e5234 | |||
| 5db4841fb8 | |||
| faa47870d0 | |||
| 15d06cdad1 | |||
| 384c87398b | |||
| 80457bde42 | |||
| f516c6676f | |||
| aa6a232b35 | |||
| 1b343339ab | |||
| c410016e37 | |||
| 2467f24ead | |||
| 55e486155e | |||
| ba07ccd951 | |||
| 31d153dd8d | |||
| 173b8c77dc | |||
| 3f893a6039 | |||
| 523888b3da | |||
| 0097cb07f7 | |||
| c7a2eba3e3 | |||
| e0df98d1af | |||
|
|
6d4ce75ca9 | ||
|
|
d108197f0f | ||
|
|
76ff373eee | ||
|
|
139a8618ca | ||
| a42264ee03 | |||
| bb9aa537f4 | |||
| 39e58da6fe | |||
| 8c6cea7465 | |||
| a9403e48cd | |||
| 667c852bf1 | |||
| d716f3540a | |||
| 25e393b406 | |||
| c25e1485d3 | |||
| 669364cebe | |||
| eba01a2e0e | |||
| 4677fadfb4 | |||
| edff5c899b | |||
| 287f152eeb | |||
| 2deacd6747 | |||
| 5054559a07 | |||
| ad39a8cc6f | |||
| b75f155899 | |||
| 208b86c4ce | |||
| 4255bb055f | |||
| 1ba179f968 | |||
| 3828c80a67 | |||
| 58db1edf2f | |||
| 47aa102d4c | |||
| d2903db557 | |||
| fd87c6780f | |||
| fb76581214 | |||
| a65a1d175f | |||
| 1a53765e80 | |||
| d7c9a99635 | |||
| c2e8f81f61 | |||
|
|
0aa59aacd6 | ||
|
|
d1026c9744 | ||
|
|
20bb0d25a8 | ||
| 6e02c303b3 | |||
| 9fc48aef73 | |||
|
|
ec78f7abea | ||
| 243817eb01 | |||
| 5e0a99767b | |||
| 665bc2bf01 | |||
|
|
cd07be9a8f | ||
|
|
9a5200ac67 | ||
|
|
9c66a01101 | ||
|
|
9b1fa54009 | ||
|
|
5524348974 | ||
|
|
a12005dc7b | ||
|
|
114cd5b6d8 | ||
|
|
efbb124ce3 | ||
|
|
9afe6d4d5d | ||
|
|
48f676dc8d | ||
|
|
1ddc65ff68 | ||
| 5f3e3f750b | |||
|
|
186310a42b | ||
| 47af8a40cf | |||
| d9f9f3c8ca | |||
|
|
1b2d784a64 | ||
|
|
fd909a9951 | ||
|
|
52941ff606 | ||
|
|
9553442b0a | ||
|
|
6b551adcb6 | ||
|
|
2877d8a736 | ||
| fc3124a6c4 | |||
|
|
a5e5268aca | ||
|
|
7a8fe1df0e | ||
|
|
df197db426 | ||
|
|
02981bdebf | ||
| aaea18c21a | |||
| 3e902aa38d | |||
|
|
c36b351e93 | ||
|
|
8bf12f392e | ||
| cae9f381b3 | |||
|
|
22de2e1eba | ||
|
|
4c7f07e7a2 | ||
|
|
ce3d46e3db | ||
|
|
67b8f5d6b2 | ||
|
|
82fef6cc3b | ||
| 6ba8285bd2 | |||
| 71d25cbb2d | |||
|
|
bcecf9b334 | ||
|
|
3cb3c46a6c | ||
| a05d163a14 | |||
| 5352b371c6 | |||
| 209eafedd8 | |||
|
|
51832ce6df | ||
|
|
094ab632cc | ||
| 56a6b14f48 | |||
|
|
d03586d2bc | ||
|
|
2f074deef6 | ||
|
|
e4391c29cd | ||
|
|
3d70d0e481 | ||
|
|
cc7d2284e6 | ||
| cc955436c9 | |||
| 09f9381271 | |||
|
|
cf317bfeac | ||
|
|
436372625b | ||
|
|
c73e4464f0 | ||
|
|
7fc0b97342 | ||
| 2932c1ee28 | |||
|
|
5672532cbe | ||
|
|
32f479a334 | ||
|
|
ad0ad1ab97 | ||
|
|
fc48b53945 | ||
| 1074d276b6 | |||
| 0ee3f5dc7c | |||
| 5b686f98e4 | |||
|
|
87502479a9 | ||
|
|
b20ee9ad9b | ||
|
|
2223a76834 | ||
|
|
cdbab4466d | ||
|
|
349baa3a6a | ||
|
|
c14b5ee281 | ||
|
|
584358795f | ||
| a28faf3a07 | |||
| ada8e9c712 | |||
|
|
ecb667c677 | ||
| ec5db836bc | |||
|
|
bb9f75e817 | ||
|
|
4d4fa005dc | ||
| 71a8636ab2 | |||
|
|
5a36687f42 | ||
|
|
b6220327cf | ||
|
|
228b0fc758 | ||
| b30df53ad0 | |||
|
|
b1c13e739e | ||
|
|
2f924ac6b3 | ||
|
|
25c35fd6d0 | ||
| 0f4cadecf0 | |||
| bf170cc2e9 | |||
|
|
b5c0e704a5 | ||
| 8eb90052f1 | |||
|
|
14d1dbb00f | ||
|
|
c1c94ec02a | ||
|
|
8188a99272 | ||
|
|
3accfe155d | ||
|
|
b7e1230dd9 | ||
|
|
4b1170fdce | ||
|
|
91e11a8ed4 | ||
|
|
35fa8d5a4f | ||
|
|
e0b86cf160 | ||
|
|
2531e0ee7f | ||
|
|
f3ab7ee6f2 | ||
|
|
061bf62f62 | ||
|
|
6a94310568 | ||
|
|
27e24c592b | ||
|
|
873daa4fb4 | ||
|
|
e4f21a9a29 | ||
| a780516770 | |||
|
|
2eebcb7f6c | ||
|
|
60b831f33b | ||
|
|
7a42453080 | ||
|
|
2640786465 | ||
|
|
dc6eb424a9 | ||
|
|
c80a31f5cb | ||
|
|
ea3515d31c | ||
|
|
a935a42528 | ||
|
|
bfe722d941 | ||
|
|
326e2c67e4 | ||
|
|
f05a5ee498 | ||
|
|
4dec8247a2 | ||
|
|
165b486547 | ||
|
|
2dd13261bc | ||
|
|
1353b358b8 | ||
|
|
5f738942e0 | ||
|
|
0a5eff6485 | ||
|
|
11d6bbafdf | ||
|
|
ceef0d7e2f | ||
|
|
4c0a08bef2 | ||
|
|
45754f1f23 | ||
|
|
54f242d0c5 | ||
| 238a1b418d | |||
| feab7e8536 | |||
| 8ef29af2a9 | |||
|
|
e83ad9fd6e | ||
|
|
62b7877238 | ||
|
|
86365203d2 | ||
|
|
db6209bda1 | ||
|
|
ef06c112f8 | ||
|
|
56c9c4ff67 | ||
|
|
dc97e718aa | ||
|
|
81f62c9a69 | ||
|
|
117dc6ea9c | ||
|
|
4c8251d683 | ||
| 5d241aa710 | |||
| 0da378440f | |||
| 1f5f7ed0cd | |||
|
|
33fa9a743c | ||
|
|
d0c3293246 | ||
|
|
b09ecea7a4 | ||
|
|
c8d3c0b935 | ||
|
|
72939267e1 | ||
|
|
a3613b2c52 | ||
|
|
5a37a75e4d | ||
|
|
4bf482d79a | ||
|
|
4b7c21342c | ||
| f4adff2a6c | |||
|
|
517f65e1ec | ||
|
|
0f05c94e4b | ||
|
|
9f8e2a646b | ||
|
|
db8ee6163a | ||
|
|
2c396ff007 | ||
|
|
177039c5e1 | ||
|
|
fec0a698e7 | ||
|
|
0a23035756 | ||
|
|
bacbf97228 | ||
| d839b1e53e | |||
| 7c9481a51c | |||
|
|
1c1c2b20b1 | ||
|
|
694cbb5543 | ||
|
|
05444297a5 | ||
|
|
f29f0c3fe3 | ||
|
|
0dd12ea53c | ||
|
|
0412716cb5 | ||
| f0660d0c95 | |||
|
|
66fefa6664 | ||
|
|
4e94166b09 | ||
|
|
73e7745d13 | ||
|
|
4b096b8c84 | ||
|
|
300528bcc6 | ||
|
|
2677f1ad84 | ||
|
|
7f28c29d10 | ||
|
|
f0498437e3 | ||
|
|
e231f46944 | ||
|
|
68c9c2c000 | ||
| 45c9d0eddd | |||
|
|
15bd5534a9 | ||
|
|
262dbccbbe | ||
| a8b7a67797 | |||
|
|
8d66251b42 | ||
|
|
1ec5ade03d | ||
| 75ccc2637f | |||
|
|
16f408790e | ||
| 828daa073f | |||
|
|
8d965486d8 | ||
|
|
a5025639c9 | ||
|
|
6ec818bf84 | ||
|
|
33d1f13b7a | ||
|
|
a7bf806955 | ||
|
|
15c5ee5585 | ||
|
|
7724f7f6f2 | ||
|
|
5c0ad32679 | ||
|
|
be0fe44b54 | ||
|
|
4f31cc811a | ||
|
|
b1f27aad30 | ||
|
|
2add2a85a8 | ||
|
|
bc37096e1b | ||
|
|
03421a9310 | ||
|
|
96b0c89261 | ||
|
|
b6d76a8094 | ||
|
|
10531e2ebf | ||
|
|
7d0c056bc2 | ||
|
|
93638c2fc4 | ||
|
|
859a973919 | ||
|
|
84f7793b54 | ||
|
|
6eea28d926 | ||
|
|
2526b6b59a | ||
|
|
fcdbb26f47 | ||
|
|
c0a970caf2 | ||
|
|
fa6a28585d | ||
|
|
38de88bf80 | ||
|
|
72d11d7392 | ||
|
|
5ece5215b0 | ||
|
|
24bef72857 | ||
|
|
dcc6b5536c | ||
|
|
bd77ad6e2c | ||
|
|
d674f63567 | ||
|
|
83488a16ec | ||
| bc8ed2dcfa | |||
|
|
fe751fb008 | ||
| 5febecae81 | |||
| 49f1a1d40b | |||
|
|
756fc7acc8 | ||
|
|
c6a14a6dba | ||
|
|
a99e6abe6d | ||
|
|
a903dd2cf3 | ||
|
|
e9769af04d | ||
|
|
dd255a2e4a | ||
| d9f22e2336 | |||
| b67fd4cc3d | |||
|
|
9052f3245f | ||
|
|
f246813e35 | ||
|
|
aa8b42041b | ||
|
|
24caa3dc5e | ||
|
|
6434f88ecb | ||
|
|
ac3ef41d3d | ||
|
|
f5037acb43 | ||
|
|
b8c5817bf8 | ||
|
|
027cd8b81a | ||
|
|
2d4e8e6119 | ||
|
|
a79d23eacc | ||
|
|
3798f350c0 | ||
|
|
50b63cbafa | ||
|
|
a726553c7d | ||
|
|
e1abca0be9 | ||
|
|
9a310b29c1 | ||
|
|
ed3b4fefd4 | ||
|
|
0c7990dd61 | ||
|
|
6de7c72752 | ||
|
|
4347477a69 | ||
|
|
fc97c41629 | ||
|
|
a3d784b812 | ||
|
|
a5ba080fee | ||
|
|
05dfb08b67 | ||
|
|
43baa7ca4c | ||
|
|
8e9ee4d813 | ||
|
|
5bc11bc320 | ||
|
|
23d6b6bee1 | ||
|
|
bf22e9e0b1 | ||
|
|
ed62cdcd06 | ||
|
|
decc9240eb | ||
|
|
a2c1f7354f | ||
|
|
222d9e1f74 | ||
| 54e7b79ca3 | |||
|
|
8ff54d6363 | ||
|
|
34a4024224 | ||
|
|
96b5422a56 | ||
|
|
f53e1a4164 | ||
|
|
b479f23db4 | ||
|
|
905aeb912d | ||
|
|
860f908f82 | ||
|
|
f107929a14 | ||
|
|
1b0f6063cb | ||
|
|
7674fa2e71 | ||
|
|
1f16286dca | ||
|
|
355c5b19b2 | ||
|
|
ec79b0bfab |
18
.env.example
18
.env.example
@ -3,12 +3,12 @@
|
|||||||
# Old Postgres database: only the source of `peppa db migrate-to-sqlite` (PEP-36)
|
# Old Postgres database: only the source of `peppa db migrate-to-sqlite` (PEP-36)
|
||||||
# DATABASE_URL=postgres://peppa:peppa@127.0.0.1:5433/peppa
|
# DATABASE_URL=postgres://peppa:peppa@127.0.0.1:5433/peppa
|
||||||
|
|
||||||
# Gitea (git.telecom.quest) — token with repo + org scope
|
# Gitea (git.vibe42.kz) — token of peppa-bot with repo scope
|
||||||
GITEA_URL=https://git.telecom.quest
|
GITEA_URL=https://git.vibe42.kz
|
||||||
GITEA_TOKEN=
|
GITEA_TOKEN=
|
||||||
GITEA_TEMPLATE_REPO=peppa/template
|
GITEA_TEMPLATE_REPO=peppa-bot/template
|
||||||
# Peppa's own repo (footer link, scripts/ci.sh --pr, scripts/peppa-release.sh)
|
# Peppa's own repo (footer link, scripts/ci.sh --pr, scripts/peppa-release.sh)
|
||||||
# GITEA_PLATFORM_REPO=peppa/peppa
|
# GITEA_PLATFORM_REPO=peppa-bot/peppa
|
||||||
|
|
||||||
# Where project repos are cloned and sessions run
|
# Where project repos are cloned and sessions run
|
||||||
PEPPA_WORKSPACES=~/peppa/workspaces
|
PEPPA_WORKSPACES=~/peppa/workspaces
|
||||||
@ -32,3 +32,13 @@ GITEA_OAUTH_CLIENT_SECRET=
|
|||||||
# Вход через Google (PEP-90): OAuth-клиент из Google Cloud, redirect URI <PEPPA_WEB_URL>/auth/google/callback
|
# Вход через Google (PEP-90): OAuth-клиент из Google Cloud, redirect URI <PEPPA_WEB_URL>/auth/google/callback
|
||||||
# GOOGLE_CLIENT_ID=
|
# GOOGLE_CLIENT_ID=
|
||||||
# GOOGLE_CLIENT_SECRET=
|
# GOOGLE_CLIENT_SECRET=
|
||||||
|
|
||||||
|
# Распознавание речи (PEP-45/108): стори голосом в своём Telegram-боте и кнопка «Голосом» в вебе.
|
||||||
|
# Свой сервис Пеппы — infra/whisper (faster-whisper, 127.0.0.1:8178, без ключа); облако — OpenAI/Groq с ключом.
|
||||||
|
# PEPPA_TRANSCRIBE_URL=http://127.0.0.1:8178/v1
|
||||||
|
# Язык записи — язык интерфейса говорящего (kk / en, PEP-131); для русского интерфейса — этот.
|
||||||
|
# auto — язык не передаётся никому, сервис определяет сам.
|
||||||
|
# PEPPA_TRANSCRIBE_LANG=ru
|
||||||
|
# PEPPA_TRANSCRIBE_KEY=
|
||||||
|
# PEPPA_TRANSCRIBE_MODEL=whisper-1
|
||||||
|
# PEPPA_TRANSCRIBE_TIMEOUT_SEC=300
|
||||||
|
|||||||
@ -20,7 +20,7 @@ jobs:
|
|||||||
# The runner has the host's docker.sock: only branches of this repository, never forks.
|
# The runner has the host's docker.sock: only branches of this repository, never forks.
|
||||||
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository
|
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository
|
||||||
runs-on: peppa-trusted
|
runs-on: peppa-trusted
|
||||||
timeout-minutes: 30
|
timeout-minutes: 45
|
||||||
env:
|
env:
|
||||||
# Peppa's data is SQLite (a temp file per test file). Postgres on the host is only the source
|
# Peppa's data is SQLite (a temp file per test file). Postgres on the host is only the source
|
||||||
# for the Postgres → SQLite migration test, which makes and drops its own database.
|
# for the Postgres → SQLite migration test, which makes and drops its own database.
|
||||||
@ -34,7 +34,13 @@ jobs:
|
|||||||
node-version: "26"
|
node-version: "26"
|
||||||
- name: tools
|
- name: tools
|
||||||
run: |
|
run: |
|
||||||
apt-get update -qq && apt-get install -y -qq tmux >/dev/null
|
# PEP-271: a mirror mid-sync fails `apt-get update`; with `&&` the install was skipped silently
|
||||||
|
# and every e2e test died later on «spawn tmux ENOENT». Retry, then fail here if tmux is missing.
|
||||||
|
for i in 1 2 3; do
|
||||||
|
{ apt-get update -qq && apt-get install -y -qq tmux >/dev/null; } && break
|
||||||
|
echo "apt: attempt $i failed, retrying"; sleep $((i * 15))
|
||||||
|
done
|
||||||
|
command -v tmux >/dev/null || { echo "::error::tmux was not installed (apt mirror unavailable)"; exit 1; }
|
||||||
# Job-local prefix: the node toolcache is shared between jobs running at the same time
|
# Job-local prefix: the node toolcache is shared between jobs running at the same time
|
||||||
# (PR + push of one commit), and two global installs into it collide (ENOTEMPTY/EEXIST).
|
# (PR + push of one commit), and two global installs into it collide (ENOTEMPTY/EEXIST).
|
||||||
npm install -g --prefix "$RUNNER_TEMP/tools" pnpm@12.18.0 @fission-ai/openspec@2.0.0 >/dev/null
|
npm install -g --prefix "$RUNNER_TEMP/tools" pnpm@12.18.0 @fission-ai/openspec@2.0.0 >/dev/null
|
||||||
@ -49,9 +55,14 @@ jobs:
|
|||||||
- name: typecheck
|
- name: typecheck
|
||||||
if: (success() || failure()) && steps.install.outcome == 'success'
|
if: (success() || failure()) && steps.install.outcome == 'success'
|
||||||
run: bash .gitea/peppa-check.sh typecheck
|
run: bash .gitea/peppa-check.sh typecheck
|
||||||
- name: build
|
- id: build
|
||||||
|
name: build
|
||||||
if: (success() || failure()) && steps.install.outcome == 'success'
|
if: (success() || failure()) && steps.install.outcome == 'success'
|
||||||
run: bash .gitea/peppa-check.sh build
|
run: bash .gitea/peppa-check.sh build
|
||||||
|
# PEP-217: weight of the first-load JS of every route against docs/bundle-baseline.json (+10 % fails).
|
||||||
|
- name: bundle
|
||||||
|
if: (success() || failure()) && steps.install.outcome == 'success' && steps.build.outcome == 'success'
|
||||||
|
run: bash .gitea/peppa-check.sh bundle
|
||||||
- name: test
|
- name: test
|
||||||
if: (success() || failure()) && steps.install.outcome == 'success'
|
if: (success() || failure()) && steps.install.outcome == 'success'
|
||||||
run: bash .gitea/peppa-check.sh test
|
run: bash .gitea/peppa-check.sh test
|
||||||
|
|||||||
@ -1,34 +0,0 @@
|
|||||||
# Память проекта
|
|
||||||
|
|
||||||
Пишет агент через MCP `remember` (PEP-30). Коротко: команды, соглашения, грабли, решения.
|
|
||||||
|
|
||||||
## Грабли
|
|
||||||
- Браузер chrome-devtools MCP может быть занят другой сессией («browser is already running») — UI проверять на временной базе: свой seed + `next dev -p <порт>` из worktree с `PEPPA_DB`/`PEPPA_HOME`, вход `peppa web login-link`, страницу читать `curl -b jar`.
|
|
||||||
- peppa-bot не может создавать организации в Gitea (403, флаг пользователя) — организацию создаёт админ Gitea и добавляет бота в Owners; после переноса раннер уровня peppa-bot репо не покрывает, нужен свой (`setupCi` / `peppa ci connect`).
|
|
||||||
- Общая рабочая копия может стоять на чужой ветке — работай в `git worktree`; CLI из worktree против живой системы: `set -a; . /Users/telecom/Dev/Peppa/.env; set +a` и `<worktree>/packages/cli/bin/peppa …`.
|
|
||||||
- Один файл e2e: `env -u NODE_TEST_CONTEXT node --test --test-reporter=spec test/<file>.test.ts` (внутри сессии Claude без этого вывод бинарный); CLI из теста с моком в том же процессе — только async execFile, execFileSync вешает мок.
|
|
||||||
- node --test из шелла Claude Code молча ничего не запускает («run() is being called recursively») — в env висит NODE_TEST_CONTEXT; запускать `env -u NODE_TEST_CONTEXT -u NODE_TEST_WORKER_ID node --test …`
|
|
||||||
- Gitea 1.22 `GET /compare/<base>...<head>` принимает только имена веток — SHA даёт 404 (PEP-101); mock-gitea ведёт себя так же. Сравнение — подсказка, не гейт: при ошибке мержить обычным путём.
|
|
||||||
- `pnpm run ci` из шелла Claude пишет «all green», но e2e не запускается (NODE_TEST_CONTEXT, «e2e 1/1 (0s)») — запускать `env -u NODE_TEST_CONTEXT -u NODE_TEST_WORKER_ID pnpm run ci`; `next dev` создаёт apps/web/AGENTS.md — не коммитить.
|
|
||||||
- В свежем worktree нет node_modules — тесты падают «Cannot find package '@peppa/db'»; сначала `pnpm install --frozen-lockfile` (секунды).
|
|
||||||
- Сверка экранов без браузера (chrome-devtools занят соседней сессией): стенд — `PEPPA_HOME`/`PEPPA_DB` во временный каталог, `peppa db migrate`, `DATABASE_URL=<тот же файл> node apps/web/scripts/mock-ui-seed.ts mock-pm`, `peppa web login-link mock-pm`, `next dev -p 3199`; страницы забирать curl с cookie и искать слова из колонки «Нельзя» в тексте без `<script>`; вид «Инженер» — строка settings `ui.mode:<userId>` = `"engineer"`.
|
|
||||||
|
|
||||||
## Решения
|
|
||||||
- Продукт по-настоящему (PEP-112): секреты проекта доходят до выкатки сами (хук `deploy-env` → override в `peppa-deploy.sh`), не через secrets Actions; `ANTHROPIC_*/CLAUDE_*/OPENCODE_*` — только продукту; нужное от владельца — `product.needs:<id>` (MCP `declare_needs`); приёмка — `productReviewTick` (при ролях PEP-84). После мержа правок `template/` — `scripts/push-template.sh` и `peppa ci connect <KEY>` старым проектам.
|
|
||||||
- Репозитории платформы — в организации Gitea `peppa` (PEP-4): `peppa/peppa`, `peppa/template`; старые адреса `peppa-bot/…` живут редиректом — не создавать `peppa-bot/peppa|template` заново. Проект переносит `peppa project transfer <KEY> <owner>`.
|
|
||||||
- Чаты (PEP-62) — проекция: новое событие для чата = строка в EVENT_TEXT (core/chats.ts), код источников не трогать; сообщения короткоживущие (TTL), источник правды — events/questions/releases/incidents.
|
|
||||||
- tmux-сервер по умолчанию: newSession чистит его глобальное окружение от GITEA_*/PEPPA_*/MOCK_*/DATABASE_URL (PEP-69; при PEPPA_TMUX_SOCKET не трогает); агенту нужное — только через new-session -e.
|
|
||||||
- Вход через Google (PEP-90): идентичность — google_sub, по почте учётки не склеиваем; без GOOGLE_CLIENT_ID/SECRET кнопки нет; в тестах эндпоинты подменяет GOOGLE_OAUTH_BASE (mock-google). `pnpm typecheck` в apps/web может падать на устаревших .next/types (auth/callback, auth/start) — не от правок.
|
|
||||||
- Подписки без остановок (PEP-107): ротация claude↔codex, когда нет того же провайдера (PEPPA_ROTATE_CROSS=off выключает, OpenCode не участвует); займы суперадмина и отметки предупреждений — строки settings (`subscription.loan:<pool>:<sub>`, `subscription.warned:<sub>:<pool>`), без миграций; картина пула — `poolOverview` в core/subscription-care.ts.
|
|
||||||
- Группы чатов (PEP-109) связываются через свой бот пользователя: `chats.tg_bot_user_id` (null — общий бот, только суперадмин без своего бота); код связки привязан к боту и чужим ботом не сжигается; новые исходящие в группу маршрутизируются по chat_id через `ownByChat` (`chatGroupBots`) — отдельный outbox не нужен.
|
|
||||||
- Новый пользователь (PEP-113): `announceNewUser` (core/new-users.ts) зовётся внутри функций создания учётки, событие уведомлений `users` только суперадминам; новый способ регистрации — добавить вызов; новое событие в NOTIFY_EVENTS требует строки в PUSH_TITLE бота и скрытых полей в настройках для не-админа.
|
|
||||||
- Слова по режиму (PEP-123): в вебе «стори»/«раннер» не пишем строкой — `w.task("acc")`, `w.runner()` из `await words()` (сервер) или `useWords()` (клиент), только-инженерное — под `w.engineer`; тексты без читателя (EVENT_TEXT чатов, вопросы PM из runner, Telegram, push, подписи core) — всегда «задача», «агент», «Peppa FACTORY», «вы»; промпты агентам, MCP и CLI не трогаем.
|
|
||||||
- Комментарий к стори в бэклоге (PEP-115) разбирает аналитик в тике вачдога (`storyRefineTick`), а не server action; курсор `refine.task:<taskId>` в settings, старше 60 мин не трогает, работает и при выключенных ролях PEP-84 (`PEPPA_STORY_REFINE=off` выключает). Новая роль модели = ветка в `mock-intake` по тексту промпта.
|
|
||||||
- Имена подписок (PEP-121) видят только суперадмин и автор: любое новое место показа подписки — через `visibleSubscriptionName`/`publicSubscriptionName` (core/subscription-names.ts), в вебе у сессий — `<SubscriptionName>`; сообщения участникам проекта — без имени. Экраны на демо-данных без браузера: `PEPPA_DB=<tmp> peppa db migrate`, `DATABASE_URL=<tmp> node apps/web/scripts/mock-ui-seed.ts`, `next dev -p <порт>`, `peppa web login-link mock-pm` + curl с cookie.
|
|
||||||
|
|
||||||
## Соглашения
|
|
||||||
- Тексты экранов вида «Продакт» — в файлах переводов core (`core/help-texts.ts`, PEP-122: объект ru/kk/en одной формы, страница берёт ru, пока нет языка интерфейса); тест сверяет ru с колонкой «Нельзя» docs/glossary.md — новые экраны делать так же.
|
|
||||||
|
|
||||||
## Команды
|
|
||||||
- Глазами проверить веб из worktree без живых данных: свои PEPPA_HOME/PEPPA_DB/DATABASE_URL (один файл) + PEPPA_SECRET + PEPPA_WEB_URL=http://localhost:3222 → `peppa db migrate`, `node apps/web/scripts/mock-ui-seed.ts mock-pm`, `next dev -p 3222` в apps/web, `peppa web login-link mock-pm`; chrome-devtools MCP бывает занят другой сессией — снимки делает headless Chrome со своим --user-data-dir (сначала открыть ссылку входа, потом --screenshot).
|
|
||||||
- Проверка словаря (PEP-124): `pnpm lint` падает, когда в файле экрана слова из «Нельзя» docs/glossary.md стало больше, чем в docs/glossary-baseline.json; чистишь тексты — `pnpm lint --update` (список только уменьшать, руками не дописывать); текст режима «Инженер» или слово в бытовом значении — комментарий `glossary-ignore: <почему>`. Ветка, начатая до PEP-124, может покраснеть на lint после rebase — править слова, не baseline.
|
|
||||||
34
.peppa/memory/common.md
Normal file
34
.peppa/memory/common.md
Normal file
@ -0,0 +1,34 @@
|
|||||||
|
# Память проекта
|
||||||
|
|
||||||
|
Пишет агент через MCP `remember` (PEP-30); файл на задачу — `.peppa/memory/<ключ>.md` (PEP-306).
|
||||||
|
|
||||||
|
## Команды
|
||||||
|
- Тесты из шелла Claude: `env -u NODE_TEST_CONTEXT -u NODE_TEST_WORKER_ID node --test --test-reporter=spec test/<file>.test.ts` (иначе тесты молчат). В свежем worktree сначала `pnpm install --frozen-lockfile`.
|
||||||
|
- CLI против живой системы (сервер): `docker exec peppa-watchdog peppa …` (docs/SERVER.md).
|
||||||
|
- Экраны без живых данных: `PEPPA_HOME=<tmp> PEPPA_DB=<tmp>/peppa.db PEPPA_SECRET=x peppa db migrate` (Node < 26 — `node packages/cli/src/index.ts`), `DATABASE_URL=… node apps/web/scripts/mock-ui-seed.ts mock-pm`, в apps/web `node server.ts [--dev] -p <порт>` с тем же env + `PEPPA_WEB_URL=http://localhost:<порт> PEPPA_RUNNER_MODE=inline PEPPA_ROTATE=off`; вход — `peppa web login-link mock-pm`; «Инженер» — settings `ui.mode:<userId>` = `"engineer"`.
|
||||||
|
- Словарь: `pnpm lint`; почистил тексты экрана — `pnpm lint --update` (baseline только уменьшать); новое слово в «Нельзя» — сразу `pnpm lint`, оно может стоять в чужих текстах.
|
||||||
|
|
||||||
|
## Грабли
|
||||||
|
- `resumeSession` без `conversationId` пишет `started`, не `resumed`.
|
||||||
|
- `next dev` правит apps/web/AGENTS.md (`git checkout`, не `rm`) и next-env.d.ts — не коммитить; открывать `localhost`, не 127.0.0.1. В песочнице dev перезагружает страницы по кругу — экраны смотри на `next build` + `node server.ts -p`.
|
||||||
|
- Headless Chrome: playwright-core + `chrome-headless-shell` (песочница: `npx playwright-core install chromium-headless-shell`; библиотеки — .deb bookworm из Packages.gz → `dpkg-deb -x` + LD_LIBRARY_PATH, шрифты fonts-dejavu-core + FONTCONFIG_PATH); вход — `peppa web login-link`; обрыв канала — `globalThis.__peppaLive.ws.close()`.
|
||||||
|
- CLI из теста с моком в том же процессе — только async execFile. Тест не импортирует apps/web статически — `import(new URL(…).href)`.
|
||||||
|
- Шаблонная строка с t()/m() внутри (`` `<b>${t("…")}</b>` ``) i18n-check считает непереведённой — собирай конкатенацией. В apps/bot `m` импортирован как `tr`.
|
||||||
|
- localizeText выбирает вариант по числу НЕпереведённых русских букв, не по кириллице: казахский тоже кириллица.
|
||||||
|
- mock-gitea `POST /tags` ставит настоящий git-тег: нужны коммиты (`addRepo(…, { files })`) и существующий SHA (`gitea.sha(owner, repo, "main")`), иначе `deployProd`/`autoPublish` в тесте молча не срабатывают. Gitea «лежит» — `gitea.down = true`.
|
||||||
|
- git-прокси релея (allowedGitPath) отклоняет %2e/%2f/%5c/%25 и `\`: fetch сворачивает %2e%2e как dot-сегмент.
|
||||||
|
- Новая фраза Claude о лимите — в `parseResetTime` и limits.test.ts. Codex 0.169 без `--full-auto`: режим — `CODEX_DEFAULT_MODE` (providers.ts), срочно — `PEPPA_CODEX_MODE` в .env.
|
||||||
|
- Скорость: `apps/web/scripts/bench-pages.ts`, канал — `bench-live.ts`; правишь live.ts — перезапусти server.ts, не `pkill -f next-server`.
|
||||||
|
- Хук грузит только лёгкий `runner/limit-delay.ts`, не flow.ts. В тесте хука PEPPA_GENERATION = поколение сессии (вставленной руками — 0).
|
||||||
|
- Настройки по префиксу — `keyPrefix(settings.key, "x:")` из @peppa/db, не `like(…"x:%")` (LIKE без индекса). Индексы — тест db-indexes.
|
||||||
|
- Номер миграции занят соседом после мержа — взять meta из main, `pnpm db:generate`, переименовать.
|
||||||
|
- Нет глобального git в контейнере: автор — `gitRelayEnv`; иначе `git -c user.name=peppa-bot -c user.email=peppa-bot@telecom.quest commit`.
|
||||||
|
- Песочница раннера: нет tmux и Node 26 — `node-v26…-linux-x64.tar.gz` (не .xz) в /tmp; tmux — .deb (tmux_3.3a-3, libevent-core-2.1-7, libutempter0) → `dpkg-deb -x` + LD_LIBRARY_PATH. Падают и на main (среда): glossary-check.test, sandbox-hosts.test.ts (нет ssh).
|
||||||
|
- Пропал `.git/worktrees/s<id>`: создать с `HEAD`, `commondir` `../..`, `gitdir`, затем `git reset`.
|
||||||
|
- Зависимость с build-скриптом (ssh2, cpu-features) роняет `pnpm install --frozen-lockfile` (ERR_PNPM_IGNORED_BUILDS): реши в `allowBuilds` pnpm-workspace.yaml.
|
||||||
|
|
||||||
|
## Соглашения
|
||||||
|
- Тесты: места подписки занимай `core.createSession` с `subscriptionId`; очередь ёмкости чисти `moveTask(backlog)`. Конец хода вопроса не создаёт — жди `idle`. Суперадмин — `superadmin()`. Текст чатов — через `stripAsIs`.
|
||||||
|
|
||||||
|
## Решения
|
||||||
|
- Речь — свой faster-whisper (`<Dictate>`). Google: по почте учётки не склеиваем.
|
||||||
4
.peppa/memory/pep-129.md
Normal file
4
.peppa/memory/pep-129.md
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
# Память: PEP-129
|
||||||
|
|
||||||
|
## Соглашения
|
||||||
|
- Словарь в сообщениях ядра (PEP-129/137): `pnpm lint` проверяет литералы в `m()/tr()/t()` packages/core|runner|mcp; подсказку агенту в `m()` не оборачивать; запрещённое слово — переписать (ключ и в `i18n/en|kk`, тестах) или `glossary-ignore: <почему>` строкой выше; человеку мимо переводов — `glossary-user: <почему>`.
|
||||||
4
.peppa/memory/pep-135.md
Normal file
4
.peppa/memory/pep-135.md
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
# Память: PEP-135
|
||||||
|
|
||||||
|
## Соглашения
|
||||||
|
- Инструкция подключения к своему Claude/ChatGPT (PEP-135): `/help/connect`, тексты — `core/connect-texts.ts` (`CONNECT_HELP` ru/kk/en одной формы, тест `connect-help.test.ts`); изменились экраны подключения или инструменты удалённого MCP — править её; копирование — `<CopyText>`.
|
||||||
4
.peppa/memory/pep-154.md
Normal file
4
.peppa/memory/pep-154.md
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
# Память: PEP-154
|
||||||
|
|
||||||
|
## Соглашения
|
||||||
|
- Служебный текст (PEP-154): текст агента/терминала человеку — через `userText` (core/user-text.ts); исключение владельцу не слать — `platformFailure` (строка только для PeppaError).
|
||||||
4
.peppa/memory/pep-158.md
Normal file
4
.peppa/memory/pep-158.md
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
# Память: PEP-158
|
||||||
|
|
||||||
|
## Соглашения
|
||||||
|
- Неудачная версия (PEP-158): `rolled_back`/`failed` → агенту задачи, `returnFailedRelease` (runner/deploy-feedback.ts); счётчик — `attempts` задержки `deploy` (3 — суперадмину, 6 — стоп).
|
||||||
4
.peppa/memory/pep-183.md
Normal file
4
.peppa/memory/pep-183.md
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
# Память: PEP-183
|
||||||
|
|
||||||
|
## Соглашения
|
||||||
|
- Специалисты (PEP-183): агент с непустым character — специалист; подбор — `runner/team-match.ts` (haiku, `PEPPA_TEAM_BIN`), результат `team.match:<taskId>`, порог ожидания `platform.team.waitMin`; в `ensureSessionAgent` порядок: прежний → свободный специалист по профилю → универсал → специалист без очереди.
|
||||||
4
.peppa/memory/pep-195.md
Normal file
4
.peppa/memory/pep-195.md
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
# Память: PEP-195
|
||||||
|
|
||||||
|
## Решения
|
||||||
|
- Привязка Google к чужой Google-only учётке — `mergeUserInto`; с eGov/Gitea — отказ (PEP-195).
|
||||||
4
.peppa/memory/pep-198.md
Normal file
4
.peppa/memory/pep-198.md
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
# Память: PEP-198
|
||||||
|
|
||||||
|
## Соглашения
|
||||||
|
- Один голос (PEP-198): человеку пишет только Аналитик — вопрос агента через `relayAgentQuestion` (runner/question-relay.ts), задачи из чата — только оффер `stories` и кнопка; новая строка сообщения роли — в `ROLE_MESSAGE_KEYS` выше «Агент {name}», иначе он её съест.
|
||||||
4
.peppa/memory/pep-208.md
Normal file
4
.peppa/memory/pep-208.md
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
# Память: PEP-208
|
||||||
|
|
||||||
|
## Решения
|
||||||
|
- Сообщения людям — только через `telegram_outbox`/`push_outbox`: ночная тишина 23–08 (PEP-208) стоит на их выборке; тестам и стенду `PEPPA_NIGHT_QUIET=off`.
|
||||||
4
.peppa/memory/pep-209.md
Normal file
4
.peppa/memory/pep-209.md
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
# Память: PEP-209
|
||||||
|
|
||||||
|
## Решения
|
||||||
|
- Застрявшая задача (PEP-209): лечит `stuckTaskTick` — платформа сама на ревью/в «Готово», агенту — новый процесс (`restartAgent`: старый не вернёт MCP), не `sendToSession`. Новая причина задержки с повторами — `platformDelay` с `retryMin`/`retryAt`, суперадмину кнопки — `buttons: true`.
|
||||||
4
.peppa/memory/pep-212.md
Normal file
4
.peppa/memory/pep-212.md
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
# Память: PEP-212
|
||||||
|
|
||||||
|
## Грабли
|
||||||
|
- QuickJS (PEP-212): строки из хост-функции читай до await; все хэндлы и deferred dispose-ить.
|
||||||
4
.peppa/memory/pep-213.md
Normal file
4
.peppa/memory/pep-213.md
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
# Память: PEP-213
|
||||||
|
|
||||||
|
## Решения
|
||||||
|
- Медленные запросы (PEP-213): `core/request-timing.ts` (`http.Server` в instrumentation.ts, probe в db) → warning Bugsink; порог `PEPPA_SLOW_REQUEST_MS`.
|
||||||
4
.peppa/memory/pep-217.md
Normal file
4
.peppa/memory/pep-217.md
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
# Память: PEP-217
|
||||||
|
|
||||||
|
## Решения
|
||||||
|
- Вес JS: `bundle-check.mjs --update`.
|
||||||
4
.peppa/memory/pep-218.md
Normal file
4
.peppa/memory/pep-218.md
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
# Память: PEP-218
|
||||||
|
|
||||||
|
## Соглашения
|
||||||
|
- Bugsink API (PEP-218): схема — `GET /api/canonical/0/schema/` (2.6.3); `q` = текст + теги `key:value`; числа пользователей нет. Экран — `core/bugsink-errors.ts` (кэш 45 с), действия — `runner/bugsink-errors.ts`.
|
||||||
4
.peppa/memory/pep-221.md
Normal file
4
.peppa/memory/pep-221.md
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
# Память: PEP-221
|
||||||
|
|
||||||
|
## Решения
|
||||||
|
- История (PEP-221): журнал/статусы — `history.db` (core/history.ts), логи — `archive/<вид>/<день>.jsonl.gz`; из основной базы события удаляет только `runRetention` после переноса.
|
||||||
4
.peppa/memory/pep-222.md
Normal file
4
.peppa/memory/pep-222.md
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
# Память: PEP-222
|
||||||
|
|
||||||
|
## Решения
|
||||||
|
- Docker (PEP-222): раннеры по умолчанию `container` (тесты — `PEPPA_DEFAULT_ISOLATION=none`).
|
||||||
4
.peppa/memory/pep-223.md
Normal file
4
.peppa/memory/pep-223.md
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
# Память: PEP-223
|
||||||
|
|
||||||
|
## Грабли
|
||||||
|
- observe.db: схема — `MIGRATIONS` по `user_version` (core/observe.ts); напоминания (PEP-223) — `remindIncidents`; в тестах «бот днём» помечай outbox `sent`, иначе напоминание заменит прежнее.
|
||||||
4
.peppa/memory/pep-224.md
Normal file
4
.peppa/memory/pep-224.md
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
# Память: PEP-224
|
||||||
|
|
||||||
|
## Соглашения
|
||||||
|
- Узкие места: подписка — `pickSubscription`/`rotationCandidate`; агент — `startRunner`/`resumeSession`, модель — `claudePrint`, сообщение — `deliverToUser`; проекты — `listProjects`/`userProjectIds` (`from(projects)` — с `isNull(deletedAt)`); веб → runnerCall; функция от внешнего сервиса — `featureGateView` + `<FeatureGate>` (PEP-224).
|
||||||
7
.peppa/memory/pep-230.md
Normal file
7
.peppa/memory/pep-230.md
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
# Память: PEP-230
|
||||||
|
|
||||||
|
## Грабли
|
||||||
|
- Сервер (PEP-230): docs/SERVER.md. Docker-клиент образа 20.10 (PEP-287).
|
||||||
|
|
||||||
|
## Решения
|
||||||
|
- Живой сайт (с PEP-230 — сервер, контейнеры) — только `scripts/platform-deploy.sh` из `~/peppa/src` на main (docs/SERVER.md); launchd/live-deploy.sh — только откат на Mac.
|
||||||
5
.peppa/memory/pep-231.md
Normal file
5
.peppa/memory/pep-231.md
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
# Память: PEP-231
|
||||||
|
|
||||||
|
## Грабли
|
||||||
|
- Продукт на другой docker — только `scripts/server-move/products-move.sh` (PEP-231, с данными); `peppa deploy redeploy` поднимает с пустыми томами.
|
||||||
|
- Агент в контейнере не видит хост сервера, Mac и Cloudflare (PEP-231): инфраструктуру — скриптом в `scripts/server-move/` + шаги в docs/SERVER.md, выполнить просить суперадмина через `report_blocker`.
|
||||||
4
.peppa/memory/pep-233.md
Normal file
4
.peppa/memory/pep-233.md
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
# Память: PEP-233
|
||||||
|
|
||||||
|
## Соглашения
|
||||||
|
- act_runner (PEP-233/248): идут контейнеры `GITEA-ACTIONS-TASK-*` — не рестартовать; голова без ci.yml или >2 суток — `orphan`, не очередь; `not_taken` — pending, а другие проекты отчитываются.
|
||||||
4
.peppa/memory/pep-234.md
Normal file
4
.peppa/memory/pep-234.md
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
# Память: PEP-234
|
||||||
|
|
||||||
|
## Грабли
|
||||||
|
- SSRF-проверка в `lookup` — только с `agent: false` (keep-alive Node пропускает lookup, PEP-234).
|
||||||
4
.peppa/memory/pep-241.md
Normal file
4
.peppa/memory/pep-241.md
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
# Память: PEP-241
|
||||||
|
|
||||||
|
## Грабли
|
||||||
|
- Codex (PEP-241): доверие папке — по корню основного репо worktree; `-c` режет ключ по точкам — пишем в config.toml CODEX_HOME (`codex-trust.ts`).
|
||||||
4
.peppa/memory/pep-242.md
Normal file
4
.peppa/memory/pep-242.md
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
# Память: PEP-242
|
||||||
|
|
||||||
|
## Решения
|
||||||
|
- `template/` уходит в Gitea сам с выкаткой (PEP-242); старым проектам — `peppa ci connect <KEY> [--secrets-only]`.
|
||||||
4
.peppa/memory/pep-245.md
Normal file
4
.peppa/memory/pep-245.md
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
# Память: PEP-245
|
||||||
|
|
||||||
|
## Грабли
|
||||||
|
- 530 при живом сервере — обрыв Mac → сервер (PEP-245); лечит только перенос адресов (ключ Cloudflare).
|
||||||
4
.peppa/memory/pep-246.md
Normal file
4
.peppa/memory/pep-246.md
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
# Память: PEP-246
|
||||||
|
|
||||||
|
## Грабли
|
||||||
|
- Пути сессий с Mac (PEP-246): `runnerCwd` пересоздаёт копию сам; чистка — `peppa session paths --fix`.
|
||||||
4
.peppa/memory/pep-249.md
Normal file
4
.peppa/memory/pep-249.md
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
# Память: PEP-249
|
||||||
|
|
||||||
|
## Соглашения
|
||||||
|
- Access Hub (PEP-249): новый HTTP-сервис — карточка в `core/connection-catalog.ts` (тест сверяет каждую); меняет данные через GET (Slack) — чтение по методам. Новый не-HTTP вид (PEP-251) — операция в `PROTOCOL_OPERATIONS`, драйвер `GatewayDrivers` (берёт проверенный `address`, DNS не разрешает) и мок в testkit/mock-access.ts. Ответ сервиса агенту (PEP-258) — только через `connectionKeyForms`+`maskConnectionKey`; новый способ ключа — в тест-ловушку access-hub.test.ts.
|
||||||
4
.peppa/memory/pep-250.md
Normal file
4
.peppa/memory/pep-250.md
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
# Память: PEP-250
|
||||||
|
|
||||||
|
## Соглашения
|
||||||
|
- Access Hub (PEP-250): сервис агенту — `request_access`; форму отказа `callConnection` не менять, автозапрос — `refusedCallService`.
|
||||||
4
.peppa/memory/pep-252.md
Normal file
4
.peppa/memory/pep-252.md
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
# Память: PEP-252
|
||||||
|
|
||||||
|
## Грабли
|
||||||
|
- Шлюз Access Hub (PEP-252): `cleanPath` не пускает голое «:» в пути — Google-диапазоны и методы (`A1:B2`, `:batchUpdate`) агент шлёт как `%3A`. OAuth-тесты: `MockOAuthService` + `fetch`, переписывающий адрес сервиса на мок (`toMock`).
|
||||||
4
.peppa/memory/pep-253.md
Normal file
4
.peppa/memory/pep-253.md
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
# Память: PEP-253
|
||||||
|
|
||||||
|
## Решения
|
||||||
|
- Секреты (PEP-253): агенту — `agent_env` при `project.agent-secrets` (нет строки = вкл.); в тестах — `{ agent: true }`.
|
||||||
4
.peppa/memory/pep-254.md
Normal file
4
.peppa/memory/pep-254.md
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
# Память: PEP-254
|
||||||
|
|
||||||
|
## Решения
|
||||||
|
- Access Hub (PEP-254): журнал — только `appendJournal` (core/connection-journal.ts, цепочка хэшей; правка строки задним числом = нарушение), ключ подключения — `sealConnectionSecret`/`openConnectionSecret`, не `encrypt`/`decrypt`.
|
||||||
4
.peppa/memory/pep-255.md
Normal file
4
.peppa/memory/pep-255.md
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
# Память: PEP-255
|
||||||
|
|
||||||
|
## Грабли
|
||||||
|
- Очередь проверок (PEP-255): `checks.queue` — `projects` (своя зависшая голова) и `lanes` (`ciLane`); `requestRebase` → false = просьба не ушла.
|
||||||
4
.peppa/memory/pep-256.md
Normal file
4
.peppa/memory/pep-256.md
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
# Память: PEP-256
|
||||||
|
|
||||||
|
## Грабли
|
||||||
|
- tmux на сервере (PEP-256) — контейнер `peppa-tmux`, сервисы — клиенты (`PEPPA_TMUX_EXTERNAL`); его образ меняет только `platform-deploy.sh --tmux`. Нет docker — compose проверяй парсером `yaml` (`{merge:true}`).
|
||||||
4
.peppa/memory/pep-260.md
Normal file
4
.peppa/memory/pep-260.md
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
# Память: PEP-260
|
||||||
|
|
||||||
|
## Решения
|
||||||
|
- Access Hub (PEP-260): агенту — только текст (`isTextResponse`) + `TEXT_TYPES`.
|
||||||
4
.peppa/memory/pep-265.md
Normal file
4
.peppa/memory/pep-265.md
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
# Память: PEP-265
|
||||||
|
|
||||||
|
## Грабли
|
||||||
|
- Состояние вачдога, которое пишет не вачдог (хук, launch), — только `markWatch` (json_set): `patchWatch` перезаписывает весь watch_state (PEP-265).
|
||||||
4
.peppa/memory/pep-266.md
Normal file
4
.peppa/memory/pep-266.md
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
# Память: PEP-266
|
||||||
|
|
||||||
|
## Решения
|
||||||
|
- Проверка запуска (PEP-266) идёт в платформенном проекте, не в отдельной строке проекта: тики обходят все проекты и шлют ложные сбои.
|
||||||
4
.peppa/memory/pep-267.md
Normal file
4
.peppa/memory/pep-267.md
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
# Память: PEP-267
|
||||||
|
|
||||||
|
## Грабли
|
||||||
|
- Версии CLI агентов (PEP-267) — только `scripts/runner-image.sh --try <cli> <версия>` (json + оба Dockerfile), откат `--rollback`.
|
||||||
4
.peppa/memory/pep-268.md
Normal file
4
.peppa/memory/pep-268.md
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
# Память: PEP-268
|
||||||
|
|
||||||
|
## Соглашения
|
||||||
|
- Сбой платформы — `planPlatformRetry` (PEP-268), `restarts` не трогать; мок `hangAtStart`.
|
||||||
4
.peppa/memory/pep-269.md
Normal file
4
.peppa/memory/pep-269.md
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
# Память: PEP-269
|
||||||
|
|
||||||
|
## Соглашения
|
||||||
|
- Конфликт PR с main (PEP-269) — только `conflictStep` (runner/conflict-step.ts), не `requestRebase` напрямую; сироты — `orphanConflictTick` (PEP-301).
|
||||||
4
.peppa/memory/pep-272.md
Normal file
4
.peppa/memory/pep-272.md
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
# Память: PEP-272
|
||||||
|
|
||||||
|
## Решения
|
||||||
|
- `/api/health` анониму — только `{ok}` (PEP-272); сводку читать с `healthHeaders()` / `scripts/lib/health-token.sh`.
|
||||||
4
.peppa/memory/pep-273.md
Normal file
4
.peppa/memory/pep-273.md
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
# Память: PEP-273
|
||||||
|
|
||||||
|
## Соглашения
|
||||||
|
- Ссылки веба — только `Link` из `@/components/Link` (предзагрузка выкл., PEP-273; тест no-prefetch); медленная страница из-за Gitea — кэш в globalThis, как `giteaServerOverview`.
|
||||||
4
.peppa/memory/pep-274.md
Normal file
4
.peppa/memory/pep-274.md
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
# Память: PEP-274
|
||||||
|
|
||||||
|
## Решения
|
||||||
|
- Заголовок вкладки (PEP-274) — `pageTitle`/`projectTitle`/`taskTitle` (apps/web/lib/title.ts); page.tsx без `generateMetadata` роняет page-titles.test.ts.
|
||||||
4
.peppa/memory/pep-278.md
Normal file
4
.peppa/memory/pep-278.md
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
# Память: PEP-278
|
||||||
|
|
||||||
|
## Соглашения
|
||||||
|
- «Готово» после выкатки (PEP-278): статус `done` не трогаем — поверх него отметка `rollout.wait:<taskId>` (core/rollout.ts), экран — псевдостатус `rollout` в `TASK_STATUS`; снимает `rolloutTick`.
|
||||||
4
.peppa/memory/pep-279.md
Normal file
4
.peppa/memory/pep-279.md
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
# Память: PEP-279
|
||||||
|
|
||||||
|
## Решения
|
||||||
|
- Старые вопросы (PEP-279) закрываются только `default_option`; без него — без выбора: варианты фабрики (бюджет, подписка) за человека не выбираем.
|
||||||
4
.peppa/memory/pep-281.md
Normal file
4
.peppa/memory/pep-281.md
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
# Память: PEP-281
|
||||||
|
|
||||||
|
## Грабли
|
||||||
|
- Git — только git.vibe42.kz; старый адрес в репо ловит old-git-cleanup.test.ts (PEP-281).
|
||||||
4
.peppa/memory/pep-282.md
Normal file
4
.peppa/memory/pep-282.md
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
# Память: PEP-282
|
||||||
|
|
||||||
|
## Грабли
|
||||||
|
- Таймаут запроса в процессе с моком-сервером: синхронная пауза дольше таймаута обрывает готовый ответ (таймеры libuv раньше сокетов) — `responsiveTimeout` (core, PEP-282), не `AbortSignal.timeout`.
|
||||||
4
.peppa/memory/pep-283.md
Normal file
4
.peppa/memory/pep-283.md
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
# Память: PEP-283
|
||||||
|
|
||||||
|
## Решения
|
||||||
|
- Стек новых проектов — docs/standards/default-stack.md (PEP-283).
|
||||||
4
.peppa/memory/pep-284.md
Normal file
4
.peppa/memory/pep-284.md
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
# Память: PEP-284
|
||||||
|
|
||||||
|
## Соглашения
|
||||||
|
- Стандарт стека в шаблоне (PEP-284): template/docs/standards/default-stack.md — побайтная копия docs/standards/default-stack.md (тест template-default-stack); правишь стандарт — копируй в template/.
|
||||||
4
.peppa/memory/pep-285.md
Normal file
4
.peppa/memory/pep-285.md
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
# Память: PEP-285
|
||||||
|
|
||||||
|
## Решения
|
||||||
|
- Аудит стека (PEP-285): docs/standards/forge-stack-audit.md — основа FORGE (TS/Node 26, Next.js, SQLite, Drizzle, целые id) сохраняется как обоснованное отклонение; условия пересмотра PostgreSQL — там же. Новый слой в default-stack.md = строка и раздел в аудите (тест stack-audit-doc).
|
||||||
4
.peppa/memory/pep-291.md
Normal file
4
.peppa/memory/pep-291.md
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
# Память: PEP-291
|
||||||
|
|
||||||
|
## Грабли
|
||||||
|
- Песочница раннера: Node 22.23 тянет одиночные тесты (PEP-291).
|
||||||
4
.peppa/memory/pep-292.md
Normal file
4
.peppa/memory/pep-292.md
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
# Память: PEP-292
|
||||||
|
|
||||||
|
## Грабли
|
||||||
|
- В образе платформы нет `.git` (PEP-292): `git` в коде службы не звать; коммит — `PEPPA_COMMIT`, история main — Gitea API.
|
||||||
4
.peppa/memory/pep-294.md
Normal file
4
.peppa/memory/pep-294.md
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
# Память: PEP-294
|
||||||
|
|
||||||
|
## Решения
|
||||||
|
- Суперадмины (PEP-294): `platform.admins` — id учёток (строка = логин без учётки, привязывается при чтении); проверка — `superadminIds`/`platformAdminUsers`, не сравнение логинов.
|
||||||
4
.peppa/memory/pep-295.md
Normal file
4
.peppa/memory/pep-295.md
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
# Память: PEP-295
|
||||||
|
|
||||||
|
## Соглашения
|
||||||
|
- Задача не от человека — `createTask` с origin сама в «Предложено» (PEP-295), путь — проверить `proposalRoom` до создания; новый вызов `createTask` — в список `proposals-only.test.ts`; автомерж — autonomy.acceptOwn.
|
||||||
4
.peppa/memory/pep-298.md
Normal file
4
.peppa/memory/pep-298.md
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
# Память: PEP-298
|
||||||
|
|
||||||
|
## Соглашения
|
||||||
|
- Конфликт PR с main: первая просьба — после второго наблюдения через 2 мин (PEP-298, в тестах `PEPPA_CONFLICT_SETTLE_MIN=0`).
|
||||||
4
.peppa/memory/pep-299.md
Normal file
4
.peppa/memory/pep-299.md
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
# Память: PEP-299
|
||||||
|
|
||||||
|
## Грабли
|
||||||
|
- `stopSession` закрывает все вопросы сессии, и карточку «готово» с «Принять» — освобождать место без неё: `releaseReviewSession` (PEP-299).
|
||||||
4
.peppa/memory/pep-302.md
Normal file
4
.peppa/memory/pep-302.md
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
# Память: PEP-302
|
||||||
|
|
||||||
|
## Грабли
|
||||||
|
- mock-intake `dedup` считает похожие названия («Идея 1»/«Идея 2») повтором — в тестах приёмки бери разные слова.
|
||||||
4
.peppa/memory/pep-303.md
Normal file
4
.peppa/memory/pep-303.md
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
# Память: PEP-303
|
||||||
|
|
||||||
|
## Грабли
|
||||||
|
- Сторож экрана (PEP-303): строки — через `screen-lines.ts` (`isQuotedLine`/`ownLines`), фразу CLI якорить к началу строки, нажимать только на неизменном экране (`still`). Мок `say` печатает «⏺ » перед текстом.
|
||||||
4
.peppa/memory/pep-304.md
Normal file
4
.peppa/memory/pep-304.md
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
# Память: PEP-304
|
||||||
|
|
||||||
|
## Соглашения
|
||||||
|
- Время людям (PEP-304) — только `platformTime`/`platformDayTime`/`platformZone` из `@peppa/shared/time`; `toLocale*String` для дат без `timeZone` не писать. Лимит в `claudePrint` — `limited`/`limitedUntil`, не «нет подписки».
|
||||||
4
.peppa/memory/pep-306.md
Normal file
4
.peppa/memory/pep-306.md
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
# Память: PEP-306
|
||||||
|
|
||||||
|
## Грабли
|
||||||
|
- Память (PEP-306): пункт — только в `.peppa/memory/<ключ задачи>.md` своей задачи; MCP `remember` до выкатки PEP-306 пишет в старый `.peppa/memory.md` — тогда правь файл задачи руками (тест project-memory-size запрещает старый файл).
|
||||||
4
.peppa/memory/pep-98.md
Normal file
4
.peppa/memory/pep-98.md
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
# Память: PEP-98
|
||||||
|
|
||||||
|
## Соглашения
|
||||||
|
- i18n (PEP-98): текст пользователю — ключ = русская строка в `t()`/`m()` + перевод в `i18n/en|kk/<раздел>.ts` (иначе падают i18n-check/i18n-kk). «Peppa FACTORY» не склоняется (kk: Peppa FACTORY-нің); к {плейсхолдеру} kk-окончание не клеить. Тексты агентам говорят «Пеппа» — не трогаем.
|
||||||
@ -8,6 +8,7 @@
|
|||||||
"lint": "pnpm lint",
|
"lint": "pnpm lint",
|
||||||
"typecheck": "pnpm -r typecheck",
|
"typecheck": "pnpm -r typecheck",
|
||||||
"build": "pnpm --filter @peppa/web build",
|
"build": "pnpm --filter @peppa/web build",
|
||||||
|
"bundle": "node scripts/bundle-check.mjs",
|
||||||
"test": "pnpm --filter @peppa/testkit test"
|
"test": "pnpm --filter @peppa/testkit test"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -3,7 +3,7 @@
|
|||||||
"version": "0.0.0",
|
"version": "0.0.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"exports": { ".": "./src/bot.ts", "./telegram": "./src/telegram.ts" },
|
"exports": { ".": "./src/bot.ts", "./telegram": "./src/telegram.ts", "./render": "./src/render.ts" },
|
||||||
"bin": { "peppa-bot": "./bin/peppa-bot" },
|
"bin": { "peppa-bot": "./bin/peppa-bot" },
|
||||||
"scripts": { "start": "node src/index.ts", "typecheck": "tsc -p ." },
|
"scripts": { "start": "node src/index.ts", "typecheck": "tsc -p ." },
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
|||||||
@ -2,7 +2,8 @@
|
|||||||
// alerts) to the paired chat and turns button presses / replies into answers delivered
|
// alerts) to the paired chat and turns button presses / replies into answers delivered
|
||||||
// back into the agent session. Telegram is an adapter over the DB, not a remote shell:
|
// back into the agent session. Telegram is an adapter over the DB, not a remote shell:
|
||||||
// it can only answer a specific pending question or resume/stop the session it is about.
|
// it can only answer a specific pending question or resume/stop the session it is about.
|
||||||
import { reportPlatformError } from "@peppa/core";
|
import { acceptDigestHold, duringPause, heldForDigest, isProjectPaused, LOCALIZED_PARAM, localizeMessage, messageDetails, questionIsFreeText, reportPlatformError, telegramChatLocale } from "@peppa/core";
|
||||||
|
import { asIs, localizeRoleMessage, m as tr, stripAsIs } from "@peppa/shared/i18n";
|
||||||
import {
|
import {
|
||||||
accountUsageForUser,
|
accountUsageForUser,
|
||||||
describeUsage,
|
describeUsage,
|
||||||
@ -32,12 +33,16 @@ import {
|
|||||||
type User,
|
type User,
|
||||||
getOffset,
|
getOffset,
|
||||||
getIncident,
|
getIncident,
|
||||||
|
agentSignature,
|
||||||
getQuestion,
|
getQuestion,
|
||||||
|
questionAuthor,
|
||||||
getSession,
|
getSession,
|
||||||
listSessions,
|
listSessions,
|
||||||
markOutboxRetry,
|
markOutboxRetry,
|
||||||
markOutboxSent,
|
markOutboxSent,
|
||||||
pendingQuestions,
|
pendingQuestions,
|
||||||
|
getUiMode,
|
||||||
|
needsPerson,
|
||||||
questionByTelegramMessage,
|
questionByTelegramMessage,
|
||||||
setOffset,
|
setOffset,
|
||||||
setSetting,
|
setSetting,
|
||||||
@ -62,20 +67,33 @@ import {
|
|||||||
migrateChatGroup,
|
migrateChatGroup,
|
||||||
mirrorTargets,
|
mirrorTargets,
|
||||||
syncChats,
|
syncChats,
|
||||||
|
isRepeatEdit,
|
||||||
|
getOutbox,
|
||||||
|
lastRepeatEdit,
|
||||||
|
questionStates,
|
||||||
|
repeatEditKey,
|
||||||
|
sentQuestionMessages,
|
||||||
telegramAccountUser,
|
telegramAccountUser,
|
||||||
threadAnchor,
|
threadAnchor,
|
||||||
type Chat,
|
type Chat,
|
||||||
type ChatMessage,
|
type ChatMessage,
|
||||||
} from "@peppa/core";
|
} from "@peppa/core";
|
||||||
import { projects, tasks, type Db } from "@peppa/db";
|
import { projects, tasks, type Db } from "@peppa/db";
|
||||||
import { formatTaskKey } from "@peppa/shared";
|
import { formatTaskKey, voiceStoriesEnabled } from "@peppa/shared";
|
||||||
import { acceptTask, answerAndDeliver, decideIncident, moveTask, postToChat, resumeSession, stopSession } from "@peppa/runner";
|
import { delayAction, denyAccessRequestAndTell, resolveTaskById } from "@peppa/runner";
|
||||||
|
import { decideIdleGrant, parseDelayCallback, parseIdleGrantCallback } from "@peppa/core";
|
||||||
|
import { acceptTask, answerAndDeliver, classifyMessage, decideIncident, decideProposals, moveTask, postToChat, REQUEST_SENT_TEXT, requestSubscription, resumeSession, stopSession } from "@peppa/runner";
|
||||||
|
import { INTENT_TEXT, statusAnswer } from "@peppa/core";
|
||||||
import { AsyncLocalStorage } from "node:async_hooks";
|
import { AsyncLocalStorage } from "node:async_hooks";
|
||||||
import { eq, sql } from "drizzle-orm";
|
import { eq, sql } from "drizzle-orm";
|
||||||
import { choiceToAnswer, esc, renderAnswered, renderQuestion } from "./render.ts";
|
import { choiceToAnswer, esc, renderAnswered, renderQuestion } from "./render.ts";
|
||||||
import { TelegramApi, TelegramError, type InlineButton, type TgCallbackQuery, type TgMessage, type TgUpdate } from "./telegram.ts";
|
import { TelegramApi, TelegramError, type InlineButton, type TgCallbackQuery, type TgMessage, type TgUpdate } from "./telegram.ts";
|
||||||
import { dropDraft, loadDraft, parseStoryText, saveDraft, splitStory, updateDraft, type Draft } from "./drafts.ts";
|
import { dropDraft, loadDraft, parseStoryText, saveDraft, splitStory, updateDraft, type Draft } from "./drafts.ts";
|
||||||
import { transcribe, transcribeConfig, TranscribeError } from "./transcribe.ts";
|
import { getUserLocale, transcribe, transcribeConfig, transcribeLanguage, TranscribeError } from "@peppa/core";
|
||||||
|
import { addFeedbackScreenshot, FEEDBACK_MAX_SHOTS, fixFeedback, isSuperadmin, linkFeedback, PeppaError, rejectFeedback, submitFeedback } from "@peppa/core";
|
||||||
|
import { readFileSync } from "node:fs";
|
||||||
|
import { basename } from "node:path";
|
||||||
|
import { askRejectReason, clearReject, closeFeedbackMode, feedbackMode, keepFeedbackMode, openFeedbackMode, pendingReject } from "./feedback.ts";
|
||||||
|
|
||||||
/** Longest voice note the bot transcribes (seconds). */
|
/** Longest voice note the bot transcribes (seconds). */
|
||||||
const VOICE_MAX_SEC = 5 * 60;
|
const VOICE_MAX_SEC = 5 * 60;
|
||||||
@ -89,6 +107,8 @@ export interface BotOptions {
|
|||||||
pollTimeoutSec?: number;
|
pollTimeoutSec?: number;
|
||||||
outboxIntervalMs?: number;
|
outboxIntervalMs?: number;
|
||||||
reconcileIntervalMs?: number;
|
reconcileIntervalMs?: number;
|
||||||
|
/** PEP-151: a delivered message is refreshed for a repeated state at most this often (5 min). */
|
||||||
|
repeatEditMs?: number;
|
||||||
/** Heartbeat + check on the watchdog and the web (PEP-20). */
|
/** Heartbeat + check on the watchdog and the web (PEP-20). */
|
||||||
heartbeatIntervalMs?: number;
|
heartbeatIntervalMs?: number;
|
||||||
// How often to check PRAGMA data_version for writes the notify() poke missed.
|
// How often to check PRAGMA data_version for writes the notify() poke missed.
|
||||||
@ -100,44 +120,53 @@ export interface BotOptions {
|
|||||||
log?: (msg: string) => void;
|
log?: (msg: string) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
const HELP = `Я бот Peppa FACTORY. Присылаю вопросы от агентов и сообщения о том, что задача готова или агент ждёт вас.
|
// One key per line: localizeMessage translates a multi-line message line by line.
|
||||||
|
const helpText = (voice: boolean) => [
|
||||||
• Кнопки под сообщением — быстрый ответ.
|
tr("Я бот FORGE. Присылаю вопросы от агентов и сообщения о том, что задача готова или агент ждёт вас."),
|
||||||
• Ответ <b>реплаем</b> на сообщение — свой текст, он уйдёт агенту.
|
"",
|
||||||
• Просто напишите (или наговорите голосом) задачу — я её заведу: «в PAY: экспорт в CSV». Проект и эпик уточню кнопками, потом предложу сразу взять в работу.
|
tr("• Кнопки под сообщением — быстрый ответ."),
|
||||||
• /status — кто из агентов работает и какие вопросы открыты.
|
tr("• Ответ <b>реплаем</b> на сообщение — свой текст, он уйдёт агенту."),
|
||||||
• /digest — сводка за сутки по вашим проектам (каждый день приходит сама; время и что присылать — в Настройках → Уведомления).`;
|
voice
|
||||||
|
? tr("• Просто напишите (или наговорите голосом) задачу — я её заведу: «в PAY: экспорт в CSV». Проект и эпик уточню кнопками, потом предложу сразу взять в работу.")
|
||||||
|
: tr("• Просто напишите задачу — я её заведу: «в PAY: экспорт в CSV». Проект и эпик уточню кнопками, потом предложу сразу взять в работу."),
|
||||||
|
tr("• Спросите, что сейчас происходит («какие задачи у агентов?», «что с PAY-3?») — отвечу сразу, задачу из вопроса не заведу."),
|
||||||
|
tr("• /status — кто из агентов работает и какие вопросы открыты."),
|
||||||
|
tr("• /problem — сообщить о проблеме в FORGE: напишите, что случилось, и приложите фото экрана."),
|
||||||
|
tr("• /digest — сводка за сутки по вашим проектам (каждый день приходит сама; время и что присылать — в Настройках → Уведомления)."),
|
||||||
|
].join("\n");
|
||||||
|
|
||||||
/** What an agent is doing, in plain words (the same wording as in the web). */
|
/** What an agent is doing, in plain words (the same wording as in the web). */
|
||||||
const STATUS_RU: Record<string, string> = {
|
const STATUS_RU: Record<string, string> = {
|
||||||
starting: "запускается",
|
starting: tr("запускается"),
|
||||||
running: "работает",
|
running: tr("работает"),
|
||||||
waiting_input: "ждёт вашего ответа",
|
waiting_input: tr("ждёт вашего ответа"),
|
||||||
idle: "свободен",
|
idle: tr("свободен"),
|
||||||
stalled: "остановился — нужна помощь",
|
stalled: tr("остановился — нужна помощь"),
|
||||||
rate_limited: "ждёт сброса лимита",
|
rate_limited: tr("ждёт сброса лимита"),
|
||||||
};
|
};
|
||||||
|
|
||||||
const PUSH_MAX_AGE_MS = 30 * 60_000;
|
const PUSH_MAX_AGE_MS = 30 * 60_000;
|
||||||
|
|
||||||
const PUSH_TITLE: Record<NotifyEvent, string> = {
|
const PUSH_TITLE: Record<NotifyEvent, string> = {
|
||||||
questions: "Агент ждёт ответа",
|
questions: tr("Агент ждёт ответа"),
|
||||||
review: "Готово к ревью",
|
review: tr("Готово к ревью"),
|
||||||
failures: "Агент остановился",
|
failures: tr("Агент остановился"),
|
||||||
releases: "Обновление продукта",
|
releases: tr("Обновление продукта"),
|
||||||
incidents: "Ошибка в продукте",
|
incidents: tr("Ошибка в продукте"),
|
||||||
chat: "Сообщение в обсуждении",
|
chat: tr("Сообщение в обсуждении"),
|
||||||
monitoring: "Мониторинг",
|
monitoring: tr("Мониторинг"),
|
||||||
users: "Новый пользователь",
|
users: tr("Новый пользователь"),
|
||||||
digest: "Сводка",
|
feedback: tr("Обращение пользователя"),
|
||||||
platform: "Обновления Peppa FACTORY",
|
digest: tr("Сводка"),
|
||||||
|
platform: tr("Обновления FORGE"),
|
||||||
};
|
};
|
||||||
|
|
||||||
/** Browser notification text for a question. */
|
/** Browser notification text for a question. */
|
||||||
function pushFor(q: Question, event: NotifyEvent, ctx: { taskKey: string | null; taskTitle: string | null }): { title: string; body: string } {
|
function pushFor(q: Question, event: NotifyEvent, ctx: { taskKey: string | null; taskTitle: string | null }): { title: string; body: string } {
|
||||||
const title = `${ctx.taskKey ? `${ctx.taskKey}: ` : ""}${q.kind === "approval" ? "нужно одобрение" : q.kind === "permission" ? "нужно разрешение" : PUSH_TITLE[event]}`;
|
const what = q.kind === "approval" ? tr("нужно одобрение") : q.kind === "permission" ? tr("нужно разрешение") : PUSH_TITLE[event];
|
||||||
const body = q.text.length > 200 ? `${q.text.slice(0, 199)}…` : q.text;
|
const title = ctx.taskKey ? `${ctx.taskKey}: ${what}` : what;
|
||||||
return { title, body };
|
const short = q.text.length > 200 ? `${q.text.slice(0, 199)}…` : q.text;
|
||||||
|
return { title, body: questionIsFreeText(q) ? asIs(short) : short };
|
||||||
}
|
}
|
||||||
|
|
||||||
export function createBot(o: BotOptions) {
|
export function createBot(o: BotOptions) {
|
||||||
@ -160,11 +189,52 @@ export function createBot(o: BotOptions) {
|
|||||||
const ownBots = new Map<number, OwnBot>();
|
const ownBots = new Map<number, OwnBot>();
|
||||||
const ownByChat = new Map<number, OwnBot>();
|
const ownByChat = new Map<number, OwnBot>();
|
||||||
const pick = (chatId?: unknown): TelegramApi => via.getStore()?.api ?? (typeof chatId === "number" ? ownByChat.get(chatId)?.api : undefined) ?? o.api;
|
const pick = (chatId?: unknown): TelegramApi => via.getStore()?.api ?? (typeof chatId === "number" ? ownByChat.get(chatId)?.api : undefined) ?? o.api;
|
||||||
|
// ── PEP-98: messages go out in the reader's language ─────────────────────────────
|
||||||
|
// Texts are rendered in Russian everywhere (core, runner, this file); right before the Bot API
|
||||||
|
// call the text, caption and button labels are translated for the chat's user.
|
||||||
|
const readerChat = new AsyncLocalStorage<number>();
|
||||||
|
/** PEP-139: the marks around free text never reach Telegram (the translation takes them off itself). */
|
||||||
|
const unmarked = (params: Record<string, unknown>): Record<string, unknown> => {
|
||||||
|
const raw = JSON.stringify(params);
|
||||||
|
return raw.includes("\u2068") || raw.includes("\u2069") ? (JSON.parse(stripAsIs(raw)) as Record<string, unknown>) : params;
|
||||||
|
};
|
||||||
|
const localizeParams = async (params: Record<string, unknown>): Promise<Record<string, unknown>> => {
|
||||||
|
if (LOCALIZED_PARAM in params) {
|
||||||
|
// PEP-138: written for this reader already (an AI role's message with free text inside).
|
||||||
|
const { [LOCALIZED_PARAM]: _done, ...rest } = params;
|
||||||
|
return unmarked(rest);
|
||||||
|
}
|
||||||
|
const chatId = typeof params.chat_id === "number" ? params.chat_id : readerChat.getStore();
|
||||||
|
if (chatId == null) return unmarked(params);
|
||||||
|
const locale = await telegramChatLocale(db, chatId).catch(() => "ru" as const);
|
||||||
|
if (locale === "ru") return unmarked(params);
|
||||||
|
const loc = (v: unknown) => (typeof v === "string" ? localizeMessage(locale, v) : v);
|
||||||
|
const out: Record<string, unknown> = { ...params, text: loc(params.text), caption: loc(params.caption) };
|
||||||
|
if (params.text === undefined) delete out.text;
|
||||||
|
if (params.caption === undefined) delete out.caption;
|
||||||
|
const markup = params.reply_markup as { inline_keyboard?: { text: string }[][]; keyboard?: ({ text: string } | string)[][] } | undefined;
|
||||||
|
if (markup && typeof markup === "object") {
|
||||||
|
const btn = <B,>(b: B): B => (typeof b === "string" ? (loc(b) as B) : b && typeof b === "object" && "text" in b ? ({ ...b, text: loc((b as { text: string }).text) } as B) : b);
|
||||||
|
out.reply_markup = {
|
||||||
|
...markup,
|
||||||
|
...(markup.inline_keyboard ? { inline_keyboard: markup.inline_keyboard.map((row) => row.map(btn)) } : {}),
|
||||||
|
...(markup.keyboard ? { keyboard: markup.keyboard.map((row) => row.map(btn)) } : {}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
};
|
||||||
/** The same surface as TelegramApi, routed to the right bot per call. */
|
/** The same surface as TelegramApi, routed to the right bot per call. */
|
||||||
const api = {
|
const api = {
|
||||||
call: <T>(method: string, params: Record<string, unknown> = {}, timeoutMs?: number) => pick(params.chat_id).call<T>(method, params, timeoutMs),
|
call: async <T,>(method: string, params: Record<string, unknown> = {}, timeoutMs?: number) => pick(params.chat_id).call<T>(method, await localizeParams(params), timeoutMs),
|
||||||
sendMessage: (chatId: number, text: string, extra: Record<string, unknown> = {}) => pick(chatId).sendMessage(chatId, text, extra),
|
sendMessage: async (chatId: number, text: string, extra: Record<string, unknown> = {}) => {
|
||||||
answerCallbackQuery: (id: string, text?: string) => pick().answerCallbackQuery(id, text),
|
const p = await localizeParams({ ...extra, chat_id: chatId, text });
|
||||||
|
return pick(chatId).sendMessage(chatId, p.text as string, p);
|
||||||
|
},
|
||||||
|
answerCallbackQuery: async (id: string, text?: string) => pick().answerCallbackQuery(id, text === undefined ? undefined : ((await localizeParams({ text })).text as string)),
|
||||||
|
sendPhoto: async (chatId: number, photo: { data: Uint8Array; filename: string; mime: string }, extra: Record<string, unknown> = {}) => {
|
||||||
|
const p = await localizeParams({ ...extra, chat_id: chatId });
|
||||||
|
return pick(chatId).sendPhoto(chatId, photo, p);
|
||||||
|
},
|
||||||
getFile: (fileId: string) => pick().getFile(fileId),
|
getFile: (fileId: string) => pick().getFile(fileId),
|
||||||
downloadFile: (filePath: string) => pick().downloadFile(filePath),
|
downloadFile: (filePath: string) => pick().downloadFile(filePath),
|
||||||
getMe: () => o.api.getMe(),
|
getMe: () => o.api.getMe(),
|
||||||
@ -226,11 +296,17 @@ export function createBot(o: BotOptions) {
|
|||||||
|
|
||||||
// ── questions → outbox ─────────────────────────────────────────────────────────
|
// ── questions → outbox ─────────────────────────────────────────────────────────
|
||||||
async function context(q: Question) {
|
async function context(q: Question) {
|
||||||
|
// PEP-152: technical details stay on the site — Telegram gets a «Подробнее» button.
|
||||||
|
return { ...(await taskContext(q)), details: (await messageDetails(db, [q.id])).has(q.id) };
|
||||||
|
}
|
||||||
|
async function taskContext(q: Question) {
|
||||||
let session: SessionView | null = null;
|
let session: SessionView | null = null;
|
||||||
if (q.sessionId) session = await getSession(db, q.sessionId).catch(() => null);
|
if (q.sessionId) session = await getSession(db, q.sessionId).catch(() => null);
|
||||||
const [st] = q.taskId ? await db.select({ status: tasks.status }).from(tasks).where(eq(tasks.id, q.taskId)) : [];
|
const [st] = q.taskId ? await db.select({ status: tasks.status }).from(tasks).where(eq(tasks.id, q.taskId)) : [];
|
||||||
const taskStatus = st?.status ?? null;
|
const taskStatus = st?.status ?? null;
|
||||||
if (session) return { taskKey: session.taskKey, taskTitle: session.taskTitle, taskStatus, session, webUrl: o.webUrl };
|
const author = await questionAuthor(db, q).catch(() => null);
|
||||||
|
const agent = author?.kind === "agent" ? author.name : null;
|
||||||
|
if (session) return { taskKey: session.taskKey, taskTitle: session.taskTitle, taskStatus, session, webUrl: o.webUrl, agent };
|
||||||
if (q.taskId) {
|
if (q.taskId) {
|
||||||
const [t] = await db
|
const [t] = await db
|
||||||
.select({ key: projects.key, number: tasks.number, title: tasks.title })
|
.select({ key: projects.key, number: tasks.number, title: tasks.title })
|
||||||
@ -247,44 +323,82 @@ export function createBot(o: BotOptions) {
|
|||||||
* settings (PEP-35): a Telegram message and/or a browser push; every closed one gets an edit.
|
* settings (PEP-35): a Telegram message and/or a browser push; every closed one gets an edit.
|
||||||
*/
|
*/
|
||||||
async function reconcile(): Promise<void> {
|
async function reconcile(): Promise<void> {
|
||||||
const open = await pendingQuestions(db);
|
// PEP-174: a project on pause gets nothing; what came up during a pause is not sent afterwards.
|
||||||
|
const open: Question[] = [];
|
||||||
|
for (const q of await pendingQuestions(db)) if (!(await duringPause(db, q.projectId, q.createdAt))) open.push(q);
|
||||||
|
const states = await questionStates(db, open.map((q) => q.id));
|
||||||
const projectsOf = new Map<number, Set<number>>();
|
const projectsOf = new Map<number, Set<number>>();
|
||||||
const waitingFor = async (userId: number) => {
|
const waitingFor = async (userId: number) => {
|
||||||
if (!projectsOf.has(userId)) projectsOf.set(userId, new Set(await userProjectIds(db, userId)));
|
if (!projectsOf.has(userId)) projectsOf.set(userId, new Set(await userProjectIds(db, userId)));
|
||||||
const ids = projectsOf.get(userId)!;
|
const ids = projectsOf.get(userId)!;
|
||||||
return open.filter((x) => ids.has(x.projectId)).length;
|
return open.filter((x) => ids.has(x.projectId) && waits.has(x.id)).length;
|
||||||
};
|
};
|
||||||
|
// PEP-149: what waits for a person — questions and finished stories; only these push and count.
|
||||||
|
const ctxOf = new Map<number, Awaited<ReturnType<typeof context>>>();
|
||||||
|
const waits = new Set<number>();
|
||||||
|
for (const q of open) {
|
||||||
|
const c = await context(q);
|
||||||
|
ctxOf.set(q.id, c);
|
||||||
|
if (needsPerson(q, c.taskStatus)) waits.add(q.id);
|
||||||
|
}
|
||||||
for (const q of open) {
|
for (const q of open) {
|
||||||
const audience = await projectAudience(db, q.projectId);
|
const audience = await projectAudience(db, q.projectId);
|
||||||
if (!audience.length) continue;
|
if (!audience.length) continue;
|
||||||
const ctx = await context(q);
|
const ctx = ctxOf.get(q.id)!;
|
||||||
const event = questionEvent(q, { taskStatus: ctx.taskStatus, sessionStatus: ctx.session?.status });
|
const event = questionEvent(q, { taskStatus: ctx.taskStatus, sessionStatus: ctx.session?.status });
|
||||||
const r = renderQuestion(q, ctx);
|
|
||||||
// A push is a "now" signal: questions older than this don't pop up on a fresh subscription.
|
// A push is a "now" signal: questions older than this don't pop up on a fresh subscription.
|
||||||
const fresh = Date.now() - q.createdAt.getTime() < PUSH_MAX_AGE_MS;
|
const fresh = Date.now() - q.createdAt.getTime() < PUSH_MAX_AGE_MS;
|
||||||
const url = ctx.taskKey ? `/t/${ctx.taskKey}` : `/p/${await projectKey(q.projectId)}`;
|
const url = ctx.taskKey ? `/t/${ctx.taskKey}` : `/p/${await projectKey(q.projectId)}`;
|
||||||
|
// PEP-198: a finished story nobody waits for comes in the evening digest, not one by one.
|
||||||
|
if (await heldForDigest(db, q, ctx.taskStatus ?? null)) continue;
|
||||||
|
// PEP-209: more than two ready within an hour — one summary with «Приёмка» instead (acceptDigestTick).
|
||||||
|
if ((await acceptDigestHold(db, q)) !== "send") continue;
|
||||||
for (const u of audience) {
|
for (const u of audience) {
|
||||||
|
// PEP-154: the terminal command is for the «Инженер» view only.
|
||||||
|
const r = renderQuestion(q, { ...ctx, engineer: (await getUiMode(db, u.id)) === "engineer" });
|
||||||
await deliverToUser(db, u, {
|
await deliverToUser(db, u, {
|
||||||
event,
|
event,
|
||||||
projectId: q.projectId,
|
projectId: q.projectId,
|
||||||
dedupeKey: `q:${q.id}:${u.telegramChatId}`,
|
dedupeKey: `q:${q.id}:${u.telegramChatId}`,
|
||||||
pushKey: `q:${q.id}:u${u.id}`,
|
pushKey: `q:${q.id}:u${u.id}`,
|
||||||
telegram: { questionId: q.id, params: { text: r.text, parse_mode: "HTML", reply_markup: { inline_keyboard: r.buttons } } },
|
telegram: { questionId: q.id, params: { text: r.text, parse_mode: "HTML", reply_markup: { inline_keyboard: r.buttons } } },
|
||||||
push: fresh ? { ...pushFor(q, event, ctx), url, tag: `q:${q.id}`, count: await waitingFor(u.id) } : undefined,
|
push: fresh && waits.has(q.id) ? { ...pushFor(q, event, ctx), url, tag: `q:${q.id}`, count: await waitingFor(u.id) } : undefined,
|
||||||
urgency: event === "questions" || event === "failures" ? "high" : "normal",
|
urgency: event === "questions" || event === "failures" ? "high" : "normal",
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
// PEP-151: the same state came again — no new message; the one already delivered gets the
|
||||||
|
// fresh text and its buttons back, at most once in `repeatEditMs`.
|
||||||
|
const repeats = states.get(q.id)?.repeats ?? 0;
|
||||||
|
if (!repeats) continue;
|
||||||
|
const r = renderQuestion(q, ctx);
|
||||||
|
for (const sent of await sentQuestionMessages(db, q.id)) {
|
||||||
|
const key = repeatEditKey(sent.id, repeats);
|
||||||
|
if (await getOutbox(db, key)) continue;
|
||||||
|
const last = await lastRepeatEdit(db, sent.id);
|
||||||
|
if (last && Date.now() - last.getTime() < (o.repeatEditMs ?? 5 * 60_000)) continue;
|
||||||
|
await enqueueTelegram(db, {
|
||||||
|
dedupeKey: key,
|
||||||
|
method: "editMessageText",
|
||||||
|
questionId: q.id,
|
||||||
|
params: { chat_id: sent.params.chat_id, message_id: sent.telegramMessageId, text: r.text, parse_mode: "HTML", link_preview_options: { is_disabled: true }, reply_markup: { inline_keyboard: r.buttons } },
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
await mirrorChats().catch((e) => log(`chats: ${(e as Error).message}`));
|
await mirrorChats().catch((e) => log(`chats: ${(e as Error).message}`));
|
||||||
for (const { sent, q } of await answeredQuestionMessages(db, new Date(Date.now() - 24 * 3600_000))) {
|
const answered = await answeredQuestionMessages(db, new Date(Date.now() - 24 * 3600_000));
|
||||||
|
const answeredStates = await questionStates(db, answered.map((a) => a.q.id));
|
||||||
|
for (const { sent, q } of answered) {
|
||||||
|
if (await isProjectPaused(db, q.projectId)) continue;
|
||||||
|
// PEP-151: a question that came again is answered again — each round closes the message anew.
|
||||||
|
const round = answeredStates.get(q.id)?.repeats ?? 0;
|
||||||
await enqueueTelegram(db, {
|
await enqueueTelegram(db, {
|
||||||
dedupeKey: `qa:${q.id}:${sent.params.chat_id}`,
|
dedupeKey: round ? `qa:${q.id}:r${round}:${sent.params.chat_id}` : `qa:${q.id}:${sent.params.chat_id}`,
|
||||||
method: "editMessageText",
|
method: "editMessageText",
|
||||||
questionId: q.id,
|
questionId: q.id,
|
||||||
params: {
|
params: {
|
||||||
chat_id: sent.params.chat_id,
|
chat_id: sent.params.chat_id,
|
||||||
message_id: sent.telegramMessageId,
|
message_id: sent.telegramMessageId,
|
||||||
text: renderAnswered(String(sent.params.text), q),
|
text: renderAnswered(round ? renderQuestion(q, await context(q)).text : String(sent.params.text), q),
|
||||||
parse_mode: "HTML",
|
parse_mode: "HTML",
|
||||||
reply_markup: { inline_keyboard: [] },
|
reply_markup: { inline_keyboard: [] },
|
||||||
},
|
},
|
||||||
@ -327,8 +441,20 @@ export function createBot(o: BotOptions) {
|
|||||||
buttons = r.buttons;
|
buttons = r.buttons;
|
||||||
questionId = q.id;
|
questionId = q.id;
|
||||||
} else {
|
} else {
|
||||||
const who = m.kind === "user" ? `<b>${esc(m.authorLogin ?? "?")}</b>${m.via === "telegram" ? "" : " (веб)"}: ` : m.authorKind === "agent" ? "🤖 " : "";
|
// PEP-139: a person's words go as written; an AI role's message gets its fixed lines in the
|
||||||
text = `${where ? `${where}\n` : ""}${who}${esc(m.text.slice(0, 3500))}${m.url ? `\n${esc(m.url)}` : ""}`;
|
// group's language and is then free text too. Events are factory phrases (free parts are
|
||||||
|
// marked where the event text is built) and are translated when sent.
|
||||||
|
// PEP-156: an agent or an AI role signs with its nickname or name: «🤖 Шустрик: …».
|
||||||
|
const bot = m.authorKind === "agent";
|
||||||
|
const inRole = bot ? await telegramChatLocale(db, tgChatId).catch(() => "ru" as const) : null;
|
||||||
|
const own = (s: string) => (inRole ? localizeRoleMessage(inRole, s) : s);
|
||||||
|
// A note the factory itself writes into a discussion (authorKind system) is a phrase, not free text.
|
||||||
|
const free = bot || (m.kind === "user" && m.authorKind !== "system");
|
||||||
|
const said = free ? asIs(esc(own(m.text).slice(0, 3500))) : esc(m.text.slice(0, 3500));
|
||||||
|
const login = own(m.authorLogin ?? "?");
|
||||||
|
const who = bot ? `<b>${asIs(esc(agentSignature(m.authorLogin ? login : null)))}</b>` : m.kind === "user" ? `<b>${asIs(esc(login))}</b>` : "";
|
||||||
|
const body = bot ? `: ${said}` : m.kind === "user" ? (m.via === "telegram" ? `: ${said}` : tr(" (веб): {text}", { text: said })) : said;
|
||||||
|
text = `${where ? `${where}\n` : ""}${who}${body}${m.url ? `\n${esc(m.url)}` : ""}`;
|
||||||
}
|
}
|
||||||
await enqueueTelegram(db, {
|
await enqueueTelegram(db, {
|
||||||
dedupeKey: `cm:${m.id}:${tgChatId}`,
|
dedupeKey: `cm:${m.id}:${tgChatId}`,
|
||||||
@ -360,6 +486,11 @@ export function createBot(o: BotOptions) {
|
|||||||
const q = await getQuestion(db, row.questionId).catch(() => null);
|
const q = await getQuestion(db, row.questionId).catch(() => null);
|
||||||
if (q?.answeredAt) return markOutboxSent(db, { ...row, questionId: null }, null);
|
if (q?.answeredAt) return markOutboxSent(db, { ...row, questionId: null }, null);
|
||||||
}
|
}
|
||||||
|
if (isRepeatEdit(row) && row.questionId) {
|
||||||
|
// PEP-151: answered while the refresh waited — the buttons must not come back.
|
||||||
|
const q = await getQuestion(db, row.questionId).catch(() => null);
|
||||||
|
if (!q || q.answeredAt) return markOutboxSent(db, row, null);
|
||||||
|
}
|
||||||
let params = row.params;
|
let params = row.params;
|
||||||
if (row.method === "sendMessage" && row.chatMessageId && !params.reply_parameters) {
|
if (row.method === "sendMessage" && row.chatMessageId && !params.reply_parameters) {
|
||||||
// PEP-62: a thread in a group = a chain of replies to its first message.
|
// PEP-62: a thread in a group = a chain of replies to its first message.
|
||||||
@ -367,6 +498,19 @@ export function createBot(o: BotOptions) {
|
|||||||
if (anchor) params = { ...params, reply_parameters: { message_id: anchor, allow_sending_without_reply: true } };
|
if (anchor) params = { ...params, reply_parameters: { message_id: anchor, allow_sending_without_reply: true } };
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
|
if (row.method === "sendPhoto") {
|
||||||
|
// PEP-143: a local file (a report's screenshot) uploaded as a photo.
|
||||||
|
const { photo_path: path, chat_id: chatId, ...extra } = params as { photo_path?: string; chat_id: number };
|
||||||
|
let data: Buffer;
|
||||||
|
try {
|
||||||
|
data = readFileSync(String(path));
|
||||||
|
} catch {
|
||||||
|
return markOutboxRetry(db, { ...row, attempts: 99 }, "file is gone");
|
||||||
|
}
|
||||||
|
const ext = basename(String(path)).split(".").pop() ?? "png";
|
||||||
|
const sent = await api.sendPhoto(chatId, { data, filename: `screenshot.${ext}`, mime: ext === "jpg" ? "image/jpeg" : `image/${ext}` }, extra);
|
||||||
|
return markOutboxSent(db, row, sent.message_id);
|
||||||
|
}
|
||||||
const res = await api.call<TgMessage | boolean>(row.method, params);
|
const res = await api.call<TgMessage | boolean>(row.method, params);
|
||||||
await markOutboxSent(db, row, typeof res === "object" ? res.message_id : null);
|
await markOutboxSent(db, row, typeof res === "object" ? res.message_id : null);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@ -392,10 +536,10 @@ export function createBot(o: BotOptions) {
|
|||||||
|
|
||||||
async function answer(q: Question, text: string): Promise<string> {
|
async function answer(q: Question, text: string): Promise<string> {
|
||||||
const fresh = await getQuestion(db, q.id);
|
const fresh = await getQuestion(db, q.id);
|
||||||
if (fresh.answeredAt) return `Уже отвечено${fresh.answeredVia === "system" ? "" : ` (${fresh.answeredVia})`}: ${fresh.answer}`;
|
if (fresh.answeredAt) return fresh.answeredVia === "system" ? tr("Уже отвечено: {answer}", { answer: fresh.answer }) : tr("Уже отвечено ({via}): {answer}", { via: fresh.answeredVia, answer: fresh.answer });
|
||||||
const { delivered } = await answerAndDeliver(db, q.id, text, "telegram");
|
const { delivered } = await answerAndDeliver(db, q.id, text, "telegram");
|
||||||
scheduleReconcile();
|
scheduleReconcile();
|
||||||
return delivered ? "Отправлено агенту ✅" : "Ответ сохранён. Агент сейчас не работает — он увидит ответ, когда вернётся к задаче.";
|
return delivered ? tr("Отправлено агенту ✅") : tr("Ответ сохранён. Агент сейчас не работает — он увидит ответ, когда вернётся к задаче.");
|
||||||
}
|
}
|
||||||
|
|
||||||
const canAccess = (user: User, projectId: number) =>
|
const canAccess = (user: User, projectId: number) =>
|
||||||
@ -408,20 +552,23 @@ export function createBot(o: BotOptions) {
|
|||||||
const ids = new Set(await userProjectIds(db, user.id));
|
const ids = new Set(await userProjectIds(db, user.id));
|
||||||
const sessions = (await listSessions(db, { active: true })).filter((s) => ids.has(s.projectId));
|
const sessions = (await listSessions(db, { active: true })).filter((s) => ids.has(s.projectId));
|
||||||
const open = (await pendingQuestions(db)).filter((q) => ids.has(q.projectId));
|
const open = (await pendingQuestions(db)).filter((q) => ids.has(q.projectId));
|
||||||
const lines = [`<b>Агентов за работой: ${sessions.length}</b>`];
|
const lines = ["<b>" + tr("Агентов за работой: {n}", { n: sessions.length }) + "</b>"];
|
||||||
// PEP-123: in plain words — no provider and no spend.
|
// PEP-123: in plain words — no provider and no spend.
|
||||||
for (const s of sessions) lines.push(`• ${esc(s.taskKey ?? `агент №${s.id}`)} — ${STATUS_RU[s.status] ?? s.status}`);
|
for (const s of sessions) {
|
||||||
lines.push("", `<b>Открытых вопросов: ${open.length}</b>`);
|
const who = s.taskKey ?? tr("агент №{id}", { id: s.id });
|
||||||
|
lines.push(`• ${esc(who)} — ${STATUS_RU[s.status] ?? s.status}`);
|
||||||
|
}
|
||||||
|
lines.push("", "<b>" + tr("Открытых вопросов: {n}", { n: open.length }) + "</b>");
|
||||||
// PEP-5: subscription limit windows.
|
// PEP-5: subscription limit windows.
|
||||||
const accounts = await accountUsageForUser(db, user);
|
const accounts = await accountUsageForUser(db, user);
|
||||||
lines.push("", "<b>Лимиты</b>", ...(accounts.length ? accounts.map((a) => `• ${esc(describeAccount(a))}`) : ["нет данных о лимитах"]));
|
lines.push("", "<b>" + tr("Лимиты") + "</b>", ...(accounts.length ? accounts.map((a) => `• ${esc(describeAccount(a))}`) : [tr("нет данных о лимитах")]));
|
||||||
return lines.join("\n");
|
return lines.join("\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── stories from messages (PEP-45) ─────────────────────────────────────────────
|
// ── stories from messages (PEP-45) ─────────────────────────────────────────────
|
||||||
const cancelRow = (d: Draft): InlineButton[] => [{ text: "✖️ Отмена", callback_data: `d:${d.id}:x` }];
|
const cancelRow = (d: Draft): InlineButton[] => [{ text: tr("✖️ Отмена"), callback_data: `d:${d.id}:x` }];
|
||||||
const rows = (buttons: InlineButton[], per = 2) => buttons.reduce<InlineButton[][]>((acc, b, i) => (i % per ? acc[acc.length - 1]!.push(b) : acc.push([b]), acc), []);
|
const rows = (buttons: InlineButton[], per = 2) => buttons.reduce<InlineButton[][]>((acc, b, i) => (i % per ? acc[acc.length - 1]!.push(b) : acc.push([b]), acc), []);
|
||||||
const storyLine = (d: Draft) => `«${esc(splitStory(d.text).title)}»`;
|
const storyLine = (d: Draft) => `«${asIs(esc(splitStory(d.text).title))}»`;
|
||||||
|
|
||||||
/** Send (or, for a button press, edit in place) a bot message with buttons. */
|
/** Send (or, for a button press, edit in place) a bot message with buttons. */
|
||||||
async function show(chatId: number, text: string, buttons: InlineButton[][], editId?: number) {
|
async function show(chatId: number, text: string, buttons: InlineButton[][], editId?: number) {
|
||||||
@ -436,48 +583,177 @@ export function createBot(o: BotOptions) {
|
|||||||
for (const r of await db.select({ projectId: tasks.projectId, at: sql<number>`max(${tasks.updatedAt})` }).from(tasks).groupBy(tasks.projectId)) touched.set(r.projectId, Number(r.at) || 0);
|
for (const r of await db.select({ projectId: tasks.projectId, at: sql<number>`max(${tasks.updatedAt})` }).from(tasks).groupBy(tasks.projectId)) touched.set(r.projectId, Number(r.at) || 0);
|
||||||
projects = [...projects].sort((a, b) => (touched.get(b.id) ?? 0) - (touched.get(a.id) ?? 0) || b.id - a.id);
|
projects = [...projects].sort((a, b) => (touched.get(b.id) ?? 0) - (touched.get(a.id) ?? 0) || b.id - a.id);
|
||||||
const buttons = projects.slice(0, 12).map((p) => ({ text: p.key, callback_data: `d:${d.id}:p:${p.id}` }));
|
const buttons = projects.slice(0, 12).map((p) => ({ text: p.key, callback_data: `d:${d.id}:p:${p.id}` }));
|
||||||
const more = projects.length > 12 ? "\nНет нужного — напишите заново с ключом: «KEY: …»." : "";
|
const text = [tr("📝 Новая задача {title}", { title: storyLine(d) }), tr("В какой проект?"), projects.length > 12 ? tr("Нет нужного — напишите заново с ключом: «KEY: …».") : null];
|
||||||
await show(d.chatId, `📝 Новая задача ${storyLine(d)}\nВ какой проект?${more}`, [...rows(buttons, 3), cancelRow(d)], editId);
|
await show(d.chatId, text.filter((l) => l != null).join("\n"), [...rows(buttons, 3), cancelRow(d)], editId);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function askEpic(d: Draft, project: Project, editId?: number) {
|
async function askEpic(d: Draft, project: Project, editId?: number) {
|
||||||
const epics = (await listGoals(db, project.id)).slice(0, 10);
|
const epics = (await listGoals(db, project.id)).slice(0, 10);
|
||||||
const buttons = epics.length
|
const buttons = epics.length
|
||||||
? [...epics.map((g) => ({ text: g.title.slice(0, 40), callback_data: `d:${d.id}:g:${g.id}` })), { text: "Без эпика", callback_data: `d:${d.id}:g:0` }]
|
? [...epics.map((g) => ({ text: asIs(g.title.slice(0, 40)), callback_data: `d:${d.id}:g:${g.id}` })), { text: tr("Без эпика"), callback_data: `d:${d.id}:g:0` }]
|
||||||
: [{ text: `✅ Создать в ${project.key}`, callback_data: `d:${d.id}:g:0` }];
|
: [{ text: tr("✅ Создать в {key}", { key: project.key }), callback_data: `d:${d.id}:g:0` }];
|
||||||
await show(d.chatId, `📝 Новая задача в <b>${esc(project.key)}</b>: ${storyLine(d)}${epics.length ? "\nЭпик?" : ""}`, [...rows(buttons), cancelRow(d)], editId);
|
const text = tr("📝 Новая задача в <b>{key}</b>: {title}", { key: esc(project.key), title: storyLine(d) }) + (epics.length ? "\n" + tr("Эпик?") : "");
|
||||||
|
await show(d.chatId, text, [...rows(buttons), cancelRow(d)], editId);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** A plain message (or a transcribed voice note) → a draft and the next question. */
|
/** A task in words (or a pressed «Завести как задачу») → a draft and the next question. */
|
||||||
async function startStory(user: User, chatId: number, text: string, voice: boolean) {
|
async function startStory(user: User, chatId: number, text: string, voice: boolean, editId?: number) {
|
||||||
const projects = await listUserProjects(db, user.id);
|
const projects = await listUserProjects(db, user.id);
|
||||||
if (!projects.length) return reply(chatId, `У вас пока нет проектов — создайте первый: ${esc(o.webUrl)}/projects/new`);
|
if (!projects.length) return reply(chatId, tr("У вас пока нет проектов — создайте первый: {url}/projects/new", { url: esc(o.webUrl) }));
|
||||||
const parsed = parseStoryText(text, projects);
|
const parsed = parseStoryText(text, projects);
|
||||||
if (!parsed.body) return reply(chatId, "Задача пустая. Напишите, что нужно сделать.");
|
if (!parsed.body) return reply(chatId, tr("Задача пустая. Напишите, что нужно сделать."));
|
||||||
const project = parsed.project ?? (projects.length === 1 ? projects[0]! : null);
|
const project = parsed.project ?? (projects.length === 1 ? projects[0]! : null);
|
||||||
const d = await saveDraft(db, { userId: user.id, chatId, text: parsed.body, projectId: project?.id ?? null, voice });
|
const d = await saveDraft(db, { userId: user.id, chatId, text: parsed.body, projectId: project?.id ?? null, voice });
|
||||||
if (project) await askEpic(d, project);
|
if (project) await askEpic(d, project, editId);
|
||||||
else await askProject(d, projects);
|
else await askProject(d, projects, editId);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function onVoice(user: User, m: TgMessage) {
|
const asTaskRow = (d: Draft): InlineButton[] => [{ text: INTENT_TEXT.asTask, callback_data: `d:${d.id}:t` }];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PEP-153: a plain message (or a transcribed voice note) is a question or a task. A question is
|
||||||
|
* answered at once, with «Завести как задачу» under the answer; a task becomes a draft (PEP-45);
|
||||||
|
* when it is not clear — or the classifier is not at hand — the person picks by a button.
|
||||||
|
*/
|
||||||
|
async function onPlainText(user: User, chatId: number, text: string, voice: boolean) {
|
||||||
|
const projects = await listUserProjects(db, user.id);
|
||||||
|
if (!projects.length) return startStory(user, chatId, text, voice);
|
||||||
|
const parsed = parseStoryText(text, projects);
|
||||||
|
void api.call("sendChatAction", { chat_id: chatId, action: "typing" }).catch(() => {});
|
||||||
|
const r = await classifyMessage(db, user, parsed.body || text, { explicit: !!parsed.project, project: parsed.project, log });
|
||||||
|
if (r.kind === "task") return startStory(user, chatId, text, voice);
|
||||||
|
const answered = r.kind === "question" && !!r.answer;
|
||||||
|
const d = await saveDraft(db, { userId: user.id, chatId, text, projectId: null, voice, offer: true, asked: !answered, answer: r.answer });
|
||||||
|
if (answered) return show(chatId, esc(r.answer!), [asTaskRow(d)]);
|
||||||
|
await show(chatId, [`«${esc(splitStory(parsed.body || text).title)}»`, r.failed ? INTENT_TEXT.failed : INTENT_TEXT.unsure].join("\n"), [
|
||||||
|
[{ text: INTENT_TEXT.answer, callback_data: `d:${d.id}:a` }, { text: INTENT_TEXT.file, callback_data: `d:${d.id}:t` }],
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Text of a voice note; null — it could not be heard, and the user has been told. */
|
||||||
|
async function voiceText(user: User, m: TgMessage): Promise<string | null> {
|
||||||
const f = m.voice ?? m.audio!;
|
const f = m.voice ?? m.audio!;
|
||||||
const cfg = transcribeConfig();
|
const cfg = transcribeConfig();
|
||||||
if (!cfg) return reply(m.chat.id, "Голосовые сообщения пока не работают. Напишите задачу текстом.", m.message_id);
|
if (!cfg) return reply(m.chat.id, tr("Голосовые сообщения пока не работают. Напишите задачу текстом."), m.message_id).then(() => null);
|
||||||
if ((f.duration ?? 0) > VOICE_MAX_SEC) return reply(m.chat.id, `Слишком длинное голосовое (больше ${VOICE_MAX_SEC / 60} минут) . Запишите короче или напишите текстом.`, m.message_id);
|
if ((f.duration ?? 0) > VOICE_MAX_SEC) return reply(m.chat.id, tr("Слишком длинное голосовое (больше {n} минут) . Запишите короче или напишите текстом.", { n: VOICE_MAX_SEC / 60 }), m.message_id).then(() => null);
|
||||||
let text: string;
|
let text: string;
|
||||||
try {
|
try {
|
||||||
const file = await api.getFile(f.file_id);
|
const file = await api.getFile(f.file_id);
|
||||||
if (!file.file_path) throw new TranscribeError("Telegram не отдал файл");
|
if (!file.file_path) throw new TranscribeError(tr("Telegram не отдал файл"));
|
||||||
const audio = await api.downloadFile(file.file_path);
|
const audio = await api.downloadFile(file.file_path);
|
||||||
text = await transcribe(cfg, audio, file.file_path.split("/").pop() || "voice.ogg", f.mime_type ?? "audio/ogg");
|
// PEP-131: in the speaker's own language (in a group too — theirs, not the group's).
|
||||||
|
const language = transcribeLanguage(cfg, await getUserLocale(db, user.id));
|
||||||
|
text = await transcribe(cfg, audio, file.file_path.split("/").pop() || "voice.ogg", f.mime_type ?? "audio/ogg", language);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
log(`voice: ${(e as Error).message}`);
|
log(`voice: ${(e as Error).message}`);
|
||||||
return reply(m.chat.id, `Не получилось расшифровать голосовое. Напишите задачу текстом.`, m.message_id);
|
return reply(m.chat.id, tr("Не получилось расшифровать голосовое. Напишите задачу текстом."), m.message_id).then(() => null);
|
||||||
}
|
}
|
||||||
if (!text) return reply(m.chat.id, "Не разобрал ни слова. Попробуйте ещё раз или напишите текстом.", m.message_id);
|
if (!text) return reply(m.chat.id, tr("Не разобрал ни слова. Попробуйте ещё раз или напишите текстом."), m.message_id).then(() => null);
|
||||||
await reply(m.chat.id, `🎙 Расслышал: «${esc(text)}»`, m.message_id);
|
await reply(m.chat.id, tr("🎙 Расслышал: «{text}»", { text: asIs(esc(text)) }), m.message_id);
|
||||||
await startStory(user, m.chat.id, text, true);
|
return text;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function onVoice(user: User, m: TgMessage) {
|
||||||
|
const text = await voiceText(user, m);
|
||||||
|
if (text) await onPlainText(user, m.chat.id, text, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── «Сообщить о проблеме» (PEP-143) ────────────────────────────────────────────
|
||||||
|
/** The picture of a message: the largest size of a photo, or an image sent as a file. */
|
||||||
|
const pictureOf = (m: TgMessage) => m.photo?.at(-1) ?? (m.document?.mime_type?.startsWith("image/") ? m.document : undefined);
|
||||||
|
|
||||||
|
async function downloadPicture(m: TgMessage): Promise<Buffer | null> {
|
||||||
|
const ref = pictureOf(m);
|
||||||
|
if (!ref) return null;
|
||||||
|
const file = await api.getFile(ref.file_id);
|
||||||
|
if (!file.file_path) throw new PeppaError(tr("Telegram не отдал файл"));
|
||||||
|
return api.downloadFile(file.file_path);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A message while «Сообщить о проблеме» is on: the first one becomes the report, photos
|
||||||
|
* right after it join it. "pass" — not about the report, handle the message as usual.
|
||||||
|
*/
|
||||||
|
async function onFeedbackMessage(user: User, m: TgMessage, text: string): Promise<"done" | "pass"> {
|
||||||
|
const mode = await feedbackMode(db, user.id);
|
||||||
|
if (!mode) return "pass";
|
||||||
|
const picture = pictureOf(m);
|
||||||
|
try {
|
||||||
|
if (mode.feedbackId) {
|
||||||
|
// The report exists: only more pictures belong to it.
|
||||||
|
if (!picture || text) return closeFeedbackMode(db, user.id).then(() => "pass" as const);
|
||||||
|
const added = await addFeedbackScreenshot(db, user, mode.feedbackId, (await downloadPicture(m))!);
|
||||||
|
if (!added) await reply(m.chat.id, tr("К этому обращению скриншот уже не приложить (не больше {n}). Чтобы начать новое, отправьте /problem.", { n: FEEDBACK_MAX_SHOTS }), m.message_id);
|
||||||
|
else await keepFeedbackMode(db, user.id, mode.feedbackId);
|
||||||
|
return "done";
|
||||||
|
}
|
||||||
|
if (text.startsWith("/")) return closeFeedbackMode(db, user.id).then(() => "pass" as const);
|
||||||
|
let said = text || m.caption?.trim() || "";
|
||||||
|
if (!said && (m.voice || m.audio)) {
|
||||||
|
const heard = await voiceText(user, m);
|
||||||
|
if (!heard) return "done";
|
||||||
|
said = heard;
|
||||||
|
}
|
||||||
|
if (!said && !picture) {
|
||||||
|
await reply(m.chat.id, tr("Напишите, что случилось, или приложите скриншот."), m.message_id);
|
||||||
|
return "done";
|
||||||
|
}
|
||||||
|
const data = picture ? await downloadPicture(m) : null;
|
||||||
|
const f = await submitFeedback(db, user, { text: said, via: "telegram", files: data ? [data] : [], context: { locale: await telegramChatLocale(db, m.chat.id).catch(() => undefined) } });
|
||||||
|
await keepFeedbackMode(db, user.id, f.id);
|
||||||
|
await reply(
|
||||||
|
m.chat.id,
|
||||||
|
// glossary-ignore: «команда» here is the team of people, not a terminal command
|
||||||
|
[tr("Спасибо, передали команде. Обращение №{id}.", { id: f.id }), tr("Можно прислать ещё скриншоты — до {n} на обращение.", { n: FEEDBACK_MAX_SHOTS }), tr("Ваши обращения: {url}/feedback", { url: esc(o.webUrl) })].join("\n"),
|
||||||
|
m.message_id,
|
||||||
|
);
|
||||||
|
} catch (e) {
|
||||||
|
if (!(e instanceof PeppaError)) throw e;
|
||||||
|
await reply(m.chat.id, esc(e.message), m.message_id);
|
||||||
|
}
|
||||||
|
return "done";
|
||||||
|
}
|
||||||
|
|
||||||
|
/** PEP-197: the owner decides on stories the factory suggested. */
|
||||||
|
async function onProposalButton(user: User, c: TgCallbackQuery, parts: string[]): Promise<string> {
|
||||||
|
const ids = (parts[1] ?? "").split(",").map(Number).filter((n) => Number.isInteger(n) && n > 0);
|
||||||
|
const choice = parts[2];
|
||||||
|
if (choice !== "do" && choice !== "no" && choice !== "important" && choice !== "none") return tr("Неизвестная кнопка");
|
||||||
|
const n = await decideProposals(db, user, ids, choice);
|
||||||
|
return choice === "do" || choice === "important" ? tr("Принято, задач: {n}", { n }) : tr("Отклонено: {n}", { n });
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A superadmin's buttons under a report: `f:<id>:o<N>` (a story from option N), `dup`, `no`. */
|
||||||
|
async function onFeedbackButton(user: User, c: TgCallbackQuery, parts: string[]): Promise<string> {
|
||||||
|
const id = Number(parts[1]);
|
||||||
|
const chatId = c.message!.chat.id;
|
||||||
|
const settle = async (line: string) => {
|
||||||
|
await api.call("editMessageReplyMarkup", { chat_id: chatId, message_id: c.message!.message_id, reply_markup: { inline_keyboard: [] } }).catch(() => {});
|
||||||
|
await reply(chatId, line, c.message!.message_id);
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
const option = /^o(\d)$/.exec(parts[2] ?? "");
|
||||||
|
if (option) {
|
||||||
|
const ref = await fixFeedback(db, user, id, Number(option[1]));
|
||||||
|
await settle([tr("✅ Обращение №{id}: заведена задача <b>{key}</b>", { id, key: esc(ref.key) }), `${esc(o.webUrl)}/t/${esc(ref.key)}`].join("\n"));
|
||||||
|
return tr("Заведена задача {key}", { key: ref.key });
|
||||||
|
}
|
||||||
|
if (parts[2] === "dup") {
|
||||||
|
const ref = await linkFeedback(db, user, id);
|
||||||
|
await settle(tr("🔗 Обращение №{id} связано с задачей <b>{key}</b>", { id, key: esc(ref.key) }));
|
||||||
|
return tr("Связано с {key}", { key: ref.key });
|
||||||
|
}
|
||||||
|
if (parts[2] === "no") {
|
||||||
|
if (!(await isSuperadmin(db, user))) return tr("Обращение не найдено");
|
||||||
|
await askRejectReason(db, user.id, id);
|
||||||
|
await reply(chatId, tr("Напишите причину одним сообщением — её увидит автор обращения №{id}. Чтобы отклонить без причины, отправьте «-».", { id }), c.message!.message_id);
|
||||||
|
return tr("Жду причину");
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
if (!(e instanceof PeppaError)) throw e;
|
||||||
|
return e.message;
|
||||||
|
}
|
||||||
|
return tr("Неизвестная кнопка");
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Buttons of a draft (`d:<id>:p:<project>` / `d:<id>:g:<epic|0>` / `d:<id>:x`) and of a new story (`t:<task>:start|keep`). */
|
/** Buttons of a draft (`d:<id>:p:<project>` / `d:<id>:g:<epic|0>` / `d:<id>:x`) and of a new story (`t:<task>:start|keep`). */
|
||||||
@ -486,63 +762,79 @@ export function createBot(o: BotOptions) {
|
|||||||
const chatId = c.message!.chat.id;
|
const chatId = c.message!.chat.id;
|
||||||
if (parts[0] === "t") {
|
if (parts[0] === "t") {
|
||||||
const [t] = await db.select().from(tasks).where(eq(tasks.id, Number(parts[1])));
|
const [t] = await db.select().from(tasks).where(eq(tasks.id, Number(parts[1])));
|
||||||
if (!t || !(await canAccess(user, t.projectId))) return "Задача не найдена";
|
if (!t || !(await canAccess(user, t.projectId))) return tr("Задача не найдена");
|
||||||
const [project] = await db.select().from(projects).where(eq(projects.id, t.projectId));
|
const [project] = await db.select().from(projects).where(eq(projects.id, t.projectId));
|
||||||
const ref = { project: project!, task: t, key: formatTaskKey(project!.key, t.number) };
|
const ref = { project: project!, task: t, key: formatTaskKey(project!.key, t.number) };
|
||||||
const head = `📥 ${esc(ref.key)}: ${esc(t.title)}\n${esc(o.webUrl)}/t/${esc(ref.key)}`;
|
const head = `📥 ${esc(ref.key)}: ${asIs(esc(t.title))}\n${esc(o.webUrl)}/t/${esc(ref.key)}`;
|
||||||
if (parts[2] === "keep") {
|
if (parts[2] === "keep") {
|
||||||
await show(chatId, `${head}\nВ бэклоге.`, [], msgId);
|
await show(chatId, head + "\n" + tr("В бэклоге."), [], msgId);
|
||||||
return "Оставил в бэклоге";
|
return tr("Оставил в бэклоге");
|
||||||
}
|
}
|
||||||
if (parts[2] !== "start") return "Неизвестная кнопка";
|
if (parts[2] !== "start") return tr("Неизвестная кнопка");
|
||||||
if (t.status !== "backlog") {
|
if (t.status !== "backlog") {
|
||||||
await show(chatId, `${head}\nУже не в бэклоге (${esc(t.status)}).`, [], msgId);
|
await show(chatId, head + "\n" + tr("Уже не в бэклоге ({status}).", { status: esc(t.status) }), [], msgId);
|
||||||
return `${ref.key} уже ${t.status}`;
|
return tr("{key} уже {status}", { key: ref.key, status: t.status });
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
await moveTask(db, ref, "in_progress");
|
await moveTask(db, ref, "in_progress");
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return (e as Error).message;
|
return (e as Error).message;
|
||||||
}
|
}
|
||||||
await show(chatId, `${head}\n▶️ В работе — агент взялся.`, [], msgId);
|
await show(chatId, head + "\n" + tr("▶️ В работе — агент взялся."), [], msgId);
|
||||||
return `${ref.key}: агент взялся ▶️`;
|
return tr("{key}: агент взялся ▶️", { key: ref.key });
|
||||||
}
|
}
|
||||||
const d = await loadDraft(db, Number(parts[1]), user.id);
|
const d = await loadDraft(db, Number(parts[1]), user.id);
|
||||||
if (!d) {
|
if (!d) {
|
||||||
await show(chatId, "Черновик устарел. Напишите задачу заново.", [], msgId);
|
await show(chatId, tr("Черновик устарел. Напишите задачу заново."), [], msgId);
|
||||||
return "Черновик устарел";
|
return tr("Черновик устарел");
|
||||||
}
|
}
|
||||||
|
// PEP-153: «Ответить» — the answer at hand, else the state of things from the platform's data.
|
||||||
|
if (parts[2] === "a" && d.offer) {
|
||||||
|
const text = d.answer ?? (await statusAnswer(db, user, { text: d.text, webUrl: o.webUrl }));
|
||||||
|
await updateDraft(db, { ...d, asked: false });
|
||||||
|
await show(chatId, esc(text), [asTaskRow(d)], msgId);
|
||||||
|
return tr("Ответил");
|
||||||
|
}
|
||||||
|
// PEP-153: «Завести как задачу» — the message becomes a draft; an answer above stays as it is.
|
||||||
|
if (parts[2] === "t" && d.offer) {
|
||||||
|
await dropDraft(db, d.id);
|
||||||
|
const answered = !d.asked;
|
||||||
|
if (answered && msgId) await api.call("editMessageReplyMarkup", { chat_id: chatId, message_id: msgId, reply_markup: { inline_keyboard: [] } }).catch(() => {});
|
||||||
|
await startStory(user, chatId, d.text, d.voice, answered ? undefined : msgId);
|
||||||
|
return tr("Завожу задачу");
|
||||||
|
}
|
||||||
|
if (d.offer) return tr("Неизвестная кнопка");
|
||||||
if (parts[2] === "x") {
|
if (parts[2] === "x") {
|
||||||
await dropDraft(db, d.id);
|
await dropDraft(db, d.id);
|
||||||
await show(chatId, `✖️ Отменено: ${storyLine(d)}`, [], msgId);
|
await show(chatId, tr("✖️ Отменено: {title}", { title: storyLine(d) }), [], msgId);
|
||||||
return "Отменено";
|
return tr("Отменено");
|
||||||
}
|
}
|
||||||
if (parts[2] === "p") {
|
if (parts[2] === "p") {
|
||||||
const projectId = Number(parts[3]);
|
const projectId = Number(parts[3]);
|
||||||
const project = await projectForUser(db, user.id, projectId).catch(() => null);
|
const project = await projectForUser(db, user.id, projectId).catch(() => null);
|
||||||
if (!project) return "Проект не найден";
|
if (!project) return tr("Проект не найден");
|
||||||
await updateDraft(db, { ...d, projectId });
|
await updateDraft(db, { ...d, projectId });
|
||||||
await askEpic(d, project, msgId);
|
await askEpic(d, project, msgId);
|
||||||
return project.key;
|
return project.key;
|
||||||
}
|
}
|
||||||
if (parts[2] === "g" && d.projectId) {
|
if (parts[2] === "g" && d.projectId) {
|
||||||
const project = await projectForUser(db, user.id, d.projectId).catch(() => null);
|
const project = await projectForUser(db, user.id, d.projectId).catch(() => null);
|
||||||
if (!project) return "Проект не найден";
|
if (!project) return tr("Проект не найден");
|
||||||
const goalId = Number(parts[3]) || undefined;
|
const goalId = Number(parts[3]) || undefined;
|
||||||
if (goalId && !(await getGoal(db, project.id, goalId).catch(() => null))) return "Эпик не найден";
|
if (goalId && !(await getGoal(db, project.id, goalId).catch(() => null))) return tr("Эпик не найден");
|
||||||
const { title, rest } = splitStory(d.text);
|
const { title, rest } = splitStory(d.text);
|
||||||
const from = `Создано из Telegram (${user.login}${d.voice ? ", расшифровка голосового" : ""}).`;
|
const from = d.voice ? tr("Создано из Telegram ({login}, расшифровка голосового).", { login: user.login }) : tr("Создано из Telegram ({login}).", { login: user.login });
|
||||||
const ref = await createTask(db, { projectId: project.id, goalId, title, description: `${rest ? `${rest}\n\n` : ""}${from}` });
|
const ref = await createTask(db, { projectId: project.id, goalId, title, description: `${rest ? `${rest}\n\n` : ""}${from}` });
|
||||||
await dropDraft(db, d.id);
|
await dropDraft(db, d.id);
|
||||||
await show(
|
await show(
|
||||||
chatId,
|
chatId,
|
||||||
`📥 Создал <b>${esc(ref.key)}</b>: ${esc(title)}\n${esc(o.webUrl)}/t/${esc(ref.key)}\nВзять в работу сейчас?`,
|
[tr("📥 Создал <b>{key}</b>: {title}", { key: esc(ref.key), title: asIs(esc(title)) }), `${esc(o.webUrl)}/t/${esc(ref.key)}`, tr("Взять в работу сейчас?")].join("\n"),
|
||||||
[[{ text: "▶️ Взять в работу", callback_data: `t:${ref.task.id}:start` }, { text: "Оставить в бэклоге", callback_data: `t:${ref.task.id}:keep` }]],
|
[[{ text: tr("▶️ Взять в работу"), callback_data: `t:${ref.task.id}:start` }, { text: tr("Оставить в бэклоге"), callback_data: `t:${ref.task.id}:keep` }]],
|
||||||
msgId,
|
msgId,
|
||||||
);
|
);
|
||||||
return `Создал ${ref.key}`;
|
return tr("Создал {key}", { key: ref.key });
|
||||||
}
|
}
|
||||||
return "Неизвестная кнопка";
|
return tr("Неизвестная кнопка");
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Is the update being handled by the bot this chat's group is linked through? */
|
/** Is the update being handled by the bot this chat's group is linked through? */
|
||||||
@ -558,12 +850,19 @@ export function createBot(o: BotOptions) {
|
|||||||
// another bot is that bot's business, this one keeps quiet.
|
// another bot is that bot's business, this one keeps quiet.
|
||||||
const codeBot = isChatLinkCode(code) ? await chatLinkCodeBot(db, o.secret, code) : undefined;
|
const codeBot = isChatLinkCode(code) ? await chatLinkCodeBot(db, o.secret, code) : undefined;
|
||||||
if (!link[1] && codeBot !== undefined && codeBot !== (via.getStore()?.userId ?? null)) return "ignored";
|
if (!link[1] && codeBot !== undefined && codeBot !== (via.getStore()?.userId ?? null)) return "ignored";
|
||||||
if (!isChatLinkCode(code)) return reply(m.chat.id, "Это не код связки чата. Получи код в вебе: Чаты → «Связать с Telegram».").then(() => "done");
|
if (!isChatLinkCode(code)) return reply(m.chat.id, tr("Это не код связки чата. Получи код в вебе: Чаты → «Связать с Telegram».")).then(() => "done");
|
||||||
const chat = await acceptChatLink(db, o.secret, code, { tgChatId: m.chat.id, title: m.chat.title ?? null, botUserId: via.getStore()?.userId });
|
const chat = await acceptChatLink(db, o.secret, code, { tgChatId: m.chat.id, title: m.chat.title ?? null, botUserId: via.getStore()?.userId });
|
||||||
if (!chat) return reply(m.chat.id, "Код связки неверный или истёк — получи новый в вебе: Чаты → «Связать с Telegram».").then(() => "done");
|
if (!chat) return reply(m.chat.id, tr("Код связки неверный или истёк — получи новый в вебе: Чаты → «Связать с Telegram».")).then(() => "done");
|
||||||
await syncOwnBots().catch(() => {}); // the group now belongs to this bot
|
await syncOwnBots().catch(() => {}); // the group now belongs to this bot
|
||||||
const name = chat.projectId ? `чатом проекта ${esc(await projectKey(chat.projectId))}` : "мастер-чатом";
|
const name = chat.projectId ? tr("чатом проекта {key}", { key: esc(await projectKey(chat.projectId)) }) : tr("мастер-чатом");
|
||||||
await reply(m.chat.id, `Группа связана с ${name} ✅\n\nСюда будут приходить события и вопросы агентов, треды — цепочками ответов. Ответьте <b>реплаем</b> — сообщение уйдёт в тред (в переписке по задаче — агенту). Отвечать могут те, кто привязал Telegram в Peppa FACTORY и имеет доступ к проекту. /help — команды.`);
|
await reply(
|
||||||
|
m.chat.id,
|
||||||
|
[
|
||||||
|
tr("Группа связана с {name} ✅", { name }),
|
||||||
|
"",
|
||||||
|
tr("Сюда будут приходить события и вопросы агентов, треды — цепочками ответов. Ответьте <b>реплаем</b> — сообщение уйдёт в тред (в переписке по задаче — агенту). Отвечать могут те, кто привязал Telegram в FORGE и имеет доступ к проекту. /help — команды."),
|
||||||
|
].join("\n"),
|
||||||
|
);
|
||||||
return "done";
|
return "done";
|
||||||
}
|
}
|
||||||
const chat = await chatByTelegram(db, m.chat.id);
|
const chat = await chatByTelegram(db, m.chat.id);
|
||||||
@ -574,7 +873,7 @@ export function createBot(o: BotOptions) {
|
|||||||
if (!m.reply_to_message && !text.startsWith("/")) return "ignored";
|
if (!m.reply_to_message && !text.startsWith("/")) return "ignored";
|
||||||
const user = await telegramAccountUser(db, m.from.id);
|
const user = await telegramAccountUser(db, m.from.id);
|
||||||
if (!user || !(await mayWriteChat(db, user, chat))) {
|
if (!user || !(await mayWriteChat(db, user, chat))) {
|
||||||
await reply(m.chat.id, user ? "У вас нет доступа к этому чату." : `Не нашёл вас в Peppa FACTORY — привяжите Telegram: ${esc(o.webUrl)}/settings → Telegram.`, m.message_id);
|
await reply(m.chat.id, user ? tr("У вас нет доступа к этому чату.") : tr("Не нашёл вас в FORGE — привяжите Telegram: {url}/settings → Telegram.", { url: esc(o.webUrl) }), m.message_id);
|
||||||
return "done";
|
return "done";
|
||||||
}
|
}
|
||||||
enterActor({ kind: "user", userId: user.id, channel: "telegram" });
|
enterActor({ kind: "user", userId: user.id, channel: "telegram" });
|
||||||
@ -609,11 +908,11 @@ export function createBot(o: BotOptions) {
|
|||||||
const b = await acceptPairing(db, o.secret, start[1], { chatId: m.chat.id, userId: m.from.id, username: m.from.username, botUserId: via.getStore()?.userId });
|
const b = await acceptPairing(db, o.secret, start[1], { chatId: m.chat.id, userId: m.from.id, username: m.from.username, botUserId: via.getStore()?.userId });
|
||||||
if (b) {
|
if (b) {
|
||||||
await syncOwnBots().catch(() => {}); // the chat now belongs to this bot
|
await syncOwnBots().catch(() => {}); // the chat now belongs to this bot
|
||||||
await reply(m.chat.id, `Привязано ✅\n\n${HELP}`);
|
await reply(m.chat.id, tr("Привязано ✅") + "\n\n" + helpText(voiceStoriesEnabled()));
|
||||||
scheduleReconcile();
|
scheduleReconcile();
|
||||||
return "done";
|
return "done";
|
||||||
}
|
}
|
||||||
await reply(m.chat.id, `Код привязки неверный или истёк. Получи новый: ${esc(o.webUrl)}/settings → Telegram`);
|
await reply(m.chat.id, tr("Код привязки неверный или истёк. Получи новый: {url}/settings → Telegram", { url: esc(o.webUrl) }));
|
||||||
return "done";
|
return "done";
|
||||||
}
|
}
|
||||||
const user = m.from ? await telegramUser(db, m.chat.id, m.from.id) : null;
|
const user = m.from ? await telegramUser(db, m.chat.id, m.from.id) : null;
|
||||||
@ -624,18 +923,39 @@ export function createBot(o: BotOptions) {
|
|||||||
// PEP-48: what follows is done by this user through Telegram.
|
// PEP-48: what follows is done by this user through Telegram.
|
||||||
enterActor({ kind: "user", userId: user.id, channel: "telegram" });
|
enterActor({ kind: "user", userId: user.id, channel: "telegram" });
|
||||||
|
|
||||||
if (/^\/(start|help)\b/.test(text)) return reply(m.chat.id, HELP).then(() => "done");
|
if (/^\/(start|help)\b/.test(text)) return reply(m.chat.id, helpText(voiceStoriesEnabled())).then(() => "done");
|
||||||
if (/^\/status\b/.test(text)) return reply(m.chat.id, await status(user)).then(() => "done");
|
if (/^\/status\b/.test(text)) return reply(m.chat.id, await status(user)).then(() => "done");
|
||||||
if (/^\/digest\b/.test(text)) {
|
if (/^\/digest\b/.test(text)) {
|
||||||
const d = await buildDigest(db, user);
|
const d = await buildDigest(db, user);
|
||||||
await api.sendMessage(m.chat.id, renderDigest(d, { webUrl: o.webUrl, title: "Сводка за сутки" }), { link_preview_options: { is_disabled: true } }).catch((e) => log(`digest: ${e.message}`));
|
await api.sendMessage(m.chat.id, renderDigest(d, { webUrl: o.webUrl, title: tr("Сводка за сутки") }), { link_preview_options: { is_disabled: true } }).catch((e) => log(`digest: ${e.message}`));
|
||||||
return "done";
|
return "done";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// PEP-143: «Сообщить о проблеме».
|
||||||
|
if (/^\/(problem|feedback)\b/.test(text)) {
|
||||||
|
await openFeedbackMode(db, user.id);
|
||||||
|
await reply(m.chat.id, [tr("Опишите, что случилось, одним сообщением — текстом, фото экрана с подписью или голосом."), tr("Мы передадим это тем, кто делает FORGE.")].join("\n"));
|
||||||
|
return "done";
|
||||||
|
}
|
||||||
|
// A superadmin pressed «Не исправлять»: this message is the reason.
|
||||||
|
const rejecting = text && !text.startsWith("/") ? await pendingReject(db, user.id) : null;
|
||||||
|
if (rejecting != null) {
|
||||||
|
await clearReject(db, user.id);
|
||||||
|
try {
|
||||||
|
await rejectFeedback(db, user, rejecting, text === "-" ? null : text);
|
||||||
|
await reply(m.chat.id, tr("Обращение №{id} отклонено, автор получит ответ.", { id: rejecting }), m.message_id);
|
||||||
|
} catch (e) {
|
||||||
|
await reply(m.chat.id, esc((e as Error).message), m.message_id);
|
||||||
|
}
|
||||||
|
wakeOutbox?.();
|
||||||
|
return "done";
|
||||||
|
}
|
||||||
|
if (!m.reply_to_message && (await onFeedbackMessage(user, m, text)) === "done") return "done";
|
||||||
|
|
||||||
if (m.reply_to_message) {
|
if (m.reply_to_message) {
|
||||||
const q = await questionByTelegramMessage(db, m.chat.id, m.reply_to_message.message_id);
|
const q = await questionByTelegramMessage(db, m.chat.id, m.reply_to_message.message_id);
|
||||||
if (!q || !(await canAccess(user, q.projectId))) {
|
if (!q || !(await canAccess(user, q.projectId))) {
|
||||||
await reply(m.chat.id, "Не нашёл вопрос для этого сообщения.", m.message_id);
|
await reply(m.chat.id, tr("Не нашёл вопрос для этого сообщения."), m.message_id);
|
||||||
return "done";
|
return "done";
|
||||||
}
|
}
|
||||||
await reply(m.chat.id, esc(await answer(q, text)), m.message_id);
|
await reply(m.chat.id, esc(await answer(q, text)), m.message_id);
|
||||||
@ -645,15 +965,27 @@ export function createBot(o: BotOptions) {
|
|||||||
await onVoice(user, m);
|
await onVoice(user, m);
|
||||||
return "done";
|
return "done";
|
||||||
}
|
}
|
||||||
if (!text || text.startsWith("/")) {
|
if (pictureOf(m)) {
|
||||||
await reply(m.chat.id, "Чтобы ответить агенту, ответьте <b>реплаем</b> на его сообщение. Чтобы завести задачу — просто напишите её. /help — что я умею.");
|
await reply(m.chat.id, tr("Чтобы сообщить о проблеме в FORGE, сначала отправьте /problem, а потом фото."), m.message_id);
|
||||||
return "done";
|
return "done";
|
||||||
}
|
}
|
||||||
// PEP-45: any other text is a new story (created only after a button press).
|
if (!text || text.startsWith("/")) {
|
||||||
await startStory(user, m.chat.id, text, false);
|
await reply(m.chat.id, tr("Чтобы ответить агенту, ответьте <b>реплаем</b> на его сообщение. Чтобы завести задачу — просто напишите её. /help — что я умею."));
|
||||||
|
return "done";
|
||||||
|
}
|
||||||
|
// PEP-153: a question is answered, a task becomes a draft (PEP-45: created only after a button press).
|
||||||
|
await onPlainText(user, m.chat.id, text, false);
|
||||||
return "done";
|
return "done";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function onDelayButton(user: User, data: string): Promise<string> {
|
||||||
|
const b = parseDelayCallback(data);
|
||||||
|
if (!b || !(await isSuperadmin(db, user))) return tr("Неизвестная кнопка");
|
||||||
|
const projectId = b.scope.projectId ?? (b.scope.taskId != null ? (await resolveTaskById(db, b.scope.taskId).catch(() => null))?.project.id : null);
|
||||||
|
if (projectId == null) return tr("Задача не найдена");
|
||||||
|
return delayAction(db, { projectId, taskId: b.scope.taskId }, b.reason, b.action);
|
||||||
|
}
|
||||||
|
|
||||||
async function onCallback(c: TgCallbackQuery): Promise<"done" | "ignored"> {
|
async function onCallback(c: TgCallbackQuery): Promise<"done" | "ignored"> {
|
||||||
let user = c.message ? await telegramUser(db, c.message.chat.id, c.from.id) : null;
|
let user = c.message ? await telegramUser(db, c.message.chat.id, c.from.id) : null;
|
||||||
if (!user && c.message && c.message.chat.type !== "private") {
|
if (!user && c.message && c.message.chat.type !== "private") {
|
||||||
@ -664,32 +996,68 @@ export function createBot(o: BotOptions) {
|
|||||||
if (chat && who && (chat.kind === "project" || chat.userId === who.id)) user = who;
|
if (chat && who && (chat.kind === "project" || chat.userId === who.id)) user = who;
|
||||||
}
|
}
|
||||||
if (!user) {
|
if (!user) {
|
||||||
await api.answerCallbackQuery(c.id, "Нет доступа").catch(() => {});
|
await api.answerCallbackQuery(c.id, tr("Нет доступа")).catch(() => {});
|
||||||
return "ignored";
|
return "ignored";
|
||||||
}
|
}
|
||||||
enterActor({ kind: "user", userId: user.id, channel: "telegram" });
|
enterActor({ kind: "user", userId: user.id, channel: "telegram" });
|
||||||
const parts = (c.data ?? "").split(":");
|
const parts = (c.data ?? "").split(":");
|
||||||
if (parts[0] === "d" || parts[0] === "t") {
|
if (parts[0] === "d" || parts[0] === "t") {
|
||||||
const toast = await onStoryButton(user, c, parts).catch((e) => (log(`story: ${(e as Error).stack ?? e}`), "Ошибка"));
|
const toast = await onStoryButton(user, c, parts).catch((e) => (log(`story: ${(e as Error).stack ?? e}`), tr("Ошибка")));
|
||||||
|
await api.answerCallbackQuery(c.id, toast.slice(0, 190)).catch((e) => log(`answerCallbackQuery: ${e.message}`));
|
||||||
|
return "done";
|
||||||
|
}
|
||||||
|
// PEP-197: «Делать» / «Не надо» under the acceptance agent's message: `p:<ids>:do|no|important|none`.
|
||||||
|
if (parts[0] === "p") {
|
||||||
|
const toast = await onProposalButton(user, c, parts).catch((e) => (e instanceof PeppaError ? e.message : (log(`proposal: ${(e as Error).stack ?? e}`), tr("Ошибка"))));
|
||||||
|
await api.answerCallbackQuery(c.id, toast.slice(0, 190)).catch((e) => log(`answerCallbackQuery: ${e.message}`));
|
||||||
|
return "done";
|
||||||
|
}
|
||||||
|
// PEP-209: the superadmin's buttons on a delay message: `pd:<t|p><id>:<reason>:r|v|x`.
|
||||||
|
if (parts[0] === "pd") {
|
||||||
|
const toast = await onDelayButton(user, c.data ?? "").catch((e) => (e instanceof PeppaError ? e.message : (log(`delay: ${(e as Error).stack ?? e}`), tr("Ошибка"))));
|
||||||
|
wakeOutbox?.();
|
||||||
|
await api.answerCallbackQuery(c.id, toast.slice(0, 190)).catch((e) => log(`answerCallbackQuery: ${e.message}`));
|
||||||
|
return "done";
|
||||||
|
}
|
||||||
|
// PEP-250: «Отказать» under an agent's access request: `ar:<id>:no` — only the project's owner (core checks).
|
||||||
|
if (parts[0] === "ar") {
|
||||||
|
const toast = await denyAccessRequestAndTell(db, user.id, Number(parts[1]), null).then(
|
||||||
|
() => tr("Отказано. Агент узнает об этом."),
|
||||||
|
(e) => (e instanceof PeppaError ? e.message : (log(`access request: ${(e as Error).stack ?? e}`), tr("Ошибка"))),
|
||||||
|
);
|
||||||
|
await api.answerCallbackQuery(c.id, toast.slice(0, 190)).catch((e) => log(`answerCallbackQuery: ${e.message}`));
|
||||||
|
return "done";
|
||||||
|
}
|
||||||
|
// PEP-259: the owner's answer to «агенты давно не пользуются разрешением — снять?»: `cg:<grantId>:r|k`.
|
||||||
|
if (parts[0] === "cg") {
|
||||||
|
const b = parseIdleGrantCallback(c.data ?? "");
|
||||||
|
const toast = b ? await decideIdleGrant(db, user.id, b.grantId, b.decision).catch((e) => (e instanceof PeppaError ? e.message : (log(`idle grant: ${(e as Error).stack ?? e}`), tr("Ошибка")))) : tr("Неизвестная кнопка");
|
||||||
|
await api.answerCallbackQuery(c.id, toast.slice(0, 190)).catch((e) => log(`answerCallbackQuery: ${e.message}`));
|
||||||
|
return "done";
|
||||||
|
}
|
||||||
|
if (parts[0] === "f") {
|
||||||
|
const toast = await onFeedbackButton(user, c, parts).catch((e) => (log(`feedback: ${(e as Error).stack ?? e}`), tr("Ошибка")));
|
||||||
|
wakeOutbox?.();
|
||||||
await api.answerCallbackQuery(c.id, toast.slice(0, 190)).catch((e) => log(`answerCallbackQuery: ${e.message}`));
|
await api.answerCallbackQuery(c.id, toast.slice(0, 190)).catch((e) => log(`answerCallbackQuery: ${e.message}`));
|
||||||
return "done";
|
return "done";
|
||||||
}
|
}
|
||||||
const [kind, idStr, choice] = parts;
|
const [kind, idStr, choice] = parts;
|
||||||
const id = Number(idStr);
|
const id = Number(idStr);
|
||||||
let toast = "Неизвестная кнопка";
|
let toast = tr("Неизвестная кнопка");
|
||||||
const q0 = kind === "q" ? await getQuestion(db, id).catch(() => null) : null;
|
const q0 = kind === "q" ? await getQuestion(db, id).catch(() => null) : null;
|
||||||
const s0 = kind === "s" ? await getSession(db, id).catch(() => null) : null;
|
const s0 = kind === "s" ? await getSession(db, id).catch(() => null) : null;
|
||||||
const i0 = kind === "i" ? await getIncident(db, id).catch(() => null) : null;
|
const i0 = kind === "i" ? await getIncident(db, id).catch(() => null) : null;
|
||||||
const projectId = q0?.projectId ?? s0?.projectId ?? i0?.projectId;
|
const projectId = q0?.projectId ?? s0?.projectId ?? i0?.projectId;
|
||||||
if (projectId == null || !(await canAccess(user, projectId))) {
|
if (projectId == null || !(await canAccess(user, projectId))) {
|
||||||
// Unknown or someone else's question/session: don't reveal which.
|
// Unknown or someone else's question/session: don't reveal which.
|
||||||
await api.answerCallbackQuery(c.id, kind === "s" ? "Агент не найден" : kind === "i" ? "Ошибка не найдена" : "Вопрос не найден").catch(() => {});
|
await api.answerCallbackQuery(c.id, kind === "s" ? tr("Агент не найден") : kind === "i" ? tr("Ошибка не найдена") : tr("Вопрос не найден")).catch(() => {});
|
||||||
return "done";
|
return "done";
|
||||||
}
|
}
|
||||||
if (kind === "q" && choice === "accept") {
|
if (kind === "q" && choice === "accept") {
|
||||||
try {
|
try {
|
||||||
const ref = await acceptTask(db, id, "telegram");
|
const ref = await acceptTask(db, id, "telegram");
|
||||||
toast = `${ref.key} принята ✅`;
|
// PEP-127: over a conflict the accept is remembered and carried through.
|
||||||
|
toast = ref.pending ? tr("{key}: принято ✅ Изменения обновляются, задача закроется сама", { key: ref.key }) : tr("{key} принята ✅", { key: ref.key });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
toast = (e as Error).message;
|
toast = (e as Error).message;
|
||||||
}
|
}
|
||||||
@ -697,30 +1065,40 @@ export function createBot(o: BotOptions) {
|
|||||||
} else if (kind === "q") {
|
} else if (kind === "q") {
|
||||||
const q = await getQuestion(db, id).catch(() => null);
|
const q = await getQuestion(db, id).catch(() => null);
|
||||||
const text = q && choice ? choiceToAnswer(q, choice) : null;
|
const text = q && choice ? choiceToAnswer(q, choice) : null;
|
||||||
toast = q && text ? await answer(q, text) : "Вопрос не найден";
|
// PEP-149: the «continue» button of an earlier message answers nothing.
|
||||||
|
toast = q && text ? await answer(q, text) : q && choice === "cont" ? tr("Кнопка устарела — ответьте на сообщение текстом.") : tr("Вопрос не найден");
|
||||||
} else if (kind === "i" && (choice === "backlog" || choice === "start" || choice === "ignore")) {
|
} else if (kind === "i" && (choice === "backlog" || choice === "start" || choice === "ignore")) {
|
||||||
// Decision on a new production error (PEP-58).
|
// Decision on a new production error (PEP-58).
|
||||||
try {
|
try {
|
||||||
const r = await decideIncident(db, id, choice, user.login);
|
const r = await decideIncident(db, id, choice, user.login);
|
||||||
toast = r.task ? `${r.task.key}: ${choice === "start" ? "агент взялся ▶️" : "в бэклоге 📥"}` : "Игнорируем 🙈";
|
toast = r.task ? (choice === "start" ? tr("{key}: агент взялся ▶️", { key: r.task.key }) : tr("{key}: в бэклоге 📥", { key: r.task.key })) : tr("Игнорируем 🙈");
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
toast = (e as Error).message;
|
toast = (e as Error).message;
|
||||||
}
|
}
|
||||||
wakeOutbox?.();
|
wakeOutbox?.();
|
||||||
} else if (kind === "s") {
|
} else if (kind === "s") {
|
||||||
const s = await getSession(db, id).catch(() => null);
|
const s = await getSession(db, id).catch(() => null);
|
||||||
if (!s) toast = "Агент не найден";
|
if (!s) toast = tr("Агент не найден");
|
||||||
else if (choice === "resume") {
|
else if (choice === "resume") {
|
||||||
try {
|
try {
|
||||||
const r = await resumeSession(db, s.id);
|
const r = await resumeSession(db, s.id);
|
||||||
toast = "Агент продолжил работу 🔁";
|
toast = tr("Агент продолжил работу 🔁");
|
||||||
void r;
|
void r;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
toast = (e as Error).message;
|
toast = (e as Error).message;
|
||||||
}
|
}
|
||||||
} else if (choice === "stop") {
|
} else if (choice === "stop") {
|
||||||
await stopSession(db, s.id);
|
await stopSession(db, s.id);
|
||||||
toast = "Агент остановлен ⏹";
|
toast = tr("Агент остановлен ⏹");
|
||||||
|
} else if (choice === "ask") {
|
||||||
|
// PEP-186: «Попросить подписку у администратора» under a limit message.
|
||||||
|
try {
|
||||||
|
await requestSubscription(db, user, await projectForUser(db, user.id, s.projectId));
|
||||||
|
toast = REQUEST_SENT_TEXT;
|
||||||
|
} catch (e) {
|
||||||
|
toast = (e as Error).message;
|
||||||
|
}
|
||||||
|
wakeOutbox?.();
|
||||||
}
|
}
|
||||||
scheduleReconcile();
|
scheduleReconcile();
|
||||||
}
|
}
|
||||||
@ -729,6 +1107,13 @@ export function createBot(o: BotOptions) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function handleUpdate(u: TgUpdate): Promise<void> {
|
async function handleUpdate(u: TgUpdate): Promise<void> {
|
||||||
|
// PEP-98: the person who sent the update reads the toasts and replies without a chat_id.
|
||||||
|
const reader = u.callback_query?.from?.id ?? u.message?.from?.id ?? u.message?.chat?.id;
|
||||||
|
if (reader != null) return readerChat.run(reader, () => handleUpdateIn(u));
|
||||||
|
return handleUpdateIn(u);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleUpdateIn(u: TgUpdate): Promise<void> {
|
||||||
const botUserId = via.getStore()?.userId;
|
const botUserId = via.getStore()?.userId;
|
||||||
if (!(await claimUpdate(db, u.update_id, botUserId))) return;
|
if (!(await claimUpdate(db, u.update_id, botUserId))) return;
|
||||||
try {
|
try {
|
||||||
|
|||||||
@ -1,10 +1,11 @@
|
|||||||
// Stories from a message to the bot (PEP-45): a draft waits for the project/epic buttons, so
|
// Stories from a message to the bot (PEP-45): a draft waits for the project/epic buttons, so
|
||||||
// a stray message never creates a story by itself. Drafts live in `settings` for a day.
|
// a stray message never creates a story by itself. Drafts live in `settings` for a day.
|
||||||
import { deleteSetting, getSetting, setSetting, type Project } from "@peppa/core";
|
import { deleteSetting, getSetting, setSetting, type Project } from "@peppa/core";
|
||||||
|
|
||||||
|
export { splitStory, TITLE_MAX } from "@peppa/core";
|
||||||
import type { Db } from "@peppa/db";
|
import type { Db } from "@peppa/db";
|
||||||
|
|
||||||
export const DRAFT_TTL_MS = 24 * 3600_000;
|
export const DRAFT_TTL_MS = 24 * 3600_000;
|
||||||
export const TITLE_MAX = 120;
|
|
||||||
|
|
||||||
export interface Draft {
|
export interface Draft {
|
||||||
id: number;
|
id: number;
|
||||||
@ -13,6 +14,12 @@ export interface Draft {
|
|||||||
text: string;
|
text: string;
|
||||||
projectId: number | null;
|
projectId: number | null;
|
||||||
voice: boolean;
|
voice: boolean;
|
||||||
|
/** PEP-153: not a story yet — a message the bot answered or asked about («Завести как задачу»). */
|
||||||
|
offer?: boolean;
|
||||||
|
/** PEP-153: the bot asked «Ответить или завести задачу?» and the person has not picked yet. */
|
||||||
|
asked?: boolean;
|
||||||
|
/** PEP-153: the answer at hand for «Ответить» (null — answer from the platform's data). */
|
||||||
|
answer?: string | null;
|
||||||
createdAt: number;
|
createdAt: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -46,29 +53,16 @@ export async function dropDraft(db: Db, id: number): Promise<void> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* "в PAY: экспорт в CSV", "PAY: …", "PAY — …", or (voice, no punctuation) "в PAY экспорт…".
|
* "в PAY: экспорт в CSV", "PAY: …", "PAY — …", or (voice, no punctuation) "в PAY экспорт…" and
|
||||||
|
* "в проекте Pay экспорт…" (how whisper writes it down, PEP-108).
|
||||||
* The key counts only if it is one of the user's projects; otherwise the whole text is the story.
|
* The key counts only if it is one of the user's projects; otherwise the whole text is the story.
|
||||||
*/
|
*/
|
||||||
export function parseStoryText(text: string, projects: Project[]): { project: Project | null; body: string } {
|
export function parseStoryText(text: string, projects: Project[]): { project: Project | null; body: string } {
|
||||||
const t = text.trim();
|
const t = text.trim();
|
||||||
const byKey = (k: string) => projects.find((p) => p.key.toLowerCase() === k.toLowerCase()) ?? null;
|
const byKey = (k: string) => projects.find((p) => p.key.toLowerCase() === k.toLowerCase()) ?? null;
|
||||||
const withSep = /^(?:(?:в|во|для|in|to)\s+)?([A-Za-z][A-Za-z0-9]{1,9})\s*[::—–-]\s*([\s\S]+)$/i.exec(t);
|
const withSep = /^(?:(?:в|во|для|in|to)\s+(?:проекте?\s+|project\s+)?)?([A-Za-z][A-Za-z0-9]{1,9})\s*[::—–-]\s*([\s\S]+)$/i.exec(t);
|
||||||
if (withSep && byKey(withSep[1]!)) return { project: byKey(withSep[1]!), body: withSep[2]!.trim() };
|
if (withSep && byKey(withSep[1]!)) return { project: byKey(withSep[1]!), body: withSep[2]!.trim() };
|
||||||
const spoken = /^(?:в|во|для|in|to)\s+([A-Za-z][A-Za-z0-9]{1,9})[,.]?\s+([\s\S]+)$/i.exec(t);
|
const spoken = /^(?:в|во|для|in|to)\s+(?:проекте?\s+|project\s+)?([A-Za-z][A-Za-z0-9]{1,9})[,.]?\s+([\s\S]+)$/i.exec(t);
|
||||||
if (spoken && byKey(spoken[1]!)) return { project: byKey(spoken[1]!), body: spoken[2]!.trim() };
|
if (spoken && byKey(spoken[1]!)) return { project: byKey(spoken[1]!), body: spoken[2]!.trim() };
|
||||||
return { project: null, body: t };
|
return { project: null, body: t };
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Title (first line, at most TITLE_MAX chars, cut at a word) and the rest as description. */
|
|
||||||
export function splitStory(body: string): { title: string; rest: string } {
|
|
||||||
const [first = "", ...lines] = body.trim().split("\n");
|
|
||||||
let title = first.trim();
|
|
||||||
let rest = lines.join("\n").trim();
|
|
||||||
if (title.length > TITLE_MAX) {
|
|
||||||
const cut = title.lastIndexOf(" ", TITLE_MAX - 1);
|
|
||||||
const at = cut > TITLE_MAX / 2 ? cut : TITLE_MAX - 1;
|
|
||||||
rest = `${title}${rest ? `\n\n${rest}` : ""}`;
|
|
||||||
title = `${title.slice(0, at).trim()}…`;
|
|
||||||
}
|
|
||||||
return { title, rest };
|
|
||||||
}
|
|
||||||
|
|||||||
44
apps/bot/src/feedback.ts
Normal file
44
apps/bot/src/feedback.ts
Normal file
@ -0,0 +1,44 @@
|
|||||||
|
// PEP-143: «Сообщить о проблеме» in the bot. `/problem` opens a short window in which the next
|
||||||
|
// message (text, a photo with a caption, a voice note) becomes a report; photos sent right after
|
||||||
|
// it join the same report. A superadmin's «Не исправлять» waits for the reason the same way.
|
||||||
|
import { deleteSetting, getSetting, setSetting } from "@peppa/core";
|
||||||
|
import type { Db } from "@peppa/db";
|
||||||
|
|
||||||
|
/** How long `/problem` waits for the message. */
|
||||||
|
export const FEEDBACK_MODE_TTL_MS = 15 * 60_000;
|
||||||
|
/** How long after the report more photos still join it (an album arrives message by message). */
|
||||||
|
export const FEEDBACK_MORE_TTL_MS = 2 * 60_000;
|
||||||
|
/** How long «Не исправлять» waits for the reason. */
|
||||||
|
export const REJECT_TTL_MS = 10 * 60_000;
|
||||||
|
|
||||||
|
export interface FeedbackMode {
|
||||||
|
/** Set once the report exists: further photos are attached to it. */
|
||||||
|
feedbackId?: number;
|
||||||
|
until: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
const modeKey = (userId: number) => `bot.feedback:${userId}`;
|
||||||
|
const rejectKey = (userId: number) => `bot.feedback.reject:${userId}`;
|
||||||
|
|
||||||
|
export async function feedbackMode(db: Db, userId: number, now = Date.now()): Promise<FeedbackMode | null> {
|
||||||
|
const m = await getSetting<FeedbackMode>(db, modeKey(userId));
|
||||||
|
if (!m) return null;
|
||||||
|
if (m.until > now) return m;
|
||||||
|
await deleteSetting(db, modeKey(userId));
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const openFeedbackMode = (db: Db, userId: number, now = Date.now()) => setSetting(db, modeKey(userId), { until: now + FEEDBACK_MODE_TTL_MS } satisfies FeedbackMode);
|
||||||
|
export const keepFeedbackMode = (db: Db, userId: number, feedbackId: number, now = Date.now()) => setSetting(db, modeKey(userId), { feedbackId, until: now + FEEDBACK_MORE_TTL_MS } satisfies FeedbackMode);
|
||||||
|
export const closeFeedbackMode = (db: Db, userId: number) => deleteSetting(db, modeKey(userId));
|
||||||
|
|
||||||
|
/** The report a superadmin is about to decline: the next message is the reason. */
|
||||||
|
export async function pendingReject(db: Db, userId: number, now = Date.now()): Promise<number | null> {
|
||||||
|
const r = await getSetting<{ feedbackId: number; until: number }>(db, rejectKey(userId));
|
||||||
|
if (!r) return null;
|
||||||
|
if (r.until > now) return r.feedbackId;
|
||||||
|
await deleteSetting(db, rejectKey(userId));
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
export const askRejectReason = (db: Db, userId: number, feedbackId: number, now = Date.now()) => setSetting(db, rejectKey(userId), { feedbackId, until: now + REJECT_TTL_MS });
|
||||||
|
export const clearReject = (db: Db, userId: number) => deleteSetting(db, rejectKey(userId));
|
||||||
@ -2,7 +2,7 @@
|
|||||||
import { createDb } from "@peppa/db";
|
import { createDb } from "@peppa/db";
|
||||||
import { loadEnv } from "@peppa/shared";
|
import { loadEnv } from "@peppa/shared";
|
||||||
import { setRunnerClient } from "@peppa/runner";
|
import { setRunnerClient } from "@peppa/runner";
|
||||||
import { installCrashReporting } from "@peppa/core";
|
import { installCrashReporting, installServiceLog } from "@peppa/core";
|
||||||
import { createBot } from "./bot.ts";
|
import { createBot } from "./bot.ts";
|
||||||
import { TelegramApi } from "./telegram.ts";
|
import { TelegramApi } from "./telegram.ts";
|
||||||
|
|
||||||
@ -16,6 +16,8 @@ const db = createDb(env.PEPPA_DB);
|
|||||||
setRunnerClient(true, db);
|
setRunnerClient(true, db);
|
||||||
// PEP-91: a crash of the bot goes to Bugsink before launchd restarts it.
|
// PEP-91: a crash of the bot goes to Bugsink before launchd restarts it.
|
||||||
installCrashReporting(db, "bot");
|
installCrashReporting(db, "bot");
|
||||||
|
// PEP-291: the log also goes to $PEPPA_HOME/logs/bot.log — it survives a redeploy.
|
||||||
|
installServiceLog("bot");
|
||||||
const bot = createBot({
|
const bot = createBot({
|
||||||
db,
|
db,
|
||||||
api: new TelegramApi(env.TELEGRAM_BOT_TOKEN, process.env.TELEGRAM_API_URL),
|
api: new TelegramApi(env.TELEGRAM_BOT_TOKEN, process.env.TELEGRAM_API_URL),
|
||||||
|
|||||||
@ -1,79 +1,104 @@
|
|||||||
// Telegram message texts and buttons for PM questions. HTML parse mode.
|
// Telegram message texts and buttons for PM questions. HTML parse mode.
|
||||||
import type { Question, SessionView } from "@peppa/core";
|
import { agentSignature, questionIsFreeText, questionText, questionType, splitForDisplay, stripServiceBlocks, userText, type Question, type SessionView } from "@peppa/core";
|
||||||
import type { InlineButton } from "./telegram.ts";
|
import type { InlineButton } from "./telegram.ts";
|
||||||
|
import { asIs, m as tr } from "@peppa/shared/i18n";
|
||||||
|
|
||||||
export const esc = (s: string) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
export const esc = (s: string) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
||||||
|
const italic = (s: string) => `<i>${s}</i>`;
|
||||||
const clip = (s: string, n: number) => (s.length > n ? `${s.slice(0, n)}…` : s);
|
const clip = (s: string, n: number) => (s.length > n ? `${s.slice(0, n)}…` : s);
|
||||||
|
|
||||||
const KIND: Record<Question["kind"], string> = {
|
const KIND: Record<Question["kind"], string> = {
|
||||||
approval: "📝 Нужно одобрение плана",
|
approval: tr("📝 Нужно одобрение плана"),
|
||||||
question: "❓ Вопрос",
|
question: tr("❓ Вопрос"),
|
||||||
permission: "🔐 Нужно разрешение",
|
permission: tr("🔐 Нужно разрешение"),
|
||||||
attention: "👀 Сообщение от фабрики",
|
attention: tr("👀 Сообщение"),
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** PEP-198: the name the owner sees on every message of the factory. */
|
||||||
|
export const VOICE = tr("🔎 Аналитик");
|
||||||
|
|
||||||
export interface Rendered {
|
export interface Rendered {
|
||||||
text: string;
|
text: string;
|
||||||
buttons: InlineButton[][];
|
buttons: InlineButton[][];
|
||||||
}
|
}
|
||||||
|
|
||||||
// callback_data (≤64 bytes): "q:<questionId>:<choice>", "s:<sessionId>:<action>" or "i:<incidentId>:<decision>" (core/incidents.ts)
|
// callback_data (≤64 bytes): "q:<questionId>:<choice>", "s:<sessionId>:<action>" (resume|stop|ask) or "i:<incidentId>:<decision>" (core/incidents.ts)
|
||||||
export function renderQuestion(
|
export function renderQuestion(
|
||||||
q: Question,
|
q: Question,
|
||||||
ctx: { taskKey: string | null; taskTitle: string | null; taskStatus?: string | null; session: SessionView | null; webUrl: string },
|
ctx: { taskKey: string | null; taskTitle: string | null; taskStatus?: string | null; session: SessionView | null; webUrl: string; /** PEP-154: the reader's view is «Инженер» — the terminal command is shown. */ engineer?: boolean; /** PEP-152: the message has technical details (kept on the site). */ details?: boolean; /** PEP-156: nickname of the agent whose own words these are. */ agent?: string | null },
|
||||||
): Rendered {
|
): Rendered {
|
||||||
const head = [`<b>${esc(ctx.taskKey ?? (q.sessionId ? `Агент №${q.sessionId}` : "Обновления продукта"))}</b>`, ctx.taskTitle ? `<i>${esc(clip(ctx.taskTitle, 80))}</i>` : null]
|
const head = ["<b>" + esc(ctx.taskKey ?? (q.sessionId ? tr("Агент №{id}", { id: q.sessionId }) : tr("Обновления продукта"))) + "</b>", ctx.taskTitle ? `<i>${asIs(esc(clip(ctx.taskTitle, 80)))}</i>` : null]
|
||||||
.filter(Boolean)
|
.filter(Boolean)
|
||||||
.join(" · ");
|
.join(" · ");
|
||||||
const body = esc(clip(q.text, 3300));
|
// PEP-154: no service text in the message (a permission request keeps its command, whole).
|
||||||
const lines = [head, KIND[q.kind], "", body];
|
// PEP-152: the main text only — at most five lines; the rest and the details open on the site.
|
||||||
|
// PEP-139: what the agent wrote itself is free text (marked) — only the factory's phrases are translated.
|
||||||
|
const free = questionIsFreeText(q);
|
||||||
|
const shown = q.kind === "permission" ? { main: q.text, more: null } : splitForDisplay(questionText({ ...q, text: userText(q.text) || q.text }));
|
||||||
|
const text = esc(clip(shown.main, 3300));
|
||||||
|
const said = free ? asIs(text) : text;
|
||||||
|
// PEP-156: «🤖 Шустрик: …» — the agent's own words; the factory's messages carry no name.
|
||||||
|
const body = `${ctx.agent ? `<b>${asIs(esc(agentSignature(ctx.agent)))}</b>: ` : ""}${said}`;
|
||||||
|
const lines = [head, q.kind === "attention" && ctx.agent ? tr("💬 Сообщение агента") : KIND[q.kind], "", body];
|
||||||
|
|
||||||
const buttons: InlineButton[][] = [];
|
const buttons: InlineButton[][] = [];
|
||||||
|
const type = questionType(q, ctx.taskStatus);
|
||||||
if (q.kind === "approval") {
|
if (q.kind === "approval") {
|
||||||
buttons.push([{ text: "✅ Одобрить", callback_data: `q:${q.id}:approve` }]);
|
buttons.push([{ text: tr("✅ Одобрить"), callback_data: `q:${q.id}:approve` }]);
|
||||||
lines.push("", "<i>Чтобы вернуть на доработку — ответьте на это сообщение комментарием.</i>");
|
lines.push("", italic(tr("Чтобы вернуть на доработку — ответьте на это сообщение комментарием.")));
|
||||||
} else if (q.kind === "permission") {
|
} else if (q.kind === "permission") {
|
||||||
buttons.push([
|
buttons.push([
|
||||||
{ text: "✅ Разрешить", callback_data: `q:${q.id}:allow` },
|
{ text: tr("✅ Разрешить"), callback_data: `q:${q.id}:allow` },
|
||||||
{ text: "♾ Всегда", callback_data: `q:${q.id}:always` },
|
{ text: tr("♾ Всегда"), callback_data: `q:${q.id}:always` },
|
||||||
{ text: "⛔ Запретить", callback_data: `q:${q.id}:deny` },
|
{ text: tr("⛔ Запретить"), callback_data: `q:${q.id}:deny` },
|
||||||
]);
|
]);
|
||||||
} else if (q.kind === "question") {
|
} else if (type === "question") {
|
||||||
(q.options ?? []).slice(0, 6).forEach((o, i) => buttons.push([{ text: clip(o, 60), callback_data: `q:${q.id}:o${i}` }]));
|
// PEP-149: a question always comes with answers to tap; the default goes first.
|
||||||
lines.push("", "<i>Выберите вариант или ответьте на это сообщение своим текстом.</i>");
|
(q.options ?? []).slice(0, 6).forEach((o, i) => buttons.push([{ text: free ? asIs(clip(o, 60)) : clip(o, 60), callback_data: `q:${q.id}:o${i}` }]));
|
||||||
} else if (ctx.taskStatus === "review") {
|
if (q.kind === "attention") lines[1] = KIND.question;
|
||||||
lines[1] = "✅ Готово к ревью";
|
lines.push("", italic(tr("Выберите вариант или ответьте на это сообщение своим текстом.")));
|
||||||
buttons.push([{ text: "✅ Принять", callback_data: `q:${q.id}:accept` }]);
|
if (q.defaultOption) lines.push(italic(esc(tr("Если не ответите, агент продолжит по варианту «{option}».", { option: q.defaultOption }))));
|
||||||
lines.push("", "<i>Есть замечания — ответьте на это сообщение, агент доработает.</i>");
|
} else if (type === "done") {
|
||||||
|
lines[1] = tr("✅ Готово к ревью");
|
||||||
|
buttons.push([{ text: tr("✅ Принять"), callback_data: `q:${q.id}:accept` }]);
|
||||||
|
lines.push("", italic(tr("Есть замечания — ответьте на это сообщение, агент доработает.")));
|
||||||
} else {
|
} else {
|
||||||
|
// A message of the factory itself (a failure, a limit): nothing to choose — no «continue» button.
|
||||||
const s = ctx.session;
|
const s = ctx.session;
|
||||||
if (s && ["failed", "rate_limited", "stalled"].includes(s.status)) {
|
if (s && ["failed", "rate_limited", "stalled"].includes(s.status)) {
|
||||||
buttons.push([
|
buttons.push([
|
||||||
{ text: "🔁 Перезапустить", callback_data: `s:${s.id}:resume` },
|
{ text: tr("🔁 Перезапустить"), callback_data: `s:${s.id}:resume` },
|
||||||
{ text: "⏹ Остановить", callback_data: `s:${s.id}:stop` },
|
{ text: tr("⏹ Остановить"), callback_data: `s:${s.id}:stop` },
|
||||||
]);
|
]);
|
||||||
} else {
|
// PEP-186: agents stand on a limit of their subscription — ask the superadmin for one.
|
||||||
buttons.push([{ text: "▶️ Продолжай", callback_data: `q:${q.id}:cont` }]);
|
if (s.status === "rate_limited" && s.subscriptionId != null) buttons.push([{ text: tr("🙋 Попросить подписку у администратора"), callback_data: `s:${s.id}:ask` }]);
|
||||||
lines.push("", "<i>Или ответьте на это сообщение — текст уйдёт агенту.</i>");
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (ctx.session) lines.push(`<code>tmux attach -t ${esc(ctx.session.tmuxName)}</code>`);
|
lines[1] = `${VOICE} · ${lines[1]}`;
|
||||||
|
if (ctx.session && ctx.engineer) lines.push(`<code>tmux attach -t ${esc(ctx.session.tmuxName)}</code>`);
|
||||||
|
const web = ctx.webUrl.replace(/\/$/, "");
|
||||||
|
if ((ctx.details || shown.more) && ctx.taskKey && /^https?:\/\//.test(web)) buttons.push([{ text: tr("Подробнее"), url: `${web}/t/${ctx.taskKey}?more=1` }]);
|
||||||
return { text: lines.join("\n"), buttons };
|
return { text: lines.join("\n"), buttons };
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Text after the question is closed: original + who answered what, no buttons. */
|
/** Text after the question is closed: original + who answered what, no buttons. */
|
||||||
export function renderAnswered(original: string, q: Question): string {
|
export function renderAnswered(original: string, q: Question): string {
|
||||||
const mark = q.answeredVia === "system" ? "⌛" : "✅";
|
const mark = q.answeredVia === "system" ? "⌛" : "✅";
|
||||||
const via = { telegram: "в Telegram", web: "в вебе", terminal: "в терминале", system: "" }[q.answeredVia ?? "telegram"];
|
const via = { telegram: tr("в Telegram"), web: tr("в вебе"), terminal: tr("в терминале"), system: "" }[q.answeredVia ?? "telegram"];
|
||||||
return `${original}\n\n${mark} ${q.answeredVia === "system" ? esc(q.answer ?? "") : `Ответ ${via}: <b>${esc(clip(q.answer ?? "", 500))}</b>`}`;
|
// PEP-154: service blocks are nobody's answer.
|
||||||
|
const answer = stripServiceBlocks(q.answer ?? "");
|
||||||
|
// A person's answer is free text; a button of a factory question (and a system answer) is a phrase.
|
||||||
|
const own = q.answeredVia !== "system" && !(q.options ?? []).includes(q.answer ?? "") ? asIs : (x: string) => x;
|
||||||
|
const said = q.answeredVia === "system" ? esc(answer) : tr("Ответ {via}: <b>{answer}</b>", { via, answer: own(esc(clip(answer, 500))) });
|
||||||
|
return `${original}\n\n${mark} ${said}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The answer text a button stands for. */
|
/** The answer text a button stands for. */
|
||||||
export function choiceToAnswer(q: Question, choice: string): string | null {
|
export function choiceToAnswer(q: Question, choice: string): string | null {
|
||||||
if (q.kind === "approval" && choice === "approve") return "ок";
|
if (q.kind === "approval" && choice === "approve") return "ок"; // i18n-ignore: the answer goes to the agent
|
||||||
if (q.kind === "permission" && ["allow", "always", "deny"].includes(choice)) return choice;
|
if (q.kind === "permission" && ["allow", "always", "deny"].includes(choice)) return choice;
|
||||||
if (q.kind === "attention" && choice === "cont") return "Продолжай.";
|
// PEP-149: the «continue» button is gone — an old one on an earlier message answers nothing.
|
||||||
const m = /^o(\d+)$/.exec(choice);
|
const m = /^o(\d+)$/.exec(choice);
|
||||||
if (q.kind === "question" && m) return q.options?.[Number(m[1])] ?? null;
|
if (m) return q.options?.[Number(m[1])] ?? null;
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,3 +1,4 @@
|
|||||||
|
import { m as tr } from "@peppa/shared/i18n";
|
||||||
// Minimal Telegram Bot API client. The base URL is configurable so tests can point it at
|
// Minimal Telegram Bot API client. The base URL is configurable so tests can point it at
|
||||||
// mock-telegram (packages/testkit).
|
// mock-telegram (packages/testkit).
|
||||||
|
|
||||||
@ -17,6 +18,13 @@ export interface TgMessage {
|
|||||||
/** PEP-45: voice notes and audio files become stories after transcription. */
|
/** PEP-45: voice notes and audio files become stories after transcription. */
|
||||||
voice?: TgFileRef;
|
voice?: TgFileRef;
|
||||||
audio?: TgFileRef;
|
audio?: TgFileRef;
|
||||||
|
/** PEP-143: a photo comes as several sizes (the last is the largest); its text is the caption. */
|
||||||
|
photo?: TgFileRef[];
|
||||||
|
/** An image sent «as a file». */
|
||||||
|
document?: TgFileRef & { file_name?: string };
|
||||||
|
caption?: string;
|
||||||
|
/** Messages of one album share it. */
|
||||||
|
media_group_id?: string;
|
||||||
}
|
}
|
||||||
export interface TgFileRef {
|
export interface TgFileRef {
|
||||||
file_id: string;
|
file_id: string;
|
||||||
@ -41,6 +49,18 @@ export interface InlineButton {
|
|||||||
url?: string;
|
url?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const TG_TEXT_MAX = 4096;
|
||||||
|
const TG_CLIP_NOTE_TEXT = tr("(полностью — на сайте FORGE)");
|
||||||
|
const TG_CLIP_NOTE = "\n\n… " + TG_CLIP_NOTE_TEXT;
|
||||||
|
|
||||||
|
/** PEP-180: a text that fits Telegram — cut at the last line break before the limit. */
|
||||||
|
export function clipForTelegram(text: string): string {
|
||||||
|
if (text.length <= TG_TEXT_MAX) return text;
|
||||||
|
const room = TG_TEXT_MAX - TG_CLIP_NOTE.length;
|
||||||
|
const cut = text.lastIndexOf("\n", room);
|
||||||
|
return `${text.slice(0, cut > room / 2 ? cut : room)}${TG_CLIP_NOTE}`;
|
||||||
|
}
|
||||||
|
|
||||||
export class TelegramError extends Error {
|
export class TelegramError extends Error {
|
||||||
readonly method: string;
|
readonly method: string;
|
||||||
readonly code: number;
|
readonly code: number;
|
||||||
@ -64,6 +84,11 @@ export class TelegramApi {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async call<T>(method: string, params: Record<string, unknown> = {}, timeoutMs = 15_000): Promise<T> {
|
async call<T>(method: string, params: Record<string, unknown> = {}, timeoutMs = 15_000): Promise<T> {
|
||||||
|
// PEP-180: Telegram refuses texts over 4096 characters — a long message goes shortened (cut at a
|
||||||
|
// line break, so no HTML tag is left open), with a note that the whole text is on the site.
|
||||||
|
if ((method === "sendMessage" || method === "editMessageText") && typeof params.text === "string" && params.text.length > TG_TEXT_MAX) {
|
||||||
|
params = { ...params, text: clipForTelegram(params.text) };
|
||||||
|
}
|
||||||
let res: Response;
|
let res: Response;
|
||||||
try {
|
try {
|
||||||
res = await fetch(`${this.baseUrl}/bot${this.token}/${method}`, {
|
res = await fetch(`${this.baseUrl}/bot${this.token}/${method}`, {
|
||||||
@ -118,6 +143,23 @@ export class TelegramApi {
|
|||||||
return Buffer.from(await res.arrayBuffer());
|
return Buffer.from(await res.arrayBuffer());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** PEP-143: a photo uploaded from memory (multipart/form-data, as the Bot API wants for new files). */
|
||||||
|
async sendPhoto(chatId: number, photo: { data: Uint8Array; filename: string; mime: string }, extra: Record<string, unknown> = {}): Promise<TgMessage> {
|
||||||
|
const form = new FormData();
|
||||||
|
form.set("chat_id", String(chatId));
|
||||||
|
for (const [k, v] of Object.entries(extra)) if (v != null && k !== "chat_id") form.set(k, typeof v === "string" ? v : JSON.stringify(v));
|
||||||
|
form.set("photo", new Blob([photo.data as BlobPart], { type: photo.mime }), photo.filename);
|
||||||
|
let res: Response;
|
||||||
|
try {
|
||||||
|
res = await fetch(`${this.baseUrl}/bot${this.token}/sendPhoto`, { method: "POST", body: form, signal: AbortSignal.timeout(60_000) });
|
||||||
|
} catch (e) {
|
||||||
|
throw new TelegramError("sendPhoto", 0, (e as Error).message);
|
||||||
|
}
|
||||||
|
const body = (await res.json().catch(() => ({}))) as { ok?: boolean; result?: TgMessage; description?: string; error_code?: number; parameters?: { retry_after?: number } };
|
||||||
|
if (!body.ok) throw new TelegramError("sendPhoto", body.error_code ?? res.status, body.description ?? res.statusText, body.parameters?.retry_after);
|
||||||
|
return body.result as TgMessage;
|
||||||
|
}
|
||||||
|
|
||||||
sendMessage(chatId: number, text: string, extra: Record<string, unknown> = {}) {
|
sendMessage(chatId: number, text: string, extra: Record<string, unknown> = {}) {
|
||||||
return this.call<TgMessage>("sendMessage", { chat_id: chatId, text, parse_mode: "HTML", ...extra });
|
return this.call<TgMessage>("sendMessage", { chat_id: chatId, text, parse_mode: "HTML", ...extra });
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,52 +0,0 @@
|
|||||||
// Speech to text for voice notes (PEP-45): any OpenAI-compatible audio API —
|
|
||||||
// POST $PEPPA_TRANSCRIBE_URL/audio/transcriptions (multipart: file, model, language,
|
|
||||||
// response_format=json) with "Authorization: Bearer $PEPPA_TRANSCRIBE_KEY" → {"text": "…"}.
|
|
||||||
// OpenAI (https://api.openai.com/v1, whisper-1), Groq (https://api.groq.com/openai/v1,
|
|
||||||
// whisper-large-v3), a local faster-whisper/speaches server — all speak this. Tests use
|
|
||||||
// mock-transcribe (packages/testkit).
|
|
||||||
|
|
||||||
export interface TranscribeConfig {
|
|
||||||
url: string;
|
|
||||||
key: string | null;
|
|
||||||
model: string;
|
|
||||||
language: string | null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** From env; null when voice is not set up (the bot asks for text then). */
|
|
||||||
export function transcribeConfig(env: NodeJS.ProcessEnv = process.env): TranscribeConfig | null {
|
|
||||||
const url = env.PEPPA_TRANSCRIBE_URL?.trim();
|
|
||||||
if (!url) return null;
|
|
||||||
return {
|
|
||||||
url: url.replace(/\/$/, ""),
|
|
||||||
key: env.PEPPA_TRANSCRIBE_KEY?.trim() || null,
|
|
||||||
model: env.PEPPA_TRANSCRIBE_MODEL?.trim() || "whisper-1",
|
|
||||||
language: env.PEPPA_TRANSCRIBE_LANG === "" ? null : (env.PEPPA_TRANSCRIBE_LANG?.trim() || "ru"),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export class TranscribeError extends Error {}
|
|
||||||
|
|
||||||
export async function transcribe(cfg: TranscribeConfig, audio: Buffer, filename = "voice.ogg", mime = "audio/ogg"): Promise<string> {
|
|
||||||
const form = new FormData();
|
|
||||||
form.set("file", new Blob([new Uint8Array(audio)], { type: mime }), filename);
|
|
||||||
form.set("model", cfg.model);
|
|
||||||
form.set("response_format", "json");
|
|
||||||
if (cfg.language) form.set("language", cfg.language);
|
|
||||||
let res: Response;
|
|
||||||
try {
|
|
||||||
res = await fetch(`${cfg.url}/audio/transcriptions`, {
|
|
||||||
method: "POST",
|
|
||||||
headers: cfg.key ? { Authorization: `Bearer ${cfg.key}` } : {},
|
|
||||||
body: form,
|
|
||||||
signal: AbortSignal.timeout(120_000),
|
|
||||||
});
|
|
||||||
} catch (e) {
|
|
||||||
throw new TranscribeError(`сервис расшифровки недоступен: ${(e as Error).message}`);
|
|
||||||
}
|
|
||||||
const body = (await res.json().catch(() => ({}))) as { text?: string; error?: { message?: string } | string };
|
|
||||||
if (!res.ok) {
|
|
||||||
const msg = typeof body.error === "string" ? body.error : body.error?.message;
|
|
||||||
throw new TranscribeError(`расшифровка не удалась: ${res.status}${msg ? ` ${msg}` : ""}`);
|
|
||||||
}
|
|
||||||
return (body.text ?? "").trim();
|
|
||||||
}
|
|
||||||
7
apps/observer/bin/peppa-observer
Executable file
7
apps/observer/bin/peppa-observer
Executable file
@ -0,0 +1,7 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Logical root (PEP-18): only the bin's own symlink (~/.local/bin) is followed, so a launch
|
||||||
|
# through ~/peppa/current keeps that path in hooks and git config instead of the release dir.
|
||||||
|
_b="$0"; [ -L "$_b" ] && { _l="$(readlink "$_b")"; if [ "${_l#/}" != "$_l" ]; then _b="$_l"; else _b="$(dirname "$_b")/$_l"; fi; }
|
||||||
|
PEPPA_ROOT="$(cd "$(dirname "$_b")/../../.." && pwd)"; unset _b _l
|
||||||
|
. "$PEPPA_ROOT/scripts/lib/load-env.sh"
|
||||||
|
exec "${PEPPA_NODE:-node}" --import "$PEPPA_ROOT/scripts/lib/require-node.mjs" "$PEPPA_ROOT/apps/observer/src/index.ts" "$@"
|
||||||
14
apps/observer/package.json
Normal file
14
apps/observer/package.json
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
{
|
||||||
|
"name": "@peppa/observer",
|
||||||
|
"version": "0.0.0",
|
||||||
|
"private": true,
|
||||||
|
"type": "module",
|
||||||
|
"exports": { ".": "./src/observer.ts" },
|
||||||
|
"bin": { "peppa-observer": "./bin/peppa-observer" },
|
||||||
|
"scripts": { "start": "node src/index.ts", "typecheck": "tsc -p ." },
|
||||||
|
"dependencies": {
|
||||||
|
"@peppa/core": "workspace:*",
|
||||||
|
"@peppa/db": "workspace:*",
|
||||||
|
"@peppa/shared": "workspace:*"
|
||||||
|
}
|
||||||
|
}
|
||||||
15
apps/observer/src/index.ts
Normal file
15
apps/observer/src/index.ts
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
// Entry point: `peppa-observer` (launchd agent quest.telecom.peppa.observer), PEP-202.
|
||||||
|
import { createDb } from "@peppa/db";
|
||||||
|
import { loadEnv } from "@peppa/shared";
|
||||||
|
import { installCrashReporting, installServiceLog, setDefaultActor } from "@peppa/core";
|
||||||
|
import { runObserver } from "./observer.ts";
|
||||||
|
|
||||||
|
const env = loadEnv();
|
||||||
|
const db = createDb(env.PEPPA_DB);
|
||||||
|
setDefaultActor({ kind: "system" });
|
||||||
|
installCrashReporting(db, "observer");
|
||||||
|
// PEP-291: the log also goes to $PEPPA_HOME/logs/observer.log — it survives a redeploy.
|
||||||
|
installServiceLog("observer");
|
||||||
|
const ac = new AbortController();
|
||||||
|
for (const sig of ["SIGINT", "SIGTERM"] as const) process.on(sig, () => (ac.abort(), setTimeout(() => process.exit(0), 200)));
|
||||||
|
await runObserver(db, { log: (m) => console.log(`${new Date().toISOString()} ${m}`) }, ac.signal);
|
||||||
59
apps/observer/src/observer.ts
Normal file
59
apps/observer/src/observer.ts
Normal file
@ -0,0 +1,59 @@
|
|||||||
|
// PEP-202: the `peppa-observer` service — runs the monitors of Observability. Every second it
|
||||||
|
// starts the checks that are due (they run in the background, each with its own timeout), every
|
||||||
|
// 30 s it writes its heartbeat (the watchdog watches it like the bot and the web), every hour it
|
||||||
|
// deletes checks older than the retention (7 days). Monitors are rows in observe.db: the web and
|
||||||
|
// MCP change them, the service picks the change up on its next pass — no restart.
|
||||||
|
import { beat, featureTick, observeTick, pruneObserve, seedFeatureMonitors, seedMonitors, vitalsAlertTick, type ObserveProbes } from "@peppa/core";
|
||||||
|
import { loadEnv } from "@peppa/shared";
|
||||||
|
import type { Db } from "@peppa/db";
|
||||||
|
|
||||||
|
export interface ObserverOptions {
|
||||||
|
log?: (m: string) => void;
|
||||||
|
tickMs?: number;
|
||||||
|
probes?: ObserveProbes;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function runObserver(db: Db, o: ObserverOptions = {}, signal?: AbortSignal): Promise<void> {
|
||||||
|
const log = o.log ?? (() => {});
|
||||||
|
const made = seedMonitors();
|
||||||
|
if (made.length) log(`observer: built-in monitors created: ${made.map((m) => m.name).join(", ")}`);
|
||||||
|
// PEP-224: MCP monitors switch the «mcp» feature off; created once, when the web has a public address.
|
||||||
|
const mcp = seedFeatureMonitors(loadEnv().PEPPA_WEB_URL);
|
||||||
|
if (mcp.length) log(`observer: built-in monitors created: ${mcp.map((m) => m.name).join(", ")}`);
|
||||||
|
let featuresBusy = false;
|
||||||
|
log("observer started");
|
||||||
|
let lastBeat = 0;
|
||||||
|
let lastPrune = 0;
|
||||||
|
let lastVitals = 0;
|
||||||
|
while (!signal?.aborted) {
|
||||||
|
const now = Date.now();
|
||||||
|
if (now - lastBeat >= 30_000) {
|
||||||
|
lastBeat = now;
|
||||||
|
await beat(db, "observer").catch((e: Error) => log(`observer: heartbeat failed: ${e.message}`));
|
||||||
|
}
|
||||||
|
if (now - lastPrune >= 3_600_000) {
|
||||||
|
lastPrune = now;
|
||||||
|
try {
|
||||||
|
const n = pruneObserve();
|
||||||
|
if (n) log(`observer: ${n} old checks deleted`);
|
||||||
|
} catch (e) {
|
||||||
|
log(`observer: prune failed: ${(e as Error).message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// PEP-217: slow pages (p75 of real users) → one warning per route and day in Bugsink.
|
||||||
|
if (now - lastVitals >= 600_000) {
|
||||||
|
lastVitals = now;
|
||||||
|
void vitalsAlertTick(db).catch((e: Error) => log(`observer: vitals failed: ${e.message}`));
|
||||||
|
}
|
||||||
|
// Not awaited: a slow check must not hold the others or the heartbeat.
|
||||||
|
void observeTick(db, { log, probes: o.probes }).catch((e: Error) => log(`observer: tick failed: ${e.message}`));
|
||||||
|
// PEP-224: features follow their monitors — announce a change (journal, channel, live pages).
|
||||||
|
if (!featuresBusy) {
|
||||||
|
featuresBusy = true;
|
||||||
|
void featureTick(db, { log })
|
||||||
|
.catch((e: Error) => log(`observer: features failed: ${e.message}`))
|
||||||
|
.finally(() => (featuresBusy = false));
|
||||||
|
}
|
||||||
|
await new Promise((r) => setTimeout(r, o.tickMs ?? 1_000));
|
||||||
|
}
|
||||||
|
}
|
||||||
1
apps/observer/tsconfig.json
Normal file
1
apps/observer/tsconfig.json
Normal file
@ -0,0 +1 @@
|
|||||||
|
{ "extends": "../../tsconfig.base.json", "compilerOptions": { "allowImportingTsExtensions": true }, "include": ["src"] }
|
||||||
@ -15,7 +15,6 @@ import {
|
|||||||
resolveTask,
|
resolveTask,
|
||||||
revokeApp,
|
revokeApp,
|
||||||
createPairingCode,
|
createPairingCode,
|
||||||
getSetting,
|
|
||||||
unpairTelegram,
|
unpairTelegram,
|
||||||
getIncident,
|
getIncident,
|
||||||
getProject as getProjectByKey,
|
getProject as getProjectByKey,
|
||||||
@ -27,7 +26,11 @@ import {
|
|||||||
type IncidentPolicy,
|
type IncidentPolicy,
|
||||||
getUser,
|
getUser,
|
||||||
isSuperadmin,
|
isSuperadmin,
|
||||||
|
getDirectOrigins,
|
||||||
|
setDirectOrigins,
|
||||||
setUserDisabled,
|
setUserDisabled,
|
||||||
|
setSuperadmin,
|
||||||
|
mergeAccounts,
|
||||||
NOTIFY_EVENTS,
|
NOTIFY_EVENTS,
|
||||||
defaultPrefs,
|
defaultPrefs,
|
||||||
deletePushSubscription,
|
deletePushSubscription,
|
||||||
@ -48,10 +51,15 @@ import {
|
|||||||
setTaskAgentSettings,
|
setTaskAgentSettings,
|
||||||
cleanBudget,
|
cleanBudget,
|
||||||
logEvent,
|
logEvent,
|
||||||
|
setPublishMode,
|
||||||
|
type PublishMode,
|
||||||
setProjectBudget,
|
setProjectBudget,
|
||||||
setTaskBudget,
|
setTaskBudget,
|
||||||
type Budget,
|
type Budget,
|
||||||
setProjectSecret,
|
setProjectSecret,
|
||||||
|
setSecretAudience,
|
||||||
|
secretToConnection,
|
||||||
|
setAgentSecretsEnabled,
|
||||||
setNeedDone,
|
setNeedDone,
|
||||||
removeNeed,
|
removeNeed,
|
||||||
deleteProjectSecret,
|
deleteProjectSecret,
|
||||||
@ -61,13 +69,18 @@ import {
|
|||||||
checkGiteaBotToken,
|
checkGiteaBotToken,
|
||||||
setUiMode,
|
setUiMode,
|
||||||
} from "@peppa/core";
|
} from "@peppa/core";
|
||||||
|
import { checkConnection, createConnection, decideIdleGrant, deleteConnection, DEFAULT_GRANT_TERM, extendGrant, grantConnection, isGatewayProtocol, isGrantTerm, replaceConnectionSecret, resetHostKey, revokeConnection, revokeGrant, setConnectionIdleHours, type CatalogAuth, type ConnectionCheckResult, type GrantMode, type GrantTerm } from "@peppa/core";
|
||||||
|
import { attachmentLabel, fixFeedback, linkAttachments, linkFeedback, parseAttachmentIds, rejectFeedback, restoreProject } from "@peppa/core";
|
||||||
|
import { deleteProject, decideProposals, mergeProposals, connectAndGrantAccessRequest, denyAccessRequestAndTell, grantAccessRequestFromExisting, decideDeferred } from "@peppa/runner";
|
||||||
import { bugsinkFromEnv } from "@peppa/bugsink";
|
import { bugsinkFromEnv } from "@peppa/bugsink";
|
||||||
import { loadEnv } from "@peppa/shared";
|
import { loadEnv } from "@peppa/shared";
|
||||||
import { acceptStory, budgetChanged, resolveTaskById, deployProd, bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, grantRepoAccess, moveTask, provisionProject, projectNamespace, setProjectVisibility, shareProject, unshareProject, type BoardColumn, resumeSession, sendToSession, startSession, stopSession, type Provider, startFreeRunner, renameRunner, promoteRunner, queueTaskOnRunner, managesProject, saveAgentsMd, cancelOwnLogin, finishOwnClaudeLogin, connectOwnSubscription, removeOwnSubscription, type OwnSubscriptionKind, chooseSharedSubscription } from "@peppa/runner";
|
import { pauseProject, resumeProject, acceptAll, acceptStory, autoPublish, fixStory, confirmTaskDecision, changeTaskDecision, undoSplit, budgetChanged, resolveTaskById, deployProd, bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, grantRepoAccess, moveTask, provisionProjectOnce, projectNamespace, setProjectVisibility, shareProject, unshareProject, type BoardColumn, resumeSession, sendToSession, syncSessionAttachments, startSession, stopSession, type Provider, startFreeRunner, renameRunner, promoteRunner, queueTaskOnRunner, managesProject, saveAgentsMd, cancelOwnLogin, finishOwnClaudeLogin, connectOwnSubscription, removeOwnSubscription, type OwnSubscriptionKind, chooseSharedSubscription, requestSubscription } from "@peppa/runner";
|
||||||
import { revalidatePath } from "next/cache";
|
import { revalidatePath } from "next/cache";
|
||||||
import { redirect } from "next/navigation";
|
import { redirect } from "next/navigation";
|
||||||
import { asWebActor, requireUser, words } from "@/lib/auth";
|
import { asWebActor, requireUser, words } from "@/lib/auth";
|
||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
|
import { getT } from "@/lib/i18n";
|
||||||
|
import { m, PRODUCT_NAME } from "@peppa/shared/i18n";
|
||||||
|
|
||||||
const str = (f: FormData, k: string) => String(f.get(k) ?? "").trim();
|
const str = (f: FormData, k: string) => String(f.get(k) ?? "").trim();
|
||||||
const back = (f: FormData) => str(f, "back") || "/";
|
const back = (f: FormData) => str(f, "back") || "/";
|
||||||
@ -78,7 +91,9 @@ async function attempt(f: FormData, fn: () => Promise<string | void>): Promise<n
|
|||||||
try {
|
try {
|
||||||
target = (await fn()) || target;
|
target = (await fn()) || target;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
const msg = e instanceof PeppaError ? e.message : `Ошибка: ${(e as Error).message}`;
|
const t = await getT();
|
||||||
|
// PEP-98: core errors are rendered Russian text — translate them for the reader.
|
||||||
|
const msg = e instanceof PeppaError ? t.text(e.message) : t("Ошибка: {message}", { message: (e as Error).message });
|
||||||
const [path, query] = target.split("?");
|
const [path, query] = target.split("?");
|
||||||
const params = new URLSearchParams(query);
|
const params = new URLSearchParams(query);
|
||||||
params.set("error", msg.slice(0, 300));
|
params.set("error", msg.slice(0, 300));
|
||||||
@ -106,8 +121,8 @@ export async function answerQuestion(f: FormData) {
|
|||||||
const q = await getQuestion(db, Number(str(f, "questionId")));
|
const q = await getQuestion(db, Number(str(f, "questionId")));
|
||||||
await projectForUser(db, user.id, q.projectId);
|
await projectForUser(db, user.id, q.projectId);
|
||||||
const answer = str(f, "choice") || str(f, "answer");
|
const answer = str(f, "choice") || str(f, "answer");
|
||||||
if (!answer) throw new PeppaError("Пустой ответ");
|
if (!answer) throw new PeppaError(m("Пустой ответ"));
|
||||||
if (q.answeredAt) throw new PeppaError(`Уже отвечено${q.answeredVia === "system" ? "" : ` (${q.answeredVia})`}: ${q.answer}`);
|
if (q.answeredAt) throw new PeppaError(q.answeredVia === "system" ? m("Уже отвечено: {answer}", { answer: q.answer }) : m("Уже отвечено ({via}): {answer}", { via: q.answeredVia, answer: q.answer }));
|
||||||
if (answer === "__accept") {
|
if (answer === "__accept") {
|
||||||
await acceptTask(db, q.id, "web");
|
await acceptTask(db, q.id, "web");
|
||||||
return;
|
return;
|
||||||
@ -120,9 +135,11 @@ export async function addTask(f: FormData) {
|
|||||||
const user = asWebActor(await requireUser());
|
const user = asWebActor(await requireUser());
|
||||||
await attempt(f, async () => {
|
await attempt(f, async () => {
|
||||||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||||||
if (!str(f, "title")) throw new PeppaError("Нужно название задачи");
|
if (!str(f, "title")) throw new PeppaError(m("Нужно название задачи"));
|
||||||
const epic = Number(str(f, "epicId")) || undefined;
|
const epic = Number(str(f, "epicId")) || undefined;
|
||||||
|
const ids = parseAttachmentIds(f.getAll("attachment"));
|
||||||
const ref = await createTask(db, { projectId: p.id, title: str(f, "title"), description: str(f, "description") || undefined, goalId: epic });
|
const ref = await createTask(db, { projectId: p.id, title: str(f, "title"), description: str(f, "description") || undefined, goalId: epic });
|
||||||
|
await linkAttachments(db, user, p.id, ids, { taskId: ref.task.id });
|
||||||
return `/t/${ref.key}`;
|
return `/t/${ref.key}`;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@ -132,7 +149,7 @@ export async function addEpic(f: FormData) {
|
|||||||
const user = asWebActor(await requireUser());
|
const user = asWebActor(await requireUser());
|
||||||
await attempt(f, async () => {
|
await attempt(f, async () => {
|
||||||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||||||
if (str(f, "title").length < 2) throw new PeppaError("Нужно название эпика");
|
if (str(f, "title").length < 2) throw new PeppaError(m("Нужно название эпика"));
|
||||||
await createEpic(db, p.id, str(f, "title"), str(f, "description") || undefined);
|
await createEpic(db, p.id, str(f, "title"), str(f, "description") || undefined);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@ -146,7 +163,7 @@ export async function editEpic(f: FormData) {
|
|||||||
await updateEpic(db, p.id, id, { status: "archived" });
|
await updateEpic(db, p.id, id, { status: "archived" });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (str(f, "title").length < 2) throw new PeppaError("Нужно название эпика");
|
if (str(f, "title").length < 2) throw new PeppaError(m("Нужно название эпика"));
|
||||||
await updateEpic(db, p.id, id, { title: str(f, "title"), description: str(f, "description") || null });
|
await updateEpic(db, p.id, id, { title: str(f, "title"), description: str(f, "description") || null });
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@ -158,7 +175,7 @@ export async function editStoryAction(f: FormData) {
|
|||||||
const ref = await resolveTask(db, str(f, "taskKey"));
|
const ref = await resolveTask(db, str(f, "taskKey"));
|
||||||
await projectForUser(db, user.id, ref.project.id);
|
await projectForUser(db, user.id, ref.project.id);
|
||||||
const title = str(f, "title");
|
const title = str(f, "title");
|
||||||
if (title.length < 2) throw new PeppaError("Нужно название задачи");
|
if (title.length < 2) throw new PeppaError(m("Нужно название задачи"));
|
||||||
const epic = str(f, "epicId");
|
const epic = str(f, "epicId");
|
||||||
await updateTask(db, ref, { title, description: String(f.get("description") ?? "").trim(), goalId: epic ? Number(epic) : null }, undefined, user.login);
|
await updateTask(db, ref, { title, description: String(f.get("description") ?? "").trim(), goalId: epic ? Number(epic) : null }, undefined, user.login);
|
||||||
});
|
});
|
||||||
@ -170,11 +187,15 @@ export async function commentStoryAction(f: FormData) {
|
|||||||
await attempt(f, async () => {
|
await attempt(f, async () => {
|
||||||
const ref = await resolveTask(db, str(f, "taskKey"));
|
const ref = await resolveTask(db, str(f, "taskKey"));
|
||||||
await projectForUser(db, user.id, ref.project.id);
|
await projectForUser(db, user.id, ref.project.id);
|
||||||
const c = await addStoryComment(db, ref, user, String(f.get("text") ?? ""));
|
const ids = parseAttachmentIds(f.getAll("attachment"));
|
||||||
|
const body = String(f.get("text") ?? "").trim() || (await attachmentLabel(db, ids));
|
||||||
|
const c = await addStoryComment(db, ref, user, body);
|
||||||
|
await linkAttachments(db, user, ref.project.id, ids, { taskId: ref.task.id, eventId: c.id });
|
||||||
if (str(f, "toAgent")) {
|
if (str(f, "toAgent")) {
|
||||||
const [live] = await listSessions(db, { active: true, taskId: ref.task.id });
|
const [live] = await listSessions(db, { active: true, taskId: ref.task.id });
|
||||||
if (!live) throw new PeppaError("Комментарий сохранён, но агент сейчас не работает — увидит его, когда вернётся к задаче");
|
if (!live) throw new PeppaError(m("Комментарий сохранён, но агент сейчас не работает — увидит его, когда вернётся к задаче"));
|
||||||
await sendToSession(db, live.id, `Комментарий PM (${user.login}) к ${ref.key}:\n${c.text}`);
|
// i18n-ignore — text for the agent
|
||||||
|
await sendToSession(db, live.id, `Комментарий PM (${user.login}) к ${ref.key}:\n${c.text}${await syncSessionAttachments(db, live.id)}`, { person: true });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@ -189,11 +210,58 @@ export async function acceptStoryAction(f: FormData) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PEP-209: «Принять» / «Принять всё» on the acceptance page — one by one, a failure of one doesn't
|
||||||
|
* stop the others; the page shows the result («Принято 6, на доработке 1…»).
|
||||||
|
*/
|
||||||
|
export async function acceptAllAction(f: FormData) {
|
||||||
|
const user = asWebActor(await requireUser());
|
||||||
|
const key = str(f, "project");
|
||||||
|
const base = `/p/${encodeURIComponent(key)}/accept`;
|
||||||
|
await attempt(f, async () => {
|
||||||
|
const refs = [];
|
||||||
|
for (const k of f.getAll("taskKey").map(String)) {
|
||||||
|
const ref = await resolveTask(db, k).catch(() => null);
|
||||||
|
if (!ref || ref.project.key !== key) continue;
|
||||||
|
await projectForUser(db, user.id, ref.project.id);
|
||||||
|
if (ref.task.status === "review") refs.push(ref);
|
||||||
|
}
|
||||||
|
if (!refs.length) throw new PeppaError(m("Принимать нечего: задачи уже приняты или вернулись в работу"));
|
||||||
|
const r = await acceptAll(db, refs, "web");
|
||||||
|
return `${base}?ok=${r.accepted.length}&pending=${r.pending.length}&failed=${r.failed.length}`;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** «Поправить» on the story page in «Продакт» mode (PEP-120): the remark goes to the agent, the story — back to work. */
|
||||||
|
export async function fixStoryAction(f: FormData) {
|
||||||
|
const user = asWebActor(await requireUser());
|
||||||
|
await attempt(f, async () => {
|
||||||
|
const ref = await resolveTask(db, str(f, "taskKey"));
|
||||||
|
await projectForUser(db, user.id, ref.project.id);
|
||||||
|
await fixStory(db, ref, user, String(f.get("text") ?? ""));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** PEP-198: «Подходит» / «Нужно иначе» / «Не делить» on a decision of «Фабрика решила за вас». */
|
||||||
|
export async function decisionAction(f: FormData) {
|
||||||
|
const user = asWebActor(await requireUser());
|
||||||
|
await attempt(f, async () => {
|
||||||
|
const ref = await resolveTask(db, str(f, "taskKey"));
|
||||||
|
await projectForUser(db, user.id, ref.project.id);
|
||||||
|
const id = Number(str(f, "id"));
|
||||||
|
const choice = str(f, "choice");
|
||||||
|
if (choice === "confirm") await confirmTaskDecision(db, ref, id, user);
|
||||||
|
else if (choice === "unsplit") await undoSplit(db, ref, id, user);
|
||||||
|
else if (choice === "change") await changeTaskDecision(db, ref, id, String(f.get("how") ?? ""), user);
|
||||||
|
else throw new PeppaError(m("Эта кнопка уже не работает. Обновите страницу."));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
/** PEP-67: a superadmin may pick a pool or tick subscriptions; otherwise the project's pool. */
|
/** PEP-67: a superadmin may pick a pool or tick subscriptions; otherwise the project's pool. */
|
||||||
async function launchChoice(f: FormData, user: Awaited<ReturnType<typeof requireUser>>) {
|
async function launchChoice(f: FormData, user: Awaited<ReturnType<typeof requireUser>>) {
|
||||||
const choice = (await isSuperadmin(db, user)) ? str(f, "choice") : "";
|
const choice = (await isSuperadmin(db, user)) ? str(f, "choice") : "";
|
||||||
const subscriptionIds = choice === "pick" ? f.getAll("subscription").map(Number).filter((n) => n > 0) : undefined;
|
const subscriptionIds = choice === "pick" ? f.getAll("subscription").map(Number).filter((n) => n > 0) : undefined;
|
||||||
if (choice === "pick" && !subscriptionIds?.length) throw new PeppaError("Отметьте хотя бы одну подписку");
|
if (choice === "pick" && !subscriptionIds?.length) throw new PeppaError(m("Отметьте хотя бы одну подписку"));
|
||||||
const poolId = choice.startsWith("pool:") ? Number(choice.slice(5)) : undefined;
|
const poolId = choice.startsWith("pool:") ? Number(choice.slice(5)) : undefined;
|
||||||
const provider = str(f, "provider") as Provider | "";
|
const provider = str(f, "provider") as Provider | "";
|
||||||
return { provider: provider || undefined, subscriptionIds, poolId };
|
return { provider: provider || undefined, subscriptionIds, poolId };
|
||||||
@ -309,21 +377,22 @@ export async function messageSession(f: FormData) {
|
|||||||
const user = asWebActor(await requireUser());
|
const user = asWebActor(await requireUser());
|
||||||
await attempt(f, async () => {
|
await attempt(f, async () => {
|
||||||
const s = await ownedSession(user.id, Number(str(f, "sessionId")));
|
const s = await ownedSession(user.id, Number(str(f, "sessionId")));
|
||||||
if (!str(f, "text")) throw new PeppaError("Пустое сообщение");
|
if (!str(f, "text")) throw new PeppaError(m("Пустое сообщение"));
|
||||||
await sendToSession(db, s.id, str(f, "text"));
|
await sendToSession(db, s.id, str(f, "text"), { person: true });
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function createProjectAction(f: FormData) {
|
export async function createProjectAction(f: FormData) {
|
||||||
const user = asWebActor(await requireUser());
|
const user = asWebActor(await requireUser());
|
||||||
await attempt(f, async () => {
|
await attempt(f, async () => {
|
||||||
const p = await provisionProject(db, {
|
// PEP-142: the same form sent twice (a second click, another tab) opens the one project.
|
||||||
|
const p = await provisionProjectOnce(db, {
|
||||||
...(await projectNamespace(db, user, str(f, "owner"))), // PEP-68: local user → peppa-bot
|
...(await projectNamespace(db, user, str(f, "owner"))), // PEP-68: local user → peppa-bot
|
||||||
slug: str(f, "slug").toLowerCase(),
|
slug: str(f, "slug").toLowerCase(),
|
||||||
key: str(f, "key"),
|
key: str(f, "key"),
|
||||||
name: str(f, "name"),
|
name: str(f, "name"),
|
||||||
existing: str(f, "mode") === "existing",
|
existing: str(f, "mode") === "existing",
|
||||||
visibility: str(f, "visibility") === "private" ? "private" : "public",
|
visibility: str(f, "visibility") === "public" ? "public" : "private", // PEP-280: closed unless chosen
|
||||||
ownerId: user.id,
|
ownerId: user.id,
|
||||||
});
|
});
|
||||||
return `/p/${p.key}?created=1`;
|
return `/p/${p.key}?created=1`;
|
||||||
@ -338,13 +407,43 @@ export async function deployProdAction(f: FormData) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** PEP-145: «Показывать всем: сам / по кнопке» (owner or member). */
|
||||||
|
export async function setPublishModeAction(f: FormData) {
|
||||||
|
const user = asWebActor(await requireUser());
|
||||||
|
await attempt(f, async () => {
|
||||||
|
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||||||
|
const mode = await setPublishMode(db, p.id, str(f, "mode") as PublishMode);
|
||||||
|
await logEvent(db, { projectId: p.id, type: "publish_mode_set", payload: { mode, login: user.login } });
|
||||||
|
// «Сам» chosen with an accepted version waiting: it goes to everyone right away.
|
||||||
|
if (mode === "auto") await autoPublish(db, p).catch(() => false);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** PEP-174: «Поставить на паузу» — owner, member or superadmin. Agents stop, nothing is sent. */
|
||||||
|
export async function pauseProjectAction(f: FormData) {
|
||||||
|
const user = asWebActor(await requireUser());
|
||||||
|
await attempt(f, async () => {
|
||||||
|
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||||||
|
await pauseProject(db, p.id, user.id);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** PEP-174: «Продолжить» — the agents stopped by the pause continue, the dispatcher takes stories again. */
|
||||||
|
export async function resumeProjectAction(f: FormData) {
|
||||||
|
const user = asWebActor(await requireUser());
|
||||||
|
await attempt(f, async () => {
|
||||||
|
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||||||
|
await resumeProject(db, p.id);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
export async function moveTaskCard(f: FormData) {
|
export async function moveTaskCard(f: FormData) {
|
||||||
const user = asWebActor(await requireUser());
|
const user = asWebActor(await requireUser());
|
||||||
await attempt(f, async () => {
|
await attempt(f, async () => {
|
||||||
const ref = await resolveTask(db, str(f, "taskKey"));
|
const ref = await resolveTask(db, str(f, "taskKey"));
|
||||||
await projectForUser(db, user.id, ref.project.id);
|
await projectForUser(db, user.id, ref.project.id);
|
||||||
const to = str(f, "to") as BoardColumn;
|
const to = str(f, "to") as BoardColumn;
|
||||||
if (!["backlog", "in_progress", "review", "done"].includes(to)) throw new PeppaError("Неизвестная колонка");
|
if (!["backlog", "in_progress", "review", "done"].includes(to)) throw new PeppaError(m("Неизвестная колонка"));
|
||||||
await moveTask(db, ref, to);
|
await moveTask(db, ref, to);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@ -362,7 +461,7 @@ export async function addProjectMember(f: FormData) {
|
|||||||
await attempt(f, async () => {
|
await attempt(f, async () => {
|
||||||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||||||
const r = await shareProject(db, user, p, str(f, "login"));
|
const r = await shareProject(db, user, p, str(f, "login"));
|
||||||
if (!r.repoAccess) throw new PeppaError((await words()).engineer ? `${r.login} добавлен, но доступ к репозиторию в Gitea выдать не удалось — добавьте соавтора в Gitea вручную` : `${r.login} добавлен, но доступ к коду проекта выдать не удалось. Напишите в поддержку Peppa FACTORY.`);
|
if (!r.repoAccess) throw new PeppaError((await words()).engineer ? m("{login} добавлен, но доступ к репозиторию в Gitea выдать не удалось — добавьте соавтора в Gitea вручную", { login: r.login }) : m("{login} добавлен, но доступ к коду проекта выдать не удалось. Напишите в поддержку FORGE.", { login: r.login }));
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -371,7 +470,24 @@ export async function grantRepoAccessToMembers(f: FormData) {
|
|||||||
await attempt(f, async () => {
|
await attempt(f, async () => {
|
||||||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||||||
const r = await grantRepoAccess(db, user, p);
|
const r = await grantRepoAccess(db, user, p);
|
||||||
if (r.failed.length) throw new PeppaError(`Не удалось выдать доступ к репозиторию: ${r.failed.join(", ")} — нет прав администратора в Gitea, добавьте соавторов вручную`);
|
if (r.failed.length) throw new PeppaError(m("Не удалось выдать доступ к репозиторию: {logins} — нет прав администратора в Gitea, добавьте соавторов вручную", { logins: r.failed.join(", ") }));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** PEP-163: the owner deletes the project; it stays with the superadmin for a week. */
|
||||||
|
export async function deleteProjectAction(f: FormData) {
|
||||||
|
const user = asWebActor(await requireUser());
|
||||||
|
await attempt(f, async () => {
|
||||||
|
if (str(f, "confirm") !== "yes") throw new PeppaError(m("Отметьте, что хотите удалить проект"));
|
||||||
|
await deleteProject(db, user.id, Number(str(f, "projectId")));
|
||||||
|
return "/projects";
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function restoreProjectAction(f: FormData) {
|
||||||
|
const user = asWebActor(await requireUser());
|
||||||
|
await attempt(f, async () => {
|
||||||
|
await restoreProject(db, Number(str(f, "projectId")), user.id);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -402,6 +518,7 @@ export async function setAutonomyAction(f: FormData) {
|
|||||||
merge: str(f, "merge") as AutonomySettings["merge"],
|
merge: str(f, "merge") as AutonomySettings["merge"],
|
||||||
close: str(f, "close") as AutonomySettings["close"],
|
close: str(f, "close") as AutonomySettings["close"],
|
||||||
closeAfterHours: Number(str(f, "closeAfterHours")),
|
closeAfterHours: Number(str(f, "closeAfterHours")),
|
||||||
|
acceptOwn: (str(f, "acceptOwn") || undefined) as AutonomySettings["acceptOwn"],
|
||||||
idlePush: f.get("idlePush") === "on",
|
idlePush: f.get("idlePush") === "on",
|
||||||
idlePushHours: Number(str(f, "idlePushHours")),
|
idlePushHours: Number(str(f, "idlePushHours")),
|
||||||
quietFrom: quiet ? hour("quietFrom") : null,
|
quietFrom: quiet ? hour("quietFrom") : null,
|
||||||
@ -410,6 +527,41 @@ export async function setAutonomyAction(f: FormData) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** PEP-197: «Делать» / «Не надо» on a suggested story (board, chat). */
|
||||||
|
export async function proposalAction(f: FormData) {
|
||||||
|
const user = asWebActor(await requireUser());
|
||||||
|
await attempt(f, async () => {
|
||||||
|
const choice = str(f, "choice");
|
||||||
|
// PEP-209: «Объединить в одну» — the ticked proposals become one story.
|
||||||
|
if (choice === "merge") {
|
||||||
|
await mergeProposals(db, user, f.getAll("pick").map(Number).filter((n) => Number.isInteger(n) && n > 0));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (choice !== "do" && choice !== "no" && choice !== "important" && choice !== "none") throw new PeppaError(m("Эта кнопка уже не работает."));
|
||||||
|
const ids = str(f, "ids").split(",").map(Number).filter((n) => Number.isInteger(n) && n > 0);
|
||||||
|
await decideProposals(db, user, ids, choice);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** PEP-302: «Делать» / «Не надо» at a finding put aside until the weekly digest. */
|
||||||
|
export async function deferredAction(f: FormData) {
|
||||||
|
const user = asWebActor(await requireUser());
|
||||||
|
await attempt(f, async () => {
|
||||||
|
const choice = str(f, "choice");
|
||||||
|
if (choice !== "do" && choice !== "no") throw new PeppaError(m("Эта кнопка уже не работает."));
|
||||||
|
await decideDeferred(db, user, Number(str(f, "projectId")), str(f, "title"), choice);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** PEP-197: «Принимать сами» — whose stories are accepted without the owner. */
|
||||||
|
export async function setAcceptOwnAction(f: FormData) {
|
||||||
|
const user = asWebActor(await requireUser());
|
||||||
|
await attempt(f, async () => {
|
||||||
|
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||||||
|
await setAutonomy(db, p.id, { acceptOwn: str(f, "acceptOwn") as AutonomySettings["acceptOwn"] });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
export async function removeProjectMember(f: FormData) {
|
export async function removeProjectMember(f: FormData) {
|
||||||
const user = asWebActor(await requireUser());
|
const user = asWebActor(await requireUser());
|
||||||
await attempt(f, async () => {
|
await attempt(f, async () => {
|
||||||
@ -427,8 +579,9 @@ export async function pairingLinkAction(): Promise<{ url?: string; error?: strin
|
|||||||
const token = loadEnv().TELEGRAM_BOT_TOKEN;
|
const token = loadEnv().TELEGRAM_BOT_TOKEN;
|
||||||
// Every user has their own bot: no pairing link through the shared one.
|
// Every user has their own bot: no pairing link through the shared one.
|
||||||
const username = user.telegramBotUsername;
|
const username = user.telegramBotUsername;
|
||||||
if (!username) return { error: "Сначала подключите своего бота (шаги 1–2)" };
|
const t = await getT();
|
||||||
if (!token) return { error: "Telegram сейчас недоступен. Попробуйте через минуту." };
|
if (!username) return { error: t("Сначала подключите своего бота (шаги 1–2)") };
|
||||||
|
if (!token) return { error: t("Telegram сейчас недоступен. Попробуйте через минуту.") };
|
||||||
return { url: `https://t.me/${username}?start=${await createPairingCode(db, token, user.id)}` };
|
return { url: `https://t.me/${username}?start=${await createPairingCode(db, token, user.id)}` };
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -438,8 +591,8 @@ export async function pairTelegram(f: FormData) {
|
|||||||
const token = loadEnv().TELEGRAM_BOT_TOKEN;
|
const token = loadEnv().TELEGRAM_BOT_TOKEN;
|
||||||
// Every user has their own bot (PEP-85/100): the platform's bot is never offered to users.
|
// Every user has their own bot (PEP-85/100): the platform's bot is never offered to users.
|
||||||
const username = user.telegramBotUsername;
|
const username = user.telegramBotUsername;
|
||||||
if (!username) throw new PeppaError("Сначала подключите своего Telegram-бота");
|
if (!username) throw new PeppaError(m("Сначала подключите своего Telegram-бота"));
|
||||||
if (!token) throw new PeppaError("Telegram сейчас недоступен. Попробуйте через минуту.");
|
if (!token) throw new PeppaError(m("Telegram сейчас недоступен. Попробуйте через минуту."));
|
||||||
return `https://t.me/${username}?start=${await createPairingCode(db, token, user.id)}`;
|
return `https://t.me/${username}?start=${await createPairingCode(db, token, user.id)}`;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@ -478,7 +631,7 @@ export async function saveNotifyPrefsAction(f: FormData) {
|
|||||||
const events = { ...d.events };
|
const events = { ...d.events };
|
||||||
for (const e of NOTIFY_EVENTS) events[e] = { telegram: f.get(`${e}.telegram`) === "on", push: f.get(`${e}.push`) === "on" };
|
for (const e of NOTIFY_EVENTS) events[e] = { telegram: f.get(`${e}.telegram`) === "on", push: f.get(`${e}.push`) === "on" };
|
||||||
const tz = str(f, "timezone") || cur.timezone;
|
const tz = str(f, "timezone") || cur.timezone;
|
||||||
if (!isValidTimezone(tz)) throw new PeppaError(`Неизвестная таймзона: ${tz}`);
|
if (!isValidTimezone(tz)) throw new PeppaError(m("Неизвестная таймзона: {tz}", { tz }));
|
||||||
const shown = f.getAll("projectShown").map(Number);
|
const shown = f.getAll("projectShown").map(Number);
|
||||||
const enabled = new Set(f.getAll("project").map(Number));
|
const enabled = new Set(f.getAll("project").map(Number));
|
||||||
// Projects not on the form (no access any more) keep their old state.
|
// Projects not on the form (no access any more) keep their old state.
|
||||||
@ -518,9 +671,10 @@ export async function deletePushSubscriptionAction(endpoint: string) {
|
|||||||
export async function testPushAction(endpoint: string): Promise<{ ok: boolean; error?: string }> {
|
export async function testPushAction(endpoint: string): Promise<{ ok: boolean; error?: string }> {
|
||||||
const user = asWebActor(await requireUser());
|
const user = asWebActor(await requireUser());
|
||||||
const sub = (await userPushSubscriptions(db, user.id)).find((s) => s.endpoint === endpoint);
|
const sub = (await userPushSubscriptions(db, user.id)).find((s) => s.endpoint === endpoint);
|
||||||
if (!sub) return { ok: false, error: "Этот браузер не подписан" };
|
const t = await getT();
|
||||||
|
if (!sub) return { ok: false, error: t("Этот браузер не подписан") };
|
||||||
const prefs = await getNotifyPrefs(db, user.id);
|
const prefs = await getNotifyPrefs(db, user.id);
|
||||||
const r = await sendWebPush(db, sub, { title: "Peppa FACTORY", body: "Уведомления в этом браузере работают ✅", url: "/settings#notifications", tag: "test", sound: prefs.sound });
|
const r = await sendWebPush(db, sub, { title: PRODUCT_NAME, body: t("Уведомления в этом браузере работают ✅"), url: "/settings#notifications", tag: "test", sound: prefs.sound });
|
||||||
if (r.ok) return { ok: true };
|
if (r.ok) return { ok: true };
|
||||||
if (r.gone) await deletePushSubscription(db, user.id, endpoint);
|
if (r.gone) await deletePushSubscription(db, user.id, endpoint);
|
||||||
return { ok: false, error: r.error };
|
return { ok: false, error: r.error };
|
||||||
@ -531,7 +685,7 @@ export async function testPushAction(endpoint: string): Promise<{ ok: boolean; e
|
|||||||
async function incidentInProject(userId: number, f: FormData) {
|
async function incidentInProject(userId: number, f: FormData) {
|
||||||
const p = await projectForUser(db, userId, Number(str(f, "projectId")));
|
const p = await projectForUser(db, userId, Number(str(f, "projectId")));
|
||||||
const i = await getIncident(db, Number(str(f, "incidentId")));
|
const i = await getIncident(db, Number(str(f, "incidentId")));
|
||||||
if (i.projectId !== p.id) throw new PeppaError("Не найдено");
|
if (i.projectId !== p.id) throw new PeppaError(m("Не найдено"));
|
||||||
return i;
|
return i;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -539,11 +693,22 @@ export async function connectErrorTrackingAction(f: FormData) {
|
|||||||
const user = asWebActor(await requireUser());
|
const user = asWebActor(await requireUser());
|
||||||
await attempt(f, async () => {
|
await attempt(f, async () => {
|
||||||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||||||
if (!(await managesProject(db, user, p))) throw new PeppaError("Подключает владелец проекта");
|
if (!(await managesProject(db, user, p))) throw new PeppaError(m("Подключает владелец проекта"));
|
||||||
await connectErrorTracking(db, p, bugsinkFromEnv(), bugsinkWebhookBase());
|
await connectErrorTracking(db, p, bugsinkFromEnv(), bugsinkWebhookBase());
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** PEP-295: the owner's exception — errors of the product go to work without «Делать». */
|
||||||
|
export async function setDirectIncidentsAction(f: FormData) {
|
||||||
|
const user = asWebActor(await requireUser());
|
||||||
|
await attempt(f, async () => {
|
||||||
|
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||||||
|
if (p.ownerId !== user.id && !(await isSuperadmin(db, user))) throw new PeppaError(m("Это решает владелец проекта."));
|
||||||
|
const rest = (await getDirectOrigins(db, p.id)).filter((o) => o !== "incident");
|
||||||
|
await setDirectOrigins(db, p.id, str(f, "on") === "yes" ? [...rest, "incident"] : rest);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
export async function saveIncidentSettings(f: FormData) {
|
export async function saveIncidentSettings(f: FormData) {
|
||||||
const user = asWebActor(await requireUser());
|
const user = asWebActor(await requireUser());
|
||||||
await attempt(f, async () => {
|
await attempt(f, async () => {
|
||||||
@ -577,7 +742,7 @@ export async function decideIncidentAction(f: FormData) {
|
|||||||
await attempt(f, async () => {
|
await attempt(f, async () => {
|
||||||
const i = await incidentInProject(user.id, f);
|
const i = await incidentInProject(user.id, f);
|
||||||
const action = str(f, "action");
|
const action = str(f, "action");
|
||||||
if (action !== "backlog" && action !== "start" && action !== "ignore") throw new PeppaError("Неизвестное решение");
|
if (action !== "backlog" && action !== "start" && action !== "ignore") throw new PeppaError(m("Неизвестное решение"));
|
||||||
await decideIncident(db, i.id, action, user.login);
|
await decideIncident(db, i.id, action, user.login);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@ -595,7 +760,7 @@ export async function resolveIncidentAction(f: FormData) {
|
|||||||
/** Superadmin-only actions: everybody else gets "not found", nothing changes. */
|
/** Superadmin-only actions: everybody else gets "not found", nothing changes. */
|
||||||
async function requireSuperadmin() {
|
async function requireSuperadmin() {
|
||||||
const user = asWebActor(await requireUser());
|
const user = asWebActor(await requireUser());
|
||||||
if (!(await isSuperadmin(db, user))) throw new PeppaError("Не найдено");
|
if (!(await isSuperadmin(db, user))) throw new PeppaError(m("Не найдено"));
|
||||||
return user;
|
return user;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -605,12 +770,30 @@ export async function setUserDisabledAction(f: FormData) {
|
|||||||
await attempt(f, async () => {
|
await attempt(f, async () => {
|
||||||
const admin = await requireSuperadmin();
|
const admin = await requireSuperadmin();
|
||||||
const u = await getUser(db, Number(str(f, "userId")));
|
const u = await getUser(db, Number(str(f, "userId")));
|
||||||
if (!u) throw new PeppaError("Не найдено");
|
if (!u) throw new PeppaError(m("Не найдено"));
|
||||||
if (u.id === admin.id) throw new PeppaError("Нельзя отключить самого себя");
|
if (u.id === admin.id) throw new PeppaError(m("Нельзя отключить самого себя"));
|
||||||
await setUserDisabled(db, u.id, str(f, "disabled") === "1");
|
await setUserDisabled(db, u.id, str(f, "disabled") === "1");
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** PEP-226: appoint or remove a superadmin from «Пользователи». */
|
||||||
|
export async function setSuperadminAction(f: FormData) {
|
||||||
|
await attempt(f, async () => {
|
||||||
|
const admin = asWebActor(await requireSuperadmin());
|
||||||
|
await setSuperadmin(db, admin, Number(str(f, "userId")), str(f, "on") === "1");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** PEP-204: merge an old account into the person's main one, after the confirmation screen. */
|
||||||
|
export async function mergeAccountsAction(f: FormData) {
|
||||||
|
await attempt(f, async () => {
|
||||||
|
// The actor is set in this frame: set inside requireSuperadmin it would not reach the journal entry.
|
||||||
|
const admin = asWebActor(await requireSuperadmin());
|
||||||
|
await mergeAccounts(db, admin, Number(str(f, "from")), Number(str(f, "to")), { confirm: str(f, "confirm") === "1", confirmAdmin: str(f, "confirmAdmin") === "1" });
|
||||||
|
return "/users";
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
// ── PEP-43: budgets ────────────────────────────────────────────────────────────────
|
// ── PEP-43: budgets ────────────────────────────────────────────────────────────────
|
||||||
const budgetFrom = (f: FormData): Budget => cleanBudget(Object.fromEntries(["minutes", "tokens", "restarts", "costUsd"].map((k) => [k, Number(str(f, k)) || null])));
|
const budgetFrom = (f: FormData): Budget => cleanBudget(Object.fromEntries(["minutes", "tokens", "restarts", "costUsd"].map((k) => [k, Number(str(f, k)) || null])));
|
||||||
@ -623,7 +806,7 @@ export async function saveTaskBudgetAction(f: FormData) {
|
|||||||
const mode = str(f, "mode");
|
const mode = str(f, "mode");
|
||||||
const budget = mode === "inherit" ? null : mode === "unlimited" ? {} : budgetFrom(f);
|
const budget = mode === "inherit" ? null : mode === "unlimited" ? {} : budgetFrom(f);
|
||||||
await setTaskBudget(db, ref.task.id, budget);
|
await setTaskBudget(db, ref.task.id, budget);
|
||||||
await logEvent(db, { projectId: ref.project.id, taskId: ref.task.id, type: "budget_changed", payload: { budget: budget ?? "проекта" } });
|
await logEvent(db, { projectId: ref.project.id, taskId: ref.task.id, type: "budget_changed", payload: { budget: budget ?? "проекта" } }); // i18n-ignore — stored value
|
||||||
await budgetChanged(db, ref.task.id);
|
await budgetChanged(db, ref.task.id);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@ -644,7 +827,32 @@ export async function saveProjectSecretAction(f: FormData) {
|
|||||||
const user = asWebActor(await requireUser());
|
const user = asWebActor(await requireUser());
|
||||||
await attempt(f, async () => {
|
await attempt(f, async () => {
|
||||||
// The value is taken as is (no trim): keys may legitimately end with spaces/newlines.
|
// The value is taken as is (no trim): keys may legitimately end with spaces/newlines.
|
||||||
await setProjectSecret(db, user.id, Number(str(f, "projectId")), str(f, "name"), String(f.get("value") ?? ""));
|
// PEP-253: «Кому» — only the product by default.
|
||||||
|
await setProjectSecret(db, user.id, Number(str(f, "projectId")), str(f, "name"), String(f.get("value") ?? ""), { agent: str(f, "audience") === "agent" });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// PEP-253: «только продукту» ⇄ «агенту и продукту».
|
||||||
|
export async function setSecretAudienceAction(f: FormData) {
|
||||||
|
const user = asWebActor(await requireUser());
|
||||||
|
await attempt(f, async () => {
|
||||||
|
await setSecretAudience(db, user.id, Number(str(f, "projectId")), str(f, "name"), str(f, "audience") === "agent");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// PEP-253: «Сделать подключением» — a catalog connection with the secret's key, granted to the project.
|
||||||
|
export async function secretToConnectionAction(f: FormData) {
|
||||||
|
const user = asWebActor(await requireUser());
|
||||||
|
await attempt(f, async () => {
|
||||||
|
await secretToConnection(db, user.id, Number(str(f, "projectId")), str(f, "name"));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// PEP-253: «Агенты получают секреты в окружение».
|
||||||
|
export async function setAgentSecretsAction(f: FormData) {
|
||||||
|
const user = asWebActor(await requireUser());
|
||||||
|
await attempt(f, async () => {
|
||||||
|
await setAgentSecretsEnabled(db, user.id, Number(str(f, "projectId")), str(f, "on") === "1");
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -722,11 +930,19 @@ export async function chooseSharedSubscriptionAction(f: FormData) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** PEP-186: «Попросить подписку у администратора». */
|
||||||
|
export async function requestSubscriptionAction(f: FormData) {
|
||||||
|
const user = asWebActor(await requireUser());
|
||||||
|
await attempt(f, async () => {
|
||||||
|
await requestSubscription(db, user, await projectForUser(db, user.id, Number(str(f, "projectId"))), new Date(), { ahead: str(f, "ahead") === "1" });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
export async function connectOwnSubscriptionAction(f: FormData) {
|
export async function connectOwnSubscriptionAction(f: FormData) {
|
||||||
const user = asWebActor(await requireUser());
|
const user = asWebActor(await requireUser());
|
||||||
await attempt(f, async () => {
|
await attempt(f, async () => {
|
||||||
const kind = str(f, "kind") as OwnSubscriptionKind;
|
const kind = str(f, "kind") as OwnSubscriptionKind;
|
||||||
if (!["claude_login", "claude", "codex_login", "codex_key", "existing"].includes(kind)) throw new PeppaError("Выберите, что подключить");
|
if (!["claude_login", "claude", "codex_login", "codex_key", "existing"].includes(kind)) throw new PeppaError(m("Выберите, что подключить"));
|
||||||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||||||
await connectOwnSubscription(db, user, p, kind, String(f.get("secret") ?? ""));
|
await connectOwnSubscription(db, user, p, kind, String(f.get("secret") ?? ""));
|
||||||
});
|
});
|
||||||
@ -737,7 +953,7 @@ export async function finishOwnClaudeLoginAction(f: FormData) {
|
|||||||
const user = asWebActor(await requireUser());
|
const user = asWebActor(await requireUser());
|
||||||
await attempt(f, async () => {
|
await attempt(f, async () => {
|
||||||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||||||
await finishOwnClaudeLogin(db, user, p, Number(str(f, "subscriptionId")), str(f, "code"));
|
await finishOwnClaudeLogin(db, user, p, Number(str(f, "subscriptionId")), str(f, "code"), str(f, "account"));
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -763,7 +979,7 @@ export async function saveIntakeSettingsAction(f: FormData) {
|
|||||||
const user = asWebActor(await requireUser());
|
const user = asWebActor(await requireUser());
|
||||||
await attempt(f, async () => {
|
await attempt(f, async () => {
|
||||||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||||||
await setIntakeSettings(db, p.id, { enabled: f.get("enabled") === "on", waitMin: Number(str(f, "waitMin") || 30) });
|
await setIntakeSettings(db, p.id, { enabled: f.get("enabled") === "on" });
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -784,3 +1000,186 @@ export async function disconnectOwnBotAction(f: FormData) {
|
|||||||
return str(f, "back") === "/" ? "/" : "/settings#telegram";
|
return str(f, "back") === "/" ? "/" : "/settings#telegram";
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// ── PEP-143: users' reports about Peppa — the superadmin decides ─────────────────────
|
||||||
|
export async function fixFeedbackAction(f: FormData) {
|
||||||
|
const user = asWebActor(await requireUser());
|
||||||
|
await attempt(f, async () => {
|
||||||
|
await fixFeedback(db, user, Number(str(f, "feedbackId")), Number(str(f, "option")));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function linkFeedbackAction(f: FormData) {
|
||||||
|
const user = asWebActor(await requireUser());
|
||||||
|
await attempt(f, async () => {
|
||||||
|
await linkFeedback(db, user, Number(str(f, "feedbackId")), str(f, "task") || null);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function rejectFeedbackAction(f: FormData) {
|
||||||
|
const user = asWebActor(await requireUser());
|
||||||
|
await attempt(f, async () => {
|
||||||
|
await rejectFeedback(db, user, Number(str(f, "feedbackId")), str(f, "reason") || null);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// PEP-234 Access Hub: the user's own connections. Every core function checks the owner itself.
|
||||||
|
// PEP-249: catalog cards, a key check right after saving, read / write modes.
|
||||||
|
const checkWord = (r: ConnectionCheckResult | null) => (!r ? "down" : r.reachableOnly ? "reachable" : r.status);
|
||||||
|
const AUTH_KINDS: CatalogAuth[] = ["bearer", "header", "query", "basic"];
|
||||||
|
|
||||||
|
// PEP-251: the form fields of a database / server / storage / mailbox (never the secret).
|
||||||
|
const PROTOCOL_FIELDS = ["host", "port", "database", "user", "tls", "root", "hostKey", "endpoint", "region", "bucket", "prefix", "accessKeyId", "imapHost", "imapPort", "smtpHost", "smtpPort", "from"];
|
||||||
|
|
||||||
|
export async function createConnectionAction(f: FormData) {
|
||||||
|
const user = asWebActor(await requireUser());
|
||||||
|
await attempt(f, async () => {
|
||||||
|
const protocol = str(f, "protocol");
|
||||||
|
if (isGatewayProtocol(protocol)) {
|
||||||
|
const config = Object.fromEntries(PROTOCOL_FIELDS.filter((k) => f.has(k)).map((k) => [k, str(f, k)]));
|
||||||
|
// An SSH key keeps its line breaks; a password is one line.
|
||||||
|
const raw = String(f.get("secret") ?? "");
|
||||||
|
const secret = protocol === "ssh" && raw.includes("-----BEGIN") ? `${raw.replace(/\r\n/g, "\n").trim()}\n` : raw.trim();
|
||||||
|
const c = await createConnection(db, user.id, { protocol, name: str(f, "name"), config, secret });
|
||||||
|
const r = await checkConnection(db, user.id, c.id).catch(() => null);
|
||||||
|
return `/connections?created=${c.id}&check=${checkWord(r)}#c${c.id}`;
|
||||||
|
}
|
||||||
|
const kind = str(f, "authKind") as CatalogAuth;
|
||||||
|
const c = await createConnection(db, user.id, {
|
||||||
|
catalogId: str(f, "catalogId") || null,
|
||||||
|
name: str(f, "name"),
|
||||||
|
baseUrl: str(f, "baseUrl"),
|
||||||
|
secret: String(f.get("secret") ?? "").trim(),
|
||||||
|
authKind: AUTH_KINDS.includes(kind) ? kind : "bearer",
|
||||||
|
authHeader: str(f, "authHeader") || null,
|
||||||
|
});
|
||||||
|
const r = await checkConnection(db, user.id, c.id).catch(() => null);
|
||||||
|
return `/connections?created=${c.id}&check=${checkWord(r)}#c${c.id}`;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function checkConnectionAction(f: FormData) {
|
||||||
|
const user = asWebActor(await requireUser());
|
||||||
|
await attempt(f, async () => {
|
||||||
|
const id = Number(str(f, "connectionId"));
|
||||||
|
const r = await checkConnection(db, user.id, id);
|
||||||
|
return `/connections?checked=${id}&check=${checkWord(r)}#c${id}`;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function replaceConnectionSecretAction(f: FormData) {
|
||||||
|
const user = asWebActor(await requireUser());
|
||||||
|
await attempt(f, async () => {
|
||||||
|
const id = Number(str(f, "connectionId"));
|
||||||
|
const raw = String(f.get("secret") ?? "");
|
||||||
|
await replaceConnectionSecret(db, user.id, id, raw.includes("-----BEGIN") ? `${raw.replace(/\r\n/g, "\n").trim()}\n` : raw.trim());
|
||||||
|
const r = await checkConnection(db, user.id, id).catch(() => null);
|
||||||
|
return `/connections?checked=${id}&check=${checkWord(r)}#c${id}`;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function resetHostKeyAction(f: FormData) {
|
||||||
|
const user = asWebActor(await requireUser());
|
||||||
|
await attempt(f, async () => {
|
||||||
|
const id = Number(str(f, "connectionId"));
|
||||||
|
await resetHostKey(db, user.id, id);
|
||||||
|
const r = await checkConnection(db, user.id, id).catch(() => null);
|
||||||
|
return `/connections?checked=${id}&check=${checkWord(r)}#c${id}`;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function revokeConnectionAction(f: FormData) {
|
||||||
|
const user = asWebActor(await requireUser());
|
||||||
|
await attempt(f, async () => {
|
||||||
|
const id = Number(str(f, "connectionId"));
|
||||||
|
const r = await revokeConnection(db, user.id, id);
|
||||||
|
// PEP-252: the service didn't confirm the revoke of a sign-in — tell the owner to do it there too.
|
||||||
|
if (r.remote === "failed") return `/connections?revoked=${id}&remote=failed#c${id}`;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function deleteConnectionAction(f: FormData) {
|
||||||
|
const user = asWebActor(await requireUser());
|
||||||
|
await attempt(f, async () => {
|
||||||
|
await deleteConnection(db, user.id, Number(str(f, "connectionId")));
|
||||||
|
return "/connections";
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function grantConnectionAction(f: FormData) {
|
||||||
|
const user = asWebActor(await requireUser());
|
||||||
|
await attempt(f, async () => {
|
||||||
|
const agent = str(f, "agentId");
|
||||||
|
const mode = (k: string): GrantMode => (["auto", "ask"].includes(str(f, k)) ? (str(f, k) as GrantMode) : "off");
|
||||||
|
await grantConnection(db, user.id, Number(str(f, "connectionId")), { projectId: Number(str(f, "projectId")), agentId: agent ? Number(agent) : null, readMode: mode("readMode"), writeMode: mode("writeMode"), operations: String(f.get("operations") ?? ""), term: isGrantTerm(str(f, "term")) ? (str(f, "term") as GrantTerm) : DEFAULT_GRANT_TERM });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** PEP-259 «Продлить»: the same term again from now. */
|
||||||
|
export async function extendGrantAction(f: FormData) {
|
||||||
|
const user = asWebActor(await requireUser());
|
||||||
|
await attempt(f, async () => {
|
||||||
|
await extendGrant(db, user.id, Number(str(f, "grantId")));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** PEP-259: the owner's answer to «агенты давно не пользуются — снять?»: «Снять» / «Оставить». */
|
||||||
|
export async function decideIdleGrantAction(f: FormData) {
|
||||||
|
const user = asWebActor(await requireUser());
|
||||||
|
await attempt(f, async () => {
|
||||||
|
await decideIdleGrant(db, user.id, Number(str(f, "grantId")), str(f, "decision") === "revoke" ? "revoke" : "keep");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** PEP-259: «Спрашивать о разрешении без дела через …» of one connection ("" — platform default). */
|
||||||
|
export async function setConnectionIdleAction(f: FormData) {
|
||||||
|
const user = asWebActor(await requireUser());
|
||||||
|
await attempt(f, async () => {
|
||||||
|
const v = str(f, "idleHours");
|
||||||
|
await setConnectionIdleHours(db, user.id, Number(str(f, "connectionId")), v === "" ? null : Number(v));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// PEP-250: an agent's access request — only its project's owner decides (core checks).
|
||||||
|
export async function connectAccessRequestAction(f: FormData) {
|
||||||
|
const user = asWebActor(await requireUser());
|
||||||
|
await attempt(f, async () => {
|
||||||
|
const id = Number(str(f, "requestId"));
|
||||||
|
const kind = str(f, "authKind") as CatalogAuth;
|
||||||
|
const { connection } = await connectAndGrantAccessRequest(db, user.id, id, {
|
||||||
|
name: str(f, "name"),
|
||||||
|
baseUrl: str(f, "baseUrl") || undefined,
|
||||||
|
secret: String(f.get("secret") ?? "").trim(),
|
||||||
|
authKind: AUTH_KINDS.includes(kind) ? kind : "bearer",
|
||||||
|
authHeader: str(f, "authHeader") || null,
|
||||||
|
});
|
||||||
|
const r = await checkConnection(db, user.id, connection.id).catch(() => null);
|
||||||
|
return `/connections/requests/${id}?done=granted&check=${checkWord(r)}`;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function grantAccessRequestAction(f: FormData) {
|
||||||
|
const user = asWebActor(await requireUser());
|
||||||
|
await attempt(f, async () => {
|
||||||
|
const id = Number(str(f, "requestId"));
|
||||||
|
await grantAccessRequestFromExisting(db, user.id, id, Number(str(f, "connectionId")));
|
||||||
|
return `/connections/requests/${id}?done=granted`;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function denyAccessRequestAction(f: FormData) {
|
||||||
|
const user = asWebActor(await requireUser());
|
||||||
|
await attempt(f, async () => {
|
||||||
|
const id = Number(str(f, "requestId"));
|
||||||
|
await denyAccessRequestAndTell(db, user.id, id, str(f, "reason") || null);
|
||||||
|
return `/connections/requests/${id}?done=denied`;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function revokeGrantAction(f: FormData) {
|
||||||
|
const user = asWebActor(await requireUser());
|
||||||
|
await attempt(f, async () => {
|
||||||
|
await revokeGrant(db, user.id, Number(str(f, "grantId")));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|||||||
@ -8,6 +8,7 @@ import { revalidatePath } from "next/cache";
|
|||||||
import { redirect } from "next/navigation";
|
import { redirect } from "next/navigation";
|
||||||
import { requireUser } from "@/lib/auth";
|
import { requireUser } from "@/lib/auth";
|
||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
|
import { m } from "@peppa/shared/i18n";
|
||||||
|
|
||||||
const str = (f: FormData, k: string) => String(f.get(k) ?? "").trim();
|
const str = (f: FormData, k: string) => String(f.get(k) ?? "").trim();
|
||||||
|
|
||||||
@ -16,7 +17,7 @@ async function attempt(f: FormData, fn: () => Promise<string | void>): Promise<n
|
|||||||
try {
|
try {
|
||||||
target = (await fn()) || target;
|
target = (await fn()) || target;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
const msg = e instanceof PeppaError ? e.message : `Ошибка: ${(e as Error).message}`;
|
const msg = e instanceof PeppaError ? e.message : m("Ошибка: {message}", { message: (e as Error).message });
|
||||||
const [path, query] = target.split("?");
|
const [path, query] = target.split("?");
|
||||||
const params = new URLSearchParams(query);
|
const params = new URLSearchParams(query);
|
||||||
params.set("error", msg.slice(0, 300));
|
params.set("error", msg.slice(0, 300));
|
||||||
@ -40,7 +41,7 @@ export async function reorderTaskCard(f: FormData) {
|
|||||||
const to = str(f, "to");
|
const to = str(f, "to");
|
||||||
if (to === "top" || to === "bottom") await reorderBoardTask(db, ref, { to });
|
if (to === "top" || to === "bottom") await reorderBoardTask(db, ref, { to });
|
||||||
else if (to === "before" || to === "after") await reorderBoardTask(db, ref, { to, other: await ownedTask(user.id, str(f, "other")) });
|
else if (to === "before" || to === "after") await reorderBoardTask(db, ref, { to, other: await ownedTask(user.id, str(f, "other")) });
|
||||||
else throw new PeppaError("Неизвестное место");
|
else throw new PeppaError(m("Неизвестное место"));
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -84,7 +85,7 @@ export async function planEpicAction(f: FormData) {
|
|||||||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||||||
const epic = await getEpic(db, p.id, Number(str(f, "epicId")));
|
const epic = await getEpic(db, p.id, Number(str(f, "epicId")));
|
||||||
const r = await planEpic(db, p, epic.id, { wishes: str(f, "wishes") || null, by: user.login });
|
const r = await planEpic(db, p, epic.id, { wishes: str(f, "wishes") || null, by: user.login });
|
||||||
if (!r.ok) throw new PeppaError(`Планировщик: ${r.error}`);
|
if (!r.ok) throw new PeppaError(m("Планировщик: {error}", { error: r.error }));
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -97,12 +98,12 @@ export async function applyPlanAction(f: FormData) {
|
|||||||
// Plan numbers in the form refer to the full draft; renumber them for the kept stories.
|
// Plan numbers in the form refer to the full draft; renumber them for the kept stories.
|
||||||
const kept: number[] = [];
|
const kept: number[] = [];
|
||||||
for (let i = 1; i <= n; i++) if (f.get(`keep_${i}`)) kept.push(i);
|
for (let i = 1; i <= n; i++) if (f.get(`keep_${i}`)) kept.push(i);
|
||||||
if (!kept.length) throw new PeppaError("Не выбрано ни одной задачи. Отметьте хотя бы одну.");
|
if (!kept.length) throw new PeppaError(m("Не выбрано ни одной задачи. Отметьте хотя бы одну."));
|
||||||
const renum = new Map(kept.map((orig, i) => [orig, i + 1]));
|
const renum = new Map(kept.map((orig, i) => [orig, i + 1]));
|
||||||
const stories: PlannedStory[] = kept.map((i) => {
|
const stories: PlannedStory[] = kept.map((i) => {
|
||||||
const deps = parseDepsInput(str(f, `deps_${i}`)).map((d): PlanDep => {
|
const deps = parseDepsInput(str(f, `deps_${i}`)).map((d): PlanDep => {
|
||||||
if (typeof d !== "number") return d;
|
if (typeof d !== "number") return d;
|
||||||
if (!renum.has(d)) throw new PeppaError(`Задача ${i} зависит от №${d}, которую вы сняли. Уберите зависимость или оставьте задачу.`);
|
if (!renum.has(d)) throw new PeppaError(m("Задача {i} зависит от №{d}, которую вы сняли. Уберите зависимость или оставьте задачу.", { i, d }));
|
||||||
return renum.get(d)!;
|
return renum.get(d)!;
|
||||||
});
|
});
|
||||||
return { title: str(f, `title_${i}`), description: str(f, `description_${i}`), dependsOn: deps };
|
return { title: str(f, `title_${i}`), description: str(f, `description_${i}`), dependsOn: deps };
|
||||||
|
|||||||
@ -1,34 +1,57 @@
|
|||||||
import Link from "next/link";
|
import Link from "@/components/Link";
|
||||||
import { notFound } from "next/navigation";
|
import { notFound } from "next/navigation";
|
||||||
import { Bot, Hash, Link2, MessagesSquare, Send, Unlink, User as UserIcon } from "lucide-react";
|
import { ArrowLeft, Bot, Link2, MessagesSquare, Send, Unlink, User as UserIcon } from "lucide-react";
|
||||||
import { analystPending, isSuperadmin, chatGroupBotName, chatMessagesView, chatThreads, chatTtlMs, discussionMessages, discussionUnread, getSetting, listChats, markDiscussionRead, masterFeed, syncChats, threadTitle, THREAD_KEY, type ChatMessageView, type Question } from "@peppa/core";
|
import { ANALYST_NAME, analystPending, attachmentsByMessage, chatStatusLine, isSuperadmin, chatGroupBotName, chatMessagesView, chatTtlMs, discussionMessages, discussionUnread, getSetting, listChats, markDiscussionRead, markThreadRead, masterFeed, projectThreadList, splitForDisplay, syncChats, threadTitle, THREAD_KEY, type AttachmentView, type ChatMessageView, type Question } from "@peppa/core";
|
||||||
import { projects, questions, tasks } from "@peppa/db";
|
import { projects, questions, tasks } from "@peppa/db";
|
||||||
import { formatTaskKey } from "@peppa/shared";
|
import { formatTaskKey } from "@peppa/shared";
|
||||||
|
import { PRODUCT_NAME, stripAsIs } from "@peppa/shared/i18n";
|
||||||
import { eq, inArray } from "drizzle-orm";
|
import { eq, inArray } from "drizzle-orm";
|
||||||
import { LiveRefresh } from "@/components/LiveRefresh";
|
import { LiveRefresh } from "@/components/LiveRefresh";
|
||||||
import { AgentBadge } from "@/components/AgentBadge";
|
import { AgentBadge } from "@/components/AgentBadge";
|
||||||
import { ago, Empty, Flash, PageHeader } from "@/components/common";
|
import { ChatThreadList } from "@/components/ChatThreadList";
|
||||||
|
import { ChatScroll } from "@/components/ChatScroll";
|
||||||
|
import { ChatLiveFeed } from "@/components/ChatLiveFeed";
|
||||||
|
import { ChatSwitch } from "@/components/ChatSwitch";
|
||||||
|
import { ago, Empty, Flash, linkify, StatusBadge } from "@/components/common";
|
||||||
import { Hidden, QuestionCard } from "@/components/cards";
|
import { Hidden, QuestionCard } from "@/components/cards";
|
||||||
|
import { ProposalList } from "@/components/ProposalList";
|
||||||
|
import { Dictate } from "@/components/Dictate";
|
||||||
|
import { Attachments } from "@/components/Attachments";
|
||||||
|
import { AttachField } from "@/components/AttachField";
|
||||||
import { Workspace } from "@/components/Workspace";
|
import { Workspace } from "@/components/Workspace";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Textarea } from "@/components/ui/input";
|
import { Textarea } from "@/components/ui/input";
|
||||||
import { requireUser, words } from "@/lib/auth";
|
import { currentUser, requireUser, words } from "@/lib/auth";
|
||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
|
import { getT } from "@/lib/i18n";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
import { linkChatAction, postChatAction, unlinkChatAction } from "../actions";
|
import { cleanText, messageLink, STUCK_NOTICE } from "@/lib/chat-text";
|
||||||
|
import { chatOfferAction, linkChatAction, postChatAction, unlinkChatAction } from "../actions";
|
||||||
|
import { pageTitle } from "@/lib/title";
|
||||||
|
|
||||||
type Params = { error?: string; thread?: string; link?: string };
|
type Params = { error?: string; thread?: string; link?: string; q?: string; list?: string };
|
||||||
|
|
||||||
const CHANNEL = "channel";
|
const CHANNEL = "channel";
|
||||||
/** PEP-106: `?thread=feed` — the agents' events; no `thread` — the people's discussion. */
|
/** PEP-106: `?thread=feed` — the agents' events; no `thread` — the people's discussion. */
|
||||||
const FEED = "feed";
|
const FEED = "feed";
|
||||||
|
|
||||||
|
// PEP-274: «Чат KEY — FORGE» (the chat list of the viewer — no names of chats they cannot see).
|
||||||
|
export async function generateMetadata({ params }: { params: Promise<{ chat: string }> }) {
|
||||||
|
const t = await getT();
|
||||||
|
const user = await currentUser();
|
||||||
|
const slug = (await params).chat;
|
||||||
|
const chat = user ? (await listChats(db, user)).find((c) => c.slug.toLowerCase() === slug.toLowerCase()) : null;
|
||||||
|
if (!chat) return pageTitle(t, t("Чаты"));
|
||||||
|
return pageTitle(t, chat.kind === "master" ? t("Все события") : t("Чат {key}", { key: chat.slug.toUpperCase() }));
|
||||||
|
}
|
||||||
|
|
||||||
/** «Чаты» (PEP-62): the master chat and project chats with threads; a linked Telegram group mirrors them. */
|
/** «Чаты» (PEP-62): the master chat and project chats with threads; a linked Telegram group mirrors them. */
|
||||||
export default async function ChatPage({ params, searchParams }: { params: Promise<{ chat: string }>; searchParams: Promise<Params> }) {
|
export default async function ChatPage({ params, searchParams }: { params: Promise<{ chat: string }>; searchParams: Promise<Params> }) {
|
||||||
const user = await requireUser();
|
const user = await requireUser();
|
||||||
|
const t = await getT();
|
||||||
const w = await words();
|
const w = await words();
|
||||||
const { chat: slug } = await params;
|
const { chat: slug } = await params;
|
||||||
const { error, thread: rawThread, link } = await searchParams;
|
const { error, thread: rawThread, link, q, list: rawList } = await searchParams;
|
||||||
// Whoever renders first moves fresh events into the chats (the bot and the watchdog do it too).
|
// Whoever renders first moves fresh events into the chats (the bot and the watchdog do it too).
|
||||||
await syncChats(db).catch((e) => console.error("syncChats", e));
|
await syncChats(db).catch((e) => console.error("syncChats", e));
|
||||||
const list = await listChats(db, user);
|
const list = await listChats(db, user);
|
||||||
@ -39,17 +62,24 @@ export default async function ChatPage({ params, searchParams }: { params: Promi
|
|||||||
// A project chat opens on the discussion: people talking to each other, no agents or events.
|
// A project chat opens on the discussion: people talking to each other, no agents or events.
|
||||||
const discussion = !master && rawThread === undefined;
|
const discussion = !master && rawThread === undefined;
|
||||||
const unread = await discussionUnread(db, user.id);
|
const unread = await discussionUnread(db, user.id);
|
||||||
if (discussion) await markDiscussionRead(db, user.id, chat.id);
|
// PEP-155: on a phone it is either the list (`?list=1`) or the open conversation, full screen.
|
||||||
|
const showList = rawList === "1";
|
||||||
|
// PEP-207: what was unread before this look — the conversation opens there.
|
||||||
|
const unreadBefore = discussion ? (unread.get(chat.id) ?? 0) : null;
|
||||||
|
const threads = master ? null : await projectThreadList(db, user, chat, { q });
|
||||||
|
if (discussion && !showList) await markDiscussionRead(db, user.id, chat.id);
|
||||||
|
if (thread && !master && !showList) await markThreadRead(db, user.id, chat.id, thread);
|
||||||
// PEP-110: a person's message the analyst has not answered yet — «печатает…».
|
// PEP-110: a person's message the analyst has not answered yet — «печатает…».
|
||||||
const typing = discussion && (await analystPending(db, chat.id));
|
const typing = discussion && (await analystPending(db, chat.id));
|
||||||
|
|
||||||
const threads = master ? [] : await chatThreads(db, chat.id);
|
const rows = threads ? [...threads.waiting, ...threads.working, ...threads.done] : [];
|
||||||
const messages = master
|
const messages = master
|
||||||
? await masterFeed(db, user, { limit: 150 })
|
? await masterFeed(db, user, { limit: 150 })
|
||||||
: discussion
|
: discussion
|
||||||
? await discussionMessages(db, chat.id)
|
? await discussionMessages(db, chat.id)
|
||||||
: await chatMessagesView(db, chat.id, { threadKey: thread, limit: 150 });
|
: await chatMessagesView(db, chat.id, { threadKey: thread, limit: 150 });
|
||||||
const current = thread ? (threads.find((t) => t.key === thread)?.title ?? (await threadTitle(db, thread)) ?? thread) : null;
|
const files = await attachmentsByMessage(db, messages.map((m) => m.id));
|
||||||
|
const current = thread ? ((await threadTitle(db, thread)) ?? thread) : null;
|
||||||
|
|
||||||
// Live state of the questions in view (answer buttons, «отвечено» marks).
|
// Live state of the questions in view (answer buttons, «отвечено» marks).
|
||||||
const qIds = messages.map((m) => m.question?.id).filter((x): x is number => x != null);
|
const qIds = messages.map((m) => m.question?.id).filter((x): x is number => x != null);
|
||||||
@ -58,10 +88,15 @@ export default async function ChatPage({ params, searchParams }: { params: Promi
|
|||||||
: [];
|
: [];
|
||||||
const qById = new Map(qs.map((r) => [r.q.id, { q: r.q as Question, taskStatus: r.status, taskKey: r.number != null ? formatTaskKey(r.key, r.number) : null }]));
|
const qById = new Map(qs.map((r) => [r.q.id, { q: r.q as Question, taskStatus: r.status, taskKey: r.number != null ? formatTaskKey(r.key, r.number) : null }]));
|
||||||
|
|
||||||
const url = (p: { thread?: string | null }) => {
|
const base = `/chats/${chat.slug}`;
|
||||||
const base = `/chats/${chat.slug}`;
|
const url = (p: { thread?: string | null; list?: boolean }) => {
|
||||||
return p.thread ? `${base}?thread=${encodeURIComponent(p.thread)}` : base;
|
const params = new URLSearchParams();
|
||||||
|
if (p.thread) params.set("thread", p.thread);
|
||||||
|
if (threads?.q) params.set("q", threads.q);
|
||||||
|
if (p.list) params.set("list", "1");
|
||||||
|
return params.size ? `${base}?${params}` : base;
|
||||||
};
|
};
|
||||||
|
const openRow = thread ? rows.find((r) => r.key === thread) : undefined;
|
||||||
const here = discussion ? url({}) : url({ thread: thread === null ? CHANNEL : (thread ?? FEED) });
|
const here = discussion ? url({}) : url({ thread: thread === null ? CHANNEL : (thread ?? FEED) });
|
||||||
// PEP-109: a group is linked through the user's own bot. The platform's bot is the superadmin's
|
// PEP-109: a group is linked through the user's own bot. The platform's bot is the superadmin's
|
||||||
// (users never see it) and links groups only for a superadmin without a bot of their own.
|
// (users never see it) and links groups only for a superadmin without a bot of their own.
|
||||||
@ -72,14 +107,14 @@ export default async function ChatPage({ params, searchParams }: { params: Promi
|
|||||||
const ttlDays = Math.round(chatTtlMs() / 86_400_000);
|
const ttlDays = Math.round(chatTtlMs() / 86_400_000);
|
||||||
const taskThread = thread?.startsWith("task:");
|
const taskThread = thread?.startsWith("task:");
|
||||||
const placeholder = master
|
const placeholder = master
|
||||||
? w.engineer ? "/status, /task KEY-N, /move KEY-N in_progress, /help" : "Заметка для себя"
|
? w.engineer ? "/status, /task KEY-N, /move KEY-N in_progress, /help" : t("Заметка для себя")
|
||||||
: discussion
|
: discussion
|
||||||
? `Спросите аналитика, что с проектом, или опишите идею — он поможет сформулировать ${w.task("acc")}…`
|
? t("Спросите аналитика, что с проектом, или опишите идею — он поможет сформулировать {task}…", { task: w.task("acc") })
|
||||||
: taskThread
|
: taskThread
|
||||||
? `Напишите агенту этой ${w.task("gen")} — ответ на его вопрос или замечание, он увидит сразу`
|
? t("Напишите агенту этой {task} — ответ на его вопрос или замечание, он увидит сразу", { task: w.task("gen") })
|
||||||
: thread
|
: thread
|
||||||
? w.engineer ? "Заметка в тред или команда /help" : "Заметка к этой переписке"
|
? w.engineer ? t("Заметка в тред или команда /help") : t("Заметка к этой переписке")
|
||||||
: w.engineer ? "Заметка в канал или команда: /status, /task KEY-N, /move KEY-N in_progress" : "Заметка для себя и участников проекта";
|
: w.engineer ? t("Заметка в канал или команда: /status, /task KEY-N, /move KEY-N in_progress") : t("Заметка для себя и участников проекта");
|
||||||
|
|
||||||
const aside = (
|
const aside = (
|
||||||
<div className="flex flex-col gap-5 text-sm">
|
<div className="flex flex-col gap-5 text-sm">
|
||||||
@ -88,61 +123,64 @@ export default async function ChatPage({ params, searchParams }: { params: Promi
|
|||||||
<p className="m-0 text-muted-foreground">
|
<p className="m-0 text-muted-foreground">
|
||||||
{user.telegramBotUsername ? (
|
{user.telegramBotUsername ? (
|
||||||
<>
|
<>
|
||||||
Новые сообщения обсуждения и вопросы агентов приходят в ваш бот <span className="font-mono text-foreground">@{user.telegramBotUsername}</span>.
|
{t("Новые сообщения обсуждения и вопросы агентов приходят в ваш бот")} <span className="font-mono text-foreground">@{user.telegramBotUsername}</span>.
|
||||||
</>
|
</>
|
||||||
) : (
|
) : (
|
||||||
<>
|
<>
|
||||||
Чтобы новые сообщения приходили в Telegram, подключите своего бота: <Link href="/settings#telegram">Настройки → Telegram</Link>.
|
{t("Чтобы новые сообщения приходили в Telegram, подключите своего бота:")} <Link href="/settings#telegram">{t("Настройки → Telegram")}</Link>.
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</p>
|
</p>
|
||||||
</section>
|
</section>
|
||||||
<section className="flex flex-col gap-2">
|
<section className="flex flex-col gap-2">
|
||||||
<h2 className="m-0 text-[15px] font-semibold">Telegram-группа</h2>
|
<h2 className="m-0 text-[15px] font-semibold">{t("Telegram-группа")}</h2>
|
||||||
{chat.tgTitle ? (
|
{chat.tgTitle ? (
|
||||||
<>
|
<>
|
||||||
<p className="m-0 text-muted-foreground">
|
<p className="m-0 text-muted-foreground">
|
||||||
Связан с группой <b className="text-foreground">{chat.tgTitle}</b>
|
{t("Связан с группой")} <b className="text-foreground">{chat.tgTitle}</b>
|
||||||
{groupBot && (
|
{groupBot && (
|
||||||
<>
|
<>
|
||||||
{" "}
|
{" "}
|
||||||
через бота <span className="font-mono text-foreground">@{groupBot}</span>
|
{t("через бота")} <span className="font-mono text-foreground">@{groupBot}</span>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
. Сообщения чата приходят туда, треды — цепочками ответов; ответ реплаем уходит в тред{master ? "" : ` (в переписке по ${w.task("dat")} — агенту)`}.
|
.{" "}
|
||||||
|
{master
|
||||||
|
? t("Сообщения чата приходят туда, треды — цепочками ответов; ответ реплаем уходит в тред.")
|
||||||
|
: t("Сообщения чата приходят туда, треды — цепочками ответов; ответ реплаем уходит в тред (в переписке по {task} — агенту).", { task: w.task("dat") })}
|
||||||
</p>
|
</p>
|
||||||
<form action={unlinkChatAction}>
|
<form action={unlinkChatAction}>
|
||||||
<Hidden fields={{ chatId: chat.id, back: here }} />
|
<Hidden fields={{ chatId: chat.id, back: here }} />
|
||||||
<Button size="sm" variant="outline">
|
<Button size="sm" variant="outline">
|
||||||
<Unlink />
|
<Unlink />
|
||||||
Отвязать группу
|
{t("Отвязать группу")}
|
||||||
</Button>
|
</Button>
|
||||||
</form>
|
</form>
|
||||||
</>
|
</>
|
||||||
) : !mayLink ? (
|
) : !mayLink ? (
|
||||||
<p className="m-0 text-muted-foreground">
|
<p className="m-0 text-muted-foreground">
|
||||||
{master ? "Мастер-чат можно связать с группой Telegram — туда пойдёт всё важное по вашим проектам." : "Чат проекта можно связать с группой команды в Telegram."} Группа подключается через вашего собственного бота — сначала подключите его:{" "}
|
{master ? t("Мастер-чат можно связать с группой Telegram — туда пойдёт всё важное по вашим проектам.") : t("Чат проекта можно связать с группой команды в Telegram.")}{" "}
|
||||||
<Link href="/settings#telegram">Настройки → Telegram</Link>.
|
{t("Группа подключается через вашего собственного бота — сначала подключите его:")} <Link href="/settings#telegram">{t("Настройки → Telegram")}</Link>.
|
||||||
</p>
|
</p>
|
||||||
) : link ? (
|
) : link ? (
|
||||||
<div className="flex flex-col gap-2 rounded-lg border bg-card p-3">
|
<div className="flex flex-col gap-2 rounded-lg border bg-card p-3">
|
||||||
<p className="m-0">Код действует 10 минут.</p>
|
<p className="m-0">{t("Код действует 10 минут.")}</p>
|
||||||
{bot && (
|
{bot && (
|
||||||
<a href={`https://t.me/${bot}?startgroup=${encodeURIComponent(link)}`} target="_blank" rel="noreferrer" className="font-medium">
|
<a href={`https://t.me/${bot}?startgroup=${encodeURIComponent(link)}`} target="_blank" rel="noreferrer" className="font-medium">
|
||||||
Добавить @{bot} в группу →
|
{t("Добавить @{bot} в группу →", { bot })}
|
||||||
</a>
|
</a>
|
||||||
)}
|
)}
|
||||||
<p className="m-0 text-muted-foreground">Или добавьте {bot ? <span className="font-mono">@{bot}</span> : "бота"} в группу сами и отправьте там:</p>
|
<p className="m-0 text-muted-foreground">{t("Или добавьте {bot} в группу сами и отправьте там:", { bot: bot ? `@${bot}` : t("бота") })}</p>
|
||||||
<code className="rounded bg-muted px-2 py-1 font-mono text-xs break-all select-all">/link{bot ? `@${bot}` : ""} {link}</code>
|
<code className="rounded bg-muted px-2 py-1 font-mono text-xs break-all select-all">/link{bot ? `@${bot}` : ""} {link}</code>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<>
|
<>
|
||||||
<p className="m-0 text-muted-foreground">
|
<p className="m-0 text-muted-foreground">
|
||||||
{master ? "Свяжите мастер-чат с группой — туда пойдёт всё важное по вашим проектам." : "Свяжите чат проекта с группой команды — по ней сразу видно, к какому проекту сообщение."}
|
{master ? t("Свяжите мастер-чат с группой — туда пойдёт всё важное по вашим проектам.") : t("Свяжите чат проекта с группой команды — по ней сразу видно, к какому проекту сообщение.")}
|
||||||
{bot && (
|
{bot && (
|
||||||
<>
|
<>
|
||||||
{" "}
|
{" "}
|
||||||
В группу добавится ваш бот <span className="font-mono text-foreground">@{bot}</span>.
|
{t("В группу добавится ваш бот")} <span className="font-mono text-foreground">@{bot}</span>.
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</p>
|
</p>
|
||||||
@ -150,117 +188,181 @@ export default async function ChatPage({ params, searchParams }: { params: Promi
|
|||||||
<Hidden fields={{ chatId: chat.id, back: here }} />
|
<Hidden fields={{ chatId: chat.id, back: here }} />
|
||||||
<Button size="sm" variant="outline">
|
<Button size="sm" variant="outline">
|
||||||
<Link2 />
|
<Link2 />
|
||||||
Связать с Telegram
|
{t("Связать с Telegram")}
|
||||||
</Button>
|
</Button>
|
||||||
</form>
|
</form>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
<p className="m-0 text-xs text-muted-foreground">Отвечать из группы могут те, кто привязал Telegram в «Настройках» и имеет доступ к {master ? "мастер-чату (только вы)" : "проекту"}.</p>
|
<p className="m-0 text-xs text-muted-foreground">{t("Отвечать из группы могут те, кто привязал Telegram в «Настройках» и имеет доступ к {target}.", { target: master ? t("мастер-чату (только вы)") : t("проекту") })}</p>
|
||||||
</section>
|
</section>
|
||||||
<section className="flex flex-col gap-1.5 text-xs text-muted-foreground">
|
<section className="flex flex-col gap-1.5 text-xs text-muted-foreground">
|
||||||
<h2 className="m-0 text-[15px] font-semibold text-foreground">Как это устроено</h2>
|
<h2 className="m-0 text-[15px] font-semibold text-foreground">{t("Как это устроено")}</h2>
|
||||||
<p className="m-0">
|
<p className="m-0">
|
||||||
{master
|
{master
|
||||||
? `Журнал: готовые ${w.task("pl")}, вопросы, обновления продукта и сбои по всем вашим проектам. Отвечать удобнее в «Обзоре» или в чате проекта.`
|
? t("Журнал: готовые {tasks}, вопросы, обновления продукта и сбои по всем вашим проектам. Отвечать удобнее в «Обзоре» или в чате проекта.", { tasks: w.task("pl") })
|
||||||
: `Слева: чат с аналитиком — для вопросов и новых задач; «События агентов» — журнал; ниже — переписка по каждой ${w.task("dat")} с её агентом.`}
|
: t("Слева: чат с аналитиком — для вопросов и новых задач; «События агентов» — журнал; ниже — переписка по каждой {task} с её агентом.", { task: w.task("dat") })}
|
||||||
</p>
|
</p>
|
||||||
<p className="m-0">Журнал событий хранится {ttlDays} дн.; ваша переписка с аналитиком не удаляется.</p>
|
<p className="m-0">{t("Журнал событий хранится {n} дн.; ваша переписка с аналитиком не удаляется.", { n: ttlDays })}</p>
|
||||||
</section>
|
</section>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|
||||||
return (
|
// PEP-207: the chat with the analyst holds people and the analyst; the factory's service notices
|
||||||
<Workspace aside={aside}>
|
// («задерживается на нашей стороне») are the status line on top, not messages — old ones included.
|
||||||
<LiveRefresh scope="chats" />
|
const shownMessages = discussion ? messages.filter((m) => !(m.authorKind !== "user" && STUCK_NOTICE.test(stripAsIs(m.text)))) : messages;
|
||||||
<Flash error={error} />
|
const status = discussion && chat.projectId ? await chatStatusLine(db, chat.projectId) : null;
|
||||||
<PageHeader title="Чаты">
|
// PEP-207: oldest first, newest at the bottom — the first unread message is where the reader lands.
|
||||||
{master
|
const ordered = [...shownMessages];
|
||||||
? "Все события по вашим проектам — журнал, справочно. Чтобы ответить агенту или написать аналитику, откройте чат проекта."
|
const unreadCount = discussion ? (unreadBefore ?? 0) : (openRow?.unread ?? 0);
|
||||||
: `Чат с аналитиком — ИИ-агентом вашего проекта. Спросите, что сделано и где это посмотреть, или опишите идею: он уточнит, предложит ${w.task("accPl")} и заведёт их в бэклог, когда вы скажете.`}
|
const counted = (m: ChatMessageView) => (discussion ? m.authorUserId !== user.id : m.kind === "question" || (m.kind === "user" && m.authorKind !== "user"));
|
||||||
</PageHeader>
|
let firstUnreadId: number | null = null;
|
||||||
|
if (unreadCount > 0) {
|
||||||
|
let left = unreadCount;
|
||||||
|
for (let i = ordered.length - 1; i >= 0 && left > 0; i--) {
|
||||||
|
if (!counted(ordered[i]!)) continue;
|
||||||
|
firstUnreadId = ordered[i]!.id;
|
||||||
|
left--;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const groups = groupMessages(ordered, !discussion && !master);
|
||||||
|
const taskStatus = openRow?.status ?? null;
|
||||||
|
const writable = !(master || (!discussion && thread === undefined));
|
||||||
|
// PEP-207: superadmins see the raw journal on its own page; this view is cleaned for everybody.
|
||||||
|
const gitea = (process.env.GITEA_URL ?? "").replace(/\/+$/, "");
|
||||||
|
const options = [...list.filter((c) => c.kind === "project"), ...list.filter((c) => c.kind === "master")].map((c) => {
|
||||||
|
const name = c.kind === "master" ? t("Все события") : c.title.includes(" · ") ? c.title.split(" · ").slice(1).join(" · ") : c.slug;
|
||||||
|
const marks = [(unread.get(c.id) ?? 0) > 0 && c.id !== chat.id ? t("{n} нов.", { n: unread.get(c.id) ?? 0 }) : null, c.open > 0 ? `${c.open} ?` : null].filter(Boolean).join(" · ");
|
||||||
|
return { slug: c.slug, label: marks ? `${c.kind === "master" ? name : `${c.slug} · ${name}`} (${marks})` : c.kind === "master" ? name : `${c.slug} · ${name}` };
|
||||||
|
});
|
||||||
|
|
||||||
<nav className="mb-4 flex flex-wrap gap-1.5" aria-label="Чаты">
|
const feed = ordered.length === 0 ? (
|
||||||
<Link href="/chats" className="flex items-center gap-1.5 rounded-md border bg-card px-2.5 py-1 text-sm text-muted-foreground hover:border-muted-foreground hover:text-foreground hover:no-underline">
|
<Empty>{discussion ? t("Напишите, что хотите узнать или сделать, — аналитик ответит здесь же. Например: «Что сейчас в работе?» или «Хочу страницу с отзывами клиентов».") : master ? t("Пока тихо: здесь появятся вопросы агентов, сбои и обновления ваших проектов.") : thread === undefined ? t("Сообщений пока нет: они появятся, когда агенты возьмутся за {tasks}.", { tasks: w.task("accPl") }) : t("В этом треде пока пусто.")}</Empty>
|
||||||
← Обзор
|
|
||||||
</Link>
|
|
||||||
{/* PEP-117: projects first (by name), the journal of all events last. */}
|
|
||||||
{[...list.filter((c) => c.kind === "project"), ...list.filter((c) => c.kind === "master")].map((c) => (
|
|
||||||
<Link
|
|
||||||
key={c.id}
|
|
||||||
href={`/chats/${c.slug}`}
|
|
||||||
aria-current={c.id === chat.id ? "page" : undefined}
|
|
||||||
title={c.title}
|
|
||||||
className={cn(
|
|
||||||
"flex items-center gap-1.5 rounded-md border bg-card px-2.5 py-1 text-sm text-muted-foreground hover:border-muted-foreground hover:text-foreground hover:no-underline",
|
|
||||||
c.id === chat.id && "border-primary/60 bg-primary/10 text-foreground",
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
{c.kind === "master" ? <MessagesSquare className="size-3.5" /> : <Hash className="size-3.5" />}
|
|
||||||
<span>{c.kind === "master" ? "Все события" : c.title.includes(" · ") ? c.title.split(" · ").slice(1).join(" · ") : c.slug}</span>
|
|
||||||
{c.tgTitle && <Send className="size-3 text-info" aria-label="связан с Telegram" />}
|
|
||||||
{(unread.get(c.id) ?? 0) > 0 && c.id !== chat.id && (
|
|
||||||
<span className="rounded-full bg-info px-1.5 font-mono text-[11px] leading-4 font-semibold text-background tabular-nums" title="новые сообщения в обсуждении">
|
|
||||||
{unread.get(c.id)}
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
{c.open > 0 && <span className="rounded-full bg-primary px-1.5 font-mono text-[11px] leading-4 font-semibold text-primary-foreground tabular-nums" title="вопросы агентов">{c.open}</span>}
|
|
||||||
</Link>
|
|
||||||
))}
|
|
||||||
</nav>
|
|
||||||
|
|
||||||
<div className={cn("grid gap-4", !master && "lg:grid-cols-[230px_minmax(0,1fr)]")}>
|
|
||||||
{!master && (
|
|
||||||
<nav aria-label="Треды" className="flex flex-col gap-0.5 self-start rounded-lg border bg-card/50 p-1.5 text-sm max-lg:max-h-48 max-lg:overflow-y-auto">
|
|
||||||
<ThreadLink href={url({})} active={discussion} title="💬 Чат с аналитиком" meta="вопросы и новые задачи" />
|
|
||||||
<ThreadLink href={url({ thread: FEED })} active={!discussion && thread === undefined} title="События агентов" meta="журнал: что делали агенты" />
|
|
||||||
{threads.length > 0 && <p className="m-0 px-2 pt-2 text-[11px] tracking-wide text-muted-foreground uppercase">Переписка по {w.task("datPl")}</p>}
|
|
||||||
{threads.map((t) => (
|
|
||||||
<ThreadLink key={t.key} href={url({ thread: t.key })} active={thread === t.key} title={t.title} meta={`${t.count} · ${ago(t.lastAt)}`} open={t.open} />
|
|
||||||
))}
|
|
||||||
{threads.length === 0 && <p className="m-0 px-2 py-1.5 text-xs text-muted-foreground">Переписки по {w.task("datPl")} пока нет.</p>}
|
|
||||||
</nav>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<section className="flex min-w-0 flex-col gap-3" aria-label="Сообщения">
|
|
||||||
{current && (
|
|
||||||
<div className="flex flex-wrap items-center gap-2 text-sm">
|
|
||||||
<span className="font-medium">🧵 {current}</span>
|
|
||||||
{taskThread && <TaskLink messages={messages} label={`открыть ${w.task("acc")} →`} />}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{messages.length === 0 ? (
|
|
||||||
<Empty>{discussion ? "Напишите, что хотите узнать или сделать, — аналитик ответит здесь же. Например: «Что сейчас в работе?» или «Хочу страницу с отзывами клиентов»." : master ? "Пока тихо: здесь появятся вопросы агентов, сбои и обновления ваших проектов." : thread === undefined ? `Сообщений пока нет: они появятся, когда агенты возьмутся за ${w.task("accPl")}.` : "В этом треде пока пусто."}</Empty>
|
|
||||||
) : (
|
) : (
|
||||||
<ol className="m-0 flex list-none flex-col gap-2 p-0">
|
<ol data-chat-messages className="m-0 flex list-none flex-col gap-2 p-0 pr-12 md:pr-14">
|
||||||
{messages.map((m) => (
|
{groups.map((g) =>
|
||||||
<li key={m.id}>
|
g.kind === "events" ? (
|
||||||
<MessageItem m={m} q={m.question ? qById.get(m.question.id) : undefined} back={here} showThread={!discussion && thread === undefined} masterView={master} mine={discussion && m.authorUserId === user.id} />
|
<li key={`e${g.items[0]!.id}`}>
|
||||||
</li>
|
<EventLines items={g.items} firstUnreadId={firstUnreadId} taskStatus={taskStatus} agentName={openRow?.agentName ?? null} masterView={master} showThread={!discussion && thread === undefined} superadmin={superadmin} gitea={gitea} />
|
||||||
))}
|
</li>
|
||||||
|
) : (
|
||||||
|
<li key={g.m.id} data-first-unread={g.m.id === firstUnreadId ? "" : undefined} className={cn("flex", discussion && g.m.authorUserId === user.id && g.m.kind === "user" ? "justify-end" : "justify-start")}>
|
||||||
|
<div className={cn("min-w-0", g.m.question ? "w-full" : "max-w-[85%]")}>
|
||||||
|
<MessageItem files={files.get(g.m.id)} m={g.m} q={g.m.question ? qById.get(g.m.question.id) : undefined} back={here} showThread={!discussion && thread === undefined} masterView={master} mine={discussion && g.m.authorUserId === user.id} agentName={openRow?.agentName ?? null} superadmin={superadmin} gitea={gitea} />
|
||||||
|
</div>
|
||||||
|
</li>
|
||||||
|
),
|
||||||
|
)}
|
||||||
</ol>
|
</ol>
|
||||||
)}
|
);
|
||||||
{typing && (
|
|
||||||
<p className="m-0 flex items-center gap-2 text-sm text-muted-foreground" aria-live="polite">
|
return (
|
||||||
<AgentBadge name="Аналитик" /> <span className="animate-pulse">печатает…</span>
|
<Workspace aside={null} wide>
|
||||||
</p>
|
{/* PEP-228: a project chat draws its new messages in place (ChatLiveFeed) and re-renders only for
|
||||||
)}
|
what it can't draw; the master feed gathers every project and re-renders. */}
|
||||||
{master || (!discussion && thread === undefined) ? (
|
<LiveRefresh scope={master ? "chats" : `chat:${chat.id}`} indicator={false} />
|
||||||
<p className="m-0 rounded-lg border border-dashed px-3 py-2 text-sm text-muted-foreground">
|
<Flash error={error} />
|
||||||
Это журнал событий — писать сюда не нужно.{" "}
|
<h1 className="sr-only">{t("Чаты")}</h1>
|
||||||
{master ? <Link href="/chats">Выберите проект</Link> : <Link href={url({})}>Откройте чат с аналитиком</Link>}, чтобы задать вопрос или описать задачу.
|
|
||||||
</p>
|
<div className="grid gap-4 lg:grid-cols-[300px_minmax(0,1fr)]">
|
||||||
|
<div className={cn("flex min-w-0 flex-col gap-2 lg:sticky lg:top-4 lg:max-h-[calc(100dvh-2rem)] lg:self-start lg:overflow-y-auto", !showList && "max-lg:hidden")}>
|
||||||
|
<Link href="/chats" className="text-sm text-muted-foreground hover:text-foreground">{t("Все чаты")}</Link>
|
||||||
|
<ChatSwitch current={chat.slug} options={options} />
|
||||||
|
{threads ? (
|
||||||
|
<ChatThreadList base={base} list={threads} active={thread ?? null} discussion={discussion} feed={!discussion && thread === undefined} raw={rawThread ?? null} />
|
||||||
) : (
|
) : (
|
||||||
<form action={postChatAction} className="sticky bottom-16 flex flex-col gap-2 rounded-lg border bg-card p-3 md:bottom-3">
|
<p className="m-0 rounded-lg border bg-card/50 p-3 text-sm text-muted-foreground">{t("Все события по вашим проектам — справочно. Чтобы ответить или написать, выберите проект.")}</p>
|
||||||
<Hidden fields={{ chatId: chat.id, thread: thread ?? "", back: here }} />
|
)}
|
||||||
<Textarea name="text" rows={2} required maxLength={8000} placeholder={placeholder} aria-label="Сообщение" />
|
{master && superadmin && (
|
||||||
<div className="flex items-center gap-2">
|
<Link href="/journal" className="text-sm">{t("Полный журнал платформы →")}</Link>
|
||||||
<span className="text-xs text-muted-foreground">{discussion ? "отвечает аналитик на подписке проекта · переписку видят участники проекта" : thread ? "в тред" : master ? "в мастер-чат" : "в канал"}{chat.tgTitle ? ` · и в Telegram «${chat.tgTitle}»` : ""}</span>
|
)}
|
||||||
<Button size="sm" className="ml-auto">
|
<details className="rounded-lg border bg-card/50 p-3 text-sm">
|
||||||
<Send />
|
<summary className="cursor-pointer text-muted-foreground">Telegram</summary>
|
||||||
Отправить
|
<div className="mt-3">{aside}</div>
|
||||||
</Button>
|
</details>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
|
||||||
|
<section className={cn("flex min-w-0 flex-col gap-3", showList && "max-lg:hidden")} aria-label={t("Сообщения")}>
|
||||||
|
<div className="flex flex-wrap items-center gap-2 text-sm">
|
||||||
|
<Link href={master ? "/chats" : url({ thread: rawThread, list: true })} aria-label={t("Назад")} title={t("Назад")} className="grid size-9 shrink-0 place-items-center rounded-md border bg-card text-muted-foreground hover:text-foreground hover:no-underline lg:hidden">
|
||||||
|
<ArrowLeft className="size-4" />
|
||||||
|
</Link>
|
||||||
|
<span className="min-w-0 truncate font-medium">{current ? t.text(current) : master ? t("Все события") : discussion ? t("Чат с аналитиком") : t("События агентов")}</span>
|
||||||
|
{openRow?.status && <StatusBadge status={openRow.status} />}
|
||||||
|
{openRow?.agentName && <AgentBadge name={openRow.agentName} />}
|
||||||
|
{taskThread && <TaskLink messages={messages} label={t("открыть {task} →", { task: w.task("acc") })} />}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{status && status.working.length + status.delayed.length > 0 && (
|
||||||
|
<details data-chat-status className="rounded-lg border bg-card/50 px-3 py-2 text-sm">
|
||||||
|
<summary className="cursor-pointer text-muted-foreground">
|
||||||
|
{status.delayed.length
|
||||||
|
? t("Сейчас: делается {n}, задерживаются на нашей стороне {m}", { n: status.working.length, m: status.delayed.length })
|
||||||
|
: t("Сейчас: делается {n}", { n: status.working.length })}
|
||||||
|
</summary>
|
||||||
|
<ul className="m-0 mt-2 flex list-none flex-col gap-1 p-0">
|
||||||
|
{[...status.delayed.map((r) => ({ ...r, delayed: true })), ...status.working.map((r) => ({ ...r, delayed: false }))].map((r) => (
|
||||||
|
<li key={r.key} className="flex gap-2">
|
||||||
|
<Link href={`/t/${r.key}`} className="font-mono text-xs">{r.key}</Link>
|
||||||
|
<span className="min-w-0 truncate">{r.title}</span>
|
||||||
|
{r.delayed && <span className="shrink-0 text-xs text-warn">{t("небольшая задержка на нашей стороне")}</span>}
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</details>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{!writable && (
|
||||||
|
<p className="m-0 rounded-lg border border-dashed px-3 py-2 text-sm text-muted-foreground">
|
||||||
|
{t("Это журнал событий — писать сюда не нужно.")}{" "}
|
||||||
|
{master ? <Link href="/chats">{t("Выберите проект")}</Link> : <Link href={url({})}>{t("Откройте чат с аналитиком")}</Link>}{t(", чтобы задать вопрос или описать задачу.")}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{master ? (
|
||||||
|
<>
|
||||||
|
{feed}
|
||||||
|
<div data-chat-end />
|
||||||
|
<ChatScroll lastId={ordered.at(-1)?.id ?? 0} />
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<ChatLiveFeed
|
||||||
|
chatId={chat.id}
|
||||||
|
lastId={messages.at(-1)?.id ?? 0}
|
||||||
|
view={discussion ? { kind: "discussion" } : thread === undefined ? { kind: "feed" } : thread === null ? { kind: "channel" } : { kind: "thread", key: thread }}
|
||||||
|
userId={user.id}
|
||||||
|
compact={!discussion}
|
||||||
|
showThread={!discussion && thread === undefined}
|
||||||
|
agentName={openRow?.agentName ?? null}
|
||||||
|
empty={ordered.length === 0}
|
||||||
|
typing={
|
||||||
|
typing ? (
|
||||||
|
<p className="m-0 flex items-center gap-2 text-sm text-muted-foreground" aria-live="polite">
|
||||||
|
<AgentBadge name={ANALYST_NAME} role /> <span className="animate-pulse">{t("печатает…")}</span>
|
||||||
|
</p>
|
||||||
|
) : null
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{feed}
|
||||||
|
</ChatLiveFeed>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{writable && (
|
||||||
|
<form action={postChatAction} data-chat-composer className="sticky bottom-[calc(4rem+env(safe-area-inset-bottom))] z-20 -mx-1 flex flex-col gap-1 rounded-lg border bg-card p-2 shadow-md md:bottom-3">
|
||||||
|
<Hidden fields={{ chatId: chat.id, thread: thread ?? "", back: here }} />
|
||||||
|
{/* PEP-274 (F-12): on a phone the field takes the whole row (the hint is not cut), the buttons go below, each ≥ 44 px. */}
|
||||||
|
<div className="flex flex-wrap items-end gap-1.5 md:flex-nowrap">
|
||||||
|
<Textarea id="chat-text" name="text" rows={1} maxLength={60000} placeholder={placeholder} aria-label={t("Сообщение")} className="max-h-40 min-h-[4.25rem] flex-1 basis-full resize-y py-1.5 [field-sizing:content] md:min-h-9 md:basis-0" data-chat-text />
|
||||||
|
{chat.projectId && <AttachField projectId={chat.projectId} target="chat-text" className="shrink-0" touch />}
|
||||||
|
<Dictate target="chat-text" compact touch />
|
||||||
|
<Button size="sm" aria-label={t("Отправить")} title={t("Отправить")} className="ml-auto size-11 md:ml-0 md:h-9 md:w-auto" data-chat-send>
|
||||||
|
<Send />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
<span className="px-1 text-[11px] text-muted-foreground">
|
||||||
|
{discussion ? t("Переписку видят участники проекта") : thread ? t("Сообщение увидят агент и участники проекта") : t("Заметку видят участники проекта")}
|
||||||
|
{chat.tgTitle ? " · " + t("и в Telegram «{title}»", { title: chat.tgTitle }) : ""}
|
||||||
|
</span>
|
||||||
|
</form>
|
||||||
)}
|
)}
|
||||||
</section>
|
</section>
|
||||||
</div>
|
</div>
|
||||||
@ -268,19 +370,54 @@ export default async function ChatPage({ params, searchParams }: { params: Promi
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function ThreadLink({ href, active, title, meta, open = 0 }: { href: string; active: boolean; title: string; meta?: string; open?: number }) {
|
|
||||||
|
type Group = { kind: "events"; items: ChatMessageView[] } | { kind: "message"; m: ChatMessageView };
|
||||||
|
|
||||||
|
/** PEP-207: events in a row become one compact block; questions and people's / agents' words stay messages. */
|
||||||
|
function groupMessages(ordered: ChatMessageView[], compact: boolean): Group[] {
|
||||||
|
const out: Group[] = [];
|
||||||
|
for (const m of ordered) {
|
||||||
|
const event = compact && (m.kind === "event" || m.kind === "system") && !m.question;
|
||||||
|
const last = out.at(-1);
|
||||||
|
if (event && last?.kind === "events") last.items.push(m);
|
||||||
|
else out.push(event ? { kind: "events", items: [m] } : { kind: "message", m });
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** An event asks the person to do something («посмотрите и примите») — stale once the story moved on. */
|
||||||
|
const ASKS_TO_ACCEPT = /посмотрите результат и примите|check the result and accept/i;
|
||||||
|
|
||||||
|
async function EventLines({ items, firstUnreadId, taskStatus, agentName, masterView, showThread, superadmin, gitea }: { items: ChatMessageView[]; firstUnreadId: number | null; taskStatus: string | null; agentName: string | null; masterView: boolean; showThread: boolean; superadmin: boolean; gitea: string }) {
|
||||||
|
const t = await getT();
|
||||||
|
const line = (m: ChatMessageView, i: number) => {
|
||||||
|
const text = cleanText(t.text(m.text), superadmin, gitea);
|
||||||
|
const stale = ASKS_TO_ACCEPT.test(stripAsIs(m.text)) && (taskStatus !== "review" || items.slice(i + 1).length > 0);
|
||||||
|
const who = m.authorKind === "agent" ? (m.authorLogin ? t.role(m.authorLogin) : agentName) : null;
|
||||||
|
const link = messageLink(m.url, superadmin, gitea);
|
||||||
|
return (
|
||||||
|
<div key={m.id} data-event-line data-first-unread={m.id === firstUnreadId ? "" : undefined} className={cn("flex items-baseline gap-2 px-1 text-xs text-muted-foreground", stale && "opacity-60")}>
|
||||||
|
<span className="min-w-0 flex-1 break-words">
|
||||||
|
{who && <span className="mr-1.5 text-foreground/80">{who}:</span>}
|
||||||
|
<span className={cn(stale && "line-through")}>{text.split("\n")[0]}</span>
|
||||||
|
{stale && <span className="ml-1.5 no-underline">({t("уже не актуально")})</span>}
|
||||||
|
{link && (
|
||||||
|
<a href={link} className="ml-1.5">{t("открыть")}</a>
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
{m.repeats > 0 && <span className="shrink-0 font-mono">×{m.repeats + 1}</span>}
|
||||||
|
<span className="shrink-0 font-mono">{ago(m.updatedAt ?? m.createdAt, t)}</span>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
if (items.length === 1) return <div className="border-y border-dashed py-1">{line(items[0]!, 0)}</div>;
|
||||||
return (
|
return (
|
||||||
<Link
|
<details data-event-group className="border-y border-dashed py-1" open={items.some((m) => m.id === firstUnreadId)}>
|
||||||
href={href}
|
<summary className="cursor-pointer px-1 text-xs text-muted-foreground">
|
||||||
aria-current={active ? "page" : undefined}
|
{t("{n} событий", { n: items.length })} · {cleanText(t.text(items.at(-1)!.text), superadmin, gitea).split("\n")[0]}
|
||||||
className={cn("flex flex-col rounded-md px-2 py-1.5 text-foreground hover:bg-accent hover:no-underline", active && "bg-accent font-medium")}
|
</summary>
|
||||||
>
|
<div className="mt-1 flex flex-col gap-1">{items.map(line)}</div>
|
||||||
<span className="flex items-center gap-1.5">
|
</details>
|
||||||
<span className="min-w-0 flex-1 truncate" title={title}>{title}</span>
|
|
||||||
{open > 0 && <span className="rounded-full bg-primary px-1.5 font-mono text-[11px] leading-4 font-semibold text-primary-foreground tabular-nums" title="ждут ответа">{open}</span>}
|
|
||||||
</span>
|
|
||||||
{meta && <span className="text-[11px] text-muted-foreground">{meta}</span>}
|
|
||||||
</Link>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -290,60 +427,118 @@ function TaskLink({ messages, label }: { messages: ChatMessageView[]; label: str
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** URLs in a message become links (the analyst points at the board, a story, a stand). */
|
/** URLs in a message become links (the analyst points at the board, a story, a stand). */
|
||||||
function linkify(text: string) {
|
|
||||||
return text.split(/(https?:\/\/[^\s<>«»"]+[^\s<>«»".,;:!?)])/g).map((part, i) =>
|
|
||||||
i % 2 ? (
|
|
||||||
<a key={i} href={part} target={part.startsWith(process.env.PEPPA_WEB_URL ?? "\0") ? undefined : "_blank"} rel="noreferrer">
|
|
||||||
{part}
|
|
||||||
</a>
|
|
||||||
) : (
|
|
||||||
part
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function threadHref(m: ChatMessageView) {
|
function threadHref(m: ChatMessageView) {
|
||||||
return m.projectKey && m.threadKey ? `/chats/${m.projectKey}?thread=${encodeURIComponent(m.threadKey)}` : m.projectKey ? `/chats/${m.projectKey}` : null;
|
return m.projectKey && m.threadKey ? `/chats/${m.projectKey}?thread=${encodeURIComponent(m.threadKey)}` : m.projectKey ? `/chats/${m.projectKey}` : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
function MessageItem({ m, q, back, showThread, masterView, mine = false }: { m: ChatMessageView; q?: { q: Question; taskStatus: string | null; taskKey: string | null }; back: string; showThread: boolean; masterView: boolean; mine?: boolean }) {
|
async function MessageItem({ m, q, back, showThread, masterView, mine = false, files, agentName, superadmin, gitea }: { files?: AttachmentView[]; m: ChatMessageView; q?: { q: Question; taskStatus: string | null; taskKey: string | null }; back: string; showThread: boolean; masterView: boolean; mine?: boolean; agentName: string | null; superadmin: boolean; gitea: string }) {
|
||||||
|
const t = await getT();
|
||||||
const where = (showThread || masterView) && (m.threadTitle || (masterView && m.projectKey));
|
const where = (showThread || masterView) && (m.threadTitle || (masterView && m.projectKey));
|
||||||
|
// An event is the factory's doing even when a person's press caused it (the event's actor).
|
||||||
|
const person = m.authorKind === "user" && m.kind === "user";
|
||||||
|
const agentLabel = m.authorKind === "agent" ? (m.authorLogin ? t.role(m.authorLogin) : agentName) : null;
|
||||||
|
const link = messageLink(m.url, superadmin, gitea);
|
||||||
const href = threadHref(m);
|
const href = threadHref(m);
|
||||||
const label = [masterView && m.projectKey ? m.projectKey : null, m.threadTitle].filter(Boolean).join(" · ");
|
const label = [masterView && m.projectKey ? m.projectKey : null, m.threadTitle ? t.text(m.threadTitle) : null].filter(Boolean).join(" · ");
|
||||||
const head = (
|
const head = (
|
||||||
<div className="flex flex-wrap items-center gap-x-2 gap-y-0.5 text-xs text-muted-foreground">
|
<div className="flex flex-wrap items-center gap-x-2 gap-y-0.5 text-xs text-muted-foreground">
|
||||||
{m.authorKind === "user" ? <UserIcon className="size-3.5" /> : m.authorKind === "agent" ? (m.authorLogin ? null : <Bot className="size-3.5" />) : <MessagesSquare className="size-3.5" />}
|
{/* PEP-207: who speaks — a person by login, an agent by its name and icon; events always come from the factory. */}
|
||||||
{m.authorKind === "agent" && m.authorLogin ? (
|
{person ? <UserIcon className="size-3.5" /> : agentLabel ? null : m.authorKind === "agent" ? <Bot className="size-3.5" /> : <MessagesSquare className="size-3.5" />}
|
||||||
<AgentBadge name={m.authorLogin} className="text-foreground" />
|
{agentLabel ? (
|
||||||
|
<AgentBadge name={agentLabel} className="text-foreground" />
|
||||||
) : (
|
) : (
|
||||||
<span className="font-medium text-foreground">{m.authorKind === "user" ? (mine ? "вы" : (m.authorLogin ?? "?")) : m.authorKind === "agent" ? "агент" : "Peppa FACTORY"}</span>
|
<span className="font-medium text-foreground">{person ? (mine ? t("вы") : (m.authorLogin ?? "?")) : m.authorKind === "agent" ? t("агент") : PRODUCT_NAME}</span>
|
||||||
)}
|
)}
|
||||||
{m.via === "telegram" && <span title="из Telegram">· Telegram</span>}
|
{m.via === "telegram" && <span title={t("из Telegram")}>· Telegram</span>}
|
||||||
{where && href && (
|
{where && href && (
|
||||||
<Link href={href} className="max-w-full truncate">
|
<Link href={href} className="max-w-full truncate">
|
||||||
🧵 {label}
|
🧵 {label}
|
||||||
</Link>
|
</Link>
|
||||||
)}
|
)}
|
||||||
<span className="ml-auto font-mono">{ago(m.createdAt)}</span>
|
{/* PEP-151: the same event in a row is one line with a counter and the time of the last one. */}
|
||||||
|
{!q && m.repeats > 0 && <span className="rounded-full border px-1.5 font-mono tabular-nums" title={t("Повторов: {n}", { n: m.repeats })}>×{m.repeats + 1}</span>}
|
||||||
|
<span className="ml-auto font-mono">{q ? ago(m.createdAt, t) : ago(m.updatedAt ?? m.createdAt, t)}</span>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
if (q) {
|
if (q) {
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col gap-1">
|
<div className="flex flex-col gap-1">
|
||||||
{head}
|
{head}
|
||||||
<QuestionCard q={q.q} taskKey={q.taskKey} taskStatus={q.taskStatus} back={back} compact />
|
<QuestionCard q={q.q} taskKey={q.taskKey} taskStatus={q.taskStatus} back={back} compact clean={!superadmin} />
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
// PEP-152: a message of an agent or of the factory takes at most five lines; the rest and the
|
||||||
|
// technical details open under «Подробнее». People's messages are shown whole.
|
||||||
|
// PEP-139: free text inside is marked — `t.text` translates only the factory's phrases around it.
|
||||||
|
const shown = m.kind === "user" ? { main: m.authorKind === "agent" ? cleanText(t.role(m.text), superadmin, gitea) : m.text, more: null } : splitForDisplay(cleanText(t.text(m.text), superadmin, gitea), m.details ? t.text(m.details) : null);
|
||||||
return (
|
return (
|
||||||
<article className={cn("flex flex-col gap-1 rounded-lg border bg-card px-3 py-2", m.kind === "user" && "border-primary/30 bg-primary/5", m.kind === "system" && "border-dashed bg-transparent")}>
|
<article className={cn("flex flex-col gap-1 rounded-lg border bg-card px-3 py-2", mine && "border-primary/30 bg-primary/10", m.kind === "system" && "border-dashed bg-transparent")}>
|
||||||
{head}
|
{head}
|
||||||
<p className="m-0 text-sm break-words whitespace-pre-wrap">{linkify(m.text)}</p>
|
<p data-message-main className="m-0 text-sm break-words whitespace-pre-wrap">{linkify(shown.main)}</p>
|
||||||
{m.url && (
|
{shown.more && (
|
||||||
<a href={m.url} target="_blank" rel="noreferrer" className="truncate text-xs">
|
<details data-message-details className="text-xs text-muted-foreground">
|
||||||
{m.url}
|
<summary className="cursor-pointer">{t("Подробнее")}</summary>
|
||||||
|
<p className="m-0 mt-1 max-h-72 overflow-auto break-words whitespace-pre-wrap">{linkify(shown.more)}</p>
|
||||||
|
</details>
|
||||||
|
)}
|
||||||
|
<Attachments files={files} />
|
||||||
|
{link && (
|
||||||
|
<a href={link} target={link.startsWith("/") ? undefined : "_blank"} rel="noreferrer" className="truncate text-xs">
|
||||||
|
{link.startsWith("/") ? t("Открыть") : link}
|
||||||
</a>
|
</a>
|
||||||
)}
|
)}
|
||||||
|
{/* PEP-153: a question is answered, not filed — the task is one press away. */}
|
||||||
|
{m.offer?.kind === "proposals" && <ProposalList items={m.offer.items ?? []} back={back} />}
|
||||||
|
{m.offer && m.offer.kind !== "proposals" && (
|
||||||
|
<form action={chatOfferAction} className="mt-1 flex flex-wrap gap-2">
|
||||||
|
<Hidden fields={{ messageId: m.id, back }} />
|
||||||
|
{m.offer.kind === "task" && (
|
||||||
|
<Button size="sm" variant="outline" name="choice" value="task">
|
||||||
|
{t("📝 Завести как задачу")}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
{m.offer.kind === "choice" && (
|
||||||
|
<>
|
||||||
|
<Button size="sm" variant="outline" name="choice" value="answer">
|
||||||
|
{t("💬 Ответить")}
|
||||||
|
</Button>
|
||||||
|
<Button size="sm" variant="outline" name="choice" value="task">
|
||||||
|
{t("📝 Завести задачу")}
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{/* PEP-198: the analyst's suggestions are filed only by this press. */}
|
||||||
|
{m.offer.kind === "stories" && (
|
||||||
|
<div data-suggested-stories className="flex w-full flex-col gap-2">
|
||||||
|
{(m.offer.stories ?? []).map((s, i) => (
|
||||||
|
<div key={i} className="flex flex-col gap-1 rounded-md border bg-card p-2 text-sm">
|
||||||
|
<span className="font-medium break-words">{s.title}</span>
|
||||||
|
{s.description && <span className="line-clamp-4 text-xs break-words whitespace-pre-wrap text-muted-foreground">{s.description}</span>}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
<Button size="sm" name="choice" value="stories" className="min-h-11">
|
||||||
|
{t("Завести задачи")}
|
||||||
|
</Button>
|
||||||
|
<Button size="sm" variant="outline" name="choice" value="cancel" className="min-h-11">
|
||||||
|
{t("Не надо")}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{m.offer.kind === "draft" && (
|
||||||
|
<>
|
||||||
|
<Button size="sm" name="choice" value="create">
|
||||||
|
{t("✅ Создать")}
|
||||||
|
</Button>
|
||||||
|
<Button size="sm" variant="outline" name="choice" value="cancel">
|
||||||
|
{t("✖️ Отмена")}
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</form>
|
||||||
|
)}
|
||||||
</article>
|
</article>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,9 +1,10 @@
|
|||||||
"use server";
|
"use server";
|
||||||
// «Чаты» (PEP-62): a message into a chat/thread, Telegram group link/unlink. Access — chatForUser.
|
// «Чаты» (PEP-62): a message into a chat/thread, Telegram group link/unlink. Access — chatForUser.
|
||||||
|
|
||||||
import { chatForUser, createChatLinkCode, isSuperadmin, PeppaError, unlinkChat } from "@peppa/core";
|
import { parseAttachmentIds, chatForUser, createChatLinkCode, isSuperadmin, markDiscussionRead, markThreadRead, PeppaError, THREAD_KEY, unlinkChat } from "@peppa/core";
|
||||||
import { postToChat } from "@peppa/runner";
|
import { postToChat, resolveChatOffer, type ChatOfferChoice } from "@peppa/runner";
|
||||||
import { loadEnv } from "@peppa/shared";
|
import { loadEnv } from "@peppa/shared";
|
||||||
|
import { m } from "@peppa/shared/i18n";
|
||||||
import { revalidatePath } from "next/cache";
|
import { revalidatePath } from "next/cache";
|
||||||
import { redirect } from "next/navigation";
|
import { redirect } from "next/navigation";
|
||||||
import { asWebActor, requireUser } from "@/lib/auth";
|
import { asWebActor, requireUser } from "@/lib/auth";
|
||||||
@ -17,7 +18,7 @@ async function attempt(f: FormData, fn: () => Promise<string | void>): Promise<n
|
|||||||
try {
|
try {
|
||||||
target = (await fn()) || target;
|
target = (await fn()) || target;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
const msg = e instanceof PeppaError ? e.message : `Ошибка: ${(e as Error).message}`;
|
const msg = e instanceof PeppaError ? e.message : m("Ошибка: {message}", { message: (e as Error).message });
|
||||||
const [path, query] = target.split("?");
|
const [path, query] = target.split("?");
|
||||||
const params = new URLSearchParams(query);
|
const params = new URLSearchParams(query);
|
||||||
params.set("error", msg.slice(0, 300));
|
params.set("error", msg.slice(0, 300));
|
||||||
@ -31,7 +32,29 @@ export async function postChatAction(f: FormData) {
|
|||||||
const user = asWebActor(await requireUser());
|
const user = asWebActor(await requireUser());
|
||||||
await attempt(f, async () => {
|
await attempt(f, async () => {
|
||||||
const thread = str(f, "thread");
|
const thread = str(f, "thread");
|
||||||
await postToChat(db, user, { chatId: Number(str(f, "chatId")), threadKey: thread || null, text: String(f.get("text") ?? ""), via: "web" });
|
await postToChat(db, user, { chatId: Number(str(f, "chatId")), threadKey: thread || null, text: String(f.get("text") ?? ""), via: "web", attachmentIds: parseAttachmentIds(f.getAll("attachment")) });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PEP-228: messages drawn in place on an open chat page are read — the discussion (thread null)
|
||||||
|
* or one thread. No redirect: the page stays as it is.
|
||||||
|
*/
|
||||||
|
export async function markChatReadAction(chatId: number, thread: string | null): Promise<void> {
|
||||||
|
const user = await requireUser();
|
||||||
|
const chat = await chatForUser(db, user, Number(chatId)).catch(() => null);
|
||||||
|
if (!chat || chat.kind !== "project") return;
|
||||||
|
if (thread == null) await markDiscussionRead(db, user.id, chat.id);
|
||||||
|
else if (typeof thread === "string" && THREAD_KEY.test(thread)) await markThreadRead(db, user.id, chat.id, thread);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** PEP-153: a button under a chat message — «Завести как задачу», «Ответить», «Создать», «Отмена». */
|
||||||
|
export async function chatOfferAction(f: FormData) {
|
||||||
|
const user = asWebActor(await requireUser());
|
||||||
|
await attempt(f, async () => {
|
||||||
|
const choice = str(f, "choice");
|
||||||
|
if (!["task", "answer", "create", "cancel", "stories"].includes(choice)) throw new PeppaError(m("Эта кнопка уже не работает. Напишите сообщение ещё раз."));
|
||||||
|
await resolveChatOffer(db, user, Number(str(f, "messageId")), choice as ChatOfferChoice);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -40,7 +63,7 @@ export async function linkChatAction(f: FormData) {
|
|||||||
const user = asWebActor(await requireUser());
|
const user = asWebActor(await requireUser());
|
||||||
await attempt(f, async () => {
|
await attempt(f, async () => {
|
||||||
const token = loadEnv().TELEGRAM_BOT_TOKEN;
|
const token = loadEnv().TELEGRAM_BOT_TOKEN;
|
||||||
if (!token) throw new PeppaError("Telegram пока не настроен. Напишите в поддержку Peppa FACTORY.");
|
if (!token) throw new PeppaError(m("Telegram пока не настроен. Напишите в поддержку FORGE."));
|
||||||
const chat = await chatForUser(db, user, Number(str(f, "chatId")));
|
const chat = await chatForUser(db, user, Number(str(f, "chatId")));
|
||||||
// PEP-109: the group is linked through the user's own bot; the platform's bot is the
|
// PEP-109: the group is linked through the user's own bot; the platform's bot is the
|
||||||
// superadmin's (PEP-106) and serves only a superadmin who has no bot of their own.
|
// superadmin's (PEP-106) and serves only a superadmin who has no bot of their own.
|
||||||
|
|||||||
@ -1,6 +1,6 @@
|
|||||||
import Link from "next/link";
|
import Link from "@/components/Link";
|
||||||
import { ArrowRight, MessagesSquare } from "lucide-react";
|
import { ArrowRight, MessagesSquare } from "lucide-react";
|
||||||
import { chatOverview, syncChats } from "@peppa/core";
|
import { chatOverview, isRoleName, syncChats } from "@peppa/core";
|
||||||
import { LiveRefresh } from "@/components/LiveRefresh";
|
import { LiveRefresh } from "@/components/LiveRefresh";
|
||||||
import { AgentBadge } from "@/components/AgentBadge";
|
import { AgentBadge } from "@/components/AgentBadge";
|
||||||
import { QuestionCard } from "@/components/cards";
|
import { QuestionCard } from "@/components/cards";
|
||||||
@ -9,8 +9,13 @@ import { Workspace } from "@/components/Workspace";
|
|||||||
import { requireUser } from "@/lib/auth";
|
import { requireUser } from "@/lib/auth";
|
||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
import { inbox } from "@/lib/queries";
|
import { inbox } from "@/lib/queries";
|
||||||
|
import { getT } from "@/lib/i18n";
|
||||||
|
|
||||||
|
export async function generateMetadata() {
|
||||||
|
const t = await getT();
|
||||||
|
return { title: t("Чаты — FORGE") };
|
||||||
|
}
|
||||||
|
|
||||||
export const metadata = { title: "Чаты — Peppa FACTORY" };
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* «Чаты» (PEP-117): the overview a product manager lands on — what waits for their answer and
|
* «Чаты» (PEP-117): the overview a product manager lands on — what waits for their answer and
|
||||||
@ -18,6 +23,7 @@ export const metadata = { title: "Чаты — Peppa FACTORY" };
|
|||||||
*/
|
*/
|
||||||
export default async function Chats({ searchParams }: { searchParams: Promise<{ error?: string }> }) {
|
export default async function Chats({ searchParams }: { searchParams: Promise<{ error?: string }> }) {
|
||||||
const user = await requireUser();
|
const user = await requireUser();
|
||||||
|
const t = await getT();
|
||||||
const { error } = await searchParams;
|
const { error } = await searchParams;
|
||||||
await syncChats(db).catch((e) => console.error("syncChats", e));
|
await syncChats(db).catch((e) => console.error("syncChats", e));
|
||||||
const [cards, waiting] = await Promise.all([chatOverview(db, user), inbox(user.id)]);
|
const [cards, waiting] = await Promise.all([chatOverview(db, user), inbox(user.id)]);
|
||||||
@ -25,20 +31,20 @@ export default async function Chats({ searchParams }: { searchParams: Promise<{
|
|||||||
<Workspace>
|
<Workspace>
|
||||||
<LiveRefresh scope="chats" />
|
<LiveRefresh scope="chats" />
|
||||||
<Flash error={error} />
|
<Flash error={error} />
|
||||||
<PageHeader title="Чаты">Здесь вы разговариваете с фабрикой: отвечаете агентам и пишете аналитику своего проекта — что узнать или что сделать.</PageHeader>
|
<PageHeader title={t("Чаты")}>{t("Здесь вы разговариваете с фабрикой: отвечаете агентам и пишете аналитику своего проекта — что узнать или что сделать.")}</PageHeader>
|
||||||
|
|
||||||
<Section title="Ждут вашего ответа" count={waiting.length}>
|
<Section title={t("Ждут вашего ответа")} count={waiting.length}>
|
||||||
{waiting.length === 0 ? (
|
{waiting.length === 0 ? (
|
||||||
<Empty>Сейчас от вас ничего не нужно — агенты работают сами.</Empty>
|
<Empty>{t("Сейчас от вас ничего не нужно — агенты работают сами.")}</Empty>
|
||||||
) : (
|
) : (
|
||||||
waiting.map((q) => <QuestionCard key={q.id} q={q} taskKey={q.taskKey} taskStatus={q.taskStatus} back="/chats" />)
|
waiting.map((q) => <QuestionCard key={q.id} q={q} taskKey={q.taskKey} taskStatus={q.taskStatus} back="/chats" />)
|
||||||
)}
|
)}
|
||||||
</Section>
|
</Section>
|
||||||
|
|
||||||
<Section title="Ваши проекты" count={cards.length}>
|
<Section title={t("Ваши проекты")} count={cards.length}>
|
||||||
{cards.length === 0 ? (
|
{cards.length === 0 ? (
|
||||||
<Empty>
|
<Empty>
|
||||||
Проектов пока нет. <Link href="/projects/new">Создайте проект</Link> — и у него появится чат с аналитиком.
|
{t("Проектов пока нет.")} <Link href="/projects/new">{t("Создайте проект")}</Link> {t("— и у него появится чат с аналитиком.")}
|
||||||
</Empty>
|
</Empty>
|
||||||
) : (
|
) : (
|
||||||
<ul className="m-0 grid list-none gap-3 p-0 md:grid-cols-2">
|
<ul className="m-0 grid list-none gap-3 p-0 md:grid-cols-2">
|
||||||
@ -48,22 +54,22 @@ export default async function Chats({ searchParams }: { searchParams: Promise<{
|
|||||||
<span className="flex items-center gap-2">
|
<span className="flex items-center gap-2">
|
||||||
<span className="rounded bg-muted px-1.5 font-mono text-xs text-primary">{c.key}</span>
|
<span className="rounded bg-muted px-1.5 font-mono text-xs text-primary">{c.key}</span>
|
||||||
<span className="min-w-0 flex-1 truncate font-medium">{c.name}</span>
|
<span className="min-w-0 flex-1 truncate font-medium">{c.name}</span>
|
||||||
{c.unread > 0 && <span className="rounded-full bg-info px-2 text-xs font-semibold text-background" title="новые сообщения">{c.unread} нов.</span>}
|
{c.unread > 0 && <span className="rounded-full bg-info px-2 text-xs font-semibold text-background" title={t("новые сообщения")}>{t("{n} нов.", { n: c.unread })}</span>}
|
||||||
{c.open > 0 && <span className="rounded-full bg-primary px-2 text-xs font-semibold text-primary-foreground" title="агенты ждут вашего ответа">ждут ответа: {c.open}</span>}
|
{c.open > 0 && <span className="rounded-full bg-primary px-2 text-xs font-semibold text-primary-foreground" title={t("агенты ждут вашего ответа")}>{t("ждут ответа: {n}", { n: c.open })}</span>}
|
||||||
</span>
|
</span>
|
||||||
{c.last ? (
|
{c.last ? (
|
||||||
<span className="flex min-w-0 flex-col gap-0.5 text-sm">
|
<span className="flex min-w-0 flex-col gap-0.5 text-sm">
|
||||||
<span className="flex items-center gap-1.5 text-xs text-muted-foreground">
|
<span className="flex items-center gap-1.5 text-xs text-muted-foreground">
|
||||||
{c.last.who === "Аналитик" ? <AgentBadge name="Аналитик" /> : <span>{c.last.mine ? "вы" : c.last.who}</span>}
|
{c.last.agent ? <AgentBadge name={c.last.who} role={isRoleName(c.last.who)} /> : <span>{c.last.mine ? t("вы") : c.last.who}</span>}
|
||||||
<span>· {ago(c.last.at)}</span>
|
<span>· {ago(c.last.at, t)}</span>
|
||||||
</span>
|
</span>
|
||||||
<span className="line-clamp-2 text-muted-foreground">{c.last.text}</span>
|
<span className="line-clamp-2 text-muted-foreground">{c.last.system ? t.text(c.last.text) : c.last.agent ? t.role(c.last.text) : c.last.text}</span>
|
||||||
</span>
|
</span>
|
||||||
) : (
|
) : (
|
||||||
<span className="text-sm text-muted-foreground">Здесь пока тихо. Спросите аналитика, что с проектом, или опишите новую задачу.</span>
|
<span className="text-sm text-muted-foreground">{t("Здесь пока тихо. Спросите аналитика, что с проектом, или опишите новую задачу.")}</span>
|
||||||
)}
|
)}
|
||||||
<span className="mt-auto inline-flex items-center gap-1.5 text-sm font-medium text-primary">
|
<span className="mt-auto inline-flex items-center gap-1.5 text-sm font-medium text-primary">
|
||||||
<MessagesSquare className="size-4" /> Написать аналитику <ArrowRight className="size-3.5" />
|
<MessagesSquare className="size-4" /> {t("Написать аналитику")} <ArrowRight className="size-3.5" />
|
||||||
</span>
|
</span>
|
||||||
</Link>
|
</Link>
|
||||||
</li>
|
</li>
|
||||||
@ -73,7 +79,7 @@ export default async function Chats({ searchParams }: { searchParams: Promise<{
|
|||||||
</Section>
|
</Section>
|
||||||
|
|
||||||
<p className="mt-6 text-sm text-muted-foreground">
|
<p className="mt-6 text-sm text-muted-foreground">
|
||||||
Нужна история? <Link href="/chats/master">Все события по вашим проектам</Link> — что делали агенты, обновления продукта и сбои, справочно.
|
{t("Нужна история?")} <Link href="/chats/master">{t("Все события по вашим проектам")}</Link> {t("— что делали агенты, обновления продукта и сбои, справочно.")}
|
||||||
</p>
|
</p>
|
||||||
</Workspace>
|
</Workspace>
|
||||||
);
|
);
|
||||||
|
|||||||
36
apps/web/app/(app)/connections/oauth/callback/route.ts
Normal file
36
apps/web/app/(app)/connections/oauth/callback/route.ts
Normal file
@ -0,0 +1,36 @@
|
|||||||
|
import { checkConnection, completeConnectionOAuth, CONNECTION_OAUTH_COOKIE, OAUTH_ERROR_TEXT, PeppaError } from "@peppa/core";
|
||||||
|
import { cookies } from "next/headers";
|
||||||
|
import { NextResponse, type NextRequest } from "next/server";
|
||||||
|
import { connOAuthCookieOptions, currentUser, publicOrigin } from "@/lib/auth";
|
||||||
|
import { db } from "@/lib/db";
|
||||||
|
import { m } from "@peppa/shared/i18n";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PEP-252: the service sends the browser back here with code and state. The state must equal this
|
||||||
|
* browser's cookie and the flow must belong to the person signed in now; then the code is
|
||||||
|
* exchanged and the connection checked. Code and state never stay in the address: 303 to
|
||||||
|
* /connections without them.
|
||||||
|
*/
|
||||||
|
export async function GET(req: NextRequest) {
|
||||||
|
const origin = await publicOrigin();
|
||||||
|
const jar = await cookies();
|
||||||
|
const cookieState = jar.get(CONNECTION_OAUTH_COOKIE)?.value ?? "";
|
||||||
|
const q = req.nextUrl.searchParams;
|
||||||
|
const go = (path: string) => {
|
||||||
|
const res = NextResponse.redirect(`${origin}${path}`, 303);
|
||||||
|
res.cookies.set(CONNECTION_OAUTH_COOKIE, "", connOAuthCookieOptions(0));
|
||||||
|
return res;
|
||||||
|
};
|
||||||
|
const fail = (msg: string) => go(`/connections?error=${encodeURIComponent(msg)}`);
|
||||||
|
const user = await currentUser();
|
||||||
|
if (!user) return go("/login");
|
||||||
|
if (q.get("error")) return fail(q.get("error") === "access_denied" ? OAUTH_ERROR_TEXT.denied : OAUTH_ERROR_TEXT.failed);
|
||||||
|
try {
|
||||||
|
const r = await completeConnectionOAuth(db, user.id, { state: q.get("state") ?? "", code: q.get("code") ?? "", cookieState });
|
||||||
|
const chk = await checkConnection(db, user.id, r.connectionId).catch(() => null);
|
||||||
|
const word = !chk ? "down" : chk.status;
|
||||||
|
return go(`/connections?${r.created ? "created" : "checked"}=${r.connectionId}&check=${word}&signed=1#c${r.connectionId}`);
|
||||||
|
} catch (e) {
|
||||||
|
return fail(e instanceof PeppaError ? e.message : m("Не удалось войти в сервис"));
|
||||||
|
}
|
||||||
|
}
|
||||||
32
apps/web/app/(app)/connections/oauth/start/route.ts
Normal file
32
apps/web/app/(app)/connections/oauth/start/route.ts
Normal file
@ -0,0 +1,32 @@
|
|||||||
|
import { CONNECTION_OAUTH_COOKIE, PeppaError, startConnectionOAuth } from "@peppa/core";
|
||||||
|
import { NextResponse, type NextRequest } from "next/server";
|
||||||
|
import { connOAuthCookieOptions, currentUser, publicOrigin } from "@/lib/auth";
|
||||||
|
import { db } from "@/lib/db";
|
||||||
|
import { m } from "@peppa/shared/i18n";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PEP-252: «Войти через Google / GitHub» in «Подключения» (POST form: catalogId + level, or
|
||||||
|
* connectionId for «Войти заново») → 303 to the service's sign-in page. The state goes into an
|
||||||
|
* httpOnly cookie of this browser; the callback must bring the same state back.
|
||||||
|
*/
|
||||||
|
export async function POST(req: NextRequest) {
|
||||||
|
const origin = await publicOrigin();
|
||||||
|
const form = await req.formData().catch(() => null);
|
||||||
|
const fail = (msg: string) => NextResponse.redirect(`${origin}/connections?error=${encodeURIComponent(msg)}#add`, 303);
|
||||||
|
const user = await currentUser();
|
||||||
|
if (!user) return NextResponse.redirect(`${origin}/login`, 303);
|
||||||
|
try {
|
||||||
|
const connectionId = Number(form?.get("connectionId") ?? "");
|
||||||
|
const flow = await startConnectionOAuth(db, user.id, {
|
||||||
|
catalogId: String(form?.get("catalogId") ?? "") || null,
|
||||||
|
connectionId: Number.isInteger(connectionId) && connectionId > 0 ? connectionId : null,
|
||||||
|
level: String(form?.get("level") ?? "") || null,
|
||||||
|
redirectUri: `${origin}/connections/oauth/callback`,
|
||||||
|
});
|
||||||
|
const res = NextResponse.redirect(flow.url, 303);
|
||||||
|
res.cookies.set(CONNECTION_OAUTH_COOKIE, flow.state, connOAuthCookieOptions(600));
|
||||||
|
return res;
|
||||||
|
} catch (e) {
|
||||||
|
return fail(e instanceof PeppaError ? e.message : m("Не удалось начать вход в сервис"));
|
||||||
|
}
|
||||||
|
}
|
||||||
734
apps/web/app/(app)/connections/page.tsx
Normal file
734
apps/web/app/(app)/connections/page.tsx
Normal file
@ -0,0 +1,734 @@
|
|||||||
|
import Link from "@/components/Link";
|
||||||
|
import { ExternalLink, PlugZap, Search } from "lucide-react";
|
||||||
|
import {
|
||||||
|
CATALOG_KIND_TEXT,
|
||||||
|
CATALOG_KINDS,
|
||||||
|
catalogService,
|
||||||
|
CONNECTION_CHECK_TEXT,
|
||||||
|
CONNECTION_REASON_TEXT,
|
||||||
|
connectionJournal,
|
||||||
|
DEFAULT_GRANT_TERM,
|
||||||
|
defaultIdleRevokeHours,
|
||||||
|
GRANT_TERM_TEXT,
|
||||||
|
GRANT_TERMS,
|
||||||
|
IDLE_HOURS_CHOICES,
|
||||||
|
serverTimezone,
|
||||||
|
JOURNAL_VERIFY_SCRIPT,
|
||||||
|
grantableAgents,
|
||||||
|
listConnections,
|
||||||
|
listUserProjects,
|
||||||
|
ownerAccessRequests,
|
||||||
|
oauthOffer,
|
||||||
|
scopeLabel,
|
||||||
|
searchCatalog,
|
||||||
|
type CatalogKind,
|
||||||
|
type CatalogService,
|
||||||
|
type ConnectionGrantView,
|
||||||
|
type ConnectionLogView,
|
||||||
|
type ConnectionReason,
|
||||||
|
type ConnectionView,
|
||||||
|
type GrantMode,
|
||||||
|
type GatewayProtocol,
|
||||||
|
GATEWAY_PROTOCOLS,
|
||||||
|
} from "@peppa/core";
|
||||||
|
import { AccessRequestList } from "@/components/AccessRequests";
|
||||||
|
import { Hidden } from "@/components/cards";
|
||||||
|
import { intlLocale } from "@peppa/shared/i18n";
|
||||||
|
import { ago, Empty, Flash, Notice, PageHeader, Section } from "@/components/common";
|
||||||
|
import { Badge } from "@/components/ui/badge";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Card } from "@/components/ui/card";
|
||||||
|
import { Input, Textarea } from "@/components/ui/input";
|
||||||
|
import { Workspace } from "@/components/Workspace";
|
||||||
|
import { requireUser, uiMode } from "@/lib/auth";
|
||||||
|
import { db } from "@/lib/db";
|
||||||
|
import { getT } from "@/lib/i18n";
|
||||||
|
import { m, type Translator } from "@peppa/shared/i18n";
|
||||||
|
import { checkConnectionAction, createConnectionAction, decideIdleGrantAction, deleteConnectionAction, extendGrantAction, grantConnectionAction, replaceConnectionSecretAction, resetHostKeyAction, revokeConnectionAction, revokeGrantAction, setConnectionIdleAction } from "../actions";
|
||||||
|
|
||||||
|
export async function generateMetadata() {
|
||||||
|
const t = await getT();
|
||||||
|
return { title: t("Подключения — FORGE") };
|
||||||
|
}
|
||||||
|
|
||||||
|
type Params = { error?: string; created?: string; checked?: string; check?: string; signed?: string; revoked?: string; remote?: string; service?: string; q?: string; kind?: string };
|
||||||
|
|
||||||
|
const SELECT = "h-9 rounded-md border border-input bg-background px-2 text-sm";
|
||||||
|
const BACK = "/connections";
|
||||||
|
|
||||||
|
function Decision({ row, t }: { row: ConnectionLogView; t: Translator }) {
|
||||||
|
// PEP-254: the call is written before the service answers; no result after a while — a crash in the middle.
|
||||||
|
if (row.state === "running") return <Badge variant="outline">{t("выполняется")}</Badge>;
|
||||||
|
if (row.state === "unfinished") return <Badge variant="warn">{t("начато, итога нет")}</Badge>;
|
||||||
|
if (row.decision === "allowed") return <Badge variant="ok">{t("разрешено")}</Badge>;
|
||||||
|
if (row.decision === "denied") return <Badge variant="danger">{t("запрещено")}</Badge>;
|
||||||
|
return <Badge variant="warn">{t("не выполнено")}</Badge>;
|
||||||
|
}
|
||||||
|
|
||||||
|
const reasonText = (r: string | null, t: Translator) => (r && r in CONNECTION_REASON_TEXT ? t.text(CONNECTION_REASON_TEXT[r as ConnectionReason]) : "");
|
||||||
|
const kindText = (k: CatalogKind, t: Translator) => t.text(CATALOG_KIND_TEXT[k]);
|
||||||
|
|
||||||
|
/** «ключ работает» / «ключ не подходит» / «сервис не отвечает» / «ещё не проверялся». */
|
||||||
|
function KeyState({ c, t }: { c: ConnectionView; t: Translator }) {
|
||||||
|
if (c.status === "relogin") return <Badge variant="danger">{t("нужно войти заново")}</Badge>;
|
||||||
|
if (c.status !== "active") return <Badge variant="danger">{t("доступ отозван")}</Badge>;
|
||||||
|
// PEP-252: a sign-in connection has no key to speak of.
|
||||||
|
if (c.authKind === "oauth") {
|
||||||
|
if (!c.checkStatus) return <Badge variant="outline">{t("вход ещё не проверялся")}</Badge>;
|
||||||
|
return c.checkStatus === "ok" ? <Badge variant="ok">{t("вход работает")}</Badge> : c.checkStatus === "bad_key" ? <Badge variant="danger">{t("сервис не пускает FORGE")}</Badge> : <Badge variant="warn">{t.text(CONNECTION_CHECK_TEXT.down)}</Badge>;
|
||||||
|
}
|
||||||
|
if (!c.checkStatus) return <Badge variant="outline">{t("ключ ещё не проверялся")}</Badge>;
|
||||||
|
const text = t.text(CONNECTION_CHECK_TEXT[c.checkStatus]);
|
||||||
|
return <Badge variant={c.checkStatus === "ok" ? "ok" : c.checkStatus === "bad_key" || c.checkStatus === "host_key" ? "danger" : "warn"}>{text}</Badge>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function modeText(m: GrantMode, t: Translator): string {
|
||||||
|
return m === "auto" ? t("сразу") : m === "ask" ? t("спрашивать меня") : t("нет");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** «14:05 25.11» in the platform's time zone. */
|
||||||
|
function when(d: Date, t: Translator): string {
|
||||||
|
const loc = intlLocale(t.locale);
|
||||||
|
const tz = serverTimezone();
|
||||||
|
return `${d.toLocaleTimeString(loc, { hour: "2-digit", minute: "2-digit", timeZone: tz })} ${d.toLocaleDateString(loc, { day: "2-digit", month: "2-digit", timeZone: tz })}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** «5 ч» / «2 дн» — how soon the owner is asked about a grant without calls. */
|
||||||
|
function hoursLeft(d: Date, t: Translator): string {
|
||||||
|
const h = Math.max(0, Math.ceil((d.getTime() - Date.now()) / 3600_000));
|
||||||
|
return h < 48 ? t("{n} ч", { n: h }) : t("{n} дн", { n: Math.round(h / 24) });
|
||||||
|
}
|
||||||
|
|
||||||
|
function GrantLine({ g, engineer, t }: { g: ConnectionGrantView; engineer: boolean; t: Translator }) {
|
||||||
|
const ended = g.state !== "active";
|
||||||
|
return (
|
||||||
|
<li className="flex flex-col gap-1 rounded-md border bg-background/40 px-2.5 py-1.5">
|
||||||
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
|
<span className="font-medium">{g.projectKey}</span>
|
||||||
|
<span>· {g.agentName ? t("агент {name}", { name: g.agentName }) : t("любой агент проекта")}</span>
|
||||||
|
<span className="text-muted-foreground">
|
||||||
|
· {t("чтение: {mode}", { mode: modeText(g.readMode, t) })} · {t("запись: {mode}", { mode: modeText(g.writeMode, t) })}
|
||||||
|
</span>
|
||||||
|
{g.state === "expired" && <Badge variant="warn">{t("срок истёк")}</Badge>}
|
||||||
|
{g.state === "idle" && <Badge variant="warn">{t("снято: {n} ч без дела", { n: g.idleHours })}</Badge>}
|
||||||
|
{g.idleAskedAt && <Badge variant="warn">{t("не используется {n} ч — снять?", { n: g.idleHours })}</Badge>}
|
||||||
|
{engineer && g.operations.length > 0 && <span className="font-mono text-xs text-muted-foreground">{g.operations.join(", ")}</span>}
|
||||||
|
<div className="ml-auto flex gap-1">
|
||||||
|
{g.idleAskedAt && (
|
||||||
|
<>
|
||||||
|
<form action={decideIdleGrantAction}>
|
||||||
|
<Hidden fields={{ grantId: g.id, decision: "revoke", back: BACK }} />
|
||||||
|
<Button variant="default" size="sm">{t("Снять")}</Button>
|
||||||
|
</form>
|
||||||
|
<form action={decideIdleGrantAction}>
|
||||||
|
<Hidden fields={{ grantId: g.id, decision: "keep", back: BACK }} />
|
||||||
|
<Button variant="ghost" size="sm">{t("Оставить")}</Button>
|
||||||
|
</form>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{(ended || g.term !== "forever") && (
|
||||||
|
<form action={extendGrantAction}>
|
||||||
|
<Hidden fields={{ grantId: g.id, back: BACK }} />
|
||||||
|
<Button variant={ended ? "default" : "ghost"} size="sm">
|
||||||
|
{g.term === "forever" ? t("Вернуть") : t("Продлить на {term}", { term: t.text(GRANT_TERM_TEXT[g.term]) })}
|
||||||
|
</Button>
|
||||||
|
</form>
|
||||||
|
)}
|
||||||
|
<form action={revokeGrantAction}>
|
||||||
|
<Hidden fields={{ grantId: g.id, back: BACK }} />
|
||||||
|
<Button variant="ghost" size="sm">{t("Убрать")}</Button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-wrap gap-x-3 text-xs text-muted-foreground">
|
||||||
|
{!ended && <span>{g.expiresAt ? t("до {when}", { when: when(g.expiresAt, t) }) : t("до отзыва")}</span>}
|
||||||
|
{g.state === "expired" && g.expiresAt && <span>{t("действовало до {when}", { when: when(g.expiresAt, t) })}</span>}
|
||||||
|
{g.state === "idle" && g.endedAt && <span>{t("снято {ago}", { ago: ago(g.endedAt, t) })}</span>}
|
||||||
|
<span>{g.lastUsedAt ? t("последний вызов {ago}", { ago: ago(g.lastUsedAt, t) }) : t("вызовов ещё не было")}</span>
|
||||||
|
{g.idleAskAt && <span>{t("спросим вас о снятии через {left} без дела", { left: hoursLeft(g.idleAskAt, t) })}</span>}
|
||||||
|
</div>
|
||||||
|
</li>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function TermSelect({ t }: { t: Translator }) {
|
||||||
|
return (
|
||||||
|
<label className="flex flex-col gap-1 text-sm">
|
||||||
|
<span className="text-muted-foreground">{t("Срок")}</span>
|
||||||
|
<select name="term" defaultValue={DEFAULT_GRANT_TERM} className={SELECT}>
|
||||||
|
{GRANT_TERMS.map((term) => (
|
||||||
|
<option key={term} value={term}>
|
||||||
|
{t.text(GRANT_TERM_TEXT[term])}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function idleText(h: number, t: Translator): string {
|
||||||
|
return h === 0 ? t("не спрашивать") : h % 24 === 0 && h >= 48 ? t("{n} дн без дела", { n: h / 24 }) : t("{n} ч без дела", { n: h });
|
||||||
|
}
|
||||||
|
|
||||||
|
/** PEP-259: «Спрашивать, снять ли разрешение без дела, через …» of one connection. */
|
||||||
|
function IdleForm({ c, t }: { c: ConnectionView; t: Translator }) {
|
||||||
|
const def = defaultIdleRevokeHours();
|
||||||
|
return (
|
||||||
|
<form action={setConnectionIdleAction} className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
|
||||||
|
<Hidden fields={{ connectionId: c.id, back: BACK }} />
|
||||||
|
<span>{t("Спрашивать, снять ли разрешение, которым не пользуются:")}</span>
|
||||||
|
<select name="idleHours" defaultValue={c.idleRevokeHours == null ? "" : String(c.idleRevokeHours)} className="h-7 rounded-md border border-input bg-background px-1.5 text-xs" aria-label={t("Спрашивать о разрешении без дела")}>
|
||||||
|
<option value="">{t("как обычно — {text}", { text: idleText(def, t) })}</option>
|
||||||
|
{IDLE_HOURS_CHOICES.filter((h) => h !== def).map((h) => (
|
||||||
|
<option key={h} value={h}>
|
||||||
|
{idleText(h, t)}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
<Button variant="ghost" size="sm">{t("Сохранить")}</Button>
|
||||||
|
</form>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function ModeSelect({ name, label, def, t }: { name: string; label: string; def: GrantMode; t: Translator }) {
|
||||||
|
return (
|
||||||
|
<label className="flex flex-col gap-1 text-sm">
|
||||||
|
<span className="text-muted-foreground">{label}</span>
|
||||||
|
<select name={name} defaultValue={def} className={SELECT}>
|
||||||
|
<option value="auto">{t("Выполнять сразу")}</option>
|
||||||
|
<option value="ask">{t("Спрашивать меня")}</option>
|
||||||
|
<option value="off">{t("Не разрешать")}</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function GrantForm({ c, projects, agents, engineer, t }: { c: ConnectionView; projects: Array<{ id: number; key: string; name: string }>; agents: Array<{ id: number; name: string }>; engineer: boolean; t: Translator }) {
|
||||||
|
return (
|
||||||
|
<form action={grantConnectionAction} className="flex flex-col gap-3 rounded-md border border-dashed p-3">
|
||||||
|
<Hidden fields={{ connectionId: c.id, back: BACK }} />
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
<label className="flex flex-col gap-1 text-sm">
|
||||||
|
<span className="text-muted-foreground">{t("Проект")}</span>
|
||||||
|
<select name="projectId" required className={SELECT}>
|
||||||
|
{projects.map((p) => (
|
||||||
|
<option key={p.id} value={p.id}>
|
||||||
|
{p.key} — {p.name}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<label className="flex flex-col gap-1 text-sm">
|
||||||
|
<span className="text-muted-foreground">{t("Агент")}</span>
|
||||||
|
<select name="agentId" className={SELECT} defaultValue="">
|
||||||
|
<option value="">{t("Любой агент проекта")}</option>
|
||||||
|
{agents.map((a) => (
|
||||||
|
<option key={a.id} value={a.id}>
|
||||||
|
{a.name}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<ModeSelect name="readMode" label={t("Чтение")} def="auto" t={t} />
|
||||||
|
{/* PEP-251: changing a database and sending letters ask the owner by default. */}
|
||||||
|
<ModeSelect name="writeMode" label={t("Запись")} def={c.protocol === "postgres" || c.protocol === "mysql" || c.protocol === "mail" ? "ask" : "off"} t={t} />
|
||||||
|
<TermSelect t={t} />
|
||||||
|
</div>
|
||||||
|
<p className="m-0 text-xs text-muted-foreground">
|
||||||
|
{c.protocol === "http" ? t("Чтение — смотреть данные, ничего не меняя. Запись — создавать, менять, удалять и отправлять. «Спрашивать меня» пока означает отказ: подтверждение запросов появится позже.") : t.text(PROTOCOL_TEXT[c.protocol as GatewayProtocol].modes)}
|
||||||
|
{c.protocol !== "http" && <> {t("«Спрашивать меня» пока означает отказ: подтверждение запросов появится позже.")}</>}
|
||||||
|
</p>
|
||||||
|
{/* PEP-260: an «echo» operation can hand the key back in a form masking doesn't know. */}
|
||||||
|
{c.protocol === "http" && <p className="m-0 text-xs text-muted-foreground">{t("Не разрешайте агенту действия, которые возвращают присланное обратно: проверку, отладку, «кто я» с ключом. Через них сервис может показать агенту ключ.")}</p>}
|
||||||
|
{engineer && c.protocol === "http" && (
|
||||||
|
<details className="text-sm">
|
||||||
|
<summary className="cursor-pointer text-muted-foreground">{t("Тонкая настройка")}</summary>
|
||||||
|
<div className="mt-2 flex flex-col gap-1">
|
||||||
|
<Textarea name="operations" rows={2} placeholder={"GET /items\nPOST /orders"} aria-label={t("Разрешённые операции")} className="font-mono" spellCheck={false} />
|
||||||
|
<p className="m-0 text-xs text-muted-foreground">{t("По одной операции в строке: действие (GET — читать, POST — создавать, PUT и PATCH — менять, DELETE — удалять) и начало пути. «GET /items» разрешает читать /items и всё внутри, остальное запрещено.")}</p>
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
)}
|
||||||
|
<Button size="sm" className="self-start">{t("Разрешить")}</Button>
|
||||||
|
</form>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function ConnectionCard({ c, projects, agents, engineer, t }: { c: ConnectionView; projects: Array<{ id: number; key: string; name: string }>; agents: Array<{ id: number; name: string }>; engineer: boolean; t: Translator }) {
|
||||||
|
const active = c.status === "active";
|
||||||
|
const card = catalogService(c.catalogId);
|
||||||
|
// PEP-252: connected by signing in to the service — «Войти заново» instead of a new key.
|
||||||
|
const signIn = c.authKind === "oauth";
|
||||||
|
const provider = signIn ? oauthOffer(c.catalogId)?.providerName ?? null : null;
|
||||||
|
return (
|
||||||
|
<Card id={`c${c.id}`} className="flex flex-col gap-4 p-4">
|
||||||
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
|
<span className="text-base font-medium">{c.name}</span>
|
||||||
|
{card && card.name !== c.name && <Badge variant="outline">{card.name}</Badge>}
|
||||||
|
<KeyState c={c} t={t} />
|
||||||
|
{c.checkedAt && <span className="text-xs text-muted-foreground">{t("проверено {ago}", { ago: ago(c.checkedAt, t) })}</span>}
|
||||||
|
<span className="ml-auto text-xs text-muted-foreground">{c.lastUsedAt ? t("последний запрос {ago}", { ago: ago(c.lastUsedAt, t) }) : t("запросов ещё не было")}</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted-foreground">
|
||||||
|
<span className="truncate font-mono">{c.baseUrl}</span>
|
||||||
|
{engineer && <span>{t("имя для агентов: {slug}", { slug: c.slug })}</span>}
|
||||||
|
{signIn && c.oauthScopes.length > 0 && <span>{t("права: {scopes}", { scopes: c.oauthScopes.map(scopeLabel).join(", ") })}</span>}
|
||||||
|
{card && (
|
||||||
|
<a href={card.docsUrl} target="_blank" rel="noreferrer noopener" className="inline-flex items-center gap-1 underline-offset-2 hover:underline">
|
||||||
|
{t("Документация сервиса")} <ExternalLink className="size-3" />
|
||||||
|
</a>
|
||||||
|
)}
|
||||||
|
{engineer && typeof c.config?.hostKey === "string" && <span className="font-mono">{t("ключ сервера: {key}", { key: c.config.hostKey })}</span>}
|
||||||
|
{active && c.checkStatus === "host_key" && (
|
||||||
|
<form action={resetHostKeyAction}>
|
||||||
|
<Hidden fields={{ connectionId: c.id, back: BACK }} />
|
||||||
|
<Button size="sm" variant="destructive">{t("Принять новый ключ сервера")}</Button>
|
||||||
|
</form>
|
||||||
|
)}
|
||||||
|
{active && c.hasKey && (
|
||||||
|
<form action={checkConnectionAction} className="ml-auto">
|
||||||
|
<Hidden fields={{ connectionId: c.id, back: BACK }} />
|
||||||
|
<Button size="sm" variant="secondary">{t("Проверить")}</Button>
|
||||||
|
</form>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex flex-col gap-2">
|
||||||
|
<span className="text-sm font-medium">{t("Кому разрешено")}</span>
|
||||||
|
{c.grants.length === 0 ? (
|
||||||
|
<p className="m-0 text-sm text-muted-foreground">{t("Пока никому: агенты не могут пользоваться этим подключением.")}</p>
|
||||||
|
) : (
|
||||||
|
<ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm">
|
||||||
|
{c.grants.map((g) => (
|
||||||
|
<GrantLine key={g.id} g={g} engineer={engineer} t={t} />
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
{c.grants.length > 0 && <IdleForm c={c} t={t} />}
|
||||||
|
{active && projects.length > 0 && <GrantForm c={c} projects={projects} agents={agents} engineer={engineer} t={t} />}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex flex-wrap items-end gap-2 border-t pt-3">
|
||||||
|
{signIn ? (
|
||||||
|
<form action="/connections/oauth/start" method="post" className="flex flex-1 flex-wrap items-center gap-2">
|
||||||
|
<input type="hidden" name="connectionId" value={c.id} />
|
||||||
|
{provider ? (
|
||||||
|
<Button size="sm" variant={active ? "secondary" : "default"}>{t("Войти заново через {service}", { service: provider })}</Button>
|
||||||
|
) : (
|
||||||
|
<span className="text-xs text-muted-foreground">{t("Вход через этот сервис сейчас выключен в FORGE.")}</span>
|
||||||
|
)}
|
||||||
|
</form>
|
||||||
|
) : (
|
||||||
|
<form action={replaceConnectionSecretAction} className="flex flex-1 flex-wrap items-center gap-2" autoComplete="off">
|
||||||
|
<Hidden fields={{ connectionId: c.id, back: BACK }} />
|
||||||
|
{c.protocol === "ssh" ? (
|
||||||
|
<Textarea name="secret" required rows={1} placeholder={t("Новый пароль или ключ входа на сервер")} aria-label={t("Новый пароль или ключ")} className="max-w-xs font-mono" spellCheck={false} />
|
||||||
|
) : (
|
||||||
|
<Input name="secret" type="password" required placeholder={c.protocol !== "http" ? t("Новый пароль") : active ? t("Новый ключ доступа") : t("Новый ключ доступа, чтобы включить снова")} aria-label={t("Новый ключ доступа")} className="max-w-xs" autoComplete="new-password" />
|
||||||
|
)}
|
||||||
|
<Button size="sm" variant="secondary">{active ? t("Заменить ключ") : t("Включить снова")}</Button>
|
||||||
|
</form>
|
||||||
|
)}
|
||||||
|
{(active || c.status === "relogin") && (
|
||||||
|
<form action={revokeConnectionAction}>
|
||||||
|
<Hidden fields={{ connectionId: c.id, back: BACK }} />
|
||||||
|
<Button size="sm" variant="destructive">{t("Отозвать доступ")}</Button>
|
||||||
|
</form>
|
||||||
|
)}
|
||||||
|
<form action={deleteConnectionAction}>
|
||||||
|
<Hidden fields={{ connectionId: c.id, back: BACK }} />
|
||||||
|
<Button size="sm" variant="ghost">{t("Удалить")}</Button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function CheckNotice({ check, created, signed, t }: { check?: string; created: boolean; signed: boolean; t: Translator }) {
|
||||||
|
if (signed) {
|
||||||
|
// PEP-252: after signing in to the service.
|
||||||
|
const head = created ? t("Подключение сохранено. Доступ хранится зашифрованным: агенты и другие люди его не видят.") : t("Вы вошли заново, разрешения остались прежними.");
|
||||||
|
const tail = check === "ok" ? t("Вход работает. Теперь решите, кому из агентов его разрешить.") : check === "bad_key" ? t("Сервис не пустил FORGE: войдите заново и разрешите доступ.") : t("Сервис сейчас не отвечает. Подключение сохранено — проверьте позже кнопкой «Проверить».");
|
||||||
|
return (
|
||||||
|
<Notice>
|
||||||
|
{head} {tail}
|
||||||
|
</Notice>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const head = created ? t("Подключение сохранено. Ключ доступа больше не показывается никому.") : "";
|
||||||
|
const tail =
|
||||||
|
check === "ok"
|
||||||
|
? t("Ключ работает. Теперь решите, кому из агентов его разрешить.")
|
||||||
|
: check === "reachable"
|
||||||
|
? t("Сервис отвечает. Ключ проверится при первом запросе агента.")
|
||||||
|
: check === "bad_key"
|
||||||
|
? t("Сервис не принял ключ: проверьте, что скопировали его целиком, и замените ключ.")
|
||||||
|
: check === "down"
|
||||||
|
? t("Сервис сейчас не отвечает. Ключ сохранён — проверьте позже кнопкой «Проверить».")
|
||||||
|
: check === "host_key"
|
||||||
|
? t("Ключ сервера изменился. Если сервер не переустанавливали, не принимайте новый ключ и сообщите тому, кто его обслуживает.")
|
||||||
|
: "";
|
||||||
|
if (!head && !tail) return null;
|
||||||
|
return (
|
||||||
|
<Notice>
|
||||||
|
{head} {tail}
|
||||||
|
</Notice>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** PEP-251: databases, servers, storages and mailboxes — words for people (translated with t.text). */
|
||||||
|
const PROTOCOL_TEXT: Record<GatewayProtocol, { name: string; hint: string; modes: string; secret: string }> = {
|
||||||
|
postgres: { name: "PostgreSQL", hint: m("База данных"), modes: m("Чтение — смотреть таблицы, ничего не меняя. Запись — добавлять, менять и удалять данные."), secret: m("Пароль пользователя базы данных") },
|
||||||
|
mysql: { name: "MySQL / MariaDB", hint: m("База данных"), modes: m("Чтение — смотреть таблицы, ничего не меняя. Запись — добавлять, менять и удалять данные."), secret: m("Пароль пользователя базы данных") },
|
||||||
|
ssh: { name: m("Сервер (SSH)"), hint: m("Сервер и файлы на нём"), modes: m("Чтение — смотреть файлы в разрешённой папке. Запись — менять файлы и выполнять действия на сервере."), secret: m("Пароль или ключ входа на сервер") },
|
||||||
|
s3: { name: m("Хранилище S3"), hint: m("Файлы в облаке"), modes: m("Чтение — смотреть и скачивать файлы в разрешённой папке. Запись — загружать и удалять файлы."), secret: m("Секретный ключ доступа к хранилищу") },
|
||||||
|
mail: { name: m("Почтовый ящик"), hint: m("Чтение и отправка писем"), modes: m("Чтение — смотреть письма. Запись — отмечать, переносить и отправлять письма."), secret: m("Пароль почтового ящика (лучше — пароль приложения)") },
|
||||||
|
};
|
||||||
|
|
||||||
|
const PROTOCOL_KIND: Record<GatewayProtocol, CatalogKind> = { postgres: "data", mysql: "data", ssh: "cloud", s3: "cloud", mail: "mail" };
|
||||||
|
|
||||||
|
function Field({ name, label, placeholder, def, type, mono, required = true }: { name: string; label: string; placeholder?: string; def?: string; type?: string; mono?: boolean; required?: boolean }) {
|
||||||
|
return (
|
||||||
|
<label className="flex flex-col gap-1 text-sm">
|
||||||
|
<span className="text-muted-foreground">{label}</span>
|
||||||
|
<Input name={name} required={required} type={type} placeholder={placeholder} defaultValue={def} className={mono ? "font-mono" : undefined} spellCheck={false} autoComplete="off" />
|
||||||
|
</label>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** PEP-251: the form of a database, a server, a storage or a mailbox. */
|
||||||
|
function ProtocolSteps({ p, t }: { p: GatewayProtocol; t: Translator }) {
|
||||||
|
const txt = PROTOCOL_TEXT[p];
|
||||||
|
const back = `/connections?service=proto:${p}#add`;
|
||||||
|
const sql = p === "postgres" || p === "mysql";
|
||||||
|
return (
|
||||||
|
<Card className="flex flex-col gap-4 p-4">
|
||||||
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
|
<span className="text-base font-medium">{t.text(txt.name)}</span>
|
||||||
|
<Badge variant="outline">{t.text(txt.hint)}</Badge>
|
||||||
|
<Link href="/connections#add" className="ml-auto text-sm text-muted-foreground underline-offset-2 hover:underline">
|
||||||
|
{t("← Другой сервис")}
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
<p className="m-0 text-sm text-muted-foreground">
|
||||||
|
{sql
|
||||||
|
? t("Лучше заведите для агентов отдельного пользователя базы данных только с нужными правами: так даже ошибка агента ничего лишнего не изменит.")
|
||||||
|
: p === "ssh"
|
||||||
|
? t("Лучше заведите для агентов отдельного пользователя на сервере. Файлы агенты видят только в папке, которую вы укажете.")
|
||||||
|
: p === "s3"
|
||||||
|
? t("Лучше создайте отдельный ключ доступа только к этому бакету. Агенты видят файлы только в папке, которую вы укажете.")
|
||||||
|
: t("Для почты Google, Яндекса и Mail.ru нужен пароль приложения: его создают в настройках безопасности почты.")}
|
||||||
|
</p>
|
||||||
|
<form action={createConnectionAction} className="flex max-w-xl flex-col gap-3" autoComplete="off">
|
||||||
|
<Hidden fields={{ back, protocol: p }} />
|
||||||
|
<Field name="name" label={t("Название")} placeholder={t("Название, например «Магазин»")} />
|
||||||
|
{sql && (
|
||||||
|
<div className="grid gap-2 sm:grid-cols-[1fr_7rem]">
|
||||||
|
<Field name="host" label={t("Адрес сервера")} placeholder="db.example.com" mono />
|
||||||
|
<Field name="port" label={t("Порт")} placeholder={p === "postgres" ? "5432" : "3306"} required={false} mono />
|
||||||
|
<Field name="database" label={t("Название базы данных")} placeholder="shop" mono />
|
||||||
|
<span />
|
||||||
|
<Field name="user" label={t("Пользователь")} placeholder="reader" mono />
|
||||||
|
<span />
|
||||||
|
<label className="flex flex-col gap-1 text-sm">
|
||||||
|
<span className="text-muted-foreground">{t("Защита соединения")}</span>
|
||||||
|
<select name="tls" defaultValue="verify" className={SELECT}>
|
||||||
|
<option value="verify">{t("Шифровать и проверять сертификат")}</option>
|
||||||
|
<option value="encrypt">{t("Шифровать без проверки сертификата")}</option>
|
||||||
|
<option value="off">{t("Без шифрования")}</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{p === "ssh" && (
|
||||||
|
<div className="grid gap-2 sm:grid-cols-[1fr_7rem]">
|
||||||
|
<Field name="host" label={t("Адрес сервера")} placeholder="srv.example.com" mono />
|
||||||
|
<Field name="port" label={t("Порт")} placeholder="22" required={false} mono />
|
||||||
|
<Field name="user" label={t("Пользователь")} placeholder="agent" mono />
|
||||||
|
<span />
|
||||||
|
<Field name="root" label={t("Папка, в которой агенты работают с файлами")} placeholder="/var/www" required={false} mono />
|
||||||
|
<span />
|
||||||
|
<Field name="hostKey" label={t("Ключ сервера, если знаете (иначе запомним при первом подключении)")} placeholder="SHA256:…" required={false} mono />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{p === "s3" && (
|
||||||
|
<div className="grid gap-2 sm:grid-cols-2">
|
||||||
|
<Field name="endpoint" label={t("Адрес хранилища")} placeholder="https://s3.eu-central-1.amazonaws.com" type="url" mono />
|
||||||
|
<Field name="region" label={t("Регион")} placeholder="eu-central-1" required={false} mono />
|
||||||
|
<Field name="bucket" label={t("Бакет")} placeholder="shop-files" mono />
|
||||||
|
<Field name="prefix" label={t("Папка в бакете (пусто — весь бакет)")} placeholder="reports/" required={false} mono />
|
||||||
|
<Field name="accessKeyId" label={t("Идентификатор ключа доступа")} placeholder="AKIA…" mono />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{p === "mail" && (
|
||||||
|
<div className="grid gap-2 sm:grid-cols-[1fr_7rem]">
|
||||||
|
<Field name="user" label={t("Логин почтового ящика")} placeholder="shop@example.com" mono />
|
||||||
|
<span />
|
||||||
|
<Field name="imapHost" label={t("Сервер входящей почты")} placeholder="imap.example.com" mono />
|
||||||
|
<Field name="imapPort" label={t("Порт")} placeholder="993" required={false} mono />
|
||||||
|
<Field name="smtpHost" label={t("Сервер исходящей почты")} placeholder="smtp.example.com" mono />
|
||||||
|
<Field name="smtpPort" label={t("Порт")} placeholder="465" required={false} mono />
|
||||||
|
<Field name="from" label={t("Адрес отправителя (пусто — логин)")} placeholder="shop@example.com" required={false} mono />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{p === "ssh" ? (
|
||||||
|
<Textarea name="secret" required rows={3} placeholder={t.text(txt.secret)} aria-label={t.text(txt.secret)} className="font-mono" spellCheck={false} />
|
||||||
|
) : (
|
||||||
|
<Input name="secret" required type="password" placeholder={t.text(txt.secret)} aria-label={t.text(txt.secret)} autoComplete="new-password" />
|
||||||
|
)}
|
||||||
|
<p className="m-0 text-xs text-muted-foreground">{t("После сохранения пароль и ключ не увидит никто: ни агенты, ни администраторы FORGE.")}</p>
|
||||||
|
<Button size="sm" className="self-start">{t("Подключить и проверить")}</Button>
|
||||||
|
</form>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Step 1–2 for a chosen service (catalog card or own). */
|
||||||
|
/** PEP-252: «Войти через Google / GitHub» — the level and exactly which rights FORGE asks for. */
|
||||||
|
function SignInStep({ s, t }: { s: CatalogService; t: Translator }) {
|
||||||
|
const offer = oauthOffer(s.id);
|
||||||
|
if (!offer) return null;
|
||||||
|
const level = (value: "read" | "write", title: string, scopes: string[], checked: boolean) => (
|
||||||
|
<label className="flex items-start gap-2 rounded-md border bg-background/40 px-3 py-2">
|
||||||
|
<input type="radio" name="level" value={value} defaultChecked={checked} className="mt-1" />
|
||||||
|
<span className="flex flex-col gap-0.5">
|
||||||
|
<span className="font-medium">{title}</span>
|
||||||
|
<span className="text-xs text-muted-foreground">{t("FORGE попросит: {scopes}", { scopes: scopes.map(scopeLabel).join(", ") })}</span>
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
);
|
||||||
|
return (
|
||||||
|
<form action="/connections/oauth/start" method="post" className="flex max-w-xl flex-col gap-2 rounded-md border border-primary/40 p-3 text-sm">
|
||||||
|
<input type="hidden" name="catalogId" value={s.id} />
|
||||||
|
<span className="font-medium">{t("Проще всего — войти через {service}", { service: offer.providerName })}</span>
|
||||||
|
<span className="text-muted-foreground">{t("Ключ не нужен: вы войдёте на странице сервиса и подтвердите доступ. FORGE сам продлевает доступ, а «Отозвать доступ» закрывает его и в сервисе.")}</span>
|
||||||
|
{level("read", t("Только чтение"), offer.read, true)}
|
||||||
|
{level("write", t("Чтение и запись"), offer.write, false)}
|
||||||
|
{offer.note && <span className="text-xs text-muted-foreground">{t.text(offer.note)}</span>}
|
||||||
|
<Button size="sm" className="self-start">{t("Войти через {service}", { service: offer.providerName })}</Button>
|
||||||
|
</form>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function AddSteps({ s, t }: { s: CatalogService | null; t: Translator }) {
|
||||||
|
const back = `/connections?service=${s?.id ?? "custom"}#add`;
|
||||||
|
return (
|
||||||
|
<Card className="flex flex-col gap-4 p-4">
|
||||||
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
|
<span className="text-base font-medium">{s ? s.name : t("Свой сервис")}</span>
|
||||||
|
{s && <Badge variant="outline">{kindText(s.kind, t)}</Badge>}
|
||||||
|
<Link href="/connections#add" className="ml-auto text-sm text-muted-foreground underline-offset-2 hover:underline">
|
||||||
|
{t("← Другой сервис")}
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
{s && <SignInStep s={s} t={t} />}
|
||||||
|
{s && oauthOffer(s.id) && <span className="text-sm text-muted-foreground">{t("Или подключите ключом доступа:")}</span>}
|
||||||
|
<ol className="m-0 flex list-decimal flex-col gap-4 pl-5 text-sm">
|
||||||
|
{s ? (
|
||||||
|
<li className="flex flex-col gap-1">
|
||||||
|
<span className="font-medium">{t("Возьмите ключ доступа")}</span>
|
||||||
|
<span className="text-muted-foreground">{t.text(s.keyHint)}</span>
|
||||||
|
<a href={s.keyUrl} target="_blank" rel="noreferrer noopener" className="inline-flex items-center gap-1 self-start text-primary underline-offset-2 hover:underline">
|
||||||
|
{t("Открыть страницу, где берут ключ")} <ExternalLink className="size-3" />
|
||||||
|
</a>
|
||||||
|
</li>
|
||||||
|
) : (
|
||||||
|
<li className="flex flex-col gap-1">
|
||||||
|
<span className="font-medium">{t("Возьмите адрес сервиса и ключ доступа")}</span>
|
||||||
|
<span className="text-muted-foreground">{t("Они есть в описании сервиса для разработчиков или у того, кто его сделал.")}</span>
|
||||||
|
</li>
|
||||||
|
)}
|
||||||
|
<li className="flex flex-col gap-2">
|
||||||
|
<span className="font-medium">{t("Вставьте его сюда")}</span>
|
||||||
|
<form action={createConnectionAction} className="flex max-w-xl flex-col gap-2" autoComplete="off">
|
||||||
|
<Hidden fields={{ back, catalogId: s?.id ?? "" }} />
|
||||||
|
<Input name="name" maxLength={60} defaultValue={s?.name ?? ""} required={!s} placeholder={t("Название, например «Магазин»")} aria-label={t("Название")} />
|
||||||
|
{(!s || s.baseEditable) && <Input name="baseUrl" required type="url" placeholder={s?.baseUrl ?? "https://api.example.com/v1"} aria-label={t("Адрес сервиса")} className="font-mono" spellCheck={false} />}
|
||||||
|
<Input name="secret" required type="password" placeholder={s?.auth === "basic" ? t("логин:пароль — после сохранения их не увидит никто") : t("Ключ доступа — после сохранения его не увидит никто")} aria-label={t("Ключ доступа")} autoComplete="new-password" />
|
||||||
|
{!s && (
|
||||||
|
<div className="flex flex-wrap items-center gap-2 text-sm">
|
||||||
|
<select name="authKind" aria-label={t("Как передавать ключ")} className={SELECT} defaultValue="bearer">
|
||||||
|
<option value="bearer">{t("Как «Authorization: Bearer …»")}</option>
|
||||||
|
<option value="header">{t("В своём заголовке")}</option>
|
||||||
|
<option value="query">{t("В адресе запроса (параметр)")}</option>
|
||||||
|
<option value="basic">{t("Логин и пароль")}</option>
|
||||||
|
</select>
|
||||||
|
<Input name="authHeader" placeholder="X-Api-Key" aria-label={t("Имя заголовка или параметра")} className="max-w-48 font-mono" spellCheck={false} />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{!s && <p className="m-0 text-xs text-muted-foreground">{t("Не разрешайте агенту действия, которые возвращают присланное обратно: проверку, отладку, «кто я» с ключом. Через них сервис может показать агенту ключ.")}</p>}
|
||||||
|
<Button size="sm" className="self-start">{t("Подключить и проверить")}</Button>
|
||||||
|
</form>
|
||||||
|
</li>
|
||||||
|
<li className="flex flex-col gap-1 text-muted-foreground">
|
||||||
|
<span className="font-medium text-foreground">{t("Проверим ключ и решите, кому разрешить")}</span>
|
||||||
|
<span>{t("После сохранения FORGE сам сделает проверочный запрос, а вы выберете проект, агента и что можно: читать или менять.")}</span>
|
||||||
|
</li>
|
||||||
|
</ol>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function Catalog({ q, kind, t }: { q: string; kind: string | null; t: Translator }) {
|
||||||
|
const list = searchCatalog(q, { kind, kindText: (k) => kindText(k, t) });
|
||||||
|
const protocols = GATEWAY_PROTOCOLS.filter((p) => (!kind || PROTOCOL_KIND[p] === kind) && (!q || `${PROTOCOL_TEXT[p].name} ${t.text(PROTOCOL_TEXT[p].name)} ${t.text(PROTOCOL_TEXT[p].hint)}`.toLowerCase().includes(q.toLowerCase())));
|
||||||
|
const chip = (active: boolean) => `rounded-full border px-3 py-1 text-xs ${active ? "border-primary bg-primary/10 text-foreground" : "text-muted-foreground hover:text-foreground"}`;
|
||||||
|
const href = (k: string | null) => `/connections?${new URLSearchParams({ ...(q ? { q } : {}), ...(k ? { kind: k } : {}) })}#add`;
|
||||||
|
return (
|
||||||
|
<Card className="flex flex-col gap-3 p-4">
|
||||||
|
<form action="/connections#add" className="flex flex-wrap gap-2" role="search">
|
||||||
|
{kind && <input type="hidden" name="kind" value={kind} />}
|
||||||
|
<div className="relative max-w-sm flex-1">
|
||||||
|
<Search className="pointer-events-none absolute top-2.5 left-2.5 size-4 text-muted-foreground" />
|
||||||
|
<Input name="q" defaultValue={q} placeholder={t("Найти сервис: почта, платежи, Stripe…")} aria-label={t("Найти сервис")} className="pl-8" />
|
||||||
|
</div>
|
||||||
|
<Button size="sm" variant="secondary">{t("Найти")}</Button>
|
||||||
|
</form>
|
||||||
|
<div className="flex flex-wrap gap-1.5">
|
||||||
|
<Link href={href(null)} className={chip(!kind)}>
|
||||||
|
{t("Все")}
|
||||||
|
</Link>
|
||||||
|
{CATALOG_KINDS.map((k) => (
|
||||||
|
<Link key={k} href={href(k)} className={chip(kind === k)}>
|
||||||
|
{kindText(k, t)}
|
||||||
|
</Link>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
<div className="grid grid-cols-2 gap-2 sm:grid-cols-3 lg:grid-cols-4">
|
||||||
|
{list.map((s) => (
|
||||||
|
<Link key={s.id} href={`/connections?service=${s.id}#add`} className="flex flex-col gap-0.5 rounded-md border bg-background/40 px-3 py-2 hover:border-primary">
|
||||||
|
<span className="text-sm font-medium">{s.name}</span>
|
||||||
|
<span className="text-xs text-muted-foreground">{kindText(s.kind, t)}</span>
|
||||||
|
</Link>
|
||||||
|
))}
|
||||||
|
{protocols.map((p) => (
|
||||||
|
<Link key={p} href={`/connections?service=proto:${p}#add`} className="flex flex-col gap-0.5 rounded-md border bg-background/40 px-3 py-2 hover:border-primary">
|
||||||
|
<span className="text-sm font-medium">{t.text(PROTOCOL_TEXT[p].name)}</span>
|
||||||
|
<span className="text-xs text-muted-foreground">{t.text(PROTOCOL_TEXT[p].hint)}</span>
|
||||||
|
</Link>
|
||||||
|
))}
|
||||||
|
<Link href="/connections?service=custom#add" className="flex flex-col gap-0.5 rounded-md border border-dashed px-3 py-2 hover:border-primary">
|
||||||
|
<span className="text-sm font-medium">{t("Свой сервис")}</span>
|
||||||
|
<span className="text-xs text-muted-foreground">{t("Адрес и ключ вручную")}</span>
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
{list.length === 0 && !protocols.length && <p className="m-0 text-sm text-muted-foreground">{t("Такого сервиса в списке нет — подключите его как «Свой сервис».")}</p>}
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** PEP-254: download the journal with hashes and how to check it yourself. */
|
||||||
|
function JournalExport({ t, engineer }: { t: Translator; engineer: boolean }) {
|
||||||
|
return (
|
||||||
|
<div className="mt-3 space-y-2 text-sm">
|
||||||
|
<p className="m-0 text-muted-foreground">
|
||||||
|
{t("Журнал нельзя незаметно изменить: каждая запись связана с предыдущей, и раз в сутки FORGE сохраняет отметку журнала отдельно. Если запись изменят, вы и администратор получите сообщение.")}
|
||||||
|
</p>
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
<Button asChild size="sm" variant="outline">
|
||||||
|
<a href="/api/connections/journal?format=csv" download>{t("Скачать журнал (таблица)")}</a>
|
||||||
|
</Button>
|
||||||
|
<Button asChild size="sm" variant="outline">
|
||||||
|
<a href="/api/connections/journal?format=jsonl" download>{t("Скачать журнал для проверки")}</a>
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
<details open={engineer}>
|
||||||
|
<summary className="cursor-pointer text-muted-foreground">{t("Как проверить журнал самому")}</summary>
|
||||||
|
<div className="mt-2 space-y-2">
|
||||||
|
<p className="m-0">
|
||||||
|
{t("Скачайте журнал для проверки и сохраните программу ниже рядом с ним. Запустите её так, как написано в её первой строке. Ответ «ok» значит, что журнал не меняли; иначе программа назовёт первую изменённую запись.")}
|
||||||
|
</p>
|
||||||
|
<pre className="overflow-x-auto rounded-md bg-muted p-2 text-xs">{JOURNAL_VERIFY_SCRIPT}</pre>
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** PEP-234/249 Access Hub: «Подключения» — the user's own external services and who may use them. */
|
||||||
|
export default async function ConnectionsPage({ searchParams }: { searchParams: Promise<Params> }) {
|
||||||
|
const q = await searchParams;
|
||||||
|
const user = await requireUser();
|
||||||
|
const t = await getT();
|
||||||
|
const engineer = (await uiMode()) === "engineer";
|
||||||
|
const [list, journal, projects, agents, requests] = await Promise.all([listConnections(db, user.id), connectionJournal(db, user.id, { limit: 50 }), listUserProjects(db, user.id), grantableAgents(db), ownerAccessRequests(db, user.id)]);
|
||||||
|
const proto = q.service?.startsWith("proto:") ? (GATEWAY_PROTOCOLS as string[]).find((p) => `proto:${p}` === q.service) as GatewayProtocol | undefined : undefined;
|
||||||
|
const chosen = q.service === "custom" ? "custom" : catalogService(q.service);
|
||||||
|
const kind = q.kind && (CATALOG_KINDS as string[]).includes(q.kind) ? q.kind : null;
|
||||||
|
return (
|
||||||
|
<Workspace>
|
||||||
|
<Flash error={q.error} />
|
||||||
|
{(q.created || q.checked) && <CheckNotice check={q.check} created={!!q.created} signed={!!q.signed} t={t} />}
|
||||||
|
{q.revoked && q.remote === "failed" && <Notice>{t("Доступ в FORGE отозван, но сервис не ответил. Чтобы закрыть доступ и там, удалите FORGE в настройках доступа самого сервиса.")}</Notice>}
|
||||||
|
<PageHeader title={<><PlugZap className="mr-1 inline size-5 text-primary" />{t("Подключения")}</>}>
|
||||||
|
<p className="m-0 text-sm text-muted-foreground">
|
||||||
|
{t("Подключите свои сервисы и решите, какие агенты и что в них могут делать. Агенты не видят ключ доступа: запросы выполняет FORGE и записывает их в журнал. Без вашего разрешения агент ничего не сделает, а «Отозвать доступ» действует сразу.")}
|
||||||
|
</p>
|
||||||
|
</PageHeader>
|
||||||
|
|
||||||
|
{requests.length > 0 && (
|
||||||
|
<Section id="requests" title={t("Агенты просят доступ")} count={requests.length}>
|
||||||
|
<AccessRequestList list={requests} t={t} />
|
||||||
|
</Section>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{list.length > 0 && (
|
||||||
|
<Section title={t("Ваши подключения")} count={list.length}>
|
||||||
|
{list.map((c) => (
|
||||||
|
<ConnectionCard key={c.id} c={c} projects={projects} agents={agents} engineer={engineer} t={t} />
|
||||||
|
))}
|
||||||
|
</Section>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<Section id="add" title={t("Подключить сервис")}>
|
||||||
|
{proto ? <ProtocolSteps p={proto} t={t} /> : chosen ? <AddSteps s={chosen === "custom" ? null : chosen} t={t} /> : <Catalog q={(q.q ?? "").slice(0, 80)} kind={kind} t={t} />}
|
||||||
|
</Section>
|
||||||
|
|
||||||
|
<Section title={t("Журнал запросов")} count={journal.length}>
|
||||||
|
{journal.length === 0 ? (
|
||||||
|
<Empty>{t("Агенты ещё не обращались к вашим подключениям.")}</Empty>
|
||||||
|
) : (
|
||||||
|
<div className="overflow-x-auto">
|
||||||
|
<table className="w-full text-sm">
|
||||||
|
<thead className="text-left text-xs text-muted-foreground">
|
||||||
|
<tr>
|
||||||
|
<th className="py-1 pr-3 font-normal">{t("Когда")}</th>
|
||||||
|
<th className="py-1 pr-3 font-normal">{t("Подключение")}</th>
|
||||||
|
<th className="py-1 pr-3 font-normal">{t("Проект и агент")}</th>
|
||||||
|
<th className="py-1 pr-3 font-normal">{t("Операция")}</th>
|
||||||
|
<th className="py-1 font-normal">{t("Решение")}</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{journal.map((r) => (
|
||||||
|
<tr key={r.id} className="border-t align-top">
|
||||||
|
<td className="py-1.5 pr-3 whitespace-nowrap text-muted-foreground">{ago(r.createdAt, t)}</td>
|
||||||
|
<td className="py-1.5 pr-3">{r.connectionName}</td>
|
||||||
|
<td className="py-1.5 pr-3">
|
||||||
|
{r.projectKey ?? "—"}
|
||||||
|
{r.agentName ? ` · ${r.agentName}` : ""}
|
||||||
|
</td>
|
||||||
|
{r.method === "REVOKE" ? (
|
||||||
|
<td className="py-1.5 pr-3 text-xs">{t("разрешение снято")}</td>
|
||||||
|
) : (
|
||||||
|
<td className="py-1.5 pr-3 font-mono text-xs">
|
||||||
|
{r.method} {r.path}
|
||||||
|
</td>
|
||||||
|
)}
|
||||||
|
<td className="py-1.5">
|
||||||
|
<span className="flex flex-wrap items-center gap-1.5">
|
||||||
|
<Decision row={r} t={t} />
|
||||||
|
<span className="text-xs text-muted-foreground">{reasonText(r.reason, t)}</span>
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<JournalExport t={t} engineer={engineer} />
|
||||||
|
</Section>
|
||||||
|
</Workspace>
|
||||||
|
);
|
||||||
|
}
|
||||||
184
apps/web/app/(app)/connections/requests/[id]/page.tsx
Normal file
184
apps/web/app/(app)/connections/requests/[id]/page.tsx
Normal file
@ -0,0 +1,184 @@
|
|||||||
|
import Link from "@/components/Link";
|
||||||
|
import { notFound } from "next/navigation";
|
||||||
|
import { ExternalLink, KeyRound } from "lucide-react";
|
||||||
|
import { accessRequestForUser, catalogService, connectionsForRequest, type AccessRequestView, type CatalogService, type ConnectionView } from "@peppa/core";
|
||||||
|
import type { Translator } from "@peppa/shared/i18n";
|
||||||
|
import { AccessStatus, accessModeText } from "@/components/AccessRequests";
|
||||||
|
import { Hidden } from "@/components/cards";
|
||||||
|
import { Flash, Notice, PageHeader, Section } from "@/components/common";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Card } from "@/components/ui/card";
|
||||||
|
import { Input, Textarea } from "@/components/ui/input";
|
||||||
|
import { Workspace } from "@/components/Workspace";
|
||||||
|
import { requireUser } from "@/lib/auth";
|
||||||
|
import { db } from "@/lib/db";
|
||||||
|
import { getT } from "@/lib/i18n";
|
||||||
|
import { connectAccessRequestAction, denyAccessRequestAction, grantAccessRequestAction } from "../../../actions";
|
||||||
|
|
||||||
|
export async function generateMetadata() {
|
||||||
|
const t = await getT();
|
||||||
|
return { title: t("Запрос доступа — FORGE") };
|
||||||
|
}
|
||||||
|
|
||||||
|
const SELECT = "h-9 rounded-md border border-input bg-background px-2 text-sm";
|
||||||
|
|
||||||
|
function Fact({ label, children }: { label: string; children: React.ReactNode }) {
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col gap-0.5 sm:flex-row sm:gap-3">
|
||||||
|
<span className="w-32 shrink-0 text-muted-foreground">{label}</span>
|
||||||
|
<span className="min-w-0 break-words">{children}</span>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function DoneNotice({ done, check, t }: { done?: string; check?: string; t: Translator }) {
|
||||||
|
if (done === "denied") return <Notice>{t("Отказано. Агент получит вашу причину и продолжит без этого сервиса.")}</Notice>;
|
||||||
|
if (done !== "granted") return null;
|
||||||
|
const tail = check === "bad_key" ? t("Но сервис не принял ключ: замените его в разделе «Подключения».") : check === "down" ? t("Сервис сейчас не отвечает — ключ проверится при первом запросе агента.") : "";
|
||||||
|
return (
|
||||||
|
<Notice>
|
||||||
|
{t("Доступ выдан. Агент получил сообщение и продолжит работу; ключ доступа он не видит.")} {tail}
|
||||||
|
</Notice>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function ConnectForm({ r, card, t }: { r: AccessRequestView; card: CatalogService | null; t: Translator }) {
|
||||||
|
const back = `/connections/requests/${r.id}`;
|
||||||
|
return (
|
||||||
|
<ol className="m-0 flex list-decimal flex-col gap-4 pl-5 text-sm">
|
||||||
|
<li className="flex flex-col gap-1">
|
||||||
|
<span className="font-medium">{t("Возьмите ключ доступа")}</span>
|
||||||
|
{card ? (
|
||||||
|
<>
|
||||||
|
<span className="text-muted-foreground">{t.text(card.keyHint)}</span>
|
||||||
|
<a href={card.keyUrl} target="_blank" rel="noreferrer noopener" className="inline-flex items-center gap-1 self-start text-primary underline-offset-2 hover:underline">
|
||||||
|
{t("Открыть страницу, где берут ключ")} <ExternalLink className="size-3" />
|
||||||
|
</a>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<span className="text-muted-foreground">{t("Он есть в описании сервиса для разработчиков или у того, кто его сделал.")}</span>
|
||||||
|
)}
|
||||||
|
</li>
|
||||||
|
<li className="flex flex-col gap-2">
|
||||||
|
<span className="font-medium">{t("Вставьте его сюда")}</span>
|
||||||
|
<form action={connectAccessRequestAction} className="flex max-w-xl flex-col gap-2" autoComplete="off">
|
||||||
|
<Hidden fields={{ back, requestId: r.id }} />
|
||||||
|
{(!card || card.baseEditable) && <Input name="baseUrl" required type="url" defaultValue={r.host ?? ""} placeholder={card?.baseUrl ?? "https://api.example.com/v1"} aria-label={t("Адрес сервиса")} className="font-mono" spellCheck={false} />}
|
||||||
|
<Input name="secret" required type="password" placeholder={card?.auth === "basic" ? t("логин:пароль — после сохранения их не увидит никто") : t("Ключ доступа — после сохранения его не увидит никто")} aria-label={t("Ключ доступа")} autoComplete="new-password" />
|
||||||
|
{!card && (
|
||||||
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
|
<select name="authKind" aria-label={t("Как передавать ключ")} className={SELECT} defaultValue="bearer">
|
||||||
|
<option value="bearer">{t("Как «Authorization: Bearer …»")}</option>
|
||||||
|
<option value="header">{t("В своём заголовке")}</option>
|
||||||
|
<option value="query">{t("В адресе запроса (параметр)")}</option>
|
||||||
|
<option value="basic">{t("Логин и пароль")}</option>
|
||||||
|
</select>
|
||||||
|
<Input name="authHeader" placeholder="X-Api-Key" aria-label={t("Имя заголовка или параметра")} className="max-w-48 font-mono" spellCheck={false} />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<Button size="sm" className="self-start">{t("Подключить и разрешить")}</Button>
|
||||||
|
</form>
|
||||||
|
</li>
|
||||||
|
</ol>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function ExistingForm({ r, fit, other, t }: { r: AccessRequestView; fit: ConnectionView[]; other: ConnectionView[]; t: Translator }) {
|
||||||
|
const all = [...fit, ...other];
|
||||||
|
if (!all.length) return null;
|
||||||
|
return (
|
||||||
|
<form action={grantAccessRequestAction} className="flex flex-wrap items-center gap-2 text-sm">
|
||||||
|
<Hidden fields={{ back: `/connections/requests/${r.id}`, requestId: r.id }} />
|
||||||
|
<select name="connectionId" required aria-label={t("Подключение")} className={SELECT} defaultValue={fit[0]?.id ?? ""}>
|
||||||
|
{!fit.length && <option value="">{t("Выберите подключение")}</option>}
|
||||||
|
{all.map((c) => (
|
||||||
|
<option key={c.id} value={c.id}>
|
||||||
|
{c.name}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
<Button size="sm" variant="secondary">{t("Разрешить из уже подключённого")}</Button>
|
||||||
|
</form>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** PEP-250: the card of an agent's access request — its project's owner only (others: 404). */
|
||||||
|
export default async function AccessRequestPage({ params, searchParams }: { params: Promise<{ id: string }>; searchParams: Promise<{ error?: string; done?: string; check?: string }> }) {
|
||||||
|
const [{ id }, q] = await Promise.all([params, searchParams]);
|
||||||
|
const user = await requireUser();
|
||||||
|
const t = await getT();
|
||||||
|
const r = /^\d+$/.test(id) ? await accessRequestForUser(db, user.id, Number(id)) : null;
|
||||||
|
if (!r) notFound();
|
||||||
|
const card = catalogService(r.catalogId);
|
||||||
|
const { fit, other } = r.status === "open" ? await connectionsForRequest(db, user.id, r) : { fit: [], other: [] };
|
||||||
|
return (
|
||||||
|
<Workspace>
|
||||||
|
<Flash error={q.error} />
|
||||||
|
<DoneNotice done={q.done} check={q.check} t={t} />
|
||||||
|
<PageHeader
|
||||||
|
title={<><KeyRound className="mr-1 inline size-5 text-primary" />{t("Агент просит доступ к {service}", { service: r.service })}</>}
|
||||||
|
crumbs={<Link href="/connections" className="hover:underline">{t("Подключения")}</Link>}
|
||||||
|
>
|
||||||
|
<p className="m-0 text-sm text-muted-foreground">
|
||||||
|
{r.status === "open"
|
||||||
|
? t("Агенту нужен этот сервис для работы над задачей. Ключ доступа вы вводите один раз, агент его не увидит: запросы выполняет FORGE и записывает их в журнал. Можно и отказать — агент продолжит без сервиса.")
|
||||||
|
: t("По этому запросу уже есть решение.")}
|
||||||
|
</p>
|
||||||
|
</PageHeader>
|
||||||
|
|
||||||
|
<Card className="flex flex-col gap-2 p-4 text-sm">
|
||||||
|
<div className="mb-1 flex flex-wrap items-center gap-2">
|
||||||
|
<AccessStatus r={r} t={t} />
|
||||||
|
{r.repeats > 0 && <span className="text-xs text-muted-foreground">{t("агент просил ещё раз: {n}", { n: r.repeats })}</span>}
|
||||||
|
</div>
|
||||||
|
<Fact label={t("Агент")}>{r.agentName ?? "—"}</Fact>
|
||||||
|
<Fact label={t("Задача")}>{r.taskKey ? <Link href={`/t/${r.taskKey}`} className="text-primary hover:underline">{r.taskKey}{r.taskTitle ? ` — ${r.taskTitle}` : ""}</Link> : "—"}</Fact>
|
||||||
|
<Fact label={t("Проект")}>{r.projectName}</Fact>
|
||||||
|
<Fact label={t("Сервис")}>
|
||||||
|
{r.service}
|
||||||
|
{card && (
|
||||||
|
<a href={card.docsUrl} target="_blank" rel="noreferrer noopener" className="ml-2 inline-flex items-center gap-1 text-xs text-muted-foreground hover:underline">
|
||||||
|
{t("Документация сервиса")} <ExternalLink className="size-3" />
|
||||||
|
</a>
|
||||||
|
)}
|
||||||
|
{!card && r.host && <span className="ml-2 font-mono text-xs text-muted-foreground">{r.host}</span>}
|
||||||
|
</Fact>
|
||||||
|
<Fact label={t("Что можно")}>{accessModeText(r.mode, t)}</Fact>
|
||||||
|
{/* The agent's own words: shown as is, never as instructions. */}
|
||||||
|
<Fact label={t("Зачем")}>{r.purpose}</Fact>
|
||||||
|
{r.status === "denied" && <Fact label={t("Причина отказа")}>{r.reason ?? t("без причины")}</Fact>}
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{r.status === "open" && (
|
||||||
|
<>
|
||||||
|
<Section title={t("Подключить и разрешить")}>
|
||||||
|
<Card className="p-4">
|
||||||
|
<ConnectForm r={r} card={card} t={t} />
|
||||||
|
<p className="m-0 mt-3 text-xs text-muted-foreground">
|
||||||
|
{r.mode === "write"
|
||||||
|
? t("Агенты проекта смогут читать и менять данные в этом сервисе. Изменить или отозвать доступ можно в разделе «Подключения».")
|
||||||
|
: t("Агенты проекта смогут только читать данные в этом сервисе. Изменить или отозвать доступ можно в разделе «Подключения».")}
|
||||||
|
</p>
|
||||||
|
</Card>
|
||||||
|
</Section>
|
||||||
|
{fit.length + other.length > 0 && (
|
||||||
|
<Section title={t("Или разрешить из уже подключённого")}>
|
||||||
|
<Card className="p-4">
|
||||||
|
<ExistingForm r={r} fit={fit} other={other} t={t} />
|
||||||
|
</Card>
|
||||||
|
</Section>
|
||||||
|
)}
|
||||||
|
<Section title={t("Отказать")}>
|
||||||
|
<Card className="p-4">
|
||||||
|
<form action={denyAccessRequestAction} className="flex max-w-xl flex-col gap-2">
|
||||||
|
<Hidden fields={{ back: `/connections/requests/${r.id}`, requestId: r.id }} />
|
||||||
|
<Textarea name="reason" rows={2} maxLength={500} placeholder={t("Причина — агент её получит, например «используйте тестовые данные»")} aria-label={t("Причина отказа")} />
|
||||||
|
<Button size="sm" variant="destructive" className="self-start">{t("Отказать")}</Button>
|
||||||
|
</form>
|
||||||
|
</Card>
|
||||||
|
</Section>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</Workspace>
|
||||||
|
);
|
||||||
|
}
|
||||||
49
apps/web/app/(app)/dashboard/actions.ts
Normal file
49
apps/web/app/(app)/dashboard/actions.ts
Normal file
@ -0,0 +1,49 @@
|
|||||||
|
"use server";
|
||||||
|
// PEP-209: the superadmin's buttons on a delay card («Дашборд → Задержки»); PEP-279: old questions.
|
||||||
|
|
||||||
|
import { DELAY_REASON_NAMES, PeppaError, requireSuperadmin, type DelayAction, type DelayReason } from "@peppa/core";
|
||||||
|
import { closeStaleQuestions, delayAction } from "@peppa/runner";
|
||||||
|
import { revalidatePath } from "next/cache";
|
||||||
|
import { redirect } from "next/navigation";
|
||||||
|
import { asWebActor, requireUser } from "@/lib/auth";
|
||||||
|
import { db } from "@/lib/db";
|
||||||
|
import { getT } from "@/lib/i18n";
|
||||||
|
|
||||||
|
const BASE = "/dashboard/delays";
|
||||||
|
const str = (f: FormData, k: string) => String(f.get(k) ?? "").trim();
|
||||||
|
|
||||||
|
export async function delayActionForm(f: FormData) {
|
||||||
|
const user = asWebActor(await requireUser());
|
||||||
|
const params = new URLSearchParams();
|
||||||
|
try {
|
||||||
|
await requireSuperadmin(db, user);
|
||||||
|
const reason = str(f, "reason") as DelayReason;
|
||||||
|
const action = str(f, "action") as DelayAction;
|
||||||
|
const projectId = Number(str(f, "project"));
|
||||||
|
const taskId = str(f, "task") ? Number(str(f, "task")) : null;
|
||||||
|
if (!(reason in DELAY_REASON_NAMES) || !["restart", "review", "close"].includes(action) || !Number.isInteger(projectId)) throw new PeppaError("?");
|
||||||
|
const t = await getT();
|
||||||
|
params.set("ok", t.text(await delayAction(db, { projectId, taskId }, reason, action)).slice(0, 300));
|
||||||
|
} catch (e) {
|
||||||
|
const t = await getT();
|
||||||
|
params.set("error", (e instanceof PeppaError ? t.text(e.message) : t("Ошибка: {message}", { message: (e as Error).message })).slice(0, 300));
|
||||||
|
}
|
||||||
|
revalidatePath("/", "layout");
|
||||||
|
redirect(`${BASE}?${params}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** PEP-279: «Закрыть все» on the old questions page — their default option, one summary per person. */
|
||||||
|
export async function closeStaleQuestionsAction() {
|
||||||
|
const user = asWebActor(await requireUser());
|
||||||
|
const params = new URLSearchParams();
|
||||||
|
const t = await getT();
|
||||||
|
try {
|
||||||
|
await requireSuperadmin(db, user);
|
||||||
|
const r = await closeStaleQuestions(db);
|
||||||
|
params.set("ok", t("Закрыто вопросов: {n}. Итоговое сообщение получили людей: {m}.", { n: r.closed.length, m: r.told }) + (r.failed ? " " + t("Не удалось закрыть: {n}.", { n: r.failed }) : ""));
|
||||||
|
} catch (e) {
|
||||||
|
params.set("error", (e instanceof PeppaError ? t.text(e.message) : t("Ошибка: {message}", { message: (e as Error).message })).slice(0, 300));
|
||||||
|
}
|
||||||
|
revalidatePath("/", "layout");
|
||||||
|
redirect(`/dashboard/questions?${params}`);
|
||||||
|
}
|
||||||
49
apps/web/app/(app)/dashboard/delays/page.tsx
Normal file
49
apps/web/app/(app)/dashboard/delays/page.tsx
Normal file
@ -0,0 +1,49 @@
|
|||||||
|
import Link from "@/components/Link";
|
||||||
|
import { notFound } from "next/navigation";
|
||||||
|
import { Hourglass } from "lucide-react";
|
||||||
|
import { isSuperadmin, platformDelayOverview } from "@peppa/core";
|
||||||
|
import { Empty, Flash, Notice, PageHeader, Section } from "@/components/common";
|
||||||
|
import { LiveRefresh } from "@/components/LiveRefresh";
|
||||||
|
import { PlatformDelays } from "@/components/PlatformDelays";
|
||||||
|
import { Workspace } from "@/components/Workspace";
|
||||||
|
import { requireUser } from "@/lib/auth";
|
||||||
|
import { db } from "@/lib/db";
|
||||||
|
import { getT } from "@/lib/i18n";
|
||||||
|
|
||||||
|
export async function generateMetadata() {
|
||||||
|
const t = await getT();
|
||||||
|
return { title: t("Задержки — FORGE") };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** PEP-209: every delay on the platform's side with the superadmin's buttons; «нужен администратор» first. */
|
||||||
|
export default async function Delays({ searchParams }: { searchParams: Promise<{ error?: string; ok?: string }> }) {
|
||||||
|
const user = await requireUser();
|
||||||
|
if (!(await isSuperadmin(db, user))) notFound();
|
||||||
|
const { error, ok } = await searchParams;
|
||||||
|
const t = await getT();
|
||||||
|
const all = await platformDelayOverview(db);
|
||||||
|
const admin = all.filter((d) => d.exhausted);
|
||||||
|
const trying = all.filter((d) => !d.exhausted);
|
||||||
|
return (
|
||||||
|
<Workspace>
|
||||||
|
<LiveRefresh scope="home" />
|
||||||
|
<Flash error={error} />
|
||||||
|
{ok && <Notice>{t.text(ok)}</Notice>}
|
||||||
|
<PageHeader title={<><Hourglass className="mr-1 inline size-5 text-primary" />{t("Задержки на стороне FORGE")}</>}>
|
||||||
|
{t("Что сейчас задерживается у пользователей и почему. Владельцы видят только строку ожидания на задаче.")}{" "}
|
||||||
|
<Link href="/dashboard" className="text-primary">{t("← Дашборд")}</Link>
|
||||||
|
</PageHeader>
|
||||||
|
{all.length === 0 && <Empty>{t("Задержек нет.")}</Empty>}
|
||||||
|
{admin.length > 0 && (
|
||||||
|
<Section title={t("Нужен администратор")} count={admin.length} id="admin">
|
||||||
|
<PlatformDelays delays={admin} actions />
|
||||||
|
</Section>
|
||||||
|
)}
|
||||||
|
{trying.length > 0 && (
|
||||||
|
<Section title={t("FORGE пробует сама")} count={trying.length} id="trying">
|
||||||
|
<PlatformDelays delays={trying} actions />
|
||||||
|
</Section>
|
||||||
|
)}
|
||||||
|
</Workspace>
|
||||||
|
);
|
||||||
|
}
|
||||||
205
apps/web/app/(app)/dashboard/page.tsx
Normal file
205
apps/web/app/(app)/dashboard/page.tsx
Normal file
@ -0,0 +1,205 @@
|
|||||||
|
import Link from "@/components/Link";
|
||||||
|
import { notFound } from "next/navigation";
|
||||||
|
import { Gauge } from "lucide-react";
|
||||||
|
import { isSuperadmin, platformDashboard, platformDelayCounts, type DashboardCounts } from "@peppa/core";
|
||||||
|
import { ago, Empty, PageHeader, Section } from "@/components/common";
|
||||||
|
import { LiveRefresh } from "@/components/LiveRefresh";
|
||||||
|
import { Badge } from "@/components/ui/badge";
|
||||||
|
import { Card } from "@/components/ui/card";
|
||||||
|
import { Workspace } from "@/components/Workspace";
|
||||||
|
import { requireUser } from "@/lib/auth";
|
||||||
|
import { db } from "@/lib/db";
|
||||||
|
import { getT } from "@/lib/i18n";
|
||||||
|
import { m } from "@peppa/shared/i18n";
|
||||||
|
import { STALE_DAYS, staleQuestions } from "@peppa/runner";
|
||||||
|
|
||||||
|
export async function generateMetadata() {
|
||||||
|
const t = await getT();
|
||||||
|
return { title: t("Дашборд — FORGE") };
|
||||||
|
}
|
||||||
|
|
||||||
|
const SIGN_IN: Record<string, string> = { egov: "eGov", google: "Google", gitea: "Gitea", local: m("пароль") };
|
||||||
|
|
||||||
|
/** «сделано / всего» with a thin bar. */
|
||||||
|
function Done({ c }: { c: DashboardCounts }) {
|
||||||
|
const pct = c.total ? Math.round((c.done / c.total) * 100) : 0;
|
||||||
|
return (
|
||||||
|
<span className="flex min-w-24 items-center gap-2">
|
||||||
|
<span className="h-1.5 w-14 overflow-hidden rounded-full bg-muted">
|
||||||
|
<span className="block h-full rounded-full bg-ok" style={{ width: `${pct}%` }} />
|
||||||
|
</span>
|
||||||
|
<span className="tabular-nums">
|
||||||
|
{c.done}/{c.total}
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function Stat({ label, value, hint }: { label: string; value: number | string; hint?: string }) {
|
||||||
|
return (
|
||||||
|
<Card className="gap-0.5 px-4 py-3">
|
||||||
|
<span className="text-xs text-muted-foreground">{label}</span>
|
||||||
|
<span className="text-2xl font-semibold tabular-nums">{value}</span>
|
||||||
|
{hint && <span className="text-xs text-muted-foreground">{hint}</span>}
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const th = "px-2 py-1.5 text-left text-xs font-medium whitespace-nowrap text-muted-foreground";
|
||||||
|
const td = "px-2 py-1.5 align-top whitespace-nowrap";
|
||||||
|
|
||||||
|
/** PEP-167: the superadmin's view of every user and project of the platform. */
|
||||||
|
export default async function Dashboard() {
|
||||||
|
const user = await requireUser();
|
||||||
|
if (!(await isSuperadmin(db, user))) notFound();
|
||||||
|
const t = await getT();
|
||||||
|
const d = await platformDashboard(db);
|
||||||
|
const x = d.totals;
|
||||||
|
const delays = await platformDelayCounts(db);
|
||||||
|
const stale = (await staleQuestions(db)).length;
|
||||||
|
return (
|
||||||
|
<Workspace>
|
||||||
|
<LiveRefresh scope="home" />
|
||||||
|
<PageHeader title={<><Gauge className="mr-1 inline size-5 text-primary" />{t("Дашборд платформы")}</>}>
|
||||||
|
{t("Как идут дела у всех пользователей и во всех проектах. Видит только суперадмин.")}
|
||||||
|
</PageHeader>
|
||||||
|
|
||||||
|
<div className="mb-6 grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-6" data-dashboard-totals>
|
||||||
|
<Stat label={t("Пользователи")} value={x.users} hint={t("новых за неделю: {n} · активны за сутки: {m}", { n: x.newUsers7d, m: x.activeUsers24h })} />
|
||||||
|
<Stat label={t("Проекты")} value={x.projects} />
|
||||||
|
<Stat label={t("Задачи готово")} value={`${x.done}/${x.total}`} hint={t("в работе {a} · ждут «Принять» {b} · бэклог {c}", { a: x.inProgress, b: x.review, c: x.backlog })} />
|
||||||
|
<Stat label={t("Принято")} value={x.acceptedLast24h} hint={t("за сутки · за неделю: {n}", { n: x.acceptedLast7d })} />
|
||||||
|
<Stat label={t("Агенты работают")} value={x.agentsNow} />
|
||||||
|
<Stat label={t("Ждут ответа людей")} value={x.openQuestions} />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p className="mb-4 text-sm" data-dashboard-delays>
|
||||||
|
<Link href="/dashboard/delays" className="text-primary">
|
||||||
|
{delays.total ? t("Задержки на платформе: {n}, требуют вас: {m}", { n: delays.total, m: delays.admin }) : t("Задержек на платформе нет")} →
|
||||||
|
</Link>
|
||||||
|
</p>
|
||||||
|
{stale > 0 && (
|
||||||
|
<p className="mb-4 text-sm" data-dashboard-stale>
|
||||||
|
<Link href="/dashboard/questions" className="text-primary">
|
||||||
|
{t("Вопросы без ответа дольше {days} дней: {n} — закрыть вариантом по умолчанию", { days: STALE_DAYS, n: stale })} →
|
||||||
|
</Link>
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<Section title={t("Требует внимания")} count={d.attention.length} id="attention">
|
||||||
|
{d.attention.length === 0 ? (
|
||||||
|
<Empty>{t("Всё в порядке: ничего не зависло.")}</Empty>
|
||||||
|
) : (
|
||||||
|
<ul className="m-0 flex list-none flex-col gap-1.5 p-0">
|
||||||
|
{d.attention.map((a, i) => (
|
||||||
|
<li key={i} className="flex flex-wrap items-baseline gap-2 rounded-md border bg-card px-3 py-2 text-sm" data-attention={a.kind}>
|
||||||
|
<Badge variant={a.kind === "subscription" || a.kind === "question" ? "warn" : "muted"}>{a.who}</Badge>
|
||||||
|
<Link href={a.href} className="text-foreground hover:text-primary">{t.text(a.text)}</Link>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
</Section>
|
||||||
|
|
||||||
|
<Section title={t("Пользователи")} count={d.users.length} id="users">
|
||||||
|
<div className="overflow-x-auto rounded-lg border bg-card">
|
||||||
|
<table className="w-full border-collapse text-sm" data-dashboard-users>
|
||||||
|
<thead className="border-b">
|
||||||
|
<tr>
|
||||||
|
<th className={th}>{t("Пользователь")}</th>
|
||||||
|
<th className={th}>{t("Вход")}</th>
|
||||||
|
<th className={th}>{t("Проекты")}</th>
|
||||||
|
<th className={th}>{t("Готово")}</th>
|
||||||
|
<th className={th}>{t("В работе")}</th>
|
||||||
|
<th className={th}>{t("Ждут «Принять»")}</th>
|
||||||
|
<th className={th}>{t("Агенты")}</th>
|
||||||
|
<th className={th}>{t("Вопросы")}</th>
|
||||||
|
<th className={th}>{t("Принято за неделю")}</th>
|
||||||
|
<th className={th}>{t("Активность")}</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{d.users.map((u) => (
|
||||||
|
<tr key={u.id} className="border-b last:border-0">
|
||||||
|
<td className={td}>
|
||||||
|
<span className="font-medium">{u.name || u.login}</span>
|
||||||
|
{u.name && <span className="ml-1 text-xs text-muted-foreground">{u.login}</span>}
|
||||||
|
<div className="text-xs text-muted-foreground">{t("с {date}", { date: u.createdAt.toLocaleDateString("ru-RU") })}</div>
|
||||||
|
</td>
|
||||||
|
<td className={td}>
|
||||||
|
{t.text(SIGN_IN[u.signIn] ?? u.signIn)}
|
||||||
|
{u.telegram && <Badge variant="muted" className="ml-1">Telegram</Badge>}
|
||||||
|
</td>
|
||||||
|
<td className={td}>
|
||||||
|
{u.projects.length ? (
|
||||||
|
<span className="flex flex-wrap gap-1">
|
||||||
|
{u.projects.map((k) => (
|
||||||
|
<Link key={k} href={`/p/${k}`} className="font-mono text-xs text-primary">{k}</Link>
|
||||||
|
))}
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
|
<span className="text-muted-foreground">{t("нет")}</span>
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
|
<td className={td}><Done c={u} /></td>
|
||||||
|
<td className={`${td} tabular-nums`}>{u.inProgress}</td>
|
||||||
|
<td className={`${td} tabular-nums`}>{u.review}</td>
|
||||||
|
<td className={`${td} tabular-nums`}>{u.agentsNow}</td>
|
||||||
|
<td className={`${td} tabular-nums`}>{u.openQuestions}</td>
|
||||||
|
<td className={`${td} tabular-nums`}>{u.acceptedLast7d}</td>
|
||||||
|
<td className={`${td} text-muted-foreground`}>{ago(u.lastActiveAt, t)}</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</Section>
|
||||||
|
|
||||||
|
<Section title={t("Проекты")} count={d.projects.length} id="projects">
|
||||||
|
<div className="overflow-x-auto rounded-lg border bg-card">
|
||||||
|
<table className="w-full border-collapse text-sm" data-dashboard-projects>
|
||||||
|
<thead className="border-b">
|
||||||
|
<tr>
|
||||||
|
<th className={th}>{t("Проект")}</th>
|
||||||
|
<th className={th}>{t("Владелец")}</th>
|
||||||
|
<th className={th}>{t("Готово")}</th>
|
||||||
|
<th className={th}>{t("Бэклог")}</th>
|
||||||
|
<th className={th}>{t("В работе")}</th>
|
||||||
|
<th className={th}>{t("Ждут «Принять»")}</th>
|
||||||
|
<th className={th}>{t("Агенты")}</th>
|
||||||
|
<th className={th}>{t("Вопросы")}</th>
|
||||||
|
<th className={th}>{t("Продукт")}</th>
|
||||||
|
<th className={th}>{t("Активность")}</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{d.projects.map((p) => (
|
||||||
|
<tr key={p.id} className="border-b last:border-0">
|
||||||
|
<td className={td}>
|
||||||
|
<Link href={`/p/${p.key}`} className="font-mono text-primary">{p.key}</Link> <span>{p.name}</span>
|
||||||
|
{p.warning && <div className="max-w-xs text-xs whitespace-normal text-warn">{t("Агенты не запустятся")}</div>}
|
||||||
|
</td>
|
||||||
|
<td className={`${td} text-muted-foreground`}>{p.ownerLogin ?? "—"}</td>
|
||||||
|
<td className={td}><Done c={p} /></td>
|
||||||
|
<td className={`${td} tabular-nums`}>{p.backlog}</td>
|
||||||
|
<td className={`${td} tabular-nums`}>{p.inProgress}</td>
|
||||||
|
<td className={`${td} tabular-nums`}>{p.review}</td>
|
||||||
|
<td className={`${td} tabular-nums`}>{p.agentsNow}</td>
|
||||||
|
<td className={`${td} tabular-nums`}>{p.openQuestions}</td>
|
||||||
|
<td className={td}>
|
||||||
|
{p.productUrl ? (
|
||||||
|
<a href={p.productUrl} target="_blank" rel="noreferrer" className="text-primary">{t("открыть")}</a>
|
||||||
|
) : (
|
||||||
|
<span className="text-muted-foreground">—</span>
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
|
<td className={`${td} text-muted-foreground`}>{ago(p.lastActiveAt, t)}</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</Section>
|
||||||
|
</Workspace>
|
||||||
|
);
|
||||||
|
}
|
||||||
62
apps/web/app/(app)/dashboard/questions/page.tsx
Normal file
62
apps/web/app/(app)/dashboard/questions/page.tsx
Normal file
@ -0,0 +1,62 @@
|
|||||||
|
import Link from "@/components/Link";
|
||||||
|
import { notFound } from "next/navigation";
|
||||||
|
import { MessageCircleQuestion } from "lucide-react";
|
||||||
|
import { isSuperadmin } from "@peppa/core";
|
||||||
|
import { asIs } from "@peppa/shared/i18n";
|
||||||
|
import { STALE_DAYS, staleQuestions } from "@peppa/runner";
|
||||||
|
import { ago, Empty, Flash, Notice, PageHeader } from "@/components/common";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Workspace } from "@/components/Workspace";
|
||||||
|
import { requireUser } from "@/lib/auth";
|
||||||
|
import { db } from "@/lib/db";
|
||||||
|
import { getT } from "@/lib/i18n";
|
||||||
|
import { closeStaleQuestionsAction } from "../actions";
|
||||||
|
|
||||||
|
export async function generateMetadata() {
|
||||||
|
const t = await getT();
|
||||||
|
return { title: t("Старые вопросы — FORGE") };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PEP-279: questions nobody answered for a week — the list is the preview, the button closes them
|
||||||
|
* all with their default option (no default — closed with no choice). Superadmin only.
|
||||||
|
*/
|
||||||
|
export default async function StaleQuestions({ searchParams }: { searchParams: Promise<{ error?: string; ok?: string }> }) {
|
||||||
|
const user = await requireUser();
|
||||||
|
if (!(await isSuperadmin(db, user))) notFound();
|
||||||
|
const { error, ok } = await searchParams;
|
||||||
|
const t = await getT();
|
||||||
|
const list = await staleQuestions(db);
|
||||||
|
return (
|
||||||
|
<Workspace>
|
||||||
|
<Flash error={error} />
|
||||||
|
{ok && <Notice>{t.text(ok)}</Notice>}
|
||||||
|
<PageHeader title={<><MessageCircleQuestion className="mr-1 inline size-5 text-primary" />{t("Вопросы без ответа дольше {n} дней", { n: STALE_DAYS })}</>}>
|
||||||
|
{t("Агенты давно продолжили по рекомендованному варианту. Закройте эти вопросы этим вариантом: владельцы получат одно итоговое сообщение. Карточки «готово» не трогаются — «Принять» нажимают сами владельцы.")}{" "}
|
||||||
|
<Link href="/dashboard" className="text-primary">{t("← Дашборд")}</Link>
|
||||||
|
</PageHeader>
|
||||||
|
{list.length === 0 ? (
|
||||||
|
<Empty>{t("Старых вопросов нет.")}</Empty>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<form action={closeStaleQuestionsAction} className="mb-4 flex flex-wrap items-center gap-3" data-stale-close>
|
||||||
|
<input type="hidden" name="expect" value={list.length} />
|
||||||
|
<Button type="submit">{t("Закрыть все: {n}", { n: list.length })}</Button>
|
||||||
|
<span className="text-sm text-muted-foreground">{t("Ниже — что будет закрыто и каким вариантом.")}</span>
|
||||||
|
</form>
|
||||||
|
<ul className="divide-y rounded-lg border text-sm" data-stale-list>
|
||||||
|
{list.map((x) => (
|
||||||
|
<li key={x.id} className="flex flex-col gap-1 px-3 py-2" data-stale-question={x.id}>
|
||||||
|
<span className="text-xs text-muted-foreground">
|
||||||
|
<Link href={x.where.includes("-") ? `/t/${x.where}` : `/p/${x.projectKey}`} className="text-primary">{x.where}</Link> · {ago(x.createdAt, t)}
|
||||||
|
</span>
|
||||||
|
<span className="line-clamp-2">{t.text(x.freeText ? asIs(x.text) : x.text)}</span>
|
||||||
|
<span className="text-xs">{x.answer ? t("Закроется вариантом: {answer}", { answer: asIs(x.answer) }) : t("Закроется без выбора варианта")}</span>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</Workspace>
|
||||||
|
);
|
||||||
|
}
|
||||||
127
apps/web/app/(app)/errors/[id]/page.tsx
Normal file
127
apps/web/app/(app)/errors/[id]/page.tsx
Normal file
@ -0,0 +1,127 @@
|
|||||||
|
// PEP-218: the card of one production error, read from Bugsink on the server. The superadmin
|
||||||
|
// opens any error, a project's owner or member — errors of that project only (else 404).
|
||||||
|
// «Инженер» and the superadmin see the stack, tags, events and the link to Bugsink.
|
||||||
|
import { platformZone } from "@peppa/shared/time";
|
||||||
|
import Link from "@/components/Link";
|
||||||
|
import { notFound } from "next/navigation";
|
||||||
|
import { Bug, ExternalLink } from "lucide-react";
|
||||||
|
import { errorDetail, errorScope } from "@peppa/core";
|
||||||
|
import { ErrorActions, ErrorStack, ErrorStateBadge, ErrorsDown } from "@/components/Errors";
|
||||||
|
import { ago, Empty, Flash, Key, PageHeader, Section } from "@/components/common";
|
||||||
|
import { Card } from "@/components/ui/card";
|
||||||
|
import { Workspace } from "@/components/Workspace";
|
||||||
|
import { requireUser } from "@/lib/auth";
|
||||||
|
import { db } from "@/lib/db";
|
||||||
|
import { getT } from "@/lib/i18n";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
export async function generateMetadata() {
|
||||||
|
const t = await getT();
|
||||||
|
return { title: t("Ошибка — FORGE") };
|
||||||
|
}
|
||||||
|
|
||||||
|
export default async function ErrorPage({ params, searchParams }: { params: Promise<{ id: string }>; searchParams: Promise<{ error?: string; from?: string }> }) {
|
||||||
|
const user = await requireUser();
|
||||||
|
const t = await getT();
|
||||||
|
const { id } = await params;
|
||||||
|
const { error, from } = await searchParams;
|
||||||
|
const scope = await errorScope(db, user);
|
||||||
|
const d = await errorDetail(db, scope, decodeURIComponent(id));
|
||||||
|
if (!d) notFound();
|
||||||
|
const r = d.row;
|
||||||
|
const back = from && from.startsWith("/") && !from.startsWith("//") ? from : r.projectKey ? `/p/${r.projectKey}?tab=bugs` : "/observability?tab=errors";
|
||||||
|
const self = `/errors/${encodeURIComponent(r.id)}?from=${encodeURIComponent(back)}`;
|
||||||
|
const tags = Object.entries(d.tags);
|
||||||
|
const grouped = new Map<string, Array<{ value: string; count: number }>>();
|
||||||
|
for (const x of d.tagCounts) grouped.set(x.key, [...(grouped.get(x.key) ?? []), { value: x.value, count: x.count }]);
|
||||||
|
return (
|
||||||
|
<Workspace>
|
||||||
|
<div className="max-w-4xl">
|
||||||
|
<Flash error={error} />
|
||||||
|
<ErrorsDown down={d.down} at={d.at} tech={scope.tech} t={t} />
|
||||||
|
<PageHeader crumbs={<Link href={back} className="hover:underline">{t("← К списку ошибок")}</Link>} title={<span className="break-words"><Bug className="mr-1 inline size-5 text-destructive" />{r.title}</span>} />
|
||||||
|
|
||||||
|
<Card className="mb-4 gap-2 py-3">
|
||||||
|
<div className="flex flex-wrap items-center gap-x-4 gap-y-1 text-sm">
|
||||||
|
<ErrorStateBadge state={r.state} t={t} />
|
||||||
|
<span>{t.n(r.events, "{n} раз", "{n} раза", "{n} раз")}</span>
|
||||||
|
{d.users != null ? <span>{t.n(d.users, "у {n} пользователя", "у {n} пользователей", "у {n} пользователей")}</span> : null}
|
||||||
|
<span className="text-muted-foreground" title={r.firstSeen.toLocaleString(undefined, { timeZone: platformZone() })}>{t("впервые {ago}", { ago: ago(r.firstSeen, t) })}</span>
|
||||||
|
<span className="text-muted-foreground" title={r.lastSeen.toLocaleString(undefined, { timeZone: platformZone() })}>{t("последний раз {ago}", { ago: ago(r.lastSeen, t) })}</span>
|
||||||
|
</div>
|
||||||
|
<div className="text-sm">
|
||||||
|
{r.taskKey ? (
|
||||||
|
<span>{t("Задача по этой ошибке:")} <Key href={`/t/${r.taskKey}`}>{r.taskKey}</Key></span>
|
||||||
|
) : (
|
||||||
|
<span className="text-muted-foreground">{d.projectId != null ? t("Задачи по этой ошибке нет.") : t("Ошибка не относится ни к одному проекту.")}</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<ErrorActions d={d} back={self} t={t} />
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{scope.tech ? (
|
||||||
|
<>
|
||||||
|
{/* glossary-ignore: everything below is for «Инженер» and the superadmin only */}
|
||||||
|
<Card className="mb-4 gap-1 py-3 text-sm">
|
||||||
|
<div className="flex flex-wrap gap-x-4 gap-y-1 text-muted-foreground">
|
||||||
|
<span>{t("Проект учёта: {name}", { name: r.bugsinkName })}{r.friendlyId ? ` · ${r.friendlyId}` : ""}</span>
|
||||||
|
{d.environment ? <span>{t("Окружение: {env}", { env: d.environment })}</span> : null}
|
||||||
|
{/* glossary-ignore: «Инженер» and the superadmin only */}
|
||||||
|
{r.release ? <span className="font-mono" title={r.release}>{t("релиз {sha}", { sha: r.release.slice(0, 8) })}</span> : null}
|
||||||
|
{d.level ? <span>{t("Уровень: {level}", { level: d.level })}</span> : null}
|
||||||
|
</div>
|
||||||
|
{r.culprit ? <div className="font-mono text-xs break-all">{r.culprit}</div> : null}
|
||||||
|
{d.url ? <div className="font-mono text-xs break-all text-muted-foreground">{d.url}</div> : null}
|
||||||
|
{/* glossary-ignore: link for «Инженер» and the superadmin */}
|
||||||
|
<a href={d.bugsinkUrl} target="_blank" rel="noreferrer" className="inline-flex w-fit items-center gap-1 text-primary hover:underline">{t("Открыть в Bugsink")}<ExternalLink className="size-3.5" /></a>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<Section title={t("Стек")}>
|
||||||
|
<ErrorStack d={d} t={t} />
|
||||||
|
</Section>
|
||||||
|
|
||||||
|
<Section title={t("Теги")} count={tags.length}>
|
||||||
|
{tags.length === 0 ? (
|
||||||
|
<Empty>{t("Тегов нет.")}</Empty>
|
||||||
|
) : (
|
||||||
|
<div className="overflow-x-auto rounded-md border">
|
||||||
|
<table className="w-full text-sm">
|
||||||
|
<tbody>
|
||||||
|
{tags.map(([k, v]) => (
|
||||||
|
<tr key={k} className="border-t first:border-t-0">
|
||||||
|
<td className="px-3 py-1.5 align-top font-mono text-xs text-muted-foreground">{k}</td>
|
||||||
|
<td className="px-3 py-1.5 font-mono text-xs break-all">
|
||||||
|
{v}
|
||||||
|
{(grouped.get(k)?.length ?? 0) > 1 ? <span className="ml-2 text-muted-foreground">{t("ещё значений: {n}", { n: grouped.get(k)!.length - 1 })}</span> : null}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</Section>
|
||||||
|
|
||||||
|
<Section title={t("Последние события")} count={d.events.length}>
|
||||||
|
{d.events.length === 0 ? (
|
||||||
|
<Empty>{t("Событий нет.")}</Empty>
|
||||||
|
) : (
|
||||||
|
<ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm">
|
||||||
|
{d.events.map((e) => (
|
||||||
|
<li key={e.id} className="flex gap-3">
|
||||||
|
<span className="tabular-nums">{e.at.toLocaleString(t.locale === "en" ? "en-GB" : "ru-RU", { dateStyle: "short", timeStyle: "medium", timeZone: platformZone() })}</span>
|
||||||
|
<span className="font-mono text-xs text-muted-foreground">{e.id.slice(0, 8)}</span>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
</Section>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<p className="text-sm text-muted-foreground">{t("Подробности для разработчиков видны в режиме «Инженер».")}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</Workspace>
|
||||||
|
);
|
||||||
|
}
|
||||||
45
apps/web/app/(app)/errors/actions.ts
Normal file
45
apps/web/app/(app)/errors/actions.ts
Normal file
@ -0,0 +1,45 @@
|
|||||||
|
"use server";
|
||||||
|
// PEP-218: actions on a Bugsink error card. Access is the viewer's error scope (superadmin — all,
|
||||||
|
// otherwise the Bugsink projects of their own projects); outside it — «not found».
|
||||||
|
import { errorScope, PeppaError, platformFailure, setErrorState } from "@peppa/core";
|
||||||
|
import { fileErrorTask, resolveError } from "@peppa/runner";
|
||||||
|
import { m } from "@peppa/shared/i18n";
|
||||||
|
import { revalidatePath } from "next/cache";
|
||||||
|
import { redirect } from "next/navigation";
|
||||||
|
import { asWebActor, requireUser } from "@/lib/auth";
|
||||||
|
import { db } from "@/lib/db";
|
||||||
|
import { getT } from "@/lib/i18n";
|
||||||
|
|
||||||
|
const str = (f: FormData, k: string) => String(f.get(k) ?? "").trim();
|
||||||
|
|
||||||
|
/** Only a local path: no open redirect through `back`. */
|
||||||
|
function safeBack(v: string, fallback: string): string {
|
||||||
|
return v.startsWith("/") && !v.startsWith("//") ? v : fallback;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function errorAction(f: FormData) {
|
||||||
|
const user = asWebActor(await requireUser());
|
||||||
|
const id = str(f, "id");
|
||||||
|
let target = safeBack(str(f, "back"), `/errors/${encodeURIComponent(id)}`);
|
||||||
|
try {
|
||||||
|
const scope = await errorScope(db, user);
|
||||||
|
const action = str(f, "action");
|
||||||
|
if (action === "task") {
|
||||||
|
const r = await fileErrorTask(db, scope, id, user.login);
|
||||||
|
target = `/t/${r.task.key}`;
|
||||||
|
} else if (action === "resolve") await resolveError(db, scope, id, user.login);
|
||||||
|
else if (action === "mute" || action === "unmute" || action === "reopen") await setErrorState(db, scope, id, action);
|
||||||
|
else throw new PeppaError(m("Неизвестное действие"));
|
||||||
|
} catch (e) {
|
||||||
|
const t = await getT();
|
||||||
|
// PEP-154: the text of an unexpected exception goes to the superadmins, not to the page.
|
||||||
|
const why = await platformFailure(db, e, { service: "web", where: "error action" });
|
||||||
|
const msg = why ? t.text(why) : t("Не получилось. Попробуйте ещё раз через минуту.");
|
||||||
|
const [path, query] = target.split("?");
|
||||||
|
const params = new URLSearchParams(query);
|
||||||
|
params.set("error", msg.slice(0, 300));
|
||||||
|
target = `${path}?${params}`;
|
||||||
|
}
|
||||||
|
revalidatePath("/", "layout");
|
||||||
|
redirect(target);
|
||||||
|
}
|
||||||
60
apps/web/app/(app)/feedback/page.tsx
Normal file
60
apps/web/app/(app)/feedback/page.tsx
Normal file
@ -0,0 +1,60 @@
|
|||||||
|
import Link from "@/components/Link";
|
||||||
|
import { FEEDBACK_ADMIN_STATUS, FEEDBACK_STATUSES, isFeedbackStatus, isSuperadmin, listAllFeedback, listUserFeedback } from "@peppa/core";
|
||||||
|
import { AdminFeedbackCard, MyFeedbackCard } from "@/components/Feedback";
|
||||||
|
import { Empty, Flash, PageHeader, Section } from "@/components/common";
|
||||||
|
import { Workspace } from "@/components/Workspace";
|
||||||
|
import { requireUser } from "@/lib/auth";
|
||||||
|
import { db } from "@/lib/db";
|
||||||
|
import { getT } from "@/lib/i18n";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
import { pageTitle } from "@/lib/title";
|
||||||
|
|
||||||
|
// PEP-274: the browser tab says which page it is.
|
||||||
|
export async function generateMetadata() {
|
||||||
|
const t = await getT();
|
||||||
|
return pageTitle(t, t("Обращения"));
|
||||||
|
}
|
||||||
|
|
||||||
|
export default async function FeedbackPage({ searchParams }: { searchParams: Promise<{ error?: string; status?: string; id?: string }> }) {
|
||||||
|
const user = await requireUser();
|
||||||
|
const t = await getT();
|
||||||
|
const { error, status, id } = await searchParams;
|
||||||
|
const superadmin = await isSuperadmin(db, user);
|
||||||
|
const mine = await listUserFeedback(db, user.id);
|
||||||
|
const filter = isFeedbackStatus(status) ? status : null;
|
||||||
|
const all = superadmin ? await listAllFeedback(db, { status: filter }) : [];
|
||||||
|
// A link from a message opens one report first.
|
||||||
|
const focus = Number(id);
|
||||||
|
const sorted = Number.isInteger(focus) ? [...all].sort((a, b) => Number(b.id === focus) - Number(a.id === focus)) : all;
|
||||||
|
const back = `/feedback${filter ? `?status=${filter}` : ""}`;
|
||||||
|
const tab = (href: string, label: string, active: boolean) => (
|
||||||
|
<Link key={href} href={href} aria-current={active ? "page" : undefined} className={cn("rounded-full border px-3 py-1 text-sm text-muted-foreground hover:text-foreground hover:no-underline", active && "border-primary/40 bg-primary/10 font-medium text-foreground")}>
|
||||||
|
{label}
|
||||||
|
</Link>
|
||||||
|
);
|
||||||
|
return (
|
||||||
|
<Workspace>
|
||||||
|
<div className="max-w-3xl">
|
||||||
|
<Flash error={error} />
|
||||||
|
<PageHeader title={t("Обращения")}>{t("Здесь всё, что вы сообщили о проблемах в FORGE, и что с этим стало. Новое обращение — кнопка «Сообщить о проблеме» внизу любой страницы.")}</PageHeader>
|
||||||
|
{superadmin && (
|
||||||
|
<Section title={t("Обращения пользователей")} count={all.length}>
|
||||||
|
<nav aria-label={t("Статус")} className="mb-1 flex flex-wrap gap-2">
|
||||||
|
{tab("/feedback", t("Все"), !filter)}
|
||||||
|
{FEEDBACK_STATUSES.map((s) => tab(`/feedback?status=${s}`, t.text(FEEDBACK_ADMIN_STATUS[s]), filter === s))}
|
||||||
|
</nav>
|
||||||
|
{sorted.length === 0 ? <Empty>{t("Таких обращений нет.")}</Empty> : sorted.map((f) => <AdminFeedbackCard key={f.id} f={f} back={back} />)}
|
||||||
|
</Section>
|
||||||
|
)}
|
||||||
|
<Section title={t("Ваши обращения")} count={mine.length}>
|
||||||
|
{mine.length === 0 ? <Empty>{t("Вы пока ничего не сообщали. Заметили проблему — нажмите «Сообщить о проблеме».")}</Empty> : mine.map((f) => <MyFeedbackCard key={f.id} f={f} />)}
|
||||||
|
</Section>
|
||||||
|
</div>
|
||||||
|
</Workspace>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PEP-143: «Обращения». Everybody sees their own reports and where they stand; the superadmin
|
||||||
|
* also sees everybody's, filtered by status, and decides on them.
|
||||||
|
*/
|
||||||
32
apps/web/app/(app)/gitea/actions.ts
Normal file
32
apps/web/app/(app)/gitea/actions.ts
Normal file
@ -0,0 +1,32 @@
|
|||||||
|
"use server";
|
||||||
|
// «Gitea» (PEP-280): the superadmin closes one public repository at a time.
|
||||||
|
|
||||||
|
import { PeppaError, requireSuperadmin } from "@peppa/core";
|
||||||
|
import { makeRepoPrivate } from "@peppa/runner";
|
||||||
|
import { revalidatePath } from "next/cache";
|
||||||
|
import { redirect } from "next/navigation";
|
||||||
|
import { asWebActor, requireUser } from "@/lib/auth";
|
||||||
|
import { db } from "@/lib/db";
|
||||||
|
import { getT } from "@/lib/i18n";
|
||||||
|
|
||||||
|
const str = (f: FormData, k: string) => String(f.get(k) ?? "").trim();
|
||||||
|
|
||||||
|
/** «Сделать закрытым»: back to the same list with what was closed, or the reason it was not. */
|
||||||
|
export async function makeRepoPrivateAction(f: FormData) {
|
||||||
|
const user = asWebActor(await requireUser());
|
||||||
|
const back = new URLSearchParams();
|
||||||
|
for (const k of ["q", "show"]) if (str(f, k)) back.set(k, str(f, k));
|
||||||
|
try {
|
||||||
|
await requireSuperadmin(db, user);
|
||||||
|
const r = await makeRepoPrivate(db, user, str(f, "repo"));
|
||||||
|
back.set("closed", r.fullName);
|
||||||
|
// The list is cached (PEP-273): without a fresh one the repository would still show as public for a minute.
|
||||||
|
back.set("fresh", "1");
|
||||||
|
} catch (e) {
|
||||||
|
const t = await getT();
|
||||||
|
const msg = e instanceof PeppaError ? t.text(e.message) : t("Ошибка: {message}", { message: (e as Error).message });
|
||||||
|
back.set("error", msg.slice(0, 300));
|
||||||
|
}
|
||||||
|
revalidatePath("/gitea");
|
||||||
|
redirect(`/gitea${back.size ? `?${back}` : ""}`);
|
||||||
|
}
|
||||||
191
apps/web/app/(app)/gitea/page.tsx
Normal file
191
apps/web/app/(app)/gitea/page.tsx
Normal file
@ -0,0 +1,191 @@
|
|||||||
|
// glossary-ignore-file: superadmin-only page about the platform's git server — «репозиторий» is the literal object here
|
||||||
|
import Link from "@/components/Link";
|
||||||
|
import { notFound } from "next/navigation";
|
||||||
|
import { ExternalLink, GitBranch, Lock } from "lucide-react";
|
||||||
|
import { giteaServerOverview, isSuperadmin, type GiteaServerRepo } from "@peppa/core";
|
||||||
|
import { ago, Empty, Flash, Notice, PageHeader, Section } from "@/components/common";
|
||||||
|
import { Badge } from "@/components/ui/badge";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Card } from "@/components/ui/card";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { Workspace } from "@/components/Workspace";
|
||||||
|
import { requireUser } from "@/lib/auth";
|
||||||
|
import { makeRepoPrivateAction } from "./actions";
|
||||||
|
import { db } from "@/lib/db";
|
||||||
|
import { getT } from "@/lib/i18n";
|
||||||
|
import type { Translator } from "@peppa/shared/i18n";
|
||||||
|
|
||||||
|
export async function generateMetadata() {
|
||||||
|
const t = await getT();
|
||||||
|
return { title: t("Gitea — FORGE") };
|
||||||
|
}
|
||||||
|
|
||||||
|
type Params = { q?: string; show?: string; closed?: string; error?: string; page?: string; fresh?: string };
|
||||||
|
type Show = "all" | "linked" | "unlinked" | "public";
|
||||||
|
|
||||||
|
/** Rows per page (PEP-273: the whole list made the page over 1 MB). */
|
||||||
|
const PAGE_SIZE = 50;
|
||||||
|
|
||||||
|
function RepoRow({ r, t, q, show }: { r: GiteaServerRepo; t: Translator; q: string; show: Show }) {
|
||||||
|
return (
|
||||||
|
<li className="flex flex-col gap-1 border-b border-border px-4 py-3 last:border-b-0">
|
||||||
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
|
<a href={r.htmlUrl} target="_blank" rel="noreferrer" className="font-mono text-sm font-medium">
|
||||||
|
{r.fullName}
|
||||||
|
<ExternalLink className="ml-1 inline size-3" />
|
||||||
|
</a>
|
||||||
|
{r.private ? (
|
||||||
|
<Badge variant="secondary">
|
||||||
|
<Lock className="size-3" />
|
||||||
|
{t("приватный")}
|
||||||
|
</Badge>
|
||||||
|
) : (
|
||||||
|
<Badge variant="info">{t("публичный")}</Badge>
|
||||||
|
)}
|
||||||
|
{r.empty && <Badge variant="warn">{t("пустой")}</Badge>}
|
||||||
|
{r.archived && <Badge variant="secondary">{t("в архиве")}</Badge>}
|
||||||
|
{r.fork && <Badge variant="secondary">{t("форк")}</Badge>}
|
||||||
|
{r.project ? (
|
||||||
|
<Link href={`/p/${r.project.key}`} className="ml-auto text-xs">
|
||||||
|
{t("проект {key} · {name}", { key: r.project.key, name: r.project.name })}
|
||||||
|
</Link>
|
||||||
|
) : (
|
||||||
|
<span className="ml-auto text-xs text-muted-foreground">{t("не подключён к проекту")}</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{r.description && <div className="text-sm text-muted-foreground">{r.description}</div>}
|
||||||
|
{!r.private && (
|
||||||
|
// PEP-280: one repository at a time; opening it again is the owner's decision in the project settings.
|
||||||
|
<form action={makeRepoPrivateAction} className="mt-1">
|
||||||
|
<input type="hidden" name="repo" value={r.fullName} />
|
||||||
|
{q && <input type="hidden" name="q" value={q} />}
|
||||||
|
{show !== "all" && <input type="hidden" name="show" value={show} />}
|
||||||
|
<Button type="submit" size="sm" variant="outline">
|
||||||
|
<Lock className="size-3" />
|
||||||
|
{t("Сделать закрытым")}
|
||||||
|
</Button>
|
||||||
|
</form>
|
||||||
|
)}
|
||||||
|
<div className="text-xs text-muted-foreground">
|
||||||
|
{t("ветка {branch} · обновлён {when} · {size}", { branch: r.defaultBranch || "—", when: ago(r.updatedAt, t), size: r.sizeKb >= 1024 ? `${(r.sizeKb / 1024).toFixed(1)} MB` : `${r.sizeKb} KB` })}
|
||||||
|
</div>
|
||||||
|
</li>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default async function GiteaPage({ searchParams }: { searchParams: Promise<Params> }) {
|
||||||
|
const user = await requireUser();
|
||||||
|
const t = await getT();
|
||||||
|
if (!(await isSuperadmin(db, user))) notFound();
|
||||||
|
const q = await searchParams;
|
||||||
|
const o = await giteaServerOverview(db, { fresh: q.fresh === "1" });
|
||||||
|
const needle = (q.q ?? "").trim().toLowerCase();
|
||||||
|
const show: Show = q.show === "linked" || q.show === "unlinked" || q.show === "public" ? q.show : "all";
|
||||||
|
const repos = o.repos.filter(
|
||||||
|
(r) =>
|
||||||
|
(!needle || r.fullName.toLowerCase().includes(needle) || r.description.toLowerCase().includes(needle)) &&
|
||||||
|
(show === "all" || (show === "public" ? !r.private : (show === "linked") === !!r.project)),
|
||||||
|
);
|
||||||
|
const open = o.repos.filter((r) => !r.private).length;
|
||||||
|
const pages = Math.max(1, Math.ceil(repos.length / PAGE_SIZE));
|
||||||
|
const page = Math.min(pages, Math.max(1, Number.parseInt(q.page ?? "1", 10) || 1));
|
||||||
|
const shown = repos.slice((page - 1) * PAGE_SIZE, page * PAGE_SIZE);
|
||||||
|
const href = (extra: Record<string, string>) => {
|
||||||
|
const sp = new URLSearchParams();
|
||||||
|
if (q.q) sp.set("q", q.q);
|
||||||
|
if (show !== "all") sp.set("show", show);
|
||||||
|
for (const [k, v] of Object.entries(extra)) sp.set(k, v);
|
||||||
|
const s = sp.toString();
|
||||||
|
return s ? `/gitea?${s}` : "/gitea";
|
||||||
|
};
|
||||||
|
const owners = new Map<string, number>();
|
||||||
|
for (const r of o.repos) owners.set(r.owner, (owners.get(r.owner) ?? 0) + 1);
|
||||||
|
const linked = o.repos.filter((r) => r.project).length;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Workspace>
|
||||||
|
<div className="max-w-4xl">
|
||||||
|
<PageHeader title={<><GitBranch className="mr-1 inline size-5 text-primary" />Gitea</>}>
|
||||||
|
{t("Git-сервер платформы и репозитории на нём — как их видит бот FORGE. Раздел видят только суперадмины.")}
|
||||||
|
</PageHeader>
|
||||||
|
|
||||||
|
<Section title={t("Сервер")}>
|
||||||
|
<Card className="flex flex-col gap-1 p-4 text-sm">
|
||||||
|
<div>
|
||||||
|
{t("Адрес")}:{" "}
|
||||||
|
{o.url ? (
|
||||||
|
<a href={o.url} target="_blank" rel="noreferrer" className="font-mono">
|
||||||
|
{o.url}
|
||||||
|
</a>
|
||||||
|
) : (
|
||||||
|
"—"
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
{t("Бот")}: <span className="font-mono">{o.bot?.login ?? "—"}</span>
|
||||||
|
{o.bot && (o.bot.admin ? <Badge variant="ok" className="ml-2">{t("админ сервера — видит все репозитории")}</Badge> : <Badge variant="warn" className="ml-2">{t("не админ — видит публичные и свои репозитории")}</Badge>)}
|
||||||
|
</div>
|
||||||
|
{o.fetchedAt && (
|
||||||
|
<div className="text-muted-foreground">
|
||||||
|
{t("Список получен {when}", { when: ago(o.fetchedAt, t) })} ·{" "}
|
||||||
|
<a href={href({ fresh: "1" })}>{t("Получить заново")}</a>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{o.repos.length > 0 && (
|
||||||
|
<div className="text-muted-foreground">
|
||||||
|
{t("Репозиториев: {n} · подключены к проектам: {linked}", { n: o.repos.length, linked })} ·{" "}
|
||||||
|
{[...owners].sort((a, b) => b[1] - a[1]).map(([owner, n]) => `${owner} ${n}`).join(", ")}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{o.repos.length > 0 && (
|
||||||
|
<div>
|
||||||
|
{open > 0 ? (
|
||||||
|
<Link href="/gitea?show=public">{t("Публичных: {n} — их видит любой, у кого есть доступ к Gitea", { n: open })}</Link>
|
||||||
|
) : (
|
||||||
|
<span className="text-muted-foreground">{t("Публичных нет")}</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</Card>
|
||||||
|
</Section>
|
||||||
|
|
||||||
|
{q.closed && <Notice>{t("{repo} теперь закрытый: его видят только владелец, участники и бот", { repo: q.closed })}</Notice>}
|
||||||
|
<Flash error={q.error} />
|
||||||
|
{o.error && <Notice>{t("Gitea не ответила: {error}", { error: o.error })}</Notice>}
|
||||||
|
|
||||||
|
<Section title={t("Репозитории")} count={repos.length}>
|
||||||
|
<form className="mb-3 flex flex-wrap items-center gap-2" action="/gitea">
|
||||||
|
<Input name="q" defaultValue={q.q ?? ""} placeholder={t("Поиск по имени или описанию")} className="h-8 max-w-xs" />
|
||||||
|
<select name="show" defaultValue={show} className="h-8 rounded-md border border-input bg-background px-2 text-sm">
|
||||||
|
<option value="all">{t("все")}</option>
|
||||||
|
<option value="linked">{t("подключённые к проектам")}</option>
|
||||||
|
<option value="unlinked">{t("без проекта")}</option>
|
||||||
|
<option value="public">{t("публичные")}</option>
|
||||||
|
</select>
|
||||||
|
<Button type="submit" size="sm">
|
||||||
|
{t("Показать")}
|
||||||
|
</Button>
|
||||||
|
</form>
|
||||||
|
{repos.length === 0 ? (
|
||||||
|
<Empty>{t("Репозиториев не найдено.")}</Empty>
|
||||||
|
) : (
|
||||||
|
<Card className="p-0">
|
||||||
|
<ul>
|
||||||
|
{shown.map((r) => (
|
||||||
|
<RepoRow key={r.fullName} r={r} t={t} q={q.q ?? ""} show={show} />
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</Card>
|
||||||
|
)}
|
||||||
|
{pages > 1 && (
|
||||||
|
<nav className="mt-3 flex items-center gap-3 text-sm">
|
||||||
|
{page > 1 ? <a href={href({ page: String(page - 1) })}>{t("‹ Назад")}</a> : <span className="text-muted-foreground">{t("‹ Назад")}</span>}
|
||||||
|
<span className="text-muted-foreground">{t("Страница {page} из {pages}", { page, pages })}</span>
|
||||||
|
{page < pages ? <a href={href({ page: String(page + 1) })}>{t("Дальше ›")}</a> : <span className="text-muted-foreground">{t("Дальше ›")}</span>}
|
||||||
|
</nav>
|
||||||
|
)}
|
||||||
|
</Section>
|
||||||
|
</div>
|
||||||
|
</Workspace>
|
||||||
|
);
|
||||||
|
}
|
||||||
82
apps/web/app/(app)/help/connect/page.tsx
Normal file
82
apps/web/app/(app)/help/connect/page.tsx
Normal file
@ -0,0 +1,82 @@
|
|||||||
|
import Link from "@/components/Link";
|
||||||
|
import { CONNECT_HELP, featureGateView } from "@peppa/core";
|
||||||
|
import { FeatureGate } from "@/components/FeatureGate";
|
||||||
|
import { LiveRefresh } from "@/components/LiveRefresh";
|
||||||
|
import { PageHeader } from "@/components/common";
|
||||||
|
import { CopyText } from "@/components/CopyText";
|
||||||
|
import { Workspace } from "@/components/Workspace";
|
||||||
|
import { publicOrigin } from "@/lib/auth";
|
||||||
|
import { getLocale, getT } from "@/lib/i18n";
|
||||||
|
import { pageTitle } from "@/lib/title";
|
||||||
|
|
||||||
|
// PEP-274: the browser tab says which page it is.
|
||||||
|
export async function generateMetadata() {
|
||||||
|
const t = await getT();
|
||||||
|
return pageTitle(t, (CONNECT_HELP[t.locale] ?? CONNECT_HELP.ru).title);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default async function ConnectHelp() {
|
||||||
|
const t = CONNECT_HELP[await getLocale()] ?? CONNECT_HELP.ru;
|
||||||
|
const address = `${await publicOrigin()}/mcp`;
|
||||||
|
const tr = await getT();
|
||||||
|
const card = "flex flex-col gap-2 rounded-lg border bg-card px-4 py-3";
|
||||||
|
const h2 = "m-0 text-[15px] font-semibold";
|
||||||
|
return (
|
||||||
|
<Workspace>
|
||||||
|
<div className="max-w-2xl text-sm leading-relaxed">
|
||||||
|
<LiveRefresh scope="features" indicator={false} />
|
||||||
|
<PageHeader crumbs={<Link href="/help" className="text-muted-foreground hover:text-foreground">{t.back}</Link>} title={t.title}>
|
||||||
|
{t.lead}
|
||||||
|
</PageHeader>
|
||||||
|
<div className="flex flex-col gap-3">
|
||||||
|
<section className={card}>
|
||||||
|
<h2 className={h2}>{t.addressTitle}</h2>
|
||||||
|
<FeatureGate view={featureGateView("mcp")} title={tr("MCP временно недоступен")}>
|
||||||
|
<CopyText value={address} label={t.copy} done={t.copied} />
|
||||||
|
</FeatureGate>
|
||||||
|
<p className="m-0 text-muted-foreground">{t.addressNote}</p>
|
||||||
|
</section>
|
||||||
|
{t.apps.map((app) => (
|
||||||
|
<section key={app.id} id={app.id} className={card}>
|
||||||
|
<h2 className={h2}>{app.title}</h2>
|
||||||
|
<p className="m-0 text-muted-foreground">{app.need}</p>
|
||||||
|
<ol className="m-0 flex list-decimal flex-col gap-1.5 pl-5">
|
||||||
|
{app.steps.map((s) => (
|
||||||
|
<li key={s}>{s}</li>
|
||||||
|
))}
|
||||||
|
</ol>
|
||||||
|
</section>
|
||||||
|
))}
|
||||||
|
<section className={card}>
|
||||||
|
<h2 className={h2}>{t.askTitle}</h2>
|
||||||
|
<p className="m-0 text-muted-foreground">{t.askLead}</p>
|
||||||
|
<ul className="m-0 flex list-none flex-col gap-1.5 p-0">
|
||||||
|
{t.asks.map((a) => (
|
||||||
|
<li key={a} className="rounded-md border bg-muted/50 px-3 py-1.5">{a}</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</section>
|
||||||
|
<section className={card}>
|
||||||
|
<h2 className={h2}>{t.troubleTitle}</h2>
|
||||||
|
<dl className="m-0 flex flex-col gap-2">
|
||||||
|
{t.troubles.map((x) => (
|
||||||
|
<div key={x.q}>
|
||||||
|
<dt className="font-medium">{x.q}</dt>
|
||||||
|
<dd className="m-0 text-muted-foreground">{x.a}</dd>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</dl>
|
||||||
|
</section>
|
||||||
|
<section className={card}>
|
||||||
|
<h2 className={h2}>{t.offTitle}</h2>
|
||||||
|
<p className="m-0">{t.off}</p>
|
||||||
|
<Link href="/settings#apps" className="text-primary">{t.offLink}</Link>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
<p className="mt-4 mb-0 text-muted-foreground">{t.other}</p>
|
||||||
|
</div>
|
||||||
|
</Workspace>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** PEP-135: how to connect FORGE to one's own Claude or ChatGPT — step by step; texts live in core/connect-texts.ts. */
|
||||||
@ -1,61 +1,95 @@
|
|||||||
import Link from "next/link";
|
import Link from "@/components/Link";
|
||||||
import { PRODUCT_HELP } from "@peppa/core";
|
import type { ReactNode } from "react";
|
||||||
|
import { CONNECT_HELP, featureGateView, PRODUCT_HELP } from "@peppa/core";
|
||||||
|
import { FeatureGate } from "@/components/FeatureGate";
|
||||||
|
import { LiveRefresh } from "@/components/LiveRefresh";
|
||||||
|
import { m } from "@peppa/shared/i18n";
|
||||||
|
import { getLocale, getT } from "@/lib/i18n";
|
||||||
import { publicOrigin, uiMode } from "@/lib/auth";
|
import { publicOrigin, uiMode } from "@/lib/auth";
|
||||||
import { Workspace } from "@/components/Workspace";
|
import { Workspace } from "@/components/Workspace";
|
||||||
|
import { voiceStoriesEnabled } from "@peppa/shared";
|
||||||
import { PageHeader, Section } from "@/components/common";
|
import { PageHeader, Section } from "@/components/common";
|
||||||
|
import { pageTitle } from "@/lib/title";
|
||||||
|
|
||||||
const TOOLS: Array<[string, string]> = [
|
const TOOLS: Array<[string, string]> = [
|
||||||
["list_projects", "мои проекты, ссылка на репозиторий в Gitea и сколько стори в каждой колонке"],
|
["get_started", m("правила работы для ИИ-клиента: вызывается первым, коротко и без кода")],
|
||||||
["create_project", "новый проект: репозиторий в Gitea (публичный по умолчанию или приватный) + шаблон + OpenSpec, или подключить существующий; отвечает ссылкой на репозиторий и кто его видит"],
|
["list_projects", m("мои проекты, ссылка на репозиторий в Gitea и сколько стори в каждой колонке")],
|
||||||
["list_epics / create_epic / update_epic", "эпики проекта (метки стори) с прогрессом «готово/всего»: завести, переименовать, описать, завершить или убрать в архив; list_goals / create_goal / update_goal — старые имена, работают так же"],
|
["create_project", m("новый проект: репозиторий в Gitea (публичный по умолчанию или приватный) + шаблон + OpenSpec, или подключить существующий; отвечает ссылкой на репозиторий и кто его видит")],
|
||||||
["list_tasks", "доска проекта: Бэклог / В работе / Ревью / Готово, в каждой колонке — по порядку (сверху — важнее); «waits for» — стори ждёт предшественников"],
|
["list_epics / create_epic / update_epic", m("эпики проекта (метки стори) с прогрессом «готово/всего»: завести, переименовать, описать, завершить или убрать в архив; list_goals / create_goal / update_goal — старые имена, работают так же")],
|
||||||
["reorder_task", "поменять место стори на доске (= приоритет): top / bottom в своей колонке, before / after другой стори; диспетчер берёт из бэклога сверху"],
|
["list_tasks", m("доска проекта: Бэклог / В работе / Ревью / Готово, в каждой колонке — по порядку (сверху — важнее); «waits for» — стори ждёт предшественников")],
|
||||||
["archive_task", "убрать стори в архив (пропадает с доски, диспетчера и прогресса эпика, агент останавливается, история остаётся) или вернуть (archived=false)"],
|
["reorder_task", m("поменять место стори на доске (= приоритет): top / bottom в своей колонке, before / after другой стори; диспетчер берёт из бэклога сверху")],
|
||||||
["set_dependencies", "от каких стори зависит стори (blocked_by, список заменяется; [] — убрать все); пока предшественники не в ревью/готово, диспетчер её не берёт; циклы и чужие проекты отклоняются"],
|
["archive_task", m("убрать стори в архив (пропадает с доски, диспетчера и прогресса эпика, агент останавливается, история остаётся) или вернуть (archived=false)")],
|
||||||
["plan_epic / apply_plan", "планировщик: разбить эпик на стори с критериями готовности и зависимостями (черновик, ничего не создаёт); после правок apply_plan создаёт стори в бэклоге под эпиком"],
|
["set_dependencies", m("от каких стори зависит стори (blocked_by, список заменяется; [] — убрать все); пока предшественники не в ревью/готово, диспетчер её не берёт; циклы и чужие проекты отклоняются")],
|
||||||
["get_task", "карточка стори: описание, эпик, статус, OpenSpec, проверки, вопросы, комментарии PM, зависимости, прогресс"],
|
["plan_epic / apply_plan", m("планировщик: разбить эпик на стори с критериями готовности и зависимостями (черновик, ничего не создаёт); после правок apply_plan создаёт стори в бэклоге под эпиком")],
|
||||||
["create_task / update_task", "завести стори (в конец Бэклога, с эпиком epic_id и зависимостями blocked_by); поправить название, описание, эпик, зависимости"],
|
["get_task", m("карточка стори: описание, эпик, статус, OpenSpec, проверки, вопросы, комментарии PM, зависимости, прогресс")],
|
||||||
["move_task", "передвинуть карточку; «В работе» запускает агента, «Бэклог»/«Готово» останавливают"],
|
["create_task / update_task", m("завести стори (в конец Бэклога, с эпиком epic_id и зависимостями blocked_by); поправить название, описание, эпик, зависимости")],
|
||||||
["set_project_visibility", "сделать репозиторий проекта публичным или приватным (только владелец); отвечает новой видимостью и кто видит репозиторий"],
|
["move_task", m("передвинуть карточку; «В работе» запускает агента, «Бэклог»/«Готово» останавливают")],
|
||||||
["list_secrets", "имена секретов проекта (ключи API для агентов); значения не отдаются никогда — заводятся и меняются только в вебе"],
|
["set_project_visibility", m("сделать репозиторий проекта публичным или приватным (только владелец); отвечает новой видимостью и кто видит репозиторий")],
|
||||||
["list_members / add_member / remove_member", "участники проекта: посмотреть, добавить по логину Gitea, убрать или выйти"],
|
["list_secrets", m("имена секретов проекта (ключи API для агентов); значения не отдаются никогда — заводятся и меняются только в вебе")],
|
||||||
["list_inbox / answer_question", "что ждёт вашего ответа; ответить агенту, принять ревью (accept — мержит PR, только при зелёных проверках)"],
|
["list_members / add_member / remove_member", m("участники проекта: посмотреть, добавить по логину Gitea, убрать или выйти")],
|
||||||
["list_releases / deploy", "что выкачено на staging и в прод, история релизов; выкатить здоровый staging в прод"],
|
["list_inbox / answer_question", m("что ждёт вашего ответа; ответить агенту, принять ревью (accept — мержит PR, только при зелёных проверках)")],
|
||||||
["list_incidents / get_incident", "ошибки из прода (Bugsink): статус, место, релиз, частота, стек"],
|
["list_releases / deploy", m("что выкачено на staging и в прод, история релизов; выкатить здоровый staging в прод")],
|
||||||
["decide_incident / resolve_incident", "решить по ошибке: в бэклог, в работу, игнорировать; отметить исправленной"],
|
["list_incidents / get_incident", m("ошибки из прода (Bugsink): статус, место, релиз, частота, стек")],
|
||||||
["get_usage", "лимиты подписок: сколько использовано окон 5 ч и 7 дней и когда сброс; «нет данных», если агенты ещё не сообщали"],
|
["decide_incident / resolve_incident", m("решить по ошибке: в бэклог, в работу, игнорировать; отметить исправленной")],
|
||||||
["get_metrics", "метрики фабрики по проекту: время цикла, доля принятых с первого раза, возвраты с ревью, вопросы, часы раннеров, ожидание PM, расход; по неделям, агентам и эпикам"],
|
["list_errors / get_error", m("ошибки прямо из учёта ошибок: список с фильтрами, карточка со стеком и тегами")],
|
||||||
["get_project_settings / update_project_settings", "автономность проекта: уровень manual / assisted / self / auto (новые проекты — auto) и отдельные настройки — кто берёт стори, одобрение плана, мерж, закрытие, пуш при простое; agent — провайдер, модель, усилия, эскалация и запасной провайдер (у стори — update_task с agent)"],
|
["resolve_error / create_error_task", m("отметить ошибку решённой; завести по ней задачу в бэклоге")],
|
||||||
["get_incident_policy / set_incident_policy", "политика инцидентов проекта: notify, backlog (по умолчанию), start, ask, triage + мини-промпт триажёра"],
|
// glossary-ignore: справочник «Инженера», имя объекта API
|
||||||
|
["search_api / execute", m("режим «код» (PEPPA_MCP_MODE=code|tools|both, по умолчанию both): вместо десятков инструментов — поиск методов API и один скрипт, который вызывает объект peppa (peppa.tasks.list, peppa.tasks.move…) под вашими правами; пределы: 10 с, 32 МБ, ответ 64 КБ, без файлов и сети")],
|
||||||
|
// glossary-ignore: справочник «Инженера», имя объекта API
|
||||||
|
["list_monitors / get_monitor / create_monitor / update_monitor / pause_monitor / delete_monitor / platform_status", m("мониторинги платформы (только суперадмин): состояние, аптайм, журнал проверок; создать, изменить, поставить на паузу, удалить; platform_status — сервисы, задержки, очередь проверок и подписки в одном ответе (в коде — peppa.platform.status())")],
|
||||||
|
["get_usage", m("лимиты подписок: сколько использовано окон 5 ч и 7 дней и когда сброс; «нет данных», если агенты ещё не сообщали")],
|
||||||
|
["get_metrics", m("метрики фабрики по проекту: время цикла, доля принятых с первого раза, возвраты с ревью, вопросы, часы раннеров, ожидание PM, расход; по неделям, агентам и эпикам")],
|
||||||
|
["get_project_settings / update_project_settings", m("автономность проекта: уровень manual / assisted / self / auto (новые проекты — auto) и отдельные настройки — кто берёт стори, одобрение плана, мерж, закрытие, пуш при простое; agent — провайдер, модель, усилия, эскалация и запасной провайдер (у стори — update_task с agent)")],
|
||||||
|
["get_incident_policy / set_incident_policy", m("политика инцидентов проекта: notify, backlog (по умолчанию), start, ask, triage + мини-промпт триажёра")],
|
||||||
];
|
];
|
||||||
|
|
||||||
const CASES: Array<{ title: string; say: string; how: string }> = [
|
const CASES: Array<{ title: string; say: string; how: string }> = [
|
||||||
{ title: "Создать проект", say: "Создай проект «Платежи», репо payments, ключ PAY", how: "create_project → проект с доской; агенты будут работать в этом репозитории" },
|
{ title: m("Создать проект"), say: m("Создай проект «Платежи», репо payments, ключ PAY"), how: m("create_project → проект с доской; агенты будут работать в этом репозитории") },
|
||||||
{ title: "Завести эпик", say: "В PAY заведи эпик «Оплата картой» — зачем и какой результат", how: "create_epic. Эпик — метка, которая группирует стори; его описание агент получает вместе со стори" },
|
{ title: m("Завести эпик"), say: m("В PAY заведи эпик «Оплата картой» — зачем и какой результат"), how: m("create_epic. Эпик — метка, которая группирует стори; его описание агент получает вместе со стори") },
|
||||||
{ title: "Создать стори в эпике", say: "В этом эпике создай стори «Форма оплаты» с условиями готовности: …", how: "create_task с epic_id. Стори — одна бизнесовая история (один OpenSpec change). Пишите контекст и список «Условия готовности» — по ним работает агент" },
|
{ title: m("Создать стори в эпике"), say: m("В этом эпике создай стори «Форма оплаты» с условиями готовности: …"), how: m("create_task с epic_id. Стори — одна бизнесовая история (один OpenSpec change). Пишите контекст и список «Условия готовности» — по ним работает агент") },
|
||||||
{ title: "Поправить стори", say: "Переименуй PAY-3 в … и замени описание на …; перенеси в эпик #5", how: "update_task — статус и агент не трогаются, дубликат не нужен" },
|
{ title: m("Поправить стори"), say: m("Переименуй PAY-3 в … и замени описание на …; перенеси в эпик #5"), how: m("update_task — статус и агент не трогаются, дубликат не нужен") },
|
||||||
{ title: "Посмотреть статус", say: "Покажи доску PAY · Что с PAY-3?", how: "list_tasks / get_task" },
|
{ title: m("Посмотреть статус"), say: m("Покажи доску PAY · Что с PAY-3?"), how: "list_tasks / get_task" },
|
||||||
{ title: "Запустить работу", say: "Двинь PAY-3 в работу", how: "move_task → in_progress: агент составляет план, реализует, открывает PR и переводит стори в Ревью" },
|
{ title: m("Запустить работу"), say: m("Двинь PAY-3 в работу"), how: m("move_task → in_progress: агент составляет план, реализует, открывает PR и переводит стори в Ревью") },
|
||||||
{ title: "Ответить агенту", say: "Что ждёт моего ответа? · Ответь на #42: берём Postgres", how: "list_inbox → answer_question. Агенты спрашивают только об архитектурных стопперах" },
|
{ title: m("Ответить агенту"), say: m("Что ждёт моего ответа? · Ответь на #42: берём Postgres"), how: m("list_inbox → answer_question. Агенты спрашивают только об архитектурных стопперах") },
|
||||||
{ title: "Принять ревью", say: "Прими PAY-3 · Верни PAY-3: добавь тесты", how: "answer_question с accept (→ Готово) или с замечанием (агент доработает)" },
|
{ title: m("Принять ревью"), say: m("Прими PAY-3 · Верни PAY-3: добавь тесты"), how: m("answer_question с accept (→ Готово) или с замечанием (агент доработает)") },
|
||||||
{ title: "Остановить", say: "Верни PAY-3 в бэклог", how: "move_task → backlog: агент останавливается, открытые вопросы закрываются" },
|
{ title: m("Остановить"), say: m("Верни PAY-3 в бэклог"), how: m("move_task → backlog: агент останавливается, открытые вопросы закрываются") },
|
||||||
{ title: "Работать вместе", say: "Добавь в PAY участника dana", how: "add_member (только владелец). Участник видит доску и входящие, двигает карточки, отвечает агентам и получает доступ к репозиторию. Тот, кто ещё не входил в Пеппу, получит приглашение — оно сработает при первом входе" },
|
{ title: m("Работать вместе"), say: m("Добавь в PAY участника dana"), how: m("add_member (только владелец). Участник видит доску и входящие, двигает карточки, отвечает агентам и получает доступ к репозиторию. Тот, кто ещё не входил в FORGE, получит приглашение — оно сработает при первом входе") },
|
||||||
{ title: "Автономность", say: "Пусть PAY делается сам: бери стори из бэклога и мержи зелёные PR", how: "update_project_settings level=auto. «С подсказками» (assisted) — только пуш, когда агенты простаивают. То же — «⋯ Настройки проекта» → «Автономность»" },
|
{ title: m("Автономность"), say: m("Пусть PAY делается сам: бери стори из бэклога и мержи зелёные PR"), how: m("update_project_settings level=auto. «С подсказками» (assisted) — только пуш, когда агенты простаивают. То же — «⋯ Настройки проекта» → «Автономность»") },
|
||||||
{ title: "Модель агента", say: "Рутину в PAY делай на sonnet, а если проверки дважды красные — переходи на opus", how: "update_project_settings agent={model: sonnet, escalate_model: opus, escalate_after: 2}. Для одной стори — update_task с agent. То же — «⋯ Настройки проекта» → «Модель агента» и раздел «Агент» на странице стори" },
|
{ title: m("Модель агента"), say: m("Рутину в PAY делай на sonnet, а если проверки дважды красные — переходи на opus"), how: m("update_project_settings agent={model: sonnet, escalate_model: opus, escalate_after: 2}. Для одной стори — update_task с agent. То же — «⋯ Настройки проекта» → «Модель агента» и раздел «Агент» на странице стори") },
|
||||||
{ title: "Видимость репозитория", say: "Сделай репозиторий PAY приватным", how: "set_project_visibility (только владелец). Новые проекты публичные по умолчанию; то же — в вебе: «⋯ Настройки проекта» → «Репозиторий»" },
|
{ title: m("Видимость репозитория"), say: m("Сделай репозиторий PAY публичным"), how: m("set_project_visibility (только владелец). Новые проекты закрытые по умолчанию; то же — в вебе: «⋯ Настройки проекта» → «Репозиторий»") },
|
||||||
{ title: "Ошибки из прода", say: "Какие ошибки ждут решения в PAY? · Ошибку #7 — в работу", how: "list_incidents → decide_incident. Подключение — на странице проекта «⋯ Настройки проекта → Баги»" },
|
{ title: m("Ошибки из прода"), say: m("Какие ошибки ждут решения в PAY? · Ошибку #7 — в работу"), how: m("list_incidents → decide_incident. Подключение — на странице проекта «⋯ Настройки проекта → Баги»") },
|
||||||
{ title: "Политика инцидентов", say: "В PAY пусть ошибки разбирает триажёр: падения оплаты — сразу в работу, косметику — в бэклог, остальное спроси", how: "set_incident_policy policy=triage, triage_prompt — ваши слова. Не уверен — спросит кнопками в Telegram" },
|
{ title: m("Политика инцидентов"), say: m("В PAY пусть ошибки разбирает триажёр: падения оплаты — сразу в работу, косметику — в бэклог, остальное спроси"), how: m("set_incident_policy policy=triage, triage_prompt — ваши слова. Не уверен — спросит кнопками в Telegram") },
|
||||||
{ title: "Выкатить в прод", say: "Что сейчас на staging в PAY? · Выкати PAY в прод", how: "list_releases → deploy. Тот же образ, что прошёл staging; не поднялся — Пеппа сама откатит и напишет" },
|
{ title: m("Выкатить в прод"), say: m("Что сейчас на staging в PAY? · Выкати PAY в прод"), how: m("list_releases → deploy. Тот же образ, что прошёл staging; не поднялся — FORGE сама откатит и напишет") },
|
||||||
{ title: "Разбить эпик на стори", say: "Спланируй эпик «Оплата картой» в PAY: сначала API, потом экран", how: "plan_epic → черновик со стори, критериями готовности и зависимостями; поправьте и подтвердите — apply_plan создаст стори. В вебе — «Спланировать стори эпика» над доской или в «⋯ Настройки проекта → Эпики»" },
|
{ title: m("Разбить эпик на стори"), say: m("Спланируй эпик «Оплата картой» в PAY: сначала API, потом экран"), how: m("plan_epic → черновик со стори, критериями готовности и зависимостями; поправьте и подтвердите — apply_plan создаст стори. В вебе — «Спланировать стори эпика» над доской или в «⋯ Настройки проекта → Эпики»") },
|
||||||
{ title: "Приоритет", say: "Подними PAY-7 наверх бэклога · Поставь PAY-9 перед PAY-4", how: "reorder_task. Порядок в колонке = приоритет: диспетчер (автономность) берёт стори сверху. В вебе — перетащите карточку внутри колонки" },
|
{ title: m("Приоритет"), say: m("Подними PAY-7 наверх бэклога · Поставь PAY-9 перед PAY-4"), how: m("reorder_task. Порядок в колонке = приоритет: диспетчер (автономность) берёт стори сверху. В вебе — перетащите карточку внутри колонки") },
|
||||||
{ title: "Зависимости", say: "PAY-8 делать только после PAY-6", how: "set_dependencies (или blocked_by в create_task / update_task). На карточке — «ждёт PAY-6», диспетчер её не возьмёт, пока PAY-6 не в ревью или готово" },
|
{ title: m("Зависимости"), say: m("PAY-8 делать только после PAY-6"), how: m("set_dependencies (или blocked_by в create_task / update_task). На карточке — «ждёт PAY-6», диспетчер её не возьмёт, пока PAY-6 не в ревью или готово") },
|
||||||
{ title: "Убрать стори", say: "PAY-5 больше не нужна", how: "archive_task — стори пропадает с доски, история остаётся; вернуть — archived=false или «Вернуть» на странице стори" },
|
{ title: m("Убрать стори"), say: m("PAY-5 больше не нужна"), how: m("archive_task — стори пропадает с доски, история остаётся; вернуть — archived=false или «Вернуть» на странице стори") },
|
||||||
{ title: "Закрыть эпик", say: "Эпик #5 закончен", how: "update_epic status=done — эпик пропадает из фильтра доски, стори не меняются" },
|
{ title: m("Закрыть эпик"), say: m("Эпик #5 закончен"), how: m("update_epic status=done — эпик пропадает из фильтра доски, стори не меняются") },
|
||||||
];
|
];
|
||||||
|
|
||||||
|
/** Renders a translated string with a small markup: <b>, <code>, <m> (monospace), <a href="/path"> (Link). */
|
||||||
|
const TAG = /<(b|code|m)>([\s\S]*?)<\/\1>|<a href="([^"]+)">([\s\S]*?)<\/a>/g;
|
||||||
|
function rich(s: string): ReactNode {
|
||||||
|
const out: ReactNode[] = [];
|
||||||
|
let last = 0;
|
||||||
|
for (const mt of s.matchAll(TAG)) {
|
||||||
|
if (mt.index > last) out.push(s.slice(last, mt.index));
|
||||||
|
const k = mt.index;
|
||||||
|
if (mt[3]) out.push(<Link key={k} href={mt[3]}>{mt[4]}</Link>);
|
||||||
|
else if (mt[1] === "b") out.push(<b key={k}>{mt[2]}</b>);
|
||||||
|
else if (mt[1] === "code") out.push(<code key={k}>{mt[2]}</code>);
|
||||||
|
else out.push(<span key={k} className="font-mono">{mt[2]}</span>);
|
||||||
|
last = mt.index + mt[0].length;
|
||||||
|
}
|
||||||
|
if (last < s.length) out.push(s.slice(last));
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
/** PEP-122: «Помощь» for the «Продакт» view — one screen, three answers; texts live in core/help-texts.ts. */
|
/** PEP-122: «Помощь» for the «Продакт» view — one screen, three answers; texts live in core/help-texts.ts. */
|
||||||
function ProductHelp() {
|
async function ProductHelp() {
|
||||||
const t = PRODUCT_HELP.ru;
|
const t = PRODUCT_HELP[await getLocale()] ?? PRODUCT_HELP.ru;
|
||||||
|
const connect = CONNECT_HELP[await getLocale()] ?? CONNECT_HELP.ru;
|
||||||
|
const tr = await getT();
|
||||||
return (
|
return (
|
||||||
<Workspace>
|
<Workspace>
|
||||||
<div className="max-w-2xl text-sm leading-relaxed">
|
<div className="max-w-2xl text-sm leading-relaxed">
|
||||||
@ -76,7 +110,28 @@ function ProductHelp() {
|
|||||||
</section>
|
</section>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
<section className="mt-4" data-help-roles>
|
||||||
|
<h2 className="m-0 mb-1.5 text-base font-semibold">{t.roles.title}</h2>
|
||||||
|
<ul className="m-0 flex list-disc flex-col gap-1 pl-5">
|
||||||
|
{t.roles.items.map((x) => <li key={x}>{x}</li>)}
|
||||||
|
</ul>
|
||||||
|
</section>
|
||||||
<p className="mt-4 mb-0">{t.question}</p>
|
<p className="mt-4 mb-0">{t.question}</p>
|
||||||
|
<p className="mt-4 mb-0">{t.product}</p>
|
||||||
|
<section className="mt-4" data-help-messages>
|
||||||
|
<h2 className="m-0 mb-1.5 text-base font-semibold">{t.messages.title}</h2>
|
||||||
|
<ul className="m-0 flex list-disc flex-col gap-1 pl-5">
|
||||||
|
{t.messages.items.map((x) => <li key={x}>{x}</li>)}
|
||||||
|
</ul>
|
||||||
|
</section>
|
||||||
|
<p className="mt-4 mb-0">
|
||||||
|
{t.problem}{" "}
|
||||||
|
<Link href="/feedback" className="text-primary">{tr("Ваши обращения")}</Link>
|
||||||
|
</p>
|
||||||
|
<p className="mt-4 mb-0">
|
||||||
|
{connect.linkFromHelp}{" "}
|
||||||
|
<Link href="/help/connect" className="text-primary">{connect.linkLabel}</Link>
|
||||||
|
</p>
|
||||||
<p className="mt-4 mb-0 text-muted-foreground">
|
<p className="mt-4 mb-0 text-muted-foreground">
|
||||||
{t.more}{" "}
|
{t.more}{" "}
|
||||||
<Link href="/settings#mode" className="text-primary">{t.moreLink}</Link>
|
<Link href="/settings#mode" className="text-primary">{t.moreLink}</Link>
|
||||||
@ -86,73 +141,85 @@ function ProductHelp() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// PEP-274: the browser tab says which page it is.
|
||||||
|
export async function generateMetadata() {
|
||||||
|
const t = await getT();
|
||||||
|
return pageTitle(t, t("Помощь"));
|
||||||
|
}
|
||||||
|
|
||||||
export default async function Help() {
|
export default async function Help() {
|
||||||
if ((await uiMode()) === "product") return <ProductHelp />;
|
if ((await uiMode()) === "product") return <ProductHelp />;
|
||||||
|
const t = await getT();
|
||||||
const mcp = `${await publicOrigin()}/mcp`;
|
const mcp = `${await publicOrigin()}/mcp`;
|
||||||
return (
|
return (
|
||||||
<Workspace>
|
<Workspace>
|
||||||
<div className="max-w-3xl text-sm leading-relaxed [&_a]:text-primary [&_code]:font-mono [&_code]:text-[0.92em] [&_li]:my-1 [&_ul]:m-0 [&_ul]:list-disc [&_ul]:pl-5">
|
<div className="max-w-3xl text-sm leading-relaxed [&_a]:text-primary [&_code]:font-mono [&_code]:text-[0.92em] [&_li]:my-1 [&_ul]:m-0 [&_ul]:list-disc [&_ul]:pl-5">
|
||||||
<PageHeader title="Помощь">Понятия Пеппы, подключение MCP-клиентов и что можно попросить.</PageHeader>
|
<PageHeader title={t("Помощь")}>{t("Понятия FORGE, подключение MCP-клиентов и что можно попросить.")}</PageHeader>
|
||||||
|
|
||||||
<Section title="Как устроена Пеппа">
|
<Section title={t("Как устроена FORGE")}>
|
||||||
<ul>
|
<ul>
|
||||||
<li><b>Проект</b> — репозиторий в Gitea с ключом стори (например, PEP). Создаётся из веба или через MCP. Страница проекта устроена как в GitHub: вкладки <b>Доска · Код</b> (README, ветки, коммиты) <b>· Спеки</b> (что система умеет сейчас — <span className="font-mono">openspec/specs</span>) <b>· PR</b> (открытые PR и их проверки) <b>· Релизы · Баги · Сессии</b>; «+ Стори» и «⋯ Настройки проекта» (репозиторий, эпики, баги, участники) — в заголовке.</li>
|
<li>{rich(t("<b>Проект</b> — репозиторий в Gitea с ключом стори (например, PEP). Создаётся из веба или через MCP. Страница проекта устроена как в GitHub: вкладки <b>Доска · Код</b> (README, ветки, коммиты) <b>· Спеки</b> (что система умеет сейчас — <m>openspec/specs</m>) <b>· PR</b> (открытые PR и их проверки) <b>· Релизы · Баги · Сессии</b>; «+ Стори» и «⋯ Настройки проекта» (репозиторий, эпики, баги, участники) — в заголовке."))}</li>
|
||||||
<li><b>Где репозиторий</b> — в выбранном при создании пространстве Gitea: личном (<span className="font-mono"><ваш логин>/<slug></span>) или организации. По умолчанию он публичный — его видят все, у кого есть доступ к Gitea; приватный видят только владелец пространства (в организации — её участники с доступом), <span className="font-mono">peppa-bot</span> и участники проекта. Ссылка «Открыть в Gitea», видимость, кто видит и кнопка смены видимости (для владельца) — в «⋯ Настройки проекта» → «Репозиторий».</li>
|
<li>{rich(t("<b>Где репозиторий</b> — в выбранном при создании пространстве Gitea: личном (<m><ваш логин>/<slug></m>) или организации. По умолчанию он публичный — его видят все, у кого есть доступ к Gitea; приватный видят только владелец пространства (в организации — её участники с доступом), <m>peppa-bot</m> и участники проекта. Ссылка «Открыть в Gitea», видимость, кто видит и кнопка смены видимости (для владельца) — в «⋯ Настройки проекта» → «Репозиторий»."))}</li>
|
||||||
<li><b>Стори</b> (PEP-12) — одна бизнесовая история с описанием и условиями готовности; агент реализует её одним OpenSpec change. «Задачи» — это пункты <span className="font-mono">tasks.md</span> внутри change, не путать.</li>
|
<li>{rich(t("<b>Стори</b> (PEP-12) — одна бизнесовая история с описанием и условиями готовности; агент реализует её одним OpenSpec change. «Задачи» — это пункты <m>tasks.md</m> внутри change, не путать."))}</li>
|
||||||
<li><b>Эпик</b> — необязательная метка, которая группирует стори («Оплата картой»): тег на карточке, фильтр над доской, выбор в «+ Стори». Его описание агент получает вместе со стори как контекст «зачем». Заводятся в «⋯ Настройки проекта» или через MCP.</li>
|
<li>{rich(t("<b>Эпик</b> — необязательная метка, которая группирует стори («Оплата картой»): тег на карточке, фильтр над доской, выбор в «+ Стори». Его описание агент получает вместе со стори как контекст «зачем». Заводятся в «⋯ Настройки проекта» или через MCP."))}</li>
|
||||||
<li><b>Доска</b> — Бэклог → В работе → Ревью → Готово. Перенос в «В работе» запускает агента. Порядок в колонке — приоритет: перетащите карточку выше или ниже (или ⇈/⇊ на карточке), диспетчер берёт стори из бэклога сверху. Над доской — фильтр по эпику с прогрессом «готово/всего»; «Готово» сворачивается. Ненужную стори — «В архив» на её странице (история остаётся, вернуть можно там же).</li>
|
<li>{rich(t("<b>Доска</b> — Бэклог → В работе → Ревью → Готово. Перенос в «В работе» запускает агента. Порядок в колонке — приоритет: перетащите карточку выше или ниже (или ⇈/⇊ на карточке), диспетчер берёт стори из бэклога сверху. Над доской — фильтр по эпику с прогрессом «готово/всего»; «Готово» сворачивается. Ненужную стори — «В архив» на её странице (история остаётся, вернуть можно там же)."))}</li>
|
||||||
<li><b>Зависимости и планировщик</b> — стори может ждать другие стори («ждёт PAY-2» на карточке, блок «Зависимости» на странице стори): пока предшественник не в ревью или готово, диспетчер её не берёт. «Спланировать стори эпика» — короткая сессия Claude (на подписке пула проекта) предлагает стори эпика с критериями готовности и зависимостями; вы правите черновик и создаёте стори одной кнопкой.</li>
|
<li>{rich(t("<b>Зависимости и планировщик</b> — стори может ждать другие стори («ждёт PAY-2» на карточке, блок «Зависимости» на странице стори): пока предшественник не в ревью или готово, диспетчер её не берёт. «Спланировать стори эпика» — короткая сессия Claude (на подписке пула проекта) предлагает стори эпика с критериями готовности и зависимостями; вы правите черновик и создаёте стори одной кнопкой."))}</li>
|
||||||
<li><b>Клавиатура</b> — <b>⌘K</b> (Ctrl+K) или «Поиск» в меню открывает палитру: проекты, стори, раннеры, вопросы и разделы; Enter — перейти, ⌘Enter — стори из бэклога в работу. Остальные сочетания — <Link href="/help/shortcuts">Горячие клавиши</Link> (или <b>?</b>).</li>
|
<li>{rich(t("<b>Клавиатура</b> — <b>⌘K</b> (Ctrl+K) или «Поиск» в меню открывает палитру: проекты, стори, раннеры, вопросы и разделы; Enter — перейти, ⌘Enter — стори из бэклога в работу. Остальные сочетания — <a href=\"/help/shortcuts\">Горячие клавиши</a> (или <b>?</b>)."))}</li>
|
||||||
<li><b>Агент</b> — Claude Code, Codex или OpenCode в сессии на машине Пеппы: составляет план стори (OpenSpec), реализует, открывает PR и отдаёт стори на ревью.</li>
|
<li>{rich(t("<b>Агент</b> — Claude Code, Codex или OpenCode в сессии на машине FORGE: составляет план стори (OpenSpec), реализует, открывает PR и отдаёт стори на ревью."))}</li>
|
||||||
<li><b>Участники</b> — владелец проекта добавляет людей по логину Gitea (блок «Участники» на странице проекта). Агенты проекта работают на подписках из пула проекта.</li>
|
<li>{rich(t("<b>Участники</b> — владелец проекта добавляет людей по логину Gitea (блок «Участники» на странице проекта). Агенты проекта работают на подписках из пула проекта."))}</li>
|
||||||
<li><b>Подписка проекта</b> — на чём работают агенты. В проекте без подписки сверху появляется подсказка: нажмите «Подключить Claude» или «Подключить ChatGPT», откройте ссылку, войдите в свой аккаунт и (для Claude) вставьте код, который он покажет. Терминал не нужен. Готовый токен или ключ OpenAI API — в «⋯ Настройки проекта → Подписки».</li>
|
<li>{rich(t("<b>Подписка проекта</b> — на чём работают агенты. В проекте без подписки сверху появляется подсказка: нажмите «Подключить Claude» или «Подключить ChatGPT», откройте ссылку, войдите в свой аккаунт и (для Claude) вставьте код, который он покажет. Терминал не нужен. Готовый токен или ключ OpenAI API — в «⋯ Настройки проекта → Подписки»."))}</li>
|
||||||
<li><b>Стори берутся сами</b> — в новом проекте карточки перетаскивать не нужно: агент сам берёт стори из бэклога по порядку на доске, вам остаётся «Принять» результат. Уровень «Сам берёт» меняется в «⋯ Настройки проекта → Автономность».</li>
|
<li>{rich(t("<b>Стори берутся сами</b> — в новом проекте карточки перетаскивать не нужно: агент сам берёт стори из бэклога по порядку на доске, вам остаётся «Принять» результат. Уровень «Сам берёт» меняется в «⋯ Настройки проекта → Автономность»."))}</li>
|
||||||
<li><b>Telegram</b> — у каждого пользователя свой бот: в «Настройки → Telegram» три шага — создать бота у @BotFather (команда <span className="font-mono">/newbot</span>), вставить его токен, открыть бота и нажать Start. Из него приходят вопросы агентов и «готово к ревью», ему же можно написать новую задачу. Не хотите создавать — там же можно выбрать общего бота Пеппы.</li>
|
<li>{rich(t("<b>Telegram</b> — у каждого пользователя свой бот: в «Настройки → Telegram» три шага — создать бота у @BotFather (команда <m>/newbot</m>), вставить его токен, открыть бота и нажать Start. Из него приходят вопросы агентов и «готово к ревью», ему же можно написать новую задачу. Ему же можно наговорить задачу голосовым, если на сервере включено распознавание речи."))}</li>
|
||||||
<li><b>Продакт и аналитик</b> — два агента, которые читают новую задачу раньше разработчика. Продакт решает, зачем это и что берём в первую версию (большое делит на несколько стори). Аналитик пишет критерии приёмки и задаёт до трёх вопросов — у каждого есть вариант по умолчанию; не ответите за 30 минут (ночью — до утра), он возьмёт его сам. Их реплики — во вкладке Comments стори и в чате проекта. Включается в «⋯ Настройки проекта → Продакт и аналитик», в новых проектах включено.</li>
|
<li>{rich(t("<b>Аналитик</b> — единственный, кто говорит с владельцем: в чате проекта, на Главной и в Telegram. Вопросы агентов-разработчиков идут через него (MCP <code>ask_pm</code>): технический вопрос и повтор до владельца не доходят, вопрос о продукте — один раз, словами Аналитика, с вариантами. Готовые задачи, которых владелец не ждёт, приходят сводкой в конце рабочего дня; застрявшая задача (агент свободен больше часа, проверки зелёные) — суперадмину. На входе Аналитик одним запросом разбирает новую задачу: цель, урезание, разбивка (не больше четырёх частей; остальные ждут приёмки первой), критерии приёмки, решения на развилках — блок «Фабрика решила за вас» на странице задачи с «Подходит» / «Нужно иначе». Вопросов не задаёт и ответа не ждёт. Включается в «⋯ Настройки проекта → Аналитик на входе задачи», в новых проектах включено. Задачи из чата заводятся только кнопкой «Завести задачи». Находки агента приёмки — одним списком в «Предложено»."))}</li>
|
||||||
<li><b>Команда</b> — ИИ-агенты с кличками (Шустрик, Беркут…), одна команда на все проекты: свободный агент берёт стори и ведёт её до конца, его кличка видна на карточке. В разделе «Команда» суперадмин задаёт агенту характер и специализацию — они добавляются к его промпту.</li>
|
<li>{rich(t("<b>Команда</b> — ИИ-агенты с кличками (Шустрик, Беркут…), одна команда на все проекты: свободный агент берёт стори и ведёт её до конца, его кличка видна на карточке. В разделе «Команда» суперадмин задаёт агенту характер и специализацию — они добавляются к его промпту."))}</li>
|
||||||
<li><b>Вход</b> — через eGov QR (с телефона — кнопка «Открыть в eGov Mobile») или через Google (кнопка есть, когда суперадмин задал <span className="font-mono">GOOGLE_CLIENT_ID/SECRET</span>); в «Настройках» их можно связать в одну учётку. Первый вход сам создаёт учётку по ИИН или Google-почте: логин из имени в сертификате (например, <span className="font-mono">aigerim.ivanova</span>). Новый пользователь видит только проекты, куда его пригласили, и свои; агенты его проектов работают только на пуле подписок, который назначает суперадмин. У такой учётки нет аккаунта Gitea — код только через Пеппу, а новые проекты создаются в пространстве <span className="font-mono">peppa-bot</span>.</li>
|
<li>{rich(t("<b>Вход</b> — через eGov QR (с телефона — кнопка «Открыть в eGov Mobile») или через Google (кнопка есть, когда суперадмин задал <m>GOOGLE_CLIENT_ID/SECRET</m>); в «Настройках» их можно связать в одну учётку. Первый вход сам создаёт учётку по ИИН или Google-почте: логин из имени в сертификате (например, <m>aigerim.ivanova</m>). Новый пользователь видит только проекты, куда его пригласили, и свои; агенты его проектов работают только на пуле подписок, который назначает суперадмин. У такой учётки нет аккаунта Gitea — код только через FORGE, а новые проекты создаются в пространстве <m>peppa-bot</m>."))}</li>
|
||||||
<li><b>Раннер</b> — агент, запущенный по стори в tmux на машине Пеппы. Все раннеры ваших и общих проектов — в разделе <Link href="/runners">Раннеры</Link>: статус, стори, команда <code>tmux attach</code>, сообщение, остановка и resume; фильтры-счётчики «ждут вас / работают / упали / готово» и поиск; строки, где нужны вы, подсвечены, у раннера на лимите — «остановлена · продолжит в HH:MM». Выбери раннер — справа его детали, вопросы, действия и <b>живой терминал</b>: экран агента в реальном времени с историей (прокрутка), размер шрифта A−/A+ и режим во весь экран. Кнопка «Ввод» позволяет печатать агенту прямо в терминал (вставка многострочного текста уходит одной вставкой, для телефона есть Esc, Tab, стрелки, Enter, Ctrl-C); ввод сбрасывает счётчик автопродолжений и отмечается в событиях раннера. Тот же терминал — на странице стори у работающего раннера. Терминал доступен владельцу и участникам проекта.</li>
|
<li>{rich(t("<b>Раннер</b> — агент, запущенный по стори в tmux на машине FORGE. Все раннеры ваших и общих проектов — в разделе <a href=\"/runners\">Раннеры</a>: статус, стори, команда <code>tmux attach</code>, сообщение, остановка и resume; фильтры-счётчики «ждут вас / работают / упали / готово» и поиск; строки, где нужны вы, подсвечены, у раннера на лимите — «остановлена · продолжит в HH:MM». Выбери раннер — справа его детали, вопросы, действия и <b>живой терминал</b>: экран агента в реальном времени с историей (прокрутка), размер шрифта A−/A+ и режим во весь экран. Кнопка «Ввод» позволяет печатать агенту прямо в терминал (вставка многострочного текста уходит одной вставкой, для телефона есть Esc, Tab, стрелки, Enter, Ctrl-C); ввод сбрасывает счётчик автопродолжений и отмечается в событиях раннера. Тот же терминал — на странице стори у работающего раннера. Терминал доступен владельцу и участникам проекта."))}</li>
|
||||||
<li><b>Новый терминал</b> — раннер без стори: в «Раннерах» или на вкладке «Сессии» проекта выберите проект, имя, агента и напишите промпт (можно голосом — кнопка «Голосом» в браузерах с распознаванием речи). После ходов такой раннер не пингует — им управляете вы в терминале. Получилась работа — «Оформить стори» в карточке раннера: стори создаётся в работе, раннер ведёт её дальше. Раннер можно переименовать.</li>
|
<li>{rich(t("<b>Новый терминал</b> — раннер без стори: в «Раннерах» или на вкладке «Сессии» проекта выберите проект, имя, агента и напишите промпт (можно голосом — кнопка «Голосом» в браузерах с распознаванием речи). После ходов такой раннер не пингует — им управляете вы в терминале. Получилась работа — «Оформить стори» в карточке раннера: стори создаётся в работе, раннер ведёт её дальше. Раннер можно переименовать."))}</li>
|
||||||
<li><b>Раннеры и стори</b> — «⋯ Настройки проекта → Раннеры» (и на странице стори — для неё одной): «один раннер на стори» (по умолчанию) или «раннер ведёт очередь стори» — стори достаётся свободному раннеру, при лимите раннеров проекта ждёт в его очереди, а «Принять» не останавливает раннер, а даёт ему следующую стори; переход — «свежий контекст» (тот же терминал, новый разговор) или «один разговор». «Свой git worktree на раннер» — у каждого раннера своя копия и ветка <code>task/…</code>, параллельные стори не мешают друг другу; копия убирается, когда всё запушено. В карточке раннера — история его стори и очередь.</li>
|
<li>{rich(t("<b>Раннеры и стори</b> — «⋯ Настройки проекта → Раннеры» (и на странице стори — для неё одной): «один раннер на стори» (по умолчанию) или «раннер ведёт очередь стори» — стори достаётся свободному раннеру, при лимите раннеров проекта ждёт в его очереди, а «Принять» не останавливает раннер, а даёт ему следующую стори; переход — «свежий контекст» (тот же терминал, новый разговор) или «один разговор». «Свой git worktree на раннер» — у каждого раннера своя копия и ветка <code>task/…</code>, параллельные стори не мешают друг другу; копия убирается, когда всё запушено. В карточке раннера — история его стори и очередь."))}</li>
|
||||||
<li><b>Изоляция и хосты</b> — там же: «Контейнер на раннер» запускает агента в docker-образе раннера — он видит только свою рабочую копию, работает на подписке из пула проекта и не видит токенов Пеппы и чужих проектов; хуки, MCP и git идут в Пеппу через релей и только к репозиторию проекта (PR агент открывает инструментом <code>open_pull_request</code>). «Где запускать раннеры» — Mac Пеппы или отмеченные хосты: раннер уходит на наименее занятый онлайн-хост, там клонируется рабочая копия, а терминал, ввод и ответы работают как обычно. Хосты подключает суперадмин в разделе «Хосты» (SSH-ключ Пеппы на хосте, tmux и docker); недоступный хост помечается «офлайн», его раннеры не считаются упавшими.</li>
|
<li>{rich(t("<b>Изоляция и хосты</b> — там же: «Контейнер на раннер» запускает агента в docker-образе раннера — он видит только свою рабочую копию, работает на подписке из пула проекта и не видит токенов FORGE и чужих проектов; хуки, MCP и git идут в FORGE через релей и только к репозиторию проекта (PR агент открывает инструментом <code>open_pull_request</code>). «Где запускать раннеры» — Mac FORGE или отмеченные хосты: раннер уходит на наименее занятый онлайн-хост, там клонируется рабочая копия, а терминал, ввод и ответы работают как обычно. Хосты подключает суперадмин в разделе «Хосты» (SSH-ключ FORGE на хосте, tmux и docker); недоступный хост помечается «офлайн», его раннеры не считаются упавшими."))}</li>
|
||||||
<li><b>Главная</b> — вопросы агентов (только архитектурные стопперы) и «готово к ревью», активные раннеры и проекты. Отвечать можно в вебе, Telegram или через MCP. Список проектов и «Новый проект» — в разделе <Link href="/projects">Проекты</Link>.</li>
|
<li>{rich(t("<b>Сообщения агента</b> — четырёх типов. <b>Вопрос</b> — нужно ваше решение о продукте: всегда с вариантами ответа кнопками и вариантом по умолчанию; только он попадает в «Вопросы агентов» на Главной и приходит в Telegram как вопрос. <b>Готово</b> — задачу можно принять: приходит только после того, как проверки прошли, со ссылкой на результат. <b>Ход работы</b> — что агент сделал; лежит в «Событиях агентов» в чате проекта и никого не будит. <b>Блокер</b> — агент не может продолжить: если дело в продукте, он спросит вас с вариантами ответа, остальное уходит администраторам фабрики. Кнопки «Продолжай» больше нет: агента, который ждёт проверок, будит сама FORGE."))}</li>
|
||||||
|
<li>{rich(t("<b>Главная</b> — вопросы агентов (только архитектурные стопперы) и «готово к ревью», активные раннеры и проекты. Отвечать можно в вебе, Telegram или через MCP. Список проектов и «Новый проект» — в разделе <a href=\"/projects\">Проекты</a>."))}</li>
|
||||||
</ul>
|
</ul>
|
||||||
</Section>
|
</Section>
|
||||||
|
|
||||||
<Section title="Подключить MCP">
|
<Section title={t("Подключить MCP")}>
|
||||||
<p className="m-0">Адрес сервера:</p>
|
<LiveRefresh scope="features" indicator={false} />
|
||||||
<code className="block overflow-x-auto rounded-md border bg-muted px-3 py-2 text-sm">{mcp}</code>
|
<FeatureGate view={featureGateView("mcp")} title={t("MCP временно недоступен")}>
|
||||||
|
<p className="m-0">{t("Адрес сервера:")}</p>
|
||||||
|
<code className="block overflow-x-auto rounded-md border bg-muted px-3 py-2 text-sm">{mcp}</code>
|
||||||
|
</FeatureGate>
|
||||||
<ul>
|
<ul>
|
||||||
<li><b>ChatGPT</b>: Settings → Apps & Connectors → Advanced → включить Developer mode → Create: URL выше, авторизация OAuth. Откроется Пеппа — войдите через eGov и нажмите «Разрешить». В чате включите коннектор Peppa.</li>
|
<li>{rich(t("<b>ChatGPT</b>: Settings → Apps & Connectors → Advanced → включить Developer mode → Create: URL выше, авторизация OAuth. Откроется FORGE — войдите через eGov и нажмите «Разрешить». В чате включите коннектор FORGE."))}</li>
|
||||||
<li><b>Codex, Claude и другие MCP-клиенты</b>: добавьте удалённый MCP-сервер по этому URL с OAuth — клиент зарегистрируется сам, вход и согласие на экране Пеппы.</li>
|
<li>{rich(t("<b>Инструкция для ИИ</b>: первым делом ИИ-клиент вызывает инструмент <m>get_started</m> — памятка менеджера: код пишут только агенты, напрямую в код проекта не лезть, «Готово» — только после «Принять». Те же слова — на открытой странице <a href=\"/mcp-guide\">/mcp-guide</a> (кнопка «Скопировать» — для «Инструкций» проекта ChatGPT или системного сообщения другого ИИ). Первый ответ <m>list_projects</m> и <m>get_task</m> напоминает о ней."))}</li>
|
||||||
<li>Если клиент не видит новых инструментов — обновите или переподключите коннектор. Доступ отзывается в <Link href="/settings">Настройках</Link>.</li>
|
<li>{rich(t("<b>Codex, Claude и другие MCP-клиенты</b>: добавьте удалённый MCP-сервер по этому URL с OAuth — клиент зарегистрируется сам, вход и согласие на экране FORGE."))}</li>
|
||||||
<li><b>Модель агента</b> — «⋯ Настройки проекта → Модель агента» (и в разделе «Агент» стори — для неё одной): провайдер (Claude Code, Codex, OpenCode), модель (<code>sonnet</code>, <code>opus</code>, <code>gpt-5-codex</code>…) и усилия. <b>Эскалация</b>: после N неудач стори (красные проверки по разным коммитам и возвраты ревьюера, по умолчанию 2) она до конца идёт на сильной модели — живой раннер перезапускается в том же разговоре. <b>Запасной провайдер</b> — если у основного нет рабочей подписки в пуле (все в лимите или с ошибкой входа), раннер стартует на нём.</li>
|
<li>{rich(t("Если клиент не видит новых инструментов — обновите или переподключите коннектор. Доступ отзывается в <a href=\"/settings\">Настройках</a>."))}</li>
|
||||||
<li><b>Память проекта</b> — <code>.peppa/memory.md</code> в репозитории: команды, соглашения, грабли и решения, которые агенты записывают в конце стори (MCP <code>remember</code>). Раннер подкладывает её вместе со сводкой последних завершённых стори в каждый запуск агента; размер ограничен — разросшуюся память агент ужимает сам. Посмотреть — вкладка проекта «Спеки».</li>
|
<li>{rich(t("<b>Модель агента</b> — «⋯ Настройки проекта → Модель агента» (и в разделе «Агент» стори — для неё одной): провайдер (Claude Code, Codex, OpenCode), модель (<code>sonnet</code>, <code>opus</code>, <code>gpt-5-codex</code>…) и усилия. <b>Эскалация</b>: после N неудач стори (красные проверки по разным коммитам и возвраты ревьюера, по умолчанию 2) она до конца идёт на сильной модели — живой раннер перезапускается в том же разговоре. <b>Запасной провайдер</b> — если у основного нет рабочей подписки в пуле (все в лимите или с ошибкой входа), раннер стартует на нём."))}</li>
|
||||||
<li><b>Первый запуск</b> — на Главной чек-лист: подписка агента (суперадмину), Telegram, eGov (необязательно), проект, первая стори, стори в работе. Исчезает, когда всё сделано, или по «Скрыть». Если у пула проекта нет ни одной рабочей подписки, на странице проекта — предупреждение «Агенты не запустятся».</li>
|
<li>{rich(t("<b>Память проекта</b> — <code>.peppa/memory/</code> в репозитории: команды, соглашения, грабли и решения, которые агенты записывают в конце стори (MCP <code>remember</code>), у каждой задачи свой файл — параллельные задачи не мешают друг другу. Раннер собирает её вместе со сводкой последних завершённых стори в каждый запуск агента; размер подсказки ограничен — сначала общая часть и новые задачи, старые агент сворачивает сам. Посмотреть — вкладка проекта «Спеки»."))}</li>
|
||||||
<li><b>Подписки</b> — аккаунты Claude Code, Codex и OpenCode, на которых работают агенты, и пулы для ротации ведёт суперадмин в разделе «Подписки». У проекта — пул по умолчанию («⋯ Настройки проекта»): раннер стартует на первой свободной активной подписке пула, а в «Раннерах» видно, на какой. Упёрся в лимит — после конца хода раннер сам переходит на свободную подписку того же агента в пуле (Claude — продолжая тот же разговор, Codex — заново, с контекстом из стори) и пишет в Telegram «переключил на подписку…»; подписки того же агента нет, а есть другая (Claude ↔ ChatGPT) — переезжает на неё и начинает заново с контекстом из стори («переехал…»; выключается <code>PEPPA_ROTATE_CROSS=off</code>); свободных нет — ждёт сброса и продолжает сам.</li>
|
<li>{rich(t("<b>Первый запуск</b> — на Главной чек-лист: подписка агента (суперадмину), Telegram, eGov (необязательно), проект, первая стори, стори в работе. Исчезает, когда всё сделано, или по «Скрыть». Если у пула проекта нет ни одной рабочей подписки, на странице проекта — предупреждение «Агенты не запустятся»."))}</li>
|
||||||
<li><b>Несколько своих подписок</b> — «⋯ Настройки проекта → Подписки»: у каждой подписки пула видно «в работе: N агентов», «свободна», «лимит до 15:40» и сколько использовано окна лимита. «Добавить ещё Claude» / «Добавить ещё ChatGPT» — тот же вход по ссылке; «Убрать» — своя подписка, на которой сейчас никто не работает. Когда в пуле остаётся одна рабочая подписка и она использована больше чем на 85%, участникам приходит одно предупреждение «осталась одна подписка, скоро лимит».</li>
|
<li>{rich(t("<b>Подписки</b> — аккаунты Claude Code, Codex и OpenCode, на которых работают агенты, и пулы для ротации ведёт суперадмин в разделе «Подписки». У проекта — пул по умолчанию («⋯ Настройки проекта»): раннер стартует на первой свободной активной подписке пула, а в «Раннерах» видно, на какой. Упёрся в лимит — после конца хода раннер сам переходит на свободную подписку того же агента в пуле (Claude — продолжая тот же разговор, Codex — заново, с контекстом из стори) и пишет в Telegram «переключил на подписку…»; подписки того же агента нет, а есть другая (Claude ↔ ChatGPT) — переезжает на неё и начинает заново с контекстом из стори («переехал…»; выключается <code>PEPPA_ROTATE_CROSS=off</code>); свободных нет — ждёт сброса и продолжает сам."))}</li>
|
||||||
<li><b>Запасная подписка от суперадмина</b> — «Подписки → Картина по пулам»: все пулы с состоянием подписок, раннерами, ждущими сброса, и пометкой «запасной нет». «Одолжить подписку» добавляет подписку в чужой пул на 1–168 часов; по сроку она возвращается сама (агенты на ней дорабатывают текущий запуск), «Вернуть сейчас» — раньше.</li>
|
<li>{rich(t("<b>Несколько своих подписок</b> — «⋯ Настройки проекта → Подписки»: у каждой подписки пула видно «в работе: N агентов», «свободна», «лимит до 15:40» и сколько использовано окна лимита. «Добавить ещё Claude» / «Добавить ещё ChatGPT» — тот же вход по ссылке; «Убрать» — своя подписка, на которой сейчас никто не работает. Когда в пуле остаётся одна рабочая подписка и она использована больше чем на 85%, участникам приходит одно предупреждение «осталась одна подписка, скоро лимит»."))}</li>
|
||||||
|
<li>{rich(t("<b>Запасная подписка от суперадмина</b> — «Подписки → Картина по пулам»: все пулы с состоянием подписок, раннерами, ждущими сброса, и пометкой «запасной нет». «Одолжить подписку» добавляет подписку в чужой пул на 1–168 часов; по сроку она возвращается сама (агенты на ней дорабатывают текущий запуск), «Вернуть сейчас» — раньше."))}</li>
|
||||||
</ul>
|
</ul>
|
||||||
</Section>
|
</Section>
|
||||||
|
|
||||||
<Section title="Сценарии">
|
<Section title={t("Сценарии")}>
|
||||||
{CASES.map((c) => (
|
{CASES.map((c) => (
|
||||||
<article key={c.title} className="flex flex-col gap-1 rounded-lg border bg-card px-4 py-3">
|
<article key={c.title} className="flex flex-col gap-1 rounded-lg border bg-card px-4 py-3">
|
||||||
<b>{c.title}</b>
|
<b>{t(c.title)}</b>
|
||||||
<p className="m-0 italic">«{c.say}»</p>
|
<p className="m-0 italic">{t("«{say}»", { say: t(c.say) })}</p>
|
||||||
<p className="m-0 text-muted-foreground">{c.how}</p>
|
<p className="m-0 text-muted-foreground">{t(c.how)}</p>
|
||||||
</article>
|
</article>
|
||||||
))}
|
))}
|
||||||
</Section>
|
</Section>
|
||||||
|
|
||||||
<Section title="Инструменты MCP">
|
<Section title={t("Инструменты MCP")}>
|
||||||
<div className="overflow-x-auto rounded-lg border">
|
<div className="overflow-x-auto rounded-lg border">
|
||||||
<table className="w-full border-collapse">
|
<table className="w-full border-collapse">
|
||||||
<tbody>
|
<tbody>
|
||||||
{TOOLS.map(([name, what]) => (
|
{TOOLS.map(([name, what]) => (
|
||||||
<tr key={name} className="border-b align-top last:border-0">
|
<tr key={name} className="border-b align-top last:border-0">
|
||||||
<td className="px-3 py-2 font-mono text-xs [overflow-wrap:anywhere] sm:whitespace-nowrap">{name}</td>
|
<td className="px-3 py-2 font-mono text-xs [overflow-wrap:anywhere] sm:whitespace-nowrap">{name}</td>
|
||||||
<td className="px-3 py-2">{what}</td>
|
<td className="px-3 py-2">{t(what)}</td>
|
||||||
</tr>
|
</tr>
|
||||||
))}
|
))}
|
||||||
</tbody>
|
</tbody>
|
||||||
@ -160,137 +227,89 @@ export default async function Help() {
|
|||||||
</div>
|
</div>
|
||||||
</Section>
|
</Section>
|
||||||
|
|
||||||
<Section title="Автономность">
|
<Section title={t("Автономность")}>
|
||||||
<p className="m-0 text-muted-foreground">
|
<p className="m-0 text-muted-foreground">
|
||||||
У каждого проекта — уровень автономности («⋯ Настройки проекта» → «Автономность», MCP <span className="font-mono">update_project_settings</span>,
|
{rich(t("У каждого проекта — уровень автономности («⋯ Настройки проекта» → «Автономность», MCP <m>update_project_settings</m>, CLI <m>peppa project autonomy KEY</m>). <b>Ручной</b> (по умолчанию): вы двигаете карточки и принимаете стори. <b>С подсказками</b>: если ни один агент не работает, а в бэклоге есть стори, придёт пуш «Агенты простаивают. Взять PEP-7?» с кнопками «Взять / Следующую / Не сейчас» — не чаще раза в N часов и не в тихие часы. <b>Автомат</b>: FORGE сама берёт следующую стори из бэклога (сверху по порядку на доске, пропуская стори, которые ждут предшественников; одновременно до N), зелёный PR без конфликтов мержит сама, стори закрывает после мержа; при конфликте агент сам делает rebase. Настройки можно комбинировать: одобрять план каждой стори, мержить сам, но закрывать вручную или «само через N часов без замечаний». Во время лимита подписки диспетчер ничего не запускает и не предлагает. PR, меняющий конвейер, всегда ждёт вашего «Принять». «Принять» мержит PR, Gitea удаляет ветку, рабочая копия проекта подтягивает main."))}
|
||||||
CLI <span className="font-mono">peppa project autonomy KEY</span>). <b>Ручной</b> (по умолчанию): вы двигаете карточки и принимаете стори.{" "}
|
</p>
|
||||||
<b>С подсказками</b>: если ни один агент не работает, а в бэклоге есть стори, придёт пуш «Агенты простаивают. Взять PEP-7?» с кнопками
|
<p className="m-0 mt-2 text-muted-foreground">
|
||||||
«Взять / Следующую / Не сейчас» — не чаще раза в N часов и не в тихие часы. <b>Автомат</b>: Пеппа сама берёт следующую стори из
|
{rich(t("<b>Пауза проекта</b>: «Поставить на паузу» на странице проекта или в «⋯ Настройки проекта → Пауза» останавливает агентов проекта (сделанное сохраняется), новые не запускаются, продакт, аналитик и ревьюер не работают, уведомлений нет — ни в Telegram, ни в браузере, вопросы проекта не показываются в «Ждут вашего ответа». «Продолжить» возвращает остановленных агентов к их задачам; то, что пришло во время паузы, задним числом не рассылается."))}
|
||||||
бэклога (сверху по порядку на доске, пропуская стори, которые ждут предшественников; одновременно до N), зелёный PR без конфликтов мержит сама, стори закрывает после мержа; при конфликте агент
|
|
||||||
сам делает rebase. Настройки можно комбинировать: одобрять план каждой стори, мержить сам, но закрывать вручную или «само через N
|
|
||||||
часов без замечаний». Во время лимита подписки диспетчер ничего не запускает и не предлагает. PR, меняющий конвейер, всегда ждёт
|
|
||||||
вашего «Принять». «Принять» мержит PR, Gitea удаляет ветку, рабочая копия проекта подтягивает main.
|
|
||||||
</p>
|
</p>
|
||||||
</Section>
|
</Section>
|
||||||
|
|
||||||
<Section title="Расход, бюджеты, метрики, журнал">
|
<Section title={t("Расход, бюджеты, метрики, журнал")}>
|
||||||
<p className="m-0 text-muted-foreground">
|
<p className="m-0 text-muted-foreground">
|
||||||
<b>Лимиты</b>: полоса над каждой страницей показывает самое загруженное окно лимитов подписки (5 ч и 7 дней) и время сброса — Claude Code сам
|
{rich(t("<b>Лимиты</b>: полоса над каждой страницей показывает самое загруженное окно лимитов подписки (5 ч и 7 дней) и время сброса — Claude Code сам сообщает их строке статуса раннера. Пока ни один раннер не сообщал — «нет данных о лимитах»; Codex и OpenCode расход не сообщают. На карточке раннера — токены, стоимость и заполненность контекста; «≈» — стоимость оценена по прайсу API, а не сообщена агентом. <b>Бюджет</b>: «⋯ Настройки проекта» → «Бюджет стори» (по умолчанию для всех стори) или карточка стори (свой бюджет) — минуты раннеров, токены, перезапуски, стоимость; по умолчанию без предела. Превышение прерывает ход агента (разговор сохраняется) и присылает вопрос «Продлить ×2 / Снять лимит / Остановить»; пока вы не ответили, стори не запускается. <b>Метрики</b>: вкладка «Метрики» проекта — время цикла, доля принятых с первого раза, возвраты с ревью, вопросы, часы раннеров, сколько агенты ждали вас, расход по неделям, агентам и эпикам. <b>Журнал</b>: вкладка «Журнал» проекта и раздел «Журнал» суперадмина — кто что сделал: человек (веб, Telegram, MCP-клиент, CLI), агент или FORGE."))}
|
||||||
сообщает их строке статуса раннера. Пока ни один раннер не сообщал — «нет данных о лимитах»; Codex и OpenCode расход не сообщают. На карточке
|
|
||||||
раннера — токены, стоимость и заполненность контекста; «≈» — стоимость оценена по прайсу API, а не сообщена агентом.{" "}
|
|
||||||
<b>Бюджет</b>: «⋯ Настройки проекта» → «Бюджет стори» (по умолчанию для всех стори) или карточка стори (свой бюджет) — минуты раннеров,
|
|
||||||
токены, перезапуски, стоимость; по умолчанию без предела. Превышение прерывает ход агента (разговор сохраняется) и присылает вопрос «Продлить ×2 /
|
|
||||||
Снять лимит / Остановить»; пока вы не ответили, стори не запускается.{" "}
|
|
||||||
<b>Метрики</b>: вкладка «Метрики» проекта — время цикла, доля принятых с первого раза, возвраты с ревью, вопросы, часы раннеров, сколько агенты
|
|
||||||
ждали вас, расход по неделям, агентам и эпикам.{" "}
|
|
||||||
<b>Журнал</b>: вкладка «Журнал» проекта и раздел «Журнал» суперадмина — кто что сделал: человек (веб, Telegram, MCP-клиент, CLI), агент или Пеппа.
|
|
||||||
</p>
|
</p>
|
||||||
</Section>
|
</Section>
|
||||||
|
|
||||||
<Section title="Секреты">
|
<Section title={t("Секреты")}>
|
||||||
<p className="m-0 text-muted-foreground">
|
<p className="m-0 text-muted-foreground">
|
||||||
<b>Секреты проекта</b>: «⋯ Настройки проекта» → «Секреты» — ключи API и доступы для агентов (например <code>STRIPE_TEST_KEY</code>). Значение
|
{rich(t("<b>Секреты проекта</b>: «⋯ Настройки проекта» → «Секреты» — ключи API и доступы для агентов (например <code>STRIPE_TEST_KEY</code>). Значение шифруется и после сохранения больше не показывается никому; сохранить то же имя — заменить значение. Агенты проекта получают секреты как переменные окружения при следующем запуске сессии, видят через MCP только имена (<code>list_secrets</code>), а в терминале раннера и ленте шагов значение заменяется на «••••» (кроме значений короче 4 символов и значения, разорванного переносом строки). Каждая выдача — событие «secrets_issued» в журнале сессии. Те же секреты получает и выкаченный продукт (версия для проверки и рабочая) — как переменные окружения с тем же именем; после изменения секрета FORGE через пару минут сама перезапускает продукт. Если продукту нужен ключ, агент объявляет это, и на странице проекта в карточке «Ваш продукт» появляется пометка «Работает в демо-режиме» с полем, куда вставить ключ. После каждой выкатки продукт смотрит агент приёмки, а Аналитик пишет в обсуждение проекта, как им пользоваться и что ещё не настоящее. <b>Ревизия</b> (суперадмин, раздел «Секреты», CLI <code>peppa secrets audit</code>): секреты платформы, их возраст и кто ими пользуется, MCP-токены по клиентам, подписки и секреты проектов — с пошаговой ротацией. Смена <code>PEPPA_SECRET</code> без потери данных: старый ключ в <code>PEPPA_SECRET_PREVIOUS</code>, новый в <code>PEPPA_SECRET</code>, перезапуск, <code>peppa secrets reencrypt</code>."))}
|
||||||
шифруется и после сохранения больше не показывается никому; сохранить то же имя — заменить значение. Агенты проекта получают секреты как
|
</p>
|
||||||
переменные окружения при следующем запуске сессии, видят через MCP только имена (<code>list_secrets</code>), а в терминале раннера и ленте шагов
|
<p className="m-0 mt-2 text-muted-foreground">
|
||||||
значение заменяется на «••••» (кроме значений короче 4 символов и значения, разорванного переносом строки). Каждая выдача — событие
|
{/* glossary-ignore: справочник режима «Инженер», имя команды CLI */}
|
||||||
«secrets_issued» в журнале сессии. Те же секреты получает и выкаченный продукт (версия для проверки и рабочая) — как переменные окружения с тем же именем; после изменения секрета Пеппа через пару минут сама перезапускает продукт. Если продукту нужен ключ, агент объявляет это, и на странице проекта в карточке «Ваш продукт» появляется пометка «Работает в демо-режиме» с полем, куда вставить ключ. После каждой выкатки продукт смотрит продакт-агент и пишет в обсуждение проекта, как им пользоваться и что ещё не настоящее.{" "}
|
{rich(t("<b>Кому идёт секрет (PEP-253)</b>: у каждого секрета пометка «только продукту» (по умолчанию для новых) или «агенту и продукту». Настройка проекта «Агенты получают секреты в окружение» у новых проектов выключена: агенты не получают ни одного секрета, продукт — все. Ключ сервиса из каталога (Stripe, OpenAI, GitHub, Telegram…) FORGE узнаёт по имени и формату значения и предлагает «Сделать подключением»: создаётся подключение с этим ключом и разрешение проекту на чтение и запись, секрет остаётся только продукту — агент работает с сервисом через <code>call_connection</code>, не видя ключа. Отчёт по всем проектам — раздел «Секреты» и <code>peppa secrets agent-report [--notify]</code>."))}
|
||||||
<b>Ревизия</b> (суперадмин, раздел «Секреты», CLI <code>peppa secrets audit</code>): секреты платформы, их возраст и кто ими пользуется, MCP-токены
|
|
||||||
по клиентам, подписки и секреты проектов — с пошаговой ротацией. Смена <code>PEPPA_SECRET</code> без потери данных: старый ключ в
|
|
||||||
<code>PEPPA_SECRET_PREVIOUS</code>, новый в <code>PEPPA_SECRET</code>, перезапуск, <code>peppa secrets reencrypt</code>.
|
|
||||||
</p>
|
</p>
|
||||||
</Section>
|
</Section>
|
||||||
|
|
||||||
<Section title="CI/CD">
|
<Section title="CI/CD">
|
||||||
<p className="m-0 text-muted-foreground">
|
<p className="m-0 text-muted-foreground">
|
||||||
Каждый PR агента проверяет Gitea Actions: <span className="font-mono">install</span>, <span className="font-mono">lint</span>,{" "}
|
{rich(t("Каждый PR агента проверяет Gitea Actions: <m>install</m>, <m>lint</m>, <m>typecheck</m>, <m>test</m>, <m>build</m>. Команды — в <m>.peppa/project.json → checks</m> (заполняет агент на первой стори), workflow приходит из шаблона; в старый проект — командой <m>peppa ci connect KEY</m> (PR от FORGE). Результат виден в карточке стори и во вкладке «PR» («Проверки: 4 из 4 пройдены»). Красная проверка уходит агенту с хвостом лога, после 3 красных прогонов подряд FORGE спросит вас. В ревью стори попадает и «Принять» мержит PR только с зелёными проверками и без конфликтов. PR, меняющий конвейер (<m>.gitea/</m>, <m>checks</m>, <m>deploy</m>), сам не мержится никогда."))}
|
||||||
<span className="font-mono">typecheck</span>, <span className="font-mono">test</span>, <span className="font-mono">build</span>. Команды —
|
|
||||||
в <span className="font-mono">.peppa/project.json → checks</span> (заполняет агент на первой стори), workflow приходит из
|
|
||||||
шаблона; в старый проект — командой <span className="font-mono">peppa ci connect KEY</span> (PR от Пеппы). Результат виден в
|
|
||||||
карточке стори и во вкладке «PR» («Проверки: 4 из 4 пройдены»). Красная проверка уходит агенту с хвостом лога, после 3 красных
|
|
||||||
прогонов подряд Пеппа спросит вас. В ревью стори попадает и «Принять» мержит PR только с зелёными проверками и без
|
|
||||||
конфликтов. PR, меняющий конвейер (<span className="font-mono">.gitea/</span>, <span className="font-mono">checks</span>,{" "}
|
|
||||||
<span className="font-mono">deploy</span>), сам не мержится никогда.
|
|
||||||
</p>
|
</p>
|
||||||
<p className="m-0 text-muted-foreground">
|
<p className="m-0 text-muted-foreground">
|
||||||
Агент-ревьюер (по умолчанию выключен; «⋯ Настройки проекта → Ревьюер»): когда проверки PR зелёные и агент отдаёт стори в ревью,
|
{t("Агент-ревьюер (по умолчанию выключен; «⋯ Настройки проекта → Ревьюер»): когда проверки PR зелёные и агент отдаёт стори в ревью, короткая сессия Claude (sonnet, на подписке пула проекта) читает дифф по чек-листу — сделано ли то, что просила стори, баги, безопасность, тесты, мусор — и ваши дополнительные правила. Замечания уходят агенту, стори остаётся «В работе»; «ок» — стори приходит вам с резюме ревьюера. После лимита возвратов (по умолчанию 2) стори приходит с незакрытыми замечаниями; если ревьюер упал — с пометкой. Последнее ревью видно в карточке стори.")}
|
||||||
короткая сессия Claude (sonnet, на подписке пула проекта) читает дифф по чек-листу — сделано ли то, что просила стори, баги,
|
|
||||||
безопасность, тесты, мусор — и ваши дополнительные правила. Замечания уходят агенту, стори остаётся «В работе»; «ок» — стори
|
|
||||||
приходит вам с резюме ревьюера. После лимита возвратов (по умолчанию 2) стори приходит с незакрытыми замечаниями; если
|
|
||||||
ревьюер упал — с пометкой. Последнее ревью видно в карточке стори.
|
|
||||||
</p>
|
</p>
|
||||||
<p className="m-0 text-muted-foreground">
|
<p className="m-0 text-muted-foreground">
|
||||||
Деплой — <span className="font-mono">deploy</span> в project.json и <span className="font-mono">Dockerfile</span> (заготовки в{" "}
|
{rich(t("Деплой — <m>deploy</m> в project.json и <m>Dockerfile</m> (заготовки в <m>deploy/</m>): PR получает preview <m>slug-prN.telecom.quest</m> (удаляется при закрытии), мерж выкатывает staging <m>slug-staging.telecom.quest</m>, прод <m>slug-prod.telecom.quest</m> — по кнопке «Выкатить в прод» (страница проекта, Telegram, MCP <m>deploy</m>). После каждого деплоя — проверка <m>/healthz</m> до 2 минут; не прошла — откат на предыдущий образ и сообщение вам. Релизы — на странице проекта."))}
|
||||||
<span className="font-mono">deploy/</span>): PR получает preview <span className="font-mono">slug-prN.telecom.quest</span> (удаляется при
|
|
||||||
закрытии), мерж выкатывает staging <span className="font-mono">slug-staging.telecom.quest</span>, прод{" "}
|
|
||||||
<span className="font-mono">slug-prod.telecom.quest</span> — по кнопке «Выкатить в прод» (страница проекта, Telegram, MCP{" "}
|
|
||||||
<span className="font-mono">deploy</span>). После каждого деплоя — проверка <span className="font-mono">/healthz</span> до 2 минут; не
|
|
||||||
прошла — откат на предыдущий образ и сообщение вам. Релизы — на странице проекта.
|
|
||||||
</p>
|
</p>
|
||||||
<p className="m-0 text-muted-foreground">
|
<p className="m-0 text-muted-foreground">
|
||||||
Превью на ревью: «готово к ревью» и карточка стори (блок «Превью») показывают «Посмотреть» — стенд PR, ссылку на
|
{/* glossary-ignore: справочник вида «Инженер» */}
|
||||||
дифф и итог проверок. Шаг деплоя превью снимает скриншоты страниц из <span className="font-mono">deploy.screenshots</span>{" "}
|
{rich(t("Продукт по ссылке с первого дня: новый проект создаётся с заглушкой «Продукт создаётся» (<m>Dockerfile</m>, <m>product/</m>, готовый <m>deploy</m>) и сразу выкладывается на <m>slug-staging.telecom.quest</m>. Нет здоровой версии для проверки при принятых стори или выкладка упала — FORGE сама заводит стори «Продукт должен открываться по ссылке» первой в бэклоге (одна открытая на проект, не чаще раза в сутки). «⋯ Настройки проекта → Показывать всем»: «Сам» — здоровый staging, все стори которого приняты, выкатывается в прод без кнопки; «По кнопке» — как раньше."))}
|
||||||
(по умолчанию главная, <span className="font-mono">[]</span> — выключить) — они в карточке стори.
|
</p>
|
||||||
|
<p>
|
||||||
|
{rich(t("Превью на ревью: «готово к ревью» и карточка стори (блок «Превью») показывают «Посмотреть» — стенд PR, ссылку на дифф и итог проверок. Шаг деплоя превью снимает скриншоты страниц из <m>deploy.screenshots</m> (по умолчанию главная, <m>[]</m> — выключить) — они в карточке стори."))}
|
||||||
</p>
|
</p>
|
||||||
<p className="m-0 text-muted-foreground">
|
<p className="m-0 text-muted-foreground">
|
||||||
Gitea знает о Пеппе: issue, открытый вами или участником проекта, становится стори в бэклоге (в issue появится
|
{rich(t("Gitea знает о FORGE: issue, открытый вами или участником проекта, становится стори в бэклоге (в issue появится ссылка; стори готова — issue закроется), старые открытые issues переносит <m>peppa project import-issues KEY</m>. Комментарий или ревью «нужны изменения» в PR стори уходит её агенту (стори из «Ревью» вернётся в работу), а мерж PR руками в Gitea переводит стори в «Готово»."))}
|
||||||
ссылка; стори готова — issue закроется), старые открытые issues переносит{" "}
|
|
||||||
<span className="font-mono">peppa project import-issues KEY</span>. Комментарий или ревью «нужны изменения» в PR стори
|
|
||||||
уходит её агенту (стори из «Ревью» вернётся в работу), а мерж PR руками в Gitea переводит стори в «Готово».
|
|
||||||
</p>
|
</p>
|
||||||
<p className="m-0 text-muted-foreground">
|
<p className="m-0 text-muted-foreground">
|
||||||
Сама Пеппа (проект PEP) выкатывается так же по кнопке, но без staging: после зелёных проверок{" "}
|
{rich(t("Сама FORGE (проект PEP) выкатывается так же по кнопке, но без staging: после зелёных проверок <m>main</m> приходит предложение «Выкатить в прод»; релиз собирается на хосте рядом с работающим, перед миграциями делается копия базы, после перезапуска — проверка здоровья, не прошла — возврат предыдущего релиза."))}
|
||||||
<span className="font-mono">main</span> приходит предложение «Выкатить в прод»; релиз собирается на хосте рядом с
|
|
||||||
работающим, перед миграциями делается копия базы, после перезапуска — проверка здоровья, не прошла — возврат
|
|
||||||
предыдущего релиза.
|
|
||||||
</p>
|
</p>
|
||||||
</Section>
|
</Section>
|
||||||
|
|
||||||
<Section title="Чаты">
|
<Section title={t("Чаты")}>
|
||||||
<p className="m-0 text-muted-foreground">
|
<p className="m-0 text-muted-foreground">
|
||||||
<Link href="/chats">Чаты</Link> — у каждого проекта свой чат с тредами: тред на стори (вопросы агента, статусы,
|
{rich(t("<a href=\"/chats\">Чаты</a> — у каждого проекта свой чат с тредами: тред на стори (вопросы агента, статусы, прогресс, комментарии, сбои раннера), на ошибку из прода и на релиз. Ответ в треде стори уходит агенту: на открытый вопрос, а без вопроса — комментарием, который агент сразу видит. Мастер-чат — всё важное по вашим проектам (вопросы, ревью, сбои, лимиты, релизы, ошибки), мониторинг и сводка; команды /status, /task KEY-N, /move KEY-N in_progress, /help. Вопросы по-прежнему видны и на Главной. Переписка хранится 14 дней."))}
|
||||||
прогресс, комментарии, сбои раннера), на ошибку из прода и на релиз. Ответ в треде стори уходит агенту: на открытый
|
|
||||||
вопрос, а без вопроса — комментарием, который агент сразу видит. Мастер-чат — всё важное по вашим проектам
|
|
||||||
(вопросы, ревью, сбои, лимиты, релизы, ошибки), мониторинг и сводка; команды /status, /task KEY-N,
|
|
||||||
/move KEY-N in_progress, /help. Вопросы по-прежнему видны и на Главной. Переписка хранится 14 дней.
|
|
||||||
</p>
|
</p>
|
||||||
<p className="m-0 text-muted-foreground">
|
<p className="m-0 text-muted-foreground">
|
||||||
Любой чат можно связать с группой Telegram через вашего собственного бота (подключается в Настройках →
|
{rich(t("Любой чат можно связать с группой Telegram через вашего собственного бота (подключается в Настройках → Telegram): «Связать с Telegram» в чате → добавьте своего бота в группу по ссылке (или отправьте в группе <m>/link код</m>). Сообщения чата придут в группу от вашего бота, тред — цепочкой ответов; ответ реплаем вернётся в тред и уйдёт агенту. Отвечать из группы могут те, кто привязал свой Telegram в Настройках и имеет доступ к проекту (в мастер-группе — только владелец). Отключите или замените бота — группа отвяжется."))}
|
||||||
Telegram): «Связать с Telegram» в чате → добавьте своего бота в группу по ссылке (или отправьте в группе{" "}
|
|
||||||
<span className="font-mono">/link код</span>). Сообщения чата придут в группу от вашего бота, тред — цепочкой
|
|
||||||
ответов; ответ реплаем вернётся в тред и уйдёт агенту. Отвечать из группы могут те, кто привязал свой Telegram в
|
|
||||||
Настройках и имеет доступ к проекту (в мастер-группе — только владелец). Отключите или замените бота — группа
|
|
||||||
отвяжется.
|
|
||||||
</p>
|
</p>
|
||||||
</Section>
|
</Section>
|
||||||
|
|
||||||
<Section title="Telegram">
|
<Section title="Telegram">
|
||||||
<p className="m-0 text-muted-foreground">
|
<p className="m-0 text-muted-foreground">
|
||||||
Привяжите свой Telegram в Настройках: бот присылает вопросы агентов из ваших и общих проектов и «готово к ревью» с
|
{t("Привяжите свой Telegram в Настройках: бот присылает вопросы агентов из ваших и общих проектов и «готово к ревью» с кнопками; ответ реплаем уходит прямо в сессию агента. Новые ошибки из прода приходят туда же — по политике проекта: сообщением, стори или с кнопками «В бэклог / В работу / Игнорировать». Команды бота: /status — что сейчас происходит, /digest — сводка за сутки.")}
|
||||||
кнопками; ответ реплаем уходит прямо в сессию агента. Новые ошибки из прода приходят туда же — по политике
|
|
||||||
проекта: сообщением, стори или с кнопками «В бэклог / В работу / Игнорировать». Команды бота: /status — что
|
|
||||||
сейчас происходит, /digest — сводка за сутки.
|
|
||||||
</p>
|
</p>
|
||||||
<p className="m-0 text-muted-foreground">
|
<p className="m-0 text-muted-foreground">
|
||||||
Новую стори можно просто написать или наговорить боту: «в PAY: экспорт в CSV». Бот уточнит проект (если не указан) и
|
{t("Новую стори можно просто написать или наговорить боту: «в PAY: экспорт в CSV». Бот уточнит проект (если не указан) и эпик кнопками, создаст стори и предложит «Взять в работу».")}{" "}
|
||||||
эпик кнопками, создаст стори и предложит «Взять в работу». Голосовые работают, если на сервере настроена расшифровка.
|
{voiceStoriesEnabled()
|
||||||
|
? t("Голосовое бот сначала расшифрует и покажет текст («Расслышал: …»); проект можно назвать голосом: «в проекте Pay …».")
|
||||||
|
: t("Голосовые пока не настроены на сервере — пишите текстом.")}
|
||||||
</p>
|
</p>
|
||||||
</Section>
|
</Section>
|
||||||
|
|
||||||
<Section title="Уведомления">
|
<Section title={t("Обращения")}>
|
||||||
<p className="m-0 text-muted-foreground">
|
<p className="m-0 text-muted-foreground">
|
||||||
В <Link href="/settings#notifications">Настройках → Уведомления</Link> для каждого события (вопросы агентов,
|
{t("Кнопка «Сообщить о проблеме» внизу любой страницы — для проблем в самой FORGE: текст и до 5 скриншотов (файл, перетаскивание, вставка из буфера); страница, вид, язык, браузер и последние ошибки браузера прикладываются сами. В Telegram — /problem, затем текст, фото с подписью или голосовое. Обращение разбирает агент обратной связи; суперадмин получает разбор с вариантами исправления и решает: завести задачу, связать с существующей или не исправлять. Автор видит статус в разделе «Обращения» и получает сообщение, когда задача принята.")}
|
||||||
готово к ревью, сбои и лимиты, релизы, ошибки из прода, дайджест) выбирается, куда присылать: Telegram и/или
|
</p>
|
||||||
браузер. Тихие часы: Telegram приходит без звука, push не показываются. Снятые проекты не присылают ничего —
|
</Section>
|
||||||
вопросы остаются в вебе. Push в браузере включаются там же кнопкой (Chrome спросит разрешение) и работают при
|
|
||||||
закрытой вкладке; клик открывает стори. Во вкладке Пеппы в заголовке и на значке приложения — сколько ждёт вас,
|
<Section title={t("Уведомления")}>
|
||||||
при новом вопросе звучит сигнал (если звук включён). Ежедневный дайджест приходит в выбранное время (по умолчанию
|
<p className="m-0 text-muted-foreground">
|
||||||
09:00): сделано за сутки, в работе, на ревью, ждёт вас, зависло, лимиты; пустой не приходит.
|
{rich(t("В <a href=\"/settings#notifications\">Настройках → Уведомления</a> для каждого события (вопросы агентов, готово к ревью, сбои и лимиты, релизы, ошибки из прода, дайджест) выбирается, куда присылать: Telegram и/или браузер. Тихие часы: Telegram приходит без звука, push не показываются. Снятые проекты не присылают ничего — вопросы остаются в вебе. Push в браузере включаются там же кнопкой (Chrome спросит разрешение) и работают при закрытой вкладке; клик открывает стори. Во вкладке FORGE в заголовке и на значке приложения — сколько ждёт вас, при новом вопросе звучит сигнал (если звук включён). Ежедневный дайджест приходит в выбранное время (по умолчанию 09:00): сделано за сутки, в работе, на ревью, ждёт вас, зависло, лимиты; пустой не приходит."))}
|
||||||
</p>
|
</p>
|
||||||
<p className="m-0 text-muted-foreground">
|
<p className="m-0 text-muted-foreground">
|
||||||
Новости самой Пеппы — новые версии, падения и перезапуски сервисов, «Дайджест обновлений Пеппы» (что нового и
|
{t("Новости самой FORGE — новые версии, падения и перезапуски сервисов, «Дайджест обновлений FORGE» (что нового и что происходит сейчас) — идут в Telegram-канал платформы, который настраивает суперадмин в разделе «Платформа». Если он включил рассылку в личные чаты, дайджест обновлений приходит и вам; отключить — строка «Дайджест обновлений FORGE» в Настройках → Уведомления.")}
|
||||||
что происходит сейчас) — идут в Telegram-канал платформы, который настраивает суперадмин в разделе «Платформа».
|
|
||||||
Если он включил рассылку в личные чаты, дайджест обновлений приходит и вам; отключить — строка «Дайджест
|
|
||||||
обновлений Пеппы» в Настройках → Уведомления.
|
|
||||||
</p>
|
</p>
|
||||||
</Section>
|
</Section>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@ -1,26 +1,36 @@
|
|||||||
import Link from "next/link";
|
import Link from "@/components/Link";
|
||||||
import { ShortcutsList } from "@/components/CommandPalette";
|
import { ShortcutsList } from "@/components/CommandPalette";
|
||||||
import { PageHeader, Section } from "@/components/common";
|
import { PageHeader, Section } from "@/components/common";
|
||||||
import { Workspace } from "@/components/Workspace";
|
import { Workspace } from "@/components/Workspace";
|
||||||
import { PALETTE_KEYS } from "@/lib/shortcuts";
|
import { PALETTE_KEYS } from "@/lib/shortcuts";
|
||||||
|
import { getT } from "@/lib/i18n";
|
||||||
|
import { pageTitle } from "@/lib/title";
|
||||||
|
|
||||||
/** PEP-52: list of keyboard shortcuts (the same list as the «?» dialog). */
|
// PEP-274: the browser tab says which page it is.
|
||||||
export default function Shortcuts() {
|
export async function generateMetadata() {
|
||||||
|
const t = await getT();
|
||||||
|
return pageTitle(t, t("Горячие клавиши"));
|
||||||
|
}
|
||||||
|
|
||||||
|
export default async function Shortcuts() {
|
||||||
|
const t = await getT();
|
||||||
return (
|
return (
|
||||||
<Workspace>
|
<Workspace>
|
||||||
<div className="max-w-3xl text-sm">
|
<div className="max-w-3xl text-sm">
|
||||||
<PageHeader crumbs={<Link href="/help" className="text-muted-foreground hover:text-foreground">Помощь</Link>} title="Горячие клавиши">
|
<PageHeader crumbs={<Link href="/help" className="text-muted-foreground hover:text-foreground">{t("Помощь")}</Link>} title={t("Горячие клавиши")}>
|
||||||
Клавиши без ⌘/Ctrl работают, когда курсор не в поле ввода.
|
{t("Клавиши без ⌘/Ctrl работают, когда курсор не в поле ввода.")}
|
||||||
</PageHeader>
|
</PageHeader>
|
||||||
<Section title="Сочетания">
|
<Section title={t("Сочетания")}>
|
||||||
<div className="rounded-lg border bg-card px-4 py-2">
|
<div className="rounded-lg border bg-card px-4 py-2">
|
||||||
<ShortcutsList />
|
<ShortcutsList />
|
||||||
</div>
|
</div>
|
||||||
</Section>
|
</Section>
|
||||||
<Section title="В палитре">
|
<Section title={t("В палитре")}>
|
||||||
<p className="m-0 text-muted-foreground">{PALETTE_KEYS}. Поиск — по ключу, названию и проекту; все слова запроса должны совпасть.</p>
|
<p className="m-0 text-muted-foreground">{t(PALETTE_KEYS)}. {t("Поиск — по ключу, названию и проекту; все слова запроса должны совпасть.")}</p>
|
||||||
</Section>
|
</Section>
|
||||||
</div>
|
</div>
|
||||||
</Workspace>
|
</Workspace>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** PEP-52: list of keyboard shortcuts (the same list as the «?» dialog). */
|
||||||
|
|||||||
@ -7,6 +7,7 @@ import { revalidatePath } from "next/cache";
|
|||||||
import { redirect } from "next/navigation";
|
import { redirect } from "next/navigation";
|
||||||
import { asWebActor, requireUser } from "@/lib/auth";
|
import { asWebActor, requireUser } from "@/lib/auth";
|
||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
|
import { getT } from "@/lib/i18n";
|
||||||
|
|
||||||
const str = (f: FormData, k: string) => String(f.get(k) ?? "").trim();
|
const str = (f: FormData, k: string) => String(f.get(k) ?? "").trim();
|
||||||
const BASE = "/hosts";
|
const BASE = "/hosts";
|
||||||
@ -18,7 +19,8 @@ async function attempt(f: FormData, fn: () => Promise<string | void>): Promise<n
|
|||||||
await requireSuperadmin(db, user);
|
await requireSuperadmin(db, user);
|
||||||
target = (await fn()) || target;
|
target = (await fn()) || target;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
const msg = e instanceof PeppaError ? e.message : `Ошибка: ${(e as Error).message}`;
|
const t = await getT();
|
||||||
|
const msg = e instanceof PeppaError ? t.text(e.message) : t("Ошибка: {message}", { message: (e as Error).message });
|
||||||
target = `${BASE}?error=${encodeURIComponent(msg.slice(0, 300))}`;
|
target = `${BASE}?error=${encodeURIComponent(msg.slice(0, 300))}`;
|
||||||
}
|
}
|
||||||
revalidatePath("/", "layout");
|
revalidatePath("/", "layout");
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user