Compare commits

...

2 Commits

Author SHA1 Message Date
Асель
3fa4d7959f PEP-179: «Погоня за задачей» на странице «Команда» — компонент, живая область, service worker, переводы, тест
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 22:34:50 +05:00
Асель
c24794c2d7 PEP-179: WIP from previous session 2026-11-16 22:34:50 +05:00
26 changed files with 1478 additions and 18 deletions

View File

@ -21,6 +21,7 @@
- mock-gitea `POST /tags` ставит настоящий git-тег: репозиторию нужны коммиты (`addRepo(…, { files })`), а target — существующий SHA (`gitea.sha(owner, repo, "main")`), иначе `deployProd`/`autoPublish` в тесте молча не срабатывают. Новое слово в «Нельзя» docs/glossary.md проверяй `pnpm lint` сразу: оно может уже стоять в чужих текстах («хост», «эндпоинт»).
- Новая фраза Claude о лимите (PEP-166: «continuing automatically at 6pm») — в `parseResetTime` и таблицу limits.test.ts, иначе подписка зря считается свободной.
- Codex 0.169 удалил `--full-auto` (PEP-171): режим — `CODEX_DEFAULT_MODE` (providers.ts), срочно — `PEPPA_CODEX_MODE` в .env.
- drizzle в select из одной таблицы убирает квалификатор у `${table.col}` внутри sql`` — в подзапросе `s.agent_id = ${agents.id}` значило `s.id` (PEP-179, listAgents.busy); пиши `agents.id` строкой.
## Решения
- Продукт по-настоящему (PEP-112): секреты проекта доходят до выкатки сами (хук `deploy-env` → override в `peppa-deploy.sh`); `ANTHROPIC_*/CLAUDE_*/OPENCODE_*` — только продукту; нужное от владельца — `product.needs:<id>` (MCP `declare_needs`); приёмка — `productReviewTick`. После правок `template/` — `scripts/push-template.sh` и `peppa ci connect <KEY>` старым проектам.

View File

@ -53,6 +53,7 @@
- **Обращения пользователей (PEP-143)**: «Сообщить о проблеме» в самой Peppa FACTORY. Таблица `feedback` (миграция 0019; статусы `received` → `analyzed` → `planned` → `fixed` | `rejected`, автору — четыре слова `FEEDBACK_USER_STATUS`; JSON `context`, `screenshots`, `analysis`), всё в `core/feedback.ts`: `submitFeedback` (текст и/или ≤5 картинок PNG/JPEG/WebP по сигнатуре `sniffImage`, ≤5 МБ, файлы `$PEPPA_HOME/feedback/<id>/<n>.<ext>` под своими именами, предел `PEPPA_FEEDBACK_MAX_PER_HOUR` = 10 на пользователя), `feedbackForUser`/`feedbackScreenshot` (автор или суперадмин, иначе null → 404), решения только суперадмина — `fixFeedback` (вариант разбора → задача в `PEPPA_PLATFORM_KEY`; ошибка — в эпик «Стабильность», то есть приоритет PEP-103; intake `done`), `linkFeedback`, `rejectFeedback` (ответ автору с причиной), `closeFixedFeedback` (задача `done` → «Исправили: …»). Агент — `feedbackTick` в тике вачдога (`runner/feedback.ts`): `claudePrint` на подписке платформенного проекта (`PEPPA_FEEDBACK_BIN` ← `PEPPA_INTAKE_BIN`, `PEPPA_FEEDBACK_MODEL`), скриншоты файлами, контекст — 10 последних `incidents` и открытые задачи платформы (`feedbackPromptContext`); одна попытка: сбой, ответ не по форме, `PEPPA_FEEDBACK=off`, умерший процесс (`analysis_started_at` старше таймаута) → `finishFeedbackAnalysis({error})` — суперадмину без разбора, один раз; обращения из Telegram ждут `PEPPA_FEEDBACK_SETTLE_SEC` (20), пока дойдёт альбом. Суперадминам — `announceFeedback`: событие уведомлений `feedback` (строка настроек только суперадмину; автору ответы идут тем же событием), скриншоты — метод outbox `sendPhoto` (`params.photo_path`, бот читает файл и шлёт multipart `TelegramApi.sendPhoto`), карточка `feedbackCardText` с кнопками `f:<id>:o<N>|dup|no`. Бот (`apps/bot/src/feedback.ts`): `/problem` → режим `bot.feedback:<userId>` (15 мин), следующее сообщение (текст / фото с подписью / голос) — обращение, фото следом (2 мин) прикладываются; «Не исправлять» ждёт причину следующим сообщением (`bot.feedback.reject:<userId>`, «-» — без причины). Веб: `POST /api/feedback` (multipart; вид и язык берёт сервер), `GET /api/feedback/<id>/shots/<n>`, плавающая кнопка `FeedbackButton` в раскладке (файл, перетаскивание, вставка из буфера; ошибки браузера — `window.__peppaErrors` из `ErrorReporter`), страница `/feedback` (свои; суперадмину — все с фильтром `?status=` и решениями, `components/Feedback.tsx`), секция на Главной, пункт меню суперадмина со счётчиком. Мок — роль `feedback` в `mock-intake`, фото/`sendPhoto`/`editMessageReplyMarkup` в `mock-telegram`; тест `feedback.test.ts`
- **Вложения (PEP-159)**: таблица `attachments` (миграция 0021: проект, загрузивший, `task_id`/`chat_message_id`/`event_id`, имя для показа, имя на диске, mime, размер), всё в `core/attachments.ts`: `sniffAttachment` (тип по содержимому — PNG/JPEG/WebP/GIF, PDF, DOCX/XLSX/PPTX по ZIP, текст TXT/MD/CSV/JSON; SVG/HTML/скрипт/архив/исполняемый — отказ), файлы `$PEPPA_HOME/files/<projectId>/<id>/<id>.<ext>`, ≤5 файлов по ≤20 МБ. Загрузка двухшаговая: `POST /api/attachments` (multipart, `projectId`) сразу после выбора → id, форма несёт скрытые `attachment=<id>`, действия (`postChatAction`/`postToChat`, `commentStoryAction`, `addTask`) зовут `linkAttachments` (только свои неотправленные файлы того же проекта); висящие старше суток убирает `pruneAttachments` (вачдог, раз в час). Отдача `GET /api/attachments/<id>` (владелец/участник/суперадмин, иначе 404; nosniff, картинки и PDF inline, прочее скачиванием). UI: `components/AttachField.tsx` (скрепка, перетаскивание и Ctrl+V на поле), `components/Attachments.tsx` (миниатюры и строки). Аналитик: `attachmentsForModel` → `claudePrint({files})` для картинок и PDF, текст файлов (≤20 КБ) в промпт, Office — по имени; чат берёт файлы сообщений после курсора, `storyRefineTick` — новых комментариев и самой стори. Агент: `launch` и `syncSessionAttachments` копируют файлы стори в `<рабочая копия>/.peppa/attachments/` (внутри свой `.gitignore` с `*`), `get_task` — раздел «Приложенные файлы»; на отдельном хосте не копируется. Не сделано (второй PR): Telegram-бот, извлечение текста из Office. Тест `attachments.test.ts`
- **Пауза проекта (PEP-174)**: `core/project-pause.ts` — `settings` `project.paused:<id>` `{since, by, sessions}` (без миграции), `isProjectPaused`/`assertProjectActive`/`pausedProjectIds`, окно последней паузы `project.pause.last:<id>` и `duringPause` (что появилось во время паузы, не рассылается потом). `runner/pause.ts`: `pauseProject` (сначала отметка, потом `stopSession` живых агентов, событие `project_paused`), `resumeProject` (событие `project_resumed` «Пауза: с … по …», `activateRunnerTask` + `resumeSession` остановленных паузой). Узкие места: запуск агента — `startSession`/`startRunner`/`resumeSession`/`relaunchFresh`/`moveTask → in_progress` (отказ `PROJECT_PAUSED_TEXT`), ИИ-роли — `claudePrint`, уведомления — `deliverToUser`, `notifyPm`, `mirrorTargets`, бот `reconcile`; тики пропускают проект без потери состояния (автономность, перезапуски, напоминания, intake, уточнение, чат с аналитиком, приёмка продукта, ссылка на продукт, перезапуск из-за секретов, ревьюер, «готово к ревью», отложенное «Принять», ошибки из прода — `open` без сообщения), вебхуки (красные проверки, комментарии Gitea) записываются без запуска агента; живой агент проекта на паузе вачдог останавливает сам и дописывает в `sessions`. Веб: `components/ProjectPause.tsx` (кнопка с подтверждением, плашка, метка «На паузе»), «⋯ Настройки проекта → Пауза», «Ждут вашего ответа»/счётчики/дайджест без проектов на паузе. CLI `peppa project pause|resume <KEY>`. Новое место, которое запускает агента, зовёт модель или пишет человеку по проекту, — через эти узкие места или с `isProjectPaused`. Тест `project-pause.test.ts`
- **«Погоня за задачей» на «Команде» (PEP-179)**: `core/team-chase.ts` (`teamChaseView`: работающие агенты — живой раннер, ≤8 + «ещё N», скамейка — свободные не убранные, счётчик `done` видимых проектов, задача видна только из своих проектов; `teamChaseHidden` — `settings` `ui.team-chase:<userId>`), живая область `team` (`LiveRefresh pauseHidden` не держит поток при скрытой вкладке), `components/TeamChase.tsx` + `.module.css` (CSS `offset-path`, «+1» при росте счётчика между обновлениями, «Жмите «Принять»» из `acceptInbox`, на касании первое нажатие — подсказка), шрифт Press Start 2P — свои файлы `public/fonts`, мопс — SVG, `public/sw.js` кэширует шрифты/`_next/static`/`/team`, без сети — снимок в `localStorage` и «Нет связи — данные на ЧЧ:ММ». `listAgents` считает занятость с явным `agents.id` (без квалификатора drizzle путал его с `s.id`). Тест `team-chase.test.ts`
- **Прогресс на Главной (PEP-77)**: `progressOverview` (core/progress.ts: стори по колонкам доски без архивных, стори в работе с агентом и прогрессом tasks.md, ждущие «Принять»; итог — только свои проекты, суперадмину отдельно `others`), раздел «Прогресс» — `components/ProgressOverview.tsx`
- **«Принять» при конфликте (PEP-127)**: PR стори конфликтует с основной веткой → `acceptTask`/`acceptStory` (runner/flow.ts `deferAccept`) не падают, а запоминают решение — `settings` `accept.pending:<taskId>` (`core/accept-pending.ts`: `{at, via, rebases}`), вопрос «готово к ревью» закрывается ответом `PENDING_ACCEPT_ANSWER`, агент получает `requestRebase` (flow.ts; общий с автомержем), результат `pending: true` (бот/MCP/веб отвечают «принято, закроется само»). `pendingAcceptTick` (runner/accept-pending.ts, тик вачдога перед `autonomyTick`): стори в `review` и гейт зелёный → мерж, `done`, событие `accept_completed`, сообщение PM; снова конфликт → ещё rebase (до `ACCEPT_MAX_REBASES` = 3); провал (3 конфликта, PR закрыт, `PEPPA_ACCEPT_WAIT_HOURS` = 24) → состояние стирается, одно `attention` PM; стори ушла в бэклог/архив — стирается молча. Пока ждёт: Stop-хук не шлёт «готово к ревью» (`awaiting_accept_merge`), ревьюер и автомерж стори не трогают. Веб: плашка `PENDING_ACCEPT_LABEL` на странице стори и карточке доски, кнопка «Принять» на вкладке результата активна при конфликте. Красные/идущие проверки по-прежнему отказ с причиной. Тест `accept-pending.test.ts`
- **Мерж только со свежим main внутри (PEP-127)**: `prGate` закрыт с `behind: true`, если ветка открытого PR не содержит голову основной (`pullBehind`: `merge_base` ≠ `base.sha` из ответа Gitea); `reviewGate` агента `behind` пропускает. Обновляет Пеппа — `GiteaClient.updatePullBranch` (`POST /pulls/{n}/update`, merge), раз на head SHA (`updateSha` в `review.hold` / `accept.pending` / `autonomy.merge`), потом ждёт проверок нового коммита: `reviewCardTick`, `pendingAcceptTick`, `autoMergeReviews`. `deferAccept` запоминает «Принять» при конфликте, отставшей ветке и идущих проверках; красные — отказ с причиной

View File

@ -1,6 +1,6 @@
"use server";
import { createAgent, isSuperadmin, PeppaError, updateAgent } from "@peppa/core";
import { createAgent, isSuperadmin, PeppaError, setTeamChaseHidden, updateAgent } from "@peppa/core";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { asWebActor, requireUser } from "@/lib/auth";
@ -44,3 +44,9 @@ export async function toggleAgentAction(f: FormData) {
await updateAgent(db, Number(f.get("id")), { disabled: f.get("disabled") === "1" });
});
}
/** PEP-179: «Скрыть» / «Показать» on the team picture — the user's own choice, anyone may. */
export async function setTeamChaseHiddenAction(hidden: boolean): Promise<void> {
const user = await requireUser();
await setTeamChaseHidden(db, user.id, hidden);
}

View File

@ -1,6 +1,8 @@
import { Plus } from "lucide-react";
import { AGENT_CHARACTER_MAX, isSuperadmin, listAgents } from "@peppa/core";
import { AGENT_CHARACTER_MAX, isSuperadmin, listAgents, teamChaseHidden, teamChaseView } from "@peppa/core";
import { AgentBadge } from "@/components/AgentBadge";
import { LiveRefresh } from "@/components/LiveRefresh";
import { TeamChase } from "@/components/TeamChase";
import { Empty, Flash, Notice, PageHeader, Section } from "@/components/common";
import { Markdown } from "@/components/Markdown";
import { Badge } from "@/components/ui/badge";
@ -10,6 +12,7 @@ import { Input, Label, Textarea } from "@/components/ui/input";
import { Workspace } from "@/components/Workspace";
import { requireUser, words } from "@/lib/auth";
import { db } from "@/lib/db";
import { acceptInbox } from "@/lib/queries";
import { getT } from "@/lib/i18n";
import { addAgentAction, saveAgentAction, toggleAgentAction } from "./actions";
@ -24,9 +27,11 @@ export default async function Team({ searchParams }: { searchParams: Promise<{ e
const t = await getT();
const { error, saved } = await searchParams;
const w = await words();
const [team, admin] = await Promise.all([listAgents(db), isSuperadmin(db, user)]);
const [team, admin, chase, hidden, accept] = await Promise.all([listAgents(db), isSuperadmin(db, user), teamChaseView(db, user), teamChaseHidden(db, user.id), acceptInbox(user.id)]);
const acceptKeys = accept.map((q) => q.taskKey).filter((k): k is string => !!k);
return (
<Workspace>
<LiveRefresh scope="team" pauseHidden />
<div className="max-w-3xl">
<Flash error={error} />
{saved && <Notice>{t("Сохранено — агент получит новый характер при следующем запуске или перезапуске.")}</Notice>}
@ -49,6 +54,8 @@ export default async function Team({ searchParams }: { searchParams: Promise<{ e
</Card>
)}
<TeamChase view={chase} acceptKeys={acceptKeys} hidden={hidden} />
<Section title={t("Агенты")} count={team.length}>
{team.length === 0 && <Empty>{t("Пока никого: первый агент появится, когда {task} уйдёт «В работу».", { task: w.task() })}</Empty>}
{team.map((a) => (

View File

@ -34,7 +34,7 @@ function busy(): boolean {
* 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.
*/
export function LiveRefresh({ scope, pollMs = 5000 }: { scope: string; pollMs?: number }) {
export function LiveRefresh({ scope, pollMs = 5000, pauseHidden = false }: { scope: string; pollMs?: number; pauseHidden?: boolean }) {
const router = useRouter();
const [mode, setMode] = useState<Mode>("connecting");
const pending = useRef(false);
@ -64,7 +64,29 @@ export function LiveRefresh({ scope, pollMs = 5000 }: { scope: string; pollMs?:
pending.current = true;
if (!flushTimer) flushTimer = setTimeout(flush, 300);
};
const onVisible = () => document.visibilityState === "visible" && pending.current && request();
// 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;
@ -102,7 +124,7 @@ export function LiveRefresh({ scope, pollMs = 5000 }: { scope: string; pollMs?:
};
};
connect();
if (!pauseHidden || document.visibilityState === "visible") connect();
document.addEventListener("visibilitychange", onVisible);
return () => {
closed = true;
@ -112,7 +134,7 @@ export function LiveRefresh({ scope, pollMs = 5000 }: { scope: string; pollMs?:
if (flushTimer) clearTimeout(flushTimer);
document.removeEventListener("visibilitychange", onVisible);
};
}, [router, scope, pollMs]);
}, [router, scope, pollMs, pauseHidden]);
return (
<div

View File

@ -0,0 +1,722 @@
/* PEP-179: «Погоня за задачей» — colours, sizes, track and keyframes follow the mockup
(peppa-team-preview.html). The track path comes from the component as --path (it depends on
the measured width); every runner stands at its own --d on the track, so with the animation
off (reduced motion, battery saver) the agents keep their places instead of piling up. */
@font-face {
font-family: "Press Start 2P";
font-style: normal;
font-weight: 400;
font-display: swap;
src: url("/fonts/press-start-2p/cyrillic-ext.woff2") format("woff2");
unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}
@font-face {
font-family: "Press Start 2P";
font-style: normal;
font-weight: 400;
font-display: swap;
src: url("/fonts/press-start-2p/cyrillic.woff2") format("woff2");
unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
@font-face {
font-family: "Press Start 2P";
font-style: normal;
font-weight: 400;
font-display: swap;
src: url("/fonts/press-start-2p/latin-ext.woff2") format("woff2");
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
@font-face {
font-family: "Press Start 2P";
font-style: normal;
font-weight: 400;
font-display: swap;
src: url("/fonts/press-start-2p/latin.woff2") format("woff2");
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
.chase {
container-type: inline-size;
position: relative;
box-sizing: border-box;
margin-bottom: 16px;
padding: 12px max(12px, env(safe-area-inset-right)) 12px max(12px, env(safe-area-inset-left));
background: #05050a;
border-radius: 12px;
font-family: "Press Start 2P", ui-monospace, monospace;
text-transform: uppercase;
color: #fff;
}
.frame {
position: relative;
overflow: hidden;
background: #000;
border: 4px double #00e5ff;
box-shadow: 0 0 18px rgba(0, 229, 255, 0.35), inset 0 0 40px rgba(0, 229, 255, 0.08);
padding: 16px 0 44px;
display: flex;
flex-direction: column;
gap: 10px;
}
.scan {
position: absolute;
inset: 0;
pointer-events: none;
background: repeating-linear-gradient(0deg, rgba(255, 255, 255, 0.035) 0 1px, transparent 1px 3px);
}
.hud {
display: flex;
justify-content: space-between;
align-items: center;
gap: 8px;
padding: 0 16px;
font-size: 10px;
}
.hud b {
color: #ffe600;
font-weight: 400;
}
.title {
font-size: 12px;
color: #ff2e97;
text-shadow: 0 0 12px rgba(255, 46, 151, 0.7);
white-space: nowrap;
}
.offline {
margin: 0 16px;
padding: 6px 8px;
border: 2px solid #ffe600;
color: #ffe600;
font-size: 8px;
line-height: 1.6;
text-align: center;
}
/* ---- stage: pug, chute, track ---- */
.stage {
position: relative;
height: 410px;
}
.track {
position: absolute;
inset: 0;
overflow: visible;
pointer-events: none;
}
.runner,
.task {
position: absolute;
left: 0;
top: 0;
offset-path: var(--path);
offset-rotate: 0deg;
offset-anchor: center;
offset-distance: var(--d, 0%);
animation: ch-run 9s linear infinite;
}
.task {
width: 26px;
height: 26px;
background: #ff2e97;
box-shadow: 0 0 0 3px #000, 0 0 0 5px #ffd6ea, 0 0 20px #ff2e97;
z-index: 3;
--d: 40%;
animation-delay: -3.6s;
pointer-events: none;
}
.task::before,
.task::after {
content: "";
position: absolute;
top: 8px;
width: 4px;
height: 6px;
background: #000;
animation: ch-look 1.2s steps(1, end) infinite;
}
.task::before {
left: 6px;
}
.task::after {
right: 6px;
}
/* Nobody at work: the task lies by the pug, still. */
.restingTask {
position: absolute;
top: 70px;
width: 22px;
height: 22px;
background: #ff2e97;
box-shadow: 0 0 0 3px #000, 0 0 0 5px #ffd6ea;
opacity: 0.8;
}
.runner {
z-index: 2;
offset-anchor: 50% 24px;
padding: 0;
border: 0;
background: none;
color: inherit;
font: inherit;
cursor: pointer;
min-width: 44px;
min-height: 44px;
}
.enter {
animation:
ch-run 9s linear infinite,
ch-in 0.6s ease-out;
}
.hop {
display: flex;
flex-direction: column;
align-items: center;
gap: 6px;
animation: ch-hop 0.36s steps(2, end) infinite;
}
.agent {
box-sizing: border-box;
width: 48px;
height: 48px;
border-radius: 50%;
border: 3px solid currentColor;
background: #000;
display: flex;
align-items: center;
justify-content: center;
font-size: 16px;
box-shadow: 0 0 0 3px #000, 0 0 16px color-mix(in srgb, currentColor 55%, transparent);
}
.tag {
font-size: 8px;
white-space: nowrap;
max-width: 96px;
overflow: hidden;
text-overflow: ellipsis;
}
.tip {
position: absolute;
bottom: calc(100% + 6px);
left: 50%;
transform: translateX(-50%);
padding: 6px 8px;
background: #000;
border: 2px solid currentColor;
font-size: 8px;
line-height: 1.6;
white-space: nowrap;
max-width: min(70cqw, 320px);
overflow: hidden;
text-overflow: ellipsis;
text-transform: none;
opacity: 0;
pointer-events: none;
z-index: 6;
}
.runner:hover .tip,
.runner:focus-visible .tip,
.runner[data-open] .tip,
.seat:hover .tip,
.seat:focus-visible .tip,
.seat[data-open] .tip,
.mini:hover .tip,
.mini:focus-visible .tip,
.mini[data-open] .tip {
opacity: 1;
}
.runner:focus-visible,
.seat:focus-visible,
.mini:focus-visible {
outline: 2px solid #fff;
outline-offset: 2px;
}
.runner:hover,
.runner:focus-visible,
.runner[data-open] {
z-index: 5;
}
.you {
position: absolute;
top: 0;
width: 92px;
margin-left: -46px;
display: flex;
flex-direction: column;
align-items: center;
gap: 8px;
z-index: 4;
}
.youbox {
width: 84px;
height: 76px;
border: 3px solid #fff;
background: #000;
color: #fff;
display: flex;
align-items: center;
justify-content: center;
box-shadow: 0 0 0 4px #000, 0 0 0 6px rgba(255, 255, 255, 0.4), 0 0 22px rgba(255, 255, 255, 0.35);
animation: ch-throw 9s steps(1, end) infinite;
animation-delay: -3.6s;
}
.pug {
animation: ch-jump 9s steps(1, end) infinite;
animation-delay: -3.6s;
}
.idle .youbox,
.idle .pug {
animation: none;
}
.zzz {
position: absolute;
top: -4px;
right: -14px;
font-size: 10px;
color: #8fd3ff;
animation: ch-zzz 2.4s ease-in-out infinite;
}
.youtag {
font-size: 8px;
white-space: nowrap;
}
.chute {
position: absolute;
top: 100px;
width: 0;
height: 50px;
border-left: 3px dashed rgba(255, 46, 151, 0.55);
}
.drop {
position: absolute;
top: 100px;
width: 18px;
height: 18px;
margin-left: -8px;
background: #ff2e97;
box-shadow: 0 0 14px #ff2e97;
opacity: 0;
animation: ch-drop 9s linear infinite;
animation-delay: -3.6s;
}
.say {
position: absolute;
top: 18px;
margin-left: 64px;
padding: 8px 10px;
border: 3px solid #ff2e97;
background: #000;
color: #ff2e97;
font-size: 9px;
white-space: nowrap;
opacity: 0;
animation: ch-say 9s steps(1, end) infinite;
animation-delay: -3.6s;
}
.plus {
position: absolute;
top: 30px;
width: 80px;
margin-left: -130px;
text-align: right;
font-size: 12px;
color: #39ff88;
text-shadow: 0 0 10px #39ff88;
opacity: 0;
animation: ch-plus 1.4s linear forwards;
pointer-events: none;
}
.more {
position: absolute;
font-size: 10px;
color: #c9c9d9;
}
.mid {
position: absolute;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 12px;
text-align: center;
}
.mid p {
margin: 0;
font-size: 9px;
line-height: 1.9;
color: #c9c9d9;
}
.legend {
display: flex;
flex-wrap: wrap;
justify-content: center;
gap: 6px 14px;
font-size: 8px;
}
.accept {
font: inherit;
font-size: 9px;
color: #ff2e97;
text-decoration: none;
padding: 12px 6px;
}
.blink {
animation: ch-blink 1.2s steps(1, end) infinite;
}
/* ---- narrow: a row of working agents instead of the track ---- */
.row {
display: none;
flex-wrap: wrap;
justify-content: center;
gap: 8px;
padding: 0 12px;
}
.mini {
position: relative;
min-width: 44px;
min-height: 44px;
padding: 0;
border: 0;
background: none;
color: inherit;
font: inherit;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
}
.mini .agent {
width: 40px;
height: 40px;
font-size: 13px;
}
/* ---- bench ---- */
.bench {
display: flex;
flex-direction: column;
align-items: center;
gap: 10px;
padding: 0 12px;
}
.bench h3 {
margin: 0;
font-size: 8px;
line-height: 1.8;
font-weight: 400;
color: #9a9ab0;
text-align: center;
}
.seats {
display: flex;
flex-wrap: wrap;
justify-content: center;
gap: 6px;
max-width: 900px;
margin: 0;
padding: 0;
list-style: none;
}
.seat {
position: relative;
width: 44px;
height: 44px;
padding: 0;
border: 0;
background: none;
color: inherit;
font: inherit;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
}
.seatIcon {
box-sizing: border-box;
width: 32px;
height: 32px;
border-radius: 50%;
border: 2px solid currentColor;
background: #000;
display: flex;
align-items: center;
justify-content: center;
font-size: 10px;
opacity: 0.75;
animation: ch-sway 1.8s ease-in-out infinite alternate;
}
.seat:hover .seatIcon,
.seat:focus-visible .seatIcon,
.seat[data-open] .seatIcon {
opacity: 1;
box-shadow: 0 0 12px currentColor;
}
.seatEnter {
animation: ch-in 0.6s ease-out;
}
.hide {
position: absolute;
right: 12px;
bottom: 10px;
min-height: 32px;
background: none;
border: 2px solid #3a3a50;
color: #9a9ab0;
font: inherit;
font-size: 8px;
padding: 6px 8px;
cursor: pointer;
z-index: 7;
}
.hide:hover,
.hide:focus-visible {
color: #fff;
border-color: #9a9ab0;
}
.collapsed {
display: flex;
justify-content: space-between;
align-items: center;
gap: 8px;
padding: 8px 12px;
font-size: 9px;
}
.collapsed .hide {
position: static;
}
@keyframes ch-run {
from {
offset-distance: 0%;
}
to {
offset-distance: 100%;
}
}
@keyframes ch-hop {
0% {
transform: translateY(0);
}
100% {
transform: translateY(-4px);
}
}
@keyframes ch-look {
0% {
transform: translateX(0);
}
50% {
transform: translateX(2px);
}
}
@keyframes ch-throw {
0%,
8% {
transform: translateY(-6px);
border-color: #ff2e97;
color: #ff2e97;
}
9%,
92% {
transform: none;
border-color: #fff;
color: #fff;
}
93%,
100% {
transform: translateY(-6px);
border-color: #ff2e97;
color: #ff2e97;
}
}
@keyframes ch-drop {
0%,
90% {
opacity: 0;
transform: translateY(0);
}
91% {
opacity: 1;
transform: translateY(0);
}
99.5% {
opacity: 1;
transform: translateY(32px);
}
100% {
opacity: 0;
transform: translateY(32px);
}
}
@keyframes ch-say {
0%,
10% {
opacity: 1;
}
11%,
88% {
opacity: 0;
}
89%,
100% {
opacity: 1;
}
}
@keyframes ch-plus {
0% {
opacity: 1;
transform: translateY(0);
}
100% {
opacity: 0;
transform: translateY(-22px);
}
}
@keyframes ch-jump {
0%,
6% {
transform: translateY(-8px);
}
7%,
93% {
transform: none;
}
94%,
100% {
transform: translateY(-8px);
}
}
@keyframes ch-blink {
0%,
49% {
opacity: 1;
}
50%,
100% {
opacity: 0;
}
}
@keyframes ch-sway {
from {
transform: translateY(0) rotate(-4deg);
}
to {
transform: translateY(-3px) rotate(4deg);
}
}
@keyframes ch-zzz {
0%,
100% {
opacity: 0.3;
transform: translateY(0);
}
50% {
opacity: 1;
transform: translateY(-4px);
}
}
@keyframes ch-in {
from {
opacity: 0;
scale: 0.4;
}
to {
opacity: 1;
scale: 1;
}
}
/* Paused (hidden tab), battery saver and reduced motion: nothing moves. */
.paused *,
.paused *::before,
.paused *::after {
animation-play-state: paused !important;
}
.still *,
.still *::before,
.still *::after {
animation: none !important;
}
.still .drop,
.still .say,
.still .plus {
display: none;
}
@media (prefers-reduced-motion: reduce) {
.chase *,
.chase *::before,
.chase *::after {
animation: none !important;
}
.drop,
.say,
.plus {
display: none;
}
}
/* Under 720 px: smaller runners, no speech bubble. */
@container (max-width: 719px) {
.agent {
width: 40px;
height: 40px;
font-size: 13px;
}
.runner {
offset-anchor: 50% 20px;
}
.say {
display: none;
}
.title {
font-size: 10px;
}
.hud {
font-size: 8px;
}
}
@container (max-width: 519px) {
.player {
display: none;
}
}
/* Under 420 px: a row of icons instead of the track. */
@container (max-width: 419px) {
.stage {
height: auto;
display: flex;
flex-direction: column;
align-items: center;
gap: 12px;
}
.track,
.runner,
.task,
.chute,
.drop,
.say,
.more,
.restingTask {
display: none;
}
.you {
position: relative;
left: auto !important;
margin-left: 0;
}
.plus {
left: 50% !important;
}
.mid {
position: static;
padding: 0 12px;
}
.row {
display: flex;
}
}

View File

@ -0,0 +1,249 @@
"use client";
// PEP-179: «Погоня за задачей» — the picture above the team list. Working agents chase the task
// round the track (CSS offset-path), free ones wait on the bench, a pug product owner throws the
// task. Data comes from the server (`teamChaseView`) and is re-read by <LiveRefresh scope="team">.
import { useRouter } from "next/navigation";
import { useEffect, useRef, useState, useTransition } from "react";
import { useT } from "@/components/I18n";
import type { TeamChaseView } from "@peppa/core";
import { setTeamChaseHiddenAction } from "@/app/(app)/team/actions";
import css from "./TeamChase.module.css";
const SNAPSHOT_KEY = "peppa.team-chase.snapshot";
const initial = (name: string) => [...name][0]?.toUpperCase() ?? "?";
/** A rounded rectangle through the stage as an offset-path (the stage width is measured). */
export function trackPath(w: number, top = 176, bottom = 372, r = 40): string {
const l = 28;
const rt = Math.max(l + 2 * r, w - 28);
return `path("M ${l + r} ${top} H ${rt - r} Q ${rt} ${top} ${rt} ${top + r} V ${bottom - r} Q ${rt} ${bottom} ${rt - r} ${bottom} H ${l + r} Q ${l} ${bottom} ${l} ${bottom - r} V ${top + r} Q ${l} ${top} ${l + r} ${top} Z")`;
}
/** Pixel pug (inline SVG: nothing to download, works offline). */
function Pug({ sleeping }: { sleeping: boolean }) {
const px = (x: number, y: number, w: number, h: number, f: string) => <rect key={`${x}-${y}-${f}`} x={x} y={y} width={w} height={h} fill={f} />;
return (
<svg width="48" height="40" viewBox="0 0 12 10" shapeRendering="crispEdges" aria-hidden className={css.pug}>
{px(1, 0, 3, 3, "#6b4a2b")}
{px(8, 0, 3, 3, "#6b4a2b")}
{px(2, 2, 8, 7, "#e8c48a")}
{px(3, 4, 6, 4, "#3a2a1a")}
{sleeping ? <>{px(3, 3, 2, 1, "#000")}{px(7, 3, 2, 1, "#000")}</> : <>{px(3, 3, 2, 2, "#fff")}{px(7, 3, 2, 2, "#fff")}{px(4, 4, 1, 1, "#000")}{px(8, 4, 1, 1, "#000")}</>}
{px(5, 6, 2, 1, "#000")}
</svg>
);
}
export function TeamChase({ view, acceptKeys, hidden: hiddenInitial }: { view: TeamChaseView; acceptKeys: string[]; hidden: boolean }) {
const t = useT();
const router = useRouter();
const [hidden, setHidden] = useState(hiddenInitial);
const [, start] = useTransition();
const stage = useRef<HTMLDivElement>(null);
const [width, setWidth] = useState(720);
const [visible, setVisible] = useState(true);
const [still, setStill] = useState(false);
const [online, setOnline] = useState(true);
const [data, setData] = useState(view);
const [plus, setPlus] = useState(0);
const [open, setOpen] = useState<string | null>(null);
const prevAccepted = useRef<number | null>(null);
const known = useRef(new Set<string>());
const [fresh, setFresh] = useState<Set<string>>(new Set());
// Fresh server data → the shown state; remember it for offline starts.
useEffect(() => {
setData(view);
try {
localStorage.setItem(SNAPSHOT_KEY, JSON.stringify(view));
} catch {}
if (prevAccepted.current != null && view.accepted > prevAccepted.current) setPlus((n) => n + 1);
prevAccepted.current = view.accepted;
const names = [...view.runners, ...view.bench].map((a) => `${a.id}`);
if (known.current.size) setFresh(new Set(names.filter((n) => !known.current.has(n))));
known.current = new Set(names);
}, [view]);
// Offline start: the page came from cache (or failed) — show the last snapshot we kept.
useEffect(() => {
const sync = () => setOnline(navigator.onLine);
sync();
window.addEventListener("online", sync);
window.addEventListener("offline", sync);
if (!navigator.onLine) {
try {
const raw = localStorage.getItem(SNAPSHOT_KEY);
if (raw) {
const snap = JSON.parse(raw) as TeamChaseView;
if (snap.at > view.at) setData(snap);
}
} catch {}
}
return () => {
window.removeEventListener("online", sync);
window.removeEventListener("offline", sync);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useEffect(() => {
const el = stage.current;
if (!el) return;
const ro = new ResizeObserver(() => setWidth(el.clientWidth));
ro.observe(el);
setWidth(el.clientWidth);
return () => ro.disconnect();
}, [hidden]);
// Hidden tab → animations pause; battery saver → they stop (agents keep their places).
useEffect(() => {
const vis = () => setVisible(document.visibilityState === "visible");
document.addEventListener("visibilitychange", vis);
let off = () => {};
type Battery = EventTarget & { level: number; charging: boolean };
(navigator as Navigator & { getBattery?: () => Promise<Battery> }).getBattery?.().then((b) => {
const upd = () => setStill(!b.charging && b.level <= 0.2);
upd();
b.addEventListener("levelchange", upd);
b.addEventListener("chargingchange", upd);
off = () => {
b.removeEventListener("levelchange", upd);
b.removeEventListener("chargingchange", upd);
};
}).catch(() => {});
if ("serviceWorker" in navigator) navigator.serviceWorker.register("/sw.js").catch(() => {});
return () => {
document.removeEventListener("visibilitychange", vis);
off();
};
}, []);
useEffect(() => {
if (!plus) return;
const id = setTimeout(() => setPlus(0), 1500);
return () => clearTimeout(id);
}, [plus]);
const toggle = (h: boolean) => {
setHidden(h);
start(() => void setTeamChaseHiddenAction(h));
};
const at = new Date(data.at).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
const n = data.runners.length;
const idle = n === 0;
const path = trackPath(width);
const awaiting = acceptKeys.length;
const mid = width / 2;
const go = (e: React.MouseEvent | React.KeyboardEvent, id: string, action: () => void) => {
// Touch: the first tap shows the hint, the second goes. A mouse goes at once.
const touch = "pointerType" in e.nativeEvent && (e.nativeEvent as PointerEvent).pointerType === "touch";
if (touch && open !== id) return setOpen(id);
setOpen(null);
action();
};
const toCard = (id: number) => {
const el = document.getElementById(`agent-${id}`);
if (!el) return;
el.scrollIntoView({ behavior: still ? "auto" : "smooth", block: "center" });
el.animate([{ outline: "2px solid #00e5ff" }, { outline: "2px solid transparent" }], { duration: 1600 });
};
if (hidden)
return (
<div className={`${css.chase} ${css.collapsed}`}>
<span>{t("Погоня за задачей")}</span>
<button type="button" className={css.hide} onClick={() => toggle(false)}>{t("Показать")}</button>
</div>
);
return (
<section className={`${css.chase} ${!visible ? css.paused : ""} ${still ? css.still : ""}`} aria-label={t("Погоня за задачей")} onClick={(e) => e.target === e.currentTarget && setOpen(null)}>
<div className={css.frame}>
<div className={css.scan} aria-hidden />
<div className={css.hud}>
<span className={css.title}>{t("Погоня за задачей")}</span>
<span aria-live="polite">{t("Принято")}: <b>{data.accepted}</b></span>
</div>
{!online && <div className={css.offline} role="status">{t("Нет связи — данные на {time}", { time: at })}</div>}
<div ref={stage} className={`${css.stage} ${idle ? css.idle : ""}`} style={{ ["--path" as string]: path }}>
<div className={css.you} style={{ left: mid }}>
<div className={css.youbox}>
<Pug sleeping={idle} />
{idle && <span className={css.zzz} aria-hidden>z z</span>}
</div>
<span className={css.youtag}>{t("мопс-продакт")}</span>
{plus > 0 && <span key={plus} className={css.plus} aria-hidden>+1</span>}
</div>
{!idle && <><div className={css.chute} style={{ left: mid }} aria-hidden /><div className={css.drop} style={{ left: mid }} aria-hidden /></>}
{!idle && <div className={css.say} style={{ left: mid }} aria-hidden>{t("Новая задача!")}</div>}
{idle ? (
<div className={css.mid} style={{ left: 0, right: 0, top: 200 }}>
<div className={css.restingTask} aria-hidden />
<p>{t("Агенты отдыхают")}</p>
</div>
) : (
<>
<div className={css.track} aria-hidden />
<div className={css.task} aria-hidden />
{data.runners.map((a, i) => {
const label = a.task ? t("агент {name} · {title}", { name: a.name, title: a.task.title }) : t("агент {name} работает", { name: a.name });
const key = `r${a.id}`;
return (
<button
key={a.id}
type="button"
className={`${css.runner} ${fresh.has(`${a.id}`) ? css.enter : ""}`}
style={{ ["--d" as string]: `${Math.round((i / n) * 100)}%`, color: a.color, animationDelay: `${-(i / n) * 9}s` }}
data-open={open === key ? "" : undefined}
aria-label={label}
onClick={(e) => go(e, key, () => (a.task ? router.push(`/t/${a.task.key}`) : toCard(a.id)))}
>
<span className={css.hop}>
<span className={css.agent}>{initial(a.name)}</span>
<span className={css.tag}>{a.name}</span>
</span>
<span className={css.tip}>{label}</span>
</button>
);
})}
{data.extra > 0 && <span className={css.more} style={{ right: 36, top: 150 }}>{t("ещё {n}", { n: data.extra })}</span>}
</>
)}
<div className={css.row}>
{data.runners.map((a) => (
<button key={a.id} type="button" className={css.mini} style={{ color: a.color }} aria-label={a.task ? t("агент {name} · {title}", { name: a.name, title: a.task.title }) : a.name} onClick={(e) => go(e, `m${a.id}`, () => (a.task ? router.push(`/t/${a.task.key}`) : toCard(a.id)))} data-open={open === `m${a.id}` ? "" : undefined}>
<span className={css.agent}>{initial(a.name)}</span>
</button>
))}
</div>
</div>
{awaiting > 0 && (
<a className={`${css.accept} ${css.blink}`} style={{ textAlign: "center" }} href={`/t/${acceptKeys[0]}`}>{t("Жмите «Принять»")}</a>
)}
<div className={css.bench}>
<h3>{data.bench.length ? t("Свободны — ждут задачу") : t("Все заняты")}</h3>
<ul className={css.seats}>
{data.bench.map((a) => (
<li key={a.id}>
<button type="button" className={css.seat} style={{ color: a.color }} aria-label={t("агент {name} свободен", { name: a.name })} data-open={open === `s${a.id}` ? "" : undefined} onClick={(e) => go(e, `s${a.id}`, () => toCard(a.id))}>
<span className={`${css.seatIcon} ${fresh.has(`${a.id}`) ? css.seatEnter : ""}`}>{initial(a.name)}</span>
<span className={css.tip}>{t("агент {name} свободен", { name: a.name })}</span>
</button>
</li>
))}
</ul>
</div>
<button type="button" className={css.hide} onClick={() => toggle(true)}>{t("Скрыть")}</button>
</div>
</section>
);
}

View File

@ -0,0 +1,93 @@
Copyright 2012 The Press Start 2P Project Authors (cody@zone38.net), with Reserved Font Name "Press Start 2P"
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -1,7 +1,54 @@
// Peppa service worker (PEP-55): shows Web Push notifications and opens the right page
// on click. Payload (core/webpush.ts PushPayload): { title, body, url, tag?, sound?, count? }.
self.addEventListener("install", () => self.skipWaiting());
self.addEventListener("activate", (event) => event.waitUntil(self.clients.claim()));
// PEP-179: the app shell works without a network — fonts, built assets and the icon come from
// the cache first, the /team page from the network first (the cached copy only when offline).
const CACHE = "peppa-shell-v1";
const SHELL = ["/icon.svg", "/fonts/press-start-2p/cyrillic.woff2", "/fonts/press-start-2p/cyrillic-ext.woff2", "/fonts/press-start-2p/latin.woff2", "/fonts/press-start-2p/latin-ext.woff2"];
self.addEventListener("install", (event) => {
event.waitUntil(caches.open(CACHE).then((c) => c.addAll(SHELL)).catch(() => {}));
self.skipWaiting();
});
self.addEventListener("activate", (event) =>
event.waitUntil(
(async () => {
// A new version drops the caches of the old one.
for (const k of await caches.keys()) if (k !== CACHE) await caches.delete(k);
await self.clients.claim();
})(),
),
);
self.addEventListener("fetch", (event) => {
const req = event.request;
if (req.method !== "GET") return;
const url = new URL(req.url);
if (url.origin !== self.location.origin) return;
const cacheFirst = url.pathname.startsWith("/fonts/") || url.pathname.startsWith("/_next/static/") || url.pathname === "/icon.svg";
const teamPage = url.pathname === "/team" && req.mode === "navigate";
if (!cacheFirst && !teamPage) return;
event.respondWith(
(async () => {
const cache = await caches.open(CACHE);
if (cacheFirst) {
const hit = await cache.match(req);
if (hit) return hit;
const res = await fetch(req);
if (res.ok) cache.put(req, res.clone()).catch(() => {});
return res;
}
try {
const res = await fetch(req);
if (res.ok && !res.redirected) cache.put(req, res.clone()).catch(() => {});
return res;
} catch (e) {
const hit = await cache.match(req);
if (hit) return hit;
throw e;
}
})(),
);
});
self.addEventListener("push", (event) => {
let p = {};

View File

@ -0,0 +1,31 @@
# PEP-179: «Погоня за задачей» на странице «Команда»
## Зачем
Раздел «Команда» — длинный список одинаковых карточек «ИИ-агент … свободен»: не видно, что
команда живая и кто чем занят. Нужна картинка над списком: мопс-продакт бросает задачу,
работающие агенты гоняют её по кругу, свободные ждут на скамейке.
## Что меняется
- `core/team-chase.ts` — `teamChaseView(db, user)`: на трассе агенты с живыми раннерами
(те же данные, что `listAgents`, не больше 8, остальные — «+N»), задача раннера (ключ и
название — только из видимых пользователю проектов), скамейка — свободные агенты в команде,
счётчик — задачи в «Готово» видимых проектов (суперадмину — всех, без удалённых), цвет агента
`agentColor` (тот же тон, что у `AgentBadge`). Скрыть картинку — `settings`
`ui.team-chase:<userId>`.
- Веб: `components/TeamChase.tsx` (+ `TeamChase.module.css`) над списком агентов на `/team`:
CSS-анимация (`offset-path` по трассе, ключевые кадры макета), «+1» только при росте счётчика
между обновлениями, «Жмите «Принять»» — только при задачах на приёмке (`acceptInbox`),
подсказки, клик по бегущему — страница задачи, по агенту на скамейке — прокрутка к карточке
и подсветка; касание: первое — подсказка, второе — переход; «Скрыть»/«Показать».
Уменьшенное движение и экономия батареи — всё стоит, агенты расставлены по трассе; скрытая
вкладка — пауза анимации и канала. Узко (< 420 px) — строка значков вместо трассы.
- Живая область `team` в `/api/live` (как `home` + состав команды); `LiveRefresh pauseHidden`
закрывает поток, пока вкладка скрыта, и сразу обновляет при возврате.
- PWA: шрифт Press Start 2P — свои файлы `public/fonts/press-start-2p/*` (OFL), пиксельный мопс —
встроенный SVG; `public/sw.js` кэширует шрифты, `/_next/static` и `/icon.svg` (сначала кэш),
страницу `/team` (сначала сеть, без сети — кэш); старые кэши удаляются при активации новой
версии. Компонент регистрирует service worker. Без сети — последний состав (страница из кэша
или снимок в `localStorage`) и строка «Нет связи — данные на ЧЧ:ММ».
## Не входит
Звук, игра, анимация в Telegram и на Главной, изменения карточек агентов.

View File

@ -0,0 +1,33 @@
## ADDED Requirements
### Requirement: Картинка «Погоня за задачей» над списком агентов
Страница «Команда» SHALL показывать над списком агентов анимацию: на трассе — агенты, у которых
сейчас есть живой раннер (не больше 8, остальные — подпись «+N»), на скамейке — свободные агенты
команды (убранные из команды не показываются); вместе они совпадают со списком ниже. Счётчик —
число задач в «Готово» в проектах, которые видит пользователь. «+1» появляется только когда счётчик
вырос между обновлениями. «Жмите «Принять»» видно, только если есть задачи на приёмке; клик ведёт
к первой. Состав обновляется по живому каналу (область `team`) без перезагрузки.
#### Scenario: Агент взял задачу
- **GIVEN** открыта «Команда», агент Барыс на скамейке
- **WHEN** Барыс начинает работу над задачей
- **THEN** без перезагрузки он переходит на трассу, подсказка — его кличка и название задачи, клик открывает задачу
#### Scenario: Никто не работает
- **WHEN** живых раннеров нет
- **THEN** трасса пустая, мопс спит, написано «Агенты отдыхают»
#### Scenario: Уменьшенное движение
- **GIVEN** в системе включено «уменьшить движение»
- **THEN** ничего не двигается, агенты стоят на трассе на своих местах
### Requirement: Работа как приложение и без сети
Шрифт и мопс картинки SHALL быть своими файлами платформы. Service worker кэширует их и страницу
«Команда»; без сети она открывается с последним составом и строкой «Нет связи — данные на ЧЧ:ММ».
Пока вкладка или приложение скрыты, анимация и подписка на обновления стоят; после возврата состав
обновляется сразу. Новая версия service worker удаляет кэши старой.
#### Scenario: Без сети
- **GIVEN** пользователь открывал «Команду» раньше
- **WHEN** он открывает её без сети
- **THEN** видит последний состав, строку «Нет связи — данные на ЧЧ:ММ», шрифт и мопса

View File

@ -0,0 +1,14 @@
## 1. Данные
- [x] 1.1 `teamChaseView` и `agentColor` в core, настройка «скрыть»
- [x] 1.2 Живая область `team`, `LiveRefresh pauseHidden`
## 2. Веб
- [x] 2.1 `TeamChase` + стили: трасса, скамейка, мопс, счётчик, «+1», «Жмите «Принять»»
- [x] 2.2 Подсказки, касания, клавиатура, прокрутка к карточке
- [x] 2.3 Уменьшенное движение, батарея, пауза скрытой вкладки, узкие экраны, safe-area
- [x] 2.4 Свой шрифт, service worker: кэш оболочки и `/team`, снимок без сети
## 3. Проверка
- [x] 3.1 Переводы ru/kk/en, словарь
- [x] 3.2 Тест `team-chase.test.ts`
- [x] 3.3 Проверка в браузере (ширина 375/720, уменьшенное движение)

View File

@ -0,0 +1,38 @@
# team-page Specification
## Purpose
TBD - created by archiving change pep-179-team-chase. Update Purpose after archive.
## Requirements
### Requirement: Картинка «Погоня за задачей» над списком агентов
Страница «Команда» SHALL показывать над списком агентов анимацию: на трассе — агенты, у которых
сейчас есть живой раннер (не больше 8, остальные — подпись «+N»), на скамейке — свободные агенты
команды (убранные из команды не показываются); вместе они совпадают со списком ниже. Счётчик —
число задач в «Готово» в проектах, которые видит пользователь. «+1» появляется только когда счётчик
вырос между обновлениями. «Жмите «Принять»» видно, только если есть задачи на приёмке; клик ведёт
к первой. Состав обновляется по живому каналу (область `team`) без перезагрузки.
#### Scenario: Агент взял задачу
- **GIVEN** открыта «Команда», агент Барыс на скамейке
- **WHEN** Барыс начинает работу над задачей
- **THEN** без перезагрузки он переходит на трассу, подсказка — его кличка и название задачи, клик открывает задачу
#### Scenario: Никто не работает
- **WHEN** живых раннеров нет
- **THEN** трасса пустая, мопс спит, написано «Агенты отдыхают»
#### Scenario: Уменьшенное движение
- **GIVEN** в системе включено «уменьшить движение»
- **THEN** ничего не двигается, агенты стоят на трассе на своих местах
### Requirement: Работа как приложение и без сети
Шрифт и мопс картинки SHALL быть своими файлами платформы. Service worker кэширует их и страницу
«Команда»; без сети она открывается с последним составом и строкой «Нет связи — данные на ЧЧ:ММ».
Пока вкладка или приложение скрыты, анимация и подписка на обновления стоят; после возврата состав
обновляется сразу. Новая версия service worker удаляет кэши старой.
#### Scenario: Без сети
- **GIVEN** пользователь открывал «Команду» раньше
- **WHEN** он открывает её без сети
- **THEN** видит последний состав, строку «Нет связи — данные на ЧЧ:ММ», шрифт и мопса

View File

@ -29,6 +29,7 @@ export * from "./ci.ts";
export * from "./egov.ts";
export * from "./google.ts";
export * from "./team.ts";
export * from "./team-chase.ts";
export * from "./progress.ts";
export * from "./platform-dashboard.ts";
export * from "./intake.ts";

View File

@ -0,0 +1,92 @@
// PEP-179: the «Погоня за задачей» picture above the team list — who of the team is at work
// right now (on the track, with their story), who is free (on the bench) and how many stories
// the team has brought to «Готово» in the projects the viewer sees. Same live-runner rule as
// `listAgents` (a session not done/failed), so the picture and the cards below always agree.
import { agents, projects, sessions, tasks, type Db } from "@peppa/db";
import type { User } from "./users.ts";
import { formatTaskKey } from "@peppa/shared";
import { and, asc, desc, eq, inArray, isNull, notInArray, sql } from "drizzle-orm";
import { isSuperadmin } from "./monitor.ts";
import { getSetting, setSetting } from "./settings.ts";
import { userProjectIds } from "./users.ts";
/** At most this many agents run on the track; the rest is «+N». */
export const CHASE_TRACK_MAX = 8;
/** The agent's colour — the same tone index as the web `AgentBadge` (sum of code points). */
const AGENT_COLORS = ["#7dd3fc", "#6ee7b7", "#fcd34d", "#f0abfc", "#fda4af", "#c4b5fd", "#5eead4", "#fdba74"];
export const agentColor = (name: string) => AGENT_COLORS[[...name].reduce((a, c) => a + c.codePointAt(0)!, 0) % AGENT_COLORS.length];
export interface ChaseAgent {
id: number;
name: string;
color: string;
/** The story of its live runner — only when the viewer can open that project. */
task: { key: string; title: string } | null;
}
export interface TeamChaseView {
/** On the track, oldest agent first (≤ CHASE_TRACK_MAX). */
runners: ChaseAgent[];
/** Working agents that did not fit on the track. */
extra: number;
/** Free agents of the team (removed ones are not on the bench). */
bench: ChaseAgent[];
/** Stories in «Готово» in the projects the viewer sees (a superadmin — all of them). */
accepted: number;
/** When the data was read (ISO) — «Нет связи — данные на ЧЧ:ММ». */
at: string;
}
export async function teamChaseView(db: Db, user: Pick<User, "id" | "login">, now = new Date()): Promise<TeamChaseView> {
const admin = await isSuperadmin(db, user);
const visible = admin ? null : new Set(await userProjectIds(db, user.id));
const live = notInArray(sessions.status, ["done", "failed"]);
const team = await db.select({ id: agents.id, name: agents.name, disabledAt: agents.disabledAt }).from(agents).orderBy(asc(agents.id));
const runs = await db
.select({ agentId: sessions.agentId, projectId: tasks.projectId, number: tasks.number, title: tasks.title, key: projects.key })
.from(sessions)
.leftJoin(tasks, eq(tasks.id, sessions.taskId))
.leftJoin(projects, eq(projects.id, tasks.projectId))
.where(and(live, sql`${sessions.agentId} is not null`))
.orderBy(desc(sessions.id));
// The newest live runner of each agent tells which story it chases.
const current = new Map<number, (typeof runs)[number]>();
for (const r of runs) if (r.agentId != null && !current.has(r.agentId)) current.set(r.agentId, r);
const working: ChaseAgent[] = [];
const bench: ChaseAgent[] = [];
for (const a of team) {
const run = current.get(a.id);
const base = { id: a.id, name: a.name, color: agentColor(a.name) };
if (run) {
const seen = run.key != null && run.number != null && run.projectId != null && (visible == null || visible.has(run.projectId));
working.push({ ...base, task: seen ? { key: formatTaskKey(run.key!, run.number!), title: run.title ?? "" } : null });
} else if (!a.disabledAt) bench.push({ ...base, task: null });
}
const ids = visible == null ? null : [...visible];
let accepted = 0;
if (ids == null || ids.length) {
const [row] = await db
.select({ n: sql<number>`count(*)` })
.from(tasks)
.innerJoin(projects, eq(projects.id, tasks.projectId))
.where(and(eq(tasks.status, "done"), isNull(projects.deletedAt), ids == null ? undefined : inArray(tasks.projectId, ids)));
accepted = Number(row?.n ?? 0);
}
return { runners: working.slice(0, CHASE_TRACK_MAX), extra: Math.max(0, working.length - CHASE_TRACK_MAX), bench, accepted, at: now.toISOString() };
}
const hiddenKey = (userId: number) => `ui.team-chase:${userId}`;
/** «Скрыть» on the picture — remembered for the user. */
export async function teamChaseHidden(db: Db, userId: number): Promise<boolean> {
return (await getSetting<string>(db, hiddenKey(userId))) === "hidden";
}
export async function setTeamChaseHidden(db: Db, userId: number, hidden: boolean): Promise<void> {
await setSetting(db, hiddenKey(userId), hidden ? "hidden" : "shown");
}

View File

@ -32,8 +32,8 @@ export async function listAgents(db: Db): Promise<AgentView[]> {
const rows = await db
.select({
a: agents,
busy: sql<number>`(select count(*) from sessions s where s.agent_id = ${agents.id} and s.status not in ('done', 'failed'))`,
runs: sql<number>`(select count(*) from sessions s where s.agent_id = ${agents.id})`,
busy: sql<number>`(select count(*) from sessions s where s.agent_id = agents.id and s.status not in ('done', 'failed'))`,
runs: sql<number>`(select count(*) from sessions s where s.agent_id = agents.id)`,
})
.from(agents)
.orderBy(asc(agents.id));
@ -122,7 +122,7 @@ export async function ensureSessionAgent(db: Db, sessionId: number): Promise<Age
.from(agents)
.where(and(isNull(agents.disabledAt), busy.length ? notInArray(agents.id, busy) : undefined))
// The one that rested longest goes first, so the team rotates.
.orderBy(sql`(select coalesce(max(s.id), 0) from sessions s where s.agent_id = ${agents.id})`, asc(agents.id))
.orderBy(sql`(select coalesce(max(s.id), 0) from sessions s where s.agent_id = agents.id)`, asc(agents.id))
.limit(1)
.get();
}

View File

@ -10,7 +10,7 @@ import { findChangeDir, listenEvents, projectForUser, STEP_EVENT, stepView, type
import { events, sessions, tasks, type Db } from "@peppa/db";
import { and, eq, gt } from "drizzle-orm";
export type LiveScope = "home" | "runners" | "chats" | `project:${number}` | `task:${number}` | `steps:${number}`;
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 };
type Listener = (e: LiveEvent) => void;
@ -30,7 +30,7 @@ const WAKE_DEBOUNCE_MS = 250;
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") out.add(part);
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);
}
@ -113,14 +113,22 @@ function fingerprint(db: Db, scope: LiveScope): string {
.get() as Record<string, unknown>;
return Object.values(row).join("|");
}
// home / runners: across projects (only wakes the page — data stays behind access checks).
// 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
// agent a live runner has.
const row = c
.prepare(
`SELECT
(SELECT coalesce(max(updated_at),0) || ':' || count(*) FROM tasks) AS t,
(SELECT count(*) || ':' || count(answered_at) FROM questions) AS q,
(SELECT count(*) || ':' || coalesce(${ACTIVE_SESSIONS},'') FROM sessions) AS s,
(SELECT count(*) FROM projects) AS p`,
(SELECT count(*) FROM projects) AS p${
kind === "team"
? `,
(SELECT coalesce(group_concat(id || ':' || name || ':' || coalesce(disabled_at,'')),'') FROM agents) AS a,
(SELECT coalesce(group_concat(id || ':' || coalesce(agent_id,'')),'') FROM sessions WHERE ended_at IS NULL) AS sa`
: ""
}`,
)
.get() as Record<string, unknown>;
return Object.values(row).join("|");

View File

@ -16,5 +16,6 @@ import { merge_c } from "./merge-c.ts";
import { merge_d } from "./merge-d.ts";
import { feedback } from "./feedback.ts";
import { attachments } from "./attachments.ts";
import { teamChase } from "./team-chase.ts";
export const en: Dict = { ...common, ...story, ...project, ...admin, ...settings, ...help, ...runner, ...bot, ...merge, ...merge_a, ...merge_b, ...merge_c, ...merge_d, ...feedback, ...attachments };
export const en: Dict = { ...common, ...story, ...project, ...admin, ...settings, ...help, ...runner, ...bot, ...merge, ...merge_a, ...merge_b, ...merge_c, ...merge_d, ...feedback, ...attachments, ...teamChase };

View File

@ -0,0 +1,20 @@
import type { Dict } from "../index.ts";
// PEP-179: «Погоня за задачей» on the team page.
export const teamChase: Dict = {
"Погоня за задачей": "Chase the task",
"Показать": "Show",
"Скрыть": "Hide",
"Принято": "Accepted",
"мопс-продакт": "pug product owner",
"Новая задача!": "New task!",
"Агенты отдыхают": "The agents are resting",
"Жмите «Принять»": "Press “Accept”",
"Нет связи — данные на {time}": "No connection — data as of {time}",
"агент {name} · {title}": "agent {name} · {title}",
"агент {name} работает": "agent {name} is working",
"агент {name} свободен": "agent {name} is free",
"ещё {n}": "{n} more",
"Свободны — ждут задачу": "Free — waiting for a task",
"Все заняты": "Everyone is busy",
};

View File

@ -16,5 +16,6 @@ import { settings } from "./settings.ts";
import { story } from "./story.ts";
import { feedback } from "./feedback.ts";
import { attachments } from "./attachments.ts";
import { teamChase } from "./team-chase.ts";
export const kk: Dict = { ...admin, ...bot, ...common, ...help, ...mergeA, ...mergeB, ...mergeC, ...mergeD, ...merge, ...project, ...runner, ...settings, ...story, ...feedback, ...attachments };
export const kk: Dict = { ...admin, ...bot, ...common, ...help, ...mergeA, ...mergeB, ...mergeC, ...mergeD, ...merge, ...project, ...runner, ...settings, ...story, ...feedback, ...attachments, ...teamChase };

View File

@ -0,0 +1,20 @@
import type { Dict } from "../index.ts";
/** Kazakh (PEP-99) for en/team-chase.ts — keys are the Russian strings. */
export const teamChase: Dict = {
"Погоня за задачей": "Тапсырма қуу",
"Показать": "Көрсету",
"Скрыть": "Жасыру",
"Принято": "Қабылданды",
"мопс-продакт": "мопс-продакт",
"Новая задача!": "Жаңа тапсырма!",
"Агенты отдыхают": "Агенттер демалып жатыр",
"Жмите «Принять»": "«Қабылдау» батырмасын басыңыз",
"Нет связи — данные на {time}": "Байланыс жоқ — деректер {time} бойынша",
"агент {name} · {title}": "{name} агенті · {title}",
"агент {name} работает": "{name} агенті жұмыс істеп жатыр",
"агент {name} свободен": "{name} агенті бос",
"ещё {n}": "тағы {n}",
"Свободны — ждут задачу": "Бос — тапсырма күтіп тұр",
"Все заняты": "Бәрі бос емес",
};

View File

@ -0,0 +1,53 @@
// PEP-179: the data behind «Погоня за задачей» — runners on the track, the bench, the counter.
import assert from "node:assert/strict";
import { after, describe, test } from "node:test";
import { core, db, project, runner, setDefaultOwner, teardown } from "./helpers.ts";
process.env.PEPPA_SECRET = "mock-secret-for-tests";
after(teardown);
describe("Погоня за задачей", () => {
test("Scenario: работающий агент — на трассе с задачей, свободный — на скамейке, как в списке команды", async () => {
const owner = await core.upsertUserFromGitea(db, { id: 7901, login: "chase-owner" }, { access_token: "x" });
setDefaultOwner(owner.id);
const p = await project({ turns: [[{ say: "ok" }]] });
const sid = await p.start();
await core.createAgent(db, { name: "Свободный" });
const v = await core.teamChaseView(db, owner);
const list = await core.listAgents(db);
assert.equal(v.runners.length, list.filter((a) => a.busy > 0).length);
assert.equal(v.runners.length, 1);
assert.equal(v.runners[0]!.task?.key, p.taskKey);
assert.deepEqual(v.bench.map((a) => a.name), ["Свободный"]);
assert.equal(v.accepted, 0);
await runner.stopSession(db, sid);
});
test("Scenario: чужая задача не показывается, счётчик — только видимые проекты", async () => {
const owner = await core.upsertUserFromGitea(db, { id: 7902, login: "chase-other-owner" }, { access_token: "x" });
const stranger = await core.upsertUserFromGitea(db, { id: 7903, login: "chase-stranger" }, { access_token: "x" });
setDefaultOwner(owner.id);
const p = await project({ turns: [[{ say: "ok" }]] });
const sid = await p.start();
const seen = await core.teamChaseView(db, stranger);
assert.ok(seen.runners.length >= 1 && seen.runners.every((a) => a.task?.key !== p.taskKey), "the agent runs, the story stays hidden");
const own = await core.teamChaseView(db, owner);
assert.equal(own.runners.find((a) => a.task)?.task?.key, p.taskKey);
await runner.stopSession(db, sid);
});
test("Scenario: убранный из команды агент на скамейке не показывается; скрытие помнится", async () => {
const user = await core.upsertUserFromGitea(db, { id: 7904, login: "chase-viewer" }, { access_token: "x" });
const a = await core.createAgent(db, { name: "Убранный" });
await core.updateAgent(db, a.id, { disabled: true });
assert.ok(!(await core.teamChaseView(db, user)).bench.some((x) => x.name === "Убранный"));
assert.equal(await core.teamChaseHidden(db, user.id), false);
await core.setTeamChaseHidden(db, user.id, true);
assert.equal(await core.teamChaseHidden(db, user.id), true);
});
test("Scenario: цвет агента стабилен и берётся из набора", () => {
assert.equal(core.agentColor("Барыс"), core.agentColor("Барыс"));
assert.match(core.agentColor("Барыс"), /^#[0-9a-f]{6}$/);
});
});