diff --git a/.peppa/memory/pep-273.md b/.peppa/memory/pep-273.md
new file mode 100644
index 00000000..942d3857
--- /dev/null
+++ b/.peppa/memory/pep-273.md
@@ -0,0 +1,4 @@
+# Память: PEP-273
+
+## Соглашения
+- Ссылки веба — только `Link` из `@/components/Link` (предзагрузка выкл., PEP-273; тест no-prefetch); медленная страница из-за Gitea — кэш в globalThis, как `giteaServerOverview`.
diff --git a/apps/web/app/(app)/chats/[chat]/page.tsx b/apps/web/app/(app)/chats/[chat]/page.tsx
index c867f609..a58cc650 100644
--- a/apps/web/app/(app)/chats/[chat]/page.tsx
+++ b/apps/web/app/(app)/chats/[chat]/page.tsx
@@ -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";
diff --git a/apps/web/app/(app)/chats/page.tsx b/apps/web/app/(app)/chats/page.tsx
index e883b82b..169bf6fd 100644
--- a/apps/web/app/(app)/chats/page.tsx
+++ b/apps/web/app/(app)/chats/page.tsx
@@ -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";
diff --git a/apps/web/app/(app)/connections/page.tsx b/apps/web/app/(app)/connections/page.tsx
index 1877e48b..aef065cc 100644
--- a/apps/web/app/(app)/connections/page.tsx
+++ b/apps/web/app/(app)/connections/page.tsx
@@ -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,
diff --git a/apps/web/app/(app)/dashboard/delays/page.tsx b/apps/web/app/(app)/dashboard/delays/page.tsx
index da5ff69e..d43f136f 100644
--- a/apps/web/app/(app)/dashboard/delays/page.tsx
+++ b/apps/web/app/(app)/dashboard/delays/page.tsx
@@ -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";
diff --git a/apps/web/app/(app)/dashboard/page.tsx b/apps/web/app/(app)/dashboard/page.tsx
index dc71f727..30bd25d2 100644
--- a/apps/web/app/(app)/dashboard/page.tsx
+++ b/apps/web/app/(app)/dashboard/page.tsx
@@ -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";
diff --git a/apps/web/app/(app)/errors/[id]/page.tsx b/apps/web/app/(app)/errors/[id]/page.tsx
index f90a055f..f9e50f84 100644
--- a/apps/web/app/(app)/errors/[id]/page.tsx
+++ b/apps/web/app/(app)/errors/[id]/page.tsx
@@ -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";
diff --git a/apps/web/app/(app)/feedback/page.tsx b/apps/web/app/(app)/feedback/page.tsx
index 878a9409..bfb7aefa 100644
--- a/apps/web/app/(app)/feedback/page.tsx
+++ b/apps/web/app/(app)/feedback/page.tsx
@@ -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";
diff --git a/apps/web/app/(app)/gitea/actions.ts b/apps/web/app/(app)/gitea/actions.ts
index 5e2de2e5..671223ae 100644
--- a/apps/web/app/(app)/gitea/actions.ts
+++ b/apps/web/app/(app)/gitea/actions.ts
@@ -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 });
diff --git a/apps/web/app/(app)/gitea/page.tsx b/apps/web/app/(app)/gitea/page.tsx
index fb310622..4d32a92d 100644
--- a/apps/web/app/(app)/gitea/page.tsx
+++ b/apps/web/app/(app)/gitea/page.tsx
@@ -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 (
diff --git a/apps/web/app/(app)/help/connect/page.tsx b/apps/web/app/(app)/help/connect/page.tsx
index 6e036997..9da0c884 100644
--- a/apps/web/app/(app)/help/connect/page.tsx
+++ b/apps/web/app/(app)/help/connect/page.tsx
@@ -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";
diff --git a/apps/web/app/(app)/help/page.tsx b/apps/web/app/(app)/help/page.tsx
index cdb38b72..8777bec5 100644
--- a/apps/web/app/(app)/help/page.tsx
+++ b/apps/web/app/(app)/help/page.tsx
@@ -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";
diff --git a/apps/web/app/(app)/help/shortcuts/page.tsx b/apps/web/app/(app)/help/shortcuts/page.tsx
index 59b23e77..465ebfd8 100644
--- a/apps/web/app/(app)/help/shortcuts/page.tsx
+++ b/apps/web/app/(app)/help/shortcuts/page.tsx
@@ -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";
diff --git a/apps/web/app/(app)/observability/[id]/page.tsx b/apps/web/app/(app)/observability/[id]/page.tsx
index c0f70dfd..14475975 100644
--- a/apps/web/app/(app)/observability/[id]/page.tsx
+++ b/apps/web/app/(app)/observability/[id]/page.tsx
@@ -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";
diff --git a/apps/web/app/(app)/observability/page.tsx b/apps/web/app/(app)/observability/page.tsx
index 8766cad4..1e582802 100644
--- a/apps/web/app/(app)/observability/page.tsx
+++ b/apps/web/app/(app)/observability/page.tsx
@@ -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";
diff --git a/apps/web/app/(app)/p/[key]/accept/page.tsx b/apps/web/app/(app)/p/[key]/accept/page.tsx
index 287ba02a..9843ee62 100644
--- a/apps/web/app/(app)/p/[key]/accept/page.tsx
+++ b/apps/web/app/(app)/p/[key]/accept/page.tsx
@@ -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";
diff --git a/apps/web/app/(app)/p/[key]/page.tsx b/apps/web/app/(app)/p/[key]/page.tsx
index 75d7bbff..5f31b7e4 100644
--- a/apps/web/app/(app)/p/[key]/page.tsx
+++ b/apps/web/app/(app)/p/[key]/page.tsx
@@ -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";
diff --git a/apps/web/app/(app)/p/[key]/plan/[epic]/page.tsx b/apps/web/app/(app)/p/[key]/plan/[epic]/page.tsx
index c67f6864..06e41495 100644
--- a/apps/web/app/(app)/p/[key]/plan/[epic]/page.tsx
+++ b/apps/web/app/(app)/p/[key]/plan/[epic]/page.tsx
@@ -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";
diff --git a/apps/web/app/(app)/page.tsx b/apps/web/app/(app)/page.tsx
index 66014d4d..9898c115 100644
--- a/apps/web/app/(app)/page.tsx
+++ b/apps/web/app/(app)/page.tsx
@@ -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";
diff --git a/apps/web/app/(app)/projects/page.tsx b/apps/web/app/(app)/projects/page.tsx
index bdf0f2d2..375301fa 100644
--- a/apps/web/app/(app)/projects/page.tsx
+++ b/apps/web/app/(app)/projects/page.tsx
@@ -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";
diff --git a/apps/web/app/(app)/runners/page.tsx b/apps/web/app/(app)/runners/page.tsx
index 8037e427..53e4fd19 100644
--- a/apps/web/app/(app)/runners/page.tsx
+++ b/apps/web/app/(app)/runners/page.tsx
@@ -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";
diff --git a/apps/web/app/(app)/sessions/page.tsx b/apps/web/app/(app)/sessions/page.tsx
index 1a5a0477..ac73cfda 100644
--- a/apps/web/app/(app)/sessions/page.tsx
+++ b/apps/web/app/(app)/sessions/page.tsx
@@ -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";
diff --git a/apps/web/app/(app)/t/[key]/page.tsx b/apps/web/app/(app)/t/[key]/page.tsx
index 801cc34f..13b5d8a8 100644
--- a/apps/web/app/(app)/t/[key]/page.tsx
+++ b/apps/web/app/(app)/t/[key]/page.tsx
@@ -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 {
diff --git a/apps/web/app/(app)/users/merge/page.tsx b/apps/web/app/(app)/users/merge/page.tsx
index 83cb77ba..82b14cfa 100644
--- a/apps/web/app/(app)/users/merge/page.tsx
+++ b/apps/web/app/(app)/users/merge/page.tsx
@@ -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";
diff --git a/apps/web/app/(app)/users/page.tsx b/apps/web/app/(app)/users/page.tsx
index 3f682e28..f4ead79f 100644
--- a/apps/web/app/(app)/users/page.tsx
+++ b/apps/web/app/(app)/users/page.tsx
@@ -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";
diff --git a/apps/web/app/(app)/welcome/page.tsx b/apps/web/app/(app)/welcome/page.tsx
index 30a750e3..80ac618e 100644
--- a/apps/web/app/(app)/welcome/page.tsx
+++ b/apps/web/app/(app)/welcome/page.tsx
@@ -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";
diff --git a/apps/web/components/Accounting.tsx b/apps/web/components/Accounting.tsx
index 7cd8d9d9..1331895b 100644
--- a/apps/web/components/Accounting.tsx
+++ b/apps/web/components/Accounting.tsx
@@ -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 {
diff --git a/apps/web/components/ActivityAside.tsx b/apps/web/components/ActivityAside.tsx
index 657e3ab1..43857107 100644
--- a/apps/web/components/ActivityAside.tsx
+++ b/apps/web/components/ActivityAside.tsx
@@ -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";
diff --git a/apps/web/components/AgentTaskSummary.tsx b/apps/web/components/AgentTaskSummary.tsx
index 73792f14..7d54fb05 100644
--- a/apps/web/components/AgentTaskSummary.tsx
+++ b/apps/web/components/AgentTaskSummary.tsx
@@ -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";
diff --git a/apps/web/components/Board.tsx b/apps/web/components/Board.tsx
index ff6a30b8..da367b50 100644
--- a/apps/web/components/Board.tsx
+++ b/apps/web/components/Board.tsx
@@ -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";
diff --git a/apps/web/components/ChatThreadList.tsx b/apps/web/components/ChatThreadList.tsx
index 8be9dfb6..e9b03e91 100644
--- a/apps/web/components/ChatThreadList.tsx
+++ b/apps/web/components/ChatThreadList.tsx
@@ -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";
diff --git a/apps/web/components/Errors.tsx b/apps/web/components/Errors.tsx
index 1dea4af3..72b33a71 100644
--- a/apps/web/components/Errors.tsx
+++ b/apps/web/components/Errors.tsx
@@ -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";
diff --git a/apps/web/components/Feedback.tsx b/apps/web/components/Feedback.tsx
index 17311b22..16ff1330 100644
--- a/apps/web/components/Feedback.tsx
+++ b/apps/web/components/Feedback.tsx
@@ -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";
diff --git a/apps/web/components/FeedbackButton.tsx b/apps/web/components/FeedbackButton.tsx
index 5dd00c27..df275f31 100644
--- a/apps/web/components/FeedbackButton.tsx
+++ b/apps/web/components/FeedbackButton.tsx
@@ -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";
diff --git a/apps/web/components/Link.tsx b/apps/web/components/Link.tsx
new file mode 100644
index 00000000..98ab4900
--- /dev/null
+++ b/apps/web/components/Link.tsx
@@ -0,0 +1,9 @@
+// PEP-273: every link of the console goes through here. Next prefetches each visible 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) {
+ return ;
+}
diff --git a/apps/web/components/PlatformDelays.tsx b/apps/web/components/PlatformDelays.tsx
index de076cec..7235aef8 100644
--- a/apps/web/components/PlatformDelays.tsx
+++ b/apps/web/components/PlatformDelays.tsx
@@ -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";
diff --git a/apps/web/components/PoolSubscriptions.tsx b/apps/web/components/PoolSubscriptions.tsx
index 3ae6723d..0a7dcafd 100644
--- a/apps/web/components/PoolSubscriptions.tsx
+++ b/apps/web/components/PoolSubscriptions.tsx
@@ -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";
diff --git a/apps/web/components/ProductCard.tsx b/apps/web/components/ProductCard.tsx
index 05729726..70e466e0 100644
--- a/apps/web/components/ProductCard.tsx
+++ b/apps/web/components/ProductCard.tsx
@@ -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";
diff --git a/apps/web/components/ProgressOverview.tsx b/apps/web/components/ProgressOverview.tsx
index 3110dea5..0cd99195 100644
--- a/apps/web/components/ProgressOverview.tsx
+++ b/apps/web/components/ProgressOverview.tsx
@@ -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";
diff --git a/apps/web/components/ProjectErrors.tsx b/apps/web/components/ProjectErrors.tsx
index 154b8791..b2666d1e 100644
--- a/apps/web/components/ProjectErrors.tsx
+++ b/apps/web/components/ProjectErrors.tsx
@@ -1,6 +1,6 @@
// PEP-218: the project's tab «Баги» — errors of its own Bugsink projects (`-web` /
// `-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";
diff --git a/apps/web/components/RunnerConsole.tsx b/apps/web/components/RunnerConsole.tsx
index 780ba020..273f37f0 100644
--- a/apps/web/components/RunnerConsole.tsx
+++ b/apps/web/components/RunnerConsole.tsx
@@ -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";
diff --git a/apps/web/components/Sidebar.tsx b/apps/web/components/Sidebar.tsx
index 78d5d340..a8a259f6 100644
--- a/apps/web/components/Sidebar.tsx
+++ b/apps/web/components/Sidebar.tsx
@@ -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";
diff --git a/apps/web/components/cards.tsx b/apps/web/components/cards.tsx
index 2c8ab1b7..5f65a77e 100644
--- a/apps/web/components/cards.tsx
+++ b/apps/web/components/cards.tsx
@@ -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";
diff --git a/apps/web/components/common.tsx b/apps/web/components/common.tsx
index 163aae8c..fea4fa6f 100644
--- a/apps/web/components/common.tsx
+++ b/apps/web/components/common.tsx
@@ -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";
diff --git a/openspec/changes/archive/2026-11-26-pep-273-fast-gitea-no-prefetch/design.md b/openspec/changes/archive/2026-11-26-pep-273-fast-gitea-no-prefetch/design.md
new file mode 100644
index 00000000..04074387
--- /dev/null
+++ b/openspec/changes/archive/2026-11-26-pep-273-fast-gitea-no-prefetch/design.md
@@ -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 в рабочей сборке предзагружает каждую видимую ``; на главной их ~40 (меню, проекты,
+задачи, вопросы). Глобального выключателя в `next.config` нет, поэтому — своя обёртка
+`components/Link.tsx` (`prefetch` по умолчанию `false`, остальное — как у `next/link`) и замена
+импорта во всех файлах. Тест `no-prefetch.test.ts` не даёт вернуть прямой импорт `next/link` в
+`apps/web/app|components|lib`. Цена — переход открывается без заранее полученной страницы; страницы у нас
+динамические и всё равно рисуются заново, а живые обновления идут по WebSocket.
diff --git a/openspec/changes/archive/2026-11-26-pep-273-fast-gitea-no-prefetch/proposal.md b/openspec/changes/archive/2026-11-26-pep-273-fast-gitea-no-prefetch/proposal.md
new file mode 100644
index 00000000..d538a4a5
--- /dev/null
+++ b/openspec/changes/archive/2026-11-26-pep-273-fast-gitea-no-prefetch/proposal.md
@@ -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.
diff --git a/openspec/changes/archive/2026-11-26-pep-273-fast-gitea-no-prefetch/specs/web-speed/spec.md b/openspec/changes/archive/2026-11-26-pep-273-fast-gitea-no-prefetch/specs/web-speed/spec.md
new file mode 100644
index 00000000..99eda85d
--- /dev/null
+++ b/openspec/changes/archive/2026-11-26-pep-273-fast-gitea-no-prefetch/specs/web-speed/spec.md
@@ -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`
diff --git a/openspec/changes/archive/2026-11-26-pep-273-fast-gitea-no-prefetch/tasks.md b/openspec/changes/archive/2026-11-26-pep-273-fast-gitea-no-prefetch/tasks.md
new file mode 100644
index 00000000..f8ca9991
--- /dev/null
+++ b/openspec/changes/archive/2026-11-26-pep-273-fast-gitea-no-prefetch/tasks.md
@@ -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
diff --git a/openspec/specs/web-speed/spec.md b/openspec/specs/web-speed/spec.md
new file mode 100644
index 00000000..065eabb9
--- /dev/null
+++ b/openspec/specs/web-speed/spec.md
@@ -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`
diff --git a/packages/core/src/gitea-server.ts b/packages/core/src/gitea-server.ts
index 784f40b7..da2f56ff 100644
--- a/packages/core/src/gitea-server.ts
+++ b/packages/core/src/gitea-server.ts
@@ -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 {
- let client;
+type Loaded = { url: string; bot: { login: string; admin: boolean }; repos: SearchRepo[] };
+type Cache = { at: number; value: Loaded | null; loading: Promise | 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 {
+ 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("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();
+ 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 {
+ 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 {
+ 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("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) };
}
diff --git a/packages/shared/src/i18n/en/admin.ts b/packages/shared/src/i18n/en/admin.ts
index ba1e5dcd..e218166f 100644
--- a/packages/shared/src/i18n/en/admin.ts
+++ b/packages/shared/src/i18n/en/admin.ts
@@ -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
diff --git a/packages/shared/src/i18n/kk/admin.ts b/packages/shared/src/i18n/kk/admin.ts
index 35eadd69..bdd820c7 100644
--- a/packages/shared/src/i18n/kk/admin.ts
+++ b/packages/shared/src/i18n/kk/admin.ts
@@ -283,6 +283,11 @@ export const admin: Dict = {
"Поиск по имени или описанию": "Атауы немесе сипаттамасы бойынша іздеу",
"подключённые к проектам": "жобаларға қосылғандар",
"без проекта": "жобасыз",
+ "Список получен {when}": "Тізім алынды: {when}",
+ "Получить заново": "Қайта алу",
+ "‹ Назад": "‹ Артқа",
+ "Страница {page} из {pages}": "{pages} беттің {page}-беті",
+ "Дальше ›": "Келесі ›",
"Репозиториев не найдено.": "Репозиторий табылмады.",
"{key}: «Принять» ждёт дольше суток — задач: {n}": "{key}: «Қабылдау» бір тәуліктен астам күтіп тұр — тапсырмалар: {n}",
"{key}: агенты не запустятся — {warning}": "{key}: агенттер іске қосылмайды — {warning}",
diff --git a/packages/testkit/src/mock-gitea.ts b/packages/testkit/src/mock-gitea.ts
index caf638d1..9820db1c 100644
--- a/packages/testkit/src/mock-gitea.ts
+++ b/packages/testkit/src/mock-gitea.ts
@@ -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();
+ /** 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$/))) {
diff --git a/packages/testkit/test/gitea-overview-speed.test.ts b/packages/testkit/test/gitea-overview-speed.test.ts
new file mode 100644
index 00000000..29375185
--- /dev/null
+++ b/packages/testkit/test/gitea-overview-speed.test.ts
@@ -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);
+ });
+});
diff --git a/packages/testkit/test/no-prefetch.test.ts b/packages/testkit/test/no-prefetch.test.ts
new file mode 100644
index 00000000..78ba88a8
--- /dev/null
+++ b/packages/testkit/test/no-prefetch.test.ts
@@ -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\}/);
+ });
+});
diff --git a/packages/testkit/test/recovery.test.ts b/packages/testkit/test/recovery.test.ts
index 570fa97a..abefe50a 100644
--- a/packages/testkit/test/recovery.test.ts
+++ b/packages/testkit/test/recovery.test.ts
@@ -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");