Merge branch 'main' into task/pep-181
This commit is contained in:
commit
ad39a8cc6f
@ -34,6 +34,7 @@
|
||||
- **Вкладка AGENTS.md (PEP-73)**: `runner/agents-md.ts` (`readAgentsMd`/`saveAgentsMd`: файл из ветки по умолчанию в Gitea через contents API — `GiteaClient.fileWithSha`/`writeFile`, сохранение против blob sha, ≤64 КБ, коммит от имени пользователя, событие `agents_md_updated`, ff свободной рабочей копии); вкладка проекта `?tab=agents` (`AgentsMdTab`, заготовка с чек-листом ИБ)
|
||||
- **Суперадмин и проекты (PEP-74)**: `projectForUser` пускает суперадмина в любой проект; `listOtherProjects` — секция «Проекты других» на «Проектах»; `userProjectIds` (Главная, вопросы, уведомления) — только свои
|
||||
- **Команда агентов (PEP-75)**: таблица `agents` (имя, `character`, `disabled_at`) + `sessions.agent_id` (миграция 0014), одна команда на платформу. `core/team.ts`: `ensureSessionAgent` (в `launch`, sync-транзакция: персонаж прошлых раннеров стори → свободный, отдыхавший дольше → новый из `AGENT_NAMES`), `agentPrompt` дописывается к правилам запуска вместе с памятью, `taskAgentNames` — имена на доске, `SessionView.agentName`. Имена сравнивать в JS: `lower()` SQLite не трогает кириллицу. Веб `/team` (видят все, меняет суперадмин — `team/actions.ts`), `components/AgentBadge.tsx`
|
||||
- **«Погоня за задачей» (PEP-179)**: над списком агентов на `/team` — `components/TeamChase.tsx` + `TeamChase.module.css` (пиксельный мопс, трасса `offset-path` из ширины — `trackPath`, ключевые кадры макета; у бегущего своё место `--d` — без анимации агенты стоят на трассе). Данные — `teamChaseView` (core/team-chase.ts): на трассе агенты с живым раннером (то же правило, что `listAgents`; ≤ `CHASE_TRACK_MAX` = 8, остальные «+N»; задача — только из видимых проектов), скамейка — свободные в команде, счётчик — задачи `done` видимых проектов (суперадмину — все), `agentColor` = тон `AgentBadge`; «Скрыть» — `settings` `ui.team-chase:<userId>`. «+1» — только при росте счётчика между обновлениями; «Жмите «Принять»» — первая из `acceptInbox`. Живая область `team` (как `home` + состав команды), `LiveRefresh pauseHidden` закрывает поток у скрытой вкладки. PWA: шрифт Press Start 2P — свои файлы `public/fonts/press-start-2p/` (OFL), `public/sw.js` (`VERSION`) кэширует шрифты, `/icon.svg` и `/_next/static` только с `immutable` (сначала кэш) и `/team` (сначала сеть); компонент регистрирует service worker; без сети — снимок `localStorage` `peppa.team-chase` и строка «Нет связи — данные на ЧЧ:ММ» (проверка — `fetch /api/health`, повтор 15 с). В подзапросах drizzle не пиши `${agents.id}` внутри `(select … from sessions s …)` — он рендерится голым `"id"` и берёт id сессии; квалифицируй `"agents"."id"`. Тест `team-chase.test.ts`
|
||||
- **Выбор подписки проекта (PEP-76)**: общий пул платформы — `platform.shared_pool` (`sharedPool`/`setSharedPool`, CLI `peppa platform shared-pool [id|-]`); владелец проекта (или суперадмин) в «⋯ Настройки проекта → Подписки» жмёт «Общая подписка Пеппы» (`chooseSharedSubscription`) или вставляет токен `claude setup-token` — «Своя подписка Claude» (`connectOwnSubscription`, runner/project-subscription.ts: подписка + личный пул `ownPool`); `projectAgentWarning` для проекта без пула и без права на вход машины — «подписка не выбрана»
|
||||
- **Чаты (PEP-62)**: таблицы `chats` (master на пользователя / project на проект, связанная Telegram-группа `tg_chat_id`) и `chat_messages` (тред = `thread_key` `task:|incident:|release:<id>`, null — канал; `important` → мастер-лента; `dedupe_key`), `telegram_outbox.chat_message_id` (миграция 0015). `core/chats.ts`: `syncChats` — идемпотентная проекция `events` (курсор `chat.cursor.events`, список `EVENT_TEXT`), `questions`, `releases`/`incidents` (по `updated_at`, ключ `<вид>:<id>:<статус>`) в чаты; зовут бот (`reconcile`), вачдог (`tick`) и страница `/chats`; `masterFeed` = свои сообщения мастер-чата ∪ `important` проектов; `pruneChats` — TTL `PEPPA_CHAT_TTL_DAYS` (14) в вачдоге раз в час; мониторинг и дайджест из `deliverToUser` пишутся в мастер-чат. `runner/chats.ts` `postToChat`: тред стори → `answerAndDeliver` открытого вопроса, иначе `addStoryComment` (`chatMessageId` в payload, проекция не дублирует) + `sendToSession`; `/status|/task|/move|/help` без LLM. Telegram (бот): связка кодом (`createChatLinkCode`, `c…`, 10 мин; `t.me/<bot>?startgroup=<код>` или `/link <код>`), зеркало по курсору `chat.mirror.cursor` (тред — реплаем на первое сообщение: `threadAnchor` при отправке), в группу принимаются только реплаи и команды от пользователя с личной привязкой (`telegramAccountUser`) и доступом; кнопки вопросов работают в группе. Веб `/chats/[master|KEY]?thread=`, live-область `chats`. Тест `chats.test.ts`
|
||||
- **Группы чатов через свой бот (PEP-109)**: «Связать с Telegram» в чате — через собственного бота пользователя (PEP-85): `chats.tg_bot_user_id` (миграция 0018; null — общий бот, им связывает только суперадмин без своего бота: `createChatLinkCode(…, { sharedBot })`, остальным без бота — отказ с подсказкой). Код привязан к боту (`botUserId` в настройке кода): `acceptChatLink` принимает только от него и чужим ботом не сжигается; на `/link` без `@бота` с чужим кодом бот молчит (`chatLinkCodeBot`). Бот: `ownByChat` дополняется группами (`chatGroupBots` в `syncOwnBots`) — исходящие в группу идут через бота связки; входящие сообщения и кнопки группы обрабатывает только он (`linkedHere`). `clearUserBot` / `setUserBot` с другим ботом отвязывают его группы. Тест `chats-own-bot.test.ts`
|
||||
|
||||
@ -1,3 +1,4 @@
|
||||
import { m as tr } from "@peppa/shared/i18n";
|
||||
// Minimal Telegram Bot API client. The base URL is configurable so tests can point it at
|
||||
// mock-telegram (packages/testkit).
|
||||
|
||||
@ -48,6 +49,18 @@ export interface InlineButton {
|
||||
url?: string;
|
||||
}
|
||||
|
||||
const TG_TEXT_MAX = 4096;
|
||||
const TG_CLIP_NOTE_TEXT = tr("(полностью — на сайте Peppa FACTORY)");
|
||||
const TG_CLIP_NOTE = "\n\n… " + TG_CLIP_NOTE_TEXT;
|
||||
|
||||
/** PEP-180: a text that fits Telegram — cut at the last line break before the limit. */
|
||||
export function clipForTelegram(text: string): string {
|
||||
if (text.length <= TG_TEXT_MAX) return text;
|
||||
const room = TG_TEXT_MAX - TG_CLIP_NOTE.length;
|
||||
const cut = text.lastIndexOf("\n", room);
|
||||
return `${text.slice(0, cut > room / 2 ? cut : room)}${TG_CLIP_NOTE}`;
|
||||
}
|
||||
|
||||
export class TelegramError extends Error {
|
||||
readonly method: string;
|
||||
readonly code: number;
|
||||
@ -71,6 +84,11 @@ export class TelegramApi {
|
||||
}
|
||||
|
||||
async call<T>(method: string, params: Record<string, unknown> = {}, timeoutMs = 15_000): Promise<T> {
|
||||
// PEP-180: Telegram refuses texts over 4096 characters — a long message goes shortened (cut at a
|
||||
// line break, so no HTML tag is left open), with a note that the whole text is on the site.
|
||||
if ((method === "sendMessage" || method === "editMessageText") && typeof params.text === "string" && params.text.length > TG_TEXT_MAX) {
|
||||
params = { ...params, text: clipForTelegram(params.text) };
|
||||
}
|
||||
let res: Response;
|
||||
try {
|
||||
res = await fetch(`${this.baseUrl}/bot${this.token}/${method}`, {
|
||||
|
||||
@ -273,7 +273,7 @@ export default async function ChatPage({ params, searchParams }: { params: Promi
|
||||
) : (
|
||||
<form action={postChatAction} className="sticky bottom-16 flex flex-col gap-2 rounded-lg border bg-card p-3 md:bottom-3">
|
||||
<Hidden fields={{ chatId: chat.id, thread: thread ?? "", back: here }} />
|
||||
<Textarea id="chat-text" name="text" rows={2} maxLength={8000} placeholder={placeholder} aria-label={t("Сообщение")} />
|
||||
<Textarea id="chat-text" name="text" rows={2} maxLength={60000} placeholder={placeholder} aria-label={t("Сообщение")} />
|
||||
{chat.projectId && <AttachField projectId={chat.projectId} target="chat-text" />}
|
||||
<div className="flex items-center gap-2">
|
||||
<Dictate target="chat-text" compact />
|
||||
|
||||
@ -191,7 +191,7 @@ export async function CommentsTab({ taskId, projectId, taskKey, taskStatus, ques
|
||||
<label htmlFor="story-comment" className="text-sm font-medium">
|
||||
{t("Комментарий к стори")}
|
||||
</label>
|
||||
<Textarea id="story-comment" name="text" rows={3} maxLength={8000} placeholder={t("Что учесть или изменить в задаче")} aria-describedby="story-comment-hint" />
|
||||
<Textarea id="story-comment" name="text" rows={3} maxLength={60000} placeholder={t("Что учесть или изменить в задаче")} aria-describedby="story-comment-hint" />
|
||||
<AttachField projectId={projectId} target="story-comment" />
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<Dictate target="story-comment" />
|
||||
|
||||
@ -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);
|
||||
}
|
||||
|
||||
@ -1,8 +1,10 @@
|
||||
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 { Empty, Flash, Notice, PageHeader, Section } from "@/components/common";
|
||||
import { LiveRefresh } from "@/components/LiveRefresh";
|
||||
import { Markdown } from "@/components/Markdown";
|
||||
import { TeamChase } from "@/components/TeamChase";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card } from "@/components/ui/card";
|
||||
@ -11,6 +13,7 @@ import { Workspace } from "@/components/Workspace";
|
||||
import { requireUser, words } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import { acceptInbox } from "@/lib/queries";
|
||||
import { addAgentAction, saveAgentAction, toggleAgentAction } from "./actions";
|
||||
|
||||
export async function generateMetadata() {
|
||||
@ -24,7 +27,7 @@ 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, chaseHidden, awaiting] = await Promise.all([listAgents(db), isSuperadmin(db, user), teamChaseView(db, user), teamChaseHidden(db, user.id), acceptInbox(user.id)]);
|
||||
return (
|
||||
<Workspace>
|
||||
<div className="max-w-3xl">
|
||||
@ -35,6 +38,8 @@ export default async function Team({ searchParams }: { searchParams: Promise<{ e
|
||||
{w.engineer ? t(" Характер добавляется к промпту агента поверх правил Peppa FACTORY и AGENTS.md проекта.") : t(" Характер влияет на то, как агент работает и пишет вам.")}
|
||||
</PageHeader>
|
||||
|
||||
<TeamChase view={chase} hidden={chaseHidden} awaitingKey={awaiting.find((q) => q.taskKey)?.taskKey ?? null} />
|
||||
|
||||
{admin && (
|
||||
<Card>
|
||||
<form action={addAgentAction} className="flex flex-wrap items-end gap-2">
|
||||
@ -97,6 +102,7 @@ export default async function Team({ searchParams }: { searchParams: Promise<{ e
|
||||
))}
|
||||
</Section>
|
||||
</div>
|
||||
<LiveRefresh scope="team" pauseHidden />
|
||||
</Workspace>
|
||||
);
|
||||
}
|
||||
|
||||
@ -119,3 +119,10 @@
|
||||
nextjs-portal {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
/* PEP-179: a team card the «Погоня за задачей» bench pointed at. */
|
||||
[data-highlight] {
|
||||
outline: 2px solid var(--ring);
|
||||
outline-offset: 4px;
|
||||
transition: outline-color 0.3s;
|
||||
}
|
||||
|
||||
@ -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
|
||||
|
||||
@ -101,7 +101,7 @@ export async function StoryProduct({ view, taskKey, taskStatus, preview, questio
|
||||
<label htmlFor="story-fix" className="text-sm">
|
||||
{t("Что поправить? Агент прочитает и доработает.")}
|
||||
</label>
|
||||
<Textarea id="story-fix" name="text" rows={3} required maxLength={8000} placeholder={t("Например: кнопка должна быть зелёной")} />
|
||||
<Textarea id="story-fix" name="text" rows={3} required maxLength={60000} placeholder={t("Например: кнопка должна быть зелёной")} />
|
||||
<Button size="sm" variant="outline" className="self-start">
|
||||
<Send />
|
||||
{t("Отправить агенту")}
|
||||
|
||||
722
apps/web/components/TeamChase.module.css
Normal file
722
apps/web/components/TeamChase.module.css
Normal 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;
|
||||
}
|
||||
}
|
||||
428
apps/web/components/TeamChase.tsx
Normal file
428
apps/web/components/TeamChase.tsx
Normal file
@ -0,0 +1,428 @@
|
||||
"use client";
|
||||
|
||||
// PEP-179: «Погоня за задачей» above the team list. The pug (the product manager) drops a task,
|
||||
// agents at work chase it around the track, free ones wait on the bench. Live data comes from
|
||||
// the page (core `teamChaseView`) and is re-read by `LiveRefresh scope="team"`; motion is pure CSS
|
||||
// (TeamChase.module.css). A copy of the last data stays in localStorage for the offline app.
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type CSSProperties } from "react";
|
||||
import type { ChaseAgent, TeamChaseView } from "@peppa/core";
|
||||
import { intlLocale } from "@peppa/shared/i18n";
|
||||
import { setTeamChaseHiddenAction } from "@/app/(app)/team/actions";
|
||||
import { useT } from "@/components/I18n";
|
||||
import { useWords } from "@/components/Words";
|
||||
import s from "./TeamChase.module.css";
|
||||
|
||||
const CYCLE = 9;
|
||||
const TASK_LEAD = 3.6;
|
||||
const FIRST_GAP = 0.67;
|
||||
const GAP = 0.54;
|
||||
const HEIGHT = 410;
|
||||
const TOP = 150;
|
||||
const BOTTOM = 380;
|
||||
const STORE = "peppa.team-chase";
|
||||
|
||||
/** The rounded track for a stage `w` px wide, starting under the pug (top middle). */
|
||||
export function trackPath(w: number): { d: string; left: number; right: number; r: number } {
|
||||
const m = Math.max(28, Math.round(w * 0.08));
|
||||
const left = m;
|
||||
const right = w - m;
|
||||
const r = Math.max(30, Math.min(80, (right - left) / 5, (BOTTOM - TOP) / 2));
|
||||
const cx = w / 2;
|
||||
const d = `M ${cx} ${TOP} H ${right - r} A ${r} ${r} 0 0 1 ${right} ${TOP + r} V ${BOTTOM - r} A ${r} ${r} 0 0 1 ${right - r} ${BOTTOM} H ${left + r} A ${r} ${r} 0 0 1 ${left} ${BOTTOM - r} V ${TOP + r} A ${r} ${r} 0 0 1 ${left + r} ${TOP} Z`;
|
||||
return { d, left, right, r };
|
||||
}
|
||||
|
||||
/** How far ahead (s) a runner in `slot` is: a line behind the task, around the loop. */
|
||||
const lead = (slot: number) => (((TASK_LEAD - FIRST_GAP - slot * GAP) % CYCLE) + CYCLE) % CYCLE;
|
||||
|
||||
/** Stable places on the track: an agent keeps its slot while it runs, so nobody jumps. */
|
||||
function useSlots(ids: number[]): Map<number, number> {
|
||||
const ref = useRef(new Map<number, number>());
|
||||
return useMemo(() => {
|
||||
const prev = ref.current;
|
||||
const next = new Map<number, number>();
|
||||
for (const id of ids) if (prev.has(id)) next.set(id, prev.get(id)!);
|
||||
for (const id of ids) {
|
||||
if (next.has(id)) continue;
|
||||
const used = new Set(next.values());
|
||||
let slot = 0;
|
||||
while (used.has(slot)) slot++;
|
||||
next.set(id, slot);
|
||||
}
|
||||
ref.current = next;
|
||||
return next;
|
||||
}, [ids.join(",")]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
}
|
||||
|
||||
// The pixel pug (12×11), coloured after the clay mascot (`PugMascot`). Asleep — eyes closed.
|
||||
const PUG_COLORS: Record<string, string> = { D: "#4A3428", F: "#E8B98A", K: "#0B0B0B", W: "#FFFFFF", P: "#FF7DB8" };
|
||||
const PUG_AWAKE = ["DD.FFFFFF.DD", "DDFFFFFFFFDD", "DFFFFFFFFFFD", "FFKKFFFFKKFF", "FFKWFFFFKWFF", "FFFFDDDDFFFF", "FFFDDDDDDFFF", "FFFDDKKDDFFF", ".FFDDDDDDFF.", ".FFFDPPDFFF.", "..FFFFFFFF.."];
|
||||
const PUG_ASLEEP = [...PUG_AWAKE.slice(0, 3), "FFFFFFFFFFFF", "FKKKFFFFKKKF", ...PUG_AWAKE.slice(5)];
|
||||
|
||||
function PixelPug({ asleep, label }: { asleep: boolean; label: string }) {
|
||||
const rows = asleep ? PUG_ASLEEP : PUG_AWAKE;
|
||||
return (
|
||||
<svg width="60" height="55" viewBox="0 0 12 11" shapeRendering="crispEdges" role="img" aria-label={label}>
|
||||
{rows.flatMap((row, y) => [...row].map((c, x) => (c === "." ? null : <rect key={`${x}-${y}`} x={x} y={y} width="1" height="1" fill={PUG_COLORS[c]} />)))}
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
/** The agent's sign: the first letter of the nickname in a circle of its colour. */
|
||||
const initial = (name: string) => [...name.trim()][0]?.toUpperCase() ?? "?";
|
||||
|
||||
function readStore(): TeamChaseView | null {
|
||||
try {
|
||||
const v = JSON.parse(localStorage.getItem(STORE) ?? "null");
|
||||
return v && Array.isArray(v.runners) && Array.isArray(v.bench) ? (v as TeamChaseView) : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function TeamChase({ view, hidden: hiddenAtStart, awaitingKey }: { view: TeamChaseView; hidden: boolean; awaitingKey: string | null }) {
|
||||
const t = useT();
|
||||
const w = useWords();
|
||||
const router = useRouter();
|
||||
const [hidden, setHidden] = useState(hiddenAtStart);
|
||||
const [data, setData] = useState(view);
|
||||
const [offline, setOffline] = useState(false);
|
||||
const [paused, setPaused] = useState(false);
|
||||
const [lowPower, setLowPower] = useState(false);
|
||||
const [open, setOpen] = useState<string | null>(null);
|
||||
const [width, setWidth] = useState(720);
|
||||
const [plus, setPlus] = useState(0);
|
||||
const stage = useRef<HTMLDivElement>(null);
|
||||
const touch = useRef(false);
|
||||
const accepted = useRef(view.accepted);
|
||||
const seen = useRef<Set<string> | null>(null);
|
||||
|
||||
// Fresh server data: keep it, remember it for the offline app, «+1» when the count grew.
|
||||
useEffect(() => {
|
||||
setData(view);
|
||||
try {
|
||||
localStorage.setItem(STORE, JSON.stringify(view));
|
||||
} catch {}
|
||||
if (view.accepted > accepted.current) setPlus((k) => k + 1);
|
||||
accepted.current = view.accepted;
|
||||
}, [view]);
|
||||
|
||||
// Offline: the newest known team (the cached page or the stored copy); back online — re-read.
|
||||
// «Offline» is also a network that is there while Peppa is not (the page came from the
|
||||
// service worker's cache): a small request to the server tells, repeated while it fails.
|
||||
useEffect(() => {
|
||||
let off = false;
|
||||
let timer: ReturnType<typeof setTimeout> | null = null;
|
||||
let stopped = false;
|
||||
const set = (next: boolean) => {
|
||||
if (next) {
|
||||
const stored = readStore();
|
||||
if (stored && stored.at > view.at) setData(stored);
|
||||
} else if (off) router.refresh();
|
||||
off = next;
|
||||
setOffline(next);
|
||||
};
|
||||
const probe = async () => {
|
||||
if (timer) clearTimeout(timer);
|
||||
timer = null;
|
||||
if (stopped || document.visibilityState !== "visible") return;
|
||||
let ok = navigator.onLine;
|
||||
if (ok) ok = await fetch("/api/health", { cache: "no-store" }).then(() => true, () => false);
|
||||
if (stopped) return;
|
||||
set(!ok);
|
||||
if (!ok) timer = setTimeout(probe, 15_000);
|
||||
};
|
||||
const onOffline = () => set(true);
|
||||
const onVisible = () => document.visibilityState === "visible" && void probe();
|
||||
void probe();
|
||||
window.addEventListener("online", probe);
|
||||
window.addEventListener("offline", onOffline);
|
||||
document.addEventListener("visibilitychange", onVisible);
|
||||
return () => {
|
||||
stopped = true;
|
||||
if (timer) clearTimeout(timer);
|
||||
window.removeEventListener("online", probe);
|
||||
window.removeEventListener("offline", onOffline);
|
||||
document.removeEventListener("visibilitychange", onVisible);
|
||||
};
|
||||
}, [router, view.at]);
|
||||
|
||||
// A hidden tab or a minimised app: the picture stands still.
|
||||
useEffect(() => {
|
||||
const onVis = () => setPaused(document.visibilityState !== "visible");
|
||||
onVis();
|
||||
document.addEventListener("visibilitychange", onVis);
|
||||
return () => document.removeEventListener("visibilitychange", onVis);
|
||||
}, []);
|
||||
|
||||
// Battery saver: a discharging battery under 20 % — no motion.
|
||||
useEffect(() => {
|
||||
const nav = navigator as Navigator & { getBattery?: () => Promise<{ charging: boolean; level: number; addEventListener: (e: string, f: () => void) => void }> };
|
||||
nav
|
||||
.getBattery?.()
|
||||
.then((b) => {
|
||||
const check = () => setLowPower(!b.charging && b.level <= 0.2);
|
||||
check();
|
||||
b.addEventListener("chargingchange", check);
|
||||
b.addEventListener("levelchange", check);
|
||||
})
|
||||
.catch(() => {});
|
||||
}, []);
|
||||
|
||||
// The installed app works offline: shell files and this page are cached by /sw.js.
|
||||
useEffect(() => {
|
||||
navigator.serviceWorker?.register("/sw.js", { scope: "/" }).catch(() => {});
|
||||
}, []);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const el = stage.current;
|
||||
if (!el) return;
|
||||
const measure = () => el.clientWidth && setWidth(el.clientWidth);
|
||||
measure();
|
||||
const ro = new ResizeObserver(measure);
|
||||
ro.observe(el);
|
||||
return () => ro.disconnect();
|
||||
}, [hidden]);
|
||||
|
||||
// Close an open hint on a tap elsewhere.
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const close = (e: PointerEvent) => !(e.target as Element).closest?.("[data-chase-key]") && setOpen(null);
|
||||
document.addEventListener("pointerdown", close);
|
||||
return () => document.removeEventListener("pointerdown", close);
|
||||
}, [open]);
|
||||
|
||||
const slots = useSlots(data.runners.map((a) => a.id));
|
||||
// Who just came in (from the bench or new to the team) — they hop in, the rest keep running.
|
||||
const fresh = useMemo(() => {
|
||||
const keys = [...data.runners.map((a) => `r${a.id}`), ...data.bench.map((a) => `b${a.id}`)];
|
||||
const before = seen.current;
|
||||
seen.current = new Set(keys);
|
||||
return before ? new Set(keys.filter((k) => !before.has(k))) : new Set<string>();
|
||||
}, [data]);
|
||||
|
||||
const toggle = (next: boolean) => {
|
||||
setHidden(next);
|
||||
void setTeamChaseHiddenAction(next).catch(() => {});
|
||||
};
|
||||
|
||||
/** Touch: the first tap shows the hint, the second acts. Mouse and keyboard act at once. */
|
||||
const tap = (key: string, act: () => void) => {
|
||||
if (touch.current && open !== key) return setOpen(key);
|
||||
setOpen(null);
|
||||
act();
|
||||
};
|
||||
const showCard = (id: number) => {
|
||||
const card = document.getElementById(`agent-${id}`);
|
||||
if (!card) return;
|
||||
const still = matchMedia("(prefers-reduced-motion: reduce)").matches;
|
||||
card.scrollIntoView({ behavior: still ? "auto" : "smooth", block: "center" });
|
||||
card.setAttribute("data-highlight", "");
|
||||
setTimeout(() => card.removeAttribute("data-highlight"), 2500);
|
||||
};
|
||||
|
||||
const hhmm = (iso: string) => new Date(iso).toLocaleTimeString(intlLocale(t.locale), { hour: "2-digit", minute: "2-digit" });
|
||||
const working = data.runners.length + data.extra;
|
||||
const idle = working === 0;
|
||||
const { d, left, right, r } = trackPath(width);
|
||||
const cx = width / 2;
|
||||
const tasksWord = w.Task("genPl");
|
||||
|
||||
if (hidden)
|
||||
return (
|
||||
<div className={`${s.chase} ${s.collapsed}`}>
|
||||
<span>
|
||||
{t("Работают: {n}", { n: working })} · {t("Свободны: {n}", { n: data.bench.length })}
|
||||
</span>
|
||||
<button type="button" className={s.hide} onClick={() => toggle(false)}>
|
||||
{t("Показать")}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
|
||||
const runnerLabel = (a: ChaseAgent) => (a.task ? t("Агент {name}, задача {title}", { name: a.name, title: a.task.title }) : t("Агент {name}, работает", { name: a.name }));
|
||||
const goTask = (a: ChaseAgent) => a.task && router.push(`/t/${a.task.key}`);
|
||||
const runnerProps = (a: ChaseAgent, key: string) => ({
|
||||
type: "button" as const,
|
||||
"aria-label": runnerLabel(a),
|
||||
"data-chase-key": key,
|
||||
"data-open": open === key ? "" : undefined,
|
||||
onPointerDown: (e: React.PointerEvent) => (touch.current = e.pointerType !== "mouse"),
|
||||
onKeyDown: () => (touch.current = false),
|
||||
onClick: () => tap(key, () => goTask(a)),
|
||||
});
|
||||
const tip = (a: ChaseAgent) => (
|
||||
<span className={s.tip} aria-hidden>
|
||||
{a.name}
|
||||
{" · "}
|
||||
{a.task ? `${a.task.key} ${a.task.title}` : t("работает")}
|
||||
</span>
|
||||
);
|
||||
|
||||
return (
|
||||
<section
|
||||
className={[s.chase, paused && s.paused, lowPower && s.still, idle && s.idle].filter(Boolean).join(" ")}
|
||||
aria-label={t("Агенты за работой")}
|
||||
data-team-chase
|
||||
>
|
||||
<div className={s.frame}>
|
||||
<div className={s.hud}>
|
||||
<span className={s.player}>
|
||||
{t("Игрок")}: <b>{t("вы")}</b>
|
||||
</span>
|
||||
<span className={s.title}>Peppa FACTORY</span>
|
||||
<span data-chase-counter={data.accepted}>
|
||||
{tasksWord}: <b>{String(data.accepted).padStart(6, "0")}</b>
|
||||
</span>
|
||||
</div>
|
||||
{offline && <p className={s.offline} role="status">{t("Нет связи — данные на {time}", { time: hhmm(data.at) })}</p>}
|
||||
|
||||
<div ref={stage} className={s.stage} style={{ "--path": `path('${d}')` } as CSSProperties}>
|
||||
<svg className={s.track} width={width} height={HEIGHT} aria-hidden>
|
||||
<path d={d} fill="none" stroke="#00E5FF" strokeWidth="10" strokeOpacity=".12" />
|
||||
<path d={d} fill="none" stroke="#00E5FF" strokeWidth="2" strokeDasharray="10 8" />
|
||||
</svg>
|
||||
{!idle && <div className={s.chute} style={{ left: cx }} />}
|
||||
<div className={s.you} style={{ left: cx }}>
|
||||
<div className={s.youbox} style={{ position: "relative" }}>
|
||||
<div className={s.pug}>
|
||||
<PixelPug asleep={idle} label={idle ? t("Мопс Peppa FACTORY спит") : t("Мопс Peppa FACTORY")} />
|
||||
</div>
|
||||
{idle && (
|
||||
<span className={s.zzz} aria-hidden>
|
||||
z<small>z</small>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<span className={s.youtag}>
|
||||
{t("вы")} · {t("продакт")}
|
||||
</span>
|
||||
</div>
|
||||
{idle ? (
|
||||
<div className={s.restingTask} style={{ left: cx + 56 }} aria-hidden />
|
||||
) : (
|
||||
<>
|
||||
<div className={s.say} style={{ left: cx }}>
|
||||
{t("Ловите {task}!", { task: w.task("acc") })}
|
||||
</div>
|
||||
<div className={s.drop} style={{ left: cx }} aria-hidden />
|
||||
<div className={s.task} aria-hidden />
|
||||
</>
|
||||
)}
|
||||
{plus > 0 && (
|
||||
<span key={plus} className={s.plus} style={{ left: cx }} aria-hidden>
|
||||
+1
|
||||
</span>
|
||||
)}
|
||||
{data.runners.map((a) => {
|
||||
const key = `r${a.id}`;
|
||||
const ahead = lead(slots.get(a.id) ?? 0);
|
||||
return (
|
||||
<button
|
||||
key={key}
|
||||
{...runnerProps(a, key)}
|
||||
className={`${s.runner} ${fresh.has(key) ? s.enter : ""}`}
|
||||
style={{ animationDelay: `-${ahead.toFixed(2)}s`, "--d": `${((ahead / CYCLE) * 100).toFixed(2)}%`, color: a.color } as CSSProperties}
|
||||
>
|
||||
<span className={s.hop} style={{ animationDelay: `-${((slots.get(a.id) ?? 0) * 0.11).toFixed(2)}s` }}>
|
||||
<span className={s.agent} aria-hidden>
|
||||
{initial(a.name)}
|
||||
</span>
|
||||
<span className={s.tag} aria-hidden>
|
||||
{a.name}
|
||||
</span>
|
||||
</span>
|
||||
{tip(a)}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
{data.extra > 0 && (
|
||||
<span className={s.more} style={{ left: right - r, top: TOP - 34 }}>
|
||||
+{data.extra}
|
||||
</span>
|
||||
)}
|
||||
<div className={s.mid} style={{ left: left + r * 0.5 + 16, right: width - right + r * 0.5 + 16, top: TOP + 34, height: BOTTOM - TOP - 68 }}>
|
||||
{idle ? (
|
||||
<p>{t("Агенты отдыхают")}</p>
|
||||
) : (
|
||||
<>
|
||||
<p>
|
||||
{t("Работают: {n}", { n: working })}
|
||||
<br />
|
||||
{t("Гоняют {task} по кругу, пока не доведут до готового", { task: w.task("acc") })}
|
||||
</p>
|
||||
<div className={s.legend} aria-hidden>
|
||||
{data.runners.map((a) => (
|
||||
<span key={a.id} style={{ color: a.color }}>
|
||||
■ {a.name}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{awaitingKey && (
|
||||
<a className={`${s.accept} ${s.blink}`} href={`/t/${awaitingKey}`}>
|
||||
{t("Жмите «Принять»")}
|
||||
</a>
|
||||
)}
|
||||
</div>
|
||||
<div className={s.row}>
|
||||
{data.runners.map((a) => {
|
||||
const key = `m${a.id}`;
|
||||
return (
|
||||
<button key={key} {...runnerProps(a, key)} className={s.mini} style={{ color: a.color }}>
|
||||
<span className={s.agent} aria-hidden>
|
||||
{initial(a.name)}
|
||||
</span>
|
||||
{tip(a)}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
{data.extra > 0 && <span className={s.more} style={{ position: "static", alignSelf: "center" }}>+{data.extra}</span>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{data.bench.length > 0 && (
|
||||
<div className={s.bench}>
|
||||
<h3>
|
||||
{t("Свободны: {n}", { n: data.bench.length })} · {t("наведите, чтобы узнать кличку")}
|
||||
</h3>
|
||||
<ul className={s.seats}>
|
||||
{data.bench.map((a, i) => {
|
||||
const key = `b${a.id}`;
|
||||
return (
|
||||
<li key={key}>
|
||||
<button
|
||||
type="button"
|
||||
className={`${s.seat} ${fresh.has(key) ? s.seatEnter : ""}`}
|
||||
style={{ color: a.color }}
|
||||
aria-label={t("Агент {name}, свободен", { name: a.name })}
|
||||
data-chase-key={key}
|
||||
data-open={open === key ? "" : undefined}
|
||||
onPointerDown={(e) => (touch.current = e.pointerType !== "mouse")}
|
||||
onKeyDown={() => (touch.current = false)}
|
||||
onClick={() => tap(key, () => showCard(a.id))}
|
||||
>
|
||||
<span className={s.seatIcon} style={{ animationDelay: `-${((i * 0.29) % 1.8).toFixed(2)}s` }} aria-hidden>
|
||||
{initial(a.name)}
|
||||
</span>
|
||||
<span className={s.tip} aria-hidden>
|
||||
{a.name} · {t("свободен")}
|
||||
</span>
|
||||
</button>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
<button type="button" className={s.hide} onClick={() => toggle(true)}>
|
||||
{t("Скрыть")}
|
||||
</button>
|
||||
<div className={s.scan} aria-hidden />
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
93
apps/web/public/fonts/press-start-2p/OFL.txt
Normal file
93
apps/web/public/fonts/press-start-2p/OFL.txt
Normal 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.
|
||||
BIN
apps/web/public/fonts/press-start-2p/cyrillic-ext.woff2
Normal file
BIN
apps/web/public/fonts/press-start-2p/cyrillic-ext.woff2
Normal file
Binary file not shown.
BIN
apps/web/public/fonts/press-start-2p/cyrillic.woff2
Normal file
BIN
apps/web/public/fonts/press-start-2p/cyrillic.woff2
Normal file
Binary file not shown.
BIN
apps/web/public/fonts/press-start-2p/latin-ext.woff2
Normal file
BIN
apps/web/public/fonts/press-start-2p/latin-ext.woff2
Normal file
Binary file not shown.
BIN
apps/web/public/fonts/press-start-2p/latin.woff2
Normal file
BIN
apps/web/public/fonts/press-start-2p/latin.woff2
Normal file
Binary file not shown.
@ -1,7 +1,75 @@
|
||||
// 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()));
|
||||
//
|
||||
// Offline shell (PEP-179): fonts, the icon and hashed Next.js files — cache first (their names
|
||||
// never change for new content); the «Команда» page — network first, the cached copy without a
|
||||
// network. A new version of this file bumps VERSION: activation drops the old caches, so an old
|
||||
// worker's files never mix with a new build's.
|
||||
const VERSION = "v2";
|
||||
const SHELL = `peppa-shell-${VERSION}`;
|
||||
const PAGES = `peppa-pages-${VERSION}`;
|
||||
const SHELL_FILES = ["/icon.svg", "/fonts/press-start-2p/latin.woff2", "/fonts/press-start-2p/cyrillic.woff2", "/fonts/press-start-2p/cyrillic-ext.woff2", "/fonts/press-start-2p/latin-ext.woff2"];
|
||||
const OFFLINE_PAGES = ["/team"];
|
||||
|
||||
self.addEventListener("install", (event) => {
|
||||
self.skipWaiting();
|
||||
event.waitUntil(
|
||||
caches
|
||||
.open(SHELL)
|
||||
.then((c) => c.addAll(SHELL_FILES))
|
||||
.catch(() => {}),
|
||||
);
|
||||
});
|
||||
self.addEventListener("activate", (event) =>
|
||||
event.waitUntil(
|
||||
(async () => {
|
||||
const keep = new Set([SHELL, PAGES]);
|
||||
for (const k of await caches.keys()) if (k.startsWith("peppa-") && !keep.has(k)) await caches.delete(k);
|
||||
await self.clients.claim();
|
||||
})(),
|
||||
),
|
||||
);
|
||||
|
||||
const isShellFile = (url) => url.pathname.startsWith("/_next/static/") || url.pathname.startsWith("/fonts/") || url.pathname === "/icon.svg";
|
||||
|
||||
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;
|
||||
if (isShellFile(url)) {
|
||||
event.respondWith(
|
||||
caches.open(SHELL).then(async (c) => {
|
||||
const hit = await c.match(req);
|
||||
if (hit) return hit;
|
||||
const res = await fetch(req);
|
||||
// Next.js files only when the server calls them immutable (a build) — the dev server's
|
||||
// chunks keep their names across edits and must not be pinned.
|
||||
const pin = !url.pathname.startsWith("/_next/") || /immutable/.test(res.headers.get("cache-control") || "");
|
||||
if (res.ok && pin) c.put(req, res.clone()).catch(() => {});
|
||||
return res;
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
// The page itself (not the RSC data of a client navigation): network first, cache offline.
|
||||
if (req.mode === "navigate" && OFFLINE_PAGES.includes(url.pathname)) {
|
||||
event.respondWith(
|
||||
(async () => {
|
||||
const c = await caches.open(PAGES);
|
||||
try {
|
||||
const res = await fetch(req);
|
||||
if (res.ok && !res.redirected) c.put(url.pathname, res.clone()).catch(() => {});
|
||||
return res;
|
||||
} catch (e) {
|
||||
const hit = await c.match(url.pathname);
|
||||
if (hit) return hit;
|
||||
throw e;
|
||||
}
|
||||
})(),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
self.addEventListener("push", (event) => {
|
||||
let p = {};
|
||||
|
||||
@ -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 и на Главной, изменения карточек агентов.
|
||||
@ -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** видит последний состав, строку «Нет связи — данные на ЧЧ:ММ», шрифт и мопса
|
||||
@ -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, уменьшенное движение)
|
||||
@ -0,0 +1 @@
|
||||
Общий предел `MAX_TEXT` = 60 000 в runner/chats.ts и core/tasks.ts. В промпте аналитика последнее сообщение — целиком, остальные `clip(…, 4000)`. Урезание для Telegram — в `TelegramApi.call` (sendMessage/editMessageText) по последнему переводу строки, чтобы не оставить открытый HTML-тег.
|
||||
@ -0,0 +1,7 @@
|
||||
## Why
|
||||
Длинный документ, вставленный в «Чат с аналитиком» или комментарий к задаче, отклонялся («длиннее 8000 символов»).
|
||||
|
||||
## What Changes
|
||||
- Лимит сообщения чата и комментария к задаче — 60 000 символов; сверх — «приложите файлом».
|
||||
- Аналитик получает последнее сообщение целиком, старые длинные — сокращённо.
|
||||
- Telegram: текст длиннее 4096 уходит сокращённым с припиской «полностью — на сайте».
|
||||
@ -0,0 +1,20 @@
|
||||
## ADDED Requirements
|
||||
### Requirement: Длинное сообщение принимается целиком
|
||||
Система SHALL принимать сообщение чата и комментарий к задаче до 60 000 символов.
|
||||
|
||||
#### Scenario: Вставлен большой документ
|
||||
- **GIVEN** открыт «Чат с аналитиком»
|
||||
- **WHEN** пользователь отправляет текст в 20 000 символов
|
||||
- **THEN** сообщение принято целиком
|
||||
- **AND** аналитик отвечает на него, читая весь текст
|
||||
|
||||
#### Scenario: Текст слишком длинный
|
||||
- **GIVEN** открыт «Чат с аналитиком»
|
||||
- **WHEN** пользователь отправляет текст в 70 000 символов
|
||||
- **THEN** сообщение не принято
|
||||
- **AND** показано «Сообщение длиннее 60000 символов»
|
||||
|
||||
#### Scenario: Длинный текст в Telegram
|
||||
- **GIVEN** к чату привязан Telegram
|
||||
- **WHEN** приходит сообщение длиннее 4096 символов
|
||||
- **THEN** в Telegram уходит сокращённый текст с припиской, что полностью — на сайте
|
||||
@ -0,0 +1,5 @@
|
||||
## 1. Реализация
|
||||
- [x] 1.1 Предел 60 000 для чата и комментариев, тексты en/kk
|
||||
- [x] 1.2 Аналитик читает последнее сообщение целиком
|
||||
- [x] 1.3 Сокращение длинного текста для Telegram
|
||||
- [x] 1.4 Тест в chats.test.ts
|
||||
@ -327,3 +327,23 @@ SHALL быть доступен под «Подробнее» только су
|
||||
- **GIVEN** тот же шаг
|
||||
- **WHEN** страницу открывает пользователь в виде «Инженер»
|
||||
- **THEN** в ленте видна команда `pnpm test --filter web`
|
||||
|
||||
### Requirement: Длинное сообщение принимается целиком
|
||||
Система SHALL принимать сообщение чата и комментарий к задаче до 60 000 символов.
|
||||
|
||||
#### Scenario: Вставлен большой документ
|
||||
- **GIVEN** открыт «Чат с аналитиком»
|
||||
- **WHEN** пользователь отправляет текст в 20 000 символов
|
||||
- **THEN** сообщение принято целиком
|
||||
- **AND** аналитик отвечает на него, читая весь текст
|
||||
|
||||
#### Scenario: Текст слишком длинный
|
||||
- **GIVEN** открыт «Чат с аналитиком»
|
||||
- **WHEN** пользователь отправляет текст в 70 000 символов
|
||||
- **THEN** сообщение не принято
|
||||
- **AND** показано «Сообщение длиннее 60000 символов»
|
||||
|
||||
#### Scenario: Длинный текст в Telegram
|
||||
- **GIVEN** к чату привязан Telegram
|
||||
- **WHEN** приходит сообщение длиннее 4096 символов
|
||||
- **THEN** в Telegram уходит сокращённый текст с припиской, что полностью — на сайте
|
||||
|
||||
38
openspec/specs/team-page/spec.md
Normal file
38
openspec/specs/team-page/spec.md
Normal 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** видит последний состав, строку «Нет связи — данные на ЧЧ:ММ», шрифт и мопса
|
||||
@ -92,7 +92,8 @@ export function analystChatPrompt(context: string, history: ChatTurn[], files =
|
||||
"",
|
||||
...(files ? [files, ""] : []),
|
||||
"## Переписка (последние сообщения, старые сверху)",
|
||||
...history.map((t) => `${t.who}: ${t.text.trim()}`),
|
||||
// PEP-180: the message being answered goes whole (a pasted document); older long ones shortened.
|
||||
...history.map((t, i) => `${t.who}: ${i === history.length - 1 ? t.text.trim() : clip(t.text.trim(), 4000)}`),
|
||||
"",
|
||||
'Ответь на последнее сообщение ОДНОЙ строкой JSON без пояснений: {"reply":"…","create":[{"title":"…","description":"…"}]}',
|
||||
"reply — твой ответ в чат (обычный текст, можно с переносами строк и списком через «•»). create — стори, которые нужно завести прямо сейчас (обычно пустой список); description — что должно получиться, для кого, и критерии приёмки списком.",
|
||||
|
||||
@ -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";
|
||||
|
||||
@ -270,10 +270,14 @@ export interface StoryComment {
|
||||
}
|
||||
|
||||
/** A PM comment on a story (PEP-32): an event the agent sees in get_task. */
|
||||
/** PEP-180: the longest message a person can send in a chat or a task's discussion. */
|
||||
export const MESSAGE_MAX = 60_000;
|
||||
|
||||
export async function addStoryComment(db: Db, ref: TaskRef, author: { id: number; login: string }, text: string, extra: { chatMessageId?: number } = {}): Promise<StoryComment> {
|
||||
const body = text.trim();
|
||||
if (!body) throw new PeppaError(tr("Пустой комментарий"));
|
||||
if (body.length > 8000) throw new PeppaError(tr("Комментарий длиннее 8000 символов"));
|
||||
// PEP-180: a pasted document fits; longer — as a file (PEP-159).
|
||||
if (body.length > MESSAGE_MAX) throw new PeppaError(tr("Текст слишком длинный (больше {n} символов) — приложите его файлом", { n: MESSAGE_MAX }));
|
||||
const [row] = await db
|
||||
.insert(events)
|
||||
.values({ projectId: ref.project.id, taskId: ref.task.id, type: COMMENT_EVENT, payload: { userId: author.id, login: author.login, text: body, ...extra }, ...actorColumns() })
|
||||
|
||||
91
packages/core/src/team-chase.ts
Normal file
91
packages/core/src/team-chase.ts
Normal file
@ -0,0 +1,91 @@
|
||||
// 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 { 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, type User } 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");
|
||||
}
|
||||
@ -32,8 +32,10 @@ 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})`,
|
||||
// Qualified on purpose: drizzle renders ${agents.id} as a bare "id", which inside the
|
||||
// subquery is the session's own id (PEP-179 found every card counting the wrong rows).
|
||||
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 +124,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();
|
||||
}
|
||||
|
||||
@ -2,29 +2,7 @@
|
||||
// answers the story's open question or becomes a PM comment typed into the live runner; in
|
||||
// other threads and the channel it is a note; a text starting with "/" is a command.
|
||||
import { asIs, m, m as tr } from "@peppa/shared/i18n";
|
||||
import {
|
||||
addChatMessage,
|
||||
addStoryComment,
|
||||
attachmentLabel,
|
||||
linkAttachments,
|
||||
parseAttachmentIds,
|
||||
refinePending,
|
||||
chatForUser,
|
||||
deliverToUser,
|
||||
projectAudience,
|
||||
listSessions,
|
||||
notify,
|
||||
pendingQuestions,
|
||||
projectForUser,
|
||||
resolveTask,
|
||||
statusRu,
|
||||
THREAD_KEY,
|
||||
userProjectIds,
|
||||
type Chat,
|
||||
type ChatMessage,
|
||||
type User,
|
||||
PeppaError,
|
||||
} from "@peppa/core";
|
||||
import { addChatMessage, addStoryComment, attachmentLabel, linkAttachments, parseAttachmentIds, refinePending, chatForUser, deliverToUser, projectAudience, listSessions, notify, pendingQuestions, projectForUser, resolveTask, statusRu, THREAD_KEY, userProjectIds, type Chat, type ChatMessage, type User, PeppaError, MESSAGE_MAX } from "@peppa/core";
|
||||
import { attachments, projects, questions, tasks, type Db } from "@peppa/db";
|
||||
import { and, desc, eq, isNull, ne } from "drizzle-orm";
|
||||
import { moveTask, type BoardColumn } from "./flow.ts";
|
||||
@ -50,7 +28,7 @@ export interface ChatPostResult {
|
||||
reply: ChatMessage | null;
|
||||
}
|
||||
|
||||
const MAX_TEXT = 8000;
|
||||
const MAX_TEXT = MESSAGE_MAX;
|
||||
|
||||
export const CHAT_HELP = [
|
||||
// glossary-ignore: команды чата (/status, /move) — не команды терминала; названия колонок — часть команды
|
||||
@ -84,7 +62,7 @@ export async function postToChat(db: Db, user: User, p: ChatPost): Promise<ChatP
|
||||
const ids = parseAttachmentIds(p.attachmentIds ?? []);
|
||||
const text = p.text.trim() || (await attachmentLabel(db, ids));
|
||||
if (!text) throw new PeppaError(m("Пустое сообщение"));
|
||||
if (text.length > MAX_TEXT) throw new PeppaError(m("Сообщение длиннее {n} символов", { n: MAX_TEXT }));
|
||||
if (text.length > MAX_TEXT) throw new PeppaError(m("Текст слишком длинный (больше {n} символов) — приложите его файлом", { n: MAX_TEXT }));
|
||||
if (p.threadKey && !THREAD_KEY.test(p.threadKey)) throw new PeppaError(m("Неизвестный тред"));
|
||||
if (chat.kind === "master" && p.threadKey) throw new PeppaError(m("В мастер-чате нет своих тредов — ответь в чате проекта"));
|
||||
const taskId = p.threadKey?.startsWith("task:") ? Number(p.threadKey.slice(5)) : null;
|
||||
|
||||
@ -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("|");
|
||||
|
||||
@ -346,6 +346,22 @@ export const admin: Dict = {
|
||||
"открыть": "open",
|
||||
"с {date}": "since {date}",
|
||||
"пароль": "password",
|
||||
|
||||
// Team picture (PEP-179)
|
||||
"Работают: {n}": "At work: {n}",
|
||||
"Свободны: {n}": "Free: {n}",
|
||||
"Агент {name}, задача {title}": "Agent {name}, task {title}",
|
||||
"Агент {name}, работает": "Agent {name}, at work",
|
||||
"Агент {name}, свободен": "Agent {name}, free",
|
||||
"Агенты за работой": "Agents at work",
|
||||
"Игрок": "Player",
|
||||
"Нет связи — данные на {time}": "Offline — data as of {time}",
|
||||
"Мопс Peppa FACTORY": "Peppa FACTORY pug",
|
||||
"Ловите {task}!": "Catch the {task}!",
|
||||
"Агенты отдыхают": "Agents are resting",
|
||||
"Гоняют {task} по кругу, пока не доведут до готового": "Chasing the {task} around until it is done",
|
||||
"Жмите «Принять»": "Press «Accept»",
|
||||
"наведите, чтобы узнать кличку": "hover to see the nickname",
|
||||
"Куда перевести агентов": "Where to move the agents",
|
||||
"на любую свободную": "to any free one",
|
||||
"Агенты сразу продолжат на выбранной подписке": "The agents continue on the chosen subscription at once",
|
||||
|
||||
@ -461,4 +461,5 @@ export const bot: Dict = {
|
||||
"Выпустить новый ключ у провайдера (OpenAI-совместимый API), старый отозвать.": "Issue a new key at the provider (OpenAI-compatible API), revoke the old one.",
|
||||
"В `PEPPA_TRANSCRIBE_KEY`, перезапустить бота.": "Into `PEPPA_TRANSCRIBE_KEY`, restart the bot.",
|
||||
"Отметить: `peppa secrets rotated PEPPA_TRANSCRIBE_KEY`.": "Mark: `peppa secrets rotated PEPPA_TRANSCRIBE_KEY`.",
|
||||
"(полностью — на сайте Peppa FACTORY)": "(in full — on the Peppa FACTORY site)",
|
||||
};
|
||||
|
||||
@ -424,4 +424,5 @@ export const runner: Dict = {
|
||||
"Завёл в бэклог:": "Added to the backlog:",
|
||||
"Чтобы продукт заработал по-настоящему, а не в демо-режиме, нужно от вас:": "For the product to work for real, not in demo mode, we need from you:",
|
||||
"Агент не может работать в копии, из которой работает сама Peppa FACTORY ({dir}): ему нужна своя рабочая копия. Запустите агента заново — он получит её сам.": "The agent cannot work in the copy Peppa FACTORY itself runs from ({dir}): it needs a working copy of its own. Start the agent again — it gets one by itself.",
|
||||
"Текст слишком длинный (больше {n} символов) — приложите его файлом": "The text is too long (over {n} characters) — attach it as a file",
|
||||
};
|
||||
|
||||
@ -306,6 +306,22 @@ export const admin: Dict = {
|
||||
"открыть": "ашу",
|
||||
"с {date}": "{date} бастап",
|
||||
"пароль": "құпиясөз",
|
||||
|
||||
// Team picture (PEP-179)
|
||||
"Работают: {n}": "Жұмыста: {n}",
|
||||
"Свободны: {n}": "Бос: {n}",
|
||||
"Агент {name}, задача {title}": "Агент {name}, тапсырма {title}",
|
||||
"Агент {name}, работает": "Агент {name}, жұмыста",
|
||||
"Агент {name}, свободен": "Агент {name}, бос",
|
||||
"Агенты за работой": "Агенттер жұмыста",
|
||||
"Игрок": "Ойыншы",
|
||||
"Нет связи — данные на {time}": "Байланыс жоқ — деректер {time} бойынша",
|
||||
"Мопс Peppa FACTORY": "Peppa FACTORY мопсы",
|
||||
"Ловите {task}!": "{task} ұстаңыз!",
|
||||
"Агенты отдыхают": "Агенттер демалып жатыр",
|
||||
"Гоняют {task} по кругу, пока не доведут до готового": "{task} дайын болғанша шеңбер бойымен қуады",
|
||||
"Жмите «Принять»": "«Қабылдау» басыңыз",
|
||||
"наведите, чтобы узнать кличку": "лақап атын көру үшін меңзерді апарыңыз",
|
||||
"Куда перевести агентов": "Агенттерді қайда ауыстыру",
|
||||
"на любую свободную": "кез келген бос жазылымға",
|
||||
"Агенты сразу продолжат на выбранной подписке": "Агенттер таңдалған жазылымда бірден жалғастырады",
|
||||
|
||||
@ -460,4 +460,5 @@ export const bot: Dict = {
|
||||
"Выпустить новый ключ у провайдера (OpenAI-совместимый API), старый отозвать.": "Провайдерден (OpenAI-үйлесімді API) жаңа кілт шығарып, ескісін қайтарып алу.",
|
||||
"В `PEPPA_TRANSCRIBE_KEY`, перезапустить бота.": "`PEPPA_TRANSCRIBE_KEY` ішіне, ботты қайта іске қосыңыз.",
|
||||
"Отметить: `peppa secrets rotated PEPPA_TRANSCRIBE_KEY`.": "Белгілеу: `peppa secrets rotated PEPPA_TRANSCRIBE_KEY`.",
|
||||
"(полностью — на сайте Peppa FACTORY)": "(толығымен — Peppa FACTORY сайтында)",
|
||||
};
|
||||
|
||||
@ -332,4 +332,5 @@ export const runner: Dict = {
|
||||
"Завёл в бэклог:": "Бэклогқа қостым:",
|
||||
"Чтобы продукт заработал по-настоящему, а не в демо-режиме, нужно от вас:": "Өнім демо-режимде емес, шын жұмыс істеуі үшін сізден керек:",
|
||||
"Агент не может работать в копии, из которой работает сама Peppa FACTORY ({dir}): ему нужна своя рабочая копия. Запустите агента заново — он получит её сам.": "Агент Peppa FACTORY өзі жұмыс істейтін көшірмеде ({dir}) жұмыс істей алмайды: оған өз жұмыс көшірмесі керек. Агентті қайта іске қосыңыз — ол оны өзі алады.",
|
||||
"Текст слишком длинный (больше {n} символов) — приложите его файлом": "Мәтін тым ұзын ({n} таңбадан көп) — оны файл етіп тіркеңіз",
|
||||
};
|
||||
|
||||
@ -101,6 +101,20 @@ describe("project chat", () => {
|
||||
assert.equal(thread.filter((m) => m.text === "не забудь заголовки").length, 1);
|
||||
});
|
||||
|
||||
test("PEP-180: длинный документ в канале проекта принимается целиком; сверх предела — просьба приложить файлом", async () => {
|
||||
const p = await newProject();
|
||||
const chat = await core.ensureProjectChat(db, p.id);
|
||||
const doc = `Документ\n${"строка документа с ролями и правами\n".repeat(900)}`;
|
||||
assert.ok(doc.length > 8000 && doc.length < core.MESSAGE_MAX);
|
||||
const r = await runner.postToChat(db, pm, { chatId: chat.id, threadKey: null, text: doc, via: "web" });
|
||||
assert.equal(r.message.text.length, doc.trim().length, "kept whole");
|
||||
await assert.rejects(runner.postToChat(db, pm, { chatId: chat.id, threadKey: null, text: "x".repeat(core.MESSAGE_MAX + 1), via: "web" }), /приложите его файлом/);
|
||||
const { clipForTelegram } = await import("@peppa/bot/telegram");
|
||||
const tg = clipForTelegram(doc);
|
||||
assert.ok(tg.length <= 4096 && tg.endsWith("(полностью — на сайте Peppa FACTORY)"), "Telegram gets a shortened copy");
|
||||
assert.equal(clipForTelegram("коротко"), "коротко");
|
||||
});
|
||||
|
||||
test("Чужой проект: запрос отклонён, сообщения нет", async () => {
|
||||
const p = await newProject();
|
||||
const chat = await core.ensureProjectChat(db, p.id);
|
||||
|
||||
99
packages/testkit/test/team-chase.test.ts
Normal file
99
packages/testkit/test/team-chase.test.ts
Normal file
@ -0,0 +1,99 @@
|
||||
// PEP-179: the «Погоня за задачей» picture on «Команда» — on the track exactly the agents with a
|
||||
// live runner (their story only when the viewer sees its project), on the bench the free agents
|
||||
// of the team (removed ones are not there), the counter = stories in «Готово» the viewer sees.
|
||||
import assert from "node:assert/strict";
|
||||
import { after, describe, test } from "node:test";
|
||||
import { agents, projects, sessions, tasks } from "@peppa/db";
|
||||
import { core, db, runner, teardown } from "./helpers.ts";
|
||||
|
||||
process.env.PEPPA_SECRET = "mock-secret-for-tests";
|
||||
after(teardown);
|
||||
|
||||
async function world() {
|
||||
const tag = Math.random().toString(36).slice(2, 8);
|
||||
const n = Math.floor(Math.random() * 1e6) + 2e6;
|
||||
const owner = await core.upsertUserFromGitea(db, { id: n, login: `mock-owner-${tag}` }, { access_token: "x" });
|
||||
const other = await core.upsertUserFromGitea(db, { id: n + 1, login: `mock-other-${tag}` }, { access_token: "y" });
|
||||
const admin = await core.upsertUserFromGitea(db, { id: n + 2, login: `mock-admin-${tag}` }, { access_token: "z" });
|
||||
await core.setSetting(db, "platform.admins", [admin.login]);
|
||||
const mkProject = async (ownerId: number, k: string) =>
|
||||
(await db.insert(projects).values({ slug: `mock-chase-${k}-${tag}`, key: `${k}${tag.toUpperCase()}`, name: k, ownerId, giteaOwner: "peppa-bot", giteaRepo: `mock-chase-${k}-${tag}`, workspacePath: `/tmp/mock-chase-${k}-${tag}` }).returning())[0]!;
|
||||
const mine = await mkProject(owner.id, "A");
|
||||
const theirs = await mkProject(other.id, "B");
|
||||
const mkTask = async (projectId: number, number: number, title: string, status: "in_progress" | "done" | "review" = "in_progress") =>
|
||||
(await db.insert(tasks).values({ projectId, number, title, status }).returning())[0]!;
|
||||
const mkAgent = async (name: string, disabled = false) => (await db.insert(agents).values({ name: `${name}-${tag}`, disabledAt: disabled ? new Date() : null }).returning())[0]!;
|
||||
const run = async (agentId: number, projectId: number, taskId: number, status: "running" | "done" = "running") =>
|
||||
db.insert(sessions).values({ projectId, taskId, agentId, provider: "claude", status, tmuxName: `mock-chase-${tag}-${Math.random().toString(36).slice(2, 6)}` });
|
||||
return { tag, owner, other, admin, mine, theirs, mkTask, mkAgent, run };
|
||||
}
|
||||
|
||||
describe("PEP-179: погоня за задачей", () => {
|
||||
test("Трасса — работающие, скамейка — свободные в команде, вместе — как список агентов", async () => {
|
||||
const w = await world();
|
||||
const t1 = await w.mkTask(w.mine.id, 1, "Корзина");
|
||||
const t2 = await w.mkTask(w.theirs.id, 1, "Чужая задача");
|
||||
const barys = await w.mkAgent("Барыс");
|
||||
const chip = await w.mkAgent("Чип");
|
||||
const free = await w.mkAgent("Искра");
|
||||
const gone = await w.mkAgent("Енот", true);
|
||||
const finished = await w.mkAgent("Байт");
|
||||
await w.run(barys.id, w.mine.id, t1.id);
|
||||
await w.run(chip.id, w.theirs.id, t2.id);
|
||||
await w.run(finished.id, w.mine.id, t1.id, "done");
|
||||
|
||||
const v = await core.teamChaseView(db, w.owner);
|
||||
const ids = (list: { id: number }[]) => list.map((a) => a.id);
|
||||
assert.deepEqual(ids(v.runners).filter((id) => [barys.id, chip.id].includes(id)), [barys.id, chip.id]);
|
||||
assert.ok(ids(v.bench).includes(free.id) && ids(v.bench).includes(finished.id));
|
||||
assert.ok(!ids(v.bench).includes(gone.id), "убранный из команды не на скамейке");
|
||||
assert.ok(!ids(v.runners).includes(free.id));
|
||||
|
||||
// Same rule as the cards: busy > 0 ↔ on the track; free and in the team ↔ on the bench.
|
||||
const team = (await core.listAgents(db)).filter((a) => a.name.endsWith(`-${w.tag}`));
|
||||
const own = (list: { id: number }[]) => new Set(ids(list).filter((id) => team.some((a) => a.id === id)));
|
||||
assert.deepEqual(own(v.runners), new Set(team.filter((a) => a.busy > 0).map((a) => a.id)));
|
||||
assert.deepEqual(own(v.bench), new Set(team.filter((a) => a.busy === 0 && !a.disabledAt).map((a) => a.id)));
|
||||
|
||||
const b = v.runners.find((a) => a.id === barys.id)!;
|
||||
assert.deepEqual(b.task, { key: `A${w.tag.toUpperCase()}-1`, title: "Корзина" });
|
||||
assert.equal(v.runners.find((a) => a.id === chip.id)!.task, null, "задачу чужого проекта не показываем");
|
||||
assert.equal(b.color, core.agentColor(barys.name));
|
||||
|
||||
const forAdmin = await core.teamChaseView(db, w.admin);
|
||||
assert.equal(forAdmin.runners.find((a) => a.id === chip.id)!.task?.title, "Чужая задача");
|
||||
});
|
||||
|
||||
test("Счётчик — задачи в «Готово» видимых проектов; суперадмину — все", async () => {
|
||||
const w = await world();
|
||||
const before = await core.teamChaseView(db, w.owner);
|
||||
const beforeAdmin = await core.teamChaseView(db, w.admin);
|
||||
await w.mkTask(w.mine.id, 10, "Готово 1", "done");
|
||||
await w.mkTask(w.mine.id, 11, "Готово 2", "done");
|
||||
await w.mkTask(w.mine.id, 12, "На приёмке", "review");
|
||||
await w.mkTask(w.theirs.id, 10, "Чужое готово", "done");
|
||||
assert.equal((await core.teamChaseView(db, w.owner)).accepted - before.accepted, 2);
|
||||
assert.equal((await core.teamChaseView(db, w.admin)).accepted - beforeAdmin.accepted, 3);
|
||||
assert.equal((await core.teamChaseView(db, w.other)).accepted, 1);
|
||||
});
|
||||
|
||||
test("Больше 8 работающих — «+N»", async () => {
|
||||
const w = await world();
|
||||
const t = await w.mkTask(w.mine.id, 20, "Много");
|
||||
for (let i = 0; i < 11; i++) await w.run((await w.mkAgent(`Агент${i}`)).id, w.mine.id, t.id);
|
||||
const v = await core.teamChaseView(db, w.owner);
|
||||
assert.equal(v.runners.length, core.CHASE_TRACK_MAX);
|
||||
assert.ok(v.extra >= 3);
|
||||
});
|
||||
|
||||
test("«Скрыть» запоминается для пользователя; живая область team", async () => {
|
||||
const w = await world();
|
||||
assert.equal(await core.teamChaseHidden(db, w.owner.id), false);
|
||||
await core.setTeamChaseHidden(db, w.owner.id, true);
|
||||
assert.equal(await core.teamChaseHidden(db, w.owner.id), true);
|
||||
assert.equal(await core.teamChaseHidden(db, w.other.id), false);
|
||||
await core.setTeamChaseHidden(db, w.owner.id, false);
|
||||
assert.equal(await core.teamChaseHidden(db, w.owner.id), false);
|
||||
assert.deepEqual(runner.parseScopes("team"), ["team"]);
|
||||
});
|
||||
});
|
||||
Loading…
Reference in New Issue
Block a user