PEP-121: one-line agents strip for «Продакт»; subscription names only for a superadmin and the one who connected it
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
parent
6f5aa007ac
commit
b977e7b5b9
@ -1,12 +1,12 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { accountUsageForUser, getNotifyPrefs, isSuperadmin } from "@peppa/core";
|
||||
import { accountUsageForUser, agentsLine, getNotifyPrefs, isSuperadmin } from "@peppa/core";
|
||||
import { db } from "@/lib/db";
|
||||
import { requireUser, uiMode } from "@/lib/auth";
|
||||
import { navCounts } from "@/lib/queries";
|
||||
import { Sidebar } from "@/components/Sidebar";
|
||||
import { AttentionBadge } from "@/components/AttentionBadge";
|
||||
import { CommandPalette } from "@/components/CommandPalette";
|
||||
import { UsageStrip } from "@/components/Accounting";
|
||||
import { AgentsStrip, UsageStrip } from "@/components/Accounting";
|
||||
import { VersionWatch } from "@/components/VersionWatch";
|
||||
import { bootId } from "@/lib/boot";
|
||||
|
||||
@ -19,15 +19,17 @@ export default async function AppLayout({ children }: { children: ReactNode }) {
|
||||
const { sound } = await getNotifyPrefs(db, user.id);
|
||||
const superadmin = await isSuperadmin(db, user);
|
||||
const engineer = (await uiMode()) === "engineer";
|
||||
// PEP-5: subscription limit windows over every page.
|
||||
const accounts = await accountUsageForUser(db, user).catch(() => []);
|
||||
// PEP-5: subscription limit windows over every page — for «Инженер»; PEP-121: «Продакт»
|
||||
// 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 }));
|
||||
return (
|
||||
<div className="min-h-dvh md:grid md:grid-cols-[232px_minmax(0,1fr)]">
|
||||
<AttentionBadge count={counts.questions + counts.waitingRunners} sound={sound} />
|
||||
<Sidebar login={user.login} avatarUrl={user.avatarUrl} counts={counts} superadmin={superadmin} engineer={engineer} />
|
||||
<div className="flex min-w-0 flex-col pb-16 md:pb-0">
|
||||
<VersionWatch boot={bootId()} />
|
||||
<UsageStrip accounts={accounts} admin={superadmin} />
|
||||
{line ? <AgentsStrip line={line} /> : <UsageStrip accounts={accounts} admin={superadmin} />}
|
||||
{children}
|
||||
</div>
|
||||
<CommandPalette />
|
||||
|
||||
@ -118,7 +118,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
||||
// PEP-31: the project's pool has no working subscription — agents won't start.
|
||||
const agentWarning = await projectAgentWarning(db, p.id);
|
||||
// PEP-107: each subscription of the pool — at work, free, limited until…, usage of its window.
|
||||
const poolView = pool ? await poolOverview(db, pool.id) : null;
|
||||
const poolView = pool ? await poolOverview(db, pool.id, new Date(), { admin: superadmin, userId: user.id }) : null;
|
||||
// PEP-80: the owner's own subscriptions — a ChatGPT device login in progress, and whether a pool exists already.
|
||||
const mayChoose = isOwner || superadmin;
|
||||
// PEP-128: a pool whose every sign-in failed or is unfinished is as good as no subscription —
|
||||
@ -344,7 +344,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
||||
Агенты работают на <b>подписке Peppa FACTORY</b> — общей для пользователей фабрики. Свою подписку можно подключить в любой момент ниже.
|
||||
</>
|
||||
) : (
|
||||
<>Агенты работают на вашей подписке — пул «{pool.name}».</>
|
||||
<>Агенты работают на своей подписке проекта{superadmin ? <> — пул «{pool.name}»</> : null}.</>
|
||||
)
|
||||
) : agentWarning ? (
|
||||
<b>Подписка не выбрана — агенты не запустятся.</b>
|
||||
|
||||
@ -8,7 +8,7 @@ import { Input } from "@/components/ui/input";
|
||||
import { NewRunnerForm } from "@/components/Runners";
|
||||
import { SettingsDialog } from "@/components/SettingsDialog";
|
||||
import { Workspace } from "@/components/Workspace";
|
||||
import { requireUser } from "@/lib/auth";
|
||||
import { requireUser, subscriptionNamesVisible } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { inbox, sessionEvents } from "@/lib/queries";
|
||||
import { cn } from "@/lib/utils";
|
||||
@ -54,7 +54,7 @@ export default async function Runners({ searchParams }: { searchParams: Promise<
|
||||
const selected = (id && all.find((s) => s.id === Number(id))) || shown[0];
|
||||
const back = url({ ...base, id: selected?.id });
|
||||
const aside = selected ? (
|
||||
<RunnerDetails s={selected} questions={asking.get(selected.id) ?? []} events={await sessionEvents(selected.id)} steps={await sessionSteps(db, selected.id)} stories={await runnerStories(db, selected.id)} back={back} closeHref={url(base)} chosen={!!id} />
|
||||
<RunnerDetails s={selected} questions={asking.get(selected.id) ?? []} events={await sessionEvents(selected.id)} steps={await sessionSteps(db, selected.id)} stories={await runnerStories(db, selected.id)} back={back} closeHref={url(base)} chosen={!!id} names={await subscriptionNamesVisible()} />
|
||||
) : null;
|
||||
|
||||
return (
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
// Accounting blocks (PEP-5/43/47/48): the usage strip on top, story budget, project metrics, journal.
|
||||
import Link from "next/link";
|
||||
import type { ReactNode } from "react";
|
||||
import { Gauge } from "lucide-react";
|
||||
import { Gauge, Hourglass, Play } from "lucide-react";
|
||||
import {
|
||||
accountPeak,
|
||||
actorLabel,
|
||||
@ -18,6 +18,7 @@ import {
|
||||
PROVIDER_NAMES,
|
||||
usageTotals,
|
||||
type AccountUsage,
|
||||
type AgentsLine,
|
||||
type Budget,
|
||||
type JournalEntry,
|
||||
type MetricsBucket,
|
||||
@ -112,6 +113,27 @@ export function UsageStrip({ accounts, admin }: { accounts: AccountUsage[]; admi
|
||||
);
|
||||
}
|
||||
|
||||
/** PEP-121: the same bar for a product manager — one line, no shares, windows or account names. */
|
||||
export function AgentsStrip({ line }: { line: AgentsLine }) {
|
||||
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">
|
||||
{line.state === "working" ? (
|
||||
<>
|
||||
<Play className="size-3.5" />
|
||||
Агенты работают
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Hourglass className="size-3.5" />
|
||||
<span>
|
||||
Агенты продолжат в <LocalTime iso={line.until.toISOString()} />
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export const usagePeakSort = (a: AccountUsage[]) => [...a].sort((x, y) => accountPeak(y) - accountPeak(x));
|
||||
|
||||
/** PEP-5: one line under a runner card. */
|
||||
|
||||
@ -19,7 +19,7 @@ function tone(s: PoolSubscriptionState): "ok" | "warn" | "danger" | "muted" | "p
|
||||
export function PoolSubscriptions({ o, action }: { o: PoolOverview; action?: (s: PoolSubscriptionState) => ReactNode }) {
|
||||
if (!o.subscriptions.length) return <p className="m-0 text-sm text-muted-foreground">В пуле нет подписок.</p>;
|
||||
return (
|
||||
<ul className="m-0 flex list-none flex-col gap-1.5 p-0" aria-label={`Подписки пула «${o.pool.name}»`}>
|
||||
<ul className="m-0 flex list-none flex-col gap-1.5 p-0" aria-label="Подписки проекта">
|
||||
{o.subscriptions.map((s) => (
|
||||
<li key={s.id} className="flex flex-wrap items-center gap-x-2 gap-y-1 text-sm" data-pool-subscription={s.id}>
|
||||
<span className="font-medium">{s.name}</span>
|
||||
|
||||
@ -3,6 +3,7 @@ import Link from "next/link";
|
||||
import { SquareTerminal, X } from "lucide-react";
|
||||
import { FINISHED_SESSION_STATUSES, PROVIDER_NAMES, type RunnerTaskView, type SessionView, type StepView } from "@peppa/core";
|
||||
import { RunnerStories } from "@/components/Runners";
|
||||
import { SubscriptionName } from "@/components/SubscriptionName";
|
||||
import { MAX_LIMIT_RESUMES_PER_DAY } from "@peppa/runner";
|
||||
import { PanelSection } from "@/components/ActivityAside";
|
||||
import { AgentSteps } from "@/components/AgentSteps";
|
||||
@ -34,10 +35,13 @@ interface SwitchPayload {
|
||||
carried?: "resume" | "fresh";
|
||||
}
|
||||
|
||||
/** «Claude A → Claude B · лимит · разговор продолжен» for a subscription_switched event (PEP-39). */
|
||||
export function switchText(payload: unknown): string {
|
||||
/**
|
||||
* «Claude A → Claude B · лимит · разговор продолжен» for a subscription_switched event (PEP-39).
|
||||
* PEP-121: the names only with `names` (a superadmin) — others read «другая подписка».
|
||||
*/
|
||||
export function switchText(payload: unknown, names = false): string {
|
||||
const p = (payload ?? {}) as SwitchPayload;
|
||||
return `${p.fromName ?? "?"} → ${p.toName ?? "?"} · ${p.reason === "threshold" ? "порог использования" : "лимит"} · ${p.carried === "fresh" ? "запуск заново" : "разговор продолжен"}`;
|
||||
return `${names ? `${p.fromName ?? "?"} → ${p.toName ?? "?"}` : "другая подписка"} · ${p.reason === "threshold" ? "порог использования" : "лимит"} · ${p.carried === "fresh" ? "запуск заново" : "разговор продолжен"}`;
|
||||
}
|
||||
|
||||
/** One line of a session's event log: type + the human part for known types. */
|
||||
@ -86,7 +90,7 @@ export function RunnerRow({ s, href, selected, needsPm }: { s: SessionView; href
|
||||
)}
|
||||
</span>
|
||||
<span className="truncate font-mono text-[11px] text-muted-foreground">
|
||||
{s.name && s.taskTitle ? `${s.name} · ` : ""}{s.projectKey} · {s.provider}{s.subscriptionName ? ` · ${s.subscriptionName}` : ""}{s.subscriptionSwitches > 0 ? ` (↻${s.subscriptionSwitches})` : ""} · #{s.id} · {s.tmuxName}
|
||||
{s.name && s.taskTitle ? `${s.name} · ` : ""}{s.projectKey} · {s.provider}<SubscriptionName s={s} prefix=" · " />{s.subscriptionSwitches > 0 ? ` (↻${s.subscriptionSwitches})` : ""} · #{s.id} · {s.tmuxName}
|
||||
</span>
|
||||
<span className="text-right font-mono text-[11px] whitespace-nowrap text-muted-foreground">{ago(s.lastActivityAt)}</span>
|
||||
{limited && (
|
||||
@ -99,7 +103,7 @@ export function RunnerRow({ s, href, selected, needsPm }: { s: SessionView; href
|
||||
);
|
||||
}
|
||||
|
||||
export function RunnerDetails({ s, questions, events, steps, stories, back, closeHref, chosen }: { s: SessionView; questions: InboxItem[]; events: Array<{ id: number; type: string; payload: unknown; createdAt: Date }>; steps: StepView[]; stories?: { history: RunnerTaskView[]; queue: RunnerTaskView[] }; back: string; closeHref: string; chosen: boolean }) {
|
||||
export function RunnerDetails({ s, questions, events, steps, stories, back, closeHref, chosen, names = false }: { names?: boolean; s: SessionView; questions: InboxItem[]; events: Array<{ id: number; type: string; payload: unknown; createdAt: Date }>; steps: StepView[]; stories?: { history: RunnerTaskView[]; queue: RunnerTaskView[] }; back: string; closeHref: string; chosen: boolean }) {
|
||||
const finished = FINISHED_SESSION_STATUSES.includes(s.status);
|
||||
return (
|
||||
<div className="flex flex-col gap-5">
|
||||
@ -143,7 +147,7 @@ export function RunnerDetails({ s, questions, events, steps, stories, back, clos
|
||||
<dd className="m-0">{PROVIDER_NAMES[s.provider]} · поколение {s.generation}</dd>
|
||||
<dt className="text-muted-foreground">Подписка</dt>
|
||||
<dd className="m-0">
|
||||
{s.subscriptionName ?? (s.subscriptionId ? `#${s.subscriptionId}` : "вход машины")}
|
||||
<SubscriptionName s={s} fallback="подключена" />
|
||||
{s.subscriptionSwitches > 0 && <span className="text-muted-foreground"> · переключений {s.subscriptionSwitches}</span>}
|
||||
</dd>
|
||||
<dt className="text-muted-foreground">Где</dt>
|
||||
@ -191,7 +195,7 @@ export function RunnerDetails({ s, questions, events, steps, stories, back, clos
|
||||
.filter((e) => e.type === "subscription_switched")
|
||||
.map((e) => (
|
||||
<li key={e.id} className="text-sm [overflow-wrap:anywhere]">
|
||||
<span className="font-mono text-xs text-muted-foreground">{ago(e.createdAt)}</span> {switchText(e.payload)}
|
||||
<span className="font-mono text-xs text-muted-foreground">{ago(e.createdAt)}</span> {switchText(e.payload, names)}
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
|
||||
12
apps/web/components/SubscriptionName.tsx
Normal file
12
apps/web/components/SubscriptionName.tsx
Normal file
@ -0,0 +1,12 @@
|
||||
import type { SessionView } from "@peppa/core";
|
||||
import { subscriptionNamesVisible } from "@/lib/auth";
|
||||
|
||||
/**
|
||||
* PEP-121: the name of the subscription an agent runs on — for a superadmin only (it carries
|
||||
* the login of whoever connected it). Others get `fallback` (nothing by default).
|
||||
*/
|
||||
export async function SubscriptionName({ s, prefix = "", fallback = null }: { s: Pick<SessionView, "subscriptionName" | "subscriptionId">; prefix?: string; fallback?: string | null }) {
|
||||
if (!(await subscriptionNamesVisible())) return fallback;
|
||||
const name = s.subscriptionName ?? (s.subscriptionId ? `#${s.subscriptionId}` : null);
|
||||
return name ? `${prefix}${name}` : fallback;
|
||||
}
|
||||
@ -2,6 +2,7 @@
|
||||
import Link from "next/link";
|
||||
import { BellRing, CircleCheck, CircleHelp, FileCheck, Hourglass, Play, RotateCcw, Send, ShieldQuestion, Square, SquareTerminal } from "lucide-react";
|
||||
import type { Project, Question, SessionView, StepView } from "@peppa/core";
|
||||
import { SubscriptionName } from "@/components/SubscriptionName";
|
||||
import { answerQuestion, messageSession, resumeTaskSession, stopTaskSession } from "@/app/(app)/actions";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { AgentBadge } from "@/components/AgentBadge";
|
||||
@ -131,7 +132,7 @@ export function SessionCard({ s, back, showTitle = false, terminal = false, step
|
||||
{showTitle && (s.taskTitle ?? s.name) && <span className="min-w-0 flex-[1_1_12em] truncate">{s.taskTitle ?? s.name}</span>}
|
||||
<span className="ml-auto font-mono text-xs text-muted-foreground">
|
||||
<Link href={`/runners?id=${s.id}`} className="text-muted-foreground hover:text-foreground">#{s.id}</Link> · {s.provider}
|
||||
{s.subscriptionName && <> · {s.subscriptionName}</>}
|
||||
<SubscriptionName s={s} prefix=" · " />
|
||||
{s.host && <> · {s.host.name}</>}
|
||||
{s.container && <> · в контейнере</>}
|
||||
{s.subscriptionSwitches > 0 && <> · переключений {s.subscriptionSwitches}</>} · пок. {s.generation} · {ago(s.lastActivityAt)}
|
||||
@ -187,7 +188,7 @@ export function AgentAtWork({ s, back }: { s: SessionView; back: string }) {
|
||||
<div className="flex flex-col gap-2 pt-2">
|
||||
<span className="font-mono text-xs text-muted-foreground">
|
||||
запуск #{s.id} · {s.provider}
|
||||
{s.subscriptionName && <> · {s.subscriptionName}</>}
|
||||
<SubscriptionName s={s} prefix=" · " />
|
||||
{s.host && <> · {s.host.name}</>}
|
||||
{s.container && <> · в контейнере</>}
|
||||
{s.subscriptionSwitches > 0 && <> · переключений {s.subscriptionSwitches}</>} · пок. {s.generation}
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
import { enterActor, getUiMode, getUser, isUserAllowed, sessionsValidAfter, sign, verify, type User } from "@peppa/core";
|
||||
import { enterActor, getUiMode, getUser, isSuperadmin, isUserAllowed, sessionsValidAfter, sign, verify, type User } from "@peppa/core";
|
||||
import { loadEnv } from "@peppa/shared";
|
||||
import { cookies, headers } from "next/headers";
|
||||
import { redirect } from "next/navigation";
|
||||
@ -80,3 +80,9 @@ export const uiMode = cache(async (): Promise<"product" | "engineer"> => {
|
||||
const u = await currentUser();
|
||||
return u ? getUiMode(db, u.id) : "product";
|
||||
});
|
||||
|
||||
/** PEP-121: subscription names carry the login of whoever connected them — a superadmin's eyes only. */
|
||||
export const subscriptionNamesVisible = cache(async (): Promise<boolean> => {
|
||||
const u = await currentUser();
|
||||
return u ? isSuperadmin(db, u) : false;
|
||||
});
|
||||
|
||||
@ -1,12 +1,12 @@
|
||||
## 1. Ядро
|
||||
- [ ] 1.1 `core/subscription-names.ts`: публичное название, зритель, `visibleSubscriptionName`
|
||||
- [ ] 1.2 `accountUsageForUser` маскирует имена; `agentsLine` — состояние строки для продакта
|
||||
- [ ] 1.3 `poolOverview(s)` со зрителем; сообщения (переключение, последняя подписка, запасная, «агенты не запустятся») без имён
|
||||
- [x] 1.1 `core/subscription-names.ts`: публичное название, зритель, `visibleSubscriptionName`
|
||||
- [x] 1.2 `accountUsageForUser` маскирует имена; `agentsLine` — состояние строки для продакта
|
||||
- [x] 1.3 `poolOverview(s)` со зрителем; сообщения (переключение, последняя подписка, запасная, «агенты не запустятся») без имён
|
||||
|
||||
## 2. Веб
|
||||
- [ ] 2.1 Полоса: одна строка в «Продакте», прежняя в «Инженере»
|
||||
- [ ] 2.2 Карточки и консоль агентов, история переключений, настройки проекта — без чужих имён
|
||||
- [x] 2.1 Полоса: одна строка в «Продакте», прежняя в «Инженере»
|
||||
- [x] 2.2 Карточки и консоль агентов, история переключений, настройки проекта — без чужих имён
|
||||
|
||||
## 3. Проверка
|
||||
- [ ] 3.1 Тест `subscription-names.test.ts` по сценариям спеки
|
||||
- [x] 3.1 Тест `subscription-names.test.ts` по сценариям спеки
|
||||
- [ ] 3.2 Проверки проекта, экраны глазами, словарь; AGENTS.md, память, архив, PR
|
||||
|
||||
@ -56,3 +56,4 @@ export * from "./agent-model.ts";
|
||||
export * from "./onboarding.ts";
|
||||
export * from "./chats.ts";
|
||||
export * from "./subscription-care.ts";
|
||||
export * from "./subscription-names.ts";
|
||||
|
||||
@ -4,6 +4,7 @@ import { and, count, eq, inArray, isNotNull } from "drizzle-orm";
|
||||
import { mayUseMachineLogin } from "./access.ts";
|
||||
import { isSuperadmin } from "./monitor.ts";
|
||||
import { getSetting, setSetting } from "./settings.ts";
|
||||
import { publicSubscriptionName } from "./subscription-names.ts";
|
||||
import { isUsable, poolSubscriptions } from "./subscriptions.ts";
|
||||
import { userProjectIds, type User } from "./users.ts";
|
||||
|
||||
@ -169,6 +170,6 @@ export async function projectAgentWarning(db: Db, projectId: number, now = new D
|
||||
const subs = await poolSubscriptions(db, p.poolId);
|
||||
if (!subs.length) return "в пуле подписок проекта нет ни одной подписки";
|
||||
if (subs.some((s) => isUsable(s, now))) return null;
|
||||
const why = subs.map((s) => `«${s.name}» — ${STATUS_RU[s.status] ?? s.status}${s.status === "limited" && s.limitedUntil ? ` до ${s.limitedUntil.toLocaleString("ru-RU", { hour: "2-digit", minute: "2-digit", day: "2-digit", month: "2-digit" })}` : ""}`);
|
||||
const why = subs.map((s) => `${publicSubscriptionName(s)} — ${STATUS_RU[s.status] ?? s.status}${s.status === "limited" && s.limitedUntil ? ` до ${s.limitedUntil.toLocaleString("ru-RU", { hour: "2-digit", minute: "2-digit", day: "2-digit", month: "2-digit" })}` : ""}`);
|
||||
return `нет рабочей подписки в пуле проекта: ${why.join(", ")}`;
|
||||
}
|
||||
|
||||
@ -8,6 +8,7 @@ import { PeppaError } from "./errors.ts";
|
||||
import { sendProjectMessage } from "./notifications.ts";
|
||||
import { deleteSetting, getSetting, setSetting } from "./settings.ts";
|
||||
import { getPool, getSubscription, isUsable, listPools, listSubscriptions, requireSuperadmin, type Subscription, type SubscriptionPool } from "./subscriptions.ts";
|
||||
import { visibleSubscriptionName, type SubscriptionViewer } from "./subscription-names.ts";
|
||||
import { listAccountUsage, type WindowView } from "./usage.ts";
|
||||
import type { User } from "./users.ts";
|
||||
|
||||
@ -74,7 +75,7 @@ export async function lendSubscription(db: Db, admin: Pick<User, "login">, o: {
|
||||
pool.id,
|
||||
"subscription_lent",
|
||||
{ subscriptionId: sub.id, name: sub.name, until: until.toISOString(), login: admin.login },
|
||||
`🎁 В ваш пул на время добавлена запасная подписка «${sub.name}» — до ${hhmm(until)}. Если основная упрётся в лимит, агенты продолжат на ней.`,
|
||||
`🎁 Вам на время добавлена запасная подписка — до ${hhmm(until)}. Если основная упрётся в лимит, агенты продолжат на запасной.`,
|
||||
`loan:${pool.id}:${sub.id}:${until.getTime()}`,
|
||||
);
|
||||
return { poolId: pool.id, subscriptionId: sub.id, until, byLogin: admin.login };
|
||||
@ -94,7 +95,7 @@ export async function returnLoan(db: Db, poolId: number, subscriptionId: number,
|
||||
poolId,
|
||||
"subscription_returned",
|
||||
{ subscriptionId, name: sub?.name ?? null, why },
|
||||
`Запасная подписка «${sub?.name ?? subscriptionId}» ${why === "expired" ? "вернулась владельцу — срок займа кончился" : "вернулась владельцу"}. Агенты, которые уже на ней, доработают текущий запуск.`,
|
||||
`Запасная подписка ${why === "expired" ? "вернулась владельцу — срок займа кончился" : "вернулась владельцу"}. Агенты, которые уже на ней, доработают текущий запуск.`,
|
||||
`loanback:${poolId}:${subscriptionId}:${loan.until}`,
|
||||
);
|
||||
return true;
|
||||
@ -150,7 +151,8 @@ function stateLabel(s: Omit<PoolSubscriptionState, "label">): string {
|
||||
return s.activeSessions ? `в работе: ${agents(s.activeSessions)}` : "свободна";
|
||||
}
|
||||
|
||||
export async function poolOverviews(db: Db, poolIds?: number[], now = new Date()): Promise<PoolOverview[]> {
|
||||
/** `viewer` (PEP-121): whose eyes — names of subscriptions connected by others are neutral for a non-admin; omitted = real names (superadmin pages, the watchdog). */
|
||||
export async function poolOverviews(db: Db, poolIds?: number[], now = new Date(), viewer?: SubscriptionViewer): Promise<PoolOverview[]> {
|
||||
const pools = (await listPools(db)).filter((p) => !poolIds || poolIds.includes(p.id));
|
||||
if (!pools.length) return [];
|
||||
const subs = await listSubscriptions(db);
|
||||
@ -170,7 +172,7 @@ export async function poolOverviews(db: Db, poolIds?: number[], now = new Date()
|
||||
.sort((a, b) => b.pct! - a.pct!)[0] ?? null;
|
||||
const base = {
|
||||
id: s.id,
|
||||
name: s.name,
|
||||
name: viewer ? visibleSubscriptionName(s, viewer) : s.name,
|
||||
provider: s.provider,
|
||||
status: s.status,
|
||||
createdBy: s.createdBy,
|
||||
@ -193,8 +195,8 @@ export async function poolOverviews(db: Db, poolIds?: number[], now = new Date()
|
||||
});
|
||||
}
|
||||
|
||||
export async function poolOverview(db: Db, poolId: number, now = new Date()): Promise<PoolOverview | null> {
|
||||
return (await poolOverviews(db, [poolId], now))[0] ?? null;
|
||||
export async function poolOverview(db: Db, poolId: number, now = new Date(), viewer?: SubscriptionViewer): Promise<PoolOverview | null> {
|
||||
return (await poolOverviews(db, [poolId], now, viewer))[0] ?? null;
|
||||
}
|
||||
|
||||
// ── early warning ────────────────────────────────────────────────────────────────
|
||||
@ -211,7 +213,7 @@ async function warnPool(db: Db, o: PoolOverview, sub: PoolSubscriptionState, mar
|
||||
await sendProjectMessage(
|
||||
db,
|
||||
p.id,
|
||||
`⚠️ Осталась одна рабочая подписка — «${sub.name}», ${detail}. Когда она упрётся в лимит, агенты встанут до сброса. Добавьте ещё одну подписку Claude или ChatGPT: «⋯ Настройки проекта → Подписки».`,
|
||||
`⚠️ Осталась одна рабочая подписка, ${detail}. Когда она упрётся в лимит, агенты встанут до сброса. Добавьте ещё одну подписку Claude или ChatGPT: «⋯ Настройки проекта → Подписки».`,
|
||||
`subwarn:${sub.id}:${mark}:p${p.id}`,
|
||||
{ title: "Скоро лимит подписки", url: `/p/${p.key}#subscription` },
|
||||
);
|
||||
|
||||
26
packages/core/src/subscription-names.ts
Normal file
26
packages/core/src/subscription-names.ts
Normal file
@ -0,0 +1,26 @@
|
||||
// PEP-121: a subscription's name usually carries the login of whoever connected it
|
||||
// («Claude — tatyana.saifarova 5»). Only a superadmin and that person see it; everyone else
|
||||
// gets a neutral name. Anything that shows a subscription to a user goes through here.
|
||||
import type { Db } from "@peppa/db";
|
||||
import { isSuperadmin } from "./monitor.ts";
|
||||
import type { User } from "./users.ts";
|
||||
|
||||
const KIND: Record<string, string> = { claude: "Claude", codex: "ChatGPT", opencode: "OpenCode" };
|
||||
|
||||
/** «Подписка Claude» — the name for texts with no particular reader (messages to a project). */
|
||||
export const publicSubscriptionName = (s: { provider: string }) => `Подписка ${KIND[s.provider] ?? "агента"}`;
|
||||
|
||||
export interface SubscriptionViewer {
|
||||
admin: boolean;
|
||||
userId: number;
|
||||
}
|
||||
|
||||
export async function subscriptionViewer(db: Db, user: Pick<User, "id" | "login">): Promise<SubscriptionViewer> {
|
||||
return { admin: await isSuperadmin(db, user), userId: user.id };
|
||||
}
|
||||
|
||||
/** The real name for a superadmin and the one who connected the subscription, the neutral one otherwise. */
|
||||
export function visibleSubscriptionName(s: { name: string; provider: string; createdBy?: number | null }, viewer: SubscriptionViewer | null | undefined): string {
|
||||
if (viewer && (viewer.admin || (s.createdBy != null && s.createdBy === viewer.userId))) return s.name;
|
||||
return publicSubscriptionName(s);
|
||||
}
|
||||
@ -4,10 +4,11 @@
|
||||
// neither — the UI says «нет данных» rather than inventing numbers.
|
||||
import { readFileSync } from "node:fs";
|
||||
import { projects, sessions, settings, subscriptionPoolMembers, subscriptions, type Db, type SessionUsage, type UsageTokens } from "@peppa/db";
|
||||
import { eq, inArray, like } from "drizzle-orm";
|
||||
import { and, eq, inArray, like, notInArray } from "drizzle-orm";
|
||||
import type { User } from "./users.ts";
|
||||
import { userProjectIds } from "./users.ts";
|
||||
import { isSuperadmin } from "./monitor.ts";
|
||||
import { visibleSubscriptionName } from "./subscription-names.ts";
|
||||
|
||||
export type { SessionUsage, UsageTokens };
|
||||
|
||||
@ -279,6 +280,8 @@ export interface AccountUsage {
|
||||
subscriptionId: number | null;
|
||||
name: string;
|
||||
provider: string;
|
||||
/** Who connected the subscription (null — unknown or this machine's login). */
|
||||
createdBy: number | null;
|
||||
fiveHour: WindowView | null;
|
||||
sevenDay: WindowView | null;
|
||||
at: Date | null;
|
||||
@ -293,6 +296,7 @@ export const accountPeak = (a: AccountUsage) => Math.max(a.fiveHour?.pct ?? -1,
|
||||
/**
|
||||
* Accounts a user should see: a superadmin — all; others — the subscriptions of their
|
||||
* projects' pools, plus this machine's login when one of their projects has no pool.
|
||||
* PEP-121: names of subscriptions connected by others are replaced with neutral ones.
|
||||
*/
|
||||
export async function accountUsageForUser(db: Db, user: Pick<User, "id" | "login">, now = Date.now()): Promise<AccountUsage[]> {
|
||||
const admin = await isSuperadmin(db, user);
|
||||
@ -307,7 +311,48 @@ export async function accountUsageForUser(db: Db, user: Pick<User, "id" | "login
|
||||
? (await db.select({ id: subscriptionPoolMembers.subscriptionId }).from(subscriptionPoolMembers).where(inArray(subscriptionPoolMembers.poolId, poolIds))).map((r) => r.id)
|
||||
: [];
|
||||
}
|
||||
return listAccountUsage(db, { subscriptionIds: subIds, machine, now });
|
||||
const list = await listAccountUsage(db, { subscriptionIds: subIds, machine, now });
|
||||
if (admin) return list;
|
||||
const viewer = { admin, userId: user.id };
|
||||
return list.map((a) => ({ ...a, name: a.subscriptionId == null ? "Подписка Peppa FACTORY" : visibleSubscriptionName(a, viewer) }));
|
||||
}
|
||||
|
||||
/** PEP-121: the whole limits strip for a product manager — agents work, or when they go on. */
|
||||
export type AgentsLine = { state: "working" } | { state: "paused"; until: Date };
|
||||
|
||||
/**
|
||||
* «Агенты работают» unless every agent of the user's projects waits for a limit reset (or
|
||||
* nobody runs and every subscription of their pools is in a limit) — then when they go on.
|
||||
*/
|
||||
export async function agentsLine(db: Db, user: Pick<User, "id" | "login">, now = Date.now()): Promise<AgentsLine> {
|
||||
const earliest = (ds: Array<Date | null | undefined>) => ds.filter((d): d is Date => !!d && d.getTime() > now).sort((a, b) => a.getTime() - b.getTime())[0];
|
||||
const ids = await userProjectIds(db, user.id);
|
||||
if (!ids.length) return { state: "working" };
|
||||
const live = await db
|
||||
.select({ status: sessions.status, resumeAt: sessions.resumeAt, subscriptionId: sessions.subscriptionId })
|
||||
.from(sessions)
|
||||
.where(and(inArray(sessions.projectId, ids), notInArray(sessions.status, ["done", "failed"])));
|
||||
const ps = await db.select({ poolId: projects.subscriptionPoolId }).from(projects).where(inArray(projects.id, ids));
|
||||
const poolIds = [...new Set(ps.map((p) => p.poolId).filter((x): x is number => x != null))];
|
||||
const subs = poolIds.length
|
||||
? await db
|
||||
.select({ id: subscriptions.id, status: subscriptions.status, limitedUntil: subscriptions.limitedUntil })
|
||||
.from(subscriptions)
|
||||
.innerJoin(subscriptionPoolMembers, eq(subscriptionPoolMembers.subscriptionId, subscriptions.id))
|
||||
.where(inArray(subscriptionPoolMembers.poolId, poolIds))
|
||||
: [];
|
||||
const limited = (s: (typeof subs)[number]) => s.status === "limited" && !!s.limitedUntil && s.limitedUntil.getTime() > now;
|
||||
const waiting = live.filter((s) => s.status === "rate_limited");
|
||||
if (waiting.length && waiting.length === live.length) {
|
||||
const until = earliest(waiting.map((s) => s.resumeAt)) ?? earliest(subs.filter(limited).map((s) => s.limitedUntil));
|
||||
return until ? { state: "paused", until } : { state: "working" };
|
||||
}
|
||||
// A project on this machine's login (no pool) is not held by the pools' limits.
|
||||
if (!live.length && subs.length && ps.every((p) => p.poolId != null) && subs.every(limited)) {
|
||||
const until = earliest(subs.map((s) => s.limitedUntil));
|
||||
if (until) return { state: "paused", until };
|
||||
}
|
||||
return { state: "working" };
|
||||
}
|
||||
|
||||
export async function listAccountUsage(db: Db, o: { subscriptionIds?: number[] | null; machine?: boolean; now?: number } = {}): Promise<AccountUsage[]> {
|
||||
@ -320,10 +365,10 @@ export async function listAccountUsage(db: Db, o: { subscriptionIds?: number[] |
|
||||
return { key, ...base, fiveHour: windowView(w?.fiveHour, now), sevenDay: windowView(w?.sevenDay, now), at: w ? new Date(w.at) : null, stale: !!w && now - w.at > STALE_USAGE_MS };
|
||||
};
|
||||
const out = subs.map((s) =>
|
||||
view(accountKey(s.id), { subscriptionId: s.id, name: s.name, provider: s.provider, limitedUntil: s.status === "limited" && s.limitedUntil && s.limitedUntil.getTime() > now ? s.limitedUntil : null }),
|
||||
view(accountKey(s.id), { subscriptionId: s.id, name: s.name, provider: s.provider, createdBy: s.createdBy, limitedUntil: s.status === "limited" && s.limitedUntil && s.limitedUntil.getTime() > now ? s.limitedUntil : null }),
|
||||
);
|
||||
if (o.machine !== false && (byKey.has(accountKey(null)) || !out.length)) {
|
||||
out.push(view(accountKey(null), { subscriptionId: null, name: "Вход машины", provider: "claude", limitedUntil: null }));
|
||||
out.push(view(accountKey(null), { subscriptionId: null, name: "Вход машины", provider: "claude", createdBy: null, limitedUntil: null }));
|
||||
}
|
||||
return out.sort((a, b) => accountPeak(b) - accountPeak(a));
|
||||
}
|
||||
|
||||
@ -93,8 +93,8 @@ export async function rotateSession(db: Db, s: SessionView, target: Subscription
|
||||
: carried === "resume"
|
||||
? "продолжает тот же разговор"
|
||||
: "Codex не переносит разговор между аккаунтами — начал заново с контекстом из стори";
|
||||
const verb = crossed ? "переехал" : "переключил";
|
||||
await sendProjectMessage(db, s.projectId, `🔁 ${who}: ${verb} с подписки «${from?.name ?? "?"}» на «${target.name}» (${why}), ${how}.`, `rot:${s.id}:g${resumed.generation}`, {
|
||||
const verb = crossed ? "переехал" : "перешёл";
|
||||
await sendProjectMessage(db, s.projectId, `🔁 ${who}: ${verb} на другую подписку (${why}), ${how}.`, `rot:${s.id}:g${resumed.generation}`, {
|
||||
title: `${who}: другая подписка`,
|
||||
url: s.taskKey ? `/t/${s.taskKey}` : `/runners?id=${s.id}`,
|
||||
});
|
||||
|
||||
@ -63,7 +63,7 @@ describe("Переключение на свободную подписку пу
|
||||
const [ev] = await switches(sid);
|
||||
assert.deepEqual({ from: ev!.fromName, to: ev!.toName, reason: ev!.reason, carried: ev!.carried }, { from: "Rot A", to: "Rot B", reason: "limit", carried: "resume" });
|
||||
const msg = await core.getOutbox(db, `rot:${sid}:g2:${CHAT}`);
|
||||
assert.match(String((msg!.params as { text: string }).text), /переключил с подписки «Rot A» на «Rot B» \(лимит до \d\d:\d\d\), продолжает тот же разговор/);
|
||||
assert.match(String((msg!.params as { text: string }).text), /перешёл на другую подписку \(лимит до \d\d:\d\d\), продолжает тот же разговор/);
|
||||
|
||||
// A new runner of the project doesn't start on the limited subscription.
|
||||
const p2 = await project({ turns: [[{ say: "ok" }]] });
|
||||
|
||||
@ -61,7 +61,7 @@ describe("Переезд на подписку другого провайдер
|
||||
const ev = (await typeEvents(runner.SWITCH_EVENT)).find((e) => e.sessionId === sid)!.payload as Record<string, unknown>;
|
||||
assert.deepEqual({ from: ev.fromProvider, to: ev.toProvider, carried: ev.carried }, { from: "claude", to: "codex", carried: "fresh" });
|
||||
const [msg] = await outboxTexts(`rot:${sid}:g2:`);
|
||||
assert.match(msg!, /переехал с подписки «Cross A» на «Cross C».*ChatGPT \(Codex\) — начал заново с контекстом из стори/);
|
||||
assert.match(msg!, /переехал на другую подписку \(.*ChatGPT \(Codex\) — начал заново с контекстом из стори/);
|
||||
await runner.stopSession(db, sid);
|
||||
});
|
||||
|
||||
@ -159,7 +159,7 @@ describe("Предупреждение до лимита", () => {
|
||||
assert.equal(await core.subscriptionWarnTick(db), 1);
|
||||
assert.equal(await core.subscriptionWarnTick(db), 0, "once per window");
|
||||
const [text] = await outboxTexts(`subwarn:${a.id}:`);
|
||||
assert.match(text!, /Осталась одна рабочая подписка — «Warn1 A», использовано 90% \(окно 5 ч, сброс в \d\d:\d\d\).*Добавьте ещё одну подписку/);
|
||||
assert.match(text!, /Осталась одна рабочая подписка, использовано 90% \(окно 5 ч, сброс в \d\d:\d\d\).*Добавьте ещё одну подписку/);
|
||||
assert.equal((await typeEvents("subscription_last_warning")).filter((e) => (e.payload as { subscriptionId: number }).subscriptionId === a.id).length, 1);
|
||||
|
||||
// A new window crosses the threshold again → a new warning.
|
||||
@ -199,7 +199,7 @@ describe("Суперадмин одалживает подписку", () => {
|
||||
await assert.rejects(core.lendSubscription(db, admin, { subscriptionId: spare.id, poolId: pool.id, hours: 2 }), /Подписка уже в этом пуле/);
|
||||
const o = (await core.poolOverview(db, pool.id))!;
|
||||
assert.ok(o.subscriptions.find((x) => x.id === spare.id)!.loan);
|
||||
assert.match((await outboxTexts(`loan:${pool.id}:${spare.id}:`))[0]!, /запасная подписка «Loan spare» — до \d\d:\d\d/);
|
||||
assert.match((await outboxTexts(`loan:${pool.id}:${spare.id}:`))[0]!, /запасная подписка — до \d\d:\d\d/);
|
||||
// The owner can't remove a lent subscription.
|
||||
await assert.rejects(runner.removeOwnSubscription(db, admin, await core.getProject(db, p.key), spare.id), /вернётся сама по сроку/);
|
||||
|
||||
|
||||
93
packages/testkit/test/subscription-names.test.ts
Normal file
93
packages/testkit/test/subscription-names.test.ts
Normal file
@ -0,0 +1,93 @@
|
||||
// PEP-121: the limits strip of a product manager is one line, and the name of a subscription
|
||||
// (it carries the login of whoever connected it) is seen only by a superadmin and that person.
|
||||
import assert from "node:assert/strict";
|
||||
import { after, describe, test } from "node:test";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { projects, sessions, subscriptionPoolMembers, subscriptionPools, subscriptions } from "@peppa/db";
|
||||
import { core, db, teardown } from "./helpers.ts";
|
||||
|
||||
process.env.PEPPA_SECRET = "mock-secret-for-tests";
|
||||
after(teardown);
|
||||
|
||||
const NAME = "Claude — tatyana.saifarova 5";
|
||||
const NOW = Date.UTC(2026, 10, 15, 9, 0);
|
||||
const at = (h: number, m = 0) => new Date(Date.UTC(2026, 10, 15, h, m));
|
||||
|
||||
async function world() {
|
||||
const tag = Math.random().toString(36).slice(2, 8);
|
||||
const n = Math.floor(Math.random() * 1e6) + 1e6;
|
||||
const tatyana = await core.upsertUserFromGitea(db, { id: n, login: `tatyana.saifarova-${tag}` }, { access_token: "x" });
|
||||
const anna = await core.upsertUserFromGitea(db, { id: n + 1, login: `anna-${tag}` }, { access_token: "y" });
|
||||
const admin = await core.upsertUserFromGitea(db, { id: n + 2, login: `mock-admin-${tag}` }, { access_token: "z" });
|
||||
await core.setSetting(db, "platform.admins", [admin.login]);
|
||||
const [sub] = await db.insert(subscriptions).values({ provider: "claude", name: NAME, authKind: "oauth", status: "active", createdBy: tatyana.id }).returning();
|
||||
const [pool] = await db.insert(subscriptionPools).values({ name: `Подписки — ${tatyana.login}` }).returning();
|
||||
await db.insert(subscriptionPoolMembers).values({ poolId: pool!.id, subscriptionId: sub!.id });
|
||||
const key = `N${tag.toUpperCase()}`;
|
||||
const [project] = await db.insert(projects).values({ slug: `mock-names-${tag}`, key, name: "BS", ownerId: tatyana.id, giteaOwner: "peppa-bot", giteaRepo: `mock-names-${tag}`, workspacePath: `/tmp/mock-names-${tag}`, subscriptionPoolId: pool!.id }).returning();
|
||||
await core.addMember(db, project!, anna.login, tatyana.id);
|
||||
const session = (status: "running" | "rate_limited", resumeAt: Date | null = null) =>
|
||||
db.insert(sessions).values({ projectId: project!.id, provider: "claude", status, tmuxName: `mock-${tag}-${Math.random().toString(36).slice(2, 6)}`, subscriptionId: sub!.id, resumeAt }).returning();
|
||||
return { tatyana, anna, admin, sub: sub!, pool: pool!, project: project!, session };
|
||||
}
|
||||
|
||||
describe("PEP-121: имя подписки видят только суперадмин и её автор", () => {
|
||||
test("Участник чужого проекта: «Подписка Claude» в полосе, /status и get_usage", async () => {
|
||||
const w = await world();
|
||||
const accounts = await core.accountUsageForUser(db, w.anna, NOW);
|
||||
assert.deepEqual(accounts.map((a) => a.name), ["Подписка Claude"]);
|
||||
const text = accounts.map(core.describeAccount).join("\n");
|
||||
assert.ok(!text.includes("tatyana.saifarova"), text);
|
||||
const view = await core.poolOverview(db, w.pool.id, new Date(NOW), await core.subscriptionViewer(db, w.anna));
|
||||
assert.deepEqual(view!.subscriptions.map((s) => s.name), ["Подписка Claude"]);
|
||||
});
|
||||
|
||||
test("Суперадмин видит название", async () => {
|
||||
const w = await world();
|
||||
const mine = (await core.accountUsageForUser(db, w.admin, NOW)).filter((a) => a.subscriptionId === w.sub.id);
|
||||
assert.deepEqual(mine.map((a) => a.name), [NAME]);
|
||||
});
|
||||
|
||||
test("Автор подписки видит название в настройках проекта", async () => {
|
||||
const w = await world();
|
||||
const view = await core.poolOverview(db, w.pool.id, new Date(NOW), await core.subscriptionViewer(db, w.tatyana));
|
||||
assert.deepEqual(view!.subscriptions.map((s) => s.name), [NAME]);
|
||||
assert.deepEqual((await core.accountUsageForUser(db, w.tatyana, NOW)).map((a) => a.name), [NAME]);
|
||||
});
|
||||
|
||||
test("«Агенты не запустятся» — без имени подписки", async () => {
|
||||
const w = await world();
|
||||
await db.update(subscriptions).set({ status: "limited", limitedUntil: at(14, 30) }).where(eq(subscriptions.id, w.sub.id));
|
||||
const warning = await core.projectAgentWarning(db, w.project.id, new Date(NOW));
|
||||
assert.match(warning!, /Подписка Claude — в лимите/);
|
||||
assert.ok(!warning!.includes("tatyana"), warning!);
|
||||
});
|
||||
});
|
||||
|
||||
describe("PEP-121: полоса лимитов для продакта", () => {
|
||||
test("Агенты работают", async () => {
|
||||
const w = await world();
|
||||
await w.session("running");
|
||||
assert.deepEqual(await core.agentsLine(db, w.anna, NOW), { state: "working" });
|
||||
});
|
||||
|
||||
test("Все агенты ждут сброса лимита — «Агенты продолжат в 14:30»", async () => {
|
||||
const w = await world();
|
||||
await w.session("rate_limited", at(14, 30));
|
||||
assert.deepEqual(await core.agentsLine(db, w.anna, NOW), { state: "paused", until: at(14, 30) });
|
||||
});
|
||||
|
||||
test("Один агент ждёт, другой работает — «Агенты работают»", async () => {
|
||||
const w = await world();
|
||||
await w.session("rate_limited", at(14, 30));
|
||||
await w.session("running");
|
||||
assert.deepEqual(await core.agentsLine(db, w.anna, NOW), { state: "working" });
|
||||
});
|
||||
|
||||
test("Никто не запущен, а все подписки в лимите — время сброса", async () => {
|
||||
const w = await world();
|
||||
await db.update(subscriptions).set({ status: "limited", limitedUntil: at(12, 15) }).where(eq(subscriptions.id, w.sub.id));
|
||||
assert.deepEqual(await core.agentsLine(db, w.anna, NOW), { state: "paused", until: at(12, 15) });
|
||||
assert.deepEqual(await core.agentsLine(db, w.anna, at(12, 16).getTime()), { state: "working" }, "после сброса");
|
||||
});
|
||||
});
|
||||
Loading…
Reference in New Issue
Block a user