Функция → мониторинги (core/feature-status.ts), серая кнопка входа через eGov и статус MCP, отказ startEgovFlow, журнал и сообщения в канал. После переезда живых обновлений на WebSocket (PEP-225): область `features` в LIVE_PLAIN_SCOPES, открыта без входа (SSE и WebSocket с `anonymous: true` — только открытые области), смотрится по таймеру вместе с `observe`, смена сбрасывает кэш статусов. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
679 lines
30 KiB
TypeScript
679 lines
30 KiB
TypeScript
// 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:<sessionId>` 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 { attachmentsByMessage, featureFingerprint, findChangeDir, newChatMessagesView, isSuperadmin, listenEvents, observeDb, observeDbPath, projectForUser, resetFeatureCache, 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";
|
||
|
||
/** Scopes without an id. `attention` and `me` are per user (the hub keys them by the viewer); `features` (PEP-224) is open without a sign-in. */
|
||
export const LIVE_PLAIN_SCOPES = ["home", "runners", "chats", "team", "attention", "version", "observe", "subs", "me", "features"] 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 or a subscription 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;
|
||
/** 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;
|
||
|
||
/** 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<LiveScope>();
|
||
for (const part of (raw ?? "").split(",").map((s) => s.trim()).filter(Boolean)) {
|
||
const s = parseScope(part);
|
||
if (s.startsWith("terminal:")) throw new LiveError(m("Неизвестная область: {scope}", { scope: part }), 400);
|
||
out.add(s);
|
||
}
|
||
if (!out.size || out.size > LIVE_MAX_SCOPES) throw new LiveError(m("Нужна область (scope)"), 400);
|
||
return [...out];
|
||
}
|
||
|
||
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:<id>` the author of that sign-in or a superadmin,
|
||
* `chat:<id>` the project's people (a master chat — its owner only); `features` (PEP-224) — anybody,
|
||
* the login page watches it.
|
||
*/
|
||
export async function checkScopeAccess(db: Db, user: User | null, scope: LiveScope): Promise<void> {
|
||
if (scope === "features") return;
|
||
if (!user) throw new LiveError(m("Нужен вход"), 401);
|
||
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 notFound();
|
||
await projectForUser(db, user.id, projectId).catch(() => {
|
||
throw notFound();
|
||
});
|
||
}
|
||
|
||
/** 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);
|
||
|
||
const ACTIVE_SESSIONS = `group_concat(CASE WHEN ended_at IS NULL THEN id || ':' || status END)`;
|
||
type Parts = Record<string, string>;
|
||
const str = (row: Record<string, unknown> | 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<string, { file: string | null; at: number }>();
|
||
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 {
|
||
// PEP-224: features follow monitors (observe.db) — no user data, the login page watches it too.
|
||
if (scope === "features") return { f: featureFingerprint() };
|
||
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) 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,
|
||
(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?.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 file = tasksMdPath(String(row.ws), String(row.ch));
|
||
if (file && existsSync(file)) tasksMtime = statSync(file).mtimeMs;
|
||
}
|
||
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(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,
|
||
(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 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<string, unknown>;
|
||
return str(row);
|
||
}
|
||
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 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<string, unknown>;
|
||
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<string, unknown> | 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<string, unknown> | 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<string, unknown>;
|
||
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
|
||
// agent a live runner has.
|
||
const row = c
|
||
.prepare(
|
||
`SELECT
|
||
(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${
|
||
kind === "team"
|
||
? `,
|
||
(SELECT coalesce(group_concat(id || ':' || name || ':' || coalesce(disabled_at,'')),'') FROM agents) AS a,
|
||
(SELECT coalesce(group_concat(id || ':' || coalesce(agent_id,'')),'') FROM sessions WHERE ended_at IS NULL) AS sa`
|
||
: ""
|
||
}`,
|
||
)
|
||
.get() as Record<string, unknown>;
|
||
return str(row);
|
||
}
|
||
|
||
/** Board rows of a project / the story, keyed by id: «status|title». */
|
||
function taskRows(db: Db, scope: LiveScope): Map<number, Row> {
|
||
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> | unknown;
|
||
const g = globalThis as { __peppaLiveHub?: LiveHub; __peppaLiveProviders?: Map<string, LiveProvider>; __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<number, AttachmentView[]>) => Promise<unknown[]> | 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<Listener>;
|
||
parts?: Parts;
|
||
v?: string;
|
||
rows?: Map<number, Row>;
|
||
chatMax?: number;
|
||
lastStep?: number;
|
||
/** Value scopes: last value sent (JSON). */
|
||
value?: string;
|
||
}
|
||
|
||
class LiveHub {
|
||
private watches = new Map<string, Watch>();
|
||
private timer: ReturnType<typeof setInterval> | null = null;
|
||
private wakeTimer: ReturnType<typeof setTimeout> | null = null;
|
||
private stopSocket: (() => Promise<void>) | null = null;
|
||
private seen = "";
|
||
private checking: Promise<void> | null = null;
|
||
private again = false;
|
||
private lastObserve = 0;
|
||
private lastLoginPoll = 0;
|
||
private run = 0;
|
||
private db: Db;
|
||
constructor(db: Db) {
|
||
this.db = db;
|
||
}
|
||
|
||
/**
|
||
* 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<string, string | number | undefined> } = {}): () => 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);
|
||
}
|
||
w.listeners.add(fn);
|
||
this.catchUp(w, fn, opts.since?.[scope]);
|
||
}
|
||
this.start();
|
||
return () => {
|
||
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.watches.size) this.stop();
|
||
};
|
||
}
|
||
|
||
/** Remembers the current state, so only later changes are reported. */
|
||
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 };
|
||
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<unknown> {
|
||
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; 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();
|
||
// PEP-224: `features` too — the observer writes observe.db only.
|
||
if ((this.watches.has("observe") || this.watches.has("features")) && 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 && 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;
|
||
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;
|
||
void this.check();
|
||
}, WAKE_DEBOUNCE_MS);
|
||
}
|
||
|
||
/** Recomputes every watched scope now (tests call it directly). One check at a time. */
|
||
check(): Promise<void> {
|
||
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 {
|
||
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));
|
||
// PEP-224: the observer announced a feature change — pages must not read the 15 s cache.
|
||
if (scope === "features") resetFeatureCache();
|
||
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<unknown[] | undefined> {
|
||
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 [...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;
|
||
}
|
||
}
|
||
|
||
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));
|
||
}
|
||
|
||
/** 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 | null, scopes: LiveScope[], signal: AbortSignal, opts: { pingMs?: number; since?: Record<string, string> } = {}): 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`), { userId: user?.id ?? 0, since: opts.since });
|
||
},
|
||
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",
|
||
},
|
||
});
|
||
}
|