peppa/packages/runner/src/live.ts
2026-11-15 14:47:50 +05:00

313 lines
12 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

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

// 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:<sessionId>` watchers as data.
import { m } from "@peppa/shared/i18n";
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 { and, eq, gt } from "drizzle-orm";
export type LiveScope = "home" | "runners" | "chats" | `project:${number}` | `task:${number}` | `steps:${number}`;
export type LiveEvent = { type: "change"; scope: LiveScope } | { type: "step"; scope: LiveScope; step: StepView };
type Listener = (e: LiveEvent) => void;
export const LIVE_PING_MS = 15_000;
/** Refusal of a live stream with its HTTP status. */
export class LiveError extends Error {
status: number;
constructor(message: string, status: number) {
super(message);
this.status = status;
}
}
const WAKE_DEBOUNCE_MS = 250;
/** Parses `?scope=a,b`; unknown parts are refused. */
export function parseScopes(raw: string | null): LiveScope[] {
const out = new Set<LiveScope>();
for (const part of (raw ?? "").split(",").map((s) => s.trim()).filter(Boolean)) {
if (part === "home" || part === "runners" || part === "chats") 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);
}
if (!out.size || out.size > 8) throw new LiveError(m("Нужна область (scope)"), 400);
return [...out];
}
/** Access: project/story/runner scopes need the project; home/runners only a user. */
export async function checkScopeAccess(db: Db, user: User, scope: LiveScope): Promise<void> {
const [kind, raw] = scope.split(":") as [string, string?];
const id = Number(raw);
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);
await projectForUser(db, user.id, projectId).catch(() => {
throw new LiveError(m("Не найдено"), 404);
});
}
const ACTIVE_SESSIONS = `group_concat(CASE WHEN ended_at IS NULL THEN id || ':' || status END)`;
/** One SQL per scope; frequent fields (last_activity_at, steps, heartbeats) are left out. */
function fingerprint(db: Db, scope: LiveScope): string {
const c = db.$client;
const [kind, raw] = scope.split(":") as [string, string?];
const id = Number(raw);
if (kind === "task") {
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 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,
(SELECT coalesce(max(updated_at),0) || ':' || count(*) FROM check_runs WHERE task_id = ?1) AS ci,
(SELECT coalesce(max(updated_at),0) || ':' || count(*) FROM code_reviews WHERE task_id = ?1) AS r,
(SELECT p.workspace_path FROM tasks t JOIN projects p ON p.id = t.project_id WHERE t.id = ?1) AS ws,
(SELECT openspec_change FROM tasks WHERE id = ?1) AS ch`,
)
.get(id) as Record<string, string | number | null> | undefined;
if (!row) 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");
if (file && existsSync(file)) tasksMtime = statSync(file).mtimeMs;
}
return [row.t, row.e, row.q, row.s, row.ci, row.r, tasksMtime].join("|");
}
if (kind === "project") {
const row = c
.prepare(
`SELECT
(SELECT coalesce(max(updated_at),0) || ':' || count(*) FROM tasks WHERE project_id = ?1) 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,
(SELECT coalesce(max(updated_at),0) FROM check_runs WHERE project_id = ?1) AS ci,
(SELECT coalesce(max(id),0) || ':' || count(*) FROM releases WHERE project_id = ?1) AS rel,
(SELECT coalesce(max(updated_at),0) FROM goals WHERE project_id = ?1) AS g,
(SELECT updated_at FROM projects WHERE id = ?1) AS p`,
)
.get(id) as Record<string, unknown>;
return Object.values(row).join("|");
}
if (kind === "chats") {
// PEP-62: a new chat message (projected or written) or a question answered anywhere.
const row = c
.prepare(
`SELECT
(SELECT coalesce(max(id),0) FROM chat_messages) AS m,
(SELECT count(*) || ':' || count(answered_at) FROM questions) AS q,
(SELECT coalesce(max(id),0) FROM events WHERE type <> 'step') AS e,
(SELECT coalesce(group_concat(id || ':' || coalesce(tg_chat_id,'')),'') FROM chats WHERE tg_chat_id IS NOT NULL) AS tg`,
)
.get() as Record<string, unknown>;
return Object.values(row).join("|");
}
// home / runners: across projects (only wakes the page — data stays behind access checks).
const row = c
.prepare(
`SELECT
(SELECT coalesce(max(updated_at),0) || ':' || count(*) FROM tasks) AS t,
(SELECT count(*) || ':' || count(answered_at) FROM questions) AS q,
(SELECT count(*) || ':' || coalesce(${ACTIVE_SESSIONS},'') FROM sessions) AS s,
(SELECT count(*) FROM projects) AS p`,
)
.get() as Record<string, unknown>;
return Object.values(row).join("|");
}
class LiveHub {
private listeners = new Map<LiveScope, Set<Listener>>();
private prints = new Map<LiveScope, string>();
private lastStep = new Map<LiveScope, number>();
private timer: ReturnType<typeof setInterval> | null = null;
private wakeTimer: ReturnType<typeof setTimeout> | null = null;
private stopSocket: (() => Promise<void>) | null = null;
private seen = "";
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);
}
set.add(fn);
}
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);
}
}
if (!this.listeners.size) this.stop();
};
}
/** Remembers the current state, so only later changes are reported. */
private prime(s: LiveScope) {
try {
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));
} catch (e) {
console.error("live: prime failed", e);
}
}
private start() {
if (this.timer) return;
this.seen = this.version();
// Writes of other processes (hooks, watchdog, bot, CLI) and of this one.
this.timer = setInterval(() => {
const v = this.version();
if (v !== this.seen) {
this.seen = v;
this.wake();
}
}, 1000);
this.timer.unref?.();
listenEvents("web", () => this.wake())
.then((stop) => {
if (this.timer) this.stopSocket = stop;
else void stop();
})
.catch((e) => console.error("live: web.events.sock unavailable, data_version only:", (e as Error).message));
}
private stop() {
if (this.timer) clearInterval(this.timer);
this.timer = null;
if (this.wakeTimer) clearTimeout(this.wakeTimer);
this.wakeTimer = null;
void this.stopSocket?.();
this.stopSocket = null;
}
private version(): string {
try {
const c = this.db.$client;
const own = c.prepare("SELECT total_changes() AS n").get() as { n: number };
return `${c.dataVersion()}:${own.n}`;
} catch {
return this.seen;
}
}
/** Debounced: a burst of writes is one check. */
wake() {
if (this.wakeTimer || !this.timer) return;
this.wakeTimer = setTimeout(() => {
this.wakeTimer = null;
this.check();
}, WAKE_DEBOUNCE_MS);
}
/** Recomputes every watched scope now (tests call it directly). */
check() {
for (const [scope, set] of this.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);
}
}
}
get watched(): LiveScope[] {
return [...this.listeners.keys()];
}
}
const g = globalThis as { __peppaLiveHub?: LiveHub };
/** The process-wide hub (survives Next dev module reloads). */
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<Response> {
for (const s of scopes) await checkScopeAccess(db, user, s);
const enc = new TextEncoder();
let cleanup = () => {};
const body = new ReadableStream<Uint8Array>({
start(controller) {
let closed = false;
let unsubscribe = () => {};
const send = (chunk: string) => {
if (closed) return;
try {
controller.enqueue(enc.encode(chunk));
} catch {
close();
}
};
const ping = setInterval(() => send(": ping\n\n"), opts.pingMs ?? LIVE_PING_MS);
const close = () => {
if (closed) return;
closed = true;
clearInterval(ping);
unsubscribe();
signal.removeEventListener("abort", close);
try {
controller.close();
} catch {}
};
cleanup = close;
signal.addEventListener("abort", close);
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`));
},
cancel() {
cleanup();
},
});
return new Response(body, {
headers: {
"Content-Type": "text/event-stream; charset=utf-8",
"Cache-Control": "no-cache, no-transform",
"X-Accel-Buffering": "no",
Connection: "keep-alive",
},
});
}