Merge main into task/pep-98: PEP-116/117 texts through the dictionary
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
ed62cdcd06
@ -39,9 +39,11 @@
|
||||
- **Группы чатов через свой бот (PEP-109)**: «Связать с Telegram» в чате — через собственного бота пользователя (PEP-85): `chats.tg_bot_user_id` (миграция 0018; null — общий бот, им связывает только суперадмин без своего бота: `createChatLinkCode(…, { sharedBot })`, остальным без бота — отказ с подсказкой). Код привязан к боту (`botUserId` в настройке кода): `acceptChatLink` принимает только от него и чужим ботом не сжигается; на `/link` без `@бота` с чужим кодом бот молчит (`chatLinkCodeBot`). Бот: `ownByChat` дополняется группами (`chatGroupBots` в `syncOwnBots`) — исходящие в группу идут через бота связки; входящие сообщения и кнопки группы обрабатывает только он (`linkedHere`). `clearUserBot` / `setUserBot` с другим ботом отвязывают его группы. Тест `chats-own-bot.test.ts`
|
||||
- **Обсуждение проекта (PEP-106)**: чат проекта открывается на «Обсуждении» — только сообщения людей в канале (`discussionMessages`: `thread_key` null, `kind` user, не команда); события агентов — `/chats/KEY?thread=feed`. `markDiscussionRead`/`discussionUnread` (`chat.read:<user>:<chat>`) → счётчик `navCounts.chats`, плашки чатов, ссылка «Обсуждение» после «Доски» на странице проекта. `postToChat` в канал проекта уведомляет остальных (`projectAudience`) событием уведомлений `chat`. `pruneChats` обсуждение не удаляет. Агентам обсуждение не уходит. Тест `discussion.test.ts`
|
||||
- **Чат с аналитиком (PEP-110)**: сообщение человека в обсуждении проекта (PEP-106) → `analystChatTick` в тике вачдога (`runner/analyst-chat.ts`): `claudePrint` на подписке проекта (`PEPPA_INTAKE_BIN`, `PEPPA_ANALYST_CHAT_MODEL`), контекст `core/analyst-chat.ts` (`intakeContext` + `projectStatusBlock` со ссылками «где что смотреть»), ответ `{reply, create[]}` → сообщение `kind: user, authorKind: agent, authorLogin: «Аналитик»` в то же обсуждение + событие уведомлений `chat`; стори из `create` — только по явной просьбе, intake у них `done`. Курсор `chat.analyst:<chatId>`, `analystPending` («печатает…»), сообщения старше `PEPPA_ANALYST_CHAT_MAX_AGE_MIN` (60) пропускаются, сбой — одна заметка без повторов, `PEPPA_ANALYST_CHAT=off`. Мок — роль `chat` в `mock-intake`; тест `analyst-chat.test.ts`
|
||||
- **Чаты для продакта (PEP-117)**: `/chats` — обзор (`chatOverview` в core/chats.ts: карточка проекта — непрочитанное, открытые вопросы, последнее сообщение; сверху `inbox` «Ждут вашего ответа»); журнал — `/chats/master` («Все события»). В журналах (`master`, `?thread=feed`) поля ввода нет. `EVENT_TEXT`: смена статуса словами по `to` (и `from` для «на доработку»), сбои, которые Peppa чинит сама, не `important`. Подписи: `attention` — «Сообщение от фабрики»
|
||||
- **Прогресс на Главной (PEP-77)**: `progressOverview` (core/progress.ts: стори по колонкам доски без архивных, стори в работе с агентом и прогрессом tasks.md, ждущие «Принять»; итог — только свои проекты, суперадмину отдельно `others`), раздел «Прогресс» — `components/ProgressOverview.tsx`
|
||||
- **Стори берутся сами (PEP-79)**: уровень автономности `self` «Сам берёт» (pick=auto, приёмка за PM); `provisionProject` ставит новому проекту `NEW_PROJECT_AUTONOMY`; диспетчер (`autonomyTick`) не запускает и не пингует, пока есть `projectAgentWarning`
|
||||
- **Продакту — без технических вопросов (PEP-94)**: правила `template/RULES.md` — технику агент решает сам (`design.md`, `remember`), `ask_pm` — только продуктовое, простыми словами, рекомендация первой, ответа не ждёт; MCP `request_approval` отклоняется, если `proposal !== "pm"`; аналитик не спрашивает (вопросы → «Допущения» сразу); `NEW_PROJECT_AUTONOMY` = `auto`; в вебе Proposal → «План», вкладки стори по-русски (id прежние)
|
||||
- **Выбор подписки с подтверждением (PEP-116)**: при заданном `platform.shared_pool` мастер `SubscriptionSetup` и панель «Подписки» предлагают «Свою» и «Подписку Peppa FACTORY». `chooseSharedSubscription` (runner/project-subscription.ts): суперадмин → `"switched"`; владелец → `"requested"` — вопрос с опциями `SHARED_APPROVE`/`SHARED_DENY` в платформенном проекте (`PEPPA_PLATFORM_KEY`; суперадмину на Главную и в Telegram), `settings` `shared.request:<projectId>` + `shared.question:<qid>`; `onSharedAnswer` (обработчик `onAnswer`) переключает пул или отказывает и пишет владельцу `attention`. На подписке фабрики пользователь не видит учётки пула
|
||||
- **Своя подписка (PEP-80)**: `connectOwnSubscription(db, user, project, kind, secret)` — `claude` (токен), `codex_login` (ChatGPT, device-вход; `ownPendingLogins` отдаёт ссылку и код панели «Подписки» проекта), `codex_key`, `existing`; личный пул «Подписки — <логин>»; общий пул на живой системе выключен (`peppa platform shared-pool -`)
|
||||
- **Мастер подписки (PEP-82)**: `components/SubscriptionSetup.tsx` на странице проекта без подписки (владелец/суперадмин): «Подключить Claude» (`claude_login`: `claude setup-token` на сервере → ссылка → код → `finishOwnClaudeLogin`) / «Подключить ChatGPT» (`codex_login`); `cancelOwnLogin` удаляет ожидающую подписку; `ownPendingLogins` — входы Claude и Codex пула
|
||||
- **Продакт и аналитик (PEP-84)**: роли перед бэклогом — `core/intake.ts` (настройка `project.intake:<id>` {enabled, waitMin, since}, состояние `intake.task:<id>`: product → analyst → waiting|finalize → done; `intakeContext` = AGENTS.md + память + эпики + стори; `productPrompt`/`analystPrompt` с тоном «без похвалы, без разрешений»; `intakeDescription` — текст стори для разработчика) и `runner/intake.ts` (`intakeTick` в тике вачдога, вызовы `claudePrint` в фоне, `PEPPA_INTAKE_BIN`/`_MODEL`/`_TIMEOUT_MS`; вопросы — обычный `askPm`, ответ ловит `onIntakeAnswer`, срок `waitMin` сдвигается за тихие часы автономности; 2 неудачи → стори идёт как есть; `releaseIntake` в `moveTask`). `readyBacklog` исключает `intakePendingTasks`. Реплики — событие `intake_note` (`storyComments` с `role`, чат проекта, `get_task`). Новый проект: включено; `ownPool` владельца назначается сам. Мок `mock-intake` (`MOCK_INTAKE_SCENARIO`)
|
||||
|
||||
@ -8,10 +8,10 @@ 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: tr("📝 Нужно одобрение proposal"),
|
||||
approval: tr("📝 Нужно одобрение плана"),
|
||||
question: tr("❓ Вопрос"),
|
||||
permission: tr("🔐 Нужно разрешение"),
|
||||
attention: tr("👀 Сессия ждёт тебя"),
|
||||
attention: tr("👀 Сообщение от фабрики"),
|
||||
};
|
||||
|
||||
export interface Rendered {
|
||||
|
||||
@ -78,7 +78,7 @@ export default async function ChatPage({ params, searchParams }: { params: Promi
|
||||
: discussion
|
||||
? t("Спросите аналитика, что с проектом, или опишите идею — он поможет сформулировать стори…")
|
||||
: taskThread
|
||||
? t("Ответ агенту: на открытый вопрос, иначе комментарий, который он увидит сразу")
|
||||
? t("Напишите агенту этой стори — ответ на его вопрос или замечание, он увидит сразу")
|
||||
: thread
|
||||
? t("Заметка в тред или команда /help")
|
||||
: t("Заметка в канал или команда: /status, /task KEY-N, /move KEY-N in_progress");
|
||||
@ -164,8 +164,12 @@ export default async function ChatPage({ params, searchParams }: { params: Promi
|
||||
</section>
|
||||
<section className="flex flex-col gap-1.5 text-xs text-muted-foreground">
|
||||
<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>
|
||||
<p className="m-0">
|
||||
{master
|
||||
? t("Журнал: готовые стори, вопросы, релизы и сбои по всем вашим проектам. Отвечать удобнее в «Обзоре» или в чате проекта.")
|
||||
: t("Слева: чат с аналитиком — для вопросов и новых задач; «События агентов» — журнал; ниже — переписка по каждой стори с её агентом.")}
|
||||
</p>
|
||||
<p className="m-0">{t("Журнал событий хранится {n} дн.; ваша переписка с аналитиком не удаляется.", { n: ttlDays })}</p>
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
@ -176,12 +180,16 @@ export default async function ChatPage({ params, searchParams }: { params: Promi
|
||||
<Flash error={error} />
|
||||
<PageHeader title={t("Чаты")}>
|
||||
{master
|
||||
? t("Мастер-чат: всё важное по вашим проектам в одной ленте.")
|
||||
? t("Все события по вашим проектам — журнал, справочно. Чтобы ответить агенту или написать аналитику, откройте чат проекта.")
|
||||
: t("Чат с аналитиком — ИИ-агентом вашего проекта. Спросите, что сделано и где это посмотреть, или опишите идею: он уточнит, предложит стори и заведёт их в бэклог, когда вы скажете.")}
|
||||
</PageHeader>
|
||||
|
||||
<nav className="mb-4 flex flex-wrap gap-1.5" aria-label={t("Чаты")}>
|
||||
{list.map((c) => (
|
||||
<Link href="/chats" className="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">
|
||||
{t("← Обзор")}
|
||||
</Link>
|
||||
{/* PEP-117: projects first (by name), the journal of all events last. */}
|
||||
{[...list.filter((c) => c.kind === "project"), ...list.filter((c) => c.kind === "master")].map((c) => (
|
||||
<Link
|
||||
key={c.id}
|
||||
href={`/chats/${c.slug}`}
|
||||
@ -193,7 +201,7 @@ export default async function ChatPage({ params, searchParams }: { params: Promi
|
||||
)}
|
||||
>
|
||||
{c.kind === "master" ? <MessagesSquare className="size-3.5" /> : <Hash className="size-3.5" />}
|
||||
<span className={c.kind === "project" ? "font-mono" : undefined}>{c.kind === "master" ? t("Мастер-чат") : c.slug}</span>
|
||||
<span>{c.kind === "master" ? t("Все события") : c.title.includes(" · ") ? c.title.split(" · ").slice(1).join(" · ") : c.slug}</span>
|
||||
{c.tgTitle && <Send className="size-3 text-info" aria-label={t("связан с Telegram")} />}
|
||||
{(unread.get(c.id) ?? 0) > 0 && c.id !== chat.id && (
|
||||
<span className="rounded-full bg-info px-1.5 font-mono text-[11px] leading-4 font-semibold text-background tabular-nums" title={t("новые сообщения в обсуждении")}>
|
||||
@ -209,12 +217,12 @@ export default async function ChatPage({ params, searchParams }: { params: Promi
|
||||
{!master && (
|
||||
<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={discussion} title={t("💬 Чат с аналитиком")} meta={t("вопросы и новые задачи")} />
|
||||
<ThreadLink href={url({ thread: FEED })} active={!discussion && thread === undefined} title={t("События агентов")} meta={t("вопросы, ревью, релизы")} />
|
||||
{threads.length > 0 && <div className="mx-2 my-1 border-t" />}
|
||||
<ThreadLink href={url({ thread: FEED })} active={!discussion && thread === undefined} title={t("События агентов")} meta={t("журнал: что делали агенты")} />
|
||||
{threads.length > 0 && <p className="m-0 px-2 pt-2 text-[11px] tracking-wide text-muted-foreground uppercase">{t("Переписка по стори")}</p>}
|
||||
{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, t)}`} open={th.open} />
|
||||
))}
|
||||
{threads.length === 0 && <p className="m-0 px-2 py-1.5 text-xs text-muted-foreground">{t("Тредов пока нет.")}</p>}
|
||||
{threads.length === 0 && <p className="m-0 px-2 py-1.5 text-xs text-muted-foreground">{t("Переписки по стори пока нет.")}</p>}
|
||||
</nav>
|
||||
)}
|
||||
|
||||
@ -241,6 +249,12 @@ export default async function ChatPage({ params, searchParams }: { params: Promi
|
||||
<AgentBadge name={t("Аналитик")} /> <span className="animate-pulse">{t("печатает…")}</span>
|
||||
</p>
|
||||
)}
|
||||
{master || (!discussion && thread === undefined) ? (
|
||||
<p className="m-0 rounded-lg border border-dashed px-3 py-2 text-sm text-muted-foreground">
|
||||
{t("Это журнал событий — писать сюда не нужно.")}{" "}
|
||||
{master ? <Link href="/chats">{t("Выберите проект")}</Link> : <Link href={url({})}>{t("Откройте чат с аналитиком")}</Link>}{t(", чтобы задать вопрос или описать задачу.")}
|
||||
</p>
|
||||
) : (
|
||||
<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={t("Сообщение")} />
|
||||
@ -252,6 +266,7 @@ export default async function ChatPage({ params, searchParams }: { params: Promi
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
</Workspace>
|
||||
|
||||
@ -1,5 +1,88 @@
|
||||
import { redirect } from "next/navigation";
|
||||
import Link from "next/link";
|
||||
import { ArrowRight, MessagesSquare } from "lucide-react";
|
||||
import { chatOverview, syncChats } from "@peppa/core";
|
||||
import { LiveRefresh } from "@/components/LiveRefresh";
|
||||
import { AgentBadge } from "@/components/AgentBadge";
|
||||
import { QuestionCard } from "@/components/cards";
|
||||
import { ago, Empty, Flash, PageHeader, Section } from "@/components/common";
|
||||
import { Workspace } from "@/components/Workspace";
|
||||
import { requireUser } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { inbox } from "@/lib/queries";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
|
||||
export default function Chats() {
|
||||
redirect("/chats/master");
|
||||
export async function generateMetadata() {
|
||||
const t = await getT();
|
||||
return { title: t("Чаты — Peppa FACTORY") };
|
||||
}
|
||||
|
||||
const ANALYST = m("Аналитик");
|
||||
|
||||
/**
|
||||
* «Чаты» (PEP-117): the overview a product manager lands on — what waits for their answer and
|
||||
* where to write to the analyst of each project. The raw feed of events lives at /chats/master.
|
||||
*/
|
||||
export default async function Chats({ searchParams }: { searchParams: Promise<{ error?: string }> }) {
|
||||
const user = await requireUser();
|
||||
const t = await getT();
|
||||
const { error } = await searchParams;
|
||||
await syncChats(db).catch((e) => console.error("syncChats", e));
|
||||
const [cards, waiting] = await Promise.all([chatOverview(db, user), inbox(user.id)]);
|
||||
return (
|
||||
<Workspace>
|
||||
<LiveRefresh scope="chats" />
|
||||
<Flash error={error} />
|
||||
<PageHeader title={t("Чаты")}>{t("Здесь вы разговариваете с фабрикой: отвечаете агентам и пишете аналитику своего проекта — что узнать или что сделать.")}</PageHeader>
|
||||
|
||||
<Section title={t("Ждут вашего ответа")} count={waiting.length}>
|
||||
{waiting.length === 0 ? (
|
||||
<Empty>{t("Сейчас от вас ничего не нужно — агенты работают сами.")}</Empty>
|
||||
) : (
|
||||
waiting.map((q) => <QuestionCard key={q.id} q={q} taskKey={q.taskKey} taskStatus={q.taskStatus} back="/chats" />)
|
||||
)}
|
||||
</Section>
|
||||
|
||||
<Section title={t("Ваши проекты")} count={cards.length}>
|
||||
{cards.length === 0 ? (
|
||||
<Empty>
|
||||
{t("Проектов пока нет.")} <Link href="/projects/new">{t("Создайте проект")}</Link> {t("— и у него появится чат с аналитиком.")}
|
||||
</Empty>
|
||||
) : (
|
||||
<ul className="m-0 grid list-none gap-3 p-0 md:grid-cols-2">
|
||||
{cards.map((c) => (
|
||||
<li key={c.chatId}>
|
||||
<Link href={`/chats/${c.key}`} className="flex h-full flex-col gap-2 rounded-xl border bg-card p-4 text-foreground hover:border-primary/60 hover:no-underline">
|
||||
<span className="flex items-center gap-2">
|
||||
<span className="rounded bg-muted px-1.5 font-mono text-xs text-primary">{c.key}</span>
|
||||
<span className="min-w-0 flex-1 truncate font-medium">{c.name}</span>
|
||||
{c.unread > 0 && <span className="rounded-full bg-info px-2 text-xs font-semibold text-background" title={t("новые сообщения")}>{t("{n} нов.", { n: c.unread })}</span>}
|
||||
{c.open > 0 && <span className="rounded-full bg-primary px-2 text-xs font-semibold text-primary-foreground" title={t("агенты ждут вашего ответа")}>{t("ждут ответа: {n}", { n: c.open })}</span>}
|
||||
</span>
|
||||
{c.last ? (
|
||||
<span className="flex min-w-0 flex-col gap-0.5 text-sm">
|
||||
<span className="flex items-center gap-1.5 text-xs text-muted-foreground">
|
||||
{c.last.who === ANALYST ? <AgentBadge name={t(ANALYST)} /> : <span>{c.last.mine ? t("вы") : c.last.who}</span>}
|
||||
<span>· {ago(c.last.at, t)}</span>
|
||||
</span>
|
||||
<span className="line-clamp-2 text-muted-foreground">{c.last.system ? t.text(c.last.text) : c.last.text}</span>
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-sm text-muted-foreground">{t("Здесь пока тихо. Спросите аналитика, что с проектом, или опишите новую задачу.")}</span>
|
||||
)}
|
||||
<span className="mt-auto inline-flex items-center gap-1.5 text-sm font-medium text-primary">
|
||||
<MessagesSquare className="size-4" /> {t("Написать аналитику")} <ArrowRight className="size-3.5" />
|
||||
</span>
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</Section>
|
||||
|
||||
<p className="mt-6 text-sm text-muted-foreground">
|
||||
{t("Нужна история?")} <Link href="/chats/master">{t("Все события по вашим проектам")}</Link> {t("— что делали агенты, релизы и сбои, справочно.")}
|
||||
</p>
|
||||
</Workspace>
|
||||
);
|
||||
}
|
||||
|
||||
@ -2,7 +2,7 @@ import { Fragment } from "react";
|
||||
import { ProductCard } from "@/components/ProductCard";
|
||||
import { notFound } from "next/navigation";
|
||||
import { ExternalLink, Plus, Rocket, SquareTerminal } from "lucide-react";
|
||||
import { columnOf, currentReleases, describeRepo, isPlatform, listReleases, bugsinkWebhookBase, openPulls, platformReleaseCandidate, platformReleaseOffers, ownPendingLogins, readAgentsMd, repoOverview, type Release } from "@peppa/runner";
|
||||
import { columnOf, currentReleases, describeRepo, isPlatform, listReleases, bugsinkWebhookBase, openPulls, platformReleaseCandidate, platformReleaseOffers, ownPendingLogins, readAgentsMd, repoOverview, type Release, sharedRequest } from "@peppa/runner";
|
||||
import { userProjectIds, projectProduct, discussionUnread, ensureProjectChat, listHosts, DEFAULT_RUNNER_SETTINGS, DEFAULT_AGENT_SETTINGS, getProjectAgentSettings, getSystemAgentSettings, getProjectRunnerSettings, getSystemRunnerSettings, blockedLabel, blockersMap, epicProgress, progressLabel, taskProgress, getProjectBudget, listJournal, listProjectSecrets, projectMetrics, type ActorChannel, type ActorKind, getAutonomy, getIncidentSettings, getReviewSettings, isSuperadmin, listEpics, listErrorSources, listIncidents, listMembers, listPools, listSpecs, taskAgentNames, getIntakeSettings, intakePendingTasks, projectAgentWarning, memoryStats, readMemory, projectPool, sharedPool, ownPool, poolOverview, repoAudience, repoVisibilityLabel } from "@peppa/core";
|
||||
import { LiveRefresh } from "@/components/LiveRefresh";
|
||||
import { PanelSection } from "@/components/ActivityAside";
|
||||
@ -152,6 +152,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
||||
const product = await projectProduct(db, p.id);
|
||||
// The chat belongs to the project's people; a superadmin looking at someone else's project has none.
|
||||
const canChat = (await userProjectIds(db, user.id)).includes(p.id);
|
||||
const sharedReq = await sharedRequest(db, p.id);
|
||||
const discussionNew = (await discussionUnread(db, user.id)).get((await ensureProjectChat(db, p.id)).id) ?? 0;
|
||||
const memory = tab === "specs" ? readMemory(p.workspacePath) : "";
|
||||
// PEP-47 metrics, PEP-48 journal, PEP-43 default budget.
|
||||
@ -331,14 +332,21 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
||||
<PanelSection title={t("Подписки")}>
|
||||
<p className="m-0 text-sm" id="subscription">
|
||||
{pool ? (
|
||||
<>{shared?.id === pool.id ? t("Агенты работают на пуле «{name}» — общая подписка Peppa FACTORY.", { name: pool.name }) : t("Агенты работают на пуле «{name}».", { name: pool.name })}</>
|
||||
shared?.id === pool.id ? (
|
||||
<>
|
||||
{t("Агенты работают на")} <b>{t("подписке Peppa FACTORY")}</b> {t("— общей для пользователей фабрики. Свою подписку можно подключить в любой момент ниже.")}
|
||||
</>
|
||||
) : (
|
||||
<>{t("Агенты работают на вашей подписке — пул «{name}».", { name: pool.name })}</>
|
||||
)
|
||||
) : agentWarning ? (
|
||||
<b>{t("Подписка не выбрана — агенты не запустятся.")}</b>
|
||||
) : (
|
||||
t("Пул не назначен — агенты работают на входе машины.")
|
||||
)}
|
||||
</p>
|
||||
{poolView && (
|
||||
{/* PEP-116: on the factory's subscription a user sees its state, not the accounts behind it. */}
|
||||
{poolView && (superadmin || poolView.pool.id !== shared?.id) && (
|
||||
<>
|
||||
<PoolSubscriptions
|
||||
o={poolView}
|
||||
@ -372,7 +380,10 @@ 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"}>{t("Общая подписка Peppa FACTORY")}</Button>
|
||||
<Button size="sm" variant={pool ? "outline" : "default"} disabled={!!sharedReq && !superadmin}>
|
||||
{superadmin ? t("Перейти на подписку Peppa FACTORY") : sharedReq ? t("Запрос на подписку Peppa FACTORY отправлен") : t("Попросить подписку Peppa FACTORY")}
|
||||
</Button>
|
||||
{!superadmin && <span className="text-xs text-muted-foreground">{sharedReq ? t("Ждём подтверждения администратора фабрики — придёт сообщение.") : t("Нужно подтверждение администратора фабрики.")}</span>}
|
||||
</form>
|
||||
)}
|
||||
<form action={connectOwnSubscriptionAction} className="flex flex-col gap-2">
|
||||
@ -459,7 +470,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
||||
<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} />}
|
||||
{mayChoose && (ownLogins.length > 0 || (!pool && agentWarning)) && <SubscriptionSetup projectId={p.id} back={back} logins={ownLogins} shared={!!shared} requested={!!sharedReq} direct={superadmin} />}
|
||||
{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">{t("Агенты не запустятся:")}</span> {t.text(agentWarning)}.
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
import { ExternalLink } from "lucide-react";
|
||||
import type { OwnLogin } from "@peppa/runner";
|
||||
import { cancelOwnLoginAction, connectOwnSubscriptionAction, finishOwnClaudeLoginAction } from "@/app/(app)/actions";
|
||||
import { cancelOwnLoginAction, chooseSharedSubscriptionAction, connectOwnSubscriptionAction, finishOwnClaudeLoginAction } from "@/app/(app)/actions";
|
||||
import { Hidden } from "@/components/cards";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
@ -13,7 +13,7 @@ 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 async function SubscriptionSetup({ projectId, back, logins }: { projectId: number; back: string; logins: OwnLogin[] }) {
|
||||
export async function SubscriptionSetup({ projectId, back, logins, shared = false, requested = false, direct = false }: { projectId: number; back: string; logins: OwnLogin[]; shared?: boolean; /** The owner already asked for the factory's subscription. */ requested?: boolean; /** A superadmin switches without a request. */ direct?: boolean }) {
|
||||
const t = await getT();
|
||||
if (logins.length) {
|
||||
return (
|
||||
@ -69,23 +69,45 @@ export async function SubscriptionSetup({ projectId, back, logins }: { projectId
|
||||
</div>
|
||||
);
|
||||
}
|
||||
// PEP-116: two equal ways — the owner's own subscription, or the one built into Peppa FACTORY.
|
||||
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={t("Подключение подписки")}>
|
||||
<h2 className="m-0 text-base font-semibold">{t("Подключите подписку — и агенты начнут работать")}</h2>
|
||||
<p className="m-0">
|
||||
{t("Агенты пишут код на вашей подписке Claude или ChatGPT — подойдёт обычная платная (Claude Pro или Max, ChatGPT Plus или Pro). Это одна минута: вы входите в свой аккаунт, как на любом сайте. Пароль Peppa FACTORY не видит.")}
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<form action={connectOwnSubscriptionAction}>
|
||||
<Hidden fields={{ projectId, kind: "claude_login", back }} />
|
||||
<Button variant="default" size="lg">{t("Подключить Claude")}</Button>
|
||||
</form>
|
||||
<form action={connectOwnSubscriptionAction}>
|
||||
<Hidden fields={{ projectId, kind: "codex_login", back }} />
|
||||
<Button variant="outline" size="lg">{t("Подключить ChatGPT")}</Button>
|
||||
</form>
|
||||
<h2 className="m-0 text-base font-semibold">{shared ? t("Выберите, на чём будут работать агенты") : t("Подключите подписку — и агенты начнут работать")}</h2>
|
||||
<div className={shared ? "grid gap-3 md:grid-cols-2" : "flex flex-col gap-3"}>
|
||||
<div className="flex flex-col gap-2 rounded-lg border bg-card px-4 py-3">
|
||||
{shared && <span className="font-medium">{t("Своя подписка")}</span>}
|
||||
<p className="m-0 text-muted-foreground">
|
||||
{t("Агенты пишут код на вашей подписке Claude или ChatGPT — подойдёт обычная платная (Claude Pro или Max, ChatGPT Plus или Pro). Лимиты и расход — только ваши, пароль Peppa FACTORY не видит.")}
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<form action={connectOwnSubscriptionAction}>
|
||||
<Hidden fields={{ projectId, kind: "claude_login", back }} />
|
||||
<Button variant="default" size="lg">{t("Подключить Claude")}</Button>
|
||||
</form>
|
||||
<form action={connectOwnSubscriptionAction}>
|
||||
<Hidden fields={{ projectId, kind: "codex_login", back }} />
|
||||
<Button variant="outline" size="lg">{t("Подключить ChatGPT")}</Button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
{shared && (
|
||||
<div className="flex flex-col gap-2 rounded-lg border bg-card px-4 py-3">
|
||||
<span className="font-medium">{t("Подписка Peppa FACTORY")}</span>
|
||||
<p className="m-0 text-muted-foreground">
|
||||
{t("Ничего подключать не нужно. Подписка общая для пользователей фабрики, поэтому её выдаёт администратор: вы отправляете запрос, он подтверждает — и агенты начинают работать. Когда она занята или упирается в лимит, агенты ждут. Перейти на свою можно в любой момент.")}
|
||||
</p>
|
||||
{requested && !direct ? (
|
||||
<p className="m-0 rounded-md border border-primary/40 bg-primary/10 px-3 py-2 font-medium">{t("Запрос отправлен — ждём подтверждения администратора. Вам придёт сообщение.")}</p>
|
||||
) : (
|
||||
<form action={chooseSharedSubscriptionAction}>
|
||||
<Hidden fields={{ projectId, back }} />
|
||||
<Button variant="outline" size="lg">{direct ? t("Работать на подписке Peppa FACTORY") : t("Попросить подписку Peppa FACTORY")}</Button>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<p className="m-0 text-xs text-muted-foreground">{t("Нет подписки? Оформите её на claude.ai или chatgpt.com и вернитесь сюда. Другие способы (готовый токен, ключ API) — в «⋯ Настройки проекта → Подписки».")}</p>
|
||||
<p className="m-0 text-xs text-muted-foreground">{t("Нет своей подписки? Оформите её на claude.ai или chatgpt.com и вернитесь сюда. Другие способы (готовый токен, ключ API) и смена выбора — в «⋯ Настройки проекта → Подписки».")}</p>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
@ -18,7 +18,7 @@ const KIND = {
|
||||
approval: { label: m("Одобрение плана"), 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" },
|
||||
attention: { label: m("Сообщение от фабрики"), icon: BellRing, border: "border-l-ok" },
|
||||
} as const;
|
||||
|
||||
/** Hidden inputs of a server-action form. */
|
||||
|
||||
10
openspec/changes/pep-116-subscription-choice/proposal.md
Normal file
10
openspec/changes/pep-116-subscription-choice/proposal.md
Normal file
@ -0,0 +1,10 @@
|
||||
# Proposal: PEP-116 — выбор подписки: своя или Peppa FACTORY
|
||||
|
||||
## Why
|
||||
PM: пользователь выбирает, на чём работают агенты, — на своей подписке или на той, что под капотом у Peppa FACTORY. Общий пул (PEP-76) был выключен (PEP-80), в мастере подключения его не было.
|
||||
|
||||
## What Changes
|
||||
- Мастер `SubscriptionSetup` при заданном `platform.shared_pool` — два равных варианта: «Своя подписка» (Claude / ChatGPT) и «Подписка Peppa FACTORY» (без подключения, общая, при лимите агенты ждут, сменить можно в любой момент).
|
||||
- «⋯ Настройки проекта → Подписки»: «Агенты работают на подписке Peppa FACTORY» / «на вашей подписке — пул …»; кнопка «Перейти на подписку Peppa FACTORY»; на подписке фабрики пользователь не видит учётки, стоящие за ней (суперадмин видит).
|
||||
- **Подтверждение суперадмина** (решение PM: подписка фабрики — её собственная): выбор владельца — это запрос. `chooseSharedSubscription` → `"requested"`: вопрос с кнопками «✅ Разрешить / ❌ Отказать» в платформенном проекте (доходит суперадмину на Главную и в Telegram), `shared.request:<projectId>`; `onSharedAnswer` — «Разрешить» переключает проект и сообщает владельцу, иначе отказ с подсказкой подключить свою. Суперадмин переключает сразу. Повторная просьба нового запроса не создаёт.
|
||||
- Живая система: `peppa platform shared-pool <id>` (координатор).
|
||||
@ -0,0 +1,16 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Выбор подписки проекта
|
||||
Владелец проекта SHALL выбирать между своей подпиской и подпиской Peppa FACTORY, когда суперадмин её предлагает.
|
||||
|
||||
#### Scenario: Проект без подписки
|
||||
- **WHEN** владелец открывает проект без подписки, а общий пул задан
|
||||
- **THEN** он видит два варианта; «Попросить подписку Peppa FACTORY» отправляет запрос суперадмину, проект не переключается до его согласия
|
||||
|
||||
#### Scenario: Суперадмин отвечает на запрос
|
||||
- **WHEN** суперадмин нажимает «Разрешить» (веб или Telegram)
|
||||
- **THEN** проект работает на подписке фабрики, владельцу приходит сообщение; при «Отказать» проект остаётся как был, владельцу — подсказка подключить свою
|
||||
|
||||
#### Scenario: Общий пул не задан
|
||||
- **WHEN** суперадмин не предлагает подписку фабрики
|
||||
- **THEN** мастер предлагает только свою подписку
|
||||
3
openspec/changes/pep-116-subscription-choice/tasks.md
Normal file
3
openspec/changes/pep-116-subscription-choice/tasks.md
Normal file
@ -0,0 +1,3 @@
|
||||
- [x] 1.1 мастер и панель подписок
|
||||
- [x] 1.2 тест (subscriptions.test.ts), проверка в браузере на копии базы
|
||||
- [ ] 1.3 включить общий пул на живой системе после выкатки
|
||||
18
openspec/changes/pep-117-chats-for-product/proposal.md
Normal file
18
openspec/changes/pep-117-chats-for-product/proposal.md
Normal file
@ -0,0 +1,18 @@
|
||||
# Proposal: PEP-117 — чаты понятны продакту
|
||||
|
||||
## Why
|
||||
PM: «чат непонятный для продакта». «Чаты» открывались на мастер-чате — ленте технических событий
|
||||
(«Статус: готово → ревью», «Сессия ждёт тебя», напоминания по чужим проектам) с полем ввода для
|
||||
команд `/status`. Непонятно, что ждёт ответа и где писать.
|
||||
|
||||
## What Changes
|
||||
- `/chats` — обзор: «Ждут вашего ответа» (вопросы агентов с кнопками) и «Ваши проекты» —
|
||||
карточка на проект (`chatOverview`: новые сообщения, сколько ждёт ответа, последнее сообщение,
|
||||
«Написать аналитику»). Журнал всех событий — по ссылке (`/chats/master`, «Все события»).
|
||||
- Страница чата: «← Обзор», проекты по названиям, «Все события» последним; в журналах (все
|
||||
события, «События агентов») поля ввода нет — подсказка, куда писать; поле в треде стори —
|
||||
«Напишите агенту этой стори…».
|
||||
- События словами: «Агент взял стори в работу», «Стори готова — посмотрите результат и примите»,
|
||||
«Стори вернулась агенту на доработку», «Стори принята и закрыта»; сбои, которые Peppa чинит
|
||||
сама (молчит, споткнулся, перезапущен), — спокойным текстом и не «важное»; без «PR», «процесс».
|
||||
- Подписи: «Сообщение от фабрики» вместо «Сессия ждёт тебя», «Одобрение плана» в напоминаниях и боте.
|
||||
@ -0,0 +1,12 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Обзор чатов
|
||||
«Чаты» SHALL открываться на обзоре: что ждёт ответа пользователя и чат с аналитиком каждого его проекта.
|
||||
|
||||
#### Scenario: Пользователь открывает «Чаты»
|
||||
- **WHEN** у пользователя два проекта и один открытый вопрос агента
|
||||
- **THEN** он видит вопрос с кнопками ответа и карточки проектов с последним сообщением и «Написать аналитику»
|
||||
|
||||
#### Scenario: Журнал событий
|
||||
- **WHEN** пользователь открывает «Все события» или «События агентов»
|
||||
- **THEN** поля ввода нет, есть подсказка, где писать; события сказаны словами, без «статус X → Y»
|
||||
4
openspec/changes/pep-117-chats-for-product/tasks.md
Normal file
4
openspec/changes/pep-117-chats-for-product/tasks.md
Normal file
@ -0,0 +1,4 @@
|
||||
- [x] 1.1 core: chatOverview, тексты событий
|
||||
- [x] 1.2 веб: обзор /chats, страница чата без поля в журналах
|
||||
- [x] 1.3 подписи карточек, бота и напоминаний
|
||||
- [x] 1.4 тесты (discussion.test.ts, chats.test.ts), проверка в браузере на копии базы
|
||||
@ -2,7 +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 { m as tr, PRODUCT_NAME } 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";
|
||||
@ -235,6 +235,38 @@ export async function discussionUnread(db: Db, userId: number): Promise<Map<numb
|
||||
return out;
|
||||
}
|
||||
|
||||
export interface ProjectChatCard {
|
||||
chatId: number;
|
||||
key: string;
|
||||
name: string;
|
||||
/** Messages of other people and the analyst the user has not read. */
|
||||
unread: number;
|
||||
/** Agent questions of the project waiting for a person. */
|
||||
open: number;
|
||||
/** The last message of the chat with the analyst. */
|
||||
last: { who: string; mine: boolean; text: string; at: Date; /** Written by the factory itself (translatable text). */ system: boolean } | null;
|
||||
}
|
||||
|
||||
/** PEP-117: the user's project chats at a glance — what is new and what was said last. */
|
||||
export async function chatOverview(db: Db, user: Pick<User, "id">): Promise<ProjectChatCard[]> {
|
||||
const list = (await listChats(db, user)).filter((c) => c.kind === "project");
|
||||
const unread = await discussionUnread(db, user.id);
|
||||
const out: ProjectChatCard[] = [];
|
||||
for (const c of list) {
|
||||
const [m] = await db.select().from(chatMessages).where(and(eq(chatMessages.chatId, c.id), DISCUSSION)).orderBy(desc(chatMessages.id)).limit(1);
|
||||
out.push({
|
||||
chatId: c.id,
|
||||
key: c.slug,
|
||||
name: c.title.includes(" · ") ? c.title.split(" · ").slice(1).join(" · ") : c.title,
|
||||
unread: unread.get(c.id) ?? 0,
|
||||
open: c.open,
|
||||
last: m ? { who: m.authorKind === "agent" ? (m.authorLogin ?? tr("Аналитик")) : (m.authorLogin ?? PRODUCT_NAME), mine: m.authorUserId === user.id, text: m.text, at: m.createdAt, system: m.authorKind === "system" } : null,
|
||||
});
|
||||
}
|
||||
// What needs the person first: open questions, then unread, then the most recent talk.
|
||||
return out.sort((a, b) => b.open - a.open || b.unread - a.unread || (b.last?.at.getTime() ?? 0) - (a.last?.at.getTime() ?? 0));
|
||||
}
|
||||
|
||||
/**
|
||||
* The master feed: the user's own master messages and the important messages of the chats
|
||||
* of their projects (muted projects left out). `threadKey` narrows it to one project thread.
|
||||
@ -307,38 +339,38 @@ const EVENT_TEXT: Record<string, (p: P) => { text: string; important?: boolean;
|
||||
const from = (p.from as P | undefined)?.status;
|
||||
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 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)) };
|
||||
// PEP-117: what happened to the story, in words — not «статус X → Y».
|
||||
const said: Record<string, string> = {
|
||||
proposing: tr("📝 Агент составляет план стори"),
|
||||
awaiting_approval: tr("⏸ План готов и ждёт вашего одобрения"),
|
||||
in_progress: from === "review" ? tr("🔧 Стори вернулась агенту на доработку") : tr("▶️ Агент взял стори в работу"),
|
||||
review: tr("👀 Стори готова — посмотрите результат и примите"),
|
||||
done: tr("✅ Стори принята и закрыта"),
|
||||
blocked: tr("⛔ Стори заблокирована — агент не может продолжать"),
|
||||
backlog: tr("↩️ Стори вернулась в бэклог"),
|
||||
};
|
||||
return { text: said[String(to)] ?? tr("• Статус: {to}", { to: statusRu(String(to)) }), 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: tr("📦 Репозиторий перенесён: {from} → {to}", { from: s(p.from), to: s(p.to) }), important: true }),
|
||||
repo_transferred: (p) => ({ text: tr("📦 Код проекта переехал: {from} → {to}", { from: s(p.from), to: s(p.to) }) }),
|
||||
// PEP-84: «продакт» and «аналитик» talk to the PM in the story's thread.
|
||||
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("▶️ Агент запущен") }),
|
||||
pr_merged_in_gitea: (p) => ({ text: p.by ? tr("🔀 Изменения стори приняты в код проекта ({by})", { by: s(p.by) }) : tr("🔀 Изменения стори приняты в код проекта") }),
|
||||
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("⬆️ Модель усилена") }),
|
||||
// Hiccups Peppa handles by itself are told calmly and are not «важное» for a product manager.
|
||||
stalled: (p) => ({ text: p.idleMinutes ? tr("⚠️ Агент давно молчит ({n} мин) — Peppa FACTORY перезапустит его сама", { n: s(p.idleMinutes) }) : tr("⚠️ Агент давно молчит — Peppa FACTORY перезапустит его сама") }),
|
||||
stop_failure: (p) => ({ text: tr("⚠️ Агент споткнулся ({error}) — Peppa FACTORY продолжит сама", { error: s(p.error) || tr("ошибка") }) }),
|
||||
exited: () => ({ text: tr("⚠️ Агент остановился раньше времени — Peppa FACTORY перезапустит его сама") }),
|
||||
usage_limit: () => ({ text: tr("⏳ Подписка упёрлась в лимит — агент продолжит после сброса или на другой подписке"), important: true }),
|
||||
auto_restarted: (p) => ({ text: p.attempt ? tr("🔁 Агент перезапущен после сбоя (попытка {attempt} из {of})", { attempt: s(p.attempt), of: s(p.of) }) : tr("🔁 Агент перезапущен после сбоя") }),
|
||||
restart_failed: () => ({ text: tr("❌ Агента не удалось перезапустить — нужна ваша помощь: откройте стори"), important: true }),
|
||||
budget_paused: () => ({ text: tr("💸 Бюджет стори исчерпан — агент на паузе, нужен ваш ответ"), important: true }),
|
||||
subscription_switched: (p) => ({ text: p.to ? tr("🔀 Агент перешёл на другую подписку ({to}) и продолжает", { to: s(p.to) }) : tr("🔀 Агент перешёл на другую подписку и продолжает") }),
|
||||
model_escalated: () => ({ text: tr("⬆️ Задача оказалась сложнее — агент взял модель посильнее") }),
|
||||
};
|
||||
|
||||
const RELEASE_ICON: Record<string, string> = { deploying: "⏳", healthy: "🚀", rolled_back: "↩️", failed: "❌", removed: "🧹" };
|
||||
|
||||
@ -2,24 +2,95 @@
|
||||
// («Общая подписка Пеппы») or the owner's own Claude subscription (a `claude setup-token` token,
|
||||
// kept encrypted like every subscription, in the owner's personal pool).
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
import { createPool, getPool, listLoans, logEvent, ownPool, PeppaError, setProjectPool, sharedPool, updatePool, isSuperadmin, listPools, listSubscriptions, poolSubscriptions, projectPool, type Project, type User } from "@peppa/core";
|
||||
import { askPmProject, deleteSetting, getProject, getSetting, platformProjectKey, setSetting, type Question, createPool, getPool, listLoans, logEvent, ownPool, PeppaError, setProjectPool, sharedPool, updatePool, isSuperadmin, listPools, listSubscriptions, poolSubscriptions, projectPool, type Project, type User } from "@peppa/core";
|
||||
import type { Db } from "@peppa/db";
|
||||
import { finishClaudeLogin, pendingLogin, pollCodexLogin, removeSubscription } from "./subscription-login.ts";
|
||||
import { addSubscription } from "./subscriptions.ts";
|
||||
import { onAnswer } from "./sessions.ts";
|
||||
import { projects } from "@peppa/db";
|
||||
import { eq } from "drizzle-orm";
|
||||
|
||||
async function requireOwner(db: Db, user: User, project: Project): Promise<void> {
|
||||
if (project.ownerId !== user.id && !(await isSuperadmin(db, user))) throw new PeppaError(m("Подписку проекта выбирает его владелец"));
|
||||
}
|
||||
|
||||
/** «Общая подписка Пеппы»: the project runs on the platform's shared pool. */
|
||||
export async function chooseSharedSubscription(db: Db, user: User, project: Project): Promise<void> {
|
||||
// ── «Подписка Peppa FACTORY» (PEP-116) ───────────────────────────────────────
|
||||
// The factory's subscription is the superadmin's own: a project gets it only after the
|
||||
// superadmin says yes. The owner's choice becomes a request — a question with buttons in the
|
||||
// platform project, which reaches the superadmin on the Home page and in Telegram.
|
||||
|
||||
export const SHARED_APPROVE = m("✅ Разрешить");
|
||||
export const SHARED_DENY = m("❌ Отказать");
|
||||
|
||||
export interface SharedRequest {
|
||||
userId: number;
|
||||
login: string;
|
||||
questionId: number;
|
||||
at: string;
|
||||
}
|
||||
|
||||
const requestKey = (projectId: number) => `shared.request:${projectId}`;
|
||||
const questionKey = (questionId: number) => `shared.question:${questionId}`;
|
||||
|
||||
/** The project's request for the factory's subscription that still waits for the superadmin. */
|
||||
export async function sharedRequest(db: Db, projectId: number): Promise<SharedRequest | null> {
|
||||
return getSetting<SharedRequest>(db, requestKey(projectId));
|
||||
}
|
||||
|
||||
async function switchToShared(db: Db, project: Project, poolId: number, login: string, approvedBy?: string): Promise<void> {
|
||||
await setProjectPool(db, project.id, poolId);
|
||||
await logEvent(db, { projectId: project.id, type: "project_subscription", payload: { login, choice: "shared", poolId, ...(approvedBy ? { approvedBy } : {}) } });
|
||||
}
|
||||
|
||||
/**
|
||||
* «Подписка Peppa FACTORY»: a superadmin switches the project at once; an owner's choice is a
|
||||
* request the superadmin confirms ("requested" — one per project, asking again changes nothing).
|
||||
*/
|
||||
export async function chooseSharedSubscription(db: Db, user: User, project: Project): Promise<"switched" | "requested"> {
|
||||
await requireOwner(db, user, project);
|
||||
const pool = await sharedPool(db);
|
||||
if (!pool) throw new PeppaError(m("Общая подписка не настроена — подключите свою или попросите администратора"));
|
||||
await setProjectPool(db, project.id, pool.id);
|
||||
await logEvent(db, { projectId: project.id, type: "project_subscription", payload: { login: user.login, choice: "shared", poolId: pool.id } });
|
||||
if (!pool) throw new PeppaError(m("Подписка Peppa FACTORY сейчас не предлагается — подключите свою"));
|
||||
if (await isSuperadmin(db, user)) {
|
||||
await switchToShared(db, project, pool.id, user.login);
|
||||
return "switched";
|
||||
}
|
||||
if (await sharedRequest(db, project.id)) return "requested";
|
||||
const platform = await getProject(db, platformProjectKey()).catch(() => null);
|
||||
if (!platform) throw new PeppaError(m("Подписку Peppa FACTORY некому подтвердить — подключите свою"));
|
||||
const q = await askPmProject(db, platform, {
|
||||
kind: "question",
|
||||
options: [SHARED_APPROVE, SHARED_DENY],
|
||||
text: m("🔑 {login} просит подписку Peppa FACTORY для проекта «{project}» ({key}).\nАгенты проекта будут работать на подписке фабрики и тратить её лимит.\nРазрешить?", { login: user.login, project: project.name, key: project.key }),
|
||||
});
|
||||
await setSetting(db, requestKey(project.id), { userId: user.id, login: user.login, questionId: q.id, at: new Date().toISOString() } satisfies SharedRequest);
|
||||
await setSetting(db, questionKey(q.id), project.id);
|
||||
await logEvent(db, { projectId: project.id, type: "project_subscription", payload: { login: user.login, choice: "shared_requested" } });
|
||||
return "requested";
|
||||
}
|
||||
|
||||
/** The superadmin answered a request (web, Telegram, MCP): yes switches the project, anything else refuses. */
|
||||
export async function onSharedAnswer(db: Db, q: Question, answer: string): Promise<boolean> {
|
||||
if (q.taskId || q.sessionId || !(q.options ?? []).includes(SHARED_APPROVE)) return false;
|
||||
const projectId = await getSetting<number>(db, questionKey(q.id));
|
||||
if (projectId == null) return false;
|
||||
const req = await sharedRequest(db, projectId);
|
||||
await deleteSetting(db, questionKey(q.id));
|
||||
await deleteSetting(db, requestKey(projectId));
|
||||
const [project] = await db.select().from(projects).where(eq(projects.id, projectId));
|
||||
if (!project || !req) return true;
|
||||
const web = process.env.PEPPA_WEB_URL ?? "";
|
||||
const pool = await sharedPool(db);
|
||||
if (answer.trim() === SHARED_APPROVE && pool) {
|
||||
await switchToShared(db, project, pool.id, req.login, "superadmin");
|
||||
await askPmProject(db, project, { kind: "attention", text: m("✅ {project}: подписка Peppa FACTORY разрешена — агенты могут работать. Перейти на свою подписку можно в любой момент в настройках проекта.", { project: project.name }) });
|
||||
} else {
|
||||
await logEvent(db, { projectId: project.id, type: "project_subscription", payload: { login: req.login, choice: "shared_denied" } });
|
||||
await askPmProject(db, project, { kind: "attention", text: m("{project}: подписку Peppa FACTORY для этого проекта не разрешили. Подключите свою подписку Claude или ChatGPT — {url}", { project: project.name, url: `${web}/p/${project.key}` }) });
|
||||
}
|
||||
return true;
|
||||
}
|
||||
onAnswer(onSharedAnswer);
|
||||
|
||||
export type OwnSubscriptionKind = "claude_login" | "claude" | "codex_login" | "codex_key" | "existing";
|
||||
|
||||
const OWN_NAMES: Record<Exclude<OwnSubscriptionKind, "existing">, string> = { claude_login: "Claude", claude: "Claude", codex_login: "ChatGPT", codex_key: "Codex API" };
|
||||
|
||||
@ -211,7 +211,7 @@ export async function restartStalled(db: Db, s: SessionView, o: { now: Date; cfg
|
||||
// ── reminders and escalation ──────────────────────────────────────────────────────
|
||||
|
||||
const REMIND_KINDS = ["question", "permission", "approval"] as const;
|
||||
const KIND_RU: Record<string, string> = { question: m("Вопрос"), permission: m("Разрешение"), approval: m("Одобрение proposal") };
|
||||
const KIND_RU: Record<string, string> = { question: m("Вопрос"), permission: m("Разрешение"), approval: m("Одобрение плана") };
|
||||
|
||||
/**
|
||||
* Unanswered questions: reminders to the project's people after `remindMin` and 2×, then the
|
||||
|
||||
@ -210,4 +210,86 @@ export const merge: Dict = {
|
||||
"мастер-чату (только вы)": "the master chat (only you)",
|
||||
"Telegram в Peppa FACTORY не настроен": "Telegram is not configured in Peppa FACTORY",
|
||||
"Чтобы связать чат с группой, подключите своего бота: Настройки → Telegram": "To link a chat to a group, connect your own bot: Settings → Telegram",
|
||||
// PEP-116: the Peppa FACTORY subscription on request
|
||||
"❌ Отказать": "❌ Refuse",
|
||||
"Подписка Peppa FACTORY сейчас не предлагается — подключите свою": "The Peppa FACTORY subscription is not offered right now — connect your own",
|
||||
"Подписку Peppa FACTORY некому подтвердить — подключите свою": "There is no one to approve the Peppa FACTORY subscription — connect your own",
|
||||
"🔑 {login} просит подписку Peppa FACTORY для проекта «{project}» ({key}).\nАгенты проекта будут работать на подписке фабрики и тратить её лимит.\nРазрешить?": "🔑 {login} asks for the Peppa FACTORY subscription for the project «{project}» ({key}).\nThe project's agents will run on the factory's subscription and use up its limit.\nAllow?",
|
||||
"✅ {project}: подписка Peppa FACTORY разрешена — агенты могут работать. Перейти на свою подписку можно в любой момент в настройках проекта.": "✅ {project}: the Peppa FACTORY subscription is approved — agents can work. You can switch to your own subscription at any time in the project settings.",
|
||||
"{project}: подписку Peppa FACTORY для этого проекта не разрешили. Подключите свою подписку Claude или ChatGPT — {url}": "{project}: the Peppa FACTORY subscription was not approved for this project. Connect your own Claude or ChatGPT subscription — {url}",
|
||||
"Агенты работают на": "Agents run on",
|
||||
"подписке Peppa FACTORY": "the Peppa FACTORY subscription",
|
||||
"— общей для пользователей фабрики. Свою подписку можно подключить в любой момент ниже.": "— shared by the factory's users. You can connect your own subscription below at any time.",
|
||||
"Агенты работают на вашей подписке — пул «{name}».": "Agents run on your subscription — pool «{name}».",
|
||||
"Перейти на подписку Peppa FACTORY": "Switch to the Peppa FACTORY subscription",
|
||||
"Запрос на подписку Peppa FACTORY отправлен": "Peppa FACTORY subscription requested",
|
||||
"Попросить подписку Peppa FACTORY": "Ask for the Peppa FACTORY subscription",
|
||||
"Ждём подтверждения администратора фабрики — придёт сообщение.": "Waiting for the factory administrator to approve — you will get a message.",
|
||||
"Нужно подтверждение администратора фабрики.": "Needs the factory administrator's approval.",
|
||||
"Выберите, на чём будут работать агенты": "Choose what your agents will run on",
|
||||
"Своя подписка": "Your own subscription",
|
||||
"Агенты пишут код на вашей подписке Claude или ChatGPT — подойдёт обычная платная (Claude Pro или Max, ChatGPT Plus или Pro). Лимиты и расход — только ваши, пароль Peppa FACTORY не видит.": "Agents write code on your Claude or ChatGPT subscription — a regular paid one will do (Claude Pro or Max, ChatGPT Plus or Pro). The limits and usage are yours alone; Peppa FACTORY never sees your password.",
|
||||
"Подписка Peppa FACTORY": "Peppa FACTORY subscription",
|
||||
"Ничего подключать не нужно. Подписка общая для пользователей фабрики, поэтому её выдаёт администратор: вы отправляете запрос, он подтверждает — и агенты начинают работать. Когда она занята или упирается в лимит, агенты ждут. Перейти на свою можно в любой момент.": "Nothing to connect. The subscription is shared by the factory's users, so the administrator grants it: you send a request, they approve — and the agents start working. When it is busy or hits its limit, the agents wait. You can switch to your own at any time.",
|
||||
"Запрос отправлен — ждём подтверждения администратора. Вам придёт сообщение.": "Request sent — waiting for the administrator to approve. You will get a message.",
|
||||
"Работать на подписке Peppa FACTORY": "Run on the Peppa FACTORY subscription",
|
||||
"Нет своей подписки? Оформите её на claude.ai или chatgpt.com и вернитесь сюда. Другие способы (готовый токен, ключ API) и смена выбора — в «⋯ Настройки проекта → Подписки».": "No subscription of your own? Get one at claude.ai or chatgpt.com and come back here. Other ways (a ready token, an API key) and changing your choice — in «⋯ Project settings → Subscriptions».",
|
||||
"Сообщение от фабрики": "Message from the factory",
|
||||
"📝 Нужно одобрение плана": "📝 Plan needs approval",
|
||||
"👀 Сообщение от фабрики": "👀 Message from the factory",
|
||||
// PEP-117: chats for a product manager
|
||||
"📝 Агент составляет план стори": "📝 The agent is drafting the story's plan",
|
||||
"⏸ План готов и ждёт вашего одобрения": "⏸ The plan is ready and awaits your approval",
|
||||
"🔧 Стори вернулась агенту на доработку": "🔧 The story went back to the agent for rework",
|
||||
"▶️ Агент взял стори в работу": "▶️ The agent started working on the story",
|
||||
"👀 Стори готова — посмотрите результат и примите": "👀 The story is ready — review the result and accept it",
|
||||
"✅ Стори принята и закрыта": "✅ The story is accepted and closed",
|
||||
"⛔ Стори заблокирована — агент не может продолжать": "⛔ The story is blocked — the agent can't continue",
|
||||
"↩️ Стори вернулась в бэклог": "↩️ The story went back to the backlog",
|
||||
"• Статус: {to}": "• Status: {to}",
|
||||
"📦 Код проекта переехал: {from} → {to}": "📦 The project's code moved: {from} → {to}",
|
||||
"🔀 Изменения стори приняты в код проекта ({by})": "🔀 The story's changes were merged into the project's code ({by})",
|
||||
"🔀 Изменения стори приняты в код проекта": "🔀 The story's changes were merged into the project's code",
|
||||
"▶️ Агент начал работу": "▶️ The agent started working",
|
||||
"⚠️ Агент давно молчит ({n} мин) — Peppa FACTORY перезапустит его сама": "⚠️ The agent has been silent for a while ({n} min) — Peppa FACTORY will restart it by itself",
|
||||
"⚠️ Агент давно молчит — Peppa FACTORY перезапустит его сама": "⚠️ The agent has been silent for a while — Peppa FACTORY will restart it by itself",
|
||||
"⚠️ Агент споткнулся ({error}) — Peppa FACTORY продолжит сама": "⚠️ The agent stumbled ({error}) — Peppa FACTORY will carry on by itself",
|
||||
"⚠️ Агент остановился раньше времени — Peppa FACTORY перезапустит его сама": "⚠️ The agent stopped early — Peppa FACTORY will restart it by itself",
|
||||
"⏳ Подписка упёрлась в лимит — агент продолжит после сброса или на другой подписке": "⏳ The subscription hit its limit — the agent will continue after the reset or on another subscription",
|
||||
"🔁 Агент перезапущен после сбоя (попытка {attempt} из {of})": "🔁 The agent was restarted after a failure (attempt {attempt} of {of})",
|
||||
"🔁 Агент перезапущен после сбоя": "🔁 The agent was restarted after a failure",
|
||||
"❌ Агента не удалось перезапустить — нужна ваша помощь: откройте стори": "❌ The agent could not be restarted — your help is needed: open the story",
|
||||
"💸 Бюджет стори исчерпан — агент на паузе, нужен ваш ответ": "💸 The story's budget is used up — the agent is paused, your answer is needed",
|
||||
"🔀 Агент перешёл на другую подписку ({to}) и продолжает": "🔀 The agent switched to another subscription ({to}) and carries on",
|
||||
"🔀 Агент перешёл на другую подписку и продолжает": "🔀 The agent switched to another subscription and carries on",
|
||||
"⬆️ Задача оказалась сложнее — агент взял модель посильнее": "⬆️ The task turned out harder — the agent switched to a stronger model",
|
||||
"Напишите агенту этой стори — ответ на его вопрос или замечание, он увидит сразу": "Write to this story's agent — an answer to its question or a remark; it will see it right away",
|
||||
"Журнал: готовые стори, вопросы, релизы и сбои по всем вашим проектам. Отвечать удобнее в «Обзоре» или в чате проекта.": "A journal: finished stories, questions, releases and failures across all your projects. It's easier to reply in the «Overview» or in the project chat.",
|
||||
"Слева: чат с аналитиком — для вопросов и новых задач; «События агентов» — журнал; ниже — переписка по каждой стори с её агентом.": "On the left: the chat with the analyst — for questions and new tasks; «Agent events» — the journal; below — the conversation about each story with its agent.",
|
||||
"Журнал событий хранится {n} дн.; ваша переписка с аналитиком не удаляется.": "The event journal is kept for {n} days; your conversation with the analyst is never deleted.",
|
||||
"Все события по вашим проектам — журнал, справочно. Чтобы ответить агенту или написать аналитику, откройте чат проекта.": "All events across your projects — a journal, for reference. To reply to an agent or write to the analyst, open the project chat.",
|
||||
"← Обзор": "← Overview",
|
||||
"Все события": "All events",
|
||||
"журнал: что делали агенты": "journal: what the agents did",
|
||||
"Переписка по стори": "Story conversations",
|
||||
"Переписки по стори пока нет.": "No story conversations yet.",
|
||||
"Это журнал событий — писать сюда не нужно.": "This is the event journal — no need to write here.",
|
||||
"Выберите проект": "Choose a project",
|
||||
"Откройте чат с аналитиком": "Open the chat with the analyst",
|
||||
", чтобы задать вопрос или описать задачу.": " to ask a question or describe a task.",
|
||||
"Чаты — Peppa FACTORY": "Chats — Peppa FACTORY",
|
||||
"Здесь вы разговариваете с фабрикой: отвечаете агентам и пишете аналитику своего проекта — что узнать или что сделать.": "This is where you talk to the factory: answer agents and write to your project's analyst — what to find out or what to build.",
|
||||
"Ждут вашего ответа": "Waiting for your answer",
|
||||
"Сейчас от вас ничего не нужно — агенты работают сами.": "Nothing needed from you right now — the agents are working on their own.",
|
||||
"Ваши проекты": "Your projects",
|
||||
"— и у него появится чат с аналитиком.": "— and it will get a chat with the analyst.",
|
||||
"новые сообщения": "new messages",
|
||||
"{n} нов.": "{n} new",
|
||||
"агенты ждут вашего ответа": "agents are waiting for your answer",
|
||||
"ждут ответа: {n}": "awaiting answer: {n}",
|
||||
"Здесь пока тихо. Спросите аналитика, что с проектом, или опишите новую задачу.": "Quiet here so far. Ask the analyst how the project is going, or describe a new task.",
|
||||
"Написать аналитику": "Write to the analyst",
|
||||
"Нужна история?": "Need the history?",
|
||||
"Все события по вашим проектам": "All events across your projects",
|
||||
"— что делали агенты, релизы и сбои, справочно.": "— what the agents did, releases and failures, for reference.",
|
||||
};
|
||||
|
||||
@ -131,10 +131,13 @@ describe("master chat", () => {
|
||||
const p = await newProject();
|
||||
const ref = await newTask(p, "Платежи");
|
||||
await core.logEvent(db, { projectId: p.id, taskId: ref.task.id, type: "stalled", payload: { idleMinutes: 15 } });
|
||||
await core.logEvent(db, { projectId: p.id, taskId: ref.task.id, type: "restart_failed", payload: { error: "tmux" } });
|
||||
await core.logEvent(db, { projectId: p.id, taskId: ref.task.id, type: "progress", payload: { text: "половина готова" } });
|
||||
await core.syncChats(db);
|
||||
const feed = await core.masterFeed(db, pm);
|
||||
assert.ok(feed.some((m) => /Агент молчит 15 мин/.test(m.text) && m.threadKey === threadOf(ref.task.id) && m.projectKey === p.key));
|
||||
// PEP-117: only what needs the person is «важное»; hiccups Peppa handles itself stay in the project feed.
|
||||
assert.ok(feed.some((m) => /Агента не удалось перезапустить — нужна ваша помощь/.test(m.text) && m.threadKey === threadOf(ref.task.id) && m.projectKey === p.key));
|
||||
assert.ok(!feed.some((m) => /Агент давно молчит/.test(m.text)), "a stall Peppa restarts by itself is not important");
|
||||
assert.ok(!feed.some((m) => /половина готова/.test(m.text)), "progress is not important");
|
||||
|
||||
const master = await core.ensureMasterChat(db, pm.id);
|
||||
|
||||
@ -69,6 +69,29 @@ describe("PEP-106: project discussion", () => {
|
||||
assert.equal((await core.discussionUnread(db, member.id)).get(chat.id), 1);
|
||||
});
|
||||
|
||||
test("PEP-117: the overview card of a project chat — unread, open questions, the last message", async () => {
|
||||
const story = await core.createTask(db, { projectId: project.id, title: "Вопросная" });
|
||||
await core.askPm(db, story, { kind: "question", text: "Какой цвет кнопки?" });
|
||||
const forMember = (await core.chatOverview(db, member)).find((c) => c.key === "MTLK")!;
|
||||
assert.equal(forMember.name, "Talk");
|
||||
assert.equal(forMember.open, 1, "agents wait for an answer");
|
||||
assert.equal(forMember.unread, 1);
|
||||
assert.deepEqual([forMember.last?.who, forMember.last?.mine, forMember.last?.text], ["mock-owner", false, "ещё одно"]);
|
||||
const forOwner = (await core.chatOverview(db, owner)).find((c) => c.key === "MTLK")!;
|
||||
assert.equal(forOwner.last?.mine, true);
|
||||
assert.equal((await core.chatOverview(db, stranger)).length, 0, "only the user's own projects");
|
||||
});
|
||||
|
||||
test("PEP-117: status changes are said in words, not «статус X → Y»", async () => {
|
||||
const story = await core.createTask(db, { projectId: project.id, title: "Словами" });
|
||||
for (const [from, to] of [["backlog", "in_progress"], ["in_progress", "review"], ["review", "in_progress"], ["review", "done"]]) {
|
||||
await core.logEvent(db, { projectId: project.id, taskId: story.task.id, type: "task_updated", payload: { from: { status: from }, to: { status: to } } });
|
||||
}
|
||||
await core.syncChats(db);
|
||||
const texts = (await core.chatMessagesView(db, chat.id, { threadKey: `task:${story.task.id}` })).map((m) => m.text);
|
||||
assert.deepEqual(texts, ["▶️ Агент взял стори в работу", "👀 Стори готова — посмотрите результат и примите", "🔧 Стори вернулась агенту на доработку", "✅ Стори принята и закрыта"]);
|
||||
});
|
||||
|
||||
test("the discussion outlives the chat TTL; the projection of events does not", async () => {
|
||||
const later = new Date(Date.now() + core.chatTtlMs() + 86_400_000);
|
||||
await core.pruneChats(db, { now: later });
|
||||
|
||||
@ -261,15 +261,39 @@ describe("PEP-76: владелец выбирает подписку проек
|
||||
assert.match((await core.projectAgentWarning(db, p.id))!, /подписка не подключена/);
|
||||
|
||||
// No shared pool yet → only the own one is possible.
|
||||
await assert.rejects(runner.chooseSharedSubscription(db, owner, p), /не настроена/);
|
||||
await assert.rejects(runner.chooseSharedSubscription(db, owner, p), /не предлагается — подключите свою/);
|
||||
const sub = await runner.addSubscription(db, { provider: "claude", name: "mock-p76 общая", method: "token", secret: "sk-ant-oat01-" + "a".repeat(40), createdBy: admin.id });
|
||||
const pool = await core.createPool(db, { name: "mock-p76 общий", subscriptionIds: [sub.id], createdBy: admin.id });
|
||||
await core.setSharedPool(db, pool.id);
|
||||
// PEP-116: the factory's subscription is the superadmin's — an owner asks, the superadmin confirms.
|
||||
const boss = await core.upsertUserFromGitea(db, { id: 7602, login: "mock-p116-boss" }, { access_token: "x" });
|
||||
await core.setSetting(db, "platform.admins", ["mock-p116-boss"]);
|
||||
const platform = await core.createProject(db, { slug: "mock-p116-platform", key: "MPLT", name: "Platform", giteaOwner: "x", workspacePath: "/tmp/mock-p116-platform", ownerId: boss.id });
|
||||
process.env.PEPPA_PLATFORM_KEY = platform.key;
|
||||
try {
|
||||
await assert.rejects(runner.chooseSharedSubscription(db, stranger, p), /владелец/);
|
||||
await runner.chooseSharedSubscription(db, owner, p);
|
||||
assert.equal(await runner.chooseSharedSubscription(db, owner, p), "requested");
|
||||
assert.equal(await core.projectPool(db, p.id), null, "not switched before the superadmin says yes");
|
||||
assert.equal(await runner.chooseSharedSubscription(db, owner, p), "requested", "asking again changes nothing");
|
||||
const asks = (await core.pendingQuestions(db, platform.id)).filter((q) => q.text.includes("просит подписку Peppa FACTORY"));
|
||||
assert.equal(asks.length, 1, "one request, to the superadmin (platform project → Home and Telegram)");
|
||||
assert.match(asks[0]!.text, new RegExp(`${owner.login} просит подписку Peppa FACTORY для проекта «P76» \\(MPSUB\\)`));
|
||||
assert.deepEqual(asks[0]!.options, [runner.SHARED_APPROVE, runner.SHARED_DENY]);
|
||||
assert.equal((await runner.sharedRequest(db, p.id))!.login, owner.login);
|
||||
|
||||
// Refused: the project stays as it was, the owner is told to connect their own.
|
||||
await runner.answerAndDeliver(db, asks[0]!.id, runner.SHARED_DENY, "telegram");
|
||||
assert.equal(await core.projectPool(db, p.id), null);
|
||||
assert.equal(await runner.sharedRequest(db, p.id), null);
|
||||
assert.ok((await core.pendingQuestions(db, p.id)).some((q) => /не разрешили\. Подключите свою подписку/.test(q.text)));
|
||||
|
||||
// Asked again and approved: the project runs on the factory's subscription, the owner is told.
|
||||
assert.equal(await runner.chooseSharedSubscription(db, owner, p), "requested");
|
||||
const [again] = (await core.pendingQuestions(db, platform.id)).filter((q) => q.text.includes("просит подписку Peppa FACTORY"));
|
||||
await runner.answerAndDeliver(db, again!.id, runner.SHARED_APPROVE, "web");
|
||||
assert.equal((await core.projectPool(db, p.id))!.id, pool.id);
|
||||
assert.equal(await core.projectAgentWarning(db, p.id), null);
|
||||
assert.ok((await core.pendingQuestions(db, p.id)).some((q) => /подписка Peppa FACTORY разрешена/.test(q.text)));
|
||||
|
||||
await assert.rejects(runner.connectOwnSubscription(db, owner, p, "claude", ""), /Вставьте токен/);
|
||||
await assert.rejects(runner.connectOwnSubscription(db, owner, p, "claude", "не токен"), /не похоже на токен/);
|
||||
@ -283,8 +307,9 @@ describe("PEP-76: владелец выбирает подписку проек
|
||||
assert.equal(mine.length, 1);
|
||||
assert.equal(core.subscriptionSecret(mine[0]!), "sk-ant-oat01-" + "b".repeat(40));
|
||||
|
||||
// Back to shared and to own again without a token: the existing pool is reused.
|
||||
await runner.chooseSharedSubscription(db, owner, p);
|
||||
// A superadmin switches at once, without a request; back to own without a token: the existing pool is reused.
|
||||
assert.equal(await runner.chooseSharedSubscription(db, boss, p), "switched");
|
||||
assert.equal((await core.projectPool(db, p.id))!.id, pool.id);
|
||||
await runner.connectOwnSubscription(db, owner, p, "existing");
|
||||
assert.equal((await core.projectPool(db, p.id))!.id, own.id);
|
||||
assert.equal((await core.listSubscriptions(db)).filter((s) => s.createdBy === owner.id).length, 1);
|
||||
@ -299,6 +324,8 @@ describe("PEP-76: владелец выбирает подписку проек
|
||||
await runner.cancelLogin(db, subscriptionId!);
|
||||
} finally {
|
||||
await core.setSharedPool(db, null);
|
||||
delete process.env.PEPPA_PLATFORM_KEY;
|
||||
await core.deleteSetting(db, "platform.admins");
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
Loading…
Reference in New Issue
Block a user