Над списком агентов — пиксельный мопс бросает задачу, работающие агенты гоняют её по
трассе (CSS offset-path), свободные ждут на скамейке. Данные — core teamChaseView: трасса
= агенты с живым раннером (≤8, остальные «+N»), скамейка — свободные в команде, счётчик —
задачи в «Готово» видимых проектов; «+1» — только при росте счётчика, «Жмите «Принять»» —
только при задачах на приёмке. Живая область team, LiveRefresh pauseHidden. Подсказки,
касание (первое — подсказка, второе — переход), клавиатура, прокрутка к карточке,
«Скрыть» с запоминанием, уменьшенное движение и экономия батареи, < 420 px — строка значков.
PWA: свой шрифт Press Start 2P (OFL), service worker кэширует оболочку и /team, без сети —
последний состав и «Нет связи — данные на ЧЧ:ММ».
Заодно: listAgents и выбор свободного агента считали занятость по id сессии вместо id агента
(drizzle рендерит ${agents.id} в подзапросе голым "id").
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
151 lines
5.2 KiB
TypeScript
151 lines
5.2 KiB
TypeScript
"use client";
|
||
|
||
import { useRouter } from "next/navigation";
|
||
import { useEffect, useRef, useState } from "react";
|
||
import { cn } from "@/lib/utils";
|
||
import { useT } from "@/components/I18n";
|
||
import { m } from "@peppa/shared/i18n";
|
||
|
||
type Mode = "connecting" | "live" | "reconnecting" | "polling";
|
||
|
||
const LABEL: Record<Mode, string> = {
|
||
connecting: m("подключение…"),
|
||
live: m("в реальном времени"),
|
||
reconnecting: m("переподключение…"),
|
||
polling: m("опрос раз в 5 с"),
|
||
};
|
||
const DOT: Record<Mode, string> = {
|
||
connecting: "bg-muted-foreground",
|
||
live: "bg-ok",
|
||
reconnecting: "bg-warn animate-pulse",
|
||
polling: "bg-warn",
|
||
};
|
||
|
||
/** True while the user is typing or left an unsent draft: a refresh must wait. */
|
||
function busy(): boolean {
|
||
const el = document.activeElement;
|
||
const typing = el instanceof HTMLTextAreaElement || (el instanceof HTMLInputElement && ["text", "search", ""].includes(el.type));
|
||
const draft = [...document.querySelectorAll<HTMLTextAreaElement | HTMLInputElement>("textarea, input[type=text]")].some((i) => i.value !== i.defaultValue);
|
||
return typing || draft;
|
||
}
|
||
|
||
/**
|
||
* Live page (PEP-37): listens to /api/live for its scope and re-renders server data when
|
||
* 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, pauseHidden = false }: { scope: string; pollMs?: number; pauseHidden?: boolean }) {
|
||
const router = useRouter();
|
||
const [mode, setMode] = useState<Mode>("connecting");
|
||
const pending = useRef(false);
|
||
const t = useT();
|
||
|
||
useEffect(() => {
|
||
let closed = false;
|
||
let es: EventSource | null = null;
|
||
let fails = 0;
|
||
let opened = false;
|
||
let poll: ReturnType<typeof setInterval> | null = null;
|
||
let retry: ReturnType<typeof setTimeout> | null = null;
|
||
let flushTimer: ReturnType<typeof setTimeout> | null = null;
|
||
|
||
// Debounced refresh that waits for the user to finish typing.
|
||
const flush = () => {
|
||
flushTimer = null;
|
||
if (closed || !pending.current) return;
|
||
if (busy() || document.visibilityState !== "visible") {
|
||
flushTimer = setTimeout(flush, 2000);
|
||
return;
|
||
}
|
||
pending.current = false;
|
||
router.refresh();
|
||
};
|
||
const request = () => {
|
||
pending.current = true;
|
||
if (!flushTimer) flushTimer = setTimeout(flush, 300);
|
||
};
|
||
// 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;
|
||
setMode("polling");
|
||
poll = setInterval(request, pollMs);
|
||
// Try the stream again now and then.
|
||
retry = setTimeout(() => {
|
||
if (poll) clearInterval(poll);
|
||
poll = null;
|
||
fails = 0;
|
||
connect();
|
||
}, 30_000);
|
||
};
|
||
|
||
const connect = () => {
|
||
if (closed) return;
|
||
if (typeof EventSource === "undefined") return startPolling();
|
||
es = new EventSource(`/api/live?scope=${encodeURIComponent(scope)}`);
|
||
es.addEventListener("ready", () => {
|
||
// Back after a drop: changes may have been missed.
|
||
if (opened) request();
|
||
opened = true;
|
||
fails = 0;
|
||
setMode("live");
|
||
});
|
||
es.addEventListener("change", request);
|
||
es.onerror = () => {
|
||
if (closed) return;
|
||
fails++;
|
||
if (fails >= 3 || es?.readyState === EventSource.CLOSED) {
|
||
es?.close();
|
||
es = null;
|
||
startPolling();
|
||
} else setMode("reconnecting");
|
||
};
|
||
};
|
||
|
||
if (!pauseHidden || document.visibilityState === "visible") connect();
|
||
document.addEventListener("visibilitychange", onVisible);
|
||
return () => {
|
||
closed = true;
|
||
es?.close();
|
||
if (poll) clearInterval(poll);
|
||
if (retry) clearTimeout(retry);
|
||
if (flushTimer) clearTimeout(flushTimer);
|
||
document.removeEventListener("visibilitychange", onVisible);
|
||
};
|
||
}, [router, scope, pollMs, pauseHidden]);
|
||
|
||
return (
|
||
<div
|
||
role="status"
|
||
aria-live="polite"
|
||
title={mode === "polling" ? t("Канал событий недоступен — страница обновляется по таймеру") : t("Страница обновляется сама, когда что-то меняется")}
|
||
className="pointer-events-none fixed right-3 bottom-[calc(4.25rem+env(safe-area-inset-bottom))] z-40 md:bottom-3 flex items-center gap-1.5 rounded-full border bg-background/90 px-2.5 py-1 font-mono text-[11px] text-muted-foreground shadow-sm backdrop-blur"
|
||
>
|
||
<span className={cn("size-1.5 rounded-full", DOT[mode])} />
|
||
{t(LABEL[mode])}
|
||
</div>
|
||
);
|
||
}
|