peppa/apps/web/lib/queries.ts
Асель 4a80d9dc6b PEP-32/33/37: story page tabs, live agent step feed, SSE live updates instead of 5 s polling
- PEP-37: change hub (runner/live.ts) woken by notify() (new 'web' subscriber) and
  PRAGMA data_version; per-scope fingerprints; GET /api/live SSE (no-transform, ping 15 s);
  LiveRefresh replaces AutoRefresh with a connection indicator and polling fallback
- PEP-33: async PostToolUse/PostToolUseFailure hook -> 'step' events (last 200 per
  session), AgentSteps live feed on the story page and runner panel, tasks.md progress
  on board cards and the story header
- PEP-32: story page header + tabs Proposal/Design/Specs/Tasks/Comments/Tests/Merge
  request/Activity, safe Markdown renderer, PM comments visible in get_task, edit
  title/description/epic, accept-and-merge (acceptStory)
- OpenSpec changes archived; specs live-updates, agent-steps, story-page

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 05:59:15 +05:00

75 lines
3.9 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.

import { listSessions, PeppaError, STEP_EVENT, projectForUser, resolveTask, userProjectIds, type Project, type TaskRef } from "@peppa/core";
import { events, projects, questions, sessions, tasks } from "@peppa/db";
import { formatTaskKey } from "@peppa/shared";
import { and, asc, count, desc, eq, inArray, isNull, ne } from "drizzle-orm";
import { db } from "./db";
export type InboxItem = Awaited<ReturnType<typeof inbox>>[number];
/** Open PM questions across the user's projects, oldest first. */
export async function inbox(userId: number) {
const ids = await userProjectIds(db, userId);
if (!ids.length) return [];
const rows = await db
.select({ q: questions, projectKey: projects.key, taskNumber: tasks.number, taskTitle: tasks.title, taskStatus: tasks.status, tmux: sessions.tmuxName })
.from(questions)
.innerJoin(projects, eq(questions.projectId, projects.id))
.leftJoin(tasks, eq(questions.taskId, tasks.id))
.leftJoin(sessions, eq(questions.sessionId, sessions.id))
.where(and(inArray(projects.id, ids), isNull(questions.answeredAt)))
.orderBy(asc(questions.id));
return rows.map((r) => ({ ...r.q, taskKey: r.taskNumber != null ? formatTaskKey(r.projectKey, r.taskNumber) : null, taskTitle: r.taskTitle, taskStatus: r.taskStatus, tmux: r.tmux }));
}
export async function activeSessions(userId: number) {
const ids = new Set(await userProjectIds(db, userId));
if (!ids.size) return [];
return (await listSessions(db, { active: true })).filter((s) => ids.has(s.projectId));
}
export async function projectForUserByKey(userId: number, key: string): Promise<Project> {
const [p] = await db.select().from(projects).where(eq(projects.key, key.toUpperCase()));
if (!p) throw new PeppaError("Не найдено");
return projectForUser(db, userId, p.id);
}
export async function board(projectId: number) {
const ts = await db.select().from(tasks).where(eq(tasks.projectId, projectId)).orderBy(asc(tasks.number));
return { tasks: ts };
}
export async function projectSessions(projectId: number) {
return (await listSessions(db)).filter((s) => s.projectId === projectId).slice(0, 20);
}
export async function taskForUser(userId: number, key: string): Promise<TaskRef> {
const ref = await resolveTask(db, key);
await projectForUser(db, userId, ref.project.id);
return ref;
}
export async function taskActivity(taskId: number) {
const qs = await db.select().from(questions).where(eq(questions.taskId, taskId)).orderBy(desc(questions.id));
const ss = await listSessions(db, { taskId });
// Steps of agents (PEP-33) have their own live feed.
const evs = await db.select().from(events).where(and(eq(events.taskId, taskId), ne(events.type, STEP_EVENT))).orderBy(desc(events.id)).limit(100);
return { questions: qs, sessions: ss, events: evs };
}
export const isActiveSession = (status: string) => !["done", "failed"].includes(status);
/** OpenSpec artifacts of a change from the working copy (active or archived). */
/** Counters of the side navigation (PEP-38): open PM questions and runners waiting for the PM. */
export async function navCounts(userId: number): Promise<{ questions: number; waitingRunners: number }> {
const ids = await userProjectIds(db, userId);
if (!ids.length) return { questions: 0, waitingRunners: 0 };
const [q] = await db.select({ n: count() }).from(questions).where(and(inArray(questions.projectId, ids), isNull(questions.answeredAt)));
const [r] = await db.select({ n: count() }).from(sessions).where(and(inArray(sessions.projectId, ids), eq(sessions.status, "waiting_input")));
return { questions: q?.n ?? 0, waitingRunners: r?.n ?? 0 };
}
/** Latest events of one runner, newest first (runner details panel, PEP-38). */
export async function sessionEvents(sessionId: number, limit = 12) {
return db.select().from(events).where(and(eq(events.sessionId, sessionId), ne(events.type, STEP_EVENT))).orderBy(desc(events.id)).limit(limit);
}