peppa/apps/web/public/sw.js
Асель 20bb0d25a8 PEP-179: «Погоня за задачей» на странице «Команда»
Над списком агентов — пиксельный мопс бросает задачу, работающие агенты гоняют её по
трассе (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>
2026-11-16 22:41:46 +05:00

110 lines
4.1 KiB
JavaScript

// 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? }.
//
// 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 = {};
try {
p = event.data ? event.data.json() : {};
} catch {
p = { title: "Peppa FACTORY", body: event.data ? event.data.text() : "" };
}
const shown = self.registration.showNotification(p.title || "Peppa FACTORY", {
body: p.body || "",
tag: p.tag,
renotify: Boolean(p.tag),
silent: p.sound === false,
icon: "/icon.svg",
badge: "/icon.svg",
data: { url: p.url || "/" },
});
const badge = typeof p.count === "number" && self.navigator.setAppBadge ? self.navigator.setAppBadge(p.count).catch(() => {}) : Promise.resolve();
event.waitUntil(Promise.all([shown, badge]));
});
self.addEventListener("notificationclick", (event) => {
event.notification.close();
const url = new URL((event.notification.data && event.notification.data.url) || "/", self.location.origin).href;
event.waitUntil(
(async () => {
const tabs = await self.clients.matchAll({ type: "window", includeUncontrolled: true });
const same = tabs.find((c) => c.url === url) || tabs.find((c) => new URL(c.url).origin === self.location.origin);
if (same) {
await same.focus();
if (same.url !== url && "navigate" in same) await same.navigate(url).catch(() => {});
return;
}
await self.clients.openWindow(url);
})(),
);
});