PEP-114: a page opened before the site was updated asks to be reloaded

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Асель 2026-11-15 15:58:52 +05:00
parent e612f09b13
commit c739e877f5
7 changed files with 84 additions and 1 deletions

View File

@ -7,6 +7,8 @@ import { Sidebar } from "@/components/Sidebar";
import { AttentionBadge } from "@/components/AttentionBadge";
import { CommandPalette } from "@/components/CommandPalette";
import { UsageStrip } from "@/components/Accounting";
import { VersionWatch } from "@/components/VersionWatch";
import { bootId } from "@/lib/boot";
export const dynamic = "force-dynamic";
@ -23,6 +25,7 @@ export default async function AppLayout({ children }: { children: ReactNode }) {
<AttentionBadge count={counts.questions + counts.waitingRunners} sound={sound} />
<Sidebar login={user.login} avatarUrl={user.avatarUrl} counts={counts} superadmin={superadmin} />
<div className="flex min-w-0 flex-col pb-16 md:pb-0">
<VersionWatch boot={bootId()} />
<UsageStrip accounts={accounts} admin={superadmin} />
{children}
</div>

View File

@ -1,4 +1,5 @@
import { healthReport } from "@peppa/core";
import { bootId } from "@/lib/boot";
import { db } from "@/lib/db";
export const dynamic = "force-dynamic";
@ -9,5 +10,6 @@ export async function GET() {
version: process.env.NEXT_PUBLIC_PEPPA_VERSION,
commit: process.env.NEXT_PUBLIC_PEPPA_COMMIT || null,
});
return Response.json(r, { status: r.ok ? 200 : 503, headers: { "Cache-Control": "no-store" } });
// PEP-114: `boot` changes when the web process restarts — open pages compare it with their own.
return Response.json({ ...r, boot: bootId() }, { status: r.ok ? 200 : 503, headers: { "Cache-Control": "no-store" } });
}

View File

@ -0,0 +1,47 @@
"use client";
import { useEffect, useState } from "react";
import { RefreshCw } from "lucide-react";
/**
* PEP-114: a page opened before the site was updated may press buttons the new server doesn't
* know — nothing happens and nothing is said. This watches the server's boot id (once a minute
* and when the tab comes back) and asks to reload when it changed. Never reloads by itself: the
* person may be in the middle of typing.
*/
export function VersionWatch({ boot }: { boot: string }) {
const [stale, setStale] = useState(false);
useEffect(() => {
let alive = true;
const check = async () => {
try {
const r = await fetch("/api/health", { cache: "no-store" });
const now = ((await r.json()) as { boot?: string }).boot;
if (alive && now && now !== boot) setStale(true);
} catch {
/* offline or restarting: the next check will tell */
}
};
const t = setInterval(check, 60_000);
const onVisible = () => document.visibilityState === "visible" && void check();
document.addEventListener("visibilitychange", onVisible);
window.addEventListener("focus", onVisible);
return () => {
alive = false;
clearInterval(t);
document.removeEventListener("visibilitychange", onVisible);
window.removeEventListener("focus", onVisible);
};
}, [boot]);
if (!stale) return null;
return (
<div role="alert" className="sticky top-0 z-40 flex flex-wrap items-center justify-center gap-3 border-b border-primary/50 bg-primary/15 px-4 py-2 text-sm">
<span>Peppa FACTORY обновилась. Обновите страницу — иначе кнопки на ней могут не сработать.</span>
<button type="button" onClick={() => window.location.reload()} className="inline-flex items-center gap-1.5 rounded-md bg-primary px-3 py-1 font-medium text-primary-foreground">
<RefreshCw className="size-3.5" /> Обновить страницу
</button>
</div>
);
}

9
apps/web/lib/boot.ts Normal file
View File

@ -0,0 +1,9 @@
// PEP-114: one id per start of the web process (shared by pages and route handlers through
// globalThis). A page keeps the id it was rendered with; when /api/health reports another one,
// the server was restarted with new code and the page's buttons may no longer be known to it.
const g = globalThis as typeof globalThis & { __peppaBoot?: string };
export function bootId(): string {
g.__peppaBoot ??= `${process.env.NEXT_PUBLIC_PEPPA_COMMIT ?? "dev"}-${Date.now().toString(36)}`;
return g.__peppaBoot;
}

View File

@ -0,0 +1,8 @@
# Proposal: PEP-114 — открытая страница просит обновиться после обновления сайта
## Why
PM нажала «Оставить комментарий» на странице, открытой до перезапуска веба: ничего не произошло и ошибки не было.
## What Changes
- `lib/boot.ts`: id запуска веб-процесса (`globalThis`), `/api/health` отдаёт его в поле `boot`.
- `VersionWatch` в layout: раз в минуту и при возврате на вкладку сверяет `boot`; при расхождении — плашка «Peppa FACTORY обновилась. Обновите страницу» с кнопкой. Сама страницу не перезагружает (человек может печатать).

View File

@ -0,0 +1,12 @@
## ADDED Requirements
### Requirement: Устаревшая страница сообщает о себе
Веб SHALL показывать на странице, открытой до перезапуска сервера, просьбу обновить её.
#### Scenario: Сайт обновили при открытой странице
- **WHEN** веб перезапущен, а вкладка пользователя открыта раньше
- **THEN** в течение минуты (или при возврате на вкладку) наверху появляется плашка с кнопкой «Обновить страницу»
#### Scenario: Сайт не менялся
- **WHEN** сервер тот же
- **THEN** плашки нет

View File

@ -0,0 +1,2 @@
- [x] 1.1 boot id, поле в /api/health, VersionWatch
- [x] 1.2 проверка в браузере (тот же запуск — плашки нет; другой — есть)