Заход приёмки 27.11: PEP-273 поверх main и принятых перед ней [skip ci]

This commit is contained in:
peppa-bot 2026-11-27 10:08:39 +05:00
commit 4a15bcf551
56 changed files with 479 additions and 80 deletions

4
.peppa/memory/pep-273.md Normal file
View File

@ -0,0 +1,4 @@
# Память: PEP-273
## Соглашения
- Ссылки веба — только `Link` из `@/components/Link` (предзагрузка выкл., PEP-273; тест no-prefetch); медленная страница из-за Gitea — кэш в globalThis, как `giteaServerOverview`.

View File

@ -1,4 +1,4 @@
import Link from "next/link";
import Link from "@/components/Link";
import { notFound } from "next/navigation";
import { ArrowLeft, Bot, Link2, MessagesSquare, Send, Unlink, User as UserIcon } from "lucide-react";
import { ANALYST_NAME, analystPending, attachmentsByMessage, chatStatusLine, isSuperadmin, chatGroupBotName, chatMessagesView, chatTtlMs, discussionMessages, discussionUnread, getSetting, listChats, markDiscussionRead, markThreadRead, masterFeed, projectThreadList, splitForDisplay, syncChats, threadTitle, THREAD_KEY, type AttachmentView, type ChatMessageView, type Question } from "@peppa/core";

View File

@ -1,4 +1,4 @@
import Link from "next/link";
import Link from "@/components/Link";
import { ArrowRight, MessagesSquare } from "lucide-react";
import { chatOverview, isRoleName, syncChats } from "@peppa/core";
import { LiveRefresh } from "@/components/LiveRefresh";

View File

@ -1,4 +1,4 @@
import Link from "next/link";
import Link from "@/components/Link";
import { ExternalLink, PlugZap, Search } from "lucide-react";
import {
CATALOG_KIND_TEXT,

View File

@ -1,4 +1,4 @@
import Link from "next/link";
import Link from "@/components/Link";
import { notFound } from "next/navigation";
import { Hourglass } from "lucide-react";
import { isSuperadmin, platformDelayOverview } from "@peppa/core";

View File

@ -1,4 +1,4 @@
import Link from "next/link";
import Link from "@/components/Link";
import { notFound } from "next/navigation";
import { Gauge } from "lucide-react";
import { isSuperadmin, platformDashboard, platformDelayCounts, type DashboardCounts } from "@peppa/core";

View File

@ -1,7 +1,7 @@
// PEP-218: the card of one production error, read from Bugsink on the server. The superadmin
// opens any error, a project's owner or member — errors of that project only (else 404).
// «Инженер» and the superadmin see the stack, tags, events and the link to Bugsink.
import Link from "next/link";
import Link from "@/components/Link";
import { notFound } from "next/navigation";
import { Bug, ExternalLink } from "lucide-react";
import { errorDetail, errorScope } from "@peppa/core";

View File

@ -1,4 +1,4 @@
import Link from "next/link";
import Link from "@/components/Link";
import { FEEDBACK_ADMIN_STATUS, FEEDBACK_STATUSES, isFeedbackStatus, isSuperadmin, listAllFeedback, listUserFeedback } from "@peppa/core";
import { AdminFeedbackCard, MyFeedbackCard } from "@/components/Feedback";
import { Empty, Flash, PageHeader, Section } from "@/components/common";

View File

@ -20,6 +20,8 @@ export async function makeRepoPrivateAction(f: FormData) {
await requireSuperadmin(db, user);
const r = await makeRepoPrivate(db, user, str(f, "repo"));
back.set("closed", r.fullName);
// The list is cached (PEP-273): without a fresh one the repository would still show as public for a minute.
back.set("fresh", "1");
} catch (e) {
const t = await getT();
const msg = e instanceof PeppaError ? t.text(e.message) : t("Ошибка: {message}", { message: (e as Error).message });

View File

@ -1,5 +1,5 @@
// glossary-ignore-file: superadmin-only page about the platform's git server — «репозиторий» is the literal object here
import Link from "next/link";
import Link from "@/components/Link";
import { notFound } from "next/navigation";
import { ExternalLink, GitBranch, Lock } from "lucide-react";
import { giteaServerOverview, isSuperadmin, type GiteaServerRepo } from "@peppa/core";
@ -20,9 +20,12 @@ export async function generateMetadata() {
return { title: t("Gitea — FORGE") };
}
type Params = { q?: string; show?: string; closed?: string; error?: string };
type Params = { q?: string; show?: string; closed?: string; error?: string; page?: string; fresh?: string };
type Show = "all" | "linked" | "unlinked" | "public";
/** Rows per page (PEP-273: the whole list made the page over 1 MB). */
const PAGE_SIZE = 50;
function RepoRow({ r, t, q, show }: { r: GiteaServerRepo; t: Translator; q: string; show: Show }) {
return (
<li className="flex flex-col gap-1 border-b border-border px-4 py-3 last:border-b-0">
@ -75,7 +78,7 @@ export default async function GiteaPage({ searchParams }: { searchParams: Promis
const t = await getT();
if (!(await isSuperadmin(db, user))) notFound();
const q = await searchParams;
const o = await giteaServerOverview(db);
const o = await giteaServerOverview(db, { fresh: q.fresh === "1" });
const needle = (q.q ?? "").trim().toLowerCase();
const show: Show = q.show === "linked" || q.show === "unlinked" || q.show === "public" ? q.show : "all";
const repos = o.repos.filter(
@ -84,6 +87,17 @@ export default async function GiteaPage({ searchParams }: { searchParams: Promis
(show === "all" || (show === "public" ? !r.private : (show === "linked") === !!r.project)),
);
const open = o.repos.filter((r) => !r.private).length;
const pages = Math.max(1, Math.ceil(repos.length / PAGE_SIZE));
const page = Math.min(pages, Math.max(1, Number.parseInt(q.page ?? "1", 10) || 1));
const shown = repos.slice((page - 1) * PAGE_SIZE, page * PAGE_SIZE);
const href = (extra: Record<string, string>) => {
const sp = new URLSearchParams();
if (q.q) sp.set("q", q.q);
if (show !== "all") sp.set("show", show);
for (const [k, v] of Object.entries(extra)) sp.set(k, v);
const s = sp.toString();
return s ? `/gitea?${s}` : "/gitea";
};
const owners = new Map<string, number>();
for (const r of o.repos) owners.set(r.owner, (owners.get(r.owner) ?? 0) + 1);
const linked = o.repos.filter((r) => r.project).length;
@ -111,6 +125,12 @@ export default async function GiteaPage({ searchParams }: { searchParams: Promis
{t("Бот")}: <span className="font-mono">{o.bot?.login ?? "—"}</span>
{o.bot && (o.bot.admin ? <Badge variant="ok" className="ml-2">{t("админ сервера — видит все репозитории")}</Badge> : <Badge variant="warn" className="ml-2">{t("не админ — видит публичные и свои репозитории")}</Badge>)}
</div>
{o.fetchedAt && (
<div className="text-muted-foreground">
{t("Список получен {when}", { when: ago(o.fetchedAt, t) })} ·{" "}
<a href={href({ fresh: "1" })}>{t("Получить заново")}</a>
</div>
)}
{o.repos.length > 0 && (
<div className="text-muted-foreground">
{t("Репозиториев: {n} · подключены к проектам: {linked}", { n: o.repos.length, linked })} ·{" "}
@ -151,12 +171,19 @@ export default async function GiteaPage({ searchParams }: { searchParams: Promis
) : (
<Card className="p-0">
<ul>
{repos.map((r) => (
{shown.map((r) => (
<RepoRow key={r.fullName} r={r} t={t} q={q.q ?? ""} show={show} />
))}
</ul>
</Card>
)}
{pages > 1 && (
<nav className="mt-3 flex items-center gap-3 text-sm">
{page > 1 ? <a href={href({ page: String(page - 1) })}>{t("‹ Назад")}</a> : <span className="text-muted-foreground">{t("‹ Назад")}</span>}
<span className="text-muted-foreground">{t("Страница {page} из {pages}", { page, pages })}</span>
{page < pages ? <a href={href({ page: String(page + 1) })}>{t("Дальше ›")}</a> : <span className="text-muted-foreground">{t("Дальше ›")}</span>}
</nav>
)}
</Section>
</div>
</Workspace>

View File

@ -1,4 +1,4 @@
import Link from "next/link";
import Link from "@/components/Link";
import { CONNECT_HELP, featureGateView } from "@peppa/core";
import { FeatureGate } from "@/components/FeatureGate";
import { LiveRefresh } from "@/components/LiveRefresh";

View File

@ -1,4 +1,4 @@
import Link from "next/link";
import Link from "@/components/Link";
import type { ReactNode } from "react";
import { CONNECT_HELP, featureGateView, PRODUCT_HELP } from "@peppa/core";
import { FeatureGate } from "@/components/FeatureGate";

View File

@ -1,4 +1,4 @@
import Link from "next/link";
import Link from "@/components/Link";
import { ShortcutsList } from "@/components/CommandPalette";
import { PageHeader, Section } from "@/components/common";
import { Workspace } from "@/components/Workspace";

View File

@ -1,5 +1,5 @@
// glossary-ignore-file: the section is for the superadmin only.
import Link from "next/link";
import Link from "@/components/Link";
import { notFound } from "next/navigation";
import { Activity, Pause, Play, Trash2 } from "lucide-react";
import { describeTarget, FEATURES, observeRemindMin, getMonitor, isSuperadmin, monitorChecks, monitorIncidents, monitorView } from "@peppa/core";

View File

@ -1,5 +1,5 @@
// glossary-ignore-file: the section is for the superadmin only.
import Link from "next/link";
import Link from "@/components/Link";
import { notFound } from "next/navigation";
import { Activity, Pause, Play, Plus } from "lucide-react";
import { describeTarget, observeRemindMin, PROVIDER_LABEL, smokeStatus, smokeTimeoutMin, type SmokeRun, type SmokeStatus, egovLoginSummary, errorScope, errorsOverview, FEATURE_NAMES, FEATURES, featureLog, featureStatuses, getLastRetention, isSuperadmin, listErrors, listMonitorViews, requestSummary, isBadVital, vitalsSummary, type VitalDevice, type VitalMetric } from "@peppa/core";

View File

@ -1,4 +1,4 @@
import Link from "next/link";
import Link from "@/components/Link";
import { notFound } from "next/navigation";
import { acceptAllSummary, acceptScreen, type AcceptItem } from "@peppa/core";
import { acceptAllAction, fixStoryAction } from "@/app/(app)/actions";

View File

@ -1,4 +1,4 @@
import Link from "next/link";
import Link from "@/components/Link";
import { Fragment } from "react";
import { ProductCard } from "@/components/ProductCard";
import { PublishPanel } from "@/components/PublishPanel";

View File

@ -1,5 +1,5 @@
// PEP-42: plan an epic — the planner proposes stories with dependencies; the PM edits and approves.
import Link from "next/link";
import Link from "@/components/Link";
import { notFound } from "next/navigation";
import { Sparkles } from "lucide-react";
import { getEpic, listTasks } from "@peppa/core";

View File

@ -1,6 +1,6 @@
import { Suspense } from "react";
import { redirect } from "next/navigation";
import Link from "next/link";
import Link from "@/components/Link";
import { agentTaskSummary, claimWelcome, isSuperadmin, listUserProjects, onboardingChecklist, pendingFeedback, platformDelayCounts, progressOverview, proposedCount, reviewCounts } from "@peppa/core";
import { AdminFeedbackCard } from "@/components/Feedback";
import { AgentTaskSummary } from "@/components/AgentTaskSummary";

View File

@ -1,4 +1,4 @@
import Link from "next/link";
import Link from "@/components/Link";
import { Plus } from "lucide-react";
import { analystLinks, isSuperadmin, listOtherProjects, listUserProjects, projectTrashDays } from "@peppa/core";
import { ProjectList } from "@/components/cards";

View File

@ -1,4 +1,4 @@
import Link from "next/link";
import Link from "@/components/Link";
import { Search, SquareTerminal } from "lucide-react";
import { listUserProjects, runnerStories, listUserSessions, RUNNER_FILTERS, sessionSteps, type RunnerFilter, type SessionView } from "@peppa/core";
import { LiveRefresh } from "@/components/LiveRefresh";

View File

@ -2,7 +2,7 @@
// «Сессии» (PEP-257): one place for the terminals of all live agent sessions of the user's
// projects. Left — the list, right — the terminal of the chosen one, open right away: the first
// of the list without `?id`, the given one with it (a story links here with its session).
import Link from "next/link";
import Link from "@/components/Link";
import { SquareTerminal } from "lucide-react";
import { FINISHED_SESSION_STATUSES, listUserSessions, PROVIDER_NAMES, type SessionView } from "@peppa/core";
import { AgentBadge } from "@/components/AgentBadge";

View File

@ -2,7 +2,7 @@
// 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 Link from "@/components/Link";
import { notFound } from "next/navigation";
import { Archive, ArchiveRestore, ChevronDown, ChevronRight, CircleCheck, CircleX, GitPullRequest, Hourglass, Lock, Pencil, Play, X } from "lucide-react";
import {

View File

@ -1,5 +1,5 @@
// glossary-ignore-file: the page is for the superadmin only (accounts, repositories, Gitea spaces).
import Link from "next/link";
import Link from "@/components/Link";
import { notFound } from "next/navigation";
import { isSuperadmin, maskIin, mergePlan, PeppaError } from "@peppa/core";
import { Hidden } from "@/components/cards";

View File

@ -1,5 +1,5 @@
import { notFound } from "next/navigation";
import Link from "next/link";
import Link from "@/components/Link";
import { canLogIn, isLocalUser, isSuperadmin, listUsers, maskIin, mergeHints, platformAdmins } from "@peppa/core";
import { Hidden } from "@/components/cards";
import { ago, Flash, PageHeader, Section } from "@/components/common";

View File

@ -1,5 +1,5 @@
// PEP-92: the welcome page for everyone who signs in — why Peppa, how work goes, where to click.
import Link from "next/link";
import Link from "@/components/Link";
import { ArrowRight, Check } from "lucide-react";
import { Workspace } from "@/components/Workspace";
import { PageHeader, Section } from "@/components/common";

View File

@ -1,5 +1,5 @@
// Accounting blocks (PEP-5/43/47/48): the usage strip on top, story budget, project metrics, journal.
import Link from "next/link";
import Link from "@/components/Link";
import type { ReactNode } from "react";
import { Gauge, Hourglass, Play } from "lucide-react";
import {

View File

@ -1,4 +1,4 @@
import Link from "next/link";
import Link from "@/components/Link";
import { ago } from "@/components/common";
import { requireUser, words } from "@/lib/auth";
import { activeSessions, inbox } from "@/lib/queries";

View File

@ -1,4 +1,4 @@
import Link from "next/link";
import Link from "@/components/Link";
import type { AgentTaskRow } from "@peppa/core";
import { Badge } from "@/components/ui/badge";
import { getT } from "@/lib/i18n";

View File

@ -1,7 +1,7 @@
"use client";
import { useWords } from "@/components/Words";
import Link from "next/link";
import Link from "@/components/Link";
import { useRouter } from "next/navigation";
import { useEffect, useState, useTransition } from "react";
import { useLiveIsland } from "@/lib/live";

View File

@ -1,4 +1,4 @@
import Link from "next/link";
import Link from "@/components/Link";
import { Search, X } from "lucide-react";
import type { ThreadList, ThreadRow } from "@peppa/core";
import { AgentBadge } from "@/components/AgentBadge";

View File

@ -1,7 +1,7 @@
// PEP-218: production errors read from Bugsink on the server — summary, filters, rows and the
// error card blocks. «Инженер» and the superadmin (`tech`) also see code places, releases,
// stacks and tags; «Продакт» — the title, how often, when and the bug task.
import Link from "next/link";
import Link from "@/components/Link";
import { Bug, TrendingUp } from "lucide-react";
import type { ErrorDetail, ErrorFilter, ErrorRow, ErrorScope, ErrorsOverview, ErrorState } from "@peppa/core";
import { m, type Translator } from "@peppa/shared/i18n";

View File

@ -1,4 +1,4 @@
import Link from "next/link";
import Link from "@/components/Link";
import { FEEDBACK_ADMIN_STATUS, FEEDBACK_KIND, FEEDBACK_SIZE, FEEDBACK_USER_STATUS, feedbackTitle, type FeedbackView } from "@peppa/core";
import { Hidden } from "@/components/cards";
import { ago, Disclosure } from "@/components/common";

View File

@ -1,6 +1,6 @@
"use client";
import Link from "next/link";
import Link from "@/components/Link";
import { useCallback, useEffect, useRef, useState } from "react";
import { usePathname } from "next/navigation";
import { CircleCheck, ImagePlus, MessageCircleWarning, X } from "lucide-react";

View File

@ -0,0 +1,9 @@
// PEP-273: every link of the console goes through here. Next prefetches each visible <Link> in a
// production build; our pages are dynamic, so the home page alone made ~40 server renders per visit.
// Prefetch only where a link asks for it explicitly (`prefetch`).
import NextLink from "next/link";
import type { ComponentProps } from "react";
export default function Link({ prefetch = false, ...props }: ComponentProps<typeof NextLink>) {
return <NextLink prefetch={prefetch} {...props} />;
}

View File

@ -1,4 +1,4 @@
import Link from "next/link";
import Link from "@/components/Link";
import { DELAY_REASON_NAMES, type DelayView } from "@peppa/core";
import { delayActionForm } from "@/app/(app)/dashboard/actions";
import { Badge } from "@/components/ui/badge";

View File

@ -1,5 +1,5 @@
import type { ReactNode } from "react";
import Link from "next/link";
import Link from "@/components/Link";
import type { PoolOverview, PoolSubscriptionState } from "@peppa/core";
import { intlLocale, type Locale } from "@peppa/shared/i18n";
import { Badge } from "@/components/ui/badge";

View File

@ -1,4 +1,4 @@
import Link from "next/link";
import Link from "@/components/Link";
import { ExternalLink, Hourglass, KeyRound, Rocket, Wrench, X } from "lucide-react";
import type { ProductNeedView, ProductReview, ProjectProduct, PublishMode } from "@peppa/core";
import { Hidden } from "@/components/cards";

View File

@ -1,4 +1,4 @@
import Link from "next/link";
import Link from "@/components/Link";
import type { ProgressOverview as Overview, ProjectProgress } from "@peppa/core";
import { AgentBadge } from "@/components/AgentBadge";
import { Empty, Key } from "@/components/common";

View File

@ -1,6 +1,6 @@
// PEP-218: the project's tab «Баги» — errors of its own Bugsink projects (`<KEY>-web` /
// `<KEY>-api`), read on the server, in the same view as the superadmin's /observability.
import Link from "next/link";
import Link from "@/components/Link";
import { errorScope, listErrors } from "@peppa/core";
import { ErrorFilters, errorFilterFrom, ErrorRows, ErrorsDown } from "@/components/Errors";
import { Section } from "@/components/common";

View File

@ -1,5 +1,5 @@
// Runners console (PEP-38): list rows with status and limit info, and the details panel of the chosen runner.
import Link from "next/link";
import Link from "@/components/Link";
import { SquareTerminal, X } from "lucide-react";
import { FINISHED_SESSION_STATUSES, PROVIDER_NAMES, type RunnerTaskView, type SessionView, type StepView } from "@peppa/core";
import { RunnerStories } from "@/components/Runners";

View File

@ -1,6 +1,6 @@
"use client";
import Link from "next/link";
import Link from "@/components/Link";
import { usePathname } from "next/navigation";
import { useEffect, useState } from "react";
import { useLive } from "@/lib/live";

View File

@ -1,5 +1,5 @@
// Domain cards shared by pages: agent questions, runners, project list.
import Link from "next/link";
import Link from "@/components/Link";
import { BellRing, CircleCheck, CircleHelp, FileCheck, Hourglass, Play, RotateCcw, Send, ShieldQuestion, Square, SquareTerminal } from "lucide-react";
import { pausedProjectIds, messageDetails, questionAuthor, questionDetails, questionIsFreeText, questionState, questionText, questionType, splitForDisplay, trashDaysLeft, type Project, type Question, type SessionView, type StepView } from "@peppa/core";
import { db } from "@/lib/db";

View File

@ -1,5 +1,5 @@
// Page building blocks of the console (PEP-38): header, sections, empty states, status badges, alerts.
import Link from "next/link";
import Link from "@/components/Link";
import type { ReactNode } from "react";
import { CircleAlert, CircleCheck } from "lucide-react";
import { Badge } from "@/components/ui/badge";

View File

@ -0,0 +1,28 @@
# Design
## Кэш списка Gitea
`giteaServerOverview(db, { fresh? })` хранит последний удачный результат в `globalThis`
(`__peppaGiteaOverview`: `{at, value}`) и одно обещание обновления (без параллельных загрузок).
- моложе `FRESH_MS` (60 с) — отдаётся как есть;
- моложе `STALE_MS` (10 мин) — отдаётся сразу, обновление идёт в фоне;
- иначе / `fresh` — ждём загрузку.
Ошибка не кэшируется: при сбое отдаётся прежний результат (если он есть) с полем `error`.
Привязка к проектам (`project`) считается при каждом вызове из базы — она дешёвая и должна быть точной.
## Параллельные страницы
`/user` и первая страница поиска — одновременно. Если первая полная — дальше пачками по 8 страниц
одновременно, пока не придёт неполная или пустая страница (предел — прежние 40 страниц × 50).
Заголовок `X-Total-Count` не используем: `GiteaClient.request` его не отдаёт, а пачки и так дают
≈ 2 круга до Gitea на 400 репозиториев вместо 8.
## Страница
`PAGE_SIZE` = 50 строк; навигация «‹ Назад · N из M · Дальше ›» с сохранением `q`/`show`; строка
«данные на ЧЧ:ММ · Обновить». 50 строк ≈ 50–80 КБ HTML — далеко ниже 1 МБ.
## Предзагрузка
Next 16 в рабочей сборке предзагружает каждую видимую `<Link>`; на главной их ~40 (меню, проекты,
задачи, вопросы). Глобального выключателя в `next.config` нет, поэтому — своя обёртка
`components/Link.tsx` (`prefetch` по умолчанию `false`, остальное — как у `next/link`) и замена
импорта во всех файлах. Тест `no-prefetch.test.ts` не даёт вернуть прямой импорт `next/link` в
`apps/web/app|components|lib`. Цена — переход открывается без заранее полученной страницы; страницы у нас
динамические и всё равно рисуются заново, а живые обновления идут по WebSocket.

View File

@ -0,0 +1,23 @@
# PEP-273: /gitea ≤ 1 с и ≤ 1 МБ, главная не предзагружает ~40 маршрутов
## Why
Замеры живого сервера (F-09, F-10 отчёта тестирования 24.11): `/gitea` отвечает 2,4–6,5 с — страница
при каждой отрисовке ходит в Gitea за списком репозиториев постранично и по очереди (до 40 запросов
подряд) и рисует сразу все репозитории (страница больше 1 МБ). Главная при открытии предзагружает
~40 маршрутов: каждая видимая ссылка `next/link` в рабочей сборке сама запрашивает свою страницу,
а страницы у нас динамические — это десятки отрисовок на сервере на каждое открытие главной.
## What Changes
- Список репозиториев Gitea кэшируется в процессе веба (свежий 60 с, устаревший до 10 мин отдаётся
сразу и обновляется в фоне; «Обновить» — `?fresh=1`), страницы поиска Gitea запрашиваются
параллельно, а не по очереди.
- `/gitea` рисует не больше 50 репозиториев на страницу (`?page=`), фильтр — до нарезки.
- Все ссылки веба идут через `@/components/Link` — обёртку `next/link` с `prefetch={false}` по
умолчанию; прямой импорт `next/link` запрещён тестом. Предзагрузка остаётся там, где её явно
попросили (`prefetch`).
## Impact
- `packages/core/src/gitea-server.ts`, `apps/web/app/(app)/gitea/page.tsx`, `apps/web/components/Link.tsx`
и все файлы с `next/link`; мок `/repos/search` в `mock-gitea`.
- Действия «Принять» / перезапуск агента / подписки из описания задачи (запись «Медленно» у ACTION)
в этот change не входят — у них уже свой порог `PEPPA_SLOW_ACTION_MS` (PEP-309); заголовок задачи — F-09/F-10.

View File

@ -0,0 +1,36 @@
## ADDED Requirements
### Requirement: Страница Gitea отвечает быстро и компактно
Страница `/gitea` SHALL брать список репозиториев из кэша процесса (свежий 60 с, устаревший до 10 минут
отдаётся сразу с обновлением в фоне), загружать страницы списка из Gitea параллельно и показывать
не больше 50 репозиториев на странице с переходом между страницами.
#### Scenario: Повторное открытие не ходит в Gitea
- **GIVEN** на сервере Gitea 600 репозиториев и суперадмин только что открыл «Gitea»
- **WHEN** он открывает страницу ещё раз в течение минуты
- **THEN** список приходит без запросов к Gitea
#### Scenario: Большой сервер — одна страница из 50
- **GIVEN** на сервере Gitea 600 репозиториев
- **WHEN** суперадмин открывает «Gitea»
- **THEN** видно «Репозиториев: 600» и ровно 50 строк репозиториев
- **AND** есть переход на следующую страницу
#### Scenario: Gitea упала после удачной загрузки
- **GIVEN** список уже загружен, а потом Gitea перестала отвечать
- **WHEN** кэш устарел и суперадмин просит «Обновить»
- **THEN** видны прежние репозитории и предупреждение «Gitea не ответила»
### Requirement: Ссылки не предзагружают страницы
Ссылки веба SHALL по умолчанию не предзагружать страницы, на которые ведут; предзагрузка — только
по явному `prefetch`.
#### Scenario: Главная открывается без предзагрузки
- **GIVEN** главная с меню, проектами и задачами
- **WHEN** пользователь открывает главную
- **THEN** браузер не запрашивает страницы, на которые ведут ссылки
#### Scenario: Прямой импорт next/link
- **GIVEN** файл веба импортирует `next/link` напрямую
- **WHEN** запускаются тесты
- **THEN** тест сообщает файл и просит импортировать `@/components/Link`

View File

@ -0,0 +1,11 @@
## 1. Gitea
- [x] 1.1 Кэш и параллельные страницы в `giteaServerOverview`
- [x] 1.2 `/gitea`: 50 на страницу, навигация, «данные на · Обновить», тексты en/kk
- [x] 1.3 Мок `/repos/search` и тест `gitea-overview-speed.test.ts`
## 2. Предзагрузка
- [x] 2.1 `components/Link.tsx` и замена импортов `next/link`
- [x] 2.2 Тест `no-prefetch.test.ts`
## 3. Завершение
- [x] 3.1 Проверки (lint, typecheck, тесты), память, archive, PR

View File

@ -0,0 +1,41 @@
# web-speed Specification
## Purpose
Как веб остаётся быстрым: тяжёлые данные внешних сервисов — из кэша процесса, длинные списки — постранично, ссылки не предзагружают страницы.
## Requirements
### Requirement: Страница Gitea отвечает быстро и компактно
Страница `/gitea` SHALL брать список репозиториев из кэша процесса (свежий 60 с, устаревший до 10 минут
отдаётся сразу с обновлением в фоне), загружать страницы списка из Gitea параллельно и показывать
не больше 50 репозиториев на странице с переходом между страницами.
#### Scenario: Повторное открытие не ходит в Gitea
- **GIVEN** на сервере Gitea 600 репозиториев и суперадмин только что открыл «Gitea»
- **WHEN** он открывает страницу ещё раз в течение минуты
- **THEN** список приходит без запросов к Gitea
#### Scenario: Большой сервер — одна страница из 50
- **GIVEN** на сервере Gitea 600 репозиториев
- **WHEN** суперадмин открывает «Gitea»
- **THEN** видно «Репозиториев: 600» и ровно 50 строк репозиториев
- **AND** есть переход на следующую страницу
#### Scenario: Gitea упала после удачной загрузки
- **GIVEN** список уже загружен, а потом Gitea перестала отвечать
- **WHEN** кэш устарел и суперадмин просит «Обновить»
- **THEN** видны прежние репозитории и предупреждение «Gitea не ответила»
### Requirement: Ссылки не предзагружают страницы
Ссылки веба SHALL по умолчанию не предзагружать страницы, на которые ведут; предзагрузка — только
по явному `prefetch`.
#### Scenario: Главная открывается без предзагрузки
- **GIVEN** главная с меню, проектами и задачами
- **WHEN** пользователь открывает главную
- **THEN** браузер не запрашивает страницы, на которые ведут ссылки
#### Scenario: Прямой импорт next/link
- **GIVEN** файл веба импортирует `next/link` напрямую
- **WHEN** запускаются тесты
- **THEN** тест сообщает файл и просит импортировать `@/components/Link`

View File

@ -1,6 +1,6 @@
// PEP-169: what the Gitea server holds, as peppa-bot sees it — for the superadmin «Gitea» page.
import { projects, type Db } from "@peppa/db";
import type { GiteaRepo, GiteaUser } from "./gitea.ts";
import type { GiteaClient, GiteaRepo, GiteaUser } from "./gitea.ts";
import { giteaForBot } from "./users.ts";
export interface GiteaServerRepo {
@ -25,47 +25,109 @@ export interface GiteaServerOverview {
bot: { login: string; admin: boolean } | null;
repos: GiteaServerRepo[];
error: string | null;
/** When the shown list was loaded from Gitea (null — never). */
fetchedAt: Date | null;
}
type SearchRepo = GiteaRepo & { description?: string; archived?: boolean; fork?: boolean; updated_at?: string; size?: number };
const PAGE = 50;
const MAX_PAGES = 40;
/** Pages fetched at once after the first one (PEP-273: sequential pages took 2–6 s). */
const BATCH = 8;
/** A cached list younger than this is served as is. */
export const GITEA_OVERVIEW_FRESH_MS = 60_000;
/** A cached list younger than this is served at once and refreshed in the background. */
export const GITEA_OVERVIEW_STALE_MS = 10 * 60_000;
/** Repositories visible to peppa-bot (all of them when it is a site admin), newest first. */
export async function giteaServerOverview(db: Db): Promise<GiteaServerOverview> {
let client;
type Loaded = { url: string; bot: { login: string; admin: boolean }; repos: SearchRepo[] };
type Cache = { at: number; value: Loaded | null; loading: Promise<Loaded> | null };
const g = globalThis as unknown as { __peppaGiteaOverview?: Cache };
function cache(): Cache {
return (g.__peppaGiteaOverview ??= { at: 0, value: null, loading: null });
}
/** Tests: forget the cached list. */
export function resetGiteaOverviewCache(): void {
g.__peppaGiteaOverview = undefined;
}
async function load(client: GiteaClient): Promise<Loaded> {
const search = (page: number) => client.request<{ ok: boolean; data: SearchRepo[] }>("GET", `/repos/search?limit=${PAGE}&page=${page}&sort=updated&order=desc`).then((r) => r.data ?? []);
const [me, first] = await Promise.all([client.request<GiteaUser>("GET", "/user"), search(1)]);
const found: SearchRepo[] = [...first];
let full = first.length >= PAGE;
for (let from = 2; full && from <= MAX_PAGES; from += BATCH) {
const pages = await Promise.all(Array.from({ length: Math.min(BATCH, MAX_PAGES - from + 1) }, (_, i) => search(from + i)));
for (const data of pages) {
found.push(...data);
if (data.length < PAGE) {
full = false;
break;
}
}
}
// Pages fetched at once can overlap when a repository moves up mid-load.
const seen = new Set<string>();
const repos = found.filter((r) => !seen.has(r.full_name) && !!seen.add(r.full_name));
return { url: client.baseUrl, bot: { login: me.login, admin: !!me.is_admin }, repos };
}
function refresh(client: GiteaClient): Promise<Loaded> {
const c = cache();
c.loading ??= load(client)
.then((value) => {
c.value = value;
c.at = Date.now();
return value;
})
.finally(() => {
c.loading = null;
});
return c.loading;
}
/** Repositories visible to peppa-bot (all of them when it is a site admin), newest first.
* Cached in the process (PEP-273): fresh for a minute, a stale list is served at once and refreshed
* in the background; `fresh` waits for a new list. A failed load keeps the previous list. */
export async function giteaServerOverview(db: Db, opts: { fresh?: boolean; now?: number } = {}): Promise<GiteaServerOverview> {
let client: GiteaClient;
try {
client = giteaForBot();
} catch (e) {
return { url: "", bot: null, repos: [], error: (e as Error).message };
return { url: "", bot: null, repos: [], error: (e as Error).message, fetchedAt: null };
}
const linked = new Map((await db.select({ key: projects.key, name: projects.name, owner: projects.giteaOwner, repo: projects.giteaRepo }).from(projects)).map((p) => [`${p.owner}/${p.repo}`.toLowerCase(), { key: p.key, name: p.name }]));
try {
const me = await client.request<GiteaUser>("GET", "/user");
const found: SearchRepo[] = [];
for (let page = 1; page <= MAX_PAGES; page++) {
const res = await client.request<{ ok: boolean; data: SearchRepo[] }>("GET", `/repos/search?limit=${PAGE}&page=${page}&sort=updated&order=desc`);
found.push(...res.data);
if (res.data.length < PAGE) break;
const c = cache();
const age = (opts.now ?? Date.now()) - c.at;
let value = c.value;
let error: string | null = null;
if (value && !opts.fresh && age < GITEA_OVERVIEW_FRESH_MS) {
// fresh
} else if (value && !opts.fresh && age < GITEA_OVERVIEW_STALE_MS) {
refresh(client).catch(() => {});
} else {
try {
value = await refresh(client);
} catch (e) {
error = (e as Error).message;
}
const repos = found.map((r) => ({
fullName: r.full_name,
owner: r.owner.login,
name: r.name,
description: r.description ?? "",
private: r.private,
empty: r.empty,
archived: !!r.archived,
fork: !!r.fork,
defaultBranch: r.default_branch,
htmlUrl: r.html_url,
updatedAt: r.updated_at ? new Date(r.updated_at) : null,
sizeKb: r.size ?? 0,
project: linked.get(r.full_name.toLowerCase()) ?? null,
}));
return { url: client.baseUrl, bot: { login: me.login, admin: !!me.is_admin }, repos, error: null };
} catch (e) {
return { url: client.baseUrl, bot: null, repos: [], error: (e as Error).message };
}
if (!value) return { url: client.baseUrl, bot: null, repos: [], error, fetchedAt: null };
const repos = value.repos.map((r) => ({
fullName: r.full_name,
owner: r.owner.login,
name: r.name,
description: r.description ?? "",
private: r.private,
empty: r.empty,
archived: !!r.archived,
fork: !!r.fork,
defaultBranch: r.default_branch,
htmlUrl: r.html_url,
updatedAt: r.updated_at ? new Date(r.updated_at) : null,
sizeKb: r.size ?? 0,
project: linked.get(r.full_name.toLowerCase()) ?? null,
}));
return { url: value.url, bot: value.bot, repos, error, fetchedAt: new Date(c.at) };
}

View File

@ -205,6 +205,11 @@ export const admin: Dict = {
"подключённые к проектам": "linked to projects",
"без проекта": "without a project",
Показать: "Show",
"Список получен {when}": "Received {when}",
"Получить заново": "Fetch again",
"‹ Назад": "‹ Back",
"Страница {page} из {pages}": "Page {page} of {pages}",
"Дальше ›": "Next ›",
"Репозиториев не найдено.": "No repositories found.",
// Hosts

View File

@ -283,6 +283,11 @@ export const admin: Dict = {
"Поиск по имени или описанию": "Атауы немесе сипаттамасы бойынша іздеу",
"подключённые к проектам": "жобаларға қосылғандар",
"без проекта": "жобасыз",
"Список получен {when}": "Тізім алынды: {when}",
"Получить заново": "Қайта алу",
"‹ Назад": "‹ Артқа",
"Страница {page} из {pages}": "{pages} беттің {page}-беті",
"Дальше ›": "Келесі ›",
"Репозиториев не найдено.": "Репозиторий табылмады.",
"{key}: «Принять» ждёт дольше суток — задач: {n}": "{key}: «Қабылдау» бір тәуліктен астам күтіп тұр — тапсырмалар: {n}",
"{key}: агенты не запустятся — {warning}": "{key}: агенттер іске қосылмайды — {warning}",

View File

@ -83,6 +83,10 @@ export class MockGitea {
readonly runnerTokens: Array<{ scope: string; token: string }> = [];
/** PEP-4: old `owner/name` → current one, like Gitea's redirects after a transfer. */
readonly redirects = new Map<string, string>();
/** PEP-273: repositories only listed by `/repos/search` (no git behind them) — a big server. */
listOnlyRepos = 0;
/** PEP-273: how many `/repos/search` pages were asked for. */
searchRequests = 0;
private seq = 1;
private server: Server | null = null;
url = "";
@ -367,12 +371,34 @@ export class MockGitea {
let m: RegExpMatchArray | null;
if (method === "GET" && path === "/api/v1/user") return { status: 200, body: { id: me.id, login: me.login, full_name: me.login, email: `${me.login}@x`, avatar_url: "", is_admin: !!me.siteAdmin } };
if (method === "GET" && path === "/api/v1/repos/search") {
// PEP-280: like Gitea — public ones, own and collaborated ones; a site admin sees all. Paged.
const q = new URL(url, "http://x").searchParams;
const limit = Number(q.get("limit") ?? 30);
const page = Number(q.get("page") ?? 1);
// PEP-280: like Gitea — public ones, own and collaborated ones; a site admin sees all.
// PEP-273: counted, paged by 50 at most, with `listOnlyRepos` repositories that exist only in the list.
this.searchRequests++;
const q = new URLSearchParams(url.split("?")[1] ?? "");
const limit = Math.min(50, Number(q.get("limit") ?? 30));
const page = Math.max(1, Number(q.get("page") ?? 1));
const seen = [...this.repos.values()].filter((r) => me.siteAdmin || !r.private || r.owner === me.login || r.admins.has(me.login) || me.login in r.collaborators);
return { status: 200, body: { ok: true, data: seen.slice((page - 1) * limit, page * limit).map((r) => this.json(r, me)) } };
const all = [
...seen.map((r) => ({ ...this.json(r, me), description: "", archived: false, fork: false, updated_at: new Date().toISOString(), size: 12 })),
...Array.from({ length: this.listOnlyRepos }, (_, i) => ({
id: 100_000 + i,
name: `listed-${i}`,
full_name: `mock-org/listed-${i}`,
owner: { login: "mock-org" },
empty: false,
private: false,
default_branch: "main",
clone_url: "",
html_url: `${this.url}/mock-org/listed-${i}`,
permissions: { admin: false, push: false, pull: true },
description: `listed repository ${i}`,
archived: false,
fork: false,
updated_at: new Date(Date.UTC(2026, 0, 1) - i * 60_000).toISOString(),
size: 2048,
})),
];
return { status: 200, body: { ok: true, data: all.slice((page - 1) * limit, page * limit) } };
}
if (method === "GET" && path === "/api/v1/user/orgs") return { status: 200, body: (me.orgs ?? []).map((o, i) => ({ id: 1000 + i, username: o })) };
if (method === "GET" && (m = path.match(/^\/api\/v1\/users\/([^/]+)\/orgs\/([^/]+)\/permissions$/))) {

View File

@ -0,0 +1,75 @@
// PEP-273, spec web-speed «Страница Gitea отвечает быстро и компактно»: the repository list is
// cached in the process and its pages are fetched in parallel batches. Mock Gitea.
import assert from "node:assert/strict";
import { mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { after, before, beforeEach, describe, test } from "node:test";
import { core, db, teardown } from "./helpers.ts";
import { MockGitea } from "../src/mock-gitea.ts";
const gitea = new MockGitea(join(mkdtempSync(join(tmpdir(), "peppa-gitea-speed-")), "gitea"));
const BOT = { id: 72, login: "peppa-bot", token: "mock-token-bot-speed" };
before(async () => {
await gitea.start();
process.env.GITEA_URL = gitea.url;
process.env.GITEA_TOKEN = BOT.token;
gitea.addUser(BOT);
gitea.listOnlyRepos = 600;
});
after(async () => {
await gitea.stop();
await teardown();
});
beforeEach(() => {
core.resetGiteaOverviewCache();
gitea.down = false;
gitea.searchRequests = 0;
});
describe("Страница Gitea отвечает быстро и компактно", () => {
test("Большой сервер — весь список загружен пачками страниц", async () => {
const o = await core.giteaServerOverview(db);
assert.equal(o.error, null);
assert.equal(o.repos.length, 600);
assert.equal(new Set(o.repos.map((r) => r.fullName)).size, 600);
assert.equal(o.repos[0]!.fullName, "mock-org/listed-0");
assert.ok(o.fetchedAt);
// 600 / 50 = 12 full pages, then an empty 13th: page 1, a batch of 8, a batch of 4 (cut at the short page).
assert.ok(gitea.searchRequests <= 17, `search pages asked: ${gitea.searchRequests}`);
});
test("Повторное открытие не ходит в Gitea", async () => {
await core.giteaServerOverview(db);
const asked = gitea.searchRequests;
const again = await core.giteaServerOverview(db);
assert.equal(again.repos.length, 600);
assert.equal(gitea.searchRequests, asked);
});
test("Устаревший список отдаётся сразу и обновляется в фоне", async () => {
await core.giteaServerOverview(db);
const asked = gitea.searchRequests;
const stale = await core.giteaServerOverview(db, { now: Date.now() + core.GITEA_OVERVIEW_FRESH_MS + 1000 });
assert.equal(stale.repos.length, 600);
await new Promise((r) => setTimeout(r, 300));
assert.ok(gitea.searchRequests > asked, "background refresh asked Gitea again");
});
test("Gitea упала после удачной загрузки — прежний список и предупреждение", async () => {
await core.giteaServerOverview(db);
gitea.down = true;
const o = await core.giteaServerOverview(db, { fresh: true });
assert.equal(o.repos.length, 600);
assert.match(o.error ?? "", /500/);
});
test("Gitea не отвечает с самого начала — пустой список и ошибка", async () => {
gitea.down = true;
const o = await core.giteaServerOverview(db);
assert.equal(o.repos.length, 0);
assert.equal(o.fetchedAt, null);
assert.ok(o.error);
});
});

View File

@ -0,0 +1,35 @@
// PEP-273, spec web-speed «Ссылки не предзагружают страницы»: links of the console go through
// `@/components/Link` (prefetch off by default), never `next/link` directly.
import assert from "node:assert/strict";
import { readdirSync, readFileSync, statSync } from "node:fs";
import { join, relative } from "node:path";
import { describe, test } from "node:test";
const WEB = new URL("../../../apps/web/", import.meta.url).pathname;
const WRAPPER = "components/Link.tsx";
function files(dir: string, out: string[] = []): string[] {
for (const name of readdirSync(dir)) {
if (name === "node_modules" || name.startsWith(".")) continue;
const p = join(dir, name);
if (statSync(p).isDirectory()) files(p, out);
else if (/\.(tsx?|jsx?)$/.test(name)) out.push(p);
}
return out;
}
describe("Ссылки не предзагружают страницы", () => {
test("Прямой импорт next/link", () => {
const bad = ["app", "components", "lib"]
.flatMap((d) => files(join(WEB, d)))
.map((p) => relative(WEB, p))
.filter((p) => p !== WRAPPER && /from\s+["']next\/link["']/.test(readFileSync(join(WEB, p), "utf8")));
assert.deepEqual(bad, [], `import Link from "@/components/Link" instead of "next/link" in: ${bad.join(", ")}`);
});
test("Главная открывается без предзагрузки: обёртка выключает её по умолчанию", () => {
const src = readFileSync(join(WEB, WRAPPER), "utf8");
assert.match(src, /prefetch\s*=\s*false/);
assert.match(src, /prefetch=\{prefetch\}/);
});
});

View File

@ -142,7 +142,17 @@ describe("Зависший раннер перезапускается", () => {
return same;
});
const t0 = Date.now();
await tickAt(new Date(t0)); // remembers the screen
// Remember the screen once it has settled: on a busy machine the agent may still be drawing
// after a fixed pause, and a change seen by the next tick counts as activity (flaky in CI).
let seen: string | undefined;
await waitFor("screen settled", async () => {
await tickAt(new Date(t0));
const now = (await sess(sid)).watchState?.screen;
const same = !!now && now === seen;
seen = now;
if (!same) await new Promise((r) => setTimeout(r, 300));
return same;
});
await tickAt(new Date(t0 + 10 * MIN), 5 * MIN); // stalled → alert
const s = await sess(sid);
assert.equal(s.status, "stalled");