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/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 (
`. +- Веб: `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/pep-179-team-chase/specs/team-page/spec.md b/openspec/changes/pep-179-team-chase/specs/team-page/spec.md new file mode 100644 index 00000000..f4501a8c --- /dev/null +++ b/openspec/changes/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/pep-179-team-chase/tasks.md b/openspec/changes/pep-179-team-chase/tasks.md new file mode 100644 index 00000000..f3654bcc --- /dev/null +++ b/openspec/changes/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/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..05117382 --- /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, 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, 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/runner/src/live.ts b/packages/runner/src/live.ts index 2fbed6fa..4a67a8f7 100644 --- a/packages/runner/src/live.ts +++ b/packages/runner/src/live.ts @@ -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(); 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("|");