PEP-225: клиент — одно соединение на вкладку, острова доски и статуса, без опросов; тесты канала

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
peppa-bot 2026-11-20 21:23:35 +05:00
parent 0d86b801ee
commit 33a830fe07
27 changed files with 904 additions and 268 deletions

View File

@ -225,7 +225,8 @@ export default async function ChatPage({ params, searchParams }: { params: Promi
return (
<Workspace aside={null} wide>
<LiveRefresh scope="chats" indicator={false} />
{/* PEP-225: a project chat re-renders only for its own new messages; the master feed gathers every project. */}
<LiveRefresh scope="chats" indicator={false} chatId={master ? undefined : chat.id} />
<Flash error={error} />
<h1 className="sr-only">{t("Чаты")}</h1>

View File

@ -4,7 +4,7 @@ import { notFound } from "next/navigation";
import { Activity, Pause, Play, Trash2 } from "lucide-react";
import { describeTarget, getMonitor, isSuperadmin, monitorChecks, monitorIncidents, monitorView } from "@peppa/core";
import { loadEnv } from "@peppa/shared";
import { AutoRefresh } from "@/components/AutoRefresh";
import { LiveRefresh } from "@/components/LiveRefresh";
import { Hidden } from "@/components/cards";
import { CheckStrip, KIND_LABEL, MonitorFields, pct, StateBadge } from "@/components/Observability";
import { ago, Disclosure, Empty, Flash, PageHeader, Section } from "@/components/common";
@ -36,7 +36,7 @@ export default async function MonitorPage({ params, searchParams }: { params: Pr
const web = loadEnv().PEPPA_WEB_URL;
return (
<Workspace>
<AutoRefresh everyMs={15_000} />
<LiveRefresh scope="observe" />
<div className="max-w-4xl">
<Flash error={error} />
<PageHeader

View File

@ -4,7 +4,7 @@ import { notFound } from "next/navigation";
import { Activity, Pause, Play, Plus } from "lucide-react";
import { describeTarget, egovLoginSummary, isSuperadmin, listMonitorViews } from "@peppa/core";
import { loadEnv } from "@peppa/shared";
import { AutoRefresh } from "@/components/AutoRefresh";
import { LiveRefresh } from "@/components/LiveRefresh";
import { Hidden } from "@/components/cards";
import { CheckStrip, KIND_LABEL, MonitorFields, pct, StateBadge } from "@/components/Observability";
import { ago, Disclosure, Empty, Flash, PageHeader, Section } from "@/components/common";
@ -35,7 +35,7 @@ export default async function Observability({ searchParams }: { searchParams: Pr
const degraded = monitors.filter((m) => !m.paused && m.state === "degraded").length;
return (
<Workspace>
<AutoRefresh everyMs={15_000} />
<LiveRefresh scope="observe" />
<div className="max-w-4xl">
<Flash error={error} />
<PageHeader title={<><Activity className="mr-1 inline size-5 text-primary" />{t("Observability")}</>}>

View File

@ -4,7 +4,7 @@ import { getQuestion, isSuperadmin, listSubscriptions, OPENCODE_KEY_ENV, PROVIDE
import { pendingLogin, pollCodexLogin, type PendingLogin, backfillCodexAccounts, openSubscriptionRequests } from "@peppa/runner";
import { answerQuestion } from "@/app/(app)/actions";
import { LocalTime } from "@/components/LocalTime";
import { AutoRefresh } from "@/components/AutoRefresh";
import { LiveRefresh } from "@/components/LiveRefresh";
import { PoolCapacity, PoolSubscriptions, PoolSummary, PoolSwitches } from "@/components/PoolSubscriptions";
import { Hidden } from "@/components/cards";
import { ago, Disclosure, Empty, Flash, Notice, PageHeader, Section } from "@/components/common";
@ -296,7 +296,8 @@ export default async function Subscriptions({ searchParams }: { searchParams: Pr
return (
<Workspace>
{[...logins.values()].some((l) => l.kind === "codex") && <AutoRefresh everyMs={3000} />}
<LiveRefresh scope="subs" />
{[...logins.entries()].filter(([, l]) => l.kind === "codex").map(([id]) => <LiveRefresh key={id} scope={`login:${id}`} indicator={false} />)}
<div className="max-w-3xl">
<Flash error={error} />
<PageHeader title={<><KeyRound className="mr-1 inline size-5 text-primary" />{t("Подписки")}</>}>

View File

@ -55,6 +55,7 @@ import { PanelSection } from "@/components/ActivityAside";
import { Hidden, SessionCard } from "@/components/cards";
import { ago, Disclosure, Flash, PageHeader, Section, StatusBadge } from "@/components/common";
import { LiveRefresh } from "@/components/LiveRefresh";
import { LiveTaskStatus } from "@/components/LiveTaskStatus";
import { TaskRunnerSettings } from "@/components/Runners";
import { TaskAgentModel } from "@/components/AgentModel";
import { Button } from "@/components/ui/button";
@ -431,7 +432,7 @@ export default async function StoryPage({ params, searchParams }: { params: Prom
}
title={
<>
<span className="font-mono text-primary">{ref.key}</span> {task.title} {engineer && <StatusBadge status={task.status} />}
<span className="font-mono text-primary">{ref.key}</span> {task.title} {engineer && <LiveTaskStatus taskId={task.id} status={task.status} />}
{pendingAccept && <Badge variant="ok" className="ml-1.5 align-middle whitespace-normal">{t.text(PENDING_ACCEPT_LABEL)}</Badge>}
{engineer && delayed && <Badge variant="muted" className="ml-1.5 align-middle whitespace-normal">{t.text(delayLine ?? PLATFORM_DELAY_LABEL)}</Badge>}
{task.archivedAt && <Badge variant="muted" className="ml-1.5 align-middle">{t("в архиве")}</Badge>}

View File

@ -1,5 +1,5 @@
// Live updates (PEP-37): SSE of `change` (a watched scope changed — refresh) and `step`
// (an agent's tool call, PEP-33) events. ?scope=home | runners | project:<id> | task:<id> | steps:<sessionId>, comma-separated.
// Live updates (PEP-37): SSE of `change` (a watched scope changed), `step` (an agent's tool call,
// PEP-33) and `data` events — since PEP-225 the fallback of the tab's WebSocket /api/ws. ?scope=home | runners | project:<id> | task:<id> | steps:<sessionId>, comma-separated.
import { LiveError, liveSse, parseScopes } from "@peppa/runner";
import { currentUser } from "@/lib/auth";
import { db } from "@/lib/db";
@ -14,7 +14,10 @@ export async function GET(req: Request) {
const user = await currentUser();
if (!user) return fail(401, m("Нужен вход"));
try {
return await liveSse(db, user, parseScopes(new URL(req.url).searchParams.get("scope")), req.signal);
const q = new URL(req.url).searchParams;
// PEP-225: `since.<scope>=<version>` — what the tab saw before a drop (fallback of the WebSocket).
const since = Object.fromEntries([...q].filter(([k]) => k.startsWith("since.")).map(([k, v]) => [k.slice(6), v]));
return await liveSse(db, user, parseScopes(q.get("scope")), req.signal, { since });
} catch (e) {
if (e instanceof LiveError) return fail(e.status, e.message);
console.error("live:", e);

View File

@ -4,6 +4,7 @@ import { useEffect, useState } from "react";
import { Bot, FilePen, FileText, FlaskConical, Globe, Plug, Search, SquareTerminal, Wrench, type LucideIcon } from "lucide-react";
import type { StepKind, StepView } from "@peppa/core";
import { cn } from "@/lib/utils";
import { useLive } from "@/lib/live";
import { useT } from "@/components/I18n";
import { m, type Translator } from "@peppa/shared/i18n";
@ -52,22 +53,22 @@ export function AgentSteps({ sessionId, initial, live, hooks = true, plain = fal
useEffect(() => setSteps((cur) => merge(initial, cur)), [initial]);
// The «N с назад» clock only (no data is fetched on it).
useEffect(() => {
const timer = setInterval(() => setNow(Date.now()), 10_000);
if (!live || typeof EventSource === "undefined") return () => clearInterval(timer);
const es = new EventSource(`/api/live?scope=steps:${sessionId}`);
es.addEventListener("step", (e) => {
try {
const { step } = JSON.parse((e as MessageEvent).data) as { step: StepView };
setSteps((cur) => merge([step], cur));
setNow(Date.now());
} catch {}
});
return () => {
clearInterval(timer);
es.close();
};
}, [sessionId, live]);
return () => clearInterval(timer);
}, []);
// PEP-225: new steps over the tab's live channel; a hidden tab drops them and catches up on return.
useLive(
live ? `steps:${sessionId}` : null,
(e) => {
if (e.type !== "step") return;
setSteps((cur) => merge([e.step as unknown as StepView], cur));
setNow(Date.now());
},
{ heavy: true },
);
if (!steps.length)
return (

View File

@ -1,6 +1,7 @@
"use client";
import { useEffect, useRef } from "react";
import { useLive } from "@/lib/live";
const PREFIX = /^\(\d+\) /;
@ -25,53 +26,45 @@ function chime() {
}
/**
* «(N) …» in the tab title and the app badge (PEP-55): what waits for the user. Polls
* /api/attention; a growing count plays a chime if sound is on in the settings.
* «(N) …» in the tab title and the app badge (PEP-55): what waits for the user. The count comes
* from the live channel (`attention`, PEP-225) the moment it changes; a growing count plays a
* chime if sound is on in the settings.
*/
export function AttentionBadge({ count: initial, sound: initialSound, everyMs = 20_000 }: { count: number; sound: boolean; everyMs?: number }) {
export function AttentionBadge({ count: initial, sound: initialSound }: { count: number; sound: boolean }) {
const count = useRef(initial);
const sound = useRef(initialSound);
const apply = () => {
const base = document.title.replace(PREFIX, "");
const want = count.current > 0 ? `(${count.current}) ${base}` : base;
if (document.title !== want) document.title = want;
const nav = navigator as Navigator & { setAppBadge?: (n?: number) => Promise<void>; clearAppBadge?: () => Promise<void> };
if (count.current > 0) nav.setAppBadge?.(count.current).catch(() => {});
else nav.clearAppBadge?.().catch(() => {});
};
useEffect(() => {
const apply = () => {
const base = document.title.replace(PREFIX, "");
const want = count.current > 0 ? `(${count.current}) ${base}` : base;
if (document.title !== want) document.title = want;
const nav = navigator as Navigator & { setAppBadge?: (n?: number) => Promise<void>; clearAppBadge?: () => Promise<void> };
if (count.current > 0) nav.setAppBadge?.(count.current).catch(() => {});
else nav.clearAppBadge?.().catch(() => {});
};
apply();
// Next sets the title on navigation: put the counter back.
const titleObserver = new MutationObserver(apply);
titleObserver.observe(document.head, { subtree: true, childList: true, characterData: true });
return () => titleObserver.disconnect();
}, []);
const poll = async () => {
if (document.visibilityState !== "visible") return;
try {
const r = await fetch("/api/attention", { cache: "no-store" });
if (!r.ok) return;
const j = (await r.json()) as { count: number; sound: boolean };
sound.current = j.sound;
if (j.count > count.current && sound.current) chime();
count.current = j.count;
apply();
} catch {}
};
const id = setInterval(poll, everyMs);
document.addEventListener("visibilitychange", poll);
return () => {
clearInterval(id);
titleObserver.disconnect();
document.removeEventListener("visibilitychange", poll);
};
}, [everyMs]);
useLive("attention", (e) => {
if (e.type !== "data") return;
const d = e.data as { count: number; sound: boolean };
sound.current = d.sound;
if (d.count > count.current && sound.current) chime();
count.current = d.count;
apply();
});
// A server re-render (router.refresh) brings a fresh count too.
// A server re-render brings a fresh count too.
useEffect(() => {
if (initial > count.current && sound.current) chime();
count.current = initial;
document.title = initial > 0 ? `(${initial}) ${document.title.replace(PREFIX, "")}` : document.title.replace(PREFIX, "");
apply();
}, [initial]);
return null;

View File

@ -1,19 +0,0 @@
"use client";
import { useRouter } from "next/navigation";
import { useEffect } from "react";
/** Re-renders server data every few seconds, unless the user is typing (or left an unsent draft). */
export function AutoRefresh({ everyMs = 5000 }: { everyMs?: number }) {
const router = useRouter();
useEffect(() => {
const id = setInterval(() => {
const el = document.activeElement;
const typing = el instanceof HTMLTextAreaElement || (el instanceof HTMLInputElement && el.type === "text");
const draft = [...document.querySelectorAll<HTMLTextAreaElement | HTMLInputElement>("textarea, input[type=text]")].some((i) => i.value !== i.defaultValue);
if (!typing && !draft && document.visibilityState === "visible") router.refresh();
}, everyMs);
return () => clearInterval(id);
}, [router, everyMs]);
return null;
}

View File

@ -4,6 +4,7 @@ import { useWords } from "@/components/Words";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useEffect, useState, useTransition } from "react";
import { useLiveIsland } from "@/lib/live";
import { ChevronDown, ChevronRight, ChevronsDown, ChevronsUp, Lock } from "lucide-react";
import { moveTaskCard, proposalAction } from "@/app/(app)/actions";
import { reorderTaskInline } from "@/app/(app)/board-actions";
@ -95,7 +96,25 @@ const NEXT: Partial<Record<Column, { to: Column; label: string }>> = {
* starts/stops agents; drag it onto a card of its own column to change the order (= priority
* for the dispatcher, PEP-34). «Готово» can be collapsed (remembered in the browser).
*/
export function Board({ cards, back }: { cards: Card[]; back: string }) {
export function Board({ cards: server, back }: { cards: Card[]; back: string }) {
// PEP-225: status and title changes from the live channel apply in place — a card moves to the
// column of its new status at once; fresh server data (a re-render) replaces the patches.
const [patches, setPatches] = useState<Map<number, Pick<Card, "status" | "title" | "column">>>(() => new Map());
useEffect(() => setPatches(new Map()), [server]);
const cards = patches.size ? server.map((c) => (c.id != null && patches.has(c.id) ? { ...c, ...patches.get(c.id)! } : c)) : server;
useLiveIsland((e) => {
if (!e.tasks?.length) return [];
const byId = new Map(server.map((c) => [c.id, c]));
const next: Array<[number, Pick<Card, "status" | "title" | "column">]> = [];
let all = true;
for (const r of e.tasks) {
// A new story, one outside the epic filter, or a change of its epic/order/«Предложено» — the server re-renders.
if (!byId.has(r.id) || r.other) all = false;
else next.push([r.id, { status: r.status, title: r.title, column: r.column }]);
}
if (next.length) setPatches((cur) => new Map([...cur, ...next]));
return all ? ["t"] : [];
});
const w = useWords();
const router = useRouter();
const t = useT();

View File

@ -1,24 +1,23 @@
"use client";
import { useRouter } from "next/navigation";
import { useEffect, useRef, useState } from "react";
import { useEffect, useRef } from "react";
import { cn } from "@/lib/utils";
import { useT } from "@/components/I18n";
import { applyIslands, useLive, useLiveMode, type LiveEvent, type LiveMode } from "@/lib/live";
import { m } from "@peppa/shared/i18n";
type Mode = "connecting" | "live" | "reconnecting" | "polling";
const LABEL: Record<Mode, string> = {
const LABEL: Record<LiveMode, string> = {
connecting: m("подключение…"),
live: m("в реальном времени"),
reconnecting: m("переподключение…"),
polling: m("опрос раз в 5 с"),
offline: m("нет связи — пробуем снова"),
};
const DOT: Record<Mode, string> = {
const DOT: Record<LiveMode, string> = {
connecting: "bg-muted-foreground",
live: "bg-ok",
reconnecting: "bg-warn animate-pulse",
polling: "bg-warn",
offline: "bg-destructive",
};
/** True while the user is typing or left an unsent draft: a refresh must wait. */
@ -29,129 +28,93 @@ function busy(): boolean {
return typing || draft;
}
/** PEP-215: at most one re-render per tab in this many ms, however many changes the stream reports. */
/** PEP-215: at most one re-render per tab in this many ms, however many changes the channel reports. */
export const MIN_REFRESH_GAP_MS = 4000;
/** PEP-225: parts of the `chats` scope a chat page cares about besides messages of its own chat. */
const CHAT_PAGE_PARTS = new Set(["q", "tg", "*"]);
/**
* 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.
* Live page (PEP-37, PEP-225): watches its scope over the tab's channel. A change the page's
* islands apply in place (board cards, the attention counter…) needs nothing more; anything else
* re-renders server data (router.refresh keeps client state and typed text) — at most once per
* 4 s, never while the person types. Shows the connection state.
*/
export function LiveRefresh({ scope, pollMs = 5000, pauseHidden = false, indicator = true }: { scope: string; pollMs?: number; pauseHidden?: boolean; /** PEP-207: the chat hides the corner pill — it sits over the message field. */ indicator?: boolean }) {
export function LiveRefresh({
scope,
pauseHidden = false,
indicator = true,
chatId,
}: {
scope: string;
/** PEP-179: a hidden tab drops the scope (battery) and catches up when back in view. */
pauseHidden?: boolean;
/** PEP-207: the chat hides the corner pill — it sits over the message field. */
indicator?: boolean;
/** PEP-225: a chat page re-renders only for new messages of this chat (and answered questions). */
chatId?: number;
}) {
const router = useRouter();
const [mode, setMode] = useState<Mode>("connecting");
const pending = useRef(false);
const mode = useLiveMode();
const t = useT();
const state = useRef({ pending: false, timer: null as ReturnType<typeof setTimeout> | null, last: 0 });
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;
let lastRefresh = 0;
// 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;
}
const wait = lastRefresh + MIN_REFRESH_GAP_MS - Date.now();
if (wait > 0) {
flushTimer = setTimeout(flush, wait);
return;
}
pending.current = false;
lastRefresh = Date.now();
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);
const s = state.current;
return () => {
closed = true;
es?.close();
if (poll) clearInterval(poll);
if (retry) clearTimeout(retry);
if (flushTimer) clearTimeout(flushTimer);
document.removeEventListener("visibilitychange", onVisible);
if (s.timer) clearTimeout(s.timer);
s.timer = null;
};
}, [router, scope, pollMs, pauseHidden]);
}, []);
const flush = () => {
const s = state.current;
s.timer = null;
if (!s.pending) return;
if (busy() || document.visibilityState !== "visible") {
s.timer = setTimeout(flush, 2000);
return;
}
const wait = s.last + MIN_REFRESH_GAP_MS - Date.now();
if (wait > 0) {
s.timer = setTimeout(flush, wait);
return;
}
s.pending = false;
s.last = Date.now();
router.refresh();
};
const request = () => {
const s = state.current;
s.pending = true;
if (!s.timer) s.timer = setTimeout(flush, 300);
};
useLive(
scope,
(e: LiveEvent) => {
if (e.type !== "change") return;
let parts = e.parts;
if (chatId != null) {
// Messages of other chats and events not yet projected into this chat don't concern it.
const mine = e.chats?.includes(chatId) ?? false;
parts = parts.filter((p) => (p === "m" ? mine : CHAT_PAGE_PARTS.has(p)));
if (!parts.length) return;
}
const applied = applyIslands(e);
if (parts.every((p) => applied.has(p))) return;
request();
},
{ heavy: pauseHidden },
);
if (!indicator) return null;
return (
<div
role="status"
aria-live="polite"
title={mode === "polling" ? t("Канал событий недоступен — страница обновляется по таймеру") : t("Страница обновляется сама, когда что-то меняется")}
data-live-mode={mode}
title={mode === "offline" ? t("Нет связи с Peppa FACTORY — страница обновится, когда связь вернётся") : 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])} />

View File

@ -0,0 +1,25 @@
"use client";
// PEP-225: the story's status badge, updated in place from the live channel (`task:<id>` rows) —
// the rest of the page follows with the next server re-render.
import { useState, useEffect } from "react";
import { Badge } from "@/components/ui/badge";
import { useT } from "@/components/I18n";
import { useLiveIsland } from "@/lib/live";
import { TASK_STATUS } from "@/lib/status";
export function LiveTaskStatus({ taskId, status: initial }: { taskId: number; status: string }) {
const t = useT();
const [status, setStatus] = useState(initial);
useEffect(() => setStatus(initial), [initial]);
useLiveIsland((e) => {
const row = e.tasks?.find((r) => r.id === taskId);
if (row) setStatus(row.status);
return []; // the page around depends on the status too
});
const s = TASK_STATUS[status] ?? { label: status, tone: "muted" as const };
return (
<Badge variant={s.tone} data-live-status={status}>
{t.text(s.label)}
</Badge>
);
}

View File

@ -2,6 +2,7 @@
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { useLive } from "@/lib/live";
import { Button } from "@/components/ui/button";
import { pairingLinkAction } from "@/app/(app)/actions";
import { useT } from "@/components/I18n";
@ -9,7 +10,7 @@ import { useT } from "@/components/I18n";
/**
* PEP-100: opens the user's bot (with the pairing code) in a new tab / the Telegram app and keeps
* Peppa open — a plain redirect used to take the page away mid-steps. While the user presses
* Start, the page refreshes itself so the step turns done.
* Start, the live channel tells the page, and it re-renders so the step turns done.
*/
export function OpenBotButton({ label, variant = "default", size = "sm" }: { label: string; variant?: "default" | "ghost" | "outline"; size?: "sm" | "xs" }) {
const t = useT();
@ -20,13 +21,13 @@ export function OpenBotButton({ label, variant = "default", size = "sm" }: { lab
useEffect(() => {
if (!waiting) return;
const timer = setInterval(() => router.refresh(), 3000);
const stop = setTimeout(() => setWaiting(false), 3 * 60_000);
return () => {
clearInterval(timer);
clearTimeout(stop);
};
}, [waiting, router]);
return () => clearTimeout(stop);
}, [waiting]);
// PEP-225: the binding (`me`) changes when the user presses Start in the bot — re-render then.
useLive(waiting ? "me" : null, (e) => {
if (e.type === "change") router.refresh();
});
async function open() {
setError(null);

View File

@ -1,10 +1,12 @@
"use client";
// Live runner terminal (PEP-9): xterm.js fed by SSE from /api/runners/<id>/terminal, input via POST.
// Live runner terminal (PEP-9): xterm.js fed by the tab's live channel (`terminal:<id>`, PEP-225),
// input over the same channel; without a WebSocket — SSE of /api/runners/<id>/terminal and POST.
import "@xterm/xterm/css/xterm.css";
import type { Terminal } from "@xterm/xterm";
import { Keyboard, Maximize2, Minimize2, Minus, Plus, RotateCw } from "lucide-react";
import { useCallback, useEffect, useRef, useState } from "react";
import { cn } from "@/lib/utils";
import { liveClient, useLiveMode } from "@/lib/live";
import { useT } from "@/components/I18n";
import { m } from "@peppa/shared/i18n";
@ -42,7 +44,10 @@ export function RunnerTerminal({ sessionId, live }: { sessionId: number; live: b
const host = useRef<HTMLDivElement>(null);
const scroller = useRef<HTMLDivElement>(null);
const term = useRef<Terminal | null>(null);
const [status, setStatus] = useState<Status>("connecting");
const [own, setStatus] = useState<Status>("connecting");
// The channel dropped: the picture is stale until it is back (a fresh frame comes then).
const mode = useLiveMode();
const status: Status = own === "live" && mode !== "live" ? "reconnecting" : own;
const [input, setInput] = useState(false);
const [full, setFull] = useState(false);
const [font, setFont] = useState(12);
@ -51,23 +56,17 @@ export function RunnerTerminal({ sessionId, live }: { sessionId: number; live: b
const t = useT();
const inputRef = useRef(false);
const queue = useRef<{ keys: string; timer: ReturnType<typeof setTimeout> | null; chain: Promise<void> }>({ keys: "", timer: null, chain: Promise.resolve() });
const url = `/api/runners/${sessionId}/terminal`;
const scope = `terminal:${sessionId}`;
const post = useCallback(
(body: { keys?: string; paste?: string }) => {
const q = queue.current;
// Strictly one request at a time: the order of keystrokes matters.
q.chain = q.chain.then(async () => {
try {
const r = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
if (!r.ok) setError(((await r.json().catch(() => null)) as { error?: string } | null)?.error ?? m("Ошибка {status}", { status: r.status }));
else setError(null);
} catch {
setError(m("Нет связи с Peppa FACTORY"));
}
setError(await liveClient().input(scope, body));
});
},
[url],
[scope],
);
const sendKeys = useCallback(
@ -136,28 +135,31 @@ export function RunnerTerminal({ sessionId, live }: { sessionId: number; live: b
};
}, [post, sendKeys]);
// The stream: (re)opened when the terminal is ready or the user asks to reconnect.
// The stream: (re)subscribed when the terminal is ready or the user asks to reconnect.
useEffect(() => {
const t = term.current;
if (!t || attempt === 0) return;
setStatus("connecting");
const es = new EventSource(url);
es.addEventListener("frame", (e) => {
const f = JSON.parse((e as MessageEvent<string>).data) as { cols: number; rows: number; data: string };
t.reset();
if (t.cols !== f.cols || t.rows !== f.rows) t.resize(f.cols, f.rows);
// The pane is usually taller than the panel: show its bottom, where the agent works.
t.write(f.data, () => scroller.current && (scroller.current.scrollTop = scroller.current.scrollHeight));
setStatus("live");
});
es.addEventListener("out", (e) => t.write((JSON.parse((e as MessageEvent<string>).data) as { data: string }).data));
es.addEventListener("end", () => {
es.close();
setStatus("ended");
});
es.onerror = () => setStatus(es.readyState === EventSource.CLOSED ? "error" : "reconnecting");
return () => es.close();
}, [url, attempt]);
let stop = () => {};
stop = liveClient().subscribe(
scope,
(e) => {
if (e.type === "frame") {
t.reset();
if (t.cols !== e.cols || t.rows !== e.rows) t.resize(e.cols, e.rows);
// The pane is usually taller than the panel: show its bottom, where the agent works.
t.write(e.data, () => scroller.current && (scroller.current.scrollTop = scroller.current.scrollHeight));
setStatus("live");
} else if (e.type === "out") t.write(e.data);
else if (e.type === "end") {
setStatus("ended");
queueMicrotask(() => stop());
} else if (e.type === "error") setStatus("error");
},
{ heavy: true },
);
return () => stop();
}, [scope, attempt]);
useEffect(() => {
inputRef.current = input && live;

View File

@ -2,6 +2,8 @@
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useEffect, useState } from "react";
import { useLive } from "@/lib/live";
import { Activity, Bot, Contact, FolderKanban, Gauge, GitBranch, Megaphone, House, KeyRound, MessagesSquare, ScrollText, LifeBuoy, LogOut, MessageCircleWarning, Search, Server, Settings, ShieldCheck, Sparkles, Users, type LucideIcon } from "lucide-react";
import { Brand } from "@/components/Brand";
import { ThemeToggle } from "@/components/ThemeToggle";
@ -48,9 +50,18 @@ const ITEMS: Item[] = [
const COUNT_TITLE = { questions: m("{n} вопросов ждут вас"), waitingRunners: m("{n} агентов ждут вас"), chats: m("{n} новых сообщений в обсуждениях"), feedback: m("{n} обращений ждут решения") };
/** Left panel on desktop; on phones a top bar plus a bottom tab bar (PEP-38): sections with «ждут вас» counters, theme, user. */
export function Sidebar({ login, avatarUrl, counts, superadmin = false, engineer = false }: { login: string; avatarUrl: string | null; counts: Record<"questions" | "waitingRunners" | "chats" | "feedback", number>; superadmin?: boolean; engineer?: boolean }) {
export function Sidebar({ login, avatarUrl, counts: initialCounts, superadmin = false, engineer = false }: { login: string; avatarUrl: string | null; counts: Record<"questions" | "waitingRunners" | "chats" | "feedback", number>; superadmin?: boolean; engineer?: boolean }) {
const path = usePathname();
const t = useT();
// PEP-225: the «ждут вас» counters follow the live channel (`attention`) without a re-render.
const [live, setLive] = useState<Partial<typeof initialCounts>>({});
useEffect(() => setLive({}), [initialCounts]);
useLive("attention", (e) => {
if (e.type !== "data") return;
const d = e.data as { questions?: number; waitingRunners?: number; chats?: number };
setLive({ questions: d.questions, waitingRunners: d.waitingRunners, chats: d.chats });
});
const counts = { ...initialCounts, ...Object.fromEntries(Object.entries(live).filter(([, v]) => typeof v === "number")) };
const items = ITEMS.filter((i) => (!i.admin || superadmin) && (!i.engineer || engineer));
// The phone tab bar holds what is left after the desktop-only and admin sections: 5 or 6 tabs.
const phoneTabs = items.filter((i) => !i.admin && !i.desktopOnly).length;

View File

@ -6,7 +6,7 @@ import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { getT } from "@/lib/i18n";
import { CopyCode } from "@/components/CopyCode";
import { AutoRefresh } from "@/components/AutoRefresh";
import { LiveRefresh } from "@/components/LiveRefresh";
const step = "flex gap-2.5";
const num = "grid size-5.5 shrink-0 place-items-center rounded-full bg-primary/15 text-xs font-semibold text-primary";
@ -28,8 +28,8 @@ export async function SubscriptionSetup({ projectId, back, logins, shared = fals
: l.provider === "claude" ? t("Подключаем Claude — осталось три шага") : t("Подключаем ChatGPT — осталось три шага")}
</h2>
{extra && <p className="m-0 text-muted-foreground">{t("Агенты уже работают на подключённой подписке. Вторая нужна только про запас — если она не нужна, нажмите «Отменить» внизу.")}</p>}
{/* PEP-148: the page asks ChatGPT itself every few seconds — the person does not have to press anything. */}
{l.provider !== "claude" && <AutoRefresh everyMs={4000} />}
{/* PEP-148 / PEP-225: the server asks ChatGPT every few seconds while the page watches this sign-in — the person does not have to press anything. */}
{l.provider !== "claude" && <LiveRefresh scope={`login:${l.subscriptionId}`} indicator={false} />}
{l.provider !== "claude" && checked && (
<p role="status" className="m-0 rounded-md border border-warn/50 bg-warn/10 px-3 py-2">
<b>{t("ChatGPT пока не подтвердил вход.")}</b>{" "}

View File

@ -1,41 +1,23 @@
"use client";
import { useEffect, useState } from "react";
import { useState } from "react";
import { useLive } from "@/lib/live";
import { RefreshCw } from "lucide-react";
import { useT } from "@/components/I18n";
/**
* 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.
* know — nothing happens and nothing is said. The live channel (`version`, PEP-225) brings the
* server's boot id on every (re)connect: a restarted web means a new id, and the page asks to
* reload. Never reloads by itself: the person may be in the middle of typing.
*/
export function VersionWatch({ boot }: { boot: string }) {
const t = useT();
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 timer = setInterval(check, 60_000);
const onVisible = () => document.visibilityState === "visible" && void check();
document.addEventListener("visibilitychange", onVisible);
window.addEventListener("focus", onVisible);
return () => {
alive = false;
clearInterval(timer);
document.removeEventListener("visibilitychange", onVisible);
window.removeEventListener("focus", onVisible);
};
}, [boot]);
useLive("version", (e) => {
const now = e.type === "data" ? (e.data as { boot?: string }).boot : undefined;
if (now && now !== boot) setStale(true);
});
if (!stale) return null;
return (

View File

@ -15,7 +15,7 @@ const g = globalThis as { __peppaLiveWs?: LiveWs };
export function registerLiveWs(): void {
setLiveProvider("attention", async (_db, userId) => {
const [c, { sound }] = await Promise.all([navCounts(userId), getNotifyPrefs(db, userId)]);
return { count: c.questions + c.waitingRunners, chats: c.chats, sound };
return { count: c.questions + c.waitingRunners, questions: c.questions, waitingRunners: c.waitingRunners, chats: c.chats, sound };
});
setLiveProvider("version", () => ({ boot: bootId() }));
g.__peppaLiveWs?.close();

413
apps/web/lib/live.ts Normal file
View File

@ -0,0 +1,413 @@
"use client";
// One live channel per tab (PEP-225): a single WebSocket to /api/ws carries every scope the page
// watches — page changes, the attention counter, the boot id, agent steps, the terminal. Scopes
// are reference-counted; after a drop the client reconnects with a growing pause and subscribes
// again with the last version it saw (`since`), so missed changes arrive at once. If the
// WebSocket never opens (a proxy cuts it), the fallback is the SSE of /api/live and of the
// terminal, and the WebSocket is tried again every minute. No data is polled on a timer: the
// only timer is the connection check (ping every 15 s).
import { useEffect, useRef, useSyncExternalStore } from "react";
import { m } from "@peppa/shared/i18n";
/** Shown through t.text by the terminal. */
const NO_LINK = m("Нет связи с Peppa FACTORY");
export interface LiveTaskRow {
id: number;
status: string;
title: string;
column: "backlog" | "in_progress" | "review" | "done";
other?: boolean;
}
export type LiveEvent =
| { type: "change"; scope: string; v: string; parts: string[]; tasks?: LiveTaskRow[]; chats?: number[] }
| { type: "step"; scope: string; step: { id: number } & Record<string, unknown> }
| { type: "data"; scope: string; v: string; data: unknown }
| { type: "frame"; scope: string; cols: number; rows: number; data: string }
| { type: "out"; scope: string; data: string }
| { type: "end"; scope: string }
/** The subscription was refused (no access, unknown scope). */
| { type: "error"; scope: string; status: number; error: string };
export type LiveHandler = (e: LiveEvent) => void;
export type LiveMode = "connecting" | "live" | "reconnecting" | "offline";
const PING_MS = 15_000;
const PONG_WAIT_MS = 10_000;
const BACKOFF_MAX_MS = 30_000;
const WS_RETRY_FROM_SSE_MS = 60_000;
/** WebSocket attempts that never opened before the SSE fallback. */
const WS_FAILS_TO_SSE = 3;
interface Sub {
handlers: Set<LiveHandler>;
/** Handlers that want the scope only while the tab is visible. */
heavy: number;
v?: string;
lastStep?: number;
active: boolean;
}
class LiveClient {
private subs = new Map<string, Sub>();
private ws: WebSocket | null = null;
private transport: "ws" | "sse" = "ws";
private everOpened = false;
private failsBeforeOpen = 0;
private attempt = 0;
private retry: ReturnType<typeof setTimeout> | null = null;
private pinger: ReturnType<typeof setInterval> | null = null;
private pongTimer: ReturnType<typeof setTimeout> | null = null;
private es: EventSource | null = null;
private esScopes = "";
private esTimer: ReturnType<typeof setTimeout> | null = null;
private terms = new Map<string, EventSource>();
private wsProbe: ReturnType<typeof setTimeout> | null = null;
private acks = new Map<number, (error: string | null) => void>();
private nextAck = 1;
private modeListeners = new Set<() => void>();
mode: LiveMode = "connecting";
/** Boot id the server greeted the tab with. */
boot: string | null = null;
constructor() {
document.addEventListener("visibilitychange", () => this.onVisibility());
window.addEventListener("online", () => this.reconnectNow());
}
private setMode(m: LiveMode) {
if (this.mode === m) return;
this.mode = m;
for (const fn of this.modeListeners) fn();
}
onMode(fn: () => void): () => void {
this.modeListeners.add(fn);
return () => this.modeListeners.delete(fn);
}
/** Watches `scope`; `heavy` scopes are dropped while the tab is hidden. */
subscribe(scope: string, handler: LiveHandler, opts: { heavy?: boolean } = {}): () => void {
let sub = this.subs.get(scope);
if (!sub) this.subs.set(scope, (sub = { handlers: new Set(), heavy: 0, active: false }));
sub.handlers.add(handler);
if (opts.heavy) sub.heavy++;
this.ensure();
this.activate(scope);
return () => {
const s = this.subs.get(scope);
if (!s) return;
s.handlers.delete(handler);
if (opts.heavy) s.heavy--;
if (!s.handlers.size) {
this.deactivate(scope);
this.subs.delete(scope);
this.syncSse();
}
};
}
/** Keyboard input / paste of a terminal; resolves to an error text or null. */
input(scope: string, body: { keys?: string; paste?: string }): Promise<string | null> {
if (this.transport === "ws" && this.ws?.readyState === WebSocket.OPEN) {
const id = this.nextAck++;
return new Promise((resolve) => {
this.acks.set(id, resolve);
this.ws!.send(JSON.stringify({ t: "in", scope, id, ...body }));
});
}
const runner = scope.slice("terminal:".length);
return fetch(`/api/runners/${runner}/terminal`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) })
.then(async (r) => (r.ok ? null : (((await r.json().catch(() => null)) as { error?: string } | null)?.error ?? `HTTP ${r.status}`)))
.catch(() => NO_LINK);
}
private wanted(sub: Sub): boolean {
return sub.handlers.size > 0 && !(document.visibilityState === "hidden" && sub.heavy > 0 && sub.heavy === sub.handlers.size);
}
private activate(scope: string) {
const sub = this.subs.get(scope);
if (!sub || sub.active || !this.wanted(sub)) return;
sub.active = true;
if (this.transport === "ws") {
if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(JSON.stringify({ t: "sub", scope, since: scope.startsWith("steps:") ? sub.lastStep : sub.v }));
} else this.syncSse();
}
private deactivate(scope: string) {
const sub = this.subs.get(scope);
if (!sub?.active) return;
sub.active = false;
if (this.transport === "ws") {
if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(JSON.stringify({ t: "unsub", scope }));
} else {
this.terms.get(scope)?.close();
this.terms.delete(scope);
this.syncSse();
}
}
private onVisibility() {
for (const [scope, sub] of this.subs) {
if (this.wanted(sub)) this.activate(scope);
else this.deactivate(scope);
}
if (document.visibilityState === "visible" && this.mode !== "live") this.reconnectNow();
}
private dispatch(e: LiveEvent) {
const sub = this.subs.get(e.scope);
if (!sub) return;
if ("v" in e && e.v) sub.v = e.v;
if (e.type === "step") sub.lastStep = Math.max(sub.lastStep ?? 0, Number(e.step.id) || 0);
for (const fn of [...sub.handlers]) {
try {
fn(e);
} catch (err) {
console.error("live:", err);
}
}
}
private ensure() {
if (this.ws || this.es || this.retry || this.transport === "sse") return;
this.connectWs();
}
private reconnectNow() {
if (this.transport === "sse" || this.ws) return;
if (this.retry) clearTimeout(this.retry);
this.retry = null;
this.connectWs();
}
private connectWs() {
if (typeof WebSocket === "undefined") return this.toSse();
let opened = false;
let ws: WebSocket;
try {
ws = new WebSocket(`${location.protocol === "https:" ? "wss" : "ws"}://${location.host}/api/ws`);
} catch {
return this.toSse();
}
this.ws = ws;
if (this.transport === "ws") this.setMode(this.everOpened ? "reconnecting" : "connecting");
ws.onopen = () => {
opened = true;
this.everOpened = true;
this.failsBeforeOpen = 0;
this.attempt = 0;
if (this.transport === "sse") this.leaveSse();
this.setMode("live");
for (const sub of this.subs.values()) sub.active = false;
for (const scope of this.subs.keys()) this.activate(scope);
this.startPing();
};
ws.onmessage = (msg) => {
let m: { t: string; scope?: string; type?: string; status?: number; error?: string; id?: number; boot?: string; v?: string };
try {
m = JSON.parse(String(msg.data));
} catch {
return;
}
if (m.t === "pong") {
if (this.pongTimer) clearTimeout(this.pongTimer);
this.pongTimer = null;
} else if (m.t === "hello") this.boot = m.boot ?? null;
else if (m.t === "ev") this.dispatch(m as unknown as LiveEvent);
else if (m.t === "ok" && m.scope && m.v) {
const sub = this.subs.get(m.scope);
if (sub && !sub.v) sub.v = m.v;
} else if (m.t === "err" && m.scope) {
const sub = this.subs.get(m.scope);
if (sub) sub.active = false;
this.dispatch({ type: "error", scope: m.scope, status: m.status ?? 500, error: m.error ?? "" });
} else if (m.t === "ack" && typeof m.id === "number") {
this.acks.get(m.id)?.(m.error ?? null);
this.acks.delete(m.id);
}
};
ws.onclose = () => {
if (this.ws !== ws) return;
this.ws = null;
this.stopPing();
for (const [id, done] of this.acks) {
done(NO_LINK);
this.acks.delete(id);
}
for (const sub of this.subs.values()) sub.active = false;
if (this.transport === "sse") return; // a failed probe from the fallback
if (!opened && !this.everOpened && ++this.failsBeforeOpen >= WS_FAILS_TO_SSE) return this.toSse();
this.scheduleReconnect();
};
}
private scheduleReconnect() {
if (!this.subs.size) return; // nothing to watch: reconnect on the next subscribe
this.setMode(this.attempt > 2 ? "offline" : "reconnecting");
const pause = Math.min(BACKOFF_MAX_MS, 1000 * 2 ** this.attempt++) * (0.75 + Math.random() * 0.5);
this.retry = setTimeout(() => {
this.retry = null;
this.connectWs();
}, pause);
}
/** Connection check — the one timer of the channel. */
private startPing() {
this.stopPing();
this.pinger = setInterval(() => {
const ws = this.ws;
if (ws?.readyState !== WebSocket.OPEN || this.pongTimer) return;
ws.send(JSON.stringify({ t: "ping" }));
this.pongTimer = setTimeout(() => {
this.pongTimer = null;
ws.close();
}, PONG_WAIT_MS);
}, PING_MS);
}
private stopPing() {
if (this.pinger) clearInterval(this.pinger);
if (this.pongTimer) clearTimeout(this.pongTimer);
this.pinger = this.pongTimer = null;
}
// ---- SSE fallback ----
private toSse() {
this.transport = "sse";
this.ws = null;
for (const sub of this.subs.values()) sub.active = false;
for (const scope of this.subs.keys()) this.activate(scope);
this.syncSse();
// Try the WebSocket again now and then (the proxy may let it through later).
const probe = () => {
this.wsProbe = null;
if (this.transport !== "sse") return;
if (!this.ws) this.connectWs();
this.wsProbe = setTimeout(probe, WS_RETRY_FROM_SSE_MS);
};
this.wsProbe = setTimeout(probe, WS_RETRY_FROM_SSE_MS);
}
private leaveSse() {
this.transport = "ws";
this.es?.close();
this.es = null;
this.esScopes = "";
for (const es of this.terms.values()) es.close();
this.terms.clear();
if (this.wsProbe) clearTimeout(this.wsProbe);
this.wsProbe = null;
}
/** One EventSource for every hub scope (reopened when the set changes), one per terminal. */
private syncSse() {
if (this.transport !== "sse") return;
if (this.esTimer) return;
this.esTimer = setTimeout(() => {
this.esTimer = null;
if (this.transport !== "sse") return;
const active = [...this.subs].filter(([, s]) => s.active);
for (const [scope] of active.filter(([s]) => s.startsWith("terminal:"))) if (!this.terms.has(scope)) this.openTerminalSse(scope);
const hub = active.filter(([s]) => !s.startsWith("terminal:")).map(([s]) => s).sort();
const key = hub.join(",");
if (key === this.esScopes && this.es) return;
this.es?.close();
this.es = null;
this.esScopes = key;
if (!hub.length) return;
if (typeof EventSource === "undefined") return this.setMode("offline");
const q = new URLSearchParams({ scope: key });
for (const s of hub) {
const sub = this.subs.get(s)!;
const since = s.startsWith("steps:") ? sub.lastStep : sub.v;
if (since) q.set(`since.${s}`, String(since));
}
const es = new EventSource(`/api/live?${q}`);
this.es = es;
let fails = 0;
es.addEventListener("ready", () => {
fails = 0;
this.setMode("live");
});
for (const type of ["change", "step", "data"]) es.addEventListener(type, (e) => this.dispatch(JSON.parse((e as MessageEvent<string>).data) as LiveEvent));
es.onerror = () => {
// EventSource reconnects by itself (retry: 3000); after a few failures say so.
this.setMode(++fails >= 3 ? "offline" : "reconnecting");
};
}, 50);
}
private openTerminalSse(scope: string) {
const es = new EventSource(`/api/runners/${scope.slice("terminal:".length)}/terminal`);
this.terms.set(scope, es);
for (const type of ["frame", "out"]) es.addEventListener(type, (e) => this.dispatch({ type, scope, ...JSON.parse((e as MessageEvent<string>).data) } as LiveEvent));
es.addEventListener("end", () => {
es.close();
this.terms.delete(scope);
this.dispatch({ type: "end", scope });
});
es.onerror = () => {
if (es.readyState === EventSource.CLOSED) this.dispatch({ type: "error", scope, status: 404, error: "" });
};
}
}
const g = globalThis as { __peppaLive?: LiveClient };
/** The tab's channel (created on first use in the browser). */
export function liveClient(): LiveClient {
return (g.__peppaLive ??= new LiveClient());
}
/** Calls `handler` with every event of `scope` (null — nothing). The latest handler is used without resubscribing. */
export function useLive(scope: string | null, handler: LiveHandler, opts: { heavy?: boolean } = {}): void {
const ref = useRef(handler);
ref.current = handler;
const heavy = !!opts.heavy;
useEffect(() => {
if (!scope) return;
return liveClient().subscribe(scope, (e) => ref.current(e), { heavy });
}, [scope, heavy]);
}
/** The connection state for the indicator. */
export function useLiveMode(): LiveMode {
return useSyncExternalStore(
(fn) => liveClient().onMode(fn),
() => liveClient().mode,
() => "connecting",
);
}
// ---- Islands (PEP-225): parts of a page that apply an event in place ----
/** Applies a `change` in place; returns the parts it fully applied (they need no server re-render). */
export type Island = (e: Extract<LiveEvent, { type: "change" }>) => string[];
const islands = new Set<Island>();
/** Registers an island for the page's `change` events (LiveRefresh asks them before re-rendering). */
export function useLiveIsland(island: Island): void {
const ref = useRef(island);
ref.current = island;
useEffect(() => {
const fn: Island = (e) => ref.current(e);
islands.add(fn);
return () => {
islands.delete(fn);
};
}, []);
}
/** Parts of `e` the page's islands applied. */
export function applyIslands(e: Extract<LiveEvent, { type: "change" }>): Set<string> {
const done = new Set<string>();
for (const fn of islands) {
try {
for (const p of fn(e)) done.add(p);
} catch (err) {
console.error("live island:", err);
}
}
return done;
}

View File

@ -128,6 +128,7 @@ export class LiveConnection {
/** Keyboard input / paste of the terminal: in order, with the PEP-9 checks and limits. */
private terminalIn(scope: LiveScope, msg: { keys?: unknown; paste?: unknown; id?: unknown }) {
const id = typeof msg.id === "number" || typeof msg.id === "string" ? msg.id : null;
// glossary-ignore: the runner terminal is the engineer's view (PEP-9).
if (!scope.startsWith("terminal:")) return this.send({ t: "ack", id, error: m("Ввод — только в терминал") });
const input = { keys: typeof msg.keys === "string" ? msg.keys : undefined, paste: typeof msg.paste === "string" ? msg.paste : undefined };
const run = async () => {
@ -135,6 +136,7 @@ export class LiveConnection {
await terminalInput(this.db, this.user, Number(scope.slice(9)), input);
this.send({ t: "ack", id });
} catch (e) {
// glossary-ignore: the runner terminal is the engineer's view (PEP-9).
this.send({ t: "ack", id, error: e instanceof PeppaError || e instanceof LiveError ? e.message : m("Ошибка терминала") });
if (!(e instanceof PeppaError)) console.error("live-ws: terminal input", e);
}

View File

@ -295,6 +295,7 @@ class LiveHub {
private again = false;
private lastObserve = 0;
private lastLoginPoll = 0;
private run = 0;
private db: Db;
constructor(db: Db) {
this.db = db;
@ -411,9 +412,11 @@ class LiveHub {
}
}, 1000);
this.timer.unref?.();
// A stop and a new start may come before the socket is up: only the current run keeps it.
const run = ++this.run;
listenEvents("web", () => this.wake())
.then((stop) => {
if (this.timer) this.stopSocket = stop;
if (this.timer && run === this.run && !this.stopSocket) this.stopSocket = stop;
else void stop();
})
.catch((e) => console.error("live: web.events.sock unavailable, data_version only:", (e as Error).message));

View File

@ -221,6 +221,9 @@ export const runner: Dict = {
"{who}: остановлен по лимиту, время сброса неизвестно — попробую продолжить в {time}.": "{who}: stopped by the limit, reset time unknown — will try to resume at {time}.",
// Live updates
"Неизвестное сообщение": "Unknown message",
"Слишком много областей": "Too many scopes",
"Ввод — только в терминал": "Input goes to a terminal only",
"Неизвестная область: {scope}": "Unknown scope: {scope}",
"Нужна область (scope)": "A scope is required",

View File

@ -303,8 +303,8 @@ export const story: Dict = {
"подключение…": "connecting…",
"в реальном времени": "live",
"переподключение…": "reconnecting…",
"опрос раз в 5 с": "polling every 5 s",
"Канал событий недоступен — страница обновляется по таймеру": "The event stream is unavailable — the page refreshes on a timer",
"нет связи — пробуем снова": "offline — retrying",
"Нет связи с Peppa FACTORY — страница обновится, когда связь вернётся": "No connection to Peppa FACTORY — the page will update when it is back",
"Страница обновляется сама, когда что-то меняется": "The page refreshes by itself when something changes",
Превью: "Preview",
Посмотреть: "View",

View File

@ -171,6 +171,9 @@ export const runner: Dict = {
"{who} упёрлась в лимит.": "{who} лимитке тірелді.",
"{who}: остановлен по лимиту, продолжит в {time} сам.": "{who}: лимит бойынша тоқтатылды, өзі жалғастырады: {time}.",
"{who}: остановлен по лимиту, время сброса неизвестно — попробую продолжить в {time}.": "{who}: лимит бойынша тоқтатылды, қалпына келу уақыты белгісіз — жалғастыруға тырысамын: {time}.",
"Неизвестное сообщение": "Белгісіз хабарлама",
"Слишком много областей": "Аймақтар тым көп",
"Ввод — только в терминал": "Енгізу тек терминалға",
"Неизвестная область: {scope}": "Белгісіз аймақ: {scope}",
"Нужна область (scope)": "Аймақ (scope) керек",
"планировщик ответил не по формату — попробуйте ещё раз или уточните описание эпика": "жоспарлаушы форматқа сай жауап бермеді — қайталап көріңіз немесе эпик сипаттамасын нақтылаңыз",

View File

@ -281,8 +281,8 @@ export const story: Dict = {
"подключение…": "қосылуда…",
"в реальном времени": "нақты уақытта",
"переподключение…": "қайта қосылуда…",
"опрос раз в 5 с": "5 с сайын сұрау",
"Канал событий недоступен — страница обновляется по таймеру": "Оқиғалар арнасы қолжетімсіз — бет таймер бойынша жаңартылады",
"нет связи — пробуем снова": "байланыс жоқ — қайта көріп жатырмыз",
"Нет связи с Peppa FACTORY — страница обновится, когда связь вернётся": "Peppa FACTORY-мен байланыс жоқ — байланыс қалпына келгенде бет жаңарады",
"Страница обновляется сама, когда что-то меняется": "Бір нәрсе өзгергенде бет өзі жаңарады",
"Превью": "Превью",
"Посмотреть": "Қарау",

View File

@ -0,0 +1,228 @@
// PEP-225: one WebSocket per tab — subscriptions with access checks, events only for their own
// scope with the changed task rows, catching up after a drop, the terminal (output and input)
// over the socket, limits, and the upgrade itself (login, origin).
import assert from "node:assert/strict";
import { createServer, type Server } from "node:http";
import type { AddressInfo } from "node:net";
import { after, describe, test } from "node:test";
import { createLiveWs, LiveConnection, LIVE_WS_RATE_MAX, type LiveWs } from "@peppa/runner/live-ws";
import { core, db, project, runner, teardown, waitFor } from "./helpers.ts";
process.env.PEPPA_SECRET = "mock-secret-for-tests";
after(teardown);
let seq = 0;
const user = (login: string) => core.upsertUserFromGitea(db, { id: 9100 + seq++, login }, { access_token: "x" });
type Msg = Record<string, unknown> & { t: string };
/** A connection driven directly: what the server sent and how it closed. */
function conn(u: core.User) {
const out: Msg[] = [];
const closed: Array<{ code: number; reason: string }> = [];
const c = new LiveConnection(db, u, (m) => out.push(m as Msg), (code, reason) => closed.push({ code, reason }));
const send = (m: object) => c.receive(JSON.stringify(m));
return { c, out, closed, send };
}
async function ownedStory(login: string) {
const owner = await user(login);
const p = await project({ turns: [] });
const ref = await core.resolveTask(db, p.taskKey);
await core.setProjectOwner(db, ref.project.id, owner.id);
return { owner, p, ref };
}
describe("tab channel (PEP-225)", () => {
test("Подписка без прав: ответ 404, события не приходят", async () => {
const { ref } = await ownedStory("ws-owner-1");
const outsider = await user("ws-outsider-1");
const x = conn(outsider);
await x.send({ t: "sub", scope: `task:${ref.task.id}` });
assert.deepEqual(x.out.at(-1), { t: "err", scope: `task:${ref.task.id}`, status: 404, error: "Не найдено" });
await x.send({ t: "sub", scope: "observe" });
assert.equal(x.out.at(-1)!.status, 404, "observe — only a superadmin");
await x.send({ t: "sub", scope: "nonsense" });
assert.equal(x.out.at(-1)!.status, 400);
assert.deepEqual(x.c.scopes, []);
x.c.close();
});
test("Событие доходит только до своей области — со строкой задачи", async () => {
const a = await ownedStory("ws-owner-2");
const b = await core.createTask(db, { projectId: a.ref.project.id, title: "Соседняя задача" });
const x = conn(a.owner);
await x.send({ t: "sub", scope: `task:${a.ref.task.id}` });
assert.equal(x.out.at(-1)!.t, "ok");
try {
await core.updateTask(db, b, { status: "in_progress" });
await runner.liveHub(db).check();
assert.equal(x.out.filter((m) => m.t === "ev").length, 0, "another story is not this scope");
await core.updateTask(db, a.ref, { status: "review" });
await runner.liveHub(db).check();
const ev = x.out.find((m) => m.t === "ev") as Msg & { tasks?: Array<{ id: number; status: string; column: string }>; parts: string[] };
assert.ok(ev, "change of the story arrives");
assert.equal(ev.type, "change");
assert.ok(ev.parts.includes("t"));
assert.deepEqual(ev.tasks?.map((r) => [r.id, r.status, r.column]), [[a.ref.task.id, "review", "review"]]);
} finally {
x.c.close();
}
assert.ok(!runner.liveHub(db).watched.includes(`task:${a.ref.task.id}`), "closing the tab unsubscribes");
});
test("Доска проекта: смена статуса — строка без пометки other, новая задача — с пометкой", async () => {
const a = await ownedStory("ws-owner-3");
const x = conn(a.owner);
const scope = `project:${a.ref.project.id}`;
await x.send({ t: "sub", scope });
try {
await core.updateTask(db, a.ref, { status: "in_progress" });
await runner.liveHub(db).check();
const first = x.out.filter((m) => m.t === "ev").at(-1) as Msg & { tasks: Array<{ id: number; other?: boolean; column: string }> };
assert.deepEqual(first.tasks.map((r) => [r.id, r.column, r.other ?? false]), [[a.ref.task.id, "in_progress", false]]);
const fresh = (await core.createTask(db, { projectId: a.ref.project.id, title: "Новая" })).task;
await runner.liveHub(db).check();
const second = x.out.filter((m) => m.t === "ev").at(-1) as Msg & { tasks: Array<{ id: number; other?: boolean }> };
assert.deepEqual(second.tasks.map((r) => [r.id, r.other]), [[fresh.id, true]], "a new card can't be drawn in place");
} finally {
x.c.close();
}
});
test("Связь пропала: переподключение с since догоняет пропущенное, без изменений — тишина", async () => {
const a = await ownedStory("ws-owner-4");
const scope = `project:${a.ref.project.id}`;
const first = conn(a.owner);
await first.send({ t: "sub", scope });
const v1 = first.out.find((m) => m.t === "ok")!.v as string;
assert.ok(v1, "ok carries the version");
first.c.close(); // the drop
// Nothing changed: no event on re-subscribe. A watcher keeps the scope alive meanwhile.
const keep = conn(a.owner);
await keep.send({ t: "sub", scope });
const same = conn(a.owner);
await same.send({ t: "sub", scope, since: v1 });
assert.equal(same.out.filter((m) => m.t === "ev").length, 0);
same.c.close();
await core.updateTask(db, a.ref, { status: "review" });
await runner.liveHub(db).check();
const back = conn(a.owner);
await back.send({ t: "sub", scope, since: v1 });
const ev = back.out.find((m) => m.t === "ev") as Msg & { parts: string[] };
assert.ok(ev, "the missed change arrives at once");
assert.deepEqual(ev.parts, ["*"]);
back.c.close();
keep.c.close();
});
test("Шаги агента после since приходят при переподключении", async () => {
const a = await ownedStory("ws-owner-5");
const s = await core.createSession(db, { projectId: a.ref.project.id, taskId: a.ref.task.id });
await core.recordStep(db, s, { tool: "Bash", kind: "command", text: "one", ok: true });
const keep = conn(a.owner);
await keep.send({ t: "sub", scope: `steps:${s.id}` });
const seen = (await db.$client.prepare(`SELECT max(id) AS id FROM events WHERE session_id = ? AND type = 'step'`).get(s.id)) as { id: number };
await core.recordStep(db, s, { tool: "Bash", kind: "command", text: "two", ok: true });
await runner.liveHub(db).check();
const back = conn(a.owner);
await back.send({ t: "sub", scope: `steps:${s.id}`, since: seen.id });
const steps = back.out.filter((m) => m.t === "ev" && m.type === "step").map((m) => (m.step as { text: string }).text);
assert.deepEqual(steps, ["two"]);
back.c.close();
keep.c.close();
});
test("Значение области: attention отдаёт текущее при подписке и новое при изменении", async () => {
const a = await ownedStory("ws-owner-6");
let n = 1;
runner.setLiveProvider("attention", (_db, uid) => ({ count: uid === a.owner.id ? n : -1, sound: false }));
const x = conn(a.owner);
await x.send({ t: "sub", scope: "attention" });
await waitFor("first value", async () => x.out.some((m) => m.t === "ev" && m.type === "data"));
assert.deepEqual((x.out.find((m) => m.type === "data")!.data as { count: number }).count, 1);
n = 2;
await core.askPm(db, a.ref, { kind: "question", text: "Какой цвет?" });
await runner.liveHub(db).check();
await waitFor("new value", async () => x.out.filter((m) => m.type === "data").length === 2);
assert.equal((x.out.filter((m) => m.type === "data")[1]!.data as { count: number }).count, 2);
x.c.close();
});
test("Терминал через сокет: кадр, ввод с подтверждением, завершённая сессия — отказ", async () => {
const a = await ownedStory("ws-owner-7");
const s = await core.createSession(db, { projectId: a.ref.project.id, taskId: a.ref.task.id });
const name = `peppa-wsterm-${process.pid}`;
await core.updateSession(db, s.id, { tmuxName: name, status: "running" });
await runner.tmux.newSession({ name, cwd: a.p.dir, command: `sh -c 'while read l; do echo "got:$l"; done'`, env: {}, width: 100 });
const x = conn(a.owner);
const scope = `terminal:${s.id}`;
try {
await x.send({ t: "sub", scope });
assert.equal(x.out.at(-1)!.t, "ok");
await waitFor("frame", async () => x.out.some((m) => m.t === "ev" && m.type === "frame"));
await x.send({ t: "in", scope, keys: "hi\r", id: 1 });
assert.deepEqual(x.out.find((m) => m.t === "ack"), { t: "ack", id: 1 });
await waitFor("echo", async () => (await runner.tmux.capturePane(name)).includes("got:hi"));
await waitFor("echo over the socket", async () => x.out.some((m) => m.t === "ev" && (m.type === "out" || m.type === "frame") && String(m.data).includes("got:hi")));
const outsider = conn(await user("ws-outsider-7"));
await outsider.send({ t: "sub", scope });
assert.equal(outsider.out.at(-1)!.status, 404);
await outsider.send({ t: "in", scope, keys: "rm\r", id: 9 });
assert.ok(outsider.out.find((m) => m.t === "ack" && m.id === 9)!.error, "no input without access");
await core.updateSession(db, s.id, { status: "done", endedAt: new Date() });
await x.send({ t: "in", scope, keys: "late\r", id: 2 });
assert.ok((x.out.find((m) => m.t === "ack" && m.id === 2) as Msg).error, "finished session refuses input");
} finally {
x.c.close();
await runner.tmux.killSession(name).catch(() => {});
}
});
test("Сообщения слишком часто: соединение закрывается 1008", async () => {
const x = conn(await user("ws-spammer"));
const now = Date.now();
for (let i = 0; i <= LIVE_WS_RATE_MAX; i++) await x.c.receive(JSON.stringify({ t: "ping" }), now);
assert.deepEqual(x.closed, [{ code: 1008, reason: "rate" }]);
x.c.close();
});
test("Апгрейд: без входа 401, чужой сайт 403, свой — hello и подписка", async () => {
const owner = await user("ws-http-owner");
const ws: LiveWs = createLiveWs({ db, authenticate: async (req) => (req.headers.cookie === "peppa_session=good" ? owner : null), boot: () => "boot-1" });
const server: Server = createServer((_req, res) => res.end());
server.on("upgrade", (req, socket, head) => ws.handleUpgrade(req, socket, head));
await new Promise<void>((r) => server.listen(0, "127.0.0.1", r));
const port = (server.address() as AddressInfo).port;
const url = `ws://127.0.0.1:${port}/api/ws`;
const open = (headers: Record<string, string>) =>
new Promise<{ ok: boolean; msgs: Msg[]; sock: WebSocket }>((resolve) => {
const sock = new (WebSocket as unknown as new (u: string, o: object) => WebSocket)(url, { headers });
const msgs: Msg[] = [];
sock.onmessage = (e) => msgs.push(JSON.parse(String(e.data)));
sock.onopen = () => resolve({ ok: true, msgs, sock });
sock.onerror = () => resolve({ ok: false, msgs, sock });
});
try {
assert.equal((await open({})).ok, false, "no login");
assert.equal((await open({ cookie: "peppa_session=good", origin: "https://evil.example" })).ok, false, "foreign origin");
const good = await open({ cookie: "peppa_session=good", origin: `http://127.0.0.1:${port}` });
assert.ok(good.ok);
await waitFor("hello", async () => good.msgs.some((m) => m.t === "hello"));
assert.equal(good.msgs[0]!.boot, "boot-1");
good.sock.send(JSON.stringify({ t: "sub", scope: "home" }));
good.sock.send(JSON.stringify({ t: "ping" }));
await waitFor("ok + pong", async () => good.msgs.some((m) => m.t === "ok") && good.msgs.some((m) => m.t === "pong"));
assert.equal(ws.clients, 1);
good.sock.close();
await waitFor("closed", async () => ws.clients === 0);
} finally {
ws.close();
server.close();
}
});
});

View File

@ -202,14 +202,14 @@ describe("live hub and SSE (PEP-37)", () => {
await core.setSetting(db, "heartbeat:test", { at: Date.now() });
await core.updateTask(db, b.ref, { status: "in_progress" });
await core.recordStep(db, s, { tool: "Bash", kind: "command", text: "ls", ok: true });
hub.check();
await hub.check();
assert.deepEqual(got.map((e) => e.type), ["step"]);
assert.equal(got[0]!.type === "step" && got[0]!.step.text, "ls");
// A question on the story: change (via the check the notify() poke schedules).
await core.askPm(db, a.ref, { kind: "question", text: "Какой цвет?" });
await waitFor("change event", async () => got.some((e) => e.type === "change"), 5000);
const n = got.length;
hub.check();
await hub.check();
assert.equal(got.length, n, "no repeat without a new write");
} finally {
stop();
@ -244,7 +244,7 @@ describe("live hub and SSE (PEP-37)", () => {
};
await until(/event: ready/);
await core.updateTask(db, ref, { title: "Переименовано" }, undefined, "live-owner");
await until(/event: change\ndata: \{"type":"change","scope":"task:\d+"\}/);
await until(/event: change\ndata: \{"type":"change","scope":"task:\d+","v":"[\w-]+","parts":\[[^\]]*"t"[^\]]*\],"tasks":\[\{"id":\d+,"status":"[a-z_]+","title":"Переименовано"/);
ac.abort();
await reader.cancel().catch(() => {});
});