Compare commits
No commits in common. "main" and "task/PEP-15" have entirely different histories.
main
...
task/PEP-1
26
.env.example
26
.env.example
@ -1,14 +1,10 @@
|
|||||||
# SQLite database file (default ~/.peppa/peppa.db)
|
# Postgres (infra/docker-compose.yml)
|
||||||
# PEPPA_DB=/Users/me/.peppa/peppa.db
|
DATABASE_URL=postgres://peppa:peppa@127.0.0.1:5433/peppa
|
||||||
# Old Postgres database: only the source of `peppa db migrate-to-sqlite` (PEP-36)
|
|
||||||
# DATABASE_URL=postgres://peppa:peppa@127.0.0.1:5433/peppa
|
|
||||||
|
|
||||||
# Gitea (git.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-bot/template
|
||||||
# Peppa's own repo (footer link, scripts/ci.sh --pr, scripts/peppa-release.sh)
|
|
||||||
# GITEA_PLATFORM_REPO=peppa-bot/peppa
|
|
||||||
|
|
||||||
# Where project repos are cloned and sessions run
|
# Where project repos are cloned and sessions run
|
||||||
PEPPA_WORKSPACES=~/peppa/workspaces
|
PEPPA_WORKSPACES=~/peppa/workspaces
|
||||||
@ -28,17 +24,3 @@ PEPPA_ROOT=/Users/telecom/Dev/Peppa
|
|||||||
# Gitea OAuth2 app for web login (scripts/create-oauth-app.sh)
|
# Gitea OAuth2 app for web login (scripts/create-oauth-app.sh)
|
||||||
GITEA_OAUTH_CLIENT_ID=
|
GITEA_OAUTH_CLIENT_ID=
|
||||||
GITEA_OAUTH_CLIENT_SECRET=
|
GITEA_OAUTH_CLIENT_SECRET=
|
||||||
|
|
||||||
# Вход через Google (PEP-90): OAuth-клиент из Google Cloud, redirect URI <PEPPA_WEB_URL>/auth/google/callback
|
|
||||||
# GOOGLE_CLIENT_ID=
|
|
||||||
# GOOGLE_CLIENT_SECRET=
|
|
||||||
|
|
||||||
# Распознавание речи (PEP-45/108): стори голосом в своём Telegram-боте и кнопка «Голосом» в вебе.
|
|
||||||
# Свой сервис Пеппы — infra/whisper (faster-whisper, 127.0.0.1:8178, без ключа); облако — OpenAI/Groq с ключом.
|
|
||||||
# PEPPA_TRANSCRIBE_URL=http://127.0.0.1:8178/v1
|
|
||||||
# Язык записи — язык интерфейса говорящего (kk / en, PEP-131); для русского интерфейса — этот.
|
|
||||||
# auto — язык не передаётся никому, сервис определяет сам.
|
|
||||||
# PEPPA_TRANSCRIBE_LANG=ru
|
|
||||||
# PEPPA_TRANSCRIBE_KEY=
|
|
||||||
# PEPPA_TRANSCRIBE_MODEL=whisper-1
|
|
||||||
# PEPPA_TRANSCRIBE_TIMEOUT_SEC=300
|
|
||||||
|
|||||||
5
.gitattributes
vendored
5
.gitattributes
vendored
@ -1,5 +0,0 @@
|
|||||||
# При конфликте в этих файлах git оставляет строки обеих сторон: каждый PR дописывает в них
|
|
||||||
# по строке в одно и то же место, и без этого любой мерж в main ломал перенос остальным (PEP-119).
|
|
||||||
AGENTS.md merge=union
|
|
||||||
.peppa/memory.md merge=union
|
|
||||||
docs/glossary.md merge=union
|
|
||||||
@ -1 +0,0 @@
|
|||||||
../template/.gitea/peppa-check.sh
|
|
||||||
@ -1,68 +0,0 @@
|
|||||||
# CI for Peppa itself (PEP-22): glossary check, typecheck, web build and the e2e suite on mocks. Runs on Peppa's
|
|
||||||
# act_runner (`peppa-trusted`, registered for peppa-bot's repos, PEP-57); tmux and the openspec
|
|
||||||
# CLI are installed in the job. Each check is a step of the factory's own pipeline (PEP-57):
|
|
||||||
# the commands are `checks` in .peppa/project.json, .gitea/peppa-check.sh (the template's) sets
|
|
||||||
# the `peppa/<check>` commit status and reports to Peppa, so PEP tasks get the same card, review
|
|
||||||
# gate and red-check feedback as any factory project. `scripts/ci.sh` runs the same locally.
|
|
||||||
name: peppa-ci
|
|
||||||
on:
|
|
||||||
pull_request:
|
|
||||||
push:
|
|
||||||
branches: [main]
|
|
||||||
env:
|
|
||||||
PEPPA_SHA: ${{ github.event.pull_request.head.sha || github.sha }}
|
|
||||||
PEPPA_BRANCH: ${{ github.head_ref || github.ref_name }}
|
|
||||||
PEPPA_PR: ${{ github.event.pull_request.number }}
|
|
||||||
PEPPA_CI_SECRET: ${{ secrets.PEPPA_CI_SECRET }}
|
|
||||||
GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
jobs:
|
|
||||||
ci:
|
|
||||||
# The runner has the host's docker.sock: only branches of this repository, never forks.
|
|
||||||
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository
|
|
||||||
runs-on: peppa-trusted
|
|
||||||
timeout-minutes: 45
|
|
||||||
env:
|
|
||||||
# Peppa's data is SQLite (a temp file per test file). Postgres on the host is only the source
|
|
||||||
# for the Postgres → SQLite migration test, which makes and drops its own database.
|
|
||||||
PEPPA_TEST_PG: postgres://peppa:peppa@host.docker.internal:5433
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
with:
|
|
||||||
ref: ${{ env.PEPPA_SHA }}
|
|
||||||
- uses: actions/setup-node@v4
|
|
||||||
with:
|
|
||||||
node-version: "26"
|
|
||||||
- name: tools
|
|
||||||
run: |
|
|
||||||
# PEP-271: a mirror mid-sync fails `apt-get update`; with `&&` the install was skipped silently
|
|
||||||
# and every e2e test died later on «spawn tmux ENOENT». Retry, then fail here if tmux is missing.
|
|
||||||
for i in 1 2 3; do
|
|
||||||
{ apt-get update -qq && apt-get install -y -qq tmux >/dev/null; } && break
|
|
||||||
echo "apt: attempt $i failed, retrying"; sleep $((i * 15))
|
|
||||||
done
|
|
||||||
command -v tmux >/dev/null || { echo "::error::tmux was not installed (apt mirror unavailable)"; exit 1; }
|
|
||||||
# Job-local prefix: the node toolcache is shared between jobs running at the same time
|
|
||||||
# (PR + push of one commit), and two global installs into it collide (ENOTEMPTY/EEXIST).
|
|
||||||
npm install -g --prefix "$RUNNER_TEMP/tools" pnpm@12.18.0 @fission-ai/openspec@2.0.0 >/dev/null
|
|
||||||
echo "$RUNNER_TEMP/tools/bin" >> "$GITHUB_PATH"
|
|
||||||
- id: install
|
|
||||||
name: install
|
|
||||||
run: bash .gitea/peppa-check.sh install
|
|
||||||
# PEP-124: the glossary check — a word from the «Нельзя» column of docs/glossary.md on a screen.
|
|
||||||
- name: lint
|
|
||||||
if: (success() || failure()) && steps.install.outcome == 'success'
|
|
||||||
run: bash .gitea/peppa-check.sh lint
|
|
||||||
- name: typecheck
|
|
||||||
if: (success() || failure()) && steps.install.outcome == 'success'
|
|
||||||
run: bash .gitea/peppa-check.sh typecheck
|
|
||||||
- id: build
|
|
||||||
name: build
|
|
||||||
if: (success() || failure()) && steps.install.outcome == 'success'
|
|
||||||
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
|
|
||||||
if: (success() || failure()) && steps.install.outcome == 'success'
|
|
||||||
run: bash .gitea/peppa-check.sh test
|
|
||||||
@ -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-261
|
|
||||||
|
|
||||||
## Грабли
|
|
||||||
- Тесты с агентом-моком (access-requests, bot) в песочнице молча висят по 25 с на Node 22 — нужен Node 26 из tarball и tmux из .deb в PATH/LD_LIBRARY_PATH (PEP-261).
|
|
||||||
@ -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-284
|
|
||||||
|
|
||||||
## Соглашения
|
|
||||||
- Стандарт стека в шаблоне (PEP-284): template/docs/standards/default-stack.md — побайтная копия docs/standards/default-stack.md (тест template-default-stack); правишь стандарт — копируй в template/.
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-285
|
|
||||||
|
|
||||||
## Решения
|
|
||||||
- Аудит стека (PEP-285): docs/standards/forge-stack-audit.md — основа FORGE (TS/Node 26, Next.js, SQLite, Drizzle, целые id) сохраняется как обоснованное отклонение; условия пересмотра PostgreSQL — там же. Новый слой в default-stack.md = строка и раздел в аудите (тест stack-audit-doc).
|
|
||||||
@ -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,7 +0,0 @@
|
|||||||
# Память: PEP-314
|
|
||||||
|
|
||||||
## Соглашения
|
|
||||||
- Go/PostgreSQL проектов (PEP-314): в проверках — только `source .gitea/peppa-tools.sh go postgres` шаблона (образ задания общий с платформой, не трогать); база стенда — `deploy.database` + `deploy/compose.postgres.yml`, пароль в томе базы, без `deploy.database` `peppa-deploy.sh` обязан вести себя как раньше (тест «Проект без базы — как раньше»).
|
|
||||||
|
|
||||||
## Грабли
|
|
||||||
- Агент в контейнере идёт от --user <uid> без записи в /etc/passwd: initdb и всё, что ищет пользователя, падает — нужен libnss-wrapper (LD_PRELOAD + NSS_WRAPPER_PASSWD). Файл шаблона *.go, который не код Go, ломает go vet/build у проекта — заготовка называется Dockerfile.golang (тест в stack-tools).
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-315
|
|
||||||
|
|
||||||
## Грабли
|
|
||||||
- Строка `connection_grants` остаётся после конца срока и после снятия «без дела»: читая «прошлую выдачу», проверяй `grantState(row, now) === "active"`, иначе вернёшь права, которых уже нет (PEP-315: «Дать: чтение» возвращало запись).
|
|
||||||
@ -1,5 +0,0 @@
|
|||||||
# Память: PEP-316
|
|
||||||
|
|
||||||
## Грабли
|
|
||||||
- Гонку двух процессов за базу тест в одном процессе не ловит: `node:sqlite` синхронный, два вызова идут по очереди. Нужен настоящий второй процесс — `packages/testkit/src/mock-db-writer.ts` держит блокировку записи (PEP-313 «починил» гонку тестом в одном процессе, на проде она осталась).
|
|
||||||
- Транзакция, начатая как читающая (`BEGIN`), получает «database is locked» на первой записи сразу, без ожидания `busy_timeout`. Поэтому `db.transaction` всегда `BEGIN IMMEDIATE` (PEP-316).
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-317
|
|
||||||
|
|
||||||
## Соглашения
|
|
||||||
- Список «Gitea» (PEP-317): отдаётся сразу при любом возрасте, хранится в `settings` `gitea.overview`, прогрев — `warmGiteaOverview` в instrumentation.ts; ждёт Gitea только `fresh`. В тестах — `giteaOverviewSettled()`, медленная Gitea — `MockGitea.searchDelayMs`.
|
|
||||||
@ -1,7 +0,0 @@
|
|||||||
# Память: PEP-318
|
|
||||||
|
|
||||||
## Соглашения
|
|
||||||
- «Принять всё» (PEP-318) — только очередь: `startAcceptAll` + `processAcceptQueue` (runner/accept-queue.ts; `accept.queue:<taskId>`, ход `accept.run:<projectId>`, аренда `accept.worker:<projectId>` 3 мин), веб — через `after()`, вачдог — `acceptQueueTick`. Синхронный `acceptAll` в вебе не звать. Медленный Gitea в тесте — `MockGitea.delayMs`.
|
|
||||||
|
|
||||||
## Грабли
|
|
||||||
- В песочнице без tmux тесты приёмки падают «spawn tmux ENOENT», а на Node 22 висят по 25 с: нужны оба — tmux из .deb bookworm и Node 26 (`nodejs.org/dist/index.json` → tarball в /tmp).
|
|
||||||
@ -1,7 +0,0 @@
|
|||||||
# Память: PEP-319
|
|
||||||
|
|
||||||
## Соглашения
|
|
||||||
- Состав задач в сообщении о версии (`storiesIn`, runner/platform-build.ts) — только ключ в начале заголовка коммита («PEP-318: …», «PEP-284, PEP-285: …») или названия слитого PR. Упоминание другой задачи в тексте коммита версию не «выпускает».
|
|
||||||
|
|
||||||
## Грабли
|
|
||||||
- 27.11.2026 канал дважды назвал задачи, вышедшие раньше: PEP-281 и PEP-282 (утро), PEP-127 (вечер) — их ключи стояли в тексте коммитов других задач. Сообщение из канала не отозвать.
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-320
|
|
||||||
|
|
||||||
## Грабли
|
|
||||||
- Сценарии infra/act-runner — busybox ash (в песочнице только dash): проверять тест act-runner-supervise с PATH на каталог апплетов статического busybox (busybox.net/downloads/binaries/1.35.0-x86_64-linux-musl). Новый supervise.sh действует только после `docker restart peppa-act-runner`.
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-321
|
|
||||||
|
|
||||||
## Соглашения
|
|
||||||
- Упавшее задание проверок (PEP-321): `checksQueueTick` до порога очереди через 2 мин (`EARLY_JOB_MS`) переоткрывает PR (`reopenFailedJob`, общий счётчик `reopened` с поздним путём, ≤2 на коммит, пауза 10 мин) — без `stuck`, задержки, сообщения суперадмину и агенту; `pending` до порога не трогается.
|
|
||||||
@ -1,9 +0,0 @@
|
|||||||
# Память: PEP-322
|
|
||||||
|
|
||||||
## Соглашения
|
|
||||||
- Папку, которую писал агент, удаляй через `removeSandbox` (runner/disk-cleanup.ts): обычный `rmSync` не берёт дерево с каталогами без права записи. Права возвращаются только настоящим каталогам внутри папки, по ссылкам не ходим.
|
|
||||||
|
|
||||||
## Грабли
|
|
||||||
- Go делает каталоги кэша модулей (`~/go/pkg/mod`) только для чтения. 27.11.2026, в день выхода PEP-314, папка агента первой же задачи на Go (722 МБ, 2776 таких каталогов) не убралась: уборка падала каждые 10 минут.
|
|
||||||
- Один и тот же отказ `rmSync` читается по-разному: на Linux — `EACCES`, на macOS — `ENOTEMPTY`. Ветвиться по коду ошибки нельзя.
|
|
||||||
- Проверки в CI идут от root, ему права каталогов не мешают: тест на это падает без правки только у обычного пользователя (локальный прогон).
|
|
||||||
@ -1,11 +0,0 @@
|
|||||||
# Память: PEP-324
|
|
||||||
|
|
||||||
## Грабли
|
|
||||||
- Id серверных действий Next (и Turbopack) — хэш с солью NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: без постоянного ключа каждая сборка образа ломает кнопки открытых вкладок (Bugsink #23). Ключ — в .env сервера, в сборку — секретом BuildKit next_actions_key; проверка на деле: две `next build` с одним ключом → одинаковые ключи server-reference-manifest.json.
|
|
||||||
- Next печатает ошибку, пойманную своей границей (`app/error.tsx`), тем `console.error`, который взял при старте, — обёртка `ErrorReporter` её не слышит. Граница сама поднимает такую ошибку через `reportError` (`reportCaughtError`), иначе ошибки страниц не доходят до «Ошибок из прода».
|
|
||||||
- На одной странице много полей с одним `name` (карточки вопросов — «answer», «Что поправить» — «text»): возвращать сохранённый текст по имени нельзя — он попадёт в чужую карточку. Адрес поля — его `id`, имя годится, только когда оно одно на странице.
|
|
||||||
- Секреты вводятся и в `textarea` (секрет проекта, ключ сервера): правило «не пароль» их не отсекает — отсекать по имени поля.
|
|
||||||
|
|
||||||
## Соглашения
|
|
||||||
- apps/web/lib/* для node-тестов — без импорта `next/navigation` (в ESM без exports-карты node его не находит): проверку Next передавать параметром из клиентского компонента, как `isStaleAction(err, unstable_isUnrecognizedActionError)`.
|
|
||||||
- Поведение страницы в браузере проверять на рабочей сборке настоящим браузером (подмена заголовка `next-action` даёт «такого действия нет»): тесты на моках DOM не увидели ни чужую карточку, ни пропавшие ошибки.
|
|
||||||
@ -1,15 +0,0 @@
|
|||||||
# Память: PEP-326
|
|
||||||
|
|
||||||
## Соглашения
|
|
||||||
- Сайт запускается только через свой сервер веба: `node server.ts` (`apps/web/server.ts`) — и в `infra/docker-compose.yml`, и в launchd, и в `pnpm start`. Он принимает постоянное соединение страниц `/api/ws`.
|
|
||||||
- После смены способа запуска сайта проверяй соединение, а не только страницы: `. scripts/lib/ws-check.sh; ws_answers http://127.0.0.1:3100` (0 — соединение принято). Выкатка делает это сама и откатывает версию без ответа.
|
|
||||||
|
|
||||||
## Грабли
|
|
||||||
- Голый `next start` на запрос WebSocket не отвечает и не отказывает. Браузер ждёт, пока запрос не оборвёт Cloudflare (524, около 125 секунд). Страницы и `/api/health` при этом в порядке, поэтому проверки выкатки ничего не замечали.
|
|
||||||
- С 21 по 28.11.2026 свежая вкладка около шести минут показывала «подключение…» и не обновлялась сама: три попытки по 125 секунд, потом запасной поток. Заметили по экрану «Приёмка»: «Принимается…» висело, хотя сервер принял задачу за секунду.
|
|
||||||
- Две задачи одного дня могут не встретиться: PEP-222 завёл compose с `next start`, PEP-225 через полтора часа поменял запуск сайта в launchd и `package.json`. В compose его никто не внёс.
|
|
||||||
- Тест проверки на подставном сервере прошёл бы и с неверным ключом запроса: настоящий сервер соединений отклоняет ключ не из 16 байт (так и было в первой версии `ws-check.sh`, выкатка откатывалась бы каждый раз). Проверку живого сервера тестируй настоящим `createLiveWs`.
|
|
||||||
|
|
||||||
## Решения
|
|
||||||
- Клиент не ждёт зависший запрос соединения дольше 4 секунд (`WS_OPEN_TIMEOUT_MS` в `apps/web/lib/live.ts`) и сразу идёт на запасной поток `/api/live`; WebSocket пробуется раз в минуту. Отклонённый запрос — по-прежнему три попытки.
|
|
||||||
- Проверка по внешнему адресу версию не откатывает: путь до сайта (Cloudflare, край) от версии не зависит, страницы при нём работают через запасной поток.
|
|
||||||
@ -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-окончание не клеить. Тексты агентам говорят «Пеппа» — не трогаем.
|
|
||||||
@ -1,14 +1 @@
|
|||||||
{
|
{ "slug": "peppa", "key": "PEP", "name": "Peppa", "peppaUrl": "https://peppa.telecom.quest" }
|
||||||
"slug": "peppa",
|
|
||||||
"key": "PEP",
|
|
||||||
"name": "Peppa",
|
|
||||||
"peppaUrl": "https://peppa.telecom.quest",
|
|
||||||
"checks": {
|
|
||||||
"install": "pnpm install --frozen-lockfile",
|
|
||||||
"lint": "pnpm lint",
|
|
||||||
"typecheck": "pnpm -r typecheck",
|
|
||||||
"build": "pnpm --filter @peppa/web build",
|
|
||||||
"bundle": "node scripts/bundle-check.mjs",
|
|
||||||
"test": "pnpm --filter @peppa/testkit test"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@ -5,7 +5,7 @@
|
|||||||
```bash
|
```bash
|
||||||
pnpm install
|
pnpm install
|
||||||
cp .env.example .env # GITEA_TOKEN и т.д.
|
cp .env.example .env # GITEA_TOKEN и т.д.
|
||||||
pnpm db:migrate # SQLite в ~/.peppa/peppa.db (PEPPA_DB)
|
pnpm db:up && pnpm db:migrate
|
||||||
scripts/push-template.sh # залить template/ в Gitea
|
scripts/push-template.sh # залить template/ в Gitea
|
||||||
peppa project create demo DEMO "Demo project"
|
peppa project create demo DEMO "Demo project"
|
||||||
```
|
```
|
||||||
|
|||||||
@ -1,7 +1,4 @@
|
|||||||
#!/usr/bin/env bash
|
#!/usr/bin/env bash
|
||||||
# Logical root (PEP-18): only the bin's own symlink (~/.local/bin) is followed, so a launch
|
PEPPA_ROOT="$(cd "$(dirname "$(readlink -f "$0")")/../../.." && pwd)"
|
||||||
# through ~/peppa/current keeps that path in hooks and git config instead of the release dir.
|
|
||||||
_b="$0"; [ -L "$_b" ] && { _l="$(readlink "$_b")"; if [ "${_l#/}" != "$_l" ]; then _b="$_l"; else _b="$(dirname "$_b")/$_l"; fi; }
|
|
||||||
PEPPA_ROOT="$(cd "$(dirname "$_b")/../../.." && pwd)"; unset _b _l
|
|
||||||
. "$PEPPA_ROOT/scripts/lib/load-env.sh"
|
. "$PEPPA_ROOT/scripts/lib/load-env.sh"
|
||||||
exec "${PEPPA_NODE:-node}" --import "$PEPPA_ROOT/scripts/lib/require-node.mjs" "$PEPPA_ROOT/apps/bot/src/index.ts" "$@"
|
exec "$PEPPA_ROOT/node_modules/.bin/tsx" "$PEPPA_ROOT/apps/bot/src/index.ts" "$@"
|
||||||
|
|||||||
@ -3,9 +3,9 @@
|
|||||||
"version": "0.0.0",
|
"version": "0.0.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"exports": { ".": "./src/bot.ts", "./telegram": "./src/telegram.ts", "./render": "./src/render.ts" },
|
"exports": { ".": "./src/bot.ts", "./telegram": "./src/telegram.ts" },
|
||||||
"bin": { "peppa-bot": "./bin/peppa-bot" },
|
"bin": { "peppa-bot": "./bin/peppa-bot" },
|
||||||
"scripts": { "start": "node src/index.ts", "typecheck": "tsc -p ." },
|
"scripts": { "start": "tsx src/index.ts", "typecheck": "tsc -p ." },
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@peppa/core": "workspace:*",
|
"@peppa/core": "workspace:*",
|
||||||
"@peppa/db": "workspace:*",
|
"@peppa/db": "workspace:*",
|
||||||
|
|||||||
1018
apps/bot/src/bot.ts
1018
apps/bot/src/bot.ts
File diff suppressed because it is too large
Load Diff
@ -1,68 +0,0 @@
|
|||||||
// Stories from a message to the bot (PEP-45): a draft waits for the project/epic buttons, so
|
|
||||||
// a stray message never creates a story by itself. Drafts live in `settings` for a day.
|
|
||||||
import { deleteSetting, getSetting, setSetting, type Project } from "@peppa/core";
|
|
||||||
|
|
||||||
export { splitStory, TITLE_MAX } from "@peppa/core";
|
|
||||||
import type { Db } from "@peppa/db";
|
|
||||||
|
|
||||||
export const DRAFT_TTL_MS = 24 * 3600_000;
|
|
||||||
|
|
||||||
export interface Draft {
|
|
||||||
id: number;
|
|
||||||
userId: number;
|
|
||||||
chatId: number;
|
|
||||||
text: string;
|
|
||||||
projectId: number | null;
|
|
||||||
voice: boolean;
|
|
||||||
/** PEP-153: not a story yet — a message the bot answered or asked about («Завести как задачу»). */
|
|
||||||
offer?: boolean;
|
|
||||||
/** PEP-153: the bot asked «Ответить или завести задачу?» and the person has not picked yet. */
|
|
||||||
asked?: boolean;
|
|
||||||
/** PEP-153: the answer at hand for «Ответить» (null — answer from the platform's data). */
|
|
||||||
answer?: string | null;
|
|
||||||
createdAt: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
const key = (id: number) => `bot.draft:${id}`;
|
|
||||||
|
|
||||||
export async function saveDraft(db: Db, d: Omit<Draft, "id" | "createdAt">): Promise<Draft> {
|
|
||||||
const id = ((await getSetting<number>(db, "bot.draft.seq")) ?? 0) + 1;
|
|
||||||
await setSetting(db, "bot.draft.seq", id);
|
|
||||||
const draft: Draft = { ...d, id, createdAt: Date.now() };
|
|
||||||
await setSetting(db, key(id), draft);
|
|
||||||
return draft;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The user's own, not expired draft. */
|
|
||||||
export async function loadDraft(db: Db, id: number, userId: number): Promise<Draft | null> {
|
|
||||||
const d = await getSetting<Draft>(db, key(id));
|
|
||||||
if (!d || d.userId !== userId) return null;
|
|
||||||
if (Date.now() - d.createdAt > DRAFT_TTL_MS) {
|
|
||||||
await deleteSetting(db, key(id));
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
return d;
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function updateDraft(db: Db, d: Draft): Promise<void> {
|
|
||||||
await setSetting(db, key(d.id), d);
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function dropDraft(db: Db, id: number): Promise<void> {
|
|
||||||
await deleteSetting(db, key(id));
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* "в PAY: экспорт в CSV", "PAY: …", "PAY — …", or (voice, no punctuation) "в PAY экспорт…" and
|
|
||||||
* "в проекте Pay экспорт…" (how whisper writes it down, PEP-108).
|
|
||||||
* The key counts only if it is one of the user's projects; otherwise the whole text is the story.
|
|
||||||
*/
|
|
||||||
export function parseStoryText(text: string, projects: Project[]): { project: Project | null; body: string } {
|
|
||||||
const t = text.trim();
|
|
||||||
const byKey = (k: string) => projects.find((p) => p.key.toLowerCase() === k.toLowerCase()) ?? null;
|
|
||||||
const withSep = /^(?:(?:в|во|для|in|to)\s+(?:проекте?\s+|project\s+)?)?([A-Za-z][A-Za-z0-9]{1,9})\s*[::—–-]\s*([\s\S]+)$/i.exec(t);
|
|
||||||
if (withSep && byKey(withSep[1]!)) return { project: byKey(withSep[1]!), body: withSep[2]!.trim() };
|
|
||||||
const spoken = /^(?:в|во|для|in|to)\s+(?:проекте?\s+|project\s+)?([A-Za-z][A-Za-z0-9]{1,9})[,.]?\s+([\s\S]+)$/i.exec(t);
|
|
||||||
if (spoken && byKey(spoken[1]!)) return { project: byKey(spoken[1]!), body: spoken[2]!.trim() };
|
|
||||||
return { project: null, body: t };
|
|
||||||
}
|
|
||||||
@ -1,44 +0,0 @@
|
|||||||
// PEP-143: «Сообщить о проблеме» in the bot. `/problem` opens a short window in which the next
|
|
||||||
// message (text, a photo with a caption, a voice note) becomes a report; photos sent right after
|
|
||||||
// it join the same report. A superadmin's «Не исправлять» waits for the reason the same way.
|
|
||||||
import { deleteSetting, getSetting, setSetting } from "@peppa/core";
|
|
||||||
import type { Db } from "@peppa/db";
|
|
||||||
|
|
||||||
/** How long `/problem` waits for the message. */
|
|
||||||
export const FEEDBACK_MODE_TTL_MS = 15 * 60_000;
|
|
||||||
/** How long after the report more photos still join it (an album arrives message by message). */
|
|
||||||
export const FEEDBACK_MORE_TTL_MS = 2 * 60_000;
|
|
||||||
/** How long «Не исправлять» waits for the reason. */
|
|
||||||
export const REJECT_TTL_MS = 10 * 60_000;
|
|
||||||
|
|
||||||
export interface FeedbackMode {
|
|
||||||
/** Set once the report exists: further photos are attached to it. */
|
|
||||||
feedbackId?: number;
|
|
||||||
until: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
const modeKey = (userId: number) => `bot.feedback:${userId}`;
|
|
||||||
const rejectKey = (userId: number) => `bot.feedback.reject:${userId}`;
|
|
||||||
|
|
||||||
export async function feedbackMode(db: Db, userId: number, now = Date.now()): Promise<FeedbackMode | null> {
|
|
||||||
const m = await getSetting<FeedbackMode>(db, modeKey(userId));
|
|
||||||
if (!m) return null;
|
|
||||||
if (m.until > now) return m;
|
|
||||||
await deleteSetting(db, modeKey(userId));
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
export const openFeedbackMode = (db: Db, userId: number, now = Date.now()) => setSetting(db, modeKey(userId), { until: now + FEEDBACK_MODE_TTL_MS } satisfies FeedbackMode);
|
|
||||||
export const keepFeedbackMode = (db: Db, userId: number, feedbackId: number, now = Date.now()) => setSetting(db, modeKey(userId), { feedbackId, until: now + FEEDBACK_MORE_TTL_MS } satisfies FeedbackMode);
|
|
||||||
export const closeFeedbackMode = (db: Db, userId: number) => deleteSetting(db, modeKey(userId));
|
|
||||||
|
|
||||||
/** The report a superadmin is about to decline: the next message is the reason. */
|
|
||||||
export async function pendingReject(db: Db, userId: number, now = Date.now()): Promise<number | null> {
|
|
||||||
const r = await getSetting<{ feedbackId: number; until: number }>(db, rejectKey(userId));
|
|
||||||
if (!r) return null;
|
|
||||||
if (r.until > now) return r.feedbackId;
|
|
||||||
await deleteSetting(db, rejectKey(userId));
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
export const askRejectReason = (db: Db, userId: number, feedbackId: number, now = Date.now()) => setSetting(db, rejectKey(userId), { feedbackId, until: now + REJECT_TTL_MS });
|
|
||||||
export const clearReject = (db: Db, userId: number) => deleteSetting(db, rejectKey(userId));
|
|
||||||
@ -1,8 +1,6 @@
|
|||||||
// Entry point: `peppa-bot` (launchd agent quest.telecom.peppa.bot).
|
// Entry point: `peppa-bot` (launchd agent quest.telecom.peppa.bot).
|
||||||
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 { installCrashReporting, installServiceLog } from "@peppa/core";
|
|
||||||
import { createBot } from "./bot.ts";
|
import { createBot } from "./bot.ts";
|
||||||
import { TelegramApi } from "./telegram.ts";
|
import { TelegramApi } from "./telegram.ts";
|
||||||
|
|
||||||
@ -11,15 +9,8 @@ if (!env.TELEGRAM_BOT_TOKEN) {
|
|||||||
console.error("TELEGRAM_BOT_TOKEN is not set");
|
console.error("TELEGRAM_BOT_TOKEN is not set");
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
const db = createDb(env.PEPPA_DB);
|
|
||||||
// PEP-21: the bot only enqueues runner commands; the runner service (watchdog) runs them.
|
|
||||||
setRunnerClient(true, db);
|
|
||||||
// PEP-91: a crash of the bot goes to Bugsink before launchd restarts it.
|
|
||||||
installCrashReporting(db, "bot");
|
|
||||||
// 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: createDb(env.DATABASE_URL),
|
||||||
api: new TelegramApi(env.TELEGRAM_BOT_TOKEN, process.env.TELEGRAM_API_URL),
|
api: new TelegramApi(env.TELEGRAM_BOT_TOKEN, process.env.TELEGRAM_API_URL),
|
||||||
secret: env.TELEGRAM_BOT_TOKEN,
|
secret: env.TELEGRAM_BOT_TOKEN,
|
||||||
webUrl: env.PEPPA_WEB_URL,
|
webUrl: env.PEPPA_WEB_URL,
|
||||||
|
|||||||
@ -1,104 +1,79 @@
|
|||||||
// Telegram message texts and buttons for PM questions. HTML parse mode.
|
// Telegram message texts and buttons for PM questions. HTML parse mode.
|
||||||
import { agentSignature, questionIsFreeText, questionText, questionType, splitForDisplay, stripServiceBlocks, userText, type Question, type SessionView } from "@peppa/core";
|
import type { Question, SessionView } from "@peppa/core";
|
||||||
import type { InlineButton } from "./telegram.ts";
|
import type { InlineButton } from "./telegram.ts";
|
||||||
import { asIs, m as tr } from "@peppa/shared/i18n";
|
|
||||||
|
|
||||||
export const esc = (s: string) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
export const esc = (s: string) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
||||||
const italic = (s: string) => `<i>${s}</i>`;
|
|
||||||
const clip = (s: string, n: number) => (s.length > n ? `${s.slice(0, n)}…` : s);
|
const clip = (s: string, n: number) => (s.length > n ? `${s.slice(0, n)}…` : s);
|
||||||
|
|
||||||
const KIND: Record<Question["kind"], string> = {
|
const KIND: Record<Question["kind"], string> = {
|
||||||
approval: tr("📝 Нужно одобрение плана"),
|
approval: "📝 Нужно одобрение proposal",
|
||||||
question: tr("❓ Вопрос"),
|
question: "❓ Вопрос",
|
||||||
permission: tr("🔐 Нужно разрешение"),
|
permission: "🔐 Нужно разрешение",
|
||||||
attention: tr("👀 Сообщение"),
|
attention: "👀 Сессия ждёт тебя",
|
||||||
};
|
};
|
||||||
|
|
||||||
/** PEP-198: the name the owner sees on every message of the factory. */
|
|
||||||
export const VOICE = tr("🔎 Аналитик");
|
|
||||||
|
|
||||||
export interface Rendered {
|
export interface Rendered {
|
||||||
text: string;
|
text: string;
|
||||||
buttons: InlineButton[][];
|
buttons: InlineButton[][];
|
||||||
}
|
}
|
||||||
|
|
||||||
// callback_data (≤64 bytes): "q:<questionId>:<choice>", "s:<sessionId>:<action>" (resume|stop|ask) or "i:<incidentId>:<decision>" (core/incidents.ts)
|
// callback_data (≤64 bytes): "q:<questionId>:<choice>" or "s:<sessionId>:<action>"
|
||||||
export function renderQuestion(
|
export function renderQuestion(
|
||||||
q: Question,
|
q: Question,
|
||||||
ctx: { taskKey: string | null; taskTitle: string | null; taskStatus?: string | null; session: SessionView | null; webUrl: string; /** PEP-154: the reader's view is «Инженер» — the terminal command is shown. */ engineer?: boolean; /** PEP-152: the message has technical details (kept on the site). */ details?: boolean; /** PEP-156: nickname of the agent whose own words these are. */ agent?: string | null },
|
ctx: { taskKey: string | null; taskTitle: string | null; taskStatus?: string | null; session: SessionView | null; webUrl: string },
|
||||||
): Rendered {
|
): Rendered {
|
||||||
const head = ["<b>" + esc(ctx.taskKey ?? (q.sessionId ? tr("Агент №{id}", { id: q.sessionId }) : tr("Обновления продукта"))) + "</b>", ctx.taskTitle ? `<i>${asIs(esc(clip(ctx.taskTitle, 80)))}</i>` : null]
|
const head = [`<b>${esc(ctx.taskKey ?? `Сессия ${q.sessionId ?? "?"}`)}</b>`, ctx.taskTitle ? `<i>${esc(clip(ctx.taskTitle, 80))}</i>` : null]
|
||||||
.filter(Boolean)
|
.filter(Boolean)
|
||||||
.join(" · ");
|
.join(" · ");
|
||||||
// PEP-154: no service text in the message (a permission request keeps its command, whole).
|
const body = esc(clip(q.text, 3300));
|
||||||
// PEP-152: the main text only — at most five lines; the rest and the details open on the site.
|
const lines = [head, KIND[q.kind], "", body];
|
||||||
// PEP-139: what the agent wrote itself is free text (marked) — only the factory's phrases are translated.
|
|
||||||
const free = questionIsFreeText(q);
|
|
||||||
const shown = q.kind === "permission" ? { main: q.text, more: null } : splitForDisplay(questionText({ ...q, text: userText(q.text) || q.text }));
|
|
||||||
const text = esc(clip(shown.main, 3300));
|
|
||||||
const said = free ? asIs(text) : text;
|
|
||||||
// PEP-156: «🤖 Шустрик: …» — the agent's own words; the factory's messages carry no name.
|
|
||||||
const body = `${ctx.agent ? `<b>${asIs(esc(agentSignature(ctx.agent)))}</b>: ` : ""}${said}`;
|
|
||||||
const lines = [head, q.kind === "attention" && ctx.agent ? tr("💬 Сообщение агента") : KIND[q.kind], "", body];
|
|
||||||
|
|
||||||
const buttons: InlineButton[][] = [];
|
const buttons: InlineButton[][] = [];
|
||||||
const type = questionType(q, ctx.taskStatus);
|
|
||||||
if (q.kind === "approval") {
|
if (q.kind === "approval") {
|
||||||
buttons.push([{ text: tr("✅ Одобрить"), callback_data: `q:${q.id}:approve` }]);
|
buttons.push([{ text: "✅ Одобрить", callback_data: `q:${q.id}:approve` }]);
|
||||||
lines.push("", italic(tr("Чтобы вернуть на доработку — ответьте на это сообщение комментарием.")));
|
lines.push("", "<i>Чтобы вернуть на доработку — ответь на это сообщение комментарием.</i>");
|
||||||
} else if (q.kind === "permission") {
|
} else if (q.kind === "permission") {
|
||||||
buttons.push([
|
buttons.push([
|
||||||
{ text: tr("✅ Разрешить"), callback_data: `q:${q.id}:allow` },
|
{ text: "✅ Разрешить", callback_data: `q:${q.id}:allow` },
|
||||||
{ text: tr("♾ Всегда"), callback_data: `q:${q.id}:always` },
|
{ text: "♾ Всегда", callback_data: `q:${q.id}:always` },
|
||||||
{ text: tr("⛔ Запретить"), callback_data: `q:${q.id}:deny` },
|
{ text: "⛔ Запретить", callback_data: `q:${q.id}:deny` },
|
||||||
]);
|
]);
|
||||||
} else if (type === "question") {
|
} else if (q.kind === "question") {
|
||||||
// PEP-149: a question always comes with answers to tap; the default goes first.
|
(q.options ?? []).slice(0, 6).forEach((o, i) => buttons.push([{ text: clip(o, 60), callback_data: `q:${q.id}:o${i}` }]));
|
||||||
(q.options ?? []).slice(0, 6).forEach((o, i) => buttons.push([{ text: free ? asIs(clip(o, 60)) : clip(o, 60), callback_data: `q:${q.id}:o${i}` }]));
|
lines.push("", "<i>Выбери вариант или ответь на это сообщение своим текстом.</i>");
|
||||||
if (q.kind === "attention") lines[1] = KIND.question;
|
} else if (ctx.taskStatus === "review") {
|
||||||
lines.push("", italic(tr("Выберите вариант или ответьте на это сообщение своим текстом.")));
|
lines[1] = "✅ Готово к ревью";
|
||||||
if (q.defaultOption) lines.push(italic(esc(tr("Если не ответите, агент продолжит по варианту «{option}».", { option: q.defaultOption }))));
|
buttons.push([{ text: "✅ Принять", callback_data: `q:${q.id}:accept` }]);
|
||||||
} else if (type === "done") {
|
lines.push("", "<i>Есть замечания — ответь на это сообщение, агент доработает.</i>");
|
||||||
lines[1] = tr("✅ Готово к ревью");
|
|
||||||
buttons.push([{ text: tr("✅ Принять"), callback_data: `q:${q.id}:accept` }]);
|
|
||||||
lines.push("", italic(tr("Есть замечания — ответьте на это сообщение, агент доработает.")));
|
|
||||||
} else {
|
} else {
|
||||||
// A message of the factory itself (a failure, a limit): nothing to choose — no «continue» button.
|
|
||||||
const s = ctx.session;
|
const s = ctx.session;
|
||||||
if (s && ["failed", "rate_limited", "stalled"].includes(s.status)) {
|
if (s && ["failed", "rate_limited", "stalled"].includes(s.status)) {
|
||||||
buttons.push([
|
buttons.push([
|
||||||
{ text: tr("🔁 Перезапустить"), callback_data: `s:${s.id}:resume` },
|
{ text: "🔁 Перезапустить", callback_data: `s:${s.id}:resume` },
|
||||||
{ text: tr("⏹ Остановить"), callback_data: `s:${s.id}:stop` },
|
{ text: "⏹ Остановить", callback_data: `s:${s.id}:stop` },
|
||||||
]);
|
]);
|
||||||
// PEP-186: agents stand on a limit of their subscription — ask the superadmin for one.
|
} else {
|
||||||
if (s.status === "rate_limited" && s.subscriptionId != null) buttons.push([{ text: tr("🙋 Попросить подписку у администратора"), callback_data: `s:${s.id}:ask` }]);
|
buttons.push([{ text: "▶️ Продолжай", callback_data: `q:${q.id}:cont` }]);
|
||||||
|
lines.push("", "<i>Или ответь на это сообщение — текст уйдёт в сессию.</i>");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
lines[1] = `${VOICE} · ${lines[1]}`;
|
if (ctx.session) lines.push(`<code>tmux attach -t ${esc(ctx.session.tmuxName)}</code>`);
|
||||||
if (ctx.session && ctx.engineer) lines.push(`<code>tmux attach -t ${esc(ctx.session.tmuxName)}</code>`);
|
|
||||||
const web = ctx.webUrl.replace(/\/$/, "");
|
|
||||||
if ((ctx.details || shown.more) && ctx.taskKey && /^https?:\/\//.test(web)) buttons.push([{ text: tr("Подробнее"), url: `${web}/t/${ctx.taskKey}?more=1` }]);
|
|
||||||
return { text: lines.join("\n"), buttons };
|
return { text: lines.join("\n"), buttons };
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Text after the question is closed: original + who answered what, no buttons. */
|
/** Text after the question is closed: original + who answered what, no buttons. */
|
||||||
export function renderAnswered(original: string, q: Question): string {
|
export function renderAnswered(original: string, q: Question): string {
|
||||||
const mark = q.answeredVia === "system" ? "⌛" : "✅";
|
const mark = q.answeredVia === "system" ? "⌛" : "✅";
|
||||||
const via = { telegram: tr("в Telegram"), web: tr("в вебе"), terminal: tr("в терминале"), system: "" }[q.answeredVia ?? "telegram"];
|
const via = { telegram: "в Telegram", web: "в вебе", terminal: "в терминале", system: "" }[q.answeredVia ?? "telegram"];
|
||||||
// PEP-154: service blocks are nobody's answer.
|
return `${original}\n\n${mark} ${q.answeredVia === "system" ? esc(q.answer ?? "") : `Ответ ${via}: <b>${esc(clip(q.answer ?? "", 500))}</b>`}`;
|
||||||
const answer = stripServiceBlocks(q.answer ?? "");
|
|
||||||
// A person's answer is free text; a button of a factory question (and a system answer) is a phrase.
|
|
||||||
const own = q.answeredVia !== "system" && !(q.options ?? []).includes(q.answer ?? "") ? asIs : (x: string) => x;
|
|
||||||
const said = q.answeredVia === "system" ? esc(answer) : tr("Ответ {via}: <b>{answer}</b>", { via, answer: own(esc(clip(answer, 500))) });
|
|
||||||
return `${original}\n\n${mark} ${said}`;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The answer text a button stands for. */
|
/** The answer text a button stands for. */
|
||||||
export function choiceToAnswer(q: Question, choice: string): string | null {
|
export function choiceToAnswer(q: Question, choice: string): string | null {
|
||||||
if (q.kind === "approval" && choice === "approve") return "ок"; // i18n-ignore: the answer goes to the agent
|
if (q.kind === "approval" && choice === "approve") return "ок";
|
||||||
if (q.kind === "permission" && ["allow", "always", "deny"].includes(choice)) return choice;
|
if (q.kind === "permission" && ["allow", "always", "deny"].includes(choice)) return choice;
|
||||||
// PEP-149: the «continue» button is gone — an old one on an earlier message answers nothing.
|
if (q.kind === "attention" && choice === "cont") return "Продолжай.";
|
||||||
const m = /^o(\d+)$/.exec(choice);
|
const m = /^o(\d+)$/.exec(choice);
|
||||||
if (m) return q.options?.[Number(m[1])] ?? null;
|
if (q.kind === "question" && m) return q.options?.[Number(m[1])] ?? null;
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,4 +1,3 @@
|
|||||||
import { m as tr } from "@peppa/shared/i18n";
|
|
||||||
// Minimal Telegram Bot API client. The base URL is configurable so tests can point it at
|
// Minimal Telegram Bot API client. The base URL is configurable so tests can point it at
|
||||||
// mock-telegram (packages/testkit).
|
// mock-telegram (packages/testkit).
|
||||||
|
|
||||||
@ -9,28 +8,10 @@ export interface TgUser {
|
|||||||
}
|
}
|
||||||
export interface TgMessage {
|
export interface TgMessage {
|
||||||
message_id: number;
|
message_id: number;
|
||||||
chat: { id: number; type: string; title?: string };
|
chat: { id: number; type: string };
|
||||||
from?: TgUser;
|
from?: TgUser;
|
||||||
text?: string;
|
text?: string;
|
||||||
/** PEP-62: a group became a supergroup (new chat id). */
|
|
||||||
migrate_to_chat_id?: number;
|
|
||||||
reply_to_message?: TgMessage;
|
reply_to_message?: TgMessage;
|
||||||
/** PEP-45: voice notes and audio files become stories after transcription. */
|
|
||||||
voice?: TgFileRef;
|
|
||||||
audio?: TgFileRef;
|
|
||||||
/** PEP-143: a photo comes as several sizes (the last is the largest); its text is the caption. */
|
|
||||||
photo?: TgFileRef[];
|
|
||||||
/** An image sent «as a file». */
|
|
||||||
document?: TgFileRef & { file_name?: string };
|
|
||||||
caption?: string;
|
|
||||||
/** Messages of one album share it. */
|
|
||||||
media_group_id?: string;
|
|
||||||
}
|
|
||||||
export interface TgFileRef {
|
|
||||||
file_id: string;
|
|
||||||
duration?: number;
|
|
||||||
mime_type?: string;
|
|
||||||
file_size?: number;
|
|
||||||
}
|
}
|
||||||
export interface TgCallbackQuery {
|
export interface TgCallbackQuery {
|
||||||
id: string;
|
id: string;
|
||||||
@ -49,46 +30,24 @@ export interface InlineButton {
|
|||||||
url?: string;
|
url?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
const TG_TEXT_MAX = 4096;
|
|
||||||
const TG_CLIP_NOTE_TEXT = tr("(полностью — на сайте FORGE)");
|
|
||||||
const TG_CLIP_NOTE = "\n\n… " + TG_CLIP_NOTE_TEXT;
|
|
||||||
|
|
||||||
/** PEP-180: a text that fits Telegram — cut at the last line break before the limit. */
|
|
||||||
export function clipForTelegram(text: string): string {
|
|
||||||
if (text.length <= TG_TEXT_MAX) return text;
|
|
||||||
const room = TG_TEXT_MAX - TG_CLIP_NOTE.length;
|
|
||||||
const cut = text.lastIndexOf("\n", room);
|
|
||||||
return `${text.slice(0, cut > room / 2 ? cut : room)}${TG_CLIP_NOTE}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class TelegramError extends Error {
|
export class TelegramError extends Error {
|
||||||
readonly method: string;
|
constructor(
|
||||||
readonly code: number;
|
readonly method: string,
|
||||||
readonly description: string;
|
readonly code: number,
|
||||||
readonly retryAfter?: number;
|
readonly description: string,
|
||||||
constructor(method: string, code: number, description: string, retryAfter?: number) {
|
readonly retryAfter?: number,
|
||||||
|
) {
|
||||||
super(`${method}: ${code} ${description}`);
|
super(`${method}: ${code} ${description}`);
|
||||||
this.method = method;
|
|
||||||
this.code = code;
|
|
||||||
this.description = description;
|
|
||||||
this.retryAfter = retryAfter;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export class TelegramApi {
|
export class TelegramApi {
|
||||||
private readonly token: string;
|
constructor(
|
||||||
private readonly baseUrl: string;
|
private readonly token: string,
|
||||||
constructor(token: string, baseUrl = "https://api.telegram.org") {
|
private readonly baseUrl = "https://api.telegram.org",
|
||||||
this.token = token;
|
) {}
|
||||||
this.baseUrl = baseUrl;
|
|
||||||
}
|
|
||||||
|
|
||||||
async call<T>(method: string, params: Record<string, unknown> = {}, timeoutMs = 15_000): Promise<T> {
|
async call<T>(method: string, params: Record<string, unknown> = {}, timeoutMs = 15_000): Promise<T> {
|
||||||
// PEP-180: Telegram refuses texts over 4096 characters — a long message goes shortened (cut at a
|
|
||||||
// line break, so no HTML tag is left open), with a note that the whole text is on the site.
|
|
||||||
if ((method === "sendMessage" || method === "editMessageText") && typeof params.text === "string" && params.text.length > TG_TEXT_MAX) {
|
|
||||||
params = { ...params, text: clipForTelegram(params.text) };
|
|
||||||
}
|
|
||||||
let res: Response;
|
let res: Response;
|
||||||
try {
|
try {
|
||||||
res = await fetch(`${this.baseUrl}/bot${this.token}/${method}`, {
|
res = await fetch(`${this.baseUrl}/bot${this.token}/${method}`, {
|
||||||
@ -132,34 +91,6 @@ export class TelegramApi {
|
|||||||
return this.call<boolean>("answerCallbackQuery", { callback_query_id: id, text });
|
return this.call<boolean>("answerCallbackQuery", { callback_query_id: id, text });
|
||||||
}
|
}
|
||||||
|
|
||||||
getFile(fileId: string) {
|
|
||||||
return this.call<{ file_id: string; file_path?: string; file_size?: number }>("getFile", { file_id: fileId });
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Bytes of a file from getFile (Bot API: GET /file/bot<token>/<file_path>, up to 20 MB). */
|
|
||||||
async downloadFile(filePath: string): Promise<Buffer> {
|
|
||||||
const res = await fetch(`${this.baseUrl}/file/bot${this.token}/${filePath}`, { signal: AbortSignal.timeout(60_000) });
|
|
||||||
if (!res.ok) throw new TelegramError("downloadFile", res.status, res.statusText);
|
|
||||||
return Buffer.from(await res.arrayBuffer());
|
|
||||||
}
|
|
||||||
|
|
||||||
/** PEP-143: a photo uploaded from memory (multipart/form-data, as the Bot API wants for new files). */
|
|
||||||
async sendPhoto(chatId: number, photo: { data: Uint8Array; filename: string; mime: string }, extra: Record<string, unknown> = {}): Promise<TgMessage> {
|
|
||||||
const form = new FormData();
|
|
||||||
form.set("chat_id", String(chatId));
|
|
||||||
for (const [k, v] of Object.entries(extra)) if (v != null && k !== "chat_id") form.set(k, typeof v === "string" ? v : JSON.stringify(v));
|
|
||||||
form.set("photo", new Blob([photo.data as BlobPart], { type: photo.mime }), photo.filename);
|
|
||||||
let res: Response;
|
|
||||||
try {
|
|
||||||
res = await fetch(`${this.baseUrl}/bot${this.token}/sendPhoto`, { method: "POST", body: form, signal: AbortSignal.timeout(60_000) });
|
|
||||||
} catch (e) {
|
|
||||||
throw new TelegramError("sendPhoto", 0, (e as Error).message);
|
|
||||||
}
|
|
||||||
const body = (await res.json().catch(() => ({}))) as { ok?: boolean; result?: TgMessage; description?: string; error_code?: number; parameters?: { retry_after?: number } };
|
|
||||||
if (!body.ok) throw new TelegramError("sendPhoto", body.error_code ?? res.status, body.description ?? res.statusText, body.parameters?.retry_after);
|
|
||||||
return body.result as TgMessage;
|
|
||||||
}
|
|
||||||
|
|
||||||
sendMessage(chatId: number, text: string, extra: Record<string, unknown> = {}) {
|
sendMessage(chatId: number, text: string, extra: Record<string, unknown> = {}) {
|
||||||
return this.call<TgMessage>("sendMessage", { chat_id: chatId, text, parse_mode: "HTML", ...extra });
|
return this.call<TgMessage>("sendMessage", { chat_id: chatId, text, parse_mode: "HTML", ...extra });
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,7 +0,0 @@
|
|||||||
#!/usr/bin/env bash
|
|
||||||
# Logical root (PEP-18): only the bin's own symlink (~/.local/bin) is followed, so a launch
|
|
||||||
# through ~/peppa/current keeps that path in hooks and git config instead of the release dir.
|
|
||||||
_b="$0"; [ -L "$_b" ] && { _l="$(readlink "$_b")"; if [ "${_l#/}" != "$_l" ]; then _b="$_l"; else _b="$(dirname "$_b")/$_l"; fi; }
|
|
||||||
PEPPA_ROOT="$(cd "$(dirname "$_b")/../../.." && pwd)"; unset _b _l
|
|
||||||
. "$PEPPA_ROOT/scripts/lib/load-env.sh"
|
|
||||||
exec "${PEPPA_NODE:-node}" --import "$PEPPA_ROOT/scripts/lib/require-node.mjs" "$PEPPA_ROOT/apps/observer/src/index.ts" "$@"
|
|
||||||
@ -1,14 +0,0 @@
|
|||||||
{
|
|
||||||
"name": "@peppa/observer",
|
|
||||||
"version": "0.0.0",
|
|
||||||
"private": true,
|
|
||||||
"type": "module",
|
|
||||||
"exports": { ".": "./src/observer.ts" },
|
|
||||||
"bin": { "peppa-observer": "./bin/peppa-observer" },
|
|
||||||
"scripts": { "start": "node src/index.ts", "typecheck": "tsc -p ." },
|
|
||||||
"dependencies": {
|
|
||||||
"@peppa/core": "workspace:*",
|
|
||||||
"@peppa/db": "workspace:*",
|
|
||||||
"@peppa/shared": "workspace:*"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,15 +0,0 @@
|
|||||||
// Entry point: `peppa-observer` (launchd agent quest.telecom.peppa.observer), PEP-202.
|
|
||||||
import { createDb } from "@peppa/db";
|
|
||||||
import { loadEnv } from "@peppa/shared";
|
|
||||||
import { installCrashReporting, installServiceLog, setDefaultActor } from "@peppa/core";
|
|
||||||
import { runObserver } from "./observer.ts";
|
|
||||||
|
|
||||||
const env = loadEnv();
|
|
||||||
const db = createDb(env.PEPPA_DB);
|
|
||||||
setDefaultActor({ kind: "system" });
|
|
||||||
installCrashReporting(db, "observer");
|
|
||||||
// PEP-291: the log also goes to $PEPPA_HOME/logs/observer.log — it survives a redeploy.
|
|
||||||
installServiceLog("observer");
|
|
||||||
const ac = new AbortController();
|
|
||||||
for (const sig of ["SIGINT", "SIGTERM"] as const) process.on(sig, () => (ac.abort(), setTimeout(() => process.exit(0), 200)));
|
|
||||||
await runObserver(db, { log: (m) => console.log(`${new Date().toISOString()} ${m}`) }, ac.signal);
|
|
||||||
@ -1,59 +0,0 @@
|
|||||||
// PEP-202: the `peppa-observer` service — runs the monitors of Observability. Every second it
|
|
||||||
// starts the checks that are due (they run in the background, each with its own timeout), every
|
|
||||||
// 30 s it writes its heartbeat (the watchdog watches it like the bot and the web), every hour it
|
|
||||||
// deletes checks older than the retention (7 days). Monitors are rows in observe.db: the web and
|
|
||||||
// MCP change them, the service picks the change up on its next pass — no restart.
|
|
||||||
import { beat, featureTick, observeTick, pruneObserve, seedFeatureMonitors, seedMonitors, vitalsAlertTick, type ObserveProbes } from "@peppa/core";
|
|
||||||
import { loadEnv } from "@peppa/shared";
|
|
||||||
import type { Db } from "@peppa/db";
|
|
||||||
|
|
||||||
export interface ObserverOptions {
|
|
||||||
log?: (m: string) => void;
|
|
||||||
tickMs?: number;
|
|
||||||
probes?: ObserveProbes;
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function runObserver(db: Db, o: ObserverOptions = {}, signal?: AbortSignal): Promise<void> {
|
|
||||||
const log = o.log ?? (() => {});
|
|
||||||
const made = seedMonitors();
|
|
||||||
if (made.length) log(`observer: built-in monitors created: ${made.map((m) => m.name).join(", ")}`);
|
|
||||||
// PEP-224: MCP monitors switch the «mcp» feature off; created once, when the web has a public address.
|
|
||||||
const mcp = seedFeatureMonitors(loadEnv().PEPPA_WEB_URL);
|
|
||||||
if (mcp.length) log(`observer: built-in monitors created: ${mcp.map((m) => m.name).join(", ")}`);
|
|
||||||
let featuresBusy = false;
|
|
||||||
log("observer started");
|
|
||||||
let lastBeat = 0;
|
|
||||||
let lastPrune = 0;
|
|
||||||
let lastVitals = 0;
|
|
||||||
while (!signal?.aborted) {
|
|
||||||
const now = Date.now();
|
|
||||||
if (now - lastBeat >= 30_000) {
|
|
||||||
lastBeat = now;
|
|
||||||
await beat(db, "observer").catch((e: Error) => log(`observer: heartbeat failed: ${e.message}`));
|
|
||||||
}
|
|
||||||
if (now - lastPrune >= 3_600_000) {
|
|
||||||
lastPrune = now;
|
|
||||||
try {
|
|
||||||
const n = pruneObserve();
|
|
||||||
if (n) log(`observer: ${n} old checks deleted`);
|
|
||||||
} catch (e) {
|
|
||||||
log(`observer: prune failed: ${(e as Error).message}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// PEP-217: slow pages (p75 of real users) → one warning per route and day in Bugsink.
|
|
||||||
if (now - lastVitals >= 600_000) {
|
|
||||||
lastVitals = now;
|
|
||||||
void vitalsAlertTick(db).catch((e: Error) => log(`observer: vitals failed: ${e.message}`));
|
|
||||||
}
|
|
||||||
// Not awaited: a slow check must not hold the others or the heartbeat.
|
|
||||||
void observeTick(db, { log, probes: o.probes }).catch((e: Error) => log(`observer: tick failed: ${e.message}`));
|
|
||||||
// PEP-224: features follow their monitors — announce a change (journal, channel, live pages).
|
|
||||||
if (!featuresBusy) {
|
|
||||||
featuresBusy = true;
|
|
||||||
void featureTick(db, { log })
|
|
||||||
.catch((e: Error) => log(`observer: features failed: ${e.message}`))
|
|
||||||
.finally(() => (featuresBusy = false));
|
|
||||||
}
|
|
||||||
await new Promise((r) => setTimeout(r, o.tickMs ?? 1_000));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1 +0,0 @@
|
|||||||
{ "extends": "../../tsconfig.base.json", "compilerOptions": { "allowImportingTsExtensions": true }, "include": ["src"] }
|
|
||||||
@ -1,9 +0,0 @@
|
|||||||
<!-- BEGIN:nextjs-agent-rules -->
|
|
||||||
|
|
||||||
## This is NOT the Next.js you know
|
|
||||||
|
|
||||||
This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` (resolved from this file's directory; in monorepos the `next` package may not be visible from the repo root) before writing any code. Heed deprecation notices.
|
|
||||||
|
|
||||||
This block is written and re-added by `next dev` — verify at `node_modules/next/dist/server/lib/generate-agent-files.js`. Removing it from a diff only re-creates the uncommitted change; committing it with your work keeps the tree clean.
|
|
||||||
|
|
||||||
<!-- END:nextjs-agent-rules -->
|
|
||||||
File diff suppressed because it is too large
Load Diff
@ -1,123 +0,0 @@
|
|||||||
"use server";
|
|
||||||
// Board order and archive (PEP-34), story dependencies and the epic planner (PEP-42).
|
|
||||||
// Thin wrappers over core/runner with the owner/member check, like actions.ts.
|
|
||||||
|
|
||||||
import { getEpic, PeppaError, projectForUser, resolveTask, setDependencies, type TaskRef } from "@peppa/core";
|
|
||||||
import { applyPlan, archiveTask, discardPlanDraft, parseDepsInput, planEpic, reorderBoardTask, type PlanDep, type PlannedStory } from "@peppa/runner";
|
|
||||||
import { revalidatePath } from "next/cache";
|
|
||||||
import { redirect } from "next/navigation";
|
|
||||||
import { requireUser } from "@/lib/auth";
|
|
||||||
import { db } from "@/lib/db";
|
|
||||||
import { m } from "@peppa/shared/i18n";
|
|
||||||
|
|
||||||
const str = (f: FormData, k: string) => String(f.get(k) ?? "").trim();
|
|
||||||
|
|
||||||
async function attempt(f: FormData, fn: () => Promise<string | void>): Promise<never> {
|
|
||||||
let target = str(f, "back") || "/";
|
|
||||||
try {
|
|
||||||
target = (await fn()) || target;
|
|
||||||
} catch (e) {
|
|
||||||
const msg = e instanceof PeppaError ? e.message : m("Ошибка: {message}", { message: (e as Error).message });
|
|
||||||
const [path, query] = target.split("?");
|
|
||||||
const params = new URLSearchParams(query);
|
|
||||||
params.set("error", msg.slice(0, 300));
|
|
||||||
target = `${path}?${params}`;
|
|
||||||
}
|
|
||||||
revalidatePath("/", "layout");
|
|
||||||
redirect(target);
|
|
||||||
}
|
|
||||||
|
|
||||||
async function ownedTask(userId: number, key: string): Promise<TaskRef> {
|
|
||||||
const ref = await resolveTask(db, key);
|
|
||||||
await projectForUser(db, userId, ref.project.id);
|
|
||||||
return ref;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Drag within a column (before/after another card) or the card menu (top/bottom). */
|
|
||||||
export async function reorderTaskCard(f: FormData) {
|
|
||||||
const user = await requireUser();
|
|
||||||
await attempt(f, async () => {
|
|
||||||
const ref = await ownedTask(user.id, str(f, "taskKey"));
|
|
||||||
const to = str(f, "to");
|
|
||||||
if (to === "top" || to === "bottom") await reorderBoardTask(db, ref, { to });
|
|
||||||
else if (to === "before" || to === "after") await reorderBoardTask(db, ref, { to, other: await ownedTask(user.id, str(f, "other")) });
|
|
||||||
else throw new PeppaError(m("Неизвестное место"));
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Called from the board without a page reload (drag and drop); errors are returned. */
|
|
||||||
export async function reorderTaskInline(taskKey: string, to: "top" | "bottom" | "before" | "after", other?: string): Promise<string | null> {
|
|
||||||
const user = await requireUser();
|
|
||||||
try {
|
|
||||||
const ref = await ownedTask(user.id, taskKey);
|
|
||||||
if (to === "before" || to === "after") await reorderBoardTask(db, ref, { to, other: await ownedTask(user.id, other ?? "") });
|
|
||||||
else await reorderBoardTask(db, ref, { to });
|
|
||||||
revalidatePath("/", "layout");
|
|
||||||
return null;
|
|
||||||
} catch (e) {
|
|
||||||
return e instanceof PeppaError ? e.message : (e as Error).message;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function archiveTaskAction(f: FormData) {
|
|
||||||
const user = await requireUser();
|
|
||||||
await attempt(f, async () => {
|
|
||||||
const ref = await ownedTask(user.id, str(f, "taskKey"));
|
|
||||||
await archiveTask(db, ref, str(f, "archived") !== "0");
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function setDependenciesAction(f: FormData) {
|
|
||||||
const user = await requireUser();
|
|
||||||
await attempt(f, async () => {
|
|
||||||
const ref = await ownedTask(user.id, str(f, "taskKey"));
|
|
||||||
const keys = str(f, "blockedBy").split(/[\s,;]+/).filter(Boolean);
|
|
||||||
// "remove" drops one key from the current list; otherwise the field adds to it.
|
|
||||||
const current = (f.getAll("current") as string[]).map(String);
|
|
||||||
const remove = str(f, "remove");
|
|
||||||
await setDependencies(db, ref, remove ? current.filter((k) => k !== remove) : [...current, ...keys]);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function planEpicAction(f: FormData) {
|
|
||||||
const user = await requireUser();
|
|
||||||
await attempt(f, async () => {
|
|
||||||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
|
||||||
const epic = await getEpic(db, p.id, Number(str(f, "epicId")));
|
|
||||||
const r = await planEpic(db, p, epic.id, { wishes: str(f, "wishes") || null, by: user.login });
|
|
||||||
if (!r.ok) throw new PeppaError(m("Планировщик: {error}", { error: r.error }));
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function applyPlanAction(f: FormData) {
|
|
||||||
const user = await requireUser();
|
|
||||||
await attempt(f, async () => {
|
|
||||||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
|
||||||
const epicId = Number(str(f, "epicId"));
|
|
||||||
const n = Number(str(f, "count"));
|
|
||||||
// Plan numbers in the form refer to the full draft; renumber them for the kept stories.
|
|
||||||
const kept: number[] = [];
|
|
||||||
for (let i = 1; i <= n; i++) if (f.get(`keep_${i}`)) kept.push(i);
|
|
||||||
if (!kept.length) throw new PeppaError(m("Не выбрано ни одной задачи. Отметьте хотя бы одну."));
|
|
||||||
const renum = new Map(kept.map((orig, i) => [orig, i + 1]));
|
|
||||||
const stories: PlannedStory[] = kept.map((i) => {
|
|
||||||
const deps = parseDepsInput(str(f, `deps_${i}`)).map((d): PlanDep => {
|
|
||||||
if (typeof d !== "number") return d;
|
|
||||||
if (!renum.has(d)) throw new PeppaError(m("Задача {i} зависит от №{d}, которую вы сняли. Уберите зависимость или оставьте задачу.", { i, d }));
|
|
||||||
return renum.get(d)!;
|
|
||||||
});
|
|
||||||
return { title: str(f, `title_${i}`), description: str(f, `description_${i}`), dependsOn: deps };
|
|
||||||
});
|
|
||||||
await applyPlan(db, p, epicId, stories);
|
|
||||||
return `/p/${p.key}?epic=${epicId}`;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function discardPlanAction(f: FormData) {
|
|
||||||
const user = await requireUser();
|
|
||||||
await attempt(f, async () => {
|
|
||||||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
|
||||||
const epic = await getEpic(db, p.id, Number(str(f, "epicId")));
|
|
||||||
await discardPlanDraft(db, epic.id);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@ -1,544 +0,0 @@
|
|||||||
import Link from "@/components/Link";
|
|
||||||
import { notFound } from "next/navigation";
|
|
||||||
import { ArrowLeft, Bot, Link2, MessagesSquare, Send, Unlink, User as UserIcon } from "lucide-react";
|
|
||||||
import { ANALYST_NAME, analystPending, attachmentsByMessage, chatStatusLine, isSuperadmin, chatGroupBotName, chatMessagesView, chatTtlMs, discussionMessages, discussionUnread, getSetting, listChats, markDiscussionRead, markThreadRead, masterFeed, projectThreadList, splitForDisplay, syncChats, threadTitle, THREAD_KEY, type AttachmentView, type ChatMessageView, type Question } from "@peppa/core";
|
|
||||||
import { projects, questions, tasks } from "@peppa/db";
|
|
||||||
import { formatTaskKey } from "@peppa/shared";
|
|
||||||
import { PRODUCT_NAME, stripAsIs } from "@peppa/shared/i18n";
|
|
||||||
import { eq, inArray } from "drizzle-orm";
|
|
||||||
import { LiveRefresh } from "@/components/LiveRefresh";
|
|
||||||
import { AgentBadge } from "@/components/AgentBadge";
|
|
||||||
import { ChatThreadList } from "@/components/ChatThreadList";
|
|
||||||
import { ChatScroll } from "@/components/ChatScroll";
|
|
||||||
import { ChatLiveFeed } from "@/components/ChatLiveFeed";
|
|
||||||
import { ChatSwitch } from "@/components/ChatSwitch";
|
|
||||||
import { ago, Empty, Flash, linkify, StatusBadge } from "@/components/common";
|
|
||||||
import { Hidden, QuestionCard } from "@/components/cards";
|
|
||||||
import { ProposalList } from "@/components/ProposalList";
|
|
||||||
import { Dictate } from "@/components/Dictate";
|
|
||||||
import { Attachments } from "@/components/Attachments";
|
|
||||||
import { AttachField } from "@/components/AttachField";
|
|
||||||
import { Workspace } from "@/components/Workspace";
|
|
||||||
import { Button } from "@/components/ui/button";
|
|
||||||
import { Textarea } from "@/components/ui/input";
|
|
||||||
import { currentUser, requireUser, words } from "@/lib/auth";
|
|
||||||
import { db } from "@/lib/db";
|
|
||||||
import { getT } from "@/lib/i18n";
|
|
||||||
import { cn } from "@/lib/utils";
|
|
||||||
import { cleanText, messageLink, STUCK_NOTICE } from "@/lib/chat-text";
|
|
||||||
import { chatOfferAction, linkChatAction, postChatAction, unlinkChatAction } from "../actions";
|
|
||||||
import { pageTitle } from "@/lib/title";
|
|
||||||
|
|
||||||
type Params = { error?: string; thread?: string; link?: string; q?: string; list?: string };
|
|
||||||
|
|
||||||
const CHANNEL = "channel";
|
|
||||||
/** PEP-106: `?thread=feed` — the agents' events; no `thread` — the people's discussion. */
|
|
||||||
const FEED = "feed";
|
|
||||||
|
|
||||||
// PEP-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. */
|
|
||||||
export default async function ChatPage({ params, searchParams }: { params: Promise<{ chat: string }>; searchParams: Promise<Params> }) {
|
|
||||||
const user = await requireUser();
|
|
||||||
const t = await getT();
|
|
||||||
const w = await words();
|
|
||||||
const { chat: slug } = await params;
|
|
||||||
const { error, thread: rawThread, link, q, list: rawList } = await searchParams;
|
|
||||||
// Whoever renders first moves fresh events into the chats (the bot and the watchdog do it too).
|
|
||||||
await syncChats(db).catch((e) => console.error("syncChats", e));
|
|
||||||
const list = await listChats(db, user);
|
|
||||||
const chat = list.find((c) => c.slug.toLowerCase() === slug.toLowerCase());
|
|
||||||
if (!chat) notFound();
|
|
||||||
const master = chat.kind === "master";
|
|
||||||
const thread = rawThread === CHANNEL ? null : rawThread && THREAD_KEY.test(rawThread) ? rawThread : undefined;
|
|
||||||
// A project chat opens on the discussion: people talking to each other, no agents or events.
|
|
||||||
const discussion = !master && rawThread === undefined;
|
|
||||||
const unread = await discussionUnread(db, user.id);
|
|
||||||
// PEP-155: on a phone it is either the list (`?list=1`) or the open conversation, full screen.
|
|
||||||
const showList = rawList === "1";
|
|
||||||
// PEP-207: what was unread before this look — the conversation opens there.
|
|
||||||
const unreadBefore = discussion ? (unread.get(chat.id) ?? 0) : null;
|
|
||||||
const threads = master ? null : await projectThreadList(db, user, chat, { q });
|
|
||||||
if (discussion && !showList) await markDiscussionRead(db, user.id, chat.id);
|
|
||||||
if (thread && !master && !showList) await markThreadRead(db, user.id, chat.id, thread);
|
|
||||||
// PEP-110: a person's message the analyst has not answered yet — «печатает…».
|
|
||||||
const typing = discussion && (await analystPending(db, chat.id));
|
|
||||||
|
|
||||||
const rows = threads ? [...threads.waiting, ...threads.working, ...threads.done] : [];
|
|
||||||
const messages = master
|
|
||||||
? await masterFeed(db, user, { limit: 150 })
|
|
||||||
: discussion
|
|
||||||
? await discussionMessages(db, chat.id)
|
|
||||||
: await chatMessagesView(db, chat.id, { threadKey: thread, limit: 150 });
|
|
||||||
const files = await attachmentsByMessage(db, messages.map((m) => m.id));
|
|
||||||
const current = thread ? ((await threadTitle(db, thread)) ?? thread) : null;
|
|
||||||
|
|
||||||
// Live state of the questions in view (answer buttons, «отвечено» marks).
|
|
||||||
const qIds = messages.map((m) => m.question?.id).filter((x): x is number => x != null);
|
|
||||||
const qs = qIds.length
|
|
||||||
? await db.select({ q: questions, status: tasks.status, key: projects.key, number: tasks.number }).from(questions).innerJoin(projects, eq(questions.projectId, projects.id)).leftJoin(tasks, eq(questions.taskId, tasks.id)).where(inArray(questions.id, qIds))
|
|
||||||
: [];
|
|
||||||
const qById = new Map(qs.map((r) => [r.q.id, { q: r.q as Question, taskStatus: r.status, taskKey: r.number != null ? formatTaskKey(r.key, r.number) : null }]));
|
|
||||||
|
|
||||||
const base = `/chats/${chat.slug}`;
|
|
||||||
const url = (p: { thread?: string | null; list?: boolean }) => {
|
|
||||||
const params = new URLSearchParams();
|
|
||||||
if (p.thread) params.set("thread", p.thread);
|
|
||||||
if (threads?.q) params.set("q", threads.q);
|
|
||||||
if (p.list) params.set("list", "1");
|
|
||||||
return params.size ? `${base}?${params}` : base;
|
|
||||||
};
|
|
||||||
const openRow = thread ? rows.find((r) => r.key === thread) : undefined;
|
|
||||||
const here = discussion ? url({}) : url({ thread: thread === null ? CHANNEL : (thread ?? FEED) });
|
|
||||||
// PEP-109: a group is linked through the user's own bot. The platform's bot is the superadmin's
|
|
||||||
// (users never see it) and links groups only for a superadmin without a bot of their own.
|
|
||||||
const superadmin = await isSuperadmin(db, user);
|
|
||||||
const bot = user.telegramBotUsername ?? (superadmin ? ((await getSetting<{ username: string }>(db, "telegram.bot"))?.username ?? null) : null);
|
|
||||||
const mayLink = !!user.telegramBotUsername || superadmin;
|
|
||||||
const groupBot = chat.tgTitle ? await chatGroupBotName(db, chat.id) : null;
|
|
||||||
const ttlDays = Math.round(chatTtlMs() / 86_400_000);
|
|
||||||
const taskThread = thread?.startsWith("task:");
|
|
||||||
const placeholder = master
|
|
||||||
? w.engineer ? "/status, /task KEY-N, /move KEY-N in_progress, /help" : t("Заметка для себя")
|
|
||||||
: discussion
|
|
||||||
? t("Спросите аналитика, что с проектом, или опишите идею — он поможет сформулировать {task}…", { task: w.task("acc") })
|
|
||||||
: taskThread
|
|
||||||
? t("Напишите агенту этой {task} — ответ на его вопрос или замечание, он увидит сразу", { task: w.task("gen") })
|
|
||||||
: thread
|
|
||||||
? w.engineer ? t("Заметка в тред или команда /help") : t("Заметка к этой переписке")
|
|
||||||
: w.engineer ? t("Заметка в канал или команда: /status, /task KEY-N, /move KEY-N in_progress") : t("Заметка для себя и участников проекта");
|
|
||||||
|
|
||||||
const aside = (
|
|
||||||
<div className="flex flex-col gap-5 text-sm">
|
|
||||||
<section className="flex flex-col gap-2">
|
|
||||||
<h2 className="m-0 text-[15px] font-semibold">Telegram</h2>
|
|
||||||
<p className="m-0 text-muted-foreground">
|
|
||||||
{user.telegramBotUsername ? (
|
|
||||||
<>
|
|
||||||
{t("Новые сообщения обсуждения и вопросы агентов приходят в ваш бот")} <span className="font-mono text-foreground">@{user.telegramBotUsername}</span>.
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
{t("Чтобы новые сообщения приходили в Telegram, подключите своего бота:")} <Link href="/settings#telegram">{t("Настройки → Telegram")}</Link>.
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</p>
|
|
||||||
</section>
|
|
||||||
<section className="flex flex-col gap-2">
|
|
||||||
<h2 className="m-0 text-[15px] font-semibold">{t("Telegram-группа")}</h2>
|
|
||||||
{chat.tgTitle ? (
|
|
||||||
<>
|
|
||||||
<p className="m-0 text-muted-foreground">
|
|
||||||
{t("Связан с группой")} <b className="text-foreground">{chat.tgTitle}</b>
|
|
||||||
{groupBot && (
|
|
||||||
<>
|
|
||||||
{" "}
|
|
||||||
{t("через бота")} <span className="font-mono text-foreground">@{groupBot}</span>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
.{" "}
|
|
||||||
{master
|
|
||||||
? t("Сообщения чата приходят туда, треды — цепочками ответов; ответ реплаем уходит в тред.")
|
|
||||||
: t("Сообщения чата приходят туда, треды — цепочками ответов; ответ реплаем уходит в тред (в переписке по {task} — агенту).", { task: w.task("dat") })}
|
|
||||||
</p>
|
|
||||||
<form action={unlinkChatAction}>
|
|
||||||
<Hidden fields={{ chatId: chat.id, back: here }} />
|
|
||||||
<Button size="sm" variant="outline">
|
|
||||||
<Unlink />
|
|
||||||
{t("Отвязать группу")}
|
|
||||||
</Button>
|
|
||||||
</form>
|
|
||||||
</>
|
|
||||||
) : !mayLink ? (
|
|
||||||
<p className="m-0 text-muted-foreground">
|
|
||||||
{master ? t("Мастер-чат можно связать с группой Telegram — туда пойдёт всё важное по вашим проектам.") : t("Чат проекта можно связать с группой команды в Telegram.")}{" "}
|
|
||||||
{t("Группа подключается через вашего собственного бота — сначала подключите его:")} <Link href="/settings#telegram">{t("Настройки → Telegram")}</Link>.
|
|
||||||
</p>
|
|
||||||
) : link ? (
|
|
||||||
<div className="flex flex-col gap-2 rounded-lg border bg-card p-3">
|
|
||||||
<p className="m-0">{t("Код действует 10 минут.")}</p>
|
|
||||||
{bot && (
|
|
||||||
<a href={`https://t.me/${bot}?startgroup=${encodeURIComponent(link)}`} target="_blank" rel="noreferrer" className="font-medium">
|
|
||||||
{t("Добавить @{bot} в группу →", { bot })}
|
|
||||||
</a>
|
|
||||||
)}
|
|
||||||
<p className="m-0 text-muted-foreground">{t("Или добавьте {bot} в группу сами и отправьте там:", { bot: bot ? `@${bot}` : t("бота") })}</p>
|
|
||||||
<code className="rounded bg-muted px-2 py-1 font-mono text-xs break-all select-all">/link{bot ? `@${bot}` : ""} {link}</code>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
<p className="m-0 text-muted-foreground">
|
|
||||||
{master ? t("Свяжите мастер-чат с группой — туда пойдёт всё важное по вашим проектам.") : t("Свяжите чат проекта с группой команды — по ней сразу видно, к какому проекту сообщение.")}
|
|
||||||
{bot && (
|
|
||||||
<>
|
|
||||||
{" "}
|
|
||||||
{t("В группу добавится ваш бот")} <span className="font-mono text-foreground">@{bot}</span>.
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</p>
|
|
||||||
<form action={linkChatAction}>
|
|
||||||
<Hidden fields={{ chatId: chat.id, back: here }} />
|
|
||||||
<Button size="sm" variant="outline">
|
|
||||||
<Link2 />
|
|
||||||
{t("Связать с Telegram")}
|
|
||||||
</Button>
|
|
||||||
</form>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
<p className="m-0 text-xs text-muted-foreground">{t("Отвечать из группы могут те, кто привязал Telegram в «Настройках» и имеет доступ к {target}.", { target: master ? t("мастер-чату (только вы)") : t("проекту") })}</p>
|
|
||||||
</section>
|
|
||||||
<section className="flex flex-col gap-1.5 text-xs text-muted-foreground">
|
|
||||||
<h2 className="m-0 text-[15px] font-semibold text-foreground">{t("Как это устроено")}</h2>
|
|
||||||
<p className="m-0">
|
|
||||||
{master
|
|
||||||
? t("Журнал: готовые {tasks}, вопросы, обновления продукта и сбои по всем вашим проектам. Отвечать удобнее в «Обзоре» или в чате проекта.", { tasks: w.task("pl") })
|
|
||||||
: t("Слева: чат с аналитиком — для вопросов и новых задач; «События агентов» — журнал; ниже — переписка по каждой {task} с её агентом.", { task: w.task("dat") })}
|
|
||||||
</p>
|
|
||||||
<p className="m-0">{t("Журнал событий хранится {n} дн.; ваша переписка с аналитиком не удаляется.", { n: ttlDays })}</p>
|
|
||||||
</section>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
|
|
||||||
// PEP-207: the chat with the analyst holds people and the analyst; the factory's service notices
|
|
||||||
// («задерживается на нашей стороне») are the status line on top, not messages — old ones included.
|
|
||||||
const shownMessages = discussion ? messages.filter((m) => !(m.authorKind !== "user" && STUCK_NOTICE.test(stripAsIs(m.text)))) : messages;
|
|
||||||
const status = discussion && chat.projectId ? await chatStatusLine(db, chat.projectId) : null;
|
|
||||||
// PEP-207: oldest first, newest at the bottom — the first unread message is where the reader lands.
|
|
||||||
const ordered = [...shownMessages];
|
|
||||||
const unreadCount = discussion ? (unreadBefore ?? 0) : (openRow?.unread ?? 0);
|
|
||||||
const counted = (m: ChatMessageView) => (discussion ? m.authorUserId !== user.id : m.kind === "question" || (m.kind === "user" && m.authorKind !== "user"));
|
|
||||||
let firstUnreadId: number | null = null;
|
|
||||||
if (unreadCount > 0) {
|
|
||||||
let left = unreadCount;
|
|
||||||
for (let i = ordered.length - 1; i >= 0 && left > 0; i--) {
|
|
||||||
if (!counted(ordered[i]!)) continue;
|
|
||||||
firstUnreadId = ordered[i]!.id;
|
|
||||||
left--;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const groups = groupMessages(ordered, !discussion && !master);
|
|
||||||
const taskStatus = openRow?.status ?? null;
|
|
||||||
const writable = !(master || (!discussion && thread === undefined));
|
|
||||||
// PEP-207: superadmins see the raw journal on its own page; this view is cleaned for everybody.
|
|
||||||
const gitea = (process.env.GITEA_URL ?? "").replace(/\/+$/, "");
|
|
||||||
const options = [...list.filter((c) => c.kind === "project"), ...list.filter((c) => c.kind === "master")].map((c) => {
|
|
||||||
const name = c.kind === "master" ? t("Все события") : c.title.includes(" · ") ? c.title.split(" · ").slice(1).join(" · ") : c.slug;
|
|
||||||
const marks = [(unread.get(c.id) ?? 0) > 0 && c.id !== chat.id ? t("{n} нов.", { n: unread.get(c.id) ?? 0 }) : null, c.open > 0 ? `${c.open} ?` : null].filter(Boolean).join(" · ");
|
|
||||||
return { slug: c.slug, label: marks ? `${c.kind === "master" ? name : `${c.slug} · ${name}`} (${marks})` : c.kind === "master" ? name : `${c.slug} · ${name}` };
|
|
||||||
});
|
|
||||||
|
|
||||||
const feed = ordered.length === 0 ? (
|
|
||||||
<Empty>{discussion ? t("Напишите, что хотите узнать или сделать, — аналитик ответит здесь же. Например: «Что сейчас в работе?» или «Хочу страницу с отзывами клиентов».") : master ? t("Пока тихо: здесь появятся вопросы агентов, сбои и обновления ваших проектов.") : thread === undefined ? t("Сообщений пока нет: они появятся, когда агенты возьмутся за {tasks}.", { tasks: w.task("accPl") }) : t("В этом треде пока пусто.")}</Empty>
|
|
||||||
) : (
|
|
||||||
<ol data-chat-messages className="m-0 flex list-none flex-col gap-2 p-0 pr-12 md:pr-14">
|
|
||||||
{groups.map((g) =>
|
|
||||||
g.kind === "events" ? (
|
|
||||||
<li key={`e${g.items[0]!.id}`}>
|
|
||||||
<EventLines items={g.items} firstUnreadId={firstUnreadId} taskStatus={taskStatus} agentName={openRow?.agentName ?? null} masterView={master} showThread={!discussion && thread === undefined} superadmin={superadmin} gitea={gitea} />
|
|
||||||
</li>
|
|
||||||
) : (
|
|
||||||
<li key={g.m.id} data-first-unread={g.m.id === firstUnreadId ? "" : undefined} className={cn("flex", discussion && g.m.authorUserId === user.id && g.m.kind === "user" ? "justify-end" : "justify-start")}>
|
|
||||||
<div className={cn("min-w-0", g.m.question ? "w-full" : "max-w-[85%]")}>
|
|
||||||
<MessageItem files={files.get(g.m.id)} m={g.m} q={g.m.question ? qById.get(g.m.question.id) : undefined} back={here} showThread={!discussion && thread === undefined} masterView={master} mine={discussion && g.m.authorUserId === user.id} agentName={openRow?.agentName ?? null} superadmin={superadmin} gitea={gitea} />
|
|
||||||
</div>
|
|
||||||
</li>
|
|
||||||
),
|
|
||||||
)}
|
|
||||||
</ol>
|
|
||||||
);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Workspace aside={null} wide>
|
|
||||||
{/* PEP-228: a project chat draws its new messages in place (ChatLiveFeed) and re-renders only for
|
|
||||||
what it can't draw; the master feed gathers every project and re-renders. */}
|
|
||||||
<LiveRefresh scope={master ? "chats" : `chat:${chat.id}`} indicator={false} />
|
|
||||||
<Flash error={error} />
|
|
||||||
<h1 className="sr-only">{t("Чаты")}</h1>
|
|
||||||
|
|
||||||
<div className="grid gap-4 lg:grid-cols-[300px_minmax(0,1fr)]">
|
|
||||||
<div className={cn("flex min-w-0 flex-col gap-2 lg:sticky lg:top-4 lg:max-h-[calc(100dvh-2rem)] lg:self-start lg:overflow-y-auto", !showList && "max-lg:hidden")}>
|
|
||||||
<Link href="/chats" className="text-sm text-muted-foreground hover:text-foreground">{t("Все чаты")}</Link>
|
|
||||||
<ChatSwitch current={chat.slug} options={options} />
|
|
||||||
{threads ? (
|
|
||||||
<ChatThreadList base={base} list={threads} active={thread ?? null} discussion={discussion} feed={!discussion && thread === undefined} raw={rawThread ?? null} />
|
|
||||||
) : (
|
|
||||||
<p className="m-0 rounded-lg border bg-card/50 p-3 text-sm text-muted-foreground">{t("Все события по вашим проектам — справочно. Чтобы ответить или написать, выберите проект.")}</p>
|
|
||||||
)}
|
|
||||||
{master && superadmin && (
|
|
||||||
<Link href="/journal" className="text-sm">{t("Полный журнал платформы →")}</Link>
|
|
||||||
)}
|
|
||||||
<details className="rounded-lg border bg-card/50 p-3 text-sm">
|
|
||||||
<summary className="cursor-pointer text-muted-foreground">Telegram</summary>
|
|
||||||
<div className="mt-3">{aside}</div>
|
|
||||||
</details>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<section className={cn("flex min-w-0 flex-col gap-3", showList && "max-lg:hidden")} aria-label={t("Сообщения")}>
|
|
||||||
<div className="flex flex-wrap items-center gap-2 text-sm">
|
|
||||||
<Link href={master ? "/chats" : url({ thread: rawThread, list: true })} aria-label={t("Назад")} title={t("Назад")} className="grid size-9 shrink-0 place-items-center rounded-md border bg-card text-muted-foreground hover:text-foreground hover:no-underline lg:hidden">
|
|
||||||
<ArrowLeft className="size-4" />
|
|
||||||
</Link>
|
|
||||||
<span className="min-w-0 truncate font-medium">{current ? t.text(current) : master ? t("Все события") : discussion ? t("Чат с аналитиком") : t("События агентов")}</span>
|
|
||||||
{openRow?.status && <StatusBadge status={openRow.status} />}
|
|
||||||
{openRow?.agentName && <AgentBadge name={openRow.agentName} />}
|
|
||||||
{taskThread && <TaskLink messages={messages} label={t("открыть {task} →", { task: w.task("acc") })} />}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{status && status.working.length + status.delayed.length > 0 && (
|
|
||||||
<details data-chat-status className="rounded-lg border bg-card/50 px-3 py-2 text-sm">
|
|
||||||
<summary className="cursor-pointer text-muted-foreground">
|
|
||||||
{status.delayed.length
|
|
||||||
? t("Сейчас: делается {n}, задерживаются на нашей стороне {m}", { n: status.working.length, m: status.delayed.length })
|
|
||||||
: t("Сейчас: делается {n}", { n: status.working.length })}
|
|
||||||
</summary>
|
|
||||||
<ul className="m-0 mt-2 flex list-none flex-col gap-1 p-0">
|
|
||||||
{[...status.delayed.map((r) => ({ ...r, delayed: true })), ...status.working.map((r) => ({ ...r, delayed: false }))].map((r) => (
|
|
||||||
<li key={r.key} className="flex gap-2">
|
|
||||||
<Link href={`/t/${r.key}`} className="font-mono text-xs">{r.key}</Link>
|
|
||||||
<span className="min-w-0 truncate">{r.title}</span>
|
|
||||||
{r.delayed && <span className="shrink-0 text-xs text-warn">{t("небольшая задержка на нашей стороне")}</span>}
|
|
||||||
</li>
|
|
||||||
))}
|
|
||||||
</ul>
|
|
||||||
</details>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{!writable && (
|
|
||||||
<p className="m-0 rounded-lg border border-dashed px-3 py-2 text-sm text-muted-foreground">
|
|
||||||
{t("Это журнал событий — писать сюда не нужно.")}{" "}
|
|
||||||
{master ? <Link href="/chats">{t("Выберите проект")}</Link> : <Link href={url({})}>{t("Откройте чат с аналитиком")}</Link>}{t(", чтобы задать вопрос или описать задачу.")}
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{master ? (
|
|
||||||
<>
|
|
||||||
{feed}
|
|
||||||
<div data-chat-end />
|
|
||||||
<ChatScroll lastId={ordered.at(-1)?.id ?? 0} />
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<ChatLiveFeed
|
|
||||||
chatId={chat.id}
|
|
||||||
lastId={messages.at(-1)?.id ?? 0}
|
|
||||||
view={discussion ? { kind: "discussion" } : thread === undefined ? { kind: "feed" } : thread === null ? { kind: "channel" } : { kind: "thread", key: thread }}
|
|
||||||
userId={user.id}
|
|
||||||
compact={!discussion}
|
|
||||||
showThread={!discussion && thread === undefined}
|
|
||||||
agentName={openRow?.agentName ?? null}
|
|
||||||
empty={ordered.length === 0}
|
|
||||||
typing={
|
|
||||||
typing ? (
|
|
||||||
<p className="m-0 flex items-center gap-2 text-sm text-muted-foreground" aria-live="polite">
|
|
||||||
<AgentBadge name={ANALYST_NAME} role /> <span className="animate-pulse">{t("печатает…")}</span>
|
|
||||||
</p>
|
|
||||||
) : null
|
|
||||||
}
|
|
||||||
>
|
|
||||||
{feed}
|
|
||||||
</ChatLiveFeed>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{writable && (
|
|
||||||
<form action={postChatAction} data-chat-composer className="sticky bottom-[calc(4rem+env(safe-area-inset-bottom))] z-20 -mx-1 flex flex-col gap-1 rounded-lg border bg-card p-2 shadow-md md:bottom-3">
|
|
||||||
<Hidden fields={{ chatId: chat.id, thread: thread ?? "", back: here }} />
|
|
||||||
{/* PEP-274 (F-12): on a phone the field takes the whole row (the hint is not cut), the buttons go below, each ≥ 44 px. */}
|
|
||||||
<div className="flex flex-wrap items-end gap-1.5 md:flex-nowrap">
|
|
||||||
<Textarea id="chat-text" name="text" rows={1} maxLength={60000} placeholder={placeholder} aria-label={t("Сообщение")} className="max-h-40 min-h-[4.25rem] flex-1 basis-full resize-y py-1.5 [field-sizing:content] md:min-h-9 md:basis-0" data-chat-text />
|
|
||||||
{chat.projectId && <AttachField projectId={chat.projectId} target="chat-text" className="shrink-0" touch />}
|
|
||||||
<Dictate target="chat-text" compact touch />
|
|
||||||
<Button size="sm" aria-label={t("Отправить")} title={t("Отправить")} className="ml-auto size-11 md:ml-0 md:h-9 md:w-auto" data-chat-send>
|
|
||||||
<Send />
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
<span className="px-1 text-[11px] text-muted-foreground">
|
|
||||||
{discussion ? t("Переписку видят участники проекта") : thread ? t("Сообщение увидят агент и участники проекта") : t("Заметку видят участники проекта")}
|
|
||||||
{chat.tgTitle ? " · " + t("и в Telegram «{title}»", { title: chat.tgTitle }) : ""}
|
|
||||||
</span>
|
|
||||||
</form>
|
|
||||||
)}
|
|
||||||
</section>
|
|
||||||
</div>
|
|
||||||
</Workspace>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
type Group = { kind: "events"; items: ChatMessageView[] } | { kind: "message"; m: ChatMessageView };
|
|
||||||
|
|
||||||
/** PEP-207: events in a row become one compact block; questions and people's / agents' words stay messages. */
|
|
||||||
function groupMessages(ordered: ChatMessageView[], compact: boolean): Group[] {
|
|
||||||
const out: Group[] = [];
|
|
||||||
for (const m of ordered) {
|
|
||||||
const event = compact && (m.kind === "event" || m.kind === "system") && !m.question;
|
|
||||||
const last = out.at(-1);
|
|
||||||
if (event && last?.kind === "events") last.items.push(m);
|
|
||||||
else out.push(event ? { kind: "events", items: [m] } : { kind: "message", m });
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** An event asks the person to do something («посмотрите и примите») — stale once the story moved on. */
|
|
||||||
const ASKS_TO_ACCEPT = /посмотрите результат и примите|check the result and accept/i;
|
|
||||||
|
|
||||||
async function EventLines({ items, firstUnreadId, taskStatus, agentName, masterView, showThread, superadmin, gitea }: { items: ChatMessageView[]; firstUnreadId: number | null; taskStatus: string | null; agentName: string | null; masterView: boolean; showThread: boolean; superadmin: boolean; gitea: string }) {
|
|
||||||
const t = await getT();
|
|
||||||
const line = (m: ChatMessageView, i: number) => {
|
|
||||||
const text = cleanText(t.text(m.text), superadmin, gitea);
|
|
||||||
const stale = ASKS_TO_ACCEPT.test(stripAsIs(m.text)) && (taskStatus !== "review" || items.slice(i + 1).length > 0);
|
|
||||||
const who = m.authorKind === "agent" ? (m.authorLogin ? t.role(m.authorLogin) : agentName) : null;
|
|
||||||
const link = messageLink(m.url, superadmin, gitea);
|
|
||||||
return (
|
|
||||||
<div key={m.id} data-event-line data-first-unread={m.id === firstUnreadId ? "" : undefined} className={cn("flex items-baseline gap-2 px-1 text-xs text-muted-foreground", stale && "opacity-60")}>
|
|
||||||
<span className="min-w-0 flex-1 break-words">
|
|
||||||
{who && <span className="mr-1.5 text-foreground/80">{who}:</span>}
|
|
||||||
<span className={cn(stale && "line-through")}>{text.split("\n")[0]}</span>
|
|
||||||
{stale && <span className="ml-1.5 no-underline">({t("уже не актуально")})</span>}
|
|
||||||
{link && (
|
|
||||||
<a href={link} className="ml-1.5">{t("открыть")}</a>
|
|
||||||
)}
|
|
||||||
</span>
|
|
||||||
{m.repeats > 0 && <span className="shrink-0 font-mono">×{m.repeats + 1}</span>}
|
|
||||||
<span className="shrink-0 font-mono">{ago(m.updatedAt ?? m.createdAt, t)}</span>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
if (items.length === 1) return <div className="border-y border-dashed py-1">{line(items[0]!, 0)}</div>;
|
|
||||||
return (
|
|
||||||
<details data-event-group className="border-y border-dashed py-1" open={items.some((m) => m.id === firstUnreadId)}>
|
|
||||||
<summary className="cursor-pointer px-1 text-xs text-muted-foreground">
|
|
||||||
{t("{n} событий", { n: items.length })} · {cleanText(t.text(items.at(-1)!.text), superadmin, gitea).split("\n")[0]}
|
|
||||||
</summary>
|
|
||||||
<div className="mt-1 flex flex-col gap-1">{items.map(line)}</div>
|
|
||||||
</details>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function TaskLink({ messages, label }: { messages: ChatMessageView[]; label: string }) {
|
|
||||||
const key = messages.find((m) => m.threadTitle)?.threadTitle?.split(" · ")[0];
|
|
||||||
return key ? <Link href={`/t/${key}`} className="text-xs">{label}</Link> : null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** URLs in a message become links (the analyst points at the board, a story, a stand). */
|
|
||||||
function threadHref(m: ChatMessageView) {
|
|
||||||
return m.projectKey && m.threadKey ? `/chats/${m.projectKey}?thread=${encodeURIComponent(m.threadKey)}` : m.projectKey ? `/chats/${m.projectKey}` : null;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function MessageItem({ m, q, back, showThread, masterView, mine = false, files, agentName, superadmin, gitea }: { files?: AttachmentView[]; m: ChatMessageView; q?: { q: Question; taskStatus: string | null; taskKey: string | null }; back: string; showThread: boolean; masterView: boolean; mine?: boolean; agentName: string | null; superadmin: boolean; gitea: string }) {
|
|
||||||
const t = await getT();
|
|
||||||
const where = (showThread || masterView) && (m.threadTitle || (masterView && m.projectKey));
|
|
||||||
// An event is the factory's doing even when a person's press caused it (the event's actor).
|
|
||||||
const person = m.authorKind === "user" && m.kind === "user";
|
|
||||||
const agentLabel = m.authorKind === "agent" ? (m.authorLogin ? t.role(m.authorLogin) : agentName) : null;
|
|
||||||
const link = messageLink(m.url, superadmin, gitea);
|
|
||||||
const href = threadHref(m);
|
|
||||||
const label = [masterView && m.projectKey ? m.projectKey : null, m.threadTitle ? t.text(m.threadTitle) : null].filter(Boolean).join(" · ");
|
|
||||||
const head = (
|
|
||||||
<div className="flex flex-wrap items-center gap-x-2 gap-y-0.5 text-xs text-muted-foreground">
|
|
||||||
{/* PEP-207: who speaks — a person by login, an agent by its name and icon; events always come from the factory. */}
|
|
||||||
{person ? <UserIcon className="size-3.5" /> : agentLabel ? null : m.authorKind === "agent" ? <Bot className="size-3.5" /> : <MessagesSquare className="size-3.5" />}
|
|
||||||
{agentLabel ? (
|
|
||||||
<AgentBadge name={agentLabel} className="text-foreground" />
|
|
||||||
) : (
|
|
||||||
<span className="font-medium text-foreground">{person ? (mine ? t("вы") : (m.authorLogin ?? "?")) : m.authorKind === "agent" ? t("агент") : PRODUCT_NAME}</span>
|
|
||||||
)}
|
|
||||||
{m.via === "telegram" && <span title={t("из Telegram")}>· Telegram</span>}
|
|
||||||
{where && href && (
|
|
||||||
<Link href={href} className="max-w-full truncate">
|
|
||||||
🧵 {label}
|
|
||||||
</Link>
|
|
||||||
)}
|
|
||||||
{/* PEP-151: the same event in a row is one line with a counter and the time of the last one. */}
|
|
||||||
{!q && m.repeats > 0 && <span className="rounded-full border px-1.5 font-mono tabular-nums" title={t("Повторов: {n}", { n: m.repeats })}>×{m.repeats + 1}</span>}
|
|
||||||
<span className="ml-auto font-mono">{q ? ago(m.createdAt, t) : ago(m.updatedAt ?? m.createdAt, t)}</span>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
if (q) {
|
|
||||||
return (
|
|
||||||
<div className="flex flex-col gap-1">
|
|
||||||
{head}
|
|
||||||
<QuestionCard q={q.q} taskKey={q.taskKey} taskStatus={q.taskStatus} back={back} compact clean={!superadmin} />
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
// PEP-152: a message of an agent or of the factory takes at most five lines; the rest and the
|
|
||||||
// technical details open under «Подробнее». People's messages are shown whole.
|
|
||||||
// PEP-139: free text inside is marked — `t.text` translates only the factory's phrases around it.
|
|
||||||
const shown = m.kind === "user" ? { main: m.authorKind === "agent" ? cleanText(t.role(m.text), superadmin, gitea) : m.text, more: null } : splitForDisplay(cleanText(t.text(m.text), superadmin, gitea), m.details ? t.text(m.details) : null);
|
|
||||||
return (
|
|
||||||
<article className={cn("flex flex-col gap-1 rounded-lg border bg-card px-3 py-2", mine && "border-primary/30 bg-primary/10", m.kind === "system" && "border-dashed bg-transparent")}>
|
|
||||||
{head}
|
|
||||||
<p data-message-main className="m-0 text-sm break-words whitespace-pre-wrap">{linkify(shown.main)}</p>
|
|
||||||
{shown.more && (
|
|
||||||
<details data-message-details className="text-xs text-muted-foreground">
|
|
||||||
<summary className="cursor-pointer">{t("Подробнее")}</summary>
|
|
||||||
<p className="m-0 mt-1 max-h-72 overflow-auto break-words whitespace-pre-wrap">{linkify(shown.more)}</p>
|
|
||||||
</details>
|
|
||||||
)}
|
|
||||||
<Attachments files={files} />
|
|
||||||
{link && (
|
|
||||||
<a href={link} target={link.startsWith("/") ? undefined : "_blank"} rel="noreferrer" className="truncate text-xs">
|
|
||||||
{link.startsWith("/") ? t("Открыть") : link}
|
|
||||||
</a>
|
|
||||||
)}
|
|
||||||
{/* PEP-153: a question is answered, not filed — the task is one press away. */}
|
|
||||||
{m.offer?.kind === "proposals" && <ProposalList items={m.offer.items ?? []} back={back} />}
|
|
||||||
{m.offer && m.offer.kind !== "proposals" && (
|
|
||||||
<form action={chatOfferAction} className="mt-1 flex flex-wrap gap-2">
|
|
||||||
<Hidden fields={{ messageId: m.id, back }} />
|
|
||||||
{m.offer.kind === "task" && (
|
|
||||||
<Button size="sm" variant="outline" name="choice" value="task">
|
|
||||||
{t("📝 Завести как задачу")}
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
{m.offer.kind === "choice" && (
|
|
||||||
<>
|
|
||||||
<Button size="sm" variant="outline" name="choice" value="answer">
|
|
||||||
{t("💬 Ответить")}
|
|
||||||
</Button>
|
|
||||||
<Button size="sm" variant="outline" name="choice" value="task">
|
|
||||||
{t("📝 Завести задачу")}
|
|
||||||
</Button>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
{/* PEP-198: the analyst's suggestions are filed only by this press. */}
|
|
||||||
{m.offer.kind === "stories" && (
|
|
||||||
<div data-suggested-stories className="flex w-full flex-col gap-2">
|
|
||||||
{(m.offer.stories ?? []).map((s, i) => (
|
|
||||||
<div key={i} className="flex flex-col gap-1 rounded-md border bg-card p-2 text-sm">
|
|
||||||
<span className="font-medium break-words">{s.title}</span>
|
|
||||||
{s.description && <span className="line-clamp-4 text-xs break-words whitespace-pre-wrap text-muted-foreground">{s.description}</span>}
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
<div className="flex flex-wrap gap-2">
|
|
||||||
<Button size="sm" name="choice" value="stories" className="min-h-11">
|
|
||||||
{t("Завести задачи")}
|
|
||||||
</Button>
|
|
||||||
<Button size="sm" variant="outline" name="choice" value="cancel" className="min-h-11">
|
|
||||||
{t("Не надо")}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{m.offer.kind === "draft" && (
|
|
||||||
<>
|
|
||||||
<Button size="sm" name="choice" value="create">
|
|
||||||
{t("✅ Создать")}
|
|
||||||
</Button>
|
|
||||||
<Button size="sm" variant="outline" name="choice" value="cancel">
|
|
||||||
{t("✖️ Отмена")}
|
|
||||||
</Button>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</form>
|
|
||||||
)}
|
|
||||||
</article>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@ -1,79 +0,0 @@
|
|||||||
"use server";
|
|
||||||
// «Чаты» (PEP-62): a message into a chat/thread, Telegram group link/unlink. Access — chatForUser.
|
|
||||||
|
|
||||||
import { parseAttachmentIds, chatForUser, createChatLinkCode, isSuperadmin, markDiscussionRead, markThreadRead, PeppaError, THREAD_KEY, unlinkChat } from "@peppa/core";
|
|
||||||
import { postToChat, resolveChatOffer, type ChatOfferChoice } from "@peppa/runner";
|
|
||||||
import { loadEnv } from "@peppa/shared";
|
|
||||||
import { m } from "@peppa/shared/i18n";
|
|
||||||
import { revalidatePath } from "next/cache";
|
|
||||||
import { redirect } from "next/navigation";
|
|
||||||
import { asWebActor, requireUser } from "@/lib/auth";
|
|
||||||
import { db } from "@/lib/db";
|
|
||||||
|
|
||||||
const str = (f: FormData, k: string) => String(f.get(k) ?? "").trim();
|
|
||||||
|
|
||||||
/** Runs an action; errors come back as ?error=… (redirect stays outside try). */
|
|
||||||
async function attempt(f: FormData, fn: () => Promise<string | void>): Promise<never> {
|
|
||||||
let target = str(f, "back") || "/chats";
|
|
||||||
try {
|
|
||||||
target = (await fn()) || target;
|
|
||||||
} catch (e) {
|
|
||||||
const msg = e instanceof PeppaError ? e.message : m("Ошибка: {message}", { message: (e as Error).message });
|
|
||||||
const [path, query] = target.split("?");
|
|
||||||
const params = new URLSearchParams(query);
|
|
||||||
params.set("error", msg.slice(0, 300));
|
|
||||||
target = `${path}?${params}`;
|
|
||||||
}
|
|
||||||
revalidatePath("/chats", "layout");
|
|
||||||
redirect(target);
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function postChatAction(f: FormData) {
|
|
||||||
const user = asWebActor(await requireUser());
|
|
||||||
await attempt(f, async () => {
|
|
||||||
const thread = str(f, "thread");
|
|
||||||
await postToChat(db, user, { chatId: Number(str(f, "chatId")), threadKey: thread || null, text: String(f.get("text") ?? ""), via: "web", attachmentIds: parseAttachmentIds(f.getAll("attachment")) });
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* PEP-228: messages drawn in place on an open chat page are read — the discussion (thread null)
|
|
||||||
* or one thread. No redirect: the page stays as it is.
|
|
||||||
*/
|
|
||||||
export async function markChatReadAction(chatId: number, thread: string | null): Promise<void> {
|
|
||||||
const user = await requireUser();
|
|
||||||
const chat = await chatForUser(db, user, Number(chatId)).catch(() => null);
|
|
||||||
if (!chat || chat.kind !== "project") return;
|
|
||||||
if (thread == null) await markDiscussionRead(db, user.id, chat.id);
|
|
||||||
else if (typeof thread === "string" && THREAD_KEY.test(thread)) await markThreadRead(db, user.id, chat.id, thread);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** PEP-153: a button under a chat message — «Завести как задачу», «Ответить», «Создать», «Отмена». */
|
|
||||||
export async function chatOfferAction(f: FormData) {
|
|
||||||
const user = asWebActor(await requireUser());
|
|
||||||
await attempt(f, async () => {
|
|
||||||
const choice = str(f, "choice");
|
|
||||||
if (!["task", "answer", "create", "cancel", "stories"].includes(choice)) throw new PeppaError(m("Эта кнопка уже не работает. Напишите сообщение ещё раз."));
|
|
||||||
await resolveChatOffer(db, user, Number(str(f, "messageId")), choice as ChatOfferChoice);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/** A one-time code (10 min) for `/link <код>` in a group, or the startgroup link of the user's bot that sends it. */
|
|
||||||
export async function linkChatAction(f: FormData) {
|
|
||||||
const user = asWebActor(await requireUser());
|
|
||||||
await attempt(f, async () => {
|
|
||||||
const token = loadEnv().TELEGRAM_BOT_TOKEN;
|
|
||||||
if (!token) throw new PeppaError(m("Telegram пока не настроен. Напишите в поддержку FORGE."));
|
|
||||||
const chat = await chatForUser(db, user, Number(str(f, "chatId")));
|
|
||||||
// PEP-109: the group is linked through the user's own bot; the platform's bot is the
|
|
||||||
// superadmin's (PEP-106) and serves only a superadmin who has no bot of their own.
|
|
||||||
const code = await createChatLinkCode(db, token, user, chat.id, { sharedBot: await isSuperadmin(db, user) });
|
|
||||||
const back = str(f, "back") || "/chats";
|
|
||||||
return `${back}${back.includes("?") ? "&" : "?"}link=${encodeURIComponent(code)}`;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function unlinkChatAction(f: FormData) {
|
|
||||||
const user = asWebActor(await requireUser());
|
|
||||||
await attempt(f, () => unlinkChat(db, user, Number(str(f, "chatId"))));
|
|
||||||
}
|
|
||||||
@ -1,86 +0,0 @@
|
|||||||
import Link from "@/components/Link";
|
|
||||||
import { ArrowRight, MessagesSquare } from "lucide-react";
|
|
||||||
import { chatOverview, isRoleName, syncChats } from "@peppa/core";
|
|
||||||
import { LiveRefresh } from "@/components/LiveRefresh";
|
|
||||||
import { AgentBadge } from "@/components/AgentBadge";
|
|
||||||
import { QuestionCard } from "@/components/cards";
|
|
||||||
import { ago, Empty, Flash, PageHeader, Section } from "@/components/common";
|
|
||||||
import { Workspace } from "@/components/Workspace";
|
|
||||||
import { requireUser } from "@/lib/auth";
|
|
||||||
import { db } from "@/lib/db";
|
|
||||||
import { inbox } from "@/lib/queries";
|
|
||||||
import { getT } from "@/lib/i18n";
|
|
||||||
|
|
||||||
export async function generateMetadata() {
|
|
||||||
const t = await getT();
|
|
||||||
return { title: t("Чаты — FORGE") };
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* «Чаты» (PEP-117): the overview a product manager lands on — what waits for their answer and
|
|
||||||
* where to write to the analyst of each project. The raw feed of events lives at /chats/master.
|
|
||||||
*/
|
|
||||||
export default async function Chats({ searchParams }: { searchParams: Promise<{ error?: string }> }) {
|
|
||||||
const user = await requireUser();
|
|
||||||
const t = await getT();
|
|
||||||
const { error } = await searchParams;
|
|
||||||
await syncChats(db).catch((e) => console.error("syncChats", e));
|
|
||||||
const [cards, waiting] = await Promise.all([chatOverview(db, user), inbox(user.id)]);
|
|
||||||
return (
|
|
||||||
<Workspace>
|
|
||||||
<LiveRefresh scope="chats" />
|
|
||||||
<Flash error={error} />
|
|
||||||
<PageHeader title={t("Чаты")}>{t("Здесь вы разговариваете с фабрикой: отвечаете агентам и пишете аналитику своего проекта — что узнать или что сделать.")}</PageHeader>
|
|
||||||
|
|
||||||
<Section title={t("Ждут вашего ответа")} count={waiting.length}>
|
|
||||||
{waiting.length === 0 ? (
|
|
||||||
<Empty>{t("Сейчас от вас ничего не нужно — агенты работают сами.")}</Empty>
|
|
||||||
) : (
|
|
||||||
waiting.map((q) => <QuestionCard key={q.id} q={q} taskKey={q.taskKey} taskStatus={q.taskStatus} back="/chats" />)
|
|
||||||
)}
|
|
||||||
</Section>
|
|
||||||
|
|
||||||
<Section title={t("Ваши проекты")} count={cards.length}>
|
|
||||||
{cards.length === 0 ? (
|
|
||||||
<Empty>
|
|
||||||
{t("Проектов пока нет.")} <Link href="/projects/new">{t("Создайте проект")}</Link> {t("— и у него появится чат с аналитиком.")}
|
|
||||||
</Empty>
|
|
||||||
) : (
|
|
||||||
<ul className="m-0 grid list-none gap-3 p-0 md:grid-cols-2">
|
|
||||||
{cards.map((c) => (
|
|
||||||
<li key={c.chatId}>
|
|
||||||
<Link href={`/chats/${c.key}`} className="flex h-full flex-col gap-2 rounded-xl border bg-card p-4 text-foreground hover:border-primary/60 hover:no-underline">
|
|
||||||
<span className="flex items-center gap-2">
|
|
||||||
<span className="rounded bg-muted px-1.5 font-mono text-xs text-primary">{c.key}</span>
|
|
||||||
<span className="min-w-0 flex-1 truncate font-medium">{c.name}</span>
|
|
||||||
{c.unread > 0 && <span className="rounded-full bg-info px-2 text-xs font-semibold text-background" title={t("новые сообщения")}>{t("{n} нов.", { n: c.unread })}</span>}
|
|
||||||
{c.open > 0 && <span className="rounded-full bg-primary px-2 text-xs font-semibold text-primary-foreground" title={t("агенты ждут вашего ответа")}>{t("ждут ответа: {n}", { n: c.open })}</span>}
|
|
||||||
</span>
|
|
||||||
{c.last ? (
|
|
||||||
<span className="flex min-w-0 flex-col gap-0.5 text-sm">
|
|
||||||
<span className="flex items-center gap-1.5 text-xs text-muted-foreground">
|
|
||||||
{c.last.agent ? <AgentBadge name={c.last.who} role={isRoleName(c.last.who)} /> : <span>{c.last.mine ? t("вы") : c.last.who}</span>}
|
|
||||||
<span>· {ago(c.last.at, t)}</span>
|
|
||||||
</span>
|
|
||||||
<span className="line-clamp-2 text-muted-foreground">{c.last.system ? t.text(c.last.text) : c.last.agent ? t.role(c.last.text) : c.last.text}</span>
|
|
||||||
</span>
|
|
||||||
) : (
|
|
||||||
<span className="text-sm text-muted-foreground">{t("Здесь пока тихо. Спросите аналитика, что с проектом, или опишите новую задачу.")}</span>
|
|
||||||
)}
|
|
||||||
<span className="mt-auto inline-flex items-center gap-1.5 text-sm font-medium text-primary">
|
|
||||||
<MessagesSquare className="size-4" /> {t("Написать аналитику")} <ArrowRight className="size-3.5" />
|
|
||||||
</span>
|
|
||||||
</Link>
|
|
||||||
</li>
|
|
||||||
))}
|
|
||||||
</ul>
|
|
||||||
)}
|
|
||||||
</Section>
|
|
||||||
|
|
||||||
<p className="mt-6 text-sm text-muted-foreground">
|
|
||||||
{t("Нужна история?")} <Link href="/chats/master">{t("Все события по вашим проектам")}</Link> {t("— что делали агенты, обновления продукта и сбои, справочно.")}
|
|
||||||
</p>
|
|
||||||
</Workspace>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@ -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("Не удалось начать вход в сервис"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user