PEP-176: the superadmin moves a subscription's agents by hand — to a chosen working subscription of the pool or to any free one
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
5f3e3f750b
commit
9c66a01101
@ -2,7 +2,7 @@
|
||||
// «Подписки» (PEP-67): every action is superadmin-only (others get "not found").
|
||||
|
||||
import { createPool, deletePool, getProject, lendSubscription, PeppaError, returnLoanNow, requireSuperadmin, setProjectPool, updatePool, updateSubscription, type SubscriptionProvider } from "@peppa/core";
|
||||
import { addPoolSubscription, addSubscription, cancelLogin, checkSubscription, finishClaudeLogin, removeSubscription, startClaudeLogin, startCodexLogin } from "@peppa/runner";
|
||||
import { addPoolSubscription, addSubscription, switchAgents, cancelLogin, checkSubscription, finishClaudeLogin, removeSubscription, startClaudeLogin, startCodexLogin } from "@peppa/runner";
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { redirect } from "next/navigation";
|
||||
import { asWebActor, requireUser } from "@/lib/auth";
|
||||
@ -60,6 +60,16 @@ export async function addPoolSubscriptionAction(f: FormData) {
|
||||
});
|
||||
}
|
||||
|
||||
/** PEP-176: the superadmin moves the agents off a subscription by hand. */
|
||||
export async function switchAgentsAction(f: FormData) {
|
||||
await attempt(f, async () => {
|
||||
const fromId = Number(str(f, "fromId"));
|
||||
const to = str(f, "toId");
|
||||
const r = await switchAgents(db, { fromId, toId: to ? Number(to) : null });
|
||||
return `${BASE}?switched=${r.moved}&left=${r.skipped}#s-${fromId}`;
|
||||
});
|
||||
}
|
||||
|
||||
export async function reconnectSubscription(f: FormData) {
|
||||
await attempt(f, async () => {
|
||||
const id = Number(str(f, "id"));
|
||||
|
||||
@ -23,6 +23,7 @@ import {
|
||||
deletePoolAction,
|
||||
deleteSubscriptionAction,
|
||||
addPoolSubscriptionAction,
|
||||
switchAgentsAction,
|
||||
returnLoanAction,
|
||||
reconnectSubscription,
|
||||
submitLoginCode,
|
||||
@ -136,6 +137,25 @@ function SetCard({ o, subs, t }: { o: PoolOverview; subs: SubscriptionView[]; t:
|
||||
o={o}
|
||||
action={(s) => (
|
||||
<>
|
||||
{/* PEP-176: move this subscription's agents by hand — to one of the pool's working subscriptions or to any free one. */}
|
||||
{s.activeSessions > 0 && (
|
||||
<form action={switchAgentsAction} className="flex items-center gap-1" data-switch-agents={s.id}>
|
||||
<Hidden fields={{ fromId: s.id }} />
|
||||
<NativeSelect name="toId" aria-label={t("Куда перевести агентов")} className="h-7 text-xs">
|
||||
<option value="">{t("на любую свободную")}</option>
|
||||
{o.subscriptions
|
||||
.filter((x) => x.id !== s.id && x.usable)
|
||||
.map((x) => (
|
||||
<option key={x.id} value={x.id}>
|
||||
{x.name}
|
||||
</option>
|
||||
))}
|
||||
</NativeSelect>
|
||||
<Button size="xs" variant="outline" title={t("Агенты сразу продолжат на выбранной подписке")}>
|
||||
{t("Перевести агентов")}
|
||||
</Button>
|
||||
</form>
|
||||
)}
|
||||
<form action={checkSubscriptionAction}>
|
||||
<Hidden fields={{ id: s.id }} />
|
||||
<Button size="xs" variant="ghost" title={t("Проверить")} aria-label={t("Проверить")} className="text-muted-foreground">
|
||||
@ -197,13 +217,13 @@ function SetCard({ o, subs, t }: { o: PoolOverview; subs: SubscriptionView[]; t:
|
||||
);
|
||||
}
|
||||
|
||||
type Params = { error?: string; login?: string; added?: string };
|
||||
type Params = { error?: string; login?: string; added?: string; switched?: string; left?: string };
|
||||
|
||||
export default async function Subscriptions({ searchParams }: { searchParams: Promise<Params> }) {
|
||||
const user = await requireUser();
|
||||
const t = await getT();
|
||||
if (!(await isSuperadmin(db, user))) notFound();
|
||||
const { error, added } = await searchParams;
|
||||
const { error, added, switched, left } = await searchParams;
|
||||
let subs = await listSubscriptions(db);
|
||||
// Codex device sign-ins finish on the user's device: look whether they are done.
|
||||
let polled = false;
|
||||
@ -231,6 +251,13 @@ export default async function Subscriptions({ searchParams }: { searchParams: Pr
|
||||
<PageHeader title={<><KeyRound className="mr-1 inline size-5 text-primary" />{t("Подписки")}</>}>
|
||||
{t("Аккаунты Claude и ChatGPT, на которых работают агенты. Кончилась одна — агенты переходят на следующую свободную, а когда лимит сбросится, она снова в строю. Раздел видят только суперадмины.")}
|
||||
</PageHeader>
|
||||
{switched !== undefined && (
|
||||
<Notice>
|
||||
{Number(left) > 0
|
||||
? t("Переведено агентов: {n}. Ещё {m} — некуда: свободной рабочей подписки нет.", { n: Number(switched), m: Number(left) })
|
||||
: t("Переведено агентов: {n}. Они продолжают на новой подписке.", { n: Number(switched) })}
|
||||
</Notice>
|
||||
)}
|
||||
{addedSub && <Notice>{addedSub.status === "active" ? t("Подписка «{name}» добавлена и активна", { name: addedSub.name }) : t("Подписка «{name}» добавлена", { name: addedSub.name })}</Notice>}
|
||||
|
||||
{(problems.length > 0 || thin.length > 0) && (
|
||||
|
||||
@ -6,7 +6,10 @@ import {
|
||||
expireSessionQuestions,
|
||||
getSession,
|
||||
getSubscription,
|
||||
isUsable,
|
||||
listSessions,
|
||||
logSessionEvent,
|
||||
PeppaError,
|
||||
rotationCandidate,
|
||||
sendProjectMessage,
|
||||
updateSession,
|
||||
@ -25,7 +28,8 @@ export const rotationEnabled = () => process.env.PEPPA_ROTATE !== "off" && proce
|
||||
/** PEP-170: move early, at the usage-warning threshold — off by default (switch only when a subscription has run out). */
|
||||
export const earlyRotationEnabled = () => process.env.PEPPA_ROTATE_EARLY === "on";
|
||||
|
||||
export type RotateReason = "limit" | "threshold";
|
||||
/** PEP-176: "manual" — the superadmin moved the agents by hand. */
|
||||
export type RotateReason = "limit" | "threshold" | "manual";
|
||||
|
||||
/** How the PM calls the providers (PEP-107 messages). */
|
||||
const PROVIDER_LABEL: Record<Subscription["provider"], string> = { claude: "Claude", codex: "ChatGPT (Codex)", opencode: "OpenCode" };
|
||||
@ -85,8 +89,8 @@ export async function rotateSession(db: Db, s: SessionView, target: Subscription
|
||||
const who = s.taskKey ?? m("Агент №{id}", { id: s.id });
|
||||
const prompt =
|
||||
carried === "fresh"
|
||||
? `Предыдущий запуск${s.taskKey ? ` над стори ${s.taskKey}` : ""} шёл на другой подписке и ${reason === "limit" ? "упёрся в лимит" : "подошёл к лимиту"}; разговор не перенесён. Восстанови контекст: peppa.get_task, tasks.md активного OpenSpec change, git status, git log и git diff в рабочей копии — и продолжай с того места.`
|
||||
: `Раннер переключён на другую подписку (${reason === "limit" ? "на прежней лимит" : "прежняя подходит к лимиту"}). Продолжай с того места, где остановился.`;
|
||||
? `Предыдущий запуск${s.taskKey ? ` над стори ${s.taskKey}` : ""} шёл на другой подписке и ${reason === "limit" ? "упёрся в лимит" : reason === "manual" ? "был переключён администратором" : "подошёл к лимиту"}; разговор не перенесён. Восстанови контекст: peppa.get_task, tasks.md активного OpenSpec change, git status, git log и git diff в рабочей копии — и продолжай с того места.`
|
||||
: `Раннер переключён на другую подписку (${reason === "limit" ? "на прежней лимит" : reason === "manual" ? "переключил администратор" : "прежняя подходит к лимиту"}). Продолжай с того места, где остановился.`;
|
||||
// Loaded lazily: the hook process imports this module (via limits) and stays light.
|
||||
const { resumeSession } = await import("./sessions.ts");
|
||||
const resumed = await resumeSession(db, s.id, { prompt });
|
||||
@ -95,7 +99,9 @@ export async function rotateSession(db: Db, s: SessionView, target: Subscription
|
||||
? from?.limitedUntil && from.status === "limited"
|
||||
? m("лимит до {time}", { time: hhmm(from.limitedUntil) })
|
||||
: m("лимит")
|
||||
: m("подписка подходит к лимиту");
|
||||
: reason === "manual"
|
||||
? m("переключил администратор")
|
||||
: m("подписка подходит к лимиту");
|
||||
const how = crossed
|
||||
? m("теперь работает на {provider} — начал заново по описанию задачи", { provider: PROVIDER_LABEL[target.provider] })
|
||||
: carried === "resume"
|
||||
@ -110,6 +116,31 @@ export async function rotateSession(db: Db, s: SessionView, target: Subscription
|
||||
return getSession(db, s.id);
|
||||
}
|
||||
|
||||
/**
|
||||
* PEP-176: the superadmin moves every agent off a subscription — to `toId`, or each to the least
|
||||
* busy working subscription of its pools (another provider if none of its own). The agent is
|
||||
* relaunched at once (Claude continues the same conversation).
|
||||
*/
|
||||
export async function switchAgents(db: Db, o: { fromId: number; toId?: number | null; now?: Date }): Promise<{ moved: number; skipped: number }> {
|
||||
const now = o.now ?? new Date();
|
||||
const fixed = o.toId ? await getSubscription(db, o.toId) : null;
|
||||
if (fixed && fixed.id === o.fromId) throw new PeppaError(m("Агенты уже на этой подписке"));
|
||||
if (fixed && !isUsable(fixed, now)) throw new PeppaError(m("Подписка «{name}» сейчас не работает — выберите другую", { name: fixed.name }));
|
||||
const sessions = (await listSessions(db, { active: true })).filter((s) => s.subscriptionId === o.fromId);
|
||||
let moved = 0;
|
||||
let skipped = 0;
|
||||
for (const s of sessions) {
|
||||
const target = fixed ?? (await rotationCandidate(db, s, { now }));
|
||||
if (!target) {
|
||||
skipped++;
|
||||
continue;
|
||||
}
|
||||
await rotateSession(db, s, target, "manual", now);
|
||||
moved++;
|
||||
}
|
||||
return { moved, skipped };
|
||||
}
|
||||
|
||||
/**
|
||||
* The turn is over (Stop / StopFailure / limit banner): move the session if it waits for a
|
||||
* rotation and somewhere to go exists. Returns true when the session was relaunched.
|
||||
|
||||
@ -346,4 +346,13 @@ export const admin: Dict = {
|
||||
"открыть": "open",
|
||||
"с {date}": "since {date}",
|
||||
"пароль": "password",
|
||||
"Куда перевести агентов": "Where to move the agents",
|
||||
"на любую свободную": "to any free one",
|
||||
"Агенты сразу продолжат на выбранной подписке": "The agents continue on the chosen subscription at once",
|
||||
"Перевести агентов": "Move agents",
|
||||
"Переведено агентов: {n}. Ещё {m} — некуда: свободной рабочей подписки нет.": "Agents moved: {n}. {m} more have nowhere to go: no free working subscription.",
|
||||
"Переведено агентов: {n}. Они продолжают на новой подписке.": "Agents moved: {n}. They carry on with the new subscription.",
|
||||
"переключил администратор": "switched by the administrator",
|
||||
"Агенты уже на этой подписке": "The agents are already on this subscription",
|
||||
"Подписка «{name}» сейчас не работает — выберите другую": "Subscription «{name}» is not working now — choose another",
|
||||
};
|
||||
|
||||
@ -306,4 +306,13 @@ export const admin: Dict = {
|
||||
"открыть": "ашу",
|
||||
"с {date}": "{date} бастап",
|
||||
"пароль": "құпиясөз",
|
||||
"Куда перевести агентов": "Агенттерді қайда ауыстыру",
|
||||
"на любую свободную": "кез келген бос жазылымға",
|
||||
"Агенты сразу продолжат на выбранной подписке": "Агенттер таңдалған жазылымда бірден жалғастырады",
|
||||
"Перевести агентов": "Агенттерді ауыстыру",
|
||||
"Переведено агентов: {n}. Ещё {m} — некуда: свободной рабочей подписки нет.": "Ауыстырылған агенттер: {n}. Тағы {m} — баратын жер жоқ: бос жұмыс жазылымы жоқ.",
|
||||
"Переведено агентов: {n}. Они продолжают на новой подписке.": "Ауыстырылған агенттер: {n}. Олар жаңа жазылымда жалғастырады.",
|
||||
"переключил администратор": "әкімші ауыстырды",
|
||||
"Агенты уже на этой подписке": "Агенттер осы жазылымда тұр",
|
||||
"Подписка «{name}» сейчас не работает — выберите другую": "«{name}» жазылымы қазір жұмыс істемейді — басқасын таңдаңыз",
|
||||
};
|
||||
|
||||
@ -4,6 +4,7 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { after, before, describe, test } from "node:test";
|
||||
import { events } from "@peppa/db";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { core, db, project, runner, setDefaultOwner, teardown, tick, waitFor } from "./helpers.ts";
|
||||
|
||||
process.env.PEPPA_SECRET = "mock-secret-for-tests";
|
||||
@ -228,3 +229,22 @@ describe("Справедливость между проектами", () => {
|
||||
for (const s of [x1, x2]) await core.updateSession(db, s.id, { status: "done" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("PEP-176: суперадмин переводит агентов вручную", () => {
|
||||
test("агент с подписки переезжает на выбранную; на ту же — отказ", async () => {
|
||||
const a = await claudeSub("Manual A", "mana");
|
||||
const b = await claudeSub("Manual B", "manb");
|
||||
const pool = await core.createPool(db, { name: "Ручной пул", subscriptionIds: [a.id, b.id] });
|
||||
const p = await project({ turns: [[{ say: "Работаю." }], [{ say: "Продолжаю на новой подписке." }]] });
|
||||
await core.setProjectPool(db, (await core.getProject(db, p.key)).id, pool.id);
|
||||
const sid = await p.start({ subscriptionIds: [a.id] });
|
||||
await waitFor("starts on A", async () => (await core.getSession(db, sid)).subscriptionId === a.id);
|
||||
await assert.rejects(runner.switchAgents(db, { fromId: a.id, toId: a.id }), /уже на этой подписке/);
|
||||
const r = await runner.switchAgents(db, { fromId: a.id, toId: b.id });
|
||||
assert.deepEqual(r, { moved: 1, skipped: 0 });
|
||||
const s = await core.getSession(db, sid);
|
||||
assert.equal(s.subscriptionId, b.id, "the agent is on B now");
|
||||
const ev = (await db.select().from(events).where(eq(events.sessionId, sid))).filter((e) => e.type === runner.SWITCH_EVENT).at(-1);
|
||||
assert.equal((ev?.payload as { reason?: string })?.reason, "manual");
|
||||
});
|
||||
});
|
||||
|
||||
Loading…
Reference in New Issue
Block a user