PEP-179: WIP from previous session

This commit is contained in:
Асель 2026-11-16 21:40:03 +05:00
parent 9fc48aef73
commit c24794c2d7
14 changed files with 1030 additions and 9 deletions

View File

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

View File

@ -34,7 +34,7 @@ function busy(): boolean {
* something there changed (router.refresh keeps client state and typed text). Falls back to
* polling every 5 s when the stream can't be opened; shows the connection state.
*/
export function LiveRefresh({ scope, pollMs = 5000 }: { scope: string; pollMs?: number }) {
export function LiveRefresh({ scope, pollMs = 5000, pauseHidden = false }: { scope: string; pollMs?: number; pauseHidden?: boolean }) {
const router = useRouter();
const [mode, setMode] = useState<Mode>("connecting");
const pending = useRef(false);
@ -64,7 +64,29 @@ export function LiveRefresh({ scope, pollMs = 5000 }: { scope: string; pollMs?:
pending.current = true;
if (!flushTimer) flushTimer = setTimeout(flush, 300);
};
const onVisible = () => document.visibilityState === "visible" && pending.current && request();
// PEP-179 `pauseHidden`: a hidden tab or a minimised app keeps no stream open (battery);
// back in view — reconnect and re-read at once.
const pause = () => {
es?.close();
es = null;
if (poll) clearInterval(poll);
poll = null;
if (retry) clearTimeout(retry);
retry = null;
};
const onVisible = () => {
const visible = document.visibilityState === "visible";
if (pauseHidden) {
if (!visible) return pause();
if (!es && !poll) {
fails = 0;
connect();
pending.current = true;
return request();
}
}
if (visible && pending.current) request();
};
const startPolling = () => {
if (poll) return;
@ -102,7 +124,7 @@ export function LiveRefresh({ scope, pollMs = 5000 }: { scope: string; pollMs?:
};
};
connect();
if (!pauseHidden || document.visibilityState === "visible") connect();
document.addEventListener("visibilitychange", onVisible);
return () => {
closed = true;
@ -112,7 +134,7 @@ export function LiveRefresh({ scope, pollMs = 5000 }: { scope: string; pollMs?:
if (flushTimer) clearTimeout(flushTimer);
document.removeEventListener("visibilitychange", onVisible);
};
}, [router, scope, pollMs]);
}, [router, scope, pollMs, pauseHidden]);
return (
<div

View File

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

View File

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

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -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("|");