PEP-209: страница «Приёмка», «Принять всё», объединение предложений, сводка в Telegram, Главная и задержки в Дашборде

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
peppa-bot 2026-11-18 16:50:03 +05:00
parent 9d1c4f0de2
commit b554f66d9c
22 changed files with 744 additions and 33 deletions

View File

@ -2,7 +2,7 @@
// alerts) to the paired chat and turns button presses / replies into answers delivered
// back into the agent session. Telegram is an adapter over the DB, not a remote shell:
// it can only answer a specific pending question or resume/stop the session it is about.
import { duringPause, heldForDigest, isProjectPaused, LOCALIZED_PARAM, localizeMessage, messageDetails, questionIsFreeText, reportPlatformError, telegramChatLocale } from "@peppa/core";
import { acceptDigestHold, duringPause, heldForDigest, isProjectPaused, LOCALIZED_PARAM, localizeMessage, messageDetails, questionIsFreeText, reportPlatformError, telegramChatLocale } from "@peppa/core";
import { asIs, localizeRoleMessage, m as tr, stripAsIs } from "@peppa/shared/i18n";
import {
accountUsageForUser,
@ -347,6 +347,8 @@ export function createBot(o: BotOptions) {
const url = ctx.taskKey ? `/t/${ctx.taskKey}` : `/p/${await projectKey(q.projectId)}`;
// PEP-198: a finished story nobody waits for comes in the evening digest, not one by one.
if (await heldForDigest(db, q, ctx.taskStatus ?? null)) continue;
// PEP-209: more than two ready within an hour — one summary with «Приёмка» instead (acceptDigestTick).
if ((await acceptDigestHold(db, q)) !== "send") continue;
for (const u of audience) {
// PEP-154: the terminal command is for the «Инженер» view only.
const r = renderQuestion(q, { ...ctx, engineer: (await getUiMode(db, u.id)) === "engineer" });

View File

@ -64,10 +64,10 @@ import {
setUiMode,
} from "@peppa/core";
import { attachmentLabel, fixFeedback, linkAttachments, linkFeedback, parseAttachmentIds, rejectFeedback, restoreProject } from "@peppa/core";
import { deleteProject, decideProposals } from "@peppa/runner";
import { deleteProject, decideProposals, mergeProposals } from "@peppa/runner";
import { bugsinkFromEnv } from "@peppa/bugsink";
import { loadEnv } from "@peppa/shared";
import { pauseProject, resumeProject, acceptStory, autoPublish, fixStory, confirmTaskDecision, changeTaskDecision, undoSplit, budgetChanged, resolveTaskById, deployProd, bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, grantRepoAccess, moveTask, provisionProjectOnce, projectNamespace, setProjectVisibility, shareProject, unshareProject, type BoardColumn, resumeSession, sendToSession, syncSessionAttachments, startSession, stopSession, type Provider, startFreeRunner, renameRunner, promoteRunner, queueTaskOnRunner, managesProject, saveAgentsMd, cancelOwnLogin, finishOwnClaudeLogin, connectOwnSubscription, removeOwnSubscription, type OwnSubscriptionKind, chooseSharedSubscription, requestSubscription } from "@peppa/runner";
import { pauseProject, resumeProject, acceptAll, acceptStory, autoPublish, fixStory, confirmTaskDecision, changeTaskDecision, undoSplit, budgetChanged, resolveTaskById, deployProd, bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, grantRepoAccess, moveTask, provisionProjectOnce, projectNamespace, setProjectVisibility, shareProject, unshareProject, type BoardColumn, resumeSession, sendToSession, syncSessionAttachments, startSession, stopSession, type Provider, startFreeRunner, renameRunner, promoteRunner, queueTaskOnRunner, managesProject, saveAgentsMd, cancelOwnLogin, finishOwnClaudeLogin, connectOwnSubscription, removeOwnSubscription, type OwnSubscriptionKind, chooseSharedSubscription, requestSubscription } from "@peppa/runner";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { asWebActor, requireUser, words } from "@/lib/auth";
@ -203,6 +203,28 @@ export async function acceptStoryAction(f: FormData) {
});
}
/**
* PEP-209: «Принять» / «Принять всё» on the acceptance page — one by one, a failure of one doesn't
* stop the others; the page shows the result («Принято 6, на доработке 1…»).
*/
export async function acceptAllAction(f: FormData) {
const user = asWebActor(await requireUser());
const key = str(f, "project");
const base = `/p/${encodeURIComponent(key)}/accept`;
await attempt(f, async () => {
const refs = [];
for (const k of f.getAll("taskKey").map(String)) {
const ref = await resolveTask(db, k).catch(() => null);
if (!ref || ref.project.key !== key) continue;
await projectForUser(db, user.id, ref.project.id);
if (ref.task.status === "review") refs.push(ref);
}
if (!refs.length) throw new PeppaError(m("Принимать нечего: задачи уже приняты или вернулись в работу"));
const r = await acceptAll(db, refs, "web");
return `${base}?ok=${r.accepted.length}&pending=${r.pending.length}&failed=${r.failed.length}`;
});
}
/** «Поправить» on the story page in «Продакт» mode (PEP-120): the remark goes to the agent, the story — back to work. */
export async function fixStoryAction(f: FormData) {
const user = asWebActor(await requireUser());
@ -503,6 +525,11 @@ export async function proposalAction(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
const choice = str(f, "choice");
// PEP-209: «Объединить в одну» — the ticked proposals become one story.
if (choice === "merge") {
await mergeProposals(db, user, f.getAll("pick").map(Number).filter((n) => Number.isInteger(n) && n > 0));
return;
}
if (choice !== "do" && choice !== "no" && choice !== "important" && choice !== "none") throw new PeppaError(m("Эта кнопка уже не работает."));
const ids = str(f, "ids").split(",").map(Number).filter((n) => Number.isInteger(n) && n > 0);
await decideProposals(db, user, ids, choice);

View File

@ -0,0 +1,33 @@
"use server";
// PEP-209: the superadmin's buttons on a delay card («Дашборд → Задержки»).
import { DELAY_REASON_NAMES, PeppaError, requireSuperadmin, type DelayAction, type DelayReason } from "@peppa/core";
import { delayAction } from "@peppa/runner";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { asWebActor, requireUser } from "@/lib/auth";
import { db } from "@/lib/db";
import { getT } from "@/lib/i18n";
const BASE = "/dashboard/delays";
const str = (f: FormData, k: string) => String(f.get(k) ?? "").trim();
export async function delayActionForm(f: FormData) {
const user = asWebActor(await requireUser());
const params = new URLSearchParams();
try {
await requireSuperadmin(db, user);
const reason = str(f, "reason") as DelayReason;
const action = str(f, "action") as DelayAction;
const projectId = Number(str(f, "project"));
const taskId = str(f, "task") ? Number(str(f, "task")) : null;
if (!(reason in DELAY_REASON_NAMES) || !["restart", "review", "close"].includes(action) || !Number.isInteger(projectId)) throw new PeppaError("?");
const t = await getT();
params.set("ok", t.text(await delayAction(db, { projectId, taskId }, reason, action)).slice(0, 300));
} catch (e) {
const t = await getT();
params.set("error", (e instanceof PeppaError ? t.text(e.message) : t("Ошибка: {message}", { message: (e as Error).message })).slice(0, 300));
}
revalidatePath("/", "layout");
redirect(`${BASE}?${params}`);
}

View File

@ -0,0 +1,49 @@
import Link from "next/link";
import { notFound } from "next/navigation";
import { Hourglass } from "lucide-react";
import { isSuperadmin, platformDelayOverview } from "@peppa/core";
import { Empty, Flash, Notice, PageHeader, Section } from "@/components/common";
import { LiveRefresh } from "@/components/LiveRefresh";
import { PlatformDelays } from "@/components/PlatformDelays";
import { Workspace } from "@/components/Workspace";
import { requireUser } from "@/lib/auth";
import { db } from "@/lib/db";
import { getT } from "@/lib/i18n";
export async function generateMetadata() {
const t = await getT();
return { title: t("Задержки — Peppa FACTORY") };
}
/** PEP-209: every delay on the platform's side with the superadmin's buttons; «нужен администратор» first. */
export default async function Delays({ searchParams }: { searchParams: Promise<{ error?: string; ok?: string }> }) {
const user = await requireUser();
if (!(await isSuperadmin(db, user))) notFound();
const { error, ok } = await searchParams;
const t = await getT();
const all = await platformDelayOverview(db);
const admin = all.filter((d) => d.exhausted);
const trying = all.filter((d) => !d.exhausted);
return (
<Workspace>
<LiveRefresh scope="home" />
<Flash error={error} />
{ok && <Notice>{t.text(ok)}</Notice>}
<PageHeader title={<><Hourglass className="mr-1 inline size-5 text-primary" />{t("Задержки на стороне Peppa FACTORY")}</>}>
{t("Что сейчас задерживается у пользователей и почему. Владельцы видят только строку ожидания на задаче.")}{" "}
<Link href="/dashboard" className="text-primary">{t("← Дашборд")}</Link>
</PageHeader>
{all.length === 0 && <Empty>{t("Задержек нет.")}</Empty>}
{admin.length > 0 && (
<Section title={t("Нужен администратор")} count={admin.length} id="admin">
<PlatformDelays delays={admin} actions />
</Section>
)}
{trying.length > 0 && (
<Section title={t("Peppa FACTORY пробует сама")} count={trying.length} id="trying">
<PlatformDelays delays={trying} actions />
</Section>
)}
</Workspace>
);
}

View File

@ -1,7 +1,7 @@
import Link from "next/link";
import { notFound } from "next/navigation";
import { Gauge } from "lucide-react";
import { isSuperadmin, platformDashboard, type DashboardCounts } from "@peppa/core";
import { isSuperadmin, platformDashboard, platformDelayCounts, type DashboardCounts } from "@peppa/core";
import { ago, Empty, PageHeader, Section } from "@/components/common";
import { LiveRefresh } from "@/components/LiveRefresh";
import { Badge } from "@/components/ui/badge";
@ -54,6 +54,7 @@ export default async function Dashboard() {
const t = await getT();
const d = await platformDashboard(db);
const x = d.totals;
const delays = await platformDelayCounts(db);
return (
<Workspace>
<LiveRefresh scope="home" />
@ -70,6 +71,12 @@ export default async function Dashboard() {
<Stat label={t("Ждут ответа людей")} value={x.openQuestions} />
</div>
<p className="mb-4 text-sm" data-dashboard-delays>
<Link href="/dashboard/delays" className="text-primary">
{delays.total ? t("Задержки на платформе: {n}, требуют вас: {m}", { n: delays.total, m: delays.admin }) : t("Задержек на платформе нет")} →
</Link>
</p>
<Section title={t("Требует внимания")} count={d.attention.length} id="attention">
{d.attention.length === 0 ? (
<Empty>{t("Всё в порядке: ничего не зависло.")}</Empty>

View File

@ -0,0 +1,181 @@
import Link from "next/link";
import { notFound } from "next/navigation";
import { acceptAllSummary, acceptScreen, type AcceptItem } from "@peppa/core";
import { acceptAllAction, fixStoryAction } from "@/app/(app)/actions";
import { Empty, Flash, Key, Notice, PageHeader } from "@/components/common";
import { LiveRefresh } from "@/components/LiveRefresh";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/input";
import { Workspace } from "@/components/Workspace";
import { requireUser } from "@/lib/auth";
import { db } from "@/lib/db";
import { getT } from "@/lib/i18n";
import { projectForUserByKey } from "@/lib/queries";
export async function generateMetadata() {
const t = await getT();
return { title: t("Приёмка — Peppa FACTORY") };
}
const BIG = "min-h-11"; // PEP-209: buttons at least 44 px on a phone
/**
* PEP-209: acceptance on one screen — every story waiting for «Принять», grouped by product page,
* with «было» / «стало», «Принять», «Поправить» and «Принять всё» on top.
*/
export default async function AcceptPage({ params, searchParams }: { params: Promise<{ key: string }>; searchParams: Promise<{ error?: string; ok?: string; pending?: string; failed?: string }> }) {
const user = await requireUser();
const { key } = await params;
const sp = await searchParams;
const t = await getT();
const p = await projectForUserByKey(user.id, key).catch(() => null);
if (!p) notFound();
const screen = await acceptScreen(db, p);
const back = `/p/${p.key}/accept`;
const all = screen.groups.flatMap((g) => g.items);
const done = sp.ok != null ? { accepted: Number(sp.ok) || 0, pending: Number(sp.pending) || 0, failed: Number(sp.failed) || 0 } : null;
return (
<Workspace>
<LiveRefresh scope={`project:${p.id}`} />
<Flash error={sp.error} />
<PageHeader crumbs={<Link href={`/p/${p.key}`} className="text-muted-foreground hover:text-foreground">{p.name}</Link>} title={t("Приёмка")}>
{screen.total ? t("Работа, которая ждёт вашего решения: посмотрите и примите или напишите, что поправить.") : t("Принимать пока нечего: агенты пришлют задачи, когда работа будет готова.")}
</PageHeader>
{done && (
<Notice>
<span data-accept-result>{t.text(acceptAllSummary(done))}</span>
{screen.liveUrl && done.accepted + done.pending > 0 && (
<a href={screen.liveUrl} target="_blank" rel="noreferrer" className="text-primary">{t("Открыть продукт")} →</a>
)}
</Notice>
)}
{screen.total > 0 && (
<div className="mb-6 flex flex-wrap items-start gap-2" data-accept-top>
{screen.checkUrl && (
<a href={screen.checkUrl} target="_blank" rel="noreferrer" className={`inline-flex items-center rounded-md border bg-card px-4 text-sm font-medium hover:bg-accent ${BIG}`}>
{t("Открыть версию для проверки")}
</a>
)}
<details className="group w-full rounded-lg border bg-card sm:w-auto" data-accept-all>
<summary className={`flex cursor-pointer list-none items-center rounded-md bg-primary px-4 text-sm font-medium text-primary-foreground select-none [&::-webkit-details-marker]:hidden ${BIG}`}>
{t("Принять всё · {n}", { n: all.length })}
</summary>
<form action={acceptAllAction} className="flex flex-col gap-2 p-3">
<input type="hidden" name="project" value={p.key} />
<input type="hidden" name="back" value={back} />
<p className="m-0 text-sm">{t("Будут приняты по очереди:")}</p>
<ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm">
{all.map((it) => (
<li key={it.key}>
<input type="hidden" name="taskKey" value={it.key} />
<Key>{it.key}</Key> {it.title}
</li>
))}
</ul>
<p className="m-0 text-xs text-muted-foreground">{t("Если какая-то не примется, остальные всё равно примутся, а у неё будет написано почему.")}</p>
<Button variant="default" className={BIG} data-accept-all-confirm>
{t("Да, принять {n}", { n: all.length })}
</Button>
</form>
</details>
</div>
)}
{screen.total === 0 && !done && <Empty>{t("Задач на приёмке нет.")}</Empty>}
{screen.groups.map((g) => (
<section key={g.page || "-"} className="mb-8" data-accept-group={g.page || "-"}>
<h2 className="mb-3 text-base font-semibold">
{g.page ? t("Страница {page}", { page: g.page }) : t("Без снимков страниц")} <span className="text-muted-foreground">· {g.items.length}</span>
</h2>
<div className="flex flex-col gap-4">
{g.items.map((it) => <AcceptCard key={it.key} it={it} back={back} />)}
</div>
</section>
))}
</Workspace>
);
}
async function AcceptCard({ it, back }: { it: AcceptItem; back: string }) {
const t = await getT();
return (
<article className="rounded-lg border bg-card p-3 sm:p-4" data-accept-item={it.key}>
<div className="mb-1 flex flex-wrap items-center gap-2 text-sm">
<Link href={`/t/${it.key}`} className="hover:underline">
<Key>{it.key}</Key>
</Link>
<span className="font-medium">{it.title}</span>
</div>
<p className="m-0 mb-3 text-sm" data-accept-summary>{t.text(it.summary)}</p>
{it.failed && (
<p role="alert" className="m-0 mb-3 rounded-md border border-destructive/50 bg-destructive/10 px-3 py-2 text-sm" data-accept-failed>
{t("Не принялась: {reason}", { reason: t.text(it.failed) })}
</p>
)}
{it.pending && <p className="m-0 mb-3 text-sm text-muted-foreground">{t("Вы уже приняли — изменения обновляются, задача закроется сама.")}</p>}
{it.shots.length > 0 ? (
// Scrolls sideways on a phone: one page per screen, «было» above «стало».
<div className="-mx-3 mb-3 flex snap-x snap-mandatory gap-3 overflow-x-auto px-3 pb-2 sm:mx-0 sm:px-0" data-accept-shots>
{it.shots.map((s, i) => (
<figure key={i} className="m-0 w-[85%] shrink-0 snap-start sm:w-[calc(50%-0.375rem)]">
<figcaption className="mb-1 text-xs text-muted-foreground">{s.path}</figcaption>
<div className="grid grid-cols-1 gap-2">
<Shot src={s.before} label={t("Было")} empty={t("Снимка рабочей версии нет")} />
<Shot src={s.after} label={t("Стало")} empty={t("Снимка нет")} />
</div>
</figure>
))}
</div>
) : it.previewUrl ? (
<p className="m-0 mb-3 text-sm">
<a href={it.previewUrl} target="_blank" rel="noreferrer" className="inline-flex min-h-11 items-center text-primary">{t("Открыть в версии для проверки")} →</a>
</p>
) : (
<p className="m-0 mb-3 text-sm text-muted-foreground">{t("Снимков и версии для проверки нет — посмотрите описание задачи.")}</p>
)}
{it.shots.length > 0 && it.previewUrl && (
<p className="m-0 mb-3 text-sm">
<a href={it.previewUrl} target="_blank" rel="noreferrer" className="inline-flex min-h-11 items-center text-primary">{t("Открыть в версии для проверки")} →</a>
</p>
)}
{!it.pending && (
<div className="flex flex-col gap-2 sm:flex-row sm:items-start">
<form action={acceptAllAction}>
<input type="hidden" name="project" value={it.key.slice(0, it.key.lastIndexOf("-"))} />
<input type="hidden" name="back" value={back} />
<input type="hidden" name="taskKey" value={it.key} />
<Button variant="default" className={`${BIG} w-full sm:w-auto`} data-accept-one={it.key}>{t("Принять")}</Button>
</form>
<details className="w-full sm:w-auto">
<summary className={`flex cursor-pointer list-none items-center justify-center rounded-md border bg-card px-4 text-sm font-medium select-none hover:bg-accent [&::-webkit-details-marker]:hidden ${BIG}`}>{t("Поправить")}</summary>
<form action={fixStoryAction} className="mt-2 flex flex-col gap-2">
<input type="hidden" name="taskKey" value={it.key} />
<input type="hidden" name="back" value={back} />
<Textarea name="text" required rows={3} placeholder={t("Что поправить? Например: кнопка должна быть синей")} />
<Button className={BIG} data-accept-fix={it.key}>{t("Отправить агенту")}</Button>
</form>
</details>
</div>
)}
</article>
);
}
function Shot({ src, label, empty }: { src: string | null; label: string; empty: string }) {
return (
<div>
<div className="mb-0.5 text-xs font-medium">{label}</div>
{src ? (
<a href={src} target="_blank" rel="noreferrer">
{/* eslint-disable-next-line @next/next/no-img-element */}
<img src={src} alt={label} loading="lazy" className="block w-full rounded border" />
</a>
) : (
<div className="flex aspect-[16/10] items-center justify-center rounded border border-dashed text-xs text-muted-foreground">{empty}</div>
)}
</div>
);
}

View File

@ -1,3 +1,4 @@
import Link from "next/link";
import { Fragment } from "react";
import { ProductCard } from "@/components/ProductCard";
import { PublishPanel } from "@/components/PublishPanel";
@ -39,7 +40,7 @@ import { setProjectPoolAction } from "../../subscriptions/actions";
import { JournalFilters, JournalList, MetricsTab, ProjectBudgetPanel } from "@/components/Accounting";
import { saveProjectBudgetAction } from "../../actions";
// PEP-127: on its own line — the long @peppa/core import above is edited by every story.
import { delayedTaskIds, pendingQuestions, listPendingAccepts, PENDING_ACCEPT_LABEL, PLATFORM_DELAY_LABEL } from "@peppa/core";
import { delayedTaskIds, taskDelayLine, pendingQuestions, listPendingAccepts, PENDING_ACCEPT_LABEL, PLATFORM_DELAY_LABEL } from "@peppa/core";
import { trashDaysLeft } from "@peppa/core";
import { queuePositions, workLine } from "@peppa/core";
import { WorkLine } from "@/components/WorkLine";
@ -153,8 +154,16 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
const agentNames = await taskAgentNames(db, p.id);
const accepted = await listPendingAccepts(db);
// PEP-150: the delay line — not on a story whose question waits for the owner.
// PEP-209: the acceptance page — every story in review on one screen.
const toAccept = tasks.filter((x) => x.status === "review" && !x.archivedAt).length;
const delayed = await delayedTaskIds(db);
if (delayed.size) for (const q of await pendingQuestions(db, p.id)) if (q.taskId != null) delayed.delete(q.taskId);
// PEP-209: the card says when the next attempt comes (or that the administrator is told).
const delayLines = new Map<number, string>();
for (const id of delayed) {
const line = await taskDelayLine(db, id);
if (line) delayLines.set(id, line);
}
// PEP-182: stories waiting for a free agent, and «Делается · В очереди» above the board.
const [queued, work] = tab === "board" ? await Promise.all([queuePositions(db, p.id), workLine(db, [p.id])]) : [new Map<number, number>(), null];
const [intake, refining] = await Promise.all([getIntakeSettings(db, p.id), intakePendingTasks(db, p.id)]);
@ -174,7 +183,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
blocked: x.status === "backlog" ? blockedLabel(deps.get(x.id)) : null,
agent: agentNames.get(x.id) ?? null,
accepted: accepted.has(x.id) ? t.text(PENDING_ACCEPT_LABEL) : null,
delayed: delayed.has(x.id) && x.status !== "done" ? t.text(PLATFORM_DELAY_LABEL) : null,
delayed: delayed.has(x.id) && x.status !== "done" ? t.text(delayLines.get(x.id) ?? PLATFORM_DELAY_LABEL) : null,
queued: queued.get(x.id) ?? null,
proposed: x.proposed,
severity: (x.severity as Card["severity"]) ?? null,
@ -573,6 +582,11 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
<PageHeader
actions={
<>
{toAccept > 0 && (
<Link href={`/p/${p.key}/accept`} className="inline-flex h-9 items-center gap-1 rounded-md bg-primary px-4 text-sm font-medium text-primary-foreground hover:bg-primary/90" data-accept-link>
{t("Принять работу · {n}", { n: toAccept })}
</Link>
)}
<SettingsDialog title={t("Новая {task}", { task: w.task() })} trigger={<><Plus />{w.Task()}</>}>
{newTask}
</SettingsDialog>

View File

@ -1,7 +1,7 @@
import { redirect } from "next/navigation";
import { agentTaskSummary, claimWelcome, isSuperadmin, listUserProjects, onboardingChecklist, pendingFeedback, platformDelayOverview, progressOverview } from "@peppa/core";
import Link from "next/link";
import { agentTaskSummary, claimWelcome, isSuperadmin, listUserProjects, onboardingChecklist, pendingFeedback, platformDelayCounts, progressOverview, proposedCount, reviewCounts } from "@peppa/core";
import { AdminFeedbackCard } from "@/components/Feedback";
import { PlatformDelays } from "@/components/PlatformDelays";
import { AgentTaskSummary } from "@/components/AgentTaskSummary";
import { ProgressOverview } from "@/components/ProgressOverview";
import { OnboardingChecklist } from "@/components/Onboarding";
@ -25,34 +25,71 @@ export default async function Home({ searchParams }: { searchParams: Promise<{ e
const [items, ready, sessions, projects, onboarding, progress] = await Promise.all([inbox(user.id), acceptInbox(user.id), activeSessions(user.id), listUserProjects(db, user.id), onboardingChecklist(db, user), progressOverview(db, user.id)]);
// PEP-143: users' reports about Peppa FACTORY wait for the superadmin's decision here.
const reports = (await isSuperadmin(db, user)) ? await pendingFeedback(db) : [];
// PEP-150: delays on the platform's side are the superadmin's to watch, not the owners'.
const delays = (await isSuperadmin(db, user)) ? await platformDelayOverview(db) : [];
// PEP-150/209: delays on the platform's side are the superadmin's to watch — one line here, the list in the dashboard.
const delays = (await isSuperadmin(db, user)) ? await platformDelayCounts(db) : null;
// PEP-209: what waits for the user comes first — accept, answer, decide on «Предложено».
const toAccept = await reviewCounts(db, projects.map((p) => p.id));
const proposed = new Map<number, number>();
for (const p of projects) {
const n = await proposedCount(db, p.id);
if (n) proposed.set(p.id, n);
}
const acceptN = [...toAccept.values()].reduce((a, b) => a + b, 0);
const decideN = [...proposed.values()].reduce((a, b) => a + b, 0);
const waits = [acceptN ? t("принять {n}", { n: acceptN }) : null, items.length ? t("ответить {n}", { n: items.length }) : null, decideN ? t("решить {n}", { n: decideN }) : null].filter(Boolean).join(", ");
// PEP-197: people against factory-made tasks per project — the superadmin's view.
const agentTasks = (await isSuperadmin(db, user)) ? (await agentTaskSummary(db)).filter((r) => r.agents > 0).slice(0, 15) : [];
return (
<Workspace aside={<ActivityAside questions={false} />}>
<LiveRefresh scope="home" />
<Flash error={error} />
<PageHeader title={t("Главная")}>{items.length ? (w.engineer ? t("Агенты ждут вашего решения — ответьте здесь, в Telegram или через MCP.") : t("Агенты ждут вашего решения — ответьте здесь или в Telegram.")) : t("Всё идёт само: агентам от вас ничего не нужно.")}</PageHeader>
<PageHeader title={waits ? t("Вас ждут: {list}", { list: waits }) : t("Всё идёт само: от вас ничего не нужно")}>
{waits ? (w.engineer ? t("Ответьте здесь, в Telegram или через MCP.") : t("Ответьте здесь или в Telegram.")) : t("Агенты работают сами и напишут, когда понадобится ваше решение.")}
</PageHeader>
{onboarding.visible && <OnboardingChecklist data={onboarding} botUsername={user.telegramBotUsername} />}
{acceptN > 0 && (
<Section title={t("Принять работу")} count={acceptN}>
<div className="mb-3 flex flex-wrap gap-2" data-home-accept>
{projects.filter((p) => toAccept.get(p.id)).map((p) => (
<Link key={p.id} href={`/p/${p.key}/accept`} className="inline-flex min-h-11 items-center rounded-md bg-primary px-4 text-sm font-medium text-primary-foreground hover:bg-primary/90">
{projects.length > 1 ? `${p.name}: ` : ""}{t("Принять работу · {n}", { n: toAccept.get(p.id)! })}
</Link>
))}
</div>
{ready.map((q) => <QuestionCard key={q.id} q={q} taskKey={q.taskKey} taskStatus={q.taskStatus} back="/" />)}
</Section>
)}
<Section title={t("Вопросы агентов")} count={items.length}>
<PugBanner count={items.length} />
{items.map((q) => <QuestionCard key={q.id} q={q} taskKey={q.taskKey} taskStatus={q.taskStatus} back="/" />)}
</Section>
{ready.length > 0 && (
{acceptN === 0 && ready.length > 0 && (
<Section title={t("Ждут «Принять»")} count={ready.length}>
{ready.map((q) => <QuestionCard key={q.id} q={q} taskKey={q.taskKey} taskStatus={q.taskStatus} back="/" />)}
</Section>
)}
{decideN > 0 && (
<Section title={t("Предложено: решите, делать ли")} count={decideN}>
<ul className="m-0 flex list-none flex-col gap-1.5 p-0" data-home-proposed>
{projects.filter((p) => proposed.get(p.id)).map((p) => (
<li key={p.id}>
<Link href={`/p/${p.key}#proposed`} className="text-primary">{t("{project}: предложено {n}", { project: p.name, n: proposed.get(p.id)! })} →</Link>
</li>
))}
</ul>
</Section>
)}
{reports.length > 0 && (
<Section title={t("Обращения пользователей")} count={reports.length} actions={<MoreLink href="/feedback">{t("все обращения")}</MoreLink>}>
{reports.slice(0, 5).map((f) => <AdminFeedbackCard key={f.id} f={f} back="/" />)}
</Section>
)}
{delays.length > 0 && (
<Section title={t("Задержки на стороне Peppa FACTORY")} count={delays.length}>
<PlatformDelays delays={delays} />
</Section>
{delays && delays.total > 0 && (
<p className="mb-6 text-sm" data-home-delays>
<Link href="/dashboard/delays" className="text-primary">
{t("На платформе задержек: {n}, требуют вас: {m}", { n: delays.total, m: delays.admin })} →
</Link>
</p>
)}
{agentTasks.length > 0 && (
<Section title={t("Задачи, которые фабрика завела сама")} count={agentTasks.length}>

View File

@ -30,6 +30,7 @@ import {
PENDING_ACCEPT_LABEL,
PLATFORM_DELAY_LABEL,
taskDelayed,
taskDelayLine,
projectPool,
PROVIDER_NAMES,
readChange,
@ -131,6 +132,8 @@ export default async function StoryPage({ params, searchParams }: { params: Prom
// PEP-150: a delay on the platform's side — one line instead of a message to the owner.
// Not while a question waits for the owner: «от вас ничего не нужно» would not be true.
const delayed = !task.archivedAt && task.status !== "done" && !questions.some((q) => !q.answeredAt) && (await taskDelayed(db, task.id));
// PEP-209: when the next attempt comes, or that the administrator is told — never the terminal's text.
const delayLine = delayed ? await taskDelayLine(db, task.id) : null;
const gate = tab === "merge" && task.prUrl ? await gateWithTimeout(ref) : null;
const openQuestions = questions.filter((q) => !q.answeredAt).length;
const counts: Partial<Record<StoryTab, number | string>> = {
@ -260,6 +263,7 @@ export default async function StoryPage({ params, searchParams }: { params: Prom
waitsFor: blockers.filter((b) => b.open).map((b) => b.title),
accepted: !!pendingAccept,
delayed,
delayLine,
// PEP-182: no agent yet because all are busy — the place in the queue.
queued: live ? null : ((await queuePositions(db, task.projectId)).get(task.id) ?? null),
});
@ -429,7 +433,7 @@ export default async function StoryPage({ params, searchParams }: { params: Prom
<>
<span className="font-mono text-primary">{ref.key}</span> {task.title} {engineer && <StatusBadge status={task.status} />}
{pendingAccept && <Badge variant="ok" className="ml-1.5 align-middle whitespace-normal">{t.text(PENDING_ACCEPT_LABEL)}</Badge>}
{engineer && delayed && <Badge variant="muted" className="ml-1.5 align-middle whitespace-normal">{t.text(PLATFORM_DELAY_LABEL)}</Badge>}
{engineer && delayed && <Badge variant="muted" className="ml-1.5 align-middle whitespace-normal">{t.text(delayLine ?? PLATFORM_DELAY_LABEL)}</Badge>}
{task.archivedAt && <Badge variant="muted" className="ml-1.5 align-middle">{t("в архиве")}</Badge>}
</>
}

View File

@ -287,7 +287,7 @@ function Proposed({ cards, back }: { cards: Card[]; back: string }) {
const ids = cards.map((c) => c.id).join(",");
const important = cards.filter((c) => c.severity !== "minor");
return (
<details data-proposed className="rounded-lg border border-dashed bg-muted/30 p-2">
<details id="proposed" data-proposed className="rounded-lg border border-dashed bg-muted/30 p-2">
<summary className="flex min-h-11 cursor-pointer items-center gap-2 px-1.5 font-mono text-[11px] font-semibold tracking-wider text-muted-foreground uppercase">
{t("Предложено")}
<span className="ml-auto tabular-nums">{cards.length}</span>
@ -312,6 +312,22 @@ function Proposed({ cards, back }: { cards: Card[]; back: string }) {
</article>
))}
</div>
{cards.length > 1 && (
// PEP-209: several small fixes of one page become one story — fewer stories to accept.
<form action={proposalAction} className="mt-2 flex flex-col gap-1.5 rounded-md border bg-card p-2.5 text-sm" data-proposed-merge>
<span className="text-xs text-muted-foreground">{t("Отметьте мелкие правки одной страницы — фабрика сделает их одной задачей:")}</span>
{cards.map((card) => (
<label key={card.key} className="flex min-h-11 items-center gap-2">
<input type="checkbox" name="pick" value={card.id} className="size-5" />
<span className="font-mono text-xs text-primary">{card.key}</span> {card.title}
</label>
))}
<input type="hidden" name="back" value={back} />
<Button size="sm" name="choice" value="merge" className="min-h-11 self-start">
{t("Объединить в одну")}
</Button>
</form>
)}
<form action={proposalAction} className="mt-2 flex flex-wrap gap-2">
<input type="hidden" name="ids" value={ids} />
<input type="hidden" name="back" value={back} />

View File

@ -1,30 +1,49 @@
import Link from "next/link";
import { DELAY_REASON_NAMES, type DelayView } from "@peppa/core";
import { delayActionForm } from "@/app/(app)/dashboard/actions";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Key } from "@/components/common";
import { getT } from "@/lib/i18n";
/**
* PEP-150: what is held up on the platform's side right now — the superadmin's list on the
* home page. Owners see one line on the story instead; a row leaves when its cause is gone.
* PEP-150/209: what is held up on the platform's side — the superadmin's list in «Дашборд →
* Задержки». Owners see one line on the story instead; a row leaves when its cause is gone.
* With `actions` every card has «Перезапустить», «Перевести на ревью» (story cards) and «Закрыть».
*/
export async function PlatformDelays({ delays }: { delays: DelayView[] }) {
export async function PlatformDelays({ delays, actions = false }: { delays: DelayView[]; actions?: boolean }) {
const t = await getT();
const hhmm = (ms: number) => new Date(ms).toLocaleString("ru-RU", { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit" });
const hhmm = (ms: number) => new Date(ms).toLocaleString("ru-RU", { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit", timeZone: process.env.PEPPA_TZ || undefined });
return (
<ul className="m-0 flex list-none flex-col gap-2 p-0">
<ul className="m-0 flex list-none flex-col gap-2 p-0" data-delays>
{delays.map((d) => (
<li key={`${d.key}:${d.reason}`} className="rounded-lg border bg-card px-3 py-2 text-sm">
<li key={`${d.key}:${d.reason}`} className="rounded-lg border bg-card px-3 py-2 text-sm" data-delay={d.reason}>
<div className="flex flex-wrap items-center gap-x-2 gap-y-1">
<Link href={d.url} className="hover:underline">
<Key>{d.key}</Key>
</Link>
<span className="font-medium">{t.text(DELAY_REASON_NAMES[d.reason])}</span>
{d.exhausted ? <Badge variant="danger">{t("нужна ваша помощь")}</Badge> : <Badge variant="muted">{t("Peppa FACTORY пробует сама")}</Badge>}
{d.exhausted ? <Badge variant="danger">{t("нужен администратор")}</Badge> : <Badge variant="muted">{t("Peppa FACTORY пробует сама")}</Badge>}
<span className="text-xs text-muted-foreground">{t("с {time} · попыток: {n}", { time: hhmm(d.since), n: d.attempts })}</span>
{!d.exhausted && d.retryAt != null && <span className="text-xs text-muted-foreground">{t("следующая попытка: {time}", { time: hhmm(d.retryAt) })}</span>}
</div>
{d.title && <div className="text-muted-foreground">{d.title}</div>}
<p className="m-0 mt-1 line-clamp-3 whitespace-pre-wrap break-words text-xs text-muted-foreground">{t.text(d.details)}</p>
{actions && (
<div className="mt-2 flex flex-wrap gap-2">
{(["restart", ...(d.taskId != null ? ["review"] : []), "close"] as const).map((a) => (
<form key={a} action={delayActionForm}>
<input type="hidden" name="project" value={d.projectId} />
{d.taskId != null && <input type="hidden" name="task" value={d.taskId} />}
<input type="hidden" name="reason" value={d.reason} />
<input type="hidden" name="action" value={a} />
<Button size="sm" variant={a === "close" ? "outline" : "secondary"} data-delay-action={a}>
{a === "restart" ? t("Перезапустить") : a === "review" ? t("Перевести на ревью") : t("Закрыть")}
</Button>
</form>
))}
</div>
)}
</li>
))}
</ul>

View File

@ -0,0 +1,98 @@
// PEP-209: fewer «готово» messages in Telegram. When more than two stories of a project become
// ready within an hour, their cards are not sent one by one: one summary «Готово к приёмке» with
// a button that opens the acceptance page comes instead (the cards stay on the site).
//
// The bot's decision on a «готово» card (`acceptDigestHold`) waits `PEPPA_ACCEPT_DIGEST_SETTLE_SEC`
// (300 s) after the card was made — so that with five ready at once the first two don't go alone —
// and is then final: it depends only on the cards made in [card − 1 h; card + pause], which no
// longer change. `acceptDigestTick` (watchdog, once a minute) sends the summary of held cards.
// `PEPPA_ACCEPT_DIGEST=off` turns both off.
import { questions, tasks, type Db } from "@peppa/db";
import { asIs, m as tr } from "@peppa/shared/i18n";
import { and, eq, gte, isNull, lte } from "drizzle-orm";
import { pausedProjectIds } from "./project-pause.ts";
import { deliverToUser, projectAudience } from "./notifications.ts";
import { listProjects } from "./projects.ts";
import { getSetting, setSetting } from "./settings.ts";
const WINDOW_MS = 3600_000;
/** More «готово» than this within an hour → one summary. */
export const ACCEPT_DIGEST_MAX_SINGLE = 2;
const settleMs = () => {
const n = Number(process.env.PEPPA_ACCEPT_DIGEST_SETTLE_SEC ?? 300);
return Number.isFinite(n) && n >= 0 ? n * 1000 : 300_000;
};
const off = () => process.env.PEPPA_ACCEPT_DIGEST === "off";
export type DigestHold = "send" | "wait" | "held";
/** The bot's question about one card: send it now, wait a little, or leave it to the summary. */
export async function acceptDigestHold(db: Db, q: { projectId: number; taskId: number | null; msgType?: string | null; createdAt: Date }, now = new Date()): Promise<DigestHold> {
if (off() || q.msgType !== "done" || q.taskId == null) return "send";
const settle = settleMs();
const at = q.createdAt.getTime();
if (now.getTime() < at + settle) return "wait";
const rows = await db
.select({ taskId: questions.taskId })
.from(questions)
.where(and(eq(questions.projectId, q.projectId), eq(questions.msgType, "done"), gte(questions.createdAt, new Date(at - WINDOW_MS)), lte(questions.createdAt, new Date(at + settle))));
return new Set(rows.map((r) => r.taskId)).size > ACCEPT_DIGEST_MAX_SINGLE ? "held" : "send";
}
interface DigestState {
/** Stories already in a summary. */
ids: number[];
at: number;
}
const stateKey = (projectId: number) => `accept.digest:${projectId}`;
export function acceptDigestText(projectName: string, n: number, url: string): string {
return [tr("✅ {project}: готово к приёмке — задач: {n}", { project: asIs(projectName), n }), tr("Откройте «Приёмка» — там всё на одном экране: посмотреть, принять или поправить."), url].join("\n");
}
/** One summary per project when cards are held; a new one only when new stories joined. */
export async function acceptDigestTick(db: Db, o: { now?: Date; log?: (m: string) => void } = {}): Promise<number> {
if (off()) return 0;
const now = o.now ?? new Date();
const paused = await pausedProjectIds(db);
let sent = 0;
for (const project of await listProjects(db)) {
if (paused.has(project.id)) continue;
const open = await db
.select({ q: questions, status: tasks.status })
.from(questions)
.innerJoin(tasks, eq(questions.taskId, tasks.id))
.where(and(eq(questions.projectId, project.id), eq(questions.msgType, "done"), isNull(questions.answeredAt), eq(tasks.status, "review"), isNull(tasks.archivedAt)));
if (!open.length) continue;
const held = new Set<number>();
let waiting = false;
for (const { q } of open) {
const h = await acceptDigestHold(db, q, now);
if (h === "wait") waiting = true;
if (h === "held") held.add(q.taskId!);
}
if (!held.size || waiting) continue;
const st = (await getSetting<DigestState>(db, stateKey(project.id))) ?? { ids: [], at: 0 };
if ([...held].every((id) => st.ids.includes(id))) continue;
const total = new Set(open.map((r) => r.q.taskId)).size;
const url = `${(process.env.PEPPA_WEB_URL ?? "").replace(/\/$/, "")}/p/${project.key}/accept`;
const text = acceptDigestText(project.name, total, url);
for (const u of await projectAudience(db, project.id)) {
await deliverToUser(db, u, {
event: "review",
projectId: project.id,
dedupeKey: `acc:${project.id}:${now.getTime()}:${u.telegramChatId}`,
pushKey: `acc:${project.id}:${now.getTime()}:u${u.id}`,
telegram: { params: { text, link_preview_options: { is_disabled: true }, reply_markup: { inline_keyboard: [[{ text: tr("Открыть «Приёмка»"), url }]] } } },
push: { title: tr("Готово к приёмке"), body: tr("{project}: задач: {n}", { project: asIs(project.name), n: total }), url: `/p/${project.key}/accept`, tag: `acc:${project.id}` },
now,
}).catch(() => null);
}
// A week-old list is forgotten: only stories still waiting stay counted.
await setSetting(db, stateKey(project.id), { ids: [...new Set([...st.ids.filter((id) => open.some((r) => r.q.taskId === id)), ...held])], at: now.getTime() } satisfies DigestState);
o.log?.(`accept digest ${project.key}: ${total} ready (${held.size} held)`);
sent++;
}
return sent;
}

View File

@ -0,0 +1,163 @@
// PEP-209: acceptance on one screen — every story of a project waiting for «Принять», grouped by
// the product page it changes, each with one plain sentence of what changed and the screenshots
// «было» (the working version, staging — else what everyone sees) and «стало» (the story's own
// version to check). No screenshot — a link to open the story's version to check.
import { releases, settings, tasks, type Db } from "@peppa/db";
import { formatTaskKey } from "@peppa/shared";
import { m as tr } from "@peppa/shared/i18n";
import { and, desc, eq, inArray, isNull, like } from "drizzle-orm";
import { getPendingAccept } from "./accept-pending.ts";
import { getTaskResult } from "./message-details.ts";
import { reviewPreview } from "./preview.ts";
import { getSetting, setSetting } from "./settings.ts";
import type { Project } from "./projects.ts";
import type { TaskRef } from "./tasks.ts";
export interface AcceptShot {
/** The product page, e.g. "/" or "/settings". */
path: string;
/** `/api/releases/<id>/shots/<n>`; null — no screenshot of this side. */
before: string | null;
after: string | null;
}
export interface AcceptItem {
taskId: number;
key: string;
title: string;
/** What changed, in one sentence: the agent's result, else the story's title. */
summary: string;
/** The page the story changes ("" — not known: no screenshots). */
page: string;
shots: AcceptShot[];
/** The story's own version to check (its preview), if it runs. */
previewUrl: string | null;
/** «Принять» was pressed already, Peppa carries it to the merge (PEP-127). */
pending: boolean;
/** Why the last «Принять всё» could not accept it (kept 30 min). */
failed: string | null;
}
export interface AcceptGroup {
page: string;
items: AcceptItem[];
}
export interface AcceptScreen {
groups: AcceptGroup[];
total: number;
/** The version to check of the whole product (staging), and the working one everyone sees. */
checkUrl: string | null;
liveUrl: string | null;
}
const shotUrl = (releaseId: number, n: number) => `/api/releases/${releaseId}/shots/${n}`;
/** The first sentence of a text, at most `max` characters. */
export function oneSentence(text: string, max = 220): string {
const flat = text.replace(/\s+/g, " ").trim();
const first = flat.match(/^.+?[.!?](?=\s|$)/)?.[0] ?? flat;
return first.length > max ? `${first.slice(0, max - 1).trimEnd()}…` : first;
}
async function latestHealthy(db: Db, projectId: number, env: "staging" | "prod") {
const [r] = await db
.select()
.from(releases)
.where(and(eq(releases.projectId, projectId), eq(releases.env, env), eq(releases.status, "healthy")))
.orderBy(desc(releases.id))
.limit(1);
return r ?? null;
}
/** Stories in review of the project, as the acceptance page shows them. */
export async function acceptScreen(db: Db, project: Project): Promise<AcceptScreen> {
const rows = await db
.select()
.from(tasks)
.where(and(eq(tasks.projectId, project.id), eq(tasks.status, "review"), isNull(tasks.archivedAt)))
.orderBy(tasks.position, tasks.number);
const staging = await latestHealthy(db, project.id, "staging");
const prod = await latestHealthy(db, project.id, "prod");
// «было»: the working version's screenshots by page (staging, else prod).
const before = new Map<string, string>();
for (const rel of [prod, staging]) for (const [n, s] of (rel?.screenshots ?? []).entries()) before.set(s.path, shotUrl(rel!.id, n));
const items: AcceptItem[] = [];
for (const task of rows) {
const ref: TaskRef = { project, task, key: formatTaskKey(project.key, task.number) };
const p = await reviewPreview(db, ref).catch(() => null);
const shots: AcceptShot[] = (p?.screenshots ?? []).map((s) => ({ path: s.path, before: before.get(s.path) ?? null, after: p?.releaseId != null ? shotUrl(p.releaseId, s.n) : null }));
const result = await getTaskResult(db, task.id);
items.push({
taskId: task.id,
key: ref.key,
title: task.title,
summary: oneSentence(result?.summary || task.title),
page: shots[0]?.path ?? "",
shots,
previewUrl: p?.previewUrl ?? null,
pending: !!(await getPendingAccept(db, task.id)),
failed: await acceptFailure(db, task.id),
});
}
// Pages in the order their first story comes; stories without a known page last.
const groups: AcceptGroup[] = [];
for (const it of items) {
const g = groups.find((x) => x.page === it.page);
if (g) g.items.push(it);
else groups.push({ page: it.page, items: [it] });
}
groups.sort((a, b) => (a.page === "" ? 1 : 0) - (b.page === "" ? 1 : 0));
return {
groups,
total: items.length,
checkUrl: staging?.host ? `https://${staging.host}` : null,
liveUrl: prod?.host ? `https://${prod.host}` : staging?.host ? `https://${staging.host}` : null,
};
}
/** Stories in review per project (the «Принять работу · N» buttons). Archived ones don't count. */
export async function reviewCounts(db: Db, projectIds: number[]): Promise<Map<number, number>> {
const out = new Map<number, number>();
if (!projectIds.length) return out;
for (const t of await db.select({ projectId: tasks.projectId }).from(tasks).where(and(inArray(tasks.projectId, projectIds), eq(tasks.status, "review"), isNull(tasks.archivedAt)))) {
out.set(t.projectId, (out.get(t.projectId) ?? 0) + 1);
}
return out;
}
// ── «Принять всё»: why a story stayed ────────────────────────────────────────────
const FAIL_PREFIX = "accept.fail:";
const FAIL_TTL_MS = 30 * 60_000;
export async function setAcceptFailure(db: Db, taskId: number, reason: string): Promise<void> {
await setSetting(db, `${FAIL_PREFIX}${taskId}`, { reason, at: Date.now() });
}
export async function acceptFailure(db: Db, taskId: number): Promise<string | null> {
const f = await getSetting<{ reason: string; at: number }>(db, `${FAIL_PREFIX}${taskId}`);
return f && Date.now() - f.at < FAIL_TTL_MS ? f.reason : null;
}
/** Old failure notes of stories no longer in review go. */
export async function pruneAcceptFailures(db: Db): Promise<void> {
for (const row of await db.select().from(settings).where(like(settings.key, `${FAIL_PREFIX}%`))) {
if (Date.now() - (row.value as { at: number }).at >= FAIL_TTL_MS) await db.delete(settings).where(eq(settings.key, row.key));
}
}
export interface AcceptAllResult {
accepted: string[];
/** Accepted, Peppa still carries it to the merge (conflict, checks running). */
pending: string[];
failed: Array<{ key: string; reason: string }>;
}
/** «Принято 6, на доработке 1. Рабочая версия обновится через несколько минут». */
export function acceptAllSummary(r: { accepted: number; pending: number; failed: number }): string {
const parts = [tr("Принято {n}", { n: r.accepted + r.pending })];
if (r.failed) parts.push(tr("на доработке {n}", { n: r.failed }));
const head = parts.join(", ");
return r.accepted + r.pending ? `${head}. ${tr("Рабочая версия обновится через несколько минут")}` : head;
}

View File

@ -99,3 +99,5 @@ export * from "./egress.ts";
export * from "./fallback-fetch.ts";
export * from "./observe.ts";
export * from "./observe-checks.ts";
export * from "./accept-screen.ts";
export * from "./accept-digest.ts";

View File

@ -22,6 +22,8 @@ export interface StoryProductInput {
waitsFor?: string[];
/** PEP-150: a delay on the platform's side holds the story up (`taskDelayed`). */
delayed?: boolean;
/** PEP-209: what the owner waits for — «Следующая попытка в 14:00» / «Нужен администратор…» (`taskDelayLine`). */
delayLine?: string | null;
/** PEP-182: place in the queue for a free agent. */
queued?: number | null;
}
@ -103,7 +105,7 @@ export function storyProductView(i: StoryProductInput): StoryProductView {
const stepText = p ? plainStep(p.current) : null;
if (asked) return { ...base, step, stepText, now: T.asking.now, need: T.answerBelow, next: T.afterAnswer };
// PEP-150: the platform is fixing something of its own — nothing for the owner to do.
if (i.delayed) return { ...base, step, stepText, ...T.delayed };
if (i.delayed) return { ...base, step, stepText, ...T.delayed, ...(i.delayLine ? { now: i.delayLine } : {}) };
if (!i.agentWorking && i.queued != null) return { ...base, step, stepText, now: T.queued.now(i.queued), next: T.queued.next };
if (!i.agentWorking) return { ...base, step, stepText, ...T.paused };
if (i.status === "proposing") return { ...base, step, stepText, now: T.proposing.now(agent), next: T.proposing.next };

View File

@ -282,6 +282,7 @@ export async function handleGiteaHook(db: Db, req: HookRequest): Promise<{ statu
const out = await recordScreenshots(db, project, {
sha: payload.sha,
prNumber: typeof payload.pr === "number" ? payload.pr : null,
env: payload.env === "staging" || payload.env === "prod" ? payload.env : "preview",
shots: (payload.shots as Array<{ path?: unknown; png?: unknown }>).map((s) => ({ path: String(s.path ?? "/"), png: String(s.png ?? "") })),
});
return { status: 200, body: { ok: true, ...out } };

View File

@ -324,6 +324,8 @@ const PNG_MAGIC = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
export interface ScreenshotReport {
sha: string;
prNumber: number | null;
/** PEP-209: the working version (staging) is shot too — «было» on the acceptance page. */
env?: "preview" | "staging" | "prod";
shots: Array<{ path: string; png: string }>;
}
@ -338,7 +340,7 @@ export async function recordScreenshots(db: Db, project: Project, r: ScreenshotR
const [rel] = await db
.select()
.from(releases)
.where(and(eq(releases.projectId, project.id), eq(releases.env, "preview"), eq(releases.sha, r.sha), r.prNumber ? eq(releases.prNumber, r.prNumber) : undefined))
.where(and(eq(releases.projectId, project.id), eq(releases.env, r.env ?? "preview"), eq(releases.sha, r.sha), r.prNumber && (r.env ?? "preview") === "preview" ? eq(releases.prNumber, r.prNumber) : undefined))
.orderBy(desc(releases.id))
.limit(1);
if (!rel) return { release: null, saved: 0 };

View File

@ -1,7 +1,7 @@
// PM-side moves on the task board and review acceptance (web and Telegram use these).
import { m } from "@peppa/shared/i18n";
import { releaseIntake } from "./intake.ts";
import { addStoryComment, checksQueueStanding, approveProposal, answerQuestion, assertProjectActive, STORY_PRODUCT_TEXT, giteaForBot, GATE_UNKNOWN_REASON, clearPendingAccept, PENDING_ACCEPT_ANSWER, setPendingAccept, dropQueuedTask, clearCapacityWait, isWaitingForCapacity, getQuestion, listSessions, PeppaError, pendingQuestions, prGate, queuedItems, reorderTask, resolveTask, setTaskArchived, updateTask, type Question, type ReorderTo, type TaskRef } from "@peppa/core";
import { setAcceptFailure, type AcceptAllResult, addStoryComment, checksQueueStanding, approveProposal, answerQuestion, assertProjectActive, STORY_PRODUCT_TEXT, giteaForBot, GATE_UNKNOWN_REASON, clearPendingAccept, PENDING_ACCEPT_ANSWER, setPendingAccept, dropQueuedTask, clearCapacityWait, isWaitingForCapacity, getQuestion, listSessions, PeppaError, pendingQuestions, prGate, queuedItems, reorderTask, resolveTask, setTaskArchived, updateTask, type Question, type ReorderTo, type TaskRef } from "@peppa/core";
import { tasks, projects, type Db } from "@peppa/db";
import { formatTaskKey } from "@peppa/shared";
import { eq } from "drizzle-orm";
@ -251,3 +251,22 @@ export async function isReviewQuestion(db: Db, q: Question): Promise<boolean> {
const [t] = await db.select({ status: tasks.status }).from(tasks).where(eq(tasks.id, q.taskId));
return t?.status === "review";
}
/**
* PEP-209: «Принять всё» on the acceptance page — the stories are accepted one by one; one that
* can't be (red checks, Gitea down) stays in review with its reason and the others go on.
*/
export async function acceptAll(db: Db, refs: TaskRef[], via: NonNullable<Question["answeredVia"]> = "web"): Promise<AcceptAllResult> {
const out: AcceptAllResult = { accepted: [], pending: [], failed: [] };
for (const ref of refs) {
try {
const r = await acceptStory(db, ref, via);
(r.pending ? out.pending : out.accepted).push(ref.key);
} catch (e) {
const reason = e instanceof PeppaError ? e.message : m("не удалось принять, попробуйте ещё раз позже");
await setAcceptFailure(db, ref.task.id, reason).catch(() => {});
out.failed.push({ key: ref.key, reason });
}
}
return out;
}

View File

@ -1,8 +1,10 @@
// PEP-197: the owner decides on stories the factory suggests: «Делать» / «Не надо», and for the
// whole list «Делать важные» / «Отклонить всё». The same for the web (chat, board) and Telegram.
import { approveProposal, PeppaError, projectForUser, rejectProposal, resolveProposals, type User } from "@peppa/core";
import { approveProposal, logEvent, notify, PeppaError, projectForUser, rejectProposal, resolveProposals, type User } from "@peppa/core";
import { tasks, type Db } from "@peppa/db";
import { inArray } from "drizzle-orm";
import { formatTaskKey } from "@peppa/shared";
import { and, eq, inArray } from "drizzle-orm";
import { projects } from "@peppa/db";
import { m } from "@peppa/shared/i18n";
export type ProposalChoice = "do" | "no" | "important" | "none";
@ -19,3 +21,30 @@ export async function decideProposals(db: Db, user: Pick<User, "id" | "login">,
else await resolveProposals(db, open, choice, user.login);
return open.length;
}
/**
* PEP-209: «Объединить в одну» — several small proposals (usually fixes of one page) become one
* story: the first in board order keeps its title, gets the others' points in its description and
* goes to the backlog; the others are archived with «Объединена в KEY». Only on the owner's button.
*/
export async function mergeProposals(db: Db, user: Pick<User, "id" | "login">, taskIds: number[]): Promise<{ key: string; merged: number }> {
const rows = (await db.select().from(tasks).where(inArray(tasks.id, taskIds))).filter((t) => t.proposed && !t.archivedAt);
if (rows.length < 2) throw new PeppaError(m("Отметьте хотя бы две задачи из «Предложено»."));
if (new Set(rows.map((r) => r.projectId)).size > 1) throw new PeppaError(m("Объединять можно задачи одного проекта."));
await projectForUser(db, user.id, rows[0]!.projectId);
const [project] = await db.select({ key: projects.key }).from(projects).where(eq(projects.id, rows[0]!.projectId));
rows.sort((a, b) => a.position - b.position || a.number - b.number);
const [main, ...rest] = rows as [typeof rows[0], ...typeof rows];
const keyOf = (t: { number: number }) => formatTaskKey(project!.key, t.number);
const points = rest.map((t) => `- ${t.title}${t.description?.trim() ? `\n ${t.description.trim().replace(/\n/g, "\n ")}` : ""}`).join("\n");
const description = `${(main.description ?? "").trim()}\n\n${m("Объединено с задачами {keys}:", { keys: rest.map(keyOf).join(", ") })}\n${points}`.trim();
await db.update(tasks).set({ description, updatedAt: new Date() }).where(eq(tasks.id, main.id));
await approveProposal(db, main.id, user.login);
for (const t of rest) {
await db.update(tasks).set({ proposed: false, archivedAt: new Date() }).where(and(eq(tasks.id, t.id), eq(tasks.proposed, true)));
await logEvent(db, { projectId: t.projectId, taskId: t.id, type: "proposal_merged", payload: { into: keyOf(main), by: user.login } });
await notify(db, { type: "task_updated", taskId: t.id });
}
await logEvent(db, { projectId: main.projectId, taskId: main.id, type: "proposals_merged", payload: { from: rest.map(keyOf), by: user.login } });
return { key: keyOf(main), merged: rest.length };
}

View File

@ -39,7 +39,7 @@ import { actRunnerTick } from "./act-runner.ts";
import { reviewWantedTick } from "./review-wanted.ts";
import { killRunner, resumeSession, stopSession } from "./sessions.ts";
import { hostTick } from "./hosts.ts";
import { getProjectPause, injectionDigestTick, getSubscription, isUsable, pausedProjectIds, reportPlatformError, setProjectPause } from "@peppa/core";
import { acceptDigestTick, pruneAcceptFailures, getProjectPause, injectionDigestTick, getSubscription, isUsable, pausedProjectIds, reportPlatformError, setProjectPause } from "@peppa/core";
import { subscriptionRequestTick } from "./subscription-request.ts";
import { earlyRotationEnabled, planRotation, rotationEnabled, tryRotate, usageWarning } from "./rotation.ts";
import { monitorTick } from "./monitor.ts";
@ -372,6 +372,9 @@ export async function runWatchdog(db: Db, opts: WatchdogOptions, signal?: AbortS
// PEP-198: the analyst's evening digest of finished stories nobody waited for; stuck stories.
await readyDigestTick(db, { log }).catch(failed(db, log, "ready digest failed"));
await stuckTaskTick(db, { log }).catch(failed(db, log, "stuck tasks failed"));
// PEP-209: one «Готово к приёмке» summary instead of many «готово» messages in Telegram.
await acceptDigestTick(db, { log }).catch(failed(db, log, "accept digest failed"));
await pruneAcceptFailures(db).catch(() => {});
// PEP-189: no container takes the platform's port or domain; the public address answers Peppa.
await domainGuardTick(db, { log }).catch(failed(db, log, "domain guard failed"));
// PEP-205: the checks executor is alive and takes jobs; otherwise it is restarted.

View File

@ -51,6 +51,8 @@ Object.assign(process.env, {
PEPPA_NIGHT_QUIET: "off",
// PEP-209: a bin started from a worktree reads the main checkout's .env — never in a test.
PEPPA_ENV_FALLBACK: "off",
// PEP-209: «готово» cards go one by one in other suites; accept-screen.test.ts turns the summary on.
PEPPA_ACCEPT_DIGEST: "off",
});
mkdirSync(process.env.PEPPA_HOME!, { recursive: true });

View File

@ -138,7 +138,7 @@ screenshots() {
echo "peppa: скриншот $p снят"
done
[[ $(jq length "$file") -gt 0 ]] || return 0
body=$(jq -c --arg repo "${GITHUB_REPOSITORY:-}" --arg sha "$sha" --arg pr "$pr" '{repository:$repo, sha:$sha, pr:($pr|tonumber? // null), shots:.}' "$file")
body=$(jq -c --arg repo "${GITHUB_REPOSITORY:-}" --arg sha "$sha" --arg pr "$pr" --arg env "$env_name" '{repository:$repo, sha:$sha, pr:($pr|tonumber? // null), env:$env, shots:.}' "$file")
sig=$(printf '%s' "$body" | openssl dgst -sha256 -hmac "$PEPPA_CI_SECRET" | awk '{print $NF}')
printf '%s' "$body" | curl -fsS -o /dev/null -m 60 -X POST "$peppa_url/api/hooks/gitea" -H "Content-Type: application/json" \
-H "X-Peppa-Event: screenshots" -H "X-Gitea-Signature: $sig" --data-binary @- || echo "peppa: скриншоты не отправлены"
@ -162,7 +162,8 @@ fi
dc "$image" up -d --remove-orphans || { report failed "docker compose up не удался"; exit 1; }
if healthy; then
report healthy
[[ $env_name == preview ]] && screenshots
# PEP-209: staging too — «было» рядом со «стало» на странице «Приёмка».
[[ $env_name == preview || $env_name == staging ]] && screenshots
docker image prune -af --filter "label=peppa.project=$slug" --filter "until=336h" >/dev/null 2>&1 || true
exit 0
fi