PEP-186: кнопка запроса подписки — Telegram, полоса, проект, «Подписки»; переводы

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
peppa-bot 2026-11-16 23:49:10 +05:00
parent 4677fadfb4
commit eba01a2e0e
13 changed files with 178 additions and 12 deletions

View File

@ -78,7 +78,7 @@ import {
} from "@peppa/core";
import { projects, tasks, type Db } from "@peppa/db";
import { formatTaskKey, voiceStoriesEnabled } from "@peppa/shared";
import { acceptTask, answerAndDeliver, decideIncident, moveTask, postToChat, resumeSession, stopSession } from "@peppa/runner";
import { acceptTask, answerAndDeliver, decideIncident, moveTask, postToChat, REQUEST_SENT_TEXT, requestSubscription, resumeSession, stopSession } from "@peppa/runner";
import { AsyncLocalStorage } from "node:async_hooks";
import { eq, sql } from "drizzle-orm";
import { choiceToAnswer, esc, renderAnswered, renderQuestion } from "./render.ts";
@ -991,6 +991,15 @@ export function createBot(o: BotOptions) {
} else if (choice === "stop") {
await stopSession(db, s.id);
toast = tr("Агент остановлен ⏹");
} else if (choice === "ask") {
// PEP-186: «Попросить подписку у администратора» under a limit message.
try {
await requestSubscription(db, user, await projectForUser(db, user.id, s.projectId));
toast = REQUEST_SENT_TEXT;
} catch (e) {
toast = (e as Error).message;
}
wakeOutbox?.();
}
scheduleReconcile();
}

View File

@ -19,7 +19,7 @@ export interface Rendered {
buttons: InlineButton[][];
}
// callback_data (≤64 bytes): "q:<questionId>:<choice>", "s:<sessionId>:<action>" or "i:<incidentId>:<decision>" (core/incidents.ts)
// callback_data (≤64 bytes): "q:<questionId>:<choice>", "s:<sessionId>:<action>" (resume|stop|ask) or "i:<incidentId>:<decision>" (core/incidents.ts)
export function renderQuestion(
q: Question,
ctx: { taskKey: string | null; taskTitle: string | null; taskStatus?: string | null; session: SessionView | null; webUrl: string; /** PEP-154: the reader's view is «Инженер» — the terminal command is shown. */ engineer?: boolean; /** PEP-152: the message has technical details (kept on the site). */ details?: boolean },
@ -64,6 +64,8 @@ export function renderQuestion(
{ text: tr("🔁 Перезапустить"), callback_data: `s:${s.id}:resume` },
{ text: tr("⏹ Остановить"), callback_data: `s:${s.id}:stop` },
]);
// PEP-186: agents stand on a limit of their subscription — ask the superadmin for one.
if (s.status === "rate_limited" && s.subscriptionId != null) buttons.push([{ text: tr("🙋 Попросить подписку у администратора"), callback_data: `s:${s.id}:ask` }]);
}
}
if (ctx.session && ctx.engineer) lines.push(`<code>tmux attach -t ${esc(ctx.session.tmuxName)}</code>`);

View File

@ -66,7 +66,7 @@ import { attachmentLabel, fixFeedback, linkAttachments, linkFeedback, parseAttac
import { deleteProject } from "@peppa/runner";
import { bugsinkFromEnv } from "@peppa/bugsink";
import { loadEnv } from "@peppa/shared";
import { pauseProject, resumeProject, acceptStory, autoPublish, fixStory, budgetChanged, resolveTaskById, deployProd, bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, grantRepoAccess, moveTask, provisionProjectOnce, projectNamespace, setProjectVisibility, shareProject, unshareProject, type BoardColumn, resumeSession, sendToSession, syncSessionAttachments, startSession, stopSession, type Provider, startFreeRunner, renameRunner, promoteRunner, queueTaskOnRunner, managesProject, saveAgentsMd, cancelOwnLogin, finishOwnClaudeLogin, connectOwnSubscription, removeOwnSubscription, type OwnSubscriptionKind, chooseSharedSubscription } from "@peppa/runner";
import { pauseProject, resumeProject, acceptStory, autoPublish, fixStory, budgetChanged, resolveTaskById, deployProd, bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, grantRepoAccess, moveTask, provisionProjectOnce, projectNamespace, setProjectVisibility, shareProject, unshareProject, type BoardColumn, resumeSession, sendToSession, syncSessionAttachments, startSession, stopSession, type Provider, startFreeRunner, renameRunner, promoteRunner, queueTaskOnRunner, managesProject, saveAgentsMd, cancelOwnLogin, finishOwnClaudeLogin, connectOwnSubscription, removeOwnSubscription, type OwnSubscriptionKind, chooseSharedSubscription, requestSubscription } from "@peppa/runner";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { asWebActor, requireUser, words } from "@/lib/auth";
@ -795,6 +795,14 @@ export async function chooseSharedSubscriptionAction(f: FormData) {
});
}
/** PEP-186: «Попросить подписку у администратора». */
export async function requestSubscriptionAction(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
await requestSubscription(db, user, await projectForUser(db, user.id, Number(str(f, "projectId"))));
});
}
export async function connectOwnSubscriptionAction(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {

View File

@ -1,6 +1,7 @@
import type { ReactNode } from "react";
import { accountUsageForUser, agentsLine, getNotifyPrefs, isSuperadmin, pendingFeedbackCount } from "@peppa/core";
import { db } from "@/lib/db";
import { subscriptionRequestOffers } from "@peppa/runner";
import { requireUser, uiMode } from "@/lib/auth";
import { navCounts } from "@/lib/queries";
import { WordsProvider } from "@/components/Words";
@ -26,6 +27,8 @@ export default async function AppLayout({ children }: { children: ReactNode }) {
// reads one line: agents work, or when they go on.
const accounts = engineer ? await accountUsageForUser(db, user).catch(() => []) : [];
const line = engineer ? null : await agentsLine(db, user).catch(() => ({ state: "working" as const }));
// PEP-186: agents stand — the owner may ask the superadmin for a subscription right from the strip.
const offers = line?.state === "paused" ? await subscriptionRequestOffers(db, user).catch(() => []) : [];
return (
<WordsProvider mode={mode}>
<div className="min-h-dvh md:grid md:grid-cols-[232px_minmax(0,1fr)]">
@ -33,7 +36,7 @@ export default async function AppLayout({ children }: { children: ReactNode }) {
<Sidebar login={user.login} avatarUrl={user.avatarUrl} counts={{ ...counts, feedback: superadmin ? await pendingFeedbackCount(db) : 0 }} superadmin={superadmin} engineer={engineer} />
<div className="flex min-w-0 flex-col pb-16 md:pb-0">
<VersionWatch boot={bootId()} />
{line ? <AgentsStrip line={line} /> : <UsageStrip accounts={accounts} admin={superadmin} />}
{line ? <AgentsStrip line={line} offers={offers} /> : <UsageStrip accounts={accounts} admin={superadmin} />}
{children}
</div>
<CommandPalette />

View File

@ -3,7 +3,7 @@ import { ProductCard } from "@/components/ProductCard";
import { PublishPanel } from "@/components/PublishPanel";
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, sharedRequest } from "@peppa/runner";
import { columnOf, currentReleases, describeRepo, isPlatform, listReleases, bugsinkWebhookBase, openPulls, platformReleaseCandidate, platformReleaseOffers, ownPendingLogins, readAgentsMd, repoOverview, type Release, sharedRequest, subscriptionRequestOffer } from "@peppa/runner";
import { getProjectPause, getPublishMode, poolSubscriptions, PRODUCT_PROJECT_TABS, 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 { productNeeds, lastProductReview } from "@peppa/core";
import { LiveRefresh } from "@/components/LiveRefresh";
@ -25,6 +25,7 @@ import { PauseBanner, PauseControl } from "@/components/ProjectPause";
import { ProjectSecretsPanel } from "@/components/ProjectSecrets";
import { Workspace } from "@/components/Workspace";
import { SubscriptionSetup } from "@/components/SubscriptionSetup";
import { SubscriptionRequestButton } from "@/components/SubscriptionRequest";
import { PoolSubscriptions, PoolSummary, PoolSwitches } from "@/components/PoolSubscriptions";
import { requireUser, words } from "@/lib/auth";
import { cn } from "@/lib/utils";
@ -177,6 +178,8 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
// 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);
// PEP-186: agents stand on a limit or a broken sign-in — ask the superadmin for a subscription.
const askOffer = await subscriptionRequestOffer(db, user, p.id).catch(() => null);
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.
@ -393,6 +396,12 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
engineer ? t("Пул не назначен — агенты работают на входе машины.") : t("Своя подписка не подключена — агенты работают на общей.")
)}
</p>
{askOffer && (
<div className="flex flex-wrap items-center gap-2 text-sm">
<span>{t("Агенты стоят — администратор может одолжить свою подписку на время.")}</span>
<SubscriptionRequestButton projectId={p.id} offer={askOffer} back={`${back}#subscription`} />
</div>
)}
{/* PEP-116: on the factory's subscription a user sees its state, not the accounts behind it. */}
{poolView && (superadmin || poolView.pool.id !== shared?.id) && (
<>
@ -574,6 +583,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
<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)}.
{pool ? (superadmin ? <a href={`/subscriptions#pool-${pool.id}`} className="text-primary">{t("Добавить ещё одну подписку")} →</a> : <span className="text-muted-foreground">{t("Смените подписку в «⋯ Настройки проекта → Подписки» или попросите суперадмина проверить её.")}</span>) : null}
{askOffer && <SubscriptionRequestButton projectId={p.id} offer={askOffer} back={back} />}
</p>
)}

View File

@ -1,7 +1,9 @@
import { notFound } from "next/navigation";
import { ExternalLink, KeyRound, Plus, RefreshCw } from "lucide-react";
import { isSuperadmin, listSubscriptions, OPENCODE_KEY_ENV, PROVIDER_NAMES, poolOverviews, type PoolOverview, type SubscriptionView } from "@peppa/core";
import { pendingLogin, pollCodexLogin, type PendingLogin, backfillCodexAccounts } from "@peppa/runner";
import { getQuestion, isSuperadmin, listSubscriptions, OPENCODE_KEY_ENV, PROVIDER_NAMES, poolOverviews, type PoolOverview, type SubscriptionView } from "@peppa/core";
import { pendingLogin, pollCodexLogin, type PendingLogin, backfillCodexAccounts, openSubscriptionRequests } from "@peppa/runner";
import { answerQuestion } from "@/app/(app)/actions";
import { LocalTime } from "@/components/LocalTime";
import { AutoRefresh } from "@/components/AutoRefresh";
import { PoolSubscriptions, PoolSummary, PoolSwitches } from "@/components/PoolSubscriptions";
import { Hidden } from "@/components/cards";
@ -264,6 +266,10 @@ export default async function Subscriptions({ searchParams }: { searchParams: Pr
const inSet = new Set(sets.flatMap((o) => o.subscriptions.map((s) => s.id)));
const loose = subs.filter((s) => !inSet.has(s.id) && s.status !== "auth_error" && s.status !== "pending");
const addedSub = added ? subs.find((s) => s.id === Number(added)) : undefined;
// PEP-186: owners asking for a subscription — answered right here, same buttons as on Home.
const requests = await Promise.all(
(await openSubscriptionRequests(db)).map(async (r) => ({ ...r, question: r.questionId ? await getQuestion(db, r.questionId).catch(() => null) : null })),
);
return (
<Workspace>
@ -282,8 +288,27 @@ export default async function Subscriptions({ searchParams }: { searchParams: Pr
)}
{addedSub && <Notice>{addedSub.status === "active" ? t("Подписка «{name}» добавлена и активна", { name: addedSub.name }) : t("Подписка «{name}» добавлена", { name: addedSub.name })}</Notice>}
{(problems.length > 0 || thin.length > 0) && (
<Section title={t("Нужно ваше внимание")} count={problems.length + thin.length}>
{(problems.length > 0 || thin.length > 0 || requests.length > 0) && (
<Section title={t("Нужно ваше внимание")} count={problems.length + thin.length + requests.length}>
{requests.map((r) => (
<div key={r.projectId} data-subscription-request={r.key} className="flex flex-col gap-2 rounded-md border border-warn/40 px-3 py-2 text-sm">
<span>{r.question && !r.question.answeredAt ? t.text(r.question.text) : t("{login} просит подписку для проекта «{project}»", { login: r.login, project: r.name })}</span>
{r.question && !r.question.answeredAt ? (
<div className="flex flex-wrap gap-2">
{(r.question.options ?? []).map((o, i) => (
<form key={o} action={answerQuestion}>
<Hidden fields={{ questionId: r.question!.id, choice: o, back: "/subscriptions" }} />
<Button size="xs" variant={i === 0 ? "default" : "outline"}>{t.text(o)}</Button>
</form>
))}
</div>
) : r.remindAt ? (
<span className="text-xs text-muted-foreground">
{t("Напомню в")} <LocalTime iso={r.remindAt.toISOString()} />
</span>
) : null}
</div>
))}
{problems.map((s) => (
<Problem key={s.id} s={s} login={logins.get(s.id) ?? null} t={t} />
))}

View File

@ -28,6 +28,7 @@ import {
type WindowView,
} from "@peppa/core";
import { Hidden } from "@/components/cards";
import { SubscriptionRequestButton } from "@/components/SubscriptionRequest";
import { eventLine } from "@/components/RunnerConsole";
import { LocalTime } from "@/components/LocalTime";
import { ago, Empty } from "@/components/common";
@ -119,7 +120,7 @@ export async function UsageStrip({ accounts, admin }: { accounts: AccountUsage[]
}
/** PEP-121: the same bar for a product manager — one line, no shares, windows or account names. */
export async function AgentsStrip({ line }: { line: AgentsLine }) {
export async function AgentsStrip({ line, offers = [] }: { line: AgentsLine; /** PEP-186: projects where the user may ask the superadmin for a subscription. */ offers?: Array<{ projectId: number; key: string; name: string; offer: "can" | "sent" }> }) {
const t = await getT();
return (
<div role="status" data-agents-line={line.state} className="flex min-h-8 items-center gap-1.5 border-b bg-sidebar/40 px-4 py-1 text-xs text-muted-foreground md:px-8">
@ -134,6 +135,11 @@ export async function AgentsStrip({ line }: { line: AgentsLine }) {
<span>
{t("Агенты продолжат в")} <LocalTime iso={line.until.toISOString()} />
</span>
{offers.map((o) => (
<span key={o.projectId} className="ml-2">
<SubscriptionRequestButton projectId={o.projectId} offer={o.offer} back={`/p/${o.key}`} name={offers.length > 1 ? o.name : undefined} size="xs" />
</span>
))}
</>
)}
</div>

View File

@ -0,0 +1,28 @@
// PEP-186: «Попросить подписку у администратора» — agents stand on a limit (or a broken sign-in)
// of the project's subscription; the owner or a member asks the superadmin to lend one.
import { HandHelping } from "lucide-react";
import { getT } from "@/lib/i18n";
import { Hidden } from "@/components/cards";
import { Button } from "@/components/ui/button";
import { requestSubscriptionAction } from "@/app/(app)/actions";
export async function SubscriptionRequestButton({ projectId, offer, back, name, size = "sm" }: { projectId: number; offer: "can" | "sent"; back: string; name?: string; size?: "xs" | "sm" }) {
const t = await getT();
if (offer === "sent") {
return (
<span data-subscription-request="sent" className="text-muted-foreground">
{name ? `${name}: ` : ""}
{t("Запрос отправлен — ждём ответа администратора")}
</span>
);
}
return (
<form action={requestSubscriptionAction} data-subscription-request="can" className="inline">
<Hidden fields={{ projectId, back }} />
<Button size={size} variant="outline">
<HandHelping className="size-3.5" />
{name ? t("Попросить подписку у администратора — {project}", { project: name }) : t("Попросить подписку у администратора")}
</Button>
</form>
);
}

View File

@ -16,5 +16,6 @@ import { merge_c } from "./merge-c.ts";
import { merge_d } from "./merge-d.ts";
import { feedback } from "./feedback.ts";
import { attachments } from "./attachments.ts";
import { subscriptionRequest } from "./subscription-request.ts";
export const en: Dict = { ...common, ...story, ...project, ...admin, ...settings, ...help, ...runner, ...bot, ...merge, ...merge_a, ...merge_b, ...merge_c, ...merge_d, ...feedback, ...attachments };
export const en: Dict = { ...common, ...story, ...project, ...admin, ...settings, ...help, ...runner, ...bot, ...merge, ...merge_a, ...merge_b, ...merge_c, ...merge_d, ...feedback, ...attachments, ...subscriptionRequest };

View File

@ -0,0 +1,34 @@
import type { Dict } from "../index.ts";
// PEP-186: asking the superadmin for a subscription when the project's one ran out.
export const subscriptionRequest: Dict = {
"Агенты стоят — администратор может одолжить свою подписку на время.": "Agents are waiting — the administrator can lend a subscription for a while.",
"{login} просит подписку для проекта «{project}»": "{login} asks for a subscription for the project “{project}”",
"Напомню в": "I will remind you at",
"Запрос отправлен — ждём ответа администратора": "Request sent — waiting for the administrator",
"Попросить подписку у администратора — {project}": "Ask the administrator for a subscription — {project}",
"Попросить подписку у администратора": "Ask the administrator for a subscription",
"🙋 Попросить подписку у администратора": "🙋 Ask the administrator for a subscription",
"срок одолженной подписки кончился": "the lent subscription has expired",
"Одолжить до сброса": "Lend until the reset",
"Одолжить на сутки": "Lend for a day",
"Отказать": "Refuse",
"Напомнить позже": "Remind me later",
"Сейчас некому одолжить подписку — агенты продолжат, когда лимит сбросится": "Nobody can lend a subscription right now — agents will continue when the limit resets",
"🙋 {login} просит подписку для проекта «{project}»: агенты стоят до {time}.": "🙋 {login} asks for a subscription for the project “{project}”: agents are waiting until {time}.",
"🙋 {login} просит подписку для проекта «{project}»: агенты стоят, время сброса неизвестно.": "🙋 {login} asks for a subscription for the project “{project}”: agents are waiting, the reset time is unknown.",
"Фабрика одолжит свободную подписку сама — выберите срок.": "The factory will pick a free subscription itself — choose for how long.",
"Свободной подписки сейчас нет.": "There is no free subscription right now.",
"Вы администратор — одолжите подписку сами в разделе «Подписки»": "You are an administrator — lend a subscription yourself in “Subscriptions”",
"Администратор уже одолжил подписку этому проекту": "The administrator has already lent a subscription to this project",
"Агенты проекта сейчас работают — подписка не нужна": "The project's agents are working now — no subscription is needed",
"Сегодня вы уже просили подписку {n} раза — попробуйте завтра": "You have already asked for a subscription {n} times today — try tomorrow",
"{project}: администратор согласился, но свободной подписки сейчас нет. Агенты продолжат в {time}, когда сбросится лимит.": "{project}: the administrator agreed, but there is no free subscription right now. Agents will continue at {time}, when the limit resets.",
"{project}: администратор согласился, но свободной подписки сейчас нет. Попросите ещё раз позже.": "{project}: the administrator agreed, but there is no free subscription right now. Ask again later.",
"✅ {project}: администратор одолжил подписку до {time} — агенты продолжают.": "✅ {project}: the administrator lent a subscription until {time} — agents continue.",
"{project}: администратор отказал в подписке: {reason}": "{project}: the administrator refused a subscription: {reason}",
"{project}: администратор отказал в подписке. Агенты продолжат, когда сбросится лимит.": "{project}: the administrator refused a subscription. Agents will continue when the limit resets.",
"{project}: срок одолженной подписки кончился. Агенты продолжат в {time}, когда сбросится лимит вашей подписки.": "{project}: the lent subscription has expired. Agents will continue at {time}, when your subscription's limit resets.",
"{project}: срок одолженной подписки кончился — агенты продолжают на вашей подписке.": "{project}: the lent subscription has expired — agents continue on your subscription.",
"(неактуально: агенты проекта снова работают)": "(no longer relevant: the project's agents are working again)",
};

View File

@ -16,5 +16,6 @@ import { settings } from "./settings.ts";
import { story } from "./story.ts";
import { feedback } from "./feedback.ts";
import { attachments } from "./attachments.ts";
import { subscriptionRequest } from "./subscription-request.ts";
export const kk: Dict = { ...admin, ...bot, ...common, ...help, ...mergeA, ...mergeB, ...mergeC, ...mergeD, ...merge, ...project, ...runner, ...settings, ...story, ...feedback, ...attachments };
export const kk: Dict = { ...admin, ...bot, ...common, ...help, ...mergeA, ...mergeB, ...mergeC, ...mergeD, ...merge, ...project, ...runner, ...settings, ...story, ...feedback, ...attachments, ...subscriptionRequest };

View File

@ -0,0 +1,34 @@
import type { Dict } from "../index.ts";
/** Kazakh (PEP-99) for en/subscription-request.ts — keys are the Russian strings. */
export const subscriptionRequest: Dict = {
"Агенты стоят — администратор может одолжить свою подписку на время.": "Агенттер тоқтап тұр — әкімші өз жазылымын уақытша бере алады.",
"{login} просит подписку для проекта «{project}»": "{login} «{project}» жобасы үшін жазылым сұрайды",
"Напомню в": "Еске саламын:",
"Запрос отправлен — ждём ответа администратора": "Сұрау жіберілді — әкімшінің жауабын күтеміз",
"Попросить подписку у администратора — {project}": "Әкімшіден жазылым сұрау — {project}",
"Попросить подписку у администратора": "Әкімшіден жазылым сұрау",
"🙋 Попросить подписку у администратора": "🙋 Әкімшіден жазылым сұрау",
"срок одолженной подписки кончился": "уақытша берілген жазылымның мерзімі бітті",
"Одолжить до сброса": "Лимит жаңарғанша беру",
"Одолжить на сутки": "Бір тәулікке беру",
"Отказать": "Бас тарту",
"Напомнить позже": "Кейінірек еске салу",
"Сейчас некому одолжить подписку — агенты продолжат, когда лимит сбросится": "Қазір жазылым беретін ешкім жоқ — лимит жаңарғанда агенттер жалғастырады",
"🙋 {login} просит подписку для проекта «{project}»: агенты стоят до {time}.": "🙋 {login} «{project}» жобасы үшін жазылым сұрайды: агенттер {time} дейін тоқтап тұр.",
"🙋 {login} просит подписку для проекта «{project}»: агенты стоят, время сброса неизвестно.": "🙋 {login} «{project}» жобасы үшін жазылым сұрайды: агенттер тоқтап тұр, лимиттің жаңару уақыты белгісіз.",
"Фабрика одолжит свободную подписку сама — выберите срок.": "Фабрика бос жазылымды өзі таңдайды — мерзімін таңдаңыз.",
"Свободной подписки сейчас нет.": "Қазір бос жазылым жоқ.",
"Вы администратор — одолжите подписку сами в разделе «Подписки»": "Сіз әкімшісіз — жазылымды «Жазылымдар» бөлімінде өзіңіз беріңіз",
"Администратор уже одолжил подписку этому проекту": "Әкімші бұл жобаға жазылымды әлдеқашан берген",
"Агенты проекта сейчас работают — подписка не нужна": "Жоба агенттері қазір жұмыс істеп жатыр — жазылым қажет емес",
"Сегодня вы уже просили подписку {n} раза — попробуйте завтра": "Бүгін жазылымды {n} рет сұрадыңыз — ертең көріңіз",
"{project}: администратор согласился, но свободной подписки сейчас нет. Агенты продолжат в {time}, когда сбросится лимит.": "{project}: әкімші келісті, бірақ қазір бос жазылым жоқ. Лимит жаңарғанда, {time} кезінде агенттер жалғастырады.",
"{project}: администратор согласился, но свободной подписки сейчас нет. Попросите ещё раз позже.": "{project}: әкімші келісті, бірақ қазір бос жазылым жоқ. Кейінірек тағы сұраңыз.",
"✅ {project}: администратор одолжил подписку до {time} — агенты продолжают.": "✅ {project}: әкімші жазылымды {time} дейін берді — агенттер жалғастырып жатыр.",
"{project}: администратор отказал в подписке: {reason}": "{project}: әкімші жазылым беруден бас тартты: {reason}",
"{project}: администратор отказал в подписке. Агенты продолжат, когда сбросится лимит.": "{project}: әкімші жазылым беруден бас тартты. Лимит жаңарғанда агенттер жалғастырады.",
"{project}: срок одолженной подписки кончился. Агенты продолжат в {time}, когда сбросится лимит вашей подписки.": "{project}: уақытша берілген жазылымның мерзімі бітті. Сіздің жазылымыңыздың лимиті жаңарғанда, {time} кезінде агенттер жалғастырады.",
"{project}: срок одолженной подписки кончился — агенты продолжают на вашей подписке.": "{project}: уақытша берілген жазылымның мерзімі бітті — агенттер сіздің жазылымыңызда жалғастырып жатыр.",
"(неактуально: агенты проекта снова работают)": "(өзекті емес: жоба агенттері қайта жұмыс істеп жатыр)",
};

View File

@ -7,6 +7,7 @@ import { stripAsIs } from "@peppa/shared/i18n";
import { core, db, project, runner, setDefaultOwner, teardown } from "./helpers.ts";
process.env.PEPPA_SECRET = "mock-secret-for-tests";
const { renderQuestion } = await import("@peppa/bot/render");
type User = Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
let admin: User;
@ -55,6 +56,10 @@ describe("Попросить подписку у администратора (P
await p.waitStatus(sid, "rate_limited");
assert.equal(await runner.subscriptionRequestOffer(db, owner, proj.id), "can");
// Telegram: the limit message has the button right there.
const limitMsg = await p.waitQuestion(sid, "attention");
const tg = renderQuestion(limitMsg, { taskKey: p.taskKey, taskTitle: null, session: await core.getSession(db, sid), webUrl: "http://peppa.test" });
assert.ok(tg.buttons.flat().some((b) => b.callback_data === `s:${sid}:ask`), "«Попросить подписку» under the limit message");
assert.equal(await runner.subscriptionRequestOffer(db, admin, proj.id), null, "a superadmin lends himself");
await runner.requestSubscription(db, owner, proj);
assert.equal(await runner.subscriptionRequestOffer(db, owner, proj.id), "sent");