Compare commits
No commits in common. "main" and "task/pep-263" have entirely different histories.
main
...
task/pep-2
@ -3,12 +3,12 @@
|
|||||||
# Old Postgres database: only the source of `peppa db migrate-to-sqlite` (PEP-36)
|
# Old Postgres database: only the source of `peppa db migrate-to-sqlite` (PEP-36)
|
||||||
# DATABASE_URL=postgres://peppa:peppa@127.0.0.1:5433/peppa
|
# DATABASE_URL=postgres://peppa:peppa@127.0.0.1:5433/peppa
|
||||||
|
|
||||||
# Gitea (git.vibe42.kz) — token of peppa-bot with repo scope
|
# Gitea (git.telecom.quest) — token with repo + org scope
|
||||||
GITEA_URL=https://git.vibe42.kz
|
GITEA_URL=https://git.telecom.quest
|
||||||
GITEA_TOKEN=
|
GITEA_TOKEN=
|
||||||
GITEA_TEMPLATE_REPO=peppa-bot/template
|
GITEA_TEMPLATE_REPO=peppa/template
|
||||||
# Peppa's own repo (footer link, scripts/ci.sh --pr, scripts/peppa-release.sh)
|
# Peppa's own repo (footer link, scripts/ci.sh --pr, scripts/peppa-release.sh)
|
||||||
# GITEA_PLATFORM_REPO=peppa-bot/peppa
|
# GITEA_PLATFORM_REPO=peppa/peppa
|
||||||
|
|
||||||
# Where project repos are cloned and sessions run
|
# Where project repos are cloned and sessions run
|
||||||
PEPPA_WORKSPACES=~/peppa/workspaces
|
PEPPA_WORKSPACES=~/peppa/workspaces
|
||||||
|
|||||||
@ -20,7 +20,7 @@ jobs:
|
|||||||
# The runner has the host's docker.sock: only branches of this repository, never forks.
|
# The runner has the host's docker.sock: only branches of this repository, never forks.
|
||||||
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository
|
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository
|
||||||
runs-on: peppa-trusted
|
runs-on: peppa-trusted
|
||||||
timeout-minutes: 45
|
timeout-minutes: 30
|
||||||
env:
|
env:
|
||||||
# Peppa's data is SQLite (a temp file per test file). Postgres on the host is only the source
|
# Peppa's data is SQLite (a temp file per test file). Postgres on the host is only the source
|
||||||
# for the Postgres → SQLite migration test, which makes and drops its own database.
|
# for the Postgres → SQLite migration test, which makes and drops its own database.
|
||||||
@ -34,13 +34,7 @@ jobs:
|
|||||||
node-version: "26"
|
node-version: "26"
|
||||||
- name: tools
|
- name: tools
|
||||||
run: |
|
run: |
|
||||||
# PEP-271: a mirror mid-sync fails `apt-get update`; with `&&` the install was skipped silently
|
apt-get update -qq && apt-get install -y -qq tmux >/dev/null
|
||||||
# and every e2e test died later on «spawn tmux ENOENT». Retry, then fail here if tmux is missing.
|
|
||||||
for i in 1 2 3; do
|
|
||||||
{ apt-get update -qq && apt-get install -y -qq tmux >/dev/null; } && break
|
|
||||||
echo "apt: attempt $i failed, retrying"; sleep $((i * 15))
|
|
||||||
done
|
|
||||||
command -v tmux >/dev/null || { echo "::error::tmux was not installed (apt mirror unavailable)"; exit 1; }
|
|
||||||
# Job-local prefix: the node toolcache is shared between jobs running at the same time
|
# Job-local prefix: the node toolcache is shared between jobs running at the same time
|
||||||
# (PR + push of one commit), and two global installs into it collide (ENOTEMPTY/EEXIST).
|
# (PR + push of one commit), and two global installs into it collide (ENOTEMPTY/EEXIST).
|
||||||
npm install -g --prefix "$RUNNER_TEMP/tools" pnpm@12.18.0 @fission-ai/openspec@2.0.0 >/dev/null
|
npm install -g --prefix "$RUNNER_TEMP/tools" pnpm@12.18.0 @fission-ai/openspec@2.0.0 >/dev/null
|
||||||
@ -55,14 +49,9 @@ jobs:
|
|||||||
- name: typecheck
|
- name: typecheck
|
||||||
if: (success() || failure()) && steps.install.outcome == 'success'
|
if: (success() || failure()) && steps.install.outcome == 'success'
|
||||||
run: bash .gitea/peppa-check.sh typecheck
|
run: bash .gitea/peppa-check.sh typecheck
|
||||||
- id: build
|
- name: build
|
||||||
name: build
|
|
||||||
if: (success() || failure()) && steps.install.outcome == 'success'
|
if: (success() || failure()) && steps.install.outcome == 'success'
|
||||||
run: bash .gitea/peppa-check.sh build
|
run: bash .gitea/peppa-check.sh build
|
||||||
# PEP-217: weight of the first-load JS of every route against docs/bundle-baseline.json (+10 % fails).
|
|
||||||
- name: bundle
|
|
||||||
if: (success() || failure()) && steps.install.outcome == 'success' && steps.build.outcome == 'success'
|
|
||||||
run: bash .gitea/peppa-check.sh bundle
|
|
||||||
- name: test
|
- name: test
|
||||||
if: (success() || failure()) && steps.install.outcome == 'success'
|
if: (success() || failure()) && steps.install.outcome == 'success'
|
||||||
run: bash .gitea/peppa-check.sh test
|
run: bash .gitea/peppa-check.sh test
|
||||||
|
|||||||
72
.peppa/memory.md
Normal file
72
.peppa/memory.md
Normal file
@ -0,0 +1,72 @@
|
|||||||
|
# Память проекта
|
||||||
|
|
||||||
|
Пишет агент через `remember` (PEP-30); не повторяй AGENTS.md.
|
||||||
|
|
||||||
|
## Команды
|
||||||
|
- Тесты из шелла Claude: `env -u NODE_TEST_CONTEXT -u NODE_TEST_WORKER_ID node --test --test-reporter=spec test/<file>.test.ts` (иначе тесты молча не запускаются). В свежем worktree сначала `pnpm install --frozen-lockfile`.
|
||||||
|
- CLI против живой системы (сервер): `docker exec peppa-watchdog peppa …` (docs/SERVER.md).
|
||||||
|
- Экраны без живых данных: `PEPPA_HOME=<tmp> PEPPA_DB=<tmp>/peppa.db PEPPA_SECRET=x peppa db migrate` (Node < 26 — `node packages/cli/src/index.ts`), `DATABASE_URL=… node apps/web/scripts/mock-ui-seed.ts mock-pm`, в apps/web `node server.ts [--dev] -p <порт>` с тем же env + `PEPPA_WEB_URL=http://localhost:<порт> PEPPA_RUNNER_MODE=inline PEPPA_ROTATE=off`; вход — `peppa web login-link mock-pm`; «Инженер» — settings `ui.mode:<userId>` = `"engineer"`.
|
||||||
|
- Словарь: `pnpm lint`; почистил тексты экрана — `pnpm lint --update` (baseline только уменьшать); новое слово в «Нельзя» — сразу `pnpm lint`, оно может стоять в чужих текстах.
|
||||||
|
|
||||||
|
## Грабли
|
||||||
|
- `resumeSession` у сессии без `conversationId` пишет событие `started`, не `resumed`.
|
||||||
|
- `next dev` правит apps/web/AGENTS.md (он в git — `git checkout`, не `rm`) и next-env.d.ts — не коммитить. Открывать `http://localhost:<порт>`, не 127.0.0.1 (allowedDevOrigins — без гидрации кнопки молчат).
|
||||||
|
- Headless Chrome: playwright-core + `chrome-headless-shell`, cookie из curl-jar в `ctx.addCookies`; обрыв канала — `globalThis.__peppaLive.ws.close()`.
|
||||||
|
- CLI из теста с моком в том же процессе — только async execFile. Тест не импортирует apps/web статически — `import(new URL(…).href)`.
|
||||||
|
- Шаблонная строка с t()/m() внутри (`` `<b>${t("…")}</b>` ``) i18n-check считает непереведённой — собирай конкатенацией. В apps/bot `m` импортирован как `tr`.
|
||||||
|
- localizeText выбирает вариант по числу НЕпереведённых русских букв, не по кириллице: казахский тоже кириллица.
|
||||||
|
- mock-gitea `POST /tags` ставит настоящий git-тег: нужны коммиты (`addRepo(…, { files })`) и существующий SHA (`gitea.sha(owner, repo, "main")`), иначе `deployProd`/`autoPublish` в тесте молча не срабатывают. Gitea «лежит» — `gitea.down = true`.
|
||||||
|
- git-прокси релея (allowedGitPath) отклоняет %2e/%2f/%5c/%25 и `\`: fetch сворачивает %2e%2e как dot-сегмент.
|
||||||
|
- Новая фраза Claude о лимите — в `parseResetTime` и таблицу limits.test.ts, иначе подписка зря считается свободной. Codex 0.169 без `--full-auto`: режим — `CODEX_DEFAULT_MODE` (providers.ts), срочно — `PEPPA_CODEX_MODE` в .env.
|
||||||
|
- Скорость: `apps/web/scripts/bench-pages.ts`, канал — `bench-live.ts` (база — после `peppa db migrate`); N+1 — `workLineIndex`. Правишь 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-ить, иначе rt.dispose падает.
|
||||||
|
- Настройки по префиксу — `keyPrefix(settings.key, "x:")` из @peppa/db, не `like(…"x:%")` (LIKE без индекса). Индексы — тест db-indexes.
|
||||||
|
- Смержено ≠ на сайте: сверь `/api/health` commit с main.
|
||||||
|
- 530 при живом сервере — обрыв Mac → сервер (PEP-245); лечит только перенос адресов (ключ Cloudflare).
|
||||||
|
- Продукт на другой docker — только `scripts/server-move/products-move.sh` (PEP-231, с данными); `peppa deploy redeploy` поднимает с пустыми томами.
|
||||||
|
- Агент в контейнере не видит хост сервера, Mac и Cloudflare (PEP-231): инфраструктуру — скриптом в `scripts/server-move/` + шаги в docs/SERVER.md, выполнить просить суперадмина через `report_blocker`.
|
||||||
|
- Пути сессий с Mac (PEP-246): `runnerCwd` пересоздаёт копию сам; чистка — `peppa session paths --fix`.
|
||||||
|
- Сервер (PEP-230): docs/SERVER.md. Нет глобального git в контейнере: автор — `gitRelayEnv`; иначе `git -c user.name=peppa-bot -c user.email=peppa-bot@telecom.quest commit`.
|
||||||
|
- Песочница раннера: нет tmux, openspec, Node 26 (есть 22). tmux — .deb с deb.debian.org (tmux_3.3a-3, libevent-core-2.1-7_2.1.12-stable-8, libutempter0) → `dpkg-deb -x` + LD_LIBRARY_PATH; openspec — `npm i -g --prefix /tmp/os @fission-ai/openspec`; тесты на 22 — MIN_MAJOR в scripts/lib/require-node.mjs (не коммитить). Падают и на main (среда): glossary-check.test, тесты хостов в sandbox-hosts.test.ts (нет ssh).
|
||||||
|
- 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.
|
||||||
|
|
||||||
|
## Соглашения
|
||||||
|
- Специалисты (PEP-183): агент с непустым character — специалист; подбор — `runner/team-match.ts` (haiku, `PEPPA_TEAM_BIN`), результат `team.match:<taskId>`, порог ожидания `platform.team.waitMin`; в `ensureSessionAgent` порядок: прежний → свободный специалист по профилю → универсал → специалист без очереди.
|
||||||
|
- i18n (PEP-98): текст пользователю — ключ = русская строка в `t()`/`m()` + перевод в `i18n/en|kk/<раздел>.ts` (иначе падают i18n-check/i18n-kk). «Peppa FACTORY» не склоняется (kk: Peppa FACTORY-нің); к {плейсхолдеру} kk-окончание не клеить. Тексты агентам говорят «Пеппа» — не трогаем.
|
||||||
|
- Слова по режиму (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.
|
||||||
|
- Инструкция подключения к своему Claude/ChatGPT (PEP-135): `/help/connect`, тексты — `core/connect-texts.ts` (`CONNECT_HELP` ru/kk/en одной формы, тест `connect-help.test.ts`); изменились экраны подключения или инструменты удалённого MCP — править её; копирование — `<CopyText>`.
|
||||||
|
- Словарь в сообщениях ядра (PEP-129/137): `pnpm lint` проверяет литералы в `m()/tr()/t()` packages/core|runner|mcp; подсказку агенту в `m()` не оборачивать; запрещённое слово — переписать (ключ и в `i18n/en|kk`, тестах) или `glossary-ignore: <почему>` строкой выше; человеку мимо переводов — `glossary-user: <почему>`.
|
||||||
|
- Служебный текст (PEP-154): текст агента/терминала человеку — через `userText` (core/user-text.ts); исключение владельцу не слать — `platformFailure` (строка только для PeppaError).
|
||||||
|
- Чужой текст в сообщениях (PEP-139/140): чужие слова в `m()` — `asIs(…)`, фразы фабрики не помечай; текст вопроса читателю — `questionText(q)`, MCP/CLI/тестам — `stripAsIs`.
|
||||||
|
- Один голос (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).
|
||||||
|
- Вопрос ≠ задача (PEP-153): текст человека, который может стать задачей, — через `classifyMessage` (runner/message-intent.ts; в тестах mock-intake роль `intent`); молча задачу не заводить — кнопки (`chat.offer:<messageId>`, `INTENT_TEXT`).
|
||||||
|
- Задачу агента заводи через createTask с origin (acceptance|incident|analyst) и fileStories/checkDuplicate (PEP-197); «Предложено» = backlog + tasks.proposed, readyBacklog их не отдаёт; автомерж задач агента — по autonomy.acceptOwn (mayAutoAcceptTask).
|
||||||
|
- Неудачная версия (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): идут контейнеры `GITEA-ACTIONS-TASK-*` — не рестартовать; голова без ci.yml или >2 суток — `orphan`, не очередь.
|
||||||
|
|
||||||
|
## Решения
|
||||||
|
- 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`.
|
||||||
|
- Сообщения людям — только через `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.
|
||||||
|
- Эталон (PEP-184, PM): подписка прогона — наименее загруженная свободная из общего пула; про подписку PM не спрашивать.
|
||||||
|
- Речь — свой faster-whisper (`<Dictate>`). Google: по почте учётки не склеиваем.
|
||||||
|
- Секреты (PEP-253): агенту — `agent_env` при `project.agent-secrets` (нет строки = вкл.); в тестах — `{ agent: true }`.
|
||||||
|
- Привязка Google к чужой Google-only учётке — `mergeUserInto`; с eGov/Gitea — отказ (PEP-195).
|
||||||
|
- Язык голоса (PEP-131): `transcribeLanguage(cfg, locale)` — язык интерфейса говорящего; новый вызов `transcribe` передаёт его пятым аргументом.
|
||||||
@ -1,34 +0,0 @@
|
|||||||
# Память проекта
|
|
||||||
|
|
||||||
Пишет агент через MCP `remember` (PEP-30); файл на задачу — `.peppa/memory/<ключ>.md` (PEP-306).
|
|
||||||
|
|
||||||
## Команды
|
|
||||||
- Тесты из шелла Claude: `env -u NODE_TEST_CONTEXT -u NODE_TEST_WORKER_ID node --test --test-reporter=spec test/<file>.test.ts` (иначе тесты молчат). В свежем worktree сначала `pnpm install --frozen-lockfile`.
|
|
||||||
- CLI против живой системы (сервер): `docker exec peppa-watchdog peppa …` (docs/SERVER.md).
|
|
||||||
- Экраны без живых данных: `PEPPA_HOME=<tmp> PEPPA_DB=<tmp>/peppa.db PEPPA_SECRET=x peppa db migrate` (Node < 26 — `node packages/cli/src/index.ts`), `DATABASE_URL=… node apps/web/scripts/mock-ui-seed.ts mock-pm`, в apps/web `node server.ts [--dev] -p <порт>` с тем же env + `PEPPA_WEB_URL=http://localhost:<порт> PEPPA_RUNNER_MODE=inline PEPPA_ROTATE=off`; вход — `peppa web login-link mock-pm`; «Инженер» — settings `ui.mode:<userId>` = `"engineer"`.
|
|
||||||
- Словарь: `pnpm lint`; почистил тексты экрана — `pnpm lint --update` (baseline только уменьшать); новое слово в «Нельзя» — сразу `pnpm lint`, оно может стоять в чужих текстах.
|
|
||||||
|
|
||||||
## Грабли
|
|
||||||
- `resumeSession` без `conversationId` пишет `started`, не `resumed`.
|
|
||||||
- `next dev` правит apps/web/AGENTS.md (`git checkout`, не `rm`) и next-env.d.ts — не коммитить; открывать `localhost`, не 127.0.0.1. В песочнице dev перезагружает страницы по кругу — экраны смотри на `next build` + `node server.ts -p`.
|
|
||||||
- Headless Chrome: playwright-core + `chrome-headless-shell` (песочница: `npx playwright-core install chromium-headless-shell`; библиотеки — .deb bookworm из Packages.gz → `dpkg-deb -x` + LD_LIBRARY_PATH, шрифты fonts-dejavu-core + FONTCONFIG_PATH); вход — `peppa web login-link`; обрыв канала — `globalThis.__peppaLive.ws.close()`.
|
|
||||||
- CLI из теста с моком в том же процессе — только async execFile. Тест не импортирует apps/web статически — `import(new URL(…).href)`.
|
|
||||||
- Шаблонная строка с t()/m() внутри (`` `<b>${t("…")}</b>` ``) i18n-check считает непереведённой — собирай конкатенацией. В apps/bot `m` импортирован как `tr`.
|
|
||||||
- localizeText выбирает вариант по числу НЕпереведённых русских букв, не по кириллице: казахский тоже кириллица.
|
|
||||||
- mock-gitea `POST /tags` ставит настоящий git-тег: нужны коммиты (`addRepo(…, { files })`) и существующий SHA (`gitea.sha(owner, repo, "main")`), иначе `deployProd`/`autoPublish` в тесте молча не срабатывают. Gitea «лежит» — `gitea.down = true`.
|
|
||||||
- git-прокси релея (allowedGitPath) отклоняет %2e/%2f/%5c/%25 и `\`: fetch сворачивает %2e%2e как dot-сегмент.
|
|
||||||
- Новая фраза Claude о лимите — в `parseResetTime` и limits.test.ts. Codex 0.169 без `--full-auto`: режим — `CODEX_DEFAULT_MODE` (providers.ts), срочно — `PEPPA_CODEX_MODE` в .env.
|
|
||||||
- Скорость: `apps/web/scripts/bench-pages.ts`, канал — `bench-live.ts`; правишь live.ts — перезапусти server.ts, не `pkill -f next-server`.
|
|
||||||
- Хук грузит только лёгкий `runner/limit-delay.ts`, не flow.ts. В тесте хука PEPPA_GENERATION = поколение сессии (вставленной руками — 0).
|
|
||||||
- Настройки по префиксу — `keyPrefix(settings.key, "x:")` из @peppa/db, не `like(…"x:%")` (LIKE без индекса). Индексы — тест db-indexes.
|
|
||||||
- Номер миграции занят соседом после мержа — взять meta из main, `pnpm db:generate`, переименовать.
|
|
||||||
- Нет глобального git в контейнере: автор — `gitRelayEnv`; иначе `git -c user.name=peppa-bot -c user.email=peppa-bot@telecom.quest commit`.
|
|
||||||
- Песочница раннера: нет tmux и Node 26 — `node-v26…-linux-x64.tar.gz` (не .xz) в /tmp; tmux — .deb (tmux_3.3a-3, libevent-core-2.1-7, libutempter0) → `dpkg-deb -x` + LD_LIBRARY_PATH. Падают и на main (среда): glossary-check.test, sandbox-hosts.test.ts (нет ssh).
|
|
||||||
- Пропал `.git/worktrees/s<id>`: создать с `HEAD`, `commondir` `../..`, `gitdir`, затем `git reset`.
|
|
||||||
- Зависимость с build-скриптом (ssh2, cpu-features) роняет `pnpm install --frozen-lockfile` (ERR_PNPM_IGNORED_BUILDS): реши в `allowBuilds` pnpm-workspace.yaml.
|
|
||||||
|
|
||||||
## Соглашения
|
|
||||||
- Тесты: места подписки занимай `core.createSession` с `subscriptionId`; очередь ёмкости чисти `moveTask(backlog)`. Конец хода вопроса не создаёт — жди `idle`. Суперадмин — `superadmin()`. Текст чатов — через `stripAsIs`.
|
|
||||||
|
|
||||||
## Решения
|
|
||||||
- Речь — свой faster-whisper (`<Dictate>`). Google: по почте учётки не склеиваем.
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-129
|
|
||||||
|
|
||||||
## Соглашения
|
|
||||||
- Словарь в сообщениях ядра (PEP-129/137): `pnpm lint` проверяет литералы в `m()/tr()/t()` packages/core|runner|mcp; подсказку агенту в `m()` не оборачивать; запрещённое слово — переписать (ключ и в `i18n/en|kk`, тестах) или `glossary-ignore: <почему>` строкой выше; человеку мимо переводов — `glossary-user: <почему>`.
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-135
|
|
||||||
|
|
||||||
## Соглашения
|
|
||||||
- Инструкция подключения к своему Claude/ChatGPT (PEP-135): `/help/connect`, тексты — `core/connect-texts.ts` (`CONNECT_HELP` ru/kk/en одной формы, тест `connect-help.test.ts`); изменились экраны подключения или инструменты удалённого MCP — править её; копирование — `<CopyText>`.
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-154
|
|
||||||
|
|
||||||
## Соглашения
|
|
||||||
- Служебный текст (PEP-154): текст агента/терминала человеку — через `userText` (core/user-text.ts); исключение владельцу не слать — `platformFailure` (строка только для PeppaError).
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-158
|
|
||||||
|
|
||||||
## Соглашения
|
|
||||||
- Неудачная версия (PEP-158): `rolled_back`/`failed` → агенту задачи, `returnFailedRelease` (runner/deploy-feedback.ts); счётчик — `attempts` задержки `deploy` (3 — суперадмину, 6 — стоп).
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-183
|
|
||||||
|
|
||||||
## Соглашения
|
|
||||||
- Специалисты (PEP-183): агент с непустым character — специалист; подбор — `runner/team-match.ts` (haiku, `PEPPA_TEAM_BIN`), результат `team.match:<taskId>`, порог ожидания `platform.team.waitMin`; в `ensureSessionAgent` порядок: прежний → свободный специалист по профилю → универсал → специалист без очереди.
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-195
|
|
||||||
|
|
||||||
## Решения
|
|
||||||
- Привязка Google к чужой Google-only учётке — `mergeUserInto`; с eGov/Gitea — отказ (PEP-195).
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-198
|
|
||||||
|
|
||||||
## Соглашения
|
|
||||||
- Один голос (PEP-198): человеку пишет только Аналитик — вопрос агента через `relayAgentQuestion` (runner/question-relay.ts), задачи из чата — только оффер `stories` и кнопка; новая строка сообщения роли — в `ROLE_MESSAGE_KEYS` выше «Агент {name}», иначе он её съест.
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-208
|
|
||||||
|
|
||||||
## Решения
|
|
||||||
- Сообщения людям — только через `telegram_outbox`/`push_outbox`: ночная тишина 23–08 (PEP-208) стоит на их выборке; тестам и стенду `PEPPA_NIGHT_QUIET=off`.
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-209
|
|
||||||
|
|
||||||
## Решения
|
|
||||||
- Застрявшая задача (PEP-209): лечит `stuckTaskTick` — платформа сама на ревью/в «Готово», агенту — новый процесс (`restartAgent`: старый не вернёт MCP), не `sendToSession`. Новая причина задержки с повторами — `platformDelay` с `retryMin`/`retryAt`, суперадмину кнопки — `buttons: true`.
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-212
|
|
||||||
|
|
||||||
## Грабли
|
|
||||||
- QuickJS (PEP-212): строки из хост-функции читай до await; все хэндлы и deferred dispose-ить.
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-213
|
|
||||||
|
|
||||||
## Решения
|
|
||||||
- Медленные запросы (PEP-213): `core/request-timing.ts` (`http.Server` в instrumentation.ts, probe в db) → warning Bugsink; порог `PEPPA_SLOW_REQUEST_MS`.
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-217
|
|
||||||
|
|
||||||
## Решения
|
|
||||||
- Вес JS: `bundle-check.mjs --update`.
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-218
|
|
||||||
|
|
||||||
## Соглашения
|
|
||||||
- Bugsink API (PEP-218): схема — `GET /api/canonical/0/schema/` (2.6.3); `q` = текст + теги `key:value`; числа пользователей нет. Экран — `core/bugsink-errors.ts` (кэш 45 с), действия — `runner/bugsink-errors.ts`.
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-221
|
|
||||||
|
|
||||||
## Решения
|
|
||||||
- История (PEP-221): журнал/статусы — `history.db` (core/history.ts), логи — `archive/<вид>/<день>.jsonl.gz`; из основной базы события удаляет только `runRetention` после переноса.
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-222
|
|
||||||
|
|
||||||
## Решения
|
|
||||||
- Docker (PEP-222): раннеры по умолчанию `container` (тесты — `PEPPA_DEFAULT_ISOLATION=none`).
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-223
|
|
||||||
|
|
||||||
## Грабли
|
|
||||||
- observe.db: схема — `MIGRATIONS` по `user_version` (core/observe.ts); напоминания (PEP-223) — `remindIncidents`; в тестах «бот днём» помечай outbox `sent`, иначе напоминание заменит прежнее.
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-224
|
|
||||||
|
|
||||||
## Соглашения
|
|
||||||
- Узкие места: подписка — `pickSubscription`/`rotationCandidate`; агент — `startRunner`/`resumeSession`, модель — `claudePrint`, сообщение — `deliverToUser`; проекты — `listProjects`/`userProjectIds` (`from(projects)` — с `isNull(deletedAt)`); веб → runnerCall; функция от внешнего сервиса — `featureGateView` + `<FeatureGate>` (PEP-224).
|
|
||||||
@ -1,7 +0,0 @@
|
|||||||
# Память: PEP-230
|
|
||||||
|
|
||||||
## Грабли
|
|
||||||
- Сервер (PEP-230): docs/SERVER.md. Docker-клиент образа 20.10 (PEP-287).
|
|
||||||
|
|
||||||
## Решения
|
|
||||||
- Живой сайт (с PEP-230 — сервер, контейнеры) — только `scripts/platform-deploy.sh` из `~/peppa/src` на main (docs/SERVER.md); launchd/live-deploy.sh — только откат на Mac.
|
|
||||||
@ -1,5 +0,0 @@
|
|||||||
# Память: PEP-231
|
|
||||||
|
|
||||||
## Грабли
|
|
||||||
- Продукт на другой docker — только `scripts/server-move/products-move.sh` (PEP-231, с данными); `peppa deploy redeploy` поднимает с пустыми томами.
|
|
||||||
- Агент в контейнере не видит хост сервера, Mac и Cloudflare (PEP-231): инфраструктуру — скриптом в `scripts/server-move/` + шаги в docs/SERVER.md, выполнить просить суперадмина через `report_blocker`.
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-233
|
|
||||||
|
|
||||||
## Соглашения
|
|
||||||
- act_runner (PEP-233/248): идут контейнеры `GITEA-ACTIONS-TASK-*` — не рестартовать; голова без ci.yml или >2 суток — `orphan`, не очередь; `not_taken` — pending, а другие проекты отчитываются.
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-234
|
|
||||||
|
|
||||||
## Грабли
|
|
||||||
- SSRF-проверка в `lookup` — только с `agent: false` (keep-alive Node пропускает lookup, PEP-234).
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-241
|
|
||||||
|
|
||||||
## Грабли
|
|
||||||
- Codex (PEP-241): доверие папке — по корню основного репо worktree; `-c` режет ключ по точкам — пишем в config.toml CODEX_HOME (`codex-trust.ts`).
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-242
|
|
||||||
|
|
||||||
## Решения
|
|
||||||
- `template/` уходит в Gitea сам с выкаткой (PEP-242); старым проектам — `peppa ci connect <KEY> [--secrets-only]`.
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-245
|
|
||||||
|
|
||||||
## Грабли
|
|
||||||
- 530 при живом сервере — обрыв Mac → сервер (PEP-245); лечит только перенос адресов (ключ Cloudflare).
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-246
|
|
||||||
|
|
||||||
## Грабли
|
|
||||||
- Пути сессий с Mac (PEP-246): `runnerCwd` пересоздаёт копию сам; чистка — `peppa session paths --fix`.
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-249
|
|
||||||
|
|
||||||
## Соглашения
|
|
||||||
- Access Hub (PEP-249): новый HTTP-сервис — карточка в `core/connection-catalog.ts` (тест сверяет каждую); меняет данные через GET (Slack) — чтение по методам. Новый не-HTTP вид (PEP-251) — операция в `PROTOCOL_OPERATIONS`, драйвер `GatewayDrivers` (берёт проверенный `address`, DNS не разрешает) и мок в testkit/mock-access.ts. Ответ сервиса агенту (PEP-258) — только через `connectionKeyForms`+`maskConnectionKey`; новый способ ключа — в тест-ловушку access-hub.test.ts.
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-250
|
|
||||||
|
|
||||||
## Соглашения
|
|
||||||
- Access Hub (PEP-250): сервис агенту — `request_access`; форму отказа `callConnection` не менять, автозапрос — `refusedCallService`.
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-252
|
|
||||||
|
|
||||||
## Грабли
|
|
||||||
- Шлюз Access Hub (PEP-252): `cleanPath` не пускает голое «:» в пути — Google-диапазоны и методы (`A1:B2`, `:batchUpdate`) агент шлёт как `%3A`. OAuth-тесты: `MockOAuthService` + `fetch`, переписывающий адрес сервиса на мок (`toMock`).
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-253
|
|
||||||
|
|
||||||
## Решения
|
|
||||||
- Секреты (PEP-253): агенту — `agent_env` при `project.agent-secrets` (нет строки = вкл.); в тестах — `{ agent: true }`.
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-254
|
|
||||||
|
|
||||||
## Решения
|
|
||||||
- Access Hub (PEP-254): журнал — только `appendJournal` (core/connection-journal.ts, цепочка хэшей; правка строки задним числом = нарушение), ключ подключения — `sealConnectionSecret`/`openConnectionSecret`, не `encrypt`/`decrypt`.
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-255
|
|
||||||
|
|
||||||
## Грабли
|
|
||||||
- Очередь проверок (PEP-255): `checks.queue` — `projects` (своя зависшая голова) и `lanes` (`ciLane`); `requestRebase` → false = просьба не ушла.
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-256
|
|
||||||
|
|
||||||
## Грабли
|
|
||||||
- tmux на сервере (PEP-256) — контейнер `peppa-tmux`, сервисы — клиенты (`PEPPA_TMUX_EXTERNAL`); его образ меняет только `platform-deploy.sh --tmux`. Нет docker — compose проверяй парсером `yaml` (`{merge:true}`).
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-260
|
|
||||||
|
|
||||||
## Решения
|
|
||||||
- Access Hub (PEP-260): агенту — только текст (`isTextResponse`) + `TEXT_TYPES`.
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-265
|
|
||||||
|
|
||||||
## Грабли
|
|
||||||
- Состояние вачдога, которое пишет не вачдог (хук, launch), — только `markWatch` (json_set): `patchWatch` перезаписывает весь watch_state (PEP-265).
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-266
|
|
||||||
|
|
||||||
## Решения
|
|
||||||
- Проверка запуска (PEP-266) идёт в платформенном проекте, не в отдельной строке проекта: тики обходят все проекты и шлют ложные сбои.
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-267
|
|
||||||
|
|
||||||
## Грабли
|
|
||||||
- Версии CLI агентов (PEP-267) — только `scripts/runner-image.sh --try <cli> <версия>` (json + оба Dockerfile), откат `--rollback`.
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-268
|
|
||||||
|
|
||||||
## Соглашения
|
|
||||||
- Сбой платформы — `planPlatformRetry` (PEP-268), `restarts` не трогать; мок `hangAtStart`.
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-269
|
|
||||||
|
|
||||||
## Соглашения
|
|
||||||
- Конфликт PR с main (PEP-269) — только `conflictStep` (runner/conflict-step.ts), не `requestRebase` напрямую; сироты — `orphanConflictTick` (PEP-301).
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-272
|
|
||||||
|
|
||||||
## Решения
|
|
||||||
- `/api/health` анониму — только `{ok}` (PEP-272); сводку читать с `healthHeaders()` / `scripts/lib/health-token.sh`.
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-273
|
|
||||||
|
|
||||||
## Соглашения
|
|
||||||
- Ссылки веба — только `Link` из `@/components/Link` (предзагрузка выкл., PEP-273; тест no-prefetch); медленная страница из-за Gitea — кэш в globalThis, как `giteaServerOverview`.
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-274
|
|
||||||
|
|
||||||
## Решения
|
|
||||||
- Заголовок вкладки (PEP-274) — `pageTitle`/`projectTitle`/`taskTitle` (apps/web/lib/title.ts); page.tsx без `generateMetadata` роняет page-titles.test.ts.
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-278
|
|
||||||
|
|
||||||
## Соглашения
|
|
||||||
- «Готово» после выкатки (PEP-278): статус `done` не трогаем — поверх него отметка `rollout.wait:<taskId>` (core/rollout.ts), экран — псевдостатус `rollout` в `TASK_STATUS`; снимает `rolloutTick`.
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-279
|
|
||||||
|
|
||||||
## Решения
|
|
||||||
- Старые вопросы (PEP-279) закрываются только `default_option`; без него — без выбора: варианты фабрики (бюджет, подписка) за человека не выбираем.
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-281
|
|
||||||
|
|
||||||
## Грабли
|
|
||||||
- Git — только git.vibe42.kz; старый адрес в репо ловит old-git-cleanup.test.ts (PEP-281).
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-282
|
|
||||||
|
|
||||||
## Грабли
|
|
||||||
- Таймаут запроса в процессе с моком-сервером: синхронная пауза дольше таймаута обрывает готовый ответ (таймеры libuv раньше сокетов) — `responsiveTimeout` (core, PEP-282), не `AbortSignal.timeout`.
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-283
|
|
||||||
|
|
||||||
## Решения
|
|
||||||
- Стек новых проектов — docs/standards/default-stack.md (PEP-283).
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-291
|
|
||||||
|
|
||||||
## Грабли
|
|
||||||
- Песочница раннера: Node 22.23 тянет одиночные тесты (PEP-291).
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-292
|
|
||||||
|
|
||||||
## Грабли
|
|
||||||
- В образе платформы нет `.git` (PEP-292): `git` в коде службы не звать; коммит — `PEPPA_COMMIT`, история main — Gitea API.
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-294
|
|
||||||
|
|
||||||
## Решения
|
|
||||||
- Суперадмины (PEP-294): `platform.admins` — id учёток (строка = логин без учётки, привязывается при чтении); проверка — `superadminIds`/`platformAdminUsers`, не сравнение логинов.
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-295
|
|
||||||
|
|
||||||
## Соглашения
|
|
||||||
- Задача не от человека — `createTask` с origin сама в «Предложено» (PEP-295), путь — проверить `proposalRoom` до создания; новый вызов `createTask` — в список `proposals-only.test.ts`; автомерж — autonomy.acceptOwn.
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-298
|
|
||||||
|
|
||||||
## Соглашения
|
|
||||||
- Конфликт PR с main: первая просьба — после второго наблюдения через 2 мин (PEP-298, в тестах `PEPPA_CONFLICT_SETTLE_MIN=0`).
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-299
|
|
||||||
|
|
||||||
## Грабли
|
|
||||||
- `stopSession` закрывает все вопросы сессии, и карточку «готово» с «Принять» — освобождать место без неё: `releaseReviewSession` (PEP-299).
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-302
|
|
||||||
|
|
||||||
## Грабли
|
|
||||||
- mock-intake `dedup` считает похожие названия («Идея 1»/«Идея 2») повтором — в тестах приёмки бери разные слова.
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-303
|
|
||||||
|
|
||||||
## Грабли
|
|
||||||
- Сторож экрана (PEP-303): строки — через `screen-lines.ts` (`isQuotedLine`/`ownLines`), фразу CLI якорить к началу строки, нажимать только на неизменном экране (`still`). Мок `say` печатает «⏺ » перед текстом.
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-304
|
|
||||||
|
|
||||||
## Соглашения
|
|
||||||
- Время людям (PEP-304) — только `platformTime`/`platformDayTime`/`platformZone` из `@peppa/shared/time`; `toLocale*String` для дат без `timeZone` не писать. Лимит в `claudePrint` — `limited`/`limitedUntil`, не «нет подписки».
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-306
|
|
||||||
|
|
||||||
## Грабли
|
|
||||||
- Память (PEP-306): пункт — только в `.peppa/memory/<ключ задачи>.md` своей задачи; MCP `remember` до выкатки PEP-306 пишет в старый `.peppa/memory.md` — тогда правь файл задачи руками (тест project-memory-size запрещает старый файл).
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-98
|
|
||||||
|
|
||||||
## Соглашения
|
|
||||||
- i18n (PEP-98): текст пользователю — ключ = русская строка в `t()`/`m()` + перевод в `i18n/en|kk/<раздел>.ts` (иначе падают i18n-check/i18n-kk). «Peppa FACTORY» не склоняется (kk: Peppa FACTORY-нің); к {плейсхолдеру} kk-окончание не клеить. Тексты агентам говорят «Пеппа» — не трогаем.
|
|
||||||
@ -8,7 +8,6 @@
|
|||||||
"lint": "pnpm lint",
|
"lint": "pnpm lint",
|
||||||
"typecheck": "pnpm -r typecheck",
|
"typecheck": "pnpm -r typecheck",
|
||||||
"build": "pnpm --filter @peppa/web build",
|
"build": "pnpm --filter @peppa/web build",
|
||||||
"bundle": "node scripts/bundle-check.mjs",
|
|
||||||
"test": "pnpm --filter @peppa/testkit test"
|
"test": "pnpm --filter @peppa/testkit test"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -80,8 +80,8 @@ import {
|
|||||||
} from "@peppa/core";
|
} from "@peppa/core";
|
||||||
import { projects, tasks, type Db } from "@peppa/db";
|
import { projects, tasks, type Db } from "@peppa/db";
|
||||||
import { formatTaskKey, voiceStoriesEnabled } from "@peppa/shared";
|
import { formatTaskKey, voiceStoriesEnabled } from "@peppa/shared";
|
||||||
import { delayAction, denyAccessRequestAndTell, resolveTaskById } from "@peppa/runner";
|
import { delayAction, resolveTaskById } from "@peppa/runner";
|
||||||
import { decideIdleGrant, parseDelayCallback, parseIdleGrantCallback } from "@peppa/core";
|
import { parseDelayCallback } from "@peppa/core";
|
||||||
import { acceptTask, answerAndDeliver, classifyMessage, decideIncident, decideProposals, moveTask, postToChat, REQUEST_SENT_TEXT, requestSubscription, resumeSession, stopSession } from "@peppa/runner";
|
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 { INTENT_TEXT, statusAnswer } from "@peppa/core";
|
||||||
import { AsyncLocalStorage } from "node:async_hooks";
|
import { AsyncLocalStorage } from "node:async_hooks";
|
||||||
@ -1019,22 +1019,6 @@ export function createBot(o: BotOptions) {
|
|||||||
await api.answerCallbackQuery(c.id, toast.slice(0, 190)).catch((e) => log(`answerCallbackQuery: ${e.message}`));
|
await api.answerCallbackQuery(c.id, toast.slice(0, 190)).catch((e) => log(`answerCallbackQuery: ${e.message}`));
|
||||||
return "done";
|
return "done";
|
||||||
}
|
}
|
||||||
// PEP-250: «Отказать» under an agent's access request: `ar:<id>:no` — only the project's owner (core checks).
|
|
||||||
if (parts[0] === "ar") {
|
|
||||||
const toast = await denyAccessRequestAndTell(db, user.id, Number(parts[1]), null).then(
|
|
||||||
() => tr("Отказано. Агент узнает об этом."),
|
|
||||||
(e) => (e instanceof PeppaError ? e.message : (log(`access request: ${(e as Error).stack ?? e}`), tr("Ошибка"))),
|
|
||||||
);
|
|
||||||
await api.answerCallbackQuery(c.id, toast.slice(0, 190)).catch((e) => log(`answerCallbackQuery: ${e.message}`));
|
|
||||||
return "done";
|
|
||||||
}
|
|
||||||
// PEP-259: the owner's answer to «агенты давно не пользуются разрешением — снять?»: `cg:<grantId>:r|k`.
|
|
||||||
if (parts[0] === "cg") {
|
|
||||||
const b = parseIdleGrantCallback(c.data ?? "");
|
|
||||||
const toast = b ? await decideIdleGrant(db, user.id, b.grantId, b.decision).catch((e) => (e instanceof PeppaError ? e.message : (log(`idle grant: ${(e as Error).stack ?? e}`), tr("Ошибка")))) : tr("Неизвестная кнопка");
|
|
||||||
await api.answerCallbackQuery(c.id, toast.slice(0, 190)).catch((e) => log(`answerCallbackQuery: ${e.message}`));
|
|
||||||
return "done";
|
|
||||||
}
|
|
||||||
if (parts[0] === "f") {
|
if (parts[0] === "f") {
|
||||||
const toast = await onFeedbackButton(user, c, parts).catch((e) => (log(`feedback: ${(e as Error).stack ?? e}`), tr("Ошибка")));
|
const toast = await onFeedbackButton(user, c, parts).catch((e) => (log(`feedback: ${(e as Error).stack ?? e}`), tr("Ошибка")));
|
||||||
wakeOutbox?.();
|
wakeOutbox?.();
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
import { createDb } from "@peppa/db";
|
import { createDb } from "@peppa/db";
|
||||||
import { loadEnv } from "@peppa/shared";
|
import { loadEnv } from "@peppa/shared";
|
||||||
import { setRunnerClient } from "@peppa/runner";
|
import { setRunnerClient } from "@peppa/runner";
|
||||||
import { installCrashReporting, installServiceLog } from "@peppa/core";
|
import { installCrashReporting } from "@peppa/core";
|
||||||
import { createBot } from "./bot.ts";
|
import { createBot } from "./bot.ts";
|
||||||
import { TelegramApi } from "./telegram.ts";
|
import { TelegramApi } from "./telegram.ts";
|
||||||
|
|
||||||
@ -16,8 +16,6 @@ const db = createDb(env.PEPPA_DB);
|
|||||||
setRunnerClient(true, db);
|
setRunnerClient(true, db);
|
||||||
// PEP-91: a crash of the bot goes to Bugsink before launchd restarts it.
|
// PEP-91: a crash of the bot goes to Bugsink before launchd restarts it.
|
||||||
installCrashReporting(db, "bot");
|
installCrashReporting(db, "bot");
|
||||||
// PEP-291: the log also goes to $PEPPA_HOME/logs/bot.log — it survives a redeploy.
|
|
||||||
installServiceLog("bot");
|
|
||||||
const bot = createBot({
|
const bot = createBot({
|
||||||
db,
|
db,
|
||||||
api: new TelegramApi(env.TELEGRAM_BOT_TOKEN, process.env.TELEGRAM_API_URL),
|
api: new TelegramApi(env.TELEGRAM_BOT_TOKEN, process.env.TELEGRAM_API_URL),
|
||||||
|
|||||||
@ -1,15 +1,13 @@
|
|||||||
// Entry point: `peppa-observer` (launchd agent quest.telecom.peppa.observer), PEP-202.
|
// Entry point: `peppa-observer` (launchd agent quest.telecom.peppa.observer), PEP-202.
|
||||||
import { createDb } from "@peppa/db";
|
import { createDb } from "@peppa/db";
|
||||||
import { loadEnv } from "@peppa/shared";
|
import { loadEnv } from "@peppa/shared";
|
||||||
import { installCrashReporting, installServiceLog, setDefaultActor } from "@peppa/core";
|
import { installCrashReporting, setDefaultActor } from "@peppa/core";
|
||||||
import { runObserver } from "./observer.ts";
|
import { runObserver } from "./observer.ts";
|
||||||
|
|
||||||
const env = loadEnv();
|
const env = loadEnv();
|
||||||
const db = createDb(env.PEPPA_DB);
|
const db = createDb(env.PEPPA_DB);
|
||||||
setDefaultActor({ kind: "system" });
|
setDefaultActor({ kind: "system" });
|
||||||
installCrashReporting(db, "observer");
|
installCrashReporting(db, "observer");
|
||||||
// PEP-291: the log also goes to $PEPPA_HOME/logs/observer.log — it survives a redeploy.
|
|
||||||
installServiceLog("observer");
|
|
||||||
const ac = new AbortController();
|
const ac = new AbortController();
|
||||||
for (const sig of ["SIGINT", "SIGTERM"] as const) process.on(sig, () => (ac.abort(), setTimeout(() => process.exit(0), 200)));
|
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);
|
await runObserver(db, { log: (m) => console.log(`${new Date().toISOString()} ${m}`) }, ac.signal);
|
||||||
|
|||||||
@ -3,7 +3,7 @@
|
|||||||
// 30 s it writes its heartbeat (the watchdog watches it like the bot and the web), every hour it
|
// 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
|
// 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.
|
// MCP change them, the service picks the change up on its next pass — no restart.
|
||||||
import { beat, featureTick, observeTick, pruneObserve, seedFeatureMonitors, seedMonitors, vitalsAlertTick, type ObserveProbes } from "@peppa/core";
|
import { beat, featureTick, observeTick, pruneObserve, seedFeatureMonitors, seedMonitors, type ObserveProbes } from "@peppa/core";
|
||||||
import { loadEnv } from "@peppa/shared";
|
import { loadEnv } from "@peppa/shared";
|
||||||
import type { Db } from "@peppa/db";
|
import type { Db } from "@peppa/db";
|
||||||
|
|
||||||
@ -24,7 +24,6 @@ export async function runObserver(db: Db, o: ObserverOptions = {}, signal?: Abor
|
|||||||
log("observer started");
|
log("observer started");
|
||||||
let lastBeat = 0;
|
let lastBeat = 0;
|
||||||
let lastPrune = 0;
|
let lastPrune = 0;
|
||||||
let lastVitals = 0;
|
|
||||||
while (!signal?.aborted) {
|
while (!signal?.aborted) {
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
if (now - lastBeat >= 30_000) {
|
if (now - lastBeat >= 30_000) {
|
||||||
@ -40,11 +39,6 @@ export async function runObserver(db: Db, o: ObserverOptions = {}, signal?: Abor
|
|||||||
log(`observer: prune failed: ${(e as Error).message}`);
|
log(`observer: prune failed: ${(e as Error).message}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// PEP-217: slow pages (p75 of real users) → one warning per route and day in Bugsink.
|
|
||||||
if (now - lastVitals >= 600_000) {
|
|
||||||
lastVitals = now;
|
|
||||||
void vitalsAlertTick(db).catch((e: Error) => log(`observer: vitals failed: ${e.message}`));
|
|
||||||
}
|
|
||||||
// Not awaited: a slow check must not hold the others or the heartbeat.
|
// 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}`));
|
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).
|
// PEP-224: features follow their monitors — announce a change (journal, channel, live pages).
|
||||||
|
|||||||
@ -26,8 +26,6 @@ import {
|
|||||||
type IncidentPolicy,
|
type IncidentPolicy,
|
||||||
getUser,
|
getUser,
|
||||||
isSuperadmin,
|
isSuperadmin,
|
||||||
getDirectOrigins,
|
|
||||||
setDirectOrigins,
|
|
||||||
setUserDisabled,
|
setUserDisabled,
|
||||||
setSuperadmin,
|
setSuperadmin,
|
||||||
mergeAccounts,
|
mergeAccounts,
|
||||||
@ -69,9 +67,9 @@ import {
|
|||||||
checkGiteaBotToken,
|
checkGiteaBotToken,
|
||||||
setUiMode,
|
setUiMode,
|
||||||
} from "@peppa/core";
|
} from "@peppa/core";
|
||||||
import { checkConnection, createConnection, decideIdleGrant, deleteConnection, DEFAULT_GRANT_TERM, extendGrant, grantConnection, isGatewayProtocol, isGrantTerm, replaceConnectionSecret, resetHostKey, revokeConnection, revokeGrant, setConnectionIdleHours, type CatalogAuth, type ConnectionCheckResult, type GrantMode, type GrantTerm } from "@peppa/core";
|
import { checkConnection, createConnection, deleteConnection, grantConnection, isGatewayProtocol, replaceConnectionSecret, resetHostKey, revokeConnection, revokeGrant, type CatalogAuth, type ConnectionCheckResult, type GrantMode } from "@peppa/core";
|
||||||
import { attachmentLabel, fixFeedback, linkAttachments, linkFeedback, parseAttachmentIds, rejectFeedback, restoreProject } from "@peppa/core";
|
import { attachmentLabel, fixFeedback, linkAttachments, linkFeedback, parseAttachmentIds, rejectFeedback, restoreProject } from "@peppa/core";
|
||||||
import { deleteProject, decideProposals, mergeProposals, connectAndGrantAccessRequest, denyAccessRequestAndTell, grantAccessRequestFromExisting, decideDeferred } from "@peppa/runner";
|
import { deleteProject, decideProposals, mergeProposals } from "@peppa/runner";
|
||||||
import { bugsinkFromEnv } from "@peppa/bugsink";
|
import { bugsinkFromEnv } from "@peppa/bugsink";
|
||||||
import { loadEnv } from "@peppa/shared";
|
import { loadEnv } from "@peppa/shared";
|
||||||
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 { 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";
|
||||||
@ -392,7 +390,7 @@ export async function createProjectAction(f: FormData) {
|
|||||||
key: str(f, "key"),
|
key: str(f, "key"),
|
||||||
name: str(f, "name"),
|
name: str(f, "name"),
|
||||||
existing: str(f, "mode") === "existing",
|
existing: str(f, "mode") === "existing",
|
||||||
visibility: str(f, "visibility") === "public" ? "public" : "private", // PEP-280: closed unless chosen
|
visibility: str(f, "visibility") === "private" ? "private" : "public",
|
||||||
ownerId: user.id,
|
ownerId: user.id,
|
||||||
});
|
});
|
||||||
return `/p/${p.key}?created=1`;
|
return `/p/${p.key}?created=1`;
|
||||||
@ -543,16 +541,6 @@ export async function proposalAction(f: FormData) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/** PEP-302: «Делать» / «Не надо» at a finding put aside until the weekly digest. */
|
|
||||||
export async function deferredAction(f: FormData) {
|
|
||||||
const user = asWebActor(await requireUser());
|
|
||||||
await attempt(f, async () => {
|
|
||||||
const choice = str(f, "choice");
|
|
||||||
if (choice !== "do" && choice !== "no") throw new PeppaError(m("Эта кнопка уже не работает."));
|
|
||||||
await decideDeferred(db, user, Number(str(f, "projectId")), str(f, "title"), choice);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/** PEP-197: «Принимать сами» — whose stories are accepted without the owner. */
|
/** PEP-197: «Принимать сами» — whose stories are accepted without the owner. */
|
||||||
export async function setAcceptOwnAction(f: FormData) {
|
export async function setAcceptOwnAction(f: FormData) {
|
||||||
const user = asWebActor(await requireUser());
|
const user = asWebActor(await requireUser());
|
||||||
@ -698,17 +686,6 @@ 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) {
|
export async function saveIncidentSettings(f: FormData) {
|
||||||
const user = asWebActor(await requireUser());
|
const user = asWebActor(await requireUser());
|
||||||
await attempt(f, async () => {
|
await attempt(f, async () => {
|
||||||
@ -1092,10 +1069,7 @@ export async function resetHostKeyAction(f: FormData) {
|
|||||||
export async function revokeConnectionAction(f: FormData) {
|
export async function revokeConnectionAction(f: FormData) {
|
||||||
const user = asWebActor(await requireUser());
|
const user = asWebActor(await requireUser());
|
||||||
await attempt(f, async () => {
|
await attempt(f, async () => {
|
||||||
const id = Number(str(f, "connectionId"));
|
await revokeConnection(db, user.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}`;
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -1112,68 +1086,7 @@ export async function grantConnectionAction(f: FormData) {
|
|||||||
await attempt(f, async () => {
|
await attempt(f, async () => {
|
||||||
const agent = str(f, "agentId");
|
const agent = str(f, "agentId");
|
||||||
const mode = (k: string): GrantMode => (["auto", "ask"].includes(str(f, k)) ? (str(f, k) as GrantMode) : "off");
|
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 });
|
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") ?? "") });
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/** PEP-259 «Продлить»: the same term again from now. */
|
|
||||||
export async function extendGrantAction(f: FormData) {
|
|
||||||
const user = asWebActor(await requireUser());
|
|
||||||
await attempt(f, async () => {
|
|
||||||
await extendGrant(db, user.id, Number(str(f, "grantId")));
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/** PEP-259: the owner's answer to «агенты давно не пользуются — снять?»: «Снять» / «Оставить». */
|
|
||||||
export async function decideIdleGrantAction(f: FormData) {
|
|
||||||
const user = asWebActor(await requireUser());
|
|
||||||
await attempt(f, async () => {
|
|
||||||
await decideIdleGrant(db, user.id, Number(str(f, "grantId")), str(f, "decision") === "revoke" ? "revoke" : "keep");
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/** PEP-259: «Спрашивать о разрешении без дела через …» of one connection ("" — platform default). */
|
|
||||||
export async function setConnectionIdleAction(f: FormData) {
|
|
||||||
const user = asWebActor(await requireUser());
|
|
||||||
await attempt(f, async () => {
|
|
||||||
const v = str(f, "idleHours");
|
|
||||||
await setConnectionIdleHours(db, user.id, Number(str(f, "connectionId")), v === "" ? null : Number(v));
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// PEP-250: an agent's access request — only its project's owner decides (core checks).
|
|
||||||
export async function connectAccessRequestAction(f: FormData) {
|
|
||||||
const user = asWebActor(await requireUser());
|
|
||||||
await attempt(f, async () => {
|
|
||||||
const id = Number(str(f, "requestId"));
|
|
||||||
const kind = str(f, "authKind") as CatalogAuth;
|
|
||||||
const { connection } = await connectAndGrantAccessRequest(db, user.id, id, {
|
|
||||||
name: str(f, "name"),
|
|
||||||
baseUrl: str(f, "baseUrl") || undefined,
|
|
||||||
secret: String(f.get("secret") ?? "").trim(),
|
|
||||||
authKind: AUTH_KINDS.includes(kind) ? kind : "bearer",
|
|
||||||
authHeader: str(f, "authHeader") || null,
|
|
||||||
});
|
|
||||||
const r = await checkConnection(db, user.id, connection.id).catch(() => null);
|
|
||||||
return `/connections/requests/${id}?done=granted&check=${checkWord(r)}`;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function grantAccessRequestAction(f: FormData) {
|
|
||||||
const user = asWebActor(await requireUser());
|
|
||||||
await attempt(f, async () => {
|
|
||||||
const id = Number(str(f, "requestId"));
|
|
||||||
await grantAccessRequestFromExisting(db, user.id, id, Number(str(f, "connectionId")));
|
|
||||||
return `/connections/requests/${id}?done=granted`;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function denyAccessRequestAction(f: FormData) {
|
|
||||||
const user = asWebActor(await requireUser());
|
|
||||||
await attempt(f, async () => {
|
|
||||||
const id = Number(str(f, "requestId"));
|
|
||||||
await denyAccessRequestAndTell(db, user.id, id, str(f, "reason") || null);
|
|
||||||
return `/connections/requests/${id}?done=denied`;
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -1,4 +1,4 @@
|
|||||||
import Link from "@/components/Link";
|
import Link from "next/link";
|
||||||
import { notFound } from "next/navigation";
|
import { notFound } from "next/navigation";
|
||||||
import { ArrowLeft, Bot, Link2, MessagesSquare, Send, Unlink, User as UserIcon } from "lucide-react";
|
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 { 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";
|
||||||
@ -21,13 +21,12 @@ import { AttachField } from "@/components/AttachField";
|
|||||||
import { Workspace } from "@/components/Workspace";
|
import { Workspace } from "@/components/Workspace";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Textarea } from "@/components/ui/input";
|
import { Textarea } from "@/components/ui/input";
|
||||||
import { currentUser, requireUser, words } from "@/lib/auth";
|
import { requireUser, words } from "@/lib/auth";
|
||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
import { getT } from "@/lib/i18n";
|
import { getT } from "@/lib/i18n";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
import { cleanText, messageLink, STUCK_NOTICE } from "@/lib/chat-text";
|
import { cleanText, messageLink, STUCK_NOTICE } from "@/lib/chat-text";
|
||||||
import { chatOfferAction, linkChatAction, postChatAction, unlinkChatAction } from "../actions";
|
import { chatOfferAction, linkChatAction, postChatAction, unlinkChatAction } from "../actions";
|
||||||
import { pageTitle } from "@/lib/title";
|
|
||||||
|
|
||||||
type Params = { error?: string; thread?: string; link?: string; q?: string; list?: string };
|
type Params = { error?: string; thread?: string; link?: string; q?: string; list?: string };
|
||||||
|
|
||||||
@ -35,16 +34,6 @@ const CHANNEL = "channel";
|
|||||||
/** PEP-106: `?thread=feed` — the agents' events; no `thread` — the people's discussion. */
|
/** PEP-106: `?thread=feed` — the agents' events; no `thread` — the people's discussion. */
|
||||||
const FEED = "feed";
|
const FEED = "feed";
|
||||||
|
|
||||||
// PEP-274: «Чат KEY — FORGE» (the chat list of the viewer — no names of chats they cannot see).
|
|
||||||
export async function generateMetadata({ params }: { params: Promise<{ chat: string }> }) {
|
|
||||||
const t = await getT();
|
|
||||||
const user = await currentUser();
|
|
||||||
const slug = (await params).chat;
|
|
||||||
const chat = user ? (await listChats(db, user)).find((c) => c.slug.toLowerCase() === slug.toLowerCase()) : null;
|
|
||||||
if (!chat) return pageTitle(t, t("Чаты"));
|
|
||||||
return pageTitle(t, chat.kind === "master" ? t("Все события") : t("Чат {key}", { key: chat.slug.toUpperCase() }));
|
|
||||||
}
|
|
||||||
|
|
||||||
/** «Чаты» (PEP-62): the master chat and project chats with threads; a linked Telegram group mirrors them. */
|
/** «Чаты» (PEP-62): the master chat and project chats with threads; a linked Telegram group mirrors them. */
|
||||||
export default async function ChatPage({ params, searchParams }: { params: Promise<{ chat: string }>; searchParams: Promise<Params> }) {
|
export default async function ChatPage({ params, searchParams }: { params: Promise<{ chat: string }>; searchParams: Promise<Params> }) {
|
||||||
const user = await requireUser();
|
const user = await requireUser();
|
||||||
@ -349,12 +338,11 @@ export default async function ChatPage({ params, searchParams }: { params: Promi
|
|||||||
{writable && (
|
{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">
|
<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 }} />
|
<Hidden fields={{ chatId: chat.id, thread: thread ?? "", back: here }} />
|
||||||
{/* PEP-274 (F-12): on a phone the field takes the whole row (the hint is not cut), the buttons go below, each ≥ 44 px. */}
|
<div className="flex items-end gap-1.5">
|
||||||
<div className="flex flex-wrap items-end gap-1.5 md:flex-nowrap">
|
<Textarea id="chat-text" name="text" rows={1} maxLength={60000} placeholder={placeholder} aria-label={t("Сообщение")} className="max-h-40 min-h-9 flex-1 resize-y py-1.5" />
|
||||||
<Textarea id="chat-text" name="text" rows={1} maxLength={60000} placeholder={placeholder} aria-label={t("Сообщение")} className="max-h-40 min-h-[4.25rem] flex-1 basis-full resize-y py-1.5 [field-sizing:content] md:min-h-9 md:basis-0" data-chat-text />
|
{chat.projectId && <AttachField projectId={chat.projectId} target="chat-text" className="shrink-0" />}
|
||||||
{chat.projectId && <AttachField projectId={chat.projectId} target="chat-text" className="shrink-0" touch />}
|
<Dictate target="chat-text" compact />
|
||||||
<Dictate target="chat-text" compact touch />
|
<Button size="sm" aria-label={t("Отправить")} title={t("Отправить")} className="h-9">
|
||||||
<Button size="sm" aria-label={t("Отправить")} title={t("Отправить")} className="ml-auto size-11 md:ml-0 md:h-9 md:w-auto" data-chat-send>
|
|
||||||
<Send />
|
<Send />
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@ -1,4 +1,4 @@
|
|||||||
import Link from "@/components/Link";
|
import Link from "next/link";
|
||||||
import { ArrowRight, MessagesSquare } from "lucide-react";
|
import { ArrowRight, MessagesSquare } from "lucide-react";
|
||||||
import { chatOverview, isRoleName, syncChats } from "@peppa/core";
|
import { chatOverview, isRoleName, syncChats } from "@peppa/core";
|
||||||
import { LiveRefresh } from "@/components/LiveRefresh";
|
import { LiveRefresh } from "@/components/LiveRefresh";
|
||||||
|
|||||||
@ -1,36 +0,0 @@
|
|||||||
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("Не удалось войти в сервис"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,32 +0,0 @@
|
|||||||
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("Не удалось начать вход в сервис"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,4 +1,4 @@
|
|||||||
import Link from "@/components/Link";
|
import Link from "next/link";
|
||||||
import { ExternalLink, PlugZap, Search } from "lucide-react";
|
import { ExternalLink, PlugZap, Search } from "lucide-react";
|
||||||
import {
|
import {
|
||||||
CATALOG_KIND_TEXT,
|
CATALOG_KIND_TEXT,
|
||||||
@ -7,19 +7,10 @@ import {
|
|||||||
CONNECTION_CHECK_TEXT,
|
CONNECTION_CHECK_TEXT,
|
||||||
CONNECTION_REASON_TEXT,
|
CONNECTION_REASON_TEXT,
|
||||||
connectionJournal,
|
connectionJournal,
|
||||||
DEFAULT_GRANT_TERM,
|
|
||||||
defaultIdleRevokeHours,
|
|
||||||
GRANT_TERM_TEXT,
|
|
||||||
GRANT_TERMS,
|
|
||||||
IDLE_HOURS_CHOICES,
|
|
||||||
serverTimezone,
|
|
||||||
JOURNAL_VERIFY_SCRIPT,
|
JOURNAL_VERIFY_SCRIPT,
|
||||||
grantableAgents,
|
grantableAgents,
|
||||||
listConnections,
|
listConnections,
|
||||||
listUserProjects,
|
listUserProjects,
|
||||||
ownerAccessRequests,
|
|
||||||
oauthOffer,
|
|
||||||
scopeLabel,
|
|
||||||
searchCatalog,
|
searchCatalog,
|
||||||
type CatalogKind,
|
type CatalogKind,
|
||||||
type CatalogService,
|
type CatalogService,
|
||||||
@ -31,9 +22,7 @@ import {
|
|||||||
type GatewayProtocol,
|
type GatewayProtocol,
|
||||||
GATEWAY_PROTOCOLS,
|
GATEWAY_PROTOCOLS,
|
||||||
} from "@peppa/core";
|
} from "@peppa/core";
|
||||||
import { AccessRequestList } from "@/components/AccessRequests";
|
|
||||||
import { Hidden } from "@/components/cards";
|
import { Hidden } from "@/components/cards";
|
||||||
import { intlLocale } from "@peppa/shared/i18n";
|
|
||||||
import { ago, Empty, Flash, Notice, PageHeader, Section } from "@/components/common";
|
import { ago, Empty, Flash, Notice, PageHeader, Section } from "@/components/common";
|
||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
@ -44,14 +33,14 @@ import { requireUser, uiMode } from "@/lib/auth";
|
|||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
import { getT } from "@/lib/i18n";
|
import { getT } from "@/lib/i18n";
|
||||||
import { m, type Translator } from "@peppa/shared/i18n";
|
import { m, type Translator } from "@peppa/shared/i18n";
|
||||||
import { checkConnectionAction, createConnectionAction, decideIdleGrantAction, deleteConnectionAction, extendGrantAction, grantConnectionAction, replaceConnectionSecretAction, resetHostKeyAction, revokeConnectionAction, revokeGrantAction, setConnectionIdleAction } from "../actions";
|
import { checkConnectionAction, createConnectionAction, deleteConnectionAction, grantConnectionAction, replaceConnectionSecretAction, resetHostKeyAction, revokeConnectionAction, revokeGrantAction } from "../actions";
|
||||||
|
|
||||||
export async function generateMetadata() {
|
export async function generateMetadata() {
|
||||||
const t = await getT();
|
const t = await getT();
|
||||||
return { title: t("Подключения — FORGE") };
|
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 };
|
type Params = { error?: string; created?: string; checked?: string; check?: string; service?: string; q?: string; kind?: string };
|
||||||
|
|
||||||
const SELECT = "h-9 rounded-md border border-input bg-background px-2 text-sm";
|
const SELECT = "h-9 rounded-md border border-input bg-background px-2 text-sm";
|
||||||
const BACK = "/connections";
|
const BACK = "/connections";
|
||||||
@ -70,13 +59,7 @@ const kindText = (k: CatalogKind, t: Translator) => t.text(CATALOG_KIND_TEXT[k])
|
|||||||
|
|
||||||
/** «ключ работает» / «ключ не подходит» / «сервис не отвечает» / «ещё не проверялся». */
|
/** «ключ работает» / «ключ не подходит» / «сервис не отвечает» / «ещё не проверялся». */
|
||||||
function KeyState({ c, t }: { c: ConnectionView; t: Translator }) {
|
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>;
|
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>;
|
if (!c.checkStatus) return <Badge variant="outline">{t("ключ ещё не проверялся")}</Badge>;
|
||||||
const text = t.text(CONNECTION_CHECK_TEXT[c.checkStatus]);
|
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>;
|
return <Badge variant={c.checkStatus === "ok" ? "ok" : c.checkStatus === "bad_key" || c.checkStatus === "host_key" ? "danger" : "warn"}>{text}</Badge>;
|
||||||
@ -86,110 +69,23 @@ function modeText(m: GrantMode, t: Translator): string {
|
|||||||
return m === "auto" ? t("сразу") : m === "ask" ? t("спрашивать меня") : t("нет");
|
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 }) {
|
function GrantLine({ g, engineer, t }: { g: ConnectionGrantView; engineer: boolean; t: Translator }) {
|
||||||
const ended = g.state !== "active";
|
|
||||||
return (
|
return (
|
||||||
<li className="flex flex-col gap-1 rounded-md border bg-background/40 px-2.5 py-1.5">
|
<li className="flex flex-wrap items-center gap-2 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 className="font-medium">{g.projectKey}</span>
|
<span>· {g.agentName ? t("агент {name}", { name: g.agentName }) : t("любой агент проекта")}</span>
|
||||||
<span>· {g.agentName ? t("агент {name}", { name: g.agentName }) : t("любой агент проекта")}</span>
|
<span className="text-muted-foreground">
|
||||||
<span className="text-muted-foreground">
|
· {t("чтение: {mode}", { mode: modeText(g.readMode, t) })} · {t("запись: {mode}", { mode: modeText(g.writeMode, t) })}
|
||||||
· {t("чтение: {mode}", { mode: modeText(g.readMode, t) })} · {t("запись: {mode}", { mode: modeText(g.writeMode, t) })}
|
</span>
|
||||||
</span>
|
{engineer && g.operations.length > 0 && <span className="font-mono text-xs text-muted-foreground">{g.operations.join(", ")}</span>}
|
||||||
{g.state === "expired" && <Badge variant="warn">{t("срок истёк")}</Badge>}
|
<form action={revokeGrantAction} className="ml-auto">
|
||||||
{g.state === "idle" && <Badge variant="warn">{t("снято: {n} ч без дела", { n: g.idleHours })}</Badge>}
|
<Hidden fields={{ grantId: g.id, back: BACK }} />
|
||||||
{g.idleAskedAt && <Badge variant="warn">{t("не используется {n} ч — снять?", { n: g.idleHours })}</Badge>}
|
<Button variant="ghost" size="sm">{t("Убрать")}</Button>
|
||||||
{engineer && g.operations.length > 0 && <span className="font-mono text-xs text-muted-foreground">{g.operations.join(", ")}</span>}
|
</form>
|
||||||
<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>
|
</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 }) {
|
function ModeSelect({ name, label, def, t }: { name: string; label: string; def: GrantMode; t: Translator }) {
|
||||||
return (
|
return (
|
||||||
<label className="flex flex-col gap-1 text-sm">
|
<label className="flex flex-col gap-1 text-sm">
|
||||||
@ -232,14 +128,11 @@ function GrantForm({ c, projects, agents, engineer, t }: { c: ConnectionView; pr
|
|||||||
<ModeSelect name="readMode" label={t("Чтение")} def="auto" t={t} />
|
<ModeSelect name="readMode" label={t("Чтение")} def="auto" t={t} />
|
||||||
{/* PEP-251: changing a database and sending letters ask the owner by default. */}
|
{/* 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} />
|
<ModeSelect name="writeMode" label={t("Запись")} def={c.protocol === "postgres" || c.protocol === "mysql" || c.protocol === "mail" ? "ask" : "off"} t={t} />
|
||||||
<TermSelect t={t} />
|
|
||||||
</div>
|
</div>
|
||||||
<p className="m-0 text-xs text-muted-foreground">
|
<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("Чтение — смотреть данные, ничего не меняя. Запись — создавать, менять, удалять и отправлять. «Спрашивать меня» пока означает отказ: подтверждение запросов появится позже.") : t.text(PROTOCOL_TEXT[c.protocol as GatewayProtocol].modes)}
|
||||||
{c.protocol !== "http" && <> {t("«Спрашивать меня» пока означает отказ: подтверждение запросов появится позже.")}</>}
|
{c.protocol !== "http" && <> {t("«Спрашивать меня» пока означает отказ: подтверждение запросов появится позже.")}</>}
|
||||||
</p>
|
</p>
|
||||||
{/* PEP-260: an «echo» operation can hand the key back in a form masking doesn't know. */}
|
|
||||||
{c.protocol === "http" && <p className="m-0 text-xs text-muted-foreground">{t("Не разрешайте агенту действия, которые возвращают присланное обратно: проверку, отладку, «кто я» с ключом. Через них сервис может показать агенту ключ.")}</p>}
|
|
||||||
{engineer && c.protocol === "http" && (
|
{engineer && c.protocol === "http" && (
|
||||||
<details className="text-sm">
|
<details className="text-sm">
|
||||||
<summary className="cursor-pointer text-muted-foreground">{t("Тонкая настройка")}</summary>
|
<summary className="cursor-pointer text-muted-foreground">{t("Тонкая настройка")}</summary>
|
||||||
@ -257,9 +150,6 @@ function GrantForm({ c, projects, agents, engineer, t }: { c: ConnectionView; pr
|
|||||||
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 }) {
|
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 active = c.status === "active";
|
||||||
const card = catalogService(c.catalogId);
|
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 (
|
return (
|
||||||
<Card id={`c${c.id}`} className="flex flex-col gap-4 p-4">
|
<Card id={`c${c.id}`} className="flex flex-col gap-4 p-4">
|
||||||
<div className="flex flex-wrap items-center gap-2">
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
@ -272,7 +162,6 @@ function ConnectionCard({ c, projects, agents, engineer, t }: { c: ConnectionVie
|
|||||||
<div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted-foreground">
|
<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>
|
<span className="truncate font-mono">{c.baseUrl}</span>
|
||||||
{engineer && <span>{t("имя для агентов: {slug}", { slug: c.slug })}</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 && (
|
{card && (
|
||||||
<a href={card.docsUrl} target="_blank" rel="noreferrer noopener" className="inline-flex items-center gap-1 underline-offset-2 hover:underline">
|
<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" />
|
{t("Документация сервиса")} <ExternalLink className="size-3" />
|
||||||
@ -304,21 +193,10 @@ function ConnectionCard({ c, projects, agents, engineer, t }: { c: ConnectionVie
|
|||||||
))}
|
))}
|
||||||
</ul>
|
</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} />}
|
{active && projects.length > 0 && <GrantForm c={c} projects={projects} agents={agents} engineer={engineer} t={t} />}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex flex-wrap items-end gap-2 border-t pt-3">
|
<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">
|
<form action={replaceConnectionSecretAction} className="flex flex-1 flex-wrap items-center gap-2" autoComplete="off">
|
||||||
<Hidden fields={{ connectionId: c.id, back: BACK }} />
|
<Hidden fields={{ connectionId: c.id, back: BACK }} />
|
||||||
{c.protocol === "ssh" ? (
|
{c.protocol === "ssh" ? (
|
||||||
@ -328,8 +206,7 @@ function ConnectionCard({ c, projects, agents, engineer, t }: { c: ConnectionVie
|
|||||||
)}
|
)}
|
||||||
<Button size="sm" variant="secondary">{active ? t("Заменить ключ") : t("Включить снова")}</Button>
|
<Button size="sm" variant="secondary">{active ? t("Заменить ключ") : t("Включить снова")}</Button>
|
||||||
</form>
|
</form>
|
||||||
)}
|
{active && (
|
||||||
{(active || c.status === "relogin") && (
|
|
||||||
<form action={revokeConnectionAction}>
|
<form action={revokeConnectionAction}>
|
||||||
<Hidden fields={{ connectionId: c.id, back: BACK }} />
|
<Hidden fields={{ connectionId: c.id, back: BACK }} />
|
||||||
<Button size="sm" variant="destructive">{t("Отозвать доступ")}</Button>
|
<Button size="sm" variant="destructive">{t("Отозвать доступ")}</Button>
|
||||||
@ -344,17 +221,7 @@ function ConnectionCard({ c, projects, agents, engineer, t }: { c: ConnectionVie
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function CheckNotice({ check, created, signed, t }: { check?: string; created: boolean; signed: boolean; t: Translator }) {
|
function CheckNotice({ check, created, t }: { check?: string; created: 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 head = created ? t("Подключение сохранено. Ключ доступа больше не показывается никому.") : "";
|
||||||
const tail =
|
const tail =
|
||||||
check === "ok"
|
check === "ok"
|
||||||
@ -484,32 +351,6 @@ function ProtocolSteps({ p, t }: { p: GatewayProtocol; t: Translator }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** Step 1–2 for a chosen service (catalog card or own). */
|
/** 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 }) {
|
function AddSteps({ s, t }: { s: CatalogService | null; t: Translator }) {
|
||||||
const back = `/connections?service=${s?.id ?? "custom"}#add`;
|
const back = `/connections?service=${s?.id ?? "custom"}#add`;
|
||||||
return (
|
return (
|
||||||
@ -521,8 +362,6 @@ function AddSteps({ s, t }: { s: CatalogService | null; t: Translator }) {
|
|||||||
{t("← Другой сервис")}
|
{t("← Другой сервис")}
|
||||||
</Link>
|
</Link>
|
||||||
</div>
|
</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">
|
<ol className="m-0 flex list-decimal flex-col gap-4 pl-5 text-sm">
|
||||||
{s ? (
|
{s ? (
|
||||||
<li className="flex flex-col gap-1">
|
<li className="flex flex-col gap-1">
|
||||||
@ -556,7 +395,6 @@ function AddSteps({ s, t }: { s: CatalogService | null; t: Translator }) {
|
|||||||
<Input name="authHeader" placeholder="X-Api-Key" aria-label={t("Имя заголовка или параметра")} className="max-w-48 font-mono" spellCheck={false} />
|
<Input name="authHeader" placeholder="X-Api-Key" aria-label={t("Имя заголовка или параметра")} className="max-w-48 font-mono" spellCheck={false} />
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
{!s && <p className="m-0 text-xs text-muted-foreground">{t("Не разрешайте агенту действия, которые возвращают присланное обратно: проверку, отладку, «кто я» с ключом. Через них сервис может показать агенту ключ.")}</p>}
|
|
||||||
<Button size="sm" className="self-start">{t("Подключить и проверить")}</Button>
|
<Button size="sm" className="self-start">{t("Подключить и проверить")}</Button>
|
||||||
</form>
|
</form>
|
||||||
</li>
|
</li>
|
||||||
@ -651,27 +489,20 @@ export default async function ConnectionsPage({ searchParams }: { searchParams:
|
|||||||
const user = await requireUser();
|
const user = await requireUser();
|
||||||
const t = await getT();
|
const t = await getT();
|
||||||
const engineer = (await uiMode()) === "engineer";
|
const engineer = (await uiMode()) === "engineer";
|
||||||
const [list, journal, projects, agents, requests] = await Promise.all([listConnections(db, user.id), connectionJournal(db, user.id, { limit: 50 }), listUserProjects(db, user.id), grantableAgents(db), ownerAccessRequests(db, user.id)]);
|
const [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 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 chosen = q.service === "custom" ? "custom" : catalogService(q.service);
|
||||||
const kind = q.kind && (CATALOG_KINDS as string[]).includes(q.kind) ? q.kind : null;
|
const kind = q.kind && (CATALOG_KINDS as string[]).includes(q.kind) ? q.kind : null;
|
||||||
return (
|
return (
|
||||||
<Workspace>
|
<Workspace>
|
||||||
<Flash error={q.error} />
|
<Flash error={q.error} />
|
||||||
{(q.created || q.checked) && <CheckNotice check={q.check} created={!!q.created} signed={!!q.signed} t={t} />}
|
{(q.created || q.checked) && <CheckNotice check={q.check} created={!!q.created} t={t} />}
|
||||||
{q.revoked && q.remote === "failed" && <Notice>{t("Доступ в FORGE отозван, но сервис не ответил. Чтобы закрыть доступ и там, удалите FORGE в настройках доступа самого сервиса.")}</Notice>}
|
|
||||||
<PageHeader title={<><PlugZap className="mr-1 inline size-5 text-primary" />{t("Подключения")}</>}>
|
<PageHeader title={<><PlugZap className="mr-1 inline size-5 text-primary" />{t("Подключения")}</>}>
|
||||||
<p className="m-0 text-sm text-muted-foreground">
|
<p className="m-0 text-sm text-muted-foreground">
|
||||||
{t("Подключите свои сервисы и решите, какие агенты и что в них могут делать. Агенты не видят ключ доступа: запросы выполняет FORGE и записывает их в журнал. Без вашего разрешения агент ничего не сделает, а «Отозвать доступ» действует сразу.")}
|
{t("Подключите свои сервисы и решите, какие агенты и что в них могут делать. Агенты не видят ключ доступа: запросы выполняет FORGE и записывает их в журнал. Без вашего разрешения агент ничего не сделает, а «Отозвать доступ» действует сразу.")}
|
||||||
</p>
|
</p>
|
||||||
</PageHeader>
|
</PageHeader>
|
||||||
|
|
||||||
{requests.length > 0 && (
|
|
||||||
<Section id="requests" title={t("Агенты просят доступ")} count={requests.length}>
|
|
||||||
<AccessRequestList list={requests} t={t} />
|
|
||||||
</Section>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{list.length > 0 && (
|
{list.length > 0 && (
|
||||||
<Section title={t("Ваши подключения")} count={list.length}>
|
<Section title={t("Ваши подключения")} count={list.length}>
|
||||||
{list.map((c) => (
|
{list.map((c) => (
|
||||||
@ -708,13 +539,9 @@ export default async function ConnectionsPage({ searchParams }: { searchParams:
|
|||||||
{r.projectKey ?? "—"}
|
{r.projectKey ?? "—"}
|
||||||
{r.agentName ? ` · ${r.agentName}` : ""}
|
{r.agentName ? ` · ${r.agentName}` : ""}
|
||||||
</td>
|
</td>
|
||||||
{r.method === "REVOKE" ? (
|
<td className="py-1.5 pr-3 font-mono text-xs">
|
||||||
<td className="py-1.5 pr-3 text-xs">{t("разрешение снято")}</td>
|
{r.method} {r.path}
|
||||||
) : (
|
</td>
|
||||||
<td className="py-1.5 pr-3 font-mono text-xs">
|
|
||||||
{r.method} {r.path}
|
|
||||||
</td>
|
|
||||||
)}
|
|
||||||
<td className="py-1.5">
|
<td className="py-1.5">
|
||||||
<span className="flex flex-wrap items-center gap-1.5">
|
<span className="flex flex-wrap items-center gap-1.5">
|
||||||
<Decision row={r} t={t} />
|
<Decision row={r} t={t} />
|
||||||
|
|||||||
@ -1,184 +0,0 @@
|
|||||||
import Link from "@/components/Link";
|
|
||||||
import { notFound } from "next/navigation";
|
|
||||||
import { ExternalLink, KeyRound } from "lucide-react";
|
|
||||||
import { accessRequestForUser, catalogService, connectionsForRequest, type AccessRequestView, type CatalogService, type ConnectionView } from "@peppa/core";
|
|
||||||
import type { Translator } from "@peppa/shared/i18n";
|
|
||||||
import { AccessStatus, accessModeText } from "@/components/AccessRequests";
|
|
||||||
import { Hidden } from "@/components/cards";
|
|
||||||
import { Flash, Notice, PageHeader, Section } from "@/components/common";
|
|
||||||
import { Button } from "@/components/ui/button";
|
|
||||||
import { Card } from "@/components/ui/card";
|
|
||||||
import { Input, Textarea } from "@/components/ui/input";
|
|
||||||
import { Workspace } from "@/components/Workspace";
|
|
||||||
import { requireUser } from "@/lib/auth";
|
|
||||||
import { db } from "@/lib/db";
|
|
||||||
import { getT } from "@/lib/i18n";
|
|
||||||
import { connectAccessRequestAction, denyAccessRequestAction, grantAccessRequestAction } from "../../../actions";
|
|
||||||
|
|
||||||
export async function generateMetadata() {
|
|
||||||
const t = await getT();
|
|
||||||
return { title: t("Запрос доступа — FORGE") };
|
|
||||||
}
|
|
||||||
|
|
||||||
const SELECT = "h-9 rounded-md border border-input bg-background px-2 text-sm";
|
|
||||||
|
|
||||||
function Fact({ label, children }: { label: string; children: React.ReactNode }) {
|
|
||||||
return (
|
|
||||||
<div className="flex flex-col gap-0.5 sm:flex-row sm:gap-3">
|
|
||||||
<span className="w-32 shrink-0 text-muted-foreground">{label}</span>
|
|
||||||
<span className="min-w-0 break-words">{children}</span>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function DoneNotice({ done, check, t }: { done?: string; check?: string; t: Translator }) {
|
|
||||||
if (done === "denied") return <Notice>{t("Отказано. Агент получит вашу причину и продолжит без этого сервиса.")}</Notice>;
|
|
||||||
if (done !== "granted") return null;
|
|
||||||
const tail = check === "bad_key" ? t("Но сервис не принял ключ: замените его в разделе «Подключения».") : check === "down" ? t("Сервис сейчас не отвечает — ключ проверится при первом запросе агента.") : "";
|
|
||||||
return (
|
|
||||||
<Notice>
|
|
||||||
{t("Доступ выдан. Агент получил сообщение и продолжит работу; ключ доступа он не видит.")} {tail}
|
|
||||||
</Notice>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function ConnectForm({ r, card, t }: { r: AccessRequestView; card: CatalogService | null; t: Translator }) {
|
|
||||||
const back = `/connections/requests/${r.id}`;
|
|
||||||
return (
|
|
||||||
<ol className="m-0 flex list-decimal flex-col gap-4 pl-5 text-sm">
|
|
||||||
<li className="flex flex-col gap-1">
|
|
||||||
<span className="font-medium">{t("Возьмите ключ доступа")}</span>
|
|
||||||
{card ? (
|
|
||||||
<>
|
|
||||||
<span className="text-muted-foreground">{t.text(card.keyHint)}</span>
|
|
||||||
<a href={card.keyUrl} target="_blank" rel="noreferrer noopener" className="inline-flex items-center gap-1 self-start text-primary underline-offset-2 hover:underline">
|
|
||||||
{t("Открыть страницу, где берут ключ")} <ExternalLink className="size-3" />
|
|
||||||
</a>
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<span className="text-muted-foreground">{t("Он есть в описании сервиса для разработчиков или у того, кто его сделал.")}</span>
|
|
||||||
)}
|
|
||||||
</li>
|
|
||||||
<li className="flex flex-col gap-2">
|
|
||||||
<span className="font-medium">{t("Вставьте его сюда")}</span>
|
|
||||||
<form action={connectAccessRequestAction} className="flex max-w-xl flex-col gap-2" autoComplete="off">
|
|
||||||
<Hidden fields={{ back, requestId: r.id }} />
|
|
||||||
{(!card || card.baseEditable) && <Input name="baseUrl" required type="url" defaultValue={r.host ?? ""} placeholder={card?.baseUrl ?? "https://api.example.com/v1"} aria-label={t("Адрес сервиса")} className="font-mono" spellCheck={false} />}
|
|
||||||
<Input name="secret" required type="password" placeholder={card?.auth === "basic" ? t("логин:пароль — после сохранения их не увидит никто") : t("Ключ доступа — после сохранения его не увидит никто")} aria-label={t("Ключ доступа")} autoComplete="new-password" />
|
|
||||||
{!card && (
|
|
||||||
<div className="flex flex-wrap items-center gap-2">
|
|
||||||
<select name="authKind" aria-label={t("Как передавать ключ")} className={SELECT} defaultValue="bearer">
|
|
||||||
<option value="bearer">{t("Как «Authorization: Bearer …»")}</option>
|
|
||||||
<option value="header">{t("В своём заголовке")}</option>
|
|
||||||
<option value="query">{t("В адресе запроса (параметр)")}</option>
|
|
||||||
<option value="basic">{t("Логин и пароль")}</option>
|
|
||||||
</select>
|
|
||||||
<Input name="authHeader" placeholder="X-Api-Key" aria-label={t("Имя заголовка или параметра")} className="max-w-48 font-mono" spellCheck={false} />
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
<Button size="sm" className="self-start">{t("Подключить и разрешить")}</Button>
|
|
||||||
</form>
|
|
||||||
</li>
|
|
||||||
</ol>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function ExistingForm({ r, fit, other, t }: { r: AccessRequestView; fit: ConnectionView[]; other: ConnectionView[]; t: Translator }) {
|
|
||||||
const all = [...fit, ...other];
|
|
||||||
if (!all.length) return null;
|
|
||||||
return (
|
|
||||||
<form action={grantAccessRequestAction} className="flex flex-wrap items-center gap-2 text-sm">
|
|
||||||
<Hidden fields={{ back: `/connections/requests/${r.id}`, requestId: r.id }} />
|
|
||||||
<select name="connectionId" required aria-label={t("Подключение")} className={SELECT} defaultValue={fit[0]?.id ?? ""}>
|
|
||||||
{!fit.length && <option value="">{t("Выберите подключение")}</option>}
|
|
||||||
{all.map((c) => (
|
|
||||||
<option key={c.id} value={c.id}>
|
|
||||||
{c.name}
|
|
||||||
</option>
|
|
||||||
))}
|
|
||||||
</select>
|
|
||||||
<Button size="sm" variant="secondary">{t("Разрешить из уже подключённого")}</Button>
|
|
||||||
</form>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** PEP-250: the card of an agent's access request — its project's owner only (others: 404). */
|
|
||||||
export default async function AccessRequestPage({ params, searchParams }: { params: Promise<{ id: string }>; searchParams: Promise<{ error?: string; done?: string; check?: string }> }) {
|
|
||||||
const [{ id }, q] = await Promise.all([params, searchParams]);
|
|
||||||
const user = await requireUser();
|
|
||||||
const t = await getT();
|
|
||||||
const r = /^\d+$/.test(id) ? await accessRequestForUser(db, user.id, Number(id)) : null;
|
|
||||||
if (!r) notFound();
|
|
||||||
const card = catalogService(r.catalogId);
|
|
||||||
const { fit, other } = r.status === "open" ? await connectionsForRequest(db, user.id, r) : { fit: [], other: [] };
|
|
||||||
return (
|
|
||||||
<Workspace>
|
|
||||||
<Flash error={q.error} />
|
|
||||||
<DoneNotice done={q.done} check={q.check} t={t} />
|
|
||||||
<PageHeader
|
|
||||||
title={<><KeyRound className="mr-1 inline size-5 text-primary" />{t("Агент просит доступ к {service}", { service: r.service })}</>}
|
|
||||||
crumbs={<Link href="/connections" className="hover:underline">{t("Подключения")}</Link>}
|
|
||||||
>
|
|
||||||
<p className="m-0 text-sm text-muted-foreground">
|
|
||||||
{r.status === "open"
|
|
||||||
? t("Агенту нужен этот сервис для работы над задачей. Ключ доступа вы вводите один раз, агент его не увидит: запросы выполняет FORGE и записывает их в журнал. Можно и отказать — агент продолжит без сервиса.")
|
|
||||||
: t("По этому запросу уже есть решение.")}
|
|
||||||
</p>
|
|
||||||
</PageHeader>
|
|
||||||
|
|
||||||
<Card className="flex flex-col gap-2 p-4 text-sm">
|
|
||||||
<div className="mb-1 flex flex-wrap items-center gap-2">
|
|
||||||
<AccessStatus r={r} t={t} />
|
|
||||||
{r.repeats > 0 && <span className="text-xs text-muted-foreground">{t("агент просил ещё раз: {n}", { n: r.repeats })}</span>}
|
|
||||||
</div>
|
|
||||||
<Fact label={t("Агент")}>{r.agentName ?? "—"}</Fact>
|
|
||||||
<Fact label={t("Задача")}>{r.taskKey ? <Link href={`/t/${r.taskKey}`} className="text-primary hover:underline">{r.taskKey}{r.taskTitle ? ` — ${r.taskTitle}` : ""}</Link> : "—"}</Fact>
|
|
||||||
<Fact label={t("Проект")}>{r.projectName}</Fact>
|
|
||||||
<Fact label={t("Сервис")}>
|
|
||||||
{r.service}
|
|
||||||
{card && (
|
|
||||||
<a href={card.docsUrl} target="_blank" rel="noreferrer noopener" className="ml-2 inline-flex items-center gap-1 text-xs text-muted-foreground hover:underline">
|
|
||||||
{t("Документация сервиса")} <ExternalLink className="size-3" />
|
|
||||||
</a>
|
|
||||||
)}
|
|
||||||
{!card && r.host && <span className="ml-2 font-mono text-xs text-muted-foreground">{r.host}</span>}
|
|
||||||
</Fact>
|
|
||||||
<Fact label={t("Что можно")}>{accessModeText(r.mode, t)}</Fact>
|
|
||||||
{/* The agent's own words: shown as is, never as instructions. */}
|
|
||||||
<Fact label={t("Зачем")}>{r.purpose}</Fact>
|
|
||||||
{r.status === "denied" && <Fact label={t("Причина отказа")}>{r.reason ?? t("без причины")}</Fact>}
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
{r.status === "open" && (
|
|
||||||
<>
|
|
||||||
<Section title={t("Подключить и разрешить")}>
|
|
||||||
<Card className="p-4">
|
|
||||||
<ConnectForm r={r} card={card} t={t} />
|
|
||||||
<p className="m-0 mt-3 text-xs text-muted-foreground">
|
|
||||||
{r.mode === "write"
|
|
||||||
? t("Агенты проекта смогут читать и менять данные в этом сервисе. Изменить или отозвать доступ можно в разделе «Подключения».")
|
|
||||||
: t("Агенты проекта смогут только читать данные в этом сервисе. Изменить или отозвать доступ можно в разделе «Подключения».")}
|
|
||||||
</p>
|
|
||||||
</Card>
|
|
||||||
</Section>
|
|
||||||
{fit.length + other.length > 0 && (
|
|
||||||
<Section title={t("Или разрешить из уже подключённого")}>
|
|
||||||
<Card className="p-4">
|
|
||||||
<ExistingForm r={r} fit={fit} other={other} t={t} />
|
|
||||||
</Card>
|
|
||||||
</Section>
|
|
||||||
)}
|
|
||||||
<Section title={t("Отказать")}>
|
|
||||||
<Card className="p-4">
|
|
||||||
<form action={denyAccessRequestAction} className="flex max-w-xl flex-col gap-2">
|
|
||||||
<Hidden fields={{ back: `/connections/requests/${r.id}`, requestId: r.id }} />
|
|
||||||
<Textarea name="reason" rows={2} maxLength={500} placeholder={t("Причина — агент её получит, например «используйте тестовые данные»")} aria-label={t("Причина отказа")} />
|
|
||||||
<Button size="sm" variant="destructive" className="self-start">{t("Отказать")}</Button>
|
|
||||||
</form>
|
|
||||||
</Card>
|
|
||||||
</Section>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</Workspace>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@ -1,8 +1,8 @@
|
|||||||
"use server";
|
"use server";
|
||||||
// PEP-209: the superadmin's buttons on a delay card («Дашборд → Задержки»); PEP-279: old questions.
|
// PEP-209: the superadmin's buttons on a delay card («Дашборд → Задержки»).
|
||||||
|
|
||||||
import { DELAY_REASON_NAMES, PeppaError, requireSuperadmin, type DelayAction, type DelayReason } from "@peppa/core";
|
import { DELAY_REASON_NAMES, PeppaError, requireSuperadmin, type DelayAction, type DelayReason } from "@peppa/core";
|
||||||
import { closeStaleQuestions, delayAction } from "@peppa/runner";
|
import { delayAction } from "@peppa/runner";
|
||||||
import { revalidatePath } from "next/cache";
|
import { revalidatePath } from "next/cache";
|
||||||
import { redirect } from "next/navigation";
|
import { redirect } from "next/navigation";
|
||||||
import { asWebActor, requireUser } from "@/lib/auth";
|
import { asWebActor, requireUser } from "@/lib/auth";
|
||||||
@ -31,19 +31,3 @@ export async function delayActionForm(f: FormData) {
|
|||||||
revalidatePath("/", "layout");
|
revalidatePath("/", "layout");
|
||||||
redirect(`${BASE}?${params}`);
|
redirect(`${BASE}?${params}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** PEP-279: «Закрыть все» on the old questions page — their default option, one summary per person. */
|
|
||||||
export async function closeStaleQuestionsAction() {
|
|
||||||
const user = asWebActor(await requireUser());
|
|
||||||
const params = new URLSearchParams();
|
|
||||||
const t = await getT();
|
|
||||||
try {
|
|
||||||
await requireSuperadmin(db, user);
|
|
||||||
const r = await closeStaleQuestions(db);
|
|
||||||
params.set("ok", t("Закрыто вопросов: {n}. Итоговое сообщение получили людей: {m}.", { n: r.closed.length, m: r.told }) + (r.failed ? " " + t("Не удалось закрыть: {n}.", { n: r.failed }) : ""));
|
|
||||||
} catch (e) {
|
|
||||||
params.set("error", (e instanceof PeppaError ? t.text(e.message) : t("Ошибка: {message}", { message: (e as Error).message })).slice(0, 300));
|
|
||||||
}
|
|
||||||
revalidatePath("/", "layout");
|
|
||||||
redirect(`/dashboard/questions?${params}`);
|
|
||||||
}
|
|
||||||
|
|||||||
@ -1,4 +1,4 @@
|
|||||||
import Link from "@/components/Link";
|
import Link from "next/link";
|
||||||
import { notFound } from "next/navigation";
|
import { notFound } from "next/navigation";
|
||||||
import { Hourglass } from "lucide-react";
|
import { Hourglass } from "lucide-react";
|
||||||
import { isSuperadmin, platformDelayOverview } from "@peppa/core";
|
import { isSuperadmin, platformDelayOverview } from "@peppa/core";
|
||||||
|
|||||||
@ -1,4 +1,4 @@
|
|||||||
import Link from "@/components/Link";
|
import Link from "next/link";
|
||||||
import { notFound } from "next/navigation";
|
import { notFound } from "next/navigation";
|
||||||
import { Gauge } from "lucide-react";
|
import { Gauge } from "lucide-react";
|
||||||
import { isSuperadmin, platformDashboard, platformDelayCounts, type DashboardCounts } from "@peppa/core";
|
import { isSuperadmin, platformDashboard, platformDelayCounts, type DashboardCounts } from "@peppa/core";
|
||||||
@ -11,7 +11,6 @@ import { requireUser } from "@/lib/auth";
|
|||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
import { getT } from "@/lib/i18n";
|
import { getT } from "@/lib/i18n";
|
||||||
import { m } from "@peppa/shared/i18n";
|
import { m } from "@peppa/shared/i18n";
|
||||||
import { STALE_DAYS, staleQuestions } from "@peppa/runner";
|
|
||||||
|
|
||||||
export async function generateMetadata() {
|
export async function generateMetadata() {
|
||||||
const t = await getT();
|
const t = await getT();
|
||||||
@ -56,7 +55,6 @@ export default async function Dashboard() {
|
|||||||
const d = await platformDashboard(db);
|
const d = await platformDashboard(db);
|
||||||
const x = d.totals;
|
const x = d.totals;
|
||||||
const delays = await platformDelayCounts(db);
|
const delays = await platformDelayCounts(db);
|
||||||
const stale = (await staleQuestions(db)).length;
|
|
||||||
return (
|
return (
|
||||||
<Workspace>
|
<Workspace>
|
||||||
<LiveRefresh scope="home" />
|
<LiveRefresh scope="home" />
|
||||||
@ -78,13 +76,6 @@ export default async function Dashboard() {
|
|||||||
{delays.total ? t("Задержки на платформе: {n}, требуют вас: {m}", { n: delays.total, m: delays.admin }) : t("Задержек на платформе нет")} →
|
{delays.total ? t("Задержки на платформе: {n}, требуют вас: {m}", { n: delays.total, m: delays.admin }) : t("Задержек на платформе нет")} →
|
||||||
</Link>
|
</Link>
|
||||||
</p>
|
</p>
|
||||||
{stale > 0 && (
|
|
||||||
<p className="mb-4 text-sm" data-dashboard-stale>
|
|
||||||
<Link href="/dashboard/questions" className="text-primary">
|
|
||||||
{t("Вопросы без ответа дольше {days} дней: {n} — закрыть вариантом по умолчанию", { days: STALE_DAYS, n: stale })} →
|
|
||||||
</Link>
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<Section title={t("Требует внимания")} count={d.attention.length} id="attention">
|
<Section title={t("Требует внимания")} count={d.attention.length} id="attention">
|
||||||
{d.attention.length === 0 ? (
|
{d.attention.length === 0 ? (
|
||||||
|
|||||||
@ -1,62 +0,0 @@
|
|||||||
import Link from "@/components/Link";
|
|
||||||
import { notFound } from "next/navigation";
|
|
||||||
import { MessageCircleQuestion } from "lucide-react";
|
|
||||||
import { isSuperadmin } from "@peppa/core";
|
|
||||||
import { asIs } from "@peppa/shared/i18n";
|
|
||||||
import { STALE_DAYS, staleQuestions } from "@peppa/runner";
|
|
||||||
import { ago, Empty, Flash, Notice, PageHeader } from "@/components/common";
|
|
||||||
import { Button } from "@/components/ui/button";
|
|
||||||
import { Workspace } from "@/components/Workspace";
|
|
||||||
import { requireUser } from "@/lib/auth";
|
|
||||||
import { db } from "@/lib/db";
|
|
||||||
import { getT } from "@/lib/i18n";
|
|
||||||
import { closeStaleQuestionsAction } from "../actions";
|
|
||||||
|
|
||||||
export async function generateMetadata() {
|
|
||||||
const t = await getT();
|
|
||||||
return { title: t("Старые вопросы — FORGE") };
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* PEP-279: questions nobody answered for a week — the list is the preview, the button closes them
|
|
||||||
* all with their default option (no default — closed with no choice). Superadmin only.
|
|
||||||
*/
|
|
||||||
export default async function StaleQuestions({ searchParams }: { searchParams: Promise<{ error?: string; ok?: string }> }) {
|
|
||||||
const user = await requireUser();
|
|
||||||
if (!(await isSuperadmin(db, user))) notFound();
|
|
||||||
const { error, ok } = await searchParams;
|
|
||||||
const t = await getT();
|
|
||||||
const list = await staleQuestions(db);
|
|
||||||
return (
|
|
||||||
<Workspace>
|
|
||||||
<Flash error={error} />
|
|
||||||
{ok && <Notice>{t.text(ok)}</Notice>}
|
|
||||||
<PageHeader title={<><MessageCircleQuestion className="mr-1 inline size-5 text-primary" />{t("Вопросы без ответа дольше {n} дней", { n: STALE_DAYS })}</>}>
|
|
||||||
{t("Агенты давно продолжили по рекомендованному варианту. Закройте эти вопросы этим вариантом: владельцы получат одно итоговое сообщение. Карточки «готово» не трогаются — «Принять» нажимают сами владельцы.")}{" "}
|
|
||||||
<Link href="/dashboard" className="text-primary">{t("← Дашборд")}</Link>
|
|
||||||
</PageHeader>
|
|
||||||
{list.length === 0 ? (
|
|
||||||
<Empty>{t("Старых вопросов нет.")}</Empty>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
<form action={closeStaleQuestionsAction} className="mb-4 flex flex-wrap items-center gap-3" data-stale-close>
|
|
||||||
<input type="hidden" name="expect" value={list.length} />
|
|
||||||
<Button type="submit">{t("Закрыть все: {n}", { n: list.length })}</Button>
|
|
||||||
<span className="text-sm text-muted-foreground">{t("Ниже — что будет закрыто и каким вариантом.")}</span>
|
|
||||||
</form>
|
|
||||||
<ul className="divide-y rounded-lg border text-sm" data-stale-list>
|
|
||||||
{list.map((x) => (
|
|
||||||
<li key={x.id} className="flex flex-col gap-1 px-3 py-2" data-stale-question={x.id}>
|
|
||||||
<span className="text-xs text-muted-foreground">
|
|
||||||
<Link href={x.where.includes("-") ? `/t/${x.where}` : `/p/${x.projectKey}`} className="text-primary">{x.where}</Link> · {ago(x.createdAt, t)}
|
|
||||||
</span>
|
|
||||||
<span className="line-clamp-2">{t.text(x.freeText ? asIs(x.text) : x.text)}</span>
|
|
||||||
<span className="text-xs">{x.answer ? t("Закроется вариантом: {answer}", { answer: asIs(x.answer) }) : t("Закроется без выбора варианта")}</span>
|
|
||||||
</li>
|
|
||||||
))}
|
|
||||||
</ul>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</Workspace>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@ -1,8 +1,7 @@
|
|||||||
// PEP-218: the card of one production error, read from Bugsink on the server. The superadmin
|
// 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).
|
// 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.
|
// «Инженер» and the superadmin see the stack, tags, events and the link to Bugsink.
|
||||||
import { platformZone } from "@peppa/shared/time";
|
import Link from "next/link";
|
||||||
import Link from "@/components/Link";
|
|
||||||
import { notFound } from "next/navigation";
|
import { notFound } from "next/navigation";
|
||||||
import { Bug, ExternalLink } from "lucide-react";
|
import { Bug, ExternalLink } from "lucide-react";
|
||||||
import { errorDetail, errorScope } from "@peppa/core";
|
import { errorDetail, errorScope } from "@peppa/core";
|
||||||
@ -47,8 +46,8 @@ export default async function ErrorPage({ params, searchParams }: { params: Prom
|
|||||||
<ErrorStateBadge state={r.state} t={t} />
|
<ErrorStateBadge state={r.state} t={t} />
|
||||||
<span>{t.n(r.events, "{n} раз", "{n} раза", "{n} раз")}</span>
|
<span>{t.n(r.events, "{n} раз", "{n} раза", "{n} раз")}</span>
|
||||||
{d.users != null ? <span>{t.n(d.users, "у {n} пользователя", "у {n} пользователей", "у {n} пользователей")}</span> : null}
|
{d.users != null ? <span>{t.n(d.users, "у {n} пользователя", "у {n} пользователей", "у {n} пользователей")}</span> : null}
|
||||||
<span className="text-muted-foreground" title={r.firstSeen.toLocaleString(undefined, { timeZone: platformZone() })}>{t("впервые {ago}", { ago: ago(r.firstSeen, t) })}</span>
|
<span className="text-muted-foreground" title={r.firstSeen.toLocaleString()}>{t("впервые {ago}", { ago: ago(r.firstSeen, t) })}</span>
|
||||||
<span className="text-muted-foreground" title={r.lastSeen.toLocaleString(undefined, { timeZone: platformZone() })}>{t("последний раз {ago}", { ago: ago(r.lastSeen, t) })}</span>
|
<span className="text-muted-foreground" title={r.lastSeen.toLocaleString()}>{t("последний раз {ago}", { ago: ago(r.lastSeen, t) })}</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="text-sm">
|
<div className="text-sm">
|
||||||
{r.taskKey ? (
|
{r.taskKey ? (
|
||||||
@ -110,7 +109,7 @@ export default async function ErrorPage({ params, searchParams }: { params: Prom
|
|||||||
<ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm">
|
<ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm">
|
||||||
{d.events.map((e) => (
|
{d.events.map((e) => (
|
||||||
<li key={e.id} className="flex gap-3">
|
<li key={e.id} className="flex gap-3">
|
||||||
<span className="tabular-nums">{e.at.toLocaleString(t.locale === "en" ? "en-GB" : "ru-RU", { dateStyle: "short", timeStyle: "medium", timeZone: platformZone() })}</span>
|
<span className="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>
|
<span className="font-mono text-xs text-muted-foreground">{e.id.slice(0, 8)}</span>
|
||||||
</li>
|
</li>
|
||||||
))}
|
))}
|
||||||
|
|||||||
@ -1,4 +1,4 @@
|
|||||||
import Link from "@/components/Link";
|
import Link from "next/link";
|
||||||
import { FEEDBACK_ADMIN_STATUS, FEEDBACK_STATUSES, isFeedbackStatus, isSuperadmin, listAllFeedback, listUserFeedback } from "@peppa/core";
|
import { FEEDBACK_ADMIN_STATUS, FEEDBACK_STATUSES, isFeedbackStatus, isSuperadmin, listAllFeedback, listUserFeedback } from "@peppa/core";
|
||||||
import { AdminFeedbackCard, MyFeedbackCard } from "@/components/Feedback";
|
import { AdminFeedbackCard, MyFeedbackCard } from "@/components/Feedback";
|
||||||
import { Empty, Flash, PageHeader, Section } from "@/components/common";
|
import { Empty, Flash, PageHeader, Section } from "@/components/common";
|
||||||
@ -7,14 +7,11 @@ import { requireUser } from "@/lib/auth";
|
|||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
import { getT } from "@/lib/i18n";
|
import { getT } from "@/lib/i18n";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
import { pageTitle } from "@/lib/title";
|
|
||||||
|
|
||||||
// PEP-274: the browser tab says which page it is.
|
|
||||||
export async function generateMetadata() {
|
|
||||||
const t = await getT();
|
|
||||||
return pageTitle(t, t("Обращения"));
|
|
||||||
}
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PEP-143: «Обращения». Everybody sees their own reports and where they stand; the superadmin
|
||||||
|
* also sees everybody's, filtered by status, and decides on them.
|
||||||
|
*/
|
||||||
export default async function FeedbackPage({ searchParams }: { searchParams: Promise<{ error?: string; status?: string; id?: string }> }) {
|
export default async function FeedbackPage({ searchParams }: { searchParams: Promise<{ error?: string; status?: string; id?: string }> }) {
|
||||||
const user = await requireUser();
|
const user = await requireUser();
|
||||||
const t = await getT();
|
const t = await getT();
|
||||||
@ -53,8 +50,3 @@ export default async function FeedbackPage({ searchParams }: { searchParams: Pro
|
|||||||
</Workspace>
|
</Workspace>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* PEP-143: «Обращения». Everybody sees their own reports and where they stand; the superadmin
|
|
||||||
* also sees everybody's, filtered by status, and decides on them.
|
|
||||||
*/
|
|
||||||
|
|||||||
@ -1,32 +0,0 @@
|
|||||||
"use server";
|
|
||||||
// «Gitea» (PEP-280): the superadmin closes one public repository at a time.
|
|
||||||
|
|
||||||
import { PeppaError, requireSuperadmin } from "@peppa/core";
|
|
||||||
import { makeRepoPrivate } from "@peppa/runner";
|
|
||||||
import { revalidatePath } from "next/cache";
|
|
||||||
import { redirect } from "next/navigation";
|
|
||||||
import { asWebActor, requireUser } from "@/lib/auth";
|
|
||||||
import { db } from "@/lib/db";
|
|
||||||
import { getT } from "@/lib/i18n";
|
|
||||||
|
|
||||||
const str = (f: FormData, k: string) => String(f.get(k) ?? "").trim();
|
|
||||||
|
|
||||||
/** «Сделать закрытым»: back to the same list with what was closed, or the reason it was not. */
|
|
||||||
export async function makeRepoPrivateAction(f: FormData) {
|
|
||||||
const user = asWebActor(await requireUser());
|
|
||||||
const back = new URLSearchParams();
|
|
||||||
for (const k of ["q", "show"]) if (str(f, k)) back.set(k, str(f, k));
|
|
||||||
try {
|
|
||||||
await requireSuperadmin(db, user);
|
|
||||||
const r = await makeRepoPrivate(db, user, str(f, "repo"));
|
|
||||||
back.set("closed", r.fullName);
|
|
||||||
// The list is cached (PEP-273): without a fresh one the repository would still show as public for a minute.
|
|
||||||
back.set("fresh", "1");
|
|
||||||
} catch (e) {
|
|
||||||
const t = await getT();
|
|
||||||
const msg = e instanceof PeppaError ? t.text(e.message) : t("Ошибка: {message}", { message: (e as Error).message });
|
|
||||||
back.set("error", msg.slice(0, 300));
|
|
||||||
}
|
|
||||||
revalidatePath("/gitea");
|
|
||||||
redirect(`/gitea${back.size ? `?${back}` : ""}`);
|
|
||||||
}
|
|
||||||
@ -1,16 +1,15 @@
|
|||||||
// glossary-ignore-file: superadmin-only page about the platform's git server — «репозиторий» is the literal object here
|
// glossary-ignore-file: superadmin-only page about the platform's git server — «репозиторий» is the literal object here
|
||||||
import Link from "@/components/Link";
|
import Link from "next/link";
|
||||||
import { notFound } from "next/navigation";
|
import { notFound } from "next/navigation";
|
||||||
import { ExternalLink, GitBranch, Lock } from "lucide-react";
|
import { ExternalLink, GitBranch, Lock } from "lucide-react";
|
||||||
import { giteaServerOverview, isSuperadmin, type GiteaServerRepo } from "@peppa/core";
|
import { giteaServerOverview, isSuperadmin, type GiteaServerRepo } from "@peppa/core";
|
||||||
import { ago, Empty, Flash, Notice, PageHeader, Section } from "@/components/common";
|
import { ago, Empty, Notice, PageHeader, Section } from "@/components/common";
|
||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Card } from "@/components/ui/card";
|
import { Card } from "@/components/ui/card";
|
||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
import { Workspace } from "@/components/Workspace";
|
import { Workspace } from "@/components/Workspace";
|
||||||
import { requireUser } from "@/lib/auth";
|
import { requireUser } from "@/lib/auth";
|
||||||
import { makeRepoPrivateAction } from "./actions";
|
|
||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
import { getT } from "@/lib/i18n";
|
import { getT } from "@/lib/i18n";
|
||||||
import type { Translator } from "@peppa/shared/i18n";
|
import type { Translator } from "@peppa/shared/i18n";
|
||||||
@ -20,13 +19,9 @@ export async function generateMetadata() {
|
|||||||
return { title: t("Gitea — FORGE") };
|
return { title: t("Gitea — FORGE") };
|
||||||
}
|
}
|
||||||
|
|
||||||
type Params = { q?: string; show?: string; closed?: string; error?: string; page?: string; fresh?: string };
|
type Params = { q?: string; show?: string };
|
||||||
type Show = "all" | "linked" | "unlinked" | "public";
|
|
||||||
|
|
||||||
/** Rows per page (PEP-273: the whole list made the page over 1 MB). */
|
function RepoRow({ r, t }: { r: GiteaServerRepo; t: Translator }) {
|
||||||
const PAGE_SIZE = 50;
|
|
||||||
|
|
||||||
function RepoRow({ r, t, q, show }: { r: GiteaServerRepo; t: Translator; q: string; show: Show }) {
|
|
||||||
return (
|
return (
|
||||||
<li className="flex flex-col gap-1 border-b border-border px-4 py-3 last:border-b-0">
|
<li className="flex flex-col gap-1 border-b border-border px-4 py-3 last:border-b-0">
|
||||||
<div className="flex flex-wrap items-center gap-2">
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
@ -54,18 +49,6 @@ function RepoRow({ r, t, q, show }: { r: GiteaServerRepo; t: Translator; q: stri
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
{r.description && <div className="text-sm text-muted-foreground">{r.description}</div>}
|
{r.description && <div className="text-sm text-muted-foreground">{r.description}</div>}
|
||||||
{!r.private && (
|
|
||||||
// PEP-280: one repository at a time; opening it again is the owner's decision in the project settings.
|
|
||||||
<form action={makeRepoPrivateAction} className="mt-1">
|
|
||||||
<input type="hidden" name="repo" value={r.fullName} />
|
|
||||||
{q && <input type="hidden" name="q" value={q} />}
|
|
||||||
{show !== "all" && <input type="hidden" name="show" value={show} />}
|
|
||||||
<Button type="submit" size="sm" variant="outline">
|
|
||||||
<Lock className="size-3" />
|
|
||||||
{t("Сделать закрытым")}
|
|
||||||
</Button>
|
|
||||||
</form>
|
|
||||||
)}
|
|
||||||
<div className="text-xs text-muted-foreground">
|
<div className="text-xs text-muted-foreground">
|
||||||
{t("ветка {branch} · обновлён {when} · {size}", { branch: r.defaultBranch || "—", when: ago(r.updatedAt, t), size: r.sizeKb >= 1024 ? `${(r.sizeKb / 1024).toFixed(1)} MB` : `${r.sizeKb} KB` })}
|
{t("ветка {branch} · обновлён {when} · {size}", { branch: r.defaultBranch || "—", when: ago(r.updatedAt, t), size: r.sizeKb >= 1024 ? `${(r.sizeKb / 1024).toFixed(1)} MB` : `${r.sizeKb} KB` })}
|
||||||
</div>
|
</div>
|
||||||
@ -78,26 +61,12 @@ export default async function GiteaPage({ searchParams }: { searchParams: Promis
|
|||||||
const t = await getT();
|
const t = await getT();
|
||||||
if (!(await isSuperadmin(db, user))) notFound();
|
if (!(await isSuperadmin(db, user))) notFound();
|
||||||
const q = await searchParams;
|
const q = await searchParams;
|
||||||
const o = await giteaServerOverview(db, { fresh: q.fresh === "1" });
|
const o = await giteaServerOverview(db);
|
||||||
const needle = (q.q ?? "").trim().toLowerCase();
|
const needle = (q.q ?? "").trim().toLowerCase();
|
||||||
const show: Show = q.show === "linked" || q.show === "unlinked" || q.show === "public" ? q.show : "all";
|
const show = q.show === "linked" || q.show === "unlinked" ? q.show : "all";
|
||||||
const repos = o.repos.filter(
|
const repos = o.repos.filter(
|
||||||
(r) =>
|
(r) => (!needle || r.fullName.toLowerCase().includes(needle) || r.description.toLowerCase().includes(needle)) && (show === "all" || (show === "linked") === !!r.project),
|
||||||
(!needle || r.fullName.toLowerCase().includes(needle) || r.description.toLowerCase().includes(needle)) &&
|
|
||||||
(show === "all" || (show === "public" ? !r.private : (show === "linked") === !!r.project)),
|
|
||||||
);
|
);
|
||||||
const open = o.repos.filter((r) => !r.private).length;
|
|
||||||
const pages = Math.max(1, Math.ceil(repos.length / PAGE_SIZE));
|
|
||||||
const page = Math.min(pages, Math.max(1, Number.parseInt(q.page ?? "1", 10) || 1));
|
|
||||||
const shown = repos.slice((page - 1) * PAGE_SIZE, page * PAGE_SIZE);
|
|
||||||
const href = (extra: Record<string, string>) => {
|
|
||||||
const sp = new URLSearchParams();
|
|
||||||
if (q.q) sp.set("q", q.q);
|
|
||||||
if (show !== "all") sp.set("show", show);
|
|
||||||
for (const [k, v] of Object.entries(extra)) sp.set(k, v);
|
|
||||||
const s = sp.toString();
|
|
||||||
return s ? `/gitea?${s}` : "/gitea";
|
|
||||||
};
|
|
||||||
const owners = new Map<string, number>();
|
const owners = new Map<string, number>();
|
||||||
for (const r of o.repos) owners.set(r.owner, (owners.get(r.owner) ?? 0) + 1);
|
for (const r of o.repos) owners.set(r.owner, (owners.get(r.owner) ?? 0) + 1);
|
||||||
const linked = o.repos.filter((r) => r.project).length;
|
const linked = o.repos.filter((r) => r.project).length;
|
||||||
@ -125,32 +94,15 @@ export default async function GiteaPage({ searchParams }: { searchParams: Promis
|
|||||||
{t("Бот")}: <span className="font-mono">{o.bot?.login ?? "—"}</span>
|
{t("Бот")}: <span className="font-mono">{o.bot?.login ?? "—"}</span>
|
||||||
{o.bot && (o.bot.admin ? <Badge variant="ok" className="ml-2">{t("админ сервера — видит все репозитории")}</Badge> : <Badge variant="warn" className="ml-2">{t("не админ — видит публичные и свои репозитории")}</Badge>)}
|
{o.bot && (o.bot.admin ? <Badge variant="ok" className="ml-2">{t("админ сервера — видит все репозитории")}</Badge> : <Badge variant="warn" className="ml-2">{t("не админ — видит публичные и свои репозитории")}</Badge>)}
|
||||||
</div>
|
</div>
|
||||||
{o.fetchedAt && (
|
|
||||||
<div className="text-muted-foreground">
|
|
||||||
{t("Список получен {when}", { when: ago(o.fetchedAt, t) })} ·{" "}
|
|
||||||
<a href={href({ fresh: "1" })}>{t("Получить заново")}</a>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{o.repos.length > 0 && (
|
{o.repos.length > 0 && (
|
||||||
<div className="text-muted-foreground">
|
<div className="text-muted-foreground">
|
||||||
{t("Репозиториев: {n} · подключены к проектам: {linked}", { n: o.repos.length, linked })} ·{" "}
|
{t("Репозиториев: {n} · подключены к проектам: {linked}", { n: o.repos.length, linked })} ·{" "}
|
||||||
{[...owners].sort((a, b) => b[1] - a[1]).map(([owner, n]) => `${owner} ${n}`).join(", ")}
|
{[...owners].sort((a, b) => b[1] - a[1]).map(([owner, n]) => `${owner} ${n}`).join(", ")}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
{o.repos.length > 0 && (
|
|
||||||
<div>
|
|
||||||
{open > 0 ? (
|
|
||||||
<Link href="/gitea?show=public">{t("Публичных: {n} — их видит любой, у кого есть доступ к Gitea", { n: open })}</Link>
|
|
||||||
) : (
|
|
||||||
<span className="text-muted-foreground">{t("Публичных нет")}</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</Card>
|
</Card>
|
||||||
</Section>
|
</Section>
|
||||||
|
|
||||||
{q.closed && <Notice>{t("{repo} теперь закрытый: его видят только владелец, участники и бот", { repo: q.closed })}</Notice>}
|
|
||||||
<Flash error={q.error} />
|
|
||||||
{o.error && <Notice>{t("Gitea не ответила: {error}", { error: o.error })}</Notice>}
|
{o.error && <Notice>{t("Gitea не ответила: {error}", { error: o.error })}</Notice>}
|
||||||
|
|
||||||
<Section title={t("Репозитории")} count={repos.length}>
|
<Section title={t("Репозитории")} count={repos.length}>
|
||||||
@ -160,7 +112,6 @@ export default async function GiteaPage({ searchParams }: { searchParams: Promis
|
|||||||
<option value="all">{t("все")}</option>
|
<option value="all">{t("все")}</option>
|
||||||
<option value="linked">{t("подключённые к проектам")}</option>
|
<option value="linked">{t("подключённые к проектам")}</option>
|
||||||
<option value="unlinked">{t("без проекта")}</option>
|
<option value="unlinked">{t("без проекта")}</option>
|
||||||
<option value="public">{t("публичные")}</option>
|
|
||||||
</select>
|
</select>
|
||||||
<Button type="submit" size="sm">
|
<Button type="submit" size="sm">
|
||||||
{t("Показать")}
|
{t("Показать")}
|
||||||
@ -171,19 +122,12 @@ export default async function GiteaPage({ searchParams }: { searchParams: Promis
|
|||||||
) : (
|
) : (
|
||||||
<Card className="p-0">
|
<Card className="p-0">
|
||||||
<ul>
|
<ul>
|
||||||
{shown.map((r) => (
|
{repos.map((r) => (
|
||||||
<RepoRow key={r.fullName} r={r} t={t} q={q.q ?? ""} show={show} />
|
<RepoRow key={r.fullName} r={r} t={t} />
|
||||||
))}
|
))}
|
||||||
</ul>
|
</ul>
|
||||||
</Card>
|
</Card>
|
||||||
)}
|
)}
|
||||||
{pages > 1 && (
|
|
||||||
<nav className="mt-3 flex items-center gap-3 text-sm">
|
|
||||||
{page > 1 ? <a href={href({ page: String(page - 1) })}>{t("‹ Назад")}</a> : <span className="text-muted-foreground">{t("‹ Назад")}</span>}
|
|
||||||
<span className="text-muted-foreground">{t("Страница {page} из {pages}", { page, pages })}</span>
|
|
||||||
{page < pages ? <a href={href({ page: String(page + 1) })}>{t("Дальше ›")}</a> : <span className="text-muted-foreground">{t("Дальше ›")}</span>}
|
|
||||||
</nav>
|
|
||||||
)}
|
|
||||||
</Section>
|
</Section>
|
||||||
</div>
|
</div>
|
||||||
</Workspace>
|
</Workspace>
|
||||||
|
|||||||
@ -1,4 +1,4 @@
|
|||||||
import Link from "@/components/Link";
|
import Link from "next/link";
|
||||||
import { CONNECT_HELP, featureGateView } from "@peppa/core";
|
import { CONNECT_HELP, featureGateView } from "@peppa/core";
|
||||||
import { FeatureGate } from "@/components/FeatureGate";
|
import { FeatureGate } from "@/components/FeatureGate";
|
||||||
import { LiveRefresh } from "@/components/LiveRefresh";
|
import { LiveRefresh } from "@/components/LiveRefresh";
|
||||||
@ -7,14 +7,8 @@ import { CopyText } from "@/components/CopyText";
|
|||||||
import { Workspace } from "@/components/Workspace";
|
import { Workspace } from "@/components/Workspace";
|
||||||
import { publicOrigin } from "@/lib/auth";
|
import { publicOrigin } from "@/lib/auth";
|
||||||
import { getLocale, getT } from "@/lib/i18n";
|
import { getLocale, getT } from "@/lib/i18n";
|
||||||
import { pageTitle } from "@/lib/title";
|
|
||||||
|
|
||||||
// PEP-274: the browser tab says which page it is.
|
|
||||||
export async function generateMetadata() {
|
|
||||||
const t = await getT();
|
|
||||||
return pageTitle(t, (CONNECT_HELP[t.locale] ?? CONNECT_HELP.ru).title);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
/** 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() {
|
export default async function ConnectHelp() {
|
||||||
const t = CONNECT_HELP[await getLocale()] ?? CONNECT_HELP.ru;
|
const t = CONNECT_HELP[await getLocale()] ?? CONNECT_HELP.ru;
|
||||||
const address = `${await publicOrigin()}/mcp`;
|
const address = `${await publicOrigin()}/mcp`;
|
||||||
@ -78,5 +72,3 @@ export default async function ConnectHelp() {
|
|||||||
</Workspace>
|
</Workspace>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** PEP-135: how to connect FORGE to one's own Claude or ChatGPT — step by step; texts live in core/connect-texts.ts. */
|
|
||||||
|
|||||||
@ -1,4 +1,4 @@
|
|||||||
import Link from "@/components/Link";
|
import Link from "next/link";
|
||||||
import type { ReactNode } from "react";
|
import type { ReactNode } from "react";
|
||||||
import { CONNECT_HELP, featureGateView, PRODUCT_HELP } from "@peppa/core";
|
import { CONNECT_HELP, featureGateView, PRODUCT_HELP } from "@peppa/core";
|
||||||
import { FeatureGate } from "@/components/FeatureGate";
|
import { FeatureGate } from "@/components/FeatureGate";
|
||||||
@ -9,7 +9,6 @@ import { publicOrigin, uiMode } from "@/lib/auth";
|
|||||||
import { Workspace } from "@/components/Workspace";
|
import { Workspace } from "@/components/Workspace";
|
||||||
import { voiceStoriesEnabled } from "@peppa/shared";
|
import { voiceStoriesEnabled } from "@peppa/shared";
|
||||||
import { PageHeader, Section } from "@/components/common";
|
import { PageHeader, Section } from "@/components/common";
|
||||||
import { pageTitle } from "@/lib/title";
|
|
||||||
|
|
||||||
const TOOLS: Array<[string, string]> = [
|
const TOOLS: Array<[string, string]> = [
|
||||||
["get_started", m("правила работы для ИИ-клиента: вызывается первым, коротко и без кода")],
|
["get_started", m("правила работы для ИИ-клиента: вызывается первым, коротко и без кода")],
|
||||||
@ -56,7 +55,7 @@ const CASES: Array<{ title: string; say: string; how: string }> = [
|
|||||||
{ title: m("Работать вместе"), say: m("Добавь в PAY участника dana"), how: m("add_member (только владелец). Участник видит доску и входящие, двигает карточки, отвечает агентам и получает доступ к репозиторию. Тот, кто ещё не входил в FORGE, получит приглашение — оно сработает при первом входе") },
|
{ 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 делается сам: бери стори из бэклога и мержи зелёные 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 делай на 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 приватным"), how: m("set_project_visibility (только владелец). Новые проекты публичные по умолчанию; то же — в вебе: «⋯ Настройки проекта» → «Репозиторий»") },
|
||||||
{ title: m("Ошибки из прода"), say: m("Какие ошибки ждут решения в PAY? · Ошибку #7 — в работу"), how: m("list_incidents → decide_incident. Подключение — на странице проекта «⋯ Настройки проекта → Баги»") },
|
{ 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("В PAY пусть ошибки разбирает триажёр: падения оплаты — сразу в работу, косметику — в бэклог, остальное спроси"), how: m("set_incident_policy policy=triage, triage_prompt — ваши слова. Не уверен — спросит кнопками в Telegram") },
|
||||||
{ title: m("Выкатить в прод"), say: m("Что сейчас на staging в PAY? · Выкати PAY в прод"), how: m("list_releases → deploy. Тот же образ, что прошёл staging; не поднялся — FORGE сама откатит и напишет") },
|
{ title: m("Выкатить в прод"), say: m("Что сейчас на staging в PAY? · Выкати PAY в прод"), how: m("list_releases → deploy. Тот же образ, что прошёл staging; не поднялся — FORGE сама откатит и напишет") },
|
||||||
@ -141,12 +140,6 @@ async function ProductHelp() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// PEP-274: the browser tab says which page it is.
|
|
||||||
export async function generateMetadata() {
|
|
||||||
const t = await getT();
|
|
||||||
return pageTitle(t, t("Помощь"));
|
|
||||||
}
|
|
||||||
|
|
||||||
export default async function Help() {
|
export default async function Help() {
|
||||||
if ((await uiMode()) === "product") return <ProductHelp />;
|
if ((await uiMode()) === "product") return <ProductHelp />;
|
||||||
const t = await getT();
|
const t = await getT();
|
||||||
@ -194,7 +187,7 @@ export default async function Help() {
|
|||||||
<li>{rich(t("<b>Codex, Claude и другие MCP-клиенты</b>: добавьте удалённый MCP-сервер по этому URL с OAuth — клиент зарегистрируется сам, вход и согласие на экране FORGE."))}</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("Если клиент не видит новых инструментов — обновите или переподключите коннектор. Доступ отзывается в <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> — «⋯ Настройки проекта → Модель агента» (и в разделе «Агент» стори — для неё одной): провайдер (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/</code> в репозитории: команды, соглашения, грабли и решения, которые агенты записывают в конце стори (MCP <code>remember</code>), у каждой задачи свой файл — параллельные задачи не мешают друг другу. Раннер собирает её вместе со сводкой последних завершённых стори в каждый запуск агента; размер подсказки ограничен — сначала общая часть и новые задачи, старые агент сворачивает сам. Посмотреть — вкладка проекта «Спеки»."))}</li>
|
<li>{rich(t("<b>Память проекта</b> — <code>.peppa/memory.md</code> в репозитории: команды, соглашения, грабли и решения, которые агенты записывают в конце стори (MCP <code>remember</code>). Раннер подкладывает её вместе со сводкой последних завершённых стори в каждый запуск агента; размер ограничен — разросшуюся память агент ужимает сам. Посмотреть — вкладка проекта «Спеки»."))}</li>
|
||||||
<li>{rich(t("<b>Первый запуск</b> — на Главной чек-лист: подписка агента (суперадмину), Telegram, eGov (необязательно), проект, первая стори, стори в работе. Исчезает, когда всё сделано, или по «Скрыть». Если у пула проекта нет ни одной рабочей подписки, на странице проекта — предупреждение «Агенты не запустятся»."))}</li>
|
<li>{rich(t("<b>Первый запуск</b> — на Главной чек-лист: подписка агента (суперадмину), Telegram, eGov (необязательно), проект, первая стори, стори в работе. Исчезает, когда всё сделано, или по «Скрыть». Если у пула проекта нет ни одной рабочей подписки, на странице проекта — предупреждение «Агенты не запустятся»."))}</li>
|
||||||
<li>{rich(t("<b>Подписки</b> — аккаунты Claude Code, Codex и OpenCode, на которых работают агенты, и пулы для ротации ведёт суперадмин в разделе «Подписки». У проекта — пул по умолчанию («⋯ Настройки проекта»): раннер стартует на первой свободной активной подписке пула, а в «Раннерах» видно, на какой. Упёрся в лимит — после конца хода раннер сам переходит на свободную подписку того же агента в пуле (Claude — продолжая тот же разговор, Codex — заново, с контекстом из стори) и пишет в Telegram «переключил на подписку…»; подписки того же агента нет, а есть другая (Claude ↔ ChatGPT) — переезжает на неё и начинает заново с контекстом из стори («переехал…»; выключается <code>PEPPA_ROTATE_CROSS=off</code>); свободных нет — ждёт сброса и продолжает сам."))}</li>
|
<li>{rich(t("<b>Подписки</b> — аккаунты Claude Code, Codex и OpenCode, на которых работают агенты, и пулы для ротации ведёт суперадмин в разделе «Подписки». У проекта — пул по умолчанию («⋯ Настройки проекта»): раннер стартует на первой свободной активной подписке пула, а в «Раннерах» видно, на какой. Упёрся в лимит — после конца хода раннер сам переходит на свободную подписку того же агента в пуле (Claude — продолжая тот же разговор, Codex — заново, с контекстом из стори) и пишет в Telegram «переключил на подписку…»; подписки того же агента нет, а есть другая (Claude ↔ ChatGPT) — переезжает на неё и начинает заново с контекстом из стори («переехал…»; выключается <code>PEPPA_ROTATE_CROSS=off</code>); свободных нет — ждёт сброса и продолжает сам."))}</li>
|
||||||
<li>{rich(t("<b>Несколько своих подписок</b> — «⋯ Настройки проекта → Подписки»: у каждой подписки пула видно «в работе: N агентов», «свободна», «лимит до 15:40» и сколько использовано окна лимита. «Добавить ещё Claude» / «Добавить ещё ChatGPT» — тот же вход по ссылке; «Убрать» — своя подписка, на которой сейчас никто не работает. Когда в пуле остаётся одна рабочая подписка и она использована больше чем на 85%, участникам приходит одно предупреждение «осталась одна подписка, скоро лимит»."))}</li>
|
<li>{rich(t("<b>Несколько своих подписок</b> — «⋯ Настройки проекта → Подписки»: у каждой подписки пула видно «в работе: N агентов», «свободна», «лимит до 15:40» и сколько использовано окна лимита. «Добавить ещё Claude» / «Добавить ещё ChatGPT» — тот же вход по ссылке; «Убрать» — своя подписка, на которой сейчас никто не работает. Когда в пуле остаётся одна рабочая подписка и она использована больше чем на 85%, участникам приходит одно предупреждение «осталась одна подписка, скоро лимит»."))}</li>
|
||||||
|
|||||||
@ -1,17 +1,11 @@
|
|||||||
import Link from "@/components/Link";
|
import Link from "next/link";
|
||||||
import { ShortcutsList } from "@/components/CommandPalette";
|
import { ShortcutsList } from "@/components/CommandPalette";
|
||||||
import { PageHeader, Section } from "@/components/common";
|
import { PageHeader, Section } from "@/components/common";
|
||||||
import { Workspace } from "@/components/Workspace";
|
import { Workspace } from "@/components/Workspace";
|
||||||
import { PALETTE_KEYS } from "@/lib/shortcuts";
|
import { PALETTE_KEYS } from "@/lib/shortcuts";
|
||||||
import { getT } from "@/lib/i18n";
|
import { getT } from "@/lib/i18n";
|
||||||
import { pageTitle } from "@/lib/title";
|
|
||||||
|
|
||||||
// PEP-274: the browser tab says which page it is.
|
|
||||||
export async function generateMetadata() {
|
|
||||||
const t = await getT();
|
|
||||||
return pageTitle(t, t("Горячие клавиши"));
|
|
||||||
}
|
|
||||||
|
|
||||||
|
/** PEP-52: list of keyboard shortcuts (the same list as the «?» dialog). */
|
||||||
export default async function Shortcuts() {
|
export default async function Shortcuts() {
|
||||||
const t = await getT();
|
const t = await getT();
|
||||||
return (
|
return (
|
||||||
@ -32,5 +26,3 @@ export default async function Shortcuts() {
|
|||||||
</Workspace>
|
</Workspace>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** PEP-52: list of keyboard shortcuts (the same list as the «?» dialog). */
|
|
||||||
|
|||||||
@ -6,14 +6,8 @@ import { Workspace } from "@/components/Workspace";
|
|||||||
import { requireUser } from "@/lib/auth";
|
import { requireUser } from "@/lib/auth";
|
||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
import { getT } from "@/lib/i18n";
|
import { getT } from "@/lib/i18n";
|
||||||
import { pageTitle } from "@/lib/title";
|
|
||||||
|
|
||||||
// PEP-274: the browser tab says which page it is.
|
|
||||||
export async function generateMetadata() {
|
|
||||||
const t = await getT();
|
|
||||||
return pageTitle(t, t("Журнал действий"));
|
|
||||||
}
|
|
||||||
|
|
||||||
|
/** Superadmin only (PEP-48): who did what — people (web, Telegram, MCP clients, CLI), agents, Peppa. */
|
||||||
export default async function Journal({ searchParams }: { searchParams: Promise<{ project?: string; actor?: string; channel?: string; all?: string }> }) {
|
export default async function Journal({ searchParams }: { searchParams: Promise<{ project?: string; actor?: string; channel?: string; all?: string }> }) {
|
||||||
const me = await requireUser();
|
const me = await requireUser();
|
||||||
if (!(await isSuperadmin(db, me))) notFound();
|
if (!(await isSuperadmin(db, me))) notFound();
|
||||||
@ -41,5 +35,3 @@ export default async function Journal({ searchParams }: { searchParams: Promise<
|
|||||||
</Workspace>
|
</Workspace>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Superadmin only (PEP-48): who did what — people (web, Telegram, MCP clients, CLI), agents, Peppa. */
|
|
||||||
|
|||||||
@ -1,5 +1,5 @@
|
|||||||
import type { ReactNode } from "react";
|
import type { ReactNode } from "react";
|
||||||
import { accountUsageForUser, agentsLine, getNotifyPrefs, httpsAvatar, isSuperadmin, pendingFeedbackCount } from "@peppa/core";
|
import { accountUsageForUser, agentsLine, getNotifyPrefs, isSuperadmin, pendingFeedbackCount } from "@peppa/core";
|
||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
import { subscriptionRequestOffers } from "@peppa/runner";
|
import { subscriptionRequestOffers } from "@peppa/runner";
|
||||||
import { requireUser, uiMode } from "@/lib/auth";
|
import { requireUser, uiMode } from "@/lib/auth";
|
||||||
@ -7,8 +7,7 @@ import { navCounts } from "@/lib/queries";
|
|||||||
import { WordsProvider } from "@/components/Words";
|
import { WordsProvider } from "@/components/Words";
|
||||||
import { Sidebar } from "@/components/Sidebar";
|
import { Sidebar } from "@/components/Sidebar";
|
||||||
import { AttentionBadge } from "@/components/AttentionBadge";
|
import { AttentionBadge } from "@/components/AttentionBadge";
|
||||||
import { LazyCommandPalette as CommandPalette } from "@/components/Lazy";
|
import { CommandPalette } from "@/components/CommandPalette";
|
||||||
import { WebVitals } from "@/components/WebVitals";
|
|
||||||
import { AgentsStrip, UsageStrip } from "@/components/Accounting";
|
import { AgentsStrip, UsageStrip } from "@/components/Accounting";
|
||||||
import { VersionWatch } from "@/components/VersionWatch";
|
import { VersionWatch } from "@/components/VersionWatch";
|
||||||
import { bootId } from "@/lib/boot";
|
import { bootId } from "@/lib/boot";
|
||||||
@ -35,15 +34,13 @@ export default async function AppLayout({ children }: { children: ReactNode }) {
|
|||||||
<WordsProvider mode={mode}>
|
<WordsProvider mode={mode}>
|
||||||
<div className="min-h-dvh md:grid md:grid-cols-[232px_minmax(0,1fr)]">
|
<div className="min-h-dvh md:grid md:grid-cols-[232px_minmax(0,1fr)]">
|
||||||
<AttentionBadge count={counts.questions + counts.waitingRunners} sound={sound} />
|
<AttentionBadge count={counts.questions + counts.waitingRunners} sound={sound} />
|
||||||
<Sidebar login={user.login} avatarUrl={httpsAvatar(user.avatarUrl)} counts={{ ...counts, feedback }} 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">
|
<div className="flex min-w-0 flex-col pb-16 md:pb-0">
|
||||||
<VersionWatch boot={bootId()} />
|
<VersionWatch boot={bootId()} />
|
||||||
{line ? <AgentsStrip line={line} offers={offers} /> : <UsageStrip accounts={accounts} admin={superadmin} />}
|
{line ? <AgentsStrip line={line} offers={offers} /> : <UsageStrip accounts={accounts} admin={superadmin} />}
|
||||||
{children}
|
{children}
|
||||||
</div>
|
</div>
|
||||||
<CommandPalette />
|
<CommandPalette />
|
||||||
{/* PEP-217: Web Vitals of real users. */}
|
|
||||||
<WebVitals mode={mode} />
|
|
||||||
{/* PEP-143: «Сообщить о проблеме» on every page. */}
|
{/* PEP-143: «Сообщить о проблеме» on every page. */}
|
||||||
<FeedbackButton />
|
<FeedbackButton />
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@ -1,6 +1,5 @@
|
|||||||
// glossary-ignore-file: the section is for the superadmin only.
|
// glossary-ignore-file: the section is for the superadmin only.
|
||||||
import { platformZone } from "@peppa/shared/time";
|
import Link from "next/link";
|
||||||
import Link from "@/components/Link";
|
|
||||||
import { notFound } from "next/navigation";
|
import { notFound } from "next/navigation";
|
||||||
import { Activity, Pause, Play, Trash2 } from "lucide-react";
|
import { Activity, Pause, Play, Trash2 } from "lucide-react";
|
||||||
import { describeTarget, FEATURES, observeRemindMin, getMonitor, isSuperadmin, monitorChecks, monitorIncidents, monitorView } from "@peppa/core";
|
import { describeTarget, FEATURES, observeRemindMin, getMonitor, isSuperadmin, monitorChecks, monitorIncidents, monitorView } from "@peppa/core";
|
||||||
@ -16,18 +15,11 @@ import { requireUser } from "@/lib/auth";
|
|||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
import { getT } from "@/lib/i18n";
|
import { getT } from "@/lib/i18n";
|
||||||
import { deleteMonitorAction, pauseMonitorAction, updateMonitorAction } from "../actions";
|
import { deleteMonitorAction, pauseMonitorAction, updateMonitorAction } from "../actions";
|
||||||
import { pageTitle } from "@/lib/title";
|
|
||||||
|
|
||||||
export const dynamic = "force-dynamic";
|
export const dynamic = "force-dynamic";
|
||||||
const PAGE = 100;
|
const PAGE = 100;
|
||||||
|
|
||||||
// PEP-274: the browser tab says which page it is.
|
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 async function generateMetadata() {
|
|
||||||
const t = await getT();
|
|
||||||
return pageTitle(t, t("Мониторинг"));
|
|
||||||
}
|
|
||||||
|
|
||||||
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", timeZone: platformZone() });
|
|
||||||
|
|
||||||
export default async function MonitorPage({ params, searchParams }: { params: Promise<{ id: string }>; searchParams: Promise<{ error?: string; page?: string }> }) {
|
export default async function MonitorPage({ params, searchParams }: { params: Promise<{ id: string }>; searchParams: Promise<{ error?: string; page?: string }> }) {
|
||||||
const user = await requireUser();
|
const user = await requireUser();
|
||||||
|
|||||||
@ -1,7 +1,7 @@
|
|||||||
"use server";
|
"use server";
|
||||||
// Observability (PEP-202): every action is superadmin-only (others get "not found").
|
// 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 { createMonitor, deleteMonitor, 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 type { Db } from "@peppa/db";
|
||||||
import { m } from "@peppa/shared/i18n";
|
import { m } from "@peppa/shared/i18n";
|
||||||
import { revalidatePath } from "next/cache";
|
import { revalidatePath } from "next/cache";
|
||||||
@ -111,10 +111,3 @@ export async function setFeatureThresholdAction(f: FormData) {
|
|||||||
await journal(db, "feature_updated", { feature: name, disableAfterMin: minutes, author: `user:${login}` });
|
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);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|||||||
@ -1,9 +1,8 @@
|
|||||||
// glossary-ignore-file: the section is for the superadmin only.
|
// glossary-ignore-file: the section is for the superadmin only.
|
||||||
import { platformZone } from "@peppa/shared/time";
|
import Link from "next/link";
|
||||||
import Link from "@/components/Link";
|
|
||||||
import { notFound } from "next/navigation";
|
import { notFound } from "next/navigation";
|
||||||
import { Activity, Pause, Play, Plus } from "lucide-react";
|
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, isBadVital, vitalsSummary, type VitalDevice, type VitalMetric } from "@peppa/core";
|
import { describeTarget, observeRemindMin, egovLoginSummary, errorScope, errorsOverview, FEATURE_NAMES, FEATURES, featureLog, featureStatuses, getLastRetention, isSuperadmin, listErrors, listMonitorViews, requestSummary } from "@peppa/core";
|
||||||
import { loadEnv } from "@peppa/shared";
|
import { loadEnv } from "@peppa/shared";
|
||||||
import { LiveRefresh } from "@/components/LiveRefresh";
|
import { LiveRefresh } from "@/components/LiveRefresh";
|
||||||
import { Hidden } from "@/components/cards";
|
import { Hidden } from "@/components/cards";
|
||||||
@ -16,7 +15,7 @@ import { Workspace } from "@/components/Workspace";
|
|||||||
import { requireUser } from "@/lib/auth";
|
import { requireUser } from "@/lib/auth";
|
||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
import { getT } from "@/lib/i18n";
|
import { getT } from "@/lib/i18n";
|
||||||
import { createMonitorAction, pauseMonitorAction, requestSmokeAction, setFeatureThresholdAction } from "./actions";
|
import { createMonitorAction, pauseMonitorAction, setFeatureThresholdAction } from "./actions";
|
||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
|
|
||||||
@ -27,10 +26,7 @@ export async function generateMetadata() {
|
|||||||
return { title: t("Observability — FORGE") };
|
return { title: t("Observability — FORGE") };
|
||||||
}
|
}
|
||||||
|
|
||||||
const VITAL_COLUMNS: VitalMetric[] = ["LCP", "INP", "CLS", "TTFB"];
|
type Search = { error?: string; tab?: string; bp?: string; state?: string; env?: string; rel?: string; q?: string; sort?: string; cursor?: string };
|
||||||
const fmtVital = (m: VitalMetric, v: number | null) => (v == null ? "—" : m === "CLS" ? v.toFixed(2) : v >= 1000 ? `${(v / 1000).toFixed(1)} s` : `${Math.round(v)} ms`);
|
|
||||||
|
|
||||||
type Search = { error?: string; tab?: string; bp?: string; state?: string; env?: string; rel?: string; q?: string; sort?: string; cursor?: string; device?: string };
|
|
||||||
|
|
||||||
/** Tabs «Мониторинги» · «Ошибки» (PEP-218). */
|
/** Tabs «Мониторинги» · «Ошибки» (PEP-218). */
|
||||||
function Tabs({ tab, t }: { tab: "monitors" | "errors"; t: Awaited<ReturnType<typeof getT>> }) {
|
function Tabs({ tab, t }: { tab: "monitors" | "errors"; t: Awaited<ReturnType<typeof getT>> }) {
|
||||||
@ -73,76 +69,6 @@ async function ErrorsTab({ user, sp }: { user: Awaited<ReturnType<typeof require
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 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", timeZone: platformZone() });
|
|
||||||
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> }) {
|
export default async function Observability({ searchParams }: { searchParams: Promise<Search> }) {
|
||||||
const user = await requireUser();
|
const user = await requireUser();
|
||||||
const t = await getT();
|
const t = await getT();
|
||||||
@ -167,8 +93,6 @@ export default async function Observability({ searchParams }: { searchParams: Pr
|
|||||||
const egov = await egovLoginSummary(db);
|
const egov = await egovLoginSummary(db);
|
||||||
const retention = await getLastRetention(db);
|
const retention = await getLastRetention(db);
|
||||||
const speed = requestSummary();
|
const speed = requestSummary();
|
||||||
const device: VitalDevice | undefined = sp.device === "narrow" || sp.device === "wide" ? sp.device : undefined;
|
|
||||||
const vitals = vitalsSummary({ device });
|
|
||||||
const ms = (n: number) => (n >= 1000 ? t("{n} с", { n: (n / 1000).toFixed(1) }) : t("{n} мс", { n: Math.round(n) }));
|
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 web = loadEnv().PEPPA_WEB_URL;
|
||||||
const down = monitors.filter((m) => !m.paused && m.state === "down").length;
|
const down = monitors.filter((m) => !m.paused && m.state === "down").length;
|
||||||
@ -240,8 +164,6 @@ export default async function Observability({ searchParams }: { searchParams: Pr
|
|||||||
</Disclosure>
|
</Disclosure>
|
||||||
</Section>
|
</Section>
|
||||||
|
|
||||||
<SmokeSection t={t} />
|
|
||||||
|
|
||||||
<Section title={t("Функции")} count={FEATURE_NAMES.length}>
|
<Section title={t("Функции")} count={FEATURE_NAMES.length}>
|
||||||
<p className="m-0 text-sm text-muted-foreground">{t("Функция становится серой у пользователей, когда связанный мониторинг не работает дольше порога, и включается сама после восстановления. Связка — «Что отключать при сбое» у мониторинга или поле features в MCP update_monitor.")}</p>
|
<p className="m-0 text-sm text-muted-foreground">{t("Функция становится серой у пользователей, когда связанный мониторинг не работает дольше порога, и включается сама после восстановления. Связка — «Что отключать при сбое» у мониторинга или поле features в MCP update_monitor.")}</p>
|
||||||
<div className="flex flex-col gap-2">
|
<div className="flex flex-col gap-2">
|
||||||
@ -288,7 +210,7 @@ export default async function Observability({ searchParams }: { searchParams: Pr
|
|||||||
<ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm">
|
<ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm">
|
||||||
{flog.map((e) => (
|
{flog.map((e) => (
|
||||||
<li key={e.id} className="flex flex-wrap gap-2">
|
<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", timeZone: platformZone() })}</span>
|
<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={e.state === "unavailable" ? "text-destructive" : "text-ok"}>{e.state === "unavailable" ? t("отключена") : t("снова включена")}</span>
|
||||||
<span className="font-medium">{t(FEATURES[e.name].label)}</span>
|
<span className="font-medium">{t(FEATURES[e.name].label)}</span>
|
||||||
{e.reason && <span className="text-muted-foreground">{e.reason}</span>}
|
{e.reason && <span className="text-muted-foreground">{e.reason}</span>}
|
||||||
@ -332,42 +254,6 @@ export default async function Observability({ searchParams }: { searchParams: Pr
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</Section>
|
</Section>
|
||||||
|
|
||||||
{/* PEP-217: what the browsers of real users measured over the last day. */}
|
|
||||||
<Section title={t("Скорость в браузере")} count={vitals.length}>
|
|
||||||
<p className="mb-2 text-sm text-muted-foreground">{t("Что измерили браузеры пользователей за сутки. Значение — p75: три из четырёх посещений не хуже него. Плохо: LCP больше 4 с, INP больше 500 мс.")}</p>
|
|
||||||
<div className="mb-2 flex gap-3 text-sm">
|
|
||||||
{([[undefined, t("Все экраны")], ["narrow", t("Узкий экран")], ["wide", t("Широкий экран")]] as const).map(([d, label]) => (
|
|
||||||
<Link key={label} href={d ? `/observability?device=${d}` : "/observability"} className={d === device ? "font-semibold" : "text-muted-foreground hover:underline"}>{label}</Link>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
{vitals.length === 0 ? (
|
|
||||||
<Empty>{t("Пока нет данных: браузеры пришлют их при следующих открытиях страниц.")}</Empty>
|
|
||||||
) : (
|
|
||||||
<Card className="overflow-x-auto py-2">
|
|
||||||
<table className="w-full text-sm">
|
|
||||||
<thead>
|
|
||||||
<tr className="text-left text-xs text-muted-foreground">
|
|
||||||
<th className="px-3 py-1 font-normal">{t("Страница")}</th>
|
|
||||||
<th className="px-3 py-1 text-right font-normal">{t("Посещений")}</th>
|
|
||||||
{VITAL_COLUMNS.map((c) => <th key={c} className="px-3 py-1 text-right font-normal">{c}</th>)}
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody>
|
|
||||||
{vitals.map((r) => (
|
|
||||||
<tr key={r.route} className="border-t">
|
|
||||||
<td className="px-3 py-1 font-mono text-xs">{r.route}</td>
|
|
||||||
<td className="px-3 py-1 text-right text-muted-foreground">{r.samples}</td>
|
|
||||||
{VITAL_COLUMNS.map((c) => (
|
|
||||||
<td key={c} className={`px-3 py-1 text-right ${isBadVital(c, r.p75[c], r.n[c]) ? "text-destructive" : ""}`}>{fmtVital(c, r.p75[c])}</td>
|
|
||||||
))}
|
|
||||||
</tr>
|
|
||||||
))}
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
</Card>
|
|
||||||
)}
|
|
||||||
</Section>
|
|
||||||
</div>
|
</div>
|
||||||
</Workspace>
|
</Workspace>
|
||||||
);
|
);
|
||||||
|
|||||||
@ -1,4 +1,4 @@
|
|||||||
import Link from "@/components/Link";
|
import Link from "next/link";
|
||||||
import { notFound } from "next/navigation";
|
import { notFound } from "next/navigation";
|
||||||
import { acceptAllSummary, acceptScreen, type AcceptItem } from "@peppa/core";
|
import { acceptAllSummary, acceptScreen, type AcceptItem } from "@peppa/core";
|
||||||
import { acceptAllAction, fixStoryAction } from "@/app/(app)/actions";
|
import { acceptAllAction, fixStoryAction } from "@/app/(app)/actions";
|
||||||
|
|||||||
@ -1,13 +1,12 @@
|
|||||||
import { platformZone } from "@peppa/shared/time";
|
import Link from "next/link";
|
||||||
import Link from "@/components/Link";
|
|
||||||
import { Fragment } from "react";
|
import { Fragment } from "react";
|
||||||
import { ProductCard } from "@/components/ProductCard";
|
import { ProductCard } from "@/components/ProductCard";
|
||||||
import { PublishPanel } from "@/components/PublishPanel";
|
import { PublishPanel } from "@/components/PublishPanel";
|
||||||
import { notFound } from "next/navigation";
|
import { notFound } from "next/navigation";
|
||||||
import { ExternalLink, Plus, Rocket, SquareTerminal } from "lucide-react";
|
import { ExternalLink, Plus, Rocket, SquareTerminal } from "lucide-react";
|
||||||
import { columnOf, currentReleases, peekRepo, isPlatform, listReleases, bugsinkWebhookBase, openPulls, platformReleaseCandidate, platformReleaseOffers, ownPendingLogins, readAgentsMd, repoOverview, type Release, sharedRequest, subscriptionRequestOffer } from "@peppa/runner";
|
import { 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 { 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, 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, deferredFindings } from "@peppa/core";
|
import { productNeeds, lastProductReview } from "@peppa/core";
|
||||||
import { LiveRefresh } from "@/components/LiveRefresh";
|
import { LiveRefresh } from "@/components/LiveRefresh";
|
||||||
import { PanelSection } from "@/components/ActivityAside";
|
import { PanelSection } from "@/components/ActivityAside";
|
||||||
import { Board, type Card } from "@/components/Board";
|
import { Board, type Card } from "@/components/Board";
|
||||||
@ -42,13 +41,12 @@ import { setProjectPoolAction } from "../../subscriptions/actions";
|
|||||||
import { JournalFilters, JournalList, MetricsTab, ProjectBudgetPanel } from "@/components/Accounting";
|
import { JournalFilters, JournalList, MetricsTab, ProjectBudgetPanel } from "@/components/Accounting";
|
||||||
import { saveProjectBudgetAction } from "../../actions";
|
import { saveProjectBudgetAction } from "../../actions";
|
||||||
// PEP-127: on its own line — the long @peppa/core import above is edited by every story.
|
// PEP-127: on its own line — the long @peppa/core import above is edited by every story.
|
||||||
import { awaitingRollout, ROLLOUT_LABEL, delayedTaskIds, taskDelayLine, pendingQuestions, listPendingAccepts, PENDING_ACCEPT_LABEL, PLATFORM_DELAY_LABEL } from "@peppa/core";
|
import { delayedTaskIds, taskDelayLine, pendingQuestions, listPendingAccepts, PENDING_ACCEPT_LABEL, PLATFORM_DELAY_LABEL } from "@peppa/core";
|
||||||
import { trashDaysLeft } from "@peppa/core";
|
import { trashDaysLeft } from "@peppa/core";
|
||||||
import { queuePositions, workLine } from "@peppa/core";
|
import { queuePositions, workLine } from "@peppa/core";
|
||||||
import { WorkLine } from "@/components/WorkLine";
|
import { WorkLine } from "@/components/WorkLine";
|
||||||
import { deleteProjectAction } from "../../actions";
|
import { deleteProjectAction } from "../../actions";
|
||||||
import { DeleteProjectControl, mayDeleteProject, RestoreProjectButton } from "@/components/ProjectDelete";
|
import { DeleteProjectControl, mayDeleteProject, RestoreProjectButton } from "@/components/ProjectDelete";
|
||||||
import { projectTitle } from "@/lib/title";
|
|
||||||
|
|
||||||
const RELEASE_STATUS: Record<Release["status"], { label: string; tone: "info" | "ok" | "warn" | "danger" | "muted" }> = {
|
const RELEASE_STATUS: Record<Release["status"], { label: string; tone: "info" | "ok" | "warn" | "danger" | "muted" }> = {
|
||||||
deploying: { label: m("выкатывается"), tone: "info" },
|
deploying: { label: m("выкатывается"), tone: "info" },
|
||||||
@ -72,14 +70,6 @@ const TABS = [
|
|||||||
{ id: "journal", label: m("Журнал") },
|
{ id: "journal", label: m("Журнал") },
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
// PEP-274: «KEY · вкладка — FORGE».
|
|
||||||
export async function generateMetadata({ params, searchParams }: { params: Promise<{ key: string }>; searchParams: Promise<{ tab?: string }> }) {
|
|
||||||
const t = await getT();
|
|
||||||
const { tab: id } = await searchParams;
|
|
||||||
const tab = TABS.find((x) => x.id === id) ?? TABS[0]!;
|
|
||||||
return projectTitle(t, (await params).key, t.text(tab.label));
|
|
||||||
}
|
|
||||||
|
|
||||||
function EnvLine({ name, r, t }: { name: string; r: Release | null | undefined; t: Translator }) {
|
function EnvLine({ name, r, t }: { name: string; r: Release | null | undefined; t: Translator }) {
|
||||||
return (
|
return (
|
||||||
<div className="flex min-w-0 flex-1 flex-col gap-0.5 rounded-md border bg-background/40 px-3 py-2">
|
<div className="flex min-w-0 flex-1 flex-col gap-0.5 rounded-md border bg-background/40 px-3 py-2">
|
||||||
@ -113,7 +103,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
|||||||
const tab = visibleTabs.find((x) => x.id === tabParam)?.id ?? "board";
|
const tab = visibleTabs.find((x) => x.id === tabParam)?.id ?? "board";
|
||||||
const p = await projectForUserByKey(user.id, key).catch(() => null);
|
const p = await projectForUserByKey(user.id, key).catch(() => null);
|
||||||
if (!p) notFound();
|
if (!p) notFound();
|
||||||
const [{ tasks }, epics, sessions, team, repo, incidentSettings, sources, incidents, releases, current, reviewer, progress, deps, directOrigins] = await Promise.all([
|
const [{ tasks }, epics, sessions, team, repo, incidentSettings, sources, incidents, releases, current, reviewer, progress, deps] = await Promise.all([
|
||||||
board(p.id),
|
board(p.id),
|
||||||
listEpics(db, p.id),
|
listEpics(db, p.id),
|
||||||
projectSessions(p.id),
|
projectSessions(p.id),
|
||||||
@ -127,7 +117,6 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
|||||||
getReviewSettings(db, p.id),
|
getReviewSettings(db, p.id),
|
||||||
epicProgress(db, p.id),
|
epicProgress(db, p.id),
|
||||||
blockersMap(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).
|
// Peppa itself has no staging: its prod candidate is the newest green main (PEP-18).
|
||||||
const prodCandidate = isPlatform(p) ? ((await platformReleaseOffers(db)) ? await platformReleaseCandidate(db, p) : null) : (current.staging?.sha ?? null);
|
const prodCandidate = isPlatform(p) ? ((await platformReleaseOffers(db)) ? await platformReleaseCandidate(db, p) : null) : (current.staging?.sha ?? null);
|
||||||
@ -168,8 +157,6 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
|||||||
const epicTitle = new Map(epics.map((e) => [e.id, e.title]));
|
const epicTitle = new Map(epics.map((e) => [e.id, e.title]));
|
||||||
const agentNames = await taskAgentNames(db, p.id);
|
const agentNames = await taskAgentNames(db, p.id);
|
||||||
const accepted = await listPendingAccepts(db);
|
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-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.
|
// PEP-209: the acceptance page — every story in review on one screen.
|
||||||
const toAccept = tasks.filter((x) => x.status === "review" && !x.archivedAt).length;
|
const toAccept = tasks.filter((x) => x.status === "review" && !x.archivedAt).length;
|
||||||
@ -202,7 +189,6 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
|||||||
blocked: x.status === "backlog" ? blockedLabel(deps.get(x.id)) : null,
|
blocked: x.status === "backlog" ? blockedLabel(deps.get(x.id)) : null,
|
||||||
agent: agentNames.get(x.id) ?? null,
|
agent: agentNames.get(x.id) ?? null,
|
||||||
accepted: accepted.has(x.id) ? t.text(PENDING_ACCEPT_LABEL) : null,
|
accepted: accepted.has(x.id) ? t.text(PENDING_ACCEPT_LABEL) : null,
|
||||||
rollout: rollout.has(x.id) ? t.text(ROLLOUT_LABEL) : null,
|
|
||||||
delayed: delayed.has(x.id) && x.status !== "done" ? t.text(delayLines.get(x.id) ?? PLATFORM_DELAY_LABEL) : null,
|
delayed: delayed.has(x.id) && x.status !== "done" ? t.text(delayLines.get(x.id) ?? PLATFORM_DELAY_LABEL) : null,
|
||||||
queued: queued.get(x.id) ?? null,
|
queued: queued.get(x.id) ?? null,
|
||||||
hold: holds.has(x.id) ? t.text(holds.get(x.id)!.text) : null,
|
hold: holds.has(x.id) ? t.text(holds.get(x.id)!.text) : null,
|
||||||
@ -218,7 +204,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
|||||||
const agentsMd = tab === "agents" ? await readAgentsMd(db, p) : null;
|
const agentsMd = tab === "agents" ? await readAgentsMd(db, p) : null;
|
||||||
const product = await projectProduct(db, p.id);
|
const product = await projectProduct(db, p.id);
|
||||||
const publish = await getPublishMode(db, p.id);
|
const publish = await getPublishMode(db, p.id);
|
||||||
const [productNeedList, productReview, deferred] = await Promise.all([productNeeds(db, p.id), lastProductReview(db, p.id), tab === "board" ? deferredFindings(db, p.id) : null]);
|
const [productNeedList, productReview] = await Promise.all([productNeeds(db, p.id), lastProductReview(db, p.id)]);
|
||||||
// The chat belongs to the project's people; a superadmin looking at someone else's project has none.
|
// The chat belongs to the project's people; a superadmin looking at someone else's project has none.
|
||||||
const canChat = (await userProjectIds(db, user.id)).includes(p.id);
|
const canChat = (await userProjectIds(db, user.id)).includes(p.id);
|
||||||
const sharedReq = await sharedRequest(db, p.id);
|
const sharedReq = await sharedRequest(db, p.id);
|
||||||
@ -371,7 +357,6 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
|||||||
projectId={p.id}
|
projectId={p.id}
|
||||||
back={back}
|
back={back}
|
||||||
isOwner={isOwner}
|
isOwner={isOwner}
|
||||||
direct={directOrigins.includes("incident")}
|
|
||||||
settings={incidentSettings}
|
settings={incidentSettings}
|
||||||
sources={sources}
|
sources={sources}
|
||||||
webhookUrl={incidentSettings ? `${bugsinkWebhookBase()}/api/hooks/bugsink/${incidentSettings.hookSecret}` : null}
|
webhookUrl={incidentSettings ? `${bugsinkWebhookBase()}/api/hooks/bugsink/${incidentSettings.hookSecret}` : null}
|
||||||
@ -710,7 +695,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
|||||||
</nav>
|
</nav>
|
||||||
)}
|
)}
|
||||||
{work && <WorkLine line={work} className="mb-2" />}
|
{work && <WorkLine line={work} className="mb-2" />}
|
||||||
<Board cards={cards} back={back} projectId={p.id} deferred={(deferred?.items ?? []).map((d) => ({ title: d.title, severity: d.severity }))} />
|
<Board cards={cards} back={back} />
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
@ -779,7 +764,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
|||||||
))}
|
))}
|
||||||
</td>
|
</td>
|
||||||
<td className="px-3 py-2 text-right whitespace-nowrap text-muted-foreground">
|
<td className="px-3 py-2 text-right whitespace-nowrap text-muted-foreground">
|
||||||
{r.deployedBy} · {r.createdAt.toLocaleString(intlLocale(t.locale), { dateStyle: "short", timeStyle: "short", timeZone: platformZone() })}
|
{r.deployedBy} · {r.createdAt.toLocaleString(intlLocale(t.locale), { dateStyle: "short", timeStyle: "short" })}
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
))}
|
))}
|
||||||
|
|||||||
@ -1,6 +1,5 @@
|
|||||||
// PEP-42: plan an epic — the planner proposes stories with dependencies; the PM edits and approves.
|
// PEP-42: plan an epic — the planner proposes stories with dependencies; the PM edits and approves.
|
||||||
import { platformZone } from "@peppa/shared/time";
|
import Link from "next/link";
|
||||||
import Link from "@/components/Link";
|
|
||||||
import { notFound } from "next/navigation";
|
import { notFound } from "next/navigation";
|
||||||
import { Sparkles } from "lucide-react";
|
import { Sparkles } from "lucide-react";
|
||||||
import { getEpic, listTasks } from "@peppa/core";
|
import { getEpic, listTasks } from "@peppa/core";
|
||||||
@ -16,15 +15,8 @@ import { db } from "@/lib/db";
|
|||||||
import { getT } from "@/lib/i18n";
|
import { getT } from "@/lib/i18n";
|
||||||
import { intlLocale } from "@peppa/shared/i18n";
|
import { intlLocale } from "@peppa/shared/i18n";
|
||||||
import { projectForUserByKey } from "@/lib/queries";
|
import { projectForUserByKey } from "@/lib/queries";
|
||||||
import { projectTitle } from "@/lib/title";
|
|
||||||
import { applyPlanAction, discardPlanAction, planEpicAction } from "../../../../board-actions";
|
import { applyPlanAction, discardPlanAction, planEpicAction } from "../../../../board-actions";
|
||||||
|
|
||||||
// PEP-274: the browser tab says which page it is.
|
|
||||||
export async function generateMetadata({ params }: { params: Promise<{ key: string }> }) {
|
|
||||||
const t = await getT();
|
|
||||||
return projectTitle(t, (await params).key, t("Эпик"));
|
|
||||||
}
|
|
||||||
|
|
||||||
export default async function PlanEpicPage({ params, searchParams }: { params: Promise<{ key: string; epic: string }>; searchParams: Promise<{ error?: string }> }) {
|
export default async function PlanEpicPage({ params, searchParams }: { params: Promise<{ key: string; epic: string }>; searchParams: Promise<{ error?: string }> }) {
|
||||||
const user = await requireUser();
|
const user = await requireUser();
|
||||||
const { key, epic: epicParam } = await params;
|
const { key, epic: epicParam } = await params;
|
||||||
@ -110,7 +102,7 @@ export default async function PlanEpicPage({ params, searchParams }: { params: P
|
|||||||
<Button size="sm" variant="ghost">{t("Удалить черновик")}</Button>
|
<Button size="sm" variant="ghost">{t("Удалить черновик")}</Button>
|
||||||
</form>
|
</form>
|
||||||
<p className="m-0 text-xs text-muted-foreground">
|
<p className="m-0 text-xs text-muted-foreground">
|
||||||
{t("Черновик от {date}, {author}.", { date: new Date(draft.createdAt).toLocaleString(intlLocale(t.locale), { dateStyle: "short", timeStyle: "short", timeZone: platformZone() }), author: draft.createdBy })}
|
{t("Черновик от {date}, {author}.", { date: new Date(draft.createdAt).toLocaleString(intlLocale(t.locale), { dateStyle: "short", timeStyle: "short" }), author: draft.createdBy })}
|
||||||
</p>
|
</p>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@ -1,5 +1,4 @@
|
|||||||
// Project page tabs «Код», «Спеки», «PR» and the epics block of «⋯ Настройки проекта» (PEP-66).
|
// Project page tabs «Код», «Спеки», «PR» and the epics block of «⋯ Настройки проекта» (PEP-66).
|
||||||
import { platformZone } from "@peppa/shared/time";
|
|
||||||
import type { Words } from "@peppa/shared/wording";
|
import type { Words } from "@peppa/shared/wording";
|
||||||
import { Archive, ExternalLink, GitBranch, GitPullRequest, Pencil } from "lucide-react";
|
import { Archive, ExternalLink, GitBranch, GitPullRequest, Pencil } from "lucide-react";
|
||||||
import type { Epic, SpecSummary } from "@peppa/core";
|
import type { Epic, SpecSummary } from "@peppa/core";
|
||||||
@ -14,7 +13,7 @@ import { Input, Textarea } from "@/components/ui/input";
|
|||||||
import { getT } from "@/lib/i18n";
|
import { getT } from "@/lib/i18n";
|
||||||
import { intlLocale, type Translator } from "@peppa/shared/i18n";
|
import { intlLocale, type Translator } from "@peppa/shared/i18n";
|
||||||
|
|
||||||
const when = (iso: string | null, t: Translator) => (iso ? new Date(iso).toLocaleString(intlLocale(t.locale), { dateStyle: "short", timeStyle: "short", timeZone: platformZone() }) : "—");
|
const when = (iso: string | null, t: Translator) => (iso ? new Date(iso).toLocaleString(intlLocale(t.locale), { dateStyle: "short", timeStyle: "short" }) : "—");
|
||||||
|
|
||||||
export async function CodeTab({ code }: { code: RepoOverview }) {
|
export async function CodeTab({ code }: { code: RepoOverview }) {
|
||||||
const t = await getT();
|
const t = await getT();
|
||||||
@ -82,12 +81,12 @@ export async function CodeTab({ code }: { code: RepoOverview }) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** PEP-30: the project memory (.peppa/memory/ of the working copy, assembled), written by agents. */
|
/** PEP-30: the project memory (.peppa/memory.md of the working copy), written by agents. */
|
||||||
export async function MemorySection({ text, chars, max, nearLimit }: { text: string; chars: number; max: number; nearLimit: boolean }) {
|
export async function MemorySection({ text, chars, max, nearLimit }: { text: string; chars: number; max: number; nearLimit: boolean }) {
|
||||||
const t = await getT();
|
const t = await getT();
|
||||||
return (
|
return (
|
||||||
<Section title={t("Память проекта")} actions={<span className={nearLimit ? "text-warn" : "text-muted-foreground"}>{t("{chars} из {max} символов", { chars, max })}</span>} className="mb-8">
|
<Section title={t("Память проекта")} actions={<span className={nearLimit ? "text-warn" : "text-muted-foreground"}>{t("{chars} из {max} символов", { chars, max })}</span>} className="mb-8">
|
||||||
<p className="m-0 text-sm text-muted-foreground">{t("Что агенты запомнили для следующих стори: команды, соглашения, грабли, решения")} (<code>.peppa/memory/</code>, MCP <code>remember</code>). {t("Раннер подкладывает её агенту при каждом запуске.")}</p>
|
<p className="m-0 text-sm text-muted-foreground">{t("Что агенты запомнили для следующих стори: команды, соглашения, грабли, решения")} (<code>.peppa/memory.md</code>, MCP <code>remember</code>). {t("Раннер подкладывает её агенту при каждом запуске.")}</p>
|
||||||
{text.trim() ? (
|
{text.trim() ? (
|
||||||
<Disclosure summary={<span className="text-sm">{nearLimit ? t("Показать память — почти предел, агент ужмёт её") : t("Показать память")}</span>}>
|
<Disclosure summary={<span className="text-sm">{nearLimit ? t("Показать память — почти предел, агент ужмёт её") : t("Показать память")}</span>}>
|
||||||
<Markdown text={text} />
|
<Markdown text={text} />
|
||||||
|
|||||||
@ -1,6 +1,6 @@
|
|||||||
import { Suspense } from "react";
|
import { Suspense } from "react";
|
||||||
import { redirect } from "next/navigation";
|
import { redirect } from "next/navigation";
|
||||||
import Link from "@/components/Link";
|
import Link from "next/link";
|
||||||
import { agentTaskSummary, claimWelcome, isSuperadmin, listUserProjects, onboardingChecklist, pendingFeedback, platformDelayCounts, progressOverview, proposedCount, reviewCounts } from "@peppa/core";
|
import { agentTaskSummary, claimWelcome, isSuperadmin, listUserProjects, onboardingChecklist, pendingFeedback, platformDelayCounts, progressOverview, proposedCount, reviewCounts } from "@peppa/core";
|
||||||
import { AdminFeedbackCard } from "@/components/Feedback";
|
import { AdminFeedbackCard } from "@/components/Feedback";
|
||||||
import { AgentTaskSummary } from "@/components/AgentTaskSummary";
|
import { AgentTaskSummary } from "@/components/AgentTaskSummary";
|
||||||
@ -16,7 +16,6 @@ import { requireUser, words } from "@/lib/auth";
|
|||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
import { getT } from "@/lib/i18n";
|
import { getT } from "@/lib/i18n";
|
||||||
import { acceptInbox, activeSessions, inbox } from "@/lib/queries";
|
import { acceptInbox, activeSessions, inbox } from "@/lib/queries";
|
||||||
import { pageTitle } from "@/lib/title";
|
|
||||||
|
|
||||||
function BlockSkeleton() {
|
function BlockSkeleton() {
|
||||||
return <div className="h-24 animate-pulse rounded-md bg-muted/40" aria-hidden />;
|
return <div className="h-24 animate-pulse rounded-md bg-muted/40" aria-hidden />;
|
||||||
@ -36,12 +35,6 @@ async function AgentsBlock({ userId, engineer }: { userId: number; engineer: boo
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// PEP-274: the browser tab says which page it is.
|
|
||||||
export async function generateMetadata() {
|
|
||||||
const t = await getT();
|
|
||||||
return pageTitle(t, t("Главная"));
|
|
||||||
}
|
|
||||||
|
|
||||||
export default async function Home({ searchParams }: { searchParams: Promise<{ error?: string }> }) {
|
export default async function Home({ searchParams }: { searchParams: Promise<{ error?: string }> }) {
|
||||||
const user = await requireUser();
|
const user = await requireUser();
|
||||||
const { error } = await searchParams;
|
const { error } = await searchParams;
|
||||||
|
|||||||
@ -1,6 +1,6 @@
|
|||||||
import { notFound } from "next/navigation";
|
import { notFound } from "next/navigation";
|
||||||
import { Megaphone, RefreshCw, Send } from "lucide-react";
|
import { Megaphone, RefreshCw, Send } from "lucide-react";
|
||||||
import { AGENT_CLIS, buildPlatformDigest, getAgentVersions, getPlatformBuild, pinnedAgentVersions, versionDrifts, getPlatformChannel, isSuperadmin, platformDigestEmpty, PLATFORM_CHANNEL_EVENT_NAMES, PLATFORM_CHANNEL_EVENTS, renderPlatformDigest } from "@peppa/core";
|
import { buildPlatformDigest, getPlatformBuild, getPlatformChannel, isSuperadmin, platformDigestEmpty, PLATFORM_CHANNEL_EVENT_NAMES, PLATFORM_CHANNEL_EVENTS, renderPlatformDigest } from "@peppa/core";
|
||||||
import { ago, Flash, PageHeader, Section } from "@/components/common";
|
import { ago, Flash, PageHeader, Section } from "@/components/common";
|
||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
@ -25,10 +25,7 @@ export default async function Platform({ searchParams }: { searchParams: Promise
|
|||||||
const t = await getT();
|
const t = await getT();
|
||||||
if (!(await isSuperadmin(db, user))) notFound();
|
if (!(await isSuperadmin(db, user))) notFound();
|
||||||
const { error, sent } = await searchParams;
|
const { error, sent } = await searchParams;
|
||||||
const [c, build, versions] = await Promise.all([getPlatformChannel(db), getPlatformBuild(db), getAgentVersions(db)]);
|
const [c, build] = await Promise.all([getPlatformChannel(db), getPlatformBuild(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) });
|
const digest = await buildPlatformDigest(db, { since: new Date(Date.now() - 24 * 3600_000) });
|
||||||
return (
|
return (
|
||||||
<Workspace>
|
<Workspace>
|
||||||
@ -102,42 +99,6 @@ export default async function Platform({ searchParams }: { searchParams: Promise
|
|||||||
</Card>
|
</Card>
|
||||||
</Section>
|
</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
|
<Section
|
||||||
title={t("Дайджест за сутки")}
|
title={t("Дайджест за сутки")}
|
||||||
actions={
|
actions={
|
||||||
|
|||||||
@ -10,7 +10,6 @@ import { requireUser, words } from "@/lib/auth";
|
|||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
import { getT } from "@/lib/i18n";
|
import { getT } from "@/lib/i18n";
|
||||||
import { createProjectAction } from "../../actions";
|
import { createProjectAction } from "../../actions";
|
||||||
import { pageTitle } from "@/lib/title";
|
|
||||||
|
|
||||||
function Choice({ name, value, checked, children }: { name: string; value: string; checked?: boolean; children: React.ReactNode }) {
|
function Choice({ name, value, checked, children }: { name: string; value: string; checked?: boolean; children: React.ReactNode }) {
|
||||||
return (
|
return (
|
||||||
@ -21,12 +20,6 @@ function Choice({ name, value, checked, children }: { name: string; value: strin
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// PEP-274: the browser tab says which page it is.
|
|
||||||
export async function generateMetadata() {
|
|
||||||
const t = await getT();
|
|
||||||
return pageTitle(t, t("Новый проект"));
|
|
||||||
}
|
|
||||||
|
|
||||||
export default async function NewProject({ searchParams }: { searchParams: Promise<{ error?: string }> }) {
|
export default async function NewProject({ searchParams }: { searchParams: Promise<{ error?: string }> }) {
|
||||||
const user = await requireUser();
|
const user = await requireUser();
|
||||||
const t = await getT();
|
const t = await getT();
|
||||||
@ -70,8 +63,8 @@ export default async function NewProject({ searchParams }: { searchParams: Promi
|
|||||||
)}
|
)}
|
||||||
<fieldset className="m-0 flex flex-col gap-2 border-0 p-0">
|
<fieldset className="m-0 flex flex-col gap-2 border-0 p-0">
|
||||||
<legend className="mb-2 text-sm font-medium">{t("Кто может посмотреть код")}</legend>
|
<legend className="mb-2 text-sm font-medium">{t("Кто может посмотреть код")}</legend>
|
||||||
<Choice name="visibility" value="private" checked>{t("Закрытый — только вы и участники проекта")}</Choice>
|
<Choice name="visibility" value="public" checked>{t("Открытый — другие пользователи фабрики тоже могут его посмотреть")}</Choice>
|
||||||
<Choice name="visibility" value="public">{t("Открытый — другие пользователи фабрики тоже могут его посмотреть")}</Choice>
|
<Choice name="visibility" value="private">{t("Закрытый — только вы и участники проекта")}</Choice>
|
||||||
</fieldset>
|
</fieldset>
|
||||||
{w.product && <input type="hidden" name="mode" value="new" />}
|
{w.product && <input type="hidden" name="mode" value="new" />}
|
||||||
{w.engineer && (
|
{w.engineer && (
|
||||||
|
|||||||
@ -1,4 +1,4 @@
|
|||||||
import Link from "@/components/Link";
|
import Link from "next/link";
|
||||||
import { Plus } from "lucide-react";
|
import { Plus } from "lucide-react";
|
||||||
import { analystLinks, isSuperadmin, listOtherProjects, listUserProjects, projectTrashDays } from "@peppa/core";
|
import { analystLinks, isSuperadmin, listOtherProjects, listUserProjects, projectTrashDays } from "@peppa/core";
|
||||||
import { ProjectList } from "@/components/cards";
|
import { ProjectList } from "@/components/cards";
|
||||||
@ -8,13 +8,6 @@ import { Workspace } from "@/components/Workspace";
|
|||||||
import { requireUser, words } from "@/lib/auth";
|
import { requireUser, words } from "@/lib/auth";
|
||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
import { getT } from "@/lib/i18n";
|
import { getT } from "@/lib/i18n";
|
||||||
import { pageTitle } from "@/lib/title";
|
|
||||||
|
|
||||||
// PEP-274: the browser tab says which page it is.
|
|
||||||
export async function generateMetadata() {
|
|
||||||
const t = await getT();
|
|
||||||
return pageTitle(t, t("Проекты"));
|
|
||||||
}
|
|
||||||
|
|
||||||
export default async function Projects({ searchParams }: { searchParams: Promise<{ error?: string }> }) {
|
export default async function Projects({ searchParams }: { searchParams: Promise<{ error?: string }> }) {
|
||||||
const user = await requireUser();
|
const user = await requireUser();
|
||||||
|
|||||||
@ -1,4 +1,4 @@
|
|||||||
import Link from "@/components/Link";
|
import Link from "next/link";
|
||||||
import { Search, SquareTerminal } from "lucide-react";
|
import { Search, SquareTerminal } from "lucide-react";
|
||||||
import { listUserProjects, runnerStories, listUserSessions, RUNNER_FILTERS, sessionSteps, type RunnerFilter, type SessionView } from "@peppa/core";
|
import { listUserProjects, runnerStories, listUserSessions, RUNNER_FILTERS, sessionSteps, type RunnerFilter, type SessionView } from "@peppa/core";
|
||||||
import { LiveRefresh } from "@/components/LiveRefresh";
|
import { LiveRefresh } from "@/components/LiveRefresh";
|
||||||
@ -14,7 +14,6 @@ import { inbox, sessionEvents } from "@/lib/queries";
|
|||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
import { getT } from "@/lib/i18n";
|
import { getT } from "@/lib/i18n";
|
||||||
import { m } from "@peppa/shared/i18n";
|
import { m } from "@peppa/shared/i18n";
|
||||||
import { pageTitle } from "@/lib/title";
|
|
||||||
|
|
||||||
const FILTERS: Array<{ key: RunnerFilter | undefined; label: string }> = [
|
const FILTERS: Array<{ key: RunnerFilter | undefined; label: string }> = [
|
||||||
{ key: undefined, label: m("все") },
|
{ key: undefined, label: m("все") },
|
||||||
@ -29,12 +28,6 @@ const matches = (s: SessionView, q: string) =>
|
|||||||
|
|
||||||
type Params = { error?: string; f?: string; q?: string; id?: string };
|
type Params = { error?: string; f?: string; q?: string; id?: string };
|
||||||
|
|
||||||
// PEP-274: the browser tab says which page it is.
|
|
||||||
export async function generateMetadata() {
|
|
||||||
const t = await getT();
|
|
||||||
return pageTitle(t, t("Работа агентов"));
|
|
||||||
}
|
|
||||||
|
|
||||||
export default async function Runners({ searchParams }: { searchParams: Promise<Params> }) {
|
export default async function Runners({ searchParams }: { searchParams: Promise<Params> }) {
|
||||||
const user = await requireUser();
|
const user = await requireUser();
|
||||||
const t = await getT();
|
const t = await getT();
|
||||||
|
|||||||
@ -1,128 +0,0 @@
|
|||||||
// 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 "@/components/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 { LazyRunnerTerminal as RunnerTerminal } from "@/components/Lazy";
|
|
||||||
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";
|
|
||||||
import { pageTitle } from "@/lib/title";
|
|
||||||
|
|
||||||
// PEP-274: the browser tab says which page it is.
|
|
||||||
export async function generateMetadata() {
|
|
||||||
const t = await getT();
|
|
||||||
return pageTitle(t, t("Сессии"));
|
|
||||||
}
|
|
||||||
|
|
||||||
export default async function 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>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user