peppa/apps/web/app/api/live/route.ts

27 lines
1.3 KiB
TypeScript

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