>({});
+ 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;
diff --git a/apps/web/components/SubscriptionSetup.tsx b/apps/web/components/SubscriptionSetup.tsx
index b40a05e3..13223ce0 100644
--- a/apps/web/components/SubscriptionSetup.tsx
+++ b/apps/web/components/SubscriptionSetup.tsx
@@ -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 — осталось три шага")}
{extra && {t("Агенты уже работают на подключённой подписке. Вторая нужна только про запас — если она не нужна, нажмите «Отменить» внизу.")}
}
- {/* PEP-148: the page asks ChatGPT itself every few seconds — the person does not have to press anything. */}
- {l.provider !== "claude" && }
+ {/* 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" && }
{l.provider !== "claude" && checked && (
{t("ChatGPT пока не подтвердил вход.")}{" "}
diff --git a/apps/web/components/VersionWatch.tsx b/apps/web/components/VersionWatch.tsx
index 2bb0cc22..b6a760b2 100644
--- a/apps/web/components/VersionWatch.tsx
+++ b/apps/web/components/VersionWatch.tsx
@@ -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 (
diff --git a/apps/web/components/common.tsx b/apps/web/components/common.tsx
index f7d98adc..163aae8c 100644
--- a/apps/web/components/common.tsx
+++ b/apps/web/components/common.tsx
@@ -6,7 +6,6 @@ import { Badge } from "@/components/ui/badge";
import { SESSION_STATUS, TASK_STATUS, TONE_BG } from "@/lib/status";
import { cn } from "@/lib/utils";
import { getT } from "@/lib/i18n";
-import { intlLocale, type Translator } from "@peppa/shared/i18n";
export function PageHeader({ title, crumbs, actions, children }: { title: ReactNode; crumbs?: ReactNode; actions?: ReactNode; children?: ReactNode }) {
return (
@@ -97,25 +96,4 @@ export function Disclosure({ summary, children, open, className }: { summary: Re
}
-/** «5 мин назад» in the page's language. */
-export function ago(d: Date | null | undefined, t: Translator): string {
- if (!d) return "—";
- const s = Math.round((Date.now() - d.getTime()) / 1000);
- if (s < 60) return t("{n} с назад", { n: s });
- if (s < 3600) return t("{n} мин назад", { n: Math.round(s / 60) });
- if (s < 86400) return t("{n} ч назад", { n: Math.round(s / 3600) });
- return d.toLocaleDateString(intlLocale(t.locale));
-}
-
-/** Text with its http(s) addresses as links. */
-export function linkify(text: string) {
- return text.split(/(https?:\/\/[^\s<>«»"]+[^\s<>«»".,;:!?)])/g).map((part, i) =>
- i % 2 ? (
-
- {part}
-
- ) : (
- part
- ),
- );
-}
+export { ago, linkify } from "@/lib/format";
diff --git a/apps/web/instrumentation.ts b/apps/web/instrumentation.ts
index 79c32d4e..0c92e8fd 100644
--- a/apps/web/instrumentation.ts
+++ b/apps/web/instrumentation.ts
@@ -8,6 +8,9 @@ export async function register() {
installCrashReporting(db, "web");
const { setRunnerClient } = await import("@peppa/runner");
setRunnerClient(true, db);
+ // PEP-225: the tab's WebSocket (/api/ws) — served by apps/web/server.ts in this process.
+ const { registerLiveWs } = await import("@/lib/live-server");
+ registerLiveWs();
const version = process.env.NEXT_PUBLIC_PEPPA_VERSION;
const tick = () => beat(db, "web", { version }).catch((e) => console.error(`heartbeat: ${(e as Error).message}`));
void tick();
diff --git a/apps/web/lib/auth.ts b/apps/web/lib/auth.ts
index f67b4d96..886eda9d 100644
--- a/apps/web/lib/auth.ts
+++ b/apps/web/lib/auth.ts
@@ -1,4 +1,4 @@
-import { enterActor, getUiMode, getUser, isSuperadmin, isUserAllowed, sessionsValidAfter, sign, verify, type User } from "@peppa/core";
+import { enterActor, getUiMode, isSuperadmin, sign, type User } from "@peppa/core";
import { loadEnv } from "@peppa/shared";
import { wording, type Words } from "@peppa/shared/wording";
import { cookies, headers } from "next/headers";
@@ -6,31 +6,17 @@ import { redirect } from "next/navigation";
import { cache } from "react";
import { db } from "./db";
import { getLocale } from "./i18n";
+import { SESSION_COOKIE, SESSION_DAYS, userFromSessionToken, type SessionPayload } from "./session-user";
-export const SESSION_COOKIE = "peppa_session";
+export { SESSION_COOKIE };
/** eGov QR flow handle (PEP-65): httpOnly, only for /auth/egov, lives as long as the QR. */
export const EGOV_COOKIE = "peppa_egov";
/** Only same-site relative paths are allowed as a post-login destination. */
export const safeNext = (n: string | null | undefined) => (n && n.startsWith("/") && !n.startsWith("//") ? n : "/");
-const SESSION_DAYS = 30;
-
-interface SessionPayload {
- uid: number;
- exp: number;
-}
/** Memoized per request: the layout, the page and the side panel all ask for the user. */
-export const currentUser = cache(async (): Promise => {
- const p = verify((await cookies()).get(SESSION_COOKIE)?.value);
- if (!p || p.exp < Date.now()) return null;
- // PEP-95: «выкинуть всех» — a session issued before the cut-off is no longer valid.
- const after = await sessionsValidAfter(db);
- if (after !== null && p.exp - SESSION_DAYS * 86400_000 < after) return null;
- const user = await getUser(db, p.uid);
- // Removed from the allowlist → the session stops working right away.
- return user && (await isUserAllowed(db, user)) ? user : null;
-});
+export const currentUser = cache(async (): Promise => userFromSessionToken((await cookies()).get(SESSION_COOKIE)?.value));
/** For pages and server actions: the logged-in user, or a redirect to /login. */
export async function requireUser(): Promise {
diff --git a/apps/web/lib/chat-live-types.ts b/apps/web/lib/chat-live-types.ts
new file mode 100644
index 00000000..607b86cf
--- /dev/null
+++ b/apps/web/lib/chat-live-types.ts
@@ -0,0 +1,56 @@
+// PEP-228: a chat message as the live channel brings it to a chat page — already translated and
+// cleaned for its viewer on the server (lib/chat-live.ts); the browser only draws it.
+import type { AttachmentView } from "@peppa/core";
+
+export interface LiveChatMessage {
+ id: number;
+ threadKey: string | null;
+ kind: "event" | "question" | "user" | "system";
+ authorKind: "system" | "agent" | "user";
+ authorUserId: number | null;
+ /** A person's login (people's messages). */
+ login: string | null;
+ /** An agent's or a role's name, translated; null — the thread's agent. */
+ agent: string | null;
+ via: "web" | "telegram" | null;
+ /** ISO time of the message (of its last repeat). */
+ at: string;
+ repeats: number;
+ /** A command («/status») — not a part of the discussion. */
+ command: boolean;
+ /** The factory's service notice — the chat with the analyst doesn't show it (PEP-207). */
+ notice: boolean;
+ /** What the screen shows at once and what opens under «Подробнее». */
+ main: string;
+ more: string | null;
+ link: string | null;
+ files: AttachmentView[];
+ /** A question or a message with buttons: the page re-renders it from the server. */
+ render: boolean;
+ /** The thread's title for the «События агентов» view (🧵 …). */
+ thread: { label: string; href: string } | null;
+}
+
+/** Which conversation the page shows — the same rules as its server query. */
+export type ChatView = { kind: "discussion" } | { kind: "channel" } | { kind: "feed" } | { kind: "thread"; key: string };
+
+export function inView(m: Pick, view: ChatView): boolean {
+ if (view.kind === "feed") return true;
+ if (view.kind === "thread") return m.threadKey === view.key;
+ if (view.kind === "channel") return m.threadKey === null;
+ return m.threadKey === null && m.kind === "user" && !m.command && !m.notice;
+}
+
+/**
+ * What of a `change` of the chat scope the feed applies in place: `m` when every new message is
+ * of this conversation and none needs buttons; `x` (offers, files) when it came with messages —
+ * they carry their own. Pure: the test and the island share it.
+ */
+export function chatParts(e: { parts: string[]; messages?: unknown[] }, view: ChatView): { applied: string[]; add: LiveChatMessage[] } {
+ const list = (e.messages ?? []) as LiveChatMessage[];
+ if (!e.messages) return { applied: [], add: [] };
+ const plain = list.every((m) => inView(m, view) && !m.render);
+ const applied = ["x"];
+ if (plain) applied.push("m");
+ return { applied, add: list.filter((m) => inView(m, view) && !m.render) };
+}
diff --git a/apps/web/lib/chat-live.ts b/apps/web/lib/chat-live.ts
new file mode 100644
index 00000000..15d96039
--- /dev/null
+++ b/apps/web/lib/chat-live.ts
@@ -0,0 +1,43 @@
+// PEP-228: new messages of a chat for the live channel — the same text a chat page renders on
+// the server (translation, cleaning, «Подробнее», links), built for one viewer.
+import { getUserLocale, isSuperadmin, splitForDisplay, type AttachmentView, type ChatMessageView } from "@peppa/core";
+import { users, type Db } from "@peppa/db";
+import { stripAsIs, translator } from "@peppa/shared/i18n";
+import { eq } from "drizzle-orm";
+import { cleanText, messageLink, STUCK_NOTICE } from "./chat-text";
+import type { LiveChatMessage } from "./chat-live-types";
+
+export async function liveChatView(db: Db, userId: number, messages: ChatMessageView[], files: Map): Promise {
+ const user = (await db.select({ login: users.login }).from(users).where(eq(users.id, userId)))[0];
+ const superadmin = await isSuperadmin(db, user ?? null);
+ const t = translator(await getUserLocale(db, userId));
+ const gitea = (process.env.GITEA_URL ?? "").replace(/\/+$/, "");
+ return messages.map((m) => {
+ // Same as MessageItem / EventLines of the chat page.
+ const shown =
+ m.kind === "user"
+ ? { main: m.authorKind === "agent" ? cleanText(t.role(m.text), superadmin, gitea) : m.text, more: null }
+ : splitForDisplay(cleanText(t.text(m.text), superadmin, gitea), m.details ? t.text(m.details) : null);
+ const label = m.threadTitle ? t.text(m.threadTitle) : null;
+ return {
+ id: m.id,
+ threadKey: m.threadKey,
+ kind: m.kind,
+ authorKind: m.authorKind,
+ authorUserId: m.authorUserId,
+ login: m.authorLogin,
+ agent: m.authorKind === "agent" && m.authorLogin ? t.role(m.authorLogin) : null,
+ via: m.via,
+ at: (m.updatedAt ?? m.createdAt).toISOString(),
+ repeats: m.repeats,
+ command: m.text.startsWith("/"),
+ notice: m.authorKind !== "user" && STUCK_NOTICE.test(stripAsIs(m.text)),
+ main: shown.main,
+ more: shown.more,
+ link: messageLink(m.url, superadmin, gitea),
+ files: files.get(m.id) ?? [],
+ render: !!m.question || !!m.offer,
+ thread: label && m.projectKey && m.threadKey ? { label, href: `/chats/${m.projectKey}?thread=${encodeURIComponent(m.threadKey)}` } : null,
+ };
+ });
+}
diff --git a/apps/web/lib/chat-text.ts b/apps/web/lib/chat-text.ts
index fddf3767..6e86bea3 100644
--- a/apps/web/lib/chat-text.ts
+++ b/apps/web/lib/chat-text.ts
@@ -12,3 +12,13 @@ export function cleanText(text: string, superadmin: boolean, gitea = ""): string
}
const TERMINAL_LINE = /^\s*(?:[⏺⎿●│└├╭╰─━]|\$ |> |✻|Calling\b|Running\b)/;
+
+/** A link under a message: never the bare «/», never Gitea for a product manager. */
+export function messageLink(url: string | null, superadmin: boolean, gitea: string): string | null {
+ if (!url || url === "/" || url === "#") return null;
+ if (!superadmin && gitea && url.startsWith(gitea)) return null;
+ return url;
+}
+
+/** PEP-207: the factory's «задерживается на нашей стороне» — the status line of the chat with the analyst, not a message. */
+export const STUCK_NOTICE = /задерживается на нашей стороне/i;
diff --git a/apps/web/lib/format.tsx b/apps/web/lib/format.tsx
new file mode 100644
index 00000000..f3a21dc9
--- /dev/null
+++ b/apps/web/lib/format.tsx
@@ -0,0 +1,25 @@
+// Formatters of the console shared by server and client components (no server imports).
+import { intlLocale, type Translator } from "@peppa/shared/i18n";
+
+/** «5 мин назад» in the page's language. */
+export function ago(d: Date | null | undefined, t: Translator): string {
+ if (!d) return "—";
+ const s = Math.round((Date.now() - d.getTime()) / 1000);
+ if (s < 60) return t("{n} с назад", { n: s });
+ if (s < 3600) return t("{n} мин назад", { n: Math.round(s / 60) });
+ if (s < 86400) return t("{n} ч назад", { n: Math.round(s / 3600) });
+ return d.toLocaleDateString(intlLocale(t.locale));
+}
+
+/** Text with its http(s) addresses as links. */
+export function linkify(text: string) {
+ return text.split(/(https?:\/\/[^\s<>«»"]+[^\s<>«»".,;:!?)])/g).map((part, i) =>
+ i % 2 ? (
+
+ {part}
+
+ ) : (
+ part
+ ),
+ );
+}
diff --git a/apps/web/lib/live-server.ts b/apps/web/lib/live-server.ts
new file mode 100644
index 00000000..a5e922f1
--- /dev/null
+++ b/apps/web/lib/live-server.ts
@@ -0,0 +1,29 @@
+// PEP-225: the tab's WebSocket, set up inside the Next process (instrumentation.ts) where the
+// web's modules live — the cookie check, navCounts, the boot id. apps/web/server.ts only hands
+// `upgrade` requests of /api/ws to what is registered here (globalThis: the custom server and
+// the Next bundle are different module graphs of one process).
+import { getNotifyPrefs } from "@peppa/core";
+import { setLiveChatView, setLiveProvider } from "@peppa/runner";
+import { createLiveWs, readCookie, type LiveWs } from "@peppa/runner/live-ws";
+import { bootId } from "./boot";
+import { liveChatView } from "./chat-live";
+import { db } from "./db";
+import { navCounts } from "./queries";
+import { SESSION_COOKIE, userFromSessionToken } from "./session-user";
+
+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, questions: c.questions, waitingRunners: c.waitingRunners, chats: c.chats, sound };
+ });
+ setLiveProvider("version", () => ({ boot: bootId() }));
+ setLiveChatView(liveChatView);
+ g.__peppaLiveWs?.close();
+ g.__peppaLiveWs = createLiveWs({
+ db,
+ authenticate: (req) => userFromSessionToken(readCookie(req.headers.cookie, SESSION_COOKIE)),
+ boot: bootId,
+ });
+}
diff --git a/apps/web/lib/live.ts b/apps/web/lib/live.ts
new file mode 100644
index 00000000..46e97e10
--- /dev/null
+++ b/apps/web/lib/live.ts
@@ -0,0 +1,414 @@
+"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 =
+ /** `messages` — new messages of a `chat:` scope, ready for this viewer (PEP-228, lib/chat-live-types.ts). */
+ | { type: "change"; scope: string; v: string; parts: string[]; tasks?: LiveTaskRow[]; messages?: unknown[] }
+ | { type: "step"; scope: string; step: { id: number } & Record }
+ | { 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;
+ /** 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();
+ private ws: WebSocket | null = null;
+ private transport: "ws" | "sse" = "ws";
+ private everOpened = false;
+ private failsBeforeOpen = 0;
+ private attempt = 0;
+ private retry: ReturnType | null = null;
+ private pinger: ReturnType | null = null;
+ private pongTimer: ReturnType | null = null;
+ private es: EventSource | null = null;
+ private esScopes = "";
+ private esTimer: ReturnType | null = null;
+ private terms = new Map();
+ private wsProbe: ReturnType | null = null;
+ private acks = new Map 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 {
+ 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).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).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) => string[];
+const islands = new Set();
+
+/** 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): Set {
+ const done = new Set();
+ for (const fn of islands) {
+ try {
+ for (const p of fn(e)) done.add(p);
+ } catch (err) {
+ console.error("live island:", err);
+ }
+ }
+ return done;
+}
diff --git a/apps/web/lib/session-user.ts b/apps/web/lib/session-user.ts
new file mode 100644
index 00000000..c355f461
--- /dev/null
+++ b/apps/web/lib/session-user.ts
@@ -0,0 +1,23 @@
+// The signed-in user of a session cookie value (PEP-225): the same checks for pages
+// (lib/auth.ts currentUser) and for the tab's WebSocket, which has no `next/headers`.
+import { getUser, isUserAllowed, sessionsValidAfter, verify, type User } from "@peppa/core";
+import { db } from "./db";
+
+export const SESSION_COOKIE = "peppa_session";
+export const SESSION_DAYS = 30;
+
+export interface SessionPayload {
+ uid: number;
+ exp: number;
+}
+
+export async function userFromSessionToken(token: string | undefined): Promise {
+ const p = verify(token);
+ if (!p || p.exp < Date.now()) return null;
+ // PEP-95: «выкинуть всех» — a session issued before the cut-off is no longer valid.
+ const after = await sessionsValidAfter(db);
+ if (after !== null && p.exp - SESSION_DAYS * 86400_000 < after) return null;
+ const user = await getUser(db, p.uid);
+ // Removed from the allowlist → the session stops working right away.
+ return user && (await isUserAllowed(db, user)) ? user : null;
+}
diff --git a/apps/web/next.config.ts b/apps/web/next.config.ts
index c3e1c657..ea9f22c0 100644
--- a/apps/web/next.config.ts
+++ b/apps/web/next.config.ts
@@ -48,7 +48,7 @@ const config: NextConfig = {
return process.env.NODE_ENV === "development" ? [all, { source: "/_next/static/:path*", headers: [{ key: "Cache-Control", value: "private, no-store" }] }, sw] : [all, sw];
},
// PEP-212: the code-mode sandbox (QuickJS wasm) loads its .wasm file itself — it must not be bundled.
- serverExternalPackages: ["quickjs-emscripten"],
+ serverExternalPackages: ["quickjs-emscripten", "ws"],
transpilePackages: ["@peppa/db", "@peppa/shared", "@peppa/core", "@peppa/runner", "@peppa/mcp"],
env: {
NEXT_PUBLIC_PEPPA_VERSION: version,
diff --git a/apps/web/package.json b/apps/web/package.json
index 310ab4eb..1ef0d794 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -4,10 +4,11 @@
"private": true,
"type": "module",
"scripts": {
- "dev": "next dev -p 3100",
+ "dev": "node server.ts --dev -p 3100",
"build": "next build",
- "start": "next start -p 3100",
- "typecheck": "tsc -p ."
+ "start": "node server.ts -p 3100",
+ "typecheck": "tsc -p .",
+ "dev:next": "next dev -p 3100"
},
"dependencies": {
"@modelcontextprotocol/sdk": "1.32.2",
@@ -29,7 +30,8 @@
"quickjs-emscripten": "0.32.0",
"react": "19.3.1",
"react-dom": "19.3.1",
- "tailwind-merge": "3.7.0"
+ "tailwind-merge": "3.7.0",
+ "ws": "8.18.3"
},
"devDependencies": {
"@tailwindcss/postcss": "4.3.5",
diff --git a/apps/web/scripts/bench-live.ts b/apps/web/scripts/bench-live.ts
new file mode 100644
index 00000000..b439e891
--- /dev/null
+++ b/apps/web/scripts/bench-live.ts
@@ -0,0 +1,116 @@
+// PEP-225: load of the tab channel — N tabs (WebSockets) on a COPY of a database, each watching
+// what a tab watches (home or a project board, a story, attention, version, me), while a writer
+// changes story statuses. Reports CPU of the process (hub + sockets), SQLite time of the hub's
+// checks and how fast an event reaches every tab.
+// PEPPA_DB= PEPPA_SECRET=x node apps/web/scripts/bench-live.ts [tabs=50] [seconds=20] [writesPerSec=2]
+import { createServer } from "node:http";
+import type { AddressInfo } from "node:net";
+import { discussionUnread, getNotifyPrefs, getUser, sign, userProjectIds } from "@peppa/core";
+import { createDb } from "@peppa/db";
+import { liveHub, setLiveProvider } from "@peppa/runner";
+import { createLiveWs, readCookie } from "@peppa/runner/live-ws";
+
+const tabs = Number(process.argv[2] ?? 50);
+const seconds = Number(process.argv[3] ?? 20);
+const rate = Number(process.argv[4] ?? 2);
+const db = createDb();
+const c = db.$client;
+
+const owner = c.prepare(`SELECT owner_id AS id FROM projects WHERE owner_id IS NOT NULL AND deleted_at IS NULL GROUP BY owner_id ORDER BY count(*) DESC LIMIT 1`).get() as { id: number };
+const user = (await getUser(db, owner.id))!;
+const projects = c.prepare(`SELECT id FROM projects WHERE owner_id = ? AND deleted_at IS NULL`).all(user.id) as Array<{ id: number }>;
+const taskRows = c.prepare(`SELECT id, project_id AS p, status FROM tasks WHERE project_id IN (${projects.map((p) => p.id).join(",")}) AND archived_at IS NULL LIMIT 40`).all() as Array<{ id: number; p: number; status: string }>;
+if (!taskRows.length) throw new Error("no tasks to change");
+
+setLiveProvider("attention", async (_db, uid) => {
+ // The queries of navCounts (lib/queries.ts needs the Next bundler for its imports).
+ const ids = await userProjectIds(db, uid);
+ const q = ids.length ? (c.prepare(`SELECT count(*) AS n FROM questions WHERE answered_at IS NULL AND project_id IN (${ids.join(",")})`).get() as { n: number }).n : 0;
+ const w = ids.length ? (c.prepare(`SELECT count(*) AS n FROM sessions WHERE status = 'waiting_input' AND project_id IN (${ids.join(",")})`).get() as { n: number }).n : 0;
+ const chats = [...(await discussionUnread(db, uid)).values()].reduce((a, b) => a + b, 0);
+ const { sound } = await getNotifyPrefs(db, uid);
+ return { count: q + w, chats, sound };
+});
+const token = sign({ uid: user.id, exp: Date.now() + 3600_000 });
+const ws = createLiveWs({ db, authenticate: async (req) => (readCookie(req.headers.cookie, "peppa_session") === token ? user : null), boot: () => "bench" });
+const server = createServer((_q, r) => r.end());
+server.on("upgrade", (q, s, h) => ws.handleUpgrade(q, s, h));
+await new Promise((r) => server.listen(0, "127.0.0.1", r));
+const port = (server.address() as AddressInfo).port;
+
+// Every change: when it was written, when each tab got it.
+const written = new Map();
+const lat: number[] = [];
+let events = 0;
+const socks: WebSocket[] = [];
+for (let i = 0; i < tabs; i++) {
+ const t = taskRows[i % taskRows.length]!;
+ const scopes = i % 3 === 0 ? ["home", "attention", "version", "me"] : ["attention", "version", "me", `project:${t.p}`, `task:${t.id}`];
+ const sock = new (WebSocket as unknown as new (u: string, o: object) => WebSocket)(`ws://127.0.0.1:${port}/api/ws`, { headers: { cookie: `peppa_session=${token}` } });
+ sock.onopen = () => scopes.forEach((scope) => sock.send(JSON.stringify({ t: "sub", scope })));
+ sock.onmessage = (e) => {
+ const m = JSON.parse(String(e.data)) as { t: string; type?: string; tasks?: Array<{ id: number; status: string }> };
+ if (m.t !== "ev") return;
+ events++;
+ for (const r of m.tasks ?? []) {
+ const at = written.get(`${r.id}:${r.status}`);
+ if (at) lat.push(performance.now() - at);
+ }
+ };
+ socks.push(sock);
+}
+await new Promise((r) => setTimeout(r, 1500));
+console.log(`tabs: ${tabs} open=${ws.clients}, watched scopes: ${liveHub(db).watched.length}`);
+
+// Time spent in the hub's checks (SQLite fingerprints + providers).
+const hub = liveHub(db) as unknown as { check: () => Promise };
+const orig = hub.check.bind(hub);
+let checkMs = 0;
+let checks = 0;
+hub.check = async () => {
+ const t = performance.now();
+ await orig();
+ checkMs += performance.now() - t;
+ checks++;
+};
+
+// Time per scope kind (BENCH_SCOPES=1).
+const perKind = new Map();
+if (process.env.BENCH_SCOPES) {
+ const h = liveHub(db) as unknown as { checkOne: (w: { scope: string }) => Promise };
+ const one = h.checkOne.bind(h);
+ h.checkOne = async (w) => {
+ const t = performance.now();
+ await one(w);
+ const k = w.scope.split(":")[0]!;
+ perKind.set(k, (perKind.get(k) ?? 0) + performance.now() - t);
+ };
+}
+const cpu0 = process.cpuUsage();
+const t0 = performance.now();
+const statuses = ["in_progress", "review", "backlog"];
+let writes = 0;
+const writer = setInterval(() => {
+ const t = taskRows[writes % taskRows.length]!;
+ const next = statuses[(statuses.indexOf(t.status) + 1) % statuses.length]!;
+ t.status = next;
+ written.set(`${t.id}:${next}`, performance.now());
+ c.prepare(`UPDATE tasks SET status = ?, updated_at = ? WHERE id = ?`).run(next, Date.now(), t.id);
+ writes++;
+}, 1000 / rate);
+await new Promise((r) => setTimeout(r, seconds * 1000));
+clearInterval(writer);
+await new Promise((r) => setTimeout(r, 1500));
+const cpu = process.cpuUsage(cpu0);
+const wall = performance.now() - t0;
+lat.sort((a, b) => a - b);
+const pct = (p: number) => (lat.length ? lat[Math.min(lat.length - 1, Math.floor(lat.length * p))]!.toFixed(0) : "-");
+console.log(`writes: ${writes} in ${seconds}s, events delivered: ${events}, hub checks: ${checks} (${(checkMs / Math.max(1, checks)).toFixed(1)} ms each, ${((checkMs / wall) * 100).toFixed(1)}% of wall time)`);
+console.log(`CPU: ${(((cpu.user + cpu.system) / 1000 / wall) * 100).toFixed(1)}% of one core (user ${(cpu.user / 1000).toFixed(0)} ms, system ${(cpu.system / 1000).toFixed(0)} ms)`);
+console.log(`write → tab latency: p50 ${pct(0.5)} ms, p95 ${pct(0.95)} ms, max ${pct(0.999)} ms (${lat.length} deliveries)`);
+if (perKind.size) console.log("ms per scope kind:", Object.fromEntries([...perKind].map(([k, v]) => [k, Math.round(v)])));
+for (const s of socks) s.close();
+ws.close();
+server.close();
+// Restore nothing: run it on a copy only.
+process.exit(0);
diff --git a/apps/web/server.ts b/apps/web/server.ts
new file mode 100644
index 00000000..0287c685
--- /dev/null
+++ b/apps/web/server.ts
@@ -0,0 +1,40 @@
+// The web's own server (PEP-225): Next.js 16 does not accept WebSockets, so this wraps it —
+// plain HTTP goes to Next, `upgrade` on /api/ws to the tab's live channel that
+// instrumentation.ts registered (lib/live-server.ts), other upgrades (dev HMR) to Next.
+// Usage: node server.ts [--dev] [-p 3100]
+import { createServer } from "node:http";
+import type { Duplex } from "node:stream";
+
+const dev = process.argv.includes("--dev");
+const pIdx = process.argv.indexOf("-p");
+const port = Number(pIdx > 0 ? process.argv[pIdx + 1] : (process.env.PORT ?? 3100));
+const env = process.env as Record;
+env.NODE_ENV ??= dev ? "development" : "production";
+
+const { default: next } = await import("next");
+const app = next({ dev, dir: import.meta.dirname, port, hostname: "localhost" });
+const handle = app.getRequestHandler();
+await app.prepare();
+const nextUpgrade = app.getUpgradeHandler();
+
+type LiveWs = { handleUpgrade(req: import("node:http").IncomingMessage, socket: Duplex, head: Buffer): void };
+const live = () => (globalThis as { __peppaLiveWs?: LiveWs }).__peppaLiveWs;
+
+const server = createServer((req, res) => void handle(req, res));
+server.on("upgrade", (req, socket: Duplex, head: Buffer) => {
+ if (req.url?.split("?")[0] === "/api/ws") {
+ const ws = live();
+ if (ws) return ws.handleUpgrade(req, socket, head);
+ socket.end("HTTP/1.1 503 Service Unavailable\r\nConnection: close\r\nContent-Length: 0\r\n\r\n");
+ return;
+ }
+ void nextUpgrade(req, socket, head);
+});
+server.listen(port, () => console.log(`peppa web: http://localhost:${port} (${dev ? "dev" : "production"}, WebSocket /api/ws)`));
+
+const shutdown = () => {
+ server.close();
+ setTimeout(() => process.exit(0), 3000).unref();
+};
+process.on("SIGTERM", shutdown);
+process.on("SIGINT", shutdown);
diff --git a/openspec/changes/archive/2026-11-20-pep-225-live-websocket/design.md b/openspec/changes/archive/2026-11-20-pep-225-live-websocket/design.md
new file mode 100644
index 00000000..037e347b
--- /dev/null
+++ b/openspec/changes/archive/2026-11-20-pep-225-live-websocket/design.md
@@ -0,0 +1,95 @@
+# Design: PEP-225
+
+## Где поднимается WebSocket
+**Решение: свой сервер `apps/web/server.ts` в том же процессе, что и Next.**
+`next({ dev })` + `getRequestHandler()` для HTTP, событие `upgrade` на пути `/api/ws` отдаётся
+обработчику канала, остальные `upgrade` — `getUpgradeHandler()` Next (HMR в разработке).
+
+Почему так:
+- хаб (`liveHub`), ленты терминала (`TerminalFeed`) и база уже живут в процессе веба на
+ `globalThis` — второй процесс дублировал бы циклы опроса и соединения с базой;
+- проверка входа и прав — тот же код, что у страниц; ничего не нужно в Traefik (путь тот же
+ домен, Cloudflare пропускает WebSocket);
+- не нужен ещё один launchd-агент, heartbeat и мониторинг.
+
+Отклонено:
+- отдельный сервис `peppa-live` за Traefik по пути `/api/ws`: ещё один процесс, маршрут,
+ перезапуск в `live-deploy.sh`, мониторинг, и всё равно нужен доступ к лентам терминала;
+- перехват `upgrade` у сервера `next start` из `instrumentation.ts`: не документировано,
+ сломается при обновлении Next.
+
+Логика канала (вход, права, протокол) регистрируется из `instrumentation.ts` на `globalThis`
+(`__peppaLiveWs`), там доступны модули веба (`navCounts`, проверка cookie). `server.ts` знает
+только `next` и `node:http`: если обработчика нет, сокет закрывается — клиент уходит на SSE.
+`next dev` без своего сервера по-прежнему работает: WebSocket не откроется, страницы живут на SSE.
+
+Библиотека — `ws` 8.18.3 (`serverExternalPackages`, без нативных модулей): в Node 26 есть только
+клиент WebSocket. `perMessageDeflate` выключен (CPU), `maxPayload` 300 КБ (вставка 64 КБ в JSON).
+
+## Протокол (JSON-сообщения)
+Клиент → сервер: `{t:"sub", scope, since?}`, `{t:"unsub", scope}`,
+`{t:"in", scope:"terminal:", keys?|paste?, id}`, `{t:"ping"}`.
+Сервер → клиент: `{t:"hello", boot}`, `{t:"ok", scope}`, `{t:"err", scope?, status, error}`,
+`{t:"ev", scope, ...событие}`, `{t:"ack", id, error?}`, `{t:"pong"}`.
+
+События области (одни и те же в WebSocket и в SSE):
+- `change` `{v, parts, tasks?}` — `v` — короткий хэш отпечатка (версия области), `parts` — какие
+ части отпечатка изменились, `tasks` — изменившиеся строки задач `{id, status, title, column}`;
+- `step` — шаг агента (как раньше), `since` для `steps:` — id последнего шага;
+- `data` `{data}` — снимок для областей-значений (`attention` — `{count, sound}`, `version` —
+ `{boot}`); при подписке сразу отдаётся текущий снимок;
+- `frame` / `out` / `end` — терминал (как в SSE PEP-9).
+
+Догон после обрыва: клиент помнит `v` каждой области и шлёт его в `since`; хаб сравнивает с
+текущим отпечатком и при расхождении сразу шлёт `change` (с `parts: ["*"]`). Для `steps:` —
+шаги после `since`; области-значения и терминал отдают снимок при каждой подписке.
+
+## Точечные обновления
+Хаб для `project:` и `task:` держит лёгкий снимок строк задач (`id, status, title, position,
+updated_at`) и отдаёт разницу в `tasks`. Клиент (`lib/live.ts`) раздаёт события «островам»:
+- доска (`Board`) правит карточки: статус, название, колонку — карточка переезжает сама;
+- шапка задачи (`LiveStatus`) — статус;
+- счётчик «ждут вас» и заголовок вкладки — `attention`;
+- шаги агента, терминал — как данные.
+`LiveRefresh` пропускает серверный рендер, если каждая изменившаяся часть закрыта островами
+(`parts` ⊆ части, которые острова объявили своими, и все строки задач применены). Иначе — прежний
+`router.refresh()` не чаще раза в 4 с (PEP-215), с ожиданием, пока человек печатает.
+Чаты: событие `chats` несёт id чатов с новыми сообщениями — страница чата обновляется, только
+если новое пришло в её чат.
+
+## Области без опроса в браузере
+- `observe` (суперадмин): отпечаток — состояния и пауза мониторингов, последний сбой и минута
+ последней проверки (полоса проверок обновляется не чаще раза в минуту).
+- `subs` (суперадмин): строки подписок (статус, обновление), займы.
+- `login:`: вход в подписку ждёт автор или суперадмин. Пока область смотрят,
+ хаб сам раз в 3 с вызывает `pollCodexLogin` (один цикл на подписку для всех зрителей) — опрос
+ ChatGPT переехал из рендера страницы на сервер.
+- `me`: привязка Telegram и свой бот пользователя (кнопка «Открыть бота» ждёт `/start`).
+- `version`: снимок `boot` при подписке; после перезапуска веба клиент переподключается и видит
+ новый `boot` — плашка «обновите страницу».
+
+## Надёжность
+- Сервер шлёт ping-кадр раз в 15 с и закрывает соединение без pong 2 раза подряд; клиент шлёт
+ `{t:"ping"}` раз в 15 с и переподключается, не получив `pong` за 10 с (Cloudflare рвёт
+ простаивающие соединения через 100 с).
+- Переподключение: 1, 2, 4 … 30 с со случайной добавкой; после переподключения — повторная
+ подписка с `since`.
+- WebSocket не открылся 3 раза подряд, ни разу не открывшись (или его нет в браузере) — запасной
+ путь: SSE `/api/live` (все области, кроме терминала) и SSE терминала с POST-вводом; раз в
+ минуту — новая попытка WebSocket.
+- Скрытая вкладка отписывается от тяжёлых областей (терминал, шаги, `team`) и подписывается
+ снова при возврате (с `since`).
+
+## Безопасность
+- Без входа — 401 до апгрейда; `Origin` должен совпадать с `Host`/`X-Forwarded-Host`.
+- Права на область — `checkScopeAccess` (проект — `projectForUser`; `observe`, `subs` —
+ суперадмин; `login:` — автор подписки или суперадмин; `terminal:` — `terminalSession`).
+- Не больше 32 областей на соединение, 60 сообщений за 5 с (иначе закрытие 1008), сообщение
+ ≤ 300 КБ; ввод в терминал — `terminalInput` (владелец/участник, живая сессия, лимиты PEP-9),
+ зрители терминала — `acquireViewer`.
+- Чужой текст (терминал, шаги) уходит как данные JSON, клиент вставляет его текстом.
+
+## Нагрузка
+Как раньше: один цикл хаба на процесс, отпечаток каждой области считается раз на изменение базы
+для всех её зрителей, один `TerminalFeed` на pane. `attention` считается по пользователю, только
+когда изменились вопросы, сессии или чаты. Замер 50 вкладок — `apps/web/scripts/bench-live.ts`.
diff --git a/openspec/changes/archive/2026-11-20-pep-225-live-websocket/proposal.md b/openspec/changes/archive/2026-11-20-pep-225-live-websocket/proposal.md
new file mode 100644
index 00000000..f0182e26
--- /dev/null
+++ b/openspec/changes/archive/2026-11-20-pep-225-live-websocket/proposal.md
@@ -0,0 +1,31 @@
+# PEP-225: один живой канал на вкладку
+
+## Зачем
+Живые страницы (PEP-37) держат по SSE-потоку на страницу, шаги агента и терминал — свои потоки,
+а счётчик «ждут вас», проверка новой версии, observability, подписки и ожидание входа опрашивают
+сервер по таймеру. В одной вкладке 2–4 соединения со своими пингами, а любое изменение области
+перерисовывает всю страницу на сервере (доска — секунды).
+
+## Что меняется
+- Один WebSocket на вкладку: `GET /api/ws` (upgrade), вход — cookie `peppa_session`, `Origin` —
+ только свой домен. Внутри — подписки на области и ответы сервера; источник событий — прежний
+ хаб `runner/live.ts`.
+- Веб запускается своим маленьким сервером `apps/web/server.ts` (Next.js 16 сам WebSocket не
+ поднимает): тот же процесс, тот же хаб, та же база.
+- Новые области: `attention` (счётчик «ждут вас»), `version` (перезапуск веба), `observe`
+ (мониторинги), `subs` (подписки суперадмина), `login:` (ожидание входа в подписку),
+ `me` (привязка Telegram), `terminal:` (вывод и ввод терминала).
+- События несут, что изменилось: части отпечатка и строки задач (`id`, статус, название,
+ колонка). Доска и шапка задачи применяют их на месте; серверный рендер — только для того, что
+ на месте применить нельзя, не чаще раза в 4 с.
+- Из веб-клиента уходят все опросы данных по таймеру (`AutoRefresh`, `setInterval` в
+ `AttentionBadge`, `VersionWatch`, `OpenBotButton`, `SubscriptionSetup`). Опрос входа ChatGPT
+ делает сервер — один цикл на подписку для всех зрителей.
+- Надёжность: пинг 15 с, переподключение с нарастающей паузой, догон пропущенного по версии
+ области, запасной путь — прежний SSE (`/api/live` и SSE терминала).
+
+## Влияние
+- `packages/runner/src/live.ts`, новый `live-ws.ts`; `apps/web/server.ts`, `lib/live.ts`,
+ компоненты живых страниц; `scripts/install-launchd.sh`, `scripts/live-deploy.sh`.
+- Новая зависимость `ws` (сервер WebSocket; в Node есть только клиент).
+- Спеки: `live-updates`, `runner-terminal`.
diff --git a/openspec/changes/archive/2026-11-20-pep-225-live-websocket/specs/live-updates/spec.md b/openspec/changes/archive/2026-11-20-pep-225-live-websocket/specs/live-updates/spec.md
new file mode 100644
index 00000000..4c8017aa
--- /dev/null
+++ b/openspec/changes/archive/2026-11-20-pep-225-live-websocket/specs/live-updates/spec.md
@@ -0,0 +1,112 @@
+## ADDED Requirements
+
+### Requirement: Один WebSocket на вкладку
+Веб SHALL принимать WebSocket `GET /api/ws` и вести через одно соединение вкладки подписки на все
+живые области: `home`, `runners`, `team`, `chats`, `project:`, `task:`, `steps:`,
+`terminal:`, `attention`, `version`, `observe`, `subs`, `login:`, `me`.
+Вход — cookie `peppa_session` с теми же проверками, что у страниц; соединение с чужим `Origin`
+или без входа MUST быть отклонено до апгрейда. Права на область — как у страницы: проект — доступ
+к проекту, `observe` и `subs` — суперадмин, `login:` — автор подписки или суперадмин.
+
+#### Scenario: Подписка без прав
+- **GIVEN** пользователь «anna» без доступа к проекту PAY открыл WebSocket
+- **WHEN** он подписывается на `task:`
+- **THEN** сервер отвечает `{t:"err", scope:"task:", status:404}`
+- **AND** события PAY-3 ему не приходят
+
+#### Scenario: Событие доходит только до своей области
+- **GIVEN** у вкладки подписки `task:` и `attention`
+- **WHEN** PAY-4 меняет статус
+- **THEN** для `task:` ничего не приходит
+- **AND** когда меняется статус PAY-3, приходит `change` с строкой задачи `status: "review"`
+
+#### Scenario: Чужой сайт
+- **WHEN** страница с другого домена открывает `wss://peppa.telecom.quest/api/ws` с cookie пользователя
+- **THEN** сервер отвечает 403, соединение не открывается
+
+### Requirement: Догон после обрыва
+Клиент SHALL помнить версию каждой области (`v` из последнего события) и после переподключения
+подписываться заново с `since`; сервер MUST сразу прислать `change`, если область изменилась,
+пока клиента не было, и шаги агента после `since` для `steps:`.
+
+#### Scenario: Связь пропала на минуту
+- **GIVEN** вкладка подписана на `project:` и получила версию `v1`
+- **WHEN** соединение рвётся, PAY-3 уходит в ревью, вкладка переподключается с `since: v1`
+- **THEN** сразу приходит `change` для `project:`
+
+#### Scenario: Ничего не изменилось
+- **GIVEN** вкладка переподключается с `since`, равным текущей версии области
+- **WHEN** сервер принимает подписку
+- **THEN** `change` не приходит
+
+### Requirement: Точечные обновления вместо перерисовки
+Событие `change` SHALL нести, что изменилось: части отпечатка (`parts`) и для `project:`/`task:` —
+изменившиеся строки задач (`id`, статус, название, колонка). Доска MUST переносить карточку в
+колонку нового статуса и менять название на месте; шапка задачи — статус. Серверный рендер
+страницы делается, только если изменилась часть, которую страница на месте применить не может,
+и не чаще раза в 4 секунды.
+
+#### Scenario: Задача ушла в ревью
+- **GIVEN** открыта доска PAY, PAY-3 в колонке «В работе»
+- **WHEN** агент переводит PAY-3 в ревью и больше ничего не меняется
+- **THEN** карточка PAY-3 за долю секунды оказывается в колонке «Ревью»
+- **AND** серверный рендер страницы не запрашивается
+
+#### Scenario: Изменилось то, что на месте не применить
+- **GIVEN** открыта доска PAY
+- **WHEN** появляется новый релиз проекта
+- **THEN** страница перерисовывается с сервера не позже чем через 4 секунды после прошлой перерисовки
+
+### Requirement: Без опросов по таймеру в браузере
+Веб-клиент SHALL NOT опрашивать данные по таймеру: счётчик «ждут вас» и заголовок вкладки,
+проверка новой версии, observability, подписки, ожидание входа в подписку и ожидание привязки
+Telegram обновляются событиями канала. Опрос входа ChatGPT MUST делать сервер — один цикл на
+подписку, пока её кто-то ждёт. Остаётся только проверка связи.
+
+#### Scenario: Вопрос агента
+- **GIVEN** у пользователя открыта любая страница, в заголовке «(1) …»
+- **WHEN** агент его проекта задаёт вопрос
+- **THEN** в заголовке вкладки становится «(2) …» без перезагрузки страницы
+
+#### Scenario: Веб перезапустили
+- **GIVEN** вкладка открыта до перезапуска веба
+- **WHEN** веб перезапускается с новой версией и вкладка переподключается
+- **THEN** появляется плашка «Peppa FACTORY обновилась. Обновите страницу…»
+
+#### Scenario: Вход в ChatGPT подтверждён
+- **GIVEN** владелец ждёт на странице подключения ChatGPT
+- **WHEN** ChatGPT подтверждает вход
+- **THEN** страница показывает подключённую подписку без нажатий, за несколько секунд
+
+### Requirement: Надёжность канала
+Канал SHALL пинговаться раз в 15 секунд в обе стороны, переподключаться с нарастающей паузой
+(1 → 30 с) и показывать состояние связи. Если WebSocket не открылся три раза подряд, клиент MUST
+перейти на SSE (`/api/live`, SSE терминала) и раз в минуту пробовать WebSocket снова. Скрытая
+вкладка отписывается от терминала, шагов агента и `team` и подписывается снова при возврате.
+
+#### Scenario: Корпоративный прокси режет WebSocket
+- **GIVEN** апгрейд до WebSocket не проходит
+- **WHEN** вкладка открывает доску
+- **THEN** после трёх попыток индикатор показывает «в реальном времени» через SSE и доска живая
+
+#### Scenario: Сообщения шлются слишком часто
+- **WHEN** клиент шлёт больше 60 сообщений за 5 секунд
+- **THEN** сервер закрывает соединение с кодом 1008
+
+## MODIFIED Requirements
+
+### Requirement: Точечное обновление страницы и индикатор связи
+Страницы Главная, проект, стори, раннеры, команда, чаты, подписки и observability SHALL
+обновляться по событиям канала без перезагрузки и без потери введённого текста (серверный рендер
+откладывается, пока пользователь печатает или оставил черновик), и показывать состояние связи:
+«в реальном времени», «переподключение» или «нет связи». Если WebSocket недоступен, страница
+работает через SSE `/api/live`; опроса по таймеру нет.
+
+#### Scenario: Черновик ответа
+- **GIVEN** PM печатает ответ на вопрос на странице стори
+- **WHEN** приходит `change`, который нельзя применить на месте
+- **THEN** текст не теряется, страница обновится, когда поле отправят или очистят
+
+#### Scenario: Канал недоступен
+- **WHEN** ни WebSocket, ни `/api/live` не открываются
+- **THEN** индикатор показывает «нет связи», клиент пробует снова с нарастающей паузой
diff --git a/openspec/changes/archive/2026-11-20-pep-225-live-websocket/specs/runner-terminal/spec.md b/openspec/changes/archive/2026-11-20-pep-225-live-websocket/specs/runner-terminal/spec.md
new file mode 100644
index 00000000..aca028af
--- /dev/null
+++ b/openspec/changes/archive/2026-11-20-pep-225-live-websocket/specs/runner-terminal/spec.md
@@ -0,0 +1,17 @@
+## ADDED Requirements
+
+### Requirement: Терминал через общий канал
+Вывод терминала раннера SHALL идти через WebSocket вкладки (область `terminal:`:
+`frame`, `out`, `end`), ввод — сообщением `{t:"in", keys|paste}` того же соединения с прежними
+правилами: только владелец или участник проекта, живая сессия, ≤1 КБ нажатий, ≤64 КБ вставки,
+40 запросов за 5 с. Без WebSocket терминал работает через прежние SSE и POST.
+
+#### Scenario: Ввод через сокет
+- **GIVEN** участник проекта подписан на `terminal:` живой сессии
+- **WHEN** он шлёт `{t:"in", scope:"terminal:", keys:"ls\r", id:1}`
+- **THEN** нажатия уходят в pane, приходит `{t:"ack", id:1}`
+
+#### Scenario: Ввод в завершённую сессию
+- **GIVEN** сессия завершена
+- **WHEN** приходит `{t:"in", …, id:2}`
+- **THEN** приходит `{t:"ack", id:2, error:"…"}`, в pane ничего не уходит
diff --git a/openspec/changes/archive/2026-11-20-pep-225-live-websocket/tasks.md b/openspec/changes/archive/2026-11-20-pep-225-live-websocket/tasks.md
new file mode 100644
index 00000000..e7eeb0dc
--- /dev/null
+++ b/openspec/changes/archive/2026-11-20-pep-225-live-websocket/tasks.md
@@ -0,0 +1,17 @@
+## 1. Сервер
+- [x] 1.1 Хаб: новые области (`attention`, `version`, `observe`, `subs`, `login:`, `me`), `parts` и строки задач в `change`, версия `v` и `since`, поставщики данных от веба
+- [x] 1.2 `runner/live-ws.ts`: протокол, права, лимиты, пинг, терминал через сокет
+- [x] 1.3 `apps/web/server.ts` + регистрация канала в `instrumentation.ts`, проверка cookie без `next/headers`
+- [x] 1.4 Запуск: `package.json`, `install-launchd.sh`, `live-deploy.sh` (переустановка агента веба)
+
+## 2. Клиент
+- [x] 2.1 `lib/live.ts`: одно соединение, подписки со счётчиком, переподключение, догон, SSE-запасной путь, скрытая вкладка
+- [x] 2.2 `LiveRefresh` на канале: острова, пропуск рендера, индикатор
+- [x] 2.3 Доска и шапка задачи — точечно; чаты — только свой чат
+- [x] 2.4 `AttentionBadge`, `VersionWatch`, `AgentSteps`, `RunnerTerminal` на канале
+- [x] 2.5 Убрать `AutoRefresh` и опросы: observability, подписки, `SubscriptionSetup`, `OpenBotButton`
+
+## 3. Проверка
+- [x] 3.1 Тесты: права, своя/чужая область, догон, терминал через сокет, лимиты
+- [x] 3.2 Замер 50 вкладок (`scripts/bench-live.ts`), цифры в PR
+- [x] 3.3 typecheck, lint, тесты; браузер (в том числе узкий экран и обрыв связи)
diff --git a/openspec/changes/archive/2026-11-21-pep-228-chat-messages-in-place/design.md b/openspec/changes/archive/2026-11-21-pep-228-chat-messages-in-place/design.md
new file mode 100644
index 00000000..0fad7029
--- /dev/null
+++ b/openspec/changes/archive/2026-11-21-pep-228-chat-messages-in-place/design.md
@@ -0,0 +1,41 @@
+## Context
+PEP-225 дал вкладке один канал и «острова» (`useLiveIsland`): событие `change` применяется на
+месте, иначе `LiveRefresh` делает `router.refresh()` не чаще раза в 4 с. Чат проекта слушал общую
+область `chats` и перерисовывался на каждое новое сообщение своего чата (`e.chats`).
+
+## Decisions
+1. **Своя область `chat:`, на зрителя.** Сообщение, готовое к показу, зависит от зрителя:
+ язык (`getUserLocale`), суперадмин видит текст без чистки (`cleanText`), «вы» у своих. Поэтому
+ область ключуется зрителем, как `attention`/`me` (`PER_USER` теперь и по префиксу `chat:`).
+ Отпечаток — один SQL по чату: `m` — последнее сообщение, `q` — вопросы проекта, `tg` — связь с
+ группой, `x` — предложения и вложения 50 последних сообщений (они пишутся отдельной записью
+ после сообщения). Доступ: чат проекта — `projectForUser`, мастер-чат — только его владелец.
+2. **Сообщение готовит сервер, рисует клиент.** Хаб берёт новые сообщения (`newChatMessagesView`,
+ не больше 30 за раз; больше — без сообщений, страница перерисуется) и вложения, а вид для
+ зрителя строит поставщик веба `setLiveChatView` (как `attention`): перевод `t.text`/`t.role`,
+ `cleanText`, `splitForDisplay`, `messageLink` — тот же код, что у серверной страницы (вынесен
+ в `lib/chat-text.ts`). Так перевод и чистка не едут в браузер (словари, ядро), а событие несёт
+ данные, не HTML: текст в браузере — текстовые узлы React, ссылки — только http(s).
+ Без поставщика (тесты хаба) — сырые поля сообщения.
+3. **Что рисуется на месте.** Клиент (`ChatLiveFeed`) отбирает сообщения своей переписки по тем же
+ правилам, что запросы страницы: обсуждение — канал, `kind: user`, не команда; тред — его ключ;
+ «События агентов» — всё. Часть `m` применена на месте, если все новые сообщения — из этой
+ переписки и среди них нет вопроса или предложения (`render`). Часть `x` считается применённой,
+ если в том же событии пришли сообщения (их вложения и предложения уже в них), иначе —
+ перерисовка (вложение/кнопки пришли к уже показанному). `q`, `tg`, `*` — перерисовка.
+ Сообщения другого треда — перерисовка: меняется список слева (последняя реплика, непрочитанное).
+4. **Без дублей.** Клиент держит дорисованные сообщения с `id` больше последнего, что нарисовал
+ сервер (`lastId`); после перерисовки они уходят из состояния клиента — их рисует сервер.
+5. **Прочитано.** Дорисованное в видимой вкладке отмечается прочитанным действием
+ `markChatReadAction` (обсуждение — `markDiscussionRead`, тред — `markThreadRead`), не чаще раза
+ в секунду; иначе счётчик «нов.» показывал бы уже прочитанное.
+6. **«печатает…»** — клиентский: скрывается, когда в обсуждении дорисовано сообщение не от людей.
+7. **Мастер-чат** остаётся на `chats` с перерисовкой: в нём смешаны проекты и `important`,
+ а пишут туда редко. `chatsAfter`/`e.chats` и `LiveRefresh chatId` удалены.
+
+## Risks / Trade-offs
+- Список тредов слева не обновляется от сообщений открытой переписки до следующей перерисовки —
+ осознанно: иначе каждая реплика снова перерисовывала бы страницу.
+- Язык зрителя без сохранённого выбора — русский (как `getUserLocale`), хотя страница могла взять
+ язык из cookie; вход переносит cookie в настройку (`adoptLocale`), так что расхождение редкое.
+- Время «N мин назад» у дорисованного считает браузер.
diff --git a/openspec/changes/archive/2026-11-21-pep-228-chat-messages-in-place/proposal.md b/openspec/changes/archive/2026-11-21-pep-228-chat-messages-in-place/proposal.md
new file mode 100644
index 00000000..fec75ff7
--- /dev/null
+++ b/openspec/changes/archive/2026-11-21-pep-228-chat-messages-in-place/proposal.md
@@ -0,0 +1,27 @@
+## Why
+После PEP-225 страница чата узнаёт о новом сообщении своего чата через канал вкладки, но
+показывает его серверной перерисовкой всей страницы — не чаще раза в 4 секунды. Ответ
+аналитика или реплика агента появляются с задержкой, страница целиком пересобирается на сервере.
+
+## What Changes
+- Новая область канала `chat:` — один чат проекта для одного зрителя (права — как у страницы
+ чата). Событие `change` несёт новые сообщения чата уже готовыми к показу этому зрителю: автор,
+ текст (переведённый и очищенный, как на странице), «Подробнее», вложения, ссылка, вид, тред.
+- Страница чата проекта дорисовывает сообщения своей переписки в ленту на месте, сразу, без
+ перерисовки; отмечает их прочитанными; убирает «печатает…», когда ответил аналитик.
+- Серверная перерисовка остаётся для того, что на месте не нарисовать: вопрос и «готово» (карточки
+ с кнопками), предложение аналитика с кнопками, сообщения других тредов (список слева), ответ на
+ вопрос, вложение или предложение, пришедшее к уже показанному сообщению, привязка Telegram.
+- «Все события» (мастер-чат) — как раньше, область `chats`. Список чатов с новыми сообщениями в
+ событии `chats` и фильтр по чату в `LiveRefresh` больше не нужны — убираются.
+
+## Capabilities
+### Modified Capabilities
+- `live-updates`: область `chat:` и сообщения чата на месте.
+
+## Impact
+- `packages/runner/src/live.ts` (область, отпечаток, сообщения в событии, поставщик вида),
+ `packages/core/src/chats.ts` (`newChatMessagesView`), `packages/shared` (`humanSize` без ядра).
+- `apps/web`: `lib/live-server.ts` (поставщик вида сообщения), `lib/chat-text.ts`,
+ `components/ChatLiveFeed.tsx` (новый), страница `/chats/[chat]`, `LiveRefresh`.
+- Основа — PEP-225 (ветка ещё не в main: эта ветка начата от неё).
diff --git a/openspec/changes/archive/2026-11-21-pep-228-chat-messages-in-place/specs/live-updates/spec.md b/openspec/changes/archive/2026-11-21-pep-228-chat-messages-in-place/specs/live-updates/spec.md
new file mode 100644
index 00000000..10a58b0d
--- /dev/null
+++ b/openspec/changes/archive/2026-11-21-pep-228-chat-messages-in-place/specs/live-updates/spec.md
@@ -0,0 +1,38 @@
+## ADDED Requirements
+
+### Requirement: Сообщения чата на месте
+Канал SHALL давать область `chat:` — чат проекта для одного зрителя (участник проекта или
+суперадмин; мастер-чат — только его владелец, иначе 404). Событие `change` этой области MUST
+нести новые сообщения чата, готовые к показу этому зрителю: автор, текст на его языке и очищенный
+как на странице, «Подробнее», вложения, ссылка, вид и тред. Страница чата проекта SHALL
+дорисовывать сообщения своей переписки в ленту сразу, без серверной перерисовки, и отмечать их
+прочитанными. Серверная перерисовка (не чаще раза в 4 с) остаётся для вопросов и «готово»,
+предложений с кнопками, сообщений других тредов и ответов на вопросы.
+
+#### Scenario: Ответ аналитика появляется сразу
+- **GIVEN** владелец проекта PAY открыл «Чат с аналитиком» и написал «Что сейчас в работе?»
+- **WHEN** аналитик отвечает «В работе PAY-3»
+- **THEN** ответ появляется внизу ленты за долю секунды, а «печатает…» пропадает
+- **AND** серверная перерисовка страницы не запрашивается
+- **AND** счётчик новых сообщений чата PAY не растёт
+
+#### Scenario: Вопрос агента — карточкой
+- **GIVEN** открыт тред задачи PAY-3
+- **WHEN** агент PAY-3 задаёт вопрос с вариантами «Да» и «Нет»
+- **THEN** страница перерисовывается с сервера и показывает карточку вопроса с кнопками
+
+#### Scenario: Сообщение другого треда
+- **GIVEN** открыт тред задачи PAY-3
+- **WHEN** приходит сообщение в тред PAY-4
+- **THEN** в ленте PAY-3 оно не появляется
+- **AND** страница перерисовывается, чтобы обновить список слева
+
+#### Scenario: Чужой чат
+- **GIVEN** пользователь «bob» не участник проекта PAY
+- **WHEN** он подписывается на `chat:`
+- **THEN** ответ 404, сообщения PAY к нему не приходят
+
+#### Scenario: Сообщение другого чата
+- **GIVEN** владелец подписан на `chat:`
+- **WHEN** новое сообщение появляется в чате проекта SHOP
+- **THEN** событие `change` для чата PAY не приходит
diff --git a/openspec/changes/archive/2026-11-21-pep-228-chat-messages-in-place/tasks.md b/openspec/changes/archive/2026-11-21-pep-228-chat-messages-in-place/tasks.md
new file mode 100644
index 00000000..180b97a9
--- /dev/null
+++ b/openspec/changes/archive/2026-11-21-pep-228-chat-messages-in-place/tasks.md
@@ -0,0 +1,13 @@
+## 1. Сервер
+- [x] 1.1 `newChatMessagesView` в core, `humanSize` в `@peppa/shared/format`
+- [x] 1.2 Хаб: область `chat:` на зрителя, доступ, отпечаток, сообщения в `change`, поставщик `setLiveChatView`; убрать `chatsAfter`
+- [x] 1.3 Веб: поставщик вида сообщения (`lib/chat-live.ts`), `messageLink` в `lib/chat-text.ts`, `markChatReadAction`
+
+## 2. Клиент
+- [x] 2.1 `ChatLiveFeed`: остров `chat:`, отбор по переписке, дорисовка сообщений и событий, прокрутка, «печатает…», прочитано
+- [x] 2.2 Страница `/chats/[chat]`: `LiveRefresh scope=chat:`, `ChatLiveFeed`; `LiveRefresh` без `chatId`
+
+## 3. Проверка
+- [x] 3.1 Тесты: доступ к `chat:`, сообщение приходит своим и не приходит чужим, вид для зрителя, вопрос помечен `render`
+- [x] 3.2 typecheck, lint, тесты, сборка; живой веб-процесс (WebSocket-клиент: сообщение пришло готовым и очищенным) — браузера в окружении нет
+- [x] 3.3 Память, архив, PR
diff --git a/openspec/specs/live-updates/spec.md b/openspec/specs/live-updates/spec.md
index a0d3dd94..e811607d 100644
--- a/openspec/specs/live-updates/spec.md
+++ b/openspec/specs/live-updates/spec.md
@@ -27,19 +27,20 @@
- **THEN** ответ 404
### Requirement: Точечное обновление страницы и индикатор связи
-Страницы Главная, проект, стори и раннеры SHALL обновляться по событиям канала без
-перезагрузки и без потери введённого текста (обновление откладывается, пока пользователь
-печатает или оставил черновик), и показывать состояние связи: «в реальном времени»,
-«переподключение» или «опрос». Если канал недоступен, страница откатывается на опрос раз в 5 с.
+Страницы Главная, проект, стори, раннеры, команда, чаты, подписки и observability SHALL
+обновляться по событиям канала без перезагрузки и без потери введённого текста (серверный рендер
+откладывается, пока пользователь печатает или оставил черновик), и показывать состояние связи:
+«в реальном времени», «переподключение» или «нет связи». Если WebSocket недоступен, страница
+работает через SSE `/api/live`; опроса по таймеру нет.
#### Scenario: Черновик ответа
- **GIVEN** PM печатает ответ на вопрос на странице стори
-- **WHEN** приходит `change`
+- **WHEN** приходит `change`, который нельзя применить на месте
- **THEN** текст не теряется, страница обновится, когда поле отправят или очистят
#### Scenario: Канал недоступен
-- **WHEN** `/api/live` трижды подряд не открывается
-- **THEN** индикатор показывает «опрос», страница обновляется раз в 5 с
+- **WHEN** ни WebSocket, ни `/api/live` не открываются
+- **THEN** индикатор показывает «нет связи», клиент пробует снова с нарастающей паузой
### Requirement: Открытая страница не вызывает пересборку
Веб в режиме разработки (живой сайт до официального запуска) SHALL NOT писать журнал браузера
@@ -85,3 +86,133 @@
- **GIVEN** сервер только перезапущен, кэш пуст, Gitea недоступна
- **WHEN** пользователь открывает доску
- **THEN** доска открывается с именем репозитория и ссылкой, видимость не показана
+
+### Requirement: Один WebSocket на вкладку
+Веб SHALL принимать WebSocket `GET /api/ws` и вести через одно соединение вкладки подписки на все
+живые области: `home`, `runners`, `team`, `chats`, `project:`, `task:`, `steps:`,
+`terminal:`, `attention`, `version`, `observe`, `subs`, `login:`, `me`.
+Вход — cookie `peppa_session` с теми же проверками, что у страниц; соединение с чужим `Origin`
+или без входа MUST быть отклонено до апгрейда. Права на область — как у страницы: проект — доступ
+к проекту, `observe` и `subs` — суперадмин, `login:` — автор подписки или суперадмин.
+
+#### Scenario: Подписка без прав
+- **GIVEN** пользователь «anna» без доступа к проекту PAY открыл WebSocket
+- **WHEN** он подписывается на `task:`
+- **THEN** сервер отвечает `{t:"err", scope:"task:", status:404}`
+- **AND** события PAY-3 ему не приходят
+
+#### Scenario: Событие доходит только до своей области
+- **GIVEN** у вкладки подписки `task:` и `attention`
+- **WHEN** PAY-4 меняет статус
+- **THEN** для `task:` ничего не приходит
+- **AND** когда меняется статус PAY-3, приходит `change` с строкой задачи `status: "review"`
+
+#### Scenario: Чужой сайт
+- **WHEN** страница с другого домена открывает `wss://peppa.telecom.quest/api/ws` с cookie пользователя
+- **THEN** сервер отвечает 403, соединение не открывается
+
+### Requirement: Догон после обрыва
+Клиент SHALL помнить версию каждой области (`v` из последнего события) и после переподключения
+подписываться заново с `since`; сервер MUST сразу прислать `change`, если область изменилась,
+пока клиента не было, и шаги агента после `since` для `steps:`.
+
+#### Scenario: Связь пропала на минуту
+- **GIVEN** вкладка подписана на `project:` и получила версию `v1`
+- **WHEN** соединение рвётся, PAY-3 уходит в ревью, вкладка переподключается с `since: v1`
+- **THEN** сразу приходит `change` для `project:`
+
+#### Scenario: Ничего не изменилось
+- **GIVEN** вкладка переподключается с `since`, равным текущей версии области
+- **WHEN** сервер принимает подписку
+- **THEN** `change` не приходит
+
+### Requirement: Точечные обновления вместо перерисовки
+Событие `change` SHALL нести, что изменилось: части отпечатка (`parts`) и для `project:`/`task:` —
+изменившиеся строки задач (`id`, статус, название, колонка). Доска MUST переносить карточку в
+колонку нового статуса и менять название на месте; шапка задачи — статус. Серверный рендер
+страницы делается, только если изменилась часть, которую страница на месте применить не может,
+и не чаще раза в 4 секунды.
+
+#### Scenario: Задача ушла в ревью
+- **GIVEN** открыта доска PAY, PAY-3 в колонке «В работе»
+- **WHEN** агент переводит PAY-3 в ревью и больше ничего не меняется
+- **THEN** карточка PAY-3 за долю секунды оказывается в колонке «Ревью»
+- **AND** серверный рендер страницы не запрашивается
+
+#### Scenario: Изменилось то, что на месте не применить
+- **GIVEN** открыта доска PAY
+- **WHEN** появляется новый релиз проекта
+- **THEN** страница перерисовывается с сервера не позже чем через 4 секунды после прошлой перерисовки
+
+### Requirement: Без опросов по таймеру в браузере
+Веб-клиент SHALL NOT опрашивать данные по таймеру: счётчик «ждут вас» и заголовок вкладки,
+проверка новой версии, observability, подписки, ожидание входа в подписку и ожидание привязки
+Telegram обновляются событиями канала. Опрос входа ChatGPT MUST делать сервер — один цикл на
+подписку, пока её кто-то ждёт. Остаётся только проверка связи.
+
+#### Scenario: Вопрос агента
+- **GIVEN** у пользователя открыта любая страница, в заголовке «(1) …»
+- **WHEN** агент его проекта задаёт вопрос
+- **THEN** в заголовке вкладки становится «(2) …» без перезагрузки страницы
+
+#### Scenario: Веб перезапустили
+- **GIVEN** вкладка открыта до перезапуска веба
+- **WHEN** веб перезапускается с новой версией и вкладка переподключается
+- **THEN** появляется плашка «Peppa FACTORY обновилась. Обновите страницу…»
+
+#### Scenario: Вход в ChatGPT подтверждён
+- **GIVEN** владелец ждёт на странице подключения ChatGPT
+- **WHEN** ChatGPT подтверждает вход
+- **THEN** страница показывает подключённую подписку без нажатий, за несколько секунд
+
+### Requirement: Надёжность канала
+Канал SHALL пинговаться раз в 15 секунд в обе стороны, переподключаться с нарастающей паузой
+(1 → 30 с) и показывать состояние связи. Если WebSocket не открылся три раза подряд, клиент MUST
+перейти на SSE (`/api/live`, SSE терминала) и раз в минуту пробовать WebSocket снова. Скрытая
+вкладка отписывается от терминала, шагов агента и `team` и подписывается снова при возврате.
+
+#### Scenario: Корпоративный прокси режет WebSocket
+- **GIVEN** апгрейд до WebSocket не проходит
+- **WHEN** вкладка открывает доску
+- **THEN** после трёх попыток индикатор показывает «в реальном времени» через SSE и доска живая
+
+#### Scenario: Сообщения шлются слишком часто
+- **WHEN** клиент шлёт больше 60 сообщений за 5 секунд
+- **THEN** сервер закрывает соединение с кодом 1008
+
+### Requirement: Сообщения чата на месте
+Канал SHALL давать область `chat:` — чат проекта для одного зрителя (участник проекта или
+суперадмин; мастер-чат — только его владелец, иначе 404). Событие `change` этой области MUST
+нести новые сообщения чата, готовые к показу этому зрителю: автор, текст на его языке и очищенный
+как на странице, «Подробнее», вложения, ссылка, вид и тред. Страница чата проекта SHALL
+дорисовывать сообщения своей переписки в ленту сразу, без серверной перерисовки, и отмечать их
+прочитанными. Серверная перерисовка (не чаще раза в 4 с) остаётся для вопросов и «готово»,
+предложений с кнопками, сообщений других тредов и ответов на вопросы.
+
+#### Scenario: Ответ аналитика появляется сразу
+- **GIVEN** владелец проекта PAY открыл «Чат с аналитиком» и написал «Что сейчас в работе?»
+- **WHEN** аналитик отвечает «В работе PAY-3»
+- **THEN** ответ появляется внизу ленты за долю секунды, а «печатает…» пропадает
+- **AND** серверная перерисовка страницы не запрашивается
+- **AND** счётчик новых сообщений чата PAY не растёт
+
+#### Scenario: Вопрос агента — карточкой
+- **GIVEN** открыт тред задачи PAY-3
+- **WHEN** агент PAY-3 задаёт вопрос с вариантами «Да» и «Нет»
+- **THEN** страница перерисовывается с сервера и показывает карточку вопроса с кнопками
+
+#### Scenario: Сообщение другого треда
+- **GIVEN** открыт тред задачи PAY-3
+- **WHEN** приходит сообщение в тред PAY-4
+- **THEN** в ленте PAY-3 оно не появляется
+- **AND** страница перерисовывается, чтобы обновить список слева
+
+#### Scenario: Чужой чат
+- **GIVEN** пользователь «bob» не участник проекта PAY
+- **WHEN** он подписывается на `chat:`
+- **THEN** ответ 404, сообщения PAY к нему не приходят
+
+#### Scenario: Сообщение другого чата
+- **GIVEN** владелец подписан на `chat:`
+- **WHEN** новое сообщение появляется в чате проекта SHOP
+- **THEN** событие `change` для чата PAY не приходит
diff --git a/openspec/specs/runner-terminal/spec.md b/openspec/specs/runner-terminal/spec.md
index 55b88678..ea8a110a 100644
--- a/openspec/specs/runner-terminal/spec.md
+++ b/openspec/specs/runner-terminal/spec.md
@@ -49,3 +49,19 @@
#### Scenario: Слишком часто или слишком много
- **WHEN** пользователь шлёт больше 40 запросов ввода за 5 с или нажатия больше 1 КБ
- **THEN** ответ 429 или 413, в tmux лишнее не уходит
+
+### Requirement: Терминал через общий канал
+Вывод терминала раннера SHALL идти через WebSocket вкладки (область `terminal:`:
+`frame`, `out`, `end`), ввод — сообщением `{t:"in", keys|paste}` того же соединения с прежними
+правилами: только владелец или участник проекта, живая сессия, ≤1 КБ нажатий, ≤64 КБ вставки,
+40 запросов за 5 с. Без WebSocket терминал работает через прежние SSE и POST.
+
+#### Scenario: Ввод через сокет
+- **GIVEN** участник проекта подписан на `terminal:` живой сессии
+- **WHEN** он шлёт `{t:"in", scope:"terminal:", keys:"ls\r", id:1}`
+- **THEN** нажатия уходят в pane, приходит `{t:"ack", id:1}`
+
+#### Scenario: Ввод в завершённую сессию
+- **GIVEN** сессия завершена
+- **WHEN** приходит `{t:"in", …, id:2}`
+- **THEN** приходит `{t:"ack", id:2, error:"…"}`, в pane ничего не уходит
diff --git a/packages/core/src/attachments.ts b/packages/core/src/attachments.ts
index af2b4524..89285513 100644
--- a/packages/core/src/attachments.ts
+++ b/packages/core/src/attachments.ts
@@ -5,6 +5,7 @@
import { guardUntrusted } from "./untrusted.ts";
import { attachments, events, chatMessages, type Db } from "@peppa/db";
import { peppaHome } from "@peppa/shared";
+import { humanSize } from "@peppa/shared/format";
import { m as tr } from "@peppa/shared/i18n";
import { and, asc, eq, inArray, isNull, lt } from "drizzle-orm";
import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
@@ -129,7 +130,7 @@ export interface AttachmentView {
const kindOf = (mime: string): AttachmentKind => (mime.startsWith("image/") ? "image" : mime === "application/pdf" ? "pdf" : mime.startsWith("application/vnd.") ? "office" : "text");
export const attachmentView = (a: Attachment): AttachmentView => ({ id: a.id, name: a.name, mime: a.mime, size: a.size, kind: kindOf(a.mime) });
-export const humanSize = (n: number) => (n < 1024 ? `${n} B` : n < 1024 * 1024 ? `${Math.round(n / 1024)} KB` : `${(n / 1024 / 1024).toFixed(1).replace(/\.0$/, "")} MB`);
+export { humanSize };
/** Stores an uploaded file for a project's person; it stays unlinked until a form takes it. */
export async function saveAttachment(db: Db, user: Pick, o: { projectId: number; name: string; data: Uint8Array; now?: Date }): Promise {
diff --git a/packages/core/src/chats.ts b/packages/core/src/chats.ts
index 97fd131c..f65e458c 100644
--- a/packages/core/src/chats.ts
+++ b/packages/core/src/chats.ts
@@ -246,6 +246,12 @@ export async function chatMessagesView(db: Db, chatId: number, o: { threadKey?:
return views(db, and(...w)!, o.limit ?? 100, o.before);
}
+/** PEP-228: messages of a chat newer than `after`, oldest first; `more` — there were more than `limit` (the page re-renders). */
+export async function newChatMessagesView(db: Db, chatId: number, after: number, limit = 30): Promise<{ messages: ChatMessageView[]; more: boolean }> {
+ const rows = await views(db, and(eq(chatMessages.chatId, chatId), gt(chatMessages.id, after))!, limit + 1);
+ return rows.length > limit ? { messages: [], more: true } : { messages: rows, more: false };
+}
+
// ── discussion (PEP-106) ────────────────────────────────────────────────────
/** People's messages in a project chat's channel: no agents, no events, no commands. */
diff --git a/packages/runner/package.json b/packages/runner/package.json
index bd52cbd1..d8c7105f 100644
--- a/packages/runner/package.json
+++ b/packages/runner/package.json
@@ -4,7 +4,8 @@
"private": true,
"type": "module",
"exports": {
- ".": "./src/index.ts"
+ ".": "./src/index.ts",
+ "./live-ws": "./src/live-ws.ts"
},
"bin": {
"peppa-hook": "./bin/peppa-hook"
@@ -17,6 +18,10 @@
"@peppa/core": "workspace:*",
"@peppa/db": "workspace:*",
"@peppa/shared": "workspace:*",
- "drizzle-orm": "0.45.4"
+ "drizzle-orm": "0.45.4",
+ "ws": "8.18.3"
+ },
+ "devDependencies": {
+ "@types/ws": "8.18.1"
}
}
diff --git a/packages/runner/src/live-ws.ts b/packages/runner/src/live-ws.ts
new file mode 100644
index 00000000..0fedc0fd
--- /dev/null
+++ b/packages/runner/src/live-ws.ts
@@ -0,0 +1,270 @@
+// One WebSocket per browser tab (PEP-225): `GET /api/ws` carries every live scope of the tab —
+// the hub's scopes (live.ts) and the runner terminal (terminal.ts, output and input) — instead of
+// an SSE stream per page part. The web's own server (apps/web/server.ts) hands the upgrade here;
+// the protocol itself (LiveConnection) knows nothing of the transport, tests drive it directly.
+//
+// Client → server: {t:"sub", scope, since?} · {t:"unsub", scope} · {t:"in", scope:"terminal:", keys?|paste?, id} · {t:"ping"}
+// Server → client: {t:"hello", boot} · {t:"ok", scope, v?} · {t:"err", scope?, status, error} · {t:"ev", scope, type, …} · {t:"ack", id, error?} · {t:"pong"}
+import type { IncomingMessage } from "node:http";
+import type { Duplex } from "node:stream";
+import { WebSocketServer, type WebSocket } from "ws";
+import { m } from "@peppa/shared/i18n";
+import { PeppaError, projectSecretMasker, type User } from "@peppa/core";
+import type { Db } from "@peppa/db";
+import * as tmux from "./tmux.ts";
+import { checkScopeAccess, LIVE_MAX_SCOPES, LIVE_PING_MS, liveHub, LiveError, parseScope, type LiveScope } from "./live.ts";
+import { acquireViewer, terminalInput, terminalSession, watchTerminal } from "./terminal.ts";
+
+/** Largest message from a client: a 64 KB paste in JSON with escapes. */
+export const LIVE_WS_MAX_PAYLOAD = 300_000;
+/** Client messages per window before the socket is closed (1008). */
+export const LIVE_WS_RATE_MAX = 60;
+export const LIVE_WS_RATE_WINDOW_MS = 5000;
+export const LIVE_WS_PATH = "/api/ws";
+
+type Out = Record;
+
+/** One tab's connection: its subscriptions, input and limits. */
+export class LiveConnection {
+ private subs = new Map void>();
+ private pending = new Set();
+ private window = { start: 0, n: 0 };
+ private input: Promise = Promise.resolve();
+ private closed = false;
+ private db: Db;
+ private user: User;
+ private out: (msg: Out) => void;
+ private kill: (code: number, reason: string) => void;
+
+ constructor(db: Db, user: User, out: (msg: Out) => void, kill: (code: number, reason: string) => void) {
+ this.db = db;
+ this.user = user;
+ this.out = out;
+ this.kill = kill;
+ }
+
+ private send(msg: Out) {
+ if (!this.closed) this.out(msg);
+ }
+
+ /** Handles one text message; returns once it is dealt with (tests await it). */
+ async receive(raw: string, now = Date.now()): Promise {
+ if (this.closed) return;
+ if (now - this.window.start >= LIVE_WS_RATE_WINDOW_MS) this.window = { start: now, n: 0 };
+ if (++this.window.n > LIVE_WS_RATE_MAX) return this.kill(1008, "rate");
+ let msg: { t?: unknown; scope?: unknown; since?: unknown; keys?: unknown; paste?: unknown; id?: unknown };
+ try {
+ msg = JSON.parse(raw);
+ } catch {
+ return this.send({ t: "err", status: 400, error: m("Неверный JSON") });
+ }
+ if (msg.t === "ping") return this.send({ t: "pong" });
+ const scopeRaw = typeof msg.scope === "string" ? msg.scope : "";
+ let scope: LiveScope;
+ try {
+ scope = parseScope(scopeRaw);
+ } catch (e) {
+ return this.send({ t: "err", scope: scopeRaw, status: 400, error: (e as Error).message });
+ }
+ if (msg.t === "sub") return this.subscribe(scope, typeof msg.since === "string" || typeof msg.since === "number" ? msg.since : undefined);
+ if (msg.t === "unsub") return this.unsubscribe(scope);
+ if (msg.t === "in") return this.terminalIn(scope, msg);
+ this.send({ t: "err", scope, status: 400, error: m("Неизвестное сообщение") });
+ }
+
+ private async subscribe(scope: LiveScope, since: string | number | undefined) {
+ if (this.subs.has(scope) || this.pending.has(scope)) return this.send({ t: "ok", scope });
+ if (this.subs.size + this.pending.size >= LIVE_MAX_SCOPES) return this.send({ t: "err", scope, status: 429, error: m("Слишком много областей") });
+ this.pending.add(scope);
+ try {
+ await checkScopeAccess(this.db, this.user, scope);
+ const stop = scope.startsWith("terminal:") ? await this.watchTerminal(scope) : this.watchHub(scope, since);
+ // Unsubscribed (or closed) while access was checked.
+ if (!this.pending.has(scope) || this.closed) return stop();
+ this.subs.set(scope, stop);
+ this.send({ t: "ok", scope, v: scope.startsWith("terminal:") ? undefined : liveHub(this.db).versionOf(scope, this.user.id) });
+ } catch (e) {
+ const status = e instanceof LiveError ? e.status : (e as { status?: number }).status ?? 500;
+ if (status === 500) console.error(`live-ws: ${scope}`, e);
+ this.send({ t: "err", scope, status, error: e instanceof LiveError || e instanceof PeppaError ? e.message : m("Ошибка потока") });
+ } finally {
+ this.pending.delete(scope);
+ }
+ }
+
+ private watchHub(scope: LiveScope, since: string | number | undefined): () => void {
+ return liveHub(this.db).subscribe([scope], (e) => this.send({ t: "ev", ...e }), { userId: this.user.id, since: { [scope]: since } });
+ }
+
+ /** The runner terminal (PEP-9): the shared TerminalFeed of the pane, secrets masked, viewers per user limited. */
+ private async watchTerminal(scope: LiveScope): Promise<() => void> {
+ const s = await terminalSession(this.db, this.user, Number(scope.slice(9)));
+ const mask = await projectSecretMasker(this.db, s.projectId);
+ const release = acquireViewer(this.user.id);
+ let done = false;
+ const stopFeed = watchTerminal(
+ tmux.sessionPane(s),
+ (e) => {
+ this.send({ t: "ev", scope, ...e });
+ if (e.type === "end") queueMicrotask(() => this.unsubscribe(scope));
+ },
+ { mask },
+ );
+ return () => {
+ if (done) return;
+ done = true;
+ stopFeed();
+ release();
+ };
+ }
+
+ private unsubscribe(scope: LiveScope) {
+ this.pending.delete(scope);
+ const stop = this.subs.get(scope);
+ this.subs.delete(scope);
+ stop?.();
+ }
+
+ /** 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 () => {
+ try {
+ 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);
+ }
+ };
+ this.input = this.input.then(run);
+ return this.input;
+ }
+
+ get scopes(): LiveScope[] {
+ return [...this.subs.keys()];
+ }
+
+ close() {
+ if (this.closed) return;
+ this.closed = true;
+ for (const stop of this.subs.values()) stop();
+ this.subs.clear();
+ this.pending.clear();
+ }
+}
+
+/** Same-site only: the cookie is `lax`, a WebSocket from another site would carry it. */
+export function sameOriginUpgrade(req: IncomingMessage): boolean {
+ const origin = req.headers.origin;
+ if (!origin) return true; // not a browser
+ const host = (req.headers["x-forwarded-host"] as string | undefined)?.split(",")[0]?.trim() || req.headers.host;
+ try {
+ return new URL(origin).host === host;
+ } catch {
+ return false;
+ }
+}
+
+export interface LiveWsOptions {
+ db: Db;
+ /** The signed-in user of the request (cookie `peppa_session`), or null. */
+ authenticate: (req: IncomingMessage) => Promise;
+ /** Boot id of the web process (the client compares it after a reconnect). */
+ boot?: () => string;
+ pingMs?: number;
+}
+
+export interface LiveWs {
+ handleUpgrade(req: IncomingMessage, socket: Duplex, head: Buffer): void;
+ readonly clients: number;
+ close(): void;
+}
+
+function refuse(socket: Duplex, status: number, text: string) {
+ try {
+ socket.write(`HTTP/1.1 ${status} ${text}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`);
+ } catch {}
+ socket.destroy();
+}
+
+/** The WebSocket endpoint: auth and origin before the upgrade, a ping every 15 s, one LiveConnection per socket. */
+export function createLiveWs(opts: LiveWsOptions): LiveWs {
+ const wss = new WebSocketServer({ noServer: true, perMessageDeflate: false, maxPayload: LIVE_WS_MAX_PAYLOAD });
+ const alive = new WeakMap();
+ const pingMs = opts.pingMs ?? LIVE_PING_MS;
+ // Two pings without a pong: the connection is dead (a sleeping phone, a dropped proxy).
+ const pinger = setInterval(() => {
+ for (const ws of wss.clients) {
+ const missed = (alive.get(ws) ?? 0) + 1;
+ if (missed > 2) {
+ ws.terminate();
+ continue;
+ }
+ alive.set(ws, missed);
+ try {
+ ws.ping();
+ } catch {}
+ }
+ }, pingMs);
+ pinger.unref?.();
+
+ wss.on("connection", (ws: WebSocket, _req: IncomingMessage, user: User) => {
+ alive.set(ws, 0);
+ const conn = new LiveConnection(
+ opts.db,
+ user,
+ (msg) => {
+ if (ws.readyState === ws.OPEN) ws.send(JSON.stringify(msg));
+ },
+ (code, reason) => ws.close(code, reason),
+ );
+ ws.on("pong", () => alive.set(ws, 0));
+ ws.on("message", (data, isBinary) => {
+ alive.set(ws, 0);
+ if (isBinary) return ws.close(1003, "text only");
+ void conn.receive(data.toString());
+ });
+ ws.on("close", () => conn.close());
+ ws.on("error", () => conn.close());
+ ws.send(JSON.stringify({ t: "hello", boot: opts.boot?.() ?? "" }));
+ });
+
+ return {
+ handleUpgrade(req, socket, head) {
+ socket.on("error", () => socket.destroy());
+ if (!sameOriginUpgrade(req)) return refuse(socket, 403, "Forbidden");
+ opts
+ .authenticate(req)
+ .then((user) => {
+ if (!user) return refuse(socket, 401, "Unauthorized");
+ wss.handleUpgrade(req, socket, head, (ws) => wss.emit("connection", ws, req, user));
+ })
+ .catch((e) => {
+ console.error("live-ws: upgrade", e);
+ refuse(socket, 500, "Internal Server Error");
+ });
+ },
+ get clients() {
+ return wss.clients.size;
+ },
+ close() {
+ clearInterval(pinger);
+ for (const ws of wss.clients) ws.terminate();
+ wss.close();
+ },
+ };
+}
+
+/** Reads one cookie from a raw Cookie header. */
+export function readCookie(header: string | undefined, name: string): string | undefined {
+ for (const part of (header ?? "").split(";")) {
+ const i = part.indexOf("=");
+ if (i > 0 && part.slice(0, i).trim() === name) return decodeURIComponent(part.slice(i + 1).trim());
+ }
+ return undefined;
+}
diff --git a/packages/runner/src/live.ts b/packages/runner/src/live.ts
index 4a67a8f7..eb13ecfb 100644
--- a/packages/runner/src/live.ts
+++ b/packages/runner/src/live.ts
@@ -1,22 +1,55 @@
-// Live web (PEP-37): one change hub per web process. notify() pokes (the `web` subscriber
-// socket, the same events the bot hears) and PRAGMA data_version (writes from the hooks,
-// the watchdog, the CLI) wake it; it then computes a fingerprint of every scope somebody
-// watches and tells only the watchers whose scope changed. Steps of agents (PEP-33) go to
-// `steps:` watchers as data.
+// Live web (PEP-37, PEP-225): one change hub per web process. notify() pokes (the `web` subscriber
+// socket, the same events the bot hears) and PRAGMA data_version (writes from the hooks, the
+// watchdog, the CLI) wake it; it then computes a fingerprint of every scope somebody watches and
+// tells only the watchers whose scope changed — with what changed (`parts`, rows of tasks), so a
+// page can apply it in place. Steps of agents (PEP-33) go to `steps:` watchers as
+// data; value scopes (`attention`, `version`) send their value. The same events go out over the
+// tab's WebSocket (live-ws.ts) and over the SSE fallback (/api/live).
import { m } from "@peppa/shared/i18n";
+import { createHash } from "node:crypto";
import { existsSync, statSync } from "node:fs";
import { join } from "node:path";
-import { findChangeDir, listenEvents, projectForUser, STEP_EVENT, stepView, type StepView, type User } from "@peppa/core";
-import { events, sessions, tasks, type Db } from "@peppa/db";
+import { attachmentsByMessage, findChangeDir, newChatMessagesView, isSuperadmin, listenEvents, observeDb, observeDbPath, projectForUser, STEP_EVENT, stepView, type AttachmentView, type ChatMessageView, type StepView, type User } from "@peppa/core";
+import { chats, events, sessions, subscriptions, tasks, type Db } from "@peppa/db";
import { and, eq, gt } from "drizzle-orm";
+import { columnOf, type BoardColumn } from "./flow.ts";
+import { pollCodexLogin } from "./subscription-login.ts";
+import { terminalSession } from "./terminal.ts";
-export type LiveScope = "home" | "runners" | "chats" | "team" | `project:${number}` | `task:${number}` | `steps:${number}`;
-export type LiveEvent = { type: "change"; scope: LiveScope } | { type: "step"; scope: LiveScope; step: StepView };
+/** Scopes without an id. `attention` and `me` are per user (the hub keys them by the viewer). */
+export const LIVE_PLAIN_SCOPES = ["home", "runners", "chats", "team", "attention", "version", "observe", "subs", "me"] as const;
+const ID_KINDS = ["project", "task", "steps", "login", "terminal", "chat"] as const;
+type PlainScope = (typeof LIVE_PLAIN_SCOPES)[number];
+type IdKind = (typeof ID_KINDS)[number];
+export type LiveScope = PlainScope | `${IdKind}:${number}`;
+
+/** A row of a task as a page shows it on the board and in the story header. */
+export interface LiveTaskRow {
+ id: number;
+ status: string;
+ title: string;
+ column: BoardColumn;
+ /** Something else of the row changed (epic, order, «Предложено», importance): the page re-renders. */
+ other?: boolean;
+}
+type Row = LiveTaskRow & { sig: string };
+
+export type LiveEvent =
+ /**
+ * The scope changed: `v` — its new version, `parts` — which parts of it, `tasks` — changed task
+ * rows, `messages` — new messages of a `chat:` scope as its viewer sees them (PEP-228).
+ */
+ | { type: "change"; scope: LiveScope; v: string; parts: string[]; tasks?: LiveTaskRow[]; messages?: unknown[] }
+ | { type: "step"; scope: LiveScope; step: StepView }
+ /** The current value of a value scope (`attention`, `version`). */
+ | { type: "data"; scope: LiveScope; v: string; data: unknown };
type Listener = (e: LiveEvent) => void;
export const LIVE_PING_MS = 15_000;
+/** Most scopes one SSE stream / one WebSocket may watch. */
+export const LIVE_MAX_SCOPES = 32;
-/** Refusal of a live stream with its HTTP status. */
+/** Refusal of a live stream or a subscription with its HTTP status. */
export class LiveError extends Error {
status: number;
constructor(message: string, status: number) {
@@ -25,38 +58,103 @@ export class LiveError extends Error {
}
}
const WAKE_DEBOUNCE_MS = 250;
+/** Scopes read from outside the main database: re-checked on a timer while watched. */
+const OBSERVE_EVERY_MS = 2000;
+/** A pending ChatGPT sign-in is asked this often while somebody waits for it (PEP-148, server side since PEP-225). */
+export const LOGIN_POLL_MS = 3000;
-/** Parses `?scope=a,b`; unknown parts are refused. */
+/** Checks one scope name; unknown ones are refused. */
+export function parseScope(part: string): LiveScope {
+ if ((LIVE_PLAIN_SCOPES as readonly string[]).includes(part)) return part as LiveScope;
+ if (/^(project|task|steps|login|terminal|chat):[1-9]\d{0,9}$/.test(part)) return part as LiveScope;
+ throw new LiveError(m("Неизвестная область: {scope}", { scope: part }), 400);
+}
+
+/** Parses `?scope=a,b` of the SSE fallback; the terminal has its own stream there. */
export function parseScopes(raw: string | null): LiveScope[] {
const out = new Set();
for (const part of (raw ?? "").split(",").map((s) => s.trim()).filter(Boolean)) {
- if (part === "home" || part === "runners" || part === "chats" || part === "team") out.add(part);
- else if (/^(project|task|steps):[1-9]\d{0,9}$/.test(part)) out.add(part as LiveScope);
- else throw new LiveError(m("Неизвестная область: {scope}", { scope: part }), 400);
+ const s = parseScope(part);
+ if (s.startsWith("terminal:")) throw new LiveError(m("Неизвестная область: {scope}", { scope: part }), 400);
+ out.add(s);
}
- if (!out.size || out.size > 8) throw new LiveError(m("Нужна область (scope)"), 400);
+ if (!out.size || out.size > LIVE_MAX_SCOPES) throw new LiveError(m("Нужна область (scope)"), 400);
return [...out];
}
-/** Access: project/story/runner scopes need the project; home/runners only a user. */
+const notFound = () => new LiveError(m("Не найдено"), 404);
+
+/**
+ * Access, the same as the page's: project / story / steps / terminal need the project,
+ * `observe` and `subs` a superadmin, `login:` the author of that sign-in or a superadmin,
+ * `chat:` the project's people (a master chat — its owner only).
+ */
export async function checkScopeAccess(db: Db, user: User, scope: LiveScope): Promise {
const [kind, raw] = scope.split(":") as [string, string?];
const id = Number(raw);
+ if (kind === "observe" || kind === "subs") {
+ if (!(await isSuperadmin(db, user))) throw notFound();
+ return;
+ }
+ if (kind === "login") {
+ const row = (await db.select({ by: subscriptions.createdBy }).from(subscriptions).where(eq(subscriptions.id, id)))[0];
+ if (!row || (row.by !== user.id && !(await isSuperadmin(db, user)))) throw notFound();
+ return;
+ }
+ if (kind === "terminal") {
+ await terminalSession(db, user, id).catch(() => {
+ throw notFound();
+ });
+ return;
+ }
+ if (kind === "chat") {
+ const chat = (await db.select({ userId: chats.userId, projectId: chats.projectId }).from(chats).where(eq(chats.id, id)))[0];
+ if (!chat) throw notFound();
+ if (chat.projectId == null) {
+ if (chat.userId !== user.id) throw notFound();
+ return;
+ }
+ await projectForUser(db, user.id, chat.projectId).catch(() => {
+ throw notFound();
+ });
+ return;
+ }
let projectId: number | undefined;
if (kind === "project") projectId = id;
else if (kind === "task") projectId = (await db.select({ p: tasks.projectId }).from(tasks).where(eq(tasks.id, id)))[0]?.p;
else if (kind === "steps") projectId = (await db.select({ p: sessions.projectId }).from(sessions).where(eq(sessions.id, id)))[0]?.p;
else return;
- if (projectId == null) throw new LiveError(m("Не найдено"), 404);
+ if (projectId == null) throw notFound();
await projectForUser(db, user.id, projectId).catch(() => {
- throw new LiveError(m("Не найдено"), 404);
+ throw notFound();
});
}
-const ACTIVE_SESSIONS = `group_concat(CASE WHEN ended_at IS NULL THEN id || ':' || status END)`;
+/** Short version of a fingerprint: what a client sends back as `since`. */
+export const liveVersion = (fp: string) => createHash("sha1").update(fp).digest("base64url").slice(0, 12);
-/** One SQL per scope; frequent fields (last_activity_at, steps, heartbeats) are left out. */
-function fingerprint(db: Db, scope: LiveScope): string {
+const ACTIVE_SESSIONS = `group_concat(CASE WHEN ended_at IS NULL THEN id || ':' || status END)`;
+type Parts = Record;
+const str = (row: Record | undefined): Parts => Object.fromEntries(Object.entries(row ?? {}).map(([k, v]) => [k, String(v ?? "")]));
+
+/** tasks.md of a change, found once a minute: the archive listing is the slow part of a story's check (PEP-225 bench). */
+const mdPaths = new Map();
+function tasksMdPath(ws: string, change: string): string | null {
+ const key = `${ws}|${change}`;
+ const hit = mdPaths.get(key);
+ if (hit && Date.now() - hit.at < 60_000 && (!hit.file || existsSync(hit.file))) return hit.file;
+ const found = findChangeDir(ws, change);
+ const file = found ? join(found.dir, "tasks.md") : null;
+ if (mdPaths.size > 2000) mdPaths.clear();
+ mdPaths.set(key, { file, at: Date.now() });
+ return file;
+}
+
+/**
+ * One SQL per scope, split into named parts; frequent fields (last_activity_at, steps,
+ * heartbeats) are left out. Part `t` is covered by the task rows sent along (see taskRows).
+ */
+function fingerprint(db: Db, scope: LiveScope, userId: number): Parts {
const c = db.$client;
const [kind, raw] = scope.split(":") as [string, string?];
const id = Number(raw);
@@ -64,7 +162,8 @@ function fingerprint(db: Db, scope: LiveScope): string {
const row = c
.prepare(
`SELECT
- (SELECT json_array(status, title, coalesce(description,''), coalesce(goal_id,0), coalesce(openspec_change,''), coalesce(pr_url,''), ci_attempts, updated_at) FROM tasks WHERE id = ?1) AS t,
+ (SELECT json_array(status, title) FROM tasks WHERE id = ?1) AS t,
+ (SELECT json_array(coalesce(description,''), coalesce(goal_id,0), coalesce(openspec_change,''), coalesce(pr_url,''), ci_attempts, updated_at) FROM tasks WHERE id = ?1) AS d,
(SELECT coalesce(max(id),0) FROM events WHERE task_id = ?1 AND type <> 'step') AS e,
(SELECT count(*) || ':' || count(answered_at) FROM questions WHERE task_id = ?1) AS q,
(SELECT coalesce(group_concat(id || ':' || status || ':' || coalesce(ended_at,'')),'') FROM sessions WHERE task_id = ?1) AS s,
@@ -74,21 +173,22 @@ function fingerprint(db: Db, scope: LiveScope): string {
(SELECT openspec_change FROM tasks WHERE id = ?1) AS ch`,
)
.get(id) as Record | undefined;
- if (!row) return "";
+ if (!row?.t) return {};
// tasks.md of the working copy changes without a database write (agent ticks items).
let tasksMtime = 0;
if (row.ws && row.ch) {
- const found = findChangeDir(String(row.ws), String(row.ch));
- const file = found && join(found.dir, "tasks.md");
+ const file = tasksMdPath(String(row.ws), String(row.ch));
if (file && existsSync(file)) tasksMtime = statSync(file).mtimeMs;
}
- return [row.t, row.e, row.q, row.s, row.ci, row.r, tasksMtime].join("|");
+ const { ws: _ws, ch: _ch, ...rest } = row;
+ return { ...str(rest), md: String(tasksMtime) };
}
if (kind === "project") {
+ // `t` — the board rows: what a page can't apply from `tasks` comes with `other: true`.
const row = c
.prepare(
`SELECT
- (SELECT coalesce(max(updated_at),0) || ':' || count(*) FROM tasks WHERE project_id = ?1) AS t,
+ (SELECT coalesce(group_concat(id || ':' || status || ':' || title || ':' || position || ':' || coalesce(goal_id,0) || ':' || proposed || ':' || coalesce(severity,'') || ':' || coalesce(origin,''), char(1)),'') FROM tasks WHERE project_id = ?1 AND archived_at IS NULL) AS t,
(SELECT coalesce(max(id),0) FROM events WHERE project_id = ?1 AND type <> 'step') AS e,
(SELECT count(*) || ':' || count(answered_at) FROM questions WHERE project_id = ?1) AS q,
(SELECT count(*) || ':' || coalesce(${ACTIVE_SESSIONS},'') FROM sessions WHERE project_id = ?1) AS s,
@@ -98,7 +198,22 @@ function fingerprint(db: Db, scope: LiveScope): string {
(SELECT updated_at FROM projects WHERE id = ?1) AS p`,
)
.get(id) as Record;
- return Object.values(row).join("|");
+ return str(row);
+ }
+ if (kind === "chat") {
+ // PEP-228: one chat — `m` new messages (sent along), `q` questions of its project, `tg` the
+ // linked group, `x` offers and files of its latest messages (written right after a message).
+ const row = c
+ .prepare(
+ `SELECT
+ (SELECT coalesce(max(id),0) FROM chat_messages WHERE chat_id = ?1) AS m,
+ (SELECT count(*) || ':' || count(answered_at) FROM questions WHERE project_id = (SELECT project_id FROM chats WHERE id = ?1)) AS q,
+ (SELECT coalesce(tg_chat_id,'') FROM chats WHERE id = ?1) AS tg,
+ (SELECT count(*) FROM settings WHERE key IN (SELECT 'chat.offer:' || id FROM chat_messages WHERE chat_id = ?1 ORDER BY id DESC LIMIT 50)) || ':' ||
+ (SELECT count(*) FROM attachments WHERE chat_message_id IN (SELECT id FROM chat_messages WHERE chat_id = ?1 ORDER BY id DESC LIMIT 50)) AS x`,
+ )
+ .get(id) as Record;
+ return str(row);
}
if (kind === "chats") {
// PEP-62: a new chat message (projected or written) or a question answered anywhere.
@@ -111,7 +226,41 @@ function fingerprint(db: Db, scope: LiveScope): string {
(SELECT coalesce(group_concat(id || ':' || coalesce(tg_chat_id,'')),'') FROM chats WHERE tg_chat_id IS NOT NULL) AS tg`,
)
.get() as Record;
- return Object.values(row).join("|");
+ return str(row);
+ }
+ if (kind === "subs") {
+ const row = c
+ .prepare(
+ `SELECT
+ (SELECT coalesce(group_concat(id || ':' || status || ':' || coalesce(limited_until,'') || ':' || coalesce(checked_at,'') || ':' || coalesce(last_error,'')),'') FROM subscriptions) AS sub,
+ (SELECT coalesce(group_concat(pool_id || ':' || subscription_id),'') FROM subscription_pool_members) AS pool,
+ (SELECT coalesce(group_concat(key || '=' || value),'') FROM settings WHERE key >= 'subscription.' AND key < 'subscription/') AS st,
+ (SELECT count(*) || ':' || coalesce(${ACTIVE_SESSIONS},'') FROM sessions) AS s`,
+ )
+ .get() as Record;
+ return str(row);
+ }
+ if (kind === "login") {
+ const row = c.prepare(`SELECT status || ':' || coalesce(last_error,'') AS sub FROM subscriptions WHERE id = ?`).get(id) as Record | undefined;
+ return { sub: String(row?.sub ?? "gone") };
+ }
+ if (kind === "me") {
+ const row = c
+ .prepare(`SELECT coalesce(telegram_chat_id,'') || ':' || coalesce(telegram_bot_username,'') || ':' || coalesce(egov_iin,'') || ':' || coalesce(google_sub,'') AS u FROM users WHERE id = ?`)
+ .get(userId) as Record | undefined;
+ return { u: String(row?.u ?? "") };
+ }
+ if (kind === "observe") {
+ const o = observeDb();
+ const row = o
+ .prepare(
+ `SELECT
+ (SELECT coalesce(group_concat(id || ':' || state || ':' || paused || ':' || name || ':' || updated_at),'') FROM monitors) AS mon,
+ (SELECT coalesce(max(id),0) || ':' || count(ended_at) FROM monitor_incidents) AS inc,
+ (SELECT coalesce(substr(max(at),1,16),'') FROM monitor_checks) AS min`,
+ )
+ .get() as Record;
+ return str(row);
}
// home / runners / team: across projects (only wakes the page — data stays behind access checks).
// team (PEP-179) also watches the team itself: a new agent, a renamed or removed one, and which
@@ -119,7 +268,7 @@ function fingerprint(db: Db, scope: LiveScope): string {
const row = c
.prepare(
`SELECT
- (SELECT coalesce(max(updated_at),0) || ':' || count(*) FROM tasks) AS t,
+ (SELECT coalesce(max(updated_at),0) || ':' || count(*) FROM tasks) AS tx,
(SELECT count(*) || ':' || count(answered_at) FROM questions) AS q,
(SELECT count(*) || ':' || coalesce(${ACTIVE_SESSIONS},'') FROM sessions) AS s,
(SELECT count(*) FROM projects) AS p${
@@ -131,78 +280,205 @@ function fingerprint(db: Db, scope: LiveScope): string {
}`,
)
.get() as Record;
- return Object.values(row).join("|");
+ return str(row);
+}
+
+/** Board rows of a project / the story, keyed by id: «status|title». */
+function taskRows(db: Db, scope: LiveScope): Map {
+ const [kind, raw] = scope.split(":");
+ const cols = `id, status, title, position || ':' || coalesce(goal_id,0) || ':' || proposed || ':' || coalesce(severity,'') || ':' || coalesce(origin,'') AS sig`;
+ const sql = kind === "project" ? `SELECT ${cols} FROM tasks WHERE project_id = ? AND archived_at IS NULL` : `SELECT ${cols} FROM tasks WHERE id = ?`;
+ const rows = db.$client.prepare(sql).all(Number(raw)) as Array<{ id: number; status: string; title: string; sig: string }>;
+ return new Map(rows.map((r) => [r.id, { id: r.id, status: r.status, title: r.title, column: columnOf(r.status), sig: String(r.sig) }]));
+}
+
+/** A value scope's provider: the web registers `attention` (it owns navCounts). */
+export type LiveProvider = (db: Db, userId: number) => Promise | unknown;
+const g = globalThis as { __peppaLiveHub?: LiveHub; __peppaLiveProviders?: Map; __peppaBoot?: string };
+const providers = (g.__peppaLiveProviders ??= new Map());
+const hubBoot = `boot-${Date.now().toString(36)}`;
+providers.set("version", () => ({ boot: g.__peppaBoot ?? hubBoot }));
+
+/** Registers the value of a value scope (`attention`, `version`). */
+export function setLiveProvider(scope: "attention" | "version", fn: LiveProvider): void {
+ providers.set(scope, fn);
+}
+
+/** PEP-228: new messages of a chat as the viewer `userId` sees them (the web registers its view). */
+export type LiveChatView = (db: Db, userId: number, messages: ChatMessageView[], files: Map) => Promise | unknown[];
+const gv = globalThis as { __peppaLiveChatView?: LiveChatView };
+export function setLiveChatView(fn: LiveChatView): void {
+ gv.__peppaLiveChatView = fn;
+}
+/** Most new messages one event carries; more — the page re-renders. */
+export const LIVE_CHAT_MAX = 30;
+
+const VALUE_SCOPES = new Set(["attention", "version"]);
+const PER_USER = new Set(["attention", "me"]);
+/** Hub key of a scope: per-user scopes (and a chat — its messages are shown per viewer) are watched per viewer. */
+const keyOf = (scope: LiveScope, userId: number) => (PER_USER.has(scope) || scope.startsWith("chat:") ? `${scope}@${userId}` : scope);
+
+interface Watch {
+ scope: LiveScope;
+ userId: number;
+ listeners: Set;
+ parts?: Parts;
+ v?: string;
+ rows?: Map;
+ chatMax?: number;
+ lastStep?: number;
+ /** Value scopes: last value sent (JSON). */
+ value?: string;
}
class LiveHub {
- private listeners = new Map>();
- private prints = new Map();
- private lastStep = new Map();
+ private watches = new Map();
private timer: ReturnType | null = null;
private wakeTimer: ReturnType | null = null;
private stopSocket: (() => Promise) | null = null;
private seen = "";
+ private checking: Promise | null = null;
+ private again = false;
+ private lastObserve = 0;
+ private lastLoginPoll = 0;
+ private run = 0;
private db: Db;
constructor(db: Db) {
this.db = db;
}
- subscribe(scopes: LiveScope[], fn: Listener): () => void {
- for (const s of scopes) {
- let set = this.listeners.get(s);
- if (!set) {
- this.listeners.set(s, (set = new Set()));
- this.prime(s);
+ /**
+ * Watches `scopes` for the viewer `userId` (needed for `attention` / `me`). `since` — the
+ * version (or the last step id for `steps:`) the client saw before a drop: whatever changed
+ * since is sent right away. Value scopes always send their current value first.
+ */
+ subscribe(scopes: LiveScope[], fn: Listener, opts: { userId?: number; since?: Record } = {}): () => void {
+ const userId = opts.userId ?? 0;
+ const keys: string[] = [];
+ for (const scope of scopes) {
+ const key = keyOf(scope, userId);
+ keys.push(key);
+ let w = this.watches.get(key);
+ if (!w) {
+ this.watches.set(key, (w = { scope, userId, listeners: new Set() }));
+ this.prime(w);
}
- set.add(fn);
+ w.listeners.add(fn);
+ this.catchUp(w, fn, opts.since?.[scope]);
}
this.start();
return () => {
- for (const s of scopes) {
- const set = this.listeners.get(s);
- set?.delete(fn);
- if (set && !set.size) {
- this.listeners.delete(s);
- this.prints.delete(s);
- this.lastStep.delete(s);
- }
+ for (const key of keys) {
+ const w = this.watches.get(key);
+ w?.listeners.delete(fn);
+ if (w && !w.listeners.size) this.watches.delete(key);
}
- if (!this.listeners.size) this.stop();
+ if (!this.watches.size) this.stop();
};
}
/** Remembers the current state, so only later changes are reported. */
- private prime(s: LiveScope) {
+ private prime(w: Watch) {
try {
+ const s = w.scope;
if (s.startsWith("steps:")) {
const row = this.db.$client.prepare(`SELECT coalesce(max(id),0) AS id FROM events WHERE session_id = ? AND type = 'step'`).get(Number(s.slice(6))) as { id: number };
- this.lastStep.set(s, row.id);
- } else this.prints.set(s, fingerprint(this.db, s));
+ w.lastStep = row.id;
+ } else if (!VALUE_SCOPES.has(s)) {
+ w.parts = fingerprint(this.db, s, w.userId);
+ w.v = liveVersion(JSON.stringify(w.parts));
+ if (s.startsWith("project:") || s.startsWith("task:")) w.rows = taskRows(this.db, s);
+ if (s.startsWith("chat:")) w.chatMax = Number(w.parts.m) || 0;
+ }
} catch (e) {
console.error("live: prime failed", e);
}
}
+ /** A new listener: the current value of a value scope, the version of others, missed steps. */
+ private catchUp(w: Watch, fn: Listener, since: string | number | undefined) {
+ const s = w.scope;
+ if (VALUE_SCOPES.has(s)) {
+ void this.value(w).then((data) => {
+ if (data !== undefined && w.listeners.has(fn)) fn({ type: "data", scope: s, v: liveVersion(JSON.stringify(data)), data });
+ });
+ return;
+ }
+ if (s.startsWith("steps:")) {
+ const after = Number(since);
+ if (!after || after >= (w.lastStep ?? 0)) return;
+ for (const r of this.stepsAfter(s, after, 200)) fn({ type: "step", scope: s, step: stepView(r) });
+ return;
+ }
+ if (since !== undefined && w.v && since !== w.v) fn({ type: "change", scope: s, v: w.v, parts: ["*"] });
+ }
+
+ private async value(w: Watch): Promise {
+ const fn = providers.get(w.scope);
+ if (!fn) return undefined;
+ try {
+ const data = await fn(this.db, w.userId);
+ w.value = JSON.stringify(data);
+ return data;
+ } catch (e) {
+ console.error(`live: ${w.scope} value failed`, e);
+ return undefined;
+ }
+ }
+
+ private stepsAfter(scope: LiveScope, after: number, limit: number) {
+ return this.db
+ .select()
+ .from(events)
+ .where(and(eq(events.sessionId, Number(scope.slice(6))), eq(events.type, STEP_EVENT), gt(events.id, after)))
+ .orderBy(events.id)
+ .limit(limit)
+ .all();
+ }
+
private start() {
if (this.timer) return;
this.seen = this.version();
- // Writes of other processes (hooks, watchdog, bot, CLI) and of this one.
+ // Writes of other processes (hooks, watchdog, bot, CLI) and of this one; the observe
+ // database and a pending ChatGPT sign-in are looked at on a timer while somebody watches.
this.timer = setInterval(() => {
const v = this.version();
if (v !== this.seen) {
this.seen = v;
this.wake();
}
+ const now = Date.now();
+ if (this.watches.has("observe") && now - this.lastObserve >= OBSERVE_EVERY_MS) {
+ this.lastObserve = now;
+ this.wake();
+ }
+ if (now - this.lastLoginPoll >= LOGIN_POLL_MS) {
+ this.lastLoginPoll = now;
+ void this.pollLogins();
+ }
}, 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));
}
+ /** One ChatGPT check per watched pending sign-in for all its viewers (it reads the sign-in's tmux pane). */
+ private async pollLogins() {
+ for (const w of [...this.watches.values()]) {
+ if (!w.scope.startsWith("login:") || !w.parts?.sub?.startsWith("pending")) continue;
+ const id = Number(w.scope.slice(6));
+ const row = this.db.$client.prepare(`SELECT provider FROM subscriptions WHERE id = ?`).get(id) as { provider?: string } | undefined;
+ if (row?.provider !== "codex") continue;
+ await pollCodexLogin(this.db, id).catch(() => "pending");
+ }
+ }
+
private stop() {
if (this.timer) clearInterval(this.timer);
this.timer = null;
@@ -227,51 +503,125 @@ class LiveHub {
if (this.wakeTimer || !this.timer) return;
this.wakeTimer = setTimeout(() => {
this.wakeTimer = null;
- this.check();
+ void this.check();
}, WAKE_DEBOUNCE_MS);
}
- /** Recomputes every watched scope now (tests call it directly). */
- check() {
- for (const [scope, set] of this.listeners) {
+ /** Recomputes every watched scope now (tests call it directly). One check at a time. */
+ check(): Promise {
+ if (this.checking) {
+ this.again = true;
+ return this.checking;
+ }
+ this.checking = (async () => {
+ do {
+ this.again = false;
+ for (const w of [...this.watches.values()]) await this.checkOne(w);
+ } while (this.again);
+ })().finally(() => {
+ this.checking = null;
+ });
+ return this.checking;
+ }
+
+ private send(w: Watch, e: LiveEvent) {
+ for (const fn of w.listeners) {
try {
- if (scope.startsWith("steps:")) {
- const after = this.lastStep.get(scope) ?? 0;
- const rows = this.db
- .select()
- .from(events)
- .where(and(eq(events.sessionId, Number(scope.slice(6))), eq(events.type, STEP_EVENT), gt(events.id, after)))
- .orderBy(events.id)
- .limit(50)
- .all();
- if (!rows.length) continue;
- this.lastStep.set(scope, rows.at(-1)!.id);
- for (const r of rows) for (const fn of set) fn({ type: "step", scope, step: stepView(r) });
- continue;
- }
- const fp = fingerprint(this.db, scope);
- if (fp === this.prints.get(scope)) continue;
- this.prints.set(scope, fp);
- for (const fn of set) fn({ type: "change", scope });
- } catch (e) {
- console.error(`live: ${scope} check failed`, e);
+ fn(e);
+ } catch (err) {
+ console.error(`live: ${w.scope} listener failed`, err);
}
}
}
+ private async checkOne(w: Watch) {
+ const scope = w.scope;
+ try {
+ if (scope.startsWith("steps:")) {
+ const rows = this.stepsAfter(scope, w.lastStep ?? 0, 50);
+ if (!rows.length) return;
+ w.lastStep = rows.at(-1)!.id;
+ for (const r of rows) this.send(w, { type: "step", scope, step: stepView(r) });
+ return;
+ }
+ if (VALUE_SCOPES.has(scope)) {
+ if (scope === "version") return; // changes only with the process: a reconnect brings it
+ const before = w.value;
+ const data = await this.value(w);
+ if (data !== undefined && w.value !== before) this.send(w, { type: "data", scope, v: liveVersion(w.value!), data });
+ return;
+ }
+ const parts = fingerprint(this.db, scope, w.userId);
+ const old = w.parts ?? {};
+ const changed = [...new Set([...Object.keys(parts), ...Object.keys(old)])].filter((k) => parts[k] !== old[k]);
+ if (!changed.length) return;
+ w.parts = parts;
+ w.v = liveVersion(JSON.stringify(parts));
+ const e: LiveEvent & { type: "change" } = { type: "change", scope, v: w.v, parts: changed };
+ if (w.rows && (scope.startsWith("project:") || scope.startsWith("task:"))) {
+ const rows = taskRows(this.db, scope);
+ const diff: LiveTaskRow[] = [];
+ for (const [id, { sig, ...r }] of rows) {
+ const was = w.rows.get(id);
+ if (!was) diff.push({ ...r, other: true });
+ else if (was.sig !== sig) diff.push({ ...r, other: true });
+ else if (was.status !== r.status || was.title !== r.title) diff.push(r);
+ }
+ // A story left the board (archived, deleted): the page can't apply that in place.
+ if ([...w.rows.keys()].some((id) => !rows.has(id))) e.parts.push("gone");
+ w.rows = rows;
+ if (diff.length) e.tasks = diff.slice(0, 100);
+ }
+ if (scope.startsWith("chat:")) {
+ const max = Number(parts.m) || 0;
+ if (max > (w.chatMax ?? 0)) {
+ const messages = await this.chatMessages(w, w.chatMax ?? 0);
+ if (messages) e.messages = messages;
+ }
+ w.chatMax = max;
+ }
+ this.send(w, e);
+ } catch (err) {
+ console.error(`live: ${scope} check failed`, err);
+ }
+ }
+
+ /** New messages of a watched chat for its viewer; undefined — too many or failed (the page re-renders). */
+ private async chatMessages(w: Watch, after: number): Promise {
+ try {
+ const { messages, more } = await newChatMessagesView(this.db, Number(w.scope.slice(5)), after, LIVE_CHAT_MAX);
+ if (more) return undefined;
+ const files = await attachmentsByMessage(this.db, messages.map((m) => m.id));
+ const view = gv.__peppaLiveChatView;
+ return view ? await view(this.db, w.userId, messages, files) : messages.map((m) => ({ ...m, files: files.get(m.id) ?? [] }));
+ } catch (err) {
+ console.error(`live: ${w.scope} messages failed`, err);
+ return undefined;
+ }
+ }
+
get watched(): LiveScope[] {
- return [...this.listeners.keys()];
+ return [...new Set([...this.watches.values()].map((w) => w.scope))];
+ }
+
+ /** Current version of a watched scope (tests, `since`). */
+ versionOf(scope: LiveScope, userId = 0): string | undefined {
+ return this.watches.get(keyOf(scope, userId))?.v;
}
}
-const g = globalThis as { __peppaLiveHub?: LiveHub };
-/** The process-wide hub (survives Next dev module reloads). */
+export type { LiveHub };
+
+/** The process-wide hub (survives Next dev module reloads and is shared with the WebSocket server). */
export function liveHub(db: Db): LiveHub {
return (g.__peppaLiveHub ??= new LiveHub(db));
}
-/** SSE response for /api/live: `change` / `step` events, pings for Cloudflare. */
-export async function liveSse(db: Db, user: User, scopes: LiveScope[], signal: AbortSignal, opts: { pingMs?: number } = {}): Promise {
+/** Where the observe database lives (for a test that wants an observe scope). */
+export const liveObservePath = observeDbPath;
+
+/** SSE response for /api/live (the fallback of the tab's WebSocket): `change` / `step` / `data` events, pings for Cloudflare. */
+export async function liveSse(db: Db, user: User, scopes: LiveScope[], signal: AbortSignal, opts: { pingMs?: number; since?: Record } = {}): Promise {
for (const s of scopes) await checkScopeAccess(db, user, s);
const enc = new TextEncoder();
let cleanup = () => {};
@@ -303,7 +653,7 @@ export async function liveSse(db: Db, user: User, scopes: LiveScope[], signal: A
send("retry: 3000\n\n");
send(`event: ready\ndata: ${JSON.stringify({ scopes })}\n\n`);
if (signal.aborted) return close();
- unsubscribe = liveHub(db).subscribe(scopes, (e) => send(`event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`));
+ unsubscribe = liveHub(db).subscribe(scopes, (e) => send(`event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`), { userId: user.id, since: opts.since });
},
cancel() {
cleanup();
diff --git a/packages/shared/package.json b/packages/shared/package.json
index 985b0eea..f4182b0d 100644
--- a/packages/shared/package.json
+++ b/packages/shared/package.json
@@ -8,7 +8,8 @@
"./palette": "./src/palette.ts",
"./i18n": "./src/i18n/index.ts",
"./wording": "./src/wording.ts",
- "./glossary": "./src/glossary.ts"
+ "./glossary": "./src/glossary.ts",
+ "./format": "./src/format.ts"
},
"scripts": {
"typecheck": "tsc -p ."
diff --git a/packages/shared/src/format.ts b/packages/shared/src/format.ts
new file mode 100644
index 00000000..a85fb615
--- /dev/null
+++ b/packages/shared/src/format.ts
@@ -0,0 +1,4 @@
+// Small formatters safe for the browser bundle (no Node modules).
+
+/** «12 KB» — the size of a file for a person. */
+export const humanSize = (n: number) => (n < 1024 ? `${n} B` : n < 1024 * 1024 ? `${Math.round(n / 1024)} KB` : `${(n / 1024 / 1024).toFixed(1).replace(/\.0$/, "")} MB`);
diff --git a/packages/shared/src/i18n/en/runner.ts b/packages/shared/src/i18n/en/runner.ts
index 07173b23..89cb4922 100644
--- a/packages/shared/src/i18n/en/runner.ts
+++ b/packages/shared/src/i18n/en/runner.ts
@@ -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",
diff --git a/packages/shared/src/i18n/en/story.ts b/packages/shared/src/i18n/en/story.ts
index 321866e5..3ecf5b87 100644
--- a/packages/shared/src/i18n/en/story.ts
+++ b/packages/shared/src/i18n/en/story.ts
@@ -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",
diff --git a/packages/shared/src/i18n/kk/runner.ts b/packages/shared/src/i18n/kk/runner.ts
index 979b11ee..4ee70b01 100644
--- a/packages/shared/src/i18n/kk/runner.ts
+++ b/packages/shared/src/i18n/kk/runner.ts
@@ -171,6 +171,9 @@ export const runner: Dict = {
"{who} упёрлась в лимит.": "{who} лимитке тірелді.",
"{who}: остановлен по лимиту, продолжит в {time} сам.": "{who}: лимит бойынша тоқтатылды, өзі жалғастырады: {time}.",
"{who}: остановлен по лимиту, время сброса неизвестно — попробую продолжить в {time}.": "{who}: лимит бойынша тоқтатылды, қалпына келу уақыты белгісіз — жалғастыруға тырысамын: {time}.",
+ "Неизвестное сообщение": "Белгісіз хабарлама",
+ "Слишком много областей": "Аймақтар тым көп",
+ "Ввод — только в терминал": "Енгізу тек терминалға",
"Неизвестная область: {scope}": "Белгісіз аймақ: {scope}",
"Нужна область (scope)": "Аймақ (scope) керек",
"планировщик ответил не по формату — попробуйте ещё раз или уточните описание эпика": "жоспарлаушы форматқа сай жауап бермеді — қайталап көріңіз немесе эпик сипаттамасын нақтылаңыз",
diff --git a/packages/shared/src/i18n/kk/story.ts b/packages/shared/src/i18n/kk/story.ts
index 9ecfbecc..1809ddaa 100644
--- a/packages/shared/src/i18n/kk/story.ts
+++ b/packages/shared/src/i18n/kk/story.ts
@@ -281,8 +281,8 @@ export const story: Dict = {
"подключение…": "қосылуда…",
"в реальном времени": "нақты уақытта",
"переподключение…": "қайта қосылуда…",
- "опрос раз в 5 с": "5 с сайын сұрау",
- "Канал событий недоступен — страница обновляется по таймеру": "Оқиғалар арнасы қолжетімсіз — бет таймер бойынша жаңартылады",
+ "нет связи — пробуем снова": "байланыс жоқ — қайта көріп жатырмыз",
+ "Нет связи с Peppa FACTORY — страница обновится, когда связь вернётся": "Peppa FACTORY-мен байланыс жоқ — байланыс қалпына келгенде бет жаңарады",
"Страница обновляется сама, когда что-то меняется": "Бір нәрсе өзгергенде бет өзі жаңарады",
"Превью": "Превью",
"Посмотреть": "Қарау",
diff --git a/packages/testkit/test/chat-live.test.ts b/packages/testkit/test/chat-live.test.ts
new file mode 100644
index 00000000..cad17689
--- /dev/null
+++ b/packages/testkit/test/chat-live.test.ts
@@ -0,0 +1,150 @@
+// PEP-228: a chat page's own scope `chat:` — access like the page's, new messages of the chat
+// come in the event (and only to this chat's watchers); the page draws messages of its
+// conversation in place and leaves questions, offers and other threads to a server re-render.
+import assert from "node:assert/strict";
+import { after, describe, test } from "node:test";
+import { LiveConnection } from "@peppa/runner/live-ws";
+import { core, db, project, runner, teardown } from "./helpers.ts";
+
+process.env.PEPPA_SECRET = "mock-secret-for-tests";
+after(teardown);
+
+const { chatParts, inView } = (await import(new URL("../../../apps/web/lib/chat-live-types.ts", import.meta.url).href)) as typeof import("../../../apps/web/lib/chat-live-types.ts");
+
+let seq = 0;
+const user = (login: string) => core.upsertUserFromGitea(db, { id: 9300 + seq++, login }, { access_token: "x" });
+type Msg = Record & { t: string };
+
+function conn(u: import("@peppa/core").User) {
+ const out: Msg[] = [];
+ const c = new LiveConnection(db, u, (m) => out.push(m as Msg), () => {});
+ return { c, out, send: (m: object) => c.receive(JSON.stringify(m)), events: () => out.filter((m) => m.t === "ev") as Array> }> };
+}
+
+async function ownedChat(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);
+ const chat = await core.ensureProjectChat(db, ref.project.id);
+ return { owner, ref, chat };
+}
+
+const say = (chatId: number, text: string, o: Partial[1]> = {}) =>
+ core.addChatMessage(db, { chatId, kind: "user", authorKind: "agent", authorLogin: "Аналитик", text, ...o });
+
+describe("chat messages in place (PEP-228)", () => {
+ test("Чужой чат: 404, мастер-чат — только владельцу", async () => {
+ const a = await ownedChat("cl-owner-1");
+ const bob = await user("cl-bob-1");
+ const x = conn(bob);
+ await x.send({ t: "sub", scope: `chat:${a.chat.id}` });
+ assert.equal(x.out.at(-1)!.status, 404);
+ const master = await core.ensureMasterChat(db, a.owner.id);
+ await x.send({ t: "sub", scope: `chat:${master.id}` });
+ assert.equal(x.out.at(-1)!.status, 404, "somebody else's master chat");
+ await x.send({ t: "sub", scope: "chat:999999" });
+ assert.equal(x.out.at(-1)!.status, 404);
+ assert.deepEqual(x.c.scopes, []);
+ const own = conn(a.owner);
+ await own.send({ t: "sub", scope: `chat:${master.id}` });
+ assert.equal(own.out.at(-1)!.t, "ok");
+ x.c.close();
+ own.c.close();
+ });
+
+ test("Ответ аналитика приходит в событии своего чата и не приходит в чужой", async () => {
+ const a = await ownedChat("cl-owner-2");
+ const b = await ownedChat("cl-owner-3");
+ const x = conn(a.owner);
+ await x.send({ t: "sub", scope: `chat:${a.chat.id}` });
+ assert.equal(x.out.at(-1)!.t, "ok");
+ try {
+ await say(b.chat.id, "Ответ в другом проекте");
+ await runner.liveHub(db).check();
+ assert.equal(x.events().length, 0, "another chat is not this scope");
+
+ const m = await say(a.chat.id, "В работе PAY-3");
+ await runner.liveHub(db).check();
+ const ev = x.events().at(-1)!;
+ assert.ok(ev, "the change arrives");
+ assert.ok(ev.parts.includes("m"));
+ assert.deepEqual(ev.messages?.map((r) => [r.id, r.text, r.authorKind]), [[m!.id, "В работе PAY-3", "agent"]]);
+ assert.deepEqual(ev.messages?.[0]!.files, []);
+ } finally {
+ x.c.close();
+ }
+ });
+
+ test("Вид для зрителя: поставщик веба получает зрителя и сообщения", async () => {
+ const a = await ownedChat("cl-owner-4");
+ const seen: Array<[number, number[]]> = [];
+ runner.setLiveChatView((_db, userId, messages) => {
+ seen.push([userId, messages.map((m) => m.id)]);
+ return messages.map((m) => ({ id: m.id, main: `для ${userId}` }));
+ });
+ const x = conn(a.owner);
+ await x.send({ t: "sub", scope: `chat:${a.chat.id}` });
+ try {
+ const m = await say(a.chat.id, "Готово");
+ await runner.liveHub(db).check();
+ assert.deepEqual(seen.at(-1), [a.owner.id, [m!.id]]);
+ assert.deepEqual(x.events().at(-1)!.messages, [{ id: m!.id, main: `для ${a.owner.id}` }]);
+ } finally {
+ x.c.close();
+ runner.setLiveChatView(undefined as never);
+ }
+ });
+
+ test("Вопрос агента: в событии с пометкой вопроса, на месте не рисуется", async () => {
+ const a = await ownedChat("cl-owner-5");
+ const x = conn(a.owner);
+ await x.send({ t: "sub", scope: `chat:${a.chat.id}` });
+ try {
+ await core.askPm(db, a.ref, { kind: "question", text: "Какой разделитель?", options: [";", ","] });
+ await core.syncChats(db);
+ await runner.liveHub(db).check();
+ const evs = x.events();
+ assert.ok(evs.some((e) => e.parts.includes("q")), "questions changed — the page re-renders");
+ const withMsg = evs.find((e) => e.messages?.length);
+ assert.ok(withMsg?.messages?.some((r) => r.question), "the question message is in the event");
+ } finally {
+ x.c.close();
+ }
+ });
+});
+
+describe("what the chat page draws in place (PEP-228)", () => {
+ const msg = (o: Record) => ({ id: 1, threadKey: null, kind: "user", command: false, notice: false, render: false, ...o }) as never;
+
+ test("Сообщение своей переписки — на месте, без перерисовки", () => {
+ const r = chatParts({ parts: ["m"], messages: [msg({ id: 5 })] }, { kind: "discussion" });
+ assert.deepEqual(r.applied, ["x", "m"]);
+ assert.deepEqual(r.add.map((m) => m.id), [5]);
+ });
+
+ test("Вопрос или кнопки — перерисовка", () => {
+ const r = chatParts({ parts: ["m", "q"], messages: [msg({ id: 6, threadKey: "task:3", kind: "question", render: true })] }, { kind: "thread", key: "task:3" });
+ assert.deepEqual(r.applied, ["x"]);
+ assert.deepEqual(r.add, []);
+ });
+
+ test("Сообщение другого треда — не в ленту, перерисовка списка", () => {
+ const r = chatParts({ parts: ["m"], messages: [msg({ id: 7, threadKey: "task:4", kind: "event" })] }, { kind: "thread", key: "task:3" });
+ assert.deepEqual(r.applied, ["x"]);
+ assert.deepEqual(r.add, []);
+ });
+
+ test("Без сообщений (их слишком много) — перерисовка", () => {
+ assert.deepEqual(chatParts({ parts: ["m", "x"] }, { kind: "feed" }).applied, []);
+ });
+
+ test("Обсуждение: без событий, команд и служебных строк; «События агентов» — всё", () => {
+ assert.equal(inView(msg({ threadKey: "task:3" }), { kind: "discussion" }), false);
+ assert.equal(inView(msg({ kind: "event" }), { kind: "discussion" }), false);
+ assert.equal(inView(msg({ command: true }), { kind: "discussion" }), false);
+ assert.equal(inView(msg({ notice: true }), { kind: "discussion" }), false);
+ assert.equal(inView(msg({ threadKey: "task:3", kind: "event" }), { kind: "feed" }), true);
+ assert.equal(inView(msg({ kind: "event" }), { kind: "channel" }), true);
+ });
+});
diff --git a/packages/testkit/test/live-ws.test.ts b/packages/testkit/test/live-ws.test.ts
new file mode 100644
index 00000000..9046ddf0
--- /dev/null
+++ b/packages/testkit/test/live-ws.test.ts
@@ -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 & { t: string };
+
+/** A connection driven directly: what the server sent and how it closed. */
+function conn(u: import("@peppa/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((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) =>
+ 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();
+ }
+ });
+});
diff --git a/packages/testkit/test/story-live.test.ts b/packages/testkit/test/story-live.test.ts
index 323bc368..76ebd3c7 100644
--- a/packages/testkit/test/story-live.test.ts
+++ b/packages/testkit/test/story-live.test.ts
@@ -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(() => {});
});
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 35c8d02f..0128d756 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -265,6 +265,9 @@ importers:
tailwind-merge:
specifier: 3.7.0
version: 3.7.0
+ ws:
+ specifier: 8.18.3
+ version: 8.18.3
devDependencies:
'@tailwindcss/postcss':
specifier: 4.3.5
@@ -374,6 +377,13 @@ importers:
drizzle-orm:
specifier: 0.45.4
version: 0.45.4(postgres@4.1.1)
+ ws:
+ specifier: 8.18.3
+ version: 8.18.3
+ devDependencies:
+ '@types/ws':
+ specifier: 8.18.1
+ version: 8.18.1
packages/shared:
dependencies:
@@ -1272,6 +1282,9 @@ packages:
'@types/react@19.3.0':
resolution: {integrity: sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==}
+ '@types/ws@8.18.1':
+ resolution: {integrity: sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==}
+
'@xterm/headless@6.0.0':
resolution: {integrity: sha512-5Yj1QINYCyzrZtf8OFIHi47iQtI+0qYFPHmouEfG8dHNxbZ9Tb9YGSuLcsEwj9Z+OL75GJqPyJbyoFer80a2Hw==}
@@ -2101,6 +2114,18 @@ packages:
wrappy@1.0.2:
resolution: {integrity: sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==}
+ ws@8.18.3:
+ resolution: {integrity: sha512-PEIGCY5tSlUt50cqyMXfCzX+oOPqN0vuGqWzbcJ2xvnkzkq46oOpz7dQaTDBdfICb4N14+GARUDw2XV2N4tvzg==}
+ engines: {node: '>=10.0.0'}
+ peerDependencies:
+ bufferutil: ^4.0.1
+ utf-8-validate: '>=5.0.2'
+ peerDependenciesMeta:
+ bufferutil:
+ optional: true
+ utf-8-validate:
+ optional: true
+
y18n@4.0.3:
resolution: {integrity: sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==}
@@ -2661,6 +2686,10 @@ snapshots:
dependencies:
csstype: 3.2.3
+ '@types/ws@8.18.1':
+ dependencies:
+ '@types/node': 26.6.6
+
'@xterm/headless@6.0.0': {}
'@xterm/xterm@6.0.0': {}
@@ -3441,6 +3470,8 @@ snapshots:
wrappy@1.0.2: {}
+ ws@8.18.3: {}
+
y18n@4.0.3: {}
yargs-parser@18.1.3:
diff --git a/scripts/install-launchd.sh b/scripts/install-launchd.sh
index bacd75f4..20035d30 100755
--- a/scripts/install-launchd.sh
+++ b/scripts/install-launchd.sh
@@ -1,9 +1,10 @@
#!/usr/bin/env bash
# Installs Peppa's launchd agents (start at login, restart on crash):
# quest.telecom.peppa.watchdog — session watchdog under caffeinate -i (no idle sleep)
-# quest.telecom.peppa.web — Next.js platform on :3100 (needs `pnpm --filter @peppa/web build`);
-# PEPPA_WEB_MODE=dev runs `next dev` instead (HMR: edits in this
-# checkout go live without build or release — the pre-launch setup)
+# quest.telecom.peppa.web — Next.js platform on :3100 (needs `pnpm --filter @peppa/web build`)
+# through its own server apps/web/server.ts (PEP-225: WebSocket
+# /api/ws); a checkout without it (a rollback) — plain `next start`.
+# PEPPA_WEB_MODE=dev runs it in dev mode (HMR)
# quest.telecom.peppa.bot — Telegram bot (TELEGRAM_BOT_TOKEN in .env)
# quest.telecom.peppa.observer — Observability monitors (PEP-202), own DB ~/.peppa/observe.db
# quest.telecom.peppa.release — Peppa's own prod releases (PEP-18): started by launchd while
@@ -84,7 +85,7 @@ for s in "${SERVICES[@]}"; do
/usr/bin/caffeinate -i "$ROOT/packages/cli/bin/peppa" watchdog ;;
web)
install_agent quest.telecom.peppa.web web.log "$ROOT/apps/web" \
- /bin/bash -c "set -a; . '$ROOT/.env'; set +a; exec '$ROOT/apps/web/node_modules/.bin/next' $WEB_MODE -p 3100" ;;
+ /bin/bash -c "set -a; . '$ROOT/.env'; set +a; if [ -f server.ts ]; then exec '$NODE_BIN' server.ts $([ "$WEB_MODE" = dev ] && echo --dev) -p 3100; else exec '$ROOT/apps/web/node_modules/.bin/next' $WEB_MODE -p 3100; fi" ;;
bot)
install_agent quest.telecom.peppa.bot bot.log "$ROOT" "$ROOT/apps/bot/bin/peppa-bot" ;;
observer)
diff --git a/scripts/live-deploy.sh b/scripts/live-deploy.sh
index cf02ee83..b9df4151 100755
--- a/scripts/live-deploy.sh
+++ b/scripts/live-deploy.sh
@@ -128,6 +128,10 @@ say "built ${TARGET:0:8}"
# 7. Restart and health.
# PEP-202: the observer is restarted too once it is installed here.
restart() {
+ # PEP-225: the web agent of an older install starts `next start` directly — reinstall it once
+ # so it goes through apps/web/server.ts (the WebSocket channel); reinstalling restarts it.
+ local webplist="$HOME/Library/LaunchAgents/quest.telecom.peppa.web.plist"
+ if [ -f "$webplist" ] && ! grep -q 'server.ts' "$webplist"; then "$ROOT/scripts/install-launchd.sh" web >/dev/null; fi
for s in web watchdog bot; do launchctl kickstart -k "gui/$UIDN/quest.telecom.peppa.$s"; done
launchctl print "gui/$UIDN/quest.telecom.peppa.observer" >/dev/null 2>&1 && launchctl kickstart -k "gui/$UIDN/quest.telecom.peppa.observer" || true
}