From 96fa6151ab5ef3356f375e07156ede11d35f0948 Mon Sep 17 00:00:00 2001 From: peppa-bot Date: Thu, 26 Nov 2026 20:31:56 +0000 Subject: [PATCH 1/4] =?UTF-8?q?PEP-273:=20/gitea=20=E2=80=94=20=D0=BA?= =?UTF-8?q?=D1=8D=D1=88=20=D1=81=D0=BF=D0=B8=D1=81=D0=BA=D0=B0,=20=D0=BF?= =?UTF-8?q?=D0=B0=D1=80=D0=B0=D0=BB=D0=BB=D0=B5=D0=BB=D1=8C=D0=BD=D1=8B?= =?UTF-8?q?=D0=B5=20=D1=81=D1=82=D1=80=D0=B0=D0=BD=D0=B8=D1=86=D1=8B,=2050?= =?UTF-8?q?=20=D1=81=D1=82=D1=80=D0=BE=D0=BA=20=D0=BD=D0=B0=20=D1=81=D1=82?= =?UTF-8?q?=D1=80=D0=B0=D0=BD=D0=B8=D1=86=D1=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- apps/web/app/(app)/gitea/page.tsx | 33 ++++- .../pep-273-fast-gitea-no-prefetch/design.md | 28 ++++ .../proposal.md | 23 ++++ .../specs/web-speed/spec.md | 36 ++++++ .../pep-273-fast-gitea-no-prefetch/tasks.md | 11 ++ packages/core/src/gitea-server.ts | 122 +++++++++++++----- packages/shared/src/i18n/en/admin.ts | 5 + packages/shared/src/i18n/kk/admin.ts | 5 + packages/testkit/src/mock-gitea.ts | 31 +++++ .../testkit/test/gitea-overview-speed.test.ts | 75 +++++++++++ 10 files changed, 336 insertions(+), 33 deletions(-) create mode 100644 openspec/changes/pep-273-fast-gitea-no-prefetch/design.md create mode 100644 openspec/changes/pep-273-fast-gitea-no-prefetch/proposal.md create mode 100644 openspec/changes/pep-273-fast-gitea-no-prefetch/specs/web-speed/spec.md create mode 100644 openspec/changes/pep-273-fast-gitea-no-prefetch/tasks.md create mode 100644 packages/testkit/test/gitea-overview-speed.test.ts diff --git a/apps/web/app/(app)/gitea/page.tsx b/apps/web/app/(app)/gitea/page.tsx index 6139dd7b..28467906 100644 --- a/apps/web/app/(app)/gitea/page.tsx +++ b/apps/web/app/(app)/gitea/page.tsx @@ -19,7 +19,10 @@ export async function generateMetadata() { return { title: t("Gitea — FORGE") }; } -type Params = { q?: string; show?: string }; +type Params = { q?: string; show?: string; page?: string; fresh?: string }; + +/** Rows per page (PEP-273: the whole list made the page over 1 MB). */ +const PAGE_SIZE = 50; function RepoRow({ r, t }: { r: GiteaServerRepo; t: Translator }) { return ( @@ -61,12 +64,23 @@ 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 = q.show === "linked" || q.show === "unlinked" ? q.show : "all"; const repos = o.repos.filter( (r) => (!needle || r.fullName.toLowerCase().includes(needle) || r.description.toLowerCase().includes(needle)) && (show === "all" || (show === "linked") === !!r.project), ); + 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) => { + 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(); 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; @@ -94,6 +108,12 @@ export default async function GiteaPage({ searchParams }: { searchParams: Promis {t("Бот")}: {o.bot?.login ?? "—"} {o.bot && (o.bot.admin ? {t("админ сервера — видит все репозитории")} : {t("не админ — видит публичные и свои репозитории")})} + {o.fetchedAt && ( +
+ {t("Список получен {when}", { when: ago(o.fetchedAt, t) })} ·{" "} + {t("Получить заново")} +
+ )} {o.repos.length > 0 && (
{t("Репозиториев: {n} · подключены к проектам: {linked}", { n: o.repos.length, linked })} ·{" "} @@ -122,12 +142,19 @@ export default async function GiteaPage({ searchParams }: { searchParams: Promis ) : (
    - {repos.map((r) => ( + {shown.map((r) => ( ))}
)} + {pages > 1 && ( + + )}
diff --git a/openspec/changes/pep-273-fast-gitea-no-prefetch/design.md b/openspec/changes/pep-273-fast-gitea-no-prefetch/design.md new file mode 100644 index 00000000..04074387 --- /dev/null +++ b/openspec/changes/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/pep-273-fast-gitea-no-prefetch/proposal.md b/openspec/changes/pep-273-fast-gitea-no-prefetch/proposal.md new file mode 100644 index 00000000..d538a4a5 --- /dev/null +++ b/openspec/changes/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/pep-273-fast-gitea-no-prefetch/specs/web-speed/spec.md b/openspec/changes/pep-273-fast-gitea-no-prefetch/specs/web-speed/spec.md new file mode 100644 index 00000000..99eda85d --- /dev/null +++ b/openspec/changes/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/pep-273-fast-gitea-no-prefetch/tasks.md b/openspec/changes/pep-273-fast-gitea-no-prefetch/tasks.md new file mode 100644 index 00000000..b90a65ce --- /dev/null +++ b/openspec/changes/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. Предзагрузка +- [ ] 2.1 `components/Link.tsx` и замена импортов `next/link` +- [ ] 2.2 Тест `no-prefetch.test.ts` + +## 3. Завершение +- [ ] 3.1 Проверки (lint, typecheck, тесты), память, archive, PR 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 2cc71140..5869e8a9 100644 --- a/packages/shared/src/i18n/en/admin.ts +++ b/packages/shared/src/i18n/en/admin.ts @@ -200,6 +200,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 8f83073c..7476dc50 100644 --- a/packages/shared/src/i18n/kk/admin.ts +++ b/packages/shared/src/i18n/kk/admin.ts @@ -278,6 +278,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 e50080a2..d42a65ac 100644 --- a/packages/testkit/src/mock-gitea.ts +++ b/packages/testkit/src/mock-gitea.ts @@ -81,6 +81,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 = ""; @@ -363,6 +367,33 @@ export class MockGitea { const me = this.users.get(auth.replace(/^token /, "")); if (!me) return { status: 401, body: { message: "unauthorized" } }; let m: RegExpMatchArray | null; + if (method === "GET" && path === "/api/v1/repos/search") { + this.searchRequests++; + const q = new URLSearchParams(url.split("?")[1] ?? ""); + const limit = Math.min(50, Number(q.get("limit") ?? 10)); + const page = Math.max(1, Number(q.get("page") ?? 1)); + const all = [ + ...[...this.repos.values()].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") return { status: 200, body: { id: me.id, login: me.login, full_name: me.login, email: `${me.login}@x`, avatar_url: "" } }; 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); + }); +}); -- 2.45.2 From f6ae77efe1592806cbedeb9da2bcd70530d48367 Mon Sep 17 00:00:00 2001 From: peppa-bot Date: Thu, 26 Nov 2026 20:34:02 +0000 Subject: [PATCH 2/4] =?UTF-8?q?PEP-273:=20=D1=81=D1=81=D1=8B=D0=BB=D0=BA?= =?UTF-8?q?=D0=B8=20=D0=B2=D0=B5=D0=B1=D0=B0=20=D0=B1=D0=B5=D0=B7=20=D0=BF?= =?UTF-8?q?=D1=80=D0=B5=D0=B4=D0=B7=D0=B0=D0=B3=D1=80=D1=83=D0=B7=D0=BA?= =?UTF-8?q?=D0=B8=20=E2=80=94=20=D0=BE=D0=B1=D1=91=D1=80=D1=82=D0=BA=D0=B0?= =?UTF-8?q?=20@/components/Link?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- apps/web/app/(app)/chats/[chat]/page.tsx | 2 +- apps/web/app/(app)/chats/page.tsx | 2 +- apps/web/app/(app)/connections/page.tsx | 2 +- apps/web/app/(app)/dashboard/delays/page.tsx | 2 +- apps/web/app/(app)/dashboard/page.tsx | 2 +- apps/web/app/(app)/errors/[id]/page.tsx | 2 +- apps/web/app/(app)/feedback/page.tsx | 2 +- apps/web/app/(app)/gitea/page.tsx | 2 +- apps/web/app/(app)/help/connect/page.tsx | 2 +- apps/web/app/(app)/help/page.tsx | 2 +- apps/web/app/(app)/help/shortcuts/page.tsx | 2 +- .../web/app/(app)/observability/[id]/page.tsx | 2 +- apps/web/app/(app)/observability/page.tsx | 2 +- apps/web/app/(app)/p/[key]/accept/page.tsx | 2 +- apps/web/app/(app)/p/[key]/page.tsx | 2 +- .../app/(app)/p/[key]/plan/[epic]/page.tsx | 2 +- apps/web/app/(app)/page.tsx | 2 +- apps/web/app/(app)/projects/page.tsx | 2 +- apps/web/app/(app)/runners/page.tsx | 2 +- apps/web/app/(app)/sessions/page.tsx | 2 +- apps/web/app/(app)/t/[key]/page.tsx | 2 +- apps/web/app/(app)/users/merge/page.tsx | 2 +- apps/web/app/(app)/users/page.tsx | 2 +- apps/web/app/(app)/welcome/page.tsx | 2 +- apps/web/components/Accounting.tsx | 2 +- apps/web/components/ActivityAside.tsx | 2 +- apps/web/components/AgentTaskSummary.tsx | 2 +- apps/web/components/Board.tsx | 2 +- apps/web/components/ChatThreadList.tsx | 2 +- apps/web/components/Errors.tsx | 2 +- apps/web/components/Feedback.tsx | 2 +- apps/web/components/FeedbackButton.tsx | 2 +- apps/web/components/Link.tsx | 9 +++++ apps/web/components/PlatformDelays.tsx | 2 +- apps/web/components/PoolSubscriptions.tsx | 2 +- apps/web/components/ProductCard.tsx | 2 +- apps/web/components/ProgressOverview.tsx | 2 +- apps/web/components/ProjectErrors.tsx | 2 +- apps/web/components/RunnerConsole.tsx | 2 +- apps/web/components/Sidebar.tsx | 2 +- apps/web/components/cards.tsx | 2 +- apps/web/components/common.tsx | 2 +- .../pep-273-fast-gitea-no-prefetch/tasks.md | 4 +-- packages/testkit/test/no-prefetch.test.ts | 35 +++++++++++++++++++ 44 files changed, 87 insertions(+), 43 deletions(-) create mode 100644 apps/web/components/Link.tsx create mode 100644 packages/testkit/test/no-prefetch.test.ts 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 4ec50ced..d2ea161e 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 7dbc1d93..74d4a491 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/page.tsx b/apps/web/app/(app)/gitea/page.tsx index 28467906..4ce0ab79 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"; 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 06f5e073..d7738010 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 af674e8b..70354870 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 } 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 f3d7271c..8b3d9cdd 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 95309001..bd8c7204 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 1103cf2d..626c25b4 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/pep-273-fast-gitea-no-prefetch/tasks.md b/openspec/changes/pep-273-fast-gitea-no-prefetch/tasks.md index b90a65ce..5b28f310 100644 --- a/openspec/changes/pep-273-fast-gitea-no-prefetch/tasks.md +++ b/openspec/changes/pep-273-fast-gitea-no-prefetch/tasks.md @@ -4,8 +4,8 @@ - [x] 1.3 Мок `/repos/search` и тест `gitea-overview-speed.test.ts` ## 2. Предзагрузка -- [ ] 2.1 `components/Link.tsx` и замена импортов `next/link` -- [ ] 2.2 Тест `no-prefetch.test.ts` +- [x] 2.1 `components/Link.tsx` и замена импортов `next/link` +- [x] 2.2 Тест `no-prefetch.test.ts` ## 3. Завершение - [ ] 3.1 Проверки (lint, typecheck, тесты), память, archive, PR 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\}/); + }); +}); -- 2.45.2 From fdc88d587c7eb352b65e3341c6b5c358dbf84a6e Mon Sep 17 00:00:00 2001 From: peppa-bot Date: Thu, 26 Nov 2026 20:34:48 +0000 Subject: [PATCH 3/4] =?UTF-8?q?PEP-273:=20=D0=B0=D1=80=D1=85=D0=B8=D0=B2?= =?UTF-8?q?=20change,=20=D0=BF=D0=B0=D0=BC=D1=8F=D1=82=D1=8C=20=D0=BF?= =?UTF-8?q?=D1=80=D0=BE=D0=B5=D0=BA=D1=82=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- .peppa/memory.md | 4 +- .../design.md | 0 .../proposal.md | 0 .../specs/web-speed/spec.md | 0 .../tasks.md | 2 +- openspec/specs/web-speed/spec.md | 41 +++++++++++++++++++ 6 files changed, 43 insertions(+), 4 deletions(-) rename openspec/changes/{pep-273-fast-gitea-no-prefetch => archive/2026-11-26-pep-273-fast-gitea-no-prefetch}/design.md (100%) rename openspec/changes/{pep-273-fast-gitea-no-prefetch => archive/2026-11-26-pep-273-fast-gitea-no-prefetch}/proposal.md (100%) rename openspec/changes/{pep-273-fast-gitea-no-prefetch => archive/2026-11-26-pep-273-fast-gitea-no-prefetch}/specs/web-speed/spec.md (100%) rename openspec/changes/{pep-273-fast-gitea-no-prefetch => archive/2026-11-26-pep-273-fast-gitea-no-prefetch}/tasks.md (88%) create mode 100644 openspec/specs/web-speed/spec.md diff --git a/.peppa/memory.md b/.peppa/memory.md index f8f59c81..c8036a6d 100644 --- a/.peppa/memory.md +++ b/.peppa/memory.md @@ -34,7 +34,6 @@ - `stopSession` закрывает все вопросы сессии, и карточку «готово» с «Принять» — освобождать место без неё: `releaseReviewSession` (PEP-299). - Состояние вачдога, которое пишет не вачдог (хук, launch), — только `markWatch` (json_set): `patchWatch` перезаписывает весь watch_state (PEP-265). - Песочница раннера: нет tmux и Node 26 — `node-v26…-linux-x64.tar.gz` (не .xz) в /tmp; tmux — .deb (tmux_3.3a-3, libevent-core-2.1-7, libutempter0) → `dpkg-deb -x` + LD_LIBRARY_PATH. Падают и на main (среда): glossary-check.test, sandbox-hosts.test.ts (нет ssh). -- Сервер (PEP-230): docs/SERVER.md. Docker-клиент образа 20.10 (PEP-287). - Пропал `.git/worktrees/s`: создать с `HEAD`, `commondir` `../..`, `gitdir`, затем `git reset`. - Версии CLI агентов (PEP-267) — только `scripts/runner-image.sh --try <версия>` (json + оба Dockerfile), откат `--rollback`. - Codex (PEP-241): доверие папке — по корню основного репо worktree; `-c` режет ключ по точкам — пишем в config.toml CODEX_HOME (`codex-trust.ts`). @@ -60,6 +59,7 @@ - act_runner (PEP-233/248): идут контейнеры `GITEA-ACTIONS-TASK-*` — не рестартовать; голова без ci.yml или >2 суток — `orphan`, не очередь; `not_taken` — pending, а другие проекты отчитываются. - Сбой платформы — `planPlatformRetry` (PEP-268), `restarts` не трогать; мок `hangAtStart`. - Конфликт PR с main (PEP-269) — только `conflictStep` (runner/conflict-step.ts), не `requestRebase` напрямую; сироты — `orphanConflictTick` (PEP-301). +- Ссылки веба — только `Link` из `@/components/Link` (предзагрузка выкл., PEP-273; тест no-prefetch); медленная страница из-за Gitea — кэш в globalThis, как `giteaServerOverview`. ## Решения - Access Hub (PEP-254): журнал — только `appendJournal` (core/connection-journal.ts, цепочка хэшей; правка строки задним числом = нарушение), ключ подключения — `sealConnectionSecret`/`openConnectionSecret`, не `encrypt`/`decrypt`. @@ -71,6 +71,4 @@ - Сообщения людям — только через `telegram_outbox`/`push_outbox`: ночная тишина 23–08 (PEP-208) стоит на их выборке; тестам и стенду `PEPPA_NIGHT_QUIET=off`. - `template/` уходит в Gitea сам с выкаткой (PEP-242); старым проектам — `peppa ci connect [--secrets-only]`. - Живой сайт (с PEP-230 — сервер, контейнеры) — только `scripts/platform-deploy.sh` из `~/peppa/src` на main (docs/SERVER.md); launchd/live-deploy.sh — только откат на Mac. -- Речь — свой faster-whisper (``). Google: по почте учётки не склеиваем. - Секреты (PEP-253): агенту — `agent_env` при `project.agent-secrets` (нет строки = вкл.); в тестах — `{ agent: true }`. -- Привязка Google к чужой Google-only учётке — `mergeUserInto`; с eGov/Gitea — отказ (PEP-195). diff --git a/openspec/changes/pep-273-fast-gitea-no-prefetch/design.md b/openspec/changes/archive/2026-11-26-pep-273-fast-gitea-no-prefetch/design.md similarity index 100% rename from openspec/changes/pep-273-fast-gitea-no-prefetch/design.md rename to openspec/changes/archive/2026-11-26-pep-273-fast-gitea-no-prefetch/design.md diff --git a/openspec/changes/pep-273-fast-gitea-no-prefetch/proposal.md b/openspec/changes/archive/2026-11-26-pep-273-fast-gitea-no-prefetch/proposal.md similarity index 100% rename from openspec/changes/pep-273-fast-gitea-no-prefetch/proposal.md rename to openspec/changes/archive/2026-11-26-pep-273-fast-gitea-no-prefetch/proposal.md diff --git a/openspec/changes/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 similarity index 100% rename from openspec/changes/pep-273-fast-gitea-no-prefetch/specs/web-speed/spec.md rename to openspec/changes/archive/2026-11-26-pep-273-fast-gitea-no-prefetch/specs/web-speed/spec.md diff --git a/openspec/changes/pep-273-fast-gitea-no-prefetch/tasks.md b/openspec/changes/archive/2026-11-26-pep-273-fast-gitea-no-prefetch/tasks.md similarity index 88% rename from openspec/changes/pep-273-fast-gitea-no-prefetch/tasks.md rename to openspec/changes/archive/2026-11-26-pep-273-fast-gitea-no-prefetch/tasks.md index 5b28f310..f8ca9991 100644 --- a/openspec/changes/pep-273-fast-gitea-no-prefetch/tasks.md +++ b/openspec/changes/archive/2026-11-26-pep-273-fast-gitea-no-prefetch/tasks.md @@ -8,4 +8,4 @@ - [x] 2.2 Тест `no-prefetch.test.ts` ## 3. Завершение -- [ ] 3.1 Проверки (lint, typecheck, тесты), память, archive, PR +- [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` -- 2.45.2 From d743b38f31b4f948a20412e1b348a3d31e56d83d Mon Sep 17 00:00:00 2001 From: peppa-bot Date: Thu, 26 Nov 2026 21:12:37 +0000 Subject: [PATCH 4/4] =?UTF-8?q?PEP-273:=20=D1=82=D0=B5=D1=81=D1=82=20?= =?UTF-8?q?=D0=B7=D0=B0=D0=B2=D0=B8=D1=81=D1=88=D0=B5=D0=B3=D0=BE=20=D1=80?= =?UTF-8?q?=D0=B0=D0=BD=D0=BD=D0=B5=D1=80=D0=B0=20=D0=B6=D0=B4=D1=91=D1=82?= =?UTF-8?q?,=20=D0=BF=D0=BE=D0=BA=D0=B0=20=D1=8D=D0=BA=D1=80=D0=B0=D0=BD?= =?UTF-8?q?=20=D1=83=D1=81=D0=BF=D0=BE=D0=BA=D0=BE=D0=B8=D1=82=D1=81=D1=8F?= =?UTF-8?q?=20(=D0=BD=D0=B5=D1=81=D1=82=D0=B0=D0=B1=D0=B8=D0=BB=D0=B5?= =?UTF-8?q?=D0=BD=20=D0=B2=20CI)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- packages/testkit/test/recovery.test.ts | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/packages/testkit/test/recovery.test.ts b/packages/testkit/test/recovery.test.ts index a9b3e1e9..5f40ce87 100644 --- a/packages/testkit/test/recovery.test.ts +++ b/packages/testkit/test/recovery.test.ts @@ -131,7 +131,17 @@ describe("Зависший раннер перезапускается", () => { await p.waitLog("turn 0", (e) => e.ev === "prompt"); await new Promise((r) => setTimeout(r, 1500)); 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"); -- 2.45.2