Compare commits
1157 Commits
task/PEP-1
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| edac120990 | |||
| 307626f300 | |||
| 3e258f24df | |||
| 1656923958 | |||
| d857b15c11 | |||
| 8bc56de251 | |||
| 9b95023cb4 | |||
| e962779d37 | |||
| 580fbac015 | |||
| c5dae8d1e7 | |||
| 113de40b8e | |||
| 0a25e94591 | |||
| 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 | |||
| 82490e958e | |||
| 4844ea5e35 | |||
| 43d78dd060 | |||
| 071d833e69 | |||
| 8701fa3886 | |||
| 7991a2e374 | |||
| b6d3921429 | |||
| 9b2b233e95 | |||
| 4bd220f20d | |||
| 01c25ab51d | |||
| 4d53a943b4 | |||
| eee9ab5c85 | |||
| 0130dc5098 | |||
| e758b17cf6 | |||
| 8769a75ae3 | |||
| e74cce689e | |||
| 13a912b7e5 | |||
| 14a6c9d4f1 | |||
| e2b75590cc | |||
| b79983f5b0 | |||
| b79f84d966 | |||
| eecdbd542f | |||
| d325840f95 | |||
| ce70d764cb | |||
| 738495afc2 | |||
| 8e4afae099 | |||
| 2b16425669 | |||
| b2344302c5 | |||
| ce706efb18 | |||
| e8a651a3b8 | |||
| 54693f8c65 | |||
| 5598af84bf | |||
| aeafc73dea | |||
| 8b3f7e9159 | |||
| b7d8ec10e5 | |||
| 9a694c6627 | |||
| 432959dd9b | |||
| 04fb99b05a | |||
| 1829b2a934 | |||
| d3e7163b66 | |||
| 156b24508a | |||
| 35f8695064 | |||
| cbb1c2aa4b | |||
| 4e0f7b163c | |||
| 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 | |||
| 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 | ||
|
|
e6d893998d | ||
|
|
9a310b29c1 | ||
|
|
ed3b4fefd4 | ||
|
|
0c7990dd61 | ||
|
|
6de7c72752 | ||
|
|
4347477a69 | ||
|
|
fc97c41629 | ||
|
|
a3d784b812 | ||
|
|
a5ba080fee | ||
| a1fb29f0da | |||
| a91e9a023b | |||
|
|
01c8cf226e | ||
|
|
1385840509 | ||
|
|
6776a9a99d | ||
|
|
253068e39c | ||
|
|
c47a26745d | ||
|
|
e2d711c1fc | ||
|
|
1b12ece0b1 | ||
| a72ebca22a | |||
|
|
d729995d24 | ||
|
|
59c34256a4 | ||
|
|
39b8b58258 | ||
| 99e2a95b75 | |||
| 33a8b81235 | |||
|
|
56ef392cfb | ||
|
|
6ff5c03bf9 | ||
|
|
e6d5742b74 | ||
|
|
77fd188775 | ||
|
|
a4474206b0 | ||
|
|
eb760d7a92 | ||
|
|
05dfb08b67 | ||
|
|
81f83fc37e | ||
| 600d7a69b7 | |||
|
|
284f1757ff | ||
|
|
4b5fee56af | ||
|
|
c4f4d3cb6d | ||
|
|
ca22e986d7 | ||
|
|
b977e7b5b9 | ||
|
|
6f5aa007ac | ||
|
|
43baa7ca4c | ||
|
|
2dcd16da3a | ||
| e35763aeec | |||
|
|
8e9ee4d813 | ||
| 8e44102fdc | |||
|
|
20f3684466 | ||
|
|
4888b37d9b | ||
|
|
323cd0f422 | ||
|
|
915f62ffde | ||
|
|
3635140503 | ||
|
|
ef846c51a6 | ||
|
|
e3abf5b43d | ||
|
|
b478390eb5 | ||
|
|
2c957631e8 | ||
|
|
40e5f6fdd3 | ||
|
|
5bc11bc320 | ||
| 8ef60fc521 | |||
|
|
554eeef7c1 | ||
|
|
258a605c16 | ||
|
|
23d6b6bee1 | ||
|
|
61c21f9823 | ||
|
|
7f8798d863 | ||
|
|
7ec9fe9bc5 | ||
|
|
7ad3d374c7 | ||
|
|
61ed80f2f6 | ||
|
|
805dd6020a | ||
| d3ae0642c6 | |||
|
|
bf22e9e0b1 | ||
|
|
ed62cdcd06 | ||
| 9d9d21f715 | |||
|
|
1676e69b26 | ||
| abf35a4ca9 | |||
|
|
bdae019820 | ||
| e47d41f273 | |||
|
|
decc9240eb | ||
|
|
2df225d33f | ||
|
|
cd2b4d4342 | ||
|
|
a2c1f7354f | ||
|
|
222d9e1f74 | ||
| 54e7b79ca3 | |||
|
|
af8298ac2a | ||
|
|
3a0d5c464d | ||
|
|
8947fe4967 | ||
|
|
81eab53459 | ||
|
|
8ff54d6363 | ||
| 70eeaf2af5 | |||
| 83ad46cefc | |||
|
|
34a4024224 | ||
| 24f6fa5e18 | |||
|
|
6d18a39acb | ||
|
|
312c1365c8 | ||
|
|
f9a4b3c56e | ||
|
|
424ab65a95 | ||
|
|
c739e877f5 | ||
| 17f7b4e416 | |||
|
|
96b5422a56 | ||
|
|
f53e1a4164 | ||
|
|
b479f23db4 | ||
| e612f09b13 | |||
|
|
b3f3547241 | ||
|
|
ac57057079 | ||
|
|
2ef05fac12 | ||
|
|
37d47ff49e | ||
|
|
905aeb912d | ||
|
|
e163086b01 | ||
| 91eca5ce23 | |||
|
|
860f908f82 | ||
|
|
f107929a14 | ||
|
|
fca28b8fec | ||
|
|
6f1cec5bc1 | ||
|
|
1b0f6063cb | ||
| 0d269114f2 | |||
|
|
7674fa2e71 | ||
| 045afa58ee | |||
|
|
1f16286dca | ||
|
|
242c5b59e9 | ||
| 6c012bb43d | |||
|
|
80a3bb79ad | ||
|
|
6d91a5473d | ||
|
|
60fa861303 | ||
|
|
bb7b1b4158 | ||
|
|
7f9b697c62 | ||
|
|
664f96a92e | ||
|
|
355c5b19b2 | ||
| 99a043d99c | |||
| 2a977bcc46 | |||
| 724031fc86 | |||
|
|
1c5a1b249b | ||
|
|
2fe9b34344 | ||
|
|
9611ab53ed | ||
|
|
ec79b0bfab | ||
|
|
b1fe8e9a84 | ||
|
|
7dc6b0ce64 | ||
|
|
03cc2191fd | ||
|
|
6fbf10e00e | ||
|
|
feeeb908e5 | ||
|
|
664054c217 | ||
| 51847e1ac1 | |||
|
|
20031adc08 | ||
| 4581a9dac0 | |||
|
|
02b045700d | ||
| 073f6716f3 | |||
| c501d4264b | |||
|
|
3159e888d2 | ||
|
|
6e54fc69a6 | ||
| b86874e409 | |||
| 30e2897f93 | |||
|
|
36f67bc2f8 | ||
|
|
bc9f53fddc | ||
|
|
044d6b9bf6 | ||
|
|
5af93d7438 | ||
| 1df43629e3 | |||
|
|
748216eef2 | ||
| 6a0cb9c7c3 | |||
|
|
03d358f9f2 | ||
| 52cb557a9c | |||
|
|
19f9577349 | ||
|
|
14177684d4 | ||
|
|
b47d2e8022 | ||
|
|
8c702b1d4e | ||
| 0157c74c94 | |||
|
|
aecd9363ad | ||
|
|
54182d0637 | ||
| 3abac8f316 | |||
|
|
01d58973ab | ||
| 215a2a9be6 | |||
|
|
ee4a313074 | ||
| 1f7194a635 | |||
|
|
27e43b1ea6 | ||
| 9bd0bc61db | |||
|
|
efe411f94e | ||
|
|
9c03009f14 | ||
| 5521a2d7be | |||
|
|
1afc95117d | ||
|
|
63576a9845 | ||
| 42d34dc584 | |||
| 3d190e60fd | |||
|
|
e9526c9329 | ||
| accfe52ac6 | |||
|
|
6066ce8763 | ||
|
|
335b8b159e | ||
| 5473470aa2 | |||
|
|
7c721db744 | ||
|
|
4729300a10 | ||
| 6b31d75b9c | |||
|
|
01cd72c121 | ||
|
|
f00076c575 | ||
| 109c74d3bb | |||
|
|
b4b31ea88c | ||
|
|
b13b87d38d | ||
|
|
3b23bbad24 | ||
|
|
fbe4336d20 | ||
|
|
82c003e209 | ||
|
|
5cfc2cb269 | ||
|
|
c751291bb9 | ||
|
|
a0d1097e37 | ||
|
|
46840ffef5 | ||
|
|
b3766d200d | ||
| 781936478e | |||
|
|
5b41e7d779 | ||
| b48791dbde | |||
|
|
d039a8ac79 | ||
| e7a58a6d36 | |||
|
|
2939bad87f | ||
|
|
cdc7e62bfc | ||
| 7bef0d3401 | |||
|
|
a1b3760afd | ||
| 62f2817a28 | |||
|
|
bd931c1c02 | ||
|
|
57d7857d94 | ||
| b6355a7ab5 | |||
|
|
7a4988ec89 | ||
|
|
06b3501427 | ||
|
|
5f1b1b4212 | ||
| 90c47b12fe | |||
|
|
1e8d9e0327 | ||
| 18eadc4c3a | |||
|
|
ca57f9543b | ||
| 4094e846c6 | |||
|
|
621aa0b5b3 | ||
|
|
12d8fea4c2 | ||
|
|
53ac7efdcc | ||
| caf102bcb7 | |||
|
|
acf2bb9623 | ||
| 134c00ff18 | |||
|
|
9149c75840 | ||
| a6a385e3d1 | |||
|
|
005d884038 | ||
|
|
0941a9f4b7 | ||
|
|
195a39ad41 | ||
| 9195c57505 | |||
|
|
14916079bc | ||
| 68ccef697c | |||
|
|
3c84608125 | ||
|
|
6b75324971 | ||
| 385e2607ff | |||
|
|
8b8a1abd5d | ||
|
|
96c54856dd | ||
|
|
ce426621e3 | ||
|
|
621f0137e5 | ||
|
|
5a8948d01e | ||
|
|
3b86c00768 | ||
|
|
4fdd3afd92 | ||
|
|
f6e3725e5f | ||
|
|
0b448a8b8a | ||
| cecabfaf75 | |||
|
|
53dd8a1f19 | ||
|
|
db822a570c | ||
|
|
6ab17456af | ||
| c3506c6f22 | |||
|
|
4a80d9dc6b | ||
| e3ed7bc367 | |||
|
|
634e40a02c | ||
|
|
5ff738c977 | ||
|
|
b3533c73bb | ||
|
|
c7283063c9 | ||
| 987ed91ed3 | |||
|
|
4c001ba5f6 | ||
|
|
5465238d1a | ||
|
|
7d1e354096 | ||
|
|
f284c40933 | ||
| 735b1af4a8 | |||
|
|
ce3e33dc5f | ||
|
|
9d8851b0b4 | ||
|
|
9f9358de2c | ||
|
|
ea4bdf38ff | ||
|
|
06337e18dc | ||
| bcd2cc317f | |||
|
|
b6bcbeb695 | ||
|
|
07ff13111d | ||
| 2444d6128d | |||
|
|
09d2750d75 | ||
| 0802e2b7eb | |||
|
|
bc457d9a26 | ||
| ba785ca7c0 | |||
|
|
16a6fcf8ac | ||
|
|
e2beb70dc4 | ||
|
|
6116b47403 | ||
|
|
9054774f96 | ||
|
|
11778d98bd | ||
| 74f88b325c | |||
|
|
9720bb7d53 | ||
|
|
90bb5daabe | ||
|
|
efeac4500b | ||
|
|
818bfe33a9 | ||
| 6a81bb5687 | |||
|
|
73b82d38a1 | ||
|
|
6cceac62b2 | ||
|
|
358fb5c0e9 | ||
|
|
328900e254 | ||
|
|
f9bc156321 | ||
| 8e16c91460 | |||
|
|
5009975a5a | ||
|
|
414e4500e4 | ||
| dbd9b04b70 | |||
|
|
13ad9cb51e | ||
| 7d0da1b83c | |||
|
|
616ce28c70 | ||
| a493b80708 | |||
|
|
0194f7f6e4 | ||
| 0d130f76a0 | |||
|
|
f958777e11 | ||
|
|
ed49767c31 | ||
| 4179690277 | |||
|
|
c55e9ce840 | ||
|
|
b517072362 | ||
| f66d3dbc5b | |||
|
|
847962d80e | ||
|
|
2a276d601e | ||
| e76fc92150 | |||
|
|
5df52468c3 | ||
| d047f9cdfe | |||
|
|
ae9f2861ae | ||
|
|
c4952b2011 | ||
|
|
52d861bbc7 | ||
| ee9dec9b60 | |||
|
|
969ad886a8 | ||
|
|
03aee432fb | ||
| 75019fdf1c | |||
|
|
3a282b8054 | ||
| 4f4850dc67 | |||
|
|
048006fd32 | ||
|
|
07e2caa393 | ||
|
|
ae37ba90d5 | ||
|
|
5120b97a0b | ||
| 843b0778d8 | |||
|
|
8dc82859c7 | ||
| 9561e83676 | |||
|
|
4c4b3a482f | ||
|
|
d3a54fc845 | ||
| cb6832f967 | |||
| ad6c917316 | |||
|
|
eeb326cc4f | ||
|
|
50b1d1afec | ||
| a9acf109e7 | |||
|
|
c03b679a1d | ||
|
|
28fbde4add | ||
| b07beb5d0f | |||
|
|
8073a27f9d | ||
|
|
d1c555a038 | ||
|
|
83b222b9e2 | ||
|
|
6cbac2bf4c | ||
|
|
961cb558a4 | ||
|
|
8fee68f8eb | ||
|
|
93f38bbcba | ||
|
|
56a7756e71 | ||
| 614750ed8d | |||
|
|
c964a00c21 | ||
|
|
59c3b583de | ||
| 0c0e3fe41c | |||
|
|
daa612b0d8 | ||
|
|
cae49d5b54 | ||
| 59beb236f8 | |||
|
|
498013472f | ||
| 86aec423a3 | |||
|
|
3ab408eb70 | ||
| 479be785c3 |
24
.env.example
24
.env.example
@ -1,10 +1,14 @@
|
||||
# Postgres (infra/docker-compose.yml)
|
||||
DATABASE_URL=postgres://peppa:peppa@127.0.0.1:5433/peppa
|
||||
# SQLite database file (default ~/.peppa/peppa.db)
|
||||
# PEPPA_DB=/Users/me/.peppa/peppa.db
|
||||
# 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
|
||||
|
||||
# Gitea (git.telecom.quest) — token with repo + org scope
|
||||
GITEA_URL=https://git.telecom.quest
|
||||
GITEA_TOKEN=
|
||||
GITEA_TEMPLATE_REPO=peppa-bot/template
|
||||
GITEA_TEMPLATE_REPO=peppa/template
|
||||
# Peppa's own repo (footer link, scripts/ci.sh --pr, scripts/peppa-release.sh)
|
||||
# GITEA_PLATFORM_REPO=peppa/peppa
|
||||
|
||||
# Where project repos are cloned and sessions run
|
||||
PEPPA_WORKSPACES=~/peppa/workspaces
|
||||
@ -24,3 +28,17 @@ PEPPA_ROOT=/Users/telecom/Dev/Peppa
|
||||
# Gitea OAuth2 app for web login (scripts/create-oauth-app.sh)
|
||||
GITEA_OAUTH_CLIENT_ID=
|
||||
GITEA_OAUTH_CLIENT_SECRET=
|
||||
|
||||
# Вход через Google (PEP-90): OAuth-клиент из Google Cloud, redirect URI <PEPPA_WEB_URL>/auth/google/callback
|
||||
# GOOGLE_CLIENT_ID=
|
||||
# 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
|
||||
|
||||
5
.gitattributes
vendored
Normal file
5
.gitattributes
vendored
Normal file
@ -0,0 +1,5 @@
|
||||
# При конфликте в этих файлах git оставляет строки обеих сторон: каждый PR дописывает в них
|
||||
# по строке в одно и то же место, и без этого любой мерж в main ломал перенос остальным (PEP-119).
|
||||
AGENTS.md merge=union
|
||||
.peppa/memory.md merge=union
|
||||
docs/glossary.md merge=union
|
||||
1
.gitea/peppa-check.sh
Symbolic link
1
.gitea/peppa-check.sh
Symbolic link
@ -0,0 +1 @@
|
||||
../template/.gitea/peppa-check.sh
|
||||
63
.gitea/workflows/ci.yml
Normal file
63
.gitea/workflows/ci.yml
Normal file
@ -0,0 +1,63 @@
|
||||
# CI for Peppa itself (PEP-22): glossary check, typecheck, web build and the e2e suite on mocks. Runs on Peppa's
|
||||
# act_runner (`peppa-trusted`, registered for peppa-bot's repos, PEP-57); tmux and the openspec
|
||||
# CLI are installed in the job. Each check is a step of the factory's own pipeline (PEP-57):
|
||||
# the commands are `checks` in .peppa/project.json, .gitea/peppa-check.sh (the template's) sets
|
||||
# the `peppa/<check>` commit status and reports to Peppa, so PEP tasks get the same card, review
|
||||
# gate and red-check feedback as any factory project. `scripts/ci.sh` runs the same locally.
|
||||
name: peppa-ci
|
||||
on:
|
||||
pull_request:
|
||||
push:
|
||||
branches: [main]
|
||||
env:
|
||||
PEPPA_SHA: ${{ github.event.pull_request.head.sha || github.sha }}
|
||||
PEPPA_BRANCH: ${{ github.head_ref || github.ref_name }}
|
||||
PEPPA_PR: ${{ github.event.pull_request.number }}
|
||||
PEPPA_CI_SECRET: ${{ secrets.PEPPA_CI_SECRET }}
|
||||
GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
jobs:
|
||||
ci:
|
||||
# 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
|
||||
runs-on: peppa-trusted
|
||||
timeout-minutes: 30
|
||||
env:
|
||||
# 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.
|
||||
PEPPA_TEST_PG: postgres://peppa:peppa@host.docker.internal:5433
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ env.PEPPA_SHA }}
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "26"
|
||||
- name: tools
|
||||
run: |
|
||||
# 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
|
||||
# (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
|
||||
echo "$RUNNER_TEMP/tools/bin" >> "$GITHUB_PATH"
|
||||
- id: install
|
||||
name: install
|
||||
run: bash .gitea/peppa-check.sh install
|
||||
# PEP-124: the glossary check — a word from the «Нельзя» column of docs/glossary.md on a screen.
|
||||
- name: lint
|
||||
if: (success() || failure()) && steps.install.outcome == 'success'
|
||||
run: bash .gitea/peppa-check.sh lint
|
||||
- name: typecheck
|
||||
if: (success() || failure()) && steps.install.outcome == 'success'
|
||||
run: bash .gitea/peppa-check.sh typecheck
|
||||
- name: build
|
||||
if: (success() || failure()) && steps.install.outcome == 'success'
|
||||
run: bash .gitea/peppa-check.sh build
|
||||
- name: test
|
||||
if: (success() || failure()) && steps.install.outcome == 'success'
|
||||
run: bash .gitea/peppa-check.sh test
|
||||
75
.peppa/memory.md
Normal file
75
.peppa/memory.md
Normal file
@ -0,0 +1,75 @@
|
||||
# Память проекта
|
||||
|
||||
Пишет агент через `remember` (PEP-30); не повторяй AGENTS.md.
|
||||
|
||||
## Команды
|
||||
- Тесты из шелла 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`.
|
||||
- observe.db: схема — `MIGRATIONS` по `user_version` (core/observe.ts); напоминания (PEP-223) — `remindIncidents`; в тестах «бот днём» помечай outbox `sent`, иначе напоминание заменит прежнее.
|
||||
- Хук грузит только лёгкий `runner/limit-delay.ts`, не flow.ts. В тесте хука PEPPA_GENERATION = поколение сессии (вставленной руками — 0).
|
||||
- Память ветки при мерже main склеивается построчно и разрастается дублями — после конфликта в `.peppa/memory.md` убери повторы (тест project-memory-size.test.ts).
|
||||
- SSRF-проверка в `lookup` — только с `agent: false` (keep-alive Node пропускает lookup, PEP-234).
|
||||
- QuickJS (PEP-212): строки из хост-функции читай до await; все хэндлы и deferred dispose-ить.
|
||||
- Настройки по префиксу — `keyPrefix(settings.key, "x:")` из @peppa/db, не `like(…"x:%")` (LIKE без индекса). Индексы — тест db-indexes.
|
||||
- 530 при живом сервере — обрыв Mac → сервер (PEP-245); лечит только перенос адресов (ключ Cloudflare).
|
||||
- Продукт на другой docker — только `scripts/server-move/products-move.sh` (PEP-231, с данными); `peppa deploy redeploy` поднимает с пустыми томами.
|
||||
- Номер миграции занят соседом после мержа — взять meta из main, `pnpm db:generate`, переименовать.
|
||||
- Агент в контейнере не видит хост сервера, Mac и Cloudflare (PEP-231): инфраструктуру — скриптом в `scripts/server-move/` + шаги в docs/SERVER.md, выполнить просить суперадмина через `report_blocker`.
|
||||
- Пути сессий с Mac (PEP-246): `runnerCwd` пересоздаёт копию сам; чистка — `peppa session paths --fix`.
|
||||
- Нет глобального git в контейнере: автор — `gitRelayEnv`; иначе `git -c user.name=peppa-bot -c user.email=peppa-bot@telecom.quest commit`.
|
||||
- `stopSession` закрывает все вопросы сессии, и карточку «готово» с «Принять» — освобождать место без неё: `releaseReviewSession` (PEP-299).
|
||||
- Состояние вачдога, которое пишет не вачдог (хук, launch), — только `markWatch` (json_set): `patchWatch` перезаписывает весь watch_state (PEP-265).
|
||||
- Песочница раннера: нет tmux, Node 26 (без 26 тесты падают на импортах — `node-v26…-linux-x64.tar.gz` (не .xz) в /tmp). tmux — .deb deb.debian.org (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).
|
||||
- Сервер (PEP-230): docs/SERVER.md. Docker-клиент образа 20.10 (PEP-287).
|
||||
- Пропал `.git/worktrees/s<id>`: создать с `HEAD`, `commondir` `../..`, `gitdir`, затем `git reset`.
|
||||
- Версии CLI агентов (PEP-267) — только `scripts/runner-image.sh --try <cli> <версия>` (json + оба Dockerfile), откат `--rollback`.
|
||||
- Codex (PEP-241): доверие папке — по корню основного репо worktree; `-c` режет ключ по точкам — пишем в config.toml CODEX_HOME (`codex-trust.ts`).
|
||||
- tmux на сервере (PEP-256) — контейнер `peppa-tmux`, сервисы — клиенты (`PEPPA_TMUX_EXTERNAL`); его образ меняет только `platform-deploy.sh --tmux`. Нет docker — compose проверяй парсером `yaml` (`{merge:true}`).
|
||||
- Зависимость с build-скриптом (ssh2, cpu-features) роняет `pnpm install --frozen-lockfile` (ERR_PNPM_IGNORED_BUILDS): реши в `allowBuilds` pnpm-workspace.yaml.
|
||||
- Шлюз Access Hub (PEP-252): `cleanPath` не пускает голое «:» в пути — Google-диапазоны и методы (`A1:B2`, `:batchUpdate`) агент шлёт как `%3A`. OAuth-тесты: `MockOAuthService` + `fetch`, переписывающий адрес сервиса на мок (`toMock`).
|
||||
- Очередь проверок (PEP-255): `checks.queue` — `projects` (своя зависшая голова) и `lanes` (`ciLane`); `requestRebase` → false = просьба не ушла.
|
||||
|
||||
## Соглашения
|
||||
- «Готово» после выкатки (PEP-278): статус `done` не трогаем — поверх него отметка `rollout.wait:<taskId>` (core/rollout.ts), экран — псевдостатус `rollout` в `TASK_STATUS`; снимает `rolloutTick`.
|
||||
- Специалисты (PEP-183): агент с непустым character — специалист; подбор — `runner/team-match.ts` (haiku, `PEPPA_TEAM_BIN`), результат `team.match:<taskId>`, порог ожидания `platform.team.waitMin`; в `ensureSessionAgent` порядок: прежний → свободный специалист по профилю → универсал → специалист без очереди.
|
||||
- i18n (PEP-98): текст пользователю — ключ = русская строка в `t()`/`m()` + перевод в `i18n/en|kk/<раздел>.ts` (иначе падают i18n-check/i18n-kk). «Peppa FACTORY» не склоняется (kk: Peppa FACTORY-нің); к {плейсхолдеру} kk-окончание не клеить. Тексты агентам говорят «Пеппа» — не трогаем.
|
||||
- Инструкция подключения к своему Claude/ChatGPT (PEP-135): `/help/connect`, тексты — `core/connect-texts.ts` (`CONNECT_HELP` ru/kk/en одной формы, тест `connect-help.test.ts`); изменились экраны подключения или инструменты удалённого MCP — править её; копирование — `<CopyText>`.
|
||||
- Словарь в сообщениях ядра (PEP-129/137): `pnpm lint` проверяет литералы в `m()/tr()/t()` packages/core|runner|mcp; подсказку агенту в `m()` не оборачивать; запрещённое слово — переписать (ключ и в `i18n/en|kk`, тестах) или `glossary-ignore: <почему>` строкой выше; человеку мимо переводов — `glossary-user: <почему>`.
|
||||
- Служебный текст (PEP-154): текст агента/терминала человеку — через `userText` (core/user-text.ts); исключение владельцу не слать — `platformFailure` (строка только для PeppaError).
|
||||
- Один голос (PEP-198): человеку пишет только Аналитик — вопрос агента через `relayAgentQuestion` (runner/question-relay.ts), задачи из чата — только оффер `stories` и кнопка; новая строка сообщения роли — в `ROLE_MESSAGE_KEYS` выше «Агент {name}», иначе он её съест.
|
||||
- Тесты: места подписки занимай `core.createSession` с `subscriptionId`; очередь ёмкости чисти `moveTask(backlog)`. Конец хода вопроса не создаёт — жди `idle`. Суперадмин — `superadmin()`. Текст чатов — через `stripAsIs`.
|
||||
- Узкие места: подписка — `pickSubscription`/`rotationCandidate`; агент — `startRunner`/`resumeSession`, модель — `claudePrint`, сообщение — `deliverToUser`; проекты — `listProjects`/`userProjectIds` (`from(projects)` — с `isNull(deletedAt)`); веб → runnerCall; функция от внешнего сервиса — `featureGateView` + `<FeatureGate>` (PEP-224).
|
||||
- Задача не от человека — `createTask` с origin сама в «Предложено» (PEP-295), путь — проверить `proposalRoom` до создания; новый вызов `createTask` — в список `proposals-only.test.ts`; автомерж — autonomy.acceptOwn.
|
||||
- Неудачная версия (PEP-158): `rolled_back`/`failed` → агенту задачи, `returnFailedRelease` (runner/deploy-feedback.ts); счётчик — `attempts` задержки `deploy` (3 — суперадмину, 6 — стоп).
|
||||
- Bugsink API (PEP-218): схема — `GET /api/canonical/0/schema/` (2.6.3); `q` = текст + теги `key:value`; числа пользователей нет. Экран — `core/bugsink-errors.ts` (кэш 45 с), действия — `runner/bugsink-errors.ts`.
|
||||
- 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.
|
||||
- act_runner (PEP-233/248): идут контейнеры `GITEA-ACTIONS-TASK-*` — не рестартовать; голова без ci.yml или >2 суток — `orphan`, не очередь; `not_taken` — pending, а другие проекты отчитываются.
|
||||
- Конфликт PR с main (PEP-269) — только `conflictStep` (runner/conflict-step.ts), не `requestRebase` напрямую.
|
||||
|
||||
## Решения
|
||||
- Access Hub (PEP-254): журнал — только `appendJournal` (core/connection-journal.ts, цепочка хэшей; правка строки задним числом = нарушение), ключ подключения — `sealConnectionSecret`/`openConnectionSecret`, не `encrypt`/`decrypt`.
|
||||
- История (PEP-221): журнал/статусы — `history.db` (core/history.ts), логи — `archive/<вид>/<день>.jsonl.gz`; из основной базы события удаляет только `runRetention` после переноса.
|
||||
- Docker (PEP-222): раннеры по умолчанию `container` (тесты — `PEPPA_DEFAULT_ISOLATION=none`).
|
||||
- Медленные запросы (PEP-213): `core/request-timing.ts` (`http.Server` в instrumentation.ts, probe в db) → warning Bugsink; порог `PEPPA_SLOW_REQUEST_MS`.
|
||||
- Застрявшая задача (PEP-209): лечит `stuckTaskTick` — платформа сама на ревью/в «Готово», агенту — новый процесс (`restartAgent`: старый не вернёт MCP), не `sendToSession`. Новая причина задержки с повторами — `platformDelay` с `retryMin`/`retryAt`, суперадмину кнопки — `buttons: true`.
|
||||
- Проверка запуска (PEP-266) идёт в платформенном проекте, не в отдельной строке проекта: тики обходят все проекты и шлют ложные сбои.
|
||||
- Сообщения людям — только через `telegram_outbox`/`push_outbox`: ночная тишина 23–08 (PEP-208) стоит на их выборке; тестам и стенду `PEPPA_NIGHT_QUIET=off`.
|
||||
- `template/` уходит в Gitea сам с выкаткой (PEP-242); старым проектам — `peppa ci connect <KEY> [--secrets-only]`.
|
||||
- Живой сайт (с PEP-230 — сервер, контейнеры) — только `scripts/platform-deploy.sh` из `~/peppa/src` на main (docs/SERVER.md); launchd/live-deploy.sh — только откат на Mac.
|
||||
- Речь — свой faster-whisper (`<Dictate>`). Google: по почте учётки не склеиваем.
|
||||
- Секреты (PEP-253): агенту — `agent_env` при `project.agent-secrets` (нет строки = вкл.); в тестах — `{ agent: true }`.
|
||||
- Привязка Google к чужой Google-only учётке — `mergeUserInto`; с eGov/Gitea — отказ (PEP-195).
|
||||
@ -1 +1,13 @@
|
||||
{ "slug": "peppa", "key": "PEP", "name": "Peppa", "peppaUrl": "https://peppa.telecom.quest" }
|
||||
{
|
||||
"slug": "peppa",
|
||||
"key": "PEP",
|
||||
"name": "Peppa",
|
||||
"peppaUrl": "https://peppa.telecom.quest",
|
||||
"checks": {
|
||||
"install": "pnpm install --frozen-lockfile",
|
||||
"lint": "pnpm lint",
|
||||
"typecheck": "pnpm -r typecheck",
|
||||
"build": "pnpm --filter @peppa/web build",
|
||||
"test": "pnpm --filter @peppa/testkit test"
|
||||
}
|
||||
}
|
||||
|
||||
@ -5,7 +5,7 @@
|
||||
```bash
|
||||
pnpm install
|
||||
cp .env.example .env # GITEA_TOKEN и т.д.
|
||||
pnpm db:up && pnpm db:migrate
|
||||
pnpm db:migrate # SQLite в ~/.peppa/peppa.db (PEPPA_DB)
|
||||
scripts/push-template.sh # залить template/ в Gitea
|
||||
peppa project create demo DEMO "Demo project"
|
||||
```
|
||||
|
||||
@ -1,4 +1,7 @@
|
||||
#!/usr/bin/env bash
|
||||
PEPPA_ROOT="$(cd "$(dirname "$(readlink -f "$0")")/../../.." && pwd)"
|
||||
# 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_ROOT/node_modules/.bin/tsx" "$PEPPA_ROOT/apps/bot/src/index.ts" "$@"
|
||||
exec "${PEPPA_NODE:-node}" --import "$PEPPA_ROOT/scripts/lib/require-node.mjs" "$PEPPA_ROOT/apps/bot/src/index.ts" "$@"
|
||||
|
||||
@ -3,9 +3,9 @@
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"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" },
|
||||
"scripts": { "start": "tsx src/index.ts", "typecheck": "tsc -p ." },
|
||||
"scripts": { "start": "node src/index.ts", "typecheck": "tsc -p ." },
|
||||
"dependencies": {
|
||||
"@peppa/core": "workspace:*",
|
||||
"@peppa/db": "workspace:*",
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
68
apps/bot/src/drafts.ts
Normal file
68
apps/bot/src/drafts.ts
Normal file
@ -0,0 +1,68 @@
|
||||
// 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.
|
||||
import { deleteSetting, getSetting, setSetting, type Project } from "@peppa/core";
|
||||
|
||||
export { splitStory, TITLE_MAX } from "@peppa/core";
|
||||
import type { Db } from "@peppa/db";
|
||||
|
||||
export const DRAFT_TTL_MS = 24 * 3600_000;
|
||||
|
||||
export interface Draft {
|
||||
id: number;
|
||||
userId: number;
|
||||
chatId: number;
|
||||
text: string;
|
||||
projectId: number | null;
|
||||
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;
|
||||
}
|
||||
|
||||
const key = (id: number) => `bot.draft:${id}`;
|
||||
|
||||
export async function saveDraft(db: Db, d: Omit<Draft, "id" | "createdAt">): Promise<Draft> {
|
||||
const id = ((await getSetting<number>(db, "bot.draft.seq")) ?? 0) + 1;
|
||||
await setSetting(db, "bot.draft.seq", id);
|
||||
const draft: Draft = { ...d, id, createdAt: Date.now() };
|
||||
await setSetting(db, key(id), draft);
|
||||
return draft;
|
||||
}
|
||||
|
||||
/** The user's own, not expired draft. */
|
||||
export async function loadDraft(db: Db, id: number, userId: number): Promise<Draft | null> {
|
||||
const d = await getSetting<Draft>(db, key(id));
|
||||
if (!d || d.userId !== userId) return null;
|
||||
if (Date.now() - d.createdAt > DRAFT_TTL_MS) {
|
||||
await deleteSetting(db, key(id));
|
||||
return null;
|
||||
}
|
||||
return d;
|
||||
}
|
||||
|
||||
export async function updateDraft(db: Db, d: Draft): Promise<void> {
|
||||
await setSetting(db, key(d.id), d);
|
||||
}
|
||||
|
||||
export async function dropDraft(db: Db, id: number): Promise<void> {
|
||||
await deleteSetting(db, key(id));
|
||||
}
|
||||
|
||||
/**
|
||||
* "в 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.
|
||||
*/
|
||||
export function parseStoryText(text: string, projects: Project[]): { project: Project | null; body: string } {
|
||||
const t = text.trim();
|
||||
const byKey = (k: string) => projects.find((p) => p.key.toLowerCase() === k.toLowerCase()) ?? null;
|
||||
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() };
|
||||
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() };
|
||||
return { project: null, body: t };
|
||||
}
|
||||
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));
|
||||
@ -1,6 +1,8 @@
|
||||
// Entry point: `peppa-bot` (launchd agent quest.telecom.peppa.bot).
|
||||
import { createDb } from "@peppa/db";
|
||||
import { loadEnv } from "@peppa/shared";
|
||||
import { setRunnerClient } from "@peppa/runner";
|
||||
import { installCrashReporting } from "@peppa/core";
|
||||
import { createBot } from "./bot.ts";
|
||||
import { TelegramApi } from "./telegram.ts";
|
||||
|
||||
@ -9,8 +11,13 @@ if (!env.TELEGRAM_BOT_TOKEN) {
|
||||
console.error("TELEGRAM_BOT_TOKEN is not set");
|
||||
process.exit(1);
|
||||
}
|
||||
const db = createDb(env.PEPPA_DB);
|
||||
// PEP-21: the bot only enqueues runner commands; the runner service (watchdog) runs them.
|
||||
setRunnerClient(true, db);
|
||||
// PEP-91: a crash of the bot goes to Bugsink before launchd restarts it.
|
||||
installCrashReporting(db, "bot");
|
||||
const bot = createBot({
|
||||
db: createDb(env.DATABASE_URL),
|
||||
db,
|
||||
api: new TelegramApi(env.TELEGRAM_BOT_TOKEN, process.env.TELEGRAM_API_URL),
|
||||
secret: env.TELEGRAM_BOT_TOKEN,
|
||||
webUrl: env.PEPPA_WEB_URL,
|
||||
|
||||
@ -1,79 +1,104 @@
|
||||
// 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 { asIs, m as tr } from "@peppa/shared/i18n";
|
||||
|
||||
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 KIND: Record<Question["kind"], string> = {
|
||||
approval: "📝 Нужно одобрение proposal",
|
||||
question: "❓ Вопрос",
|
||||
permission: "🔐 Нужно разрешение",
|
||||
attention: "👀 Сессия ждёт тебя",
|
||||
approval: tr("📝 Нужно одобрение плана"),
|
||||
question: tr("❓ Вопрос"),
|
||||
permission: tr("🔐 Нужно разрешение"),
|
||||
attention: tr("👀 Сообщение"),
|
||||
};
|
||||
|
||||
/** PEP-198: the name the owner sees on every message of the factory. */
|
||||
export const VOICE = tr("🔎 Аналитик");
|
||||
|
||||
export interface Rendered {
|
||||
text: string;
|
||||
buttons: InlineButton[][];
|
||||
}
|
||||
|
||||
// callback_data (≤64 bytes): "q:<questionId>:<choice>" or "s:<sessionId>:<action>"
|
||||
// callback_data (≤64 bytes): "q:<questionId>:<choice>", "s:<sessionId>:<action>" (resume|stop|ask) or "i:<incidentId>:<decision>" (core/incidents.ts)
|
||||
export function renderQuestion(
|
||||
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 {
|
||||
const head = [`<b>${esc(ctx.taskKey ?? `Сессия ${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)
|
||||
.join(" · ");
|
||||
const body = esc(clip(q.text, 3300));
|
||||
const lines = [head, KIND[q.kind], "", body];
|
||||
// PEP-154: no service text in the message (a permission request keeps its command, whole).
|
||||
// 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 type = questionType(q, ctx.taskStatus);
|
||||
if (q.kind === "approval") {
|
||||
buttons.push([{ text: "✅ Одобрить", callback_data: `q:${q.id}:approve` }]);
|
||||
lines.push("", "<i>Чтобы вернуть на доработку — ответь на это сообщение комментарием.</i>");
|
||||
buttons.push([{ text: tr("✅ Одобрить"), callback_data: `q:${q.id}:approve` }]);
|
||||
lines.push("", italic(tr("Чтобы вернуть на доработку — ответьте на это сообщение комментарием.")));
|
||||
} else if (q.kind === "permission") {
|
||||
buttons.push([
|
||||
{ text: "✅ Разрешить", callback_data: `q:${q.id}:allow` },
|
||||
{ text: "♾ Всегда", callback_data: `q:${q.id}:always` },
|
||||
{ text: "⛔ Запретить", callback_data: `q:${q.id}:deny` },
|
||||
{ text: tr("✅ Разрешить"), callback_data: `q:${q.id}:allow` },
|
||||
{ text: tr("♾ Всегда"), callback_data: `q:${q.id}:always` },
|
||||
{ text: tr("⛔ Запретить"), callback_data: `q:${q.id}:deny` },
|
||||
]);
|
||||
} else if (q.kind === "question") {
|
||||
(q.options ?? []).slice(0, 6).forEach((o, i) => buttons.push([{ text: clip(o, 60), callback_data: `q:${q.id}:o${i}` }]));
|
||||
lines.push("", "<i>Выбери вариант или ответь на это сообщение своим текстом.</i>");
|
||||
} else if (ctx.taskStatus === "review") {
|
||||
lines[1] = "✅ Готово к ревью";
|
||||
buttons.push([{ text: "✅ Принять", callback_data: `q:${q.id}:accept` }]);
|
||||
lines.push("", "<i>Есть замечания — ответь на это сообщение, агент доработает.</i>");
|
||||
} else if (type === "question") {
|
||||
// PEP-149: a question always comes with answers to tap; the default goes first.
|
||||
(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}` }]));
|
||||
if (q.kind === "attention") lines[1] = KIND.question;
|
||||
lines.push("", italic(tr("Выберите вариант или ответьте на это сообщение своим текстом.")));
|
||||
if (q.defaultOption) lines.push(italic(esc(tr("Если не ответите, агент продолжит по варианту «{option}».", { option: q.defaultOption }))));
|
||||
} else if (type === "done") {
|
||||
lines[1] = tr("✅ Готово к ревью");
|
||||
buttons.push([{ text: tr("✅ Принять"), callback_data: `q:${q.id}:accept` }]);
|
||||
lines.push("", italic(tr("Есть замечания — ответьте на это сообщение, агент доработает.")));
|
||||
} else {
|
||||
// A message of the factory itself (a failure, a limit): nothing to choose — no «continue» button.
|
||||
const s = ctx.session;
|
||||
if (s && ["failed", "rate_limited", "stalled"].includes(s.status)) {
|
||||
buttons.push([
|
||||
{ text: "🔁 Перезапустить", callback_data: `s:${s.id}:resume` },
|
||||
{ text: "⏹ Остановить", callback_data: `s:${s.id}:stop` },
|
||||
{ text: tr("🔁 Перезапустить"), callback_data: `s:${s.id}:resume` },
|
||||
{ text: tr("⏹ Остановить"), callback_data: `s:${s.id}:stop` },
|
||||
]);
|
||||
} else {
|
||||
buttons.push([{ text: "▶️ Продолжай", callback_data: `q:${q.id}:cont` }]);
|
||||
lines.push("", "<i>Или ответь на это сообщение — текст уйдёт в сессию.</i>");
|
||||
// PEP-186: agents stand on a limit of their subscription — ask the superadmin for one.
|
||||
if (s.status === "rate_limited" && s.subscriptionId != null) buttons.push([{ text: tr("🙋 Попросить подписку у администратора"), callback_data: `s:${s.id}:ask` }]);
|
||||
}
|
||||
}
|
||||
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 };
|
||||
}
|
||||
|
||||
/** Text after the question is closed: original + who answered what, no buttons. */
|
||||
export function renderAnswered(original: string, q: Question): string {
|
||||
const mark = q.answeredVia === "system" ? "⌛" : "✅";
|
||||
const via = { telegram: "в Telegram", web: "в вебе", terminal: "в терминале", system: "" }[q.answeredVia ?? "telegram"];
|
||||
return `${original}\n\n${mark} ${q.answeredVia === "system" ? esc(q.answer ?? "") : `Ответ ${via}: <b>${esc(clip(q.answer ?? "", 500))}</b>`}`;
|
||||
const via = { telegram: tr("в Telegram"), web: tr("в вебе"), terminal: tr("в терминале"), system: "" }[q.answeredVia ?? "telegram"];
|
||||
// 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. */
|
||||
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 === "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);
|
||||
if (q.kind === "question" && m) return q.options?.[Number(m[1])] ?? null;
|
||||
if (m) return q.options?.[Number(m[1])] ?? 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
|
||||
// mock-telegram (packages/testkit).
|
||||
|
||||
@ -8,10 +9,28 @@ export interface TgUser {
|
||||
}
|
||||
export interface TgMessage {
|
||||
message_id: number;
|
||||
chat: { id: number; type: string };
|
||||
chat: { id: number; type: string; title?: string };
|
||||
from?: TgUser;
|
||||
text?: string;
|
||||
/** PEP-62: a group became a supergroup (new chat id). */
|
||||
migrate_to_chat_id?: number;
|
||||
reply_to_message?: TgMessage;
|
||||
/** PEP-45: voice notes and audio files become stories after transcription. */
|
||||
voice?: 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 {
|
||||
file_id: string;
|
||||
duration?: number;
|
||||
mime_type?: string;
|
||||
file_size?: number;
|
||||
}
|
||||
export interface TgCallbackQuery {
|
||||
id: string;
|
||||
@ -30,24 +49,46 @@ export interface InlineButton {
|
||||
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 {
|
||||
constructor(
|
||||
readonly method: string,
|
||||
readonly code: number,
|
||||
readonly description: string,
|
||||
readonly retryAfter?: number,
|
||||
) {
|
||||
readonly method: string;
|
||||
readonly code: number;
|
||||
readonly description: string;
|
||||
readonly retryAfter?: number;
|
||||
constructor(method: string, code: number, description: string, retryAfter?: number) {
|
||||
super(`${method}: ${code} ${description}`);
|
||||
this.method = method;
|
||||
this.code = code;
|
||||
this.description = description;
|
||||
this.retryAfter = retryAfter;
|
||||
}
|
||||
}
|
||||
|
||||
export class TelegramApi {
|
||||
constructor(
|
||||
private readonly token: string,
|
||||
private readonly baseUrl = "https://api.telegram.org",
|
||||
) {}
|
||||
private readonly token: string;
|
||||
private readonly baseUrl: string;
|
||||
constructor(token: string, baseUrl = "https://api.telegram.org") {
|
||||
this.token = token;
|
||||
this.baseUrl = baseUrl;
|
||||
}
|
||||
|
||||
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;
|
||||
try {
|
||||
res = await fetch(`${this.baseUrl}/bot${this.token}/${method}`, {
|
||||
@ -91,6 +132,34 @@ export class TelegramApi {
|
||||
return this.call<boolean>("answerCallbackQuery", { callback_query_id: id, text });
|
||||
}
|
||||
|
||||
getFile(fileId: string) {
|
||||
return this.call<{ file_id: string; file_path?: string; file_size?: number }>("getFile", { file_id: fileId });
|
||||
}
|
||||
|
||||
/** Bytes of a file from getFile (Bot API: GET /file/bot<token>/<file_path>, up to 20 MB). */
|
||||
async downloadFile(filePath: string): Promise<Buffer> {
|
||||
const res = await fetch(`${this.baseUrl}/file/bot${this.token}/${filePath}`, { signal: AbortSignal.timeout(60_000) });
|
||||
if (!res.ok) throw new TelegramError("downloadFile", res.status, res.statusText);
|
||||
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> = {}) {
|
||||
return this.call<TgMessage>("sendMessage", { chat_id: chatId, text, parse_mode: "HTML", ...extra });
|
||||
}
|
||||
|
||||
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:*"
|
||||
}
|
||||
}
|
||||
13
apps/observer/src/index.ts
Normal file
13
apps/observer/src/index.ts
Normal file
@ -0,0 +1,13 @@
|
||||
// Entry point: `peppa-observer` (launchd agent quest.telecom.peppa.observer), PEP-202.
|
||||
import { createDb } from "@peppa/db";
|
||||
import { loadEnv } from "@peppa/shared";
|
||||
import { installCrashReporting, setDefaultActor } from "@peppa/core";
|
||||
import { runObserver } from "./observer.ts";
|
||||
|
||||
const env = loadEnv();
|
||||
const db = createDb(env.PEPPA_DB);
|
||||
setDefaultActor({ kind: "system" });
|
||||
installCrashReporting(db, "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);
|
||||
53
apps/observer/src/observer.ts
Normal file
53
apps/observer/src/observer.ts
Normal file
@ -0,0 +1,53 @@
|
||||
// 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, 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;
|
||||
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}`);
|
||||
}
|
||||
}
|
||||
// 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"] }
|
||||
9
apps/web/AGENTS.md
Normal file
9
apps/web/AGENTS.md
Normal file
@ -0,0 +1,9 @@
|
||||
<!-- BEGIN:nextjs-agent-rules -->
|
||||
|
||||
## This is NOT the Next.js you know
|
||||
|
||||
This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` (resolved from this file's directory; in monorepos the `next` package may not be visible from the repo root) before writing any code. Heed deprecation notices.
|
||||
|
||||
This block is written and re-added by `next dev` — verify at `node_modules/next/dist/server/lib/generate-agent-files.js`. Removing it from a diff only re-creates the uncommitted change; committing it with your work keeps the tree clean.
|
||||
|
||||
<!-- END:nextjs-agent-rules -->
|
||||
File diff suppressed because it is too large
Load Diff
123
apps/web/app/(app)/board-actions.ts
Normal file
123
apps/web/app/(app)/board-actions.ts
Normal file
@ -0,0 +1,123 @@
|
||||
"use server";
|
||||
// Board order and archive (PEP-34), story dependencies and the epic planner (PEP-42).
|
||||
// Thin wrappers over core/runner with the owner/member check, like actions.ts.
|
||||
|
||||
import { getEpic, PeppaError, projectForUser, resolveTask, setDependencies, type TaskRef } from "@peppa/core";
|
||||
import { applyPlan, archiveTask, discardPlanDraft, parseDepsInput, planEpic, reorderBoardTask, type PlanDep, type PlannedStory } from "@peppa/runner";
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { redirect } from "next/navigation";
|
||||
import { requireUser } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
|
||||
const str = (f: FormData, k: string) => String(f.get(k) ?? "").trim();
|
||||
|
||||
async function attempt(f: FormData, fn: () => Promise<string | void>): Promise<never> {
|
||||
let target = str(f, "back") || "/";
|
||||
try {
|
||||
target = (await fn()) || target;
|
||||
} catch (e) {
|
||||
const msg = e instanceof PeppaError ? e.message : m("Ошибка: {message}", { message: (e as Error).message });
|
||||
const [path, query] = target.split("?");
|
||||
const params = new URLSearchParams(query);
|
||||
params.set("error", msg.slice(0, 300));
|
||||
target = `${path}?${params}`;
|
||||
}
|
||||
revalidatePath("/", "layout");
|
||||
redirect(target);
|
||||
}
|
||||
|
||||
async function ownedTask(userId: number, key: string): Promise<TaskRef> {
|
||||
const ref = await resolveTask(db, key);
|
||||
await projectForUser(db, userId, ref.project.id);
|
||||
return ref;
|
||||
}
|
||||
|
||||
/** Drag within a column (before/after another card) or the card menu (top/bottom). */
|
||||
export async function reorderTaskCard(f: FormData) {
|
||||
const user = await requireUser();
|
||||
await attempt(f, async () => {
|
||||
const ref = await ownedTask(user.id, str(f, "taskKey"));
|
||||
const to = str(f, "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 throw new PeppaError(m("Неизвестное место"));
|
||||
});
|
||||
}
|
||||
|
||||
/** Called from the board without a page reload (drag and drop); errors are returned. */
|
||||
export async function reorderTaskInline(taskKey: string, to: "top" | "bottom" | "before" | "after", other?: string): Promise<string | null> {
|
||||
const user = await requireUser();
|
||||
try {
|
||||
const ref = await ownedTask(user.id, taskKey);
|
||||
if (to === "before" || to === "after") await reorderBoardTask(db, ref, { to, other: await ownedTask(user.id, other ?? "") });
|
||||
else await reorderBoardTask(db, ref, { to });
|
||||
revalidatePath("/", "layout");
|
||||
return null;
|
||||
} catch (e) {
|
||||
return e instanceof PeppaError ? e.message : (e as Error).message;
|
||||
}
|
||||
}
|
||||
|
||||
export async function archiveTaskAction(f: FormData) {
|
||||
const user = await requireUser();
|
||||
await attempt(f, async () => {
|
||||
const ref = await ownedTask(user.id, str(f, "taskKey"));
|
||||
await archiveTask(db, ref, str(f, "archived") !== "0");
|
||||
});
|
||||
}
|
||||
|
||||
export async function setDependenciesAction(f: FormData) {
|
||||
const user = await requireUser();
|
||||
await attempt(f, async () => {
|
||||
const ref = await ownedTask(user.id, str(f, "taskKey"));
|
||||
const keys = str(f, "blockedBy").split(/[\s,;]+/).filter(Boolean);
|
||||
// "remove" drops one key from the current list; otherwise the field adds to it.
|
||||
const current = (f.getAll("current") as string[]).map(String);
|
||||
const remove = str(f, "remove");
|
||||
await setDependencies(db, ref, remove ? current.filter((k) => k !== remove) : [...current, ...keys]);
|
||||
});
|
||||
}
|
||||
|
||||
export async function planEpicAction(f: FormData) {
|
||||
const user = await requireUser();
|
||||
await attempt(f, async () => {
|
||||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||||
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 });
|
||||
if (!r.ok) throw new PeppaError(m("Планировщик: {error}", { error: r.error }));
|
||||
});
|
||||
}
|
||||
|
||||
export async function applyPlanAction(f: FormData) {
|
||||
const user = await requireUser();
|
||||
await attempt(f, async () => {
|
||||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||||
const epicId = Number(str(f, "epicId"));
|
||||
const n = Number(str(f, "count"));
|
||||
// Plan numbers in the form refer to the full draft; renumber them for the kept stories.
|
||||
const kept: number[] = [];
|
||||
for (let i = 1; i <= n; i++) if (f.get(`keep_${i}`)) kept.push(i);
|
||||
if (!kept.length) throw new PeppaError(m("Не выбрано ни одной задачи. Отметьте хотя бы одну."));
|
||||
const renum = new Map(kept.map((orig, i) => [orig, i + 1]));
|
||||
const stories: PlannedStory[] = kept.map((i) => {
|
||||
const deps = parseDepsInput(str(f, `deps_${i}`)).map((d): PlanDep => {
|
||||
if (typeof d !== "number") return d;
|
||||
if (!renum.has(d)) throw new PeppaError(m("Задача {i} зависит от №{d}, которую вы сняли. Уберите зависимость или оставьте задачу.", { i, d }));
|
||||
return renum.get(d)!;
|
||||
});
|
||||
return { title: str(f, `title_${i}`), description: str(f, `description_${i}`), dependsOn: deps };
|
||||
});
|
||||
await applyPlan(db, p, epicId, stories);
|
||||
return `/p/${p.key}?epic=${epicId}`;
|
||||
});
|
||||
}
|
||||
|
||||
export async function discardPlanAction(f: FormData) {
|
||||
const user = await requireUser();
|
||||
await attempt(f, async () => {
|
||||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||||
const epic = await getEpic(db, p.id, Number(str(f, "epicId")));
|
||||
await discardPlanDraft(db, epic.id);
|
||||
});
|
||||
}
|
||||
532
apps/web/app/(app)/chats/[chat]/page.tsx
Normal file
532
apps/web/app/(app)/chats/[chat]/page.tsx
Normal file
@ -0,0 +1,532 @@
|
||||
import Link from "next/link";
|
||||
import { notFound } from "next/navigation";
|
||||
import { ArrowLeft, Bot, Link2, MessagesSquare, Send, Unlink, User as UserIcon } from "lucide-react";
|
||||
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 { formatTaskKey } from "@peppa/shared";
|
||||
import { PRODUCT_NAME, stripAsIs } from "@peppa/shared/i18n";
|
||||
import { eq, inArray } from "drizzle-orm";
|
||||
import { LiveRefresh } from "@/components/LiveRefresh";
|
||||
import { AgentBadge } from "@/components/AgentBadge";
|
||||
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 { 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 { Button } from "@/components/ui/button";
|
||||
import { Textarea } from "@/components/ui/input";
|
||||
import { requireUser, words } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { cleanText, messageLink, STUCK_NOTICE } from "@/lib/chat-text";
|
||||
import { chatOfferAction, linkChatAction, postChatAction, unlinkChatAction } from "../actions";
|
||||
|
||||
type Params = { error?: string; thread?: string; link?: string; q?: string; list?: string };
|
||||
|
||||
const CHANNEL = "channel";
|
||||
/** PEP-106: `?thread=feed` — the agents' events; no `thread` — the people's discussion. */
|
||||
const FEED = "feed";
|
||||
|
||||
/** «Чаты» (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> }) {
|
||||
const user = await requireUser();
|
||||
const t = await getT();
|
||||
const w = await words();
|
||||
const { chat: slug } = await params;
|
||||
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).
|
||||
await syncChats(db).catch((e) => console.error("syncChats", e));
|
||||
const list = await listChats(db, user);
|
||||
const chat = list.find((c) => c.slug.toLowerCase() === slug.toLowerCase());
|
||||
if (!chat) notFound();
|
||||
const master = chat.kind === "master";
|
||||
const thread = rawThread === CHANNEL ? null : rawThread && THREAD_KEY.test(rawThread) ? rawThread : undefined;
|
||||
// A project chat opens on the discussion: people talking to each other, no agents or events.
|
||||
const discussion = !master && rawThread === undefined;
|
||||
const unread = await discussionUnread(db, user.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 — «печатает…».
|
||||
const typing = discussion && (await analystPending(db, chat.id));
|
||||
|
||||
const rows = threads ? [...threads.waiting, ...threads.working, ...threads.done] : [];
|
||||
const messages = master
|
||||
? await masterFeed(db, user, { limit: 150 })
|
||||
: discussion
|
||||
? await discussionMessages(db, chat.id)
|
||||
: await chatMessagesView(db, chat.id, { threadKey: thread, limit: 150 });
|
||||
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).
|
||||
const qIds = messages.map((m) => m.question?.id).filter((x): x is number => x != null);
|
||||
const qs = qIds.length
|
||||
? await db.select({ q: questions, status: tasks.status, key: projects.key, number: tasks.number }).from(questions).innerJoin(projects, eq(questions.projectId, projects.id)).leftJoin(tasks, eq(questions.taskId, tasks.id)).where(inArray(questions.id, qIds))
|
||||
: [];
|
||||
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 base = `/chats/${chat.slug}`;
|
||||
const url = (p: { thread?: string | null; list?: boolean }) => {
|
||||
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) });
|
||||
// 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.
|
||||
const superadmin = await isSuperadmin(db, user);
|
||||
const bot = user.telegramBotUsername ?? (superadmin ? ((await getSetting<{ username: string }>(db, "telegram.bot"))?.username ?? null) : null);
|
||||
const mayLink = !!user.telegramBotUsername || superadmin;
|
||||
const groupBot = chat.tgTitle ? await chatGroupBotName(db, chat.id) : null;
|
||||
const ttlDays = Math.round(chatTtlMs() / 86_400_000);
|
||||
const taskThread = thread?.startsWith("task:");
|
||||
const placeholder = master
|
||||
? w.engineer ? "/status, /task KEY-N, /move KEY-N in_progress, /help" : t("Заметка для себя")
|
||||
: discussion
|
||||
? t("Спросите аналитика, что с проектом, или опишите идею — он поможет сформулировать {task}…", { task: w.task("acc") })
|
||||
: taskThread
|
||||
? t("Напишите агенту этой {task} — ответ на его вопрос или замечание, он увидит сразу", { task: w.task("gen") })
|
||||
: thread
|
||||
? w.engineer ? t("Заметка в тред или команда /help") : t("Заметка к этой переписке")
|
||||
: w.engineer ? t("Заметка в канал или команда: /status, /task KEY-N, /move KEY-N in_progress") : t("Заметка для себя и участников проекта");
|
||||
|
||||
const aside = (
|
||||
<div className="flex flex-col gap-5 text-sm">
|
||||
<section className="flex flex-col gap-2">
|
||||
<h2 className="m-0 text-[15px] font-semibold">Telegram</h2>
|
||||
<p className="m-0 text-muted-foreground">
|
||||
{user.telegramBotUsername ? (
|
||||
<>
|
||||
{t("Новые сообщения обсуждения и вопросы агентов приходят в ваш бот")} <span className="font-mono text-foreground">@{user.telegramBotUsername}</span>.
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
{t("Чтобы новые сообщения приходили в Telegram, подключите своего бота:")} <Link href="/settings#telegram">{t("Настройки → Telegram")}</Link>.
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
</section>
|
||||
<section className="flex flex-col gap-2">
|
||||
<h2 className="m-0 text-[15px] font-semibold">{t("Telegram-группа")}</h2>
|
||||
{chat.tgTitle ? (
|
||||
<>
|
||||
<p className="m-0 text-muted-foreground">
|
||||
{t("Связан с группой")} <b className="text-foreground">{chat.tgTitle}</b>
|
||||
{groupBot && (
|
||||
<>
|
||||
{" "}
|
||||
{t("через бота")} <span className="font-mono text-foreground">@{groupBot}</span>
|
||||
</>
|
||||
)}
|
||||
.{" "}
|
||||
{master
|
||||
? t("Сообщения чата приходят туда, треды — цепочками ответов; ответ реплаем уходит в тред.")
|
||||
: t("Сообщения чата приходят туда, треды — цепочками ответов; ответ реплаем уходит в тред (в переписке по {task} — агенту).", { task: w.task("dat") })}
|
||||
</p>
|
||||
<form action={unlinkChatAction}>
|
||||
<Hidden fields={{ chatId: chat.id, back: here }} />
|
||||
<Button size="sm" variant="outline">
|
||||
<Unlink />
|
||||
{t("Отвязать группу")}
|
||||
</Button>
|
||||
</form>
|
||||
</>
|
||||
) : !mayLink ? (
|
||||
<p className="m-0 text-muted-foreground">
|
||||
{master ? t("Мастер-чат можно связать с группой Telegram — туда пойдёт всё важное по вашим проектам.") : t("Чат проекта можно связать с группой команды в Telegram.")}{" "}
|
||||
{t("Группа подключается через вашего собственного бота — сначала подключите его:")} <Link href="/settings#telegram">{t("Настройки → Telegram")}</Link>.
|
||||
</p>
|
||||
) : link ? (
|
||||
<div className="flex flex-col gap-2 rounded-lg border bg-card p-3">
|
||||
<p className="m-0">{t("Код действует 10 минут.")}</p>
|
||||
{bot && (
|
||||
<a href={`https://t.me/${bot}?startgroup=${encodeURIComponent(link)}`} target="_blank" rel="noreferrer" className="font-medium">
|
||||
{t("Добавить @{bot} в группу →", { bot })}
|
||||
</a>
|
||||
)}
|
||||
<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>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<p className="m-0 text-muted-foreground">
|
||||
{master ? t("Свяжите мастер-чат с группой — туда пойдёт всё важное по вашим проектам.") : t("Свяжите чат проекта с группой команды — по ней сразу видно, к какому проекту сообщение.")}
|
||||
{bot && (
|
||||
<>
|
||||
{" "}
|
||||
{t("В группу добавится ваш бот")} <span className="font-mono text-foreground">@{bot}</span>.
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
<form action={linkChatAction}>
|
||||
<Hidden fields={{ chatId: chat.id, back: here }} />
|
||||
<Button size="sm" variant="outline">
|
||||
<Link2 />
|
||||
{t("Связать с Telegram")}
|
||||
</Button>
|
||||
</form>
|
||||
</>
|
||||
)}
|
||||
<p className="m-0 text-xs text-muted-foreground">{t("Отвечать из группы могут те, кто привязал Telegram в «Настройках» и имеет доступ к {target}.", { target: master ? t("мастер-чату (только вы)") : t("проекту") })}</p>
|
||||
</section>
|
||||
<section className="flex flex-col gap-1.5 text-xs text-muted-foreground">
|
||||
<h2 className="m-0 text-[15px] font-semibold text-foreground">{t("Как это устроено")}</h2>
|
||||
<p className="m-0">
|
||||
{master
|
||||
? t("Журнал: готовые {tasks}, вопросы, обновления продукта и сбои по всем вашим проектам. Отвечать удобнее в «Обзоре» или в чате проекта.", { tasks: w.task("pl") })
|
||||
: t("Слева: чат с аналитиком — для вопросов и новых задач; «События агентов» — журнал; ниже — переписка по каждой {task} с её агентом.", { task: w.task("dat") })}
|
||||
</p>
|
||||
<p className="m-0">{t("Журнал событий хранится {n} дн.; ваша переписка с аналитиком не удаляется.", { n: ttlDays })}</p>
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
|
||||
// PEP-207: the chat with the analyst holds people and the analyst; the factory's service notices
|
||||
// («задерживается на нашей стороне») are the status line on top, not messages — old ones included.
|
||||
const shownMessages = discussion ? messages.filter((m) => !(m.authorKind !== "user" && STUCK_NOTICE.test(stripAsIs(m.text)))) : messages;
|
||||
const status = discussion && chat.projectId ? await chatStatusLine(db, chat.projectId) : null;
|
||||
// PEP-207: oldest first, newest at the bottom — the first unread message is where the reader lands.
|
||||
const ordered = [...shownMessages];
|
||||
const unreadCount = discussion ? (unreadBefore ?? 0) : (openRow?.unread ?? 0);
|
||||
const counted = (m: ChatMessageView) => (discussion ? m.authorUserId !== user.id : m.kind === "question" || (m.kind === "user" && m.authorKind !== "user"));
|
||||
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}` };
|
||||
});
|
||||
|
||||
const feed = ordered.length === 0 ? (
|
||||
<Empty>{discussion ? t("Напишите, что хотите узнать или сделать, — аналитик ответит здесь же. Например: «Что сейчас в работе?» или «Хочу страницу с отзывами клиентов».") : master ? t("Пока тихо: здесь появятся вопросы агентов, сбои и обновления ваших проектов.") : thread === undefined ? t("Сообщений пока нет: они появятся, когда агенты возьмутся за {tasks}.", { tasks: w.task("accPl") }) : t("В этом треде пока пусто.")}</Empty>
|
||||
) : (
|
||||
<ol data-chat-messages className="m-0 flex list-none flex-col gap-2 p-0 pr-12 md:pr-14">
|
||||
{groups.map((g) =>
|
||||
g.kind === "events" ? (
|
||||
<li key={`e${g.items[0]!.id}`}>
|
||||
<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>
|
||||
);
|
||||
|
||||
return (
|
||||
<Workspace aside={null} wide>
|
||||
{/* 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. */}
|
||||
<LiveRefresh scope={master ? "chats" : `chat:${chat.id}`} indicator={false} />
|
||||
<Flash error={error} />
|
||||
<h1 className="sr-only">{t("Чаты")}</h1>
|
||||
|
||||
<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} />
|
||||
) : (
|
||||
<p className="m-0 rounded-lg border bg-card/50 p-3 text-sm text-muted-foreground">{t("Все события по вашим проектам — справочно. Чтобы ответить или написать, выберите проект.")}</p>
|
||||
)}
|
||||
{master && superadmin && (
|
||||
<Link href="/journal" className="text-sm">{t("Полный журнал платформы →")}</Link>
|
||||
)}
|
||||
<details className="rounded-lg border bg-card/50 p-3 text-sm">
|
||||
<summary className="cursor-pointer text-muted-foreground">Telegram</summary>
|
||||
<div className="mt-3">{aside}</div>
|
||||
</details>
|
||||
</div>
|
||||
|
||||
<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 }} />
|
||||
<div className="flex items-end gap-1.5">
|
||||
<Textarea id="chat-text" name="text" rows={1} maxLength={60000} placeholder={placeholder} aria-label={t("Сообщение")} className="max-h-40 min-h-9 flex-1 resize-y py-1.5" />
|
||||
{chat.projectId && <AttachField projectId={chat.projectId} target="chat-text" className="shrink-0" />}
|
||||
<Dictate target="chat-text" compact />
|
||||
<Button size="sm" aria-label={t("Отправить")} title={t("Отправить")} className="h-9">
|
||||
<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>
|
||||
</div>
|
||||
</Workspace>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
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 (
|
||||
<details data-event-group className="border-y border-dashed py-1" open={items.some((m) => m.id === firstUnreadId)}>
|
||||
<summary className="cursor-pointer px-1 text-xs text-muted-foreground">
|
||||
{t("{n} событий", { n: items.length })} · {cleanText(t.text(items.at(-1)!.text), superadmin, gitea).split("\n")[0]}
|
||||
</summary>
|
||||
<div className="mt-1 flex flex-col gap-1">{items.map(line)}</div>
|
||||
</details>
|
||||
);
|
||||
}
|
||||
|
||||
function TaskLink({ messages, label }: { messages: ChatMessageView[]; label: string }) {
|
||||
const key = messages.find((m) => m.threadTitle)?.threadTitle?.split(" · ")[0];
|
||||
return key ? <Link href={`/t/${key}`} className="text-xs">{label}</Link> : null;
|
||||
}
|
||||
|
||||
/** URLs in a message become links (the analyst points at the board, a story, a stand). */
|
||||
function threadHref(m: ChatMessageView) {
|
||||
return m.projectKey && m.threadKey ? `/chats/${m.projectKey}?thread=${encodeURIComponent(m.threadKey)}` : m.projectKey ? `/chats/${m.projectKey}` : null;
|
||||
}
|
||||
|
||||
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));
|
||||
// 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 label = [masterView && m.projectKey ? m.projectKey : null, m.threadTitle ? t.text(m.threadTitle) : null].filter(Boolean).join(" · ");
|
||||
const head = (
|
||||
<div className="flex flex-wrap items-center gap-x-2 gap-y-0.5 text-xs text-muted-foreground">
|
||||
{/* PEP-207: who speaks — a person by login, an agent by its name and icon; events always come from the factory. */}
|
||||
{person ? <UserIcon className="size-3.5" /> : agentLabel ? null : m.authorKind === "agent" ? <Bot className="size-3.5" /> : <MessagesSquare className="size-3.5" />}
|
||||
{agentLabel ? (
|
||||
<AgentBadge name={agentLabel} className="text-foreground" />
|
||||
) : (
|
||||
<span className="font-medium text-foreground">{person ? (mine ? t("вы") : (m.authorLogin ?? "?")) : m.authorKind === "agent" ? t("агент") : PRODUCT_NAME}</span>
|
||||
)}
|
||||
{m.via === "telegram" && <span title={t("из Telegram")}>· Telegram</span>}
|
||||
{where && href && (
|
||||
<Link href={href} className="max-w-full truncate">
|
||||
🧵 {label}
|
||||
</Link>
|
||||
)}
|
||||
{/* 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>
|
||||
);
|
||||
if (q) {
|
||||
return (
|
||||
<div className="flex flex-col gap-1">
|
||||
{head}
|
||||
<QuestionCard q={q.q} taskKey={q.taskKey} taskStatus={q.taskStatus} back={back} compact clean={!superadmin} />
|
||||
</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 (
|
||||
<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}
|
||||
<p data-message-main className="m-0 text-sm break-words whitespace-pre-wrap">{linkify(shown.main)}</p>
|
||||
{shown.more && (
|
||||
<details data-message-details className="text-xs text-muted-foreground">
|
||||
<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>
|
||||
)}
|
||||
{/* 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>
|
||||
);
|
||||
}
|
||||
79
apps/web/app/(app)/chats/actions.ts
Normal file
79
apps/web/app/(app)/chats/actions.ts
Normal file
@ -0,0 +1,79 @@
|
||||
"use server";
|
||||
// «Чаты» (PEP-62): a message into a chat/thread, Telegram group link/unlink. Access — chatForUser.
|
||||
|
||||
import { parseAttachmentIds, chatForUser, createChatLinkCode, isSuperadmin, markDiscussionRead, markThreadRead, PeppaError, THREAD_KEY, unlinkChat } from "@peppa/core";
|
||||
import { postToChat, resolveChatOffer, type ChatOfferChoice } from "@peppa/runner";
|
||||
import { loadEnv } from "@peppa/shared";
|
||||
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";
|
||||
|
||||
const str = (f: FormData, k: string) => String(f.get(k) ?? "").trim();
|
||||
|
||||
/** Runs an action; errors come back as ?error=… (redirect stays outside try). */
|
||||
async function attempt(f: FormData, fn: () => Promise<string | void>): Promise<never> {
|
||||
let target = str(f, "back") || "/chats";
|
||||
try {
|
||||
target = (await fn()) || target;
|
||||
} catch (e) {
|
||||
const msg = e instanceof PeppaError ? e.message : m("Ошибка: {message}", { message: (e as Error).message });
|
||||
const [path, query] = target.split("?");
|
||||
const params = new URLSearchParams(query);
|
||||
params.set("error", msg.slice(0, 300));
|
||||
target = `${path}?${params}`;
|
||||
}
|
||||
revalidatePath("/chats", "layout");
|
||||
redirect(target);
|
||||
}
|
||||
|
||||
export async function postChatAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const thread = str(f, "thread");
|
||||
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);
|
||||
});
|
||||
}
|
||||
|
||||
/** A one-time code (10 min) for `/link <код>` in a group, or the startgroup link of the user's bot that sends it. */
|
||||
export async function linkChatAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const token = loadEnv().TELEGRAM_BOT_TOKEN;
|
||||
if (!token) throw new PeppaError(m("Telegram пока не настроен. Напишите в поддержку FORGE."));
|
||||
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
|
||||
// superadmin's (PEP-106) and serves only a superadmin who has no bot of their own.
|
||||
const code = await createChatLinkCode(db, token, user, chat.id, { sharedBot: await isSuperadmin(db, user) });
|
||||
const back = str(f, "back") || "/chats";
|
||||
return `${back}${back.includes("?") ? "&" : "?"}link=${encodeURIComponent(code)}`;
|
||||
});
|
||||
}
|
||||
|
||||
export async function unlinkChatAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, () => unlinkChat(db, user, Number(str(f, "chatId"))));
|
||||
}
|
||||
86
apps/web/app/(app)/chats/page.tsx
Normal file
86
apps/web/app/(app)/chats/page.tsx
Normal file
@ -0,0 +1,86 @@
|
||||
import Link from "next/link";
|
||||
import { ArrowRight, MessagesSquare } from "lucide-react";
|
||||
import { chatOverview, isRoleName, syncChats } from "@peppa/core";
|
||||
import { LiveRefresh } from "@/components/LiveRefresh";
|
||||
import { AgentBadge } from "@/components/AgentBadge";
|
||||
import { QuestionCard } from "@/components/cards";
|
||||
import { ago, Empty, Flash, PageHeader, Section } from "@/components/common";
|
||||
import { Workspace } from "@/components/Workspace";
|
||||
import { requireUser } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { inbox } from "@/lib/queries";
|
||||
import { getT } from "@/lib/i18n";
|
||||
|
||||
export async function generateMetadata() {
|
||||
const t = await getT();
|
||||
return { title: t("Чаты — FORGE") };
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* «Чаты» (PEP-117): the overview a product manager lands on — what waits for their answer and
|
||||
* where to write to the analyst of each project. The raw feed of events lives at /chats/master.
|
||||
*/
|
||||
export default async function Chats({ searchParams }: { searchParams: Promise<{ error?: string }> }) {
|
||||
const user = await requireUser();
|
||||
const t = await getT();
|
||||
const { error } = await searchParams;
|
||||
await syncChats(db).catch((e) => console.error("syncChats", e));
|
||||
const [cards, waiting] = await Promise.all([chatOverview(db, user), inbox(user.id)]);
|
||||
return (
|
||||
<Workspace>
|
||||
<LiveRefresh scope="chats" />
|
||||
<Flash error={error} />
|
||||
<PageHeader title={t("Чаты")}>{t("Здесь вы разговариваете с фабрикой: отвечаете агентам и пишете аналитику своего проекта — что узнать или что сделать.")}</PageHeader>
|
||||
|
||||
<Section title={t("Ждут вашего ответа")} count={waiting.length}>
|
||||
{waiting.length === 0 ? (
|
||||
<Empty>{t("Сейчас от вас ничего не нужно — агенты работают сами.")}</Empty>
|
||||
) : (
|
||||
waiting.map((q) => <QuestionCard key={q.id} q={q} taskKey={q.taskKey} taskStatus={q.taskStatus} back="/chats" />)
|
||||
)}
|
||||
</Section>
|
||||
|
||||
<Section title={t("Ваши проекты")} count={cards.length}>
|
||||
{cards.length === 0 ? (
|
||||
<Empty>
|
||||
{t("Проектов пока нет.")} <Link href="/projects/new">{t("Создайте проект")}</Link> {t("— и у него появится чат с аналитиком.")}
|
||||
</Empty>
|
||||
) : (
|
||||
<ul className="m-0 grid list-none gap-3 p-0 md:grid-cols-2">
|
||||
{cards.map((c) => (
|
||||
<li key={c.chatId}>
|
||||
<Link href={`/chats/${c.key}`} className="flex h-full flex-col gap-2 rounded-xl border bg-card p-4 text-foreground hover:border-primary/60 hover:no-underline">
|
||||
<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="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={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={t("агенты ждут вашего ответа")}>{t("ждут ответа: {n}", { n: c.open })}</span>}
|
||||
</span>
|
||||
{c.last ? (
|
||||
<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">
|
||||
{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, t)}</span>
|
||||
</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 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">
|
||||
<MessagesSquare className="size-4" /> {t("Написать аналитику")} <ArrowRight className="size-3.5" />
|
||||
</span>
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</Section>
|
||||
|
||||
<p className="mt-6 text-sm text-muted-foreground">
|
||||
{t("Нужна история?")} <Link href="/chats/master">{t("Все события по вашим проектам")}</Link> {t("— что делали агенты, обновления продукта и сбои, справочно.")}
|
||||
</p>
|
||||
</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("Не удалось начать вход в сервис"));
|
||||
}
|
||||
}
|
||||
723
apps/web/app/(app)/connections/page.tsx
Normal file
723
apps/web/app/(app)/connections/page.tsx
Normal file
@ -0,0 +1,723 @@
|
||||
import Link from "next/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,
|
||||
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 { 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>
|
||||
{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>
|
||||
)}
|
||||
<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] = await Promise.all([listConnections(db, user.id), connectionJournal(db, user.id, { limit: 50 }), listUserProjects(db, user.id), grantableAgents(db)]);
|
||||
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>
|
||||
|
||||
{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>
|
||||
);
|
||||
}
|
||||
33
apps/web/app/(app)/dashboard/actions.ts
Normal file
33
apps/web/app/(app)/dashboard/actions.ts
Normal file
@ -0,0 +1,33 @@
|
||||
"use server";
|
||||
// PEP-209: the superadmin's buttons on a delay card («Дашборд → Задержки»).
|
||||
|
||||
import { DELAY_REASON_NAMES, PeppaError, requireSuperadmin, type DelayAction, type DelayReason } from "@peppa/core";
|
||||
import { 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}`);
|
||||
}
|
||||
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 "next/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>
|
||||
);
|
||||
}
|
||||
196
apps/web/app/(app)/dashboard/page.tsx
Normal file
196
apps/web/app/(app)/dashboard/page.tsx
Normal file
@ -0,0 +1,196 @@
|
||||
import Link from "next/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";
|
||||
|
||||
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);
|
||||
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>
|
||||
|
||||
<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>
|
||||
);
|
||||
}
|
||||
126
apps/web/app/(app)/errors/[id]/page.tsx
Normal file
126
apps/web/app/(app)/errors/[id]/page.tsx
Normal file
@ -0,0 +1,126 @@
|
||||
// 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 Link from "next/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()}>{t("впервые {ago}", { ago: ago(r.firstSeen, t) })}</span>
|
||||
<span className="text-muted-foreground" title={r.lastSeen.toLocaleString()}>{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" })}</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);
|
||||
}
|
||||
52
apps/web/app/(app)/feedback/page.tsx
Normal file
52
apps/web/app/(app)/feedback/page.tsx
Normal file
@ -0,0 +1,52 @@
|
||||
import Link from "next/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";
|
||||
|
||||
/**
|
||||
* PEP-143: «Обращения». Everybody sees their own reports and where they stand; the superadmin
|
||||
* also sees everybody's, filtered by status, and decides on them.
|
||||
*/
|
||||
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>
|
||||
);
|
||||
}
|
||||
135
apps/web/app/(app)/gitea/page.tsx
Normal file
135
apps/web/app/(app)/gitea/page.tsx
Normal file
@ -0,0 +1,135 @@
|
||||
// glossary-ignore-file: superadmin-only page about the platform's git server — «репозиторий» is the literal object here
|
||||
import Link from "next/link";
|
||||
import { notFound } from "next/navigation";
|
||||
import { ExternalLink, GitBranch, Lock } from "lucide-react";
|
||||
import { giteaServerOverview, isSuperadmin, type GiteaServerRepo } from "@peppa/core";
|
||||
import { ago, Empty, 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 { 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 };
|
||||
|
||||
function RepoRow({ r, t }: { r: GiteaServerRepo; t: Translator }) {
|
||||
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>}
|
||||
<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);
|
||||
const needle = (q.q ?? "").trim().toLowerCase();
|
||||
const show = q.show === "linked" || q.show === "unlinked" ? q.show : "all";
|
||||
const repos = o.repos.filter(
|
||||
(r) => (!needle || r.fullName.toLowerCase().includes(needle) || r.description.toLowerCase().includes(needle)) && (show === "all" || (show === "linked") === !!r.project),
|
||||
);
|
||||
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.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>
|
||||
)}
|
||||
</Card>
|
||||
</Section>
|
||||
|
||||
{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>
|
||||
</select>
|
||||
<Button type="submit" size="sm">
|
||||
{t("Показать")}
|
||||
</Button>
|
||||
</form>
|
||||
{repos.length === 0 ? (
|
||||
<Empty>{t("Репозиториев не найдено.")}</Empty>
|
||||
) : (
|
||||
<Card className="p-0">
|
||||
<ul>
|
||||
{repos.map((r) => (
|
||||
<RepoRow key={r.fullName} r={r} t={t} />
|
||||
))}
|
||||
</ul>
|
||||
</Card>
|
||||
)}
|
||||
</Section>
|
||||
</div>
|
||||
</Workspace>
|
||||
);
|
||||
}
|
||||
74
apps/web/app/(app)/help/connect/page.tsx
Normal file
74
apps/web/app/(app)/help/connect/page.tsx
Normal file
@ -0,0 +1,74 @@
|
||||
import Link from "next/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";
|
||||
|
||||
/** PEP-135: how to connect FORGE to one's own Claude or ChatGPT — step by step; texts live in core/connect-texts.ts. */
|
||||
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>
|
||||
);
|
||||
}
|
||||
@ -1,87 +1,311 @@
|
||||
import Link from "next/link";
|
||||
import { publicOrigin } from "@/lib/auth";
|
||||
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 { Workspace } from "@/components/Workspace";
|
||||
import { voiceStoriesEnabled } from "@peppa/shared";
|
||||
import { PageHeader, Section } from "@/components/common";
|
||||
|
||||
const TOOLS: Array<[string, string]> = [
|
||||
["list_projects", "мои проекты, ссылка на репозиторий в Gitea и сколько задач в каждой колонке"],
|
||||
["create_project", "новый проект: репозиторий в Gitea (приватный по умолчанию или публичный) + шаблон + OpenSpec, или подключить существующий; отвечает ссылкой на репозиторий и кто его видит"],
|
||||
["list_goals / create_goal / update_goal", "цели проекта: завести, переименовать, отметить достигнутой или убрать в архив"],
|
||||
["list_tasks", "доска проекта: Бэклог / В работе / Ревью / Готово"],
|
||||
["get_task", "карточка задачи: описание, цель, статус, OpenSpec, вопросы, прогресс"],
|
||||
["create_task / update_task", "завести задачу (в Бэклог); поправить название, описание, цель"],
|
||||
["move_task", "передвинуть карточку; «В работе» запускает агента, «Бэклог»/«Готово» останавливают"],
|
||||
["list_members / add_member / remove_member", "участники проекта: посмотреть, добавить по логину Gitea, убрать или выйти"],
|
||||
["list_inbox / answer_question", "что ждёт вашего ответа; ответить агенту, принять ревью (accept)"],
|
||||
["get_started", m("правила работы для ИИ-клиента: вызывается первым, коротко и без кода")],
|
||||
["list_projects", m("мои проекты, ссылка на репозиторий в Gitea и сколько стори в каждой колонке")],
|
||||
["create_project", m("новый проект: репозиторий в Gitea (публичный по умолчанию или приватный) + шаблон + OpenSpec, или подключить существующий; отвечает ссылкой на репозиторий и кто его видит")],
|
||||
["list_epics / create_epic / update_epic", m("эпики проекта (метки стори) с прогрессом «готово/всего»: завести, переименовать, описать, завершить или убрать в архив; list_goals / create_goal / update_goal — старые имена, работают так же")],
|
||||
["list_tasks", m("доска проекта: Бэклог / В работе / Ревью / Готово, в каждой колонке — по порядку (сверху — важнее); «waits for» — стори ждёт предшественников")],
|
||||
["reorder_task", m("поменять место стори на доске (= приоритет): top / bottom в своей колонке, before / after другой стори; диспетчер берёт из бэклога сверху")],
|
||||
["archive_task", m("убрать стори в архив (пропадает с доски, диспетчера и прогресса эпика, агент останавливается, история остаётся) или вернуть (archived=false)")],
|
||||
["set_dependencies", m("от каких стори зависит стори (blocked_by, список заменяется; [] — убрать все); пока предшественники не в ревью/готово, диспетчер её не берёт; циклы и чужие проекты отклоняются")],
|
||||
["plan_epic / apply_plan", m("планировщик: разбить эпик на стори с критериями готовности и зависимостями (черновик, ничего не создаёт); после правок apply_plan создаёт стори в бэклоге под эпиком")],
|
||||
["get_task", m("карточка стори: описание, эпик, статус, OpenSpec, проверки, вопросы, комментарии PM, зависимости, прогресс")],
|
||||
["create_task / update_task", m("завести стори (в конец Бэклога, с эпиком epic_id и зависимостями blocked_by); поправить название, описание, эпик, зависимости")],
|
||||
["move_task", m("передвинуть карточку; «В работе» запускает агента, «Бэклог»/«Готово» останавливают")],
|
||||
["set_project_visibility", m("сделать репозиторий проекта публичным или приватным (только владелец); отвечает новой видимостью и кто видит репозиторий")],
|
||||
["list_secrets", m("имена секретов проекта (ключи API для агентов); значения не отдаются никогда — заводятся и меняются только в вебе")],
|
||||
["list_members / add_member / remove_member", m("участники проекта: посмотреть, добавить по логину Gitea, убрать или выйти")],
|
||||
["list_inbox / answer_question", m("что ждёт вашего ответа; ответить агенту, принять ревью (accept — мержит PR, только при зелёных проверках)")],
|
||||
["list_releases / deploy", m("что выкачено на staging и в прод, история релизов; выкатить здоровый staging в прод")],
|
||||
["list_incidents / get_incident", m("ошибки из прода (Bugsink): статус, место, релиз, частота, стек")],
|
||||
["decide_incident / resolve_incident", m("решить по ошибке: в бэклог, в работу, игнорировать; отметить исправленной")],
|
||||
["list_errors / get_error", m("ошибки прямо из учёта ошибок: список с фильтрами, карточка со стеком и тегами")],
|
||||
["resolve_error / create_error_task", m("отметить ошибку решённой; завести по ней задачу в бэклоге")],
|
||||
// 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 }> = [
|
||||
{ title: "Создать проект", say: "Создай проект «Платежи», репо payments, ключ PAY", how: "create_project → проект с доской; агенты будут работать в этом репозитории" },
|
||||
{ title: "Завести цель", say: "В PAY заведи цель «Приём оплат картой» — зачем и какой результат", how: "create_goal. Цель — верхнеуровневый результат, под ней собираются задачи" },
|
||||
{ title: "Создать задачу под целью", say: "Под этой целью создай задачу «Форма оплаты» с условиями готовности: …", how: "create_task с goal_id. Пишите контекст и список «Условия готовности» — по ним работает агент" },
|
||||
{ title: "Поправить задачу", say: "Переименуй PAY-3 в … и замени описание на …; перенеси в цель #5", how: "update_task — статус и агент не трогаются, дубликат не нужен" },
|
||||
{ title: "Посмотреть статус", say: "Покажи доску PAY · Что с PAY-3?", how: "list_tasks / get_task" },
|
||||
{ title: "Запустить работу", say: "Двинь PAY-3 в работу", how: "move_task → in_progress: агент пишет proposal, реализует, открывает PR и переводит задачу в Ревью" },
|
||||
{ title: "Ответить агенту", say: "Что ждёт моего ответа? · Ответь на #42: берём Postgres", how: "list_inbox → answer_question. Агенты спрашивают только об архитектурных стопперах" },
|
||||
{ title: "Принять ревью", say: "Прими PAY-3 · Верни PAY-3: добавь тесты", how: "answer_question с accept (→ Готово) или с замечанием (агент доработает)" },
|
||||
{ title: "Остановить", say: "Верни PAY-3 в бэклог", how: "move_task → backlog: агент останавливается, открытые вопросы закрываются" },
|
||||
{ title: "Работать вместе", say: "Добавь в PAY участника dana", how: "add_member (только владелец). Участник видит доску и входящие, двигает карточки, отвечает агентам и получает доступ к репозиторию. Тот, кто ещё не входил в Пеппу, получит приглашение — оно сработает при первом входе" },
|
||||
{ title: "Закрыть цель", say: "Отметь цель #5 достигнутой", how: "update_goal status=done" },
|
||||
{ title: m("Создать проект"), say: m("Создай проект «Платежи», репо payments, ключ PAY"), how: m("create_project → проект с доской; агенты будут работать в этом репозитории") },
|
||||
{ title: m("Завести эпик"), say: m("В PAY заведи эпик «Оплата картой» — зачем и какой результат"), how: m("create_epic. Эпик — метка, которая группирует стори; его описание агент получает вместе со стори") },
|
||||
{ title: m("Создать стори в эпике"), say: m("В этом эпике создай стори «Форма оплаты» с условиями готовности: …"), how: m("create_task с epic_id. Стори — одна бизнесовая история (один OpenSpec change). Пишите контекст и список «Условия готовности» — по ним работает агент") },
|
||||
{ title: m("Поправить стори"), say: m("Переименуй PAY-3 в … и замени описание на …; перенеси в эпик #5"), how: m("update_task — статус и агент не трогаются, дубликат не нужен") },
|
||||
{ title: m("Посмотреть статус"), say: m("Покажи доску PAY · Что с PAY-3?"), how: "list_tasks / get_task" },
|
||||
{ title: m("Запустить работу"), say: m("Двинь PAY-3 в работу"), how: m("move_task → in_progress: агент составляет план, реализует, открывает PR и переводит стори в Ревью") },
|
||||
{ title: m("Ответить агенту"), say: m("Что ждёт моего ответа? · Ответь на #42: берём Postgres"), how: m("list_inbox → answer_question. Агенты спрашивают только об архитектурных стопперах") },
|
||||
{ title: m("Принять ревью"), say: m("Прими PAY-3 · Верни PAY-3: добавь тесты"), how: m("answer_question с accept (→ Готово) или с замечанием (агент доработает)") },
|
||||
{ title: m("Остановить"), say: m("Верни PAY-3 в бэклог"), how: m("move_task → backlog: агент останавливается, открытые вопросы закрываются") },
|
||||
{ title: m("Работать вместе"), say: m("Добавь в PAY участника dana"), how: m("add_member (только владелец). Участник видит доску и входящие, двигает карточки, отвечает агентам и получает доступ к репозиторию. Тот, кто ещё не входил в FORGE, получит приглашение — оно сработает при первом входе") },
|
||||
{ title: m("Автономность"), say: m("Пусть PAY делается сам: бери стори из бэклога и мержи зелёные PR"), how: m("update_project_settings level=auto. «С подсказками» (assisted) — только пуш, когда агенты простаивают. То же — «⋯ Настройки проекта» → «Автономность»") },
|
||||
{ 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: m("Видимость репозитория"), say: m("Сделай репозиторий PAY приватным"), how: m("set_project_visibility (только владелец). Новые проекты публичные по умолчанию; то же — в вебе: «⋯ Настройки проекта» → «Репозиторий»") },
|
||||
{ title: m("Ошибки из прода"), say: m("Какие ошибки ждут решения в PAY? · Ошибку #7 — в работу"), how: m("list_incidents → decide_incident. Подключение — на странице проекта «⋯ Настройки проекта → Баги»") },
|
||||
{ title: m("Политика инцидентов"), say: m("В PAY пусть ошибки разбирает триажёр: падения оплаты — сразу в работу, косметику — в бэклог, остальное спроси"), how: m("set_incident_policy policy=triage, triage_prompt — ваши слова. Не уверен — спросит кнопками в Telegram") },
|
||||
{ title: m("Выкатить в прод"), say: m("Что сейчас на staging в PAY? · Выкати PAY в прод"), how: m("list_releases → deploy. Тот же образ, что прошёл staging; не поднялся — FORGE сама откатит и напишет") },
|
||||
{ title: m("Разбить эпик на стори"), say: m("Спланируй эпик «Оплата картой» в PAY: сначала API, потом экран"), how: m("plan_epic → черновик со стори, критериями готовности и зависимостями; поправьте и подтвердите — apply_plan создаст стори. В вебе — «Спланировать стори эпика» над доской или в «⋯ Настройки проекта → Эпики»") },
|
||||
{ title: m("Приоритет"), say: m("Подними PAY-7 наверх бэклога · Поставь PAY-9 перед PAY-4"), how: m("reorder_task. Порядок в колонке = приоритет: диспетчер (автономность) берёт стори сверху. В вебе — перетащите карточку внутри колонки") },
|
||||
{ title: m("Зависимости"), say: m("PAY-8 делать только после PAY-6"), how: m("set_dependencies (или blocked_by в create_task / update_task). На карточке — «ждёт PAY-6», диспетчер её не возьмёт, пока PAY-6 не в ревью или готово") },
|
||||
{ title: m("Убрать стори"), say: m("PAY-5 больше не нужна"), how: m("archive_task — стори пропадает с доски, история остаётся; вернуть — archived=false или «Вернуть» на странице стори") },
|
||||
{ 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. */
|
||||
async function ProductHelp() {
|
||||
const t = PRODUCT_HELP[await getLocale()] ?? PRODUCT_HELP.ru;
|
||||
const connect = CONNECT_HELP[await getLocale()] ?? CONNECT_HELP.ru;
|
||||
const tr = await getT();
|
||||
return (
|
||||
<Workspace>
|
||||
<div className="max-w-2xl text-sm leading-relaxed">
|
||||
<PageHeader title={t.title}>{t.lead}</PageHeader>
|
||||
<div className="flex flex-col gap-3">
|
||||
{t.sections.map((s, i) => (
|
||||
<section key={s.title} className="flex flex-col gap-2 rounded-lg border bg-card px-4 py-3">
|
||||
<h2 className="m-0 flex items-center gap-2 text-[15px] font-semibold">
|
||||
<span className="flex size-6 shrink-0 items-center justify-center rounded-full bg-primary text-xs text-primary-foreground tabular-nums">{i + 1}</span>
|
||||
{s.title}
|
||||
</h2>
|
||||
<ol className="m-0 flex list-decimal flex-col gap-1 pl-5">
|
||||
{s.steps.map((step) => (
|
||||
<li key={step}>{step}</li>
|
||||
))}
|
||||
</ol>
|
||||
<p className="m-0 text-muted-foreground">{s.note}</p>
|
||||
</section>
|
||||
))}
|
||||
</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.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">
|
||||
{t.more}{" "}
|
||||
<Link href="/settings#mode" className="text-primary">{t.moreLink}</Link>
|
||||
</p>
|
||||
</div>
|
||||
</Workspace>
|
||||
);
|
||||
}
|
||||
|
||||
export default async function Help() {
|
||||
if ((await uiMode()) === "product") return <ProductHelp />;
|
||||
const t = await getT();
|
||||
const mcp = `${await publicOrigin()}/mcp`;
|
||||
return (
|
||||
<section className="narrow help">
|
||||
<h1>Помощь</h1>
|
||||
<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">
|
||||
<PageHeader title={t("Помощь")}>{t("Понятия FORGE, подключение MCP-клиентов и что можно попросить.")}</PageHeader>
|
||||
|
||||
<h2>Как устроена Пеппа</h2>
|
||||
<Section title={t("Как устроена FORGE")}>
|
||||
<ul>
|
||||
<li><b>Проект</b> — репозиторий в Gitea с ключом задач (например, PEP). Создаётся из веба или через MCP.</li>
|
||||
<li><b>Где репозиторий</b> — в выбранном при создании пространстве Gitea: личном (<span className="mono"><ваш логин>/<slug></span>) или организации. По умолчанию он приватный: его видят владелец пространства (в организации — её участники с доступом), <span className="mono">peppa-bot</span> и участники проекта. Ссылка «Открыть в Gitea», видимость и кто видит — в блоке «Репозиторий» на странице проекта.</li>
|
||||
<li><b>Цель</b> — верхнеуровневый результат («Мультипользовательская платформа»). Группирует задачи и даёт агенту контекст «зачем».</li>
|
||||
<li><b>Задача</b> (PEP-12) — один результат с описанием и условиями готовности.</li>
|
||||
<li><b>Доска</b> — Бэклог → В работе → Ревью → Готово. Перенос в «В работе» запускает агента.</li>
|
||||
<li><b>Агент</b> — Claude Code (или Codex) в сессии на машине Пеппы: пишет OpenSpec-proposal, реализует, открывает PR и отдаёт задачу на ревью.</li>
|
||||
<li><b>Участники</b> — владелец проекта добавляет людей по логину Gitea (блок «Участники» на странице проекта). Агенты проекта работают на подписке Claude владельца.</li>
|
||||
<li><b>Раннер</b> — агент, запущенный по задаче в tmux на машине Пеппы. Все раннеры твоих и общих проектов — в разделе <Link href="/runners">Раннеры</Link>: статус, задача, команда <code>tmux attach</code>, сообщение, остановка и resume; фильтры «ждут тебя / работают / остановлены (упали) / завершены».</li>
|
||||
<li><b>Главная</b> — вопросы агентов (только архитектурные стопперы) и «готово к ревью», активные раннеры и проекты. Отвечать можно в вебе, Telegram или через MCP. Список проектов и «Новый проект» — в разделе <Link href="/projects">Проекты</Link>.</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>{rich(t("<b>Где репозиторий</b> — в выбранном при создании пространстве Gitea: личном (<m><ваш логин>/<slug></m>) или организации. По умолчанию он публичный — его видят все, у кого есть доступ к Gitea; приватный видят только владелец пространства (в организации — её участники с доступом), <m>peppa-bot</m> и участники проекта. Ссылка «Открыть в Gitea», видимость, кто видит и кнопка смены видимости (для владельца) — в «⋯ Настройки проекта» → «Репозиторий»."))}</li>
|
||||
<li>{rich(t("<b>Стори</b> (PEP-12) — одна бизнесовая история с описанием и условиями готовности; агент реализует её одним OpenSpec change. «Задачи» — это пункты <m>tasks.md</m> внутри change, не путать."))}</li>
|
||||
<li>{rich(t("<b>Эпик</b> — необязательная метка, которая группирует стори («Оплата картой»): тег на карточке, фильтр над доской, выбор в «+ Стори». Его описание агент получает вместе со стори как контекст «зачем». Заводятся в «⋯ Настройки проекта» или через MCP."))}</li>
|
||||
<li>{rich(t("<b>Доска</b> — Бэклог → В работе → Ревью → Готово. Перенос в «В работе» запускает агента. Порядок в колонке — приоритет: перетащите карточку выше или ниже (или ⇈/⇊ на карточке), диспетчер берёт стори из бэклога сверху. Над доской — фильтр по эпику с прогрессом «готово/всего»; «Готово» сворачивается. Ненужную стори — «В архив» на её странице (история остаётся, вернуть можно там же)."))}</li>
|
||||
<li>{rich(t("<b>Зависимости и планировщик</b> — стори может ждать другие стори («ждёт PAY-2» на карточке, блок «Зависимости» на странице стори): пока предшественник не в ревью или готово, диспетчер её не берёт. «Спланировать стори эпика» — короткая сессия Claude (на подписке пула проекта) предлагает стори эпика с критериями готовности и зависимостями; вы правите черновик и создаёте стори одной кнопкой."))}</li>
|
||||
<li>{rich(t("<b>Клавиатура</b> — <b>⌘K</b> (Ctrl+K) или «Поиск» в меню открывает палитру: проекты, стори, раннеры, вопросы и разделы; Enter — перейти, ⌘Enter — стори из бэклога в работу. Остальные сочетания — <a href=\"/help/shortcuts\">Горячие клавиши</a> (или <b>?</b>)."))}</li>
|
||||
<li>{rich(t("<b>Агент</b> — Claude Code, Codex или OpenCode в сессии на машине FORGE: составляет план стори (OpenSpec), реализует, открывает PR и отдаёт стори на ревью."))}</li>
|
||||
<li>{rich(t("<b>Участники</b> — владелец проекта добавляет людей по логину Gitea (блок «Участники» на странице проекта). Агенты проекта работают на подписках из пула проекта."))}</li>
|
||||
<li>{rich(t("<b>Подписка проекта</b> — на чём работают агенты. В проекте без подписки сверху появляется подсказка: нажмите «Подключить Claude» или «Подключить ChatGPT», откройте ссылку, войдите в свой аккаунт и (для Claude) вставьте код, который он покажет. Терминал не нужен. Готовый токен или ключ OpenAI API — в «⋯ Настройки проекта → Подписки»."))}</li>
|
||||
<li>{rich(t("<b>Стори берутся сами</b> — в новом проекте карточки перетаскивать не нужно: агент сам берёт стори из бэклога по порядку на доске, вам остаётся «Принять» результат. Уровень «Сам берёт» меняется в «⋯ Настройки проекта → Автономность»."))}</li>
|
||||
<li>{rich(t("<b>Telegram</b> — у каждого пользователя свой бот: в «Настройки → Telegram» три шага — создать бота у @BotFather (команда <m>/newbot</m>), вставить его токен, открыть бота и нажать Start. Из него приходят вопросы агентов и «готово к ревью», ему же можно написать новую задачу. Ему же можно наговорить задачу голосовым, если на сервере включено распознавание речи."))}</li>
|
||||
<li>{rich(t("<b>Аналитик</b> — единственный, кто говорит с владельцем: в чате проекта, на Главной и в Telegram. Вопросы агентов-разработчиков идут через него (MCP <code>ask_pm</code>): технический вопрос и повтор до владельца не доходят, вопрос о продукте — один раз, словами Аналитика, с вариантами. Готовые задачи, которых владелец не ждёт, приходят сводкой в конце рабочего дня; застрявшая задача (агент свободен больше часа, проверки зелёные) — суперадмину. На входе Аналитик одним запросом разбирает новую задачу: цель, урезание, разбивка (не больше четырёх частей; остальные ждут приёмки первой), критерии приёмки, решения на развилках — блок «Фабрика решила за вас» на странице задачи с «Подходит» / «Нужно иначе». Вопросов не задаёт и ответа не ждёт. Включается в «⋯ Настройки проекта → Аналитик на входе задачи», в новых проектах включено. Задачи из чата заводятся только кнопкой «Завести задачи». Находки агента приёмки — одним списком в «Предложено»."))}</li>
|
||||
<li>{rich(t("<b>Команда</b> — ИИ-агенты с кличками (Шустрик, Беркут…), одна команда на все проекты: свободный агент берёт стори и ведёт её до конца, его кличка видна на карточке. В разделе «Команда» суперадмин задаёт агенту характер и специализацию — они добавляются к его промпту."))}</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>{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>{rich(t("<b>Новый терминал</b> — раннер без стори: в «Раннерах» или на вкладке «Сессии» проекта выберите проект, имя, агента и напишите промпт (можно голосом — кнопка «Голосом» в браузерах с распознаванием речи). После ходов такой раннер не пингует — им управляете вы в терминале. Получилась работа — «Оформить стори» в карточке раннера: стори создаётся в работе, раннер ведёт её дальше. Раннер можно переименовать."))}</li>
|
||||
<li>{rich(t("<b>Раннеры и стори</b> — «⋯ Настройки проекта → Раннеры» (и на странице стори — для неё одной): «один раннер на стори» (по умолчанию) или «раннер ведёт очередь стори» — стори достаётся свободному раннеру, при лимите раннеров проекта ждёт в его очереди, а «Принять» не останавливает раннер, а даёт ему следующую стори; переход — «свежий контекст» (тот же терминал, новый разговор) или «один разговор». «Свой git worktree на раннер» — у каждого раннера своя копия и ветка <code>task/…</code>, параллельные стори не мешают друг другу; копия убирается, когда всё запушено. В карточке раннера — история его стори и очередь."))}</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>{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>
|
||||
</Section>
|
||||
|
||||
<h2>Подключить MCP</h2>
|
||||
<p>Адрес сервера:</p>
|
||||
<code className="mcp-url">{mcp}</code>
|
||||
<Section title={t("Подключить MCP")}>
|
||||
<LiveRefresh scope="features" indicator={false} />
|
||||
<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>
|
||||
<li><b>ChatGPT</b>: Settings → Apps & Connectors → Advanced → включить Developer mode → Create: URL выше, авторизация OAuth. Откроется Пеппа — войдите через Gitea и нажмите «Разрешить». В чате включите коннектор Peppa.</li>
|
||||
<li><b>Codex, Claude и другие MCP-клиенты</b>: добавьте удалённый MCP-сервер по этому URL с OAuth — клиент зарегистрируется сам, вход и согласие на экране Пеппы.</li>
|
||||
<li>Если клиент не видит новых инструментов — обновите или переподключите коннектор. Доступ отзывается в <Link href="/settings">Настройках</Link>.</li>
|
||||
<li>Чтобы агенты работали на вашей подписке, подключите Claude в <Link href="/settings">Настройках</Link>.</li>
|
||||
<li>{rich(t("<b>ChatGPT</b>: Settings → Apps & Connectors → Advanced → включить Developer mode → Create: URL выше, авторизация OAuth. Откроется FORGE — войдите через eGov и нажмите «Разрешить». В чате включите коннектор FORGE."))}</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>{rich(t("<b>Codex, Claude и другие MCP-клиенты</b>: добавьте удалённый MCP-сервер по этому URL с OAuth — клиент зарегистрируется сам, вход и согласие на экране FORGE."))}</li>
|
||||
<li>{rich(t("Если клиент не видит новых инструментов — обновите или переподключите коннектор. Доступ отзывается в <a href=\"/settings\">Настройках</a>."))}</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>{rich(t("<b>Память проекта</b> — <code>.peppa/memory.md</code> в репозитории: команды, соглашения, грабли и решения, которые агенты записывают в конце стори (MCP <code>remember</code>). Раннер подкладывает её вместе со сводкой последних завершённых стори в каждый запуск агента; размер ограничен — разросшуюся память агент ужимает сам. Посмотреть — вкладка проекта «Спеки»."))}</li>
|
||||
<li>{rich(t("<b>Первый запуск</b> — на Главной чек-лист: подписка агента (суперадмину), Telegram, eGov (необязательно), проект, первая стори, стори в работе. Исчезает, когда всё сделано, или по «Скрыть». Если у пула проекта нет ни одной рабочей подписки, на странице проекта — предупреждение «Агенты не запустятся»."))}</li>
|
||||
<li>{rich(t("<b>Подписки</b> — аккаунты Claude Code, Codex и OpenCode, на которых работают агенты, и пулы для ротации ведёт суперадмин в разделе «Подписки». У проекта — пул по умолчанию («⋯ Настройки проекта»): раннер стартует на первой свободной активной подписке пула, а в «Раннерах» видно, на какой. Упёрся в лимит — после конца хода раннер сам переходит на свободную подписку того же агента в пуле (Claude — продолжая тот же разговор, Codex — заново, с контекстом из стори) и пишет в Telegram «переключил на подписку…»; подписки того же агента нет, а есть другая (Claude ↔ ChatGPT) — переезжает на неё и начинает заново с контекстом из стори («переехал…»; выключается <code>PEPPA_ROTATE_CROSS=off</code>); свободных нет — ждёт сброса и продолжает сам."))}</li>
|
||||
<li>{rich(t("<b>Несколько своих подписок</b> — «⋯ Настройки проекта → Подписки»: у каждой подписки пула видно «в работе: N агентов», «свободна», «лимит до 15:40» и сколько использовано окна лимита. «Добавить ещё Claude» / «Добавить ещё ChatGPT» — тот же вход по ссылке; «Убрать» — своя подписка, на которой сейчас никто не работает. Когда в пуле остаётся одна рабочая подписка и она использована больше чем на 85%, участникам приходит одно предупреждение «осталась одна подписка, скоро лимит»."))}</li>
|
||||
<li>{rich(t("<b>Запасная подписка от суперадмина</b> — «Подписки → Картина по пулам»: все пулы с состоянием подписок, раннерами, ждущими сброса, и пометкой «запасной нет». «Одолжить подписку» добавляет подписку в чужой пул на 1–168 часов; по сроку она возвращается сама (агенты на ней дорабатывают текущий запуск), «Вернуть сейчас» — раньше."))}</li>
|
||||
</ul>
|
||||
</Section>
|
||||
|
||||
<h2>Сценарии</h2>
|
||||
<Section title={t("Сценарии")}>
|
||||
{CASES.map((c) => (
|
||||
<article key={c.title} className="card">
|
||||
<b>{c.title}</b>
|
||||
<p className="say">«{c.say}»</p>
|
||||
<p className="muted">{c.how}</p>
|
||||
<article key={c.title} className="flex flex-col gap-1 rounded-lg border bg-card px-4 py-3">
|
||||
<b>{t(c.title)}</b>
|
||||
<p className="m-0 italic">{t("«{say}»", { say: t(c.say) })}</p>
|
||||
<p className="m-0 text-muted-foreground">{t(c.how)}</p>
|
||||
</article>
|
||||
))}
|
||||
</Section>
|
||||
|
||||
<h2>Инструменты MCP</h2>
|
||||
<table className="tools">
|
||||
<Section title={t("Инструменты MCP")}>
|
||||
<div className="overflow-x-auto rounded-lg border">
|
||||
<table className="w-full border-collapse">
|
||||
<tbody>
|
||||
{TOOLS.map(([name, what]) => (
|
||||
<tr key={name}>
|
||||
<td className="mono">{name}</td>
|
||||
<td>{what}</td>
|
||||
<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">{t(what)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</Section>
|
||||
|
||||
<h2>Telegram</h2>
|
||||
<p className="muted">
|
||||
Привяжите свой Telegram в Настройках: бот присылает вопросы агентов из ваших и общих проектов и «готово к ревью» с
|
||||
кнопками; ответ реплаем уходит прямо в сессию агента.
|
||||
<Section title={t("Автономность")}>
|
||||
<p className="m-0 text-muted-foreground">
|
||||
{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."))}
|
||||
</p>
|
||||
</section>
|
||||
<p className="m-0 mt-2 text-muted-foreground">
|
||||
{rich(t("<b>Пауза проекта</b>: «Поставить на паузу» на странице проекта или в «⋯ Настройки проекта → Пауза» останавливает агентов проекта (сделанное сохраняется), новые не запускаются, продакт, аналитик и ревьюер не работают, уведомлений нет — ни в Telegram, ни в браузере, вопросы проекта не показываются в «Ждут вашего ответа». «Продолжить» возвращает остановленных агентов к их задачам; то, что пришло во время паузы, задним числом не рассылается."))}
|
||||
</p>
|
||||
</Section>
|
||||
|
||||
<Section title={t("Расход, бюджеты, метрики, журнал")}>
|
||||
<p className="m-0 text-muted-foreground">
|
||||
{rich(t("<b>Лимиты</b>: полоса над каждой страницей показывает самое загруженное окно лимитов подписки (5 ч и 7 дней) и время сброса — Claude Code сам сообщает их строке статуса раннера. Пока ни один раннер не сообщал — «нет данных о лимитах»; Codex и OpenCode расход не сообщают. На карточке раннера — токены, стоимость и заполненность контекста; «≈» — стоимость оценена по прайсу API, а не сообщена агентом. <b>Бюджет</b>: «⋯ Настройки проекта» → «Бюджет стори» (по умолчанию для всех стори) или карточка стори (свой бюджет) — минуты раннеров, токены, перезапуски, стоимость; по умолчанию без предела. Превышение прерывает ход агента (разговор сохраняется) и присылает вопрос «Продлить ×2 / Снять лимит / Остановить»; пока вы не ответили, стори не запускается. <b>Метрики</b>: вкладка «Метрики» проекта — время цикла, доля принятых с первого раза, возвраты с ревью, вопросы, часы раннеров, сколько агенты ждали вас, расход по неделям, агентам и эпикам. <b>Журнал</b>: вкладка «Журнал» проекта и раздел «Журнал» суперадмина — кто что сделал: человек (веб, Telegram, MCP-клиент, CLI), агент или FORGE."))}
|
||||
</p>
|
||||
</Section>
|
||||
|
||||
<Section title={t("Секреты")}>
|
||||
<p className="m-0 text-muted-foreground">
|
||||
{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>
|
||||
<p className="m-0 mt-2 text-muted-foreground">
|
||||
{/* glossary-ignore: справочник режима «Инженер», имя команды CLI */}
|
||||
{rich(t("<b>Кому идёт секрет (PEP-253)</b>: у каждого секрета пометка «только продукту» (по умолчанию для новых) или «агенту и продукту». Настройка проекта «Агенты получают секреты в окружение» у новых проектов выключена: агенты не получают ни одного секрета, продукт — все. Ключ сервиса из каталога (Stripe, OpenAI, GitHub, Telegram…) FORGE узнаёт по имени и формату значения и предлагает «Сделать подключением»: создаётся подключение с этим ключом и разрешение проекту на чтение и запись, секрет остаётся только продукту — агент работает с сервисом через <code>call_connection</code>, не видя ключа. Отчёт по всем проектам — раздел «Секреты» и <code>peppa secrets agent-report [--notify]</code>."))}
|
||||
</p>
|
||||
</Section>
|
||||
|
||||
<Section title="CI/CD">
|
||||
<p className="m-0 text-muted-foreground">
|
||||
{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>), сам не мержится никогда."))}
|
||||
</p>
|
||||
<p className="m-0 text-muted-foreground">
|
||||
{t("Агент-ревьюер (по умолчанию выключен; «⋯ Настройки проекта → Ревьюер»): когда проверки PR зелёные и агент отдаёт стори в ревью, короткая сессия Claude (sonnet, на подписке пула проекта) читает дифф по чек-листу — сделано ли то, что просила стори, баги, безопасность, тесты, мусор — и ваши дополнительные правила. Замечания уходят агенту, стори остаётся «В работе»; «ок» — стори приходит вам с резюме ревьюера. После лимита возвратов (по умолчанию 2) стори приходит с незакрытыми замечаниями; если ревьюер упал — с пометкой. Последнее ревью видно в карточке стори.")}
|
||||
</p>
|
||||
<p className="m-0 text-muted-foreground">
|
||||
{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 минут; не прошла — откат на предыдущий образ и сообщение вам. Релизы — на странице проекта."))}
|
||||
</p>
|
||||
<p className="m-0 text-muted-foreground">
|
||||
{/* glossary-ignore: справочник вида «Инженер» */}
|
||||
{rich(t("Продукт по ссылке с первого дня: новый проект создаётся с заглушкой «Продукт создаётся» (<m>Dockerfile</m>, <m>product/</m>, готовый <m>deploy</m>) и сразу выкладывается на <m>slug-staging.telecom.quest</m>. Нет здоровой версии для проверки при принятых стори или выкладка упала — FORGE сама заводит стори «Продукт должен открываться по ссылке» первой в бэклоге (одна открытая на проект, не чаще раза в сутки). «⋯ Настройки проекта → Показывать всем»: «Сам» — здоровый staging, все стори которого приняты, выкатывается в прод без кнопки; «По кнопке» — как раньше."))}
|
||||
</p>
|
||||
<p>
|
||||
{rich(t("Превью на ревью: «готово к ревью» и карточка стори (блок «Превью») показывают «Посмотреть» — стенд PR, ссылку на дифф и итог проверок. Шаг деплоя превью снимает скриншоты страниц из <m>deploy.screenshots</m> (по умолчанию главная, <m>[]</m> — выключить) — они в карточке стори."))}
|
||||
</p>
|
||||
<p className="m-0 text-muted-foreground">
|
||||
{rich(t("Gitea знает о FORGE: issue, открытый вами или участником проекта, становится стори в бэклоге (в issue появится ссылка; стори готова — issue закроется), старые открытые issues переносит <m>peppa project import-issues KEY</m>. Комментарий или ревью «нужны изменения» в PR стори уходит её агенту (стори из «Ревью» вернётся в работу), а мерж PR руками в Gitea переводит стори в «Готово»."))}
|
||||
</p>
|
||||
<p className="m-0 text-muted-foreground">
|
||||
{rich(t("Сама FORGE (проект PEP) выкатывается так же по кнопке, но без staging: после зелёных проверок <m>main</m> приходит предложение «Выкатить в прод»; релиз собирается на хосте рядом с работающим, перед миграциями делается копия базы, после перезапуска — проверка здоровья, не прошла — возврат предыдущего релиза."))}
|
||||
</p>
|
||||
</Section>
|
||||
|
||||
<Section title={t("Чаты")}>
|
||||
<p className="m-0 text-muted-foreground">
|
||||
{rich(t("<a href=\"/chats\">Чаты</a> — у каждого проекта свой чат с тредами: тред на стори (вопросы агента, статусы, прогресс, комментарии, сбои раннера), на ошибку из прода и на релиз. Ответ в треде стори уходит агенту: на открытый вопрос, а без вопроса — комментарием, который агент сразу видит. Мастер-чат — всё важное по вашим проектам (вопросы, ревью, сбои, лимиты, релизы, ошибки), мониторинг и сводка; команды /status, /task KEY-N, /move KEY-N in_progress, /help. Вопросы по-прежнему видны и на Главной. Переписка хранится 14 дней."))}
|
||||
</p>
|
||||
<p className="m-0 text-muted-foreground">
|
||||
{rich(t("Любой чат можно связать с группой Telegram через вашего собственного бота (подключается в Настройках → Telegram): «Связать с Telegram» в чате → добавьте своего бота в группу по ссылке (или отправьте в группе <m>/link код</m>). Сообщения чата придут в группу от вашего бота, тред — цепочкой ответов; ответ реплаем вернётся в тред и уйдёт агенту. Отвечать из группы могут те, кто привязал свой Telegram в Настройках и имеет доступ к проекту (в мастер-группе — только владелец). Отключите или замените бота — группа отвяжется."))}
|
||||
</p>
|
||||
</Section>
|
||||
|
||||
<Section title="Telegram">
|
||||
<p className="m-0 text-muted-foreground">
|
||||
{t("Привяжите свой Telegram в Настройках: бот присылает вопросы агентов из ваших и общих проектов и «готово к ревью» с кнопками; ответ реплаем уходит прямо в сессию агента. Новые ошибки из прода приходят туда же — по политике проекта: сообщением, стори или с кнопками «В бэклог / В работу / Игнорировать». Команды бота: /status — что сейчас происходит, /digest — сводка за сутки.")}
|
||||
</p>
|
||||
<p className="m-0 text-muted-foreground">
|
||||
{t("Новую стори можно просто написать или наговорить боту: «в PAY: экспорт в CSV». Бот уточнит проект (если не указан) и эпик кнопками, создаст стори и предложит «Взять в работу».")}{" "}
|
||||
{voiceStoriesEnabled()
|
||||
? t("Голосовое бот сначала расшифрует и покажет текст («Расслышал: …»); проект можно назвать голосом: «в проекте Pay …».")
|
||||
: t("Голосовые пока не настроены на сервере — пишите текстом.")}
|
||||
</p>
|
||||
</Section>
|
||||
|
||||
<Section title={t("Обращения")}>
|
||||
<p className="m-0 text-muted-foreground">
|
||||
{t("Кнопка «Сообщить о проблеме» внизу любой страницы — для проблем в самой FORGE: текст и до 5 скриншотов (файл, перетаскивание, вставка из буфера); страница, вид, язык, браузер и последние ошибки браузера прикладываются сами. В Telegram — /problem, затем текст, фото с подписью или голосовое. Обращение разбирает агент обратной связи; суперадмин получает разбор с вариантами исправления и решает: завести задачу, связать с существующей или не исправлять. Автор видит статус в разделе «Обращения» и получает сообщение, когда задача принята.")}
|
||||
</p>
|
||||
</Section>
|
||||
|
||||
<Section title={t("Уведомления")}>
|
||||
<p className="m-0 text-muted-foreground">
|
||||
{rich(t("В <a href=\"/settings#notifications\">Настройках → Уведомления</a> для каждого события (вопросы агентов, готово к ревью, сбои и лимиты, релизы, ошибки из прода, дайджест) выбирается, куда присылать: Telegram и/или браузер. Тихие часы: Telegram приходит без звука, push не показываются. Снятые проекты не присылают ничего — вопросы остаются в вебе. Push в браузере включаются там же кнопкой (Chrome спросит разрешение) и работают при закрытой вкладке; клик открывает стори. Во вкладке FORGE в заголовке и на значке приложения — сколько ждёт вас, при новом вопросе звучит сигнал (если звук включён). Ежедневный дайджест приходит в выбранное время (по умолчанию 09:00): сделано за сутки, в работе, на ревью, ждёт вас, зависло, лимиты; пустой не приходит."))}
|
||||
</p>
|
||||
<p className="m-0 text-muted-foreground">
|
||||
{t("Новости самой FORGE — новые версии, падения и перезапуски сервисов, «Дайджест обновлений FORGE» (что нового и что происходит сейчас) — идут в Telegram-канал платформы, который настраивает суперадмин в разделе «Платформа». Если он включил рассылку в личные чаты, дайджест обновлений приходит и вам; отключить — строка «Дайджест обновлений FORGE» в Настройках → Уведомления.")}
|
||||
</p>
|
||||
</Section>
|
||||
</div>
|
||||
</Workspace>
|
||||
);
|
||||
}
|
||||
|
||||
28
apps/web/app/(app)/help/shortcuts/page.tsx
Normal file
28
apps/web/app/(app)/help/shortcuts/page.tsx
Normal file
@ -0,0 +1,28 @@
|
||||
import Link from "next/link";
|
||||
import { ShortcutsList } from "@/components/CommandPalette";
|
||||
import { PageHeader, Section } from "@/components/common";
|
||||
import { Workspace } from "@/components/Workspace";
|
||||
import { PALETTE_KEYS } from "@/lib/shortcuts";
|
||||
import { getT } from "@/lib/i18n";
|
||||
|
||||
/** PEP-52: list of keyboard shortcuts (the same list as the «?» dialog). */
|
||||
export default async function Shortcuts() {
|
||||
const t = await getT();
|
||||
return (
|
||||
<Workspace>
|
||||
<div className="max-w-3xl text-sm">
|
||||
<PageHeader crumbs={<Link href="/help" className="text-muted-foreground hover:text-foreground">{t("Помощь")}</Link>} title={t("Горячие клавиши")}>
|
||||
{t("Клавиши без ⌘/Ctrl работают, когда курсор не в поле ввода.")}
|
||||
</PageHeader>
|
||||
<Section title={t("Сочетания")}>
|
||||
<div className="rounded-lg border bg-card px-4 py-2">
|
||||
<ShortcutsList />
|
||||
</div>
|
||||
</Section>
|
||||
<Section title={t("В палитре")}>
|
||||
<p className="m-0 text-muted-foreground">{t(PALETTE_KEYS)}. {t("Поиск — по ключу, названию и проекту; все слова запроса должны совпасть.")}</p>
|
||||
</Section>
|
||||
</div>
|
||||
</Workspace>
|
||||
);
|
||||
}
|
||||
75
apps/web/app/(app)/hosts/actions.ts
Normal file
75
apps/web/app/(app)/hosts/actions.ts
Normal file
@ -0,0 +1,75 @@
|
||||
"use server";
|
||||
// «Хосты» (PEP-40): every action is superadmin-only (others get "not found").
|
||||
|
||||
import { createHost, deleteHost, getHost, PeppaError, requireSuperadmin, setHostDisabled, updateHost } from "@peppa/core";
|
||||
import { checkHost, ensureSshKey } 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();
|
||||
const BASE = "/hosts";
|
||||
|
||||
async function attempt(f: FormData, fn: () => Promise<string | void>): Promise<never> {
|
||||
const user = asWebActor(await requireUser());
|
||||
let target = BASE;
|
||||
try {
|
||||
await requireSuperadmin(db, user);
|
||||
target = (await fn()) || target;
|
||||
} catch (e) {
|
||||
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))}`;
|
||||
}
|
||||
revalidatePath("/", "layout");
|
||||
redirect(target);
|
||||
}
|
||||
|
||||
const fields = (f: FormData) => ({
|
||||
sshTarget: str(f, "sshTarget"),
|
||||
sshPort: str(f, "sshPort") ? Number(str(f, "sshPort")) : undefined,
|
||||
workdir: str(f, "workdir") || undefined,
|
||||
peppaUrl: str(f, "peppaUrl") || null,
|
||||
});
|
||||
|
||||
export async function addHostAction(f: FormData) {
|
||||
await attempt(f, async () => {
|
||||
await ensureSshKey();
|
||||
const h = await createHost(db, { name: str(f, "name"), ...fields(f) });
|
||||
await checkHost(db, h);
|
||||
return `${BASE}#h-${h.id}`;
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateHostAction(f: FormData) {
|
||||
await attempt(f, async () => {
|
||||
const id = Number(str(f, "id"));
|
||||
const h = await updateHost(db, id, fields(f));
|
||||
await checkHost(db, h);
|
||||
return `${BASE}#h-${id}`;
|
||||
});
|
||||
}
|
||||
|
||||
export async function checkHostAction(f: FormData) {
|
||||
await attempt(f, async () => {
|
||||
const id = Number(str(f, "id"));
|
||||
await checkHost(db, await getHost(db, id));
|
||||
return `${BASE}#h-${id}`;
|
||||
});
|
||||
}
|
||||
|
||||
export async function toggleHostAction(f: FormData) {
|
||||
await attempt(f, async () => {
|
||||
const id = Number(str(f, "id"));
|
||||
await setHostDisabled(db, id, str(f, "disable") === "1");
|
||||
return `${BASE}#h-${id}`;
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteHostAction(f: FormData) {
|
||||
await attempt(f, async () => {
|
||||
await deleteHost(db, Number(str(f, "id")));
|
||||
});
|
||||
}
|
||||
139
apps/web/app/(app)/hosts/page.tsx
Normal file
139
apps/web/app/(app)/hosts/page.tsx
Normal file
@ -0,0 +1,139 @@
|
||||
import { notFound } from "next/navigation";
|
||||
import { Plus, RefreshCw, Server, Trash2 } from "lucide-react";
|
||||
import { HOST_STATUS_RU, isSuperadmin, listHosts, type RunnerHostView } from "@peppa/core";
|
||||
import { ensureSshKey, runnerImage } from "@peppa/runner";
|
||||
import { Hidden } from "@/components/cards";
|
||||
import { ago, Disclosure, Empty, Flash, 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, Label } 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 type { Translator } from "@peppa/shared/i18n";
|
||||
import { addHostAction, checkHostAction, deleteHostAction, toggleHostAction, updateHostAction } from "./actions";
|
||||
|
||||
export async function generateMetadata() {
|
||||
const t = await getT();
|
||||
return { title: t("Хосты — FORGE") };
|
||||
}
|
||||
|
||||
function StatusOf({ h, t }: { h: RunnerHostView; t: Translator }) {
|
||||
if (h.disabledAt) return <Badge variant="secondary">{t("отключён")}</Badge>;
|
||||
return <Badge variant={h.status === "online" ? "ok" : h.status === "offline" ? "danger" : "info"}>{t(HOST_STATUS_RU[h.status])}</Badge>;
|
||||
}
|
||||
|
||||
function HostFields({ h, t }: { h?: RunnerHostView; t: Translator }) {
|
||||
return (
|
||||
<div className="grid gap-2 sm:grid-cols-2">
|
||||
<Label>
|
||||
{t("SSH-адрес")}
|
||||
<Input name="sshTarget" required placeholder="peppa@build1.example.com" defaultValue={h?.sshTarget} className="h-8 font-mono" />
|
||||
</Label>
|
||||
<Label>
|
||||
{t("Порт SSH")}
|
||||
<Input name="sshPort" type="number" min={1} max={65535} placeholder="22" defaultValue={h?.sshPort} className="h-8" />
|
||||
</Label>
|
||||
<Label>
|
||||
{t("Каталог на хосте (от домашнего)")}
|
||||
<Input name="workdir" placeholder="peppa" defaultValue={h?.workdir} className="h-8 font-mono" />
|
||||
</Label>
|
||||
<Label>
|
||||
{t("Адрес FORGE для хоста (релей агента)")}
|
||||
<Input name="peppaUrl" placeholder={t("как PEPPA_WEB_URL")} defaultValue={h?.peppaUrl ?? ""} className="h-8 font-mono" />
|
||||
</Label>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function HostCard({ h, t }: { h: RunnerHostView; t: Translator }) {
|
||||
const i = h.info ?? {};
|
||||
return (
|
||||
<Card id={`h-${h.id}`} className="gap-2">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className="font-semibold">{h.name}</span>
|
||||
<span className="font-mono text-xs text-muted-foreground">{h.sshTarget}{h.sshPort !== 22 ? `:${h.sshPort}` : ""}</span>
|
||||
<StatusOf h={h} t={t} />
|
||||
<span className="ml-auto text-xs text-muted-foreground">{t("раннеров: {n}", { n: h.runners })}</span>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-x-4 gap-y-1 text-xs text-muted-foreground">
|
||||
{i.load != null && <span>{t("загрузка {load}", { load: i.load })}{i.cpus ? ` / ${i.cpus} CPU` : ""}</span>}
|
||||
{i.docker && <span>docker {i.docker}</span>}
|
||||
{i.tmux && <span>{i.tmux}</span>}
|
||||
{i.os && <span>{i.os}</span>}
|
||||
<span>{t("образ раннера:")} {i.image ? <span className="font-mono">{i.image}</span> : t("не загружен")}</span>
|
||||
<span>{t("проверен {ago}", { ago: ago(h.lastSeenAt, t) })}</span>
|
||||
</div>
|
||||
{h.lastError && <p className="m-0 text-xs text-destructive">{h.lastError}</p>}
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<form action={checkHostAction}>
|
||||
<Hidden fields={{ id: h.id }} />
|
||||
<Button size="sm" variant="outline"><RefreshCw />{t("Проверить")}</Button>
|
||||
</form>
|
||||
<form action={toggleHostAction}>
|
||||
<Hidden fields={{ id: h.id, disable: h.disabledAt ? "0" : "1" }} />
|
||||
<Button size="sm" variant="outline">{h.disabledAt ? t("Включить") : t("Отключить")}</Button>
|
||||
</form>
|
||||
<form action={deleteHostAction}>
|
||||
<Hidden fields={{ id: h.id }} />
|
||||
<Button size="sm" variant="ghost" disabled={h.runners > 0} title={h.runners > 0 ? t("На хосте работают раннеры") : undefined}><Trash2 />{t("Удалить")}</Button>
|
||||
</form>
|
||||
</div>
|
||||
<Disclosure summary={t("Изменить")}>
|
||||
<form action={updateHostAction} className="flex flex-col gap-2">
|
||||
<Hidden fields={{ id: h.id }} />
|
||||
<HostFields h={h} t={t} />
|
||||
<Button size="sm" variant="default" className="self-start">{t("Сохранить и проверить")}</Button>
|
||||
</form>
|
||||
</Disclosure>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
export default async function Hosts({ searchParams }: { searchParams: Promise<{ error?: string }> }) {
|
||||
const user = await requireUser();
|
||||
const t = await getT();
|
||||
if (!(await isSuperadmin(db, user))) notFound();
|
||||
const { error } = await searchParams;
|
||||
const [hosts, pub] = await Promise.all([listHosts(db), ensureSshKey().catch((e: Error) => t("(ключ не создан: {message})", { message: e.message }))]);
|
||||
return (
|
||||
<Workspace>
|
||||
<div className="max-w-3xl">
|
||||
<Flash error={error} />
|
||||
<PageHeader title={<><Server className="mr-1 inline size-5 text-primary" />{t("Хосты")}</>}>
|
||||
{t("Серверы, на которых работают раннеры. FORGE заходит на хост по SSH своим ключом и запускает там tmux с агентом в контейнере образа раннера; агент ходит в FORGE только через релей. Демона на хосте нет — нужны sshd, tmux и docker. Проект выбирает хосты в «⋯ Настройки проекта → Раннеры». Раздел видят только суперадмины.")}
|
||||
</PageHeader>
|
||||
|
||||
<Section title={t("Хосты")} count={hosts.length}>
|
||||
{hosts.length === 0 ? <Empty>{t("Хостов нет — раннеры работают на Mac FORGE.")}</Empty> : hosts.map((h) => <HostCard key={h.id} h={h} t={t} />)}
|
||||
<Disclosure summary={<span className="flex items-center gap-1.5"><Plus className="size-4" />{t("Подключить хост")}</span>}>
|
||||
<form action={addHostAction} className="flex flex-col gap-2">
|
||||
<Label>
|
||||
{t("Имя")}
|
||||
<Input name="name" required placeholder="build1" className="h-8" />
|
||||
</Label>
|
||||
<HostFields t={t} />
|
||||
<Button size="sm" variant="default" className="self-start">{t("Подключить и проверить")}</Button>
|
||||
</form>
|
||||
</Disclosure>
|
||||
</Section>
|
||||
|
||||
<Section title={t("Как подготовить хост")}>
|
||||
<ol className="m-0 flex list-decimal flex-col gap-2 pl-5 text-sm">
|
||||
<li>
|
||||
{t("Добавьте ключ FORGE в {file} пользователя на хосте:").split("{file}").flatMap((part, i) => (i ? [<code key={i}>~/.ssh/authorized_keys</code>, part] : [part]))}
|
||||
<pre className="mt-1 overflow-x-auto rounded-md bg-muted p-2 text-xs"><code>{pub}</code></pre>
|
||||
</li>
|
||||
<li>{t("Установите tmux и docker; пользователь должен иметь доступ к docker.")}</li>
|
||||
<li>
|
||||
{t("Загрузите образ раннера")} <code>{runnerImage()}</code>: <code>{t("scripts/runner-image.sh --push <имя хоста>")}</code> ({t("или")} <code>{t("peppa host push-image <имя>")}</code>).
|
||||
</li>
|
||||
<li>{t("Адрес FORGE для хоста должен открываться с хоста (по умолчанию — адрес веба); через него идут хуки, MCP и git агента.")}</li>
|
||||
</ol>
|
||||
</Section>
|
||||
</div>
|
||||
</Workspace>
|
||||
);
|
||||
}
|
||||
37
apps/web/app/(app)/journal/page.tsx
Normal file
37
apps/web/app/(app)/journal/page.tsx
Normal file
@ -0,0 +1,37 @@
|
||||
import { notFound } from "next/navigation";
|
||||
import { getProject, isSuperadmin, JOURNAL_NOISE, listJournal, listProjects, type ActorChannel, type ActorKind } from "@peppa/core";
|
||||
import { JournalFilters, JournalList } from "@/components/Accounting";
|
||||
import { PageHeader } from "@/components/common";
|
||||
import { Workspace } from "@/components/Workspace";
|
||||
import { requireUser } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { getT } from "@/lib/i18n";
|
||||
|
||||
/** Superadmin only (PEP-48): who did what — people (web, Telegram, MCP clients, CLI), agents, Peppa. */
|
||||
export default async function Journal({ searchParams }: { searchParams: Promise<{ project?: string; actor?: string; channel?: string; all?: string }> }) {
|
||||
const me = await requireUser();
|
||||
if (!(await isSuperadmin(db, me))) notFound();
|
||||
const t = await getT();
|
||||
const { project, actor, channel, all } = await searchParams;
|
||||
const projects = await listProjects(db);
|
||||
const p = project ? await getProject(db, project).catch(() => null) : null;
|
||||
const entries = await listJournal(db, {
|
||||
projectId: p?.id ?? (project ? -1 : undefined),
|
||||
actorKind: (actor || undefined) as ActorKind | undefined,
|
||||
channel: (channel || undefined) as ActorChannel | undefined,
|
||||
excludeTypes: all ? undefined : JOURNAL_NOISE,
|
||||
limit: 300,
|
||||
});
|
||||
return (
|
||||
<Workspace aside={null}>
|
||||
<PageHeader title={t("Журнал действий")}>
|
||||
{t("Кто что сделал: люди (веб, Telegram, MCP-клиенты, CLI, терминал), агенты и сама FORGE. Новые сверху, последние 300.")}
|
||||
{!all && " " + t("Служебные события хуков скрыты.")}
|
||||
</PageHeader>
|
||||
<div className="mb-4">
|
||||
<JournalFilters action="/journal" projects={projects.map((x) => ({ key: x.key, name: x.name }))} value={{ project, actor, channel }} />
|
||||
</div>
|
||||
<JournalList entries={entries} />
|
||||
</Workspace>
|
||||
);
|
||||
}
|
||||
@ -1,29 +1,49 @@
|
||||
import Link from "next/link";
|
||||
import type { ReactNode } from "react";
|
||||
import { requireUser } from "@/lib/auth";
|
||||
import { Footer } from "@/components/Footer";
|
||||
import { Nav, SettingsLink } from "@/components/Nav";
|
||||
import { accountUsageForUser, agentsLine, getNotifyPrefs, isSuperadmin, pendingFeedbackCount } from "@peppa/core";
|
||||
import { db } from "@/lib/db";
|
||||
import { subscriptionRequestOffers } from "@peppa/runner";
|
||||
import { requireUser, uiMode } from "@/lib/auth";
|
||||
import { navCounts } from "@/lib/queries";
|
||||
import { WordsProvider } from "@/components/Words";
|
||||
import { Sidebar } from "@/components/Sidebar";
|
||||
import { AttentionBadge } from "@/components/AttentionBadge";
|
||||
import { CommandPalette } from "@/components/CommandPalette";
|
||||
import { AgentsStrip, UsageStrip } from "@/components/Accounting";
|
||||
import { VersionWatch } from "@/components/VersionWatch";
|
||||
import { bootId } from "@/lib/boot";
|
||||
import { FeedbackButton } from "@/components/FeedbackButton";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** Console layout (PEP-38): navigation on the left, each page renders centre + right panel via <Workspace>. */
|
||||
export default async function AppLayout({ children }: { children: ReactNode }) {
|
||||
const user = await requireUser();
|
||||
// PEP-216: independent reads together, not one after another on every page.
|
||||
const [counts, { sound }, superadmin, mode] = await Promise.all([navCounts(user.id), getNotifyPrefs(db, user.id), isSuperadmin(db, user), uiMode()]);
|
||||
const engineer = mode === "engineer";
|
||||
// PEP-5: subscription limit windows over every page — for «Инженер»; PEP-121: «Продакт»
|
||||
// reads one line: agents work, or when they go on.
|
||||
const [accounts, line, feedback] = await Promise.all([
|
||||
engineer ? accountUsageForUser(db, user).catch(() => []) : [],
|
||||
engineer ? null : agentsLine(db, user).catch(() => ({ state: "working" as const })),
|
||||
superadmin ? pendingFeedbackCount(db) : 0,
|
||||
]);
|
||||
// PEP-186: agents stand — the owner may ask the superadmin for a subscription right from the strip.
|
||||
const offers = line?.state === "paused" ? await subscriptionRequestOffers(db, user).catch(() => []) : [];
|
||||
return (
|
||||
<>
|
||||
<header className="top">
|
||||
<Link href="/" className="brand">🐷 Peppa</Link>
|
||||
<Nav />
|
||||
<div className="me">
|
||||
<SettingsLink />
|
||||
{user.avatarUrl && <img src={user.avatarUrl} alt="" width={24} height={24} />}
|
||||
<span>{user.login}</span>
|
||||
<form action="/logout" method="post">
|
||||
<button className="link">Выйти</button>
|
||||
</form>
|
||||
</div>
|
||||
</header>
|
||||
<main>{children}</main>
|
||||
<Footer />
|
||||
</>
|
||||
<WordsProvider mode={mode}>
|
||||
<div className="min-h-dvh md:grid md:grid-cols-[232px_minmax(0,1fr)]">
|
||||
<AttentionBadge count={counts.questions + counts.waitingRunners} sound={sound} />
|
||||
<Sidebar login={user.login} avatarUrl={user.avatarUrl} counts={{ ...counts, feedback }} superadmin={superadmin} engineer={engineer} />
|
||||
<div className="flex min-w-0 flex-col pb-16 md:pb-0">
|
||||
<VersionWatch boot={bootId()} />
|
||||
{line ? <AgentsStrip line={line} offers={offers} /> : <UsageStrip accounts={accounts} admin={superadmin} />}
|
||||
{children}
|
||||
</div>
|
||||
<CommandPalette />
|
||||
{/* PEP-143: «Сообщить о проблеме» on every page. */}
|
||||
<FeedbackButton />
|
||||
</div>
|
||||
</WordsProvider>
|
||||
);
|
||||
}
|
||||
|
||||
142
apps/web/app/(app)/observability/[id]/page.tsx
Normal file
142
apps/web/app/(app)/observability/[id]/page.tsx
Normal file
@ -0,0 +1,142 @@
|
||||
// glossary-ignore-file: the section is for the superadmin only.
|
||||
import Link from "next/link";
|
||||
import { notFound } from "next/navigation";
|
||||
import { Activity, Pause, Play, Trash2 } from "lucide-react";
|
||||
import { describeTarget, FEATURES, observeRemindMin, getMonitor, isSuperadmin, monitorChecks, monitorIncidents, monitorView } from "@peppa/core";
|
||||
import { loadEnv } from "@peppa/shared";
|
||||
import { LiveRefresh } from "@/components/LiveRefresh";
|
||||
import { Hidden } from "@/components/cards";
|
||||
import { CheckStrip, KIND_LABEL, MonitorFields, OutageLine, pct, StateBadge } from "@/components/Observability";
|
||||
import { ago, Disclosure, Empty, Flash, PageHeader, Section } from "@/components/common";
|
||||
import { Button } from "@/components/ui/button";
|
||||
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 { deleteMonitorAction, pauseMonitorAction, updateMonitorAction } from "../actions";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
const PAGE = 100;
|
||||
|
||||
const when = (iso: string) => new Date(iso).toLocaleString("ru-RU", { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit" });
|
||||
|
||||
export default async function MonitorPage({ params, searchParams }: { params: Promise<{ id: string }>; searchParams: Promise<{ error?: string; page?: string }> }) {
|
||||
const user = await requireUser();
|
||||
const t = await getT();
|
||||
if (!(await isSuperadmin(db, user))) notFound();
|
||||
const { id } = await params;
|
||||
const { error, page } = await searchParams;
|
||||
const found = getMonitor(Number(id));
|
||||
if (!found) notFound();
|
||||
const m = monitorView(found);
|
||||
const p = Math.max(0, Number(page) || 0);
|
||||
const checks = monitorChecks(m.id, { limit: PAGE + 1, offset: p * PAGE });
|
||||
const incidents = monitorIncidents(m.id);
|
||||
const web = loadEnv().PEPPA_WEB_URL;
|
||||
return (
|
||||
<Workspace>
|
||||
<LiveRefresh scope="observe" />
|
||||
<div className="max-w-4xl">
|
||||
<Flash error={error} />
|
||||
<PageHeader
|
||||
crumbs={<Link href="/observability" className="hover:underline">{t("Observability")}</Link>}
|
||||
title={<><Activity className="mr-1 inline size-5 text-primary" />{m.name}</>}
|
||||
>
|
||||
<span className="flex flex-wrap items-center gap-2">
|
||||
<StateBadge m={m} t={t} />
|
||||
<span>{t(KIND_LABEL[m.kind])}</span>
|
||||
<span className="font-mono text-xs break-all">{describeTarget(m, web)}</span>
|
||||
</span>
|
||||
</PageHeader>
|
||||
|
||||
<Card className="mb-4 gap-2 py-3">
|
||||
<div className="flex flex-wrap items-center gap-4 text-sm">
|
||||
<span>{t("Аптайм 24 ч:")} <b>{pct(m.uptime24h)}</b></span>
|
||||
<span>{t("7 дней:")} <b>{pct(m.uptime7d)}</b></span>
|
||||
<span className="text-muted-foreground">{m.stateSince ? t("в этом состоянии {ago}", { ago: ago(new Date(m.stateSince), t) }) : ""}</span>
|
||||
<span className="ml-auto"><CheckStrip recent={m.recent} t={t} /></span>
|
||||
</div>
|
||||
{m.lastDetail?.reason ? <p className="m-0 text-sm text-destructive">{String(m.lastDetail.reason)}</p> : null}
|
||||
<p className="m-0 text-sm empty:hidden"><OutageLine m={m} t={t} /></p>
|
||||
{m.kind === "heartbeat" && (
|
||||
<p className="m-0 text-xs text-muted-foreground">
|
||||
{t("Сервис отмечается запросом GET или POST по адресу:")} <code className="break-all">{describeTarget(m, web)}</code>
|
||||
</p>
|
||||
)}
|
||||
<p className="m-0 text-xs text-muted-foreground">
|
||||
{t("Раз в {n} с · «не работает» после {f} неудач подряд · «работает» после {r} удач · создал {who}", { n: m.intervalSec, f: m.failThreshold, r: m.recoverThreshold, who: m.createdBy })}
|
||||
{" · "}
|
||||
{(m.remindMin ?? observeRemindMin()) ? t("напоминание раз в {n} мин", { n: m.remindMin ?? observeRemindMin() }) : t("без напоминаний")}
|
||||
</p>
|
||||
<p className="m-0 text-xs text-muted-foreground">
|
||||
{t("Что отключать при сбое:")} {m.features.length ? m.features.map((f) => t(FEATURES[f].label)).join(", ") : t("ничего")}
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<form action={pauseMonitorAction}>
|
||||
<Hidden fields={{ id: m.id, paused: m.paused ? "0" : "1", back: `/observability/${m.id}` }} />
|
||||
<Button size="sm" variant="outline">{m.paused ? <><Play />{t("Продолжить")}</> : <><Pause />{t("Пауза")}</>}</Button>
|
||||
</form>
|
||||
<Disclosure summary={<span className="flex items-center gap-1.5 text-sm"><Trash2 className="size-4" />{t("Удалить")}</span>}>
|
||||
<form action={deleteMonitorAction} className="flex items-center gap-2">
|
||||
<Hidden fields={{ id: m.id, confirm: "1" }} />
|
||||
<span className="text-sm">{t("Удалить мониторинг вместе с журналом?")}</span>
|
||||
<Button size="sm" variant="destructive">{t("Да, удалить")}</Button>
|
||||
</form>
|
||||
</Disclosure>
|
||||
</div>
|
||||
<Disclosure summary={t("Изменить")}>
|
||||
<form action={updateMonitorAction} className="flex flex-col gap-2">
|
||||
<Hidden fields={{ id: m.id }} />
|
||||
<MonitorFields t={t} m={m} kindFixed remindDefault={observeRemindMin()} />
|
||||
<Button size="sm" variant="default" className="self-start">{t("Сохранить")}</Button>
|
||||
</form>
|
||||
</Disclosure>
|
||||
</Card>
|
||||
|
||||
<Section title={t("Сбои за неделю")} count={incidents.length}>
|
||||
{incidents.length === 0 ? (
|
||||
<Empty>{t("Сбоев не было.")}</Empty>
|
||||
) : (
|
||||
<ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm">
|
||||
{incidents.map((i) => (
|
||||
<li key={i.id} className="flex flex-wrap gap-2">
|
||||
<StateBadge m={{ state: i.state, paused: false }} t={t} />
|
||||
<span>{when(i.startedAt)} → {i.endedAt ? when(i.endedAt) : t("сейчас")}</span>
|
||||
<span className="text-muted-foreground">{i.reason}</span>
|
||||
{i.quiet && <span className="text-xs text-muted-foreground">{t("(вместе с интернетом, без сообщения)")}</span>}
|
||||
{i.reminders > 0 && <span className="text-xs text-muted-foreground">{t("напоминаний: {n}", { n: i.reminders })}</span>}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</Section>
|
||||
|
||||
<Section title={t("Журнал проверок")}>
|
||||
{checks.length === 0 ? (
|
||||
<Empty>{t("Проверок ещё не было.")}</Empty>
|
||||
) : (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-xs">
|
||||
<tbody>
|
||||
{checks.slice(0, PAGE).map((c) => (
|
||||
<tr key={c.id} className="border-b border-border/50">
|
||||
<td className="py-1 pr-3 whitespace-nowrap text-muted-foreground">{when(c.at)}</td>
|
||||
<td className={`py-1 pr-3 whitespace-nowrap ${!c.ok ? "text-destructive" : c.degraded ? "text-warn" : "text-ok"}`}>{!c.ok ? t("неудача") : c.degraded ? t("нестабильно") : "ok"}</td>
|
||||
<td className="py-1 pr-3 whitespace-nowrap text-muted-foreground">{c.latencyMs != null ? t("{n} мс", { n: c.latencyMs }) : ""}</td>
|
||||
<td className="py-1">{String(c.detail.reason ?? "")}{c.detail.status != null ? ` · ${c.detail.status}` : ""}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
<div className="mt-2 flex gap-3 text-sm">
|
||||
{p > 0 && <Link href={`/observability/${m.id}?page=${p - 1}`} className="hover:underline">{t("← новее")}</Link>}
|
||||
{checks.length > PAGE && <Link href={`/observability/${m.id}?page=${p + 1}`} className="hover:underline">{t("старее →")}</Link>}
|
||||
</div>
|
||||
</Section>
|
||||
</div>
|
||||
</Workspace>
|
||||
);
|
||||
}
|
||||
120
apps/web/app/(app)/observability/actions.ts
Normal file
120
apps/web/app/(app)/observability/actions.ts
Normal file
@ -0,0 +1,120 @@
|
||||
"use server";
|
||||
// Observability (PEP-202): every action is superadmin-only (others get "not found").
|
||||
|
||||
import { createMonitor, deleteMonitor, requestSmoke, resetFeatureCache, setFeatureThreshold, getProject, logEvent, MONITOR_KINDS, PeppaError, platformProjectKey, requireSuperadmin, setMonitorPaused, updateMonitor, type MonitorKind, type MonitorTarget } from "@peppa/core";
|
||||
import type { Db } from "@peppa/db";
|
||||
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();
|
||||
const BASE = "/observability";
|
||||
|
||||
async function attempt(f: FormData, back: string, fn: (login: string) => Promise<string | void>): Promise<never> {
|
||||
const user = asWebActor(await requireUser());
|
||||
let target = back;
|
||||
try {
|
||||
await requireSuperadmin(db, user);
|
||||
target = (await fn(user.login)) || target;
|
||||
} catch (e) {
|
||||
const t = await getT();
|
||||
const msg = e instanceof PeppaError ? t.text(e.message) : t("Ошибка: {message}", { message: (e as Error).message });
|
||||
target = `${back}?error=${encodeURIComponent(msg.slice(0, 300))}`;
|
||||
}
|
||||
revalidatePath(BASE, "layout");
|
||||
redirect(target);
|
||||
}
|
||||
|
||||
async function journal(d: Db, type: string, payload: Record<string, unknown>) {
|
||||
const p = await getProject(d, platformProjectKey()).catch(() => null);
|
||||
if (p) await logEvent(d, { projectId: p.id, type, payload }).catch(() => {});
|
||||
}
|
||||
|
||||
/** The form's fields → the monitor's target for its kind. */
|
||||
function targetOf(kind: MonitorKind, f: FormData): MonitorTarget {
|
||||
const where = str(f, "where");
|
||||
switch (kind) {
|
||||
case "http":
|
||||
return { url: where, contains: str(f, "contains") || undefined, expectStatus: str(f, "expectStatus") ? (str(f, "expectStatus").split(/[\s,]+/).map(Number) as number[]) : undefined, maxLatencyMs: str(f, "maxLatencyMs") ? Number(str(f, "maxLatencyMs")) : undefined };
|
||||
case "tcp": {
|
||||
const [host, port] = where.split(/:(?=\d+$)/);
|
||||
return { host: host ?? "", port: Number(port) };
|
||||
}
|
||||
case "dns":
|
||||
return { host: where };
|
||||
case "internet":
|
||||
return { hosts: where.split(/[\s,]+/).filter(Boolean) };
|
||||
case "heartbeat":
|
||||
return { graceSec: str(f, "graceSec") ? Number(str(f, "graceSec")) : undefined };
|
||||
}
|
||||
}
|
||||
|
||||
const numbers = (f: FormData) => ({
|
||||
// PEP-224: «Что отключать при сбое» — the checked features.
|
||||
features: f.getAll("features").map(String),
|
||||
intervalSec: str(f, "intervalSec") ? Number(str(f, "intervalSec")) : undefined,
|
||||
failThreshold: str(f, "failThreshold") ? Number(str(f, "failThreshold")) : undefined,
|
||||
recoverThreshold: str(f, "recoverThreshold") ? Number(str(f, "recoverThreshold")) : undefined,
|
||||
// PEP-223: empty — the common default; the form always carries the whole state.
|
||||
remindMin: str(f, "remindMin") ? Number(str(f, "remindMin")) : null,
|
||||
remindDegraded: f.get("remindDegraded") === "1",
|
||||
});
|
||||
|
||||
export async function createMonitorAction(f: FormData) {
|
||||
await attempt(f, BASE, async (login) => {
|
||||
const kind = str(f, "kind") as MonitorKind;
|
||||
if (!MONITOR_KINDS.includes(kind)) throw new PeppaError(m("Неизвестный вид мониторинга: {kind}", { kind }));
|
||||
const mon = createMonitor({ name: str(f, "name"), kind, target: targetOf(kind, f), ...numbers(f) }, `user:${login}`);
|
||||
await journal(db, "monitor_created", { id: mon.id, name: mon.name, kind: mon.kind, target: mon.target, author: `user:${login}` });
|
||||
return `${BASE}/${mon.id}`;
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateMonitorAction(f: FormData) {
|
||||
const id = Number(str(f, "id"));
|
||||
await attempt(f, `${BASE}/${id}`, async (login) => {
|
||||
const kind = str(f, "kind") as MonitorKind;
|
||||
const mon = updateMonitor(id, { name: str(f, "name"), target: targetOf(kind, f), ...numbers(f) });
|
||||
await journal(db, "monitor_updated", { id: mon.id, name: mon.name, author: `user:${login}` });
|
||||
});
|
||||
}
|
||||
|
||||
export async function pauseMonitorAction(f: FormData) {
|
||||
const id = Number(str(f, "id"));
|
||||
await attempt(f, str(f, "back") || BASE, async (login) => {
|
||||
const paused = str(f, "paused") === "1";
|
||||
const mon = setMonitorPaused(id, paused);
|
||||
await journal(db, "monitor_updated", { id: mon.id, name: mon.name, paused, author: `user:${login}` });
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteMonitorAction(f: FormData) {
|
||||
const id = Number(str(f, "id"));
|
||||
await attempt(f, `${BASE}/${id}`, async (login) => {
|
||||
if (str(f, "confirm") !== "1") throw new PeppaError(m("Подтвердите удаление"));
|
||||
const mon = deleteMonitor(id);
|
||||
await journal(db, "monitor_deleted", { id: mon.id, name: mon.name, author: `user:${login}` });
|
||||
return BASE;
|
||||
});
|
||||
}
|
||||
|
||||
/** PEP-224: how long a linked monitor may be down before the feature turns grey. */
|
||||
export async function setFeatureThresholdAction(f: FormData) {
|
||||
await attempt(f, BASE, async (login) => {
|
||||
const name = str(f, "name");
|
||||
const minutes = Number(str(f, "disableAfterMin"));
|
||||
setFeatureThreshold(name, minutes);
|
||||
resetFeatureCache();
|
||||
await journal(db, "feature_updated", { feature: name, disableAfterMin: minutes, author: `user:${login}` });
|
||||
});
|
||||
}
|
||||
|
||||
/** PEP-266: «Проверить сейчас» — the runner service starts the launch smoke test on its next tick. */
|
||||
export async function requestSmokeAction(f: FormData) {
|
||||
await attempt(f, BASE, async (login) => {
|
||||
await requestSmoke(db, login);
|
||||
});
|
||||
}
|
||||
332
apps/web/app/(app)/observability/page.tsx
Normal file
332
apps/web/app/(app)/observability/page.tsx
Normal file
@ -0,0 +1,332 @@
|
||||
// glossary-ignore-file: the section is for the superadmin only.
|
||||
import Link from "next/link";
|
||||
import { notFound } from "next/navigation";
|
||||
import { Activity, Pause, Play, Plus } from "lucide-react";
|
||||
import { describeTarget, observeRemindMin, PROVIDER_LABEL, smokeStatus, smokeTimeoutMin, type SmokeRun, type SmokeStatus, egovLoginSummary, errorScope, errorsOverview, FEATURE_NAMES, FEATURES, featureLog, featureStatuses, getLastRetention, isSuperadmin, listErrors, listMonitorViews, requestSummary } from "@peppa/core";
|
||||
import { loadEnv } from "@peppa/shared";
|
||||
import { LiveRefresh } from "@/components/LiveRefresh";
|
||||
import { Hidden } from "@/components/cards";
|
||||
import { CheckStrip, KIND_LABEL, MonitorFields, OutageLine, pct, StateBadge } from "@/components/Observability";
|
||||
import { ErrorFilters, errorFilterFrom, ErrorRows, ErrorsDown, ErrorsSummary } from "@/components/Errors";
|
||||
import { ago, Disclosure, Empty, Flash, PageHeader, Section } from "@/components/common";
|
||||
import { Button } from "@/components/ui/button";
|
||||
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 { createMonitorAction, pauseMonitorAction, requestSmokeAction, setFeatureThresholdAction } from "./actions";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export async function generateMetadata() {
|
||||
const t = await getT();
|
||||
return { title: t("Observability — FORGE") };
|
||||
}
|
||||
|
||||
type Search = { error?: string; tab?: string; bp?: string; state?: string; env?: string; rel?: string; q?: string; sort?: string; cursor?: string };
|
||||
|
||||
/** Tabs «Мониторинги» · «Ошибки» (PEP-218). */
|
||||
function Tabs({ tab, t }: { tab: "monitors" | "errors"; t: Awaited<ReturnType<typeof getT>> }) {
|
||||
const cls = (on: boolean) => `border-b-2 px-3 py-1.5 text-sm ${on ? "border-primary font-semibold" : "border-transparent text-muted-foreground hover:text-foreground"}`;
|
||||
return (
|
||||
<nav className="mb-4 flex gap-1 border-b">
|
||||
<Link href="/observability" className={cls(tab === "monitors")}>{t("Мониторинги")}</Link>
|
||||
<Link href="/observability?tab=errors" className={cls(tab === "errors")}>{t("Ошибки")}</Link>
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
|
||||
/** PEP-218: errors of every Bugsink project, read from its REST API on the server. */
|
||||
async function ErrorsTab({ user, sp }: { user: Awaited<ReturnType<typeof requireUser>>; sp: Search }) {
|
||||
const t = await getT();
|
||||
const scope = await errorScope(db, user);
|
||||
const f = errorFilterFrom(sp);
|
||||
const [ov, list] = await Promise.all([errorsOverview(db, scope), listErrors(db, scope, f)]);
|
||||
const query = new URLSearchParams(Object.entries({ tab: "errors", bp: sp.bp, state: sp.state, env: sp.env, rel: sp.rel, q: sp.q, sort: sp.sort }).filter((e): e is [string, string] => !!e[1]));
|
||||
const from = `/observability?${query}`;
|
||||
return (
|
||||
<>
|
||||
<ErrorsDown down={ov.down || list.down} at={list.at ?? ov.at} tech t={t} />
|
||||
<Section title={t("Сводка")}>
|
||||
<ErrorsSummary ov={ov} t={t} hrefFor={(id) => `/observability?tab=errors&bp=${id}`} />
|
||||
</Section>
|
||||
{ov.top.length ? (
|
||||
<Section title={t("Частые и свежие")} count={ov.top.length}>
|
||||
<ErrorRows rows={ov.top} tech from={from} t={t} />
|
||||
</Section>
|
||||
) : null}
|
||||
<Section title={t("Все ошибки")} count={list.rows.length}>
|
||||
<ErrorFilters action="/observability" scope={scope} f={f} keep={{ tab: "errors" }} t={t} />
|
||||
<ErrorRows rows={list.rows} tech from={from} t={t} />
|
||||
{list.next ? (
|
||||
<Link href={`/observability?${new URLSearchParams([...query, ["cursor", list.next]])}`} className="mt-2 inline-block text-sm text-primary hover:underline">{t("Дальше →")}</Link>
|
||||
) : null}
|
||||
</Section>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** PEP-266: the launch smoke test — every provider started the real way after a deploy and hourly. */
|
||||
async function SmokeSection({ t }: { t: Awaited<ReturnType<typeof getT>> }) {
|
||||
const st = await smokeStatus(db);
|
||||
const shown: SmokeRun | null = st.current ?? st.history[0] ?? null;
|
||||
const STATE: Record<SmokeStatus, [string, string]> = {
|
||||
running: [t("идёт проверка"), "border-primary/40 text-primary"],
|
||||
ok: [t("запускается"), "border-ok/40 text-ok"],
|
||||
failed: [t("не запустился"), "border-destructive/40 text-destructive"],
|
||||
skipped: [t("не проверен"), "text-muted-foreground"],
|
||||
};
|
||||
const TRIGGER = { deploy: t("после выкатки"), hourly: t("плановая"), manual: t("по запросу") } as const;
|
||||
const when = (r: SmokeRun) => new Date(r.at).toLocaleString("ru-RU", { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit" });
|
||||
return (
|
||||
<Section
|
||||
title={t("Запуск агентов")}
|
||||
actions={
|
||||
<form action={requestSmokeAction}>
|
||||
<Button size="sm" variant="outline" disabled={st.requested || !!st.current}>{st.requested ? t("Проверка запрошена") : t("Проверить сейчас")}</Button>
|
||||
</form>
|
||||
}
|
||||
>
|
||||
<p className="m-0 text-sm text-muted-foreground">{t("После каждой выкатки и раз в час FORGE запускает каждого агента (Claude, Codex, OpenCode — у кого есть подписка) так же, как для задачи, с одной просьбой: создать файл и закоммитить. Нет коммита за {n} мин — суперадминам уходит сообщение в Telegram.", { n: smokeTimeoutMin() })}</p>
|
||||
{!shown ? (
|
||||
<Empty>{t("Проверок ещё не было.")}</Empty>
|
||||
) : (
|
||||
<Card className="gap-1.5 py-3" data-smoke-run={shown.id}>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{t("{when} · {trigger} · версия {commit}", { when: when(shown), trigger: TRIGGER[shown.trigger], commit: shown.commit?.slice(0, 7) ?? "?" })}
|
||||
</div>
|
||||
{shown.items.map((i) => {
|
||||
const [label, cls] = STATE[i.status];
|
||||
return (
|
||||
<div key={i.provider} className="flex flex-col gap-1" data-smoke-row={i.provider} data-smoke-status={i.status}>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Badge variant="outline" className={cls}>{label}</Badge>
|
||||
<span className="font-semibold">{PROVIDER_LABEL[i.provider]}</span>
|
||||
{i.sec != null && i.status !== "skipped" ? <span className="text-xs text-muted-foreground">{t("{n} с", { n: i.sec })}</span> : null}
|
||||
{i.reason ? <span className={`text-xs ${i.status === "failed" ? "text-destructive" : "text-muted-foreground"}`}>{t.text(i.reason)}</span> : null}
|
||||
</div>
|
||||
{i.screen ? (
|
||||
<Disclosure summary={t("Экран агента")}>
|
||||
<pre className="m-0 max-h-60 overflow-auto whitespace-pre-wrap text-xs">{i.screen}</pre>
|
||||
</Disclosure>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</Card>
|
||||
)}
|
||||
{st.history.length > 1 ? (
|
||||
<Disclosure summary={t("Прошлые проверки ({n})", { n: st.history.length - (st.current ? 0 : 1) })}>
|
||||
<ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm">
|
||||
{st.history.slice(st.current ? 0 : 1).map((r) => (
|
||||
<li key={r.id} className="flex flex-wrap gap-2">
|
||||
<span className="text-muted-foreground">{when(r)}</span>
|
||||
<span className="text-muted-foreground">{TRIGGER[r.trigger]}</span>
|
||||
{r.items.map((i) => (
|
||||
<span key={i.provider} className={i.status === "failed" ? "text-destructive" : i.status === "ok" ? "text-ok" : "text-muted-foreground"}>
|
||||
{PROVIDER_LABEL[i.provider]}: {STATE[i.status][0]}
|
||||
</span>
|
||||
))}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</Disclosure>
|
||||
) : null}
|
||||
</Section>
|
||||
);
|
||||
}
|
||||
|
||||
export default async function Observability({ searchParams }: { searchParams: Promise<Search> }) {
|
||||
const user = await requireUser();
|
||||
const t = await getT();
|
||||
if (!(await isSuperadmin(db, user))) notFound();
|
||||
const sp = await searchParams;
|
||||
const { error } = sp;
|
||||
if (sp.tab === "errors") {
|
||||
return (
|
||||
<Workspace>
|
||||
<div className="max-w-4xl">
|
||||
<Flash error={error} />
|
||||
<PageHeader title={<><Activity className="mr-1 inline size-5 text-primary" />{t("Observability")}</>}>
|
||||
{t("Ошибки всех проектов из учёта ошибок (Bugsink): сводка, самые частые и свежие, список с фильтрами. Данные обновляются раз в минуту.")}
|
||||
</PageHeader>
|
||||
<Tabs tab="errors" t={t} />
|
||||
<ErrorsTab user={user} sp={sp} />
|
||||
</div>
|
||||
</Workspace>
|
||||
);
|
||||
}
|
||||
const monitors = listMonitorViews();
|
||||
const egov = await egovLoginSummary(db);
|
||||
const retention = await getLastRetention(db);
|
||||
const speed = requestSummary();
|
||||
const ms = (n: number) => (n >= 1000 ? t("{n} с", { n: (n / 1000).toFixed(1) }) : t("{n} мс", { n: Math.round(n) }));
|
||||
const web = loadEnv().PEPPA_WEB_URL;
|
||||
const down = monitors.filter((m) => !m.paused && m.state === "down").length;
|
||||
const degraded = monitors.filter((m) => !m.paused && m.state === "degraded").length;
|
||||
// PEP-224: features follow their monitors.
|
||||
const features = featureStatuses({ fresh: true });
|
||||
const flog = featureLog(20);
|
||||
const FEATURE_STATE = { available: [t("доступна"), "border-ok/40 text-ok"], degraded: [t("с задержками"), "border-warn/40 text-warn"], unavailable: [t("отключена"), "border-destructive/40 text-destructive"] } as const;
|
||||
return (
|
||||
<Workspace>
|
||||
<LiveRefresh scope="observe" />
|
||||
<div className="max-w-4xl">
|
||||
<Flash error={error} />
|
||||
<PageHeader title={<><Activity className="mr-1 inline size-5 text-primary" />{t("Observability")}</>}>
|
||||
{t("Мониторинги сервисов, от которых зависит FORGE, и интернета на её сервере. Смена состояния — одно сообщение в Telegram-канал платформы, пока не работает — напоминание раз в 30 минут (настраивается у мониторинга). Журнал проверок хранится 7 дней. Мониторинги можно создавать здесь и через MCP; раздел видят только суперадмины.")}
|
||||
</PageHeader>
|
||||
<Tabs tab="monitors" t={t} />
|
||||
{retention && (
|
||||
<p className="mb-3 text-sm text-muted-foreground">
|
||||
{t("Уборка журналов: {ago} — удалено строк {n}, база {size} МБ, свободно внутри {free} МБ", { ago: ago(new Date(retention.at), t), n: retention.total, size: (retention.dbBytes / 1048576).toFixed(1), free: (retention.freedBytes / 1048576).toFixed(1) })}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<Section title={t("Мониторинги")} count={monitors.length} actions={down || degraded ? <span className="text-sm text-muted-foreground">{t("не работает: {n} · нестабильно: {m}", { n: down, m: degraded })}</span> : undefined}>
|
||||
{monitors.length === 0 ? (
|
||||
<Empty>{t("Мониторингов нет. Сервис мониторингов создаст встроенные при первом запуске.")}</Empty>
|
||||
) : (
|
||||
<div className="flex flex-col gap-2">
|
||||
{monitors.map((m) => (
|
||||
<Card key={m.id} className="gap-1.5 py-3">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<StateBadge m={m} t={t} />
|
||||
<Link href={`/observability/${m.id}`} className="font-semibold hover:underline">{m.name}</Link>
|
||||
<span className="text-xs text-muted-foreground">{t(KIND_LABEL[m.kind])}</span>
|
||||
<span className="ml-auto flex items-center gap-3 text-xs text-muted-foreground">
|
||||
<span title={t("Аптайм за 24 часа")}>{t("24 ч")} {pct(m.uptime24h)}</span>
|
||||
<span title={t("Аптайм за 7 дней")}>{t("7 д")} {pct(m.uptime7d)}</span>
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<span className="min-w-0 flex-1 truncate font-mono text-xs text-muted-foreground">{describeTarget(m, web)}</span>
|
||||
<CheckStrip recent={m.recent} t={t} />
|
||||
</div>
|
||||
{m.name === "eGov relay" ? (
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{egov.failed > 0
|
||||
? t("Входы за сутки: {n}, неудачных {m} ({reasons})", { n: egov.total, m: egov.failed, reasons: egov.byReason.map((r) => `${t(r.reason)}: ${r.n}`).join(", ") })
|
||||
: t("Входы за сутки: {n}, неудачных нет", { n: egov.total })}
|
||||
</div>
|
||||
) : null}
|
||||
<div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
|
||||
{m.lastDetail?.reason ? <span className={m.state === "down" ? "text-destructive" : "text-warn"}>{String(m.lastDetail.reason)}</span> : null}
|
||||
<OutageLine m={m} t={t} />
|
||||
<span>{m.lastCheckAt ? t("проверен {ago}", { ago: ago(new Date(m.lastCheckAt), t) }) : t("ещё не проверялся")}</span>
|
||||
<form action={pauseMonitorAction} className="ml-auto">
|
||||
<Hidden fields={{ id: m.id, paused: m.paused ? "0" : "1", back: "/observability" }} />
|
||||
<Button size="sm" variant="ghost">{m.paused ? <><Play />{t("Продолжить")}</> : <><Pause />{t("Пауза")}</>}</Button>
|
||||
</form>
|
||||
</div>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<Disclosure summary={<span className="flex items-center gap-1.5"><Plus className="size-4" />{t("Новый мониторинг")}</span>}>
|
||||
<form action={createMonitorAction} className="flex flex-col gap-2">
|
||||
<MonitorFields t={t} remindDefault={observeRemindMin()} />
|
||||
<Button size="sm" variant="default" className="self-start">{t("Создать")}</Button>
|
||||
</form>
|
||||
</Disclosure>
|
||||
</Section>
|
||||
|
||||
<SmokeSection t={t} />
|
||||
|
||||
<Section title={t("Функции")} count={FEATURE_NAMES.length}>
|
||||
<p className="m-0 text-sm text-muted-foreground">{t("Функция становится серой у пользователей, когда связанный мониторинг не работает дольше порога, и включается сама после восстановления. Связка — «Что отключать при сбое» у мониторинга или поле features в MCP update_monitor.")}</p>
|
||||
<div className="flex flex-col gap-2">
|
||||
{FEATURE_NAMES.map((name) => {
|
||||
const f = features[name];
|
||||
const [label, cls] = FEATURE_STATE[f.state];
|
||||
return (
|
||||
<Card key={name} className="gap-1.5 py-3" data-feature-row={name}>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Badge variant="outline" className={cls}>{label}</Badge>
|
||||
<span className="font-semibold">{t(FEATURES[name].label)}</span>
|
||||
<span className="font-mono text-xs text-muted-foreground">{name}</span>
|
||||
<form action={setFeatureThresholdAction} className="ml-auto flex items-center gap-1.5 text-xs text-muted-foreground">
|
||||
<Hidden fields={{ name }} />
|
||||
{t("отключать через, мин")}
|
||||
<Input name="disableAfterMin" type="number" min={0} max={1440} defaultValue={f.disableAfterMin} className="h-7 w-16" />
|
||||
<Button size="sm" variant="ghost">{t("Сохранить")}</Button>
|
||||
</form>
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{f.monitors.length ? (
|
||||
<>
|
||||
{t("Мониторинги:")}{" "}
|
||||
{f.monitors.map((mm, i) => (
|
||||
<span key={mm.id}>
|
||||
{i ? ", " : ""}
|
||||
<Link href={`/observability/${mm.id}`} className="hover:underline">{mm.name}</Link>
|
||||
</span>
|
||||
))}
|
||||
</>
|
||||
) : (
|
||||
t("Не связана ни с одним мониторингом — всегда доступна.")
|
||||
)}
|
||||
{f.failing.length ? <span className="text-destructive"> · {f.failing.map((x) => `${x.name}${x.reason ? `: ${x.reason}` : ""}`).join("; ")}</span> : null}
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<Disclosure summary={t("Журнал включений и выключений ({n})", { n: flog.length })}>
|
||||
{flog.length === 0 ? (
|
||||
<Empty>{t("Функции ещё не отключались.")}</Empty>
|
||||
) : (
|
||||
<ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm">
|
||||
{flog.map((e) => (
|
||||
<li key={e.id} className="flex flex-wrap gap-2">
|
||||
<span className="text-muted-foreground">{new Date(e.at).toLocaleString("ru-RU", { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit" })}</span>
|
||||
<span className={e.state === "unavailable" ? "text-destructive" : "text-ok"}>{e.state === "unavailable" ? t("отключена") : t("снова включена")}</span>
|
||||
<span className="font-medium">{t(FEATURES[e.name].label)}</span>
|
||||
{e.reason && <span className="text-muted-foreground">{e.reason}</span>}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</Disclosure>
|
||||
</Section>
|
||||
|
||||
<Section title={t("Скорость страниц")} count={speed.length}>
|
||||
<p className="mb-2 text-sm text-muted-foreground">{t("Страницы и действия за последние 24 часа: сколько раз открывали, как долго отвечали и какая часть времени ушла на базу данных. Медленные запросы приходят в Bugsink сами. Числа считаются с последнего перезапуска сайта.")}</p>
|
||||
{speed.length === 0 ? (
|
||||
<Empty>{t("Пока нет данных: сайт открывали недавно.")}</Empty>
|
||||
) : (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr className="text-left text-xs text-muted-foreground">
|
||||
<th className="py-1 pr-3 font-medium">{t("Страница")}</th>
|
||||
<th className="px-2 text-right font-medium">{t("Запросов")}</th>
|
||||
<th className="px-2 text-right font-medium">{t("Типичный (p50)")}</th>
|
||||
<th className="px-2 text-right font-medium">{t("Медленные (p95)")}</th>
|
||||
<th className="px-2 text-right font-medium">{t("Дольше всех")}</th>
|
||||
<th className="pl-2 text-right font-medium">{t("Доля базы")}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{speed.map((r) => (
|
||||
<tr key={r.route} className="border-t border-border">
|
||||
<td className="py-1 pr-3 font-mono text-xs">{r.route}</td>
|
||||
<td className="px-2 text-right tabular-nums">{r.count}</td>
|
||||
<td className="px-2 text-right tabular-nums">{ms(r.p50)}</td>
|
||||
<td className={`px-2 text-right tabular-nums ${r.p95 >= 1500 ? "text-warn" : ""}`}>{ms(r.p95)}</td>
|
||||
<td className="px-2 text-right tabular-nums">{ms(r.max)}</td>
|
||||
<td className="pl-2 text-right tabular-nums">{Math.round(r.sqlShare * 100)}%</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</Section>
|
||||
</div>
|
||||
</Workspace>
|
||||
);
|
||||
}
|
||||
181
apps/web/app/(app)/p/[key]/accept/page.tsx
Normal file
181
apps/web/app/(app)/p/[key]/accept/page.tsx
Normal file
@ -0,0 +1,181 @@
|
||||
import Link from "next/link";
|
||||
import { notFound } from "next/navigation";
|
||||
import { acceptAllSummary, acceptScreen, type AcceptItem } from "@peppa/core";
|
||||
import { acceptAllAction, fixStoryAction } from "@/app/(app)/actions";
|
||||
import { Empty, Flash, Key, Notice, PageHeader } from "@/components/common";
|
||||
import { LiveRefresh } from "@/components/LiveRefresh";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { 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 { projectForUserByKey } from "@/lib/queries";
|
||||
|
||||
export async function generateMetadata() {
|
||||
const t = await getT();
|
||||
return { title: t("Приёмка — FORGE") };
|
||||
}
|
||||
|
||||
const BIG = "min-h-11"; // PEP-209: buttons at least 44 px on a phone
|
||||
|
||||
/**
|
||||
* PEP-209: acceptance on one screen — every story waiting for «Принять», grouped by product page,
|
||||
* with «было» / «стало», «Принять», «Поправить» and «Принять всё» on top.
|
||||
*/
|
||||
export default async function AcceptPage({ params, searchParams }: { params: Promise<{ key: string }>; searchParams: Promise<{ error?: string; ok?: string; pending?: string; failed?: string }> }) {
|
||||
const user = await requireUser();
|
||||
const { key } = await params;
|
||||
const sp = await searchParams;
|
||||
const t = await getT();
|
||||
const p = await projectForUserByKey(user.id, key).catch(() => null);
|
||||
if (!p) notFound();
|
||||
const screen = await acceptScreen(db, p);
|
||||
const back = `/p/${p.key}/accept`;
|
||||
const all = screen.groups.flatMap((g) => g.items);
|
||||
const done = sp.ok != null ? { accepted: Number(sp.ok) || 0, pending: Number(sp.pending) || 0, failed: Number(sp.failed) || 0 } : null;
|
||||
return (
|
||||
<Workspace>
|
||||
<LiveRefresh scope={`project:${p.id}`} />
|
||||
<Flash error={sp.error} />
|
||||
<PageHeader crumbs={<Link href={`/p/${p.key}`} className="text-muted-foreground hover:text-foreground">{p.name}</Link>} title={t("Приёмка")}>
|
||||
{screen.total ? t("Работа, которая ждёт вашего решения: посмотрите и примите или напишите, что поправить.") : t("Принимать пока нечего: агенты пришлют задачи, когда работа будет готова.")}
|
||||
</PageHeader>
|
||||
|
||||
{done && (
|
||||
<Notice>
|
||||
<span data-accept-result>{t.text(acceptAllSummary(done))}</span>
|
||||
{screen.liveUrl && done.accepted + done.pending > 0 && (
|
||||
<a href={screen.liveUrl} target="_blank" rel="noreferrer" className="text-primary">{t("Открыть продукт")} →</a>
|
||||
)}
|
||||
</Notice>
|
||||
)}
|
||||
|
||||
{screen.total > 0 && (
|
||||
<div className="mb-6 flex flex-wrap items-start gap-2" data-accept-top>
|
||||
{screen.checkUrl && (
|
||||
<a href={screen.checkUrl} target="_blank" rel="noreferrer" className={`inline-flex items-center rounded-md border bg-card px-4 text-sm font-medium hover:bg-accent ${BIG}`}>
|
||||
{t("Открыть версию для проверки")}
|
||||
</a>
|
||||
)}
|
||||
<details className="group w-full rounded-lg border bg-card sm:w-auto" data-accept-all>
|
||||
<summary className={`flex cursor-pointer list-none items-center rounded-md bg-primary px-4 text-sm font-medium text-primary-foreground select-none [&::-webkit-details-marker]:hidden ${BIG}`}>
|
||||
{t("Принять всё · {n}", { n: all.length })}
|
||||
</summary>
|
||||
<form action={acceptAllAction} className="flex flex-col gap-2 p-3">
|
||||
<input type="hidden" name="project" value={p.key} />
|
||||
<input type="hidden" name="back" value={back} />
|
||||
<p className="m-0 text-sm">{t("Будут приняты по очереди:")}</p>
|
||||
<ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm">
|
||||
{all.map((it) => (
|
||||
<li key={it.key}>
|
||||
<input type="hidden" name="taskKey" value={it.key} />
|
||||
<Key>{it.key}</Key> {it.title}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<p className="m-0 text-xs text-muted-foreground">{t("Если какая-то не примется, остальные всё равно примутся, а у неё будет написано почему.")}</p>
|
||||
<Button variant="default" className={BIG} data-accept-all-confirm>
|
||||
{t("Да, принять {n}", { n: all.length })}
|
||||
</Button>
|
||||
</form>
|
||||
</details>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{screen.total === 0 && !done && <Empty>{t("Задач на приёмке нет.")}</Empty>}
|
||||
|
||||
{screen.groups.map((g) => (
|
||||
<section key={g.page || "-"} className="mb-8" data-accept-group={g.page || "-"}>
|
||||
<h2 className="mb-3 text-base font-semibold">
|
||||
{g.page ? t("Страница {page}", { page: g.page }) : t("Без снимков страниц")} <span className="text-muted-foreground">· {g.items.length}</span>
|
||||
</h2>
|
||||
<div className="flex flex-col gap-4">
|
||||
{g.items.map((it) => <AcceptCard key={it.key} it={it} back={back} />)}
|
||||
</div>
|
||||
</section>
|
||||
))}
|
||||
</Workspace>
|
||||
);
|
||||
}
|
||||
|
||||
async function AcceptCard({ it, back }: { it: AcceptItem; back: string }) {
|
||||
const t = await getT();
|
||||
return (
|
||||
<article className="rounded-lg border bg-card p-3 sm:p-4" data-accept-item={it.key}>
|
||||
<div className="mb-1 flex flex-wrap items-center gap-2 text-sm">
|
||||
<Link href={`/t/${it.key}`} className="hover:underline">
|
||||
<Key>{it.key}</Key>
|
||||
</Link>
|
||||
<span className="font-medium">{it.title}</span>
|
||||
</div>
|
||||
{it.summary !== it.title && <p className="m-0 mb-3 text-sm" data-accept-summary>{t.text(it.summary)}</p>}
|
||||
{it.failed && (
|
||||
<p role="alert" className="m-0 mb-3 rounded-md border border-destructive/50 bg-destructive/10 px-3 py-2 text-sm" data-accept-failed>
|
||||
{t("Не принялась: {reason}", { reason: t.text(it.failed) })}
|
||||
</p>
|
||||
)}
|
||||
{it.pending && <p className="m-0 mb-3 text-sm text-muted-foreground">{t("Вы уже приняли — изменения обновляются, задача закроется сама.")}</p>}
|
||||
{it.shots.length > 0 ? (
|
||||
// Scrolls sideways on a phone: one page per screen, «было» above «стало».
|
||||
<div className="-mx-3 mb-3 flex snap-x snap-mandatory gap-3 overflow-x-auto px-3 pb-2 sm:mx-0 sm:px-0" data-accept-shots>
|
||||
{it.shots.map((s, i) => (
|
||||
<figure key={i} className="m-0 w-[85%] shrink-0 snap-start sm:w-[calc(50%-0.375rem)]">
|
||||
<figcaption className="mb-1 text-xs text-muted-foreground">{s.path}</figcaption>
|
||||
<div className="grid grid-cols-1 gap-2">
|
||||
<Shot src={s.before} label={t("Было")} empty={t("Снимка рабочей версии нет")} />
|
||||
<Shot src={s.after} label={t("Стало")} empty={t("Снимка нет")} />
|
||||
</div>
|
||||
</figure>
|
||||
))}
|
||||
</div>
|
||||
) : it.previewUrl ? (
|
||||
<p className="m-0 mb-3 text-sm">
|
||||
<a href={it.previewUrl} target="_blank" rel="noreferrer" className="inline-flex min-h-11 items-center text-primary">{t("Открыть в версии для проверки")} →</a>
|
||||
</p>
|
||||
) : (
|
||||
<p className="m-0 mb-3 text-sm text-muted-foreground">{t("Снимков и версии для проверки нет — посмотрите описание задачи.")}</p>
|
||||
)}
|
||||
{it.shots.length > 0 && it.previewUrl && (
|
||||
<p className="m-0 mb-3 text-sm">
|
||||
<a href={it.previewUrl} target="_blank" rel="noreferrer" className="inline-flex min-h-11 items-center text-primary">{t("Открыть в версии для проверки")} →</a>
|
||||
</p>
|
||||
)}
|
||||
{!it.pending && (
|
||||
<div className="flex flex-col gap-2 sm:flex-row sm:items-start">
|
||||
<form action={acceptAllAction}>
|
||||
<input type="hidden" name="project" value={it.key.slice(0, it.key.lastIndexOf("-"))} />
|
||||
<input type="hidden" name="back" value={back} />
|
||||
<input type="hidden" name="taskKey" value={it.key} />
|
||||
<Button variant="default" className={`${BIG} w-full sm:w-auto`} data-accept-one={it.key}>{t("Принять")}</Button>
|
||||
</form>
|
||||
<details className="w-full sm:w-auto">
|
||||
<summary className={`flex cursor-pointer list-none items-center justify-center rounded-md border bg-card px-4 text-sm font-medium select-none hover:bg-accent [&::-webkit-details-marker]:hidden ${BIG}`}>{t("Поправить")}</summary>
|
||||
<form action={fixStoryAction} className="mt-2 flex flex-col gap-2">
|
||||
<input type="hidden" name="taskKey" value={it.key} />
|
||||
<input type="hidden" name="back" value={back} />
|
||||
<Textarea name="text" required rows={3} placeholder={t("Что поправить? Например: кнопка должна быть синей")} />
|
||||
<Button className={BIG} data-accept-fix={it.key}>{t("Отправить агенту")}</Button>
|
||||
</form>
|
||||
</details>
|
||||
</div>
|
||||
)}
|
||||
</article>
|
||||
);
|
||||
}
|
||||
|
||||
function Shot({ src, label, empty }: { src: string | null; label: string; empty: string }) {
|
||||
return (
|
||||
<div>
|
||||
<div className="mb-0.5 text-xs font-medium">{label}</div>
|
||||
{src ? (
|
||||
<a href={src} target="_blank" rel="noreferrer">
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img src={src} alt={label} loading="lazy" className="block w-full rounded border" />
|
||||
</a>
|
||||
) : (
|
||||
<div className="flex aspect-[16/10] items-center justify-center rounded border border-dashed text-xs text-muted-foreground">{empty}</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@ -1,166 +1,812 @@
|
||||
import Link from "next/link";
|
||||
import { Fragment } from "react";
|
||||
import { ProductCard } from "@/components/ProductCard";
|
||||
import { PublishPanel } from "@/components/PublishPanel";
|
||||
import { notFound } from "next/navigation";
|
||||
import { AutoRefresh } from "@/components/AutoRefresh";
|
||||
import { Flash, Notice, SessionCard } from "@/components/ui";
|
||||
import { ExternalLink, Plus, Rocket, SquareTerminal } from "lucide-react";
|
||||
import { columnOf, currentReleases, peekRepo, isPlatform, listReleases, bugsinkWebhookBase, openPulls, platformReleaseCandidate, platformReleaseOffers, ownPendingLogins, readAgentsMd, repoOverview, type Release, sharedRequest, subscriptionRequestOffer } from "@peppa/runner";
|
||||
import { getProjectPause, getPublishMode, poolSubscriptions, PRODUCT_PROJECT_TABS, userProjectIds, projectProduct, discussionUnread, ensureProjectChat, listHosts, DEFAULT_RUNNER_SETTINGS, DEFAULT_AGENT_SETTINGS, getProjectAgentSettings, getSystemAgentSettings, getProjectRunnerSettings, getSystemRunnerSettings, blockedLabel, blockersMap, epicProgress, progressLabel, taskProgress, getProjectBudget, listJournal, listProjectSecrets, agentSecretsEnabled, secretsAgentReport, secretNameHints, projectMetrics, type ActorChannel, type ActorKind, getAutonomy, getIncidentSettings, getDirectOrigins, getReviewSettings, isSuperadmin, listEpics, listErrorSources, listIncidents, listMembers, listPools, listSpecs, taskAgentNames, getIntakeSettings, intakePendingTasks, projectAgentWarning, taskHoldReasons, memoryStats, readMemory, projectPool, sharedPool, ownPool, poolOverview, repoAudience, repoVisibilityLabel } from "@peppa/core";
|
||||
import { productNeeds, lastProductReview } from "@peppa/core";
|
||||
import { LiveRefresh } from "@/components/LiveRefresh";
|
||||
import { PanelSection } from "@/components/ActivityAside";
|
||||
import { Board, type Card } from "@/components/Board";
|
||||
import { columnOf, describeRepo } from "@peppa/runner";
|
||||
import { requireUser } from "@/lib/auth";
|
||||
import { board, projectForUserByKey, projectSessions } from "@/lib/queries";
|
||||
import { listMembers, repoAudience, repoVisibilityLabel } from "@peppa/core";
|
||||
import { Hidden, SessionCard } from "@/components/cards";
|
||||
import { AttachField } from "@/components/AttachField";
|
||||
import { Dictate } from "@/components/Dictate";
|
||||
import { Empty, Flash, Key, Notice, PageHeader, Section } from "@/components/common";
|
||||
import { IncidentSettingsPanel, IncidentsSection } from "@/components/Incidents";
|
||||
import { ProjectErrors, type ErrorSearch } from "@/components/ProjectErrors";
|
||||
import { AutonomyPanel } from "@/components/Autonomy";
|
||||
import { NewRunnerForm, RunnerSettingsPanel } from "@/components/Runners";
|
||||
import { AgentModelPanel } from "@/components/AgentModel";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input, NativeSelect, Textarea } from "@/components/ui/input";
|
||||
import { SettingsDialog } from "@/components/SettingsDialog";
|
||||
import { PauseBanner, PauseControl } from "@/components/ProjectPause";
|
||||
import { ProjectSecretsPanel } from "@/components/ProjectSecrets";
|
||||
import { Workspace } from "@/components/Workspace";
|
||||
import { SubscriptionSetup } from "@/components/SubscriptionSetup";
|
||||
import { SubscriptionRequestButton } from "@/components/SubscriptionRequest";
|
||||
import { PoolSubscriptions, PoolSummary, PoolSwitches } from "@/components/PoolSubscriptions";
|
||||
import { requireUser, words } from "@/lib/auth";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { db } from "@/lib/db";
|
||||
import { addGoal, addProjectMember, addTask, grantRepoAccessToMembers, removeProjectMember } from "../../actions";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import { intlLocale, m, type Translator } from "@peppa/shared/i18n";
|
||||
import { board, projectForUserByKey, projectSessions } from "@/lib/queries";
|
||||
import { addProjectMember, addTask, deployProdAction, grantRepoAccessToMembers, removeProjectMember, saveReviewSettingsAction, saveIntakeSettingsAction, setProjectVisibilityAction, connectOwnSubscriptionAction, chooseSharedSubscriptionAction, removeOwnSubscriptionAction } from "../../actions";
|
||||
import { AgentsMdTab, CodeTab, EpicsPanel, EpicsTab, MemorySection, ProgressBar, PullsTab, SpecsTab } from "./tabs";
|
||||
import { setProjectPoolAction } from "../../subscriptions/actions";
|
||||
import { JournalFilters, JournalList, MetricsTab, ProjectBudgetPanel } from "@/components/Accounting";
|
||||
import { saveProjectBudgetAction } from "../../actions";
|
||||
// PEP-127: on its own line — the long @peppa/core import above is edited by every story.
|
||||
import { awaitingRollout, ROLLOUT_LABEL, delayedTaskIds, taskDelayLine, pendingQuestions, listPendingAccepts, PENDING_ACCEPT_LABEL, PLATFORM_DELAY_LABEL } from "@peppa/core";
|
||||
import { trashDaysLeft } from "@peppa/core";
|
||||
import { queuePositions, workLine } from "@peppa/core";
|
||||
import { WorkLine } from "@/components/WorkLine";
|
||||
import { deleteProjectAction } from "../../actions";
|
||||
import { DeleteProjectControl, mayDeleteProject, RestoreProjectButton } from "@/components/ProjectDelete";
|
||||
|
||||
export default async function ProjectPage({ params, searchParams }: { params: Promise<{ key: string }>; searchParams: Promise<{ error?: string; created?: string }> }) {
|
||||
const RELEASE_STATUS: Record<Release["status"], { label: string; tone: "info" | "ok" | "warn" | "danger" | "muted" }> = {
|
||||
deploying: { label: m("выкатывается"), tone: "info" },
|
||||
healthy: { label: m("работает"), tone: "ok" },
|
||||
rolled_back: { label: m("откат"), tone: "warn" },
|
||||
failed: { label: m("не поднялся"), tone: "danger" },
|
||||
removed: { label: m("удалён"), tone: "muted" },
|
||||
};
|
||||
|
||||
const TABS = [
|
||||
{ id: "board", label: m("Доска") },
|
||||
{ id: "epics", label: m("Эпики") },
|
||||
{ id: "code", label: m("Код") },
|
||||
{ id: "specs", label: m("Спеки") },
|
||||
{ id: "agents", label: "AGENTS.md" },
|
||||
{ id: "pulls", label: "PR" },
|
||||
{ id: "releases", label: m("Релизы") },
|
||||
{ id: "bugs", label: m("Баги") },
|
||||
{ id: "sessions", label: m("Сессии") },
|
||||
{ id: "metrics", label: m("Метрики") },
|
||||
{ id: "journal", label: m("Журнал") },
|
||||
] as const;
|
||||
|
||||
function EnvLine({ name, r, t }: { name: string; r: Release | null | undefined; t: Translator }) {
|
||||
return (
|
||||
<div className="flex min-w-0 flex-1 flex-col gap-0.5 rounded-md border bg-background/40 px-3 py-2">
|
||||
<span className="font-mono text-[11px] tracking-wider text-muted-foreground uppercase">{name}</span>
|
||||
{r ? (
|
||||
<span className="flex min-w-0 flex-wrap items-center gap-x-2 text-sm">
|
||||
<span className="font-mono">{r.sha.slice(0, 7)}</span>
|
||||
{r.host && (
|
||||
<a href={`https://${r.host}`} className="truncate text-primary">
|
||||
{r.host}
|
||||
</a>
|
||||
)}
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-sm text-muted-foreground">{t("нет")}</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default async function ProjectPage({ params, searchParams }: { params: Promise<{ key: string }>; searchParams: Promise<{ error?: string; created?: string; checked?: string; tab?: string; epic?: string; weeks?: string; actor?: string; channel?: string; edit?: string; saved?: string } & ErrorSearch> }) {
|
||||
const user = await requireUser();
|
||||
const { key } = await params;
|
||||
const { error, created } = await searchParams;
|
||||
const sp = await searchParams;
|
||||
const { error, created, checked, tab: tabParam, epic: epicParam, weeks, actor, channel, edit, saved } = sp;
|
||||
const t = await getT();
|
||||
// PEP-119: «Продакт» sees the board, epics and bugs; the developer's tabs belong to «Инженер».
|
||||
const w = await words();
|
||||
const engineer = w.engineer;
|
||||
const visibleTabs = engineer ? TABS : TABS.filter((x) => (PRODUCT_PROJECT_TABS as readonly string[]).includes(x.id));
|
||||
const tab = visibleTabs.find((x) => x.id === tabParam)?.id ?? "board";
|
||||
const p = await projectForUserByKey(user.id, key).catch(() => null);
|
||||
if (!p) notFound();
|
||||
const [{ goals, tasks }, sessions, team, repo] = await Promise.all([board(p.id), projectSessions(p.id), listMembers(db, p), describeRepo(db, p)]);
|
||||
const [{ tasks }, epics, sessions, team, repo, incidentSettings, sources, incidents, releases, current, reviewer, progress, deps, directOrigins] = await Promise.all([
|
||||
board(p.id),
|
||||
listEpics(db, p.id),
|
||||
projectSessions(p.id),
|
||||
listMembers(db, p),
|
||||
Promise.resolve(peekRepo(db, p)),
|
||||
getIncidentSettings(db, p.id),
|
||||
listErrorSources(db, p.id),
|
||||
listIncidents(db, p.id),
|
||||
listReleases(db, p.id, 15),
|
||||
currentReleases(db, p.id),
|
||||
getReviewSettings(db, p.id),
|
||||
epicProgress(db, p.id),
|
||||
blockersMap(db, p.id),
|
||||
getDirectOrigins(db, p.id),
|
||||
]);
|
||||
// Peppa itself has no staging: its prod candidate is the newest green main (PEP-18).
|
||||
const prodCandidate = isPlatform(p) ? ((await platformReleaseOffers(db)) ? await platformReleaseCandidate(db, p) : null) : (current.staging?.sha ?? null);
|
||||
const collaborators = new Set((repo.collaborators ?? []).map((l) => l.toLowerCase()));
|
||||
// Members who are not repo collaborators (only known when Gitea listed them; owners of the namespace see it anyway).
|
||||
const noRepoAccess = (login: string) =>
|
||||
repo.collaborators !== null && login.toLowerCase() !== p.giteaOwner.toLowerCase() && !collaborators.has(login.toLowerCase());
|
||||
const missingAccess = team.members.some((m) => noRepoAccess(m.login));
|
||||
const isOwner = p.ownerId === user.id;
|
||||
const back = `/p/${p.key}`;
|
||||
const groups = [...goals.map((g) => ({ goal: g })), { goal: null }];
|
||||
const goalTitle = new Map(goals.map((g) => [g.id, g.title]));
|
||||
const cards: Card[] = tasks.map((t) => ({
|
||||
key: `${p.key}-${t.number}`,
|
||||
title: t.title,
|
||||
status: t.status,
|
||||
column: columnOf(t.status),
|
||||
goal: t.goalId ? (goalTitle.get(t.goalId) ?? null) : null,
|
||||
}));
|
||||
return (
|
||||
<>
|
||||
<AutoRefresh />
|
||||
<Flash error={error} />
|
||||
{created && !error && (
|
||||
<Notice>
|
||||
Репозиторий создан: <a href={repo.url}>{repo.fullName}</a> ({repoVisibilityLabel(repo.private)}).{" "}
|
||||
<a href={repo.url} className="button small">Открыть в Gitea</a>
|
||||
</Notice>
|
||||
// PEP-67: default subscription pool; only a superadmin changes it.
|
||||
const superadmin = await isSuperadmin(db, user);
|
||||
// PEP-88: a superadmin manages any project like its owner.
|
||||
const isOwner = p.ownerId === user.id || superadmin;
|
||||
const [pool, pools, autonomy, shared] = await Promise.all([projectPool(db, p.id), superadmin ? listPools(db) : Promise.resolve([]), getAutonomy(db, p.id), sharedPool(db)]);
|
||||
// PEP-10/27: runner settings of the project over the system ones.
|
||||
const [runnerOwn, runnerSystem, secrets, runnerHosts] = await Promise.all([getProjectRunnerSettings(db, p.id), getSystemRunnerSettings(db), listProjectSecrets(db, p.id), listHosts(db, { enabled: true })]);
|
||||
// PEP-253: where secrets go and which of them are keys of catalog services.
|
||||
const [agentSecrets, secretReport] = await Promise.all([agentSecretsEnabled(db, p.id), secretsAgentReport(db, { projectIds: [p.id] })]);
|
||||
// PEP-41: agent provider/model of the project over the platform's.
|
||||
const [agentOwn, agentSystem] = await Promise.all([getProjectAgentSettings(db, p.id), getSystemAgentSettings(db)]);
|
||||
// PEP-31: the project's pool has no working subscription — agents won't start.
|
||||
const agentWarning = await projectAgentWarning(db, p.id);
|
||||
// PEP-174: the project on pause — a plaque on top, «Продолжить» instead of «Поставить на паузу».
|
||||
const pause = await getProjectPause(db, p.id);
|
||||
// PEP-107: each subscription of the pool — at work, free, limited until…, usage of its window.
|
||||
const poolView = pool ? await poolOverview(db, pool.id, new Date(), { admin: superadmin, userId: user.id }) : null;
|
||||
// PEP-80: the owner's own subscriptions — a ChatGPT device login in progress, and whether a pool exists already.
|
||||
const mayChoose = isOwner || superadmin;
|
||||
// PEP-128: a pool whose every sign-in failed or is unfinished is as good as no subscription —
|
||||
// the owner gets the connection wizard again, with what went wrong.
|
||||
const poolSubs = pool ? await poolSubscriptions(db, pool.id) : [];
|
||||
const connected = poolSubs.some((s) => s.status === "active" || s.status === "limited");
|
||||
const failedLogins = poolSubs.filter((s) => s.status === "auth_error").map((s) => ({ provider: s.provider, timedOut: /timed out/i.test(s.lastError ?? "") }));
|
||||
const [ownLogins, hasOwnPool] = await Promise.all([mayChoose && pool ? ownPendingLogins(db, pool.id) : Promise.resolve([]), mayChoose ? ownPool(db, user.id).then((x) => !!x) : Promise.resolve(false)]);
|
||||
// Epic filter (PEP-66): only an open epic of this project filters; anything else shows all.
|
||||
const epicFilter = epics.find((e) => String(e.id) === epicParam) ?? null;
|
||||
const boardHref = (epicId?: number) => (epicId ? `/p/${p.key}?epic=${epicId}` : `/p/${p.key}`);
|
||||
const back = tab === "board" ? boardHref(epicFilter?.id) : `/p/${p.key}?tab=${tab}`;
|
||||
const epicTitle = new Map(epics.map((e) => [e.id, e.title]));
|
||||
const agentNames = await taskAgentNames(db, p.id);
|
||||
const accepted = await listPendingAccepts(db);
|
||||
// PEP-278: accepted stories whose changes do not run yet.
|
||||
const rollout = await awaitingRollout(db, tasks.filter((x) => x.status === "done").map((x) => x.id));
|
||||
// PEP-150: the delay line — not on a story whose question waits for the owner.
|
||||
// PEP-209: the acceptance page — every story in review on one screen.
|
||||
const toAccept = tasks.filter((x) => x.status === "review" && !x.archivedAt).length;
|
||||
const delayed = await delayedTaskIds(db);
|
||||
if (delayed.size) for (const q of await pendingQuestions(db, p.id)) if (q.taskId != null) delayed.delete(q.taskId);
|
||||
// PEP-209: the card says when the next attempt comes (or that the administrator is told).
|
||||
const delayLines = new Map<number, string>();
|
||||
for (const id of delayed) {
|
||||
const line = await taskDelayLine(db, id);
|
||||
if (line) delayLines.set(id, line);
|
||||
}
|
||||
// PEP-182: stories waiting for a free agent, and «Делается · В очереди» above the board.
|
||||
const [queued, work] = tab === "board" ? await Promise.all([queuePositions(db, p.id), workLine(db, [p.id])]) : [new Map<number, number>(), null];
|
||||
const [intake, refining] = await Promise.all([getIntakeSettings(db, p.id), intakePendingTasks(db, p.id)]);
|
||||
// PEP-247: in work without an agent for a lawful reason (pause, no subscription, budget) — the card says why.
|
||||
const holds = tab === "board" ? await taskHoldReasons(db, p.id, tasks.filter((x) => x.status === "in_progress" && !agentNames.has(x.id) && !delayed.has(x.id) && !queued.has(x.id)).map((x) => x.id)) : new Map();
|
||||
const cards: Card[] = tasks
|
||||
.filter((x) => !epicFilter || x.goalId === epicFilter.id)
|
||||
.map((x) => {
|
||||
const pr = columnOf(x.status) === "in_progress" ? taskProgress(p, x.openspecChange) : null;
|
||||
return {
|
||||
key: `${p.key}-${x.number}`,
|
||||
id: x.id,
|
||||
title: x.title,
|
||||
status: x.status,
|
||||
column: columnOf(x.status),
|
||||
epic: x.goalId ? (epicTitle.get(x.goalId) ?? null) : null,
|
||||
// PEP-33: tasks.md progress of stories in work.
|
||||
progress: pr && { done: pr.done, total: pr.total, current: pr.current },
|
||||
blocked: x.status === "backlog" ? blockedLabel(deps.get(x.id)) : null,
|
||||
agent: agentNames.get(x.id) ?? null,
|
||||
accepted: accepted.has(x.id) ? t.text(PENDING_ACCEPT_LABEL) : null,
|
||||
rollout: rollout.has(x.id) ? t.text(ROLLOUT_LABEL) : null,
|
||||
delayed: delayed.has(x.id) && x.status !== "done" ? t.text(delayLines.get(x.id) ?? PLATFORM_DELAY_LABEL) : null,
|
||||
queued: queued.get(x.id) ?? null,
|
||||
hold: holds.has(x.id) ? t.text(holds.get(x.id)!.text) : null,
|
||||
proposed: x.proposed,
|
||||
severity: (x.severity as Card["severity"]) ?? null,
|
||||
agentMade: x.origin !== "human",
|
||||
refining: refining.has(x.id) ? (refining.get(x.id) === "waiting" ? t("ждёт ваших ответов") : t("уточняется")) : null,
|
||||
};
|
||||
});
|
||||
// Gitea and the working copy are read only for the open tab.
|
||||
const [code, pulls] = await Promise.all([tab === "code" ? repoOverview(db, p) : null, tab === "pulls" ? openPulls(db, p) : null]);
|
||||
const specs = tab === "specs" ? listSpecs(p) : [];
|
||||
const agentsMd = tab === "agents" ? await readAgentsMd(db, p) : null;
|
||||
const product = await projectProduct(db, p.id);
|
||||
const publish = await getPublishMode(db, p.id);
|
||||
const [productNeedList, productReview] = await Promise.all([productNeeds(db, p.id), lastProductReview(db, p.id)]);
|
||||
// The chat belongs to the project's people; a superadmin looking at someone else's project has none.
|
||||
const canChat = (await userProjectIds(db, user.id)).includes(p.id);
|
||||
const sharedReq = await sharedRequest(db, p.id);
|
||||
// PEP-186: agents stand on a limit or a broken sign-in — ask the superadmin for a subscription.
|
||||
const askOffer = await subscriptionRequestOffer(db, user, p.id).catch(() => null);
|
||||
// PEP-206: «Подписки» offers the request always (ahead of a limit, too).
|
||||
const askAhead = askOffer ? null : await subscriptionRequestOffer(db, user, p.id, new Date(), { always: true }).catch(() => null);
|
||||
const discussionNew = (await discussionUnread(db, user.id)).get((await ensureProjectChat(db, p.id)).id) ?? 0;
|
||||
const memory = tab === "specs" ? readMemory(p.workspacePath) : "";
|
||||
// PEP-47 metrics, PEP-48 journal, PEP-43 default budget.
|
||||
const metrics = tab === "metrics" ? await projectMetrics(db, p.id, { weeks: Number(weeks) || 8 }) : null;
|
||||
const journal = tab === "journal" ? await listJournal(db, { projectId: p.id, actorKind: (actor || undefined) as ActorKind | undefined, channel: (channel || undefined) as ActorChannel | undefined, limit: 200 }) : [];
|
||||
const projectBudget = await getProjectBudget(db, p.id);
|
||||
|
||||
const aside = (
|
||||
<div className="flex flex-col gap-6">
|
||||
<PanelSection title={t("Пауза")}>
|
||||
<p className="m-0 mb-2 text-xs text-muted-foreground">
|
||||
{pause ? t("Проект на паузе: агенты не работают, уведомлений нет.") : t("На паузе агенты не работают, а вы не получаете уведомлений по проекту.")}
|
||||
</p>
|
||||
<PauseControl projectId={p.id} back={back} paused={!!pause} />
|
||||
</PanelSection>
|
||||
{engineer && (
|
||||
<PanelSection title={t("Репозиторий")}>
|
||||
<dl className="m-0 grid grid-cols-[max-content_minmax(0,1fr)] gap-x-3 gap-y-1.5 text-sm">
|
||||
<dt className="text-muted-foreground">{t("Где")}</dt>
|
||||
<dd className="m-0 truncate">
|
||||
<a href={repo.url} className="text-primary">{repo.fullName}</a>
|
||||
</dd>
|
||||
<dt className="text-muted-foreground">{t("Пространство")}</dt>
|
||||
<dd className="m-0">
|
||||
{p.giteaOwner}
|
||||
{repo.ownerKind && <> — {repo.ownerKind === "org" ? t("организация") : t("личное")}</>}
|
||||
</dd>
|
||||
<dt className="text-muted-foreground">{t("Видимость")}</dt>
|
||||
<dd className="m-0">{t.text(repoVisibilityLabel(repo.private))}</dd>
|
||||
<dt className="text-muted-foreground">{t("Кто видит")}</dt>
|
||||
<dd className="m-0">{t.text(repoAudience(repo))}</dd>
|
||||
<dt className="text-muted-foreground">{t("Рабочая копия")}</dt>
|
||||
<dd className="m-0 font-mono text-xs break-all">{p.workspacePath}</dd>
|
||||
</dl>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button asChild size="sm">
|
||||
<a href={repo.url}>
|
||||
{t("Открыть в Gitea")} <ExternalLink />
|
||||
</a>
|
||||
</Button>
|
||||
{isOwner && repo.private !== null && (
|
||||
<form action={setProjectVisibilityAction}>
|
||||
<Hidden fields={{ projectId: p.id, visibility: repo.private ? "public" : "private", back }} />
|
||||
<Button size="sm" variant="outline">{repo.private ? t("Сделать публичным") : t("Сделать приватным")}</Button>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
{isOwner && repo.private !== null && (
|
||||
<p className="m-0 text-xs text-muted-foreground">
|
||||
{repo.private ? t("Публичный репозиторий видят все, у кого есть доступ к Gitea.") : t("Приватный репозиторий видят только владелец пространства, соавторы и peppa-bot.")} {t("Видимость меняется в Gitea сразу.")}
|
||||
</p>
|
||||
)}
|
||||
</PanelSection>
|
||||
)}
|
||||
<h1>
|
||||
<span className="mono">{p.key}</span> {p.name}
|
||||
</h1>
|
||||
<p className="muted">
|
||||
<a href={repo.url}>{repo.fullName}</a> · {repoVisibilityLabel(repo.private)}
|
||||
</p>
|
||||
|
||||
<Board cards={cards} back={back} />
|
||||
<PanelSection title={t("Автономность")}>
|
||||
<AutonomyPanel projectId={p.id} settings={autonomy} back={back} engineer={engineer} />
|
||||
</PanelSection>
|
||||
|
||||
{groups.map(({ goal }) => (
|
||||
<details key={goal?.id ?? "none"} className="add">
|
||||
<summary>+ Задача{goal ? ` · 🎯 ${goal.title}` : " без цели"}</summary>
|
||||
<form action={addTask} className="stack">
|
||||
<input type="hidden" name="projectId" value={p.id} />
|
||||
<input type="hidden" name="back" value={back} />
|
||||
{goal && <input type="hidden" name="goalId" value={goal.id} />}
|
||||
<input type="text" name="title" required placeholder="Что сделать" aria-label="Название задачи" />
|
||||
<textarea name="description" rows={3} placeholder="Описание: контекст, критерии готовности" aria-label="Описание задачи" />
|
||||
<button className="primary">Создать задачу</button>
|
||||
</form>
|
||||
</details>
|
||||
))}
|
||||
<PanelSection title={t("Показывать всем")}>
|
||||
<PublishPanel projectId={p.id} mode={publish} back={back} />
|
||||
</PanelSection>
|
||||
|
||||
<section>
|
||||
<details>
|
||||
<summary>+ Цель</summary>
|
||||
<form action={addGoal} className="stack">
|
||||
<input type="hidden" name="projectId" value={p.id} />
|
||||
<input type="hidden" name="back" value={back} />
|
||||
<input type="text" name="title" required placeholder="Верхнеуровневая цель" aria-label="Название цели" />
|
||||
<textarea name="description" rows={3} placeholder="Зачем и какой результат" aria-label="Описание цели" />
|
||||
<button className="primary">Создать цель</button>
|
||||
</form>
|
||||
</details>
|
||||
</section>
|
||||
{engineer && (
|
||||
<PanelSection title={t("Раннеры")}>
|
||||
<RunnerSettingsPanel projectId={p.id} own={runnerOwn} inherited={{ ...DEFAULT_RUNNER_SETTINGS, ...runnerSystem }} back={back} hosts={runnerHosts} />
|
||||
</PanelSection>
|
||||
)}
|
||||
|
||||
<section>
|
||||
<h2>Участники</h2>
|
||||
<ul className="members">
|
||||
<li>
|
||||
<span><b>{team.owner?.login ?? "—"}</b> <span className="muted">владелец · агенты работают на его подписке Claude</span></span>
|
||||
{/* glossary-ignore: раздел виден только в виде «Инженер» */}
|
||||
{engineer && (
|
||||
<PanelSection title={t("Модель агента")}>
|
||||
<AgentModelPanel projectId={p.id} own={agentOwn} inherited={{ ...DEFAULT_AGENT_SETTINGS, ...agentSystem }} back={back} />
|
||||
</PanelSection>
|
||||
)}
|
||||
|
||||
<PanelSection title={t("Эпики")} count={epics.length}>
|
||||
<EpicsPanel w={w} projectId={p.id} projectKey={p.key} epics={epics} progress={progress} back={back} />
|
||||
</PanelSection>
|
||||
|
||||
<PanelSection title={t("Секреты")} count={secrets.length}>
|
||||
<ProjectSecretsPanel
|
||||
projectId={p.id}
|
||||
secrets={secrets}
|
||||
back={back}
|
||||
agentsEnabled={agentSecrets}
|
||||
services={new Map(secretReport.map((r) => [r.name, { serviceName: r.serviceName, connectionName: r.connectionName }]))}
|
||||
hints={secretNameHints()}
|
||||
engineer={engineer}
|
||||
/>
|
||||
</PanelSection>
|
||||
|
||||
{engineer && (
|
||||
<PanelSection title={t("Бюджет стори")}>
|
||||
<ProjectBudgetPanel projectId={p.id} budget={projectBudget} back={back} action={saveProjectBudgetAction} />
|
||||
</PanelSection>
|
||||
)}
|
||||
|
||||
<PanelSection title={t("Аналитик на входе задачи")}>
|
||||
<form action={saveIntakeSettingsAction} className="flex flex-col gap-2.5">
|
||||
<Hidden fields={{ projectId: p.id, back }} />
|
||||
<label className="flex items-center gap-2 text-sm">
|
||||
<input type="checkbox" name="enabled" defaultChecked={intake.enabled} className="size-4 accent-primary" />
|
||||
{t("Новые {tasks} сначала разбирает аналитик", { tasks: w.task("accPl") })}
|
||||
</label>
|
||||
<Button size="sm" className="self-start">{t("Сохранить")}</Button>
|
||||
</form>
|
||||
<p className="m-0 text-xs text-muted-foreground">
|
||||
{t("Аналитик решает, зачем это и что берём в первую версию, делит большое (не больше четырёх частей) и пишет критерии приёмки. Вопросов не задаёт: развилки решает сам и показывает решения на странице задачи — «Фабрика решила за вас». {Tasks}, созданные до включения, не трогает.", { Tasks: w.Task("pl") })}
|
||||
</p>
|
||||
</PanelSection>
|
||||
|
||||
{engineer && (
|
||||
<PanelSection title={t("Ревьюер")}>
|
||||
<form action={saveReviewSettingsAction} className="flex flex-col gap-2.5">
|
||||
<Hidden fields={{ projectId: p.id, back }} />
|
||||
<label className="flex items-center gap-2 text-sm">
|
||||
<input type="checkbox" name="enabled" defaultChecked={reviewer.enabled} className="size-4 accent-primary" />
|
||||
{t("Агент-ревьюер читает дифф до ревью PM")}
|
||||
</label>
|
||||
<label className="flex items-center gap-2 text-sm">
|
||||
{t("Возвратов агенту не больше")}
|
||||
<Input type="number" name="maxIterations" min={1} max={10} defaultValue={reviewer.maxIterations} aria-label={t("Лимит итераций ревьюера")} className="h-8 w-20" />
|
||||
</label>
|
||||
<Textarea
|
||||
name="rules"
|
||||
rows={3}
|
||||
defaultValue={reviewer.rules ?? ""}
|
||||
aria-label={t("Дополнительные правила ревьюера")}
|
||||
placeholder={t("Дополнительные правила ревьюера: например, «новые эндпоинты — только с проверкой доступа», «без новых зависимостей»")}
|
||||
/>
|
||||
<Button size="sm" className="self-start">{t("Сохранить")}</Button>
|
||||
</form>
|
||||
<p className="m-0 text-xs text-muted-foreground">
|
||||
{t("Когда проверки PR зелёные и агент отдаёт стори в ревью, короткая сессия Claude (sonnet, на подписке пула проекта) читает дифф по чек-листу. Замечания уходят агенту, «ок» — стори к вам с резюме ревьюера. После лимита возвратов стори приходит к вам с незакрытыми замечаниями.")}
|
||||
</p>
|
||||
</PanelSection>
|
||||
)}
|
||||
|
||||
<PanelSection title={t("Баги")}>
|
||||
<IncidentSettingsPanel
|
||||
w={w}
|
||||
projectId={p.id}
|
||||
back={back}
|
||||
isOwner={isOwner}
|
||||
direct={directOrigins.includes("incident")}
|
||||
settings={incidentSettings}
|
||||
sources={sources}
|
||||
webhookUrl={incidentSettings ? `${bugsinkWebhookBase()}/api/hooks/bugsink/${incidentSettings.hookSecret}` : null}
|
||||
/>
|
||||
</PanelSection>
|
||||
|
||||
<PanelSection title={t("Участники")} count={team.members.length + 1}>
|
||||
<ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm">
|
||||
<li className="flex flex-col rounded-md px-2 py-1.5">
|
||||
<span className="font-medium">{team.owner?.login ?? "—"}</span>
|
||||
<span className="text-xs text-muted-foreground">{t("владелец")}</span>
|
||||
</li>
|
||||
{team.members.map((m) => (
|
||||
<li key={m.id}>
|
||||
<span>
|
||||
{m.login} <span className="muted">участник</span>
|
||||
{noRepoAccess(m.login) && <span className="muted"> · нет доступа к репозиторию</span>}
|
||||
<li key={m.id} className="flex items-center gap-2 rounded-md px-2 py-1.5">
|
||||
<span className="flex min-w-0 flex-1 flex-col">
|
||||
<span>{m.login}</span>
|
||||
<span className="text-xs text-muted-foreground">{t("участник")}{engineer && noRepoAccess(m.login) && " · " + t("нет доступа к репозиторию")}</span>
|
||||
</span>
|
||||
{(isOwner || m.id === user.id) && (
|
||||
<form action={removeProjectMember}>
|
||||
<input type="hidden" name="projectId" value={p.id} />
|
||||
<input type="hidden" name="login" value={m.login} />
|
||||
<input type="hidden" name="back" value={back} />
|
||||
<button className="small danger">{m.id === user.id ? "Выйти из проекта" : "Убрать"}</button>
|
||||
<Hidden fields={{ projectId: p.id, login: m.login, back }} />
|
||||
<Button size="xs" variant="destructive">{m.id === user.id ? t("Выйти из проекта") : t("Убрать")}</Button>
|
||||
</form>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
{team.invites.map((login) => (
|
||||
<li key={login}>
|
||||
<span>{login} <span className="muted">приглашён · появится после первого входа в Пеппу</span></span>
|
||||
<li key={login} className="flex items-center gap-2 rounded-md px-2 py-1.5">
|
||||
<span className="flex min-w-0 flex-1 flex-col">
|
||||
<span>{login}</span>
|
||||
<span className="text-xs text-muted-foreground">{t("приглашён · появится после первого входа в FORGE")}</span>
|
||||
</span>
|
||||
{isOwner && (
|
||||
<form action={removeProjectMember}>
|
||||
<input type="hidden" name="projectId" value={p.id} />
|
||||
<input type="hidden" name="login" value={login} />
|
||||
<input type="hidden" name="back" value={back} />
|
||||
<button className="small danger">Отозвать</button>
|
||||
<Hidden fields={{ projectId: p.id, login, back }} />
|
||||
<Button size="xs" variant="destructive">{t("Отозвать")}</Button>
|
||||
</form>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
{isOwner && (
|
||||
<form action={addProjectMember} className="row">
|
||||
<input type="hidden" name="projectId" value={p.id} />
|
||||
<input type="hidden" name="back" value={back} />
|
||||
<input type="text" name="login" required placeholder="Логин в Gitea" aria-label="Логин участника в Gitea" />
|
||||
<button>Добавить участника</button>
|
||||
<form action={addProjectMember} className="flex gap-2">
|
||||
<Hidden fields={{ projectId: p.id, back }} />
|
||||
<Input name="login" required placeholder={engineer ? t("Логин в Gitea") : t("Логин участника")} aria-label={engineer ? t("Логин участника в Gitea") : t("Логин участника")} className="h-8" />
|
||||
<Button size="sm">{t("Добавить участника")}</Button>
|
||||
</form>
|
||||
)}
|
||||
{isOwner && missingAccess && (
|
||||
{engineer && isOwner && missingAccess && (
|
||||
<form action={grantRepoAccessToMembers}>
|
||||
<input type="hidden" name="projectId" value={p.id} />
|
||||
<input type="hidden" name="back" value={back} />
|
||||
<button>Выдать доступ участникам</button>
|
||||
<Hidden fields={{ projectId: p.id, back }} />
|
||||
<Button size="sm">{t("Выдать доступ участникам")}</Button>
|
||||
</form>
|
||||
)}
|
||||
{isOwner && (
|
||||
<p className="muted">
|
||||
Участник видит доску и входящие, двигает карточки и отвечает агентам; получает доступ на запись к репозиторию.
|
||||
</p>
|
||||
{isOwner && <p className="m-0 text-xs text-muted-foreground">{engineer ? t("Участник видит доску и входящие, двигает карточки и отвечает агентам; получает доступ на запись к репозиторию.") : t("Участник видит доску и входящие, двигает карточки и отвечает агентам.")}</p>}
|
||||
</PanelSection>
|
||||
|
||||
<PanelSection title={t("Подписки")}>
|
||||
<p className="m-0 text-sm" id="subscription">
|
||||
{pool ? (
|
||||
shared?.id === pool.id ? (
|
||||
<>
|
||||
{t("Агенты работают на")} <b>{t("подписке FORGE")}</b> {t("— общей для пользователей фабрики. Свою подписку можно подключить в любой момент ниже.")}
|
||||
</>
|
||||
) : (
|
||||
<>{superadmin ? t("Агенты работают на подписке проекта — пул «{name}».", { name: pool.name }) : t("Агенты работают на подписке проекта.")}</>
|
||||
)
|
||||
) : agentWarning ? (
|
||||
<b>{t("Подписка не выбрана — агенты не запустятся.")}</b>
|
||||
) : (
|
||||
engineer ? t("Пул не назначен — агенты работают на входе машины.") : t("Своя подписка не подключена — агенты работают на общей.")
|
||||
)}
|
||||
</p>
|
||||
{askOffer && (
|
||||
<div className="flex flex-wrap items-center gap-2 text-sm">
|
||||
<span>{t("Агенты стоят — администратор может одолжить свою подписку на время.")}</span>
|
||||
<SubscriptionRequestButton projectId={p.id} offer={askOffer} back={`${back}#subscription`} />
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
{askAhead && (
|
||||
<div className="flex flex-wrap items-center gap-2 text-sm" data-subscription-ahead>
|
||||
<span>{t("Нужна ещё подписка? Администратор может одолжить свою на время.")}</span>
|
||||
<SubscriptionRequestButton projectId={p.id} offer={askAhead} back={`${back}#subscription`} ahead />
|
||||
</div>
|
||||
)}
|
||||
{/* PEP-116: on the factory's subscription a user sees its state, not the accounts behind it. */}
|
||||
{poolView && (superadmin || poolView.pool.id !== shared?.id) && (
|
||||
<>
|
||||
<PoolSubscriptions
|
||||
o={poolView}
|
||||
action={(s) =>
|
||||
mayChoose && !s.loan && (s.createdBy === user.id || superadmin) && poolView.pool.id !== shared?.id ? (
|
||||
<form action={removeOwnSubscriptionAction}>
|
||||
<Hidden fields={{ projectId: p.id, subscriptionId: s.id, back }} />
|
||||
<Button size="xs" variant="ghost" className="text-muted-foreground">{t("Убрать")}</Button>
|
||||
</form>
|
||||
) : null
|
||||
}
|
||||
/>
|
||||
<PoolSummary o={poolView} />
|
||||
<PoolSwitches o={poolView} />
|
||||
</>
|
||||
)}
|
||||
{superadmin && pool && pool.id === shared?.id && (
|
||||
// PEP-164: the factory's pool is filled on «Подписки» — straight to this pool's card.
|
||||
<a href={`/subscriptions#pool-${pool.id}`} className="self-start text-sm font-medium text-primary">{t("Добавить ещё одну подписку")} →</a>
|
||||
)}
|
||||
{mayChoose && pool && pool.id !== shared?.id && (
|
||||
<div className="flex flex-wrap gap-2" aria-label={t("Добавить подписку")}>
|
||||
<form action={connectOwnSubscriptionAction}>
|
||||
<Hidden fields={{ projectId: p.id, kind: "claude_login", back }} />
|
||||
<Button size="sm" variant="outline">{t("Добавить ещё Claude")}</Button>
|
||||
</form>
|
||||
<form action={connectOwnSubscriptionAction}>
|
||||
<Hidden fields={{ projectId: p.id, kind: "codex_login", back }} />
|
||||
<Button size="sm" variant="outline">{t("Добавить ещё ChatGPT")}</Button>
|
||||
</form>
|
||||
<span className="basis-full text-xs text-muted-foreground">{t("Две и больше подписок — агенты не ждут лимита: упёрлась одна — продолжают на другой, в том числе Claude ↔ ChatGPT.")}</span>
|
||||
</div>
|
||||
)}
|
||||
{(isOwner || superadmin) && (
|
||||
<>
|
||||
{shared && shared.id !== pool?.id && (
|
||||
<form action={chooseSharedSubscriptionAction}>
|
||||
<Hidden fields={{ projectId: p.id, back }} />
|
||||
<Button size="sm" variant={pool ? "outline" : "default"} disabled={!!sharedReq && !superadmin}>
|
||||
{superadmin ? t("Перейти на подписку FORGE") : sharedReq ? t("Запрос на подписку FORGE отправлен") : t("Попросить подписку FORGE")}
|
||||
</Button>
|
||||
{!superadmin && <span className="text-xs text-muted-foreground">{sharedReq ? t("Ждём подтверждения администратора фабрики — придёт сообщение.") : t("Нужно подтверждение администратора фабрики.")}</span>}
|
||||
</form>
|
||||
)}
|
||||
{engineer ? (
|
||||
<form action={connectOwnSubscriptionAction} className="flex flex-col gap-2">
|
||||
<Hidden fields={{ projectId: p.id, back }} />
|
||||
<NativeSelect name="kind" defaultValue="claude_login" aria-label={t("Что подключить")} className="h-8">
|
||||
<option value="claude_login">{t("Claude — вход по ссылке")}</option>
|
||||
<option value="codex_login">{t("ChatGPT — вход по ссылке и коду")}</option>
|
||||
<option value="claude">{t("Claude — готовый токен (claude setup-token)")}</option>
|
||||
<option value="codex_key">{t("Codex — ключ OpenAI API")}</option>
|
||||
{hasOwnPool && <option value="existing">{t("Моя уже подключённая подписка")}</option>}
|
||||
</NativeSelect>
|
||||
<Input name="secret" type="password" autoComplete="off" placeholder={t("Токен Claude или ключ OpenAI (для входа по ссылке не нужен)")} aria-label={t("Токен или ключ своей подписки")} className="h-8 font-mono" />
|
||||
<Button size="sm" variant={pool ? "outline" : "default"} className="self-start">{t("Подключить свою подписку")}</Button>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{t("Вход по ссылке: поле оставьте пустым — на странице проекта появятся шаги. Готовый токен Claude выдаёт")} <span className="font-mono">claude setup-token</span>{" "}
|
||||
{t("на вашем компьютере. Токены и ключи хранятся зашифрованными, показать их нельзя.")}
|
||||
</span>
|
||||
</form>
|
||||
) : (
|
||||
!pool || pool.id === shared?.id ? (
|
||||
<div className="flex flex-wrap gap-2" aria-label={t("Подключить свою подписку")}>
|
||||
<form action={connectOwnSubscriptionAction}>
|
||||
<Hidden fields={{ projectId: p.id, kind: "claude_login", back }} />
|
||||
<Button size="sm" variant={pool ? "outline" : "default"}>{t("Подключить Claude")}</Button>
|
||||
</form>
|
||||
<form action={connectOwnSubscriptionAction}>
|
||||
<Hidden fields={{ projectId: p.id, kind: "codex_login", back }} />
|
||||
<Button size="sm" variant="outline">{t("Подключить ChatGPT")}</Button>
|
||||
</form>
|
||||
<span className="basis-full text-xs text-muted-foreground">{t("Подойдёт обычная платная подписка. После нажатия на странице проекта появятся шаги — это одна минута.")}</span>
|
||||
</div>
|
||||
) : null
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{superadmin && (
|
||||
<form action={setProjectPoolAction} className="flex gap-2">
|
||||
<Hidden fields={{ projectKey: p.key, back }} />
|
||||
<NativeSelect name="poolId" defaultValue={pool?.id ?? ""} aria-label={t("Пул подписок по умолчанию")} className="h-8">
|
||||
<option value="">{t("Без пула — вход машины")}</option>
|
||||
{pools.map((x) => (
|
||||
<option key={x.id} value={x.id}>{x.name}</option>
|
||||
))}
|
||||
</NativeSelect>
|
||||
<Button size="sm">{t("Сохранить")}</Button>
|
||||
</form>
|
||||
)}
|
||||
{engineer && <p className="m-0 text-xs text-muted-foreground">{t("Раннеры проекта стартуют на свободной подписке пула.")} {superadmin ? <a href="/subscriptions#pools" className="text-primary">{t("Пулы и подписки")}</a> : t("Выбирает владелец проекта.")}</p>}
|
||||
</PanelSection>
|
||||
{mayDeleteProject(p, user.id, superadmin) && (
|
||||
<PanelSection title={t("Удалить проект")}>
|
||||
<p className="m-0 text-xs text-muted-foreground">{t("Проект пропадёт из вашего списка, а агенты остановятся. Ещё неделю он хранится у администратора FORGE — если передумаете, попросите вернуть его. Потом проект удаляется насовсем.")}</p>
|
||||
<form action={deleteProjectAction} className="flex flex-col gap-2">
|
||||
<Hidden fields={{ projectId: p.id, back }} />
|
||||
<label className="flex items-center gap-2 text-sm">
|
||||
<input type="checkbox" name="confirm" value="yes" required />
|
||||
{t("Да, удалить проект {name}", { name: p.name })}
|
||||
</label>
|
||||
<Button size="sm" variant="destructive" className="self-start">{t("Удалить проект")}</Button>
|
||||
</form>
|
||||
</PanelSection>
|
||||
)}
|
||||
{!engineer && <p className="m-0 text-xs text-muted-foreground">{t("Настройки для разработчиков — код проекта, настройки и расход агентов — открываются в виде «Инженер»:")} <a href="/settings#mode" className="text-primary">{t("Настройки → Вид FORGE")}</a>.</p>}
|
||||
</div>
|
||||
);
|
||||
|
||||
<section>
|
||||
<h2>Репозиторий</h2>
|
||||
<dl className="repo">
|
||||
<dt>Где</dt>
|
||||
<dd>
|
||||
<a href={repo.url}>{repo.fullName}</a> · <a href={repo.url}>Открыть в Gitea</a>
|
||||
</dd>
|
||||
<dt>Пространство</dt>
|
||||
<dd>
|
||||
{p.giteaOwner}
|
||||
{repo.ownerKind && ` — ${repo.ownerKind === "org" ? "организация" : "личное"}`}
|
||||
</dd>
|
||||
<dt>Видимость</dt>
|
||||
<dd>{repoVisibilityLabel(repo.private)}</dd>
|
||||
<dt>Кто видит</dt>
|
||||
<dd>{repoAudience(repo)}</dd>
|
||||
<dt>Рабочая копия</dt>
|
||||
<dd className="mono">{p.workspacePath}</dd>
|
||||
</dl>
|
||||
</section>
|
||||
const newTask = (
|
||||
<form action={addTask} className="flex flex-col gap-2">
|
||||
<Hidden fields={{ projectId: p.id, back }} />
|
||||
<Input name="title" required placeholder={t("Что сделать")} aria-label={t("Название {task}", { task: w.task("gen") })} />
|
||||
<Textarea id="new-story-description" name="description" rows={5} placeholder={t("Описание: кому и зачем, критерии готовности")} aria-label={t("Описание {task}", { task: w.task("gen") })} />
|
||||
<Dictate target="new-story-description" className="self-start" />
|
||||
<AttachField projectId={p.id} target="new-story-description" />
|
||||
<NativeSelect name="epicId" defaultValue={epicFilter ? String(epicFilter.id) : ""} aria-label={t("Эпик")}>
|
||||
<option value="">{t("Без эпика")}</option>
|
||||
{epics.map((e) => (
|
||||
<option key={e.id} value={e.id}>
|
||||
{e.title}
|
||||
</option>
|
||||
))}
|
||||
</NativeSelect>
|
||||
<Button variant="default" size="sm" className="self-start">{t("Создать {task}", { task: w.task("acc") })}</Button>
|
||||
</form>
|
||||
);
|
||||
const tabCount: Partial<Record<(typeof TABS)[number]["id"], number>> = { board: tasks.length, epics: epics.length, bugs: incidents.length, sessions: sessions.length };
|
||||
|
||||
<section>
|
||||
<h2>Сессии</h2>
|
||||
{sessions.length === 0 ? <p className="empty">Сессий ещё не было.</p> : sessions.map((s) => <SessionCard key={s.id} s={s} back={back} />)}
|
||||
</section>
|
||||
</>
|
||||
return (
|
||||
<Workspace aside={null} wide>
|
||||
<LiveRefresh scope={`project:${p.id}`} />
|
||||
<Flash error={error} />
|
||||
{p.deletedAt && (
|
||||
<div className="flex flex-wrap items-center gap-3 rounded-lg border border-destructive/50 bg-destructive/10 px-4 py-3 text-sm">
|
||||
<span>{t("Проект удалён. Он хранится ещё {days} дн., потом исчезнет насовсем.", { days: trashDaysLeft(p) })}</span>
|
||||
{superadmin && <RestoreProjectButton projectId={p.id} back={back} />}
|
||||
</div>
|
||||
)}
|
||||
{created && !error && !engineer && <Notice>{t("Проект создан. Напишите первую задачу — кнопка «Задача» справа вверху.")}</Notice>}
|
||||
{created && !error && engineer && (
|
||||
<Notice>
|
||||
{t("Репозиторий создан:")} <a href={repo.url} className="text-primary">{repo.fullName}</a> ({t.text(repoVisibilityLabel(repo.private))}).
|
||||
<Button asChild size="xs">
|
||||
<a href={repo.url}>{t("Открыть в Gitea")}</a>
|
||||
</Button>
|
||||
</Notice>
|
||||
)}
|
||||
<PageHeader
|
||||
actions={
|
||||
<>
|
||||
{toAccept > 0 && (
|
||||
<Link href={`/p/${p.key}/accept`} className="inline-flex h-9 items-center gap-1 rounded-md bg-primary px-4 text-sm font-medium text-primary-foreground hover:bg-primary/90" data-accept-link>
|
||||
{t("Принять работу · {n}", { n: toAccept })}
|
||||
</Link>
|
||||
)}
|
||||
<SettingsDialog title={t("Новая {task}", { task: w.task() })} trigger={<><Plus />{w.Task()}</>}>
|
||||
{newTask}
|
||||
</SettingsDialog>
|
||||
{!pause && <PauseControl projectId={p.id} back={back} paused={false} popover />}
|
||||
{mayDeleteProject(p, user.id, superadmin) && <DeleteProjectControl project={p} back={back} popover />}
|
||||
<SettingsDialog title={t("Настройки проекта")}>{aside}</SettingsDialog>
|
||||
</>
|
||||
}
|
||||
crumbs={<a href="/projects" className="text-muted-foreground hover:text-foreground">{t("Проекты")}</a>}
|
||||
title={
|
||||
<>
|
||||
<span className="rounded-md bg-muted px-2 font-mono text-primary">{p.key}</span> {p.name}
|
||||
</>
|
||||
}
|
||||
>
|
||||
{engineer && <><a href={repo.url} className="text-primary">{repo.fullName}</a> · {t.text(repoVisibilityLabel(repo.private))}</>}
|
||||
</PageHeader>
|
||||
|
||||
{pause && <PauseBanner projectId={p.id} back={back} since={pause.since} />}
|
||||
{mayChoose && (ownLogins.length > 0 || (agentWarning && !connected)) && (
|
||||
<SubscriptionSetup projectId={p.id} back={back} logins={ownLogins} checked={checked === "1"} extra={!agentWarning} shared={!!shared} requested={!!sharedReq} direct={superadmin} failed={failedLogins} />
|
||||
)}
|
||||
{agentWarning && !(mayChoose && (ownLogins.length > 0 || !pool || !connected)) && (
|
||||
<p role="alert" className="mb-4 flex flex-wrap items-center gap-2 rounded-lg border border-warn/40 bg-warn/10 px-4 py-3 text-sm">
|
||||
<span className="font-medium">{t("Агенты не запустятся:")}</span> {t.text(agentWarning)}.
|
||||
{pool ? (superadmin ? <a href={`/subscriptions#pool-${pool.id}`} className="text-primary">{t("Добавить ещё одну подписку")} →</a> : <span className="text-muted-foreground">{t("Смените подписку в «⋯ Настройки проекта → Подписки» или попросите суперадмина проверить её.")}</span>) : null}
|
||||
{askOffer && <SubscriptionRequestButton projectId={p.id} offer={askOffer} back={back} />}
|
||||
</p>
|
||||
)}
|
||||
{/* Кнопка «Попросить подписку у администратора» видна на странице проекта всегда, не только в «⋯ Настройки проекта». */}
|
||||
{askAhead && (
|
||||
<div className="mb-4 flex flex-wrap items-center gap-2 text-sm text-muted-foreground" data-subscription-request-page>
|
||||
<span>{t("Нужна ещё подписка? Администратор может одолжить свою на время.")}</span>
|
||||
<SubscriptionRequestButton projectId={p.id} offer={askAhead} back={back} ahead />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{tab === "board" && <ProductCard product={product} projectKey={p.key} chat={canChat} engineer={engineer} projectId={p.id} needs={productNeedList} review={productReview} back={back} publish={publish} />}
|
||||
<nav aria-label={t("Разделы проекта")} className="-mt-2 mb-4 flex gap-1 overflow-x-auto border-b">
|
||||
{visibleTabs.map((x) => (
|
||||
<Fragment key={x.id}>
|
||||
<a
|
||||
href={x.id === "board" ? `/p/${p.key}` : `/p/${p.key}?tab=${x.id}`}
|
||||
aria-current={tab === x.id ? "page" : undefined}
|
||||
className={cn(
|
||||
"-mb-px flex items-center gap-1.5 border-b-2 px-3 py-2 text-sm whitespace-nowrap text-muted-foreground hover:text-foreground hover:no-underline",
|
||||
tab === x.id ? "border-primary text-foreground" : "border-transparent",
|
||||
)}
|
||||
>
|
||||
{t(x.label)}
|
||||
{!!tabCount[x.id] && <span className="rounded-full bg-muted px-1.5 font-mono text-[11px] tabular-nums">{tabCount[x.id]}</span>}
|
||||
</a>
|
||||
{/* PEP-106: the people's chat of the project lives in «Чаты»; the link sits right after the board. */}
|
||||
{x.id === "board" && canChat && (
|
||||
<a href={`/chats/${p.key}`} className="-mb-px flex items-center gap-1.5 border-b-2 border-transparent px-3 py-2 text-sm whitespace-nowrap text-muted-foreground hover:text-foreground hover:no-underline">
|
||||
{t("Чат с аналитиком")}
|
||||
{discussionNew > 0 && <span className="rounded-full bg-info px-1.5 font-mono text-[11px] text-background tabular-nums">{discussionNew}</span>}
|
||||
</a>
|
||||
)}
|
||||
</Fragment>
|
||||
))}
|
||||
</nav>
|
||||
|
||||
{tab === "board" && (
|
||||
<>
|
||||
{epics.length > 0 && (
|
||||
<nav aria-label={t("Фильтр по эпику")} className="mb-3 flex flex-wrap items-center gap-1.5 text-sm">
|
||||
<a href={`/p/${p.key}?tab=epics`} className="text-xs text-muted-foreground" title={t("Эпик — большая цель; карточки на доске — {tasks}, шаги к ней", { tasks: w.task("pl") })}>{t("Эпики:")}</a>
|
||||
{[{ id: 0, title: t("все") }, ...epics].map((e) => {
|
||||
const active = (epicFilter?.id ?? 0) === e.id;
|
||||
return (
|
||||
<a
|
||||
key={e.id}
|
||||
href={boardHref(e.id || undefined)}
|
||||
aria-current={active ? "page" : undefined}
|
||||
className={cn("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs hover:no-underline", active ? "border-primary bg-primary/12 text-primary" : "text-muted-foreground hover:text-foreground")}
|
||||
>
|
||||
{e.title}
|
||||
{e.id > 0 && (
|
||||
<span className="ml-1.5 inline-flex items-center gap-1 font-mono text-[10px] tabular-nums" title={t("Готово {progress}", { progress: progressLabel(progress.get(e.id)) })}>
|
||||
<ProgressBar done={progress.get(e.id)?.done ?? 0} total={progress.get(e.id)?.total ?? 0} className="w-8" />
|
||||
{progressLabel(progress.get(e.id))}
|
||||
</span>
|
||||
)}
|
||||
</a>
|
||||
);
|
||||
})}
|
||||
{epicFilter && (
|
||||
<a href={`/p/${p.key}/plan/${epicFilter.id}`} className="ml-auto text-xs text-primary">
|
||||
{t("Спланировать {tasks} эпика", { tasks: w.task("accPl") })} →
|
||||
</a>
|
||||
)}
|
||||
</nav>
|
||||
)}
|
||||
{work && <WorkLine line={work} className="mb-2" />}
|
||||
<Board cards={cards} back={back} />
|
||||
</>
|
||||
)}
|
||||
|
||||
{tab === "epics" && (
|
||||
<EpicsTab
|
||||
w={w}
|
||||
projectId={p.id}
|
||||
projectKey={p.key}
|
||||
epics={epics}
|
||||
stories={tasks.map((x) => ({ key: `${p.key}-${x.number}`, title: x.title, status: x.status, goalId: x.goalId }))}
|
||||
progress={progress}
|
||||
back={back}
|
||||
/>
|
||||
)}
|
||||
|
||||
{tab === "code" && code && <CodeTab code={code} />}
|
||||
|
||||
{tab === "specs" && (
|
||||
<>
|
||||
<MemorySection text={memory} {...memoryStats(memory)} />
|
||||
<SpecsTab specs={specs} />
|
||||
</>
|
||||
)}
|
||||
|
||||
{tab === "agents" && agentsMd && <AgentsMdTab projectId={p.id} projectKey={p.key} md={agentsMd} edit={edit === "1"} saved={saved === "1"} />}
|
||||
|
||||
{tab === "pulls" && pulls && <PullsTab pulls={pulls.pulls} error={pulls.error} repoUrl={repo.url} />}
|
||||
|
||||
{tab === "releases" && (
|
||||
<Section title={t("Релизы")}>
|
||||
<div className="flex flex-col gap-2 sm:flex-row">
|
||||
<EnvLine name="staging" r={current.staging} t={t} />
|
||||
<EnvLine name={t("прод")} r={current.prod} t={t} />
|
||||
</div>
|
||||
{prodCandidate && prodCandidate !== current.prod?.sha && (
|
||||
<form action={deployProdAction}>
|
||||
<Hidden fields={{ projectKey: p.key, back }} />
|
||||
<Button variant="default" size="sm">
|
||||
<Rocket />
|
||||
{t("Выкатить в прод {sha}", { sha: prodCandidate.slice(0, 7) })}
|
||||
</Button>
|
||||
</form>
|
||||
)}
|
||||
{releases.length === 0 ? (
|
||||
<Empty>
|
||||
{t("Деплоев ещё не было. Настройка —")} <span className="font-mono">deploy</span> {t("в .peppa/project.json (см. «Помощь → CI/CD»).")}
|
||||
</Empty>
|
||||
) : (
|
||||
<div className="overflow-x-auto rounded-lg border">
|
||||
<table className="w-full border-collapse text-sm">
|
||||
<tbody>
|
||||
{releases.map((r) => (
|
||||
<tr key={r.id} className="border-b last:border-0">
|
||||
<td className="px-3 py-2 whitespace-nowrap">
|
||||
{r.env}
|
||||
{r.prNumber ? ` #${r.prNumber}` : ""}
|
||||
</td>
|
||||
<td className="px-3 py-2 font-mono">{r.sha.slice(0, 7)}</td>
|
||||
<td className="px-3 py-2">
|
||||
<Badge variant={RELEASE_STATUS[r.status].tone}>{t(RELEASE_STATUS[r.status].label)}</Badge>
|
||||
{r.reason && <span className="ml-1.5 text-muted-foreground">{t.text(r.reason)}</span>}
|
||||
</td>
|
||||
<td className="px-3 py-2">
|
||||
{r.tasks.map((k) => (
|
||||
<Key key={k} href={`/t/${k}`} className="mr-1.5">{k}</Key>
|
||||
))}
|
||||
</td>
|
||||
<td className="px-3 py-2 text-right whitespace-nowrap text-muted-foreground">
|
||||
{r.deployedBy} · {r.createdAt.toLocaleString(intlLocale(t.locale), { dateStyle: "short", timeStyle: "short" })}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</Section>
|
||||
)}
|
||||
|
||||
{tab === "bugs" && (
|
||||
<>
|
||||
<IncidentsSection w={w} projectId={p.id} back={back} settings={incidentSettings} incidents={incidents} taskKeys={new Map(tasks.map((t) => [t.id, `${p.key}-${t.number}`]))} />
|
||||
{sources.length ? <ProjectErrors projectId={p.id} projectKey={p.key} sp={sp} /> : null}
|
||||
</>
|
||||
)}
|
||||
|
||||
{tab === "metrics" && metrics && <MetricsTab m={metrics} projectKey={p.key} />}
|
||||
|
||||
{tab === "journal" && (
|
||||
<Section title={t("Журнал действий")} actions={<JournalFilters action={`/p/${p.key}`} value={{ tab: "journal", actor, channel }} />}>
|
||||
<JournalList entries={journal} showProject={false} />
|
||||
</Section>
|
||||
)}
|
||||
|
||||
{tab === "sessions" && (
|
||||
<Section
|
||||
title={t("Сессии")}
|
||||
actions={
|
||||
<SettingsDialog title={t("Новый терминал")} trigger={<><SquareTerminal />{t("Новый терминал")}</>}>
|
||||
<NewRunnerForm projectId={p.id} back={back} />
|
||||
</SettingsDialog>
|
||||
}
|
||||
>
|
||||
{sessions.length === 0 ? <Empty>{t("Сессий ещё не было.")}</Empty> : sessions.map((s) => <SessionCard key={s.id} s={s} back={back} showTitle />)}
|
||||
</Section>
|
||||
)}
|
||||
</Workspace>
|
||||
);
|
||||
}
|
||||
|
||||
112
apps/web/app/(app)/p/[key]/plan/[epic]/page.tsx
Normal file
112
apps/web/app/(app)/p/[key]/plan/[epic]/page.tsx
Normal file
@ -0,0 +1,112 @@
|
||||
// PEP-42: plan an epic — the planner proposes stories with dependencies; the PM edits and approves.
|
||||
import Link from "next/link";
|
||||
import { notFound } from "next/navigation";
|
||||
import { Sparkles } from "lucide-react";
|
||||
import { getEpic, listTasks } from "@peppa/core";
|
||||
import { getPlanDraft } from "@peppa/runner";
|
||||
import { Hidden } from "@/components/cards";
|
||||
import { Empty, Flash, PageHeader, Section } from "@/components/common";
|
||||
import { PendingButton } from "@/components/PendingButton";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input, Textarea } from "@/components/ui/input";
|
||||
import { Workspace } from "@/components/Workspace";
|
||||
import { requireUser, words } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import { intlLocale } from "@peppa/shared/i18n";
|
||||
import { projectForUserByKey } from "@/lib/queries";
|
||||
import { applyPlanAction, discardPlanAction, planEpicAction } from "../../../../board-actions";
|
||||
|
||||
export default async function PlanEpicPage({ params, searchParams }: { params: Promise<{ key: string; epic: string }>; searchParams: Promise<{ error?: string }> }) {
|
||||
const user = await requireUser();
|
||||
const { key, epic: epicParam } = await params;
|
||||
const { error } = await searchParams;
|
||||
const t = await getT();
|
||||
const w = await words();
|
||||
const p = await projectForUserByKey(user.id, key).catch(() => null);
|
||||
if (!p) notFound();
|
||||
const epic = await getEpic(db, p.id, Number(epicParam)).catch(() => null);
|
||||
if (!epic) notFound();
|
||||
const [draft, existing] = await Promise.all([getPlanDraft(db, epic.id), listTasks(db, { projectId: p.id, goalId: epic.id })]);
|
||||
const back = `/p/${p.key}/plan/${epic.id}`;
|
||||
|
||||
return (
|
||||
<Workspace aside={null}>
|
||||
<Flash error={error} />
|
||||
<PageHeader
|
||||
crumbs={
|
||||
<>
|
||||
<Link href={`/p/${p.key}`} className="text-muted-foreground hover:text-foreground">{p.name}</Link>
|
||||
<span className="text-muted-foreground">/</span>
|
||||
<Link href={`/p/${p.key}?epic=${epic.id}`} className="text-muted-foreground hover:text-foreground">{t("эпик «{name}»", { name: epic.title })}</Link>
|
||||
</>
|
||||
}
|
||||
title={t("Спланировать эпик «{name}»", { name: epic.title })}
|
||||
>
|
||||
{w.engineer
|
||||
? t("Планировщик (короткая сессия Claude на подписке пула проекта) предложит {tasks} с критериями готовности и порядком. Ничего не создаётся, пока вы не утвердите план.", { tasks: w.task("accPl") })
|
||||
: t("Планировщик предложит {tasks} с критериями готовности и порядком. Ничего не создаётся, пока вы не утвердите план.", { tasks: w.task("accPl") })}
|
||||
</PageHeader>
|
||||
|
||||
<Section title={t("Эпик")}>
|
||||
<div className="rounded-lg border bg-card p-3 text-sm whitespace-pre-wrap">{epic.description || <span className="text-muted-foreground">{t("Без описания — опишите эпик в «Настройках проекта → Эпики», так план будет точнее.")}</span>}</div>
|
||||
{existing.length > 0 && (
|
||||
<p className="m-0 text-sm text-muted-foreground">
|
||||
{t("Уже есть {tasks}: {keys} — планировщик их не повторит и может от них зависеть.", { tasks: w.task("pl"), keys: existing.map((x) => x.key).join(", ") })}
|
||||
</p>
|
||||
)}
|
||||
<form action={planEpicAction} className="flex flex-col gap-2">
|
||||
<Hidden fields={{ projectId: p.id, epicId: epic.id, back }} />
|
||||
<Textarea name="wishes" rows={2} defaultValue={draft?.wishes ?? ""} placeholder={t("Пожелания планировщику (необязательно): например, «сначала API, потом экран», «без новых зависимостей»")} aria-label={t("Пожелания планировщику")} />
|
||||
<PendingButton pendingText={t("Планировщик думает (до 3 минут)…")} className="self-start">
|
||||
<Sparkles />
|
||||
{draft ? t("Спланировать заново") : t("Спланировать")}
|
||||
</PendingButton>
|
||||
</form>
|
||||
</Section>
|
||||
|
||||
<Section title={draft ? t("Черновик плана — {tasks}", { tasks: w.tasks(draft.stories.length) }) : t("Черновик плана")}>
|
||||
{!draft ? (
|
||||
<Empty>{t("Черновика нет. Нажмите «Спланировать».")}</Empty>
|
||||
) : (
|
||||
<>
|
||||
<form action={applyPlanAction} className="flex flex-col gap-3">
|
||||
<Hidden fields={{ projectId: p.id, epicId: epic.id, back, count: draft.stories.length }} />
|
||||
{draft.stories.map((s, i) => {
|
||||
const n = i + 1;
|
||||
return (
|
||||
<fieldset key={n} className="m-0 flex flex-col gap-2 rounded-lg border bg-card p-3">
|
||||
<legend className="sr-only">{t("{Task} № {n} плана", { Task: w.Task(), n })}</legend>
|
||||
<div className="flex items-center gap-2">
|
||||
<input type="checkbox" name={`keep_${n}`} defaultChecked aria-label={t("Создать {task} {n}", { task: w.task("acc"), n })} className="size-4 accent-primary" />
|
||||
<span className="font-mono text-xs text-muted-foreground">№{n}</span>
|
||||
<Input name={`title_${n}`} required minLength={3} defaultValue={s.title} aria-label={t("Название {task} {n}", { task: w.task("gen"), n })} className="h-8 flex-1" />
|
||||
</div>
|
||||
<Textarea name={`description_${n}`} rows={5} defaultValue={s.description} aria-label={t("Описание {task} {n}", { task: w.task("gen"), n })} />
|
||||
<label className="flex items-center gap-2 text-sm">
|
||||
<span className="text-muted-foreground whitespace-nowrap">{t("Ждёт")}</span>
|
||||
<Input name={`deps_${n}`} defaultValue={s.dependsOn.join(", ")} placeholder={t("номера плана или ключи: 1, {key}-3", { key: p.key })} aria-label={t("Зависимости {task} {n}", { task: w.task("gen"), n })} className="h-8" />
|
||||
</label>
|
||||
</fieldset>
|
||||
);
|
||||
})}
|
||||
<p className="m-0 text-xs text-muted-foreground">
|
||||
{w.engineer
|
||||
? t("Снимите галочку, чтобы не создавать {task}. {Tasks} встанут в конец бэклога в этом порядке; зависимые диспетчер не возьмёт, пока предшественники не в ревью или готово.", { task: w.task("acc"), Tasks: w.Task("pl") })
|
||||
: t("Снимите галочку, чтобы не создавать {task}. {Tasks} встанут в конец бэклога в этом порядке; зависимую задачу агенты возьмут, когда будут готовы те, которых она ждёт.", { task: w.task("acc"), Tasks: w.Task("pl") })}
|
||||
</p>
|
||||
<Button variant="default" className="self-start">{t("Создать {tasks}", { tasks: w.task("accPl") })}</Button>
|
||||
</form>
|
||||
<form action={discardPlanAction}>
|
||||
<Hidden fields={{ projectId: p.id, epicId: epic.id, back }} />
|
||||
<Button size="sm" variant="ghost">{t("Удалить черновик")}</Button>
|
||||
</form>
|
||||
<p className="m-0 text-xs text-muted-foreground">
|
||||
{t("Черновик от {date}, {author}.", { date: new Date(draft.createdAt).toLocaleString(intlLocale(t.locale), { dateStyle: "short", timeStyle: "short" }), author: draft.createdBy })}
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
</Section>
|
||||
</Workspace>
|
||||
);
|
||||
}
|
||||
394
apps/web/app/(app)/p/[key]/tabs.tsx
Normal file
394
apps/web/app/(app)/p/[key]/tabs.tsx
Normal file
@ -0,0 +1,394 @@
|
||||
// Project page tabs «Код», «Спеки», «PR» and the epics block of «⋯ Настройки проекта» (PEP-66).
|
||||
import type { Words } from "@peppa/shared/wording";
|
||||
import { Archive, ExternalLink, GitBranch, GitPullRequest, Pencil } from "lucide-react";
|
||||
import type { Epic, SpecSummary } from "@peppa/core";
|
||||
import { Markdown } from "@/components/Markdown";
|
||||
import type { AgentsMd, OpenPull, RepoOverview } from "@peppa/runner";
|
||||
import { addEpic, editEpic, saveAgentsMdAction } from "../../actions";
|
||||
import { Hidden } from "@/components/cards";
|
||||
import { Disclosure, Empty, Key, Notice, Section, StatusBadge } from "@/components/common";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input, Textarea } from "@/components/ui/input";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import { intlLocale, type Translator } from "@peppa/shared/i18n";
|
||||
|
||||
const when = (iso: string | null, t: Translator) => (iso ? new Date(iso).toLocaleString(intlLocale(t.locale), { dateStyle: "short", timeStyle: "short" }) : "—");
|
||||
|
||||
export async function CodeTab({ code }: { code: RepoOverview }) {
|
||||
const t = await getT();
|
||||
const gitea = (
|
||||
<Button asChild size="sm">
|
||||
<a href={code.url}>
|
||||
{t("Открыть в Gitea")} <ExternalLink />
|
||||
</a>
|
||||
</Button>
|
||||
);
|
||||
if (code.error) {
|
||||
return (
|
||||
<Section title={t("Код")} actions={gitea}>
|
||||
<Empty>{t.text(code.error)}. {t("Репозиторий:")} <a href={code.url} className="text-primary">{code.url}</a></Empty>
|
||||
</Section>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div className="grid gap-6 lg:grid-cols-[minmax(0,1fr)_320px]">
|
||||
<Section title={<>README {code.readme && <span className="ml-1 font-mono text-xs font-normal text-muted-foreground">{code.readme.path}</span>}</>} actions={gitea}>
|
||||
{code.readme ? (
|
||||
<pre className="m-0 max-h-[40em] overflow-auto rounded-lg border bg-card p-4 font-mono text-xs leading-relaxed whitespace-pre-wrap">{code.readme.text}</pre>
|
||||
) : (
|
||||
<Empty>{code.defaultBranch ? t("В ветке {branch} нет README.", { branch: code.defaultBranch }) : t("Репозиторий пуст.")}</Empty>
|
||||
)}
|
||||
</Section>
|
||||
<div className="flex flex-col gap-6">
|
||||
<Section title={t("Ветки")} count={code.branches.length}>
|
||||
{code.branches.length === 0 ? (
|
||||
<Empty>{t("Веток нет.")}</Empty>
|
||||
) : (
|
||||
<ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm">
|
||||
{code.branches.map((b) => (
|
||||
<li key={b.name} className="flex min-w-0 items-center gap-2 rounded-md px-2 py-1">
|
||||
<GitBranch className="size-3.5 shrink-0 text-muted-foreground" />
|
||||
<a href={`${code.url}/src/branch/${b.name.split("/").map(encodeURIComponent).join("/")}`} className="truncate font-mono text-xs text-primary">
|
||||
{b.name}
|
||||
</a>
|
||||
{b.name === code.defaultBranch && <Badge variant="muted">{t("по умолчанию")}</Badge>}
|
||||
<span className="ml-auto shrink-0 font-mono text-[11px] text-muted-foreground">{b.sha.slice(0, 7)}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</Section>
|
||||
<Section title={t("Коммиты {branch}", { branch: code.defaultBranch ?? "" })}>
|
||||
{code.commits.length === 0 ? (
|
||||
<Empty>{t("Коммитов нет.")}</Empty>
|
||||
) : (
|
||||
<ul className="m-0 flex list-none flex-col gap-2 p-0 text-sm">
|
||||
{code.commits.map((c) => (
|
||||
<li key={c.sha} className="flex flex-col gap-0.5 rounded-md border bg-card px-3 py-2">
|
||||
<span className="[overflow-wrap:anywhere]">{c.message}</span>
|
||||
<span className="flex flex-wrap gap-x-2 text-xs text-muted-foreground">
|
||||
<a href={c.url} className="font-mono text-primary">{c.sha.slice(0, 7)}</a>
|
||||
{c.author} · {when(c.date, t)}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</Section>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** PEP-30: the project memory (.peppa/memory.md of the working copy), written by agents. */
|
||||
export async function MemorySection({ text, chars, max, nearLimit }: { text: string; chars: number; max: number; nearLimit: boolean }) {
|
||||
const t = await getT();
|
||||
return (
|
||||
<Section title={t("Память проекта")} actions={<span className={nearLimit ? "text-warn" : "text-muted-foreground"}>{t("{chars} из {max} символов", { chars, max })}</span>} className="mb-8">
|
||||
<p className="m-0 text-sm text-muted-foreground">{t("Что агенты запомнили для следующих стори: команды, соглашения, грабли, решения")} (<code>.peppa/memory.md</code>, MCP <code>remember</code>). {t("Раннер подкладывает её агенту при каждом запуске.")}</p>
|
||||
{text.trim() ? (
|
||||
<Disclosure summary={<span className="text-sm">{nearLimit ? t("Показать память — почти предел, агент ужмёт её") : t("Показать память")}</span>}>
|
||||
<Markdown text={text} />
|
||||
</Disclosure>
|
||||
) : (
|
||||
<Empty>{t("Память пуста — агенты пополнят её в конце стори.")}</Empty>
|
||||
)}
|
||||
</Section>
|
||||
);
|
||||
}
|
||||
|
||||
export async function SpecsTab({ specs }: { specs: SpecSummary[] }) {
|
||||
const t = await getT();
|
||||
return (
|
||||
<Section title={t("Спеки")} count={specs.length}>
|
||||
<p className="m-0 text-sm text-muted-foreground">{t("Что система умеет сейчас: требования OpenSpec из рабочей копии (openspec/specs). Обновляются, когда стори архивирует свой change.")}</p>
|
||||
{specs.length === 0 ? (
|
||||
<Empty>{t("Спек ещё нет — они появляются после archive первого change.")}</Empty>
|
||||
) : (
|
||||
specs.map((s) => (
|
||||
<Disclosure
|
||||
key={s.name}
|
||||
summary={
|
||||
<span className="flex min-w-0 flex-1 flex-col gap-0.5">
|
||||
<span className="flex items-center gap-2">
|
||||
<span className="font-mono">{s.name}</span>
|
||||
<Badge variant="muted">
|
||||
{t.n(s.requirements, "{n} требование", "{n} требования", "{n} требований")}
|
||||
</Badge>
|
||||
</span>
|
||||
{s.purpose && <span className="text-xs font-normal text-muted-foreground">{s.purpose.split("\n")[0]}</span>}
|
||||
</span>
|
||||
}
|
||||
>
|
||||
<pre className="m-0 max-h-[40em] overflow-auto font-mono text-xs leading-relaxed whitespace-pre-wrap">{s.text}</pre>
|
||||
</Disclosure>
|
||||
))
|
||||
)}
|
||||
</Section>
|
||||
);
|
||||
}
|
||||
|
||||
const CI_TONE = { success: "ok", failure: "danger", pending: "info", none: "muted", not_configured: "muted" } as const;
|
||||
|
||||
export async function PullsTab({ pulls, error, repoUrl }: { pulls: OpenPull[]; error: string | null; repoUrl: string }) {
|
||||
const t = await getT();
|
||||
return (
|
||||
<Section
|
||||
title={t("Открытые PR")}
|
||||
count={pulls.length}
|
||||
actions={
|
||||
<Button asChild size="sm">
|
||||
<a href={`${repoUrl}/pulls`}>
|
||||
{t("Все PR в Gitea")} <ExternalLink />
|
||||
</a>
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
{error ? (
|
||||
<Empty>{t.text(error)}.</Empty>
|
||||
) : pulls.length === 0 ? (
|
||||
<Empty>{t("Открытых PR нет.")}</Empty>
|
||||
) : (
|
||||
pulls.map((p) => (
|
||||
<article key={p.number} className="flex flex-col gap-1.5 rounded-lg border bg-card p-3.5 text-sm">
|
||||
<div className="flex items-start gap-2">
|
||||
<GitPullRequest className="mt-0.5 size-4 shrink-0 text-ok" />
|
||||
<a href={p.url} className="min-w-0 flex-1 text-foreground [overflow-wrap:anywhere]">
|
||||
<span className="font-mono text-xs text-muted-foreground">#{p.number}</span> {p.title}
|
||||
</a>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground">
|
||||
<span className="font-mono">{p.branch}</span>
|
||||
{p.task ? (
|
||||
<>
|
||||
· <Key href={`/t/${p.task.key}`}>{p.task.key}</Key>
|
||||
<StatusBadge status={p.task.status} />
|
||||
<Badge variant={CI_TONE[p.task.ci.state]}>{t.text(p.task.ci.label)}</Badge>
|
||||
</>
|
||||
) : (
|
||||
<span>· {t("не стори FORGE")}</span>
|
||||
)}
|
||||
</div>
|
||||
</article>
|
||||
))
|
||||
)}
|
||||
</Section>
|
||||
);
|
||||
}
|
||||
|
||||
/** «⋯ Настройки проекта» → Эпики: labels that group stories (stored as goals). */
|
||||
/** PEP-34: done/total of an epic as a thin bar. */
|
||||
export async function ProgressBar({ done, total, className }: { done: number; total: number; className?: string }) {
|
||||
const t = await getT();
|
||||
const pct = total ? Math.round((done / total) * 100) : 0;
|
||||
return (
|
||||
<span role="progressbar" aria-valuemin={0} aria-valuemax={total} aria-valuenow={done} aria-label={t("Готово {done} из {total}", { done, total })} className={`inline-block h-1 overflow-hidden rounded-full bg-muted ${className ?? "w-12"}`}>
|
||||
<span className="block h-full rounded-full bg-ok" style={{ width: `${pct}%` }} />
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export async function EpicsPanel({ projectId, projectKey, epics, progress, back, w }: { w: Words; projectId: number; projectKey: string; epics: Epic[]; progress: Map<number, { done: number; total: number }>; back: string }) {
|
||||
const t = await getT();
|
||||
return (
|
||||
<div className="flex flex-col gap-2 text-sm">
|
||||
{epics.length === 0 && <p className="m-0 text-muted-foreground">{t("Эпиков нет. Эпик — большая цель, которая объединяет {tasks}; его описание агент получает вместе с {task}.", { tasks: w.task("accPl"), task: w.task("ins") })}</p>}
|
||||
{epics.map((e) => (
|
||||
<details key={e.id} className="group rounded-md border bg-card">
|
||||
<summary className="flex cursor-pointer list-none items-center gap-2 px-3 py-2 select-none [&::-webkit-details-marker]:hidden">
|
||||
<span className="text-muted-foreground transition-transform group-open:rotate-90">›</span>
|
||||
<span className="min-w-0 flex-1 truncate">{e.title}</span>
|
||||
<ProgressBar done={progress.get(e.id)?.done ?? 0} total={progress.get(e.id)?.total ?? 0} />
|
||||
<span className="font-mono text-[11px] text-muted-foreground tabular-nums">{progress.get(e.id)?.done ?? 0}/{progress.get(e.id)?.total ?? 0}</span>
|
||||
{w.engineer && <span className="font-mono text-[11px] text-muted-foreground">#{e.id}</span>}
|
||||
</summary>
|
||||
<div className="flex flex-col gap-2 border-t px-3 py-2.5">
|
||||
<form action={editEpic} className="flex flex-col gap-2">
|
||||
<Hidden fields={{ projectId, epicId: e.id, back }} />
|
||||
<Input name="title" required minLength={2} defaultValue={e.title} aria-label={t("Название эпика")} className="h-8" />
|
||||
<Textarea name="description" rows={3} defaultValue={e.description ?? ""} placeholder={t("Описание для агента: зачем этот эпик")} aria-label={t("Описание эпика")} />
|
||||
<Button size="xs" className="self-start">{t("Сохранить")}</Button>
|
||||
</form>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button asChild size="xs" variant="outline">
|
||||
<a href={`/p/${projectKey}/plan/${e.id}`}>{t("Спланировать {tasks}", { tasks: w.task("accPl") })}</a>
|
||||
</Button>
|
||||
<form action={editEpic}>
|
||||
<Hidden fields={{ projectId, epicId: e.id, back, archive: "1" }} />
|
||||
<Button size="xs" variant="ghost">
|
||||
<Archive />{t("В архив")}
|
||||
</Button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
))}
|
||||
<form action={addEpic} className="flex flex-col gap-2">
|
||||
<Hidden fields={{ projectId, back }} />
|
||||
<div className="flex gap-2">
|
||||
<Input name="title" required minLength={2} placeholder={t("Новый эпик")} aria-label={t("Название нового эпика")} className="h-8" />
|
||||
<Button size="sm">{t("Добавить")}</Button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** PEP-73: the project's AGENTS.md — prompt and standards every agent follows; read and edit. */
|
||||
export async function AgentsMdTab({ projectId, projectKey, md, edit, saved }: { projectId: number; projectKey: string; md: AgentsMd; edit: boolean; saved: boolean }) {
|
||||
const t = await getT();
|
||||
const tabHref = `/p/${projectKey}?tab=agents`;
|
||||
const gitea = (
|
||||
<Button asChild size="sm">
|
||||
<a href={md.url}>
|
||||
{t("В Gitea")} <ExternalLink />
|
||||
</a>
|
||||
</Button>
|
||||
);
|
||||
if (md.error) {
|
||||
return (
|
||||
<Section title="AGENTS.md" actions={gitea}>
|
||||
<Empty>{t.text(md.error)}</Empty>
|
||||
</Section>
|
||||
);
|
||||
}
|
||||
if (edit) {
|
||||
return (
|
||||
<Section title={t("AGENTS.md — правка")} actions={gitea}>
|
||||
<form action={saveAgentsMdAction} className="flex flex-col gap-3">
|
||||
<Hidden fields={{ projectId: String(projectId), sha: md.sha ?? "", back: `${tabHref}&edit=1` }} />
|
||||
<Textarea name="text" defaultValue={md.text || AGENTS_MD_STARTER} rows={28} spellCheck={false} className="font-mono text-xs leading-relaxed" aria-label={t("Текст AGENTS.md")} />
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Button variant="default">{t("Сохранить в {branch}", { branch: md.branch })}</Button>
|
||||
<Button asChild variant="ghost">
|
||||
<a href={tabHref}>{t("Отмена")}</a>
|
||||
</Button>
|
||||
<span className="text-xs text-muted-foreground">{t("Коммит в ветку {branch} от вашего имени. Новые и перезапущенные агенты прочитают его сразу.", { branch: md.branch })}</span>
|
||||
</div>
|
||||
</form>
|
||||
</Section>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Section
|
||||
title="AGENTS.md"
|
||||
actions={
|
||||
<>
|
||||
<Button asChild size="sm" variant="default">
|
||||
<a href={`${tabHref}&edit=1`}>
|
||||
<Pencil /> {t("Изменить")}
|
||||
</a>
|
||||
</Button>
|
||||
{gitea}
|
||||
</>
|
||||
}
|
||||
>
|
||||
{saved && <Notice>{t("AGENTS.md сохранён в {branch}", { branch: md.branch })}</Notice>}
|
||||
<p className="m-0 text-sm text-muted-foreground">
|
||||
{t("Промпт и стандарты проекта: стек, команды, соглашения, этапы (например, проверка ИБ перед PR). Его читают все агенты — Claude, Codex и OpenCode; общие правила FORGE добавляются сами.")}
|
||||
</p>
|
||||
{md.text.trim() ? (
|
||||
<div className="rounded-lg border bg-card p-4">
|
||||
<Markdown text={md.text} />
|
||||
</div>
|
||||
) : (
|
||||
<Empty>{t("В репозитории ещё нет AGENTS.md — нажмите «Изменить», чтобы создать его из заготовки.")}</Empty>
|
||||
)}
|
||||
</Section>
|
||||
);
|
||||
}
|
||||
|
||||
// i18n-ignore — file content for the project repository (like template/AGENTS.md), not UI text
|
||||
const AGENTS_MD_STARTER = `# AGENTS.md
|
||||
|
||||
Проект ведётся на **FORGE**. Общие правила (OpenSpec, PR, ревью) агент получает от FORGE;
|
||||
здесь — только стандарты этого проекта.
|
||||
|
||||
## Стек и команды
|
||||
<!-- Язык, фреймворки, как собрать и запустить тесты. -->
|
||||
|
||||
## Соглашения
|
||||
<!-- Стиль кода, структура, именование, что запрещено. -->
|
||||
|
||||
## Перед PR
|
||||
- Тесты и линтеры проходят.
|
||||
- Безопасность (ИБ): нет секретов в коде и логах; весь ввод проверяется; доступ к данным — только своему пользователю;
|
||||
новые зависимости — без известных уязвимостей. Итог проверки — раздел «ИБ» в описании PR.
|
||||
`;
|
||||
|
||||
interface EpicStory {
|
||||
key: string;
|
||||
title: string;
|
||||
status: string;
|
||||
goalId: number | null;
|
||||
}
|
||||
|
||||
/** PEP-81: epics in plain sight — each epic (a big goal) with its stories (the steps agents do). */
|
||||
export async function EpicsTab({ projectId, projectKey, epics, stories, progress, back, w }: { w: Words; projectId: number; projectKey: string; epics: Epic[]; stories: EpicStory[]; progress: Map<number, { done: number; total: number }>; back: string }) {
|
||||
const t = await getT();
|
||||
const loose = stories.filter((s) => !s.goalId || !epics.some((e) => e.id === s.goalId));
|
||||
const list = (items: EpicStory[]) =>
|
||||
items.length ? (
|
||||
<ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm">
|
||||
{items.map((s) => (
|
||||
<li key={s.key} className="flex flex-wrap items-center gap-x-2 gap-y-0.5">
|
||||
<Key href={`/t/${s.key}`}>{s.key}</Key>
|
||||
<span className="min-w-0 flex-[1_1_12em] truncate">{s.title}</span>
|
||||
<StatusBadge status={s.status} />
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : (
|
||||
<p className="m-0 text-sm text-muted-foreground">{t("{Tasks} пока нет.", { Tasks: w.Task("genPl") })}</p>
|
||||
);
|
||||
return (
|
||||
<Section title={t("Эпики")} count={epics.length}>
|
||||
<p className="m-0 text-sm text-muted-foreground">
|
||||
<b className="text-foreground">{t("Эпик")}</b> {t("— большая цель, например «Оплата» или «Личный кабинет».")} <b className="text-foreground">{w.Task()}</b>{" "}
|
||||
{t("— один конкретный шаг к ней: её делает агент, она — карточка на доске. У {task} может быть один эпик; его описание агент получает вместе с {taskIns}.", { task: w.task("gen"), taskIns: w.task("ins") })}
|
||||
</p>
|
||||
<form action={addEpic} className="flex flex-wrap items-end gap-2 rounded-lg border bg-card px-4 py-3">
|
||||
<Hidden fields={{ projectId, back }} />
|
||||
<Input name="title" required minLength={2} placeholder={t("Новый эпик: большая цель")} aria-label={t("Название нового эпика")} className="h-8 min-w-48 flex-1" />
|
||||
<Input name="description" placeholder={t("Зачем он — одной фразой (необязательно)")} aria-label={t("Описание нового эпика")} className="h-8 min-w-48 flex-[2]" />
|
||||
<Button size="sm" variant="default">{t("Добавить эпик")}</Button>
|
||||
</form>
|
||||
{epics.map((e) => {
|
||||
const pr = progress.get(e.id) ?? { done: 0, total: 0 };
|
||||
return (
|
||||
<article key={e.id} id={`epic-${e.id}`} className="flex flex-col gap-2.5 rounded-lg border bg-card px-4 py-3" data-epic={e.id}>
|
||||
<header className="flex flex-wrap items-center gap-2">
|
||||
<Badge variant="primary">{t("эпик")}</Badge>
|
||||
<h3 className="m-0 min-w-0 flex-1 truncate text-base font-medium">{e.title}</h3>
|
||||
<ProgressBar done={pr.done} total={pr.total} className="w-24" />
|
||||
<span className="text-xs text-muted-foreground tabular-nums">
|
||||
{t("готово {done} из {total}", { done: pr.done, total: pr.total })}
|
||||
</span>
|
||||
</header>
|
||||
{e.description && <p className="m-0 text-sm text-muted-foreground">{e.description}</p>}
|
||||
{list(stories.filter((s) => s.goalId === e.id))}
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button asChild size="xs" variant="outline">
|
||||
<a href={`/p/${projectKey}?epic=${e.id}`}>{t("На доске")}</a>
|
||||
</Button>
|
||||
<Button asChild size="xs" variant="outline">
|
||||
<a href={`/p/${projectKey}/plan/${e.id}`}>{t("Спланировать {tasks}", { tasks: w.task("accPl") })}</a>
|
||||
</Button>
|
||||
</div>
|
||||
</article>
|
||||
);
|
||||
})}
|
||||
{loose.length > 0 && (
|
||||
<article className="flex flex-col gap-2.5 rounded-lg border border-dashed px-4 py-3">
|
||||
<header className="flex items-center gap-2">
|
||||
<h3 className="m-0 text-base font-medium text-muted-foreground">{t("{Tasks} без эпика", { Tasks: w.Task("pl") })}</h3>
|
||||
<span className="text-xs text-muted-foreground">{loose.length}</span>
|
||||
</header>
|
||||
{list(loose)}
|
||||
</article>
|
||||
)}
|
||||
<p className="m-0 text-xs text-muted-foreground">{t("Переименовать эпик, изменить описание или убрать в архив — «Настройки проекта → Эпики». Эпик {task} меняется кнопкой «Изменить» на её странице.", { task: w.task("gen") })}</p>
|
||||
</Section>
|
||||
);
|
||||
}
|
||||
@ -1,36 +1,133 @@
|
||||
import { Suspense } from "react";
|
||||
import { redirect } from "next/navigation";
|
||||
import Link from "next/link";
|
||||
import { listUserProjects } from "@peppa/core";
|
||||
import { AutoRefresh } from "@/components/AutoRefresh";
|
||||
import { Flash, ProjectList, QuestionCard, SessionCard } from "@/components/ui";
|
||||
import { requireUser } from "@/lib/auth";
|
||||
import { agentTaskSummary, claimWelcome, isSuperadmin, listUserProjects, onboardingChecklist, pendingFeedback, platformDelayCounts, progressOverview, proposedCount, reviewCounts } from "@peppa/core";
|
||||
import { AdminFeedbackCard } from "@/components/Feedback";
|
||||
import { AgentTaskSummary } from "@/components/AgentTaskSummary";
|
||||
import { ProgressOverview } from "@/components/ProgressOverview";
|
||||
import { OnboardingChecklist } from "@/components/Onboarding";
|
||||
import { PugBanner } from "@/components/PugMascot";
|
||||
import { LiveRefresh } from "@/components/LiveRefresh";
|
||||
import { ActivityAside } from "@/components/ActivityAside";
|
||||
import { AgentAtWork, ProjectList, QuestionCard } from "@/components/cards";
|
||||
import { Empty, Flash, MoreLink, PageHeader, Section } from "@/components/common";
|
||||
import { Workspace } from "@/components/Workspace";
|
||||
import { requireUser, words } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { activeSessions, inbox } from "@/lib/queries";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import { acceptInbox, activeSessions, inbox } from "@/lib/queries";
|
||||
|
||||
function BlockSkeleton() {
|
||||
return <div className="h-24 animate-pulse rounded-md bg-muted/40" aria-hidden />;
|
||||
}
|
||||
|
||||
async function ProgressBlock({ userId }: { userId: number }) {
|
||||
return <ProgressOverview data={await progressOverview(db, userId)} />;
|
||||
}
|
||||
|
||||
async function AgentsBlock({ userId, engineer }: { userId: number; engineer: boolean }) {
|
||||
const t = await getT();
|
||||
const sessions = await activeSessions(userId);
|
||||
return (
|
||||
<Section title={t("Агенты за работой")} count={sessions.length} actions={engineer ? <MoreLink href="/runners">{t("вся работа агентов")}</MoreLink> : undefined}>
|
||||
{sessions.length === 0 ? <Empty>{t("Сейчас никто не работает: напишите задачу — и агент возьмёт её.")}</Empty> : sessions.map((s) => <AgentAtWork key={s.id} s={s} back="/" engineer={engineer} />)}
|
||||
</Section>
|
||||
);
|
||||
}
|
||||
|
||||
export default async function Home({ searchParams }: { searchParams: Promise<{ error?: string }> }) {
|
||||
const user = await requireUser();
|
||||
const { error } = await searchParams;
|
||||
const [items, sessions, projects] = await Promise.all([inbox(user.id), activeSessions(user.id), listUserProjects(db, user.id)]);
|
||||
const t = await getT();
|
||||
const w = await words();
|
||||
if (await claimWelcome(db, user.id)) redirect("/welcome");
|
||||
// PEP-216: the top of the page needs only what waits for the person; the heavy blocks below
|
||||
// (progress, agents, projects) stream in their own Suspense boundaries.
|
||||
const [items, ready, projects, onboarding, superadmin] = await Promise.all([inbox(user.id), acceptInbox(user.id), listUserProjects(db, user.id), onboardingChecklist(db, user), isSuperadmin(db, user)]);
|
||||
// PEP-143: users' reports about FORGE wait for the superadmin's decision here.
|
||||
// PEP-150/209: delays on the platform's side are the superadmin's to watch — one line here, the list in the dashboard.
|
||||
// PEP-209: what waits for the user comes first — accept, answer, decide on «Предложено».
|
||||
// PEP-197: people against factory-made tasks per project — the superadmin's view.
|
||||
const [reports, delays, toAccept, proposedList, agentTasksAll] = await Promise.all([
|
||||
superadmin ? pendingFeedback(db) : [],
|
||||
superadmin ? platformDelayCounts(db) : null,
|
||||
reviewCounts(db, projects.map((p) => p.id)),
|
||||
Promise.all(projects.map(async (p) => [p.id, await proposedCount(db, p.id)] as const)),
|
||||
superadmin ? agentTaskSummary(db) : [],
|
||||
]);
|
||||
const proposed = new Map(proposedList.filter(([, n]) => n > 0));
|
||||
const acceptN = [...toAccept.values()].reduce((a, b) => a + b, 0);
|
||||
const decideN = [...proposed.values()].reduce((a, b) => a + b, 0);
|
||||
const waits = [acceptN ? t("принять {n}", { n: acceptN }) : null, items.length ? t("ответить {n}", { n: items.length }) : null, decideN ? t("решить {n}", { n: decideN }) : null].filter(Boolean).join(", ");
|
||||
const agentTasks = agentTasksAll.filter((r) => r.agents > 0).slice(0, 15);
|
||||
return (
|
||||
<>
|
||||
<AutoRefresh />
|
||||
<Workspace aside={<ActivityAside questions={false} />}>
|
||||
<LiveRefresh scope="home" />
|
||||
<Flash error={error} />
|
||||
<h1>Главная</h1>
|
||||
<section>
|
||||
<h2>Вопросы агентов {items.length > 0 && <span className="count">{items.length}</span>}</h2>
|
||||
{items.length === 0 ? <p className="empty">Агентам от тебя ничего не нужно.</p> : items.map((q) => <QuestionCard key={q.id} q={q} taskKey={q.taskKey} taskStatus={q.taskStatus} back="/" />)}
|
||||
</section>
|
||||
<section>
|
||||
<h2>
|
||||
Активные раннеры <Link href="/runners" className="more">все раннеры →</Link>
|
||||
</h2>
|
||||
{sessions.length === 0 ? <p className="empty">Сейчас ничего не запущено.</p> : sessions.map((s) => <SessionCard key={s.id} s={s} back="/" />)}
|
||||
</section>
|
||||
<section>
|
||||
<h2>
|
||||
Мои проекты <Link href="/projects" className="more">все проекты →</Link>
|
||||
</h2>
|
||||
<ProjectList projects={projects} userId={user.id} />
|
||||
</section>
|
||||
</>
|
||||
<PageHeader title={waits ? t("Вас ждут: {list}", { list: waits }) : t("Всё идёт само: от вас ничего не нужно")}>
|
||||
{waits ? (w.engineer ? t("Ответьте здесь, в Telegram или через MCP.") : t("Ответьте здесь или в Telegram.")) : t("Агенты работают сами и напишут, когда понадобится ваше решение.")}
|
||||
</PageHeader>
|
||||
{onboarding.visible && <OnboardingChecklist data={onboarding} botUsername={user.telegramBotUsername} />}
|
||||
{acceptN > 0 && (
|
||||
<Section title={t("Принять работу")} count={acceptN}>
|
||||
<div className="mb-3 flex flex-wrap gap-2" data-home-accept>
|
||||
{projects.filter((p) => toAccept.get(p.id)).map((p) => (
|
||||
<Link key={p.id} href={`/p/${p.key}/accept`} className="inline-flex min-h-11 items-center rounded-md bg-primary px-4 text-sm font-medium text-primary-foreground hover:bg-primary/90">
|
||||
{projects.length > 1 ? `${p.name}: ` : ""}{t("Принять работу · {n}", { n: toAccept.get(p.id)! })}
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
{ready.map((q) => <QuestionCard key={q.id} q={q} taskKey={q.taskKey} taskStatus={q.taskStatus} back="/" />)}
|
||||
</Section>
|
||||
)}
|
||||
<Section title={t("Вопросы агентов")} count={items.length}>
|
||||
<PugBanner count={items.length} />
|
||||
{items.map((q) => <QuestionCard key={q.id} q={q} taskKey={q.taskKey} taskStatus={q.taskStatus} back="/" />)}
|
||||
</Section>
|
||||
{acceptN === 0 && ready.length > 0 && (
|
||||
<Section title={t("Ждут «Принять»")} count={ready.length}>
|
||||
{ready.map((q) => <QuestionCard key={q.id} q={q} taskKey={q.taskKey} taskStatus={q.taskStatus} back="/" />)}
|
||||
</Section>
|
||||
)}
|
||||
{decideN > 0 && (
|
||||
<Section title={t("Предложено: решите, делать ли")} count={decideN}>
|
||||
<ul className="m-0 flex list-none flex-col gap-1.5 p-0" data-home-proposed>
|
||||
{projects.filter((p) => proposed.get(p.id)).map((p) => (
|
||||
<li key={p.id}>
|
||||
<Link href={`/p/${p.key}#proposed`} className="text-primary">{t("{project}: предложено {n}", { project: p.name, n: proposed.get(p.id)! })} →</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</Section>
|
||||
)}
|
||||
{reports.length > 0 && (
|
||||
<Section title={t("Обращения пользователей")} count={reports.length} actions={<MoreLink href="/feedback">{t("все обращения")}</MoreLink>}>
|
||||
{reports.slice(0, 5).map((f) => <AdminFeedbackCard key={f.id} f={f} back="/" />)}
|
||||
</Section>
|
||||
)}
|
||||
{delays && delays.total > 0 && (
|
||||
<p className="mb-6 text-sm" data-home-delays>
|
||||
<Link href="/dashboard/delays" className="text-primary">
|
||||
{t("На платформе задержек: {n}, требуют вас: {m}", { n: delays.total, m: delays.admin })} →
|
||||
</Link>
|
||||
</p>
|
||||
)}
|
||||
{agentTasks.length > 0 && (
|
||||
<Section title={t("Задачи, которые фабрика завела сама")} count={agentTasks.length}>
|
||||
<AgentTaskSummary rows={agentTasks} engineer={w.engineer} />
|
||||
</Section>
|
||||
)}
|
||||
<Section title={t("Прогресс")}>
|
||||
<Suspense fallback={<BlockSkeleton />}>
|
||||
<ProgressBlock userId={user.id} />
|
||||
</Suspense>
|
||||
</Section>
|
||||
<Suspense fallback={<Section title={t("Агенты за работой")}><BlockSkeleton /></Section>}>
|
||||
<AgentsBlock userId={user.id} engineer={w.engineer} />
|
||||
</Suspense>
|
||||
<Section title={t("Мои проекты")} actions={<MoreLink href="/projects">{t("все проекты")}</MoreLink>}>
|
||||
<ProjectList projects={projects} userId={user.id} engineer={w.engineer} />
|
||||
</Section>
|
||||
</Workspace>
|
||||
);
|
||||
}
|
||||
|
||||
60
apps/web/app/(app)/platform/actions.ts
Normal file
60
apps/web/app/(app)/platform/actions.ts
Normal file
@ -0,0 +1,60 @@
|
||||
"use server";
|
||||
// «Платформа» (PEP-60): the platform's Telegram channel and digest — superadmin only.
|
||||
|
||||
import { checkPlatformChannel, parseChatId, PeppaError, platformDigestTick, PLATFORM_CHANNEL_EVENTS, requireSuperadmin, setPlatformChannel } from "@peppa/core";
|
||||
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";
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
|
||||
const str = (f: FormData, k: string) => String(f.get(k) ?? "").trim();
|
||||
const BASE = "/platform";
|
||||
|
||||
async function attempt(fn: () => Promise<string | void>): Promise<never> {
|
||||
const user = asWebActor(await requireUser());
|
||||
let target = BASE;
|
||||
try {
|
||||
await requireSuperadmin(db, user);
|
||||
target = (await fn()) || target;
|
||||
} catch (e) {
|
||||
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))}`;
|
||||
}
|
||||
revalidatePath(BASE);
|
||||
redirect(target);
|
||||
}
|
||||
|
||||
/** Saves the Chat ID (and checks the channel right away). */
|
||||
export async function saveChannelAction(f: FormData) {
|
||||
await attempt(async () => {
|
||||
const raw = str(f, "chatId");
|
||||
const c = await setPlatformChannel(db, { chatId: raw ? parseChatId(raw) : null });
|
||||
if (c.chatId != null) await checkPlatformChannel(db);
|
||||
});
|
||||
}
|
||||
|
||||
export async function checkChannelAction() {
|
||||
await attempt(async () => {
|
||||
await checkPlatformChannel(db);
|
||||
});
|
||||
}
|
||||
|
||||
export async function saveChannelSettingsAction(f: FormData) {
|
||||
await attempt(async () => {
|
||||
const events = Object.fromEntries(PLATFORM_CHANNEL_EVENTS.map((e) => [e, f.get(`event.${e}`) === "on"]));
|
||||
await setPlatformChannel(db, { events, digest: { time: str(f, "time"), timezone: str(f, "timezone"), users: f.get("users") === "on" } });
|
||||
});
|
||||
}
|
||||
|
||||
/** Sends the platform digest now (over the time since the previous one). */
|
||||
export async function sendDigestNowAction() {
|
||||
await attempt(async () => {
|
||||
const r = await platformDigestTick(db, { force: true });
|
||||
if (!r) throw new PeppaError(m("Некуда отправлять: канал не подключён и дайджест пользователям выключен"));
|
||||
if (!r.channel && !r.users) return `${BASE}?sent=empty`;
|
||||
return `${BASE}?sent=${r.channel ? "channel" : ""}${r.users ? `,users:${r.users}` : ""}`;
|
||||
});
|
||||
}
|
||||
158
apps/web/app/(app)/platform/page.tsx
Normal file
158
apps/web/app/(app)/platform/page.tsx
Normal file
@ -0,0 +1,158 @@
|
||||
import { notFound } from "next/navigation";
|
||||
import { Megaphone, RefreshCw, Send } from "lucide-react";
|
||||
import { AGENT_CLIS, buildPlatformDigest, getAgentVersions, getPlatformBuild, pinnedAgentVersions, versionDrifts, getPlatformChannel, isSuperadmin, platformDigestEmpty, PLATFORM_CHANNEL_EVENT_NAMES, PLATFORM_CHANNEL_EVENTS, renderPlatformDigest } from "@peppa/core";
|
||||
import { ago, Flash, 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, Label } 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 { checkChannelAction, saveChannelAction, saveChannelSettingsAction, sendDigestNowAction } from "./actions";
|
||||
|
||||
export async function generateMetadata() {
|
||||
const t = await getT();
|
||||
return { title: t("Платформа — FORGE") };
|
||||
}
|
||||
|
||||
/** Telegram HTML of the digest → plain text for the preview. */
|
||||
const plain = (html: string) => html.replace(/<[^>]+>/g, "").replace(/</g, "<").replace(/>/g, ">").replace(/&/g, "&");
|
||||
|
||||
export default async function Platform({ searchParams }: { searchParams: Promise<{ error?: string; sent?: string }> }) {
|
||||
const user = await requireUser();
|
||||
const t = await getT();
|
||||
if (!(await isSuperadmin(db, user))) notFound();
|
||||
const { error, sent } = await searchParams;
|
||||
const [c, build, versions] = await Promise.all([getPlatformChannel(db), getPlatformBuild(db), getAgentVersions(db)]);
|
||||
// PEP-267: pinned agent CLI versions against what runs (the watchdog checks once an hour).
|
||||
const pinned = pinnedAgentVersions();
|
||||
const drifts = versions ? versionDrifts(versions) : [];
|
||||
const digest = await buildPlatformDigest(db, { since: new Date(Date.now() - 24 * 3600_000) });
|
||||
return (
|
||||
<Workspace>
|
||||
<div className="max-w-3xl">
|
||||
<Flash error={error} />
|
||||
{sent && <p className="mb-4 rounded-lg border px-4 py-3 text-sm">{sent === "empty" ? t("Дайджест пуст — нечего отправлять.") : t("Дайджест отправлен: {to}", { to: sent.replace("channel", t("в канал")).replace(",users:", " · " + t("пользователям:") + " ") })}</p>}
|
||||
<PageHeader title={<><Megaphone className="mr-1 inline size-5 text-primary" />{t("Платформа")}</>}>
|
||||
{t("Telegram-канал FORGE: новые версии, падения и перезапуски сервисов и ежедневный дайджест — что нового в FORGE и что происходит сейчас. Раздел видят только суперадмины.")}
|
||||
{build && <> {t("Сейчас: v{version}", { version: build.version })} · <span className="font-mono">{build.commit.slice(0, 7)}</span>.</>}
|
||||
</PageHeader>
|
||||
|
||||
<Section title={t("Канал")}>
|
||||
<Card className="gap-3">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{c.chatId == null ? (
|
||||
<Badge variant="secondary">{t("канал не задан")}</Badge>
|
||||
) : !c.check ? (
|
||||
<Badge variant="info">{t("не проверен")}</Badge>
|
||||
) : c.check.ok ? (
|
||||
<Badge variant="ok">{t("канал подключён")}</Badge>
|
||||
) : (
|
||||
<Badge variant="danger">{t("не работает")}</Badge>
|
||||
)}
|
||||
{c.check?.ok && c.title && <span className="font-semibold">{c.title}</span>}
|
||||
{c.check && <span className="ml-auto text-xs text-muted-foreground">{t("проверен {ago}", { ago: ago(new Date(c.check.at), t) })}</span>}
|
||||
</div>
|
||||
{c.check && !c.check.ok && <p className="m-0 text-sm text-destructive">{t.text(c.check.error)}</p>}
|
||||
<form action={saveChannelAction} className="flex flex-wrap items-end gap-2">
|
||||
<Label className="min-w-56 flex-1">
|
||||
{t("Chat ID канала")}
|
||||
<Input name="chatId" placeholder={t("-100… или @имя")} defaultValue={c.chatId == null ? "" : String(c.chatId)} className="h-8 font-mono" />
|
||||
</Label>
|
||||
<Button size="sm">{t("Сохранить и проверить")}</Button>
|
||||
</form>
|
||||
{c.chatId != null && (
|
||||
<form action={checkChannelAction}>
|
||||
<Button size="sm" variant="outline"><RefreshCw />{t("Проверить ещё раз")}</Button>
|
||||
</form>
|
||||
)}
|
||||
<p className="m-0 text-xs text-muted-foreground">
|
||||
{t("Добавьте бота FORGE в канал администратором с правом «Публикация сообщений». Пока проверка не прошла, FORGE перепроверяет канал раз в час и ничего туда не пишет. Ответы в канале бот не читает.")}
|
||||
</p>
|
||||
</Card>
|
||||
</Section>
|
||||
|
||||
<Section title={t("Что присылать")}>
|
||||
<Card>
|
||||
<form action={saveChannelSettingsAction} className="flex flex-col gap-3">
|
||||
{PLATFORM_CHANNEL_EVENTS.map((e) => (
|
||||
<label key={e} className="flex items-center gap-2 text-sm">
|
||||
<input type="checkbox" name={`event.${e}`} defaultChecked={c.events[e]} className="size-4 accent-primary" />
|
||||
{t("{event} — в канал", { event: t(PLATFORM_CHANNEL_EVENT_NAMES[e]) })}
|
||||
</label>
|
||||
))}
|
||||
<label className="flex items-center gap-2 text-sm">
|
||||
<input type="checkbox" name="users" defaultChecked={c.digest.users} className="size-4 accent-primary" />
|
||||
{t("Дайджест ещё и в личные чаты всем, кто привязал Telegram (отписка — «Настройки → Уведомления»)")}
|
||||
</label>
|
||||
<div className="grid gap-2 sm:grid-cols-2">
|
||||
<Label>
|
||||
{t("Время дайджеста")}
|
||||
<Input name="time" type="time" required defaultValue={c.digest.time} className="h-8" />
|
||||
</Label>
|
||||
<Label>
|
||||
{t("Таймзона")}
|
||||
<Input name="timezone" required defaultValue={c.digest.timezone} className="h-8 font-mono" />
|
||||
</Label>
|
||||
</div>
|
||||
<Button size="sm" className="self-start">{t("Сохранить")}</Button>
|
||||
</form>
|
||||
</Card>
|
||||
</Section>
|
||||
|
||||
<Section title={t("Версии программ агентов")}>
|
||||
<Card className="gap-3">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="text-left text-xs text-muted-foreground">
|
||||
<tr>
|
||||
<th className="font-normal">{t("Программа")}</th>
|
||||
<th className="font-normal">{t("Закреплена")}</th>
|
||||
<th className="font-normal">{t("В сервисе FORGE")}</th>
|
||||
<th className="font-normal">{t("В образе агентов")}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="font-mono">
|
||||
{AGENT_CLIS.map(({ cli, name }) => {
|
||||
const cell = (place: "service" | "runner", v: string | undefined) => {
|
||||
const bad = drifts.some((d) => d.cli === cli && d.place === place);
|
||||
return <td className={bad ? "text-destructive" : undefined}>{v ?? "—"}{bad && <> <Badge variant="danger">{t("не та версия")}</Badge></>}</td>;
|
||||
};
|
||||
return (
|
||||
<tr key={cli}>
|
||||
<td className="font-sans">{name}</td>
|
||||
<td>{pinned[cli] ?? "—"}</td>
|
||||
{cell("service", versions?.service[cli])}
|
||||
{cell("runner", versions?.runner?.[cli])}
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
<p className="m-0 text-xs text-muted-foreground">
|
||||
{versions ? t("Проверено {ago}.", { ago: ago(new Date(versions.at), t) }) : t("Ещё не проверялось.")}{" "}
|
||||
{/* glossary-ignore: раздел видят только суперадмины — имя скрипта, не слово для продакта */}
|
||||
{t("Программы сами не обновляются. Новая версия — scripts/runner-image.sh --try <программа> <версия> (сначала проверка), вернуть прежний образ агентов — scripts/runner-image.sh --rollback.")}
|
||||
</p>
|
||||
</Card>
|
||||
</Section>
|
||||
|
||||
<Section
|
||||
title={t("Дайджест за сутки")}
|
||||
actions={
|
||||
<form action={sendDigestNowAction}>
|
||||
<Button size="sm" variant="outline"><Send />{t("Отправить сейчас")}</Button>
|
||||
</form>
|
||||
}
|
||||
>
|
||||
{platformDigestEmpty(digest) ? (
|
||||
<p className="m-0 text-sm text-muted-foreground">{t("За сутки ничего нового и ничего не происходит — дайджест не уйдёт.")}</p>
|
||||
) : (
|
||||
<pre className="m-0 overflow-x-auto rounded-md bg-muted p-3 text-xs whitespace-pre-wrap">{plain(renderPlatformDigest(digest))}</pre>
|
||||
)}
|
||||
</Section>
|
||||
</div>
|
||||
</Workspace>
|
||||
);
|
||||
}
|
||||
@ -1,79 +1,84 @@
|
||||
import { giteaForUser, type GiteaOrg } from "@peppa/core";
|
||||
import { giteaForUser, isLocalUser, type GiteaOrg } from "@peppa/core";
|
||||
import { loadEnv } from "@peppa/shared";
|
||||
import { Flash } from "@/components/ui";
|
||||
import { requireUser } from "@/lib/auth";
|
||||
import { Flash, PageHeader } from "@/components/common";
|
||||
import { Hidden } from "@/components/cards";
|
||||
import { Label, NativeSelect } from "@/components/ui/input";
|
||||
import { ProjectBasics } from "@/components/ProjectBasics";
|
||||
import { PendingButton } from "@/components/PendingButton";
|
||||
import { Workspace } from "@/components/Workspace";
|
||||
import { requireUser, words } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import { createProjectAction } from "../../actions";
|
||||
|
||||
function Choice({ name, value, checked, children }: { name: string; value: string; checked?: boolean; children: React.ReactNode }) {
|
||||
return (
|
||||
<label className="flex cursor-pointer items-start gap-2.5 rounded-md border bg-background/40 px-3 py-2 text-sm has-checked:border-primary/60 has-checked:bg-primary/5">
|
||||
<input type="radio" name={name} value={value} defaultChecked={checked} className="mt-1 accent-primary" />
|
||||
<span>{children}</span>
|
||||
</label>
|
||||
);
|
||||
}
|
||||
|
||||
export default async function NewProject({ searchParams }: { searchParams: Promise<{ error?: string }> }) {
|
||||
const user = await requireUser();
|
||||
const t = await getT();
|
||||
const { error } = await searchParams;
|
||||
const w = await words();
|
||||
let orgs: GiteaOrg[] = [];
|
||||
let giteaError: string | undefined;
|
||||
const giteaUrl = loadEnv().GITEA_URL.replace(/^https?:\/\//, "");
|
||||
try {
|
||||
orgs = await (await giteaForUser(db, user)).orgsWithRepoCreate(user.login);
|
||||
} catch (e) {
|
||||
giteaError = (e as Error).message;
|
||||
// PEP-68: a local user has no Gitea account — the repo is created in peppa-bot's namespace.
|
||||
const local = isLocalUser(user);
|
||||
const botLogin = process.env.GITEA_BOT_USER ?? "peppa-bot";
|
||||
if (!local) {
|
||||
try {
|
||||
orgs = await (await giteaForUser(db, user)).orgsWithRepoCreate(user.login);
|
||||
} catch (e) {
|
||||
giteaError = (e as Error).message;
|
||||
}
|
||||
}
|
||||
return (
|
||||
<section className="narrow">
|
||||
<h1>Новый проект</h1>
|
||||
<Flash error={error ?? giteaError} />
|
||||
<form action={createProjectAction} className="stack">
|
||||
<input type="hidden" name="back" value="/projects/new" />
|
||||
<label>
|
||||
Название
|
||||
<input type="text" name="name" required placeholder="Платёжный сервис" />
|
||||
</label>
|
||||
<div className="row">
|
||||
<label className="grow">
|
||||
Репозиторий (slug)
|
||||
<input type="text" name="slug" required pattern="[a-z0-9][a-z0-9-]*" placeholder="payments" />
|
||||
</label>
|
||||
<label>
|
||||
Ключ задач
|
||||
<input type="text" name="key" required pattern="[A-Za-z][A-Za-z0-9]{1,9}" placeholder="PAY" className="short" />
|
||||
</label>
|
||||
</div>
|
||||
<label>
|
||||
Пространство в Gitea
|
||||
<select name="owner" defaultValue={user.login}>
|
||||
<option value={user.login}>{user.login} — личное</option>
|
||||
{orgs.map((o) => (
|
||||
<option key={o.id} value={o.username}>{o.username} — организация</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<p className="muted">
|
||||
Репозиторий будет <span className="mono">{giteaUrl}/<пространство>/<slug></span>. В личном пространстве приватный репозиторий видите
|
||||
только вы, <span className="mono">peppa-bot</span> и участники проекта; в организации — ещё её участники с доступом к репозиториям.
|
||||
{orgs.length === 0 && " Организаций, где вы можете создавать репозитории, нет."}
|
||||
</p>
|
||||
<fieldset>
|
||||
<legend>Видимость</legend>
|
||||
<label className="inline">
|
||||
<input type="radio" name="visibility" value="private" defaultChecked /> Приватный — только те, кому выдан доступ
|
||||
</label>
|
||||
<label className="inline">
|
||||
<input type="radio" name="visibility" value="public" /> Публичный — все, у кого есть доступ к Gitea
|
||||
</label>
|
||||
</fieldset>
|
||||
<fieldset>
|
||||
<legend>Репозиторий</legend>
|
||||
<label className="inline">
|
||||
<input type="radio" name="mode" value="new" defaultChecked /> Создать новый
|
||||
</label>
|
||||
<label className="inline">
|
||||
<input type="radio" name="mode" value="existing" /> Подключить существующий (нужны права админа; видимость не меняется)
|
||||
</label>
|
||||
</fieldset>
|
||||
<p className="muted">
|
||||
Пеппа добавит <span className="mono">peppa-bot</span> соавтором, положит AGENTS.md, .mcp.json и .peppa/project.json из шаблона и запустит
|
||||
openspec init. Занимает до ~15 секунд.
|
||||
</p>
|
||||
<button className="primary">Создать проект</button>
|
||||
</form>
|
||||
</section>
|
||||
<Workspace>
|
||||
<div className="max-w-xl">
|
||||
<PageHeader title={t("Новый проект")}>{t("Проект — это ваш продукт. Создайте его, а потом описывайте задачи словами: агенты будут их делать.")}</PageHeader>
|
||||
<Flash error={error ?? giteaError} />
|
||||
<form action={createProjectAction} className="flex flex-col gap-4">
|
||||
<Hidden fields={{ back: "/projects/new" }} />
|
||||
<ProjectBasics>
|
||||
{local ? (
|
||||
<p className="m-0 text-sm text-muted-foreground">
|
||||
{t("Код хранится в FORGE")}{w.engineer && <>: <span className="font-mono">{giteaUrl}/{botLogin}/…</span></>}. {t("Работать с ним вам не нужно — это делают агенты.")}
|
||||
</p>
|
||||
) : (
|
||||
<Label>
|
||||
{w.engineer ? t("Где хранить код (Gitea)") : t("Где хранить код")}
|
||||
<NativeSelect name="owner" defaultValue={user.login}>
|
||||
<option value={user.login}>{t("{login} — личное пространство", { login: user.login })}</option>
|
||||
{orgs.map((o) => (
|
||||
<option key={o.id} value={o.username}>{t("{login} — организация", { login: o.username })}</option>
|
||||
))}
|
||||
</NativeSelect>
|
||||
</Label>
|
||||
)}
|
||||
<fieldset className="m-0 flex flex-col gap-2 border-0 p-0">
|
||||
<legend className="mb-2 text-sm font-medium">{t("Кто может посмотреть код")}</legend>
|
||||
<Choice name="visibility" value="public" checked>{t("Открытый — другие пользователи фабрики тоже могут его посмотреть")}</Choice>
|
||||
<Choice name="visibility" value="private">{t("Закрытый — только вы и участники проекта")}</Choice>
|
||||
</fieldset>
|
||||
{w.product && <input type="hidden" name="mode" value="new" />}
|
||||
{w.engineer && (
|
||||
<fieldset className="m-0 flex flex-col gap-2 border-0 p-0">
|
||||
<legend className="mb-2 text-sm font-medium">{t("Код продукта")}</legend>
|
||||
<Choice name="mode" value="new" checked>{t("Начать с нуля — агенты напишут код сами")}</Choice>
|
||||
<Choice name="mode" value="existing">{t("У меня уже есть код в Gitea — подключить его (адрес кода = имя репозитория)")}</Choice>
|
||||
</fieldset>
|
||||
)}
|
||||
</ProjectBasics>
|
||||
<p className="m-0 text-sm text-muted-foreground">{t("FORGE подготовит всё для агентов — это займёт до 15 секунд.")}</p>
|
||||
<PendingButton pendingText={t("Создаём проект…")} className="self-start">{t("Создать проект")}</PendingButton>
|
||||
</form>
|
||||
</div>
|
||||
</Workspace>
|
||||
);
|
||||
}
|
||||
|
||||
@ -1,23 +1,52 @@
|
||||
import Link from "next/link";
|
||||
import { listUserProjects } from "@peppa/core";
|
||||
import { Flash, ProjectList } from "@/components/ui";
|
||||
import { requireUser } from "@/lib/auth";
|
||||
import { Plus } from "lucide-react";
|
||||
import { analystLinks, isSuperadmin, listOtherProjects, listUserProjects, projectTrashDays } from "@peppa/core";
|
||||
import { ProjectList } from "@/components/cards";
|
||||
import { Flash, PageHeader, Section } from "@/components/common";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Workspace } from "@/components/Workspace";
|
||||
import { requireUser, words } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { getT } from "@/lib/i18n";
|
||||
|
||||
export default async function Projects({ searchParams }: { searchParams: Promise<{ error?: string }> }) {
|
||||
const user = await requireUser();
|
||||
const w = await words();
|
||||
const { error } = await searchParams;
|
||||
const projects = await listUserProjects(db, user.id);
|
||||
const t = await getT();
|
||||
const [projects, allOthers, analyst, superadmin] = await Promise.all([listUserProjects(db, user.id), listOtherProjects(db, user.id), analystLinks(db, user), isSuperadmin(db, user)]);
|
||||
// PEP-181: deleted projects get their own section (superadmin) — not mixed with the live ones.
|
||||
const others = allOthers.filter((p) => !p.deletedAt);
|
||||
const deleted = allOthers.filter((p) => p.deletedAt);
|
||||
return (
|
||||
<>
|
||||
<Workspace>
|
||||
<Flash error={error} />
|
||||
<h1>
|
||||
Проекты{" "}
|
||||
<Link href="/projects/new" className="button primary small">
|
||||
Новый проект
|
||||
</Link>
|
||||
</h1>
|
||||
<ProjectList projects={projects} userId={user.id} />
|
||||
</>
|
||||
<PageHeader
|
||||
title={t("Проекты")}
|
||||
actions={
|
||||
<Button asChild variant="default" size="sm">
|
||||
<Link href="/projects/new">
|
||||
<Plus />
|
||||
{t("Новый проект")}
|
||||
</Link>
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
{w.engineer ? t("Свои и общие проекты: доска стори, код, PR, релизы, ошибки из прода, участники.") : t("Ваши проекты и те, куда вас пригласили. Откройте проект, чтобы поставить задачу или посмотреть результат.")}
|
||||
</PageHeader>
|
||||
<ProjectList projects={projects} userId={user.id} engineer={w.engineer} analyst={analyst} superadmin={superadmin} />
|
||||
{others.length > 0 && (
|
||||
<Section title={t("Проекты других")} count={others.length}>
|
||||
<p className="m-0 text-sm text-muted-foreground">{t("Видны вам как суперадмину. Вопросы агентов и уведомления этих проектов к вам не приходят.")}</p>
|
||||
<ProjectList projects={others} userId={user.id} engineer={w.engineer} superadmin={superadmin} />
|
||||
</Section>
|
||||
)}
|
||||
{deleted.length > 0 && (
|
||||
<Section title={t("Удалённые проекты")} count={deleted.length} id="deleted">
|
||||
<p className="m-0 text-sm text-muted-foreground">{t("Каждый хранится {days} дней со дня удаления — до этого его можно вернуть, потом он исчезнет насовсем.", { days: projectTrashDays() })}</p>
|
||||
<ProjectList projects={deleted} userId={user.id} engineer={w.engineer} superadmin={superadmin} />
|
||||
</Section>
|
||||
)}
|
||||
</Workspace>
|
||||
);
|
||||
}
|
||||
|
||||
@ -1,40 +1,117 @@
|
||||
import Link from "next/link";
|
||||
import { listUserSessions, RUNNER_FILTERS, type RunnerFilter } from "@peppa/core";
|
||||
import { AutoRefresh } from "@/components/AutoRefresh";
|
||||
import { Flash, SessionCard } from "@/components/ui";
|
||||
import { requireUser } from "@/lib/auth";
|
||||
import { Search, SquareTerminal } from "lucide-react";
|
||||
import { listUserProjects, runnerStories, listUserSessions, RUNNER_FILTERS, sessionSteps, type RunnerFilter, type SessionView } from "@peppa/core";
|
||||
import { LiveRefresh } from "@/components/LiveRefresh";
|
||||
import { Empty, Flash, PageHeader } from "@/components/common";
|
||||
import { RunnerDetails, RunnerRow } from "@/components/RunnerConsole";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { NewRunnerForm } from "@/components/Runners";
|
||||
import { SettingsDialog } from "@/components/SettingsDialog";
|
||||
import { Workspace } from "@/components/Workspace";
|
||||
import { requireUser, subscriptionNamesVisible } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { inbox, sessionEvents } from "@/lib/queries";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
|
||||
const FILTERS: Array<{ key: RunnerFilter | undefined; label: string }> = [
|
||||
{ key: undefined, label: "Все" },
|
||||
{ key: "waiting", label: "Ждут тебя" },
|
||||
{ key: "working", label: "Работают" },
|
||||
{ key: "stopped", label: "Остановлены" },
|
||||
{ key: "finished", label: "Завершены" },
|
||||
{ key: undefined, label: m("все") },
|
||||
{ key: "waiting", label: m("ждут вас") },
|
||||
{ key: "working", label: m("работают") },
|
||||
{ key: "stopped", label: m("упали") },
|
||||
{ key: "finished", label: m("готово") },
|
||||
];
|
||||
const inFilter = (s: SessionView, f: RunnerFilter) => (RUNNER_FILTERS[f] as string[]).includes(s.status);
|
||||
const matches = (s: SessionView, q: string) =>
|
||||
[s.name, s.taskKey, s.taskTitle, s.projectKey, s.tmuxName, `#${s.id}`].some((v) => v?.toLowerCase().includes(q));
|
||||
|
||||
export default async function Runners({ searchParams }: { searchParams: Promise<{ error?: string; f?: string }> }) {
|
||||
type Params = { error?: string; f?: string; q?: string; id?: string };
|
||||
|
||||
export default async function Runners({ searchParams }: { searchParams: Promise<Params> }) {
|
||||
const user = await requireUser();
|
||||
const { error, f } = await searchParams;
|
||||
const t = await getT();
|
||||
const { error, f, q: rawQ, id } = await searchParams;
|
||||
const filter = f && f in RUNNER_FILTERS ? (f as RunnerFilter) : undefined;
|
||||
const all = await listUserSessions(db, user.id);
|
||||
const count = (k: RunnerFilter | undefined) => (k ? all.filter((s) => (RUNNER_FILTERS[k] as string[]).includes(s.status)).length : all.length);
|
||||
const shown = filter ? all.filter((s) => (RUNNER_FILTERS[filter] as string[]).includes(s.status)) : all;
|
||||
const back = filter ? `/runners?f=${filter}` : "/runners";
|
||||
const q = rawQ?.trim().toLowerCase() ?? "";
|
||||
const [all, open, projects] = await Promise.all([listUserSessions(db, user.id), inbox(user.id), listUserProjects(db, user.id)]);
|
||||
const asking = new Map<number, typeof open>();
|
||||
for (const x of open) if (x.sessionId) asking.set(x.sessionId, [...(asking.get(x.sessionId) ?? []), x]);
|
||||
const needsPm = (s: SessionView) => s.status === "waiting_input" || asking.has(s.id);
|
||||
|
||||
const found = q ? all.filter((s) => matches(s, q)) : all;
|
||||
const count = (k: RunnerFilter | undefined) => (k ? found.filter((s) => inFilter(s, k)).length : found.length);
|
||||
// Who needs the PM first, then live runners, then finished ones; newest first inside each group.
|
||||
const rank = (s: SessionView) => (needsPm(s) ? 0 : ["done", "failed"].includes(s.status) ? 2 : 1);
|
||||
const shown = (filter ? found.filter((s) => inFilter(s, filter)) : found).sort((a, b) => rank(a) - rank(b) || b.id - a.id);
|
||||
|
||||
const url = (p: { f?: string; q?: string; id?: number | string }) => {
|
||||
const sp = new URLSearchParams();
|
||||
if (p.f) sp.set("f", p.f);
|
||||
if (p.q) sp.set("q", p.q);
|
||||
if (p.id) sp.set("id", String(p.id));
|
||||
const s = sp.toString();
|
||||
return s ? `/runners?${s}` : "/runners";
|
||||
};
|
||||
const base = { f: filter, q: rawQ?.trim() || undefined };
|
||||
const selected = (id && all.find((s) => s.id === Number(id))) || shown[0];
|
||||
const back = url({ ...base, id: selected?.id });
|
||||
const aside = selected ? (
|
||||
<RunnerDetails s={selected} questions={asking.get(selected.id) ?? []} events={await sessionEvents(selected.id)} steps={await sessionSteps(db, selected.id)} stories={await runnerStories(db, selected.id)} back={back} closeHref={url(base)} chosen={!!id} names={await subscriptionNamesVisible()} />
|
||||
) : null;
|
||||
|
||||
return (
|
||||
<>
|
||||
<AutoRefresh />
|
||||
<Workspace aside={aside} asideWideOnly={!id}>
|
||||
<LiveRefresh scope="runners" />
|
||||
<Flash error={error} />
|
||||
<h1>Раннеры</h1>
|
||||
<p className="muted">Агенты в tmux по задачам твоих и общих проектов. Подключиться к раннеру — команда tmux attach на машине Пеппы.</p>
|
||||
<nav className="filters" aria-label="Фильтр раннеров">
|
||||
{FILTERS.map((x) => (
|
||||
<Link key={x.label} href={x.key ? `/runners?f=${x.key}` : "/runners"} className={x.key === filter ? "active" : undefined} aria-current={x.key === filter ? "page" : undefined}>
|
||||
{x.label} <span className="muted">{count(x.key)}</span>
|
||||
</Link>
|
||||
))}
|
||||
</nav>
|
||||
{shown.length === 0 ? <p className="empty">{filter ? "Таких раннеров нет." : "Раннеров пока не было: перенеси задачу в «В работе» на доске проекта."}</p> : shown.map((s) => <SessionCard key={s.id} s={s} back={back} showTitle />)}
|
||||
</>
|
||||
<PageHeader
|
||||
title={t("Работа агентов")}
|
||||
actions={
|
||||
projects.length > 0 && (
|
||||
<SettingsDialog title={t("Новый терминал")} trigger={<><SquareTerminal />{t("Новый терминал")}</>}>
|
||||
<NewRunnerForm projects={projects} back="/runners" />
|
||||
</SettingsDialog>
|
||||
)
|
||||
}
|
||||
>
|
||||
{t("Агенты в tmux по стори ваших и общих проектов и свободные терминалы: кто ждёт вас, кто работает, что готово.")}
|
||||
</PageHeader>
|
||||
<div className="mb-3 flex flex-col gap-3 lg:flex-row lg:items-center">
|
||||
<nav className="flex flex-wrap gap-1.5" aria-label={t("Фильтр раннеров")}>
|
||||
{FILTERS.map((x) => {
|
||||
const n = count(x.key);
|
||||
const active = x.key === filter;
|
||||
return (
|
||||
<Link
|
||||
key={x.label}
|
||||
href={url({ ...base, f: x.key })}
|
||||
aria-current={active ? "page" : undefined}
|
||||
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",
|
||||
active && "border-primary/60 bg-primary/10 text-foreground",
|
||||
)}
|
||||
>
|
||||
<span className={cn("font-mono font-semibold tabular-nums", x.key === "waiting" && n > 0 ? "text-primary" : "text-foreground")}>{n}</span>
|
||||
{t(x.label)}
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
<form action="/runners" className="relative lg:ml-auto lg:w-64" role="search">
|
||||
{filter && <input type="hidden" name="f" value={filter} />}
|
||||
<Search className="pointer-events-none absolute top-1/2 left-2.5 size-4 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input type="search" name="q" data-hotkey-search defaultValue={rawQ ?? ""} placeholder={t("Стори, проект, tmux…")} aria-label={t("Поиск раннеров")} className="h-8 pl-8" />
|
||||
</form>
|
||||
</div>
|
||||
{shown.length === 0 ? (
|
||||
<Empty>{q || filter ? t("Таких раннеров нет.") : t("Раннеров пока не было: перенесите стори в «В работе» на доске проекта.")}</Empty>
|
||||
) : (
|
||||
<ul className="m-0 flex list-none flex-col gap-1 rounded-lg border bg-card/50 p-1.5">
|
||||
{shown.map((s) => (
|
||||
<RunnerRow key={s.id} s={s} href={url({ ...base, id: s.id })} selected={s.id === selected?.id && (id ? true : "wide")} needsPm={needsPm(s)} />
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</Workspace>
|
||||
);
|
||||
}
|
||||
|
||||
235
apps/web/app/(app)/secrets/page.tsx
Normal file
235
apps/web/app/(app)/secrets/page.tsx
Normal file
@ -0,0 +1,235 @@
|
||||
import { notFound } from "next/navigation";
|
||||
import { ShieldCheck } from "lucide-react";
|
||||
import { isSuperadmin, secretsAudit, secretsAgentReport, type PlatformSecretRow } from "@peppa/core";
|
||||
import { Hidden } from "@/components/cards";
|
||||
import { Disclosure, 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 { Workspace } from "@/components/Workspace";
|
||||
import { requireUser } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import { intlLocale, type Translator } from "@peppa/shared/i18n";
|
||||
import { checkGiteaTokenAction, markSecretRotatedAction, reencryptSecretsAction, revokeClientTokensAction } from "../actions";
|
||||
|
||||
export async function generateMetadata() {
|
||||
const t = await getT();
|
||||
return { title: t("Секреты — FORGE") };
|
||||
}
|
||||
|
||||
type Params = { error?: string; reencrypted?: string; unreadable?: string; revoked?: string; gitea?: string };
|
||||
|
||||
const day = (d: Date | null, t: Translator) => (d ? d.toLocaleDateString(intlLocale(t.locale)) : "—");
|
||||
|
||||
function State({ r, t }: { r: PlatformSecretRow; t: Translator }) {
|
||||
if (r.set === null) return <Badge variant="secondary">{t("вне .env")}</Badge>;
|
||||
if (!r.set) return r.optional ? <Badge variant="secondary">{t("не задан")}</Badge> : <Badge variant="danger">{t("не задан")}</Badge>;
|
||||
return <Badge variant="ok">{t("задан")}</Badge>;
|
||||
}
|
||||
|
||||
function Age({ r, t }: { r: PlatformSecretRow; t: Translator }) {
|
||||
if (r.ageDays === null) return <Badge variant="warn">{t("возраст неизвестен")}</Badge>;
|
||||
return r.stale ? <Badge variant="warn">{t("{n} дн. — пора ротировать", { n: r.ageDays })}</Badge> : <Badge variant="info">{t("{n} дн.", { n: r.ageDays })}</Badge>;
|
||||
}
|
||||
|
||||
/** Inline `code` in instruction steps. */
|
||||
function Step({ text }: { text: string }) {
|
||||
return (
|
||||
<>
|
||||
{text.split(/(`[^`]+`)/).map((part, i) =>
|
||||
part.startsWith("`") ? (
|
||||
<code key={i} className="rounded bg-muted px-1 font-mono text-[12px]">
|
||||
{part.slice(1, -1)}
|
||||
</code>
|
||||
) : (
|
||||
part
|
||||
),
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default async function Secrets({ searchParams }: { searchParams: Promise<Params> }) {
|
||||
const user = await requireUser();
|
||||
const t = await getT();
|
||||
if (!(await isSuperadmin(db, user))) notFound();
|
||||
const q = await searchParams;
|
||||
const a = await secretsAudit(db);
|
||||
// PEP-253: service keys in project secrets, those still reaching agents first.
|
||||
const keys = (await secretsAgentReport(db)).filter((r) => r.serviceId).sort((x, y) => Number(y.inAgentEnv && !y.connectionId) - Number(x.inAgentEnv && !x.connectionId));
|
||||
const enc = a.encryption;
|
||||
// The link sits inside the sentence: split the translated text around {link}.
|
||||
const reissue = t("Перевыпуск — в {link}: «Переподключить» запускает новый вход, старый токен Claude отзывается в claude.ai → Settings → Claude Code.").split("{link}");
|
||||
|
||||
return (
|
||||
<Workspace>
|
||||
<div className="max-w-3xl">
|
||||
<Flash error={q.error} />
|
||||
<PageHeader title={<><ShieldCheck className="mr-1 inline size-5 text-primary" />{t("Секреты")}</>}>
|
||||
{t("Ревизия секретов и доступов платформы: что задано, сколько лет каждому секрету, кто им пользуется и как его сменить. Значения здесь не показываются никогда. Раздел видят только суперадмины.")}
|
||||
</PageHeader>
|
||||
{q.reencrypted !== undefined && (
|
||||
<Notice>
|
||||
{t("Перешифровано: {n}", { n: q.reencrypted })}
|
||||
{Number(q.unreadable) > 0 ? " · " + t("не читается ни одним ключом: {n}", { n: q.unreadable }) : ""}
|
||||
</Notice>
|
||||
)}
|
||||
{q.revoked !== undefined && <Notice>{t("Отозвано токенов: {n}", { n: q.revoked })}</Notice>}
|
||||
{q.gitea && <Notice>{q.gitea.startsWith("ok:") ? t("GITEA_TOKEN принадлежит {login}, админских прав нет", { login: q.gitea.slice(3) }) : `GITEA_TOKEN: ${t.text(q.gitea)}`}</Notice>}
|
||||
|
||||
<Section title={t("Ключ шифрования")}>
|
||||
<Card className="flex flex-col gap-2 p-4 text-sm">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{!enc.configured ? <Badge variant="danger">{t("PEPPA_SECRET не задан")}</Badge> : enc.rotating ? <Badge variant="warn">{t("идёт смена ключа")}</Badge> : <Badge variant="ok">{t("один ключ")}</Badge>}
|
||||
<span>{t("на старом ключе: {n}", { n: enc.previous })}</span>
|
||||
<span>· {t("не читается: {n}", { n: enc.unreadable })}</span>
|
||||
</div>
|
||||
<ul className="m-0 flex list-none flex-col gap-0.5 p-0 text-xs text-muted-foreground">
|
||||
{enc.columns.filter((c) => c.total).map((c) => (
|
||||
<li key={`${c.table}.${c.column}`} className="font-mono">
|
||||
{c.table}.{c.column}: {t("{total} · текущий {current} · старый {previous} · не читается {unreadable}", { total: c.total, current: c.current, previous: c.previous, unreadable: c.unreadable })}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<form action={reencryptSecretsAction}>
|
||||
<Hidden fields={{ back: "/secrets" }} />
|
||||
<Button size="sm" variant={enc.previous ? "default" : "outline"} disabled={!enc.configured}>
|
||||
{t("Перешифровать текущим ключом")}
|
||||
</Button>
|
||||
</form>
|
||||
</Card>
|
||||
</Section>
|
||||
|
||||
<Section title={t("Секреты платформы")} count={a.platform.length}>
|
||||
{a.platform.map((r) => (
|
||||
<Card key={r.name} className="flex flex-col gap-2 p-4">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className="font-mono text-sm font-medium">{r.name}</span>
|
||||
<State r={r} t={t} />
|
||||
<Age r={r} t={t} />
|
||||
<Badge variant="secondary">{r.how === "peppa" ? t("ротирует FORGE") : t("вручную")}</Badge>
|
||||
</div>
|
||||
<p className="m-0 text-sm">{t.text(r.label)}</p>
|
||||
<p className="m-0 text-xs text-muted-foreground">
|
||||
{t("Использует: {who}", { who: t.text(r.usedBy) })}
|
||||
{r.rotatedAt ? " · " + (r.rotatedBy ? t("последняя ротация {date} ({by})", { date: day(r.rotatedAt, t), by: r.rotatedBy }) : t("последняя ротация {date}", { date: day(r.rotatedAt, t) })) : ""}
|
||||
</p>
|
||||
<Disclosure summary={t("Как ротировать")}>
|
||||
<ol className="m-0 flex flex-col gap-1 pl-5 text-sm">
|
||||
{r.steps.map((s, i) => (
|
||||
<li key={i}>
|
||||
<Step text={t.text(s)} />
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</Disclosure>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{r.how === "external" && (
|
||||
<form action={markSecretRotatedAction}>
|
||||
<Hidden fields={{ name: r.name, back: "/secrets" }} />
|
||||
<Button size="sm" variant="outline">{t("Отметить: ротирован сегодня")}</Button>
|
||||
</form>
|
||||
)}
|
||||
{r.name === "GITEA_TOKEN" && (
|
||||
<form action={checkGiteaTokenAction}>
|
||||
<Hidden fields={{ back: "/secrets" }} />
|
||||
<Button size="sm" variant="outline">{t("Проверить токен Gitea")}</Button>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
</Card>
|
||||
))}
|
||||
</Section>
|
||||
|
||||
<Section title={t("MCP-клиенты (OAuth)")} count={a.oauth.length}>
|
||||
{a.oauth.length === 0 ? (
|
||||
<Empty>{t("Живых MCP-токенов нет.")}</Empty>
|
||||
) : (
|
||||
a.oauth.map((c) => (
|
||||
<Card key={c.clientId} className="flex flex-wrap items-center gap-2 p-3 text-sm">
|
||||
<span className="font-medium">{c.name}</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{t("токенов {tokens} · людей {users} · старейший {oldest} · использован {used}", { tokens: c.liveTokens, users: c.users, oldest: day(c.oldestAt, t), used: day(c.lastUsedAt, t) })}
|
||||
{c.beforeKeyRotation ? " · " + t("выданы до смены ключа: {n}", { n: c.beforeKeyRotation }) : ""}
|
||||
</span>
|
||||
<form action={revokeClientTokensAction} className="ml-auto">
|
||||
<Hidden fields={{ clientId: c.clientId, back: "/secrets" }} />
|
||||
<Button size="sm" variant="outline">{t("Отозвать все токены")}</Button>
|
||||
</form>
|
||||
</Card>
|
||||
))
|
||||
)}
|
||||
<p className="m-0 text-xs text-muted-foreground">{t("Пользователи отзывают свои подключения сами в «Настройках»; OAuth Gitea у пользователей: {n} (истекли {expired}) — обновляются при входе.", { n: a.gitea.usersWithToken, expired: a.gitea.expired })}</p>
|
||||
</Section>
|
||||
|
||||
<Section title={t("Подписки агентов")} count={a.subscriptions.length}>
|
||||
{a.subscriptions.length === 0 ? (
|
||||
<Empty>{t("Подписок нет.")}</Empty>
|
||||
) : (
|
||||
<ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm">
|
||||
{a.subscriptions.map((s) => (
|
||||
<li key={s.id} className="flex flex-wrap items-center gap-2 rounded-md border px-3 py-2">
|
||||
<span className="font-medium">{s.name}</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{s.provider} · {s.status} · {t("сессий {n} · пулы: {pools}", { n: s.liveSessions, pools: s.pools.join(", ") || "—" })}
|
||||
</span>
|
||||
{s.stale ? <Badge variant="warn">{t("{n} дн. — перевыпустить", { n: s.ageDays })}</Badge> : <Badge variant="info">{t("{n} дн.", { n: s.ageDays })}</Badge>}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
<p className="m-0 text-xs text-muted-foreground">
|
||||
{reissue[0]}
|
||||
<a href="/subscriptions">{t("«Подписках»")}</a>
|
||||
{reissue[1]}
|
||||
</p>
|
||||
</Section>
|
||||
|
||||
<Section title={t("Секреты проектов")} count={a.projects.length}>
|
||||
{a.projects.length === 0 ? (
|
||||
<Empty>{t("Ни в одном проекте секретов нет.")}</Empty>
|
||||
) : (
|
||||
<ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm">
|
||||
{a.projects.map((p) => (
|
||||
<li key={p.projectId} className="flex flex-wrap items-center gap-2 rounded-md border px-3 py-2">
|
||||
<a href={`/p/${p.key}`} className="font-mono font-medium">
|
||||
{p.key}
|
||||
</a>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{t("секретов {n} · старейший {oldest} · выдан агенту {used}", { n: p.secrets, oldest: day(p.oldestAt, t), used: day(p.lastUsedAt, t) })}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</Section>
|
||||
|
||||
<Section title={t("Ключи сервисов в секретах проектов")} count={keys.length}>
|
||||
<p className="m-0 mb-2 text-xs text-muted-foreground">
|
||||
{/* glossary-ignore: страница суперадмина, имя команды CLI */}
|
||||
{t("Секреты, в которых узнан ключ сервиса из каталога подключений. Пока ключ уходит агентам, агент может его прочитать; владелец переносит его кнопкой «Сделать подключением» в настройках проекта. Сообщить владельцам один раз: peppa secrets agent-report --notify.")}
|
||||
</p>
|
||||
{keys.length === 0 ? (
|
||||
<Empty>{t("Ключей сервисов в секретах проектов нет.")}</Empty>
|
||||
) : (
|
||||
<ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm">
|
||||
{keys.map((r) => (
|
||||
<li key={`${r.projectId}:${r.name}`} className="flex flex-wrap items-center gap-2 rounded-md border px-3 py-2">
|
||||
<a href={`/p/${r.projectKey}`} className="font-mono font-medium">
|
||||
{r.projectKey}
|
||||
</a>
|
||||
<span className="font-mono text-[13px]">{r.name}</span>
|
||||
<Badge variant="outline">{r.serviceName}</Badge>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{r.connectionName ? t("стал подключением «{name}»", { name: r.connectionName }) : r.inAgentEnv ? t("уходит агентам") : t("только продукту")}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</Section>
|
||||
</div>
|
||||
</Workspace>
|
||||
);
|
||||
}
|
||||
121
apps/web/app/(app)/sessions/page.tsx
Normal file
121
apps/web/app/(app)/sessions/page.tsx
Normal file
@ -0,0 +1,121 @@
|
||||
// glossary-ignore-file: раздел «Сессии» — терминалы агентов, только в виде «Инженер» (PEP-257)
|
||||
// «Сессии» (PEP-257): one place for the terminals of all live agent sessions of the user's
|
||||
// projects. Left — the list, right — the terminal of the chosen one, open right away: the first
|
||||
// of the list without `?id`, the given one with it (a story links here with its session).
|
||||
import Link from "next/link";
|
||||
import { SquareTerminal } from "lucide-react";
|
||||
import { FINISHED_SESSION_STATUSES, listUserSessions, PROVIDER_NAMES, type SessionView } from "@peppa/core";
|
||||
import { AgentBadge } from "@/components/AgentBadge";
|
||||
import { AttachCommand } from "@/components/cards";
|
||||
import { ago, Empty, Key, PageHeader, StatusBadge } from "@/components/common";
|
||||
import { LiveRefresh } from "@/components/LiveRefresh";
|
||||
import { RunnerTerminal } from "@/components/RunnerTerminal";
|
||||
import { Workspace } from "@/components/Workspace";
|
||||
import { requireUser } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { inbox } from "@/lib/queries";
|
||||
import { SESSION_STATUS, TONE_BG, TONE_TEXT } from "@/lib/status";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { getT } from "@/lib/i18n";
|
||||
|
||||
export default async function Sessions({ searchParams }: { searchParams: Promise<{ id?: string }> }) {
|
||||
const user = await requireUser();
|
||||
const t = await getT();
|
||||
const { id } = await searchParams;
|
||||
const [all, open] = await Promise.all([listUserSessions(db, user.id), inbox(user.id)]);
|
||||
const asking = new Set(open.map((q) => q.sessionId).filter(Boolean));
|
||||
const needsPm = (s: SessionView) => s.status === "waiting_input" || asking.has(s.id);
|
||||
// Live ones only: who needs a person first, then the newest.
|
||||
const live = all.filter((s) => !FINISHED_SESSION_STATUSES.includes(s.status)).sort((a, b) => Number(needsPm(b)) - Number(needsPm(a)) || b.id - a.id);
|
||||
const wanted = id ? Number(id) : null;
|
||||
const selected = (wanted && live.find((s) => s.id === wanted)) || live[0];
|
||||
// The link pointed at a session that has ended (or is not the user's): say so, show the first.
|
||||
const gone = wanted && selected?.id !== wanted ? wanted : null;
|
||||
|
||||
return (
|
||||
<Workspace aside={null} wide>
|
||||
<LiveRefresh scope="runners" />
|
||||
<PageHeader title={t("Сессии")}>{t("Живые сессии агентов ваших проектов: выберите слева — справа сразу её терминал.")}</PageHeader>
|
||||
{gone && (
|
||||
<p className="mb-3 rounded-md border border-warn/40 bg-warn/10 px-3 py-2 text-sm" data-session-gone={gone}>
|
||||
{t("Сессия #{id} уже завершена — открыта другая.", { id: gone })}
|
||||
</p>
|
||||
)}
|
||||
{!selected ? (
|
||||
<Empty>
|
||||
<span className="flex flex-col items-center gap-2">
|
||||
<SquareTerminal className="size-6" />
|
||||
<span>{t("Живых сессий нет.")}</span>
|
||||
<span>{t("Агент запускается, когда стори переносят в «В работе» на доске проекта, или кнопкой «Новый терминал» в «Работе агентов».")}</span>
|
||||
</span>
|
||||
</Empty>
|
||||
) : (
|
||||
<div className="grid gap-4 lg:grid-cols-[minmax(240px,300px)_minmax(0,1fr)]" data-sessions>
|
||||
<nav aria-label={t("Список сессий")} className="min-w-0">
|
||||
<ul className="m-0 flex list-none flex-col gap-1 rounded-lg border bg-card/50 p-1.5 lg:max-h-[calc(100dvh-10rem)] lg:overflow-y-auto">
|
||||
{live.map((s) => (
|
||||
<SessionRow key={s.id} s={s} selected={s.id === selected.id} needsPm={needsPm(s)} />
|
||||
))}
|
||||
</ul>
|
||||
</nav>
|
||||
<SessionPane key={selected.id} s={selected} />
|
||||
</div>
|
||||
)}
|
||||
</Workspace>
|
||||
);
|
||||
}
|
||||
|
||||
async function SessionRow({ s, selected, needsPm }: { s: SessionView; selected: boolean; needsPm: boolean }) {
|
||||
const t = await getT();
|
||||
const st = SESSION_STATUS[s.status] ?? { label: s.status, tone: "muted" as const };
|
||||
return (
|
||||
<li>
|
||||
<Link
|
||||
href={`/sessions?id=${s.id}`}
|
||||
scroll={false}
|
||||
data-hotkey-item
|
||||
data-session-row={s.id}
|
||||
aria-current={selected ? "true" : undefined}
|
||||
className={cn(
|
||||
"grid grid-cols-[auto_minmax(0,1fr)] items-center gap-x-2.5 gap-y-0.5 rounded-md border border-transparent px-2.5 py-2 text-sm text-foreground transition-colors hover:bg-accent hover:no-underline",
|
||||
needsPm && "bg-primary/[0.07] shadow-[inset_2px_0_0_var(--primary)]",
|
||||
selected && "border-border bg-accent",
|
||||
)}
|
||||
>
|
||||
<span className={cn("row-span-3 size-2 self-start mt-1.5 rounded-full", TONE_BG[st.tone], (s.status === "running" || s.status === "starting") && "animate-pulse")} />
|
||||
<span className="flex min-w-0 items-baseline gap-2">
|
||||
<span className="shrink-0 font-mono text-xs text-primary">{s.taskKey ?? s.projectKey}</span>
|
||||
<span className="truncate">{s.taskTitle ?? s.name ?? t("без стори")}</span>
|
||||
</span>
|
||||
<span className="flex min-w-0 flex-wrap items-center gap-x-1.5 font-mono text-[11px]">
|
||||
<span className={TONE_TEXT[st.tone]}>{t(st.label)}</span>
|
||||
<span className="text-muted-foreground">· {PROVIDER_NAMES[s.provider]}</span>
|
||||
</span>
|
||||
<span className="truncate font-mono text-[11px] text-muted-foreground">
|
||||
{s.agentName ? `${s.agentName} · ` : ""}#{s.id} · {ago(s.lastActivityAt, t)}
|
||||
</span>
|
||||
</Link>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
async function SessionPane({ s }: { s: SessionView }) {
|
||||
const t = await getT();
|
||||
return (
|
||||
<section aria-label={t("Терминал")} className="flex min-w-0 flex-col gap-2.5 lg:h-[calc(100dvh-10rem)]" data-session-pane={s.id}>
|
||||
<header className="flex flex-wrap items-center gap-x-2 gap-y-1 text-sm">
|
||||
<StatusBadge status={s.status} kind="session" />
|
||||
{s.taskKey ? <Key href={`/t/${s.taskKey}`}>{s.taskKey}</Key> : <Key href={`/p/${s.projectKey}`}>{s.projectKey}</Key>}
|
||||
<span className="min-w-0 flex-[1_1_12em] truncate font-medium">{s.taskTitle ?? s.name ?? t("без стори")}</span>
|
||||
{s.agentName && <AgentBadge name={s.agentName} />}
|
||||
<span className="font-mono text-xs text-muted-foreground">
|
||||
{PROVIDER_NAMES[s.provider]} · <Link href={`/runners?id=${s.id}`} className="text-muted-foreground hover:text-foreground">#{s.id}</Link>
|
||||
</span>
|
||||
</header>
|
||||
<AttachCommand name={s.tmuxName} />
|
||||
<div className="h-[70dvh] min-h-0 lg:h-auto lg:flex-1">
|
||||
<RunnerTerminal sessionId={s.id} live fill />
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@ -1,116 +1,352 @@
|
||||
import { connectedApps } from "@peppa/core";
|
||||
import { ago, Flash } from "@/components/ui";
|
||||
import { publicOrigin, requireUser } from "@/lib/auth";
|
||||
import { CONNECT_HELP, featureGateView, googleEnabled, connectedApps, getNotifyPrefs, isLocalUser, isSuperadmin, listUserProjects, maskIin, NOTIFY_EVENT_NAMES, NOTIFY_EVENTS, userPushSubscriptions, vapidPublicKey } from "@peppa/core";
|
||||
import { Hidden } from "@/components/cards";
|
||||
import { ago, Disclosure, Empty, Flash, Notice, PageHeader, Section } from "@/components/common";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card } from "@/components/ui/card";
|
||||
import { Input, Label } from "@/components/ui/input";
|
||||
import { GoogleSignIn } from "@/components/GoogleSignIn";
|
||||
import { EgovSign } from "@/components/EgovSign";
|
||||
import { FeatureGate } from "@/components/FeatureGate";
|
||||
import { LiveRefresh } from "@/components/LiveRefresh";
|
||||
import { OwnBotSteps } from "@/components/OwnBotSteps";
|
||||
import { voiceStoriesEnabled } from "@peppa/shared";
|
||||
import { Workspace } from "@/components/Workspace";
|
||||
import { publicOrigin, requireUser, uiMode, words } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { pendingClaudeSetup } from "@peppa/runner";
|
||||
import { cancelClaude, connectClaude, disconnectClaude, pairTelegram, revokeConnectedApp, submitClaudeCode, unpairTelegramAction } from "../actions";
|
||||
import { unlinkGoogleAction, disconnectOwnBotAction, revokeConnectedApp, saveNotifyPrefsAction, setUiModeAction, unpairTelegramAction } from "../actions";
|
||||
import { PushNotifications } from "@/components/PushNotifications";
|
||||
import { TimezoneField } from "@/components/TimezoneField";
|
||||
import { LanguageSwitcher } from "@/components/I18n";
|
||||
import { getLocale, getT } from "@/lib/i18n";
|
||||
import { CopyText } from "@/components/CopyText";
|
||||
import { intlLocale } from "@peppa/shared/i18n";
|
||||
|
||||
export default async function Settings({ searchParams }: { searchParams: Promise<{ error?: string; claude?: string }> }) {
|
||||
const user = await requireUser();
|
||||
const { error, claude } = await searchParams;
|
||||
const setup = await pendingClaudeSetup(db, user.id);
|
||||
const apps = await connectedApps(db, user.id);
|
||||
const origin = await publicOrigin();
|
||||
const back = { back: "/settings" };
|
||||
|
||||
/** A connected thing: title + details on the left, actions on the right. */
|
||||
function Row({ title, children, actions }: { title: React.ReactNode; children?: React.ReactNode; actions?: React.ReactNode }) {
|
||||
return (
|
||||
<section className="narrow">
|
||||
<Flash error={error} />
|
||||
<h1>Настройки</h1>
|
||||
<h2>Claude</h2>
|
||||
{claude === "connected" && <p className="ok">Claude подключён ✅</p>}
|
||||
{setup ? (
|
||||
<div className="card stack">
|
||||
<p>
|
||||
1. Откройте ссылку на любом устройстве и войдите в аккаунт Claude (нужна подписка):
|
||||
</p>
|
||||
<a className="button primary" href={setup.url} target="_blank" rel="noreferrer">Войти в Claude ↗</a>
|
||||
<p>2. Claude покажет код — вставьте его сюда:</p>
|
||||
<form action={submitClaudeCode} className="row">
|
||||
<input type="hidden" name="back" value="/settings" />
|
||||
<input type="text" name="code" placeholder="Код из Claude" aria-label="Код из Claude" autoComplete="off" required />
|
||||
<button className="primary">Подключить</button>
|
||||
</form>
|
||||
<form action={cancelClaude}>
|
||||
<input type="hidden" name="back" value="/settings" />
|
||||
<button className="link">Отменить</button>
|
||||
</form>
|
||||
</div>
|
||||
) : user.claudeTokenEnc ? (
|
||||
<article className="card row">
|
||||
<div className="grow">
|
||||
<b>Claude подключён</b>
|
||||
<div className="muted">
|
||||
с {user.claudeTokenSetAt?.toLocaleDateString("ru-RU")} · сессии ваших проектов работают на вашей подписке
|
||||
</div>
|
||||
</div>
|
||||
<form action={connectClaude}>
|
||||
<input type="hidden" name="back" value="/settings" />
|
||||
<button>Переподключить</button>
|
||||
</form>
|
||||
<form action={disconnectClaude}>
|
||||
<input type="hidden" name="back" value="/settings" />
|
||||
<button className="danger">Отключить</button>
|
||||
</form>
|
||||
</article>
|
||||
) : (
|
||||
<div className="stack">
|
||||
<p className="muted">
|
||||
Агенты ваших проектов запускаются как Claude Code. Подключите свой аккаунт Claude — Пеппа получит годовой
|
||||
токен через <span className="mono">claude setup-token</span>, вход делаете вы сами по ссылке.
|
||||
</p>
|
||||
<form action={connectClaude}>
|
||||
<input type="hidden" name="back" value="/settings" />
|
||||
<button className="primary">Подключить Claude</button>
|
||||
</form>
|
||||
</div>
|
||||
)}
|
||||
<h2>Telegram</h2>
|
||||
{user.telegramChatId ? (
|
||||
<article className="card row">
|
||||
<div className="grow">
|
||||
<b>Telegram привязан{user.telegramUsername ? ` (@${user.telegramUsername})` : ""}</b>
|
||||
<div className="muted">Вопросы агентов из ваших и общих проектов приходят в этот чат.</div>
|
||||
</div>
|
||||
<form action={unpairTelegramAction}>
|
||||
<input type="hidden" name="back" value="/settings" />
|
||||
<button className="danger">Отвязать</button>
|
||||
</form>
|
||||
</article>
|
||||
) : (
|
||||
<div className="stack">
|
||||
<p className="muted">
|
||||
Бот присылает вопросы агентов и «готово к ревью» с кнопками. Нажмите кнопку — откроется бот, в нём нажмите Start.
|
||||
</p>
|
||||
<form action={pairTelegram}>
|
||||
<input type="hidden" name="back" value="/settings" />
|
||||
<button className="primary">Привязать Telegram</button>
|
||||
</form>
|
||||
</div>
|
||||
)}
|
||||
<h2>MCP для ChatGPT и других клиентов</h2>
|
||||
<p>
|
||||
Адрес сервера — подключите его как MCP-коннектор с авторизацией OAuth. Клиент
|
||||
зарегистрируется сам, вы подтвердите доступ на экране Пеппы.
|
||||
</p>
|
||||
<code className="mcp-url">{origin}/mcp</code>
|
||||
<p className="muted">Как подключить и что спрашивать — в <a href="/help">Помощи</a>.</p>
|
||||
<h2>Подключённые приложения</h2>
|
||||
{apps.length === 0 ? (
|
||||
<p className="empty">Нет подключённых приложений.</p>
|
||||
) : (
|
||||
apps.map((a) => (
|
||||
<article key={a.clientId} className="card row">
|
||||
<div className="grow">
|
||||
<b>{a.name}</b>
|
||||
<div className="muted">с {a.since.toLocaleDateString("ru-RU")} · последний запрос {ago(a.lastUsedAt)}</div>
|
||||
</div>
|
||||
<form action={revokeConnectedApp}>
|
||||
<input type="hidden" name="clientId" value={a.clientId} />
|
||||
<input type="hidden" name="back" value="/settings" />
|
||||
<button className="danger">Отозвать</button>
|
||||
</form>
|
||||
</article>
|
||||
))
|
||||
)}
|
||||
</section>
|
||||
<Card className="flex-row flex-wrap items-center gap-3">
|
||||
<div className="min-w-0 flex-[1_1_16rem]">
|
||||
<div className="font-medium">{title}</div>
|
||||
{children && <div className="text-sm text-muted-foreground">{children}</div>}
|
||||
</div>
|
||||
{actions && <div className="flex gap-2">{actions}</div>}
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
export default async function Settings({ searchParams }: { searchParams: Promise<{ error?: string; mode?: string; egov?: string; google?: string; notify?: string; bot?: string }> }) {
|
||||
const user = await requireUser();
|
||||
const { error, egov, google, notify, bot, mode: modeSaved } = await searchParams;
|
||||
const mode = await uiMode();
|
||||
const w = await words();
|
||||
const hasBot = !!user.telegramBotUsername;
|
||||
const local = isLocalUser(user);
|
||||
const superadmin = await isSuperadmin(db, user);
|
||||
const apps = await connectedApps(db, user.id);
|
||||
const origin = await publicOrigin();
|
||||
const prefs = await getNotifyPrefs(db, user.id);
|
||||
const myProjects = await listUserProjects(db, user.id);
|
||||
const pushSubs = await userPushSubscriptions(db, user.id);
|
||||
const vapid = await vapidPublicKey(db);
|
||||
const t = await getT();
|
||||
const connect = CONNECT_HELP[await getLocale()] ?? CONNECT_HELP.ru;
|
||||
// PEP-224: features whose service is down are grey here (eGov binding, connecting AI clients).
|
||||
const egovGate = featureGateView("egov_login");
|
||||
const mcpGate = featureGateView("mcp");
|
||||
const ownBotSteps = <OwnBotSteps botUsername={user.telegramBotUsername} back="/settings" />;
|
||||
return (
|
||||
<Workspace>
|
||||
<div className="max-w-2xl">
|
||||
<LiveRefresh scope="features" indicator={false} />
|
||||
<Flash error={error} />
|
||||
<PageHeader title={t("Настройки")} />
|
||||
<Section title={t("Язык интерфейса")} id="language">
|
||||
<Card className="flex-row flex-wrap items-center gap-3">
|
||||
<LanguageSwitcher />
|
||||
</Card>
|
||||
</Section>
|
||||
<Section title={t("Вид FORGE")} id="mode">
|
||||
{modeSaved === "saved" && <Notice>{t("Сохранено. Сейчас у вас вид «{mode}».", { mode: mode === "engineer" ? t("Инженер") : t("Продакт") })}</Notice>}
|
||||
<form action={setUiModeAction} className="flex flex-col gap-2">
|
||||
<label className="flex cursor-pointer items-start gap-2.5 rounded-lg border bg-card px-4 py-3 text-sm has-checked:border-primary/60 has-checked:bg-primary/5">
|
||||
<input type="radio" name="mode" value="product" defaultChecked={mode === "product"} className="mt-1 accent-primary" />
|
||||
<span className="flex flex-col gap-0.5">
|
||||
<span className="font-medium">{t("Продакт")}</span>
|
||||
<span className="text-muted-foreground">{t("Только главное: что делается, что нужно от вас и где результат. Для тех, кто придумывает продукт, а не пишет код.")}</span>
|
||||
</span>
|
||||
</label>
|
||||
<label className="flex cursor-pointer items-start gap-2.5 rounded-lg border bg-card px-4 py-3 text-sm has-checked:border-primary/60 has-checked:bg-primary/5">
|
||||
<input type="radio" name="mode" value="engineer" defaultChecked={mode === "engineer"} className="mt-1 accent-primary" />
|
||||
<span className="flex flex-col gap-0.5">
|
||||
<span className="font-medium">{t("Инженер")}</span>
|
||||
<span className="text-muted-foreground">{t("Всё, что делают агенты: код, проверки, каждый шаг агента, расход. Для тех, кто хочет заглянуть под капот.")}</span>
|
||||
</span>
|
||||
</label>
|
||||
<Button variant="default" size="sm" className="self-start">{t("Сохранить")}</Button>
|
||||
</form>
|
||||
</Section>
|
||||
<Section title={t("Учётная запись")}>
|
||||
<Card>
|
||||
<p className="m-0 text-sm">
|
||||
{t("Логин")} <span className="font-mono">{user.login}</span>
|
||||
{user.name ? <> · {user.name}</> : null}.{" "}{t("Вход в FORGE — через eGov QR или Google")}
|
||||
{user.egovIin ? (
|
||||
<>
|
||||
, {t("ИИН")} <span className="font-mono">{maskIin(user.egovIin)}</span>.
|
||||
</>
|
||||
) : (
|
||||
<>. <b>{t("ИИН ещё не привязан")}</b>{user.googleSub ? "." : <>{" — "}{t("привяжите его ниже или Google, иначе после выхода вы не сможете войти.")}</>}</>
|
||||
)}
|
||||
</p>
|
||||
{local && w.engineer && (
|
||||
<p className="m-0 text-sm text-muted-foreground">
|
||||
{t("Аккаунта Gitea нет: код проектов — через FORGE (агенты, PR, проверки), новые проекты создаются в пространстве")} <span className="font-mono">peppa-bot</span>.
|
||||
</p>
|
||||
)}
|
||||
</Card>
|
||||
{superadmin && (
|
||||
<Row
|
||||
title={t("Суперадмин")}
|
||||
actions={
|
||||
<>
|
||||
<Button asChild size="sm">
|
||||
<a href="/users">{t("Пользователи")}</a>
|
||||
</Button>
|
||||
<Button asChild size="sm">
|
||||
<a href="/feedback">{t("Обращения")}</a>
|
||||
</Button>
|
||||
<Button asChild size="sm">
|
||||
<a href="/subscriptions">{t("Подписки")}</a>
|
||||
</Button>
|
||||
<Button asChild size="sm">
|
||||
<a href="/secrets">{t("Секреты")}</a>
|
||||
</Button>
|
||||
<Button asChild size="sm">
|
||||
<a href="/hosts">{t("Хосты")}</a>
|
||||
</Button>
|
||||
<Button asChild size="sm">
|
||||
<a href="/journal">{t("Журнал")}</a>
|
||||
</Button>
|
||||
<Button asChild size="sm">
|
||||
<a href="/platform">{t("Платформа")}</a>
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
{t("Пользователи: кто зарегистрировался через eGov, отключить и включить. Подписки агентов и пулы для ротации. Журнал: кто что сделал.")}
|
||||
</Row>
|
||||
)}
|
||||
</Section>
|
||||
{w.engineer && (
|
||||
<Section title={t("Агенты")}>
|
||||
<p className="m-0 text-sm text-muted-foreground">
|
||||
{t("Подписки Claude Code, Codex и OpenCode, на которых работают агенты, ведёт суперадмин в разделе «Подписки»; проект запускает раннеры на своём пуле подписок.")}
|
||||
</p>
|
||||
</Section>
|
||||
)}
|
||||
{!user.egovIin && (
|
||||
<Section title="eGov" id="egov">
|
||||
{egov === "linked" && <Notice>{t("eGov привязан — теперь можно входить по QR")}</Notice>}
|
||||
<Card>
|
||||
<p className="m-0 text-sm">{t("Привяжите свой ИИН: отсканируйте QR в eGov Mobile и подпишите. Вход в FORGE — только через eGov.")}</p>
|
||||
<div className="max-w-xs">
|
||||
<FeatureGate view={egovGate} label={t("Привязать eGov")}>
|
||||
<EgovSign purpose="link" label={t("Привязать eGov")} />
|
||||
</FeatureGate>
|
||||
</div>
|
||||
</Card>
|
||||
</Section>
|
||||
)}
|
||||
{user.egovIin && egov === "linked" && <Notice>{t("eGov привязан — теперь можно входить по QR")}</Notice>}
|
||||
|
||||
{(googleEnabled() || user.googleSub) && (
|
||||
<Section title="Google" id="google">
|
||||
{google === "linked" && <Notice>{t("Google привязан — теперь можно входить через него")}</Notice>}
|
||||
{user.googleSub ? (
|
||||
<Row
|
||||
title={t("Google привязан")}
|
||||
actions={
|
||||
<form action={unlinkGoogleAction}>
|
||||
<Hidden fields={{ back: "/settings#google" }} />
|
||||
<Button size="sm" variant="destructive">{t("Отвязать")}</Button>
|
||||
</form>
|
||||
}
|
||||
>
|
||||
{user.googleEmail}. {t("Войти через Google можно в ту же учётку.")}
|
||||
</Row>
|
||||
) : (
|
||||
<Card>
|
||||
<p className="m-0 text-sm">{t("Привяжите Google-аккаунт — и в эту учётку можно будет входить и через него.")}</p>
|
||||
<div className="max-w-xs">
|
||||
<GoogleSignIn purpose="link" label={t("Привязать Google")} />
|
||||
</div>
|
||||
</Card>
|
||||
)}
|
||||
</Section>
|
||||
)}
|
||||
|
||||
<Section title="Telegram" id="telegram">
|
||||
{bot === "connected" && <Notice>{t("Бот @{bot} подключён — остался последний шаг: откройте его и нажмите Start.", { bot: user.telegramBotUsername })}</Notice>}
|
||||
{user.telegramChatId ? (
|
||||
<Row
|
||||
title={t("Telegram привязан") + (user.telegramUsername ? ` (@${user.telegramUsername})` : "")}
|
||||
actions={
|
||||
<form action={unpairTelegramAction}>
|
||||
<Hidden fields={back} />
|
||||
<Button size="sm" variant="destructive">{t("Отвязать")}</Button>
|
||||
</form>
|
||||
}
|
||||
>
|
||||
{t("Вопросы агентов и «готово к ревью» приходят вам")} {user.telegramBotUsername ? <>{t("от вашего бота")} <span className="font-mono">@{user.telegramBotUsername}</span></> : t("от общего бота FORGE")}. {voiceStoriesEnabled() ? t("Новую задачу можно просто написать или наговорить голосом боту.") : t("Новую задачу можно просто написать боту.")}
|
||||
</Row>
|
||||
) : (
|
||||
ownBotSteps
|
||||
)}
|
||||
{/* PEP-100: every user has their own bot — someone still on the shared one is asked to switch. */}
|
||||
{user.telegramChatId && !hasBot && (
|
||||
<>
|
||||
<Notice>{t("Сейчас сообщения приходят от общего бота FORGE. Подключите своего бота — так у вас будет свой канал для задач и ответов.")}</Notice>
|
||||
{ownBotSteps}
|
||||
</>
|
||||
)}
|
||||
{user.telegramChatId && hasBot && (
|
||||
<form action={disconnectOwnBotAction}>
|
||||
<Hidden fields={back} />
|
||||
<Button size="xs" variant="ghost" className="text-muted-foreground">{t("Отключить бота @{bot}", { bot: user.telegramBotUsername })}</Button>
|
||||
</form>
|
||||
)}
|
||||
</Section>
|
||||
<Section title={t("Уведомления")} id="notifications">
|
||||
{notify === "saved" && <Notice>{t("Настройки уведомлений сохранены")}</Notice>}
|
||||
<Card>
|
||||
<div className="flex flex-col gap-1">
|
||||
<div className="font-medium">{t("Браузер")}</div>
|
||||
<p className="m-0 text-sm text-muted-foreground">
|
||||
{t("Push приходят и при закрытой вкладке; клик открывает {task} или проект. Подписано браузеров: {n}. FORGE можно установить как приложение (Chrome → «Установить»).", { task: w.task("acc"), n: pushSubs.length })}
|
||||
</p>
|
||||
</div>
|
||||
<PushNotifications vapidKey={vapid} known={pushSubs.map((s) => s.endpoint)} />
|
||||
</Card>
|
||||
<form action={saveNotifyPrefsAction} className="flex flex-col gap-4" aria-label={t("Настройки уведомлений")}>
|
||||
<Hidden fields={back} />
|
||||
<Card className="gap-0 p-0">
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr className="border-b text-left text-muted-foreground">
|
||||
<th className="px-4 py-2 font-normal">{t("Событие")}</th>
|
||||
<th className="w-24 px-2 py-2 text-center font-normal">Telegram</th>
|
||||
<th className="w-24 px-2 py-2 text-center font-normal">{t("Браузер")}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{NOTIFY_EVENTS.filter((e) => (e !== "monitoring" && e !== "users" && e !== "feedback") || superadmin).map((e) => (
|
||||
<tr key={e} className="border-b last:border-0">
|
||||
<td className="px-4 py-2">{t.text(NOTIFY_EVENT_NAMES[e])}</td>
|
||||
<td className="px-2 py-2 text-center">
|
||||
<input type="checkbox" name={`${e}.telegram`} defaultChecked={prefs.events[e].telegram} aria-label={`${t.text(NOTIFY_EVENT_NAMES[e])} — Telegram`} className="size-4 accent-primary" />
|
||||
</td>
|
||||
<td className="px-2 py-2 text-center">
|
||||
<input type="checkbox" name={`${e}.push`} defaultChecked={prefs.events[e].push} aria-label={t.text(NOTIFY_EVENT_NAMES[e]) + " — " + t("браузер")} className="size-4 accent-primary" />
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
{!superadmin && (
|
||||
<>
|
||||
<input type="hidden" name="monitoring.telegram" value={prefs.events.monitoring.telegram ? "on" : ""} />
|
||||
<input type="hidden" name="monitoring.push" value={prefs.events.monitoring.push ? "on" : ""} />
|
||||
<input type="hidden" name="users.telegram" value={prefs.events.users.telegram ? "on" : ""} />
|
||||
<input type="hidden" name="users.push" value={prefs.events.users.push ? "on" : ""} />
|
||||
{/* PEP-143: the author's own «исправили» comes by this event; the row is the superadmin's. */}
|
||||
<input type="hidden" name="feedback.telegram" value={prefs.events.feedback.telegram ? "on" : ""} />
|
||||
<input type="hidden" name="feedback.push" value={prefs.events.feedback.push ? "on" : ""} />
|
||||
</>
|
||||
)}
|
||||
</Card>
|
||||
<Card>
|
||||
<label className="flex items-center gap-2 text-sm font-medium">
|
||||
<input type="checkbox" name="quietOn" defaultChecked={!!prefs.quiet} className="size-4 accent-primary" />
|
||||
{t("Тихие часы")}
|
||||
</label>
|
||||
<div className="flex flex-wrap items-end gap-3">
|
||||
<Label className="w-32">
|
||||
{t("С")}
|
||||
<Input type="time" name="quietFrom" defaultValue={prefs.quiet?.from ?? "23:00"} />
|
||||
</Label>
|
||||
<Label className="w-32">
|
||||
{t("До")}
|
||||
<Input type="time" name="quietTo" defaultValue={prefs.quiet?.to ?? "08:00"} />
|
||||
</Label>
|
||||
</div>
|
||||
<p className="m-0 text-sm text-muted-foreground">{t("В тихие часы Telegram приходит без звука, push в браузер не показываются. Дайджест приходит в своё время.")}</p>
|
||||
<div className="flex flex-wrap items-end gap-3">
|
||||
<Label className="w-32">
|
||||
{t("Дайджест в")}
|
||||
<Input type="time" name="digestTime" defaultValue={prefs.digestTime} />
|
||||
</Label>
|
||||
<TimezoneField value={prefs.timezone} />
|
||||
</div>
|
||||
<p className="m-0 text-sm text-muted-foreground">
|
||||
{t("Сводка за сутки по вашим проектам: сделано, в работе, на ревью, ждёт вас, зависло, лимиты. Пустая не приходит. В боте — команда /digest.")}
|
||||
</p>
|
||||
<label className="flex items-center gap-2 text-sm">
|
||||
<input type="checkbox" name="sound" defaultChecked={prefs.sound} className="size-4 accent-primary" />
|
||||
{t("Звук: сигнал в открытой вкладке при новом вопросе и звук у push")}
|
||||
</label>
|
||||
</Card>
|
||||
{myProjects.length > 0 && (
|
||||
<Card>
|
||||
<div className="text-sm font-medium">{t("Проекты")}</div>
|
||||
<p className="m-0 text-sm text-muted-foreground">{t("Из снятых проектов уведомления не приходят (вопросы остаются в вебе).")}</p>
|
||||
<div className="flex flex-wrap gap-x-5 gap-y-2">
|
||||
{myProjects.map((p) => (
|
||||
<label key={p.id} className="flex items-center gap-2 text-sm">
|
||||
<input type="hidden" name="projectShown" value={p.id} />
|
||||
<input type="checkbox" name="project" value={p.id} defaultChecked={!prefs.mutedProjects.includes(p.id)} className="size-4 accent-primary" />
|
||||
{p.name} <span className="font-mono text-xs text-muted-foreground">{p.key}</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</Card>
|
||||
)}
|
||||
<Button variant="default" className="self-start">{t("Сохранить уведомления")}</Button>
|
||||
</form>
|
||||
</Section>
|
||||
<Section title={w.engineer ? t("MCP для ChatGPT и других клиентов") : t("FORGE в вашем Claude или ChatGPT")}>
|
||||
<p className="m-0 text-sm">{w.engineer ? t("Адрес сервера — подключите его как MCP-коннектор с авторизацией OAuth. Клиент зарегистрируется сам, вы подтвердите доступ на экране FORGE.") : t("Подключите FORGE к своему чату — и ставьте задачи и отвечайте агентам прямо из него. Понадобится этот адрес; доступ вы подтвердите на экране FORGE.")}</p>
|
||||
<FeatureGate view={mcpGate} title={t("MCP временно недоступен")}>
|
||||
<CopyText value={`${origin}/mcp`} label={connect.copy} done={connect.copied} />
|
||||
<p className="m-0 text-sm">
|
||||
<a href="/help/connect" className="font-medium text-primary">{connect.linkLabel} →</a>
|
||||
{" · "}
|
||||
<a href="/mcp-guide" className="font-medium text-primary">{t("Инструкция для ИИ")} →</a>
|
||||
</p>
|
||||
</FeatureGate>
|
||||
</Section>
|
||||
<Section title={t("Подключённые приложения")} id="apps">
|
||||
{apps.length === 0 ? (
|
||||
<Empty>{t("Нет подключённых приложений.")}</Empty>
|
||||
) : (
|
||||
apps.map((a) => (
|
||||
<Row
|
||||
key={a.clientId}
|
||||
title={a.name}
|
||||
actions={
|
||||
<form action={revokeConnectedApp}>
|
||||
<Hidden fields={{ clientId: a.clientId, ...back }} />
|
||||
<Button size="sm" variant="destructive">{t("Отозвать")}</Button>
|
||||
</form>
|
||||
}
|
||||
>
|
||||
{t("с {date} · последний запрос {ago}", { date: a.since.toLocaleDateString(intlLocale(t.locale)), ago: ago(a.lastUsedAt, t) })}
|
||||
</Row>
|
||||
))
|
||||
)}
|
||||
</Section>
|
||||
</div>
|
||||
</Workspace>
|
||||
);
|
||||
}
|
||||
|
||||
174
apps/web/app/(app)/subscriptions/actions.ts
Normal file
174
apps/web/app/(app)/subscriptions/actions.ts
Normal file
@ -0,0 +1,174 @@
|
||||
"use server";
|
||||
// «Подписки» (PEP-67): every action is superadmin-only (others get "not found").
|
||||
|
||||
import { createPool, setPoolCapacity, deletePool, getProject, lendSubscription, PeppaError, returnLoanNow, requireSuperadmin, setProjectPool, updatePool, updateSubscription, type SubscriptionProvider, setSubscriptionAccount } from "@peppa/core";
|
||||
import { addPoolSubscription, addSubscription, switchAgents, cancelLogin, checkSubscription, finishClaudeLogin, removeSubscription, startClaudeLogin, startCodexLogin } 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";
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
|
||||
const str = (f: FormData, k: string) => String(f.get(k) ?? "").trim();
|
||||
const ids = (f: FormData, k: string) => f.getAll(k).map(Number).filter((n) => Number.isInteger(n) && n > 0);
|
||||
const BASE = "/subscriptions";
|
||||
|
||||
/** Runs a superadmin action; errors come back as ?error=… (redirect stays outside try). */
|
||||
async function attempt(f: FormData, fn: () => Promise<string | void>): Promise<never> {
|
||||
const user = asWebActor(await requireUser());
|
||||
let target = str(f, "back") || BASE;
|
||||
try {
|
||||
await requireSuperadmin(db, user);
|
||||
target = (await fn()) || target;
|
||||
} catch (e) {
|
||||
const t = await getT();
|
||||
const msg = e instanceof PeppaError ? t.text(e.message) : t("Ошибка: {message}", { message: (e as Error).message });
|
||||
const [path, query] = target.split("?");
|
||||
const params = new URLSearchParams(query);
|
||||
params.set("error", msg.slice(0, 300));
|
||||
target = `${path}?${params}`;
|
||||
}
|
||||
revalidatePath("/", "layout");
|
||||
redirect(target);
|
||||
}
|
||||
|
||||
export async function addSubscriptionAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const provider = str(f, "provider") as SubscriptionProvider;
|
||||
if (!["claude", "codex", "opencode"].includes(provider)) throw new PeppaError(m("Неизвестный провайдер"));
|
||||
const s = await addSubscription(db, {
|
||||
provider,
|
||||
name: str(f, "name"),
|
||||
method: str(f, "method"),
|
||||
secret: str(f, "secret") || undefined,
|
||||
keyProvider: str(f, "keyProvider") || undefined,
|
||||
createdBy: user.id,
|
||||
});
|
||||
return s.status === "pending" ? `${BASE}?login=${s.id}#s-${s.id}` : `${BASE}?added=${s.id}#s-${s.id}`;
|
||||
});
|
||||
}
|
||||
|
||||
/** PEP-164: one more Claude / ChatGPT straight into a pool, sign-in starts at once. */
|
||||
export async function addPoolSubscriptionAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const provider = str(f, "provider") === "codex" ? "codex" : "claude";
|
||||
const s = await addPoolSubscription(db, { poolId: Number(str(f, "poolId")), provider, createdBy: user.id });
|
||||
return `${BASE}?login=${s.id}#s-${s.id}`;
|
||||
});
|
||||
}
|
||||
|
||||
/** PEP-176: the superadmin moves the agents off a subscription by hand. */
|
||||
export async function switchAgentsAction(f: FormData) {
|
||||
await attempt(f, async () => {
|
||||
const fromId = Number(str(f, "fromId"));
|
||||
const to = str(f, "toId");
|
||||
const r = await switchAgents(db, { fromId, toId: to ? Number(to) : null });
|
||||
return `${BASE}?switched=${r.moved}&left=${r.skipped}#s-${fromId}`;
|
||||
});
|
||||
}
|
||||
|
||||
export async function reconnectSubscription(f: FormData) {
|
||||
await attempt(f, async () => {
|
||||
const id = Number(str(f, "id"));
|
||||
if (str(f, "provider") === "codex") await startCodexLogin(db, id);
|
||||
else await startClaudeLogin(db, id);
|
||||
return `${BASE}?login=${id}#s-${id}`;
|
||||
});
|
||||
}
|
||||
|
||||
export async function submitLoginCode(f: FormData) {
|
||||
await attempt(f, async () => {
|
||||
const id = Number(str(f, "id"));
|
||||
await finishClaudeLogin(db, id, str(f, "code"), str(f, "account"));
|
||||
return `${BASE}?added=${id}#s-${id}`;
|
||||
});
|
||||
}
|
||||
|
||||
export async function cancelLoginAction(f: FormData) {
|
||||
await attempt(f, async () => {
|
||||
await cancelLogin(db, Number(str(f, "id")));
|
||||
});
|
||||
}
|
||||
|
||||
export async function checkSubscriptionAction(f: FormData) {
|
||||
await attempt(f, async () => {
|
||||
const id = Number(str(f, "id"));
|
||||
await checkSubscription(db, id);
|
||||
return `${BASE}#s-${id}`;
|
||||
});
|
||||
}
|
||||
|
||||
export async function renameSubscription(f: FormData) {
|
||||
await attempt(f, async () => {
|
||||
if (!str(f, "name")) throw new PeppaError(m("Нужно название подписки"));
|
||||
await updateSubscription(db, Number(str(f, "id")), { name: str(f, "name") });
|
||||
// PEP-178: which account it is — the e-mail the person signed in with.
|
||||
if (f.has("account")) await setSubscriptionAccount(db, Number(str(f, "id")), str(f, "account"));
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteSubscriptionAction(f: FormData) {
|
||||
await attempt(f, async () => {
|
||||
await removeSubscription(db, Number(str(f, "id")));
|
||||
});
|
||||
}
|
||||
|
||||
export async function createPoolAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
await createPool(db, { name: str(f, "name"), subscriptionIds: ids(f, "subscription"), createdBy: user.id });
|
||||
return `${BASE}#pools`;
|
||||
});
|
||||
}
|
||||
|
||||
export async function updatePoolAction(f: FormData) {
|
||||
await attempt(f, async () => {
|
||||
await updatePool(db, Number(str(f, "id")), { name: str(f, "name") || undefined, subscriptionIds: ids(f, "subscription") });
|
||||
return `${BASE}#pools`;
|
||||
});
|
||||
}
|
||||
|
||||
export async function deletePoolAction(f: FormData) {
|
||||
await attempt(f, async () => {
|
||||
await deletePool(db, Number(str(f, "id")));
|
||||
return `${BASE}#pools`;
|
||||
});
|
||||
}
|
||||
|
||||
/** «⋯ Настройки проекта» → пул по умолчанию (only a superadmin changes it). */
|
||||
export async function setProjectPoolAction(f: FormData) {
|
||||
await attempt(f, async () => {
|
||||
const p = await getProject(db, str(f, "projectKey"));
|
||||
await setProjectPool(db, p.id, str(f, "poolId") ? Number(str(f, "poolId")) : null);
|
||||
});
|
||||
}
|
||||
|
||||
// ── PEP-107: lending a spare subscription to someone's pool ─────────────────────────
|
||||
export async function lendSubscriptionAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
await lendSubscription(db, user, { subscriptionId: Number(str(f, "subscriptionId")), poolId: Number(str(f, "poolId")), hours: Number(str(f, "hours")) });
|
||||
return `${BASE}#overview`;
|
||||
});
|
||||
}
|
||||
|
||||
export async function returnLoanAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
await returnLoanNow(db, user, Number(str(f, "poolId")), Number(str(f, "subscriptionId")));
|
||||
return `${BASE}#overview`;
|
||||
});
|
||||
}
|
||||
|
||||
/** PEP-182: «Агентов на подписку» of a set (1–20), works from the next start on. */
|
||||
export async function setPoolCapacityAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const id = Number(str(f, "poolId"));
|
||||
await setPoolCapacity(db, user, id, Number(str(f, "capacity")));
|
||||
return `${BASE}#pool-${id}`;
|
||||
});
|
||||
}
|
||||
423
apps/web/app/(app)/subscriptions/page.tsx
Normal file
423
apps/web/app/(app)/subscriptions/page.tsx
Normal file
@ -0,0 +1,423 @@
|
||||
import { notFound } from "next/navigation";
|
||||
import { ExternalLink, KeyRound, Plus, RefreshCw } from "lucide-react";
|
||||
import { getQuestion, isSuperadmin, listSubscriptions, OPENCODE_KEY_ENV, PROVIDER_NAMES, poolOverviews, type PoolOverview, type SubscriptionView } from "@peppa/core";
|
||||
import { pendingLogin, pollCodexLogin, type PendingLogin, backfillCodexAccounts, openSubscriptionRequests } from "@peppa/runner";
|
||||
import { answerQuestion } from "@/app/(app)/actions";
|
||||
import { LocalTime } from "@/components/LocalTime";
|
||||
import { LiveRefresh } from "@/components/LiveRefresh";
|
||||
import { PoolCapacity, PoolSubscriptions, PoolSummary, PoolSwitches } from "@/components/PoolSubscriptions";
|
||||
import { Hidden } from "@/components/cards";
|
||||
import { ago, Disclosure, 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, Label, NativeSelect } 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 type { Translator } from "@peppa/shared/i18n";
|
||||
import {
|
||||
addSubscriptionAction,
|
||||
cancelLoginAction,
|
||||
checkSubscriptionAction,
|
||||
createPoolAction,
|
||||
deletePoolAction,
|
||||
deleteSubscriptionAction,
|
||||
addPoolSubscriptionAction,
|
||||
switchAgentsAction,
|
||||
returnLoanAction,
|
||||
setPoolCapacityAction,
|
||||
reconnectSubscription,
|
||||
submitLoginCode,
|
||||
renameSubscription,
|
||||
updatePoolAction,
|
||||
} from "./actions";
|
||||
|
||||
// PEP-216: the backfill reads auth files — once per process is enough, not on every visit.
|
||||
let backfilled = false;
|
||||
async function backfillOnce(d: typeof db) {
|
||||
if (backfilled) return;
|
||||
backfilled = true;
|
||||
await backfillCodexAccounts(d).catch(() => {});
|
||||
}
|
||||
|
||||
export async function generateMetadata() {
|
||||
const t = await getT();
|
||||
return { title: t("Подписки — FORGE") };
|
||||
}
|
||||
|
||||
// PEP-170: one simple picture — a subscription runs out, agents move to the next free one.
|
||||
// Problems first, then one card per set of subscriptions (whose they are, which projects run on
|
||||
// them), rows with one status each, the latest switches. No pool editor, no lending form.
|
||||
|
||||
function LoginSteps({ s, login, t }: { s: SubscriptionView; login: PendingLogin; t: Translator }) {
|
||||
return (
|
||||
<div className="flex flex-col gap-2 rounded-md border bg-background/40 p-3">
|
||||
{login.kind === "claude" ? (
|
||||
<>
|
||||
<p className="m-0 text-sm">{t("1. Откройте ссылку на любом устройстве и войдите в аккаунт Claude с подпиской:")}</p>
|
||||
<Button asChild variant="default" size="sm" className="self-start">
|
||||
<a href={login.url} target="_blank" rel="noreferrer">
|
||||
{t("Войти в Claude")} <ExternalLink />
|
||||
</a>
|
||||
</Button>
|
||||
<p className="m-0 text-sm">{t("2. Claude покажет код — вставьте его сюда:")}</p>
|
||||
<form action={submitLoginCode} className="flex gap-2">
|
||||
<Hidden fields={{ id: s.id }} />
|
||||
<Input name="code" placeholder={t("Код из Claude")} aria-label={t("Код из Claude")} autoComplete="off" required className="font-mono" />
|
||||
<Input name="account" type="email" autoComplete="email" placeholder={t("Почта аккаунта Claude — по желанию")} aria-label={t("Почта аккаунта Claude")} />
|
||||
<Button variant="default">{t("Подключить")}</Button>
|
||||
</form>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<p className="m-0 text-sm">{t("1. Откройте ссылку на любом устройстве и войдите в ChatGPT:")}</p>
|
||||
<Button asChild variant="default" size="sm" className="self-start">
|
||||
<a href={login.url} target="_blank" rel="noreferrer">
|
||||
{login.url} <ExternalLink />
|
||||
</a>
|
||||
</Button>
|
||||
<p className="m-0 text-sm">
|
||||
{t("2. Введите одноразовый код:")} <span className="rounded bg-muted px-2 py-0.5 font-mono text-base font-semibold tracking-wider">{login.code}</span>
|
||||
</p>
|
||||
<p className="m-0 text-xs text-muted-foreground">{t("Страница обновится сама, когда Codex подтвердит вход.")}</p>
|
||||
</>
|
||||
)}
|
||||
<form action={cancelLoginAction}>
|
||||
<Hidden fields={{ id: s.id }} />
|
||||
<Button variant="link" size="sm" className="px-0 text-muted-foreground">{t("Отменить вход")}</Button>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function AddForm({ provider, children, t }: { provider: string; children: React.ReactNode; t: Translator }) {
|
||||
return (
|
||||
<form action={addSubscriptionAction} className="flex flex-col gap-3">
|
||||
<Hidden fields={{ provider }} />
|
||||
<Label>
|
||||
{t("Название")}
|
||||
<Input name="name" required placeholder={provider === "claude" ? "Claude Max — asel" : provider === "codex" ? "ChatGPT Pro — asel" : "OpenCode — Anthropic"} />
|
||||
</Label>
|
||||
{children}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
const PENDING_STALE_MS = 3_600_000;
|
||||
|
||||
/** Rows that need a person: a broken sign-in, a sign-in started and left. */
|
||||
function Problem({ s, login, t }: { s: SubscriptionView; login: PendingLogin | null; t: Translator }) {
|
||||
return (
|
||||
<Card id={`s-${s.id}`} className="gap-2">
|
||||
<div className="flex flex-wrap items-center gap-2 text-sm">
|
||||
<span className="font-medium">{s.name}</span>
|
||||
{s.ownerName && !s.name.includes(s.ownerName) && <span className="text-xs text-muted-foreground">· {s.ownerName}</span>}
|
||||
<span className="text-xs text-muted-foreground">{PROVIDER_NAMES[s.provider]}</span>
|
||||
{s.status === "auth_error" ? <Badge variant="danger">{t("ошибка входа")}</Badge> : <Badge variant="muted">{t("вход не закончен · {ago}", { ago: ago(s.createdAt, t) })}</Badge>}
|
||||
</div>
|
||||
{s.lastError && s.status === "auth_error" && <p className="m-0 font-mono text-xs [overflow-wrap:anywhere] text-destructive">{s.lastError}</p>}
|
||||
{login && <LoginSteps s={s} login={login} t={t} />}
|
||||
{!login && (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{(s.provider === "claude" || (s.provider === "codex" && s.authKind === "device")) && (
|
||||
<form action={reconnectSubscription}>
|
||||
<Hidden fields={{ id: s.id, provider: s.provider }} />
|
||||
<Button size="sm" variant="default">{t("Подключить заново")}</Button>
|
||||
</form>
|
||||
)}
|
||||
<form action={deleteSubscriptionAction}>
|
||||
<Hidden fields={{ id: s.id }} />
|
||||
<Button size="sm" variant="ghost" className="text-muted-foreground">{t("Удалить")}</Button>
|
||||
</form>
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
/** A set of subscriptions: its projects, the rows, what happens on a limit, the latest switches. */
|
||||
function SetCard({ o, subs, t }: { o: PoolOverview; subs: SubscriptionView[]; t: Translator }) {
|
||||
const ids = o.subscriptions.map((s) => s.id);
|
||||
const addable = subs.filter((s) => !ids.includes(s.id) && s.status !== "auth_error");
|
||||
return (
|
||||
<Card className="gap-3" id={`pool-${o.pool.id}`} data-pool-overview={o.pool.id}>
|
||||
<div className="flex flex-wrap items-baseline gap-2">
|
||||
<span className="font-medium">{o.pool.name}</span>
|
||||
<span className="text-xs text-muted-foreground">{o.projects.length ? t("работают: {keys}", { keys: o.projects.map((x) => x.key).join(", ") }) : t("ни один проект не работает на них")}</span>
|
||||
</div>
|
||||
<PoolSubscriptions
|
||||
o={o}
|
||||
capacity
|
||||
action={(s) => (
|
||||
<>
|
||||
{/* PEP-176: move this subscription's agents by hand — to one of the pool's working subscriptions or to any free one. */}
|
||||
{s.activeSessions > 0 && (
|
||||
<form action={switchAgentsAction} className="flex items-center gap-1" data-switch-agents={s.id}>
|
||||
<Hidden fields={{ fromId: s.id }} />
|
||||
<NativeSelect name="toId" aria-label={t("Куда перевести агентов")} className="h-7 text-xs">
|
||||
<option value="">{t("на любую свободную")}</option>
|
||||
{o.subscriptions
|
||||
.filter((x) => x.id !== s.id && x.usable)
|
||||
.map((x) => (
|
||||
<option key={x.id} value={x.id}>
|
||||
{x.name}
|
||||
{x.accountEmail ? ` · ${x.accountEmail}` : x.ownerName && !x.name.includes(x.ownerName) ? ` · ${x.ownerName}` : ""}
|
||||
</option>
|
||||
))}
|
||||
</NativeSelect>
|
||||
<Button size="xs" variant="outline" title={t("Агенты сразу продолжат на выбранной подписке")}>
|
||||
{t("Перевести агентов")}
|
||||
</Button>
|
||||
</form>
|
||||
)}
|
||||
{/* PEP-178: name and account of the subscription — which login it is. */}
|
||||
<details className="relative" data-edit-subscription={s.id}>
|
||||
<summary className="cursor-pointer list-none rounded px-2 py-1 text-xs text-muted-foreground hover:text-foreground">{t("Изменить")}</summary>
|
||||
<form action={renameSubscription} className="absolute right-0 z-20 mt-1 flex w-72 flex-col gap-2 rounded-lg border bg-card p-3 shadow-lg">
|
||||
<Hidden fields={{ id: s.id, back: `/subscriptions#pool-${o.pool.id}` }} />
|
||||
<Label>
|
||||
{t("Название")}
|
||||
<Input name="name" required defaultValue={s.name} className="h-8" />
|
||||
</Label>
|
||||
<Label>
|
||||
{t("Почта аккаунта")}
|
||||
<Input name="account" type="email" defaultValue={s.accountEmail ?? ""} placeholder="name@example.com" className="h-8" />
|
||||
</Label>
|
||||
<Button size="sm" variant="default" className="self-start">{t("Сохранить")}</Button>
|
||||
</form>
|
||||
</details>
|
||||
<form action={checkSubscriptionAction}>
|
||||
<Hidden fields={{ id: s.id }} />
|
||||
<Button size="xs" variant="ghost" title={t("Проверить")} aria-label={t("Проверить")} className="text-muted-foreground">
|
||||
<RefreshCw />
|
||||
</Button>
|
||||
</form>
|
||||
{s.loan ? (
|
||||
<form action={returnLoanAction}>
|
||||
<Hidden fields={{ poolId: o.pool.id, subscriptionId: s.id }} />
|
||||
<Button size="xs" variant="ghost" className="text-muted-foreground">{t("Вернуть")}</Button>
|
||||
</form>
|
||||
) : (
|
||||
<form action={updatePoolAction}>
|
||||
<Hidden fields={{ id: o.pool.id }} />
|
||||
{ids.filter((x) => x !== s.id).map((x) => <input key={x} type="hidden" name="subscription" value={x} />)}
|
||||
<Button size="xs" variant="ghost" className="text-muted-foreground">{t("Убрать")}</Button>
|
||||
</form>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
/>
|
||||
<PoolSummary o={o} />
|
||||
<PoolCapacity
|
||||
o={o}
|
||||
form={
|
||||
<form action={setPoolCapacityAction} className="ml-auto flex items-center gap-1.5">
|
||||
<Hidden fields={{ poolId: o.pool.id }} />
|
||||
<Label className="flex-row items-center gap-1.5 text-xs font-normal">
|
||||
{t("Агентов на подписку")}
|
||||
<Input name="capacity" type="number" min={1} max={20} required defaultValue={o.capacity} className="h-7 w-16 text-sm" />
|
||||
</Label>
|
||||
<Button size="xs" variant="outline">{t("Сохранить")}</Button>
|
||||
</form>
|
||||
}
|
||||
/>
|
||||
{addable.length > 0 && (
|
||||
<form action={updatePoolAction} className="flex flex-wrap items-center gap-2">
|
||||
<Hidden fields={{ id: o.pool.id }} />
|
||||
{ids.map((x) => <input key={x} type="hidden" name="subscription" value={x} />)}
|
||||
<NativeSelect name="subscription" aria-label={t("Добавить подписку")} className="h-8 max-w-xs text-sm" required defaultValue="">
|
||||
<option value="" disabled>{t("Добавить подписку…")}</option>
|
||||
{addable.map((s) => (
|
||||
<option key={s.id} value={s.id}>{s.name}{s.ownerName && !s.name.includes(s.ownerName) ? ` · ${s.ownerName}` : ""} ({PROVIDER_NAMES[s.provider]})</option>
|
||||
))}
|
||||
</NativeSelect>
|
||||
<Button size="sm">{t("Добавить")}</Button>
|
||||
</form>
|
||||
)}
|
||||
{/* PEP-164: one more subscription straight into this set — the sign-in starts right away. */}
|
||||
<div className="flex flex-wrap gap-2" data-add-to-pool={o.pool.id}>
|
||||
<form action={addPoolSubscriptionAction}>
|
||||
<Hidden fields={{ poolId: o.pool.id, provider: "claude" }} />
|
||||
<Button size="sm" variant={o.usableCount <= 1 ? "default" : "outline"}>
|
||||
<Plus /> {t("Добавить ещё Claude")}
|
||||
</Button>
|
||||
</form>
|
||||
<form action={addPoolSubscriptionAction}>
|
||||
<Hidden fields={{ poolId: o.pool.id, provider: "codex" }} />
|
||||
<Button size="sm" variant="outline">
|
||||
<Plus /> {t("Добавить ещё ChatGPT")}
|
||||
</Button>
|
||||
</form>
|
||||
</div>
|
||||
{!o.projects.length && !ids.length && (
|
||||
<form action={deletePoolAction}>
|
||||
<Hidden fields={{ id: o.pool.id }} />
|
||||
<Button size="xs" variant="ghost" className="px-0 text-muted-foreground">{t("Удалить пустой набор")}</Button>
|
||||
</form>
|
||||
)}
|
||||
<PoolSwitches o={o} />
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
type Params = { error?: string; login?: string; added?: string; switched?: string; left?: string };
|
||||
|
||||
export default async function Subscriptions({ searchParams }: { searchParams: Promise<Params> }) {
|
||||
const user = await requireUser();
|
||||
const t = await getT();
|
||||
if (!(await isSuperadmin(db, user))) notFound();
|
||||
const { error, added, switched, left } = await searchParams;
|
||||
// PEP-178: ChatGPT logins carry their account — fill in the ones signed in before it was kept.
|
||||
await backfillOnce(db);
|
||||
let subs = await listSubscriptions(db);
|
||||
// Codex device sign-ins finish on the user's device: look whether they are done.
|
||||
let polled = false;
|
||||
for (const s of subs) if (s.provider === "codex" && s.status === "pending") polled = (await pollCodexLogin(db, s.id)) !== "pending" || polled;
|
||||
if (polled) subs = await listSubscriptions(db);
|
||||
const logins = new Map<number, PendingLogin>();
|
||||
for (const s of subs) {
|
||||
const l = await pendingLogin(db, s.id);
|
||||
if (l) logins.set(s.id, l);
|
||||
}
|
||||
const now = Date.now();
|
||||
const problems = subs.filter((s) => s.status === "auth_error" || (s.status === "pending" && (logins.has(s.id) || now - s.createdAt.getTime() > PENDING_STALE_MS)));
|
||||
// Sets: the ones projects run on and the troubled first.
|
||||
const sets = (await poolOverviews(db)).sort((a, b) => Number(!a.projects.length) - Number(!b.projects.length) || a.usableCount - b.usableCount || b.waiting - a.waiting);
|
||||
const thin = sets.filter((o) => o.projects.length && o.usableCount <= 1);
|
||||
const inSet = new Set(sets.flatMap((o) => o.subscriptions.map((s) => s.id)));
|
||||
const loose = subs.filter((s) => !inSet.has(s.id) && s.status !== "auth_error" && s.status !== "pending");
|
||||
const addedSub = added ? subs.find((s) => s.id === Number(added)) : undefined;
|
||||
// PEP-186: owners asking for a subscription — answered right here, same buttons as on Home.
|
||||
const requests = await Promise.all(
|
||||
(await openSubscriptionRequests(db)).map(async (r) => ({ ...r, question: r.questionId ? await getQuestion(db, r.questionId).catch(() => null) : null })),
|
||||
);
|
||||
|
||||
return (
|
||||
<Workspace>
|
||||
<LiveRefresh scope="subs" />
|
||||
{[...logins.entries()].filter(([, l]) => l.kind === "codex").map(([id]) => <LiveRefresh key={id} scope={`login:${id}`} indicator={false} />)}
|
||||
<div className="max-w-3xl">
|
||||
<Flash error={error} />
|
||||
<PageHeader title={<><KeyRound className="mr-1 inline size-5 text-primary" />{t("Подписки")}</>}>
|
||||
{t("Аккаунты Claude и ChatGPT, на которых работают агенты. Кончилась одна — агенты переходят на следующую свободную, а когда лимит сбросится, она снова в строю. Раздел видят только суперадмины.")}
|
||||
</PageHeader>
|
||||
{switched !== undefined && (
|
||||
<Notice>
|
||||
{Number(left) > 0
|
||||
? t("Переведено агентов: {n}. Ещё {m} — некуда: свободной рабочей подписки нет.", { n: Number(switched), m: Number(left) })
|
||||
: t("Переведено агентов: {n}. Они продолжают на новой подписке.", { n: Number(switched) })}
|
||||
</Notice>
|
||||
)}
|
||||
{addedSub && <Notice>{addedSub.status === "active" ? t("Подписка «{name}» добавлена и активна", { name: addedSub.name }) : t("Подписка «{name}» добавлена", { name: addedSub.name })}</Notice>}
|
||||
|
||||
{(problems.length > 0 || thin.length > 0 || requests.length > 0) && (
|
||||
<Section title={t("Нужно ваше внимание")} count={problems.length + thin.length + requests.length}>
|
||||
{requests.map((r) => (
|
||||
<div key={r.projectId} data-subscription-request={r.key} className="flex flex-col gap-2 rounded-md border border-warn/40 px-3 py-2 text-sm">
|
||||
<span>{r.question && !r.question.answeredAt ? t.text(r.question.text) : t("{login} просит подписку для проекта «{project}»", { login: r.login, project: r.name })}</span>
|
||||
{r.question && !r.question.answeredAt ? (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{(r.question.options ?? []).map((o, i) => (
|
||||
<form key={o} action={answerQuestion}>
|
||||
<Hidden fields={{ questionId: r.question!.id, choice: o, back: "/subscriptions" }} />
|
||||
<Button size="xs" variant={i === 0 ? "default" : "outline"}>{t.text(o)}</Button>
|
||||
</form>
|
||||
))}
|
||||
</div>
|
||||
) : r.remindAt ? (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{t("Напомню в")} <LocalTime iso={r.remindAt.toISOString()} />
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
))}
|
||||
{problems.map((s) => (
|
||||
<Problem key={s.id} s={s} login={logins.get(s.id) ?? null} t={t} />
|
||||
))}
|
||||
{thin.map((o) => (
|
||||
<a key={o.pool.id} href={`#pool-${o.pool.id}`} className="block rounded-md border border-warn/40 px-3 py-2 text-sm text-warn hover:no-underline">
|
||||
{o.usableCount === 0
|
||||
? t("{keys}: все подписки кончились — агенты ждут сброса лимита", { keys: o.projects.map((x) => x.key).join(", ") })
|
||||
: t("{keys}: запасной подписки нет", { keys: o.projects.map((x) => x.key).join(", ") })}
|
||||
</a>
|
||||
))}
|
||||
</Section>
|
||||
)}
|
||||
|
||||
<Section title={t("Кто на чём работает")} count={sets.length} id="pools">
|
||||
{sets.length === 0 && <Empty>{t("Подписок пока нет — подключите первую ниже.")}</Empty>}
|
||||
{sets.map((o) => (
|
||||
<SetCard key={o.pool.id} o={o} subs={subs} t={t} />
|
||||
))}
|
||||
{loose.length > 0 && (
|
||||
<Card className="gap-2">
|
||||
<span className="font-medium">{t("Ни к чему не подключены")}</span>
|
||||
<ul className="m-0 flex list-none flex-col divide-y divide-border p-0">
|
||||
{loose.map((s) => (
|
||||
<li key={s.id} className="flex flex-wrap items-center gap-2 py-2 text-sm first:pt-0 last:pb-0">
|
||||
<span className="font-medium">{s.name}</span>
|
||||
{s.ownerName && !s.name.includes(s.ownerName) && <span className="text-xs text-muted-foreground">· {s.ownerName}</span>}
|
||||
<span className="text-xs text-muted-foreground">{PROVIDER_NAMES[s.provider]}</span>
|
||||
<form action={deleteSubscriptionAction} className="ml-auto">
|
||||
<Hidden fields={{ id: s.id }} />
|
||||
<Button size="xs" variant="ghost" className="text-muted-foreground">{t("Удалить")}</Button>
|
||||
</form>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</Card>
|
||||
)}
|
||||
</Section>
|
||||
|
||||
<Section title={t("Подключить подписку")}>
|
||||
<div className="grid gap-2 md:grid-cols-3">
|
||||
<Disclosure summary={<span className="flex items-center gap-1.5"><Plus className="size-4" />Claude</span>}>
|
||||
<AddForm provider="claude" t={t}>
|
||||
<NativeSelect name="method" defaultValue="login" aria-label={t("Способ входа")}>
|
||||
<option value="login">{t("Войти по ссылке (claude setup-token)")}</option>
|
||||
<option value="token">{t("Вставить готовый токен")}</option>
|
||||
</NativeSelect>
|
||||
<Input name="secret" type="password" placeholder={t("sk-ant-oat… (только для готового токена)")} autoComplete="off" aria-label={t("Токен")} />
|
||||
<Button variant="default" className="self-start">{t("Добавить")}</Button>
|
||||
</AddForm>
|
||||
</Disclosure>
|
||||
<Disclosure summary={<span className="flex items-center gap-1.5"><Plus className="size-4" />ChatGPT</span>}>
|
||||
<AddForm provider="codex" t={t}>
|
||||
<NativeSelect name="method" defaultValue="device" aria-label={t("Способ входа")}>
|
||||
<option value="device">{t("Подписка ChatGPT (ссылка + код)")}</option>
|
||||
<option value="api_key">{t("API-ключ OpenAI")}</option>
|
||||
</NativeSelect>
|
||||
<Input name="secret" type="password" placeholder={t("sk-… (только для API-ключа)")} autoComplete="off" aria-label={t("API-ключ")} />
|
||||
<Button variant="default" className="self-start">{t("Добавить")}</Button>
|
||||
</AddForm>
|
||||
</Disclosure>
|
||||
<Disclosure summary={<span className="flex items-center gap-1.5"><Plus className="size-4" />OpenCode</span>}>
|
||||
<AddForm provider="opencode" t={t}>
|
||||
<input type="hidden" name="method" value="api_key" />
|
||||
<NativeSelect name="keyProvider" defaultValue="anthropic" aria-label={t("Провайдер ключа")}>
|
||||
{Object.keys(OPENCODE_KEY_ENV).map((k) => (
|
||||
<option key={k} value={k}>{k}</option>
|
||||
))}
|
||||
</NativeSelect>
|
||||
<Input name="secret" type="password" required placeholder={t("Ключ провайдера")} autoComplete="off" aria-label={t("Ключ")} />
|
||||
<Button variant="default" className="self-start">{t("Добавить")}</Button>
|
||||
</AddForm>
|
||||
</Disclosure>
|
||||
</div>
|
||||
<Disclosure summary={<span className="flex items-center gap-1.5 text-sm text-muted-foreground"><Plus className="size-4" />{t("Новый набор подписок")}</span>}>
|
||||
<form action={createPoolAction} className="flex flex-col gap-3">
|
||||
<Label>
|
||||
{t("Название")}
|
||||
<Input name="name" required placeholder={t("Основной")} />
|
||||
</Label>
|
||||
<Button variant="default" className="self-start">{t("Создать")}</Button>
|
||||
<span className="text-xs text-muted-foreground">{t("Проекту набор выбирается в «⋯ Настройки проекта → Подписки».")}</span>
|
||||
</form>
|
||||
</Disclosure>
|
||||
</Section>
|
||||
</div>
|
||||
</Workspace>
|
||||
);
|
||||
}
|
||||
@ -1,84 +1,503 @@
|
||||
// Story page (PEP-32): header with the story, the agent and its live session; tabs by the
|
||||
// OpenSpec artifacts and the course of work (?tab=). Live updates — PEP-37, agent steps — PEP-33.
|
||||
import { queuePositions } from "@peppa/core";
|
||||
import { Markdown } from "@/components/Markdown";
|
||||
import Link from "next/link";
|
||||
import { notFound } from "next/navigation";
|
||||
import { AutoRefresh } from "@/components/AutoRefresh";
|
||||
import { ago, Badge, Flash, QuestionCard, SessionCard } from "@/components/ui";
|
||||
import { requireUser } from "@/lib/auth";
|
||||
import { openspecArtifacts, taskActivity, taskForUser } from "@/lib/queries";
|
||||
import { Archive, ArchiveRestore, ChevronDown, ChevronRight, CircleCheck, CircleX, GitPullRequest, Hourglass, Lock, Pencil, Play, X } from "lucide-react";
|
||||
import {
|
||||
blockersOf,
|
||||
dependentsOf,
|
||||
actorLabel,
|
||||
FINISHED_SESSION_STATUSES,
|
||||
getTaskRunnerSettings,
|
||||
getTaskAgentSettings,
|
||||
getEscalation,
|
||||
resolveAgentSettings,
|
||||
resolveRunnerSettings,
|
||||
getProjectBudget,
|
||||
listJournal,
|
||||
archivedLog,
|
||||
taskBudgetView,
|
||||
getEpic,
|
||||
isSuperadmin,
|
||||
latestReview,
|
||||
listEpics,
|
||||
listPools,
|
||||
listSubscriptions,
|
||||
parseTasks,
|
||||
prGate,
|
||||
getPendingAccept,
|
||||
getRolloutWait,
|
||||
PENDING_ACCEPT_LABEL,
|
||||
PLATFORM_DELAY_LABEL,
|
||||
taskDelayed,
|
||||
taskDelayLine,
|
||||
taskHoldReason,
|
||||
projectPool,
|
||||
PROVIDER_NAMES,
|
||||
readChange,
|
||||
reviewLabel,
|
||||
reviewPreview,
|
||||
storyProductView,
|
||||
sessionSteps,
|
||||
refinePending,
|
||||
storyComments,
|
||||
getIntakeSettings,
|
||||
getIntakeState,
|
||||
intakePending,
|
||||
taskCiSummary,
|
||||
type GateResult,
|
||||
productUrls,
|
||||
questionType,
|
||||
} from "@peppa/core";
|
||||
import { checkRuns } from "@peppa/db";
|
||||
import { desc, eq } from "drizzle-orm";
|
||||
import { getDecisions, getTeamMatch, matchLine } from "@peppa/core";
|
||||
import { PanelSection } from "@/components/ActivityAside";
|
||||
import { Hidden, SessionCard } from "@/components/cards";
|
||||
import { ago, Disclosure, Flash, PageHeader, Section, StatusBadge } from "@/components/common";
|
||||
import { LiveRefresh } from "@/components/LiveRefresh";
|
||||
import { LiveTaskStatus } from "@/components/LiveTaskStatus";
|
||||
import { TaskRunnerSettings } from "@/components/Runners";
|
||||
import { TaskAgentModel } from "@/components/AgentModel";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input, NativeSelect, Textarea } from "@/components/ui/input";
|
||||
import { Workspace } from "@/components/Workspace";
|
||||
import { ReviewPreview } from "@/components/ReviewPreview";
|
||||
import { requireUser, uiMode } from "@/lib/auth";
|
||||
import { StoryProduct } from "@/components/StoryProduct";
|
||||
import { TaskDecisions } from "@/components/TaskDecisions";
|
||||
import { db } from "@/lib/db";
|
||||
import { goals } from "@peppa/db";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { startTaskSession } from "../../actions";
|
||||
import { taskActivity, taskForUser } from "@/lib/queries";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import { editStoryAction, saveTaskBudgetAction, startTaskSession } from "../../actions";
|
||||
import { BudgetPanel } from "@/components/Accounting";
|
||||
import { ActivityTab, ArtifactTab, CommentsTab, MergeTab, ProgressBar, SpecsTab, STORY_TABS, TasksTab, TestsTab, type CheckRunRow, type StoryTab } from "./tabs";
|
||||
import { archiveTaskAction, setDependenciesAction } from "../../board-actions";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
|
||||
export default async function TaskPage({ params, searchParams }: { params: Promise<{ key: string }>; searchParams: Promise<{ error?: string }> }) {
|
||||
const CI_ICON = { success: <CircleCheck className="size-4 text-ok" />, failure: <CircleX className="size-4 text-destructive" />, pending: <Hourglass className="size-4 text-warn" /> };
|
||||
|
||||
/** Gitea behind Cloudflare can hang: the merge tab waits at most this long. */
|
||||
async function gateWithTimeout(ref: Parameters<typeof prGate>[0]): Promise<GateResult | null> {
|
||||
return Promise.race([prGate(ref).catch(() => null), new Promise<null>((r) => setTimeout(() => r(null), 5000))]);
|
||||
}
|
||||
|
||||
export default async function StoryPage({ params, searchParams }: { params: Promise<{ key: string }>; searchParams: Promise<{ error?: string; tab?: string; edit?: string; more?: string }> }) {
|
||||
const user = await requireUser();
|
||||
const t = await getT();
|
||||
const { key } = await params;
|
||||
const { error } = await searchParams;
|
||||
const sp = await searchParams;
|
||||
const ref = await taskForUser(user.id, decodeURIComponent(key)).catch(() => null);
|
||||
if (!ref) notFound();
|
||||
const { task, project } = ref;
|
||||
const [goal] = task.goalId ? await db.select().from(goals).where(eq(goals.id, task.goalId)) : [];
|
||||
const { questions, sessions, events } = await taskActivity(task.id);
|
||||
const artifacts = openspecArtifacts(project, task.openspecChange);
|
||||
const back = `/t/${ref.key}`;
|
||||
return (
|
||||
<>
|
||||
<AutoRefresh />
|
||||
<Flash error={error} />
|
||||
<p className="crumbs">
|
||||
<Link href={`/p/${project.key}`}>{project.name}</Link>
|
||||
{goal && <> · 🎯 {goal.title}</>}
|
||||
</p>
|
||||
<h1>
|
||||
<span className="mono">{ref.key}</span> {task.title} <Badge status={task.status} />
|
||||
</h1>
|
||||
{task.prUrl && <p><a href={task.prUrl}>PR</a></p>}
|
||||
<p className="desc">{task.description || <span className="muted">Без описания</span>}</p>
|
||||
const live = sessions.find((s) => !FINISHED_SESSION_STATUSES.includes(s.status)) ?? null;
|
||||
const past = sessions.filter((s) => s !== live);
|
||||
const change = readChange(project, task.openspecChange, sessions.map((s) => s.workspacePath));
|
||||
const progress = change?.tasks ? parseTasks(change.tasks) : null;
|
||||
// PEP-10: runner mode/context of this story over the project's.
|
||||
const [runnerOwn, runnerProject] = await Promise.all([getTaskRunnerSettings(db, task.id), resolveRunnerSettings(db, project.id)]);
|
||||
// PEP-41: the story's agent model over the project's, and its escalation.
|
||||
const [agentOwn, agentProject, escalation] = await Promise.all([getTaskAgentSettings(db, task.id), resolveAgentSettings(db, project.id), getEscalation(db, task.id)]);
|
||||
const ci = await taskCiSummary(db, ref);
|
||||
const review = await latestReview(db, task.id);
|
||||
const epics = await listEpics(db, project.id);
|
||||
const epic = task.goalId ? (epics.find((e) => e.id === task.goalId) ?? (await getEpic(db, project.id, task.goalId).catch(() => null))) : null;
|
||||
const tab: StoryTab = STORY_TABS.find((x) => x.id === sp.tab)?.id ?? (change ? "proposal" : "comments");
|
||||
const tabHref = (id: StoryTab) => `/t/${ref.key}?tab=${id}`;
|
||||
// PEP-120: «Продакт» sees one plain card; the rest of the page opens by «Подробнее» (?more=1, a tab or the edit form).
|
||||
const engineer = (await uiMode()) === "engineer";
|
||||
// PEP-183: was the story given to a specialist of the team (engineer only).
|
||||
const teamMatchText = engineer ? matchLine(await getTeamMatch(db, task.id)) : null;
|
||||
const detailsOpen = engineer || !!(sp.more || sp.tab || sp.edit);
|
||||
const back = engineer || sp.tab ? tabHref(tab) : detailsOpen ? `/t/${ref.key}?more=1` : `/t/${ref.key}`;
|
||||
const preview = await reviewPreview(db, ref);
|
||||
const [blockers, dependents] = await Promise.all([blockersOf(db, ref), dependentsOf(db, ref)]);
|
||||
// PEP-67: superadmins choose the subscriptions a runner may take; others run on the project's pool.
|
||||
const superadmin = await isSuperadmin(db, user);
|
||||
const pool = await projectPool(db, project.id);
|
||||
const [pools, subs] = superadmin ? await Promise.all([listPools(db), listSubscriptions(db)]) : [[], []];
|
||||
const steps = live ? await sessionSteps(db, live.id) : undefined;
|
||||
|
||||
<section>
|
||||
<h2>Сессии</h2>
|
||||
<form action={startTaskSession} className="row wrap">
|
||||
<input type="hidden" name="taskKey" value={ref.key} />
|
||||
<input type="hidden" name="back" value={back} />
|
||||
<select name="provider" defaultValue="claude" aria-label="Агент">
|
||||
<option value="claude">Claude Code</option>
|
||||
<option value="codex">Codex</option>
|
||||
</select>
|
||||
<input type="text" name="prompt" placeholder="Доп. инструкция (необязательно)" aria-label="Доп. инструкция" className="grow" />
|
||||
<button className="primary">Запустить агента</button>
|
||||
</form>
|
||||
{sessions.map((s) => <SessionCard key={s.id} s={s} back={back} />)}
|
||||
</section>
|
||||
// Only the open tab reads the rest (Gitea for the merge request).
|
||||
const comments = tab === "comments" ? await storyComments(db, task.id) : [];
|
||||
const commentRefining = tab === "comments" && (await refinePending(db, task));
|
||||
// PEP-84 / PEP-198: is the story still with the analyst?
|
||||
const intake = task.status === "backlog" ? await getIntakeState(db, task.id) : null;
|
||||
const refining = task.status === "backlog" && intakePending(await getIntakeSettings(db, ref.project.id), task, intake) ? (intake?.stage ?? "analyst") : null;
|
||||
const runs: CheckRunRow[] =
|
||||
tab === "tests" && ci.sha
|
||||
? (await db.select().from(checkRuns).where(eq(checkRuns.taskId, task.id)).orderBy(desc(checkRuns.updatedAt)))
|
||||
.filter((r) => r.sha === ci.sha)
|
||||
.sort((a, b) => a.check.localeCompare(b.check))
|
||||
// PEP-221: a tail older than a day was moved to the log archive.
|
||||
.map((r) => (r.logTail || r.state === "success" || r.state === "pending" ? r : { ...r, logTail: archivedLog("checks", r.id, r.updatedAt) }))
|
||||
: [];
|
||||
const pendingAccept = await getPendingAccept(db, task.id);
|
||||
// PEP-278: accepted, but the version with the changes is not running yet.
|
||||
const rollout = task.status === "done" && !!(await getRolloutWait(db, task.id));
|
||||
// PEP-150: a delay on the platform's side — one line instead of a message to the owner.
|
||||
// Not while a question waits for the owner: «от вас ничего не нужно» would not be true.
|
||||
const delayed = !task.archivedAt && task.status !== "done" && !questions.some((q) => !q.answeredAt) && (await taskDelayed(db, task.id));
|
||||
// PEP-209: when the next attempt comes, or that the administrator is told — never the terminal's text.
|
||||
const delayLine = delayed ? await taskDelayLine(db, task.id) : null;
|
||||
// PEP-247: in work, no agent, for a lawful reason (pause, no subscription, budget) — said on the page.
|
||||
const hold = task.status === "in_progress" && !live && !delayed && !task.archivedAt ? await taskHoldReason(db, task.projectId, task.id) : null;
|
||||
const gate = tab === "merge" && task.prUrl ? await gateWithTimeout(ref) : null;
|
||||
const openQuestions = questions.filter((q) => !q.answeredAt).length;
|
||||
const counts: Partial<Record<StoryTab, number | string>> = {
|
||||
specs: change?.specs.length || undefined,
|
||||
tasks: progress?.total ? `${progress.done}/${progress.total}` : undefined,
|
||||
comments: openQuestions || undefined,
|
||||
};
|
||||
// PEP-43: spend against the budget; PEP-48: who did each event.
|
||||
const budget = await taskBudgetView(db, task);
|
||||
const projectBudget = await getProjectBudget(db, project.id);
|
||||
const authors = new Map((await listJournal(db, { taskId: task.id, limit: 200 })).map((e) => [e.id, actorLabel(e)]));
|
||||
|
||||
<section>
|
||||
<h2>Вопросы</h2>
|
||||
{questions.length === 0 ? <p className="empty">Вопросов не было.</p> : questions.map((q) => <QuestionCard key={q.id} q={q} taskStatus={task.status} back={back} />)}
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>OpenSpec {task.openspecChange && <span className="mono muted">{task.openspecChange}</span>}</h2>
|
||||
{artifacts?.length ? (
|
||||
artifacts.map((a) => (
|
||||
<details key={a.name} open={a.name === "proposal.md"}>
|
||||
<summary className="mono">{a.name}</summary>
|
||||
<pre className="md">{a.text}</pre>
|
||||
</details>
|
||||
))
|
||||
) : (
|
||||
<p className="empty">Change ещё не создан.</p>
|
||||
const aside = (
|
||||
<div className="flex flex-col gap-6">
|
||||
<ReviewPreview preview={preview} />
|
||||
<PanelSection title={t("Расход и бюджет")}>
|
||||
<BudgetPanel view={budget} taskId={task.id} projectBudget={projectBudget} back={back} action={saveTaskBudgetAction} paused={!!budget.paused} />
|
||||
</PanelSection>
|
||||
<PanelSection title={t("Зависимости")}>
|
||||
{blockers.length === 0 && dependents.length === 0 && <p className="m-0 text-sm text-muted-foreground">{t("Стори ни от чего не зависит.")}</p>}
|
||||
{blockers.length > 0 && (
|
||||
<ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm">
|
||||
{blockers.map((b) => (
|
||||
<li key={b.id} className="flex items-center gap-2">
|
||||
{b.open ? <Lock className="size-3.5 text-warn" /> : <CircleCheck className="size-3.5 text-ok" />}
|
||||
<Link href={`/t/${b.key}`} className="min-w-0 flex-1 truncate">
|
||||
<span className="font-mono text-xs text-primary">{b.key}</span> {b.title}
|
||||
</Link>
|
||||
<StatusBadge status={b.status} />
|
||||
<form action={setDependenciesAction}>
|
||||
<Hidden fields={{ taskKey: ref.key, back, remove: b.key }} />
|
||||
{blockers.map((x) => <input key={x.id} type="hidden" name="current" value={x.key} />)}
|
||||
<button type="submit" title={t("Убрать зависимость от {key}", { key: b.key })} aria-label={t("Убрать зависимость от {key}", { key: b.key })} className="rounded p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground">
|
||||
<X className="size-3.5" />
|
||||
</button>
|
||||
</form>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
{blockers.some((b) => b.open) && <p className="m-0 text-xs text-muted-foreground">{t("Диспетчер не возьмёт стори, пока предшественники не в ревью или готово.")}</p>}
|
||||
<form action={setDependenciesAction} className="flex gap-2">
|
||||
<Hidden fields={{ taskKey: ref.key, back }} />
|
||||
{blockers.map((x) => <input key={x.id} type="hidden" name="current" value={x.key} />)}
|
||||
<Input name="blockedBy" required placeholder={t("Ждёт стори: {key}", { key: `${project.key}-3` })} aria-label={t("Добавить зависимость")} className="h-8" />
|
||||
<Button size="sm" variant="outline">{t("Добавить")}</Button>
|
||||
</form>
|
||||
{dependents.length > 0 && (
|
||||
<p className="m-0 text-sm">
|
||||
<span className="text-muted-foreground">{t("Её ждут:")} </span>
|
||||
{dependents.map((d, i) => (
|
||||
<span key={d.id}>
|
||||
{i > 0 && ", "}
|
||||
<Link href={`/t/${d.key}`} className="font-mono text-xs">{d.key}</Link>
|
||||
</span>
|
||||
))}
|
||||
</p>
|
||||
)}
|
||||
</PanelSection>
|
||||
<PanelSection title={t("Проверки")}>
|
||||
<Link href={tabHref("tests")} className="flex flex-wrap items-center gap-2 text-sm text-foreground hover:no-underline">
|
||||
{CI_ICON[ci.state as keyof typeof CI_ICON]}
|
||||
{t.text(ci.label)}
|
||||
{ci.sha && <span className="font-mono text-xs text-muted-foreground">{ci.sha.slice(0, 7)}</span>}
|
||||
</Link>
|
||||
{task.ciAttempts > 0 && <p className="m-0 text-xs text-muted-foreground">{t("красных подряд: {n}", { n: task.ciAttempts })}</p>}
|
||||
</PanelSection>
|
||||
{review && (
|
||||
<PanelSection title={t("Ревьюер")}>
|
||||
<p className="m-0 text-sm [overflow-wrap:anywhere]">{t.text(reviewLabel(review))}</p>
|
||||
<p className="m-0 text-xs text-muted-foreground">
|
||||
{review.sha.slice(0, 7)} · {ago(review.updatedAt, t)}
|
||||
</p>
|
||||
</PanelSection>
|
||||
)}
|
||||
<PanelSection title={t("Последнее")}>
|
||||
{events.length === 0 ? (
|
||||
<p className="m-0 text-sm text-muted-foreground">{t("Событий нет.")}</p>
|
||||
) : (
|
||||
<>
|
||||
<ActivityTab events={events.slice(0, 8)} authors={authors} />
|
||||
<Link href={tabHref("activity")} className="text-xs text-primary">
|
||||
{t("Вся активность →")}
|
||||
</Link>
|
||||
</>
|
||||
)}
|
||||
</PanelSection>
|
||||
</div>
|
||||
);
|
||||
|
||||
<section>
|
||||
<h2>События</h2>
|
||||
<ul className="events">
|
||||
{events.map((e) => (
|
||||
<li key={e.id}>
|
||||
<span className="muted">{ago(e.createdAt)}</span> <span className="mono">{e.type}</span>{" "}
|
||||
{e.type === "progress" ? (e.payload as { text: string }).text : e.type === "task_updated" ? JSON.stringify((e.payload as { to: unknown }).to) : ""}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
const headerActions = (
|
||||
<>
|
||||
<Button asChild size="sm" variant="outline">
|
||||
<Link href={sp.edit ? back : `${back}&edit=1`} scroll={false}>
|
||||
<Pencil />
|
||||
{t("Изменить")}
|
||||
</Link>
|
||||
</Button>
|
||||
{task.prUrl && (
|
||||
<Button asChild size="sm">
|
||||
<a href={task.prUrl}>
|
||||
<GitPullRequest />
|
||||
PR
|
||||
</a>
|
||||
</Button>
|
||||
)}
|
||||
<form action={archiveTaskAction}>
|
||||
<Hidden fields={{ taskKey: ref.key, back, archived: task.archivedAt ? "0" : "1" }} />
|
||||
<Button size="sm" variant="ghost" title={task.archivedAt ? t("Вернуть стори на доску (в конец)") : t("Убрать с доски; агент остановится, история останется")}>
|
||||
{task.archivedAt ? <><ArchiveRestore />{t("Вернуть")}</> : <><Archive />{t("В архив")}</>}
|
||||
</Button>
|
||||
</form>
|
||||
</>
|
||||
);
|
||||
|
||||
// What a product manager reads first: open questions (the «готово к ревью» message is the card's own buttons).
|
||||
// PEP-149: only messages of type `question`; failures and other factory messages stay under «Подробнее».
|
||||
const productQuestions = questions.filter((q) => !q.answeredAt && questionType(q, task.status) === "question").reverse();
|
||||
const productView = storyProductView({
|
||||
status: task.status,
|
||||
archived: !!task.archivedAt,
|
||||
progress,
|
||||
agentWorking: !!live,
|
||||
agentName: live?.agentName,
|
||||
openQuestions: productQuestions.length,
|
||||
refining,
|
||||
waitsFor: blockers.filter((b) => b.open).map((b) => b.title),
|
||||
accepted: !!pendingAccept,
|
||||
rollout,
|
||||
delayed,
|
||||
delayLine,
|
||||
// PEP-182: no agent yet because all are busy — the place in the queue.
|
||||
queued: live ? null : ((await queuePositions(db, task.projectId)).get(task.id) ?? null),
|
||||
hold: hold?.kind ?? null,
|
||||
});
|
||||
|
||||
const body = (
|
||||
<>
|
||||
{refining && (
|
||||
<p role="status" className="mb-4 flex flex-wrap items-center gap-2 rounded-lg border border-info/40 bg-info/10 px-4 py-3 text-sm">
|
||||
<span className="font-medium">{refining === "waiting" ? t("Аналитик ждёт ваших ответов") : t("Аналитик уточняет задачу")}</span>
|
||||
<span className="text-muted-foreground">
|
||||
{refining === "waiting" ? t("— вопрос во вкладке «Comments». Не ответите — возьмёт варианты по умолчанию и отдаст стори в работу.") : t("— через минуту здесь появятся критерии приёмки. Агент-разработчик возьмёт стори после этого.")}
|
||||
</span>
|
||||
</p>
|
||||
)}
|
||||
{sp.edit ? (
|
||||
<form action={editStoryAction} className="flex flex-col gap-2 rounded-lg border bg-card p-4">
|
||||
<Hidden fields={{ taskKey: ref.key, back }} />
|
||||
<label className="flex flex-col gap-1 text-sm">
|
||||
{t("Название")}
|
||||
<Input name="title" defaultValue={task.title} required minLength={2} />
|
||||
</label>
|
||||
<label className="flex flex-col gap-1 text-sm">
|
||||
{t("Описание")}
|
||||
<Textarea name="description" defaultValue={task.description ?? ""} rows={6} />
|
||||
</label>
|
||||
<label className="flex flex-col gap-1 text-sm">
|
||||
{t("Эпик")}
|
||||
<NativeSelect name="epicId" defaultValue={task.goalId ?? ""} className="w-auto">
|
||||
<option value="">{t("Без эпика")}</option>
|
||||
{epics.map((e) => (
|
||||
<option key={e.id} value={e.id}>{e.title}</option>
|
||||
))}
|
||||
{epic && !epics.some((e) => e.id === epic.id) && <option value={epic.id}>{t("{title} (в архиве)", { title: epic.title })}</option>}
|
||||
</NativeSelect>
|
||||
</label>
|
||||
<div className="flex gap-2">
|
||||
<Button size="sm">{t("Сохранить")}</Button>
|
||||
<Button asChild size="sm" variant="ghost">
|
||||
<Link href={back} scroll={false}>{t("Отмена")}</Link>
|
||||
</Button>
|
||||
</div>
|
||||
<p className="m-0 text-xs text-muted-foreground">{t("Агент не запускается; изменение попадёт в Activity.")}</p>
|
||||
</form>
|
||||
) : (
|
||||
<Disclosure open={!change} summary={<span className="text-sm font-medium">{t("Описание")}</span>}>
|
||||
{/* PEP-84: the analyst writes the story in Markdown (criteria, out of scope, assumptions). */}
|
||||
{task.description && /^## /m.test(task.description) ? (
|
||||
<Markdown text={task.description} className="text-sm" />
|
||||
) : (
|
||||
<div className="text-sm whitespace-pre-wrap [overflow-wrap:anywhere]">{task.description || <span className="text-muted-foreground">{t("Без описания")}</span>}</div>
|
||||
)}
|
||||
</Disclosure>
|
||||
)}
|
||||
|
||||
<Section title={t("Агент")} count={sessions.length || undefined}>
|
||||
{progress?.current && live && (
|
||||
<p className="m-0 text-sm">
|
||||
<span className="text-muted-foreground">{t("Сейчас по tasks.md:")}</span> {progress.current}
|
||||
</p>
|
||||
)}
|
||||
<TaskRunnerSettings taskKey={ref.key} own={runnerOwn} inherited={runnerProject} back={back} />
|
||||
<TaskAgentModel taskKey={ref.key} own={agentOwn} inherited={agentProject} escalation={escalation} back={back} />
|
||||
{live ? (
|
||||
// PEP-33 step feed of the newest unfinished runner; its terminal — in «Сессии» (PEP-257).
|
||||
<SessionCard s={live} back={back} live steps={steps} plainSteps={!engineer} />
|
||||
) : (
|
||||
<form action={startTaskSession} className="flex flex-wrap gap-2">
|
||||
<Hidden fields={{ taskKey: ref.key, back }} />
|
||||
<NativeSelect name="provider" defaultValue="" aria-label={t("Агент")} className="w-auto">
|
||||
<option value="">{pool || superadmin ? t("Любой агент") : "Claude Code"}</option>
|
||||
<option value="claude">Claude Code</option>
|
||||
<option value="codex">Codex</option>
|
||||
<option value="opencode">OpenCode</option>
|
||||
</NativeSelect>
|
||||
{superadmin && (
|
||||
<NativeSelect name="choice" defaultValue="" aria-label={t("Подписки")} className="w-auto">
|
||||
<option value="">{pool ? t("Пул проекта: {name}", { name: pool.name }) : t("Без пула (вход машины)")}</option>
|
||||
{pools.filter((p) => p.id !== pool?.id).map((p) => (
|
||||
<option key={p.id} value={`pool:${p.id}`}>{t("Пул: {name}", { name: p.name })}</option>
|
||||
))}
|
||||
{subs.length > 0 && <option value="pick">{t("Отмеченные подписки ↓")}</option>}
|
||||
</NativeSelect>
|
||||
)}
|
||||
<Input name="prompt" placeholder={t("Доп. инструкция (необязательно)")} aria-label={t("Доп. инструкция")} className="flex-[1_1_14rem]" />
|
||||
<Button variant="default">
|
||||
<Play />
|
||||
{t("Запустить агента")}
|
||||
</Button>
|
||||
{superadmin && subs.length > 0 && (
|
||||
<details className="basis-full text-sm">
|
||||
<summary className="cursor-pointer text-muted-foreground">{t("Отметить подписки (для «Отмеченные подписки»)")}</summary>
|
||||
<div className="mt-2 flex flex-col gap-1">
|
||||
{subs.map((s) => (
|
||||
<label key={s.id} className="flex items-center gap-2">
|
||||
<input type="checkbox" name="subscription" value={s.id} className="size-4 accent-primary" />
|
||||
<span className="text-muted-foreground">{PROVIDER_NAMES[s.provider]}</span> {s.name}
|
||||
<span className="text-xs text-muted-foreground">· {s.status === "active" ? t("активна") : s.status === "limited" ? t("лимит") : s.status === "pending" ? t("ожидает входа") : t("ошибка входа")} · {t("сессий {n}", { n: s.activeSessions })}</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</details>
|
||||
)}
|
||||
{!superadmin && pool && <p className="m-0 basis-full text-xs text-muted-foreground">{t("Агент запустится на свободной подписке пула «{name}».", { name: pool.name })}</p>}
|
||||
</form>
|
||||
)}
|
||||
{past.length > 0 && (
|
||||
<Disclosure summary={<span className="text-sm text-muted-foreground">{t("Прошлые сессии: {n}", { n: past.length })}</span>}>
|
||||
<div className="flex flex-col gap-2">
|
||||
{past.map((s) => (
|
||||
<SessionCard key={s.id} s={s} back={back} />
|
||||
))}
|
||||
</div>
|
||||
</Disclosure>
|
||||
)}
|
||||
</Section>
|
||||
|
||||
<nav aria-label={t("Разделы стори")} className="mt-2 flex gap-1 overflow-x-auto border-b">
|
||||
{STORY_TABS.map((x) => (
|
||||
<Link
|
||||
key={x.id}
|
||||
href={tabHref(x.id)}
|
||||
scroll={false}
|
||||
aria-current={tab === x.id ? "page" : undefined}
|
||||
className={cn(
|
||||
"-mb-px flex items-center gap-1.5 border-b-2 px-3 py-2 text-sm whitespace-nowrap text-muted-foreground hover:text-foreground hover:no-underline",
|
||||
tab === x.id ? "border-primary text-foreground" : "border-transparent",
|
||||
)}
|
||||
>
|
||||
{t(x.label)}
|
||||
{counts[x.id] != null && <span className={cn("rounded-full px-1.5 font-mono text-[11px] tabular-nums", x.id === "comments" ? "bg-primary/15 text-primary" : "bg-muted")}>{counts[x.id]}</span>}
|
||||
</Link>
|
||||
))}
|
||||
</nav>
|
||||
|
||||
<div className="flex flex-col gap-3">
|
||||
{tab === "proposal" && <ArtifactTab change={change} changeId={task.openspecChange} file="proposal" />}
|
||||
{tab === "design" && <ArtifactTab change={change} changeId={task.openspecChange} file="design" />}
|
||||
{tab === "specs" && <SpecsTab change={change} changeId={task.openspecChange} />}
|
||||
{tab === "tasks" && <TasksTab change={change} changeId={task.openspecChange} progress={progress} />}
|
||||
{tab === "comments" && <CommentsTab taskId={task.id} projectId={project.id} taskKey={ref.key} taskStatus={task.status} questions={[...questions].reverse()} comments={comments} back={back} hasLive={!!live} refining={commentRefining} />}
|
||||
{tab === "tests" && <TestsTab ci={ci} runs={runs} review={review} />}
|
||||
{tab === "merge" && <MergeTab taskKey={ref.key} taskStatus={task.status} prUrl={task.prUrl} pull={gate?.pull ?? null} gate={gate} back={back} accepted={!!pendingAccept} />}
|
||||
{tab === "activity" && <ActivityTab events={events} authors={authors} />}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
|
||||
return (
|
||||
<Workspace aside={engineer ? aside : null}>
|
||||
<LiveRefresh scope={`task:${task.id}`} />
|
||||
<Flash error={sp.error} />
|
||||
<PageHeader
|
||||
crumbs={
|
||||
<>
|
||||
<Link href={`/p/${project.key}`} className="text-muted-foreground hover:text-foreground">{project.name}</Link>
|
||||
{epic && (
|
||||
<>
|
||||
<span className="text-muted-foreground">/</span>
|
||||
<Link href={`/p/${project.key}?epic=${epic.id}`} title={t("Эпик")} className="text-muted-foreground hover:text-foreground">
|
||||
{t("эпик «{title}»", { title: epic.title })}
|
||||
</Link>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
}
|
||||
title={
|
||||
<>
|
||||
<span className="font-mono text-primary">{ref.key}</span> {task.title} {engineer && <LiveTaskStatus taskId={task.id} status={task.status} rollout={rollout} />}
|
||||
{pendingAccept && <Badge variant="ok" className="ml-1.5 align-middle whitespace-normal">{t.text(PENDING_ACCEPT_LABEL)}</Badge>}
|
||||
{engineer && hold && <Badge variant="warn" className="ml-1.5 align-middle whitespace-normal">{t.text(hold.text)}</Badge>}
|
||||
{engineer && delayed && <Badge variant="muted" className="ml-1.5 align-middle whitespace-normal">{t.text(delayLine ?? PLATFORM_DELAY_LABEL)}</Badge>}
|
||||
{task.archivedAt && <Badge variant="muted" className="ml-1.5 align-middle">{t("в архиве")}</Badge>}
|
||||
</>
|
||||
}
|
||||
actions={engineer ? headerActions : undefined}
|
||||
>
|
||||
{engineer && (
|
||||
<span className="flex flex-wrap items-center gap-x-3 gap-y-1">
|
||||
{teamMatchText && <span className="text-xs">{t.text(teamMatchText)}</span>}
|
||||
{task.openspecChange ? (
|
||||
<span className="font-mono text-xs">
|
||||
{task.openspecChange}
|
||||
{change?.archived && <span className="ml-1 rounded bg-muted px-1">{t("в архиве")}</span>}
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-xs">{t("change ещё нет")}</span>
|
||||
)}
|
||||
{progress?.total ? (
|
||||
<span className="w-56 max-w-full">
|
||||
<ProgressBar done={progress.done} total={progress.total} current={null} compact />
|
||||
</span>
|
||||
) : null}
|
||||
</span>
|
||||
)}
|
||||
</PageHeader>
|
||||
|
||||
<TaskDecisions taskKey={ref.key} decisions={await getDecisions(db, task.id)} back={back} />
|
||||
{engineer ? (
|
||||
body
|
||||
) : (
|
||||
<>
|
||||
<StoryProduct view={productView} taskKey={ref.key} taskStatus={task.status} preview={preview} questions={productQuestions} back={back} productUrl={task.status === "done" ? ((await productUrls(db, [ref.project.id])).get(ref.project.id)?.url ?? null) : null} />
|
||||
<Link
|
||||
href={detailsOpen ? `/t/${ref.key}` : `/t/${ref.key}?more=1`}
|
||||
scroll={false}
|
||||
aria-expanded={detailsOpen}
|
||||
className="mt-4 inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground hover:no-underline"
|
||||
>
|
||||
{detailsOpen ? <ChevronDown className="size-4" /> : <ChevronRight className="size-4" />}
|
||||
{t("Подробнее")}
|
||||
</Link>
|
||||
{detailsOpen && (
|
||||
<div data-story-details className="mt-3 flex flex-col gap-4">
|
||||
<div className="flex flex-wrap items-center gap-2">{headerActions}</div>
|
||||
{body}
|
||||
<div className="rounded-lg border bg-card p-4">{aside}</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</Workspace>
|
||||
);
|
||||
}
|
||||
|
||||
461
apps/web/app/(app)/t/[key]/tabs.tsx
Normal file
461
apps/web/app/(app)/t/[key]/tabs.tsx
Normal file
@ -0,0 +1,461 @@
|
||||
// Story page tabs (PEP-32): OpenSpec artifacts of the change, comments, checks, the PR and
|
||||
// the activity log. Server components; each tab reads only what it shows.
|
||||
import { AgentBadge } from "@/components/AgentBadge";
|
||||
import { CircleCheck, CircleX, ExternalLink, GitMerge, GitPullRequest, Hourglass, MessageSquare, Send } from "lucide-react";
|
||||
import type { ChangeArtifacts, CiSummary, CodeReview, DeltaOp, GiteaPull, Question, StoryComment, TasksProgress } from "@peppa/core";
|
||||
import { attachmentsByEvent, PENDING_ACCEPT_LABEL, reviewLabel, storyOwnAttachments } from "@peppa/core";
|
||||
import { db } from "@/lib/db";
|
||||
import { AttachField } from "@/components/AttachField";
|
||||
import { Attachments } from "@/components/Attachments";
|
||||
import { Hidden, QuestionCard } from "@/components/cards";
|
||||
import { Dictate } from "@/components/Dictate";
|
||||
import { ago, Disclosure, Empty } from "@/components/common";
|
||||
import { Markdown } from "@/components/Markdown";
|
||||
import { eventLine } from "@/components/RunnerConsole";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Textarea } from "@/components/ui/input";
|
||||
import { commentHint } from "@/lib/comment-hint";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import { m, translator, type Translator } from "@peppa/shared/i18n";
|
||||
import { acceptStoryAction, commentStoryAction } from "../../actions";
|
||||
|
||||
export const STORY_TABS = [
|
||||
// PEP-94: names a product manager understands (ids stay — links keep working).
|
||||
{ id: "proposal", label: m("План") },
|
||||
{ id: "design", label: m("Как устроено") },
|
||||
{ id: "specs", label: m("Требования") },
|
||||
{ id: "tasks", label: m("Шаги") },
|
||||
{ id: "comments", label: m("Обсуждение") },
|
||||
{ id: "tests", label: m("Проверки") },
|
||||
{ id: "merge", label: m("Результат") },
|
||||
{ id: "activity", label: m("История") },
|
||||
] as const;
|
||||
export type StoryTab = (typeof STORY_TABS)[number]["id"];
|
||||
|
||||
// glossary-ignore: имя OpenSpec change — техническое, как в main
|
||||
const noChange = (t: Translator, change: string | null) => <Empty>{change ? t("Change {change} не найден в рабочей копии.", { change }) : t("План ещё не написан — агент составит его, когда возьмёт стори.")}</Empty>;
|
||||
|
||||
export async function ArtifactTab({ change, changeId, file }: { change: ChangeArtifacts | null; changeId: string | null; file: "proposal" | "design" }) {
|
||||
const t = await getT();
|
||||
if (!change) return noChange(t, changeId);
|
||||
const text = change[file];
|
||||
if (!text) return <Empty>{file === "design" ? t("Отдельных решений об устройстве не понадобилось — всё есть в плане.") : t("План ещё не написан.")}</Empty>;
|
||||
return (
|
||||
<article className="rounded-lg border bg-card p-5">
|
||||
<Markdown text={text} />
|
||||
</article>
|
||||
);
|
||||
}
|
||||
|
||||
const OP: Record<DeltaOp, { label: string; variant: "ok" | "info" | "danger" | "outline" }> = {
|
||||
ADDED: { label: m("добавлено"), variant: "ok" },
|
||||
MODIFIED: { label: m("изменено"), variant: "info" },
|
||||
REMOVED: { label: m("удалено"), variant: "danger" },
|
||||
RENAMED: { label: m("переименовано"), variant: "outline" },
|
||||
};
|
||||
|
||||
export async function SpecsTab({ change, changeId }: { change: ChangeArtifacts | null; changeId: string | null }) {
|
||||
const t = await getT();
|
||||
if (!change) return noChange(t, changeId);
|
||||
if (!change.specs.length) return <Empty>{t("В change нет дельта-спецификаций (specs/*/spec.md).")}</Empty>;
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
{change.specs.map((spec) => (
|
||||
<section key={spec.capability} className="flex flex-col gap-3 rounded-lg border bg-card p-4">
|
||||
<h3 className="m-0 font-mono text-sm font-semibold">{spec.capability}</h3>
|
||||
{spec.sections.map((sec, si) => (
|
||||
<div key={si} className="flex flex-col gap-2">
|
||||
{sec.requirements.length === 0 && <p className="m-0 text-xs text-muted-foreground">{t("{op}: без требований", { op: t(OP[sec.op].label) })}</p>}
|
||||
{sec.requirements.map((r, ri) => (
|
||||
<Disclosure
|
||||
key={ri}
|
||||
open={change.specs.length === 1 && ri < 3}
|
||||
summary={
|
||||
<span className="flex min-w-0 items-center gap-2">
|
||||
<Badge variant={OP[sec.op].variant}>{t(OP[sec.op].label)}</Badge>
|
||||
<span className="min-w-0 font-medium [overflow-wrap:anywhere]">{r.name}</span>
|
||||
{r.scenarios.length > 0 && <span className="ml-auto shrink-0 font-mono text-[11px] text-muted-foreground">{t("сценариев: {n}", { n: r.scenarios.length })}</span>}
|
||||
</span>
|
||||
}
|
||||
>
|
||||
<div className="flex flex-col gap-3">
|
||||
{r.body && <Markdown text={r.body} />}
|
||||
{r.scenarios.map((sc, i) => (
|
||||
<div key={i} className="rounded-md border-l-2 border-primary/50 bg-muted/30 py-2 pr-3 pl-3">
|
||||
<p className="m-0 mb-1 text-xs font-semibold">{t("Сценарий: {name}", { name: sc.name })}</p>
|
||||
<Markdown text={sc.body} className="text-xs" />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</Disclosure>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
</section>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export async function TasksTab({ change, changeId, progress }: { change: ChangeArtifacts | null; changeId: string | null; progress: TasksProgress | null }) {
|
||||
const t = await getT();
|
||||
if (!change) return noChange(t, changeId);
|
||||
if (!progress?.total) return <Empty>{t("tasks.md ещё нет или в нём нет пунктов.")}</Empty>;
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<ProgressBar done={progress.done} total={progress.total} current={progress.current} />
|
||||
{progress.sections.map((sec, i) => {
|
||||
const done = sec.items.filter((it) => it.done).length;
|
||||
return (
|
||||
<section key={i} className="flex flex-col gap-1.5 rounded-lg border bg-card p-4">
|
||||
<h3 className="m-0 flex items-center gap-2 text-sm font-semibold">
|
||||
{sec.title || t("Пункты")}
|
||||
<span className={cn("ml-auto font-mono text-xs tabular-nums", done === sec.items.length ? "text-ok" : "text-muted-foreground")}>
|
||||
{done}/{sec.items.length}
|
||||
</span>
|
||||
</h3>
|
||||
<ul className="m-0 flex list-none flex-col gap-1 p-0">
|
||||
{sec.items.map((it, j) => (
|
||||
<li key={j} className={cn("flex items-start gap-2 text-sm", it.text === progress.current && !it.done && "rounded bg-info/10 px-1 -mx-1")}>
|
||||
<input type="checkbox" checked={it.done} readOnly disabled aria-label={it.done ? t("выполнено") : t("не выполнено")} className="mt-1 size-3.5 shrink-0 accent-primary" />
|
||||
<span className={cn("[overflow-wrap:anywhere]", it.done && "text-muted-foreground line-through decoration-muted-foreground/40")}>{it.text}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export async function ProgressBar({ done, total, current, compact = false }: { done: number; total: number; current: string | null; compact?: boolean }) {
|
||||
const t = await getT();
|
||||
const pct = total ? Math.round((done / total) * 100) : 0;
|
||||
return (
|
||||
<div className="flex min-w-0 flex-col gap-1" title={current ? t("Сейчас: {current}", { current }) : undefined}>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className={cn("flex-1 overflow-hidden rounded-full bg-muted", compact ? "h-1" : "h-1.5")}>
|
||||
<div className={cn("h-full rounded-full", done === total ? "bg-ok" : "bg-info")} style={{ width: `${pct}%` }} />
|
||||
</div>
|
||||
<span className="font-mono text-xs text-muted-foreground tabular-nums">
|
||||
{done}/{total}
|
||||
</span>
|
||||
</div>
|
||||
{current && !compact && <span className="truncate text-xs text-muted-foreground">{t("Сейчас: {current}", { current })}</span>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
type Thread = { at: number; kind: "q"; q: Question } | { at: number; kind: "c"; c: StoryComment };
|
||||
|
||||
export async function CommentsTab({ taskId, projectId, taskKey, taskStatus, questions, comments, back, hasLive, refining = false }: { taskId: number; projectId: number; taskKey: string; taskStatus: string; questions: Question[]; comments: StoryComment[]; back: string; hasLive: boolean; refining?: boolean }) {
|
||||
const t = await getT();
|
||||
// PEP-159: the files of every comment and the story's own.
|
||||
const files = await attachmentsByEvent(db, comments.map((c) => c.id));
|
||||
const own = await storyOwnAttachments(db, taskId);
|
||||
const thread: Thread[] = [...questions.map((q) => ({ at: q.createdAt.getTime(), kind: "q" as const, q })), ...comments.map((c) => ({ at: c.createdAt.getTime(), kind: "c" as const, c }))].sort((a, b) => a.at - b.at);
|
||||
return (
|
||||
<div className="flex flex-col gap-3">
|
||||
{own.length > 0 && (
|
||||
<section className="flex flex-col gap-1.5 rounded-lg border bg-card p-3.5" aria-label={t("Файлы задачи")}>
|
||||
<h3 className="m-0 text-xs font-medium text-muted-foreground">{t("Файлы задачи")}</h3>
|
||||
<Attachments files={own} />
|
||||
</section>
|
||||
)}
|
||||
{thread.length === 0 && own.length === 0 && <Empty>{t("Вопросов и комментариев пока нет.")}</Empty>}
|
||||
{thread.map((x) =>
|
||||
x.kind === "q" ? (
|
||||
<QuestionCard key={`q${x.q.id}`} q={x.q} taskStatus={taskStatus} back={back} />
|
||||
) : (
|
||||
<article key={`c${x.c.id}`} data-role={x.c.role} className={cn("flex flex-col gap-1.5 rounded-lg border p-3.5", x.c.role ? "border-info/40 bg-info/[0.06]" : "border-primary/30 bg-primary/[0.04]")}>
|
||||
<header className="flex items-center gap-2 text-xs text-muted-foreground">
|
||||
{x.c.role ? <AgentBadge name={x.c.login} role className="font-medium text-foreground" /> : <MessageSquare className="size-3.5 text-primary" />}
|
||||
{x.c.role ? (x.c.role === "product" ? t("зачем и что берём") : t("что должно получиться")) : <><span className="font-medium text-foreground">{x.c.login}</span> {t("комментарий PM")}</>} · {ago(x.c.createdAt, t)}
|
||||
</header>
|
||||
<p className="m-0 text-sm whitespace-pre-wrap [overflow-wrap:anywhere]">{x.c.text}</p>
|
||||
<Attachments files={files.get(x.c.id)} />
|
||||
</article>
|
||||
),
|
||||
)}
|
||||
{refining && (
|
||||
<p data-refining className="m-0 flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<Hourglass className="size-3.5" />
|
||||
{t("Аналитик уточняет постановку…")}
|
||||
</p>
|
||||
)}
|
||||
<form action={commentStoryAction} className="flex flex-col gap-2 rounded-lg border bg-card p-3.5">
|
||||
<Hidden fields={{ taskKey, back }} />
|
||||
<label htmlFor="story-comment" className="text-sm font-medium">
|
||||
{t("Комментарий к стори")}
|
||||
</label>
|
||||
<Textarea id="story-comment" name="text" rows={3} maxLength={60000} placeholder={t("Что учесть или изменить в задаче")} aria-describedby="story-comment-hint" />
|
||||
<AttachField projectId={projectId} target="story-comment" />
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<Dictate target="story-comment" />
|
||||
<p id="story-comment-hint" className="m-0 text-sm text-muted-foreground">
|
||||
{t(commentHint(taskStatus, hasLive))}
|
||||
</p>
|
||||
{hasLive && (
|
||||
<label className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<input type="checkbox" name="toAgent" value="1" defaultChecked className="size-4 accent-primary" />
|
||||
{t("Отправить агенту сейчас")}
|
||||
</label>
|
||||
)}
|
||||
<Button size="sm" className="ml-auto">
|
||||
<Send />
|
||||
{t("Оставить комментарий")}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const STATE_ICON = {
|
||||
success: <CircleCheck className="size-4 text-ok" />,
|
||||
failure: <CircleX className="size-4 text-destructive" />,
|
||||
error: <CircleX className="size-4 text-destructive" />,
|
||||
pending: <Hourglass className="size-4 text-warn" />,
|
||||
};
|
||||
|
||||
export interface CheckRunRow {
|
||||
check: string;
|
||||
state: "pending" | "success" | "failure" | "error";
|
||||
runUrl: string | null;
|
||||
logTail: string | null;
|
||||
durationSec: number | null;
|
||||
updatedAt: Date;
|
||||
}
|
||||
|
||||
export async function TestsTab({ ci, runs, review }: { ci: CiSummary; runs: CheckRunRow[]; review: CodeReview | null }) {
|
||||
const t = await getT();
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<section className="flex flex-col gap-3 rounded-lg border bg-card p-4">
|
||||
<h3 className="m-0 flex flex-wrap items-center gap-2 text-sm font-semibold">
|
||||
{STATE_ICON[ci.state as keyof typeof STATE_ICON]}
|
||||
{ci.state === "not_configured" ? t("Проверки не настроены") : t.text(ci.label)}
|
||||
{ci.sha && <span className="font-mono text-xs font-normal text-muted-foreground">{t("коммит {sha}", { sha: ci.sha.slice(0, 7) })}</span>}
|
||||
{ci.runUrl && (
|
||||
<a href={ci.runUrl} className="ml-auto text-xs font-normal text-primary">
|
||||
{t("запуск в Gitea")}
|
||||
</a>
|
||||
)}
|
||||
</h3>
|
||||
{ci.state === "not_configured" && <p className="m-0 text-sm text-muted-foreground">{t("В `.peppa/project.json` проекта нет `checks` — PR проверяется только человеком.")}</p>}
|
||||
{ci.state === "none" && <p className="m-0 text-sm text-muted-foreground">{t("Проверки ещё не запускались: появятся после первого пуша ветки стори.")}</p>}
|
||||
{runs.length > 0 && (
|
||||
<ul className="m-0 flex list-none flex-col gap-1.5 p-0">
|
||||
{runs.map((r) => (
|
||||
<li key={r.check}>
|
||||
{r.logTail && r.state !== "success" ? (
|
||||
<Disclosure open={r.state !== "pending"} summary={<CheckLine r={r} />}>
|
||||
<pre className="m-0 max-h-80 overflow-auto font-mono text-[11px] whitespace-pre-wrap">{r.logTail.split("\n").slice(-80).join("\n")}</pre>
|
||||
</Disclosure>
|
||||
) : (
|
||||
<div className="px-3 py-1.5">
|
||||
<CheckLine r={r} />
|
||||
</div>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
<section className="flex flex-col gap-2 rounded-lg border bg-card p-4">
|
||||
<h3 className="m-0 text-sm font-semibold">{t("Агент-ревьюер")}</h3>
|
||||
{review ? (
|
||||
<>
|
||||
<p className="m-0 flex flex-wrap items-center gap-2 text-sm">
|
||||
{review.verdict === "ok" ? STATE_ICON.success : review.verdict === "changes" || review.state === "error" ? STATE_ICON.failure : STATE_ICON.pending}
|
||||
<span className="[overflow-wrap:anywhere]">{t.text(reviewLabel(review))}</span>
|
||||
<span className="font-mono text-xs text-muted-foreground">
|
||||
{review.sha.slice(0, 7)} · {ago(review.updatedAt, t)}
|
||||
</span>
|
||||
</p>
|
||||
{review.summary && <Markdown text={review.summary} className="text-xs" />}
|
||||
{review.findings.length > 0 && (
|
||||
<ul className="m-0 flex list-disc flex-col gap-1 pl-5 text-xs">
|
||||
{review.findings.map((f, i) => (
|
||||
<li key={i} className="[overflow-wrap:anywhere]">
|
||||
{f.file && <span className="font-mono text-muted-foreground">{f.file}{f.line ? `:${f.line}` : ""} — </span>}
|
||||
{f.text}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<p className="m-0 text-sm text-muted-foreground">{t("Ревью не было: ревьюер выключен в настройках проекта или PR ещё не отдан в ревью.")}</p>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
async function CheckLine({ r }: { r: CheckRunRow }) {
|
||||
const t = await getT();
|
||||
return (
|
||||
<span className="flex min-w-0 items-center gap-2 text-sm">
|
||||
{STATE_ICON[r.state]}
|
||||
<span className="font-mono">{r.check}</span>
|
||||
{r.durationSec != null && <span className="font-mono text-xs text-muted-foreground">{t("{n} с", { n: r.durationSec })}</span>}
|
||||
<span className="ml-auto font-mono text-xs text-muted-foreground">{ago(r.updatedAt, t)}</span>
|
||||
{r.runUrl && (
|
||||
<a href={r.runUrl} className="text-xs text-primary">
|
||||
{t("лог")}
|
||||
</a>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export async function MergeTab({
|
||||
taskKey,
|
||||
taskStatus,
|
||||
prUrl,
|
||||
pull,
|
||||
gate,
|
||||
back,
|
||||
accepted,
|
||||
}: {
|
||||
taskKey: string;
|
||||
taskStatus: string;
|
||||
prUrl: string | null;
|
||||
pull: GiteaPull | null;
|
||||
gate: { ok: boolean; reason?: string } | null;
|
||||
back: string;
|
||||
/** PEP-127: «Принять» is remembered — the agent updates the changes, Peppa closes the story itself. */
|
||||
accepted?: boolean;
|
||||
}) {
|
||||
const t = await getT();
|
||||
// PEP-127: an open PR that can't be merged yet does not block «Принять» — it is remembered and carried through.
|
||||
const carried = pull?.state === "open" && !!gate && !gate.ok;
|
||||
const checksFailed = !!gate?.reason?.startsWith("проверки не пройдены"); // i18n-ignore: the Russian reason from core (prGate)
|
||||
if (!prUrl) return <Empty>{t("PR ещё нет — агент откроет его, когда закончит работу.")}</Empty>;
|
||||
return (
|
||||
<section className="flex flex-col gap-3 rounded-lg border bg-card p-4">
|
||||
<h3 className="m-0 flex flex-wrap items-center gap-2 text-sm font-semibold">
|
||||
{pull?.merged ? <GitMerge className="size-4 text-ok" /> : <GitPullRequest className={cn("size-4", pull?.state === "closed" ? "text-destructive" : "text-primary")} />}
|
||||
{pull ? (
|
||||
<>
|
||||
#{pull.number} {pull.title}
|
||||
</>
|
||||
) : (
|
||||
"Pull request"
|
||||
)}
|
||||
<Badge variant={pull?.merged ? "ok" : pull?.state === "closed" ? "danger" : "info"} className="ml-auto">
|
||||
{pull ? (pull.merged ? t("смержен") : pull.state === "closed" ? t("закрыт") : t("открыт")) : t("Gitea недоступна")}
|
||||
</Badge>
|
||||
</h3>
|
||||
{pull && (
|
||||
<dl className="m-0 grid grid-cols-[max-content_minmax(0,1fr)] gap-x-3 gap-y-1.5 text-sm">
|
||||
<dt className="text-muted-foreground">{t("Ветка")}</dt>
|
||||
<dd className="m-0 font-mono text-xs [overflow-wrap:anywhere]">
|
||||
{pull.head.ref} → {pull.base.ref}
|
||||
</dd>
|
||||
<dt className="text-muted-foreground">{t("Коммит")}</dt>
|
||||
<dd className="m-0 font-mono text-xs">{pull.head.sha.slice(0, 10)}</dd>
|
||||
{!pull.merged && pull.state === "open" && (
|
||||
<>
|
||||
<dt className="text-muted-foreground">{t("Мерж")}</dt>
|
||||
<dd className="m-0">{gate?.ok ? <span className="text-ok">{t("можно мержить")}</span> : <span className="text-warn">{gate?.reason ? t.text(gate.reason) : pull.mergeable ? t("без конфликтов") : t("есть конфликты")}</span>}</dd>
|
||||
</>
|
||||
)}
|
||||
</dl>
|
||||
)}
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Button asChild variant="outline" size="sm">
|
||||
<a href={prUrl}>
|
||||
<ExternalLink />
|
||||
{t("PR в Gitea")}
|
||||
</a>
|
||||
</Button>
|
||||
<Button asChild variant="outline" size="sm">
|
||||
<a href={`${prUrl.replace(/\/$/, "")}/files`}>{t("Дифф")}</a>
|
||||
</Button>
|
||||
{taskStatus === "review" && !pull?.merged && !accepted && (
|
||||
<form action={acceptStoryAction} className="ml-auto">
|
||||
<Hidden fields={{ taskKey, back }} />
|
||||
<Button size="sm" disabled={!!gate && !gate.ok && (!carried || checksFailed)} title={checksFailed && gate?.reason ? t.text(gate.reason) : carried ? t("Сначала изменения обновятся и пройдут проверки, затем задача закроется сама") : undefined}>
|
||||
<GitMerge />
|
||||
{t("Принять и смержить")}
|
||||
</Button>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
{accepted && !pull?.merged && <p className="m-0 text-sm text-ok">{t("{label}. Нажимать ещё раз не нужно — мы сообщим, когда задача закроется.", { label: t.text(PENDING_ACCEPT_LABEL) })}</p>}
|
||||
{!accepted && taskStatus !== "review" && !pull?.merged && <p className="m-0 text-xs text-muted-foreground">{t("Мерж — когда стори в ревью: агент отдаёт её туда после зелёных проверок.")}</p>}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
const EVENT_RU: Record<string, string> = {
|
||||
task_updated: m("стори изменена"),
|
||||
progress: m("прогресс"),
|
||||
pm_comment: m("комментарий"),
|
||||
claude_session: m("сессия агента"),
|
||||
claude_session_end: m("конец сессии агента"),
|
||||
session_started: m("раннер запущен"),
|
||||
session_stopped: m("раннер остановлен"),
|
||||
auto_continue: m("автопродолжение"),
|
||||
awaiting_review: m("ждёт ревьюера"),
|
||||
stop_failure: m("ход оборвался"),
|
||||
notification: m("уведомление"),
|
||||
terminal_input: m("ввод в терминал"),
|
||||
subscription_switched: m("смена подписки"),
|
||||
};
|
||||
|
||||
export interface ActivityEvent {
|
||||
id: number;
|
||||
type: string;
|
||||
payload: unknown;
|
||||
sessionId: number | null;
|
||||
createdAt: Date;
|
||||
}
|
||||
|
||||
/** Who did it: a PM by login, the agent of a session, or Peppa itself. */
|
||||
export function eventAuthor(e: ActivityEvent, authors?: Map<number, string | null>, t: Translator = translator("ru")): { label: string; tone: "pm" | "agent" | "system" } {
|
||||
// PEP-48: the recorded author (person + channel, agent, Peppa) when the event has one.
|
||||
const kind = (e as { actorKind?: string | null }).actorKind;
|
||||
const recorded = authors?.get(e.id);
|
||||
if (kind && recorded) return { label: t.text(recorded), tone: kind === "user" ? "pm" : kind === "agent" ? "agent" : "system" };
|
||||
const login = (e.payload as { login?: unknown } | null)?.login;
|
||||
if (typeof login === "string" && login) return { label: login, tone: "pm" };
|
||||
if (e.sessionId) return { label: t("агент · #{id}", { id: e.sessionId }), tone: "agent" };
|
||||
return { label: t("система"), tone: "system" };
|
||||
}
|
||||
|
||||
const CHANGE_FIELD: Record<string, string> = { status: m("статус"), title: m("название"), description: m("описание"), goalId: m("эпик"), openspecChange: "change", prUrl: "PR" };
|
||||
|
||||
function changeLine(e: ActivityEvent, t: Translator): string {
|
||||
if (e.type !== "task_updated") return eventLine(e, t);
|
||||
const to = ((e.payload as { to?: Record<string, unknown> } | null)?.to ?? {}) as Record<string, unknown>;
|
||||
const parts = Object.entries(to).map(([k, v]) => {
|
||||
const name = t(CHANGE_FIELD[k] ?? k);
|
||||
return k === "description" ? name : `${name} → ${v ?? "—"}`;
|
||||
});
|
||||
return parts.join(", ");
|
||||
}
|
||||
|
||||
export async function ActivityTab({ events, authors }: { events: ActivityEvent[]; authors?: Map<number, string | null> }) {
|
||||
const t = await getT();
|
||||
if (!events.length) return <Empty>{t("Событий нет.")}</Empty>;
|
||||
return (
|
||||
<ol className="m-0 flex list-none flex-col gap-0 border-l p-0 pl-4">
|
||||
{events.map((e) => {
|
||||
const a = eventAuthor(e, authors, t);
|
||||
return (
|
||||
<li key={e.id} className="relative py-1.5 text-sm [overflow-wrap:anywhere]">
|
||||
<span className={cn("absolute top-3 -left-[1.3rem] size-2 rounded-full", a.tone === "pm" ? "bg-primary" : a.tone === "agent" ? "bg-info" : "bg-muted-foreground")} />
|
||||
<span className="font-mono text-xs text-muted-foreground">{ago(e.createdAt, t)}</span> <span className={cn("text-xs font-medium", a.tone === "pm" ? "text-primary" : a.tone === "agent" ? "text-info" : "text-muted-foreground")}>{a.label}</span>{" "}
|
||||
<span className="font-mono text-xs text-muted-foreground">{EVENT_RU[e.type] ? t(EVENT_RU[e.type]) : e.type}</span> {changeLine(e, t)}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ol>
|
||||
);
|
||||
}
|
||||
60
apps/web/app/(app)/team/actions.ts
Normal file
60
apps/web/app/(app)/team/actions.ts
Normal file
@ -0,0 +1,60 @@
|
||||
"use server";
|
||||
|
||||
import { createAgent, isSuperadmin, PeppaError, setTeamChaseHidden, setTeamSettings, updateAgent } from "@peppa/core";
|
||||
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";
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
|
||||
/** PEP-75: the team is platform-wide, so only a superadmin changes it. */
|
||||
async function run(fn: () => Promise<string | void>): Promise<never> {
|
||||
let target = "/team";
|
||||
try {
|
||||
const user = asWebActor(await requireUser());
|
||||
if (!(await isSuperadmin(db, user))) throw new PeppaError(m("Команду меняет только суперадмин"));
|
||||
target = (await fn()) || target;
|
||||
} catch (e) {
|
||||
const t = await getT();
|
||||
const msg = e instanceof PeppaError ? t.text(e.message) : t("Ошибка: {message}", { message: (e as Error).message });
|
||||
target = `/team?error=${encodeURIComponent(msg.slice(0, 300))}`;
|
||||
}
|
||||
revalidatePath("/", "layout");
|
||||
redirect(target);
|
||||
}
|
||||
|
||||
export async function addAgentAction(f: FormData) {
|
||||
await run(async () => {
|
||||
const a = await createAgent(db, { name: String(f.get("name") ?? "") });
|
||||
return `/team?saved=${a.id}#agent-${a.id}`;
|
||||
});
|
||||
}
|
||||
|
||||
export async function saveAgentAction(f: FormData) {
|
||||
await run(async () => {
|
||||
const id = Number(f.get("id"));
|
||||
await updateAgent(db, id, { name: String(f.get("name") ?? ""), character: String(f.get("character") ?? "") });
|
||||
return `/team?saved=${id}#agent-${id}`;
|
||||
});
|
||||
}
|
||||
|
||||
export async function toggleAgentAction(f: FormData) {
|
||||
await run(async () => {
|
||||
await updateAgent(db, Number(f.get("id")), { disabled: f.get("disabled") === "1" });
|
||||
});
|
||||
}
|
||||
|
||||
/** PEP-183: how long a story waits for its busy specialist. */
|
||||
export async function saveTeamWaitAction(f: FormData) {
|
||||
await run(async () => {
|
||||
await setTeamSettings(db, { waitMin: Number(f.get("waitMin")) });
|
||||
return "/team?saved=wait";
|
||||
});
|
||||
}
|
||||
|
||||
/** PEP-179: «Скрыть» / «Показать» on the team picture — the user's own choice, anyone may. */
|
||||
export async function setTeamChaseHiddenAction(hidden: boolean): Promise<void> {
|
||||
const user = await requireUser();
|
||||
await setTeamChaseHidden(db, user.id, hidden);
|
||||
}
|
||||
123
apps/web/app/(app)/team/page.tsx
Normal file
123
apps/web/app/(app)/team/page.tsx
Normal file
@ -0,0 +1,123 @@
|
||||
import { Plus } from "lucide-react";
|
||||
import { AGENT_CHARACTER_MAX, getTeamSettings, isSuperadmin, listAgents, teamChaseHidden, teamChaseView } from "@peppa/core";
|
||||
import { AgentBadge } from "@/components/AgentBadge";
|
||||
import { Empty, Flash, Notice, PageHeader, Section } from "@/components/common";
|
||||
import { LiveRefresh } from "@/components/LiveRefresh";
|
||||
import { Markdown } from "@/components/Markdown";
|
||||
import { TeamChase } from "@/components/TeamChase";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card } from "@/components/ui/card";
|
||||
import { Input, Label, Textarea } from "@/components/ui/input";
|
||||
import { Workspace } from "@/components/Workspace";
|
||||
import { requireUser, words } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import { acceptInbox } from "@/lib/queries";
|
||||
import { addAgentAction, saveAgentAction, saveTeamWaitAction, toggleAgentAction } from "./actions";
|
||||
|
||||
export async function generateMetadata() {
|
||||
const t = await getT();
|
||||
return { title: t("Команда — FORGE") };
|
||||
}
|
||||
|
||||
/** PEP-75: the platform's team of agents — names and characters. Everyone sees it; a superadmin edits. */
|
||||
export default async function Team({ searchParams }: { searchParams: Promise<{ error?: string; saved?: string }> }) {
|
||||
const user = await requireUser();
|
||||
const t = await getT();
|
||||
const { error, saved } = await searchParams;
|
||||
const w = await words();
|
||||
const [team, admin, chase, chaseHidden, awaiting, teamSettings] = await Promise.all([listAgents(db), isSuperadmin(db, user), teamChaseView(db, user), teamChaseHidden(db, user.id), acceptInbox(user.id), getTeamSettings(db)]);
|
||||
return (
|
||||
<Workspace>
|
||||
<div className="max-w-3xl">
|
||||
<Flash error={error} />
|
||||
{saved === "wait" && <Notice>{t("Порог ожидания сохранён")}</Notice>}
|
||||
{saved && saved !== "wait" && <Notice>{t("Сохранено — агент получит новый характер при следующем запуске или перезапуске.")}</Notice>}
|
||||
<PageHeader title={t("Команда")}>
|
||||
{t("Это ИИ-агенты, не люди: у каждого своя кличка и характер, одна команда на все проекты. Свободный агент берёт {task} и ведёт её до конца; если все заняты — в команде появляется новый.", { task: w.task("acc") })}
|
||||
{w.engineer ? t(" Характер добавляется к промпту агента поверх правил FORGE и AGENTS.md проекта.") : t(" Характер влияет на то, как агент работает и пишет вам.")}
|
||||
</PageHeader>
|
||||
|
||||
<TeamChase view={chase} hidden={chaseHidden} awaitingKey={awaiting.find((q) => q.taskKey)?.taskKey ?? null} />
|
||||
|
||||
{admin && (
|
||||
<Card>
|
||||
<form action={addAgentAction} className="flex flex-wrap items-end gap-2">
|
||||
<Label className="min-w-48 flex-1">
|
||||
{t("Новый агент")}
|
||||
<Input name="name" placeholder={t("Кличка — или пусто: выберем сами")} maxLength={40} autoComplete="off" />
|
||||
</Label>
|
||||
<Button variant="default">
|
||||
<Plus /> {t("Добавить")}
|
||||
</Button>
|
||||
</form>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{admin && (
|
||||
<Card>
|
||||
<form action={saveTeamWaitAction} className="flex flex-wrap items-end gap-2">
|
||||
<Label className="min-w-64 flex-1">
|
||||
{t("Сколько минут {task} ждёт занятого специалиста, прежде чем её возьмёт другой агент", { task: w.task() })}
|
||||
<Input name="waitMin" type="number" min={0} max={1440} defaultValue={teamSettings.waitMin} className="max-w-32" />
|
||||
</Label>
|
||||
<Button size="sm" variant="default">{t("Сохранить")}</Button>
|
||||
</form>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<Section title={t("Агенты")} count={team.length}>
|
||||
{team.length === 0 && <Empty>{t("Пока никого: первый агент появится, когда {task} уйдёт «В работу».", { task: w.task() })}</Empty>}
|
||||
{team.map((a) => (
|
||||
<Card key={a.id} id={`agent-${a.id}`} className="gap-3" data-agent={a.name}>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<AgentBadge name={a.name} large />
|
||||
{a.busy > 0 ? <Badge variant="info">{t("работает")}{a.busy > 1 ? ` ×${a.busy}` : ""}</Badge> : <Badge variant="muted">{t("свободен")}</Badge>}
|
||||
{a.specialist && <Badge variant="ok">{t("специалист")}</Badge>}
|
||||
{a.specialist && <span className="text-xs text-muted-foreground">{t("по профилю: {n}", { n: a.profileTasks })}</span>}
|
||||
{a.disabledAt && <Badge variant="danger">{t("не в команде")}</Badge>}
|
||||
<span className="ml-auto text-xs text-muted-foreground">{t("запусков: {n}", { n: a.runs })}</span>
|
||||
</div>
|
||||
{admin ? (
|
||||
<>
|
||||
<form action={saveAgentAction} className="flex flex-col gap-2">
|
||||
<input type="hidden" name="id" value={a.id} />
|
||||
<Label className="max-w-xs">
|
||||
{t("Кличка")}
|
||||
<Input name="name" defaultValue={a.name} required maxLength={40} autoComplete="off" />
|
||||
</Label>
|
||||
<Label>
|
||||
{t("Характер и специализация")}
|
||||
<Textarea
|
||||
name="character"
|
||||
defaultValue={a.character}
|
||||
rows={a.character ? 8 : 3}
|
||||
maxLength={AGENT_CHARACTER_MAX}
|
||||
placeholder={t("Например: педант по безопасности — любой ввод проверяет, секреты ищет в каждом диффе. Пишет коротко и сухо, без извинений.")}
|
||||
className="text-sm"
|
||||
/>
|
||||
</Label>
|
||||
<Button className="self-start" size="sm" variant="default">{t("Сохранить")}</Button>
|
||||
</form>
|
||||
<form action={toggleAgentAction}>
|
||||
<input type="hidden" name="id" value={a.id} />
|
||||
<input type="hidden" name="disabled" value={a.disabledAt ? "0" : "1"} />
|
||||
<Button size="sm" variant="ghost" className="text-muted-foreground">
|
||||
{a.disabledAt ? t("Вернуть в команду") : t("Убрать из команды — новые {tasks} не получит", { tasks: w.task("accPl") })}
|
||||
</Button>
|
||||
</form>
|
||||
</>
|
||||
) : a.character ? (
|
||||
<Markdown text={a.character} />
|
||||
) : (
|
||||
<p className="m-0 text-sm text-muted-foreground">{t("Характер не задан.")}</p>
|
||||
)}
|
||||
</Card>
|
||||
))}
|
||||
</Section>
|
||||
</div>
|
||||
<LiveRefresh scope="team" pauseHidden />
|
||||
</Workspace>
|
||||
);
|
||||
}
|
||||
113
apps/web/app/(app)/users/merge/page.tsx
Normal file
113
apps/web/app/(app)/users/merge/page.tsx
Normal file
@ -0,0 +1,113 @@
|
||||
// glossary-ignore-file: the page is for the superadmin only (accounts, repositories, Gitea spaces).
|
||||
import Link from "next/link";
|
||||
import { notFound } from "next/navigation";
|
||||
import { isSuperadmin, maskIin, mergePlan, PeppaError } from "@peppa/core";
|
||||
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 { Workspace } from "@/components/Workspace";
|
||||
import { requireUser } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import { mergeAccountsAction } from "../../actions";
|
||||
|
||||
/** PEP-204: what moves from the old account to the main one — confirmed before anything changes. Superadmin only. */
|
||||
export default async function MergeAccounts({ searchParams }: { searchParams: Promise<{ from?: string; to?: string; error?: string }> }) {
|
||||
const me = await requireUser();
|
||||
if (!(await isSuperadmin(db, me))) notFound();
|
||||
const t = await getT();
|
||||
const { from, to, error } = await searchParams;
|
||||
const plan = await mergePlan(db, Number(from), Number(to)).catch((e) => {
|
||||
if (e instanceof PeppaError) notFound();
|
||||
throw e;
|
||||
});
|
||||
const back = `/users/merge?from=${plan.from.id}&to=${plan.to.id}`;
|
||||
const who = (u: typeof plan.from) => (
|
||||
<span>
|
||||
<span className="font-mono font-medium">{u.login}</span>
|
||||
{u.name && <span className="text-muted-foreground"> · {u.name}</span>}
|
||||
{u.egovIin && <span className="text-muted-foreground"> · eGov {maskIin(u.egovIin)}</span>}
|
||||
{(u.googleEmail || u.email) && <span className="text-muted-foreground"> · {u.googleEmail ?? u.email}</span>}
|
||||
</span>
|
||||
);
|
||||
const rows: [string, string[]][] = [
|
||||
[t("Проекты"), plan.projects.map((p) => `${p.key} «${p.name}»`)],
|
||||
[t("Участие в проектах"), plan.memberships.map((p) => `${p.key} «${p.name}»`)],
|
||||
[t("Приглашения"), plan.invites ? [String(plan.invites)] : []],
|
||||
[t("Подписки"), plan.subscriptions],
|
||||
[t("Пулы подписок"), plan.pools],
|
||||
[t("Чаты"), [...(plan.masterChat ? [t("личный чат")] : []), ...(plan.groups ? [t("Telegram-группы: {n}", { n: plan.groups })] : [])]],
|
||||
[t("Telegram"), plan.telegram ? [t("привязка")] : []],
|
||||
[t("Свой бот"), plan.bot ? [`@${plan.bot}`] : []],
|
||||
[t("Способы входа"), [...(plan.egov ? ["eGov"] : []), ...(plan.google ? [`Google ${plan.google}`] : [])]],
|
||||
];
|
||||
const moving = rows.filter(([, v]) => v.length);
|
||||
const personal = plan.projects.filter((p) => p.personalRepo);
|
||||
return (
|
||||
<Workspace>
|
||||
<div className="max-w-3xl">
|
||||
<Flash error={error} />
|
||||
<PageHeader crumbs={<Link href="/users" className="hover:underline">{t("Пользователи")}</Link>} title={t("Объединить учётки")}>
|
||||
{t("Всё, с чем человек работает, переедет со старой учётки на главную. Старая учётка будет отключена.")}
|
||||
</PageHeader>
|
||||
|
||||
<Card className="mb-4 gap-2 text-sm">
|
||||
<div>{t("Старая учётка:")} {who(plan.from)}</div>
|
||||
<div>{t("Главная учётка (куда переносим):")} {who(plan.to)}</div>
|
||||
</Card>
|
||||
|
||||
{plan.refusal ? (
|
||||
<Notice>{t.text(plan.refusal)}</Notice>
|
||||
) : (
|
||||
<>
|
||||
<Section title={t("Переедет")}>
|
||||
{moving.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">
|
||||
{moving.map(([k, v]) => (
|
||||
<li key={k}>
|
||||
<span className="text-muted-foreground">{k}:</span> {v.join(", ")}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</Section>
|
||||
<Section title={t("Останется")}>
|
||||
<ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm">
|
||||
<li>{t("История (журнал, комментарии, ответы) — под старым логином {login}.", { login: plan.from.login })}</li>
|
||||
{plan.projects.map((p) => (
|
||||
<li key={p.id}>
|
||||
{t("Репозиторий {key}: {repo}", { key: p.key, repo: p.repo })}
|
||||
{p.personalRepo && <span> — {t("лежит в личном пространстве старой учётки Gitea; остаётся там, агенты работают с ним через peppa-bot")}</span>}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
{personal.length > 0 && <Notice>{t("Перенос репозиториев между пространствами Gitea не выполняется.")}</Notice>}
|
||||
</Section>
|
||||
<form action={mergeAccountsAction} className="flex flex-col gap-2">
|
||||
<Hidden fields={{ from: plan.from.id, to: plan.to.id, back }} />
|
||||
<label className="flex items-center gap-2 text-sm">
|
||||
<input type="checkbox" name="confirm" value="1" required />
|
||||
{t("Да, это один человек — объединить")}
|
||||
</label>
|
||||
{plan.adminConfirm && (
|
||||
<label className="flex items-center gap-2 text-sm">
|
||||
<input type="checkbox" name="confirmAdmin" value="1" required />
|
||||
{t("Одна из учёток — суперадмин, и это сделано намеренно")}
|
||||
</label>
|
||||
)}
|
||||
<div className="flex gap-2">
|
||||
<Button size="sm" variant="destructive">{t("Объединить")}</Button>
|
||||
<Button asChild size="sm" variant="ghost">
|
||||
<Link href="/users">{t("Отмена")}</Link>
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</Workspace>
|
||||
);
|
||||
}
|
||||
96
apps/web/app/(app)/users/page.tsx
Normal file
96
apps/web/app/(app)/users/page.tsx
Normal file
@ -0,0 +1,96 @@
|
||||
import { notFound } from "next/navigation";
|
||||
import Link from "next/link";
|
||||
import { canLogIn, isLocalUser, isSuperadmin, listUsers, maskIin, mergeHints, platformAdmins } from "@peppa/core";
|
||||
import { Hidden } from "@/components/cards";
|
||||
import { ago, Flash, PageHeader, Section } from "@/components/common";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card } from "@/components/ui/card";
|
||||
import { NativeSelect } 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 { setSuperadminAction, setUserDisabledAction } from "../actions";
|
||||
|
||||
const back = { back: "/users" };
|
||||
|
||||
/** Superadmin only (PEP-68/71): who is registered, disable / enable. */
|
||||
export default async function Users({ searchParams }: { searchParams: Promise<{ error?: string }> }) {
|
||||
const me = await requireUser();
|
||||
if (!(await isSuperadmin(db, me))) notFound();
|
||||
const t = await getT();
|
||||
const { error } = await searchParams;
|
||||
const all = await listUsers(db);
|
||||
const admins = new Set(await platformAdmins(db));
|
||||
const hints = await mergeHints(db, all);
|
||||
const mains = all.filter((u) => !u.disabledAt && canLogIn(u));
|
||||
return (
|
||||
<Workspace>
|
||||
<div className="max-w-3xl">
|
||||
<Flash error={error} />
|
||||
<PageHeader title={t("Пользователи")}>
|
||||
{t(
|
||||
"Вход только через eGov: первый вход по QR сам создаёт учётку по ИИН. Доступ к проектам — приглашением владельца; агенты проекта нового пользователя работают только на пуле подписок. Отключённый пользователь сразу теряет сессии веба и MCP.",
|
||||
)}
|
||||
</PageHeader>
|
||||
|
||||
<Section title={t("Все пользователи")} count={all.length}>
|
||||
{all.map((u) => {
|
||||
const local = isLocalUser(u);
|
||||
const hint = hints.get(u.id);
|
||||
const targets = mains.filter((v) => v.id !== u.id);
|
||||
const isAdmin = admins.has(u.login.toLowerCase());
|
||||
return (
|
||||
<Card key={u.id} className="gap-3" data-user={u.login}>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className="font-mono font-medium">{u.login}</span>
|
||||
{u.name && <span className="text-sm text-muted-foreground">{u.name}</span>}
|
||||
{!local && <Badge variant="muted">Gitea</Badge>}
|
||||
{isAdmin && <Badge variant="primary">{t("суперадмин")}</Badge>}
|
||||
{u.disabledAt && <Badge variant="danger">{t("отключён")}</Badge>}
|
||||
{u.egovIin && <Badge variant="muted">eGov {maskIin(u.egovIin)}</Badge>}
|
||||
{u.googleSub && <Badge variant="muted">Google {u.googleEmail}</Badge>}
|
||||
{!canLogIn(u) && !hint?.stranded && <Badge variant="warn">{t("без eGov и Google — не войдёт")}</Badge>}
|
||||
{hint?.stranded && <Badge variant="danger">{t("Есть проекты — войти нельзя")}</Badge>}
|
||||
<span className="ml-auto text-xs text-muted-foreground">{u.lastLoginAt ? t("вход {ago}", { ago: ago(u.lastLoginAt, t) }) : t("ещё не входил")}</span>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{hint?.candidate && (
|
||||
<Button asChild size="sm" variant="default">
|
||||
<Link href={`/users/merge?from=${u.id}&to=${hint.candidate.id}`}>{t("Объединить с {login}?", { login: hint.candidate.login })}</Link>
|
||||
</Button>
|
||||
)}
|
||||
{u.id !== me.id && targets.length > 0 && (
|
||||
<form action="/users/merge" className="flex items-center gap-1.5">
|
||||
<input type="hidden" name="from" value={u.id} />
|
||||
<NativeSelect name="to" aria-label={t("Главная учётка")} className="h-8 w-auto" defaultValue={hint?.candidate?.id ?? ""}>
|
||||
<option value="" disabled>{t("Объединить с…")}</option>
|
||||
{targets.map((v) => (
|
||||
<option key={v.id} value={v.id}>{v.name ? `${v.login} · ${v.name}` : v.login}</option>
|
||||
))}
|
||||
</NativeSelect>
|
||||
<Button size="sm" variant="outline">{t("Далее")}</Button>
|
||||
</form>
|
||||
)}
|
||||
{u.id !== me.id && (isAdmin || !u.disabledAt) && (
|
||||
<form action={setSuperadminAction} className="ml-auto" data-superadmin-toggle={u.login}>
|
||||
<Hidden fields={{ userId: String(u.id), on: isAdmin ? "0" : "1", ...back }} />
|
||||
<Button size="sm" variant="outline">{isAdmin ? t("Снять суперадмина") : t("Сделать суперадмином")}</Button>
|
||||
</form>
|
||||
)}
|
||||
{u.id !== me.id && (
|
||||
<form action={setUserDisabledAction} className={isAdmin || !u.disabledAt ? undefined : "ml-auto"}>
|
||||
<Hidden fields={{ userId: String(u.id), disabled: u.disabledAt ? "0" : "1", ...back }} />
|
||||
<Button size="sm" variant={u.disabledAt ? "default" : "destructive"}>{u.disabledAt ? t("Включить") : t("Отключить")}</Button>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
})}
|
||||
</Section>
|
||||
</div>
|
||||
</Workspace>
|
||||
);
|
||||
}
|
||||
105
apps/web/app/(app)/welcome/page.tsx
Normal file
105
apps/web/app/(app)/welcome/page.tsx
Normal file
@ -0,0 +1,105 @@
|
||||
// PEP-92: the welcome page for everyone who signs in — why Peppa, how work goes, where to click.
|
||||
import Link from "next/link";
|
||||
import { ArrowRight, Check } from "lucide-react";
|
||||
import { Workspace } from "@/components/Workspace";
|
||||
import { PageHeader, Section } from "@/components/common";
|
||||
import { PugMascot } from "@/components/PugMascot";
|
||||
import { requireUser, words } from "@/lib/auth";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import { m, type Translator } from "@peppa/shared/i18n";
|
||||
import type { Words } from "@peppa/shared/wording";
|
||||
|
||||
const WHY = [
|
||||
{ title: m("Программировать не нужно"), text: m("Вы пишете, что должно получиться, — как объяснили бы коллеге. Как это сделать, решают агенты.") },
|
||||
{ title: m("Всё на виду"), text: m("Доска показывает, что в работе, что готово и какой агент чем занят.") },
|
||||
{ title: m("Последнее слово за вами"), text: m("Ничего не считается готовым, пока вы не посмотрели результат и не нажали «Принять».") },
|
||||
];
|
||||
|
||||
const flow = (w: Words, t: Translator) => [
|
||||
{ title: w.Task(), text: t("Одна понятная история: «Страница каталога: фото, цена, кнопка „Купить“». Пишите, зачем это нужно и как понять, что готово."), href: "/projects", cta: t("К проектам") },
|
||||
{ title: t("Бэклог → В работе"), text: t("Когда {task} переходит «В работе», её берёт агент: составляет план, пишет код и проверяет себя.", { task: w.task() }), href: null, cta: "" },
|
||||
{ title: t("Вопросы агентов"), text: t("Агент спрашивает только о важном: решения, деньги, доступы. Ответьте на Главной или в Telegram."), href: "/", cta: t("На Главную") },
|
||||
{ title: t("Ревью → Готово"), text: t("Придёт сообщение «готово» со ссылкой на версию для проверки. Посмотрите и нажмите «Принять» — или напишите, что поправить, агент доделает."), href: null, cta: "" },
|
||||
];
|
||||
|
||||
const glossary = (w: Words, t: Translator): Array<[string, string]> => [
|
||||
[t("Проект"), t("ваш продукт: у него своя доска, свой код и свои агенты")],
|
||||
[t("Эпик"), t("большая цель, которая объединяет несколько {tasks}", { tasks: w.task("genPl") })],
|
||||
[w.Task(), w.engineer ? t("одна задача для агента; одна стори — одно законченное изменение") : t("один понятный шаг: агент делает его от начала до конца и показывает результат")],
|
||||
[t("Агент"), t("ИИ-разработчик со своим именем; работает на вашей подписке Claude или ChatGPT")],
|
||||
[t("Ревью"), t("момент, когда агент закончил, а вы решаете: принять или вернуть")],
|
||||
];
|
||||
|
||||
export default async function Welcome() {
|
||||
await requireUser();
|
||||
const t = await getT();
|
||||
const w = await words();
|
||||
return (
|
||||
<Workspace>
|
||||
<PageHeader title={t("Добро пожаловать в FORGE")}>{t("Опишите идею словами — команда ИИ-агентов сделает продукт, а вы примете результат.")}</PageHeader>
|
||||
<div className="mb-8 flex flex-wrap items-center gap-5 rounded-xl border bg-card p-5">
|
||||
<PugMascot mood="alert" size={88} />
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="m-0 text-sm text-muted-foreground">{t("FORGE — фабрика программ для тех, кто придумывает продукты, а не пишет код. Вы ставите задачи и принимаете результат; агенты программируют, проверяют себя и отчитываются.")}</p>
|
||||
<Link href="/" className="mt-3 inline-flex items-center gap-1.5 rounded-md bg-primary px-3.5 py-2 text-sm font-medium text-primary-foreground hover:no-underline">
|
||||
{t("Начать с первых шагов")} <ArrowRight className="size-4" />
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
<Section title={t("Зачем это вам")}>
|
||||
<ul className="m-0 grid list-none gap-3 p-0 sm:grid-cols-3">
|
||||
{WHY.map((y) => (
|
||||
<li key={y.title} className="flex flex-col gap-1.5 rounded-xl border bg-card p-4">
|
||||
<span className="flex items-center gap-2 font-medium"><Check className="size-4 shrink-0 text-ok" /> {t(y.title)}</span>
|
||||
<span className="text-sm text-muted-foreground">{t(y.text)}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</Section>
|
||||
<Section title={t("Как тут работать")}>
|
||||
<ol className="m-0 flex list-none flex-col gap-2 p-0">
|
||||
{flow(w, t).map((s, i) => (
|
||||
<li key={s.title} className="flex items-start gap-3 rounded-xl border bg-card px-4 py-3">
|
||||
<span aria-hidden className="mt-0.5 grid size-7 shrink-0 place-items-center rounded-full bg-primary/15 text-sm font-semibold text-primary">{i + 1}</span>
|
||||
<div className="flex min-w-0 flex-1 flex-col gap-0.5">
|
||||
<span className="font-medium">{s.title}</span>
|
||||
<span className="text-sm text-muted-foreground">{s.text}</span>
|
||||
{s.href && <Link href={s.href} className="mt-1 text-sm">{s.cta} →</Link>}
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</Section>
|
||||
<Section title={t("Три способа говорить с фабрикой")}>
|
||||
<div className="grid gap-2 sm:grid-cols-3">
|
||||
<div className="flex flex-col gap-1 rounded-xl border bg-card px-4 py-3">
|
||||
<span className="font-medium">{t("Чат с аналитиком")}</span>
|
||||
<span className="text-sm text-muted-foreground">{t("ИИ-агент вашего проекта: спросите, что сделано и где это посмотреть, или опишите идею — он поможет сформулировать {tasks} и заведёт их.", { tasks: w.task("accPl") })}</span>
|
||||
<Link href="/chats" className="mt-1 text-sm">{t("Открыть чаты →")}</Link>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1 rounded-xl border bg-card px-4 py-3">
|
||||
<span className="font-medium">{t("Свой Telegram-бот")}</span>
|
||||
<span className="text-sm text-muted-foreground">{t("Через него приходят вопросы и статусы, и ему же можно написать или наговорить новую задачу.")}</span>
|
||||
<Link href="/settings#telegram" className="mt-1 text-sm">{t("Подключить бота →")}</Link>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1 rounded-xl border bg-card px-4 py-3">
|
||||
<span className="font-medium">{t("Ваш Claude или ChatGPT")}</span>
|
||||
<span className="text-sm text-muted-foreground">{t("Подключите FORGE к своему чату — и ведите проекты прямо из него: «создай {task}», «что ждёт моего ответа?».", { task: w.task("acc") })}</span>
|
||||
<Link href="/help" className="mt-1 text-sm">{t("Как подключить →")}</Link>
|
||||
</div>
|
||||
</div>
|
||||
</Section>
|
||||
<Section title={t("Слова, которые встретятся")}>
|
||||
<dl className="m-0 grid gap-2 sm:grid-cols-2">
|
||||
{glossary(w, t).map(([term, d]) => (
|
||||
<div key={term} className="rounded-xl border bg-card px-4 py-3">
|
||||
<dt className="font-medium">{term}</dt>
|
||||
<dd className="m-0 text-sm text-muted-foreground">{d}</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
<p className="mt-4 text-sm text-muted-foreground">{t("Что-то непонятно? Загляните в")} <Link href="/help">{t("Помощь")}</Link> {t("— там всё по шагам.")}</p>
|
||||
</Section>
|
||||
</Workspace>
|
||||
);
|
||||
}
|
||||
18
apps/web/app/api/agent/[...path]/route.ts
Normal file
18
apps/web/app/api/agent/[...path]/route.ts
Normal file
@ -0,0 +1,18 @@
|
||||
import { agentRelayMcp } from "@peppa/mcp/relay";
|
||||
import { handleAgentRelay } from "@peppa/runner";
|
||||
import { db } from "@/lib/db";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
// A blocking hook (question to the PM) is answered in ≤25 s chunks (`wait` + `rid`).
|
||||
export const maxDuration = 60;
|
||||
|
||||
/**
|
||||
* PEP-17: the agent relay — hooks, MCP and git of agents in runner containers (here or on
|
||||
* runner hosts, PEP-40). No web login: Bearer = the run's own token.
|
||||
*/
|
||||
async function handle(req: Request, { params }: { params: Promise<{ path: string[] }> }) {
|
||||
const { path } = await params;
|
||||
return handleAgentRelay(db, req, `/${path.join("/")}`, { mcp: agentRelayMcp });
|
||||
}
|
||||
export const GET = handle;
|
||||
export const POST = handle;
|
||||
42
apps/web/app/api/attachments/[id]/route.ts
Normal file
42
apps/web/app/api/attachments/[id]/route.ts
Normal file
@ -0,0 +1,42 @@
|
||||
// PEP-159: a file — only for the project's people and superadmins. Pictures and PDFs open in the
|
||||
// browser, everything else downloads; the browser never guesses a type (nosniff, sandbox).
|
||||
import { attachmentForUser, discardAttachment } from "@peppa/core";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { asWebActor, currentUser } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { getT } from "@/lib/i18n";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export async function GET(req: Request, { params }: { params: Promise<{ id: string }> }) {
|
||||
const user = await currentUser();
|
||||
const t = await getT();
|
||||
if (!user) return new Response(t("Нужен вход"), { status: 401 });
|
||||
const { id } = await params;
|
||||
const found = /^\d+$/.test(id) ? await attachmentForUser(db, user, Number(id)) : null;
|
||||
// Somebody else's file and a missing one look the same.
|
||||
if (!found) return new Response(t("Не найдено"), { status: 404 });
|
||||
const { row, path } = found;
|
||||
const inline = (row.mime.startsWith("image/") || row.mime === "application/pdf") && new URL(req.url).searchParams.get("download") !== "1";
|
||||
const name = encodeURIComponent(row.name).replace(/['()]/g, escape);
|
||||
return new Response(new Uint8Array(readFileSync(path)), {
|
||||
headers: {
|
||||
"Content-Type": row.mime,
|
||||
"Content-Length": String(row.size),
|
||||
"Cache-Control": "private, max-age=3600",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
"Content-Disposition": `${inline ? "inline" : "attachment"}; filename*=UTF-8''${name}`,
|
||||
// A PDF viewer does not run in a sandboxed response; everything else is locked down.
|
||||
...(row.mime === "application/pdf" ? {} : { "Content-Security-Policy": "default-src 'none'; sandbox" }),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/** The cross next to a chosen file: takes it back before sending. */
|
||||
export async function DELETE(_req: Request, { params }: { params: Promise<{ id: string }> }) {
|
||||
const me = await currentUser();
|
||||
if (!me) return new Response(null, { status: 401 });
|
||||
const { id } = await params;
|
||||
const ok = /^\d+$/.test(id) && (await discardAttachment(db, asWebActor(me), Number(id)));
|
||||
return new Response(null, { status: ok ? 204 : 404 });
|
||||
}
|
||||
42
apps/web/app/api/attachments/route.ts
Normal file
42
apps/web/app/api/attachments/route.ts
Normal file
@ -0,0 +1,42 @@
|
||||
// PEP-159: files for a chat message, a comment or a new story. The file is uploaded as soon as it is
|
||||
// chosen (multipart: a server action's body is capped at 1 MB, files go up to 20 MB) and gets an id
|
||||
// the form sends along; the action links it to the message. Access — the project's people.
|
||||
import { ATTACHMENT_MAX_BYTES, ATTACHMENT_MAX_FILES, PeppaError, saveAttachment } from "@peppa/core";
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
import { asWebActor, currentUser } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { getT } from "@/lib/i18n";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export async function POST(req: Request) {
|
||||
const t = await getT();
|
||||
const fail = (status: number, error: string) => Response.json({ error }, { status });
|
||||
const me = await currentUser();
|
||||
if (!me) return fail(401, t("Нужен вход"));
|
||||
const user = asWebActor(me);
|
||||
if (Number(req.headers.get("content-length") ?? 0) > ATTACHMENT_MAX_BYTES * ATTACHMENT_MAX_FILES + 512 * 1024) return fail(413, t("Файл больше 20 МБ. Приложите файл поменьше."));
|
||||
let form: FormData;
|
||||
try {
|
||||
form = await req.formData();
|
||||
} catch {
|
||||
return fail(400, t("Не получилось прочитать форму. Попробуйте ещё раз."));
|
||||
}
|
||||
const projectId = Number(form.get("projectId"));
|
||||
const files = form.getAll("files").filter((v): v is File => typeof v !== "string");
|
||||
if (!Number.isInteger(projectId) || !files.length) return fail(400, t("Выберите файл."));
|
||||
if (files.length > ATTACHMENT_MAX_FILES) return fail(400, t("Можно приложить не больше {n} файлов.", { n: ATTACHMENT_MAX_FILES }));
|
||||
const saved = [];
|
||||
const errors: string[] = [];
|
||||
for (const f of files) {
|
||||
try {
|
||||
// Oversized files are refused before their bytes are read into memory.
|
||||
if (f.size > ATTACHMENT_MAX_BYTES) throw new PeppaError(m("Файл «{name}» больше 20 МБ. Приложите файл поменьше.", { name: f.name }));
|
||||
saved.push(await saveAttachment(db, user, { projectId, name: f.name, data: new Uint8Array(await f.arrayBuffer()) }));
|
||||
} catch (e) {
|
||||
if (!(e instanceof PeppaError)) throw e;
|
||||
errors.push(t.text(e.message));
|
||||
}
|
||||
}
|
||||
return Response.json({ files: saved, errors });
|
||||
}
|
||||
15
apps/web/app/api/attention/route.ts
Normal file
15
apps/web/app/api/attention/route.ts
Normal file
@ -0,0 +1,15 @@
|
||||
import { getNotifyPrefs } from "@peppa/core";
|
||||
import { currentUser } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { navCounts } from "@/lib/queries";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** What waits for the signed-in user (tab title counter and app badge, PEP-55). */
|
||||
export async function GET() {
|
||||
const user = await currentUser();
|
||||
if (!user) return Response.json({ error: "unauthorized" }, { status: 401 });
|
||||
const c = await navCounts(user.id);
|
||||
const { sound } = await getNotifyPrefs(db, user.id);
|
||||
return Response.json({ count: c.questions + c.waitingRunners, sound }, { headers: { "Cache-Control": "no-store" } });
|
||||
}
|
||||
42
apps/web/app/api/client-errors/route.ts
Normal file
42
apps/web/app/api/client-errors/route.ts
Normal file
@ -0,0 +1,42 @@
|
||||
// PEP-91: errors from the browser (ErrorReporter) → Bugsink, source `web` of the platform project.
|
||||
// No login needed (the login page breaks too): size cap and a per-IP limit instead.
|
||||
import { reportPlatformError } from "@peppa/core";
|
||||
import { db } from "@/lib/db";
|
||||
|
||||
const MAX_BYTES = 16 * 1024;
|
||||
const PER_IP_PER_MIN = 20;
|
||||
const hits = new Map<string, { at: number; n: number }>();
|
||||
|
||||
function limited(ip: string, now = Date.now()): boolean {
|
||||
const h = hits.get(ip);
|
||||
if (!h || now - h.at >= 60_000) {
|
||||
if (hits.size > 5000) hits.clear();
|
||||
hits.set(ip, { at: now, n: 1 });
|
||||
return false;
|
||||
}
|
||||
return ++h.n > PER_IP_PER_MIN;
|
||||
}
|
||||
|
||||
const str = (v: unknown, max: number) => (typeof v === "string" ? v.slice(0, max) : undefined);
|
||||
|
||||
export async function POST(req: Request) {
|
||||
const ip = req.headers.get("cf-connecting-ip") ?? req.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ?? "local";
|
||||
if (limited(ip)) return new Response(null, { status: 429 });
|
||||
const raw = await req.text();
|
||||
if (raw.length > MAX_BYTES) return new Response(null, { status: 413 });
|
||||
let b: Record<string, unknown>;
|
||||
try {
|
||||
b = JSON.parse(raw) as Record<string, unknown>;
|
||||
} catch {
|
||||
return new Response(null, { status: 400 });
|
||||
}
|
||||
const message = str(b.message, 2000);
|
||||
if (!message) return new Response(null, { status: 400 });
|
||||
const path = str(b.url, 500);
|
||||
const sent = await reportPlatformError(
|
||||
db,
|
||||
{ name: str(b.type, 100) || "Error", message, stack: str(b.stack, 8000) },
|
||||
{ service: "browser", kind: "web", platform: "javascript", where: path?.split("?")[0], request: { url: path, method: "GET", userAgent: req.headers.get("user-agent") ?? undefined } },
|
||||
);
|
||||
return Response.json({ sent });
|
||||
}
|
||||
25
apps/web/app/api/connections/journal/route.ts
Normal file
25
apps/web/app/api/connections/journal/route.ts
Normal file
@ -0,0 +1,25 @@
|
||||
// PEP-254: the owner downloads their whole Access Hub journal with hashes (JSONL or CSV) to
|
||||
// check it on their own. Only the signed-in user's own rows.
|
||||
import { exportConnectionJournal } from "@peppa/core";
|
||||
import { currentUser } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { getT } from "@/lib/i18n";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export async function GET(req: Request) {
|
||||
const t = await getT();
|
||||
const me = await currentUser();
|
||||
if (!me) return Response.json({ error: t("Нужен вход") }, { status: 401 });
|
||||
const format = new URL(req.url).searchParams.get("format") === "csv" ? "csv" : "jsonl";
|
||||
const body = await exportConnectionJournal(db, me.id, format);
|
||||
const day = new Date().toISOString().slice(0, 10);
|
||||
return new Response(body, {
|
||||
headers: {
|
||||
"content-type": format === "csv" ? "text/csv; charset=utf-8" : "application/x-ndjson; charset=utf-8",
|
||||
"content-disposition": `attachment; filename="connections-journal-${day}.${format}"`,
|
||||
"cache-control": "no-store",
|
||||
"x-content-type-options": "nosniff",
|
||||
},
|
||||
});
|
||||
}
|
||||
20
apps/web/app/api/feedback/[id]/shots/[n]/route.ts
Normal file
20
apps/web/app/api/feedback/[id]/shots/[n]/route.ts
Normal file
@ -0,0 +1,20 @@
|
||||
// PEP-143: a screenshot of a report — only its author and the superadmins see it.
|
||||
import { feedbackScreenshot } from "@peppa/core";
|
||||
import { currentUser } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { getT } from "@/lib/i18n";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export async function GET(_req: Request, { params }: { params: Promise<{ id: string; n: string }> }) {
|
||||
const user = await currentUser();
|
||||
const t = await getT();
|
||||
if (!user) return new Response(t("Нужен вход"), { status: 401 });
|
||||
const { id, n } = await params;
|
||||
const shot = /^\d+$/.test(id) && /^\d+$/.test(n) ? await feedbackScreenshot(db, user, Number(id), Number(n)) : null;
|
||||
// Somebody else's report and a missing one look the same.
|
||||
if (!shot) return new Response(t("Не найдено"), { status: 404 });
|
||||
return new Response(new Uint8Array(shot.data), {
|
||||
headers: { "Content-Type": shot.mime, "Cache-Control": "private, max-age=3600", "X-Content-Type-Options": "nosniff", "Content-Disposition": "inline", "Content-Security-Policy": "default-src 'none'; sandbox" },
|
||||
});
|
||||
}
|
||||
47
apps/web/app/api/feedback/route.ts
Normal file
47
apps/web/app/api/feedback/route.ts
Normal file
@ -0,0 +1,47 @@
|
||||
// PEP-143: «Сообщить о проблеме» — the form posts text, screenshots and what the page knows
|
||||
// (multipart: a server action's body is capped at 1 MB, screenshots are bigger).
|
||||
import { FEEDBACK_MAX_BYTES, FEEDBACK_MAX_SHOTS, PeppaError, submitFeedback } from "@peppa/core";
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
import { asWebActor, currentUser, uiMode } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { getLocale, getT } from "@/lib/i18n";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const MAX_BODY = FEEDBACK_MAX_SHOTS * FEEDBACK_MAX_BYTES + 512 * 1024;
|
||||
|
||||
export async function POST(req: Request) {
|
||||
const t = await getT();
|
||||
const fail = (status: number, error: string) => Response.json({ error }, { status });
|
||||
const me = await currentUser();
|
||||
if (!me) return fail(401, t("Нужен вход"));
|
||||
const user = asWebActor(me);
|
||||
if (Number(req.headers.get("content-length") ?? 0) > MAX_BODY) return fail(413, t("Скриншоты слишком большие. Приложите файлы поменьше."));
|
||||
let form: FormData;
|
||||
try {
|
||||
form = await req.formData();
|
||||
} catch {
|
||||
return fail(400, t("Не получилось прочитать форму. Попробуйте ещё раз."));
|
||||
}
|
||||
const shots = form.getAll("shots").filter((v): v is File => typeof v !== "string");
|
||||
let context: Record<string, unknown> = {};
|
||||
try {
|
||||
context = JSON.parse(String(form.get("context") ?? "{}")) as Record<string, unknown>;
|
||||
} catch {}
|
||||
try {
|
||||
// Oversized files are refused before their bytes are read into memory.
|
||||
if (shots.some((s) => s.size > FEEDBACK_MAX_BYTES)) throw new PeppaError(m("Скриншот больше 5 МБ. Приложите файл поменьше."));
|
||||
const files = await Promise.all(shots.slice(0, FEEDBACK_MAX_SHOTS + 1).map(async (s) => new Uint8Array(await s.arrayBuffer())));
|
||||
const f = await submitFeedback(db, user, {
|
||||
text: String(form.get("text") ?? ""),
|
||||
via: "web",
|
||||
files,
|
||||
// The view and the language are the server's knowledge, not the page's claim.
|
||||
context: { ...context, mode: await uiMode(), locale: await getLocale(), userAgent: req.headers.get("user-agent") ?? undefined },
|
||||
});
|
||||
return Response.json({ ok: true, id: f.id });
|
||||
} catch (e) {
|
||||
if (e instanceof PeppaError) return fail(400, t.text(e.message));
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
@ -1,4 +1,5 @@
|
||||
import { healthReport } from "@peppa/core";
|
||||
import { bootId } from "@/lib/boot";
|
||||
import { db } from "@/lib/db";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
@ -9,5 +10,6 @@ export async function GET() {
|
||||
version: process.env.NEXT_PUBLIC_PEPPA_VERSION,
|
||||
commit: process.env.NEXT_PUBLIC_PEPPA_COMMIT || null,
|
||||
});
|
||||
return Response.json(r, { status: r.ok ? 200 : 503, headers: { "Cache-Control": "no-store" } });
|
||||
// PEP-114: `boot` changes when the web process restarts — open pages compare it with their own.
|
||||
return Response.json({ ...r, boot: bootId() }, { status: r.ok ? 200 : 503, headers: { "Cache-Control": "no-store" } });
|
||||
}
|
||||
|
||||
15
apps/web/app/api/hooks/bugsink/[secret]/route.ts
Normal file
15
apps/web/app/api/hooks/bugsink/[secret]/route.ts
Normal file
@ -0,0 +1,15 @@
|
||||
import { after } from "next/server";
|
||||
import { bugsinkFromEnv } from "@peppa/bugsink";
|
||||
import { processIncidents, receiveBugsinkWebhook } from "@peppa/runner";
|
||||
import { db } from "@/lib/db";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** Bugsink custom-webhook alerts (PEP-58). Unknown secret → 404; the policy runs after the reply. */
|
||||
export async function POST(req: Request, { params }: { params: Promise<{ secret: string }> }) {
|
||||
const { secret } = await params;
|
||||
const body = await req.json().catch(() => null);
|
||||
const r = await receiveBugsinkWebhook(db, secret, body, bugsinkFromEnv());
|
||||
if (r.status === 200) after(() => processIncidents(db, { log: (m) => console.error(`[incidents] ${m}`) }).then(() => undefined));
|
||||
return Response.json(r.body, { status: r.status });
|
||||
}
|
||||
21
apps/web/app/api/hooks/gitea/route.ts
Normal file
21
apps/web/app/api/hooks/gitea/route.ts
Normal file
@ -0,0 +1,21 @@
|
||||
import { enterActor } from "@peppa/core";
|
||||
import { handleGiteaHook } from "@peppa/runner";
|
||||
import { db } from "@/lib/db";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/**
|
||||
* Gitea webhooks and CI step reports of project repos (PEP-57). No login: each request is
|
||||
* signed (X-Gitea-Signature, HMAC-SHA256 of the body) with the project's secret.
|
||||
*/
|
||||
export async function POST(req: Request) {
|
||||
// PEP-48: CI results and Gitea events act as Peppa itself.
|
||||
enterActor({ kind: "system", channel: "gitea" });
|
||||
const body = await req.text();
|
||||
const r = await handleGiteaHook(db, {
|
||||
event: req.headers.get("x-peppa-event") ?? req.headers.get("x-gitea-event") ?? "",
|
||||
signature: req.headers.get("x-gitea-signature"),
|
||||
body,
|
||||
});
|
||||
return Response.json(r.body, { status: r.status });
|
||||
}
|
||||
28
apps/web/app/api/live/route.ts
Normal file
28
apps/web/app/api/live/route.ts
Normal file
@ -0,0 +1,28 @@
|
||||
// Live updates (PEP-37): SSE of `change` (a watched scope changed), `step` (an agent's tool call,
|
||||
// PEP-33) and `data` events — since PEP-225 the fallback of the tab's WebSocket /api/ws. ?scope=home | runners | project:<id> | task:<id> | steps:<sessionId>, comma-separated.
|
||||
import { LiveError, liveSse, parseScopes } from "@peppa/runner";
|
||||
import { currentUser } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const fail = async (status: number, error: string) => Response.json({ error: (await getT()).text(error) }, { status, headers: { "Cache-Control": "no-store" } });
|
||||
|
||||
export async function GET(req: Request) {
|
||||
const user = await currentUser();
|
||||
try {
|
||||
const q = new URL(req.url).searchParams;
|
||||
const scopes = parseScopes(q.get("scope"));
|
||||
// PEP-224: only `features` (state of platform features, no user data) is open without a sign-in.
|
||||
if (!user && scopes.some((s) => s !== "features")) return fail(401, m("Нужен вход"));
|
||||
// PEP-225: `since.<scope>=<version>` — what the tab saw before a drop (fallback of the WebSocket).
|
||||
const since = Object.fromEntries([...q].filter(([k]) => k.startsWith("since.")).map(([k, v]) => [k.slice(6), v]));
|
||||
return await liveSse(db, user, scopes, req.signal, { since });
|
||||
} catch (e) {
|
||||
if (e instanceof LiveError) return fail(e.status, e.message);
|
||||
console.error("live:", e);
|
||||
return fail(500, m("Ошибка потока"));
|
||||
}
|
||||
}
|
||||
12
apps/web/app/api/observe/hb/[token]/route.ts
Normal file
12
apps/web/app/api/observe/hb/[token]/route.ts
Normal file
@ -0,0 +1,12 @@
|
||||
import { pingHeartbeat } from "@peppa/core";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** PEP-202: a heartbeat monitor's ping — the watched service calls it (GET or POST, no login). */
|
||||
async function ping(_req: Request, { params }: { params: Promise<{ token: string }> }) {
|
||||
const { token } = await params;
|
||||
const ok = pingHeartbeat(token);
|
||||
return Response.json({ ok }, { status: ok ? 200 : 404, headers: { "Cache-Control": "no-store" } });
|
||||
}
|
||||
export const GET = ping;
|
||||
export const POST = ping;
|
||||
15
apps/web/app/api/palette/route.ts
Normal file
15
apps/web/app/api/palette/route.ts
Normal file
@ -0,0 +1,15 @@
|
||||
import { paletteItems } from "@peppa/core";
|
||||
import { currentUser, uiMode } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** Command palette data (PEP-52): projects, stories, runners and open questions of the user's projects. */
|
||||
export async function GET() {
|
||||
const user = await currentUser();
|
||||
if (!user) return Response.json({ error: "unauthorized" }, { status: 401 });
|
||||
// PEP-123: terminals of agents are a tool of «Инженер»; «Продакт» searches projects, tasks and questions.
|
||||
const all = await paletteItems(db, user.id);
|
||||
const items = (await uiMode()) === "engineer" ? all : all.filter((i) => i.kind !== "runner" && i.href !== "/runners");
|
||||
return Response.json({ items }, { headers: { "Cache-Control": "private, no-store" } });
|
||||
}
|
||||
20
apps/web/app/api/releases/[id]/shots/[n]/route.ts
Normal file
20
apps/web/app/api/releases/[id]/shots/[n]/route.ts
Normal file
@ -0,0 +1,20 @@
|
||||
// Screenshots of a preview stand (PEP-44), taken by the project's CI step: only the
|
||||
// project's owner and members see them.
|
||||
import { projectForUser } from "@peppa/core";
|
||||
import { releaseScreenshot } from "@peppa/runner";
|
||||
import { currentUser } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { getT } from "@/lib/i18n";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export async function GET(_req: Request, { params }: { params: Promise<{ id: string; n: string }> }) {
|
||||
const user = await currentUser();
|
||||
const t = await getT();
|
||||
if (!user) return new Response(t("Нужен вход"), { status: 401 });
|
||||
const { id, n } = await params;
|
||||
const shot = await releaseScreenshot(db, Number(id), Number(n));
|
||||
const allowed = shot && (await projectForUser(db, user.id, shot.projectId).then(() => true, () => false));
|
||||
if (!shot || !allowed) return new Response(t("Не найдено"), { status: 404 });
|
||||
return new Response(new Uint8Array(shot.png), { headers: { "Content-Type": "image/png", "Cache-Control": "private, max-age=3600" } });
|
||||
}
|
||||
64
apps/web/app/api/runners/[id]/terminal/route.ts
Normal file
64
apps/web/app/api/runners/[id]/terminal/route.ts
Normal file
@ -0,0 +1,64 @@
|
||||
// Live runner terminal (PEP-9): GET — SSE stream of the pane, POST — keyboard input / paste.
|
||||
import { TerminalError, terminalInput, terminalSse } from "@peppa/runner";
|
||||
import { currentUser } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
type Ctx = { params: Promise<{ id: string }> };
|
||||
|
||||
const fail = async (status: number, error: string) => Response.json({ error: (await getT()).text(error) }, { status, headers: { "Cache-Control": "no-store" } });
|
||||
|
||||
function asResponse(e: unknown): Promise<Response> {
|
||||
if (e instanceof TerminalError) return fail(e.status, e.message);
|
||||
console.error("terminal:", e);
|
||||
return fail(500, m("Ошибка терминала"));
|
||||
}
|
||||
|
||||
export async function GET(req: Request, { params }: Ctx) {
|
||||
const user = await currentUser();
|
||||
if (!user) return fail(401, m("Нужен вход"));
|
||||
try {
|
||||
return await terminalSse(db, user, Number((await params).id), req.signal);
|
||||
} catch (e) {
|
||||
return asResponse(e);
|
||||
}
|
||||
}
|
||||
|
||||
/** Same-origin only: the session cookie is lax, and JSON bodies need a CORS preflight anyway. */
|
||||
function sameOrigin(req: Request): boolean {
|
||||
const origin = req.headers.get("origin");
|
||||
if (!origin) return true;
|
||||
const host = req.headers.get("x-forwarded-host") ?? req.headers.get("host");
|
||||
try {
|
||||
return new URL(origin).host === host;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(req: Request, { params }: Ctx) {
|
||||
const user = await currentUser();
|
||||
if (!user) return fail(401, m("Нужен вход"));
|
||||
if (!sameOrigin(req)) return fail(403, m("Чужой источник"));
|
||||
if (!req.headers.get("content-type")?.startsWith("application/json")) return fail(415, m("Нужен JSON"));
|
||||
// Paste limit is 64 KB; refuse oversized bodies before parsing.
|
||||
if (Number(req.headers.get("content-length") ?? 0) > 300_000) return fail(413, m("Слишком длинный ввод"));
|
||||
let body: { keys?: unknown; paste?: unknown };
|
||||
try {
|
||||
body = await req.json();
|
||||
} catch {
|
||||
return fail(400, m("Неверный JSON"));
|
||||
}
|
||||
try {
|
||||
await terminalInput(db, user, Number((await params).id), {
|
||||
keys: typeof body.keys === "string" ? body.keys : undefined,
|
||||
paste: typeof body.paste === "string" ? body.paste : undefined,
|
||||
});
|
||||
return new Response(null, { status: 204 });
|
||||
} catch (e) {
|
||||
return asResponse(e);
|
||||
}
|
||||
}
|
||||
54
apps/web/app/api/transcribe/route.ts
Normal file
54
apps/web/app/api/transcribe/route.ts
Normal file
@ -0,0 +1,54 @@
|
||||
// PEP-108: dictation in the web — the browser records (MediaRecorder: webm/opus, Safari mp4) and
|
||||
// posts the audio here; Peppa forwards it to the same speech-to-text service as the Telegram bot
|
||||
// (PEPPA_TRANSCRIBE_URL, core/transcribe.ts) and returns the text. The page puts it into the
|
||||
// field, the user edits and sends. The recording is recognised in the user's interface language
|
||||
// (PEP-131). Logged-in users only; size cap and a per-user rate limit.
|
||||
import { transcribe, transcribeConfig, transcribeLanguage, TranscribeError } from "@peppa/core";
|
||||
import { currentUser } from "@/lib/auth";
|
||||
import { getLocale, getT } from "@/lib/i18n";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** ~10 minutes of opus; the service itself takes up to 25 MB. */
|
||||
const MAX_BYTES = 10 * 1024 * 1024;
|
||||
const PER_USER_PER_5MIN = 30;
|
||||
const g = globalThis as { __peppaTranscribeHits?: Map<number, { at: number; n: number }> };
|
||||
const hits = (g.__peppaTranscribeHits ??= new Map());
|
||||
|
||||
function limited(userId: number, now = Date.now()): boolean {
|
||||
const h = hits.get(userId);
|
||||
if (!h || now - h.at >= 5 * 60_000) {
|
||||
hits.set(userId, { at: now, n: 1 });
|
||||
return false;
|
||||
}
|
||||
return ++h.n > PER_USER_PER_5MIN;
|
||||
}
|
||||
|
||||
const json = (status: number, body: { text?: string; error?: string }) => Response.json(body, { status, headers: { "Cache-Control": "private, no-store" } });
|
||||
|
||||
export async function POST(req: Request) {
|
||||
const user = await currentUser();
|
||||
const t = await getT();
|
||||
if (!user) return json(401, { error: t("Нужно войти") });
|
||||
const cfg = transcribeConfig();
|
||||
if (!cfg) return json(503, { error: t("Распознавание речи не настроено — напишите текстом") });
|
||||
if (Number(req.headers.get("content-length") ?? 0) > MAX_BYTES) return json(413, { error: t("Слишком длинная запись — запишите короче") });
|
||||
if (limited(user.id)) return json(429, { error: t("Слишком много записей подряд — подождите пару минут") });
|
||||
let file: FormDataEntryValue | null;
|
||||
try {
|
||||
file = (await req.formData()).get("file");
|
||||
} catch {
|
||||
return json(400, { error: t("Запись не пришла") });
|
||||
}
|
||||
if (!(file instanceof Blob) || !file.size) return json(400, { error: t("Запись пустая") });
|
||||
if (file.size > MAX_BYTES) return json(413, { error: t("Слишком длинная запись — запишите короче") });
|
||||
const type = file.type || "audio/webm";
|
||||
const ext = type.includes("mp4") ? "m4a" : type.includes("ogg") ? "ogg" : type.includes("wav") ? "wav" : "webm";
|
||||
try {
|
||||
const text = await transcribe(cfg, Buffer.from(await file.arrayBuffer()), `dictation.${ext}`, type, transcribeLanguage(cfg, await getLocale()));
|
||||
return json(200, { text });
|
||||
} catch (e) {
|
||||
if (e instanceof TranscribeError) return json(502, { error: e.message });
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
128
apps/web/app/app.css
Normal file
128
apps/web/app/app.css
Normal file
@ -0,0 +1,128 @@
|
||||
@import "tailwindcss";
|
||||
|
||||
/* Theme tokens (shadcn/ui naming): light in :root, dark — the default — in .dark (PEP-38). */
|
||||
@custom-variant dark (&:where(.dark, .dark *));
|
||||
|
||||
:root {
|
||||
--radius: 0.625rem;
|
||||
--background: oklch(0.985 0.002 265);
|
||||
--foreground: oklch(0.21 0.02 265);
|
||||
--card: oklch(1 0 0);
|
||||
--card-foreground: oklch(0.21 0.02 265);
|
||||
--popover: oklch(1 0 0);
|
||||
--popover-foreground: oklch(0.21 0.02 265);
|
||||
--primary: oklch(0.55 0.2 258);
|
||||
--primary-foreground: oklch(0.99 0 0);
|
||||
--secondary: oklch(0.955 0.005 265);
|
||||
--secondary-foreground: oklch(0.25 0.02 265);
|
||||
--muted: oklch(0.955 0.005 265);
|
||||
--muted-foreground: oklch(0.5 0.02 265);
|
||||
--accent: oklch(0.94 0.008 265);
|
||||
--accent-foreground: oklch(0.21 0.02 265);
|
||||
--destructive: oklch(0.58 0.22 27);
|
||||
--border: oklch(0.9 0.006 265);
|
||||
--input: oklch(0.88 0.008 265);
|
||||
--ring: oklch(0.55 0.2 258);
|
||||
--sidebar: oklch(0.97 0.004 265);
|
||||
--ok: oklch(0.55 0.15 150);
|
||||
--warn: oklch(0.62 0.15 65);
|
||||
--info: oklch(0.55 0.15 245);
|
||||
--danger: var(--destructive);
|
||||
color-scheme: light;
|
||||
}
|
||||
|
||||
.dark {
|
||||
--background: oklch(0.16 0.012 265);
|
||||
--foreground: oklch(0.95 0.006 265);
|
||||
--card: oklch(0.195 0.014 265);
|
||||
--card-foreground: oklch(0.95 0.006 265);
|
||||
--popover: oklch(0.2 0.014 265);
|
||||
--popover-foreground: oklch(0.95 0.006 265);
|
||||
--primary: oklch(0.7 0.16 252);
|
||||
--primary-foreground: oklch(0.17 0.03 255);
|
||||
--secondary: oklch(0.25 0.014 265);
|
||||
--secondary-foreground: oklch(0.93 0.006 265);
|
||||
--muted: oklch(0.235 0.014 265);
|
||||
--muted-foreground: oklch(0.69 0.018 265);
|
||||
--accent: oklch(0.26 0.016 265);
|
||||
--accent-foreground: oklch(0.96 0.006 265);
|
||||
--destructive: oklch(0.66 0.2 25);
|
||||
--border: oklch(1 0 0 / 9%);
|
||||
--input: oklch(1 0 0 / 13%);
|
||||
--ring: oklch(0.7 0.16 252);
|
||||
--sidebar: oklch(0.135 0.011 265);
|
||||
--ok: oklch(0.76 0.16 152);
|
||||
--warn: oklch(0.8 0.14 75);
|
||||
--info: oklch(0.74 0.12 240);
|
||||
color-scheme: dark;
|
||||
}
|
||||
|
||||
@theme inline {
|
||||
--font-sans: var(--font-geist-sans), ui-sans-serif, system-ui, sans-serif;
|
||||
--font-mono: var(--font-geist-mono), ui-monospace, "SF Mono", Menlo, monospace;
|
||||
--color-background: var(--background);
|
||||
--color-foreground: var(--foreground);
|
||||
--color-card: var(--card);
|
||||
--color-card-foreground: var(--card-foreground);
|
||||
--color-popover: var(--popover);
|
||||
--color-popover-foreground: var(--popover-foreground);
|
||||
--color-primary: var(--primary);
|
||||
--color-primary-foreground: var(--primary-foreground);
|
||||
--color-secondary: var(--secondary);
|
||||
--color-secondary-foreground: var(--secondary-foreground);
|
||||
--color-muted: var(--muted);
|
||||
--color-muted-foreground: var(--muted-foreground);
|
||||
--color-accent: var(--accent);
|
||||
--color-accent-foreground: var(--accent-foreground);
|
||||
--color-destructive: var(--destructive);
|
||||
--color-border: var(--border);
|
||||
--color-input: var(--input);
|
||||
--color-ring: var(--ring);
|
||||
--color-sidebar: var(--sidebar);
|
||||
--color-ok: var(--ok);
|
||||
--color-warn: var(--warn);
|
||||
--color-info: var(--info);
|
||||
--radius-sm: calc(var(--radius) - 4px);
|
||||
--radius-md: calc(var(--radius) - 2px);
|
||||
--radius-lg: var(--radius);
|
||||
--radius-xl: calc(var(--radius) + 4px);
|
||||
}
|
||||
|
||||
@layer base {
|
||||
* {
|
||||
@apply border-border outline-ring/50;
|
||||
}
|
||||
body {
|
||||
@apply bg-background text-foreground font-sans antialiased;
|
||||
font-size: 15px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
::selection {
|
||||
@apply bg-primary/30;
|
||||
}
|
||||
}
|
||||
|
||||
/* PEP-70: pug mascot — breathing while asleep, a curious head tilt and a blinking cursor when agents ask. */
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
.pug-sleep .pug-body { animation: pug-breathe 3.2s ease-in-out infinite; }
|
||||
.pug-sleep .pug-zzz { animation: pug-zzz 3.2s ease-in-out infinite; }
|
||||
.pug-alert .pug-head { animation: pug-tilt 2.4s ease-in-out infinite; }
|
||||
.pug-alert .pug-cursor { animation: pug-blink 1s steps(1) infinite; }
|
||||
}
|
||||
@keyframes pug-breathe { 0%, 100% { transform: scale(1); } 50% { transform: scale(1.02, 0.985); } }
|
||||
@keyframes pug-zzz { 0%, 100% { opacity: 0.25; transform: translateY(2px); } 50% { opacity: 0.6; transform: translateY(-2px); } }
|
||||
@keyframes pug-tilt { 0%, 60%, 100% { transform: rotate(0deg); } 70% { transform: rotate(-7deg); } 85% { transform: rotate(4deg); } }
|
||||
@keyframes pug-blink { 0%, 100% { opacity: 1; } 50% { opacity: 0; } }
|
||||
|
||||
/* PEP-137: the live site runs `next dev` before launch; its «N Issue» pill and error overlay are
|
||||
developer tools — a product person must never see them. Errors go to Bugsink (ErrorReporter). */
|
||||
nextjs-portal {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
/* PEP-179: a team card the «Погоня за задачей» bench pointed at. */
|
||||
[data-highlight] {
|
||||
outline: 2px solid var(--ring);
|
||||
outline-offset: 4px;
|
||||
transition: outline-color 0.3s;
|
||||
}
|
||||
@ -1,34 +0,0 @@
|
||||
import { exchangeOAuthCode, getUserByLogin, GiteaClient, isLoginAllowed, isUserAllowed, upsertUserFromGitea } from "@peppa/core";
|
||||
import { loadEnv } from "@peppa/shared";
|
||||
import { cookies } from "next/headers";
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
import { NEXT_COOKIE, publicOrigin, safeNext, sessionCookie, STATE_COOKIE } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
const env = loadEnv();
|
||||
const origin = await publicOrigin();
|
||||
const fail = (msg: string) => NextResponse.redirect(`${origin}/login?error=${encodeURIComponent(msg)}`);
|
||||
const code = req.nextUrl.searchParams.get("code");
|
||||
const state = req.nextUrl.searchParams.get("state");
|
||||
const expected = (await cookies()).get(STATE_COOKIE)?.value;
|
||||
if (!code || !state || !expected || state !== expected) return fail("Вход не подтверждён (state не совпал) — попробуйте ещё раз");
|
||||
if (!env.GITEA_OAUTH_CLIENT_ID || !env.GITEA_OAUTH_CLIENT_SECRET) return fail("OAuth не настроен");
|
||||
try {
|
||||
const tokens = await exchangeOAuthCode(env.GITEA_URL, env.GITEA_OAUTH_CLIENT_ID, env.GITEA_OAUTH_CLIENT_SECRET, code, `${origin}/auth/callback`);
|
||||
const me = await new GiteaClient(env.GITEA_URL, tokens.access_token).me();
|
||||
const existing = await getUserByLogin(db, me.login);
|
||||
if (!(await isLoginAllowed(db, me.login)) && !(existing && (await isUserAllowed(db, existing)))) {
|
||||
return fail("Нет доступа к Пеппе — попросите администратора");
|
||||
}
|
||||
const user = await upsertUserFromGitea(db, me, tokens);
|
||||
const res = NextResponse.redirect(`${origin}${safeNext((await cookies()).get(NEXT_COOKIE)?.value)}`);
|
||||
res.cookies.delete({ name: NEXT_COOKIE, path: "/auth" });
|
||||
const c = sessionCookie(user.id);
|
||||
res.cookies.set(c.name, c.value, c.options);
|
||||
res.cookies.delete({ name: STATE_COOKIE, path: "/auth" });
|
||||
return res;
|
||||
} catch (e) {
|
||||
return fail(`Не удалось войти: ${(e as Error).message}`);
|
||||
}
|
||||
}
|
||||
38
apps/web/app/auth/egov/complete/route.ts
Normal file
38
apps/web/app/auth/egov/complete/route.ts
Normal file
@ -0,0 +1,38 @@
|
||||
import { completeEgovFlow, isUserAllowed, logEgovEvent, PeppaError } from "@peppa/core";
|
||||
import { cookies } from "next/headers";
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
import { EGOV_COOKIE, egovCookieOptions, safeNext, sessionCookie } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { adoptLocale, localeCookieOptions } from "@/lib/i18n";
|
||||
import { LOCALE_COOKIE, m } from "@peppa/shared/i18n";
|
||||
|
||||
/** Finishes a signed eGov flow: logs in by the IIN (PEP-71: registers an unknown one), or links it to the current account. */
|
||||
export async function POST(req: NextRequest) {
|
||||
const { next } = (await req.json().catch(() => ({}))) as { next?: string };
|
||||
const handle = (await cookies()).get(EGOV_COOKIE)?.value ?? "";
|
||||
const done = (body: object, status = 200) => {
|
||||
const res = NextResponse.json(body, { status });
|
||||
res.cookies.set(EGOV_COOKIE, "", egovCookieOptions(0));
|
||||
return res;
|
||||
};
|
||||
try {
|
||||
const r = await completeEgovFlow(db, handle);
|
||||
// The handle lives only in the starter's httpOnly cookie, so a link flow is finished by the
|
||||
// browser (and account) that started it.
|
||||
if (r.purpose === "link") return done({ redirect: "/settings?egov=linked" });
|
||||
if (!(await isUserAllowed(db, r.user))) {
|
||||
await logEgovEvent(db, { ok: false, step: "complete", error: null, code: "not_allowed", purpose: "login", handle, userId: r.user.id });
|
||||
return done({ error: m("Учётка отключена — обратитесь к администратору") }, 403);
|
||||
}
|
||||
await logEgovEvent(db, { ok: true, step: "complete", purpose: "login", handle, userId: r.user.id });
|
||||
const res = done({ redirect: safeNext(next) });
|
||||
const c = sessionCookie(r.user.id);
|
||||
res.cookies.set(c.name, c.value, c.options);
|
||||
// PEP-98: the language picked on the login page sticks to the account (or the account's wins).
|
||||
const lang = await adoptLocale(r.user.id, req.cookies.get(LOCALE_COOKIE)?.value);
|
||||
if (lang) res.cookies.set(LOCALE_COOKIE, lang, localeCookieOptions);
|
||||
return res;
|
||||
} catch (e) {
|
||||
return done({ error: e instanceof PeppaError ? e.message : m("Не удалось войти через eGov") }, 400);
|
||||
}
|
||||
}
|
||||
21
apps/web/app/auth/egov/start/route.ts
Normal file
21
apps/web/app/auth/egov/start/route.ts
Normal file
@ -0,0 +1,21 @@
|
||||
import { PeppaError, startEgovFlow, type EgovPurpose } from "@peppa/core";
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
import QRCode from "qrcode";
|
||||
import { currentUser, EGOV_COOKIE, egovCookieOptions } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
|
||||
/** Starts an eGov QR flow (PEP-65): `login` from the login page, `link` from Settings (needs a session). */
|
||||
export async function POST(req: NextRequest) {
|
||||
const { purpose } = (await req.json().catch(() => ({}))) as { purpose?: EgovPurpose };
|
||||
try {
|
||||
const user = purpose === "link" ? await currentUser() : null;
|
||||
const flow = await startEgovFlow(db, purpose === "link" ? "link" : "login", user?.id ?? null);
|
||||
const qr = await QRCode.toDataURL(flow.qrContent, { errorCorrectionLevel: "M", margin: 2, width: 280 });
|
||||
const res = NextResponse.json({ qr, deeplink: flow.deeplink, expiresAt: flow.expiresAt });
|
||||
res.cookies.set(EGOV_COOKIE, flow.handle, egovCookieOptions(Math.ceil((flow.expiresAt - Date.now()) / 1000)));
|
||||
return res;
|
||||
} catch (e) {
|
||||
return NextResponse.json({ error: e instanceof PeppaError ? e.message : m("Не удалось создать QR eGov") }, { status: 424 } /* not 5xx: Cloudflare replaces those with its own page (PEP-194) */);
|
||||
}
|
||||
}
|
||||
15
apps/web/app/auth/egov/status/route.ts
Normal file
15
apps/web/app/auth/egov/status/route.ts
Normal file
@ -0,0 +1,15 @@
|
||||
import { egovFlowStatus, PeppaError } from "@peppa/core";
|
||||
import { cookies } from "next/headers";
|
||||
import { NextResponse } from "next/server";
|
||||
import { EGOV_COOKIE } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
|
||||
/** Status of this browser's eGov QR flow: pending | scanned | completed | expired | rejected. */
|
||||
export async function GET() {
|
||||
try {
|
||||
return NextResponse.json({ status: await egovFlowStatus(db, (await cookies()).get(EGOV_COOKIE)?.value ?? "") });
|
||||
} catch (e) {
|
||||
return NextResponse.json({ error: e instanceof PeppaError ? e.message : m("eGov недоступен") }, { status: 424 } /* not 5xx: Cloudflare replaces those with its own page (PEP-194) */);
|
||||
}
|
||||
}
|
||||
39
apps/web/app/auth/google/callback/route.ts
Normal file
39
apps/web/app/auth/google/callback/route.ts
Normal file
@ -0,0 +1,39 @@
|
||||
import { completeGoogleFlow, googleFlowPurpose, isUserAllowed, PeppaError } from "@peppa/core";
|
||||
import { cookies } from "next/headers";
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
import { GOOGLE_COOKIE, googleCookieOptions, publicOrigin, safeNext, sessionCookie } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { adoptLocale, localeCookieOptions } from "@/lib/i18n";
|
||||
import { LOCALE_COOKIE, m } from "@peppa/shared/i18n";
|
||||
|
||||
/** Google redirects here (PEP-90): checks state against the browser's cookie, then logs in, registers or links. */
|
||||
export async function GET(req: NextRequest) {
|
||||
const origin = await publicOrigin();
|
||||
const jar = await cookies();
|
||||
const cookieState = jar.get(GOOGLE_COOKIE)?.value ?? "";
|
||||
const next = safeNext(jar.get(`${GOOGLE_COOKIE}_next`)?.value);
|
||||
const q = req.nextUrl.searchParams;
|
||||
const done = (path: string, error?: string) => {
|
||||
const res = NextResponse.redirect(`${origin}${path}${error ? `${path.includes("?") ? "&" : "?"}error=${encodeURIComponent(error)}` : ""}`, 303);
|
||||
res.cookies.set(GOOGLE_COOKIE, "", googleCookieOptions(0));
|
||||
res.cookies.set(`${GOOGLE_COOKIE}_next`, "", googleCookieOptions(0));
|
||||
return res;
|
||||
};
|
||||
// A link starts in Settings and its errors go back there: /login sends a signed-in user home and the error is lost (PEP-195).
|
||||
const failPath = (await googleFlowPurpose(db, q.get("state") ?? "")) === "link" ? "/settings" : "/login";
|
||||
if (q.get("error")) return done(failPath, q.get("error") === "access_denied" ? m("Вход через Google отменён") : m("Google отказал во входе"));
|
||||
try {
|
||||
const r = await completeGoogleFlow(db, { state: q.get("state") ?? "", code: q.get("code") ?? "", cookieState });
|
||||
if (r.purpose === "link") return done("/settings?google=linked");
|
||||
if (!(await isUserAllowed(db, r.user))) return done("/login", m("Учётка отключена — обратитесь к администратору"));
|
||||
const res = done(next);
|
||||
const c = sessionCookie(r.user.id);
|
||||
res.cookies.set(c.name, c.value, c.options);
|
||||
// PEP-98: the language picked on the login page sticks to the account (or the account's wins).
|
||||
const lang = await adoptLocale(r.user.id, req.cookies.get(LOCALE_COOKIE)?.value);
|
||||
if (lang) res.cookies.set(LOCALE_COOKIE, lang, localeCookieOptions);
|
||||
return res;
|
||||
} catch (e) {
|
||||
return done(failPath, e instanceof PeppaError ? e.message : m("Не удалось войти через Google"));
|
||||
}
|
||||
}
|
||||
26
apps/web/app/auth/google/start/route.ts
Normal file
26
apps/web/app/auth/google/start/route.ts
Normal file
@ -0,0 +1,26 @@
|
||||
import { PeppaError, startGoogleFlow } from "@peppa/core";
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
import { currentUser, GOOGLE_COOKIE, googleCookieOptions, publicOrigin, safeNext } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
|
||||
/** Starts a Google login (PEP-90) or, from Settings (`purpose=link`, needs a session), linking. POST form → 303 to Google. */
|
||||
export async function POST(req: NextRequest) {
|
||||
const origin = await publicOrigin();
|
||||
const form = await req.formData().catch(() => null);
|
||||
const purpose = form?.get("purpose") === "link" ? "link" : "login";
|
||||
const next = safeNext(String(form?.get("next") ?? ""));
|
||||
const fail = (msg: string) => NextResponse.redirect(`${origin}${purpose === "link" ? "/settings" : "/login"}?error=${encodeURIComponent(msg)}`, 303);
|
||||
try {
|
||||
const user = purpose === "link" ? await currentUser() : null;
|
||||
if (purpose === "link" && !user) return fail(m("Войдите, чтобы привязать Google"));
|
||||
const flow = await startGoogleFlow(db, purpose, `${origin}/auth/google/callback`, user?.id ?? null);
|
||||
const res = NextResponse.redirect(flow.url, 303);
|
||||
res.cookies.set(GOOGLE_COOKIE, flow.state, googleCookieOptions(600));
|
||||
// Where to go after login: a separate cookie value would leak into the URL, so keep it beside the state.
|
||||
res.cookies.set(`${GOOGLE_COOKIE}_next`, next, googleCookieOptions(600));
|
||||
return res;
|
||||
} catch (e) {
|
||||
return fail(e instanceof PeppaError ? e.message : m("Не удалось начать вход через Google"));
|
||||
}
|
||||
}
|
||||
@ -2,14 +2,20 @@ import { consumeLoginLink } from "@peppa/core";
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
import { publicOrigin, sessionCookie } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { adoptLocale, localeCookieOptions } from "@/lib/i18n";
|
||||
import { LOCALE_COOKIE, m } from "@peppa/shared/i18n";
|
||||
|
||||
/** One-time admin login link from `peppa web login-link`. */
|
||||
export async function GET(req: NextRequest) {
|
||||
const origin = await publicOrigin();
|
||||
const uid = await consumeLoginLink(db, req.nextUrl.searchParams.get("code") ?? "");
|
||||
if (!uid) return NextResponse.redirect(`${origin}/login?error=${encodeURIComponent("Ссылка входа недействительна или уже использована")}`);
|
||||
const invalid = m("Ссылка входа недействительна или уже использована");
|
||||
if (!uid) return NextResponse.redirect(`${origin}/login?error=${encodeURIComponent(invalid)}`);
|
||||
const res = NextResponse.redirect(`${origin}/`);
|
||||
const c = sessionCookie(uid);
|
||||
res.cookies.set(c.name, c.value, c.options);
|
||||
// PEP-98: the language picked on the login page sticks to the account (or the account's wins).
|
||||
const lang = await adoptLocale(uid, req.cookies.get(LOCALE_COOKIE)?.value);
|
||||
if (lang) res.cookies.set(LOCALE_COOKIE, lang, localeCookieOptions);
|
||||
return res;
|
||||
}
|
||||
|
||||
@ -1,16 +0,0 @@
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { oauthAuthorizeUrl } from "@peppa/core";
|
||||
import { loadEnv } from "@peppa/shared";
|
||||
import { NextResponse } from "next/server";
|
||||
import { NEXT_COOKIE, publicOrigin, safeNext, STATE_COOKIE } from "@/lib/auth";
|
||||
|
||||
export async function GET(req: Request) {
|
||||
const env = loadEnv();
|
||||
if (!env.GITEA_OAUTH_CLIENT_ID) return new NextResponse("GITEA_OAUTH_CLIENT_ID is not configured", { status: 500 });
|
||||
const state = randomBytes(18).toString("base64url");
|
||||
const res = NextResponse.redirect(oauthAuthorizeUrl(env.GITEA_URL, env.GITEA_OAUTH_CLIENT_ID, `${await publicOrigin()}/auth/callback`, state));
|
||||
const next = safeNext(new URL(req.url).searchParams.get("next"));
|
||||
res.cookies.set(NEXT_COOKIE, next, { httpOnly: true, sameSite: "lax", path: "/auth", maxAge: 600, secure: env.PEPPA_WEB_URL.startsWith("https://") });
|
||||
res.cookies.set(STATE_COOKIE, state, { httpOnly: true, sameSite: "lax", path: "/auth", maxAge: 600, secure: env.PEPPA_WEB_URL.startsWith("https://") });
|
||||
return res;
|
||||
}
|
||||
@ -1,189 +0,0 @@
|
||||
:root {
|
||||
--bg: #f7f6f3;
|
||||
--surface: #ffffff;
|
||||
--text: #1f1d1a;
|
||||
--muted: #6f6a62;
|
||||
--border: #e4e0d8;
|
||||
--accent: #d6457a;
|
||||
--accent-text: #ffffff;
|
||||
--danger: #b4332b;
|
||||
--ok: #2f7d4f;
|
||||
--warn: #a8661b;
|
||||
--info: #3460a8;
|
||||
--code-bg: #f0ede7;
|
||||
--radius: 10px;
|
||||
color-scheme: light;
|
||||
}
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--bg: #151412;
|
||||
--surface: #1e1d1a;
|
||||
--text: #ece8e1;
|
||||
--muted: #a39d93;
|
||||
--border: #34312c;
|
||||
--accent: #ec6b9a;
|
||||
--accent-text: #1a0d12;
|
||||
--danger: #e0675e;
|
||||
--ok: #6cc28f;
|
||||
--warn: #e0a05a;
|
||||
--info: #7fa6ea;
|
||||
--code-bg: #26241f;
|
||||
color-scheme: dark;
|
||||
}
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
html, body { margin: 0; }
|
||||
body {
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
font: 15px/1.5 system-ui, -apple-system, "Segoe UI", sans-serif;
|
||||
}
|
||||
a { color: var(--accent); text-decoration: none; }
|
||||
a:hover { text-decoration: underline; }
|
||||
h1 { font-size: 1.5rem; margin: 0 0 12px; display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
|
||||
h2 { font-size: 1.1rem; margin: 28px 0 10px; }
|
||||
.mono, code, pre { font-family: ui-monospace, "SF Mono", Menlo, monospace; font-size: 0.9em; }
|
||||
.muted { color: var(--muted); }
|
||||
.empty { color: var(--muted); padding: 12px 0; }
|
||||
|
||||
.top {
|
||||
display: flex; align-items: center; gap: 20px; padding: 10px 24px;
|
||||
background: var(--surface); border-bottom: 1px solid var(--border);
|
||||
position: sticky; top: 0; z-index: 1;
|
||||
}
|
||||
.brand { font-weight: 700; color: var(--text); }
|
||||
.top nav { display: flex; gap: 16px; flex: 1; }
|
||||
.top nav a, .me > a { color: var(--muted); }
|
||||
.top nav a.active, .me > a.active { color: var(--text); font-weight: 600; box-shadow: inset 0 -2px 0 var(--accent); }
|
||||
.top nav a:hover, .me > a:hover { color: var(--text); text-decoration: none; }
|
||||
h2 .more { font-size: 0.85rem; font-weight: 400; margin-left: 8px; }
|
||||
.filters { display: flex; flex-wrap: wrap; gap: 6px; margin: 12px 0 4px; }
|
||||
.filters a { padding: 4px 12px; border: 1px solid var(--border); border-radius: 999px; color: var(--text); background: var(--surface); }
|
||||
.filters a:hover { text-decoration: none; border-color: var(--muted); }
|
||||
.filters a.active { border-color: var(--accent); box-shadow: inset 0 0 0 1px var(--accent); }
|
||||
.session header.row { flex-wrap: wrap; row-gap: 2px; }
|
||||
.session header .mono { white-space: nowrap; }
|
||||
.session .title { flex: 1 1 12em; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.me { display: flex; align-items: center; gap: 8px; color: var(--muted); }
|
||||
.me img { border-radius: 50%; }
|
||||
main { max-width: 960px; margin: 0 auto; padding: 24px; }
|
||||
.narrow { max-width: 560px; }
|
||||
.crumbs { margin: 0 0 4px; color: var(--muted); }
|
||||
.desc { white-space: pre-wrap; }
|
||||
|
||||
.card {
|
||||
background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius);
|
||||
padding: 14px 16px; margin: 10px 0;
|
||||
}
|
||||
.q { border-left: 4px solid var(--info); }
|
||||
.q-approval { border-left-color: var(--accent); }
|
||||
.q-permission { border-left-color: var(--warn); }
|
||||
.q-attention { border-left-color: var(--ok); }
|
||||
.q.answered { opacity: 0.7; border-left-color: var(--border); }
|
||||
.kind { font-weight: 600; }
|
||||
.qtext { white-space: pre-wrap; margin: 8px 0; max-height: 18em; overflow: auto; }
|
||||
.attach { display: block; color: var(--muted); margin: 6px 0; overflow-x: auto; }
|
||||
.count { background: var(--accent); color: var(--accent-text); border-radius: 999px; font-size: 0.8rem; padding: 1px 9px; }
|
||||
|
||||
.row { display: flex; gap: 8px; align-items: center; }
|
||||
.row.wrap { flex-wrap: wrap; }
|
||||
.grow { flex: 1; min-width: 0; }
|
||||
.row > input[type=text] { flex: 1; min-width: 0; }
|
||||
.stack { display: flex; flex-direction: column; gap: 12px; margin: 10px 0; }
|
||||
label { display: flex; flex-direction: column; gap: 4px; font-weight: 500; }
|
||||
label.inline { flex-direction: row; align-items: center; font-weight: 400; }
|
||||
fieldset { border: 1px solid var(--border); border-radius: var(--radius); padding: 8px 12px; }
|
||||
.answer { display: flex; flex-direction: column; gap: 8px; margin-top: 8px; }
|
||||
|
||||
input[type=text], textarea, select {
|
||||
font: inherit; color: var(--text); background: var(--bg);
|
||||
border: 1px solid var(--border); border-radius: 8px; padding: 7px 10px; width: 100%;
|
||||
}
|
||||
input.short { width: 8em; }
|
||||
textarea { resize: vertical; }
|
||||
input:focus, textarea:focus, select:focus, button:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
|
||||
|
||||
button, .button {
|
||||
font: inherit; cursor: pointer; border-radius: 8px; padding: 7px 14px;
|
||||
border: 1px solid var(--border); background: var(--surface); color: var(--text); white-space: nowrap;
|
||||
display: inline-block;
|
||||
}
|
||||
button:hover, .button:hover { border-color: var(--muted); text-decoration: none; }
|
||||
.primary { background: var(--accent); color: var(--accent-text); border-color: var(--accent); }
|
||||
.danger { color: var(--danger); }
|
||||
button.link { border: 0; background: none; padding: 0; color: var(--muted); }
|
||||
|
||||
.badge {
|
||||
font-size: 0.75rem; font-weight: 600; border-radius: 999px; padding: 2px 9px;
|
||||
background: var(--code-bg); color: var(--muted); white-space: nowrap;
|
||||
}
|
||||
.s-in_progress, .s-running { color: var(--info); }
|
||||
.s-awaiting_approval, .s-waiting_input, .s-proposing { color: var(--accent); }
|
||||
.s-review, .s-done { color: var(--ok); }
|
||||
.s-blocked, .s-failed, .s-stalled, .s-rate_limited { color: var(--danger); }
|
||||
|
||||
.notice { background: color-mix(in srgb, var(--ok) 12%, var(--surface)); border: 1px solid var(--ok); border-radius: var(--radius); padding: 10px 14px; }
|
||||
.flash { background: color-mix(in srgb, var(--danger) 12%, var(--surface)); border: 1px solid var(--danger); border-radius: var(--radius); padding: 10px 14px; }
|
||||
|
||||
ul.tasks, ul.projects, ul.events { list-style: none; padding: 0; margin: 0; }
|
||||
ul.tasks li, ul.projects li {
|
||||
display: flex; gap: 10px; align-items: center; justify-content: space-between;
|
||||
padding: 8px 12px; background: var(--surface); border: 1px solid var(--border); border-radius: 8px; margin: 6px 0;
|
||||
}
|
||||
ul.tasks li a, ul.projects li a { color: var(--text); min-width: 0; overflow: hidden; text-overflow: ellipsis; }
|
||||
ul.events li { padding: 3px 0; border-bottom: 1px dashed var(--border); overflow-wrap: anywhere; }
|
||||
details { margin: 8px 0; }
|
||||
summary { cursor: pointer; color: var(--accent); }
|
||||
pre.md {
|
||||
white-space: pre-wrap; background: var(--code-bg); border-radius: 8px; padding: 12px;
|
||||
max-height: 32em; overflow: auto;
|
||||
}
|
||||
|
||||
.board { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 10px; margin: 16px 0; }
|
||||
.board.busy { opacity: 0.6; pointer-events: none; }
|
||||
.col { background: color-mix(in srgb, var(--border) 35%, var(--bg)); border-radius: var(--radius); padding: 8px; min-height: 120px; }
|
||||
.col.over { outline: 2px dashed var(--accent); }
|
||||
.col h3 { font-size: 0.85rem; text-transform: uppercase; letter-spacing: 0.04em; margin: 4px 4px 8px; color: var(--muted); }
|
||||
.hint { font-size: 0.75rem; margin: -4px 4px 8px; }
|
||||
.tcard { background: var(--surface); border: 1px solid var(--border); border-radius: 8px; padding: 8px 10px; margin: 6px 0; cursor: grab; display: flex; flex-direction: column; gap: 6px; }
|
||||
.tcard a { color: var(--text); }
|
||||
.tcard .goal { font-size: 0.75rem; flex-basis: 100%; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.small { font-size: 0.78rem; padding: 3px 8px; }
|
||||
details.add { margin: 4px 0; }
|
||||
.login { max-width: 420px; margin: 18vh auto; text-align: center; display: flex; flex-direction: column; gap: 14px; align-items: center; }
|
||||
.login h1 { font-size: 2rem; justify-content: center; }
|
||||
|
||||
@media (max-width: 640px) {
|
||||
main { padding: 16px; }
|
||||
.top { padding: 10px 16px; gap: 12px; flex-wrap: wrap; }
|
||||
.top nav { order: 3; flex-basis: 100%; overflow-x: auto; }
|
||||
.me span { display: none; }
|
||||
.session form.grow { flex-basis: 100%; }
|
||||
ul.tasks li { flex-direction: column; align-items: flex-start; }
|
||||
.board { grid-template-columns: 1fr; }
|
||||
}
|
||||
|
||||
.consent { text-align: left; align-items: stretch; }
|
||||
.consent h1 { justify-content: flex-start; }
|
||||
.scopes { margin: 0; padding-left: 20px; }
|
||||
.mcp-url { display: block; padding: 10px 12px; background: var(--code-bg); border-radius: 8px; overflow-x: auto; }
|
||||
|
||||
.ok { background: color-mix(in srgb, var(--ok) 12%, var(--surface)); border: 1px solid var(--ok); border-radius: var(--radius); padding: 10px 14px; }
|
||||
|
||||
.help ul { padding-left: 20px; }
|
||||
.help li { margin: 4px 0; }
|
||||
.say { margin: 6px 0; font-style: italic; }
|
||||
table.tools { width: 100%; border-collapse: collapse; }
|
||||
table.tools td { border-top: 1px solid var(--border); padding: 6px 8px; vertical-align: top; }
|
||||
table.tools td.mono { white-space: nowrap; }
|
||||
@media (max-width: 640px) { table.tools td.mono { white-space: normal; overflow-wrap: anywhere; } }
|
||||
|
||||
ul.members { list-style: none; padding: 0; margin: 0 0 10px; }
|
||||
ul.members li { display: flex; gap: 10px; align-items: center; justify-content: space-between; padding: 6px 0; border-bottom: 1px dashed var(--border); }
|
||||
|
||||
.foot { max-width: 960px; margin: 0 auto; padding: 16px 24px 32px; font-size: 0.8rem; text-align: center; }
|
||||
|
||||
dl.repo { display: grid; grid-template-columns: max-content 1fr; gap: 4px 14px; margin: 0 0 10px; }
|
||||
dl.repo dt { color: var(--muted); }
|
||||
dl.repo dd { margin: 0; }
|
||||
@ -1,12 +1,32 @@
|
||||
import type { ReactNode } from "react";
|
||||
import "./globals.css";
|
||||
import { cookies } from "next/headers";
|
||||
import { GeistSans } from "geist/font/sans";
|
||||
import { GeistMono } from "geist/font/mono";
|
||||
import { productName } from "@peppa/shared/i18n";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { THEME_COOKIE } from "@/lib/theme";
|
||||
import { getLocale, getT } from "@/lib/i18n";
|
||||
import { ErrorReporter } from "@/components/ErrorReporter";
|
||||
import { I18nProvider } from "@/components/I18n";
|
||||
import "./app.css";
|
||||
|
||||
export const metadata = { title: "Peppa", description: "Софтвейр-фабрика: проекты, задачи и агенты" };
|
||||
export async function generateMetadata() {
|
||||
const t = await getT();
|
||||
return { title: productName(t.locale), description: t("FORGE: опишите идею словами — ИИ-агенты сделают продукт"), icons: { icon: "/icon.svg" } };
|
||||
}
|
||||
|
||||
export default function RootLayout({ children }: { children: ReactNode }) {
|
||||
export default async function RootLayout({ children }: { children: ReactNode }) {
|
||||
// Dark by default; the cookie is read on the server so a light choice renders without a dark flash.
|
||||
const light = (await cookies()).get(THEME_COOKIE)?.value === "light";
|
||||
const locale = await getLocale();
|
||||
return (
|
||||
<html lang="ru">
|
||||
<body>{children}</body>
|
||||
<html lang={locale === "kk" ? "kk" : locale} className={cn(GeistSans.variable, GeistMono.variable, !light && "dark")}>
|
||||
<body>
|
||||
<I18nProvider locale={locale}>
|
||||
<ErrorReporter />
|
||||
{children}
|
||||
</I18nProvider>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
|
||||
19
apps/web/app/locale-actions.ts
Normal file
19
apps/web/app/locale-actions.ts
Normal file
@ -0,0 +1,19 @@
|
||||
"use server";
|
||||
|
||||
import { forgetChatLocales, setUserLocale } from "@peppa/core";
|
||||
import { LOCALE_COOKIE, normalizeLocale } from "@peppa/shared/i18n";
|
||||
import { cookies } from "next/headers";
|
||||
import { currentUser } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { localeCookieOptions } from "@/lib/i18n";
|
||||
|
||||
/** PEP-98: language switcher — cookie for everyone, plus the user's setting when logged in. */
|
||||
export async function setLanguage(value: string): Promise<void> {
|
||||
const locale = normalizeLocale(value);
|
||||
(await cookies()).set(LOCALE_COOKIE, locale, localeCookieOptions);
|
||||
const user = await currentUser();
|
||||
if (user) {
|
||||
await setUserLocale(db, user.id, locale);
|
||||
forgetChatLocales();
|
||||
}
|
||||
}
|
||||
@ -1,20 +1,124 @@
|
||||
import { redirect } from "next/navigation";
|
||||
import { Check, Laptop, MessageCircle, ShieldCheck, Sparkles } from "lucide-react";
|
||||
import { featureGateView, googleEnabled } from "@peppa/core";
|
||||
import { FeatureGate } from "@/components/FeatureGate";
|
||||
import { LiveRefresh } from "@/components/LiveRefresh";
|
||||
import { currentUser, safeNext } from "@/lib/auth";
|
||||
import { Flash } from "@/components/ui";
|
||||
import { Brand } from "@/components/Brand";
|
||||
import { GoogleSignIn } from "@/components/GoogleSignIn";
|
||||
import { Flash } from "@/components/common";
|
||||
import { EgovSign } from "@/components/EgovSign";
|
||||
import { Footer } from "@/components/Footer";
|
||||
import { PugMascot } from "@/components/PugMascot";
|
||||
import { LanguageSwitcher } from "@/components/I18n";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const WHY = [
|
||||
{ title: m("Программировать не нужно"), text: m("Вы пишете, что должно получиться, — как объяснили бы коллеге. Как это сделать, решают агенты.") },
|
||||
{ title: m("Всё на виду"), text: m("Доска показывает, что в работе, что готово и какой агент чем занят. Никаких «спросите у разработчиков».") },
|
||||
{ title: m("Последнее слово за вами"), text: m("Ничего не считается готовым, пока вы не посмотрели результат и не нажали «Принять».") },
|
||||
];
|
||||
|
||||
const STEPS = [
|
||||
{ title: m("Войдите с ноутбука"), text: m("Через eGov QR или Google — учётка создаётся сама, пароль не нужен.") },
|
||||
{ title: m("Привяжите Telegram-бота"), text: m("Он на телефоне позовёт вас, когда агенту нужен ответ или работа готова.") },
|
||||
{ title: m("Создайте проект и подключите подписку"), text: m("Свою Claude или ChatGPT — на ней агенты пишут код. Это одна минута.") },
|
||||
{ title: m("Опишите задачу словами"), text: m("«Страница с каталогом: фото, цена, кнопка „Купить“». Агент возьмёт её сам.") },
|
||||
{ title: m("Примите результат"), text: m("Придёт сообщение «готово». Посмотрите и нажмите «Принять» — или напишите, что поправить.") },
|
||||
];
|
||||
|
||||
const NEED = [
|
||||
{ icon: Laptop, text: m("Ноутбук — управлять фабрикой удобнее с большого экрана") },
|
||||
{ icon: ShieldCheck, text: m("eGov Mobile на телефоне — для входа") },
|
||||
{ icon: MessageCircle, text: m("Telegram — туда приходят вопросы агентов и «готово»") },
|
||||
{ icon: Sparkles, text: m("Платная подписка Claude или ChatGPT — на ней работают агенты") },
|
||||
];
|
||||
|
||||
/** PEP-71: eGov QR is the only way in. PEP-83: the page first says why the factory and how it works. */
|
||||
export default async function Login({ searchParams }: { searchParams: Promise<{ error?: string; next?: string }> }) {
|
||||
const { error, next } = await searchParams;
|
||||
if (await currentUser()) redirect(safeNext(next));
|
||||
const t = await getT();
|
||||
// PEP-224: eGov known to be down — a grey button with a caption; Google (if on) becomes the main way in.
|
||||
const egov = featureGateView("egov_login");
|
||||
const egovDown = egov.state === "unavailable";
|
||||
const google = googleEnabled();
|
||||
const googleButton = google && <GoogleSignIn purpose="login" next={safeNext(next)} label={t("Войти через Google")} primary={egovDown} />;
|
||||
return (
|
||||
<main className="login">
|
||||
<h1>🐷 Peppa</h1>
|
||||
<p className="muted">Софтвейр-фабрика: проекты в Gitea, задачи по OpenSpec, агенты Claude Code и Codex.</p>
|
||||
<Flash error={error} />
|
||||
<a className="button primary" href={`/auth/start?next=${encodeURIComponent(safeNext(next))}`}>Войти через Gitea</a>
|
||||
<Footer />
|
||||
<main className="relative mx-auto grid min-h-dvh w-full max-w-6xl content-start items-start gap-x-10 gap-y-8 px-5 py-10 lg:grid-cols-[minmax(0,1fr)_380px] lg:py-16">
|
||||
<LanguageSwitcher className="absolute top-3 right-5 z-10" />
|
||||
{/* Phone: headline → sign-in → details. Laptop: text on the left, sign-in sticks on the right. */}
|
||||
<header className="flex flex-col gap-4 lg:col-start-1 lg:row-start-1">
|
||||
<Brand large />
|
||||
<h1 className="m-0 text-3xl leading-tight font-semibold tracking-tight text-balance sm:text-4xl">{t("Опишите идею словами — команда ИИ-агентов сделает продукт")}</h1>
|
||||
<p className="m-0 max-w-2xl text-base text-muted-foreground">
|
||||
{t("FORGE — фабрика программ для тех, кто придумывает продукты, а не пишет код. Вы ставите задачи и принимаете результат; агенты программируют, проверяют себя и отчитываются.")}
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<aside className="flex flex-col items-center gap-4 rounded-2xl border bg-card p-6 text-center lg:sticky lg:top-10 lg:col-start-2 lg:row-span-2 lg:row-start-1">
|
||||
<PugMascot mood="alert" size={112} />
|
||||
<h2 className="m-0 text-xl font-semibold">{t("Начать — одна минута")}</h2>
|
||||
<p className="m-0 text-sm text-muted-foreground">{t("Вход через eGov или Google. Первый вход сам создаёт учётку — регистрироваться отдельно не нужно.")}</p>
|
||||
<Flash error={error ? t.text(error) : undefined} />
|
||||
<LiveRefresh scope="features" indicator={false} />
|
||||
{egovDown && googleButton}
|
||||
<FeatureGate view={egov} label={t("Войти через eGov")}>
|
||||
<EgovSign purpose="login" next={safeNext(next)} label={t("Войти через eGov")} />
|
||||
</FeatureGate>
|
||||
{!egovDown && googleButton}
|
||||
{egovDown && !google && <p className="m-0 text-sm text-muted-foreground">{t("Другого способа входа сейчас нет. Откройте эту страницу позже — кнопка заработает сама, как только eGov снова будет доступен.")}</p>}
|
||||
<p className="m-0 text-xs text-muted-foreground lg:hidden">{t("Вы с телефона? Войти можно и отсюда, но управлять фабрикой удобнее с ноутбука.")}</p>
|
||||
</aside>
|
||||
|
||||
<div className="flex flex-col gap-9 lg:col-start-1 lg:row-start-2">
|
||||
<section aria-labelledby="why" className="flex flex-col gap-3">
|
||||
<h2 id="why" className="m-0 text-sm font-semibold tracking-wide text-muted-foreground uppercase">{t("Зачем это вам")}</h2>
|
||||
<ul className="m-0 grid list-none gap-3 p-0 sm:grid-cols-3">
|
||||
{WHY.map((w) => (
|
||||
<li key={w.title} className="flex flex-col gap-1.5 rounded-xl border bg-card p-4">
|
||||
<span className="flex items-center gap-2 font-medium">
|
||||
<Check className="size-4 shrink-0 text-ok" /> {t(w.title)}
|
||||
</span>
|
||||
<span className="text-sm text-muted-foreground">{t(w.text)}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<section aria-labelledby="how" className="flex flex-col gap-3">
|
||||
<h2 id="how" className="m-0 text-sm font-semibold tracking-wide text-muted-foreground uppercase">{t("Как это работает — пять шагов")}</h2>
|
||||
<ol className="m-0 flex list-none flex-col gap-2 p-0">
|
||||
{STEPS.map((s, i) => (
|
||||
<li key={s.title} className="flex items-start gap-3 rounded-xl border bg-card px-4 py-3">
|
||||
<span aria-hidden className="mt-0.5 grid size-7 shrink-0 place-items-center rounded-full bg-primary/15 text-sm font-semibold text-primary">
|
||||
{i + 1}
|
||||
</span>
|
||||
<span className="flex min-w-0 flex-col">
|
||||
<span className="font-medium">{t(s.title)}</span>
|
||||
<span className="text-sm text-muted-foreground">{t(s.text)}</span>
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</section>
|
||||
|
||||
<section aria-labelledby="need" className="flex flex-col gap-3">
|
||||
<h2 id="need" className="m-0 text-sm font-semibold tracking-wide text-muted-foreground uppercase">{t("Что понадобится")}</h2>
|
||||
<ul className="m-0 grid list-none gap-2 p-0 sm:grid-cols-2">
|
||||
{NEED.map((n) => (
|
||||
<li key={n.text} className="flex items-start gap-2.5 text-sm">
|
||||
<n.icon className="mt-0.5 size-4 shrink-0 text-primary" /> {t(n.text)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
<Footer />
|
||||
</div>
|
||||
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
19
apps/web/app/manifest.ts
Normal file
19
apps/web/app/manifest.ts
Normal file
@ -0,0 +1,19 @@
|
||||
import type { MetadataRoute } from "next";
|
||||
import { PRODUCT_NAME } from "@peppa/shared/i18n";
|
||||
import { getT } from "@/lib/i18n";
|
||||
|
||||
/** Installable as an app (PEP-55): Chrome «Установить FORGE», badge on the app icon. */
|
||||
export default async function manifest(): Promise<MetadataRoute.Manifest> {
|
||||
const t = await getT();
|
||||
return {
|
||||
name: PRODUCT_NAME,
|
||||
short_name: PRODUCT_NAME,
|
||||
description: t("Проекты, задачи и агенты"),
|
||||
start_url: "/",
|
||||
scope: "/",
|
||||
display: "standalone",
|
||||
background_color: "#0a0a0a",
|
||||
theme_color: "#0a0a0a",
|
||||
icons: [{ src: "/icon.svg", sizes: "any", type: "image/svg+xml", purpose: "any" }],
|
||||
};
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user