diff --git a/apps/bot/src/bot.ts b/apps/bot/src/bot.ts index 9e777c17..011d3c09 100644 --- a/apps/bot/src/bot.ts +++ b/apps/bot/src/bot.ts @@ -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(); } diff --git a/apps/bot/src/render.ts b/apps/bot/src/render.ts index f76566d1..19fa61fa 100644 --- a/apps/bot/src/render.ts +++ b/apps/bot/src/render.ts @@ -19,7 +19,7 @@ export interface Rendered { buttons: InlineButton[][]; } -// callback_data (≤64 bytes): "q::", "s::" or "i::" (core/incidents.ts) +// callback_data (≤64 bytes): "q::", "s::" (resume|stop|ask) or "i::" (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(`tmux attach -t ${esc(ctx.session.tmuxName)}`); diff --git a/apps/web/app/(app)/actions.ts b/apps/web/app/(app)/actions.ts index 379dc093..c9dff167 100644 --- a/apps/web/app/(app)/actions.ts +++ b/apps/web/app/(app)/actions.ts @@ -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 () => { diff --git a/apps/web/app/(app)/layout.tsx b/apps/web/app/(app)/layout.tsx index 4639ee97..c3b7b00e 100644 --- a/apps/web/app/(app)/layout.tsx +++ b/apps/web/app/(app)/layout.tsx @@ -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 (
@@ -33,7 +36,7 @@ export default async function AppLayout({ children }: { children: ReactNode }) {
- {line ? : } + {line ? : } {children}
diff --git a/apps/web/app/(app)/p/[key]/page.tsx b/apps/web/app/(app)/p/[key]/page.tsx index 7e9ffaab..91338b8d 100644 --- a/apps/web/app/(app)/p/[key]/page.tsx +++ b/apps/web/app/(app)/p/[key]/page.tsx @@ -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("Своя подписка не подключена — агенты работают на общей.") )}

+ {askOffer && ( +
+ {t("Агенты стоят — администратор может одолжить свою подписку на время.")} + +
+ )} {/* 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

{t("Агенты не запустятся:")} {t.text(agentWarning)}. {pool ? (superadmin ? {t("Добавить ещё одну подписку")} → : {t("Смените подписку в «⋯ Настройки проекта → Подписки» или попросите суперадмина проверить её.")}) : null} + {askOffer && }

)} diff --git a/apps/web/app/(app)/subscriptions/page.tsx b/apps/web/app/(app)/subscriptions/page.tsx index 8752ab07..af41a7b8 100644 --- a/apps/web/app/(app)/subscriptions/page.tsx +++ b/apps/web/app/(app)/subscriptions/page.tsx @@ -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 ( @@ -282,8 +288,27 @@ export default async function Subscriptions({ searchParams }: { searchParams: Pr )} {addedSub && {addedSub.status === "active" ? t("Подписка «{name}» добавлена и активна", { name: addedSub.name }) : t("Подписка «{name}» добавлена", { name: addedSub.name })}} - {(problems.length > 0 || thin.length > 0) && ( -
+ {(problems.length > 0 || thin.length > 0 || requests.length > 0) && ( +
+ {requests.map((r) => ( +
+ {r.question && !r.question.answeredAt ? t.text(r.question.text) : t("{login} просит подписку для проекта «{project}»", { login: r.login, project: r.name })} + {r.question && !r.question.answeredAt ? ( +
+ {(r.question.options ?? []).map((o, i) => ( +
+ + + + ))} +
+ ) : r.remindAt ? ( + + {t("Напомню в")} + + ) : null} +
+ ))} {problems.map((s) => ( ))} diff --git a/apps/web/components/Accounting.tsx b/apps/web/components/Accounting.tsx index dd09be24..7cd8d9d9 100644 --- a/apps/web/components/Accounting.tsx +++ b/apps/web/components/Accounting.tsx @@ -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 (
@@ -134,6 +135,11 @@ export async function AgentsStrip({ line }: { line: AgentsLine }) { {t("Агенты продолжат в")} + {offers.map((o) => ( + + 1 ? o.name : undefined} size="xs" /> + + ))} )}
diff --git a/apps/web/components/SubscriptionRequest.tsx b/apps/web/components/SubscriptionRequest.tsx new file mode 100644 index 00000000..df888541 --- /dev/null +++ b/apps/web/components/SubscriptionRequest.tsx @@ -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 ( + + {name ? `${name}: ` : ""} + {t("Запрос отправлен — ждём ответа администратора")} + + ); + } + return ( +
+ + + + ); +} diff --git a/packages/shared/src/i18n/en/index.ts b/packages/shared/src/i18n/en/index.ts index ff65685d..5e785ca5 100644 --- a/packages/shared/src/i18n/en/index.ts +++ b/packages/shared/src/i18n/en/index.ts @@ -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 }; diff --git a/packages/shared/src/i18n/en/subscription-request.ts b/packages/shared/src/i18n/en/subscription-request.ts new file mode 100644 index 00000000..1f656ebf --- /dev/null +++ b/packages/shared/src/i18n/en/subscription-request.ts @@ -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)", +}; diff --git a/packages/shared/src/i18n/kk/index.ts b/packages/shared/src/i18n/kk/index.ts index 0c4376c7..a9a88e2a 100644 --- a/packages/shared/src/i18n/kk/index.ts +++ b/packages/shared/src/i18n/kk/index.ts @@ -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 }; diff --git a/packages/shared/src/i18n/kk/subscription-request.ts b/packages/shared/src/i18n/kk/subscription-request.ts new file mode 100644 index 00000000..c6263428 --- /dev/null +++ b/packages/shared/src/i18n/kk/subscription-request.ts @@ -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}: уақытша берілген жазылымның мерзімі бітті — агенттер сіздің жазылымыңызда жалғастырып жатыр.", + "(неактуально: агенты проекта снова работают)": "(өзекті емес: жоба агенттері қайта жұмыс істеп жатыр)", +}; diff --git a/packages/testkit/test/subscription-request.test.ts b/packages/testkit/test/subscription-request.test.ts index a84e68d5..a099a135 100644 --- a/packages/testkit/test/subscription-request.test.ts +++ b/packages/testkit/test/subscription-request.test.ts @@ -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>; 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");