Merge main into task/pep-98: PEP-111/114 texts through the dictionary

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Асель 2026-11-15 16:32:40 +05:00
commit 8ff54d6363
23 changed files with 420 additions and 23 deletions

View File

@ -7,6 +7,8 @@ import { Sidebar } from "@/components/Sidebar";
import { AttentionBadge } from "@/components/AttentionBadge";
import { CommandPalette } from "@/components/CommandPalette";
import { UsageStrip } from "@/components/Accounting";
import { VersionWatch } from "@/components/VersionWatch";
import { bootId } from "@/lib/boot";
export const dynamic = "force-dynamic";
@ -23,6 +25,7 @@ export default async function AppLayout({ children }: { children: ReactNode }) {
<AttentionBadge count={counts.questions + counts.waitingRunners} sound={sound} />
<Sidebar login={user.login} avatarUrl={user.avatarUrl} counts={counts} superadmin={superadmin} />
<div className="flex min-w-0 flex-col pb-16 md:pb-0">
<VersionWatch boot={bootId()} />
<UsageStrip accounts={accounts} admin={superadmin} />
{children}
</div>

View File

@ -1,8 +1,9 @@
import { Fragment } from "react";
import { ProductCard } from "@/components/ProductCard";
import { notFound } from "next/navigation";
import { ExternalLink, Plus, Rocket, SquareTerminal } from "lucide-react";
import { columnOf, currentReleases, describeRepo, isPlatform, listReleases, bugsinkWebhookBase, openPulls, platformReleaseCandidate, platformReleaseOffers, ownPendingLogins, readAgentsMd, repoOverview, type Release } from "@peppa/runner";
import { discussionUnread, ensureProjectChat, listHosts, DEFAULT_RUNNER_SETTINGS, DEFAULT_AGENT_SETTINGS, getProjectAgentSettings, getSystemAgentSettings, getProjectRunnerSettings, getSystemRunnerSettings, blockedLabel, blockersMap, epicProgress, progressLabel, taskProgress, getProjectBudget, listJournal, listProjectSecrets, projectMetrics, type ActorChannel, type ActorKind, getAutonomy, getIncidentSettings, getReviewSettings, isSuperadmin, listEpics, listErrorSources, listIncidents, listMembers, listPools, listSpecs, taskAgentNames, getIntakeSettings, intakePendingTasks, projectAgentWarning, memoryStats, readMemory, projectPool, sharedPool, ownPool, poolOverview, repoAudience, repoVisibilityLabel } from "@peppa/core";
import { userProjectIds, projectProduct, discussionUnread, ensureProjectChat, listHosts, DEFAULT_RUNNER_SETTINGS, DEFAULT_AGENT_SETTINGS, getProjectAgentSettings, getSystemAgentSettings, getProjectRunnerSettings, getSystemRunnerSettings, blockedLabel, blockersMap, epicProgress, progressLabel, taskProgress, getProjectBudget, listJournal, listProjectSecrets, projectMetrics, type ActorChannel, type ActorKind, getAutonomy, getIncidentSettings, getReviewSettings, isSuperadmin, listEpics, listErrorSources, listIncidents, listMembers, listPools, listSpecs, taskAgentNames, getIntakeSettings, intakePendingTasks, projectAgentWarning, memoryStats, readMemory, projectPool, sharedPool, ownPool, poolOverview, repoAudience, repoVisibilityLabel } from "@peppa/core";
import { LiveRefresh } from "@/components/LiveRefresh";
import { PanelSection } from "@/components/ActivityAside";
import { Board, type Card } from "@/components/Board";
@ -148,6 +149,9 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
const [code, pulls] = await Promise.all([tab === "code" ? repoOverview(db, p) : null, tab === "pulls" ? openPulls(db, p) : null]);
const specs = tab === "specs" ? listSpecs(p) : [];
const agentsMd = tab === "agents" ? await readAgentsMd(db, p) : null;
const product = await projectProduct(db, p.id);
// The chat belongs to the project's people; a superadmin looking at someone else's project has none.
const canChat = (await userProjectIds(db, user.id)).includes(p.id);
const discussionNew = (await discussionUnread(db, user.id)).get((await ensureProjectChat(db, p.id)).id) ?? 0;
const memory = tab === "specs" ? readMemory(p.workspacePath) : "";
// PEP-47 metrics, PEP-48 journal, PEP-43 default budget.
@ -463,6 +467,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
</p>
)}
{tab === "board" && <ProductCard product={product} projectKey={p.key} chat={canChat} />}
<nav aria-label={t("Разделы проекта")} className="-mt-2 mb-4 flex gap-1 overflow-x-auto border-b">
{TABS.map((x) => (
<Fragment key={x.id}>
@ -478,7 +483,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
{!!tabCount[x.id] && <span className="rounded-full bg-muted px-1.5 font-mono text-[11px] tabular-nums">{tabCount[x.id]}</span>}
</a>
{/* PEP-106: the people's chat of the project lives in «Чаты»; the link sits right after the board. */}
{x.id === "board" && (
{x.id === "board" && canChat && (
<a href={`/chats/${p.key}`} className="-mb-px flex items-center gap-1.5 border-b-2 border-transparent px-3 py-2 text-sm whitespace-nowrap text-muted-foreground hover:text-foreground hover:no-underline">
{t("Чат с аналитиком")}
{discussionNew > 0 && <span className="rounded-full bg-info px-1.5 font-mono text-[11px] text-background tabular-nums">{discussionNew}</span>}

View File

@ -1,4 +1,5 @@
import { healthReport } from "@peppa/core";
import { bootId } from "@/lib/boot";
import { db } from "@/lib/db";
export const dynamic = "force-dynamic";
@ -9,5 +10,6 @@ export async function GET() {
version: process.env.NEXT_PUBLIC_PEPPA_VERSION,
commit: process.env.NEXT_PUBLIC_PEPPA_COMMIT || null,
});
return Response.json(r, { status: r.ok ? 200 : 503, headers: { "Cache-Control": "no-store" } });
// PEP-114: `boot` changes when the web process restarts — open pages compare it with their own.
return Response.json({ ...r, boot: bootId() }, { status: r.ok ? 200 : 503, headers: { "Cache-Control": "no-store" } });
}

View File

@ -0,0 +1,77 @@
import Link from "next/link";
import { ExternalLink, Rocket } from "lucide-react";
import type { ProjectProduct } from "@peppa/core";
import { ago } from "@/components/common";
import { Button } from "@/components/ui/button";
import { getT } from "@/lib/i18n";
const host = (url: string) => url.replace(/^https?:\/\//, "");
/**
* PEP-111: «Ваш продукт» on the project page — where the result is and what to do next, for a
* product manager who asks «где это работает?». Nothing is shown before the first accepted story.
*/
export async function ProductCard({ product, projectKey, chat = true }: { product: ProjectProduct; projectKey: string; chat?: boolean }) {
const { live, check, doneStories } = product;
if (!live && !check && doneStories === 0) return null;
const t = await getT();
const next = chat && (
<p className="m-0 text-sm text-muted-foreground">
{t("Что дальше: опишите следующую задачу")} <Link href={`/chats/${projectKey}`}>{t("аналитику в чате")}</Link> — {t("он поможет сформулировать стори, агенты сделают.")}
</p>
);
return (
<section aria-label={t("Ваш продукт")} className="mb-5 flex flex-col gap-3 rounded-xl border border-ok/40 bg-ok/5 p-4">
{live ? (
<div className="flex flex-wrap items-center gap-x-4 gap-y-2">
<div className="flex min-w-0 flex-1 flex-col gap-0.5">
<span className="text-[15px] font-semibold">{t("Ваш продукт работает")}</span>
<span className="text-sm text-muted-foreground">
{t("Открыт для всех по адресу")} <span className="font-mono text-foreground">{host(live.url)}</span> · {t("обновлён {when}", { when: ago(live.at, t) })}
{live.stories.length > 0 && <> · {t("вошли стори {keys}", { keys: live.stories.slice(0, 6).join(", ") })}</>}
</span>
</div>
<Button asChild variant="default">
<a href={live.url} target="_blank" rel="noreferrer">
<ExternalLink /> {t("Открыть продукт")}
</a>
</Button>
</div>
) : check ? (
<div className="flex flex-wrap items-center gap-x-4 gap-y-2">
<div className="flex min-w-0 flex-1 flex-col gap-0.5">
<span className="text-[15px] font-semibold">{t("Версия для проверки готова")}</span>
<span className="text-sm text-muted-foreground">
{t("Пока её видите только вы:")} <span className="font-mono text-foreground">{host(check.url)}</span> · {t("обновлена {when}.", { when: ago(check.at, t) })} {t("Посмотрите — и покажите всем кнопкой «Выкатить» в")}{" "}
<Link href={`/p/${projectKey}?tab=releases`}>{t("Релизах")}</Link>.
</span>
</div>
<Button asChild variant="default">
<a href={check.url} target="_blank" rel="noreferrer">
<ExternalLink /> {t("Посмотреть")}
</a>
</Button>
</div>
) : (
<div className="flex flex-col gap-0.5">
<span className="text-[15px] font-semibold">{t("Готово стори: {n}", { n: doneStories })}</span>
<span className="text-sm text-muted-foreground">
{t("Этот проект пока не выкатывается как сайт. Что получилось — на странице каждой готовой стори, вкладка «Результат», и во вкладке «Код». Хотите открыть продукт по ссылке — попросите аналитика в чате: «сделай, чтобы продукт открывался по ссылке».")}
</span>
</div>
)}
{live && check && (
<p className="m-0 flex flex-wrap items-center gap-2 text-sm">
<Rocket className="size-4 text-primary" />
{t("Есть новая версия для проверки:")}{" "}
<a href={check.url} target="_blank" rel="noreferrer">
{host(check.url)}
</a>
{check.stories.length > 0 && <span className="text-muted-foreground">({check.stories.slice(0, 6).join(", ")})</span>} — {t("показать её всем можно в")}{" "}
<Link href={`/p/${projectKey}?tab=releases`}>{t("Релизах")}</Link>.
</p>
)}
{next}
</section>
);
}

View File

@ -47,6 +47,11 @@ function ProjectRow({ p, t }: { p: ProjectProgress; t: Translator }) {
<Key href={`/p/${p.key}`}>{p.key}</Key>
<Link href={`/p/${p.key}`} className="min-w-0 truncate font-medium text-foreground hover:no-underline">{p.name}</Link>
{p.ownerLogin && <span className="rounded-full border px-2 text-[11px] text-muted-foreground">{p.ownerLogin}</span>}
{p.product && (
<a href={p.product.url} target="_blank" rel="noreferrer" className="rounded-full border border-ok/50 bg-ok/10 px-2 text-[11px] font-medium text-foreground hover:no-underline" title={p.product.live ? t("Рабочая версия, открыта для всех") : t("Версия для проверки")}>
{p.product.live ? t("Открыть продукт") : t("Версия для проверки")} ↗
</a>
)}
<span className="ml-auto text-xs text-muted-foreground">
{p.total ? (
<>

View File

@ -0,0 +1,49 @@
"use client";
import { useEffect, useState } from "react";
import { RefreshCw } from "lucide-react";
import { useT } from "@/components/I18n";
/**
* PEP-114: a page opened before the site was updated may press buttons the new server doesn't
* know — nothing happens and nothing is said. This watches the server's boot id (once a minute
* and when the tab comes back) and asks to reload when it changed. Never reloads by itself: the
* person may be in the middle of typing.
*/
export function VersionWatch({ boot }: { boot: string }) {
const t = useT();
const [stale, setStale] = useState(false);
useEffect(() => {
let alive = true;
const check = async () => {
try {
const r = await fetch("/api/health", { cache: "no-store" });
const now = ((await r.json()) as { boot?: string }).boot;
if (alive && now && now !== boot) setStale(true);
} catch {
/* offline or restarting: the next check will tell */
}
};
const timer = setInterval(check, 60_000);
const onVisible = () => document.visibilityState === "visible" && void check();
document.addEventListener("visibilitychange", onVisible);
window.addEventListener("focus", onVisible);
return () => {
alive = false;
clearInterval(timer);
document.removeEventListener("visibilitychange", onVisible);
window.removeEventListener("focus", onVisible);
};
}, [boot]);
if (!stale) return null;
return (
<div role="alert" className="sticky top-0 z-40 flex flex-wrap items-center justify-center gap-3 border-b border-primary/50 bg-primary/15 px-4 py-2 text-sm">
<span>{t("Peppa FACTORY обновилась. Обновите страницу — иначе кнопки на ней могут не сработать.")}</span>
<button type="button" onClick={() => window.location.reload()} className="inline-flex items-center gap-1.5 rounded-md bg-primary px-3 py-1 font-medium text-primary-foreground">
<RefreshCw className="size-3.5" /> {t("Обновить страницу")}
</button>
</div>
);
}

9
apps/web/lib/boot.ts Normal file
View File

@ -0,0 +1,9 @@
// PEP-114: one id per start of the web process (shared by pages and route handlers through
// globalThis). A page keeps the id it was rendered with; when /api/health reports another one,
// the server was restarted with new code and the page's buttons may no longer be known to it.
const g = globalThis as typeof globalThis & { __peppaBoot?: string };
export function bootId(): string {
g.__peppaBoot ??= `${process.env.NEXT_PUBLIC_PEPPA_COMMIT ?? "dev"}-${Date.now().toString(36)}`;
return g.__peppaBoot;
}

View File

@ -0,0 +1,19 @@
# Proposal: PEP-111 — «Ваш продукт»: где результат и что дальше
## Why
Владелец проекта: стори приняты, продукт выкачен и открыт по адресу, но она об этом не знает и
спрашивает в чате «где это работает? где увидеть результат?». В ленте вместо ответа —
«preview bc476e6: убран».
## What Changes
- `core/product.ts`: `projectProduct` (рабочая версия — prod; версия для проверки — staging, если
новее; число принятых стори), `productUrls` (для Главной).
- Веб: карточка `ProductCard` над доской проекта («Ваш продукт работает» + адрес + «Открыть
продукт» / «Версия для проверки готова» / «проект не выкатывается как сайт — где смотреть»),
ссылка «Открыть продукт ↗» у проекта на Главной.
- Сообщения PM: staging — «новая версия готова к проверке… Показать её всем?»; prod — «ваш
продукт обновлён и открыт для всех… Что дальше»; «бэклог пуст» — со ссылкой на продукт и
подсказкой написать аналитику. Без хэшей коммитов.
- Чат: релизы словами («Версия для проверки: работает», «Рабочая версия продукта: работает»),
черновые стенды стори в ленту не попадают (кроме сбоя).
- Ссылка «Чат с аналитиком» на странице проекта — только участникам проекта.

View File

@ -0,0 +1,16 @@
## ADDED Requirements
### Requirement: Результат проекта на виду
Веб SHALL показывать владельцу, где работает его продукт, и что делать дальше.
#### Scenario: Продукт выкачен
- **WHEN** у проекта есть здоровая рабочая версия
- **THEN** над доской видно «Ваш продукт работает», адрес и кнопка «Открыть продукт»
#### Scenario: Только версия для проверки
- **WHEN** есть здоровая версия для проверки новее рабочей
- **THEN** карточка предлагает посмотреть её и показать всем
#### Scenario: Проект не выкатывается
- **WHEN** принятые стори есть, а версий нет
- **THEN** карточка говорит, где смотреть результат

View File

@ -0,0 +1,3 @@
- [x] 1.1 core/product.ts, сообщения релизов и «бэклог пуст»
- [x] 1.2 веб: ProductCard, ссылка на Главной
- [x] 1.3 тест product.test.ts; проверка в браузере на копии базы

View File

@ -0,0 +1,8 @@
# Proposal: PEP-114 — открытая страница просит обновиться после обновления сайта
## Why
PM нажала «Оставить комментарий» на странице, открытой до перезапуска веба: ничего не произошло и ошибки не было.
## What Changes
- `lib/boot.ts`: id запуска веб-процесса (`globalThis`), `/api/health` отдаёт его в поле `boot`.
- `VersionWatch` в layout: раз в минуту и при возврате на вкладку сверяет `boot`; при расхождении — плашка «Peppa FACTORY обновилась. Обновите страницу» с кнопкой. Сама страницу не перезагружает (человек может печатать).

View File

@ -0,0 +1,12 @@
## ADDED Requirements
### Requirement: Устаревшая страница сообщает о себе
Веб SHALL показывать на странице, открытой до перезапуска сервера, просьбу обновить её.
#### Scenario: Сайт обновили при открытой странице
- **WHEN** веб перезапущен, а вкладка пользователя открыта раньше
- **THEN** в течение минуты (или при возврате на вкладку) наверху появляется плашка с кнопкой «Обновить страницу»
#### Scenario: Сайт не менялся
- **WHEN** сервер тот же
- **THEN** плашки нет

View File

@ -0,0 +1,2 @@
- [x] 1.1 boot id, поле в /api/health, VersionWatch
- [x] 1.2 проверка в браузере (тот же запуск — плашки нет; другой — есть)

View File

@ -342,14 +342,16 @@ const EVENT_TEXT: Record<string, (p: P) => { text: string; important?: boolean;
};
const RELEASE_ICON: Record<string, string> = { deploying: "⏳", healthy: "🚀", rolled_back: "↩️", failed: "❌", removed: "🧹" };
// "<icon> <env> <sha>: <status>[ · <stories>]" — a whole template per status, so the line translates.
const RELEASE_LINE: Record<string, (v: { release: string; tasks: string }) => string> = {
deploying: (v) => (v.tasks ? tr("{release}: выкатывается · {tasks}", v) : tr("{release}: выкатывается", v)),
healthy: (v) => (v.tasks ? tr("{release}: здоров · {tasks}", v) : tr("{release}: здоров", v)),
rolled_back: (v) => (v.tasks ? tr("{release}: откатан · {tasks}", v) : tr("{release}: откатан", v)),
failed: (v) => (v.tasks ? tr("{release}: не выкатился · {tasks}", v) : tr("{release}: не выкатился", v)),
removed: (v) => (v.tasks ? tr("{release}: убран · {tasks}", v) : tr("{release}: убран", v)),
// "<icon> <what>: <status>[ · стори: <keys>]" — each piece is a dictionary entry, so the line translates.
const RELEASE_RU: Record<string, string> = {
deploying: tr("выкатывается"),
healthy: tr("работает"),
rolled_back: tr("не прошла проверку — возвращена прежняя"),
failed: tr("не выкатилась"),
removed: tr("убрана"),
};
// PEP-111: what a release is, in words for a product manager.
const ENV_RU: Record<string, string> = { preview: tr("Черновой стенд стори"), staging: tr("Версия для проверки"), prod: tr("Рабочая версия продукта") };
const INCIDENT_RU: Record<string, string> = {
new: tr("новая"),
open: tr("открыта"),
@ -461,15 +463,15 @@ export async function syncChats(db: Db, o: { now?: Date } = {}): Promise<number>
const savedObjects = await getSetting<number>(db, CURSOR_OBJECTS);
const since = new Date((savedObjects ?? now.getTime() - DAY) - 60_000);
for (const r of await db.select().from(releases).where(gt(releases.updatedAt, since)).orderBy(asc(releases.id))) {
const release = `${RELEASE_ICON[r.status] ?? "•"} ${r.env} ${r.sha.slice(0, 7)}`;
const tasksIn = r.tasks.slice(0, 8).join(", ");
const line = RELEASE_LINE[r.status]?.({ release, tasks: tasksIn }) ?? `${release}: ${r.status}${tasksIn ? ` · ${tasksIn}` : ""}`;
// A story's draft stand coming and going is plumbing: only its failure is worth a message.
if (r.env === "preview" && r.status !== "failed" && r.status !== "rolled_back") continue;
const tasksIn = r.tasks.length ? ` · ${tr("стори: {tasks}", { tasks: r.tasks.slice(0, 8).join(", ") })}` : "";
await add({
chatId: await chatId(r.projectId),
threadKey: `release:${r.id}`,
kind: "event",
important: r.env !== "preview" || r.status === "failed" || r.status === "rolled_back",
text: `${line}${r.reason ? `\n${cut(r.reason, 300)}` : ""}`,
text: `${RELEASE_ICON[r.status] ?? "•"} ${ENV_RU[r.env] ?? r.env}: ${RELEASE_RU[r.status] ?? r.status}${tasksIn}${r.reason ? `\n${cut(r.reason, 300)}` : ""}`,
url: r.host ? `https://${r.host}` : r.runUrl,
dedupeKey: `release:${r.id}:${r.status}`,
});

View File

@ -27,6 +27,7 @@ export * from "./team.ts";
export * from "./progress.ts";
export * from "./intake.ts";
export * from "./analyst-chat.ts";
export * from "./product.ts";
export * from "./local-users.ts";
export * from "./specs.ts";
export * from "./subscriptions.ts";

View File

@ -0,0 +1,51 @@
// PEP-111: «Ваш продукт» — where the result of the project lives, in words for a product
// manager: the working version everyone sees (prod), the version to check (staging), or the
// fact that the project is not deployed as a site at all.
import { releases, tasks, type Db } from "@peppa/db";
import { and, desc, eq, inArray, isNull } from "drizzle-orm";
export interface ProductVersion {
url: string;
at: Date;
/** Story keys that went into it. */
stories: string[];
}
export interface ProjectProduct {
/** The working product, open to everyone. */
live: ProductVersion | null;
/** The version to check before showing it to everyone — only when newer than `live`. */
check: ProductVersion | null;
/** Stories accepted so far (a product without a site still has results). */
doneStories: number;
}
export async function projectProduct(db: Db, projectId: number): Promise<ProjectProduct> {
const latest = async (env: "prod" | "staging") =>
(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))[0];
const [prod, staging] = [await latest("prod"), await latest("staging")];
const version = (r: NonNullable<typeof prod>): ProductVersion | null => (r.host ? { url: `https://${r.host}`, at: r.updatedAt ?? r.createdAt, stories: r.tasks } : null);
const done = await db.select({ id: tasks.id }).from(tasks).where(and(eq(tasks.projectId, projectId), eq(tasks.status, "done"), isNull(tasks.archivedAt)));
return {
live: prod ? version(prod) : null,
check: staging && (!prod || (staging.id > prod.id && staging.sha !== prod.sha)) ? version(staging) : null,
doneStories: done.length,
};
}
/** Product links of several projects at once (the Home page): projectId → URL of the best version. */
export async function productUrls(db: Db, projectIds: number[]): Promise<Map<number, { url: string; live: boolean }>> {
const out = new Map<number, { url: string; live: boolean }>();
if (!projectIds.length) return out;
const rows = await db
.select({ projectId: releases.projectId, env: releases.env, host: releases.host })
.from(releases)
.where(and(inArray(releases.projectId, projectIds), inArray(releases.env, ["prod", "staging"]), eq(releases.status, "healthy")))
.orderBy(desc(releases.id));
for (const r of rows) {
if (!r.host) continue;
const cur = out.get(r.projectId);
if (!cur || (!cur.live && r.env === "prod")) out.set(r.projectId, { url: `https://${r.host}`, live: r.env === "prod" });
}
return out;
}

View File

@ -1,6 +1,7 @@
// PEP-77: progress of every project on the Home page — stories per board column and what is
// in work right now (agent, tasks.md progress).
import { m as tr } from "@peppa/shared/i18n";
import { productUrls } from "./product.ts";
import { projects, tasks, users, type Db } from "@peppa/db";
import { formatTaskKey } from "@peppa/shared";
import { and, asc, eq, inArray, isNull } from "drizzle-orm";
@ -32,6 +33,8 @@ export interface ProjectProgress {
working: StoryInWork[];
/** Stories waiting for the PM's «Принять». */
reviewKeys: string[];
/** PEP-111: where the product runs (prod, else the version to check), if it is deployed. */
product: { url: string; live: boolean } | null;
}
export interface ProgressOverview {
@ -48,6 +51,7 @@ export async function progressOverview(db: Db, userId: number): Promise<Progress
const mineIds = await userProjectIds(db, userId);
const otherRows = await listOtherProjects(db, userId);
const ids = [...mineIds, ...otherRows.map((p) => p.id)];
const products = await productUrls(db, ids);
const empty: ProgressOverview = { mine: [], others: [], totals: { backlog: 0, inProgress: 0, review: 0, done: 0, total: 0 } };
if (!ids.length) return empty;
const ps = await db.select({ p: projects, ownerLogin: users.login }).from(projects).leftJoin(users, eq(users.id, projects.ownerId)).where(inArray(projects.id, ids)).orderBy(asc(projects.key));
@ -55,7 +59,7 @@ export async function progressOverview(db: Db, userId: number): Promise<Progress
const mine = new Set(mineIds);
const out = empty;
for (const { p, ownerLogin } of ps) {
const row: ProjectProgress = { key: p.key, name: p.name, ownerLogin: mine.has(p.id) ? null : (ownerLogin ?? tr("без владельца")), backlog: 0, inProgress: 0, review: 0, done: 0, total: 0, working: [], reviewKeys: [] };
const row: ProjectProgress = { key: p.key, name: p.name, ownerLogin: mine.has(p.id) ? null : (ownerLogin ?? tr("без владельца")), backlog: 0, inProgress: 0, review: 0, done: 0, total: 0, working: [], reviewKeys: [], product: products.get(p.id) ?? null };
const own = ts.filter((t) => t.projectId === p.id);
const agentsOf = own.some((t) => column(t.status) === "inProgress") ? await taskAgentNames(db, p.id) : new Map<number, string>();
for (const t of own) {

View File

@ -34,6 +34,7 @@ import {
type TaskRef,
projectAgentWarning,
intakePendingTasks,
productUrls,
} from "@peppa/core";
import { goals, incidents, questions, tasks, type Db } from "@peppa/db";
import { formatTaskKey } from "@peppa/shared";
@ -273,7 +274,17 @@ async function dispatch(db: Db, project: Project, a: AutonomySettings, now: Date
}
if (!backlog.length && working.length === 0 && a.idlePush && !state.emptyNotified) {
await setIdle(db, project.id, { ...state, emptyNotified: true });
await askPmProject(db, project, { kind: "attention", text: m("📭 {project}: бэклог пуст — агентам нечего делать. Добавьте стори, и Пеппа возьмёт их сама.", { project: project.name }) });
// PEP-111: everything asked for is done — say where the result is and what to do next.
const product = (await productUrls(db, [project.id])).get(project.id);
const web = process.env.PEPPA_WEB_URL ?? "";
await askPmProject(db, project, {
kind: "attention",
text: [
m("📭 {project}: все стори сделаны, бэклог пуст — агентам нечего делать.", { project: project.name }),
...(product ? [product.live ? m("Ваш продукт: {url}", { url: product.url }) : m("Версия для проверки: {url}", { url: product.url })] : []),
m("Что дальше: опишите следующую задачу аналитику в чате проекта ({url}) или добавьте стори на доске — агенты возьмут её сами.", { url: `${web}/chats/${project.key}` }),
].join("\n"),
});
}
return;
}

View File

@ -111,8 +111,7 @@ export async function recordRelease(db: Db, project: Project, r: DeployReport):
async function notifyRelease(db: Db, project: Project, rel: Release) {
const tasks = rel.tasks.join(", ");
const host = rel.host ? `\nhttps://${rel.host}` : "";
const v = { project: project.name, sha: short(rel.sha), tasks, host };
const v = { project: project.name, sha: short(rel.sha), tasks };
const log = runLink(rel.runUrl);
if (rel.status === "rolled_back" || rel.status === "failed") {
const head =
@ -128,12 +127,19 @@ async function notifyRelease(db: Db, project: Project, rel: Release) {
await askPmProject(db, project, {
kind: "question",
options: [PROD_OPTION],
text: rel.tasks.length
? m("✅ {project}: staging обновлён — {sha} · стори: {tasks}{host}\nВыкатить этот релиз в прод?", v)
: m("✅ {project}: staging обновлён — {sha}{host}\nВыкатить этот релиз в прод?", v),
// PEP-111: said for a product manager — what it is, where to look, what the button does.
text: [
rel.tasks.length ? m("✅ {project}: новая версия готова к проверке · стори: {tasks}", v) : m("✅ {project}: новая версия готова к проверке", v),
...(rel.host ? [m("Посмотреть: {url}", { url: `https://${rel.host}` })] : []),
m("Это версия только для вас. Показать её всем пользователям?"),
].join("\n"),
});
} else if (rel.status === "healthy" && rel.env === "prod") {
await askPmProject(db, project, { kind: "attention", text: rel.tasks.length ? m("🚀 {project} в проде: {sha} · стори: {tasks}{host}", v) : m("🚀 {project} в проде: {sha}{host}", v) });
const storiesIn = rel.tasks.length ? ` · ${m("стори: {tasks}", v)}` : "";
await askPmProject(db, project, {
kind: "attention",
text: `${m("🚀 {project}: ваш продукт обновлён и открыт для всех", v)}${rel.host ? `\n${m("Открыть: {url}", { url: `https://${rel.host}` })}` : ""}${storiesIn}\n${m("Что дальше: опишите следующую задачу аналитику в чате проекта — {url}", { url: `${process.env.PEPPA_WEB_URL ?? ""}/chats/${project.key}` })}`,
});
}
}

View File

@ -154,4 +154,46 @@ export const merge: Dict = {
"ждут сброса: {n}": "waiting for reset: {n}",
"<b>Несколько своих подписок</b> — «⋯ Настройки проекта → Подписки»: у каждой подписки пула видно «в работе: N агентов», «свободна», «лимит до 15:40» и сколько использовано окна лимита. «Добавить ещё Claude» / «Добавить ещё ChatGPT» — тот же вход по ссылке; «Убрать» — своя подписка, на которой сейчас никто не работает. Когда в пуле остаётся одна рабочая подписка и она использована больше чем на 85%, участникам приходит одно предупреждение «осталась одна подписка, скоро лимит».": "<b>Several subscriptions of your own</b> — “⋯ Project settings → Subscriptions”: each subscription in the pool shows “at work: N agents”, “free”, “limit until 15:40” and how much of the limit window is used. “Add another Claude” / “Add another ChatGPT” — the same sign-in by link; “Remove” — your own subscription that nobody is working on right now. When the pool is down to one working subscription and it is more than 85% used, members get a single warning “only one subscription left, limit soon”.",
"<b>Запасная подписка от суперадмина</b> — «Подписки → Картина по пулам»: все пулы с состоянием подписок, раннерами, ждущими сброса, и пометкой «запасной нет». «Одолжить подписку» добавляет подписку в чужой пул на 1–168 часов; по сроку она возвращается сама (агенты на ней дорабатывают текущий запуск), «Вернуть сейчас» — раньше.": "<b>A spare subscription from the superadmin</b> — “Subscriptions → Pools at a glance”: every pool with the state of its subscriptions, runners waiting for a reset, and a “no spare” mark. “Lend a subscription” adds a subscription to someone's pool for 1–168 hours; it goes back on its own when the time is up (agents on it finish their current run), “Return now” — earlier.",
// PEP-111: your product; PEP-114: stale page banner
"Что дальше: опишите следующую задачу": "What's next: describe the next task",
"аналитику в чате": "to the analyst in the chat",
"он поможет сформулировать стори, агенты сделают.": "they will help shape it into a story, and the agents will build it.",
"Ваш продукт": "Your product",
"Ваш продукт работает": "Your product is live",
"Открыт для всех по адресу": "Open to everyone at",
"обновлён {when}": "updated {when}",
"вошли стори {keys}": "includes stories {keys}",
"Открыть продукт": "Open product",
"Версия для проверки готова": "A version to check is ready",
"Пока её видите только вы:": "Only you can see it for now:",
"обновлена {when}.": "updated {when}.",
"Посмотрите — и покажите всем кнопкой «Выкатить» в": "Take a look, then show it to everyone with the “Deploy” button in",
"Релизах": "Releases",
"Готово стори: {n}": "Stories done: {n}",
"Этот проект пока не выкатывается как сайт. Что получилось — на странице каждой готовой стори, вкладка «Результат», и во вкладке «Код». Хотите открыть продукт по ссылке — попросите аналитика в чате: «сделай, чтобы продукт открывался по ссылке».":
"This project is not deployed as a website yet. See the results on each finished story's page, on the “Result” tab, and on the “Code” tab. Want the product to open by a link? Ask the analyst in the chat: “make the product open by a link”.",
"Есть новая версия для проверки:": "A new version to check is available:",
"показать её всем можно в": "you can show it to everyone in",
"Рабочая версия, открыта для всех": "Live version, open to everyone",
"Версия для проверки": "Version to check",
"Peppa FACTORY обновилась. Обновите страницу — иначе кнопки на ней могут не сработать.": "Peppa FACTORY has been updated. Reload the page, or its buttons may not work.",
"Обновить страницу": "Reload page",
"не прошла проверку — возвращена прежняя": "failed the check — the previous one is back",
"не выкатилась": "deployment failed",
убрана: "removed",
"Черновой стенд стори": "Story draft environment",
"Рабочая версия продукта": "Live product version",
"стори: {tasks}": "stories: {tasks}",
"📭 {project}: все стори сделаны, бэклог пуст — агентам нечего делать.": "📭 {project}: all stories are done, the backlog is empty — agents have nothing to do.",
"Ваш продукт: {url}": "Your product: {url}",
"Версия для проверки: {url}": "Version to check: {url}",
"Что дальше: опишите следующую задачу аналитику в чате проекта ({url}) или добавьте стори на доске — агенты возьмут её сами.":
"What's next: describe the next task to the analyst in the project chat ({url}) or add a story on the board — agents will pick it up on their own.",
"✅ {project}: новая версия готова к проверке · стори: {tasks}": "✅ {project}: a new version is ready to check · stories: {tasks}",
"✅ {project}: новая версия готова к проверке": "✅ {project}: a new version is ready to check",
"Посмотреть: {url}": "Take a look: {url}",
"Это версия только для вас. Показать её всем пользователям?": "Only you can see this version. Show it to all users?",
"🚀 {project}: ваш продукт обновлён и открыт для всех": "🚀 {project}: your product is updated and open to everyone",
"Открыть: {url}": "Open: {url}",
"Что дальше: опишите следующую задачу аналитику в чате проекта — {url}": "What's next: describe the next task to the analyst in the project chat — {url}",
};

View File

@ -103,6 +103,7 @@ describe("dispatcher", () => {
await autonomy();
assert.equal((await taskOf(second.key)).status, "done");
const empty = (await openQuestions(p.id)).filter((q) => q.text.includes("бэклог пуст"));
assert.match(empty[0]?.text ?? "", /Что дальше: опишите следующую задачу аналитику в чате проекта/, "PEP-111: what to do next");
assert.equal(empty.length, 1);
await autonomy();
assert.equal((await openQuestions(p.id)).filter((q) => q.text.includes("бэклог пуст")).length, 1, "told once");

View File

@ -162,7 +162,7 @@ describe("Релиз с бэкапом и автооткатом", () => {
assert.equal(done.id, rel.id, "the button's release row is the one completed");
assert.equal(done.status, "healthy");
assert.deepEqual(done.tasks, [`${pep.key}-5`]);
assert.ok((await messages()).some((t) => t.includes(`в проде: ${rel.sha.slice(0, 7)}`)), "the PM is told");
assert.ok((await messages()).some((t) => t.includes("ваш продукт обновлён и открыт для всех")), "the PM is told");
// The worktree is the commit; .env is the shared one.
assert.equal(readlinkSync(join(RELEASES, "releases", rel.sha, ".env")), join(RELEASES, "shared/.env"));
assert.ok(existsSync(join(RELEASES, "releases", rel.sha, "apps/web/.next/BUILD_ID")));

View File

@ -0,0 +1,69 @@
// PEP-111: «Ваш продукт» — where the project's result lives and how releases are said to a PM.
import assert from "node:assert/strict";
import { after, describe, test } from "node:test";
import { releases } from "@peppa/db";
import { core, db, teardown } from "./helpers.ts";
after(teardown);
let n = 0;
const proj = async () => {
n++;
return core.createProject(db, { slug: `mock-prod-${n}`, key: `MPR${String.fromCharCode(64 + n)}`, name: `Продукт ${n}`, giteaOwner: "x", workspacePath: `/tmp/mock-prod-${n}` });
};
const rel = (projectId: number, env: "preview" | "staging" | "prod", sha: string, status: "healthy" | "removed" | "failed" = "healthy", tasks: string[] = []) =>
db.insert(releases).values({ projectId, env, sha, status, host: `${env}.mock.test`, tasks }).returning().then((r) => r[0]!);
describe("PEP-111: the project's product", () => {
test("nothing deployed: no versions, only the count of accepted stories", async () => {
const p = await proj();
const t = await core.createTask(db, { projectId: p.id, title: "Первая" });
assert.deepEqual(await core.projectProduct(db, p.id), { live: null, check: null, doneStories: 0 });
await core.updateTask(db, t, { status: "done" });
assert.equal((await core.projectProduct(db, p.id)).doneStories, 1);
assert.equal((await core.productUrls(db, [p.id])).size, 0);
});
test("staging only → the version to check; prod → the working product; a newer staging is offered again", async () => {
const p = await proj();
await rel(p.id, "preview", "aaa1111", "removed");
await rel(p.id, "staging", "bbb2222", "healthy", ["X-1"]);
let v = await core.projectProduct(db, p.id);
assert.equal(v.live, null);
assert.equal(v.check?.url, "https://staging.mock.test");
assert.deepEqual((await core.productUrls(db, [p.id])).get(p.id), { url: "https://staging.mock.test", live: false });
await rel(p.id, "prod", "bbb2222", "healthy", ["X-1"]);
v = await core.projectProduct(db, p.id);
assert.equal(v.live?.url, "https://prod.mock.test");
assert.deepEqual(v.live?.stories, ["X-1"]);
assert.equal(v.check, null, "the same commit is already live");
assert.deepEqual((await core.productUrls(db, [p.id])).get(p.id), { url: "https://prod.mock.test", live: true });
await rel(p.id, "staging", "ccc3333", "healthy", ["X-2"]);
v = await core.projectProduct(db, p.id);
assert.equal(v.live?.url, "https://prod.mock.test");
assert.deepEqual(v.check?.stories, ["X-2"], "a newer version waits to be shown to everyone");
});
test("the chat says releases in plain words and keeps the draft stands out", async () => {
const p = await proj();
await rel(p.id, "preview", "ddd4444", "healthy");
await rel(p.id, "preview", "ddd4445", "removed");
await rel(p.id, "preview", "ddd4446", "failed");
await rel(p.id, "staging", "eee5555", "healthy", ["Y-1"]);
await rel(p.id, "prod", "eee5555", "healthy", ["Y-1"]);
await core.syncChats(db);
const chat = await core.ensureProjectChat(db, p.id);
const texts = (await core.chatMessagesView(db, chat.id, {})).map((m) => m.text);
assert.deepEqual(texts, ["❌ Черновой стенд стори: не выкатилась", "🚀 Версия для проверки: работает · стори: Y-1", "🚀 Рабочая версия продукта: работает · стори: Y-1"]);
assert.ok(texts.every((t) => !/[0-9a-f]{7}/.test(t)), "no commit hashes for a product manager");
});
test("the Home page carries the product link of each project", async () => {
const owner = await core.registerEgovUser(db, { iin: "880808400011", name: "ПРОДАКТ ТЕСТОВЫЙ" });
const p = await core.createProject(db, { slug: "mock-prod-home", key: "MPRH", name: "Домой", giteaOwner: "x", workspacePath: "/tmp/mock-prod-home", ownerId: owner.id });
await rel(p.id, "prod", "fff6666");
const o = await core.progressOverview(db, owner.id);
assert.deepEqual(o.mine.find((x) => x.key === "MPRH")?.product, { url: "https://prod.mock.test", live: true });
});
});