PEP-123: wording by view — «задача»/«агент» for «Продакт», «вы» everywhere; engineer-only project settings

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Асель 2026-11-15 18:05:34 +05:00
parent 554eeef7c1
commit 2c957631e8
39 changed files with 389 additions and 192 deletions

View File

@ -118,7 +118,7 @@ export async function addTask(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
if (!str(f, "title")) throw new PeppaError("Нужно название стори");
if (!str(f, "title")) throw new PeppaError("Нужно название задачи");
const epic = Number(str(f, "epicId")) || undefined;
const ref = await createTask(db, { projectId: p.id, title: str(f, "title"), description: str(f, "description") || undefined, goalId: epic });
return `/t/${ref.key}`;
@ -156,7 +156,7 @@ export async function editStoryAction(f: FormData) {
const ref = await resolveTask(db, str(f, "taskKey"));
await projectForUser(db, user.id, ref.project.id);
const title = str(f, "title");
if (title.length < 2) throw new PeppaError("Нужно название стори");
if (title.length < 2) throw new PeppaError("Нужно название задачи");
const epic = str(f, "epicId");
await updateTask(db, ref, { title, description: String(f.get("description") ?? "").trim(), goalId: epic ? Number(epic) : null }, undefined, user.login);
});
@ -426,7 +426,7 @@ export async function pairingLinkAction(): Promise<{ url?: string; error?: strin
// Every user has their own bot: no pairing link through the shared one.
const username = user.telegramBotUsername;
if (!username) return { error: "Сначала подключите своего бота (шаги 1–2)" };
if (!token) return { error: "Telegram-сервис Пеппы не запущен" };
if (!token) return { error: "Telegram сейчас недоступен. Попробуйте через минуту." };
return { url: `https://t.me/${username}?start=${await createPairingCode(db, token, user.id)}` };
}
@ -437,7 +437,7 @@ export async function pairTelegram(f: FormData) {
// Every user has their own bot (PEP-85/100): the platform's bot is never offered to users.
const username = user.telegramBotUsername;
if (!username) throw new PeppaError("Сначала подключите своего Telegram-бота");
if (!token) throw new PeppaError("Telegram-сервис Пеппы не запущен");
if (!token) throw new PeppaError("Telegram сейчас недоступен. Попробуйте через минуту.");
return `https://t.me/${username}?start=${await createPairingCode(db, token, user.id)}`;
});
}
@ -518,7 +518,7 @@ export async function testPushAction(endpoint: string): Promise<{ ok: boolean; e
const sub = (await userPushSubscriptions(db, user.id)).find((s) => s.endpoint === endpoint);
if (!sub) return { ok: false, error: "Этот браузер не подписан" };
const prefs = await getNotifyPrefs(db, user.id);
const r = await sendWebPush(db, sub, { title: "Пеппа", body: "Уведомления в этом браузере работают ✅", url: "/settings#notifications", tag: "test", sound: prefs.sound });
const r = await sendWebPush(db, sub, { title: "Peppa FACTORY", body: "Уведомления в этом браузере работают ✅", url: "/settings#notifications", tag: "test", sound: prefs.sound });
if (r.ok) return { ok: true };
if (r.gone) await deletePushSubscription(db, user.id, endpoint);
return { ok: false, error: r.error };

View File

@ -97,12 +97,12 @@ export async function applyPlanAction(f: FormData) {
// Plan numbers in the form refer to the full draft; renumber them for the kept stories.
const kept: number[] = [];
for (let i = 1; i <= n; i++) if (f.get(`keep_${i}`)) kept.push(i);
if (!kept.length) throw new PeppaError("Не выбрано ни одной стори");
if (!kept.length) throw new PeppaError("Не выбрано ни одной задачи. Отметьте хотя бы одну.");
const renum = new Map(kept.map((orig, i) => [orig, i + 1]));
const stories: PlannedStory[] = kept.map((i) => {
const deps = parseDepsInput(str(f, `deps_${i}`)).map((d): PlanDep => {
if (typeof d !== "number") return d;
if (!renum.has(d)) throw new PeppaError(`Стори ${i} зависит от №${d}, которую вы сняли — уберите зависимость или оставьте стори`);
if (!renum.has(d)) throw new PeppaError(`Задача ${i} зависит от №${d}, которую вы сняли. Уберите зависимость или оставьте задачу.`);
return renum.get(d)!;
});
return { title: str(f, `title_${i}`), description: str(f, `description_${i}`), dependsOn: deps };

View File

@ -12,7 +12,7 @@ import { Hidden, QuestionCard } from "@/components/cards";
import { Workspace } from "@/components/Workspace";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/input";
import { requireUser } from "@/lib/auth";
import { requireUser, words } from "@/lib/auth";
import { db } from "@/lib/db";
import { cn } from "@/lib/utils";
import { linkChatAction, postChatAction, unlinkChatAction } from "../actions";
@ -26,6 +26,7 @@ const FEED = "feed";
/** «Чаты» (PEP-62): the master chat and project chats with threads; a linked Telegram group mirrors them. */
export default async function ChatPage({ params, searchParams }: { params: Promise<{ chat: string }>; searchParams: Promise<Params> }) {
const user = await requireUser();
const w = await words();
const { chat: slug } = await params;
const { error, thread: rawThread, link } = await searchParams;
// Whoever renders first moves fresh events into the chats (the bot and the watchdog do it too).
@ -71,14 +72,14 @@ export default async function ChatPage({ params, searchParams }: { params: Promi
const ttlDays = Math.round(chatTtlMs() / 86_400_000);
const taskThread = thread?.startsWith("task:");
const placeholder = master
? "/status, /task KEY-N, /move KEY-N in_progress, /help"
? w.engineer ? "/status, /task KEY-N, /move KEY-N in_progress, /help" : "Заметка для себя"
: discussion
? "Спросите аналитика, что с проектом, или опишите идею — он поможет сформулировать стори…"
? `Спросите аналитика, что с проектом, или опишите идею — он поможет сформулировать ${w.task("acc")}…`
: taskThread
? "Напишите агенту этой стори — ответ на его вопрос или замечание, он увидит сразу"
? `Напишите агенту этой ${w.task("gen")} — ответ на его вопрос или замечание, он увидит сразу`
: thread
? "Заметка в тред или команда /help"
: "Заметка в канал или команда: /status, /task KEY-N, /move KEY-N in_progress";
? w.engineer ? "Заметка в тред или команда /help" : "Заметка к этой переписке"
: w.engineer ? "Заметка в канал или команда: /status, /task KEY-N, /move KEY-N in_progress" : "Заметка для себя и участников проекта";
const aside = (
<div className="flex flex-col gap-5 text-sm">
@ -108,7 +109,7 @@ export default async function ChatPage({ params, searchParams }: { params: Promi
через бота <span className="font-mono text-foreground">@{groupBot}</span>
</>
)}
. Сообщения чата приходят туда, треды — цепочками ответов; ответ реплаем уходит в тред{master ? "" : " (в треде стори — агенту)"}.
. Сообщения чата приходят туда, треды — цепочками ответов; ответ реплаем уходит в тред{master ? "" : ` (в переписке по ${w.task("dat")} — агенту)`}.
</p>
<form action={unlinkChatAction}>
<Hidden fields={{ chatId: chat.id, back: here }} />
@ -160,8 +161,8 @@ export default async function ChatPage({ params, searchParams }: { params: Promi
<h2 className="m-0 text-[15px] font-semibold text-foreground">Как это устроено</h2>
<p className="m-0">
{master
? "Журнал: готовые стори, вопросы, релизы и сбои по всем вашим проектам. Отвечать удобнее в «Обзоре» или в чате проекта."
: "Слева: чат с аналитиком — для вопросов и новых задач; «События агентов» — журнал; ниже — переписка по каждой стори с её агентом."}
? `Журнал: готовые ${w.task("pl")}, вопросы, обновления продукта и сбои по всем вашим проектам. Отвечать удобнее в «Обзоре» или в чате проекта.`
: `Слева: чат с аналитиком — для вопросов и новых задач; «События агентов» — журнал; ниже — переписка по каждой ${w.task("dat")} с её агентом.`}
</p>
<p className="m-0">Журнал событий хранится {ttlDays} дн.; ваша переписка с аналитиком не удаляется.</p>
</section>
@ -175,7 +176,7 @@ export default async function ChatPage({ params, searchParams }: { params: Promi
<PageHeader title="Чаты">
{master
? "Все события по вашим проектам — журнал, справочно. Чтобы ответить агенту или написать аналитику, откройте чат проекта."
: "Чат с аналитиком — ИИ-агентом вашего проекта. Спросите, что сделано и где это посмотреть, или опишите идею: он уточнит, предложит стори и заведёт их в бэклог, когда вы скажете."}
: `Чат с аналитиком — ИИ-агентом вашего проекта. Спросите, что сделано и где это посмотреть, или опишите идею: он уточнит, предложит ${w.task("accPl")} и заведёт их в бэклог, когда вы скажете.`}
</PageHeader>
<nav className="mb-4 flex flex-wrap gap-1.5" aria-label="Чаты">
@ -212,11 +213,11 @@ export default async function ChatPage({ params, searchParams }: { params: Promi
<nav aria-label="Треды" className="flex flex-col gap-0.5 self-start rounded-lg border bg-card/50 p-1.5 text-sm max-lg:max-h-48 max-lg:overflow-y-auto">
<ThreadLink href={url({})} active={discussion} title="💬 Чат с аналитиком" meta="вопросы и новые задачи" />
<ThreadLink href={url({ thread: FEED })} active={!discussion && thread === undefined} title="События агентов" meta="журнал: что делали агенты" />
{threads.length > 0 && <p className="m-0 px-2 pt-2 text-[11px] tracking-wide text-muted-foreground uppercase">Переписка по стори</p>}
{threads.length > 0 && <p className="m-0 px-2 pt-2 text-[11px] tracking-wide text-muted-foreground uppercase">Переписка по {w.task("datPl")}</p>}
{threads.map((t) => (
<ThreadLink key={t.key} href={url({ thread: t.key })} active={thread === t.key} title={t.title} meta={`${t.count} · ${ago(t.lastAt)}`} open={t.open} />
))}
{threads.length === 0 && <p className="m-0 px-2 py-1.5 text-xs text-muted-foreground">Переписки по стори пока нет.</p>}
{threads.length === 0 && <p className="m-0 px-2 py-1.5 text-xs text-muted-foreground">Переписки по {w.task("datPl")} пока нет.</p>}
</nav>
)}
@ -224,11 +225,11 @@ export default async function ChatPage({ params, searchParams }: { params: Promi
{current && (
<div className="flex flex-wrap items-center gap-2 text-sm">
<span className="font-medium">🧵 {current}</span>
{taskThread && <TaskLink messages={messages} />}
{taskThread && <TaskLink messages={messages} label={`открыть ${w.task("acc")} →`} />}
</div>
)}
{messages.length === 0 ? (
<Empty>{discussion ? "Напишите, что хотите узнать или сделать, — аналитик ответит здесь же. Например: «Что сейчас в работе?» или «Хочу страницу с отзывами клиентов»." : master ? "Пока тихо: здесь появятся вопросы агентов, сбои, релизы и ошибки твоих проектов." : thread === undefined ? "Сообщений пока нет: они появятся, когда агенты возьмутся за стори." : "В этом треде пока пусто."}</Empty>
<Empty>{discussion ? "Напишите, что хотите узнать или сделать, — аналитик ответит здесь же. Например: «Что сейчас в работе?» или «Хочу страницу с отзывами клиентов»." : master ? "Пока тихо: здесь появятся вопросы агентов, сбои и обновления ваших проектов." : thread === undefined ? `Сообщений пока нет: они появятся, когда агенты возьмутся за ${w.task("accPl")}.` : "В этом треде пока пусто."}</Empty>
) : (
<ol className="m-0 flex list-none flex-col gap-2 p-0">
{messages.map((m) => (
@ -283,9 +284,9 @@ function ThreadLink({ href, active, title, meta, open = 0 }: { href: string; act
);
}
function TaskLink({ messages }: { messages: ChatMessageView[] }) {
function TaskLink({ messages, label }: { messages: ChatMessageView[]; label: string }) {
const key = messages.find((m) => m.threadTitle)?.threadTitle?.split(" · ")[0];
return key ? <Link href={`/t/${key}`} className="text-xs">открыть стори →</Link> : null;
return key ? <Link href={`/t/${key}`} className="text-xs">{label}</Link> : null;
}
/** URLs in a message become links (the analyst points at the board, a story, a stand). */
@ -315,7 +316,7 @@ function MessageItem({ m, q, back, showThread, masterView, mine = false }: { m:
{m.authorKind === "agent" && m.authorLogin ? (
<AgentBadge name={m.authorLogin} className="text-foreground" />
) : (
<span className="font-medium text-foreground">{m.authorKind === "user" ? (mine ? "вы" : (m.authorLogin ?? "?")) : m.authorKind === "agent" ? "агент" : "Пеппа"}</span>
<span className="font-medium text-foreground">{m.authorKind === "user" ? (mine ? "вы" : (m.authorLogin ?? "?")) : m.authorKind === "agent" ? "агент" : "Peppa FACTORY"}</span>
)}
{m.via === "telegram" && <span title="из Telegram">· Telegram</span>}
{where && href && (

View File

@ -40,7 +40,7 @@ export async function linkChatAction(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
const token = loadEnv().TELEGRAM_BOT_TOKEN;
if (!token) throw new PeppaError("Telegram в Пеппе не настроен");
if (!token) throw new PeppaError("Telegram пока не настроен. Напишите в поддержку Peppa FACTORY.");
const chat = await chatForUser(db, user, Number(str(f, "chatId")));
// PEP-109: the group is linked through the user's own bot; the platform's bot is the
// superadmin's (PEP-106) and serves only a superadmin who has no bot of their own.

View File

@ -73,7 +73,7 @@ export default async function Chats({ searchParams }: { searchParams: Promise<{
</Section>
<p className="mt-6 text-sm text-muted-foreground">
Нужна история? <Link href="/chats/master">Все события по вашим проектам</Link> — что делали агенты, релизы и сбои, справочно.
Нужна история? <Link href="/chats/master">Все события по вашим проектам</Link> — что делали агенты, обновления продукта и сбои, справочно.
</p>
</Workspace>
);

View File

@ -76,8 +76,8 @@ export default async function Help() {
<li><b>Продакт и аналитик</b> — два агента, которые читают новую задачу раньше разработчика. Продакт решает, зачем это и что берём в первую версию (большое делит на несколько стори). Аналитик пишет критерии приёмки и задаёт до трёх вопросов — у каждого есть вариант по умолчанию; не ответите за 30 минут (ночью — до утра), он возьмёт его сам. Их реплики — во вкладке Comments стори и в чате проекта. Включается в «⋯ Настройки проекта → Продакт и аналитик», в новых проектах включено.</li>
<li><b>Команда</b> — ИИ-агенты с кличками (Шустрик, Беркут…), одна команда на все проекты: свободный агент берёт стори и ведёт её до конца, его кличка видна на карточке. В разделе «Команда» суперадмин задаёт агенту характер и специализацию — они добавляются к его промпту.</li>
<li><b>Вход</b> — через eGov QR (с телефона — кнопка «Открыть в eGov Mobile») или через Google (кнопка есть, когда суперадмин задал <span className="font-mono">GOOGLE_CLIENT_ID/SECRET</span>); в «Настройках» их можно связать в одну учётку. Первый вход сам создаёт учётку по ИИН или Google-почте: логин из имени в сертификате (например, <span className="font-mono">aigerim.ivanova</span>). Новый пользователь видит только проекты, куда его пригласили, и свои; агенты его проектов работают только на пуле подписок, который назначает суперадмин. У такой учётки нет аккаунта Gitea — код только через Пеппу, а новые проекты создаются в пространстве <span className="font-mono">peppa-bot</span>.</li>
<li><b>Раннер</b> — агент, запущенный по стори в tmux на машине Пеппы. Все раннеры твоих и общих проектов — в разделе <Link href="/runners">Раннеры</Link>: статус, стори, команда <code>tmux attach</code>, сообщение, остановка и resume; фильтры-счётчики «ждут тебя / работают / упали / готово» и поиск; строки, где нужен ты, подсвечены, у раннера на лимите — «остановлена · продолжит в HH:MM». Выбери раннер — справа его детали, вопросы, действия и <b>живой терминал</b>: экран агента в реальном времени с историей (прокрутка), размер шрифта A−/A+ и режим во весь экран. Кнопка «Ввод» позволяет печатать агенту прямо в терминал (вставка многострочного текста уходит одной вставкой, для телефона есть Esc, Tab, стрелки, Enter, Ctrl-C); ввод сбрасывает счётчик автопродолжений и отмечается в событиях раннера. Тот же терминал — на странице стори у работающего раннера. Терминал доступен владельцу и участникам проекта.</li>
<li><b>Новый терминал</b> — раннер без стори: в «Раннерах» или на вкладке «Сессии» проекта выбери проект, имя, агента и напиши промпт (можно голосом — кнопка «Голосом» в браузерах с распознаванием речи). После ходов такой раннер не пингует — им управляешь ты в терминале. Получилась работа — «Оформить стори» в карточке раннера: стори создаётся в работе, раннер ведёт её дальше. Раннер можно переименовать.</li>
<li><b>Раннер</b> — агент, запущенный по стори в tmux на машине Пеппы. Все раннеры ваших и общих проектов — в разделе <Link href="/runners">Раннеры</Link>: статус, стори, команда <code>tmux attach</code>, сообщение, остановка и resume; фильтры-счётчики «ждут вас / работают / упали / готово» и поиск; строки, где нужны вы, подсвечены, у раннера на лимите — «остановлена · продолжит в HH:MM». Выбери раннер — справа его детали, вопросы, действия и <b>живой терминал</b>: экран агента в реальном времени с историей (прокрутка), размер шрифта A−/A+ и режим во весь экран. Кнопка «Ввод» позволяет печатать агенту прямо в терминал (вставка многострочного текста уходит одной вставкой, для телефона есть Esc, Tab, стрелки, Enter, Ctrl-C); ввод сбрасывает счётчик автопродолжений и отмечается в событиях раннера. Тот же терминал — на странице стори у работающего раннера. Терминал доступен владельцу и участникам проекта.</li>
<li><b>Новый терминал</b> — раннер без стори: в «Раннерах» или на вкладке «Сессии» проекта выберите проект, имя, агента и напишите промпт (можно голосом — кнопка «Голосом» в браузерах с распознаванием речи). После ходов такой раннер не пингует — им управляете вы в терминале. Получилась работа — «Оформить стори» в карточке раннера: стори создаётся в работе, раннер ведёт её дальше. Раннер можно переименовать.</li>
<li><b>Раннеры и стори</b> — «⋯ Настройки проекта → Раннеры» (и на странице стори — для неё одной): «один раннер на стори» (по умолчанию) или «раннер ведёт очередь стори» — стори достаётся свободному раннеру, при лимите раннеров проекта ждёт в его очереди, а «Принять» не останавливает раннер, а даёт ему следующую стори; переход — «свежий контекст» (тот же терминал, новый разговор) или «один разговор». «Свой git worktree на раннер» — у каждого раннера своя копия и ветка <code>task/…</code>, параллельные стори не мешают друг другу; копия убирается, когда всё запушено. В карточке раннера — история его стори и очередь.</li>
<li><b>Изоляция и хосты</b> — там же: «Контейнер на раннер» запускает агента в docker-образе раннера — он видит только свою рабочую копию, работает на подписке из пула проекта и не видит токенов Пеппы и чужих проектов; хуки, MCP и git идут в Пеппу через релей и только к репозиторию проекта (PR агент открывает инструментом <code>open_pull_request</code>). «Где запускать раннеры» — Mac Пеппы или отмеченные хосты: раннер уходит на наименее занятый онлайн-хост, там клонируется рабочая копия, а терминал, ввод и ответы работают как обычно. Хосты подключает суперадмин в разделе «Хосты» (SSH-ключ Пеппы на хосте, tmux и docker); недоступный хост помечается «офлайн», его раннеры не считаются упавшими.</li>
<li><b>Главная</b> — вопросы агентов (только архитектурные стопперы) и «готово к ревью», активные раннеры и проекты. Отвечать можно в вебе, Telegram или через MCP. Список проектов и «Новый проект» — в разделе <Link href="/projects">Проекты</Link>.</li>

View File

@ -3,6 +3,7 @@ import { accountUsageForUser, getNotifyPrefs, isSuperadmin } from "@peppa/core";
import { db } from "@/lib/db";
import { requireUser, uiMode } from "@/lib/auth";
import { navCounts } from "@/lib/queries";
import { WordsProvider } from "@/components/Words";
import { Sidebar } from "@/components/Sidebar";
import { AttentionBadge } from "@/components/AttentionBadge";
import { CommandPalette } from "@/components/CommandPalette";
@ -18,10 +19,12 @@ export default async function AppLayout({ children }: { children: ReactNode }) {
const counts = await navCounts(user.id);
const { sound } = await getNotifyPrefs(db, user.id);
const superadmin = await isSuperadmin(db, user);
const engineer = (await uiMode()) === "engineer";
const mode = await uiMode();
const engineer = mode === "engineer";
// PEP-5: subscription limit windows over every page.
const accounts = await accountUsageForUser(db, user).catch(() => []);
return (
<WordsProvider mode={mode}>
<div className="min-h-dvh md:grid md:grid-cols-[232px_minmax(0,1fr)]">
<AttentionBadge count={counts.questions + counts.waitingRunners} sound={sound} />
<Sidebar login={user.login} avatarUrl={user.avatarUrl} counts={counts} superadmin={superadmin} engineer={engineer} />
@ -32,5 +35,6 @@ export default async function AppLayout({ children }: { children: ReactNode }) {
</div>
<CommandPalette />
</div>
</WordsProvider>
);
}

View File

@ -21,7 +21,7 @@ import { ProjectSecretsPanel } from "@/components/ProjectSecrets";
import { Workspace } from "@/components/Workspace";
import { SubscriptionSetup } from "@/components/SubscriptionSetup";
import { PoolSubscriptions, PoolSummary } from "@/components/PoolSubscriptions";
import { requireUser, uiMode } from "@/lib/auth";
import { requireUser, words } from "@/lib/auth";
import { cn } from "@/lib/utils";
import { db } from "@/lib/db";
import { board, projectForUserByKey, projectSessions } from "@/lib/queries";
@ -78,7 +78,8 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
const { key } = await params;
const { error, created, tab: tabParam, epic: epicParam, weeks, actor, channel, edit, saved } = await searchParams;
// PEP-119: «Продакт» sees the board, epics and bugs; the developer's tabs belong to «Инженер».
const engineer = (await uiMode()) === "engineer";
const w = await words();
const engineer = w.engineer;
const visibleTabs = engineer ? TABS : TABS.filter((t) => (PRODUCT_PROJECT_TABS as readonly string[]).includes(t.id));
const tab = visibleTabs.find((t) => t.id === tabParam)?.id ?? "board";
const p = await projectForUserByKey(user.id, key).catch(() => null);
@ -162,6 +163,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
const aside = (
<div className="flex flex-col gap-6">
{engineer && (
<PanelSection title="Репозиторий">
<dl className="m-0 grid grid-cols-[max-content_minmax(0,1fr)] gap-x-3 gap-y-1.5 text-sm">
<dt className="text-muted-foreground">Где</dt>
@ -199,37 +201,46 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
</p>
)}
</PanelSection>
)}
<PanelSection title="Автономность">
<AutonomyPanel projectId={p.id} settings={autonomy} back={back} />
<AutonomyPanel projectId={p.id} settings={autonomy} back={back} engineer={engineer} />
</PanelSection>
{engineer && (
<PanelSection title="Раннеры">
<RunnerSettingsPanel projectId={p.id} own={runnerOwn} inherited={{ ...DEFAULT_RUNNER_SETTINGS, ...runnerSystem }} back={back} hosts={runnerHosts} />
</PanelSection>
)}
{engineer && (
<PanelSection title="Модель агента">
<AgentModelPanel projectId={p.id} own={agentOwn} inherited={{ ...DEFAULT_AGENT_SETTINGS, ...agentSystem }} back={back} />
</PanelSection>
)}
<PanelSection title="Эпики" count={epics.length}>
<EpicsPanel projectId={p.id} projectKey={p.key} epics={epics} progress={progress} back={back} />
<EpicsPanel w={w} projectId={p.id} projectKey={p.key} epics={epics} progress={progress} back={back} />
</PanelSection>
{engineer && (
<PanelSection title="Секреты" count={secrets.length}>
<ProjectSecretsPanel projectId={p.id} secrets={secrets} back={back} />
</PanelSection>
)}
{engineer && (
<PanelSection title="Бюджет стори">
<ProjectBudgetPanel projectId={p.id} budget={projectBudget} back={back} action={saveProjectBudgetAction} />
</PanelSection>
)}
<PanelSection title="Продакт и аналитик">
<form action={saveIntakeSettingsAction} className="flex flex-col gap-2.5">
<Hidden fields={{ projectId: p.id, back }} />
<label className="flex items-center gap-2 text-sm">
<input type="checkbox" name="enabled" defaultChecked={intake.enabled} className="size-4 accent-primary" />
Новые стори сначала уточняют продакт и аналитик
Новые {w.task("accPl")} сначала уточняют продакт и аналитик
</label>
<label className="flex items-center gap-2 text-sm">
Ждать ответа на вопросы, минут
@ -238,11 +249,12 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
<Button size="sm" className="self-start">Сохранить</Button>
</form>
<p className="m-0 text-xs text-muted-foreground">
Продакт решает, зачем это и что берём в первую версию; аналитик пишет критерии приёмки и задаёт до трёх вопросов. Не ответили вовремя — идёт по вариантам по умолчанию (ночью ждёт до утра). Стори, созданные
Продакт решает, зачем это и что берём в первую версию; аналитик пишет критерии приёмки и задаёт до трёх вопросов. Не ответили вовремя — идёт по вариантам по умолчанию (ночью ждёт до утра). {w.Task("pl")}, созданные
до включения, не трогает.
</p>
</PanelSection>
{engineer && (
<PanelSection title="Ревьюер">
<form action={saveReviewSettingsAction} className="flex flex-col gap-2.5">
<Hidden fields={{ projectId: p.id, back }} />
@ -267,9 +279,11 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
Когда проверки PR зелёные и агент отдаёт стори в ревью, короткая сессия Claude (sonnet, на подписке пула проекта) читает дифф по чек-листу. Замечания уходят агенту, «ок» — стори к вам с резюме ревьюера. После лимита возвратов стори приходит к вам с незакрытыми замечаниями.
</p>
</PanelSection>
)}
<PanelSection title="Баги">
<IncidentSettingsPanel
w={w}
projectId={p.id}
back={back}
isOwner={isOwner}
@ -289,7 +303,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
<li key={m.id} className="flex items-center gap-2 rounded-md px-2 py-1.5">
<span className="flex min-w-0 flex-1 flex-col">
<span>{m.login}</span>
<span className="text-xs text-muted-foreground">участник{noRepoAccess(m.login) && " · нет доступа к репозиторию"}</span>
<span className="text-xs text-muted-foreground">участник{engineer && noRepoAccess(m.login) && " · нет доступа к репозиторию"}</span>
</span>
{(isOwner || m.id === user.id) && (
<form action={removeProjectMember}>
@ -303,7 +317,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
<li key={login} className="flex items-center gap-2 rounded-md px-2 py-1.5">
<span className="flex min-w-0 flex-1 flex-col">
<span>{login}</span>
<span className="text-xs text-muted-foreground">приглашён · появится после первого входа в Пеппу</span>
<span className="text-xs text-muted-foreground">приглашён · появится после первого входа в Peppa FACTORY</span>
</span>
{isOwner && (
<form action={removeProjectMember}>
@ -317,17 +331,17 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
{isOwner && (
<form action={addProjectMember} className="flex gap-2">
<Hidden fields={{ projectId: p.id, back }} />
<Input name="login" required placeholder="Логин в Gitea" aria-label="Логин участника в Gitea" className="h-8" />
<Input name="login" required placeholder={engineer ? "Логин в Gitea" : "Логин участника"} aria-label={engineer ? "Логин участника в Gitea" : "Логин участника"} className="h-8" />
<Button size="sm">Добавить участника</Button>
</form>
)}
{isOwner && missingAccess && (
{engineer && isOwner && missingAccess && (
<form action={grantRepoAccessToMembers}>
<Hidden fields={{ projectId: p.id, back }} />
<Button size="sm">Выдать доступ участникам</Button>
</form>
)}
{isOwner && <p className="m-0 text-xs text-muted-foreground">Участник видит доску и входящие, двигает карточки и отвечает агентам; получает доступ на запись к репозиторию.</p>}
{isOwner && <p className="m-0 text-xs text-muted-foreground">Участник видит доску и входящие, двигает карточки и отвечает агентам{engineer ? "; получает доступ на запись к репозиторию" : ""}.</p>}
</PanelSection>
<PanelSection title="Подписки">
@ -338,12 +352,12 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
Агенты работают на <b>подписке Peppa FACTORY</b> — общей для пользователей фабрики. Свою подписку можно подключить в любой момент ниже.
</>
) : (
<>Агенты работают на вашей подписке — пул «{pool.name}».</>
<>Агенты работают на вашей подписке{engineer ? ` — пул «${pool.name}»` : ""}.</>
)
) : agentWarning ? (
<b>Подписка не выбрана — агенты не запустятся.</b>
) : (
"Пул не назначен — агенты работают на входе машины."
engineer ? "Пул не назначен — агенты работают на входе машины." : "Своя подписка не подключена — агенты работают на общей."
)}
</p>
{/* PEP-116: on the factory's subscription a user sees its state, not the accounts behind it. */}
@ -387,6 +401,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
{!superadmin && <span className="text-xs text-muted-foreground">{sharedReq ? "Ждём подтверждения администратора фабрики — придёт сообщение." : "Нужно подтверждение администратора фабрики."}</span>}
</form>
)}
{engineer ? (
<form action={connectOwnSubscriptionAction} className="flex flex-col gap-2">
<Hidden fields={{ projectId: p.id, back }} />
<NativeSelect name="kind" defaultValue="claude_login" aria-label="Что подключить" className="h-8">
@ -403,6 +418,21 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
хранятся зашифрованными, показать их нельзя.
</span>
</form>
) : (
!pool || pool.id === shared?.id ? (
<div className="flex flex-wrap gap-2" aria-label="Подключить свою подписку">
<form action={connectOwnSubscriptionAction}>
<Hidden fields={{ projectId: p.id, kind: "claude_login", back }} />
<Button size="sm" variant={pool ? "outline" : "default"}>Подключить Claude</Button>
</form>
<form action={connectOwnSubscriptionAction}>
<Hidden fields={{ projectId: p.id, kind: "codex_login", back }} />
<Button size="sm" variant="outline">Подключить ChatGPT</Button>
</form>
<span className="basis-full text-xs text-muted-foreground">Подойдёт обычная платная подписка. После нажатия на странице проекта появятся шаги — это одна минута.</span>
</div>
) : null
)}
</>
)}
{superadmin && (
@ -417,16 +447,17 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
<Button size="sm">Сохранить</Button>
</form>
)}
<p className="m-0 text-xs text-muted-foreground">Раннеры проекта стартуют на свободной подписке пула. {superadmin ? <a href="/subscriptions#pools" className="text-primary">Пулы и подписки</a> : "Выбирает владелец проекта."}</p>
{engineer && <p className="m-0 text-xs text-muted-foreground">Раннеры проекта стартуют на свободной подписке пула. {superadmin ? <a href="/subscriptions#pools" className="text-primary">Пулы и подписки</a> : "Выбирает владелец проекта."}</p>}
</PanelSection>
{!engineer && <p className="m-0 text-xs text-muted-foreground">Настройки для разработчиков — код проекта, модель и расход агентов — открываются в виде «Инженер»: <a href="/settings#mode" className="text-primary">Настройки → Вид Peppa FACTORY</a>.</p>}
</div>
);
const newTask = (
<form action={addTask} className="flex flex-col gap-2">
<Hidden fields={{ projectId: p.id, back }} />
<Input name="title" required placeholder="Что сделать" aria-label="Название стори" />
<Textarea name="description" rows={5} placeholder="Описание: кому и зачем, критерии готовности" aria-label="Описание стори" />
<Input name="title" required placeholder="Что сделать" aria-label={`Название ${w.task("gen")}`} />
<Textarea name="description" rows={5} placeholder="Описание: кому и зачем, критерии готовности" aria-label={`Описание ${w.task("gen")}`} />
<NativeSelect name="epicId" defaultValue={epicFilter ? String(epicFilter.id) : ""} aria-label="Эпик">
<option value="">Без эпика</option>
{epics.map((e) => (
@ -435,7 +466,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
</option>
))}
</NativeSelect>
<Button variant="default" size="sm" className="self-start">Создать стори</Button>
<Button variant="default" size="sm" className="self-start">Создать {w.task("acc")}</Button>
</form>
);
const tabCount: Partial<Record<(typeof TABS)[number]["id"], number>> = { board: tasks.length, epics: epics.length, bugs: incidents.length, sessions: sessions.length };
@ -444,7 +475,8 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
<Workspace aside={null} wide>
<LiveRefresh scope={`project:${p.id}`} />
<Flash error={error} />
{created && !error && (
{created && !error && !engineer && <Notice>Проект создан. Напишите первую задачу — кнопка «Задача» справа вверху.</Notice>}
{created && !error && engineer && (
<Notice>
Репозиторий создан: <a href={repo.url} className="text-primary">{repo.fullName}</a> ({repoVisibilityLabel(repo.private)}).
<Button asChild size="xs">
@ -455,7 +487,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
<PageHeader
actions={
<>
<SettingsDialog title="Новая стори" trigger={<><Plus />Стори</>}>
<SettingsDialog title={`Новая ${w.task()}`} trigger={<><Plus />{w.Task()}</>}>
{newTask}
</SettingsDialog>
<SettingsDialog title="Настройки проекта">{aside}</SettingsDialog>
@ -468,7 +500,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
</>
}
>
<a href={repo.url} className="text-primary">{repo.fullName}</a> · {repoVisibilityLabel(repo.private)}
{engineer && <><a href={repo.url} className="text-primary">{repo.fullName}</a> · {repoVisibilityLabel(repo.private)}</>}
</PageHeader>
{mayChoose && (ownLogins.length > 0 || (!pool && agentWarning)) && <SubscriptionSetup projectId={p.id} back={back} logins={ownLogins} shared={!!shared} requested={!!sharedReq} direct={superadmin} />}
@ -509,7 +541,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
<>
{epics.length > 0 && (
<nav aria-label="Фильтр по эпику" className="mb-3 flex flex-wrap items-center gap-1.5 text-sm">
<a href={`/p/${p.key}?tab=epics`} className="text-xs text-muted-foreground" title="Эпик — большая цель; карточки на доске — стори, шаги к ней">Эпики:</a>
<a href={`/p/${p.key}?tab=epics`} className="text-xs text-muted-foreground" title={`Эпик — большая цель; карточки на доске — ${w.task("pl")}, шаги к ней`}>Эпики:</a>
{[{ id: 0, title: "все" }, ...epics].map((e) => {
const active = (epicFilter?.id ?? 0) === e.id;
return (
@ -531,7 +563,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
})}
{epicFilter && (
<a href={`/p/${p.key}/plan/${epicFilter.id}`} className="ml-auto text-xs text-primary">
Спланировать стори эпика →
Спланировать {w.task("accPl")} эпика →
</a>
)}
</nav>
@ -542,6 +574,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
{tab === "epics" && (
<EpicsTab
w={w}
projectId={p.id}
projectKey={p.key}
epics={epics}
@ -616,7 +649,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
)}
{tab === "bugs" && (
<IncidentsSection projectId={p.id} back={back} settings={incidentSettings} incidents={incidents} taskKeys={new Map(tasks.map((t) => [t.id, `${p.key}-${t.number}`]))} />
<IncidentsSection w={w} projectId={p.id} back={back} settings={incidentSettings} incidents={incidents} taskKeys={new Map(tasks.map((t) => [t.id, `${p.key}-${t.number}`]))} />
)}
{tab === "metrics" && metrics && <MetricsTab m={metrics} projectKey={p.key} />}

View File

@ -10,7 +10,7 @@ import { PendingButton } from "@/components/PendingButton";
import { Button } from "@/components/ui/button";
import { Input, Textarea } from "@/components/ui/input";
import { Workspace } from "@/components/Workspace";
import { requireUser } from "@/lib/auth";
import { requireUser, words } from "@/lib/auth";
import { db } from "@/lib/db";
import { projectForUserByKey } from "@/lib/queries";
import { applyPlanAction, discardPlanAction, planEpicAction } from "../../../../board-actions";
@ -19,6 +19,7 @@ export default async function PlanEpicPage({ params, searchParams }: { params: P
const user = await requireUser();
const { key, epic: epicParam } = await params;
const { error } = await searchParams;
const w = await words();
const p = await projectForUserByKey(user.id, key).catch(() => null);
if (!p) notFound();
const epic = await getEpic(db, p.id, Number(epicParam)).catch(() => null);
@ -39,14 +40,14 @@ export default async function PlanEpicPage({ params, searchParams }: { params: P
}
title={<>Спланировать эпик «{epic.title}»</>}
>
Планировщик (короткая сессия Claude на подписке пула проекта) предложит стори с критериями готовности и зависимостями. Ничего не создаётся, пока вы не утвердите план.
Планировщик{w.engineer ? " (короткая сессия Claude на подписке пула проекта)" : ""} предложит {w.task("accPl")} с критериями готовности и порядком. Ничего не создаётся, пока вы не утвердите план.
</PageHeader>
<Section title="Эпик">
<div className="rounded-lg border bg-card p-3 text-sm whitespace-pre-wrap">{epic.description || <span className="text-muted-foreground">Без описания — опишите эпик в «⋯ Настройки проекта → Эпики», так план будет точнее.</span>}</div>
<div className="rounded-lg border bg-card p-3 text-sm whitespace-pre-wrap">{epic.description || <span className="text-muted-foreground">Без описания — опишите эпик в «Настройках проекта → Эпики», так план будет точнее.</span>}</div>
{existing.length > 0 && (
<p className="m-0 text-sm text-muted-foreground">
Уже есть стори: {existing.map((t) => t.key).join(", ")} — планировщик их не повторит и может от них зависеть.
Уже есть {w.task("pl")}: {existing.map((t) => t.key).join(", ")} — планировщик их не повторит и может от них зависеть.
</p>
)}
<form action={planEpicAction} className="flex flex-col gap-2">
@ -59,7 +60,7 @@ export default async function PlanEpicPage({ params, searchParams }: { params: P
</form>
</Section>
<Section title={draft ? `Черновик плана — ${draft.stories.length} стори` : "Черновик плана"}>
<Section title={draft ? `Черновик плана — ${w.tasks(draft.stories.length)}` : "Черновик плана"}>
{!draft ? (
<Empty>Черновика нет. Нажмите «Спланировать».</Empty>
) : (
@ -70,22 +71,22 @@ export default async function PlanEpicPage({ params, searchParams }: { params: P
const n = i + 1;
return (
<fieldset key={n} className="m-0 flex flex-col gap-2 rounded-lg border bg-card p-3">
<legend className="sr-only">Стори {n}</legend>
<legend className="sr-only">{w.Task()} {n}</legend>
<div className="flex items-center gap-2">
<input type="checkbox" name={`keep_${n}`} defaultChecked aria-label={`Создать стори ${n}`} className="size-4 accent-primary" />
<input type="checkbox" name={`keep_${n}`} defaultChecked aria-label={`Создать ${w.task("acc")} ${n}`} className="size-4 accent-primary" />
<span className="font-mono text-xs text-muted-foreground">№{n}</span>
<Input name={`title_${n}`} required minLength={3} defaultValue={s.title} aria-label={`Название стори ${n}`} className="h-8 flex-1" />
<Input name={`title_${n}`} required minLength={3} defaultValue={s.title} aria-label={`Название ${w.task("gen")} ${n}`} className="h-8 flex-1" />
</div>
<Textarea name={`description_${n}`} rows={5} defaultValue={s.description} aria-label={`Описание стори ${n}`} />
<Textarea name={`description_${n}`} rows={5} defaultValue={s.description} aria-label={`Описание ${w.task("gen")} ${n}`} />
<label className="flex items-center gap-2 text-sm">
<span className="text-muted-foreground whitespace-nowrap">Ждёт</span>
<Input name={`deps_${n}`} defaultValue={s.dependsOn.join(", ")} placeholder={`номера плана или ключи: 1, ${p.key}-3`} aria-label={`Зависимости стори ${n}`} className="h-8" />
<Input name={`deps_${n}`} defaultValue={s.dependsOn.join(", ")} placeholder={`номера плана или ключи: 1, ${p.key}-3`} aria-label={`Зависимости ${w.task("gen")} ${n}`} className="h-8" />
</label>
</fieldset>
);
})}
<p className="m-0 text-xs text-muted-foreground">Снимите галочку, чтобы не создавать стори. Стори встанут в конец бэклога в этом порядке; зависимые диспетчер не возьмёт, пока предшественники не в ревью или готово.</p>
<Button variant="default" className="self-start">Создать стори</Button>
<p className="m-0 text-xs text-muted-foreground">Снимите галочку, чтобы не создавать {w.task("acc")}. {w.Task("pl")} встанут в конец бэклога в этом порядке; {w.engineer ? "зависимые диспетчер не возьмёт, пока предшественники не в ревью или готово" : "зависимую задачу агенты возьмут, когда будут готовы те, которых она ждёт"}.</p>
<Button variant="default" className="self-start">Создать {w.task("accPl")}</Button>
</form>
<form action={discardPlanAction}>
<Hidden fields={{ projectId: p.id, epicId: epic.id, back }} />

View File

@ -1,4 +1,5 @@
// Project page tabs «Код», «Спеки», «PR» and the epics block of «⋯ Настройки проекта» (PEP-66).
import type { Words } from "@peppa/shared/wording";
import { Archive, ExternalLink, GitBranch, GitPullRequest, Pencil } from "lucide-react";
import type { Epic, SpecSummary } from "@peppa/core";
import { Markdown } from "@/components/Markdown";
@ -187,10 +188,10 @@ export function ProgressBar({ done, total, className }: { done: number; total: n
);
}
export function EpicsPanel({ projectId, projectKey, epics, progress, back }: { projectId: number; projectKey: string; epics: Epic[]; progress: Map<number, { done: number; total: number }>; back: string }) {
export function EpicsPanel({ projectId, projectKey, epics, progress, back, w }: { w: Words; projectId: number; projectKey: string; epics: Epic[]; progress: Map<number, { done: number; total: number }>; back: string }) {
return (
<div className="flex flex-col gap-2 text-sm">
{epics.length === 0 && <p className="m-0 text-muted-foreground">Эпиков нет. Эпик — метка, которая группирует стори; его описание агент получает вместе со стори.</p>}
{epics.length === 0 && <p className="m-0 text-muted-foreground">Эпиков нет. Эпик — большая цель, которая объединяет {w.task("accPl")}; его описание агент получает вместе с {w.task("ins")}.</p>}
{epics.map((e) => (
<details key={e.id} className="group rounded-md border bg-card">
<summary className="flex cursor-pointer list-none items-center gap-2 px-3 py-2 select-none [&::-webkit-details-marker]:hidden">
@ -198,7 +199,7 @@ export function EpicsPanel({ projectId, projectKey, epics, progress, back }: { p
<span className="min-w-0 flex-1 truncate">{e.title}</span>
<ProgressBar done={progress.get(e.id)?.done ?? 0} total={progress.get(e.id)?.total ?? 0} />
<span className="font-mono text-[11px] text-muted-foreground tabular-nums">{progress.get(e.id)?.done ?? 0}/{progress.get(e.id)?.total ?? 0}</span>
<span className="font-mono text-[11px] text-muted-foreground">#{e.id}</span>
{w.engineer && <span className="font-mono text-[11px] text-muted-foreground">#{e.id}</span>}
</summary>
<div className="flex flex-col gap-2 border-t px-3 py-2.5">
<form action={editEpic} className="flex flex-col gap-2">
@ -209,7 +210,7 @@ export function EpicsPanel({ projectId, projectKey, epics, progress, back }: { p
</form>
<div className="flex flex-wrap gap-2">
<Button asChild size="xs" variant="outline">
<a href={`/p/${projectKey}/plan/${e.id}`}>Спланировать стори</a>
<a href={`/p/${projectKey}/plan/${e.id}`}>Спланировать {w.task("accPl")}</a>
</Button>
<form action={editEpic}>
<Hidden fields={{ projectId, epicId: e.id, back, archive: "1" }} />
@ -321,7 +322,7 @@ interface EpicStory {
}
/** PEP-81: epics in plain sight — each epic (a big goal) with its stories (the steps agents do). */
export function EpicsTab({ projectId, projectKey, epics, stories, progress, back }: { projectId: number; projectKey: string; epics: Epic[]; stories: EpicStory[]; progress: Map<number, { done: number; total: number }>; back: string }) {
export function EpicsTab({ projectId, projectKey, epics, stories, progress, back, w }: { w: Words; projectId: number; projectKey: string; epics: Epic[]; stories: EpicStory[]; progress: Map<number, { done: number; total: number }>; back: string }) {
const loose = stories.filter((s) => !s.goalId || !epics.some((e) => e.id === s.goalId));
const list = (items: EpicStory[]) =>
items.length ? (
@ -335,13 +336,13 @@ export function EpicsTab({ projectId, projectKey, epics, stories, progress, back
))}
</ul>
) : (
<p className="m-0 text-sm text-muted-foreground">Стори пока нет.</p>
<p className="m-0 text-sm text-muted-foreground">{w.Task("genPl")} пока нет.</p>
);
return (
<Section title="Эпики" count={epics.length}>
<p className="m-0 text-sm text-muted-foreground">
<b className="text-foreground">Эпик</b> — большая цель, например «Оплата» или «Личный кабинет». <b className="text-foreground">Стори</b> — один конкретный шаг к ней: её делает агент, она — карточка на
доске. У стори может быть один эпик; его описание агент получает вместе со стори.
<b className="text-foreground">Эпик</b> — большая цель, например «Оплата» или «Личный кабинет». <b className="text-foreground">{w.Task()}</b> — один конкретный шаг к ней: её делает агент, она — карточка на
доске. У {w.task("gen")} может быть один эпик; его описание агент получает вместе с {w.task("ins")}.
</p>
<form action={addEpic} className="flex flex-wrap items-end gap-2 rounded-lg border bg-card px-4 py-3">
<Hidden fields={{ projectId, back }} />
@ -368,7 +369,7 @@ export function EpicsTab({ projectId, projectKey, epics, stories, progress, back
<a href={`/p/${projectKey}?epic=${e.id}`}>На доске</a>
</Button>
<Button asChild size="xs" variant="outline">
<a href={`/p/${projectKey}/plan/${e.id}`}>Спланировать стори</a>
<a href={`/p/${projectKey}/plan/${e.id}`}>Спланировать {w.task("accPl")}</a>
</Button>
</div>
</article>
@ -377,13 +378,13 @@ export function EpicsTab({ projectId, projectKey, epics, stories, progress, back
{loose.length > 0 && (
<article className="flex flex-col gap-2.5 rounded-lg border border-dashed px-4 py-3">
<header className="flex items-center gap-2">
<h3 className="m-0 text-base font-medium text-muted-foreground">Стори без эпика</h3>
<h3 className="m-0 text-base font-medium text-muted-foreground">{w.Task("pl")} без эпика</h3>
<span className="text-xs text-muted-foreground">{loose.length}</span>
</header>
{list(loose)}
</article>
)}
<p className="m-0 text-xs text-muted-foreground">Переименовать эпик, изменить описание или убрать в архив — «⋯ Настройки проекта → Эпики». Эпик стори меняется кнопкой «Изменить» на её странице.</p>
<p className="m-0 text-xs text-muted-foreground">Переименовать эпик, изменить описание или убрать в архив — «Настройки проекта → Эпики». Эпик {w.task("gen")} меняется кнопкой «Изменить» на её странице.</p>
</Section>
);
}

View File

@ -8,20 +8,21 @@ import { ActivityAside } from "@/components/ActivityAside";
import { AgentAtWork, ProjectList, QuestionCard } from "@/components/cards";
import { Empty, Flash, MoreLink, PageHeader, Section } from "@/components/common";
import { Workspace } from "@/components/Workspace";
import { requireUser } from "@/lib/auth";
import { requireUser, words } from "@/lib/auth";
import { db } from "@/lib/db";
import { activeSessions, inbox } from "@/lib/queries";
export default async function Home({ searchParams }: { searchParams: Promise<{ error?: string }> }) {
const user = await requireUser();
const { error } = await searchParams;
const w = await words();
if (await claimWelcome(db, user.id)) redirect("/welcome");
const [items, sessions, projects, onboarding, progress] = await Promise.all([inbox(user.id), activeSessions(user.id), listUserProjects(db, user.id), onboardingChecklist(db, user), progressOverview(db, user.id)]);
return (
<Workspace aside={<ActivityAside questions={false} />}>
<LiveRefresh scope="home" />
<Flash error={error} />
<PageHeader title="Главная">{items.length ? "Агенты ждут твоего решения — ответь здесь, в Telegram или через MCP." : "Всё идёт само: агентам от тебя ничего не нужно."}</PageHeader>
<PageHeader title="Главная">{items.length ? `Агенты ждут вашего решения — ответьте здесь${w.engineer ? ", в Telegram или через MCP" : " или в Telegram"}.` : "Всё идёт само: агентам от вас ничего не нужно."}</PageHeader>
{onboarding.visible && <OnboardingChecklist data={onboarding} botUsername={user.telegramBotUsername} />}
<Section title="Вопросы агентов" count={items.length}>
<PugBanner count={items.length} />
@ -30,11 +31,11 @@ export default async function Home({ searchParams }: { searchParams: Promise<{ e
<Section title="Прогресс">
<ProgressOverview data={progress} />
</Section>
<Section title="Агенты за работой" count={sessions.length} actions={<MoreLink href="/runners">вся работа агентов</MoreLink>}>
{sessions.length === 0 ? <Empty>Сейчас никто не работает: напишите задачу — и агент возьмёт её.</Empty> : sessions.map((s) => <AgentAtWork key={s.id} s={s} back="/" />)}
<Section title="Агенты за работой" count={sessions.length} actions={w.engineer ? <MoreLink href="/runners">вся работа агентов</MoreLink> : undefined}>
{sessions.length === 0 ? <Empty>Сейчас никто не работает: напишите задачу — и агент возьмёт её.</Empty> : sessions.map((s) => <AgentAtWork key={s.id} s={s} back="/" engineer={w.engineer} />)}
</Section>
<Section title="Мои проекты" actions={<MoreLink href="/projects">все проекты</MoreLink>}>
<ProjectList projects={projects} userId={user.id} />
<ProjectList projects={projects} userId={user.id} engineer={w.engineer} />
</Section>
</Workspace>
);

View File

@ -6,7 +6,7 @@ import { Button } from "@/components/ui/button";
import { Label, NativeSelect } from "@/components/ui/input";
import { ProjectBasics } from "@/components/ProjectBasics";
import { Workspace } from "@/components/Workspace";
import { requireUser } from "@/lib/auth";
import { requireUser, words } from "@/lib/auth";
import { db } from "@/lib/db";
import { createProjectAction } from "../../actions";
@ -22,6 +22,7 @@ function Choice({ name, value, checked, children }: { name: string; value: strin
export default async function NewProject({ searchParams }: { searchParams: Promise<{ error?: string }> }) {
const user = await requireUser();
const { error } = await searchParams;
const w = await words();
let orgs: GiteaOrg[] = [];
let giteaError: string | undefined;
const giteaUrl = loadEnv().GITEA_URL.replace(/^https?:\/\//, "");
@ -45,11 +46,11 @@ export default async function NewProject({ searchParams }: { searchParams: Promi
<ProjectBasics>
{local ? (
<p className="m-0 text-sm text-muted-foreground">
Код хранится на фабрике: <span className="font-mono">{giteaUrl}/{botLogin}/…</span>. Работать с ним вам не нужно — это делают агенты.
Код хранится в Peppa FACTORY{w.engineer && <>: <span className="font-mono">{giteaUrl}/{botLogin}/…</span></>}. Работать с ним вам не нужно — это делают агенты.
</p>
) : (
<Label>
Где хранить код (Gitea)
{w.engineer ? "Где хранить код (Gitea)" : "Где хранить код"}
<NativeSelect name="owner" defaultValue={user.login}>
<option value={user.login}>{user.login} — личное пространство</option>
{orgs.map((o) => (
@ -63,13 +64,16 @@ export default async function NewProject({ searchParams }: { searchParams: Promi
<Choice name="visibility" value="public" checked>Открытый — другие пользователи фабрики тоже могут его посмотреть</Choice>
<Choice name="visibility" value="private">Закрытый — только вы и участники проекта</Choice>
</fieldset>
{w.product && <input type="hidden" name="mode" value="new" />}
{w.engineer && (
<fieldset className="m-0 flex flex-col gap-2 border-0 p-0">
<legend className="mb-2 text-sm font-medium">Код продукта</legend>
<Choice name="mode" value="new" checked>Начать с нуля — агенты напишут код сами</Choice>
<Choice name="mode" value="existing">У меня уже есть код в Gitea — подключить его (адрес кода = имя репозитория)</Choice>
</fieldset>
)}
</ProjectBasics>
<p className="m-0 text-sm text-muted-foreground">Фабрика заведёт хранилище кода и подготовит его для агентов — это займёт до 15 секунд.</p>
<p className="m-0 text-sm text-muted-foreground">Peppa FACTORY подготовит всё для агентов — это займёт до 15 секунд.</p>
<Button variant="default" className="self-start">Создать проект</Button>
</form>
</div>

View File

@ -5,11 +5,12 @@ import { ProjectList } from "@/components/cards";
import { Flash, PageHeader, Section } from "@/components/common";
import { Button } from "@/components/ui/button";
import { Workspace } from "@/components/Workspace";
import { requireUser } from "@/lib/auth";
import { requireUser, words } from "@/lib/auth";
import { db } from "@/lib/db";
export default async function Projects({ searchParams }: { searchParams: Promise<{ error?: string }> }) {
const user = await requireUser();
const w = await words();
const { error } = await searchParams;
const [projects, others] = await Promise.all([listUserProjects(db, user.id), listOtherProjects(db, user.id)]);
return (
@ -26,13 +27,13 @@ export default async function Projects({ searchParams }: { searchParams: Promise
</Button>
}
>
Свои и общие проекты: доска стори, код, PR, релизы, ошибки из прода, участники.
{w.engineer ? "Свои и общие проекты: доска стори, код, PR, релизы, ошибки из прода, участники." : "Ваши проекты и те, куда вас пригласили. Откройте проект, чтобы поставить задачу или посмотреть результат."}
</PageHeader>
<ProjectList projects={projects} userId={user.id} />
<ProjectList projects={projects} userId={user.id} engineer={w.engineer} />
{others.length > 0 && (
<Section title="Проекты других" count={others.length}>
<p className="m-0 text-sm text-muted-foreground">Видны вам как суперадмину. Вопросы агентов и уведомления этих проектов к вам не приходят.</p>
<ProjectList projects={others} userId={user.id} />
<ProjectList projects={others} userId={user.id} engineer={w.engineer} />
</Section>
)}
</Workspace>

View File

@ -15,7 +15,7 @@ import { cn } from "@/lib/utils";
const FILTERS: Array<{ key: RunnerFilter | undefined; label: string }> = [
{ key: undefined, label: "все" },
{ key: "waiting", label: "ждут тебя" },
{ key: "waiting", label: "ждут вас" },
{ key: "working", label: "работают" },
{ key: "stopped", label: "упали" },
{ key: "finished", label: "готово" },
@ -71,7 +71,7 @@ export default async function Runners({ searchParams }: { searchParams: Promise<
)
}
>
Агенты в tmux по стори твоих и общих проектов и свободные терминалы: кто ждёт тебя, кто работает, что готово.
Агенты в tmux по стори ваших и общих проектов и свободные терминалы: кто ждёт вас, кто работает, что готово.
</PageHeader>
<div className="mb-3 flex flex-col gap-3 lg:flex-row lg:items-center">
<nav className="flex flex-wrap gap-1.5" aria-label="Фильтр раннеров">
@ -101,7 +101,7 @@ export default async function Runners({ searchParams }: { searchParams: Promise<
</form>
</div>
{shown.length === 0 ? (
<Empty>{q || filter ? "Таких раннеров нет." : "Раннеров пока не было: перенеси стори в «В работе» на доске проекта."}</Empty>
<Empty>{q || filter ? "Таких раннеров нет." : "Раннеров пока не было: перенесите стори в «В работе» на доске проекта."}</Empty>
) : (
<ul className="m-0 flex list-none flex-col gap-1 rounded-lg border bg-card/50 p-1.5">
{shown.map((s) => (

View File

@ -8,7 +8,7 @@ import { GoogleSignIn } from "@/components/GoogleSignIn";
import { EgovSign } from "@/components/EgovSign";
import { OwnBotSteps } from "@/components/OwnBotSteps";
import { Workspace } from "@/components/Workspace";
import { publicOrigin, requireUser, uiMode } from "@/lib/auth";
import { publicOrigin, requireUser, uiMode, words } from "@/lib/auth";
import { db } from "@/lib/db";
import { unlinkGoogleAction, disconnectOwnBotAction, revokeConnectedApp, saveNotifyPrefsAction, setUiModeAction, unpairTelegramAction } from "../actions";
import { PushNotifications } from "@/components/PushNotifications";
@ -33,6 +33,7 @@ export default async function Settings({ searchParams }: { searchParams: Promise
const user = await requireUser();
const { error, egov, google, notify, bot, mode: modeSaved } = await searchParams;
const mode = await uiMode();
const w = await words();
const hasBot = !!user.telegramBotUsername;
const local = isLocalUser(user);
const superadmin = await isSuperadmin(db, user);
@ -72,7 +73,7 @@ export default async function Settings({ searchParams }: { searchParams: Promise
<Card>
<p className="m-0 text-sm">
Логин <span className="font-mono">{user.login}</span>
{user.name ? <> · {user.name}</> : null}. Вход в Пеппу — через eGov QR или Google
{user.name ? <> · {user.name}</> : null}. Вход в Peppa FACTORY — через eGov QR или Google
{user.egovIin ? (
<>
, ИИН <span className="font-mono">{maskIin(user.egovIin)}</span>.
@ -81,9 +82,9 @@ export default async function Settings({ searchParams }: { searchParams: Promise
<>. <b>ИИН ещё не привязан</b>{user.googleSub ? "." : " — привяжите его ниже или Google, иначе после выхода вы не сможете войти."}</>
)}
</p>
{local && (
{local && w.engineer && (
<p className="m-0 text-sm text-muted-foreground">
Аккаунта Gitea нет: код проектов — через Пеппу (агенты, PR, проверки), новые проекты создаются в пространстве <span className="font-mono">peppa-bot</span>.
Аккаунта Gitea нет: код проектов — через Peppa FACTORY (агенты, PR, проверки), новые проекты создаются в пространстве <span className="font-mono">peppa-bot</span>.
</p>
)}
</Card>
@ -117,16 +118,18 @@ export default async function Settings({ searchParams }: { searchParams: Promise
</Row>
)}
</Section>
{w.engineer && (
<Section title="Агенты">
<p className="m-0 text-sm text-muted-foreground">
Подписки Claude Code, Codex и OpenCode, на которых работают агенты, ведёт суперадмин в разделе «Подписки»; проект запускает раннеры на своём пуле подписок.
</p>
</Section>
)}
{!user.egovIin && (
<Section title="eGov" id="egov">
{egov === "linked" && <Notice>eGov привязан — теперь можно входить по QR</Notice>}
<Card>
<p className="m-0 text-sm">Привяжите свой ИИН: отсканируйте QR в eGov Mobile и подпишите. Вход в Пеппу — только через eGov.</p>
<p className="m-0 text-sm">Привяжите свой ИИН: отсканируйте QR в eGov Mobile и подпишите. Вход в Peppa FACTORY — только через eGov.</p>
<div className="max-w-xs">
<EgovSign purpose="link" label="Привязать eGov" />
</div>
@ -173,7 +176,7 @@ export default async function Settings({ searchParams }: { searchParams: Promise
</form>
}
>
Вопросы агентов и «готово к ревью» приходят вам {user.telegramBotUsername ? <>от вашего бота <span className="font-mono">@{user.telegramBotUsername}</span></> : "от общего бота Пеппы"}. Новую задачу можно просто написать боту.
Вопросы агентов и «готово к ревью» приходят вам {user.telegramBotUsername ? <>от вашего бота <span className="font-mono">@{user.telegramBotUsername}</span></> : "от общего бота Peppa FACTORY"}. Новую задачу можно просто написать боту.
</Row>
) : (
ownBotSteps
@ -181,7 +184,7 @@ export default async function Settings({ searchParams }: { searchParams: Promise
{/* PEP-100: every user has their own bot — someone still on the shared one is asked to switch. */}
{user.telegramChatId && !hasBot && (
<>
<Notice>Сейчас сообщения приходят от общего бота Пеппы. Подключите своего бота — так у каждого пользователя свой канал с фабрикой.</Notice>
<Notice>Сейчас сообщения приходят от общего бота Peppa FACTORY. Подключите своего бота — так у вас будет свой канал для задач и ответов.</Notice>
{ownBotSteps}
</>
)}
@ -198,7 +201,7 @@ export default async function Settings({ searchParams }: { searchParams: Promise
<div className="flex flex-col gap-1">
<div className="font-medium">Браузер</div>
<p className="m-0 text-sm text-muted-foreground">
Push приходят и при закрытой вкладке; клик открывает стори или проект. Подписано браузеров: {pushSubs.length}. Пеппу можно установить как приложение (Chrome → «Установить»).
Push приходят и при закрытой вкладке; клик открывает {w.task("acc")} или проект. Подписано браузеров: {pushSubs.length}. Peppa FACTORY можно установить как приложение (Chrome → «Установить»).
</p>
</div>
<PushNotifications vapidKey={vapid} known={pushSubs.map((s) => s.endpoint)} />
@ -286,8 +289,8 @@ export default async function Settings({ searchParams }: { searchParams: Promise
<Button variant="default" className="self-start">Сохранить уведомления</Button>
</form>
</Section>
<Section title="MCP для ChatGPT и других клиентов">
<p className="m-0 text-sm">Адрес сервера — подключите его как MCP-коннектор с авторизацией OAuth. Клиент зарегистрируется сам, вы подтвердите доступ на экране Пеппы.</p>
<Section title={w.engineer ? "MCP для ChatGPT и других клиентов" : "Peppa FACTORY в вашем Claude или ChatGPT"}>
<p className="m-0 text-sm">{w.engineer ? "Адрес сервера — подключите его как MCP-коннектор с авторизацией OAuth. Клиент зарегистрируется сам, вы подтвердите доступ на экране Peppa FACTORY." : "Подключите Peppa FACTORY к своему чату — и ставьте задачи и отвечайте агентам прямо из него. Понадобится этот адрес; доступ вы подтвердите на экране Peppa FACTORY."}</p>
<code className="block overflow-x-auto rounded-md border bg-muted px-3 py-2 font-mono text-sm">{origin}/mcp</code>
<p className="m-0 text-sm text-muted-foreground">
Как подключить и что спрашивать — в <a href="/help" className="text-primary">Помощи</a>.

View File

@ -8,7 +8,7 @@ import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { Input, Label, Textarea } from "@/components/ui/input";
import { Workspace } from "@/components/Workspace";
import { requireUser } from "@/lib/auth";
import { requireUser, words } from "@/lib/auth";
import { db } from "@/lib/db";
import { addAgentAction, saveAgentAction, toggleAgentAction } from "./actions";
@ -18,6 +18,7 @@ export const metadata = { title: "Команда — Peppa FACTORY" };
export default async function Team({ searchParams }: { searchParams: Promise<{ error?: string; saved?: string }> }) {
const user = await requireUser();
const { error, saved } = await searchParams;
const w = await words();
const [team, admin] = await Promise.all([listAgents(db), isSuperadmin(db, user)]);
return (
<Workspace>
@ -25,8 +26,8 @@ export default async function Team({ searchParams }: { searchParams: Promise<{ e
<Flash error={error} />
{saved && <Notice>Сохранено — агент получит новый характер при следующем запуске или перезапуске.</Notice>}
<PageHeader title="Команда">
Это ИИ-агенты, не люди: у каждого своя кличка и характер, одна команда на все проекты. Свободный агент берёт стори и ведёт её до конца; если все заняты — в
команде появляется новый. Характер добавляется к промпту агента поверх правил Пеппы и AGENTS.md проекта.
Это ИИ-агенты, не люди: у каждого своя кличка и характер, одна команда на все проекты. Свободный агент берёт {w.task("acc")} и ведёт её до конца; если все заняты — в
команде появляется новый.{w.engineer ? " Характер добавляется к промпту агента поверх правил Peppa FACTORY и AGENTS.md проекта." : " Характер влияет на то, как агент работает и пишет вам."}
</PageHeader>
{admin && (
@ -34,7 +35,7 @@ export default async function Team({ searchParams }: { searchParams: Promise<{ e
<form action={addAgentAction} className="flex flex-wrap items-end gap-2">
<Label className="min-w-48 flex-1">
Новый агент
<Input name="name" placeholder="Кличка — или пусто: Пеппа выберет сама" maxLength={40} autoComplete="off" />
<Input name="name" placeholder="Кличка — или пусто: выберем сами" maxLength={40} autoComplete="off" />
</Label>
<Button variant="default">
<Plus /> Добавить
@ -44,7 +45,7 @@ export default async function Team({ searchParams }: { searchParams: Promise<{ e
)}
<Section title="Агенты" count={team.length}>
{team.length === 0 && <Empty>Пока никого: первый агент появится, когда стори уйдёт «В работу».</Empty>}
{team.length === 0 && <Empty>Пока никого: первый агент появится, когда {w.task()} уйдёт «В работу».</Empty>}
{team.map((a) => (
<Card key={a.id} id={`agent-${a.id}`} className="gap-3" data-agent={a.name}>
<div className="flex flex-wrap items-center gap-2">
@ -78,7 +79,7 @@ export default async function Team({ searchParams }: { searchParams: Promise<{ e
<input type="hidden" name="id" value={a.id} />
<input type="hidden" name="disabled" value={a.disabledAt ? "0" : "1"} />
<Button size="sm" variant="ghost" className="text-muted-foreground">
{a.disabledAt ? "Вернуть в команду" : "Убрать из команды — новые стори не получит"}
{a.disabledAt ? "Вернуть в команду" : `Убрать из команды — новые ${w.task("accPl")} не получит`}
</Button>
</form>
</>

View File

@ -4,7 +4,8 @@ import { ArrowRight, Check } from "lucide-react";
import { Workspace } from "@/components/Workspace";
import { PageHeader, Section } from "@/components/common";
import { PugMascot } from "@/components/PugMascot";
import { requireUser } from "@/lib/auth";
import { requireUser, words } from "@/lib/auth";
import type { Words } from "@peppa/shared/wording";
const WHY = [
{ title: "Программировать не нужно", text: "Вы пишете, что должно получиться, — как объяснили бы коллеге. Как это сделать, решают агенты." },
@ -12,23 +13,24 @@ const WHY = [
{ title: "Последнее слово за вами", text: "Ничего не считается готовым, пока вы не посмотрели результат и не нажали «Принять»." },
];
const FLOW = [
{ title: "Стори", text: "Одна понятная история: «Страница каталога: фото, цена, кнопка „Купить“». Пишите, зачем это нужно и как понять, что готово.", href: "/projects", cta: "К проектам" },
{ title: "Бэклог → В работе", text: "Когда стори переходит «В работе», её берёт агент: придумывает план, пишет код, проверяет себя и открывает изменение.", href: null, cta: "" },
{ title: "Вопросы агентов", text: "Агент спрашивает только о важном: решения, деньги, доступы. Ответ — на Главной, в Telegram или через MCP.", href: "/", cta: "На Главную" },
{ title: "Ревью → Готово", text: "Придёт «готово к ревью» со ссылкой на стенд. Посмотрите и нажмите «Принять» — или напишите, что поправить, агент доделает.", href: null, cta: "" },
const flow = (w: Words) => [
{ title: w.Task(), text: "Одна понятная история: «Страница каталога: фото, цена, кнопка „Купить“». Пишите, зачем это нужно и как понять, что готово.", href: "/projects", cta: "К проектам" },
{ title: "Бэклог → В работе", text: `Когда ${w.task()} переходит «В работе», её берёт агент: составляет план, пишет код и проверяет себя.`, href: null, cta: "" },
{ title: "Вопросы агентов", text: "Агент спрашивает только о важном: решения, деньги, доступы. Ответьте на Главной или в Telegram.", href: "/", cta: "На Главную" },
{ title: "Ревью → Готово", text: "Придёт сообщение «готово» со ссылкой на версию для проверки. Посмотрите и нажмите «Принять» — или напишите, что поправить, агент доделает.", href: null, cta: "" },
];
const WORDS: Array<[string, string]> = [
["Проект", "ваш продукт: у него свой репозиторий, доска и агенты"],
["Эпик", "метка, которая группирует стори одной большой цели"],
["Стори", "одна задача для агента; одна стори — одно законченное изменение"],
const glossary = (w: Words): Array<[string, string]> => [
["Проект", "ваш продукт: у него своя доска, свой код и свои агенты"],
["Эпик", `большая цель, которая объединяет несколько ${w.task("genPl")}`],
[w.Task(), w.engineer ? "одна задача для агента; одна стори — одно законченное изменение" : "один понятный шаг: агент делает его от начала до конца и показывает результат"],
["Агент", "ИИ-разработчик со своим именем; работает на вашей подписке Claude или ChatGPT"],
["Ревью", "момент, когда агент закончил, а вы решаете: принять или вернуть"],
];
export default async function Welcome() {
await requireUser();
const w = await words();
return (
<Workspace>
<PageHeader title="Добро пожаловать в Peppa FACTORY">Опишите идею словами — команда ИИ-агентов сделает продукт, а вы примете результат.</PageHeader>
@ -43,17 +45,17 @@ export default async function Welcome() {
</div>
<Section title="Зачем это вам">
<ul className="m-0 grid list-none gap-3 p-0 sm:grid-cols-3">
{WHY.map((w) => (
<li key={w.title} className="flex flex-col gap-1.5 rounded-xl border bg-card p-4">
<span className="flex items-center gap-2 font-medium"><Check className="size-4 shrink-0 text-ok" /> {w.title}</span>
<span className="text-sm text-muted-foreground">{w.text}</span>
{WHY.map((y) => (
<li key={y.title} className="flex flex-col gap-1.5 rounded-xl border bg-card p-4">
<span className="flex items-center gap-2 font-medium"><Check className="size-4 shrink-0 text-ok" /> {y.title}</span>
<span className="text-sm text-muted-foreground">{y.text}</span>
</li>
))}
</ul>
</Section>
<Section title="Как тут работать">
<ol className="m-0 flex list-none flex-col gap-2 p-0">
{FLOW.map((s, i) => (
{flow(w).map((s, i) => (
<li key={s.title} className="flex items-start gap-3 rounded-xl border bg-card px-4 py-3">
<span aria-hidden className="mt-0.5 grid size-7 shrink-0 place-items-center rounded-full bg-primary/15 text-sm font-semibold text-primary">{i + 1}</span>
<div className="flex min-w-0 flex-1 flex-col gap-0.5">
@ -69,7 +71,7 @@ export default async function Welcome() {
<div className="grid gap-2 sm:grid-cols-3">
<div className="flex flex-col gap-1 rounded-xl border bg-card px-4 py-3">
<span className="font-medium">Чат с аналитиком</span>
<span className="text-sm text-muted-foreground">ИИ-агент вашего проекта: спросите, что сделано и где это посмотреть, или опишите идею — он поможет сформулировать стори и заведёт их.</span>
<span className="text-sm text-muted-foreground">ИИ-агент вашего проекта: спросите, что сделано и где это посмотреть, или опишите идею — он поможет сформулировать {w.task("accPl")} и заведёт их.</span>
<Link href="/chats" className="mt-1 text-sm">Открыть чаты →</Link>
</div>
<div className="flex flex-col gap-1 rounded-xl border bg-card px-4 py-3">
@ -79,21 +81,21 @@ export default async function Welcome() {
</div>
<div className="flex flex-col gap-1 rounded-xl border bg-card px-4 py-3">
<span className="font-medium">Ваш Claude или ChatGPT</span>
<span className="text-sm text-muted-foreground">Подключите Peppa FACTORY к своему чату (MCP) — и ведите проекты прямо из него: «создай стори», «что ждёт моего ответа?».</span>
<span className="text-sm text-muted-foreground">Подключите Peppa FACTORY к своему чату — и ведите проекты прямо из него: «создай {w.task("acc")}», «что ждёт моего ответа?».</span>
<Link href="/help" className="mt-1 text-sm">Как подключить →</Link>
</div>
</div>
</Section>
<Section title="Слова, которые встретятся">
<dl className="m-0 grid gap-2 sm:grid-cols-2">
{WORDS.map(([t, d]) => (
{glossary(w).map(([t, d]) => (
<div key={t} className="rounded-xl border bg-card px-4 py-3">
<dt className="font-medium">{t}</dt>
<dd className="m-0 text-sm text-muted-foreground">{d}</dd>
</div>
))}
</dl>
<p className="mt-4 text-sm text-muted-foreground">Что-то непонятно? Загляните в <Link href="/help">Помощь</Link> — там и подключение через MCP, и горячие клавиши.</p>
<p className="mt-4 text-sm text-muted-foreground">Что-то непонятно? Загляните в <Link href="/help">Помощь</Link> — там всё по шагам.</p>
</Section>
</Workspace>
);

View File

@ -1,5 +1,5 @@
import { paletteItems } from "@peppa/core";
import { currentUser } from "@/lib/auth";
import { currentUser, uiMode } from "@/lib/auth";
import { db } from "@/lib/db";
export const dynamic = "force-dynamic";
@ -8,5 +8,8 @@ export const dynamic = "force-dynamic";
export async function GET() {
const user = await currentUser();
if (!user) return Response.json({ error: "unauthorized" }, { status: 401 });
return Response.json({ items: await paletteItems(db, user.id) }, { headers: { "Cache-Control": "private, no-store" } });
// PEP-123: terminals of agents are a tool of «Инженер»; «Продакт» searches projects, tasks and questions.
const all = await paletteItems(db, user.id);
const items = (await uiMode()) === "engineer" ? all : all.filter((i) => i.kind !== "runner" && i.href !== "/runners");
return Response.json({ items }, { headers: { "Cache-Control": "private, no-store" } });
}

View File

@ -5,7 +5,7 @@ export default function manifest(): MetadataRoute.Manifest {
return {
name: "Peppa FACTORY",
short_name: "Peppa FACTORY",
description: "Проекты, стори и агенты",
description: "Проекты, задачи и агенты",
start_url: "/",
scope: "/",
display: "standalone",

View File

@ -40,12 +40,12 @@ export default async function Authorize({ searchParams }: { searchParams: Promis
) : (
<>
<p className="m-0 text-sm">
<b>{client.name}</b> <span className="text-muted-foreground">({host})</span> просит доступ к Пеппе от имени <b>{user.login}</b>.
<b>{client.name}</b> <span className="text-muted-foreground">({host})</span> просит доступ к Peppa FACTORY от имени <b>{user.login}</b>.
</p>
<ul className="m-0 flex list-disc flex-col gap-1 pl-5 text-sm">
<li>видеть ваши проекты, эпики, стори и вопросы агентов;</li>
<li>создавать стори и двигать карточки — перенос в «В работе» запускает агента;</li>
<li>отвечать на вопросы агентов и принимать ревью.</li>
<li>видеть ваши проекты, эпики, задачи и вопросы агентов;</li>
<li>создавать задачи и двигать карточки — перенос в «В работе» запускает агента;</li>
<li>отвечать на вопросы агентов и принимать результат.</li>
</ul>
<p className="m-0 text-xs text-muted-foreground">Отозвать доступ можно в «Настройки → Подключённые приложения».</p>
<div className="flex gap-2">

View File

@ -1,6 +1,6 @@
import Link from "next/link";
import { ago } from "@/components/common";
import { requireUser } from "@/lib/auth";
import { requireUser, words } from "@/lib/auth";
import { activeSessions, inbox } from "@/lib/queries";
import { SESSION_STATUS, TONE_BG } from "@/lib/status";
import { cn } from "@/lib/utils";
@ -8,11 +8,12 @@ import { cn } from "@/lib/utils";
/** Default right panel: what waits for the PM and what is running now. */
export async function ActivityAside({ questions = true }: { questions?: boolean }) {
const user = await requireUser();
const w = await words();
const [items, sessions] = await Promise.all([questions ? inbox(user.id) : [], activeSessions(user.id)]);
return (
<div className="flex flex-col gap-6">
{questions && (
<PanelSection title="Ждут тебя" count={items.length} href="/" more="на Главную">
<PanelSection title="Ждут вас" count={items.length} href="/" more="на Главную">
{items.length === 0 ? (
<p className="text-sm text-muted-foreground">Агентам ничего не нужно.</p>
) : (
@ -25,14 +26,14 @@ export async function ActivityAside({ questions = true }: { questions?: boolean
)}
</PanelSection>
)}
<PanelSection title="Агенты за работой" count={sessions.length} href="/runners" more="все">
<PanelSection title="Агенты за работой" count={sessions.length} href={w.engineer ? "/runners" : undefined} more="все">
{sessions.length === 0 ? (
<p className="text-sm text-muted-foreground">Сейчас ничего не запущено.</p>
) : (
sessions.slice(0, 12).map((s) => {
const st = SESSION_STATUS[s.status] ?? { label: s.status, tone: "muted" as const };
return (
<Link key={s.id} href={`/runners?id=${s.id}`} className="flex items-center gap-2 rounded-md px-2 py-1.5 text-sm text-foreground hover:bg-accent hover:no-underline">
<Link key={s.id} href={w.engineer ? `/runners?id=${s.id}` : s.taskKey ? `/t/${s.taskKey}` : `/p/${s.projectKey}`} className="flex items-center gap-2 rounded-md px-2 py-1.5 text-sm text-foreground hover:bg-accent hover:no-underline">
<span className={cn("size-2 shrink-0 rounded-full", TONE_BG[st.tone], s.status === "running" && "animate-pulse")} title={st.label} />
<span className="shrink-0 font-mono text-xs">{s.taskKey ?? s.projectKey}</span>
<span className="min-w-0 flex-1 truncate text-muted-foreground">{s.taskTitle}</span>

View File

@ -5,7 +5,7 @@ import { Hidden } from "@/components/cards";
import { Button } from "@/components/ui/button";
import { Input, Label, NativeSelect } from "@/components/ui/input";
export function AutonomyPanel({ projectId, settings, back }: { projectId: number; settings: AutonomySettings; back: string }) {
export function AutonomyPanel({ projectId, settings, back, engineer = false }: { projectId: number; settings: AutonomySettings; back: string; /** PEP-123: the detailed settings speak of merges and pipelines — «Инженер» only. */ engineer?: boolean }) {
const current = autonomyLevel(settings);
const s = settings;
return (
@ -26,6 +26,7 @@ export function AutonomyPanel({ projectId, settings, back }: { projectId: number
)}
</div>
<p className="m-0 text-xs text-muted-foreground">{current === "custom" ? "Своя комбинация настроек ниже." : AUTONOMY_LEVEL_HINT[current]}</p>
{engineer && (
<details>
<summary className="cursor-pointer text-sm text-primary">Настроить подробно</summary>
<form action={setAutonomyAction} className="mt-3 flex flex-col gap-3">
@ -34,11 +35,11 @@ export function AutonomyPanel({ projectId, settings, back }: { projectId: number
Кто берёт стори из бэклога
<NativeSelect name="pick" defaultValue={s.pick} className="h-8">
<option value="pm">PM — двигает карточки сам</option>
<option value="auto">Пеппа — сама, по номеру стори</option>
<option value="auto">Peppa FACTORY — сама, по порядку на доске</option>
</NativeSelect>
</Label>
<Label>
Сколько стори в работе одновременно (для «Пеппа сама»)
Сколько стори в работе одновременно (для «Peppa FACTORY сама»)
<Input name="wipLimit" type="number" min={1} max={5} defaultValue={s.wipLimit} className="h-8" />
</Label>
<Label>
@ -84,7 +85,8 @@ export function AutonomyPanel({ projectId, settings, back }: { projectId: number
<Button size="sm" className="self-start">Сохранить</Button>
</form>
</details>
<p className="m-0 text-xs text-muted-foreground">PR, меняющий конвейер (.gitea/, checks, deploy), сам не мержится и не закрывается — его принимает PM.</p>
)}
{engineer && <p className="m-0 text-xs text-muted-foreground">PR, меняющий конвейер (.gitea/, checks, deploy), сам не мержится и не закрывается — его принимает PM.</p>}
</div>
);
}

View File

@ -1,5 +1,6 @@
"use client";
import { useWords } from "@/components/Words";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useEffect, useState, useTransition } from "react";
@ -36,9 +37,10 @@ export interface CardProgress {
/** «7/12» bar and the item the agent is on (PEP-33). */
export function ProgressLine({ p, className }: { p: CardProgress; className?: string }) {
const w = useWords();
const pct = p.total ? Math.round((p.done / p.total) * 100) : 0;
return (
<div className={cn("flex min-w-0 flex-col gap-1", className)} title={p.current ? `Сейчас: ${p.current}` : "Все пункты tasks.md выполнены"}>
<div className={cn("flex min-w-0 flex-col gap-1", className)} title={p.current ? `Сейчас: ${p.current}` : w.engineer ? "Все пункты tasks.md выполнены" : "Все шаги плана выполнены"}>
<div className="flex items-center gap-2">
<div className="h-1 flex-1 overflow-hidden rounded-full bg-muted">
<div className="h-full rounded-full bg-info" style={{ width: `${pct}%` }} />
@ -77,6 +79,7 @@ const NEXT: Partial<Record<Column, { to: Column; label: string }>> = {
* for the dispatcher, PEP-34). «Готово» can be collapsed (remembered in the browser).
*/
export function Board({ cards, back }: { cards: Card[]; back: string }) {
const w = useWords();
const router = useRouter();
const [pending, start] = useTransition();
const [over, setOver] = useState<Column | null>(null);
@ -198,7 +201,7 @@ export function Board({ cards, back }: { cards: Card[]; back: string }) {
{(STATUS[card.status] || NEXT[c.id] || card.epic || card.blocked) && (
<div className="flex flex-wrap items-center gap-1.5">
{card.blocked && (
<Badge variant="warn" title="Диспетчер не возьмёт стори, пока предшественники не в ревью или готово">
<Badge variant="warn" title={w.engineer ? "Диспетчер не возьмёт стори, пока предшественники не в ревью или готово" : "Агенты возьмут эту задачу, когда будут готовы задачи, от которых она зависит"}>
<Lock className="size-3" />
{card.blocked}
</Badge>
@ -223,7 +226,7 @@ export function Board({ cards, back }: { cards: Card[]; back: string }) {
);
})}
</div>
<p className="m-0 text-xs text-muted-foreground">Порядок в колонке — приоритет: перетащите карточку выше или ниже; диспетчер берёт стори из бэклога сверху.</p>
<p className="m-0 text-xs text-muted-foreground">Порядок в колонке — приоритет: перетащите карточку выше или ниже; {w.engineer ? "диспетчер берёт стори из бэклога сверху" : "агенты берут задачи из бэклога сверху"}.</p>
</div>
);
}

View File

@ -7,7 +7,8 @@ import { useCallback, useEffect, useRef, useState, useTransition } from "react";
import { Bot, CircleHelp, FileText, FolderKanban, Keyboard, MessageCircleQuestion, Play, Search } from "lucide-react";
import { matchPalette, type PaletteItem } from "@peppa/shared/palette";
import { moveTaskCard } from "@/app/(app)/actions";
import { PALETTE_KEYS, SHORTCUTS } from "@/lib/shortcuts";
import { PALETTE_KEYS, shortcutsFor } from "@/lib/shortcuts";
import { useWords } from "@/components/Words";
import { cn } from "@/lib/utils";
const ICON = { project: FolderKanban, story: FileText, runner: Bot, question: MessageCircleQuestion, page: CircleHelp } as const;
@ -24,10 +25,11 @@ export function Kbd({ children }: { children: React.ReactNode }) {
}
export function ShortcutsList() {
const w = useWords();
return (
<table className="w-full border-collapse text-sm">
<tbody>
{SHORTCUTS.map((s) => (
{shortcutsFor(w).map((s) => (
<tr key={s.keys.join(" ") + s.what} className="border-b last:border-0">
<td className="py-1.5 pr-3 whitespace-nowrap">
{s.keys.map((k, i) => (
@ -58,6 +60,10 @@ export function CommandPalette() {
const [query, setQuery] = useState("");
const [sel, setSel] = useState(0);
const [note, setNote] = useState<string | null>(null);
const w = useWords();
// PEP-123: «g r» (terminals of agents) works in «Инженер» only.
const engineer = useRef(w.engineer);
engineer.current = w.engineer;
const [pending, start] = useTransition();
const shown = matchPalette(items, query);
@ -112,7 +118,7 @@ export function CommandPalette() {
return;
}
if (e.metaKey || e.ctrlKey || e.altKey || typing(e.target) || palette.current?.open || help.current?.open) return;
if (prefix && prefix.key === "g" && Date.now() - prefix.at < 1000 && GO[e.key]) {
if (prefix && prefix.key === "g" && Date.now() - prefix.at < 1000 && GO[e.key] && (e.key !== "r" || engineer.current)) {
e.preventDefault();
prefix = null;
router.push(GO[e.key]!);
@ -211,7 +217,7 @@ export function CommandPalette() {
else go(shown[sel]!);
}
}}
placeholder="Проект, стори, раннер, вопрос или раздел…"
placeholder={w.engineer ? "Проект, стори, раннер, вопрос или раздел…" : "Проект, задача, вопрос или раздел…"}
aria-label="Поиск"
role="combobox"
aria-expanded="true"

View File

@ -7,6 +7,7 @@ import { ago, Disclosure, Empty, Key, Section } from "@/components/common";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input, Label, NativeSelect, Textarea } from "@/components/ui/input";
import type { Words } from "@peppa/shared/wording";
const STATUS_TONE: Record<Incident["status"], "danger" | "warn" | "info" | "ok" | "muted"> = { new: "danger", open: "warn", pending: "warn", task: "info", ignored: "muted", resolved: "ok", regressed: "danger" };
@ -21,20 +22,21 @@ export function IncidentsSection(props: {
settings: IncidentSettings | null;
incidents: Incident[];
taskKeys: Map<number, string>;
w: Words;
}) {
const { settings: s } = props;
const { settings: s, w } = props;
if (!s) {
return (
<Section title="Баги">
<p className="m-0 text-sm text-muted-foreground">Ошибки фронта и бэка из прода (Bugsink, SDK Sentry) приходят сюда и становятся стори по политике проекта.</p>
<Empty>Отслеживание ошибок не подключено — подключает владелец в «⋯ Настройки проекта».</Empty>
<p className="m-0 text-sm text-muted-foreground">{w.engineer ? "Ошибки фронта и бэка из прода (Bugsink, SDK Sentry) приходят сюда и становятся стори по политике проекта." : "Когда ваш продукт заработает, его ошибки будут приходить сюда и становиться задачами для агентов."}</p>
<Empty>Отслеживание ошибок не подключено — подключает владелец в «Настройках проекта».</Empty>
</Section>
);
}
const active = props.incidents.filter((i) => !["ignored", "resolved"].includes(i.status));
const rest = props.incidents.filter((i) => ["ignored", "resolved"].includes(i.status));
return (
<Section title="Баги" count={active.length} actions={<span className="text-xs text-muted-foreground">политика: {POLICY_RU[s.policy]}</span>}>
<Section title="Баги" count={active.length} actions={w.engineer ? <span className="text-xs text-muted-foreground">политика: {POLICY_RU[s.policy]}</span> : undefined}>
{active.length === 0 ? <Empty>Открытых ошибок нет.</Empty> : active.map((i) => <IncidentCard key={i.id} i={i} {...props} />)}
{rest.length > 0 && (
<Disclosure summary={`Исправленные и игнорируемые (${rest.length})`}>
@ -57,12 +59,13 @@ export function IncidentSettingsPanel(props: {
settings: IncidentSettings | null;
sources: ErrorSource[];
webhookUrl: string | null;
w: Words;
}) {
const { projectId, back, settings: s } = props;
const { projectId, back, settings: s, w } = props;
if (!s) {
return (
<div className="flex flex-col gap-2 text-sm">
<p className="m-0 text-muted-foreground">Ошибки фронта и бэка из прода (Bugsink, SDK Sentry) приходят во вкладку «Баги» и становятся стори по политике проекта.</p>
<p className="m-0 text-muted-foreground">{w.engineer ? "Ошибки фронта и бэка из прода (Bugsink, SDK Sentry) приходят во вкладку «Баги» и становятся стори по политике проекта." : "Ошибки вашего продукта будут приходить во вкладку «Баги» и становиться задачами для агентов."}</p>
{props.isOwner ? (
<form action={connectErrorTrackingAction}>
<Hidden fields={{ projectId, back }} />
@ -77,6 +80,8 @@ export function IncidentSettingsPanel(props: {
</div>
);
}
// PEP-123: addresses, variables and the policy of incidents are an engineer's settings.
if (w.product) return <p className="m-0 text-sm text-muted-foreground">Подключено: ошибки вашего продукта приходят во вкладку «Баги» и становятся задачами для агентов.</p>;
return (
<div className="flex flex-col gap-3 text-sm">
{props.sources.map((src) => (
@ -93,7 +98,7 @@ export function IncidentSettingsPanel(props: {
<div className="flex flex-col gap-1">
<span><b>Вебхук не настроен автоматически.</b> В Bugsink: проект → Alerts → Custom webhook:</span>
<Code>{props.webhookUrl}</Code>
<span className="text-muted-foreground">Пока его нет, Пеппа опрашивает Bugsink раз в 2 минуты.</span>
<span className="text-muted-foreground">Пока его нет, Peppa FACTORY опрашивает Bugsink раз в 2 минуты.</span>
</div>
)}
<form action={saveIncidentSettings} className="flex flex-col gap-2.5">
@ -126,7 +131,7 @@ export function IncidentSettingsPanel(props: {
);
}
function IncidentCard({ i, back, projectId, taskKeys }: { i: Incident; back: string; projectId: number; taskKeys: Map<number, string> }) {
function IncidentCard({ i, back, projectId, taskKeys, w }: { i: Incident; back: string; projectId: number; taskKeys: Map<number, string>; w: Words }) {
const taskKey = i.taskId ? taskKeys.get(i.taskId) : null;
const decide = (action: string, label: string, icon: React.ReactNode) => (
<form action={decideIncidentAction}>
@ -145,13 +150,13 @@ function IncidentCard({ i, back, projectId, taskKeys }: { i: Incident; back: str
<span className="shrink-0 font-mono text-xs text-muted-foreground">{ago(i.lastSeen)}</span>
</div>
<div className="flex flex-wrap items-center gap-x-1.5 text-xs text-muted-foreground">
{i.source} · {i.environment ?? "—"} · релиз {i.lastRelease ?? "—"} · событий {i.events}
{i.culprit && (
{w.engineer ? <>{i.source} · {i.environment ?? "—"} · релиз {i.lastRelease ?? "—"} · событий {i.events}</> : <>случалась раз: {i.events}</>}
{w.engineer && i.culprit && (
<span className="inline-flex items-center gap-1">
· <MapPin className="size-3" /> {i.culprit}
</span>
)}
{i.url && (
{w.engineer && i.url && (
<>
· <a href={i.url} className="text-primary">Bugsink</a>
</>

View File

@ -73,8 +73,8 @@ export function OwnBotSteps({ botUsername, back, bare = false }: { botUsername:
) : (
<>
<span className="text-muted-foreground">
Токен выглядит так: <span className="font-mono">1234567890:AAH…</span> (цифры, двоеточие, буквы). Вставьте его сюда — Пеппа хранит его
зашифрованным и никому не показывает. Никому, кроме Пеппы, токен не отправляйте.
Токен выглядит так: <span className="font-mono">1234567890:AAH…</span> (цифры, двоеточие, буквы). Вставьте его сюда — Peppa FACTORY хранит его
зашифрованным и никому не показывает. Никому, кроме Peppa FACTORY, токен не отправляйте.
</span>
<form action={connectOwnBotAction} className="flex w-full flex-wrap gap-2">
<Hidden fields={fields} />

View File

@ -5,6 +5,7 @@ import { ago } from "@/components/common";
import { Button } from "@/components/ui/button";
import { Hidden } from "@/components/cards";
import { deployProdAction } from "@/app/(app)/actions";
import { wording } from "@peppa/shared/wording";
const host = (url: string) => url.replace(/^https?:\/\//, "");
@ -24,11 +25,12 @@ export function ProductCard({ product, projectKey, chat = true, engineer = false
<Button size="sm" variant="default">Показать всем</Button>
</form>
);
const { task } = wording(engineer ? "engineer" : "product");
const { live, check, doneStories } = product;
if (!live && !check && doneStories === 0) return null;
const next = chat && (
<p className="m-0 text-sm text-muted-foreground">
Что дальше: опишите следующую задачу <Link href={`/chats/${projectKey}`}>аналитику в чате</Link> — он поможет сформулировать стори, агенты сделают.
Что дальше: опишите следующую задачу <Link href={`/chats/${projectKey}`}>аналитику в чате</Link> — он поможет сформулировать {task("acc")}, агенты сделают.
</p>
);
return (
@ -39,7 +41,7 @@ export function ProductCard({ product, projectKey, chat = true, engineer = false
<span className="text-[15px] font-semibold">Ваш продукт работает</span>
<span className="text-sm text-muted-foreground">
Открыт для всех по адресу <span className="font-mono text-foreground">{host(live.url)}</span> · обновлён {ago(live.at)}
{live.stories.length > 0 && <> · вошли стори {live.stories.slice(0, 6).join(", ")}</>}
{live.stories.length > 0 && <> · вошли {task("pl")} {live.stories.slice(0, 6).join(", ")}</>}
</span>
</div>
<Button asChild variant="default">
@ -64,9 +66,9 @@ export function ProductCard({ product, projectKey, chat = true, engineer = false
</div>
) : (
<div className="flex flex-col gap-0.5">
<span className="text-[15px] font-semibold">Готово стори: {doneStories}</span>
<span className="text-[15px] font-semibold">Готово {task("genPl")}: {doneStories}</span>
<span className="text-sm text-muted-foreground">
Этот проект пока не открывается по ссылке как сайт. Что получилось — на странице каждой готовой стори, вкладка «Результат»{engineer ? ", и во вкладке «Код»" : ""}. Хотите открывать продукт по
Этот проект пока не открывается по ссылке как сайт. Что получилось — на странице каждой готовой {task("gen")}, вкладка «Результат»{engineer ? ", и во вкладке «Код»" : ""}. Хотите открывать продукт по
ссылке — попросите аналитика в чате: «сделай, чтобы продукт открывался по ссылке».
</span>
</div>

View File

@ -3,6 +3,8 @@ import type { ProgressOverview as Overview, ProjectProgress } from "@peppa/core"
import { AgentBadge } from "@/components/AgentBadge";
import { Empty, Key } from "@/components/common";
import { cn } from "@/lib/utils";
import { words } from "@/lib/auth";
import type { Words } from "@peppa/shared/wording";
const PARTS = [
{ k: "done", label: "готово", bar: "bg-ok" },
@ -14,10 +16,10 @@ const PARTS = [
type Counts = Pick<ProjectProgress, "done" | "review" | "inProgress" | "backlog" | "total">;
/** One bar split by board column: done · review · in work · backlog. */
function StackedBar({ c, className }: { c: Counts; className?: string }) {
function StackedBar({ c, className, w }: { c: Counts; className?: string; w: Words }) {
const label = PARTS.map((p) => `${p.label} ${c[p.k]}`).join(", ");
return (
<span role="img" aria-label={`Стори: ${label}`} title={label} className={cn("flex h-2 w-full gap-0.5 overflow-hidden rounded-full bg-muted", className)}>
<span role="img" aria-label={`${w.Task("pl")}: ${label}`} title={label} className={cn("flex h-2 w-full gap-0.5 overflow-hidden rounded-full bg-muted", className)}>
{c.total > 0 && PARTS.map((p) => (c[p.k] ? <span key={p.k} className={cn("h-full", p.bar)} style={{ flexGrow: c[p.k], flexBasis: 0 }} /> : null))}
</span>
);
@ -38,7 +40,7 @@ function Legend({ c }: { c: Counts }) {
);
}
function ProjectRow({ p }: { p: ProjectProgress }) {
function ProjectRow({ p, w }: { p: ProjectProgress; w: Words }) {
return (
<li className="flex flex-col gap-2 rounded-lg border bg-card px-4 py-3">
<div className="flex flex-wrap items-center gap-2 text-sm">
@ -56,11 +58,11 @@ function ProjectRow({ p }: { p: ProjectProgress }) {
готово <b className="font-medium text-foreground">{p.done}</b> из {p.total} · {pct(p)}%
</>
) : (
"стори пока нет"
`${w.task("genPl")} пока нет`
)}
</span>
</div>
<StackedBar c={p} />
<StackedBar c={p} w={w} />
{p.working.length > 0 && (
<ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm">
{p.working.map((s) => (
@ -91,8 +93,9 @@ function ProjectRow({ p }: { p: ProjectProgress }) {
}
/** PEP-77: progress of the user's own projects on the Home page (other people's projects — on «Проекты», for a superadmin). */
export function ProgressOverview({ data }: { data: Overview }) {
if (!data.mine.length) return <Empty>Проектов пока нет — прогресс появится с первой стори.</Empty>;
export async function ProgressOverview({ data }: { data: Overview }) {
const w = await words();
if (!data.mine.length) return <Empty>Проектов пока нет — прогресс появится с первой {w.task("ins")}.</Empty>;
const t = data.totals;
return (
<div className="flex flex-col gap-3">
@ -101,16 +104,16 @@ export function ProgressOverview({ data }: { data: Overview }) {
<div className="flex flex-wrap items-baseline gap-x-3 gap-y-1">
<span className="text-2xl font-semibold tabular-nums">{pct(t)}%</span>
<span className="text-sm text-muted-foreground">
готово {t.done} из {t.total} стори в {data.mine.length} {data.mine.length === 1 ? "проекте" : "проектах"}
готово {t.done} из {t.total} {w.task("genPl")} в {data.mine.length} {data.mine.length === 1 ? "проекте" : "проектах"}
</span>
</div>
<StackedBar c={t} className="h-3" />
<StackedBar c={t} className="h-3" w={w} />
<Legend c={t} />
</div>
)}
<ul className="m-0 flex list-none flex-col gap-2 p-0">
{data.mine.map((p) => (
<ProjectRow key={p.key} p={p} />
<ProjectRow key={p.key} p={p} w={w} />
))}
</ul>
</div>

View File

@ -16,7 +16,7 @@ export function PugMascot({ mood, size = 96, className }: { mood: Mood; size?: n
width={(size * 120) / 140}
height={size}
role="img"
aria-label={awake ? "Мопс Пеппы ждёт твоего ответа" : "Мопс Пеппы спит"}
aria-label={awake ? "Мопс Peppa FACTORY ждёт вашего ответа" : "Мопс Peppa FACTORY спит"}
className={cn("shrink-0 overflow-visible", awake ? "pug-alert" : "pug-sleep", className)}
>
<defs>
@ -129,11 +129,11 @@ export function PugBanner({ count }: { count: number }) {
<div className="relative rounded-2xl border bg-card px-4 py-2.5 text-sm shadow-xs before:absolute before:top-1/2 before:-left-[7px] before:size-3 before:-translate-y-1/2 before:rotate-45 before:border-b before:border-l before:bg-card">
{awake ? (
<>
<span className="font-medium">Гав! {count === 1 ? "Агент ждёт" : "Агенты ждут"} твоего ответа</span>
<span className="font-medium">Гав! {count === 1 ? "Агент ждёт" : "Агенты ждут"} вашего ответа</span>
<span className="text-muted-foreground"> — {plural(count)} ниже.</span>
</>
) : (
<span className="text-muted-foreground">Тихо… Агентам от тебя ничего не нужно, мопс спит.</span>
<span className="text-muted-foreground">Тихо… Агентам от вас ничего не нужно, мопс спит.</span>
)}
</div>
</div>

View File

@ -30,7 +30,7 @@ export function NewRunnerForm({ projects, projectId, back }: { projects?: Array<
return (
<form action={startFreeRunnerAction} className="flex flex-col gap-3">
<Hidden fields={{ back, ...(projectId ? { projectId } : {}) }} />
<p className="m-0 text-sm text-muted-foreground">Агент в tmux без стори: разобраться, попробовать, спросить. Пинги после ходов не приходят — раннером управляешь ты в терминале. Получилась работа — «Оформить стори».</p>
<p className="m-0 text-sm text-muted-foreground">Агент в tmux без стори: разобраться, попробовать, спросить. Пинги после ходов не приходят — раннером управляете вы в терминале. Получилась работа — «Оформить стори».</p>
{!projectId && (
<Label>
Проект

View File

@ -28,7 +28,7 @@ const ITEMS: Item[] = [
{ href: "/projects", label: "Проекты", icon: FolderKanban, match: (p) => p.startsWith("/projects") || p.startsWith("/p/") || p.startsWith("/t/") },
{ href: "/runners", label: "Работа агентов", icon: Bot, match: (p) => p.startsWith("/runners"), count: "waitingRunners", engineer: true },
{ href: "/team", label: "Команда", icon: Contact, match: (p) => p.startsWith("/team"), desktopOnly: true },
{ href: "/welcome", label: "О Пеппе", icon: Sparkles, match: (p) => p.startsWith("/welcome"), desktopOnly: true },
{ href: "/welcome", label: "О Peppa FACTORY", icon: Sparkles, match: (p) => p.startsWith("/welcome"), desktopOnly: true },
{ href: "/help", label: "Помощь", icon: LifeBuoy, match: (p) => p.startsWith("/help") },
{ href: "/subscriptions", label: "Подписки", icon: KeyRound, match: (p) => p.startsWith("/subscriptions"), admin: true },
{ href: "/secrets", label: "Секреты", icon: ShieldCheck, match: (p) => p.startsWith("/secrets"), admin: true },
@ -40,7 +40,7 @@ const ITEMS: Item[] = [
];
const COUNT_TITLE = { questions: "вопросов ждут вас", waitingRunners: "агентов ждут вас", chats: "новых сообщений в обсуждениях" };
/** Left panel on desktop; on phones a top bar plus a bottom tab bar (PEP-38): sections with «ждут тебя» counters, theme, user. */
/** Left panel on desktop; on phones a top bar plus a bottom tab bar (PEP-38): sections with «ждут вас» counters, theme, user. */
export function Sidebar({ login, avatarUrl, counts, superadmin = false, engineer = false }: { login: string; avatarUrl: string | null; counts: Record<"questions" | "waitingRunners" | "chats", number>; superadmin?: boolean; engineer?: boolean }) {
const path = usePathname();
const items = ITEMS.filter((i) => (!i.admin || superadmin) && (!i.engineer || engineer));

View File

@ -75,7 +75,7 @@ export function SubscriptionSetup({ projectId, back, logins, shared = false, req
<div className="flex flex-col gap-2 rounded-lg border bg-card px-4 py-3">
{shared && <span className="font-medium">Своя подписка</span>}
<p className="m-0 text-muted-foreground">
Агенты пишут код на вашей подписке Claude или ChatGPT — подойдёт обычная платная (Claude Pro или Max, ChatGPT Plus или Pro). Лимиты и расход — только ваши, пароль Пеппа не видит.
Агенты пишут код на вашей подписке Claude или ChatGPT — подойдёт обычная платная (Claude Pro или Max, ChatGPT Plus или Pro). Лимиты — только ваши, пароль Peppa FACTORY не видит.
</p>
<div className="flex flex-wrap gap-2">
<form action={connectOwnSubscriptionAction}>
@ -106,7 +106,7 @@ export function SubscriptionSetup({ projectId, back, logins, shared = false, req
</div>
)}
</div>
<p className="m-0 text-xs text-muted-foreground">Нет своей подписки? Оформите её на claude.ai или chatgpt.com и вернитесь сюда. Другие способы (готовый токен, ключ API) и смена выбора — в «⋯ Настройки проекта → Подписки».</p>
<p className="m-0 text-xs text-muted-foreground">Нет своей подписки? Оформите её на claude.ai или chatgpt.com и вернитесь сюда. Сменить выбор можно в «Настройках проекта → Подписки».</p>
</section>
);
}

View File

@ -0,0 +1,17 @@
"use client";
import { createContext, useContext, useMemo, type ReactNode } from "react";
import { wording, type WordMode, type Words } from "@peppa/shared/wording";
const Ctx = createContext<WordMode>("product");
/** PEP-123: the layout tells client components which view the user chose («Продакт» / «Инженер»). */
export function WordsProvider({ mode, children }: { mode: WordMode; children: ReactNode }) {
return <Ctx.Provider value={mode}>{children}</Ctx.Provider>;
}
/** Words of the current view for client components; server components call `words()` from lib/auth. */
export function useWords(): Words {
const mode = useContext(Ctx);
return useMemo(() => wording(mode), [mode]);
}

View File

@ -108,7 +108,7 @@ export function SessionActions({ s, back }: { s: SessionView; back: string }) {
<Hidden fields={{ sessionId: s.id, back }} />
<Button size="sm">
{alive ? <RotateCcw /> : <Play />}
Resume
Продолжить
</Button>
</form>
)}
@ -155,9 +155,10 @@ export function SessionCard({ s, back, showTitle = false, terminal = false, step
/**
* PEP-89: an agent at work, for a product manager — who, on what, in what state. The run's
* number, subscription, terminal command and spend sit under «Подробнее».
* number, subscription, terminal command and spend sit under «Подробнее» — in «Инженер» only
* (PEP-123: «Продакт» sees no terminal commands, subscriptions or spend).
*/
export function AgentAtWork({ s, back }: { s: SessionView; back: string }) {
export function AgentAtWork({ s, back, engineer = false }: { s: SessionView; back: string; engineer?: boolean }) {
const alive = !["done", "failed"].includes(s.status);
const verb = s.status === "running" || s.status === "starting" ? "работает над" : s.status === "waiting_input" ? "спрашивает по" : "вёл";
return (
@ -176,13 +177,14 @@ export function AgentAtWork({ s, back }: { s: SessionView; back: string }) {
</>
) : (
<>
<span className="text-muted-foreground">свободный терминал в проекте</span>
<span className="text-muted-foreground">{engineer ? "свободный терминал в проекте" : "помогает в проекте"}</span>
<Key href={`/p/${s.projectKey}`}>{s.projectKey}</Key>
{s.name && <span className="min-w-0 truncate">{s.name}</span>}
</>
)}
</p>
<SessionActions s={s} back={back} />
{engineer && (
<Disclosure summary="Подробнее" className="border-0 bg-transparent [&>summary]:px-0 [&>summary]:py-0 [&>summary]:text-xs [&>summary]:font-normal [&>summary]:text-muted-foreground">
<div className="flex flex-col gap-2 pt-2">
<span className="font-mono text-xs text-muted-foreground">
@ -203,11 +205,13 @@ export function AgentAtWork({ s, back }: { s: SessionView; back: string }) {
)}
</div>
</Disclosure>
)}
</article>
);
}
export function ProjectList({ projects, userId }: { projects: Array<Project & { ownerLogin?: string | null }>; userId: number }) {
/** `engineer` (PEP-123): the address of the code is shown in «Инженер» only. */
export function ProjectList({ projects, userId, engineer = false }: { projects: Array<Project & { ownerLogin?: string | null }>; userId: number; engineer?: boolean }) {
if (!projects.length)
return (
<Empty>
@ -224,9 +228,11 @@ export function ProjectList({ projects, userId }: { projects: Array<Project & {
<span className="min-w-0 truncate font-medium">{p.name}</span>
{p.ownerId !== userId && <span className="ml-auto rounded-full border px-2 text-[11px] text-muted-foreground">{p.ownerLogin !== undefined ? (p.ownerLogin ?? "без владельца") : "общий"}</span>}
</span>
<span className="truncate font-mono text-xs text-muted-foreground">
{p.giteaOwner}/{p.giteaRepo}
</span>
{engineer && (
<span className="truncate font-mono text-xs text-muted-foreground">
{p.giteaOwner}/{p.giteaRepo}
</span>
)}
</Link>
</li>
))}

View File

@ -1,5 +1,6 @@
import { enterActor, getUiMode, getUser, isUserAllowed, sessionsValidAfter, sign, verify, type User } from "@peppa/core";
import { loadEnv } from "@peppa/shared";
import { wording, type Words } from "@peppa/shared/wording";
import { cookies, headers } from "next/headers";
import { redirect } from "next/navigation";
import { cache } from "react";
@ -80,3 +81,6 @@ export const uiMode = cache(async (): Promise<"product" | "engineer"> => {
const u = await currentUser();
return u ? getUiMode(db, u.id) : "product";
});
/** PEP-123: «задача» / «стори», «агент» / «раннер» — the words of the current user's view. */
export const words = cache(async (): Promise<Words> => wording(await uiMode()));

View File

@ -1,10 +1,26 @@
// Keyboard shortcuts (PEP-52): one list for the «?» dialog and /help/shortcuts.
import type { Words } from "@peppa/shared/wording";
export interface Shortcut {
keys: string[];
what: string;
where?: string;
}
/** PEP-123: the list in the words of the user's view; «Продакт» has no terminals of agents. */
export function shortcutsFor(w: Words): Shortcut[] {
if (w.engineer) return SHORTCUTS;
return [
{ keys: ["⌘K", "Ctrl+K"], what: "Поиск и переход к проекту, задаче или вопросу; «В работу», «Ответить»" },
{ keys: ["g", "h"], what: "Главная" },
{ keys: ["g", "p"], what: "Проекты" },
{ keys: ["g", "s"], what: "Настройки" },
{ keys: ["a"], what: "Перейти к полю ответа на первый открытый вопрос", where: "Главная, задача" },
{ keys: ["?"], what: "Список сочетаний" },
{ keys: ["Esc"], what: "Закрыть поиск или окно" },
];
}
export const SHORTCUTS: Shortcut[] = [
{ keys: ["⌘K", "Ctrl+K"], what: "Командная палитра: поиск и переход к проекту, стори, раннеру, вопросу; «В работу», «Ответить»" },
{ keys: ["/"], what: "Фокус в поиск на странице", where: "списки с полем поиска (Раннеры)" },

View File

@ -5,7 +5,8 @@
"type": "module",
"exports": {
".": "./src/index.ts",
"./palette": "./src/palette.ts"
"./palette": "./src/palette.ts",
"./wording": "./src/wording.ts"
},
"scripts": {
"typecheck": "tsc -p ."

View File

@ -1,2 +1,3 @@
export * from "./env.ts";
export * from "./task-key.ts";
export * from "./wording.ts";

View File

@ -0,0 +1,75 @@
// PEP-123: the words a person reads depend on the view (PEP-119). «Продакт» reads «задача» and
// «агент» (docs/glossary.md); «Инженер» keeps «стори» (one OpenSpec change; «задачи» there are
// the items of tasks.md) and «раннер» (the process, as opposed to the agent's persona).
// Pure module: used by the browser too.
export type WordMode = "product" | "engineer";
/** Case forms: singular nom/gen/dat/acc/ins/pre and the same in plural. */
export type WordForm = "nom" | "gen" | "dat" | "acc" | "ins" | "pre" | "pl" | "genPl" | "datPl" | "accPl" | "insPl" | "prePl";
export const BRAND = "Peppa FACTORY";
const TASK: Record<WordForm, string> = {
nom: "задача",
gen: "задачи",
dat: "задаче",
acc: "задачу",
ins: "задачей",
pre: "задаче",
pl: "задачи",
genPl: "задач",
datPl: "задачам",
accPl: "задачи",
insPl: "задачами",
prePl: "задачах",
};
// «агент» and «раннер» decline alike; both are animate, so the accusative follows the genitive.
const ENDING: Record<WordForm, string> = { nom: "", gen: "а", dat: "у", acc: "а", ins: "ом", pre: "е", pl: "ы", genPl: "ов", datPl: "ам", accPl: "ов", insPl: "ами", prePl: "ах" };
const cap = (s: string) => s.charAt(0).toUpperCase() + s.slice(1);
/** «1 задача», «2 задачи», «5 задач» — the form of a counted noun. */
export function plural(n: number, one: string, few: string, many: string): string {
const d = Math.abs(n) % 100;
const u = d % 10;
if (d > 10 && d < 20) return many;
if (u === 1) return one;
return u >= 2 && u <= 4 ? few : many;
}
export interface Words {
mode: WordMode;
/** True in «Продакт»: hide what only an engineer reads. */
product: boolean;
engineer: boolean;
/** «задача» / «стори» in the given form. */
task(form?: WordForm): string;
/** The same, capitalized. */
Task(form?: WordForm): string;
/** «5 задач» / «5 стори». */
tasks(n: number): string;
/** «агент» / «раннер» in the given form. */
runner(form?: WordForm): string;
Runner(form?: WordForm): string;
}
export function wording(mode: WordMode | null | undefined): Words {
const product = mode !== "engineer";
const task = (form: WordForm = "nom") => (product ? TASK[form] : "стори");
const runner = (form: WordForm = "nom") => (product ? "агент" : "раннер") + ENDING[form];
return {
mode: product ? "product" : "engineer",
product,
engineer: !product,
task,
Task: (form) => cap(task(form)),
tasks: (n) => `${n} ${product ? plural(n, TASK.nom, TASK.gen, TASK.genPl) : "стори"}`,
runner,
Runner: (form) => cap(runner(form)),
};
}
/** Texts stored or sent without knowing the reader's view (chat events, Telegram, push). */
export const PRODUCT_WORDS = wording("product");