PEP-98: English for web, bot, notifications and runner messages; product name «Peppa FACTORY» everywhere
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
355c5b19b2
commit
1f16286dca
@ -67,6 +67,7 @@
|
||||
- **Расход, бюджеты, метрики, журнал (PEP-5/43/47/48)**: раннер подключает к Claude `statusLine: peppa-hook statusline` (run-settings) — хук сохраняет стоимость по поколениям и контекст в `sessions.usage` (JSON, миграция 0010) и окна лимитов 5 ч / 7 д аккаунта в `settings` `usage.account:sub:<id>|machine` (троттлинг 20 с); Stop/SessionEnd суммируют токены transcript по разговору (core/usage.ts: `parseStatusLine` сверен с 2.1.323 (PEP-3: `context_window.total_*_tokens` — последний запрос, не сумма; токены только из transcript), `transcriptUsage`, `usageTotals`: нет стоимости → оценка по прайсу, «≈»). Веб: `UsageStrip` над каждой страницей (layout), расход на карточке раннера; бот `/status`, MCP `get_usage`. Бюджеты (core/budgets.ts, без миграций): `budget.project:<id>` / `budget.task:<id>` (минуты, токены, перезапуски, $; нет = без предела), `budgetTick` вачдога (runner/budgets.ts) при превышении — Escape в pane (ход прерван, процесс жив), `budget.state:<taskId>`, вопрос PM «Продлить ×2 / Снять лимит / Остановить» (`onBudgetAnswer`), `assertBudgetOpen` в start/resume/moveTask, Stop-хук не подталкивает; карточка стори и «⋯ Настройки проекта → Бюджет стори». Метрики (core/analytics.ts `projectMetrics`, из событий `task_updated`, вопросов, сессий, ревью): вкладка проекта «Метрики», MCP `get_metrics`. Журнал: автор события — колонки `events.actor_kind/actor_user_id/actor_channel/actor_client_id`, контекст `core/actor.ts` (AsyncLocalStorage: веб — `asWebActor(await requireUser())` в теле server action, `/mcp` — пользователь + OAuth-клиент, бот — `enterActor` после `telegramUser`, процессы — `setDefaultActor`: MCP агента, хук, CLI; `tick` вачдога — `runAsActor` system); без контекста: есть сессия — агент, иначе Пеппа; ответы — событие `question_answered` (кроме `system`). `/journal` — суперадмин, вкладка «Журнал» проекта — участники. Новые события пиши через `logSessionEvent` / `logEvent` (core/audit.ts), не прямой вставкой
|
||||
- **Память проекта (PEP-30)**: `.peppa/memory.md` в репо проекта (разделы Команды/Соглашения/Грабли/Решения), `core/memory.ts` (`rememberFact` — дубли пропускаются, предел `PEPPA_MEMORY_MAX_CHARS` 12 000 → отказ с просьбой ужать; `replaceMemory`; `memoryContext` = файл рабочей копии + 5 последних `done` стори). MCP агента `get_memory`/`remember` (файл рядом с `.peppa/project.json`, коммитит агент в ветке стори). Раннер (`launch` в runner/sessions.ts) дописывает `memoryContext` к общим правилам при каждом запуске/resume. Правило — «Завершение» в `template/RULES.md`; веб — вкладка «Спеки» (`MemorySection`)
|
||||
- **Модель агента (PEP-41)**: `core/agent-model.ts`, наследование `platform.agent` → `project.agent:<id>` → `task.agent:<taskId>` (`settings`): `provider`, `model`, `effort` (Claude `--effort`, Codex `-c model_reasoning_effort`, xhigh/max → high), `escalateModel`/`escalateEffort`/`escalateAfter` (по умолчанию 2; null — выкл), `fallbackProvider`/`fallbackModel`. Модель — только своему провайдеру (`launchModelFor`). Неудачи стори = `ci_attempts` + `reviewRejections`; порог → `agent.escalated:<taskId>` (липко). `startRunner`: провайдер из настроек, нет рабочей подписки → запасной (событие `provider_fallback`); `launch` пишет `model`/`effort` в `started`/`resumed`. `sendWithEscalation` (runner/escalation.ts, из ci-feedback и reviewer; у клиентов PEP-21 — команда сервиса `sendEscalated`): эскалация наступила, а модель живого запуска другая → kill tmux + `resumeSession` с сообщением (событие `model_escalated`). Веб «⋯ Настройки проекта → Модель агента», раздел «Агент» стори (`components/AgentModel.tsx`); MCP PM `agent` в `update_project_settings`/`update_task`; CLI `peppa project agent <KEY|KEY-N|--platform> k=v…`
|
||||
- **Язык интерфейса (PEP-98)**: `@peppa/shared/i18n` — ключ словаря = русская строка-шаблон (`{name}`), словари `packages/shared/src/i18n/en/*.ts` (по разделам), `kk.ts` (PEP-99, пока откат на русский). `t(locale, key, vars)` / `translator(locale)` (`t.n` — множественное, `t.text` — перевод уже собранного текста), `m(key, vars)` — пометка шаблона в core/runner/bot (рендерит русский), `localizeText` — обратное сопоставление по шаблонам (целиком → строки → куски между HTML-тегами → «a · b», «Метка: значение»; захваченные значения переводятся рекурсивно). Язык: `settings` `user.locale:<id>` (`getUserLocale`/`setUserLocale`, core/locale.ts) + cookie `peppa_lang`; веб `getLocale`/`getT` (lib/i18n.ts: пользователь → cookie → Accept-Language до входа → ru), клиент `useT()`/`LanguageSwitcher` (components/I18n.tsx), вход переносит язык (`adoptLocale`); ошибки server actions — `t.text` в `attempt()`. Бот переводит `text`/`caption`/кнопки/тосты по языку читателя (`localizeParams`, `telegramChatLocale`: группа — язык связавшего); push — в `deliverToUser`. Английское название — «Peppa FACTORY». Новый текст пользователю = ключ в `en/*.ts`, иначе падает `node scripts/i18n-check.ts` (тест `i18n.test.ts`); тексты агентам не переводятся (`// i18n-ignore`)
|
||||
- **Вход и старт для продактов (PEP-83)**: `/login` — зачем фабрика, пять шагов, что понадобится, вход справа (на телефоне: заголовок → вход → подробности); шаги `onboardingChecklist` для обычного пользователя: telegram → project → subscription (нет `projectAgentWarning` хотя бы у одного проекта) → story → started → accepted (первая `done`), у шага `action` — подпись кнопки; суперадмину subscription первым; тексты для непрограммиста
|
||||
- **Онбординг (PEP-31)**: `core/onboarding.ts` — `onboardingChecklist` (шаги из БД: подписка — только суперадмину, Telegram, eGov — необязательный, проект, стори, сессия стори; скрыт после выполнения или `onboarding.dismissed:<userId>`), `projectAgentWarning` (у пула проекта нет рабочей подписки; без пула — не проверяется). Веб: `components/Onboarding.tsx` на Главной, плашка «Агенты не запустятся» на странице проекта
|
||||
- `template/` — содержимое репо `peppa/template` в Gitea (`GITEA_TEMPLATE_REPO`) (`scripts/push-template.sh`). `RULES.md` — общие правила агентов: не копируется в проекты, раннер берёт свежую версию из Gitea при каждом запуске (`--append-system-prompt-file`), кэш `~/.peppa/rules.md`; MCP `get_rules` для ручных сессий. `AGENTS.md` — заготовка под специфику проекта
|
||||
|
||||
@ -2,8 +2,8 @@
|
||||
// alerts) to the paired chat and turns button presses / replies into answers delivered
|
||||
// back into the agent session. Telegram is an adapter over the DB, not a remote shell:
|
||||
// it can only answer a specific pending question or resume/stop the session it is about.
|
||||
import { reportPlatformError, telegramChatLocale } from "@peppa/core";
|
||||
import { localizeText } from "@peppa/shared/i18n";
|
||||
import { localizeMessage, reportPlatformError, telegramChatLocale } from "@peppa/core";
|
||||
import { m as tr } from "@peppa/shared/i18n";
|
||||
import {
|
||||
accountUsageForUser,
|
||||
describeUsage,
|
||||
@ -99,30 +99,34 @@ export interface BotOptions {
|
||||
log?: (msg: string) => void;
|
||||
}
|
||||
|
||||
const HELP = `Я бот Пеппы. Присылаю вопросы от агентов: одобрения proposal, вопросы, разрешения и сигналы, что сессия ждёт тебя.
|
||||
|
||||
• Кнопки под сообщением — быстрый ответ.
|
||||
• Ответ <b>реплаем</b> на сообщение — свой текст, он уйдёт прямо в сессию.
|
||||
• Просто напиши (или наговори голосом) задачу — я заведу стори: «в PAY: экспорт в CSV». Проект и эпик уточню кнопками, потом предложу сразу взять в работу.
|
||||
• /status — активные сессии и открытые вопросы.
|
||||
• /digest — сводка за сутки по твоим проектам (каждый день приходит сама; время и что присылать — в Настройках → Уведомления).`;
|
||||
// One key per line: localizeMessage translates a multi-line message line by line.
|
||||
const HELP = [
|
||||
tr("Я бот Пеппы. Присылаю вопросы от агентов: одобрения proposal, вопросы, разрешения и сигналы, что сессия ждёт тебя."),
|
||||
"",
|
||||
tr("• Кнопки под сообщением — быстрый ответ."),
|
||||
tr("• Ответ <b>реплаем</b> на сообщение — свой текст, он уйдёт прямо в сессию."),
|
||||
tr("• Просто напиши (или наговори голосом) задачу — я заведу стори: «в PAY: экспорт в CSV». Проект и эпик уточню кнопками, потом предложу сразу взять в работу."),
|
||||
tr("• /status — активные сессии и открытые вопросы."),
|
||||
tr("• /digest — сводка за сутки по твоим проектам (каждый день приходит сама; время и что присылать — в Настройках → Уведомления)."),
|
||||
].join("\n");
|
||||
|
||||
const PUSH_MAX_AGE_MS = 30 * 60_000;
|
||||
|
||||
const PUSH_TITLE: Record<NotifyEvent, string> = {
|
||||
questions: "Агент ждёт ответа",
|
||||
review: "Готово к ревью",
|
||||
failures: "Раннер остановился",
|
||||
releases: "Релиз",
|
||||
incidents: "Ошибка в проде",
|
||||
monitoring: "Мониторинг",
|
||||
digest: "Сводка",
|
||||
platform: "Обновления Пеппы",
|
||||
questions: tr("Агент ждёт ответа"),
|
||||
review: tr("Готово к ревью"),
|
||||
failures: tr("Раннер остановился"),
|
||||
releases: tr("Релиз"),
|
||||
incidents: tr("Ошибка в проде"),
|
||||
monitoring: tr("Мониторинг"),
|
||||
digest: tr("Сводка"),
|
||||
platform: tr("Обновления Пеппы"),
|
||||
};
|
||||
|
||||
/** Browser notification text for a question. */
|
||||
function pushFor(q: Question, event: NotifyEvent, ctx: { taskKey: string | null; taskTitle: string | null }): { title: string; body: string } {
|
||||
const title = `${ctx.taskKey ? `${ctx.taskKey}: ` : ""}${q.kind === "approval" ? "нужно одобрение" : q.kind === "permission" ? "нужно разрешение" : PUSH_TITLE[event]}`;
|
||||
const what = q.kind === "approval" ? tr("нужно одобрение") : q.kind === "permission" ? tr("нужно разрешение") : PUSH_TITLE[event];
|
||||
const title = ctx.taskKey ? `${ctx.taskKey}: ${what}` : what;
|
||||
const body = q.text.length > 200 ? `${q.text.slice(0, 199)}…` : q.text;
|
||||
return { title, body };
|
||||
}
|
||||
@ -156,13 +160,13 @@ export function createBot(o: BotOptions) {
|
||||
if (chatId == null) return params;
|
||||
const locale = await telegramChatLocale(db, chatId).catch(() => "ru" as const);
|
||||
if (locale === "ru") return params;
|
||||
const tr = (v: unknown) => (typeof v === "string" ? localizeText(locale, v) : v);
|
||||
const out: Record<string, unknown> = { ...params, text: tr(params.text), caption: tr(params.caption) };
|
||||
const loc = (v: unknown) => (typeof v === "string" ? localizeMessage(locale, v) : v);
|
||||
const out: Record<string, unknown> = { ...params, text: loc(params.text), caption: loc(params.caption) };
|
||||
if (params.text === undefined) delete out.text;
|
||||
if (params.caption === undefined) delete out.caption;
|
||||
const markup = params.reply_markup as { inline_keyboard?: { text: string }[][]; keyboard?: ({ text: string } | string)[][] } | undefined;
|
||||
if (markup && typeof markup === "object") {
|
||||
const btn = <B,>(b: B): B => (typeof b === "string" ? (tr(b) as B) : b && typeof b === "object" && "text" in b ? ({ ...b, text: tr((b as { text: string }).text) } as B) : b);
|
||||
const btn = <B,>(b: B): B => (typeof b === "string" ? (loc(b) as B) : b && typeof b === "object" && "text" in b ? ({ ...b, text: loc((b as { text: string }).text) } as B) : b);
|
||||
out.reply_markup = {
|
||||
...markup,
|
||||
...(markup.inline_keyboard ? { inline_keyboard: markup.inline_keyboard.map((row) => row.map(btn)) } : {}),
|
||||
@ -336,8 +340,10 @@ export function createBot(o: BotOptions) {
|
||||
buttons = r.buttons;
|
||||
questionId = q.id;
|
||||
} else {
|
||||
const who = m.kind === "user" ? `<b>${esc(m.authorLogin ?? "?")}</b>${m.via === "telegram" ? "" : " (веб)"}: ` : m.authorKind === "agent" ? "🤖 " : "";
|
||||
text = `${where ? `${where}\n` : ""}${who}${esc(m.text.slice(0, 3500))}${m.url ? `\n${esc(m.url)}` : ""}`;
|
||||
const said = esc(m.text.slice(0, 3500));
|
||||
const who = m.kind === "user" ? `<b>${esc(m.authorLogin ?? "?")}</b>` : m.authorKind === "agent" ? "🤖 " : "";
|
||||
const body = m.kind === "user" ? (m.via === "telegram" ? `: ${said}` : tr(" (веб): {text}", { text: said })) : said;
|
||||
text = `${where ? `${where}\n` : ""}${who}${body}${m.url ? `\n${esc(m.url)}` : ""}`;
|
||||
}
|
||||
await enqueueTelegram(db, {
|
||||
dedupeKey: `cm:${m.id}:${tgChatId}`,
|
||||
@ -401,10 +407,10 @@ export function createBot(o: BotOptions) {
|
||||
|
||||
async function answer(q: Question, text: string): Promise<string> {
|
||||
const fresh = await getQuestion(db, q.id);
|
||||
if (fresh.answeredAt) return `Уже отвечено${fresh.answeredVia === "system" ? "" : ` (${fresh.answeredVia})`}: ${fresh.answer}`;
|
||||
if (fresh.answeredAt) return fresh.answeredVia === "system" ? tr("Уже отвечено: {answer}", { answer: fresh.answer }) : tr("Уже отвечено ({via}): {answer}", { via: fresh.answeredVia, answer: fresh.answer });
|
||||
const { delivered } = await answerAndDeliver(db, q.id, text, "telegram");
|
||||
scheduleReconcile();
|
||||
return delivered ? "Отправлено в сессию ✅" : "Ответ сохранён, но сессия сейчас не запущена — агент увидит его в истории стори.";
|
||||
return delivered ? tr("Отправлено в сессию ✅") : tr("Ответ сохранён, но сессия сейчас не запущена — агент увидит его в истории стори.");
|
||||
}
|
||||
|
||||
const canAccess = (user: User, projectId: number) =>
|
||||
@ -417,17 +423,17 @@ export function createBot(o: BotOptions) {
|
||||
const ids = new Set(await userProjectIds(db, user.id));
|
||||
const sessions = (await listSessions(db, { active: true })).filter((s) => ids.has(s.projectId));
|
||||
const open = (await pendingQuestions(db)).filter((q) => ids.has(q.projectId));
|
||||
const lines = [`<b>Активные сессии: ${sessions.length}</b>`];
|
||||
const lines = ["<b>" + tr("Активные сессии: {n}", { n: sessions.length }) + "</b>"];
|
||||
for (const s of sessions) lines.push(`• ${esc(s.taskKey ?? `#${s.id}`)} — ${s.status} (${s.provider})${usageTotals(s.usage).hasData ? ` · ${esc(describeUsage(s.usage))}` : ""}`);
|
||||
lines.push("", `<b>Открытых вопросов: ${open.length}</b>`);
|
||||
lines.push("", "<b>" + tr("Открытых вопросов: {n}", { n: open.length }) + "</b>");
|
||||
// PEP-5: subscription limit windows.
|
||||
const accounts = await accountUsageForUser(db, user);
|
||||
lines.push("", "<b>Лимиты</b>", ...(accounts.length ? accounts.map((a) => `• ${esc(describeAccount(a))}`) : ["нет данных о лимитах"]));
|
||||
lines.push("", "<b>" + tr("Лимиты") + "</b>", ...(accounts.length ? accounts.map((a) => `• ${esc(describeAccount(a))}`) : [tr("нет данных о лимитах")]));
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
// ── stories from messages (PEP-45) ─────────────────────────────────────────────
|
||||
const cancelRow = (d: Draft): InlineButton[] => [{ text: "✖️ Отмена", callback_data: `d:${d.id}:x` }];
|
||||
const cancelRow = (d: Draft): InlineButton[] => [{ text: tr("✖️ Отмена"), callback_data: `d:${d.id}:x` }];
|
||||
const rows = (buttons: InlineButton[], per = 2) => buttons.reduce<InlineButton[][]>((acc, b, i) => (i % per ? acc[acc.length - 1]!.push(b) : acc.push([b]), acc), []);
|
||||
const storyLine = (d: Draft) => `«${esc(splitStory(d.text).title)}»`;
|
||||
|
||||
@ -444,24 +450,25 @@ export function createBot(o: BotOptions) {
|
||||
for (const r of await db.select({ projectId: tasks.projectId, at: sql<number>`max(${tasks.updatedAt})` }).from(tasks).groupBy(tasks.projectId)) touched.set(r.projectId, Number(r.at) || 0);
|
||||
projects = [...projects].sort((a, b) => (touched.get(b.id) ?? 0) - (touched.get(a.id) ?? 0) || b.id - a.id);
|
||||
const buttons = projects.slice(0, 12).map((p) => ({ text: p.key, callback_data: `d:${d.id}:p:${p.id}` }));
|
||||
const more = projects.length > 12 ? "\nНет нужного — напиши заново с ключом: «KEY: …»." : "";
|
||||
await show(d.chatId, `📝 Новая стори ${storyLine(d)}\nВ какой проект?${more}`, [...rows(buttons, 3), cancelRow(d)], editId);
|
||||
const text = [tr("📝 Новая стори {story}", { story: storyLine(d) }), tr("В какой проект?"), projects.length > 12 ? tr("Нет нужного — напиши заново с ключом: «KEY: …».") : null];
|
||||
await show(d.chatId, text.filter((l) => l != null).join("\n"), [...rows(buttons, 3), cancelRow(d)], editId);
|
||||
}
|
||||
|
||||
async function askEpic(d: Draft, project: Project, editId?: number) {
|
||||
const epics = (await listGoals(db, project.id)).slice(0, 10);
|
||||
const buttons = epics.length
|
||||
? [...epics.map((g) => ({ text: g.title.slice(0, 40), callback_data: `d:${d.id}:g:${g.id}` })), { text: "Без эпика", callback_data: `d:${d.id}:g:0` }]
|
||||
: [{ text: `✅ Создать в ${project.key}`, callback_data: `d:${d.id}:g:0` }];
|
||||
await show(d.chatId, `📝 Новая стори в <b>${esc(project.key)}</b>: ${storyLine(d)}${epics.length ? "\nЭпик?" : ""}`, [...rows(buttons), cancelRow(d)], editId);
|
||||
? [...epics.map((g) => ({ text: g.title.slice(0, 40), callback_data: `d:${d.id}:g:${g.id}` })), { text: tr("Без эпика"), callback_data: `d:${d.id}:g:0` }]
|
||||
: [{ text: tr("✅ Создать в {key}", { key: project.key }), callback_data: `d:${d.id}:g:0` }];
|
||||
const text = tr("📝 Новая стори в <b>{key}</b>: {story}", { key: esc(project.key), story: storyLine(d) }) + (epics.length ? "\n" + tr("Эпик?") : "");
|
||||
await show(d.chatId, text, [...rows(buttons), cancelRow(d)], editId);
|
||||
}
|
||||
|
||||
/** A plain message (or a transcribed voice note) → a draft and the next question. */
|
||||
async function startStory(user: User, chatId: number, text: string, voice: boolean) {
|
||||
const projects = await listUserProjects(db, user.id);
|
||||
if (!projects.length) return reply(chatId, `У тебя пока нет проектов — создай первый: ${esc(o.webUrl)}/projects/new`);
|
||||
if (!projects.length) return reply(chatId, tr("У тебя пока нет проектов — создай первый: {url}/projects/new", { url: esc(o.webUrl) }));
|
||||
const parsed = parseStoryText(text, projects);
|
||||
if (!parsed.body) return reply(chatId, "Пустая стори — напиши, что сделать.");
|
||||
if (!parsed.body) return reply(chatId, tr("Пустая стори — напиши, что сделать."));
|
||||
const project = parsed.project ?? (projects.length === 1 ? projects[0]! : null);
|
||||
const d = await saveDraft(db, { userId: user.id, chatId, text: parsed.body, projectId: project?.id ?? null, voice });
|
||||
if (project) await askEpic(d, project);
|
||||
@ -471,20 +478,20 @@ export function createBot(o: BotOptions) {
|
||||
async function onVoice(user: User, m: TgMessage) {
|
||||
const f = m.voice ?? m.audio!;
|
||||
const cfg = transcribeConfig();
|
||||
if (!cfg) return reply(m.chat.id, "Голосовые пока не настроены — напиши задачу текстом.", m.message_id);
|
||||
if ((f.duration ?? 0) > VOICE_MAX_SEC) return reply(m.chat.id, `Слишком длинное голосовое (больше ${VOICE_MAX_SEC / 60} минут) — запиши короче или напиши текстом.`, m.message_id);
|
||||
if (!cfg) return reply(m.chat.id, tr("Голосовые пока не настроены — напиши задачу текстом."), m.message_id);
|
||||
if ((f.duration ?? 0) > VOICE_MAX_SEC) return reply(m.chat.id, tr("Слишком длинное голосовое (больше {n} минут) — запиши короче или напиши текстом.", { n: VOICE_MAX_SEC / 60 }), m.message_id);
|
||||
let text: string;
|
||||
try {
|
||||
const file = await api.getFile(f.file_id);
|
||||
if (!file.file_path) throw new TranscribeError("Telegram не отдал файл");
|
||||
if (!file.file_path) throw new TranscribeError(tr("Telegram не отдал файл"));
|
||||
const audio = await api.downloadFile(file.file_path);
|
||||
text = await transcribe(cfg, audio, file.file_path.split("/").pop() || "voice.ogg", f.mime_type ?? "audio/ogg");
|
||||
} catch (e) {
|
||||
log(`voice: ${(e as Error).message}`);
|
||||
return reply(m.chat.id, `Не получилось расшифровать голосовое (${esc((e as Error).message)}). Напиши текстом.`, m.message_id);
|
||||
return reply(m.chat.id, tr("Не получилось расшифровать голосовое ({error}). Напиши текстом.", { error: esc((e as Error).message) }), m.message_id);
|
||||
}
|
||||
if (!text) return reply(m.chat.id, "Не разобрал ни слова — попробуй ещё раз или напиши текстом.", m.message_id);
|
||||
await reply(m.chat.id, `🎙 Расслышал: «${esc(text)}»`, m.message_id);
|
||||
if (!text) return reply(m.chat.id, tr("Не разобрал ни слова — попробуй ещё раз или напиши текстом."), m.message_id);
|
||||
await reply(m.chat.id, tr("🎙 Расслышал: «{text}»", { text: esc(text) }), m.message_id);
|
||||
await startStory(user, m.chat.id, text, true);
|
||||
}
|
||||
|
||||
@ -494,63 +501,63 @@ export function createBot(o: BotOptions) {
|
||||
const chatId = c.message!.chat.id;
|
||||
if (parts[0] === "t") {
|
||||
const [t] = await db.select().from(tasks).where(eq(tasks.id, Number(parts[1])));
|
||||
if (!t || !(await canAccess(user, t.projectId))) return "Стори не найдена";
|
||||
if (!t || !(await canAccess(user, t.projectId))) return tr("Стори не найдена");
|
||||
const [project] = await db.select().from(projects).where(eq(projects.id, t.projectId));
|
||||
const ref = { project: project!, task: t, key: formatTaskKey(project!.key, t.number) };
|
||||
const head = `📥 ${esc(ref.key)}: ${esc(t.title)}\n${esc(o.webUrl)}/t/${esc(ref.key)}`;
|
||||
if (parts[2] === "keep") {
|
||||
await show(chatId, `${head}\nВ бэклоге.`, [], msgId);
|
||||
return "Оставил в бэклоге";
|
||||
await show(chatId, head + "\n" + tr("В бэклоге."), [], msgId);
|
||||
return tr("Оставил в бэклоге");
|
||||
}
|
||||
if (parts[2] !== "start") return "Неизвестная кнопка";
|
||||
if (parts[2] !== "start") return tr("Неизвестная кнопка");
|
||||
if (t.status !== "backlog") {
|
||||
await show(chatId, `${head}\nУже не в бэклоге (${esc(t.status)}).`, [], msgId);
|
||||
return `${ref.key} уже ${t.status}`;
|
||||
await show(chatId, head + "\n" + tr("Уже не в бэклоге ({status}).", { status: esc(t.status) }), [], msgId);
|
||||
return tr("{key} уже {status}", { key: ref.key, status: t.status });
|
||||
}
|
||||
try {
|
||||
await moveTask(db, ref, "in_progress");
|
||||
} catch (e) {
|
||||
return (e as Error).message;
|
||||
}
|
||||
await show(chatId, `${head}\n▶️ В работе — агент взялся.`, [], msgId);
|
||||
return `${ref.key}: агент взялся ▶️`;
|
||||
await show(chatId, head + "\n" + tr("▶️ В работе — агент взялся."), [], msgId);
|
||||
return tr("{key}: агент взялся ▶️", { key: ref.key });
|
||||
}
|
||||
const d = await loadDraft(db, Number(parts[1]), user.id);
|
||||
if (!d) {
|
||||
await show(chatId, "Черновик не найден или устарел — напиши заново.", [], msgId);
|
||||
return "Черновик устарел";
|
||||
await show(chatId, tr("Черновик не найден или устарел — напиши заново."), [], msgId);
|
||||
return tr("Черновик устарел");
|
||||
}
|
||||
if (parts[2] === "x") {
|
||||
await dropDraft(db, d.id);
|
||||
await show(chatId, `✖️ Отменено: ${storyLine(d)}`, [], msgId);
|
||||
return "Отменено";
|
||||
await show(chatId, tr("✖️ Отменено: {story}", { story: storyLine(d) }), [], msgId);
|
||||
return tr("Отменено");
|
||||
}
|
||||
if (parts[2] === "p") {
|
||||
const projectId = Number(parts[3]);
|
||||
const project = await projectForUser(db, user.id, projectId).catch(() => null);
|
||||
if (!project) return "Проект не найден";
|
||||
if (!project) return tr("Проект не найден");
|
||||
await updateDraft(db, { ...d, projectId });
|
||||
await askEpic(d, project, msgId);
|
||||
return project.key;
|
||||
}
|
||||
if (parts[2] === "g" && d.projectId) {
|
||||
const project = await projectForUser(db, user.id, d.projectId).catch(() => null);
|
||||
if (!project) return "Проект не найден";
|
||||
if (!project) return tr("Проект не найден");
|
||||
const goalId = Number(parts[3]) || undefined;
|
||||
if (goalId && !(await getGoal(db, project.id, goalId).catch(() => null))) return "Эпик не найден";
|
||||
if (goalId && !(await getGoal(db, project.id, goalId).catch(() => null))) return tr("Эпик не найден");
|
||||
const { title, rest } = splitStory(d.text);
|
||||
const from = `Создано из Telegram (${user.login}${d.voice ? ", расшифровка голосового" : ""}).`;
|
||||
const from = d.voice ? tr("Создано из Telegram ({login}, расшифровка голосового).", { login: user.login }) : tr("Создано из Telegram ({login}).", { login: user.login });
|
||||
const ref = await createTask(db, { projectId: project.id, goalId, title, description: `${rest ? `${rest}\n\n` : ""}${from}` });
|
||||
await dropDraft(db, d.id);
|
||||
await show(
|
||||
chatId,
|
||||
`📥 Создал <b>${esc(ref.key)}</b>: ${esc(title)}\n${esc(o.webUrl)}/t/${esc(ref.key)}\nВзять в работу сейчас?`,
|
||||
[[{ text: "▶️ Взять в работу", callback_data: `t:${ref.task.id}:start` }, { text: "Оставить в бэклоге", callback_data: `t:${ref.task.id}:keep` }]],
|
||||
[tr("📥 Создал <b>{key}</b>: {title}", { key: esc(ref.key), title: esc(title) }), `${esc(o.webUrl)}/t/${esc(ref.key)}`, tr("Взять в работу сейчас?")].join("\n"),
|
||||
[[{ text: tr("▶️ Взять в работу"), callback_data: `t:${ref.task.id}:start` }, { text: tr("Оставить в бэклоге"), callback_data: `t:${ref.task.id}:keep` }]],
|
||||
msgId,
|
||||
);
|
||||
return `Создал ${ref.key}`;
|
||||
return tr("Создал {key}", { key: ref.key });
|
||||
}
|
||||
return "Неизвестная кнопка";
|
||||
return tr("Неизвестная кнопка");
|
||||
}
|
||||
|
||||
/** A message in a group (PEP-62): linking by code, then replies and commands of the linked chat. */
|
||||
@ -558,11 +565,18 @@ export function createBot(o: BotOptions) {
|
||||
const text = m.text?.trim() ?? "";
|
||||
const link = /^\/(?:start|link)(?:@\w+)?\s+(\S+)$/.exec(text);
|
||||
if (link) {
|
||||
if (!isChatLinkCode(link[1]!)) return reply(m.chat.id, "Это не код связки чата. Получи код в вебе: Чаты → «Связать с Telegram».").then(() => "done");
|
||||
if (!isChatLinkCode(link[1]!)) return reply(m.chat.id, tr("Это не код связки чата. Получи код в вебе: Чаты → «Связать с Telegram».")).then(() => "done");
|
||||
const chat = await acceptChatLink(db, o.secret, link[1]!, { tgChatId: m.chat.id, title: m.chat.title ?? null });
|
||||
if (!chat) return reply(m.chat.id, "Код связки неверный или истёк — получи новый в вебе: Чаты → «Связать с Telegram».").then(() => "done");
|
||||
const name = chat.projectId ? `чатом проекта ${esc(await projectKey(chat.projectId))}` : "мастер-чатом";
|
||||
await reply(m.chat.id, `Группа связана с ${name} ✅\n\nСюда будут приходить события и вопросы агентов, треды — цепочками ответов. Ответь <b>реплаем</b> — сообщение уйдёт в тред (в треде стори — агенту). Отвечать могут те, кто привязал Telegram в Пеппе и имеет доступ к проекту. /help — команды.`);
|
||||
if (!chat) return reply(m.chat.id, tr("Код связки неверный или истёк — получи новый в вебе: Чаты → «Связать с Telegram».")).then(() => "done");
|
||||
const name = chat.projectId ? tr("чатом проекта {key}", { key: esc(await projectKey(chat.projectId)) }) : tr("мастер-чатом");
|
||||
await reply(
|
||||
m.chat.id,
|
||||
[
|
||||
tr("Группа связана с {name} ✅", { name }),
|
||||
"",
|
||||
tr("Сюда будут приходить события и вопросы агентов, треды — цепочками ответов. Ответь <b>реплаем</b> — сообщение уйдёт в тред (в треде стори — агенту). Отвечать могут те, кто привязал Telegram в Пеппе и имеет доступ к проекту. /help — команды."),
|
||||
].join("\n"),
|
||||
);
|
||||
return "done";
|
||||
}
|
||||
const chat = await chatByTelegram(db, m.chat.id);
|
||||
@ -571,7 +585,7 @@ export function createBot(o: BotOptions) {
|
||||
if (!m.reply_to_message && !text.startsWith("/")) return "ignored";
|
||||
const user = await telegramAccountUser(db, m.from.id);
|
||||
if (!user || !(await mayWriteChat(db, user, chat))) {
|
||||
await reply(m.chat.id, user ? "У тебя нет доступа к этому чату." : `Не знаю тебя в Пеппе — привяжи Telegram: ${esc(o.webUrl)}/settings → Telegram.`, m.message_id);
|
||||
await reply(m.chat.id, user ? tr("У тебя нет доступа к этому чату.") : tr("Не знаю тебя в Пеппе — привяжи Telegram: {url}/settings → Telegram.", { url: esc(o.webUrl) }), m.message_id);
|
||||
return "done";
|
||||
}
|
||||
enterActor({ kind: "user", userId: user.id, channel: "telegram" });
|
||||
@ -605,11 +619,11 @@ export function createBot(o: BotOptions) {
|
||||
const b = await acceptPairing(db, o.secret, start[1], { chatId: m.chat.id, userId: m.from.id, username: m.from.username, botUserId: via.getStore()?.userId });
|
||||
if (b) {
|
||||
await syncOwnBots().catch(() => {}); // the chat now belongs to this bot
|
||||
await reply(m.chat.id, `Привязано ✅\n\n${HELP}`);
|
||||
await reply(m.chat.id, tr("Привязано ✅") + "\n\n" + HELP);
|
||||
scheduleReconcile();
|
||||
return "done";
|
||||
}
|
||||
await reply(m.chat.id, `Код привязки неверный или истёк. Получи новый: ${esc(o.webUrl)}/settings → Telegram`);
|
||||
await reply(m.chat.id, tr("Код привязки неверный или истёк. Получи новый: {url}/settings → Telegram", { url: esc(o.webUrl) }));
|
||||
return "done";
|
||||
}
|
||||
const user = m.from ? await telegramUser(db, m.chat.id, m.from.id) : null;
|
||||
@ -624,14 +638,14 @@ export function createBot(o: BotOptions) {
|
||||
if (/^\/status\b/.test(text)) return reply(m.chat.id, await status(user)).then(() => "done");
|
||||
if (/^\/digest\b/.test(text)) {
|
||||
const d = await buildDigest(db, user);
|
||||
await api.sendMessage(m.chat.id, renderDigest(d, { webUrl: o.webUrl, title: "Сводка за сутки" }), { link_preview_options: { is_disabled: true } }).catch((e) => log(`digest: ${e.message}`));
|
||||
await api.sendMessage(m.chat.id, renderDigest(d, { webUrl: o.webUrl, title: tr("Сводка за сутки") }), { link_preview_options: { is_disabled: true } }).catch((e) => log(`digest: ${e.message}`));
|
||||
return "done";
|
||||
}
|
||||
|
||||
if (m.reply_to_message) {
|
||||
const q = await questionByTelegramMessage(db, m.chat.id, m.reply_to_message.message_id);
|
||||
if (!q || !(await canAccess(user, q.projectId))) {
|
||||
await reply(m.chat.id, "Не нашёл вопрос для этого сообщения.", m.message_id);
|
||||
await reply(m.chat.id, tr("Не нашёл вопрос для этого сообщения."), m.message_id);
|
||||
return "done";
|
||||
}
|
||||
await reply(m.chat.id, esc(await answer(q, text)), m.message_id);
|
||||
@ -642,7 +656,7 @@ export function createBot(o: BotOptions) {
|
||||
return "done";
|
||||
}
|
||||
if (!text || text.startsWith("/")) {
|
||||
await reply(m.chat.id, "Чтобы ответить агенту, ответь <b>реплаем</b> на его сообщение. Чтобы завести стори — просто напиши её. /help — что я умею.");
|
||||
await reply(m.chat.id, tr("Чтобы ответить агенту, ответь <b>реплаем</b> на его сообщение. Чтобы завести стори — просто напиши её. /help — что я умею."));
|
||||
return "done";
|
||||
}
|
||||
// PEP-45: any other text is a new story (created only after a button press).
|
||||
@ -659,32 +673,32 @@ export function createBot(o: BotOptions) {
|
||||
if (chat && who && (chat.kind === "project" || chat.userId === who.id)) user = who;
|
||||
}
|
||||
if (!user) {
|
||||
await api.answerCallbackQuery(c.id, "Нет доступа").catch(() => {});
|
||||
await api.answerCallbackQuery(c.id, tr("Нет доступа")).catch(() => {});
|
||||
return "ignored";
|
||||
}
|
||||
enterActor({ kind: "user", userId: user.id, channel: "telegram" });
|
||||
const parts = (c.data ?? "").split(":");
|
||||
if (parts[0] === "d" || parts[0] === "t") {
|
||||
const toast = await onStoryButton(user, c, parts).catch((e) => (log(`story: ${(e as Error).stack ?? e}`), "Ошибка"));
|
||||
const toast = await onStoryButton(user, c, parts).catch((e) => (log(`story: ${(e as Error).stack ?? e}`), tr("Ошибка")));
|
||||
await api.answerCallbackQuery(c.id, toast.slice(0, 190)).catch((e) => log(`answerCallbackQuery: ${e.message}`));
|
||||
return "done";
|
||||
}
|
||||
const [kind, idStr, choice] = parts;
|
||||
const id = Number(idStr);
|
||||
let toast = "Неизвестная кнопка";
|
||||
let toast = tr("Неизвестная кнопка");
|
||||
const q0 = kind === "q" ? await getQuestion(db, id).catch(() => null) : null;
|
||||
const s0 = kind === "s" ? await getSession(db, id).catch(() => null) : null;
|
||||
const i0 = kind === "i" ? await getIncident(db, id).catch(() => null) : null;
|
||||
const projectId = q0?.projectId ?? s0?.projectId ?? i0?.projectId;
|
||||
if (projectId == null || !(await canAccess(user, projectId))) {
|
||||
// Unknown or someone else's question/session: don't reveal which.
|
||||
await api.answerCallbackQuery(c.id, kind === "s" ? "Сессия не найдена" : kind === "i" ? "Ошибка не найдена" : "Вопрос не найден").catch(() => {});
|
||||
await api.answerCallbackQuery(c.id, kind === "s" ? tr("Сессия не найдена") : kind === "i" ? tr("Ошибка не найдена") : tr("Вопрос не найден")).catch(() => {});
|
||||
return "done";
|
||||
}
|
||||
if (kind === "q" && choice === "accept") {
|
||||
try {
|
||||
const ref = await acceptTask(db, id, "telegram");
|
||||
toast = `${ref.key} принята ✅`;
|
||||
toast = tr("{key} принята ✅", { key: ref.key });
|
||||
} catch (e) {
|
||||
toast = (e as Error).message;
|
||||
}
|
||||
@ -692,29 +706,29 @@ export function createBot(o: BotOptions) {
|
||||
} else if (kind === "q") {
|
||||
const q = await getQuestion(db, id).catch(() => null);
|
||||
const text = q && choice ? choiceToAnswer(q, choice) : null;
|
||||
toast = q && text ? await answer(q, text) : "Вопрос не найден";
|
||||
toast = q && text ? await answer(q, text) : tr("Вопрос не найден");
|
||||
} else if (kind === "i" && (choice === "backlog" || choice === "start" || choice === "ignore")) {
|
||||
// Decision on a new production error (PEP-58).
|
||||
try {
|
||||
const r = await decideIncident(db, id, choice, user.login);
|
||||
toast = r.task ? `${r.task.key}: ${choice === "start" ? "агент взялся ▶️" : "в бэклоге 📥"}` : "Игнорируем 🙈";
|
||||
toast = r.task ? (choice === "start" ? tr("{key}: агент взялся ▶️", { key: r.task.key }) : tr("{key}: в бэклоге 📥", { key: r.task.key })) : tr("Игнорируем 🙈");
|
||||
} catch (e) {
|
||||
toast = (e as Error).message;
|
||||
}
|
||||
wakeOutbox?.();
|
||||
} else if (kind === "s") {
|
||||
const s = await getSession(db, id).catch(() => null);
|
||||
if (!s) toast = "Сессия не найдена";
|
||||
if (!s) toast = tr("Сессия не найдена");
|
||||
else if (choice === "resume") {
|
||||
try {
|
||||
const r = await resumeSession(db, s.id);
|
||||
toast = `Перезапущено (поколение ${r.generation}) 🔁`;
|
||||
toast = tr("Перезапущено (поколение {n}) 🔁", { n: r.generation });
|
||||
} catch (e) {
|
||||
toast = (e as Error).message;
|
||||
}
|
||||
} else if (choice === "stop") {
|
||||
await stopSession(db, s.id);
|
||||
toast = "Сессия остановлена ⏹";
|
||||
toast = tr("Сессия остановлена ⏹");
|
||||
}
|
||||
scheduleReconcile();
|
||||
}
|
||||
|
||||
@ -1,15 +1,17 @@
|
||||
// Telegram message texts and buttons for PM questions. HTML parse mode.
|
||||
import type { Question, SessionView } from "@peppa/core";
|
||||
import type { InlineButton } from "./telegram.ts";
|
||||
import { m as tr } from "@peppa/shared/i18n";
|
||||
|
||||
export const esc = (s: string) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
||||
const italic = (s: string) => `<i>${s}</i>`;
|
||||
const clip = (s: string, n: number) => (s.length > n ? `${s.slice(0, n)}…` : s);
|
||||
|
||||
const KIND: Record<Question["kind"], string> = {
|
||||
approval: "📝 Нужно одобрение proposal",
|
||||
question: "❓ Вопрос",
|
||||
permission: "🔐 Нужно разрешение",
|
||||
attention: "👀 Сессия ждёт тебя",
|
||||
approval: tr("📝 Нужно одобрение proposal"),
|
||||
question: tr("❓ Вопрос"),
|
||||
permission: tr("🔐 Нужно разрешение"),
|
||||
attention: tr("👀 Сессия ждёт тебя"),
|
||||
};
|
||||
|
||||
export interface Rendered {
|
||||
@ -22,7 +24,7 @@ export function renderQuestion(
|
||||
q: Question,
|
||||
ctx: { taskKey: string | null; taskTitle: string | null; taskStatus?: string | null; session: SessionView | null; webUrl: string },
|
||||
): Rendered {
|
||||
const head = [`<b>${esc(ctx.taskKey ?? (q.sessionId ? `Сессия ${q.sessionId}` : "Релизы проекта"))}</b>`, ctx.taskTitle ? `<i>${esc(clip(ctx.taskTitle, 80))}</i>` : null]
|
||||
const head = ["<b>" + esc(ctx.taskKey ?? (q.sessionId ? tr("Сессия {id}", { id: q.sessionId }) : tr("Релизы проекта"))) + "</b>", ctx.taskTitle ? `<i>${esc(clip(ctx.taskTitle, 80))}</i>` : null]
|
||||
.filter(Boolean)
|
||||
.join(" · ");
|
||||
const body = esc(clip(q.text, 3300));
|
||||
@ -30,31 +32,31 @@ export function renderQuestion(
|
||||
|
||||
const buttons: InlineButton[][] = [];
|
||||
if (q.kind === "approval") {
|
||||
buttons.push([{ text: "✅ Одобрить", callback_data: `q:${q.id}:approve` }]);
|
||||
lines.push("", "<i>Чтобы вернуть на доработку — ответь на это сообщение комментарием.</i>");
|
||||
buttons.push([{ text: tr("✅ Одобрить"), callback_data: `q:${q.id}:approve` }]);
|
||||
lines.push("", italic(tr("Чтобы вернуть на доработку — ответь на это сообщение комментарием.")));
|
||||
} else if (q.kind === "permission") {
|
||||
buttons.push([
|
||||
{ text: "✅ Разрешить", callback_data: `q:${q.id}:allow` },
|
||||
{ text: "♾ Всегда", callback_data: `q:${q.id}:always` },
|
||||
{ text: "⛔ Запретить", callback_data: `q:${q.id}:deny` },
|
||||
{ text: tr("✅ Разрешить"), callback_data: `q:${q.id}:allow` },
|
||||
{ text: tr("♾ Всегда"), callback_data: `q:${q.id}:always` },
|
||||
{ text: tr("⛔ Запретить"), callback_data: `q:${q.id}:deny` },
|
||||
]);
|
||||
} else if (q.kind === "question") {
|
||||
(q.options ?? []).slice(0, 6).forEach((o, i) => buttons.push([{ text: clip(o, 60), callback_data: `q:${q.id}:o${i}` }]));
|
||||
lines.push("", "<i>Выбери вариант или ответь на это сообщение своим текстом.</i>");
|
||||
lines.push("", italic(tr("Выбери вариант или ответь на это сообщение своим текстом.")));
|
||||
} else if (ctx.taskStatus === "review") {
|
||||
lines[1] = "✅ Готово к ревью";
|
||||
buttons.push([{ text: "✅ Принять", callback_data: `q:${q.id}:accept` }]);
|
||||
lines.push("", "<i>Есть замечания — ответь на это сообщение, агент доработает.</i>");
|
||||
lines[1] = tr("✅ Готово к ревью");
|
||||
buttons.push([{ text: tr("✅ Принять"), callback_data: `q:${q.id}:accept` }]);
|
||||
lines.push("", italic(tr("Есть замечания — ответь на это сообщение, агент доработает.")));
|
||||
} else {
|
||||
const s = ctx.session;
|
||||
if (s && ["failed", "rate_limited", "stalled"].includes(s.status)) {
|
||||
buttons.push([
|
||||
{ text: "🔁 Перезапустить", callback_data: `s:${s.id}:resume` },
|
||||
{ text: "⏹ Остановить", callback_data: `s:${s.id}:stop` },
|
||||
{ text: tr("🔁 Перезапустить"), callback_data: `s:${s.id}:resume` },
|
||||
{ text: tr("⏹ Остановить"), callback_data: `s:${s.id}:stop` },
|
||||
]);
|
||||
} else {
|
||||
buttons.push([{ text: "▶️ Продолжай", callback_data: `q:${q.id}:cont` }]);
|
||||
lines.push("", "<i>Или ответь на это сообщение — текст уйдёт в сессию.</i>");
|
||||
buttons.push([{ text: tr("▶️ Продолжай"), callback_data: `q:${q.id}:cont` }]);
|
||||
lines.push("", italic(tr("Или ответь на это сообщение — текст уйдёт в сессию.")));
|
||||
}
|
||||
}
|
||||
if (ctx.session) lines.push(`<code>tmux attach -t ${esc(ctx.session.tmuxName)}</code>`);
|
||||
@ -64,15 +66,16 @@ export function renderQuestion(
|
||||
/** Text after the question is closed: original + who answered what, no buttons. */
|
||||
export function renderAnswered(original: string, q: Question): string {
|
||||
const mark = q.answeredVia === "system" ? "⌛" : "✅";
|
||||
const via = { telegram: "в Telegram", web: "в вебе", terminal: "в терминале", system: "" }[q.answeredVia ?? "telegram"];
|
||||
return `${original}\n\n${mark} ${q.answeredVia === "system" ? esc(q.answer ?? "") : `Ответ ${via}: <b>${esc(clip(q.answer ?? "", 500))}</b>`}`;
|
||||
const via = { telegram: tr("в Telegram"), web: tr("в вебе"), terminal: tr("в терминале"), system: "" }[q.answeredVia ?? "telegram"];
|
||||
const said = q.answeredVia === "system" ? esc(q.answer ?? "") : tr("Ответ {via}: <b>{answer}</b>", { via, answer: esc(clip(q.answer ?? "", 500)) });
|
||||
return `${original}\n\n${mark} ${said}`;
|
||||
}
|
||||
|
||||
/** The answer text a button stands for. */
|
||||
export function choiceToAnswer(q: Question, choice: string): string | null {
|
||||
if (q.kind === "approval" && choice === "approve") return "ок";
|
||||
if (q.kind === "approval" && choice === "approve") return "ок"; // i18n-ignore: the answer goes to the agent
|
||||
if (q.kind === "permission" && ["allow", "always", "deny"].includes(choice)) return choice;
|
||||
if (q.kind === "attention" && choice === "cont") return "Продолжай.";
|
||||
if (q.kind === "attention" && choice === "cont") return "Продолжай."; // i18n-ignore: the answer goes to the agent
|
||||
const m = /^o(\d+)$/.exec(choice);
|
||||
if (q.kind === "question" && m) return q.options?.[Number(m[1])] ?? null;
|
||||
return null;
|
||||
|
||||
@ -4,6 +4,7 @@
|
||||
// OpenAI (https://api.openai.com/v1, whisper-1), Groq (https://api.groq.com/openai/v1,
|
||||
// whisper-large-v3), a local faster-whisper/speaches server — all speak this. Tests use
|
||||
// mock-transcribe (packages/testkit).
|
||||
import { m as tr } from "@peppa/shared/i18n";
|
||||
|
||||
export interface TranscribeConfig {
|
||||
url: string;
|
||||
@ -41,12 +42,12 @@ export async function transcribe(cfg: TranscribeConfig, audio: Buffer, filename
|
||||
signal: AbortSignal.timeout(120_000),
|
||||
});
|
||||
} catch (e) {
|
||||
throw new TranscribeError(`сервис расшифровки недоступен: ${(e as Error).message}`);
|
||||
throw new TranscribeError(tr("сервис расшифровки недоступен: {error}", { error: (e as Error).message }));
|
||||
}
|
||||
const body = (await res.json().catch(() => ({}))) as { text?: string; error?: { message?: string } | string };
|
||||
if (!res.ok) {
|
||||
const msg = typeof body.error === "string" ? body.error : body.error?.message;
|
||||
throw new TranscribeError(`расшифровка не удалась: ${res.status}${msg ? ` ${msg}` : ""}`);
|
||||
throw new TranscribeError(tr("расшифровка не удалась: {status}", { status: `${res.status}${msg ? ` ${msg}` : ""}` }));
|
||||
}
|
||||
return (body.text ?? "").trim();
|
||||
}
|
||||
|
||||
@ -66,6 +66,7 @@ import { redirect } from "next/navigation";
|
||||
import { asWebActor, requireUser } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import { m, PRODUCT_NAME } from "@peppa/shared/i18n";
|
||||
|
||||
const str = (f: FormData, k: string) => String(f.get(k) ?? "").trim();
|
||||
const back = (f: FormData) => str(f, "back") || "/";
|
||||
@ -106,8 +107,8 @@ export async function answerQuestion(f: FormData) {
|
||||
const q = await getQuestion(db, Number(str(f, "questionId")));
|
||||
await projectForUser(db, user.id, q.projectId);
|
||||
const answer = str(f, "choice") || str(f, "answer");
|
||||
if (!answer) throw new PeppaError("Пустой ответ");
|
||||
if (q.answeredAt) throw new PeppaError(`Уже отвечено${q.answeredVia === "system" ? "" : ` (${q.answeredVia})`}: ${q.answer}`);
|
||||
if (!answer) throw new PeppaError(m("Пустой ответ"));
|
||||
if (q.answeredAt) throw new PeppaError(q.answeredVia === "system" ? m("Уже отвечено: {answer}", { answer: q.answer }) : m("Уже отвечено ({via}): {answer}", { via: q.answeredVia, answer: q.answer }));
|
||||
if (answer === "__accept") {
|
||||
await acceptTask(db, q.id, "web");
|
||||
return;
|
||||
@ -120,7 +121,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(m("Нужно название стори"));
|
||||
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}`;
|
||||
@ -132,7 +133,7 @@ export async function addEpic(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").length < 2) throw new PeppaError("Нужно название эпика");
|
||||
if (str(f, "title").length < 2) throw new PeppaError(m("Нужно название эпика"));
|
||||
await createEpic(db, p.id, str(f, "title"), str(f, "description") || undefined);
|
||||
});
|
||||
}
|
||||
@ -146,7 +147,7 @@ export async function editEpic(f: FormData) {
|
||||
await updateEpic(db, p.id, id, { status: "archived" });
|
||||
return;
|
||||
}
|
||||
if (str(f, "title").length < 2) throw new PeppaError("Нужно название эпика");
|
||||
if (str(f, "title").length < 2) throw new PeppaError(m("Нужно название эпика"));
|
||||
await updateEpic(db, p.id, id, { title: str(f, "title"), description: str(f, "description") || null });
|
||||
});
|
||||
}
|
||||
@ -158,7 +159,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(m("Нужно название стори"));
|
||||
const epic = str(f, "epicId");
|
||||
await updateTask(db, ref, { title, description: String(f.get("description") ?? "").trim(), goalId: epic ? Number(epic) : null }, undefined, user.login);
|
||||
});
|
||||
@ -173,7 +174,8 @@ export async function commentStoryAction(f: FormData) {
|
||||
const c = await addStoryComment(db, ref, user, String(f.get("text") ?? ""));
|
||||
if (str(f, "toAgent")) {
|
||||
const [live] = await listSessions(db, { active: true, taskId: ref.task.id });
|
||||
if (!live) throw new PeppaError("Комментарий сохранён, но живой сессии нет — агент увидит его в get_task");
|
||||
if (!live) throw new PeppaError(m("Комментарий сохранён, но живой сессии нет — агент увидит его в get_task"));
|
||||
// i18n-ignore — text for the agent
|
||||
await sendToSession(db, live.id, `Комментарий PM (${user.login}) к ${ref.key}:\n${c.text}`);
|
||||
}
|
||||
});
|
||||
@ -193,7 +195,7 @@ export async function acceptStoryAction(f: FormData) {
|
||||
async function launchChoice(f: FormData, user: Awaited<ReturnType<typeof requireUser>>) {
|
||||
const choice = (await isSuperadmin(db, user)) ? str(f, "choice") : "";
|
||||
const subscriptionIds = choice === "pick" ? f.getAll("subscription").map(Number).filter((n) => n > 0) : undefined;
|
||||
if (choice === "pick" && !subscriptionIds?.length) throw new PeppaError("Отметьте хотя бы одну подписку");
|
||||
if (choice === "pick" && !subscriptionIds?.length) throw new PeppaError(m("Отметьте хотя бы одну подписку"));
|
||||
const poolId = choice.startsWith("pool:") ? Number(choice.slice(5)) : undefined;
|
||||
const provider = str(f, "provider") as Provider | "";
|
||||
return { provider: provider || undefined, subscriptionIds, poolId };
|
||||
@ -309,7 +311,7 @@ export async function messageSession(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const s = await ownedSession(user.id, Number(str(f, "sessionId")));
|
||||
if (!str(f, "text")) throw new PeppaError("Пустое сообщение");
|
||||
if (!str(f, "text")) throw new PeppaError(m("Пустое сообщение"));
|
||||
await sendToSession(db, s.id, str(f, "text"));
|
||||
});
|
||||
}
|
||||
@ -344,7 +346,7 @@ export async function moveTaskCard(f: FormData) {
|
||||
const ref = await resolveTask(db, str(f, "taskKey"));
|
||||
await projectForUser(db, user.id, ref.project.id);
|
||||
const to = str(f, "to") as BoardColumn;
|
||||
if (!["backlog", "in_progress", "review", "done"].includes(to)) throw new PeppaError("Неизвестная колонка");
|
||||
if (!["backlog", "in_progress", "review", "done"].includes(to)) throw new PeppaError(m("Неизвестная колонка"));
|
||||
await moveTask(db, ref, to);
|
||||
});
|
||||
}
|
||||
@ -362,7 +364,7 @@ export async function addProjectMember(f: FormData) {
|
||||
await attempt(f, async () => {
|
||||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||||
const r = await shareProject(db, user, p, str(f, "login"));
|
||||
if (!r.repoAccess) throw new PeppaError(`${r.login} добавлен, но доступ к репозиторию в Gitea выдать не удалось — добавьте соавтора в Gitea вручную`);
|
||||
if (!r.repoAccess) throw new PeppaError(m("{login} добавлен, но доступ к репозиторию в Gitea выдать не удалось — добавьте соавтора в Gitea вручную", { login: r.login }));
|
||||
});
|
||||
}
|
||||
|
||||
@ -371,7 +373,7 @@ export async function grantRepoAccessToMembers(f: FormData) {
|
||||
await attempt(f, async () => {
|
||||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||||
const r = await grantRepoAccess(db, user, p);
|
||||
if (r.failed.length) throw new PeppaError(`Не удалось выдать доступ к репозиторию: ${r.failed.join(", ")} — нет прав администратора в Gitea, добавьте соавторов вручную`);
|
||||
if (r.failed.length) throw new PeppaError(m("Не удалось выдать доступ к репозиторию: {logins} — нет прав администратора в Gitea, добавьте соавторов вручную", { logins: r.failed.join(", ") }));
|
||||
});
|
||||
}
|
||||
|
||||
@ -427,7 +429,7 @@ export async function pairTelegram(f: FormData) {
|
||||
const token = loadEnv().TELEGRAM_BOT_TOKEN;
|
||||
// PEP-85: the user's own bot if they connected one, else the platform's shared bot.
|
||||
const username = user.telegramBotUsername ?? (await getSetting<{ username: string }>(db, "telegram.bot"))?.username;
|
||||
if (!token || !username) throw new PeppaError("Telegram-бот Пеппы не запущен");
|
||||
if (!token || !username) throw new PeppaError(m("Telegram-бот Пеппы не запущен"));
|
||||
return `https://t.me/${username}?start=${await createPairingCode(db, token, user.id)}`;
|
||||
});
|
||||
}
|
||||
@ -457,7 +459,7 @@ export async function saveNotifyPrefsAction(f: FormData) {
|
||||
const events = { ...d.events };
|
||||
for (const e of NOTIFY_EVENTS) events[e] = { telegram: f.get(`${e}.telegram`) === "on", push: f.get(`${e}.push`) === "on" };
|
||||
const tz = str(f, "timezone") || cur.timezone;
|
||||
if (!isValidTimezone(tz)) throw new PeppaError(`Неизвестная таймзона: ${tz}`);
|
||||
if (!isValidTimezone(tz)) throw new PeppaError(m("Неизвестная таймзона: {tz}", { tz }));
|
||||
const shown = f.getAll("projectShown").map(Number);
|
||||
const enabled = new Set(f.getAll("project").map(Number));
|
||||
// Projects not on the form (no access any more) keep their old state.
|
||||
@ -497,9 +499,10 @@ export async function deletePushSubscriptionAction(endpoint: string) {
|
||||
export async function testPushAction(endpoint: string): Promise<{ ok: boolean; error?: string }> {
|
||||
const user = asWebActor(await requireUser());
|
||||
const sub = (await userPushSubscriptions(db, user.id)).find((s) => s.endpoint === endpoint);
|
||||
if (!sub) return { ok: false, error: "Этот браузер не подписан" };
|
||||
const t = await getT();
|
||||
if (!sub) return { ok: false, error: t("Этот браузер не подписан") };
|
||||
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: PRODUCT_NAME, body: t("Уведомления в этом браузере работают ✅"), 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 };
|
||||
@ -510,7 +513,7 @@ export async function testPushAction(endpoint: string): Promise<{ ok: boolean; e
|
||||
async function incidentInProject(userId: number, f: FormData) {
|
||||
const p = await projectForUser(db, userId, Number(str(f, "projectId")));
|
||||
const i = await getIncident(db, Number(str(f, "incidentId")));
|
||||
if (i.projectId !== p.id) throw new PeppaError("Не найдено");
|
||||
if (i.projectId !== p.id) throw new PeppaError(m("Не найдено"));
|
||||
return i;
|
||||
}
|
||||
|
||||
@ -518,7 +521,7 @@ export async function connectErrorTrackingAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||||
if (!(await managesProject(db, user, p))) throw new PeppaError("Подключает владелец проекта");
|
||||
if (!(await managesProject(db, user, p))) throw new PeppaError(m("Подключает владелец проекта"));
|
||||
await connectErrorTracking(db, p, bugsinkFromEnv(), bugsinkWebhookBase());
|
||||
});
|
||||
}
|
||||
@ -556,7 +559,7 @@ export async function decideIncidentAction(f: FormData) {
|
||||
await attempt(f, async () => {
|
||||
const i = await incidentInProject(user.id, f);
|
||||
const action = str(f, "action");
|
||||
if (action !== "backlog" && action !== "start" && action !== "ignore") throw new PeppaError("Неизвестное решение");
|
||||
if (action !== "backlog" && action !== "start" && action !== "ignore") throw new PeppaError(m("Неизвестное решение"));
|
||||
await decideIncident(db, i.id, action, user.login);
|
||||
});
|
||||
}
|
||||
@ -574,7 +577,7 @@ export async function resolveIncidentAction(f: FormData) {
|
||||
/** Superadmin-only actions: everybody else gets "not found", nothing changes. */
|
||||
async function requireSuperadmin() {
|
||||
const user = asWebActor(await requireUser());
|
||||
if (!(await isSuperadmin(db, user))) throw new PeppaError("Не найдено");
|
||||
if (!(await isSuperadmin(db, user))) throw new PeppaError(m("Не найдено"));
|
||||
return user;
|
||||
}
|
||||
|
||||
@ -584,8 +587,8 @@ export async function setUserDisabledAction(f: FormData) {
|
||||
await attempt(f, async () => {
|
||||
const admin = await requireSuperadmin();
|
||||
const u = await getUser(db, Number(str(f, "userId")));
|
||||
if (!u) throw new PeppaError("Не найдено");
|
||||
if (u.id === admin.id) throw new PeppaError("Нельзя отключить самого себя");
|
||||
if (!u) throw new PeppaError(m("Не найдено"));
|
||||
if (u.id === admin.id) throw new PeppaError(m("Нельзя отключить самого себя"));
|
||||
await setUserDisabled(db, u.id, str(f, "disabled") === "1");
|
||||
});
|
||||
}
|
||||
@ -602,7 +605,7 @@ export async function saveTaskBudgetAction(f: FormData) {
|
||||
const mode = str(f, "mode");
|
||||
const budget = mode === "inherit" ? null : mode === "unlimited" ? {} : budgetFrom(f);
|
||||
await setTaskBudget(db, ref.task.id, budget);
|
||||
await logEvent(db, { projectId: ref.project.id, taskId: ref.task.id, type: "budget_changed", payload: { budget: budget ?? "проекта" } });
|
||||
await logEvent(db, { projectId: ref.project.id, taskId: ref.task.id, type: "budget_changed", payload: { budget: budget ?? "проекта" } }); // i18n-ignore — stored value
|
||||
await budgetChanged(db, ref.task.id);
|
||||
});
|
||||
}
|
||||
@ -688,7 +691,7 @@ export async function connectOwnSubscriptionAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const kind = str(f, "kind") as OwnSubscriptionKind;
|
||||
if (!["claude_login", "claude", "codex_login", "codex_key", "existing"].includes(kind)) throw new PeppaError("Выберите, что подключить");
|
||||
if (!["claude_login", "claude", "codex_login", "codex_key", "existing"].includes(kind)) throw new PeppaError(m("Выберите, что подключить"));
|
||||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||||
await connectOwnSubscription(db, user, p, kind, String(f.get("secret") ?? ""));
|
||||
});
|
||||
|
||||
@ -8,6 +8,7 @@ import { revalidatePath } from "next/cache";
|
||||
import { redirect } from "next/navigation";
|
||||
import { requireUser } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
|
||||
const str = (f: FormData, k: string) => String(f.get(k) ?? "").trim();
|
||||
|
||||
@ -16,7 +17,7 @@ async function attempt(f: FormData, fn: () => Promise<string | void>): Promise<n
|
||||
try {
|
||||
target = (await fn()) || target;
|
||||
} catch (e) {
|
||||
const msg = e instanceof PeppaError ? e.message : `Ошибка: ${(e as Error).message}`;
|
||||
const msg = e instanceof PeppaError ? e.message : m("Ошибка: {message}", { message: (e as Error).message });
|
||||
const [path, query] = target.split("?");
|
||||
const params = new URLSearchParams(query);
|
||||
params.set("error", msg.slice(0, 300));
|
||||
@ -40,7 +41,7 @@ export async function reorderTaskCard(f: FormData) {
|
||||
const to = str(f, "to");
|
||||
if (to === "top" || to === "bottom") await reorderBoardTask(db, ref, { to });
|
||||
else if (to === "before" || to === "after") await reorderBoardTask(db, ref, { to, other: await ownedTask(user.id, str(f, "other")) });
|
||||
else throw new PeppaError("Неизвестное место");
|
||||
else throw new PeppaError(m("Неизвестное место"));
|
||||
});
|
||||
}
|
||||
|
||||
@ -84,7 +85,7 @@ export async function planEpicAction(f: FormData) {
|
||||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||||
const epic = await getEpic(db, p.id, Number(str(f, "epicId")));
|
||||
const r = await planEpic(db, p, epic.id, { wishes: str(f, "wishes") || null, by: user.login });
|
||||
if (!r.ok) throw new PeppaError(`Планировщик: ${r.error}`);
|
||||
if (!r.ok) throw new PeppaError(m("Планировщик: {error}", { error: r.error }));
|
||||
});
|
||||
}
|
||||
|
||||
@ -97,12 +98,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(m("Не выбрано ни одной стори"));
|
||||
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(m("Стори {i} зависит от №{d}, которую вы сняли — уберите зависимость или оставьте стори", { i, d }));
|
||||
return renum.get(d)!;
|
||||
});
|
||||
return { title: str(f, `title_${i}`), description: str(f, `description_${i}`), dependsOn: deps };
|
||||
|
||||
@ -1,4 +1,5 @@
|
||||
import Link from "next/link";
|
||||
import { PRODUCT_NAME } from "@peppa/shared/i18n";
|
||||
import { notFound } from "next/navigation";
|
||||
import { Bot, Hash, Link2, MessagesSquare, Send, Unlink, User as UserIcon } from "lucide-react";
|
||||
import { chatMessagesView, chatThreads, chatTtlMs, getSetting, listChats, masterFeed, syncChats, threadTitle, THREAD_KEY, type ChatMessageView, type Question } from "@peppa/core";
|
||||
@ -14,6 +15,7 @@ import { Textarea } from "@/components/ui/input";
|
||||
import { requireUser } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import { linkChatAction, postChatAction, unlinkChatAction } from "../actions";
|
||||
|
||||
type Params = { error?: string; thread?: string; link?: string };
|
||||
@ -23,6 +25,7 @@ const CHANNEL = "channel";
|
||||
/** «Чаты» (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 t = await getT();
|
||||
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).
|
||||
@ -35,7 +38,7 @@ export default async function ChatPage({ params, searchParams }: { params: Promi
|
||||
|
||||
const threads = master ? [] : await chatThreads(db, chat.id);
|
||||
const messages = master ? await masterFeed(db, user, { limit: 150 }) : await chatMessagesView(db, chat.id, { threadKey: thread, limit: 150 });
|
||||
const current = thread ? (threads.find((t) => t.key === thread)?.title ?? (await threadTitle(db, thread)) ?? thread) : null;
|
||||
const current = thread ? (threads.find((th) => th.key === thread)?.title ?? (await threadTitle(db, thread)) ?? thread) : null;
|
||||
|
||||
// Live state of the questions in view (answer buttons, «отвечено» marks).
|
||||
const qIds = messages.map((m) => m.question?.id).filter((x): x is number => x != null);
|
||||
@ -55,10 +58,10 @@ export default async function ChatPage({ params, searchParams }: { params: Promi
|
||||
const placeholder = master
|
||||
? "/status, /task KEY-N, /move KEY-N in_progress, /help"
|
||||
: taskThread
|
||||
? "Ответ агенту: на открытый вопрос, иначе комментарий, который он увидит сразу"
|
||||
? t("Ответ агенту: на открытый вопрос, иначе комментарий, который он увидит сразу")
|
||||
: thread
|
||||
? "Заметка в тред или команда /help"
|
||||
: "Заметка в канал или команда: /status, /task KEY-N, /move KEY-N in_progress";
|
||||
? t("Заметка в тред или команда /help")
|
||||
: t("Заметка в канал или команда: /status, /task KEY-N, /move KEY-N in_progress");
|
||||
|
||||
const aside = (
|
||||
<div className="flex flex-col gap-5 text-sm">
|
||||
@ -67,45 +70,48 @@ export default async function ChatPage({ params, searchParams }: { params: Promi
|
||||
{chat.tgTitle ? (
|
||||
<>
|
||||
<p className="m-0 text-muted-foreground">
|
||||
Связан с группой <b className="text-foreground">{chat.tgTitle}</b>. Сообщения чата приходят туда, треды — цепочками ответов; ответ реплаем уходит в тред{master ? "" : " (в треде стори — агенту)"}.
|
||||
{t("Связан с группой")} <b className="text-foreground">{chat.tgTitle}</b>.{" "}
|
||||
{master
|
||||
? t("Сообщения чата приходят туда, треды — цепочками ответов; ответ реплаем уходит в тред.")
|
||||
: t("Сообщения чата приходят туда, треды — цепочками ответов; ответ реплаем уходит в тред (в треде стори — агенту).")}
|
||||
</p>
|
||||
<form action={unlinkChatAction}>
|
||||
<Hidden fields={{ chatId: chat.id, back: here }} />
|
||||
<Button size="sm" variant="outline">
|
||||
<Unlink />
|
||||
Отвязать группу
|
||||
{t("Отвязать группу")}
|
||||
</Button>
|
||||
</form>
|
||||
</>
|
||||
) : link ? (
|
||||
<div className="flex flex-col gap-2 rounded-lg border bg-card p-3">
|
||||
<p className="m-0">Код действует 10 минут.</p>
|
||||
<p className="m-0">{t("Код действует 10 минут.")}</p>
|
||||
{bot && (
|
||||
<a href={`https://t.me/${bot}?startgroup=${encodeURIComponent(link)}`} target="_blank" rel="noreferrer" className="font-medium">
|
||||
Добавить @{bot} в группу →
|
||||
{t("Добавить @{bot} в группу →", { bot })}
|
||||
</a>
|
||||
)}
|
||||
<p className="m-0 text-muted-foreground">Или добавь бота в группу сам и отправь там:</p>
|
||||
<p className="m-0 text-muted-foreground">{t("Или добавь бота в группу сам и отправь там:")}</p>
|
||||
<code className="rounded bg-muted px-2 py-1 font-mono text-xs break-all select-all">/link {link}</code>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<p className="m-0 text-muted-foreground">{master ? "Свяжи мастер-чат с группой — туда пойдёт всё важное по твоим проектам." : "Свяжи чат проекта с группой команды — по ней сразу видно, к какому проекту сообщение."}</p>
|
||||
<p className="m-0 text-muted-foreground">{master ? t("Свяжи мастер-чат с группой — туда пойдёт всё важное по твоим проектам.") : t("Свяжи чат проекта с группой команды — по ней сразу видно, к какому проекту сообщение.")}</p>
|
||||
<form action={linkChatAction}>
|
||||
<Hidden fields={{ chatId: chat.id, back: here }} />
|
||||
<Button size="sm" variant="outline">
|
||||
<Link2 />
|
||||
Связать с Telegram
|
||||
{t("Связать с Telegram")}
|
||||
</Button>
|
||||
</form>
|
||||
</>
|
||||
)}
|
||||
<p className="m-0 text-xs text-muted-foreground">Отвечать из группы могут те, кто привязал Telegram в «Настройках» и имеет доступ к {master ? "мастер-чату (только ты)" : "проекту"}.</p>
|
||||
<p className="m-0 text-xs text-muted-foreground">{t("Отвечать из группы могут те, кто привязал Telegram в «Настройках» и имеет доступ к {target}.", { target: master ? t("мастер-чату (только ты)") : t("проекту") })}</p>
|
||||
</section>
|
||||
<section className="flex flex-col gap-1.5 text-xs text-muted-foreground">
|
||||
<h2 className="m-0 text-[15px] font-semibold text-foreground">Как это устроено</h2>
|
||||
<p className="m-0">{master ? "Мастер-чат — вопросы, ревью, сбои, лимиты, релизы и ошибки всех твоих проектов, мониторинг и сводка. Команды — без LLM." : "Тред на каждую стори, инцидент и релиз. Вопросы агентов видны и здесь, и на Главной."}</p>
|
||||
<p className="m-0">Переписка хранится {ttlDays} дн.; стори, вопросы и события остаются на своих страницах.</p>
|
||||
<h2 className="m-0 text-[15px] font-semibold text-foreground">{t("Как это устроено")}</h2>
|
||||
<p className="m-0">{master ? t("Мастер-чат — вопросы, ревью, сбои, лимиты, релизы и ошибки всех твоих проектов, мониторинг и сводка. Команды — без LLM.") : t("Тред на каждую стори, инцидент и релиз. Вопросы агентов видны и здесь, и на Главной.")}</p>
|
||||
<p className="m-0">{t("Переписка хранится {n} дн.; стори, вопросы и события остаются на своих страницах.", { n: ttlDays })}</p>
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
@ -114,23 +120,23 @@ export default async function ChatPage({ params, searchParams }: { params: Promi
|
||||
<Workspace aside={aside}>
|
||||
<LiveRefresh scope="chats" />
|
||||
<Flash error={error} />
|
||||
<PageHeader title="Чаты">Мастер-чат и чаты проектов: события и вопросы агентов по тредам. Ответ в треде стори уходит агенту.</PageHeader>
|
||||
<PageHeader title={t("Чаты")}>{t("Мастер-чат и чаты проектов: события и вопросы агентов по тредам. Ответ в треде стори уходит агенту.")}</PageHeader>
|
||||
|
||||
<nav className="mb-4 flex flex-wrap gap-1.5" aria-label="Чаты">
|
||||
<nav className="mb-4 flex flex-wrap gap-1.5" aria-label={t("Чаты")}>
|
||||
{list.map((c) => (
|
||||
<Link
|
||||
key={c.id}
|
||||
href={`/chats/${c.slug}`}
|
||||
aria-current={c.id === chat.id ? "page" : undefined}
|
||||
title={c.title}
|
||||
title={t.text(c.title)}
|
||||
className={cn(
|
||||
"flex items-center gap-1.5 rounded-md border bg-card px-2.5 py-1 text-sm text-muted-foreground hover:border-muted-foreground hover:text-foreground hover:no-underline",
|
||||
c.id === chat.id && "border-primary/60 bg-primary/10 text-foreground",
|
||||
)}
|
||||
>
|
||||
{c.kind === "master" ? <MessagesSquare className="size-3.5" /> : <Hash className="size-3.5" />}
|
||||
<span className={c.kind === "project" ? "font-mono" : undefined}>{c.kind === "master" ? "Мастер-чат" : c.slug}</span>
|
||||
{c.tgTitle && <Send className="size-3 text-info" aria-label="связан с Telegram" />}
|
||||
<span className={c.kind === "project" ? "font-mono" : undefined}>{c.kind === "master" ? t("Мастер-чат") : c.slug}</span>
|
||||
{c.tgTitle && <Send className="size-3 text-info" aria-label={t("связан с Telegram")} />}
|
||||
{c.open > 0 && <span className="rounded-full bg-primary px-1.5 font-mono text-[11px] leading-4 font-semibold text-primary-foreground tabular-nums">{c.open}</span>}
|
||||
</Link>
|
||||
))}
|
||||
@ -138,26 +144,26 @@ export default async function ChatPage({ params, searchParams }: { params: Promi
|
||||
|
||||
<div className={cn("grid gap-4", !master && "lg:grid-cols-[230px_minmax(0,1fr)]")}>
|
||||
{!master && (
|
||||
<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={thread === undefined} title="Вся лента" />
|
||||
<ThreadLink href={url({ thread: CHANNEL })} active={thread === null} title="# Канал" />
|
||||
<nav aria-label={t("Треды")} 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={thread === undefined} title={t("Вся лента")} />
|
||||
<ThreadLink href={url({ thread: CHANNEL })} active={thread === null} title={t("# Канал")} />
|
||||
{threads.length > 0 && <div className="mx-2 my-1 border-t" />}
|
||||
{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.map((th) => (
|
||||
<ThreadLink key={th.key} href={url({ thread: th.key })} active={thread === th.key} title={t.text(th.title)} meta={`${th.count} · ${ago(th.lastAt)}`} open={th.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">{t("Тредов пока нет.")}</p>}
|
||||
</nav>
|
||||
)}
|
||||
|
||||
<section className="flex min-w-0 flex-col gap-3" aria-label="Сообщения">
|
||||
<section className="flex min-w-0 flex-col gap-3" aria-label={t("Сообщения")}>
|
||||
{current && (
|
||||
<div className="flex flex-wrap items-center gap-2 text-sm">
|
||||
<span className="font-medium">🧵 {current}</span>
|
||||
<span className="font-medium">🧵 {t.text(current)}</span>
|
||||
{taskThread && <TaskLink messages={messages} />}
|
||||
</div>
|
||||
)}
|
||||
{messages.length === 0 ? (
|
||||
<Empty>{master ? "Пока тихо: здесь появятся вопросы агентов, сбои, релизы и ошибки твоих проектов." : thread === undefined ? "Сообщений пока нет: они появятся, когда агенты возьмутся за стори." : "В этом треде пока пусто."}</Empty>
|
||||
<Empty>{master ? t("Пока тихо: здесь появятся вопросы агентов, сбои, релизы и ошибки твоих проектов.") : thread === undefined ? t("Сообщений пока нет: они появятся, когда агенты возьмутся за стори.") : t("В этом треде пока пусто.")}</Empty>
|
||||
) : (
|
||||
<ol className="m-0 flex list-none flex-col gap-2 p-0">
|
||||
{messages.map((m) => (
|
||||
@ -169,12 +175,12 @@ export default async function ChatPage({ params, searchParams }: { params: Promi
|
||||
)}
|
||||
<form action={postChatAction} className="sticky bottom-16 flex flex-col gap-2 rounded-lg border bg-card p-3 md:bottom-3">
|
||||
<Hidden fields={{ chatId: chat.id, thread: thread ?? "", back: here }} />
|
||||
<Textarea name="text" rows={2} required maxLength={8000} placeholder={placeholder} aria-label="Сообщение" />
|
||||
<Textarea name="text" rows={2} required maxLength={8000} placeholder={placeholder} aria-label={t("Сообщение")} />
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs text-muted-foreground">{thread ? "в тред" : master ? "в мастер-чат" : "в канал"}{chat.tgTitle ? ` · и в Telegram «${chat.tgTitle}»` : ""}</span>
|
||||
<span className="text-xs text-muted-foreground">{thread ? t("в тред") : master ? t("в мастер-чат") : t("в канал")}{chat.tgTitle ? " · " + t("и в Telegram «{title}»", { title: chat.tgTitle }) : ""}</span>
|
||||
<Button size="sm" className="ml-auto">
|
||||
<Send />
|
||||
Отправить
|
||||
{t("Отправить")}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
@ -184,7 +190,8 @@ export default async function ChatPage({ params, searchParams }: { params: Promi
|
||||
);
|
||||
}
|
||||
|
||||
function ThreadLink({ href, active, title, meta, open = 0 }: { href: string; active: boolean; title: string; meta?: string; open?: number }) {
|
||||
async function ThreadLink({ href, active, title, meta, open = 0 }: { href: string; active: boolean; title: string; meta?: string; open?: number }) {
|
||||
const t = await getT();
|
||||
return (
|
||||
<Link
|
||||
href={href}
|
||||
@ -193,31 +200,33 @@ function ThreadLink({ href, active, title, meta, open = 0 }: { href: string; act
|
||||
>
|
||||
<span className="flex items-center gap-1.5">
|
||||
<span className="min-w-0 flex-1 truncate" title={title}>{title}</span>
|
||||
{open > 0 && <span className="rounded-full bg-primary px-1.5 font-mono text-[11px] leading-4 font-semibold text-primary-foreground tabular-nums" title="ждут ответа">{open}</span>}
|
||||
{open > 0 && <span className="rounded-full bg-primary px-1.5 font-mono text-[11px] leading-4 font-semibold text-primary-foreground tabular-nums" title={t("ждут ответа")}>{open}</span>}
|
||||
</span>
|
||||
{meta && <span className="text-[11px] text-muted-foreground">{meta}</span>}
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
function TaskLink({ messages }: { messages: ChatMessageView[] }) {
|
||||
async function TaskLink({ messages }: { messages: ChatMessageView[] }) {
|
||||
const t = await getT();
|
||||
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">{t("открыть стори →")}</Link> : null;
|
||||
}
|
||||
|
||||
function threadHref(m: ChatMessageView) {
|
||||
return m.projectKey && m.threadKey ? `/chats/${m.projectKey}?thread=${encodeURIComponent(m.threadKey)}` : m.projectKey ? `/chats/${m.projectKey}` : null;
|
||||
}
|
||||
|
||||
function MessageItem({ m, q, back, showThread, masterView }: { m: ChatMessageView; q?: { q: Question; taskStatus: string | null; taskKey: string | null }; back: string; showThread: boolean; masterView: boolean }) {
|
||||
async function MessageItem({ m, q, back, showThread, masterView }: { m: ChatMessageView; q?: { q: Question; taskStatus: string | null; taskKey: string | null }; back: string; showThread: boolean; masterView: boolean }) {
|
||||
const t = await getT();
|
||||
const where = (showThread || masterView) && (m.threadTitle || (masterView && m.projectKey));
|
||||
const href = threadHref(m);
|
||||
const label = [masterView && m.projectKey ? m.projectKey : null, m.threadTitle].filter(Boolean).join(" · ");
|
||||
const label = [masterView && m.projectKey ? m.projectKey : null, m.threadTitle ? t.text(m.threadTitle) : null].filter(Boolean).join(" · ");
|
||||
const head = (
|
||||
<div className="flex flex-wrap items-center gap-x-2 gap-y-0.5 text-xs text-muted-foreground">
|
||||
{m.authorKind === "user" ? <UserIcon className="size-3.5" /> : m.authorKind === "agent" ? <Bot className="size-3.5" /> : <MessagesSquare className="size-3.5" />}
|
||||
<span className="font-medium text-foreground">{m.authorKind === "user" ? (m.authorLogin ?? "?") : m.authorKind === "agent" ? "агент" : "Пеппа"}</span>
|
||||
{m.via === "telegram" && <span title="из Telegram">· Telegram</span>}
|
||||
<span className="font-medium text-foreground">{m.authorKind === "user" ? (m.authorLogin ?? "?") : m.authorKind === "agent" ? t("агент") : PRODUCT_NAME}</span>
|
||||
{m.via === "telegram" && <span title={t("из Telegram")}>· Telegram</span>}
|
||||
{where && href && (
|
||||
<Link href={href} className="max-w-full truncate">
|
||||
🧵 {label}
|
||||
@ -237,7 +246,7 @@ function MessageItem({ m, q, back, showThread, masterView }: { m: ChatMessageVie
|
||||
return (
|
||||
<article className={cn("flex flex-col gap-1 rounded-lg border bg-card px-3 py-2", m.kind === "user" && "border-primary/30 bg-primary/5", m.kind === "system" && "border-dashed bg-transparent")}>
|
||||
{head}
|
||||
<p className="m-0 text-sm break-words whitespace-pre-wrap">{m.text}</p>
|
||||
<p className="m-0 text-sm break-words whitespace-pre-wrap">{t.text(m.text)}</p>
|
||||
{m.url && (
|
||||
<a href={m.url} target="_blank" rel="noreferrer" className="truncate text-xs">
|
||||
{m.url}
|
||||
|
||||
@ -4,6 +4,7 @@
|
||||
import { chatForUser, createChatLinkCode, PeppaError, unlinkChat } from "@peppa/core";
|
||||
import { postToChat } from "@peppa/runner";
|
||||
import { loadEnv } from "@peppa/shared";
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { redirect } from "next/navigation";
|
||||
import { asWebActor, requireUser } from "@/lib/auth";
|
||||
@ -17,7 +18,7 @@ async function attempt(f: FormData, fn: () => Promise<string | void>): Promise<n
|
||||
try {
|
||||
target = (await fn()) || target;
|
||||
} catch (e) {
|
||||
const msg = e instanceof PeppaError ? e.message : `Ошибка: ${(e as Error).message}`;
|
||||
const msg = e instanceof PeppaError ? e.message : m("Ошибка: {message}", { message: (e as Error).message });
|
||||
const [path, query] = target.split("?");
|
||||
const params = new URLSearchParams(query);
|
||||
params.set("error", msg.slice(0, 300));
|
||||
@ -40,7 +41,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(m("Telegram-бот Пеппы не настроен"));
|
||||
const chat = await chatForUser(db, user, Number(str(f, "chatId")));
|
||||
const code = await createChatLinkCode(db, token, user, chat.id);
|
||||
const back = str(f, "back") || "/chats";
|
||||
|
||||
@ -1,121 +1,143 @@
|
||||
import Link from "next/link";
|
||||
import type { ReactNode } from "react";
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import { publicOrigin } from "@/lib/auth";
|
||||
import { Workspace } from "@/components/Workspace";
|
||||
import { PageHeader, Section } from "@/components/common";
|
||||
|
||||
const TOOLS: Array<[string, string]> = [
|
||||
["list_projects", "мои проекты, ссылка на репозиторий в Gitea и сколько стори в каждой колонке"],
|
||||
["create_project", "новый проект: репозиторий в Gitea (публичный по умолчанию или приватный) + шаблон + OpenSpec, или подключить существующий; отвечает ссылкой на репозиторий и кто его видит"],
|
||||
["list_epics / create_epic / update_epic", "эпики проекта (метки стори) с прогрессом «готово/всего»: завести, переименовать, описать, завершить или убрать в архив; list_goals / create_goal / update_goal — старые имена, работают так же"],
|
||||
["list_tasks", "доска проекта: Бэклог / В работе / Ревью / Готово, в каждой колонке — по порядку (сверху — важнее); «waits for» — стори ждёт предшественников"],
|
||||
["reorder_task", "поменять место стори на доске (= приоритет): top / bottom в своей колонке, before / after другой стори; диспетчер берёт из бэклога сверху"],
|
||||
["archive_task", "убрать стори в архив (пропадает с доски, диспетчера и прогресса эпика, агент останавливается, история остаётся) или вернуть (archived=false)"],
|
||||
["set_dependencies", "от каких стори зависит стори (blocked_by, список заменяется; [] — убрать все); пока предшественники не в ревью/готово, диспетчер её не берёт; циклы и чужие проекты отклоняются"],
|
||||
["plan_epic / apply_plan", "планировщик: разбить эпик на стори с критериями готовности и зависимостями (черновик, ничего не создаёт); после правок apply_plan создаёт стори в бэклоге под эпиком"],
|
||||
["get_task", "карточка стори: описание, эпик, статус, OpenSpec, проверки, вопросы, комментарии PM, зависимости, прогресс"],
|
||||
["create_task / update_task", "завести стори (в конец Бэклога, с эпиком epic_id и зависимостями blocked_by); поправить название, описание, эпик, зависимости"],
|
||||
["move_task", "передвинуть карточку; «В работе» запускает агента, «Бэклог»/«Готово» останавливают"],
|
||||
["set_project_visibility", "сделать репозиторий проекта публичным или приватным (только владелец); отвечает новой видимостью и кто видит репозиторий"],
|
||||
["list_secrets", "имена секретов проекта (ключи API для агентов); значения не отдаются никогда — заводятся и меняются только в вебе"],
|
||||
["list_members / add_member / remove_member", "участники проекта: посмотреть, добавить по логину Gitea, убрать или выйти"],
|
||||
["list_inbox / answer_question", "что ждёт вашего ответа; ответить агенту, принять ревью (accept — мержит PR, только при зелёных проверках)"],
|
||||
["list_releases / deploy", "что выкачено на staging и в прод, история релизов; выкатить здоровый staging в прод"],
|
||||
["list_incidents / get_incident", "ошибки из прода (Bugsink): статус, место, релиз, частота, стек"],
|
||||
["decide_incident / resolve_incident", "решить по ошибке: в бэклог, в работу, игнорировать; отметить исправленной"],
|
||||
["get_usage", "лимиты подписок: сколько использовано окон 5 ч и 7 дней и когда сброс; «нет данных», если агенты ещё не сообщали"],
|
||||
["get_metrics", "метрики фабрики по проекту: время цикла, доля принятых с первого раза, возвраты с ревью, вопросы, часы раннеров, ожидание PM, расход; по неделям, агентам и эпикам"],
|
||||
["get_project_settings / update_project_settings", "автономность проекта: уровень manual (по умолчанию) / assisted / auto и отдельные настройки — кто берёт стори, одобрение proposal, мерж, закрытие, пуш при простое; agent — провайдер, модель, усилия, эскалация и запасной провайдер (у стори — update_task с agent)"],
|
||||
["get_incident_policy / set_incident_policy", "политика инцидентов проекта: notify, backlog (по умолчанию), start, ask, triage + мини-промпт триажёра"],
|
||||
["list_projects", m("мои проекты, ссылка на репозиторий в Gitea и сколько стори в каждой колонке")],
|
||||
["create_project", m("новый проект: репозиторий в Gitea (публичный по умолчанию или приватный) + шаблон + OpenSpec, или подключить существующий; отвечает ссылкой на репозиторий и кто его видит")],
|
||||
["list_epics / create_epic / update_epic", m("эпики проекта (метки стори) с прогрессом «готово/всего»: завести, переименовать, описать, завершить или убрать в архив; list_goals / create_goal / update_goal — старые имена, работают так же")],
|
||||
["list_tasks", m("доска проекта: Бэклог / В работе / Ревью / Готово, в каждой колонке — по порядку (сверху — важнее); «waits for» — стори ждёт предшественников")],
|
||||
["reorder_task", m("поменять место стори на доске (= приоритет): top / bottom в своей колонке, before / after другой стори; диспетчер берёт из бэклога сверху")],
|
||||
["archive_task", m("убрать стори в архив (пропадает с доски, диспетчера и прогресса эпика, агент останавливается, история остаётся) или вернуть (archived=false)")],
|
||||
["set_dependencies", m("от каких стори зависит стори (blocked_by, список заменяется; [] — убрать все); пока предшественники не в ревью/готово, диспетчер её не берёт; циклы и чужие проекты отклоняются")],
|
||||
["plan_epic / apply_plan", m("планировщик: разбить эпик на стори с критериями готовности и зависимостями (черновик, ничего не создаёт); после правок apply_plan создаёт стори в бэклоге под эпиком")],
|
||||
["get_task", m("карточка стори: описание, эпик, статус, OpenSpec, проверки, вопросы, комментарии PM, зависимости, прогресс")],
|
||||
["create_task / update_task", m("завести стори (в конец Бэклога, с эпиком epic_id и зависимостями blocked_by); поправить название, описание, эпик, зависимости")],
|
||||
["move_task", m("передвинуть карточку; «В работе» запускает агента, «Бэклог»/«Готово» останавливают")],
|
||||
["set_project_visibility", m("сделать репозиторий проекта публичным или приватным (только владелец); отвечает новой видимостью и кто видит репозиторий")],
|
||||
["list_secrets", m("имена секретов проекта (ключи API для агентов); значения не отдаются никогда — заводятся и меняются только в вебе")],
|
||||
["list_members / add_member / remove_member", m("участники проекта: посмотреть, добавить по логину Gitea, убрать или выйти")],
|
||||
["list_inbox / answer_question", m("что ждёт вашего ответа; ответить агенту, принять ревью (accept — мержит PR, только при зелёных проверках)")],
|
||||
["list_releases / deploy", m("что выкачено на staging и в прод, история релизов; выкатить здоровый staging в прод")],
|
||||
["list_incidents / get_incident", m("ошибки из прода (Bugsink): статус, место, релиз, частота, стек")],
|
||||
["decide_incident / resolve_incident", m("решить по ошибке: в бэклог, в работу, игнорировать; отметить исправленной")],
|
||||
["get_usage", m("лимиты подписок: сколько использовано окон 5 ч и 7 дней и когда сброс; «нет данных», если агенты ещё не сообщали")],
|
||||
["get_metrics", m("метрики фабрики по проекту: время цикла, доля принятых с первого раза, возвраты с ревью, вопросы, часы раннеров, ожидание PM, расход; по неделям, агентам и эпикам")],
|
||||
["get_project_settings / update_project_settings", m("автономность проекта: уровень manual (по умолчанию) / assisted / auto и отдельные настройки — кто берёт стори, одобрение proposal, мерж, закрытие, пуш при простое; agent — провайдер, модель, усилия, эскалация и запасной провайдер (у стори — update_task с agent)")],
|
||||
["get_incident_policy / set_incident_policy", m("политика инцидентов проекта: notify, backlog (по умолчанию), start, ask, triage + мини-промпт триажёра")],
|
||||
];
|
||||
|
||||
const CASES: Array<{ title: string; say: string; how: string }> = [
|
||||
{ title: "Создать проект", say: "Создай проект «Платежи», репо payments, ключ PAY", how: "create_project → проект с доской; агенты будут работать в этом репозитории" },
|
||||
{ title: "Завести эпик", say: "В PAY заведи эпик «Оплата картой» — зачем и какой результат", how: "create_epic. Эпик — метка, которая группирует стори; его описание агент получает вместе со стори" },
|
||||
{ title: "Создать стори в эпике", say: "В этом эпике создай стори «Форма оплаты» с условиями готовности: …", how: "create_task с epic_id. Стори — одна бизнесовая история (один OpenSpec change). Пишите контекст и список «Условия готовности» — по ним работает агент" },
|
||||
{ title: "Поправить стори", say: "Переименуй PAY-3 в … и замени описание на …; перенеси в эпик #5", how: "update_task — статус и агент не трогаются, дубликат не нужен" },
|
||||
{ title: "Посмотреть статус", say: "Покажи доску PAY · Что с PAY-3?", how: "list_tasks / get_task" },
|
||||
{ title: "Запустить работу", say: "Двинь PAY-3 в работу", how: "move_task → in_progress: агент пишет proposal, реализует, открывает PR и переводит стори в Ревью" },
|
||||
{ title: "Ответить агенту", say: "Что ждёт моего ответа? · Ответь на #42: берём Postgres", how: "list_inbox → answer_question. Агенты спрашивают только об архитектурных стопперах" },
|
||||
{ title: "Принять ревью", say: "Прими PAY-3 · Верни PAY-3: добавь тесты", how: "answer_question с accept (→ Готово) или с замечанием (агент доработает)" },
|
||||
{ title: "Остановить", say: "Верни PAY-3 в бэклог", how: "move_task → backlog: агент останавливается, открытые вопросы закрываются" },
|
||||
{ title: "Работать вместе", say: "Добавь в PAY участника dana", how: "add_member (только владелец). Участник видит доску и входящие, двигает карточки, отвечает агентам и получает доступ к репозиторию. Тот, кто ещё не входил в Пеппу, получит приглашение — оно сработает при первом входе" },
|
||||
{ title: "Автономность", say: "Пусть PAY делается сам: бери стори из бэклога и мержи зелёные PR", how: "update_project_settings level=auto. «С подсказками» (assisted) — только пуш, когда агенты простаивают. То же — «⋯ Настройки проекта» → «Автономность»" },
|
||||
{ title: "Модель агента", say: "Рутину в PAY делай на sonnet, а если проверки дважды красные — переходи на opus", how: "update_project_settings agent={model: sonnet, escalate_model: opus, escalate_after: 2}. Для одной стори — update_task с agent. То же — «⋯ Настройки проекта» → «Модель агента» и раздел «Агент» на странице стори" },
|
||||
{ title: "Видимость репозитория", say: "Сделай репозиторий PAY приватным", how: "set_project_visibility (только владелец). Новые проекты публичные по умолчанию; то же — в вебе: «⋯ Настройки проекта» → «Репозиторий»" },
|
||||
{ title: "Ошибки из прода", say: "Какие ошибки ждут решения в PAY? · Ошибку #7 — в работу", how: "list_incidents → decide_incident. Подключение — на странице проекта «⋯ Настройки проекта → Баги»" },
|
||||
{ title: "Политика инцидентов", say: "В PAY пусть ошибки разбирает триажёр: падения оплаты — сразу в работу, косметику — в бэклог, остальное спроси", how: "set_incident_policy policy=triage, triage_prompt — ваши слова. Не уверен — спросит кнопками в Telegram" },
|
||||
{ title: "Выкатить в прод", say: "Что сейчас на staging в PAY? · Выкати PAY в прод", how: "list_releases → deploy. Тот же образ, что прошёл staging; не поднялся — Пеппа сама откатит и напишет" },
|
||||
{ title: "Разбить эпик на стори", say: "Спланируй эпик «Оплата картой» в PAY: сначала API, потом экран", how: "plan_epic → черновик со стори, критериями готовности и зависимостями; поправьте и подтвердите — apply_plan создаст стори. В вебе — «Спланировать стори эпика» над доской или в «⋯ Настройки проекта → Эпики»" },
|
||||
{ title: "Приоритет", say: "Подними PAY-7 наверх бэклога · Поставь PAY-9 перед PAY-4", how: "reorder_task. Порядок в колонке = приоритет: диспетчер (автономность) берёт стори сверху. В вебе — перетащите карточку внутри колонки" },
|
||||
{ title: "Зависимости", say: "PAY-8 делать только после PAY-6", how: "set_dependencies (или blocked_by в create_task / update_task). На карточке — «ждёт PAY-6», диспетчер её не возьмёт, пока PAY-6 не в ревью или готово" },
|
||||
{ title: "Убрать стори", say: "PAY-5 больше не нужна", how: "archive_task — стори пропадает с доски, история остаётся; вернуть — archived=false или «Вернуть» на странице стори" },
|
||||
{ title: "Закрыть эпик", say: "Эпик #5 закончен", how: "update_epic status=done — эпик пропадает из фильтра доски, стори не меняются" },
|
||||
{ title: m("Создать проект"), say: m("Создай проект «Платежи», репо payments, ключ PAY"), how: m("create_project → проект с доской; агенты будут работать в этом репозитории") },
|
||||
{ title: m("Завести эпик"), say: m("В PAY заведи эпик «Оплата картой» — зачем и какой результат"), how: m("create_epic. Эпик — метка, которая группирует стори; его описание агент получает вместе со стори") },
|
||||
{ title: m("Создать стори в эпике"), say: m("В этом эпике создай стори «Форма оплаты» с условиями готовности: …"), how: m("create_task с epic_id. Стори — одна бизнесовая история (один OpenSpec change). Пишите контекст и список «Условия готовности» — по ним работает агент") },
|
||||
{ title: m("Поправить стори"), say: m("Переименуй PAY-3 в … и замени описание на …; перенеси в эпик #5"), how: m("update_task — статус и агент не трогаются, дубликат не нужен") },
|
||||
{ title: m("Посмотреть статус"), say: m("Покажи доску PAY · Что с PAY-3?"), how: "list_tasks / get_task" },
|
||||
{ title: m("Запустить работу"), say: m("Двинь PAY-3 в работу"), how: m("move_task → in_progress: агент пишет proposal, реализует, открывает PR и переводит стори в Ревью") },
|
||||
{ title: m("Ответить агенту"), say: m("Что ждёт моего ответа? · Ответь на #42: берём Postgres"), how: m("list_inbox → answer_question. Агенты спрашивают только об архитектурных стопперах") },
|
||||
{ title: m("Принять ревью"), say: m("Прими PAY-3 · Верни PAY-3: добавь тесты"), how: m("answer_question с accept (→ Готово) или с замечанием (агент доработает)") },
|
||||
{ title: m("Остановить"), say: m("Верни PAY-3 в бэклог"), how: m("move_task → backlog: агент останавливается, открытые вопросы закрываются") },
|
||||
{ title: m("Работать вместе"), say: m("Добавь в PAY участника dana"), how: m("add_member (только владелец). Участник видит доску и входящие, двигает карточки, отвечает агентам и получает доступ к репозиторию. Тот, кто ещё не входил в Пеппу, получит приглашение — оно сработает при первом входе") },
|
||||
{ title: m("Автономность"), say: m("Пусть PAY делается сам: бери стори из бэклога и мержи зелёные PR"), how: m("update_project_settings level=auto. «С подсказками» (assisted) — только пуш, когда агенты простаивают. То же — «⋯ Настройки проекта» → «Автономность»") },
|
||||
{ title: m("Модель агента"), say: m("Рутину в PAY делай на sonnet, а если проверки дважды красные — переходи на opus"), how: m("update_project_settings agent={model: sonnet, escalate_model: opus, escalate_after: 2}. Для одной стори — update_task с agent. То же — «⋯ Настройки проекта» → «Модель агента» и раздел «Агент» на странице стори") },
|
||||
{ title: m("Видимость репозитория"), say: m("Сделай репозиторий PAY приватным"), how: m("set_project_visibility (только владелец). Новые проекты публичные по умолчанию; то же — в вебе: «⋯ Настройки проекта» → «Репозиторий»") },
|
||||
{ title: m("Ошибки из прода"), say: m("Какие ошибки ждут решения в PAY? · Ошибку #7 — в работу"), how: m("list_incidents → decide_incident. Подключение — на странице проекта «⋯ Настройки проекта → Баги»") },
|
||||
{ title: m("Политика инцидентов"), say: m("В PAY пусть ошибки разбирает триажёр: падения оплаты — сразу в работу, косметику — в бэклог, остальное спроси"), how: m("set_incident_policy policy=triage, triage_prompt — ваши слова. Не уверен — спросит кнопками в Telegram") },
|
||||
{ title: m("Выкатить в прод"), say: m("Что сейчас на staging в PAY? · Выкати PAY в прод"), how: m("list_releases → deploy. Тот же образ, что прошёл staging; не поднялся — Пеппа сама откатит и напишет") },
|
||||
{ title: m("Разбить эпик на стори"), say: m("Спланируй эпик «Оплата картой» в PAY: сначала API, потом экран"), how: m("plan_epic → черновик со стори, критериями готовности и зависимостями; поправьте и подтвердите — apply_plan создаст стори. В вебе — «Спланировать стори эпика» над доской или в «⋯ Настройки проекта → Эпики»") },
|
||||
{ title: m("Приоритет"), say: m("Подними PAY-7 наверх бэклога · Поставь PAY-9 перед PAY-4"), how: m("reorder_task. Порядок в колонке = приоритет: диспетчер (автономность) берёт стори сверху. В вебе — перетащите карточку внутри колонки") },
|
||||
{ title: m("Зависимости"), say: m("PAY-8 делать только после PAY-6"), how: m("set_dependencies (или blocked_by в create_task / update_task). На карточке — «ждёт PAY-6», диспетчер её не возьмёт, пока PAY-6 не в ревью или готово") },
|
||||
{ title: m("Убрать стори"), say: m("PAY-5 больше не нужна"), how: m("archive_task — стори пропадает с доски, история остаётся; вернуть — archived=false или «Вернуть» на странице стори") },
|
||||
{ title: m("Закрыть эпик"), say: m("Эпик #5 закончен"), how: m("update_epic status=done — эпик пропадает из фильтра доски, стори не меняются") },
|
||||
];
|
||||
|
||||
/** Renders a translated string with a small markup: <b>, <code>, <m> (monospace), <a href="/path"> (Link). */
|
||||
const TAG = /<(b|code|m)>([\s\S]*?)<\/\1>|<a href="([^"]+)">([\s\S]*?)<\/a>/g;
|
||||
function rich(s: string): ReactNode {
|
||||
const out: ReactNode[] = [];
|
||||
let last = 0;
|
||||
for (const mt of s.matchAll(TAG)) {
|
||||
if (mt.index > last) out.push(s.slice(last, mt.index));
|
||||
const k = mt.index;
|
||||
if (mt[3]) out.push(<Link key={k} href={mt[3]}>{mt[4]}</Link>);
|
||||
else if (mt[1] === "b") out.push(<b key={k}>{mt[2]}</b>);
|
||||
else if (mt[1] === "code") out.push(<code key={k}>{mt[2]}</code>);
|
||||
else out.push(<span key={k} className="font-mono">{mt[2]}</span>);
|
||||
last = mt.index + mt[0].length;
|
||||
}
|
||||
if (last < s.length) out.push(s.slice(last));
|
||||
return out;
|
||||
}
|
||||
|
||||
export default async function Help() {
|
||||
const t = await getT();
|
||||
const mcp = `${await publicOrigin()}/mcp`;
|
||||
return (
|
||||
<Workspace>
|
||||
<div className="max-w-3xl text-sm leading-relaxed [&_a]:text-primary [&_code]:font-mono [&_code]:text-[0.92em] [&_li]:my-1 [&_ul]:m-0 [&_ul]:list-disc [&_ul]:pl-5">
|
||||
<PageHeader title="Помощь">Понятия Пеппы, подключение MCP-клиентов и что можно попросить.</PageHeader>
|
||||
<PageHeader title={t("Помощь")}>{t("Понятия Пеппы, подключение MCP-клиентов и что можно попросить.")}</PageHeader>
|
||||
|
||||
<Section title="Как устроена Пеппа">
|
||||
<Section title={t("Как устроена Пеппа")}>
|
||||
<ul>
|
||||
<li><b>Проект</b> — репозиторий в Gitea с ключом стори (например, PEP). Создаётся из веба или через MCP. Страница проекта устроена как в GitHub: вкладки <b>Доска · Код</b> (README, ветки, коммиты) <b>· Спеки</b> (что система умеет сейчас — <span className="font-mono">openspec/specs</span>) <b>· PR</b> (открытые PR и их проверки) <b>· Релизы · Баги · Сессии</b>; «+ Стори» и «⋯ Настройки проекта» (репозиторий, эпики, баги, участники) — в заголовке.</li>
|
||||
<li><b>Где репозиторий</b> — в выбранном при создании пространстве Gitea: личном (<span className="font-mono"><ваш логин>/<slug></span>) или организации. По умолчанию он публичный — его видят все, у кого есть доступ к Gitea; приватный видят только владелец пространства (в организации — её участники с доступом), <span className="font-mono">peppa-bot</span> и участники проекта. Ссылка «Открыть в Gitea», видимость, кто видит и кнопка смены видимости (для владельца) — в «⋯ Настройки проекта» → «Репозиторий».</li>
|
||||
<li><b>Стори</b> (PEP-12) — одна бизнесовая история с описанием и условиями готовности; агент реализует её одним OpenSpec change. «Задачи» — это пункты <span className="font-mono">tasks.md</span> внутри change, не путать.</li>
|
||||
<li><b>Эпик</b> — необязательная метка, которая группирует стори («Оплата картой»): тег на карточке, фильтр над доской, выбор в «+ Стори». Его описание агент получает вместе со стори как контекст «зачем». Заводятся в «⋯ Настройки проекта» или через MCP.</li>
|
||||
<li><b>Доска</b> — Бэклог → В работе → Ревью → Готово. Перенос в «В работе» запускает агента. Порядок в колонке — приоритет: перетащите карточку выше или ниже (или ⇈/⇊ на карточке), диспетчер берёт стори из бэклога сверху. Над доской — фильтр по эпику с прогрессом «готово/всего»; «Готово» сворачивается. Ненужную стори — «В архив» на её странице (история остаётся, вернуть можно там же).</li>
|
||||
<li><b>Зависимости и планировщик</b> — стори может ждать другие стори («ждёт PAY-2» на карточке, блок «Зависимости» на странице стори): пока предшественник не в ревью или готово, диспетчер её не берёт. «Спланировать стори эпика» — короткая сессия Claude (на подписке пула проекта) предлагает стори эпика с критериями готовности и зависимостями; вы правите черновик и создаёте стори одной кнопкой.</li>
|
||||
<li><b>Клавиатура</b> — <b>⌘K</b> (Ctrl+K) или «Поиск» в меню открывает палитру: проекты, стори, раннеры, вопросы и разделы; Enter — перейти, ⌘Enter — стори из бэклога в работу. Остальные сочетания — <Link href="/help/shortcuts">Горячие клавиши</Link> (или <b>?</b>).</li>
|
||||
<li><b>Агент</b> — Claude Code, Codex или OpenCode в сессии на машине Пеппы: пишет OpenSpec-proposal, реализует, открывает PR и отдаёт стори на ревью.</li>
|
||||
<li><b>Участники</b> — владелец проекта добавляет людей по логину Gitea (блок «Участники» на странице проекта). Агенты проекта работают на подписках из пула проекта.</li>
|
||||
<li><b>Подписка проекта</b> — на чём работают агенты. В проекте без подписки сверху появляется подсказка: нажмите «Подключить Claude» или «Подключить ChatGPT», откройте ссылку, войдите в свой аккаунт и (для Claude) вставьте код, который он покажет. Терминал не нужен. Готовый токен или ключ OpenAI API — в «⋯ Настройки проекта → Подписки».</li>
|
||||
<li><b>Стори берутся сами</b> — в новом проекте карточки перетаскивать не нужно: агент сам берёт стори из бэклога по порядку на доске, вам остаётся «Принять» результат. Уровень «Сам берёт» меняется в «⋯ Настройки проекта → Автономность».</li>
|
||||
<li><b>Telegram</b> — у каждого пользователя свой бот: в «Настройки → Telegram» три шага — создать бота у @BotFather (команда <span className="font-mono">/newbot</span>), вставить его токен, открыть бота и нажать Start. Из него приходят вопросы агентов и «готово к ревью», ему же можно написать новую задачу. Не хотите создавать — там же можно выбрать общего бота Пеппы.</li>
|
||||
<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> — «⋯ Настройки проекта → Раннеры» (и на странице стори — для неё одной): «один раннер на стори» (по умолчанию) или «раннер ведёт очередь стори» — стори достаётся свободному раннеру, при лимите раннеров проекта ждёт в его очереди, а «Принять» не останавливает раннер, а даёт ему следующую стори; переход — «свежий контекст» (тот же терминал, новый разговор) или «один разговор». «Свой 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>
|
||||
<li>{rich(t("<b>Проект</b> — репозиторий в Gitea с ключом стори (например, PEP). Создаётся из веба или через MCP. Страница проекта устроена как в GitHub: вкладки <b>Доска · Код</b> (README, ветки, коммиты) <b>· Спеки</b> (что система умеет сейчас — <m>openspec/specs</m>) <b>· PR</b> (открытые PR и их проверки) <b>· Релизы · Баги · Сессии</b>; «+ Стори» и «⋯ Настройки проекта» (репозиторий, эпики, баги, участники) — в заголовке."))}</li>
|
||||
<li>{rich(t("<b>Где репозиторий</b> — в выбранном при создании пространстве Gitea: личном (<m><ваш логин>/<slug></m>) или организации. По умолчанию он публичный — его видят все, у кого есть доступ к Gitea; приватный видят только владелец пространства (в организации — её участники с доступом), <m>peppa-bot</m> и участники проекта. Ссылка «Открыть в Gitea», видимость, кто видит и кнопка смены видимости (для владельца) — в «⋯ Настройки проекта» → «Репозиторий»."))}</li>
|
||||
<li>{rich(t("<b>Стори</b> (PEP-12) — одна бизнесовая история с описанием и условиями готовности; агент реализует её одним OpenSpec change. «Задачи» — это пункты <m>tasks.md</m> внутри change, не путать."))}</li>
|
||||
<li>{rich(t("<b>Эпик</b> — необязательная метка, которая группирует стори («Оплата картой»): тег на карточке, фильтр над доской, выбор в «+ Стори». Его описание агент получает вместе со стори как контекст «зачем». Заводятся в «⋯ Настройки проекта» или через MCP."))}</li>
|
||||
<li>{rich(t("<b>Доска</b> — Бэклог → В работе → Ревью → Готово. Перенос в «В работе» запускает агента. Порядок в колонке — приоритет: перетащите карточку выше или ниже (или ⇈/⇊ на карточке), диспетчер берёт стори из бэклога сверху. Над доской — фильтр по эпику с прогрессом «готово/всего»; «Готово» сворачивается. Ненужную стори — «В архив» на её странице (история остаётся, вернуть можно там же)."))}</li>
|
||||
<li>{rich(t("<b>Зависимости и планировщик</b> — стори может ждать другие стори («ждёт PAY-2» на карточке, блок «Зависимости» на странице стори): пока предшественник не в ревью или готово, диспетчер её не берёт. «Спланировать стори эпика» — короткая сессия Claude (на подписке пула проекта) предлагает стори эпика с критериями готовности и зависимостями; вы правите черновик и создаёте стори одной кнопкой."))}</li>
|
||||
<li>{rich(t("<b>Клавиатура</b> — <b>⌘K</b> (Ctrl+K) или «Поиск» в меню открывает палитру: проекты, стори, раннеры, вопросы и разделы; Enter — перейти, ⌘Enter — стори из бэклога в работу. Остальные сочетания — <a href=\"/help/shortcuts\">Горячие клавиши</a> (или <b>?</b>)."))}</li>
|
||||
<li>{rich(t("<b>Агент</b> — Claude Code, Codex или OpenCode в сессии на машине Пеппы: пишет OpenSpec-proposal, реализует, открывает PR и отдаёт стори на ревью."))}</li>
|
||||
<li>{rich(t("<b>Участники</b> — владелец проекта добавляет людей по логину Gitea (блок «Участники» на странице проекта). Агенты проекта работают на подписках из пула проекта."))}</li>
|
||||
<li>{rich(t("<b>Подписка проекта</b> — на чём работают агенты. В проекте без подписки сверху появляется подсказка: нажмите «Подключить Claude» или «Подключить ChatGPT», откройте ссылку, войдите в свой аккаунт и (для Claude) вставьте код, который он покажет. Терминал не нужен. Готовый токен или ключ OpenAI API — в «⋯ Настройки проекта → Подписки»."))}</li>
|
||||
<li>{rich(t("<b>Стори берутся сами</b> — в новом проекте карточки перетаскивать не нужно: агент сам берёт стори из бэклога по порядку на доске, вам остаётся «Принять» результат. Уровень «Сам берёт» меняется в «⋯ Настройки проекта → Автономность»."))}</li>
|
||||
<li>{rich(t("<b>Telegram</b> — у каждого пользователя свой бот: в «Настройки → Telegram» три шага — создать бота у @BotFather (команда <m>/newbot</m>), вставить его токен, открыть бота и нажать Start. Из него приходят вопросы агентов и «готово к ревью», ему же можно написать новую задачу. Не хотите создавать — там же можно выбрать общего бота Пеппы."))}</li>
|
||||
<li>{rich(t("<b>Продакт и аналитик</b> — два агента, которые читают новую задачу раньше разработчика. Продакт решает, зачем это и что берём в первую версию (большое делит на несколько стори). Аналитик пишет критерии приёмки и задаёт до трёх вопросов — у каждого есть вариант по умолчанию; не ответите за 30 минут (ночью — до утра), он возьмёт его сам. Их реплики — во вкладке Comments стори и в чате проекта. Включается в «⋯ Настройки проекта → Продакт и аналитик», в новых проектах включено."))}</li>
|
||||
<li>{rich(t("<b>Команда</b> — агенты Пеппы с именами (Айгерим, Нурлан…), одна команда на все проекты: свободный агент берёт стори и ведёт её до конца, его имя видно на карточке. В разделе «Команда» суперадмин задаёт агенту характер и специализацию — они добавляются к его промпту."))}</li>
|
||||
<li>{rich(t("<b>Вход</b> — через eGov QR (с телефона — кнопка «Открыть в eGov Mobile») или через Google (кнопка есть, когда суперадмин задал <m>GOOGLE_CLIENT_ID/SECRET</m>); в «Настройках» их можно связать в одну учётку. Первый вход сам создаёт учётку по ИИН или Google-почте: логин из имени в сертификате (например, <m>aigerim.ivanova</m>). Новый пользователь видит только проекты, куда его пригласили, и свои; агенты его проектов работают только на пуле подписок, который назначает суперадмин. У такой учётки нет аккаунта Gitea — код только через Пеппу, а новые проекты создаются в пространстве <m>peppa-bot</m>."))}</li>
|
||||
<li>{rich(t("<b>Раннер</b> — агент, запущенный по стори в tmux на машине Пеппы. Все раннеры твоих и общих проектов — в разделе <a href=\"/runners\">Раннеры</a>: статус, стори, команда <code>tmux attach</code>, сообщение, остановка и resume; фильтры-счётчики «ждут тебя / работают / упали / готово» и поиск; строки, где нужен ты, подсвечены, у раннера на лимите — «остановлена · продолжит в HH:MM». Выбери раннер — справа его детали, вопросы, действия и <b>живой терминал</b>: экран агента в реальном времени с историей (прокрутка), размер шрифта A−/A+ и режим во весь экран. Кнопка «Ввод» позволяет печатать агенту прямо в терминал (вставка многострочного текста уходит одной вставкой, для телефона есть Esc, Tab, стрелки, Enter, Ctrl-C); ввод сбрасывает счётчик автопродолжений и отмечается в событиях раннера. Тот же терминал — на странице стори у работающего раннера. Терминал доступен владельцу и участникам проекта."))}</li>
|
||||
<li>{rich(t("<b>Новый терминал</b> — раннер без стори: в «Раннерах» или на вкладке «Сессии» проекта выбери проект, имя, агента и напиши промпт (можно голосом — кнопка «Голосом» в браузерах с распознаванием речи). После ходов такой раннер не пингует — им управляешь ты в терминале. Получилась работа — «Оформить стори» в карточке раннера: стори создаётся в работе, раннер ведёт её дальше. Раннер можно переименовать."))}</li>
|
||||
<li>{rich(t("<b>Раннеры и стори</b> — «⋯ Настройки проекта → Раннеры» (и на странице стори — для неё одной): «один раннер на стори» (по умолчанию) или «раннер ведёт очередь стори» — стори достаётся свободному раннеру, при лимите раннеров проекта ждёт в его очереди, а «Принять» не останавливает раннер, а даёт ему следующую стори; переход — «свежий контекст» (тот же терминал, новый разговор) или «один разговор». «Свой git worktree на раннер» — у каждого раннера своя копия и ветка <code>task/…</code>, параллельные стори не мешают друг другу; копия убирается, когда всё запушено. В карточке раннера — история его стори и очередь."))}</li>
|
||||
<li>{rich(t("<b>Изоляция и хосты</b> — там же: «Контейнер на раннер» запускает агента в docker-образе раннера — он видит только свою рабочую копию, работает на подписке из пула проекта и не видит токенов Пеппы и чужих проектов; хуки, MCP и git идут в Пеппу через релей и только к репозиторию проекта (PR агент открывает инструментом <code>open_pull_request</code>). «Где запускать раннеры» — Mac Пеппы или отмеченные хосты: раннер уходит на наименее занятый онлайн-хост, там клонируется рабочая копия, а терминал, ввод и ответы работают как обычно. Хосты подключает суперадмин в разделе «Хосты» (SSH-ключ Пеппы на хосте, tmux и docker); недоступный хост помечается «офлайн», его раннеры не считаются упавшими."))}</li>
|
||||
<li>{rich(t("<b>Главная</b> — вопросы агентов (только архитектурные стопперы) и «готово к ревью», активные раннеры и проекты. Отвечать можно в вебе, Telegram или через MCP. Список проектов и «Новый проект» — в разделе <a href=\"/projects\">Проекты</a>."))}</li>
|
||||
</ul>
|
||||
</Section>
|
||||
|
||||
<Section title="Подключить MCP">
|
||||
<p className="m-0">Адрес сервера:</p>
|
||||
<Section title={t("Подключить MCP")}>
|
||||
<p className="m-0">{t("Адрес сервера:")}</p>
|
||||
<code className="block overflow-x-auto rounded-md border bg-muted px-3 py-2 text-sm">{mcp}</code>
|
||||
<ul>
|
||||
<li><b>ChatGPT</b>: Settings → Apps & Connectors → Advanced → включить Developer mode → Create: URL выше, авторизация OAuth. Откроется Пеппа — войдите через eGov и нажмите «Разрешить». В чате включите коннектор Peppa.</li>
|
||||
<li><b>Codex, Claude и другие MCP-клиенты</b>: добавьте удалённый MCP-сервер по этому URL с OAuth — клиент зарегистрируется сам, вход и согласие на экране Пеппы.</li>
|
||||
<li>Если клиент не видит новых инструментов — обновите или переподключите коннектор. Доступ отзывается в <Link href="/settings">Настройках</Link>.</li>
|
||||
<li><b>Модель агента</b> — «⋯ Настройки проекта → Модель агента» (и в разделе «Агент» стори — для неё одной): провайдер (Claude Code, Codex, OpenCode), модель (<code>sonnet</code>, <code>opus</code>, <code>gpt-5-codex</code>…) и усилия. <b>Эскалация</b>: после N неудач стори (красные проверки по разным коммитам и возвраты ревьюера, по умолчанию 2) она до конца идёт на сильной модели — живой раннер перезапускается в том же разговоре. <b>Запасной провайдер</b> — если у основного нет рабочей подписки в пуле (все в лимите или с ошибкой входа), раннер стартует на нём.</li>
|
||||
<li><b>Память проекта</b> — <code>.peppa/memory.md</code> в репозитории: команды, соглашения, грабли и решения, которые агенты записывают в конце стори (MCP <code>remember</code>). Раннер подкладывает её вместе со сводкой последних завершённых стори в каждый запуск агента; размер ограничен — разросшуюся память агент ужимает сам. Посмотреть — вкладка проекта «Спеки».</li>
|
||||
<li><b>Первый запуск</b> — на Главной чек-лист: подписка агента (суперадмину), Telegram, eGov (необязательно), проект, первая стори, стори в работе. Исчезает, когда всё сделано, или по «Скрыть». Если у пула проекта нет ни одной рабочей подписки, на странице проекта — предупреждение «Агенты не запустятся».</li>
|
||||
<li><b>Подписки</b> — аккаунты Claude Code, Codex и OpenCode, на которых работают агенты, и пулы для ротации ведёт суперадмин в разделе «Подписки». У проекта — пул по умолчанию («⋯ Настройки проекта»): раннер стартует на первой свободной активной подписке пула, а в «Раннерах» видно, на какой. Упёрся в лимит — после конца хода раннер сам переходит на свободную подписку того же агента в пуле (Claude — продолжая тот же разговор, Codex — заново, с контекстом из стори) и пишет в Telegram «переключил на подписку…»; свободных нет — ждёт сброса и продолжает сам.</li>
|
||||
<li>{rich(t("<b>ChatGPT</b>: Settings → Apps & Connectors → Advanced → включить Developer mode → Create: URL выше, авторизация OAuth. Откроется Пеппа — войдите через eGov и нажмите «Разрешить». В чате включите коннектор Peppa."))}</li>
|
||||
<li>{rich(t("<b>Codex, Claude и другие MCP-клиенты</b>: добавьте удалённый MCP-сервер по этому URL с OAuth — клиент зарегистрируется сам, вход и согласие на экране Пеппы."))}</li>
|
||||
<li>{rich(t("Если клиент не видит новых инструментов — обновите или переподключите коннектор. Доступ отзывается в <a href=\"/settings\">Настройках</a>."))}</li>
|
||||
<li>{rich(t("<b>Модель агента</b> — «⋯ Настройки проекта → Модель агента» (и в разделе «Агент» стори — для неё одной): провайдер (Claude Code, Codex, OpenCode), модель (<code>sonnet</code>, <code>opus</code>, <code>gpt-5-codex</code>…) и усилия. <b>Эскалация</b>: после N неудач стори (красные проверки по разным коммитам и возвраты ревьюера, по умолчанию 2) она до конца идёт на сильной модели — живой раннер перезапускается в том же разговоре. <b>Запасной провайдер</b> — если у основного нет рабочей подписки в пуле (все в лимите или с ошибкой входа), раннер стартует на нём."))}</li>
|
||||
<li>{rich(t("<b>Память проекта</b> — <code>.peppa/memory.md</code> в репозитории: команды, соглашения, грабли и решения, которые агенты записывают в конце стори (MCP <code>remember</code>). Раннер подкладывает её вместе со сводкой последних завершённых стори в каждый запуск агента; размер ограничен — разросшуюся память агент ужимает сам. Посмотреть — вкладка проекта «Спеки»."))}</li>
|
||||
<li>{rich(t("<b>Первый запуск</b> — на Главной чек-лист: подписка агента (суперадмину), Telegram, eGov (необязательно), проект, первая стори, стори в работе. Исчезает, когда всё сделано, или по «Скрыть». Если у пула проекта нет ни одной рабочей подписки, на странице проекта — предупреждение «Агенты не запустятся»."))}</li>
|
||||
<li>{rich(t("<b>Подписки</b> — аккаунты Claude Code, Codex и OpenCode, на которых работают агенты, и пулы для ротации ведёт суперадмин в разделе «Подписки». У проекта — пул по умолчанию («⋯ Настройки проекта»): раннер стартует на первой свободной активной подписке пула, а в «Раннерах» видно, на какой. Упёрся в лимит — после конца хода раннер сам переходит на свободную подписку того же агента в пуле (Claude — продолжая тот же разговор, Codex — заново, с контекстом из стори) и пишет в Telegram «переключил на подписку…»; свободных нет — ждёт сброса и продолжает сам."))}</li>
|
||||
</ul>
|
||||
</Section>
|
||||
|
||||
<Section title="Сценарии">
|
||||
<Section title={t("Сценарии")}>
|
||||
{CASES.map((c) => (
|
||||
<article key={c.title} className="flex flex-col gap-1 rounded-lg border bg-card px-4 py-3">
|
||||
<b>{c.title}</b>
|
||||
<p className="m-0 italic">«{c.say}»</p>
|
||||
<p className="m-0 text-muted-foreground">{c.how}</p>
|
||||
<b>{t(c.title)}</b>
|
||||
<p className="m-0 italic">{t("«{say}»", { say: t(c.say) })}</p>
|
||||
<p className="m-0 text-muted-foreground">{t(c.how)}</p>
|
||||
</article>
|
||||
))}
|
||||
</Section>
|
||||
|
||||
<Section title="Инструменты MCP">
|
||||
<Section title={t("Инструменты MCP")}>
|
||||
<div className="overflow-x-auto rounded-lg border">
|
||||
<table className="w-full border-collapse">
|
||||
<tbody>
|
||||
{TOOLS.map(([name, what]) => (
|
||||
<tr key={name} className="border-b align-top last:border-0">
|
||||
<td className="px-3 py-2 font-mono text-xs [overflow-wrap:anywhere] sm:whitespace-nowrap">{name}</td>
|
||||
<td className="px-3 py-2">{what}</td>
|
||||
<td className="px-3 py-2">{t(what)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
@ -123,135 +145,69 @@ export default async function Help() {
|
||||
</div>
|
||||
</Section>
|
||||
|
||||
<Section title="Автономность">
|
||||
<Section title={t("Автономность")}>
|
||||
<p className="m-0 text-muted-foreground">
|
||||
У каждого проекта — уровень автономности («⋯ Настройки проекта» → «Автономность», MCP <span className="font-mono">update_project_settings</span>,
|
||||
CLI <span className="font-mono">peppa project autonomy KEY</span>). <b>Ручной</b> (по умолчанию): вы двигаете карточки и принимаете стори.{" "}
|
||||
<b>С подсказками</b>: если ни один агент не работает, а в бэклоге есть стори, придёт пуш «Агенты простаивают. Взять PEP-7?» с кнопками
|
||||
«Взять / Следующую / Не сейчас» — не чаще раза в N часов и не в тихие часы. <b>Автомат</b>: Пеппа сама берёт следующую стори из
|
||||
бэклога (сверху по порядку на доске, пропуская стори, которые ждут предшественников; одновременно до N), зелёный PR без конфликтов мержит сама, стори закрывает после мержа; при конфликте агент
|
||||
сам делает rebase. Настройки можно комбинировать: одобрять каждый proposal, мержить сам, но закрывать вручную или «само через N
|
||||
часов без замечаний». Во время лимита подписки диспетчер ничего не запускает и не предлагает. PR, меняющий конвейер, всегда ждёт
|
||||
вашего «Принять». «Принять» мержит PR, Gitea удаляет ветку, рабочая копия проекта подтягивает main.
|
||||
{rich(t("У каждого проекта — уровень автономности («⋯ Настройки проекта» → «Автономность», MCP <m>update_project_settings</m>, CLI <m>peppa project autonomy KEY</m>). <b>Ручной</b> (по умолчанию): вы двигаете карточки и принимаете стори. <b>С подсказками</b>: если ни один агент не работает, а в бэклоге есть стори, придёт пуш «Агенты простаивают. Взять PEP-7?» с кнопками «Взять / Следующую / Не сейчас» — не чаще раза в N часов и не в тихие часы. <b>Автомат</b>: Пеппа сама берёт следующую стори из бэклога (сверху по порядку на доске, пропуская стори, которые ждут предшественников; одновременно до N), зелёный PR без конфликтов мержит сама, стори закрывает после мержа; при конфликте агент сам делает rebase. Настройки можно комбинировать: одобрять каждый proposal, мержить сам, но закрывать вручную или «само через N часов без замечаний». Во время лимита подписки диспетчер ничего не запускает и не предлагает. PR, меняющий конвейер, всегда ждёт вашего «Принять». «Принять» мержит PR, Gitea удаляет ветку, рабочая копия проекта подтягивает main."))}
|
||||
</p>
|
||||
</Section>
|
||||
|
||||
<Section title="Расход, бюджеты, метрики, журнал">
|
||||
<Section title={t("Расход, бюджеты, метрики, журнал")}>
|
||||
<p className="m-0 text-muted-foreground">
|
||||
<b>Лимиты</b>: полоса над каждой страницей показывает самое загруженное окно лимитов подписки (5 ч и 7 дней) и время сброса — Claude Code сам
|
||||
сообщает их строке статуса раннера. Пока ни один раннер не сообщал — «нет данных о лимитах»; Codex и OpenCode расход не сообщают. На карточке
|
||||
раннера — токены, стоимость и заполненность контекста; «≈» — стоимость оценена по прайсу API, а не сообщена агентом.{" "}
|
||||
<b>Бюджет</b>: «⋯ Настройки проекта» → «Бюджет стори» (по умолчанию для всех стори) или карточка стори (свой бюджет) — минуты раннеров,
|
||||
токены, перезапуски, стоимость; по умолчанию без предела. Превышение прерывает ход агента (разговор сохраняется) и присылает вопрос «Продлить ×2 /
|
||||
Снять лимит / Остановить»; пока вы не ответили, стори не запускается.{" "}
|
||||
<b>Метрики</b>: вкладка «Метрики» проекта — время цикла, доля принятых с первого раза, возвраты с ревью, вопросы, часы раннеров, сколько агенты
|
||||
ждали вас, расход по неделям, агентам и эпикам.{" "}
|
||||
<b>Журнал</b>: вкладка «Журнал» проекта и раздел «Журнал» суперадмина — кто что сделал: человек (веб, Telegram, MCP-клиент, CLI), агент или Пеппа.
|
||||
{rich(t("<b>Лимиты</b>: полоса над каждой страницей показывает самое загруженное окно лимитов подписки (5 ч и 7 дней) и время сброса — Claude Code сам сообщает их строке статуса раннера. Пока ни один раннер не сообщал — «нет данных о лимитах»; Codex и OpenCode расход не сообщают. На карточке раннера — токены, стоимость и заполненность контекста; «≈» — стоимость оценена по прайсу API, а не сообщена агентом. <b>Бюджет</b>: «⋯ Настройки проекта» → «Бюджет стори» (по умолчанию для всех стори) или карточка стори (свой бюджет) — минуты раннеров, токены, перезапуски, стоимость; по умолчанию без предела. Превышение прерывает ход агента (разговор сохраняется) и присылает вопрос «Продлить ×2 / Снять лимит / Остановить»; пока вы не ответили, стори не запускается. <b>Метрики</b>: вкладка «Метрики» проекта — время цикла, доля принятых с первого раза, возвраты с ревью, вопросы, часы раннеров, сколько агенты ждали вас, расход по неделям, агентам и эпикам. <b>Журнал</b>: вкладка «Журнал» проекта и раздел «Журнал» суперадмина — кто что сделал: человек (веб, Telegram, MCP-клиент, CLI), агент или Пеппа."))}
|
||||
</p>
|
||||
</Section>
|
||||
|
||||
<Section title="Секреты">
|
||||
<Section title={t("Секреты")}>
|
||||
<p className="m-0 text-muted-foreground">
|
||||
<b>Секреты проекта</b>: «⋯ Настройки проекта» → «Секреты» — ключи API и доступы для агентов (например <code>STRIPE_TEST_KEY</code>). Значение
|
||||
шифруется и после сохранения больше не показывается никому; сохранить то же имя — заменить значение. Агенты проекта получают секреты как
|
||||
переменные окружения при следующем запуске сессии, видят через MCP только имена (<code>list_secrets</code>), а в терминале раннера и ленте шагов
|
||||
значение заменяется на «••••» (кроме значений короче 4 символов и значения, разорванного переносом строки). Каждая выдача — событие
|
||||
«secrets_issued» в журнале сессии. Секреты для деплоя приложения — по-прежнему в secrets Actions репозитория.{" "}
|
||||
<b>Ревизия</b> (суперадмин, раздел «Секреты», CLI <code>peppa secrets audit</code>): секреты платформы, их возраст и кто ими пользуется, MCP-токены
|
||||
по клиентам, подписки и секреты проектов — с пошаговой ротацией. Смена <code>PEPPA_SECRET</code> без потери данных: старый ключ в
|
||||
<code>PEPPA_SECRET_PREVIOUS</code>, новый в <code>PEPPA_SECRET</code>, перезапуск, <code>peppa secrets reencrypt</code>.
|
||||
{rich(t("<b>Секреты проекта</b>: «⋯ Настройки проекта» → «Секреты» — ключи API и доступы для агентов (например <code>STRIPE_TEST_KEY</code>). Значение шифруется и после сохранения больше не показывается никому; сохранить то же имя — заменить значение. Агенты проекта получают секреты как переменные окружения при следующем запуске сессии, видят через MCP только имена (<code>list_secrets</code>), а в терминале раннера и ленте шагов значение заменяется на «••••» (кроме значений короче 4 символов и значения, разорванного переносом строки). Каждая выдача — событие «secrets_issued» в журнале сессии. Секреты для деплоя приложения — по-прежнему в secrets Actions репозитория. <b>Ревизия</b> (суперадмин, раздел «Секреты», CLI <code>peppa secrets audit</code>): секреты платформы, их возраст и кто ими пользуется, MCP-токены по клиентам, подписки и секреты проектов — с пошаговой ротацией. Смена <code>PEPPA_SECRET</code> без потери данных: старый ключ в <code>PEPPA_SECRET_PREVIOUS</code>, новый в <code>PEPPA_SECRET</code>, перезапуск, <code>peppa secrets reencrypt</code>."))}
|
||||
</p>
|
||||
</Section>
|
||||
|
||||
<Section title="CI/CD">
|
||||
<p className="m-0 text-muted-foreground">
|
||||
Каждый PR агента проверяет Gitea Actions: <span className="font-mono">install</span>, <span className="font-mono">lint</span>,{" "}
|
||||
<span className="font-mono">typecheck</span>, <span className="font-mono">test</span>, <span className="font-mono">build</span>. Команды —
|
||||
в <span className="font-mono">.peppa/project.json → checks</span> (заполняет агент на первой стори), workflow приходит из
|
||||
шаблона; в старый проект — командой <span className="font-mono">peppa ci connect KEY</span> (PR от Пеппы). Результат виден в
|
||||
карточке стори и во вкладке «PR» («Проверки: 4 из 4 пройдены»). Красная проверка уходит агенту с хвостом лога, после 3 красных
|
||||
прогонов подряд Пеппа спросит вас. В ревью стори попадает и «Принять» мержит PR только с зелёными проверками и без
|
||||
конфликтов. PR, меняющий конвейер (<span className="font-mono">.gitea/</span>, <span className="font-mono">checks</span>,{" "}
|
||||
<span className="font-mono">deploy</span>), сам не мержится никогда.
|
||||
{rich(t("Каждый PR агента проверяет Gitea Actions: <m>install</m>, <m>lint</m>, <m>typecheck</m>, <m>test</m>, <m>build</m>. Команды — в <m>.peppa/project.json → checks</m> (заполняет агент на первой стори), workflow приходит из шаблона; в старый проект — командой <m>peppa ci connect KEY</m> (PR от Пеппы). Результат виден в карточке стори и во вкладке «PR» («Проверки: 4 из 4 пройдены»). Красная проверка уходит агенту с хвостом лога, после 3 красных прогонов подряд Пеппа спросит вас. В ревью стори попадает и «Принять» мержит PR только с зелёными проверками и без конфликтов. PR, меняющий конвейер (<m>.gitea/</m>, <m>checks</m>, <m>deploy</m>), сам не мержится никогда."))}
|
||||
</p>
|
||||
<p className="m-0 text-muted-foreground">
|
||||
Агент-ревьюер (по умолчанию выключен; «⋯ Настройки проекта → Ревьюер»): когда проверки PR зелёные и агент отдаёт стори в ревью,
|
||||
короткая сессия Claude (sonnet, на подписке пула проекта) читает дифф по чек-листу — сделано ли то, что просила стори, баги,
|
||||
безопасность, тесты, мусор — и ваши дополнительные правила. Замечания уходят агенту, стори остаётся «В работе»; «ок» — стори
|
||||
приходит вам с резюме ревьюера. После лимита возвратов (по умолчанию 2) стори приходит с незакрытыми замечаниями; если
|
||||
ревьюер упал — с пометкой. Последнее ревью видно в карточке стори.
|
||||
{t("Агент-ревьюер (по умолчанию выключен; «⋯ Настройки проекта → Ревьюер»): когда проверки PR зелёные и агент отдаёт стори в ревью, короткая сессия Claude (sonnet, на подписке пула проекта) читает дифф по чек-листу — сделано ли то, что просила стори, баги, безопасность, тесты, мусор — и ваши дополнительные правила. Замечания уходят агенту, стори остаётся «В работе»; «ок» — стори приходит вам с резюме ревьюера. После лимита возвратов (по умолчанию 2) стори приходит с незакрытыми замечаниями; если ревьюер упал — с пометкой. Последнее ревью видно в карточке стори.")}
|
||||
</p>
|
||||
<p className="m-0 text-muted-foreground">
|
||||
Деплой — <span className="font-mono">deploy</span> в project.json и <span className="font-mono">Dockerfile</span> (заготовки в{" "}
|
||||
<span className="font-mono">deploy/</span>): PR получает preview <span className="font-mono">slug-prN.telecom.quest</span> (удаляется при
|
||||
закрытии), мерж выкатывает staging <span className="font-mono">slug-staging.telecom.quest</span>, прод{" "}
|
||||
<span className="font-mono">slug-prod.telecom.quest</span> — по кнопке «Выкатить в прод» (страница проекта, Telegram, MCP{" "}
|
||||
<span className="font-mono">deploy</span>). После каждого деплоя — проверка <span className="font-mono">/healthz</span> до 2 минут; не
|
||||
прошла — откат на предыдущий образ и сообщение вам. Релизы — на странице проекта.
|
||||
{rich(t("Деплой — <m>deploy</m> в project.json и <m>Dockerfile</m> (заготовки в <m>deploy/</m>): PR получает preview <m>slug-prN.telecom.quest</m> (удаляется при закрытии), мерж выкатывает staging <m>slug-staging.telecom.quest</m>, прод <m>slug-prod.telecom.quest</m> — по кнопке «Выкатить в прод» (страница проекта, Telegram, MCP <m>deploy</m>). После каждого деплоя — проверка <m>/healthz</m> до 2 минут; не прошла — откат на предыдущий образ и сообщение вам. Релизы — на странице проекта."))}
|
||||
</p>
|
||||
<p className="m-0 text-muted-foreground">
|
||||
Превью на ревью: «готово к ревью» и карточка стори (блок «Превью») показывают «Посмотреть» — стенд PR, ссылку на
|
||||
дифф и итог проверок. Шаг деплоя превью снимает скриншоты страниц из <span className="font-mono">deploy.screenshots</span>{" "}
|
||||
(по умолчанию главная, <span className="font-mono">[]</span> — выключить) — они в карточке стори.
|
||||
{rich(t("Превью на ревью: «готово к ревью» и карточка стори (блок «Превью») показывают «Посмотреть» — стенд PR, ссылку на дифф и итог проверок. Шаг деплоя превью снимает скриншоты страниц из <m>deploy.screenshots</m> (по умолчанию главная, <m>[]</m> — выключить) — они в карточке стори."))}
|
||||
</p>
|
||||
<p className="m-0 text-muted-foreground">
|
||||
Gitea знает о Пеппе: issue, открытый вами или участником проекта, становится стори в бэклоге (в issue появится
|
||||
ссылка; стори готова — issue закроется), старые открытые issues переносит{" "}
|
||||
<span className="font-mono">peppa project import-issues KEY</span>. Комментарий или ревью «нужны изменения» в PR стори
|
||||
уходит её агенту (стори из «Ревью» вернётся в работу), а мерж PR руками в Gitea переводит стори в «Готово».
|
||||
{rich(t("Gitea знает о Пеппе: issue, открытый вами или участником проекта, становится стори в бэклоге (в issue появится ссылка; стори готова — issue закроется), старые открытые issues переносит <m>peppa project import-issues KEY</m>. Комментарий или ревью «нужны изменения» в PR стори уходит её агенту (стори из «Ревью» вернётся в работу), а мерж PR руками в Gitea переводит стори в «Готово»."))}
|
||||
</p>
|
||||
<p className="m-0 text-muted-foreground">
|
||||
Сама Пеппа (проект PEP) выкатывается так же по кнопке, но без staging: после зелёных проверок{" "}
|
||||
<span className="font-mono">main</span> приходит предложение «Выкатить в прод»; релиз собирается на хосте рядом с
|
||||
работающим, перед миграциями делается копия базы, после перезапуска — проверка здоровья, не прошла — возврат
|
||||
предыдущего релиза.
|
||||
{rich(t("Сама Пеппа (проект PEP) выкатывается так же по кнопке, но без staging: после зелёных проверок <m>main</m> приходит предложение «Выкатить в прод»; релиз собирается на хосте рядом с работающим, перед миграциями делается копия базы, после перезапуска — проверка здоровья, не прошла — возврат предыдущего релиза."))}
|
||||
</p>
|
||||
</Section>
|
||||
|
||||
<Section title="Чаты">
|
||||
<Section title={t("Чаты")}>
|
||||
<p className="m-0 text-muted-foreground">
|
||||
<Link href="/chats">Чаты</Link> — у каждого проекта свой чат с тредами: тред на стори (вопросы агента, статусы,
|
||||
прогресс, комментарии, сбои раннера), на ошибку из прода и на релиз. Ответ в треде стори уходит агенту: на открытый
|
||||
вопрос, а без вопроса — комментарием, который агент сразу видит. Мастер-чат — всё важное по вашим проектам
|
||||
(вопросы, ревью, сбои, лимиты, релизы, ошибки), мониторинг и сводка; команды /status, /task KEY-N,
|
||||
/move KEY-N in_progress, /help. Вопросы по-прежнему видны и на Главной. Переписка хранится 14 дней.
|
||||
{rich(t("<a href=\"/chats\">Чаты</a> — у каждого проекта свой чат с тредами: тред на стори (вопросы агента, статусы, прогресс, комментарии, сбои раннера), на ошибку из прода и на релиз. Ответ в треде стори уходит агенту: на открытый вопрос, а без вопроса — комментарием, который агент сразу видит. Мастер-чат — всё важное по вашим проектам (вопросы, ревью, сбои, лимиты, релизы, ошибки), мониторинг и сводка; команды /status, /task KEY-N, /move KEY-N in_progress, /help. Вопросы по-прежнему видны и на Главной. Переписка хранится 14 дней."))}
|
||||
</p>
|
||||
<p className="m-0 text-muted-foreground">
|
||||
Любой чат можно связать с группой Telegram: «Связать с Telegram» в чате → добавьте бота в группу по ссылке (или
|
||||
отправьте в группе <span className="font-mono">/link код</span>). Сообщения чата придут в группу, тред — цепочкой
|
||||
ответов; ответ реплаем вернётся в тред и уйдёт агенту. Отвечать из группы могут те, кто привязал свой Telegram в
|
||||
Настройках и имеет доступ к проекту (в мастер-группе — только владелец).
|
||||
{rich(t("Любой чат можно связать с группой Telegram: «Связать с Telegram» в чате → добавьте бота в группу по ссылке (или отправьте в группе <m>/link код</m>). Сообщения чата придут в группу, тред — цепочкой ответов; ответ реплаем вернётся в тред и уйдёт агенту. Отвечать из группы могут те, кто привязал свой Telegram в Настройках и имеет доступ к проекту (в мастер-группе — только владелец)."))}
|
||||
</p>
|
||||
</Section>
|
||||
|
||||
<Section title="Telegram">
|
||||
<p className="m-0 text-muted-foreground">
|
||||
Привяжите свой Telegram в Настройках: бот присылает вопросы агентов из ваших и общих проектов и «готово к ревью» с
|
||||
кнопками; ответ реплаем уходит прямо в сессию агента. Новые ошибки из прода приходят туда же — по политике
|
||||
проекта: сообщением, стори или с кнопками «В бэклог / В работу / Игнорировать». Команды бота: /status — что
|
||||
сейчас происходит, /digest — сводка за сутки.
|
||||
{t("Привяжите свой Telegram в Настройках: бот присылает вопросы агентов из ваших и общих проектов и «готово к ревью» с кнопками; ответ реплаем уходит прямо в сессию агента. Новые ошибки из прода приходят туда же — по политике проекта: сообщением, стори или с кнопками «В бэклог / В работу / Игнорировать». Команды бота: /status — что сейчас происходит, /digest — сводка за сутки.")}
|
||||
</p>
|
||||
<p className="m-0 text-muted-foreground">
|
||||
Новую стори можно просто написать или наговорить боту: «в PAY: экспорт в CSV». Бот уточнит проект (если не указан) и
|
||||
эпик кнопками, создаст стори и предложит «Взять в работу». Голосовые работают, если на сервере настроена расшифровка.
|
||||
{t("Новую стори можно просто написать или наговорить боту: «в PAY: экспорт в CSV». Бот уточнит проект (если не указан) и эпик кнопками, создаст стори и предложит «Взять в работу». Голосовые работают, если на сервере настроена расшифровка.")}
|
||||
</p>
|
||||
</Section>
|
||||
|
||||
<Section title="Уведомления">
|
||||
<Section title={t("Уведомления")}>
|
||||
<p className="m-0 text-muted-foreground">
|
||||
В <Link href="/settings#notifications">Настройках → Уведомления</Link> для каждого события (вопросы агентов,
|
||||
готово к ревью, сбои и лимиты, релизы, ошибки из прода, дайджест) выбирается, куда присылать: Telegram и/или
|
||||
браузер. Тихие часы: Telegram приходит без звука, push не показываются. Снятые проекты не присылают ничего —
|
||||
вопросы остаются в вебе. Push в браузере включаются там же кнопкой (Chrome спросит разрешение) и работают при
|
||||
закрытой вкладке; клик открывает стори. Во вкладке Пеппы в заголовке и на значке приложения — сколько ждёт вас,
|
||||
при новом вопросе звучит сигнал (если звук включён). Ежедневный дайджест приходит в выбранное время (по умолчанию
|
||||
09:00): сделано за сутки, в работе, на ревью, ждёт вас, зависло, лимиты; пустой не приходит.
|
||||
{rich(t("В <a href=\"/settings#notifications\">Настройках → Уведомления</a> для каждого события (вопросы агентов, готово к ревью, сбои и лимиты, релизы, ошибки из прода, дайджест) выбирается, куда присылать: Telegram и/или браузер. Тихие часы: Telegram приходит без звука, push не показываются. Снятые проекты не присылают ничего — вопросы остаются в вебе. Push в браузере включаются там же кнопкой (Chrome спросит разрешение) и работают при закрытой вкладке; клик открывает стори. Во вкладке Пеппы в заголовке и на значке приложения — сколько ждёт вас, при новом вопросе звучит сигнал (если звук включён). Ежедневный дайджест приходит в выбранное время (по умолчанию 09:00): сделано за сутки, в работе, на ревью, ждёт вас, зависло, лимиты; пустой не приходит."))}
|
||||
</p>
|
||||
<p className="m-0 text-muted-foreground">
|
||||
Новости самой Пеппы — новые версии, падения и перезапуски сервисов, «Дайджест обновлений Пеппы» (что нового и
|
||||
что происходит сейчас) — идут в Telegram-канал платформы, который настраивает суперадмин в разделе «Платформа».
|
||||
Если он включил рассылку в личные чаты, дайджест обновлений приходит и вам; отключить — строка «Дайджест
|
||||
обновлений Пеппы» в Настройках → Уведомления.
|
||||
{t("Новости самой Пеппы — новые версии, падения и перезапуски сервисов, «Дайджест обновлений Пеппы» (что нового и что происходит сейчас) — идут в Telegram-канал платформы, который настраивает суперадмин в разделе «Платформа». Если он включил рассылку в личные чаты, дайджест обновлений приходит и вам; отключить — строка «Дайджест обновлений Пеппы» в Настройках → Уведомления.")}
|
||||
</p>
|
||||
</Section>
|
||||
</div>
|
||||
|
||||
@ -3,22 +3,24 @@ import { ShortcutsList } from "@/components/CommandPalette";
|
||||
import { PageHeader, Section } from "@/components/common";
|
||||
import { Workspace } from "@/components/Workspace";
|
||||
import { PALETTE_KEYS } from "@/lib/shortcuts";
|
||||
import { getT } from "@/lib/i18n";
|
||||
|
||||
/** PEP-52: list of keyboard shortcuts (the same list as the «?» dialog). */
|
||||
export default function Shortcuts() {
|
||||
export default async function Shortcuts() {
|
||||
const t = await getT();
|
||||
return (
|
||||
<Workspace>
|
||||
<div className="max-w-3xl text-sm">
|
||||
<PageHeader crumbs={<Link href="/help" className="text-muted-foreground hover:text-foreground">Помощь</Link>} title="Горячие клавиши">
|
||||
Клавиши без ⌘/Ctrl работают, когда курсор не в поле ввода.
|
||||
<PageHeader crumbs={<Link href="/help" className="text-muted-foreground hover:text-foreground">{t("Помощь")}</Link>} title={t("Горячие клавиши")}>
|
||||
{t("Клавиши без ⌘/Ctrl работают, когда курсор не в поле ввода.")}
|
||||
</PageHeader>
|
||||
<Section title="Сочетания">
|
||||
<Section title={t("Сочетания")}>
|
||||
<div className="rounded-lg border bg-card px-4 py-2">
|
||||
<ShortcutsList />
|
||||
</div>
|
||||
</Section>
|
||||
<Section title="В палитре">
|
||||
<p className="m-0 text-muted-foreground">{PALETTE_KEYS}. Поиск — по ключу, названию и проекту; все слова запроса должны совпасть.</p>
|
||||
<Section title={t("В палитре")}>
|
||||
<p className="m-0 text-muted-foreground">{t(PALETTE_KEYS)}. {t("Поиск — по ключу, названию и проекту; все слова запроса должны совпасть.")}</p>
|
||||
</Section>
|
||||
</div>
|
||||
</Workspace>
|
||||
|
||||
@ -7,6 +7,7 @@ import { revalidatePath } from "next/cache";
|
||||
import { redirect } from "next/navigation";
|
||||
import { asWebActor, requireUser } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { getT } from "@/lib/i18n";
|
||||
|
||||
const str = (f: FormData, k: string) => String(f.get(k) ?? "").trim();
|
||||
const BASE = "/hosts";
|
||||
@ -18,7 +19,8 @@ async function attempt(f: FormData, fn: () => Promise<string | void>): Promise<n
|
||||
await requireSuperadmin(db, user);
|
||||
target = (await fn()) || target;
|
||||
} catch (e) {
|
||||
const msg = e instanceof PeppaError ? e.message : `Ошибка: ${(e as Error).message}`;
|
||||
const t = await getT();
|
||||
const msg = e instanceof PeppaError ? t.text(e.message) : t("Ошибка: {message}", { message: (e as Error).message });
|
||||
target = `${BASE}?error=${encodeURIComponent(msg.slice(0, 300))}`;
|
||||
}
|
||||
revalidatePath("/", "layout");
|
||||
|
||||
@ -11,76 +11,81 @@ import { Input, Label } from "@/components/ui/input";
|
||||
import { Workspace } from "@/components/Workspace";
|
||||
import { requireUser } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import type { Translator } from "@peppa/shared/i18n";
|
||||
import { addHostAction, checkHostAction, deleteHostAction, toggleHostAction, updateHostAction } from "./actions";
|
||||
|
||||
export const metadata = { title: "Хосты — Пеппа" };
|
||||
|
||||
function StatusOf({ h }: { h: RunnerHostView }) {
|
||||
if (h.disabledAt) return <Badge variant="secondary">отключён</Badge>;
|
||||
return <Badge variant={h.status === "online" ? "ok" : h.status === "offline" ? "danger" : "info"}>{HOST_STATUS_RU[h.status]}</Badge>;
|
||||
export async function generateMetadata() {
|
||||
const t = await getT();
|
||||
return { title: t("Хосты — Пеппа") };
|
||||
}
|
||||
|
||||
function HostFields({ h }: { h?: RunnerHostView }) {
|
||||
function StatusOf({ h, t }: { h: RunnerHostView; t: Translator }) {
|
||||
if (h.disabledAt) return <Badge variant="secondary">{t("отключён")}</Badge>;
|
||||
return <Badge variant={h.status === "online" ? "ok" : h.status === "offline" ? "danger" : "info"}>{t(HOST_STATUS_RU[h.status])}</Badge>;
|
||||
}
|
||||
|
||||
function HostFields({ h, t }: { h?: RunnerHostView; t: Translator }) {
|
||||
return (
|
||||
<div className="grid gap-2 sm:grid-cols-2">
|
||||
<Label>
|
||||
SSH-адрес
|
||||
{t("SSH-адрес")}
|
||||
<Input name="sshTarget" required placeholder="peppa@build1.example.com" defaultValue={h?.sshTarget} className="h-8 font-mono" />
|
||||
</Label>
|
||||
<Label>
|
||||
Порт SSH
|
||||
{t("Порт SSH")}
|
||||
<Input name="sshPort" type="number" min={1} max={65535} placeholder="22" defaultValue={h?.sshPort} className="h-8" />
|
||||
</Label>
|
||||
<Label>
|
||||
Каталог на хосте (от домашнего)
|
||||
{t("Каталог на хосте (от домашнего)")}
|
||||
<Input name="workdir" placeholder="peppa" defaultValue={h?.workdir} className="h-8 font-mono" />
|
||||
</Label>
|
||||
<Label>
|
||||
Адрес Пеппы для хоста (релей агента)
|
||||
<Input name="peppaUrl" placeholder="как PEPPA_WEB_URL" defaultValue={h?.peppaUrl ?? ""} className="h-8 font-mono" />
|
||||
{t("Адрес Пеппы для хоста (релей агента)")}
|
||||
<Input name="peppaUrl" placeholder={t("как PEPPA_WEB_URL")} defaultValue={h?.peppaUrl ?? ""} className="h-8 font-mono" />
|
||||
</Label>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function HostCard({ h }: { h: RunnerHostView }) {
|
||||
function HostCard({ h, t }: { h: RunnerHostView; t: Translator }) {
|
||||
const i = h.info ?? {};
|
||||
return (
|
||||
<Card id={`h-${h.id}`} className="gap-2">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className="font-semibold">{h.name}</span>
|
||||
<span className="font-mono text-xs text-muted-foreground">{h.sshTarget}{h.sshPort !== 22 ? `:${h.sshPort}` : ""}</span>
|
||||
<StatusOf h={h} />
|
||||
<span className="ml-auto text-xs text-muted-foreground">раннеров: {h.runners}</span>
|
||||
<StatusOf h={h} t={t} />
|
||||
<span className="ml-auto text-xs text-muted-foreground">{t("раннеров: {n}", { n: h.runners })}</span>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-x-4 gap-y-1 text-xs text-muted-foreground">
|
||||
{i.load != null && <span>загрузка {i.load}{i.cpus ? ` / ${i.cpus} CPU` : ""}</span>}
|
||||
{i.load != null && <span>{t("загрузка {load}", { load: i.load })}{i.cpus ? ` / ${i.cpus} CPU` : ""}</span>}
|
||||
{i.docker && <span>docker {i.docker}</span>}
|
||||
{i.tmux && <span>{i.tmux}</span>}
|
||||
{i.os && <span>{i.os}</span>}
|
||||
<span>образ раннера: {i.image ? <span className="font-mono">{i.image}</span> : "не загружен"}</span>
|
||||
<span>проверен {ago(h.lastSeenAt)}</span>
|
||||
<span>{t("образ раннера:")} {i.image ? <span className="font-mono">{i.image}</span> : t("не загружен")}</span>
|
||||
<span>{t("проверен {ago}", { ago: ago(h.lastSeenAt, t) })}</span>
|
||||
</div>
|
||||
{h.lastError && <p className="m-0 text-xs text-destructive">{h.lastError}</p>}
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<form action={checkHostAction}>
|
||||
<Hidden fields={{ id: h.id }} />
|
||||
<Button size="sm" variant="outline"><RefreshCw />Проверить</Button>
|
||||
<Button size="sm" variant="outline"><RefreshCw />{t("Проверить")}</Button>
|
||||
</form>
|
||||
<form action={toggleHostAction}>
|
||||
<Hidden fields={{ id: h.id, disable: h.disabledAt ? "0" : "1" }} />
|
||||
<Button size="sm" variant="outline">{h.disabledAt ? "Включить" : "Отключить"}</Button>
|
||||
<Button size="sm" variant="outline">{h.disabledAt ? t("Включить") : t("Отключить")}</Button>
|
||||
</form>
|
||||
<form action={deleteHostAction}>
|
||||
<Hidden fields={{ id: h.id }} />
|
||||
<Button size="sm" variant="ghost" disabled={h.runners > 0} title={h.runners > 0 ? "На хосте работают раннеры" : undefined}><Trash2 />Удалить</Button>
|
||||
<Button size="sm" variant="ghost" disabled={h.runners > 0} title={h.runners > 0 ? t("На хосте работают раннеры") : undefined}><Trash2 />{t("Удалить")}</Button>
|
||||
</form>
|
||||
</div>
|
||||
<Disclosure summary="Изменить">
|
||||
<Disclosure summary={t("Изменить")}>
|
||||
<form action={updateHostAction} className="flex flex-col gap-2">
|
||||
<Hidden fields={{ id: h.id }} />
|
||||
<HostFields h={h} />
|
||||
<Button size="sm" variant="default" className="self-start">Сохранить и проверить</Button>
|
||||
<HostFields h={h} t={t} />
|
||||
<Button size="sm" variant="default" className="self-start">{t("Сохранить и проверить")}</Button>
|
||||
</form>
|
||||
</Disclosure>
|
||||
</Card>
|
||||
@ -89,42 +94,43 @@ function HostCard({ h }: { h: RunnerHostView }) {
|
||||
|
||||
export default async function Hosts({ searchParams }: { searchParams: Promise<{ error?: string }> }) {
|
||||
const user = await requireUser();
|
||||
const t = await getT();
|
||||
if (!(await isSuperadmin(db, user))) notFound();
|
||||
const { error } = await searchParams;
|
||||
const [hosts, pub] = await Promise.all([listHosts(db), ensureSshKey().catch((e: Error) => `(ключ не создан: ${e.message})`)]);
|
||||
const [hosts, pub] = await Promise.all([listHosts(db), ensureSshKey().catch((e: Error) => t("(ключ не создан: {message})", { message: e.message }))]);
|
||||
return (
|
||||
<Workspace>
|
||||
<div className="max-w-3xl">
|
||||
<Flash error={error} />
|
||||
<PageHeader title={<><Server className="mr-1 inline size-5 text-primary" />Хосты</>}>
|
||||
Серверы, на которых работают раннеры. Пеппа заходит на хост по SSH своим ключом и запускает там tmux с агентом в контейнере образа раннера; агент ходит в Пеппу только через релей. Демона на хосте нет — нужны sshd, tmux и docker. Проект выбирает хосты в «⋯ Настройки проекта → Раннеры». Раздел видят только суперадмины.
|
||||
<PageHeader title={<><Server className="mr-1 inline size-5 text-primary" />{t("Хосты")}</>}>
|
||||
{t("Серверы, на которых работают раннеры. Пеппа заходит на хост по SSH своим ключом и запускает там tmux с агентом в контейнере образа раннера; агент ходит в Пеппу только через релей. Демона на хосте нет — нужны sshd, tmux и docker. Проект выбирает хосты в «⋯ Настройки проекта → Раннеры». Раздел видят только суперадмины.")}
|
||||
</PageHeader>
|
||||
|
||||
<Section title="Хосты" count={hosts.length}>
|
||||
{hosts.length === 0 ? <Empty>Хостов нет — раннеры работают на Mac Пеппы.</Empty> : hosts.map((h) => <HostCard key={h.id} h={h} />)}
|
||||
<Disclosure summary={<span className="flex items-center gap-1.5"><Plus className="size-4" />Подключить хост</span>}>
|
||||
<Section title={t("Хосты")} count={hosts.length}>
|
||||
{hosts.length === 0 ? <Empty>{t("Хостов нет — раннеры работают на Mac Пеппы.")}</Empty> : hosts.map((h) => <HostCard key={h.id} h={h} t={t} />)}
|
||||
<Disclosure summary={<span className="flex items-center gap-1.5"><Plus className="size-4" />{t("Подключить хост")}</span>}>
|
||||
<form action={addHostAction} className="flex flex-col gap-2">
|
||||
<Label>
|
||||
Имя
|
||||
{t("Имя")}
|
||||
<Input name="name" required placeholder="build1" className="h-8" />
|
||||
</Label>
|
||||
<HostFields />
|
||||
<Button size="sm" variant="default" className="self-start">Подключить и проверить</Button>
|
||||
<HostFields t={t} />
|
||||
<Button size="sm" variant="default" className="self-start">{t("Подключить и проверить")}</Button>
|
||||
</form>
|
||||
</Disclosure>
|
||||
</Section>
|
||||
|
||||
<Section title="Как подготовить хост">
|
||||
<Section title={t("Как подготовить хост")}>
|
||||
<ol className="m-0 flex list-decimal flex-col gap-2 pl-5 text-sm">
|
||||
<li>
|
||||
Добавьте ключ Пеппы в <code>~/.ssh/authorized_keys</code> пользователя на хосте:
|
||||
{t("Добавьте ключ Пеппы в {file} пользователя на хосте:").split("{file}").flatMap((part, i) => (i ? [<code key={i}>~/.ssh/authorized_keys</code>, part] : [part]))}
|
||||
<pre className="mt-1 overflow-x-auto rounded-md bg-muted p-2 text-xs"><code>{pub}</code></pre>
|
||||
</li>
|
||||
<li>Установите tmux и docker; пользователь должен иметь доступ к docker.</li>
|
||||
<li>{t("Установите tmux и docker; пользователь должен иметь доступ к docker.")}</li>
|
||||
<li>
|
||||
Загрузите образ раннера <code>{runnerImage()}</code>: <code>scripts/runner-image.sh --push <имя хоста></code> (или <code>peppa host push-image <имя></code>).
|
||||
{t("Загрузите образ раннера")} <code>{runnerImage()}</code>: <code>{t("scripts/runner-image.sh --push <имя хоста>")}</code> ({t("или")} <code>{t("peppa host push-image <имя>")}</code>).
|
||||
</li>
|
||||
<li>Адрес Пеппы для хоста должен открываться с хоста (по умолчанию — адрес веба); через него идут хуки, MCP и git агента.</li>
|
||||
<li>{t("Адрес Пеппы для хоста должен открываться с хоста (по умолчанию — адрес веба); через него идут хуки, MCP и git агента.")}</li>
|
||||
</ol>
|
||||
</Section>
|
||||
</div>
|
||||
|
||||
@ -5,11 +5,13 @@ import { PageHeader } from "@/components/common";
|
||||
import { Workspace } from "@/components/Workspace";
|
||||
import { requireUser } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { getT } from "@/lib/i18n";
|
||||
|
||||
/** Superadmin only (PEP-48): who did what — people (web, Telegram, MCP clients, CLI), agents, Peppa. */
|
||||
export default async function Journal({ searchParams }: { searchParams: Promise<{ project?: string; actor?: string; channel?: string; all?: string }> }) {
|
||||
const me = await requireUser();
|
||||
if (!(await isSuperadmin(db, me))) notFound();
|
||||
const t = await getT();
|
||||
const { project, actor, channel, all } = await searchParams;
|
||||
const projects = await listProjects(db);
|
||||
const p = project ? await getProject(db, project).catch(() => null) : null;
|
||||
@ -22,9 +24,9 @@ export default async function Journal({ searchParams }: { searchParams: Promise<
|
||||
});
|
||||
return (
|
||||
<Workspace aside={null}>
|
||||
<PageHeader title="Журнал действий">
|
||||
Кто что сделал: люди (веб, Telegram, MCP-клиенты, CLI, терминал), агенты и сама Пеппа. Новые сверху, последние 300.
|
||||
{!all && " Служебные события хуков скрыты."}
|
||||
<PageHeader title={t("Журнал действий")}>
|
||||
{t("Кто что сделал: люди (веб, Telegram, MCP-клиенты, CLI, терминал), агенты и сама Пеппа. Новые сверху, последние 300.")}
|
||||
{!all && " " + t("Служебные события хуков скрыты.")}
|
||||
</PageHeader>
|
||||
<div className="mb-4">
|
||||
<JournalFilters action="/journal" projects={projects.map((x) => ({ key: x.key, name: x.name }))} value={{ project, actor, channel }} />
|
||||
|
||||
@ -21,6 +21,8 @@ import { SubscriptionSetup } from "@/components/SubscriptionSetup";
|
||||
import { requireUser } from "@/lib/auth";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { db } from "@/lib/db";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import { intlLocale, m, type Translator } from "@peppa/shared/i18n";
|
||||
import { board, projectForUserByKey, projectSessions } from "@/lib/queries";
|
||||
import { addProjectMember, addTask, deployProdAction, grantRepoAccessToMembers, removeProjectMember, saveReviewSettingsAction, saveIntakeSettingsAction, setProjectVisibilityAction, connectOwnSubscriptionAction, chooseSharedSubscriptionAction } from "../../actions";
|
||||
import { AgentsMdTab, CodeTab, EpicsPanel, EpicsTab, MemorySection, ProgressBar, PullsTab, SpecsTab } from "./tabs";
|
||||
@ -29,28 +31,28 @@ import { JournalFilters, JournalList, MetricsTab, ProjectBudgetPanel } from "@/c
|
||||
import { saveProjectBudgetAction } from "../../actions";
|
||||
|
||||
const RELEASE_STATUS: Record<Release["status"], { label: string; tone: "info" | "ok" | "warn" | "danger" | "muted" }> = {
|
||||
deploying: { label: "выкатывается", tone: "info" },
|
||||
healthy: { label: "работает", tone: "ok" },
|
||||
rolled_back: { label: "откат", tone: "warn" },
|
||||
failed: { label: "не поднялся", tone: "danger" },
|
||||
removed: { label: "удалён", tone: "muted" },
|
||||
deploying: { label: m("выкатывается"), tone: "info" },
|
||||
healthy: { label: m("работает"), tone: "ok" },
|
||||
rolled_back: { label: m("откат"), tone: "warn" },
|
||||
failed: { label: m("не поднялся"), tone: "danger" },
|
||||
removed: { label: m("удалён"), tone: "muted" },
|
||||
};
|
||||
|
||||
const TABS = [
|
||||
{ id: "board", label: "Доска" },
|
||||
{ id: "epics", label: "Эпики" },
|
||||
{ id: "code", label: "Код" },
|
||||
{ id: "specs", label: "Спеки" },
|
||||
{ id: "board", label: m("Доска") },
|
||||
{ id: "epics", label: m("Эпики") },
|
||||
{ id: "code", label: m("Код") },
|
||||
{ id: "specs", label: m("Спеки") },
|
||||
{ id: "agents", label: "AGENTS.md" },
|
||||
{ id: "pulls", label: "PR" },
|
||||
{ id: "releases", label: "Релизы" },
|
||||
{ id: "bugs", label: "Баги" },
|
||||
{ id: "sessions", label: "Сессии" },
|
||||
{ id: "metrics", label: "Метрики" },
|
||||
{ id: "journal", label: "Журнал" },
|
||||
{ id: "releases", label: m("Релизы") },
|
||||
{ id: "bugs", label: m("Баги") },
|
||||
{ id: "sessions", label: m("Сессии") },
|
||||
{ id: "metrics", label: m("Метрики") },
|
||||
{ id: "journal", label: m("Журнал") },
|
||||
] as const;
|
||||
|
||||
function EnvLine({ name, r }: { name: string; r: Release | null | undefined }) {
|
||||
function EnvLine({ name, r, t }: { name: string; r: Release | null | undefined; t: Translator }) {
|
||||
return (
|
||||
<div className="flex min-w-0 flex-1 flex-col gap-0.5 rounded-md border bg-background/40 px-3 py-2">
|
||||
<span className="font-mono text-[11px] tracking-wider text-muted-foreground uppercase">{name}</span>
|
||||
@ -64,7 +66,7 @@ function EnvLine({ name, r }: { name: string; r: Release | null | undefined }) {
|
||||
)}
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-sm text-muted-foreground">нет</span>
|
||||
<span className="text-sm text-muted-foreground">{t("нет")}</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
@ -74,7 +76,8 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
||||
const user = await requireUser();
|
||||
const { key } = await params;
|
||||
const { error, created, tab: tabParam, epic: epicParam, weeks, actor, channel, edit, saved } = await searchParams;
|
||||
const tab = TABS.find((t) => t.id === tabParam)?.id ?? "board";
|
||||
const t = await getT();
|
||||
const tab = TABS.find((x) => x.id === tabParam)?.id ?? "board";
|
||||
const p = await projectForUserByKey(user.id, key).catch(() => null);
|
||||
if (!p) notFound();
|
||||
const [{ tasks }, epics, sessions, team, repo, incidentSettings, sources, incidents, releases, current, reviewer, progress, deps] = await Promise.all([
|
||||
@ -121,20 +124,20 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
||||
const agentNames = await taskAgentNames(db, p.id);
|
||||
const [intake, refining] = await Promise.all([getIntakeSettings(db, p.id), intakePendingTasks(db, p.id)]);
|
||||
const cards: Card[] = tasks
|
||||
.filter((t) => !epicFilter || t.goalId === epicFilter.id)
|
||||
.map((t) => {
|
||||
const pr = columnOf(t.status) === "in_progress" ? taskProgress(p, t.openspecChange) : null;
|
||||
.filter((x) => !epicFilter || x.goalId === epicFilter.id)
|
||||
.map((x) => {
|
||||
const pr = columnOf(x.status) === "in_progress" ? taskProgress(p, x.openspecChange) : null;
|
||||
return {
|
||||
key: `${p.key}-${t.number}`,
|
||||
title: t.title,
|
||||
status: t.status,
|
||||
column: columnOf(t.status),
|
||||
epic: t.goalId ? (epicTitle.get(t.goalId) ?? null) : null,
|
||||
key: `${p.key}-${x.number}`,
|
||||
title: x.title,
|
||||
status: x.status,
|
||||
column: columnOf(x.status),
|
||||
epic: x.goalId ? (epicTitle.get(x.goalId) ?? null) : null,
|
||||
// PEP-33: tasks.md progress of stories in work.
|
||||
progress: pr && { done: pr.done, total: pr.total, current: pr.current },
|
||||
blocked: t.status === "backlog" ? blockedLabel(deps.get(t.id)) : null,
|
||||
agent: agentNames.get(t.id) ?? null,
|
||||
refining: refining.has(t.id) ? (refining.get(t.id) === "waiting" ? "ждёт ваших ответов" : "уточняется") : null,
|
||||
blocked: x.status === "backlog" ? blockedLabel(deps.get(x.id)) : null,
|
||||
agent: agentNames.get(x.id) ?? null,
|
||||
refining: refining.has(x.id) ? (refining.get(x.id) === "waiting" ? t("ждёт ваших ответов") : t("уточняется")) : null,
|
||||
};
|
||||
});
|
||||
// Gitea and the working copy are read only for the open tab.
|
||||
@ -149,113 +152,112 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
||||
|
||||
const aside = (
|
||||
<div className="flex flex-col gap-6">
|
||||
<PanelSection title="Репозиторий">
|
||||
<PanelSection title={t("Репозиторий")}>
|
||||
<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>
|
||||
<dt className="text-muted-foreground">{t("Где")}</dt>
|
||||
<dd className="m-0 truncate">
|
||||
<a href={repo.url} className="text-primary">{repo.fullName}</a>
|
||||
</dd>
|
||||
<dt className="text-muted-foreground">Пространство</dt>
|
||||
<dt className="text-muted-foreground">{t("Пространство")}</dt>
|
||||
<dd className="m-0">
|
||||
{p.giteaOwner}
|
||||
{repo.ownerKind && ` — ${repo.ownerKind === "org" ? "организация" : "личное"}`}
|
||||
{repo.ownerKind && <> — {repo.ownerKind === "org" ? t("организация") : t("личное")}</>}
|
||||
</dd>
|
||||
<dt className="text-muted-foreground">Видимость</dt>
|
||||
<dd className="m-0">{repoVisibilityLabel(repo.private)}</dd>
|
||||
<dt className="text-muted-foreground">Кто видит</dt>
|
||||
<dd className="m-0">{repoAudience(repo)}</dd>
|
||||
<dt className="text-muted-foreground">Рабочая копия</dt>
|
||||
<dt className="text-muted-foreground">{t("Видимость")}</dt>
|
||||
<dd className="m-0">{t.text(repoVisibilityLabel(repo.private))}</dd>
|
||||
<dt className="text-muted-foreground">{t("Кто видит")}</dt>
|
||||
<dd className="m-0">{t.text(repoAudience(repo))}</dd>
|
||||
<dt className="text-muted-foreground">{t("Рабочая копия")}</dt>
|
||||
<dd className="m-0 font-mono text-xs break-all">{p.workspacePath}</dd>
|
||||
</dl>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button asChild size="sm">
|
||||
<a href={repo.url}>
|
||||
Открыть в Gitea <ExternalLink />
|
||||
{t("Открыть в Gitea")} <ExternalLink />
|
||||
</a>
|
||||
</Button>
|
||||
{isOwner && repo.private !== null && (
|
||||
<form action={setProjectVisibilityAction}>
|
||||
<Hidden fields={{ projectId: p.id, visibility: repo.private ? "public" : "private", back }} />
|
||||
<Button size="sm" variant="outline">{repo.private ? "Сделать публичным" : "Сделать приватным"}</Button>
|
||||
<Button size="sm" variant="outline">{repo.private ? t("Сделать публичным") : t("Сделать приватным")}</Button>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
{isOwner && repo.private !== null && (
|
||||
<p className="m-0 text-xs text-muted-foreground">
|
||||
{repo.private ? "Публичный репозиторий видят все, у кого есть доступ к Gitea." : "Приватный репозиторий видят только владелец пространства, соавторы и peppa-bot."} Видимость меняется в Gitea сразу.
|
||||
{repo.private ? t("Публичный репозиторий видят все, у кого есть доступ к Gitea.") : t("Приватный репозиторий видят только владелец пространства, соавторы и peppa-bot.")} {t("Видимость меняется в Gitea сразу.")}
|
||||
</p>
|
||||
)}
|
||||
</PanelSection>
|
||||
|
||||
<PanelSection title="Автономность">
|
||||
<PanelSection title={t("Автономность")}>
|
||||
<AutonomyPanel projectId={p.id} settings={autonomy} back={back} />
|
||||
</PanelSection>
|
||||
|
||||
<PanelSection title="Раннеры">
|
||||
<PanelSection title={t("Раннеры")}>
|
||||
<RunnerSettingsPanel projectId={p.id} own={runnerOwn} inherited={{ ...DEFAULT_RUNNER_SETTINGS, ...runnerSystem }} back={back} hosts={runnerHosts} />
|
||||
</PanelSection>
|
||||
|
||||
<PanelSection title="Модель агента">
|
||||
<PanelSection title={t("Модель агента")}>
|
||||
<AgentModelPanel projectId={p.id} own={agentOwn} inherited={{ ...DEFAULT_AGENT_SETTINGS, ...agentSystem }} back={back} />
|
||||
</PanelSection>
|
||||
|
||||
<PanelSection title="Эпики" count={epics.length}>
|
||||
<PanelSection title={t("Эпики")} count={epics.length}>
|
||||
<EpicsPanel projectId={p.id} projectKey={p.key} epics={epics} progress={progress} back={back} />
|
||||
</PanelSection>
|
||||
|
||||
<PanelSection title="Секреты" count={secrets.length}>
|
||||
<PanelSection title={t("Секреты")} count={secrets.length}>
|
||||
<ProjectSecretsPanel projectId={p.id} secrets={secrets} back={back} />
|
||||
</PanelSection>
|
||||
|
||||
<PanelSection title="Бюджет стори">
|
||||
<PanelSection title={t("Бюджет стори")}>
|
||||
<ProjectBudgetPanel projectId={p.id} budget={projectBudget} back={back} action={saveProjectBudgetAction} />
|
||||
</PanelSection>
|
||||
|
||||
<PanelSection title="Продакт и аналитик">
|
||||
<PanelSection title={t("Продакт и аналитик")}>
|
||||
<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" />
|
||||
Новые стори сначала уточняют продакт и аналитик
|
||||
{t("Новые стори сначала уточняют продакт и аналитик")}
|
||||
</label>
|
||||
<label className="flex items-center gap-2 text-sm">
|
||||
Ждать ответа на вопросы, минут
|
||||
<Input type="number" name="waitMin" min={0} max={1440} defaultValue={intake.waitMin} aria-label="Сколько минут аналитик ждёт ответа" className="h-8 w-20" />
|
||||
{t("Ждать ответа на вопросы, минут")}
|
||||
<Input type="number" name="waitMin" min={0} max={1440} defaultValue={intake.waitMin} aria-label={t("Сколько минут аналитик ждёт ответа")} className="h-8 w-20" />
|
||||
</label>
|
||||
<Button size="sm" className="self-start">Сохранить</Button>
|
||||
<Button size="sm" className="self-start">{t("Сохранить")}</Button>
|
||||
</form>
|
||||
<p className="m-0 text-xs text-muted-foreground">
|
||||
Продакт решает, зачем это и что берём в первую версию; аналитик пишет критерии приёмки и задаёт до трёх вопросов. Не ответили вовремя — идёт по вариантам по умолчанию (ночью ждёт до утра). Стори, созданные
|
||||
до включения, не трогает.
|
||||
{t("Продакт решает, зачем это и что берём в первую версию; аналитик пишет критерии приёмки и задаёт до трёх вопросов. Не ответили вовремя — идёт по вариантам по умолчанию (ночью ждёт до утра). Стори, созданные до включения, не трогает.")}
|
||||
</p>
|
||||
</PanelSection>
|
||||
|
||||
<PanelSection title="Ревьюер">
|
||||
<PanelSection title={t("Ревьюер")}>
|
||||
<form action={saveReviewSettingsAction} 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={reviewer.enabled} className="size-4 accent-primary" />
|
||||
Агент-ревьюер читает дифф до ревью PM
|
||||
{t("Агент-ревьюер читает дифф до ревью PM")}
|
||||
</label>
|
||||
<label className="flex items-center gap-2 text-sm">
|
||||
Возвратов агенту не больше
|
||||
<Input type="number" name="maxIterations" min={1} max={10} defaultValue={reviewer.maxIterations} aria-label="Лимит итераций ревьюера" className="h-8 w-20" />
|
||||
{t("Возвратов агенту не больше")}
|
||||
<Input type="number" name="maxIterations" min={1} max={10} defaultValue={reviewer.maxIterations} aria-label={t("Лимит итераций ревьюера")} className="h-8 w-20" />
|
||||
</label>
|
||||
<Textarea
|
||||
name="rules"
|
||||
rows={3}
|
||||
defaultValue={reviewer.rules ?? ""}
|
||||
aria-label="Дополнительные правила ревьюера"
|
||||
placeholder="Дополнительные правила ревьюера: например, «новые эндпоинты — только с проверкой доступа», «без новых зависимостей»"
|
||||
aria-label={t("Дополнительные правила ревьюера")}
|
||||
placeholder={t("Дополнительные правила ревьюера: например, «новые эндпоинты — только с проверкой доступа», «без новых зависимостей»")}
|
||||
/>
|
||||
<Button size="sm" className="self-start">Сохранить</Button>
|
||||
<Button size="sm" className="self-start">{t("Сохранить")}</Button>
|
||||
</form>
|
||||
<p className="m-0 text-xs text-muted-foreground">
|
||||
Когда проверки PR зелёные и агент отдаёт стори в ревью, короткая сессия Claude (sonnet, на подписке пула проекта) читает дифф по чек-листу. Замечания уходят агенту, «ок» — стори к вам с резюме ревьюера. После лимита возвратов стори приходит к вам с незакрытыми замечаниями.
|
||||
{t("Когда проверки PR зелёные и агент отдаёт стори в ревью, короткая сессия Claude (sonnet, на подписке пула проекта) читает дифф по чек-листу. Замечания уходят агенту, «ок» — стори к вам с резюме ревьюера. После лимита возвратов стори приходит к вам с незакрытыми замечаниями.")}
|
||||
</p>
|
||||
</PanelSection>
|
||||
|
||||
<PanelSection title="Баги">
|
||||
<PanelSection title={t("Баги")}>
|
||||
<IncidentSettingsPanel
|
||||
projectId={p.id}
|
||||
back={back}
|
||||
@ -266,22 +268,22 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
||||
/>
|
||||
</PanelSection>
|
||||
|
||||
<PanelSection title="Участники" count={team.members.length + 1}>
|
||||
<PanelSection title={t("Участники")} count={team.members.length + 1}>
|
||||
<ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm">
|
||||
<li className="flex flex-col rounded-md px-2 py-1.5">
|
||||
<span className="font-medium">{team.owner?.login ?? "—"}</span>
|
||||
<span className="text-xs text-muted-foreground">владелец</span>
|
||||
<span className="text-xs text-muted-foreground">{t("владелец")}</span>
|
||||
</li>
|
||||
{team.members.map((m) => (
|
||||
<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">{t("участник")}{noRepoAccess(m.login) && " · " + t("нет доступа к репозиторию")}</span>
|
||||
</span>
|
||||
{(isOwner || m.id === user.id) && (
|
||||
<form action={removeProjectMember}>
|
||||
<Hidden fields={{ projectId: p.id, login: m.login, back }} />
|
||||
<Button size="xs" variant="destructive">{m.id === user.id ? "Выйти из проекта" : "Убрать"}</Button>
|
||||
<Button size="xs" variant="destructive">{m.id === user.id ? t("Выйти из проекта") : t("Убрать")}</Button>
|
||||
</form>
|
||||
)}
|
||||
</li>
|
||||
@ -290,12 +292,12 @@ 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">{t("приглашён · появится после первого входа в Пеппу")}</span>
|
||||
</span>
|
||||
{isOwner && (
|
||||
<form action={removeProjectMember}>
|
||||
<Hidden fields={{ projectId: p.id, login, back }} />
|
||||
<Button size="xs" variant="destructive">Отозвать</Button>
|
||||
<Button size="xs" variant="destructive">{t("Отозвать")}</Button>
|
||||
</form>
|
||||
)}
|
||||
</li>
|
||||
@ -304,27 +306,27 @@ 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" />
|
||||
<Button size="sm">Добавить участника</Button>
|
||||
<Input name="login" required placeholder={t("Логин в Gitea")} aria-label={t("Логин участника в Gitea")} className="h-8" />
|
||||
<Button size="sm">{t("Добавить участника")}</Button>
|
||||
</form>
|
||||
)}
|
||||
{isOwner && missingAccess && (
|
||||
<form action={grantRepoAccessToMembers}>
|
||||
<Hidden fields={{ projectId: p.id, back }} />
|
||||
<Button size="sm">Выдать доступ участникам</Button>
|
||||
<Button size="sm">{t("Выдать доступ участникам")}</Button>
|
||||
</form>
|
||||
)}
|
||||
{isOwner && <p className="m-0 text-xs text-muted-foreground">Участник видит доску и входящие, двигает карточки и отвечает агентам; получает доступ на запись к репозиторию.</p>}
|
||||
{isOwner && <p className="m-0 text-xs text-muted-foreground">{t("Участник видит доску и входящие, двигает карточки и отвечает агентам; получает доступ на запись к репозиторию.")}</p>}
|
||||
</PanelSection>
|
||||
|
||||
<PanelSection title="Подписки">
|
||||
<PanelSection title={t("Подписки")}>
|
||||
<p className="m-0 text-sm" id="subscription">
|
||||
{pool ? (
|
||||
<>Агенты работают на пуле «{pool.name}»{shared?.id === pool.id ? " — общая подписка Пеппы" : ""}.</>
|
||||
<>{shared?.id === pool.id ? t("Агенты работают на пуле «{name}» — общая подписка Пеппы.", { name: pool.name }) : t("Агенты работают на пуле «{name}».", { name: pool.name })}</>
|
||||
) : agentWarning ? (
|
||||
<b>Подписка не выбрана — агенты не запустятся.</b>
|
||||
<b>{t("Подписка не выбрана — агенты не запустятся.")}</b>
|
||||
) : (
|
||||
"Пул не назначен — агенты работают на входе машины."
|
||||
t("Пул не назначен — агенты работают на входе машины.")
|
||||
)}
|
||||
</p>
|
||||
{(isOwner || superadmin) && (
|
||||
@ -332,23 +334,23 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
||||
{shared && shared.id !== pool?.id && (
|
||||
<form action={chooseSharedSubscriptionAction}>
|
||||
<Hidden fields={{ projectId: p.id, back }} />
|
||||
<Button size="sm" variant={pool ? "outline" : "default"}>Общая подписка Пеппы</Button>
|
||||
<Button size="sm" variant={pool ? "outline" : "default"}>{t("Общая подписка Пеппы")}</Button>
|
||||
</form>
|
||||
)}
|
||||
<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">
|
||||
<option value="claude_login">Claude — вход по ссылке</option>
|
||||
<option value="codex_login">ChatGPT — вход по ссылке и коду</option>
|
||||
<option value="claude">Claude — готовый токен (claude setup-token)</option>
|
||||
<option value="codex_key">Codex — ключ OpenAI API</option>
|
||||
{hasOwnPool && <option value="existing">Моя уже подключённая подписка</option>}
|
||||
<NativeSelect name="kind" defaultValue="claude_login" aria-label={t("Что подключить")} className="h-8">
|
||||
<option value="claude_login">{t("Claude — вход по ссылке")}</option>
|
||||
<option value="codex_login">{t("ChatGPT — вход по ссылке и коду")}</option>
|
||||
<option value="claude">{t("Claude — готовый токен (claude setup-token)")}</option>
|
||||
<option value="codex_key">{t("Codex — ключ OpenAI API")}</option>
|
||||
{hasOwnPool && <option value="existing">{t("Моя уже подключённая подписка")}</option>}
|
||||
</NativeSelect>
|
||||
<Input name="secret" type="password" autoComplete="off" placeholder="Токен Claude или ключ OpenAI (для входа по ссылке не нужен)" aria-label="Токен или ключ своей подписки" className="h-8 font-mono" />
|
||||
<Button size="sm" variant={pool ? "outline" : "default"} className="self-start">Подключить свою подписку</Button>
|
||||
<Input name="secret" type="password" autoComplete="off" placeholder={t("Токен Claude или ключ OpenAI (для входа по ссылке не нужен)")} aria-label={t("Токен или ключ своей подписки")} className="h-8 font-mono" />
|
||||
<Button size="sm" variant={pool ? "outline" : "default"} className="self-start">{t("Подключить свою подписку")}</Button>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
Вход по ссылке: поле оставьте пустым — на странице проекта появятся шаги. Готовый токен Claude выдаёт <span className="font-mono">claude setup-token</span> на вашем компьютере. Токены и ключи
|
||||
хранятся зашифрованными, показать их нельзя.
|
||||
{t("Вход по ссылке: поле оставьте пустым — на странице проекта появятся шаги. Готовый токен Claude выдаёт")} <span className="font-mono">claude setup-token</span>{" "}
|
||||
{t("на вашем компьютере. Токены и ключи хранятся зашифрованными, показать их нельзя.")}
|
||||
</span>
|
||||
</form>
|
||||
</>
|
||||
@ -356,16 +358,16 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
||||
{superadmin && (
|
||||
<form action={setProjectPoolAction} className="flex gap-2">
|
||||
<Hidden fields={{ projectKey: p.key, back }} />
|
||||
<NativeSelect name="poolId" defaultValue={pool?.id ?? ""} aria-label="Пул подписок по умолчанию" className="h-8">
|
||||
<option value="">Без пула — вход машины</option>
|
||||
<NativeSelect name="poolId" defaultValue={pool?.id ?? ""} aria-label={t("Пул подписок по умолчанию")} className="h-8">
|
||||
<option value="">{t("Без пула — вход машины")}</option>
|
||||
{pools.map((x) => (
|
||||
<option key={x.id} value={x.id}>{x.name}</option>
|
||||
))}
|
||||
</NativeSelect>
|
||||
<Button size="sm">Сохранить</Button>
|
||||
<Button size="sm">{t("Сохранить")}</Button>
|
||||
</form>
|
||||
)}
|
||||
<p className="m-0 text-xs text-muted-foreground">Раннеры проекта стартуют на свободной подписке пула. {superadmin ? <a href="/subscriptions#pools" className="text-primary">Пулы и подписки</a> : "Выбирает владелец проекта."}</p>
|
||||
<p className="m-0 text-xs text-muted-foreground">{t("Раннеры проекта стартуют на свободной подписке пула.")} {superadmin ? <a href="/subscriptions#pools" className="text-primary">{t("Пулы и подписки")}</a> : t("Выбирает владелец проекта.")}</p>
|
||||
</PanelSection>
|
||||
</div>
|
||||
);
|
||||
@ -373,17 +375,17 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
||||
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="Описание стори" />
|
||||
<NativeSelect name="epicId" defaultValue={epicFilter ? String(epicFilter.id) : ""} aria-label="Эпик">
|
||||
<option value="">Без эпика</option>
|
||||
<Input name="title" required placeholder={t("Что сделать")} aria-label={t("Название стори")} />
|
||||
<Textarea name="description" rows={5} placeholder={t("Описание: кому и зачем, критерии готовности")} aria-label={t("Описание стори")} />
|
||||
<NativeSelect name="epicId" defaultValue={epicFilter ? String(epicFilter.id) : ""} aria-label={t("Эпик")}>
|
||||
<option value="">{t("Без эпика")}</option>
|
||||
{epics.map((e) => (
|
||||
<option key={e.id} value={e.id}>
|
||||
{e.title}
|
||||
</option>
|
||||
))}
|
||||
</NativeSelect>
|
||||
<Button variant="default" size="sm" className="self-start">Создать стори</Button>
|
||||
<Button variant="default" size="sm" className="self-start">{t("Создать стори")}</Button>
|
||||
</form>
|
||||
);
|
||||
const tabCount: Partial<Record<(typeof TABS)[number]["id"], number>> = { board: tasks.length, epics: epics.length, bugs: incidents.length, sessions: sessions.length };
|
||||
@ -394,52 +396,52 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
||||
<Flash error={error} />
|
||||
{created && !error && (
|
||||
<Notice>
|
||||
Репозиторий создан: <a href={repo.url} className="text-primary">{repo.fullName}</a> ({repoVisibilityLabel(repo.private)}).
|
||||
{t("Репозиторий создан:")} <a href={repo.url} className="text-primary">{repo.fullName}</a> ({t.text(repoVisibilityLabel(repo.private))}).
|
||||
<Button asChild size="xs">
|
||||
<a href={repo.url}>Открыть в Gitea</a>
|
||||
<a href={repo.url}>{t("Открыть в Gitea")}</a>
|
||||
</Button>
|
||||
</Notice>
|
||||
)}
|
||||
<PageHeader
|
||||
actions={
|
||||
<>
|
||||
<SettingsDialog title="Новая стори" trigger={<><Plus />Стори</>}>
|
||||
<SettingsDialog title={t("Новая стори")} trigger={<><Plus />{t("Стори")}</>}>
|
||||
{newTask}
|
||||
</SettingsDialog>
|
||||
<SettingsDialog title="Настройки проекта">{aside}</SettingsDialog>
|
||||
<SettingsDialog title={t("Настройки проекта")}>{aside}</SettingsDialog>
|
||||
</>
|
||||
}
|
||||
crumbs={<a href="/projects" className="text-muted-foreground hover:text-foreground">Проекты</a>}
|
||||
crumbs={<a href="/projects" className="text-muted-foreground hover:text-foreground">{t("Проекты")}</a>}
|
||||
title={
|
||||
<>
|
||||
<span className="rounded-md bg-muted px-2 font-mono text-primary">{p.key}</span> {p.name}
|
||||
</>
|
||||
}
|
||||
>
|
||||
<a href={repo.url} className="text-primary">{repo.fullName}</a> · {repoVisibilityLabel(repo.private)}
|
||||
<a href={repo.url} className="text-primary">{repo.fullName}</a> · {t.text(repoVisibilityLabel(repo.private))}
|
||||
</PageHeader>
|
||||
|
||||
{mayChoose && (ownLogins.length > 0 || (!pool && agentWarning)) && <SubscriptionSetup projectId={p.id} back={back} logins={ownLogins} />}
|
||||
{agentWarning && !(mayChoose && (ownLogins.length > 0 || !pool)) && (
|
||||
<p role="alert" className="mb-4 flex flex-wrap items-center gap-2 rounded-lg border border-warn/40 bg-warn/10 px-4 py-3 text-sm">
|
||||
<span className="font-medium">Агенты не запустятся:</span> {agentWarning}.
|
||||
{pool ? (superadmin ? <a href="/subscriptions" className="text-primary">Подписки →</a> : <span className="text-muted-foreground">Смените подписку в «⋯ Настройки проекта → Подписки» или попросите суперадмина проверить её.</span>) : null}
|
||||
<span className="font-medium">{t("Агенты не запустятся:")}</span> {t.text(agentWarning)}.
|
||||
{pool ? (superadmin ? <a href="/subscriptions" className="text-primary">{t("Подписки")} →</a> : <span className="text-muted-foreground">{t("Смените подписку в «⋯ Настройки проекта → Подписки» или попросите суперадмина проверить её.")}</span>) : null}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<nav aria-label="Разделы проекта" className="-mt-2 mb-4 flex gap-1 overflow-x-auto border-b">
|
||||
{TABS.map((t) => (
|
||||
<nav aria-label={t("Разделы проекта")} className="-mt-2 mb-4 flex gap-1 overflow-x-auto border-b">
|
||||
{TABS.map((x) => (
|
||||
<a
|
||||
key={t.id}
|
||||
href={t.id === "board" ? `/p/${p.key}` : `/p/${p.key}?tab=${t.id}`}
|
||||
aria-current={tab === t.id ? "page" : undefined}
|
||||
key={x.id}
|
||||
href={x.id === "board" ? `/p/${p.key}` : `/p/${p.key}?tab=${x.id}`}
|
||||
aria-current={tab === x.id ? "page" : undefined}
|
||||
className={cn(
|
||||
"-mb-px flex items-center gap-1.5 border-b-2 px-3 py-2 text-sm whitespace-nowrap text-muted-foreground hover:text-foreground hover:no-underline",
|
||||
tab === t.id ? "border-primary text-foreground" : "border-transparent",
|
||||
tab === x.id ? "border-primary text-foreground" : "border-transparent",
|
||||
)}
|
||||
>
|
||||
{t.label}
|
||||
{!!tabCount[t.id] && <span className="rounded-full bg-muted px-1.5 font-mono text-[11px] tabular-nums">{tabCount[t.id]}</span>}
|
||||
{t(x.label)}
|
||||
{!!tabCount[x.id] && <span className="rounded-full bg-muted px-1.5 font-mono text-[11px] tabular-nums">{tabCount[x.id]}</span>}
|
||||
</a>
|
||||
))}
|
||||
</nav>
|
||||
@ -447,9 +449,9 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
||||
{tab === "board" && (
|
||||
<>
|
||||
{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>
|
||||
{[{ id: 0, title: "все" }, ...epics].map((e) => {
|
||||
<nav aria-label={t("Фильтр по эпику")} 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={t("Эпик — большая цель; карточки на доске — стори, шаги к ней")}>{t("Эпики:")}</a>
|
||||
{[{ id: 0, title: t("все") }, ...epics].map((e) => {
|
||||
const active = (epicFilter?.id ?? 0) === e.id;
|
||||
return (
|
||||
<a
|
||||
@ -460,7 +462,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
||||
>
|
||||
{e.title}
|
||||
{e.id > 0 && (
|
||||
<span className="ml-1.5 inline-flex items-center gap-1 font-mono text-[10px] tabular-nums" title={`Готово ${progressLabel(progress.get(e.id))}`}>
|
||||
<span className="ml-1.5 inline-flex items-center gap-1 font-mono text-[10px] tabular-nums" title={t("Готово {progress}", { progress: progressLabel(progress.get(e.id)) })}>
|
||||
<ProgressBar done={progress.get(e.id)?.done ?? 0} total={progress.get(e.id)?.total ?? 0} className="w-8" />
|
||||
{progressLabel(progress.get(e.id))}
|
||||
</span>
|
||||
@ -470,7 +472,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">
|
||||
Спланировать стори эпика →
|
||||
{t("Спланировать стори эпика")} →
|
||||
</a>
|
||||
)}
|
||||
</nav>
|
||||
@ -484,7 +486,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
||||
projectId={p.id}
|
||||
projectKey={p.key}
|
||||
epics={epics}
|
||||
stories={tasks.map((t) => ({ key: `${p.key}-${t.number}`, title: t.title, status: t.status, goalId: t.goalId }))}
|
||||
stories={tasks.map((x) => ({ key: `${p.key}-${x.number}`, title: x.title, status: x.status, goalId: x.goalId }))}
|
||||
progress={progress}
|
||||
back={back}
|
||||
/>
|
||||
@ -504,23 +506,23 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
||||
{tab === "pulls" && pulls && <PullsTab pulls={pulls.pulls} error={pulls.error} repoUrl={repo.url} />}
|
||||
|
||||
{tab === "releases" && (
|
||||
<Section title="Релизы">
|
||||
<Section title={t("Релизы")}>
|
||||
<div className="flex flex-col gap-2 sm:flex-row">
|
||||
<EnvLine name="staging" r={current.staging} />
|
||||
<EnvLine name="прод" r={current.prod} />
|
||||
<EnvLine name="staging" r={current.staging} t={t} />
|
||||
<EnvLine name={t("прод")} r={current.prod} t={t} />
|
||||
</div>
|
||||
{prodCandidate && prodCandidate !== current.prod?.sha && (
|
||||
<form action={deployProdAction}>
|
||||
<Hidden fields={{ projectKey: p.key, back }} />
|
||||
<Button variant="default" size="sm">
|
||||
<Rocket />
|
||||
Выкатить в прод {prodCandidate.slice(0, 7)}
|
||||
{t("Выкатить в прод {sha}", { sha: prodCandidate.slice(0, 7) })}
|
||||
</Button>
|
||||
</form>
|
||||
)}
|
||||
{releases.length === 0 ? (
|
||||
<Empty>
|
||||
Деплоев ещё не было. Настройка — <span className="font-mono">deploy</span> в .peppa/project.json (см. «Помощь → CI/CD»).
|
||||
{t("Деплоев ещё не было. Настройка —")} <span className="font-mono">deploy</span> {t("в .peppa/project.json (см. «Помощь → CI/CD»).")}
|
||||
</Empty>
|
||||
) : (
|
||||
<div className="overflow-x-auto rounded-lg border">
|
||||
@ -534,16 +536,16 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
||||
</td>
|
||||
<td className="px-3 py-2 font-mono">{r.sha.slice(0, 7)}</td>
|
||||
<td className="px-3 py-2">
|
||||
<Badge variant={RELEASE_STATUS[r.status].tone}>{RELEASE_STATUS[r.status].label}</Badge>
|
||||
{r.reason && <span className="ml-1.5 text-muted-foreground">{r.reason}</span>}
|
||||
<Badge variant={RELEASE_STATUS[r.status].tone}>{t(RELEASE_STATUS[r.status].label)}</Badge>
|
||||
{r.reason && <span className="ml-1.5 text-muted-foreground">{t.text(r.reason)}</span>}
|
||||
</td>
|
||||
<td className="px-3 py-2">
|
||||
{r.tasks.map((t) => (
|
||||
<Key key={t} href={`/t/${t}`} className="mr-1.5">{t}</Key>
|
||||
{r.tasks.map((k) => (
|
||||
<Key key={k} href={`/t/${k}`} className="mr-1.5">{k}</Key>
|
||||
))}
|
||||
</td>
|
||||
<td className="px-3 py-2 text-right whitespace-nowrap text-muted-foreground">
|
||||
{r.deployedBy} · {r.createdAt.toLocaleString("ru-RU", { dateStyle: "short", timeStyle: "short" })}
|
||||
{r.deployedBy} · {r.createdAt.toLocaleString(intlLocale(t.locale), { dateStyle: "short", timeStyle: "short" })}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
@ -561,21 +563,21 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
||||
{tab === "metrics" && metrics && <MetricsTab m={metrics} projectKey={p.key} />}
|
||||
|
||||
{tab === "journal" && (
|
||||
<Section title="Журнал действий" actions={<JournalFilters action={`/p/${p.key}`} value={{ tab: "journal", actor, channel }} />}>
|
||||
<Section title={t("Журнал действий")} actions={<JournalFilters action={`/p/${p.key}`} value={{ tab: "journal", actor, channel }} />}>
|
||||
<JournalList entries={journal} showProject={false} />
|
||||
</Section>
|
||||
)}
|
||||
|
||||
{tab === "sessions" && (
|
||||
<Section
|
||||
title="Сессии"
|
||||
title={t("Сессии")}
|
||||
actions={
|
||||
<SettingsDialog title="Новый терминал" trigger={<><SquareTerminal />Новый терминал</>}>
|
||||
<SettingsDialog title={t("Новый терминал")} trigger={<><SquareTerminal />{t("Новый терминал")}</>}>
|
||||
<NewRunnerForm projectId={p.id} back={back} />
|
||||
</SettingsDialog>
|
||||
}
|
||||
>
|
||||
{sessions.length === 0 ? <Empty>Сессий ещё не было.</Empty> : sessions.map((s) => <SessionCard key={s.id} s={s} back={back} showTitle />)}
|
||||
{sessions.length === 0 ? <Empty>{t("Сессий ещё не было.")}</Empty> : sessions.map((s) => <SessionCard key={s.id} s={s} back={back} showTitle />)}
|
||||
</Section>
|
||||
)}
|
||||
</Workspace>
|
||||
|
||||
@ -12,6 +12,8 @@ import { Input, Textarea } from "@/components/ui/input";
|
||||
import { Workspace } from "@/components/Workspace";
|
||||
import { requireUser } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import { intlLocale } from "@peppa/shared/i18n";
|
||||
import { projectForUserByKey } from "@/lib/queries";
|
||||
import { applyPlanAction, discardPlanAction, planEpicAction } from "../../../../board-actions";
|
||||
|
||||
@ -19,6 +21,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 t = await getT();
|
||||
const p = await projectForUserByKey(user.id, key).catch(() => null);
|
||||
if (!p) notFound();
|
||||
const epic = await getEpic(db, p.id, Number(epicParam)).catch(() => null);
|
||||
@ -34,34 +37,34 @@ export default async function PlanEpicPage({ params, searchParams }: { params: P
|
||||
<>
|
||||
<Link href={`/p/${p.key}`} className="text-muted-foreground hover:text-foreground">{p.name}</Link>
|
||||
<span className="text-muted-foreground">/</span>
|
||||
<Link href={`/p/${p.key}?epic=${epic.id}`} className="text-muted-foreground hover:text-foreground">эпик «{epic.title}»</Link>
|
||||
<Link href={`/p/${p.key}?epic=${epic.id}`} className="text-muted-foreground hover:text-foreground">{t("эпик «{name}»", { name: epic.title })}</Link>
|
||||
</>
|
||||
}
|
||||
title={<>Спланировать эпик «{epic.title}»</>}
|
||||
title={t("Спланировать эпик «{name}»", { name: epic.title })}
|
||||
>
|
||||
Планировщик (короткая сессия Claude на подписке пула проекта) предложит стори с критериями готовности и зависимостями. Ничего не создаётся, пока вы не утвердите план.
|
||||
{t("Планировщик (короткая сессия Claude на подписке пула проекта) предложит стори с критериями готовности и зависимостями. Ничего не создаётся, пока вы не утвердите план.")}
|
||||
</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>
|
||||
<Section title={t("Эпик")}>
|
||||
<div className="rounded-lg border bg-card p-3 text-sm whitespace-pre-wrap">{epic.description || <span className="text-muted-foreground">{t("Без описания — опишите эпик в «⋯ Настройки проекта → Эпики», так план будет точнее.")}</span>}</div>
|
||||
{existing.length > 0 && (
|
||||
<p className="m-0 text-sm text-muted-foreground">
|
||||
Уже есть стори: {existing.map((t) => t.key).join(", ")} — планировщик их не повторит и может от них зависеть.
|
||||
{t("Уже есть стори: {keys} — планировщик их не повторит и может от них зависеть.", { keys: existing.map((x) => x.key).join(", ") })}
|
||||
</p>
|
||||
)}
|
||||
<form action={planEpicAction} className="flex flex-col gap-2">
|
||||
<Hidden fields={{ projectId: p.id, epicId: epic.id, back }} />
|
||||
<Textarea name="wishes" rows={2} defaultValue={draft?.wishes ?? ""} placeholder="Пожелания планировщику (необязательно): например, «сначала API, потом экран», «без новых зависимостей»" aria-label="Пожелания планировщику" />
|
||||
<PendingButton pendingText="Планировщик думает (до 3 минут)…" className="self-start">
|
||||
<Textarea name="wishes" rows={2} defaultValue={draft?.wishes ?? ""} placeholder={t("Пожелания планировщику (необязательно): например, «сначала API, потом экран», «без новых зависимостей»")} aria-label={t("Пожелания планировщику")} />
|
||||
<PendingButton pendingText={t("Планировщик думает (до 3 минут)…")} className="self-start">
|
||||
<Sparkles />
|
||||
{draft ? "Спланировать заново" : "Спланировать"}
|
||||
{draft ? t("Спланировать заново") : t("Спланировать")}
|
||||
</PendingButton>
|
||||
</form>
|
||||
</Section>
|
||||
|
||||
<Section title={draft ? `Черновик плана — ${draft.stories.length} стори` : "Черновик плана"}>
|
||||
<Section title={draft ? t("Черновик плана — {n} стори", { n: draft.stories.length }) : t("Черновик плана")}>
|
||||
{!draft ? (
|
||||
<Empty>Черновика нет. Нажмите «Спланировать».</Empty>
|
||||
<Empty>{t("Черновика нет. Нажмите «Спланировать».")}</Empty>
|
||||
) : (
|
||||
<>
|
||||
<form action={applyPlanAction} className="flex flex-col gap-3">
|
||||
@ -70,29 +73,29 @@ 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">{t("Стори № {n} плана", { 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={t("Создать стори {n}", { 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={t("Название стори {n}", { 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={t("Описание стори {n}", { 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" />
|
||||
<span className="text-muted-foreground whitespace-nowrap">{t("Ждёт")}</span>
|
||||
<Input name={`deps_${n}`} defaultValue={s.dependsOn.join(", ")} placeholder={t("номера плана или ключи: 1, {key}-3", { key: p.key })} aria-label={t("Зависимости стори {n}", { 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">{t("Снимите галочку, чтобы не создавать стори. Стори встанут в конец бэклога в этом порядке; зависимые диспетчер не возьмёт, пока предшественники не в ревью или готово.")}</p>
|
||||
<Button variant="default" className="self-start">{t("Создать стори")}</Button>
|
||||
</form>
|
||||
<form action={discardPlanAction}>
|
||||
<Hidden fields={{ projectId: p.id, epicId: epic.id, back }} />
|
||||
<Button size="sm" variant="ghost">Удалить черновик</Button>
|
||||
<Button size="sm" variant="ghost">{t("Удалить черновик")}</Button>
|
||||
</form>
|
||||
<p className="m-0 text-xs text-muted-foreground">
|
||||
Черновик от {new Date(draft.createdAt).toLocaleString("ru-RU", { dateStyle: "short", timeStyle: "short" })}, {draft.createdBy}.
|
||||
{t("Черновик от {date}, {author}.", { date: new Date(draft.createdAt).toLocaleString(intlLocale(t.locale), { dateStyle: "short", timeStyle: "short" }), author: draft.createdBy })}
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
|
||||
@ -9,27 +9,24 @@ import { Disclosure, Empty, Key, Notice, Section, StatusBadge } from "@/componen
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input, Textarea } from "@/components/ui/input";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import { intlLocale, type Translator } from "@peppa/shared/i18n";
|
||||
|
||||
const when = (iso: string | null) => (iso ? new Date(iso).toLocaleString("ru-RU", { dateStyle: "short", timeStyle: "short" }) : "—");
|
||||
const when = (iso: string | null, t: Translator) => (iso ? new Date(iso).toLocaleString(intlLocale(t.locale), { dateStyle: "short", timeStyle: "short" }) : "—");
|
||||
|
||||
function plural(n: number, one: string, few: string, many: string) {
|
||||
const m10 = n % 10;
|
||||
const m100 = n % 100;
|
||||
return m10 === 1 && m100 !== 11 ? one : m10 >= 2 && m10 <= 4 && (m100 < 12 || m100 > 14) ? few : many;
|
||||
}
|
||||
|
||||
export function CodeTab({ code }: { code: RepoOverview }) {
|
||||
export async function CodeTab({ code }: { code: RepoOverview }) {
|
||||
const t = await getT();
|
||||
const gitea = (
|
||||
<Button asChild size="sm">
|
||||
<a href={code.url}>
|
||||
Открыть в Gitea <ExternalLink />
|
||||
{t("Открыть в Gitea")} <ExternalLink />
|
||||
</a>
|
||||
</Button>
|
||||
);
|
||||
if (code.error) {
|
||||
return (
|
||||
<Section title="Код" actions={gitea}>
|
||||
<Empty>{code.error}. Репозиторий: <a href={code.url} className="text-primary">{code.url}</a></Empty>
|
||||
<Section title={t("Код")} actions={gitea}>
|
||||
<Empty>{t.text(code.error)}. {t("Репозиторий:")} <a href={code.url} className="text-primary">{code.url}</a></Empty>
|
||||
</Section>
|
||||
);
|
||||
}
|
||||
@ -39,13 +36,13 @@ export function CodeTab({ code }: { code: RepoOverview }) {
|
||||
{code.readme ? (
|
||||
<pre className="m-0 max-h-[40em] overflow-auto rounded-lg border bg-card p-4 font-mono text-xs leading-relaxed whitespace-pre-wrap">{code.readme.text}</pre>
|
||||
) : (
|
||||
<Empty>{code.defaultBranch ? `В ветке ${code.defaultBranch} нет README.` : "Репозиторий пуст."}</Empty>
|
||||
<Empty>{code.defaultBranch ? t("В ветке {branch} нет README.", { branch: code.defaultBranch }) : t("Репозиторий пуст.")}</Empty>
|
||||
)}
|
||||
</Section>
|
||||
<div className="flex flex-col gap-6">
|
||||
<Section title="Ветки" count={code.branches.length}>
|
||||
<Section title={t("Ветки")} count={code.branches.length}>
|
||||
{code.branches.length === 0 ? (
|
||||
<Empty>Веток нет.</Empty>
|
||||
<Empty>{t("Веток нет.")}</Empty>
|
||||
) : (
|
||||
<ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm">
|
||||
{code.branches.map((b) => (
|
||||
@ -54,16 +51,16 @@ export function CodeTab({ code }: { code: RepoOverview }) {
|
||||
<a href={`${code.url}/src/branch/${b.name.split("/").map(encodeURIComponent).join("/")}`} className="truncate font-mono text-xs text-primary">
|
||||
{b.name}
|
||||
</a>
|
||||
{b.name === code.defaultBranch && <Badge variant="muted">по умолчанию</Badge>}
|
||||
{b.name === code.defaultBranch && <Badge variant="muted">{t("по умолчанию")}</Badge>}
|
||||
<span className="ml-auto shrink-0 font-mono text-[11px] text-muted-foreground">{b.sha.slice(0, 7)}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</Section>
|
||||
<Section title={`Коммиты ${code.defaultBranch ?? ""}`}>
|
||||
<Section title={t("Коммиты {branch}", { branch: code.defaultBranch ?? "" })}>
|
||||
{code.commits.length === 0 ? (
|
||||
<Empty>Коммитов нет.</Empty>
|
||||
<Empty>{t("Коммитов нет.")}</Empty>
|
||||
) : (
|
||||
<ul className="m-0 flex list-none flex-col gap-2 p-0 text-sm">
|
||||
{code.commits.map((c) => (
|
||||
@ -71,7 +68,7 @@ export function CodeTab({ code }: { code: RepoOverview }) {
|
||||
<span className="[overflow-wrap:anywhere]">{c.message}</span>
|
||||
<span className="flex flex-wrap gap-x-2 text-xs text-muted-foreground">
|
||||
<a href={c.url} className="font-mono text-primary">{c.sha.slice(0, 7)}</a>
|
||||
{c.author} · {when(c.date)}
|
||||
{c.author} · {when(c.date, t)}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
@ -84,27 +81,29 @@ export function CodeTab({ code }: { code: RepoOverview }) {
|
||||
}
|
||||
|
||||
/** PEP-30: the project memory (.peppa/memory.md of the working copy), written by agents. */
|
||||
export function MemorySection({ text, chars, max, nearLimit }: { text: string; chars: number; max: number; nearLimit: boolean }) {
|
||||
export async function MemorySection({ text, chars, max, nearLimit }: { text: string; chars: number; max: number; nearLimit: boolean }) {
|
||||
const t = await getT();
|
||||
return (
|
||||
<Section title="Память проекта" actions={<span className={nearLimit ? "text-warn" : "text-muted-foreground"}>{chars} из {max} символов</span>} className="mb-8">
|
||||
<p className="m-0 text-sm text-muted-foreground">Что агенты запомнили для следующих стори: команды, соглашения, грабли, решения (<code>.peppa/memory.md</code>, MCP <code>remember</code>). Раннер подкладывает её агенту при каждом запуске.</p>
|
||||
<Section title={t("Память проекта")} actions={<span className={nearLimit ? "text-warn" : "text-muted-foreground"}>{t("{chars} из {max} символов", { chars, max })}</span>} className="mb-8">
|
||||
<p className="m-0 text-sm text-muted-foreground">{t("Что агенты запомнили для следующих стори: команды, соглашения, грабли, решения")} (<code>.peppa/memory.md</code>, MCP <code>remember</code>). {t("Раннер подкладывает её агенту при каждом запуске.")}</p>
|
||||
{text.trim() ? (
|
||||
<Disclosure summary={<span className="text-sm">Показать память{nearLimit ? " — почти предел, агент ужмёт её" : ""}</span>}>
|
||||
<Disclosure summary={<span className="text-sm">{nearLimit ? t("Показать память — почти предел, агент ужмёт её") : t("Показать память")}</span>}>
|
||||
<Markdown text={text} />
|
||||
</Disclosure>
|
||||
) : (
|
||||
<Empty>Память пуста — агенты пополнят её в конце стори.</Empty>
|
||||
<Empty>{t("Память пуста — агенты пополнят её в конце стори.")}</Empty>
|
||||
)}
|
||||
</Section>
|
||||
);
|
||||
}
|
||||
|
||||
export function SpecsTab({ specs }: { specs: SpecSummary[] }) {
|
||||
export async function SpecsTab({ specs }: { specs: SpecSummary[] }) {
|
||||
const t = await getT();
|
||||
return (
|
||||
<Section title="Спеки" count={specs.length}>
|
||||
<p className="m-0 text-sm text-muted-foreground">Что система умеет сейчас: требования OpenSpec из рабочей копии (openspec/specs). Обновляются, когда стори архивирует свой change.</p>
|
||||
<Section title={t("Спеки")} count={specs.length}>
|
||||
<p className="m-0 text-sm text-muted-foreground">{t("Что система умеет сейчас: требования OpenSpec из рабочей копии (openspec/specs). Обновляются, когда стори архивирует свой change.")}</p>
|
||||
{specs.length === 0 ? (
|
||||
<Empty>Спек ещё нет — они появляются после archive первого change.</Empty>
|
||||
<Empty>{t("Спек ещё нет — они появляются после archive первого change.")}</Empty>
|
||||
) : (
|
||||
specs.map((s) => (
|
||||
<Disclosure
|
||||
@ -114,7 +113,7 @@ export function SpecsTab({ specs }: { specs: SpecSummary[] }) {
|
||||
<span className="flex items-center gap-2">
|
||||
<span className="font-mono">{s.name}</span>
|
||||
<Badge variant="muted">
|
||||
{s.requirements} {plural(s.requirements, "требование", "требования", "требований")}
|
||||
{t.n(s.requirements, "{n} требование", "{n} требования", "{n} требований")}
|
||||
</Badge>
|
||||
</span>
|
||||
{s.purpose && <span className="text-xs font-normal text-muted-foreground">{s.purpose.split("\n")[0]}</span>}
|
||||
@ -131,23 +130,24 @@ export function SpecsTab({ specs }: { specs: SpecSummary[] }) {
|
||||
|
||||
const CI_TONE = { success: "ok", failure: "danger", pending: "info", none: "muted", not_configured: "muted" } as const;
|
||||
|
||||
export function PullsTab({ pulls, error, repoUrl }: { pulls: OpenPull[]; error: string | null; repoUrl: string }) {
|
||||
export async function PullsTab({ pulls, error, repoUrl }: { pulls: OpenPull[]; error: string | null; repoUrl: string }) {
|
||||
const t = await getT();
|
||||
return (
|
||||
<Section
|
||||
title="Открытые PR"
|
||||
title={t("Открытые PR")}
|
||||
count={pulls.length}
|
||||
actions={
|
||||
<Button asChild size="sm">
|
||||
<a href={`${repoUrl}/pulls`}>
|
||||
Все PR в Gitea <ExternalLink />
|
||||
{t("Все PR в Gitea")} <ExternalLink />
|
||||
</a>
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
{error ? (
|
||||
<Empty>{error}.</Empty>
|
||||
<Empty>{t.text(error)}.</Empty>
|
||||
) : pulls.length === 0 ? (
|
||||
<Empty>Открытых PR нет.</Empty>
|
||||
<Empty>{t("Открытых PR нет.")}</Empty>
|
||||
) : (
|
||||
pulls.map((p) => (
|
||||
<article key={p.number} className="flex flex-col gap-1.5 rounded-lg border bg-card p-3.5 text-sm">
|
||||
@ -163,10 +163,10 @@ export function PullsTab({ pulls, error, repoUrl }: { pulls: OpenPull[]; error:
|
||||
<>
|
||||
· <Key href={`/t/${p.task.key}`}>{p.task.key}</Key>
|
||||
<StatusBadge status={p.task.status} />
|
||||
<Badge variant={CI_TONE[p.task.ci.state]}>{p.task.ci.label}</Badge>
|
||||
<Badge variant={CI_TONE[p.task.ci.state]}>{t.text(p.task.ci.label)}</Badge>
|
||||
</>
|
||||
) : (
|
||||
<span>· не стори Пеппы</span>
|
||||
<span>· {t("не стори Пеппы")}</span>
|
||||
)}
|
||||
</div>
|
||||
</article>
|
||||
@ -178,19 +178,21 @@ export function PullsTab({ pulls, error, repoUrl }: { pulls: OpenPull[]; error:
|
||||
|
||||
/** «⋯ Настройки проекта» → Эпики: labels that group stories (stored as goals). */
|
||||
/** PEP-34: done/total of an epic as a thin bar. */
|
||||
export function ProgressBar({ done, total, className }: { done: number; total: number; className?: string }) {
|
||||
export async function ProgressBar({ done, total, className }: { done: number; total: number; className?: string }) {
|
||||
const t = await getT();
|
||||
const pct = total ? Math.round((done / total) * 100) : 0;
|
||||
return (
|
||||
<span role="progressbar" aria-valuemin={0} aria-valuemax={total} aria-valuenow={done} aria-label={`Готово ${done} из ${total}`} className={`inline-block h-1 overflow-hidden rounded-full bg-muted ${className ?? "w-12"}`}>
|
||||
<span role="progressbar" aria-valuemin={0} aria-valuemax={total} aria-valuenow={done} aria-label={t("Готово {done} из {total}", { done, total })} className={`inline-block h-1 overflow-hidden rounded-full bg-muted ${className ?? "w-12"}`}>
|
||||
<span className="block h-full rounded-full bg-ok" style={{ width: `${pct}%` }} />
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export function EpicsPanel({ projectId, projectKey, epics, progress, back }: { projectId: number; projectKey: string; epics: Epic[]; progress: Map<number, { done: number; total: number }>; back: string }) {
|
||||
export async function EpicsPanel({ projectId, projectKey, epics, progress, back }: { projectId: number; projectKey: string; epics: Epic[]; progress: Map<number, { done: number; total: number }>; back: string }) {
|
||||
const t = await getT();
|
||||
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">{t("Эпиков нет. Эпик — метка, которая группирует стори; его описание агент получает вместе со стори.")}</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">
|
||||
@ -203,18 +205,18 @@ export function EpicsPanel({ projectId, projectKey, epics, progress, back }: { p
|
||||
<div className="flex flex-col gap-2 border-t px-3 py-2.5">
|
||||
<form action={editEpic} className="flex flex-col gap-2">
|
||||
<Hidden fields={{ projectId, epicId: e.id, back }} />
|
||||
<Input name="title" required minLength={2} defaultValue={e.title} aria-label="Название эпика" className="h-8" />
|
||||
<Textarea name="description" rows={3} defaultValue={e.description ?? ""} placeholder="Описание для агента: зачем этот эпик" aria-label="Описание эпика" />
|
||||
<Button size="xs" className="self-start">Сохранить</Button>
|
||||
<Input name="title" required minLength={2} defaultValue={e.title} aria-label={t("Название эпика")} className="h-8" />
|
||||
<Textarea name="description" rows={3} defaultValue={e.description ?? ""} placeholder={t("Описание для агента: зачем этот эпик")} aria-label={t("Описание эпика")} />
|
||||
<Button size="xs" className="self-start">{t("Сохранить")}</Button>
|
||||
</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}`}>{t("Спланировать стори")}</a>
|
||||
</Button>
|
||||
<form action={editEpic}>
|
||||
<Hidden fields={{ projectId, epicId: e.id, back, archive: "1" }} />
|
||||
<Button size="xs" variant="ghost">
|
||||
<Archive />В архив
|
||||
<Archive />{t("В архив")}
|
||||
</Button>
|
||||
</form>
|
||||
</div>
|
||||
@ -224,8 +226,8 @@ export function EpicsPanel({ projectId, projectKey, epics, progress, back }: { p
|
||||
<form action={addEpic} className="flex flex-col gap-2">
|
||||
<Hidden fields={{ projectId, back }} />
|
||||
<div className="flex gap-2">
|
||||
<Input name="title" required minLength={2} placeholder="Новый эпик" aria-label="Название нового эпика" className="h-8" />
|
||||
<Button size="sm">Добавить</Button>
|
||||
<Input name="title" required minLength={2} placeholder={t("Новый эпик")} aria-label={t("Название нового эпика")} className="h-8" />
|
||||
<Button size="sm">{t("Добавить")}</Button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
@ -233,34 +235,35 @@ export function EpicsPanel({ projectId, projectKey, epics, progress, back }: { p
|
||||
}
|
||||
|
||||
/** PEP-73: the project's AGENTS.md — prompt and standards every agent follows; read and edit. */
|
||||
export function AgentsMdTab({ projectId, projectKey, md, edit, saved }: { projectId: number; projectKey: string; md: AgentsMd; edit: boolean; saved: boolean }) {
|
||||
export async function AgentsMdTab({ projectId, projectKey, md, edit, saved }: { projectId: number; projectKey: string; md: AgentsMd; edit: boolean; saved: boolean }) {
|
||||
const t = await getT();
|
||||
const tabHref = `/p/${projectKey}?tab=agents`;
|
||||
const gitea = (
|
||||
<Button asChild size="sm">
|
||||
<a href={md.url}>
|
||||
В Gitea <ExternalLink />
|
||||
{t("В Gitea")} <ExternalLink />
|
||||
</a>
|
||||
</Button>
|
||||
);
|
||||
if (md.error) {
|
||||
return (
|
||||
<Section title="AGENTS.md" actions={gitea}>
|
||||
<Empty>{md.error}</Empty>
|
||||
<Empty>{t.text(md.error)}</Empty>
|
||||
</Section>
|
||||
);
|
||||
}
|
||||
if (edit) {
|
||||
return (
|
||||
<Section title="AGENTS.md — правка" actions={gitea}>
|
||||
<Section title={t("AGENTS.md — правка")} actions={gitea}>
|
||||
<form action={saveAgentsMdAction} className="flex flex-col gap-3">
|
||||
<Hidden fields={{ projectId: String(projectId), sha: md.sha ?? "", back: `${tabHref}&edit=1` }} />
|
||||
<Textarea name="text" defaultValue={md.text || AGENTS_MD_STARTER} rows={28} spellCheck={false} className="font-mono text-xs leading-relaxed" aria-label="Текст AGENTS.md" />
|
||||
<Textarea name="text" defaultValue={md.text || AGENTS_MD_STARTER} rows={28} spellCheck={false} className="font-mono text-xs leading-relaxed" aria-label={t("Текст AGENTS.md")} />
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Button variant="default">Сохранить в {md.branch}</Button>
|
||||
<Button variant="default">{t("Сохранить в {branch}", { branch: md.branch })}</Button>
|
||||
<Button asChild variant="ghost">
|
||||
<a href={tabHref}>Отмена</a>
|
||||
<a href={tabHref}>{t("Отмена")}</a>
|
||||
</Button>
|
||||
<span className="text-xs text-muted-foreground">Коммит в ветку {md.branch} от вашего имени. Новые и перезапущенные агенты прочитают его сразу.</span>
|
||||
<span className="text-xs text-muted-foreground">{t("Коммит в ветку {branch} от вашего имени. Новые и перезапущенные агенты прочитают его сразу.", { branch: md.branch })}</span>
|
||||
</div>
|
||||
</form>
|
||||
</Section>
|
||||
@ -273,29 +276,29 @@ export function AgentsMdTab({ projectId, projectKey, md, edit, saved }: { projec
|
||||
<>
|
||||
<Button asChild size="sm" variant="default">
|
||||
<a href={`${tabHref}&edit=1`}>
|
||||
<Pencil /> Изменить
|
||||
<Pencil /> {t("Изменить")}
|
||||
</a>
|
||||
</Button>
|
||||
{gitea}
|
||||
</>
|
||||
}
|
||||
>
|
||||
{saved && <Notice>AGENTS.md сохранён в {md.branch}</Notice>}
|
||||
{saved && <Notice>{t("AGENTS.md сохранён в {branch}", { branch: md.branch })}</Notice>}
|
||||
<p className="m-0 text-sm text-muted-foreground">
|
||||
Промпт и стандарты проекта: стек, команды, соглашения, этапы (например, проверка ИБ перед PR). Его читают все агенты — Claude, Codex и OpenCode; общие правила
|
||||
Пеппы добавляются сами.
|
||||
{t("Промпт и стандарты проекта: стек, команды, соглашения, этапы (например, проверка ИБ перед PR). Его читают все агенты — Claude, Codex и OpenCode; общие правила Пеппы добавляются сами.")}
|
||||
</p>
|
||||
{md.text.trim() ? (
|
||||
<div className="rounded-lg border bg-card p-4">
|
||||
<Markdown text={md.text} />
|
||||
</div>
|
||||
) : (
|
||||
<Empty>В репозитории ещё нет AGENTS.md — нажмите «Изменить», чтобы создать его из заготовки.</Empty>
|
||||
<Empty>{t("В репозитории ещё нет AGENTS.md — нажмите «Изменить», чтобы создать его из заготовки.")}</Empty>
|
||||
)}
|
||||
</Section>
|
||||
);
|
||||
}
|
||||
|
||||
// i18n-ignore — file content for the project repository (like template/AGENTS.md), not UI text
|
||||
const AGENTS_MD_STARTER = `# AGENTS.md
|
||||
|
||||
Проект ведётся софтвейр-фабрикой **Пеппа**. Общие правила (OpenSpec, PR, ревью) агент получает от Пеппы;
|
||||
@ -321,7 +324,8 @@ 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 async 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 }) {
|
||||
const t = await getT();
|
||||
const loose = stories.filter((s) => !s.goalId || !epics.some((e) => e.id === s.goalId));
|
||||
const list = (items: EpicStory[]) =>
|
||||
items.length ? (
|
||||
@ -335,40 +339,40 @@ 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">{t("Стори пока нет.")}</p>
|
||||
);
|
||||
return (
|
||||
<Section title="Эпики" count={epics.length}>
|
||||
<Section title={t("Эпики")} 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">{t("Эпик")}</b> {t("— большая цель, например «Оплата» или «Личный кабинет».")} <b className="text-foreground">{t("Стори")}</b>{" "}
|
||||
{t("— один конкретный шаг к ней: её делает агент, она — карточка на доске. У стори может быть один эпик; его описание агент получает вместе со стори.")}
|
||||
</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 }} />
|
||||
<Input name="title" required minLength={2} placeholder="Новый эпик: большая цель" aria-label="Название нового эпика" className="h-8 min-w-48 flex-1" />
|
||||
<Input name="description" placeholder="Зачем он — одной фразой (необязательно)" aria-label="Описание нового эпика" className="h-8 min-w-48 flex-[2]" />
|
||||
<Button size="sm" variant="default">Добавить эпик</Button>
|
||||
<Input name="title" required minLength={2} placeholder={t("Новый эпик: большая цель")} aria-label={t("Название нового эпика")} className="h-8 min-w-48 flex-1" />
|
||||
<Input name="description" placeholder={t("Зачем он — одной фразой (необязательно)")} aria-label={t("Описание нового эпика")} className="h-8 min-w-48 flex-[2]" />
|
||||
<Button size="sm" variant="default">{t("Добавить эпик")}</Button>
|
||||
</form>
|
||||
{epics.map((e) => {
|
||||
const pr = progress.get(e.id) ?? { done: 0, total: 0 };
|
||||
return (
|
||||
<article key={e.id} id={`epic-${e.id}`} className="flex flex-col gap-2.5 rounded-lg border bg-card px-4 py-3" data-epic={e.id}>
|
||||
<header className="flex flex-wrap items-center gap-2">
|
||||
<Badge variant="primary">эпик</Badge>
|
||||
<Badge variant="primary">{t("эпик")}</Badge>
|
||||
<h3 className="m-0 min-w-0 flex-1 truncate text-base font-medium">{e.title}</h3>
|
||||
<ProgressBar done={pr.done} total={pr.total} className="w-24" />
|
||||
<span className="text-xs text-muted-foreground tabular-nums">
|
||||
готово {pr.done} из {pr.total}
|
||||
{t("готово {done} из {total}", { done: pr.done, total: pr.total })}
|
||||
</span>
|
||||
</header>
|
||||
{e.description && <p className="m-0 text-sm text-muted-foreground">{e.description}</p>}
|
||||
{list(stories.filter((s) => s.goalId === e.id))}
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button asChild size="xs" variant="outline">
|
||||
<a href={`/p/${projectKey}?epic=${e.id}`}>На доске</a>
|
||||
<a href={`/p/${projectKey}?epic=${e.id}`}>{t("На доске")}</a>
|
||||
</Button>
|
||||
<Button asChild size="xs" variant="outline">
|
||||
<a href={`/p/${projectKey}/plan/${e.id}`}>Спланировать стори</a>
|
||||
<a href={`/p/${projectKey}/plan/${e.id}`}>{t("Спланировать стори")}</a>
|
||||
</Button>
|
||||
</div>
|
||||
</article>
|
||||
@ -377,13 +381,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">{t("Стори без эпика")}</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">{t("Переименовать эпик, изменить описание или убрать в архив — «⋯ Настройки проекта → Эпики». Эпик стори меняется кнопкой «Изменить» на её странице.")}</p>
|
||||
</Section>
|
||||
);
|
||||
}
|
||||
|
||||
@ -10,30 +10,32 @@ import { Empty, Flash, MoreLink, PageHeader, Section } from "@/components/common
|
||||
import { Workspace } from "@/components/Workspace";
|
||||
import { requireUser } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { getT } from "@/lib/i18n";
|
||||
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 t = await getT();
|
||||
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={t("Главная")}>{items.length ? t("Агенты ждут твоего решения — ответь здесь, в Telegram или через MCP.") : t("Всё идёт само: агентам от тебя ничего не нужно.")}</PageHeader>
|
||||
{onboarding.visible && <OnboardingChecklist data={onboarding} botUsername={user.telegramBotUsername} />}
|
||||
<Section title="Вопросы агентов" count={items.length}>
|
||||
<Section title={t("Вопросы агентов")} count={items.length}>
|
||||
<PugBanner count={items.length} />
|
||||
{items.map((q) => <QuestionCard key={q.id} q={q} taskKey={q.taskKey} taskStatus={q.taskStatus} back="/" />)}
|
||||
</Section>
|
||||
<Section title="Прогресс">
|
||||
<Section title={t("Прогресс")}>
|
||||
<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={t("Агенты за работой")} count={sessions.length} actions={<MoreLink href="/runners">{t("вся работа агентов")}</MoreLink>}>
|
||||
{sessions.length === 0 ? <Empty>{t("Сейчас никто не работает: напишите задачу — и агент возьмёт её.")}</Empty> : sessions.map((s) => <AgentAtWork key={s.id} s={s} back="/" />)}
|
||||
</Section>
|
||||
<Section title="Мои проекты" actions={<MoreLink href="/projects">все проекты</MoreLink>}>
|
||||
<Section title={t("Мои проекты")} actions={<MoreLink href="/projects">{t("все проекты")}</MoreLink>}>
|
||||
<ProjectList projects={projects} userId={user.id} />
|
||||
</Section>
|
||||
</Workspace>
|
||||
|
||||
@ -6,6 +6,8 @@ import { revalidatePath } from "next/cache";
|
||||
import { redirect } from "next/navigation";
|
||||
import { asWebActor, requireUser } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
|
||||
const str = (f: FormData, k: string) => String(f.get(k) ?? "").trim();
|
||||
const BASE = "/platform";
|
||||
@ -17,7 +19,8 @@ async function attempt(fn: () => Promise<string | void>): Promise<never> {
|
||||
await requireSuperadmin(db, user);
|
||||
target = (await fn()) || target;
|
||||
} catch (e) {
|
||||
const msg = e instanceof PeppaError ? e.message : `Ошибка: ${(e as Error).message}`;
|
||||
const t = await getT();
|
||||
const msg = e instanceof PeppaError ? t.text(e.message) : t("Ошибка: {message}", { message: (e as Error).message });
|
||||
target = `${BASE}?error=${encodeURIComponent(msg.slice(0, 300))}`;
|
||||
}
|
||||
revalidatePath(BASE);
|
||||
@ -50,7 +53,7 @@ export async function saveChannelSettingsAction(f: FormData) {
|
||||
export async function sendDigestNowAction() {
|
||||
await attempt(async () => {
|
||||
const r = await platformDigestTick(db, { force: true });
|
||||
if (!r) throw new PeppaError("Некуда отправлять: канал не подключён и дайджест пользователям выключен");
|
||||
if (!r) throw new PeppaError(m("Некуда отправлять: канал не подключён и дайджест пользователям выключен"));
|
||||
if (!r.channel && !r.users) return `${BASE}?sent=empty`;
|
||||
return `${BASE}?sent=${r.channel ? "channel" : ""}${r.users ? `,users:${r.users}` : ""}`;
|
||||
});
|
||||
|
||||
@ -9,15 +9,20 @@ import { Input, Label } from "@/components/ui/input";
|
||||
import { Workspace } from "@/components/Workspace";
|
||||
import { requireUser } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import { checkChannelAction, saveChannelAction, saveChannelSettingsAction, sendDigestNowAction } from "./actions";
|
||||
|
||||
export const metadata = { title: "Платформа — Пеппа" };
|
||||
export async function generateMetadata() {
|
||||
const t = await getT();
|
||||
return { title: t("Платформа — Пеппа") };
|
||||
}
|
||||
|
||||
/** Telegram HTML of the digest → plain text for the preview. */
|
||||
const plain = (html: string) => html.replace(/<[^>]+>/g, "").replace(/</g, "<").replace(/>/g, ">").replace(/&/g, "&");
|
||||
|
||||
export default async function Platform({ searchParams }: { searchParams: Promise<{ error?: string; sent?: string }> }) {
|
||||
const user = await requireUser();
|
||||
const t = await getT();
|
||||
if (!(await isSuperadmin(db, user))) notFound();
|
||||
const { error, sent } = await searchParams;
|
||||
const [c, build] = await Promise.all([getPlatformChannel(db), getPlatformBuild(db)]);
|
||||
@ -26,84 +31,84 @@ export default async function Platform({ searchParams }: { searchParams: Promise
|
||||
<Workspace>
|
||||
<div className="max-w-3xl">
|
||||
<Flash error={error} />
|
||||
{sent && <p className="mb-4 rounded-lg border px-4 py-3 text-sm">{sent === "empty" ? "Дайджест пуст — нечего отправлять." : `Дайджест отправлен: ${sent.replace("channel", "в канал").replace(",users:", " · пользователям: ")}`}</p>}
|
||||
<PageHeader title={<><Megaphone className="mr-1 inline size-5 text-primary" />Платформа</>}>
|
||||
Telegram-канал Пеппы: новые версии, падения и перезапуски сервисов и ежедневный дайджест — что нового в Пеппе и что происходит сейчас. Раздел видят только суперадмины.
|
||||
{build && <> Сейчас: v{build.version} · <span className="font-mono">{build.commit.slice(0, 7)}</span>.</>}
|
||||
{sent && <p className="mb-4 rounded-lg border px-4 py-3 text-sm">{sent === "empty" ? t("Дайджест пуст — нечего отправлять.") : t("Дайджест отправлен: {to}", { to: sent.replace("channel", t("в канал")).replace(",users:", " · " + t("пользователям:") + " ") })}</p>}
|
||||
<PageHeader title={<><Megaphone className="mr-1 inline size-5 text-primary" />{t("Платформа")}</>}>
|
||||
{t("Telegram-канал Пеппы: новые версии, падения и перезапуски сервисов и ежедневный дайджест — что нового в Пеппе и что происходит сейчас. Раздел видят только суперадмины.")}
|
||||
{build && <> {t("Сейчас: v{version}", { version: build.version })} · <span className="font-mono">{build.commit.slice(0, 7)}</span>.</>}
|
||||
</PageHeader>
|
||||
|
||||
<Section title="Канал">
|
||||
<Section title={t("Канал")}>
|
||||
<Card className="gap-3">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{c.chatId == null ? (
|
||||
<Badge variant="secondary">канал не задан</Badge>
|
||||
<Badge variant="secondary">{t("канал не задан")}</Badge>
|
||||
) : !c.check ? (
|
||||
<Badge variant="info">не проверен</Badge>
|
||||
<Badge variant="info">{t("не проверен")}</Badge>
|
||||
) : c.check.ok ? (
|
||||
<Badge variant="ok">канал подключён</Badge>
|
||||
<Badge variant="ok">{t("канал подключён")}</Badge>
|
||||
) : (
|
||||
<Badge variant="danger">не работает</Badge>
|
||||
<Badge variant="danger">{t("не работает")}</Badge>
|
||||
)}
|
||||
{c.check?.ok && c.title && <span className="font-semibold">{c.title}</span>}
|
||||
{c.check && <span className="ml-auto text-xs text-muted-foreground">проверен {ago(new Date(c.check.at))}</span>}
|
||||
{c.check && <span className="ml-auto text-xs text-muted-foreground">{t("проверен {ago}", { ago: ago(new Date(c.check.at), t) })}</span>}
|
||||
</div>
|
||||
{c.check && !c.check.ok && <p className="m-0 text-sm text-destructive">{c.check.error}</p>}
|
||||
{c.check && !c.check.ok && <p className="m-0 text-sm text-destructive">{t.text(c.check.error)}</p>}
|
||||
<form action={saveChannelAction} className="flex flex-wrap items-end gap-2">
|
||||
<Label className="min-w-56 flex-1">
|
||||
Chat ID канала
|
||||
<Input name="chatId" placeholder="-100… или @имя" defaultValue={c.chatId == null ? "" : String(c.chatId)} className="h-8 font-mono" />
|
||||
{t("Chat ID канала")}
|
||||
<Input name="chatId" placeholder={t("-100… или @имя")} defaultValue={c.chatId == null ? "" : String(c.chatId)} className="h-8 font-mono" />
|
||||
</Label>
|
||||
<Button size="sm">Сохранить и проверить</Button>
|
||||
<Button size="sm">{t("Сохранить и проверить")}</Button>
|
||||
</form>
|
||||
{c.chatId != null && (
|
||||
<form action={checkChannelAction}>
|
||||
<Button size="sm" variant="outline"><RefreshCw />Проверить ещё раз</Button>
|
||||
<Button size="sm" variant="outline"><RefreshCw />{t("Проверить ещё раз")}</Button>
|
||||
</form>
|
||||
)}
|
||||
<p className="m-0 text-xs text-muted-foreground">
|
||||
Добавьте бота Пеппы в канал администратором с правом «Публикация сообщений». Пока проверка не прошла, Пеппа перепроверяет канал раз в час и ничего туда не пишет. Ответы в канале бот не читает.
|
||||
{t("Добавьте бота Пеппы в канал администратором с правом «Публикация сообщений». Пока проверка не прошла, Пеппа перепроверяет канал раз в час и ничего туда не пишет. Ответы в канале бот не читает.")}
|
||||
</p>
|
||||
</Card>
|
||||
</Section>
|
||||
|
||||
<Section title="Что присылать">
|
||||
<Section title={t("Что присылать")}>
|
||||
<Card>
|
||||
<form action={saveChannelSettingsAction} className="flex flex-col gap-3">
|
||||
{PLATFORM_CHANNEL_EVENTS.map((e) => (
|
||||
<label key={e} className="flex items-center gap-2 text-sm">
|
||||
<input type="checkbox" name={`event.${e}`} defaultChecked={c.events[e]} className="size-4 accent-primary" />
|
||||
{PLATFORM_CHANNEL_EVENT_NAMES[e]} — в канал
|
||||
{t("{event} — в канал", { event: t(PLATFORM_CHANNEL_EVENT_NAMES[e]) })}
|
||||
</label>
|
||||
))}
|
||||
<label className="flex items-center gap-2 text-sm">
|
||||
<input type="checkbox" name="users" defaultChecked={c.digest.users} className="size-4 accent-primary" />
|
||||
Дайджест ещё и в личные чаты всем, кто привязал Telegram (отписка — «Настройки → Уведомления»)
|
||||
{t("Дайджест ещё и в личные чаты всем, кто привязал Telegram (отписка — «Настройки → Уведомления»)")}
|
||||
</label>
|
||||
<div className="grid gap-2 sm:grid-cols-2">
|
||||
<Label>
|
||||
Время дайджеста
|
||||
{t("Время дайджеста")}
|
||||
<Input name="time" type="time" required defaultValue={c.digest.time} className="h-8" />
|
||||
</Label>
|
||||
<Label>
|
||||
Таймзона
|
||||
{t("Таймзона")}
|
||||
<Input name="timezone" required defaultValue={c.digest.timezone} className="h-8 font-mono" />
|
||||
</Label>
|
||||
</div>
|
||||
<Button size="sm" className="self-start">Сохранить</Button>
|
||||
<Button size="sm" className="self-start">{t("Сохранить")}</Button>
|
||||
</form>
|
||||
</Card>
|
||||
</Section>
|
||||
|
||||
<Section
|
||||
title="Дайджест за сутки"
|
||||
title={t("Дайджест за сутки")}
|
||||
actions={
|
||||
<form action={sendDigestNowAction}>
|
||||
<Button size="sm" variant="outline"><Send />Отправить сейчас</Button>
|
||||
<Button size="sm" variant="outline"><Send />{t("Отправить сейчас")}</Button>
|
||||
</form>
|
||||
}
|
||||
>
|
||||
{platformDigestEmpty(digest) ? (
|
||||
<p className="m-0 text-sm text-muted-foreground">За сутки ничего нового и ничего не происходит — дайджест не уйдёт.</p>
|
||||
<p className="m-0 text-sm text-muted-foreground">{t("За сутки ничего нового и ничего не происходит — дайджест не уйдёт.")}</p>
|
||||
) : (
|
||||
<pre className="m-0 overflow-x-auto rounded-md bg-muted p-3 text-xs whitespace-pre-wrap">{plain(renderPlatformDigest(digest))}</pre>
|
||||
)}
|
||||
|
||||
@ -7,6 +7,7 @@ import { Input, Label, NativeSelect } from "@/components/ui/input";
|
||||
import { Workspace } from "@/components/Workspace";
|
||||
import { requireUser } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import { createProjectAction } from "../../actions";
|
||||
|
||||
function Choice({ name, value, checked, children }: { name: string; value: string; checked?: boolean; children: React.ReactNode }) {
|
||||
@ -21,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 t = await getT();
|
||||
let orgs: GiteaOrg[] = [];
|
||||
let giteaError: string | undefined;
|
||||
const giteaUrl = loadEnv().GITEA_URL.replace(/^https?:\/\//, "");
|
||||
@ -37,62 +39,63 @@ export default async function NewProject({ searchParams }: { searchParams: Promi
|
||||
return (
|
||||
<Workspace>
|
||||
<div className="max-w-xl">
|
||||
<PageHeader title="Новый проект" />
|
||||
<PageHeader title={t("Новый проект")} />
|
||||
<Flash error={error ?? giteaError} />
|
||||
<form action={createProjectAction} className="flex flex-col gap-4">
|
||||
<Hidden fields={{ back: "/projects/new" }} />
|
||||
<Label>
|
||||
Название
|
||||
<Input name="name" required placeholder="Платёжный сервис" />
|
||||
{t("Название")}
|
||||
<Input name="name" required placeholder={t("Платёжный сервис")} />
|
||||
</Label>
|
||||
<div className="flex gap-3">
|
||||
<Label className="flex-1">
|
||||
Репозиторий (slug)
|
||||
{t("Репозиторий (slug)")}
|
||||
<Input name="slug" required pattern="[a-z0-9][a-z0-9-]*" placeholder="payments" className="font-mono" />
|
||||
</Label>
|
||||
<Label className="w-32">
|
||||
Ключ стори
|
||||
{t("Ключ стори")}
|
||||
<Input name="key" required pattern="[A-Za-z][A-Za-z0-9]{1,9}" placeholder="PAY" className="font-mono uppercase" />
|
||||
</Label>
|
||||
</div>
|
||||
{local ? (
|
||||
<p className="m-0 rounded-md border bg-muted/40 px-3 py-2 text-sm text-muted-foreground">
|
||||
У вас нет аккаунта Gitea — репозиторий будет <span className="font-mono">{giteaUrl}/{botLogin}/<slug></span>. Доступ к коду — только через
|
||||
Пеппу (агенты, PR, проверки); соавтором в Gitea вас добавить нельзя.
|
||||
{t("У вас нет аккаунта Gitea — репозиторий будет")} <span className="font-mono">{giteaUrl}/{botLogin}/<slug></span>.{" "}
|
||||
{t("Доступ к коду — только через Пеппу (агенты, PR, проверки); соавтором в Gitea вас добавить нельзя.")}
|
||||
</p>
|
||||
) : (
|
||||
<>
|
||||
<Label>
|
||||
Пространство в Gitea
|
||||
{t("Пространство в Gitea")}
|
||||
<NativeSelect name="owner" defaultValue={user.login}>
|
||||
<option value={user.login}>{user.login} — личное</option>
|
||||
<option value={user.login}>{t("{name} — личное", { name: user.login })}</option>
|
||||
{orgs.map((o) => (
|
||||
<option key={o.id} value={o.username}>{o.username} — организация</option>
|
||||
<option key={o.id} value={o.username}>{t("{name} — организация", { name: o.username })}</option>
|
||||
))}
|
||||
</NativeSelect>
|
||||
</Label>
|
||||
<p className="m-0 text-sm text-muted-foreground">
|
||||
Репозиторий будет <span className="font-mono">{giteaUrl}/<пространство>/<slug></span>. В личном пространстве приватный репозиторий видите
|
||||
только вы, <span className="font-mono">peppa-bot</span> и участники проекта; в организации — ещё её участники с доступом к репозиториям.
|
||||
{orgs.length === 0 && " Организаций, где вы можете создавать репозитории, нет."}
|
||||
{t("Репозиторий будет")} <span className="font-mono">{giteaUrl}/<{t("пространство")}>/<slug></span>.{" "}
|
||||
{t("В личном пространстве приватный репозиторий видите только вы,")} <span className="font-mono">peppa-bot</span>{" "}
|
||||
{t("и участники проекта; в организации — ещё её участники с доступом к репозиториям.")}
|
||||
{orgs.length === 0 && " " + t("Организаций, где вы можете создавать репозитории, нет.")}
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
<fieldset className="m-0 flex flex-col gap-2 border-0 p-0">
|
||||
<legend className="mb-2 text-sm font-medium">Видимость</legend>
|
||||
<Choice name="visibility" value="public" checked>Публичный — все, у кого есть доступ к Gitea</Choice>
|
||||
<Choice name="visibility" value="private">Приватный — только те, кому выдан доступ</Choice>
|
||||
<legend className="mb-2 text-sm font-medium">{t("Видимость")}</legend>
|
||||
<Choice name="visibility" value="public" checked>{t("Публичный — все, у кого есть доступ к Gitea")}</Choice>
|
||||
<Choice name="visibility" value="private">{t("Приватный — только те, кому выдан доступ")}</Choice>
|
||||
</fieldset>
|
||||
<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">Подключить существующий (нужны права админа; видимость не меняется)</Choice>
|
||||
<legend className="mb-2 text-sm font-medium">{t("Репозиторий")}</legend>
|
||||
<Choice name="mode" value="new" checked>{t("Создать новый")}</Choice>
|
||||
<Choice name="mode" value="existing">{t("Подключить существующий (нужны права админа; видимость не меняется)")}</Choice>
|
||||
</fieldset>
|
||||
<p className="m-0 text-sm text-muted-foreground">
|
||||
Пеппа добавит <span className="font-mono">peppa-bot</span> соавтором, положит AGENTS.md, .mcp.json и .peppa/project.json из шаблона и запустит
|
||||
openspec init. Занимает до ~15 секунд.
|
||||
{t("Пеппа добавит")} <span className="font-mono">peppa-bot</span>{" "}
|
||||
{t("соавтором, положит AGENTS.md, .mcp.json и .peppa/project.json из шаблона и запустит openspec init. Занимает до ~15 секунд.")}
|
||||
</p>
|
||||
<Button variant="default" className="self-start">Создать проект</Button>
|
||||
<Button variant="default" className="self-start">{t("Создать проект")}</Button>
|
||||
</form>
|
||||
</div>
|
||||
</Workspace>
|
||||
|
||||
@ -7,31 +7,33 @@ import { Button } from "@/components/ui/button";
|
||||
import { Workspace } from "@/components/Workspace";
|
||||
import { requireUser } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { getT } from "@/lib/i18n";
|
||||
|
||||
export default async function Projects({ searchParams }: { searchParams: Promise<{ error?: string }> }) {
|
||||
const user = await requireUser();
|
||||
const { error } = await searchParams;
|
||||
const t = await getT();
|
||||
const [projects, others] = await Promise.all([listUserProjects(db, user.id), listOtherProjects(db, user.id)]);
|
||||
return (
|
||||
<Workspace>
|
||||
<Flash error={error} />
|
||||
<PageHeader
|
||||
title="Проекты"
|
||||
title={t("Проекты")}
|
||||
actions={
|
||||
<Button asChild variant="default" size="sm">
|
||||
<Link href="/projects/new">
|
||||
<Plus />
|
||||
Новый проект
|
||||
{t("Новый проект")}
|
||||
</Link>
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
Свои и общие проекты: доска стори, код, PR, релизы, ошибки из прода, участники.
|
||||
{t("Свои и общие проекты: доска стори, код, PR, релизы, ошибки из прода, участники.")}
|
||||
</PageHeader>
|
||||
<ProjectList projects={projects} userId={user.id} />
|
||||
{others.length > 0 && (
|
||||
<Section title="Проекты других" count={others.length}>
|
||||
<p className="m-0 text-sm text-muted-foreground">Видны вам как суперадмину. Вопросы агентов и уведомления этих проектов к вам не приходят.</p>
|
||||
<Section title={t("Проекты других")} count={others.length}>
|
||||
<p className="m-0 text-sm text-muted-foreground">{t("Видны вам как суперадмину. Вопросы агентов и уведомления этих проектов к вам не приходят.")}</p>
|
||||
<ProjectList projects={others} userId={user.id} />
|
||||
</Section>
|
||||
)}
|
||||
|
||||
@ -12,13 +12,15 @@ import { requireUser } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { inbox, sessionEvents } from "@/lib/queries";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
|
||||
const FILTERS: Array<{ key: RunnerFilter | undefined; label: string }> = [
|
||||
{ key: undefined, label: "все" },
|
||||
{ key: "waiting", label: "ждут тебя" },
|
||||
{ key: "working", label: "работают" },
|
||||
{ key: "stopped", label: "упали" },
|
||||
{ key: "finished", label: "готово" },
|
||||
{ key: undefined, label: m("все") },
|
||||
{ key: "waiting", label: m("ждут тебя") },
|
||||
{ key: "working", label: m("работают") },
|
||||
{ key: "stopped", label: m("упали") },
|
||||
{ key: "finished", label: m("готово") },
|
||||
];
|
||||
const inFilter = (s: SessionView, f: RunnerFilter) => (RUNNER_FILTERS[f] as string[]).includes(s.status);
|
||||
const matches = (s: SessionView, q: string) =>
|
||||
@ -28,6 +30,7 @@ type Params = { error?: string; f?: string; q?: string; id?: string };
|
||||
|
||||
export default async function Runners({ searchParams }: { searchParams: Promise<Params> }) {
|
||||
const user = await requireUser();
|
||||
const t = await getT();
|
||||
const { error, f, q: rawQ, id } = await searchParams;
|
||||
const filter = f && f in RUNNER_FILTERS ? (f as RunnerFilter) : undefined;
|
||||
const q = rawQ?.trim().toLowerCase() ?? "";
|
||||
@ -62,19 +65,19 @@ export default async function Runners({ searchParams }: { searchParams: Promise<
|
||||
<LiveRefresh scope="runners" />
|
||||
<Flash error={error} />
|
||||
<PageHeader
|
||||
title="Работа агентов"
|
||||
title={t("Работа агентов")}
|
||||
actions={
|
||||
projects.length > 0 && (
|
||||
<SettingsDialog title="Новый терминал" trigger={<><SquareTerminal />Новый терминал</>}>
|
||||
<SettingsDialog title={t("Новый терминал")} trigger={<><SquareTerminal />{t("Новый терминал")}</>}>
|
||||
<NewRunnerForm projects={projects} back="/runners" />
|
||||
</SettingsDialog>
|
||||
)
|
||||
}
|
||||
>
|
||||
Агенты в tmux по стори твоих и общих проектов и свободные терминалы: кто ждёт тебя, кто работает, что готово.
|
||||
{t("Агенты в 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="Фильтр раннеров">
|
||||
<nav className="flex flex-wrap gap-1.5" aria-label={t("Фильтр раннеров")}>
|
||||
{FILTERS.map((x) => {
|
||||
const n = count(x.key);
|
||||
const active = x.key === filter;
|
||||
@ -89,7 +92,7 @@ export default async function Runners({ searchParams }: { searchParams: Promise<
|
||||
)}
|
||||
>
|
||||
<span className={cn("font-mono font-semibold tabular-nums", x.key === "waiting" && n > 0 ? "text-primary" : "text-foreground")}>{n}</span>
|
||||
{x.label}
|
||||
{t(x.label)}
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
@ -97,11 +100,11 @@ export default async function Runners({ searchParams }: { searchParams: Promise<
|
||||
<form action="/runners" className="relative lg:ml-auto lg:w-64" role="search">
|
||||
{filter && <input type="hidden" name="f" value={filter} />}
|
||||
<Search className="pointer-events-none absolute top-1/2 left-2.5 size-4 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input type="search" name="q" data-hotkey-search defaultValue={rawQ ?? ""} placeholder="Стори, проект, tmux…" aria-label="Поиск раннеров" className="h-8 pl-8" />
|
||||
<Input type="search" name="q" data-hotkey-search defaultValue={rawQ ?? ""} placeholder={t("Стори, проект, tmux…")} aria-label={t("Поиск раннеров")} className="h-8 pl-8" />
|
||||
</form>
|
||||
</div>
|
||||
{shown.length === 0 ? (
|
||||
<Empty>{q || filter ? "Таких раннеров нет." : "Раннеров пока не было: перенеси стори в «В работе» на доске проекта."}</Empty>
|
||||
<Empty>{q || filter ? t("Таких раннеров нет.") : t("Раннеров пока не было: перенеси стори в «В работе» на доске проекта.")}</Empty>
|
||||
) : (
|
||||
<ul className="m-0 flex list-none flex-col gap-1 rounded-lg border bg-card/50 p-1.5">
|
||||
{shown.map((s) => (
|
||||
|
||||
@ -9,23 +9,28 @@ import { Card } from "@/components/ui/card";
|
||||
import { Workspace } from "@/components/Workspace";
|
||||
import { requireUser } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import { intlLocale, type Translator } from "@peppa/shared/i18n";
|
||||
import { checkGiteaTokenAction, markSecretRotatedAction, reencryptSecretsAction, revokeClientTokensAction } from "../actions";
|
||||
|
||||
export const metadata = { title: "Секреты — Пеппа" };
|
||||
export async function generateMetadata() {
|
||||
const t = await getT();
|
||||
return { title: t("Секреты — Пеппа") };
|
||||
}
|
||||
|
||||
type Params = { error?: string; reencrypted?: string; unreadable?: string; revoked?: string; gitea?: string };
|
||||
|
||||
const day = (d: Date | null) => (d ? d.toLocaleDateString("ru-RU") : "—");
|
||||
const day = (d: Date | null, t: Translator) => (d ? d.toLocaleDateString(intlLocale(t.locale)) : "—");
|
||||
|
||||
function State({ r }: { r: PlatformSecretRow }) {
|
||||
if (r.set === null) return <Badge variant="secondary">вне .env</Badge>;
|
||||
if (!r.set) return r.optional ? <Badge variant="secondary">не задан</Badge> : <Badge variant="danger">не задан</Badge>;
|
||||
return <Badge variant="ok">задан</Badge>;
|
||||
function State({ r, t }: { r: PlatformSecretRow; t: Translator }) {
|
||||
if (r.set === null) return <Badge variant="secondary">{t("вне .env")}</Badge>;
|
||||
if (!r.set) return r.optional ? <Badge variant="secondary">{t("не задан")}</Badge> : <Badge variant="danger">{t("не задан")}</Badge>;
|
||||
return <Badge variant="ok">{t("задан")}</Badge>;
|
||||
}
|
||||
|
||||
function Age({ r }: { r: PlatformSecretRow }) {
|
||||
if (r.ageDays === null) return <Badge variant="warn">возраст неизвестен</Badge>;
|
||||
return r.stale ? <Badge variant="warn">{r.ageDays} дн. — пора ротировать</Badge> : <Badge variant="info">{r.ageDays} дн.</Badge>;
|
||||
function Age({ r, t }: { r: PlatformSecretRow; t: Translator }) {
|
||||
if (r.ageDays === null) return <Badge variant="warn">{t("возраст неизвестен")}</Badge>;
|
||||
return r.stale ? <Badge variant="warn">{t("{n} дн. — пора ротировать", { n: r.ageDays })}</Badge> : <Badge variant="info">{t("{n} дн.", { n: r.ageDays })}</Badge>;
|
||||
}
|
||||
|
||||
/** Inline `code` in instruction steps. */
|
||||
@ -47,69 +52,72 @@ function Step({ text }: { text: string }) {
|
||||
|
||||
export default async function Secrets({ searchParams }: { searchParams: Promise<Params> }) {
|
||||
const user = await requireUser();
|
||||
const t = await getT();
|
||||
if (!(await isSuperadmin(db, user))) notFound();
|
||||
const q = await searchParams;
|
||||
const a = await secretsAudit(db);
|
||||
const enc = a.encryption;
|
||||
// The link sits inside the sentence: split the translated text around {link}.
|
||||
const reissue = t("Перевыпуск — в {link}: «Переподключить» запускает новый вход, старый токен Claude отзывается в claude.ai → Settings → Claude Code.").split("{link}");
|
||||
|
||||
return (
|
||||
<Workspace>
|
||||
<div className="max-w-3xl">
|
||||
<Flash error={q.error} />
|
||||
<PageHeader title={<><ShieldCheck className="mr-1 inline size-5 text-primary" />Секреты</>}>
|
||||
Ревизия секретов и доступов платформы: что задано, сколько лет каждому секрету, кто им пользуется и как его сменить. Значения здесь не показываются никогда. Раздел видят только суперадмины.
|
||||
<PageHeader title={<><ShieldCheck className="mr-1 inline size-5 text-primary" />{t("Секреты")}</>}>
|
||||
{t("Ревизия секретов и доступов платформы: что задано, сколько лет каждому секрету, кто им пользуется и как его сменить. Значения здесь не показываются никогда. Раздел видят только суперадмины.")}
|
||||
</PageHeader>
|
||||
{q.reencrypted !== undefined && (
|
||||
<Notice>
|
||||
Перешифровано: {q.reencrypted}
|
||||
{Number(q.unreadable) > 0 ? ` · не читается ни одним ключом: ${q.unreadable}` : ""}
|
||||
{t("Перешифровано: {n}", { n: q.reencrypted })}
|
||||
{Number(q.unreadable) > 0 ? " · " + t("не читается ни одним ключом: {n}", { n: q.unreadable }) : ""}
|
||||
</Notice>
|
||||
)}
|
||||
{q.revoked !== undefined && <Notice>Отозвано токенов: {q.revoked}</Notice>}
|
||||
{q.gitea && <Notice>{q.gitea.startsWith("ok:") ? `GITEA_TOKEN принадлежит ${q.gitea.slice(3)}, админских прав нет` : `GITEA_TOKEN: ${q.gitea}`}</Notice>}
|
||||
{q.revoked !== undefined && <Notice>{t("Отозвано токенов: {n}", { n: q.revoked })}</Notice>}
|
||||
{q.gitea && <Notice>{q.gitea.startsWith("ok:") ? t("GITEA_TOKEN принадлежит {login}, админских прав нет", { login: q.gitea.slice(3) }) : `GITEA_TOKEN: ${t.text(q.gitea)}`}</Notice>}
|
||||
|
||||
<Section title="Ключ шифрования">
|
||||
<Section title={t("Ключ шифрования")}>
|
||||
<Card className="flex flex-col gap-2 p-4 text-sm">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{!enc.configured ? <Badge variant="danger">PEPPA_SECRET не задан</Badge> : enc.rotating ? <Badge variant="warn">идёт смена ключа</Badge> : <Badge variant="ok">один ключ</Badge>}
|
||||
<span>на старом ключе: {enc.previous}</span>
|
||||
<span>· не читается: {enc.unreadable}</span>
|
||||
{!enc.configured ? <Badge variant="danger">{t("PEPPA_SECRET не задан")}</Badge> : enc.rotating ? <Badge variant="warn">{t("идёт смена ключа")}</Badge> : <Badge variant="ok">{t("один ключ")}</Badge>}
|
||||
<span>{t("на старом ключе: {n}", { n: enc.previous })}</span>
|
||||
<span>· {t("не читается: {n}", { n: enc.unreadable })}</span>
|
||||
</div>
|
||||
<ul className="m-0 flex list-none flex-col gap-0.5 p-0 text-xs text-muted-foreground">
|
||||
{enc.columns.filter((c) => c.total).map((c) => (
|
||||
<li key={`${c.table}.${c.column}`} className="font-mono">
|
||||
{c.table}.{c.column}: {c.total} · текущий {c.current} · старый {c.previous} · не читается {c.unreadable}
|
||||
{c.table}.{c.column}: {t("{total} · текущий {current} · старый {previous} · не читается {unreadable}", { total: c.total, current: c.current, previous: c.previous, unreadable: c.unreadable })}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<form action={reencryptSecretsAction}>
|
||||
<Hidden fields={{ back: "/secrets" }} />
|
||||
<Button size="sm" variant={enc.previous ? "default" : "outline"} disabled={!enc.configured}>
|
||||
Перешифровать текущим ключом
|
||||
{t("Перешифровать текущим ключом")}
|
||||
</Button>
|
||||
</form>
|
||||
</Card>
|
||||
</Section>
|
||||
|
||||
<Section title="Секреты платформы" count={a.platform.length}>
|
||||
<Section title={t("Секреты платформы")} count={a.platform.length}>
|
||||
{a.platform.map((r) => (
|
||||
<Card key={r.name} className="flex flex-col gap-2 p-4">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className="font-mono text-sm font-medium">{r.name}</span>
|
||||
<State r={r} />
|
||||
<Age r={r} />
|
||||
<Badge variant="secondary">{r.how === "peppa" ? "ротирует Пеппа" : "вручную"}</Badge>
|
||||
<State r={r} t={t} />
|
||||
<Age r={r} t={t} />
|
||||
<Badge variant="secondary">{r.how === "peppa" ? t("ротирует Пеппа") : t("вручную")}</Badge>
|
||||
</div>
|
||||
<p className="m-0 text-sm">{r.label}</p>
|
||||
<p className="m-0 text-sm">{t.text(r.label)}</p>
|
||||
<p className="m-0 text-xs text-muted-foreground">
|
||||
Использует: {r.usedBy}
|
||||
{r.rotatedAt ? ` · последняя ротация ${day(r.rotatedAt)}${r.rotatedBy ? ` (${r.rotatedBy})` : ""}` : ""}
|
||||
{t("Использует: {who}", { who: t.text(r.usedBy) })}
|
||||
{r.rotatedAt ? " · " + (r.rotatedBy ? t("последняя ротация {date} ({by})", { date: day(r.rotatedAt, t), by: r.rotatedBy }) : t("последняя ротация {date}", { date: day(r.rotatedAt, t) })) : ""}
|
||||
</p>
|
||||
<Disclosure summary="Как ротировать">
|
||||
<Disclosure summary={t("Как ротировать")}>
|
||||
<ol className="m-0 flex flex-col gap-1 pl-5 text-sm">
|
||||
{r.steps.map((s, i) => (
|
||||
<li key={i}>
|
||||
<Step text={s} />
|
||||
<Step text={t.text(s)} />
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
@ -118,13 +126,13 @@ export default async function Secrets({ searchParams }: { searchParams: Promise<
|
||||
{r.how === "external" && (
|
||||
<form action={markSecretRotatedAction}>
|
||||
<Hidden fields={{ name: r.name, back: "/secrets" }} />
|
||||
<Button size="sm" variant="outline">Отметить: ротирован сегодня</Button>
|
||||
<Button size="sm" variant="outline">{t("Отметить: ротирован сегодня")}</Button>
|
||||
</form>
|
||||
)}
|
||||
{r.name === "GITEA_TOKEN" && (
|
||||
<form action={checkGiteaTokenAction}>
|
||||
<Hidden fields={{ back: "/secrets" }} />
|
||||
<Button size="sm" variant="outline">Проверить токен Gitea</Button>
|
||||
<Button size="sm" variant="outline">{t("Проверить токен Gitea")}</Button>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
@ -132,51 +140,53 @@ export default async function Secrets({ searchParams }: { searchParams: Promise<
|
||||
))}
|
||||
</Section>
|
||||
|
||||
<Section title="MCP-клиенты (OAuth)" count={a.oauth.length}>
|
||||
<Section title={t("MCP-клиенты (OAuth)")} count={a.oauth.length}>
|
||||
{a.oauth.length === 0 ? (
|
||||
<Empty>Живых MCP-токенов нет.</Empty>
|
||||
<Empty>{t("Живых MCP-токенов нет.")}</Empty>
|
||||
) : (
|
||||
a.oauth.map((c) => (
|
||||
<Card key={c.clientId} className="flex flex-wrap items-center gap-2 p-3 text-sm">
|
||||
<span className="font-medium">{c.name}</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
токенов {c.liveTokens} · людей {c.users} · старейший {day(c.oldestAt)} · использован {day(c.lastUsedAt)}
|
||||
{c.beforeKeyRotation ? ` · выданы до смены ключа: ${c.beforeKeyRotation}` : ""}
|
||||
{t("токенов {tokens} · людей {users} · старейший {oldest} · использован {used}", { tokens: c.liveTokens, users: c.users, oldest: day(c.oldestAt, t), used: day(c.lastUsedAt, t) })}
|
||||
{c.beforeKeyRotation ? " · " + t("выданы до смены ключа: {n}", { n: c.beforeKeyRotation }) : ""}
|
||||
</span>
|
||||
<form action={revokeClientTokensAction} className="ml-auto">
|
||||
<Hidden fields={{ clientId: c.clientId, back: "/secrets" }} />
|
||||
<Button size="sm" variant="outline">Отозвать все токены</Button>
|
||||
<Button size="sm" variant="outline">{t("Отозвать все токены")}</Button>
|
||||
</form>
|
||||
</Card>
|
||||
))
|
||||
)}
|
||||
<p className="m-0 text-xs text-muted-foreground">Пользователи отзывают свои подключения сами в «Настройках»; OAuth Gitea у пользователей: {a.gitea.usersWithToken} (истекли {a.gitea.expired}) — обновляются при входе.</p>
|
||||
<p className="m-0 text-xs text-muted-foreground">{t("Пользователи отзывают свои подключения сами в «Настройках»; OAuth Gitea у пользователей: {n} (истекли {expired}) — обновляются при входе.", { n: a.gitea.usersWithToken, expired: a.gitea.expired })}</p>
|
||||
</Section>
|
||||
|
||||
<Section title="Подписки агентов" count={a.subscriptions.length}>
|
||||
<Section title={t("Подписки агентов")} count={a.subscriptions.length}>
|
||||
{a.subscriptions.length === 0 ? (
|
||||
<Empty>Подписок нет.</Empty>
|
||||
<Empty>{t("Подписок нет.")}</Empty>
|
||||
) : (
|
||||
<ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm">
|
||||
{a.subscriptions.map((s) => (
|
||||
<li key={s.id} className="flex flex-wrap items-center gap-2 rounded-md border px-3 py-2">
|
||||
<span className="font-medium">{s.name}</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{s.provider} · {s.status} · сессий {s.liveSessions} · пулы: {s.pools.join(", ") || "—"}
|
||||
{s.provider} · {s.status} · {t("сессий {n} · пулы: {pools}", { n: s.liveSessions, pools: s.pools.join(", ") || "—" })}
|
||||
</span>
|
||||
{s.stale ? <Badge variant="warn">{s.ageDays} дн. — перевыпустить</Badge> : <Badge variant="info">{s.ageDays} дн.</Badge>}
|
||||
{s.stale ? <Badge variant="warn">{t("{n} дн. — перевыпустить", { n: s.ageDays })}</Badge> : <Badge variant="info">{t("{n} дн.", { n: s.ageDays })}</Badge>}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
<p className="m-0 text-xs text-muted-foreground">
|
||||
Перевыпуск — в <a href="/subscriptions">«Подписках»</a>: «Переподключить» запускает новый вход, старый токен Claude отзывается в claude.ai → Settings → Claude Code.
|
||||
{reissue[0]}
|
||||
<a href="/subscriptions">{t("«Подписках»")}</a>
|
||||
{reissue[1]}
|
||||
</p>
|
||||
</Section>
|
||||
|
||||
<Section title="Секреты проектов" count={a.projects.length}>
|
||||
<Section title={t("Секреты проектов")} count={a.projects.length}>
|
||||
{a.projects.length === 0 ? (
|
||||
<Empty>Ни в одном проекте секретов нет.</Empty>
|
||||
<Empty>{t("Ни в одном проекте секретов нет.")}</Empty>
|
||||
) : (
|
||||
<ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm">
|
||||
{a.projects.map((p) => (
|
||||
@ -185,7 +195,7 @@ export default async function Secrets({ searchParams }: { searchParams: Promise<
|
||||
{p.key}
|
||||
</a>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
секретов {p.secrets} · старейший {day(p.oldestAt)} · выдан агенту {day(p.lastUsedAt)}
|
||||
{t("секретов {n} · старейший {oldest} · выдан агенту {used}", { n: p.secrets, oldest: day(p.oldestAt, t), used: day(p.lastUsedAt, t) })}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
|
||||
@ -13,6 +13,9 @@ import { db } from "@/lib/db";
|
||||
import { unlinkGoogleAction, disconnectOwnBotAction, revokeConnectedApp, saveNotifyPrefsAction, unpairTelegramAction } from "../actions";
|
||||
import { PushNotifications } from "@/components/PushNotifications";
|
||||
import { TimezoneField } from "@/components/TimezoneField";
|
||||
import { LanguageSwitcher } from "@/components/I18n";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import { intlLocale } from "@peppa/shared/i18n";
|
||||
|
||||
const back = { back: "/settings" };
|
||||
|
||||
@ -41,99 +44,106 @@ export default async function Settings({ searchParams }: { searchParams: Promise
|
||||
const myProjects = await listUserProjects(db, user.id);
|
||||
const pushSubs = await userPushSubscriptions(db, user.id);
|
||||
const vapid = await vapidPublicKey(db);
|
||||
const t = await getT();
|
||||
const ownBotSteps = <OwnBotSteps botUsername={user.telegramBotUsername} back="/settings" />;
|
||||
return (
|
||||
<Workspace>
|
||||
<div className="max-w-2xl">
|
||||
<Flash error={error} />
|
||||
<PageHeader title="Настройки" />
|
||||
<Section title="Учётная запись">
|
||||
<PageHeader title={t("Настройки")} />
|
||||
<Section title={t("Язык интерфейса")} id="language">
|
||||
<Card className="flex-row flex-wrap items-center gap-3">
|
||||
<LanguageSwitcher />
|
||||
<p className="m-0 min-w-0 flex-[1_1_16rem] text-sm text-muted-foreground">{t("Казахский скоро появится — пока вместо него показывается русский.")}</p>
|
||||
</Card>
|
||||
</Section>
|
||||
<Section title={t("Учётная запись")}>
|
||||
<Card>
|
||||
<p className="m-0 text-sm">
|
||||
Логин <span className="font-mono">{user.login}</span>
|
||||
{user.name ? <> · {user.name}</> : null}. Вход в Пеппу — через eGov QR или Google
|
||||
{t("Логин")} <span className="font-mono">{user.login}</span>
|
||||
{user.name ? <> · {user.name}</> : null}.{" "}{t("Вход в Пеппу — через eGov QR или Google")}
|
||||
{user.egovIin ? (
|
||||
<>
|
||||
, ИИН <span className="font-mono">{maskIin(user.egovIin)}</span>.
|
||||
, {t("ИИН")} <span className="font-mono">{maskIin(user.egovIin)}</span>.
|
||||
</>
|
||||
) : (
|
||||
<>. <b>ИИН ещё не привязан</b>{user.googleSub ? "." : " — привяжите его ниже или Google, иначе после выхода вы не сможете войти."}</>
|
||||
<>. <b>{t("ИИН ещё не привязан")}</b>{user.googleSub ? "." : <>{" — "}{t("привяжите его ниже или Google, иначе после выхода вы не сможете войти.")}</>}</>
|
||||
)}
|
||||
</p>
|
||||
{local && (
|
||||
<p className="m-0 text-sm text-muted-foreground">
|
||||
Аккаунта Gitea нет: код проектов — через Пеппу (агенты, PR, проверки), новые проекты создаются в пространстве <span className="font-mono">peppa-bot</span>.
|
||||
{t("Аккаунта Gitea нет: код проектов — через Пеппу (агенты, PR, проверки), новые проекты создаются в пространстве")} <span className="font-mono">peppa-bot</span>.
|
||||
</p>
|
||||
)}
|
||||
</Card>
|
||||
{superadmin && (
|
||||
<Row
|
||||
title="Суперадмин"
|
||||
title={t("Суперадмин")}
|
||||
actions={
|
||||
<>
|
||||
<Button asChild size="sm">
|
||||
<a href="/users">Пользователи</a>
|
||||
<a href="/users">{t("Пользователи")}</a>
|
||||
</Button>
|
||||
<Button asChild size="sm">
|
||||
<a href="/subscriptions">Подписки</a>
|
||||
<a href="/subscriptions">{t("Подписки")}</a>
|
||||
</Button>
|
||||
<Button asChild size="sm">
|
||||
<a href="/secrets">Секреты</a>
|
||||
<a href="/secrets">{t("Секреты")}</a>
|
||||
</Button>
|
||||
<Button asChild size="sm">
|
||||
<a href="/hosts">Хосты</a>
|
||||
<a href="/hosts">{t("Хосты")}</a>
|
||||
</Button>
|
||||
<Button asChild size="sm">
|
||||
<a href="/journal">Журнал</a>
|
||||
<a href="/journal">{t("Журнал")}</a>
|
||||
</Button>
|
||||
<Button asChild size="sm">
|
||||
<a href="/platform">Платформа</a>
|
||||
<a href="/platform">{t("Платформа")}</a>
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
Пользователи: кто зарегистрировался через eGov, отключить и включить. Подписки агентов и пулы для ротации. Журнал: кто что сделал.
|
||||
{t("Пользователи: кто зарегистрировался через eGov, отключить и включить. Подписки агентов и пулы для ротации. Журнал: кто что сделал.")}
|
||||
</Row>
|
||||
)}
|
||||
</Section>
|
||||
<Section title="Агенты">
|
||||
<Section title={t("Агенты")}>
|
||||
<p className="m-0 text-sm text-muted-foreground">
|
||||
Подписки Claude Code, Codex и OpenCode, на которых работают агенты, ведёт суперадмин в разделе «Подписки»; проект запускает раннеры на своём пуле подписок.
|
||||
{t("Подписки Claude Code, Codex и OpenCode, на которых работают агенты, ведёт суперадмин в разделе «Подписки»; проект запускает раннеры на своём пуле подписок.")}
|
||||
</p>
|
||||
</Section>
|
||||
{!user.egovIin && (
|
||||
<Section title="eGov" id="egov">
|
||||
{egov === "linked" && <Notice>eGov привязан — теперь можно входить по QR</Notice>}
|
||||
{egov === "linked" && <Notice>{t("eGov привязан — теперь можно входить по QR")}</Notice>}
|
||||
<Card>
|
||||
<p className="m-0 text-sm">Привяжите свой ИИН: отсканируйте QR в eGov Mobile и подпишите. Вход в Пеппу — только через eGov.</p>
|
||||
<p className="m-0 text-sm">{t("Привяжите свой ИИН: отсканируйте QR в eGov Mobile и подпишите. Вход в Пеппу — только через eGov.")}</p>
|
||||
<div className="max-w-xs">
|
||||
<EgovSign purpose="link" label="Привязать eGov" />
|
||||
<EgovSign purpose="link" label={t("Привязать eGov")} />
|
||||
</div>
|
||||
</Card>
|
||||
</Section>
|
||||
)}
|
||||
{user.egovIin && egov === "linked" && <Notice>eGov привязан — теперь можно входить по QR</Notice>}
|
||||
{user.egovIin && egov === "linked" && <Notice>{t("eGov привязан — теперь можно входить по QR")}</Notice>}
|
||||
|
||||
{(googleEnabled() || user.googleSub) && (
|
||||
<Section title="Google" id="google">
|
||||
{google === "linked" && <Notice>Google привязан — теперь можно входить через него</Notice>}
|
||||
{google === "linked" && <Notice>{t("Google привязан — теперь можно входить через него")}</Notice>}
|
||||
{user.googleSub ? (
|
||||
<Row
|
||||
title="Google привязан"
|
||||
title={t("Google привязан")}
|
||||
actions={
|
||||
<form action={unlinkGoogleAction}>
|
||||
<Hidden fields={{ back: "/settings#google" }} />
|
||||
<Button size="sm" variant="destructive">Отвязать</Button>
|
||||
<Button size="sm" variant="destructive">{t("Отвязать")}</Button>
|
||||
</form>
|
||||
}
|
||||
>
|
||||
{user.googleEmail}. Войти через Google можно в ту же учётку.
|
||||
{user.googleEmail}. {t("Войти через Google можно в ту же учётку.")}
|
||||
</Row>
|
||||
) : (
|
||||
<Card>
|
||||
<p className="m-0 text-sm">Привяжите Google-аккаунт — и в эту учётку можно будет входить и через него.</p>
|
||||
<p className="m-0 text-sm">{t("Привяжите Google-аккаунт — и в эту учётку можно будет входить и через него.")}</p>
|
||||
<div className="max-w-xs">
|
||||
<GoogleSignIn purpose="link" label="Привязать Google" />
|
||||
<GoogleSignIn purpose="link" label={t("Привязать Google")} />
|
||||
</div>
|
||||
</Card>
|
||||
)}
|
||||
@ -141,65 +151,65 @@ export default async function Settings({ searchParams }: { searchParams: Promise
|
||||
)}
|
||||
|
||||
<Section title="Telegram" id="telegram">
|
||||
{bot === "connected" && <Notice>Бот @{user.telegramBotUsername} подключён — остался последний шаг: откройте его и нажмите Start.</Notice>}
|
||||
{bot === "connected" && <Notice>{t("Бот @{bot} подключён — остался последний шаг: откройте его и нажмите Start.", { bot: user.telegramBotUsername })}</Notice>}
|
||||
{user.telegramChatId ? (
|
||||
<Row
|
||||
title={`Telegram привязан${user.telegramUsername ? ` (@${user.telegramUsername})` : ""}`}
|
||||
title={t("Telegram привязан") + (user.telegramUsername ? ` (@${user.telegramUsername})` : "")}
|
||||
actions={
|
||||
<form action={unpairTelegramAction}>
|
||||
<Hidden fields={back} />
|
||||
<Button size="sm" variant="destructive">Отвязать</Button>
|
||||
<Button size="sm" variant="destructive">{t("Отвязать")}</Button>
|
||||
</form>
|
||||
}
|
||||
>
|
||||
Вопросы агентов и «готово к ревью» приходят вам {user.telegramBotUsername ? <>от вашего бота <span className="font-mono">@{user.telegramBotUsername}</span></> : "от общего бота Пеппы"}. Новую задачу можно просто написать боту.
|
||||
{t("Вопросы агентов и «готово к ревью» приходят вам")} {user.telegramBotUsername ? <>{t("от вашего бота")} <span className="font-mono">@{user.telegramBotUsername}</span></> : t("от общего бота Пеппы")}. {t("Новую задачу можно просто написать боту.")}
|
||||
</Row>
|
||||
) : (
|
||||
ownBotSteps
|
||||
)}
|
||||
{user.telegramChatId && !hasBot && (
|
||||
<Disclosure summary="Перейти на своего бота">
|
||||
<Disclosure summary={t("Перейти на своего бота")}>
|
||||
<div className="px-4 pb-4">{ownBotSteps}</div>
|
||||
</Disclosure>
|
||||
)}
|
||||
{user.telegramChatId && hasBot && (
|
||||
<form action={disconnectOwnBotAction}>
|
||||
<Hidden fields={back} />
|
||||
<Button size="xs" variant="ghost" className="text-muted-foreground">Отключить бота @{user.telegramBotUsername}</Button>
|
||||
<Button size="xs" variant="ghost" className="text-muted-foreground">{t("Отключить бота @{bot}", { bot: user.telegramBotUsername })}</Button>
|
||||
</form>
|
||||
)}
|
||||
</Section>
|
||||
<Section title="Уведомления" id="notifications">
|
||||
{notify === "saved" && <Notice>Настройки уведомлений сохранены</Notice>}
|
||||
<Section title={t("Уведомления")} id="notifications">
|
||||
{notify === "saved" && <Notice>{t("Настройки уведомлений сохранены")}</Notice>}
|
||||
<Card>
|
||||
<div className="flex flex-col gap-1">
|
||||
<div className="font-medium">Браузер</div>
|
||||
<div className="font-medium">{t("Браузер")}</div>
|
||||
<p className="m-0 text-sm text-muted-foreground">
|
||||
Push приходят и при закрытой вкладке; клик открывает стори или проект. Подписано браузеров: {pushSubs.length}. Пеппу можно установить как приложение (Chrome → «Установить»).
|
||||
{t("Push приходят и при закрытой вкладке; клик открывает стори или проект. Подписано браузеров: {n}. Пеппу можно установить как приложение (Chrome → «Установить»).", { n: pushSubs.length })}
|
||||
</p>
|
||||
</div>
|
||||
<PushNotifications vapidKey={vapid} known={pushSubs.map((s) => s.endpoint)} />
|
||||
</Card>
|
||||
<form action={saveNotifyPrefsAction} className="flex flex-col gap-4" aria-label="Настройки уведомлений">
|
||||
<form action={saveNotifyPrefsAction} className="flex flex-col gap-4" aria-label={t("Настройки уведомлений")}>
|
||||
<Hidden fields={back} />
|
||||
<Card className="gap-0 p-0">
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr className="border-b text-left text-muted-foreground">
|
||||
<th className="px-4 py-2 font-normal">Событие</th>
|
||||
<th className="px-4 py-2 font-normal">{t("Событие")}</th>
|
||||
<th className="w-24 px-2 py-2 text-center font-normal">Telegram</th>
|
||||
<th className="w-24 px-2 py-2 text-center font-normal">Браузер</th>
|
||||
<th className="w-24 px-2 py-2 text-center font-normal">{t("Браузер")}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{NOTIFY_EVENTS.filter((e) => e !== "monitoring" || superadmin).map((e) => (
|
||||
<tr key={e} className="border-b last:border-0">
|
||||
<td className="px-4 py-2">{NOTIFY_EVENT_NAMES[e]}</td>
|
||||
<td className="px-4 py-2">{t.text(NOTIFY_EVENT_NAMES[e])}</td>
|
||||
<td className="px-2 py-2 text-center">
|
||||
<input type="checkbox" name={`${e}.telegram`} defaultChecked={prefs.events[e].telegram} aria-label={`${NOTIFY_EVENT_NAMES[e]} — Telegram`} className="size-4 accent-primary" />
|
||||
<input type="checkbox" name={`${e}.telegram`} defaultChecked={prefs.events[e].telegram} aria-label={`${t.text(NOTIFY_EVENT_NAMES[e])} — Telegram`} className="size-4 accent-primary" />
|
||||
</td>
|
||||
<td className="px-2 py-2 text-center">
|
||||
<input type="checkbox" name={`${e}.push`} defaultChecked={prefs.events[e].push} aria-label={`${NOTIFY_EVENT_NAMES[e]} — браузер`} className="size-4 accent-primary" />
|
||||
<input type="checkbox" name={`${e}.push`} defaultChecked={prefs.events[e].push} aria-label={t.text(NOTIFY_EVENT_NAMES[e]) + " — " + t("браузер")} className="size-4 accent-primary" />
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
@ -215,38 +225,38 @@ export default async function Settings({ searchParams }: { searchParams: Promise
|
||||
<Card>
|
||||
<label className="flex items-center gap-2 text-sm font-medium">
|
||||
<input type="checkbox" name="quietOn" defaultChecked={!!prefs.quiet} className="size-4 accent-primary" />
|
||||
Тихие часы
|
||||
{t("Тихие часы")}
|
||||
</label>
|
||||
<div className="flex flex-wrap items-end gap-3">
|
||||
<Label className="w-32">
|
||||
С
|
||||
{t("С")}
|
||||
<Input type="time" name="quietFrom" defaultValue={prefs.quiet?.from ?? "23:00"} />
|
||||
</Label>
|
||||
<Label className="w-32">
|
||||
До
|
||||
{t("До")}
|
||||
<Input type="time" name="quietTo" defaultValue={prefs.quiet?.to ?? "08:00"} />
|
||||
</Label>
|
||||
</div>
|
||||
<p className="m-0 text-sm text-muted-foreground">В тихие часы Telegram приходит без звука, push в браузер не показываются. Дайджест приходит в своё время.</p>
|
||||
<p className="m-0 text-sm text-muted-foreground">{t("В тихие часы Telegram приходит без звука, push в браузер не показываются. Дайджест приходит в своё время.")}</p>
|
||||
<div className="flex flex-wrap items-end gap-3">
|
||||
<Label className="w-32">
|
||||
Дайджест в
|
||||
{t("Дайджест в")}
|
||||
<Input type="time" name="digestTime" defaultValue={prefs.digestTime} />
|
||||
</Label>
|
||||
<TimezoneField value={prefs.timezone} />
|
||||
</div>
|
||||
<p className="m-0 text-sm text-muted-foreground">
|
||||
Сводка за сутки по вашим проектам: сделано, в работе, на ревью, ждёт вас, зависло, лимиты. Пустая не приходит. В боте — команда /digest.
|
||||
{t("Сводка за сутки по вашим проектам: сделано, в работе, на ревью, ждёт вас, зависло, лимиты. Пустая не приходит. В боте — команда /digest.")}
|
||||
</p>
|
||||
<label className="flex items-center gap-2 text-sm">
|
||||
<input type="checkbox" name="sound" defaultChecked={prefs.sound} className="size-4 accent-primary" />
|
||||
Звук: сигнал в открытой вкладке при новом вопросе и звук у push
|
||||
{t("Звук: сигнал в открытой вкладке при новом вопросе и звук у push")}
|
||||
</label>
|
||||
</Card>
|
||||
{myProjects.length > 0 && (
|
||||
<Card>
|
||||
<div className="text-sm font-medium">Проекты</div>
|
||||
<p className="m-0 text-sm text-muted-foreground">Из снятых проектов уведомления не приходят (вопросы остаются в вебе).</p>
|
||||
<div className="text-sm font-medium">{t("Проекты")}</div>
|
||||
<p className="m-0 text-sm text-muted-foreground">{t("Из снятых проектов уведомления не приходят (вопросы остаются в вебе).")}</p>
|
||||
<div className="flex flex-wrap gap-x-5 gap-y-2">
|
||||
{myProjects.map((p) => (
|
||||
<label key={p.id} className="flex items-center gap-2 text-sm">
|
||||
@ -258,19 +268,19 @@ export default async function Settings({ searchParams }: { searchParams: Promise
|
||||
</div>
|
||||
</Card>
|
||||
)}
|
||||
<Button variant="default" className="self-start">Сохранить уведомления</Button>
|
||||
<Button variant="default" className="self-start">{t("Сохранить уведомления")}</Button>
|
||||
</form>
|
||||
</Section>
|
||||
<Section title="MCP для ChatGPT и других клиентов">
|
||||
<p className="m-0 text-sm">Адрес сервера — подключите его как MCP-коннектор с авторизацией OAuth. Клиент зарегистрируется сам, вы подтвердите доступ на экране Пеппы.</p>
|
||||
<Section title={t("MCP для ChatGPT и других клиентов")}>
|
||||
<p className="m-0 text-sm">{t("Адрес сервера — подключите его как MCP-коннектор с авторизацией OAuth. Клиент зарегистрируется сам, вы подтвердите доступ на экране Пеппы.")}</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>.
|
||||
{t("Как подключить и что спрашивать — в")} <a href="/help" className="text-primary">{t("Помощи")}</a>.
|
||||
</p>
|
||||
</Section>
|
||||
<Section title="Подключённые приложения">
|
||||
<Section title={t("Подключённые приложения")}>
|
||||
{apps.length === 0 ? (
|
||||
<Empty>Нет подключённых приложений.</Empty>
|
||||
<Empty>{t("Нет подключённых приложений.")}</Empty>
|
||||
) : (
|
||||
apps.map((a) => (
|
||||
<Row
|
||||
@ -279,11 +289,11 @@ export default async function Settings({ searchParams }: { searchParams: Promise
|
||||
actions={
|
||||
<form action={revokeConnectedApp}>
|
||||
<Hidden fields={{ clientId: a.clientId, ...back }} />
|
||||
<Button size="sm" variant="destructive">Отозвать</Button>
|
||||
<Button size="sm" variant="destructive">{t("Отозвать")}</Button>
|
||||
</form>
|
||||
}
|
||||
>
|
||||
с {a.since.toLocaleDateString("ru-RU")} · последний запрос {ago(a.lastUsedAt)}
|
||||
{t("с {date} · последний запрос {ago}", { date: a.since.toLocaleDateString(intlLocale(t.locale)), ago: ago(a.lastUsedAt, t) })}
|
||||
</Row>
|
||||
))
|
||||
)}
|
||||
|
||||
@ -7,6 +7,8 @@ import { revalidatePath } from "next/cache";
|
||||
import { redirect } from "next/navigation";
|
||||
import { asWebActor, requireUser } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
|
||||
const str = (f: FormData, k: string) => String(f.get(k) ?? "").trim();
|
||||
const ids = (f: FormData, k: string) => f.getAll(k).map(Number).filter((n) => Number.isInteger(n) && n > 0);
|
||||
@ -20,7 +22,8 @@ async function attempt(f: FormData, fn: () => Promise<string | void>): Promise<n
|
||||
await requireSuperadmin(db, user);
|
||||
target = (await fn()) || target;
|
||||
} catch (e) {
|
||||
const msg = e instanceof PeppaError ? e.message : `Ошибка: ${(e as Error).message}`;
|
||||
const t = await getT();
|
||||
const msg = e instanceof PeppaError ? t.text(e.message) : t("Ошибка: {message}", { message: (e as Error).message });
|
||||
const [path, query] = target.split("?");
|
||||
const params = new URLSearchParams(query);
|
||||
params.set("error", msg.slice(0, 300));
|
||||
@ -34,7 +37,7 @@ export async function addSubscriptionAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const provider = str(f, "provider") as SubscriptionProvider;
|
||||
if (!["claude", "codex", "opencode"].includes(provider)) throw new PeppaError("Неизвестный провайдер");
|
||||
if (!["claude", "codex", "opencode"].includes(provider)) throw new PeppaError(m("Неизвестный провайдер"));
|
||||
const s = await addSubscription(db, {
|
||||
provider,
|
||||
name: str(f, "name"),
|
||||
@ -80,7 +83,7 @@ export async function checkSubscriptionAction(f: FormData) {
|
||||
|
||||
export async function renameSubscription(f: FormData) {
|
||||
await attempt(f, async () => {
|
||||
if (!str(f, "name")) throw new PeppaError("Нужно название подписки");
|
||||
if (!str(f, "name")) throw new PeppaError(m("Нужно название подписки"));
|
||||
await updateSubscription(db, Number(str(f, "id")), { name: str(f, "name") });
|
||||
});
|
||||
}
|
||||
|
||||
@ -12,6 +12,8 @@ import { Input, Label, NativeSelect } from "@/components/ui/input";
|
||||
import { Workspace } from "@/components/Workspace";
|
||||
import { requireUser } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import { intlLocale, type Translator } from "@peppa/shared/i18n";
|
||||
import {
|
||||
addSubscriptionAction,
|
||||
cancelLoginAction,
|
||||
@ -24,77 +26,81 @@ import {
|
||||
updatePoolAction,
|
||||
} from "./actions";
|
||||
|
||||
export const metadata = { title: "Подписки — Пеппа" };
|
||||
|
||||
const hhmm = (d: Date) => d.toLocaleString("ru-RU", { day: "numeric", month: "short", hour: "2-digit", minute: "2-digit" });
|
||||
|
||||
function StatusOf({ s }: { s: SubscriptionView }) {
|
||||
if (s.status === "pending") return <Badge variant="info">ожидает входа</Badge>;
|
||||
if (s.status === "auth_error") return <Badge variant="danger">ошибка входа</Badge>;
|
||||
if (s.status === "limited" && !isUsable(s)) return <Badge variant="warn">лимит до {s.limitedUntil ? hhmm(s.limitedUntil) : "?"}</Badge>;
|
||||
return <Badge variant="ok">активна</Badge>;
|
||||
export async function generateMetadata() {
|
||||
const t = await getT();
|
||||
return { title: t("Подписки — Пеппа") };
|
||||
}
|
||||
|
||||
function LoginSteps({ s, login }: { s: SubscriptionView; login: PendingLogin }) {
|
||||
const hhmm = (d: Date, t: Translator) => d.toLocaleString(intlLocale(t.locale), { day: "numeric", month: "short", hour: "2-digit", minute: "2-digit" });
|
||||
|
||||
function StatusOf({ s, t }: { s: SubscriptionView; t: Translator }) {
|
||||
if (s.status === "pending") return <Badge variant="info">{t("ожидает входа")}</Badge>;
|
||||
if (s.status === "auth_error") return <Badge variant="danger">{t("ошибка входа")}</Badge>;
|
||||
if (s.status === "limited" && !isUsable(s)) return <Badge variant="warn">{t("лимит до {time}", { time: s.limitedUntil ? hhmm(s.limitedUntil, t) : "?" })}</Badge>;
|
||||
return <Badge variant="ok">{t("активна")}</Badge>;
|
||||
}
|
||||
|
||||
function LoginSteps({ s, login, t }: { s: SubscriptionView; login: PendingLogin; t: Translator }) {
|
||||
return (
|
||||
<div className="flex flex-col gap-2 rounded-md border bg-background/40 p-3">
|
||||
{login.kind === "claude" ? (
|
||||
<>
|
||||
<p className="m-0 text-sm">1. Откройте ссылку на любом устройстве и войдите в аккаунт Claude с подпиской:</p>
|
||||
<p className="m-0 text-sm">{t("1. Откройте ссылку на любом устройстве и войдите в аккаунт Claude с подпиской:")}</p>
|
||||
<Button asChild variant="default" size="sm" className="self-start">
|
||||
<a href={login.url} target="_blank" rel="noreferrer">
|
||||
Войти в Claude <ExternalLink />
|
||||
{t("Войти в Claude")} <ExternalLink />
|
||||
</a>
|
||||
</Button>
|
||||
<p className="m-0 text-sm">2. Claude покажет код — вставьте его сюда:</p>
|
||||
<p className="m-0 text-sm">{t("2. Claude покажет код — вставьте его сюда:")}</p>
|
||||
<form action={submitLoginCode} className="flex gap-2">
|
||||
<Hidden fields={{ id: s.id }} />
|
||||
<Input name="code" placeholder="Код из Claude" aria-label="Код из Claude" autoComplete="off" required className="font-mono" />
|
||||
<Button variant="default">Подключить</Button>
|
||||
<Input name="code" placeholder={t("Код из Claude")} aria-label={t("Код из Claude")} autoComplete="off" required className="font-mono" />
|
||||
<Button variant="default">{t("Подключить")}</Button>
|
||||
</form>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<p className="m-0 text-sm">1. Откройте ссылку на любом устройстве и войдите в ChatGPT:</p>
|
||||
<p className="m-0 text-sm">{t("1. Откройте ссылку на любом устройстве и войдите в ChatGPT:")}</p>
|
||||
<Button asChild variant="default" size="sm" className="self-start">
|
||||
<a href={login.url} target="_blank" rel="noreferrer">
|
||||
{login.url} <ExternalLink />
|
||||
</a>
|
||||
</Button>
|
||||
<p className="m-0 text-sm">
|
||||
2. Введите одноразовый код: <span className="rounded bg-muted px-2 py-0.5 font-mono text-base font-semibold tracking-wider">{login.code}</span>
|
||||
{t("2. Введите одноразовый код:")} <span className="rounded bg-muted px-2 py-0.5 font-mono text-base font-semibold tracking-wider">{login.code}</span>
|
||||
</p>
|
||||
<p className="m-0 text-xs text-muted-foreground">Страница обновится сама, когда Codex подтвердит вход.</p>
|
||||
<p className="m-0 text-xs text-muted-foreground">{t("Страница обновится сама, когда Codex подтвердит вход.")}</p>
|
||||
</>
|
||||
)}
|
||||
<form action={cancelLoginAction}>
|
||||
<Hidden fields={{ id: s.id }} />
|
||||
<Button variant="link" size="sm" className="px-0 text-muted-foreground">Отменить вход</Button>
|
||||
<Button variant="link" size="sm" className="px-0 text-muted-foreground">{t("Отменить вход")}</Button>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SubscriptionCard({ s, login, pools }: { s: SubscriptionView; login: PendingLogin | null; pools: Map<number, string> }) {
|
||||
function SubscriptionCard({ s, login, pools, t }: { s: SubscriptionView; login: PendingLogin | null; pools: Map<number, string>; t: Translator }) {
|
||||
return (
|
||||
<Card id={`s-${s.id}`} className="gap-2">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Badge variant="outline">{PROVIDER_NAMES[s.provider]}</Badge>
|
||||
<span className="font-medium">{s.name}</span>
|
||||
<StatusOf s={s} />
|
||||
<StatusOf s={s} t={t} />
|
||||
<span className="ml-auto text-xs text-muted-foreground">
|
||||
сессий сейчас: <span className="font-mono text-foreground tabular-nums">{s.activeSessions}</span>
|
||||
{t("сессий сейчас:")} <span className="font-mono text-foreground tabular-nums">{s.activeSessions}</span>
|
||||
{s.projectSessions.length > 0 && <> ({s.projectSessions.map((p) => `${p.key}${p.n > 1 ? ` ×${p.n}` : ""}`).join(", ")})</>}
|
||||
</span>
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{s.authKind === "api_key" ? `API-ключ${s.keyProvider ? ` ${s.keyProvider}` : ""}` : s.authKind === "device" ? "вход ChatGPT" : "токен Claude"}
|
||||
{" · "}добавил {s.createdByLogin ?? "—"} {ago(s.createdAt)}
|
||||
{s.checkedAt && <> · проверена {ago(s.checkedAt)}</>}
|
||||
{s.poolIds.length > 0 && <> · пулы: {s.poolIds.map((id) => pools.get(id)).filter(Boolean).join(", ")}</>}
|
||||
{s.authKind === "api_key" ? (s.keyProvider ? t("API-ключ {provider}", { provider: s.keyProvider }) : t("API-ключ")) : s.authKind === "device" ? t("вход ChatGPT") : t("токен Claude")}
|
||||
{" · "}
|
||||
{t("добавил {login} {ago}", { login: s.createdByLogin ?? "—", ago: ago(s.createdAt, t) })}
|
||||
{s.checkedAt && <> · {t("проверена {ago}", { ago: ago(s.checkedAt, t) })}</>}
|
||||
{s.poolIds.length > 0 && <> · {t("пулы: {names}", { names: s.poolIds.map((id) => pools.get(id)).filter(Boolean).join(", ") })}</>}
|
||||
</div>
|
||||
{s.lastError && s.status !== "active" && <p className="m-0 font-mono text-xs [overflow-wrap:anywhere] text-destructive">{s.lastError}</p>}
|
||||
{login && <LoginSteps s={s} login={login} />}
|
||||
{login && <LoginSteps s={s} login={login} t={t} />}
|
||||
{!login && (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{s.status !== "pending" && (
|
||||
@ -102,21 +108,21 @@ function SubscriptionCard({ s, login, pools }: { s: SubscriptionView; login: Pen
|
||||
<Hidden fields={{ id: s.id }} />
|
||||
<Button size="sm">
|
||||
<RefreshCw />
|
||||
Проверить
|
||||
{t("Проверить")}
|
||||
</Button>
|
||||
</form>
|
||||
)}
|
||||
{(s.provider === "claude" || (s.provider === "codex" && s.authKind === "device")) && (
|
||||
<form action={reconnectSubscription}>
|
||||
<Hidden fields={{ id: s.id, provider: s.provider }} />
|
||||
<Button size="sm" variant="outline">{s.status === "pending" ? "Войти" : "Переподключить"}</Button>
|
||||
<Button size="sm" variant="outline">{s.status === "pending" ? t("Войти") : t("Переподключить")}</Button>
|
||||
</form>
|
||||
)}
|
||||
<form action={deleteSubscriptionAction}>
|
||||
<Hidden fields={{ id: s.id }} />
|
||||
<Button size="sm" variant="destructive" title="Удалить подписку">
|
||||
<Button size="sm" variant="destructive" title={t("Удалить подписку")}>
|
||||
<Trash2 />
|
||||
Удалить
|
||||
{t("Удалить")}
|
||||
</Button>
|
||||
</form>
|
||||
</div>
|
||||
@ -125,9 +131,9 @@ function SubscriptionCard({ s, login, pools }: { s: SubscriptionView; login: Pen
|
||||
);
|
||||
}
|
||||
|
||||
function SubscriptionChecks({ subs, checked }: { subs: SubscriptionView[]; checked: number[] }) {
|
||||
function SubscriptionChecks({ subs, checked, t }: { subs: SubscriptionView[]; checked: number[]; t: Translator }) {
|
||||
return subs.length === 0 ? (
|
||||
<p className="m-0 text-sm text-muted-foreground">Сначала добавьте подписки.</p>
|
||||
<p className="m-0 text-sm text-muted-foreground">{t("Сначала добавьте подписки.")}</p>
|
||||
) : (
|
||||
<div className="flex flex-col gap-1">
|
||||
{subs.map((s) => (
|
||||
@ -140,12 +146,12 @@ function SubscriptionChecks({ subs, checked }: { subs: SubscriptionView[]; check
|
||||
);
|
||||
}
|
||||
|
||||
function AddForm({ provider, children }: { provider: string; children: React.ReactNode }) {
|
||||
function AddForm({ provider, children, t }: { provider: string; children: React.ReactNode; t: Translator }) {
|
||||
return (
|
||||
<form action={addSubscriptionAction} className="flex flex-col gap-3">
|
||||
<Hidden fields={{ provider }} />
|
||||
<Label>
|
||||
Название
|
||||
{t("Название")}
|
||||
<Input name="name" required placeholder={provider === "claude" ? "Claude Max — asel" : provider === "codex" ? "ChatGPT Pro — asel" : "OpenCode — Anthropic"} />
|
||||
</Label>
|
||||
{children}
|
||||
@ -157,6 +163,7 @@ type Params = { error?: string; login?: string; added?: string };
|
||||
|
||||
export default async function Subscriptions({ searchParams }: { searchParams: Promise<Params> }) {
|
||||
const user = await requireUser();
|
||||
const t = await getT();
|
||||
if (!(await isSuperadmin(db, user))) notFound();
|
||||
const { error, added } = await searchParams;
|
||||
let subs = await listSubscriptions(db);
|
||||
@ -178,81 +185,81 @@ export default async function Subscriptions({ searchParams }: { searchParams: Pr
|
||||
{[...logins.values()].some((l) => l.kind === "codex") && <AutoRefresh everyMs={3000} />}
|
||||
<div className="max-w-3xl">
|
||||
<Flash error={error} />
|
||||
<PageHeader title={<><KeyRound className="mr-1 inline size-5 text-primary" />Подписки</>}>
|
||||
Аккаунты, на которых работают агенты, и пулы для ротации. Раннер берёт свободную активную подписку из пула проекта или из выбранных при запуске, а при лимите переключается на другую свободную подписку пула. Раздел видят только суперадмины.
|
||||
<PageHeader title={<><KeyRound className="mr-1 inline size-5 text-primary" />{t("Подписки")}</>}>
|
||||
{t("Аккаунты, на которых работают агенты, и пулы для ротации. Раннер берёт свободную активную подписку из пула проекта или из выбранных при запуске, а при лимите переключается на другую свободную подписку пула. Раздел видят только суперадмины.")}
|
||||
</PageHeader>
|
||||
{addedSub && <Notice>Подписка «{addedSub.name}» добавлена{addedSub.status === "active" ? " и активна" : ""}</Notice>}
|
||||
{addedSub && <Notice>{addedSub.status === "active" ? t("Подписка «{name}» добавлена и активна", { name: addedSub.name }) : t("Подписка «{name}» добавлена", { name: addedSub.name })}</Notice>}
|
||||
|
||||
<Section title="Подписки" count={subs.length}>
|
||||
{subs.length === 0 ? <Empty>Подписок пока нет — добавьте первую ниже.</Empty> : subs.map((s) => <SubscriptionCard key={s.id} s={s} login={logins.get(s.id) ?? null} pools={poolNames} />)}
|
||||
<Section title={t("Подписки")} count={subs.length}>
|
||||
{subs.length === 0 ? <Empty>{t("Подписок пока нет — добавьте первую ниже.")}</Empty> : subs.map((s) => <SubscriptionCard key={s.id} s={s} login={logins.get(s.id) ?? null} pools={poolNames} t={t} />)}
|
||||
<div className="grid gap-2 md:grid-cols-3">
|
||||
<Disclosure summary={<span className="flex items-center gap-1.5"><Plus className="size-4" />Claude Code</span>}>
|
||||
<AddForm provider="claude">
|
||||
<NativeSelect name="method" defaultValue="login" aria-label="Способ входа">
|
||||
<option value="login">Войти по ссылке (claude setup-token)</option>
|
||||
<option value="token">Вставить готовый токен</option>
|
||||
<AddForm provider="claude" t={t}>
|
||||
<NativeSelect name="method" defaultValue="login" aria-label={t("Способ входа")}>
|
||||
<option value="login">{t("Войти по ссылке (claude setup-token)")}</option>
|
||||
<option value="token">{t("Вставить готовый токен")}</option>
|
||||
</NativeSelect>
|
||||
<Input name="secret" type="password" placeholder="sk-ant-oat… (только для готового токена)" autoComplete="off" aria-label="Токен" />
|
||||
<Button variant="default" className="self-start">Добавить</Button>
|
||||
<Input name="secret" type="password" placeholder={t("sk-ant-oat… (только для готового токена)")} autoComplete="off" aria-label={t("Токен")} />
|
||||
<Button variant="default" className="self-start">{t("Добавить")}</Button>
|
||||
</AddForm>
|
||||
</Disclosure>
|
||||
<Disclosure summary={<span className="flex items-center gap-1.5"><Plus className="size-4" />Codex</span>}>
|
||||
<AddForm provider="codex">
|
||||
<NativeSelect name="method" defaultValue="device" aria-label="Способ входа">
|
||||
<option value="device">Подписка ChatGPT (ссылка + код)</option>
|
||||
<option value="api_key">API-ключ OpenAI</option>
|
||||
<AddForm provider="codex" t={t}>
|
||||
<NativeSelect name="method" defaultValue="device" aria-label={t("Способ входа")}>
|
||||
<option value="device">{t("Подписка ChatGPT (ссылка + код)")}</option>
|
||||
<option value="api_key">{t("API-ключ OpenAI")}</option>
|
||||
</NativeSelect>
|
||||
<Input name="secret" type="password" placeholder="sk-… (только для API-ключа)" autoComplete="off" aria-label="API-ключ" />
|
||||
<Button variant="default" className="self-start">Добавить</Button>
|
||||
<Input name="secret" type="password" placeholder={t("sk-… (только для API-ключа)")} autoComplete="off" aria-label={t("API-ключ")} />
|
||||
<Button variant="default" className="self-start">{t("Добавить")}</Button>
|
||||
</AddForm>
|
||||
</Disclosure>
|
||||
<Disclosure summary={<span className="flex items-center gap-1.5"><Plus className="size-4" />OpenCode</span>}>
|
||||
<AddForm provider="opencode">
|
||||
<AddForm provider="opencode" t={t}>
|
||||
<input type="hidden" name="method" value="api_key" />
|
||||
<NativeSelect name="keyProvider" defaultValue="anthropic" aria-label="Провайдер ключа">
|
||||
<NativeSelect name="keyProvider" defaultValue="anthropic" aria-label={t("Провайдер ключа")}>
|
||||
{Object.keys(OPENCODE_KEY_ENV).map((k) => (
|
||||
<option key={k} value={k}>{k}</option>
|
||||
))}
|
||||
</NativeSelect>
|
||||
<Input name="secret" type="password" required placeholder="Ключ провайдера" autoComplete="off" aria-label="Ключ" />
|
||||
<Button variant="default" className="self-start">Добавить</Button>
|
||||
<Input name="secret" type="password" required placeholder={t("Ключ провайдера")} autoComplete="off" aria-label={t("Ключ")} />
|
||||
<Button variant="default" className="self-start">{t("Добавить")}</Button>
|
||||
</AddForm>
|
||||
</Disclosure>
|
||||
</div>
|
||||
</Section>
|
||||
|
||||
<Section title="Пулы" count={pools.length} id="pools">
|
||||
{pools.length === 0 && <Empty>Пулов нет. Пул — набор подписок, который назначается проекту по умолчанию.</Empty>}
|
||||
<Section title={t("Пулы")} count={pools.length} id="pools">
|
||||
{pools.length === 0 && <Empty>{t("Пулов нет. Пул — набор подписок, который назначается проекту по умолчанию.")}</Empty>}
|
||||
{pools.map((p) => (
|
||||
<Card key={p.id} className="gap-3">
|
||||
<form action={updatePoolAction} className="flex flex-col gap-3">
|
||||
<Hidden fields={{ id: p.id }} />
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Input name="name" defaultValue={p.name} aria-label="Название пула" className="max-w-xs font-medium" />
|
||||
<Input name="name" defaultValue={p.name} aria-label={t("Название пула")} className="max-w-xs font-medium" />
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{p.projectKeys.length ? `по умолчанию у ${p.projectKeys.join(", ")}` : "не назначен проектам"}
|
||||
{p.projectKeys.length ? t("по умолчанию у {keys}", { keys: p.projectKeys.join(", ") }) : t("не назначен проектам")}
|
||||
</span>
|
||||
</div>
|
||||
<SubscriptionChecks subs={subs} checked={p.subscriptionIds} />
|
||||
<Button size="sm" className="self-start">Сохранить</Button>
|
||||
<SubscriptionChecks subs={subs} checked={p.subscriptionIds} t={t} />
|
||||
<Button size="sm" className="self-start">{t("Сохранить")}</Button>
|
||||
</form>
|
||||
<form action={deletePoolAction}>
|
||||
<Hidden fields={{ id: p.id }} />
|
||||
<Button size="sm" variant="link" className="px-0 text-destructive">Удалить пул</Button>
|
||||
<Button size="sm" variant="link" className="px-0 text-destructive">{t("Удалить пул")}</Button>
|
||||
</form>
|
||||
</Card>
|
||||
))}
|
||||
<Disclosure summary={<span className="flex items-center gap-1.5"><Plus className="size-4" />Новый пул</span>}>
|
||||
<Disclosure summary={<span className="flex items-center gap-1.5"><Plus className="size-4" />{t("Новый пул")}</span>}>
|
||||
<form action={createPoolAction} className="flex flex-col gap-3">
|
||||
<Label>
|
||||
Название
|
||||
<Input name="name" required placeholder="Основной" />
|
||||
{t("Название")}
|
||||
<Input name="name" required placeholder={t("Основной")} />
|
||||
</Label>
|
||||
<SubscriptionChecks subs={subs} checked={[]} />
|
||||
<Button variant="default" className="self-start">Создать пул</Button>
|
||||
<SubscriptionChecks subs={subs} checked={[]} t={t} />
|
||||
<Button variant="default" className="self-start">{t("Создать пул")}</Button>
|
||||
</form>
|
||||
</Disclosure>
|
||||
<p className="m-0 text-xs text-muted-foreground">Пул проекта по умолчанию выбирается в «⋯ Настройки проекта».</p>
|
||||
<p className="m-0 text-xs text-muted-foreground">{t("Пул проекта по умолчанию выбирается в «⋯ Настройки проекта».")}</p>
|
||||
</Section>
|
||||
</div>
|
||||
</Workspace>
|
||||
|
||||
@ -54,6 +54,7 @@ import { requireUser } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { taskActivity, taskForUser } from "@/lib/queries";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import { editStoryAction, saveTaskBudgetAction, startTaskSession } from "../../actions";
|
||||
import { BudgetPanel } from "@/components/Accounting";
|
||||
import { ActivityTab, ArtifactTab, CommentsTab, MergeTab, ProgressBar, SpecsTab, STORY_TABS, TasksTab, TestsTab, type CheckRunRow, type StoryTab } from "./tabs";
|
||||
@ -69,6 +70,7 @@ async function gateWithTimeout(ref: Parameters<typeof prGate>[0]): Promise<GateR
|
||||
|
||||
export default async function StoryPage({ params, searchParams }: { params: Promise<{ key: string }>; searchParams: Promise<{ error?: string; tab?: string; edit?: string }> }) {
|
||||
const user = await requireUser();
|
||||
const t = await getT();
|
||||
const { key } = await params;
|
||||
const sp = await searchParams;
|
||||
const ref = await taskForUser(user.id, decodeURIComponent(key)).catch(() => null);
|
||||
@ -87,7 +89,7 @@ export default async function StoryPage({ params, searchParams }: { params: Prom
|
||||
const review = await latestReview(db, task.id);
|
||||
const epics = await listEpics(db, project.id);
|
||||
const epic = task.goalId ? (epics.find((e) => e.id === task.goalId) ?? (await getEpic(db, project.id, task.goalId).catch(() => null))) : null;
|
||||
const tab: StoryTab = STORY_TABS.find((t) => t.id === sp.tab)?.id ?? (change ? "proposal" : "comments");
|
||||
const tab: StoryTab = STORY_TABS.find((x) => x.id === sp.tab)?.id ?? (change ? "proposal" : "comments");
|
||||
const tabHref = (id: StoryTab) => `/t/${ref.key}?tab=${id}`;
|
||||
const back = tabHref(tab);
|
||||
const preview = await reviewPreview(db, ref);
|
||||
@ -122,11 +124,11 @@ export default async function StoryPage({ params, searchParams }: { params: Prom
|
||||
const aside = (
|
||||
<div className="flex flex-col gap-6">
|
||||
<ReviewPreview preview={preview} />
|
||||
<PanelSection title="Расход и бюджет">
|
||||
<PanelSection title={t("Расход и бюджет")}>
|
||||
<BudgetPanel view={budget} taskId={task.id} projectBudget={projectBudget} back={back} action={saveTaskBudgetAction} paused={!!budget.paused} />
|
||||
</PanelSection>
|
||||
<PanelSection title="Зависимости">
|
||||
{blockers.length === 0 && dependents.length === 0 && <p className="m-0 text-sm text-muted-foreground">Стори ни от чего не зависит.</p>}
|
||||
<PanelSection title={t("Зависимости")}>
|
||||
{blockers.length === 0 && dependents.length === 0 && <p className="m-0 text-sm text-muted-foreground">{t("Стори ни от чего не зависит.")}</p>}
|
||||
{blockers.length > 0 && (
|
||||
<ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm">
|
||||
{blockers.map((b) => (
|
||||
@ -139,7 +141,7 @@ export default async function StoryPage({ params, searchParams }: { params: Prom
|
||||
<form action={setDependenciesAction}>
|
||||
<Hidden fields={{ taskKey: ref.key, back, remove: b.key }} />
|
||||
{blockers.map((x) => <input key={x.id} type="hidden" name="current" value={x.key} />)}
|
||||
<button type="submit" title={`Убрать зависимость от ${b.key}`} aria-label={`Убрать зависимость от ${b.key}`} className="rounded p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground">
|
||||
<button type="submit" title={t("Убрать зависимость от {key}", { key: b.key })} aria-label={t("Убрать зависимость от {key}", { key: b.key })} className="rounded p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground">
|
||||
<X className="size-3.5" />
|
||||
</button>
|
||||
</form>
|
||||
@ -147,16 +149,16 @@ export default async function StoryPage({ params, searchParams }: { params: Prom
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
{blockers.some((b) => b.open) && <p className="m-0 text-xs text-muted-foreground">Диспетчер не возьмёт стори, пока предшественники не в ревью или готово.</p>}
|
||||
{blockers.some((b) => b.open) && <p className="m-0 text-xs text-muted-foreground">{t("Диспетчер не возьмёт стори, пока предшественники не в ревью или готово.")}</p>}
|
||||
<form action={setDependenciesAction} className="flex gap-2">
|
||||
<Hidden fields={{ taskKey: ref.key, back }} />
|
||||
{blockers.map((x) => <input key={x.id} type="hidden" name="current" value={x.key} />)}
|
||||
<Input name="blockedBy" required placeholder={`Ждёт стори: ${project.key}-3`} aria-label="Добавить зависимость" className="h-8" />
|
||||
<Button size="sm" variant="outline">Добавить</Button>
|
||||
<Input name="blockedBy" required placeholder={t("Ждёт стори: {key}", { key: `${project.key}-3` })} aria-label={t("Добавить зависимость")} className="h-8" />
|
||||
<Button size="sm" variant="outline">{t("Добавить")}</Button>
|
||||
</form>
|
||||
{dependents.length > 0 && (
|
||||
<p className="m-0 text-sm">
|
||||
<span className="text-muted-foreground">Её ждут: </span>
|
||||
<span className="text-muted-foreground">{t("Её ждут:")} </span>
|
||||
{dependents.map((d, i) => (
|
||||
<span key={d.id}>
|
||||
{i > 0 && ", "}
|
||||
@ -166,30 +168,30 @@ export default async function StoryPage({ params, searchParams }: { params: Prom
|
||||
</p>
|
||||
)}
|
||||
</PanelSection>
|
||||
<PanelSection title="Проверки">
|
||||
<PanelSection title={t("Проверки")}>
|
||||
<Link href={tabHref("tests")} className="flex flex-wrap items-center gap-2 text-sm text-foreground hover:no-underline">
|
||||
{CI_ICON[ci.state as keyof typeof CI_ICON]}
|
||||
{ci.label}
|
||||
{t.text(ci.label)}
|
||||
{ci.sha && <span className="font-mono text-xs text-muted-foreground">{ci.sha.slice(0, 7)}</span>}
|
||||
</Link>
|
||||
{task.ciAttempts > 0 && <p className="m-0 text-xs text-muted-foreground">красных подряд: {task.ciAttempts}</p>}
|
||||
{task.ciAttempts > 0 && <p className="m-0 text-xs text-muted-foreground">{t("красных подряд: {n}", { n: task.ciAttempts })}</p>}
|
||||
</PanelSection>
|
||||
{review && (
|
||||
<PanelSection title="Ревьюер">
|
||||
<p className="m-0 text-sm [overflow-wrap:anywhere]">{reviewLabel(review)}</p>
|
||||
<PanelSection title={t("Ревьюер")}>
|
||||
<p className="m-0 text-sm [overflow-wrap:anywhere]">{t.text(reviewLabel(review))}</p>
|
||||
<p className="m-0 text-xs text-muted-foreground">
|
||||
{review.sha.slice(0, 7)} · {ago(review.updatedAt)}
|
||||
</p>
|
||||
</PanelSection>
|
||||
)}
|
||||
<PanelSection title="Последнее">
|
||||
<PanelSection title={t("Последнее")}>
|
||||
{events.length === 0 ? (
|
||||
<p className="m-0 text-sm text-muted-foreground">Событий нет.</p>
|
||||
<p className="m-0 text-sm text-muted-foreground">{t("Событий нет.")}</p>
|
||||
) : (
|
||||
<>
|
||||
<ActivityTab events={events.slice(0, 8)} authors={authors} />
|
||||
<Link href={tabHref("activity")} className="text-xs text-primary">
|
||||
Вся активность →
|
||||
{t("Вся активность →")}
|
||||
</Link>
|
||||
</>
|
||||
)}
|
||||
@ -208,8 +210,8 @@ export default async function StoryPage({ params, searchParams }: { params: Prom
|
||||
{epic && (
|
||||
<>
|
||||
<span className="text-muted-foreground">/</span>
|
||||
<Link href={`/p/${project.key}?epic=${epic.id}`} title="Эпик" className="text-muted-foreground hover:text-foreground">
|
||||
эпик «{epic.title}»
|
||||
<Link href={`/p/${project.key}?epic=${epic.id}`} title={t("Эпик")} className="text-muted-foreground hover:text-foreground">
|
||||
{t("эпик «{title}»", { title: epic.title })}
|
||||
</Link>
|
||||
</>
|
||||
)}
|
||||
@ -218,7 +220,7 @@ export default async function StoryPage({ params, searchParams }: { params: Prom
|
||||
title={
|
||||
<>
|
||||
<span className="font-mono text-primary">{ref.key}</span> {task.title} <StatusBadge status={task.status} />
|
||||
{task.archivedAt && <Badge variant="muted" className="ml-1.5 align-middle">в архиве</Badge>}
|
||||
{task.archivedAt && <Badge variant="muted" className="ml-1.5 align-middle">{t("в архиве")}</Badge>}
|
||||
</>
|
||||
}
|
||||
actions={
|
||||
@ -226,7 +228,7 @@ export default async function StoryPage({ params, searchParams }: { params: Prom
|
||||
<Button asChild size="sm" variant="outline">
|
||||
<Link href={sp.edit ? back : `${back}&edit=1`} scroll={false}>
|
||||
<Pencil />
|
||||
Изменить
|
||||
{t("Изменить")}
|
||||
</Link>
|
||||
</Button>
|
||||
{task.prUrl && (
|
||||
@ -239,8 +241,8 @@ export default async function StoryPage({ params, searchParams }: { params: Prom
|
||||
)}
|
||||
<form action={archiveTaskAction}>
|
||||
<Hidden fields={{ taskKey: ref.key, back, archived: task.archivedAt ? "0" : "1" }} />
|
||||
<Button size="sm" variant="ghost" title={task.archivedAt ? "Вернуть стори на доску (в конец)" : "Убрать с доски; агент остановится, история останется"}>
|
||||
{task.archivedAt ? <><ArchiveRestore />Вернуть</> : <><Archive />В архив</>}
|
||||
<Button size="sm" variant="ghost" title={task.archivedAt ? t("Вернуть стори на доску (в конец)") : t("Убрать с доски; агент остановится, история останется")}>
|
||||
{task.archivedAt ? <><ArchiveRestore />{t("Вернуть")}</> : <><Archive />{t("В архив")}</>}
|
||||
</Button>
|
||||
</form>
|
||||
</>
|
||||
@ -250,10 +252,10 @@ export default async function StoryPage({ params, searchParams }: { params: Prom
|
||||
{task.openspecChange ? (
|
||||
<span className="font-mono text-xs">
|
||||
{task.openspecChange}
|
||||
{change?.archived && <span className="ml-1 rounded bg-muted px-1">в архиве</span>}
|
||||
{change?.archived && <span className="ml-1 rounded bg-muted px-1">{t("в архиве")}</span>}
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-xs">change ещё нет</span>
|
||||
<span className="text-xs">{t("change ещё нет")}</span>
|
||||
)}
|
||||
{progress?.total ? (
|
||||
<span className="w-56 max-w-full">
|
||||
@ -265,9 +267,9 @@ export default async function StoryPage({ params, searchParams }: { params: Prom
|
||||
|
||||
{refining && (
|
||||
<p role="status" className="mb-4 flex flex-wrap items-center gap-2 rounded-lg border border-info/40 bg-info/10 px-4 py-3 text-sm">
|
||||
<span className="font-medium">{refining === "waiting" ? "Аналитик ждёт ваших ответов" : "Продакт и аналитик уточняют задачу"}</span>
|
||||
<span className="font-medium">{refining === "waiting" ? t("Аналитик ждёт ваших ответов") : t("Продакт и аналитик уточняют задачу")}</span>
|
||||
<span className="text-muted-foreground">
|
||||
{refining === "waiting" ? "— вопрос во вкладке «Comments». Не ответите — возьмёт варианты по умолчанию и отдаст стори в работу." : "— через минуту здесь появятся критерии приёмки. Агент-разработчик возьмёт стори после этого."}
|
||||
{refining === "waiting" ? t("— вопрос во вкладке «Comments». Не ответите — возьмёт варианты по умолчанию и отдаст стори в работу.") : t("— через минуту здесь появятся критерии приёмки. Агент-разработчик возьмёт стори после этого.")}
|
||||
</span>
|
||||
</p>
|
||||
)}
|
||||
@ -275,46 +277,46 @@ export default async function StoryPage({ params, searchParams }: { params: Prom
|
||||
<form action={editStoryAction} className="flex flex-col gap-2 rounded-lg border bg-card p-4">
|
||||
<Hidden fields={{ taskKey: ref.key, back }} />
|
||||
<label className="flex flex-col gap-1 text-sm">
|
||||
Название
|
||||
{t("Название")}
|
||||
<Input name="title" defaultValue={task.title} required minLength={2} />
|
||||
</label>
|
||||
<label className="flex flex-col gap-1 text-sm">
|
||||
Описание
|
||||
{t("Описание")}
|
||||
<Textarea name="description" defaultValue={task.description ?? ""} rows={6} />
|
||||
</label>
|
||||
<label className="flex flex-col gap-1 text-sm">
|
||||
Эпик
|
||||
{t("Эпик")}
|
||||
<NativeSelect name="epicId" defaultValue={task.goalId ?? ""} className="w-auto">
|
||||
<option value="">Без эпика</option>
|
||||
<option value="">{t("Без эпика")}</option>
|
||||
{epics.map((e) => (
|
||||
<option key={e.id} value={e.id}>{e.title}</option>
|
||||
))}
|
||||
{epic && !epics.some((e) => e.id === epic.id) && <option value={epic.id}>{epic.title} (в архиве)</option>}
|
||||
{epic && !epics.some((e) => e.id === epic.id) && <option value={epic.id}>{t("{title} (в архиве)", { title: epic.title })}</option>}
|
||||
</NativeSelect>
|
||||
</label>
|
||||
<div className="flex gap-2">
|
||||
<Button size="sm">Сохранить</Button>
|
||||
<Button size="sm">{t("Сохранить")}</Button>
|
||||
<Button asChild size="sm" variant="ghost">
|
||||
<Link href={back} scroll={false}>Отмена</Link>
|
||||
<Link href={back} scroll={false}>{t("Отмена")}</Link>
|
||||
</Button>
|
||||
</div>
|
||||
<p className="m-0 text-xs text-muted-foreground">Агент не запускается; изменение попадёт в Activity.</p>
|
||||
<p className="m-0 text-xs text-muted-foreground">{t("Агент не запускается; изменение попадёт в Activity.")}</p>
|
||||
</form>
|
||||
) : (
|
||||
<Disclosure open={!change} summary={<span className="text-sm font-medium">Описание</span>}>
|
||||
<Disclosure open={!change} summary={<span className="text-sm font-medium">{t("Описание")}</span>}>
|
||||
{/* PEP-84: the analyst writes the story in Markdown (criteria, out of scope, assumptions). */}
|
||||
{task.description && /^## /m.test(task.description) ? (
|
||||
<Markdown text={task.description} className="text-sm" />
|
||||
) : (
|
||||
<div className="text-sm whitespace-pre-wrap [overflow-wrap:anywhere]">{task.description || <span className="text-muted-foreground">Без описания</span>}</div>
|
||||
<div className="text-sm whitespace-pre-wrap [overflow-wrap:anywhere]">{task.description || <span className="text-muted-foreground">{t("Без описания")}</span>}</div>
|
||||
)}
|
||||
</Disclosure>
|
||||
)}
|
||||
|
||||
<Section title="Агент" count={sessions.length || undefined}>
|
||||
<Section title={t("Агент")} count={sessions.length || undefined}>
|
||||
{progress?.current && live && (
|
||||
<p className="m-0 text-sm">
|
||||
<span className="text-muted-foreground">Сейчас по tasks.md:</span> {progress.current}
|
||||
<span className="text-muted-foreground">{t("Сейчас по tasks.md:")}</span> {progress.current}
|
||||
</p>
|
||||
)}
|
||||
<TaskRunnerSettings taskKey={ref.key} own={runnerOwn} inherited={runnerProject} back={back} />
|
||||
@ -325,45 +327,45 @@ export default async function StoryPage({ params, searchParams }: { params: Prom
|
||||
) : (
|
||||
<form action={startTaskSession} className="flex flex-wrap gap-2">
|
||||
<Hidden fields={{ taskKey: ref.key, back }} />
|
||||
<NativeSelect name="provider" defaultValue="" aria-label="Агент" className="w-auto">
|
||||
<option value="">{pool || superadmin ? "Любой агент" : "Claude Code"}</option>
|
||||
<NativeSelect name="provider" defaultValue="" aria-label={t("Агент")} className="w-auto">
|
||||
<option value="">{pool || superadmin ? t("Любой агент") : "Claude Code"}</option>
|
||||
<option value="claude">Claude Code</option>
|
||||
<option value="codex">Codex</option>
|
||||
<option value="opencode">OpenCode</option>
|
||||
</NativeSelect>
|
||||
{superadmin && (
|
||||
<NativeSelect name="choice" defaultValue="" aria-label="Подписки" className="w-auto">
|
||||
<option value="">{pool ? `Пул проекта: ${pool.name}` : "Без пула (вход машины)"}</option>
|
||||
<NativeSelect name="choice" defaultValue="" aria-label={t("Подписки")} className="w-auto">
|
||||
<option value="">{pool ? t("Пул проекта: {name}", { name: pool.name }) : t("Без пула (вход машины)")}</option>
|
||||
{pools.filter((p) => p.id !== pool?.id).map((p) => (
|
||||
<option key={p.id} value={`pool:${p.id}`}>Пул: {p.name}</option>
|
||||
<option key={p.id} value={`pool:${p.id}`}>{t("Пул: {name}", { name: p.name })}</option>
|
||||
))}
|
||||
{subs.length > 0 && <option value="pick">Отмеченные подписки ↓</option>}
|
||||
{subs.length > 0 && <option value="pick">{t("Отмеченные подписки ↓")}</option>}
|
||||
</NativeSelect>
|
||||
)}
|
||||
<Input name="prompt" placeholder="Доп. инструкция (необязательно)" aria-label="Доп. инструкция" className="flex-[1_1_14rem]" />
|
||||
<Input name="prompt" placeholder={t("Доп. инструкция (необязательно)")} aria-label={t("Доп. инструкция")} className="flex-[1_1_14rem]" />
|
||||
<Button variant="default">
|
||||
<Play />
|
||||
Запустить агента
|
||||
{t("Запустить агента")}
|
||||
</Button>
|
||||
{superadmin && subs.length > 0 && (
|
||||
<details className="basis-full text-sm">
|
||||
<summary className="cursor-pointer text-muted-foreground">Отметить подписки (для «Отмеченные подписки»)</summary>
|
||||
<summary className="cursor-pointer text-muted-foreground">{t("Отметить подписки (для «Отмеченные подписки»)")}</summary>
|
||||
<div className="mt-2 flex flex-col gap-1">
|
||||
{subs.map((s) => (
|
||||
<label key={s.id} className="flex items-center gap-2">
|
||||
<input type="checkbox" name="subscription" value={s.id} className="size-4 accent-primary" />
|
||||
<span className="text-muted-foreground">{PROVIDER_NAMES[s.provider]}</span> {s.name}
|
||||
<span className="text-xs text-muted-foreground">· {s.status === "active" ? "активна" : s.status === "limited" ? "лимит" : s.status === "pending" ? "ожидает входа" : "ошибка входа"} · сессий {s.activeSessions}</span>
|
||||
<span className="text-xs text-muted-foreground">· {s.status === "active" ? t("активна") : s.status === "limited" ? t("лимит") : s.status === "pending" ? t("ожидает входа") : t("ошибка входа")} · {t("сессий {n}", { n: s.activeSessions })}</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</details>
|
||||
)}
|
||||
{!superadmin && pool && <p className="m-0 basis-full text-xs text-muted-foreground">Агент запустится на свободной подписке пула «{pool.name}».</p>}
|
||||
{!superadmin && pool && <p className="m-0 basis-full text-xs text-muted-foreground">{t("Агент запустится на свободной подписке пула «{name}».", { name: pool.name })}</p>}
|
||||
</form>
|
||||
)}
|
||||
{past.length > 0 && (
|
||||
<Disclosure summary={<span className="text-sm text-muted-foreground">Прошлые сессии: {past.length}</span>}>
|
||||
<Disclosure summary={<span className="text-sm text-muted-foreground">{t("Прошлые сессии: {n}", { n: past.length })}</span>}>
|
||||
<div className="flex flex-col gap-2">
|
||||
{past.map((s) => (
|
||||
<SessionCard key={s.id} s={s} back={back} />
|
||||
@ -373,20 +375,20 @@ export default async function StoryPage({ params, searchParams }: { params: Prom
|
||||
)}
|
||||
</Section>
|
||||
|
||||
<nav aria-label="Разделы стори" className="mt-2 flex gap-1 overflow-x-auto border-b">
|
||||
{STORY_TABS.map((t) => (
|
||||
<nav aria-label={t("Разделы стори")} className="mt-2 flex gap-1 overflow-x-auto border-b">
|
||||
{STORY_TABS.map((x) => (
|
||||
<Link
|
||||
key={t.id}
|
||||
href={tabHref(t.id)}
|
||||
key={x.id}
|
||||
href={tabHref(x.id)}
|
||||
scroll={false}
|
||||
aria-current={tab === t.id ? "page" : undefined}
|
||||
aria-current={tab === x.id ? "page" : undefined}
|
||||
className={cn(
|
||||
"-mb-px flex items-center gap-1.5 border-b-2 px-3 py-2 text-sm whitespace-nowrap text-muted-foreground hover:text-foreground hover:no-underline",
|
||||
tab === t.id ? "border-primary text-foreground" : "border-transparent",
|
||||
tab === x.id ? "border-primary text-foreground" : "border-transparent",
|
||||
)}
|
||||
>
|
||||
{t.label}
|
||||
{counts[t.id] != null && <span className={cn("rounded-full px-1.5 font-mono text-[11px] tabular-nums", t.id === "comments" ? "bg-primary/15 text-primary" : "bg-muted")}>{counts[t.id]}</span>}
|
||||
{t(x.label)}
|
||||
{counts[x.id] != null && <span className={cn("rounded-full px-1.5 font-mono text-[11px] tabular-nums", x.id === "comments" ? "bg-primary/15 text-primary" : "bg-muted")}>{counts[x.id]}</span>}
|
||||
</Link>
|
||||
))}
|
||||
</nav>
|
||||
|
||||
@ -12,6 +12,8 @@ import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Textarea } from "@/components/ui/input";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import { m, translator, type Translator } from "@peppa/shared/i18n";
|
||||
import { acceptStoryAction, commentStoryAction } from "../../actions";
|
||||
|
||||
export const STORY_TABS = [
|
||||
@ -26,12 +28,13 @@ export const STORY_TABS = [
|
||||
] as const;
|
||||
export type StoryTab = (typeof STORY_TABS)[number]["id"];
|
||||
|
||||
const noChange = (change: string | null) => <Empty>{change ? `Change ${change} не найден в рабочей копии.` : "Change ещё не создан — агент заведёт его на этапе proposal."}</Empty>;
|
||||
const noChange = (t: Translator, change: string | null) => <Empty>{change ? t("Change {change} не найден в рабочей копии.", { change }) : t("Change ещё не создан — агент заведёт его на этапе proposal.")}</Empty>;
|
||||
|
||||
export function ArtifactTab({ change, changeId, file }: { change: ChangeArtifacts | null; changeId: string | null; file: "proposal" | "design" }) {
|
||||
if (!change) return noChange(changeId);
|
||||
export async function ArtifactTab({ change, changeId, file }: { change: ChangeArtifacts | null; changeId: string | null; file: "proposal" | "design" }) {
|
||||
const t = await getT();
|
||||
if (!change) return noChange(t, changeId);
|
||||
const text = change[file];
|
||||
if (!text) return <Empty>{file === "design" ? "design.md в этом change нет — значит, решений сверх proposal не понадобилось." : "proposal.md ещё не написан."}</Empty>;
|
||||
if (!text) return <Empty>{file === "design" ? t("design.md в этом change нет — значит, решений сверх proposal не понадобилось.") : t("proposal.md ещё не написан.")}</Empty>;
|
||||
return (
|
||||
<article className="rounded-lg border bg-card p-5">
|
||||
<Markdown text={text} />
|
||||
@ -40,15 +43,16 @@ export function ArtifactTab({ change, changeId, file }: { change: ChangeArtifact
|
||||
}
|
||||
|
||||
const OP: Record<DeltaOp, { label: string; variant: "ok" | "info" | "danger" | "outline" }> = {
|
||||
ADDED: { label: "добавлено", variant: "ok" },
|
||||
MODIFIED: { label: "изменено", variant: "info" },
|
||||
REMOVED: { label: "удалено", variant: "danger" },
|
||||
RENAMED: { label: "переименовано", variant: "outline" },
|
||||
ADDED: { label: m("добавлено"), variant: "ok" },
|
||||
MODIFIED: { label: m("изменено"), variant: "info" },
|
||||
REMOVED: { label: m("удалено"), variant: "danger" },
|
||||
RENAMED: { label: m("переименовано"), variant: "outline" },
|
||||
};
|
||||
|
||||
export function SpecsTab({ change, changeId }: { change: ChangeArtifacts | null; changeId: string | null }) {
|
||||
if (!change) return noChange(changeId);
|
||||
if (!change.specs.length) return <Empty>В change нет дельта-спецификаций (specs/*/spec.md).</Empty>;
|
||||
export async function SpecsTab({ change, changeId }: { change: ChangeArtifacts | null; changeId: string | null }) {
|
||||
const t = await getT();
|
||||
if (!change) return noChange(t, changeId);
|
||||
if (!change.specs.length) return <Empty>{t("В change нет дельта-спецификаций (specs/*/spec.md).")}</Empty>;
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
{change.specs.map((spec) => (
|
||||
@ -56,16 +60,16 @@ export function SpecsTab({ change, changeId }: { change: ChangeArtifacts | null;
|
||||
<h3 className="m-0 font-mono text-sm font-semibold">{spec.capability}</h3>
|
||||
{spec.sections.map((sec, si) => (
|
||||
<div key={si} className="flex flex-col gap-2">
|
||||
{sec.requirements.length === 0 && <p className="m-0 text-xs text-muted-foreground">{OP[sec.op].label}: без требований</p>}
|
||||
{sec.requirements.length === 0 && <p className="m-0 text-xs text-muted-foreground">{t("{op}: без требований", { op: t(OP[sec.op].label) })}</p>}
|
||||
{sec.requirements.map((r, ri) => (
|
||||
<Disclosure
|
||||
key={ri}
|
||||
open={change.specs.length === 1 && ri < 3}
|
||||
summary={
|
||||
<span className="flex min-w-0 items-center gap-2">
|
||||
<Badge variant={OP[sec.op].variant}>{OP[sec.op].label}</Badge>
|
||||
<Badge variant={OP[sec.op].variant}>{t(OP[sec.op].label)}</Badge>
|
||||
<span className="min-w-0 font-medium [overflow-wrap:anywhere]">{r.name}</span>
|
||||
{r.scenarios.length > 0 && <span className="ml-auto shrink-0 font-mono text-[11px] text-muted-foreground">сценариев: {r.scenarios.length}</span>}
|
||||
{r.scenarios.length > 0 && <span className="ml-auto shrink-0 font-mono text-[11px] text-muted-foreground">{t("сценариев: {n}", { n: r.scenarios.length })}</span>}
|
||||
</span>
|
||||
}
|
||||
>
|
||||
@ -73,7 +77,7 @@ export function SpecsTab({ change, changeId }: { change: ChangeArtifacts | null;
|
||||
{r.body && <Markdown text={r.body} />}
|
||||
{r.scenarios.map((sc, i) => (
|
||||
<div key={i} className="rounded-md border-l-2 border-primary/50 bg-muted/30 py-2 pr-3 pl-3">
|
||||
<p className="m-0 mb-1 text-xs font-semibold">Сценарий: {sc.name}</p>
|
||||
<p className="m-0 mb-1 text-xs font-semibold">{t("Сценарий: {name}", { name: sc.name })}</p>
|
||||
<Markdown text={sc.body} className="text-xs" />
|
||||
</div>
|
||||
))}
|
||||
@ -88,9 +92,10 @@ export function SpecsTab({ change, changeId }: { change: ChangeArtifacts | null;
|
||||
);
|
||||
}
|
||||
|
||||
export function TasksTab({ change, changeId, progress }: { change: ChangeArtifacts | null; changeId: string | null; progress: TasksProgress | null }) {
|
||||
if (!change) return noChange(changeId);
|
||||
if (!progress?.total) return <Empty>tasks.md ещё нет или в нём нет пунктов.</Empty>;
|
||||
export async function TasksTab({ change, changeId, progress }: { change: ChangeArtifacts | null; changeId: string | null; progress: TasksProgress | null }) {
|
||||
const t = await getT();
|
||||
if (!change) return noChange(t, changeId);
|
||||
if (!progress?.total) return <Empty>{t("tasks.md ещё нет или в нём нет пунктов.")}</Empty>;
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<ProgressBar done={progress.done} total={progress.total} current={progress.current} />
|
||||
@ -99,7 +104,7 @@ export function TasksTab({ change, changeId, progress }: { change: ChangeArtifac
|
||||
return (
|
||||
<section key={i} className="flex flex-col gap-1.5 rounded-lg border bg-card p-4">
|
||||
<h3 className="m-0 flex items-center gap-2 text-sm font-semibold">
|
||||
{sec.title || "Пункты"}
|
||||
{sec.title || t("Пункты")}
|
||||
<span className={cn("ml-auto font-mono text-xs tabular-nums", done === sec.items.length ? "text-ok" : "text-muted-foreground")}>
|
||||
{done}/{sec.items.length}
|
||||
</span>
|
||||
@ -107,7 +112,7 @@ export function TasksTab({ change, changeId, progress }: { change: ChangeArtifac
|
||||
<ul className="m-0 flex list-none flex-col gap-1 p-0">
|
||||
{sec.items.map((it, j) => (
|
||||
<li key={j} className={cn("flex items-start gap-2 text-sm", it.text === progress.current && !it.done && "rounded bg-info/10 px-1 -mx-1")}>
|
||||
<input type="checkbox" checked={it.done} readOnly disabled aria-label={it.done ? "выполнено" : "не выполнено"} className="mt-1 size-3.5 shrink-0 accent-primary" />
|
||||
<input type="checkbox" checked={it.done} readOnly disabled aria-label={it.done ? t("выполнено") : t("не выполнено")} className="mt-1 size-3.5 shrink-0 accent-primary" />
|
||||
<span className={cn("[overflow-wrap:anywhere]", it.done && "text-muted-foreground line-through decoration-muted-foreground/40")}>{it.text}</span>
|
||||
</li>
|
||||
))}
|
||||
@ -119,10 +124,11 @@ export function TasksTab({ change, changeId, progress }: { change: ChangeArtifac
|
||||
);
|
||||
}
|
||||
|
||||
export function ProgressBar({ done, total, current, compact = false }: { done: number; total: number; current: string | null; compact?: boolean }) {
|
||||
export async function ProgressBar({ done, total, current, compact = false }: { done: number; total: number; current: string | null; compact?: boolean }) {
|
||||
const t = await getT();
|
||||
const pct = total ? Math.round((done / total) * 100) : 0;
|
||||
return (
|
||||
<div className="flex min-w-0 flex-col gap-1" title={current ? `Сейчас: ${current}` : undefined}>
|
||||
<div className="flex min-w-0 flex-col gap-1" title={current ? t("Сейчас: {current}", { current }) : undefined}>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className={cn("flex-1 overflow-hidden rounded-full bg-muted", compact ? "h-1" : "h-1.5")}>
|
||||
<div className={cn("h-full rounded-full", done === total ? "bg-ok" : "bg-info")} style={{ width: `${pct}%` }} />
|
||||
@ -131,45 +137,46 @@ export function ProgressBar({ done, total, current, compact = false }: { done: n
|
||||
{done}/{total}
|
||||
</span>
|
||||
</div>
|
||||
{current && !compact && <span className="truncate text-xs text-muted-foreground">Сейчас: {current}</span>}
|
||||
{current && !compact && <span className="truncate text-xs text-muted-foreground">{t("Сейчас: {current}", { current })}</span>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
type Thread = { at: number; kind: "q"; q: Question } | { at: number; kind: "c"; c: StoryComment };
|
||||
|
||||
export function CommentsTab({ taskKey, taskStatus, questions, comments, back, hasLive }: { taskKey: string; taskStatus: string; questions: Question[]; comments: StoryComment[]; back: string; hasLive: boolean }) {
|
||||
export async function CommentsTab({ taskKey, taskStatus, questions, comments, back, hasLive }: { taskKey: string; taskStatus: string; questions: Question[]; comments: StoryComment[]; back: string; hasLive: boolean }) {
|
||||
const t = await getT();
|
||||
const thread: Thread[] = [...questions.map((q) => ({ at: q.createdAt.getTime(), kind: "q" as const, q })), ...comments.map((c) => ({ at: c.createdAt.getTime(), kind: "c" as const, c }))].sort((a, b) => a.at - b.at);
|
||||
return (
|
||||
<div className="flex flex-col gap-3">
|
||||
{thread.length === 0 && <Empty>Вопросов и комментариев пока нет.</Empty>}
|
||||
{thread.map((t) =>
|
||||
t.kind === "q" ? (
|
||||
<QuestionCard key={`q${t.q.id}`} q={t.q} taskStatus={taskStatus} back={back} />
|
||||
{thread.length === 0 && <Empty>{t("Вопросов и комментариев пока нет.")}</Empty>}
|
||||
{thread.map((x) =>
|
||||
x.kind === "q" ? (
|
||||
<QuestionCard key={`q${x.q.id}`} q={x.q} taskStatus={taskStatus} back={back} />
|
||||
) : (
|
||||
<article key={`c${t.c.id}`} data-role={t.c.role} className={cn("flex flex-col gap-1.5 rounded-lg border p-3.5", t.c.role ? "border-info/40 bg-info/[0.06]" : "border-primary/30 bg-primary/[0.04]")}>
|
||||
<article key={`c${x.c.id}`} data-role={x.c.role} className={cn("flex flex-col gap-1.5 rounded-lg border p-3.5", x.c.role ? "border-info/40 bg-info/[0.06]" : "border-primary/30 bg-primary/[0.04]")}>
|
||||
<header className="flex items-center gap-2 text-xs text-muted-foreground">
|
||||
{t.c.role ? <AgentBadge name={t.c.login} className="font-medium text-foreground" /> : <MessageSquare className="size-3.5 text-primary" />}
|
||||
{t.c.role ? (t.c.role === "product" ? "зачем и что берём" : "что должно получиться") : <><span className="font-medium text-foreground">{t.c.login}</span> комментарий PM</>} · {ago(t.c.createdAt)}
|
||||
{x.c.role ? <AgentBadge name={x.c.login} className="font-medium text-foreground" /> : <MessageSquare className="size-3.5 text-primary" />}
|
||||
{x.c.role ? (x.c.role === "product" ? t("зачем и что берём") : t("что должно получиться")) : <><span className="font-medium text-foreground">{x.c.login}</span> {t("комментарий PM")}</>} · {ago(x.c.createdAt)}
|
||||
</header>
|
||||
<p className="m-0 text-sm whitespace-pre-wrap [overflow-wrap:anywhere]">{t.c.text}</p>
|
||||
<p className="m-0 text-sm whitespace-pre-wrap [overflow-wrap:anywhere]">{x.c.text}</p>
|
||||
</article>
|
||||
),
|
||||
)}
|
||||
<form action={commentStoryAction} className="flex flex-col gap-2 rounded-lg border bg-card p-3.5">
|
||||
<Hidden fields={{ taskKey, back }} />
|
||||
<label htmlFor="story-comment" className="text-sm font-medium">
|
||||
Комментарий для агента
|
||||
{t("Комментарий для агента")}
|
||||
</label>
|
||||
<Textarea id="story-comment" name="text" rows={3} required maxLength={8000} placeholder="Что учесть: агент видит комментарии в get_task" />
|
||||
<Textarea id="story-comment" name="text" rows={3} required maxLength={8000} placeholder={t("Что учесть: агент видит комментарии в get_task")} />
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<label className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<input type="checkbox" name="toAgent" value="1" defaultChecked={hasLive} disabled={!hasLive} className="size-4 accent-primary" />
|
||||
Отправить агенту сейчас{!hasLive && " (живой сессии нет)"}
|
||||
{hasLive ? t("Отправить агенту сейчас") : t("Отправить агенту сейчас (живой сессии нет)")}
|
||||
</label>
|
||||
<Button size="sm" className="ml-auto">
|
||||
<Send />
|
||||
Оставить комментарий
|
||||
{t("Оставить комментарий")}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
@ -193,22 +200,23 @@ export interface CheckRunRow {
|
||||
updatedAt: Date;
|
||||
}
|
||||
|
||||
export function TestsTab({ ci, runs, review }: { ci: CiSummary; runs: CheckRunRow[]; review: CodeReview | null }) {
|
||||
export async function TestsTab({ ci, runs, review }: { ci: CiSummary; runs: CheckRunRow[]; review: CodeReview | null }) {
|
||||
const t = await getT();
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<section className="flex flex-col gap-3 rounded-lg border bg-card p-4">
|
||||
<h3 className="m-0 flex flex-wrap items-center gap-2 text-sm font-semibold">
|
||||
{STATE_ICON[ci.state as keyof typeof STATE_ICON]}
|
||||
{ci.state === "not_configured" ? "Проверки не настроены" : ci.label}
|
||||
{ci.sha && <span className="font-mono text-xs font-normal text-muted-foreground">коммит {ci.sha.slice(0, 7)}</span>}
|
||||
{ci.state === "not_configured" ? t("Проверки не настроены") : t.text(ci.label)}
|
||||
{ci.sha && <span className="font-mono text-xs font-normal text-muted-foreground">{t("коммит {sha}", { sha: ci.sha.slice(0, 7) })}</span>}
|
||||
{ci.runUrl && (
|
||||
<a href={ci.runUrl} className="ml-auto text-xs font-normal text-primary">
|
||||
запуск в Gitea
|
||||
{t("запуск в Gitea")}
|
||||
</a>
|
||||
)}
|
||||
</h3>
|
||||
{ci.state === "not_configured" && <p className="m-0 text-sm text-muted-foreground">В `.peppa/project.json` проекта нет `checks` — PR проверяется только человеком.</p>}
|
||||
{ci.state === "none" && <p className="m-0 text-sm text-muted-foreground">Проверки ещё не запускались: появятся после первого пуша ветки стори.</p>}
|
||||
{ci.state === "not_configured" && <p className="m-0 text-sm text-muted-foreground">{t("В `.peppa/project.json` проекта нет `checks` — PR проверяется только человеком.")}</p>}
|
||||
{ci.state === "none" && <p className="m-0 text-sm text-muted-foreground">{t("Проверки ещё не запускались: появятся после первого пуша ветки стори.")}</p>}
|
||||
{runs.length > 0 && (
|
||||
<ul className="m-0 flex list-none flex-col gap-1.5 p-0">
|
||||
{runs.map((r) => (
|
||||
@ -228,12 +236,12 @@ export function TestsTab({ ci, runs, review }: { ci: CiSummary; runs: CheckRunRo
|
||||
)}
|
||||
</section>
|
||||
<section className="flex flex-col gap-2 rounded-lg border bg-card p-4">
|
||||
<h3 className="m-0 text-sm font-semibold">Агент-ревьюер</h3>
|
||||
<h3 className="m-0 text-sm font-semibold">{t("Агент-ревьюер")}</h3>
|
||||
{review ? (
|
||||
<>
|
||||
<p className="m-0 flex flex-wrap items-center gap-2 text-sm">
|
||||
{review.verdict === "ok" ? STATE_ICON.success : review.verdict === "changes" || review.state === "error" ? STATE_ICON.failure : STATE_ICON.pending}
|
||||
<span className="[overflow-wrap:anywhere]">{reviewLabel(review)}</span>
|
||||
<span className="[overflow-wrap:anywhere]">{t.text(reviewLabel(review))}</span>
|
||||
<span className="font-mono text-xs text-muted-foreground">
|
||||
{review.sha.slice(0, 7)} · {ago(review.updatedAt)}
|
||||
</span>
|
||||
@ -251,30 +259,31 @@ export function TestsTab({ ci, runs, review }: { ci: CiSummary; runs: CheckRunRo
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<p className="m-0 text-sm text-muted-foreground">Ревью не было: ревьюер выключен в настройках проекта или PR ещё не отдан в ревью.</p>
|
||||
<p className="m-0 text-sm text-muted-foreground">{t("Ревью не было: ревьюер выключен в настройках проекта или PR ещё не отдан в ревью.")}</p>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function CheckLine({ r }: { r: CheckRunRow }) {
|
||||
async function CheckLine({ r }: { r: CheckRunRow }) {
|
||||
const t = await getT();
|
||||
return (
|
||||
<span className="flex min-w-0 items-center gap-2 text-sm">
|
||||
{STATE_ICON[r.state]}
|
||||
<span className="font-mono">{r.check}</span>
|
||||
{r.durationSec != null && <span className="font-mono text-xs text-muted-foreground">{r.durationSec} с</span>}
|
||||
{r.durationSec != null && <span className="font-mono text-xs text-muted-foreground">{t("{n} с", { n: r.durationSec })}</span>}
|
||||
<span className="ml-auto font-mono text-xs text-muted-foreground">{ago(r.updatedAt)}</span>
|
||||
{r.runUrl && (
|
||||
<a href={r.runUrl} className="text-xs text-primary">
|
||||
лог
|
||||
{t("лог")}
|
||||
</a>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export function MergeTab({
|
||||
export async function MergeTab({
|
||||
taskKey,
|
||||
taskStatus,
|
||||
prUrl,
|
||||
@ -289,7 +298,8 @@ export function MergeTab({
|
||||
gate: { ok: boolean; reason?: string } | null;
|
||||
back: string;
|
||||
}) {
|
||||
if (!prUrl) return <Empty>PR ещё нет — агент откроет его, когда закончит работу.</Empty>;
|
||||
const t = await getT();
|
||||
if (!prUrl) return <Empty>{t("PR ещё нет — агент откроет его, когда закончит работу.")}</Empty>;
|
||||
return (
|
||||
<section className="flex flex-col gap-3 rounded-lg border bg-card p-4">
|
||||
<h3 className="m-0 flex flex-wrap items-center gap-2 text-sm font-semibold">
|
||||
@ -302,21 +312,21 @@ export function MergeTab({
|
||||
"Pull request"
|
||||
)}
|
||||
<Badge variant={pull?.merged ? "ok" : pull?.state === "closed" ? "danger" : "info"} className="ml-auto">
|
||||
{pull ? (pull.merged ? "смержен" : pull.state === "closed" ? "закрыт" : "открыт") : "Gitea недоступна"}
|
||||
{pull ? (pull.merged ? t("смержен") : pull.state === "closed" ? t("закрыт") : t("открыт")) : t("Gitea недоступна")}
|
||||
</Badge>
|
||||
</h3>
|
||||
{pull && (
|
||||
<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>
|
||||
<dt className="text-muted-foreground">{t("Ветка")}</dt>
|
||||
<dd className="m-0 font-mono text-xs [overflow-wrap:anywhere]">
|
||||
{pull.head.ref} → {pull.base.ref}
|
||||
</dd>
|
||||
<dt className="text-muted-foreground">Коммит</dt>
|
||||
<dt className="text-muted-foreground">{t("Коммит")}</dt>
|
||||
<dd className="m-0 font-mono text-xs">{pull.head.sha.slice(0, 10)}</dd>
|
||||
{!pull.merged && pull.state === "open" && (
|
||||
<>
|
||||
<dt className="text-muted-foreground">Мерж</dt>
|
||||
<dd className="m-0">{gate?.ok ? <span className="text-ok">можно мержить</span> : <span className="text-warn">{gate?.reason ?? (pull.mergeable ? "без конфликтов" : "есть конфликты")}</span>}</dd>
|
||||
<dt className="text-muted-foreground">{t("Мерж")}</dt>
|
||||
<dd className="m-0">{gate?.ok ? <span className="text-ok">{t("можно мержить")}</span> : <span className="text-warn">{gate?.reason ? t.text(gate.reason) : pull.mergeable ? t("без конфликтов") : t("есть конфликты")}</span>}</dd>
|
||||
</>
|
||||
)}
|
||||
</dl>
|
||||
@ -325,41 +335,41 @@ export function MergeTab({
|
||||
<Button asChild variant="outline" size="sm">
|
||||
<a href={prUrl}>
|
||||
<ExternalLink />
|
||||
PR в Gitea
|
||||
{t("PR в Gitea")}
|
||||
</a>
|
||||
</Button>
|
||||
<Button asChild variant="outline" size="sm">
|
||||
<a href={`${prUrl.replace(/\/$/, "")}/files`}>Дифф</a>
|
||||
<a href={`${prUrl.replace(/\/$/, "")}/files`}>{t("Дифф")}</a>
|
||||
</Button>
|
||||
{taskStatus === "review" && !pull?.merged && (
|
||||
<form action={acceptStoryAction} className="ml-auto">
|
||||
<Hidden fields={{ taskKey, back }} />
|
||||
<Button size="sm" disabled={gate ? !gate.ok : false} title={gate && !gate.ok ? gate.reason : undefined}>
|
||||
<Button size="sm" disabled={gate ? !gate.ok : false} title={gate && !gate.ok && gate.reason ? t.text(gate.reason) : undefined}>
|
||||
<GitMerge />
|
||||
Принять и смержить
|
||||
{t("Принять и смержить")}
|
||||
</Button>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
{taskStatus !== "review" && !pull?.merged && <p className="m-0 text-xs text-muted-foreground">Мерж — когда стори в ревью: агент отдаёт её туда после зелёных проверок.</p>}
|
||||
{taskStatus !== "review" && !pull?.merged && <p className="m-0 text-xs text-muted-foreground">{t("Мерж — когда стори в ревью: агент отдаёт её туда после зелёных проверок.")}</p>}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
const EVENT_RU: Record<string, string> = {
|
||||
task_updated: "стори изменена",
|
||||
progress: "прогресс",
|
||||
pm_comment: "комментарий",
|
||||
claude_session: "сессия агента",
|
||||
claude_session_end: "конец сессии агента",
|
||||
session_started: "раннер запущен",
|
||||
session_stopped: "раннер остановлен",
|
||||
auto_continue: "автопродолжение",
|
||||
awaiting_review: "ждёт ревьюера",
|
||||
stop_failure: "ход оборвался",
|
||||
notification: "уведомление",
|
||||
terminal_input: "ввод в терминал",
|
||||
subscription_switched: "смена подписки",
|
||||
task_updated: m("стори изменена"),
|
||||
progress: m("прогресс"),
|
||||
pm_comment: m("комментарий"),
|
||||
claude_session: m("сессия агента"),
|
||||
claude_session_end: m("конец сессии агента"),
|
||||
session_started: m("раннер запущен"),
|
||||
session_stopped: m("раннер остановлен"),
|
||||
auto_continue: m("автопродолжение"),
|
||||
awaiting_review: m("ждёт ревьюера"),
|
||||
stop_failure: m("ход оборвался"),
|
||||
notification: m("уведомление"),
|
||||
terminal_input: m("ввод в терминал"),
|
||||
subscription_switched: m("смена подписки"),
|
||||
};
|
||||
|
||||
export interface ActivityEvent {
|
||||
@ -371,38 +381,41 @@ export interface ActivityEvent {
|
||||
}
|
||||
|
||||
/** Who did it: a PM by login, the agent of a session, or Peppa itself. */
|
||||
export function eventAuthor(e: ActivityEvent, authors?: Map<number, string | null>): { label: string; tone: "pm" | "agent" | "system" } {
|
||||
export function eventAuthor(e: ActivityEvent, authors?: Map<number, string | null>, t: Translator = translator("ru")): { label: string; tone: "pm" | "agent" | "system" } {
|
||||
// PEP-48: the recorded author (person + channel, agent, Peppa) when the event has one.
|
||||
const kind = (e as { actorKind?: string | null }).actorKind;
|
||||
const recorded = authors?.get(e.id);
|
||||
if (kind && recorded) return { label: recorded, tone: kind === "user" ? "pm" : kind === "agent" ? "agent" : "system" };
|
||||
if (kind && recorded) return { label: t.text(recorded), tone: kind === "user" ? "pm" : kind === "agent" ? "agent" : "system" };
|
||||
const login = (e.payload as { login?: unknown } | null)?.login;
|
||||
if (typeof login === "string" && login) return { label: login, tone: "pm" };
|
||||
if (e.sessionId) return { label: `агент · #${e.sessionId}`, tone: "agent" };
|
||||
return { label: "система", tone: "system" };
|
||||
if (e.sessionId) return { label: t("агент · #{id}", { id: e.sessionId }), tone: "agent" };
|
||||
return { label: t("система"), tone: "system" };
|
||||
}
|
||||
|
||||
function changeLine(e: ActivityEvent): string {
|
||||
if (e.type !== "task_updated") return eventLine(e);
|
||||
const CHANGE_FIELD: Record<string, string> = { status: m("статус"), title: m("название"), description: m("описание"), goalId: m("эпик"), openspecChange: "change", prUrl: "PR" };
|
||||
|
||||
function changeLine(e: ActivityEvent, t: Translator): string {
|
||||
if (e.type !== "task_updated") return eventLine(e, t);
|
||||
const to = ((e.payload as { to?: Record<string, unknown> } | null)?.to ?? {}) as Record<string, unknown>;
|
||||
const parts = Object.entries(to).map(([k, v]) => {
|
||||
const name = { status: "статус", title: "название", description: "описание", goalId: "эпик", openspecChange: "change", prUrl: "PR" }[k] ?? k;
|
||||
const name = t(CHANGE_FIELD[k] ?? k);
|
||||
return k === "description" ? name : `${name} → ${v ?? "—"}`;
|
||||
});
|
||||
return parts.join(", ");
|
||||
}
|
||||
|
||||
export function ActivityTab({ events, authors }: { events: ActivityEvent[]; authors?: Map<number, string | null> }) {
|
||||
if (!events.length) return <Empty>Событий нет.</Empty>;
|
||||
export async function ActivityTab({ events, authors }: { events: ActivityEvent[]; authors?: Map<number, string | null> }) {
|
||||
const t = await getT();
|
||||
if (!events.length) return <Empty>{t("Событий нет.")}</Empty>;
|
||||
return (
|
||||
<ol className="m-0 flex list-none flex-col gap-0 border-l p-0 pl-4">
|
||||
{events.map((e) => {
|
||||
const a = eventAuthor(e, authors);
|
||||
const a = eventAuthor(e, authors, t);
|
||||
return (
|
||||
<li key={e.id} className="relative py-1.5 text-sm [overflow-wrap:anywhere]">
|
||||
<span className={cn("absolute top-3 -left-[1.3rem] size-2 rounded-full", a.tone === "pm" ? "bg-primary" : a.tone === "agent" ? "bg-info" : "bg-muted-foreground")} />
|
||||
<span className="font-mono text-xs text-muted-foreground">{ago(e.createdAt)}</span> <span className={cn("text-xs font-medium", a.tone === "pm" ? "text-primary" : a.tone === "agent" ? "text-info" : "text-muted-foreground")}>{a.label}</span>{" "}
|
||||
<span className="font-mono text-xs text-muted-foreground">{EVENT_RU[e.type] ?? e.type}</span> {changeLine(e)}
|
||||
<span className="font-mono text-xs text-muted-foreground">{EVENT_RU[e.type] ? t(EVENT_RU[e.type]) : e.type}</span> {changeLine(e, t)}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
|
||||
@ -5,16 +5,20 @@ import { revalidatePath } from "next/cache";
|
||||
import { redirect } from "next/navigation";
|
||||
import { asWebActor, requireUser } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
|
||||
/** PEP-75: the team is platform-wide, so only a superadmin changes it. */
|
||||
async function run(fn: () => Promise<string | void>): Promise<never> {
|
||||
let target = "/team";
|
||||
try {
|
||||
const user = asWebActor(await requireUser());
|
||||
if (!(await isSuperadmin(db, user))) throw new PeppaError("Команду меняет только суперадмин");
|
||||
if (!(await isSuperadmin(db, user))) throw new PeppaError(m("Команду меняет только суперадмин"));
|
||||
target = (await fn()) || target;
|
||||
} catch (e) {
|
||||
target = `/team?error=${encodeURIComponent((e instanceof PeppaError ? e.message : `Ошибка: ${(e as Error).message}`).slice(0, 300))}`;
|
||||
const t = await getT();
|
||||
const msg = e instanceof PeppaError ? t.text(e.message) : t("Ошибка: {message}", { message: (e as Error).message });
|
||||
target = `/team?error=${encodeURIComponent(msg.slice(0, 300))}`;
|
||||
}
|
||||
revalidatePath("/", "layout");
|
||||
redirect(target);
|
||||
|
||||
@ -10,82 +10,88 @@ import { Input, Label, Textarea } from "@/components/ui/input";
|
||||
import { Workspace } from "@/components/Workspace";
|
||||
import { requireUser } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import { addAgentAction, saveAgentAction, toggleAgentAction } from "./actions";
|
||||
|
||||
export const metadata = { title: "Команда — Пеппа" };
|
||||
export async function generateMetadata() {
|
||||
const t = await getT();
|
||||
return { title: t("Команда — Пеппа") };
|
||||
}
|
||||
|
||||
/** PEP-75: the platform's team of agents — names and characters. Everyone sees it; a superadmin edits. */
|
||||
export default async function Team({ searchParams }: { searchParams: Promise<{ error?: string; saved?: string }> }) {
|
||||
const user = await requireUser();
|
||||
const t = await getT();
|
||||
const { error, saved } = await searchParams;
|
||||
const [team, admin] = await Promise.all([listAgents(db), isSuperadmin(db, user)]);
|
||||
return (
|
||||
<Workspace>
|
||||
<div className="max-w-3xl">
|
||||
<Flash error={error} />
|
||||
{saved && <Notice>Сохранено — агент получит новый характер при следующем запуске или перезапуске.</Notice>}
|
||||
<PageHeader title="Команда">
|
||||
Агенты Пеппы — постоянные персонажи, одна команда на все проекты. Раннер берёт свободного агента на стори, и тот ведёт её до конца; если все заняты — в команде
|
||||
появляется новый. Характер агента добавляется к его промпту поверх правил Пеппы и AGENTS.md проекта.
|
||||
{saved && <Notice>{t("Сохранено — агент получит новый характер при следующем запуске или перезапуске.")}</Notice>}
|
||||
<PageHeader title={t("Команда")}>
|
||||
{t(
|
||||
"Агенты Пеппы — постоянные персонажи, одна команда на все проекты. Раннер берёт свободного агента на стори, и тот ведёт её до конца; если все заняты — в команде появляется новый. Характер агента добавляется к его промпту поверх правил Пеппы и AGENTS.md проекта.",
|
||||
)}
|
||||
</PageHeader>
|
||||
|
||||
{admin && (
|
||||
<Card>
|
||||
<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" />
|
||||
{t("Новый агент")}
|
||||
<Input name="name" placeholder={t("Имя — или пусто: Пеппа выберет сама")} maxLength={40} autoComplete="off" />
|
||||
</Label>
|
||||
<Button variant="default">
|
||||
<Plus /> Добавить
|
||||
<Plus /> {t("Добавить")}
|
||||
</Button>
|
||||
</form>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<Section title="Агенты" count={team.length}>
|
||||
{team.length === 0 && <Empty>Пока никого: первый агент появится, когда стори уйдёт «В работу».</Empty>}
|
||||
<Section title={t("Агенты")} count={team.length}>
|
||||
{team.length === 0 && <Empty>{t("Пока никого: первый агент появится, когда стори уйдёт «В работу».")}</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">
|
||||
<AgentBadge name={a.name} large />
|
||||
{a.busy > 0 ? <Badge variant="info">работает{a.busy > 1 ? ` ×${a.busy}` : ""}</Badge> : <Badge variant="muted">свободен</Badge>}
|
||||
{a.disabledAt && <Badge variant="danger">не в команде</Badge>}
|
||||
<span className="ml-auto text-xs text-muted-foreground">запусков: {a.runs}</span>
|
||||
{a.busy > 0 ? <Badge variant="info">{t("работает")}{a.busy > 1 ? ` ×${a.busy}` : ""}</Badge> : <Badge variant="muted">{t("свободен")}</Badge>}
|
||||
{a.disabledAt && <Badge variant="danger">{t("не в команде")}</Badge>}
|
||||
<span className="ml-auto text-xs text-muted-foreground">{t("запусков: {n}", { n: a.runs })}</span>
|
||||
</div>
|
||||
{admin ? (
|
||||
<>
|
||||
<form action={saveAgentAction} className="flex flex-col gap-2">
|
||||
<input type="hidden" name="id" value={a.id} />
|
||||
<Label className="max-w-xs">
|
||||
Имя
|
||||
{t("Имя")}
|
||||
<Input name="name" defaultValue={a.name} required maxLength={40} autoComplete="off" />
|
||||
</Label>
|
||||
<Label>
|
||||
Характер и специализация
|
||||
{t("Характер и специализация")}
|
||||
<Textarea
|
||||
name="character"
|
||||
defaultValue={a.character}
|
||||
rows={a.character ? 8 : 3}
|
||||
maxLength={AGENT_CHARACTER_MAX}
|
||||
placeholder={"Например: педант по безопасности — любой ввод проверяет, секреты ищет в каждом диффе. Пишет коротко и сухо, без извинений."}
|
||||
placeholder={t("Например: педант по безопасности — любой ввод проверяет, секреты ищет в каждом диффе. Пишет коротко и сухо, без извинений.")}
|
||||
className="text-sm"
|
||||
/>
|
||||
</Label>
|
||||
<Button className="self-start" size="sm" variant="default">Сохранить</Button>
|
||||
<Button className="self-start" size="sm" variant="default">{t("Сохранить")}</Button>
|
||||
</form>
|
||||
<form action={toggleAgentAction}>
|
||||
<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 ? t("Вернуть в команду") : t("Убрать из команды — новые стори не получит")}
|
||||
</Button>
|
||||
</form>
|
||||
</>
|
||||
) : a.character ? (
|
||||
<Markdown text={a.character} />
|
||||
) : (
|
||||
<p className="m-0 text-sm text-muted-foreground">Характер не задан.</p>
|
||||
<p className="m-0 text-sm text-muted-foreground">{t("Характер не задан.")}</p>
|
||||
)}
|
||||
</Card>
|
||||
))}
|
||||
|
||||
@ -8,6 +8,7 @@ import { Card } from "@/components/ui/card";
|
||||
import { Workspace } from "@/components/Workspace";
|
||||
import { requireUser } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import { setUserDisabledAction } from "../actions";
|
||||
|
||||
const back = { back: "/users" };
|
||||
@ -16,6 +17,7 @@ const back = { back: "/users" };
|
||||
export default async function Users({ searchParams }: { searchParams: Promise<{ error?: string }> }) {
|
||||
const me = await requireUser();
|
||||
if (!(await isSuperadmin(db, me))) notFound();
|
||||
const t = await getT();
|
||||
const { error } = await searchParams;
|
||||
const all = await listUsers(db);
|
||||
const admins = new Set(await platformAdmins(db));
|
||||
@ -23,12 +25,13 @@ export default async function Users({ searchParams }: { searchParams: Promise<{
|
||||
<Workspace>
|
||||
<div className="max-w-3xl">
|
||||
<Flash error={error} />
|
||||
<PageHeader title="Пользователи">
|
||||
Вход только через eGov: первый вход по QR сам создаёт учётку по ИИН. Доступ к проектам — приглашением владельца; агенты проекта нового пользователя
|
||||
работают только на пуле подписок. Отключённый пользователь сразу теряет сессии веба и MCP.
|
||||
<PageHeader title={t("Пользователи")}>
|
||||
{t(
|
||||
"Вход только через eGov: первый вход по QR сам создаёт учётку по ИИН. Доступ к проектам — приглашением владельца; агенты проекта нового пользователя работают только на пуле подписок. Отключённый пользователь сразу теряет сессии веба и MCP.",
|
||||
)}
|
||||
</PageHeader>
|
||||
|
||||
<Section title="Все пользователи" count={all.length}>
|
||||
<Section title={t("Все пользователи")} count={all.length}>
|
||||
{all.map((u) => {
|
||||
const local = isLocalUser(u);
|
||||
return (
|
||||
@ -37,18 +40,18 @@ export default async function Users({ searchParams }: { searchParams: Promise<{
|
||||
<span className="font-mono font-medium">{u.login}</span>
|
||||
{u.name && <span className="text-sm text-muted-foreground">{u.name}</span>}
|
||||
{!local && <Badge variant="muted">Gitea</Badge>}
|
||||
{admins.has(u.login.toLowerCase()) && <Badge variant="primary">суперадмин</Badge>}
|
||||
{u.disabledAt && <Badge variant="danger">отключён</Badge>}
|
||||
{admins.has(u.login.toLowerCase()) && <Badge variant="primary">{t("суперадмин")}</Badge>}
|
||||
{u.disabledAt && <Badge variant="danger">{t("отключён")}</Badge>}
|
||||
{u.egovIin && <Badge variant="muted">eGov {maskIin(u.egovIin)}</Badge>}
|
||||
{u.googleSub && <Badge variant="muted">Google {u.googleEmail}</Badge>}
|
||||
{!u.egovIin && !u.googleSub && !u.passwordHash && <Badge variant="warn">без eGov и Google — не войдёт</Badge>}
|
||||
<span className="ml-auto text-xs text-muted-foreground">{u.lastLoginAt ? `вход ${ago(u.lastLoginAt)}` : "ещё не входил"}</span>
|
||||
{!u.egovIin && !u.googleSub && !u.passwordHash && <Badge variant="warn">{t("без eGov и Google — не войдёт")}</Badge>}
|
||||
<span className="ml-auto text-xs text-muted-foreground">{u.lastLoginAt ? t("вход {ago}", { ago: ago(u.lastLoginAt, t) }) : t("ещё не входил")}</span>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{u.id !== me.id && (
|
||||
<form action={setUserDisabledAction} className="ml-auto">
|
||||
<Hidden fields={{ userId: String(u.id), disabled: u.disabledAt ? "0" : "1", ...back }} />
|
||||
<Button size="sm" variant={u.disabledAt ? "default" : "destructive"}>{u.disabledAt ? "Включить" : "Отключить"}</Button>
|
||||
<Button size="sm" variant={u.disabledAt ? "default" : "destructive"}>{u.disabledAt ? t("Включить") : t("Отключить")}</Button>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@ -5,76 +5,79 @@ import { Workspace } from "@/components/Workspace";
|
||||
import { PageHeader, Section } from "@/components/common";
|
||||
import { PugMascot } from "@/components/PugMascot";
|
||||
import { requireUser } from "@/lib/auth";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
|
||||
const WHY = [
|
||||
{ title: "Программировать не нужно", text: "Вы пишете, что должно получиться, — как объяснили бы коллеге. Как это сделать, решают агенты." },
|
||||
{ title: "Всё на виду", text: "Доска показывает, что в работе, что готово и какой агент чем занят." },
|
||||
{ title: "Последнее слово за вами", text: "Ничего не считается готовым, пока вы не посмотрели результат и не нажали «Принять»." },
|
||||
{ title: m("Программировать не нужно"), text: m("Вы пишете, что должно получиться, — как объяснили бы коллеге. Как это сделать, решают агенты.") },
|
||||
{ title: m("Всё на виду"), text: m("Доска показывает, что в работе, что готово и какой агент чем занят.") },
|
||||
{ title: m("Последнее слово за вами"), text: m("Ничего не считается готовым, пока вы не посмотрели результат и не нажали «Принять».") },
|
||||
];
|
||||
|
||||
const FLOW = [
|
||||
{ title: "Стори", text: "Одна понятная история: «Страница каталога: фото, цена, кнопка „Купить“». Пишите, зачем это нужно и как понять, что готово.", href: "/projects", cta: "К проектам" },
|
||||
{ title: "Бэклог → В работе", text: "Когда стори переходит «В работе», её берёт агент: придумывает план, пишет код, проверяет себя и открывает изменение.", href: null, cta: "" },
|
||||
{ title: "Вопросы агентов", text: "Агент спрашивает только о важном: решения, деньги, доступы. Ответ — на Главной, в Telegram или через MCP.", href: "/", cta: "На Главную" },
|
||||
{ title: "Ревью → Готово", text: "Придёт «готово к ревью» со ссылкой на стенд. Посмотрите и нажмите «Принять» — или напишите, что поправить, агент доделает.", href: null, cta: "" },
|
||||
{ title: m("Стори"), text: m("Одна понятная история: «Страница каталога: фото, цена, кнопка „Купить“». Пишите, зачем это нужно и как понять, что готово."), href: "/projects", cta: m("К проектам") },
|
||||
{ title: m("Бэклог → В работе"), text: m("Когда стори переходит «В работе», её берёт агент: придумывает план, пишет код, проверяет себя и открывает изменение."), href: null, cta: "" },
|
||||
{ title: m("Вопросы агентов"), text: m("Агент спрашивает только о важном: решения, деньги, доступы. Ответ — на Главной, в Telegram или через MCP."), href: "/", cta: m("На Главную") },
|
||||
{ title: m("Ревью → Готово"), text: m("Придёт «готово к ревью» со ссылкой на стенд. Посмотрите и нажмите «Принять» — или напишите, что поправить, агент доделает."), href: null, cta: "" },
|
||||
];
|
||||
|
||||
const WORDS: Array<[string, string]> = [
|
||||
["Проект", "ваш продукт: у него свой репозиторий, доска и агенты"],
|
||||
["Эпик", "метка, которая группирует стори одной большой цели"],
|
||||
["Стори", "одна задача для агента; одна стори — одно законченное изменение"],
|
||||
["Агент", "ИИ-разработчик со своим именем; работает на вашей подписке Claude или ChatGPT"],
|
||||
["Ревью", "момент, когда агент закончил, а вы решаете: принять или вернуть"],
|
||||
[m("Проект"), m("ваш продукт: у него свой репозиторий, доска и агенты")],
|
||||
[m("Эпик"), m("метка, которая группирует стори одной большой цели")],
|
||||
[m("Стори"), m("одна задача для агента; одна стори — одно законченное изменение")],
|
||||
[m("Агент"), m("ИИ-разработчик со своим именем; работает на вашей подписке Claude или ChatGPT")],
|
||||
[m("Ревью"), m("момент, когда агент закончил, а вы решаете: принять или вернуть")],
|
||||
];
|
||||
|
||||
export default async function Welcome() {
|
||||
await requireUser();
|
||||
const t = await getT();
|
||||
return (
|
||||
<Workspace>
|
||||
<PageHeader title="Добро пожаловать в Пеппу">Опишите идею словами — команда ИИ-агентов сделает продукт, а вы примете результат.</PageHeader>
|
||||
<PageHeader title={t("Добро пожаловать в Пеппу")}>{t("Опишите идею словами — команда ИИ-агентов сделает продукт, а вы примете результат.")}</PageHeader>
|
||||
<div className="mb-8 flex flex-wrap items-center gap-5 rounded-xl border bg-card p-5">
|
||||
<PugMascot mood="alert" size={88} />
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="m-0 text-sm text-muted-foreground">Пеппа — софтвер-фабрика для тех, кто придумывает продукты, а не пишет код. Вы ставите задачи и принимаете результат; агенты программируют, проверяют себя и отчитываются.</p>
|
||||
<p className="m-0 text-sm text-muted-foreground">{t("Пеппа — софтвер-фабрика для тех, кто придумывает продукты, а не пишет код. Вы ставите задачи и принимаете результат; агенты программируют, проверяют себя и отчитываются.")}</p>
|
||||
<Link href="/" className="mt-3 inline-flex items-center gap-1.5 rounded-md bg-primary px-3.5 py-2 text-sm font-medium text-primary-foreground hover:no-underline">
|
||||
Начать с первых шагов <ArrowRight className="size-4" />
|
||||
{t("Начать с первых шагов")} <ArrowRight className="size-4" />
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
<Section title="Зачем это вам">
|
||||
<Section title={t("Зачем это вам")}>
|
||||
<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>
|
||||
<span className="flex items-center gap-2 font-medium"><Check className="size-4 shrink-0 text-ok" /> {t(w.title)}</span>
|
||||
<span className="text-sm text-muted-foreground">{t(w.text)}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</Section>
|
||||
<Section title="Как тут работать">
|
||||
<Section title={t("Как тут работать")}>
|
||||
<ol className="m-0 flex list-none flex-col gap-2 p-0">
|
||||
{FLOW.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">
|
||||
<span className="font-medium">{s.title}</span>
|
||||
<span className="text-sm text-muted-foreground">{s.text}</span>
|
||||
{s.href && <Link href={s.href} className="mt-1 text-sm">{s.cta} →</Link>}
|
||||
<span className="font-medium">{t(s.title)}</span>
|
||||
<span className="text-sm text-muted-foreground">{t(s.text)}</span>
|
||||
{s.href && <Link href={s.href} className="mt-1 text-sm">{t(s.cta)} →</Link>}
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</Section>
|
||||
<Section title="Слова, которые встретятся">
|
||||
<Section title={t("Слова, которые встретятся")}>
|
||||
<dl className="m-0 grid gap-2 sm:grid-cols-2">
|
||||
{WORDS.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>
|
||||
{WORDS.map(([w, d]) => (
|
||||
<div key={w} className="rounded-xl border bg-card px-4 py-3">
|
||||
<dt className="font-medium">{t(w)}</dt>
|
||||
<dd className="m-0 text-sm text-muted-foreground">{t(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">{t("Что-то непонятно? Загляните в")} <Link href="/help">{t("Помощь")}</Link> {t("— там и подключение через MCP, и горячие клавиши.")}</p>
|
||||
</Section>
|
||||
</Workspace>
|
||||
);
|
||||
|
||||
@ -3,19 +3,21 @@
|
||||
import { LiveError, liveSse, parseScopes } from "@peppa/runner";
|
||||
import { currentUser } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const fail = (status: number, error: string) => Response.json({ error }, { status, headers: { "Cache-Control": "no-store" } });
|
||||
const fail = async (status: number, error: string) => Response.json({ error: (await getT()).text(error) }, { status, headers: { "Cache-Control": "no-store" } });
|
||||
|
||||
export async function GET(req: Request) {
|
||||
const user = await currentUser();
|
||||
if (!user) return fail(401, "Нужен вход");
|
||||
if (!user) return fail(401, m("Нужен вход"));
|
||||
try {
|
||||
return await liveSse(db, user, parseScopes(new URL(req.url).searchParams.get("scope")), req.signal);
|
||||
} catch (e) {
|
||||
if (e instanceof LiveError) return fail(e.status, e.message);
|
||||
console.error("live:", e);
|
||||
return fail(500, "Ошибка потока");
|
||||
return fail(500, m("Ошибка потока"));
|
||||
}
|
||||
}
|
||||
|
||||
@ -4,15 +4,17 @@ import { projectForUser } from "@peppa/core";
|
||||
import { releaseScreenshot } from "@peppa/runner";
|
||||
import { currentUser } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { getT } from "@/lib/i18n";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export async function GET(_req: Request, { params }: { params: Promise<{ id: string; n: string }> }) {
|
||||
const user = await currentUser();
|
||||
if (!user) return new Response("Нужен вход", { status: 401 });
|
||||
const t = await getT();
|
||||
if (!user) return new Response(t("Нужен вход"), { status: 401 });
|
||||
const { id, n } = await params;
|
||||
const shot = await releaseScreenshot(db, Number(id), Number(n));
|
||||
const allowed = shot && (await projectForUser(db, user.id, shot.projectId).then(() => true, () => false));
|
||||
if (!shot || !allowed) return new Response("Не найдено", { status: 404 });
|
||||
if (!shot || !allowed) return new Response(t("Не найдено"), { status: 404 });
|
||||
return new Response(new Uint8Array(shot.png), { headers: { "Content-Type": "image/png", "Cache-Control": "private, max-age=3600" } });
|
||||
}
|
||||
|
||||
@ -2,22 +2,24 @@
|
||||
import { TerminalError, terminalInput, terminalSse } from "@peppa/runner";
|
||||
import { currentUser } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
type Ctx = { params: Promise<{ id: string }> };
|
||||
|
||||
const fail = (status: number, error: string) => Response.json({ error }, { status, headers: { "Cache-Control": "no-store" } });
|
||||
const fail = async (status: number, error: string) => Response.json({ error: (await getT()).text(error) }, { status, headers: { "Cache-Control": "no-store" } });
|
||||
|
||||
function asResponse(e: unknown): Response {
|
||||
function asResponse(e: unknown): Promise<Response> {
|
||||
if (e instanceof TerminalError) return fail(e.status, e.message);
|
||||
console.error("terminal:", e);
|
||||
return fail(500, "Ошибка терминала");
|
||||
return fail(500, m("Ошибка терминала"));
|
||||
}
|
||||
|
||||
export async function GET(req: Request, { params }: Ctx) {
|
||||
const user = await currentUser();
|
||||
if (!user) return fail(401, "Нужен вход");
|
||||
if (!user) return fail(401, m("Нужен вход"));
|
||||
try {
|
||||
return await terminalSse(db, user, Number((await params).id), req.signal);
|
||||
} catch (e) {
|
||||
@ -39,16 +41,16 @@ function sameOrigin(req: Request): boolean {
|
||||
|
||||
export async function POST(req: Request, { params }: Ctx) {
|
||||
const user = await currentUser();
|
||||
if (!user) return fail(401, "Нужен вход");
|
||||
if (!sameOrigin(req)) return fail(403, "Чужой источник");
|
||||
if (!req.headers.get("content-type")?.startsWith("application/json")) return fail(415, "Нужен JSON");
|
||||
if (!user) return fail(401, m("Нужен вход"));
|
||||
if (!sameOrigin(req)) return fail(403, m("Чужой источник"));
|
||||
if (!req.headers.get("content-type")?.startsWith("application/json")) return fail(415, m("Нужен JSON"));
|
||||
// Paste limit is 64 KB; refuse oversized bodies before parsing.
|
||||
if (Number(req.headers.get("content-length") ?? 0) > 300_000) return fail(413, "Слишком длинный ввод");
|
||||
if (Number(req.headers.get("content-length") ?? 0) > 300_000) return fail(413, m("Слишком длинный ввод"));
|
||||
let body: { keys?: unknown; paste?: unknown };
|
||||
try {
|
||||
body = await req.json();
|
||||
} catch {
|
||||
return fail(400, "Неверный JSON");
|
||||
return fail(400, m("Неверный JSON"));
|
||||
}
|
||||
try {
|
||||
await terminalInput(db, user, Number((await params).id), {
|
||||
|
||||
@ -4,7 +4,7 @@ import { NextResponse, type NextRequest } from "next/server";
|
||||
import { EGOV_COOKIE, egovCookieOptions, safeNext, sessionCookie } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { adoptLocale, localeCookieOptions } from "@/lib/i18n";
|
||||
import { LOCALE_COOKIE } from "@peppa/shared/i18n";
|
||||
import { LOCALE_COOKIE, m } from "@peppa/shared/i18n";
|
||||
|
||||
/** Finishes a signed eGov flow: logs in by the IIN (PEP-71: registers an unknown one), or links it to the current account. */
|
||||
export async function POST(req: NextRequest) {
|
||||
@ -20,7 +20,7 @@ export async function POST(req: NextRequest) {
|
||||
// The handle lives only in the starter's httpOnly cookie, so a link flow is finished by the
|
||||
// browser (and account) that started it.
|
||||
if (r.purpose === "link") return done({ redirect: "/settings?egov=linked" });
|
||||
if (!(await isUserAllowed(db, r.user))) return done({ error: "Учётка отключена — обратитесь к администратору" }, 403);
|
||||
if (!(await isUserAllowed(db, r.user))) return done({ error: m("Учётка отключена — обратитесь к администратору") }, 403);
|
||||
const res = done({ redirect: safeNext(next) });
|
||||
const c = sessionCookie(r.user.id);
|
||||
res.cookies.set(c.name, c.value, c.options);
|
||||
@ -29,6 +29,6 @@ export async function POST(req: NextRequest) {
|
||||
if (lang) res.cookies.set(LOCALE_COOKIE, lang, localeCookieOptions);
|
||||
return res;
|
||||
} catch (e) {
|
||||
return done({ error: e instanceof PeppaError ? e.message : "Не удалось войти через eGov" }, 400);
|
||||
return done({ error: e instanceof PeppaError ? e.message : m("Не удалось войти через eGov") }, 400);
|
||||
}
|
||||
}
|
||||
|
||||
@ -3,6 +3,7 @@ import { NextResponse, type NextRequest } from "next/server";
|
||||
import QRCode from "qrcode";
|
||||
import { currentUser, EGOV_COOKIE, egovCookieOptions } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
|
||||
/** Starts an eGov QR flow (PEP-65): `login` from the login page, `link` from Settings (needs a session). */
|
||||
export async function POST(req: NextRequest) {
|
||||
@ -15,6 +16,6 @@ export async function POST(req: NextRequest) {
|
||||
res.cookies.set(EGOV_COOKIE, flow.handle, egovCookieOptions(Math.ceil((flow.expiresAt - Date.now()) / 1000)));
|
||||
return res;
|
||||
} catch (e) {
|
||||
return NextResponse.json({ error: e instanceof PeppaError ? e.message : "Не удалось создать QR eGov" }, { status: 502 });
|
||||
return NextResponse.json({ error: e instanceof PeppaError ? e.message : m("Не удалось создать QR eGov") }, { status: 502 });
|
||||
}
|
||||
}
|
||||
|
||||
@ -3,12 +3,13 @@ import { cookies } from "next/headers";
|
||||
import { NextResponse } from "next/server";
|
||||
import { EGOV_COOKIE } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
|
||||
/** Status of this browser's eGov QR flow: pending | scanned | completed | expired | rejected. */
|
||||
export async function GET() {
|
||||
try {
|
||||
return NextResponse.json({ status: await egovFlowStatus(db, (await cookies()).get(EGOV_COOKIE)?.value ?? "") });
|
||||
} catch (e) {
|
||||
return NextResponse.json({ error: e instanceof PeppaError ? e.message : "eGov недоступен" }, { status: 502 });
|
||||
return NextResponse.json({ error: e instanceof PeppaError ? e.message : m("eGov недоступен") }, { status: 502 });
|
||||
}
|
||||
}
|
||||
|
||||
@ -4,7 +4,7 @@ import { NextResponse, type NextRequest } from "next/server";
|
||||
import { GOOGLE_COOKIE, googleCookieOptions, publicOrigin, safeNext, sessionCookie } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { adoptLocale, localeCookieOptions } from "@/lib/i18n";
|
||||
import { LOCALE_COOKIE } from "@peppa/shared/i18n";
|
||||
import { LOCALE_COOKIE, m } from "@peppa/shared/i18n";
|
||||
|
||||
/** Google redirects here (PEP-90): checks state against the browser's cookie, then logs in, registers or links. */
|
||||
export async function GET(req: NextRequest) {
|
||||
@ -19,11 +19,11 @@ export async function GET(req: NextRequest) {
|
||||
res.cookies.set(`${GOOGLE_COOKIE}_next`, "", googleCookieOptions(0));
|
||||
return res;
|
||||
};
|
||||
if (q.get("error")) return done("/login", q.get("error") === "access_denied" ? "Вход через Google отменён" : "Google отказал во входе");
|
||||
if (q.get("error")) return done("/login", q.get("error") === "access_denied" ? m("Вход через Google отменён") : m("Google отказал во входе"));
|
||||
try {
|
||||
const r = await completeGoogleFlow(db, { state: q.get("state") ?? "", code: q.get("code") ?? "", cookieState });
|
||||
if (r.purpose === "link") return done("/settings?google=linked");
|
||||
if (!(await isUserAllowed(db, r.user))) return done("/login", "Учётка отключена — обратитесь к администратору");
|
||||
if (!(await isUserAllowed(db, r.user))) return done("/login", m("Учётка отключена — обратитесь к администратору"));
|
||||
const res = done(next);
|
||||
const c = sessionCookie(r.user.id);
|
||||
res.cookies.set(c.name, c.value, c.options);
|
||||
@ -32,6 +32,6 @@ export async function GET(req: NextRequest) {
|
||||
if (lang) res.cookies.set(LOCALE_COOKIE, lang, localeCookieOptions);
|
||||
return res;
|
||||
} catch (e) {
|
||||
return done("/login", e instanceof PeppaError ? e.message : "Не удалось войти через Google");
|
||||
return done("/login", e instanceof PeppaError ? e.message : m("Не удалось войти через Google"));
|
||||
}
|
||||
}
|
||||
|
||||
@ -2,6 +2,7 @@ import { PeppaError, startGoogleFlow } from "@peppa/core";
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
import { currentUser, GOOGLE_COOKIE, googleCookieOptions, publicOrigin, safeNext } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
|
||||
/** Starts a Google login (PEP-90) or, from Settings (`purpose=link`, needs a session), linking. POST form → 303 to Google. */
|
||||
export async function POST(req: NextRequest) {
|
||||
@ -12,7 +13,7 @@ export async function POST(req: NextRequest) {
|
||||
const fail = (msg: string) => NextResponse.redirect(`${origin}${purpose === "link" ? "/settings" : "/login"}?error=${encodeURIComponent(msg)}`, 303);
|
||||
try {
|
||||
const user = purpose === "link" ? await currentUser() : null;
|
||||
if (purpose === "link" && !user) return fail("Войдите, чтобы привязать Google");
|
||||
if (purpose === "link" && !user) return fail(m("Войдите, чтобы привязать Google"));
|
||||
const flow = await startGoogleFlow(db, purpose, `${origin}/auth/google/callback`, user?.id ?? null);
|
||||
const res = NextResponse.redirect(flow.url, 303);
|
||||
res.cookies.set(GOOGLE_COOKIE, flow.state, googleCookieOptions(600));
|
||||
@ -20,6 +21,6 @@ export async function POST(req: NextRequest) {
|
||||
res.cookies.set(`${GOOGLE_COOKIE}_next`, next, googleCookieOptions(600));
|
||||
return res;
|
||||
} catch (e) {
|
||||
return fail(e instanceof PeppaError ? e.message : "Не удалось начать вход через Google");
|
||||
return fail(e instanceof PeppaError ? e.message : m("Не удалось начать вход через Google"));
|
||||
}
|
||||
}
|
||||
|
||||
@ -3,13 +3,14 @@ import { NextResponse, type NextRequest } from "next/server";
|
||||
import { publicOrigin, sessionCookie } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { adoptLocale, localeCookieOptions } from "@/lib/i18n";
|
||||
import { LOCALE_COOKIE } from "@peppa/shared/i18n";
|
||||
import { LOCALE_COOKIE, m } from "@peppa/shared/i18n";
|
||||
|
||||
/** One-time admin login link from `peppa web login-link`. */
|
||||
export async function GET(req: NextRequest) {
|
||||
const origin = await publicOrigin();
|
||||
const uid = await consumeLoginLink(db, req.nextUrl.searchParams.get("code") ?? "");
|
||||
if (!uid) return NextResponse.redirect(`${origin}/login?error=${encodeURIComponent("Ссылка входа недействительна или уже использована")}`);
|
||||
const invalid = m("Ссылка входа недействительна или уже использована");
|
||||
if (!uid) return NextResponse.redirect(`${origin}/login?error=${encodeURIComponent(invalid)}`);
|
||||
const res = NextResponse.redirect(`${origin}/`);
|
||||
const c = sessionCookie(uid);
|
||||
res.cookies.set(c.name, c.value, c.options);
|
||||
|
||||
@ -8,72 +8,77 @@ import { Flash } from "@/components/common";
|
||||
import { EgovSign } from "@/components/EgovSign";
|
||||
import { Footer } from "@/components/Footer";
|
||||
import { PugMascot } from "@/components/PugMascot";
|
||||
import { LanguageSwitcher } from "@/components/I18n";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const WHY = [
|
||||
{ title: "Программировать не нужно", text: "Вы пишете, что должно получиться, — как объяснили бы коллеге. Как это сделать, решают агенты." },
|
||||
{ title: "Всё на виду", text: "Доска показывает, что в работе, что готово и какой агент чем занят. Никаких «спросите у разработчиков»." },
|
||||
{ title: "Последнее слово за вами", text: "Ничего не считается готовым, пока вы не посмотрели результат и не нажали «Принять»." },
|
||||
{ title: m("Программировать не нужно"), text: m("Вы пишете, что должно получиться, — как объяснили бы коллеге. Как это сделать, решают агенты.") },
|
||||
{ title: m("Всё на виду"), text: m("Доска показывает, что в работе, что готово и какой агент чем занят. Никаких «спросите у разработчиков».") },
|
||||
{ title: m("Последнее слово за вами"), text: m("Ничего не считается готовым, пока вы не посмотрели результат и не нажали «Принять».") },
|
||||
];
|
||||
|
||||
const STEPS = [
|
||||
{ title: "Войдите с ноутбука", text: "Через eGov QR или Google — учётка создаётся сама, пароль не нужен." },
|
||||
{ title: "Привяжите Telegram-бота", text: "Он на телефоне позовёт вас, когда агенту нужен ответ или работа готова." },
|
||||
{ title: "Создайте проект и подключите подписку", text: "Свою Claude или ChatGPT — на ней агенты пишут код. Это одна минута." },
|
||||
{ title: "Опишите задачу словами", text: "«Страница с каталогом: фото, цена, кнопка „Купить“». Агент возьмёт её сам." },
|
||||
{ title: "Примите результат", text: "Придёт сообщение «готово». Посмотрите и нажмите «Принять» — или напишите, что поправить." },
|
||||
{ title: m("Войдите с ноутбука"), text: m("Через eGov QR или Google — учётка создаётся сама, пароль не нужен.") },
|
||||
{ title: m("Привяжите Telegram-бота"), text: m("Он на телефоне позовёт вас, когда агенту нужен ответ или работа готова.") },
|
||||
{ title: m("Создайте проект и подключите подписку"), text: m("Свою Claude или ChatGPT — на ней агенты пишут код. Это одна минута.") },
|
||||
{ title: m("Опишите задачу словами"), text: m("«Страница с каталогом: фото, цена, кнопка „Купить“». Агент возьмёт её сам.") },
|
||||
{ title: m("Примите результат"), text: m("Придёт сообщение «готово». Посмотрите и нажмите «Принять» — или напишите, что поправить.") },
|
||||
];
|
||||
|
||||
const NEED = [
|
||||
{ icon: Laptop, text: "Ноутбук — управлять фабрикой удобнее с большого экрана" },
|
||||
{ icon: ShieldCheck, text: "eGov Mobile на телефоне — для входа" },
|
||||
{ icon: MessageCircle, text: "Telegram — туда приходят вопросы агентов и «готово»" },
|
||||
{ icon: Sparkles, text: "Платная подписка Claude или ChatGPT — на ней работают агенты" },
|
||||
{ icon: Laptop, text: m("Ноутбук — управлять фабрикой удобнее с большого экрана") },
|
||||
{ icon: ShieldCheck, text: m("eGov Mobile на телефоне — для входа") },
|
||||
{ icon: MessageCircle, text: m("Telegram — туда приходят вопросы агентов и «готово»") },
|
||||
{ icon: Sparkles, text: m("Платная подписка Claude или ChatGPT — на ней работают агенты") },
|
||||
];
|
||||
|
||||
/** PEP-71: eGov QR is the only way in. PEP-83: the page first says why the factory and how it works. */
|
||||
export default async function Login({ searchParams }: { searchParams: Promise<{ error?: string; next?: string }> }) {
|
||||
const { error, next } = await searchParams;
|
||||
if (await currentUser()) redirect(safeNext(next));
|
||||
const t = await getT();
|
||||
return (
|
||||
<main className="mx-auto grid min-h-dvh w-full max-w-6xl content-start items-start gap-x-10 gap-y-8 px-5 py-10 lg:grid-cols-[minmax(0,1fr)_380px] lg:py-16">
|
||||
<main className="relative mx-auto grid min-h-dvh w-full max-w-6xl content-start items-start gap-x-10 gap-y-8 px-5 py-10 lg:grid-cols-[minmax(0,1fr)_380px] lg:py-16">
|
||||
<LanguageSwitcher className="absolute top-3 right-5 z-10" />
|
||||
{/* Phone: headline → sign-in → details. Laptop: text on the left, sign-in sticks on the right. */}
|
||||
<header className="flex flex-col gap-4 lg:col-start-1 lg:row-start-1">
|
||||
<Brand large />
|
||||
<h1 className="m-0 text-3xl leading-tight font-semibold tracking-tight text-balance sm:text-4xl">Опишите идею словами — команда ИИ-агентов сделает продукт</h1>
|
||||
<h1 className="m-0 text-3xl leading-tight font-semibold tracking-tight text-balance sm:text-4xl">{t("Опишите идею словами — команда ИИ-агентов сделает продукт")}</h1>
|
||||
<p className="m-0 max-w-2xl text-base text-muted-foreground">
|
||||
Пеппа — софтвер-фабрика для тех, кто придумывает продукты, а не пишет код. Вы ставите задачи и принимаете результат; агенты программируют, проверяют себя и отчитываются.
|
||||
{t("Пеппа — софтвер-фабрика для тех, кто придумывает продукты, а не пишет код. Вы ставите задачи и принимаете результат; агенты программируют, проверяют себя и отчитываются.")}
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<aside className="flex flex-col items-center gap-4 rounded-2xl border bg-card p-6 text-center lg:sticky lg:top-10 lg:col-start-2 lg:row-span-2 lg:row-start-1">
|
||||
<PugMascot mood="alert" size={112} />
|
||||
<h2 className="m-0 text-xl font-semibold">Начать — одна минута</h2>
|
||||
<p className="m-0 text-sm text-muted-foreground">Вход через eGov или Google. Первый вход сам создаёт учётку — регистрироваться отдельно не нужно.</p>
|
||||
<Flash error={error} />
|
||||
<EgovSign purpose="login" next={safeNext(next)} label="Войти через eGov" />
|
||||
{googleEnabled() && <GoogleSignIn purpose="login" next={safeNext(next)} label="Войти через Google" />}
|
||||
<p className="m-0 text-xs text-muted-foreground lg:hidden">Вы с телефона? Войти можно и отсюда, но управлять фабрикой удобнее с ноутбука.</p>
|
||||
<h2 className="m-0 text-xl font-semibold">{t("Начать — одна минута")}</h2>
|
||||
<p className="m-0 text-sm text-muted-foreground">{t("Вход через eGov или Google. Первый вход сам создаёт учётку — регистрироваться отдельно не нужно.")}</p>
|
||||
<Flash error={error ? t.text(error) : undefined} />
|
||||
<EgovSign purpose="login" next={safeNext(next)} label={t("Войти через eGov")} />
|
||||
{googleEnabled() && <GoogleSignIn purpose="login" next={safeNext(next)} label={t("Войти через Google")} />}
|
||||
<p className="m-0 text-xs text-muted-foreground lg:hidden">{t("Вы с телефона? Войти можно и отсюда, но управлять фабрикой удобнее с ноутбука.")}</p>
|
||||
</aside>
|
||||
|
||||
<div className="flex flex-col gap-9 lg:col-start-1 lg:row-start-2">
|
||||
<section aria-labelledby="why" className="flex flex-col gap-3">
|
||||
<h2 id="why" className="m-0 text-sm font-semibold tracking-wide text-muted-foreground uppercase">Зачем это вам</h2>
|
||||
<h2 id="why" className="m-0 text-sm font-semibold tracking-wide text-muted-foreground uppercase">{t("Зачем это вам")}</h2>
|
||||
<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}
|
||||
<Check className="size-4 shrink-0 text-ok" /> {t(w.title)}
|
||||
</span>
|
||||
<span className="text-sm text-muted-foreground">{w.text}</span>
|
||||
<span className="text-sm text-muted-foreground">{t(w.text)}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<section aria-labelledby="how" className="flex flex-col gap-3">
|
||||
<h2 id="how" className="m-0 text-sm font-semibold tracking-wide text-muted-foreground uppercase">Как это работает — пять шагов</h2>
|
||||
<h2 id="how" className="m-0 text-sm font-semibold tracking-wide text-muted-foreground uppercase">{t("Как это работает — пять шагов")}</h2>
|
||||
<ol className="m-0 flex list-none flex-col gap-2 p-0">
|
||||
{STEPS.map((s, i) => (
|
||||
<li key={s.title} className="flex items-start gap-3 rounded-xl border bg-card px-4 py-3">
|
||||
@ -81,8 +86,8 @@ export default async function Login({ searchParams }: { searchParams: Promise<{
|
||||
{i + 1}
|
||||
</span>
|
||||
<span className="flex min-w-0 flex-col">
|
||||
<span className="font-medium">{s.title}</span>
|
||||
<span className="text-sm text-muted-foreground">{s.text}</span>
|
||||
<span className="font-medium">{t(s.title)}</span>
|
||||
<span className="text-sm text-muted-foreground">{t(s.text)}</span>
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
@ -90,11 +95,11 @@ export default async function Login({ searchParams }: { searchParams: Promise<{
|
||||
</section>
|
||||
|
||||
<section aria-labelledby="need" className="flex flex-col gap-3">
|
||||
<h2 id="need" className="m-0 text-sm font-semibold tracking-wide text-muted-foreground uppercase">Что понадобится</h2>
|
||||
<h2 id="need" className="m-0 text-sm font-semibold tracking-wide text-muted-foreground uppercase">{t("Что понадобится")}</h2>
|
||||
<ul className="m-0 grid list-none gap-2 p-0 sm:grid-cols-2">
|
||||
{NEED.map((n) => (
|
||||
<li key={n.text} className="flex items-start gap-2.5 text-sm">
|
||||
<n.icon className="mt-0.5 size-4 shrink-0 text-primary" /> {n.text}
|
||||
<n.icon className="mt-0.5 size-4 shrink-0 text-primary" /> {t(n.text)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
@ -1,11 +1,14 @@
|
||||
import type { MetadataRoute } from "next";
|
||||
import { PRODUCT_NAME } from "@peppa/shared/i18n";
|
||||
import { getT } from "@/lib/i18n";
|
||||
|
||||
/** Installable as an app (PEP-55): Chrome «Установить Пеппу», badge on the app icon. */
|
||||
export default function manifest(): MetadataRoute.Manifest {
|
||||
export default async function manifest(): Promise<MetadataRoute.Manifest> {
|
||||
const t = await getT();
|
||||
return {
|
||||
name: "Peppa — софтвейр-фабрика",
|
||||
short_name: "Peppa",
|
||||
description: "Проекты, стори и агенты",
|
||||
name: PRODUCT_NAME,
|
||||
short_name: PRODUCT_NAME,
|
||||
description: t("Проекты, стори и агенты"),
|
||||
start_url: "/",
|
||||
scope: "/",
|
||||
display: "standalone",
|
||||
|
||||
@ -6,6 +6,7 @@ import { approve, deny } from "./actions";
|
||||
import { Brand } from "@/components/Brand";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card } from "@/components/ui/card";
|
||||
import { getT } from "@/lib/i18n";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
@ -30,32 +31,33 @@ export default async function Authorize({ searchParams }: { searchParams: Promis
|
||||
} catch (e) {
|
||||
error = e instanceof OAuthError ? e.message : (e as Error).message;
|
||||
}
|
||||
const t = await getT();
|
||||
const host = p.redirect_uri ? new URL(p.redirect_uri).host : "";
|
||||
return (
|
||||
<main className="grid min-h-dvh place-items-center px-4">
|
||||
<Card className="w-full max-w-md gap-4 p-6">
|
||||
<Brand />
|
||||
{error || !client ? (
|
||||
<p role="alert" className="m-0 rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm">Запрос авторизации некорректен: {error}</p>
|
||||
<p role="alert" className="m-0 rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm">{t("Запрос авторизации некорректен: {error}", { error: t.text(error ?? "") })}</p>
|
||||
) : (
|
||||
<>
|
||||
<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> {t("просит доступ к Пеппе от имени")} <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>{t("видеть ваши проекты, эпики, стори и вопросы агентов;")}</li>
|
||||
<li>{t("создавать стори и двигать карточки — перенос в «В работе» запускает агента;")}</li>
|
||||
<li>{t("отвечать на вопросы агентов и принимать ревью.")}</li>
|
||||
</ul>
|
||||
<p className="m-0 text-xs text-muted-foreground">Отозвать доступ можно в «Настройки → Подключённые приложения».</p>
|
||||
<p className="m-0 text-xs text-muted-foreground">{t("Отозвать доступ можно в «Настройки → Подключённые приложения».")}</p>
|
||||
<div className="flex gap-2">
|
||||
<form action={approve}>
|
||||
<Hidden p={p} />
|
||||
<Button variant="default">Разрешить</Button>
|
||||
<Button variant="default">{t("Разрешить")}</Button>
|
||||
</form>
|
||||
<form action={deny}>
|
||||
<Hidden p={p} />
|
||||
<Button>Отклонить</Button>
|
||||
<Button>{t("Отклонить")}</Button>
|
||||
</form>
|
||||
</div>
|
||||
</>
|
||||
|
||||
@ -34,6 +34,8 @@ import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import { intlLocale, type Locale, type Translator } from "@peppa/shared/i18n";
|
||||
|
||||
const tone = (pct: number) => (pct >= 90 ? "bg-destructive" : pct >= 70 ? "bg-warn" : "bg-primary");
|
||||
|
||||
@ -45,20 +47,20 @@ function Meter({ pct, className }: { pct: number; className?: string }) {
|
||||
);
|
||||
}
|
||||
|
||||
function WindowCell({ label, w }: { label: string; w: WindowView | null }) {
|
||||
function WindowCell({ label, w, t }: { label: string; w: WindowView | null; t: Translator }) {
|
||||
if (!w) return null;
|
||||
return (
|
||||
<span className="flex items-center gap-1.5 whitespace-nowrap">
|
||||
<span className="text-muted-foreground">{label}</span>
|
||||
{w.reset ? (
|
||||
<span className="text-muted-foreground">сброшено</span>
|
||||
<span className="text-muted-foreground">{t("сброшено")}</span>
|
||||
) : (
|
||||
<>
|
||||
<Meter pct={w.pct!} />
|
||||
<span className="font-mono tabular-nums">{Math.round(w.pct!)}%</span>
|
||||
{w.resetsAt && (
|
||||
<span className="text-muted-foreground">
|
||||
сброс <LocalTime iso={w.resetsAt.toISOString()} />
|
||||
{t("сброс")} <LocalTime iso={w.resetsAt.toISOString()} />
|
||||
</span>
|
||||
)}
|
||||
</>
|
||||
@ -67,45 +69,48 @@ function WindowCell({ label, w }: { label: string; w: WindowView | null }) {
|
||||
);
|
||||
}
|
||||
|
||||
function accountTitle(a: AccountUsage): string {
|
||||
const w = (l: string, v: WindowView | null) => (!v ? `${l}: нет данных` : v.reset ? `${l}: сброшено` : `${l}: ${Math.round(v.pct!)}%`);
|
||||
return `${a.name} — ${w("5 ч", a.fiveHour)}, ${w("7 д", a.sevenDay)}${a.limitedUntil ? ", в лимите" : ""}${a.at ? `, обновлено ${a.at.toLocaleString("ru-RU")}` : ""}`;
|
||||
function accountTitle(a: AccountUsage, t: Translator): string {
|
||||
const w = (l: string, v: WindowView | null) => (!v ? t("{label}: нет данных", { label: l }) : v.reset ? t("{label}: сброшено", { label: l }) : `${l}: ${Math.round(v.pct!)}%`);
|
||||
const limited = a.limitedUntil ? ", " + t("в лимите") : "";
|
||||
const updated = a.at ? ", " + t("обновлено {at}", { at: a.at.toLocaleString(intlLocale(t.locale)) }) : "";
|
||||
return t.text(a.name) + " — " + w(t("5 ч"), a.fiveHour) + ", " + w(t("7 д"), a.sevenDay) + limited + updated;
|
||||
}
|
||||
|
||||
/** PEP-5: thin bar above every page — the most loaded limit window of the user's accounts. */
|
||||
export function UsageStrip({ accounts, admin }: { accounts: AccountUsage[]; admin: boolean }) {
|
||||
export async function UsageStrip({ accounts, admin }: { accounts: AccountUsage[]; admin: boolean }) {
|
||||
const t = await getT();
|
||||
const withData = accounts.filter((a) => a.fiveHour || a.sevenDay || a.limitedUntil);
|
||||
const top = withData[0];
|
||||
const limited = accounts.filter((a) => a.limitedUntil);
|
||||
return (
|
||||
<div
|
||||
role="status"
|
||||
aria-label="Лимиты подписок"
|
||||
title={accounts.map(accountTitle).join("\n") || undefined}
|
||||
aria-label={t("Лимиты подписок")}
|
||||
title={accounts.map((a) => accountTitle(a, t)).join("\n") || undefined}
|
||||
className="flex min-h-8 flex-wrap items-center gap-x-4 gap-y-1 border-b bg-sidebar/40 px-4 py-1 text-xs md:px-8"
|
||||
>
|
||||
<span className="flex items-center gap-1.5 text-muted-foreground">
|
||||
<Gauge className="size-3.5" />
|
||||
Лимиты
|
||||
{t("Лимиты")}
|
||||
</span>
|
||||
{!top ? (
|
||||
<span className="text-muted-foreground">нет данных о лимитах</span>
|
||||
<span className="text-muted-foreground">{t("нет данных о лимитах")}</span>
|
||||
) : (
|
||||
<>
|
||||
{withData.length > 1 && <span className="font-medium">{top.name}</span>}
|
||||
<WindowCell label="5 ч" w={top.fiveHour} />
|
||||
<WindowCell label="7 д" w={top.sevenDay} />
|
||||
{top.stale && top.at && <span className="text-warn">устарело ({ago(top.at)})</span>}
|
||||
{withData.length > 1 && <span className="font-medium">{t.text(top.name)}</span>}
|
||||
<WindowCell label={t("5 ч")} w={top.fiveHour} t={t} />
|
||||
<WindowCell label={t("7 д")} w={top.sevenDay} t={t} />
|
||||
{top.stale && top.at && <span className="text-warn">{t("устарело ({ago})", { ago: ago(top.at, t) })}</span>}
|
||||
</>
|
||||
)}
|
||||
{limited.map((a) => (
|
||||
<span key={a.key} className="whitespace-nowrap text-destructive">
|
||||
{a.name}: лимит до <LocalTime iso={a.limitedUntil!.toISOString()} />
|
||||
{t.text(a.name)}: {t("лимит до")} <LocalTime iso={a.limitedUntil!.toISOString()} />
|
||||
</span>
|
||||
))}
|
||||
{withData.length > 1 && (
|
||||
<span className="text-muted-foreground">
|
||||
+{withData.length - 1} {admin ? <Link href="/subscriptions" className="text-muted-foreground underline-offset-2 hover:text-foreground">подписки</Link> : "аккаунт"}
|
||||
+{withData.length - 1} {admin ? <Link href="/subscriptions" className="text-muted-foreground underline-offset-2 hover:text-foreground">{t("подписки")}</Link> : t("аккаунт")}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
@ -115,15 +120,16 @@ export function UsageStrip({ accounts, admin }: { accounts: AccountUsage[]; admi
|
||||
export const usagePeakSort = (a: AccountUsage[]) => [...a].sort((x, y) => accountPeak(y) - accountPeak(x));
|
||||
|
||||
/** PEP-5: one line under a runner card. */
|
||||
export function SessionUsageLine({ usage, provider }: { usage: SessionUsage | null; provider: string }) {
|
||||
export async function SessionUsageLine({ usage, provider }: { usage: SessionUsage | null; provider: string }) {
|
||||
const tr = await getT();
|
||||
const t = usageTotals(usage);
|
||||
if (!t.hasData) return <p className="m-0 text-xs text-muted-foreground">Расход: нет данных{provider !== "claude" ? ` (${provider} не сообщает)` : ""}</p>;
|
||||
if (!t.hasData) return <p className="m-0 text-xs text-muted-foreground">{tr("Расход: нет данных")}{provider !== "claude" ? " (" + tr("{provider} не сообщает", { provider }) + ")" : ""}</p>;
|
||||
return (
|
||||
<p className="m-0 flex flex-wrap items-center gap-x-3 text-xs text-muted-foreground">
|
||||
<span>Расход: {describeUsage(usage)}</span>
|
||||
<span>{tr("Расход: {usage}", { usage: tr.text(describeUsage(usage)) })}</span>
|
||||
{t.context && (
|
||||
<span className="flex items-center gap-1.5">
|
||||
контекст <Meter pct={t.context.pct} className="w-12" /> {fmtTokens(t.context.used)} / {fmtTokens(t.context.size)}
|
||||
{tr("контекст")} <Meter pct={t.context.pct} className="w-12" /> {tr.text(fmtTokens(t.context.used))} / {tr.text(fmtTokens(t.context.size))}
|
||||
</span>
|
||||
)}
|
||||
</p>
|
||||
@ -132,9 +138,10 @@ export function SessionUsageLine({ usage, provider }: { usage: SessionUsage | nu
|
||||
|
||||
// ── PEP-43: budget ────────────────────────────────────────────────────────────────
|
||||
const spentOf = (v: TaskBudgetView, k: (typeof BUDGET_KINDS)[number]) => (k === "costUsd" ? (v.spend.costUsd ?? 0) : v.spend[k]);
|
||||
const spentText = (v: TaskBudgetView, k: (typeof BUDGET_KINDS)[number]) => (k === "costUsd" ? fmtCost(v.spend.usage) : formatBudgetValue(k, v.spend[k]));
|
||||
const spentText = (v: TaskBudgetView, k: (typeof BUDGET_KINDS)[number], t: Translator) => (k === "costUsd" ? fmtCost(v.spend.usage) : t.text(formatBudgetValue(k, v.spend[k])));
|
||||
|
||||
export function BudgetFields({ budget, placeholder }: { budget: Budget; placeholder?: Budget }) {
|
||||
export async function BudgetFields({ budget, placeholder }: { budget: Budget; placeholder?: Budget }) {
|
||||
const t = await getT();
|
||||
const field = (k: (typeof BUDGET_KINDS)[number], label: string, step = "1") => (
|
||||
<label className="flex flex-col gap-1 text-xs text-muted-foreground">
|
||||
{label}
|
||||
@ -152,46 +159,47 @@ export function BudgetFields({ budget, placeholder }: { budget: Budget; placehol
|
||||
);
|
||||
return (
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
{field("minutes", "Минуты раннеров")}
|
||||
{field("tokens", "Токены")}
|
||||
{field("restarts", "Перезапуски")}
|
||||
{field("costUsd", "Стоимость, $", "0.01")}
|
||||
{field("minutes", t("Минуты раннеров"))}
|
||||
{field("tokens", t("Токены"))}
|
||||
{field("restarts", t("Перезапуски"))}
|
||||
{field("costUsd", t("Стоимость, $"), "0.01")}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function BudgetPanel({ view, taskId, projectBudget, back, action, paused }: { view: TaskBudgetView; taskId: number; projectBudget: Budget; back: string; action: (f: FormData) => Promise<void>; paused: boolean }) {
|
||||
export async function BudgetPanel({ view, taskId, projectBudget, back, action, paused }: { view: TaskBudgetView; taskId: number; projectBudget: Budget; back: string; action: (f: FormData) => Promise<void>; paused: boolean }) {
|
||||
const t = await getT();
|
||||
return (
|
||||
<div className="flex flex-col gap-2.5">
|
||||
{paused && <p className="m-0 rounded-md border border-destructive/40 bg-destructive/10 px-2.5 py-1.5 text-xs text-destructive">Бюджет исчерпан — агент на паузе до вашего решения (вопрос во «Входящих» или новый бюджет ниже).</p>}
|
||||
{paused && <p className="m-0 rounded-md border border-destructive/40 bg-destructive/10 px-2.5 py-1.5 text-xs text-destructive">{t("Бюджет исчерпан — агент на паузе до вашего решения (вопрос во «Входящих» или новый бюджет ниже).")}</p>}
|
||||
<ul className="m-0 flex list-none flex-col gap-1.5 p-0 text-sm">
|
||||
{BUDGET_KINDS.map((k) => {
|
||||
const limit = view.budget[k];
|
||||
const pct = limit ? (spentOf(view, k) / limit) * 100 : null;
|
||||
return (
|
||||
<li key={k} className="flex items-center gap-2">
|
||||
<span className="w-24 shrink-0 text-xs text-muted-foreground">{BUDGET_LABELS[k]}</span>
|
||||
<span className="font-mono text-xs tabular-nums">{spentText(view, k)}</span>
|
||||
<span className="text-xs text-muted-foreground">из {formatBudgetValue(k, limit)}</span>
|
||||
<span className="w-24 shrink-0 text-xs text-muted-foreground">{t.text(BUDGET_LABELS[k])}</span>
|
||||
<span className="font-mono text-xs tabular-nums">{spentText(view, k, t)}</span>
|
||||
<span className="text-xs text-muted-foreground">{t("из {value}", { value: t.text(formatBudgetValue(k, limit)) })}</span>
|
||||
{pct != null && <Meter pct={pct} className="ml-auto w-14" />}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
<p className="m-0 text-xs text-muted-foreground">
|
||||
{view.source === "task" ? "Свой бюджет стори." : view.source === "project" ? "Бюджет проекта по умолчанию." : "Без бюджета."} Сессий {view.spend.sessions}
|
||||
{view.spend.costEstimated && " · ≈ — оценка по прайсу API"}.
|
||||
{view.source === "task" ? t("Свой бюджет стори.") : view.source === "project" ? t("Бюджет проекта по умолчанию.") : t("Без бюджета.")} {t("Сессий {n}", { n: view.spend.sessions })}
|
||||
{view.spend.costEstimated && " · ≈ — " + t("оценка по прайсу API")}.
|
||||
</p>
|
||||
<details className="text-sm">
|
||||
<summary className="cursor-pointer text-xs text-muted-foreground">Изменить бюджет стори</summary>
|
||||
<summary className="cursor-pointer text-xs text-muted-foreground">{t("Изменить бюджет стори")}</summary>
|
||||
<form action={action} className="mt-2 flex flex-col gap-2">
|
||||
<Hidden fields={{ taskId, back }} />
|
||||
<BudgetFields budget={view.source === "task" ? view.budget : {}} placeholder={projectBudget} />
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button size="sm" name="mode" value="set">Сохранить</Button>
|
||||
<Button size="sm" variant="outline" name="mode" value="unlimited">Без лимита</Button>
|
||||
<Button size="sm" name="mode" value="set">{t("Сохранить")}</Button>
|
||||
<Button size="sm" variant="outline" name="mode" value="unlimited">{t("Без лимита")}</Button>
|
||||
{view.source === "task" && (
|
||||
<Button size="sm" variant="ghost" name="mode" value="inherit">Как в проекте</Button>
|
||||
<Button size="sm" variant="ghost" name="mode" value="inherit">{t("Как в проекте")}</Button>
|
||||
)}
|
||||
</div>
|
||||
</form>
|
||||
@ -200,14 +208,15 @@ export function BudgetPanel({ view, taskId, projectBudget, back, action, paused
|
||||
);
|
||||
}
|
||||
|
||||
export function ProjectBudgetPanel({ projectId, budget, back, action }: { projectId: number; budget: Budget; back: string; action: (f: FormData) => Promise<void> }) {
|
||||
export async function ProjectBudgetPanel({ projectId, budget, back, action }: { projectId: number; budget: Budget; back: string; action: (f: FormData) => Promise<void> }) {
|
||||
const t = await getT();
|
||||
return (
|
||||
<form action={action} className="flex flex-col gap-2">
|
||||
<Hidden fields={{ projectId, back }} />
|
||||
<BudgetFields budget={budget} />
|
||||
<Button size="sm" className="self-start">Сохранить</Button>
|
||||
<Button size="sm" className="self-start">{t("Сохранить")}</Button>
|
||||
<p className="m-0 text-xs text-muted-foreground">
|
||||
Бюджет по умолчанию для каждой стори; пусто — без предела. Превышение ставит стори на паузу (ход прерывается, разговор сохраняется) и присылает вопрос: продлить, снять лимит или остановить.
|
||||
{t("Бюджет по умолчанию для каждой стори; пусто — без предела. Превышение ставит стори на паузу (ход прерывается, разговор сохраняется) и присылает вопрос: продлить, снять лимит или остановить.")}
|
||||
</p>
|
||||
</form>
|
||||
);
|
||||
@ -223,7 +232,7 @@ function Stat({ label, value, hint }: { label: string; value: ReactNode; hint?:
|
||||
);
|
||||
}
|
||||
|
||||
const day = (d: Date) => d.toLocaleDateString("ru-RU", { day: "2-digit", month: "2-digit" });
|
||||
const day = (d: Date, locale: Locale) => d.toLocaleDateString(intlLocale(locale), { day: "2-digit", month: "2-digit" });
|
||||
|
||||
function Bar({ value, max }: { value: number; max: number }) {
|
||||
return (
|
||||
@ -233,52 +242,55 @@ function Bar({ value, max }: { value: number; max: number }) {
|
||||
);
|
||||
}
|
||||
|
||||
export function MetricsTab({ m, projectKey }: { m: ProjectMetrics; projectKey: string }) {
|
||||
export async function MetricsTab({ m, projectKey }: { m: ProjectMetrics; projectKey: string }) {
|
||||
const t = await getT();
|
||||
const hours = (h: number | null) => t.text(fmtHours(h));
|
||||
const tokens = (n: number) => t.text(fmtTokens(n));
|
||||
const s = m.summary;
|
||||
const maxDone = Math.max(...m.weekly.map((w) => w.done), 0);
|
||||
const maxHours = Math.max(...m.weekly.map((w) => w.runnerHours), 0);
|
||||
const cols: Array<[string, (b: MetricsBucket) => ReactNode]> = [
|
||||
["Цикл", (b) => fmtHours(b.cycleHoursMedian)],
|
||||
["1-й проход", (b) => fmtPct(b.firstPassRate)],
|
||||
["Возвраты", (b) => fmtPct(b.reviewReturnRate)],
|
||||
["Вопр./стори", (b) => (b.questionsPerStory == null ? "—" : b.questionsPerStory.toFixed(1))],
|
||||
["Ждали PM", (b) => fmtHours(b.pmWaitHours)],
|
||||
["Лимиты", (b) => b.limitHits],
|
||||
["Токены", (b) => fmtTokens(b.spend.tokens)],
|
||||
["Стоимость", (b) => fmtCost(b.spend.usage)],
|
||||
[t("Цикл"), (b) => hours(b.cycleHoursMedian)],
|
||||
[t("1-й проход"), (b) => fmtPct(b.firstPassRate)],
|
||||
[t("Возвраты"), (b) => fmtPct(b.reviewReturnRate)],
|
||||
[t("Вопр./стори"), (b) => (b.questionsPerStory == null ? "—" : b.questionsPerStory.toFixed(1))],
|
||||
[t("Ждали PM"), (b) => hours(b.pmWaitHours)],
|
||||
[t("Лимиты"), (b) => b.limitHits],
|
||||
[t("Токены"), (b) => tokens(b.spend.tokens)],
|
||||
[t("Стоимость"), (b) => fmtCost(b.spend.usage)],
|
||||
];
|
||||
return (
|
||||
<div className="flex flex-col gap-8">
|
||||
<div className="flex flex-wrap items-center gap-2 text-sm">
|
||||
<span className="text-muted-foreground">Период:</span>
|
||||
<span className="text-muted-foreground">{t("Период:")}</span>
|
||||
{[4, 8, 12].map((w) => (
|
||||
<Link key={w} href={`/p/${projectKey}?tab=metrics&weeks=${w}`} aria-current={m.weeks === w ? "page" : undefined} className={cn("rounded-md border px-2 py-0.5 text-xs", m.weeks === w ? "border-primary text-foreground" : "text-muted-foreground")}>
|
||||
{w} нед.
|
||||
{t("{n} нед.", { n: w })}
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-2 sm:grid-cols-3 lg:grid-cols-5">
|
||||
<Stat label="Готово стори" value={s.done} />
|
||||
<Stat label="Время цикла (медиана)" value={fmtHours(s.cycleHoursMedian)} hint="От «В работу» до «Готово»" />
|
||||
<Stat label="Приняты с первого раза" value={fmtPct(s.firstPassRate)} hint="Без возврата из ревью и без замечаний ревьюера" />
|
||||
<Stat label="Возвраты с ревью" value={fmtPct(s.reviewReturnRate)} />
|
||||
<Stat label="Вопросов PM на стори" value={s.questionsPerStory == null ? "—" : s.questionsPerStory.toFixed(1)} hint="Вопросы, разрешения и одобрения; уведомления не считаются" />
|
||||
<Stat label="Часы раннеров" value={fmtHours(s.runnerHours)} />
|
||||
<Stat label="Агенты ждали PM" value={fmtHours(s.pmWaitHours)} hint="Сумма времени от вопроса агента до ответа человека" />
|
||||
<Stat label="Упоры в лимит" value={s.limitHits} />
|
||||
<Stat label="Токены" value={fmtTokens(s.spend.tokens)} />
|
||||
<Stat label="Стоимость" value={fmtCost(s.spend.usage)} hint="≈ — оценка по прайсу API, если агент не сообщил стоимость" />
|
||||
<Stat label={t("Готово стори")} value={s.done} />
|
||||
<Stat label={t("Время цикла (медиана)")} value={hours(s.cycleHoursMedian)} hint={t("От «В работу» до «Готово»")} />
|
||||
<Stat label={t("Приняты с первого раза")} value={fmtPct(s.firstPassRate)} hint={t("Без возврата из ревью и без замечаний ревьюера")} />
|
||||
<Stat label={t("Возвраты с ревью")} value={fmtPct(s.reviewReturnRate)} />
|
||||
<Stat label={t("Вопросов PM на стори")} value={s.questionsPerStory == null ? "—" : s.questionsPerStory.toFixed(1)} hint={t("Вопросы, разрешения и одобрения; уведомления не считаются")} />
|
||||
<Stat label={t("Часы раннеров")} value={hours(s.runnerHours)} />
|
||||
<Stat label={t("Агенты ждали PM")} value={hours(s.pmWaitHours)} hint={t("Сумма времени от вопроса агента до ответа человека")} />
|
||||
<Stat label={t("Упоры в лимит")} value={s.limitHits} />
|
||||
<Stat label={t("Токены")} value={tokens(s.spend.tokens)} />
|
||||
<Stat label={t("Стоимость")} value={fmtCost(s.spend.usage)} hint={t("≈ — оценка по прайсу API, если агент не сообщил стоимость")} />
|
||||
</div>
|
||||
|
||||
<section className="flex flex-col gap-2">
|
||||
<h2 className="m-0 text-[15px] font-semibold">По неделям</h2>
|
||||
<h2 className="m-0 text-[15px] font-semibold">{t("По неделям")}</h2>
|
||||
<div className="overflow-x-auto rounded-lg border">
|
||||
<table className="w-full min-w-[760px] border-collapse text-sm">
|
||||
<thead className="bg-muted/40 text-xs text-muted-foreground">
|
||||
<tr>
|
||||
<th className="px-3 py-2 text-left font-medium">Неделя</th>
|
||||
<th className="px-3 py-2 text-left font-medium">Готово</th>
|
||||
<th className="px-3 py-2 text-left font-medium">Раннеры</th>
|
||||
<th className="px-3 py-2 text-left font-medium">{t("Неделя")}</th>
|
||||
<th className="px-3 py-2 text-left font-medium">{t("Готово")}</th>
|
||||
<th className="px-3 py-2 text-left font-medium">{t("Раннеры")}</th>
|
||||
{cols.map(([h]) => (
|
||||
<th key={h} className="px-3 py-2 text-right font-medium whitespace-nowrap">{h}</th>
|
||||
))}
|
||||
@ -287,12 +299,12 @@ export function MetricsTab({ m, projectKey }: { m: ProjectMetrics; projectKey: s
|
||||
<tbody>
|
||||
{[...m.weekly].reverse().map((w) => (
|
||||
<tr key={w.from.toISOString()} className="border-t">
|
||||
<td className="px-3 py-1.5 font-mono text-xs whitespace-nowrap">{day(w.from)}</td>
|
||||
<td className="px-3 py-1.5 font-mono text-xs whitespace-nowrap">{day(w.from, t.locale)}</td>
|
||||
<td className="px-3 py-1.5">
|
||||
<span className="flex items-center gap-2"><span className="w-5 font-mono tabular-nums">{w.done}</span><Bar value={w.done} max={maxDone} /></span>
|
||||
</td>
|
||||
<td className="px-3 py-1.5">
|
||||
<span className="flex items-center gap-2"><span className="w-16 shrink-0 font-mono text-xs whitespace-nowrap tabular-nums">{fmtHours(w.runnerHours)}</span><Bar value={w.runnerHours} max={maxHours} /></span>
|
||||
<span className="flex items-center gap-2"><span className="w-16 shrink-0 font-mono text-xs whitespace-nowrap tabular-nums">{hours(w.runnerHours)}</span><Bar value={w.runnerHours} max={maxHours} /></span>
|
||||
</td>
|
||||
{cols.map(([h, f]) => (
|
||||
<td key={h} className="px-3 py-1.5 text-right font-mono text-xs tabular-nums whitespace-nowrap">{f(w)}</td>
|
||||
@ -306,29 +318,29 @@ export function MetricsTab({ m, projectKey }: { m: ProjectMetrics; projectKey: s
|
||||
|
||||
<div className="grid gap-8 lg:grid-cols-2">
|
||||
<section className="flex flex-col gap-2">
|
||||
<h2 className="m-0 text-[15px] font-semibold">По агентам</h2>
|
||||
<h2 className="m-0 text-[15px] font-semibold">{t("По агентам")}</h2>
|
||||
{m.byProvider.length === 0 ? (
|
||||
<Empty>Сессий за период не было.</Empty>
|
||||
<Empty>{t("Сессий за период не было.")}</Empty>
|
||||
) : (
|
||||
<SimpleTable
|
||||
head={["Агент", "Сессий", "Стори", "Часы", "Токены", "Стоимость"]}
|
||||
rows={m.byProvider.map((p) => [PROVIDER_NAMES[p.provider as keyof typeof PROVIDER_NAMES] ?? p.provider, p.sessions, p.stories, fmtHours(p.hours), fmtTokens(p.spend.tokens), fmtCost(p.spend.usage)])}
|
||||
head={[t("Агент"), t("Сессий"), t("Стори"), t("Часы"), t("Токены"), t("Стоимость")]}
|
||||
rows={m.byProvider.map((p) => [PROVIDER_NAMES[p.provider as keyof typeof PROVIDER_NAMES] ?? p.provider, p.sessions, p.stories, hours(p.hours), tokens(p.spend.tokens), fmtCost(p.spend.usage)])}
|
||||
/>
|
||||
)}
|
||||
</section>
|
||||
<section className="flex flex-col gap-2">
|
||||
<h2 className="m-0 text-[15px] font-semibold">По эпикам (всё время)</h2>
|
||||
<h2 className="m-0 text-[15px] font-semibold">{t("По эпикам (всё время)")}</h2>
|
||||
{m.byEpic.length === 0 ? (
|
||||
<Empty>Стори нет.</Empty>
|
||||
<Empty>{t("Стори нет.")}</Empty>
|
||||
) : (
|
||||
<SimpleTable
|
||||
head={["Эпик", "Стори", "Готово", "Время", "Токены", "Стоимость"]}
|
||||
head={[t("Эпик"), t("Стори"), t("Готово"), t("Время"), t("Токены"), t("Стоимость")]}
|
||||
rows={m.byEpic.map((e) => [
|
||||
e.goalId ? <Link key="t" href={`/p/${projectKey}?epic=${e.goalId}`}>{e.title}</Link> : e.title,
|
||||
e.stories,
|
||||
e.done,
|
||||
fmtHours(e.spend.minutes / 60),
|
||||
fmtTokens(e.spend.tokens),
|
||||
hours(e.spend.minutes / 60),
|
||||
tokens(e.spend.tokens),
|
||||
fmtCost(e.spend.usage),
|
||||
])}
|
||||
/>
|
||||
@ -367,17 +379,18 @@ function SimpleTable({ head, rows }: { head: string[]; rows: ReactNode[][] }) {
|
||||
// ── PEP-48: journal ───────────────────────────────────────────────────────────────
|
||||
const KIND_TONE = { user: "info", agent: "ok", system: "muted" } as const;
|
||||
|
||||
export function JournalList({ entries, showProject = true }: { entries: JournalEntry[]; showProject?: boolean }) {
|
||||
if (!entries.length) return <Empty>Действий нет.</Empty>;
|
||||
export async function JournalList({ entries, showProject = true }: { entries: JournalEntry[]; showProject?: boolean }) {
|
||||
const t = await getT();
|
||||
if (!entries.length) return <Empty>{t("Действий нет.")}</Empty>;
|
||||
return (
|
||||
<ol className="m-0 flex list-none flex-col divide-y rounded-lg border p-0">
|
||||
{entries.map((e) => {
|
||||
const who = actorLabel(e);
|
||||
const line = eventLine(e);
|
||||
const who = t.text(actorLabel(e));
|
||||
const line = eventLine(e, t);
|
||||
return (
|
||||
<li key={e.id} className="flex flex-wrap items-baseline gap-x-2.5 gap-y-1 px-3 py-2 text-sm">
|
||||
<span className="w-14 shrink-0 font-mono text-xs text-muted-foreground">{ago(e.createdAt)}</span>
|
||||
{e.actorKind ? <Badge variant={KIND_TONE[e.actorKind]}>{who}</Badge> : <Badge variant="muted">автор не записан</Badge>}
|
||||
<span className="w-14 shrink-0 font-mono text-xs text-muted-foreground">{ago(e.createdAt, t)}</span>
|
||||
{e.actorKind ? <Badge variant={KIND_TONE[e.actorKind]}>{who}</Badge> : <Badge variant="muted">{t("автор не записан")}</Badge>}
|
||||
<span className="font-mono text-xs text-primary">{e.type}</span>
|
||||
{showProject && !e.taskKey && <Link href={`/p/${e.projectKey}`} className="font-mono text-xs">{e.projectKey}</Link>}
|
||||
{e.taskKey && <Link href={`/t/${e.taskKey}`} className="font-mono text-xs">{e.taskKey}</Link>}
|
||||
@ -389,31 +402,32 @@ export function JournalList({ entries, showProject = true }: { entries: JournalE
|
||||
);
|
||||
}
|
||||
|
||||
export function JournalFilters({ action, projects, value }: { action: string; projects?: Array<{ key: string; name: string }>; value: { project?: string; actor?: string; channel?: string; tab?: string } }) {
|
||||
export async function JournalFilters({ action, projects, value }: { action: string; projects?: Array<{ key: string; name: string }>; value: { project?: string; actor?: string; channel?: string; tab?: string } }) {
|
||||
const t = await getT();
|
||||
return (
|
||||
<form action={action} method="get" className="flex flex-wrap items-center gap-2 text-sm">
|
||||
{value.tab && <input type="hidden" name="tab" value={value.tab} />}
|
||||
{projects && (
|
||||
<select name="project" defaultValue={value.project ?? ""} aria-label="Проект" className="h-8 rounded-md border bg-background px-2 text-sm">
|
||||
<option value="">Все проекты</option>
|
||||
<select name="project" defaultValue={value.project ?? ""} aria-label={t("Проект")} className="h-8 rounded-md border bg-background px-2 text-sm">
|
||||
<option value="">{t("Все проекты")}</option>
|
||||
{projects.map((p) => (
|
||||
<option key={p.key} value={p.key}>{p.key} — {p.name}</option>
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
<select name="actor" defaultValue={value.actor ?? ""} aria-label="Кто" className="h-8 rounded-md border bg-background px-2 text-sm">
|
||||
<option value="">Все авторы</option>
|
||||
<select name="actor" defaultValue={value.actor ?? ""} aria-label={t("Кто")} className="h-8 rounded-md border bg-background px-2 text-sm">
|
||||
<option value="">{t("Все авторы")}</option>
|
||||
{Object.entries(ACTOR_KIND_NAMES).map(([k, v]) => (
|
||||
<option key={k} value={k}>{v}</option>
|
||||
<option key={k} value={k}>{t.text(v)}</option>
|
||||
))}
|
||||
</select>
|
||||
<select name="channel" defaultValue={value.channel ?? ""} aria-label="Канал" className="h-8 rounded-md border bg-background px-2 text-sm">
|
||||
<option value="">Все каналы</option>
|
||||
<select name="channel" defaultValue={value.channel ?? ""} aria-label={t("Канал")} className="h-8 rounded-md border bg-background px-2 text-sm">
|
||||
<option value="">{t("Все каналы")}</option>
|
||||
{Object.entries(ACTOR_CHANNEL_NAMES).map(([k, v]) => (
|
||||
<option key={k} value={k}>{v}</option>
|
||||
<option key={k} value={k}>{t.text(v)}</option>
|
||||
))}
|
||||
</select>
|
||||
<Button size="sm" variant="outline">Показать</Button>
|
||||
<Button size="sm" variant="outline">{t("Показать")}</Button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
@ -4,17 +4,19 @@ import { requireUser } from "@/lib/auth";
|
||||
import { activeSessions, inbox } from "@/lib/queries";
|
||||
import { SESSION_STATUS, TONE_BG } from "@/lib/status";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { getT } from "@/lib/i18n";
|
||||
|
||||
/** 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 t = await getT();
|
||||
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={t("Ждут тебя")} count={items.length} href="/" more={t("на Главную")}>
|
||||
{items.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground">Агентам ничего не нужно.</p>
|
||||
<p className="text-sm text-muted-foreground">{t("Агентам ничего не нужно.")}</p>
|
||||
) : (
|
||||
items.slice(0, 6).map((q) => (
|
||||
<Link key={q.id} href={q.taskKey ? `/t/${q.taskKey}` : "/"} className="block rounded-md border border-primary/25 bg-primary/5 px-3 py-2 text-sm text-foreground hover:border-primary/50 hover:no-underline">
|
||||
@ -25,18 +27,18 @@ export async function ActivityAside({ questions = true }: { questions?: boolean
|
||||
)}
|
||||
</PanelSection>
|
||||
)}
|
||||
<PanelSection title="Активные раннеры" count={sessions.length} href="/runners" more="все">
|
||||
<PanelSection title={t("Активные раннеры")} count={sessions.length} href="/runners" more={t("все")}>
|
||||
{sessions.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground">Сейчас ничего не запущено.</p>
|
||||
<p className="text-sm text-muted-foreground">{t("Сейчас ничего не запущено.")}</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">
|
||||
<span className={cn("size-2 shrink-0 rounded-full", TONE_BG[st.tone], s.status === "running" && "animate-pulse")} title={st.label} />
|
||||
<span className={cn("size-2 shrink-0 rounded-full", TONE_BG[st.tone], s.status === "running" && "animate-pulse")} title={t.text(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>
|
||||
<span className="shrink-0 font-mono text-[11px] text-muted-foreground">{ago(s.lastActivityAt)}</span>
|
||||
<span className="shrink-0 font-mono text-[11px] text-muted-foreground">{ago(s.lastActivityAt, t)}</span>
|
||||
</Link>
|
||||
);
|
||||
})
|
||||
|
||||
@ -1,12 +1,16 @@
|
||||
"use client";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useT } from "@/components/I18n";
|
||||
|
||||
const TONES = ["bg-sky-500/20 text-sky-300", "bg-emerald-500/20 text-emerald-300", "bg-amber-500/20 text-amber-300", "bg-fuchsia-500/20 text-fuchsia-300", "bg-rose-500/20 text-rose-300", "bg-violet-500/20 text-violet-300", "bg-teal-500/20 text-teal-300", "bg-orange-500/20 text-orange-300"];
|
||||
|
||||
/** PEP-75: an agent persona — a round initial in its own colour and the name. */
|
||||
export function AgentBadge({ name, className, large = false }: { name: string; className?: string; large?: boolean }) {
|
||||
const t = useT();
|
||||
const tone = TONES[[...name].reduce((a, c) => a + c.codePointAt(0)!, 0) % TONES.length];
|
||||
return (
|
||||
<span className={cn("inline-flex min-w-0 items-center gap-1.5", large ? "text-base font-medium" : "text-xs", className)} title={`Агент ${name}`}>
|
||||
<span className={cn("inline-flex min-w-0 items-center gap-1.5", large ? "text-base font-medium" : "text-xs", className)} title={t("Агент {name}", { name })}>
|
||||
<span aria-hidden className={cn("grid shrink-0 place-items-center rounded-full font-semibold", large ? "size-8 text-sm" : "size-4.5 text-[10px]", tone)}>
|
||||
{[...name][0]}
|
||||
</span>
|
||||
|
||||
@ -5,14 +5,17 @@ import { Hidden } from "@/components/cards";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input, Label, NativeSelect } from "@/components/ui/input";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import { m, type Translator } from "@peppa/shared/i18n";
|
||||
|
||||
const PROVIDER_RU: Record<string, string> = { claude: "Claude Code", codex: "Codex", opencode: "OpenCode" };
|
||||
const inherit = (v: string | number | null | undefined, none = "по умолчанию") => (v == null ? none : `как выше: ${v}`);
|
||||
const inherit = (t: Translator, v: string | number | null | undefined, none = m("по умолчанию")) => (v == null ? t(none) : t("как выше: {n}", { n: typeof v === "string" ? t(v) : v }));
|
||||
|
||||
function ProviderSelect({ name, own, inherited, none }: { name: string; own?: string | null; inherited?: string | null; none?: string }) {
|
||||
async function ProviderSelect({ name, own, inherited, none }: { name: string; own?: string | null; inherited?: string | null; none?: string }) {
|
||||
const t = await getT();
|
||||
return (
|
||||
<NativeSelect name={name} defaultValue={own ?? ""} className="h-8">
|
||||
<option value="">{inherit(inherited ? PROVIDER_RU[inherited] : null, none)}</option>
|
||||
<option value="">{inherit(t, inherited ? PROVIDER_RU[inherited] : null, none)}</option>
|
||||
{AGENT_PROVIDERS.map((p) => (
|
||||
<option key={p} value={p}>{PROVIDER_RU[p]}</option>
|
||||
))}
|
||||
@ -20,93 +23,98 @@ function ProviderSelect({ name, own, inherited, none }: { name: string; own?: st
|
||||
);
|
||||
}
|
||||
|
||||
function EffortSelect({ name, own, inherited }: { name: string; own?: string | null; inherited?: string | null }) {
|
||||
async function EffortSelect({ name, own, inherited }: { name: string; own?: string | null; inherited?: string | null }) {
|
||||
const t = await getT();
|
||||
return (
|
||||
<NativeSelect name={name} defaultValue={own ?? ""} className="h-8">
|
||||
<option value="">{inherit(inherited ? AGENT_EFFORT_RU[inherited as keyof typeof AGENT_EFFORT_RU] : null)}</option>
|
||||
<option value="">{inherit(t, inherited ? AGENT_EFFORT_RU[inherited as keyof typeof AGENT_EFFORT_RU] : null)}</option>
|
||||
{AGENT_EFFORTS.map((e) => (
|
||||
<option key={e} value={e}>{AGENT_EFFORT_RU[e]}</option>
|
||||
<option key={e} value={e}>{t(AGENT_EFFORT_RU[e])}</option>
|
||||
))}
|
||||
</NativeSelect>
|
||||
);
|
||||
}
|
||||
|
||||
/** «⋯ Настройки проекта → Модель агента». */
|
||||
export function AgentModelPanel({ projectId, own, inherited, back }: { projectId: number; own: AgentSettingsPatch; inherited: AgentSettings; back: string }) {
|
||||
export async function AgentModelPanel({ projectId, own, inherited, back }: { projectId: number; own: AgentSettingsPatch; inherited: AgentSettings; back: string }) {
|
||||
const t = await getT();
|
||||
return (
|
||||
<form action={setAgentSettingsAction} className="flex flex-col gap-3">
|
||||
<Hidden fields={{ projectId, back }} />
|
||||
<Label>
|
||||
Провайдер
|
||||
<ProviderSelect name="provider" own={own.provider} inherited={inherited.provider} none="решает подписка" />
|
||||
{t("Провайдер")}
|
||||
<ProviderSelect name="provider" own={own.provider} inherited={inherited.provider} none={m("решает подписка")} />
|
||||
</Label>
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<Label>
|
||||
Модель
|
||||
<Input name="model" defaultValue={own.model ?? ""} placeholder={inherited.model ?? "по умолчанию CLI"} className="h-8" />
|
||||
{t("Модель")}
|
||||
<Input name="model" defaultValue={own.model ?? ""} placeholder={inherited.model ?? t("по умолчанию CLI")} className="h-8" />
|
||||
</Label>
|
||||
<Label>
|
||||
Усилия
|
||||
{t("Усилия")}
|
||||
<EffortSelect name="effort" own={own.effort} inherited={inherited.effort} />
|
||||
</Label>
|
||||
</div>
|
||||
<p className="m-0 text-xs font-medium">Эскалация после неудач</p>
|
||||
<p className="m-0 text-xs font-medium">{t("Эскалация после неудач")}</p>
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<Label>
|
||||
Сильная модель
|
||||
<Input name="escalateModel" defaultValue={own.escalateModel ?? ""} placeholder={inherited.escalateModel ?? "нет — без эскалации"} className="h-8" />
|
||||
{t("Сильная модель")}
|
||||
<Input name="escalateModel" defaultValue={own.escalateModel ?? ""} placeholder={inherited.escalateModel ?? t("нет — без эскалации")} className="h-8" />
|
||||
</Label>
|
||||
<Label>
|
||||
Усилия
|
||||
{t("Усилия")}
|
||||
<EffortSelect name="escalateEffort" own={own.escalateEffort} inherited={inherited.escalateEffort} />
|
||||
</Label>
|
||||
</div>
|
||||
<Label>
|
||||
После скольких неудач (пусто — {inherited.escalateAfter ?? "никогда"}, 0 — выключить)
|
||||
{t("После скольких неудач (пусто — {n}, 0 — выключить)", { n: inherited.escalateAfter ?? t("никогда") })}
|
||||
<Input name="escalateAfter" type="number" min={0} max={20} defaultValue={own.escalateAfter === undefined ? "" : (own.escalateAfter ?? 0)} className="h-8" />
|
||||
</Label>
|
||||
<p className="m-0 text-xs font-medium">Запасной провайдер</p>
|
||||
<p className="m-0 text-xs font-medium">{t("Запасной провайдер")}</p>
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<Label>
|
||||
Провайдер
|
||||
<ProviderSelect name="fallbackProvider" own={own.fallbackProvider} inherited={inherited.fallbackProvider} none="нет" />
|
||||
{t("Провайдер")}
|
||||
<ProviderSelect name="fallbackProvider" own={own.fallbackProvider} inherited={inherited.fallbackProvider} none={m("нет")} />
|
||||
</Label>
|
||||
<Label>
|
||||
Модель
|
||||
<Input name="fallbackModel" defaultValue={own.fallbackModel ?? ""} placeholder={inherited.fallbackModel ?? "по умолчанию CLI"} className="h-8" />
|
||||
{t("Модель")}
|
||||
<Input name="fallbackModel" defaultValue={own.fallbackModel ?? ""} placeholder={inherited.fallbackModel ?? t("по умолчанию CLI")} className="h-8" />
|
||||
</Label>
|
||||
</div>
|
||||
<p className="m-0 text-xs text-muted-foreground">
|
||||
Модель — для <code>--model</code> (sonnet, opus, gpt-5-codex…), действует только на своего провайдера. Неудачи — красные проверки по разным коммитам и возвраты ревьюера; после порога стори до конца идёт на сильной модели, живой раннер перезапускается в том же разговоре. Запасной провайдер — если у основного нет рабочей подписки в пуле.
|
||||
{t("Модель — для")} <code>--model</code> {t("(sonnet, opus, gpt-5-codex…), действует только на своего провайдера.")}{" "}
|
||||
{t("Неудачи — красные проверки по разным коммитам и возвраты ревьюера; после порога стори до конца идёт на сильной модели, живой раннер перезапускается в том же разговоре.")}{" "}
|
||||
{t("Запасной провайдер — если у основного нет рабочей подписки в пуле.")}
|
||||
</p>
|
||||
<Button size="sm" className="self-start">Сохранить</Button>
|
||||
<Button size="sm" className="self-start">{t("Сохранить")}</Button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
/** Story page: provider / model / effort for this story only, and the escalation mark. */
|
||||
export function TaskAgentModel({ taskKey, own, inherited, escalation, back }: { taskKey: string; own: AgentSettingsPatch; inherited: AgentSettings; escalation: Escalation | null; back: string }) {
|
||||
export async function TaskAgentModel({ taskKey, own, inherited, escalation, back }: { taskKey: string; own: AgentSettingsPatch; inherited: AgentSettings; escalation: Escalation | null; back: string }) {
|
||||
const t = await getT();
|
||||
return (
|
||||
<form action={setAgentSettingsAction} className="flex flex-wrap items-end gap-2">
|
||||
<Hidden fields={{ taskKey, back }} />
|
||||
<Label className="flex-[1_1_9rem]">
|
||||
Провайдер стори
|
||||
<ProviderSelect name="provider" own={own.provider} inherited={inherited.provider} none="решает подписка" />
|
||||
{t("Провайдер стори")}
|
||||
<ProviderSelect name="provider" own={own.provider} inherited={inherited.provider} none={m("решает подписка")} />
|
||||
</Label>
|
||||
<Label className="flex-[1_1_9rem]">
|
||||
Модель
|
||||
<Input name="model" defaultValue={own.model ?? ""} placeholder={inherited.model ?? "по умолчанию"} className="h-8" />
|
||||
{t("Модель")}
|
||||
<Input name="model" defaultValue={own.model ?? ""} placeholder={inherited.model ?? t("по умолчанию")} className="h-8" />
|
||||
</Label>
|
||||
<Label className="flex-[1_1_9rem]">
|
||||
Усилия
|
||||
{t("Усилия")}
|
||||
<EffortSelect name="effort" own={own.effort} inherited={inherited.effort} />
|
||||
</Label>
|
||||
<Button size="sm" variant="outline">Сохранить</Button>
|
||||
<Button size="sm" variant="outline">{t("Сохранить")}</Button>
|
||||
<p className="m-0 flex w-full flex-wrap items-center gap-2 text-xs text-muted-foreground">
|
||||
Сейчас: {agentSettingsLabel({ ...inherited, ...own })}
|
||||
{t("Сейчас:")} {t.text(agentSettingsLabel({ ...inherited, ...own }))}
|
||||
{escalation && (
|
||||
<Badge variant="warn" title={`с ${escalation.at.slice(0, 16).replace("T", " ")}`}>
|
||||
эскалация на {escalation.model} после {escalation.failures} неудач
|
||||
<Badge variant="warn" title={t("с {at}", { at: escalation.at.slice(0, 16).replace("T", " ") })}>
|
||||
{t("эскалация на {model} после {failures} неудач", { model: escalation.model, failures: escalation.failures })}
|
||||
</Badge>
|
||||
)}
|
||||
</p>
|
||||
|
||||
@ -4,26 +4,28 @@ import { useEffect, useState } from "react";
|
||||
import { Bot, FilePen, FileText, FlaskConical, Globe, Plug, Search, SquareTerminal, Wrench, type LucideIcon } from "lucide-react";
|
||||
import type { StepKind, StepView } from "@peppa/core";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useT } from "@/components/I18n";
|
||||
import { m, type Translator } from "@peppa/shared/i18n";
|
||||
|
||||
const KIND: Record<StepKind, { icon: LucideIcon; label: string }> = {
|
||||
command: { icon: SquareTerminal, label: "команда" },
|
||||
test: { icon: FlaskConical, label: "тест" },
|
||||
edit: { icon: FilePen, label: "правка" },
|
||||
read: { icon: FileText, label: "чтение" },
|
||||
search: { icon: Search, label: "поиск" },
|
||||
web: { icon: Globe, label: "веб" },
|
||||
agent: { icon: Bot, label: "субагент" },
|
||||
command: { icon: SquareTerminal, label: m("команда") },
|
||||
test: { icon: FlaskConical, label: m("тест") },
|
||||
edit: { icon: FilePen, label: m("правка") },
|
||||
read: { icon: FileText, label: m("чтение") },
|
||||
search: { icon: Search, label: m("поиск") },
|
||||
web: { icon: Globe, label: m("веб") },
|
||||
agent: { icon: Bot, label: m("субагент") },
|
||||
mcp: { icon: Plug, label: "MCP" },
|
||||
other: { icon: Wrench, label: "инструмент" },
|
||||
other: { icon: Wrench, label: m("инструмент") },
|
||||
};
|
||||
|
||||
const KEEP = 30;
|
||||
|
||||
function since(iso: string, now: number): string {
|
||||
function since(iso: string, now: number, t: Translator): string {
|
||||
const s = Math.max(0, Math.round((now - Date.parse(iso)) / 1000));
|
||||
if (s < 60) return `${s} с`;
|
||||
if (s < 3600) return `${Math.floor(s / 60)} мин`;
|
||||
return `${Math.floor(s / 3600)} ч`;
|
||||
if (s < 60) return t("{n} с", { n: s });
|
||||
if (s < 3600) return t("{n} мин", { n: Math.floor(s / 60) });
|
||||
return t("{n} ч", { n: Math.floor(s / 3600) });
|
||||
}
|
||||
|
||||
/**
|
||||
@ -33,12 +35,13 @@ function since(iso: string, now: number): string {
|
||||
export function AgentSteps({ sessionId, initial, live, hooks = true }: { sessionId: number; initial: StepView[]; live: boolean; hooks?: boolean }) {
|
||||
const [steps, setSteps] = useState(initial);
|
||||
const [now, setNow] = useState(() => Date.now());
|
||||
const t = useT();
|
||||
|
||||
useEffect(() => setSteps((cur) => merge(initial, cur)), [initial]);
|
||||
|
||||
useEffect(() => {
|
||||
const t = setInterval(() => setNow(Date.now()), 10_000);
|
||||
if (!live || typeof EventSource === "undefined") return () => clearInterval(t);
|
||||
const timer = setInterval(() => setNow(Date.now()), 10_000);
|
||||
if (!live || typeof EventSource === "undefined") return () => clearInterval(timer);
|
||||
const es = new EventSource(`/api/live?scope=steps:${sessionId}`);
|
||||
es.addEventListener("step", (e) => {
|
||||
try {
|
||||
@ -48,7 +51,7 @@ export function AgentSteps({ sessionId, initial, live, hooks = true }: { session
|
||||
} catch {}
|
||||
});
|
||||
return () => {
|
||||
clearInterval(t);
|
||||
clearInterval(timer);
|
||||
es.close();
|
||||
};
|
||||
}, [sessionId, live]);
|
||||
@ -56,22 +59,22 @@ export function AgentSteps({ sessionId, initial, live, hooks = true }: { session
|
||||
if (!steps.length)
|
||||
return (
|
||||
<p className="m-0 rounded-md border border-dashed px-3 py-2 text-xs text-muted-foreground">
|
||||
{hooks ? (live ? "Агент ещё ничего не сделал — шаги появятся здесь." : "Шагов не записано.") : "Этот агент не сообщает шаги (нет хуков) — смотри терминал."}
|
||||
{hooks ? (live ? t("Агент ещё ничего не сделал — шаги появятся здесь.") : t("Шагов не записано.")) : t("Этот агент не сообщает шаги (нет хуков) — смотри терминал.")}
|
||||
</p>
|
||||
);
|
||||
return (
|
||||
<ol aria-label="Шаги агента" className="m-0 flex max-h-72 list-none flex-col gap-0.5 overflow-auto p-0">
|
||||
<ol aria-label={t("Шаги агента")} className="m-0 flex max-h-72 list-none flex-col gap-0.5 overflow-auto p-0">
|
||||
{steps.map((s, i) => {
|
||||
const k = KIND[s.kind] ?? KIND.other;
|
||||
const Icon = k.icon;
|
||||
return (
|
||||
<li key={s.id} className={cn("flex items-center gap-2 rounded px-1.5 py-1 text-xs", i === 0 && live && "bg-info/10")}>
|
||||
<Icon className={cn("size-3.5 shrink-0", s.ok ? "text-muted-foreground" : "text-destructive")} aria-label={k.label} />
|
||||
<Icon className={cn("size-3.5 shrink-0", s.ok ? "text-muted-foreground" : "text-destructive")} aria-label={t(k.label)} />
|
||||
<span className={cn("min-w-0 flex-1 truncate font-mono", !s.ok && "text-destructive")} title={`${s.tool}: ${s.text}`}>
|
||||
{s.text}
|
||||
</span>
|
||||
{!s.ok && <span className="shrink-0 text-[10px] text-destructive">ошибка</span>}
|
||||
<span className="shrink-0 font-mono text-[10px] text-muted-foreground tabular-nums">{since(s.at, now)}</span>
|
||||
{!s.ok && <span className="shrink-0 text-[10px] text-destructive">{t("ошибка")}</span>}
|
||||
<span className="shrink-0 font-mono text-[10px] text-muted-foreground tabular-nums">{since(s.at, now, t)}</span>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
|
||||
@ -4,87 +4,89 @@ import { setAutonomyAction } from "@/app/(app)/actions";
|
||||
import { Hidden } from "@/components/cards";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input, Label, NativeSelect } from "@/components/ui/input";
|
||||
import { getT } from "@/lib/i18n";
|
||||
|
||||
export function AutonomyPanel({ projectId, settings, back }: { projectId: number; settings: AutonomySettings; back: string }) {
|
||||
export async function AutonomyPanel({ projectId, settings, back }: { projectId: number; settings: AutonomySettings; back: string }) {
|
||||
const t = await getT();
|
||||
const current = autonomyLevel(settings);
|
||||
const s = settings;
|
||||
return (
|
||||
<div className="flex flex-col gap-3">
|
||||
<div className="flex flex-wrap gap-2" role="group" aria-label="Уровень автономности">
|
||||
<div className="flex flex-wrap gap-2" role="group" aria-label={t("Уровень автономности")}>
|
||||
{(Object.keys(AUTONOMY_LEVELS) as AutonomyLevel[]).map((level) => (
|
||||
<form key={level} action={setAutonomyAction}>
|
||||
<Hidden fields={{ projectId, level, back }} />
|
||||
<Button size="sm" variant={current === level ? "default" : "outline"} aria-pressed={current === level} title={AUTONOMY_LEVEL_HINT[level]}>
|
||||
{AUTONOMY_LEVEL_RU[level]}
|
||||
<Button size="sm" variant={current === level ? "default" : "outline"} aria-pressed={current === level} title={t.text(AUTONOMY_LEVEL_HINT[level])}>
|
||||
{t.text(AUTONOMY_LEVEL_RU[level])}
|
||||
</Button>
|
||||
</form>
|
||||
))}
|
||||
{current === "custom" && (
|
||||
<Button size="sm" variant="default" disabled aria-pressed>
|
||||
{AUTONOMY_LEVEL_RU.custom}
|
||||
{t.text(AUTONOMY_LEVEL_RU.custom)}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<p className="m-0 text-xs text-muted-foreground">{current === "custom" ? "Своя комбинация настроек ниже." : AUTONOMY_LEVEL_HINT[current]}</p>
|
||||
<p className="m-0 text-xs text-muted-foreground">{current === "custom" ? t("Своя комбинация настроек ниже.") : t.text(AUTONOMY_LEVEL_HINT[current])}</p>
|
||||
<details>
|
||||
<summary className="cursor-pointer text-sm text-primary">Настроить подробно</summary>
|
||||
<summary className="cursor-pointer text-sm text-primary">{t("Настроить подробно")}</summary>
|
||||
<form action={setAutonomyAction} className="mt-3 flex flex-col gap-3">
|
||||
<Hidden fields={{ projectId, back }} />
|
||||
<Label>
|
||||
Кто берёт стори из бэклога
|
||||
{t("Кто берёт стори из бэклога")}
|
||||
<NativeSelect name="pick" defaultValue={s.pick} className="h-8">
|
||||
<option value="pm">PM — двигает карточки сам</option>
|
||||
<option value="auto">Пеппа — сама, по номеру стори</option>
|
||||
<option value="pm">{t("PM — двигает карточки сам")}</option>
|
||||
<option value="auto">{t("Пеппа — сама, по номеру стори")}</option>
|
||||
</NativeSelect>
|
||||
</Label>
|
||||
<Label>
|
||||
Сколько стори в работе одновременно (для «Пеппа сама»)
|
||||
{t("Сколько стори в работе одновременно (для «Пеппа сама»)")}
|
||||
<Input name="wipLimit" type="number" min={1} max={5} defaultValue={s.wipLimit} className="h-8" />
|
||||
</Label>
|
||||
<Label>
|
||||
Proposal
|
||||
{t("Proposal")}
|
||||
<NativeSelect name="proposal" defaultValue={s.proposal} className="h-8">
|
||||
<option value="agent">Без одобрения — PM только на архитектурные стопперы</option>
|
||||
<option value="pm">Каждый proposal одобряет PM</option>
|
||||
<option value="agent">{t("Без одобрения — PM только на архитектурные стопперы")}</option>
|
||||
<option value="pm">{t("Каждый proposal одобряет PM")}</option>
|
||||
</NativeSelect>
|
||||
</Label>
|
||||
<Label>
|
||||
Мерж PR
|
||||
{t("Мерж PR")}
|
||||
<NativeSelect name="merge" defaultValue={s.merge} className="h-8">
|
||||
<option value="manual">По кнопке «Принять»</option>
|
||||
<option value="auto">Сам после зелёных проверок и без конфликтов</option>
|
||||
<option value="manual">{t("По кнопке «Принять»")}</option>
|
||||
<option value="auto">{t("Сам после зелёных проверок и без конфликтов")}</option>
|
||||
</NativeSelect>
|
||||
</Label>
|
||||
<Label>
|
||||
Закрытие стори
|
||||
{t("Закрытие стори")}
|
||||
<NativeSelect name="close" defaultValue={s.close} className="h-8">
|
||||
<option value="pm">PM принимает</option>
|
||||
<option value="after_merge">Сразу после мержа</option>
|
||||
<option value="after_hours">Само через N часов без замечаний</option>
|
||||
<option value="pm">{t("PM принимает")}</option>
|
||||
<option value="after_merge">{t("Сразу после мержа")}</option>
|
||||
<option value="after_hours">{t("Само через N часов без замечаний")}</option>
|
||||
</NativeSelect>
|
||||
</Label>
|
||||
<Label>
|
||||
N часов до автозакрытия
|
||||
{t("N часов до автозакрытия")}
|
||||
<Input name="closeAfterHours" type="number" min={1} max={336} defaultValue={s.closeAfterHours} className="h-8" />
|
||||
</Label>
|
||||
<label className="flex items-center gap-2 text-sm">
|
||||
<input type="checkbox" name="idlePush" defaultChecked={s.idlePush} /> Пуш, если агенты простаивают, а в бэклоге есть стори
|
||||
<input type="checkbox" name="idlePush" defaultChecked={s.idlePush} /> {t("Пуш, если агенты простаивают, а в бэклоге есть стори")}
|
||||
</label>
|
||||
<Label>
|
||||
Не чаще раза в (часов); столько же длится «Не сейчас»
|
||||
{t("Не чаще раза в (часов); столько же длится «Не сейчас»")}
|
||||
<Input name="idlePushHours" type="number" min={1} max={168} defaultValue={s.idlePushHours} className="h-8" />
|
||||
</Label>
|
||||
<label className="flex items-center gap-2 text-sm">
|
||||
<input type="checkbox" name="quiet" defaultChecked={s.quietFrom != null} /> Тихие часы
|
||||
<input type="checkbox" name="quiet" defaultChecked={s.quietFrom != null} /> {t("Тихие часы")}
|
||||
</label>
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
с <Input name="quietFrom" type="number" min={0} max={23} defaultValue={s.quietFrom ?? 22} className="h-8 w-20" aria-label="Тихие часы с" />
|
||||
до <Input name="quietTo" type="number" min={0} max={23} defaultValue={s.quietTo ?? 9} className="h-8 w-20" aria-label="Тихие часы до" />
|
||||
{t("с")} <Input name="quietFrom" type="number" min={0} max={23} defaultValue={s.quietFrom ?? 22} className="h-8 w-20" aria-label={t("Тихие часы с")} />
|
||||
{t("до")} <Input name="quietTo" type="number" min={0} max={23} defaultValue={s.quietTo ?? 9} className="h-8 w-20" aria-label={t("Тихие часы до")} />
|
||||
</div>
|
||||
<Button size="sm" className="self-start">Сохранить</Button>
|
||||
<Button size="sm" className="self-start">{t("Сохранить")}</Button>
|
||||
</form>
|
||||
</details>
|
||||
<p className="m-0 text-xs text-muted-foreground">PR, меняющий конвейер (.gitea/, checks, deploy), сам не мержится и не закрывается — его принимает PM.</p>
|
||||
<p className="m-0 text-xs text-muted-foreground">{t("PR, меняющий конвейер (.gitea/, checks, deploy), сам не мержится и не закрывается — его принимает PM.")}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@ -10,6 +10,8 @@ import { Button } from "@/components/ui/button";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { AgentBadge } from "@/components/AgentBadge";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useT } from "@/components/I18n";
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
|
||||
export type Column = "backlog" | "in_progress" | "review" | "done";
|
||||
export interface Card {
|
||||
@ -36,9 +38,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 t = useT();
|
||||
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 ? t("Сейчас: {item}", { item: p.current }) : t("Все пункты 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}%` }} />
|
||||
@ -55,20 +58,20 @@ export function ProgressLine({ p, className }: { p: CardProgress; className?: st
|
||||
const DONE_COLLAPSED = "peppa.board.doneCollapsed";
|
||||
|
||||
const COLUMNS: Array<{ id: Column; title: string; hint: string; dot: string }> = [
|
||||
{ id: "backlog", title: "Бэклог", hint: "", dot: "bg-muted-foreground" },
|
||||
{ id: "in_progress", title: "В работе", hint: "сюда — запустить агента", dot: "bg-info" },
|
||||
{ id: "review", title: "Ревью", hint: "", dot: "bg-ok" },
|
||||
{ id: "done", title: "Готово", hint: "", dot: "bg-ok" },
|
||||
{ id: "backlog", title: m("Бэклог"), hint: "", dot: "bg-muted-foreground" },
|
||||
{ id: "in_progress", title: m("В работе"), hint: m("сюда — запустить агента"), dot: "bg-info" },
|
||||
{ id: "review", title: m("Ревью"), hint: "", dot: "bg-ok" },
|
||||
{ id: "done", title: m("Готово"), hint: "", dot: "bg-ok" },
|
||||
];
|
||||
const STATUS: Record<string, { label: string; tone: "primary" | "danger" | "info" }> = {
|
||||
proposing: { label: "proposal", tone: "primary" },
|
||||
awaiting_approval: { label: "ждёт PM", tone: "primary" },
|
||||
blocked: { label: "блок", tone: "danger" },
|
||||
in_progress: { label: "агент", tone: "info" },
|
||||
awaiting_approval: { label: m("ждёт PM"), tone: "primary" },
|
||||
blocked: { label: m("блок"), tone: "danger" },
|
||||
in_progress: { label: m("агент"), tone: "info" },
|
||||
};
|
||||
const NEXT: Partial<Record<Column, { to: Column; label: string }>> = {
|
||||
backlog: { to: "in_progress", label: "В работу →" },
|
||||
review: { to: "done", label: "Принять ✓" },
|
||||
backlog: { to: "in_progress", label: m("В работу →") },
|
||||
review: { to: "done", label: m("Принять ✓") },
|
||||
};
|
||||
|
||||
/**
|
||||
@ -78,6 +81,7 @@ const NEXT: Partial<Record<Column, { to: Column; label: string }>> = {
|
||||
*/
|
||||
export function Board({ cards, back }: { cards: Card[]; back: string }) {
|
||||
const router = useRouter();
|
||||
const t = useT();
|
||||
const [pending, start] = useTransition();
|
||||
const [over, setOver] = useState<Column | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
@ -111,7 +115,7 @@ export function Board({ cards, back }: { cards: Card[]; back: string }) {
|
||||
<div className="flex flex-col gap-2">
|
||||
{error && (
|
||||
<p role="alert" className="m-0 rounded-md border border-destructive/40 bg-destructive/10 px-3 py-1.5 text-sm text-destructive">
|
||||
{error}
|
||||
{t.text(error)}
|
||||
</p>
|
||||
)}
|
||||
<div className={cn("grid gap-3 sm:grid-cols-2 lg:grid-cols-4", pending && "pointer-events-none opacity-60")}>
|
||||
@ -121,7 +125,7 @@ export function Board({ cards, back }: { cards: Card[]; back: string }) {
|
||||
return (
|
||||
<section
|
||||
key={c.id}
|
||||
aria-label={c.title}
|
||||
aria-label={t(c.title)}
|
||||
className={cn("flex min-h-32 flex-col gap-2 rounded-lg border bg-muted/40 p-2", over === c.id && "border-dashed border-primary bg-primary/5", collapsed && "min-h-0")}
|
||||
onDragOver={(e) => {
|
||||
e.preventDefault();
|
||||
@ -140,15 +144,15 @@ export function Board({ cards, back }: { cards: Card[]; back: string }) {
|
||||
>
|
||||
<h3 className="m-0 flex items-center gap-2 px-1.5 pt-1 font-mono text-[11px] font-semibold tracking-wider text-muted-foreground uppercase">
|
||||
<span className={cn("size-1.5 rounded-full", c.dot)} />
|
||||
{c.title}
|
||||
{t(c.title)}
|
||||
<span className="ml-auto tabular-nums">{list.length}</span>
|
||||
{c.id === "done" && (
|
||||
<button type="button" onClick={toggleDone} aria-expanded={!collapsed} aria-label={collapsed ? "Развернуть «Готово»" : "Свернуть «Готово»"} className="-mr-1 rounded p-0.5 hover:bg-muted hover:text-foreground">
|
||||
<button type="button" onClick={toggleDone} aria-expanded={!collapsed} aria-label={collapsed ? t("Развернуть «Готово»") : t("Свернуть «Готово»")} className="-mr-1 rounded p-0.5 hover:bg-muted hover:text-foreground">
|
||||
{collapsed ? <ChevronRight className="size-3.5" /> : <ChevronDown className="size-3.5" />}
|
||||
</button>
|
||||
)}
|
||||
</h3>
|
||||
{!collapsed && c.hint && <p className="m-0 px-1.5 text-[11px] text-muted-foreground">{c.hint}</p>}
|
||||
{!collapsed && c.hint && <p className="m-0 px-1.5 text-[11px] text-muted-foreground">{t(c.hint)}</p>}
|
||||
{!collapsed &&
|
||||
list.map((card, i) => (
|
||||
<article
|
||||
@ -176,12 +180,12 @@ export function Board({ cards, back }: { cards: Card[]; back: string }) {
|
||||
{list.length > 1 && (
|
||||
<span className="flex shrink-0 opacity-0 transition-opacity group-focus-within:opacity-100 group-hover:opacity-100 max-sm:opacity-100">
|
||||
{i > 0 && (
|
||||
<button type="button" title="Наверх" aria-label={`${card.key} наверх`} disabled={pending} onClick={() => reorder(card.key, "top")} className="rounded p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground">
|
||||
<button type="button" title={t("Наверх")} aria-label={t("{key} наверх", { key: card.key })} disabled={pending} onClick={() => reorder(card.key, "top")} className="rounded p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground">
|
||||
<ChevronsUp className="size-3.5" />
|
||||
</button>
|
||||
)}
|
||||
{i < list.length - 1 && (
|
||||
<button type="button" title="Вниз" aria-label={`${card.key} вниз`} disabled={pending} onClick={() => reorder(card.key, "bottom")} className="rounded p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground">
|
||||
<button type="button" title={t("Вниз")} aria-label={t("{key} вниз", { key: card.key })} disabled={pending} onClick={() => reorder(card.key, "bottom")} className="rounded p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground">
|
||||
<ChevronsDown className="size-3.5" />
|
||||
</button>
|
||||
)}
|
||||
@ -189,8 +193,8 @@ export function Board({ cards, back }: { cards: Card[]; back: string }) {
|
||||
)}
|
||||
</div>
|
||||
{card.refining && (
|
||||
<Badge variant="info" className="self-start" title="Продакт и аналитик уточняют задачу; агент-разработчик возьмёт её после этого">
|
||||
{card.refining}
|
||||
<Badge variant="info" className="self-start" title={t("Продакт и аналитик уточняют задачу; агент-разработчик возьмёт её после этого")}>
|
||||
{t.text(card.refining)}
|
||||
</Badge>
|
||||
)}
|
||||
{card.agent && <AgentBadge name={card.agent} className="text-muted-foreground" />}
|
||||
@ -198,21 +202,21 @@ 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={t("Диспетчер не возьмёт стори, пока предшественники не в ревью или готово")}>
|
||||
<Lock className="size-3" />
|
||||
{card.blocked}
|
||||
{t.text(card.blocked)}
|
||||
</Badge>
|
||||
)}
|
||||
{card.epic && (
|
||||
<Badge variant="outline" className="max-w-full min-w-0" title={`Эпик: ${card.epic}`}>
|
||||
<span className="shrink-0 text-muted-foreground">эпик</span>
|
||||
<Badge variant="outline" className="max-w-full min-w-0" title={t("Эпик: {name}", { name: card.epic })}>
|
||||
<span className="shrink-0 text-muted-foreground">{t("эпик")}</span>
|
||||
<span className="truncate">{card.epic}</span>
|
||||
</Badge>
|
||||
)}
|
||||
{STATUS[card.status] && <Badge variant={STATUS[card.status]!.tone}>{STATUS[card.status]!.label}</Badge>}
|
||||
{STATUS[card.status] && <Badge variant={STATUS[card.status]!.tone}>{t(STATUS[card.status]!.label)}</Badge>}
|
||||
{NEXT[c.id] && (
|
||||
<Button size="xs" className="ml-auto" disabled={pending} onClick={() => move(card.key, NEXT[c.id]!.to)}>
|
||||
{NEXT[c.id]!.label}
|
||||
{t(NEXT[c.id]!.label)}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
@ -223,7 +227,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">{t("Порядок в колонке — приоритет: перетащите карточку выше или ниже; диспетчер берёт стори из бэклога сверху.")}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@ -1,3 +1,5 @@
|
||||
import { PRODUCT_NAME } from "@peppa/shared/i18n";
|
||||
|
||||
/** Peppa mark: pink tile with a glow + mono word. */
|
||||
export function Brand({ large = false }: { large?: boolean }) {
|
||||
return (
|
||||
@ -5,7 +7,7 @@ export function Brand({ large = false }: { large?: boolean }) {
|
||||
<span className={large ? "grid size-10 place-items-center rounded-lg bg-primary font-mono text-lg font-bold text-primary-foreground shadow-[0_0_28px_-4px_var(--primary)]" : "grid size-7 place-items-center rounded-md bg-primary font-mono text-sm font-bold text-primary-foreground shadow-[0_0_18px_-4px_var(--primary)]"}>
|
||||
P
|
||||
</span>
|
||||
<span className={large ? "font-mono text-2xl font-semibold tracking-tight" : "font-mono text-[15px] font-semibold tracking-tight"}>peppa</span>
|
||||
<span className={large ? "font-mono text-2xl font-semibold tracking-tight" : "font-mono text-[15px] font-semibold tracking-tight"}>{PRODUCT_NAME}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
@ -9,6 +9,7 @@ import { matchPalette, type PaletteItem } from "@peppa/shared/palette";
|
||||
import { moveTaskCard } from "@/app/(app)/actions";
|
||||
import { PALETTE_KEYS, SHORTCUTS } from "@/lib/shortcuts";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useT } from "@/components/I18n";
|
||||
|
||||
const ICON = { project: FolderKanban, story: FileText, runner: Bot, question: MessageCircleQuestion, page: CircleHelp } as const;
|
||||
const GO: Record<string, string> = { h: "/", p: "/projects", r: "/runners", s: "/settings" };
|
||||
@ -24,6 +25,7 @@ export function Kbd({ children }: { children: React.ReactNode }) {
|
||||
}
|
||||
|
||||
export function ShortcutsList() {
|
||||
const t = useT();
|
||||
return (
|
||||
<table className="w-full border-collapse text-sm">
|
||||
<tbody>
|
||||
@ -38,8 +40,8 @@ export function ShortcutsList() {
|
||||
))}
|
||||
</td>
|
||||
<td className="py-1.5">
|
||||
{s.what}
|
||||
{s.where && <span className="text-muted-foreground"> — {s.where}</span>}
|
||||
{t(s.what)}
|
||||
{s.where && <span className="text-muted-foreground"> — {t(s.where)}</span>}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
@ -49,6 +51,7 @@ export function ShortcutsList() {
|
||||
}
|
||||
|
||||
export function CommandPalette() {
|
||||
const t = useT();
|
||||
const router = useRouter();
|
||||
const palette = useRef<HTMLDialogElement>(null);
|
||||
const help = useRef<HTMLDialogElement>(null);
|
||||
@ -93,7 +96,7 @@ export function CommandPalette() {
|
||||
f.set("taskKey", item.key);
|
||||
f.set("to", "in_progress");
|
||||
f.set("back", item.href);
|
||||
setNote(`${item.key} → В работу…`);
|
||||
setNote(item.key + " → " + t("В работу…"));
|
||||
start(async () => {
|
||||
close();
|
||||
setLoadedAt(0);
|
||||
@ -185,7 +188,7 @@ export function CommandPalette() {
|
||||
<>
|
||||
<dialog
|
||||
ref={palette}
|
||||
aria-label="Командная палитра"
|
||||
aria-label={t("Командная палитра")}
|
||||
className="m-auto mt-[12vh] w-[min(640px,calc(100vw-2rem))] rounded-xl border bg-popover p-0 text-popover-foreground shadow-2xl backdrop:bg-black/50"
|
||||
onClick={(e) => e.target === palette.current && close()}
|
||||
>
|
||||
@ -211,8 +214,8 @@ export function CommandPalette() {
|
||||
else go(shown[sel]!);
|
||||
}
|
||||
}}
|
||||
placeholder="Проект, стори, раннер, вопрос или раздел…"
|
||||
aria-label="Поиск"
|
||||
placeholder={t("Проект, стори, раннер, вопрос или раздел…")}
|
||||
aria-label={t("Поиск")}
|
||||
role="combobox"
|
||||
aria-expanded="true"
|
||||
aria-controls="palette-list"
|
||||
@ -222,7 +225,7 @@ export function CommandPalette() {
|
||||
<Kbd>Esc</Kbd>
|
||||
</div>
|
||||
<ul id="palette-list" role="listbox" className="m-0 max-h-[52vh] list-none overflow-y-auto p-1.5">
|
||||
{shown.length === 0 && <li className="px-3 py-6 text-center text-sm text-muted-foreground">{loadedAt ? "Ничего не найдено" : "Загрузка…"}</li>}
|
||||
{shown.length === 0 && <li className="px-3 py-6 text-center text-sm text-muted-foreground">{loadedAt ? t("Ничего не найдено") : t("Загрузка…")}</li>}
|
||||
{shown.map((item, i) => {
|
||||
const Icon = ICON[item.kind];
|
||||
return (
|
||||
@ -237,12 +240,12 @@ export function CommandPalette() {
|
||||
>
|
||||
<Icon className="size-4 shrink-0 text-muted-foreground" />
|
||||
{item.key && <span className={cn("shrink-0 font-mono text-xs", item.kind === "page" ? "text-muted-foreground" : "text-primary")}>{item.key}</span>}
|
||||
<span className="min-w-0 flex-1 truncate">{item.title}</span>
|
||||
{item.hint && <span className="hidden shrink-0 text-xs text-muted-foreground sm:inline">{item.hint}</span>}
|
||||
<span className="min-w-0 flex-1 truncate">{item.kind === "page" ? t.text(item.title) : item.title}</span>
|
||||
{item.hint && <span className="hidden shrink-0 text-xs text-muted-foreground sm:inline">{t.text(item.hint)}</span>}
|
||||
{item.canStart && (
|
||||
<button
|
||||
type="button"
|
||||
title="В работу (⌘Enter)"
|
||||
title={t("В работу (⌘Enter)")}
|
||||
disabled={pending}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
@ -250,7 +253,8 @@ export function CommandPalette() {
|
||||
}}
|
||||
className="flex shrink-0 items-center gap-1 rounded border px-1.5 py-0.5 text-xs text-muted-foreground hover:border-primary hover:text-foreground"
|
||||
>
|
||||
<Play className="size-3" />В работу
|
||||
<Play className="size-3" />
|
||||
{t("В работу")}
|
||||
</button>
|
||||
)}
|
||||
</li>
|
||||
@ -258,7 +262,7 @@ export function CommandPalette() {
|
||||
})}
|
||||
</ul>
|
||||
<div className="flex items-center gap-2 border-t px-3 py-2 text-[11px] text-muted-foreground">
|
||||
<span className="min-w-0 flex-1 truncate">{note ?? PALETTE_KEYS}</span>
|
||||
<span className="min-w-0 flex-1 truncate">{note ?? t(PALETTE_KEYS)}</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
@ -268,21 +272,25 @@ export function CommandPalette() {
|
||||
className="flex items-center gap-1 hover:text-foreground"
|
||||
>
|
||||
<Keyboard className="size-3.5" />
|
||||
Сочетания <Kbd>?</Kbd>
|
||||
{t("Сочетания")} <Kbd>?</Kbd>
|
||||
</button>
|
||||
</div>
|
||||
</dialog>
|
||||
|
||||
<dialog
|
||||
ref={help}
|
||||
aria-label="Горячие клавиши"
|
||||
aria-label={t("Горячие клавиши")}
|
||||
className="m-auto w-[min(560px,calc(100vw-2rem))] rounded-xl border bg-popover p-4 text-popover-foreground shadow-2xl backdrop:bg-black/50"
|
||||
onClick={(e) => e.target === help.current && help.current?.close()}
|
||||
>
|
||||
<h2 className="m-0 mb-2 text-base font-semibold">Горячие клавиши</h2>
|
||||
<h2 className="m-0 mb-2 text-base font-semibold">{t("Горячие клавиши")}</h2>
|
||||
<ShortcutsList />
|
||||
<p className="m-0 mt-3 text-xs text-muted-foreground">
|
||||
Клавиши без ⌘ работают вне полей ввода. Список — на странице <a href="/help/shortcuts" className="text-primary">Помощь → Горячие клавиши</a>.
|
||||
{t("Клавиши без ⌘ работают вне полей ввода. Список — на странице")}{" "}
|
||||
<a href="/help/shortcuts" className="text-primary">
|
||||
{t("Помощь → Горячие клавиши")}
|
||||
</a>
|
||||
.
|
||||
</p>
|
||||
</dialog>
|
||||
</>
|
||||
|
||||
@ -3,19 +3,21 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { ChevronDown, QrCode, Smartphone } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useT } from "@/components/I18n";
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
|
||||
type Purpose = "login" | "link";
|
||||
type Phase = { at: "idle" } | { at: "qr"; qr: string; deeplink: string; status: string } | { at: "done" } | { at: "error"; message: string };
|
||||
|
||||
const STATUS: Record<string, string> = {
|
||||
pending: "Отсканируйте QR в eGov Mobile",
|
||||
scanned: "QR отсканирован — подпишите в eGov Mobile",
|
||||
completed: "Подписано, входим…",
|
||||
pending: m("Отсканируйте QR в eGov Mobile"),
|
||||
scanned: m("QR отсканирован — подпишите в eGov Mobile"),
|
||||
completed: m("Подписано, входим…"),
|
||||
};
|
||||
const PHONE_STATUS: Record<string, string> = {
|
||||
pending: "Откройте eGov Mobile и подпишите вход, потом вернитесь сюда",
|
||||
scanned: "Подпишите в eGov Mobile и вернитесь сюда",
|
||||
completed: "Подписано, входим…",
|
||||
pending: m("Откройте eGov Mobile и подпишите вход, потом вернитесь сюда"),
|
||||
scanned: m("Подпишите в eGov Mobile и вернитесь сюда"),
|
||||
completed: m("Подписано, входим…"),
|
||||
};
|
||||
|
||||
/** Saved per tab so a phone that reloads the page on return from eGov Mobile picks the flow up again. */
|
||||
@ -52,6 +54,7 @@ const isPhone = () => typeof window !== "undefined" && (/Android|iPhone|iPad|iPo
|
||||
* `login` signs in (PEP-71: registers on first login), `link` binds the IIN (Settings).
|
||||
*/
|
||||
export function EgovSign({ purpose, next, label }: { purpose: Purpose; next?: string; label: string }) {
|
||||
const t = useT();
|
||||
const [phase, setPhase] = useState<Phase>({ at: "idle" });
|
||||
const [phone, setPhone] = useState(false);
|
||||
const [showQr, setShowQr] = useState(false);
|
||||
@ -83,14 +86,14 @@ export function EgovSign({ purpose, next, label }: { purpose: Purpose; next?: st
|
||||
const s = (await (await fetch("/auth/egov/status", { cache: "no-store" })).json().catch(() => ({}))) as { status?: string; error?: string };
|
||||
if (stale()) return;
|
||||
if (s.error) return fail(s.error);
|
||||
if (s.status === "expired") return fail("Вход истёк — начните заново");
|
||||
if (s.status === "rejected") return fail("Подписание отменено в eGov Mobile");
|
||||
if (s.status === "expired") return fail(m("Вход истёк — начните заново"));
|
||||
if (s.status === "rejected") return fail(m("Подписание отменено в eGov Mobile"));
|
||||
setPhase((p) => (p.at === "qr" ? { ...p, status: s.status ?? p.status } : p));
|
||||
if (s.status === "completed") break;
|
||||
}
|
||||
const c = await fetch("/auth/egov/complete", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ next }) });
|
||||
const done = (await c.json().catch(() => ({}))) as { redirect?: string; error?: string };
|
||||
if (!c.ok || !done.redirect) return fail(done.error ?? "Не удалось войти через eGov");
|
||||
if (!c.ok || !done.redirect) return fail(done.error ?? m("Не удалось войти через eGov"));
|
||||
writeSaved(null);
|
||||
setPhase({ at: "done" });
|
||||
window.location.assign(done.redirect);
|
||||
@ -122,7 +125,7 @@ export function EgovSign({ purpose, next, label }: { purpose: Purpose; next?: st
|
||||
async function start() {
|
||||
const r = await fetch("/auth/egov/start", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ purpose }) });
|
||||
const body = (await r.json()) as { qr?: string; deeplink?: string; expiresAt?: number; error?: string };
|
||||
if (!r.ok || !body.qr) return fail(body.error ?? "Не удалось начать вход через eGov");
|
||||
if (!r.ok || !body.qr) return fail(body.error ?? m("Не удалось начать вход через eGov"));
|
||||
const deeplink = body.deeplink ?? "";
|
||||
writeSaved({ purpose, qr: body.qr, deeplink, expiresAt: body.expiresAt ?? Date.now() + 5 * 60_000 });
|
||||
setShowQr(false);
|
||||
@ -133,20 +136,20 @@ export function EgovSign({ purpose, next, label }: { purpose: Purpose; next?: st
|
||||
if (phase.at === "qr") {
|
||||
const qrBlock = (
|
||||
// eslint-disable-next-line @next/next/no-img-element -- data URL from the server
|
||||
<img src={phase.qr} alt="QR для eGov Mobile" width={220} height={220} className="rounded-md bg-white p-1" />
|
||||
<img src={phase.qr} alt={t("QR для eGov Mobile")} width={220} height={220} className="rounded-md bg-white p-1" />
|
||||
);
|
||||
const status = (phone ? PHONE_STATUS : STATUS)[phase.status] ?? phase.status;
|
||||
const status = t.text((phone ? PHONE_STATUS : STATUS)[phase.status] ?? phase.status);
|
||||
if (phone && phase.deeplink) {
|
||||
return (
|
||||
<div className="flex w-full flex-col items-center gap-3 rounded-lg border bg-card p-4">
|
||||
<Button asChild variant="default" size="lg" className="w-full">
|
||||
<a href={phase.deeplink}>
|
||||
<Smartphone /> Открыть eGov Mobile
|
||||
<Smartphone /> {t("Открыть eGov Mobile")}
|
||||
</a>
|
||||
</Button>
|
||||
<p className="m-0 text-sm text-muted-foreground" aria-live="polite">{status}</p>
|
||||
<button type="button" className="inline-flex items-center gap-1 text-xs text-muted-foreground underline-offset-2 hover:underline" onClick={() => setShowQr((v) => !v)}>
|
||||
<ChevronDown className={showQr ? "size-3 rotate-180" : "size-3"} /> {showQr ? "Скрыть QR" : "Войти с другого телефона по QR"}
|
||||
<ChevronDown className={showQr ? "size-3 rotate-180" : "size-3"} /> {showQr ? t("Скрыть QR") : t("Войти с другого телефона по QR")}
|
||||
</button>
|
||||
{showQr && qrBlock}
|
||||
</div>
|
||||
@ -159,7 +162,7 @@ export function EgovSign({ purpose, next, label }: { purpose: Purpose; next?: st
|
||||
{phase.deeplink && (
|
||||
<Button asChild variant="outline" size="sm" className="w-full">
|
||||
<a href={phase.deeplink}>
|
||||
<Smartphone /> Открыть в eGov Mobile
|
||||
<Smartphone /> {t("Открыть в eGov Mobile")}
|
||||
</a>
|
||||
</Button>
|
||||
)}
|
||||
@ -168,9 +171,9 @@ export function EgovSign({ purpose, next, label }: { purpose: Purpose; next?: st
|
||||
}
|
||||
return (
|
||||
<div className="flex w-full flex-col gap-2">
|
||||
{phase.at === "error" && <p className="m-0 text-sm text-destructive">{phase.message}</p>}
|
||||
{phase.at === "error" && <p className="m-0 text-sm text-destructive">{t.text(phase.message)}</p>}
|
||||
<Button variant={purpose === "login" ? "default" : "outline"} size="lg" className="w-full" disabled={phase.at === "done"} onClick={() => void start().catch((e: Error) => fail(e.message))}>
|
||||
{phone ? <Smartphone /> : <QrCode />} {phase.at === "error" ? (phone ? "Начать заново" : "Новый QR") : phone ? `${label} Mobile` : label}
|
||||
{phone ? <Smartphone /> : <QrCode />} {phase.at === "error" ? (phone ? t("Начать заново") : t("Новый QR")) : phone ? `${label} Mobile` : label}
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
|
||||
@ -1,7 +1,10 @@
|
||||
import { loadEnv } from "@peppa/shared";
|
||||
import { intlLocale } from "@peppa/shared/i18n";
|
||||
import { getT } from "@/lib/i18n";
|
||||
|
||||
/** Build stamp: which Peppa version and commit is running. */
|
||||
export function Footer() {
|
||||
export async function Footer() {
|
||||
const t = await getT();
|
||||
const version = process.env.NEXT_PUBLIC_PEPPA_VERSION;
|
||||
const commit = process.env.NEXT_PUBLIC_PEPPA_COMMIT;
|
||||
const full = process.env.NEXT_PUBLIC_PEPPA_COMMIT_FULL;
|
||||
@ -16,10 +19,10 @@ export function Footer() {
|
||||
<a href={`${loadEnv().GITEA_URL}/${loadEnv().GITEA_PLATFORM_REPO}/commit/${full}`} className="font-mono text-primary">
|
||||
{commit}
|
||||
</a>
|
||||
{dirty && <span title="Собрано с незакоммиченными изменениями"> +изменения</span>}
|
||||
{dirty && <span title={t("Собрано с незакоммиченными изменениями")}> {t("+изменения")}</span>}
|
||||
</>
|
||||
)}
|
||||
{date && ` · ${new Date(date).toLocaleDateString("ru-RU")}`}
|
||||
{date && ` · ${new Date(date).toLocaleDateString(intlLocale(t.locale))}`}
|
||||
</footer>
|
||||
);
|
||||
}
|
||||
|
||||
@ -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 { getT } from "@/lib/i18n";
|
||||
|
||||
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" };
|
||||
|
||||
@ -15,7 +16,7 @@ function Code({ children }: { children: React.ReactNode }) {
|
||||
}
|
||||
|
||||
/** Tab «Баги»: the incidents list. Settings live in «⋯ Настройки проекта» (PEP-66). */
|
||||
export function IncidentsSection(props: {
|
||||
export async function IncidentsSection(props: {
|
||||
projectId: number;
|
||||
back: string;
|
||||
settings: IncidentSettings | null;
|
||||
@ -23,21 +24,22 @@ export function IncidentsSection(props: {
|
||||
taskKeys: Map<number, string>;
|
||||
}) {
|
||||
const { settings: s } = props;
|
||||
const t = await getT();
|
||||
if (!s) {
|
||||
return (
|
||||
<Section title="Баги">
|
||||
<p className="m-0 text-sm text-muted-foreground">Ошибки фронта и бэка из прода (Bugsink, SDK Sentry) приходят сюда и становятся стори по политике проекта.</p>
|
||||
<Empty>Отслеживание ошибок не подключено — подключает владелец в «⋯ Настройки проекта».</Empty>
|
||||
<Section title={t("Баги")}>
|
||||
<p className="m-0 text-sm text-muted-foreground">{t("Ошибки фронта и бэка из прода (Bugsink, SDK Sentry) приходят сюда и становятся стори по политике проекта.")}</p>
|
||||
<Empty>{t("Отслеживание ошибок не подключено — подключает владелец в «⋯ Настройки проекта».")}</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>}>
|
||||
{active.length === 0 ? <Empty>Открытых ошибок нет.</Empty> : active.map((i) => <IncidentCard key={i.id} i={i} {...props} />)}
|
||||
<Section title={t("Баги")} count={active.length} actions={<span className="text-xs text-muted-foreground">{t("политика: {policy}", { policy: t(POLICY_RU[s.policy]) })}</span>}>
|
||||
{active.length === 0 ? <Empty>{t("Открытых ошибок нет.")}</Empty> : active.map((i) => <IncidentCard key={i.id} i={i} {...props} />)}
|
||||
{rest.length > 0 && (
|
||||
<Disclosure summary={`Исправленные и игнорируемые (${rest.length})`}>
|
||||
<Disclosure summary={t("Исправленные и игнорируемые ({n})", { n: rest.length })}>
|
||||
<div className="flex flex-col gap-2">
|
||||
{rest.map((i) => (
|
||||
<IncidentCard key={i.id} i={i} {...props} />
|
||||
@ -50,7 +52,7 @@ export function IncidentsSection(props: {
|
||||
}
|
||||
|
||||
/** «⋯ Настройки проекта» → Баги: connect Bugsink, DSN, webhook, incident policy (PEP-66). */
|
||||
export function IncidentSettingsPanel(props: {
|
||||
export async function IncidentSettingsPanel(props: {
|
||||
projectId: number;
|
||||
back: string;
|
||||
isOwner: boolean;
|
||||
@ -59,20 +61,21 @@ export function IncidentSettingsPanel(props: {
|
||||
webhookUrl: string | null;
|
||||
}) {
|
||||
const { projectId, back, settings: s } = props;
|
||||
const t = await getT();
|
||||
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">{t("Ошибки фронта и бэка из прода (Bugsink, SDK Sentry) приходят во вкладку «Баги» и становятся стори по политике проекта.")}</p>
|
||||
{props.isOwner ? (
|
||||
<form action={connectErrorTrackingAction}>
|
||||
<Hidden fields={{ projectId, back }} />
|
||||
<Button variant="default" size="sm">
|
||||
<Bug />
|
||||
Подключить отслеживание ошибок
|
||||
{t("Подключить отслеживание ошибок")}
|
||||
</Button>
|
||||
</form>
|
||||
) : (
|
||||
<Empty>Не подключено — подключает владелец проекта.</Empty>
|
||||
<Empty>{t("Не подключено — подключает владелец проекта.")}</Empty>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
@ -81,29 +84,29 @@ export function IncidentSettingsPanel(props: {
|
||||
<div className="flex flex-col gap-3 text-sm">
|
||||
{props.sources.map((src) => (
|
||||
<div key={src.id} className="flex flex-col gap-1">
|
||||
<span className="font-medium">DSN {src.kind === "web" ? "фронта (web)" : "бэка (api)"}</span>
|
||||
<span className="font-medium">{src.kind === "web" ? t("DSN фронта (web)") : t("DSN бэка (api)")}</span>
|
||||
<Code>{src.dsn}</Code>
|
||||
</div>
|
||||
))}
|
||||
<p className="m-0 text-muted-foreground">
|
||||
В коде: <code className="font-mono">NEXT_PUBLIC_SENTRY_DSN</code> / <code className="font-mono">SENTRY_DSN</code> из окружения, <code className="font-mono">release</code> = SHA деплоя,{" "}
|
||||
{t("В коде:")} <code className="font-mono">NEXT_PUBLIC_SENTRY_DSN</code> / <code className="font-mono">SENTRY_DSN</code> {t("из окружения,")} <code className="font-mono">release</code> = {t("SHA деплоя,")}{" "}
|
||||
<code className="font-mono">environment</code> = prod, <code className="font-mono">sendDefaultPii: false</code>.
|
||||
</p>
|
||||
{!s.webhookAuto && props.webhookUrl && (
|
||||
<div className="flex flex-col gap-1">
|
||||
<span><b>Вебхук не настроен автоматически.</b> В Bugsink: проект → Alerts → Custom webhook:</span>
|
||||
<span><b>{t("Вебхук не настроен автоматически.")}</b> {t("В Bugsink: проект → Alerts → Custom webhook:")}</span>
|
||||
<Code>{props.webhookUrl}</Code>
|
||||
<span className="text-muted-foreground">Пока его нет, Пеппа опрашивает Bugsink раз в 2 минуты.</span>
|
||||
<span className="text-muted-foreground">{t("Пока его нет, Пеппа опрашивает Bugsink раз в 2 минуты.")}</span>
|
||||
</div>
|
||||
)}
|
||||
<form action={saveIncidentSettings} className="flex flex-col gap-2.5">
|
||||
<Hidden fields={{ projectId, back }} />
|
||||
<Label>
|
||||
Политика инцидентов
|
||||
<NativeSelect name="policy" defaultValue={s.policy} aria-label="Политика инцидентов">
|
||||
{t("Политика инцидентов")}
|
||||
<NativeSelect name="policy" defaultValue={s.policy} aria-label={t("Политика инцидентов")}>
|
||||
{incidentPolicies.map((p) => (
|
||||
<option key={p} value={p}>
|
||||
{p} — {POLICY_RU[p]}
|
||||
{p} — {t(POLICY_RU[p])}
|
||||
</option>
|
||||
))}
|
||||
</NativeSelect>
|
||||
@ -112,21 +115,22 @@ export function IncidentSettingsPanel(props: {
|
||||
name="triagePrompt"
|
||||
rows={3}
|
||||
defaultValue={s.triagePrompt ?? ""}
|
||||
aria-label="Как принимать решение (для триажёра)"
|
||||
placeholder="Как принимать решение (для политики triage): например, «падения оплаты — сразу в работу, косметику фронта — в бэклог, остальное спроси»"
|
||||
aria-label={t("Как принимать решение (для триажёра)")}
|
||||
placeholder={t("Как принимать решение (для политики triage): например, «падения оплаты — сразу в работу, косметику фронта — в бэклог, остальное спроси»")}
|
||||
/>
|
||||
<div className="flex gap-2">
|
||||
<Input name="environments" defaultValue={s.environments.join(", ")} aria-label="Окружения" placeholder="Окружения: prod, production" />
|
||||
<Input type="number" name="dailyLimit" min={0} defaultValue={s.dailyLimit} aria-label="Стори в сутки" title="Стори из ошибок в сутки" className="w-24" />
|
||||
<Input name="environments" defaultValue={s.environments.join(", ")} aria-label={t("Окружения")} placeholder={t("Окружения: prod, production")} />
|
||||
<Input type="number" name="dailyLimit" min={0} defaultValue={s.dailyLimit} aria-label={t("Стори в сутки")} title={t("Стори из ошибок в сутки")} className="w-24" />
|
||||
</div>
|
||||
<Input name="ignorePattern" defaultValue={s.ignorePattern ?? ""} aria-label="Игнорировать по названию" placeholder="Игнорировать по названию (регэксп), например ResizeObserver loop" />
|
||||
<Button size="sm" className="self-start">Сохранить</Button>
|
||||
<Input name="ignorePattern" defaultValue={s.ignorePattern ?? ""} aria-label={t("Игнорировать по названию")} placeholder={t("Игнорировать по названию (регэксп), например ResizeObserver loop")} />
|
||||
<Button size="sm" className="self-start">{t("Сохранить")}</Button>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function IncidentCard({ i, back, projectId, taskKeys }: { i: Incident; back: string; projectId: number; taskKeys: Map<number, string> }) {
|
||||
async function IncidentCard({ i, back, projectId, taskKeys }: { i: Incident; back: string; projectId: number; taskKeys: Map<number, string> }) {
|
||||
const t = await getT();
|
||||
const taskKey = i.taskId ? taskKeys.get(i.taskId) : null;
|
||||
const decide = (action: string, label: string, icon: React.ReactNode) => (
|
||||
<form action={decideIncidentAction}>
|
||||
@ -140,12 +144,12 @@ function IncidentCard({ i, back, projectId, taskKeys }: { i: Incident; back: str
|
||||
return (
|
||||
<article className="flex flex-col gap-1.5 rounded-lg border bg-card p-3.5 text-sm">
|
||||
<div className="flex items-start gap-2">
|
||||
<Badge variant={STATUS_TONE[i.status]}>{INCIDENT_STATUS_RU[i.status]}</Badge>
|
||||
<Badge variant={STATUS_TONE[i.status]}>{t(INCIDENT_STATUS_RU[i.status])}</Badge>
|
||||
<b className="min-w-0 flex-1 font-mono text-[13px] font-medium [overflow-wrap:anywhere]">{i.title}</b>
|
||||
<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.source} · {i.environment ?? "—"} · {t("релиз {release}", { release: i.lastRelease ?? "—" })} · {t("событий {n}", { n: i.events })}
|
||||
{i.culprit && (
|
||||
<span className="inline-flex items-center gap-1">
|
||||
· <MapPin className="size-3" /> {i.culprit}
|
||||
@ -162,13 +166,13 @@ function IncidentCard({ i, back, projectId, taskKeys }: { i: Incident; back: str
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
{i.decisionReason && <div className="text-xs text-muted-foreground">{i.decidedBy === "triage" ? "🤖 " : ""}{i.decisionReason}</div>}
|
||||
{i.decisionReason && <div className="text-xs text-muted-foreground">{i.decidedBy === "triage" ? "🤖 " : ""}{t.text(i.decisionReason)}</div>}
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{!i.taskId && i.status !== "resolved" && (
|
||||
<>
|
||||
{decide("backlog", "В бэклог", <Inbox />)}
|
||||
{decide("start", "В работу", <Play />)}
|
||||
{i.status !== "ignored" && decide("ignore", "Игнорировать", <EyeOff />)}
|
||||
{decide("backlog", t("В бэклог"), <Inbox />)}
|
||||
{decide("start", t("В работу"), <Play />)}
|
||||
{i.status !== "ignored" && decide("ignore", t("Игнорировать"), <EyeOff />)}
|
||||
</>
|
||||
)}
|
||||
{i.status !== "resolved" && i.status !== "ignored" && (
|
||||
@ -176,7 +180,7 @@ function IncidentCard({ i, back, projectId, taskKeys }: { i: Incident; back: str
|
||||
<Hidden fields={{ projectId, back, incidentId: i.id }} />
|
||||
<Button size="xs">
|
||||
<CircleCheck />
|
||||
Исправлено
|
||||
{t("Исправлено")}
|
||||
</Button>
|
||||
</form>
|
||||
)}
|
||||
|
||||
@ -3,14 +3,16 @@
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useT } from "@/components/I18n";
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
|
||||
type Mode = "connecting" | "live" | "reconnecting" | "polling";
|
||||
|
||||
const LABEL: Record<Mode, string> = {
|
||||
connecting: "подключение…",
|
||||
live: "в реальном времени",
|
||||
reconnecting: "переподключение…",
|
||||
polling: "опрос раз в 5 с",
|
||||
connecting: m("подключение…"),
|
||||
live: m("в реальном времени"),
|
||||
reconnecting: m("переподключение…"),
|
||||
polling: m("опрос раз в 5 с"),
|
||||
};
|
||||
const DOT: Record<Mode, string> = {
|
||||
connecting: "bg-muted-foreground",
|
||||
@ -36,6 +38,7 @@ export function LiveRefresh({ scope, pollMs = 5000 }: { scope: string; pollMs?:
|
||||
const router = useRouter();
|
||||
const [mode, setMode] = useState<Mode>("connecting");
|
||||
const pending = useRef(false);
|
||||
const t = useT();
|
||||
|
||||
useEffect(() => {
|
||||
let closed = false;
|
||||
@ -115,11 +118,11 @@ export function LiveRefresh({ scope, pollMs = 5000 }: { scope: string; pollMs?:
|
||||
<div
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
title={mode === "polling" ? "Канал событий недоступен — страница обновляется по таймеру" : "Страница обновляется сама, когда что-то меняется"}
|
||||
title={mode === "polling" ? t("Канал событий недоступен — страница обновляется по таймеру") : t("Страница обновляется сама, когда что-то меняется")}
|
||||
className="pointer-events-none fixed right-3 bottom-3 z-40 flex items-center gap-1.5 rounded-full border bg-background/90 px-2.5 py-1 font-mono text-[11px] text-muted-foreground shadow-sm backdrop-blur"
|
||||
>
|
||||
<span className={cn("size-1.5 rounded-full", DOT[mode])} />
|
||||
{LABEL[mode]}
|
||||
{t(LABEL[mode])}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@ -1,15 +1,18 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef } from "react";
|
||||
import { useLocale } from "@/components/I18n";
|
||||
import { intlLocale } from "@peppa/shared/i18n";
|
||||
|
||||
/** HH:MM (with the date when not today) in the viewer's time zone; the server renders its own zone first. */
|
||||
export function LocalTime({ iso }: { iso: string }) {
|
||||
const d = new Date(iso);
|
||||
const loc = intlLocale(useLocale());
|
||||
const today = new Date().toDateString() === d.toDateString();
|
||||
const time = d.toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" });
|
||||
const time = d.toLocaleTimeString(loc, { hour: "2-digit", minute: "2-digit" });
|
||||
return (
|
||||
<time dateTime={iso} suppressHydrationWarning>
|
||||
{today ? time : `${d.toLocaleDateString("ru-RU", { day: "2-digit", month: "2-digit" })} ${time}`}
|
||||
{today ? time : `${d.toLocaleDateString(loc, { day: "2-digit", month: "2-digit" })} ${time}`}
|
||||
</time>
|
||||
);
|
||||
}
|
||||
|
||||
@ -7,34 +7,36 @@ import { Hidden } from "@/components/cards";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { OwnBotSteps } from "@/components/OwnBotSteps";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { getT } from "@/lib/i18n";
|
||||
|
||||
export function OnboardingChecklist({ data, botUsername = null }: { data: Onboarding; botUsername?: string | null }) {
|
||||
export async function OnboardingChecklist({ data, botUsername = null }: { data: Onboarding; botUsername?: string | null }) {
|
||||
const t = await getT();
|
||||
const next = data.steps.find((s) => !s.done && !s.optional);
|
||||
const fresh = data.done === 0;
|
||||
return (
|
||||
<section aria-label="С чего начать" className="mb-8 rounded-xl border bg-card p-5">
|
||||
<section aria-label={t("С чего начать")} className="mb-8 rounded-xl border bg-card p-5">
|
||||
<div className="mb-1 flex flex-wrap items-start gap-3">
|
||||
<div className="min-w-0 flex-1">
|
||||
<h2 className="m-0 text-lg font-semibold">{fresh ? "Добро пожаловать! Запустим вашу фабрику за шесть шагов" : "С чего начать"}</h2>
|
||||
<h2 className="m-0 text-lg font-semibold">{fresh ? t("Добро пожаловать! Запустим вашу фабрику за шесть шагов") : t("С чего начать")}</h2>
|
||||
<p className="m-0 mt-1 text-sm text-muted-foreground">
|
||||
{fresh
|
||||
? "Вы описываете задачу обычными словами — команда ИИ-агентов пишет код и показывает результат. Программировать не нужно. Идите по шагам сверху вниз."
|
||||
: "Идите по шагам сверху вниз — на текущем шаге есть кнопка."}
|
||||
? t("Вы описываете задачу обычными словами — команда ИИ-агентов пишет код и показывает результат. Программировать не нужно. Идите по шагам сверху вниз.")
|
||||
: t("Идите по шагам сверху вниз — на текущем шаге есть кнопка.")}
|
||||
</p>
|
||||
</div>
|
||||
<form action={dismissOnboardingAction}>
|
||||
<Hidden fields={{ back: "/" }} />
|
||||
<Button size="sm" variant="ghost" title="Скрыть шаги" aria-label="Скрыть шаги">
|
||||
<X className="size-4" /> Скрыть
|
||||
<Button size="sm" variant="ghost" title={t("Скрыть шаги")} aria-label={t("Скрыть шаги")}>
|
||||
<X className="size-4" /> {t("Скрыть")}
|
||||
</Button>
|
||||
</form>
|
||||
</div>
|
||||
<div className="mb-4 flex items-center gap-3">
|
||||
<div className="h-1.5 min-w-24 flex-1 overflow-hidden rounded-full bg-muted" role="progressbar" aria-valuemin={0} aria-valuemax={data.total} aria-valuenow={data.done} aria-label={`Сделано ${data.done} из ${data.total}`}>
|
||||
<div className="h-1.5 min-w-24 flex-1 overflow-hidden rounded-full bg-muted" role="progressbar" aria-valuemin={0} aria-valuemax={data.total} aria-valuenow={data.done} aria-label={t("Сделано {done} из {total}", { done: data.done, total: data.total })}>
|
||||
<div className="h-full rounded-full bg-primary" style={{ width: `${Math.round((data.done / Math.max(1, data.total)) * 100)}%` }} />
|
||||
</div>
|
||||
<span className="text-xs text-muted-foreground tabular-nums">
|
||||
{data.done} из {data.total}
|
||||
{t("{done} из {total}", { done: data.done, total: data.total })}
|
||||
</span>
|
||||
</div>
|
||||
<ol className="m-0 flex list-none flex-col gap-1.5 p-0">
|
||||
@ -52,8 +54,8 @@ export function OnboardingChecklist({ data, botUsername = null }: { data: Onboar
|
||||
{s.done ? <Check className="size-3.5" /> : i + 1}
|
||||
</span>
|
||||
<div className="flex min-w-0 flex-1 flex-col gap-1">
|
||||
<span className={cn("text-sm font-medium", s.done && "text-muted-foreground line-through")}>{s.title}</span>
|
||||
{!s.done && <span className="text-sm text-muted-foreground">{s.hint}</span>}
|
||||
<span className={cn("text-sm font-medium", s.done && "text-muted-foreground line-through")}>{t.text(s.title)}</span>
|
||||
{!s.done && <span className="text-sm text-muted-foreground">{t.text(s.hint)}</span>}
|
||||
{current && s.id === "telegram" ? (
|
||||
// PEP-85: the first thing to do — right here, not behind a link to Settings.
|
||||
<div className="mt-1">
|
||||
@ -62,7 +64,7 @@ export function OnboardingChecklist({ data, botUsername = null }: { data: Onboar
|
||||
) : current && (
|
||||
<Button asChild variant="default" size="sm" className="mt-1 self-start">
|
||||
<a href={s.href}>
|
||||
{s.action} <ArrowRight />
|
||||
{t.text(s.action)} <ArrowRight />
|
||||
</a>
|
||||
</Button>
|
||||
)}
|
||||
|
||||
@ -3,6 +3,7 @@ import { Hidden } from "@/components/cards";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { getT } from "@/lib/i18n";
|
||||
|
||||
function StepNum({ n, done }: { n: number; done: boolean }) {
|
||||
return (
|
||||
@ -16,29 +17,31 @@ function StepNum({ n, done }: { n: number; done: boolean }) {
|
||||
* PEP-85: connecting the user's own Telegram bot in three plain steps (BotFather → token →
|
||||
* Start). Shown on the Home page as the first thing a new user does, and in Settings.
|
||||
*/
|
||||
export function OwnBotSteps({ botUsername, back, bare = false }: { botUsername: string | null; back: string; bare?: boolean }) {
|
||||
export async function OwnBotSteps({ botUsername, back, bare = false }: { botUsername: string | null; back: string; bare?: boolean }) {
|
||||
const t = await getT();
|
||||
const hasBot = !!botUsername;
|
||||
const fields = { back };
|
||||
return (
|
||||
<div className={cn("flex flex-col gap-4", !bare && "rounded-lg border bg-card p-4")}>
|
||||
{!bare && (
|
||||
<p className="m-0 text-sm">
|
||||
Через Telegram фабрика зовёт вас, когда агенту нужен ответ или работа готова, — отвечать можно кнопками с телефона. У каждого пользователя свой бот: вы создаёте его за две минуты, без программирования.
|
||||
{t("Через Telegram фабрика зовёт вас, когда агенту нужен ответ или работа готова, — отвечать можно кнопками с телефона. У каждого пользователя свой бот: вы создаёте его за две минуты, без программирования.")}
|
||||
</p>
|
||||
)}
|
||||
<ol className="m-0 flex list-none flex-col gap-3 p-0 text-sm">
|
||||
<li className="flex gap-2.5">
|
||||
<StepNum n={1} done={hasBot} />
|
||||
<div className="flex min-w-0 flex-col items-start gap-1.5">
|
||||
<span className="font-medium">Создайте бота в Telegram</span>
|
||||
<span className="font-medium">{t("Создайте бота в Telegram")}</span>
|
||||
{!hasBot && (
|
||||
<>
|
||||
<span className="text-muted-foreground">
|
||||
Откройте <b>@BotFather</b> (официальный бот Telegram), отправьте ему <span className="font-mono">/newbot</span>, придумайте название и адрес — адрес должен заканчиваться на <span className="font-mono">bot</span>, например{" "}
|
||||
<span className="font-mono">my_factory_bot</span>.
|
||||
{t("Откройте")} <b>@BotFather</b> {t("(официальный бот Telegram), отправьте ему")} <span className="font-mono">/newbot</span>
|
||||
{t(", придумайте название и адрес — адрес должен заканчиваться на")} <span className="font-mono">bot</span>
|
||||
{t(", например")} <span className="font-mono">my_factory_bot</span>.
|
||||
</span>
|
||||
<Button asChild size="sm" variant="outline">
|
||||
<a href="https://t.me/BotFather" target="_blank" rel="noreferrer">Открыть BotFather</a>
|
||||
<a href="https://t.me/BotFather" target="_blank" rel="noreferrer">{t("Открыть BotFather")}</a>
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
@ -47,20 +50,20 @@ export function OwnBotSteps({ botUsername, back, bare = false }: { botUsername:
|
||||
<li className="flex gap-2.5">
|
||||
<StepNum n={2} done={hasBot} />
|
||||
<div className="flex min-w-0 flex-1 flex-col items-start gap-1.5">
|
||||
<span className="font-medium">Вставьте токен бота</span>
|
||||
<span className="font-medium">{t("Вставьте токен бота")}</span>
|
||||
{hasBot ? (
|
||||
<span className="text-muted-foreground">
|
||||
Подключён <span className="font-mono">@{botUsername}</span>. Токен хранится зашифрованным.
|
||||
{t("Подключён")} <span className="font-mono">@{botUsername}</span>. {t("Токен хранится зашифрованным.")}
|
||||
</span>
|
||||
) : (
|
||||
<>
|
||||
<span className="text-muted-foreground">
|
||||
BotFather пришлёт сообщение с длинной строкой вида <span className="font-mono">1234567890:AAH…</span> — это токен. Скопируйте его сюда. Пеппа хранит его зашифрованным и никому не показывает.
|
||||
{t("BotFather пришлёт сообщение с длинной строкой вида")} <span className="font-mono">1234567890:AAH…</span> {t("— это токен. Скопируйте его сюда. Пеппа хранит его зашифрованным и никому не показывает.")}
|
||||
</span>
|
||||
<form action={connectOwnBotAction} className="flex w-full flex-wrap gap-2">
|
||||
<Hidden fields={fields} />
|
||||
<Input name="token" type="password" required autoComplete="off" placeholder="Токен от BotFather" aria-label="Токен бота" className="h-9 min-w-48 flex-1 font-mono" />
|
||||
<Button variant="default">Подключить бота</Button>
|
||||
<Input name="token" type="password" required autoComplete="off" placeholder={t("Токен от BotFather")} aria-label={t("Токен бота")} className="h-9 min-w-48 flex-1 font-mono" />
|
||||
<Button variant="default">{t("Подключить бота")}</Button>
|
||||
</form>
|
||||
</>
|
||||
)}
|
||||
@ -69,12 +72,12 @@ export function OwnBotSteps({ botUsername, back, bare = false }: { botUsername:
|
||||
<li className="flex gap-2.5">
|
||||
<StepNum n={3} done={false} />
|
||||
<div className="flex min-w-0 flex-col items-start gap-1.5">
|
||||
<span className="font-medium">Откройте своего бота и нажмите Start</span>
|
||||
<span className="text-muted-foreground">Так бот узнает, куда вам писать. Удобнее сделать это на телефоне — там и будут приходить сообщения.</span>
|
||||
<span className="font-medium">{t("Откройте своего бота и нажмите Start")}</span>
|
||||
<span className="text-muted-foreground">{t("Так бот узнает, куда вам писать. Удобнее сделать это на телефоне — там и будут приходить сообщения.")}</span>
|
||||
{hasBot && (
|
||||
<form action={pairTelegram}>
|
||||
<Hidden fields={fields} />
|
||||
<Button variant="default" size="sm">Открыть @{botUsername}</Button>
|
||||
<Button variant="default" size="sm">{t("Открыть @{bot}", { bot: botUsername })}</Button>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
@ -83,13 +86,13 @@ export function OwnBotSteps({ botUsername, back, bare = false }: { botUsername:
|
||||
{hasBot ? (
|
||||
<form action={disconnectOwnBotAction}>
|
||||
<Hidden fields={fields} />
|
||||
<Button size="xs" variant="ghost" className="text-muted-foreground">Отключить этого бота</Button>
|
||||
<Button size="xs" variant="ghost" className="text-muted-foreground">{t("Отключить этого бота")}</Button>
|
||||
</form>
|
||||
) : (
|
||||
<form action={pairTelegram} className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
|
||||
<Hidden fields={fields} />
|
||||
Не хотите создавать бота?
|
||||
<Button size="xs" variant="ghost">Использовать общего бота Пеппы</Button>
|
||||
{t("Не хотите создавать бота?")}
|
||||
<Button size="xs" variant="ghost">{t("Использовать общего бота Пеппы")}</Button>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@ -3,21 +3,23 @@ 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 { getT } from "@/lib/i18n";
|
||||
import { m, type Translator } from "@peppa/shared/i18n";
|
||||
|
||||
const PARTS = [
|
||||
{ k: "done", label: "готово", bar: "bg-ok" },
|
||||
{ k: "review", label: "ревью", bar: "bg-primary" },
|
||||
{ k: "inProgress", label: "в работе", bar: "bg-info" },
|
||||
{ k: "backlog", label: "бэклог", bar: "bg-muted-foreground/40" },
|
||||
{ k: "done", label: m("готово"), bar: "bg-ok" },
|
||||
{ k: "review", label: m("ревью"), bar: "bg-primary" },
|
||||
{ k: "inProgress", label: m("в работе"), bar: "bg-info" },
|
||||
{ k: "backlog", label: m("бэклог"), bar: "bg-muted-foreground/40" },
|
||||
] as const;
|
||||
|
||||
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 }) {
|
||||
const label = PARTS.map((p) => `${p.label} ${c[p.k]}`).join(", ");
|
||||
function StackedBar({ c, className, t }: { c: Counts; className?: string; t: Translator }) {
|
||||
const label = PARTS.map((p) => `${t(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={t("Стори: {list}", { list: 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>
|
||||
);
|
||||
@ -25,20 +27,20 @@ function StackedBar({ c, className }: { c: Counts; className?: string }) {
|
||||
|
||||
const pct = (c: Counts) => (c.total ? Math.round((c.done / c.total) * 100) : 0);
|
||||
|
||||
function Legend({ c }: { c: Counts }) {
|
||||
function Legend({ c, t }: { c: Counts; t: Translator }) {
|
||||
return (
|
||||
<span className="flex flex-wrap gap-x-3 gap-y-0.5 text-xs text-muted-foreground">
|
||||
{PARTS.map((p) => (
|
||||
<span key={p.k} className="inline-flex items-center gap-1">
|
||||
<span aria-hidden className={cn("size-2 rounded-full", p.bar)} />
|
||||
{p.label} <b className="font-medium text-foreground">{c[p.k]}</b>
|
||||
{t(p.label)} <b className="font-medium text-foreground">{c[p.k]}</b>
|
||||
</span>
|
||||
))}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function ProjectRow({ p }: { p: ProjectProgress }) {
|
||||
function ProjectRow({ p, t }: { p: ProjectProgress; t: Translator }) {
|
||||
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">
|
||||
@ -48,14 +50,14 @@ function ProjectRow({ p }: { p: ProjectProgress }) {
|
||||
<span className="ml-auto text-xs text-muted-foreground">
|
||||
{p.total ? (
|
||||
<>
|
||||
готово <b className="font-medium text-foreground">{p.done}</b> из {p.total} · {pct(p)}%
|
||||
{t("готово")} <b className="font-medium text-foreground">{p.done}</b> {t("из {total}", { total: p.total })} · {pct(p)}%
|
||||
</>
|
||||
) : (
|
||||
"стори пока нет"
|
||||
t("стори пока нет")
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
<StackedBar c={p} />
|
||||
<StackedBar c={p} t={t} />
|
||||
{p.working.length > 0 && (
|
||||
<ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm">
|
||||
{p.working.map((s) => (
|
||||
@ -74,11 +76,11 @@ function ProjectRow({ p }: { p: ProjectProgress }) {
|
||||
)}
|
||||
{p.reviewKeys.length > 0 && (
|
||||
<p className="m-0 flex flex-wrap items-center gap-1.5 text-xs text-muted-foreground">
|
||||
Ждут «Принять»:
|
||||
{t("Ждут «Принять»:")}
|
||||
{p.reviewKeys.slice(0, 8).map((k) => (
|
||||
<Key key={k} href={`/t/${k}`}>{k}</Key>
|
||||
))}
|
||||
{p.reviewKeys.length > 8 && <span>и ещё {p.reviewKeys.length - 8}</span>}
|
||||
{p.reviewKeys.length > 8 && <span>{t("и ещё {n}", { n: p.reviewKeys.length - 8 })}</span>}
|
||||
</p>
|
||||
)}
|
||||
</li>
|
||||
@ -86,26 +88,27 @@ 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>;
|
||||
const t = data.totals;
|
||||
export async function ProgressOverview({ data }: { data: Overview }) {
|
||||
const t = await getT();
|
||||
if (!data.mine.length) return <Empty>{t("Проектов пока нет — прогресс появится с первой стори.")}</Empty>;
|
||||
const tot = data.totals;
|
||||
return (
|
||||
<div className="flex flex-col gap-3">
|
||||
{data.mine.length > 0 && (
|
||||
<div className="flex flex-col gap-2 rounded-lg border bg-card px-4 py-3">
|
||||
<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-2xl font-semibold tabular-nums">{pct(tot)}%</span>
|
||||
<span className="text-sm text-muted-foreground">
|
||||
готово {t.done} из {t.total} стори в {data.mine.length} {data.mine.length === 1 ? "проекте" : "проектах"}
|
||||
{t.n(data.mine.length, "готово {done} из {total} стори в {n} проекте", "готово {done} из {total} стори в {n} проектах", "готово {done} из {total} стори в {n} проектах", { done: tot.done, total: tot.total })}
|
||||
</span>
|
||||
</div>
|
||||
<StackedBar c={t} className="h-3" />
|
||||
<Legend c={t} />
|
||||
<StackedBar c={tot} className="h-3" t={t} />
|
||||
<Legend c={tot} t={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} t={t} />
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
@ -4,26 +4,28 @@ import { Hidden } from "@/components/cards";
|
||||
import { ago } from "@/components/common";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input, Textarea } from "@/components/ui/input";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import { deleteProjectSecretAction, saveProjectSecretAction } from "@/app/(app)/actions";
|
||||
|
||||
/** PEP-54: the project's secrets for agents — names only; values are write-only. */
|
||||
export function ProjectSecretsPanel({ projectId, secrets, back }: { projectId: number; secrets: ProjectSecretView[]; back: string }) {
|
||||
export async function ProjectSecretsPanel({ projectId, secrets, back }: { projectId: number; secrets: ProjectSecretView[]; back: string }) {
|
||||
const t = await getT();
|
||||
return (
|
||||
<div className="flex flex-col gap-3">
|
||||
{secrets.length > 0 && (
|
||||
<ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm" aria-label="Секреты проекта">
|
||||
<ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm" aria-label={t("Секреты проекта")}>
|
||||
{secrets.map((s) => (
|
||||
<li key={s.id} className="flex items-center gap-2 rounded-md border bg-background/40 px-2.5 py-1.5">
|
||||
<span className="flex min-w-0 flex-1 flex-col">
|
||||
<span className="truncate font-mono text-[13px]">{s.name}</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
изменён {ago(s.updatedAt)}
|
||||
{s.updatedBy ? ` · ${s.updatedBy}` : ""} · {s.lastUsedAt ? `выдан агенту ${ago(s.lastUsedAt)}` : "агентам ещё не выдавался"}
|
||||
{t("изменён {ago}", { ago: ago(s.updatedAt, t) })}
|
||||
{s.updatedBy ? ` · ${s.updatedBy}` : ""} · {s.lastUsedAt ? t("выдан агенту {ago}", { ago: ago(s.lastUsedAt, t) }) : t("агентам ещё не выдавался")}
|
||||
</span>
|
||||
</span>
|
||||
<form action={deleteProjectSecretAction}>
|
||||
<Hidden fields={{ projectId, name: s.name, back }} />
|
||||
<Button variant="ghost" size="icon" aria-label={`Удалить ${s.name}`} title={`Удалить ${s.name}`}>
|
||||
<Button variant="ghost" size="icon" aria-label={t("Удалить {name}", { name: s.name })} title={t("Удалить {name}", { name: s.name })}>
|
||||
<Trash2 />
|
||||
</Button>
|
||||
</form>
|
||||
@ -33,12 +35,12 @@ export function ProjectSecretsPanel({ projectId, secrets, back }: { projectId: n
|
||||
)}
|
||||
<form action={saveProjectSecretAction} className="flex flex-col gap-2" autoComplete="off">
|
||||
<Hidden fields={{ projectId, back }} />
|
||||
<Input name="name" required placeholder="STRIPE_TEST_KEY" aria-label="Имя секрета" pattern="[A-Z][A-Z0-9_]{0,63}" className="font-mono" autoComplete="off" spellCheck={false} />
|
||||
<Textarea name="value" required rows={2} placeholder="Значение — после сохранения его не увидит никто" aria-label="Значение секрета" className="font-mono" autoComplete="off" spellCheck={false} />
|
||||
<Button size="sm" className="self-start">Сохранить</Button>
|
||||
<Input name="name" required placeholder="STRIPE_TEST_KEY" aria-label={t("Имя секрета")} pattern="[A-Z][A-Z0-9_]{0,63}" className="font-mono" autoComplete="off" spellCheck={false} />
|
||||
<Textarea name="value" required rows={2} placeholder={t("Значение — после сохранения его не увидит никто")} aria-label={t("Значение секрета")} className="font-mono" autoComplete="off" spellCheck={false} />
|
||||
<Button size="sm" className="self-start">{t("Сохранить")}</Button>
|
||||
</form>
|
||||
<p className="m-0 text-xs text-muted-foreground">
|
||||
Секреты получают агенты проекта как переменные окружения с тем же именем — при следующем запуске сессии. Имя существующего секрета заменяет его значение. Значение хранится зашифрованным и больше не показывается; в терминале и ленте шагов оно заменяется на «••••». Агент видит только имена (<code>list_secrets</code>).
|
||||
{t("Секреты получают агенты проекта как переменные окружения с тем же именем — при следующем запуске сессии. Имя существующего секрета заменяет его значение. Значение хранится зашифрованным и больше не показывается; в терминале и ленте шагов оно заменяется на «••••». Агент видит только имена")} (<code>list_secrets</code>).
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
|
||||
@ -1,12 +1,16 @@
|
||||
// PEP-70: Peppa's mascot — a soft "clay" chibi pug with a terminal prompt (`> _`) glowing on its belly.
|
||||
// Pure SVG (no external images), fixed colours that read on both themes; motion only without
|
||||
// reduced-motion (see .pug-* in app.css).
|
||||
"use client";
|
||||
|
||||
import { useId } from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useT } from "@/components/I18n";
|
||||
|
||||
type Mood = "sleep" | "alert";
|
||||
|
||||
export function PugMascot({ mood, size = 96, className }: { mood: Mood; size?: number; className?: string }) {
|
||||
const t = useT();
|
||||
const awake = mood === "alert";
|
||||
const id = useId().replace(/[^a-zA-Z0-9]/g, "");
|
||||
const fur = `pf${id}`, furDark = `pd${id}`, ear = `pe${id}`, screen = `ps${id}`, glow = `pg${id}`, soft = `po${id}`;
|
||||
@ -16,7 +20,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 ? t("Мопс Пеппы ждёт твоего ответа") : t("Мопс Пеппы спит")}
|
||||
className={cn("shrink-0 overflow-visible", awake ? "pug-alert" : "pug-sleep", className)}
|
||||
>
|
||||
<defs>
|
||||
@ -122,6 +126,7 @@ export function PugMascot({ mood, size = 96, className }: { mood: Mood; size?: n
|
||||
|
||||
/** Mascot with a speech bubble: sleeps when nothing waits, perks up when agents ask. */
|
||||
export function PugBanner({ count }: { count: number }) {
|
||||
const t = useT();
|
||||
const awake = count > 0;
|
||||
return (
|
||||
<div className="flex items-center gap-3">
|
||||
@ -129,19 +134,14 @@ 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="text-muted-foreground"> — {plural(count)} ниже.</span>
|
||||
<span className="font-medium">{count === 1 ? t("Гав! Агент ждёт твоего ответа") : t("Гав! Агенты ждут твоего ответа")}</span>
|
||||
<span className="text-muted-foreground">{t.n(count, " — {n} вопрос ниже.", " — {n} вопроса ниже.", " — {n} вопросов ниже.")}</span>
|
||||
</>
|
||||
) : (
|
||||
<span className="text-muted-foreground">Тихо… Агентам от тебя ничего не нужно, мопс спит.</span>
|
||||
<span className="text-muted-foreground">{t("Тихо… Агентам от тебя ничего не нужно, мопс спит.")}</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function plural(n: number) {
|
||||
const m10 = n % 10, m100 = n % 100;
|
||||
const w = m10 === 1 && m100 !== 11 ? "вопрос" : m10 >= 2 && m10 <= 4 && (m100 < 12 || m100 > 14) ? "вопроса" : "вопросов";
|
||||
return `${n} ${w}`;
|
||||
}
|
||||
|
||||
@ -3,6 +3,7 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Bell, BellOff, Send } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useT } from "@/components/I18n";
|
||||
import { deletePushSubscriptionAction, savePushSubscriptionAction, testPushAction } from "@/app/(app)/actions";
|
||||
|
||||
type State = "loading" | "unsupported" | "denied" | "off" | "on";
|
||||
@ -19,6 +20,7 @@ async function registration() {
|
||||
|
||||
/** «Push в этом браузере» (PEP-55): permission, Web Push subscription, test, unsubscribe. */
|
||||
export function PushNotifications({ vapidKey, known }: { vapidKey: string; known: string[] }) {
|
||||
const t = useT();
|
||||
const [state, setState] = useState<State>("loading");
|
||||
const [endpoint, setEndpoint] = useState<string | null>(null);
|
||||
const [msg, setMsg] = useState<string | null>(null);
|
||||
@ -49,7 +51,7 @@ export function PushNotifications({ vapidKey, known }: { vapidKey: string; known
|
||||
setEndpoint(sub.endpoint);
|
||||
setState("on");
|
||||
} catch (e) {
|
||||
setMsg(`Не удалось включить: ${(e as Error).message}`);
|
||||
setMsg(t("Не удалось включить: {message}", { message: (e as Error).message }));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
@ -75,7 +77,7 @@ export function PushNotifications({ vapidKey, known }: { vapidKey: string; known
|
||||
if (!endpoint) return;
|
||||
setBusy(true);
|
||||
const r = await testPushAction(endpoint).catch((e) => ({ ok: false, error: String(e) }));
|
||||
setMsg(r.ok ? "Отправлено — уведомление должно появиться через пару секунд." : `Не дошло: ${r.error}`);
|
||||
setMsg(r.ok ? t("Отправлено — уведомление должно появиться через пару секунд.") : t("Не дошло: {error}", { error: t.text(r.error) }));
|
||||
setBusy(false);
|
||||
}
|
||||
|
||||
@ -84,24 +86,24 @@ export function PushNotifications({ vapidKey, known }: { vapidKey: string; known
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{state === "on" ? (
|
||||
<>
|
||||
<span className="text-sm">Push в этом браузере включены.</span>
|
||||
<span className="text-sm">{t("Push в этом браузере включены.")}</span>
|
||||
<Button size="sm" type="button" onClick={test} disabled={busy}>
|
||||
<Send /> Проверить
|
||||
<Send /> {t("Проверить")}
|
||||
</Button>
|
||||
<Button size="sm" type="button" variant="destructive" onClick={disable} disabled={busy}>
|
||||
<BellOff /> Отключить
|
||||
<BellOff /> {t("Отключить")}
|
||||
</Button>
|
||||
</>
|
||||
) : state === "off" ? (
|
||||
<Button size="sm" type="button" variant="default" onClick={enable} disabled={busy}>
|
||||
<Bell /> Включить push в этом браузере
|
||||
<Bell /> {t("Включить push в этом браузере")}
|
||||
</Button>
|
||||
) : state === "denied" ? (
|
||||
<span className="text-sm text-muted-foreground">Уведомления для этого сайта запрещены в браузере — разрешите их в настройках сайта (значок слева от адреса) и обновите страницу.</span>
|
||||
<span className="text-sm text-muted-foreground">{t("Уведомления для этого сайта запрещены в браузере — разрешите их в настройках сайта (значок слева от адреса) и обновите страницу.")}</span>
|
||||
) : state === "unsupported" ? (
|
||||
<span className="text-sm text-muted-foreground">Этот браузер не умеет Web Push. В Safari на iPhone — сначала «На экран Домой».</span>
|
||||
<span className="text-sm text-muted-foreground">{t("Этот браузер не умеет Web Push. В Safari на iPhone — сначала «На экран Домой».")}</span>
|
||||
) : (
|
||||
<span className="text-sm text-muted-foreground">Проверяю…</span>
|
||||
<span className="text-sm text-muted-foreground">{t("Проверяю…")}</span>
|
||||
)}
|
||||
</div>
|
||||
{msg && <p className="m-0 text-sm text-muted-foreground">{msg}</p>}
|
||||
|
||||
@ -3,27 +3,29 @@
|
||||
import { Eye, FileDiff, CircleDot } from "lucide-react";
|
||||
import type { ReviewPreview as Preview } from "@peppa/core";
|
||||
import { PanelSection } from "@/components/ActivityAside";
|
||||
import { getT } from "@/lib/i18n";
|
||||
|
||||
export function ReviewPreview({ preview }: { preview: Preview }) {
|
||||
export async function ReviewPreview({ preview }: { preview: Preview }) {
|
||||
if (!preview.previewUrl && !preview.diffUrl && !preview.issueUrl) return null;
|
||||
const t = await getT();
|
||||
return (
|
||||
<PanelSection title="Превью">
|
||||
<PanelSection title={t("Превью")}>
|
||||
<div className="flex flex-col gap-1.5 text-sm">
|
||||
{preview.previewUrl ? (
|
||||
<a href={preview.previewUrl} target="_blank" rel="noreferrer" className="flex items-center gap-1.5 text-primary [overflow-wrap:anywhere]">
|
||||
<Eye className="size-4" /> Посмотреть{preview.sha && <span className="font-mono text-xs text-muted-foreground">{preview.sha.slice(0, 7)}</span>}
|
||||
<Eye className="size-4" /> {t("Посмотреть")}{preview.sha && <span className="font-mono text-xs text-muted-foreground">{preview.sha.slice(0, 7)}</span>}
|
||||
</a>
|
||||
) : (
|
||||
preview.diffUrl && <span className="text-xs text-muted-foreground">Стенда PR ещё нет (деплой превью не настроен или не прошёл).</span>
|
||||
preview.diffUrl && <span className="text-xs text-muted-foreground">{t("Стенда PR ещё нет (деплой превью не настроен или не прошёл).")}</span>
|
||||
)}
|
||||
{preview.diffUrl && (
|
||||
<a href={preview.diffUrl} target="_blank" rel="noreferrer" className="flex items-center gap-1.5 text-primary">
|
||||
<FileDiff className="size-4" /> Дифф
|
||||
<FileDiff className="size-4" /> {t("Дифф")}
|
||||
</a>
|
||||
)}
|
||||
{preview.issueUrl && (
|
||||
<a href={preview.issueUrl} target="_blank" rel="noreferrer" className="flex items-center gap-1.5 text-primary">
|
||||
<CircleDot className="size-4" /> Issue в Gitea
|
||||
<CircleDot className="size-4" /> {t("Issue в Gitea")}
|
||||
</a>
|
||||
)}
|
||||
</div>
|
||||
@ -34,7 +36,7 @@ export function ReviewPreview({ preview }: { preview: Preview }) {
|
||||
return (
|
||||
<a key={s.n} href={src} target="_blank" rel="noreferrer" title={s.path} className="block overflow-hidden rounded border">
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img src={src} alt={`Скриншот ${s.path}`} loading="lazy" className="block aspect-[16/10] w-full object-cover object-top" />
|
||||
<img src={src} alt={t("Скриншот {path}", { path: s.path })} loading="lazy" className="block aspect-[16/10] w-full object-cover object-top" />
|
||||
<span className="block truncate px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground">{s.path}</span>
|
||||
</a>
|
||||
);
|
||||
|
||||
@ -14,15 +14,18 @@ import { SessionUsageLine } from "@/components/Accounting";
|
||||
import type { InboxItem } from "@/lib/queries";
|
||||
import { SESSION_STATUS, TONE_BG, TONE_TEXT } from "@/lib/status";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import { translator, type Translator } from "@peppa/shared/i18n";
|
||||
|
||||
/** «остановлена · продолжит в 03:10» for a runner that hit the usage limit (PEP-56). */
|
||||
export function LimitNote({ s }: { s: SessionView }) {
|
||||
export async function LimitNote({ s }: { s: SessionView }) {
|
||||
if (s.status !== "rate_limited") return null;
|
||||
if (!s.resumeAt) return <>остановлена · лимит</>;
|
||||
if (s.resumeAt.getTime() <= Date.now()) return <>остановлена · продолжит сейчас</>;
|
||||
const t = await getT();
|
||||
if (!s.resumeAt) return <>{t("остановлена · лимит")}</>;
|
||||
if (s.resumeAt.getTime() <= Date.now()) return <>{t("остановлена · продолжит сейчас")}</>;
|
||||
return (
|
||||
<>
|
||||
остановлена · продолжит в <LocalTime iso={s.resumeAt.toISOString()} />
|
||||
{t("остановлена · продолжит в")} <LocalTime iso={s.resumeAt.toISOString()} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@ -35,24 +38,27 @@ interface SwitchPayload {
|
||||
}
|
||||
|
||||
/** «Claude A → Claude B · лимит · разговор продолжен» for a subscription_switched event (PEP-39). */
|
||||
export function switchText(payload: unknown): string {
|
||||
export function switchText(payload: unknown, t: Translator = translator("ru")): string {
|
||||
const p = (payload ?? {}) as SwitchPayload;
|
||||
return `${p.fromName ?? "?"} → ${p.toName ?? "?"} · ${p.reason === "threshold" ? "порог использования" : "лимит"} · ${p.carried === "fresh" ? "запуск заново" : "разговор продолжен"}`;
|
||||
const reason = p.reason === "threshold" ? t("порог использования") : t("лимит");
|
||||
const carried = p.carried === "fresh" ? t("запуск заново") : t("разговор продолжен");
|
||||
return `${p.fromName ?? "?"} → ${p.toName ?? "?"} · ${reason} · ${carried}`;
|
||||
}
|
||||
|
||||
/** One line of a session's event log: type + the human part for known types. */
|
||||
export function eventLine(e: { type: string; payload: unknown }): string {
|
||||
/** One line of a session's event log: type + the human part for known types. `t` defaults to Russian. */
|
||||
export function eventLine(e: { type: string; payload: unknown }, t: Translator = translator("ru")): string {
|
||||
if (e.type === "progress") return (e.payload as { text: string }).text;
|
||||
if (e.type === "subscription_switched") return switchText(e.payload);
|
||||
if (e.type === "subscription_switched") return switchText(e.payload, t);
|
||||
if (e.type === "task_updated") return JSON.stringify((e.payload as { to: unknown }).to);
|
||||
if (e.type === "pm_comment") return (e.payload as { text: string }).text;
|
||||
if (e.type === "question_answered") return `ответ на #${(e.payload as { questionId?: number }).questionId}: ${(e.payload as { answer?: string }).answer ?? ""}`;
|
||||
if (e.type === "budget_paused") return `бюджет исчерпан: ${(e.payload as { summary?: string }).summary ?? ""}`;
|
||||
if (e.type === "question_answered") return t("ответ на #{id}: {answer}", { id: (e.payload as { questionId?: number }).questionId, answer: (e.payload as { answer?: string }).answer ?? "" });
|
||||
if (e.type === "budget_paused") return t("бюджет исчерпан: {summary}", { summary: (e.payload as { summary?: string }).summary ?? "" });
|
||||
return "";
|
||||
}
|
||||
|
||||
/** `selected`: "wide" — picked by default, highlighted only where the side panel is visible. */
|
||||
export function RunnerRow({ s, href, selected, needsPm }: { s: SessionView; href: string; selected: boolean | "wide"; needsPm: boolean }) {
|
||||
export async function RunnerRow({ s, href, selected, needsPm }: { s: SessionView; href: string; selected: boolean | "wide"; needsPm: boolean }) {
|
||||
const t = await getT();
|
||||
const limited = s.status === "rate_limited";
|
||||
const st = SESSION_STATUS[s.status] ?? { label: s.status, tone: "muted" as const };
|
||||
return (
|
||||
@ -72,17 +78,17 @@ export function RunnerRow({ s, href, selected, needsPm }: { s: SessionView; href
|
||||
<span className={cn("row-span-2 size-2 self-start mt-1.5 rounded-full", TONE_BG[st.tone], (s.status === "running" || s.status === "starting") && "animate-pulse")} />
|
||||
<span className="flex min-w-0 items-baseline gap-2">
|
||||
<span className="shrink-0 font-mono text-xs text-primary">{s.taskKey ?? s.projectKey}</span>
|
||||
<span className="truncate">{s.taskTitle ?? s.name ?? "без стори"}</span>
|
||||
<span className="truncate">{s.taskTitle ?? s.name ?? t("без стори")}</span>
|
||||
</span>
|
||||
<span className={cn("text-right font-mono text-xs whitespace-nowrap", TONE_TEXT[st.tone])}>{limited ? (
|
||||
<>
|
||||
<span className="sm:hidden">{st.label}</span>
|
||||
<span className="sm:hidden">{t(st.label)}</span>
|
||||
<span className="max-sm:hidden">
|
||||
<LimitNote s={s} />
|
||||
</span>
|
||||
</>
|
||||
) : (
|
||||
st.label
|
||||
t(st.label)
|
||||
)}
|
||||
</span>
|
||||
<span className="truncate font-mono text-[11px] text-muted-foreground">
|
||||
@ -99,7 +105,8 @@ export function RunnerRow({ s, href, selected, needsPm }: { s: SessionView; href
|
||||
);
|
||||
}
|
||||
|
||||
export function RunnerDetails({ s, questions, events, steps, stories, back, closeHref, chosen }: { s: SessionView; questions: InboxItem[]; events: Array<{ id: number; type: string; payload: unknown; createdAt: Date }>; steps: StepView[]; stories?: { history: RunnerTaskView[]; queue: RunnerTaskView[] }; back: string; closeHref: string; chosen: boolean }) {
|
||||
export async function RunnerDetails({ s, questions, events, steps, stories, back, closeHref, chosen }: { s: SessionView; questions: InboxItem[]; events: Array<{ id: number; type: string; payload: unknown; createdAt: Date }>; steps: StepView[]; stories?: { history: RunnerTaskView[]; queue: RunnerTaskView[] }; back: string; closeHref: string; chosen: boolean }) {
|
||||
const t = await getT();
|
||||
const finished = FINISHED_SESSION_STATUSES.includes(s.status);
|
||||
return (
|
||||
<div className="flex flex-col gap-5">
|
||||
@ -109,13 +116,13 @@ export function RunnerDetails({ s, questions, events, steps, stories, back, clos
|
||||
<div className="flex items-center gap-2">
|
||||
<StatusBadge status={s.status} kind="session" />
|
||||
<span className="font-mono text-xs text-muted-foreground">#{s.id}</span>
|
||||
<Link href={closeHref} scroll={false} aria-label="Закрыть" title="Закрыть" className="ml-auto rounded-md p-1 text-muted-foreground hover:bg-accent hover:text-foreground">
|
||||
<Link href={closeHref} scroll={false} aria-label={t("Закрыть")} title={t("Закрыть")} className="ml-auto rounded-md p-1 text-muted-foreground hover:bg-accent hover:text-foreground">
|
||||
<X className="size-4" />
|
||||
</Link>
|
||||
</div>
|
||||
<h2 className="m-0 text-base leading-snug font-semibold">
|
||||
{s.taskKey && <Key href={`/t/${s.taskKey}`} className="mr-1.5">{s.taskKey}</Key>}
|
||||
{s.taskTitle ?? s.name ?? "без стори"}
|
||||
{s.taskTitle ?? s.name ?? t("без стори")}
|
||||
</h2>
|
||||
{s.name && s.taskTitle && <p className="m-0 text-sm text-muted-foreground">{s.name}</p>}
|
||||
{/* PEP-5: tokens, cost, context of this runner. */}
|
||||
@ -124,36 +131,36 @@ export function RunnerDetails({ s, questions, events, steps, stories, back, clos
|
||||
<p className="m-0 rounded-md border border-warn/40 bg-warn/10 px-3 py-2 text-sm">
|
||||
<LimitNote s={s} />
|
||||
<span className="block text-xs text-muted-foreground">
|
||||
авто-продолжений сегодня: {s.limitResumes} из {MAX_LIMIT_RESUMES_PER_DAY}
|
||||
{t("авто-продолжений сегодня: {n} из {max}", { n: s.limitResumes, max: MAX_LIMIT_RESUMES_PER_DAY })}
|
||||
</span>
|
||||
{s.rotateReason === "limit" && <span className="block text-xs">переключается на свободную подписку пула…</span>}
|
||||
{s.rotateReason === "limit" && <span className="block text-xs">{t("переключается на свободную подписку пула…")}</span>}
|
||||
</p>
|
||||
)}
|
||||
{s.rotateReason === "threshold" && (
|
||||
<p className="m-0 rounded-md border border-warn/40 bg-warn/10 px-3 py-2 text-sm">Подписка подходит к лимиту — после этого хода переключится на свободную.</p>
|
||||
<p className="m-0 rounded-md border border-warn/40 bg-warn/10 px-3 py-2 text-sm">{t("Подписка подходит к лимиту — после этого хода переключится на свободную.")}</p>
|
||||
)}
|
||||
</header>
|
||||
|
||||
<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>
|
||||
<dt className="text-muted-foreground">{t("Проект")}</dt>
|
||||
<dd className="m-0">
|
||||
<Key href={`/p/${s.projectKey}`}>{s.projectKey}</Key>
|
||||
</dd>
|
||||
<dt className="text-muted-foreground">Агент</dt>
|
||||
<dd className="m-0">{PROVIDER_NAMES[s.provider]} · поколение {s.generation}</dd>
|
||||
<dt className="text-muted-foreground">Подписка</dt>
|
||||
<dt className="text-muted-foreground">{t("Агент")}</dt>
|
||||
<dd className="m-0">{PROVIDER_NAMES[s.provider]} · {t("поколение {n}", { n: s.generation })}</dd>
|
||||
<dt className="text-muted-foreground">{t("Подписка")}</dt>
|
||||
<dd className="m-0">
|
||||
{s.subscriptionName ?? (s.subscriptionId ? `#${s.subscriptionId}` : "вход машины")}
|
||||
{s.subscriptionSwitches > 0 && <span className="text-muted-foreground"> · переключений {s.subscriptionSwitches}</span>}
|
||||
{s.subscriptionName ?? (s.subscriptionId ? `#${s.subscriptionId}` : t("вход машины"))}
|
||||
{s.subscriptionSwitches > 0 && <span className="text-muted-foreground"> · {t("переключений {n}", { n: s.subscriptionSwitches })}</span>}
|
||||
</dd>
|
||||
<dt className="text-muted-foreground">Где</dt>
|
||||
<dt className="text-muted-foreground">{t("Где")}</dt>
|
||||
<dd className="m-0">
|
||||
{s.host ? `хост ${s.host.name}` : "Mac Пеппы"}
|
||||
{s.container ? <span className="text-muted-foreground"> · контейнер {s.container}</span> : <span className="text-muted-foreground"> · без изоляции</span>}
|
||||
{s.host ? t("хост {name}", { name: s.host.name }) : t("Mac Пеппы")}
|
||||
{s.container ? <span className="text-muted-foreground"> · {t("контейнер {name}", { name: s.container })}</span> : <span className="text-muted-foreground"> · {t("без изоляции")}</span>}
|
||||
</dd>
|
||||
<dt className="text-muted-foreground">Запущен</dt>
|
||||
<dt className="text-muted-foreground">{t("Запущен")}</dt>
|
||||
<dd className="m-0">{ago(s.startedAt)}</dd>
|
||||
<dt className="text-muted-foreground">Активность</dt>
|
||||
<dt className="text-muted-foreground">{t("Активность")}</dt>
|
||||
<dd className="m-0">{ago(s.lastActivityAt)}</dd>
|
||||
</dl>
|
||||
|
||||
@ -162,22 +169,22 @@ export function RunnerDetails({ s, questions, events, steps, stories, back, clos
|
||||
{stories && <RunnerStories s={s} history={stories.history} queue={stories.queue} back={back} />}
|
||||
|
||||
{questions.length > 0 && (
|
||||
<PanelSection title="Ждёт ответа" count={questions.length}>
|
||||
<PanelSection title={t("Ждёт ответа")} count={questions.length}>
|
||||
{questions.map((q) => (
|
||||
<QuestionCard key={q.id} q={q} taskKey={s.taskKey} taskStatus={q.taskStatus} back={back} compact />
|
||||
))}
|
||||
</PanelSection>
|
||||
)}
|
||||
|
||||
<PanelSection title="Что делает агент">
|
||||
<PanelSection title={t("Что делает агент")}>
|
||||
<AgentSteps key={s.id} sessionId={s.id} initial={steps} live={!finished} hooks={s.provider === "claude"} />
|
||||
</PanelSection>
|
||||
|
||||
<PanelSection title="Терминал">
|
||||
<PanelSection title={t("Терминал")}>
|
||||
{finished ? (
|
||||
<div className="flex min-h-24 flex-col items-center justify-center gap-2 rounded-lg border border-dashed bg-background/60 p-4 text-center font-mono text-xs text-muted-foreground">
|
||||
<SquareTerminal className="size-6" />
|
||||
Сессия завершена — терминала больше нет.
|
||||
{t("Сессия завершена — терминала больше нет.")}
|
||||
</div>
|
||||
) : (
|
||||
<RunnerTerminal key={s.id} sessionId={s.id} live />
|
||||
@ -185,13 +192,13 @@ export function RunnerDetails({ s, questions, events, steps, stories, back, clos
|
||||
</PanelSection>
|
||||
|
||||
{events.some((e) => e.type === "subscription_switched") && (
|
||||
<PanelSection title="Переключения подписок">
|
||||
<PanelSection title={t("Переключения подписок")}>
|
||||
<ol className="m-0 flex list-none flex-col gap-1.5 p-0">
|
||||
{events
|
||||
.filter((e) => e.type === "subscription_switched")
|
||||
.map((e) => (
|
||||
<li key={e.id} className="text-sm [overflow-wrap:anywhere]">
|
||||
<span className="font-mono text-xs text-muted-foreground">{ago(e.createdAt)}</span> {switchText(e.payload)}
|
||||
<span className="font-mono text-xs text-muted-foreground">{ago(e.createdAt)}</span> {switchText(e.payload, t)}
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
@ -199,12 +206,12 @@ export function RunnerDetails({ s, questions, events, steps, stories, back, clos
|
||||
)}
|
||||
|
||||
{events.length > 0 && (
|
||||
<PanelSection title="События">
|
||||
<PanelSection title={t("События")}>
|
||||
<ol className="m-0 flex list-none flex-col gap-1.5 border-l p-0 pl-3">
|
||||
{events.map((e) => (
|
||||
<li key={e.id} className="text-xs [overflow-wrap:anywhere]">
|
||||
<span className="font-mono text-muted-foreground">{ago(e.createdAt)}</span> <span className="font-mono text-primary">{e.type}</span>{" "}
|
||||
{eventLine(e)}
|
||||
{eventLine(e, t)}
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
|
||||
@ -5,14 +5,16 @@ import type { Terminal } from "@xterm/xterm";
|
||||
import { Keyboard, Maximize2, Minimize2, Minus, Plus, RotateCw } from "lucide-react";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useT } from "@/components/I18n";
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
|
||||
type Status = "connecting" | "live" | "reconnecting" | "ended" | "error";
|
||||
const STATUS_TEXT: Record<Status, string> = {
|
||||
connecting: "подключение…",
|
||||
live: "в эфире",
|
||||
reconnecting: "переподключение…",
|
||||
ended: "tmux-сессии нет",
|
||||
error: "нет доступа к терминалу",
|
||||
connecting: m("подключение…"),
|
||||
live: m("в эфире"),
|
||||
reconnecting: m("переподключение…"),
|
||||
ended: m("tmux-сессии нет"),
|
||||
error: m("нет доступа к терминалу"),
|
||||
};
|
||||
const FONT_KEY = "peppa_term_font";
|
||||
const FONT_MIN = 7;
|
||||
@ -46,6 +48,7 @@ export function RunnerTerminal({ sessionId, live }: { sessionId: number; live: b
|
||||
const [font, setFont] = useState(12);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [attempt, setAttempt] = useState(0);
|
||||
const t = useT();
|
||||
const inputRef = useRef(false);
|
||||
const queue = useRef<{ keys: string; timer: ReturnType<typeof setTimeout> | null; chain: Promise<void> }>({ keys: "", timer: null, chain: Promise.resolve() });
|
||||
const url = `/api/runners/${sessionId}/terminal`;
|
||||
@ -57,10 +60,10 @@ export function RunnerTerminal({ sessionId, live }: { sessionId: number; live: b
|
||||
q.chain = q.chain.then(async () => {
|
||||
try {
|
||||
const r = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
|
||||
if (!r.ok) setError(((await r.json().catch(() => null)) as { error?: string } | null)?.error ?? `Ошибка ${r.status}`);
|
||||
if (!r.ok) setError(((await r.json().catch(() => null)) as { error?: string } | null)?.error ?? m("Ошибка {status}", { status: r.status }));
|
||||
else setError(null);
|
||||
} catch {
|
||||
setError("Нет связи с Пеппой");
|
||||
setError(m("Нет связи с Пеппой"));
|
||||
}
|
||||
});
|
||||
},
|
||||
@ -187,26 +190,26 @@ export function RunnerTerminal({ sessionId, live }: { sessionId: number; live: b
|
||||
<div className="flex flex-wrap items-center gap-1.5">
|
||||
<span className={cn("mr-auto flex items-center gap-1.5 font-mono text-[11px]", status === "live" ? "text-ok" : status === "error" ? "text-destructive" : "text-muted-foreground")}>
|
||||
<span className={cn("size-1.5 rounded-full bg-current", status === "live" && "animate-pulse")} />
|
||||
{STATUS_TEXT[status]}
|
||||
{t(STATUS_TEXT[status])}
|
||||
</span>
|
||||
{live && (
|
||||
<button type="button" className={cn(btn, input && "border-primary/60 bg-primary/10 text-foreground")} onClick={() => setInput((v) => !v)} aria-pressed={input} title="Печатать в терминал агента">
|
||||
<button type="button" className={cn(btn, input && "border-primary/60 bg-primary/10 text-foreground")} onClick={() => setInput((v) => !v)} aria-pressed={input} title={t("Печатать в терминал агента")}>
|
||||
<Keyboard className="size-3.5" />
|
||||
{input ? "Ввод включён" : "Ввод"}
|
||||
{input ? t("Ввод включён") : t("Ввод")}
|
||||
</button>
|
||||
)}
|
||||
<button type="button" className={btn} onClick={() => setFont((f) => Math.max(FONT_MIN, f - 1))} aria-label="Мельче" title="Мельче">
|
||||
<button type="button" className={btn} onClick={() => setFont((f) => Math.max(FONT_MIN, f - 1))} aria-label={t("Мельче")} title={t("Мельче")}>
|
||||
<Minus className="size-3.5" />
|
||||
</button>
|
||||
<button type="button" className={btn} onClick={() => setFont((f) => Math.min(FONT_MAX, f + 1))} aria-label="Крупнее" title="Крупнее">
|
||||
<button type="button" className={btn} onClick={() => setFont((f) => Math.min(FONT_MAX, f + 1))} aria-label={t("Крупнее")} title={t("Крупнее")}>
|
||||
<Plus className="size-3.5" />
|
||||
</button>
|
||||
{(status === "ended" || status === "error") && (
|
||||
<button type="button" className={btn} onClick={() => setAttempt((n) => n + 1)} title="Подключиться снова">
|
||||
<button type="button" className={btn} onClick={() => setAttempt((n) => n + 1)} title={t("Подключиться снова")}>
|
||||
<RotateCw className="size-3.5" />
|
||||
</button>
|
||||
)}
|
||||
<button type="button" className={btn} onClick={() => setFull((v) => !v)} aria-label={full ? "Свернуть" : "Во весь экран"} title={full ? "Свернуть" : "Во весь экран"}>
|
||||
<button type="button" className={btn} onClick={() => setFull((v) => !v)} aria-label={full ? t("Свернуть") : t("Во весь экран")} title={full ? t("Свернуть") : t("Во весь экран")}>
|
||||
{full ? <Minimize2 className="size-3.5" /> : <Maximize2 className="size-3.5" />}
|
||||
</button>
|
||||
</div>
|
||||
@ -222,8 +225,8 @@ export function RunnerTerminal({ sessionId, live }: { sessionId: number; live: b
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{error && <p className="m-0 text-xs text-destructive">{error}</p>}
|
||||
{!live && <p className="m-0 text-xs text-muted-foreground">Сессия завершена — только просмотр.</p>}
|
||||
{error && <p className="m-0 text-xs text-destructive">{t.text(error)}</p>}
|
||||
{!live && <p className="m-0 text-xs text-muted-foreground">{t("Сессия завершена — только просмотр.")}</p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@ -23,19 +23,22 @@ import { PanelSection } from "@/components/ActivityAside";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input, Label, NativeSelect, Textarea } from "@/components/ui/input";
|
||||
import { VoiceInput } from "@/components/VoiceInput";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import { m, type Translator } from "@peppa/shared/i18n";
|
||||
|
||||
/** Free runner form: project (or fixed), name, agent, prompt with voice input. */
|
||||
export function NewRunnerForm({ projects, projectId, back }: { projects?: Array<{ id: number; key: string; name: string }>; projectId?: number; back: string }) {
|
||||
export async function NewRunnerForm({ projects, projectId, back }: { projects?: Array<{ id: number; key: string; name: string }>; projectId?: number; back: string }) {
|
||||
const t = await getT();
|
||||
const promptId = `runner-prompt-${projectId ?? "any"}`;
|
||||
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">{t("Агент в tmux без стори: разобраться, попробовать, спросить. Пинги после ходов не приходят — раннером управляешь ты в терминале. Получилась работа — «Оформить стори».")}</p>
|
||||
{!projectId && (
|
||||
<Label>
|
||||
Проект
|
||||
{t("Проект")}
|
||||
<NativeSelect name="projectId" required defaultValue="" className="h-8">
|
||||
<option value="" disabled>Выбери проект</option>
|
||||
<option value="" disabled>{t("Выбери проект")}</option>
|
||||
{projects?.map((p) => (
|
||||
<option key={p.id} value={p.id}>
|
||||
{p.key} — {p.name}
|
||||
@ -45,24 +48,24 @@ export function NewRunnerForm({ projects, projectId, back }: { projects?: Array<
|
||||
</Label>
|
||||
)}
|
||||
<Label>
|
||||
Имя
|
||||
<Input name="name" placeholder="Новый терминал" maxLength={80} className="h-8" />
|
||||
{t("Имя")}
|
||||
<Input name="name" placeholder={t("Новый терминал")} maxLength={80} className="h-8" />
|
||||
</Label>
|
||||
<Label>
|
||||
Агент
|
||||
{t("Агент")}
|
||||
<NativeSelect name="provider" defaultValue="" className="h-8">
|
||||
<option value="">По пулу проекта (иначе Claude Code)</option>
|
||||
<option value="">{t("По пулу проекта (иначе Claude Code)")}</option>
|
||||
<option value="claude">Claude Code</option>
|
||||
<option value="codex">Codex</option>
|
||||
<option value="opencode">OpenCode</option>
|
||||
</NativeSelect>
|
||||
</Label>
|
||||
<Label htmlFor={promptId}>Промпт (необязательно)</Label>
|
||||
<Textarea id={promptId} name="prompt" rows={4} placeholder="Что сделать агенту" />
|
||||
<Label htmlFor={promptId}>{t("Промпт (необязательно)")}</Label>
|
||||
<Textarea id={promptId} name="prompt" rows={4} placeholder={t("Что сделать агенту")} />
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button>
|
||||
<SquareTerminal />
|
||||
Запустить
|
||||
{t("Запустить")}
|
||||
</Button>
|
||||
<VoiceInput target={promptId} />
|
||||
</div>
|
||||
@ -70,60 +73,61 @@ export function NewRunnerForm({ projects, projectId, back }: { projects?: Array<
|
||||
);
|
||||
}
|
||||
|
||||
const inherit = (label: string) => `Как выше: ${label}`;
|
||||
const inherit = (t: Translator, label: string) => t("Как выше: {label}", { label: t(label) });
|
||||
|
||||
/** «⋯ Настройки проекта → Раннеры»: overrides of the project; empty = system. */
|
||||
export function RunnerSettingsPanel({ projectId, own, inherited, back, hosts = [] }: { projectId: number; own: RunnerSettingsPatch; inherited: RunnerSettings; back: string; hosts?: Pick<RunnerHost, "id" | "name" | "status">[] }) {
|
||||
const hostNames = (ids: number[]) => (ids.length ? ids.map((id) => hosts.find((h) => h.id === id)?.name ?? `#${id}`).join(", ") : "Mac Пеппы");
|
||||
export async function RunnerSettingsPanel({ projectId, own, inherited, back, hosts = [] }: { projectId: number; own: RunnerSettingsPatch; inherited: RunnerSettings; back: string; hosts?: Pick<RunnerHost, "id" | "name" | "status">[] }) {
|
||||
const t = await getT();
|
||||
const hostNames = (ids: number[]) => (ids.length ? ids.map((id) => hosts.find((h) => h.id === id)?.name ?? `#${id}`).join(", ") : m("Mac Пеппы"));
|
||||
return (
|
||||
<form action={setRunnerSettingsAction} className="flex flex-col gap-3">
|
||||
<Hidden fields={{ projectId, back }} />
|
||||
<Label>
|
||||
Раннер и стори
|
||||
{t("Раннер и стори")}
|
||||
<NativeSelect name="mode" defaultValue={own.mode ?? ""} className="h-8">
|
||||
<option value="">{inherit(RUNNER_MODE_RU[inherited.mode])}</option>
|
||||
<option value="">{inherit(t, RUNNER_MODE_RU[inherited.mode])}</option>
|
||||
{RUNNER_MODES.map((m) => (
|
||||
<option key={m} value={m}>{RUNNER_MODE_RU[m]}</option>
|
||||
<option key={m} value={m}>{t(RUNNER_MODE_RU[m])}</option>
|
||||
))}
|
||||
</NativeSelect>
|
||||
</Label>
|
||||
<Label>
|
||||
Переход к следующей стори (для очереди)
|
||||
{t("Переход к следующей стори (для очереди)")}
|
||||
<NativeSelect name="context" defaultValue={own.context ?? ""} className="h-8">
|
||||
<option value="">{inherit(RUNNER_CONTEXT_RU[inherited.context])}</option>
|
||||
<option value="">{inherit(t, RUNNER_CONTEXT_RU[inherited.context])}</option>
|
||||
{RUNNER_CONTEXTS.map((m) => (
|
||||
<option key={m} value={m}>{RUNNER_CONTEXT_RU[m]}</option>
|
||||
<option key={m} value={m}>{t(RUNNER_CONTEXT_RU[m])}</option>
|
||||
))}
|
||||
</NativeSelect>
|
||||
</Label>
|
||||
<Label>
|
||||
Рабочая копия
|
||||
{t("Рабочая копия")}
|
||||
<NativeSelect name="workspace" defaultValue={own.workspace ?? ""} className="h-8">
|
||||
<option value="">{inherit(RUNNER_WORKSPACE_RU[inherited.workspace])}</option>
|
||||
<option value="">{inherit(t, RUNNER_WORKSPACE_RU[inherited.workspace])}</option>
|
||||
{RUNNER_WORKSPACES.map((m) => (
|
||||
<option key={m} value={m}>{RUNNER_WORKSPACE_RU[m]}</option>
|
||||
<option key={m} value={m}>{t(RUNNER_WORKSPACE_RU[m])}</option>
|
||||
))}
|
||||
</NativeSelect>
|
||||
</Label>
|
||||
<Label>
|
||||
Лимит раннеров проекта (пусто — {inherited.maxRunners ? `как выше: ${inherited.maxRunners}` : "без лимита"}, 0 — без лимита)
|
||||
{t("Лимит раннеров проекта (пусто — {inherited}, 0 — без лимита)", { inherited: inherited.maxRunners ? t("как выше: {n}", { n: inherited.maxRunners }) : t("без лимита") })}
|
||||
<Input name="maxRunners" type="number" min={0} max={50} defaultValue={own.maxRunners === undefined ? "" : (own.maxRunners ?? 0)} className="h-8" />
|
||||
</Label>
|
||||
<Label>
|
||||
Изоляция агента
|
||||
{t("Изоляция агента")}
|
||||
<NativeSelect name="isolation" defaultValue={own.isolation ?? ""} className="h-8">
|
||||
<option value="">{inherit(RUNNER_ISOLATION_RU[inherited.isolation])}</option>
|
||||
<option value="">{inherit(t, RUNNER_ISOLATION_RU[inherited.isolation])}</option>
|
||||
{RUNNER_ISOLATIONS.map((m) => (
|
||||
<option key={m} value={m}>{RUNNER_ISOLATION_RU[m]}</option>
|
||||
<option key={m} value={m}>{t(RUNNER_ISOLATION_RU[m])}</option>
|
||||
))}
|
||||
</NativeSelect>
|
||||
</Label>
|
||||
<Label>
|
||||
Где запускать раннеры
|
||||
{t("Где запускать раннеры")}
|
||||
<NativeSelect name="hostsMode" defaultValue={own.hosts === undefined ? "" : own.hosts.length ? "list" : "local"} className="h-8">
|
||||
<option value="">{inherit(hostNames(inherited.hosts))}</option>
|
||||
<option value="local">Mac Пеппы</option>
|
||||
<option value="list" disabled={!hosts.length}>Хосты, отмеченные ниже (наименее занятый онлайн)</option>
|
||||
<option value="">{inherit(t, hostNames(inherited.hosts))}</option>
|
||||
<option value="local">{t("Mac Пеппы")}</option>
|
||||
<option value="list" disabled={!hosts.length}>{t("Хосты, отмеченные ниже (наименее занятый онлайн)")}</option>
|
||||
</NativeSelect>
|
||||
</Label>
|
||||
{hosts.length > 0 && (
|
||||
@ -131,87 +135,90 @@ export function RunnerSettingsPanel({ projectId, own, inherited, back, hosts = [
|
||||
{hosts.map((h) => (
|
||||
<label key={h.id} className="flex items-center gap-1.5">
|
||||
<input type="checkbox" name="hosts" value={h.id} defaultChecked={(own.hosts ?? []).includes(h.id)} /> {h.name}
|
||||
<span className="text-xs text-muted-foreground">({HOST_STATUS_RU[h.status]})</span>
|
||||
<span className="text-xs text-muted-foreground">({t(HOST_STATUS_RU[h.status])})</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<p className="m-0 text-xs text-muted-foreground">
|
||||
Контейнер: агент работает в docker-образе раннера и видит только свою рабочую копию; токены Пеппы и чужие проекты ему недоступны, нужна подписка в пуле проекта. На хосте агент всегда в контейнере.
|
||||
{t("Контейнер: агент работает в docker-образе раннера и видит только свою рабочую копию; токены Пеппы и чужие проекты ему недоступны, нужна подписка в пуле проекта. На хосте агент всегда в контейнере.")}
|
||||
</p>
|
||||
<p className="m-0 text-xs text-muted-foreground">
|
||||
Очередь: стори достаётся свободному раннеру, при лимите ждёт в очереди; «Принять» не останавливает раннер, а даёт ему следующую стори. Свой worktree: у каждого раннера своя копия и ветка <code>task/…</code>, параллельные стори не мешают друг другу.
|
||||
{t("Очередь: стори достаётся свободному раннеру, при лимите ждёт в очереди; «Принять» не останавливает раннер, а даёт ему следующую стори.")}{" "}
|
||||
{t("Свой worktree: у каждого раннера своя копия и ветка")} <code>task/…</code>{t(", параллельные стори не мешают друг другу.")}
|
||||
</p>
|
||||
<Button size="sm" className="self-start">Сохранить</Button>
|
||||
<Button size="sm" className="self-start">{t("Сохранить")}</Button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
/** Story page: mode/context for this story only. */
|
||||
export function TaskRunnerSettings({ taskKey, own, inherited, back }: { taskKey: string; own: { mode?: string; context?: string }; inherited: RunnerSettings; back: string }) {
|
||||
export async function TaskRunnerSettings({ taskKey, own, inherited, back }: { taskKey: string; own: { mode?: string; context?: string }; inherited: RunnerSettings; back: string }) {
|
||||
const t = await getT();
|
||||
return (
|
||||
<form action={setRunnerSettingsAction} className="flex flex-wrap items-end gap-2">
|
||||
<Hidden fields={{ taskKey, back }} />
|
||||
<Label className="flex-[1_1_12rem]">
|
||||
Раннер этой стори
|
||||
{t("Раннер этой стори")}
|
||||
<NativeSelect name="mode" defaultValue={own.mode ?? ""} className="h-8">
|
||||
<option value="">{inherit(RUNNER_MODE_RU[inherited.mode])}</option>
|
||||
<option value="">{inherit(t, RUNNER_MODE_RU[inherited.mode])}</option>
|
||||
{RUNNER_MODES.map((m) => (
|
||||
<option key={m} value={m}>{RUNNER_MODE_RU[m]}</option>
|
||||
<option key={m} value={m}>{t(RUNNER_MODE_RU[m])}</option>
|
||||
))}
|
||||
</NativeSelect>
|
||||
</Label>
|
||||
<Label className="flex-[1_1_12rem]">
|
||||
Контекст
|
||||
{t("Контекст")}
|
||||
<NativeSelect name="context" defaultValue={own.context ?? ""} className="h-8">
|
||||
<option value="">{inherit(RUNNER_CONTEXT_RU[inherited.context])}</option>
|
||||
<option value="">{inherit(t, RUNNER_CONTEXT_RU[inherited.context])}</option>
|
||||
{RUNNER_CONTEXTS.map((m) => (
|
||||
<option key={m} value={m}>{RUNNER_CONTEXT_RU[m]}</option>
|
||||
<option key={m} value={m}>{t(RUNNER_CONTEXT_RU[m])}</option>
|
||||
))}
|
||||
</NativeSelect>
|
||||
</Label>
|
||||
<Button size="sm" variant="outline">Сохранить</Button>
|
||||
<Button size="sm" variant="outline">{t("Сохранить")}</Button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
/** Runner details: name, stories (history and queue), «Оформить стори» for a free runner. */
|
||||
export function RunnerStories({ s, history, queue, back }: { s: SessionView; history: RunnerTaskView[]; queue: RunnerTaskView[]; back: string }) {
|
||||
export async function RunnerStories({ s, history, queue, back }: { s: SessionView; history: RunnerTaskView[]; queue: RunnerTaskView[]; back: string }) {
|
||||
const t = await getT();
|
||||
const alive = !["done", "failed"].includes(s.status);
|
||||
return (
|
||||
<>
|
||||
<form action={renameRunnerAction} className="flex gap-2">
|
||||
<Hidden fields={{ sessionId: s.id, back }} />
|
||||
<Input name="name" defaultValue={s.name ?? ""} placeholder="Имя раннера" aria-label="Имя раннера" maxLength={80} className="h-8" />
|
||||
<Button size="sm" variant="outline">Переименовать</Button>
|
||||
<Input name="name" defaultValue={s.name ?? ""} placeholder={t("Имя раннера")} aria-label={t("Имя раннера")} maxLength={80} className="h-8" />
|
||||
<Button size="sm" variant="outline">{t("Переименовать")}</Button>
|
||||
</form>
|
||||
{s.workspacePath && <p className="m-0 font-mono text-xs break-all text-muted-foreground">worktree: {s.workspacePath}</p>}
|
||||
{!s.taskId && (
|
||||
<PanelSection title="Оформить стори">
|
||||
<PanelSection title={t("Оформить стори")}>
|
||||
<form action={promoteRunnerAction} className="flex flex-col gap-2">
|
||||
<Hidden fields={{ sessionId: s.id, back }} />
|
||||
<Input name="title" required minLength={3} placeholder="Название стори" aria-label="Название стори" className="h-8" />
|
||||
<Textarea name="description" rows={2} placeholder="Описание (необязательно)" aria-label="Описание стори" />
|
||||
<Input name="title" required minLength={3} placeholder={t("Название стори")} aria-label={t("Название стори")} className="h-8" />
|
||||
<Textarea name="description" rows={2} placeholder={t("Описание (необязательно)")} aria-label={t("Описание стори")} />
|
||||
<Button size="sm" className="self-start">
|
||||
<Plus />
|
||||
Оформить стори
|
||||
{t("Оформить стори")}
|
||||
</Button>
|
||||
</form>
|
||||
</PanelSection>
|
||||
)}
|
||||
{(history.length > 0 || queue.length > 0 || (alive && s.taskId)) && (
|
||||
<PanelSection title="Стори раннера" count={history.length + queue.length}>
|
||||
<PanelSection title={t("Стори раннера")} count={history.length + queue.length}>
|
||||
<ol className="m-0 flex list-none flex-col gap-1.5 p-0 text-sm">
|
||||
{queue.map((r) => (
|
||||
<li key={r.id} className="flex items-center gap-2">
|
||||
<span className="font-mono text-xs text-muted-foreground">в очереди{r.front ? " (первой)" : ""}</span>
|
||||
<span className="font-mono text-xs text-muted-foreground">{r.front ? t("в очереди (первой)") : t("в очереди")}</span>
|
||||
<Key href={`/t/${r.taskKey}`}>{r.taskKey}</Key>
|
||||
<span className="truncate">{r.taskTitle}</span>
|
||||
</li>
|
||||
))}
|
||||
{history.map((r) => (
|
||||
<li key={r.id} className="flex items-center gap-2">
|
||||
<span className="font-mono text-xs text-muted-foreground">{r.status === "active" ? "ведёт" : "вёл"}</span>
|
||||
<span className="font-mono text-xs text-muted-foreground">{r.status === "active" ? t("ведёт") : t("вёл")}</span>
|
||||
<Key href={`/t/${r.taskKey}`}>{r.taskKey}</Key>
|
||||
<span className="min-w-0 truncate">{r.taskTitle}</span>
|
||||
<span className="ml-auto">
|
||||
@ -223,8 +230,8 @@ export function RunnerStories({ s, history, queue, back }: { s: SessionView; his
|
||||
{alive && s.taskId && (
|
||||
<form action={queueOnRunnerAction} className="flex gap-2">
|
||||
<Hidden fields={{ sessionId: s.id, back }} />
|
||||
<Input name="taskKey" required placeholder={`${s.projectKey}-N`} aria-label="Стори в очередь" className="h-8" />
|
||||
<Button size="sm" variant="outline">В очередь</Button>
|
||||
<Input name="taskKey" required placeholder={`${s.projectKey}-N`} aria-label={t("Стори в очередь")} className="h-8" />
|
||||
<Button size="sm" variant="outline">{t("В очередь")}</Button>
|
||||
</form>
|
||||
)}
|
||||
</PanelSection>
|
||||
|
||||
@ -3,12 +3,14 @@
|
||||
import { useRef, type ReactNode } from "react";
|
||||
import { Ellipsis, X } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useT } from "@/components/I18n";
|
||||
|
||||
/**
|
||||
* Button that opens a side dialog (native <dialog>) with content rendered on the server.
|
||||
* Default trigger is "⋯" (page settings); pass `trigger` for a labelled button such as "+ Стори".
|
||||
*/
|
||||
export function SettingsDialog({ title, trigger, children }: { title: string; trigger?: ReactNode; children: ReactNode }) {
|
||||
const t = useT();
|
||||
const ref = useRef<HTMLDialogElement>(null);
|
||||
const open = () => ref.current?.showModal();
|
||||
return (
|
||||
@ -31,7 +33,7 @@ export function SettingsDialog({ title, trigger, children }: { title: string; tr
|
||||
<div className="flex flex-col gap-4 px-4 py-5">
|
||||
<div className="flex items-center gap-2">
|
||||
<h2 className="m-0 text-[15px] font-semibold">{title}</h2>
|
||||
<Button variant="ghost" size="icon" className="ml-auto" aria-label="Закрыть" onClick={() => ref.current?.close()}>
|
||||
<Button variant="ghost" size="icon" className="ml-auto" aria-label={t("Закрыть")} onClick={() => ref.current?.close()}>
|
||||
<X />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@ -48,7 +48,6 @@ export function Sidebar({ login, avatarUrl, counts, superadmin = false }: { logi
|
||||
<header className="sticky top-0 z-30 flex h-14 items-center gap-2 border-b bg-sidebar px-3 md:h-dvh md:flex-col md:items-stretch md:gap-1 md:border-r md:border-b-0 md:px-3 md:py-4">
|
||||
<Link href="/" className="flex shrink-0 items-center gap-2 rounded-md px-1 text-foreground hover:no-underline md:mb-4 md:px-2">
|
||||
<Brand />
|
||||
<span className="hidden font-mono text-[11px] text-muted-foreground md:inline">{t("фабрика")}</span>
|
||||
</Link>
|
||||
{/* PEP-52: the palette listens for clicks on [data-open-palette]. */}
|
||||
<button
|
||||
|
||||
@ -4,6 +4,7 @@ import { cancelOwnLoginAction, connectOwnSubscriptionAction, finishOwnClaudeLogi
|
||||
import { Hidden } from "@/components/cards";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { getT } from "@/lib/i18n";
|
||||
|
||||
const step = "flex gap-2.5";
|
||||
const num = "grid size-5.5 shrink-0 place-items-center rounded-full bg-primary/15 text-xs font-semibold text-primary";
|
||||
@ -12,20 +13,21 @@ const num = "grid size-5.5 shrink-0 place-items-center rounded-full bg-primary/1
|
||||
* PEP-82: connecting the owner's own subscription without a terminal, in plain steps, right on
|
||||
* the project page — «Подключить Claude» / «Подключить ChatGPT», then the link and the code.
|
||||
*/
|
||||
export function SubscriptionSetup({ projectId, back, logins }: { projectId: number; back: string; logins: OwnLogin[] }) {
|
||||
export async function SubscriptionSetup({ projectId, back, logins }: { projectId: number; back: string; logins: OwnLogin[] }) {
|
||||
const t = await getT();
|
||||
if (logins.length) {
|
||||
return (
|
||||
<div className="mb-4 flex flex-col gap-4">
|
||||
{logins.map((l) => (
|
||||
<section key={l.subscriptionId} className="flex flex-col gap-3 rounded-lg border border-primary/40 bg-card px-4 py-4 text-sm" data-own-login={l.subscriptionId} aria-label={`Подключение ${l.provider === "claude" ? "Claude" : "ChatGPT"}`}>
|
||||
<h2 className="m-0 text-base font-semibold">Подключаем {l.provider === "claude" ? "Claude" : "ChatGPT"} — осталось {l.provider === "claude" ? "три шага" : "два шага"}</h2>
|
||||
<section key={l.subscriptionId} className="flex flex-col gap-3 rounded-lg border border-primary/40 bg-card px-4 py-4 text-sm" data-own-login={l.subscriptionId} aria-label={t("Подключение {provider}", { provider: l.provider === "claude" ? "Claude" : "ChatGPT" })}>
|
||||
<h2 className="m-0 text-base font-semibold">{l.provider === "claude" ? t("Подключаем Claude — осталось три шага") : t("Подключаем ChatGPT — осталось два шага")}</h2>
|
||||
<div className={step}>
|
||||
<span className={num}>1</span>
|
||||
<div className="flex flex-col items-start gap-1.5">
|
||||
<span>Откройте страницу входа и войдите в свой аккаунт {l.provider === "claude" ? "Claude" : "ChatGPT"}{l.provider === "claude" ? ", затем нажмите «Authorize»" : ""}.</span>
|
||||
<span>{l.provider === "claude" ? t("Откройте страницу входа и войдите в свой аккаунт Claude, затем нажмите «Authorize».") : t("Откройте страницу входа и войдите в свой аккаунт ChatGPT.")}</span>
|
||||
<Button asChild size="sm" variant="default">
|
||||
<a href={l.url} target="_blank" rel="noreferrer">
|
||||
Открыть страницу входа <ExternalLink />
|
||||
{t("Открыть страницу входа")} <ExternalLink />
|
||||
</a>
|
||||
</Button>
|
||||
</div>
|
||||
@ -34,14 +36,14 @@ export function SubscriptionSetup({ projectId, back, logins }: { projectId: numb
|
||||
<>
|
||||
<div className={step}>
|
||||
<span className={num}>2</span>
|
||||
<span>Claude покажет длинный код — нажмите «Copy code».</span>
|
||||
<span>{t("Claude покажет длинный код — нажмите «Copy code».")}</span>
|
||||
</div>
|
||||
<div className={step}>
|
||||
<span className={num}>3</span>
|
||||
<form action={finishOwnClaudeLoginAction} className="flex min-w-0 flex-1 flex-wrap items-center gap-2">
|
||||
<Hidden fields={{ projectId, subscriptionId: l.subscriptionId, back }} />
|
||||
<Input name="code" required autoComplete="off" placeholder="Вставьте код сюда" aria-label="Код от Claude" className="h-9 min-w-48 flex-1 font-mono" />
|
||||
<Button variant="default">Готово</Button>
|
||||
<Input name="code" required autoComplete="off" placeholder={t("Вставьте код сюда")} aria-label={t("Код от Claude")} className="h-9 min-w-48 flex-1 font-mono" />
|
||||
<Button variant="default">{t("Готово")}</Button>
|
||||
</form>
|
||||
</div>
|
||||
</>
|
||||
@ -50,17 +52,17 @@ export function SubscriptionSetup({ projectId, back, logins }: { projectId: numb
|
||||
<span className={num}>2</span>
|
||||
<div className="flex flex-col items-start gap-1.5">
|
||||
<span>
|
||||
На той странице введите код <span className="rounded bg-muted px-2 py-0.5 font-mono text-base tracking-wider">{l.code}</span> и подтвердите вход.
|
||||
{t("На той странице введите код")} <span className="rounded bg-muted px-2 py-0.5 font-mono text-base tracking-wider">{l.code}</span> {t("и подтвердите вход.")}
|
||||
</span>
|
||||
<Button asChild size="sm" variant="default">
|
||||
<a href={back}>Я вошёл — проверить</a>
|
||||
<a href={back}>{t("Я вошёл — проверить")}</a>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<form action={cancelOwnLoginAction}>
|
||||
<Hidden fields={{ projectId, subscriptionId: l.subscriptionId, back }} />
|
||||
<Button size="xs" variant="ghost" className="text-muted-foreground">Отменить и начать заново</Button>
|
||||
<Button size="xs" variant="ghost" className="text-muted-foreground">{t("Отменить и начать заново")}</Button>
|
||||
</form>
|
||||
</section>
|
||||
))}
|
||||
@ -68,23 +70,22 @@ export function SubscriptionSetup({ projectId, back, logins }: { projectId: numb
|
||||
);
|
||||
}
|
||||
return (
|
||||
<section className="mb-4 flex flex-col gap-3 rounded-lg border border-warn/50 bg-warn/10 px-4 py-4 text-sm" aria-label="Подключение подписки">
|
||||
<h2 className="m-0 text-base font-semibold">Подключите подписку — и агенты начнут работать</h2>
|
||||
<section className="mb-4 flex flex-col gap-3 rounded-lg border border-warn/50 bg-warn/10 px-4 py-4 text-sm" aria-label={t("Подключение подписки")}>
|
||||
<h2 className="m-0 text-base font-semibold">{t("Подключите подписку — и агенты начнут работать")}</h2>
|
||||
<p className="m-0">
|
||||
Агенты пишут код на вашей подписке Claude или ChatGPT — подойдёт обычная платная (Claude Pro или Max, ChatGPT Plus или Pro). Это одна минута: вы входите в свой аккаунт, как на любом сайте. Пароль
|
||||
Пеппа не видит.
|
||||
{t("Агенты пишут код на вашей подписке Claude или ChatGPT — подойдёт обычная платная (Claude Pro или Max, ChatGPT Plus или Pro). Это одна минута: вы входите в свой аккаунт, как на любом сайте. Пароль Пеппа не видит.")}
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<form action={connectOwnSubscriptionAction}>
|
||||
<Hidden fields={{ projectId, kind: "claude_login", back }} />
|
||||
<Button variant="default" size="lg">Подключить Claude</Button>
|
||||
<Button variant="default" size="lg">{t("Подключить Claude")}</Button>
|
||||
</form>
|
||||
<form action={connectOwnSubscriptionAction}>
|
||||
<Hidden fields={{ projectId, kind: "codex_login", back }} />
|
||||
<Button variant="outline" size="lg">Подключить ChatGPT</Button>
|
||||
<Button variant="outline" size="lg">{t("Подключить ChatGPT")}</Button>
|
||||
</form>
|
||||
</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">{t("Нет подписки? Оформите её на claude.ai или chatgpt.com и вернитесь сюда. Другие способы (готовый токен, ключ API) — в «⋯ Настройки проекта → Подписки».")}</p>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
@ -2,9 +2,11 @@
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { Input, Label } from "@/components/ui/input";
|
||||
import { useT } from "@/components/I18n";
|
||||
|
||||
/** IANA timezone for quiet hours and the digest, with «как в браузере» (PEP-35). */
|
||||
export function TimezoneField({ value }: { value: string }) {
|
||||
const t = useT();
|
||||
const [tz, setTz] = useState(value);
|
||||
const [browser, setBrowser] = useState<string | null>(null);
|
||||
const [zones, setZones] = useState<string[]>([]);
|
||||
@ -16,7 +18,7 @@ export function TimezoneField({ value }: { value: string }) {
|
||||
return (
|
||||
<div className="flex flex-wrap items-end gap-2">
|
||||
<Label className="w-56">
|
||||
Таймзона
|
||||
{t("Таймзона")}
|
||||
<Input name="timezone" value={tz} onChange={(e) => setTz(e.target.value)} list="peppa-timezones" />
|
||||
</Label>
|
||||
<datalist id="peppa-timezones">
|
||||
@ -26,7 +28,7 @@ export function TimezoneField({ value }: { value: string }) {
|
||||
</datalist>
|
||||
{browser && browser !== tz && (
|
||||
<button type="button" className="mb-2 text-sm text-primary" onClick={() => setTz(browser)}>
|
||||
как в браузере ({browser})
|
||||
{t("как в браузере ({browser})", { browser })}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@ -5,6 +5,8 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { Mic, MicOff } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useT } from "@/components/I18n";
|
||||
import { intlLocale } from "@peppa/shared/i18n";
|
||||
|
||||
type Recognition = {
|
||||
lang: string;
|
||||
@ -21,6 +23,7 @@ export function VoiceInput({ target }: { target: string }) {
|
||||
const [supported, setSupported] = useState(false);
|
||||
const [on, setOn] = useState(false);
|
||||
const rec = useRef<Recognition | null>(null);
|
||||
const t = useT();
|
||||
useEffect(() => {
|
||||
const w = window as unknown as { SpeechRecognition?: new () => Recognition; webkitSpeechRecognition?: new () => Recognition };
|
||||
setSupported(!!(w.SpeechRecognition ?? w.webkitSpeechRecognition));
|
||||
@ -36,7 +39,7 @@ export function VoiceInput({ target }: { target: string }) {
|
||||
const w = window as unknown as { SpeechRecognition?: new () => Recognition; webkitSpeechRecognition?: new () => Recognition };
|
||||
const Ctor = (w.SpeechRecognition ?? w.webkitSpeechRecognition)!;
|
||||
const r = new Ctor();
|
||||
r.lang = "ru-RU";
|
||||
r.lang = intlLocale(t.locale);
|
||||
r.interimResults = false;
|
||||
r.continuous = true;
|
||||
r.onresult = (e) => {
|
||||
@ -54,9 +57,9 @@ export function VoiceInput({ target }: { target: string }) {
|
||||
setOn(true);
|
||||
};
|
||||
return (
|
||||
<Button type="button" size="sm" variant={on ? "default" : "outline"} onClick={toggle} aria-pressed={on} title={on ? "Остановить диктовку" : "Надиктовать промпт"}>
|
||||
<Button type="button" size="sm" variant={on ? "default" : "outline"} onClick={toggle} aria-pressed={on} title={on ? t("Остановить диктовку") : t("Надиктовать промпт")}>
|
||||
{on ? <MicOff /> : <Mic />}
|
||||
{on ? "Стоп" : "Голосом"}
|
||||
{on ? t("Стоп") : t("Голосом")}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
@ -2,6 +2,7 @@ import type { ReactNode } from "react";
|
||||
import { ActivityAside } from "@/components/ActivityAside";
|
||||
import { Footer } from "@/components/Footer";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { getT } from "@/lib/i18n";
|
||||
|
||||
/**
|
||||
* Centre + right panel of the console (PEP-38). The page decides what the right panel shows;
|
||||
@ -9,7 +10,8 @@ import { cn } from "@/lib/utils";
|
||||
* `wide` lets the centre grow past the reading width (the board page, with its panel moved into a dialog).
|
||||
* Below xl the panel goes under the page content (`asideWideOnly`: shown on xl only), the footer is always last.
|
||||
*/
|
||||
export function Workspace({ children, aside, asideWideOnly = false, wide = false }: { children: ReactNode; aside?: ReactNode; asideWideOnly?: boolean; wide?: boolean }) {
|
||||
export async function Workspace({ children, aside, asideWideOnly = false, wide = false }: { children: ReactNode; aside?: ReactNode; asideWideOnly?: boolean; wide?: boolean }) {
|
||||
const t = await getT();
|
||||
const panel = aside === undefined ? <ActivityAside /> : aside;
|
||||
return (
|
||||
<div className={cn("grid flex-1", panel && "xl:grid-cols-[minmax(0,1fr)_360px] xl:grid-rows-[1fr_auto]")}>
|
||||
@ -17,7 +19,7 @@ export function Workspace({ children, aside, asideWideOnly = false, wide = false
|
||||
<div className={cn("mx-auto w-full", wide ? "max-w-[1600px]" : "max-w-5xl")}>{children}</div>
|
||||
</main>
|
||||
{panel && (
|
||||
<aside aria-label="Панель" className={cn(asideWideOnly && "max-xl:hidden", "min-w-0 border-t bg-sidebar/60 px-4 py-5 xl:sticky xl:top-0 xl:col-start-2 xl:row-span-2 xl:row-start-1 xl:h-dvh xl:overflow-y-auto xl:border-t-0 xl:border-l")}>
|
||||
<aside aria-label={t("Панель")} className={cn(asideWideOnly && "max-xl:hidden", "min-w-0 border-t bg-sidebar/60 px-4 py-5 xl:sticky xl:top-0 xl:col-start-2 xl:row-span-2 xl:row-start-1 xl:h-dvh xl:overflow-y-auto xl:border-t-0 xl:border-l")}>
|
||||
{panel}
|
||||
</aside>
|
||||
)}
|
||||
|
||||
@ -11,12 +11,14 @@ import { AgentSteps } from "@/components/AgentSteps";
|
||||
import { RunnerTerminal } from "@/components/RunnerTerminal";
|
||||
import { SessionUsageLine } from "@/components/Accounting";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
|
||||
const KIND = {
|
||||
approval: { label: "Одобрение proposal", icon: FileCheck, border: "border-l-primary" },
|
||||
question: { label: "Вопрос", icon: CircleHelp, border: "border-l-info" },
|
||||
permission: { label: "Разрешение", icon: ShieldQuestion, border: "border-l-warn" },
|
||||
attention: { label: "Сессия ждёт тебя", icon: BellRing, border: "border-l-ok" },
|
||||
approval: { label: m("Одобрение proposal"), icon: FileCheck, border: "border-l-primary" },
|
||||
question: { label: m("Вопрос"), icon: CircleHelp, border: "border-l-info" },
|
||||
permission: { label: m("Разрешение"), icon: ShieldQuestion, border: "border-l-warn" },
|
||||
attention: { label: m("Сессия ждёт тебя"), icon: BellRing, border: "border-l-ok" },
|
||||
} as const;
|
||||
|
||||
/** Hidden inputs of a server-action form. */
|
||||
@ -28,7 +30,8 @@ export function Hidden({ fields }: { fields: Record<string, string | number | nu
|
||||
);
|
||||
}
|
||||
|
||||
export function QuestionCard({ q, taskKey, taskStatus, back, compact = false }: { q: Question; taskKey?: string | null; taskStatus?: string | null; back: string; compact?: boolean }) {
|
||||
export async function QuestionCard({ q, taskKey, taskStatus, back, compact = false }: { q: Question; taskKey?: string | null; taskStatus?: string | null; back: string; compact?: boolean }) {
|
||||
const t = await getT();
|
||||
const review = q.kind === "attention" && taskStatus === "review";
|
||||
const answered = !!q.answeredAt;
|
||||
const k = KIND[q.kind];
|
||||
@ -37,40 +40,42 @@ export function QuestionCard({ q, taskKey, taskStatus, back, compact = false }:
|
||||
<article id={`q-${q.id}`} className={cn("flex flex-col gap-2.5 rounded-lg border border-l-2 bg-card p-4", answered ? "border-l-border opacity-70" : k.border)}>
|
||||
<header className="flex flex-wrap items-center gap-x-2 gap-y-1 text-sm">
|
||||
<Icon className="size-4 text-muted-foreground" />
|
||||
<span className="font-medium">{review ? "Готово к ревью" : k.label}</span>
|
||||
<span className="font-medium">{review ? t("Готово к ревью") : t(k.label)}</span>
|
||||
{taskKey && <Key href={`/t/${taskKey}`}>{taskKey}</Key>}
|
||||
<span className="ml-auto font-mono text-xs text-muted-foreground">
|
||||
#{q.id} · {ago(q.createdAt)}
|
||||
#{q.id} · {ago(q.createdAt, t)}
|
||||
</span>
|
||||
</header>
|
||||
<p className={cn("m-0 overflow-auto text-sm whitespace-pre-wrap", compact ? "max-h-40" : "max-h-72")}>{q.text}</p>
|
||||
<p className={cn("m-0 overflow-auto text-sm whitespace-pre-wrap", compact ? "max-h-40" : "max-h-72")}>{t.text(q.text)}</p>
|
||||
{answered ? (
|
||||
<p className="m-0 flex items-center gap-1.5 text-sm text-muted-foreground">
|
||||
{q.answeredVia === "system" ? <Hourglass className="size-3.5" /> : <CircleCheck className="size-3.5 text-ok" />}
|
||||
{q.answeredVia === "system" ? q.answer : `Ответ (${q.answeredVia}): ${q.answer}`}
|
||||
{q.answeredVia === "system" ? t.text(q.answer) : t("Ответ ({via}): {answer}", { via: q.answeredVia, answer: q.answer })}
|
||||
</p>
|
||||
) : (
|
||||
<form action={answerQuestion} className="flex flex-col gap-2">
|
||||
<Hidden fields={{ questionId: q.id, back }} />
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{q.kind === "approval" && <Button name="choice" value="ок" variant="default" size="sm">Одобрить</Button>}
|
||||
{/* i18n-ignore: choice values are answers to the agent */}
|
||||
{q.kind === "approval" && <Button name="choice" value="ок" variant="default" size="sm">{t("Одобрить")}</Button>}
|
||||
{q.kind === "permission" && (
|
||||
<>
|
||||
<Button name="choice" value="allow" variant="default" size="sm">Разрешить</Button>
|
||||
<Button name="choice" value="always" size="sm">Всегда</Button>
|
||||
<Button name="choice" value="deny" variant="destructive" size="sm">Запретить</Button>
|
||||
<Button name="choice" value="allow" variant="default" size="sm">{t("Разрешить")}</Button>
|
||||
<Button name="choice" value="always" size="sm">{t("Всегда")}</Button>
|
||||
<Button name="choice" value="deny" variant="destructive" size="sm">{t("Запретить")}</Button>
|
||||
</>
|
||||
)}
|
||||
{review && <Button name="choice" value="__accept" variant="default" size="sm">Принять</Button>}
|
||||
{q.kind === "attention" && !review && <Button name="choice" value="Продолжай." variant="default" size="sm">Продолжай</Button>}
|
||||
{review && <Button name="choice" value="__accept" variant="default" size="sm">{t("Принять")}</Button>}
|
||||
{/* i18n-ignore: the value is the message to the agent */}
|
||||
{q.kind === "attention" && !review && <Button name="choice" value="Продолжай." variant="default" size="sm">{t("Продолжай")}</Button>}
|
||||
{(q.options ?? []).map((o) => (
|
||||
<Button key={o} name="choice" value={o} size="sm">{o}</Button>
|
||||
<Button key={o} name="choice" value={o} size="sm">{t.text(o)}</Button>
|
||||
))}
|
||||
</div>
|
||||
{q.kind !== "permission" && (
|
||||
<div className="flex gap-2">
|
||||
<Input name="answer" data-hotkey-answer placeholder={q.kind === "approval" || review ? "Замечание — вернёт на доработку" : "Свой ответ"} aria-label="Ответ" className="h-8" />
|
||||
<Button size="sm">Ответить</Button>
|
||||
<Input name="answer" data-hotkey-answer placeholder={q.kind === "approval" || review ? t("Замечание — вернёт на доработку") : t("Свой ответ")} aria-label={t("Ответ")} className="h-8" />
|
||||
<Button size="sm">{t("Ответить")}</Button>
|
||||
</div>
|
||||
)}
|
||||
</form>
|
||||
@ -80,17 +85,18 @@ export function QuestionCard({ q, taskKey, taskStatus, back, compact = false }:
|
||||
}
|
||||
|
||||
/** Message / stop / resume controls of one runner. */
|
||||
export function SessionActions({ s, back }: { s: SessionView; back: string }) {
|
||||
export async function SessionActions({ s, back }: { s: SessionView; back: string }) {
|
||||
const t = await getT();
|
||||
const alive = !["done", "failed"].includes(s.status);
|
||||
return (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{alive && (
|
||||
<form action={messageSession} className="flex min-w-0 flex-[1_1_16rem] gap-2">
|
||||
<Hidden fields={{ sessionId: s.id, back }} />
|
||||
<Input name="text" placeholder="Написать агенту" aria-label="Написать агенту" className="h-8" />
|
||||
<Button size="sm" aria-label="Отправить" title="Отправить">
|
||||
<Input name="text" placeholder={t("Написать агенту")} aria-label={t("Написать агенту")} className="h-8" />
|
||||
<Button size="sm" aria-label={t("Отправить")} title={t("Отправить")}>
|
||||
<Send />
|
||||
<span className="max-sm:hidden">Отправить</span>
|
||||
<span className="max-sm:hidden">{t("Отправить")}</span>
|
||||
</Button>
|
||||
</form>
|
||||
)}
|
||||
@ -99,7 +105,7 @@ export function SessionActions({ s, back }: { s: SessionView; back: string }) {
|
||||
<Hidden fields={{ sessionId: s.id, back }} />
|
||||
<Button variant="destructive" size="sm">
|
||||
<Square />
|
||||
Остановить
|
||||
{t("Остановить")}
|
||||
</Button>
|
||||
</form>
|
||||
)}
|
||||
@ -121,7 +127,8 @@ export function AttachCommand({ name }: { name: string }) {
|
||||
}
|
||||
|
||||
/** `steps` (PEP-33): the live step feed of the agent, shown with the terminal. */
|
||||
export function SessionCard({ s, back, showTitle = false, terminal = false, steps }: { s: SessionView; back: string; showTitle?: boolean; terminal?: boolean; steps?: StepView[] }) {
|
||||
export async function SessionCard({ s, back, showTitle = false, terminal = false, steps }: { s: SessionView; back: string; showTitle?: boolean; terminal?: boolean; steps?: StepView[] }) {
|
||||
const t = await getT();
|
||||
return (
|
||||
<article className="flex flex-col gap-2.5 rounded-lg border bg-card p-3.5">
|
||||
<header className="flex flex-wrap items-center gap-x-2 gap-y-1 text-sm">
|
||||
@ -133,8 +140,8 @@ export function SessionCard({ s, back, showTitle = false, terminal = false, step
|
||||
<Link href={`/runners?id=${s.id}`} className="text-muted-foreground hover:text-foreground">#{s.id}</Link> · {s.provider}
|
||||
{s.subscriptionName && <> · {s.subscriptionName}</>}
|
||||
{s.host && <> · {s.host.name}</>}
|
||||
{s.container && <> · в контейнере</>}
|
||||
{s.subscriptionSwitches > 0 && <> · переключений {s.subscriptionSwitches}</>} · пок. {s.generation} · {ago(s.lastActivityAt)}
|
||||
{s.container && <> · {t("в контейнере")}</>}
|
||||
{s.subscriptionSwitches > 0 && <> · {t("переключений {n}", { n: s.subscriptionSwitches })}</>} · {t("пок. {n}", { n: s.generation })} · {ago(s.lastActivityAt, t)}
|
||||
</span>
|
||||
</header>
|
||||
<SessionUsageLine usage={s.usage} provider={s.provider} />
|
||||
@ -143,7 +150,7 @@ export function SessionCard({ s, back, showTitle = false, terminal = false, step
|
||||
{!terminal && !["done", "failed"].includes(s.status) && (
|
||||
<Button asChild size="sm" variant="outline" className="self-start">
|
||||
<Link href={`/runners?id=${s.id}`}>
|
||||
<SquareTerminal /> Открыть терминал
|
||||
<SquareTerminal /> {t("Открыть терминал")}
|
||||
</Link>
|
||||
</Button>
|
||||
)}
|
||||
@ -157,15 +164,16 @@ 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 «Подробнее».
|
||||
*/
|
||||
export function AgentAtWork({ s, back }: { s: SessionView; back: string }) {
|
||||
export async function AgentAtWork({ s, back }: { s: SessionView; back: string }) {
|
||||
const alive = !["done", "failed"].includes(s.status);
|
||||
const verb = s.status === "running" || s.status === "starting" ? "работает над" : s.status === "waiting_input" ? "спрашивает по" : "вёл";
|
||||
const t = await getT();
|
||||
const verb = s.status === "running" || s.status === "starting" ? t("работает над") : s.status === "waiting_input" ? t("спрашивает по") : t("вёл");
|
||||
return (
|
||||
<article className="flex flex-col gap-2.5 rounded-lg border bg-card p-3.5" data-agent-at-work={s.id}>
|
||||
<header className="flex flex-wrap items-center gap-x-2.5 gap-y-1.5">
|
||||
<AgentBadge name={s.agentName ?? "Агент"} large />
|
||||
<AgentBadge name={s.agentName ?? t("Агент")} large />
|
||||
<StatusBadge status={s.status} kind="session" />
|
||||
<span className="ml-auto text-xs text-muted-foreground">{ago(s.lastActivityAt)}</span>
|
||||
<span className="ml-auto text-xs text-muted-foreground">{ago(s.lastActivityAt, t)}</span>
|
||||
</header>
|
||||
<p className="m-0 flex flex-wrap items-center gap-x-2 gap-y-0.5 text-sm">
|
||||
{s.taskKey ? (
|
||||
@ -176,28 +184,28 @@ export function AgentAtWork({ s, back }: { s: SessionView; back: string }) {
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<span className="text-muted-foreground">свободный терминал в проекте</span>
|
||||
<span className="text-muted-foreground">{t("свободный терминал в проекте")}</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} />
|
||||
<Disclosure summary="Подробнее" className="border-0 bg-transparent [&>summary]:px-0 [&>summary]:py-0 [&>summary]:text-xs [&>summary]:font-normal [&>summary]:text-muted-foreground">
|
||||
<Disclosure summary={t("Подробнее")} 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">
|
||||
запуск #{s.id} · {s.provider}
|
||||
{t("запуск #{id}", { id: s.id })} · {s.provider}
|
||||
{s.subscriptionName && <> · {s.subscriptionName}</>}
|
||||
{s.host && <> · {s.host.name}</>}
|
||||
{s.container && <> · в контейнере</>}
|
||||
{s.subscriptionSwitches > 0 && <> · переключений {s.subscriptionSwitches}</>} · пок. {s.generation}
|
||||
{s.container && <> · {t("в контейнере")}</>}
|
||||
{s.subscriptionSwitches > 0 && <> · {t("переключений {n}", { n: s.subscriptionSwitches })}</>} · {t("пок. {n}", { n: s.generation })}
|
||||
</span>
|
||||
<SessionUsageLine usage={s.usage} provider={s.provider} />
|
||||
<AttachCommand name={s.tmuxName} />
|
||||
{alive && (
|
||||
<Button asChild size="sm" variant="outline" className="self-start">
|
||||
<Link href={`/runners?id=${s.id}`}>
|
||||
<SquareTerminal /> Открыть терминал
|
||||
<SquareTerminal /> {t("Открыть терминал")}
|
||||
</Link>
|
||||
</Button>
|
||||
)}
|
||||
@ -207,11 +215,12 @@ export function AgentAtWork({ s, back }: { s: SessionView; back: string }) {
|
||||
);
|
||||
}
|
||||
|
||||
export function ProjectList({ projects, userId }: { projects: Array<Project & { ownerLogin?: string | null }>; userId: number }) {
|
||||
export async function ProjectList({ projects, userId }: { projects: Array<Project & { ownerLogin?: string | null }>; userId: number }) {
|
||||
const t = await getT();
|
||||
if (!projects.length)
|
||||
return (
|
||||
<Empty>
|
||||
Проектов пока нет. <Link href="/projects/new" className="text-primary">Создать первый</Link>
|
||||
{t("Проектов пока нет.")} <Link href="/projects/new" className="text-primary">{t("Создать первый")}</Link>
|
||||
</Empty>
|
||||
);
|
||||
return (
|
||||
@ -222,7 +231,7 @@ export function ProjectList({ projects, userId }: { projects: Array<Project & {
|
||||
<span className="flex items-center gap-2">
|
||||
<span className="rounded bg-muted px-1.5 font-mono text-xs text-primary">{p.key}</span>
|
||||
<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>}
|
||||
{p.ownerId !== userId && <span className="ml-auto rounded-full border px-2 text-[11px] text-muted-foreground">{p.ownerLogin !== undefined ? (p.ownerLogin ?? t("без владельца")) : t("общий")}</span>}
|
||||
</span>
|
||||
<span className="truncate font-mono text-xs text-muted-foreground">
|
||||
{p.giteaOwner}/{p.giteaRepo}
|
||||
|
||||
@ -5,6 +5,8 @@ import { CircleAlert, CircleCheck } from "lucide-react";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { SESSION_STATUS, TASK_STATUS, TONE_BG } from "@/lib/status";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import { intlLocale, translator, type Translator } from "@peppa/shared/i18n";
|
||||
|
||||
export function PageHeader({ title, crumbs, actions, children }: { title: ReactNode; crumbs?: ReactNode; actions?: ReactNode; children?: ReactNode }) {
|
||||
return (
|
||||
@ -50,22 +52,24 @@ export function Key({ children, href, className }: { children: ReactNode; href?:
|
||||
return href ? <Link href={href} className={cls}>{children}</Link> : <span className={cls}>{children}</span>;
|
||||
}
|
||||
|
||||
export function StatusBadge({ status, kind = "task" }: { status: string; kind?: "task" | "session" }) {
|
||||
export async function StatusBadge({ status, kind = "task" }: { status: string; kind?: "task" | "session" }) {
|
||||
const t = await getT();
|
||||
const s = (kind === "task" ? TASK_STATUS : SESSION_STATUS)[status] ?? { label: status, tone: "muted" as const };
|
||||
return (
|
||||
<Badge variant={s.tone}>
|
||||
{kind === "session" && <span className={cn("size-1.5 rounded-full", TONE_BG[s.tone], status === "running" && "animate-pulse")} />}
|
||||
{s.label}
|
||||
{t.text(s.label)}
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
|
||||
export function Flash({ error }: { error?: string }) {
|
||||
export async function Flash({ error }: { error?: string }) {
|
||||
const t = await getT();
|
||||
return error ? (
|
||||
// Sticky: an action far down the page (a board card, «Принять») must not fail silently above the fold.
|
||||
<p role="alert" className="sticky top-2 z-40 mb-4 flex items-start gap-2 rounded-lg border border-destructive/60 bg-[color-mix(in_oklab,var(--destructive)_14%,var(--background))] px-4 py-3 text-sm text-foreground shadow-lg">
|
||||
<CircleAlert className="mt-0.5 size-4 shrink-0 text-destructive" />
|
||||
<span>{error}</span>
|
||||
<span>{t.text(error)}</span>
|
||||
</p>
|
||||
) : null;
|
||||
}
|
||||
@ -92,11 +96,14 @@ export function Disclosure({ summary, children, open, className }: { summary: Re
|
||||
);
|
||||
}
|
||||
|
||||
export function ago(d: Date | null | undefined): string {
|
||||
const ruT = translator("ru");
|
||||
|
||||
/** «5 мин назад»; pass the page's translator for its language (Russian without one). */
|
||||
export function ago(d: Date | null | undefined, t: Translator = ruT): string {
|
||||
if (!d) return "—";
|
||||
const s = Math.round((Date.now() - d.getTime()) / 1000);
|
||||
if (s < 60) return `${s} с назад`;
|
||||
if (s < 3600) return `${Math.round(s / 60)} мин назад`;
|
||||
if (s < 86400) return `${Math.round(s / 3600)} ч назад`;
|
||||
return d.toLocaleDateString("ru-RU");
|
||||
if (s < 60) return t("{n} с назад", { n: s });
|
||||
if (s < 3600) return t("{n} мин назад", { n: Math.round(s / 60) });
|
||||
if (s < 86400) return t("{n} ч назад", { n: Math.round(s / 3600) });
|
||||
return d.toLocaleDateString(intlLocale(t.locale));
|
||||
}
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
import { listSessions, PeppaError, STEP_EVENT, projectForUser, resolveTask, userProjectIds, type Project, type TaskRef } from "@peppa/core";
|
||||
import { events, projects, questions, sessions, tasks } from "@peppa/db";
|
||||
import { formatTaskKey } from "@peppa/shared";
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
import { and, asc, count, desc, eq, inArray, isNull, ne } from "drizzle-orm";
|
||||
import { db } from "./db";
|
||||
|
||||
@ -29,7 +30,7 @@ export async function activeSessions(userId: number) {
|
||||
|
||||
export async function projectForUserByKey(userId: number, key: string): Promise<Project> {
|
||||
const [p] = await db.select().from(projects).where(eq(projects.key, key.toUpperCase()));
|
||||
if (!p) throw new PeppaError("Не найдено");
|
||||
if (!p) throw new PeppaError(m("Не найдено"));
|
||||
return projectForUser(db, userId, p.id);
|
||||
}
|
||||
|
||||
|
||||
@ -1,4 +1,7 @@
|
||||
// Keyboard shortcuts (PEP-52): one list for the «?» dialog and /help/shortcuts.
|
||||
// Texts are dictionary keys (m): translate where rendered with t(s.what) / t(PALETTE_KEYS).
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
|
||||
export interface Shortcut {
|
||||
keys: string[];
|
||||
what: string;
|
||||
@ -6,18 +9,18 @@ export interface Shortcut {
|
||||
}
|
||||
|
||||
export const SHORTCUTS: Shortcut[] = [
|
||||
{ keys: ["⌘K", "Ctrl+K"], what: "Командная палитра: поиск и переход к проекту, стори, раннеру, вопросу; «В работу», «Ответить»" },
|
||||
{ keys: ["/"], what: "Фокус в поиск на странице", where: "списки с полем поиска (Раннеры)" },
|
||||
{ keys: ["g", "h"], what: "Главная" },
|
||||
{ keys: ["g", "p"], what: "Проекты" },
|
||||
{ keys: ["g", "r"], what: "Раннеры" },
|
||||
{ keys: ["g", "s"], what: "Настройки" },
|
||||
{ keys: ["j"], what: "Следующий раннер", where: "Раннеры" },
|
||||
{ keys: ["k"], what: "Предыдущий раннер", where: "Раннеры" },
|
||||
{ keys: ["a"], what: "Фокус в поле ответа первого открытого вопроса", where: "Главная, стори, раннер" },
|
||||
{ keys: ["?"], what: "Список сочетаний" },
|
||||
{ keys: ["Esc"], what: "Закрыть палитру или окно" },
|
||||
{ keys: ["⌘K", "Ctrl+K"], what: m("Командная палитра: поиск и переход к проекту, стори, раннеру, вопросу; «В работу», «Ответить»") },
|
||||
{ keys: ["/"], what: m("Фокус в поиск на странице"), where: m("списки с полем поиска (Раннеры)") },
|
||||
{ keys: ["g", "h"], what: m("Главная") },
|
||||
{ keys: ["g", "p"], what: m("Проекты") },
|
||||
{ keys: ["g", "r"], what: m("Раннеры") },
|
||||
{ keys: ["g", "s"], what: m("Настройки") },
|
||||
{ keys: ["j"], what: m("Следующий раннер"), where: m("Раннеры") },
|
||||
{ keys: ["k"], what: m("Предыдущий раннер"), where: m("Раннеры") },
|
||||
{ keys: ["a"], what: m("Фокус в поле ответа первого открытого вопроса"), where: m("Главная, стори, раннер") },
|
||||
{ keys: ["?"], what: m("Список сочетаний") },
|
||||
{ keys: ["Esc"], what: m("Закрыть палитру или окно") },
|
||||
];
|
||||
|
||||
/** In the palette: ↑/↓ choose, Enter opens, ⌘Enter / Ctrl+Enter — «В работу» for a backlog story. */
|
||||
export const PALETTE_KEYS = "↑↓ — выбор · Enter — открыть · ⌘Enter — в работу · Esc — закрыть";
|
||||
export const PALETTE_KEYS = m("↑↓ — выбор · Enter — открыть · ⌘Enter — в работу · Esc — закрыть");
|
||||
|
||||
@ -1,26 +1,29 @@
|
||||
// Labels and colour tones of task and runner statuses, shared by badges, rows and the side panel.
|
||||
// Labels are Russian dictionary keys (PEP-98): render them through `t(label)`.
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
|
||||
export type Tone = "primary" | "ok" | "warn" | "info" | "danger" | "muted";
|
||||
|
||||
export const TASK_STATUS: Record<string, { label: string; tone: Tone }> = {
|
||||
backlog: { label: "Бэклог", tone: "muted" },
|
||||
backlog: { label: m("Бэклог"), tone: "muted" },
|
||||
proposing: { label: "Proposal", tone: "primary" },
|
||||
awaiting_approval: { label: "Ждёт одобрения", tone: "primary" },
|
||||
in_progress: { label: "В работе", tone: "info" },
|
||||
review: { label: "Ревью", tone: "ok" },
|
||||
done: { label: "Готово", tone: "ok" },
|
||||
blocked: { label: "Блок", tone: "danger" },
|
||||
awaiting_approval: { label: m("Ждёт одобрения"), tone: "primary" },
|
||||
in_progress: { label: m("В работе"), tone: "info" },
|
||||
review: { label: m("Ревью"), tone: "ok" },
|
||||
done: { label: m("Готово"), tone: "ok" },
|
||||
blocked: { label: m("Блок"), tone: "danger" },
|
||||
};
|
||||
|
||||
// PEP-89: said about an agent, in plain words — the reader is a product manager.
|
||||
export const SESSION_STATUS: Record<string, { label: string; tone: Tone }> = {
|
||||
starting: { label: "запускается", tone: "info" },
|
||||
running: { label: "работает", tone: "info" },
|
||||
waiting_input: { label: "ждёт вашего ответа", tone: "primary" },
|
||||
idle: { label: "свободен", tone: "muted" },
|
||||
stalled: { label: "остановился — нужна помощь", tone: "warn" },
|
||||
rate_limited: { label: "ждёт сброса лимита", tone: "warn" },
|
||||
done: { label: "закончил", tone: "ok" },
|
||||
failed: { label: "остановился с ошибкой", tone: "danger" },
|
||||
starting: { label: m("запускается"), tone: "info" },
|
||||
running: { label: m("работает"), tone: "info" },
|
||||
waiting_input: { label: m("ждёт вашего ответа"), tone: "primary" },
|
||||
idle: { label: m("свободен"), tone: "muted" },
|
||||
stalled: { label: m("остановился — нужна помощь"), tone: "warn" },
|
||||
rate_limited: { label: m("ждёт сброса лимита"), tone: "warn" },
|
||||
done: { label: m("закончил"), tone: "ok" },
|
||||
failed: { label: m("остановился с ошибкой"), tone: "danger" },
|
||||
};
|
||||
|
||||
/** Text colour per tone, e.g. for status dots. */
|
||||
|
||||
@ -1,11 +1,11 @@
|
||||
# Tasks: PEP-98
|
||||
|
||||
## 1. Основа
|
||||
- [ ] 1.1 `@peppa/shared/i18n`: локали, `t`, `localizeText`, `m`, словари `en` (по разделам), `kk` (пустой)
|
||||
- [ ] 1.2 Язык пользователя: `getUserLocale`/`setUserLocale` (core, `settings`), cookie `peppa_lang`
|
||||
- [ ] 1.3 Веб: `getLocale`/`getT` (сервер), `I18nProvider`/`useT` (клиент), `<html lang>`, title «Peppa FACTORY»
|
||||
- [x] 1.1 `@peppa/shared/i18n`: локали, `t`, `localizeText`, `m`, словари `en` (по разделам), `kk` (пустой)
|
||||
- [x] 1.2 Язык пользователя: `getUserLocale`/`setUserLocale` (core, `settings`), cookie `peppa_lang`
|
||||
- [x] 1.3 Веб: `getLocale`/`getT` (сервер), `I18nProvider`/`useT` (клиент), `<html lang>`, title «Peppa FACTORY»
|
||||
- [ ] 1.4 Переключатель RU/EN/KZ: страница входа и «Настройки»; при входе язык пользователя → cookie
|
||||
- [ ] 1.5 Скрипт и тест `i18n-check` (ключи `t(`/`m(` в коде ↔ `en`)
|
||||
- [x] 1.5 Скрипт и тест `i18n-check` (ключи `t(`/`m(` в коде ↔ `en`)
|
||||
|
||||
## 2. Веб
|
||||
- [ ] 2.1 Каркас: Sidebar, Workspace, layout, общие компоненты, палитра, вход/велком
|
||||
@ -15,8 +15,8 @@
|
||||
- [ ] 2.5 Ошибки server actions и тексты из core на страницах — через `localizeText`
|
||||
|
||||
## 3. Бот и уведомления
|
||||
- [ ] 3.1 Бот: локализация `text`/`caption`/кнопок/`answerCallbackQuery` по языку чата
|
||||
- [ ] 3.2 `deliverToUser`: push на языке пользователя
|
||||
- [x] 3.1 Бот: локализация `text`/`caption`/кнопок/`answerCallbackQuery` по языку чата
|
||||
- [x] 3.2 `deliverToUser`: push на языке пользователя
|
||||
- [ ] 3.3 Шаблоны сообщений core/runner/bot помечены `m(…)` и переведены
|
||||
|
||||
## 4. Завершение
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
// Who may log into Peppa at all (web and remote MCP): an allowlist of Gitea logins, plus
|
||||
// people invited to or members of a project, plus local accounts without Gitea (PEP-68).
|
||||
import { m as tr } from "@peppa/shared/i18n";
|
||||
import { projectInvites, projectMembers, users, type Db } from "@peppa/db";
|
||||
import { eq, sql } from "drizzle-orm";
|
||||
import { getSetting, setSetting } from "./settings.ts";
|
||||
@ -43,8 +44,8 @@ export async function isUserAllowed(db: Db, user: User): Promise<boolean> {
|
||||
export async function giteaLoginRefusal(db: Db, login: string): Promise<string | null> {
|
||||
const [u] = await db.select().from(users).where(sql`lower(${users.login}) = ${login.toLowerCase()}`);
|
||||
if (!u) return null;
|
||||
if (u.giteaId < 0) return `Логин «${login}» занят локальным пользователем Пеппы — войдите по логину и паролю`;
|
||||
if (u.disabledAt) return "Нет доступа к Пеппе — попросите администратора";
|
||||
if (u.giteaId < 0) return tr("Логин «{login}» занят локальным пользователем Пеппы — войдите по логину и паролю", { login });
|
||||
if (u.disabledAt) return tr("Нет доступа к Пеппе — попросите администратора");
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
// PEP-41: provider, model and effort of the agent per platform → project → story, escalation
|
||||
// to a stronger model after failures, a fallback provider when the main one has no login.
|
||||
import { m as tr } from "@peppa/shared/i18n";
|
||||
import { events, tasks, type Db } from "@peppa/db";
|
||||
import { and, desc, eq, inArray } from "drizzle-orm";
|
||||
import { PeppaError } from "./errors.ts";
|
||||
@ -10,7 +11,7 @@ export const AGENT_PROVIDERS = ["claude", "codex", "opencode"] as const;
|
||||
export type AgentProvider = (typeof AGENT_PROVIDERS)[number];
|
||||
export const AGENT_EFFORTS = ["low", "medium", "high", "xhigh", "max"] as const;
|
||||
export type AgentEffort = (typeof AGENT_EFFORTS)[number];
|
||||
export const AGENT_EFFORT_RU: Record<AgentEffort, string> = { low: "низкие", medium: "средние", high: "высокие", xhigh: "очень высокие", max: "максимальные" };
|
||||
export const AGENT_EFFORT_RU: Record<AgentEffort, string> = { low: tr("низкие"), medium: tr("средние"), high: tr("высокие"), xhigh: tr("очень высокие"), max: tr("максимальные") };
|
||||
|
||||
export interface AgentSettings {
|
||||
/** null = the subscription decides (as before PEP-41). */
|
||||
@ -48,7 +49,7 @@ const MODEL_RE = /^[A-Za-z0-9][A-Za-z0-9._:/\[\]-]{0,79}$/;
|
||||
/** Validates one field; returns undefined for "inherit" (empty), throws on a bad value when strict. */
|
||||
function parseField(k: keyof AgentSettings, v: unknown, strict: boolean): AgentSettings[keyof AgentSettings] | undefined {
|
||||
const bad = () => {
|
||||
if (strict) throw new PeppaError(`Недопустимое значение ${k}: ${String(v)}`);
|
||||
if (strict) throw new PeppaError(tr("Недопустимое значение {k}: {v}", { k, v: String(v) }));
|
||||
return undefined;
|
||||
};
|
||||
if (v === undefined || v === "") return undefined;
|
||||
@ -75,7 +76,7 @@ function clean(p: Record<string, unknown> | null, strict = false): AgentSettings
|
||||
if (!p) return out;
|
||||
for (const [k, v] of Object.entries(p)) {
|
||||
if (!AGENT_FIELDS.includes(k as keyof AgentSettings)) {
|
||||
if (strict) throw new PeppaError(`Неизвестная настройка агента: ${k}`);
|
||||
if (strict) throw new PeppaError(tr("Неизвестная настройка агента: {k}", { k }));
|
||||
continue;
|
||||
}
|
||||
const val = parseField(k as keyof AgentSettings, v, strict);
|
||||
@ -130,7 +131,7 @@ export function parseAgentPairs(pairs: string[]): Record<string, unknown> {
|
||||
const out: Record<string, unknown> = {};
|
||||
for (const p of pairs) {
|
||||
const i = p.indexOf("=");
|
||||
if (i < 1) throw new PeppaError(`Ожидается ключ=значение: ${p}`);
|
||||
if (i < 1) throw new PeppaError(tr("Ожидается ключ=значение: {p}", { p }));
|
||||
const k = p.slice(0, i).trim();
|
||||
const v = p.slice(i + 1).trim();
|
||||
out[k] = v === "-" ? "" : v;
|
||||
@ -204,6 +205,6 @@ export async function sessionLaunchModel(db: Db, sessionId: number): Promise<str
|
||||
|
||||
/** One line for a card: "opus · усилия высокие" / "как у подписки". */
|
||||
export function agentSettingsLabel(s: Pick<AgentSettings, "provider" | "model" | "effort">): string {
|
||||
const parts = [s.provider, s.model, s.effort ? `усилия ${AGENT_EFFORT_RU[s.effort]}` : null].filter(Boolean);
|
||||
return parts.length ? parts.join(" · ") : "по умолчанию";
|
||||
const parts = [s.provider, s.model, s.effort ? tr("усилия {effort}", { effort: AGENT_EFFORT_RU[s.effort] }) : null].filter(Boolean);
|
||||
return parts.length ? parts.join(" · ") : tr("по умолчанию");
|
||||
}
|
||||
|
||||
@ -2,6 +2,7 @@
|
||||
// questions to the PM, runner hours, time agents waited for the PM, limit hits, spend.
|
||||
// Computed from what is already recorded (task_updated events, questions, sessions,
|
||||
// code reviews, sessions.usage); projects are small enough to do it per request.
|
||||
import { m as tr } from "@peppa/shared/i18n";
|
||||
import { codeReviews, events, questions, sessions, tasks, type Db } from "@peppa/db";
|
||||
import { and, eq, gte, inArray } from "drizzle-orm";
|
||||
import { epicSpend, spendOf, type EpicSpend, type Spend } from "./budgets.ts";
|
||||
@ -174,4 +175,4 @@ export async function projectMetrics(db: Db, projectId: number, o: { weeks?: num
|
||||
}
|
||||
|
||||
export const fmtPct = (x: number | null) => (x == null ? "—" : `${Math.round(x * 100)}%`);
|
||||
export const fmtHours = (h: number | null) => (h == null ? "—" : h < 1 ? `${Math.round(h * 60)} мин` : h < 48 ? `${Math.round(h * 10) / 10} ч` : `${Math.round((h / 24) * 10) / 10} дн`);
|
||||
export const fmtHours = (h: number | null) => (h == null ? "—" : h < 1 ? tr("{n} мин", { n: Math.round(h * 60) }) : h < 48 ? tr("{n} ч", { n: Math.round(h * 10) / 10 }) : tr("{n} дн", { n: Math.round((h / 24) * 10) / 10 }));
|
||||
|
||||
@ -1,4 +1,5 @@
|
||||
// PEP-48: the journal — events with their authors (person + channel, agent, Peppa itself).
|
||||
import { m as tr } from "@peppa/shared/i18n";
|
||||
import { events, oauthClients, projects, tasks, users, type Db } from "@peppa/db";
|
||||
import { formatTaskKey } from "@peppa/shared";
|
||||
import { and, desc, eq, inArray, lt, type SQL } from "drizzle-orm";
|
||||
@ -13,15 +14,15 @@ export async function logEvent(db: Db, e: { projectId: number; taskId?: number |
|
||||
return row!;
|
||||
}
|
||||
|
||||
export const ACTOR_KIND_NAMES: Record<ActorKind, string> = { user: "человек", agent: "агент", system: "Пеппа" };
|
||||
export const ACTOR_KIND_NAMES: Record<ActorKind, string> = { user: tr("человек"), agent: tr("агент"), system: tr("Пеппа") };
|
||||
export const ACTOR_CHANNEL_NAMES: Record<ActorChannel, string> = {
|
||||
web: "веб",
|
||||
web: tr("веб"),
|
||||
telegram: "Telegram",
|
||||
mcp: "MCP",
|
||||
cli: "CLI",
|
||||
terminal: "терминал",
|
||||
hook: "хук",
|
||||
watchdog: "вачдог",
|
||||
terminal: tr("терминал"),
|
||||
hook: tr("хук"),
|
||||
watchdog: tr("вачдог"),
|
||||
gitea: "Gitea",
|
||||
};
|
||||
|
||||
@ -101,7 +102,7 @@ export async function listJournal(db: Db, f: JournalFilter = {}): Promise<Journa
|
||||
export function actorLabel(e: Pick<JournalEntry, "actorKind" | "actorChannel" | "actorLogin" | "actorClient" | "sessionId">): string | null {
|
||||
if (!e.actorKind) return null;
|
||||
const ch = e.actorChannel ? ACTOR_CHANNEL_NAMES[e.actorChannel] : null;
|
||||
if (e.actorKind === "user") return [e.actorLogin ?? "человек", ch && `${ch}${e.actorClient ? ` (${e.actorClient})` : ""}`].filter(Boolean).join(" · ");
|
||||
if (e.actorKind === "agent") return e.sessionId ? `агент · раннер #${e.sessionId}` : "агент";
|
||||
return ch ? `Пеппа · ${ch}` : "Пеппа";
|
||||
if (e.actorKind === "user") return [e.actorLogin ?? tr("человек"), ch && `${ch}${e.actorClient ? ` (${e.actorClient})` : ""}`].filter(Boolean).join(" · ");
|
||||
if (e.actorKind === "agent") return e.sessionId ? `${tr("агент")} · ${tr("раннер #{id}", { id: e.sessionId })}` : tr("агент");
|
||||
return ch ? `${tr("Пеппа")} · ${ch}` : tr("Пеппа");
|
||||
}
|
||||
|
||||
@ -2,6 +2,7 @@
|
||||
// proposals, how PRs are merged and how stories are closed, and idle pushes (PEP-24).
|
||||
// Stored in `settings` (`project.autonomy:<id>`), no schema change; a project without a
|
||||
// row is "manual" — exactly the behaviour before PEP-23.
|
||||
import { m as tr } from "@peppa/shared/i18n";
|
||||
import type { Db } from "@peppa/db";
|
||||
import { PeppaError } from "./errors.ts";
|
||||
import { deleteSetting, getSetting, setSetting } from "./settings.ts";
|
||||
@ -61,18 +62,18 @@ export const AUTONOMY_LEVELS: Record<AutonomyLevel, AutonomySettings> = {
|
||||
};
|
||||
|
||||
export const AUTONOMY_LEVEL_RU: Record<AutonomyLevel | "custom", string> = {
|
||||
manual: "Ручной",
|
||||
assisted: "С подсказками",
|
||||
self: "Сам берёт",
|
||||
auto: "Автомат",
|
||||
custom: "Свой",
|
||||
manual: tr("Ручной"),
|
||||
assisted: tr("С подсказками"),
|
||||
self: tr("Сам берёт"),
|
||||
auto: tr("Автомат"),
|
||||
custom: tr("Свой"),
|
||||
};
|
||||
|
||||
export const AUTONOMY_LEVEL_HINT: Record<AutonomyLevel, string> = {
|
||||
manual: "PM двигает карточки и принимает стори; при простое Пеппа молчит.",
|
||||
assisted: "PM решает сам, но если агенты простаивают, а в бэклоге есть стори, — пуш с кнопками «Взять / Следующую / Не сейчас».",
|
||||
self: "Стори берутся из бэклога сами, по порядку на доске; результат принимаете вы («Принять» в ревью).",
|
||||
auto: "Стори берутся из бэклога сами, зелёный PR мержится, стори закрывается после мержа. PM — только на стопперы и изменения конвейера.",
|
||||
manual: tr("PM двигает карточки и принимает стори; при простое Пеппа молчит."),
|
||||
assisted: tr("PM решает сам, но если агенты простаивают, а в бэклоге есть стори, — пуш с кнопками «Взять / Следующую / Не сейчас»."),
|
||||
self: tr("Стори берутся из бэклога сами, по порядку на доске; результат принимаете вы («Принять» в ревью)."),
|
||||
auto: tr("Стори берутся из бэклога сами, зелёный PR мержится, стори закрывается после мержа. PM — только на стопперы и изменения конвейера."),
|
||||
};
|
||||
|
||||
/** PEP-79: what a newly created project starts with (existing projects keep their settings). */
|
||||
@ -96,13 +97,13 @@ export type AutonomyPatch = Partial<AutonomySettings> & { level?: AutonomyLevel
|
||||
|
||||
const intIn = (v: unknown, min: number, max: number, name: string): number => {
|
||||
const n = Number(v);
|
||||
if (!Number.isInteger(n) || n < min || n > max) throw new PeppaError(`${name}: целое от ${min} до ${max}`);
|
||||
if (!Number.isInteger(n) || n < min || n > max) throw new PeppaError(tr("{name}: целое от {min} до {max}", { name, min, max }));
|
||||
return n;
|
||||
};
|
||||
|
||||
function normalize(s: AutonomySettings): AutonomySettings {
|
||||
const oneOf = <T extends string>(v: unknown, all: readonly T[], name: string): T => {
|
||||
if (!all.includes(v as T)) throw new PeppaError(`${name}: одно из ${all.join(", ")}`);
|
||||
if (!all.includes(v as T)) throw new PeppaError(tr("{name}: одно из {list}", { name, list: all.join(", ") }));
|
||||
return v as T;
|
||||
};
|
||||
const hour = (v: unknown, name: string) => (v === null || v === undefined || v === "" ? null : intIn(v, 0, 23, name));
|
||||
@ -129,7 +130,7 @@ function normalize(s: AutonomySettings): AutonomySettings {
|
||||
*/
|
||||
export async function setAutonomy(db: Db, projectId: number, patch: AutonomyPatch): Promise<AutonomySettings> {
|
||||
const { level, ...fields } = patch;
|
||||
if (level && !(level in AUTONOMY_LEVELS)) throw new PeppaError(`Уровень: одно из ${Object.keys(AUTONOMY_LEVELS).join(", ")}`);
|
||||
if (level && !(level in AUTONOMY_LEVELS)) throw new PeppaError(tr("Уровень: одно из {list}", { list: Object.keys(AUTONOMY_LEVELS).join(", ") }));
|
||||
const base = level ? AUTONOMY_LEVELS[level] : await getAutonomy(db, projectId);
|
||||
const defined = Object.fromEntries(Object.entries(fields).filter(([, v]) => v !== undefined));
|
||||
const next = normalize({ ...base, ...defined });
|
||||
@ -149,12 +150,20 @@ export function inAutonomyQuietHours(s: Pick<AutonomySettings, "quietFrom" | "qu
|
||||
export function describeAutonomy(s: AutonomySettings): string {
|
||||
const level = autonomyLevel(s);
|
||||
const lines = [
|
||||
`Уровень: ${AUTONOMY_LEVEL_RU[level]}`,
|
||||
`Стори из бэклога берёт: ${s.pick === "auto" ? `Пеппа сама (одновременно до ${s.wipLimit})` : "PM"}`,
|
||||
`Proposal: ${s.proposal === "pm" ? "каждый одобряет PM" : "без одобрения, кроме архитектурных стопперов"}`,
|
||||
`Мерж PR: ${s.merge === "auto" ? "автоматически после зелёных проверок (кроме изменений конвейера)" : "по «Принять»"}`,
|
||||
`Закрытие: ${s.close === "pm" ? "PM принимает" : s.close === "after_merge" ? "сразу после мержа" : `само через ${s.closeAfterHours} ч без замечаний`}`,
|
||||
`Пуш при простое: ${s.idlePush ? `да, не чаще раза в ${s.idlePushHours} ч${s.quietFrom != null ? `, тихие часы ${s.quietFrom}:00–${s.quietTo}:00` : ""}` : "нет"}`,
|
||||
tr("Уровень: {v}", { v: AUTONOMY_LEVEL_RU[level] }),
|
||||
tr("Стори из бэклога берёт: {v}", { v: s.pick === "auto" ? tr("Пеппа сама (одновременно до {n})", { n: s.wipLimit }) : "PM" }),
|
||||
tr("Proposal: {v}", { v: s.proposal === "pm" ? tr("каждый одобряет PM") : tr("без одобрения, кроме архитектурных стопперов") }),
|
||||
tr("Мерж PR: {v}", { v: s.merge === "auto" ? tr("автоматически после зелёных проверок (кроме изменений конвейера)") : tr("по «Принять»") }),
|
||||
tr("Закрытие: {v}", {
|
||||
v: s.close === "pm" ? tr("PM принимает") : s.close === "after_merge" ? tr("сразу после мержа") : tr("само через {n} ч без замечаний", { n: s.closeAfterHours }),
|
||||
}),
|
||||
tr("Пуш при простое: {v}", {
|
||||
v: !s.idlePush
|
||||
? tr("нет")
|
||||
: s.quietFrom != null
|
||||
? tr("да, не чаще раза в {n} ч, тихие часы {from}:00–{to}:00", { n: s.idlePushHours, from: s.quietFrom, to: s.quietTo })
|
||||
: tr("да, не чаще раза в {n} ч", { n: s.idlePushHours }),
|
||||
}),
|
||||
];
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
@ -1,3 +1,4 @@
|
||||
import { m as tr } from "@peppa/shared/i18n";
|
||||
import type { Db } from "@peppa/db";
|
||||
import { peppaHome } from "@peppa/shared";
|
||||
import { mkdirSync, readdirSync, rmSync } from "node:fs";
|
||||
@ -25,7 +26,7 @@ export function verifyBackup(file: string): void {
|
||||
const copy = new DatabaseSync(file, { readOnly: true });
|
||||
try {
|
||||
const r = copy.prepare("PRAGMA quick_check").get() as { quick_check?: string } | undefined;
|
||||
if (r?.quick_check !== "ok") throw new Error(`копия повреждена: ${r?.quick_check ?? "нет ответа"}`);
|
||||
if (r?.quick_check !== "ok") throw new Error(tr("копия повреждена: {v}", { v: r?.quick_check ?? tr("нет ответа") }));
|
||||
copy.prepare("select count(*) from settings").get();
|
||||
} finally {
|
||||
copy.close();
|
||||
@ -56,8 +57,8 @@ export async function backupDb(db: Db, o: BackupOptions = {}): Promise<{ file?:
|
||||
rmSync(file, { force: true });
|
||||
} catch {}
|
||||
const msg = (e as Error).message;
|
||||
const reason = /SQLITE_FULL|ENOSPC|disk is full/i.test(msg) ? "нет места на диске" : msg;
|
||||
await alertAdmins(db, `backup:fail:${day}`, `⚠️ Резервная копия базы Пеппы не сделана: ${reason}`, log);
|
||||
const reason = /SQLITE_FULL|ENOSPC|disk is full/i.test(msg) ? tr("нет места на диске") : msg;
|
||||
await alertAdmins(db, `backup:fail:${day}`, tr("⚠️ Резервная копия базы Пеппы не сделана: {reason}", { reason }), log);
|
||||
return { error: reason };
|
||||
}
|
||||
if (o.file) {
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
// PEP-43: story budgets (runner minutes, tokens, restarts, cost) and what a story has spent.
|
||||
// Stored in `settings` like autonomy (PEP-23): `budget.project:<id>` is the default for the
|
||||
// project's stories, `budget.task:<id>` replaces it for one story. No row = no limit.
|
||||
import { m as tr } from "@peppa/shared/i18n";
|
||||
import { goals, sessions, tasks, type Db } from "@peppa/db";
|
||||
import { eq, inArray } from "drizzle-orm";
|
||||
import { deleteSetting, getSetting, setSetting } from "./settings.ts";
|
||||
@ -10,7 +11,7 @@ export const BUDGET_KINDS = ["minutes", "tokens", "restarts", "costUsd"] as cons
|
||||
export type BudgetKind = (typeof BUDGET_KINDS)[number];
|
||||
export type Budget = Partial<Record<BudgetKind, number | null>>;
|
||||
|
||||
export const BUDGET_LABELS: Record<BudgetKind, string> = { minutes: "время", tokens: "токены", restarts: "перезапуски", costUsd: "стоимость" };
|
||||
export const BUDGET_LABELS: Record<BudgetKind, string> = { minutes: tr("время"), tokens: tr("токены"), restarts: tr("перезапуски"), costUsd: tr("стоимость") };
|
||||
|
||||
const projectKey = (projectId: number) => `budget.project:${projectId}`;
|
||||
const taskKey = (taskId: number) => `budget.task:${taskId}`;
|
||||
@ -132,7 +133,7 @@ export async function taskBudgetView(db: Db, task: { id: number; projectId: numb
|
||||
|
||||
export function formatBudgetValue(k: BudgetKind, v: number | null | undefined): string {
|
||||
if (v == null) return "∞";
|
||||
if (k === "minutes") return v >= 120 ? `${Math.round((v / 60) * 10) / 10} ч` : `${v} мин`;
|
||||
if (k === "minutes") return v >= 120 ? tr("{n} ч", { n: Math.round((v / 60) * 10) / 10 }) : tr("{n} мин", { n: v });
|
||||
if (k === "costUsd") return `$${v.toFixed(2)}`;
|
||||
return v.toLocaleString("ru-RU");
|
||||
}
|
||||
@ -141,7 +142,12 @@ export function formatBudgetValue(k: BudgetKind, v: number | null | undefined):
|
||||
export function describeBudget(v: Pick<TaskBudgetView, "budget" | "spend">): string {
|
||||
return BUDGET_KINDS.map((k) => {
|
||||
const spent = k === "costUsd" ? (v.spend.costUsd == null ? "—" : `${v.spend.costEstimated ? "≈ " : ""}$${v.spend.costUsd.toFixed(2)}`) : formatBudgetValue(k, v.spend[k]);
|
||||
return `${BUDGET_LABELS[k]} ${spent} из ${formatBudgetValue(k, v.budget[k])}`;
|
||||
const vars = { spent, budget: formatBudgetValue(k, v.budget[k]) };
|
||||
// A key per kind: "<label> {spent} из {budget}" translates as one piece.
|
||||
if (k === "minutes") return tr("время {spent} из {budget}", vars);
|
||||
if (k === "tokens") return tr("токены {spent} из {budget}", vars);
|
||||
if (k === "restarts") return tr("перезапуски {spent} из {budget}", vars);
|
||||
return tr("стоимость {spent} из {budget}", vars);
|
||||
}).join(" · ");
|
||||
}
|
||||
|
||||
@ -167,7 +173,7 @@ export async function epicSpend(db: Db, projectId: number, now = Date.now()): Pr
|
||||
return [...groups.entries()]
|
||||
.map(([goalId, g]) => ({
|
||||
goalId,
|
||||
title: goalId == null ? "без эпика" : (gs.find((x) => x.id === goalId)?.title ?? `#${goalId}`),
|
||||
title: goalId == null ? tr("без эпика") : (gs.find((x) => x.id === goalId)?.title ?? `#${goalId}`),
|
||||
stories: g.ids.size,
|
||||
done: g.done,
|
||||
spend: spendOf(ss.filter((s) => s.taskId != null && g.ids.has(s.taskId)), now),
|
||||
|
||||
@ -2,6 +2,7 @@
|
||||
// chat per user. Messages are a short-lived projection (PEPPA_CHAT_TTL_DAYS) of events,
|
||||
// questions, releases and incidents, which stay in their own tables; people's messages are
|
||||
// stored here too. Telegram groups linked to chats are the bot's business (apps/bot).
|
||||
import { m as tr } from "@peppa/shared/i18n";
|
||||
import { createHmac, randomBytes } from "node:crypto";
|
||||
import { chatMessages, chats, events, incidents, projects, questions, releases, tasks, telegramOutbox, users, type Db } from "@peppa/db";
|
||||
import { formatTaskKey } from "@peppa/shared";
|
||||
@ -36,7 +37,7 @@ export async function ensureMasterChat(db: Db, userId: number): Promise<Chat> {
|
||||
|
||||
export async function getChat(db: Db, id: number): Promise<Chat> {
|
||||
const [c] = await db.select().from(chats).where(eq(chats.id, id));
|
||||
if (!c) throw new PeppaError("Чат не найден");
|
||||
if (!c) throw new PeppaError(tr("Чат не найден"));
|
||||
return c;
|
||||
}
|
||||
|
||||
@ -44,9 +45,9 @@ export async function getChat(db: Db, id: number): Promise<Chat> {
|
||||
export async function chatForUser(db: Db, user: Pick<User, "id">, chatId: number): Promise<Chat> {
|
||||
const c = await getChat(db, chatId);
|
||||
if (c.kind === "master") {
|
||||
if (c.userId !== user.id) throw new PeppaError("Чат не найден");
|
||||
if (c.userId !== user.id) throw new PeppaError(tr("Чат не найден"));
|
||||
} else await projectForUser(db, user.id, c.projectId!).catch(() => {
|
||||
throw new PeppaError("Чат не найден");
|
||||
throw new PeppaError(tr("Чат не найден"));
|
||||
});
|
||||
return c;
|
||||
}
|
||||
@ -87,7 +88,7 @@ export async function listChats(db: Db, user: Pick<User, "id">): Promise<ChatLis
|
||||
);
|
||||
const masterAt = [...last.values()].reduce<Date | null>((a, b) => (b && (!a || b > a) ? b : a), null);
|
||||
return [
|
||||
{ id: master.id, kind: "master", slug: "master", title: "Мастер-чат", projectId: null, tgTitle: master.tgTitle, lastAt: masterAt, open: [...open.values()].reduce((a, b) => a + b, 0) },
|
||||
{ id: master.id, kind: "master", slug: "master", title: tr("Мастер-чат"), projectId: null, tgTitle: master.tgTitle, lastAt: masterAt, open: [...open.values()].reduce((a, b) => a + b, 0) },
|
||||
...ps.map((p) => {
|
||||
const c = projectChats.get(p.id)!;
|
||||
return { id: c.id, kind: "project" as const, slug: p.key, title: `${p.key} · ${p.name}`, projectId: p.id, tgTitle: c.tgTitle, lastAt: last.get(c.id) ?? null, open: open.get(p.id) ?? 0 };
|
||||
@ -130,11 +131,11 @@ export async function threadTitle(db: Db, key: string): Promise<string | null> {
|
||||
}
|
||||
if (kind === "incident") {
|
||||
const [i] = await db.select({ title: incidents.title }).from(incidents).where(eq(incidents.id, id));
|
||||
return i ? `Ошибка: ${i.title}` : null;
|
||||
return i ? tr("Ошибка: {title}", { title: i.title }) : null;
|
||||
}
|
||||
if (kind === "release") {
|
||||
const [r] = await db.select({ env: releases.env, sha: releases.sha }).from(releases).where(eq(releases.id, id));
|
||||
return r ? `Релиз ${r.env} ${r.sha.slice(0, 7)}` : null;
|
||||
return r ? tr("Релиз {env} {sha}", { env: r.env, sha: r.sha.slice(0, 7) }) : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@ -248,13 +249,13 @@ const CURSOR_OBJECTS = "chat.cursor.objects";
|
||||
const BATCH = 500;
|
||||
|
||||
const STATUS_RU: Record<string, string> = {
|
||||
backlog: "бэклог",
|
||||
backlog: tr("бэклог"),
|
||||
proposing: "proposal",
|
||||
awaiting_approval: "ждёт одобрения",
|
||||
in_progress: "в работе",
|
||||
review: "ревью",
|
||||
done: "готово",
|
||||
blocked: "заблокирована",
|
||||
awaiting_approval: tr("ждёт одобрения"),
|
||||
in_progress: tr("в работе"),
|
||||
review: tr("ревью"),
|
||||
done: tr("готово"),
|
||||
blocked: tr("заблокирована"),
|
||||
};
|
||||
export const statusRu = (s: string) => STATUS_RU[s] ?? s;
|
||||
|
||||
@ -269,33 +270,63 @@ const EVENT_TEXT: Record<string, (p: P) => { text: string; important?: boolean;
|
||||
const to = (p.to as P | undefined)?.status;
|
||||
if (!to || from === to) return null;
|
||||
const icon = to === "review" ? "👀" : to === "done" ? "✅" : to === "in_progress" ? "▶️" : to === "blocked" ? "⛔" : "•";
|
||||
const tail = to === "review" ? " — готово к ревью" : "";
|
||||
return { text: `${icon} Статус: ${from ? `${statusRu(String(from))} → ` : ""}${statusRu(String(to))}${tail}`, important: ["review", "done", "blocked", "awaiting_approval"].includes(String(to)) };
|
||||
const v = { from: statusRu(String(from)), to: statusRu(String(to)) };
|
||||
// One key per variant: localizeText matches a rendered line against a whole template.
|
||||
const change =
|
||||
to === "review"
|
||||
? from
|
||||
? tr("Статус: {from} → {to} — готово к ревью", v)
|
||||
: tr("Статус: {to} — готово к ревью", v)
|
||||
: from
|
||||
? tr("Статус: {from} → {to}", v)
|
||||
: tr("Статус: {to}", v);
|
||||
return { text: `${icon} ${change}`, important: ["review", "done", "blocked", "awaiting_approval"].includes(String(to)) };
|
||||
},
|
||||
progress: (p) => ({ text: `📈 ${cut(s(p.text), 1500)}`, author: "agent" }),
|
||||
pm_comment: () => null, // handled separately: a person's message
|
||||
// PEP-4: the project's repo moved to another Gitea namespace.
|
||||
repo_transferred: (p) => ({ text: `📦 Репозиторий перенесён: ${s(p.from)} → ${s(p.to)}`, important: true }),
|
||||
repo_transferred: (p) => ({ text: tr("📦 Репозиторий перенесён: {from} → {to}", { from: s(p.from), to: s(p.to) }), important: true }),
|
||||
// PEP-84: «продакт» and «аналитик» talk to the PM in the story's thread.
|
||||
intake_note: (p) => ({ text: `${p.role === "product" ? "🧭 Продакт" : "🔎 Аналитик"}: ${cut(s(p.text), 3000)}`, important: true, author: "agent" }),
|
||||
pr_merged_in_gitea: (p) => ({ text: `🔀 PR #${s(p.pr)} смержен${p.by ? ` (${s(p.by)})` : ""}`, important: true }),
|
||||
started: () => ({ text: "▶️ Агент запущен" }),
|
||||
resumed: () => ({ text: "🔁 Агент продолжает работу" }),
|
||||
stopped: () => ({ text: "⏹ Агент остановлен" }),
|
||||
stalled: (p) => ({ text: `⚠️ Агент молчит${p.idleMinutes ? ` ${s(p.idleMinutes)} мин` : ""}`, important: true }),
|
||||
stop_failure: (p) => ({ text: `❌ Ход агента прерван: ${s(p.error) || "ошибка"}`, important: true }),
|
||||
exited: (p) => ({ text: `💀 Процесс агента завершился${p.exitStatus != null ? ` (код ${s(p.exitStatus)})` : ""}`, important: true }),
|
||||
usage_limit: (p) => ({ text: `⏳ Лимит подписки${p.line ? `: ${cut(s(p.line), 200)}` : ""}`, important: true }),
|
||||
auto_restarted: (p) => ({ text: `🔁 Перезапуск после сбоя${p.attempt ? ` (${s(p.attempt)} из ${s(p.of)})` : ""}`, important: true }),
|
||||
restart_failed: (p) => ({ text: `❌ Перезапуск не удался${p.error ? `: ${cut(s(p.error), 200)}` : ""}`, important: true }),
|
||||
budget_paused: () => ({ text: "💸 Бюджет стори исчерпан — агент на паузе", important: true }),
|
||||
subscription_switched: (p) => ({ text: `🔀 Подписка переключена${p.to ? ` на ${s(p.to)}` : ""}`, important: true }),
|
||||
model_escalated: (p) => ({ text: `⬆️ Модель усилена${p.model ? `: ${s(p.model)}` : ""}` }),
|
||||
intake_note: (p) => ({ text: p.role === "product" ? tr("🧭 Продакт: {text}", { text: cut(s(p.text), 3000) }) : tr("🔎 Аналитик: {text}", { text: cut(s(p.text), 3000) }), important: true, author: "agent" }),
|
||||
pr_merged_in_gitea: (p) => ({ text: p.by ? tr("🔀 PR #{pr} смержен ({by})", { pr: s(p.pr), by: s(p.by) }) : tr("🔀 PR #{pr} смержен", { pr: s(p.pr) }), important: true }),
|
||||
started: () => ({ text: tr("▶️ Агент запущен") }),
|
||||
resumed: () => ({ text: tr("🔁 Агент продолжает работу") }),
|
||||
stopped: () => ({ text: tr("⏹ Агент остановлен") }),
|
||||
stalled: (p) => ({ text: p.idleMinutes ? tr("⚠️ Агент молчит {n} мин", { n: s(p.idleMinutes) }) : tr("⚠️ Агент молчит"), important: true }),
|
||||
stop_failure: (p) => ({ text: tr("❌ Ход агента прерван: {error}", { error: s(p.error) || tr("ошибка") }), important: true }),
|
||||
exited: (p) => ({ text: p.exitStatus != null ? tr("💀 Процесс агента завершился (код {code})", { code: s(p.exitStatus) }) : tr("💀 Процесс агента завершился"), important: true }),
|
||||
usage_limit: (p) => ({ text: p.line ? tr("⏳ Лимит подписки: {line}", { line: cut(s(p.line), 200) }) : tr("⏳ Лимит подписки"), important: true }),
|
||||
auto_restarted: (p) => ({ text: p.attempt ? tr("🔁 Перезапуск после сбоя ({attempt} из {of})", { attempt: s(p.attempt), of: s(p.of) }) : tr("🔁 Перезапуск после сбоя"), important: true }),
|
||||
restart_failed: (p) => ({ text: p.error ? tr("❌ Перезапуск не удался: {error}", { error: cut(s(p.error), 200) }) : tr("❌ Перезапуск не удался"), important: true }),
|
||||
budget_paused: () => ({ text: tr("💸 Бюджет стори исчерпан — агент на паузе"), important: true }),
|
||||
subscription_switched: (p) => ({ text: p.to ? tr("🔀 Подписка переключена на {to}", { to: s(p.to) }) : tr("🔀 Подписка переключена"), important: true }),
|
||||
model_escalated: (p) => ({ text: p.model ? tr("⬆️ Модель усилена: {model}", { model: s(p.model) }) : tr("⬆️ Модель усилена") }),
|
||||
};
|
||||
|
||||
const RELEASE_ICON: Record<string, string> = { deploying: "⏳", healthy: "🚀", rolled_back: "↩️", failed: "❌", removed: "🧹" };
|
||||
const RELEASE_RU: Record<string, string> = { deploying: "выкатывается", healthy: "здоров", rolled_back: "откатан", failed: "не выкатился", removed: "убран" };
|
||||
const INCIDENT_RU: Record<string, string> = { new: "новая", open: "открыта", pending: "ждёт решения", task: "заведена стори", ignored: "игнорируем", resolved: "исправлена", regressed: "вернулась" };
|
||||
// "<icon> <env> <sha>: <status>[ · <stories>]" — a whole template per status, so the line translates.
|
||||
const RELEASE_LINE: Record<string, (v: { release: string; tasks: string }) => string> = {
|
||||
deploying: (v) => (v.tasks ? tr("{release}: выкатывается · {tasks}", v) : tr("{release}: выкатывается", v)),
|
||||
healthy: (v) => (v.tasks ? tr("{release}: здоров · {tasks}", v) : tr("{release}: здоров", v)),
|
||||
rolled_back: (v) => (v.tasks ? tr("{release}: откатан · {tasks}", v) : tr("{release}: откатан", v)),
|
||||
failed: (v) => (v.tasks ? tr("{release}: не выкатился · {tasks}", v) : tr("{release}: не выкатился", v)),
|
||||
removed: (v) => (v.tasks ? tr("{release}: убран · {tasks}", v) : tr("{release}: убран", v)),
|
||||
};
|
||||
const INCIDENT_RU: Record<string, string> = {
|
||||
new: tr("новая"),
|
||||
open: tr("открыта"),
|
||||
pending: tr("ждёт решения"),
|
||||
task: tr("заведена стори"),
|
||||
ignored: tr("игнорируем"),
|
||||
resolved: tr("исправлена"),
|
||||
regressed: tr("вернулась"),
|
||||
};
|
||||
|
||||
/** "🐞 <status>: <title>[\n<culprit>][ · <env>][ · N раз]". */
|
||||
function incidentText(i: { status: string; title: string; culprit: string | null; environment: string | null; events: number }): string {
|
||||
const base = `${tr("🐞 {status}: {title}", { status: INCIDENT_RU[i.status] ?? i.status, title: cut(i.title, 300) })}${i.culprit ? `\n${cut(i.culprit, 200)}` : ""}${i.environment ? ` · ${i.environment}` : ""}`;
|
||||
return i.events > 1 ? tr("{text} · {n} раз", { text: base, n: i.events }) : base;
|
||||
}
|
||||
|
||||
/** First id of rows newer than a day (a fresh install doesn't import the whole history). */
|
||||
async function initialCursor(db: Db, table: typeof events | typeof questions, now: Date): Promise<number> {
|
||||
@ -369,7 +400,7 @@ export async function syncChats(db: Db, o: { now?: Date } = {}): Promise<number>
|
||||
for (;;) {
|
||||
const rows = await db.select().from(questions).where(gt(questions.id, qCursor)).orderBy(asc(questions.id)).limit(BATCH);
|
||||
for (const q of rows) {
|
||||
const head = q.kind === "approval" ? "🟡 Нужно одобрение" : q.kind === "permission" ? "🔐 Нужно разрешение" : q.kind === "question" ? "❓ Вопрос агента" : "🔔";
|
||||
const head = q.kind === "approval" ? tr("🟡 Нужно одобрение") : q.kind === "permission" ? tr("🔐 Нужно разрешение") : q.kind === "question" ? tr("❓ Вопрос агента") : "🔔";
|
||||
await add({
|
||||
chatId: await chatId(q.projectId),
|
||||
threadKey: q.taskId ? `task:${q.taskId}` : null,
|
||||
@ -392,13 +423,15 @@ export async function syncChats(db: Db, o: { now?: Date } = {}): Promise<number>
|
||||
const savedObjects = await getSetting<number>(db, CURSOR_OBJECTS);
|
||||
const since = new Date((savedObjects ?? now.getTime() - DAY) - 60_000);
|
||||
for (const r of await db.select().from(releases).where(gt(releases.updatedAt, since)).orderBy(asc(releases.id))) {
|
||||
const tasksIn = r.tasks.length ? ` · ${r.tasks.slice(0, 8).join(", ")}` : "";
|
||||
const release = `${RELEASE_ICON[r.status] ?? "•"} ${r.env} ${r.sha.slice(0, 7)}`;
|
||||
const tasksIn = r.tasks.slice(0, 8).join(", ");
|
||||
const line = RELEASE_LINE[r.status]?.({ release, tasks: tasksIn }) ?? `${release}: ${r.status}${tasksIn ? ` · ${tasksIn}` : ""}`;
|
||||
await add({
|
||||
chatId: await chatId(r.projectId),
|
||||
threadKey: `release:${r.id}`,
|
||||
kind: "event",
|
||||
important: r.env !== "preview" || r.status === "failed" || r.status === "rolled_back",
|
||||
text: `${RELEASE_ICON[r.status] ?? "•"} ${r.env} ${r.sha.slice(0, 7)}: ${RELEASE_RU[r.status] ?? r.status}${tasksIn}${r.reason ? `\n${cut(r.reason, 300)}` : ""}`,
|
||||
text: `${line}${r.reason ? `\n${cut(r.reason, 300)}` : ""}`,
|
||||
url: r.host ? `https://${r.host}` : r.runUrl,
|
||||
dedupeKey: `release:${r.id}:${r.status}`,
|
||||
});
|
||||
@ -410,7 +443,7 @@ export async function syncChats(db: Db, o: { now?: Date } = {}): Promise<number>
|
||||
taskId: i.taskId,
|
||||
kind: "event",
|
||||
important: i.status === "new" || i.status === "regressed" || i.status === "pending",
|
||||
text: `🐞 ${INCIDENT_RU[i.status] ?? i.status}: ${cut(i.title, 300)}${i.culprit ? `\n${cut(i.culprit, 200)}` : ""}${i.environment ? ` · ${i.environment}` : ""}${i.events > 1 ? ` · ${i.events} раз` : ""}`,
|
||||
text: incidentText(i),
|
||||
url: i.url,
|
||||
dedupeKey: `incident:${i.id}:${i.status}`,
|
||||
});
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
// CI results of factory projects (PEP-57): check runs per commit, the summary shown on the
|
||||
// task card and the gate for review and merge (green checks of the PR head, no conflicts).
|
||||
import { m as tr } from "@peppa/shared/i18n";
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { checkRuns, tasks, type Db } from "@peppa/db";
|
||||
@ -58,14 +59,14 @@ type RunLike = { check: string; state: CheckState; runUrl?: string | null; logTa
|
||||
export function summarizeChecks(configured: string[], runs: RunLike[], sha: string | null): CiSummary {
|
||||
const total = configured.length;
|
||||
const base = { sha, total, runUrl: runLink(runs.find((r) => r.runUrl)?.runUrl) };
|
||||
if (!total) return { ...base, state: "not_configured", passed: 0, failed: [], label: "проверки не настроены" };
|
||||
if (!total) return { ...base, state: "not_configured", passed: 0, failed: [], label: tr("проверки не настроены") };
|
||||
// `install` is not a check of its own, but when it fails nothing else ran.
|
||||
const failed = runs.filter((r) => r.state === "failure" || r.state === "error").map((r) => ({ check: r.check, runUrl: runLink(r.runUrl), logTail: r.logTail }));
|
||||
const passed = configured.filter((c) => runs.some((r) => r.check === c && r.state === "success")).length;
|
||||
if (failed.length) return { ...base, state: "failure", passed, failed, label: `Проверки: ${passed} из ${total} пройдены, упало: ${failed.map((f) => f.check).join(", ")}` };
|
||||
if (passed === total) return { ...base, state: "success", passed, failed, label: `Проверки: ${passed} из ${total} пройдены` };
|
||||
if (!runs.length) return { ...base, state: "none", passed, failed, label: "Проверки ещё не запускались" };
|
||||
return { ...base, state: "pending", passed, failed, label: `Проверки идут: ${passed} из ${total}` };
|
||||
if (failed.length) return { ...base, state: "failure", passed, failed, label: tr("Проверки: {passed} из {total} пройдены, упало: {failed}", { passed, total, failed: failed.map((f) => f.check).join(", ") }) };
|
||||
if (passed === total) return { ...base, state: "success", passed, failed, label: tr("Проверки: {passed} из {total} пройдены", { passed, total }) };
|
||||
if (!runs.length) return { ...base, state: "none", passed, failed, label: tr("Проверки ещё не запускались") };
|
||||
return { ...base, state: "pending", passed, failed, label: tr("Проверки идут: {passed} из {total}", { passed, total }) };
|
||||
}
|
||||
|
||||
/** Stores a CI result (one row per project/commit/check). `changed` — the state is new. */
|
||||
@ -149,9 +150,9 @@ export async function prGate(ref: TaskRef, client?: GiteaClient): Promise<GateRe
|
||||
.filter((s) => s.context.startsWith("peppa/"))
|
||||
.map((s) => ({ check: s.context.slice(6), state: (s.status === "error" || s.status === "failure" ? "failure" : s.status === "success" ? "success" : "pending") as CheckState, runUrl: s.target_url }));
|
||||
const summary = summarizeChecks(configuredChecks(projectJson), runs, pull.head.sha);
|
||||
if (summary.state === "failure") return { ok: false, reason: `проверки не пройдены (${summary.failed.map((f) => f.check).join(", ")})`, summary, pull };
|
||||
if (summary.state === "pending" || summary.state === "none") return { ok: false, reason: `проверки ещё идут (${summary.passed} из ${summary.total})`, summary, pull };
|
||||
if (pull.state === "open" && pull.mergeable === false) return { ok: false, reason: "есть конфликты с основной веткой", summary, pull };
|
||||
if (summary.state === "failure") return { ok: false, reason: tr("проверки не пройдены ({list})", { list: summary.failed.map((f) => f.check).join(", ") }), summary, pull };
|
||||
if (summary.state === "pending" || summary.state === "none") return { ok: false, reason: tr("проверки ещё идут ({passed} из {total})", { passed: summary.passed, total: summary.total }), summary, pull };
|
||||
if (pull.state === "open" && pull.mergeable === false) return { ok: false, reason: tr("есть конфликты с основной веткой"), summary, pull };
|
||||
return { ok: true, summary, pull };
|
||||
}
|
||||
|
||||
|
||||
@ -1,3 +1,4 @@
|
||||
import { m as tr } from "@peppa/shared/i18n";
|
||||
import { actorColumns } from "./actor.ts";
|
||||
// PEP-42: story dependencies. "PAY-3 waits for PAY-2": PAY-3 is blocked until every
|
||||
// predecessor reaches review/done (an archived predecessor doesn't block). Same project only,
|
||||
@ -79,9 +80,9 @@ async function reaches(db: Db, from: number, to: number): Promise<boolean> {
|
||||
|
||||
/** Makes `ref` wait for `blocker`. Idempotent; rejects other projects, itself and cycles. */
|
||||
export async function addDependency(db: Db, ref: TaskRef, blocker: TaskRef): Promise<void> {
|
||||
if (blocker.project.id !== ref.project.id) throw new PeppaError(`${blocker.key} из другого проекта — зависимости только внутри проекта`);
|
||||
if (blocker.task.id === ref.task.id) throw new PeppaError(`${ref.key} не может зависеть от самой себя`);
|
||||
if (await reaches(db, blocker.task.id, ref.task.id)) throw new PeppaError(`Цикл зависимостей: ${blocker.key} уже ждёт ${ref.key}`);
|
||||
if (blocker.project.id !== ref.project.id) throw new PeppaError(tr("{key} из другого проекта — зависимости только внутри проекта", { key: blocker.key }));
|
||||
if (blocker.task.id === ref.task.id) throw new PeppaError(tr("{key} не может зависеть от самой себя", { key: ref.key }));
|
||||
if (await reaches(db, blocker.task.id, ref.task.id)) throw new PeppaError(tr("Цикл зависимостей: {key} уже ждёт {key2}", { key: blocker.key, key2: ref.key }));
|
||||
const r = await db.insert(taskDeps).values({ taskId: ref.task.id, blockedById: blocker.task.id }).onConflictDoNothing().returning();
|
||||
if (r.length) await logDeps(db, ref, { added: blocker.key });
|
||||
}
|
||||
@ -123,5 +124,5 @@ async function logDeps(db: Db, ref: TaskRef, payload: Record<string, string>) {
|
||||
/** "ждёт PAY-2, PAY-5" for the open blockers, or null. */
|
||||
export function blockedLabel(list: Blocker[] | undefined): string | null {
|
||||
const open = (list ?? []).filter((b) => b.open);
|
||||
return open.length ? `ждёт ${open.map((b) => b.key).join(", ")}` : null;
|
||||
return open.length ? tr("ждёт {list}", { list: open.map((b) => b.key).join(", ") }) : null;
|
||||
}
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
// Daily digest (PEP-29): per user, per project — done in the last day, in progress, in
|
||||
// review, waiting for the user, stuck, limits. Sent from the watchdog tick at the user's
|
||||
// time; /digest in the bot renders it on demand.
|
||||
import { m as tr } from "@peppa/shared/i18n";
|
||||
import { projects, pushSubscriptions, questions, sessions, tasks, users, type Db } from "@peppa/db";
|
||||
import { formatTaskKey, loadEnv } from "@peppa/shared";
|
||||
import { and, asc, gte, inArray, isNull, notInArray } from "drizzle-orm";
|
||||
@ -92,37 +93,50 @@ const clip = (s: string, n: number) => (s.length > n ? `${s.slice(0, n)}…` : s
|
||||
|
||||
function taskList(webUrl: string, items: TaskLine[], max = 8): string {
|
||||
const shown = items.slice(0, max).map((t) => `<a href="${esc(`${webUrl}/t/${t.key}`)}">${esc(t.key)}</a> ${esc(clip(t.title, 60))}`);
|
||||
if (items.length > max) shown.push(`…и ещё ${items.length - max}`);
|
||||
if (items.length > max) shown.push(`…${tr("и ещё {n}", { n: items.length - max })}`);
|
||||
return shown.map((s) => ` • ${s}`).join("\n");
|
||||
}
|
||||
|
||||
/** Telegram HTML text of the digest. */
|
||||
export function renderDigest(d: Digest, o: { webUrl: string; title?: string }): string {
|
||||
const lines = [`<b>${esc(o.title ?? "☀️ Сводка за сутки")}</b>`];
|
||||
const lines = [`<b>${esc(o.title ?? tr("☀️ Сводка за сутки"))}</b>`];
|
||||
if (!d.projects.length) {
|
||||
lines.push("", "Всё тихо: за сутки ничего не сделано, ничего не в работе и ничего не ждёт тебя.");
|
||||
lines.push("", tr("Всё тихо: за сутки ничего не сделано, ничего не в работе и ничего не ждёт тебя."));
|
||||
return lines.join("\n");
|
||||
}
|
||||
for (const p of d.projects) {
|
||||
lines.push("", `<b>${esc(p.name)}</b> (${esc(p.key)}) — <a href="${esc(`${o.webUrl}/p/${p.key}`)}">доска</a>`);
|
||||
if (p.done.length) lines.push(`✅ Сделано: ${p.done.length}`, taskList(o.webUrl, p.done));
|
||||
if (p.inProgress.length) lines.push(`🔨 В работе: ${p.inProgress.length}`, taskList(o.webUrl, p.inProgress, 5));
|
||||
if (p.review.length) lines.push(`👀 На ревью: ${p.review.length}`, taskList(o.webUrl, p.review));
|
||||
if (p.waiting) lines.push(`⏳ Ждёт тебя: ${p.waiting}`);
|
||||
if (p.blocked.length) lines.push(`⛔ Заблокировано: ${p.blocked.length}`, taskList(o.webUrl, p.blocked));
|
||||
if (p.stalled) lines.push(`🧊 Зависло раннеров: ${p.stalled}`);
|
||||
lines.push("", `<b>${esc(p.name)}</b> (${esc(p.key)}) — <a href="${esc(`${o.webUrl}/p/${p.key}`)}">${tr("доска")}</a>`);
|
||||
if (p.done.length) lines.push(tr("✅ Сделано: {n}", { n: p.done.length }), taskList(o.webUrl, p.done));
|
||||
if (p.inProgress.length) lines.push(tr("🔨 В работе: {n}", { n: p.inProgress.length }), taskList(o.webUrl, p.inProgress, 5));
|
||||
if (p.review.length) lines.push(tr("👀 На ревью: {n}", { n: p.review.length }), taskList(o.webUrl, p.review));
|
||||
if (p.waiting) lines.push(tr("⏳ Ждёт тебя: {n}", { n: p.waiting }));
|
||||
if (p.blocked.length) lines.push(tr("⛔ Заблокировано: {n}", { n: p.blocked.length }), taskList(o.webUrl, p.blocked));
|
||||
if (p.stalled) lines.push(tr("🧊 Зависло раннеров: {n}", { n: p.stalled }));
|
||||
if (p.rateLimited || p.limitResumes) {
|
||||
lines.push(`⌛ Лимит: ${[p.rateLimited ? `ждут сброса ${p.rateLimited}` : null, p.limitResumes ? `авто-продолжений за сутки ${p.limitResumes}` : null].filter(Boolean).join(", ")}`);
|
||||
const v = { waiting: p.rateLimited, resumes: p.limitResumes };
|
||||
lines.push(
|
||||
p.rateLimited && p.limitResumes
|
||||
? tr("⌛ Лимит: ждут сброса {waiting}, авто-продолжений за сутки {resumes}", v)
|
||||
: p.rateLimited
|
||||
? tr("⌛ Лимит: ждут сброса {waiting}", v)
|
||||
: tr("⌛ Лимит: авто-продолжений за сутки {resumes}", v),
|
||||
);
|
||||
}
|
||||
}
|
||||
if (d.totals.waiting) lines.push("", `<a href="${esc(o.webUrl)}">Открыть Пеппу</a> — ответить на ${d.totals.waiting}.`);
|
||||
if (d.totals.waiting) lines.push("", `<a href="${esc(o.webUrl)}">${tr("Открыть Пеппу")}</a> — ${tr("ответить на {n}", { n: d.totals.waiting })}.`);
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
/** One-line summary for a push notification. */
|
||||
export function digestSummary(d: Digest): string {
|
||||
const t = d.totals;
|
||||
return [t.done && `сделано ${t.done}`, t.inProgress && `в работе ${t.inProgress}`, t.review && `на ревью ${t.review}`, t.waiting && `ждёт тебя ${t.waiting}`, t.stuck && `зависло ${t.stuck}`]
|
||||
return [
|
||||
t.done && tr("сделано {n}", { n: t.done }),
|
||||
t.inProgress && tr("в работе {n}", { n: t.inProgress }),
|
||||
t.review && tr("на ревью {n}", { n: t.review }),
|
||||
t.waiting && tr("ждёт тебя {n}", { n: t.waiting }),
|
||||
t.stuck && tr("зависло {n}", { n: t.stuck }),
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(" · ");
|
||||
}
|
||||
@ -158,7 +172,7 @@ export async function digestTick(db: Db, o: { now?: Date; log?: (m: string) => v
|
||||
event: "digest",
|
||||
dedupeKey: `digest:u${u.id}:${clock.date}`,
|
||||
telegram: { params: { text: renderDigest(d, { webUrl }), parse_mode: "HTML", link_preview_options: { is_disabled: true } } },
|
||||
push: { title: "Сводка за сутки", body: digestSummary(d), url: "/", tag: "digest" },
|
||||
push: { title: tr("Сводка за сутки"), body: digestSummary(d), url: "/", tag: "digest" },
|
||||
now,
|
||||
},
|
||||
prefs,
|
||||
|
||||
@ -2,6 +2,7 @@
|
||||
// short-lived <auth><challenge/><nonce/></auth>, reads the signed XML from the relay itself and takes
|
||||
// the signer's IIN from the certificate. The XMLDSig itself is not verified here — the relay is
|
||||
// trusted (PM decision, see openspec design); the challenge and nonce never leave the server.
|
||||
import { m as tr } from "@peppa/shared/i18n";
|
||||
import { randomBytes, randomInt, randomUUID } from "node:crypto";
|
||||
import { eq, sql } from "drizzle-orm";
|
||||
import { users, type Db } from "@peppa/db";
|
||||
@ -53,7 +54,7 @@ export interface EgovStart {
|
||||
|
||||
/** Starts a signing session in the relay for a login or for linking `userId`'s IIN. */
|
||||
export async function startEgovFlow(db: Db, purpose: EgovPurpose, userId: number | null = null): Promise<EgovStart> {
|
||||
if (purpose === "link" && !userId) throw new PeppaError("Привязать eGov можно только после входа");
|
||||
if (purpose === "link" && !userId) throw new PeppaError(tr("Привязать eGov можно только после входа"));
|
||||
const env = loadEnv();
|
||||
const nonce = randomUUID();
|
||||
const challenge = randomBytes(32).toString("base64url");
|
||||
@ -110,7 +111,7 @@ export type EgovResult =
|
||||
*/
|
||||
export async function completeEgovFlow(db: Db, handle: string): Promise<EgovResult> {
|
||||
const flow = await loadFlow(db, handle);
|
||||
if (!flow) throw new PeppaError("QR-код истёк — начните заново");
|
||||
if (!flow) throw new PeppaError(tr("QR-код истёк — начните заново"));
|
||||
await deleteSetting(db, flowKey(handle));
|
||||
const s = await relay<{ status: EgovStatus; signedDocuments?: SignedDocument[] }>(`/egov/${encodeURIComponent(flow.relaySessionId)}/status`);
|
||||
if (s.status !== "completed") throw new PeppaError(s.status === "rejected" ? "Подписание отменено" : "Документ ещё не подписан");
|
||||
@ -152,7 +153,7 @@ export async function registerEgovUser(db: Db, identity: EgovIdentity): Promise<
|
||||
if (same) return same;
|
||||
}
|
||||
}
|
||||
throw new PeppaError("Не удалось создать пользователя");
|
||||
throw new PeppaError(tr("Не удалось создать пользователя"));
|
||||
}
|
||||
|
||||
const TRANSLIT: Record<string, string> = {
|
||||
@ -185,13 +186,13 @@ function displayName(name: string | null): string | null {
|
||||
function verifySigned(docs: SignedDocument[], flow: Flow): EgovIdentity {
|
||||
const xml = docs[0]?.documentXml ?? "";
|
||||
if (!xml.includes(`<challenge>${flow.challenge}</challenge>`) || !xml.includes(`<nonce>${flow.nonce}</nonce>`)) {
|
||||
throw new PeppaError("Подписан не тот документ — начните заново");
|
||||
throw new PeppaError(tr("Подписан не тот документ — начните заново"));
|
||||
}
|
||||
const cert = /<(?:\w+:)?X509Certificate>\s*([A-Za-z0-9+/=\s]+?)\s*<\/(?:\w+:)?X509Certificate>/.exec(xml)?.[1];
|
||||
if (!cert) throw new PeppaError("В подписи нет сертификата");
|
||||
if (!cert) throw new PeppaError(tr("В подписи нет сертификата"));
|
||||
const subject = certificateSubject(Buffer.from(cert.replace(/\s+/g, ""), "base64"));
|
||||
const iin = /^IIN(\d{12})$/.exec(subject.serialNumber ?? "")?.[1];
|
||||
if (!iin || !isValidIin(iin)) throw new PeppaError("В сертификате нет ИИН");
|
||||
if (!iin || !isValidIin(iin)) throw new PeppaError(tr("В сертификате нет ИИН"));
|
||||
const name = subject.commonName ?? ([subject.surname, subject.givenName].filter(Boolean).join(" ") || null);
|
||||
return { iin, name };
|
||||
}
|
||||
@ -261,14 +262,14 @@ export function isValidIin(iin: string): boolean {
|
||||
|
||||
/** Links an IIN to an account (or unlinks with null). One account per IIN. */
|
||||
export async function linkEgovIin(db: Db, userId: number, iin: string | null): Promise<User> {
|
||||
if (iin !== null && !isValidIin(iin)) throw new PeppaError("Неверный ИИН");
|
||||
if (iin !== null && !isValidIin(iin)) throw new PeppaError(tr("Неверный ИИН"));
|
||||
if (iin) {
|
||||
const [other] = await db.select().from(users).where(eq(users.egovIin, iin));
|
||||
if (other && other.id !== userId) throw new PeppaError("Этот ИИН уже привязан к другой учётке");
|
||||
if (other && other.id !== userId) throw new PeppaError(tr("Этот ИИН уже привязан к другой учётке"));
|
||||
}
|
||||
await db.update(users).set({ egovIin: iin, egovLinkedAt: iin ? new Date() : null }).where(eq(users.id, userId));
|
||||
const user = await getUser(db, userId);
|
||||
if (!user) throw new PeppaError("Пользователь не найден");
|
||||
if (!user) throw new PeppaError(tr("Пользователь не найден"));
|
||||
return user;
|
||||
}
|
||||
|
||||
|
||||
@ -3,6 +3,7 @@
|
||||
// accounts are never merged by e-mail. State lives in `settings` (one-shot, 10 min) and in an
|
||||
// httpOnly cookie of the starting browser, so a forged or replayed callback is refused before
|
||||
// Google is contacted. Tokens are not stored.
|
||||
import { m as tr } from "@peppa/shared/i18n";
|
||||
import { createHash, randomBytes, randomInt } from "node:crypto";
|
||||
import { eq, sql } from "drizzle-orm";
|
||||
import { users, type Db } from "@peppa/db";
|
||||
@ -59,8 +60,8 @@ export interface GoogleStart {
|
||||
|
||||
export async function startGoogleFlow(db: Db, purpose: GooglePurpose, redirectUri: string, userId: number | null = null): Promise<GoogleStart> {
|
||||
const env = loadEnv();
|
||||
if (!googleEnabled(env)) throw new PeppaError("Вход через Google не настроен");
|
||||
if (purpose === "link" && !userId) throw new PeppaError("Привязать Google можно только после входа");
|
||||
if (!googleEnabled(env)) throw new PeppaError(tr("Вход через Google не настроен"));
|
||||
if (purpose === "link" && !userId) throw new PeppaError(tr("Привязать Google можно только после входа"));
|
||||
const state = randomBytes(24).toString("base64url");
|
||||
const verifier = randomBytes(32).toString("base64url");
|
||||
await setSetting(db, flowKey(state), { purpose, userId, verifier, redirectUri, expiresAt: Date.now() + GOOGLE_FLOW_TTL_MS } satisfies Flow);
|
||||
@ -90,10 +91,10 @@ async function post<T>(url: string, body: URLSearchParams): Promise<T> {
|
||||
*/
|
||||
export async function completeGoogleFlow(db: Db, input: { state: string; code: string; cookieState: string }): Promise<GoogleResult> {
|
||||
const { state, code, cookieState } = input;
|
||||
if (!state || !code || state !== cookieState) throw new PeppaError("Вход не удался — начните заново");
|
||||
if (!state || !code || state !== cookieState) throw new PeppaError(tr("Вход не удался — начните заново"));
|
||||
const flow = await getSetting<Flow>(db, flowKey(state));
|
||||
await deleteSetting(db, flowKey(state));
|
||||
if (!flow || Date.now() >= flow.expiresAt) throw new PeppaError("Вход устарел — начните заново");
|
||||
if (!flow || Date.now() >= flow.expiresAt) throw new PeppaError(tr("Вход устарел — начните заново"));
|
||||
const env = loadEnv();
|
||||
const ep = endpoints();
|
||||
const tok = await post<{ access_token?: string }>(
|
||||
@ -107,11 +108,11 @@ export async function completeGoogleFlow(db: Db, input: { state: string; code: s
|
||||
code_verifier: flow.verifier,
|
||||
}),
|
||||
);
|
||||
if (!tok.access_token) throw new PeppaError("Google не выдал токен");
|
||||
if (!tok.access_token) throw new PeppaError(tr("Google не выдал токен"));
|
||||
const res = await fetch(ep.userinfo, { headers: { Authorization: `Bearer ${tok.access_token}` }, signal: AbortSignal.timeout(15_000) });
|
||||
const p = (await res.json().catch(() => ({}))) as { sub?: string; email?: string; email_verified?: boolean; name?: string };
|
||||
if (!res.ok || !p.sub || !p.email) throw new PeppaError("Google не вернул профиль");
|
||||
if (p.email_verified !== true) throw new PeppaError("Почта в Google не подтверждена");
|
||||
if (!res.ok || !p.sub || !p.email) throw new PeppaError(tr("Google не вернул профиль"));
|
||||
if (p.email_verified !== true) throw new PeppaError(tr("Почта в Google не подтверждена"));
|
||||
const identity: GoogleIdentity = { sub: p.sub, email: p.email.toLowerCase(), name: p.name?.trim() || null };
|
||||
|
||||
if (flow.purpose === "link") {
|
||||
@ -150,24 +151,24 @@ export async function registerGoogleUser(db: Db, identity: GoogleIdentity): Prom
|
||||
if (same) return same;
|
||||
}
|
||||
}
|
||||
throw new PeppaError("Не удалось создать пользователя");
|
||||
throw new PeppaError(tr("Не удалось создать пользователя"));
|
||||
}
|
||||
|
||||
/** Links a Google account to `userId`. One Google account — one Peppa account. */
|
||||
export async function linkGoogle(db: Db, userId: number, identity: GoogleIdentity): Promise<User> {
|
||||
const [other] = await db.select().from(users).where(eq(users.googleSub, identity.sub));
|
||||
if (other && other.id !== userId) throw new PeppaError("Этот Google-аккаунт уже привязан к другой учётке");
|
||||
if (other && other.id !== userId) throw new PeppaError(tr("Этот Google-аккаунт уже привязан к другой учётке"));
|
||||
await db.update(users).set({ googleSub: identity.sub, googleEmail: identity.email, googleLinkedAt: new Date() }).where(eq(users.id, userId));
|
||||
const user = await getUser(db, userId);
|
||||
if (!user) throw new PeppaError("Пользователь не найден");
|
||||
if (!user) throw new PeppaError(tr("Пользователь не найден"));
|
||||
return user;
|
||||
}
|
||||
|
||||
/** Unlinks Google, unless it is the account's only way in. */
|
||||
export async function unlinkGoogle(db: Db, userId: number): Promise<User> {
|
||||
const user = await getUser(db, userId);
|
||||
if (!user) throw new PeppaError("Пользователь не найден");
|
||||
if (!user.egovIin && !user.passwordHash) throw new PeppaError("Это единственный способ входа — сначала привяжите eGov");
|
||||
if (!user) throw new PeppaError(tr("Пользователь не найден"));
|
||||
if (!user.egovIin && !user.passwordHash) throw new PeppaError(tr("Это единственный способ входа — сначала привяжите eGov"));
|
||||
await db.update(users).set({ googleSub: null, googleEmail: null, googleLinkedAt: null }).where(eq(users.id, userId));
|
||||
return (await getUser(db, userId))!;
|
||||
}
|
||||
|
||||
@ -1,4 +1,5 @@
|
||||
// PEP-40: servers runners run on (SSH, no daemon). Reaching them — runner/exec.ts, checks — runner/hosts.ts.
|
||||
import { m as tr } from "@peppa/shared/i18n";
|
||||
import { runnerHosts, sessions, type Db, type RunnerHostInfo } from "@peppa/db";
|
||||
import { and, asc, eq, inArray, isNull, notInArray, sql } from "drizzle-orm";
|
||||
import { PeppaError } from "./errors.ts";
|
||||
@ -24,16 +25,16 @@ export interface HostInput {
|
||||
}
|
||||
|
||||
function check(h: Partial<HostInput>) {
|
||||
if (h.name !== undefined && !NAME_RE.test(h.name)) throw new PeppaError("Имя хоста — латиница, цифры, «.-_», до 40 символов");
|
||||
if (h.sshTarget !== undefined && !TARGET_RE.test(h.sshTarget)) throw new PeppaError("SSH-адрес — user@host или host");
|
||||
if (h.sshPort !== undefined && !(Number.isInteger(h.sshPort) && h.sshPort > 0 && h.sshPort < 65536)) throw new PeppaError("Порт SSH — от 1 до 65535");
|
||||
if (h.workdir !== undefined && (!WORKDIR_RE.test(h.workdir) || h.workdir.split("/").includes(".."))) throw new PeppaError("Каталог на хосте — путь без пробелов и «..»");
|
||||
if (h.name !== undefined && !NAME_RE.test(h.name)) throw new PeppaError(tr("Имя хоста — латиница, цифры, «.-_», до 40 символов"));
|
||||
if (h.sshTarget !== undefined && !TARGET_RE.test(h.sshTarget)) throw new PeppaError(tr("SSH-адрес — user@host или host"));
|
||||
if (h.sshPort !== undefined && !(Number.isInteger(h.sshPort) && h.sshPort > 0 && h.sshPort < 65536)) throw new PeppaError(tr("Порт SSH — от 1 до 65535"));
|
||||
if (h.workdir !== undefined && (!WORKDIR_RE.test(h.workdir) || h.workdir.split("/").includes(".."))) throw new PeppaError(tr("Каталог на хосте — путь без пробелов и «..»"));
|
||||
if (h.peppaUrl) {
|
||||
try {
|
||||
const u = new URL(h.peppaUrl);
|
||||
if (u.protocol !== "http:" && u.protocol !== "https:") throw new Error();
|
||||
} catch {
|
||||
throw new PeppaError("Адрес Пеппы — http(s)://…");
|
||||
throw new PeppaError(tr("Адрес Пеппы — http(s)://…"));
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -42,7 +43,7 @@ export async function createHost(db: Db, h: HostInput): Promise<RunnerHost> {
|
||||
const v = { ...h, name: h.name.trim(), sshTarget: h.sshTarget.trim(), workdir: h.workdir?.trim() || undefined, peppaUrl: h.peppaUrl?.trim() || null };
|
||||
check(v);
|
||||
const [dup] = await db.select({ id: runnerHosts.id }).from(runnerHosts).where(eq(runnerHosts.name, v.name));
|
||||
if (dup) throw new PeppaError(`Хост «${v.name}» уже есть`);
|
||||
if (dup) throw new PeppaError(tr("Хост «{name}» уже есть", { name: v.name }));
|
||||
const [row] = await db.insert(runnerHosts).values(v).returning();
|
||||
return row!;
|
||||
}
|
||||
@ -56,7 +57,7 @@ export async function updateHost(db: Db, id: number, patch: Partial<HostInput>):
|
||||
|
||||
export async function getHost(db: Db, id: number): Promise<RunnerHost> {
|
||||
const [row] = await db.select().from(runnerHosts).where(eq(runnerHosts.id, id));
|
||||
if (!row) throw new PeppaError(`Хост #${id} не найден`);
|
||||
if (!row) throw new PeppaError(tr("Хост #{id} не найден", { id }));
|
||||
return row;
|
||||
}
|
||||
|
||||
@ -64,7 +65,7 @@ export async function getHost(db: Db, id: number): Promise<RunnerHost> {
|
||||
export async function findHost(db: Db, ref: string | number): Promise<RunnerHost> {
|
||||
if (typeof ref === "number" || /^\d+$/.test(ref)) return getHost(db, Number(ref));
|
||||
const [row] = await db.select().from(runnerHosts).where(eq(runnerHosts.name, ref));
|
||||
if (!row) throw new PeppaError(`Хост «${ref}» не найден`);
|
||||
if (!row) throw new PeppaError(tr("Хост «{ref}» не найден", { ref }));
|
||||
return row;
|
||||
}
|
||||
|
||||
@ -91,7 +92,7 @@ export async function deleteHost(db: Db, id: number): Promise<void> {
|
||||
.select({ n: sql<number>`count(*)` })
|
||||
.from(sessions)
|
||||
.where(and(eq(sessions.hostId, id), notInArray(sessions.status, FINISHED_SESSION_STATUSES)));
|
||||
if (Number(live?.n ?? 0) > 0) throw new PeppaError("На хосте работают раннеры — остановите их или отключите хост");
|
||||
if (Number(live?.n ?? 0) > 0) throw new PeppaError(tr("На хосте работают раннеры — остановите их или отключите хост"));
|
||||
await db.delete(runnerHosts).where(eq(runnerHosts.id, id));
|
||||
}
|
||||
|
||||
@ -112,4 +113,4 @@ export async function pickHost(db: Db, ids: number[]): Promise<RunnerHostView |
|
||||
return hosts[0] ?? null;
|
||||
}
|
||||
|
||||
export const HOST_STATUS_RU: Record<RunnerHost["status"], string> = { unknown: "не проверен", online: "онлайн", offline: "офлайн" };
|
||||
export const HOST_STATUS_RU: Record<RunnerHost["status"], string> = { unknown: tr("не проверен"), online: tr("онлайн"), offline: tr("офлайн") };
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
// Incidents (PEP-58): Bugsink issues seen in Peppa, the project's incident policy settings,
|
||||
// bug tasks made from incidents and their Telegram messages. The policy itself (which may
|
||||
// start a runner) is applied in runner/incidents.ts.
|
||||
import { m as tr } from "@peppa/shared/i18n";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import type { BugsinkIssue } from "@peppa/bugsink";
|
||||
import { errorSources, incidentPolicies, incidents, incidentSettings, incidentStatuses, projects, telegramOutbox, type Db, type IncidentPolicy } from "@peppa/db";
|
||||
@ -21,21 +22,21 @@ export type IncidentAction = "notify" | "backlog" | "start" | "ignore";
|
||||
export { incidentPolicies, incidentStatuses, type IncidentPolicy };
|
||||
|
||||
export const INCIDENT_STATUS_RU: Record<IncidentStatus, string> = {
|
||||
new: "новая",
|
||||
open: "без стори",
|
||||
pending: "ждёт разбора",
|
||||
task: "стори",
|
||||
ignored: "игнорируется",
|
||||
resolved: "исправлена",
|
||||
regressed: "вернулась",
|
||||
new: tr("новая"),
|
||||
open: tr("без стори"),
|
||||
pending: tr("ждёт разбора"),
|
||||
task: tr("стори"),
|
||||
ignored: tr("игнорируется"),
|
||||
resolved: tr("исправлена"),
|
||||
regressed: tr("вернулась"),
|
||||
};
|
||||
|
||||
export const POLICY_RU: Record<IncidentPolicy, string> = {
|
||||
notify: "только уведомить",
|
||||
backlog: "стори в бэклог",
|
||||
start: "стори сразу в работу",
|
||||
ask: "спросить в Telegram",
|
||||
triage: "решает агент-триажёр",
|
||||
notify: tr("только уведомить"),
|
||||
backlog: tr("стори в бэклог"),
|
||||
start: tr("стори сразу в работу"),
|
||||
ask: tr("спросить в Telegram"),
|
||||
triage: tr("решает агент-триажёр"),
|
||||
};
|
||||
|
||||
export const STABILITY_GOAL = "Стабильность";
|
||||
@ -75,16 +76,16 @@ export interface IncidentSettingsPatch {
|
||||
}
|
||||
|
||||
export async function updateIncidentSettings(db: Db, projectId: number, patch: IncidentSettingsPatch): Promise<IncidentSettings> {
|
||||
if (!(await getIncidentSettings(db, projectId))) throw new PeppaError("Отслеживание ошибок в проекте не подключено");
|
||||
if (patch.policy && !incidentPolicies.includes(patch.policy)) throw new PeppaError(`Неизвестная политика «${patch.policy}»: ${incidentPolicies.join(", ")}`);
|
||||
if (!(await getIncidentSettings(db, projectId))) throw new PeppaError(tr("Отслеживание ошибок в проекте не подключено"));
|
||||
if (patch.policy && !incidentPolicies.includes(patch.policy)) throw new PeppaError(tr("Неизвестная политика «{policy}»: {list}", { policy: patch.policy, list: incidentPolicies.join(", ") }));
|
||||
if (patch.ignorePattern) {
|
||||
try {
|
||||
new RegExp(patch.ignorePattern, "i");
|
||||
} catch {
|
||||
throw new PeppaError("Шаблон игнора — неверное регулярное выражение");
|
||||
throw new PeppaError(tr("Шаблон игнора — неверное регулярное выражение"));
|
||||
}
|
||||
}
|
||||
if (patch.dailyLimit != null && (!Number.isInteger(patch.dailyLimit) || patch.dailyLimit < 0)) throw new PeppaError("Предел в сутки — целое число ≥ 0");
|
||||
if (patch.dailyLimit != null && (!Number.isInteger(patch.dailyLimit) || patch.dailyLimit < 0)) throw new PeppaError(tr("Предел в сутки — целое число ≥ 0"));
|
||||
if (patch.environments) patch.environments = [...new Set(patch.environments.map((e) => e.trim()).filter(Boolean))];
|
||||
const [row] = await db.update(incidentSettings).set(patch).where(eq(incidentSettings.projectId, projectId)).returning();
|
||||
return row!;
|
||||
@ -178,7 +179,7 @@ export async function ingestIssue(db: Db, i: BugsinkIssue): Promise<IngestResult
|
||||
|
||||
export async function getIncident(db: Db, id: number): Promise<Incident> {
|
||||
const [row] = await db.select().from(incidents).where(eq(incidents.id, id));
|
||||
if (!row) throw new PeppaError(`Инцидент #${id} не найден`);
|
||||
if (!row) throw new PeppaError(tr("Инцидент #{id} не найден", { id }));
|
||||
return row;
|
||||
}
|
||||
|
||||
@ -198,7 +199,7 @@ export async function listIncidents(db: Db, projectId: number, statuses?: Incide
|
||||
|
||||
export async function updateIncident(db: Db, id: number, patch: Partial<Omit<Incident, "id" | "projectId" | "bugsinkIssueId">>): Promise<Incident> {
|
||||
const [row] = await db.update(incidents).set(patch).where(eq(incidents.id, id)).returning();
|
||||
if (!row) throw new PeppaError(`Инцидент #${id} не найден`);
|
||||
if (!row) throw new PeppaError(tr("Инцидент #{id} не найден", { id }));
|
||||
await notify(db, { type: "incident", incidentId: id });
|
||||
return row;
|
||||
}
|
||||
@ -284,32 +285,33 @@ export type IncidentMessage =
|
||||
export function incidentButtons(id: number) {
|
||||
return [
|
||||
[
|
||||
{ text: "📥 В бэклог", callback_data: `i:${id}:backlog` },
|
||||
{ text: "▶️ В работу", callback_data: `i:${id}:start` },
|
||||
{ text: tr("📥 В бэклог"), callback_data: `i:${id}:backlog` },
|
||||
{ text: tr("▶️ В работу"), callback_data: `i:${id}:start` },
|
||||
],
|
||||
[{ text: "🙈 Игнорировать", callback_data: `i:${id}:ignore` }],
|
||||
[{ text: tr("🙈 Игнорировать"), callback_data: `i:${id}:ignore` }],
|
||||
];
|
||||
}
|
||||
|
||||
export function renderIncidentMessage(project: Pick<Project, "key" | "name">, i: Incident, m: IncidentMessage, webUrl: string): string {
|
||||
const head = m.kind === "regressed" ? "🔁 Ошибка вернулась" : "🐞 Новая ошибка";
|
||||
const where = { source: i.source, env: esc(i.environment ?? "—") };
|
||||
const head = m.kind === "regressed" ? `🔁 ${tr("Ошибка вернулась ({source}, {env})", where)}` : `🐞 ${tr("Новая ошибка ({source}, {env})", where)}`;
|
||||
const lines = [
|
||||
`<b>${esc(project.key)}</b> · ${head} (${i.source}, ${esc(i.environment ?? "—")})`,
|
||||
`<b>${esc(project.key)}</b> · ${head}`,
|
||||
`<b>${esc(clip(i.title, 300))}</b>`,
|
||||
[i.culprit && `📍 ${esc(i.culprit)}`, i.lastRelease && `релиз ${esc(i.lastRelease)}`, `событий: ${i.events}`].filter(Boolean).join(" · "),
|
||||
[i.culprit && `📍 ${esc(i.culprit)}`, i.lastRelease && tr("релиз {release}", { release: esc(i.lastRelease) }), tr("событий: {n}", { n: i.events })].filter(Boolean).join(" · "),
|
||||
];
|
||||
if (i.url) lines.push(`<a href="${esc(i.url)}">Открыть в Bugsink</a>`);
|
||||
if (i.url) lines.push(`<a href="${esc(i.url)}">${tr("Открыть в Bugsink")}</a>`);
|
||||
const taskLink = (t: TaskRef) => `<a href="${esc(`${webUrl}/t/${t.key}`)}">${esc(t.key)}</a>`;
|
||||
if (m.kind === "task") {
|
||||
lines.push("", m.started ? `▶️ Агент взялся: ${taskLink(m.task)}` : `📥 Стори в бэклоге: ${taskLink(m.task)}`);
|
||||
if (m.reason) lines.push(`🤖 Триажёр: ${esc(clip(m.reason, 500))}`);
|
||||
lines.push("", m.started ? tr("▶️ Агент взялся: {link}", { link: taskLink(m.task) }) : tr("📥 Стори в бэклоге: {link}", { link: taskLink(m.task) }));
|
||||
if (m.reason) lines.push(tr("🤖 Триажёр: {reason}", { reason: esc(clip(m.reason, 500)) }));
|
||||
} else if (m.kind === "ask") {
|
||||
if (m.note) lines.push("", `<i>${esc(clip(m.note, 500))}</i>`);
|
||||
lines.push("", "Что делаем?");
|
||||
lines.push("", tr("Что делаем?"));
|
||||
} else if (m.kind === "regressed") {
|
||||
lines.push("", m.task ? `Стори ${taskLink(m.task)} снова в бэклоге.` : "Стори нет — реши, что делать.");
|
||||
lines.push("", m.task ? tr("Стори {link} снова в бэклоге.", { link: taskLink(m.task) }) : tr("Стори нет — реши, что делать."));
|
||||
} else {
|
||||
lines.push("", `<a href="${esc(`${webUrl}/p/${project.key}`)}">Ошибки проекта</a>`);
|
||||
lines.push("", `<a href="${esc(`${webUrl}/p/${project.key}`)}">${tr("Ошибки проекта")}</a>`);
|
||||
}
|
||||
return lines.join("\n");
|
||||
}
|
||||
@ -333,7 +335,7 @@ export async function sendIncidentMessage(db: Db, i: Incident, m: IncidentMessag
|
||||
pushKey: `inc:${i.id}:${kind}:r${i.regressions}:u${u.id}`,
|
||||
telegram: { params: { text, parse_mode: "HTML", link_preview_options: { is_disabled: true }, ...(markup ? { reply_markup: markup } : {}) } },
|
||||
push: {
|
||||
title: `${m.kind === "regressed" ? "Ошибка вернулась" : "Ошибка"} в ${project.name}`,
|
||||
title: m.kind === "regressed" ? tr("Ошибка вернулась в {project}", { project: project.name }) : tr("Ошибка в {project}", { project: project.name }),
|
||||
body: clip(i.title, 200),
|
||||
url: taskKey ? `/t/${taskKey}` : `/p/${project.key}`,
|
||||
tag: `inc:${i.id}`,
|
||||
|
||||
@ -4,6 +4,7 @@
|
||||
// questions, each with the default it will take if nobody answers. They do not flatter, see the
|
||||
// project's context, and never wait for permission: no answer in time — they go by the defaults.
|
||||
// State lives in `settings` (`intake.task:<taskId>`, `project.intake:<projectId>`): no schema change.
|
||||
import { m as tr } from "@peppa/shared/i18n";
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { events, goals, tasks, type Db } from "@peppa/db";
|
||||
@ -17,7 +18,7 @@ import { getSetting, setSetting } from "./settings.ts";
|
||||
import type { Task } from "./tasks.ts";
|
||||
|
||||
export type IntakeRole = "product" | "analyst";
|
||||
export const INTAKE_ROLE_RU: Record<IntakeRole, string> = { product: "Продакт", analyst: "Аналитик" };
|
||||
export const INTAKE_ROLE_RU: Record<IntakeRole, string> = { product: tr("Продакт"), analyst: tr("Аналитик") };
|
||||
export const INTAKE_EVENT = "intake_note";
|
||||
export const INTAKE_MAX_QUESTIONS = 3;
|
||||
export const INTAKE_MAX_SPLIT = 4;
|
||||
@ -276,23 +277,23 @@ export function intakeDescription(original: { title: string; description: string
|
||||
|
||||
/** What the PM reads from the roles. */
|
||||
export function productMessage(p: ProductNote, splitKeys: string[]): string {
|
||||
return [`Цель: ${p.goal}`, p.comment, ...(splitKeys.length ? [`Разделил на стори: эта и ${splitKeys.join(", ")}.`] : [])].filter(Boolean).join("\n\n");
|
||||
return [tr("Цель: {goal}", { goal: p.goal }), p.comment, ...(splitKeys.length ? [tr("Разделил на стори: эта и {list}.", { list: splitKeys.join(", ") })] : [])].filter(Boolean).join("\n\n");
|
||||
}
|
||||
export function analystMessage(a: AnalystNote): string {
|
||||
const bullets = (items: string[]) => items.map((x) => `• ${x}`).join("\n");
|
||||
return [
|
||||
a.comment,
|
||||
`Критерии приёмки:\n${bullets(a.criteria)}`,
|
||||
...(a.assumptions.length ? [`Решил сам:\n${bullets(a.assumptions)}`] : []),
|
||||
...(a.questions.length ? ["Есть вопросы — отдельным сообщением. Не ответите — сделаю по вариантам по умолчанию."] : ["Вопросов нет — стори готова к работе."]),
|
||||
`${tr("Критерии приёмки:")}\n${bullets(a.criteria)}`,
|
||||
...(a.assumptions.length ? [`${tr("Решил сам:")}\n${bullets(a.assumptions)}`] : []),
|
||||
...(a.questions.length ? [tr("Есть вопросы — отдельным сообщением. Не ответите — сделаю по вариантам по умолчанию.")] : [tr("Вопросов нет — стори готова к работе.")]),
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join("\n\n");
|
||||
}
|
||||
export function questionsText(key: string, qs: IntakeQuestion[], waitMin: number): string {
|
||||
return [
|
||||
`Аналитик уточняет ${key}. Ответьте одним сообщением — или не отвечайте: через ${waitMin} мин возьму варианты по умолчанию.`,
|
||||
...qs.map((q, i) => `${i + 1}. ${q.q}\n По умолчанию: ${q.default}`),
|
||||
tr("Аналитик уточняет {key}. Ответьте одним сообщением — или не отвечайте: через {n} мин возьму варианты по умолчанию.", { key, n: waitMin }),
|
||||
...qs.map((q, i) => `${i + 1}. ${q.q}\n ${tr("По умолчанию: {default}", { default: q.default })}`),
|
||||
].join("\n\n");
|
||||
}
|
||||
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
// Local Peppa users without a Gitea account (PEP-68): password login with attempt limits,
|
||||
// created, reset and disabled by a superadmin (web «Пользователи») or the machine CLI.
|
||||
import { m as tr } from "@peppa/shared/i18n";
|
||||
import { users, type Db } from "@peppa/db";
|
||||
import { eq, sql } from "drizzle-orm";
|
||||
import { randomBytes, randomInt, scrypt, timingSafeEqual } from "node:crypto";
|
||||
@ -7,8 +8,8 @@ import { PeppaError } from "./errors.ts";
|
||||
import { deleteSetting, getSetting, setSetting } from "./settings.ts";
|
||||
import type { User } from "./users.ts";
|
||||
|
||||
export const BAD_CREDENTIALS = "Неверный логин или пароль";
|
||||
export const TOO_MANY_ATTEMPTS = "Слишком много попыток входа — попробуйте через 15 минут";
|
||||
export const BAD_CREDENTIALS = tr("Неверный логин или пароль");
|
||||
export const TOO_MANY_ATTEMPTS = tr("Слишком много попыток входа — попробуйте через 15 минут");
|
||||
export const MIN_PASSWORD = 8;
|
||||
|
||||
// ── hashing ──────────────────────────────────────────────────────────────────────────
|
||||
@ -44,8 +45,8 @@ export async function verifyPassword(password: string, stored: string | null | u
|
||||
const DUMMY_HASH = `scrypt$${N}$${R}$${P}$${Buffer.alloc(16).toString("base64")}$${Buffer.alloc(KEYLEN).toString("base64")}`;
|
||||
|
||||
export function checkPasswordPolicy(password: string): void {
|
||||
if (password.length < MIN_PASSWORD) throw new PeppaError(`Пароль — не короче ${MIN_PASSWORD} символов`);
|
||||
if (password.length > 256) throw new PeppaError("Слишком длинный пароль");
|
||||
if (password.length < MIN_PASSWORD) throw new PeppaError(tr("Пароль — не короче {n} символов", { n: MIN_PASSWORD }));
|
||||
if (password.length > 256) throw new PeppaError(tr("Слишком длинный пароль"));
|
||||
}
|
||||
|
||||
/** A random temporary password (CLI), 16 characters without look-alikes. */
|
||||
@ -121,9 +122,9 @@ const LOGIN_RE = /^[a-z0-9][a-z0-9._-]{1,38}$/;
|
||||
/** A local user (negative gitea_id: can never come from Gitea OAuth). */
|
||||
export async function createLocalUser(db: Db, o: { login: string; name?: string | null; password: string }): Promise<User> {
|
||||
const login = o.login.trim().toLowerCase();
|
||||
if (!LOGIN_RE.test(login)) throw new PeppaError("Логин: 2–39 символов a–z, 0–9, точка, дефис, подчёркивание; начинается с буквы или цифры");
|
||||
if (!LOGIN_RE.test(login)) throw new PeppaError(tr("Логин: 2–39 символов a–z, 0–9, точка, дефис, подчёркивание; начинается с буквы или цифры"));
|
||||
checkPasswordPolicy(o.password);
|
||||
if (await userByLoginCi(db, login)) throw new PeppaError(`Логин «${login}» уже занят`);
|
||||
if (await userByLoginCi(db, login)) throw new PeppaError(tr("Логин «{login}» уже занят", { login }));
|
||||
const passwordHash = await hashPassword(o.password);
|
||||
for (let i = 0; i < 5; i++) {
|
||||
const giteaId = -1 - randomInt(2 ** 47);
|
||||
@ -134,7 +135,7 @@ export async function createLocalUser(db: Db, o: { login: string; name?: string
|
||||
.returning();
|
||||
if (row) return row;
|
||||
}
|
||||
throw new PeppaError("Не удалось создать пользователя");
|
||||
throw new PeppaError(tr("Не удалось создать пользователя"));
|
||||
}
|
||||
|
||||
/** Sets a password (superadmin reset / CLI). */
|
||||
@ -145,7 +146,7 @@ export async function setUserPassword(db: Db, userId: number, password: string):
|
||||
|
||||
/** The user changes their own password: the current one must match. */
|
||||
export async function changeOwnPassword(db: Db, user: User, current: string, next: string): Promise<void> {
|
||||
if (!(await verifyPassword(current, user.passwordHash))) throw new PeppaError("Текущий пароль неверный");
|
||||
if (!(await verifyPassword(current, user.passwordHash))) throw new PeppaError(tr("Текущий пароль неверный"));
|
||||
await setUserPassword(db, user.id, next);
|
||||
}
|
||||
|
||||
|
||||
@ -1,4 +1,5 @@
|
||||
// PEP-30: project memory — `.peppa/memory.md` in the project repo, written by agents.
|
||||
import { m as tr } from "@peppa/shared/i18n";
|
||||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
import { projects, tasks, type Db } from "@peppa/db";
|
||||
@ -49,7 +50,7 @@ const SECTION_ALIASES: Record<string, MemorySection> = {
|
||||
};
|
||||
export function parseSection(s: string | undefined): MemorySection {
|
||||
const v = SECTION_ALIASES[(s ?? "").trim().toLowerCase()];
|
||||
if (!v) throw new PeppaError(`Раздел памяти: ${MEMORY_SECTIONS.join(", ")}`);
|
||||
if (!v) throw new PeppaError(tr("Раздел памяти: {v}", { v: MEMORY_SECTIONS.join(", ") }));
|
||||
return v;
|
||||
}
|
||||
|
||||
@ -69,8 +70,8 @@ function tooBig(chars: number): PeppaError {
|
||||
export function rememberFact(dir: string, sectionInput: string, fact: string): { result: "added" | "exists"; stats: MemoryStats } {
|
||||
const section = parseSection(sectionInput);
|
||||
const line = fact.replace(/\s+/g, " ").trim().replace(/^[-*]\s+/, "");
|
||||
if (!line) throw new PeppaError("Пустой пункт памяти");
|
||||
if (line.length > MAX_FACT) throw new PeppaError(`Пункт памяти длиннее ${MAX_FACT} символов — сформулируй короче`);
|
||||
if (!line) throw new PeppaError(tr("Пустой пункт памяти"));
|
||||
if (line.length > MAX_FACT) throw new PeppaError(tr("Пункт памяти длиннее {n} символов — сформулируй короче", { n: MAX_FACT }));
|
||||
const cur = readMemory(dir) || HEADER;
|
||||
const lines = cur.replace(/\n+$/, "").split("\n");
|
||||
const key = norm(line);
|
||||
@ -96,7 +97,7 @@ export function rememberFact(dir: string, sectionInput: string, fact: string): {
|
||||
/** Rewrites the whole memory (compaction); still within the limit. */
|
||||
export function replaceMemory(dir: string, text: string): MemoryStats {
|
||||
const body = text.trim();
|
||||
if (!body) throw new PeppaError("Пустая память — чтобы ужать, передай сокращённый текст");
|
||||
if (!body) throw new PeppaError(tr("Пустая память — чтобы ужать, передай сокращённый текст"));
|
||||
const next = `${body}\n`;
|
||||
if (next.length > memoryMaxChars()) throw tooBig(next.length);
|
||||
write(dir, next);
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
// Service monitoring (PEP-20): web, bot and watchdog write heartbeats into `settings`; the
|
||||
// watchdog and the bot check each other (and the web) and alert the platform admins in
|
||||
// Telegram through the outbox when a service goes quiet, without spamming.
|
||||
import { m as tr } from "@peppa/shared/i18n";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { hostname } from "node:os";
|
||||
@ -17,7 +18,7 @@ import type { User } from "./users.ts";
|
||||
export const SERVICES = ["web", "bot", "watchdog"] as const;
|
||||
export type Service = (typeof SERVICES)[number];
|
||||
|
||||
export const SERVICE_NAMES: Record<Service, string> = { web: "веб", bot: "бот", watchdog: "вачдог" };
|
||||
export const SERVICE_NAMES: Record<Service, string> = { web: tr("веб"), bot: tr("бот"), watchdog: tr("вачдог") };
|
||||
|
||||
export interface Heartbeat {
|
||||
at: string;
|
||||
@ -122,8 +123,8 @@ export const minutes = (ms: number) => Math.round(ms / MIN);
|
||||
|
||||
/** "ok" / "молчит 7 мин" / "нет данных". */
|
||||
export function describeState(s: ServiceState): string {
|
||||
if (s.ageMs == null) return "нет данных";
|
||||
return s.ok ? "ok" : `молчит ${minutes(s.ageMs)} мин`;
|
||||
if (s.ageMs == null) return tr("нет данных");
|
||||
return s.ok ? "ok" : tr("молчит {n} мин", { n: minutes(s.ageMs) });
|
||||
}
|
||||
|
||||
// ── admins ─────────────────────────────────────────────────────────────────────────
|
||||
@ -165,7 +166,7 @@ export async function alertAdmins(db: Db, key: string, text: string, log: (m: st
|
||||
dedupeKey: `${key}:${u.telegramChatId}`,
|
||||
pushKey: `${key}:u${u.id}`,
|
||||
telegram: { params: { text } },
|
||||
push: { title: "Мониторинг Пеппы", body: text, url: "/", tag: key.split(":").slice(0, 2).join(":") },
|
||||
push: { title: tr("Мониторинг Пеппы"), body: text, url: "/", tag: key.split(":").slice(0, 2).join(":") },
|
||||
urgency: "high",
|
||||
});
|
||||
if (r.telegram) queued++;
|
||||
@ -199,7 +200,7 @@ export async function checkServices(db: Db, o: MonitorOptions & { self: Service
|
||||
// PEP-60: a new process without an outage = a restart (an outage ends with «снова на связи»).
|
||||
if (restarted) {
|
||||
const build = `v${s.heartbeat.version}${s.heartbeat.commit ? ` · ${s.heartbeat.commit.slice(0, 7)}` : ""}`;
|
||||
await postToChannel(db, "services", `mon:ch:${s.service}:restart:${s.heartbeat.host}:${s.heartbeat.pid}`, `🔄 Пеппа: ${name} перезапущен (${build}).`, channel);
|
||||
await postToChannel(db, "services", `mon:ch:${s.service}:restart:${s.heartbeat.host}:${s.heartbeat.pid}`, tr("🔄 Пеппа: {name} перезапущен ({build}).", { name, build }), channel);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
@ -207,16 +208,16 @@ export async function checkServices(db: Db, o: MonitorOptions & { self: Service
|
||||
await setSetting(db, alertKey(s.service), { since: null, alerted: false, reminders: 0, lastAlertAt: st.lastAlertAt });
|
||||
const quiet = minutes(Date.parse(s.heartbeat.at) - Date.parse(st.since));
|
||||
if (st.alerted) {
|
||||
queued += await alertAdmins(db, `mon:${s.service}:up:${st.since}`, `✅ Пеппа: ${name} снова на связи (молчал ${quiet} мин).`, log);
|
||||
queued += await alertAdmins(db, `mon:${s.service}:up:${st.since}`, tr("✅ Пеппа: {name} снова на связи (молчал {n} мин).", { name, n: quiet }), log);
|
||||
}
|
||||
if (st.channelPosted && (await postToChannel(db, "services", `mon:ch:${s.service}:up:${st.since}`, `✅ Пеппа: ${name} снова работает — простой ${quiet} мин.`, channel))) queued++;
|
||||
if (st.channelPosted && (await postToChannel(db, "services", `mon:ch:${s.service}:up:${st.since}`, tr("✅ Пеппа: {name} снова работает — простой {n} мин.", { name, n: quiet }), channel))) queued++;
|
||||
continue;
|
||||
}
|
||||
// Down. A new outage starts when the last heartbeat differs from the remembered one.
|
||||
const cur: AlertState =
|
||||
st?.since === s.heartbeat.at ? st : { since: s.heartbeat.at, alerted: false, reminders: 0, lastAlertAt: st?.lastAlertAt ?? null };
|
||||
// PEP-60: the channel hears about an outage once (no reminders, no cooldown games).
|
||||
if (!cur.channelPosted && (await postToChannel(db, "services", `mon:ch:${s.service}:down:${cur.since}`, `⚠️ Пеппа: ${name} не отвечает с ${hhmm(s.heartbeat.at)}.`, channel))) {
|
||||
if (!cur.channelPosted && (await postToChannel(db, "services", `mon:ch:${s.service}:down:${cur.since}`, tr("⚠️ Пеппа: {name} не отвечает с {time}.", { name, time: hhmm(s.heartbeat.at) }), channel))) {
|
||||
cur.channelPosted = true;
|
||||
queued++;
|
||||
if (cur === st) await setSetting(db, alertKey(s.service), cur);
|
||||
@ -225,7 +226,7 @@ export async function checkServices(db: Db, o: MonitorOptions & { self: Service
|
||||
const due = cur.alerted ? sinceLast >= remindMs : sinceLast >= cooldownMs;
|
||||
if (due) {
|
||||
const n = cur.alerted ? cur.reminders + 1 : 0;
|
||||
const text = `⚠️ Пеппа: ${name} молчит ${minutes(s.ageMs!)} мин (последний heartbeat ${hhmm(s.heartbeat.at)}, pid ${s.heartbeat.pid}, ${s.heartbeat.host}).`;
|
||||
const text = tr("⚠️ Пеппа: {name} молчит {n} мин (последний heartbeat {time}, pid {pid}, {host}).", { name, n: minutes(s.ageMs!), time: hhmm(s.heartbeat.at), pid: s.heartbeat.pid, host: s.heartbeat.host });
|
||||
queued += await alertAdmins(db, `mon:${s.service}:down:${cur.since}:${n}`, text, log);
|
||||
Object.assign(cur, { alerted: true, reminders: n, lastAlertAt: now.toISOString() });
|
||||
}
|
||||
|
||||
@ -9,7 +9,13 @@ import type { User } from "./users.ts";
|
||||
import { enqueuePush, type PushPayload } from "./webpush.ts";
|
||||
import { addMasterMessage } from "./chats.ts";
|
||||
import { getUserLocale } from "./locale.ts";
|
||||
import { localizeText } from "@peppa/shared/i18n";
|
||||
import { localizeText, m as tr, type Locale } from "@peppa/shared/i18n";
|
||||
|
||||
|
||||
/** PEP-98: a rendered message (Telegram text, push body) in `locale` — see localizeText. */
|
||||
export function localizeMessage(locale: Locale, text: string): string {
|
||||
return localizeText(locale, text);
|
||||
}
|
||||
|
||||
/** Telegram HTML → plain text for the web chat. */
|
||||
export function htmlToText(html: string): string {
|
||||
@ -28,14 +34,14 @@ export const NOTIFY_EVENTS = ["questions", "review", "failures", "releases", "in
|
||||
export type NotifyEvent = (typeof NOTIFY_EVENTS)[number];
|
||||
|
||||
export const NOTIFY_EVENT_NAMES: Record<NotifyEvent, string> = {
|
||||
questions: "Вопросы агентов (одобрения, вопросы, разрешения)",
|
||||
review: "Готово к ревью",
|
||||
failures: "Сбои, зависания и лимиты раннеров",
|
||||
releases: "Релизы и выкаты",
|
||||
incidents: "Ошибки из прода",
|
||||
monitoring: "Мониторинг Пеппы (админам)",
|
||||
digest: "Ежедневный дайджест",
|
||||
platform: "Дайджест обновлений Пеппы",
|
||||
questions: tr("Вопросы агентов (одобрения, вопросы, разрешения)"),
|
||||
review: tr("Готово к ревью"),
|
||||
failures: tr("Сбои, зависания и лимиты раннеров"),
|
||||
releases: tr("Релизы и выкаты"),
|
||||
incidents: tr("Ошибки из прода"),
|
||||
monitoring: tr("Мониторинг Пеппы (админам)"),
|
||||
digest: tr("Ежедневный дайджест"),
|
||||
platform: tr("Дайджест обновлений Пеппы"),
|
||||
};
|
||||
|
||||
export interface Channels {
|
||||
@ -101,10 +107,10 @@ export async function getNotifyPrefs(db: Db, userId: number): Promise<NotifyPref
|
||||
}
|
||||
|
||||
export async function setNotifyPrefs(db: Db, userId: number, p: NotifyPrefs): Promise<NotifyPrefs> {
|
||||
if (p.quiet && (!HHMM.test(p.quiet.from) || !HHMM.test(p.quiet.to))) throw new Error("Тихие часы: время в формате ЧЧ:ММ");
|
||||
if (p.quiet && p.quiet.from === p.quiet.to) throw new Error("Тихие часы: начало и конец совпадают");
|
||||
if (!HHMM.test(p.digestTime)) throw new Error("Время дайджеста: формат ЧЧ:ММ");
|
||||
if (!isValidTimezone(p.timezone)) throw new Error(`Неизвестная таймзона: ${p.timezone}`);
|
||||
if (p.quiet && (!HHMM.test(p.quiet.from) || !HHMM.test(p.quiet.to))) throw new Error(tr("Тихие часы: время в формате ЧЧ:ММ"));
|
||||
if (p.quiet && p.quiet.from === p.quiet.to) throw new Error(tr("Тихие часы: начало и конец совпадают"));
|
||||
if (!HHMM.test(p.digestTime)) throw new Error(tr("Время дайджеста: формат ЧЧ:ММ"));
|
||||
if (!isValidTimezone(p.timezone)) throw new Error(tr("Неизвестная таймзона: {tz}", { tz: p.timezone }));
|
||||
await setSetting(db, prefsKey(userId), p);
|
||||
return getNotifyPrefs(db, userId);
|
||||
}
|
||||
@ -194,7 +200,7 @@ export async function deliverToUser(db: Db, user: User, d: Delivery, prefs?: Not
|
||||
if (ch.push && d.push && !quiet) {
|
||||
// PEP-98: push text in the user's language (Telegram is translated by the bot when sent).
|
||||
const locale = await getUserLocale(db, user.id);
|
||||
const push = locale === "ru" ? d.push : { ...d.push, title: localizeText(locale, d.push.title), body: localizeText(locale, d.push.body) };
|
||||
const push = locale === "ru" ? d.push : { ...d.push, title: localizeMessage(locale, d.push.title), body: localizeMessage(locale, d.push.body) };
|
||||
out.push = await enqueuePush(db, user.id, { dedupeKey: d.pushKey ?? d.dedupeKey, payload: { ...push, sound: d.push.sound ?? p.sound }, urgency: d.urgency });
|
||||
}
|
||||
return out;
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user