peppa/apps/web/components/LiveRefresh.tsx
Асель 4a80d9dc6b PEP-32/33/37: story page tabs, live agent step feed, SSE live updates instead of 5 s polling
- PEP-37: change hub (runner/live.ts) woken by notify() (new 'web' subscriber) and
  PRAGMA data_version; per-scope fingerprints; GET /api/live SSE (no-transform, ping 15 s);
  LiveRefresh replaces AutoRefresh with a connection indicator and polling fallback
- PEP-33: async PostToolUse/PostToolUseFailure hook -> 'step' events (last 200 per
  session), AgentSteps live feed on the story page and runner panel, tasks.md progress
  on board cards and the story header
- PEP-32: story page header + tabs Proposal/Design/Specs/Tasks/Comments/Tests/Merge
  request/Activity, safe Markdown renderer, PM comments visible in get_task, edit
  title/description/epic, accept-and-merge (acceptStory)
- OpenSpec changes archived; specs live-updates, agent-steps, story-page

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 05:59:15 +05:00

126 lines
4.4 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"use client";
import { useRouter } from "next/navigation";
import { useEffect, useRef, useState } from "react";
import { cn } from "@/lib/utils";
type Mode = "connecting" | "live" | "reconnecting" | "polling";
const LABEL: Record<Mode, string> = {
connecting: "подключение…",
live: "в реальном времени",
reconnecting: "переподключение…",
polling: "опрос раз в 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 }: { scope: string; pollMs?: number }) {
const router = useRouter();
const [mode, setMode] = useState<Mode>("connecting");
const pending = useRef(false);
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);
};
const onVisible = () => document.visibilityState === "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");
};
};
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]);
return (
<div
role="status"
aria-live="polite"
title={mode === "polling" ? "Канал событий недоступен — страница обновляется по таймеру" : "Страница обновляется сама, когда что-то меняется"}
className="pointer-events-none fixed right-3 bottom-3 z-40 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])} />
{LABEL[mode]}
</div>
);
}