diff --git a/AGENTS.md b/AGENTS.md index e1a38d39..d63158c7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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:`. «+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:`, 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`, ключ `<вид>::<статус>`) в чаты; зовут бот (`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/?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` diff --git a/apps/web/app/(app)/team/actions.ts b/apps/web/app/(app)/team/actions.ts index 246f47e5..96dd8381 100644 --- a/apps/web/app/(app)/team/actions.ts +++ b/apps/web/app/(app)/team/actions.ts @@ -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 { + const user = await requireUser(); + await setTeamChaseHidden(db, user.id, hidden); +} diff --git a/apps/web/app/(app)/team/page.tsx b/apps/web/app/(app)/team/page.tsx index 13f1291b..4f45f241 100644 --- a/apps/web/app/(app)/team/page.tsx +++ b/apps/web/app/(app)/team/page.tsx @@ -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 (
@@ -35,6 +38,8 @@ export default async function Team({ searchParams }: { searchParams: Promise<{ e {w.engineer ? t(" Характер добавляется к промпту агента поверх правил Peppa FACTORY и AGENTS.md проекта.") : t(" Характер влияет на то, как агент работает и пишет вам.")} +
+
); } diff --git a/apps/web/app/app.css b/apps/web/app/app.css index fa461e73..f2222df3 100644 --- a/apps/web/app/app.css +++ b/apps/web/app/app.css @@ -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; +} diff --git a/apps/web/components/LiveRefresh.tsx b/apps/web/components/LiveRefresh.tsx index 53f6cbc4..1650ab67 100644 --- a/apps/web/components/LiveRefresh.tsx +++ b/apps/web/components/LiveRefresh.tsx @@ -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("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 (
(((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 { + const ref = useRef(new Map()); + return useMemo(() => { + const prev = ref.current; + const next = new Map(); + 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 = { 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 ( + + {rows.flatMap((row, y) => [...row].map((c, x) => (c === "." ? null : )))} + + ); +} + +/** 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(null); + const [width, setWidth] = useState(720); + const [plus, setPlus] = useState(0); + const stage = useRef(null); + const touch = useRef(false); + const accepted = useRef(view.accepted); + const seen = useRef | 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 | 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(); + }, [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 ( +
+ + {t("Работают: {n}", { n: working })} · {t("Свободны: {n}", { n: data.bench.length })} + + +
+ ); + + 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) => ( + + {a.name} + {" · "} + {a.task ? `${a.task.key} ${a.task.title}` : t("работает")} + + ); + + return ( +
+
+
+ + {t("Игрок")}: {t("вы")} + + Peppa FACTORY + + {tasksWord}: {String(data.accepted).padStart(6, "0")} + +
+ {offline &&

{t("Нет связи — данные на {time}", { time: hhmm(data.at) })}

} + +
+ + + + + {!idle &&
} +
+
+
+ +
+ {idle && ( + + zz + + )} +
+ + {t("вы")} · {t("продакт")} + +
+ {idle ? ( +
+ ) : ( + <> +
+ {t("Ловите {task}!", { task: w.task("acc") })} +
+
+
+ + )} + {plus > 0 && ( + + +1 + + )} + {data.runners.map((a) => { + const key = `r${a.id}`; + const ahead = lead(slots.get(a.id) ?? 0); + return ( + + ); + })} + {data.extra > 0 && ( + + +{data.extra} + + )} +
+ {idle ? ( +

{t("Агенты отдыхают")}

+ ) : ( + <> +

+ {t("Работают: {n}", { n: working })} +
+ {t("Гоняют {task} по кругу, пока не доведут до готового", { task: w.task("acc") })} +

+
+ {data.runners.map((a) => ( + + ■ {a.name} + + ))} +
+ + )} + {awaitingKey && ( + + {t("Жмите «Принять»")} + + )} +
+
+ {data.runners.map((a) => { + const key = `m${a.id}`; + return ( + + ); + })} + {data.extra > 0 && +{data.extra}} +
+
+ + {data.bench.length > 0 && ( +
+

+ {t("Свободны: {n}", { n: data.bench.length })} · {t("наведите, чтобы узнать кличку")} +

+
    + {data.bench.map((a, i) => { + const key = `b${a.id}`; + return ( +
  • + +
  • + ); + })} +
+
+ )} + +
+
+
+ ); +} diff --git a/apps/web/public/fonts/press-start-2p/OFL.txt b/apps/web/public/fonts/press-start-2p/OFL.txt new file mode 100644 index 00000000..5891186b --- /dev/null +++ b/apps/web/public/fonts/press-start-2p/OFL.txt @@ -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. diff --git a/apps/web/public/fonts/press-start-2p/cyrillic-ext.woff2 b/apps/web/public/fonts/press-start-2p/cyrillic-ext.woff2 new file mode 100644 index 00000000..6dcf15a2 Binary files /dev/null and b/apps/web/public/fonts/press-start-2p/cyrillic-ext.woff2 differ diff --git a/apps/web/public/fonts/press-start-2p/cyrillic.woff2 b/apps/web/public/fonts/press-start-2p/cyrillic.woff2 new file mode 100644 index 00000000..3ba14437 Binary files /dev/null and b/apps/web/public/fonts/press-start-2p/cyrillic.woff2 differ diff --git a/apps/web/public/fonts/press-start-2p/latin-ext.woff2 b/apps/web/public/fonts/press-start-2p/latin-ext.woff2 new file mode 100644 index 00000000..0919c5f6 Binary files /dev/null and b/apps/web/public/fonts/press-start-2p/latin-ext.woff2 differ diff --git a/apps/web/public/fonts/press-start-2p/latin.woff2 b/apps/web/public/fonts/press-start-2p/latin.woff2 new file mode 100644 index 00000000..947a9792 Binary files /dev/null and b/apps/web/public/fonts/press-start-2p/latin.woff2 differ diff --git a/apps/web/public/sw.js b/apps/web/public/sw.js index 3893a249..c7618097 100644 --- a/apps/web/public/sw.js +++ b/apps/web/public/sw.js @@ -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 = {}; diff --git a/openspec/changes/archive/2026-11-16-pep-179-team-chase/proposal.md b/openspec/changes/archive/2026-11-16-pep-179-team-chase/proposal.md new file mode 100644 index 00000000..ddc521ab --- /dev/null +++ b/openspec/changes/archive/2026-11-16-pep-179-team-chase/proposal.md @@ -0,0 +1,31 @@ +# PEP-179: «Погоня за задачей» на странице «Команда» + +## Зачем +Раздел «Команда» — длинный список одинаковых карточек «ИИ-агент … свободен»: не видно, что +команда живая и кто чем занят. Нужна картинка над списком: мопс-продакт бросает задачу, +работающие агенты гоняют её по кругу, свободные ждут на скамейке. + +## Что меняется +- `core/team-chase.ts` — `teamChaseView(db, user)`: на трассе агенты с живыми раннерами + (те же данные, что `listAgents`, не больше 8, остальные — «+N»), задача раннера (ключ и + название — только из видимых пользователю проектов), скамейка — свободные агенты в команде, + счётчик — задачи в «Готово» видимых проектов (суперадмину — всех, без удалённых), цвет агента + `agentColor` (тот же тон, что у `AgentBadge`). Скрыть картинку — `settings` + `ui.team-chase:`. +- Веб: `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 и на Главной, изменения карточек агентов. diff --git a/openspec/changes/archive/2026-11-16-pep-179-team-chase/specs/team-page/spec.md b/openspec/changes/archive/2026-11-16-pep-179-team-chase/specs/team-page/spec.md new file mode 100644 index 00000000..f4501a8c --- /dev/null +++ b/openspec/changes/archive/2026-11-16-pep-179-team-chase/specs/team-page/spec.md @@ -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** видит последний состав, строку «Нет связи — данные на ЧЧ:ММ», шрифт и мопса diff --git a/openspec/changes/archive/2026-11-16-pep-179-team-chase/tasks.md b/openspec/changes/archive/2026-11-16-pep-179-team-chase/tasks.md new file mode 100644 index 00000000..f3654bcc --- /dev/null +++ b/openspec/changes/archive/2026-11-16-pep-179-team-chase/tasks.md @@ -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, уменьшенное движение) diff --git a/openspec/specs/team-page/spec.md b/openspec/specs/team-page/spec.md new file mode 100644 index 00000000..42ae1ff5 --- /dev/null +++ b/openspec/specs/team-page/spec.md @@ -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** видит последний состав, строку «Нет связи — данные на ЧЧ:ММ», шрифт и мопса diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index b6843d9d..1bcf59ed 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -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"; diff --git a/packages/core/src/team-chase.ts b/packages/core/src/team-chase.ts new file mode 100644 index 00000000..e734d6ba --- /dev/null +++ b/packages/core/src/team-chase.ts @@ -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, now = new Date()): Promise { + 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(); + 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`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 { + return (await getSetting(db, hiddenKey(userId))) === "hidden"; +} + +export async function setTeamChaseHidden(db: Db, userId: number, hidden: boolean): Promise { + await setSetting(db, hiddenKey(userId), hidden ? "hidden" : "shown"); +} diff --git a/packages/core/src/team.ts b/packages/core/src/team.ts index a551eb3c..37eafeb5 100644 --- a/packages/core/src/team.ts +++ b/packages/core/src/team.ts @@ -32,8 +32,10 @@ export async function listAgents(db: Db): Promise { const rows = await db .select({ a: agents, - busy: sql`(select count(*) from sessions s where s.agent_id = ${agents.id} and s.status not in ('done', 'failed'))`, - runs: sql`(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`(select count(*) from sessions s where s.agent_id = "agents"."id" and s.status not in ('done', 'failed'))`, + runs: sql`(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 void; @@ -30,7 +30,7 @@ const WAKE_DEBOUNCE_MS = 250; export function parseScopes(raw: string | null): LiveScope[] { const out = new Set(); for (const part of (raw ?? "").split(",").map((s) => s.trim()).filter(Boolean)) { - if (part === "home" || part === "runners" || part === "chats") 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; 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; return Object.values(row).join("|"); diff --git a/packages/shared/src/i18n/en/admin.ts b/packages/shared/src/i18n/en/admin.ts index c78fe4fa..06b49666 100644 --- a/packages/shared/src/i18n/en/admin.ts +++ b/packages/shared/src/i18n/en/admin.ts @@ -346,4 +346,20 @@ 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", }; diff --git a/packages/shared/src/i18n/kk/admin.ts b/packages/shared/src/i18n/kk/admin.ts index e2f049ce..67f05865 100644 --- a/packages/shared/src/i18n/kk/admin.ts +++ b/packages/shared/src/i18n/kk/admin.ts @@ -306,4 +306,20 @@ 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} дайын болғанша шеңбер бойымен қуады", + "Жмите «Принять»": "«Қабылдау» басыңыз", + "наведите, чтобы узнать кличку": "лақап атын көру үшін меңзерді апарыңыз", }; diff --git a/packages/testkit/test/team-chase.test.ts b/packages/testkit/test/team-chase.test.ts new file mode 100644 index 00000000..c8a82d03 --- /dev/null +++ b/packages/testkit/test/team-chase.test.ts @@ -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"]); + }); +});