Compare commits
453 Commits
task/pep-2
...
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 | |||
| 2f6ee065cf | |||
| 05a4dab2f4 | |||
| 156f1fbaaf | |||
| d8cedab5f0 | |||
| e29e95e13f | |||
| 218f35af86 |
@ -36,6 +36,8 @@ GITEA_OAUTH_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
|
||||
|
||||
@ -34,7 +34,13 @@ jobs:
|
||||
node-version: "26"
|
||||
- name: tools
|
||||
run: |
|
||||
apt-get update -qq && apt-get install -y -qq tmux >/dev/null
|
||||
# PEP-271: a mirror mid-sync fails `apt-get update`; with `&&` the install was skipped silently
|
||||
# and every e2e test died later on «spawn tmux ENOENT». Retry, then fail here if tmux is missing.
|
||||
for i in 1 2 3; do
|
||||
{ apt-get update -qq && apt-get install -y -qq tmux >/dev/null; } && break
|
||||
echo "apt: attempt $i failed, retrying"; sleep $((i * 15))
|
||||
done
|
||||
command -v tmux >/dev/null || { echo "::error::tmux was not installed (apt mirror unavailable)"; exit 1; }
|
||||
# Job-local prefix: the node toolcache is shared between jobs running at the same time
|
||||
# (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
|
||||
|
||||
@ -1,56 +1,75 @@
|
||||
# Память проекта
|
||||
|
||||
Пишет агент через MCP `remember` (PEP-30). Не повторяй AGENTS.md — здесь только то, чего там нет или что легко пропустить.
|
||||
Пишет агент через `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` (иначе node --test и `pnpm run ci` молча ничего не запускают). В свежем worktree сначала `pnpm install --frozen-lockfile`.
|
||||
- Экраны без живых данных: `PEPPA_HOME=<tmp> PEPPA_DB=<tmp>/peppa.db PEPPA_SECRET=x peppa db migrate`, `DATABASE_URL=<tmp>/peppa.db node apps/web/scripts/mock-ui-seed.ts mock-pm`, `next dev -p <порт>` в apps/web с тем же env, `PEPPA_WEB_URL=http://localhost:<порт>` и `PEPPA_RUNNER_MODE=inline PEPPA_ROTATE=off`; `peppa web login-link mock-pm` (суперадмину — `peppa platform allow <login>`); страницы — curl с cookie; «Инженер» — settings `ui.mode:<userId>` = `"engineer"`. Подписок mock-ui-seed не создаёт — вставь subscriptions, subscription_pools(+members), `projects.subscription_pool_id`, `sessions.subscription_id` через sqlite3.
|
||||
- CLI из worktree против живой системы: `set -a; . /Users/telecom/Dev/Peppa/.env; set +a` и `<worktree>/packages/cli/bin/peppa …`.
|
||||
- Тесты из шелла 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`, оно может стоять в чужих текстах.
|
||||
- Эталон (PEP-184): `node bench/lib/run-checks.mjs <task> <копия> [ctx]`.
|
||||
|
||||
## Грабли
|
||||
- `next dev` правит apps/web/AGENTS.md (он в git — `git checkout`, не `rm`) и next-env.d.ts — не коммитить. Открывать `http://localhost:<порт>`, не 127.0.0.1 (allowedDevOrigins — без гидрации кнопки молчат).
|
||||
- Headless Chrome: chrome-devtools MCP бывает занят другой сессией — playwright-core (`~/.hermes/hermes-agent/node_modules/playwright-core`) + `chrome-headless-shell` из `~/Library/Caches/ms-playwright`; fake-audio не работает — подменяй getUserMedia; `--screenshot` страницы за входом виснет — проверяй текст curl'ом. Homebrew на Mac Пеппы чужой — brew install не проходит.
|
||||
- CLI из теста с моком в том же процессе — только async execFile. Тест testkit не импортирует apps/web статически (типы Next ломают ProcessEnv) — `import(new URL(…).href)`.
|
||||
- `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 выбирает вариант по числу НЕпереведённых русских букв, не по кириллице: казахский тоже кириллица.
|
||||
- Gitea 1.22 `GET /compare/<base>...<head>` — только имена веток (SHA → 404; mock-gitea так же). peppa-bot не создаёт организации (403) — их создаёт админ.
|
||||
- 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-сегмент. Строгий script-CSP не включён (inline-скрипты Next).
|
||||
- act-runner: `capacity` применяется только перезапуском `peppa-act-runner` (убивает идущие проверки); после правок compose — `scripts/infra-up.sh act-runner`.
|
||||
- Новая фраза Claude о лимите — в `parseResetTime` и таблицу limits.test.ts, иначе подписка зря считается свободной. Codex 0.169 без `--full-auto`: режим — `CODEX_DEFAULT_MODE` (providers.ts), срочно — `PEPPA_CODEX_MODE` в .env.
|
||||
- bench: check.mjs не импортирует run-checks.mjs (главный модуль с top-level await — взаимная блокировка), помощники — bench/lib/check-kit.mjs.
|
||||
- Хук грузит только лёгкий `runner/limit-delay.ts` — не тянуть в него flow.ts. В тесте хука PEPPA_GENERATION = поколение сессии (вставленной руками — 0).
|
||||
- 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/<раздел>.ts` и `i18n/kk/<раздел>.ts` (тесты i18n-check и i18n-kk падают без перевода). Ключ-шаблон, кончающийся плейсхолдером, — специфичный. «Peppa FACTORY» не склоняется; в kk окончание через дефис (Peppa FACTORY-нің); к {плейсхолдеру} kk-окончание не клеить — фраза вокруг именительного («Жаңа {task}»); `wording(mode,"kk")` отдаёт именительный. Тексты агентам (RULES.md, промпты) говорят «Пеппа» — не трогаем.
|
||||
- Слова по режиму (PEP-123): в вебе «стори»/«раннер» строкой не пишем — `w.task("acc")`, `w.runner()` из `await words()` / `useWords()`, инженерное — под `w.engineer`; тексты без читателя (чаты, Telegram, push, core) — «задача», «агент», «вы».
|
||||
- Экраны «Продакт» (PEP-120/122): вид — чистая функция в core с текстами в одном объекте (`storyProductView`, `core/help-texts.ts` ru/kk/en), инженерное — под «Подробнее» (`?more=1`); тест сверяет ru с «Нельзя» docs/glossary.md.
|
||||
- «Готова к ревью» (с «Принять») — только через `sendReviewCard` (core/review-card.ts): при зелёном `prGate`, иначе дошлёт `reviewCardTick`. «Принять» при конфликте (PEP-127): `accept.pending:<taskId>`, доводит `pendingAcceptTick`; новые пути «готово к ревью»/мержа пропускают стори с `getPendingAccept`. В тестах Gitea «лежит» — `gitea.down = true`.
|
||||
- Подписки (PEP-107/121): ротация claude↔codex без того же провайдера (PEPPA_ROTATE_CROSS=off); займы и предупреждения — в settings (`subscription.loan:…`, `subscription.warned:…`), картина — `poolOverview`. Имя подписки видят только суперадмин и автор — `visibleSubscriptionName`/`publicSubscriptionName`, в вебе `<SubscriptionName>`.
|
||||
- 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` в packages/core|runner|mcp проверяет литералы внутри `m()/tr()/t()/t.n()`; подсказку агенту в `m()` не оборачивать. Запрещённое слово там роняет lint сразу, `--update` не поможет: переписать (ключ = русская строка — поменять в `i18n/en`, `i18n/kk` и тестах) или `glossary-ignore: <почему>` строкой выше (читает инженер); текст человеку мимо словаря переводов — `glossary-user: <почему>`. Разбор словаря — `@peppa/shared/glossary`.
|
||||
- Долгая форма (PEP-142): кнопка — `<PendingButton pendingText>`; создание проекта из веба — `provisionProjectOnce` (общий промис; повтор за 2 мин — `justCreatedProject`), CLI/MCP — `provisionProject`.
|
||||
- Обращения (PEP-143): вся логика в `core/feedback.ts`, агент — `feedbackTick` (runner/feedback.ts, одна попытка, сбой → суперадмину без разбора); новый текст — в `i18n/{en,kk}/feedback.ts`; файл в Telegram — outbox-метод `sendPhoto` с `params.photo_path`; слово «команда» (люди) словарь запрещает — перефразируй; загрузка файлов из веба — route handler с multipart, не server action (предел 1 МБ).
|
||||
- Без повторов (PEP-151): `raiseSessionQuestion`/`askPm` при том же состоянии задачи (отпечаток, `core/message-state.ts`) не создают вопрос, а обновляют прежний и возвращают его id (закрытый открывается снова); свободный текст агента — `topic: "turn"`, «готово» — `topic: "review"`.
|
||||
- Служебный текст (PEP-154): текст агента/терминала человеку — через `core/user-text.ts` (`userText`; `stripServiceBlocks` — для слов человека); `raiseSessionQuestion`/`askPm`/`addChatMessage` чистят сами, пусто → PeppaError, исходник — `questionDetails` (инженер/суперадмин). Текст исключения владельцу не слать: `platformFailure` даёт строку только для PeppaError, иначе null (ушло суперадмину и в учёт ошибок). В тесте хука PEPPA_GENERATION = поколение сессии (вставленной руками — 0).
|
||||
- Типы сообщений (PEP-149): пишешь пользователю — выбери тип: вопрос только с вариантами (`askPm`/`raiseSessionQuestion` с `msgType`, `defaultOption`), «готово» — только `sendReviewCard`, ход работы/блокер — события `progress`/`blocker`; читать тип — `questionType`/`needsPerson` (core/questions.ts), не `kind === "attention"`. Конец хода агента вопроса не создаёт: в тестах жди статус сессии `idle`, а не `waitQuestion(sid, "attention")`.
|
||||
- Формат сообщения агента (PEP-152): сообщение агента человеку — через `admitAgentMessage` + `renderMain` (core/agent-message.ts): в тексте — основная часть (слова агента в `asIs`), техника — `details` (`messageDetails`), экран режет `splitForDisplay`. Суть с файлом, веткой, командой, «PR #N», статусом из кода, словом «Нельзя» — отказ.
|
||||
- Чужой текст в сообщениях (PEP-139/140): слова человека/модели, название задачи/проекта, логин, варианты агента, причину извне подставляй в `m()` как `asIs(…)` (shared/i18n) — перевод их не трогает; фразы самой фабрики (`PeppaError`, причина гейта) не помечай. Вопрос агента = `questionIsFreeText`, текст переводящему читателю — `questionText(q)`; MCP, CLI, агенту и сравнение текста в тестах — `stripAsIs`.
|
||||
- Вложения (PEP-159): файл грузится отдельно (`POST /api/attachments`, не server action — предел 1 МБ) и привязывается действием через `linkAttachments`; новое место с файлами — `<AttachField projectId target>` в форме и `<Attachments files>` для показа; типы только по содержимому (`sniffAttachment`). Агент читает файлы из `.peppa/attachments/` (папка сама в gitignore).
|
||||
- Переписка проекта (PEP-155): `projectThreadList`/`threadGroup`/`plainLine` (core/chat-threads.ts); поиск кириллицы — в JS.
|
||||
- Тесты: места подписки занимай `core.createSession` с `subscriptionId`; задачу из очереди ёмкости убирай `moveTask(backlog)`, иначе её подхватит тик соседнего теста. Конец хода агента вопроса не создаёт — жди статус сессии `idle`. Сообщения суперадмина — `superadmin()` из helpers.ts. Текст из `chat_messages` сравнивай через `stripAsIs`.
|
||||
- Узкие места: запуск/перенос раннера — `pickSubscription`/`rotationCandidate`; агент, модель, сообщение человеку — `startRunner`/`resumeSession`, `claudePrint`, `deliverToUser` или с `isProjectPaused`; список проектов — `listProjects(db)`/`userProjectIds`, прямой `from(projects)` — с `isNull(projects.deletedAt)`; действие веба, которое запускает/убивает агентов, — через runnerCall.
|
||||
- Сообщения человеку: вопрос — `askPm`/`raiseSessionQuestion` с `msgType` и вариантами; «готово» — только `sendReviewCard`; ход работы/блокер — события; сбой платформы — `platformDelay`/`sessionDelay`, исключение — `platformFailure`; тип читать `questionType`/`needsPerson`, не `kind`. Текст агента — `admitAgentMessage` + `renderMain`, техника в `details`.
|
||||
- Вопрос ≠ задача (PEP-153): текст человека, который может стать задачей, — через `classifyMessage` (runner/message-intent.ts; в тестах mock-intake роль `intent`); молча задачу не заводить — кнопки (`chat.offer:<messageId>`, `INTENT_TEXT`).
|
||||
- Словарь в сообщениях ядра (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` напрямую.
|
||||
|
||||
## Решения
|
||||
- После правок `template/` — `scripts/push-template.sh` и `peppa ci connect <KEY>` старым проектам.
|
||||
- Живой сайт — только `scripts/live-deploy.sh`; в живой копии коммиты запрещены хуком, агенты там не запускаются.
|
||||
- Эталон (PEP-184, PM): подписка прогона — наименее загруженная свободная из общего пула; про подписку PM не спрашивать.
|
||||
- Распознавание речи — свой faster-whisper (`<Dictate>`, MediaRecorder), не Web Speech API. Вход через Google: по почте учётки не склеиваем.
|
||||
- Привязка Google к учётке с другим Google-only пользователем объединяет учётки (core/merge-users.ts `mergeUserInto`); с eGov/Gitea — отказ к админу (PEP-195).
|
||||
- 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).
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
// alerts) to the paired chat and turns button presses / replies into answers delivered
|
||||
// back into the agent session. Telegram is an adapter over the DB, not a remote shell:
|
||||
// it can only answer a specific pending question or resume/stop the session it is about.
|
||||
import { duringPause, isProjectPaused, LOCALIZED_PARAM, localizeMessage, messageDetails, questionIsFreeText, reportPlatformError, telegramChatLocale } from "@peppa/core";
|
||||
import { acceptDigestHold, duringPause, heldForDigest, isProjectPaused, LOCALIZED_PARAM, localizeMessage, messageDetails, questionIsFreeText, reportPlatformError, telegramChatLocale } from "@peppa/core";
|
||||
import { asIs, localizeRoleMessage, m as tr, stripAsIs } from "@peppa/shared/i18n";
|
||||
import {
|
||||
accountUsageForUser,
|
||||
@ -33,7 +33,9 @@ import {
|
||||
type User,
|
||||
getOffset,
|
||||
getIncident,
|
||||
agentSignature,
|
||||
getQuestion,
|
||||
questionAuthor,
|
||||
getSession,
|
||||
listSessions,
|
||||
markOutboxRetry,
|
||||
@ -78,14 +80,16 @@ import {
|
||||
} from "@peppa/core";
|
||||
import { projects, tasks, type Db } from "@peppa/db";
|
||||
import { formatTaskKey, voiceStoriesEnabled } from "@peppa/shared";
|
||||
import { acceptTask, answerAndDeliver, classifyMessage, decideIncident, moveTask, postToChat, REQUEST_SENT_TEXT, requestSubscription, resumeSession, stopSession } from "@peppa/runner";
|
||||
import { delayAction, resolveTaskById } from "@peppa/runner";
|
||||
import { decideIdleGrant, parseDelayCallback, parseIdleGrantCallback } from "@peppa/core";
|
||||
import { acceptTask, answerAndDeliver, classifyMessage, decideIncident, decideProposals, moveTask, postToChat, REQUEST_SENT_TEXT, requestSubscription, resumeSession, stopSession } from "@peppa/runner";
|
||||
import { INTENT_TEXT, statusAnswer } from "@peppa/core";
|
||||
import { AsyncLocalStorage } from "node:async_hooks";
|
||||
import { eq, sql } from "drizzle-orm";
|
||||
import { choiceToAnswer, esc, renderAnswered, renderQuestion } from "./render.ts";
|
||||
import { TelegramApi, TelegramError, type InlineButton, type TgCallbackQuery, type TgMessage, type TgUpdate } from "./telegram.ts";
|
||||
import { dropDraft, loadDraft, parseStoryText, saveDraft, splitStory, updateDraft, type Draft } from "./drafts.ts";
|
||||
import { transcribe, transcribeConfig, TranscribeError } from "@peppa/core";
|
||||
import { getUserLocale, transcribe, transcribeConfig, transcribeLanguage, TranscribeError } from "@peppa/core";
|
||||
import { addFeedbackScreenshot, FEEDBACK_MAX_SHOTS, fixFeedback, isSuperadmin, linkFeedback, PeppaError, rejectFeedback, submitFeedback } from "@peppa/core";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { basename } from "node:path";
|
||||
@ -118,7 +122,7 @@ export interface BotOptions {
|
||||
|
||||
// One key per line: localizeMessage translates a multi-line message line by line.
|
||||
const helpText = (voice: boolean) => [
|
||||
tr("Я бот Peppa FACTORY. Присылаю вопросы от агентов и сообщения о том, что задача готова или агент ждёт вас."),
|
||||
tr("Я бот FORGE. Присылаю вопросы от агентов и сообщения о том, что задача готова или агент ждёт вас."),
|
||||
"",
|
||||
tr("• Кнопки под сообщением — быстрый ответ."),
|
||||
tr("• Ответ <b>реплаем</b> на сообщение — свой текст, он уйдёт агенту."),
|
||||
@ -127,7 +131,7 @@ const helpText = (voice: boolean) => [
|
||||
: tr("• Просто напишите задачу — я её заведу: «в PAY: экспорт в CSV». Проект и эпик уточню кнопками, потом предложу сразу взять в работу."),
|
||||
tr("• Спросите, что сейчас происходит («какие задачи у агентов?», «что с PAY-3?») — отвечу сразу, задачу из вопроса не заведу."),
|
||||
tr("• /status — кто из агентов работает и какие вопросы открыты."),
|
||||
tr("• /problem — сообщить о проблеме в Peppa FACTORY: напишите, что случилось, и приложите фото экрана."),
|
||||
tr("• /problem — сообщить о проблеме в FORGE: напишите, что случилось, и приложите фото экрана."),
|
||||
tr("• /digest — сводка за сутки по вашим проектам (каждый день приходит сама; время и что присылать — в Настройках → Уведомления)."),
|
||||
].join("\n");
|
||||
|
||||
@ -154,7 +158,7 @@ const PUSH_TITLE: Record<NotifyEvent, string> = {
|
||||
users: tr("Новый пользователь"),
|
||||
feedback: tr("Обращение пользователя"),
|
||||
digest: tr("Сводка"),
|
||||
platform: tr("Обновления Peppa FACTORY"),
|
||||
platform: tr("Обновления FORGE"),
|
||||
};
|
||||
|
||||
/** Browser notification text for a question. */
|
||||
@ -300,7 +304,9 @@ export function createBot(o: BotOptions) {
|
||||
if (q.sessionId) session = await getSession(db, q.sessionId).catch(() => null);
|
||||
const [st] = q.taskId ? await db.select({ status: tasks.status }).from(tasks).where(eq(tasks.id, q.taskId)) : [];
|
||||
const taskStatus = st?.status ?? null;
|
||||
if (session) return { taskKey: session.taskKey, taskTitle: session.taskTitle, taskStatus, session, webUrl: o.webUrl };
|
||||
const author = await questionAuthor(db, q).catch(() => null);
|
||||
const agent = author?.kind === "agent" ? author.name : null;
|
||||
if (session) return { taskKey: session.taskKey, taskTitle: session.taskTitle, taskStatus, session, webUrl: o.webUrl, agent };
|
||||
if (q.taskId) {
|
||||
const [t] = await db
|
||||
.select({ key: projects.key, number: tasks.number, title: tasks.title })
|
||||
@ -343,6 +349,10 @@ export function createBot(o: BotOptions) {
|
||||
// A push is a "now" signal: questions older than this don't pop up on a fresh subscription.
|
||||
const fresh = Date.now() - q.createdAt.getTime() < PUSH_MAX_AGE_MS;
|
||||
const url = ctx.taskKey ? `/t/${ctx.taskKey}` : `/p/${await projectKey(q.projectId)}`;
|
||||
// PEP-198: a finished story nobody waits for comes in the evening digest, not one by one.
|
||||
if (await heldForDigest(db, q, ctx.taskStatus ?? null)) continue;
|
||||
// PEP-209: more than two ready within an hour — one summary with «Приёмка» instead (acceptDigestTick).
|
||||
if ((await acceptDigestHold(db, q)) !== "send") continue;
|
||||
for (const u of audience) {
|
||||
// PEP-154: the terminal command is for the «Инженер» view only.
|
||||
const r = renderQuestion(q, { ...ctx, engineer: (await getUiMode(db, u.id)) === "engineer" });
|
||||
@ -434,15 +444,16 @@ export function createBot(o: BotOptions) {
|
||||
// PEP-139: a person's words go as written; an AI role's message gets its fixed lines in the
|
||||
// group's language and is then free text too. Events are factory phrases (free parts are
|
||||
// marked where the event text is built) and are translated when sent.
|
||||
const role = m.kind === "user" && m.authorKind === "agent";
|
||||
const inRole = role ? await telegramChatLocale(db, tgChatId).catch(() => "ru" as const) : null;
|
||||
// PEP-156: an agent or an AI role signs with its nickname or name: «🤖 Шустрик: …».
|
||||
const bot = m.authorKind === "agent";
|
||||
const inRole = bot ? await telegramChatLocale(db, tgChatId).catch(() => "ru" as const) : null;
|
||||
const own = (s: string) => (inRole ? localizeRoleMessage(inRole, s) : s);
|
||||
// A note the factory itself writes into a discussion (authorKind system) is a phrase, not free text.
|
||||
const free = m.kind === "user" && m.authorKind !== "system";
|
||||
const free = bot || (m.kind === "user" && m.authorKind !== "system");
|
||||
const said = free ? asIs(esc(own(m.text).slice(0, 3500))) : esc(m.text.slice(0, 3500));
|
||||
const login = own(m.authorLogin ?? "?");
|
||||
const who = m.kind === "user" ? `<b>${asIs(esc(login))}</b>` : m.authorKind === "agent" ? "🤖 " : "";
|
||||
const body = m.kind === "user" ? (m.via === "telegram" ? `: ${said}` : tr(" (веб): {text}", { text: said })) : said;
|
||||
const who = bot ? `<b>${asIs(esc(agentSignature(m.authorLogin ? login : null)))}</b>` : m.kind === "user" ? `<b>${asIs(esc(login))}</b>` : "";
|
||||
const body = bot ? `: ${said}` : m.kind === "user" ? (m.via === "telegram" ? `: ${said}` : tr(" (веб): {text}", { text: said })) : said;
|
||||
text = `${where ? `${where}\n` : ""}${who}${body}${m.url ? `\n${esc(m.url)}` : ""}`;
|
||||
}
|
||||
await enqueueTelegram(db, {
|
||||
@ -620,7 +631,7 @@ export function createBot(o: BotOptions) {
|
||||
}
|
||||
|
||||
/** Text of a voice note; null — it could not be heard, and the user has been told. */
|
||||
async function voiceText(m: TgMessage): Promise<string | null> {
|
||||
async function voiceText(user: User, m: TgMessage): Promise<string | null> {
|
||||
const f = m.voice ?? m.audio!;
|
||||
const cfg = transcribeConfig();
|
||||
if (!cfg) return reply(m.chat.id, tr("Голосовые сообщения пока не работают. Напишите задачу текстом."), m.message_id).then(() => null);
|
||||
@ -630,7 +641,9 @@ export function createBot(o: BotOptions) {
|
||||
const file = await api.getFile(f.file_id);
|
||||
if (!file.file_path) throw new TranscribeError(tr("Telegram не отдал файл"));
|
||||
const audio = await api.downloadFile(file.file_path);
|
||||
text = await transcribe(cfg, audio, file.file_path.split("/").pop() || "voice.ogg", f.mime_type ?? "audio/ogg");
|
||||
// PEP-131: in the speaker's own language (in a group too — theirs, not the group's).
|
||||
const language = transcribeLanguage(cfg, await getUserLocale(db, user.id));
|
||||
text = await transcribe(cfg, audio, file.file_path.split("/").pop() || "voice.ogg", f.mime_type ?? "audio/ogg", language);
|
||||
} catch (e) {
|
||||
log(`voice: ${(e as Error).message}`);
|
||||
return reply(m.chat.id, tr("Не получилось расшифровать голосовое. Напишите задачу текстом."), m.message_id).then(() => null);
|
||||
@ -641,7 +654,7 @@ export function createBot(o: BotOptions) {
|
||||
}
|
||||
|
||||
async function onVoice(user: User, m: TgMessage) {
|
||||
const text = await voiceText(m);
|
||||
const text = await voiceText(user, m);
|
||||
if (text) await onPlainText(user, m.chat.id, text, true);
|
||||
}
|
||||
|
||||
@ -677,7 +690,7 @@ export function createBot(o: BotOptions) {
|
||||
if (text.startsWith("/")) return closeFeedbackMode(db, user.id).then(() => "pass" as const);
|
||||
let said = text || m.caption?.trim() || "";
|
||||
if (!said && (m.voice || m.audio)) {
|
||||
const heard = await voiceText(m);
|
||||
const heard = await voiceText(user, m);
|
||||
if (!heard) return "done";
|
||||
said = heard;
|
||||
}
|
||||
@ -701,6 +714,15 @@ export function createBot(o: BotOptions) {
|
||||
return "done";
|
||||
}
|
||||
|
||||
/** PEP-197: the owner decides on stories the factory suggested. */
|
||||
async function onProposalButton(user: User, c: TgCallbackQuery, parts: string[]): Promise<string> {
|
||||
const ids = (parts[1] ?? "").split(",").map(Number).filter((n) => Number.isInteger(n) && n > 0);
|
||||
const choice = parts[2];
|
||||
if (choice !== "do" && choice !== "no" && choice !== "important" && choice !== "none") return tr("Неизвестная кнопка");
|
||||
const n = await decideProposals(db, user, ids, choice);
|
||||
return choice === "do" || choice === "important" ? tr("Принято, задач: {n}", { n }) : tr("Отклонено: {n}", { n });
|
||||
}
|
||||
|
||||
/** A superadmin's buttons under a report: `f:<id>:o<N>` (a story from option N), `dup`, `no`. */
|
||||
async function onFeedbackButton(user: User, c: TgCallbackQuery, parts: string[]): Promise<string> {
|
||||
const id = Number(parts[1]);
|
||||
@ -838,7 +860,7 @@ export function createBot(o: BotOptions) {
|
||||
[
|
||||
tr("Группа связана с {name} ✅", { name }),
|
||||
"",
|
||||
tr("Сюда будут приходить события и вопросы агентов, треды — цепочками ответов. Ответьте <b>реплаем</b> — сообщение уйдёт в тред (в переписке по задаче — агенту). Отвечать могут те, кто привязал Telegram в Peppa FACTORY и имеет доступ к проекту. /help — команды."),
|
||||
tr("Сюда будут приходить события и вопросы агентов, треды — цепочками ответов. Ответьте <b>реплаем</b> — сообщение уйдёт в тред (в переписке по задаче — агенту). Отвечать могут те, кто привязал Telegram в FORGE и имеет доступ к проекту. /help — команды."),
|
||||
].join("\n"),
|
||||
);
|
||||
return "done";
|
||||
@ -851,7 +873,7 @@ export function createBot(o: BotOptions) {
|
||||
if (!m.reply_to_message && !text.startsWith("/")) return "ignored";
|
||||
const user = await telegramAccountUser(db, m.from.id);
|
||||
if (!user || !(await mayWriteChat(db, user, chat))) {
|
||||
await reply(m.chat.id, user ? tr("У вас нет доступа к этому чату.") : tr("Не нашёл вас в Peppa FACTORY — привяжите Telegram: {url}/settings → Telegram.", { url: esc(o.webUrl) }), m.message_id);
|
||||
await reply(m.chat.id, user ? tr("У вас нет доступа к этому чату.") : tr("Не нашёл вас в FORGE — привяжите Telegram: {url}/settings → Telegram.", { url: esc(o.webUrl) }), m.message_id);
|
||||
return "done";
|
||||
}
|
||||
enterActor({ kind: "user", userId: user.id, channel: "telegram" });
|
||||
@ -912,7 +934,7 @@ export function createBot(o: BotOptions) {
|
||||
// PEP-143: «Сообщить о проблеме».
|
||||
if (/^\/(problem|feedback)\b/.test(text)) {
|
||||
await openFeedbackMode(db, user.id);
|
||||
await reply(m.chat.id, [tr("Опишите, что случилось, одним сообщением — текстом, фото экрана с подписью или голосом."), tr("Мы передадим это тем, кто делает Peppa FACTORY.")].join("\n"));
|
||||
await reply(m.chat.id, [tr("Опишите, что случилось, одним сообщением — текстом, фото экрана с подписью или голосом."), tr("Мы передадим это тем, кто делает FORGE.")].join("\n"));
|
||||
return "done";
|
||||
}
|
||||
// A superadmin pressed «Не исправлять»: this message is the reason.
|
||||
@ -944,7 +966,7 @@ export function createBot(o: BotOptions) {
|
||||
return "done";
|
||||
}
|
||||
if (pictureOf(m)) {
|
||||
await reply(m.chat.id, tr("Чтобы сообщить о проблеме в Peppa FACTORY, сначала отправьте /problem, а потом фото."), m.message_id);
|
||||
await reply(m.chat.id, tr("Чтобы сообщить о проблеме в FORGE, сначала отправьте /problem, а потом фото."), m.message_id);
|
||||
return "done";
|
||||
}
|
||||
if (!text || text.startsWith("/")) {
|
||||
@ -956,6 +978,14 @@ export function createBot(o: BotOptions) {
|
||||
return "done";
|
||||
}
|
||||
|
||||
async function onDelayButton(user: User, data: string): Promise<string> {
|
||||
const b = parseDelayCallback(data);
|
||||
if (!b || !(await isSuperadmin(db, user))) return tr("Неизвестная кнопка");
|
||||
const projectId = b.scope.projectId ?? (b.scope.taskId != null ? (await resolveTaskById(db, b.scope.taskId).catch(() => null))?.project.id : null);
|
||||
if (projectId == null) return tr("Задача не найдена");
|
||||
return delayAction(db, { projectId, taskId: b.scope.taskId }, b.reason, b.action);
|
||||
}
|
||||
|
||||
async function onCallback(c: TgCallbackQuery): Promise<"done" | "ignored"> {
|
||||
let user = c.message ? await telegramUser(db, c.message.chat.id, c.from.id) : null;
|
||||
if (!user && c.message && c.message.chat.type !== "private") {
|
||||
@ -976,6 +1006,26 @@ export function createBot(o: BotOptions) {
|
||||
await api.answerCallbackQuery(c.id, toast.slice(0, 190)).catch((e) => log(`answerCallbackQuery: ${e.message}`));
|
||||
return "done";
|
||||
}
|
||||
// PEP-197: «Делать» / «Не надо» under the acceptance agent's message: `p:<ids>:do|no|important|none`.
|
||||
if (parts[0] === "p") {
|
||||
const toast = await onProposalButton(user, c, parts).catch((e) => (e instanceof PeppaError ? e.message : (log(`proposal: ${(e as Error).stack ?? e}`), tr("Ошибка"))));
|
||||
await api.answerCallbackQuery(c.id, toast.slice(0, 190)).catch((e) => log(`answerCallbackQuery: ${e.message}`));
|
||||
return "done";
|
||||
}
|
||||
// PEP-209: the superadmin's buttons on a delay message: `pd:<t|p><id>:<reason>:r|v|x`.
|
||||
if (parts[0] === "pd") {
|
||||
const toast = await onDelayButton(user, c.data ?? "").catch((e) => (e instanceof PeppaError ? e.message : (log(`delay: ${(e as Error).stack ?? e}`), tr("Ошибка"))));
|
||||
wakeOutbox?.();
|
||||
await api.answerCallbackQuery(c.id, toast.slice(0, 190)).catch((e) => log(`answerCallbackQuery: ${e.message}`));
|
||||
return "done";
|
||||
}
|
||||
// PEP-259: the owner's answer to «агенты давно не пользуются разрешением — снять?»: `cg:<grantId>:r|k`.
|
||||
if (parts[0] === "cg") {
|
||||
const b = parseIdleGrantCallback(c.data ?? "");
|
||||
const toast = b ? await decideIdleGrant(db, user.id, b.grantId, b.decision).catch((e) => (e instanceof PeppaError ? e.message : (log(`idle grant: ${(e as Error).stack ?? e}`), tr("Ошибка")))) : tr("Неизвестная кнопка");
|
||||
await api.answerCallbackQuery(c.id, toast.slice(0, 190)).catch((e) => log(`answerCallbackQuery: ${e.message}`));
|
||||
return "done";
|
||||
}
|
||||
if (parts[0] === "f") {
|
||||
const toast = await onFeedbackButton(user, c, parts).catch((e) => (log(`feedback: ${(e as Error).stack ?? e}`), tr("Ошибка")));
|
||||
wakeOutbox?.();
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
// Telegram message texts and buttons for PM questions. HTML parse mode.
|
||||
import { questionIsFreeText, questionText, questionType, splitForDisplay, stripServiceBlocks, userText, type Question, type 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";
|
||||
|
||||
@ -11,9 +11,12 @@ const KIND: Record<Question["kind"], string> = {
|
||||
approval: tr("📝 Нужно одобрение плана"),
|
||||
question: tr("❓ Вопрос"),
|
||||
permission: tr("🔐 Нужно разрешение"),
|
||||
attention: 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[][];
|
||||
@ -22,7 +25,7 @@ export interface Rendered {
|
||||
// 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; /** 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 },
|
||||
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 ? tr("Агент №{id}", { id: q.sessionId }) : tr("Обновления продукта"))) + "</b>", ctx.taskTitle ? `<i>${asIs(esc(clip(ctx.taskTitle, 80)))}</i>` : null]
|
||||
.filter(Boolean)
|
||||
@ -32,8 +35,11 @@ export function renderQuestion(
|
||||
// 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 body = esc(clip(shown.main, 3300));
|
||||
const lines = [head, KIND[q.kind], "", body];
|
||||
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);
|
||||
@ -68,6 +74,7 @@ export function renderQuestion(
|
||||
if (s.status === "rate_limited" && s.subscriptionId != null) buttons.push([{ text: tr("🙋 Попросить подписку у администратора"), callback_data: `s:${s.id}:ask` }]);
|
||||
}
|
||||
}
|
||||
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` }]);
|
||||
|
||||
@ -50,7 +50,7 @@ export interface InlineButton {
|
||||
}
|
||||
|
||||
const TG_TEXT_MAX = 4096;
|
||||
const TG_CLIP_NOTE_TEXT = tr("(полностью — на сайте Peppa FACTORY)");
|
||||
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. */
|
||||
|
||||
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"] }
|
||||
@ -26,7 +26,11 @@ import {
|
||||
type IncidentPolicy,
|
||||
getUser,
|
||||
isSuperadmin,
|
||||
getDirectOrigins,
|
||||
setDirectOrigins,
|
||||
setUserDisabled,
|
||||
setSuperadmin,
|
||||
mergeAccounts,
|
||||
NOTIFY_EVENTS,
|
||||
defaultPrefs,
|
||||
deletePushSubscription,
|
||||
@ -53,6 +57,9 @@ import {
|
||||
setTaskBudget,
|
||||
type Budget,
|
||||
setProjectSecret,
|
||||
setSecretAudience,
|
||||
secretToConnection,
|
||||
setAgentSecretsEnabled,
|
||||
setNeedDone,
|
||||
removeNeed,
|
||||
deleteProjectSecret,
|
||||
@ -62,11 +69,12 @@ import {
|
||||
checkGiteaBotToken,
|
||||
setUiMode,
|
||||
} from "@peppa/core";
|
||||
import { checkConnection, createConnection, decideIdleGrant, deleteConnection, DEFAULT_GRANT_TERM, extendGrant, grantConnection, isGatewayProtocol, isGrantTerm, replaceConnectionSecret, resetHostKey, revokeConnection, revokeGrant, setConnectionIdleHours, type CatalogAuth, type ConnectionCheckResult, type GrantMode, type GrantTerm } from "@peppa/core";
|
||||
import { attachmentLabel, fixFeedback, linkAttachments, linkFeedback, parseAttachmentIds, rejectFeedback, restoreProject } from "@peppa/core";
|
||||
import { deleteProject } from "@peppa/runner";
|
||||
import { deleteProject, decideProposals, mergeProposals } from "@peppa/runner";
|
||||
import { bugsinkFromEnv } from "@peppa/bugsink";
|
||||
import { loadEnv } from "@peppa/shared";
|
||||
import { pauseProject, resumeProject, acceptStory, autoPublish, fixStory, budgetChanged, resolveTaskById, deployProd, bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, grantRepoAccess, moveTask, provisionProjectOnce, projectNamespace, setProjectVisibility, shareProject, unshareProject, type BoardColumn, resumeSession, sendToSession, syncSessionAttachments, startSession, stopSession, type Provider, startFreeRunner, renameRunner, promoteRunner, queueTaskOnRunner, managesProject, saveAgentsMd, cancelOwnLogin, finishOwnClaudeLogin, connectOwnSubscription, removeOwnSubscription, type OwnSubscriptionKind, chooseSharedSubscription, requestSubscription } from "@peppa/runner";
|
||||
import { pauseProject, resumeProject, acceptAll, acceptStory, autoPublish, fixStory, confirmTaskDecision, changeTaskDecision, undoSplit, budgetChanged, resolveTaskById, deployProd, bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, grantRepoAccess, moveTask, provisionProjectOnce, projectNamespace, setProjectVisibility, shareProject, unshareProject, type BoardColumn, resumeSession, sendToSession, syncSessionAttachments, startSession, stopSession, type Provider, startFreeRunner, renameRunner, promoteRunner, queueTaskOnRunner, managesProject, saveAgentsMd, cancelOwnLogin, finishOwnClaudeLogin, connectOwnSubscription, removeOwnSubscription, type OwnSubscriptionKind, chooseSharedSubscription, requestSubscription } from "@peppa/runner";
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { redirect } from "next/navigation";
|
||||
import { asWebActor, requireUser, words } from "@/lib/auth";
|
||||
@ -202,6 +210,28 @@ export async function acceptStoryAction(f: FormData) {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* PEP-209: «Принять» / «Принять всё» on the acceptance page — one by one, a failure of one doesn't
|
||||
* stop the others; the page shows the result («Принято 6, на доработке 1…»).
|
||||
*/
|
||||
export async function acceptAllAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
const key = str(f, "project");
|
||||
const base = `/p/${encodeURIComponent(key)}/accept`;
|
||||
await attempt(f, async () => {
|
||||
const refs = [];
|
||||
for (const k of f.getAll("taskKey").map(String)) {
|
||||
const ref = await resolveTask(db, k).catch(() => null);
|
||||
if (!ref || ref.project.key !== key) continue;
|
||||
await projectForUser(db, user.id, ref.project.id);
|
||||
if (ref.task.status === "review") refs.push(ref);
|
||||
}
|
||||
if (!refs.length) throw new PeppaError(m("Принимать нечего: задачи уже приняты или вернулись в работу"));
|
||||
const r = await acceptAll(db, refs, "web");
|
||||
return `${base}?ok=${r.accepted.length}&pending=${r.pending.length}&failed=${r.failed.length}`;
|
||||
});
|
||||
}
|
||||
|
||||
/** «Поправить» on the story page in «Продакт» mode (PEP-120): the remark goes to the agent, the story — back to work. */
|
||||
export async function fixStoryAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
@ -212,6 +242,21 @@ export async function fixStoryAction(f: FormData) {
|
||||
});
|
||||
}
|
||||
|
||||
/** PEP-198: «Подходит» / «Нужно иначе» / «Не делить» on a decision of «Фабрика решила за вас». */
|
||||
export async function decisionAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const ref = await resolveTask(db, str(f, "taskKey"));
|
||||
await projectForUser(db, user.id, ref.project.id);
|
||||
const id = Number(str(f, "id"));
|
||||
const choice = str(f, "choice");
|
||||
if (choice === "confirm") await confirmTaskDecision(db, ref, id, user);
|
||||
else if (choice === "unsplit") await undoSplit(db, ref, id, user);
|
||||
else if (choice === "change") await changeTaskDecision(db, ref, id, String(f.get("how") ?? ""), user);
|
||||
else throw new PeppaError(m("Эта кнопка уже не работает. Обновите страницу."));
|
||||
});
|
||||
}
|
||||
|
||||
/** PEP-67: a superadmin may pick a pool or tick subscriptions; otherwise the project's pool. */
|
||||
async function launchChoice(f: FormData, user: Awaited<ReturnType<typeof requireUser>>) {
|
||||
const choice = (await isSuperadmin(db, user)) ? str(f, "choice") : "";
|
||||
@ -416,7 +461,7 @@ export async function addProjectMember(f: FormData) {
|
||||
await attempt(f, async () => {
|
||||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||||
const r = await shareProject(db, user, p, str(f, "login"));
|
||||
if (!r.repoAccess) throw new PeppaError((await words()).engineer ? m("{login} добавлен, но доступ к репозиторию в Gitea выдать не удалось — добавьте соавтора в Gitea вручную", { login: r.login }) : m("{login} добавлен, но доступ к коду проекта выдать не удалось. Напишите в поддержку Peppa FACTORY.", { login: r.login }));
|
||||
if (!r.repoAccess) throw new PeppaError((await words()).engineer ? m("{login} добавлен, но доступ к репозиторию в Gitea выдать не удалось — добавьте соавтора в Gitea вручную", { login: r.login }) : m("{login} добавлен, но доступ к коду проекта выдать не удалось. Напишите в поддержку FORGE.", { login: r.login }));
|
||||
});
|
||||
}
|
||||
|
||||
@ -473,6 +518,7 @@ export async function setAutonomyAction(f: FormData) {
|
||||
merge: str(f, "merge") as AutonomySettings["merge"],
|
||||
close: str(f, "close") as AutonomySettings["close"],
|
||||
closeAfterHours: Number(str(f, "closeAfterHours")),
|
||||
acceptOwn: (str(f, "acceptOwn") || undefined) as AutonomySettings["acceptOwn"],
|
||||
idlePush: f.get("idlePush") === "on",
|
||||
idlePushHours: Number(str(f, "idlePushHours")),
|
||||
quietFrom: quiet ? hour("quietFrom") : null,
|
||||
@ -481,6 +527,31 @@ export async function setAutonomyAction(f: FormData) {
|
||||
});
|
||||
}
|
||||
|
||||
/** PEP-197: «Делать» / «Не надо» on a suggested story (board, chat). */
|
||||
export async function proposalAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const choice = str(f, "choice");
|
||||
// PEP-209: «Объединить в одну» — the ticked proposals become one story.
|
||||
if (choice === "merge") {
|
||||
await mergeProposals(db, user, f.getAll("pick").map(Number).filter((n) => Number.isInteger(n) && n > 0));
|
||||
return;
|
||||
}
|
||||
if (choice !== "do" && choice !== "no" && choice !== "important" && choice !== "none") throw new PeppaError(m("Эта кнопка уже не работает."));
|
||||
const ids = str(f, "ids").split(",").map(Number).filter((n) => Number.isInteger(n) && n > 0);
|
||||
await decideProposals(db, user, ids, choice);
|
||||
});
|
||||
}
|
||||
|
||||
/** PEP-197: «Принимать сами» — whose stories are accepted without the owner. */
|
||||
export async function setAcceptOwnAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||||
await setAutonomy(db, p.id, { acceptOwn: str(f, "acceptOwn") as AutonomySettings["acceptOwn"] });
|
||||
});
|
||||
}
|
||||
|
||||
export async function removeProjectMember(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
@ -617,6 +688,17 @@ export async function connectErrorTrackingAction(f: FormData) {
|
||||
});
|
||||
}
|
||||
|
||||
/** PEP-295: the owner's exception — errors of the product go to work without «Делать». */
|
||||
export async function setDirectIncidentsAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||||
if (p.ownerId !== user.id && !(await isSuperadmin(db, user))) throw new PeppaError(m("Это решает владелец проекта."));
|
||||
const rest = (await getDirectOrigins(db, p.id)).filter((o) => o !== "incident");
|
||||
await setDirectOrigins(db, p.id, str(f, "on") === "yes" ? [...rest, "incident"] : rest);
|
||||
});
|
||||
}
|
||||
|
||||
export async function saveIncidentSettings(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
@ -684,6 +766,24 @@ export async function setUserDisabledAction(f: FormData) {
|
||||
});
|
||||
}
|
||||
|
||||
/** PEP-226: appoint or remove a superadmin from «Пользователи». */
|
||||
export async function setSuperadminAction(f: FormData) {
|
||||
await attempt(f, async () => {
|
||||
const admin = asWebActor(await requireSuperadmin());
|
||||
await setSuperadmin(db, admin, Number(str(f, "userId")), str(f, "on") === "1");
|
||||
});
|
||||
}
|
||||
|
||||
/** PEP-204: merge an old account into the person's main one, after the confirmation screen. */
|
||||
export async function mergeAccountsAction(f: FormData) {
|
||||
await attempt(f, async () => {
|
||||
// The actor is set in this frame: set inside requireSuperadmin it would not reach the journal entry.
|
||||
const admin = asWebActor(await requireSuperadmin());
|
||||
await mergeAccounts(db, admin, Number(str(f, "from")), Number(str(f, "to")), { confirm: str(f, "confirm") === "1", confirmAdmin: str(f, "confirmAdmin") === "1" });
|
||||
return "/users";
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
// ── PEP-43: budgets ────────────────────────────────────────────────────────────────
|
||||
const budgetFrom = (f: FormData): Budget => cleanBudget(Object.fromEntries(["minutes", "tokens", "restarts", "costUsd"].map((k) => [k, Number(str(f, k)) || null])));
|
||||
@ -717,7 +817,32 @@ export async function saveProjectSecretAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
// The value is taken as is (no trim): keys may legitimately end with spaces/newlines.
|
||||
await setProjectSecret(db, user.id, Number(str(f, "projectId")), str(f, "name"), String(f.get("value") ?? ""));
|
||||
// PEP-253: «Кому» — only the product by default.
|
||||
await setProjectSecret(db, user.id, Number(str(f, "projectId")), str(f, "name"), String(f.get("value") ?? ""), { agent: str(f, "audience") === "agent" });
|
||||
});
|
||||
}
|
||||
|
||||
// PEP-253: «только продукту» ⇄ «агенту и продукту».
|
||||
export async function setSecretAudienceAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
await setSecretAudience(db, user.id, Number(str(f, "projectId")), str(f, "name"), str(f, "audience") === "agent");
|
||||
});
|
||||
}
|
||||
|
||||
// PEP-253: «Сделать подключением» — a catalog connection with the secret's key, granted to the project.
|
||||
export async function secretToConnectionAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
await secretToConnection(db, user.id, Number(str(f, "projectId")), str(f, "name"));
|
||||
});
|
||||
}
|
||||
|
||||
// PEP-253: «Агенты получают секреты в окружение».
|
||||
export async function setAgentSecretsAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
await setAgentSecretsEnabled(db, user.id, Number(str(f, "projectId")), str(f, "on") === "1");
|
||||
});
|
||||
}
|
||||
|
||||
@ -799,7 +924,7 @@ export async function chooseSharedSubscriptionAction(f: FormData) {
|
||||
export async function requestSubscriptionAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
await requestSubscription(db, user, await projectForUser(db, user.id, Number(str(f, "projectId"))));
|
||||
await requestSubscription(db, user, await projectForUser(db, user.id, Number(str(f, "projectId"))), new Date(), { ahead: str(f, "ahead") === "1" });
|
||||
});
|
||||
}
|
||||
|
||||
@ -844,7 +969,7 @@ export async function saveIntakeSettingsAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||||
await setIntakeSettings(db, p.id, { enabled: f.get("enabled") === "on", waitMin: Number(str(f, "waitMin") || 30) });
|
||||
await setIntakeSettings(db, p.id, { enabled: f.get("enabled") === "on" });
|
||||
});
|
||||
}
|
||||
|
||||
@ -888,3 +1013,127 @@ export async function rejectFeedbackAction(f: FormData) {
|
||||
await rejectFeedback(db, user, Number(str(f, "feedbackId")), str(f, "reason") || null);
|
||||
});
|
||||
}
|
||||
|
||||
// PEP-234 Access Hub: the user's own connections. Every core function checks the owner itself.
|
||||
// PEP-249: catalog cards, a key check right after saving, read / write modes.
|
||||
const checkWord = (r: ConnectionCheckResult | null) => (!r ? "down" : r.reachableOnly ? "reachable" : r.status);
|
||||
const AUTH_KINDS: CatalogAuth[] = ["bearer", "header", "query", "basic"];
|
||||
|
||||
// PEP-251: the form fields of a database / server / storage / mailbox (never the secret).
|
||||
const PROTOCOL_FIELDS = ["host", "port", "database", "user", "tls", "root", "hostKey", "endpoint", "region", "bucket", "prefix", "accessKeyId", "imapHost", "imapPort", "smtpHost", "smtpPort", "from"];
|
||||
|
||||
export async function createConnectionAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const protocol = str(f, "protocol");
|
||||
if (isGatewayProtocol(protocol)) {
|
||||
const config = Object.fromEntries(PROTOCOL_FIELDS.filter((k) => f.has(k)).map((k) => [k, str(f, k)]));
|
||||
// An SSH key keeps its line breaks; a password is one line.
|
||||
const raw = String(f.get("secret") ?? "");
|
||||
const secret = protocol === "ssh" && raw.includes("-----BEGIN") ? `${raw.replace(/\r\n/g, "\n").trim()}\n` : raw.trim();
|
||||
const c = await createConnection(db, user.id, { protocol, name: str(f, "name"), config, secret });
|
||||
const r = await checkConnection(db, user.id, c.id).catch(() => null);
|
||||
return `/connections?created=${c.id}&check=${checkWord(r)}#c${c.id}`;
|
||||
}
|
||||
const kind = str(f, "authKind") as CatalogAuth;
|
||||
const c = await createConnection(db, user.id, {
|
||||
catalogId: str(f, "catalogId") || null,
|
||||
name: str(f, "name"),
|
||||
baseUrl: str(f, "baseUrl"),
|
||||
secret: String(f.get("secret") ?? "").trim(),
|
||||
authKind: AUTH_KINDS.includes(kind) ? kind : "bearer",
|
||||
authHeader: str(f, "authHeader") || null,
|
||||
});
|
||||
const r = await checkConnection(db, user.id, c.id).catch(() => null);
|
||||
return `/connections?created=${c.id}&check=${checkWord(r)}#c${c.id}`;
|
||||
});
|
||||
}
|
||||
|
||||
export async function checkConnectionAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const id = Number(str(f, "connectionId"));
|
||||
const r = await checkConnection(db, user.id, id);
|
||||
return `/connections?checked=${id}&check=${checkWord(r)}#c${id}`;
|
||||
});
|
||||
}
|
||||
|
||||
export async function replaceConnectionSecretAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const id = Number(str(f, "connectionId"));
|
||||
const raw = String(f.get("secret") ?? "");
|
||||
await replaceConnectionSecret(db, user.id, id, raw.includes("-----BEGIN") ? `${raw.replace(/\r\n/g, "\n").trim()}\n` : raw.trim());
|
||||
const r = await checkConnection(db, user.id, id).catch(() => null);
|
||||
return `/connections?checked=${id}&check=${checkWord(r)}#c${id}`;
|
||||
});
|
||||
}
|
||||
|
||||
export async function resetHostKeyAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const id = Number(str(f, "connectionId"));
|
||||
await resetHostKey(db, user.id, id);
|
||||
const r = await checkConnection(db, user.id, id).catch(() => null);
|
||||
return `/connections?checked=${id}&check=${checkWord(r)}#c${id}`;
|
||||
});
|
||||
}
|
||||
|
||||
export async function revokeConnectionAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const id = Number(str(f, "connectionId"));
|
||||
const r = await revokeConnection(db, user.id, id);
|
||||
// PEP-252: the service didn't confirm the revoke of a sign-in — tell the owner to do it there too.
|
||||
if (r.remote === "failed") return `/connections?revoked=${id}&remote=failed#c${id}`;
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteConnectionAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
await deleteConnection(db, user.id, Number(str(f, "connectionId")));
|
||||
return "/connections";
|
||||
});
|
||||
}
|
||||
|
||||
export async function grantConnectionAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const agent = str(f, "agentId");
|
||||
const mode = (k: string): GrantMode => (["auto", "ask"].includes(str(f, k)) ? (str(f, k) as GrantMode) : "off");
|
||||
await grantConnection(db, user.id, Number(str(f, "connectionId")), { projectId: Number(str(f, "projectId")), agentId: agent ? Number(agent) : null, readMode: mode("readMode"), writeMode: mode("writeMode"), operations: String(f.get("operations") ?? ""), term: isGrantTerm(str(f, "term")) ? (str(f, "term") as GrantTerm) : DEFAULT_GRANT_TERM });
|
||||
});
|
||||
}
|
||||
|
||||
/** PEP-259 «Продлить»: the same term again from now. */
|
||||
export async function extendGrantAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
await extendGrant(db, user.id, Number(str(f, "grantId")));
|
||||
});
|
||||
}
|
||||
|
||||
/** PEP-259: the owner's answer to «агенты давно не пользуются — снять?»: «Снять» / «Оставить». */
|
||||
export async function decideIdleGrantAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
await decideIdleGrant(db, user.id, Number(str(f, "grantId")), str(f, "decision") === "revoke" ? "revoke" : "keep");
|
||||
});
|
||||
}
|
||||
|
||||
/** PEP-259: «Спрашивать о разрешении без дела через …» of one connection ("" — platform default). */
|
||||
export async function setConnectionIdleAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const v = str(f, "idleHours");
|
||||
await setConnectionIdleHours(db, user.id, Number(str(f, "connectionId")), v === "" ? null : Number(v));
|
||||
});
|
||||
}
|
||||
|
||||
export async function revokeGrantAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
await revokeGrant(db, user.id, Number(str(f, "grantId")));
|
||||
});
|
||||
}
|
||||
|
||||
@ -1,16 +1,20 @@
|
||||
import Link from "next/link";
|
||||
import { notFound } from "next/navigation";
|
||||
import { Bot, Hash, Link2, MessagesSquare, Send, Unlink, User as UserIcon } from "lucide-react";
|
||||
import { analystPending, attachmentsByMessage, 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 { 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 } from "@peppa/shared/i18n";
|
||||
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 { ago, Empty, Flash, linkify, PageHeader, StatusBadge } from "@/components/common";
|
||||
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";
|
||||
@ -21,6 +25,7 @@ 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 };
|
||||
@ -47,13 +52,15 @@ export default async function ChatPage({ params, searchParams }: { params: Promi
|
||||
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 = !master && rawList === "1";
|
||||
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 threads = master ? null : await projectThreadList(db, user, chat, { q });
|
||||
const rows = threads ? [...threads.waiting, ...threads.working, ...threads.done] : [];
|
||||
const messages = master
|
||||
? await masterFeed(db, user, { limit: 150 })
|
||||
@ -189,101 +196,161 @@ export default async function ChatPage({ params, searchParams }: { params: Promi
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<Workspace aside={aside}>
|
||||
<LiveRefresh scope="chats" />
|
||||
<Flash error={error} />
|
||||
<PageHeader title={t("Чаты")}>
|
||||
{master
|
||||
? t("Все события по вашим проектам — журнал, справочно. Чтобы ответить агенту или написать аналитику, откройте чат проекта.")
|
||||
: t("Чат с аналитиком — ИИ-агентом вашего проекта. Спросите, что сделано и где это посмотреть, или опишите идею: он уточнит, предложит {tasks} и заведёт их в бэклог, когда вы скажете.", { tasks: w.task("accPl") })}
|
||||
</PageHeader>
|
||||
// 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}` };
|
||||
});
|
||||
|
||||
<nav className="mb-4 flex flex-wrap gap-1.5" aria-label={t("Чаты")}>
|
||||
<Link href="/chats" className="flex items-center gap-1.5 rounded-md border bg-card px-2.5 py-1 text-sm text-muted-foreground hover:border-muted-foreground hover:text-foreground hover:no-underline">
|
||||
{t("← Обзор")}
|
||||
</Link>
|
||||
{/* PEP-117: projects first (by name), the journal of all events last. */}
|
||||
{[...list.filter((c) => c.kind === "project"), ...list.filter((c) => c.kind === "master")].map((c) => (
|
||||
<Link
|
||||
key={c.id}
|
||||
href={`/chats/${c.slug}`}
|
||||
aria-current={c.id === chat.id ? "page" : undefined}
|
||||
title={t.text(c.title)}
|
||||
className={cn(
|
||||
"flex items-center gap-1.5 rounded-md border bg-card px-2.5 py-1 text-sm text-muted-foreground hover:border-muted-foreground hover:text-foreground hover:no-underline",
|
||||
c.id === chat.id && "border-primary/60 bg-primary/10 text-foreground",
|
||||
)}
|
||||
>
|
||||
{c.kind === "master" ? <MessagesSquare className="size-3.5" /> : <Hash className="size-3.5" />}
|
||||
<span>{c.kind === "master" ? t("Все события") : c.title.includes(" · ") ? c.title.split(" · ").slice(1).join(" · ") : c.slug}</span>
|
||||
{c.tgTitle && <Send className="size-3 text-info" aria-label={t("связан с Telegram")} />}
|
||||
{(unread.get(c.id) ?? 0) > 0 && c.id !== chat.id && (
|
||||
<span className="rounded-full bg-info px-1.5 font-mono text-[11px] leading-4 font-semibold text-background tabular-nums" title={t("новые сообщения в обсуждении")}>
|
||||
{unread.get(c.id)}
|
||||
</span>
|
||||
)}
|
||||
{c.open > 0 && <span className="rounded-full bg-primary px-1.5 font-mono text-[11px] leading-4 font-semibold text-primary-foreground tabular-nums" title={t("вопросы агентов")}>{c.open}</span>}
|
||||
</Link>
|
||||
))}
|
||||
</nav>
|
||||
|
||||
<div className={cn("grid gap-4", !master && "lg:grid-cols-[280px_minmax(0,1fr)] xl:grid-cols-[320px_minmax(0,1fr)]")}>
|
||||
{threads && (
|
||||
<div className={cn("min-w-0", !showList && "max-lg:hidden")}>
|
||||
<ChatThreadList base={base} list={threads} active={thread ?? null} discussion={discussion} feed={!discussion && thread === undefined} raw={rawThread ?? null} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
<section className={cn("flex min-w-0 flex-col gap-3", showList && "max-lg:hidden")} aria-label={t("Сообщения")}>
|
||||
{!master && (
|
||||
<Link href={url({ thread: rawThread, list: true })} className="self-start rounded-md border bg-card px-2.5 py-1 text-sm text-muted-foreground hover:text-foreground hover:no-underline lg:hidden">
|
||||
{t("← К списку")}
|
||||
</Link>
|
||||
)}
|
||||
{current && (
|
||||
<div className="flex flex-wrap items-center gap-2 text-sm">
|
||||
<span className="font-medium">🧵 {t.text(current)}</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>
|
||||
)}
|
||||
{messages.length === 0 ? (
|
||||
const feed = ordered.length === 0 ? (
|
||||
<Empty>{discussion ? t("Напишите, что хотите узнать или сделать, — аналитик ответит здесь же. Например: «Что сейчас в работе?» или «Хочу страницу с отзывами клиентов».") : master ? t("Пока тихо: здесь появятся вопросы агентов, сбои и обновления ваших проектов.") : thread === undefined ? t("Сообщений пока нет: они появятся, когда агенты возьмутся за {tasks}.", { tasks: w.task("accPl") }) : t("В этом треде пока пусто.")}</Empty>
|
||||
) : (
|
||||
<ol className="m-0 flex list-none flex-col gap-2 p-0">
|
||||
{messages.map((m) => (
|
||||
<li key={m.id}>
|
||||
<MessageItem files={files.get(m.id)} m={m} q={m.question ? qById.get(m.question.id) : undefined} back={here} showThread={!discussion && thread === undefined} masterView={master} mine={discussion && m.authorUserId === user.id} />
|
||||
</li>
|
||||
))}
|
||||
<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>
|
||||
)}
|
||||
{typing && (
|
||||
<p className="m-0 flex items-center gap-2 text-sm text-muted-foreground" aria-live="polite">
|
||||
<AgentBadge name={t("Аналитик")} /> <span className="animate-pulse">{t("печатает…")}</span>
|
||||
</p>
|
||||
{master && superadmin && (
|
||||
<Link href="/journal" className="text-sm">{t("Полный журнал платформы →")}</Link>
|
||||
)}
|
||||
{master || (!discussion && thread === undefined) ? (
|
||||
<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} />
|
||||
</>
|
||||
) : (
|
||||
<form action={postChatAction} className="sticky bottom-16 flex flex-col gap-2 rounded-lg border bg-card p-3 md:bottom-3">
|
||||
<Hidden fields={{ chatId: chat.id, thread: thread ?? "", back: here }} />
|
||||
<Textarea id="chat-text" name="text" rows={2} maxLength={60000} placeholder={placeholder} aria-label={t("Сообщение")} />
|
||||
{chat.projectId && <AttachField projectId={chat.projectId} target="chat-text" />}
|
||||
<div className="flex items-center gap-2">
|
||||
<Dictate target="chat-text" compact />
|
||||
<span className="text-xs text-muted-foreground">{discussion ? t("отвечает аналитик на подписке проекта · переписку видят участники проекта") : thread ? t("в тред") : master ? t("в мастер-чат") : t("в канал")}{chat.tgTitle ? " · " + t("и в Telegram «{title}»", { title: chat.tgTitle }) : ""}</span>
|
||||
<Button size="sm" className="ml-auto">
|
||||
<Send />
|
||||
{t("Отправить")}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
<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>
|
||||
@ -291,6 +358,57 @@ export default async function ChatPage({ params, searchParams }: { params: Promi
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
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;
|
||||
@ -301,18 +419,23 @@ 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 }: { files?: AttachmentView[]; m: ChatMessageView; q?: { q: Question; taskStatus: string | null; taskKey: string | null }; back: string; showThread: boolean; masterView: boolean; mine?: boolean }) {
|
||||
async function MessageItem({ m, q, back, showThread, masterView, mine = false, files, agentName, superadmin, gitea }: { files?: AttachmentView[]; m: ChatMessageView; q?: { q: Question; taskStatus: string | null; taskKey: string | null }; back: string; showThread: boolean; masterView: boolean; mine?: boolean; agentName: string | null; superadmin: boolean; gitea: string }) {
|
||||
const t = await getT();
|
||||
const where = (showThread || masterView) && (m.threadTitle || (masterView && m.projectKey));
|
||||
// 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">
|
||||
{m.authorKind === "user" ? <UserIcon className="size-3.5" /> : m.authorKind === "agent" ? (m.authorLogin ? null : <Bot className="size-3.5" />) : <MessagesSquare className="size-3.5" />}
|
||||
{m.authorKind === "agent" && m.authorLogin ? (
|
||||
<AgentBadge name={t.role(m.authorLogin)} className="text-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">{m.authorKind === "user" ? (mine ? t("вы") : (m.authorLogin ?? "?")) : m.authorKind === "agent" ? t("агент") : PRODUCT_NAME}</span>
|
||||
<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 && (
|
||||
@ -329,16 +452,16 @@ async function MessageItem({ m, q, back, showThread, masterView, mine = false, f
|
||||
return (
|
||||
<div className="flex flex-col gap-1">
|
||||
{head}
|
||||
<QuestionCard q={q.q} taskKey={q.taskKey} taskStatus={q.taskStatus} back={back} compact />
|
||||
<QuestionCard q={q.q} taskKey={q.taskKey} taskStatus={q.taskStatus} back={back} compact clean={!superadmin} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
// 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" ? t.role(m.text) : m.text, more: null } : splitForDisplay(t.text(m.text), m.details ? t.text(m.details) : null);
|
||||
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", m.kind === "user" && "border-primary/30 bg-primary/5", m.kind === "system" && "border-dashed bg-transparent")}>
|
||||
<article className={cn("flex flex-col gap-1 rounded-lg border bg-card px-3 py-2", mine && "border-primary/30 bg-primary/10", m.kind === "system" && "border-dashed bg-transparent")}>
|
||||
{head}
|
||||
<p data-message-main className="m-0 text-sm break-words whitespace-pre-wrap">{linkify(shown.main)}</p>
|
||||
{shown.more && (
|
||||
@ -348,13 +471,14 @@ async function MessageItem({ m, q, back, showThread, masterView, mine = false, f
|
||||
</details>
|
||||
)}
|
||||
<Attachments files={files} />
|
||||
{m.url && (
|
||||
<a href={m.url} target="_blank" rel="noreferrer" className="truncate text-xs">
|
||||
{m.url}
|
||||
{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 && (
|
||||
{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" && (
|
||||
@ -372,6 +496,25 @@ async function MessageItem({ m, q, back, showThread, masterView, mine = false, f
|
||||
</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">
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
"use server";
|
||||
// «Чаты» (PEP-62): a message into a chat/thread, Telegram group link/unlink. Access — chatForUser.
|
||||
|
||||
import { parseAttachmentIds, chatForUser, createChatLinkCode, isSuperadmin, PeppaError, unlinkChat } from "@peppa/core";
|
||||
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";
|
||||
@ -36,12 +36,24 @@ export async function postChatAction(f: FormData) {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 (choice !== "task" && choice !== "answer" && choice !== "create" && choice !== "cancel") throw new PeppaError(m("Эта кнопка уже не работает. Напишите сообщение ещё раз."));
|
||||
if (!["task", "answer", "create", "cancel", "stories"].includes(choice)) throw new PeppaError(m("Эта кнопка уже не работает. Напишите сообщение ещё раз."));
|
||||
await resolveChatOffer(db, user, Number(str(f, "messageId")), choice as ChatOfferChoice);
|
||||
});
|
||||
}
|
||||
@ -51,7 +63,7 @@ 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 пока не настроен. Напишите в поддержку Peppa FACTORY."));
|
||||
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.
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
import Link from "next/link";
|
||||
import { ArrowRight, MessagesSquare } from "lucide-react";
|
||||
import { chatOverview, syncChats } from "@peppa/core";
|
||||
import { chatOverview, isRoleName, syncChats } from "@peppa/core";
|
||||
import { LiveRefresh } from "@/components/LiveRefresh";
|
||||
import { AgentBadge } from "@/components/AgentBadge";
|
||||
import { QuestionCard } from "@/components/cards";
|
||||
@ -13,7 +13,7 @@ import { getT } from "@/lib/i18n";
|
||||
|
||||
export async function generateMetadata() {
|
||||
const t = await getT();
|
||||
return { title: t("Чаты — Peppa FACTORY") };
|
||||
return { title: t("Чаты — FORGE") };
|
||||
}
|
||||
|
||||
|
||||
@ -60,7 +60,7 @@ export default async function Chats({ searchParams }: { searchParams: Promise<{
|
||||
{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={t.role(c.last.who)} /> : <span>{c.last.mine ? t("вы") : c.last.who}</span>}
|
||||
{c.last.agent ? <AgentBadge name={c.last.who} role={isRoleName(c.last.who)} /> : <span>{c.last.mine ? t("вы") : c.last.who}</span>}
|
||||
<span>· {ago(c.last.at, 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>
|
||||
|
||||
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>
|
||||
);
|
||||
}
|
||||
@ -1,7 +1,7 @@
|
||||
import Link from "next/link";
|
||||
import { notFound } from "next/navigation";
|
||||
import { Gauge } from "lucide-react";
|
||||
import { isSuperadmin, platformDashboard, type DashboardCounts } from "@peppa/core";
|
||||
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";
|
||||
@ -14,7 +14,7 @@ import { m } from "@peppa/shared/i18n";
|
||||
|
||||
export async function generateMetadata() {
|
||||
const t = await getT();
|
||||
return { title: t("Дашборд — Peppa FACTORY") };
|
||||
return { title: t("Дашборд — FORGE") };
|
||||
}
|
||||
|
||||
const SIGN_IN: Record<string, string> = { egov: "eGov", google: "Google", gitea: "Gitea", local: m("пароль") };
|
||||
@ -54,6 +54,7 @@ export default async function Dashboard() {
|
||||
const t = await getT();
|
||||
const d = await platformDashboard(db);
|
||||
const x = d.totals;
|
||||
const delays = await platformDelayCounts(db);
|
||||
return (
|
||||
<Workspace>
|
||||
<LiveRefresh scope="home" />
|
||||
@ -70,6 +71,12 @@ export default async function Dashboard() {
|
||||
<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>
|
||||
|
||||
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);
|
||||
}
|
||||
@ -33,7 +33,7 @@ export default async function FeedbackPage({ searchParams }: { searchParams: Pro
|
||||
<Workspace>
|
||||
<div className="max-w-3xl">
|
||||
<Flash error={error} />
|
||||
<PageHeader title={t("Обращения")}>{t("Здесь всё, что вы сообщили о проблемах в Peppa FACTORY, и что с этим стало. Новое обращение — кнопка «Сообщить о проблеме» внизу любой страницы.")}</PageHeader>
|
||||
<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">
|
||||
|
||||
@ -16,7 +16,7 @@ import type { Translator } from "@peppa/shared/i18n";
|
||||
|
||||
export async function generateMetadata() {
|
||||
const t = await getT();
|
||||
return { title: t("Gitea — Peppa FACTORY") };
|
||||
return { title: t("Gitea — FORGE") };
|
||||
}
|
||||
|
||||
type Params = { q?: string; show?: string };
|
||||
@ -75,7 +75,7 @@ export default async function GiteaPage({ searchParams }: { searchParams: Promis
|
||||
<Workspace>
|
||||
<div className="max-w-4xl">
|
||||
<PageHeader title={<><GitBranch className="mr-1 inline size-5 text-primary" />Gitea</>}>
|
||||
{t("Git-сервер платформы и репозитории на нём — как их видит бот Peppa FACTORY. Раздел видят только суперадмины.")}
|
||||
{t("Git-сервер платформы и репозитории на нём — как их видит бот FORGE. Раздел видят только суперадмины.")}
|
||||
</PageHeader>
|
||||
|
||||
<Section title={t("Сервер")}>
|
||||
|
||||
@ -1,27 +1,33 @@
|
||||
import Link from "next/link";
|
||||
import { CONNECT_HELP } from "@peppa/core";
|
||||
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 } from "@/lib/i18n";
|
||||
import { getLocale, getT } from "@/lib/i18n";
|
||||
|
||||
/** PEP-135: how to connect Peppa FACTORY to one's own Claude or ChatGPT — step by step; texts live in core/connect-texts.ts. */
|
||||
/** 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>
|
||||
<CopyText value={address} label={t.copy} done={t.copied} />
|
||||
<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) => (
|
||||
|
||||
@ -1,6 +1,8 @@
|
||||
import Link from "next/link";
|
||||
import type { ReactNode } from "react";
|
||||
import { CONNECT_HELP, PRODUCT_HELP } from "@peppa/core";
|
||||
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";
|
||||
@ -28,6 +30,12 @@ const TOOLS: Array<[string, string]> = [
|
||||
["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)")],
|
||||
@ -44,13 +52,13 @@ const CASES: Array<{ title: string; say: string; how: string }> = [
|
||||
{ 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 (только владелец). Участник видит доску и входящие, двигает карточки, отвечает агентам и получает доступ к репозиторию. Тот, кто ещё не входил в Peppa FACTORY, получит приглашение — оно сработает при первом входе") },
|
||||
{ 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; не поднялся — Peppa FACTORY сама откатит и напишет") },
|
||||
{ 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 не в ревью или готово") },
|
||||
@ -101,6 +109,12 @@ async function ProductHelp() {
|
||||
</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>
|
||||
@ -133,9 +147,9 @@ export default async function Help() {
|
||||
return (
|
||||
<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("Понятия Peppa FACTORY, подключение MCP-клиентов и что можно попросить.")}</PageHeader>
|
||||
<PageHeader title={t("Помощь")}>{t("Понятия FORGE, подключение MCP-клиентов и что можно попросить.")}</PageHeader>
|
||||
|
||||
<Section title={t("Как устроена Peppa FACTORY")}>
|
||||
<Section title={t("Как устроена FORGE")}>
|
||||
<ul>
|
||||
<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>
|
||||
@ -144,30 +158,33 @@ export default async function Help() {
|
||||
<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 в сессии на машине Peppa FACTORY: составляет план стори (OpenSpec), реализует, открывает PR и отдаёт стори на ревью."))}</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> — два агента, которые читают новую задачу раньше разработчика. Продакт решает, зачем это и что берём в первую версию (большое делит на несколько стори). Аналитик пишет критерии приёмки и задаёт до трёх вопросов — у каждого есть вариант по умолчанию; не ответите за 30 минут (ночью — до утра), он возьмёт его сам. Их реплики — во вкладке Comments стори и в чате проекта. Включается в «⋯ Настройки проекта → Продакт и аналитик», в новых проектах включено."))}</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 — код только через Peppa FACTORY, а новые проекты создаются в пространстве <m>peppa-bot</m>."))}</li>
|
||||
<li>{rich(t("<b>Раннер</b> — агент, запущенный по стори в tmux на машине Peppa FACTORY. Все раннеры ваших и общих проектов — в разделе <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> — через 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-образе раннера — он видит только свою рабочую копию, работает на подписке из пула проекта и не видит токенов Peppa FACTORY и чужих проектов; хуки, MCP и git идут в Peppa FACTORY через релей и только к репозиторию проекта (PR агент открывает инструментом <code>open_pull_request</code>). «Где запускать раннеры» — Mac Peppa FACTORY или отмеченные хосты: раннер уходит на наименее занятый онлайн-хост, там клонируется рабочая копия, а терминал, ввод и ответы работают как обычно. Хосты подключает суперадмин в разделе «Хосты» (SSH-ключ Peppa FACTORY на хосте, tmux и docker); недоступный хост помечается «офлайн», его раннеры не считаются упавшими."))}</li>
|
||||
<li>{rich(t("<b>Сообщения агента</b> — четырёх типов. <b>Вопрос</b> — нужно ваше решение о продукте: всегда с вариантами ответа кнопками и вариантом по умолчанию; только он попадает в «Вопросы агентов» на Главной и приходит в Telegram как вопрос. <b>Готово</b> — задачу можно принять: приходит только после того, как проверки прошли, со ссылкой на результат. <b>Ход работы</b> — что агент сделал; лежит в «Событиях агентов» в чате проекта и никого не будит. <b>Блокер</b> — агент не может продолжить: если дело в продукте, он спросит вас с вариантами ответа, остальное уходит администраторам фабрики. Кнопки «Продолжай» больше нет: агента, который ждёт проверок, будит сама Peppa FACTORY."))}</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>
|
||||
|
||||
<Section 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>
|
||||
<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>{rich(t("<b>ChatGPT</b>: Settings → Apps & Connectors → Advanced → включить Developer mode → Create: URL выше, авторизация OAuth. Откроется Peppa FACTORY — войдите через eGov и нажмите «Разрешить». В чате включите коннектор Peppa."))}</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 — клиент зарегистрируется сам, вход и согласие на экране Peppa FACTORY."))}</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>
|
||||
@ -205,7 +222,7 @@ export default async function Help() {
|
||||
|
||||
<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>: Peppa FACTORY сама берёт следующую стори из бэклога (сверху по порядку на доске, пропуская стори, которые ждут предшественников; одновременно до N), зелёный PR без конфликтов мержит сама, стори закрывает после мержа; при конфликте агент сам делает rebase. Настройки можно комбинировать: одобрять план каждой стори, мержить сам, но закрывать вручную или «само через N часов без замечаний». Во время лимита подписки диспетчер ничего не запускает и не предлагает. PR, меняющий конвейер, всегда ждёт вашего «Принять». «Принять» мержит PR, Gitea удаляет ветку, рабочая копия проекта подтягивает main."))}
|
||||
{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>
|
||||
<p className="m-0 mt-2 text-muted-foreground">
|
||||
{rich(t("<b>Пауза проекта</b>: «Поставить на паузу» на странице проекта или в «⋯ Настройки проекта → Пауза» останавливает агентов проекта (сделанное сохраняется), новые не запускаются, продакт, аналитик и ревьюер не работают, уведомлений нет — ни в Telegram, ни в браузере, вопросы проекта не показываются в «Ждут вашего ответа». «Продолжить» возвращает остановленных агентов к их задачам; то, что пришло во время паузы, задним числом не рассылается."))}
|
||||
@ -214,19 +231,23 @@ export default async function Help() {
|
||||
|
||||
<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), агент или Peppa FACTORY."))}
|
||||
{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» в журнале сессии. Те же секреты получает и выкаченный продукт (версия для проверки и рабочая) — как переменные окружения с тем же именем; после изменения секрета Peppa FACTORY через пару минут сама перезапускает продукт. Если продукту нужен ключ, агент объявляет это, и на странице проекта в карточке «Ваш продукт» появляется пометка «Работает в демо-режиме» с полем, куда вставить ключ. После каждой выкатки продукт смотрит продакт-агент и пишет в обсуждение проекта, как им пользоваться и что ещё не настоящее. <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>."))}
|
||||
{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 от Peppa FACTORY). Результат виден в карточке стори и во вкладке «PR» («Проверки: 4 из 4 пройдены»). Красная проверка уходит агенту с хвостом лога, после 3 красных прогонов подряд Peppa FACTORY спросит вас. В ревью стори попадает и «Принять» мержит PR только с зелёными проверками и без конфликтов. PR, меняющий конвейер (<m>.gitea/</m>, <m>checks</m>, <m>deploy</m>), сам не мержится никогда."))}
|
||||
{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) стори приходит с незакрытыми замечаниями; если ревьюер упал — с пометкой. Последнее ревью видно в карточке стори.")}
|
||||
@ -236,16 +257,16 @@ export default async function Help() {
|
||||
</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>. Нет здоровой версии для проверки при принятых стори или выкладка упала — Peppa FACTORY сама заводит стори «Продукт должен открываться по ссылке» первой в бэклоге (одна открытая на проект, не чаще раза в сутки). «⋯ Настройки проекта → Показывать всем»: «Сам» — здоровый staging, все стори которого приняты, выкатывается в прод без кнопки; «По кнопке» — как раньше."))}
|
||||
{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 знает о Peppa FACTORY: issue, открытый вами или участником проекта, становится стори в бэклоге (в issue появится ссылка; стори готова — issue закроется), старые открытые issues переносит <m>peppa project import-issues KEY</m>. Комментарий или ревью «нужны изменения» в PR стори уходит её агенту (стори из «Ревью» вернётся в работу), а мерж PR руками в Gitea переводит стори в «Готово»."))}
|
||||
{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("Сама Peppa FACTORY (проект PEP) выкатывается так же по кнопке, но без staging: после зелёных проверок <m>main</m> приходит предложение «Выкатить в прод»; релиз собирается на хосте рядом с работающим, перед миграциями делается копия базы, после перезапуска — проверка здоровья, не прошла — возврат предыдущего релиза."))}
|
||||
{rich(t("Сама FORGE (проект PEP) выкатывается так же по кнопке, но без staging: после зелёных проверок <m>main</m> приходит предложение «Выкатить в прод»; релиз собирается на хосте рядом с работающим, перед миграциями делается копия базы, после перезапуска — проверка здоровья, не прошла — возврат предыдущего релиза."))}
|
||||
</p>
|
||||
</Section>
|
||||
|
||||
@ -272,16 +293,16 @@ export default async function Help() {
|
||||
|
||||
<Section title={t("Обращения")}>
|
||||
<p className="m-0 text-muted-foreground">
|
||||
{t("Кнопка «Сообщить о проблеме» внизу любой страницы — для проблем в самой Peppa FACTORY: текст и до 5 скриншотов (файл, перетаскивание, вставка из буфера); страница, вид, язык, браузер и последние ошибки браузера прикладываются сами. В Telegram — /problem, затем текст, фото с подписью или голосовое. Обращение разбирает агент обратной связи; суперадмин получает разбор с вариантами исправления и решает: завести задачу, связать с существующей или не исправлять. Автор видит статус в разделе «Обращения» и получает сообщение, когда задача принята.")}
|
||||
{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 спросит разрешение) и работают при закрытой вкладке; клик открывает стори. Во вкладке Peppa FACTORY в заголовке и на значке приложения — сколько ждёт вас, при новом вопросе звучит сигнал (если звук включён). Ежедневный дайджест приходит в выбранное время (по умолчанию 09:00): сделано за сутки, в работе, на ревью, ждёт вас, зависло, лимиты; пустой не приходит."))}
|
||||
{rich(t("В <a href=\"/settings#notifications\">Настройках → Уведомления</a> для каждого события (вопросы агентов, готово к ревью, сбои и лимиты, релизы, ошибки из прода, дайджест) выбирается, куда присылать: Telegram и/или браузер. Тихие часы: Telegram приходит без звука, push не показываются. Снятые проекты не присылают ничего — вопросы остаются в вебе. Push в браузере включаются там же кнопкой (Chrome спросит разрешение) и работают при закрытой вкладке; клик открывает стори. Во вкладке FORGE в заголовке и на значке приложения — сколько ждёт вас, при новом вопросе звучит сигнал (если звук включён). Ежедневный дайджест приходит в выбранное время (по умолчанию 09:00): сделано за сутки, в работе, на ревью, ждёт вас, зависло, лимиты; пустой не приходит."))}
|
||||
</p>
|
||||
<p className="m-0 text-muted-foreground">
|
||||
{t("Новости самой Peppa FACTORY — новые версии, падения и перезапуски сервисов, «Дайджест обновлений Peppa FACTORY» (что нового и что происходит сейчас) — идут в Telegram-канал платформы, который настраивает суперадмин в разделе «Платформа». Если он включил рассылку в личные чаты, дайджест обновлений приходит и вам; отключить — строка «Дайджест обновлений Peppa FACTORY» в Настройках → Уведомления.")}
|
||||
{t("Новости самой FORGE — новые версии, падения и перезапуски сервисов, «Дайджест обновлений FORGE» (что нового и что происходит сейчас) — идут в Telegram-канал платформы, который настраивает суперадмин в разделе «Платформа». Если он включил рассылку в личные чаты, дайджест обновлений приходит и вам; отключить — строка «Дайджест обновлений FORGE» в Настройках → Уведомления.")}
|
||||
</p>
|
||||
</Section>
|
||||
</div>
|
||||
|
||||
@ -17,7 +17,7 @@ import { addHostAction, checkHostAction, deleteHostAction, toggleHostAction, upd
|
||||
|
||||
export async function generateMetadata() {
|
||||
const t = await getT();
|
||||
return { title: t("Хосты — Peppa FACTORY") };
|
||||
return { title: t("Хосты — FORGE") };
|
||||
}
|
||||
|
||||
function StatusOf({ h, t }: { h: RunnerHostView; t: Translator }) {
|
||||
@ -41,7 +41,7 @@ function HostFields({ h, t }: { h?: RunnerHostView; t: Translator }) {
|
||||
<Input name="workdir" placeholder="peppa" defaultValue={h?.workdir} className="h-8 font-mono" />
|
||||
</Label>
|
||||
<Label>
|
||||
{t("Адрес Peppa FACTORY для хоста (релей агента)")}
|
||||
{t("Адрес FORGE для хоста (релей агента)")}
|
||||
<Input name="peppaUrl" placeholder={t("как PEPPA_WEB_URL")} defaultValue={h?.peppaUrl ?? ""} className="h-8 font-mono" />
|
||||
</Label>
|
||||
</div>
|
||||
@ -103,11 +103,11 @@ export default async function Hosts({ searchParams }: { searchParams: Promise<{
|
||||
<div className="max-w-3xl">
|
||||
<Flash error={error} />
|
||||
<PageHeader title={<><Server className="mr-1 inline size-5 text-primary" />{t("Хосты")}</>}>
|
||||
{t("Серверы, на которых работают раннеры. Peppa FACTORY заходит на хост по SSH своим ключом и запускает там tmux с агентом в контейнере образа раннера; агент ходит в Peppa FACTORY только через релей. Демона на хосте нет — нужны sshd, tmux и docker. Проект выбирает хосты в «⋯ Настройки проекта → Раннеры». Раздел видят только суперадмины.")}
|
||||
{t("Серверы, на которых работают раннеры. FORGE заходит на хост по SSH своим ключом и запускает там tmux с агентом в контейнере образа раннера; агент ходит в FORGE только через релей. Демона на хосте нет — нужны sshd, tmux и docker. Проект выбирает хосты в «⋯ Настройки проекта → Раннеры». Раздел видят только суперадмины.")}
|
||||
</PageHeader>
|
||||
|
||||
<Section title={t("Хосты")} count={hosts.length}>
|
||||
{hosts.length === 0 ? <Empty>{t("Хостов нет — раннеры работают на Mac Peppa FACTORY.")}</Empty> : hosts.map((h) => <HostCard key={h.id} h={h} t={t} />)}
|
||||
{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>
|
||||
@ -123,14 +123,14 @@ export default async function Hosts({ searchParams }: { searchParams: Promise<{
|
||||
<Section title={t("Как подготовить хост")}>
|
||||
<ol className="m-0 flex list-decimal flex-col gap-2 pl-5 text-sm">
|
||||
<li>
|
||||
{t("Добавьте ключ Peppa FACTORY в {file} пользователя на хосте:").split("{file}").flatMap((part, i) => (i ? [<code key={i}>~/.ssh/authorized_keys</code>, part] : [part]))}
|
||||
{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("Адрес Peppa FACTORY для хоста должен открываться с хоста (по умолчанию — адрес веба); через него идут хуки, MCP и git агента.")}</li>
|
||||
<li>{t("Адрес FORGE для хоста должен открываться с хоста (по умолчанию — адрес веба); через него идут хуки, MCP и git агента.")}</li>
|
||||
</ol>
|
||||
</Section>
|
||||
</div>
|
||||
|
||||
@ -25,7 +25,7 @@ export default async function Journal({ searchParams }: { searchParams: Promise<
|
||||
return (
|
||||
<Workspace aside={null}>
|
||||
<PageHeader title={t("Журнал действий")}>
|
||||
{t("Кто что сделал: люди (веб, Telegram, MCP-клиенты, CLI, терминал), агенты и сама Peppa FACTORY. Новые сверху, последние 300.")}
|
||||
{t("Кто что сделал: люди (веб, Telegram, MCP-клиенты, CLI, терминал), агенты и сама FORGE. Новые сверху, последние 300.")}
|
||||
{!all && " " + t("Служебные события хуков скрыты.")}
|
||||
</PageHeader>
|
||||
<div className="mb-4">
|
||||
|
||||
@ -18,22 +18,23 @@ 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();
|
||||
const counts = await navCounts(user.id);
|
||||
const { sound } = await getNotifyPrefs(db, user.id);
|
||||
const superadmin = await isSuperadmin(db, user);
|
||||
const mode = await uiMode();
|
||||
// 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 = engineer ? await accountUsageForUser(db, user).catch(() => []) : [];
|
||||
const line = engineer ? null : await agentsLine(db, user).catch(() => ({ state: "working" as const }));
|
||||
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 (
|
||||
<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 ? await pendingFeedbackCount(db) : 0 }} superadmin={superadmin} engineer={engineer} />
|
||||
<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} />}
|
||||
|
||||
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,10 +1,11 @@
|
||||
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 { ExternalLink, Plus, Rocket, SquareTerminal } from "lucide-react";
|
||||
import { columnOf, currentReleases, describeRepo, 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, projectMetrics, type ActorChannel, type ActorKind, getAutonomy, getIncidentSettings, getReviewSettings, isSuperadmin, listEpics, listErrorSources, listIncidents, listMembers, listPools, listSpecs, taskAgentNames, getIntakeSettings, intakePendingTasks, projectAgentWarning, memoryStats, readMemory, projectPool, sharedPool, ownPool, poolOverview, repoAudience, repoVisibilityLabel } from "@peppa/core";
|
||||
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";
|
||||
@ -14,6 +15,7 @@ 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";
|
||||
@ -39,7 +41,7 @@ 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 { delayedTaskIds, pendingQuestions, listPendingAccepts, PENDING_ACCEPT_LABEL, PLATFORM_DELAY_LABEL } from "@peppa/core";
|
||||
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";
|
||||
@ -88,10 +90,11 @@ function EnvLine({ name, r, t }: { name: string; r: Release | null | undefined;
|
||||
);
|
||||
}
|
||||
|
||||
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 }> }) {
|
||||
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, checked, tab: tabParam, epic: epicParam, weeks, actor, channel, edit, saved } = 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();
|
||||
@ -100,12 +103,12 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
||||
const tab = visibleTabs.find((x) => x.id === tabParam)?.id ?? "board";
|
||||
const p = await projectForUserByKey(user.id, key).catch(() => null);
|
||||
if (!p) notFound();
|
||||
const [{ tasks }, epics, sessions, team, repo, incidentSettings, sources, incidents, releases, current, reviewer, progress, deps] = await Promise.all([
|
||||
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),
|
||||
describeRepo(db, p),
|
||||
Promise.resolve(peekRepo(db, p)),
|
||||
getIncidentSettings(db, p.id),
|
||||
listErrorSources(db, p.id),
|
||||
listIncidents(db, p.id),
|
||||
@ -114,6 +117,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
||||
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);
|
||||
@ -129,6 +133,8 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
||||
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.
|
||||
@ -152,18 +158,31 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
||||
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),
|
||||
@ -173,8 +192,13 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
||||
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,
|
||||
delayed: delayed.has(x.id) && x.status !== "done" ? t.text(PLATFORM_DELAY_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,
|
||||
};
|
||||
});
|
||||
@ -190,6 +214,8 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
||||
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.
|
||||
@ -270,11 +296,17 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
||||
<EpicsPanel w={w} projectId={p.id} projectKey={p.key} epics={epics} progress={progress} back={back} />
|
||||
</PanelSection>
|
||||
|
||||
{engineer && (
|
||||
<PanelSection title={t("Секреты")} count={secrets.length}>
|
||||
<ProjectSecretsPanel projectId={p.id} secrets={secrets} back={back} />
|
||||
<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("Бюджет стори")}>
|
||||
@ -282,21 +314,17 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
||||
</PanelSection>
|
||||
)}
|
||||
|
||||
<PanelSection title={t("Продакт и аналитик")}>
|
||||
<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>
|
||||
<label className="flex items-center gap-2 text-sm">
|
||||
{t("Ждать ответа на вопросы, минут")}
|
||||
<Input type="number" name="waitMin" min={0} max={1440} defaultValue={intake.waitMin} aria-label={t("Сколько минут аналитик ждёт ответа")} className="h-8 w-20" />
|
||||
{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") })}
|
||||
{t("Аналитик решает, зачем это и что берём в первую версию, делит большое (не больше четырёх частей) и пишет критерии приёмки. Вопросов не задаёт: развилки решает сам и показывает решения на странице задачи — «Фабрика решила за вас». {Tasks}, созданные до включения, не трогает.", { Tasks: w.Task("pl") })}
|
||||
</p>
|
||||
</PanelSection>
|
||||
|
||||
@ -333,6 +361,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
||||
projectId={p.id}
|
||||
back={back}
|
||||
isOwner={isOwner}
|
||||
direct={directOrigins.includes("incident")}
|
||||
settings={incidentSettings}
|
||||
sources={sources}
|
||||
webhookUrl={incidentSettings ? `${bugsinkWebhookBase()}/api/hooks/bugsink/${incidentSettings.hookSecret}` : null}
|
||||
@ -363,7 +392,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
||||
<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("приглашён · появится после первого входа в Peppa FACTORY")}</span>
|
||||
<span className="text-xs text-muted-foreground">{t("приглашён · появится после первого входа в FORGE")}</span>
|
||||
</span>
|
||||
{isOwner && (
|
||||
<form action={removeProjectMember}>
|
||||
@ -395,7 +424,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
||||
{pool ? (
|
||||
shared?.id === pool.id ? (
|
||||
<>
|
||||
{t("Агенты работают на")} <b>{t("подписке Peppa FACTORY")}</b> {t("— общей для пользователей фабрики. Свою подписку можно подключить в любой момент ниже.")}
|
||||
{t("Агенты работают на")} <b>{t("подписке FORGE")}</b> {t("— общей для пользователей фабрики. Свою подписку можно подключить в любой момент ниже.")}
|
||||
</>
|
||||
) : (
|
||||
<>{superadmin ? t("Агенты работают на подписке проекта — пул «{name}».", { name: pool.name }) : t("Агенты работают на подписке проекта.")}</>
|
||||
@ -412,6 +441,12 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
||||
<SubscriptionRequestButton projectId={p.id} offer={askOffer} back={`${back}#subscription`} />
|
||||
</div>
|
||||
)}
|
||||
{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) && (
|
||||
<>
|
||||
@ -453,7 +488,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
||||
<form action={chooseSharedSubscriptionAction}>
|
||||
<Hidden fields={{ projectId: p.id, back }} />
|
||||
<Button size="sm" variant={pool ? "outline" : "default"} disabled={!!sharedReq && !superadmin}>
|
||||
{superadmin ? t("Перейти на подписку Peppa FACTORY") : sharedReq ? t("Запрос на подписку Peppa FACTORY отправлен") : t("Попросить подписку Peppa FACTORY")}
|
||||
{superadmin ? t("Перейти на подписку FORGE") : sharedReq ? t("Запрос на подписку FORGE отправлен") : t("Попросить подписку FORGE")}
|
||||
</Button>
|
||||
{!superadmin && <span className="text-xs text-muted-foreground">{sharedReq ? t("Ждём подтверждения администратора фабрики — придёт сообщение.") : t("Нужно подтверждение администратора фабрики.")}</span>}
|
||||
</form>
|
||||
@ -508,7 +543,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
||||
</PanelSection>
|
||||
{mayDeleteProject(p, user.id, superadmin) && (
|
||||
<PanelSection title={t("Удалить проект")}>
|
||||
<p className="m-0 text-xs text-muted-foreground">{t("Проект пропадёт из вашего списка, а агенты остановятся. Ещё неделю он хранится у администратора Peppa FACTORY — если передумаете, попросите вернуть его. Потом проект удаляется насовсем.")}</p>
|
||||
<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">
|
||||
@ -519,7 +554,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
||||
</form>
|
||||
</PanelSection>
|
||||
)}
|
||||
{!engineer && <p className="m-0 text-xs text-muted-foreground">{t("Настройки для разработчиков — код проекта, настройки и расход агентов — открываются в виде «Инженер»:")} <a href="/settings#mode" className="text-primary">{t("Настройки → Вид Peppa FACTORY")}</a>.</p>}
|
||||
{!engineer && <p className="m-0 text-xs text-muted-foreground">{t("Настройки для разработчиков — код проекта, настройки и расход агентов — открываются в виде «Инженер»:")} <a href="/settings#mode" className="text-primary">{t("Настройки → Вид FORGE")}</a>.</p>}
|
||||
</div>
|
||||
);
|
||||
|
||||
@ -565,6 +600,11 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
||||
<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>
|
||||
@ -594,6 +634,13 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
||||
{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">
|
||||
@ -734,7 +781,10 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
||||
)}
|
||||
|
||||
{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}`]))} />
|
||||
<>
|
||||
<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} />}
|
||||
|
||||
@ -167,7 +167,7 @@ export async function PullsTab({ pulls, error, repoUrl }: { pulls: OpenPull[]; e
|
||||
<Badge variant={CI_TONE[p.task.ci.state]}>{t.text(p.task.ci.label)}</Badge>
|
||||
</>
|
||||
) : (
|
||||
<span>· {t("не стори Peppa FACTORY")}</span>
|
||||
<span>· {t("не стори FORGE")}</span>
|
||||
)}
|
||||
</div>
|
||||
</article>
|
||||
@ -286,7 +286,7 @@ export async function AgentsMdTab({ projectId, projectKey, md, edit, saved }: {
|
||||
>
|
||||
{saved && <Notice>{t("AGENTS.md сохранён в {branch}", { branch: md.branch })}</Notice>}
|
||||
<p className="m-0 text-sm text-muted-foreground">
|
||||
{t("Промпт и стандарты проекта: стек, команды, соглашения, этапы (например, проверка ИБ перед PR). Его читают все агенты — Claude, Codex и OpenCode; общие правила Peppa FACTORY добавляются сами.")}
|
||||
{t("Промпт и стандарты проекта: стек, команды, соглашения, этапы (например, проверка ИБ перед PR). Его читают все агенты — Claude, Codex и OpenCode; общие правила FORGE добавляются сами.")}
|
||||
</p>
|
||||
{md.text.trim() ? (
|
||||
<div className="rounded-lg border bg-card p-4">
|
||||
@ -302,7 +302,7 @@ export async function AgentsMdTab({ projectId, projectKey, md, edit, saved }: {
|
||||
// i18n-ignore — file content for the project repository (like template/AGENTS.md), not UI text
|
||||
const AGENTS_MD_STARTER = `# AGENTS.md
|
||||
|
||||
Проект ведётся на **Peppa FACTORY**. Общие правила (OpenSpec, PR, ревью) агент получает от Peppa FACTORY;
|
||||
Проект ведётся на **FORGE**. Общие правила (OpenSpec, PR, ревью) агент получает от FORGE;
|
||||
здесь — только стандарты этого проекта.
|
||||
|
||||
## Стек и команды
|
||||
|
||||
@ -1,7 +1,9 @@
|
||||
import { Suspense } from "react";
|
||||
import { redirect } from "next/navigation";
|
||||
import { claimWelcome, isSuperadmin, listUserProjects, onboardingChecklist, pendingFeedback, platformDelayOverview, progressOverview } from "@peppa/core";
|
||||
import Link from "next/link";
|
||||
import { agentTaskSummary, claimWelcome, isSuperadmin, listUserProjects, onboardingChecklist, pendingFeedback, platformDelayCounts, progressOverview, proposedCount, reviewCounts } from "@peppa/core";
|
||||
import { AdminFeedbackCard } from "@/components/Feedback";
|
||||
import { PlatformDelays } from "@/components/PlatformDelays";
|
||||
import { AgentTaskSummary } from "@/components/AgentTaskSummary";
|
||||
import { ProgressOverview } from "@/components/ProgressOverview";
|
||||
import { OnboardingChecklist } from "@/components/Onboarding";
|
||||
import { PugBanner } from "@/components/PugMascot";
|
||||
@ -15,48 +17,114 @@ import { db } from "@/lib/db";
|
||||
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 t = await getT();
|
||||
const w = await words();
|
||||
if (await claimWelcome(db, user.id)) redirect("/welcome");
|
||||
const [items, ready, sessions, projects, onboarding, progress] = await Promise.all([inbox(user.id), acceptInbox(user.id), activeSessions(user.id), listUserProjects(db, user.id), onboardingChecklist(db, user), progressOverview(db, user.id)]);
|
||||
// PEP-143: users' reports about Peppa FACTORY wait for the superadmin's decision here.
|
||||
const reports = (await isSuperadmin(db, user)) ? await pendingFeedback(db) : [];
|
||||
// PEP-150: delays on the platform's side are the superadmin's to watch, not the owners'.
|
||||
const delays = (await isSuperadmin(db, user)) ? await platformDelayOverview(db) : [];
|
||||
// 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 (
|
||||
<Workspace aside={<ActivityAside questions={false} />}>
|
||||
<LiveRefresh scope="home" />
|
||||
<Flash error={error} />
|
||||
<PageHeader title={t("Главная")}>{items.length ? (w.engineer ? t("Агенты ждут вашего решения — ответьте здесь, в Telegram или через MCP.") : t("Агенты ждут вашего решения — ответьте здесь или в Telegram.")) : t("Всё идёт само: агентам от вас ничего не нужно.")}</PageHeader>
|
||||
<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>
|
||||
{ready.length > 0 && (
|
||||
{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.length > 0 && (
|
||||
<Section title={t("Задержки на стороне Peppa FACTORY")} count={delays.length}>
|
||||
<PlatformDelays delays={delays} />
|
||||
{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("Прогресс")}>
|
||||
<ProgressOverview data={progress} />
|
||||
</Section>
|
||||
<Section title={t("Агенты за работой")} count={sessions.length} actions={w.engineer ? <MoreLink href="/runners">{t("вся работа агентов")}</MoreLink> : undefined}>
|
||||
{sessions.length === 0 ? <Empty>{t("Сейчас никто не работает: напишите задачу — и агент возьмёт её.")}</Empty> : sessions.map((s) => <AgentAtWork key={s.id} s={s} back="/" engineer={w.engineer} />)}
|
||||
<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>
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
import { notFound } from "next/navigation";
|
||||
import { Megaphone, RefreshCw, Send } from "lucide-react";
|
||||
import { buildPlatformDigest, getPlatformBuild, getPlatformChannel, isSuperadmin, platformDigestEmpty, PLATFORM_CHANNEL_EVENT_NAMES, PLATFORM_CHANNEL_EVENTS, renderPlatformDigest } from "@peppa/core";
|
||||
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";
|
||||
@ -14,7 +14,7 @@ import { checkChannelAction, saveChannelAction, saveChannelSettingsAction, sendD
|
||||
|
||||
export async function generateMetadata() {
|
||||
const t = await getT();
|
||||
return { title: t("Платформа — Peppa FACTORY") };
|
||||
return { title: t("Платформа — FORGE") };
|
||||
}
|
||||
|
||||
/** Telegram HTML of the digest → plain text for the preview. */
|
||||
@ -25,7 +25,10 @@ export default async function Platform({ searchParams }: { searchParams: Promise
|
||||
const t = await getT();
|
||||
if (!(await isSuperadmin(db, user))) notFound();
|
||||
const { error, sent } = await searchParams;
|
||||
const [c, build] = await Promise.all([getPlatformChannel(db), getPlatformBuild(db)]);
|
||||
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>
|
||||
@ -33,7 +36,7 @@ export default async function Platform({ searchParams }: { searchParams: Promise
|
||||
<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-канал Peppa FACTORY: новые версии, падения и перезапуски сервисов и ежедневный дайджест — что нового в Peppa FACTORY и что происходит сейчас. Раздел видят только суперадмины.")}
|
||||
{t("Telegram-канал FORGE: новые версии, падения и перезапуски сервисов и ежедневный дайджест — что нового в FORGE и что происходит сейчас. Раздел видят только суперадмины.")}
|
||||
{build && <> {t("Сейчас: v{version}", { version: build.version })} · <span className="font-mono">{build.commit.slice(0, 7)}</span>.</>}
|
||||
</PageHeader>
|
||||
|
||||
@ -66,7 +69,7 @@ export default async function Platform({ searchParams }: { searchParams: Promise
|
||||
</form>
|
||||
)}
|
||||
<p className="m-0 text-xs text-muted-foreground">
|
||||
{t("Добавьте бота Peppa FACTORY в канал администратором с правом «Публикация сообщений». Пока проверка не прошла, Peppa FACTORY перепроверяет канал раз в час и ничего туда не пишет. Ответы в канале бот не читает.")}
|
||||
{t("Добавьте бота FORGE в канал администратором с правом «Публикация сообщений». Пока проверка не прошла, FORGE перепроверяет канал раз в час и ничего туда не пишет. Ответы в канале бот не читает.")}
|
||||
</p>
|
||||
</Card>
|
||||
</Section>
|
||||
@ -99,6 +102,42 @@ export default async function Platform({ searchParams }: { searchParams: Promise
|
||||
</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={
|
||||
|
||||
@ -48,7 +48,7 @@ export default async function NewProject({ searchParams }: { searchParams: Promi
|
||||
<ProjectBasics>
|
||||
{local ? (
|
||||
<p className="m-0 text-sm text-muted-foreground">
|
||||
{t("Код хранится в Peppa FACTORY")}{w.engineer && <>: <span className="font-mono">{giteaUrl}/{botLogin}/…</span></>}. {t("Работать с ним вам не нужно — это делают агенты.")}
|
||||
{t("Код хранится в FORGE")}{w.engineer && <>: <span className="font-mono">{giteaUrl}/{botLogin}/…</span></>}. {t("Работать с ним вам не нужно — это делают агенты.")}
|
||||
</p>
|
||||
) : (
|
||||
<Label>
|
||||
@ -75,7 +75,7 @@ export default async function NewProject({ searchParams }: { searchParams: Promi
|
||||
</fieldset>
|
||||
)}
|
||||
</ProjectBasics>
|
||||
<p className="m-0 text-sm text-muted-foreground">{t("Peppa FACTORY подготовит всё для агентов — это займёт до 15 секунд.")}</p>
|
||||
<p className="m-0 text-sm text-muted-foreground">{t("FORGE подготовит всё для агентов — это займёт до 15 секунд.")}</p>
|
||||
<PendingButton pendingText={t("Создаём проект…")} className="self-start">{t("Создать проект")}</PendingButton>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
import { notFound } from "next/navigation";
|
||||
import { ShieldCheck } from "lucide-react";
|
||||
import { isSuperadmin, secretsAudit, type PlatformSecretRow } from "@peppa/core";
|
||||
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";
|
||||
@ -15,7 +15,7 @@ import { checkGiteaTokenAction, markSecretRotatedAction, reencryptSecretsAction,
|
||||
|
||||
export async function generateMetadata() {
|
||||
const t = await getT();
|
||||
return { title: t("Секреты — Peppa FACTORY") };
|
||||
return { title: t("Секреты — FORGE") };
|
||||
}
|
||||
|
||||
type Params = { error?: string; reencrypted?: string; unreadable?: string; revoked?: string; gitea?: string };
|
||||
@ -56,6 +56,8 @@ export default async function Secrets({ searchParams }: { searchParams: Promise<
|
||||
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}");
|
||||
@ -106,7 +108,7 @@ export default async function Secrets({ searchParams }: { searchParams: Promise<
|
||||
<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("ротирует Peppa FACTORY") : t("вручную")}</Badge>
|
||||
<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">
|
||||
@ -202,6 +204,31 @@ export default async function Secrets({ searchParams }: { searchParams: Promise<
|
||||
</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,4 +1,4 @@
|
||||
import { CONNECT_HELP, googleEnabled, connectedApps, getNotifyPrefs, isLocalUser, isSuperadmin, listUserProjects, maskIin, NOTIFY_EVENT_NAMES, NOTIFY_EVENTS, userPushSubscriptions, vapidPublicKey } from "@peppa/core";
|
||||
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";
|
||||
@ -6,6 +6,8 @@ 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";
|
||||
@ -50,10 +52,14 @@ export default async function Settings({ searchParams }: { searchParams: Promise
|
||||
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">
|
||||
@ -61,7 +67,7 @@ export default async function Settings({ searchParams }: { searchParams: Promise
|
||||
<LanguageSwitcher />
|
||||
</Card>
|
||||
</Section>
|
||||
<Section title={t("Вид Peppa FACTORY")} id="mode">
|
||||
<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">
|
||||
@ -85,7 +91,7 @@ export default async function Settings({ searchParams }: { searchParams: Promise
|
||||
<Card>
|
||||
<p className="m-0 text-sm">
|
||||
{t("Логин")} <span className="font-mono">{user.login}</span>
|
||||
{user.name ? <> · {user.name}</> : null}.{" "}{t("Вход в Peppa FACTORY — через eGov QR или Google")}
|
||||
{user.name ? <> · {user.name}</> : null}.{" "}{t("Вход в FORGE — через eGov QR или Google")}
|
||||
{user.egovIin ? (
|
||||
<>
|
||||
, {t("ИИН")} <span className="font-mono">{maskIin(user.egovIin)}</span>.
|
||||
@ -96,7 +102,7 @@ export default async function Settings({ searchParams }: { searchParams: Promise
|
||||
</p>
|
||||
{local && w.engineer && (
|
||||
<p className="m-0 text-sm text-muted-foreground">
|
||||
{t("Аккаунта Gitea нет: код проектов — через Peppa FACTORY (агенты, PR, проверки), новые проекты создаются в пространстве")} <span className="font-mono">peppa-bot</span>.
|
||||
{t("Аккаунта Gitea нет: код проектов — через FORGE (агенты, PR, проверки), новые проекты создаются в пространстве")} <span className="font-mono">peppa-bot</span>.
|
||||
</p>
|
||||
)}
|
||||
</Card>
|
||||
@ -144,9 +150,11 @@ export default async function Settings({ searchParams }: { searchParams: Promise
|
||||
<Section title="eGov" id="egov">
|
||||
{egov === "linked" && <Notice>{t("eGov привязан — теперь можно входить по QR")}</Notice>}
|
||||
<Card>
|
||||
<p className="m-0 text-sm">{t("Привяжите свой ИИН: отсканируйте QR в eGov Mobile и подпишите. Вход в Peppa FACTORY — только через eGov.")}</p>
|
||||
<p className="m-0 text-sm">{t("Привяжите свой ИИН: отсканируйте QR в eGov Mobile и подпишите. Вход в FORGE — только через eGov.")}</p>
|
||||
<div className="max-w-xs">
|
||||
<EgovSign purpose="link" label={t("Привязать eGov")} />
|
||||
<FeatureGate view={egovGate} label={t("Привязать eGov")}>
|
||||
<EgovSign purpose="link" label={t("Привязать eGov")} />
|
||||
</FeatureGate>
|
||||
</div>
|
||||
</Card>
|
||||
</Section>
|
||||
@ -191,7 +199,7 @@ export default async function Settings({ searchParams }: { searchParams: Promise
|
||||
</form>
|
||||
}
|
||||
>
|
||||
{t("Вопросы агентов и «готово к ревью» приходят вам")} {user.telegramBotUsername ? <>{t("от вашего бота")} <span className="font-mono">@{user.telegramBotUsername}</span></> : t("от общего бота Peppa FACTORY")}. {voiceStoriesEnabled() ? t("Новую задачу можно просто написать или наговорить голосом боту.") : t("Новую задачу можно просто написать боту.")}
|
||||
{t("Вопросы агентов и «готово к ревью» приходят вам")} {user.telegramBotUsername ? <>{t("от вашего бота")} <span className="font-mono">@{user.telegramBotUsername}</span></> : t("от общего бота FORGE")}. {voiceStoriesEnabled() ? t("Новую задачу можно просто написать или наговорить голосом боту.") : t("Новую задачу можно просто написать боту.")}
|
||||
</Row>
|
||||
) : (
|
||||
ownBotSteps
|
||||
@ -199,7 +207,7 @@ export default async function Settings({ searchParams }: { searchParams: Promise
|
||||
{/* PEP-100: every user has their own bot — someone still on the shared one is asked to switch. */}
|
||||
{user.telegramChatId && !hasBot && (
|
||||
<>
|
||||
<Notice>{t("Сейчас сообщения приходят от общего бота Peppa FACTORY. Подключите своего бота — так у вас будет свой канал для задач и ответов.")}</Notice>
|
||||
<Notice>{t("Сейчас сообщения приходят от общего бота FORGE. Подключите своего бота — так у вас будет свой канал для задач и ответов.")}</Notice>
|
||||
{ownBotSteps}
|
||||
</>
|
||||
)}
|
||||
@ -216,7 +224,7 @@ export default async function Settings({ searchParams }: { searchParams: Promise
|
||||
<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}. Peppa FACTORY можно установить как приложение (Chrome → «Установить»).", { task: w.task("acc"), n: pushSubs.length })}
|
||||
{t("Push приходят и при закрытой вкладке; клик открывает {task} или проект. Подписано браузеров: {n}. FORGE можно установить как приложение (Chrome → «Установить»).", { task: w.task("acc"), n: pushSubs.length })}
|
||||
</p>
|
||||
</div>
|
||||
<PushNotifications vapidKey={vapid} known={pushSubs.map((s) => s.endpoint)} />
|
||||
@ -307,14 +315,16 @@ export default async function Settings({ searchParams }: { searchParams: Promise
|
||||
<Button variant="default" className="self-start">{t("Сохранить уведомления")}</Button>
|
||||
</form>
|
||||
</Section>
|
||||
<Section title={w.engineer ? t("MCP для ChatGPT и других клиентов") : t("Peppa FACTORY в вашем Claude или ChatGPT")}>
|
||||
<p className="m-0 text-sm">{w.engineer ? t("Адрес сервера — подключите его как MCP-коннектор с авторизацией OAuth. Клиент зарегистрируется сам, вы подтвердите доступ на экране Peppa FACTORY.") : t("Подключите Peppa FACTORY к своему чату — и ставьте задачи и отвечайте агентам прямо из него. Понадобится этот адрес; доступ вы подтвердите на экране Peppa FACTORY.")}</p>
|
||||
<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>
|
||||
<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 ? (
|
||||
|
||||
@ -4,7 +4,7 @@ import { getQuestion, isSuperadmin, listSubscriptions, OPENCODE_KEY_ENV, PROVIDE
|
||||
import { pendingLogin, pollCodexLogin, type PendingLogin, backfillCodexAccounts, openSubscriptionRequests } from "@peppa/runner";
|
||||
import { answerQuestion } from "@/app/(app)/actions";
|
||||
import { LocalTime } from "@/components/LocalTime";
|
||||
import { AutoRefresh } from "@/components/AutoRefresh";
|
||||
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";
|
||||
@ -34,9 +34,17 @@ import {
|
||||
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("Подписки — Peppa FACTORY") };
|
||||
return { title: t("Подписки — FORGE") };
|
||||
}
|
||||
|
||||
// PEP-170: one simple picture — a subscription runs out, agents move to the next free one.
|
||||
@ -262,7 +270,7 @@ export default async function Subscriptions({ searchParams }: { searchParams: Pr
|
||||
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 backfillCodexAccounts(db).catch(() => {});
|
||||
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;
|
||||
@ -288,7 +296,8 @@ export default async function Subscriptions({ searchParams }: { searchParams: Pr
|
||||
|
||||
return (
|
||||
<Workspace>
|
||||
{[...logins.values()].some((l) => l.kind === "codex") && <AutoRefresh everyMs={3000} />}
|
||||
<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("Подписки")}</>}>
|
||||
|
||||
@ -17,6 +17,7 @@ import {
|
||||
resolveRunnerSettings,
|
||||
getProjectBudget,
|
||||
listJournal,
|
||||
archivedLog,
|
||||
taskBudgetView,
|
||||
getEpic,
|
||||
isSuperadmin,
|
||||
@ -27,9 +28,12 @@ import {
|
||||
parseTasks,
|
||||
prGate,
|
||||
getPendingAccept,
|
||||
getRolloutWait,
|
||||
PENDING_ACCEPT_LABEL,
|
||||
PLATFORM_DELAY_LABEL,
|
||||
taskDelayed,
|
||||
taskDelayLine,
|
||||
taskHoldReason,
|
||||
projectPool,
|
||||
PROVIDER_NAMES,
|
||||
readChange,
|
||||
@ -49,11 +53,12 @@ import {
|
||||
} from "@peppa/core";
|
||||
import { checkRuns } from "@peppa/db";
|
||||
import { desc, eq } from "drizzle-orm";
|
||||
import { getTeamMatch, matchLine } from "@peppa/core";
|
||||
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";
|
||||
@ -62,6 +67,7 @@ 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 { taskActivity, taskForUser } from "@/lib/queries";
|
||||
import { cn } from "@/lib/utils";
|
||||
@ -119,17 +125,27 @@ export default async function StoryPage({ params, searchParams }: { params: Prom
|
||||
// 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: is the story still with «продакт» and «аналитик»?
|
||||
// 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 ?? "product") : 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))
|
||||
? (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>> = {
|
||||
@ -258,16 +274,19 @@ export default async function StoryPage({ params, searchParams }: { params: Prom
|
||||
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="font-medium">{refining === "waiting" ? t("Аналитик ждёт ваших ответов") : t("Аналитик уточняет задачу")}</span>
|
||||
<span className="text-muted-foreground">
|
||||
{refining === "waiting" ? t("— вопрос во вкладке «Comments». Не ответите — возьмёт варианты по умолчанию и отдаст стори в работу.") : t("— через минуту здесь появятся критерии приёмки. Агент-разработчик возьмёт стори после этого.")}
|
||||
</span>
|
||||
@ -322,8 +341,8 @@ export default async function StoryPage({ params, searchParams }: { params: Prom
|
||||
<TaskRunnerSettings taskKey={ref.key} own={runnerOwn} inherited={runnerProject} back={back} />
|
||||
<TaskAgentModel taskKey={ref.key} own={agentOwn} inherited={agentProject} escalation={escalation} back={back} />
|
||||
{live ? (
|
||||
// PEP-9 terminal + PEP-33 step feed of the newest unfinished runner.
|
||||
<SessionCard s={live} back={back} terminal steps={steps} plainSteps={!engineer} />
|
||||
// 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 }} />
|
||||
@ -426,9 +445,10 @@ export default async function StoryPage({ params, searchParams }: { params: Prom
|
||||
}
|
||||
title={
|
||||
<>
|
||||
<span className="font-mono text-primary">{ref.key}</span> {task.title} {engineer && <StatusBadge status={task.status} />}
|
||||
<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 && delayed && <Badge variant="muted" className="ml-1.5 align-middle whitespace-normal">{t.text(PLATFORM_DELAY_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>}
|
||||
</>
|
||||
}
|
||||
@ -454,6 +474,7 @@ export default async function StoryPage({ params, searchParams }: { params: Prom
|
||||
)}
|
||||
</PageHeader>
|
||||
|
||||
<TaskDecisions taskKey={ref.key} decisions={await getDecisions(db, task.id)} back={back} />
|
||||
{engineer ? (
|
||||
body
|
||||
) : (
|
||||
|
||||
@ -172,7 +172,7 @@ export async function CommentsTab({ taskId, projectId, taskKey, taskStatus, ques
|
||||
) : (
|
||||
<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} className="font-medium text-foreground" /> : <MessageSquare className="size-3.5 text-primary" />}
|
||||
{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>
|
||||
|
||||
@ -18,7 +18,7 @@ import { addAgentAction, saveAgentAction, saveTeamWaitAction, toggleAgentAction
|
||||
|
||||
export async function generateMetadata() {
|
||||
const t = await getT();
|
||||
return { title: t("Команда — Peppa FACTORY") };
|
||||
return { title: t("Команда — FORGE") };
|
||||
}
|
||||
|
||||
/** PEP-75: the platform's team of agents — names and characters. Everyone sees it; a superadmin edits. */
|
||||
@ -36,7 +36,7 @@ export default async function Team({ searchParams }: { searchParams: Promise<{ e
|
||||
{saved && saved !== "wait" && <Notice>{t("Сохранено — агент получит новый характер при следующем запуске или перезапуске.")}</Notice>}
|
||||
<PageHeader title={t("Команда")}>
|
||||
{t("Это ИИ-агенты, не люди: у каждого своя кличка и характер, одна команда на все проекты. Свободный агент берёт {task} и ведёт её до конца; если все заняты — в команде появляется новый.", { task: w.task("acc") })}
|
||||
{w.engineer ? t(" Характер добавляется к промпту агента поверх правил Peppa FACTORY и AGENTS.md проекта.") : t(" Характер влияет на то, как агент работает и пишет вам.")}
|
||||
{w.engineer ? t(" Характер добавляется к промпту агента поверх правил FORGE и AGENTS.md проекта.") : t(" Характер влияет на то, как агент работает и пишет вам.")}
|
||||
</PageHeader>
|
||||
|
||||
<TeamChase view={chase} hidden={chaseHidden} awaitingKey={awaiting.find((q) => q.taskKey)?.taskKey ?? null} />
|
||||
|
||||
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>
|
||||
);
|
||||
}
|
||||
@ -1,15 +1,17 @@
|
||||
import { notFound } from "next/navigation";
|
||||
import { isLocalUser, isSuperadmin, listUsers, maskIin, platformAdmins } from "@peppa/core";
|
||||
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 { setUserDisabledAction } from "../actions";
|
||||
import { setSuperadminAction, setUserDisabledAction } from "../actions";
|
||||
|
||||
const back = { back: "/users" };
|
||||
|
||||
@ -21,6 +23,8 @@ export default async function Users({ searchParams }: { searchParams: Promise<{
|
||||
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">
|
||||
@ -34,22 +38,49 @@ export default async function Users({ searchParams }: { searchParams: Promise<{
|
||||
<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>}
|
||||
{admins.has(u.login.toLowerCase()) && <Badge variant="primary">{t("суперадмин")}</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>}
|
||||
{!u.egovIin && !u.googleSub && !u.passwordHash && <Badge variant="warn">{t("без eGov и Google — не войдёт")}</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="ml-auto">
|
||||
<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>
|
||||
|
||||
@ -36,11 +36,11 @@ export default async function Welcome() {
|
||||
const w = await words();
|
||||
return (
|
||||
<Workspace>
|
||||
<PageHeader title={t("Добро пожаловать в Peppa FACTORY")}>{t("Опишите идею словами — команда ИИ-агентов сделает продукт, а вы примете результат.")}</PageHeader>
|
||||
<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("Peppa FACTORY — фабрика программ для тех, кто придумывает продукты, а не пишет код. Вы ставите задачи и принимаете результат; агенты программируют, проверяют себя и отчитываются.")}</p>
|
||||
<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>
|
||||
@ -84,7 +84,7 @@ export default async function Welcome() {
|
||||
</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("Подключите Peppa FACTORY к своему чату — и ведите проекты прямо из него: «создай {task}», «что ждёт моего ответа?».", { task: w.task("acc") })}</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>
|
||||
|
||||
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",
|
||||
},
|
||||
});
|
||||
}
|
||||
@ -1,5 +1,5 @@
|
||||
// Live updates (PEP-37): SSE of `change` (a watched scope changed — refresh) and `step`
|
||||
// (an agent's tool call, PEP-33) events. ?scope=home | runners | project:<id> | task:<id> | steps:<sessionId>, comma-separated.
|
||||
// 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";
|
||||
@ -12,9 +12,14 @@ const fail = async (status: number, error: string) => Response.json({ error: (aw
|
||||
|
||||
export async function GET(req: Request) {
|
||||
const user = await currentUser();
|
||||
if (!user) return fail(401, m("Нужен вход"));
|
||||
try {
|
||||
return await liveSse(db, user, parseScopes(new URL(req.url).searchParams.get("scope")), req.signal);
|
||||
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);
|
||||
|
||||
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;
|
||||
@ -1,10 +1,11 @@
|
||||
// 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. Logged-in users only; size cap and a per-user rate limit.
|
||||
import { transcribe, transcribeConfig, TranscribeError } from "@peppa/core";
|
||||
// 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 { getT } from "@/lib/i18n";
|
||||
import { getLocale, getT } from "@/lib/i18n";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
@ -44,7 +45,7 @@ export async function POST(req: Request) {
|
||||
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);
|
||||
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 });
|
||||
|
||||
@ -11,7 +11,7 @@
|
||||
--card-foreground: oklch(0.21 0.02 265);
|
||||
--popover: oklch(1 0 0);
|
||||
--popover-foreground: oklch(0.21 0.02 265);
|
||||
--primary: oklch(0.6 0.21 355);
|
||||
--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);
|
||||
@ -22,7 +22,7 @@
|
||||
--destructive: oklch(0.58 0.22 27);
|
||||
--border: oklch(0.9 0.006 265);
|
||||
--input: oklch(0.88 0.008 265);
|
||||
--ring: oklch(0.6 0.21 355);
|
||||
--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);
|
||||
@ -38,8 +38,8 @@
|
||||
--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.72 0.19 352);
|
||||
--primary-foreground: oklch(0.17 0.03 352);
|
||||
--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);
|
||||
@ -49,7 +49,7 @@
|
||||
--destructive: oklch(0.66 0.2 25);
|
||||
--border: oklch(1 0 0 / 9%);
|
||||
--input: oklch(1 0 0 / 13%);
|
||||
--ring: oklch(0.72 0.19 352);
|
||||
--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);
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
import { completeEgovFlow, isUserAllowed, PeppaError } from "@peppa/core";
|
||||
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";
|
||||
@ -20,7 +20,11 @@ export async function POST(req: NextRequest) {
|
||||
// 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))) return done({ error: m("Учётка отключена — обратитесь к администратору") }, 403);
|
||||
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);
|
||||
|
||||
@ -12,7 +12,7 @@ import "./app.css";
|
||||
|
||||
export async function generateMetadata() {
|
||||
const t = await getT();
|
||||
return { title: productName(t.locale), description: t("Peppa FACTORY: опишите идею словами — ИИ-агенты сделают продукт"), icons: { icon: "/icon.svg" } };
|
||||
return { title: productName(t.locale), description: t("FORGE: опишите идею словами — ИИ-агенты сделают продукт"), icons: { icon: "/icon.svg" } };
|
||||
}
|
||||
|
||||
export default async function RootLayout({ children }: { children: ReactNode }) {
|
||||
|
||||
@ -1,6 +1,8 @@
|
||||
import { redirect } from "next/navigation";
|
||||
import { Check, Laptop, MessageCircle, ShieldCheck, Sparkles } from "lucide-react";
|
||||
import { googleEnabled } from "@peppa/core";
|
||||
import { featureGateView, googleEnabled } from "@peppa/core";
|
||||
import { FeatureGate } from "@/components/FeatureGate";
|
||||
import { LiveRefresh } from "@/components/LiveRefresh";
|
||||
import { currentUser, safeNext } from "@/lib/auth";
|
||||
import { Brand } from "@/components/Brand";
|
||||
import { GoogleSignIn } from "@/components/GoogleSignIn";
|
||||
@ -40,6 +42,11 @@ export default async function Login({ searchParams }: { searchParams: Promise<{
|
||||
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="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" />
|
||||
@ -48,7 +55,7 @@ export default async function Login({ searchParams }: { searchParams: Promise<{
|
||||
<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("Peppa FACTORY — фабрика программ для тех, кто придумывает продукты, а не пишет код. Вы ставите задачи и принимаете результат; агенты программируют, проверяют себя и отчитываются.")}
|
||||
{t("FORGE — фабрика программ для тех, кто придумывает продукты, а не пишет код. Вы ставите задачи и принимаете результат; агенты программируют, проверяют себя и отчитываются.")}
|
||||
</p>
|
||||
</header>
|
||||
|
||||
@ -57,8 +64,13 @@ export default async function Login({ searchParams }: { searchParams: Promise<{
|
||||
<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} />
|
||||
<EgovSign purpose="login" next={safeNext(next)} label={t("Войти через eGov")} />
|
||||
{googleEnabled() && <GoogleSignIn purpose="login" next={safeNext(next)} label={t("Войти через Google")} />}
|
||||
<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>
|
||||
|
||||
|
||||
@ -2,7 +2,7 @@ import type { MetadataRoute } from "next";
|
||||
import { PRODUCT_NAME } from "@peppa/shared/i18n";
|
||||
import { getT } from "@/lib/i18n";
|
||||
|
||||
/** Installable as an app (PEP-55): Chrome «Установить Пеппу», badge on the app icon. */
|
||||
/** 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 {
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
import { MCP_GUIDE } from "@peppa/core";
|
||||
import { featureGateView, MCP_GUIDE } from "@peppa/core";
|
||||
import { FeatureGate } from "@/components/FeatureGate";
|
||||
import { LiveRefresh } from "@/components/LiveRefresh";
|
||||
import { Brand } from "@/components/Brand";
|
||||
import { GuideCopy } from "@/components/GuideCopy";
|
||||
import { getT } from "@/lib/i18n";
|
||||
@ -12,8 +14,11 @@ export default async function McpGuide() {
|
||||
<main className="mx-auto flex max-w-2xl flex-col gap-4 px-4 py-8 text-sm leading-relaxed">
|
||||
<Brand />
|
||||
<h1 className="m-0 text-xl font-semibold">{t("Инструкция для ИИ")}</h1>
|
||||
<p className="m-0 text-muted-foreground">{t("Памятка для ИИ, подключённого к Peppa FACTORY. Вставьте её в «Инструкции» проекта ChatGPT или в системное сообщение другого ИИ.")}</p>
|
||||
<GuideCopy value={MCP_GUIDE} label={t("Скопировать")} done={t("Скопировано")} />
|
||||
<p className="m-0 text-muted-foreground">{t("Памятка для ИИ, подключённого к FORGE. Вставьте её в «Инструкции» проекта ChatGPT или в системное сообщение другого ИИ.")}</p>
|
||||
<LiveRefresh scope="features" indicator={false} />
|
||||
<FeatureGate view={featureGateView("mcp")} title={t("MCP временно недоступен")}>
|
||||
<GuideCopy value={MCP_GUIDE} label={t("Скопировать")} done={t("Скопировано")} />
|
||||
</FeatureGate>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
|
||||
import { enterActor, getUser, isUserAllowed, verifyAccessToken } from "@peppa/core";
|
||||
import { enterActor, FEATURES, featureStatus, getUser, isUserAllowed, verifyAccessToken } from "@peppa/core";
|
||||
import { stripAsIs, t as translate } from "@peppa/shared/i18n";
|
||||
import { createManagerServer } from "@peppa/mcp/manager";
|
||||
import { publicOrigin } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
@ -20,6 +21,15 @@ export async function POST(req: Request) {
|
||||
const auth = await verifyAccessToken(db, token);
|
||||
const user = auth && (await getUser(db, auth.userId));
|
||||
if (!user || !(await isUserAllowed(db, user))) return unauthorized();
|
||||
// PEP-224: a service MCP depends on is down (Observability) — say so plainly instead of failing midway.
|
||||
// HTTP 200 with a JSON-RPC error: a 5xx is replaced by Cloudflare's own page (PEP-194).
|
||||
if (featureStatus("mcp").state === "unavailable") {
|
||||
const body = (await req.clone().json().catch(() => null)) as { id?: unknown } | Array<{ id?: unknown }> | null;
|
||||
const id = (Array.isArray(body) ? body[0]?.id : body?.id) ?? null;
|
||||
const text = FEATURES.mcp.unavailableText;
|
||||
const message = `${stripAsIs(text)} / ${stripAsIs(translate("en", text))}`;
|
||||
return json({ jsonrpc: "2.0", id, error: { code: -32001, message } }, 200, { "Access-Control-Allow-Origin": "*", "Retry-After": "300" });
|
||||
}
|
||||
// PEP-48: everything this request does is done by the user through this OAuth client.
|
||||
enterActor({ kind: "user", userId: user.id, channel: "mcp", clientId: auth.clientId });
|
||||
const server = createManagerServer(db, user, await publicOrigin());
|
||||
|
||||
@ -42,7 +42,7 @@ export default async function Authorize({ searchParams }: { searchParams: Promis
|
||||
) : (
|
||||
<>
|
||||
<p className="m-0 text-sm">
|
||||
<b>{client.name}</b> <span className="text-muted-foreground">({host})</span> {t("просит доступ к Peppa FACTORY от имени")} <b>{user.login}</b>.
|
||||
<b>{client.name}</b> <span className="text-muted-foreground">({host})</span> {t("просит доступ к FORGE от имени")} <b>{user.login}</b>.
|
||||
</p>
|
||||
<ul className="m-0 flex list-disc flex-col gap-1 pl-5 text-sm">
|
||||
<li>{t("видеть ваши проекты, эпики, задачи и вопросы агентов;")}</li>
|
||||
|
||||
@ -4,22 +4,23 @@ import { Bot } from "lucide-react";
|
||||
import { useT } from "@/components/I18n";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const TONES = ["bg-sky-500/20 text-sky-300", "bg-emerald-500/20 text-emerald-300", "bg-amber-500/20 text-amber-300", "bg-fuchsia-500/20 text-fuchsia-300", "bg-rose-500/20 text-rose-300", "bg-violet-500/20 text-violet-300", "bg-teal-500/20 text-teal-300", "bg-orange-500/20 text-orange-300"];
|
||||
const TONES = ["bg-sky-500/20 text-sky-300", "bg-emerald-500/20 text-emerald-300", "bg-amber-500/20 text-amber-300", "bg-blue-500/20 text-blue-300", "bg-indigo-500/20 text-indigo-300", "bg-violet-500/20 text-violet-300", "bg-teal-500/20 text-teal-300", "bg-orange-500/20 text-orange-300"];
|
||||
|
||||
/**
|
||||
* PEP-75/96: an AI agent — a robot in its own colour and «агент <кличка>», so a product manager
|
||||
* never takes it for a person.
|
||||
* never takes it for a person. PEP-156: an AI role («Аналитик», «Продакт-агент») is shown by its
|
||||
* name alone, in the reader's language.
|
||||
*/
|
||||
export function AgentBadge({ name, className, large = false }: { name: string; className?: string; large?: boolean }) {
|
||||
export function AgentBadge({ name, className, large = false, role = false }: { name: string; className?: string; large?: boolean; role?: boolean }) {
|
||||
const t = useT();
|
||||
const tone = TONES[[...name].reduce((a, c) => a + c.codePointAt(0)!, 0) % TONES.length];
|
||||
return (
|
||||
<span className={cn("inline-flex min-w-0 items-center gap-1.5", large ? "text-base font-medium" : "text-xs", className)} title={t("ИИ-агент {name}", { name })}>
|
||||
<span className={cn("inline-flex min-w-0 items-center gap-1.5", large ? "text-base font-medium" : "text-xs", className)} title={t("ИИ-агент {name}", { name: role ? t(name) : name })}>
|
||||
<span aria-hidden className={cn("grid shrink-0 place-items-center rounded-full font-semibold", large ? "size-8 text-sm" : "size-4.5 text-[10px]", tone)}>
|
||||
<Bot className={large ? "size-4.5" : "size-3"} />
|
||||
</span>
|
||||
<span className="truncate">
|
||||
<span className="text-muted-foreground">{large ? t("ИИ-агент") : t("агент")}</span> {name}
|
||||
{role ? t(name) : <><span className="text-muted-foreground">{large ? t("ИИ-агент") : t("агент")}</span> {name}</>}
|
||||
</span>
|
||||
</span>
|
||||
);
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
// PEP-41: provider / model / effort of the agent and escalation (project and story).
|
||||
import { AGENT_EFFORT_RU, AGENT_EFFORTS, AGENT_PROVIDERS, agentSettingsLabel, type AgentSettings, type AgentSettingsPatch, type Escalation } from "@peppa/core";
|
||||
import { AGENT_EFFORT_RU, AGENT_EFFORTS, AGENT_PROVIDERS, agentSettingsLabel, providerModelField, type AgentSettings, type AgentSettingsPatch, type Escalation } from "@peppa/core";
|
||||
import { setAgentSettingsAction } from "@/app/(app)/actions";
|
||||
import { Hidden } from "@/components/cards";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
@ -55,6 +55,20 @@ export async function AgentModelPanel({ projectId, own, inherited, back }: { pro
|
||||
<EffortSelect name="effort" own={own.effort} inherited={inherited.effort} />
|
||||
</Label>
|
||||
</div>
|
||||
{/* glossary-ignore: панель «Модель агента» видна только в виде «Инженер» */}
|
||||
<p className="m-0 text-xs font-medium">{t("Модель для каждого провайдера")}</p>
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
{AGENT_PROVIDERS.map((p) => {
|
||||
const f = providerModelField(p);
|
||||
return (
|
||||
// glossary-ignore: панель «Модель агента» видна только в виде «Инженер»
|
||||
<Label key={p}>
|
||||
{p}
|
||||
<Input name={f} defaultValue={own[f] ?? ""} placeholder={inherited[f] ?? t("как «Модель»")} className="h-8" />
|
||||
</Label>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<p className="m-0 text-xs font-medium">{t("Эскалация после неудач")}</p>
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<Label>
|
||||
@ -82,7 +96,8 @@ export async function AgentModelPanel({ projectId, own, inherited, back }: { pro
|
||||
</Label>
|
||||
</div>
|
||||
<p className="m-0 text-xs text-muted-foreground">
|
||||
{t("Модель — для")} <code>--model</code> {t("(sonnet, opus, gpt-5-codex…), действует только на своего провайдера.")}{" "}
|
||||
{/* glossary-ignore: панель «Модель агента» видна только в виде «Инженер» */}
|
||||
{t("Модель — для")} <code>--model</code> {t("(sonnet, opus, gpt-5-codex…), действует только на своего провайдера; модель другого провайдера при запуске отбрасывается.")}{" "}
|
||||
{t("Неудачи — красные проверки по разным коммитам и возвраты ревьюера; после порога стори до конца идёт на сильной модели, живой раннер перезапускается в том же разговоре.")}{" "}
|
||||
{t("Запасной провайдер — если у основного нет рабочей подписки в пуле.")}
|
||||
</p>
|
||||
|
||||
@ -4,6 +4,7 @@ import { useEffect, useState } from "react";
|
||||
import { Bot, FilePen, FileText, FlaskConical, Globe, Plug, Search, SquareTerminal, Wrench, type LucideIcon } from "lucide-react";
|
||||
import type { StepKind, StepView } from "@peppa/core";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useLive } from "@/lib/live";
|
||||
import { useT } from "@/components/I18n";
|
||||
import { m, type Translator } from "@peppa/shared/i18n";
|
||||
|
||||
@ -52,22 +53,22 @@ export function AgentSteps({ sessionId, initial, live, hooks = true, plain = fal
|
||||
|
||||
useEffect(() => setSteps((cur) => merge(initial, cur)), [initial]);
|
||||
|
||||
// The «N с назад» clock only (no data is fetched on it).
|
||||
useEffect(() => {
|
||||
const timer = setInterval(() => setNow(Date.now()), 10_000);
|
||||
if (!live || typeof EventSource === "undefined") return () => clearInterval(timer);
|
||||
const es = new EventSource(`/api/live?scope=steps:${sessionId}`);
|
||||
es.addEventListener("step", (e) => {
|
||||
try {
|
||||
const { step } = JSON.parse((e as MessageEvent).data) as { step: StepView };
|
||||
setSteps((cur) => merge([step], cur));
|
||||
setNow(Date.now());
|
||||
} catch {}
|
||||
});
|
||||
return () => {
|
||||
clearInterval(timer);
|
||||
es.close();
|
||||
};
|
||||
}, [sessionId, live]);
|
||||
return () => clearInterval(timer);
|
||||
}, []);
|
||||
|
||||
// PEP-225: new steps over the tab's live channel; a hidden tab drops them and catches up on return.
|
||||
useLive(
|
||||
live ? `steps:${sessionId}` : null,
|
||||
(e) => {
|
||||
if (e.type !== "step") return;
|
||||
setSteps((cur) => merge([e.step as unknown as StepView], cur));
|
||||
setNow(Date.now());
|
||||
},
|
||||
{ heavy: true },
|
||||
);
|
||||
|
||||
if (!steps.length)
|
||||
return (
|
||||
|
||||
41
apps/web/components/AgentTaskSummary.tsx
Normal file
41
apps/web/components/AgentTaskSummary.tsx
Normal file
@ -0,0 +1,41 @@
|
||||
import Link from "next/link";
|
||||
import type { AgentTaskRow } from "@peppa/core";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { getT } from "@/lib/i18n";
|
||||
|
||||
/**
|
||||
* PEP-197: for the superadmin — per project, tasks of people and of agents, how many of the
|
||||
* agents' wait for a decision, and where agents made more than people. Money only in «Инженер».
|
||||
*/
|
||||
export async function AgentTaskSummary({ rows, engineer }: { rows: AgentTaskRow[]; engineer: boolean }) {
|
||||
const t = await getT();
|
||||
return (
|
||||
<div className="overflow-x-auto rounded-lg border bg-card">
|
||||
<table className="w-full min-w-[28rem] border-collapse text-sm">
|
||||
<thead>
|
||||
<tr className="text-left text-xs text-muted-foreground">
|
||||
<th className="px-3 py-2 font-medium">{t("Проект")}</th>
|
||||
<th className="px-3 py-2 font-medium">{t("Люди")}</th>
|
||||
<th className="px-3 py-2 font-medium">{t("Фабрика")}</th>
|
||||
<th className="px-3 py-2 font-medium">{t("Ждут решения")}</th>
|
||||
{/* glossary-ignore: сумма показана только в режиме «Инженер» */}
|
||||
{engineer && <th className="px-3 py-2 font-medium">{t("За неделю, $")}</th>}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((r) => (
|
||||
<tr key={r.projectId} className="border-t">
|
||||
<td className="px-3 py-2">
|
||||
<Link href={`/p/${r.key}`}>{r.name}</Link> {r.agentsMoreThanHuman && <Badge variant="warn">{t("фабрика завела больше")}</Badge>}
|
||||
</td>
|
||||
<td className="px-3 py-2 tabular-nums">{r.human}</td>
|
||||
<td className="px-3 py-2 tabular-nums">{r.agents}</td>
|
||||
<td className="px-3 py-2 tabular-nums">{r.proposed}</td>
|
||||
{engineer && <td className="px-3 py-2 tabular-nums">{r.agentCostWeek.toFixed(2)}</td>}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@ -1,5 +1,6 @@
|
||||
import { FileSpreadsheet, FileText, Presentation } from "lucide-react";
|
||||
import { humanSize, type AttachmentView } from "@peppa/core";
|
||||
import type { AttachmentView } from "@peppa/core";
|
||||
import { humanSize } from "@peppa/shared/format";
|
||||
|
||||
/**
|
||||
* PEP-159: files of a message, a comment or a story — pictures as thumbnails that open large,
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef } from "react";
|
||||
import { useLive } from "@/lib/live";
|
||||
|
||||
const PREFIX = /^\(\d+\) /;
|
||||
|
||||
@ -25,53 +26,45 @@ function chime() {
|
||||
}
|
||||
|
||||
/**
|
||||
* «(N) …» in the tab title and the app badge (PEP-55): what waits for the user. Polls
|
||||
* /api/attention; a growing count plays a chime if sound is on in the settings.
|
||||
* «(N) …» in the tab title and the app badge (PEP-55): what waits for the user. The count comes
|
||||
* from the live channel (`attention`, PEP-225) the moment it changes; a growing count plays a
|
||||
* chime if sound is on in the settings.
|
||||
*/
|
||||
export function AttentionBadge({ count: initial, sound: initialSound, everyMs = 20_000 }: { count: number; sound: boolean; everyMs?: number }) {
|
||||
export function AttentionBadge({ count: initial, sound: initialSound }: { count: number; sound: boolean }) {
|
||||
const count = useRef(initial);
|
||||
const sound = useRef(initialSound);
|
||||
|
||||
const apply = () => {
|
||||
const base = document.title.replace(PREFIX, "");
|
||||
const want = count.current > 0 ? `(${count.current}) ${base}` : base;
|
||||
if (document.title !== want) document.title = want;
|
||||
const nav = navigator as Navigator & { setAppBadge?: (n?: number) => Promise<void>; clearAppBadge?: () => Promise<void> };
|
||||
if (count.current > 0) nav.setAppBadge?.(count.current).catch(() => {});
|
||||
else nav.clearAppBadge?.().catch(() => {});
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const apply = () => {
|
||||
const base = document.title.replace(PREFIX, "");
|
||||
const want = count.current > 0 ? `(${count.current}) ${base}` : base;
|
||||
if (document.title !== want) document.title = want;
|
||||
const nav = navigator as Navigator & { setAppBadge?: (n?: number) => Promise<void>; clearAppBadge?: () => Promise<void> };
|
||||
if (count.current > 0) nav.setAppBadge?.(count.current).catch(() => {});
|
||||
else nav.clearAppBadge?.().catch(() => {});
|
||||
};
|
||||
apply();
|
||||
// Next sets the title on navigation: put the counter back.
|
||||
const titleObserver = new MutationObserver(apply);
|
||||
titleObserver.observe(document.head, { subtree: true, childList: true, characterData: true });
|
||||
return () => titleObserver.disconnect();
|
||||
}, []);
|
||||
|
||||
const poll = async () => {
|
||||
if (document.visibilityState !== "visible") return;
|
||||
try {
|
||||
const r = await fetch("/api/attention", { cache: "no-store" });
|
||||
if (!r.ok) return;
|
||||
const j = (await r.json()) as { count: number; sound: boolean };
|
||||
sound.current = j.sound;
|
||||
if (j.count > count.current && sound.current) chime();
|
||||
count.current = j.count;
|
||||
apply();
|
||||
} catch {}
|
||||
};
|
||||
const id = setInterval(poll, everyMs);
|
||||
document.addEventListener("visibilitychange", poll);
|
||||
return () => {
|
||||
clearInterval(id);
|
||||
titleObserver.disconnect();
|
||||
document.removeEventListener("visibilitychange", poll);
|
||||
};
|
||||
}, [everyMs]);
|
||||
useLive("attention", (e) => {
|
||||
if (e.type !== "data") return;
|
||||
const d = e.data as { count: number; sound: boolean };
|
||||
sound.current = d.sound;
|
||||
if (d.count > count.current && sound.current) chime();
|
||||
count.current = d.count;
|
||||
apply();
|
||||
});
|
||||
|
||||
// A server re-render (router.refresh) brings a fresh count too.
|
||||
// A server re-render brings a fresh count too.
|
||||
useEffect(() => {
|
||||
if (initial > count.current && sound.current) chime();
|
||||
count.current = initial;
|
||||
document.title = initial > 0 ? `(${initial}) ${document.title.replace(PREFIX, "")}` : document.title.replace(PREFIX, "");
|
||||
apply();
|
||||
}, [initial]);
|
||||
|
||||
return null;
|
||||
|
||||
@ -1,19 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect } from "react";
|
||||
|
||||
/** Re-renders server data every few seconds, unless the user is typing (or left an unsent draft). */
|
||||
export function AutoRefresh({ everyMs = 5000 }: { everyMs?: number }) {
|
||||
const router = useRouter();
|
||||
useEffect(() => {
|
||||
const id = setInterval(() => {
|
||||
const el = document.activeElement;
|
||||
const typing = el instanceof HTMLTextAreaElement || (el instanceof HTMLInputElement && el.type === "text");
|
||||
const draft = [...document.querySelectorAll<HTMLTextAreaElement | HTMLInputElement>("textarea, input[type=text]")].some((i) => i.value !== i.defaultValue);
|
||||
if (!typing && !draft && document.visibilityState === "visible") router.refresh();
|
||||
}, everyMs);
|
||||
return () => clearInterval(id);
|
||||
}, [router, everyMs]);
|
||||
return null;
|
||||
}
|
||||
@ -1,6 +1,6 @@
|
||||
// PEP-23: project autonomy in «⋯ Настройки проекта» — preset levels and the individual settings.
|
||||
import { AUTONOMY_LEVEL_HINT, AUTONOMY_LEVEL_RU, AUTONOMY_LEVELS, autonomyLevel, type AutonomyLevel, type AutonomySettings } from "@peppa/core";
|
||||
import { setAutonomyAction } from "@/app/(app)/actions";
|
||||
import { setAcceptOwnAction, setAutonomyAction } from "@/app/(app)/actions";
|
||||
import { Hidden } from "@/components/cards";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input, Label, NativeSelect } from "@/components/ui/input";
|
||||
@ -28,6 +28,18 @@ export async function AutonomyPanel({ projectId, settings, back, engineer = fals
|
||||
)}
|
||||
</div>
|
||||
<p className="m-0 text-xs text-muted-foreground">{current === "custom" ? t("Своя комбинация настроек ниже.") : t.text(AUTONOMY_LEVEL_HINT[current])}</p>
|
||||
<form action={setAcceptOwnAction} className="flex flex-wrap items-end gap-2">
|
||||
<Hidden fields={{ projectId, back }} />
|
||||
<Label className="min-w-0 flex-1">
|
||||
{t("Принимать сами")}
|
||||
<NativeSelect name="acceptOwn" defaultValue={s.acceptOwn} className="h-11 sm:h-8">
|
||||
<option value="mine">{t("Только мои задачи")}</option>
|
||||
<option value="mine_breakage">{t("Мои задачи и поломки")}</option>
|
||||
<option value="all">{t("Всё, что завела фабрика")}</option>
|
||||
</NativeSelect>
|
||||
</Label>
|
||||
<Button size="sm" variant="outline" className="h-11 sm:h-8">{t("Сохранить")}</Button>
|
||||
</form>
|
||||
{engineer && (
|
||||
<details>
|
||||
<summary className="cursor-pointer text-sm text-primary">{t("Настроить подробно")}</summary>
|
||||
@ -37,11 +49,11 @@ export async function AutonomyPanel({ projectId, settings, back, engineer = fals
|
||||
{t("Кто берёт стори из бэклога")}
|
||||
<NativeSelect name="pick" defaultValue={s.pick} className="h-8">
|
||||
<option value="pm">{t("PM — двигает карточки сам")}</option>
|
||||
<option value="auto">{t("Peppa FACTORY — сама, по порядку на доске")}</option>
|
||||
<option value="auto">{t("FORGE — сама, по порядку на доске")}</option>
|
||||
</NativeSelect>
|
||||
</Label>
|
||||
<Label>
|
||||
{t("Сколько стори в работе одновременно (для «Peppa FACTORY сама»)")}
|
||||
{t("Сколько стори в работе одновременно (для «FORGE сама»)")}
|
||||
<Input name="wipLimit" type="number" min={1} max={5} defaultValue={s.wipLimit} className="h-8" />
|
||||
</Label>
|
||||
<Label>
|
||||
|
||||
@ -4,8 +4,9 @@ import { useWords } from "@/components/Words";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useState, useTransition } from "react";
|
||||
import { useLiveIsland } from "@/lib/live";
|
||||
import { ChevronDown, ChevronRight, ChevronsDown, ChevronsUp, Lock } from "lucide-react";
|
||||
import { moveTaskCard } from "@/app/(app)/actions";
|
||||
import { moveTaskCard, proposalAction } from "@/app/(app)/actions";
|
||||
import { reorderTaskInline } from "@/app/(app)/board-actions";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
@ -17,6 +18,8 @@ import { m } from "@peppa/shared/i18n";
|
||||
export type Column = "backlog" | "in_progress" | "review" | "done";
|
||||
export interface Card {
|
||||
key: string;
|
||||
/** PEP-197: the task id (the buttons of «Предложено» send ids). */
|
||||
id?: number;
|
||||
title: string;
|
||||
status: string;
|
||||
column: Column;
|
||||
@ -28,14 +31,24 @@ export interface Card {
|
||||
blocked?: string | null;
|
||||
/** PEP-75: the persona working on the story right now. */
|
||||
agent?: string | null;
|
||||
/** PEP-84: «продакт» and «аналитик» still hold the story ("уточняется" / "ждёт ваших ответов"). */
|
||||
/** PEP-84 / PEP-198: the analyst still holds the story ("уточняется" / "ждёт ваших ответов"). */
|
||||
refining?: string | null;
|
||||
/** PEP-127: accepted over a conflict — the agent updates the changes, the story closes by itself. */
|
||||
accepted?: string | null;
|
||||
/** PEP-278: accepted, the version with the changes is not running yet. */
|
||||
rollout?: string | null;
|
||||
/** PEP-150: a delay on the platform's side — nothing is needed from the owner. */
|
||||
delayed?: string | null;
|
||||
/** PEP-247: in work without an agent for a lawful reason (pause, no subscription, budget). */
|
||||
hold?: string | null;
|
||||
/** PEP-182: place in the queue for a free agent (in work, no agent yet). */
|
||||
queued?: number | null;
|
||||
/** PEP-197: a story of an agent the owner has not decided on — shown in «Предложено», not in the backlog. */
|
||||
proposed?: boolean;
|
||||
/** PEP-197: «Поломка» / «Важно» / «Мелочь» on stories of the acceptance agent. */
|
||||
severity?: "breakage" | "important" | "minor" | null;
|
||||
/** PEP-197: made by an agent, not by a person. */
|
||||
agentMade?: boolean;
|
||||
}
|
||||
export interface CardProgress {
|
||||
done: number;
|
||||
@ -87,7 +100,25 @@ const NEXT: Partial<Record<Column, { to: Column; label: string }>> = {
|
||||
* starts/stops agents; drag it onto a card of its own column to change the order (= priority
|
||||
* for the dispatcher, PEP-34). «Готово» can be collapsed (remembered in the browser).
|
||||
*/
|
||||
export function Board({ cards, back }: { cards: Card[]; back: string }) {
|
||||
export function Board({ cards: server, back }: { cards: Card[]; back: string }) {
|
||||
// PEP-225: status and title changes from the live channel apply in place — a card moves to the
|
||||
// column of its new status at once; fresh server data (a re-render) replaces the patches.
|
||||
const [patches, setPatches] = useState<Map<number, Pick<Card, "status" | "title" | "column">>>(() => new Map());
|
||||
useEffect(() => setPatches(new Map()), [server]);
|
||||
const cards = patches.size ? server.map((c) => (c.id != null && patches.has(c.id) ? { ...c, ...patches.get(c.id)! } : c)) : server;
|
||||
useLiveIsland((e) => {
|
||||
if (!e.tasks?.length) return [];
|
||||
const byId = new Map(server.map((c) => [c.id, c]));
|
||||
const next: Array<[number, Pick<Card, "status" | "title" | "column">]> = [];
|
||||
let all = true;
|
||||
for (const r of e.tasks) {
|
||||
// A new story, one outside the epic filter, or a change of its epic/order/«Предложено» — the server re-renders.
|
||||
if (!byId.has(r.id) || r.other) all = false;
|
||||
else next.push([r.id, { status: r.status, title: r.title, column: r.column }]);
|
||||
}
|
||||
if (next.length) setPatches((cur) => new Map([...cur, ...next]));
|
||||
return all ? ["t"] : [];
|
||||
});
|
||||
const w = useWords();
|
||||
const router = useRouter();
|
||||
const t = useT();
|
||||
@ -122,6 +153,7 @@ export function Board({ cards, back }: { cards: Card[]; back: string }) {
|
||||
});
|
||||
return (
|
||||
<div className="flex flex-col gap-2">
|
||||
<Proposed cards={cards.filter((x) => x.proposed)} back={back} />
|
||||
{error && (
|
||||
<p role="alert" className="m-0 rounded-md border border-destructive/40 bg-destructive/10 px-3 py-1.5 text-sm text-destructive">
|
||||
{t.text(error)}
|
||||
@ -129,11 +161,12 @@ export function Board({ cards, back }: { cards: Card[]; back: string }) {
|
||||
)}
|
||||
<div className={cn("grid gap-3 sm:grid-cols-2 lg:grid-cols-4", pending && "pointer-events-none opacity-60")}>
|
||||
{COLUMNS.map((c) => {
|
||||
const list = cards.filter((x) => x.column === c.id);
|
||||
const list = cards.filter((x) => x.column === c.id && !x.proposed);
|
||||
const collapsed = c.id === "done" && doneCollapsed;
|
||||
return (
|
||||
<section
|
||||
key={c.id}
|
||||
data-column={c.id}
|
||||
aria-label={t(c.title)}
|
||||
className={cn("flex min-h-32 flex-col gap-2 rounded-lg border bg-muted/40 p-2", over === c.id && "border-dashed border-primary bg-primary/5", collapsed && "min-h-0")}
|
||||
onDragOver={(e) => {
|
||||
@ -202,7 +235,7 @@ export function Board({ cards, back }: { cards: Card[]; back: string }) {
|
||||
)}
|
||||
</div>
|
||||
{card.refining && (
|
||||
<Badge variant="info" className="self-start" title={t("Продакт и аналитик уточняют задачу; агент-разработчик возьмёт её после этого")}>
|
||||
<Badge variant="info" className="self-start" title={t("Аналитик уточняет задачу; агент-разработчик возьмёт её после этого")}>
|
||||
{t.text(card.refining)}
|
||||
</Badge>
|
||||
)}
|
||||
@ -211,16 +244,31 @@ export function Board({ cards, back }: { cards: Card[]; back: string }) {
|
||||
{card.accepted}
|
||||
</Badge>
|
||||
)}
|
||||
{card.rollout && (
|
||||
<Badge variant="info" className="self-start whitespace-normal text-left" data-rollout>
|
||||
{card.rollout}
|
||||
</Badge>
|
||||
)}
|
||||
{card.delayed && (
|
||||
<Badge variant="muted" className="self-start whitespace-normal text-left">
|
||||
{card.delayed}
|
||||
</Badge>
|
||||
)}
|
||||
{card.hold && (
|
||||
<Badge variant="warn" className="self-start whitespace-normal text-left" data-hold>
|
||||
{card.hold}
|
||||
</Badge>
|
||||
)}
|
||||
{card.queued != null && (
|
||||
<Badge variant="muted" className="self-start whitespace-normal text-left" data-queued={card.queued}>
|
||||
{t("В очереди: {n}-я, начнётся, когда освободится агент", { n: card.queued })}
|
||||
</Badge>
|
||||
)}
|
||||
{card.severity === "breakage" && !card.proposed && (
|
||||
<Badge variant="danger" className="self-start" data-severity="breakage">
|
||||
{t("Поломка")}
|
||||
</Badge>
|
||||
)}
|
||||
{card.agent && <AgentBadge name={card.agent} className="text-muted-foreground" />}
|
||||
{card.progress && <ProgressLine p={card.progress} />}
|
||||
{(STATUS[card.status] || NEXT[c.id] || card.epic || card.blocked) && (
|
||||
@ -255,3 +303,91 @@ export function Board({ cards, back }: { cards: Card[]; back: string }) {
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const SEVERITY: Record<string, { label: string; variant: "danger" | "warn" | "muted" }> = {
|
||||
breakage: { label: m("Поломка"), variant: "danger" },
|
||||
important: { label: m("Важно"), variant: "warn" },
|
||||
minor: { label: m("Мелочь"), variant: "muted" },
|
||||
};
|
||||
|
||||
/**
|
||||
* PEP-197: «Предложено» — what the factory suggests on its own. Folded, with a counter; the
|
||||
* dispatcher takes nothing from here. «Делать» sends a story to the backlog, «Не надо» archives
|
||||
* it and the acceptance agent will not suggest it again. Buttons are at least 44 px for a thumb.
|
||||
*/
|
||||
function Proposed({ cards, back }: { cards: Card[]; back: string }) {
|
||||
const t = useT();
|
||||
if (!cards.length) return null;
|
||||
const ids = cards.map((c) => c.id).join(",");
|
||||
const important = cards.filter((c) => c.severity !== "minor");
|
||||
return (
|
||||
<details id="proposed" data-proposed className="rounded-lg border border-dashed bg-muted/30 p-2">
|
||||
<summary className="flex min-h-11 cursor-pointer items-center gap-2 px-1.5 font-mono text-[11px] font-semibold tracking-wider text-muted-foreground uppercase">
|
||||
{t("Предложено")}
|
||||
<span className="ml-auto tabular-nums">{cards.length}</span>
|
||||
</summary>
|
||||
<p className="m-0 px-1.5 pb-2 text-xs text-muted-foreground">{t("Это придумала сама фабрика. Пока вы не нажмёте «Делать», агенты за эти задачи не возьмутся.")}</p>
|
||||
<div className="flex flex-col gap-2">
|
||||
{cards.map((card) => (
|
||||
<article key={card.key} data-task-key={card.key} className="flex flex-col gap-2 rounded-md border bg-card p-2.5 text-sm">
|
||||
<Link href={`/t/${card.key}`} className="text-foreground hover:no-underline">
|
||||
<span className="font-mono text-xs text-primary">{card.key}</span> {card.title}
|
||||
</Link>
|
||||
{card.severity && SEVERITY[card.severity] && (
|
||||
<Badge variant={SEVERITY[card.severity]!.variant} className="self-start">
|
||||
{t(SEVERITY[card.severity]!.label)}
|
||||
</Badge>
|
||||
)}
|
||||
<form action={proposalAction} className="flex flex-wrap gap-2">
|
||||
<input type="hidden" name="ids" value={String(card.id)} />
|
||||
<input type="hidden" name="back" value={back} />
|
||||
<ProposalButtons />
|
||||
</form>
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
{cards.length > 1 && (
|
||||
// PEP-209: several small fixes of one page become one story — fewer stories to accept.
|
||||
<form action={proposalAction} className="mt-2 flex flex-col gap-1.5 rounded-md border bg-card p-2.5 text-sm" data-proposed-merge>
|
||||
<span className="text-xs text-muted-foreground">{t("Отметьте мелкие правки одной страницы — фабрика сделает их одной задачей:")}</span>
|
||||
{cards.map((card) => (
|
||||
<label key={card.key} className="flex min-h-11 items-center gap-2">
|
||||
<input type="checkbox" name="pick" value={card.id} className="size-5" />
|
||||
<span className="font-mono text-xs text-primary">{card.key}</span> {card.title}
|
||||
</label>
|
||||
))}
|
||||
<input type="hidden" name="back" value={back} />
|
||||
<Button size="sm" name="choice" value="merge" className="min-h-11 self-start">
|
||||
{t("Объединить в одну")}
|
||||
</Button>
|
||||
</form>
|
||||
)}
|
||||
<form action={proposalAction} className="mt-2 flex flex-wrap gap-2">
|
||||
<input type="hidden" name="ids" value={ids} />
|
||||
<input type="hidden" name="back" value={back} />
|
||||
{important.length > 0 && (
|
||||
<Button size="sm" name="choice" value="important" className="min-h-11">
|
||||
{t("Делать важные")}
|
||||
</Button>
|
||||
)}
|
||||
<Button size="sm" variant="outline" name="choice" value="none" className="min-h-11">
|
||||
{t("Отклонить всё")}
|
||||
</Button>
|
||||
</form>
|
||||
</details>
|
||||
);
|
||||
}
|
||||
|
||||
function ProposalButtons() {
|
||||
const t = useT();
|
||||
return (
|
||||
<>
|
||||
<Button size="sm" name="choice" value="do" className="min-h-11 min-w-11">
|
||||
{t("Делать")}
|
||||
</Button>
|
||||
<Button size="sm" variant="outline" name="choice" value="no" className="min-h-11 min-w-11">
|
||||
{t("Не надо")}
|
||||
</Button>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@ -1,12 +1,12 @@
|
||||
/** PEP-97: the mark users see — pink tile with a glow + «Peppa FACTORY». */
|
||||
/** PEP-97: the mark users see — blue tile (PEP-239) with a glow + «FORGE». */
|
||||
export function Brand({ large = false }: { large?: boolean }) {
|
||||
return (
|
||||
<span className="flex items-center gap-2.5">
|
||||
<span className={large ? "grid size-10 place-items-center rounded-lg bg-primary font-mono text-lg font-bold text-primary-foreground shadow-[0_0_28px_-4px_var(--primary)]" : "grid size-7 place-items-center rounded-md bg-primary font-mono text-sm font-bold text-primary-foreground shadow-[0_0_18px_-4px_var(--primary)]"}>
|
||||
P
|
||||
F
|
||||
</span>
|
||||
<span className={large ? "font-mono text-2xl font-semibold tracking-tight" : "font-mono text-[15px] font-semibold tracking-tight"}>
|
||||
Peppa <span className="text-primary">FACTORY</span>
|
||||
<span className="text-primary">FORGE</span>
|
||||
</span>
|
||||
</span>
|
||||
);
|
||||
|
||||
176
apps/web/components/ChatLiveFeed.tsx
Normal file
176
apps/web/components/ChatLiveFeed.tsx
Normal file
@ -0,0 +1,176 @@
|
||||
"use client";
|
||||
// PEP-228: new messages of the open conversation drawn in place. The page's chat scope
|
||||
// (`chat:<id>`) brings them ready for this viewer (lib/chat-live.ts); what belongs to this
|
||||
// conversation and needs no buttons is added to the end of the feed at once — no server
|
||||
// re-render. Questions, offers, other threads go to LiveRefresh (the island leaves `m` to it).
|
||||
import { useEffect, useRef, useState, type ReactNode } from "react";
|
||||
import { Bot, MessagesSquare, User as UserIcon } from "lucide-react";
|
||||
import { PRODUCT_NAME } from "@peppa/shared/i18n";
|
||||
import { AgentBadge } from "@/components/AgentBadge";
|
||||
import { Attachments } from "@/components/Attachments";
|
||||
import { ChatScroll } from "@/components/ChatScroll";
|
||||
import { useT } from "@/components/I18n";
|
||||
import { ago, linkify } from "@/lib/format";
|
||||
import { useLiveIsland } from "@/lib/live";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { chatParts, type ChatView, type LiveChatMessage } from "@/lib/chat-live-types";
|
||||
import { markChatReadAction } from "@/app/(app)/chats/actions";
|
||||
|
||||
export function ChatLiveFeed({
|
||||
chatId,
|
||||
lastId,
|
||||
view,
|
||||
userId,
|
||||
compact,
|
||||
showThread,
|
||||
agentName,
|
||||
typing,
|
||||
empty,
|
||||
children,
|
||||
}: {
|
||||
chatId: number;
|
||||
/** The last message the server drew: anything newer is ours to draw. */
|
||||
lastId: number;
|
||||
view: ChatView;
|
||||
userId: number;
|
||||
/** Events as compact lines (threads and «События агентов»). */
|
||||
compact: boolean;
|
||||
showThread: boolean;
|
||||
agentName: string | null;
|
||||
/** «Аналитик печатает…» while the analyst has not answered yet (PEP-110); hidden once an answer is drawn. */
|
||||
typing: ReactNode;
|
||||
/** The server drew no messages (its children are the empty state). */
|
||||
empty: boolean;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const t = useT();
|
||||
const [added, setAdded] = useState<LiveChatMessage[]>([]);
|
||||
const [answered, setAnswered] = useState(false);
|
||||
const read = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const scope = `chat:${chatId}`;
|
||||
const thread = view.kind === "thread" ? view.key : view.kind === "discussion" ? null : undefined;
|
||||
|
||||
// A server re-render drew them itself.
|
||||
const shown = added.filter((m) => m.id > lastId);
|
||||
useEffect(() => setAnswered(false), [lastId]);
|
||||
|
||||
const markRead = () => {
|
||||
if (thread === undefined || read.current) return;
|
||||
read.current = setTimeout(() => {
|
||||
read.current = null;
|
||||
if (document.visibilityState === "visible") void markChatReadAction(chatId, thread).catch(() => {});
|
||||
}, 1000);
|
||||
};
|
||||
useEffect(() => () => {
|
||||
if (read.current) clearTimeout(read.current);
|
||||
}, []);
|
||||
|
||||
useLiveIsland((e) => {
|
||||
if (e.scope !== scope) return [];
|
||||
const { applied, add } = chatParts(e, view);
|
||||
const fresh = add.filter((m) => m.id > lastId);
|
||||
if (fresh.length) {
|
||||
setAdded((was) => {
|
||||
const have = new Set(was.map((m) => m.id));
|
||||
return [...was, ...fresh.filter((m) => !have.has(m.id))].sort((a, b) => a.id - b.id);
|
||||
});
|
||||
if (view.kind === "discussion" && fresh.some((m) => m.authorKind !== "user")) setAnswered(true);
|
||||
markRead();
|
||||
}
|
||||
return applied;
|
||||
});
|
||||
|
||||
const groups: Array<{ events: LiveChatMessage[] } | { m: LiveChatMessage }> = [];
|
||||
for (const m of shown) {
|
||||
const event = compact && (m.kind === "event" || m.kind === "system");
|
||||
const last = groups.at(-1);
|
||||
if (event && last && "events" in last) last.events.push(m);
|
||||
else groups.push(event ? { events: [m] } : { m });
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{!(empty && shown.length) && children}
|
||||
{shown.length > 0 && (
|
||||
<ol data-chat-live className="m-0 flex list-none flex-col gap-2 p-0 pr-12 md:pr-14">
|
||||
{groups.map((g) =>
|
||||
"events" in g ? (
|
||||
<li key={`e${g.events[0]!.id}`} className="flex flex-col gap-1 border-y border-dashed py-1">
|
||||
{g.events.map((m) => (
|
||||
<div key={m.id} data-event-line className="flex items-baseline gap-2 px-1 text-xs text-muted-foreground">
|
||||
<span className="min-w-0 flex-1 break-words">
|
||||
{m.authorKind === "agent" && (m.agent ?? agentName) && <span className="mr-1.5 text-foreground/80">{m.agent ?? agentName}:</span>}
|
||||
{m.main.split("\n")[0]}
|
||||
{m.link && (
|
||||
<a href={m.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(new Date(m.at), t)}</span>
|
||||
</div>
|
||||
))}
|
||||
</li>
|
||||
) : (
|
||||
<li key={g.m.id} className={cn("flex", view.kind === "discussion" && g.m.authorUserId === userId && g.m.kind === "user" ? "justify-end" : "justify-start")}>
|
||||
<div className="min-w-0 max-w-[85%]">
|
||||
<LiveMessage m={g.m} mine={view.kind === "discussion" && g.m.authorUserId === userId} showThread={showThread} agentName={agentName} />
|
||||
</div>
|
||||
</li>
|
||||
),
|
||||
)}
|
||||
</ol>
|
||||
)}
|
||||
{!answered && typing}
|
||||
<div data-chat-end />
|
||||
<ChatScroll lastId={Math.max(lastId, shown.at(-1)?.id ?? 0)} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** The client twin of the page's MessageItem for a message without buttons. */
|
||||
function LiveMessage({ m, mine, showThread, agentName }: { m: LiveChatMessage; mine: boolean; showThread: boolean; agentName: string | null }) {
|
||||
const t = useT();
|
||||
const person = m.authorKind === "user" && m.kind === "user";
|
||||
const agentLabel = m.authorKind === "agent" ? (m.agent ?? agentName) : null;
|
||||
return (
|
||||
<article data-live-message={m.id} 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")}>
|
||||
<div className="flex flex-wrap items-center gap-x-2 gap-y-0.5 text-xs text-muted-foreground">
|
||||
{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.login ?? "?")) : m.authorKind === "agent" ? t("агент") : PRODUCT_NAME}</span>
|
||||
)}
|
||||
{m.via === "telegram" && <span title={t("из Telegram")}>· Telegram</span>}
|
||||
{showThread && m.thread && (
|
||||
<a href={m.thread.href} className="max-w-full truncate">
|
||||
🧵 {m.thread.label}
|
||||
</a>
|
||||
)}
|
||||
{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">{ago(new Date(m.at), t)}</span>
|
||||
</div>
|
||||
<p data-message-main className="m-0 text-sm break-words whitespace-pre-wrap">
|
||||
{linkify(m.main)}
|
||||
</p>
|
||||
{m.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(m.more)}</p>
|
||||
</details>
|
||||
)}
|
||||
<Attachments files={m.files} />
|
||||
{m.link && (
|
||||
<a href={m.link} target={m.link.startsWith("/") ? undefined : "_blank"} rel="noreferrer" className="truncate text-xs">
|
||||
{m.link.startsWith("/") ? t("Открыть") : m.link}
|
||||
</a>
|
||||
)}
|
||||
</article>
|
||||
);
|
||||
}
|
||||
20
apps/web/components/ChatScroll.tsx
Normal file
20
apps/web/components/ChatScroll.tsx
Normal file
@ -0,0 +1,20 @@
|
||||
"use client";
|
||||
// PEP-207: a conversation opens at the first unread message (or at its end); a new message
|
||||
// arriving while the reader is at the bottom keeps them at the bottom.
|
||||
import { useEffect, useRef } from "react";
|
||||
|
||||
export function ChatScroll({ lastId }: { lastId: number }) {
|
||||
const first = useRef(true);
|
||||
useEffect(() => {
|
||||
const end = document.querySelector("[data-chat-end]");
|
||||
if (first.current) {
|
||||
first.current = false;
|
||||
const unread = document.querySelector("[data-first-unread]");
|
||||
(unread ?? end)?.scrollIntoView({ block: unread ? "center" : "end" });
|
||||
return;
|
||||
}
|
||||
const nearBottom = window.innerHeight + window.scrollY >= document.documentElement.scrollHeight - 320;
|
||||
if (nearBottom) end?.scrollIntoView({ block: "end", behavior: "smooth" });
|
||||
}, [lastId]);
|
||||
return null;
|
||||
}
|
||||
20
apps/web/components/ChatSwitch.tsx
Normal file
20
apps/web/components/ChatSwitch.tsx
Normal file
@ -0,0 +1,20 @@
|
||||
"use client";
|
||||
// PEP-207: the project of the chats is picked from a list on top, not from a row of tabs that
|
||||
// doesn't fit on a phone.
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useT } from "@/components/I18n";
|
||||
import { NativeSelect } from "@/components/ui/input";
|
||||
|
||||
export function ChatSwitch({ current, options }: { current: string; options: Array<{ slug: string; label: string }> }) {
|
||||
const router = useRouter();
|
||||
const t = useT();
|
||||
return (
|
||||
<NativeSelect aria-label={t("Проект")} value={current} onChange={(e) => router.push(`/chats/${e.target.value}?list=1`)} className="h-9 w-full">
|
||||
{options.map((o) => (
|
||||
<option key={o.slug} value={o.slug}>
|
||||
{o.label}
|
||||
</option>
|
||||
))}
|
||||
</NativeSelect>
|
||||
);
|
||||
}
|
||||
@ -46,7 +46,7 @@ export async function ChatThreadList({
|
||||
const total = list.waiting.length + list.working.length + list.done.length;
|
||||
const rows = (items: ThreadRow[]) => items.map((r) => <Row key={r.key} r={r} href={href(r.key)} active={active === r.key} />);
|
||||
return (
|
||||
<nav aria-label={t("Треды")} className="flex min-w-0 flex-col gap-0.5 self-start rounded-lg border bg-card/50 p-1.5 text-sm">
|
||||
<nav aria-label={t("Треды")} className="flex w-full min-w-0 flex-col gap-0.5 rounded-lg border bg-card/50 p-1.5 text-sm">
|
||||
<form action={base} method="get" role="search" className="mb-1 flex items-center gap-1">
|
||||
{/* On a phone the answer to a search is the list, not the open conversation. */}
|
||||
<Hidden fields={{ list: 1, ...(raw ? { thread: raw } : {}) }} />
|
||||
|
||||
201
apps/web/components/Errors.tsx
Normal file
201
apps/web/components/Errors.tsx
Normal file
@ -0,0 +1,201 @@
|
||||
// PEP-218: production errors read from Bugsink on the server — summary, filters, rows and the
|
||||
// error card blocks. «Инженер» and the superadmin (`tech`) also see code places, releases,
|
||||
// stacks and tags; «Продакт» — the title, how often, when and the bug task.
|
||||
import Link from "next/link";
|
||||
import { Bug, TrendingUp } from "lucide-react";
|
||||
import type { ErrorDetail, ErrorFilter, ErrorRow, ErrorScope, ErrorsOverview, ErrorState } from "@peppa/core";
|
||||
import { m, type Translator } from "@peppa/shared/i18n";
|
||||
import { Hidden } from "@/components/cards";
|
||||
import { ago, Empty, Key, Notice } from "@/components/common";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card } from "@/components/ui/card";
|
||||
import { Input, NativeSelect } from "@/components/ui/input";
|
||||
import { errorAction } from "@/app/(app)/errors/actions";
|
||||
|
||||
const STATE_LABEL: Record<ErrorState, string> = { unresolved: m("не решена"), resolved: m("решена"), muted: m("приглушена") };
|
||||
const STATE_TONE: Record<ErrorState, "danger" | "ok" | "muted"> = { unresolved: "danger", resolved: "ok", muted: "muted" };
|
||||
|
||||
const hhmm = (d: Date, t: Translator) => d.toLocaleTimeString(t.locale === "en" ? "en-GB" : "ru-RU", { hour: "2-digit", minute: "2-digit" });
|
||||
|
||||
/** Bugsink failed: say so; the data below (if any) is from the cache. */
|
||||
export function ErrorsDown({ down, at, tech, t }: { down: boolean; at: Date | null; tech: boolean; t: Translator }) {
|
||||
if (!down) return null;
|
||||
return (
|
||||
<Notice>
|
||||
{tech
|
||||
? at
|
||||
? // glossary-ignore: «Инженер» and the superadmin only.
|
||||
t("Bugsink не отвечает — показаны данные на {time}.", { time: hhmm(at, t) })
|
||||
: // glossary-ignore: «Инженер» and the superadmin only.
|
||||
t("Bugsink не отвечает, данных пока нет. Загляните через минуту.")
|
||||
: at
|
||||
? t("Учёт ошибок не отвечает — показаны данные на {time}.", { time: hhmm(at, t) })
|
||||
: t("Учёт ошибок не отвечает. Загляните через минуту.")}
|
||||
</Notice>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorStateBadge({ state, t }: { state: ErrorState; t: Translator }) {
|
||||
return <Badge variant={STATE_TONE[state]}>{t(STATE_LABEL[state])}</Badge>;
|
||||
}
|
||||
|
||||
/** Superadmin summary: one line per Bugsink project. */
|
||||
export function ErrorsSummary({ ov, t, hrefFor }: { ov: ErrorsOverview; t: Translator; hrefFor: (bugsinkId: number) => string }) {
|
||||
if (!ov.projects.length) return <Empty>{t("Проектов учёта ошибок нет.")}</Empty>;
|
||||
return (
|
||||
<div className="overflow-x-auto rounded-md border">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="text-left text-xs text-muted-foreground">
|
||||
<tr>
|
||||
<th className="px-3 py-2 font-medium">{t("Проект")}</th>
|
||||
<th className="px-3 py-2 text-right font-medium">{t("Нерешённых")}</th>
|
||||
<th className="px-3 py-2 text-right font-medium">{t("Новых за сутки")}</th>
|
||||
<th className="px-3 py-2 text-right font-medium" title={t("Событий за последний час и в среднем за час прошлых суток")}>{t("За час")}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{ov.projects.map((p) => (
|
||||
<tr key={p.bugsinkId} className="border-t">
|
||||
<td className="px-3 py-2">
|
||||
<Link href={hrefFor(p.bugsinkId)} className="font-medium hover:underline">{p.name}</Link>
|
||||
{p.projectKey ? <Key href={`/p/${p.projectKey}?tab=bugs`} className="ml-2">{p.projectKey}</Key> : <span className="ml-2 text-xs text-muted-foreground">{t("не подключён")}</span>}
|
||||
</td>
|
||||
<td className={`px-3 py-2 text-right tabular-nums ${p.unresolved ? "font-semibold" : "text-muted-foreground"}`}>{p.unresolved}{p.more ? "+" : ""}</td>
|
||||
<td className={`px-3 py-2 text-right tabular-nums ${p.newDay ? "text-destructive" : "text-muted-foreground"}`}>{p.newDay}</td>
|
||||
<td className="px-3 py-2 text-right whitespace-nowrap tabular-nums">
|
||||
{p.growing ? <Badge variant="danger" className="mr-1.5"><TrendingUp className="size-3" />{t("растёт")}</Badge> : null}
|
||||
{p.lastHour} <span className="text-xs text-muted-foreground">/ {p.dayAvg}</span>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Errors as cards; the title opens the error card. */
|
||||
export function ErrorRows({ rows, tech, from, t, showProject = true }: { rows: ErrorRow[]; tech: boolean; from: string; t: Translator; showProject?: boolean }) {
|
||||
if (!rows.length) return <Empty>{t("Ошибок нет.")}</Empty>;
|
||||
return (
|
||||
<div className="flex flex-col gap-2">
|
||||
{rows.map((r) => (
|
||||
<Card key={r.id} className="gap-1 py-2.5">
|
||||
<div className="flex min-w-0 items-start gap-2">
|
||||
<Bug className={`mt-0.5 size-4 shrink-0 ${r.state === "unresolved" ? "text-destructive" : "text-muted-foreground"}`} />
|
||||
<Link href={`/errors/${encodeURIComponent(r.id)}?from=${encodeURIComponent(from)}`} className="line-clamp-2 min-w-0 flex-1 font-medium break-all hover:underline" title={r.title}>{r.title}</Link>
|
||||
{r.state !== "unresolved" ? <ErrorStateBadge state={r.state} t={t} /> : null}
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-x-3 gap-y-1 pl-6 text-xs text-muted-foreground">
|
||||
{tech && r.culprit ? <span className="max-w-full truncate font-mono">{r.culprit}</span> : null}
|
||||
{showProject ? <span>{r.bugsinkName}</span> : null}
|
||||
<span className="tabular-nums">{t.n(r.events, "{n} раз", "{n} раза", "{n} раз")}</span>
|
||||
<span title={r.firstSeen.toLocaleString()}>{t("впервые {ago}", { ago: ago(r.firstSeen, t) })}</span>
|
||||
<span title={r.lastSeen.toLocaleString()}>{t("последний раз {ago}", { ago: ago(r.lastSeen, t) })}</span>
|
||||
{/* glossary-ignore: the release is shown to «Инженер» and the superadmin only */}
|
||||
{tech && r.release ? <span className="font-mono" title={r.release}>{t("релиз {sha}", { sha: r.release.slice(0, 8) })}</span> : null}
|
||||
{r.taskKey ? <Key href={`/t/${r.taskKey}`}>{r.taskKey}</Key> : null}
|
||||
</div>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Filters (GET form): project, state, environment, release, text, order. */
|
||||
export function ErrorFilters({ action, scope, f, keep, t, showProject = true }: { action: string; scope: ErrorScope; f: ErrorFilter; keep: Record<string, string>; t: Translator; showProject?: boolean }) {
|
||||
return (
|
||||
<form action={action} method="get" className="mb-3 flex flex-wrap items-end gap-2 text-sm">
|
||||
{Object.entries(keep).map(([k, v]) => (
|
||||
<input key={k} type="hidden" name={k} value={v} />
|
||||
))}
|
||||
{showProject && scope.projects.length > 1 ? (
|
||||
<NativeSelect name="bp" defaultValue={f.bugsink != null ? String(f.bugsink) : ""} aria-label={t("Проект")} className="w-auto">
|
||||
<option value="">{t("Все проекты")}</option>
|
||||
{scope.projects.map((p) => (
|
||||
<option key={p.bugsinkId} value={p.bugsinkId}>{p.name}</option>
|
||||
))}
|
||||
</NativeSelect>
|
||||
) : null}
|
||||
<NativeSelect name="state" defaultValue={f.state ?? "unresolved"} aria-label={t("Состояние")} className="w-auto">
|
||||
<option value="unresolved">{t("Нерешённые")}</option>
|
||||
<option value="resolved">{t("Решённые")}</option>
|
||||
<option value="muted">{t("Приглушённые")}</option>
|
||||
<option value="all">{t("Все")}</option>
|
||||
</NativeSelect>
|
||||
<NativeSelect name="sort" defaultValue={f.sort ?? "last_seen"} aria-label={t("Порядок")} className="w-auto">
|
||||
<option value="last_seen">{t("Сначала свежие")}</option>
|
||||
<option value="digested_event_count">{t("Сначала частые")}</option>
|
||||
</NativeSelect>
|
||||
{scope.tech ? (
|
||||
<>
|
||||
<Input name="env" defaultValue={f.environment ?? ""} placeholder={t("Окружение")} className="w-32" />
|
||||
{/* glossary-ignore: «Инженер» and the superadmin only */}
|
||||
<Input name="rel" defaultValue={f.release ?? ""} placeholder={t("Релиз")} className="w-32" />
|
||||
</>
|
||||
) : null}
|
||||
<Input name="q" defaultValue={f.q ?? ""} placeholder={t("Поиск по тексту")} className="w-48" />
|
||||
<Button size="sm" variant="secondary">{t("Показать")}</Button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
/** The filter from the page's query string. */
|
||||
export function errorFilterFrom(sp: Record<string, string | undefined>): ErrorFilter {
|
||||
const state = sp.state === "resolved" || sp.state === "muted" || sp.state === "all" ? sp.state : "unresolved";
|
||||
return {
|
||||
bugsink: sp.bp && /^\d+$/.test(sp.bp) ? Number(sp.bp) : undefined,
|
||||
state,
|
||||
environment: sp.env?.trim() || undefined,
|
||||
release: sp.rel?.trim() || undefined,
|
||||
q: sp.q?.trim() || undefined,
|
||||
sort: sp.sort === "digested_event_count" ? "digested_event_count" : "last_seen",
|
||||
cursor: sp.cursor || undefined,
|
||||
};
|
||||
}
|
||||
|
||||
/** «Решено», «Приглушить»/«Вернуть», «Завести задачу» on the error card. */
|
||||
export function ErrorActions({ d, back, t }: { d: ErrorDetail; back: string; t: Translator }) {
|
||||
const btn = (action: string, label: string, variant: "default" | "secondary" | "ghost" = "secondary") => (
|
||||
<form action={errorAction}>
|
||||
<Hidden fields={{ id: d.row.id, action, back }} />
|
||||
<Button size="sm" variant={variant}>{label}</Button>
|
||||
</form>
|
||||
);
|
||||
return (
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{d.row.taskKey ? null : d.projectId != null ? btn("task", t("Завести задачу"), "default") : null}
|
||||
{d.row.state === "resolved" ? btn("reopen", t("Открыть снова")) : btn("resolve", t("Решено"))}
|
||||
{d.row.state === "muted" ? btn("unmute", t("Вернуть")) : d.row.state === "unresolved" ? btn("mute", t("Приглушить"), "ghost") : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Stack frames, innermost first; code around the line where the SDK sent it. */
|
||||
export function ErrorStack({ d, t }: { d: ErrorDetail; t: Translator }) {
|
||||
if (!d.frames.length) return <Empty>{t("Кадров нет.")}</Empty>;
|
||||
return (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
{d.frames.map((f, n) => (
|
||||
<div key={n} className={`rounded-md border px-2.5 py-1.5 ${f.inApp ? "" : "opacity-60"}`}>
|
||||
<div className="font-mono text-xs break-all">
|
||||
<span className="font-semibold">{f.fn ?? "?"}</span> <span className="text-muted-foreground">{f.file}{f.line != null ? `:${f.line}` : ""}</span>
|
||||
</div>
|
||||
{f.context.length ? (
|
||||
<pre className="m-0 mt-1 overflow-x-auto rounded bg-muted px-2 py-1 font-mono text-xs leading-5">
|
||||
{f.context.map(([no, text, hit], k) => (
|
||||
<div key={k} className={hit ? "bg-destructive/15 font-semibold" : ""}>
|
||||
<span className="mr-3 inline-block w-10 text-right text-muted-foreground select-none">{no ?? ""}</span>
|
||||
{text}
|
||||
</div>
|
||||
))}
|
||||
</pre>
|
||||
) : n === 0 ? (
|
||||
<div className="text-xs text-muted-foreground">{t("Кода вокруг строки нет: его не прислали.")}</div>
|
||||
) : null}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
41
apps/web/components/FeatureGate.tsx
Normal file
41
apps/web/components/FeatureGate.tsx
Normal file
@ -0,0 +1,41 @@
|
||||
// PEP-224: a feature that depends on a failing service (Observability) — grey, inactive, with a
|
||||
// plain caption and the time it failed. Available — its children as they are; unstable — the
|
||||
// children with a note «может работать с задержками». For any new feature: pass `featureGateView`.
|
||||
import type { ReactNode } from "react";
|
||||
import { CircleSlash, Clock } from "lucide-react";
|
||||
import { serverTimezone, type FeatureGateView } from "@peppa/core";
|
||||
import { getLocale, getT } from "@/lib/i18n";
|
||||
import { intlLocale } from "@peppa/shared/i18n";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export async function FeatureGate({ view, label, title, children, className }: { view: FeatureGateView; /** The grey button's text (a button-like control). */ label?: ReactNode; /** A grey status instead (an instruction, a section). */ title?: ReactNode; children: ReactNode; className?: string }) {
|
||||
if (view.state === "available") return <>{children}</>;
|
||||
const t = await getT();
|
||||
if (view.state === "degraded")
|
||||
return (
|
||||
<>
|
||||
{children}
|
||||
<p className="m-0 flex items-center gap-1.5 text-xs text-warn" data-feature={view.name} data-feature-state="degraded">
|
||||
<Clock className="size-3.5 shrink-0" /> {t.text(view.text)}
|
||||
</p>
|
||||
</>
|
||||
);
|
||||
const since = view.since ? new Date(view.since).toLocaleTimeString(intlLocale(await getLocale()), { hour: "2-digit", minute: "2-digit", timeZone: serverTimezone() }) : null;
|
||||
return (
|
||||
<div className={cn("flex w-full flex-col gap-1.5", className)} data-feature={view.name} data-feature-state="unavailable">
|
||||
{label ? (
|
||||
<button type="button" disabled aria-disabled="true" className="inline-flex h-10 w-full cursor-not-allowed items-center justify-center gap-2 rounded-md border border-dashed bg-muted px-4 text-sm font-medium text-muted-foreground opacity-80">
|
||||
<CircleSlash className="size-4" /> {label}
|
||||
</button>
|
||||
) : (
|
||||
<div role="status" aria-disabled="true" className="flex items-center gap-2 rounded-lg border border-dashed bg-muted px-4 py-3 text-sm font-medium text-muted-foreground">
|
||||
<CircleSlash className="size-4 shrink-0" /> {title}
|
||||
</div>
|
||||
)}
|
||||
<p className="m-0 text-xs text-muted-foreground">
|
||||
{t.text(view.text)}
|
||||
{since ? " · " + t("с {time}", { time: since }) : ""}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@ -26,6 +26,7 @@ interface Shot {
|
||||
export function FeedbackButton() {
|
||||
const t = useT();
|
||||
const path = usePathname();
|
||||
const inChat = /^\/chats\/[^/]+/.test(path ?? "");
|
||||
const dialog = useRef<HTMLDialogElement>(null);
|
||||
const picker = useRef<HTMLInputElement>(null);
|
||||
const [text, setText] = useState("");
|
||||
@ -123,10 +124,14 @@ export function FeedbackButton() {
|
||||
// Sits above the «в реальном времени» indicator of LiveRefresh (the same corner).
|
||||
title={t("Сообщить о проблеме")}
|
||||
aria-label={t("Сообщить о проблеме")}
|
||||
className="fixed right-3 bottom-[calc(6.5rem+env(safe-area-inset-bottom))] z-30 flex h-10 cursor-pointer items-center gap-2 rounded-full border bg-card px-3 text-sm text-muted-foreground shadow-md transition-colors hover:text-foreground md:bottom-12"
|
||||
className={cn(
|
||||
"fixed right-3 z-30 flex h-10 cursor-pointer items-center gap-2 rounded-full border bg-card px-3 text-sm text-muted-foreground shadow-md transition-colors hover:text-foreground",
|
||||
// PEP-207: in a conversation the message field is pinned to the bottom — the button goes above it, icon only.
|
||||
inChat ? "bottom-[calc(11rem+env(safe-area-inset-bottom))] md:bottom-32" : "bottom-[calc(6.5rem+env(safe-area-inset-bottom))] md:bottom-12",
|
||||
)}
|
||||
>
|
||||
<MessageCircleWarning className="size-5" />
|
||||
<span className="hidden md:inline">{t("Сообщить о проблеме")}</span>
|
||||
{!inChat && <span className="hidden md:inline">{t("Сообщить о проблеме")}</span>}
|
||||
</button>
|
||||
<dialog
|
||||
ref={dialog}
|
||||
@ -162,7 +167,7 @@ export function FeedbackButton() {
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<p className="m-0 text-sm text-muted-foreground">{t("Напишите, что случилось, и приложите скриншот. Обращение увидят те, кто делает Peppa FACTORY, — мы разберёмся и ответим вам.")}</p>
|
||||
<p className="m-0 text-sm text-muted-foreground">{t("Напишите, что случилось, и приложите скриншот. Обращение увидят те, кто делает FORGE, — мы разберёмся и ответим вам.")}</p>
|
||||
<Textarea value={text} onChange={(e) => setText(e.target.value)} rows={4} maxLength={4000} autoFocus placeholder={t("Что случилось? Что вы делали и что ожидали увидеть?")} aria-label={t("Что случилось")} />
|
||||
<div
|
||||
onDragOver={(e) => (e.preventDefault(), setOver(true))}
|
||||
|
||||
@ -12,7 +12,7 @@ export async function Footer() {
|
||||
const dirty = process.env.NEXT_PUBLIC_PEPPA_DIRTY;
|
||||
return (
|
||||
<footer className="px-4 py-6 text-center text-xs text-muted-foreground">
|
||||
Peppa FACTORY v{version}
|
||||
FORGE v{version}
|
||||
{commit && (
|
||||
<>
|
||||
{" · "}
|
||||
|
||||
@ -1,12 +1,12 @@
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
/** «Войти через Google» / «Привязать Google» (PEP-90): обычная форма, браузер уходит на Google. */
|
||||
export function GoogleSignIn({ purpose, next, label }: { purpose: "login" | "link"; next?: string; label: string }) {
|
||||
export function GoogleSignIn({ purpose, next, label, primary = false }: { purpose: "login" | "link"; next?: string; label: string; /** PEP-224: the main way in while eGov is unavailable. */ primary?: boolean }) {
|
||||
return (
|
||||
<form method="post" action="/auth/google/start" className="w-full">
|
||||
<input type="hidden" name="purpose" value={purpose} />
|
||||
{next && <input type="hidden" name="next" value={next} />}
|
||||
<Button type="submit" variant="outline" size="lg" className="w-full">
|
||||
<Button type="submit" variant={primary ? "default" : "outline"} size="lg" className="w-full">
|
||||
<svg aria-hidden viewBox="0 0 48 48" className="size-4">
|
||||
<path fill="#EA4335" d="M24 9.5c3.5 0 6.6 1.2 9.1 3.6l6.8-6.8C35.8 2.4 30.3 0 24 0 14.6 0 6.5 5.4 2.6 13.2l7.9 6.1C12.4 13.6 17.7 9.5 24 9.5z" />
|
||||
<path fill="#4285F4" d="M46.5 24.5c0-1.6-.1-3.1-.4-4.5H24v9h12.7c-.6 3-2.3 5.5-4.8 7.2l7.5 5.8c4.4-4.1 7.1-10.1 7.1-17.5z" />
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
// Project page «Баги» (PEP-58, PEP-66): incidents list (tab) and Bugsink settings (⋯ Настройки проекта).
|
||||
import { Bug, CircleCheck, EyeOff, Inbox, MapPin, Play } from "lucide-react";
|
||||
import { INCIDENT_STATUS_RU, incidentPolicies, POLICY_RU, type ErrorSource, type Incident, type IncidentSettings } from "@peppa/core";
|
||||
import { connectErrorTrackingAction, decideIncidentAction, resolveIncidentAction, saveIncidentSettings } from "@/app/(app)/actions";
|
||||
import { connectErrorTrackingAction, decideIncidentAction, resolveIncidentAction, saveIncidentSettings, setDirectIncidentsAction } from "@/app/(app)/actions";
|
||||
import { Hidden } from "@/components/cards";
|
||||
import { ago, Disclosure, Empty, Key, Section } from "@/components/common";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
@ -61,6 +61,8 @@ export async function IncidentSettingsPanel(props: {
|
||||
settings: IncidentSettings | null;
|
||||
sources: ErrorSource[];
|
||||
webhookUrl: string | null;
|
||||
/** PEP-295: the owner let errors of the product go to work without «Делать». */
|
||||
direct: boolean;
|
||||
w: Words;
|
||||
}) {
|
||||
const { projectId, back, settings: s, w } = props;
|
||||
@ -83,10 +85,35 @@ export async function IncidentSettingsPanel(props: {
|
||||
</div>
|
||||
);
|
||||
}
|
||||
// PEP-295: whether errors go to work without «Делать» is the owner's decision — shown in both views.
|
||||
const direct = (
|
||||
<div className="flex flex-col gap-1.5 text-sm">
|
||||
<span>
|
||||
{props.direct
|
||||
? t("Задачи из ошибок продукта агенты берут в работу сразу, без вашего «Делать».")
|
||||
: t("Задачи из ошибок продукта ждут вашего «Делать» в «Предложено».")}
|
||||
</span>
|
||||
{props.isOwner && (
|
||||
<form action={setDirectIncidentsAction}>
|
||||
<Hidden fields={{ projectId, back, on: props.direct ? "no" : "yes" }} />
|
||||
<Button size="sm" variant="outline">
|
||||
{props.direct ? t("Ждать моего решения") : t("Брать в работу сразу")}
|
||||
</Button>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
// PEP-123: addresses, variables and the policy of incidents are an engineer's settings.
|
||||
if (w.product) return <p className="m-0 text-sm text-muted-foreground">{t("Подключено: ошибки вашего продукта приходят во вкладку «Баги» и становятся задачами для агентов.")}</p>;
|
||||
if (w.product)
|
||||
return (
|
||||
<div className="flex flex-col gap-3">
|
||||
<p className="m-0 text-sm text-muted-foreground">{t("Подключено: ошибки вашего продукта приходят во вкладку «Баги» и становятся задачами для агентов.")}</p>
|
||||
{direct}
|
||||
</div>
|
||||
);
|
||||
return (
|
||||
<div className="flex flex-col gap-3 text-sm">
|
||||
{direct}
|
||||
{props.sources.map((src) => (
|
||||
<div key={src.id} className="flex flex-col gap-1">
|
||||
<span className="font-medium">{src.kind === "web" ? t("DSN фронта (web)") : t("DSN бэка (api)")}</span>
|
||||
@ -101,7 +128,7 @@ export async function IncidentSettingsPanel(props: {
|
||||
<div className="flex flex-col gap-1">
|
||||
<span><b>{t("Вебхук не настроен автоматически.")}</b> {t("В Bugsink: проект → Alerts → Custom webhook:")}</span>
|
||||
<Code>{props.webhookUrl}</Code>
|
||||
<span className="text-muted-foreground">{t("Пока его нет, Peppa FACTORY опрашивает Bugsink раз в 2 минуты.")}</span>
|
||||
<span className="text-muted-foreground">{t("Пока его нет, FORGE опрашивает Bugsink раз в 2 минуты.")}</span>
|
||||
</div>
|
||||
)}
|
||||
<form action={saveIncidentSettings} className="flex flex-col gap-2.5">
|
||||
|
||||
@ -1,24 +1,23 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useEffect, useRef } from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useT } from "@/components/I18n";
|
||||
import { applyIslands, liveClient, useLive, useLiveMode, type LiveEvent, type LiveMode } from "@/lib/live";
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
|
||||
type Mode = "connecting" | "live" | "reconnecting" | "polling";
|
||||
|
||||
const LABEL: Record<Mode, string> = {
|
||||
const LABEL: Record<LiveMode, string> = {
|
||||
connecting: m("подключение…"),
|
||||
live: m("в реальном времени"),
|
||||
reconnecting: m("переподключение…"),
|
||||
polling: m("опрос раз в 5 с"),
|
||||
offline: m("нет связи — пробуем снова"),
|
||||
};
|
||||
const DOT: Record<Mode, string> = {
|
||||
const DOT: Record<LiveMode, string> = {
|
||||
connecting: "bg-muted-foreground",
|
||||
live: "bg-ok",
|
||||
reconnecting: "bg-warn animate-pulse",
|
||||
polling: "bg-warn",
|
||||
offline: "bg-destructive",
|
||||
};
|
||||
|
||||
/** True while the user is typing or left an unsent draft: a refresh must wait. */
|
||||
@ -29,118 +28,81 @@ function busy(): boolean {
|
||||
return typing || draft;
|
||||
}
|
||||
|
||||
/** PEP-215: at most one re-render per tab in this many ms, however many changes the channel reports. */
|
||||
export const MIN_REFRESH_GAP_MS = 4000;
|
||||
|
||||
/**
|
||||
* Live page (PEP-37): listens to /api/live for its scope and re-renders server data when
|
||||
* something there changed (router.refresh keeps client state and typed text). Falls back to
|
||||
* polling every 5 s when the stream can't be opened; shows the connection state.
|
||||
* Live page (PEP-37, PEP-225): watches its scope over the tab's channel. A change the page's
|
||||
* islands apply in place (board cards, the attention counter…) needs nothing more; anything else
|
||||
* re-renders server data (router.refresh keeps client state and typed text) — at most once per
|
||||
* 4 s, never while the person types. Shows the connection state.
|
||||
*/
|
||||
export function LiveRefresh({ scope, pollMs = 5000, pauseHidden = false }: { scope: string; pollMs?: number; pauseHidden?: boolean }) {
|
||||
export function LiveRefresh({
|
||||
scope,
|
||||
pauseHidden = false,
|
||||
indicator = true,
|
||||
}: {
|
||||
scope: string;
|
||||
/** PEP-179: a hidden tab drops the scope (battery) and catches up when back in view. */
|
||||
pauseHidden?: boolean;
|
||||
/** PEP-207: the chat hides the corner pill — it sits over the message field. */
|
||||
indicator?: boolean;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const [mode, setMode] = useState<Mode>("connecting");
|
||||
const pending = useRef(false);
|
||||
const mode = useLiveMode();
|
||||
const t = useT();
|
||||
const state = useRef({ pending: false, timer: null as ReturnType<typeof setTimeout> | null, last: 0 });
|
||||
|
||||
useEffect(() => {
|
||||
let closed = false;
|
||||
let es: EventSource | null = null;
|
||||
let fails = 0;
|
||||
let opened = false;
|
||||
let poll: ReturnType<typeof setInterval> | null = null;
|
||||
let retry: ReturnType<typeof setTimeout> | null = null;
|
||||
let flushTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
// Debounced refresh that waits for the user to finish typing.
|
||||
const flush = () => {
|
||||
flushTimer = null;
|
||||
if (closed || !pending.current) return;
|
||||
if (busy() || document.visibilityState !== "visible") {
|
||||
flushTimer = setTimeout(flush, 2000);
|
||||
return;
|
||||
}
|
||||
pending.current = false;
|
||||
router.refresh();
|
||||
};
|
||||
const request = () => {
|
||||
pending.current = true;
|
||||
if (!flushTimer) flushTimer = setTimeout(flush, 300);
|
||||
};
|
||||
// PEP-179 `pauseHidden`: a hidden tab or a minimised app keeps no stream open (battery);
|
||||
// back in view — reconnect and re-read at once.
|
||||
const pause = () => {
|
||||
es?.close();
|
||||
es = null;
|
||||
if (poll) clearInterval(poll);
|
||||
poll = null;
|
||||
if (retry) clearTimeout(retry);
|
||||
retry = null;
|
||||
};
|
||||
const onVisible = () => {
|
||||
const visible = document.visibilityState === "visible";
|
||||
if (pauseHidden) {
|
||||
if (!visible) return pause();
|
||||
if (!es && !poll) {
|
||||
fails = 0;
|
||||
connect();
|
||||
pending.current = true;
|
||||
return request();
|
||||
}
|
||||
}
|
||||
if (visible && pending.current) request();
|
||||
};
|
||||
|
||||
const startPolling = () => {
|
||||
if (poll) return;
|
||||
setMode("polling");
|
||||
poll = setInterval(request, pollMs);
|
||||
// Try the stream again now and then.
|
||||
retry = setTimeout(() => {
|
||||
if (poll) clearInterval(poll);
|
||||
poll = null;
|
||||
fails = 0;
|
||||
connect();
|
||||
}, 30_000);
|
||||
};
|
||||
|
||||
const connect = () => {
|
||||
if (closed) return;
|
||||
if (typeof EventSource === "undefined") return startPolling();
|
||||
es = new EventSource(`/api/live?scope=${encodeURIComponent(scope)}`);
|
||||
es.addEventListener("ready", () => {
|
||||
// Back after a drop: changes may have been missed.
|
||||
if (opened) request();
|
||||
opened = true;
|
||||
fails = 0;
|
||||
setMode("live");
|
||||
});
|
||||
es.addEventListener("change", request);
|
||||
es.onerror = () => {
|
||||
if (closed) return;
|
||||
fails++;
|
||||
if (fails >= 3 || es?.readyState === EventSource.CLOSED) {
|
||||
es?.close();
|
||||
es = null;
|
||||
startPolling();
|
||||
} else setMode("reconnecting");
|
||||
};
|
||||
};
|
||||
|
||||
if (!pauseHidden || document.visibilityState === "visible") connect();
|
||||
document.addEventListener("visibilitychange", onVisible);
|
||||
const s = state.current;
|
||||
return () => {
|
||||
closed = true;
|
||||
es?.close();
|
||||
if (poll) clearInterval(poll);
|
||||
if (retry) clearTimeout(retry);
|
||||
if (flushTimer) clearTimeout(flushTimer);
|
||||
document.removeEventListener("visibilitychange", onVisible);
|
||||
if (s.timer) clearTimeout(s.timer);
|
||||
s.timer = null;
|
||||
};
|
||||
}, [router, scope, pollMs, pauseHidden]);
|
||||
}, []);
|
||||
|
||||
const flush = () => {
|
||||
const s = state.current;
|
||||
s.timer = null;
|
||||
if (!s.pending) return;
|
||||
// Offline a re-render fails into a full navigation to the browser's error page: wait for the channel.
|
||||
if (busy() || document.visibilityState !== "visible" || !navigator.onLine || liveClient().mode !== "live") {
|
||||
s.timer = setTimeout(flush, 2000);
|
||||
return;
|
||||
}
|
||||
const wait = s.last + MIN_REFRESH_GAP_MS - Date.now();
|
||||
if (wait > 0) {
|
||||
s.timer = setTimeout(flush, wait);
|
||||
return;
|
||||
}
|
||||
s.pending = false;
|
||||
s.last = Date.now();
|
||||
router.refresh();
|
||||
};
|
||||
const request = () => {
|
||||
const s = state.current;
|
||||
s.pending = true;
|
||||
if (!s.timer) s.timer = setTimeout(flush, 300);
|
||||
};
|
||||
|
||||
useLive(
|
||||
scope,
|
||||
(e: LiveEvent) => {
|
||||
if (e.type !== "change") return;
|
||||
const applied = applyIslands(e);
|
||||
if (e.parts.every((p) => applied.has(p))) return;
|
||||
request();
|
||||
},
|
||||
{ heavy: pauseHidden },
|
||||
);
|
||||
|
||||
if (!indicator) return null;
|
||||
return (
|
||||
<div
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
title={mode === "polling" ? t("Канал событий недоступен — страница обновляется по таймеру") : t("Страница обновляется сама, когда что-то меняется")}
|
||||
data-live-mode={mode}
|
||||
title={mode === "offline" ? t("Нет связи с FORGE — страница обновится, когда связь вернётся") : t("Страница обновляется сама, когда что-то меняется")}
|
||||
className="pointer-events-none fixed right-3 bottom-[calc(4.25rem+env(safe-area-inset-bottom))] z-40 md:bottom-3 flex items-center gap-1.5 rounded-full border bg-background/90 px-2.5 py-1 font-mono text-[11px] text-muted-foreground shadow-sm backdrop-blur"
|
||||
>
|
||||
<span className={cn("size-1.5 rounded-full", DOT[mode])} />
|
||||
|
||||
26
apps/web/components/LiveTaskStatus.tsx
Normal file
26
apps/web/components/LiveTaskStatus.tsx
Normal file
@ -0,0 +1,26 @@
|
||||
"use client";
|
||||
// PEP-225: the story's status badge, updated in place from the live channel (`task:<id>` rows) —
|
||||
// the rest of the page follows with the next server re-render.
|
||||
import { useState, useEffect } from "react";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { useT } from "@/components/I18n";
|
||||
import { useLiveIsland } from "@/lib/live";
|
||||
import { TASK_STATUS } from "@/lib/status";
|
||||
|
||||
export function LiveTaskStatus({ taskId, status: initial, rollout = false }: { taskId: number; status: string; /** PEP-278: done, the version with the changes is not running yet. */ rollout?: boolean }) {
|
||||
const t = useT();
|
||||
const [status, setStatus] = useState(initial);
|
||||
useEffect(() => setStatus(initial), [initial]);
|
||||
useLiveIsland((e) => {
|
||||
const row = e.tasks?.find((r) => r.id === taskId);
|
||||
if (row) setStatus(row.status);
|
||||
return []; // the page around depends on the status too
|
||||
});
|
||||
const shown = status === "done" && rollout ? "rollout" : status;
|
||||
const s = TASK_STATUS[shown] ?? { label: shown, tone: "muted" as const };
|
||||
return (
|
||||
<Badge variant={s.tone} data-live-status={shown}>
|
||||
{t.text(s.label)}
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
128
apps/web/components/Observability.tsx
Normal file
128
apps/web/components/Observability.tsx
Normal file
@ -0,0 +1,128 @@
|
||||
// Observability (PEP-202): shared pieces of the monitors list and the monitor page.
|
||||
// glossary-ignore-file: the section is for the superadmin only.
|
||||
import { durationText, FEATURE_NAMES, FEATURES, type MonitorKind, type MonitorState, type MonitorView } from "@peppa/core";
|
||||
import type { Translator } from "@peppa/shared/i18n";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Input, Label, NativeSelect } from "@/components/ui/input";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
|
||||
export const KIND_LABEL: Record<MonitorKind, string> = { http: "HTTP(S)", tcp: "TCP", dns: "DNS", internet: m("Интернет"), heartbeat: "Heartbeat" };
|
||||
const STATE_LABEL: Record<MonitorState, string> = { up: m("работает"), down: m("не работает"), degraded: m("нестабилен"), unknown: m("проверяется") };
|
||||
const STATE_VARIANT = { up: "ok", down: "danger", degraded: "warn", unknown: "muted" } as const;
|
||||
|
||||
export function StateBadge({ m, t }: { m: Pick<MonitorView, "state" | "paused">; t: Translator }) {
|
||||
if (m.paused) return <Badge variant="muted">{t("на паузе")}</Badge>;
|
||||
return <Badge variant={STATE_VARIANT[m.state]}>{t(STATE_LABEL[m.state])}</Badge>;
|
||||
}
|
||||
|
||||
export const pct = (v: number | null) => (v == null ? "—" : `${(v * 100).toFixed(v >= 0.9995 ? 0 : 2)}%`);
|
||||
|
||||
/** The last checks as a strip of bars, oldest left. */
|
||||
export function CheckStrip({ recent, t }: { recent: MonitorView["recent"]; t: Translator }) {
|
||||
return (
|
||||
<div className="flex h-5 items-end gap-px" aria-label={t("Последние проверки")}>
|
||||
{Array.from({ length: Math.max(0, 30 - recent.length) }, (_, i) => (
|
||||
<span key={`e${i}`} className="h-full w-1.5 rounded-sm bg-muted" />
|
||||
))}
|
||||
{recent.map((c) => (
|
||||
<span key={c.at} title={new Date(c.at).toLocaleString("ru-RU")} className={cn("h-full w-1.5 rounded-sm", !c.ok ? "bg-destructive" : c.degraded ? "bg-warn" : "bg-ok")} />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Fields of the create / edit form; `where` is read by the kind (address, host, host:port, hosts). */
|
||||
export function MonitorFields({ t, m, kindFixed, remindDefault }: { t: Translator; m?: MonitorView; kindFixed?: boolean; remindDefault: number }) {
|
||||
const tg = (m?.target ?? {}) as Record<string, unknown>;
|
||||
const where = !m ? "" : m.kind === "http" ? String(tg.url) : m.kind === "tcp" ? `${tg.host}:${tg.port}` : m.kind === "dns" ? String(tg.host) : m.kind === "internet" ? (tg.hosts as string[]).join(", ") : "";
|
||||
return (
|
||||
<div className="grid gap-2 sm:grid-cols-2">
|
||||
<Label>
|
||||
{t("Название")}
|
||||
<Input name="name" required maxLength={80} defaultValue={m?.name} placeholder="eGov relay" className="h-8" />
|
||||
</Label>
|
||||
<Label>
|
||||
{t("Вид")}
|
||||
{kindFixed && m ? (
|
||||
<>
|
||||
<input type="hidden" name="kind" value={m.kind} />
|
||||
<Input value={t(KIND_LABEL[m.kind])} disabled className="h-8" />
|
||||
</>
|
||||
) : (
|
||||
<NativeSelect name="kind" defaultValue={m?.kind ?? "http"} className="h-8">
|
||||
{(Object.keys(KIND_LABEL) as MonitorKind[]).map((k) => (
|
||||
<option key={k} value={k}>{t(KIND_LABEL[k])}</option>
|
||||
))}
|
||||
</NativeSelect>
|
||||
)}
|
||||
</Label>
|
||||
<Label className="sm:col-span-2">
|
||||
{t("Адрес")}
|
||||
<Input name="where" defaultValue={where} placeholder={t("https://… · хост · хост:порт · адреса через запятую (у heartbeat пусто)")} className="h-8 font-mono" />
|
||||
</Label>
|
||||
<Label>
|
||||
{t("Проверять раз в, с")}
|
||||
<Input name="intervalSec" type="number" min={30} defaultValue={m?.intervalSec ?? 60} className="h-8" />
|
||||
</Label>
|
||||
<Label>
|
||||
{t("Текст в ответе (HTTP)")}
|
||||
<Input name="contains" defaultValue={String(tg.contains ?? "")} className="h-8" />
|
||||
</Label>
|
||||
<Label>
|
||||
{t("Коды ответа (HTTP), через запятую")}
|
||||
<Input name="expectStatus" defaultValue={Array.isArray(tg.expectStatus) ? (tg.expectStatus as number[]).join(", ") : ""} placeholder="200–399" className="h-8" />
|
||||
</Label>
|
||||
<Label>
|
||||
{t("Медленнее, мс — нестабилен (HTTP)")}
|
||||
<Input name="maxLatencyMs" type="number" min={1} defaultValue={tg.maxLatencyMs != null ? String(tg.maxLatencyMs) : ""} className="h-8" />
|
||||
</Label>
|
||||
<Label>
|
||||
{t("Неудач подряд до «не работает»")}
|
||||
<Input name="failThreshold" type="number" min={1} max={20} defaultValue={m?.failThreshold ?? 3} className="h-8" />
|
||||
</Label>
|
||||
<Label>
|
||||
{t("Удач подряд до «работает»")}
|
||||
<Input name="recoverThreshold" type="number" min={1} max={20} defaultValue={m?.recoverThreshold ?? 2} className="h-8" />
|
||||
</Label>
|
||||
<Label>
|
||||
{t("Напоминать раз в, мин (0 — не напоминать)")}
|
||||
<Input name="remindMin" type="number" min={0} max={1440} defaultValue={m?.remindMin != null ? String(m.remindMin) : ""} placeholder={String(remindDefault)} className="h-8" />
|
||||
</Label>
|
||||
<label className="flex items-center gap-2 self-end pb-1.5 text-sm">
|
||||
<input type="checkbox" name="remindDegraded" value="1" defaultChecked={m?.remindDegraded ?? false} />
|
||||
{t("Напоминать и когда нестабилен")}
|
||||
</label>
|
||||
<Label>
|
||||
{t("Запас heartbeat, с")}
|
||||
<Input name="graceSec" type="number" min={0} defaultValue={tg.graceSec != null ? String(tg.graceSec) : ""} placeholder="60" className="h-8" />
|
||||
</Label>
|
||||
<fieldset className="m-0 flex flex-col gap-1 border-0 p-0 sm:col-span-2">
|
||||
<legend className="mb-1 text-sm font-medium">{t("Что отключать при сбое")}</legend>
|
||||
<span className="flex flex-wrap gap-x-4 gap-y-1">
|
||||
{FEATURE_NAMES.map((f) => (
|
||||
<label key={f} className="flex items-center gap-1.5 text-sm">
|
||||
<input type="checkbox" name="features" value={f} defaultChecked={m?.features.includes(f)} className="size-4 accent-primary" />
|
||||
{t(FEATURES[f].label)}
|
||||
</label>
|
||||
))}
|
||||
</span>
|
||||
</fieldset>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** PEP-223: «не работает 1 ч 30 мин · напоминаний: 3 · следующее в 14:30». */
|
||||
export function OutageLine({ m, t, now = new Date() }: { m: MonitorView; t: Translator; now?: Date }) {
|
||||
if (!m.outage || m.paused || (m.state !== "down" && m.state !== "degraded")) return null;
|
||||
const o = m.outage;
|
||||
const duration = t.text(durationText(now.getTime() - Date.parse(o.startedAt)));
|
||||
const parts = [
|
||||
m.state === "down" ? t("не работает {duration}", { duration }) : t("нестабилен {duration}", { duration }),
|
||||
t("напоминаний: {n}", { n: o.reminders }),
|
||||
o.nextRemindAt ? t("следующее в {time}", { time: hhmm(o.nextRemindAt) }) : o.quiet ? t("без напоминаний: вместе с интернетом") : t("без напоминаний"),
|
||||
];
|
||||
return <span className={m.state === "down" ? "text-destructive" : "text-warn"}>{parts.join(" · ")}</span>;
|
||||
}
|
||||
|
||||
const hhmm = (iso: string) => new Date(iso).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit", timeZone: process.env.PEPPA_TZ || undefined });
|
||||
@ -2,6 +2,7 @@
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useLive } from "@/lib/live";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { pairingLinkAction } from "@/app/(app)/actions";
|
||||
import { useT } from "@/components/I18n";
|
||||
@ -9,7 +10,7 @@ import { useT } from "@/components/I18n";
|
||||
/**
|
||||
* PEP-100: opens the user's bot (with the pairing code) in a new tab / the Telegram app and keeps
|
||||
* Peppa open — a plain redirect used to take the page away mid-steps. While the user presses
|
||||
* Start, the page refreshes itself so the step turns done.
|
||||
* Start, the live channel tells the page, and it re-renders so the step turns done.
|
||||
*/
|
||||
export function OpenBotButton({ label, variant = "default", size = "sm" }: { label: string; variant?: "default" | "ghost" | "outline"; size?: "sm" | "xs" }) {
|
||||
const t = useT();
|
||||
@ -20,13 +21,13 @@ export function OpenBotButton({ label, variant = "default", size = "sm" }: { lab
|
||||
|
||||
useEffect(() => {
|
||||
if (!waiting) return;
|
||||
const timer = setInterval(() => router.refresh(), 3000);
|
||||
const stop = setTimeout(() => setWaiting(false), 3 * 60_000);
|
||||
return () => {
|
||||
clearInterval(timer);
|
||||
clearTimeout(stop);
|
||||
};
|
||||
}, [waiting, router]);
|
||||
return () => clearTimeout(stop);
|
||||
}, [waiting]);
|
||||
// PEP-225: the binding (`me`) changes when the user presses Start in the bot — re-render then.
|
||||
useLive(waiting ? "me" : null, (e) => {
|
||||
if (e.type === "change") router.refresh();
|
||||
});
|
||||
|
||||
async function open() {
|
||||
setError(null);
|
||||
|
||||
@ -99,7 +99,7 @@ export async function OwnBotSteps({ botUsername, back, bare = false }: { botUser
|
||||
<>
|
||||
<span className="text-muted-foreground">
|
||||
{rich(
|
||||
t("Токен выглядит так: {sample} (цифры, двоеточие, буквы). Вставьте его сюда — Peppa FACTORY хранит его зашифрованным и никому не показывает. Никому, кроме Peppa FACTORY, токен не отправляйте."),
|
||||
t("Токен выглядит так: {sample} (цифры, двоеточие, буквы). Вставьте его сюда — FORGE хранит его зашифрованным и никому не показывает. Никому, кроме FORGE, токен не отправляйте."),
|
||||
{ sample: <span className="font-mono">1234567890:AAH…</span> },
|
||||
)}
|
||||
</span>
|
||||
|
||||
@ -1,30 +1,49 @@
|
||||
import Link from "next/link";
|
||||
import { DELAY_REASON_NAMES, type DelayView } from "@peppa/core";
|
||||
import { delayActionForm } from "@/app/(app)/dashboard/actions";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Key } from "@/components/common";
|
||||
import { getT } from "@/lib/i18n";
|
||||
|
||||
/**
|
||||
* PEP-150: what is held up on the platform's side right now — the superadmin's list on the
|
||||
* home page. Owners see one line on the story instead; a row leaves when its cause is gone.
|
||||
* PEP-150/209: what is held up on the platform's side — the superadmin's list in «Дашборд →
|
||||
* Задержки». Owners see one line on the story instead; a row leaves when its cause is gone.
|
||||
* With `actions` every card has «Перезапустить», «Перевести на ревью» (story cards) and «Закрыть».
|
||||
*/
|
||||
export async function PlatformDelays({ delays }: { delays: DelayView[] }) {
|
||||
export async function PlatformDelays({ delays, actions = false }: { delays: DelayView[]; actions?: boolean }) {
|
||||
const t = await getT();
|
||||
const hhmm = (ms: number) => new Date(ms).toLocaleString("ru-RU", { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit" });
|
||||
const hhmm = (ms: number) => new Date(ms).toLocaleString("ru-RU", { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit", timeZone: process.env.PEPPA_TZ || undefined });
|
||||
return (
|
||||
<ul className="m-0 flex list-none flex-col gap-2 p-0">
|
||||
<ul className="m-0 flex list-none flex-col gap-2 p-0" data-delays>
|
||||
{delays.map((d) => (
|
||||
<li key={`${d.key}:${d.reason}`} className="rounded-lg border bg-card px-3 py-2 text-sm">
|
||||
<li key={`${d.key}:${d.reason}`} className="rounded-lg border bg-card px-3 py-2 text-sm" data-delay={d.reason}>
|
||||
<div className="flex flex-wrap items-center gap-x-2 gap-y-1">
|
||||
<Link href={d.url} className="hover:underline">
|
||||
<Key>{d.key}</Key>
|
||||
</Link>
|
||||
<span className="font-medium">{t.text(DELAY_REASON_NAMES[d.reason])}</span>
|
||||
{d.exhausted ? <Badge variant="danger">{t("нужна ваша помощь")}</Badge> : <Badge variant="muted">{t("Peppa FACTORY пробует сама")}</Badge>}
|
||||
{d.exhausted ? <Badge variant="danger">{t("нужен администратор")}</Badge> : <Badge variant="muted">{t("FORGE пробует сама")}</Badge>}
|
||||
<span className="text-xs text-muted-foreground">{t("с {time} · попыток: {n}", { time: hhmm(d.since), n: d.attempts })}</span>
|
||||
{!d.exhausted && d.retryAt != null && <span className="text-xs text-muted-foreground">{t("следующая попытка: {time}", { time: hhmm(d.retryAt) })}</span>}
|
||||
</div>
|
||||
{d.title && <div className="text-muted-foreground">{d.title}</div>}
|
||||
<p className="m-0 mt-1 line-clamp-3 whitespace-pre-wrap break-words text-xs text-muted-foreground">{t.text(d.details)}</p>
|
||||
{actions && (
|
||||
<div className="mt-2 flex flex-wrap gap-2">
|
||||
{(["restart", ...(d.taskId != null ? ["review"] : []), "close"] as const).map((a) => (
|
||||
<form key={a} action={delayActionForm}>
|
||||
<input type="hidden" name="project" value={d.projectId} />
|
||||
{d.taskId != null && <input type="hidden" name="task" value={d.taskId} />}
|
||||
<input type="hidden" name="reason" value={d.reason} />
|
||||
<input type="hidden" name="action" value={a} />
|
||||
<Button size="sm" variant={a === "close" ? "outline" : "secondary"} data-delay-action={a}>
|
||||
{a === "restart" ? t("Перезапустить") : a === "review" ? t("Перевести на ревью") : t("Закрыть")}
|
||||
</Button>
|
||||
</form>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
@ -71,14 +71,17 @@ export async function ProductCard({
|
||||
{link ? (
|
||||
<div className="flex flex-wrap items-center gap-x-4 gap-y-3">
|
||||
<div className="flex min-w-0 flex-1 basis-full flex-col gap-0.5 sm:basis-0">
|
||||
<span className="text-[15px] font-semibold">{live ? t("Ваш продукт работает") : t("Ваш продукт готов — пока его видите только вы")}</span>
|
||||
<span className="flex flex-wrap items-center gap-2 text-[15px] font-semibold">
|
||||
{live ? t("Ваш продукт работает") : t("Ваш продукт готов — пока его видите только вы")}
|
||||
{product.versionDone && <span data-version-done className="rounded-full bg-ok/15 px-2 py-0.5 text-xs font-medium text-ok">{t("Готово")}</span>}
|
||||
</span>
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{live ? t("Открыт для всех по адресу") : t("Адрес:")} <span className="font-mono text-foreground [overflow-wrap:anywhere]">{host(link.url)}</span> · {t("обновлён {when}", { when: ago(link.at, t) })}
|
||||
{link.stories.length > 0 && <> · {t("вошли {tasks} {keys}", { tasks: task("pl"), keys: link.stories.slice(0, 6).join(", ") })}</>}
|
||||
</span>
|
||||
{!live && (
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{publish === "auto" ? t("Когда задачи этой версии будут приняты, Peppa FACTORY сама покажет её всем.") : <>{t("Посмотрите — и, если всё хорошо,")} {showAll}</>}
|
||||
{publish === "auto" ? t("Когда задачи этой версии будут приняты, FORGE сама покажет её всем.") : <>{t("Посмотрите — и, если всё хорошо,")} {showAll}</>}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
@ -126,7 +129,7 @@ export async function ProductCard({
|
||||
<a href={check.url} target="_blank" rel="noreferrer">
|
||||
{host(check.url)}
|
||||
</a>
|
||||
{check.stories.length > 0 && <span className="text-muted-foreground">({check.stories.slice(0, 6).join(", ")})</span>} — {publish === "auto" ? t("Peppa FACTORY покажет её всем сама, когда задачи будут приняты.") : showAll}
|
||||
{check.stories.length > 0 && <span className="text-muted-foreground">({check.stories.slice(0, 6).join(", ")})</span>} — {publish === "auto" ? t("FORGE покажет её всем сама, когда задачи будут приняты.") : showAll}
|
||||
</p>
|
||||
)}
|
||||
{open.length > 0 && (
|
||||
@ -135,7 +138,7 @@ export async function ProductCard({
|
||||
{deployed ? t("Работает в демо-режиме — чтобы заработало по-настоящему, нужно от вас:") : t("Продукт будет работать в демо-режиме — чтобы заработало по-настоящему, нужно от вас:")}
|
||||
</span>
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{t("Пока этого нет, продукт показывает примеры вместо настоящей работы. Ключи хранятся зашифрованными; Peppa FACTORY сама передаст их продукту и перезапустит его — через пару минут после сохранения.")}
|
||||
{t("Пока этого нет, продукт показывает примеры вместо настоящей работы. Ключи хранятся зашифрованными; FORGE сама передаст их продукту и перезапустит его — через пару минут после сохранения.")}
|
||||
</span>
|
||||
<ul className="m-0 flex list-none flex-col gap-2 p-0">
|
||||
{open.map((n) => (
|
||||
@ -199,7 +202,7 @@ export async function ProductCard({
|
||||
</div>
|
||||
)}
|
||||
<p className="m-0 text-xs text-muted-foreground">
|
||||
{t("Продукт посмотрел продакт-агент {when} — подробности в", { when: ago(new Date(review.at), t) })} <Link href={`/chats/${projectKey}`}>{t("обсуждении проекта")}</Link>.
|
||||
{t("Продукт посмотрел агент приёмки {when} — подробности в", { when: ago(new Date(review.at), t) })} <Link href={`/chats/${projectKey}`}>{t("обсуждении проекта")}</Link>.
|
||||
</p>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
32
apps/web/components/ProjectErrors.tsx
Normal file
32
apps/web/components/ProjectErrors.tsx
Normal file
@ -0,0 +1,32 @@
|
||||
// PEP-218: the project's tab «Баги» — errors of its own Bugsink projects (`<KEY>-web` /
|
||||
// `<KEY>-api`), read on the server, in the same view as the superadmin's /observability.
|
||||
import Link from "next/link";
|
||||
import { errorScope, listErrors } from "@peppa/core";
|
||||
import { ErrorFilters, errorFilterFrom, ErrorRows, ErrorsDown } from "@/components/Errors";
|
||||
import { Section } from "@/components/common";
|
||||
import { requireUser } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { getT } from "@/lib/i18n";
|
||||
|
||||
export type ErrorSearch = { bp?: string; state?: string; env?: string; rel?: string; q?: string; sort?: string; cursor?: string };
|
||||
|
||||
export async function ProjectErrors({ projectId, projectKey, sp }: { projectId: number; projectKey: string; sp: ErrorSearch }) {
|
||||
const user = await requireUser();
|
||||
const t = await getT();
|
||||
const scope = await errorScope(db, user, { projectId });
|
||||
if (!scope.projects.length) return null;
|
||||
const f = errorFilterFrom(sp);
|
||||
const list = await listErrors(db, scope, f);
|
||||
const query = new URLSearchParams(Object.entries({ tab: "bugs", 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 = `/p/${projectKey}?${query}`;
|
||||
return (
|
||||
<Section title={t("Ошибки продукта")} count={list.rows.length}>
|
||||
<ErrorsDown down={list.down} at={list.at} tech={scope.tech} t={t} />
|
||||
<ErrorFilters action={`/p/${projectKey}`} scope={scope} f={f} keep={{ tab: "bugs" }} t={t} showProject={scope.tech} />
|
||||
<ErrorRows rows={list.rows} tech={scope.tech} from={from} t={t} showProject={scope.tech} />
|
||||
{list.next ? (
|
||||
<Link href={`/p/${projectKey}?${new URLSearchParams([...query, ["cursor", list.next]])}`} className="mt-2 inline-block text-sm text-primary hover:underline">{t("Дальше →")}</Link>
|
||||
) : null}
|
||||
</Section>
|
||||
);
|
||||
}
|
||||
@ -3,9 +3,10 @@ import type { ProjectSecretView } from "@peppa/core";
|
||||
import { Hidden } from "@/components/cards";
|
||||
import { ago } from "@/components/common";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input, Textarea } from "@/components/ui/input";
|
||||
import { Textarea } from "@/components/ui/input";
|
||||
import { SecretNameHint } from "@/components/SecretNameHint";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import { deleteProjectSecretAction, saveProjectSecretAction } from "@/app/(app)/actions";
|
||||
import { deleteProjectSecretAction, saveProjectSecretAction, secretToConnectionAction, setAgentSecretsAction, setSecretAudienceAction } from "@/app/(app)/actions";
|
||||
import { Fragment, type ReactNode } from "react";
|
||||
|
||||
/** A translated sentence with {name} placeholders replaced by inline elements. */
|
||||
@ -13,44 +14,121 @@ function rich(text: string, parts: Record<string, ReactNode>): ReactNode {
|
||||
return text.split(/\{(\w+)\}/).map((piece, i) => <Fragment key={i}>{i % 2 ? (parts[piece] ?? `{${piece}}`) : piece}</Fragment>);
|
||||
}
|
||||
|
||||
/** PEP-54: the project's secrets for agents and (PEP-112) for the deployed product — names only; values are write-only. */
|
||||
export async function ProjectSecretsPanel({ projectId, secrets, back }: { projectId: number; secrets: ProjectSecretView[]; back: string }) {
|
||||
/**
|
||||
* PEP-54: the project's secrets for agents and (PEP-112) for the deployed product — names only; values are write-only.
|
||||
* PEP-253: where each secret goes (only the product / also agents), the project setting «Агенты получают секреты
|
||||
* в окружение», and keys of catalog services with «Сделать подключением».
|
||||
*/
|
||||
export async function ProjectSecretsPanel({
|
||||
projectId,
|
||||
secrets,
|
||||
back,
|
||||
agentsEnabled,
|
||||
services,
|
||||
hints,
|
||||
engineer,
|
||||
}: {
|
||||
projectId: number;
|
||||
secrets: ProjectSecretView[];
|
||||
back: string;
|
||||
agentsEnabled: boolean;
|
||||
/** secret name → the recognised catalog service and the connection it became. */
|
||||
services: Map<string, { serviceName: string | null; connectionName: string | null }>;
|
||||
hints: Array<{ prefix: string; exact: boolean; service: string }>;
|
||||
engineer: boolean;
|
||||
}) {
|
||||
const t = await getT();
|
||||
return (
|
||||
<div className="flex flex-col gap-3">
|
||||
<form action={setAgentSecretsAction} className="flex flex-col gap-1.5 rounded-md border bg-background/40 px-2.5 py-2 text-sm">
|
||||
<Hidden fields={{ projectId, back, on: agentsEnabled ? "0" : "1" }} />
|
||||
<span className="font-medium">
|
||||
{t("Агенты получают секреты в окружение")}: {agentsEnabled ? t("да") : t("нет")}
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{agentsEnabled
|
||||
? t("Агент видит ключи с пометкой «агенту и продукту» и может их напечатать или унести. Внешние сервисы безопаснее давать подключениями.")
|
||||
: t("Агенты не получают ни одного секрета; продукт получает все. Внешние сервисы агентам — через подключения.")}
|
||||
</span>
|
||||
<Button size="sm" variant="outline" className="self-start">
|
||||
{agentsEnabled ? t("Не давать агентам секреты") : t("Давать агентам секреты «агенту и продукту»")}
|
||||
</Button>
|
||||
</form>
|
||||
{secrets.length > 0 && (
|
||||
<ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm" aria-label={t("Секреты проекта")}>
|
||||
{secrets.map((s) => (
|
||||
<li key={s.id} className="flex items-center gap-2 rounded-md border bg-background/40 px-2.5 py-1.5">
|
||||
<span className="flex min-w-0 flex-1 flex-col">
|
||||
<span className="truncate font-mono text-[13px]">{s.name}</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{t("изменён {ago}", { ago: ago(s.updatedAt, t) })}
|
||||
{s.updatedBy ? ` · ${s.updatedBy}` : ""} · {s.lastUsedAt ? t("выдан агенту {ago}", { ago: ago(s.lastUsedAt, t) }) : t("агентам ещё не выдавался")}
|
||||
</span>
|
||||
</span>
|
||||
<form action={deleteProjectSecretAction}>
|
||||
<Hidden fields={{ projectId, name: s.name, back }} />
|
||||
<Button variant="ghost" size="icon" aria-label={t("Удалить {name}", { name: s.name })} title={t("Удалить {name}", { name: s.name })}>
|
||||
<Trash2 />
|
||||
</Button>
|
||||
</form>
|
||||
</li>
|
||||
))}
|
||||
{secrets.map((s) => {
|
||||
const svc = services.get(s.name);
|
||||
const toAgent = s.agentEnv && agentsEnabled;
|
||||
const canMove = !!svc?.serviceName && !s.connectionId;
|
||||
return (
|
||||
<li key={s.id} className="flex flex-col gap-1.5 rounded-md border bg-background/40 px-2.5 py-1.5">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="flex min-w-0 flex-1 flex-col">
|
||||
<span className="truncate font-mono text-[13px]">{s.name}</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{s.agentEnv ? t("агенту и продукту") : t("только продукту")}
|
||||
{s.agentEnv && !agentsEnabled ? " (" + t("агентам секреты не выдаются") + ")" : ""}
|
||||
{" · "}
|
||||
{t("изменён {ago}", { ago: ago(s.updatedAt, t) })}
|
||||
{s.updatedBy ? ` · ${s.updatedBy}` : ""}
|
||||
{toAgent ? " · " + (s.lastUsedAt ? t("выдан агенту {ago}", { ago: ago(s.lastUsedAt, t) }) : t("агентам ещё не выдавался")) : ""}
|
||||
</span>
|
||||
</span>
|
||||
<form action={deleteProjectSecretAction}>
|
||||
<Hidden fields={{ projectId, name: s.name, back }} />
|
||||
<Button variant="ghost" size="icon" aria-label={t("Удалить {name}", { name: s.name })} title={t("Удалить {name}", { name: s.name })}>
|
||||
<Trash2 />
|
||||
</Button>
|
||||
</form>
|
||||
</div>
|
||||
{svc?.connectionName && <span className="text-xs text-muted-foreground">{t("Стал подключением «{name}»: агент работает с сервисом, не видя ключа.", { name: svc.connectionName })}</span>}
|
||||
{canMove && (
|
||||
<span className={`text-xs ${toAgent ? "text-amber-600 dark:text-amber-400" : "text-muted-foreground"}`}>
|
||||
{toAgent
|
||||
? t("Это ключ {service}, и агент его видит. Сделайте подключение: агент будет работать с сервисом, не видя ключа, продукт получит ключ как раньше.", { service: svc!.serviceName! })
|
||||
: t("Это ключ {service}. Агенту его можно дать подключением — ключ он не увидит.", { service: svc!.serviceName! })}
|
||||
</span>
|
||||
)}
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{canMove && (
|
||||
<form action={secretToConnectionAction}>
|
||||
<Hidden fields={{ projectId, name: s.name, back }} />
|
||||
<Button size="sm">{t("Сделать подключением")}</Button>
|
||||
</form>
|
||||
)}
|
||||
<form action={setSecretAudienceAction}>
|
||||
<Hidden fields={{ projectId, name: s.name, back, audience: s.agentEnv ? "product" : "agent" }} />
|
||||
<Button size="sm" variant="ghost">{s.agentEnv ? t("Только продукту") : t("Дать и агенту (видит ключ)")}</Button>
|
||||
</form>
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
<form action={saveProjectSecretAction} className="flex flex-col gap-2" autoComplete="off">
|
||||
<Hidden fields={{ projectId, back }} />
|
||||
<Input name="name" required placeholder="STRIPE_TEST_KEY" aria-label={t("Имя секрета")} pattern="[A-Z][A-Z0-9_]{0,63}" className="font-mono" autoComplete="off" spellCheck={false} />
|
||||
<SecretNameHint hints={hints} label={t("Имя секрета")} />
|
||||
<Textarea name="value" required rows={2} placeholder={t("Значение — после сохранения его не увидит никто")} aria-label={t("Значение секрета")} className="font-mono" autoComplete="off" spellCheck={false} />
|
||||
<fieldset className="m-0 flex flex-col gap-1 border-0 p-0 text-sm">
|
||||
<legend className="mb-1 text-xs text-muted-foreground">{t("Кому")}</legend>
|
||||
<label className="flex items-center gap-2">
|
||||
<input type="radio" name="audience" value="product" defaultChecked /> {t("Только продукту")}
|
||||
</label>
|
||||
<label className="flex items-center gap-2">
|
||||
<input type="radio" name="audience" value="agent" /> {t("Агенту и продукту (агент видит ключ)")}
|
||||
</label>
|
||||
</fieldset>
|
||||
<Button size="sm" className="self-start">{t("Сохранить")}</Button>
|
||||
</form>
|
||||
<p className="m-0 text-xs text-muted-foreground">
|
||||
{rich(
|
||||
t("Секреты получают агенты проекта (при следующем запуске сессии) и сам выкаченный продукт — как переменные окружения с тем же именем; после изменения Peppa FACTORY через пару минут перезапускает продукт. Имена {a}, {c}, {o} идут только в продукт. Имя существующего секрета заменяет его значение. Значение хранится зашифрованным и больше не показывается; в терминале и ленте шагов оно заменяется на «••••». Агент видит только имена ({list})."),
|
||||
{ a: <code>ANTHROPIC_…</code>, c: <code>CLAUDE_…</code>, o: <code>OPENCODE_…</code>, list: <code>list_secrets</code> },
|
||||
)}
|
||||
</p>
|
||||
{engineer && (
|
||||
<p className="m-0 text-xs text-muted-foreground">
|
||||
{rich(
|
||||
t("Все секреты получает выкаченный продукт — как переменные окружения с тем же именем; после изменения FORGE через пару минут перезапускает продукт. Агенты проекта (при следующем запуске сессии) получают только секреты «агенту и продукту» и только при включённой настройке выше; имена {a}, {c}, {o} идут только в продукт. Имя существующего секрета заменяет его значение. Значение хранится зашифрованным и больше не показывается; в терминале и ленте шагов оно заменяется на «••••». Агент видит только имена ({list})."),
|
||||
{ a: <code>ANTHROPIC_…</code>, c: <code>CLAUDE_…</code>, o: <code>OPENCODE_…</code>, list: <code>list_secrets</code> },
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
62
apps/web/components/ProposalList.tsx
Normal file
62
apps/web/components/ProposalList.tsx
Normal file
@ -0,0 +1,62 @@
|
||||
// PEP-197: the acceptance agent's list in the project chat — per item «Делать» / «Не надо»,
|
||||
// below «Делать важные» / «Отклонить всё». Once an item is decided the buttons give way to the outcome.
|
||||
import { proposalAction } from "@/app/(app)/actions";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import type { ProposalItem } from "@peppa/core";
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
|
||||
const SEVERITY = {
|
||||
breakage: { label: m("Поломка"), variant: "danger" },
|
||||
important: { label: m("Важно"), variant: "warn" },
|
||||
minor: { label: m("Мелочь"), variant: "muted" },
|
||||
} as const;
|
||||
|
||||
export async function ProposalList({ items, back }: { items: ProposalItem[]; back: string }) {
|
||||
const t = await getT();
|
||||
const open = items.filter((i) => i.open);
|
||||
return (
|
||||
<div data-proposals className="mt-1 flex flex-col gap-2">
|
||||
{items.map((i) => (
|
||||
<div key={i.id} className="flex flex-col gap-2 rounded-md border bg-card p-2 text-sm">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className="font-mono text-xs text-primary">{i.key}</span>
|
||||
<span className="min-w-0 break-words">{i.title}</span>
|
||||
{i.severity && (
|
||||
<Badge variant={SEVERITY[i.severity].variant} className="ml-auto">
|
||||
{t(SEVERITY[i.severity].label)}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
{i.open ? (
|
||||
<form action={proposalAction} className="flex flex-wrap gap-2">
|
||||
<input type="hidden" name="ids" value={i.id} />
|
||||
<input type="hidden" name="back" value={back} />
|
||||
<Button size="sm" name="choice" value="do" className="min-h-11 min-w-11">
|
||||
{t("Делать")}
|
||||
</Button>
|
||||
<Button size="sm" variant="outline" name="choice" value="no" className="min-h-11 min-w-11">
|
||||
{t("Не надо")}
|
||||
</Button>
|
||||
</form>
|
||||
) : (
|
||||
<span className="text-xs text-muted-foreground">{i.decision === "rejected" ? t("Отклонено") : t("Взято в бэклог")}</span>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
{open.length > 0 && (
|
||||
<form action={proposalAction} className="flex flex-wrap gap-2">
|
||||
<input type="hidden" name="ids" value={open.map((i) => i.id).join(",")} />
|
||||
<input type="hidden" name="back" value={back} />
|
||||
<Button size="sm" name="choice" value="important" className="min-h-11">
|
||||
{t("Делать важные")}
|
||||
</Button>
|
||||
<Button size="sm" variant="outline" name="choice" value="none" className="min-h-11">
|
||||
{t("Отклонить всё")}
|
||||
</Button>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@ -20,7 +20,7 @@ export function PugMascot({ mood, size = 96, className }: { mood: Mood; size?: n
|
||||
width={(size * 120) / 140}
|
||||
height={size}
|
||||
role="img"
|
||||
aria-label={awake ? t("Мопс Peppa FACTORY ждёт вашего ответа") : t("Мопс Peppa FACTORY спит")}
|
||||
aria-label={awake ? t("Мопс FORGE ждёт вашего ответа") : t("Мопс FORGE спит")}
|
||||
className={cn("shrink-0 overflow-visible", awake ? "pug-alert" : "pug-sleep", className)}
|
||||
>
|
||||
<defs>
|
||||
|
||||
@ -10,7 +10,6 @@ import { AgentSteps } from "@/components/AgentSteps";
|
||||
import { AttachCommand, QuestionCard, SessionActions } from "@/components/cards";
|
||||
import { ago, Key, StatusBadge } from "@/components/common";
|
||||
import { LocalTime, ScrollIntoViewOnNarrow } from "@/components/LocalTime";
|
||||
import { RunnerTerminal } from "@/components/RunnerTerminal";
|
||||
import { SessionUsageLine } from "@/components/Accounting";
|
||||
import type { InboxItem } from "@/lib/queries";
|
||||
import { SESSION_STATUS, TONE_BG, TONE_TEXT } from "@/lib/status";
|
||||
@ -160,7 +159,7 @@ export async function RunnerDetails({ s, questions, events, steps, stories, back
|
||||
</dd>
|
||||
<dt className="text-muted-foreground">{t("Где")}</dt>
|
||||
<dd className="m-0">
|
||||
{s.host ? t("хост {name}", { name: s.host.name }) : t("Mac Peppa FACTORY")}
|
||||
{s.host ? t("хост {name}", { name: s.host.name }) : t("Mac FORGE")}
|
||||
{s.container ? <span className="text-muted-foreground"> · {t("контейнер {name}", { name: s.container })}</span> : <span className="text-muted-foreground"> · {t("без изоляции")}</span>}
|
||||
</dd>
|
||||
<dt className="text-muted-foreground">{t("Запущен")}</dt>
|
||||
@ -192,7 +191,12 @@ export async function RunnerDetails({ s, questions, events, steps, stories, back
|
||||
{t("Сессия завершена — терминала больше нет.")}
|
||||
</div>
|
||||
) : (
|
||||
<RunnerTerminal key={s.id} sessionId={s.id} live />
|
||||
// PEP-257: one place for terminals — «Сессии», opened on this session.
|
||||
<Link href={`/sessions?id=${s.id}`} data-open-session={s.id} className="inline-flex items-center gap-2 self-start rounded-md border bg-card px-3 py-1.5 text-sm text-foreground hover:bg-accent hover:no-underline">
|
||||
<SquareTerminal className="size-4" />
|
||||
{/* glossary-ignore: «Работа агентов» и «Сессии» — только в виде «Инженер» */}
|
||||
{t("Открыть в «Сессиях»")}
|
||||
</Link>
|
||||
)}
|
||||
</PanelSection>
|
||||
|
||||
|
||||
@ -1,10 +1,18 @@
|
||||
"use client";
|
||||
// Live runner terminal (PEP-9): xterm.js fed by SSE from /api/runners/<id>/terminal, input via POST.
|
||||
// Live runner terminal (PEP-9): xterm.js fed by the tab's live channel (`terminal:<id>`, PEP-225),
|
||||
// input over the same channel; without a WebSocket — SSE of /api/runners/<id>/terminal and POST.
|
||||
// PEP-257: the font is given to xterm resolved (a CSS variable is not understood when xterm
|
||||
// measures its cell — the cell came out wider than the glyphs and got letter-spacing), the cell
|
||||
// is re-measured when web fonts arrive. By default the whole grid is scaled to the panel width so
|
||||
// all columns of the pane are visible («по ширине»): a CSS scale of the grid xterm drew, because
|
||||
// font sizes alone do not fit — browsers round small glyph advances to whole pixels. +/- switch
|
||||
// to a fixed font size, unscaled, with scrolling.
|
||||
import "@xterm/xterm/css/xterm.css";
|
||||
import type { Terminal } from "@xterm/xterm";
|
||||
import { Keyboard, Maximize2, Minimize2, Minus, Plus, RotateCw } from "lucide-react";
|
||||
import { ArrowLeftRight, Keyboard, Maximize2, Minimize2, Minus, Plus, RotateCw } from "lucide-react";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { liveClient, useLiveMode } from "@/lib/live";
|
||||
import { useT } from "@/components/I18n";
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
|
||||
@ -17,8 +25,13 @@ const STATUS_TEXT: Record<Status, string> = {
|
||||
error: m("нет доступа к терминалу"),
|
||||
};
|
||||
const FONT_KEY = "peppa_term_font";
|
||||
const FIT_KEY = "peppa_term_fit";
|
||||
const FONT_MIN = 7;
|
||||
const FONT_MAX = 20;
|
||||
/** «По ширине» does not blow a narrow pane up beyond this. */
|
||||
const FIT_MAX_SCALE = 1.5;
|
||||
/** Horizontal padding of the terminal frame (p-1.5 on both sides + border). */
|
||||
const FRAME_PAD = 14;
|
||||
/** Keys a phone keyboard lacks. */
|
||||
const QUICK_KEYS: Array<[string, string]> = [
|
||||
["Esc", "\x1b"],
|
||||
@ -29,6 +42,23 @@ const QUICK_KEYS: Array<[string, string]> = [
|
||||
["Ctrl-C", "\x03"],
|
||||
];
|
||||
|
||||
function readFit(): boolean {
|
||||
try {
|
||||
return localStorage.getItem(FIT_KEY) !== "0";
|
||||
} catch {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The page's monospace font as real family names: `var(--font-geist-mono)` resolved here,
|
||||
* because xterm measures its cell with this string outside CSS (PEP-257).
|
||||
*/
|
||||
function monoFont(): string {
|
||||
const v = getComputedStyle(document.documentElement).getPropertyValue("--font-geist-mono").trim();
|
||||
return [v, "ui-monospace", "Menlo", '"DejaVu Sans Mono"', "monospace"].filter(Boolean).join(", ");
|
||||
}
|
||||
|
||||
function readFont(): number {
|
||||
try {
|
||||
const n = Number(localStorage.getItem(FONT_KEY));
|
||||
@ -38,36 +68,39 @@ function readFont(): number {
|
||||
}
|
||||
}
|
||||
|
||||
export function RunnerTerminal({ sessionId, live }: { sessionId: number; live: boolean }) {
|
||||
/** `fill`: the terminal takes the height of its parent (the «Сессии» page), not 60vh. */
|
||||
export function RunnerTerminal({ sessionId, live, fill = false }: { sessionId: number; live: boolean; fill?: boolean }) {
|
||||
const host = useRef<HTMLDivElement>(null);
|
||||
const scroller = useRef<HTMLDivElement>(null);
|
||||
const term = useRef<Terminal | null>(null);
|
||||
const [status, setStatus] = useState<Status>("connecting");
|
||||
const [own, setStatus] = useState<Status>("connecting");
|
||||
// The channel dropped: the picture is stale until it is back (a fresh frame comes then).
|
||||
const mode = useLiveMode();
|
||||
const status: Status = own === "live" && mode !== "live" ? "reconnecting" : own;
|
||||
const [input, setInput] = useState(false);
|
||||
const [full, setFull] = useState(false);
|
||||
const [font, setFont] = useState(12);
|
||||
const [fit, setFit] = useState(true);
|
||||
/** The panel's width and the size of the grid xterm drew (unscaled): what «по ширине» fits. */
|
||||
const [width, setWidth] = useState(0);
|
||||
const [grid, setGrid] = useState({ w: 0, h: 0 });
|
||||
const family = useRef("monospace");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [attempt, setAttempt] = useState(0);
|
||||
const t = useT();
|
||||
const inputRef = useRef(false);
|
||||
const queue = useRef<{ keys: string; timer: ReturnType<typeof setTimeout> | null; chain: Promise<void> }>({ keys: "", timer: null, chain: Promise.resolve() });
|
||||
const url = `/api/runners/${sessionId}/terminal`;
|
||||
const scope = `terminal:${sessionId}`;
|
||||
|
||||
const post = useCallback(
|
||||
(body: { keys?: string; paste?: string }) => {
|
||||
const q = queue.current;
|
||||
// Strictly one request at a time: the order of keystrokes matters.
|
||||
q.chain = q.chain.then(async () => {
|
||||
try {
|
||||
const r = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
|
||||
if (!r.ok) setError(((await r.json().catch(() => null)) as { error?: string } | null)?.error ?? m("Ошибка {status}", { status: r.status }));
|
||||
else setError(null);
|
||||
} catch {
|
||||
setError(m("Нет связи с Peppa FACTORY"));
|
||||
}
|
||||
setError(await liveClient().input(scope, body));
|
||||
});
|
||||
},
|
||||
[url],
|
||||
[scope],
|
||||
);
|
||||
|
||||
const sendKeys = useCallback(
|
||||
@ -96,13 +129,21 @@ export function RunnerTerminal({ sessionId, live }: { sessionId: number; live: b
|
||||
let disposed = false;
|
||||
let cleanup = () => {};
|
||||
setFont(readFont());
|
||||
void import("@xterm/xterm").then(({ Terminal }) => {
|
||||
setFit(readFit());
|
||||
const font = monoFont();
|
||||
family.current = font;
|
||||
// Open only when the web font is there: xterm measures the cell once, at open.
|
||||
const fonts = document.fonts;
|
||||
// i18n-ignore: sample glyphs (Latin and Cyrillic) for the font loader, not a text
|
||||
const ready = fonts ? Promise.race([fonts.load(`12px ${font}`, "W Ж").then(() => fonts.ready), new Promise((r) => setTimeout(r, 2000))]) : Promise.resolve();
|
||||
void Promise.all([import("@xterm/xterm"), ready]).then(([{ Terminal }]) => {
|
||||
if (disposed || !host.current) return;
|
||||
const t = new Terminal({
|
||||
cols: 120,
|
||||
rows: 30,
|
||||
fontSize: readFont(),
|
||||
fontFamily: "var(--font-geist-mono), ui-monospace, Menlo, monospace",
|
||||
fontFamily: font,
|
||||
letterSpacing: 0,
|
||||
scrollback: 5000,
|
||||
disableStdin: true,
|
||||
cursorBlink: false,
|
||||
@ -121,8 +162,16 @@ export function RunnerTerminal({ sessionId, live }: { sessionId: number; live: b
|
||||
};
|
||||
const el = host.current;
|
||||
el.addEventListener("paste", onPaste, true);
|
||||
// A font (or a Cyrillic subset of it) loaded later: make xterm measure the cell again.
|
||||
let flip = false;
|
||||
const remeasure = () => {
|
||||
flip = !flip;
|
||||
t.options.fontFamily = flip ? `${font} ` : font;
|
||||
};
|
||||
fonts?.addEventListener("loadingdone", remeasure);
|
||||
term.current = t;
|
||||
cleanup = () => {
|
||||
fonts?.removeEventListener("loadingdone", remeasure);
|
||||
el.removeEventListener("paste", onPaste, true);
|
||||
onData.dispose();
|
||||
t.dispose();
|
||||
@ -136,28 +185,31 @@ export function RunnerTerminal({ sessionId, live }: { sessionId: number; live: b
|
||||
};
|
||||
}, [post, sendKeys]);
|
||||
|
||||
// The stream: (re)opened when the terminal is ready or the user asks to reconnect.
|
||||
// The stream: (re)subscribed when the terminal is ready or the user asks to reconnect.
|
||||
useEffect(() => {
|
||||
const t = term.current;
|
||||
if (!t || attempt === 0) return;
|
||||
setStatus("connecting");
|
||||
const es = new EventSource(url);
|
||||
es.addEventListener("frame", (e) => {
|
||||
const f = JSON.parse((e as MessageEvent<string>).data) as { cols: number; rows: number; data: string };
|
||||
t.reset();
|
||||
if (t.cols !== f.cols || t.rows !== f.rows) t.resize(f.cols, f.rows);
|
||||
// The pane is usually taller than the panel: show its bottom, where the agent works.
|
||||
t.write(f.data, () => scroller.current && (scroller.current.scrollTop = scroller.current.scrollHeight));
|
||||
setStatus("live");
|
||||
});
|
||||
es.addEventListener("out", (e) => t.write((JSON.parse((e as MessageEvent<string>).data) as { data: string }).data));
|
||||
es.addEventListener("end", () => {
|
||||
es.close();
|
||||
setStatus("ended");
|
||||
});
|
||||
es.onerror = () => setStatus(es.readyState === EventSource.CLOSED ? "error" : "reconnecting");
|
||||
return () => es.close();
|
||||
}, [url, attempt]);
|
||||
let stop = () => {};
|
||||
stop = liveClient().subscribe(
|
||||
scope,
|
||||
(e) => {
|
||||
if (e.type === "frame") {
|
||||
t.reset();
|
||||
if (t.cols !== e.cols || t.rows !== e.rows) t.resize(e.cols, e.rows);
|
||||
// The pane is usually taller than the panel: show its bottom, where the agent works.
|
||||
t.write(e.data, () => scroller.current && (scroller.current.scrollTop = scroller.current.scrollHeight));
|
||||
setStatus("live");
|
||||
} else if (e.type === "out") t.write(e.data);
|
||||
else if (e.type === "end") {
|
||||
setStatus("ended");
|
||||
queueMicrotask(() => stop());
|
||||
} else if (e.type === "error") setStatus("error");
|
||||
},
|
||||
{ heavy: true },
|
||||
);
|
||||
return () => stop();
|
||||
}, [scope, attempt]);
|
||||
|
||||
useEffect(() => {
|
||||
inputRef.current = input && live;
|
||||
@ -168,14 +220,46 @@ export function RunnerTerminal({ sessionId, live }: { sessionId: number; live: b
|
||||
if (inputRef.current) t.focus();
|
||||
}, [input, live, attempt]);
|
||||
|
||||
// The panel's width and the grid's size (layout size: a transform does not change it).
|
||||
useEffect(() => {
|
||||
const el = scroller.current;
|
||||
const g = host.current;
|
||||
if (!el || !g || typeof ResizeObserver === "undefined") return;
|
||||
const ro = new ResizeObserver(() => {
|
||||
setWidth(el.clientWidth);
|
||||
setGrid({ w: g.offsetWidth, h: g.offsetHeight });
|
||||
});
|
||||
ro.observe(el);
|
||||
ro.observe(g);
|
||||
return () => ro.disconnect();
|
||||
}, []);
|
||||
|
||||
const scale = fit && grid.w && width ? Math.min(FIT_MAX_SCALE, (width - FRAME_PAD) / grid.w) : 1;
|
||||
/** The font size the user sees. */
|
||||
const size = Math.round(font * scale * 10) / 10;
|
||||
|
||||
useEffect(() => {
|
||||
const t = term.current;
|
||||
if (!t || t.options.fontSize === font) return;
|
||||
t.options.fontSize = font;
|
||||
// Keep the bottom of the pane (where the agent works and the tmux status line is) in view.
|
||||
requestAnimationFrame(() => scroller.current && (scroller.current.scrollTop = scroller.current.scrollHeight));
|
||||
}, [font, attempt]);
|
||||
|
||||
useEffect(() => {
|
||||
if (term.current) term.current.options.fontSize = font;
|
||||
try {
|
||||
localStorage.setItem(FONT_KEY, String(font));
|
||||
localStorage.setItem(FIT_KEY, fit ? "1" : "0");
|
||||
} catch {
|
||||
// private mode: the size just is not remembered
|
||||
}
|
||||
}, [font]);
|
||||
}, [font, fit]);
|
||||
|
||||
/** +/-: from «по ширине» go on from the size shown now. */
|
||||
const zoom = (d: number) => {
|
||||
setFit(false);
|
||||
setFont(Math.max(FONT_MIN, Math.min(FONT_MAX, Math.round(fit ? size : font) + d)));
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (!full) return;
|
||||
@ -186,7 +270,7 @@ export function RunnerTerminal({ sessionId, live }: { sessionId: number; live: b
|
||||
|
||||
const btn = "inline-flex items-center gap-1 rounded-md border bg-card px-2 py-1 text-xs text-muted-foreground hover:bg-accent hover:text-foreground disabled:opacity-50";
|
||||
return (
|
||||
<div className={cn("flex flex-col gap-2", full && "fixed inset-0 z-50 bg-background p-3")} data-terminal-status={status}>
|
||||
<div className={cn("flex min-w-0 flex-col gap-2", fill && "h-full min-h-0", full && "fixed inset-0 z-50 bg-background p-3")} data-terminal-status={status} data-terminal-font={size}>
|
||||
<div className="flex flex-wrap items-center gap-1.5">
|
||||
<span className={cn("mr-auto flex items-center gap-1.5 font-mono text-[11px]", status === "live" ? "text-ok" : status === "error" ? "text-destructive" : "text-muted-foreground")}>
|
||||
<span className={cn("size-1.5 rounded-full bg-current", status === "live" && "animate-pulse")} />
|
||||
@ -198,10 +282,14 @@ export function RunnerTerminal({ sessionId, live }: { sessionId: number; live: b
|
||||
{input ? t("Ввод включён") : t("Ввод")}
|
||||
</button>
|
||||
)}
|
||||
<button type="button" className={btn} onClick={() => setFont((f) => Math.max(FONT_MIN, f - 1))} aria-label={t("Мельче")} title={t("Мельче")}>
|
||||
<button type="button" className={cn(btn, fit && "border-primary/60 bg-primary/10 text-foreground")} onClick={() => setFit((v) => !v)} aria-pressed={fit} title={t("Все колонки по ширине окна")} data-terminal-fit>
|
||||
<ArrowLeftRight className="size-3.5" />
|
||||
{t("По ширине")}
|
||||
</button>
|
||||
<button type="button" className={btn} onClick={() => zoom(-1)} aria-label={t("Мельче")} title={t("Мельче")} data-terminal-zoom="-">
|
||||
<Minus className="size-3.5" />
|
||||
</button>
|
||||
<button type="button" className={btn} onClick={() => setFont((f) => Math.min(FONT_MAX, f + 1))} aria-label={t("Крупнее")} title={t("Крупнее")}>
|
||||
<button type="button" className={btn} onClick={() => zoom(1)} aria-label={t("Крупнее")} title={t("Крупнее")} data-terminal-zoom="+">
|
||||
<Plus className="size-3.5" />
|
||||
</button>
|
||||
{(status === "ended" || status === "error") && (
|
||||
@ -213,8 +301,12 @@ export function RunnerTerminal({ sessionId, live }: { sessionId: number; live: b
|
||||
{full ? <Minimize2 className="size-3.5" /> : <Maximize2 className="size-3.5" />}
|
||||
</button>
|
||||
</div>
|
||||
<div ref={scroller} className={cn("overflow-auto rounded-lg border bg-[#0b0b0d] p-1.5", full ? "min-h-0 flex-1" : "max-h-[60vh]", input && live && "border-primary/60")}>
|
||||
<div ref={host} className="w-max" />
|
||||
<div ref={scroller} data-terminal-scroller className={cn("overflow-auto rounded-lg border bg-[#0b0b0d] p-1.5", full || fill ? "min-h-0 flex-1" : "max-h-[60vh]", input && live && "border-primary/60")}>
|
||||
{/* xterm's helper textarea and scrollbar keep offsets of the previous font size for a
|
||||
moment and stuck out below the terminal (a blank strip to scroll into) — clip them. */}
|
||||
<div style={scale !== 1 ? { width: grid.w * scale, height: grid.h * scale } : undefined} className="w-max overflow-hidden">
|
||||
<div ref={host} className="w-max origin-top-left overflow-hidden" style={scale !== 1 ? { transform: `scale(${scale})` } : undefined} />
|
||||
</div>
|
||||
</div>
|
||||
{input && live && (
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
|
||||
@ -78,7 +78,7 @@ const inherit = (t: Translator, label: string) => t("Как выше: {label}",
|
||||
/** «⋯ Настройки проекта → Раннеры»: overrides of the project; empty = system. */
|
||||
export async function RunnerSettingsPanel({ projectId, own, inherited, back, hosts = [] }: { projectId: number; own: RunnerSettingsPatch; inherited: RunnerSettings; back: string; hosts?: Pick<RunnerHost, "id" | "name" | "status">[] }) {
|
||||
const t = await getT();
|
||||
const hostNames = (ids: number[]) => (ids.length ? ids.map((id) => hosts.find((h) => h.id === id)?.name ?? `#${id}`).join(", ") : m("Mac Peppa FACTORY"));
|
||||
const hostNames = (ids: number[]) => (ids.length ? ids.map((id) => hosts.find((h) => h.id === id)?.name ?? `#${id}`).join(", ") : m("Mac FORGE"));
|
||||
return (
|
||||
<form action={setRunnerSettingsAction} className="flex flex-col gap-3">
|
||||
<Hidden fields={{ projectId, back }} />
|
||||
@ -126,7 +126,7 @@ export async function RunnerSettingsPanel({ projectId, own, inherited, back, hos
|
||||
{t("Где запускать раннеры")}
|
||||
<NativeSelect name="hostsMode" defaultValue={own.hosts === undefined ? "" : own.hosts.length ? "list" : "local"} className="h-8">
|
||||
<option value="">{inherit(t, hostNames(inherited.hosts))}</option>
|
||||
<option value="local">{t("Mac Peppa FACTORY")}</option>
|
||||
<option value="local">{t("Mac FORGE")}</option>
|
||||
<option value="list" disabled={!hosts.length}>{t("Хосты, отмеченные ниже (наименее занятый онлайн)")}</option>
|
||||
</NativeSelect>
|
||||
</Label>
|
||||
@ -141,7 +141,7 @@ export async function RunnerSettingsPanel({ projectId, own, inherited, back, hos
|
||||
</div>
|
||||
)}
|
||||
<p className="m-0 text-xs text-muted-foreground">
|
||||
{t("Контейнер: агент работает в docker-образе раннера и видит только свою рабочую копию; токены Peppa FACTORY и чужие проекты ему недоступны, нужна подписка в пуле проекта. На хосте агент всегда в контейнере.")}
|
||||
{t("Контейнер: агент работает в docker-образе раннера и видит только свою рабочую копию; токены FORGE и чужие проекты ему недоступны, нужна подписка в пуле проекта. На хосте агент всегда в контейнере.")}
|
||||
</p>
|
||||
<p className="m-0 text-xs text-muted-foreground">
|
||||
{t("Очередь: стори достаётся свободному раннеру, при лимите ждёт в очереди; «Принять» не останавливает раннер, а даёт ему следующую стори.")}{" "}
|
||||
|
||||
34
apps/web/components/SecretNameHint.tsx
Normal file
34
apps/web/components/SecretNameHint.tsx
Normal file
@ -0,0 +1,34 @@
|
||||
"use client";
|
||||
// PEP-253: the secret name field with a live hint «это ключ <Сервис> — агенту лучше дать подключение».
|
||||
// The rules come from the server (`secretNameHints`), so no core code reaches the browser.
|
||||
import { useState } from "react";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { useT } from "@/components/I18n";
|
||||
|
||||
export function SecretNameHint({ hints, label }: { hints: Array<{ prefix: string; exact: boolean; service: string }>; label: string }) {
|
||||
const t = useT();
|
||||
const [name, setName] = useState("");
|
||||
const n = name.trim().toUpperCase();
|
||||
const hit = n ? hints.find((h) => (h.exact ? n === h.prefix : n.startsWith(h.prefix))) : undefined;
|
||||
return (
|
||||
<div className="flex flex-col gap-1">
|
||||
<Input
|
||||
name="name"
|
||||
required
|
||||
placeholder="MAPS_API_KEY"
|
||||
aria-label={label}
|
||||
pattern="[A-Z][A-Z0-9_]{0,63}"
|
||||
className="font-mono"
|
||||
autoComplete="off"
|
||||
spellCheck={false}
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
/>
|
||||
{hit && (
|
||||
<p className="m-0 text-xs text-amber-600 dark:text-amber-400" role="status">
|
||||
{t("Это ключ {service} — агенту лучше дать подключение: он будет работать с сервисом, не видя ключа. Сохраните ключ здесь «только продукту» и нажмите «Сделать подключением».", { service: hit.service })}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@ -2,7 +2,9 @@
|
||||
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { Bot, Contact, FolderKanban, Gauge, GitBranch, Megaphone, House, KeyRound, MessagesSquare, ScrollText, LifeBuoy, LogOut, MessageCircleWarning, Search, Server, Settings, ShieldCheck, Sparkles, Users, type LucideIcon } from "lucide-react";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useLive } from "@/lib/live";
|
||||
import { Activity, Bot, PlugZap, Contact, FolderKanban, Gauge, GitBranch, Megaphone, House, KeyRound, MessagesSquare, ScrollText, LifeBuoy, LogOut, MessageCircleWarning, Search, Server, Settings, ShieldCheck, Sparkles, SquareTerminal, Users, type LucideIcon } from "lucide-react";
|
||||
import { Brand } from "@/components/Brand";
|
||||
import { ThemeToggle } from "@/components/ThemeToggle";
|
||||
import { LanguageSwitcher } from "@/components/I18n";
|
||||
@ -29,14 +31,18 @@ const ITEMS: Item[] = [
|
||||
{ href: "/", label: m("Главная"), icon: House, match: (p) => p === "/", count: "questions" },
|
||||
{ href: "/chats", label: m("Чаты"), icon: MessagesSquare, match: (p) => p.startsWith("/chats"), count: "chats" },
|
||||
{ href: "/projects", label: m("Проекты"), icon: FolderKanban, match: (p) => p.startsWith("/projects") || p.startsWith("/p/") || p.startsWith("/t/") },
|
||||
// glossary-ignore: PEP-257, терминалы агентов — пункт только в виде «Инженер»
|
||||
{ href: "/sessions", label: m("Сессии"), icon: SquareTerminal, match: (p) => p.startsWith("/sessions"), desktopOnly: true, engineer: true },
|
||||
{ href: "/runners", label: m("Работа агентов"), icon: Bot, match: (p) => p.startsWith("/runners"), count: "waitingRunners", engineer: true },
|
||||
{ href: "/connections", label: m("Подключения"), icon: PlugZap, match: (p) => p.startsWith("/connections"), desktopOnly: true },
|
||||
{ href: "/team", label: m("Команда"), icon: Contact, match: (p) => p.startsWith("/team"), desktopOnly: true },
|
||||
{ href: "/welcome", label: m("О Peppa FACTORY"), icon: Sparkles, match: (p) => p.startsWith("/welcome"), desktopOnly: true },
|
||||
{ href: "/welcome", label: m("О FORGE"), icon: Sparkles, match: (p) => p.startsWith("/welcome"), desktopOnly: true },
|
||||
{ href: "/help", label: m("Помощь"), icon: LifeBuoy, match: (p) => p.startsWith("/help") },
|
||||
{ href: "/dashboard", label: m("Дашборд"), icon: Gauge, match: (p) => p.startsWith("/dashboard"), admin: true },
|
||||
{ href: "/subscriptions", label: m("Подписки"), icon: KeyRound, match: (p) => p.startsWith("/subscriptions"), admin: true },
|
||||
{ href: "/secrets", label: m("Секреты"), icon: ShieldCheck, match: (p) => p.startsWith("/secrets"), admin: true },
|
||||
{ href: "/gitea", label: m("Gitea"), icon: GitBranch, match: (p) => p.startsWith("/gitea"), admin: true },
|
||||
{ href: "/observability", label: m("Observability"), icon: Activity, match: (p) => p.startsWith("/observability"), admin: true },
|
||||
{ href: "/hosts", label: m("Хосты"), icon: Server, match: (p) => p.startsWith("/hosts"), admin: true },
|
||||
{ href: "/journal", label: m("Журнал"), icon: ScrollText, match: (p) => p.startsWith("/journal"), admin: true },
|
||||
{ href: "/platform", label: m("Платформа"), icon: Megaphone, match: (p) => p.startsWith("/platform"), admin: true },
|
||||
@ -47,9 +53,18 @@ const ITEMS: Item[] = [
|
||||
const COUNT_TITLE = { questions: m("{n} вопросов ждут вас"), waitingRunners: m("{n} агентов ждут вас"), chats: m("{n} новых сообщений в обсуждениях"), feedback: m("{n} обращений ждут решения") };
|
||||
|
||||
/** Left panel on desktop; on phones a top bar plus a bottom tab bar (PEP-38): sections with «ждут вас» counters, theme, user. */
|
||||
export function Sidebar({ login, avatarUrl, counts, superadmin = false, engineer = false }: { login: string; avatarUrl: string | null; counts: Record<"questions" | "waitingRunners" | "chats" | "feedback", number>; superadmin?: boolean; engineer?: boolean }) {
|
||||
export function Sidebar({ login, avatarUrl, counts: initialCounts, superadmin = false, engineer = false }: { login: string; avatarUrl: string | null; counts: Record<"questions" | "waitingRunners" | "chats" | "feedback", number>; superadmin?: boolean; engineer?: boolean }) {
|
||||
const path = usePathname();
|
||||
const t = useT();
|
||||
// PEP-225: the «ждут вас» counters follow the live channel (`attention`) without a re-render.
|
||||
const [live, setLive] = useState<Partial<typeof initialCounts>>({});
|
||||
useEffect(() => setLive({}), [initialCounts]);
|
||||
useLive("attention", (e) => {
|
||||
if (e.type !== "data") return;
|
||||
const d = e.data as { questions?: number; waitingRunners?: number; chats?: number };
|
||||
setLive({ questions: d.questions, waitingRunners: d.waitingRunners, chats: d.chats });
|
||||
});
|
||||
const counts = { ...initialCounts, ...Object.fromEntries(Object.entries(live).filter(([, v]) => typeof v === "number")) };
|
||||
const items = ITEMS.filter((i) => (!i.admin || superadmin) && (!i.engineer || engineer));
|
||||
// The phone tab bar holds what is left after the desktop-only and admin sections: 5 or 6 tabs.
|
||||
const phoneTabs = items.filter((i) => !i.admin && !i.desktopOnly).length;
|
||||
|
||||
@ -6,7 +6,7 @@ import { Hidden } from "@/components/cards";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { requestSubscriptionAction } from "@/app/(app)/actions";
|
||||
|
||||
export async function SubscriptionRequestButton({ projectId, offer, back, name, size = "sm" }: { projectId: number; offer: "can" | "sent"; back: string; name?: string; size?: "xs" | "sm" }) {
|
||||
export async function SubscriptionRequestButton({ projectId, offer, back, name, size = "sm", ahead }: { projectId: number; offer: "can" | "sent"; back: string; name?: string; size?: "xs" | "sm"; /** PEP-206: may be asked while the agents still work. */ ahead?: boolean }) {
|
||||
const t = await getT();
|
||||
if (offer === "sent") {
|
||||
return (
|
||||
@ -18,7 +18,7 @@ export async function SubscriptionRequestButton({ projectId, offer, back, name,
|
||||
}
|
||||
return (
|
||||
<form action={requestSubscriptionAction} data-subscription-request="can" className="inline">
|
||||
<Hidden fields={{ projectId, back }} />
|
||||
<Hidden fields={{ projectId, back, ahead: ahead ? "1" : null }} />
|
||||
<Button size={size} variant="outline">
|
||||
<HandHelping className="size-3.5" />
|
||||
{name ? t("Попросить подписку у администратора — {project}", { project: name }) : t("Попросить подписку у администратора")}
|
||||
|
||||
@ -6,7 +6,7 @@ import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import { CopyCode } from "@/components/CopyCode";
|
||||
import { AutoRefresh } from "@/components/AutoRefresh";
|
||||
import { LiveRefresh } from "@/components/LiveRefresh";
|
||||
|
||||
const step = "flex gap-2.5";
|
||||
const num = "grid size-5.5 shrink-0 place-items-center rounded-full bg-primary/15 text-xs font-semibold text-primary";
|
||||
@ -28,8 +28,8 @@ export async function SubscriptionSetup({ projectId, back, logins, shared = fals
|
||||
: l.provider === "claude" ? t("Подключаем Claude — осталось три шага") : t("Подключаем ChatGPT — осталось три шага")}
|
||||
</h2>
|
||||
{extra && <p className="m-0 text-muted-foreground">{t("Агенты уже работают на подключённой подписке. Вторая нужна только про запас — если она не нужна, нажмите «Отменить» внизу.")}</p>}
|
||||
{/* PEP-148: the page asks ChatGPT itself every few seconds — the person does not have to press anything. */}
|
||||
{l.provider !== "claude" && <AutoRefresh everyMs={4000} />}
|
||||
{/* PEP-148 / PEP-225: the server asks ChatGPT every few seconds while the page watches this sign-in — the person does not have to press anything. */}
|
||||
{l.provider !== "claude" && <LiveRefresh scope={`login:${l.subscriptionId}`} indicator={false} />}
|
||||
{l.provider !== "claude" && checked && (
|
||||
<p role="status" className="m-0 rounded-md border border-warn/50 bg-warn/10 px-3 py-2">
|
||||
<b>{t("ChatGPT пока не подтвердил вход.")}</b>{" "}
|
||||
@ -78,7 +78,7 @@ export async function SubscriptionSetup({ projectId, back, logins, shared = fals
|
||||
<CopyCode code={l.code ?? ""} />
|
||||
<span className="text-muted-foreground">
|
||||
{/* glossary-ignore: дословная цитата экрана ChatGPT — объясняем, что терминал не нужен */}
|
||||
{t("ChatGPT назовёт его «9-значный код, отображаемый в вашем терминале». Терминал вам не нужен: код — вот этот, из Peppa FACTORY.")}
|
||||
{t("ChatGPT назовёт его «9-значный код, отображаемый в вашем терминале». Терминал вам не нужен: код — вот этот, из FORGE.")}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
@ -96,7 +96,7 @@ export async function SubscriptionSetup({ projectId, back, logins, shared = fals
|
||||
{t("Так бывает, если вы не были в нём авторизованы. Поля для кода в чате нет: вернитесь на эту вкладку и нажмите «Открыть страницу ChatGPT» ещё раз — теперь откроется страница с полем для кода.")}
|
||||
</span>
|
||||
<span className="text-muted-foreground">
|
||||
{t("ChatGPT покажет «Предупреждение безопасности» — это обычная осторожность: вход начали вы сами, здесь, поэтому смело нажимайте «Продолжить». Страница Peppa FACTORY останется открытой в соседней вкладке.")}
|
||||
{t("ChatGPT покажет «Предупреждение безопасности» — это обычная осторожность: вход начали вы сами, здесь, поэтому смело нажимайте «Продолжить». Страница FORGE останется открытой в соседней вкладке.")}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
@ -135,7 +135,7 @@ export async function SubscriptionSetup({ projectId, back, logins, shared = fals
|
||||
</div>
|
||||
);
|
||||
}
|
||||
// PEP-116: two equal ways — the owner's own subscription, or the one built into Peppa FACTORY.
|
||||
// PEP-116: two equal ways — the owner's own subscription, or the one built into FORGE.
|
||||
return (
|
||||
<section className="mb-4 flex flex-col gap-3 rounded-lg border border-warn/50 bg-warn/10 px-4 py-4 text-sm" aria-label={t("Подключение подписки")}>
|
||||
<h2 className="m-0 text-base font-semibold">{shared ? t("Выберите, на чём будут работать агенты") : t("Подключите подписку — и агенты начнут работать")}</h2>
|
||||
@ -151,7 +151,7 @@ export async function SubscriptionSetup({ projectId, back, logins, shared = fals
|
||||
<div className="flex flex-col gap-2 rounded-lg border bg-card px-4 py-3">
|
||||
{shared && <span className="font-medium">{t("Своя подписка")}</span>}
|
||||
<p className="m-0 text-muted-foreground">
|
||||
{t("Агенты пишут код на вашей подписке Claude или ChatGPT — подойдёт обычная платная (Claude Pro или Max, ChatGPT Plus или Pro). Лимиты — только ваши, пароль Peppa FACTORY не видит.")}
|
||||
{t("Агенты пишут код на вашей подписке Claude или ChatGPT — подойдёт обычная платная (Claude Pro или Max, ChatGPT Plus или Pro). Лимиты — только ваши, пароль FORGE не видит.")}
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<form action={connectOwnSubscriptionAction}>
|
||||
@ -166,7 +166,7 @@ export async function SubscriptionSetup({ projectId, back, logins, shared = fals
|
||||
</div>
|
||||
{shared && (
|
||||
<div className="flex flex-col gap-2 rounded-lg border bg-card px-4 py-3">
|
||||
<span className="font-medium">{t("Подписка Peppa FACTORY")}</span>
|
||||
<span className="font-medium">{t("Подписка FORGE")}</span>
|
||||
<p className="m-0 text-muted-foreground">
|
||||
{t("Ничего подключать не нужно. Подписка общая для пользователей фабрики, поэтому её выдаёт администратор: вы отправляете запрос, он подтверждает — и агенты начинают работать. Когда она занята или упирается в лимит, агенты ждут. Перейти на свою можно в любой момент.")}
|
||||
</p>
|
||||
@ -175,7 +175,7 @@ export async function SubscriptionSetup({ projectId, back, logins, shared = fals
|
||||
) : (
|
||||
<form action={chooseSharedSubscriptionAction}>
|
||||
<Hidden fields={{ projectId, back }} />
|
||||
<Button variant="outline" size="lg">{direct ? t("Работать на подписке Peppa FACTORY") : t("Попросить подписку Peppa FACTORY")}</Button>
|
||||
<Button variant="outline" size="lg">{direct ? t("Работать на подписке FORGE") : t("Попросить подписку FORGE")}</Button>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user