From 0b6a474c2b696382e56db5d78e765fda1a07f25a Mon Sep 17 00:00:00 2001 From: peppa-bot Date: Fri, 20 Nov 2026 20:57:52 +0500 Subject: [PATCH 01/14] =?UTF-8?q?PEP-225:=20proposal,=20design,=20=D1=81?= =?UTF-8?q?=D0=BF=D0=B5=D0=BA=D0=B8,=20tasks?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- .../changes/pep-225-live-websocket/design.md | 95 +++++++++++++++ .../pep-225-live-websocket/proposal.md | 31 +++++ .../specs/live-updates/spec.md | 112 ++++++++++++++++++ .../specs/runner-terminal/spec.md | 17 +++ .../changes/pep-225-live-websocket/tasks.md | 17 +++ 5 files changed, 272 insertions(+) create mode 100644 openspec/changes/pep-225-live-websocket/design.md create mode 100644 openspec/changes/pep-225-live-websocket/proposal.md create mode 100644 openspec/changes/pep-225-live-websocket/specs/live-updates/spec.md create mode 100644 openspec/changes/pep-225-live-websocket/specs/runner-terminal/spec.md create mode 100644 openspec/changes/pep-225-live-websocket/tasks.md diff --git a/openspec/changes/pep-225-live-websocket/design.md b/openspec/changes/pep-225-live-websocket/design.md new file mode 100644 index 00000000..037e347b --- /dev/null +++ b/openspec/changes/pep-225-live-websocket/design.md @@ -0,0 +1,95 @@ +# Design: PEP-225 + +## Где поднимается WebSocket +**Решение: свой сервер `apps/web/server.ts` в том же процессе, что и Next.** +`next({ dev })` + `getRequestHandler()` для HTTP, событие `upgrade` на пути `/api/ws` отдаётся +обработчику канала, остальные `upgrade` — `getUpgradeHandler()` Next (HMR в разработке). + +Почему так: +- хаб (`liveHub`), ленты терминала (`TerminalFeed`) и база уже живут в процессе веба на + `globalThis` — второй процесс дублировал бы циклы опроса и соединения с базой; +- проверка входа и прав — тот же код, что у страниц; ничего не нужно в Traefik (путь тот же + домен, Cloudflare пропускает WebSocket); +- не нужен ещё один launchd-агент, heartbeat и мониторинг. + +Отклонено: +- отдельный сервис `peppa-live` за Traefik по пути `/api/ws`: ещё один процесс, маршрут, + перезапуск в `live-deploy.sh`, мониторинг, и всё равно нужен доступ к лентам терминала; +- перехват `upgrade` у сервера `next start` из `instrumentation.ts`: не документировано, + сломается при обновлении Next. + +Логика канала (вход, права, протокол) регистрируется из `instrumentation.ts` на `globalThis` +(`__peppaLiveWs`), там доступны модули веба (`navCounts`, проверка cookie). `server.ts` знает +только `next` и `node:http`: если обработчика нет, сокет закрывается — клиент уходит на SSE. +`next dev` без своего сервера по-прежнему работает: WebSocket не откроется, страницы живут на SSE. + +Библиотека — `ws` 8.18.3 (`serverExternalPackages`, без нативных модулей): в Node 26 есть только +клиент WebSocket. `perMessageDeflate` выключен (CPU), `maxPayload` 300 КБ (вставка 64 КБ в JSON). + +## Протокол (JSON-сообщения) +Клиент → сервер: `{t:"sub", scope, since?}`, `{t:"unsub", scope}`, +`{t:"in", scope:"terminal:", keys?|paste?, id}`, `{t:"ping"}`. +Сервер → клиент: `{t:"hello", boot}`, `{t:"ok", scope}`, `{t:"err", scope?, status, error}`, +`{t:"ev", scope, ...событие}`, `{t:"ack", id, error?}`, `{t:"pong"}`. + +События области (одни и те же в WebSocket и в SSE): +- `change` `{v, parts, tasks?}` — `v` — короткий хэш отпечатка (версия области), `parts` — какие + части отпечатка изменились, `tasks` — изменившиеся строки задач `{id, status, title, column}`; +- `step` — шаг агента (как раньше), `since` для `steps:` — id последнего шага; +- `data` `{data}` — снимок для областей-значений (`attention` — `{count, sound}`, `version` — + `{boot}`); при подписке сразу отдаётся текущий снимок; +- `frame` / `out` / `end` — терминал (как в SSE PEP-9). + +Догон после обрыва: клиент помнит `v` каждой области и шлёт его в `since`; хаб сравнивает с +текущим отпечатком и при расхождении сразу шлёт `change` (с `parts: ["*"]`). Для `steps:` — +шаги после `since`; области-значения и терминал отдают снимок при каждой подписке. + +## Точечные обновления +Хаб для `project:` и `task:` держит лёгкий снимок строк задач (`id, status, title, position, +updated_at`) и отдаёт разницу в `tasks`. Клиент (`lib/live.ts`) раздаёт события «островам»: +- доска (`Board`) правит карточки: статус, название, колонку — карточка переезжает сама; +- шапка задачи (`LiveStatus`) — статус; +- счётчик «ждут вас» и заголовок вкладки — `attention`; +- шаги агента, терминал — как данные. +`LiveRefresh` пропускает серверный рендер, если каждая изменившаяся часть закрыта островами +(`parts` ⊆ части, которые острова объявили своими, и все строки задач применены). Иначе — прежний +`router.refresh()` не чаще раза в 4 с (PEP-215), с ожиданием, пока человек печатает. +Чаты: событие `chats` несёт id чатов с новыми сообщениями — страница чата обновляется, только +если новое пришло в её чат. + +## Области без опроса в браузере +- `observe` (суперадмин): отпечаток — состояния и пауза мониторингов, последний сбой и минута + последней проверки (полоса проверок обновляется не чаще раза в минуту). +- `subs` (суперадмин): строки подписок (статус, обновление), займы. +- `login:`: вход в подписку ждёт автор или суперадмин. Пока область смотрят, + хаб сам раз в 3 с вызывает `pollCodexLogin` (один цикл на подписку для всех зрителей) — опрос + ChatGPT переехал из рендера страницы на сервер. +- `me`: привязка Telegram и свой бот пользователя (кнопка «Открыть бота» ждёт `/start`). +- `version`: снимок `boot` при подписке; после перезапуска веба клиент переподключается и видит + новый `boot` — плашка «обновите страницу». + +## Надёжность +- Сервер шлёт ping-кадр раз в 15 с и закрывает соединение без pong 2 раза подряд; клиент шлёт + `{t:"ping"}` раз в 15 с и переподключается, не получив `pong` за 10 с (Cloudflare рвёт + простаивающие соединения через 100 с). +- Переподключение: 1, 2, 4 … 30 с со случайной добавкой; после переподключения — повторная + подписка с `since`. +- WebSocket не открылся 3 раза подряд, ни разу не открывшись (или его нет в браузере) — запасной + путь: SSE `/api/live` (все области, кроме терминала) и SSE терминала с POST-вводом; раз в + минуту — новая попытка WebSocket. +- Скрытая вкладка отписывается от тяжёлых областей (терминал, шаги, `team`) и подписывается + снова при возврате (с `since`). + +## Безопасность +- Без входа — 401 до апгрейда; `Origin` должен совпадать с `Host`/`X-Forwarded-Host`. +- Права на область — `checkScopeAccess` (проект — `projectForUser`; `observe`, `subs` — + суперадмин; `login:` — автор подписки или суперадмин; `terminal:` — `terminalSession`). +- Не больше 32 областей на соединение, 60 сообщений за 5 с (иначе закрытие 1008), сообщение + ≤ 300 КБ; ввод в терминал — `terminalInput` (владелец/участник, живая сессия, лимиты PEP-9), + зрители терминала — `acquireViewer`. +- Чужой текст (терминал, шаги) уходит как данные JSON, клиент вставляет его текстом. + +## Нагрузка +Как раньше: один цикл хаба на процесс, отпечаток каждой области считается раз на изменение базы +для всех её зрителей, один `TerminalFeed` на pane. `attention` считается по пользователю, только +когда изменились вопросы, сессии или чаты. Замер 50 вкладок — `apps/web/scripts/bench-live.ts`. diff --git a/openspec/changes/pep-225-live-websocket/proposal.md b/openspec/changes/pep-225-live-websocket/proposal.md new file mode 100644 index 00000000..f0182e26 --- /dev/null +++ b/openspec/changes/pep-225-live-websocket/proposal.md @@ -0,0 +1,31 @@ +# PEP-225: один живой канал на вкладку + +## Зачем +Живые страницы (PEP-37) держат по SSE-потоку на страницу, шаги агента и терминал — свои потоки, +а счётчик «ждут вас», проверка новой версии, observability, подписки и ожидание входа опрашивают +сервер по таймеру. В одной вкладке 2–4 соединения со своими пингами, а любое изменение области +перерисовывает всю страницу на сервере (доска — секунды). + +## Что меняется +- Один WebSocket на вкладку: `GET /api/ws` (upgrade), вход — cookie `peppa_session`, `Origin` — + только свой домен. Внутри — подписки на области и ответы сервера; источник событий — прежний + хаб `runner/live.ts`. +- Веб запускается своим маленьким сервером `apps/web/server.ts` (Next.js 16 сам WebSocket не + поднимает): тот же процесс, тот же хаб, та же база. +- Новые области: `attention` (счётчик «ждут вас»), `version` (перезапуск веба), `observe` + (мониторинги), `subs` (подписки суперадмина), `login:` (ожидание входа в подписку), + `me` (привязка Telegram), `terminal:` (вывод и ввод терминала). +- События несут, что изменилось: части отпечатка и строки задач (`id`, статус, название, + колонка). Доска и шапка задачи применяют их на месте; серверный рендер — только для того, что + на месте применить нельзя, не чаще раза в 4 с. +- Из веб-клиента уходят все опросы данных по таймеру (`AutoRefresh`, `setInterval` в + `AttentionBadge`, `VersionWatch`, `OpenBotButton`, `SubscriptionSetup`). Опрос входа ChatGPT + делает сервер — один цикл на подписку для всех зрителей. +- Надёжность: пинг 15 с, переподключение с нарастающей паузой, догон пропущенного по версии + области, запасной путь — прежний SSE (`/api/live` и SSE терминала). + +## Влияние +- `packages/runner/src/live.ts`, новый `live-ws.ts`; `apps/web/server.ts`, `lib/live.ts`, + компоненты живых страниц; `scripts/install-launchd.sh`, `scripts/live-deploy.sh`. +- Новая зависимость `ws` (сервер WebSocket; в Node есть только клиент). +- Спеки: `live-updates`, `runner-terminal`. diff --git a/openspec/changes/pep-225-live-websocket/specs/live-updates/spec.md b/openspec/changes/pep-225-live-websocket/specs/live-updates/spec.md new file mode 100644 index 00000000..4c8017aa --- /dev/null +++ b/openspec/changes/pep-225-live-websocket/specs/live-updates/spec.md @@ -0,0 +1,112 @@ +## ADDED Requirements + +### Requirement: Один WebSocket на вкладку +Веб SHALL принимать WebSocket `GET /api/ws` и вести через одно соединение вкладки подписки на все +живые области: `home`, `runners`, `team`, `chats`, `project:`, `task:`, `steps:`, +`terminal:`, `attention`, `version`, `observe`, `subs`, `login:`, `me`. +Вход — cookie `peppa_session` с теми же проверками, что у страниц; соединение с чужим `Origin` +или без входа MUST быть отклонено до апгрейда. Права на область — как у страницы: проект — доступ +к проекту, `observe` и `subs` — суперадмин, `login:` — автор подписки или суперадмин. + +#### Scenario: Подписка без прав +- **GIVEN** пользователь «anna» без доступа к проекту PAY открыл WebSocket +- **WHEN** он подписывается на `task:` +- **THEN** сервер отвечает `{t:"err", scope:"task:", status:404}` +- **AND** события PAY-3 ему не приходят + +#### Scenario: Событие доходит только до своей области +- **GIVEN** у вкладки подписки `task:` и `attention` +- **WHEN** PAY-4 меняет статус +- **THEN** для `task:` ничего не приходит +- **AND** когда меняется статус PAY-3, приходит `change` с строкой задачи `status: "review"` + +#### Scenario: Чужой сайт +- **WHEN** страница с другого домена открывает `wss://peppa.telecom.quest/api/ws` с cookie пользователя +- **THEN** сервер отвечает 403, соединение не открывается + +### Requirement: Догон после обрыва +Клиент SHALL помнить версию каждой области (`v` из последнего события) и после переподключения +подписываться заново с `since`; сервер MUST сразу прислать `change`, если область изменилась, +пока клиента не было, и шаги агента после `since` для `steps:`. + +#### Scenario: Связь пропала на минуту +- **GIVEN** вкладка подписана на `project:` и получила версию `v1` +- **WHEN** соединение рвётся, PAY-3 уходит в ревью, вкладка переподключается с `since: v1` +- **THEN** сразу приходит `change` для `project:` + +#### Scenario: Ничего не изменилось +- **GIVEN** вкладка переподключается с `since`, равным текущей версии области +- **WHEN** сервер принимает подписку +- **THEN** `change` не приходит + +### Requirement: Точечные обновления вместо перерисовки +Событие `change` SHALL нести, что изменилось: части отпечатка (`parts`) и для `project:`/`task:` — +изменившиеся строки задач (`id`, статус, название, колонка). Доска MUST переносить карточку в +колонку нового статуса и менять название на месте; шапка задачи — статус. Серверный рендер +страницы делается, только если изменилась часть, которую страница на месте применить не может, +и не чаще раза в 4 секунды. + +#### Scenario: Задача ушла в ревью +- **GIVEN** открыта доска PAY, PAY-3 в колонке «В работе» +- **WHEN** агент переводит PAY-3 в ревью и больше ничего не меняется +- **THEN** карточка PAY-3 за долю секунды оказывается в колонке «Ревью» +- **AND** серверный рендер страницы не запрашивается + +#### Scenario: Изменилось то, что на месте не применить +- **GIVEN** открыта доска PAY +- **WHEN** появляется новый релиз проекта +- **THEN** страница перерисовывается с сервера не позже чем через 4 секунды после прошлой перерисовки + +### Requirement: Без опросов по таймеру в браузере +Веб-клиент SHALL NOT опрашивать данные по таймеру: счётчик «ждут вас» и заголовок вкладки, +проверка новой версии, observability, подписки, ожидание входа в подписку и ожидание привязки +Telegram обновляются событиями канала. Опрос входа ChatGPT MUST делать сервер — один цикл на +подписку, пока её кто-то ждёт. Остаётся только проверка связи. + +#### Scenario: Вопрос агента +- **GIVEN** у пользователя открыта любая страница, в заголовке «(1) …» +- **WHEN** агент его проекта задаёт вопрос +- **THEN** в заголовке вкладки становится «(2) …» без перезагрузки страницы + +#### Scenario: Веб перезапустили +- **GIVEN** вкладка открыта до перезапуска веба +- **WHEN** веб перезапускается с новой версией и вкладка переподключается +- **THEN** появляется плашка «Peppa FACTORY обновилась. Обновите страницу…» + +#### Scenario: Вход в ChatGPT подтверждён +- **GIVEN** владелец ждёт на странице подключения ChatGPT +- **WHEN** ChatGPT подтверждает вход +- **THEN** страница показывает подключённую подписку без нажатий, за несколько секунд + +### Requirement: Надёжность канала +Канал SHALL пинговаться раз в 15 секунд в обе стороны, переподключаться с нарастающей паузой +(1 → 30 с) и показывать состояние связи. Если WebSocket не открылся три раза подряд, клиент MUST +перейти на SSE (`/api/live`, SSE терминала) и раз в минуту пробовать WebSocket снова. Скрытая +вкладка отписывается от терминала, шагов агента и `team` и подписывается снова при возврате. + +#### Scenario: Корпоративный прокси режет WebSocket +- **GIVEN** апгрейд до WebSocket не проходит +- **WHEN** вкладка открывает доску +- **THEN** после трёх попыток индикатор показывает «в реальном времени» через SSE и доска живая + +#### Scenario: Сообщения шлются слишком часто +- **WHEN** клиент шлёт больше 60 сообщений за 5 секунд +- **THEN** сервер закрывает соединение с кодом 1008 + +## MODIFIED Requirements + +### Requirement: Точечное обновление страницы и индикатор связи +Страницы Главная, проект, стори, раннеры, команда, чаты, подписки и observability SHALL +обновляться по событиям канала без перезагрузки и без потери введённого текста (серверный рендер +откладывается, пока пользователь печатает или оставил черновик), и показывать состояние связи: +«в реальном времени», «переподключение» или «нет связи». Если WebSocket недоступен, страница +работает через SSE `/api/live`; опроса по таймеру нет. + +#### Scenario: Черновик ответа +- **GIVEN** PM печатает ответ на вопрос на странице стори +- **WHEN** приходит `change`, который нельзя применить на месте +- **THEN** текст не теряется, страница обновится, когда поле отправят или очистят + +#### Scenario: Канал недоступен +- **WHEN** ни WebSocket, ни `/api/live` не открываются +- **THEN** индикатор показывает «нет связи», клиент пробует снова с нарастающей паузой diff --git a/openspec/changes/pep-225-live-websocket/specs/runner-terminal/spec.md b/openspec/changes/pep-225-live-websocket/specs/runner-terminal/spec.md new file mode 100644 index 00000000..aca028af --- /dev/null +++ b/openspec/changes/pep-225-live-websocket/specs/runner-terminal/spec.md @@ -0,0 +1,17 @@ +## ADDED Requirements + +### Requirement: Терминал через общий канал +Вывод терминала раннера SHALL идти через WebSocket вкладки (область `terminal:`: +`frame`, `out`, `end`), ввод — сообщением `{t:"in", keys|paste}` того же соединения с прежними +правилами: только владелец или участник проекта, живая сессия, ≤1 КБ нажатий, ≤64 КБ вставки, +40 запросов за 5 с. Без WebSocket терминал работает через прежние SSE и POST. + +#### Scenario: Ввод через сокет +- **GIVEN** участник проекта подписан на `terminal:` живой сессии +- **WHEN** он шлёт `{t:"in", scope:"terminal:", keys:"ls\r", id:1}` +- **THEN** нажатия уходят в pane, приходит `{t:"ack", id:1}` + +#### Scenario: Ввод в завершённую сессию +- **GIVEN** сессия завершена +- **WHEN** приходит `{t:"in", …, id:2}` +- **THEN** приходит `{t:"ack", id:2, error:"…"}`, в pane ничего не уходит diff --git a/openspec/changes/pep-225-live-websocket/tasks.md b/openspec/changes/pep-225-live-websocket/tasks.md new file mode 100644 index 00000000..c3e7b6e6 --- /dev/null +++ b/openspec/changes/pep-225-live-websocket/tasks.md @@ -0,0 +1,17 @@ +## 1. Сервер +- [ ] 1.1 Хаб: новые области (`attention`, `version`, `observe`, `subs`, `login:`, `me`), `parts` и строки задач в `change`, версия `v` и `since`, поставщики данных от веба +- [ ] 1.2 `runner/live-ws.ts`: протокол, права, лимиты, пинг, терминал через сокет +- [ ] 1.3 `apps/web/server.ts` + регистрация канала в `instrumentation.ts`, проверка cookie без `next/headers` +- [ ] 1.4 Запуск: `package.json`, `install-launchd.sh`, `live-deploy.sh` (переустановка агента веба) + +## 2. Клиент +- [ ] 2.1 `lib/live.ts`: одно соединение, подписки со счётчиком, переподключение, догон, SSE-запасной путь, скрытая вкладка +- [ ] 2.2 `LiveRefresh` на канале: острова, пропуск рендера, индикатор +- [ ] 2.3 Доска и шапка задачи — точечно; чаты — только свой чат +- [ ] 2.4 `AttentionBadge`, `VersionWatch`, `AgentSteps`, `RunnerTerminal` на канале +- [ ] 2.5 Убрать `AutoRefresh` и опросы: observability, подписки, `SubscriptionSetup`, `OpenBotButton` + +## 3. Проверка +- [ ] 3.1 Тесты: права, своя/чужая область, догон, терминал через сокет, лимиты +- [ ] 3.2 Замер 50 вкладок (`scripts/bench-live.ts`), цифры в PR +- [ ] 3.3 typecheck, lint, тесты; браузер (в том числе узкий экран и обрыв связи) -- 2.45.2 From d3c29890f4dc7b17ebc3e6a050ad9afa02890155 Mon Sep 17 00:00:00 2001 From: peppa-bot Date: Fri, 20 Nov 2026 21:03:20 +0500 Subject: [PATCH 02/14] =?UTF-8?q?PEP-225:=20=D1=85=D0=B0=D0=B1=20=D1=81=20?= =?UTF-8?q?=D1=87=D0=B0=D1=81=D1=82=D1=8F=D0=BC=D0=B8=20=D0=B8=20=D1=81?= =?UTF-8?q?=D1=82=D1=80=D0=BE=D0=BA=D0=B0=D0=BC=D0=B8=20=D0=B7=D0=B0=D0=B4?= =?UTF-8?q?=D0=B0=D1=87,=20=D0=BF=D1=80=D0=BE=D1=82=D0=BE=D0=BA=D0=BE?= =?UTF-8?q?=D0=BB=20WebSocket,=20=D1=81=D0=B2=D0=BE=D0=B9=20=D1=81=D0=B5?= =?UTF-8?q?=D1=80=D0=B2=D0=B5=D1=80=20=D0=B2=D0=B5=D0=B1=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- apps/web/instrumentation.ts | 3 + apps/web/lib/auth.ts | 22 +- apps/web/lib/live-server.ts | 27 ++ apps/web/lib/session-user.ts | 23 ++ apps/web/next.config.ts | 2 +- apps/web/package.json | 10 +- apps/web/server.ts | 40 +++ packages/runner/package.json | 9 +- packages/runner/src/live-ws.ts | 268 ++++++++++++++++++++ packages/runner/src/live.ts | 448 +++++++++++++++++++++++++++------ pnpm-lock.yaml | 31 +++ 11 files changed, 776 insertions(+), 107 deletions(-) create mode 100644 apps/web/lib/live-server.ts create mode 100644 apps/web/lib/session-user.ts create mode 100644 apps/web/server.ts create mode 100644 packages/runner/src/live-ws.ts diff --git a/apps/web/instrumentation.ts b/apps/web/instrumentation.ts index 79c32d4e..0c92e8fd 100644 --- a/apps/web/instrumentation.ts +++ b/apps/web/instrumentation.ts @@ -8,6 +8,9 @@ export async function register() { installCrashReporting(db, "web"); const { setRunnerClient } = await import("@peppa/runner"); setRunnerClient(true, db); + // PEP-225: the tab's WebSocket (/api/ws) — served by apps/web/server.ts in this process. + const { registerLiveWs } = await import("@/lib/live-server"); + registerLiveWs(); const version = process.env.NEXT_PUBLIC_PEPPA_VERSION; const tick = () => beat(db, "web", { version }).catch((e) => console.error(`heartbeat: ${(e as Error).message}`)); void tick(); diff --git a/apps/web/lib/auth.ts b/apps/web/lib/auth.ts index f67b4d96..886eda9d 100644 --- a/apps/web/lib/auth.ts +++ b/apps/web/lib/auth.ts @@ -1,4 +1,4 @@ -import { enterActor, getUiMode, getUser, isSuperadmin, isUserAllowed, sessionsValidAfter, sign, verify, type User } from "@peppa/core"; +import { enterActor, getUiMode, isSuperadmin, sign, type User } from "@peppa/core"; import { loadEnv } from "@peppa/shared"; import { wording, type Words } from "@peppa/shared/wording"; import { cookies, headers } from "next/headers"; @@ -6,31 +6,17 @@ import { redirect } from "next/navigation"; import { cache } from "react"; import { db } from "./db"; import { getLocale } from "./i18n"; +import { SESSION_COOKIE, SESSION_DAYS, userFromSessionToken, type SessionPayload } from "./session-user"; -export const SESSION_COOKIE = "peppa_session"; +export { SESSION_COOKIE }; /** eGov QR flow handle (PEP-65): httpOnly, only for /auth/egov, lives as long as the QR. */ export const EGOV_COOKIE = "peppa_egov"; /** Only same-site relative paths are allowed as a post-login destination. */ export const safeNext = (n: string | null | undefined) => (n && n.startsWith("/") && !n.startsWith("//") ? n : "/"); -const SESSION_DAYS = 30; - -interface SessionPayload { - uid: number; - exp: number; -} /** Memoized per request: the layout, the page and the side panel all ask for the user. */ -export const currentUser = cache(async (): Promise => { - const p = verify((await cookies()).get(SESSION_COOKIE)?.value); - if (!p || p.exp < Date.now()) return null; - // PEP-95: «выкинуть всех» — a session issued before the cut-off is no longer valid. - const after = await sessionsValidAfter(db); - if (after !== null && p.exp - SESSION_DAYS * 86400_000 < after) return null; - const user = await getUser(db, p.uid); - // Removed from the allowlist → the session stops working right away. - return user && (await isUserAllowed(db, user)) ? user : null; -}); +export const currentUser = cache(async (): Promise => userFromSessionToken((await cookies()).get(SESSION_COOKIE)?.value)); /** For pages and server actions: the logged-in user, or a redirect to /login. */ export async function requireUser(): Promise { diff --git a/apps/web/lib/live-server.ts b/apps/web/lib/live-server.ts new file mode 100644 index 00000000..a5c6b144 --- /dev/null +++ b/apps/web/lib/live-server.ts @@ -0,0 +1,27 @@ +// PEP-225: the tab's WebSocket, set up inside the Next process (instrumentation.ts) where the +// web's modules live — the cookie check, navCounts, the boot id. apps/web/server.ts only hands +// `upgrade` requests of /api/ws to what is registered here (globalThis: the custom server and +// the Next bundle are different module graphs of one process). +import { getNotifyPrefs } from "@peppa/core"; +import { setLiveProvider } from "@peppa/runner"; +import { createLiveWs, readCookie, type LiveWs } from "@peppa/runner/live-ws"; +import { bootId } from "./boot"; +import { db } from "./db"; +import { navCounts } from "./queries"; +import { SESSION_COOKIE, userFromSessionToken } from "./session-user"; + +const g = globalThis as { __peppaLiveWs?: LiveWs }; + +export function registerLiveWs(): void { + setLiveProvider("attention", async (_db, userId) => { + const [c, { sound }] = await Promise.all([navCounts(userId), getNotifyPrefs(db, userId)]); + return { count: c.questions + c.waitingRunners, chats: c.chats, sound }; + }); + setLiveProvider("version", () => ({ boot: bootId() })); + g.__peppaLiveWs?.close(); + g.__peppaLiveWs = createLiveWs({ + db, + authenticate: (req) => userFromSessionToken(readCookie(req.headers.cookie, SESSION_COOKIE)), + boot: bootId, + }); +} diff --git a/apps/web/lib/session-user.ts b/apps/web/lib/session-user.ts new file mode 100644 index 00000000..c355f461 --- /dev/null +++ b/apps/web/lib/session-user.ts @@ -0,0 +1,23 @@ +// The signed-in user of a session cookie value (PEP-225): the same checks for pages +// (lib/auth.ts currentUser) and for the tab's WebSocket, which has no `next/headers`. +import { getUser, isUserAllowed, sessionsValidAfter, verify, type User } from "@peppa/core"; +import { db } from "./db"; + +export const SESSION_COOKIE = "peppa_session"; +export const SESSION_DAYS = 30; + +export interface SessionPayload { + uid: number; + exp: number; +} + +export async function userFromSessionToken(token: string | undefined): Promise { + const p = verify(token); + if (!p || p.exp < Date.now()) return null; + // PEP-95: «выкинуть всех» — a session issued before the cut-off is no longer valid. + const after = await sessionsValidAfter(db); + if (after !== null && p.exp - SESSION_DAYS * 86400_000 < after) return null; + const user = await getUser(db, p.uid); + // Removed from the allowlist → the session stops working right away. + return user && (await isUserAllowed(db, user)) ? user : null; +} diff --git a/apps/web/next.config.ts b/apps/web/next.config.ts index c3e1c657..ea9f22c0 100644 --- a/apps/web/next.config.ts +++ b/apps/web/next.config.ts @@ -48,7 +48,7 @@ const config: NextConfig = { return process.env.NODE_ENV === "development" ? [all, { source: "/_next/static/:path*", headers: [{ key: "Cache-Control", value: "private, no-store" }] }, sw] : [all, sw]; }, // PEP-212: the code-mode sandbox (QuickJS wasm) loads its .wasm file itself — it must not be bundled. - serverExternalPackages: ["quickjs-emscripten"], + serverExternalPackages: ["quickjs-emscripten", "ws"], transpilePackages: ["@peppa/db", "@peppa/shared", "@peppa/core", "@peppa/runner", "@peppa/mcp"], env: { NEXT_PUBLIC_PEPPA_VERSION: version, diff --git a/apps/web/package.json b/apps/web/package.json index 310ab4eb..1ef0d794 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -4,10 +4,11 @@ "private": true, "type": "module", "scripts": { - "dev": "next dev -p 3100", + "dev": "node server.ts --dev -p 3100", "build": "next build", - "start": "next start -p 3100", - "typecheck": "tsc -p ." + "start": "node server.ts -p 3100", + "typecheck": "tsc -p .", + "dev:next": "next dev -p 3100" }, "dependencies": { "@modelcontextprotocol/sdk": "1.32.2", @@ -29,7 +30,8 @@ "quickjs-emscripten": "0.32.0", "react": "19.3.1", "react-dom": "19.3.1", - "tailwind-merge": "3.7.0" + "tailwind-merge": "3.7.0", + "ws": "8.18.3" }, "devDependencies": { "@tailwindcss/postcss": "4.3.5", diff --git a/apps/web/server.ts b/apps/web/server.ts new file mode 100644 index 00000000..0287c685 --- /dev/null +++ b/apps/web/server.ts @@ -0,0 +1,40 @@ +// The web's own server (PEP-225): Next.js 16 does not accept WebSockets, so this wraps it — +// plain HTTP goes to Next, `upgrade` on /api/ws to the tab's live channel that +// instrumentation.ts registered (lib/live-server.ts), other upgrades (dev HMR) to Next. +// Usage: node server.ts [--dev] [-p 3100] +import { createServer } from "node:http"; +import type { Duplex } from "node:stream"; + +const dev = process.argv.includes("--dev"); +const pIdx = process.argv.indexOf("-p"); +const port = Number(pIdx > 0 ? process.argv[pIdx + 1] : (process.env.PORT ?? 3100)); +const env = process.env as Record; +env.NODE_ENV ??= dev ? "development" : "production"; + +const { default: next } = await import("next"); +const app = next({ dev, dir: import.meta.dirname, port, hostname: "localhost" }); +const handle = app.getRequestHandler(); +await app.prepare(); +const nextUpgrade = app.getUpgradeHandler(); + +type LiveWs = { handleUpgrade(req: import("node:http").IncomingMessage, socket: Duplex, head: Buffer): void }; +const live = () => (globalThis as { __peppaLiveWs?: LiveWs }).__peppaLiveWs; + +const server = createServer((req, res) => void handle(req, res)); +server.on("upgrade", (req, socket: Duplex, head: Buffer) => { + if (req.url?.split("?")[0] === "/api/ws") { + const ws = live(); + if (ws) return ws.handleUpgrade(req, socket, head); + socket.end("HTTP/1.1 503 Service Unavailable\r\nConnection: close\r\nContent-Length: 0\r\n\r\n"); + return; + } + void nextUpgrade(req, socket, head); +}); +server.listen(port, () => console.log(`peppa web: http://localhost:${port} (${dev ? "dev" : "production"}, WebSocket /api/ws)`)); + +const shutdown = () => { + server.close(); + setTimeout(() => process.exit(0), 3000).unref(); +}; +process.on("SIGTERM", shutdown); +process.on("SIGINT", shutdown); diff --git a/packages/runner/package.json b/packages/runner/package.json index bd52cbd1..d8c7105f 100644 --- a/packages/runner/package.json +++ b/packages/runner/package.json @@ -4,7 +4,8 @@ "private": true, "type": "module", "exports": { - ".": "./src/index.ts" + ".": "./src/index.ts", + "./live-ws": "./src/live-ws.ts" }, "bin": { "peppa-hook": "./bin/peppa-hook" @@ -17,6 +18,10 @@ "@peppa/core": "workspace:*", "@peppa/db": "workspace:*", "@peppa/shared": "workspace:*", - "drizzle-orm": "0.45.4" + "drizzle-orm": "0.45.4", + "ws": "8.18.3" + }, + "devDependencies": { + "@types/ws": "8.18.1" } } diff --git a/packages/runner/src/live-ws.ts b/packages/runner/src/live-ws.ts new file mode 100644 index 00000000..01063e9a --- /dev/null +++ b/packages/runner/src/live-ws.ts @@ -0,0 +1,268 @@ +// One WebSocket per browser tab (PEP-225): `GET /api/ws` carries every live scope of the tab — +// the hub's scopes (live.ts) and the runner terminal (terminal.ts, output and input) — instead of +// an SSE stream per page part. The web's own server (apps/web/server.ts) hands the upgrade here; +// the protocol itself (LiveConnection) knows nothing of the transport, tests drive it directly. +// +// Client → server: {t:"sub", scope, since?} · {t:"unsub", scope} · {t:"in", scope:"terminal:", keys?|paste?, id} · {t:"ping"} +// Server → client: {t:"hello", boot} · {t:"ok", scope, v?} · {t:"err", scope?, status, error} · {t:"ev", scope, type, …} · {t:"ack", id, error?} · {t:"pong"} +import type { IncomingMessage } from "node:http"; +import type { Duplex } from "node:stream"; +import { WebSocketServer, type WebSocket } from "ws"; +import { m } from "@peppa/shared/i18n"; +import { PeppaError, projectSecretMasker, type User } from "@peppa/core"; +import type { Db } from "@peppa/db"; +import * as tmux from "./tmux.ts"; +import { checkScopeAccess, LIVE_MAX_SCOPES, LIVE_PING_MS, liveHub, LiveError, parseScope, type LiveScope } from "./live.ts"; +import { acquireViewer, terminalInput, terminalSession, watchTerminal } from "./terminal.ts"; + +/** Largest message from a client: a 64 KB paste in JSON with escapes. */ +export const LIVE_WS_MAX_PAYLOAD = 300_000; +/** Client messages per window before the socket is closed (1008). */ +export const LIVE_WS_RATE_MAX = 60; +export const LIVE_WS_RATE_WINDOW_MS = 5000; +export const LIVE_WS_PATH = "/api/ws"; + +type Out = Record; + +/** One tab's connection: its subscriptions, input and limits. */ +export class LiveConnection { + private subs = new Map void>(); + private pending = new Set(); + private window = { start: 0, n: 0 }; + private input: Promise = Promise.resolve(); + private closed = false; + private db: Db; + private user: User; + private out: (msg: Out) => void; + private kill: (code: number, reason: string) => void; + + constructor(db: Db, user: User, out: (msg: Out) => void, kill: (code: number, reason: string) => void) { + this.db = db; + this.user = user; + this.out = out; + this.kill = kill; + } + + private send(msg: Out) { + if (!this.closed) this.out(msg); + } + + /** Handles one text message; returns once it is dealt with (tests await it). */ + async receive(raw: string, now = Date.now()): Promise { + if (this.closed) return; + if (now - this.window.start >= LIVE_WS_RATE_WINDOW_MS) this.window = { start: now, n: 0 }; + if (++this.window.n > LIVE_WS_RATE_MAX) return this.kill(1008, "rate"); + let msg: { t?: unknown; scope?: unknown; since?: unknown; keys?: unknown; paste?: unknown; id?: unknown }; + try { + msg = JSON.parse(raw); + } catch { + return this.send({ t: "err", status: 400, error: m("Неверный JSON") }); + } + if (msg.t === "ping") return this.send({ t: "pong" }); + const scopeRaw = typeof msg.scope === "string" ? msg.scope : ""; + let scope: LiveScope; + try { + scope = parseScope(scopeRaw); + } catch (e) { + return this.send({ t: "err", scope: scopeRaw, status: 400, error: (e as Error).message }); + } + if (msg.t === "sub") return this.subscribe(scope, typeof msg.since === "string" || typeof msg.since === "number" ? msg.since : undefined); + if (msg.t === "unsub") return this.unsubscribe(scope); + if (msg.t === "in") return this.terminalIn(scope, msg); + this.send({ t: "err", scope, status: 400, error: m("Неизвестное сообщение") }); + } + + private async subscribe(scope: LiveScope, since: string | number | undefined) { + if (this.subs.has(scope) || this.pending.has(scope)) return this.send({ t: "ok", scope }); + if (this.subs.size + this.pending.size >= LIVE_MAX_SCOPES) return this.send({ t: "err", scope, status: 429, error: m("Слишком много областей") }); + this.pending.add(scope); + try { + await checkScopeAccess(this.db, this.user, scope); + const stop = scope.startsWith("terminal:") ? await this.watchTerminal(scope) : this.watchHub(scope, since); + // Unsubscribed (or closed) while access was checked. + if (!this.pending.has(scope) || this.closed) return stop(); + this.subs.set(scope, stop); + this.send({ t: "ok", scope, v: scope.startsWith("terminal:") ? undefined : liveHub(this.db).versionOf(scope, this.user.id) }); + } catch (e) { + const status = e instanceof LiveError ? e.status : (e as { status?: number }).status ?? 500; + if (status === 500) console.error(`live-ws: ${scope}`, e); + this.send({ t: "err", scope, status, error: e instanceof LiveError || e instanceof PeppaError ? e.message : m("Ошибка потока") }); + } finally { + this.pending.delete(scope); + } + } + + private watchHub(scope: LiveScope, since: string | number | undefined): () => void { + return liveHub(this.db).subscribe([scope], (e) => this.send({ t: "ev", ...e }), { userId: this.user.id, since: { [scope]: since } }); + } + + /** The runner terminal (PEP-9): the shared TerminalFeed of the pane, secrets masked, viewers per user limited. */ + private async watchTerminal(scope: LiveScope): Promise<() => void> { + const s = await terminalSession(this.db, this.user, Number(scope.slice(9))); + const mask = await projectSecretMasker(this.db, s.projectId); + const release = acquireViewer(this.user.id); + let done = false; + const stopFeed = watchTerminal( + tmux.sessionPane(s), + (e) => { + this.send({ t: "ev", scope, ...e }); + if (e.type === "end") queueMicrotask(() => this.unsubscribe(scope)); + }, + { mask }, + ); + return () => { + if (done) return; + done = true; + stopFeed(); + release(); + }; + } + + private unsubscribe(scope: LiveScope) { + this.pending.delete(scope); + const stop = this.subs.get(scope); + this.subs.delete(scope); + stop?.(); + } + + /** Keyboard input / paste of the terminal: in order, with the PEP-9 checks and limits. */ + private terminalIn(scope: LiveScope, msg: { keys?: unknown; paste?: unknown; id?: unknown }) { + const id = typeof msg.id === "number" || typeof msg.id === "string" ? msg.id : null; + if (!scope.startsWith("terminal:")) return this.send({ t: "ack", id, error: m("Ввод — только в терминал") }); + const input = { keys: typeof msg.keys === "string" ? msg.keys : undefined, paste: typeof msg.paste === "string" ? msg.paste : undefined }; + const run = async () => { + try { + await terminalInput(this.db, this.user, Number(scope.slice(9)), input); + this.send({ t: "ack", id }); + } catch (e) { + this.send({ t: "ack", id, error: e instanceof PeppaError || e instanceof LiveError ? e.message : m("Ошибка терминала") }); + if (!(e instanceof PeppaError)) console.error("live-ws: terminal input", e); + } + }; + this.input = this.input.then(run); + return this.input; + } + + get scopes(): LiveScope[] { + return [...this.subs.keys()]; + } + + close() { + if (this.closed) return; + this.closed = true; + for (const stop of this.subs.values()) stop(); + this.subs.clear(); + this.pending.clear(); + } +} + +/** Same-site only: the cookie is `lax`, a WebSocket from another site would carry it. */ +export function sameOriginUpgrade(req: IncomingMessage): boolean { + const origin = req.headers.origin; + if (!origin) return true; // not a browser + const host = (req.headers["x-forwarded-host"] as string | undefined)?.split(",")[0]?.trim() || req.headers.host; + try { + return new URL(origin).host === host; + } catch { + return false; + } +} + +export interface LiveWsOptions { + db: Db; + /** The signed-in user of the request (cookie `peppa_session`), or null. */ + authenticate: (req: IncomingMessage) => Promise; + /** Boot id of the web process (the client compares it after a reconnect). */ + boot?: () => string; + pingMs?: number; +} + +export interface LiveWs { + handleUpgrade(req: IncomingMessage, socket: Duplex, head: Buffer): void; + readonly clients: number; + close(): void; +} + +function refuse(socket: Duplex, status: number, text: string) { + try { + socket.write(`HTTP/1.1 ${status} ${text}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`); + } catch {} + socket.destroy(); +} + +/** The WebSocket endpoint: auth and origin before the upgrade, a ping every 15 s, one LiveConnection per socket. */ +export function createLiveWs(opts: LiveWsOptions): LiveWs { + const wss = new WebSocketServer({ noServer: true, perMessageDeflate: false, maxPayload: LIVE_WS_MAX_PAYLOAD }); + const alive = new WeakMap(); + const pingMs = opts.pingMs ?? LIVE_PING_MS; + // Two pings without a pong: the connection is dead (a sleeping phone, a dropped proxy). + const pinger = setInterval(() => { + for (const ws of wss.clients) { + const missed = (alive.get(ws) ?? 0) + 1; + if (missed > 2) { + ws.terminate(); + continue; + } + alive.set(ws, missed); + try { + ws.ping(); + } catch {} + } + }, pingMs); + pinger.unref?.(); + + wss.on("connection", (ws: WebSocket, _req: IncomingMessage, user: User) => { + alive.set(ws, 0); + const conn = new LiveConnection( + opts.db, + user, + (msg) => { + if (ws.readyState === ws.OPEN) ws.send(JSON.stringify(msg)); + }, + (code, reason) => ws.close(code, reason), + ); + ws.on("pong", () => alive.set(ws, 0)); + ws.on("message", (data, isBinary) => { + alive.set(ws, 0); + if (isBinary) return ws.close(1003, "text only"); + void conn.receive(data.toString()); + }); + ws.on("close", () => conn.close()); + ws.on("error", () => conn.close()); + ws.send(JSON.stringify({ t: "hello", boot: opts.boot?.() ?? "" })); + }); + + return { + handleUpgrade(req, socket, head) { + socket.on("error", () => socket.destroy()); + if (!sameOriginUpgrade(req)) return refuse(socket, 403, "Forbidden"); + opts + .authenticate(req) + .then((user) => { + if (!user) return refuse(socket, 401, "Unauthorized"); + wss.handleUpgrade(req, socket, head, (ws) => wss.emit("connection", ws, req, user)); + }) + .catch((e) => { + console.error("live-ws: upgrade", e); + refuse(socket, 500, "Internal Server Error"); + }); + }, + get clients() { + return wss.clients.size; + }, + close() { + clearInterval(pinger); + for (const ws of wss.clients) ws.terminate(); + wss.close(); + }, + }; +} + +/** Reads one cookie from a raw Cookie header. */ +export function readCookie(header: string | undefined, name: string): string | undefined { + for (const part of (header ?? "").split(";")) { + const i = part.indexOf("="); + if (i > 0 && part.slice(0, i).trim() === name) return decodeURIComponent(part.slice(i + 1).trim()); + } + return undefined; +} diff --git a/packages/runner/src/live.ts b/packages/runner/src/live.ts index 4a67a8f7..1558e950 100644 --- a/packages/runner/src/live.ts +++ b/packages/runner/src/live.ts @@ -1,22 +1,52 @@ -// Live web (PEP-37): one change hub per web process. notify() pokes (the `web` subscriber -// socket, the same events the bot hears) and PRAGMA data_version (writes from the hooks, -// the watchdog, the CLI) wake it; it then computes a fingerprint of every scope somebody -// watches and tells only the watchers whose scope changed. Steps of agents (PEP-33) go to -// `steps:` watchers as data. +// Live web (PEP-37, PEP-225): one change hub per web process. notify() pokes (the `web` subscriber +// socket, the same events the bot hears) and PRAGMA data_version (writes from the hooks, the +// watchdog, the CLI) wake it; it then computes a fingerprint of every scope somebody watches and +// tells only the watchers whose scope changed — with what changed (`parts`, rows of tasks), so a +// page can apply it in place. Steps of agents (PEP-33) go to `steps:` watchers as +// data; value scopes (`attention`, `version`) send their value. The same events go out over the +// tab's WebSocket (live-ws.ts) and over the SSE fallback (/api/live). import { m } from "@peppa/shared/i18n"; +import { createHash } from "node:crypto"; import { existsSync, statSync } from "node:fs"; import { join } from "node:path"; -import { findChangeDir, listenEvents, projectForUser, STEP_EVENT, stepView, type StepView, type User } from "@peppa/core"; -import { events, sessions, tasks, type Db } from "@peppa/db"; +import { findChangeDir, isSuperadmin, listenEvents, observeDb, observeDbPath, projectForUser, STEP_EVENT, stepView, type StepView, type User } from "@peppa/core"; +import { events, sessions, subscriptions, tasks, type Db } from "@peppa/db"; import { and, eq, gt } from "drizzle-orm"; +import { columnOf, type BoardColumn } from "./flow.ts"; +import { pollCodexLogin } from "./subscription-login.ts"; +import { terminalSession } from "./terminal.ts"; -export type LiveScope = "home" | "runners" | "chats" | "team" | `project:${number}` | `task:${number}` | `steps:${number}`; -export type LiveEvent = { type: "change"; scope: LiveScope } | { type: "step"; scope: LiveScope; step: StepView }; +/** Scopes without an id. `attention` and `me` are per user (the hub keys them by the viewer). */ +export const LIVE_PLAIN_SCOPES = ["home", "runners", "chats", "team", "attention", "version", "observe", "subs", "me"] as const; +const ID_KINDS = ["project", "task", "steps", "login", "terminal"] as const; +type PlainScope = (typeof LIVE_PLAIN_SCOPES)[number]; +type IdKind = (typeof ID_KINDS)[number]; +export type LiveScope = PlainScope | `${IdKind}:${number}`; + +/** A row of a task as a page shows it on the board and in the story header. */ +export interface LiveTaskRow { + id: number; + status: string; + title: string; + column: BoardColumn; + /** Something else of the row changed (epic, order, «Предложено», importance): the page re-renders. */ + other?: boolean; +} +type Row = LiveTaskRow & { sig: string }; + +export type LiveEvent = + /** The scope changed: `v` — its new version, `parts` — which parts of it, `tasks` — changed task rows, `chats` — chats with new messages. */ + | { type: "change"; scope: LiveScope; v: string; parts: string[]; tasks?: LiveTaskRow[]; chats?: number[] } + | { type: "step"; scope: LiveScope; step: StepView } + /** The current value of a value scope (`attention`, `version`). */ + | { type: "data"; scope: LiveScope; v: string; data: unknown }; type Listener = (e: LiveEvent) => void; export const LIVE_PING_MS = 15_000; +/** Most scopes one SSE stream / one WebSocket may watch. */ +export const LIVE_MAX_SCOPES = 32; -/** Refusal of a live stream with its HTTP status. */ +/** Refusal of a live stream or a subscription with its HTTP status. */ export class LiveError extends Error { status: number; constructor(message: string, status: number) { @@ -25,38 +55,77 @@ export class LiveError extends Error { } } const WAKE_DEBOUNCE_MS = 250; +/** Scopes read from outside the main database: re-checked on a timer while watched. */ +const OBSERVE_EVERY_MS = 2000; +/** A pending ChatGPT sign-in is asked this often while somebody waits for it (PEP-148, server side since PEP-225). */ +export const LOGIN_POLL_MS = 3000; -/** Parses `?scope=a,b`; unknown parts are refused. */ +/** Checks one scope name; unknown ones are refused. */ +export function parseScope(part: string): LiveScope { + if ((LIVE_PLAIN_SCOPES as readonly string[]).includes(part)) return part as LiveScope; + if (/^(project|task|steps|login|terminal):[1-9]\d{0,9}$/.test(part)) return part as LiveScope; + throw new LiveError(m("Неизвестная область: {scope}", { scope: part }), 400); +} + +/** Parses `?scope=a,b` of the SSE fallback; the terminal has its own stream there. */ export function parseScopes(raw: string | null): LiveScope[] { const out = new Set(); for (const part of (raw ?? "").split(",").map((s) => s.trim()).filter(Boolean)) { - if (part === "home" || part === "runners" || part === "chats" || part === "team") out.add(part); - else if (/^(project|task|steps):[1-9]\d{0,9}$/.test(part)) out.add(part as LiveScope); - else throw new LiveError(m("Неизвестная область: {scope}", { scope: part }), 400); + const s = parseScope(part); + if (s.startsWith("terminal:")) throw new LiveError(m("Неизвестная область: {scope}", { scope: part }), 400); + out.add(s); } - if (!out.size || out.size > 8) throw new LiveError(m("Нужна область (scope)"), 400); + if (!out.size || out.size > LIVE_MAX_SCOPES) throw new LiveError(m("Нужна область (scope)"), 400); return [...out]; } -/** Access: project/story/runner scopes need the project; home/runners only a user. */ +const notFound = () => new LiveError(m("Не найдено"), 404); + +/** + * Access, the same as the page's: project / story / steps / terminal need the project, + * `observe` and `subs` a superadmin, `login:` the author of that sign-in or a superadmin. + */ export async function checkScopeAccess(db: Db, user: User, scope: LiveScope): Promise { const [kind, raw] = scope.split(":") as [string, string?]; const id = Number(raw); + if (kind === "observe" || kind === "subs") { + if (!(await isSuperadmin(db, user))) throw notFound(); + return; + } + if (kind === "login") { + const row = (await db.select({ by: subscriptions.createdBy }).from(subscriptions).where(eq(subscriptions.id, id)))[0]; + if (!row || (row.by !== user.id && !(await isSuperadmin(db, user)))) throw notFound(); + return; + } + if (kind === "terminal") { + await terminalSession(db, user, id).catch(() => { + throw notFound(); + }); + return; + } let projectId: number | undefined; if (kind === "project") projectId = id; else if (kind === "task") projectId = (await db.select({ p: tasks.projectId }).from(tasks).where(eq(tasks.id, id)))[0]?.p; else if (kind === "steps") projectId = (await db.select({ p: sessions.projectId }).from(sessions).where(eq(sessions.id, id)))[0]?.p; else return; - if (projectId == null) throw new LiveError(m("Не найдено"), 404); + if (projectId == null) throw notFound(); await projectForUser(db, user.id, projectId).catch(() => { - throw new LiveError(m("Не найдено"), 404); + throw notFound(); }); } -const ACTIVE_SESSIONS = `group_concat(CASE WHEN ended_at IS NULL THEN id || ':' || status END)`; +/** Short version of a fingerprint: what a client sends back as `since`. */ +export const liveVersion = (fp: string) => createHash("sha1").update(fp).digest("base64url").slice(0, 12); -/** One SQL per scope; frequent fields (last_activity_at, steps, heartbeats) are left out. */ -function fingerprint(db: Db, scope: LiveScope): string { +const ACTIVE_SESSIONS = `group_concat(CASE WHEN ended_at IS NULL THEN id || ':' || status END)`; +type Parts = Record; +const str = (row: Record | undefined): Parts => Object.fromEntries(Object.entries(row ?? {}).map(([k, v]) => [k, String(v ?? "")])); + +/** + * One SQL per scope, split into named parts; frequent fields (last_activity_at, steps, + * heartbeats) are left out. Part `t` is covered by the task rows sent along (see taskRows). + */ +function fingerprint(db: Db, scope: LiveScope, userId: number): Parts { const c = db.$client; const [kind, raw] = scope.split(":") as [string, string?]; const id = Number(raw); @@ -64,7 +133,8 @@ function fingerprint(db: Db, scope: LiveScope): string { const row = c .prepare( `SELECT - (SELECT json_array(status, title, coalesce(description,''), coalesce(goal_id,0), coalesce(openspec_change,''), coalesce(pr_url,''), ci_attempts, updated_at) FROM tasks WHERE id = ?1) AS t, + (SELECT json_array(status, title) FROM tasks WHERE id = ?1) AS t, + (SELECT json_array(coalesce(description,''), coalesce(goal_id,0), coalesce(openspec_change,''), coalesce(pr_url,''), ci_attempts, updated_at) FROM tasks WHERE id = ?1) AS d, (SELECT coalesce(max(id),0) FROM events WHERE task_id = ?1 AND type <> 'step') AS e, (SELECT count(*) || ':' || count(answered_at) FROM questions WHERE task_id = ?1) AS q, (SELECT coalesce(group_concat(id || ':' || status || ':' || coalesce(ended_at,'')),'') FROM sessions WHERE task_id = ?1) AS s, @@ -74,7 +144,7 @@ function fingerprint(db: Db, scope: LiveScope): string { (SELECT openspec_change FROM tasks WHERE id = ?1) AS ch`, ) .get(id) as Record | undefined; - if (!row) return ""; + if (!row?.t) return {}; // tasks.md of the working copy changes without a database write (agent ticks items). let tasksMtime = 0; if (row.ws && row.ch) { @@ -82,13 +152,15 @@ function fingerprint(db: Db, scope: LiveScope): string { const file = found && join(found.dir, "tasks.md"); if (file && existsSync(file)) tasksMtime = statSync(file).mtimeMs; } - return [row.t, row.e, row.q, row.s, row.ci, row.r, tasksMtime].join("|"); + const { ws: _ws, ch: _ch, ...rest } = row; + return { ...str(rest), md: String(tasksMtime) }; } if (kind === "project") { + // `t` — the board rows: what a page can't apply from `tasks` comes with `other: true`. const row = c .prepare( `SELECT - (SELECT coalesce(max(updated_at),0) || ':' || count(*) FROM tasks WHERE project_id = ?1) AS t, + (SELECT coalesce(group_concat(id || ':' || status || ':' || title || ':' || position || ':' || coalesce(goal_id,0) || ':' || proposed || ':' || coalesce(severity,'') || ':' || coalesce(origin,''), char(1)),'') FROM tasks WHERE project_id = ?1 AND archived_at IS NULL) AS t, (SELECT coalesce(max(id),0) FROM events WHERE project_id = ?1 AND type <> 'step') AS e, (SELECT count(*) || ':' || count(answered_at) FROM questions WHERE project_id = ?1) AS q, (SELECT count(*) || ':' || coalesce(${ACTIVE_SESSIONS},'') FROM sessions WHERE project_id = ?1) AS s, @@ -98,7 +170,7 @@ function fingerprint(db: Db, scope: LiveScope): string { (SELECT updated_at FROM projects WHERE id = ?1) AS p`, ) .get(id) as Record; - return Object.values(row).join("|"); + return str(row); } if (kind === "chats") { // PEP-62: a new chat message (projected or written) or a question answered anywhere. @@ -111,7 +183,41 @@ function fingerprint(db: Db, scope: LiveScope): string { (SELECT coalesce(group_concat(id || ':' || coalesce(tg_chat_id,'')),'') FROM chats WHERE tg_chat_id IS NOT NULL) AS tg`, ) .get() as Record; - return Object.values(row).join("|"); + return str(row); + } + if (kind === "subs") { + const row = c + .prepare( + `SELECT + (SELECT coalesce(group_concat(id || ':' || status || ':' || coalesce(limited_until,'') || ':' || coalesce(checked_at,'') || ':' || coalesce(last_error,'')),'') FROM subscriptions) AS sub, + (SELECT coalesce(group_concat(pool_id || ':' || subscription_id),'') FROM subscription_pool_members) AS pool, + (SELECT coalesce(group_concat(key || '=' || value),'') FROM settings WHERE key >= 'subscription.' AND key < 'subscription/') AS st, + (SELECT count(*) || ':' || coalesce(${ACTIVE_SESSIONS},'') FROM sessions) AS s`, + ) + .get() as Record; + return str(row); + } + if (kind === "login") { + const row = c.prepare(`SELECT status || ':' || coalesce(last_error,'') AS sub FROM subscriptions WHERE id = ?`).get(id) as Record | undefined; + return { sub: String(row?.sub ?? "gone") }; + } + if (kind === "me") { + const row = c + .prepare(`SELECT coalesce(telegram_chat_id,'') || ':' || coalesce(telegram_bot_username,'') || ':' || coalesce(egov_iin,'') || ':' || coalesce(google_sub,'') AS u FROM users WHERE id = ?`) + .get(userId) as Record | undefined; + return { u: String(row?.u ?? "") }; + } + if (kind === "observe") { + const o = observeDb(); + const row = o + .prepare( + `SELECT + (SELECT coalesce(group_concat(id || ':' || state || ':' || paused || ':' || name || ':' || updated_at),'') FROM monitors) AS mon, + (SELECT coalesce(max(id),0) || ':' || count(ended_at) FROM monitor_incidents) AS inc, + (SELECT coalesce(substr(max(at),1,16),'') FROM monitor_checks) AS min`, + ) + .get() as Record; + return str(row); } // home / runners / team: across projects (only wakes the page — data stays behind access checks). // team (PEP-179) also watches the team itself: a new agent, a renamed or removed one, and which @@ -119,7 +225,7 @@ function fingerprint(db: Db, scope: LiveScope): string { const row = c .prepare( `SELECT - (SELECT coalesce(max(updated_at),0) || ':' || count(*) FROM tasks) AS t, + (SELECT coalesce(max(updated_at),0) || ':' || count(*) FROM tasks) AS tx, (SELECT count(*) || ':' || count(answered_at) FROM questions) AS q, (SELECT count(*) || ':' || coalesce(${ACTIVE_SESSIONS},'') FROM sessions) AS s, (SELECT count(*) FROM projects) AS p${ @@ -131,68 +237,178 @@ function fingerprint(db: Db, scope: LiveScope): string { }`, ) .get() as Record; - return Object.values(row).join("|"); + return str(row); +} + +/** Board rows of a project / the story, keyed by id: «status|title». */ +function taskRows(db: Db, scope: LiveScope): Map { + const [kind, raw] = scope.split(":"); + const cols = `id, status, title, position || ':' || coalesce(goal_id,0) || ':' || proposed || ':' || coalesce(severity,'') || ':' || coalesce(origin,'') AS sig`; + const sql = kind === "project" ? `SELECT ${cols} FROM tasks WHERE project_id = ? AND archived_at IS NULL` : `SELECT ${cols} FROM tasks WHERE id = ?`; + const rows = db.$client.prepare(sql).all(Number(raw)) as Array<{ id: number; status: string; title: string; sig: string }>; + return new Map(rows.map((r) => [r.id, { id: r.id, status: r.status, title: r.title, column: columnOf(r.status), sig: String(r.sig) }])); +} + +/** Chats with a message newer than `after` (PEP-225: a chat page re-renders only for its own chat). */ +function chatsAfter(db: Db, after: number): number[] { + const rows = db.$client.prepare(`SELECT DISTINCT chat_id AS id FROM chat_messages WHERE id > ? LIMIT 50`).all(after) as Array<{ id: number }>; + return rows.map((r) => r.id); +} + +/** A value scope's provider: the web registers `attention` (it owns navCounts). */ +export type LiveProvider = (db: Db, userId: number) => Promise | unknown; +const g = globalThis as { __peppaLiveHub?: LiveHub; __peppaLiveProviders?: Map; __peppaBoot?: string }; +const providers = (g.__peppaLiveProviders ??= new Map()); +const hubBoot = `boot-${Date.now().toString(36)}`; +providers.set("version", () => ({ boot: g.__peppaBoot ?? hubBoot })); + +/** Registers the value of a value scope (`attention`, `version`). */ +export function setLiveProvider(scope: "attention" | "version", fn: LiveProvider): void { + providers.set(scope, fn); +} + +const VALUE_SCOPES = new Set(["attention", "version"]); +const PER_USER = new Set(["attention", "me"]); +/** Hub key of a scope: per-user scopes are watched per viewer. */ +const keyOf = (scope: LiveScope, userId: number) => (PER_USER.has(scope) ? `${scope}@${userId}` : scope); + +interface Watch { + scope: LiveScope; + userId: number; + listeners: Set; + parts?: Parts; + v?: string; + rows?: Map; + chatMax?: number; + lastStep?: number; + /** Value scopes: last value sent (JSON). */ + value?: string; } class LiveHub { - private listeners = new Map>(); - private prints = new Map(); - private lastStep = new Map(); + private watches = new Map(); private timer: ReturnType | null = null; private wakeTimer: ReturnType | null = null; private stopSocket: (() => Promise) | null = null; private seen = ""; + private checking: Promise | null = null; + private again = false; + private lastObserve = 0; + private lastLoginPoll = 0; private db: Db; constructor(db: Db) { this.db = db; } - subscribe(scopes: LiveScope[], fn: Listener): () => void { - for (const s of scopes) { - let set = this.listeners.get(s); - if (!set) { - this.listeners.set(s, (set = new Set())); - this.prime(s); + /** + * Watches `scopes` for the viewer `userId` (needed for `attention` / `me`). `since` — the + * version (or the last step id for `steps:`) the client saw before a drop: whatever changed + * since is sent right away. Value scopes always send their current value first. + */ + subscribe(scopes: LiveScope[], fn: Listener, opts: { userId?: number; since?: Record } = {}): () => void { + const userId = opts.userId ?? 0; + const keys: string[] = []; + for (const scope of scopes) { + const key = keyOf(scope, userId); + keys.push(key); + let w = this.watches.get(key); + if (!w) { + this.watches.set(key, (w = { scope, userId, listeners: new Set() })); + this.prime(w); } - set.add(fn); + w.listeners.add(fn); + this.catchUp(w, fn, opts.since?.[scope]); } this.start(); return () => { - for (const s of scopes) { - const set = this.listeners.get(s); - set?.delete(fn); - if (set && !set.size) { - this.listeners.delete(s); - this.prints.delete(s); - this.lastStep.delete(s); - } + for (const key of keys) { + const w = this.watches.get(key); + w?.listeners.delete(fn); + if (w && !w.listeners.size) this.watches.delete(key); } - if (!this.listeners.size) this.stop(); + if (!this.watches.size) this.stop(); }; } /** Remembers the current state, so only later changes are reported. */ - private prime(s: LiveScope) { + private prime(w: Watch) { try { + const s = w.scope; if (s.startsWith("steps:")) { const row = this.db.$client.prepare(`SELECT coalesce(max(id),0) AS id FROM events WHERE session_id = ? AND type = 'step'`).get(Number(s.slice(6))) as { id: number }; - this.lastStep.set(s, row.id); - } else this.prints.set(s, fingerprint(this.db, s)); + w.lastStep = row.id; + } else if (!VALUE_SCOPES.has(s)) { + w.parts = fingerprint(this.db, s, w.userId); + w.v = liveVersion(JSON.stringify(w.parts)); + if (s.startsWith("project:") || s.startsWith("task:")) w.rows = taskRows(this.db, s); + if (s === "chats") w.chatMax = Number(w.parts.m) || 0; + } } catch (e) { console.error("live: prime failed", e); } } + /** A new listener: the current value of a value scope, the version of others, missed steps. */ + private catchUp(w: Watch, fn: Listener, since: string | number | undefined) { + const s = w.scope; + if (VALUE_SCOPES.has(s)) { + void this.value(w).then((data) => { + if (data !== undefined && w.listeners.has(fn)) fn({ type: "data", scope: s, v: liveVersion(JSON.stringify(data)), data }); + }); + return; + } + if (s.startsWith("steps:")) { + const after = Number(since); + if (!after || after >= (w.lastStep ?? 0)) return; + for (const r of this.stepsAfter(s, after, 200)) fn({ type: "step", scope: s, step: stepView(r) }); + return; + } + if (since !== undefined && w.v && since !== w.v) fn({ type: "change", scope: s, v: w.v, parts: ["*"] }); + } + + private async value(w: Watch): Promise { + const fn = providers.get(w.scope); + if (!fn) return undefined; + try { + const data = await fn(this.db, w.userId); + w.value = JSON.stringify(data); + return data; + } catch (e) { + console.error(`live: ${w.scope} value failed`, e); + return undefined; + } + } + + private stepsAfter(scope: LiveScope, after: number, limit: number) { + return this.db + .select() + .from(events) + .where(and(eq(events.sessionId, Number(scope.slice(6))), eq(events.type, STEP_EVENT), gt(events.id, after))) + .orderBy(events.id) + .limit(limit) + .all(); + } + private start() { if (this.timer) return; this.seen = this.version(); - // Writes of other processes (hooks, watchdog, bot, CLI) and of this one. + // Writes of other processes (hooks, watchdog, bot, CLI) and of this one; the observe + // database and a pending ChatGPT sign-in are looked at on a timer while somebody watches. this.timer = setInterval(() => { const v = this.version(); if (v !== this.seen) { this.seen = v; this.wake(); } + const now = Date.now(); + if (this.watches.has("observe") && now - this.lastObserve >= OBSERVE_EVERY_MS) { + this.lastObserve = now; + this.wake(); + } + if (now - this.lastLoginPoll >= LOGIN_POLL_MS) { + this.lastLoginPoll = now; + void this.pollLogins(); + } }, 1000); this.timer.unref?.(); listenEvents("web", () => this.wake()) @@ -203,6 +419,17 @@ class LiveHub { .catch((e) => console.error("live: web.events.sock unavailable, data_version only:", (e as Error).message)); } + /** One ChatGPT check per watched pending sign-in for all its viewers (it reads the sign-in's tmux pane). */ + private async pollLogins() { + for (const w of [...this.watches.values()]) { + if (!w.scope.startsWith("login:") || !w.parts?.sub?.startsWith("pending")) continue; + const id = Number(w.scope.slice(6)); + const row = this.db.$client.prepare(`SELECT provider FROM subscriptions WHERE id = ?`).get(id) as { provider?: string } | undefined; + if (row?.provider !== "codex") continue; + await pollCodexLogin(this.db, id).catch(() => "pending"); + } + } + private stop() { if (this.timer) clearInterval(this.timer); this.timer = null; @@ -227,51 +454,108 @@ class LiveHub { if (this.wakeTimer || !this.timer) return; this.wakeTimer = setTimeout(() => { this.wakeTimer = null; - this.check(); + void this.check(); }, WAKE_DEBOUNCE_MS); } - /** Recomputes every watched scope now (tests call it directly). */ - check() { - for (const [scope, set] of this.listeners) { + /** Recomputes every watched scope now (tests call it directly). One check at a time. */ + check(): Promise { + if (this.checking) { + this.again = true; + return this.checking; + } + this.checking = (async () => { + do { + this.again = false; + for (const w of [...this.watches.values()]) await this.checkOne(w); + } while (this.again); + })().finally(() => { + this.checking = null; + }); + return this.checking; + } + + private send(w: Watch, e: LiveEvent) { + for (const fn of w.listeners) { try { - if (scope.startsWith("steps:")) { - const after = this.lastStep.get(scope) ?? 0; - const rows = this.db - .select() - .from(events) - .where(and(eq(events.sessionId, Number(scope.slice(6))), eq(events.type, STEP_EVENT), gt(events.id, after))) - .orderBy(events.id) - .limit(50) - .all(); - if (!rows.length) continue; - this.lastStep.set(scope, rows.at(-1)!.id); - for (const r of rows) for (const fn of set) fn({ type: "step", scope, step: stepView(r) }); - continue; - } - const fp = fingerprint(this.db, scope); - if (fp === this.prints.get(scope)) continue; - this.prints.set(scope, fp); - for (const fn of set) fn({ type: "change", scope }); - } catch (e) { - console.error(`live: ${scope} check failed`, e); + fn(e); + } catch (err) { + console.error(`live: ${w.scope} listener failed`, err); } } } + private async checkOne(w: Watch) { + const scope = w.scope; + try { + if (scope.startsWith("steps:")) { + const rows = this.stepsAfter(scope, w.lastStep ?? 0, 50); + if (!rows.length) return; + w.lastStep = rows.at(-1)!.id; + for (const r of rows) this.send(w, { type: "step", scope, step: stepView(r) }); + return; + } + if (VALUE_SCOPES.has(scope)) { + if (scope === "version") return; // changes only with the process: a reconnect brings it + const before = w.value; + const data = await this.value(w); + if (data !== undefined && w.value !== before) this.send(w, { type: "data", scope, v: liveVersion(w.value!), data }); + return; + } + const parts = fingerprint(this.db, scope, w.userId); + const old = w.parts ?? {}; + const changed = [...new Set([...Object.keys(parts), ...Object.keys(old)])].filter((k) => parts[k] !== old[k]); + if (!changed.length) return; + w.parts = parts; + w.v = liveVersion(JSON.stringify(parts)); + const e: LiveEvent & { type: "change" } = { type: "change", scope, v: w.v, parts: changed }; + if (w.rows && (scope.startsWith("project:") || scope.startsWith("task:"))) { + const rows = taskRows(this.db, scope); + const diff: LiveTaskRow[] = []; + for (const [id, { sig, ...r }] of rows) { + const was = w.rows.get(id); + if (!was) diff.push({ ...r, other: true }); + else if (was.sig !== sig) diff.push({ ...r, other: true }); + else if (was.status !== r.status || was.title !== r.title) diff.push(r); + } + // A story left the board (archived, deleted): the page can't apply that in place. + if ([...w.rows.keys()].some((id) => !rows.has(id))) e.parts.push("gone"); + w.rows = rows; + if (diff.length) e.tasks = diff.slice(0, 100); + } + if (scope === "chats") { + const max = Number(parts.m) || 0; + if (max > (w.chatMax ?? 0)) e.chats = chatsAfter(this.db, w.chatMax ?? 0); + w.chatMax = max; + } + this.send(w, e); + } catch (err) { + console.error(`live: ${scope} check failed`, err); + } + } + get watched(): LiveScope[] { - return [...this.listeners.keys()]; + return [...new Set([...this.watches.values()].map((w) => w.scope))]; + } + + /** Current version of a watched scope (tests, `since`). */ + versionOf(scope: LiveScope, userId = 0): string | undefined { + return this.watches.get(keyOf(scope, userId))?.v; } } -const g = globalThis as { __peppaLiveHub?: LiveHub }; -/** The process-wide hub (survives Next dev module reloads). */ +export type { LiveHub }; + +/** The process-wide hub (survives Next dev module reloads and is shared with the WebSocket server). */ export function liveHub(db: Db): LiveHub { return (g.__peppaLiveHub ??= new LiveHub(db)); } -/** SSE response for /api/live: `change` / `step` events, pings for Cloudflare. */ -export async function liveSse(db: Db, user: User, scopes: LiveScope[], signal: AbortSignal, opts: { pingMs?: number } = {}): Promise { +/** Where the observe database lives (for a test that wants an observe scope). */ +export const liveObservePath = observeDbPath; + +/** SSE response for /api/live (the fallback of the tab's WebSocket): `change` / `step` / `data` events, pings for Cloudflare. */ +export async function liveSse(db: Db, user: User, scopes: LiveScope[], signal: AbortSignal, opts: { pingMs?: number; since?: Record } = {}): Promise { for (const s of scopes) await checkScopeAccess(db, user, s); const enc = new TextEncoder(); let cleanup = () => {}; @@ -303,7 +587,7 @@ export async function liveSse(db: Db, user: User, scopes: LiveScope[], signal: A send("retry: 3000\n\n"); send(`event: ready\ndata: ${JSON.stringify({ scopes })}\n\n`); if (signal.aborted) return close(); - unsubscribe = liveHub(db).subscribe(scopes, (e) => send(`event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`)); + unsubscribe = liveHub(db).subscribe(scopes, (e) => send(`event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`), { userId: user.id, since: opts.since }); }, cancel() { cleanup(); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 35c8d02f..0128d756 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -265,6 +265,9 @@ importers: tailwind-merge: specifier: 3.7.0 version: 3.7.0 + ws: + specifier: 8.18.3 + version: 8.18.3 devDependencies: '@tailwindcss/postcss': specifier: 4.3.5 @@ -374,6 +377,13 @@ importers: drizzle-orm: specifier: 0.45.4 version: 0.45.4(postgres@4.1.1) + ws: + specifier: 8.18.3 + version: 8.18.3 + devDependencies: + '@types/ws': + specifier: 8.18.1 + version: 8.18.1 packages/shared: dependencies: @@ -1272,6 +1282,9 @@ packages: '@types/react@19.3.0': resolution: {integrity: sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==} + '@types/ws@8.18.1': + resolution: {integrity: sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==} + '@xterm/headless@6.0.0': resolution: {integrity: sha512-5Yj1QINYCyzrZtf8OFIHi47iQtI+0qYFPHmouEfG8dHNxbZ9Tb9YGSuLcsEwj9Z+OL75GJqPyJbyoFer80a2Hw==} @@ -2101,6 +2114,18 @@ packages: wrappy@1.0.2: resolution: {integrity: sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==} + ws@8.18.3: + resolution: {integrity: sha512-PEIGCY5tSlUt50cqyMXfCzX+oOPqN0vuGqWzbcJ2xvnkzkq46oOpz7dQaTDBdfICb4N14+GARUDw2XV2N4tvzg==} + engines: {node: '>=10.0.0'} + peerDependencies: + bufferutil: ^4.0.1 + utf-8-validate: '>=5.0.2' + peerDependenciesMeta: + bufferutil: + optional: true + utf-8-validate: + optional: true + y18n@4.0.3: resolution: {integrity: sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==} @@ -2661,6 +2686,10 @@ snapshots: dependencies: csstype: 3.2.3 + '@types/ws@8.18.1': + dependencies: + '@types/node': 26.6.6 + '@xterm/headless@6.0.0': {} '@xterm/xterm@6.0.0': {} @@ -3441,6 +3470,8 @@ snapshots: wrappy@1.0.2: {} + ws@8.18.3: {} + y18n@4.0.3: {} yargs-parser@18.1.3: -- 2.45.2 From 0d86b801ee87dcf9cd50da1b9098c9c33d43038c Mon Sep 17 00:00:00 2001 From: peppa-bot Date: Fri, 20 Nov 2026 21:04:14 +0500 Subject: [PATCH 03/14] =?UTF-8?q?PEP-225:=20=D0=B2=D0=B5=D0=B1=20=D1=87?= =?UTF-8?q?=D0=B5=D1=80=D0=B5=D0=B7=20=D1=81=D0=B2=D0=BE=D0=B9=20=D1=81?= =?UTF-8?q?=D0=B5=D1=80=D0=B2=D0=B5=D1=80=20=D0=B2=20launchd,=20=D0=BF?= =?UTF-8?q?=D0=B5=D1=80=D0=B5=D1=83=D1=81=D1=82=D0=B0=D0=BD=D0=BE=D0=B2?= =?UTF-8?q?=D0=BA=D0=B0=20=D0=B0=D0=B3=D0=B5=D0=BD=D1=82=D0=B0=20=D0=B2?= =?UTF-8?q?=D0=B5=D0=B1=D0=B0=20=D0=BF=D1=80=D0=B8=20=D0=B2=D1=8B=D0=BA?= =?UTF-8?q?=D0=B0=D1=82=D0=BA=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- scripts/install-launchd.sh | 9 +++++---- scripts/live-deploy.sh | 4 ++++ 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/scripts/install-launchd.sh b/scripts/install-launchd.sh index bacd75f4..20035d30 100755 --- a/scripts/install-launchd.sh +++ b/scripts/install-launchd.sh @@ -1,9 +1,10 @@ #!/usr/bin/env bash # Installs Peppa's launchd agents (start at login, restart on crash): # quest.telecom.peppa.watchdog — session watchdog under caffeinate -i (no idle sleep) -# quest.telecom.peppa.web — Next.js platform on :3100 (needs `pnpm --filter @peppa/web build`); -# PEPPA_WEB_MODE=dev runs `next dev` instead (HMR: edits in this -# checkout go live without build or release — the pre-launch setup) +# quest.telecom.peppa.web — Next.js platform on :3100 (needs `pnpm --filter @peppa/web build`) +# through its own server apps/web/server.ts (PEP-225: WebSocket +# /api/ws); a checkout without it (a rollback) — plain `next start`. +# PEPPA_WEB_MODE=dev runs it in dev mode (HMR) # quest.telecom.peppa.bot — Telegram bot (TELEGRAM_BOT_TOKEN in .env) # quest.telecom.peppa.observer — Observability monitors (PEP-202), own DB ~/.peppa/observe.db # quest.telecom.peppa.release — Peppa's own prod releases (PEP-18): started by launchd while @@ -84,7 +85,7 @@ for s in "${SERVICES[@]}"; do /usr/bin/caffeinate -i "$ROOT/packages/cli/bin/peppa" watchdog ;; web) install_agent quest.telecom.peppa.web web.log "$ROOT/apps/web" \ - /bin/bash -c "set -a; . '$ROOT/.env'; set +a; exec '$ROOT/apps/web/node_modules/.bin/next' $WEB_MODE -p 3100" ;; + /bin/bash -c "set -a; . '$ROOT/.env'; set +a; if [ -f server.ts ]; then exec '$NODE_BIN' server.ts $([ "$WEB_MODE" = dev ] && echo --dev) -p 3100; else exec '$ROOT/apps/web/node_modules/.bin/next' $WEB_MODE -p 3100; fi" ;; bot) install_agent quest.telecom.peppa.bot bot.log "$ROOT" "$ROOT/apps/bot/bin/peppa-bot" ;; observer) diff --git a/scripts/live-deploy.sh b/scripts/live-deploy.sh index cf02ee83..b9df4151 100755 --- a/scripts/live-deploy.sh +++ b/scripts/live-deploy.sh @@ -128,6 +128,10 @@ say "built ${TARGET:0:8}" # 7. Restart and health. # PEP-202: the observer is restarted too once it is installed here. restart() { + # PEP-225: the web agent of an older install starts `next start` directly — reinstall it once + # so it goes through apps/web/server.ts (the WebSocket channel); reinstalling restarts it. + local webplist="$HOME/Library/LaunchAgents/quest.telecom.peppa.web.plist" + if [ -f "$webplist" ] && ! grep -q 'server.ts' "$webplist"; then "$ROOT/scripts/install-launchd.sh" web >/dev/null; fi for s in web watchdog bot; do launchctl kickstart -k "gui/$UIDN/quest.telecom.peppa.$s"; done launchctl print "gui/$UIDN/quest.telecom.peppa.observer" >/dev/null 2>&1 && launchctl kickstart -k "gui/$UIDN/quest.telecom.peppa.observer" || true } -- 2.45.2 From 33a830fe07a875e71c90bd48b50c931ba5b428b3 Mon Sep 17 00:00:00 2001 From: peppa-bot Date: Fri, 20 Nov 2026 21:23:35 +0500 Subject: [PATCH 04/14] =?UTF-8?q?PEP-225:=20=D0=BA=D0=BB=D0=B8=D0=B5=D0=BD?= =?UTF-8?q?=D1=82=20=E2=80=94=20=D0=BE=D0=B4=D0=BD=D0=BE=20=D1=81=D0=BE?= =?UTF-8?q?=D0=B5=D0=B4=D0=B8=D0=BD=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=BD=D0=B0?= =?UTF-8?q?=20=D0=B2=D0=BA=D0=BB=D0=B0=D0=B4=D0=BA=D1=83,=20=D0=BE=D1=81?= =?UTF-8?q?=D1=82=D1=80=D0=BE=D0=B2=D0=B0=20=D0=B4=D0=BE=D1=81=D0=BA=D0=B8?= =?UTF-8?q?=20=D0=B8=20=D1=81=D1=82=D0=B0=D1=82=D1=83=D1=81=D0=B0,=20?= =?UTF-8?q?=D0=B1=D0=B5=D0=B7=20=D0=BE=D0=BF=D1=80=D0=BE=D1=81=D0=BE=D0=B2?= =?UTF-8?q?;=20=D1=82=D0=B5=D1=81=D1=82=D1=8B=20=D0=BA=D0=B0=D0=BD=D0=B0?= =?UTF-8?q?=D0=BB=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- apps/web/app/(app)/chats/[chat]/page.tsx | 3 +- .../web/app/(app)/observability/[id]/page.tsx | 4 +- apps/web/app/(app)/observability/page.tsx | 4 +- apps/web/app/(app)/subscriptions/page.tsx | 5 +- apps/web/app/(app)/t/[key]/page.tsx | 3 +- apps/web/app/api/live/route.ts | 9 +- apps/web/components/AgentSteps.tsx | 29 +- apps/web/components/AttentionBadge.tsx | 59 ++- apps/web/components/AutoRefresh.tsx | 19 - apps/web/components/Board.tsx | 21 +- apps/web/components/LiveRefresh.tsx | 191 ++++---- apps/web/components/LiveTaskStatus.tsx | 25 ++ apps/web/components/OpenBotButton.tsx | 15 +- apps/web/components/RunnerTerminal.tsx | 60 +-- apps/web/components/Sidebar.tsx | 13 +- apps/web/components/SubscriptionSetup.tsx | 6 +- apps/web/components/VersionWatch.tsx | 36 +- apps/web/lib/live-server.ts | 2 +- apps/web/lib/live.ts | 413 ++++++++++++++++++ packages/runner/src/live-ws.ts | 2 + packages/runner/src/live.ts | 5 +- packages/shared/src/i18n/en/runner.ts | 3 + packages/shared/src/i18n/en/story.ts | 4 +- packages/shared/src/i18n/kk/runner.ts | 3 + packages/shared/src/i18n/kk/story.ts | 4 +- packages/testkit/test/live-ws.test.ts | 228 ++++++++++ packages/testkit/test/story-live.test.ts | 6 +- 27 files changed, 904 insertions(+), 268 deletions(-) delete mode 100644 apps/web/components/AutoRefresh.tsx create mode 100644 apps/web/components/LiveTaskStatus.tsx create mode 100644 apps/web/lib/live.ts create mode 100644 packages/testkit/test/live-ws.test.ts diff --git a/apps/web/app/(app)/chats/[chat]/page.tsx b/apps/web/app/(app)/chats/[chat]/page.tsx index 3cc3fdcb..c7a3848b 100644 --- a/apps/web/app/(app)/chats/[chat]/page.tsx +++ b/apps/web/app/(app)/chats/[chat]/page.tsx @@ -225,7 +225,8 @@ export default async function ChatPage({ params, searchParams }: { params: Promi return ( - + {/* PEP-225: a project chat re-renders only for its own new messages; the master feed gathers every project. */} +

{t("Чаты")}

diff --git a/apps/web/app/(app)/observability/[id]/page.tsx b/apps/web/app/(app)/observability/[id]/page.tsx index 3bc634a2..3a992d66 100644 --- a/apps/web/app/(app)/observability/[id]/page.tsx +++ b/apps/web/app/(app)/observability/[id]/page.tsx @@ -4,7 +4,7 @@ import { notFound } from "next/navigation"; import { Activity, Pause, Play, Trash2 } from "lucide-react"; import { describeTarget, getMonitor, isSuperadmin, monitorChecks, monitorIncidents, monitorView } from "@peppa/core"; import { loadEnv } from "@peppa/shared"; -import { AutoRefresh } from "@/components/AutoRefresh"; +import { LiveRefresh } from "@/components/LiveRefresh"; import { Hidden } from "@/components/cards"; import { CheckStrip, KIND_LABEL, MonitorFields, pct, StateBadge } from "@/components/Observability"; import { ago, Disclosure, Empty, Flash, PageHeader, Section } from "@/components/common"; @@ -36,7 +36,7 @@ export default async function MonitorPage({ params, searchParams }: { params: Pr const web = loadEnv().PEPPA_WEB_URL; return ( - +