PEP-228: новые сообщения чата появляются без перерисовки страницы #220
@ -1,16 +1,17 @@
|
||||
# Память проекта
|
||||
|
||||
Пишет агент через MCP `remember` (PEP-30). Не повторяй AGENTS.md — здесь только то, чего там нет или что легко пропустить.
|
||||
Пишет агент через `remember` (PEP-30); не повторяй AGENTS.md.
|
||||
|
||||
## Команды
|
||||
- Тесты из шелла Claude: `env -u NODE_TEST_CONTEXT -u NODE_TEST_WORKER_ID node --test --test-reporter=spec test/<file>.test.ts` (иначе node --test и `pnpm run ci` молча ничего не запускают). В свежем worktree сначала `pnpm install --frozen-lockfile`.
|
||||
- Экраны без живых данных: `PEPPA_HOME=<tmp> PEPPA_DB=<tmp>/peppa.db PEPPA_SECRET=x peppa db migrate`, `DATABASE_URL=<tmp>/peppa.db node apps/web/scripts/mock-ui-seed.ts mock-pm`, `next dev -p <порт>` в apps/web с тем же env, `PEPPA_WEB_URL=http://localhost:<порт>` и `PEPPA_RUNNER_MODE=inline PEPPA_ROTATE=off`; `peppa web login-link mock-pm` (суперадмину — `peppa platform allow <login>`); страницы — curl с cookie; «Инженер» — settings `ui.mode:<userId>` = `"engineer"`. Подписок mock-ui-seed не создаёт — вставь через sqlite3 subscriptions, пул, `projects.subscription_pool_id`.
|
||||
- Экраны без живых данных: `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"`.
|
||||
- CLI из worktree против живой системы: `set -a; . /Users/telecom/Dev/Peppa/.env; set +a` и `<worktree>/packages/cli/bin/peppa …`.
|
||||
- Словарь: `pnpm lint`; почистил тексты экрана — `pnpm lint --update` (baseline только уменьшать); новое слово в «Нельзя» — сразу `pnpm lint`, оно может стоять в чужих текстах.
|
||||
|
||||
## Грабли
|
||||
- `resumeSession` у сессии без `conversationId` пишет событие `started`, не `resumed`. Скриншоты staging (PEP-209) идут отчётом `screenshots` с `env`.
|
||||
- `next dev` правит apps/web/AGENTS.md (он в git — `git checkout`, не `rm`) и next-env.d.ts — не коммитить. Открывать `http://localhost:<порт>`, не 127.0.0.1 (allowedDevOrigins — без гидрации кнопки молчат).
|
||||
- Headless Chrome (Mac): playwright-core из `~/.hermes/hermes-agent/node_modules`, `chrome-headless-shell` из `~/Library/Caches/ms-playwright`, cookie из curl-jar; getUserMedia подменяй; обрыв канала — `globalThis.__peppaLive.ws.close()`. Без браузера канал проверяй WebSocket-клиентом Node (`headers: {cookie, origin}`).
|
||||
- Headless Chrome: playwright-core (`~/.hermes/hermes-agent/node_modules/playwright-core`) + `chrome-headless-shell` из `~/Library/Caches/ms-playwright`, cookie из curl-jar в `ctx.addCookies`; fake-audio нет — подменяй getUserMedia. На Mac нет `timeout`. Свежий `next dev` первую минуту перезагружает вкладку (сборка) — подожди, прежде чем кликать.
|
||||
- CLI из теста с моком в том же процессе — только async execFile. Тест testkit не импортирует apps/web статически (типы Next ломают ProcessEnv) — `import(new URL(…).href)`.
|
||||
- Шаблонная строка с t()/m() внутри (`` `<b>${t("…")}</b>` ``) i18n-check считает непереведённой — собирай конкатенацией. В apps/bot `m` импортирован как `tr`.
|
||||
@ -18,7 +19,7 @@
|
||||
- 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`; N+1 по проектам — `workLineIndex`. Не `pkill -f next-server` — убьёт живой веб.
|
||||
- Скорость: замер `apps/web/scripts/bench-pages.ts`, канал — `bench-live.ts` (копию базы сначала `peppa db migrate`, иначе без индексов PEP-214 в 15 раз медленнее); N+1 по проектам — `workLineIndex`. `liveHub` на globalThis переживает HMR — после правок live.ts перезапусти server.ts. Не `pkill -f next-server` — убьёт живой веб.
|
||||
- Хук грузит только лёгкий `runner/limit-delay.ts`, не flow.ts. В тесте хука PEPPA_GENERATION = поколение сессии (вставленной руками — 0).
|
||||
- Память ветки при мерже main склеивается построчно и разрастается дублями — после конфликта в `.peppa/memory.md` убери повторы (тест project-memory-size.test.ts).
|
||||
- QuickJS (PEP-212): строки из хост-функции читай синхронно до await (хэндлы аргументов слабые); все хэндлы и deferred dispose-ить, иначе rt.dispose падает.
|
||||
@ -28,11 +29,11 @@
|
||||
|
||||
## Соглашения
|
||||
- Специалисты (PEP-183): агент с непустым character — специалист; подбор — `runner/team-match.ts` (haiku, `PEPPA_TEAM_BIN`), результат `team.match:<taskId>`, порог ожидания `platform.team.waitMin`; в `ensureSessionAgent` порядок: прежний → свободный специалист по профилю → универсал → специалист без очереди.
|
||||
- i18n (PEP-98): текст пользователю — ключ = русская строка в `t()`/`m()` + перевод в `i18n/en/<раздел>.ts` и `i18n/kk/<раздел>.ts` (тесты i18n-check и i18n-kk падают без перевода). Ключ-шаблон, кончающийся плейсхолдером, — специфичный. «Peppa FACTORY» не склоняется; в kk окончание через дефис (Peppa FACTORY-нің); к {плейсхолдеру} kk-окончание не клеить — фраза вокруг именительного («Жаңа {task}»); `wording(mode,"kk")` отдаёт именительный. Тексты агентам (RULES.md, промпты) говорят «Пеппа» — не трогаем.
|
||||
- i18n (PEP-98): текст пользователю — ключ = русская строка в `t()`/`m()` + перевод в `i18n/en|kk/<раздел>.ts` (иначе падают i18n-check/i18n-kk). «Peppa FACTORY» не склоняется (kk: Peppa FACTORY-нің); к {плейсхолдеру} kk-окончание не клеить. Тексты агентам говорят «Пеппа» — не трогаем.
|
||||
- Слова по режиму (PEP-123): в вебе «стори»/«раннер» строкой не пишем — `w.task("acc")`, `w.runner()` из `await words()` / `useWords()`, инженерное — под `w.engineer`; тексты без читателя (чаты, Telegram, push, core) — «задача», «агент», «вы».
|
||||
- Экраны «Продакт» (PEP-120/122): вид — чистая функция в core с текстами в одном объекте (`storyProductView`, `core/help-texts.ts` ru/kk/en), инженерное — под «Подробнее» (`?more=1`); тест сверяет ru с «Нельзя» docs/glossary.md.
|
||||
- Инструкция подключения к своему Claude/ChatGPT (PEP-135): `/help/connect`, тексты — `core/connect-texts.ts` (`CONNECT_HELP` ru/kk/en одной формы, тест `connect-help.test.ts`); изменились экраны подключения или инструменты удалённого MCP — править её; копирование — `<CopyText>`.
|
||||
- Словарь в сообщениях ядра (PEP-129/137): `pnpm lint` в packages/core|runner|mcp проверяет литералы внутри `m()/tr()/t()/t.n()`; подсказку агенту в `m()` не оборачивать. Запрещённое слово там роняет lint сразу, `--update` не поможет: переписать (ключ = русская строка — поменять в `i18n/en`, `i18n/kk` и тестах) или `glossary-ignore: <почему>` строкой выше (читает инженер); текст человеку мимо словаря переводов — `glossary-user: <почему>`. Разбор словаря — `@peppa/shared/glossary`.
|
||||
- Словарь в сообщениях ядра (PEP-129/137): `pnpm lint` проверяет литералы в `m()/tr()/t()` packages/core|runner|mcp; подсказку агенту в `m()` не оборачивать; запрещённое слово — переписать (ключ и в `i18n/en|kk`, тестах) или `glossary-ignore: <почему>` строкой выше; человеку мимо переводов — `glossary-user: <почему>`.
|
||||
- Без повторов (PEP-151): `raiseSessionQuestion`/`askPm` при том же состоянии задачи (отпечаток, `core/message-state.ts`) не создают вопрос, а обновляют прежний и возвращают его id (закрытый открывается снова); свободный текст агента — `topic: "turn"`, «готово» — `topic: "review"`.
|
||||
- Служебный текст (PEP-154): текст агента/терминала человеку — через `core/user-text.ts` (`userText`; `stripServiceBlocks` — для слов человека); `raiseSessionQuestion`/`askPm`/`addChatMessage` чистят сами, пусто → PeppaError, исходник — `questionDetails` (инженер/суперадмин). Текст исключения владельцу не слать: `platformFailure` даёт строку только для PeppaError, иначе null (ушло суперадмину и в учёт ошибок).
|
||||
- Типы сообщений (PEP-149): пишешь пользователю — выбери тип: вопрос только с вариантами (`askPm`/`raiseSessionQuestion` с `msgType`, `defaultOption`), «готово» — только `sendReviewCard`, ход работы/блокер — события `progress`/`blocker`; читать тип — `questionType`/`needsPerson` (core/questions.ts), не `kind === "attention"`.
|
||||
@ -40,9 +41,11 @@
|
||||
- Чужой текст в сообщениях (PEP-139/140): слова человека/модели, название задачи/проекта, логин, варианты агента, причину извне подставляй в `m()` как `asIs(…)` (shared/i18n) — перевод их не трогает; фразы самой фабрики (`PeppaError`, причина гейта) не помечай. Вопрос агента = `questionIsFreeText`, текст переводящему читателю — `questionText(q)`; MCP, CLI, агенту и сравнение текста в тестах — `stripAsIs`.
|
||||
- Один голос (PEP-198): человеку пишет только Аналитик — вопрос агента через `relayAgentQuestion` (runner/question-relay.ts; `runner/agent-relay.ts` — это релей песочницы, не путать), задачи из чата — только оффер `stories` и кнопка; новая строка сообщения роли — в `ROLE_MESSAGE_KEYS` выше «Агент {name}», иначе он её съест.
|
||||
- Тесты: места подписки занимай `core.createSession` с `subscriptionId`; задачу из очереди ёмкости убирай `moveTask(backlog)`, иначе её подхватит тик соседнего теста. Конец хода агента вопроса не создаёт — жди статус сессии `idle`. Сообщения суперадмина — `superadmin()` из helpers.ts. Текст из `chat_messages` сравнивай через `stripAsIs`.
|
||||
- Узкие места: раннер — `pickSubscription`/`rotationCandidate`; агент, модель, сообщение — `startRunner`/`resumeSession`, `claudePrint`, `deliverToUser` (или `isProjectPaused`); проекты — `listProjects(db)`/`userProjectIds` (`from(projects)` — с `isNull(deletedAt)`); действие веба с агентами — через runnerCall.
|
||||
- Узкие места: подписка — `pickSubscription`/`rotationCandidate`; агент — `startRunner`/`resumeSession`, модель — `claudePrint`, сообщение — `deliverToUser`; проекты — `listProjects`/`userProjectIds` (`from(projects)` — с `isNull(deletedAt)`); веб с агентами — runnerCall.
|
||||
- Вопрос ≠ задача (PEP-153): текст человека, который может стать задачей, — через `classifyMessage` (runner/message-intent.ts; в тестах mock-intake роль `intent`); молча задачу не заводить — кнопки (`chat.offer:<messageId>`, `INTENT_TEXT`).
|
||||
- Задачу агента заводи через createTask с origin (acceptance|incident|analyst) и fileStories/checkDuplicate (PEP-197); «Предложено» = backlog + tasks.proposed, readyBacklog их не отдаёт; автомерж задач агента — по autonomy.acceptOwn (mayAutoAcceptTask).
|
||||
- Неудачная версия (PEP-158): `rolled_back`/`failed` → агенту задачи, `returnFailedRelease` (runner/deploy-feedback.ts); счётчик — `attempts` задержки `deploy` (3 — суперадмину, 6 — стоп).
|
||||
- Чат проекта на месте (PEP-228): новые сообщения — область `chat:<id>` (на зрителя), вид — `apps/web/lib/chat-live.ts` (`setLiveChatView`), рисует `ChatLiveFeed`; меняешь вид сообщения на странице чата — поменяй и там.
|
||||
- Bugsink API (PEP-218): схема — `GET /api/canonical/0/schema/` (2.6.3); `q` = текст + теги `key:value`; числа пользователей нет. Экран — `core/bugsink-errors.ts` (кэш 45 с), действия — `runner/bugsink-errors.ts`.
|
||||
|
||||
## Решения
|
||||
|
||||
@ -10,6 +10,7 @@ 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";
|
||||
@ -24,7 +25,7 @@ import { requireUser, words } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { cleanText } from "@/lib/chat-text";
|
||||
import { cleanText, messageLink, STUCK_NOTICE } from "@/lib/chat-text";
|
||||
import { chatOfferAction, linkChatAction, postChatAction, unlinkChatAction } from "../actions";
|
||||
|
||||
type Params = { error?: string; thread?: string; link?: string; q?: string; list?: string };
|
||||
@ -223,9 +224,31 @@ export default async function ChatPage({ params, searchParams }: { params: Promi
|
||||
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>
|
||||
<LiveRefresh scope="chats" indicator={false} />
|
||||
{/* 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>
|
||||
|
||||
@ -284,32 +307,33 @@ export default async function ChatPage({ params, searchParams }: { params: Promi
|
||||
</p>
|
||||
)}
|
||||
|
||||
{ordered.length === 0 ? (
|
||||
<Empty>{discussion ? t("Напишите, что хотите узнать или сделать, — аналитик ответит здесь же. Например: «Что сейчас в работе?» или «Хочу страницу с отзывами клиентов».") : master ? t("Пока тихо: здесь появятся вопросы агентов, сбои и обновления ваших проектов.") : thread === undefined ? t("Сообщений пока нет: они появятся, когда агенты возьмутся за {tasks}.", { tasks: w.task("accPl") }) : t("В этом треде пока пусто.")}</Empty>
|
||||
{master ? (
|
||||
<>
|
||||
{feed}
|
||||
<div data-chat-end />
|
||||
<ChatScroll lastId={ordered.at(-1)?.id ?? 0} />
|
||||
</>
|
||||
) : (
|
||||
<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>
|
||||
<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>
|
||||
)}
|
||||
{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>
|
||||
)}
|
||||
<div data-chat-end />
|
||||
<ChatScroll lastId={ordered.at(-1)?.id ?? 0} />
|
||||
|
||||
{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">
|
||||
@ -334,7 +358,6 @@ export default async function ChatPage({ params, searchParams }: { params: Promi
|
||||
);
|
||||
}
|
||||
|
||||
const STUCK_NOTICE = /задерживается на нашей стороне/i;
|
||||
|
||||
type Group = { kind: "events"; items: ChatMessageView[] } | { kind: "message"; m: ChatMessageView };
|
||||
|
||||
@ -386,13 +409,6 @@ async function EventLines({ items, firstUnreadId, taskStatus, agentName, masterV
|
||||
);
|
||||
}
|
||||
|
||||
/** A link under a message: never the bare «/», never Gitea for a product manager. */
|
||||
function messageLink(url: string | null, superadmin: boolean, gitea: string): string | null {
|
||||
if (!url || url === "/" || url === "#") return null;
|
||||
if (!superadmin && gitea && url.startsWith(gitea)) return null;
|
||||
return url;
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
"use server";
|
||||
// «Чаты» (PEP-62): a message into a chat/thread, Telegram group link/unlink. Access — chatForUser.
|
||||
|
||||
import { parseAttachmentIds, chatForUser, createChatLinkCode, isSuperadmin, PeppaError, unlinkChat } from "@peppa/core";
|
||||
import { parseAttachmentIds, chatForUser, createChatLinkCode, isSuperadmin, markDiscussionRead, markThreadRead, PeppaError, THREAD_KEY, unlinkChat } from "@peppa/core";
|
||||
import { postToChat, resolveChatOffer, type ChatOfferChoice } from "@peppa/runner";
|
||||
import { loadEnv } from "@peppa/shared";
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
@ -36,6 +36,18 @@ export async function postChatAction(f: FormData) {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* PEP-228: messages drawn in place on an open chat page are read — the discussion (thread null)
|
||||
* or one thread. No redirect: the page stays as it is.
|
||||
*/
|
||||
export async function markChatReadAction(chatId: number, thread: string | null): Promise<void> {
|
||||
const user = await requireUser();
|
||||
const chat = await chatForUser(db, user, Number(chatId)).catch(() => null);
|
||||
if (!chat || chat.kind !== "project") return;
|
||||
if (thread == null) await markDiscussionRead(db, user.id, chat.id);
|
||||
else if (typeof thread === "string" && THREAD_KEY.test(thread)) await markThreadRead(db, user.id, chat.id, thread);
|
||||
}
|
||||
|
||||
/** PEP-153: a button under a chat message — «Завести как задачу», «Ответить», «Создать», «Отмена». */
|
||||
export async function chatOfferAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
|
||||
@ -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 (
|
||||
<Workspace>
|
||||
<AutoRefresh everyMs={15_000} />
|
||||
<LiveRefresh scope="observe" />
|
||||
<div className="max-w-4xl">
|
||||
<Flash error={error} />
|
||||
<PageHeader
|
||||
|
||||
@ -4,7 +4,7 @@ import { notFound } from "next/navigation";
|
||||
import { Activity, Pause, Play, Plus } from "lucide-react";
|
||||
import { describeTarget, egovLoginSummary, errorScope, errorsOverview, isSuperadmin, listErrors, listMonitorViews } 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 { ErrorFilters, errorFilterFrom, ErrorRows, ErrorsDown, ErrorsSummary } from "@/components/Errors";
|
||||
@ -76,7 +76,6 @@ export default async function Observability({ searchParams }: { searchParams: Pr
|
||||
if (sp.tab === "errors") {
|
||||
return (
|
||||
<Workspace>
|
||||
<AutoRefresh everyMs={60_000} />
|
||||
<div className="max-w-4xl">
|
||||
<Flash error={error} />
|
||||
<PageHeader title={<><Activity className="mr-1 inline size-5 text-primary" />{t("Observability")}</>}>
|
||||
@ -95,7 +94,7 @@ export default async function Observability({ searchParams }: { searchParams: Pr
|
||||
const degraded = monitors.filter((m) => !m.paused && m.state === "degraded").length;
|
||||
return (
|
||||
<Workspace>
|
||||
<AutoRefresh everyMs={15_000} />
|
||||
<LiveRefresh scope="observe" />
|
||||
<div className="max-w-4xl">
|
||||
<Flash error={error} />
|
||||
<PageHeader title={<><Activity className="mr-1 inline size-5 text-primary" />{t("Observability")}</>}>
|
||||
|
||||
@ -4,7 +4,7 @@ import { getQuestion, isSuperadmin, listSubscriptions, OPENCODE_KEY_ENV, PROVIDE
|
||||
import { pendingLogin, pollCodexLogin, type PendingLogin, backfillCodexAccounts, openSubscriptionRequests } from "@peppa/runner";
|
||||
import { answerQuestion } from "@/app/(app)/actions";
|
||||
import { LocalTime } from "@/components/LocalTime";
|
||||
import { AutoRefresh } from "@/components/AutoRefresh";
|
||||
import { LiveRefresh } from "@/components/LiveRefresh";
|
||||
import { PoolCapacity, PoolSubscriptions, PoolSummary, PoolSwitches } from "@/components/PoolSubscriptions";
|
||||
import { Hidden } from "@/components/cards";
|
||||
import { ago, Disclosure, Empty, Flash, Notice, PageHeader, Section } from "@/components/common";
|
||||
@ -296,7 +296,8 @@ export default async function Subscriptions({ searchParams }: { searchParams: Pr
|
||||
|
||||
return (
|
||||
<Workspace>
|
||||
{[...logins.values()].some((l) => l.kind === "codex") && <AutoRefresh everyMs={3000} />}
|
||||
<LiveRefresh scope="subs" />
|
||||
{[...logins.entries()].filter(([, l]) => l.kind === "codex").map(([id]) => <LiveRefresh key={id} scope={`login:${id}`} indicator={false} />)}
|
||||
<div className="max-w-3xl">
|
||||
<Flash error={error} />
|
||||
<PageHeader title={<><KeyRound className="mr-1 inline size-5 text-primary" />{t("Подписки")}</>}>
|
||||
|
||||
@ -55,6 +55,7 @@ import { PanelSection } from "@/components/ActivityAside";
|
||||
import { Hidden, SessionCard } from "@/components/cards";
|
||||
import { ago, Disclosure, Flash, PageHeader, Section, StatusBadge } from "@/components/common";
|
||||
import { LiveRefresh } from "@/components/LiveRefresh";
|
||||
import { LiveTaskStatus } from "@/components/LiveTaskStatus";
|
||||
import { TaskRunnerSettings } from "@/components/Runners";
|
||||
import { TaskAgentModel } from "@/components/AgentModel";
|
||||
import { Button } from "@/components/ui/button";
|
||||
@ -431,7 +432,7 @@ export default async function StoryPage({ params, searchParams }: { params: Prom
|
||||
}
|
||||
title={
|
||||
<>
|
||||
<span className="font-mono text-primary">{ref.key}</span> {task.title} {engineer && <StatusBadge status={task.status} />}
|
||||
<span className="font-mono text-primary">{ref.key}</span> {task.title} {engineer && <LiveTaskStatus taskId={task.id} status={task.status} />}
|
||||
{pendingAccept && <Badge variant="ok" className="ml-1.5 align-middle whitespace-normal">{t.text(PENDING_ACCEPT_LABEL)}</Badge>}
|
||||
{engineer && delayed && <Badge variant="muted" className="ml-1.5 align-middle whitespace-normal">{t.text(delayLine ?? PLATFORM_DELAY_LABEL)}</Badge>}
|
||||
{task.archivedAt && <Badge variant="muted" className="ml-1.5 align-middle">{t("в архиве")}</Badge>}
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
// Live updates (PEP-37): SSE of `change` (a watched scope changed — refresh) and `step`
|
||||
// (an agent's tool call, PEP-33) events. ?scope=home | runners | project:<id> | task:<id> | steps:<sessionId>, comma-separated.
|
||||
// Live updates (PEP-37): SSE of `change` (a watched scope changed), `step` (an agent's tool call,
|
||||
// PEP-33) and `data` events — since PEP-225 the fallback of the tab's WebSocket /api/ws. ?scope=home | runners | project:<id> | task:<id> | steps:<sessionId>, comma-separated.
|
||||
import { LiveError, liveSse, parseScopes } from "@peppa/runner";
|
||||
import { currentUser } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
@ -14,7 +14,10 @@ export async function GET(req: Request) {
|
||||
const user = await currentUser();
|
||||
if (!user) return fail(401, m("Нужен вход"));
|
||||
try {
|
||||
return await liveSse(db, user, parseScopes(new URL(req.url).searchParams.get("scope")), req.signal);
|
||||
const q = new URL(req.url).searchParams;
|
||||
// PEP-225: `since.<scope>=<version>` — what the tab saw before a drop (fallback of the WebSocket).
|
||||
const since = Object.fromEntries([...q].filter(([k]) => k.startsWith("since.")).map(([k, v]) => [k.slice(6), v]));
|
||||
return await liveSse(db, user, parseScopes(q.get("scope")), req.signal, { since });
|
||||
} catch (e) {
|
||||
if (e instanceof LiveError) return fail(e.status, e.message);
|
||||
console.error("live:", e);
|
||||
|
||||
@ -4,6 +4,7 @@ import { useEffect, useState } from "react";
|
||||
import { Bot, FilePen, FileText, FlaskConical, Globe, Plug, Search, SquareTerminal, Wrench, type LucideIcon } from "lucide-react";
|
||||
import type { StepKind, StepView } from "@peppa/core";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useLive } from "@/lib/live";
|
||||
import { useT } from "@/components/I18n";
|
||||
import { m, type Translator } from "@peppa/shared/i18n";
|
||||
|
||||
@ -52,22 +53,22 @@ export function AgentSteps({ sessionId, initial, live, hooks = true, plain = fal
|
||||
|
||||
useEffect(() => setSteps((cur) => merge(initial, cur)), [initial]);
|
||||
|
||||
// The «N с назад» clock only (no data is fetched on it).
|
||||
useEffect(() => {
|
||||
const timer = setInterval(() => setNow(Date.now()), 10_000);
|
||||
if (!live || typeof EventSource === "undefined") return () => clearInterval(timer);
|
||||
const es = new EventSource(`/api/live?scope=steps:${sessionId}`);
|
||||
es.addEventListener("step", (e) => {
|
||||
try {
|
||||
const { step } = JSON.parse((e as MessageEvent).data) as { step: StepView };
|
||||
setSteps((cur) => merge([step], cur));
|
||||
setNow(Date.now());
|
||||
} catch {}
|
||||
});
|
||||
return () => {
|
||||
clearInterval(timer);
|
||||
es.close();
|
||||
};
|
||||
}, [sessionId, live]);
|
||||
return () => clearInterval(timer);
|
||||
}, []);
|
||||
|
||||
// PEP-225: new steps over the tab's live channel; a hidden tab drops them and catches up on return.
|
||||
useLive(
|
||||
live ? `steps:${sessionId}` : null,
|
||||
(e) => {
|
||||
if (e.type !== "step") return;
|
||||
setSteps((cur) => merge([e.step as unknown as StepView], cur));
|
||||
setNow(Date.now());
|
||||
},
|
||||
{ heavy: true },
|
||||
);
|
||||
|
||||
if (!steps.length)
|
||||
return (
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
import { FileSpreadsheet, FileText, Presentation } from "lucide-react";
|
||||
import { humanSize, type AttachmentView } from "@peppa/core";
|
||||
import type { AttachmentView } from "@peppa/core";
|
||||
import { humanSize } from "@peppa/shared/format";
|
||||
|
||||
/**
|
||||
* PEP-159: files of a message, a comment or a story — pictures as thumbnails that open large,
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef } from "react";
|
||||
import { useLive } from "@/lib/live";
|
||||
|
||||
const PREFIX = /^\(\d+\) /;
|
||||
|
||||
@ -25,53 +26,45 @@ function chime() {
|
||||
}
|
||||
|
||||
/**
|
||||
* «(N) …» in the tab title and the app badge (PEP-55): what waits for the user. Polls
|
||||
* /api/attention; a growing count plays a chime if sound is on in the settings.
|
||||
* «(N) …» in the tab title and the app badge (PEP-55): what waits for the user. The count comes
|
||||
* from the live channel (`attention`, PEP-225) the moment it changes; a growing count plays a
|
||||
* chime if sound is on in the settings.
|
||||
*/
|
||||
export function AttentionBadge({ count: initial, sound: initialSound, everyMs = 20_000 }: { count: number; sound: boolean; everyMs?: number }) {
|
||||
export function AttentionBadge({ count: initial, sound: initialSound }: { count: number; sound: boolean }) {
|
||||
const count = useRef(initial);
|
||||
const sound = useRef(initialSound);
|
||||
|
||||
const apply = () => {
|
||||
const base = document.title.replace(PREFIX, "");
|
||||
const want = count.current > 0 ? `(${count.current}) ${base}` : base;
|
||||
if (document.title !== want) document.title = want;
|
||||
const nav = navigator as Navigator & { setAppBadge?: (n?: number) => Promise<void>; clearAppBadge?: () => Promise<void> };
|
||||
if (count.current > 0) nav.setAppBadge?.(count.current).catch(() => {});
|
||||
else nav.clearAppBadge?.().catch(() => {});
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const apply = () => {
|
||||
const base = document.title.replace(PREFIX, "");
|
||||
const want = count.current > 0 ? `(${count.current}) ${base}` : base;
|
||||
if (document.title !== want) document.title = want;
|
||||
const nav = navigator as Navigator & { setAppBadge?: (n?: number) => Promise<void>; clearAppBadge?: () => Promise<void> };
|
||||
if (count.current > 0) nav.setAppBadge?.(count.current).catch(() => {});
|
||||
else nav.clearAppBadge?.().catch(() => {});
|
||||
};
|
||||
apply();
|
||||
// Next sets the title on navigation: put the counter back.
|
||||
const titleObserver = new MutationObserver(apply);
|
||||
titleObserver.observe(document.head, { subtree: true, childList: true, characterData: true });
|
||||
return () => titleObserver.disconnect();
|
||||
}, []);
|
||||
|
||||
const poll = async () => {
|
||||
if (document.visibilityState !== "visible") return;
|
||||
try {
|
||||
const r = await fetch("/api/attention", { cache: "no-store" });
|
||||
if (!r.ok) return;
|
||||
const j = (await r.json()) as { count: number; sound: boolean };
|
||||
sound.current = j.sound;
|
||||
if (j.count > count.current && sound.current) chime();
|
||||
count.current = j.count;
|
||||
apply();
|
||||
} catch {}
|
||||
};
|
||||
const id = setInterval(poll, everyMs);
|
||||
document.addEventListener("visibilitychange", poll);
|
||||
return () => {
|
||||
clearInterval(id);
|
||||
titleObserver.disconnect();
|
||||
document.removeEventListener("visibilitychange", poll);
|
||||
};
|
||||
}, [everyMs]);
|
||||
useLive("attention", (e) => {
|
||||
if (e.type !== "data") return;
|
||||
const d = e.data as { count: number; sound: boolean };
|
||||
sound.current = d.sound;
|
||||
if (d.count > count.current && sound.current) chime();
|
||||
count.current = d.count;
|
||||
apply();
|
||||
});
|
||||
|
||||
// A server re-render (router.refresh) brings a fresh count too.
|
||||
// A server re-render brings a fresh count too.
|
||||
useEffect(() => {
|
||||
if (initial > count.current && sound.current) chime();
|
||||
count.current = initial;
|
||||
document.title = initial > 0 ? `(${initial}) ${document.title.replace(PREFIX, "")}` : document.title.replace(PREFIX, "");
|
||||
apply();
|
||||
}, [initial]);
|
||||
|
||||
return null;
|
||||
|
||||
@ -1,19 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect } from "react";
|
||||
|
||||
/** Re-renders server data every few seconds, unless the user is typing (or left an unsent draft). */
|
||||
export function AutoRefresh({ everyMs = 5000 }: { everyMs?: number }) {
|
||||
const router = useRouter();
|
||||
useEffect(() => {
|
||||
const id = setInterval(() => {
|
||||
const el = document.activeElement;
|
||||
const typing = el instanceof HTMLTextAreaElement || (el instanceof HTMLInputElement && el.type === "text");
|
||||
const draft = [...document.querySelectorAll<HTMLTextAreaElement | HTMLInputElement>("textarea, input[type=text]")].some((i) => i.value !== i.defaultValue);
|
||||
if (!typing && !draft && document.visibilityState === "visible") router.refresh();
|
||||
}, everyMs);
|
||||
return () => clearInterval(id);
|
||||
}, [router, everyMs]);
|
||||
return null;
|
||||
}
|
||||
@ -4,6 +4,7 @@ import { useWords } from "@/components/Words";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useState, useTransition } from "react";
|
||||
import { useLiveIsland } from "@/lib/live";
|
||||
import { ChevronDown, ChevronRight, ChevronsDown, ChevronsUp, Lock } from "lucide-react";
|
||||
import { moveTaskCard, proposalAction } from "@/app/(app)/actions";
|
||||
import { reorderTaskInline } from "@/app/(app)/board-actions";
|
||||
@ -95,7 +96,25 @@ const NEXT: Partial<Record<Column, { to: Column; label: string }>> = {
|
||||
* starts/stops agents; drag it onto a card of its own column to change the order (= priority
|
||||
* for the dispatcher, PEP-34). «Готово» can be collapsed (remembered in the browser).
|
||||
*/
|
||||
export function Board({ cards, back }: { cards: Card[]; back: string }) {
|
||||
export function Board({ cards: server, back }: { cards: Card[]; back: string }) {
|
||||
// PEP-225: status and title changes from the live channel apply in place — a card moves to the
|
||||
// column of its new status at once; fresh server data (a re-render) replaces the patches.
|
||||
const [patches, setPatches] = useState<Map<number, Pick<Card, "status" | "title" | "column">>>(() => new Map());
|
||||
useEffect(() => setPatches(new Map()), [server]);
|
||||
const cards = patches.size ? server.map((c) => (c.id != null && patches.has(c.id) ? { ...c, ...patches.get(c.id)! } : c)) : server;
|
||||
useLiveIsland((e) => {
|
||||
if (!e.tasks?.length) return [];
|
||||
const byId = new Map(server.map((c) => [c.id, c]));
|
||||
const next: Array<[number, Pick<Card, "status" | "title" | "column">]> = [];
|
||||
let all = true;
|
||||
for (const r of e.tasks) {
|
||||
// A new story, one outside the epic filter, or a change of its epic/order/«Предложено» — the server re-renders.
|
||||
if (!byId.has(r.id) || r.other) all = false;
|
||||
else next.push([r.id, { status: r.status, title: r.title, column: r.column }]);
|
||||
}
|
||||
if (next.length) setPatches((cur) => new Map([...cur, ...next]));
|
||||
return all ? ["t"] : [];
|
||||
});
|
||||
const w = useWords();
|
||||
const router = useRouter();
|
||||
const t = useT();
|
||||
@ -143,6 +162,7 @@ export function Board({ cards, back }: { cards: Card[]; back: string }) {
|
||||
return (
|
||||
<section
|
||||
key={c.id}
|
||||
data-column={c.id}
|
||||
aria-label={t(c.title)}
|
||||
className={cn("flex min-h-32 flex-col gap-2 rounded-lg border bg-muted/40 p-2", over === c.id && "border-dashed border-primary bg-primary/5", collapsed && "min-h-0")}
|
||||
onDragOver={(e) => {
|
||||
|
||||
176
apps/web/components/ChatLiveFeed.tsx
Normal file
176
apps/web/components/ChatLiveFeed.tsx
Normal file
@ -0,0 +1,176 @@
|
||||
"use client";
|
||||
// PEP-228: new messages of the open conversation drawn in place. The page's chat scope
|
||||
// (`chat:<id>`) brings them ready for this viewer (lib/chat-live.ts); what belongs to this
|
||||
// conversation and needs no buttons is added to the end of the feed at once — no server
|
||||
// re-render. Questions, offers, other threads go to LiveRefresh (the island leaves `m` to it).
|
||||
import { useEffect, useRef, useState, type ReactNode } from "react";
|
||||
import { Bot, MessagesSquare, User as UserIcon } from "lucide-react";
|
||||
import { PRODUCT_NAME } from "@peppa/shared/i18n";
|
||||
import { AgentBadge } from "@/components/AgentBadge";
|
||||
import { Attachments } from "@/components/Attachments";
|
||||
import { ChatScroll } from "@/components/ChatScroll";
|
||||
import { useT } from "@/components/I18n";
|
||||
import { ago, linkify } from "@/lib/format";
|
||||
import { useLiveIsland } from "@/lib/live";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { chatParts, type ChatView, type LiveChatMessage } from "@/lib/chat-live-types";
|
||||
import { markChatReadAction } from "@/app/(app)/chats/actions";
|
||||
|
||||
export function ChatLiveFeed({
|
||||
chatId,
|
||||
lastId,
|
||||
view,
|
||||
userId,
|
||||
compact,
|
||||
showThread,
|
||||
agentName,
|
||||
typing,
|
||||
empty,
|
||||
children,
|
||||
}: {
|
||||
chatId: number;
|
||||
/** The last message the server drew: anything newer is ours to draw. */
|
||||
lastId: number;
|
||||
view: ChatView;
|
||||
userId: number;
|
||||
/** Events as compact lines (threads and «События агентов»). */
|
||||
compact: boolean;
|
||||
showThread: boolean;
|
||||
agentName: string | null;
|
||||
/** «Аналитик печатает…» while the analyst has not answered yet (PEP-110); hidden once an answer is drawn. */
|
||||
typing: ReactNode;
|
||||
/** The server drew no messages (its children are the empty state). */
|
||||
empty: boolean;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const t = useT();
|
||||
const [added, setAdded] = useState<LiveChatMessage[]>([]);
|
||||
const [answered, setAnswered] = useState(false);
|
||||
const read = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const scope = `chat:${chatId}`;
|
||||
const thread = view.kind === "thread" ? view.key : view.kind === "discussion" ? null : undefined;
|
||||
|
||||
// A server re-render drew them itself.
|
||||
const shown = added.filter((m) => m.id > lastId);
|
||||
useEffect(() => setAnswered(false), [lastId]);
|
||||
|
||||
const markRead = () => {
|
||||
if (thread === undefined || read.current) return;
|
||||
read.current = setTimeout(() => {
|
||||
read.current = null;
|
||||
if (document.visibilityState === "visible") void markChatReadAction(chatId, thread).catch(() => {});
|
||||
}, 1000);
|
||||
};
|
||||
useEffect(() => () => {
|
||||
if (read.current) clearTimeout(read.current);
|
||||
}, []);
|
||||
|
||||
useLiveIsland((e) => {
|
||||
if (e.scope !== scope) return [];
|
||||
const { applied, add } = chatParts(e, view);
|
||||
const fresh = add.filter((m) => m.id > lastId);
|
||||
if (fresh.length) {
|
||||
setAdded((was) => {
|
||||
const have = new Set(was.map((m) => m.id));
|
||||
return [...was, ...fresh.filter((m) => !have.has(m.id))].sort((a, b) => a.id - b.id);
|
||||
});
|
||||
if (view.kind === "discussion" && fresh.some((m) => m.authorKind !== "user")) setAnswered(true);
|
||||
markRead();
|
||||
}
|
||||
return applied;
|
||||
});
|
||||
|
||||
const groups: Array<{ events: LiveChatMessage[] } | { m: LiveChatMessage }> = [];
|
||||
for (const m of shown) {
|
||||
const event = compact && (m.kind === "event" || m.kind === "system");
|
||||
const last = groups.at(-1);
|
||||
if (event && last && "events" in last) last.events.push(m);
|
||||
else groups.push(event ? { events: [m] } : { m });
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{!(empty && shown.length) && children}
|
||||
{shown.length > 0 && (
|
||||
<ol data-chat-live className="m-0 flex list-none flex-col gap-2 p-0 pr-12 md:pr-14">
|
||||
{groups.map((g) =>
|
||||
"events" in g ? (
|
||||
<li key={`e${g.events[0]!.id}`} className="flex flex-col gap-1 border-y border-dashed py-1">
|
||||
{g.events.map((m) => (
|
||||
<div key={m.id} data-event-line className="flex items-baseline gap-2 px-1 text-xs text-muted-foreground">
|
||||
<span className="min-w-0 flex-1 break-words">
|
||||
{m.authorKind === "agent" && (m.agent ?? agentName) && <span className="mr-1.5 text-foreground/80">{m.agent ?? agentName}:</span>}
|
||||
{m.main.split("\n")[0]}
|
||||
{m.link && (
|
||||
<a href={m.link} className="ml-1.5">
|
||||
{t("открыть")}
|
||||
</a>
|
||||
)}
|
||||
</span>
|
||||
{m.repeats > 0 && <span className="shrink-0 font-mono">×{m.repeats + 1}</span>}
|
||||
<span className="shrink-0 font-mono">{ago(new Date(m.at), t)}</span>
|
||||
</div>
|
||||
))}
|
||||
</li>
|
||||
) : (
|
||||
<li key={g.m.id} className={cn("flex", view.kind === "discussion" && g.m.authorUserId === userId && g.m.kind === "user" ? "justify-end" : "justify-start")}>
|
||||
<div className="min-w-0 max-w-[85%]">
|
||||
<LiveMessage m={g.m} mine={view.kind === "discussion" && g.m.authorUserId === userId} showThread={showThread} agentName={agentName} />
|
||||
</div>
|
||||
</li>
|
||||
),
|
||||
)}
|
||||
</ol>
|
||||
)}
|
||||
{!answered && typing}
|
||||
<div data-chat-end />
|
||||
<ChatScroll lastId={Math.max(lastId, shown.at(-1)?.id ?? 0)} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** The client twin of the page's MessageItem for a message without buttons. */
|
||||
function LiveMessage({ m, mine, showThread, agentName }: { m: LiveChatMessage; mine: boolean; showThread: boolean; agentName: string | null }) {
|
||||
const t = useT();
|
||||
const person = m.authorKind === "user" && m.kind === "user";
|
||||
const agentLabel = m.authorKind === "agent" ? (m.agent ?? agentName) : null;
|
||||
return (
|
||||
<article data-live-message={m.id} className={cn("flex flex-col gap-1 rounded-lg border bg-card px-3 py-2", mine && "border-primary/30 bg-primary/10", m.kind === "system" && "border-dashed bg-transparent")}>
|
||||
<div className="flex flex-wrap items-center gap-x-2 gap-y-0.5 text-xs text-muted-foreground">
|
||||
{person ? <UserIcon className="size-3.5" /> : agentLabel ? null : m.authorKind === "agent" ? <Bot className="size-3.5" /> : <MessagesSquare className="size-3.5" />}
|
||||
{agentLabel ? (
|
||||
<AgentBadge name={agentLabel} className="text-foreground" />
|
||||
) : (
|
||||
<span className="font-medium text-foreground">{person ? (mine ? t("вы") : (m.login ?? "?")) : m.authorKind === "agent" ? t("агент") : PRODUCT_NAME}</span>
|
||||
)}
|
||||
{m.via === "telegram" && <span title={t("из Telegram")}>· Telegram</span>}
|
||||
{showThread && m.thread && (
|
||||
<a href={m.thread.href} className="max-w-full truncate">
|
||||
🧵 {m.thread.label}
|
||||
</a>
|
||||
)}
|
||||
{m.repeats > 0 && (
|
||||
<span className="rounded-full border px-1.5 font-mono tabular-nums" title={t("Повторов: {n}", { n: m.repeats })}>
|
||||
×{m.repeats + 1}
|
||||
</span>
|
||||
)}
|
||||
<span className="ml-auto font-mono">{ago(new Date(m.at), t)}</span>
|
||||
</div>
|
||||
<p data-message-main className="m-0 text-sm break-words whitespace-pre-wrap">
|
||||
{linkify(m.main)}
|
||||
</p>
|
||||
{m.more && (
|
||||
<details data-message-details className="text-xs text-muted-foreground">
|
||||
<summary className="cursor-pointer">{t("Подробнее")}</summary>
|
||||
<p className="m-0 mt-1 max-h-72 overflow-auto break-words whitespace-pre-wrap">{linkify(m.more)}</p>
|
||||
</details>
|
||||
)}
|
||||
<Attachments files={m.files} />
|
||||
{m.link && (
|
||||
<a href={m.link} target={m.link.startsWith("/") ? undefined : "_blank"} rel="noreferrer" className="truncate text-xs">
|
||||
{m.link.startsWith("/") ? t("Открыть") : m.link}
|
||||
</a>
|
||||
)}
|
||||
</article>
|
||||
);
|
||||
}
|
||||
@ -1,24 +1,23 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useEffect, useRef } from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useT } from "@/components/I18n";
|
||||
import { applyIslands, liveClient, useLive, useLiveMode, type LiveEvent, type LiveMode } from "@/lib/live";
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
|
||||
type Mode = "connecting" | "live" | "reconnecting" | "polling";
|
||||
|
||||
const LABEL: Record<Mode, string> = {
|
||||
const LABEL: Record<LiveMode, string> = {
|
||||
connecting: m("подключение…"),
|
||||
live: m("в реальном времени"),
|
||||
reconnecting: m("переподключение…"),
|
||||
polling: m("опрос раз в 5 с"),
|
||||
offline: m("нет связи — пробуем снова"),
|
||||
};
|
||||
const DOT: Record<Mode, string> = {
|
||||
const DOT: Record<LiveMode, string> = {
|
||||
connecting: "bg-muted-foreground",
|
||||
live: "bg-ok",
|
||||
reconnecting: "bg-warn animate-pulse",
|
||||
polling: "bg-warn",
|
||||
offline: "bg-destructive",
|
||||
};
|
||||
|
||||
/** True while the user is typing or left an unsent draft: a refresh must wait. */
|
||||
@ -29,129 +28,81 @@ function busy(): boolean {
|
||||
return typing || draft;
|
||||
}
|
||||
|
||||
/** PEP-215: at most one re-render per tab in this many ms, however many changes the stream reports. */
|
||||
/** PEP-215: at most one re-render per tab in this many ms, however many changes the channel reports. */
|
||||
export const MIN_REFRESH_GAP_MS = 4000;
|
||||
|
||||
/**
|
||||
* Live page (PEP-37): listens to /api/live for its scope and re-renders server data when
|
||||
* something there changed (router.refresh keeps client state and typed text). Falls back to
|
||||
* polling every 5 s when the stream can't be opened; shows the connection state.
|
||||
* Live page (PEP-37, PEP-225): watches its scope over the tab's channel. A change the page's
|
||||
* islands apply in place (board cards, the attention counter…) needs nothing more; anything else
|
||||
* re-renders server data (router.refresh keeps client state and typed text) — at most once per
|
||||
* 4 s, never while the person types. Shows the connection state.
|
||||
*/
|
||||
export function LiveRefresh({ scope, pollMs = 5000, pauseHidden = false, indicator = true }: { scope: string; pollMs?: number; pauseHidden?: boolean; /** PEP-207: the chat hides the corner pill — it sits over the message field. */ indicator?: boolean }) {
|
||||
export function LiveRefresh({
|
||||
scope,
|
||||
pauseHidden = false,
|
||||
indicator = true,
|
||||
}: {
|
||||
scope: string;
|
||||
/** PEP-179: a hidden tab drops the scope (battery) and catches up when back in view. */
|
||||
pauseHidden?: boolean;
|
||||
/** PEP-207: the chat hides the corner pill — it sits over the message field. */
|
||||
indicator?: boolean;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const [mode, setMode] = useState<Mode>("connecting");
|
||||
const pending = useRef(false);
|
||||
const mode = useLiveMode();
|
||||
const t = useT();
|
||||
const state = useRef({ pending: false, timer: null as ReturnType<typeof setTimeout> | null, last: 0 });
|
||||
|
||||
useEffect(() => {
|
||||
let closed = false;
|
||||
let es: EventSource | null = null;
|
||||
let fails = 0;
|
||||
let opened = false;
|
||||
let poll: ReturnType<typeof setInterval> | null = null;
|
||||
let retry: ReturnType<typeof setTimeout> | null = null;
|
||||
let flushTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let lastRefresh = 0;
|
||||
|
||||
// Debounced refresh that waits for the user to finish typing.
|
||||
const flush = () => {
|
||||
flushTimer = null;
|
||||
if (closed || !pending.current) return;
|
||||
if (busy() || document.visibilityState !== "visible") {
|
||||
flushTimer = setTimeout(flush, 2000);
|
||||
return;
|
||||
}
|
||||
const wait = lastRefresh + MIN_REFRESH_GAP_MS - Date.now();
|
||||
if (wait > 0) {
|
||||
flushTimer = setTimeout(flush, wait);
|
||||
return;
|
||||
}
|
||||
pending.current = false;
|
||||
lastRefresh = Date.now();
|
||||
router.refresh();
|
||||
};
|
||||
const request = () => {
|
||||
pending.current = true;
|
||||
if (!flushTimer) flushTimer = setTimeout(flush, 300);
|
||||
};
|
||||
// PEP-179 `pauseHidden`: a hidden tab or a minimised app keeps no stream open (battery);
|
||||
// back in view — reconnect and re-read at once.
|
||||
const pause = () => {
|
||||
es?.close();
|
||||
es = null;
|
||||
if (poll) clearInterval(poll);
|
||||
poll = null;
|
||||
if (retry) clearTimeout(retry);
|
||||
retry = null;
|
||||
};
|
||||
const onVisible = () => {
|
||||
const visible = document.visibilityState === "visible";
|
||||
if (pauseHidden) {
|
||||
if (!visible) return pause();
|
||||
if (!es && !poll) {
|
||||
fails = 0;
|
||||
connect();
|
||||
pending.current = true;
|
||||
return request();
|
||||
}
|
||||
}
|
||||
if (visible && pending.current) request();
|
||||
};
|
||||
|
||||
const startPolling = () => {
|
||||
if (poll) return;
|
||||
setMode("polling");
|
||||
poll = setInterval(request, pollMs);
|
||||
// Try the stream again now and then.
|
||||
retry = setTimeout(() => {
|
||||
if (poll) clearInterval(poll);
|
||||
poll = null;
|
||||
fails = 0;
|
||||
connect();
|
||||
}, 30_000);
|
||||
};
|
||||
|
||||
const connect = () => {
|
||||
if (closed) return;
|
||||
if (typeof EventSource === "undefined") return startPolling();
|
||||
es = new EventSource(`/api/live?scope=${encodeURIComponent(scope)}`);
|
||||
es.addEventListener("ready", () => {
|
||||
// Back after a drop: changes may have been missed.
|
||||
if (opened) request();
|
||||
opened = true;
|
||||
fails = 0;
|
||||
setMode("live");
|
||||
});
|
||||
es.addEventListener("change", request);
|
||||
es.onerror = () => {
|
||||
if (closed) return;
|
||||
fails++;
|
||||
if (fails >= 3 || es?.readyState === EventSource.CLOSED) {
|
||||
es?.close();
|
||||
es = null;
|
||||
startPolling();
|
||||
} else setMode("reconnecting");
|
||||
};
|
||||
};
|
||||
|
||||
if (!pauseHidden || document.visibilityState === "visible") connect();
|
||||
document.addEventListener("visibilitychange", onVisible);
|
||||
const s = state.current;
|
||||
return () => {
|
||||
closed = true;
|
||||
es?.close();
|
||||
if (poll) clearInterval(poll);
|
||||
if (retry) clearTimeout(retry);
|
||||
if (flushTimer) clearTimeout(flushTimer);
|
||||
document.removeEventListener("visibilitychange", onVisible);
|
||||
if (s.timer) clearTimeout(s.timer);
|
||||
s.timer = null;
|
||||
};
|
||||
}, [router, scope, pollMs, pauseHidden]);
|
||||
}, []);
|
||||
|
||||
const flush = () => {
|
||||
const s = state.current;
|
||||
s.timer = null;
|
||||
if (!s.pending) return;
|
||||
// Offline a re-render fails into a full navigation to the browser's error page: wait for the channel.
|
||||
if (busy() || document.visibilityState !== "visible" || !navigator.onLine || liveClient().mode !== "live") {
|
||||
s.timer = setTimeout(flush, 2000);
|
||||
return;
|
||||
}
|
||||
const wait = s.last + MIN_REFRESH_GAP_MS - Date.now();
|
||||
if (wait > 0) {
|
||||
s.timer = setTimeout(flush, wait);
|
||||
return;
|
||||
}
|
||||
s.pending = false;
|
||||
s.last = Date.now();
|
||||
router.refresh();
|
||||
};
|
||||
const request = () => {
|
||||
const s = state.current;
|
||||
s.pending = true;
|
||||
if (!s.timer) s.timer = setTimeout(flush, 300);
|
||||
};
|
||||
|
||||
useLive(
|
||||
scope,
|
||||
(e: LiveEvent) => {
|
||||
if (e.type !== "change") return;
|
||||
const applied = applyIslands(e);
|
||||
if (e.parts.every((p) => applied.has(p))) return;
|
||||
request();
|
||||
},
|
||||
{ heavy: pauseHidden },
|
||||
);
|
||||
|
||||
if (!indicator) return null;
|
||||
return (
|
||||
<div
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
title={mode === "polling" ? t("Канал событий недоступен — страница обновляется по таймеру") : t("Страница обновляется сама, когда что-то меняется")}
|
||||
data-live-mode={mode}
|
||||
title={mode === "offline" ? t("Нет связи с Peppa FACTORY — страница обновится, когда связь вернётся") : t("Страница обновляется сама, когда что-то меняется")}
|
||||
className="pointer-events-none fixed right-3 bottom-[calc(4.25rem+env(safe-area-inset-bottom))] z-40 md:bottom-3 flex items-center gap-1.5 rounded-full border bg-background/90 px-2.5 py-1 font-mono text-[11px] text-muted-foreground shadow-sm backdrop-blur"
|
||||
>
|
||||
<span className={cn("size-1.5 rounded-full", DOT[mode])} />
|
||||
|
||||
25
apps/web/components/LiveTaskStatus.tsx
Normal file
25
apps/web/components/LiveTaskStatus.tsx
Normal file
@ -0,0 +1,25 @@
|
||||
"use client";
|
||||
// PEP-225: the story's status badge, updated in place from the live channel (`task:<id>` rows) —
|
||||
// the rest of the page follows with the next server re-render.
|
||||
import { useState, useEffect } from "react";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { useT } from "@/components/I18n";
|
||||
import { useLiveIsland } from "@/lib/live";
|
||||
import { TASK_STATUS } from "@/lib/status";
|
||||
|
||||
export function LiveTaskStatus({ taskId, status: initial }: { taskId: number; status: string }) {
|
||||
const t = useT();
|
||||
const [status, setStatus] = useState(initial);
|
||||
useEffect(() => setStatus(initial), [initial]);
|
||||
useLiveIsland((e) => {
|
||||
const row = e.tasks?.find((r) => r.id === taskId);
|
||||
if (row) setStatus(row.status);
|
||||
return []; // the page around depends on the status too
|
||||
});
|
||||
const s = TASK_STATUS[status] ?? { label: status, tone: "muted" as const };
|
||||
return (
|
||||
<Badge variant={s.tone} data-live-status={status}>
|
||||
{t.text(s.label)}
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
@ -2,6 +2,7 @@
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useLive } from "@/lib/live";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { pairingLinkAction } from "@/app/(app)/actions";
|
||||
import { useT } from "@/components/I18n";
|
||||
@ -9,7 +10,7 @@ import { useT } from "@/components/I18n";
|
||||
/**
|
||||
* PEP-100: opens the user's bot (with the pairing code) in a new tab / the Telegram app and keeps
|
||||
* Peppa open — a plain redirect used to take the page away mid-steps. While the user presses
|
||||
* Start, the page refreshes itself so the step turns done.
|
||||
* Start, the live channel tells the page, and it re-renders so the step turns done.
|
||||
*/
|
||||
export function OpenBotButton({ label, variant = "default", size = "sm" }: { label: string; variant?: "default" | "ghost" | "outline"; size?: "sm" | "xs" }) {
|
||||
const t = useT();
|
||||
@ -20,13 +21,13 @@ export function OpenBotButton({ label, variant = "default", size = "sm" }: { lab
|
||||
|
||||
useEffect(() => {
|
||||
if (!waiting) return;
|
||||
const timer = setInterval(() => router.refresh(), 3000);
|
||||
const stop = setTimeout(() => setWaiting(false), 3 * 60_000);
|
||||
return () => {
|
||||
clearInterval(timer);
|
||||
clearTimeout(stop);
|
||||
};
|
||||
}, [waiting, router]);
|
||||
return () => clearTimeout(stop);
|
||||
}, [waiting]);
|
||||
// PEP-225: the binding (`me`) changes when the user presses Start in the bot — re-render then.
|
||||
useLive(waiting ? "me" : null, (e) => {
|
||||
if (e.type === "change") router.refresh();
|
||||
});
|
||||
|
||||
async function open() {
|
||||
setError(null);
|
||||
|
||||
@ -1,10 +1,12 @@
|
||||
"use client";
|
||||
// Live runner terminal (PEP-9): xterm.js fed by SSE from /api/runners/<id>/terminal, input via POST.
|
||||
// Live runner terminal (PEP-9): xterm.js fed by the tab's live channel (`terminal:<id>`, PEP-225),
|
||||
// input over the same channel; without a WebSocket — SSE of /api/runners/<id>/terminal and POST.
|
||||
import "@xterm/xterm/css/xterm.css";
|
||||
import type { Terminal } from "@xterm/xterm";
|
||||
import { Keyboard, Maximize2, Minimize2, Minus, Plus, RotateCw } from "lucide-react";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { liveClient, useLiveMode } from "@/lib/live";
|
||||
import { useT } from "@/components/I18n";
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
|
||||
@ -42,7 +44,10 @@ export function RunnerTerminal({ sessionId, live }: { sessionId: number; live: b
|
||||
const host = useRef<HTMLDivElement>(null);
|
||||
const scroller = useRef<HTMLDivElement>(null);
|
||||
const term = useRef<Terminal | null>(null);
|
||||
const [status, setStatus] = useState<Status>("connecting");
|
||||
const [own, setStatus] = useState<Status>("connecting");
|
||||
// The channel dropped: the picture is stale until it is back (a fresh frame comes then).
|
||||
const mode = useLiveMode();
|
||||
const status: Status = own === "live" && mode !== "live" ? "reconnecting" : own;
|
||||
const [input, setInput] = useState(false);
|
||||
const [full, setFull] = useState(false);
|
||||
const [font, setFont] = useState(12);
|
||||
@ -51,23 +56,17 @@ export function RunnerTerminal({ sessionId, live }: { sessionId: number; live: b
|
||||
const t = useT();
|
||||
const inputRef = useRef(false);
|
||||
const queue = useRef<{ keys: string; timer: ReturnType<typeof setTimeout> | null; chain: Promise<void> }>({ keys: "", timer: null, chain: Promise.resolve() });
|
||||
const url = `/api/runners/${sessionId}/terminal`;
|
||||
const scope = `terminal:${sessionId}`;
|
||||
|
||||
const post = useCallback(
|
||||
(body: { keys?: string; paste?: string }) => {
|
||||
const q = queue.current;
|
||||
// Strictly one request at a time: the order of keystrokes matters.
|
||||
q.chain = q.chain.then(async () => {
|
||||
try {
|
||||
const r = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
|
||||
if (!r.ok) setError(((await r.json().catch(() => null)) as { error?: string } | null)?.error ?? m("Ошибка {status}", { status: r.status }));
|
||||
else setError(null);
|
||||
} catch {
|
||||
setError(m("Нет связи с Peppa FACTORY"));
|
||||
}
|
||||
setError(await liveClient().input(scope, body));
|
||||
});
|
||||
},
|
||||
[url],
|
||||
[scope],
|
||||
);
|
||||
|
||||
const sendKeys = useCallback(
|
||||
@ -136,28 +135,31 @@ export function RunnerTerminal({ sessionId, live }: { sessionId: number; live: b
|
||||
};
|
||||
}, [post, sendKeys]);
|
||||
|
||||
// The stream: (re)opened when the terminal is ready or the user asks to reconnect.
|
||||
// The stream: (re)subscribed when the terminal is ready or the user asks to reconnect.
|
||||
useEffect(() => {
|
||||
const t = term.current;
|
||||
if (!t || attempt === 0) return;
|
||||
setStatus("connecting");
|
||||
const es = new EventSource(url);
|
||||
es.addEventListener("frame", (e) => {
|
||||
const f = JSON.parse((e as MessageEvent<string>).data) as { cols: number; rows: number; data: string };
|
||||
t.reset();
|
||||
if (t.cols !== f.cols || t.rows !== f.rows) t.resize(f.cols, f.rows);
|
||||
// The pane is usually taller than the panel: show its bottom, where the agent works.
|
||||
t.write(f.data, () => scroller.current && (scroller.current.scrollTop = scroller.current.scrollHeight));
|
||||
setStatus("live");
|
||||
});
|
||||
es.addEventListener("out", (e) => t.write((JSON.parse((e as MessageEvent<string>).data) as { data: string }).data));
|
||||
es.addEventListener("end", () => {
|
||||
es.close();
|
||||
setStatus("ended");
|
||||
});
|
||||
es.onerror = () => setStatus(es.readyState === EventSource.CLOSED ? "error" : "reconnecting");
|
||||
return () => es.close();
|
||||
}, [url, attempt]);
|
||||
let stop = () => {};
|
||||
stop = liveClient().subscribe(
|
||||
scope,
|
||||
(e) => {
|
||||
if (e.type === "frame") {
|
||||
t.reset();
|
||||
if (t.cols !== e.cols || t.rows !== e.rows) t.resize(e.cols, e.rows);
|
||||
// The pane is usually taller than the panel: show its bottom, where the agent works.
|
||||
t.write(e.data, () => scroller.current && (scroller.current.scrollTop = scroller.current.scrollHeight));
|
||||
setStatus("live");
|
||||
} else if (e.type === "out") t.write(e.data);
|
||||
else if (e.type === "end") {
|
||||
setStatus("ended");
|
||||
queueMicrotask(() => stop());
|
||||
} else if (e.type === "error") setStatus("error");
|
||||
},
|
||||
{ heavy: true },
|
||||
);
|
||||
return () => stop();
|
||||
}, [scope, attempt]);
|
||||
|
||||
useEffect(() => {
|
||||
inputRef.current = input && live;
|
||||
|
||||
@ -2,6 +2,8 @@
|
||||
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useLive } from "@/lib/live";
|
||||
import { Activity, Bot, Contact, FolderKanban, Gauge, GitBranch, Megaphone, House, KeyRound, MessagesSquare, ScrollText, LifeBuoy, LogOut, MessageCircleWarning, Search, Server, Settings, ShieldCheck, Sparkles, Users, type LucideIcon } from "lucide-react";
|
||||
import { Brand } from "@/components/Brand";
|
||||
import { ThemeToggle } from "@/components/ThemeToggle";
|
||||
@ -48,9 +50,18 @@ const ITEMS: Item[] = [
|
||||
const COUNT_TITLE = { questions: m("{n} вопросов ждут вас"), waitingRunners: m("{n} агентов ждут вас"), chats: m("{n} новых сообщений в обсуждениях"), feedback: m("{n} обращений ждут решения") };
|
||||
|
||||
/** Left panel on desktop; on phones a top bar plus a bottom tab bar (PEP-38): sections with «ждут вас» counters, theme, user. */
|
||||
export function Sidebar({ login, avatarUrl, counts, superadmin = false, engineer = false }: { login: string; avatarUrl: string | null; counts: Record<"questions" | "waitingRunners" | "chats" | "feedback", number>; superadmin?: boolean; engineer?: boolean }) {
|
||||
export function Sidebar({ login, avatarUrl, counts: initialCounts, superadmin = false, engineer = false }: { login: string; avatarUrl: string | null; counts: Record<"questions" | "waitingRunners" | "chats" | "feedback", number>; superadmin?: boolean; engineer?: boolean }) {
|
||||
const path = usePathname();
|
||||
const t = useT();
|
||||
// PEP-225: the «ждут вас» counters follow the live channel (`attention`) without a re-render.
|
||||
const [live, setLive] = useState<Partial<typeof initialCounts>>({});
|
||||
useEffect(() => setLive({}), [initialCounts]);
|
||||
useLive("attention", (e) => {
|
||||
if (e.type !== "data") return;
|
||||
const d = e.data as { questions?: number; waitingRunners?: number; chats?: number };
|
||||
setLive({ questions: d.questions, waitingRunners: d.waitingRunners, chats: d.chats });
|
||||
});
|
||||
const counts = { ...initialCounts, ...Object.fromEntries(Object.entries(live).filter(([, v]) => typeof v === "number")) };
|
||||
const items = ITEMS.filter((i) => (!i.admin || superadmin) && (!i.engineer || engineer));
|
||||
// The phone tab bar holds what is left after the desktop-only and admin sections: 5 or 6 tabs.
|
||||
const phoneTabs = items.filter((i) => !i.admin && !i.desktopOnly).length;
|
||||
|
||||
@ -6,7 +6,7 @@ import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import { CopyCode } from "@/components/CopyCode";
|
||||
import { AutoRefresh } from "@/components/AutoRefresh";
|
||||
import { LiveRefresh } from "@/components/LiveRefresh";
|
||||
|
||||
const step = "flex gap-2.5";
|
||||
const num = "grid size-5.5 shrink-0 place-items-center rounded-full bg-primary/15 text-xs font-semibold text-primary";
|
||||
@ -28,8 +28,8 @@ export async function SubscriptionSetup({ projectId, back, logins, shared = fals
|
||||
: l.provider === "claude" ? t("Подключаем Claude — осталось три шага") : t("Подключаем ChatGPT — осталось три шага")}
|
||||
</h2>
|
||||
{extra && <p className="m-0 text-muted-foreground">{t("Агенты уже работают на подключённой подписке. Вторая нужна только про запас — если она не нужна, нажмите «Отменить» внизу.")}</p>}
|
||||
{/* PEP-148: the page asks ChatGPT itself every few seconds — the person does not have to press anything. */}
|
||||
{l.provider !== "claude" && <AutoRefresh everyMs={4000} />}
|
||||
{/* PEP-148 / PEP-225: the server asks ChatGPT every few seconds while the page watches this sign-in — the person does not have to press anything. */}
|
||||
{l.provider !== "claude" && <LiveRefresh scope={`login:${l.subscriptionId}`} indicator={false} />}
|
||||
{l.provider !== "claude" && checked && (
|
||||
<p role="status" className="m-0 rounded-md border border-warn/50 bg-warn/10 px-3 py-2">
|
||||
<b>{t("ChatGPT пока не подтвердил вход.")}</b>{" "}
|
||||
|
||||
@ -1,41 +1,23 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { useState } from "react";
|
||||
import { useLive } from "@/lib/live";
|
||||
import { RefreshCw } from "lucide-react";
|
||||
import { useT } from "@/components/I18n";
|
||||
|
||||
/**
|
||||
* PEP-114: a page opened before the site was updated may press buttons the new server doesn't
|
||||
* know — nothing happens and nothing is said. This watches the server's boot id (once a minute
|
||||
* and when the tab comes back) and asks to reload when it changed. Never reloads by itself: the
|
||||
* person may be in the middle of typing.
|
||||
* know — nothing happens and nothing is said. The live channel (`version`, PEP-225) brings the
|
||||
* server's boot id on every (re)connect: a restarted web means a new id, and the page asks to
|
||||
* reload. Never reloads by itself: the person may be in the middle of typing.
|
||||
*/
|
||||
export function VersionWatch({ boot }: { boot: string }) {
|
||||
const t = useT();
|
||||
const [stale, setStale] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
const check = async () => {
|
||||
try {
|
||||
const r = await fetch("/api/health", { cache: "no-store" });
|
||||
const now = ((await r.json()) as { boot?: string }).boot;
|
||||
if (alive && now && now !== boot) setStale(true);
|
||||
} catch {
|
||||
/* offline or restarting: the next check will tell */
|
||||
}
|
||||
};
|
||||
const timer = setInterval(check, 60_000);
|
||||
const onVisible = () => document.visibilityState === "visible" && void check();
|
||||
document.addEventListener("visibilitychange", onVisible);
|
||||
window.addEventListener("focus", onVisible);
|
||||
return () => {
|
||||
alive = false;
|
||||
clearInterval(timer);
|
||||
document.removeEventListener("visibilitychange", onVisible);
|
||||
window.removeEventListener("focus", onVisible);
|
||||
};
|
||||
}, [boot]);
|
||||
useLive("version", (e) => {
|
||||
const now = e.type === "data" ? (e.data as { boot?: string }).boot : undefined;
|
||||
if (now && now !== boot) setStale(true);
|
||||
});
|
||||
|
||||
if (!stale) return null;
|
||||
return (
|
||||
|
||||
@ -6,7 +6,6 @@ import { Badge } from "@/components/ui/badge";
|
||||
import { SESSION_STATUS, TASK_STATUS, TONE_BG } from "@/lib/status";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import { intlLocale, type Translator } from "@peppa/shared/i18n";
|
||||
|
||||
export function PageHeader({ title, crumbs, actions, children }: { title: ReactNode; crumbs?: ReactNode; actions?: ReactNode; children?: ReactNode }) {
|
||||
return (
|
||||
@ -97,25 +96,4 @@ export function Disclosure({ summary, children, open, className }: { summary: Re
|
||||
}
|
||||
|
||||
|
||||
/** «5 мин назад» in the page's language. */
|
||||
export function ago(d: Date | null | undefined, t: Translator): string {
|
||||
if (!d) return "—";
|
||||
const s = Math.round((Date.now() - d.getTime()) / 1000);
|
||||
if (s < 60) return t("{n} с назад", { n: s });
|
||||
if (s < 3600) return t("{n} мин назад", { n: Math.round(s / 60) });
|
||||
if (s < 86400) return t("{n} ч назад", { n: Math.round(s / 3600) });
|
||||
return d.toLocaleDateString(intlLocale(t.locale));
|
||||
}
|
||||
|
||||
/** Text with its http(s) addresses as links. */
|
||||
export function linkify(text: string) {
|
||||
return text.split(/(https?:\/\/[^\s<>«»"]+[^\s<>«»".,;:!?)])/g).map((part, i) =>
|
||||
i % 2 ? (
|
||||
<a key={i} href={part} target={part.startsWith(process.env.PEPPA_WEB_URL ?? "\0") ? undefined : "_blank"} rel="noreferrer">
|
||||
{part}
|
||||
</a>
|
||||
) : (
|
||||
part
|
||||
),
|
||||
);
|
||||
}
|
||||
export { ago, linkify } from "@/lib/format";
|
||||
|
||||
@ -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();
|
||||
|
||||
@ -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<User | null> => {
|
||||
const p = verify<SessionPayload>((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<User | null> => 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<User> {
|
||||
|
||||
56
apps/web/lib/chat-live-types.ts
Normal file
56
apps/web/lib/chat-live-types.ts
Normal file
@ -0,0 +1,56 @@
|
||||
// PEP-228: a chat message as the live channel brings it to a chat page — already translated and
|
||||
// cleaned for its viewer on the server (lib/chat-live.ts); the browser only draws it.
|
||||
import type { AttachmentView } from "@peppa/core";
|
||||
|
||||
export interface LiveChatMessage {
|
||||
id: number;
|
||||
threadKey: string | null;
|
||||
kind: "event" | "question" | "user" | "system";
|
||||
authorKind: "system" | "agent" | "user";
|
||||
authorUserId: number | null;
|
||||
/** A person's login (people's messages). */
|
||||
login: string | null;
|
||||
/** An agent's or a role's name, translated; null — the thread's agent. */
|
||||
agent: string | null;
|
||||
via: "web" | "telegram" | null;
|
||||
/** ISO time of the message (of its last repeat). */
|
||||
at: string;
|
||||
repeats: number;
|
||||
/** A command («/status») — not a part of the discussion. */
|
||||
command: boolean;
|
||||
/** The factory's service notice — the chat with the analyst doesn't show it (PEP-207). */
|
||||
notice: boolean;
|
||||
/** What the screen shows at once and what opens under «Подробнее». */
|
||||
main: string;
|
||||
more: string | null;
|
||||
link: string | null;
|
||||
files: AttachmentView[];
|
||||
/** A question or a message with buttons: the page re-renders it from the server. */
|
||||
render: boolean;
|
||||
/** The thread's title for the «События агентов» view (🧵 …). */
|
||||
thread: { label: string; href: string } | null;
|
||||
}
|
||||
|
||||
/** Which conversation the page shows — the same rules as its server query. */
|
||||
export type ChatView = { kind: "discussion" } | { kind: "channel" } | { kind: "feed" } | { kind: "thread"; key: string };
|
||||
|
||||
export function inView(m: Pick<LiveChatMessage, "threadKey" | "kind" | "command" | "notice">, view: ChatView): boolean {
|
||||
if (view.kind === "feed") return true;
|
||||
if (view.kind === "thread") return m.threadKey === view.key;
|
||||
if (view.kind === "channel") return m.threadKey === null;
|
||||
return m.threadKey === null && m.kind === "user" && !m.command && !m.notice;
|
||||
}
|
||||
|
||||
/**
|
||||
* What of a `change` of the chat scope the feed applies in place: `m` when every new message is
|
||||
* of this conversation and none needs buttons; `x` (offers, files) when it came with messages —
|
||||
* they carry their own. Pure: the test and the island share it.
|
||||
*/
|
||||
export function chatParts(e: { parts: string[]; messages?: unknown[] }, view: ChatView): { applied: string[]; add: LiveChatMessage[] } {
|
||||
const list = (e.messages ?? []) as LiveChatMessage[];
|
||||
if (!e.messages) return { applied: [], add: [] };
|
||||
const plain = list.every((m) => inView(m, view) && !m.render);
|
||||
const applied = ["x"];
|
||||
if (plain) applied.push("m");
|
||||
return { applied, add: list.filter((m) => inView(m, view) && !m.render) };
|
||||
}
|
||||
43
apps/web/lib/chat-live.ts
Normal file
43
apps/web/lib/chat-live.ts
Normal file
@ -0,0 +1,43 @@
|
||||
// PEP-228: new messages of a chat for the live channel — the same text a chat page renders on
|
||||
// the server (translation, cleaning, «Подробнее», links), built for one viewer.
|
||||
import { getUserLocale, isSuperadmin, splitForDisplay, type AttachmentView, type ChatMessageView } from "@peppa/core";
|
||||
import { users, type Db } from "@peppa/db";
|
||||
import { stripAsIs, translator } from "@peppa/shared/i18n";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { cleanText, messageLink, STUCK_NOTICE } from "./chat-text";
|
||||
import type { LiveChatMessage } from "./chat-live-types";
|
||||
|
||||
export async function liveChatView(db: Db, userId: number, messages: ChatMessageView[], files: Map<number, AttachmentView[]>): Promise<LiveChatMessage[]> {
|
||||
const user = (await db.select({ login: users.login }).from(users).where(eq(users.id, userId)))[0];
|
||||
const superadmin = await isSuperadmin(db, user ?? null);
|
||||
const t = translator(await getUserLocale(db, userId));
|
||||
const gitea = (process.env.GITEA_URL ?? "").replace(/\/+$/, "");
|
||||
return messages.map((m) => {
|
||||
// Same as MessageItem / EventLines of the chat page.
|
||||
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);
|
||||
const label = m.threadTitle ? t.text(m.threadTitle) : null;
|
||||
return {
|
||||
id: m.id,
|
||||
threadKey: m.threadKey,
|
||||
kind: m.kind,
|
||||
authorKind: m.authorKind,
|
||||
authorUserId: m.authorUserId,
|
||||
login: m.authorLogin,
|
||||
agent: m.authorKind === "agent" && m.authorLogin ? t.role(m.authorLogin) : null,
|
||||
via: m.via,
|
||||
at: (m.updatedAt ?? m.createdAt).toISOString(),
|
||||
repeats: m.repeats,
|
||||
command: m.text.startsWith("/"),
|
||||
notice: m.authorKind !== "user" && STUCK_NOTICE.test(stripAsIs(m.text)),
|
||||
main: shown.main,
|
||||
more: shown.more,
|
||||
link: messageLink(m.url, superadmin, gitea),
|
||||
files: files.get(m.id) ?? [],
|
||||
render: !!m.question || !!m.offer,
|
||||
thread: label && m.projectKey && m.threadKey ? { label, href: `/chats/${m.projectKey}?thread=${encodeURIComponent(m.threadKey)}` } : null,
|
||||
};
|
||||
});
|
||||
}
|
||||
@ -12,3 +12,13 @@ export function cleanText(text: string, superadmin: boolean, gitea = ""): string
|
||||
}
|
||||
const TERMINAL_LINE = /^\s*(?:[⏺⎿●│└├╭╰─━]|\$ |> |✻|Calling\b|Running\b)/;
|
||||
|
||||
|
||||
/** A link under a message: never the bare «/», never Gitea for a product manager. */
|
||||
export function messageLink(url: string | null, superadmin: boolean, gitea: string): string | null {
|
||||
if (!url || url === "/" || url === "#") return null;
|
||||
if (!superadmin && gitea && url.startsWith(gitea)) return null;
|
||||
return url;
|
||||
}
|
||||
|
||||
/** PEP-207: the factory's «задерживается на нашей стороне» — the status line of the chat with the analyst, not a message. */
|
||||
export const STUCK_NOTICE = /задерживается на нашей стороне/i;
|
||||
|
||||
25
apps/web/lib/format.tsx
Normal file
25
apps/web/lib/format.tsx
Normal file
@ -0,0 +1,25 @@
|
||||
// Formatters of the console shared by server and client components (no server imports).
|
||||
import { intlLocale, type Translator } from "@peppa/shared/i18n";
|
||||
|
||||
/** «5 мин назад» in the page's language. */
|
||||
export function ago(d: Date | null | undefined, t: Translator): string {
|
||||
if (!d) return "—";
|
||||
const s = Math.round((Date.now() - d.getTime()) / 1000);
|
||||
if (s < 60) return t("{n} с назад", { n: s });
|
||||
if (s < 3600) return t("{n} мин назад", { n: Math.round(s / 60) });
|
||||
if (s < 86400) return t("{n} ч назад", { n: Math.round(s / 3600) });
|
||||
return d.toLocaleDateString(intlLocale(t.locale));
|
||||
}
|
||||
|
||||
/** Text with its http(s) addresses as links. */
|
||||
export function linkify(text: string) {
|
||||
return text.split(/(https?:\/\/[^\s<>«»"]+[^\s<>«»".,;:!?)])/g).map((part, i) =>
|
||||
i % 2 ? (
|
||||
<a key={i} href={part} target={part.startsWith(process.env.PEPPA_WEB_URL ?? "\0") ? undefined : "_blank"} rel="noreferrer">
|
||||
{part}
|
||||
</a>
|
||||
) : (
|
||||
part
|
||||
),
|
||||
);
|
||||
}
|
||||
29
apps/web/lib/live-server.ts
Normal file
29
apps/web/lib/live-server.ts
Normal file
@ -0,0 +1,29 @@
|
||||
// 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 { setLiveChatView, setLiveProvider } from "@peppa/runner";
|
||||
import { createLiveWs, readCookie, type LiveWs } from "@peppa/runner/live-ws";
|
||||
import { bootId } from "./boot";
|
||||
import { liveChatView } from "./chat-live";
|
||||
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, questions: c.questions, waitingRunners: c.waitingRunners, chats: c.chats, sound };
|
||||
});
|
||||
setLiveProvider("version", () => ({ boot: bootId() }));
|
||||
setLiveChatView(liveChatView);
|
||||
g.__peppaLiveWs?.close();
|
||||
g.__peppaLiveWs = createLiveWs({
|
||||
db,
|
||||
authenticate: (req) => userFromSessionToken(readCookie(req.headers.cookie, SESSION_COOKIE)),
|
||||
boot: bootId,
|
||||
});
|
||||
}
|
||||
414
apps/web/lib/live.ts
Normal file
414
apps/web/lib/live.ts
Normal file
@ -0,0 +1,414 @@
|
||||
"use client";
|
||||
// One live channel per tab (PEP-225): a single WebSocket to /api/ws carries every scope the page
|
||||
// watches — page changes, the attention counter, the boot id, agent steps, the terminal. Scopes
|
||||
// are reference-counted; after a drop the client reconnects with a growing pause and subscribes
|
||||
// again with the last version it saw (`since`), so missed changes arrive at once. If the
|
||||
// WebSocket never opens (a proxy cuts it), the fallback is the SSE of /api/live and of the
|
||||
// terminal, and the WebSocket is tried again every minute. No data is polled on a timer: the
|
||||
// only timer is the connection check (ping every 15 s).
|
||||
import { useEffect, useRef, useSyncExternalStore } from "react";
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
|
||||
/** Shown through t.text by the terminal. */
|
||||
const NO_LINK = m("Нет связи с Peppa FACTORY");
|
||||
|
||||
export interface LiveTaskRow {
|
||||
id: number;
|
||||
status: string;
|
||||
title: string;
|
||||
column: "backlog" | "in_progress" | "review" | "done";
|
||||
other?: boolean;
|
||||
}
|
||||
export type LiveEvent =
|
||||
/** `messages` — new messages of a `chat:` scope, ready for this viewer (PEP-228, lib/chat-live-types.ts). */
|
||||
| { type: "change"; scope: string; v: string; parts: string[]; tasks?: LiveTaskRow[]; messages?: unknown[] }
|
||||
| { type: "step"; scope: string; step: { id: number } & Record<string, unknown> }
|
||||
| { type: "data"; scope: string; v: string; data: unknown }
|
||||
| { type: "frame"; scope: string; cols: number; rows: number; data: string }
|
||||
| { type: "out"; scope: string; data: string }
|
||||
| { type: "end"; scope: string }
|
||||
/** The subscription was refused (no access, unknown scope). */
|
||||
| { type: "error"; scope: string; status: number; error: string };
|
||||
export type LiveHandler = (e: LiveEvent) => void;
|
||||
export type LiveMode = "connecting" | "live" | "reconnecting" | "offline";
|
||||
|
||||
const PING_MS = 15_000;
|
||||
const PONG_WAIT_MS = 10_000;
|
||||
const BACKOFF_MAX_MS = 30_000;
|
||||
const WS_RETRY_FROM_SSE_MS = 60_000;
|
||||
/** WebSocket attempts that never opened before the SSE fallback. */
|
||||
const WS_FAILS_TO_SSE = 3;
|
||||
|
||||
interface Sub {
|
||||
handlers: Set<LiveHandler>;
|
||||
/** Handlers that want the scope only while the tab is visible. */
|
||||
heavy: number;
|
||||
v?: string;
|
||||
lastStep?: number;
|
||||
active: boolean;
|
||||
}
|
||||
|
||||
class LiveClient {
|
||||
private subs = new Map<string, Sub>();
|
||||
private ws: WebSocket | null = null;
|
||||
private transport: "ws" | "sse" = "ws";
|
||||
private everOpened = false;
|
||||
private failsBeforeOpen = 0;
|
||||
private attempt = 0;
|
||||
private retry: ReturnType<typeof setTimeout> | null = null;
|
||||
private pinger: ReturnType<typeof setInterval> | null = null;
|
||||
private pongTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private es: EventSource | null = null;
|
||||
private esScopes = "";
|
||||
private esTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private terms = new Map<string, EventSource>();
|
||||
private wsProbe: ReturnType<typeof setTimeout> | null = null;
|
||||
private acks = new Map<number, (error: string | null) => void>();
|
||||
private nextAck = 1;
|
||||
private modeListeners = new Set<() => void>();
|
||||
mode: LiveMode = "connecting";
|
||||
/** Boot id the server greeted the tab with. */
|
||||
boot: string | null = null;
|
||||
|
||||
constructor() {
|
||||
document.addEventListener("visibilitychange", () => this.onVisibility());
|
||||
window.addEventListener("online", () => this.reconnectNow());
|
||||
}
|
||||
|
||||
private setMode(m: LiveMode) {
|
||||
if (this.mode === m) return;
|
||||
this.mode = m;
|
||||
for (const fn of this.modeListeners) fn();
|
||||
}
|
||||
|
||||
onMode(fn: () => void): () => void {
|
||||
this.modeListeners.add(fn);
|
||||
return () => this.modeListeners.delete(fn);
|
||||
}
|
||||
|
||||
/** Watches `scope`; `heavy` scopes are dropped while the tab is hidden. */
|
||||
subscribe(scope: string, handler: LiveHandler, opts: { heavy?: boolean } = {}): () => void {
|
||||
let sub = this.subs.get(scope);
|
||||
if (!sub) this.subs.set(scope, (sub = { handlers: new Set(), heavy: 0, active: false }));
|
||||
sub.handlers.add(handler);
|
||||
if (opts.heavy) sub.heavy++;
|
||||
this.ensure();
|
||||
this.activate(scope);
|
||||
return () => {
|
||||
const s = this.subs.get(scope);
|
||||
if (!s) return;
|
||||
s.handlers.delete(handler);
|
||||
if (opts.heavy) s.heavy--;
|
||||
if (!s.handlers.size) {
|
||||
this.deactivate(scope);
|
||||
this.subs.delete(scope);
|
||||
this.syncSse();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/** Keyboard input / paste of a terminal; resolves to an error text or null. */
|
||||
input(scope: string, body: { keys?: string; paste?: string }): Promise<string | null> {
|
||||
if (this.transport === "ws" && this.ws?.readyState === WebSocket.OPEN) {
|
||||
const id = this.nextAck++;
|
||||
return new Promise((resolve) => {
|
||||
this.acks.set(id, resolve);
|
||||
this.ws!.send(JSON.stringify({ t: "in", scope, id, ...body }));
|
||||
});
|
||||
}
|
||||
const runner = scope.slice("terminal:".length);
|
||||
return fetch(`/api/runners/${runner}/terminal`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) })
|
||||
.then(async (r) => (r.ok ? null : (((await r.json().catch(() => null)) as { error?: string } | null)?.error ?? `HTTP ${r.status}`)))
|
||||
.catch(() => NO_LINK);
|
||||
}
|
||||
|
||||
private wanted(sub: Sub): boolean {
|
||||
return sub.handlers.size > 0 && !(document.visibilityState === "hidden" && sub.heavy > 0 && sub.heavy === sub.handlers.size);
|
||||
}
|
||||
|
||||
private activate(scope: string) {
|
||||
const sub = this.subs.get(scope);
|
||||
if (!sub || sub.active || !this.wanted(sub)) return;
|
||||
sub.active = true;
|
||||
if (this.transport === "ws") {
|
||||
if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(JSON.stringify({ t: "sub", scope, since: scope.startsWith("steps:") ? sub.lastStep : sub.v }));
|
||||
} else this.syncSse();
|
||||
}
|
||||
|
||||
private deactivate(scope: string) {
|
||||
const sub = this.subs.get(scope);
|
||||
if (!sub?.active) return;
|
||||
sub.active = false;
|
||||
if (this.transport === "ws") {
|
||||
if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(JSON.stringify({ t: "unsub", scope }));
|
||||
} else {
|
||||
this.terms.get(scope)?.close();
|
||||
this.terms.delete(scope);
|
||||
this.syncSse();
|
||||
}
|
||||
}
|
||||
|
||||
private onVisibility() {
|
||||
for (const [scope, sub] of this.subs) {
|
||||
if (this.wanted(sub)) this.activate(scope);
|
||||
else this.deactivate(scope);
|
||||
}
|
||||
if (document.visibilityState === "visible" && this.mode !== "live") this.reconnectNow();
|
||||
}
|
||||
|
||||
private dispatch(e: LiveEvent) {
|
||||
const sub = this.subs.get(e.scope);
|
||||
if (!sub) return;
|
||||
if ("v" in e && e.v) sub.v = e.v;
|
||||
if (e.type === "step") sub.lastStep = Math.max(sub.lastStep ?? 0, Number(e.step.id) || 0);
|
||||
for (const fn of [...sub.handlers]) {
|
||||
try {
|
||||
fn(e);
|
||||
} catch (err) {
|
||||
console.error("live:", err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private ensure() {
|
||||
if (this.ws || this.es || this.retry || this.transport === "sse") return;
|
||||
this.connectWs();
|
||||
}
|
||||
|
||||
private reconnectNow() {
|
||||
if (this.transport === "sse" || this.ws) return;
|
||||
if (this.retry) clearTimeout(this.retry);
|
||||
this.retry = null;
|
||||
this.connectWs();
|
||||
}
|
||||
|
||||
private connectWs() {
|
||||
if (typeof WebSocket === "undefined") return this.toSse();
|
||||
let opened = false;
|
||||
let ws: WebSocket;
|
||||
try {
|
||||
ws = new WebSocket(`${location.protocol === "https:" ? "wss" : "ws"}://${location.host}/api/ws`);
|
||||
} catch {
|
||||
return this.toSse();
|
||||
}
|
||||
this.ws = ws;
|
||||
if (this.transport === "ws") this.setMode(this.everOpened ? "reconnecting" : "connecting");
|
||||
ws.onopen = () => {
|
||||
opened = true;
|
||||
this.everOpened = true;
|
||||
this.failsBeforeOpen = 0;
|
||||
this.attempt = 0;
|
||||
if (this.transport === "sse") this.leaveSse();
|
||||
this.setMode("live");
|
||||
for (const sub of this.subs.values()) sub.active = false;
|
||||
for (const scope of this.subs.keys()) this.activate(scope);
|
||||
this.startPing();
|
||||
};
|
||||
ws.onmessage = (msg) => {
|
||||
let m: { t: string; scope?: string; type?: string; status?: number; error?: string; id?: number; boot?: string; v?: string };
|
||||
try {
|
||||
m = JSON.parse(String(msg.data));
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
if (m.t === "pong") {
|
||||
if (this.pongTimer) clearTimeout(this.pongTimer);
|
||||
this.pongTimer = null;
|
||||
} else if (m.t === "hello") this.boot = m.boot ?? null;
|
||||
else if (m.t === "ev") this.dispatch(m as unknown as LiveEvent);
|
||||
else if (m.t === "ok" && m.scope && m.v) {
|
||||
const sub = this.subs.get(m.scope);
|
||||
if (sub && !sub.v) sub.v = m.v;
|
||||
} else if (m.t === "err" && m.scope) {
|
||||
const sub = this.subs.get(m.scope);
|
||||
if (sub) sub.active = false;
|
||||
this.dispatch({ type: "error", scope: m.scope, status: m.status ?? 500, error: m.error ?? "" });
|
||||
} else if (m.t === "ack" && typeof m.id === "number") {
|
||||
this.acks.get(m.id)?.(m.error ?? null);
|
||||
this.acks.delete(m.id);
|
||||
}
|
||||
};
|
||||
ws.onclose = () => {
|
||||
if (this.ws !== ws) return;
|
||||
this.ws = null;
|
||||
this.stopPing();
|
||||
for (const [id, done] of this.acks) {
|
||||
done(NO_LINK);
|
||||
this.acks.delete(id);
|
||||
}
|
||||
for (const sub of this.subs.values()) sub.active = false;
|
||||
if (this.transport === "sse") return; // a failed probe from the fallback
|
||||
if (!opened && !this.everOpened && ++this.failsBeforeOpen >= WS_FAILS_TO_SSE) return this.toSse();
|
||||
this.scheduleReconnect();
|
||||
};
|
||||
}
|
||||
|
||||
private scheduleReconnect() {
|
||||
if (!this.subs.size) return; // nothing to watch: reconnect on the next subscribe
|
||||
this.setMode(this.attempt > 2 ? "offline" : "reconnecting");
|
||||
const pause = Math.min(BACKOFF_MAX_MS, 1000 * 2 ** this.attempt++) * (0.75 + Math.random() * 0.5);
|
||||
this.retry = setTimeout(() => {
|
||||
this.retry = null;
|
||||
this.connectWs();
|
||||
}, pause);
|
||||
}
|
||||
|
||||
/** Connection check — the one timer of the channel. */
|
||||
private startPing() {
|
||||
this.stopPing();
|
||||
this.pinger = setInterval(() => {
|
||||
const ws = this.ws;
|
||||
if (ws?.readyState !== WebSocket.OPEN || this.pongTimer) return;
|
||||
ws.send(JSON.stringify({ t: "ping" }));
|
||||
this.pongTimer = setTimeout(() => {
|
||||
this.pongTimer = null;
|
||||
ws.close();
|
||||
}, PONG_WAIT_MS);
|
||||
}, PING_MS);
|
||||
}
|
||||
|
||||
private stopPing() {
|
||||
if (this.pinger) clearInterval(this.pinger);
|
||||
if (this.pongTimer) clearTimeout(this.pongTimer);
|
||||
this.pinger = this.pongTimer = null;
|
||||
}
|
||||
|
||||
// ---- SSE fallback ----
|
||||
|
||||
private toSse() {
|
||||
this.transport = "sse";
|
||||
this.ws = null;
|
||||
for (const sub of this.subs.values()) sub.active = false;
|
||||
for (const scope of this.subs.keys()) this.activate(scope);
|
||||
this.syncSse();
|
||||
// Try the WebSocket again now and then (the proxy may let it through later).
|
||||
const probe = () => {
|
||||
this.wsProbe = null;
|
||||
if (this.transport !== "sse") return;
|
||||
if (!this.ws) this.connectWs();
|
||||
this.wsProbe = setTimeout(probe, WS_RETRY_FROM_SSE_MS);
|
||||
};
|
||||
this.wsProbe = setTimeout(probe, WS_RETRY_FROM_SSE_MS);
|
||||
}
|
||||
|
||||
private leaveSse() {
|
||||
this.transport = "ws";
|
||||
this.es?.close();
|
||||
this.es = null;
|
||||
this.esScopes = "";
|
||||
for (const es of this.terms.values()) es.close();
|
||||
this.terms.clear();
|
||||
if (this.wsProbe) clearTimeout(this.wsProbe);
|
||||
this.wsProbe = null;
|
||||
}
|
||||
|
||||
/** One EventSource for every hub scope (reopened when the set changes), one per terminal. */
|
||||
private syncSse() {
|
||||
if (this.transport !== "sse") return;
|
||||
if (this.esTimer) return;
|
||||
this.esTimer = setTimeout(() => {
|
||||
this.esTimer = null;
|
||||
if (this.transport !== "sse") return;
|
||||
const active = [...this.subs].filter(([, s]) => s.active);
|
||||
for (const [scope] of active.filter(([s]) => s.startsWith("terminal:"))) if (!this.terms.has(scope)) this.openTerminalSse(scope);
|
||||
const hub = active.filter(([s]) => !s.startsWith("terminal:")).map(([s]) => s).sort();
|
||||
const key = hub.join(",");
|
||||
if (key === this.esScopes && this.es) return;
|
||||
this.es?.close();
|
||||
this.es = null;
|
||||
this.esScopes = key;
|
||||
if (!hub.length) return;
|
||||
if (typeof EventSource === "undefined") return this.setMode("offline");
|
||||
const q = new URLSearchParams({ scope: key });
|
||||
for (const s of hub) {
|
||||
const sub = this.subs.get(s)!;
|
||||
const since = s.startsWith("steps:") ? sub.lastStep : sub.v;
|
||||
if (since) q.set(`since.${s}`, String(since));
|
||||
}
|
||||
const es = new EventSource(`/api/live?${q}`);
|
||||
this.es = es;
|
||||
let fails = 0;
|
||||
es.addEventListener("ready", () => {
|
||||
fails = 0;
|
||||
this.setMode("live");
|
||||
});
|
||||
for (const type of ["change", "step", "data"]) es.addEventListener(type, (e) => this.dispatch(JSON.parse((e as MessageEvent<string>).data) as LiveEvent));
|
||||
es.onerror = () => {
|
||||
// EventSource reconnects by itself (retry: 3000); after a few failures say so.
|
||||
this.setMode(++fails >= 3 ? "offline" : "reconnecting");
|
||||
};
|
||||
}, 50);
|
||||
}
|
||||
|
||||
private openTerminalSse(scope: string) {
|
||||
const es = new EventSource(`/api/runners/${scope.slice("terminal:".length)}/terminal`);
|
||||
this.terms.set(scope, es);
|
||||
for (const type of ["frame", "out"]) es.addEventListener(type, (e) => this.dispatch({ type, scope, ...JSON.parse((e as MessageEvent<string>).data) } as LiveEvent));
|
||||
es.addEventListener("end", () => {
|
||||
es.close();
|
||||
this.terms.delete(scope);
|
||||
this.dispatch({ type: "end", scope });
|
||||
});
|
||||
es.onerror = () => {
|
||||
if (es.readyState === EventSource.CLOSED) this.dispatch({ type: "error", scope, status: 404, error: "" });
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const g = globalThis as { __peppaLive?: LiveClient };
|
||||
/** The tab's channel (created on first use in the browser). */
|
||||
export function liveClient(): LiveClient {
|
||||
return (g.__peppaLive ??= new LiveClient());
|
||||
}
|
||||
|
||||
/** Calls `handler` with every event of `scope` (null — nothing). The latest handler is used without resubscribing. */
|
||||
export function useLive(scope: string | null, handler: LiveHandler, opts: { heavy?: boolean } = {}): void {
|
||||
const ref = useRef(handler);
|
||||
ref.current = handler;
|
||||
const heavy = !!opts.heavy;
|
||||
useEffect(() => {
|
||||
if (!scope) return;
|
||||
return liveClient().subscribe(scope, (e) => ref.current(e), { heavy });
|
||||
}, [scope, heavy]);
|
||||
}
|
||||
|
||||
/** The connection state for the indicator. */
|
||||
export function useLiveMode(): LiveMode {
|
||||
return useSyncExternalStore(
|
||||
(fn) => liveClient().onMode(fn),
|
||||
() => liveClient().mode,
|
||||
() => "connecting",
|
||||
);
|
||||
}
|
||||
|
||||
// ---- Islands (PEP-225): parts of a page that apply an event in place ----
|
||||
|
||||
/** Applies a `change` in place; returns the parts it fully applied (they need no server re-render). */
|
||||
export type Island = (e: Extract<LiveEvent, { type: "change" }>) => string[];
|
||||
const islands = new Set<Island>();
|
||||
|
||||
/** Registers an island for the page's `change` events (LiveRefresh asks them before re-rendering). */
|
||||
export function useLiveIsland(island: Island): void {
|
||||
const ref = useRef(island);
|
||||
ref.current = island;
|
||||
useEffect(() => {
|
||||
const fn: Island = (e) => ref.current(e);
|
||||
islands.add(fn);
|
||||
return () => {
|
||||
islands.delete(fn);
|
||||
};
|
||||
}, []);
|
||||
}
|
||||
|
||||
/** Parts of `e` the page's islands applied. */
|
||||
export function applyIslands(e: Extract<LiveEvent, { type: "change" }>): Set<string> {
|
||||
const done = new Set<string>();
|
||||
for (const fn of islands) {
|
||||
try {
|
||||
for (const p of fn(e)) done.add(p);
|
||||
} catch (err) {
|
||||
console.error("live island:", err);
|
||||
}
|
||||
}
|
||||
return done;
|
||||
}
|
||||
23
apps/web/lib/session-user.ts
Normal file
23
apps/web/lib/session-user.ts
Normal file
@ -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<User | null> {
|
||||
const p = verify<SessionPayload>(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;
|
||||
}
|
||||
@ -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,
|
||||
|
||||
@ -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",
|
||||
|
||||
116
apps/web/scripts/bench-live.ts
Normal file
116
apps/web/scripts/bench-live.ts
Normal file
@ -0,0 +1,116 @@
|
||||
// PEP-225: load of the tab channel — N tabs (WebSockets) on a COPY of a database, each watching
|
||||
// what a tab watches (home or a project board, a story, attention, version, me), while a writer
|
||||
// changes story statuses. Reports CPU of the process (hub + sockets), SQLite time of the hub's
|
||||
// checks and how fast an event reaches every tab.
|
||||
// PEPPA_DB=<copy> PEPPA_SECRET=x node apps/web/scripts/bench-live.ts [tabs=50] [seconds=20] [writesPerSec=2]
|
||||
import { createServer } from "node:http";
|
||||
import type { AddressInfo } from "node:net";
|
||||
import { discussionUnread, getNotifyPrefs, getUser, sign, userProjectIds } from "@peppa/core";
|
||||
import { createDb } from "@peppa/db";
|
||||
import { liveHub, setLiveProvider } from "@peppa/runner";
|
||||
import { createLiveWs, readCookie } from "@peppa/runner/live-ws";
|
||||
|
||||
const tabs = Number(process.argv[2] ?? 50);
|
||||
const seconds = Number(process.argv[3] ?? 20);
|
||||
const rate = Number(process.argv[4] ?? 2);
|
||||
const db = createDb();
|
||||
const c = db.$client;
|
||||
|
||||
const owner = c.prepare(`SELECT owner_id AS id FROM projects WHERE owner_id IS NOT NULL AND deleted_at IS NULL GROUP BY owner_id ORDER BY count(*) DESC LIMIT 1`).get() as { id: number };
|
||||
const user = (await getUser(db, owner.id))!;
|
||||
const projects = c.prepare(`SELECT id FROM projects WHERE owner_id = ? AND deleted_at IS NULL`).all(user.id) as Array<{ id: number }>;
|
||||
const taskRows = c.prepare(`SELECT id, project_id AS p, status FROM tasks WHERE project_id IN (${projects.map((p) => p.id).join(",")}) AND archived_at IS NULL LIMIT 40`).all() as Array<{ id: number; p: number; status: string }>;
|
||||
if (!taskRows.length) throw new Error("no tasks to change");
|
||||
|
||||
setLiveProvider("attention", async (_db, uid) => {
|
||||
// The queries of navCounts (lib/queries.ts needs the Next bundler for its imports).
|
||||
const ids = await userProjectIds(db, uid);
|
||||
const q = ids.length ? (c.prepare(`SELECT count(*) AS n FROM questions WHERE answered_at IS NULL AND project_id IN (${ids.join(",")})`).get() as { n: number }).n : 0;
|
||||
const w = ids.length ? (c.prepare(`SELECT count(*) AS n FROM sessions WHERE status = 'waiting_input' AND project_id IN (${ids.join(",")})`).get() as { n: number }).n : 0;
|
||||
const chats = [...(await discussionUnread(db, uid)).values()].reduce((a, b) => a + b, 0);
|
||||
const { sound } = await getNotifyPrefs(db, uid);
|
||||
return { count: q + w, chats, sound };
|
||||
});
|
||||
const token = sign({ uid: user.id, exp: Date.now() + 3600_000 });
|
||||
const ws = createLiveWs({ db, authenticate: async (req) => (readCookie(req.headers.cookie, "peppa_session") === token ? user : null), boot: () => "bench" });
|
||||
const server = createServer((_q, r) => r.end());
|
||||
server.on("upgrade", (q, s, h) => ws.handleUpgrade(q, s, h));
|
||||
await new Promise<void>((r) => server.listen(0, "127.0.0.1", r));
|
||||
const port = (server.address() as AddressInfo).port;
|
||||
|
||||
// Every change: when it was written, when each tab got it.
|
||||
const written = new Map<string, number>();
|
||||
const lat: number[] = [];
|
||||
let events = 0;
|
||||
const socks: WebSocket[] = [];
|
||||
for (let i = 0; i < tabs; i++) {
|
||||
const t = taskRows[i % taskRows.length]!;
|
||||
const scopes = i % 3 === 0 ? ["home", "attention", "version", "me"] : ["attention", "version", "me", `project:${t.p}`, `task:${t.id}`];
|
||||
const sock = new (WebSocket as unknown as new (u: string, o: object) => WebSocket)(`ws://127.0.0.1:${port}/api/ws`, { headers: { cookie: `peppa_session=${token}` } });
|
||||
sock.onopen = () => scopes.forEach((scope) => sock.send(JSON.stringify({ t: "sub", scope })));
|
||||
sock.onmessage = (e) => {
|
||||
const m = JSON.parse(String(e.data)) as { t: string; type?: string; tasks?: Array<{ id: number; status: string }> };
|
||||
if (m.t !== "ev") return;
|
||||
events++;
|
||||
for (const r of m.tasks ?? []) {
|
||||
const at = written.get(`${r.id}:${r.status}`);
|
||||
if (at) lat.push(performance.now() - at);
|
||||
}
|
||||
};
|
||||
socks.push(sock);
|
||||
}
|
||||
await new Promise((r) => setTimeout(r, 1500));
|
||||
console.log(`tabs: ${tabs} open=${ws.clients}, watched scopes: ${liveHub(db).watched.length}`);
|
||||
|
||||
// Time spent in the hub's checks (SQLite fingerprints + providers).
|
||||
const hub = liveHub(db) as unknown as { check: () => Promise<void> };
|
||||
const orig = hub.check.bind(hub);
|
||||
let checkMs = 0;
|
||||
let checks = 0;
|
||||
hub.check = async () => {
|
||||
const t = performance.now();
|
||||
await orig();
|
||||
checkMs += performance.now() - t;
|
||||
checks++;
|
||||
};
|
||||
|
||||
// Time per scope kind (BENCH_SCOPES=1).
|
||||
const perKind = new Map<string, number>();
|
||||
if (process.env.BENCH_SCOPES) {
|
||||
const h = liveHub(db) as unknown as { checkOne: (w: { scope: string }) => Promise<void> };
|
||||
const one = h.checkOne.bind(h);
|
||||
h.checkOne = async (w) => {
|
||||
const t = performance.now();
|
||||
await one(w);
|
||||
const k = w.scope.split(":")[0]!;
|
||||
perKind.set(k, (perKind.get(k) ?? 0) + performance.now() - t);
|
||||
};
|
||||
}
|
||||
const cpu0 = process.cpuUsage();
|
||||
const t0 = performance.now();
|
||||
const statuses = ["in_progress", "review", "backlog"];
|
||||
let writes = 0;
|
||||
const writer = setInterval(() => {
|
||||
const t = taskRows[writes % taskRows.length]!;
|
||||
const next = statuses[(statuses.indexOf(t.status) + 1) % statuses.length]!;
|
||||
t.status = next;
|
||||
written.set(`${t.id}:${next}`, performance.now());
|
||||
c.prepare(`UPDATE tasks SET status = ?, updated_at = ? WHERE id = ?`).run(next, Date.now(), t.id);
|
||||
writes++;
|
||||
}, 1000 / rate);
|
||||
await new Promise((r) => setTimeout(r, seconds * 1000));
|
||||
clearInterval(writer);
|
||||
await new Promise((r) => setTimeout(r, 1500));
|
||||
const cpu = process.cpuUsage(cpu0);
|
||||
const wall = performance.now() - t0;
|
||||
lat.sort((a, b) => a - b);
|
||||
const pct = (p: number) => (lat.length ? lat[Math.min(lat.length - 1, Math.floor(lat.length * p))]!.toFixed(0) : "-");
|
||||
console.log(`writes: ${writes} in ${seconds}s, events delivered: ${events}, hub checks: ${checks} (${(checkMs / Math.max(1, checks)).toFixed(1)} ms each, ${((checkMs / wall) * 100).toFixed(1)}% of wall time)`);
|
||||
console.log(`CPU: ${(((cpu.user + cpu.system) / 1000 / wall) * 100).toFixed(1)}% of one core (user ${(cpu.user / 1000).toFixed(0)} ms, system ${(cpu.system / 1000).toFixed(0)} ms)`);
|
||||
console.log(`write → tab latency: p50 ${pct(0.5)} ms, p95 ${pct(0.95)} ms, max ${pct(0.999)} ms (${lat.length} deliveries)`);
|
||||
if (perKind.size) console.log("ms per scope kind:", Object.fromEntries([...perKind].map(([k, v]) => [k, Math.round(v)])));
|
||||
for (const s of socks) s.close();
|
||||
ws.close();
|
||||
server.close();
|
||||
// Restore nothing: run it on a copy only.
|
||||
process.exit(0);
|
||||
40
apps/web/server.ts
Normal file
40
apps/web/server.ts
Normal file
@ -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<string, string | undefined>;
|
||||
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);
|
||||
@ -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:<id>", 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:<subscriptionId>`: вход в подписку ждёт автор или суперадмин. Пока область смотрят,
|
||||
хаб сам раз в 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`.
|
||||
@ -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:<id>` (ожидание входа в подписку),
|
||||
`me` (привязка Telegram), `terminal:<sessionId>` (вывод и ввод терминала).
|
||||
- События несут, что изменилось: части отпечатка и строки задач (`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`.
|
||||
@ -0,0 +1,112 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Один WebSocket на вкладку
|
||||
Веб SHALL принимать WebSocket `GET /api/ws` и вести через одно соединение вкладки подписки на все
|
||||
живые области: `home`, `runners`, `team`, `chats`, `project:<id>`, `task:<id>`, `steps:<sessionId>`,
|
||||
`terminal:<sessionId>`, `attention`, `version`, `observe`, `subs`, `login:<subscriptionId>`, `me`.
|
||||
Вход — cookie `peppa_session` с теми же проверками, что у страниц; соединение с чужим `Origin`
|
||||
или без входа MUST быть отклонено до апгрейда. Права на область — как у страницы: проект — доступ
|
||||
к проекту, `observe` и `subs` — суперадмин, `login:` — автор подписки или суперадмин.
|
||||
|
||||
#### Scenario: Подписка без прав
|
||||
- **GIVEN** пользователь «anna» без доступа к проекту PAY открыл WebSocket
|
||||
- **WHEN** он подписывается на `task:<id PAY-3>`
|
||||
- **THEN** сервер отвечает `{t:"err", scope:"task:<id>", status:404}`
|
||||
- **AND** события PAY-3 ему не приходят
|
||||
|
||||
#### Scenario: Событие доходит только до своей области
|
||||
- **GIVEN** у вкладки подписки `task:<id PAY-3>` и `attention`
|
||||
- **WHEN** PAY-4 меняет статус
|
||||
- **THEN** для `task:<id PAY-3>` ничего не приходит
|
||||
- **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:<id PAY>` и получила версию `v1`
|
||||
- **WHEN** соединение рвётся, PAY-3 уходит в ревью, вкладка переподключается с `since: v1`
|
||||
- **THEN** сразу приходит `change` для `project:<id PAY>`
|
||||
|
||||
#### 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** индикатор показывает «нет связи», клиент пробует снова с нарастающей паузой
|
||||
@ -0,0 +1,17 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Терминал через общий канал
|
||||
Вывод терминала раннера SHALL идти через WebSocket вкладки (область `terminal:<sessionId>`:
|
||||
`frame`, `out`, `end`), ввод — сообщением `{t:"in", keys|paste}` того же соединения с прежними
|
||||
правилами: только владелец или участник проекта, живая сессия, ≤1 КБ нажатий, ≤64 КБ вставки,
|
||||
40 запросов за 5 с. Без WebSocket терминал работает через прежние SSE и POST.
|
||||
|
||||
#### Scenario: Ввод через сокет
|
||||
- **GIVEN** участник проекта подписан на `terminal:<id>` живой сессии
|
||||
- **WHEN** он шлёт `{t:"in", scope:"terminal:<id>", 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 ничего не уходит
|
||||
@ -0,0 +1,17 @@
|
||||
## 1. Сервер
|
||||
- [x] 1.1 Хаб: новые области (`attention`, `version`, `observe`, `subs`, `login:`, `me`), `parts` и строки задач в `change`, версия `v` и `since`, поставщики данных от веба
|
||||
- [x] 1.2 `runner/live-ws.ts`: протокол, права, лимиты, пинг, терминал через сокет
|
||||
- [x] 1.3 `apps/web/server.ts` + регистрация канала в `instrumentation.ts`, проверка cookie без `next/headers`
|
||||
- [x] 1.4 Запуск: `package.json`, `install-launchd.sh`, `live-deploy.sh` (переустановка агента веба)
|
||||
|
||||
## 2. Клиент
|
||||
- [x] 2.1 `lib/live.ts`: одно соединение, подписки со счётчиком, переподключение, догон, SSE-запасной путь, скрытая вкладка
|
||||
- [x] 2.2 `LiveRefresh` на канале: острова, пропуск рендера, индикатор
|
||||
- [x] 2.3 Доска и шапка задачи — точечно; чаты — только свой чат
|
||||
- [x] 2.4 `AttentionBadge`, `VersionWatch`, `AgentSteps`, `RunnerTerminal` на канале
|
||||
- [x] 2.5 Убрать `AutoRefresh` и опросы: observability, подписки, `SubscriptionSetup`, `OpenBotButton`
|
||||
|
||||
## 3. Проверка
|
||||
- [x] 3.1 Тесты: права, своя/чужая область, догон, терминал через сокет, лимиты
|
||||
- [x] 3.2 Замер 50 вкладок (`scripts/bench-live.ts`), цифры в PR
|
||||
- [x] 3.3 typecheck, lint, тесты; браузер (в том числе узкий экран и обрыв связи)
|
||||
@ -0,0 +1,41 @@
|
||||
## Context
|
||||
PEP-225 дал вкладке один канал и «острова» (`useLiveIsland`): событие `change` применяется на
|
||||
месте, иначе `LiveRefresh` делает `router.refresh()` не чаще раза в 4 с. Чат проекта слушал общую
|
||||
область `chats` и перерисовывался на каждое новое сообщение своего чата (`e.chats`).
|
||||
|
||||
## Decisions
|
||||
1. **Своя область `chat:<id>`, на зрителя.** Сообщение, готовое к показу, зависит от зрителя:
|
||||
язык (`getUserLocale`), суперадмин видит текст без чистки (`cleanText`), «вы» у своих. Поэтому
|
||||
область ключуется зрителем, как `attention`/`me` (`PER_USER` теперь и по префиксу `chat:`).
|
||||
Отпечаток — один SQL по чату: `m` — последнее сообщение, `q` — вопросы проекта, `tg` — связь с
|
||||
группой, `x` — предложения и вложения 50 последних сообщений (они пишутся отдельной записью
|
||||
после сообщения). Доступ: чат проекта — `projectForUser`, мастер-чат — только его владелец.
|
||||
2. **Сообщение готовит сервер, рисует клиент.** Хаб берёт новые сообщения (`newChatMessagesView`,
|
||||
не больше 30 за раз; больше — без сообщений, страница перерисуется) и вложения, а вид для
|
||||
зрителя строит поставщик веба `setLiveChatView` (как `attention`): перевод `t.text`/`t.role`,
|
||||
`cleanText`, `splitForDisplay`, `messageLink` — тот же код, что у серверной страницы (вынесен
|
||||
в `lib/chat-text.ts`). Так перевод и чистка не едут в браузер (словари, ядро), а событие несёт
|
||||
данные, не HTML: текст в браузере — текстовые узлы React, ссылки — только http(s).
|
||||
Без поставщика (тесты хаба) — сырые поля сообщения.
|
||||
3. **Что рисуется на месте.** Клиент (`ChatLiveFeed`) отбирает сообщения своей переписки по тем же
|
||||
правилам, что запросы страницы: обсуждение — канал, `kind: user`, не команда; тред — его ключ;
|
||||
«События агентов» — всё. Часть `m` применена на месте, если все новые сообщения — из этой
|
||||
переписки и среди них нет вопроса или предложения (`render`). Часть `x` считается применённой,
|
||||
если в том же событии пришли сообщения (их вложения и предложения уже в них), иначе —
|
||||
перерисовка (вложение/кнопки пришли к уже показанному). `q`, `tg`, `*` — перерисовка.
|
||||
Сообщения другого треда — перерисовка: меняется список слева (последняя реплика, непрочитанное).
|
||||
4. **Без дублей.** Клиент держит дорисованные сообщения с `id` больше последнего, что нарисовал
|
||||
сервер (`lastId`); после перерисовки они уходят из состояния клиента — их рисует сервер.
|
||||
5. **Прочитано.** Дорисованное в видимой вкладке отмечается прочитанным действием
|
||||
`markChatReadAction` (обсуждение — `markDiscussionRead`, тред — `markThreadRead`), не чаще раза
|
||||
в секунду; иначе счётчик «нов.» показывал бы уже прочитанное.
|
||||
6. **«печатает…»** — клиентский: скрывается, когда в обсуждении дорисовано сообщение не от людей.
|
||||
7. **Мастер-чат** остаётся на `chats` с перерисовкой: в нём смешаны проекты и `important`,
|
||||
а пишут туда редко. `chatsAfter`/`e.chats` и `LiveRefresh chatId` удалены.
|
||||
|
||||
## Risks / Trade-offs
|
||||
- Список тредов слева не обновляется от сообщений открытой переписки до следующей перерисовки —
|
||||
осознанно: иначе каждая реплика снова перерисовывала бы страницу.
|
||||
- Язык зрителя без сохранённого выбора — русский (как `getUserLocale`), хотя страница могла взять
|
||||
язык из cookie; вход переносит cookie в настройку (`adoptLocale`), так что расхождение редкое.
|
||||
- Время «N мин назад» у дорисованного считает браузер.
|
||||
@ -0,0 +1,27 @@
|
||||
## Why
|
||||
После PEP-225 страница чата узнаёт о новом сообщении своего чата через канал вкладки, но
|
||||
показывает его серверной перерисовкой всей страницы — не чаще раза в 4 секунды. Ответ
|
||||
аналитика или реплика агента появляются с задержкой, страница целиком пересобирается на сервере.
|
||||
|
||||
## What Changes
|
||||
- Новая область канала `chat:<id>` — один чат проекта для одного зрителя (права — как у страницы
|
||||
чата). Событие `change` несёт новые сообщения чата уже готовыми к показу этому зрителю: автор,
|
||||
текст (переведённый и очищенный, как на странице), «Подробнее», вложения, ссылка, вид, тред.
|
||||
- Страница чата проекта дорисовывает сообщения своей переписки в ленту на месте, сразу, без
|
||||
перерисовки; отмечает их прочитанными; убирает «печатает…», когда ответил аналитик.
|
||||
- Серверная перерисовка остаётся для того, что на месте не нарисовать: вопрос и «готово» (карточки
|
||||
с кнопками), предложение аналитика с кнопками, сообщения других тредов (список слева), ответ на
|
||||
вопрос, вложение или предложение, пришедшее к уже показанному сообщению, привязка Telegram.
|
||||
- «Все события» (мастер-чат) — как раньше, область `chats`. Список чатов с новыми сообщениями в
|
||||
событии `chats` и фильтр по чату в `LiveRefresh` больше не нужны — убираются.
|
||||
|
||||
## Capabilities
|
||||
### Modified Capabilities
|
||||
- `live-updates`: область `chat:<id>` и сообщения чата на месте.
|
||||
|
||||
## Impact
|
||||
- `packages/runner/src/live.ts` (область, отпечаток, сообщения в событии, поставщик вида),
|
||||
`packages/core/src/chats.ts` (`newChatMessagesView`), `packages/shared` (`humanSize` без ядра).
|
||||
- `apps/web`: `lib/live-server.ts` (поставщик вида сообщения), `lib/chat-text.ts`,
|
||||
`components/ChatLiveFeed.tsx` (новый), страница `/chats/[chat]`, `LiveRefresh`.
|
||||
- Основа — PEP-225 (ветка ещё не в main: эта ветка начата от неё).
|
||||
@ -0,0 +1,38 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Сообщения чата на месте
|
||||
Канал SHALL давать область `chat:<id>` — чат проекта для одного зрителя (участник проекта или
|
||||
суперадмин; мастер-чат — только его владелец, иначе 404). Событие `change` этой области MUST
|
||||
нести новые сообщения чата, готовые к показу этому зрителю: автор, текст на его языке и очищенный
|
||||
как на странице, «Подробнее», вложения, ссылка, вид и тред. Страница чата проекта SHALL
|
||||
дорисовывать сообщения своей переписки в ленту сразу, без серверной перерисовки, и отмечать их
|
||||
прочитанными. Серверная перерисовка (не чаще раза в 4 с) остаётся для вопросов и «готово»,
|
||||
предложений с кнопками, сообщений других тредов и ответов на вопросы.
|
||||
|
||||
#### Scenario: Ответ аналитика появляется сразу
|
||||
- **GIVEN** владелец проекта PAY открыл «Чат с аналитиком» и написал «Что сейчас в работе?»
|
||||
- **WHEN** аналитик отвечает «В работе PAY-3»
|
||||
- **THEN** ответ появляется внизу ленты за долю секунды, а «печатает…» пропадает
|
||||
- **AND** серверная перерисовка страницы не запрашивается
|
||||
- **AND** счётчик новых сообщений чата PAY не растёт
|
||||
|
||||
#### Scenario: Вопрос агента — карточкой
|
||||
- **GIVEN** открыт тред задачи PAY-3
|
||||
- **WHEN** агент PAY-3 задаёт вопрос с вариантами «Да» и «Нет»
|
||||
- **THEN** страница перерисовывается с сервера и показывает карточку вопроса с кнопками
|
||||
|
||||
#### Scenario: Сообщение другого треда
|
||||
- **GIVEN** открыт тред задачи PAY-3
|
||||
- **WHEN** приходит сообщение в тред PAY-4
|
||||
- **THEN** в ленте PAY-3 оно не появляется
|
||||
- **AND** страница перерисовывается, чтобы обновить список слева
|
||||
|
||||
#### Scenario: Чужой чат
|
||||
- **GIVEN** пользователь «bob» не участник проекта PAY
|
||||
- **WHEN** он подписывается на `chat:<id чата PAY>`
|
||||
- **THEN** ответ 404, сообщения PAY к нему не приходят
|
||||
|
||||
#### Scenario: Сообщение другого чата
|
||||
- **GIVEN** владелец подписан на `chat:<id чата PAY>`
|
||||
- **WHEN** новое сообщение появляется в чате проекта SHOP
|
||||
- **THEN** событие `change` для чата PAY не приходит
|
||||
@ -0,0 +1,13 @@
|
||||
## 1. Сервер
|
||||
- [x] 1.1 `newChatMessagesView` в core, `humanSize` в `@peppa/shared/format`
|
||||
- [x] 1.2 Хаб: область `chat:<id>` на зрителя, доступ, отпечаток, сообщения в `change`, поставщик `setLiveChatView`; убрать `chatsAfter`
|
||||
- [x] 1.3 Веб: поставщик вида сообщения (`lib/chat-live.ts`), `messageLink` в `lib/chat-text.ts`, `markChatReadAction`
|
||||
|
||||
## 2. Клиент
|
||||
- [x] 2.1 `ChatLiveFeed`: остров `chat:<id>`, отбор по переписке, дорисовка сообщений и событий, прокрутка, «печатает…», прочитано
|
||||
- [x] 2.2 Страница `/chats/[chat]`: `LiveRefresh scope=chat:<id>`, `ChatLiveFeed`; `LiveRefresh` без `chatId`
|
||||
|
||||
## 3. Проверка
|
||||
- [x] 3.1 Тесты: доступ к `chat:<id>`, сообщение приходит своим и не приходит чужим, вид для зрителя, вопрос помечен `render`
|
||||
- [x] 3.2 typecheck, lint, тесты, сборка; живой веб-процесс (WebSocket-клиент: сообщение пришло готовым и очищенным) — браузера в окружении нет
|
||||
- [x] 3.3 Память, архив, PR
|
||||
@ -27,19 +27,20 @@
|
||||
- **THEN** ответ 404
|
||||
|
||||
### Requirement: Точечное обновление страницы и индикатор связи
|
||||
Страницы Главная, проект, стори и раннеры SHALL обновляться по событиям канала без
|
||||
перезагрузки и без потери введённого текста (обновление откладывается, пока пользователь
|
||||
печатает или оставил черновик), и показывать состояние связи: «в реальном времени»,
|
||||
«переподключение» или «опрос». Если канал недоступен, страница откатывается на опрос раз в 5 с.
|
||||
Страницы Главная, проект, стори, раннеры, команда, чаты, подписки и observability SHALL
|
||||
обновляться по событиям канала без перезагрузки и без потери введённого текста (серверный рендер
|
||||
откладывается, пока пользователь печатает или оставил черновик), и показывать состояние связи:
|
||||
«в реальном времени», «переподключение» или «нет связи». Если WebSocket недоступен, страница
|
||||
работает через SSE `/api/live`; опроса по таймеру нет.
|
||||
|
||||
#### Scenario: Черновик ответа
|
||||
- **GIVEN** PM печатает ответ на вопрос на странице стори
|
||||
- **WHEN** приходит `change`
|
||||
- **WHEN** приходит `change`, который нельзя применить на месте
|
||||
- **THEN** текст не теряется, страница обновится, когда поле отправят или очистят
|
||||
|
||||
#### Scenario: Канал недоступен
|
||||
- **WHEN** `/api/live` трижды подряд не открывается
|
||||
- **THEN** индикатор показывает «опрос», страница обновляется раз в 5 с
|
||||
- **WHEN** ни WebSocket, ни `/api/live` не открываются
|
||||
- **THEN** индикатор показывает «нет связи», клиент пробует снова с нарастающей паузой
|
||||
|
||||
### Requirement: Открытая страница не вызывает пересборку
|
||||
Веб в режиме разработки (живой сайт до официального запуска) SHALL NOT писать журнал браузера
|
||||
@ -85,3 +86,133 @@
|
||||
- **GIVEN** сервер только перезапущен, кэш пуст, Gitea недоступна
|
||||
- **WHEN** пользователь открывает доску
|
||||
- **THEN** доска открывается с именем репозитория и ссылкой, видимость не показана
|
||||
|
||||
### Requirement: Один WebSocket на вкладку
|
||||
Веб SHALL принимать WebSocket `GET /api/ws` и вести через одно соединение вкладки подписки на все
|
||||
живые области: `home`, `runners`, `team`, `chats`, `project:<id>`, `task:<id>`, `steps:<sessionId>`,
|
||||
`terminal:<sessionId>`, `attention`, `version`, `observe`, `subs`, `login:<subscriptionId>`, `me`.
|
||||
Вход — cookie `peppa_session` с теми же проверками, что у страниц; соединение с чужим `Origin`
|
||||
или без входа MUST быть отклонено до апгрейда. Права на область — как у страницы: проект — доступ
|
||||
к проекту, `observe` и `subs` — суперадмин, `login:` — автор подписки или суперадмин.
|
||||
|
||||
#### Scenario: Подписка без прав
|
||||
- **GIVEN** пользователь «anna» без доступа к проекту PAY открыл WebSocket
|
||||
- **WHEN** он подписывается на `task:<id PAY-3>`
|
||||
- **THEN** сервер отвечает `{t:"err", scope:"task:<id>", status:404}`
|
||||
- **AND** события PAY-3 ему не приходят
|
||||
|
||||
#### Scenario: Событие доходит только до своей области
|
||||
- **GIVEN** у вкладки подписки `task:<id PAY-3>` и `attention`
|
||||
- **WHEN** PAY-4 меняет статус
|
||||
- **THEN** для `task:<id PAY-3>` ничего не приходит
|
||||
- **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:<id PAY>` и получила версию `v1`
|
||||
- **WHEN** соединение рвётся, PAY-3 уходит в ревью, вкладка переподключается с `since: v1`
|
||||
- **THEN** сразу приходит `change` для `project:<id PAY>`
|
||||
|
||||
#### 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
|
||||
|
||||
### Requirement: Сообщения чата на месте
|
||||
Канал SHALL давать область `chat:<id>` — чат проекта для одного зрителя (участник проекта или
|
||||
суперадмин; мастер-чат — только его владелец, иначе 404). Событие `change` этой области MUST
|
||||
нести новые сообщения чата, готовые к показу этому зрителю: автор, текст на его языке и очищенный
|
||||
как на странице, «Подробнее», вложения, ссылка, вид и тред. Страница чата проекта SHALL
|
||||
дорисовывать сообщения своей переписки в ленту сразу, без серверной перерисовки, и отмечать их
|
||||
прочитанными. Серверная перерисовка (не чаще раза в 4 с) остаётся для вопросов и «готово»,
|
||||
предложений с кнопками, сообщений других тредов и ответов на вопросы.
|
||||
|
||||
#### Scenario: Ответ аналитика появляется сразу
|
||||
- **GIVEN** владелец проекта PAY открыл «Чат с аналитиком» и написал «Что сейчас в работе?»
|
||||
- **WHEN** аналитик отвечает «В работе PAY-3»
|
||||
- **THEN** ответ появляется внизу ленты за долю секунды, а «печатает…» пропадает
|
||||
- **AND** серверная перерисовка страницы не запрашивается
|
||||
- **AND** счётчик новых сообщений чата PAY не растёт
|
||||
|
||||
#### Scenario: Вопрос агента — карточкой
|
||||
- **GIVEN** открыт тред задачи PAY-3
|
||||
- **WHEN** агент PAY-3 задаёт вопрос с вариантами «Да» и «Нет»
|
||||
- **THEN** страница перерисовывается с сервера и показывает карточку вопроса с кнопками
|
||||
|
||||
#### Scenario: Сообщение другого треда
|
||||
- **GIVEN** открыт тред задачи PAY-3
|
||||
- **WHEN** приходит сообщение в тред PAY-4
|
||||
- **THEN** в ленте PAY-3 оно не появляется
|
||||
- **AND** страница перерисовывается, чтобы обновить список слева
|
||||
|
||||
#### Scenario: Чужой чат
|
||||
- **GIVEN** пользователь «bob» не участник проекта PAY
|
||||
- **WHEN** он подписывается на `chat:<id чата PAY>`
|
||||
- **THEN** ответ 404, сообщения PAY к нему не приходят
|
||||
|
||||
#### Scenario: Сообщение другого чата
|
||||
- **GIVEN** владелец подписан на `chat:<id чата PAY>`
|
||||
- **WHEN** новое сообщение появляется в чате проекта SHOP
|
||||
- **THEN** событие `change` для чата PAY не приходит
|
||||
|
||||
@ -49,3 +49,19 @@
|
||||
#### Scenario: Слишком часто или слишком много
|
||||
- **WHEN** пользователь шлёт больше 40 запросов ввода за 5 с или нажатия больше 1 КБ
|
||||
- **THEN** ответ 429 или 413, в tmux лишнее не уходит
|
||||
|
||||
### Requirement: Терминал через общий канал
|
||||
Вывод терминала раннера SHALL идти через WebSocket вкладки (область `terminal:<sessionId>`:
|
||||
`frame`, `out`, `end`), ввод — сообщением `{t:"in", keys|paste}` того же соединения с прежними
|
||||
правилами: только владелец или участник проекта, живая сессия, ≤1 КБ нажатий, ≤64 КБ вставки,
|
||||
40 запросов за 5 с. Без WebSocket терминал работает через прежние SSE и POST.
|
||||
|
||||
#### Scenario: Ввод через сокет
|
||||
- **GIVEN** участник проекта подписан на `terminal:<id>` живой сессии
|
||||
- **WHEN** он шлёт `{t:"in", scope:"terminal:<id>", 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 ничего не уходит
|
||||
|
||||
@ -5,6 +5,7 @@
|
||||
import { guardUntrusted } from "./untrusted.ts";
|
||||
import { attachments, events, chatMessages, type Db } from "@peppa/db";
|
||||
import { peppaHome } from "@peppa/shared";
|
||||
import { humanSize } from "@peppa/shared/format";
|
||||
import { m as tr } from "@peppa/shared/i18n";
|
||||
import { and, asc, eq, inArray, isNull, lt } from "drizzle-orm";
|
||||
import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
|
||||
@ -129,7 +130,7 @@ export interface AttachmentView {
|
||||
const kindOf = (mime: string): AttachmentKind => (mime.startsWith("image/") ? "image" : mime === "application/pdf" ? "pdf" : mime.startsWith("application/vnd.") ? "office" : "text");
|
||||
export const attachmentView = (a: Attachment): AttachmentView => ({ id: a.id, name: a.name, mime: a.mime, size: a.size, kind: kindOf(a.mime) });
|
||||
|
||||
export const humanSize = (n: number) => (n < 1024 ? `${n} B` : n < 1024 * 1024 ? `${Math.round(n / 1024)} KB` : `${(n / 1024 / 1024).toFixed(1).replace(/\.0$/, "")} MB`);
|
||||
export { humanSize };
|
||||
|
||||
/** Stores an uploaded file for a project's person; it stays unlinked until a form takes it. */
|
||||
export async function saveAttachment(db: Db, user: Pick<User, "id">, o: { projectId: number; name: string; data: Uint8Array; now?: Date }): Promise<AttachmentView> {
|
||||
|
||||
@ -246,6 +246,12 @@ export async function chatMessagesView(db: Db, chatId: number, o: { threadKey?:
|
||||
return views(db, and(...w)!, o.limit ?? 100, o.before);
|
||||
}
|
||||
|
||||
/** PEP-228: messages of a chat newer than `after`, oldest first; `more` — there were more than `limit` (the page re-renders). */
|
||||
export async function newChatMessagesView(db: Db, chatId: number, after: number, limit = 30): Promise<{ messages: ChatMessageView[]; more: boolean }> {
|
||||
const rows = await views(db, and(eq(chatMessages.chatId, chatId), gt(chatMessages.id, after))!, limit + 1);
|
||||
return rows.length > limit ? { messages: [], more: true } : { messages: rows, more: false };
|
||||
}
|
||||
|
||||
// ── discussion (PEP-106) ────────────────────────────────────────────────────
|
||||
|
||||
/** People's messages in a project chat's channel: no agents, no events, no commands. */
|
||||
|
||||
@ -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"
|
||||
}
|
||||
}
|
||||
|
||||
270
packages/runner/src/live-ws.ts
Normal file
270
packages/runner/src/live-ws.ts
Normal file
@ -0,0 +1,270 @@
|
||||
// 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:<id>", 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<string, unknown>;
|
||||
|
||||
/** One tab's connection: its subscriptions, input and limits. */
|
||||
export class LiveConnection {
|
||||
private subs = new Map<LiveScope, () => void>();
|
||||
private pending = new Set<LiveScope>();
|
||||
private window = { start: 0, n: 0 };
|
||||
private input: Promise<void> = 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<void> {
|
||||
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;
|
||||
// glossary-ignore: the runner terminal is the engineer's view (PEP-9).
|
||||
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) {
|
||||
// glossary-ignore: the runner terminal is the engineer's view (PEP-9).
|
||||
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<User | null>;
|
||||
/** 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<WebSocket, number>();
|
||||
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;
|
||||
}
|
||||
@ -1,22 +1,55 @@
|
||||
// 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:<sessionId>` 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:<sessionId>` 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 { attachmentsByMessage, findChangeDir, newChatMessagesView, isSuperadmin, listenEvents, observeDb, observeDbPath, projectForUser, STEP_EVENT, stepView, type AttachmentView, type ChatMessageView, type StepView, type User } from "@peppa/core";
|
||||
import { chats, 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", "chat"] 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, `messages` — new messages of a `chat:` scope as its viewer sees them (PEP-228).
|
||||
*/
|
||||
| { type: "change"; scope: LiveScope; v: string; parts: string[]; tasks?: LiveTaskRow[]; messages?: unknown[] }
|
||||
| { 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 +58,103 @@ 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|chat):[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<LiveScope>();
|
||||
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:<id>` the author of that sign-in or a superadmin,
|
||||
* `chat:<id>` the project's people (a master chat — its owner only).
|
||||
*/
|
||||
export async function checkScopeAccess(db: Db, user: User, scope: LiveScope): Promise<void> {
|
||||
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;
|
||||
}
|
||||
if (kind === "chat") {
|
||||
const chat = (await db.select({ userId: chats.userId, projectId: chats.projectId }).from(chats).where(eq(chats.id, id)))[0];
|
||||
if (!chat) throw notFound();
|
||||
if (chat.projectId == null) {
|
||||
if (chat.userId !== user.id) throw notFound();
|
||||
return;
|
||||
}
|
||||
await projectForUser(db, user.id, chat.projectId).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<string, string>;
|
||||
const str = (row: Record<string, unknown> | undefined): Parts => Object.fromEntries(Object.entries(row ?? {}).map(([k, v]) => [k, String(v ?? "")]));
|
||||
|
||||
/** tasks.md of a change, found once a minute: the archive listing is the slow part of a story's check (PEP-225 bench). */
|
||||
const mdPaths = new Map<string, { file: string | null; at: number }>();
|
||||
function tasksMdPath(ws: string, change: string): string | null {
|
||||
const key = `${ws}|${change}`;
|
||||
const hit = mdPaths.get(key);
|
||||
if (hit && Date.now() - hit.at < 60_000 && (!hit.file || existsSync(hit.file))) return hit.file;
|
||||
const found = findChangeDir(ws, change);
|
||||
const file = found ? join(found.dir, "tasks.md") : null;
|
||||
if (mdPaths.size > 2000) mdPaths.clear();
|
||||
mdPaths.set(key, { file, at: Date.now() });
|
||||
return file;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 +162,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,21 +173,22 @@ function fingerprint(db: Db, scope: LiveScope): string {
|
||||
(SELECT openspec_change FROM tasks WHERE id = ?1) AS ch`,
|
||||
)
|
||||
.get(id) as Record<string, string | number | null> | 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) {
|
||||
const found = findChangeDir(String(row.ws), String(row.ch));
|
||||
const file = found && join(found.dir, "tasks.md");
|
||||
const file = tasksMdPath(String(row.ws), String(row.ch));
|
||||
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 +198,22 @@ function fingerprint(db: Db, scope: LiveScope): string {
|
||||
(SELECT updated_at FROM projects WHERE id = ?1) AS p`,
|
||||
)
|
||||
.get(id) as Record<string, unknown>;
|
||||
return Object.values(row).join("|");
|
||||
return str(row);
|
||||
}
|
||||
if (kind === "chat") {
|
||||
// PEP-228: one chat — `m` new messages (sent along), `q` questions of its project, `tg` the
|
||||
// linked group, `x` offers and files of its latest messages (written right after a message).
|
||||
const row = c
|
||||
.prepare(
|
||||
`SELECT
|
||||
(SELECT coalesce(max(id),0) FROM chat_messages WHERE chat_id = ?1) AS m,
|
||||
(SELECT count(*) || ':' || count(answered_at) FROM questions WHERE project_id = (SELECT project_id FROM chats WHERE id = ?1)) AS q,
|
||||
(SELECT coalesce(tg_chat_id,'') FROM chats WHERE id = ?1) AS tg,
|
||||
(SELECT count(*) FROM settings WHERE key IN (SELECT 'chat.offer:' || id FROM chat_messages WHERE chat_id = ?1 ORDER BY id DESC LIMIT 50)) || ':' ||
|
||||
(SELECT count(*) FROM attachments WHERE chat_message_id IN (SELECT id FROM chat_messages WHERE chat_id = ?1 ORDER BY id DESC LIMIT 50)) AS x`,
|
||||
)
|
||||
.get(id) as Record<string, unknown>;
|
||||
return str(row);
|
||||
}
|
||||
if (kind === "chats") {
|
||||
// PEP-62: a new chat message (projected or written) or a question answered anywhere.
|
||||
@ -111,7 +226,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<string, unknown>;
|
||||
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<string, unknown>;
|
||||
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<string, unknown> | 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<string, unknown> | 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<string, unknown>;
|
||||
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 +268,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,78 +280,205 @@ function fingerprint(db: Db, scope: LiveScope): string {
|
||||
}`,
|
||||
)
|
||||
.get() as Record<string, unknown>;
|
||||
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<number, Row> {
|
||||
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) }]));
|
||||
}
|
||||
|
||||
/** A value scope's provider: the web registers `attention` (it owns navCounts). */
|
||||
export type LiveProvider = (db: Db, userId: number) => Promise<unknown> | unknown;
|
||||
const g = globalThis as { __peppaLiveHub?: LiveHub; __peppaLiveProviders?: Map<string, LiveProvider>; __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);
|
||||
}
|
||||
|
||||
/** PEP-228: new messages of a chat as the viewer `userId` sees them (the web registers its view). */
|
||||
export type LiveChatView = (db: Db, userId: number, messages: ChatMessageView[], files: Map<number, AttachmentView[]>) => Promise<unknown[]> | unknown[];
|
||||
const gv = globalThis as { __peppaLiveChatView?: LiveChatView };
|
||||
export function setLiveChatView(fn: LiveChatView): void {
|
||||
gv.__peppaLiveChatView = fn;
|
||||
}
|
||||
/** Most new messages one event carries; more — the page re-renders. */
|
||||
export const LIVE_CHAT_MAX = 30;
|
||||
|
||||
const VALUE_SCOPES = new Set(["attention", "version"]);
|
||||
const PER_USER = new Set(["attention", "me"]);
|
||||
/** Hub key of a scope: per-user scopes (and a chat — its messages are shown per viewer) are watched per viewer. */
|
||||
const keyOf = (scope: LiveScope, userId: number) => (PER_USER.has(scope) || scope.startsWith("chat:") ? `${scope}@${userId}` : scope);
|
||||
|
||||
interface Watch {
|
||||
scope: LiveScope;
|
||||
userId: number;
|
||||
listeners: Set<Listener>;
|
||||
parts?: Parts;
|
||||
v?: string;
|
||||
rows?: Map<number, Row>;
|
||||
chatMax?: number;
|
||||
lastStep?: number;
|
||||
/** Value scopes: last value sent (JSON). */
|
||||
value?: string;
|
||||
}
|
||||
|
||||
class LiveHub {
|
||||
private listeners = new Map<LiveScope, Set<Listener>>();
|
||||
private prints = new Map<LiveScope, string>();
|
||||
private lastStep = new Map<LiveScope, number>();
|
||||
private watches = new Map<string, Watch>();
|
||||
private timer: ReturnType<typeof setInterval> | null = null;
|
||||
private wakeTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private stopSocket: (() => Promise<void>) | null = null;
|
||||
private seen = "";
|
||||
private checking: Promise<void> | null = null;
|
||||
private again = false;
|
||||
private lastObserve = 0;
|
||||
private lastLoginPoll = 0;
|
||||
private run = 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<string, string | number | undefined> } = {}): () => 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.startsWith("chat:")) 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<unknown> {
|
||||
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?.();
|
||||
// A stop and a new start may come before the socket is up: only the current run keeps it.
|
||||
const run = ++this.run;
|
||||
listenEvents("web", () => this.wake())
|
||||
.then((stop) => {
|
||||
if (this.timer) this.stopSocket = stop;
|
||||
if (this.timer && run === this.run && !this.stopSocket) this.stopSocket = stop;
|
||||
else void stop();
|
||||
})
|
||||
.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 +503,125 @@ 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<void> {
|
||||
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.startsWith("chat:")) {
|
||||
const max = Number(parts.m) || 0;
|
||||
if (max > (w.chatMax ?? 0)) {
|
||||
const messages = await this.chatMessages(w, w.chatMax ?? 0);
|
||||
if (messages) e.messages = messages;
|
||||
}
|
||||
w.chatMax = max;
|
||||
}
|
||||
this.send(w, e);
|
||||
} catch (err) {
|
||||
console.error(`live: ${scope} check failed`, err);
|
||||
}
|
||||
}
|
||||
|
||||
/** New messages of a watched chat for its viewer; undefined — too many or failed (the page re-renders). */
|
||||
private async chatMessages(w: Watch, after: number): Promise<unknown[] | undefined> {
|
||||
try {
|
||||
const { messages, more } = await newChatMessagesView(this.db, Number(w.scope.slice(5)), after, LIVE_CHAT_MAX);
|
||||
if (more) return undefined;
|
||||
const files = await attachmentsByMessage(this.db, messages.map((m) => m.id));
|
||||
const view = gv.__peppaLiveChatView;
|
||||
return view ? await view(this.db, w.userId, messages, files) : messages.map((m) => ({ ...m, files: files.get(m.id) ?? [] }));
|
||||
} catch (err) {
|
||||
console.error(`live: ${w.scope} messages failed`, err);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
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<Response> {
|
||||
/** 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<string, string> } = {}): Promise<Response> {
|
||||
for (const s of scopes) await checkScopeAccess(db, user, s);
|
||||
const enc = new TextEncoder();
|
||||
let cleanup = () => {};
|
||||
@ -303,7 +653,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();
|
||||
|
||||
@ -8,7 +8,8 @@
|
||||
"./palette": "./src/palette.ts",
|
||||
"./i18n": "./src/i18n/index.ts",
|
||||
"./wording": "./src/wording.ts",
|
||||
"./glossary": "./src/glossary.ts"
|
||||
"./glossary": "./src/glossary.ts",
|
||||
"./format": "./src/format.ts"
|
||||
},
|
||||
"scripts": {
|
||||
"typecheck": "tsc -p ."
|
||||
|
||||
4
packages/shared/src/format.ts
Normal file
4
packages/shared/src/format.ts
Normal file
@ -0,0 +1,4 @@
|
||||
// Small formatters safe for the browser bundle (no Node modules).
|
||||
|
||||
/** «12 KB» — the size of a file for a person. */
|
||||
export const humanSize = (n: number) => (n < 1024 ? `${n} B` : n < 1024 * 1024 ? `${Math.round(n / 1024)} KB` : `${(n / 1024 / 1024).toFixed(1).replace(/\.0$/, "")} MB`);
|
||||
@ -221,6 +221,9 @@ export const runner: Dict = {
|
||||
"{who}: остановлен по лимиту, время сброса неизвестно — попробую продолжить в {time}.": "{who}: stopped by the limit, reset time unknown — will try to resume at {time}.",
|
||||
|
||||
// Live updates
|
||||
"Неизвестное сообщение": "Unknown message",
|
||||
"Слишком много областей": "Too many scopes",
|
||||
"Ввод — только в терминал": "Input goes to a terminal only",
|
||||
"Неизвестная область: {scope}": "Unknown scope: {scope}",
|
||||
"Нужна область (scope)": "A scope is required",
|
||||
|
||||
|
||||
@ -303,8 +303,8 @@ export const story: Dict = {
|
||||
"подключение…": "connecting…",
|
||||
"в реальном времени": "live",
|
||||
"переподключение…": "reconnecting…",
|
||||
"опрос раз в 5 с": "polling every 5 s",
|
||||
"Канал событий недоступен — страница обновляется по таймеру": "The event stream is unavailable — the page refreshes on a timer",
|
||||
"нет связи — пробуем снова": "offline — retrying",
|
||||
"Нет связи с Peppa FACTORY — страница обновится, когда связь вернётся": "No connection to Peppa FACTORY — the page will update when it is back",
|
||||
"Страница обновляется сама, когда что-то меняется": "The page refreshes by itself when something changes",
|
||||
Превью: "Preview",
|
||||
Посмотреть: "View",
|
||||
|
||||
@ -171,6 +171,9 @@ export const runner: Dict = {
|
||||
"{who} упёрлась в лимит.": "{who} лимитке тірелді.",
|
||||
"{who}: остановлен по лимиту, продолжит в {time} сам.": "{who}: лимит бойынша тоқтатылды, өзі жалғастырады: {time}.",
|
||||
"{who}: остановлен по лимиту, время сброса неизвестно — попробую продолжить в {time}.": "{who}: лимит бойынша тоқтатылды, қалпына келу уақыты белгісіз — жалғастыруға тырысамын: {time}.",
|
||||
"Неизвестное сообщение": "Белгісіз хабарлама",
|
||||
"Слишком много областей": "Аймақтар тым көп",
|
||||
"Ввод — только в терминал": "Енгізу тек терминалға",
|
||||
"Неизвестная область: {scope}": "Белгісіз аймақ: {scope}",
|
||||
"Нужна область (scope)": "Аймақ (scope) керек",
|
||||
"планировщик ответил не по формату — попробуйте ещё раз или уточните описание эпика": "жоспарлаушы форматқа сай жауап бермеді — қайталап көріңіз немесе эпик сипаттамасын нақтылаңыз",
|
||||
|
||||
@ -281,8 +281,8 @@ export const story: Dict = {
|
||||
"подключение…": "қосылуда…",
|
||||
"в реальном времени": "нақты уақытта",
|
||||
"переподключение…": "қайта қосылуда…",
|
||||
"опрос раз в 5 с": "5 с сайын сұрау",
|
||||
"Канал событий недоступен — страница обновляется по таймеру": "Оқиғалар арнасы қолжетімсіз — бет таймер бойынша жаңартылады",
|
||||
"нет связи — пробуем снова": "байланыс жоқ — қайта көріп жатырмыз",
|
||||
"Нет связи с Peppa FACTORY — страница обновится, когда связь вернётся": "Peppa FACTORY-мен байланыс жоқ — байланыс қалпына келгенде бет жаңарады",
|
||||
"Страница обновляется сама, когда что-то меняется": "Бір нәрсе өзгергенде бет өзі жаңарады",
|
||||
"Превью": "Превью",
|
||||
"Посмотреть": "Қарау",
|
||||
|
||||
150
packages/testkit/test/chat-live.test.ts
Normal file
150
packages/testkit/test/chat-live.test.ts
Normal file
@ -0,0 +1,150 @@
|
||||
// PEP-228: a chat page's own scope `chat:<id>` — access like the page's, new messages of the chat
|
||||
// come in the event (and only to this chat's watchers); the page draws messages of its
|
||||
// conversation in place and leaves questions, offers and other threads to a server re-render.
|
||||
import assert from "node:assert/strict";
|
||||
import { after, describe, test } from "node:test";
|
||||
import { LiveConnection } from "@peppa/runner/live-ws";
|
||||
import { core, db, project, runner, teardown } from "./helpers.ts";
|
||||
|
||||
process.env.PEPPA_SECRET = "mock-secret-for-tests";
|
||||
after(teardown);
|
||||
|
||||
const { chatParts, inView } = (await import(new URL("../../../apps/web/lib/chat-live-types.ts", import.meta.url).href)) as typeof import("../../../apps/web/lib/chat-live-types.ts");
|
||||
|
||||
let seq = 0;
|
||||
const user = (login: string) => core.upsertUserFromGitea(db, { id: 9300 + seq++, login }, { access_token: "x" });
|
||||
type Msg = Record<string, unknown> & { t: string };
|
||||
|
||||
function conn(u: import("@peppa/core").User) {
|
||||
const out: Msg[] = [];
|
||||
const c = new LiveConnection(db, u, (m) => out.push(m as Msg), () => {});
|
||||
return { c, out, send: (m: object) => c.receive(JSON.stringify(m)), events: () => out.filter((m) => m.t === "ev") as Array<Msg & { parts: string[]; messages?: Array<Record<string, unknown>> }> };
|
||||
}
|
||||
|
||||
async function ownedChat(login: string) {
|
||||
const owner = await user(login);
|
||||
const p = await project({ turns: [] });
|
||||
const ref = await core.resolveTask(db, p.taskKey);
|
||||
await core.setProjectOwner(db, ref.project.id, owner.id);
|
||||
const chat = await core.ensureProjectChat(db, ref.project.id);
|
||||
return { owner, ref, chat };
|
||||
}
|
||||
|
||||
const say = (chatId: number, text: string, o: Partial<Parameters<typeof core.addChatMessage>[1]> = {}) =>
|
||||
core.addChatMessage(db, { chatId, kind: "user", authorKind: "agent", authorLogin: "Аналитик", text, ...o });
|
||||
|
||||
describe("chat messages in place (PEP-228)", () => {
|
||||
test("Чужой чат: 404, мастер-чат — только владельцу", async () => {
|
||||
const a = await ownedChat("cl-owner-1");
|
||||
const bob = await user("cl-bob-1");
|
||||
const x = conn(bob);
|
||||
await x.send({ t: "sub", scope: `chat:${a.chat.id}` });
|
||||
assert.equal(x.out.at(-1)!.status, 404);
|
||||
const master = await core.ensureMasterChat(db, a.owner.id);
|
||||
await x.send({ t: "sub", scope: `chat:${master.id}` });
|
||||
assert.equal(x.out.at(-1)!.status, 404, "somebody else's master chat");
|
||||
await x.send({ t: "sub", scope: "chat:999999" });
|
||||
assert.equal(x.out.at(-1)!.status, 404);
|
||||
assert.deepEqual(x.c.scopes, []);
|
||||
const own = conn(a.owner);
|
||||
await own.send({ t: "sub", scope: `chat:${master.id}` });
|
||||
assert.equal(own.out.at(-1)!.t, "ok");
|
||||
x.c.close();
|
||||
own.c.close();
|
||||
});
|
||||
|
||||
test("Ответ аналитика приходит в событии своего чата и не приходит в чужой", async () => {
|
||||
const a = await ownedChat("cl-owner-2");
|
||||
const b = await ownedChat("cl-owner-3");
|
||||
const x = conn(a.owner);
|
||||
await x.send({ t: "sub", scope: `chat:${a.chat.id}` });
|
||||
assert.equal(x.out.at(-1)!.t, "ok");
|
||||
try {
|
||||
await say(b.chat.id, "Ответ в другом проекте");
|
||||
await runner.liveHub(db).check();
|
||||
assert.equal(x.events().length, 0, "another chat is not this scope");
|
||||
|
||||
const m = await say(a.chat.id, "В работе PAY-3");
|
||||
await runner.liveHub(db).check();
|
||||
const ev = x.events().at(-1)!;
|
||||
assert.ok(ev, "the change arrives");
|
||||
assert.ok(ev.parts.includes("m"));
|
||||
assert.deepEqual(ev.messages?.map((r) => [r.id, r.text, r.authorKind]), [[m!.id, "В работе PAY-3", "agent"]]);
|
||||
assert.deepEqual(ev.messages?.[0]!.files, []);
|
||||
} finally {
|
||||
x.c.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("Вид для зрителя: поставщик веба получает зрителя и сообщения", async () => {
|
||||
const a = await ownedChat("cl-owner-4");
|
||||
const seen: Array<[number, number[]]> = [];
|
||||
runner.setLiveChatView((_db, userId, messages) => {
|
||||
seen.push([userId, messages.map((m) => m.id)]);
|
||||
return messages.map((m) => ({ id: m.id, main: `для ${userId}` }));
|
||||
});
|
||||
const x = conn(a.owner);
|
||||
await x.send({ t: "sub", scope: `chat:${a.chat.id}` });
|
||||
try {
|
||||
const m = await say(a.chat.id, "Готово");
|
||||
await runner.liveHub(db).check();
|
||||
assert.deepEqual(seen.at(-1), [a.owner.id, [m!.id]]);
|
||||
assert.deepEqual(x.events().at(-1)!.messages, [{ id: m!.id, main: `для ${a.owner.id}` }]);
|
||||
} finally {
|
||||
x.c.close();
|
||||
runner.setLiveChatView(undefined as never);
|
||||
}
|
||||
});
|
||||
|
||||
test("Вопрос агента: в событии с пометкой вопроса, на месте не рисуется", async () => {
|
||||
const a = await ownedChat("cl-owner-5");
|
||||
const x = conn(a.owner);
|
||||
await x.send({ t: "sub", scope: `chat:${a.chat.id}` });
|
||||
try {
|
||||
await core.askPm(db, a.ref, { kind: "question", text: "Какой разделитель?", options: [";", ","] });
|
||||
await core.syncChats(db);
|
||||
await runner.liveHub(db).check();
|
||||
const evs = x.events();
|
||||
assert.ok(evs.some((e) => e.parts.includes("q")), "questions changed — the page re-renders");
|
||||
const withMsg = evs.find((e) => e.messages?.length);
|
||||
assert.ok(withMsg?.messages?.some((r) => r.question), "the question message is in the event");
|
||||
} finally {
|
||||
x.c.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("what the chat page draws in place (PEP-228)", () => {
|
||||
const msg = (o: Record<string, unknown>) => ({ id: 1, threadKey: null, kind: "user", command: false, notice: false, render: false, ...o }) as never;
|
||||
|
||||
test("Сообщение своей переписки — на месте, без перерисовки", () => {
|
||||
const r = chatParts({ parts: ["m"], messages: [msg({ id: 5 })] }, { kind: "discussion" });
|
||||
assert.deepEqual(r.applied, ["x", "m"]);
|
||||
assert.deepEqual(r.add.map((m) => m.id), [5]);
|
||||
});
|
||||
|
||||
test("Вопрос или кнопки — перерисовка", () => {
|
||||
const r = chatParts({ parts: ["m", "q"], messages: [msg({ id: 6, threadKey: "task:3", kind: "question", render: true })] }, { kind: "thread", key: "task:3" });
|
||||
assert.deepEqual(r.applied, ["x"]);
|
||||
assert.deepEqual(r.add, []);
|
||||
});
|
||||
|
||||
test("Сообщение другого треда — не в ленту, перерисовка списка", () => {
|
||||
const r = chatParts({ parts: ["m"], messages: [msg({ id: 7, threadKey: "task:4", kind: "event" })] }, { kind: "thread", key: "task:3" });
|
||||
assert.deepEqual(r.applied, ["x"]);
|
||||
assert.deepEqual(r.add, []);
|
||||
});
|
||||
|
||||
test("Без сообщений (их слишком много) — перерисовка", () => {
|
||||
assert.deepEqual(chatParts({ parts: ["m", "x"] }, { kind: "feed" }).applied, []);
|
||||
});
|
||||
|
||||
test("Обсуждение: без событий, команд и служебных строк; «События агентов» — всё", () => {
|
||||
assert.equal(inView(msg({ threadKey: "task:3" }), { kind: "discussion" }), false);
|
||||
assert.equal(inView(msg({ kind: "event" }), { kind: "discussion" }), false);
|
||||
assert.equal(inView(msg({ command: true }), { kind: "discussion" }), false);
|
||||
assert.equal(inView(msg({ notice: true }), { kind: "discussion" }), false);
|
||||
assert.equal(inView(msg({ threadKey: "task:3", kind: "event" }), { kind: "feed" }), true);
|
||||
assert.equal(inView(msg({ kind: "event" }), { kind: "channel" }), true);
|
||||
});
|
||||
});
|
||||
228
packages/testkit/test/live-ws.test.ts
Normal file
228
packages/testkit/test/live-ws.test.ts
Normal file
@ -0,0 +1,228 @@
|
||||
// PEP-225: one WebSocket per tab — subscriptions with access checks, events only for their own
|
||||
// scope with the changed task rows, catching up after a drop, the terminal (output and input)
|
||||
// over the socket, limits, and the upgrade itself (login, origin).
|
||||
import assert from "node:assert/strict";
|
||||
import { createServer, type Server } from "node:http";
|
||||
import type { AddressInfo } from "node:net";
|
||||
import { after, describe, test } from "node:test";
|
||||
import { createLiveWs, LiveConnection, LIVE_WS_RATE_MAX, type LiveWs } from "@peppa/runner/live-ws";
|
||||
import { core, db, project, runner, teardown, waitFor } from "./helpers.ts";
|
||||
|
||||
process.env.PEPPA_SECRET = "mock-secret-for-tests";
|
||||
after(teardown);
|
||||
|
||||
let seq = 0;
|
||||
const user = (login: string) => core.upsertUserFromGitea(db, { id: 9100 + seq++, login }, { access_token: "x" });
|
||||
type Msg = Record<string, unknown> & { t: string };
|
||||
|
||||
/** A connection driven directly: what the server sent and how it closed. */
|
||||
function conn(u: import("@peppa/core").User) {
|
||||
const out: Msg[] = [];
|
||||
const closed: Array<{ code: number; reason: string }> = [];
|
||||
const c = new LiveConnection(db, u, (m) => out.push(m as Msg), (code, reason) => closed.push({ code, reason }));
|
||||
const send = (m: object) => c.receive(JSON.stringify(m));
|
||||
return { c, out, closed, send };
|
||||
}
|
||||
|
||||
async function ownedStory(login: string) {
|
||||
const owner = await user(login);
|
||||
const p = await project({ turns: [] });
|
||||
const ref = await core.resolveTask(db, p.taskKey);
|
||||
await core.setProjectOwner(db, ref.project.id, owner.id);
|
||||
return { owner, p, ref };
|
||||
}
|
||||
|
||||
describe("tab channel (PEP-225)", () => {
|
||||
test("Подписка без прав: ответ 404, события не приходят", async () => {
|
||||
const { ref } = await ownedStory("ws-owner-1");
|
||||
const outsider = await user("ws-outsider-1");
|
||||
const x = conn(outsider);
|
||||
await x.send({ t: "sub", scope: `task:${ref.task.id}` });
|
||||
assert.deepEqual(x.out.at(-1), { t: "err", scope: `task:${ref.task.id}`, status: 404, error: "Не найдено" });
|
||||
await x.send({ t: "sub", scope: "observe" });
|
||||
assert.equal(x.out.at(-1)!.status, 404, "observe — only a superadmin");
|
||||
await x.send({ t: "sub", scope: "nonsense" });
|
||||
assert.equal(x.out.at(-1)!.status, 400);
|
||||
assert.deepEqual(x.c.scopes, []);
|
||||
x.c.close();
|
||||
});
|
||||
|
||||
test("Событие доходит только до своей области — со строкой задачи", async () => {
|
||||
const a = await ownedStory("ws-owner-2");
|
||||
const b = await core.createTask(db, { projectId: a.ref.project.id, title: "Соседняя задача" });
|
||||
const x = conn(a.owner);
|
||||
await x.send({ t: "sub", scope: `task:${a.ref.task.id}` });
|
||||
assert.equal(x.out.at(-1)!.t, "ok");
|
||||
try {
|
||||
await core.updateTask(db, b, { status: "in_progress" });
|
||||
await runner.liveHub(db).check();
|
||||
assert.equal(x.out.filter((m) => m.t === "ev").length, 0, "another story is not this scope");
|
||||
|
||||
await core.updateTask(db, a.ref, { status: "review" });
|
||||
await runner.liveHub(db).check();
|
||||
const ev = x.out.find((m) => m.t === "ev") as Msg & { tasks?: Array<{ id: number; status: string; column: string }>; parts: string[] };
|
||||
assert.ok(ev, "change of the story arrives");
|
||||
assert.equal(ev.type, "change");
|
||||
assert.ok(ev.parts.includes("t"));
|
||||
assert.deepEqual(ev.tasks?.map((r) => [r.id, r.status, r.column]), [[a.ref.task.id, "review", "review"]]);
|
||||
} finally {
|
||||
x.c.close();
|
||||
}
|
||||
assert.ok(!runner.liveHub(db).watched.includes(`task:${a.ref.task.id}`), "closing the tab unsubscribes");
|
||||
});
|
||||
|
||||
test("Доска проекта: смена статуса — строка без пометки other, новая задача — с пометкой", async () => {
|
||||
const a = await ownedStory("ws-owner-3");
|
||||
const x = conn(a.owner);
|
||||
const scope = `project:${a.ref.project.id}`;
|
||||
await x.send({ t: "sub", scope });
|
||||
try {
|
||||
await core.updateTask(db, a.ref, { status: "in_progress" });
|
||||
await runner.liveHub(db).check();
|
||||
const first = x.out.filter((m) => m.t === "ev").at(-1) as Msg & { tasks: Array<{ id: number; other?: boolean; column: string }> };
|
||||
assert.deepEqual(first.tasks.map((r) => [r.id, r.column, r.other ?? false]), [[a.ref.task.id, "in_progress", false]]);
|
||||
const fresh = (await core.createTask(db, { projectId: a.ref.project.id, title: "Новая" })).task;
|
||||
await runner.liveHub(db).check();
|
||||
const second = x.out.filter((m) => m.t === "ev").at(-1) as Msg & { tasks: Array<{ id: number; other?: boolean }> };
|
||||
assert.deepEqual(second.tasks.map((r) => [r.id, r.other]), [[fresh.id, true]], "a new card can't be drawn in place");
|
||||
} finally {
|
||||
x.c.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("Связь пропала: переподключение с since догоняет пропущенное, без изменений — тишина", async () => {
|
||||
const a = await ownedStory("ws-owner-4");
|
||||
const scope = `project:${a.ref.project.id}`;
|
||||
const first = conn(a.owner);
|
||||
await first.send({ t: "sub", scope });
|
||||
const v1 = first.out.find((m) => m.t === "ok")!.v as string;
|
||||
assert.ok(v1, "ok carries the version");
|
||||
first.c.close(); // the drop
|
||||
|
||||
// Nothing changed: no event on re-subscribe. A watcher keeps the scope alive meanwhile.
|
||||
const keep = conn(a.owner);
|
||||
await keep.send({ t: "sub", scope });
|
||||
const same = conn(a.owner);
|
||||
await same.send({ t: "sub", scope, since: v1 });
|
||||
assert.equal(same.out.filter((m) => m.t === "ev").length, 0);
|
||||
same.c.close();
|
||||
|
||||
await core.updateTask(db, a.ref, { status: "review" });
|
||||
await runner.liveHub(db).check();
|
||||
const back = conn(a.owner);
|
||||
await back.send({ t: "sub", scope, since: v1 });
|
||||
const ev = back.out.find((m) => m.t === "ev") as Msg & { parts: string[] };
|
||||
assert.ok(ev, "the missed change arrives at once");
|
||||
assert.deepEqual(ev.parts, ["*"]);
|
||||
back.c.close();
|
||||
keep.c.close();
|
||||
});
|
||||
|
||||
test("Шаги агента после since приходят при переподключении", async () => {
|
||||
const a = await ownedStory("ws-owner-5");
|
||||
const s = await core.createSession(db, { projectId: a.ref.project.id, taskId: a.ref.task.id });
|
||||
await core.recordStep(db, s, { tool: "Bash", kind: "command", text: "one", ok: true });
|
||||
const keep = conn(a.owner);
|
||||
await keep.send({ t: "sub", scope: `steps:${s.id}` });
|
||||
const seen = (await db.$client.prepare(`SELECT max(id) AS id FROM events WHERE session_id = ? AND type = 'step'`).get(s.id)) as { id: number };
|
||||
await core.recordStep(db, s, { tool: "Bash", kind: "command", text: "two", ok: true });
|
||||
await runner.liveHub(db).check();
|
||||
const back = conn(a.owner);
|
||||
await back.send({ t: "sub", scope: `steps:${s.id}`, since: seen.id });
|
||||
const steps = back.out.filter((m) => m.t === "ev" && m.type === "step").map((m) => (m.step as { text: string }).text);
|
||||
assert.deepEqual(steps, ["two"]);
|
||||
back.c.close();
|
||||
keep.c.close();
|
||||
});
|
||||
|
||||
test("Значение области: attention отдаёт текущее при подписке и новое при изменении", async () => {
|
||||
const a = await ownedStory("ws-owner-6");
|
||||
let n = 1;
|
||||
runner.setLiveProvider("attention", (_db, uid) => ({ count: uid === a.owner.id ? n : -1, sound: false }));
|
||||
const x = conn(a.owner);
|
||||
await x.send({ t: "sub", scope: "attention" });
|
||||
await waitFor("first value", async () => x.out.some((m) => m.t === "ev" && m.type === "data"));
|
||||
assert.deepEqual((x.out.find((m) => m.type === "data")!.data as { count: number }).count, 1);
|
||||
n = 2;
|
||||
await core.askPm(db, a.ref, { kind: "question", text: "Какой цвет?" });
|
||||
await runner.liveHub(db).check();
|
||||
await waitFor("new value", async () => x.out.filter((m) => m.type === "data").length === 2);
|
||||
assert.equal((x.out.filter((m) => m.type === "data")[1]!.data as { count: number }).count, 2);
|
||||
x.c.close();
|
||||
});
|
||||
|
||||
test("Терминал через сокет: кадр, ввод с подтверждением, завершённая сессия — отказ", async () => {
|
||||
const a = await ownedStory("ws-owner-7");
|
||||
const s = await core.createSession(db, { projectId: a.ref.project.id, taskId: a.ref.task.id });
|
||||
const name = `peppa-wsterm-${process.pid}`;
|
||||
await core.updateSession(db, s.id, { tmuxName: name, status: "running" });
|
||||
await runner.tmux.newSession({ name, cwd: a.p.dir, command: `sh -c 'while read l; do echo "got:$l"; done'`, env: {}, width: 100 });
|
||||
const x = conn(a.owner);
|
||||
const scope = `terminal:${s.id}`;
|
||||
try {
|
||||
await x.send({ t: "sub", scope });
|
||||
assert.equal(x.out.at(-1)!.t, "ok");
|
||||
await waitFor("frame", async () => x.out.some((m) => m.t === "ev" && m.type === "frame"));
|
||||
await x.send({ t: "in", scope, keys: "hi\r", id: 1 });
|
||||
assert.deepEqual(x.out.find((m) => m.t === "ack"), { t: "ack", id: 1 });
|
||||
await waitFor("echo", async () => (await runner.tmux.capturePane(name)).includes("got:hi"));
|
||||
await waitFor("echo over the socket", async () => x.out.some((m) => m.t === "ev" && (m.type === "out" || m.type === "frame") && String(m.data).includes("got:hi")));
|
||||
|
||||
const outsider = conn(await user("ws-outsider-7"));
|
||||
await outsider.send({ t: "sub", scope });
|
||||
assert.equal(outsider.out.at(-1)!.status, 404);
|
||||
await outsider.send({ t: "in", scope, keys: "rm\r", id: 9 });
|
||||
assert.ok(outsider.out.find((m) => m.t === "ack" && m.id === 9)!.error, "no input without access");
|
||||
|
||||
await core.updateSession(db, s.id, { status: "done", endedAt: new Date() });
|
||||
await x.send({ t: "in", scope, keys: "late\r", id: 2 });
|
||||
assert.ok((x.out.find((m) => m.t === "ack" && m.id === 2) as Msg).error, "finished session refuses input");
|
||||
} finally {
|
||||
x.c.close();
|
||||
await runner.tmux.killSession(name).catch(() => {});
|
||||
}
|
||||
});
|
||||
|
||||
test("Сообщения слишком часто: соединение закрывается 1008", async () => {
|
||||
const x = conn(await user("ws-spammer"));
|
||||
const now = Date.now();
|
||||
for (let i = 0; i <= LIVE_WS_RATE_MAX; i++) await x.c.receive(JSON.stringify({ t: "ping" }), now);
|
||||
assert.deepEqual(x.closed, [{ code: 1008, reason: "rate" }]);
|
||||
x.c.close();
|
||||
});
|
||||
|
||||
test("Апгрейд: без входа 401, чужой сайт 403, свой — hello и подписка", async () => {
|
||||
const owner = await user("ws-http-owner");
|
||||
const ws: LiveWs = createLiveWs({ db, authenticate: async (req) => (req.headers.cookie === "peppa_session=good" ? owner : null), boot: () => "boot-1" });
|
||||
const server: Server = createServer((_req, res) => res.end());
|
||||
server.on("upgrade", (req, socket, head) => ws.handleUpgrade(req, socket, head));
|
||||
await new Promise<void>((r) => server.listen(0, "127.0.0.1", r));
|
||||
const port = (server.address() as AddressInfo).port;
|
||||
const url = `ws://127.0.0.1:${port}/api/ws`;
|
||||
const open = (headers: Record<string, string>) =>
|
||||
new Promise<{ ok: boolean; msgs: Msg[]; sock: WebSocket }>((resolve) => {
|
||||
const sock = new (WebSocket as unknown as new (u: string, o: object) => WebSocket)(url, { headers });
|
||||
const msgs: Msg[] = [];
|
||||
sock.onmessage = (e) => msgs.push(JSON.parse(String(e.data)));
|
||||
sock.onopen = () => resolve({ ok: true, msgs, sock });
|
||||
sock.onerror = () => resolve({ ok: false, msgs, sock });
|
||||
});
|
||||
try {
|
||||
assert.equal((await open({})).ok, false, "no login");
|
||||
assert.equal((await open({ cookie: "peppa_session=good", origin: "https://evil.example" })).ok, false, "foreign origin");
|
||||
const good = await open({ cookie: "peppa_session=good", origin: `http://127.0.0.1:${port}` });
|
||||
assert.ok(good.ok);
|
||||
await waitFor("hello", async () => good.msgs.some((m) => m.t === "hello"));
|
||||
assert.equal(good.msgs[0]!.boot, "boot-1");
|
||||
good.sock.send(JSON.stringify({ t: "sub", scope: "home" }));
|
||||
good.sock.send(JSON.stringify({ t: "ping" }));
|
||||
await waitFor("ok + pong", async () => good.msgs.some((m) => m.t === "ok") && good.msgs.some((m) => m.t === "pong"));
|
||||
assert.equal(ws.clients, 1);
|
||||
good.sock.close();
|
||||
await waitFor("closed", async () => ws.clients === 0);
|
||||
} finally {
|
||||
ws.close();
|
||||
server.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
@ -202,14 +202,14 @@ describe("live hub and SSE (PEP-37)", () => {
|
||||
await core.setSetting(db, "heartbeat:test", { at: Date.now() });
|
||||
await core.updateTask(db, b.ref, { status: "in_progress" });
|
||||
await core.recordStep(db, s, { tool: "Bash", kind: "command", text: "ls", ok: true });
|
||||
hub.check();
|
||||
await hub.check();
|
||||
assert.deepEqual(got.map((e) => e.type), ["step"]);
|
||||
assert.equal(got[0]!.type === "step" && got[0]!.step.text, "ls");
|
||||
// A question on the story: change (via the check the notify() poke schedules).
|
||||
await core.askPm(db, a.ref, { kind: "question", text: "Какой цвет?" });
|
||||
await waitFor("change event", async () => got.some((e) => e.type === "change"), 5000);
|
||||
const n = got.length;
|
||||
hub.check();
|
||||
await hub.check();
|
||||
assert.equal(got.length, n, "no repeat without a new write");
|
||||
} finally {
|
||||
stop();
|
||||
@ -244,7 +244,7 @@ describe("live hub and SSE (PEP-37)", () => {
|
||||
};
|
||||
await until(/event: ready/);
|
||||
await core.updateTask(db, ref, { title: "Переименовано" }, undefined, "live-owner");
|
||||
await until(/event: change\ndata: \{"type":"change","scope":"task:\d+"\}/);
|
||||
await until(/event: change\ndata: \{"type":"change","scope":"task:\d+","v":"[\w-]+","parts":\[[^\]]*"t"[^\]]*\],"tasks":\[\{"id":\d+,"status":"[a-z_]+","title":"Переименовано"/);
|
||||
ac.abort();
|
||||
await reader.cancel().catch(() => {});
|
||||
});
|
||||
|
||||
31
pnpm-lock.yaml
generated
31
pnpm-lock.yaml
generated
@ -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:
|
||||
|
||||
@ -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)
|
||||
|
||||
@ -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
|
||||
}
|
||||
|
||||
Loading…
Reference in New Issue
Block a user