// PEP-31: first-run checklist on the home page and the "agents won't start" project warning. import { projects, sessions, subscriptions, tasks, users, type Db } from "@peppa/db"; import { and, count, eq, inArray, isNotNull } from "drizzle-orm"; import { mayUseMachineLogin } from "./access.ts"; import { isSuperadmin } from "./monitor.ts"; import { getSetting, setSetting } from "./settings.ts"; import { isUsable, poolSubscriptions } from "./subscriptions.ts"; import { userProjectIds, type User } from "./users.ts"; export type OnboardingStepId = "subscription" | "telegram" | "egov" | "project" | "story" | "started"; export interface OnboardingStep { id: OnboardingStepId; title: string; hint: string; href: string; done: boolean; optional: boolean; } export interface Onboarding { steps: OnboardingStep[]; /** Required steps done / total. */ done: number; total: number; /** All required steps done. */ complete: boolean; dismissed: boolean; /** Shown on the home page. */ visible: boolean; } const dismissedKey = (userId: number) => `onboarding.dismissed:${userId}`; export async function dismissOnboarding(db: Db, userId: number): Promise { await setSetting(db, dismissedKey(userId), { at: new Date().toISOString() }); } export async function onboardingChecklist(db: Db, user: Pick): Promise { const [me] = await db.select({ chat: users.telegramChatId, iin: users.egovIin }).from(users).where(eq(users.id, user.id)); const admin = await isSuperadmin(db, user); const ids = await userProjectIds(db, user.id); const n = async (q: Promise>) => (await q)[0]?.n ?? 0; const storyCount = ids.length ? await n(db.select({ n: count() }).from(tasks).where(inArray(tasks.projectId, ids))) : 0; const started = ids.length ? await n(db.select({ n: count() }).from(sessions).where(and(inArray(sessions.projectId, ids), isNotNull(sessions.taskId)))) : 0; const firstKey = ids.length ? (await db.select({ key: projects.key }).from(projects).where(inArray(projects.id, ids)).limit(1))[0]?.key : undefined; const steps: OnboardingStep[] = []; if (admin) { const subs = await db.select({ status: subscriptions.status, limitedUntil: subscriptions.limitedUntil }).from(subscriptions); steps.push({ id: "subscription", title: "Подключить подписку агента", hint: "Claude, Codex или OpenCode — на ней работают агенты; добавь её в пул проекта.", href: "/subscriptions", done: subs.some((s) => s.status === "active" || s.status === "limited"), optional: false, }); } steps.push( { id: "telegram", title: "Привязать Telegram", hint: "Вопросы агентов и «готово к ревью» придут в бот, отвечать можно кнопками.", href: "/settings#telegram", done: me?.chat != null, optional: false }, { id: "egov", title: "Привязать eGov", hint: "Вход по QR из eGov Mobile без пароля.", href: "/settings#egov", done: !!me?.iin, optional: true }, { id: "project", title: "Создать проект", hint: "Пеппа заведёт репозиторий в Gitea с шаблоном и CI.", href: "/projects/new", done: ids.length > 0, optional: false }, { id: "story", title: "Завести стори", hint: "Опиши, что нужно сделать, — одна стори = одно изменение.", href: firstKey ? `/p/${firstKey}` : "/projects", done: storyCount > 0, optional: false }, { id: "started", title: "Двинуть стори в работу", hint: "Перетащи карточку в «В работе» — агент запустится сам.", href: firstKey ? `/p/${firstKey}` : "/projects", done: started > 0, optional: false }, ); const required = steps.filter((s) => !s.optional); const done = required.filter((s) => s.done).length; const complete = done === required.length; const dismissed = !!(await getSetting(db, dismissedKey(user.id))); return { steps, done, total: required.length, complete, dismissed, visible: !complete && !dismissed }; } const STATUS_RU: Record = { pending: "не подключена", limited: "в лимите", auth_error: "ошибка входа", active: "активна" }; /** * Why agents of the project won't start, or null: the project's pool has no working * subscription. Without a pool the runner uses this machine's login (not checked here). */ export async function projectAgentWarning(db: Db, projectId: number, now = new Date()): Promise { const [p] = await db.select({ poolId: projects.subscriptionPoolId }).from(projects).where(eq(projects.id, projectId)); if (p?.poolId == null) { // PEP-71/76: a self-registered owner has no machine login — a subscription must be chosen. const [o] = await db.select({ ownerId: projects.ownerId }).from(projects).where(eq(projects.id, projectId)); return (await mayUseMachineLogin(db, o?.ownerId ?? null)) ? null : "подписка не подключена — владелец подключает свою (Claude или ChatGPT) в «⋯ Настройки проекта → Подписки»"; } const subs = await poolSubscriptions(db, p.poolId); if (!subs.length) return "в пуле подписок проекта нет ни одной подписки"; if (subs.some((s) => isUsable(s, now))) return null; const why = subs.map((s) => `«${s.name}» — ${STATUS_RU[s.status] ?? s.status}${s.status === "limited" && s.limitedUntil ? ` до ${s.limitedUntil.toLocaleString("ru-RU", { hour: "2-digit", minute: "2-digit", day: "2-digit", month: "2-digit" })}` : ""}`); return `нет рабочей подписки в пуле проекта: ${why.join(", ")}`; }