Merge branch 'main' into task/pep-184
This commit is contained in:
commit
173b8c77dc
@ -3,6 +3,7 @@
|
||||
Пишет агент через MCP `remember` (PEP-30).
|
||||
|
||||
## Команды
|
||||
- Экраны без живых данных: `PEPPA_HOME=<tmp> PEPPA_DB=<tmp>/peppa.db PEPPA_SECRET=x peppa db migrate`, `DATABASE_URL=<tmp>/peppa.db node apps/web/scripts/mock-ui-seed.ts mock-pm`, `next dev -p <порт>` в apps/web с тем же env и `PEPPA_WEB_URL`, `peppa web login-link mock-pm`; страницы — curl с cookie (текст без `<script>`); вид «Инженер» — settings `ui.mode:<userId>` = `"engineer"`. `next dev` правит apps/web/AGENTS.md (он в git — `git checkout`, не удалять) и next-env.d.ts — не коммитить.
|
||||
- Экраны без живых данных: `PEPPA_HOME=<tmp> PEPPA_DB=<tmp>/peppa.db PEPPA_SECRET=x peppa db migrate`, `DATABASE_URL=<tmp>/peppa.db node apps/web/scripts/mock-ui-seed.ts mock-pm`, `next dev -p <порт>` в apps/web с тем же env и `PEPPA_WEB_URL`, `peppa web login-link mock-pm`; страницы — curl с cookie (текст без `<script>`); вид «Инженер» — settings `ui.mode:<userId>` = `"engineer"`. `next dev` создаёт apps/web/AGENTS.md и правит next-env.d.ts — не коммитить, вернуть `git checkout` (AGENTS.md в репо — не `rm`).
|
||||
- Проверка словаря (PEP-124): `pnpm lint` падает, когда в файле экрана слов из «Нельзя» docs/glossary.md больше, чем в docs/glossary-baseline.json; чистишь тексты — `pnpm lint --update` (список только уменьшать); текст «Инженер» или бытовое значение — `glossary-ignore: <почему>`. После rebase на PEP-124 править слова, не baseline.
|
||||
|
||||
@ -13,6 +14,7 @@
|
||||
- Шаблонная строка с t()/m() внутри (`` `<b>${t("…")}</b>` ``) i18n-check считает непереведённой — собирай конкатенацией. В apps/bot `m` импортирован как `tr`.
|
||||
- Gitea 1.22 `GET /compare/<base>...<head>` принимает только имена веток (SHA → 404, PEP-101; mock-gitea так же) — сравнение подсказка, не гейт.
|
||||
- localizeText выбирает вариант по числу НЕпереведённых русских букв (Rendered.left), не по кириллице: казахский тоже кириллица. Эвристика «есть кириллица = не переведено» ломает kk.
|
||||
- Homebrew на Mac Пеппы чужой — brew install не проходит. Headless Chrome: fake-audio не работает — подменяй getUserMedia; `--screenshot` страницы за входом виснет на живых обновлениях — проверяй текст curl'ом.
|
||||
- Homebrew на Mac Пеппы чужой. Headless Chrome игнорирует fake-audio — подменяй getUserMedia.
|
||||
- Безопасность (PEP-133): git-прокси релея агента (allowedGitPath) отклоняет %2e/%2f/%5c/%25 и `\` — fetch сворачивает %2e%2e как dot-сегмент; защитные заголовки — headers() в next.config.ts, строгий script-CSP не включён (Next inline-скрипты).
|
||||
- Проверка экранов на `next dev`: открывай `http://localhost:<порт>`, не 127.0.0.1 (allowedDevOrigins — без гидрации кнопки молчат); `PEPPA_WEB_URL` для login-link тот же. chrome-devtools MCP занят другой сессией — playwright-core (`~/.hermes/hermes-agent/node_modules/playwright-core`) + `chrome-headless-shell` из `~/Library/Caches/ms-playwright`.
|
||||
@ -38,6 +40,7 @@
|
||||
- Эталон (PEP-184, PM): подписка прогона — в момент запуска наименее загруженная свободная из общего пула, только свободная ёмкость (PEP-182); суперадмин может закрепить подписку/пул. Про подписку PM не спрашивать.
|
||||
|
||||
## Соглашения
|
||||
- Ёмкость подписки (PEP-182): новый путь запуска или переноса раннера — только через `pickSubscription`/`rotationCandidate` (считают живых по `capacity.ts`); `NoCapacityError` → `startTaskOnRunner` ставит задачу в очередь `capacity.wait:<taskId>`, запускает `capacityQueueTick`. В тестах места заполняй `core.createSession` с `subscriptionId`, задачу из очереди убирай `moveTask(backlog)` — иначе её подхватит тик соседнего теста.
|
||||
- Тестовый стенд со службой «inline» (PEP-186): `PEPPA_RUNNER_MODE=inline PEPPA_ROTATE=off` у `next dev`, иначе ответ из веба не дойдёт или ротация запустит агентов; суперадмину для входа по ссылке — `peppa platform allow <login>`. `apps/web/AGENTS.md` в репо — не удалять (next dev его не создаёт заново).
|
||||
- Пауза проекта (PEP-174): всё, что запускает агента, зовёт модель или пишет человеку по проекту, — через узкие места (`startRunner`/`resumeSession`, `claudePrint`, `deliverToUser`) или с `isProjectPaused`; тик пропускает проект, не теряя своё состояние.
|
||||
- i18n (PEP-98): текст пользователю — ключ = русская строка в `t()`/`m()` + перевод в `i18n/en/<раздел>.ts` и `i18n/kk/<раздел>.ts` (тесты i18n-check и i18n-kk падают без перевода). Ключ-шаблон, кончающийся плейсхолдером, — специфичный. «Peppa FACTORY» не склоняется; в kk окончание через дефис (Peppa FACTORY-нің); к {плейсхолдеру} kk-окончание не клеить — фраза вокруг именительного («Жаңа {task}»); `wording(mode,"kk")` отдаёт именительный. Тексты агентам (RULES.md, промпты) говорят «Пеппа» — не трогаем.
|
||||
|
||||
@ -82,6 +82,7 @@
|
||||
- **Секреты (PEP-54/19)**: секреты проекта (агентам и, PEP-112, выкаченному продукту) — таблица `project_secrets` (имя env, `value_enc` = `encrypt`, кто менял, `last_used_at`), `core/secrets.ts` (`setProjectSecret`/`deleteProjectSecret` через `projectForUser`, имена `^[A-Z][A-Z0-9_]*$` без зарезервированных `PATH`/`PEPPA_*`/`CLAUDE_*`…, `projectSecretEnv`, `projectSecretMasker`); веб «⋯ Настройки проекта → Секреты» (значение только на запись). Раннер (`launch` в runner/sessions.ts) пишет `secrets.env` (0600) в каталог поколения, `launch.sh` его читает и сразу удаляет — значений нет в argv tmux; событие `secrets_issued {names}`. Маскировка `••••` — `TerminalFeed` (`mask`, из `terminalSse`) и `recordStep`. MCP `list_secrets` (агент — проект своей сессии; PM — доступный проект), только имена. Ревизия (core/secrets-audit.ts `secretsAudit`): секреты платформы `PLATFORM_SECRETS` (задан ли, возраст от `settings` `secrets.rotated:<NAME>`, кто использует, шаги ротации), шифрование по колонкам, MCP-токены по клиентам, подписки, секреты проектов — `/secrets` (суперадмин) и `peppa secrets audit|new-key|reencrypt|rotated|revoke-client|check-gitea|list`. Ротация `PEPPA_SECRET` двумя ключами: `PEPPA_SECRET_PREVIOUS` принимается для `decrypt`/`verify`/хэшей OAuth (`hashTokenCandidates`)/подписей вебхуков, пишется только текущим; `reencryptAll` переводит все `*_enc`. Новые зашифрованные колонки — добавлять в `encryptedColumns` (secrets-audit.ts), иначе ротация их потеряет
|
||||
- **Подписки (PEP-67)**: раздел `/subscriptions` только для суперадмина (`isSuperadmin(db, user)` в core/monitor.ts = логин из `platform.admins`; остальным пункта меню нет, URL → 404, actions в `app/(app)/subscriptions/actions.ts` через `requireSuperadmin`). Таблицы `subscriptions` (claude|codex|opencode, статус pending/active/limited/auth_error), `subscription_pools` + `subscription_pool_members`, `projects.subscription_pool_id` (пул проекта, «⋯ Настройки проекта»), `sessions.subscription_id`. Вход — runner/subscription-login.ts в tmux `peppa-auth-sub<id>`: Claude `claude setup-token` (ссылка → код → токен в `secret_enc`) или готовый токен; Codex `codex login --device-auth` (ссылка + код, страница опрашивает) или `--with-api-key`, вход живёт в своём `CODEX_HOME` = `$PEPPA_HOME/subscriptions/s<id>/codex` (0700); OpenCode — ключ провайдера (anthropic/openai/openrouter) зашифрован. «Проверить» — `checkSubscription` (runner/subscriptions.ts: `claude -p` / `codex exec` / `opencode run`). Раннер: `startSession(…, { subscriptionIds, poolId, provider })` → `pickSubscription` (отмеченные → пул → пул проекта; первая свободная активная, иначе наименее занятая; нет пула — вход машины), провайдер сессии = провайдер подписки, env подписки (`CLAUDE_CODE_OAUTH_TOKEN` / `CODEX_HOME` / ключ), resume — на той же. **Ротация (PEP-39)**: лимит (StopFailure/баннер) помечает подписку «лимит до …» (`markSubscriptionLimited`), `recordLimit` при свободной подписке того же провайдера в пуле (`rotationCandidate`: пул проекта, иначе пулы текущей подписки; наименее занятая) ставит `sessions.rotate_reason=limit` вместо пинга PM, вачдог (runner/rotation.ts `tryRotate`/`rotateSession`) убивает tmux и `resumeSession` на новой подписке — Claude/OpenCode тот же разговор, Codex заново (`conversation_id` сбрасывается, история в `CODEX_HOME` аккаунта не переносится); событие `subscription_switched` + сообщение в Telegram (`sendProjectMessage`). Порог: баннер «N% of your … limit» (≥ `PEPPA_ROTATE_THRESHOLD_PCT`, 85) → `rotate_reason=threshold`, Stop-хук не подталкивает, после хода — на подписку без сессий. Свободных нет — ждёт сброса (PEP-56); освободилась раньше — переключит. Предел `PEPPA_ROTATE_MAX_PER_HOUR` (3), выключение `PEPPA_ROTATE=off`. Справедливость: проект с ≥ `PEPPA_POOL_PROJECT_MAX` (2) подписками пула не получает свободную, пока сессия другого проекта ждёт сброса на этом пуле (`poolRestricted`). Мок: `limit.credential` в сценарии — лимит только на входе с этой подстрокой, `{warn: N}` — баннер порога. Провайдер OpenCode (`providers.ts`): `opencode <dir> --prompt`, правила и MCP из `OPENCODE_CONFIG` (opencode.json в каталоге запуска), хуков нет — статус по процессу. Миграция 0003 перенесла токены `users.claude_token_enc` (PEP-13, колонки больше не читаются) в подписки «Claude — <login>» и пулы проектов владельца. Моки: `mock-claude setup-token|-p`, `mock-codex login|exec`, `mock-opencode`
|
||||
- **Подписки без остановок (PEP-107)**: `rotationCandidate` — нет свободной подписки того же провайдера → claude↔codex (`PEPPA_ROTATE_CROSS=off` выключает; OpenCode не участвует), `rotateSession` меняет `sessions.provider` (`updateSession` принимает `provider`), новый запуск без resume, событие `subscription_switched` с `fromProvider`/`toProvider`, «переехал…». `core/subscription-care.ts`: `poolOverview(s)` (подписки пула: `label` «в работе: N агентов»/«свободна»/«лимит до»/…, окно использования из `listAccountUsage`, заём), `subscriptionWarnTick` (вачдог: пул проекта с одной пригодной подпиской ≥ `PEPPA_ROTATE_THRESHOLD_PCT` → одно сообщение на окно, отметка `settings` `subscription.warned:<sub>:<pool>`), `warnLastSubscription` (баннер CLI без замены, раз в 5 ч), займы `lendSubscription`/`returnLoan(Now)`/`expireLoans` (строки `settings` `subscription.loan:<pool>:<sub>`, член пула; по сроку из тика). `removeOwnSubscription` (runner/project-subscription.ts; не при работающих на ней агентах, не заём). Веб: `components/PoolSubscriptions.tsx` в «⋯ Настройки проекта → Подписки» («Добавить ещё Claude/ChatGPT», «Убрать») и «Картина по пулам» + «Одолжить подписку» на `/subscriptions`. Подсказка «добавьте ещё одну подписку» — `ADD_SUBSCRIPTION_HINT` в сообщениях о лимите. Тест `subscription-failover.test.ts`
|
||||
- **Ёмкость подписки (PEP-182)**: `core/capacity.ts` — не больше ёмкости живых раннеров (не `done`/`failed`) на подписку по всем проектам; ёмкость набора — `settings` `pool.capacity:<poolId>` (1–20, нет строки = `defaultCapacity()` 9, `PEPPA_SUBSCRIPTION_CAPACITY`), подписки в нескольких наборах — минимум. `pickSubscription` берёт наименее занятую подписку с местом, иначе `NoCapacityError`; `rotationCandidate` не ведёт на полную. `startTaskOnRunner` (`startOrWait`) ловит отказ → задача остаётся «В работе» без раннера, `capacity.wait:<taskId>` (`waitForCapacity`, событие `capacity_wait`); `moveTask` в бэклог/готово и архив чистят. Порядок — `capacityQueue` (очередь на набор: внутри проекта по доске, проекты по кругу, первым ждущий дольше), `capacityQueueTick` (runner/capacity-queue.ts) в вачдоге перед `autonomyTick`; отказ по месту — не сбой (никому не пишется). Диспетчер считает очередь в WIP и без места (`poolHasRoom`) не берёт из бэклога. Команда: `assertAgentAvailable` в `startRunner` до создания сессии и `teamHasRoomSync` в `ensureSessionAgent` — новый агент, только если свободных нет и живые раннеры на подписках с новым помещаются в суммарную ёмкость; сессии без подписки — как раньше. Resume ёмкость не проверяет. Веб: «Подписки» — «агентов: N из M», `PoolCapacity` (загрузка, очередь, поле «Агентов на подписку» → `setPoolCapacityAction`); `WorkLine` «Делается · В очереди» на Главной (`progressOverview.work`) и доске; пометка на карточке (`Card.queued`) и странице задачи (`storyProductView.queued`). Тест `subscription-capacity.test.ts`
|
||||
- **Простая ротация (PEP-170)**: кончилась подписка — агент переходит на следующую свободную; заранее по порогу (85%) не переключает, только предупреждает, если запасной нет (`PEPPA_ROTATE_EARLY=on` возвращает старое). `/subscriptions` — «Нужно ваше внимание» (ошибка входа, брошенный вход, проект без запасной) → «Кто на чём работает» (карточка набора = пул: строки с одним статусом, «следующая» — `PoolSubscriptionState.next`, «Убрать» / «Добавить подписку…» через `updatePoolAction`, лента `PoolOverview.switches` из событий `subscription_switched` за неделю) → «Подключить подписку»; редактора пулов и формы «Одолжить» в вебе нет (функции займа остались). Лента переключений — и в «⋯ Настройки проекта → Подписки» (`PoolSwitches`)
|
||||
- **Попросить подписку у администратора (PEP-186)**: `runner/subscription-request.ts`. Кнопка «Попросить подписку у администратора» (`components/SubscriptionRequest.tsx`, `requestSubscriptionAction`) — в полосе «Агенты продолжат в…» (`subscriptionRequestOffers`), на плашке «Агенты не запустятся» и в «⋯ Настройки проекта → Подписки» (`subscriptionRequestOffer`: владелец/участник, не суперадмин; агенты `rate_limited` или `projectPoolExhausted`; в наборе уже есть заём — кнопки нет), в Telegram под сообщением фабрики о лимите (`s:<sessionId>:ask`). `requestSubscription`: один открытый запрос на проект, 3 в сутки на пользователя (`settings` `subscription.request:<projectId>` / `subscription.request.q:<qid>` / `subscription.request.log:<userId>`), вопрос `question` суперадмину в платформенном проекте: «Одолжить до сброса» (по умолчанию) · «Одолжить на сутки» · «Отказать»; нет свободной подписки (`loanCandidate`: рабочая подписка суперадмина или общего пула, вне набора, < `LOAN_MAX_AGENTS` = 9 агентов, окно ниже 85%) — «Напомнить позже» · «Отказать». `onSubscriptionRequestAnswer`: заём — `lendSubscription(…, { until, quiet })` до ближайшего сброса (или 24 ч), ждущие агенты сразу `tryRotate`; отказ (свой текст = причина) — запрос закрыт. `subscriptionRequestTick` (вачдог, до `expireLoans`): срок вышел → `returnLoan(…, { quiet })`, агенты на ней — `rotateSession` с причиной `loan` на свою подписку, иначе `rate_limited` до её сброса; «Напомнить позже» — снова через час; агенты снова работают сами — вопрос закрывается. Пользователю — `attention` без имени подписки. `/subscriptions` → «Нужно ваше внимание» — открытые запросы с теми же кнопками (`answerQuestion`). Тест `subscription-request.test.ts`
|
||||
- **Полоса для продакта и имена подписок (PEP-121)**: в режиме «Продакт» полоса над страницами — `AgentsStrip` («Агенты работают» / «Агенты продолжат в ЧЧ:ММ», `agentsLine` в core/usage.ts: пауза — только когда все живые агенты проектов пользователя ждут лимита, или никто не запущен и все подписки пулов в лимите); «Инженер» — прежний `UsageStrip`. Имя подписки (в нём логин подключившего) видят суперадмин и автор (`subscriptions.created_by`): `core/subscription-names.ts` (`visibleSubscriptionName(sub, viewer)`, `publicSubscriptionName` → «Подписка Claude|ChatGPT|OpenCode»); `accountUsageForUser` (полоса, `/status`, `get_usage`) и `poolOverview(…, viewer)` маскируют сами; в вебе имя у сессий — только через `<SubscriptionName>` / `subscriptionNamesVisible()` (суперадмин), `switchText(payload, names)`; сообщения участникам проекта (переключение, последняя подписка, запасная, «агенты не запустятся») — без имён, в payload событий имена остаются. Новое место показа подписки — через эти функции. Тест `subscription-names.test.ts`
|
||||
|
||||
@ -41,6 +41,8 @@ import { saveProjectBudgetAction } from "../../actions";
|
||||
// PEP-127: on its own line — the long @peppa/core import above is edited by every story.
|
||||
import { delayedTaskIds, pendingQuestions, listPendingAccepts, PENDING_ACCEPT_LABEL, PLATFORM_DELAY_LABEL } from "@peppa/core";
|
||||
import { trashDaysLeft } from "@peppa/core";
|
||||
import { queuePositions, workLine } from "@peppa/core";
|
||||
import { WorkLine } from "@/components/WorkLine";
|
||||
import { deleteProjectAction } from "../../actions";
|
||||
import { DeleteProjectControl, mayDeleteProject, RestoreProjectButton } from "@/components/ProjectDelete";
|
||||
|
||||
@ -153,6 +155,8 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
||||
// PEP-150: the delay line — not on a story whose question waits for the owner.
|
||||
const delayed = await delayedTaskIds(db);
|
||||
if (delayed.size) for (const q of await pendingQuestions(db, p.id)) if (q.taskId != null) delayed.delete(q.taskId);
|
||||
// PEP-182: stories waiting for a free agent, and «Делается · В очереди» above the board.
|
||||
const [queued, work] = tab === "board" ? await Promise.all([queuePositions(db, p.id), workLine(db, [p.id])]) : [new Map<number, number>(), null];
|
||||
const [intake, refining] = await Promise.all([getIntakeSettings(db, p.id), intakePendingTasks(db, p.id)]);
|
||||
const cards: Card[] = tasks
|
||||
.filter((x) => !epicFilter || x.goalId === epicFilter.id)
|
||||
@ -170,6 +174,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
||||
agent: agentNames.get(x.id) ?? null,
|
||||
accepted: accepted.has(x.id) ? t.text(PENDING_ACCEPT_LABEL) : null,
|
||||
delayed: delayed.has(x.id) && x.status !== "done" ? t.text(PLATFORM_DELAY_LABEL) : null,
|
||||
queued: queued.get(x.id) ?? null,
|
||||
refining: refining.has(x.id) ? (refining.get(x.id) === "waiting" ? t("ждёт ваших ответов") : t("уточняется")) : null,
|
||||
};
|
||||
});
|
||||
@ -647,6 +652,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
||||
)}
|
||||
</nav>
|
||||
)}
|
||||
{work && <WorkLine line={work} className="mb-2" />}
|
||||
<Board cards={cards} back={back} />
|
||||
</>
|
||||
)}
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
"use server";
|
||||
// «Подписки» (PEP-67): every action is superadmin-only (others get "not found").
|
||||
|
||||
import { createPool, deletePool, getProject, lendSubscription, PeppaError, returnLoanNow, requireSuperadmin, setProjectPool, updatePool, updateSubscription, type SubscriptionProvider, setSubscriptionAccount } from "@peppa/core";
|
||||
import { createPool, setPoolCapacity, deletePool, getProject, lendSubscription, PeppaError, returnLoanNow, requireSuperadmin, setProjectPool, updatePool, updateSubscription, type SubscriptionProvider, setSubscriptionAccount } from "@peppa/core";
|
||||
import { addPoolSubscription, addSubscription, switchAgents, cancelLogin, checkSubscription, finishClaudeLogin, removeSubscription, startClaudeLogin, startCodexLogin } from "@peppa/runner";
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { redirect } from "next/navigation";
|
||||
@ -162,3 +162,13 @@ export async function returnLoanAction(f: FormData) {
|
||||
return `${BASE}#overview`;
|
||||
});
|
||||
}
|
||||
|
||||
/** PEP-182: «Агентов на подписку» of a set (1–20), works from the next start on. */
|
||||
export async function setPoolCapacityAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const id = Number(str(f, "poolId"));
|
||||
await setPoolCapacity(db, user, id, Number(str(f, "capacity")));
|
||||
return `${BASE}#pool-${id}`;
|
||||
});
|
||||
}
|
||||
|
||||
@ -5,7 +5,7 @@ import { pendingLogin, pollCodexLogin, type PendingLogin, backfillCodexAccounts,
|
||||
import { answerQuestion } from "@/app/(app)/actions";
|
||||
import { LocalTime } from "@/components/LocalTime";
|
||||
import { AutoRefresh } from "@/components/AutoRefresh";
|
||||
import { PoolSubscriptions, PoolSummary, PoolSwitches } from "@/components/PoolSubscriptions";
|
||||
import { PoolCapacity, PoolSubscriptions, PoolSummary, PoolSwitches } from "@/components/PoolSubscriptions";
|
||||
import { Hidden } from "@/components/cards";
|
||||
import { ago, Disclosure, Empty, Flash, Notice, PageHeader, Section } from "@/components/common";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
@ -27,6 +27,7 @@ import {
|
||||
addPoolSubscriptionAction,
|
||||
switchAgentsAction,
|
||||
returnLoanAction,
|
||||
setPoolCapacityAction,
|
||||
reconnectSubscription,
|
||||
submitLoginCode,
|
||||
renameSubscription,
|
||||
@ -140,6 +141,7 @@ function SetCard({ o, subs, t }: { o: PoolOverview; subs: SubscriptionView[]; t:
|
||||
</div>
|
||||
<PoolSubscriptions
|
||||
o={o}
|
||||
capacity
|
||||
action={(s) => (
|
||||
<>
|
||||
{/* PEP-176: move this subscription's agents by hand — to one of the pool's working subscriptions or to any free one. */}
|
||||
@ -200,6 +202,19 @@ function SetCard({ o, subs, t }: { o: PoolOverview; subs: SubscriptionView[]; t:
|
||||
)}
|
||||
/>
|
||||
<PoolSummary o={o} />
|
||||
<PoolCapacity
|
||||
o={o}
|
||||
form={
|
||||
<form action={setPoolCapacityAction} className="ml-auto flex items-center gap-1.5">
|
||||
<Hidden fields={{ poolId: o.pool.id }} />
|
||||
<Label className="flex-row items-center gap-1.5 text-xs font-normal">
|
||||
{t("Агентов на подписку")}
|
||||
<Input name="capacity" type="number" min={1} max={20} required defaultValue={o.capacity} className="h-7 w-16 text-sm" />
|
||||
</Label>
|
||||
<Button size="xs" variant="outline">{t("Сохранить")}</Button>
|
||||
</form>
|
||||
}
|
||||
/>
|
||||
{addable.length > 0 && (
|
||||
<form action={updatePoolAction} className="flex flex-wrap items-center gap-2">
|
||||
<Hidden fields={{ id: o.pool.id }} />
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
// Story page (PEP-32): header with the story, the agent and its live session; tabs by the
|
||||
// OpenSpec artifacts and the course of work (?tab=). Live updates — PEP-37, agent steps — PEP-33.
|
||||
import { queuePositions } from "@peppa/core";
|
||||
import { Markdown } from "@/components/Markdown";
|
||||
import Link from "next/link";
|
||||
import { notFound } from "next/navigation";
|
||||
@ -255,6 +256,8 @@ export default async function StoryPage({ params, searchParams }: { params: Prom
|
||||
waitsFor: blockers.filter((b) => b.open).map((b) => b.title),
|
||||
accepted: !!pendingAccept,
|
||||
delayed,
|
||||
// PEP-182: no agent yet because all are busy — the place in the queue.
|
||||
queued: live ? null : ((await queuePositions(db, task.projectId)).get(task.id) ?? null),
|
||||
});
|
||||
|
||||
const body = (
|
||||
|
||||
@ -34,6 +34,8 @@ export interface Card {
|
||||
accepted?: string | null;
|
||||
/** PEP-150: a delay on the platform's side — nothing is needed from the owner. */
|
||||
delayed?: string | null;
|
||||
/** PEP-182: place in the queue for a free agent (in work, no agent yet). */
|
||||
queued?: number | null;
|
||||
}
|
||||
export interface CardProgress {
|
||||
done: number;
|
||||
@ -214,6 +216,11 @@ export function Board({ cards, back }: { cards: Card[]; back: string }) {
|
||||
{card.delayed}
|
||||
</Badge>
|
||||
)}
|
||||
{card.queued != null && (
|
||||
<Badge variant="muted" className="self-start whitespace-normal text-left" data-queued={card.queued}>
|
||||
{t("В очереди: {n}-я, начнётся, когда освободится агент", { n: card.queued })}
|
||||
</Badge>
|
||||
)}
|
||||
{card.agent && <AgentBadge name={card.agent} className="text-muted-foreground" />}
|
||||
{card.progress && <ProgressLine p={card.progress} />}
|
||||
{(STATUS[card.status] || NEXT[c.id] || card.epic || card.blocked) && (
|
||||
|
||||
@ -20,7 +20,7 @@ function tone(s: PoolSubscriptionState): "ok" | "warn" | "danger" | "muted" | "p
|
||||
* free, limit until, sign-in error) and «следующая» on the one agents move to when theirs runs
|
||||
* out; `action` adds buttons per row.
|
||||
*/
|
||||
export async function PoolSubscriptions({ o, action }: { o: PoolOverview; action?: (s: PoolSubscriptionState) => ReactNode }) {
|
||||
export async function PoolSubscriptions({ o, action, capacity }: { o: PoolOverview; action?: (s: PoolSubscriptionState) => ReactNode; capacity?: boolean }) {
|
||||
const t = await getT();
|
||||
if (!o.subscriptions.length) return <p className="m-0 text-sm text-muted-foreground">{t("Подписок пока нет.")}</p>;
|
||||
return (
|
||||
@ -33,6 +33,12 @@ export async function PoolSubscriptions({ o, action }: { o: PoolOverview; action
|
||||
{!s.name.includes(KIND[s.provider]) && <span className="text-xs text-muted-foreground">{KIND[s.provider]}</span>}
|
||||
<Badge variant={tone(s)}>{t.text(s.label)}</Badge>
|
||||
{s.next && <Badge variant="info">{t("следующая")}</Badge>}
|
||||
{/* PEP-182: live runners against the set's capacity — the superadmin's «Подписки» only. */}
|
||||
{capacity && (
|
||||
<span className={`text-xs ${s.activeSessions >= s.capacity ? "text-warn" : "text-muted-foreground"}`} data-subscription-load={s.id}>
|
||||
{t("агентов: {n} из {max}", { n: s.activeSessions, max: s.capacity })}
|
||||
</span>
|
||||
)}
|
||||
{s.usage && !s.limitedUntil && s.usage.pct! >= 50 && (
|
||||
<span className={`text-xs ${s.usage.pct! >= 85 ? "text-warn" : "text-muted-foreground"}`}>
|
||||
{s.usage.resetsAt
|
||||
@ -81,3 +87,15 @@ export async function PoolSwitches({ o }: { o: PoolOverview }) {
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** PEP-182: the set's load and queue, and the capacity per subscription (superadmin). */
|
||||
export async function PoolCapacity({ o, form }: { o: PoolOverview; form?: ReactNode }) {
|
||||
const t = await getT();
|
||||
return (
|
||||
<div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted-foreground" data-pool-capacity={o.pool.id}>
|
||||
<span className={o.total && o.live >= o.total ? "text-warn" : undefined}>{t("Загрузка: {live} из {total}", { live: o.live, total: o.total })}</span>
|
||||
<span className={o.queued ? "text-warn" : undefined}>{t("В очереди: {n}", { n: o.queued })}</span>
|
||||
{form}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@ -2,6 +2,7 @@ import Link from "next/link";
|
||||
import type { ProgressOverview as Overview, ProjectProgress } from "@peppa/core";
|
||||
import { AgentBadge } from "@/components/AgentBadge";
|
||||
import { Empty, Key } from "@/components/common";
|
||||
import { WorkLine } from "@/components/WorkLine";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import { m, type Translator } from "@peppa/shared/i18n";
|
||||
@ -72,6 +73,7 @@ function ProjectRow({ p, t, w }: { p: ProjectProgress; t: Translator; w: Words }
|
||||
</span>
|
||||
</div>
|
||||
<StackedBar c={p} t={t} w={w} />
|
||||
<WorkLine line={p.work} className="text-xs" />
|
||||
{p.working.length > 0 && (
|
||||
<ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm">
|
||||
{p.working.map((s) => (
|
||||
@ -79,6 +81,7 @@ function ProjectRow({ p, t, w }: { p: ProjectProgress; t: Translator; w: Words }
|
||||
<Key href={`/t/${s.key}`}>{s.key}</Key>
|
||||
<span className="min-w-0 flex-[1_1_10em] truncate">{s.title}</span>
|
||||
{s.agent && <AgentBadge name={s.agent} className="text-muted-foreground" />}
|
||||
{s.queued != null && <span className="text-xs text-muted-foreground">{t("В очереди: {n}-я, начнётся, когда освободится агент", { n: s.queued })}</span>}
|
||||
{s.total ? (
|
||||
<span className="text-xs text-muted-foreground" title={s.current ?? undefined}>
|
||||
{s.done}/{s.total}
|
||||
@ -119,6 +122,7 @@ export async function ProgressOverview({ data }: { data: Overview }) {
|
||||
</div>
|
||||
<StackedBar c={tot} className="h-3" t={t} w={w} />
|
||||
<Legend c={tot} t={t} />
|
||||
<WorkLine line={data.work} />
|
||||
</div>
|
||||
)}
|
||||
<ul className="m-0 flex list-none flex-col gap-2 p-0">
|
||||
|
||||
23
apps/web/components/WorkLine.tsx
Normal file
23
apps/web/components/WorkLine.tsx
Normal file
@ -0,0 +1,23 @@
|
||||
import type { WorkLine as Line } from "@peppa/core";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { getT } from "@/lib/i18n";
|
||||
|
||||
/**
|
||||
* PEP-182: «Делается: 4 · В очереди: 3» — how many tasks agents work on now and how many wait
|
||||
* for a free agent. No subscriptions and no capacity numbers: that is the superadmin's page.
|
||||
*/
|
||||
export async function WorkLine({ line, className }: { line: Line; className?: string }) {
|
||||
const t = await getT();
|
||||
if (!line.doing && !line.queued) return null;
|
||||
return (
|
||||
<p className={cn("m-0 text-sm text-muted-foreground", className)} data-work-line>
|
||||
{t("Делается: {n}", { n: line.doing })}
|
||||
{line.queued > 0 && (
|
||||
<>
|
||||
{" · "}
|
||||
<span className="text-warn" title={t("Все агенты заняты — задачи начнутся по порядку, когда агент освободится")}>{t("В очереди: {n}", { n: line.queued })}</span>
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
);
|
||||
}
|
||||
@ -0,0 +1,23 @@
|
||||
## Context
|
||||
Подписки и пулы (PEP-67/39/107/170): `pickSubscription` выбирает наименее занятую рабочую подписку без всякого предела, `rotationCandidate` — то же для ротации. Очередь раннеров (`runner_tasks`, PEP-10) — про режим `queue` одного раннера, к ёмкости подписок отношения не имеет. Команда агентов (PEP-75): `ensureSessionAgent` создаёт персонажа, когда все заняты.
|
||||
|
||||
## Goals / Non-Goals
|
||||
Goals: предел живых раннеров на подписку, очередь задач при нехватке места, команда в пределах ёмкости, видимость.
|
||||
Non-Goals: выбор агента по специализации; удаление лишних агентов; анимация «Погоня за задачей»; ёмкость для запуска на входе машины (без подписки) — там предела нет, как раньше.
|
||||
|
||||
## Decisions
|
||||
1. **Ёмкость хранится в `settings`** `pool.capacity:<poolId>` (число 1–20); нет строки = `DEFAULT_CAPACITY` 9 (`PEPPA_SUBSCRIPTION_CAPACITY` меняет умолчание для стендов и тестов). Миграция не нужна. Ёмкость подписки = минимум ёмкостей её наборов (подписка бывает в нескольких); вне наборов — умолчание. При выборе внутри набора берётся ёмкость этого набора.
|
||||
2. **Живой раннер** = сессия с `subscription_id` подписки и статусом не `done`/`failed` (`FINISHED_SESSION_STATUSES`), по всем проектам — тот же счёт, что уже есть в `activeRows`.
|
||||
3. **`NoCapacityError extends PeppaError`** — отдельный класс: его ловят `startTaskOnRunner` (ставит задачу в очередь) и запасной провайдер в `startRunner` (сначала пробует запасного, потом тот же отказ). Отмеченные вручную подписки (`subscriptionIds`) тоже уважают ёмкость.
|
||||
4. **Очередь по ёмкости — `settings` `capacity.wait:<taskId>`** `{at, prompt}`, не `runner_tasks`: там очередь привязана к живому раннеру, а здесь раннера нет. Задача остаётся в статусе `in_progress`. `moveTask` в «В работу» не стартует второй раз, если задача уже ждёт; в «Бэклог»/«Готово» и архив — запись удаляется.
|
||||
5. **Порядок очереди** (`capacityQueue`): очередь общая для набора подписок (пул проекта). Внутри проекта — по порядку на доске (`tasks.position`, затем номер); проекты набора чередуются по кругу, первым идёт тот, кто ждёт дольше. «N-я» — место в очереди набора.
|
||||
6. **`capacityQueueTick`** в тике вачдога перед `autonomyTick`: чистит записи задач, которые ушли из работы, в архиве или уже с раннером; затем по порядку зовёт `startTaskOnRunner`. Отказ по ёмкости — набор полон, его остальные задачи в этом тике не трогаются. Другая ошибка — `platformFailure` (раз в сутки на ошибку), запись остаётся. Владельцу о самой очереди не пишется ничего, кроме пометки на карточке.
|
||||
7. **Диспетчер** (`autonomyTick`, PEP-24): ждущие задачи проекта входят в WIP; новые из бэклога не берутся, пока у набора проекта нет места (`poolHasRoom`) — иначе бэклог перетекал бы в очередь.
|
||||
8. **Ротация**: `rotationCandidate` отбрасывает подписки, где живых раннеров уже не меньше ёмкости. PEP-176 (`switchAgents`) в main ещё нет — когда появится, он должен звать тот же `subscriptionRoom`.
|
||||
9. **Команда**: `ensureSessionAgent` создаёт нового агента, только если свободных нет и `teamHasRoom`: у сессии без подписки (вход машины) — как раньше; иначе живые раннеры на подписках (с новым) помещаются в суммарную ёмкость всех подписок наборов — и подписок на лимите тоже: их раннеры ждут сброса и держат персонажей. Без места — `null` (раннер без персонажа; на практике недостижимо, потому что `startRunner` сначала проверяет `assertAgentAvailable` и отказывает `NoCapacityError` ещё до создания сессии).
|
||||
10. **Resume/перезапуск** существующего раннера ёмкость не проверяет — это не новый раннер; уже работающие раннеры не останавливаются.
|
||||
11. **Видимость**: суперадмину в `PoolOverview` — `capacity`, `live`, `queued`, у подписки `capacity` и строка «агентов: 6 из 9»; форма ёмкости на карточке набора (`setPoolCapacityAction`). Продакту — `workLine` (`doing`, `queued`) на Главной и доске, пометка очереди на карточке; без подписок и чисел ёмкости.
|
||||
|
||||
## Risks / Trade-offs
|
||||
- Между проверкой места и созданием сессии другой раннер может занять слот (ключи сервиса — на задачу): в худшем случае подписка получит ёмкость+1, следующий запуск подождёт. Приемлемо.
|
||||
- Задача, ждущая в очереди, на доске в «В работе» без агента — так и задумано, пометка объясняет.
|
||||
@ -0,0 +1,25 @@
|
||||
## Why
|
||||
Число одновременно работающих агентов ничем не ограничено: на одной подписке Claude шло 16 сессий, и лимит сгорал за час. Когда все агенты заняты, `ensureSessionAgent` создаёт нового — команда только растёт (27 при 4 работающих). PEP-182.
|
||||
|
||||
## What Changes
|
||||
- **Ёмкость подписки** — 9 живых раннеров (сессии не `done`/`failed`) на подписку, по всем проектам. Значение по умолчанию 9, суперадмин меняет его для набора (пула) в «Подписках» (1–20), действует сразу. Ёмкость пула = ёмкость × число рабочих подписок.
|
||||
- **Запуск**: `pickSubscription` берёт наименее загруженную рабочую подписку, где живых раннеров меньше ёмкости. Места нет ни на одной — `NoCapacityError`.
|
||||
- **Очередь по ёмкости**: задача, которой не нашлось места, остаётся «В работе» без раннера с пометкой «В очереди: N-я, начнётся, когда освободится агент» (`settings` `capacity.wait:<taskId>`). `capacityQueueTick` в вачдоге запускает такие задачи сами, как только место освободилось: внутри проекта — по порядку на доске, между проектами пула — по очереди. Это не сбой: владельцу — пометка, суперадминам — ничего.
|
||||
- **Ротация при лимите** переводит раннер только на подписку, где меньше ёмкости; места нет — ждёт сброса, как сейчас.
|
||||
- **Команда не растёт сама**: новый агент создаётся, только если свободных нет и ёмкость позволяет ещё один раннер; иначе раннер не стартует и задача встаёт в очередь. Ручное «Добавить» не меняется.
|
||||
- **Диспетчер** считает задачи в очереди как взятые (WIP) и не берёт новые из бэклога, пока у пула проекта нет места.
|
||||
- **Видно**: «Подписки» — у подписки «агентов: 6 из 9», у набора — общая загрузка, длина очереди и поле ёмкости; режим «Продакт» — на Главной и доске проекта «Делается: 4 · В очереди: 3», на карточке задачи — пометка очереди. Тексты ru/kk/en.
|
||||
- Уже работающие раннеры не останавливаются: на подписке больше ёмкости — новые просто не стартуют.
|
||||
|
||||
## Capabilities
|
||||
### New Capabilities
|
||||
- `subscription-capacity`: ёмкость подписки и пула, очередь задач по ёмкости, рост команды в пределах ёмкости.
|
||||
|
||||
### Modified Capabilities
|
||||
—
|
||||
|
||||
## Impact
|
||||
- `packages/core`: `capacity.ts` (новый), `subscriptions.ts` (`pickSubscription`, `rotationCandidate`), `team.ts`, `subscription-care.ts`, `progress.ts`.
|
||||
- `packages/runner`: `runners.ts` (`startTaskOnRunner`), `flow.ts`, `autonomy.ts`, `capacity-queue.ts` (новый), вачдог.
|
||||
- `apps/web`: «Подписки», Главная, доска проекта; переводы en/kk.
|
||||
- Без миграции: настройки и очередь — в `settings`.
|
||||
@ -0,0 +1,72 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Ёмкость подписки и набора
|
||||
Подписка SHALL держать не больше «ёмкости» живых раннеров одновременно (сессии со статусом не `done` и не `failed`, привязанные к подписке, по всем проектам). Ёмкость по умолчанию — 9; суперадмин SHALL менять её для набора подписок в «Подписках» в пределах от 1 до 20, и новое значение SHALL действовать сразу. Ёмкость набора = ёмкость × число рабочих подписок (активна, не на лимите, не ждёт входа, без ошибки входа).
|
||||
|
||||
#### Scenario: Подписка заполнена — раннер на другой
|
||||
- **GIVEN** в наборе проекта подписки Claude «A» и «B», ёмкость 9
|
||||
- **AND** на «A» работают 9 раннеров, на «B» — 2
|
||||
- **WHEN** задача уходит в работу
|
||||
- **THEN** её раннер запускается на «B»
|
||||
|
||||
#### Scenario: Суперадмин меняет ёмкость
|
||||
- **GIVEN** набор с одной подпиской «A», на ней 3 раннера, ёмкость 9
|
||||
- **WHEN** суперадмин ставит ёмкость 3
|
||||
- **THEN** следующая задача встаёт в очередь, а «A» в «Подписках» показывает «агентов: 3 из 3»
|
||||
|
||||
#### Scenario: Ёмкость вне пределов
|
||||
- **GIVEN** суперадмин на странице «Подписки»
|
||||
- **WHEN** он вводит ёмкость 25
|
||||
- **THEN** значение не сохраняется, и он видит «Агентов на подписку — от 1 до 20»
|
||||
|
||||
### Requirement: Очередь задач при нехватке места
|
||||
Если места нет ни на одной рабочей подписке набора, раннер SHALL не запускаться, а задача SHALL оставаться «В работе» с пометкой «В очереди: N-я, начнётся, когда освободится агент». Как только место освободилось, задача SHALL запускаться сама: внутри проекта — по порядку на доске, проекты набора — по очереди. Очередь — не сбой: суперадминам сообщение не уходит.
|
||||
|
||||
#### Scenario: Мест нет — задача в очереди
|
||||
- **GIVEN** набор с одной подпиской «A», на ней 9 раннеров
|
||||
- **WHEN** задача PEP-5 уходит в работу
|
||||
- **THEN** раннер не запускается, PEP-5 остаётся «В работе» с пометкой «В очереди: 1-я, начнётся, когда освободится агент»
|
||||
|
||||
#### Scenario: Место освободилось
|
||||
- **GIVEN** на подписке «A» 9 раннеров, в очереди PEP-6 и PEP-5, PEP-5 выше на доске
|
||||
- **WHEN** один раннер закончил работу и вачдог сделал тик
|
||||
- **THEN** запускается раннер PEP-5, а PEP-6 остаётся в очереди первой
|
||||
|
||||
#### Scenario: Уже работающие не останавливаются
|
||||
- **GIVEN** на подписке «A» уже 12 раннеров, ёмкость 9
|
||||
- **WHEN** правила включены
|
||||
- **THEN** все 12 продолжают работу, а новые раннеры на «A» не запускаются, пока их не станет меньше 9
|
||||
|
||||
### Requirement: Ротация уважает ёмкость
|
||||
Ротация при лимите SHALL переводить раннер только на подписку набора, где живых раннеров меньше ёмкости; если такой нет, раннер SHALL ждать сброса лимита, как раньше.
|
||||
|
||||
#### Scenario: На запасной подписке нет места
|
||||
- **GIVEN** раннер на «A» упёрся в лимит, на «B» 9 раннеров, ёмкость 9
|
||||
- **WHEN** вачдог ищет, куда переключить раннер
|
||||
- **THEN** переключения нет, раннер ждёт сброса лимита на «A»
|
||||
|
||||
### Requirement: Команда растёт в пределах ёмкости
|
||||
Новый агент в команде SHALL создаваться автоматически, только если свободных агентов нет И ёмкость позволяет запустить ещё один раннер. Иначе раннер SHALL не стартовать (задача встаёт в очередь). Ручное «Добавить» в «Команде» SHALL работать как раньше.
|
||||
|
||||
#### Scenario: Все заняты, ёмкость заполнена
|
||||
- **GIVEN** в команде 9 агентов, все работают на подписке «A» ёмкостью 9
|
||||
- **WHEN** ещё одна задача уходит в работу
|
||||
- **THEN** новый агент не создаётся, задача в очереди
|
||||
|
||||
#### Scenario: Все заняты, место есть
|
||||
- **GIVEN** в команде 2 агента, оба работают на «A» ёмкостью 9
|
||||
- **WHEN** задача уходит в работу
|
||||
- **THEN** создаётся третий агент и запускается раннер
|
||||
|
||||
### Requirement: Загрузка на виду
|
||||
В «Подписках» у каждой подписки SHALL быть видно «агентов: N из M», у набора — общая загрузка и длина очереди. В режиме «Продакт» на Главной и доске проекта SHALL быть видно «Делается: N · В очереди: M» без названий подписок и чисел ёмкости; тексты — на русском, казахском и английском.
|
||||
|
||||
#### Scenario: Продакт видит очередь
|
||||
- **GIVEN** в проекте 4 задачи с работающими агентами и 3 в очереди
|
||||
- **WHEN** владелец в режиме «Продакт» открывает доску
|
||||
- **THEN** он видит «Делается: 4 · В очереди: 3» и не видит названий подписок
|
||||
|
||||
#### Scenario: Очереди нет
|
||||
- **GIVEN** в проекте 2 задачи с работающими агентами и пустая очередь
|
||||
- **WHEN** владелец открывает Главную
|
||||
- **THEN** он видит «Делается: 2» без «В очереди»
|
||||
@ -0,0 +1,19 @@
|
||||
## 1. Ядро
|
||||
- [x] 1.1 `core/capacity.ts`: ёмкость набора (`settings` `pool.capacity:<id>`, 1–20, умолчание 9), ёмкость подписки, `NoCapacityError`, очередь `capacity.wait:<taskId>`, порядок очереди, `workLine`
|
||||
- [x] 1.2 `pickSubscription` и `rotationCandidate` уважают ёмкость
|
||||
- [x] 1.3 `ensureSessionAgent` создаёт агента только при наличии места; `assertAgentAvailable`
|
||||
- [x] 1.4 `poolOverviews`: ёмкость, загрузка, очередь; «агентов: N из M»
|
||||
|
||||
## 2. Раннер
|
||||
- [x] 2.1 `startRunner` / `startTaskOnRunner`: отказ по ёмкости → очередь; `moveTask`/`archiveTask` чистят очередь
|
||||
- [x] 2.2 `capacityQueueTick` в вачдоге перед `autonomyTick`
|
||||
- [x] 2.3 Диспетчер: очередь в WIP, без места — не берёт из бэклога
|
||||
|
||||
## 3. Веб
|
||||
- [x] 3.1 «Подписки»: «агентов: N из M», загрузка и очередь набора, поле ёмкости (суперадмин)
|
||||
- [x] 3.2 Режим «Продакт»: «Делается · В очереди» на Главной и доске, пометка очереди на карточке
|
||||
- [x] 3.3 Переводы en/kk, словарь
|
||||
|
||||
## 4. Проверка
|
||||
- [x] 4.1 Тест `subscription-capacity.test.ts` по сценариям спеки
|
||||
- [x] 4.2 typecheck, lint, i18n, тесты подписок/ротации/команды/автономности
|
||||
77
openspec/specs/subscription-capacity/spec.md
Normal file
77
openspec/specs/subscription-capacity/spec.md
Normal file
@ -0,0 +1,77 @@
|
||||
# subscription-capacity Specification
|
||||
|
||||
## Purpose
|
||||
Ёмкость подписки (PEP-182): не больше N живых раннеров на подписку (9 по умолчанию, суперадмин меняет для набора), очередь задач, которым не хватило места, рост команды агентов в пределах ёмкости и загрузка на виду.
|
||||
|
||||
## Requirements
|
||||
|
||||
### Requirement: Ёмкость подписки и набора
|
||||
Подписка SHALL держать не больше «ёмкости» живых раннеров одновременно (сессии со статусом не `done` и не `failed`, привязанные к подписке, по всем проектам). Ёмкость по умолчанию — 9; суперадмин SHALL менять её для набора подписок в «Подписках» в пределах от 1 до 20, и новое значение SHALL действовать сразу. Ёмкость набора = ёмкость × число рабочих подписок (активна, не на лимите, не ждёт входа, без ошибки входа).
|
||||
|
||||
#### Scenario: Подписка заполнена — раннер на другой
|
||||
- **GIVEN** в наборе проекта подписки Claude «A» и «B», ёмкость 9
|
||||
- **AND** на «A» работают 9 раннеров, на «B» — 2
|
||||
- **WHEN** задача уходит в работу
|
||||
- **THEN** её раннер запускается на «B»
|
||||
|
||||
#### Scenario: Суперадмин меняет ёмкость
|
||||
- **GIVEN** набор с одной подпиской «A», на ней 3 раннера, ёмкость 9
|
||||
- **WHEN** суперадмин ставит ёмкость 3
|
||||
- **THEN** следующая задача встаёт в очередь, а «A» в «Подписках» показывает «агентов: 3 из 3»
|
||||
|
||||
#### Scenario: Ёмкость вне пределов
|
||||
- **GIVEN** суперадмин на странице «Подписки»
|
||||
- **WHEN** он вводит ёмкость 25
|
||||
- **THEN** значение не сохраняется, и он видит «Агентов на подписку — от 1 до 20»
|
||||
|
||||
### Requirement: Очередь задач при нехватке места
|
||||
Если места нет ни на одной рабочей подписке набора, раннер SHALL не запускаться, а задача SHALL оставаться «В работе» с пометкой «В очереди: N-я, начнётся, когда освободится агент». Как только место освободилось, задача SHALL запускаться сама: внутри проекта — по порядку на доске, проекты набора — по очереди. Очередь — не сбой: суперадминам сообщение не уходит.
|
||||
|
||||
#### Scenario: Мест нет — задача в очереди
|
||||
- **GIVEN** набор с одной подпиской «A», на ней 9 раннеров
|
||||
- **WHEN** задача PEP-5 уходит в работу
|
||||
- **THEN** раннер не запускается, PEP-5 остаётся «В работе» с пометкой «В очереди: 1-я, начнётся, когда освободится агент»
|
||||
|
||||
#### Scenario: Место освободилось
|
||||
- **GIVEN** на подписке «A» 9 раннеров, в очереди PEP-6 и PEP-5, PEP-5 выше на доске
|
||||
- **WHEN** один раннер закончил работу и вачдог сделал тик
|
||||
- **THEN** запускается раннер PEP-5, а PEP-6 остаётся в очереди первой
|
||||
|
||||
#### Scenario: Уже работающие не останавливаются
|
||||
- **GIVEN** на подписке «A» уже 12 раннеров, ёмкость 9
|
||||
- **WHEN** правила включены
|
||||
- **THEN** все 12 продолжают работу, а новые раннеры на «A» не запускаются, пока их не станет меньше 9
|
||||
|
||||
### Requirement: Ротация уважает ёмкость
|
||||
Ротация при лимите SHALL переводить раннер только на подписку набора, где живых раннеров меньше ёмкости; если такой нет, раннер SHALL ждать сброса лимита, как раньше.
|
||||
|
||||
#### Scenario: На запасной подписке нет места
|
||||
- **GIVEN** раннер на «A» упёрся в лимит, на «B» 9 раннеров, ёмкость 9
|
||||
- **WHEN** вачдог ищет, куда переключить раннер
|
||||
- **THEN** переключения нет, раннер ждёт сброса лимита на «A»
|
||||
|
||||
### Requirement: Команда растёт в пределах ёмкости
|
||||
Новый агент в команде SHALL создаваться автоматически, только если свободных агентов нет И ёмкость позволяет запустить ещё один раннер. Иначе раннер SHALL не стартовать (задача встаёт в очередь). Ручное «Добавить» в «Команде» SHALL работать как раньше.
|
||||
|
||||
#### Scenario: Все заняты, ёмкость заполнена
|
||||
- **GIVEN** в команде 9 агентов, все работают на подписке «A» ёмкостью 9
|
||||
- **WHEN** ещё одна задача уходит в работу
|
||||
- **THEN** новый агент не создаётся, задача в очереди
|
||||
|
||||
#### Scenario: Все заняты, место есть
|
||||
- **GIVEN** в команде 2 агента, оба работают на «A» ёмкостью 9
|
||||
- **WHEN** задача уходит в работу
|
||||
- **THEN** создаётся третий агент и запускается раннер
|
||||
|
||||
### Requirement: Загрузка на виду
|
||||
В «Подписках» у каждой подписки SHALL быть видно «агентов: N из M», у набора — общая загрузка и длина очереди. В режиме «Продакт» на Главной и доске проекта SHALL быть видно «Делается: N · В очереди: M» без названий подписок и чисел ёмкости; тексты — на русском, казахском и английском.
|
||||
|
||||
#### Scenario: Продакт видит очередь
|
||||
- **GIVEN** в проекте 4 задачи с работающими агентами и 3 в очереди
|
||||
- **WHEN** владелец в режиме «Продакт» открывает доску
|
||||
- **THEN** он видит «Делается: 4 · В очереди: 3» и не видит названий подписок
|
||||
|
||||
#### Scenario: Очереди нет
|
||||
- **GIVEN** в проекте 2 задачи с работающими агентами и пустая очередь
|
||||
- **WHEN** владелец открывает Главную
|
||||
- **THEN** он видит «Делается: 2» без «В очереди»
|
||||
252
packages/core/src/capacity.ts
Normal file
252
packages/core/src/capacity.ts
Normal file
@ -0,0 +1,252 @@
|
||||
// PEP-182: capacity of a subscription — at most N live runners at once (9 by default, a
|
||||
// superadmin changes it per set of subscriptions). A story that finds no room waits «В очереди»
|
||||
// (in progress, no runner) and starts by itself once a runner finishes; the team of personas
|
||||
// grows only within the capacity.
|
||||
import { m as tr } from "@peppa/shared/i18n";
|
||||
import { formatTaskKey } from "@peppa/shared";
|
||||
import { projects, sessions, settings, subscriptionPoolMembers, subscriptions, tasks, type Db } from "@peppa/db";
|
||||
import { and, eq, inArray, isNotNull, like, notInArray } from "drizzle-orm";
|
||||
import { PeppaError } from "./errors.ts";
|
||||
import { FINISHED_SESSION_STATUSES } from "./sessions.ts";
|
||||
import { deleteSetting, getSetting, setSetting } from "./settings.ts";
|
||||
import { getPool, isUsable, requireSuperadmin } from "./subscriptions.ts";
|
||||
import type { User } from "./users.ts";
|
||||
|
||||
export const CAPACITY_MIN = 1;
|
||||
export const CAPACITY_MAX = 20;
|
||||
/** Live runners per subscription when the set has no own value (`PEPPA_SUBSCRIPTION_CAPACITY` for stands). */
|
||||
export const defaultCapacity = () => {
|
||||
const n = Number(process.env.PEPPA_SUBSCRIPTION_CAPACITY ?? 9);
|
||||
return Number.isInteger(n) && n >= CAPACITY_MIN && n <= CAPACITY_MAX ? n : 9;
|
||||
};
|
||||
|
||||
const CAPACITY_PREFIX = "pool.capacity:";
|
||||
const capacityKey = (poolId: number) => `${CAPACITY_PREFIX}${poolId}`;
|
||||
|
||||
/** No subscription of the set has room for one more runner: the story waits in the queue. */
|
||||
export class NoCapacityError extends PeppaError {
|
||||
constructor() {
|
||||
super(tr("Все агенты заняты — задача начнётся, когда освободится агент"));
|
||||
this.name = "NoCapacityError";
|
||||
}
|
||||
}
|
||||
|
||||
export const isNoCapacity = (e: unknown): e is NoCapacityError => e instanceof NoCapacityError || (e as Error | null)?.name === "NoCapacityError";
|
||||
|
||||
/** Runners per subscription of the set (its own value, else the default). */
|
||||
export async function poolCapacity(db: Db, poolId: number): Promise<number> {
|
||||
return (await getSetting<number>(db, capacityKey(poolId))) ?? defaultCapacity();
|
||||
}
|
||||
|
||||
/** Own capacities of the sets: poolId → value (sets with the default are absent). */
|
||||
export async function poolCapacities(db: Db): Promise<Map<number, number>> {
|
||||
const rows = await db.select().from(settings).where(like(settings.key, `${CAPACITY_PREFIX}%`));
|
||||
return new Map(rows.map((r) => [Number(r.key.slice(CAPACITY_PREFIX.length)), Number(r.value)]));
|
||||
}
|
||||
|
||||
/** Superadmin's «Агентов на подписку»: 1..20, works from the next start on. */
|
||||
export async function setPoolCapacity(db: Db, admin: Pick<User, "login">, poolId: number, value: number): Promise<number> {
|
||||
await requireSuperadmin(db, admin);
|
||||
await getPool(db, poolId);
|
||||
const n = Math.floor(Number(value));
|
||||
if (!(n >= CAPACITY_MIN && n <= CAPACITY_MAX)) throw new PeppaError(tr("Агентов на подписку — от {min} до {max}", { min: CAPACITY_MIN, max: CAPACITY_MAX }));
|
||||
if (n === defaultCapacity()) await deleteSetting(db, capacityKey(poolId));
|
||||
else await setSetting(db, capacityKey(poolId), n);
|
||||
return n;
|
||||
}
|
||||
|
||||
/**
|
||||
* Capacity of each subscription: the smallest of its sets' values (a subscription may be in
|
||||
* several), the default for one outside any set.
|
||||
*/
|
||||
export async function subscriptionCapacities(db: Db): Promise<(subscriptionId: number) => number> {
|
||||
const own = await poolCapacities(db);
|
||||
const members = await db.select().from(subscriptionPoolMembers);
|
||||
const caps = new Map<number, number>();
|
||||
for (const m of members) {
|
||||
const c = own.get(m.poolId) ?? defaultCapacity();
|
||||
caps.set(m.subscriptionId, Math.min(caps.get(m.subscriptionId) ?? Infinity, c));
|
||||
}
|
||||
return (id) => caps.get(id) ?? defaultCapacity();
|
||||
}
|
||||
|
||||
/** Live runners (not done/failed) per subscription, over all projects. */
|
||||
export async function liveBySubscription(db: Db): Promise<Map<number, number>> {
|
||||
const rows = await db
|
||||
.select({ id: sessions.subscriptionId })
|
||||
.from(sessions)
|
||||
.where(and(isNotNull(sessions.subscriptionId), notInArray(sessions.status, FINISHED_SESSION_STATUSES)));
|
||||
const m = new Map<number, number>();
|
||||
for (const r of rows) m.set(r.id!, (m.get(r.id!) ?? 0) + 1);
|
||||
return m;
|
||||
}
|
||||
|
||||
/**
|
||||
* True when one more runner of the project can start now: some usable subscription of its set
|
||||
* has fewer live runners than the capacity. A project without a set (this machine's login) — always.
|
||||
*/
|
||||
export async function poolHasRoom(db: Db, projectId: number, now = new Date()): Promise<boolean> {
|
||||
const [p] = await db.select({ poolId: projects.subscriptionPoolId }).from(projects).where(eq(projects.id, projectId));
|
||||
if (p?.poolId == null) return true;
|
||||
const cap = await poolCapacity(db, p.poolId);
|
||||
const live = await liveBySubscription(db);
|
||||
const subs = await db
|
||||
.select({ s: subscriptions })
|
||||
.from(subscriptionPoolMembers)
|
||||
.innerJoin(subscriptions, eq(subscriptionPoolMembers.subscriptionId, subscriptions.id))
|
||||
.where(eq(subscriptionPoolMembers.poolId, p.poolId));
|
||||
return subs.some(({ s }) => isUsable(s, now) && (live.get(s.id) ?? 0) < cap);
|
||||
}
|
||||
|
||||
type SyncDb = Pick<Db, "select">;
|
||||
|
||||
/**
|
||||
* Inside `ensureSessionAgent`'s transaction: may the team get one more persona for this
|
||||
* session? A runner on this machine's login (no subscription) — yes, as before. Otherwise only
|
||||
* while the live runners on subscriptions (this one included) fit in the total capacity of
|
||||
* the subscriptions of all sets. `extra`: runners about to be created (not in the table yet).
|
||||
*/
|
||||
export function teamHasRoomSync(tx: SyncDb, session: { subscriptionId: number | null }, extra = 0): boolean {
|
||||
if (session.subscriptionId == null) return true;
|
||||
const own = new Map(
|
||||
tx
|
||||
.select()
|
||||
.from(settings)
|
||||
.where(like(settings.key, `${CAPACITY_PREFIX}%`))
|
||||
.all()
|
||||
.map((r) => [Number(r.key.slice(CAPACITY_PREFIX.length)), Number(r.value)] as const),
|
||||
);
|
||||
const members = tx.select().from(subscriptionPoolMembers).all();
|
||||
const subs = new Map(tx.select().from(subscriptions).all().map((s) => [s.id, s] as const));
|
||||
const caps = new Map<number, number>();
|
||||
for (const m of members) {
|
||||
// Every subscription of a set counts, a limited one too: its runners wait for the reset and
|
||||
// keep their personas, so they are part of how many runners can be live at once.
|
||||
const s = subs.get(m.subscriptionId);
|
||||
if (!s) continue;
|
||||
caps.set(s.id, Math.min(caps.get(s.id) ?? Infinity, own.get(m.poolId) ?? defaultCapacity()));
|
||||
}
|
||||
// The session's own subscription counts even outside any set (ticked by hand).
|
||||
if (!caps.has(session.subscriptionId)) caps.set(session.subscriptionId, defaultCapacity());
|
||||
const total = [...caps.values()].reduce((a, b) => a + b, 0);
|
||||
const live = tx
|
||||
.select({ id: sessions.id })
|
||||
.from(sessions)
|
||||
.where(and(isNotNull(sessions.subscriptionId), notInArray(sessions.status, FINISHED_SESSION_STATUSES)))
|
||||
.all().length;
|
||||
return live + extra <= total;
|
||||
}
|
||||
|
||||
// ── the queue of stories waiting for room ────────────────────────────────────────
|
||||
|
||||
const WAIT_PREFIX = "capacity.wait:";
|
||||
const waitKey = (taskId: number) => `${WAIT_PREFIX}${taskId}`;
|
||||
interface WaitRow {
|
||||
at: number;
|
||||
prompt?: string | null;
|
||||
}
|
||||
|
||||
/** The story waits for room (in progress, no runner); a repeated call keeps its place. */
|
||||
export async function waitForCapacity(db: Db, taskId: number, prompt?: string | null, now = new Date()): Promise<void> {
|
||||
const cur = await getSetting<WaitRow>(db, waitKey(taskId));
|
||||
await setSetting(db, waitKey(taskId), { at: cur?.at ?? now.getTime(), prompt: prompt ?? cur?.prompt ?? null } satisfies WaitRow);
|
||||
}
|
||||
|
||||
export async function clearCapacityWait(db: Db, taskId: number): Promise<void> {
|
||||
await deleteSetting(db, waitKey(taskId));
|
||||
}
|
||||
|
||||
export async function isWaitingForCapacity(db: Db, taskId: number): Promise<boolean> {
|
||||
return (await getSetting<WaitRow>(db, waitKey(taskId))) != null;
|
||||
}
|
||||
|
||||
export interface CapacityQueueItem {
|
||||
taskId: number;
|
||||
projectId: number;
|
||||
key: string;
|
||||
/** The set of subscriptions the story waits on (null: the project has none). */
|
||||
poolId: number | null;
|
||||
/** 1-based place in the set's queue. */
|
||||
position: number;
|
||||
at: Date;
|
||||
prompt: string | null;
|
||||
}
|
||||
|
||||
/** Task statuses of the «В работе» column. */
|
||||
const WORKING = ["proposing", "awaiting_approval", "in_progress", "blocked"] as const;
|
||||
|
||||
/**
|
||||
* Stories waiting for room, in the order they start: one queue per set of subscriptions;
|
||||
* inside a project — board order; the projects of a set take turns, the one waiting longest first.
|
||||
* Rows of stories that left work or were archived are not returned (`capacityQueueTick` drops them).
|
||||
*/
|
||||
export async function capacityQueue(db: Db, o: { projectIds?: number[] } = {}): Promise<CapacityQueueItem[]> {
|
||||
const rows = await db.select().from(settings).where(like(settings.key, `${WAIT_PREFIX}%`));
|
||||
if (!rows.length) return [];
|
||||
const waits = new Map(rows.map((r) => [Number(r.key.slice(WAIT_PREFIX.length)), r.value as WaitRow] as const));
|
||||
const ts = await db
|
||||
.select({ t: tasks, projectKey: projects.key, poolId: projects.subscriptionPoolId })
|
||||
.from(tasks)
|
||||
.innerJoin(projects, eq(tasks.projectId, projects.id))
|
||||
.where(inArray(tasks.id, [...waits.keys()]));
|
||||
// A story that already has a live runner is not waiting any more.
|
||||
const running = new Set(
|
||||
(await db.select({ id: sessions.taskId }).from(sessions).where(and(inArray(sessions.taskId, [...waits.keys()]), notInArray(sessions.status, FINISHED_SESSION_STATUSES)))).map((r) => r.id),
|
||||
);
|
||||
const live = ts.filter(({ t }) => (WORKING as readonly string[]).includes(t.status) && !t.archivedAt && !running.has(t.id));
|
||||
const byPool = new Map<string, typeof live>();
|
||||
for (const r of live) {
|
||||
const k = r.poolId == null ? `p${r.t.projectId}` : `s${r.poolId}`;
|
||||
byPool.set(k, [...(byPool.get(k) ?? []), r]);
|
||||
}
|
||||
const out: CapacityQueueItem[] = [];
|
||||
for (const group of byPool.values()) {
|
||||
const byProject = new Map<number, typeof live>();
|
||||
for (const r of group) byProject.set(r.t.projectId, [...(byProject.get(r.t.projectId) ?? []), r]);
|
||||
const lists = [...byProject.values()].map((l) => l.sort((a, b) => a.t.position - b.t.position || a.t.number - b.t.number));
|
||||
const since = (l: typeof live) => Math.min(...l.map((r) => waits.get(r.t.id)!.at));
|
||||
lists.sort((a, b) => since(a) - since(b) || a[0]!.t.projectId - b[0]!.t.projectId);
|
||||
let position = 0;
|
||||
for (let i = 0; lists.some((l) => l.length > i); i++) {
|
||||
for (const l of lists) {
|
||||
const r = l[i];
|
||||
if (!r) continue;
|
||||
const w = waits.get(r.t.id)!;
|
||||
out.push({ taskId: r.t.id, projectId: r.t.projectId, key: formatTaskKey(r.projectKey, r.t.number), poolId: r.poolId, position: ++position, at: new Date(w.at), prompt: w.prompt ?? null });
|
||||
}
|
||||
}
|
||||
}
|
||||
return o.projectIds ? out.filter((q) => o.projectIds!.includes(q.projectId)) : out;
|
||||
}
|
||||
|
||||
/** Stories that left the queue's reach (out of work, archived, gone) — their rows are dropped. */
|
||||
export async function staleCapacityWaits(db: Db): Promise<number[]> {
|
||||
const rows = await db.select().from(settings).where(like(settings.key, `${WAIT_PREFIX}%`));
|
||||
if (!rows.length) return [];
|
||||
const ids = rows.map((r) => Number(r.key.slice(WAIT_PREFIX.length)));
|
||||
const kept = new Set((await capacityQueue(db)).map((q) => q.taskId));
|
||||
return ids.filter((id) => !kept.has(id));
|
||||
}
|
||||
|
||||
/** taskId → place in its queue, for the board and the story page. */
|
||||
export async function queuePositions(db: Db, projectId: number): Promise<Map<number, number>> {
|
||||
return new Map((await capacityQueue(db, { projectIds: [projectId] })).map((q) => [q.taskId, q.position]));
|
||||
}
|
||||
|
||||
export interface WorkLine {
|
||||
/** Stories with an agent working on them right now. */
|
||||
doing: number;
|
||||
/** Stories waiting for a free agent. */
|
||||
queued: number;
|
||||
}
|
||||
|
||||
/** «Делается: 4 · В очереди: 3» of the projects (product view: no subscriptions, no capacity). */
|
||||
export async function workLine(db: Db, projectIds: number[]): Promise<WorkLine> {
|
||||
if (!projectIds.length) return { doing: 0, queued: 0 };
|
||||
const rows = await db
|
||||
.selectDistinct({ taskId: sessions.taskId })
|
||||
.from(sessions)
|
||||
.innerJoin(tasks, eq(sessions.taskId, tasks.id))
|
||||
.where(and(inArray(sessions.projectId, projectIds), notInArray(sessions.status, FINISHED_SESSION_STATUSES), inArray(tasks.status, [...WORKING])));
|
||||
return { doing: rows.length, queued: (await capacityQueue(db, { projectIds })).length };
|
||||
}
|
||||
@ -45,6 +45,7 @@ export * from "./local-users.ts";
|
||||
export * from "./new-users.ts";
|
||||
export * from "./specs.ts";
|
||||
export * from "./subscriptions.ts";
|
||||
export * from "./capacity.ts";
|
||||
export * from "./reviews.ts";
|
||||
export * from "./webpush.ts";
|
||||
export * from "./notifications.ts";
|
||||
|
||||
@ -8,6 +8,7 @@ import { formatTaskKey } from "@peppa/shared";
|
||||
import { and, asc, eq, inArray, isNull } from "drizzle-orm";
|
||||
import { taskProgress } from "./openspec.ts";
|
||||
import { taskAgentNames } from "./team.ts";
|
||||
import { capacityQueue, workLine, type WorkLine } from "./capacity.ts";
|
||||
import { pausedProjectIds } from "./project-pause.ts";
|
||||
import { listOtherProjects, userProjectIds } from "./users.ts";
|
||||
|
||||
@ -20,6 +21,8 @@ export interface StoryInWork {
|
||||
done: number | null;
|
||||
total: number | null;
|
||||
current: string | null;
|
||||
/** PEP-182: place in the queue for a free agent (no agent yet). */
|
||||
queued: number | null;
|
||||
}
|
||||
|
||||
export interface ProjectProgress {
|
||||
@ -39,6 +42,8 @@ export interface ProjectProgress {
|
||||
product: { url: string; live: boolean } | null;
|
||||
/** PEP-145: no link yet — the key of the system story that makes the product open by a link. */
|
||||
productFix: string | null;
|
||||
/** PEP-182: «Делается · В очереди» of the project. */
|
||||
work: WorkLine;
|
||||
/** PEP-174: the project is on pause. */
|
||||
paused: boolean;
|
||||
}
|
||||
@ -48,6 +53,8 @@ export interface ProgressOverview {
|
||||
/** Other people's projects — for a superadmin only. */
|
||||
others: ProjectProgress[];
|
||||
totals: { backlog: number; inProgress: number; review: number; done: number; total: number };
|
||||
/** PEP-182: «Делается · В очереди» over the user's own projects. */
|
||||
work: WorkLine;
|
||||
}
|
||||
|
||||
/** Board column of a story status (the same split as the board). */
|
||||
@ -58,15 +65,17 @@ export async function progressOverview(db: Db, userId: number): Promise<Progress
|
||||
const otherRows = await listOtherProjects(db, userId);
|
||||
const ids = [...mineIds, ...otherRows.map((p) => p.id)];
|
||||
const products = await productUrls(db, ids);
|
||||
const empty: ProgressOverview = { mine: [], others: [], totals: { backlog: 0, inProgress: 0, review: 0, done: 0, total: 0 } };
|
||||
const empty: ProgressOverview = { mine: [], others: [], totals: { backlog: 0, inProgress: 0, review: 0, done: 0, total: 0 }, work: { doing: 0, queued: 0 } };
|
||||
if (!ids.length) return empty;
|
||||
const ps = await db.select({ p: projects, ownerLogin: users.login }).from(projects).leftJoin(users, eq(users.id, projects.ownerId)).where(inArray(projects.id, ids)).orderBy(asc(projects.key));
|
||||
const ts = await db.select().from(tasks).where(and(inArray(tasks.projectId, ids), isNull(tasks.archivedAt))).orderBy(asc(tasks.position), asc(tasks.number));
|
||||
const mine = new Set(mineIds);
|
||||
const paused = await pausedProjectIds(db);
|
||||
const out = empty;
|
||||
const queue = new Map((await capacityQueue(db, { projectIds: ids })).map((q) => [q.taskId, q.position]));
|
||||
out.work = await workLine(db, mineIds);
|
||||
for (const { p, ownerLogin } of ps) {
|
||||
const row: ProjectProgress = { key: p.key, name: p.name, ownerLogin: mine.has(p.id) ? null : (ownerLogin ?? tr("без владельца")), backlog: 0, inProgress: 0, review: 0, done: 0, total: 0, working: [], reviewKeys: [], product: products.get(p.id) ?? null, productFix: null, paused: paused.has(p.id) };
|
||||
const row: ProjectProgress = { key: p.key, name: p.name, ownerLogin: mine.has(p.id) ? null : (ownerLogin ?? tr("без владельца")), backlog: 0, inProgress: 0, review: 0, done: 0, total: 0, working: [], reviewKeys: [], product: products.get(p.id) ?? null, productFix: null, work: await workLine(db, [p.id]), paused: paused.has(p.id) };
|
||||
const fix = row.product ? null : await openProductLinkTask(db, p.id);
|
||||
if (fix) row.productFix = formatTaskKey(p.key, fix.number);
|
||||
const own = ts.filter((t) => t.projectId === p.id);
|
||||
@ -79,7 +88,7 @@ export async function progressOverview(db: Db, userId: number): Promise<Progress
|
||||
if (c === "review") row.reviewKeys.push(key);
|
||||
if (c === "inProgress") {
|
||||
const pr = taskProgress(p, t.openspecChange);
|
||||
row.working.push({ key, title: t.title, status: t.status, agent: agentsOf.get(t.id) ?? null, done: pr?.done ?? null, total: pr?.total ?? null, current: pr?.current ?? null });
|
||||
row.working.push({ key, title: t.title, status: t.status, agent: agentsOf.get(t.id) ?? null, done: pr?.done ?? null, total: pr?.total ?? null, current: pr?.current ?? null, queued: queue.get(t.id) ?? null });
|
||||
}
|
||||
}
|
||||
if (mine.has(p.id)) {
|
||||
|
||||
@ -22,6 +22,8 @@ export interface StoryProductInput {
|
||||
waitsFor?: string[];
|
||||
/** PEP-150: a delay on the platform's side holds the story up (`taskDelayed`). */
|
||||
delayed?: boolean;
|
||||
/** PEP-182: place in the queue for a free agent. */
|
||||
queued?: number | null;
|
||||
}
|
||||
|
||||
export interface StoryProductView {
|
||||
@ -52,6 +54,7 @@ export const STORY_PRODUCT_TEXT = {
|
||||
asking: { now: m("Агент ждёт вашего ответа") },
|
||||
working: { now: (name: string | null) => (name ? m("Агент {name} работает над задачей", { name }) : m("Агент работает над задачей")), next: m("Когда работа будет готова, вы получите сообщение и сможете посмотреть результат.") },
|
||||
delayed: { now: m("Небольшая задержка на нашей стороне"), next: m("Peppa FACTORY продолжит работу сама. Вы получите сообщение, когда работа будет готова.") },
|
||||
queued: { now: (n: number) => m("В очереди: {n}-я, начнётся, когда освободится агент", { n }), next: m("Все агенты сейчас заняты другими задачами. Агент возьмёт эту сам, как только освободится, — делать ничего не нужно.") },
|
||||
paused: { now: m("Агент сейчас не работает над задачей"), next: m("Peppa FACTORY запустит агента снова. Если работа долго не продолжается, напишите в чат проекта.") },
|
||||
review: { now: m("Работа готова — посмотрите результат"), need: m("Посмотрите результат и нажмите «Принять» или «Поправить»."), next: m("«Принять» — задача закроется, изменения войдут в ваш продукт. «Поправить» — агент доработает по вашему замечанию.") },
|
||||
done: { now: m("Задача готова"), next: m("Изменения приняты. Делать ничего не нужно.") },
|
||||
@ -101,6 +104,7 @@ export function storyProductView(i: StoryProductInput): StoryProductView {
|
||||
if (asked) return { ...base, step, stepText, now: T.asking.now, need: T.answerBelow, next: T.afterAnswer };
|
||||
// PEP-150: the platform is fixing something of its own — nothing for the owner to do.
|
||||
if (i.delayed) return { ...base, step, stepText, ...T.delayed };
|
||||
if (!i.agentWorking && i.queued != null) return { ...base, step, stepText, now: T.queued.now(i.queued), next: T.queued.next };
|
||||
if (!i.agentWorking) return { ...base, step, stepText, ...T.paused };
|
||||
if (i.status === "proposing") return { ...base, step, stepText, now: T.proposing.now(agent), next: T.proposing.next };
|
||||
return { ...base, step, stepText, now: T.working.now(agent), next: T.working.next };
|
||||
|
||||
@ -9,6 +9,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 { capacityQueue, poolCapacities, defaultCapacity } from "./capacity.ts";
|
||||
import { visibleSubscriptionName, type SubscriptionViewer } from "./subscription-names.ts";
|
||||
import { listAccountUsage, type WindowView } from "./usage.ts";
|
||||
import type { User } from "./users.ts";
|
||||
@ -143,6 +144,10 @@ export interface PoolSubscriptionState {
|
||||
loan: Loan | null;
|
||||
/** PEP-170: the free subscription an agent of this pool moves to when its own runs out. */
|
||||
next: boolean;
|
||||
/** PEP-182: live runners it may hold (the set's value). */
|
||||
capacity: number;
|
||||
/** «агентов: 6 из 9». */
|
||||
load: string;
|
||||
/** PEP-177: whose subscription (the person's name); null when the viewer must not see it. */
|
||||
ownerName: string | null;
|
||||
/** PEP-178: the account e-mail; null when the viewer must not see it. */
|
||||
@ -160,6 +165,12 @@ export interface PoolOverview {
|
||||
waiting: number;
|
||||
/** PEP-170: the latest switches between this pool's subscriptions, newest first. */
|
||||
switches: SubscriptionSwitch[];
|
||||
/** PEP-182: live runners per subscription of the set; `live` of `total` (capacity × usable subscriptions). */
|
||||
capacity: number;
|
||||
live: number;
|
||||
total: number;
|
||||
/** Stories of the set's projects waiting for a free agent. */
|
||||
queued: number;
|
||||
}
|
||||
|
||||
export interface SubscriptionSwitch {
|
||||
@ -203,7 +214,7 @@ async function recentSwitches(db: Db, now: Date) {
|
||||
});
|
||||
}
|
||||
|
||||
function stateLabel(s: Omit<PoolSubscriptionState, "label" | "next">): string {
|
||||
function stateLabel(s: Omit<PoolSubscriptionState, "label" | "next" | "capacity" | "load">): string {
|
||||
if (s.status === "pending") return tr("ждёт входа");
|
||||
if (s.status === "auth_error") return tr("ошибка входа — подключите заново");
|
||||
if (s.limitedUntil) return tr("лимит до {time}", { time: hhmm(s.limitedUntil) });
|
||||
@ -223,11 +234,14 @@ export async function poolOverviews(db: Db, poolIds?: number[], now = new Date()
|
||||
: [];
|
||||
const allProjects = await db.select({ id: projects.id, key: projects.key, name: projects.name, poolId: projects.subscriptionPoolId }).from(projects);
|
||||
const switches = await recentSwitches(db, now);
|
||||
const caps = await poolCapacities(db);
|
||||
const queue = await capacityQueue(db);
|
||||
const nameOf = (id: number, fallback: string) => {
|
||||
const s = subs.find((x) => x.id === id);
|
||||
return s && viewer ? visibleSubscriptionName(s, viewer) : fallback;
|
||||
};
|
||||
return pools.map((p) => {
|
||||
const capacity = caps.get(p.id) ?? defaultCapacity();
|
||||
const list = p.subscriptionIds.map((id) => subs.find((s) => s.id === id)).filter((s): s is NonNullable<typeof s> => !!s);
|
||||
const states = list.map((s) => {
|
||||
const u = usage.get(s.id);
|
||||
@ -249,7 +263,7 @@ export async function poolOverviews(db: Db, poolIds?: number[], now = new Date()
|
||||
usage: w,
|
||||
loan: loans.find((l) => l.poolId === p.id && l.subscriptionId === s.id) ?? null,
|
||||
};
|
||||
return { ...base, next: false, label: stateLabel(base) };
|
||||
return { ...base, next: false, label: stateLabel(base), capacity, load: tr("агентов: {n} из {max}", { n: base.activeSessions, max: capacity }) };
|
||||
});
|
||||
// Mirrors rotationCandidate: a free usable subscription, the lowest id first.
|
||||
const next = states.filter((x) => x.usable && !x.activeSessions).sort((a, b) => a.id - b.id)[0];
|
||||
@ -260,6 +274,10 @@ export async function poolOverviews(db: Db, poolIds?: number[], now = new Date()
|
||||
projects: allProjects.filter((x) => x.poolId === p.id).map(({ id, key, name }) => ({ id, key, name })),
|
||||
subscriptions: states,
|
||||
usableCount: states.filter((s) => s.usable).length,
|
||||
capacity,
|
||||
live: states.reduce((n, s) => n + s.activeSessions, 0),
|
||||
total: capacity * states.filter((s) => s.usable).length,
|
||||
queued: queue.filter((q) => q.poolId === p.id).length,
|
||||
waiting: waitingRows.filter((r) => r.subscriptionId != null && memberIds.has(r.subscriptionId)).length,
|
||||
switches: switches.filter((x) => memberIds.has(x.toId) || (x.fromId != null && memberIds.has(x.fromId))).slice(0, SWITCHES_SHOWN).map((x) => ({
|
||||
at: x.at,
|
||||
|
||||
@ -12,6 +12,7 @@ import { isSuperadmin } from "./monitor.ts";
|
||||
import type { Project } from "./projects.ts";
|
||||
import { deleteSetting, getSetting, setSetting } from "./settings.ts";
|
||||
import { FINISHED_SESSION_STATUSES } from "./sessions.ts";
|
||||
import { NoCapacityError, poolCapacity, subscriptionCapacities } from "./capacity.ts";
|
||||
import type { User } from "./users.ts";
|
||||
|
||||
export type Subscription = typeof subscriptions.$inferSelect;
|
||||
@ -281,9 +282,9 @@ export interface PickOptions {
|
||||
}
|
||||
|
||||
/**
|
||||
* The subscription a new runner starts on: the first free usable one of the chosen set
|
||||
* (ticked subscriptions, else the chosen pool, else the project's pool), by id; if all are
|
||||
* busy — the least busy one (the runner never waits); fairness: poolRestricted. Null when nothing
|
||||
* The subscription a new runner starts on: the least busy usable one of the chosen set
|
||||
* (ticked subscriptions, else the chosen pool, else the project's pool) with room under the
|
||||
* capacity (PEP-182; none → NoCapacityError, the story waits); fairness: poolRestricted. Null when nothing
|
||||
* is chosen and the project has no pool: the agent runs on this machine's own login.
|
||||
*/
|
||||
export async function pickSubscription(db: Db, o: PickOptions): Promise<Subscription | null> {
|
||||
@ -310,13 +311,17 @@ export async function pickSubscription(db: Db, o: PickOptions): Promise<Subscrip
|
||||
if (!usable.length) throw new PeppaError(candidates.length ? tr("Нет активных подписок среди {source} — проверьте их в «Подписках»", { source }) : tr("Нет активных подписок среди {source} (ни одной не подключено) — проверьте их в «Подписках»", { source }));
|
||||
const active = await activeRows(db);
|
||||
const counts = countBySubscription(active);
|
||||
// PEP-182: only a subscription with fewer live runners than the capacity takes one more.
|
||||
const capOf = poolIdUsed != null ? ((c: number) => () => c)(await poolCapacity(db, poolIdUsed)) : await subscriptionCapacities(db);
|
||||
const roomy = usable.filter((s) => (counts.get(s.id) ?? 0) < capOf(s.id));
|
||||
if (!roomy.length) throw new NoCapacityError();
|
||||
// Fairness (PEP-39): a project already holding K subscriptions of the pool while another
|
||||
// project waits for a limit reset shares a busy subscription instead of taking a free one.
|
||||
if (poolIdUsed != null && (await poolRestricted(db, poolIdUsed, o.projectId, active))) {
|
||||
const shared = usable.filter((s) => (counts.get(s.id) ?? 0) > 0);
|
||||
const shared = roomy.filter((s) => (counts.get(s.id) ?? 0) > 0);
|
||||
if (shared.length) return leastBusy(shared, counts);
|
||||
}
|
||||
return leastBusy(usable, counts);
|
||||
return leastBusy(roomy, counts);
|
||||
}
|
||||
|
||||
const leastBusy = (list: Subscription[], counts: Map<number, number>) =>
|
||||
@ -384,7 +389,9 @@ export async function rotationCandidate(
|
||||
const pick = async (ok: (x: Subscription) => boolean): Promise<Subscription | null> => {
|
||||
const found = new Map<number, Subscription>();
|
||||
for (const poolId of poolIds) {
|
||||
let list = (await poolSubscriptions(db, poolId)).filter((x) => ok(x) && x.id !== s.subscriptionId && isUsable(x, o.now));
|
||||
// PEP-182: never onto a subscription that already holds its capacity of runners.
|
||||
const cap = await poolCapacity(db, poolId);
|
||||
let list = (await poolSubscriptions(db, poolId)).filter((x) => ok(x) && x.id !== s.subscriptionId && isUsable(x, o.now) && (counts.get(x.id) ?? 0) < cap);
|
||||
if (o.onlyIdle) list = list.filter((x) => !counts.get(x.id));
|
||||
// Fair share: a project over K while others wait gets no free subscription here.
|
||||
if (list.length && (await poolRestricted(db, poolId, s.projectId, active))) list = list.filter((x) => (counts.get(x.id) ?? 0) > 0);
|
||||
|
||||
@ -6,6 +6,7 @@ import { m as tr } from "@peppa/shared/i18n";
|
||||
import { agents, sessions, type Db } from "@peppa/db";
|
||||
import { and, asc, desc, eq, isNotNull, isNull, notInArray, sql } from "drizzle-orm";
|
||||
import { PeppaError } from "./errors.ts";
|
||||
import { NoCapacityError, teamHasRoomSync } from "./capacity.ts";
|
||||
|
||||
export type Agent = typeof agents.$inferSelect;
|
||||
|
||||
@ -95,7 +96,8 @@ export async function updateAgent(db: Db, id: number, patch: { name?: string; ch
|
||||
|
||||
/**
|
||||
* The persona of a runner, assigning one on first use: the story's previous persona if it is
|
||||
* still in the team, else a free one (no live runner), else a new one with the next name.
|
||||
* still in the team, else a free one (no live runner), else a new one with the next name —
|
||||
* only while the capacity of the subscriptions allows one more runner (PEP-182), else null.
|
||||
* One synchronous transaction, so two runners starting together never share a free persona.
|
||||
*/
|
||||
export async function ensureSessionAgent(db: Db, sessionId: number): Promise<Agent | null> {
|
||||
@ -128,6 +130,8 @@ export async function ensureSessionAgent(db: Db, sessionId: number): Promise<Age
|
||||
.limit(1)
|
||||
.get();
|
||||
}
|
||||
// PEP-182: the team grows by itself only while the capacity allows one more runner.
|
||||
if (!agent && !teamHasRoomSync(tx, s)) return null;
|
||||
if (!agent) {
|
||||
const taken = new Set(tx.select({ name: agents.name }).from(agents).all().map((r) => r.name.toLowerCase()));
|
||||
agent = tx.insert(agents).values({ name: nextName(taken) }).returning().get();
|
||||
@ -137,6 +141,26 @@ export async function ensureSessionAgent(db: Db, sessionId: number): Promise<Age
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* PEP-182, before a new runner is created: a free persona exists, or the team may grow (the
|
||||
* live runners on subscriptions plus this one fit in the capacity). Otherwise NoCapacityError —
|
||||
* the story waits in the queue instead of a runner without a persona.
|
||||
*/
|
||||
export async function assertAgentAvailable(db: Db, subscriptionId: number | null): Promise<void> {
|
||||
db.transaction((tx) => {
|
||||
const busy = tx.select({ id: sessions.agentId }).from(sessions).where(and(isNotNull(sessions.agentId), notInArray(sessions.status, [...FINISHED]))).all().map((r) => r.id!);
|
||||
const free = tx
|
||||
.select({ id: agents.id })
|
||||
.from(agents)
|
||||
.where(and(isNull(agents.disabledAt), busy.length ? notInArray(agents.id, busy) : undefined))
|
||||
.limit(1)
|
||||
.get();
|
||||
if (free) return;
|
||||
// The runner is not created yet: it counts as one more live runner.
|
||||
if (!teamHasRoomSync(tx, { subscriptionId }, 1)) throw new NoCapacityError();
|
||||
});
|
||||
}
|
||||
|
||||
/** What the persona adds to the agent's system prompt. */
|
||||
export function agentPrompt(agent: Pick<Agent, "name" | "character">): string {
|
||||
const lines = [
|
||||
|
||||
@ -22,6 +22,8 @@ import {
|
||||
pipelineChanges,
|
||||
prGate,
|
||||
projectPoolExhausted,
|
||||
capacityQueue,
|
||||
poolHasRoom,
|
||||
questionRecipients,
|
||||
raiseSessionQuestion,
|
||||
alertAdmins,
|
||||
@ -282,8 +284,11 @@ async function dispatch(db: Db, project: Project, a: AutonomySettings, now: Date
|
||||
// PEP-79: no subscription chosen (or none works) — the project page says so; no retries, no pings.
|
||||
if (await projectAgentWarning(db, project.id, now)) return;
|
||||
if (limited || (state.failUntil ?? 0) > now.getTime()) return;
|
||||
// PEP-10: stories waiting in runner queues count as taken.
|
||||
let slots = a.wipLimit - working.length - (await queuedItems(db, { sessionIds: sessions.map((s) => s.id) })).length;
|
||||
// PEP-182: no room on the project's subscriptions — new stories stay in the backlog (the
|
||||
// waiting ones start first, by capacityQueueTick).
|
||||
if (ready.length && !(await poolHasRoom(db, project.id, now))) return;
|
||||
// PEP-10: stories waiting in runner queues count as taken; PEP-182: so do the ones waiting for room.
|
||||
let slots = a.wipLimit - working.length - (await queuedItems(db, { sessionIds: sessions.map((s) => s.id) })).length - (await capacityQueue(db, { projectIds: [project.id] })).length;
|
||||
for (const task of ready) {
|
||||
if (slots <= 0) break;
|
||||
const ref = refOf(project, task);
|
||||
@ -291,8 +296,10 @@ async function dispatch(db: Db, project: Project, a: AutonomySettings, now: Date
|
||||
if ((await getPlatformDelay(db, { projectId: project.id, taskId: task.id }, "start"))?.exhausted) continue;
|
||||
try {
|
||||
const r = await moveTask(db, ref, "in_progress", { prompt: "Стори взята из бэклога автоматически (автономность проекта). Работай по правилам до PR и review." });
|
||||
log(`${ref.key}: dispatched (${r.waiting ? "waits for room" : `session #${r.started}`})`);
|
||||
// PEP-182: no room after all — the next ones wait in the backlog.
|
||||
if (r.waiting) break;
|
||||
await clearPlatformDelay(db, { projectId: project.id, taskId: task.id }, "start");
|
||||
log(`${ref.key}: dispatched (session #${r.started})`);
|
||||
slots--;
|
||||
} catch (e) {
|
||||
// Back to the backlog: the card must not hang in "in progress" without an agent.
|
||||
|
||||
43
packages/runner/src/capacity-queue.ts
Normal file
43
packages/runner/src/capacity-queue.ts
Normal file
@ -0,0 +1,43 @@
|
||||
// PEP-182: stories waiting «В очереди» for room on the subscriptions start by themselves as
|
||||
// soon as a runner finishes — in each set's queue order (board order inside a project, projects
|
||||
// taking turns). A wait is not a failure: the owner sees the mark on the card, nobody is paged.
|
||||
import { capacityQueue, clearCapacityWait, isNoCapacity, platformFailure, staleCapacityWaits } from "@peppa/core";
|
||||
import type { Db } from "@peppa/db";
|
||||
import { resolveTaskById } from "./sessions.ts";
|
||||
import { startTaskOnRunner } from "./runners.ts";
|
||||
|
||||
export async function capacityQueueTick(db: Db, opts: { now?: Date; log?: (m: string) => void } = {}): Promise<number> {
|
||||
const log = opts.log ?? (() => {});
|
||||
for (const id of await staleCapacityWaits(db)) await clearCapacityWait(db, id);
|
||||
const full = new Set<string>();
|
||||
let started = 0;
|
||||
for (const q of await capacityQueue(db)) {
|
||||
const set = q.poolId == null ? `p${q.projectId}` : `s${q.poolId}`;
|
||||
if (full.has(set)) continue;
|
||||
const ref = await resolveTaskById(db, q.taskId).catch(() => null);
|
||||
if (!ref) {
|
||||
await clearCapacityWait(db, q.taskId);
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
// Still no room: startTaskOnRunner keeps the story in its place in the queue.
|
||||
const r = await startTaskOnRunner(db, ref, { prompt: q.prompt ?? undefined });
|
||||
if (r.waiting) {
|
||||
full.add(set);
|
||||
continue;
|
||||
}
|
||||
await clearCapacityWait(db, q.taskId);
|
||||
started++;
|
||||
log(`${ref.key}: room on the subscriptions — started from the queue (${r.started ? `new #${r.started}` : `#${r.runner}`})`);
|
||||
} catch (e) {
|
||||
if (isNoCapacity(e)) {
|
||||
full.add(set);
|
||||
continue;
|
||||
}
|
||||
// The story keeps its place; a platform failure goes to the superadmins (once a day), not to the owner.
|
||||
await platformFailure(db, e, { service: "watchdog", where: `capacity queue ${ref.key}`, log, now: opts.now });
|
||||
log(`${ref.key}: start from the queue failed — ${(e as Error).message}`);
|
||||
}
|
||||
}
|
||||
return started;
|
||||
}
|
||||
@ -1,7 +1,7 @@
|
||||
// PM-side moves on the task board and review acceptance (web and Telegram use these).
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
import { releaseIntake } from "./intake.ts";
|
||||
import { addStoryComment, answerQuestion, assertProjectActive, STORY_PRODUCT_TEXT, giteaForBot, GATE_UNKNOWN_REASON, clearPendingAccept, PENDING_ACCEPT_ANSWER, setPendingAccept, dropQueuedTask, getQuestion, listSessions, PeppaError, pendingQuestions, prGate, queuedItems, reorderTask, resolveTask, setTaskArchived, updateTask, type Question, type ReorderTo, type TaskRef } from "@peppa/core";
|
||||
import { addStoryComment, answerQuestion, assertProjectActive, STORY_PRODUCT_TEXT, giteaForBot, GATE_UNKNOWN_REASON, clearPendingAccept, PENDING_ACCEPT_ANSWER, setPendingAccept, dropQueuedTask, clearCapacityWait, isWaitingForCapacity, getQuestion, listSessions, PeppaError, pendingQuestions, prGate, queuedItems, reorderTask, resolveTask, setTaskArchived, updateTask, type Question, type ReorderTo, type TaskRef } from "@peppa/core";
|
||||
import { tasks, projects, type Db } from "@peppa/db";
|
||||
import { formatTaskKey } from "@peppa/shared";
|
||||
import { eq } from "drizzle-orm";
|
||||
@ -43,7 +43,7 @@ export async function reviewGate(ref: TaskRef): Promise<string | null> {
|
||||
* started unless one is running. Into "review": only past the CI gate. Into
|
||||
* "backlog"/"done": active sessions are stopped.
|
||||
*/
|
||||
export async function moveTask(db: Db, ref: TaskRef, to: BoardColumn, start: StartOptions = {}, gitea?: GiteaClient): Promise<{ started?: number; runner?: number; queued?: boolean; stopped: number }> {
|
||||
export async function moveTask(db: Db, ref: TaskRef, to: BoardColumn, start: StartOptions = {}, gitea?: GiteaClient): Promise<{ started?: number; runner?: number; queued?: boolean; waiting?: boolean; stopped: number }> {
|
||||
// PEP-174: a project on pause takes no story into work.
|
||||
if (to === "in_progress") await assertProjectActive(db, ref.project.id);
|
||||
// PEP-21: the whole move runs in the runner service (one at a time per story).
|
||||
@ -56,7 +56,8 @@ export async function moveTask(db: Db, ref: TaskRef, to: BoardColumn, start: Sta
|
||||
if ((await activeSessions(db, ref.task.id)).length === 0) await assertBudgetOpen(db, ref.task.id);
|
||||
if (from !== "in_progress") await updateTask(db, ref, { status: "in_progress" });
|
||||
// PEP-10: by the runner settings — a new runner, or a free/queued runner of the project.
|
||||
if ((await activeSessions(db, ref.task.id)).length === 0 && (await queuedItems(db, { taskId: ref.task.id })).length === 0) {
|
||||
// PEP-182: a story waiting for a free agent keeps its place — `capacityQueueTick` starts it.
|
||||
if ((await activeSessions(db, ref.task.id)).length === 0 && (await queuedItems(db, { taskId: ref.task.id })).length === 0 && !(await isWaitingForCapacity(db, ref.task.id))) {
|
||||
return { ...(await startTaskOnRunner(db, ref, start)), stopped };
|
||||
}
|
||||
return { stopped };
|
||||
@ -68,6 +69,7 @@ export async function moveTask(db: Db, ref: TaskRef, to: BoardColumn, start: Sta
|
||||
const release: number[] = [];
|
||||
if (to === "backlog" || to === "done") {
|
||||
await dropQueuedTask(db, ref.task.id);
|
||||
await clearCapacityWait(db, ref.task.id);
|
||||
for (const s of await activeSessions(db, ref.task.id)) {
|
||||
// PEP-10: a queue runner is released on "done" and takes its next story.
|
||||
if (to === "done" && (await runnerFollowsQueue(db, s))) {
|
||||
@ -96,6 +98,7 @@ export async function archiveTask(db: Db, ref: TaskRef, archived: boolean): Prom
|
||||
if (isRunnerClient()) return runnerCall(db, "archive", { task: ref.key, archived }, { key: `task:${ref.task.id}` });
|
||||
let stopped = 0;
|
||||
if (archived) {
|
||||
await clearCapacityWait(db, ref.task.id);
|
||||
for (const s of await activeSessions(db, ref.task.id)) {
|
||||
await stopSession(db, s.id);
|
||||
stopped++;
|
||||
|
||||
@ -42,6 +42,7 @@ export * from "./live.ts";
|
||||
export * from "./gitea-events.ts";
|
||||
export * from "./planner.ts";
|
||||
export * from "./runners.ts";
|
||||
export * from "./capacity-queue.ts";
|
||||
export * from "./worktree.ts";
|
||||
export * from "./budgets.ts";
|
||||
export * from "./runner-client.ts";
|
||||
|
||||
@ -7,6 +7,8 @@ import {
|
||||
getSession,
|
||||
getSubscription,
|
||||
isUsable,
|
||||
liveBySubscription,
|
||||
subscriptionCapacities,
|
||||
listSessions,
|
||||
logSessionEvent,
|
||||
PeppaError,
|
||||
@ -134,8 +136,11 @@ export async function switchAgents(db: Db, o: { fromId: number; toId?: number |
|
||||
const sessions = (await listSessions(db, { active: true })).filter((s) => s.subscriptionId === o.fromId);
|
||||
let moved = 0;
|
||||
let skipped = 0;
|
||||
// PEP-182: a chosen subscription takes agents only up to its capacity; the rest stay put.
|
||||
let room = fixed ? (await subscriptionCapacities(db))(fixed.id) - ((await liveBySubscription(db)).get(fixed.id) ?? 0) : Infinity;
|
||||
for (const s of sessions) {
|
||||
const target = fixed ?? (await rotationCandidate(db, s, { now }));
|
||||
const target = fixed ? (room > 0 ? fixed : null) : await rotationCandidate(db, s, { now });
|
||||
if (fixed && target) room--;
|
||||
if (!target) {
|
||||
skipped++;
|
||||
continue;
|
||||
|
||||
@ -13,7 +13,10 @@ import {
|
||||
FINISHED_SESSION_STATUSES,
|
||||
getAutonomy,
|
||||
getSession,
|
||||
isNoCapacity,
|
||||
waitForCapacity,
|
||||
listSessions,
|
||||
logEvent,
|
||||
logSessionEvent,
|
||||
nextQueued,
|
||||
PeppaError,
|
||||
@ -64,6 +67,20 @@ export interface AssignResult {
|
||||
/** An existing runner took the story (now or from its queue). */
|
||||
runner?: number;
|
||||
queued?: boolean;
|
||||
/** PEP-182: no room on the subscriptions — the story waits «В очереди» for a free agent. */
|
||||
waiting?: boolean;
|
||||
}
|
||||
|
||||
/** A new runner for the story; no room on the subscriptions (PEP-182) → the story waits in the queue. */
|
||||
async function startOrWait(db: Db, ref: TaskRef, opts: StartOptions): Promise<AssignResult> {
|
||||
try {
|
||||
return { started: (await startSession(db, ref.key, opts)).id };
|
||||
} catch (e) {
|
||||
if (!isNoCapacity(e)) throw e;
|
||||
await waitForCapacity(db, ref.task.id, opts.prompt);
|
||||
await logEvent(db, { projectId: ref.project.id, taskId: ref.task.id, type: "capacity_wait", payload: { key: ref.key } });
|
||||
return { queued: true, waiting: true };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@ -74,7 +91,7 @@ export interface AssignResult {
|
||||
export async function startTaskOnRunner(db: Db, ref: TaskRef, opts: StartOptions = {}): Promise<AssignResult> {
|
||||
if (isRunnerClient()) return runnerCall<AssignResult>(db, "assign", { task: ref.key, opts }, { key: `task:${ref.task.id}` });
|
||||
const rs = await resolveRunnerSettings(db, ref.project.id, ref.task.id);
|
||||
if (rs.mode === "story") return { started: (await startSession(db, ref.key, opts)).id };
|
||||
if (rs.mode === "story") return startOrWait(db, ref, opts);
|
||||
if ((await queuedItems(db, { taskId: ref.task.id })).length) return { queued: true };
|
||||
const live = await listSessions(db, { active: true, projectId: ref.project.id });
|
||||
for (const s of live) {
|
||||
@ -83,7 +100,7 @@ export async function startTaskOnRunner(db: Db, ref: TaskRef, opts: StartOptions
|
||||
await advanceRunner(db, s.id);
|
||||
return { runner: s.id, queued: false };
|
||||
}
|
||||
if (rs.maxRunners == null || live.length < rs.maxRunners) return { started: (await startSession(db, ref.key, opts)).id };
|
||||
if (rs.maxRunners == null || live.length < rs.maxRunners) return startOrWait(db, ref, opts);
|
||||
const hosts = live.filter((s) => s.taskId != null && !s.tmuxName.startsWith("pending-"));
|
||||
if (!hosts.length) throw new PeppaError(m("Предел агентов проекта: {max}, очередь вести некому", { max: rs.maxRunners }));
|
||||
const queues = await queuedItems(db, { sessionIds: hosts.map((s) => s.id) });
|
||||
|
||||
@ -21,6 +21,7 @@ import {
|
||||
memoryContext,
|
||||
agentPrompt,
|
||||
ensureSessionAgent,
|
||||
assertAgentAvailable,
|
||||
checkEscalation,
|
||||
launchModelFor,
|
||||
resolveAgentSettings,
|
||||
@ -179,6 +180,8 @@ export async function startRunner(
|
||||
// The container has no login of this machine: the agent runs on its subscription.
|
||||
if (sandboxed && !sub) throw new PeppaError(m("Для запуска агента в контейнере нужна подписка: подключите её в настройках проекта (раздел «Подписки»)"));
|
||||
if (host && provider === "codex") throw new PeppaError(m("Codex на удалённом хосте пока не поддерживается — выберите подписку Claude или OpenCode"));
|
||||
// PEP-182: no free persona and the team may not grow — the story waits for a free agent.
|
||||
await assertAgentAvailable(db, sub?.id ?? null);
|
||||
const session = await createSession(db, { projectId: project.id, taskId: task?.id ?? null, provider, subscriptionId: sub?.id ?? null, name: opts.name?.trim() || null });
|
||||
if (fallback) await logSessionEvent(db, await getSession(db, session.id), "provider_fallback", { from: fallback.from, to: provider, subscriptionId: sub?.id ?? null, reason: fallback.reason });
|
||||
const tmuxName = `peppa-${(task?.key ?? project.key).toLowerCase()}-s${session.id}`;
|
||||
|
||||
@ -42,6 +42,7 @@ import { incidentTick } from "./incidents.ts";
|
||||
import { pollChecks } from "./ci-feedback.ts";
|
||||
import { reviewTick } from "./reviewer.ts";
|
||||
import { autonomyTick } from "./autonomy.ts";
|
||||
import { capacityQueueTick } from "./capacity-queue.ts";
|
||||
import { pendingAcceptTick } from "./accept-pending.ts";
|
||||
import { reviewCardTick } from "./review-card.ts";
|
||||
import { intakeTick } from "./intake.ts";
|
||||
@ -131,6 +132,8 @@ async function tickInner(db: Db, opts: WatchdogOptions): Promise<void> {
|
||||
// PEP-145: a project whose product does not open by a link gets a story for that, first in the
|
||||
// backlog — before the dispatcher looks; «Показывать всем: сам» is carried through.
|
||||
await productLinkTick(db, { now: opts.now, log }).catch(failed(db, log, "product link"));
|
||||
// PEP-182: stories waiting for room go first, before the dispatcher takes new ones.
|
||||
await capacityQueueTick(db, { now: opts.now, log }).catch(failed(db, log, "capacity queue"));
|
||||
await autonomyTick(db, { now: opts.now, log }).catch(failed(db, log, "autonomy"));
|
||||
// PEP-150: delays on the platform's side — due retries, and lines of delays that are over.
|
||||
await platformDelayTick(db, { now: opts.now, log }).catch(failed(db, log, "platform delays"));
|
||||
|
||||
13
packages/shared/src/i18n/en/capacity.ts
Normal file
13
packages/shared/src/i18n/en/capacity.ts
Normal file
@ -0,0 +1,13 @@
|
||||
// PEP-182: capacity of a subscription and the queue for a free agent.
|
||||
export const capacity: Record<string, string> = {
|
||||
"Агентов на подписку": "Agents per subscription",
|
||||
"В очереди: {n}-я, начнётся, когда освободится агент": "Queued: #{n}, starts when an agent is free",
|
||||
"агентов: {n} из {max}": "agents: {n} of {max}",
|
||||
"Загрузка: {live} из {total}": "Load: {live} of {total}",
|
||||
"В очереди: {n}": "Queued: {n}",
|
||||
"Делается: {n}": "In progress: {n}",
|
||||
"Все агенты заняты — задачи начнутся по порядку, когда агент освободится": "All agents are busy — the tasks start in order as soon as an agent is free",
|
||||
"Все агенты заняты — задача начнётся, когда освободится агент": "All agents are busy — the task starts as soon as an agent is free",
|
||||
"Агентов на подписку — от {min} до {max}": "Agents per subscription: from {min} to {max}",
|
||||
"Все агенты сейчас заняты другими задачами. Агент возьмёт эту сам, как только освободится, — делать ничего не нужно.": "All agents are busy with other tasks right now. An agent takes this one by itself as soon as it is free — nothing to do.",
|
||||
};
|
||||
@ -16,6 +16,7 @@ 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 { capacity } from "./capacity.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, ...subscriptionRequest };
|
||||
export const en: Dict = { ...common, ...story, ...project, ...admin, ...settings, ...help, ...runner, ...bot, ...merge, ...merge_a, ...merge_b, ...merge_c, ...merge_d, ...feedback, ...attachments, ...capacity, ...subscriptionRequest };
|
||||
|
||||
13
packages/shared/src/i18n/kk/capacity.ts
Normal file
13
packages/shared/src/i18n/kk/capacity.ts
Normal file
@ -0,0 +1,13 @@
|
||||
// PEP-182: жазылымның сыйымдылығы және бос агентті күту кезегі.
|
||||
export const capacity: Record<string, string> = {
|
||||
"Агентов на подписку": "Бір жазылымдағы агенттер",
|
||||
"В очереди: {n}-я, начнётся, когда освободится агент": "Кезектегі орны: {n}, агент босағанда басталады",
|
||||
"агентов: {n} из {max}": "агенттер: {n} / {max}",
|
||||
"Загрузка: {live} из {total}": "Жүктеме: {live} / {total}",
|
||||
"В очереди: {n}": "Кезекте: {n}",
|
||||
"Делается: {n}": "Орындалуда: {n}",
|
||||
"Все агенты заняты — задачи начнутся по порядку, когда агент освободится": "Барлық агент бос емес — агент босағанда тапсырмалар кезегімен басталады",
|
||||
"Все агенты заняты — задача начнётся, когда освободится агент": "Барлық агент бос емес — агент босағанда тапсырма басталады",
|
||||
"Агентов на подписку — от {min} до {max}": "Бір жазылымдағы агенттер саны: {min} мен {max} аралығында",
|
||||
"Все агенты сейчас заняты другими задачами. Агент возьмёт эту сам, как только освободится, — делать ничего не нужно.": "Қазір барлық агент басқа тапсырмалармен айналысады. Агент босаған бойда бұны өзі алады — ештеңе істеудің қажеті жоқ.",
|
||||
};
|
||||
@ -16,6 +16,7 @@ import { settings } from "./settings.ts";
|
||||
import { story } from "./story.ts";
|
||||
import { feedback } from "./feedback.ts";
|
||||
import { attachments } from "./attachments.ts";
|
||||
import { capacity } from "./capacity.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, ...subscriptionRequest };
|
||||
export const kk: Dict = { ...admin, ...bot, ...common, ...help, ...mergeA, ...mergeB, ...mergeC, ...mergeD, ...merge, ...project, ...runner, ...settings, ...story, ...feedback, ...attachments, ...capacity, ...subscriptionRequest };
|
||||
|
||||
218
packages/testkit/test/subscription-capacity.test.ts
Normal file
218
packages/testkit/test/subscription-capacity.test.ts
Normal file
@ -0,0 +1,218 @@
|
||||
// PEP-182: at most N live runners per subscription (9 by default, a superadmin changes it per
|
||||
// set); no room → the story waits «В очереди» and starts by itself in board order; rotation
|
||||
// never moves onto a full subscription; the team grows only within the capacity.
|
||||
import assert from "node:assert/strict";
|
||||
import { after, before, describe, test } from "node:test";
|
||||
import { agents } from "@peppa/db";
|
||||
import { stripAsIs } from "@peppa/shared/i18n";
|
||||
import { core, db, project, runner, setDefaultOwner, teardown, waitFor } from "./helpers.ts";
|
||||
|
||||
process.env.PEPPA_SECRET = "mock-secret-for-tests";
|
||||
|
||||
type User = Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
|
||||
let pm: User;
|
||||
let admin: User;
|
||||
before(async () => {
|
||||
pm = await core.upsertUserFromGitea(db, { id: 182, login: "mock-pm-182" }, { access_token: "x" });
|
||||
admin = await core.upsertUserFromGitea(db, { id: 1182, login: "mock-admin-182" }, { access_token: "x" });
|
||||
await core.setSetting(db, "platform.admins", [admin.login]);
|
||||
setDefaultOwner(pm.id);
|
||||
});
|
||||
after(teardown);
|
||||
|
||||
const TOKEN = (tag: string) => `sk-ant-oat01-mock${"x".repeat(24)}${tag}`;
|
||||
const claudeSub = (name: string, tag: string) => runner.addSubscription(db, { provider: "claude", name, method: "token", secret: TOKEN(tag), createdBy: pm.id });
|
||||
let seq = 0;
|
||||
const poolFor = async (key: string, ids: number[]) => {
|
||||
const pool = await core.createPool(db, { name: `Пул C${++seq}`, subscriptionIds: ids });
|
||||
await core.setProjectPool(db, (await core.getProject(db, key)).id, pool.id);
|
||||
return pool;
|
||||
};
|
||||
/** A live runner on the subscription without a process (counts like a real one). */
|
||||
const fakeRunner = async (projectKey: string, subscriptionId: number) =>
|
||||
(await core.createSession(db, { projectId: (await core.getProject(db, projectKey)).id, subscriptionId, provider: "claude" })).id;
|
||||
const fill = async (projectKey: string, subscriptionId: number, n: number) => {
|
||||
const ids: number[] = [];
|
||||
for (let i = 0; i < n; i++) ids.push(await fakeRunner(projectKey, subscriptionId));
|
||||
return ids;
|
||||
};
|
||||
const finish = (id: number) => core.updateSession(db, id, { status: "done", endedAt: new Date() });
|
||||
const LONG = { turns: [[{ work: 60_000 }, { say: "Готово." }]] };
|
||||
|
||||
describe("Команда растёт в пределах ёмкости", () => {
|
||||
// First in the file: the team rule looks at all subscriptions of all sets.
|
||||
test("Все заняты, место есть — новый агент; ёмкость заполнена — не создаётся", async () => {
|
||||
for (const a of await core.listAgents(db)) await core.updateAgent(db, a.id, { disabled: true });
|
||||
const a = await claudeSub("Team A", "teamA");
|
||||
const p = await project({ turns: [] });
|
||||
const pool = await poolFor(p.key, [a.id]);
|
||||
await core.setPoolCapacity(db, admin, pool.id, 2);
|
||||
const [s1, s2] = await fill(p.key, a.id, 2);
|
||||
const g1 = await core.ensureSessionAgent(db, s1!);
|
||||
const g2 = await core.ensureSessionAgent(db, s2!);
|
||||
assert.ok(g1 && g2 && g1.id !== g2.id, "both runners got a persona while there was room");
|
||||
const before = (await db.select().from(agents)).length;
|
||||
// A third runner past the capacity (as if started before the rules): no new persona.
|
||||
const s3 = await fakeRunner(p.key, a.id);
|
||||
assert.equal(await core.ensureSessionAgent(db, s3), null);
|
||||
assert.equal((await db.select().from(agents)).length, before, "the team did not grow");
|
||||
await assert.rejects(core.assertAgentAvailable(db, a.id), (e) => core.isNoCapacity(e));
|
||||
// The manual «Добавить» works as before.
|
||||
const manual = await core.createAgent(db, {});
|
||||
assert.ok(manual.id);
|
||||
for (const id of [s1!, s2!, s3]) await finish(id);
|
||||
await core.updateAgent(db, manual.id, { disabled: true });
|
||||
});
|
||||
});
|
||||
|
||||
describe("Ёмкость подписки при запуске", () => {
|
||||
test("На подписке 9 живых — раннер на другой подписке набора; других нет — задача в очереди", async () => {
|
||||
const [a, b] = [await claudeSub("Cap A", "capA"), await claudeSub("Cap B", "capB")];
|
||||
const p = await project(LONG);
|
||||
await poolFor(p.key, [a.id, b.id]);
|
||||
const busy = await fill(p.key, a.id, 9);
|
||||
const r = await runner.moveTask(db, await core.resolveTask(db, p.taskKey), "in_progress");
|
||||
assert.ok(r.started, "a runner started");
|
||||
assert.equal((await core.getSession(db, r.started!)).subscriptionId, b.id, "on the subscription with room");
|
||||
await runner.stopSession(db, r.started!);
|
||||
|
||||
// The other subscription is full too: the story waits.
|
||||
const busyB = await fill(p.key, b.id, 9);
|
||||
const ref = await core.createTask(db, { projectId: (await core.getProject(db, p.key)).id, title: "Ждёт места" });
|
||||
const w = await runner.moveTask(db, ref, "in_progress");
|
||||
assert.equal(w.waiting, true);
|
||||
assert.equal(w.started, undefined);
|
||||
assert.equal((await core.resolveTask(db, ref.key)).task.status, "in_progress", "stays in work");
|
||||
assert.equal((await core.listSessions(db, { active: true, taskId: ref.task.id })).length, 0, "no runner");
|
||||
const q = await core.capacityQueue(db, { projectIds: [ref.project.id] });
|
||||
assert.deepEqual(q.map((x) => [x.key, x.position]), [[ref.key, 1]]);
|
||||
// Moving it to «В работу» again keeps its place and starts nothing.
|
||||
assert.equal((await runner.moveTask(db, ref, "in_progress")).started, undefined);
|
||||
// Back to the backlog: out of the queue.
|
||||
await runner.moveTask(db, ref, "backlog");
|
||||
assert.equal((await core.capacityQueue(db, { projectIds: [ref.project.id] })).length, 0);
|
||||
for (const id of [...busy, ...busyB]) await finish(id);
|
||||
});
|
||||
|
||||
test("Уже работающие сверх ёмкости не останавливаются, новые не стартуют, пока их не станет меньше", async () => {
|
||||
const a = await claudeSub("Over A", "overA");
|
||||
const p = await project(LONG);
|
||||
await poolFor(p.key, [a.id]);
|
||||
const over = await fill(p.key, a.id, 12);
|
||||
const w = await runner.moveTask(db, await core.resolveTask(db, p.taskKey), "in_progress");
|
||||
assert.equal(w.waiting, true);
|
||||
for (const id of over) assert.notEqual((await core.getSession(db, id)).status, "done", "nobody was stopped");
|
||||
// 12 → 9: still full.
|
||||
for (const id of over.slice(0, 3)) await finish(id);
|
||||
assert.equal(await runner.capacityQueueTick(db), 0);
|
||||
for (const id of over.slice(3)) await finish(id);
|
||||
await runner.moveTask(db, await core.resolveTask(db, p.taskKey), "backlog");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Очередь задач по ёмкости", () => {
|
||||
test("Место освободилось — задача из очереди запускается сама, по порядку на доске", async () => {
|
||||
const a = await claudeSub("Queue A", "queueA");
|
||||
const p = await project(LONG);
|
||||
const projectId = (await core.getProject(db, p.key)).id;
|
||||
const pool = await poolFor(p.key, [a.id]);
|
||||
await core.setPoolCapacity(db, admin, pool.id, 1);
|
||||
const [holder] = await fill(p.key, a.id, 1);
|
||||
const first = await core.resolveTask(db, p.taskKey); // higher on the board
|
||||
const second = await core.createTask(db, { projectId, title: "Вторая на доске" });
|
||||
// Queued in the opposite order: the board decides, not who came first.
|
||||
assert.equal((await runner.moveTask(db, second, "in_progress")).waiting, true);
|
||||
assert.equal((await runner.moveTask(db, first, "in_progress")).waiting, true);
|
||||
const q = await core.capacityQueue(db, { projectIds: [projectId] });
|
||||
assert.deepEqual(q.map((x) => [x.key, x.position]), [[first.key, 1], [second.key, 2]]);
|
||||
assert.deepEqual(await core.workLine(db, [projectId]), { doing: 0, queued: 2 });
|
||||
|
||||
// Still full — nothing starts.
|
||||
assert.equal(await runner.capacityQueueTick(db), 0);
|
||||
await finish(holder!);
|
||||
assert.equal(await runner.capacityQueueTick(db), 1);
|
||||
const live = await core.listSessions(db, { active: true, taskId: first.task.id });
|
||||
assert.equal(live.length, 1, "the story higher on the board started");
|
||||
assert.equal(live[0]!.subscriptionId, a.id);
|
||||
const left = await core.capacityQueue(db, { projectIds: [projectId] });
|
||||
assert.deepEqual(left.map((x) => [x.key, x.position]), [[second.key, 1]]);
|
||||
assert.deepEqual(await core.workLine(db, [projectId]), { doing: 1, queued: 1 });
|
||||
await runner.stopSession(db, live[0]!.id);
|
||||
await waitFor("runner stopped", async () => (await core.getSession(db, live[0]!.id)).status === "done" || (await core.getSession(db, live[0]!.id)).status === "failed");
|
||||
await runner.moveTask(db, second, "backlog");
|
||||
});
|
||||
|
||||
test("Диспетчер не берёт задачи из бэклога, пока у набора нет места", async () => {
|
||||
const a = await claudeSub("Disp A", "dispA");
|
||||
const p = await project(LONG);
|
||||
const projectId = (await core.getProject(db, p.key)).id;
|
||||
const pool = await poolFor(p.key, [a.id]);
|
||||
await core.setPoolCapacity(db, admin, pool.id, 1);
|
||||
const [holder] = await fill(p.key, a.id, 1);
|
||||
assert.equal(await core.poolHasRoom(db, projectId), false);
|
||||
await core.setAutonomy(db, projectId, { level: "auto" });
|
||||
await runner.autonomyTick(db, {});
|
||||
assert.equal((await core.resolveTask(db, p.taskKey)).task.status, "backlog", "stays in the backlog");
|
||||
await finish(holder!);
|
||||
assert.equal(await core.poolHasRoom(db, projectId), true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Ротация уважает ёмкость", () => {
|
||||
test("Запасная подписка заполнена — переключения нет", async () => {
|
||||
const [a, b] = [await claudeSub("Rot A", "rotA"), await claudeSub("Rot B", "rotB")];
|
||||
const p = await project({ turns: [] });
|
||||
const projectId = (await core.getProject(db, p.key)).id;
|
||||
await poolFor(p.key, [a.id, b.id]);
|
||||
const busyB = await fill(p.key, b.id, 9);
|
||||
assert.equal(await core.rotationCandidate(db, { projectId, provider: "claude", subscriptionId: a.id }), null);
|
||||
await finish(busyB[0]!);
|
||||
assert.equal((await core.rotationCandidate(db, { projectId, provider: "claude", subscriptionId: a.id }))?.id, b.id, "room again — moves there");
|
||||
for (const id of busyB) await finish(id);
|
||||
});
|
||||
|
||||
test("Ручной перевод на заполненную подписку — агенты остаются на месте", async () => {
|
||||
const [a, b] = [await claudeSub("Sw A", "swA"), await claudeSub("Sw B", "swB")];
|
||||
const p = await project({ turns: [] });
|
||||
await poolFor(p.key, [a.id, b.id]);
|
||||
const onA = await fill(p.key, a.id, 1);
|
||||
const busyB = await fill(p.key, b.id, 9);
|
||||
assert.deepEqual(await runner.switchAgents(db, { fromId: a.id, toId: b.id }), { moved: 0, skipped: 1 });
|
||||
assert.equal((await core.getSession(db, onA[0]!)).subscriptionId, a.id);
|
||||
for (const id of [...onA, ...busyB]) await finish(id);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Суперадмин меняет ёмкость", () => {
|
||||
test("Новое значение действует сразу; вне 1–20 и не суперадмину — отказ; «агентов: N из M»", async () => {
|
||||
const a = await claudeSub("Set A", "setA");
|
||||
const p = await project({ turns: [] });
|
||||
const projectId = (await core.getProject(db, p.key)).id;
|
||||
const pool = await poolFor(p.key, [a.id]);
|
||||
const busy = await fill(p.key, a.id, 3);
|
||||
assert.equal(await core.poolHasRoom(db, projectId), true);
|
||||
let o = (await core.poolOverview(db, pool.id))!;
|
||||
assert.equal(o.capacity, 9);
|
||||
assert.equal(o.subscriptions[0]!.capacity, 9);
|
||||
assert.equal(o.subscriptions[0]!.load, "агентов: 3 из 9");
|
||||
assert.equal(await core.setPoolCapacity(db, admin, pool.id, 3), 3);
|
||||
assert.equal(await core.poolHasRoom(db, projectId), false, "works at once");
|
||||
o = (await core.poolOverview(db, pool.id))!;
|
||||
assert.equal(o.subscriptions[0]!.load, "агентов: 3 из 3");
|
||||
assert.deepEqual({ live: o.live, total: o.total }, { live: 3, total: 3 });
|
||||
await assert.rejects(core.setPoolCapacity(db, admin, pool.id, 25), /от 1 до 20/);
|
||||
await assert.rejects(core.setPoolCapacity(db, admin, pool.id, 0), /от 1 до 20/);
|
||||
await assert.rejects(core.setPoolCapacity(db, pm, pool.id, 5));
|
||||
for (const id of busy) await finish(id);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Очередь на виду у продакта", () => {
|
||||
test("Страница задачи в очереди: место в очереди и что дальше — без подписок", () => {
|
||||
const v = core.storyProductView({ status: "in_progress", agentWorking: false, openQuestions: 0, queued: 2 });
|
||||
assert.equal(stripAsIs(v.now), "В очереди: 2-я, начнётся, когда освободится агент");
|
||||
assert.doesNotMatch(`${v.now} ${v.next}`, /подписк|раннер|ёмкост/i);
|
||||
const paused = core.storyProductView({ status: "in_progress", agentWorking: false, openQuestions: 0 });
|
||||
assert.equal(paused.now, core.STORY_PRODUCT_TEXT.paused.now, "without a queue — as before");
|
||||
});
|
||||
});
|
||||
Loading…
Reference in New Issue
Block a user