Merge pull request 'PEP-274: «Готовим ссылку» со сроком, поле чата на телефоне, свои заголовки вкладок' (#283) from task/pep-274 into main

Заход приёмки 27.11: двадцать задач одним заходом, проверки сервера — на итоговом коммите. [skip ci]
This commit is contained in:
peppa-bot 2026-11-27 05:30:47 +00:00
commit ad6dd0a178
46 changed files with 648 additions and 35 deletions

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

@ -0,0 +1,4 @@
# Память: PEP-274
## Решения
- Заголовок вкладки (PEP-274) — `pageTitle`/`projectTitle`/`taskTitle` (apps/web/lib/title.ts); page.tsx без `generateMetadata` роняет page-titles.test.ts.

View File

@ -21,12 +21,13 @@ import { AttachField } from "@/components/AttachField";
import { Workspace } from "@/components/Workspace";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/input";
import { requireUser, words } from "@/lib/auth";
import { currentUser, requireUser, words } from "@/lib/auth";
import { db } from "@/lib/db";
import { getT } from "@/lib/i18n";
import { cn } from "@/lib/utils";
import { cleanText, messageLink, STUCK_NOTICE } from "@/lib/chat-text";
import { chatOfferAction, linkChatAction, postChatAction, unlinkChatAction } from "../actions";
import { pageTitle } from "@/lib/title";
type Params = { error?: string; thread?: string; link?: string; q?: string; list?: string };
@ -34,6 +35,16 @@ const CHANNEL = "channel";
/** PEP-106: `?thread=feed` — the agents' events; no `thread` — the people's discussion. */
const FEED = "feed";
// PEP-274: «Чат KEY — FORGE» (the chat list of the viewer — no names of chats they cannot see).
export async function generateMetadata({ params }: { params: Promise<{ chat: string }> }) {
const t = await getT();
const user = await currentUser();
const slug = (await params).chat;
const chat = user ? (await listChats(db, user)).find((c) => c.slug.toLowerCase() === slug.toLowerCase()) : null;
if (!chat) return pageTitle(t, t("Чаты"));
return pageTitle(t, chat.kind === "master" ? t("Все события") : t("Чат {key}", { key: chat.slug.toUpperCase() }));
}
/** «Чаты» (PEP-62): the master chat and project chats with threads; a linked Telegram group mirrors them. */
export default async function ChatPage({ params, searchParams }: { params: Promise<{ chat: string }>; searchParams: Promise<Params> }) {
const user = await requireUser();
@ -338,11 +349,12 @@ export default async function ChatPage({ params, searchParams }: { params: Promi
{writable && (
<form action={postChatAction} data-chat-composer className="sticky bottom-[calc(4rem+env(safe-area-inset-bottom))] z-20 -mx-1 flex flex-col gap-1 rounded-lg border bg-card p-2 shadow-md md:bottom-3">
<Hidden fields={{ chatId: chat.id, thread: thread ?? "", back: here }} />
<div className="flex items-end gap-1.5">
<Textarea id="chat-text" name="text" rows={1} maxLength={60000} placeholder={placeholder} aria-label={t("Сообщение")} className="max-h-40 min-h-9 flex-1 resize-y py-1.5" />
{chat.projectId && <AttachField projectId={chat.projectId} target="chat-text" className="shrink-0" />}
<Dictate target="chat-text" compact />
<Button size="sm" aria-label={t("Отправить")} title={t("Отправить")} className="h-9">
{/* PEP-274 (F-12): on a phone the field takes the whole row (the hint is not cut), the buttons go below, each ≥ 44 px. */}
<div className="flex flex-wrap items-end gap-1.5 md:flex-nowrap">
<Textarea id="chat-text" name="text" rows={1} maxLength={60000} placeholder={placeholder} aria-label={t("Сообщение")} className="max-h-40 min-h-[4.25rem] flex-1 basis-full resize-y py-1.5 [field-sizing:content] md:min-h-9 md:basis-0" data-chat-text />
{chat.projectId && <AttachField projectId={chat.projectId} target="chat-text" className="shrink-0" touch />}
<Dictate target="chat-text" compact touch />
<Button size="sm" aria-label={t("Отправить")} title={t("Отправить")} className="ml-auto size-11 md:ml-0 md:h-9 md:w-auto" data-chat-send>
<Send />
</Button>
</div>

View File

@ -7,11 +7,14 @@ import { requireUser } from "@/lib/auth";
import { db } from "@/lib/db";
import { getT } from "@/lib/i18n";
import { cn } from "@/lib/utils";
import { pageTitle } from "@/lib/title";
// PEP-274: the browser tab says which page it is.
export async function generateMetadata() {
const t = await getT();
return pageTitle(t, t("Обращения"));
}
/**
* PEP-143: «Обращения». Everybody sees their own reports and where they stand; the superadmin
* also sees everybody's, filtered by status, and decides on them.
*/
export default async function FeedbackPage({ searchParams }: { searchParams: Promise<{ error?: string; status?: string; id?: string }> }) {
const user = await requireUser();
const t = await getT();
@ -50,3 +53,8 @@ export default async function FeedbackPage({ searchParams }: { searchParams: Pro
</Workspace>
);
}
/**
* PEP-143: «Обращения». Everybody sees their own reports and where they stand; the superadmin
* also sees everybody's, filtered by status, and decides on them.
*/

View File

@ -7,8 +7,14 @@ import { CopyText } from "@/components/CopyText";
import { Workspace } from "@/components/Workspace";
import { publicOrigin } from "@/lib/auth";
import { getLocale, getT } from "@/lib/i18n";
import { pageTitle } from "@/lib/title";
// PEP-274: the browser tab says which page it is.
export async function generateMetadata() {
const t = await getT();
return pageTitle(t, (CONNECT_HELP[t.locale] ?? CONNECT_HELP.ru).title);
}
/** PEP-135: how to connect FORGE to one's own Claude or ChatGPT — step by step; texts live in core/connect-texts.ts. */
export default async function ConnectHelp() {
const t = CONNECT_HELP[await getLocale()] ?? CONNECT_HELP.ru;
const address = `${await publicOrigin()}/mcp`;
@ -72,3 +78,5 @@ export default async function ConnectHelp() {
</Workspace>
);
}
/** PEP-135: how to connect FORGE to one's own Claude or ChatGPT — step by step; texts live in core/connect-texts.ts. */

View File

@ -9,6 +9,7 @@ import { publicOrigin, uiMode } from "@/lib/auth";
import { Workspace } from "@/components/Workspace";
import { voiceStoriesEnabled } from "@peppa/shared";
import { PageHeader, Section } from "@/components/common";
import { pageTitle } from "@/lib/title";
const TOOLS: Array<[string, string]> = [
["get_started", m("правила работы для ИИ-клиента: вызывается первым, коротко и без кода")],
@ -140,6 +141,12 @@ async function ProductHelp() {
);
}
// PEP-274: the browser tab says which page it is.
export async function generateMetadata() {
const t = await getT();
return pageTitle(t, t("Помощь"));
}
export default async function Help() {
if ((await uiMode()) === "product") return <ProductHelp />;
const t = await getT();

View File

@ -4,8 +4,14 @@ import { PageHeader, Section } from "@/components/common";
import { Workspace } from "@/components/Workspace";
import { PALETTE_KEYS } from "@/lib/shortcuts";
import { getT } from "@/lib/i18n";
import { pageTitle } from "@/lib/title";
// PEP-274: the browser tab says which page it is.
export async function generateMetadata() {
const t = await getT();
return pageTitle(t, t("Горячие клавиши"));
}
/** PEP-52: list of keyboard shortcuts (the same list as the «?» dialog). */
export default async function Shortcuts() {
const t = await getT();
return (
@ -26,3 +32,5 @@ export default async function Shortcuts() {
</Workspace>
);
}
/** PEP-52: list of keyboard shortcuts (the same list as the «?» dialog). */

View File

@ -6,8 +6,14 @@ import { Workspace } from "@/components/Workspace";
import { requireUser } from "@/lib/auth";
import { db } from "@/lib/db";
import { getT } from "@/lib/i18n";
import { pageTitle } from "@/lib/title";
// PEP-274: the browser tab says which page it is.
export async function generateMetadata() {
const t = await getT();
return pageTitle(t, t("Журнал действий"));
}
/** Superadmin only (PEP-48): who did what — people (web, Telegram, MCP clients, CLI), agents, Peppa. */
export default async function Journal({ searchParams }: { searchParams: Promise<{ project?: string; actor?: string; channel?: string; all?: string }> }) {
const me = await requireUser();
if (!(await isSuperadmin(db, me))) notFound();
@ -35,3 +41,5 @@ export default async function Journal({ searchParams }: { searchParams: Promise<
</Workspace>
);
}
/** Superadmin only (PEP-48): who did what — people (web, Telegram, MCP clients, CLI), agents, Peppa. */

View File

@ -15,10 +15,17 @@ import { requireUser } from "@/lib/auth";
import { db } from "@/lib/db";
import { getT } from "@/lib/i18n";
import { deleteMonitorAction, pauseMonitorAction, updateMonitorAction } from "../actions";
import { pageTitle } from "@/lib/title";
export const dynamic = "force-dynamic";
const PAGE = 100;
// PEP-274: the browser tab says which page it is.
export async function generateMetadata() {
const t = await getT();
return pageTitle(t, t("Мониторинг"));
}
const when = (iso: string) => new Date(iso).toLocaleString("ru-RU", { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit" });
export default async function MonitorPage({ params, searchParams }: { params: Promise<{ id: string }>; searchParams: Promise<{ error?: string; page?: string }> }) {

View File

@ -47,6 +47,7 @@ import { queuePositions, workLine } from "@peppa/core";
import { WorkLine } from "@/components/WorkLine";
import { deleteProjectAction } from "../../actions";
import { DeleteProjectControl, mayDeleteProject, RestoreProjectButton } from "@/components/ProjectDelete";
import { projectTitle } from "@/lib/title";
const RELEASE_STATUS: Record<Release["status"], { label: string; tone: "info" | "ok" | "warn" | "danger" | "muted" }> = {
deploying: { label: m("выкатывается"), tone: "info" },
@ -70,6 +71,14 @@ const TABS = [
{ id: "journal", label: m("Журнал") },
] as const;
// PEP-274: «KEY · вкладка — FORGE».
export async function generateMetadata({ params, searchParams }: { params: Promise<{ key: string }>; searchParams: Promise<{ tab?: string }> }) {
const t = await getT();
const { tab: id } = await searchParams;
const tab = TABS.find((x) => x.id === id) ?? TABS[0]!;
return projectTitle(t, (await params).key, t.text(tab.label));
}
function EnvLine({ name, r, t }: { name: string; r: Release | null | undefined; t: Translator }) {
return (
<div className="flex min-w-0 flex-1 flex-col gap-0.5 rounded-md border bg-background/40 px-3 py-2">

View File

@ -15,8 +15,15 @@ import { db } from "@/lib/db";
import { getT } from "@/lib/i18n";
import { intlLocale } from "@peppa/shared/i18n";
import { projectForUserByKey } from "@/lib/queries";
import { projectTitle } from "@/lib/title";
import { applyPlanAction, discardPlanAction, planEpicAction } from "../../../../board-actions";
// PEP-274: the browser tab says which page it is.
export async function generateMetadata({ params }: { params: Promise<{ key: string }> }) {
const t = await getT();
return projectTitle(t, (await params).key, t("Эпик"));
}
export default async function PlanEpicPage({ params, searchParams }: { params: Promise<{ key: string; epic: string }>; searchParams: Promise<{ error?: string }> }) {
const user = await requireUser();
const { key, epic: epicParam } = await params;

View File

@ -16,6 +16,7 @@ import { requireUser, words } from "@/lib/auth";
import { db } from "@/lib/db";
import { getT } from "@/lib/i18n";
import { acceptInbox, activeSessions, inbox } from "@/lib/queries";
import { pageTitle } from "@/lib/title";
function BlockSkeleton() {
return <div className="h-24 animate-pulse rounded-md bg-muted/40" aria-hidden />;
@ -35,6 +36,12 @@ async function AgentsBlock({ userId, engineer }: { userId: number; engineer: boo
);
}
// PEP-274: the browser tab says which page it is.
export async function generateMetadata() {
const t = await getT();
return pageTitle(t, t("Главная"));
}
export default async function Home({ searchParams }: { searchParams: Promise<{ error?: string }> }) {
const user = await requireUser();
const { error } = await searchParams;

View File

@ -10,6 +10,7 @@ import { requireUser, words } from "@/lib/auth";
import { db } from "@/lib/db";
import { getT } from "@/lib/i18n";
import { createProjectAction } from "../../actions";
import { pageTitle } from "@/lib/title";
function Choice({ name, value, checked, children }: { name: string; value: string; checked?: boolean; children: React.ReactNode }) {
return (
@ -20,6 +21,12 @@ function Choice({ name, value, checked, children }: { name: string; value: strin
);
}
// PEP-274: the browser tab says which page it is.
export async function generateMetadata() {
const t = await getT();
return pageTitle(t, t("Новый проект"));
}
export default async function NewProject({ searchParams }: { searchParams: Promise<{ error?: string }> }) {
const user = await requireUser();
const t = await getT();

View File

@ -8,6 +8,13 @@ import { Workspace } from "@/components/Workspace";
import { requireUser, words } from "@/lib/auth";
import { db } from "@/lib/db";
import { getT } from "@/lib/i18n";
import { pageTitle } from "@/lib/title";
// PEP-274: the browser tab says which page it is.
export async function generateMetadata() {
const t = await getT();
return pageTitle(t, t("Проекты"));
}
export default async function Projects({ searchParams }: { searchParams: Promise<{ error?: string }> }) {
const user = await requireUser();

View File

@ -14,6 +14,7 @@ import { inbox, sessionEvents } from "@/lib/queries";
import { cn } from "@/lib/utils";
import { getT } from "@/lib/i18n";
import { m } from "@peppa/shared/i18n";
import { pageTitle } from "@/lib/title";
const FILTERS: Array<{ key: RunnerFilter | undefined; label: string }> = [
{ key: undefined, label: m("все") },
@ -28,6 +29,12 @@ const matches = (s: SessionView, q: string) =>
type Params = { error?: string; f?: string; q?: string; id?: string };
// PEP-274: the browser tab says which page it is.
export async function generateMetadata() {
const t = await getT();
return pageTitle(t, t("Работа агентов"));
}
export default async function Runners({ searchParams }: { searchParams: Promise<Params> }) {
const user = await requireUser();
const t = await getT();

View File

@ -17,6 +17,13 @@ import { inbox } from "@/lib/queries";
import { SESSION_STATUS, TONE_BG, TONE_TEXT } from "@/lib/status";
import { cn } from "@/lib/utils";
import { getT } from "@/lib/i18n";
import { pageTitle } from "@/lib/title";
// PEP-274: the browser tab says which page it is.
export async function generateMetadata() {
const t = await getT();
return pageTitle(t, t("Сессии"));
}
export default async function Sessions({ searchParams }: { searchParams: Promise<{ id?: string }> }) {
const user = await requireUser();

View File

@ -20,6 +20,7 @@ import { LanguageSwitcher } from "@/components/I18n";
import { getLocale, getT } from "@/lib/i18n";
import { CopyText } from "@/components/CopyText";
import { intlLocale } from "@peppa/shared/i18n";
import { pageTitle } from "@/lib/title";
const back = { back: "/settings" };
@ -36,6 +37,12 @@ function Row({ title, children, actions }: { title: React.ReactNode; children?:
);
}
// PEP-274: the browser tab says which page it is.
export async function generateMetadata() {
const t = await getT();
return pageTitle(t, t("Настройки"));
}
export default async function Settings({ searchParams }: { searchParams: Promise<{ error?: string; mode?: string; egov?: string; google?: string; notify?: string; bot?: string }> }) {
const user = await requireUser();
const { error, egov, google, notify, bot, mode: modeSaved } = await searchParams;

View File

@ -77,9 +77,15 @@ import { BudgetPanel } from "@/components/Accounting";
import { ActivityTab, ArtifactTab, CommentsTab, MergeTab, ProgressBar, SpecsTab, STORY_TABS, TasksTab, TestsTab, type CheckRunRow, type StoryTab } from "./tabs";
import { archiveTaskAction, setDependenciesAction } from "../../board-actions";
import { Badge } from "@/components/ui/badge";
import { taskTitle } from "@/lib/title";
const CI_ICON = { success: <CircleCheck className="size-4 text-ok" />, failure: <CircleX className="size-4 text-destructive" />, pending: <Hourglass className="size-4 text-warn" /> };
// PEP-274: «KEY-N · название — FORGE».
export async function generateMetadata({ params }: { params: Promise<{ key: string }> }) {
return taskTitle(await getT(), (await params).key);
}
/** Gitea behind Cloudflare can hang: the merge tab waits at most this long. */
async function gateWithTimeout(ref: Parameters<typeof prGate>[0]): Promise<GateResult | null> {
return Promise.race([prGate(ref).catch(() => null), new Promise<null>((r) => setTimeout(() => r(null), 5000))]);

View File

@ -11,8 +11,14 @@ import { requireUser } from "@/lib/auth";
import { db } from "@/lib/db";
import { getT } from "@/lib/i18n";
import { mergeAccountsAction } from "../../actions";
import { pageTitle } from "@/lib/title";
// PEP-274: the browser tab says which page it is.
export async function generateMetadata() {
const t = await getT();
return pageTitle(t, t("Объединить учётки"));
}
/** PEP-204: what moves from the old account to the main one — confirmed before anything changes. Superadmin only. */
export default async function MergeAccounts({ searchParams }: { searchParams: Promise<{ from?: string; to?: string; error?: string }> }) {
const me = await requireUser();
if (!(await isSuperadmin(db, me))) notFound();
@ -111,3 +117,5 @@ export default async function MergeAccounts({ searchParams }: { searchParams: Pr
</Workspace>
);
}
/** PEP-204: what moves from the old account to the main one — confirmed before anything changes. Superadmin only. */

View File

@ -12,10 +12,16 @@ import { requireUser } from "@/lib/auth";
import { db } from "@/lib/db";
import { getT } from "@/lib/i18n";
import { setSuperadminAction, setUserDisabledAction } from "../actions";
import { pageTitle } from "@/lib/title";
const back = { back: "/users" };
/** Superadmin only (PEP-68/71): who is registered, disable / enable. */
// PEP-274: the browser tab says which page it is.
export async function generateMetadata() {
const t = await getT();
return pageTitle(t, t("Пользователи"));
}
export default async function Users({ searchParams }: { searchParams: Promise<{ error?: string }> }) {
const me = await requireUser();
if (!(await isSuperadmin(db, me))) notFound();
@ -94,3 +100,5 @@ export default async function Users({ searchParams }: { searchParams: Promise<{
</Workspace>
);
}
/** Superadmin only (PEP-68/71): who is registered, disable / enable. */

View File

@ -8,6 +8,7 @@ import { requireUser, words } from "@/lib/auth";
import { getT } from "@/lib/i18n";
import { m, type Translator } from "@peppa/shared/i18n";
import type { Words } from "@peppa/shared/wording";
import { pageTitle } from "@/lib/title";
const WHY = [
{ title: m("Программировать не нужно"), text: m("Вы пишете, что должно получиться, — как объяснили бы коллеге. Как это сделать, решают агенты.") },
@ -30,6 +31,12 @@ const glossary = (w: Words, t: Translator): Array<[string, string]> => [
[t("Ревью"), t("момент, когда агент закончил, а вы решаете: принять или вернуть")],
];
// PEP-274: the browser tab says which page it is.
export async function generateMetadata() {
const t = await getT();
return pageTitle(t, t("Добро пожаловать в FORGE"));
}
export default async function Welcome() {
await requireUser();
const t = await getT();

View File

@ -13,6 +13,7 @@ import { PugMascot } from "@/components/PugMascot";
import { LanguageSwitcher } from "@/components/I18n";
import { getT } from "@/lib/i18n";
import { m } from "@peppa/shared/i18n";
import { pageTitle } from "@/lib/title";
export const dynamic = "force-dynamic";
@ -37,7 +38,12 @@ const NEED = [
{ icon: Sparkles, text: m("Платная подписка Claude или ChatGPT — на ней работают агенты") },
];
/** PEP-71: eGov QR is the only way in. PEP-83: the page first says why the factory and how it works. */
// PEP-274: the browser tab says which page it is.
export async function generateMetadata() {
const t = await getT();
return pageTitle(t, t("Вход"));
}
export default async function Login({ searchParams }: { searchParams: Promise<{ error?: string; next?: string }> }) {
const { error, next } = await searchParams;
if (await currentUser()) redirect(safeNext(next));
@ -122,3 +128,5 @@ export default async function Login({ searchParams }: { searchParams: Promise<{
</main>
);
}
/** PEP-71: eGov QR is the only way in. PEP-83: the page first says why the factory and how it works. */

View File

@ -4,10 +4,16 @@ import { LiveRefresh } from "@/components/LiveRefresh";
import { Brand } from "@/components/Brand";
import { GuideCopy } from "@/components/GuideCopy";
import { getT } from "@/lib/i18n";
import { pageTitle } from "@/lib/title";
export const dynamic = "force-dynamic";
/** PEP-190: public page (no sign-in) with the same guide that the MCP tool get_started returns. */
// PEP-274: the browser tab says which page it is.
export async function generateMetadata() {
const t = await getT();
return pageTitle(t, t("Инструкция для ИИ"));
}
export default async function McpGuide() {
const t = await getT();
return (
@ -22,3 +28,5 @@ export default async function McpGuide() {
</main>
);
}
/** PEP-190: public page (no sign-in) with the same guide that the MCP tool get_started returns. */

View File

@ -7,12 +7,18 @@ import { Brand } from "@/components/Brand";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { getT } from "@/lib/i18n";
import { pageTitle } from "@/lib/title";
export const dynamic = "force-dynamic";
type Params = Record<string, string | undefined>;
/** OAuth consent screen: who asks, what they get, allow / deny. */
// PEP-274: the browser tab says which page it is.
export async function generateMetadata() {
const t = await getT();
return pageTitle(t, t("Доступ для приложения"));
}
export default async function Authorize({ searchParams }: { searchParams: Promise<Params> }) {
const p = await searchParams;
const user = await currentUser();
@ -76,3 +82,5 @@ function Hidden({ p }: { p: Params }) {
</>
);
}
/** OAuth consent screen: who asks, what they get, allow / deny. */

View File

@ -26,7 +26,7 @@ const fmt = (n: number) => (n < 1024 ? `${n} B` : n < 1048576 ? `${Math.round(n
* picture (Ctrl+V). Each file goes up at once (`POST /api/attachments`); the form carries the
* returned ids as hidden `attachment` fields and the action links them to the message.
*/
export function AttachField({ projectId, target, className }: { projectId: number; /** id of the textarea that takes drops and pastes */ target?: string; className?: string }) {
export function AttachField({ projectId, target, className, touch = false }: { projectId: number; /** id of the textarea that takes drops and pastes */ target?: string; className?: string; /** PEP-274: a 44 px target on a phone */ touch?: boolean }) {
const t = useT();
const inputId = useId();
const picker = useRef<HTMLInputElement>(null);
@ -139,7 +139,7 @@ export function AttachField({ projectId, target, className }: { projectId: numbe
<button
type="button"
onClick={() => picker.current?.click()}
className={cn("inline-flex h-8 items-center gap-1.5 rounded-md border px-2.5 text-sm text-muted-foreground hover:bg-accent hover:text-foreground", over && "border-primary bg-accent text-foreground")}
className={cn("inline-flex h-8 items-center gap-1.5 rounded-md border px-2.5 text-sm text-muted-foreground hover:bg-accent hover:text-foreground", touch && "h-11 min-w-11 justify-center md:h-8 md:min-w-0", over && "border-primary bg-accent text-foreground")}
aria-label={t("Приложить файл")}
title={t("Картинки, PDF, текст, Word, Excel, PowerPoint — до 5 файлов, каждый до 20 МБ. Можно перетащить файл в поле или вставить картинку из буфера.")}
>

View File

@ -2,6 +2,6 @@
import { voiceStoriesEnabled } from "@peppa/shared";
import { DictateButton } from "@/components/DictateButton";
export function Dictate(props: { target: string; className?: string; compact?: boolean }) {
export function Dictate(props: { target: string; className?: string; compact?: boolean; touch?: boolean }) {
return voiceStoriesEnabled() ? <DictateButton {...props} /> : null;
}

View File

@ -33,7 +33,7 @@ function pickMime(): string | undefined {
return undefined;
}
export function DictateButton({ target, className, compact = false }: { target: string; className?: string; compact?: boolean }) {
export function DictateButton({ target, className, compact = false, touch = false }: { target: string; className?: string; compact?: boolean; /** PEP-274: a 44 px target on a phone */ touch?: boolean }) {
const t = useT();
const [supported, setSupported] = useState(false);
const [state, setState] = useState<State>("idle");
@ -103,6 +103,7 @@ export function DictateButton({ target, className, compact = false }: { target:
aria-pressed={state === "recording"}
title={state === "recording" ? t("Остановить запись и распознать") : t("Наговорить текст голосом")}
data-dictate={target}
className={cn(touch && "h-11 min-w-11 md:h-8 md:min-w-0")}
>
{state === "recording" ? <Square /> : state === "sending" ? <Loader2 className="animate-spin" /> : <Mic />}
{!compact && label}

View File

@ -35,6 +35,7 @@ export function FeedbackButton() {
const [busy, setBusy] = useState(false);
const [sent, setSent] = useState(false);
const [over, setOver] = useState(false);
const lift = useComposerLift(inChat);
const add = useCallback(
(files: Iterable<File>) => {
@ -124,8 +125,9 @@ export function FeedbackButton() {
// Sits above the «в реальном времени» indicator of LiveRefresh (the same corner).
title={t("Сообщить о проблеме")}
aria-label={t("Сообщить о проблеме")}
style={lift != null ? { bottom: lift } : undefined}
className={cn(
"fixed right-3 z-30 flex h-10 cursor-pointer items-center gap-2 rounded-full border bg-card px-3 text-sm text-muted-foreground shadow-md transition-colors hover:text-foreground",
"fixed right-3 z-30 flex h-11 min-w-11 justify-center cursor-pointer items-center gap-2 rounded-full border bg-card px-3 text-sm text-muted-foreground shadow-md transition-colors hover:text-foreground",
// PEP-207: in a conversation the message field is pinned to the bottom — the button goes above it, icon only.
inChat ? "bottom-[calc(11rem+env(safe-area-inset-bottom))] md:bottom-32" : "bottom-[calc(6.5rem+env(safe-area-inset-bottom))] md:bottom-12",
)}
@ -231,3 +233,51 @@ export function FeedbackButton() {
</>
);
}
/**
* PEP-274 (F-12): in a conversation the button stays above the top edge of the message field,
* however tall the field grew (lines, attached files) — measured, not a fixed height that the
* field outgrows on a phone. `null` — no field on the page, the classes place the button.
*/
function useComposerLift(inChat: boolean): number | null {
const [lift, setLift] = useState<number | null>(null);
useEffect(() => {
if (!inChat) return setLift(null);
let frame = 0;
let observed: Element | null = null;
const ro = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(() => schedule());
const measure = () => {
frame = 0;
const box = document.querySelector("[data-chat-composer]");
if (box !== observed) {
if (observed) ro?.unobserve(observed);
if (box) ro?.observe(box);
observed = box;
}
if (!box) return setLift(null);
const top = box.getBoundingClientRect().top;
const viewport = window.visualViewport?.height ?? window.innerHeight;
// 8 px above the field; never under the bottom menu if the field scrolled out of view.
setLift(Math.max(Math.round(viewport - top + 8), 72));
};
const schedule = () => {
if (!frame) frame = requestAnimationFrame(measure);
};
schedule();
window.addEventListener("resize", schedule);
window.addEventListener("scroll", schedule, { passive: true, capture: true });
window.visualViewport?.addEventListener("resize", schedule);
// The page re-renders on live updates and may replace the field.
const mo = new MutationObserver(schedule);
mo.observe(document.body, { childList: true, subtree: true });
return () => {
if (frame) cancelAnimationFrame(frame);
ro?.disconnect();
mo.disconnect();
window.removeEventListener("resize", schedule);
window.removeEventListener("scroll", schedule, { capture: true });
window.visualViewport?.removeEventListener("resize", schedule);
};
}, [inChat]);
return lift;
}

View File

@ -56,7 +56,7 @@ export async function ProductCard({
const { task } = wording(engineer ? "engineer" : "product", t.locale);
const { live, check, doneStories } = product;
const open = needs.filter((n) => n.open);
if (!live && !check && doneStories === 0 && !open.length && !product.preparing) return null;
if (!live && !check && doneStories === 0 && !open.length && !product.preparing && !product.stalled) return null;
// PEP-145: one big button — the working product, else the version to check.
const link = live ?? check;
const deployed = !!(live || check);
@ -67,7 +67,7 @@ export async function ProductCard({
</p>
);
return (
<section aria-label={t("Ваш продукт")} className={`mb-5 flex flex-col gap-3 rounded-xl border p-4 ${open.length ? "border-warn/50 bg-warn/5" : link ? "border-ok/40 bg-ok/5" : "border-info/40 bg-info/5"}`}>
<section aria-label={t("Ваш продукт")} className={`mb-5 flex flex-col gap-3 rounded-xl border p-4 ${open.length || (!link && product.stalled) ? "border-warn/50 bg-warn/5" : link ? "border-ok/40 bg-ok/5" : "border-info/40 bg-info/5"}`}>
{link ? (
<div className="flex flex-wrap items-center gap-x-4 gap-y-3">
<div className="flex min-w-0 flex-1 basis-full flex-col gap-0.5 sm:basis-0">
@ -97,6 +97,24 @@ export async function ProductCard({
</a>
</Button>
</div>
) : product.stalled ? (
// PEP-274: the wait ran out — an error in two phrases (what happened, what to do), not an endless «готовим».
<div className="flex flex-col gap-0.5" role="alert" data-product-stalled>
<span className="flex items-center gap-2 text-[15px] font-semibold">
<Wrench className="size-4 text-warn" /> {t("Ссылка на продукт пока не открывается")}
</span>
<span className="text-sm text-muted-foreground">
{product.fix ? (
<>
{t("Агент уже чинит это:")} <Link href={`/t/${product.fix.key}`}>{product.fix.key}</Link>. {t("Ссылка появится здесь сама, делать ничего не нужно.")}
</>
) : (
<>
{t("Запустить продукт пока не получилось. Если ссылка нужна срочно —")} <Link href={`/chats/${projectKey}`}>{t("напишите аналитику в чате")}</Link>.
</>
)}
</span>
</div>
) : product.preparing || doneStories > 0 ? (
<div className="flex flex-col gap-0.5" role="status">
<span className="flex items-center gap-2 text-[15px] font-semibold">

View File

@ -58,8 +58,8 @@ function ProjectRow({ p, t, w }: { p: ProjectProgress; t: Translator; w: Words }
{t("Открыть продукт")} ↗
</a>
) : p.productFix ? (
<Link href={`/t/${p.productFix}`} className="rounded-full border border-info/50 bg-info/10 px-2 text-[11px] font-medium text-foreground hover:no-underline">
{t("Готовим ссылку на продукт")}
<Link href={`/t/${p.productFix}`} className={cn("rounded-full border px-2 text-[11px] font-medium text-foreground hover:no-underline", p.productStalled ? "border-warn/50 bg-warn/12" : "border-info/50 bg-info/10")}>
{p.productStalled ? t("Ссылка пока не открывается") : t("Готовим ссылку на продукт")}
</Link>
) : null}
<span className="ml-auto text-xs text-muted-foreground">

26
apps/web/lib/title.ts Normal file
View File

@ -0,0 +1,26 @@
// PEP-274 (F-13): every browser tab says which page it is — «<страница> — FORGE».
import type { Metadata } from "next";
import { formatTaskKey } from "@peppa/shared";
import { productName, type Translator } from "@peppa/shared/i18n";
import { currentUser } from "@/lib/auth";
import { projectForUserByKey, taskForUser } from "@/lib/queries";
/** «часть · часть — FORGE». Parts are already translated (or are data: keys, names). */
export function pageTitle(t: Translator, ...parts: Array<string | null | undefined | false>): Metadata {
const head = parts.filter((x): x is string => !!x && !!x.trim()).join(" · ");
return { title: head ? `${head} — ${productName(t.locale)}` : productName(t.locale) };
}
/** A project page: «KEY · вкладка — FORGE»; a stranger gets no project name, only the key. */
export async function projectTitle(t: Translator, key: string, ...rest: Array<string | null | undefined | false>): Promise<Metadata> {
const user = await currentUser();
const p = user ? await projectForUserByKey(user.id, decodeURIComponent(key)).catch(() => null) : null;
return pageTitle(t, p?.key ?? null, ...rest);
}
/** A story page: «KEY-N · название — FORGE», only for whoever may see the story. */
export async function taskTitle(t: Translator, key: string): Promise<Metadata> {
const user = await currentUser();
const ref = user ? await taskForUser(user.id, decodeURIComponent(key)).catch(() => null) : null;
return ref ? pageTitle(t, formatTaskKey(ref.project.key, ref.task.number), ref.task.title) : pageTitle(t);
}

View File

@ -0,0 +1,29 @@
# Design — PEP-274
## F-11: срок у «Готовим ссылку»
- Начало ожидания (`waitFrom`) — самое раннее из: создание системной задачи «Продукт должен
открываться по ссылке», первая выкладка версии для проверки, первая принятая задача (её
`updated_at`). Это наблюдаемые в базе моменты, новых колонок не нужно.
- `stalled = нет ссылки && выкладка не идёт && (последняя выкладка упала || сейчас − waitFrom > 60 мин)`.
Идущая выкладка уже ограничена 30 мин (`DEPLOYING_MS`), поэтому «запускается» тоже не вечное.
- Текст ошибки — две фразы (RULES: «что случилось и что сделать»): «Ссылка на продукт пока не
открывается» + либо «Агент уже чинит это: KEY — ссылка появится здесь сама», либо «Если ссылка
нужна срочно — напишите аналитику в чате». Не обещаем «сообщили администратору» — это не всегда так.
- На Главной (`progressOverview`) просрочку считаем дёшево — по возрасту системной задачи
(`productLinkStalled`), без полного `projectProduct` на каждый проект.
## F-12: поле ввода чата на телефоне
- Отчёт: подсказка обрезана, кнопка накладывается, цели < 44 px. Узкий экран (< md):
`flex-wrap`, поле `basis-full`, `min-h` под две строки и `field-sizing: content` (где браузер
умеет — растёт по тексту; где нет — две строки достаточно для самой длинной подсказки на 360 px).
Кнопки «Файл», «Голосом», «Отправить» — `h-11`/`min-w-11` на узком, прежние размеры от `md`.
- «Сообщить о проблеме» в переписке: позиция считается от верхнего края
`[data-chat-composer]` (ResizeObserver + scroll/resize), запасная — прежние классы. Так кнопка
не наезжает на поле, сколько бы строк и файлов в нём ни было. Сама кнопка — 44 px.
## F-13: заголовки вкладок
- Хелпер `pageTitle(t, ...части)` в `apps/web/lib/title.ts` → «часть · часть — FORGE».
Шаблон Next (`title.template`) не берём: существующие страницы уже пишут «… — FORGE» целиком.
- Проект: «KEY · Доска — FORGE» (вкладка из `?tab=`), задача: «KEY · название — FORGE», чат:
«Чат KEY — FORGE». Названия задач/проектов — данные, в шаблон перевода не попадают.
- Тест `page-titles.test.ts`: каждая `page.tsx` в `apps/web/app` экспортирует `generateMetadata`.

View File

@ -0,0 +1,28 @@
# PEP-274: мелкие UX-дефекты из отчёта тестирования (F-11–F-13)
## Why
Отчёт тестирования FORGE (24.11.2026) нашёл три мелких дефекта, которые путают владельца:
- **F-11** — «Готовим ссылку на продукт» висит бесконечно: если выкладка не поднялась или ссылка
не появилась за разумное время, человек видит «готовим» без срока и без ошибки.
- **F-12** — чат на телефоне: длинная подсказка в поле ввода обрезана (поле в одну строку
между четырьмя кнопками), плавающая кнопка «Сообщить о проблеме» наезжает на поле, когда оно
выросло, кнопки поля меньше 44 px.
- **F-13** — у большинства страниц заголовок вкладки браузера — просто «FORGE»: десять открытых
вкладок не различить.
## What Changes
- `projectProduct` отдаёт `stalled`: ссылки нет, выкладка сейчас не идёт, и либо последняя
выкладка версии для проверки упала, либо ссылку ждём дольше `LINK_WAIT_MS` (60 мин). Карточка
«Ваш продукт» тогда вместо «Готовим ссылку» показывает ошибку из двух фраз: что случилось и что
сделать. Плашка на Главной — «Ссылка пока не открывается».
- Поле ввода чата на узком экране: текст на всю ширину и растёт по подсказке, кнопки ниже,
каждая не меньше 44 px; на широком — как раньше в одну строку. Кнопка «Сообщить о проблеме» в
переписке держится над верхним краем поля (меряет его), а не на фиксированной высоте.
- У каждой страницы свой заголовок вкладки: «<страница> — FORGE», у проекта — ключ и вкладка,
у задачи — ключ и название, у чата — проект. Тест следит, что у каждой `page.tsx` есть
`generateMetadata`.
## Impact
- `packages/core/src/product.ts`, `progress.ts`; `apps/web/components/ProductCard.tsx`,
`ProgressOverview.tsx`, `FeedbackButton.tsx`; `app/(app)/chats/[chat]/page.tsx`; все страницы
без `generateMetadata`; `apps/web/lib/title.ts`; переводы en/kk.

View File

@ -0,0 +1,27 @@
## ADDED Requirements
### Requirement: Ожидание ссылки со сроком
Карточка «Ваш продукт» SHALL показывать «Готовим ссылку на продукт» только пока ожидание разумно:
ссылки нет, и либо идёт выкладка, либо ссылку ждут не дольше 60 минут. Если последняя выкладка
версии для проверки упала или ссылку ждут дольше 60 минут и выкладка не идёт, карточка SHALL
показывать ошибку из двух фраз: что случилось и что сделать.
#### Scenario: Выкладка упала — ошибка вместо «готовим»
- **GIVEN** у проекта принятая задача и нет здоровой версии для проверки
- **AND** последняя выкладка версии для проверки завершилась неудачей
- **WHEN** владелец открывает страницу проекта
- **THEN** карточка показывает «Ссылка на продукт пока не открывается»
- **AND** подсказывает, что делать дальше
- **BUT** не показывает «Готовим ссылку на продукт»
#### Scenario: Идёт выкладка — ещё готовим
- **GIVEN** у проекта нет ссылки
- **AND** выкладка версии для проверки началась 5 минут назад
- **WHEN** владелец открывает страницу проекта
- **THEN** карточка показывает «Готовим ссылку на продукт»
#### Scenario: Ссылку ждут больше часа
- **GIVEN** задача «Продукт должен открываться по ссылке» открыта 2 часа назад
- **AND** выкладка сейчас не идёт
- **WHEN** владелец открывает Главную
- **THEN** у проекта плашка «Ссылка пока не открывается» со ссылкой на эту задачу

View File

@ -0,0 +1,22 @@
## ADDED Requirements
### Requirement: Поле ввода чата на телефоне
На экране уже 768 px поле ввода переписки SHALL занимать всю ширину и показывать подсказку
целиком, кнопки поля SHALL быть не меньше 44 × 44 px, а кнопка «Сообщить о проблеме» SHALL
держаться выше поля ввода, не перекрывая его.
#### Scenario: Подсказка видна целиком
- **GIVEN** экран шириной 360 px и открытое обсуждение проекта
- **WHEN** поле ввода пустое
- **THEN** подсказка «Спросите аналитика, что с проектом…» видна целиком, без обрезки
#### Scenario: Кнопки удобно нажимать
- **GIVEN** экран шириной 360 px и открытая переписка
- **WHEN** пользователь смотрит на поле ввода
- **THEN** кнопки «Файл», «Голосом» и «Отправить» не меньше 44 px по высоте и ширине
#### Scenario: Поле выросло — кнопка жалобы не накрывает его
- **GIVEN** экран шириной 360 px
- **AND** в поле ввода пять строк текста и приложен файл
- **WHEN** пользователь смотрит на низ экрана
- **THEN** кнопка «Сообщить о проблеме» находится выше верхнего края поля ввода

View File

@ -0,0 +1,20 @@
## ADDED Requirements
### Requirement: Свой заголовок у каждой вкладки браузера
Каждая страница веба SHALL задавать свой заголовок вкладки вида «<страница> — FORGE»: у проекта —
ключ и открытая вкладка проекта, у задачи — ключ и название, у переписки — проект.
#### Scenario: Задача во вкладке
- **GIVEN** задача PEP-42 «Вход по почте»
- **WHEN** пользователь открывает её страницу
- **THEN** заголовок вкладки браузера — «PEP-42 · Вход по почте — FORGE»
#### Scenario: Вкладка проекта
- **GIVEN** проект PEP
- **WHEN** пользователь открывает его доску
- **THEN** заголовок вкладки — «PEP · Доска — FORGE»
#### Scenario: Страница без заголовка не проходит проверку
- **GIVEN** новая страница веба без `generateMetadata`
- **WHEN** запускаются проверки
- **THEN** тест заголовков падает с именем этой страницы

View File

@ -0,0 +1,17 @@
## 1. F-11 «Готовим ссылку» со сроком
- [x] 1.1 `projectProduct`: `stalled` (+ `LINK_WAIT_MS`), `productLinkStalled` для Главной
- [x] 1.2 `ProductCard` и `ProgressOverview`: ошибка из двух фраз вместо «Готовим»
- [x] 1.3 Тест на `stalled` (упавшая выкладка, просрочка, идущая выкладка)
## 2. F-12 мобильный чат
- [x] 2.1 Поле ввода: подсказка целиком на узком экране, кнопки ≥ 44 px
- [x] 2.2 «Сообщить о проблеме» держится над полем ввода
- [x] 2.3 Проверка в браузере на 360 px
## 3. F-13 заголовки вкладок
- [x] 3.1 `pageTitle` и `generateMetadata` у всех страниц
- [x] 3.2 Тест `page-titles.test.ts`
## 4. Завершение
- [x] 4.1 Переводы, `pnpm lint`, typecheck, тесты
- [x] 4.2 Archive, PR

View File

@ -101,3 +101,29 @@ Peppa SHALL сама заводить задачу «Продукт должен
- **GIVEN** у проекта нет ни одной здоровой выкладки
- **WHEN** задача закрывается автоматически
- **THEN** в сообщении нет строки «Посмотреть»
### Requirement: Ожидание ссылки со сроком
Карточка «Ваш продукт» SHALL показывать «Готовим ссылку на продукт» только пока ожидание разумно:
ссылки нет, и либо идёт выкладка, либо ссылку ждут не дольше 60 минут. Если последняя выкладка
версии для проверки упала или ссылку ждут дольше 60 минут и выкладка не идёт, карточка SHALL
показывать ошибку из двух фраз: что случилось и что сделать.
#### Scenario: Выкладка упала — ошибка вместо «готовим»
- **GIVEN** у проекта принятая задача и нет здоровой версии для проверки
- **AND** последняя выкладка версии для проверки завершилась неудачей
- **WHEN** владелец открывает страницу проекта
- **THEN** карточка показывает «Ссылка на продукт пока не открывается»
- **AND** подсказывает, что делать дальше
- **BUT** не показывает «Готовим ссылку на продукт»
#### Scenario: Идёт выкладка — ещё готовим
- **GIVEN** у проекта нет ссылки
- **AND** выкладка версии для проверки началась 5 минут назад
- **WHEN** владелец открывает страницу проекта
- **THEN** карточка показывает «Готовим ссылку на продукт»
#### Scenario: Ссылку ждут больше часа
- **GIVEN** задача «Продукт должен открываться по ссылке» открыта 2 часа назад
- **AND** выкладка сейчас не идёт
- **WHEN** владелец открывает Главную
- **THEN** у проекта плашка «Ссылка пока не открывается» со ссылкой на эту задачу

View File

@ -429,3 +429,24 @@ SHALL быть доступен под «Подробнее» только су
- **GIVEN** к чату привязан Telegram
- **WHEN** приходит сообщение длиннее 4096 символов
- **THEN** в Telegram уходит сокращённый текст с припиской, что полностью — на сайте
### Requirement: Поле ввода чата на телефоне
На экране уже 768 px поле ввода переписки SHALL занимать всю ширину и показывать подсказку
целиком, кнопки поля SHALL быть не меньше 44 × 44 px, а кнопка «Сообщить о проблеме» SHALL
держаться выше поля ввода, не перекрывая его.
#### Scenario: Подсказка видна целиком
- **GIVEN** экран шириной 360 px и открытое обсуждение проекта
- **WHEN** поле ввода пустое
- **THEN** подсказка «Спросите аналитика, что с проектом…» видна целиком, без обрезки
#### Scenario: Кнопки удобно нажимать
- **GIVEN** экран шириной 360 px и открытая переписка
- **WHEN** пользователь смотрит на поле ввода
- **THEN** кнопки «Файл», «Голосом» и «Отправить» не меньше 44 px по высоте и ширине
#### Scenario: Поле выросло — кнопка жалобы не накрывает его
- **GIVEN** экран шириной 360 px
- **AND** в поле ввода пять строк текста и приложен файл
- **WHEN** пользователь смотрит на низ экрана
- **THEN** кнопка «Сообщить о проблеме» находится выше верхнего края поля ввода

View File

@ -599,3 +599,22 @@ PM SHALL уметь убрать стори в архив и вернуть её
- **GIVEN** пользователь переключил веб на тёмную тему
- **WHEN** он смотрит на основную кнопку
- **THEN** кнопка светло-синяя с тёмным текстом, а не розовая
### Requirement: Свой заголовок у каждой вкладки браузера
Каждая страница веба SHALL задавать свой заголовок вкладки вида «<страница> — FORGE»: у проекта —
ключ и открытая вкладка проекта, у задачи — ключ и название, у переписки — проект.
#### Scenario: Задача во вкладке
- **GIVEN** задача PEP-42 «Вход по почте»
- **WHEN** пользователь открывает её страницу
- **THEN** заголовок вкладки браузера — «PEP-42 · Вход по почте — FORGE»
#### Scenario: Вкладка проекта
- **GIVEN** проект PEP
- **WHEN** пользователь открывает его доску
- **THEN** заголовок вкладки — «PEP · Доска — FORGE»
#### Scenario: Страница без заголовка не проходит проверку
- **GIVEN** новая страница веба без `generateMetadata`
- **WHEN** запускаются проверки
- **THEN** тест заголовков падает с именем этой страницы

View File

@ -60,12 +60,12 @@ export async function setProductLinkState(db: Db, projectId: number, state: Prod
}
/** The open system story of a project (not accepted, not archived), if any. */
export async function openProductLinkTask(db: Db, projectId: number): Promise<{ id: number; number: number; status: string } | null> {
export async function openProductLinkTask(db: Db, projectId: number): Promise<{ id: number; number: number; status: string; /** when the story was filed (ms) */ at: number } | null> {
const state = await getProductLinkState(db, projectId);
if (!state) return null;
const [t] = await db.select({ id: tasks.id, number: tasks.number, status: tasks.status, archivedAt: tasks.archivedAt, projectId: tasks.projectId }).from(tasks).where(eq(tasks.id, state.taskId));
if (!t || t.projectId !== projectId || t.archivedAt || t.status === "done") return null;
return { id: t.id, number: t.number, status: t.status };
return { id: t.id, number: t.number, status: t.status, at: state.at };
}
// glossary-user: название и описание задачи читает владелец проекта

View File

@ -5,7 +5,7 @@ import { getVersion, proposedCount } from "./task-origin.ts";
import { m as tr } from "@peppa/shared/i18n";
import { formatTaskKey } from "@peppa/shared";
import { projects, releases, tasks, type Db } from "@peppa/db";
import { and, desc, eq, inArray, isNull, sql } from "drizzle-orm";
import { and, asc, desc, eq, inArray, isNull, sql } from "drizzle-orm";
import { openProductLinkTask } from "./product-link.ts";
export interface ProductVersion {
@ -28,6 +28,11 @@ export interface ProjectProduct {
broken: boolean;
/** PEP-145: no link yet, but it is on its way — an update is running or the system story is open. */
preparing: boolean;
/**
* PEP-274: no link and nothing is coming up now, while the last update failed or the link has
* been awaited longer than `LINK_WAIT_MS` — «Готовим ссылку» would be a lie, show an error.
*/
stalled: boolean;
/** PEP-145: a screenshot of the first page (taken on a story's version to check, PEP-44). */
shot: { releaseId: number; n: number } | null;
/** PEP-197: everything a person asked for in this version is accepted and nothing is broken. */
@ -39,6 +44,12 @@ export interface ProjectProduct {
/** An update that reported «начато» and nothing since is not «идёт» for ever. */
const DEPLOYING_MS = 30 * 60_000;
/** PEP-274: how long «Готовим ссылку на продукт» stays honest without a link. */
export const LINK_WAIT_MS = 60 * 60_000;
/** PEP-274: the Home pill — the system story about the link is older than `LINK_WAIT_MS`. */
export const productLinkStalled = (fix: { at: number } | null, now = Date.now()): boolean => !!fix && now - fix.at > LINK_WAIT_MS;
export async function projectProduct(db: Db, projectId: number): Promise<ProjectProduct> {
const latest = async (env: "prod" | "staging") =>
(await db.select().from(releases).where(and(eq(releases.projectId, projectId), eq(releases.env, env), eq(releases.status, "healthy"))).orderBy(desc(releases.id)).limit(1))[0];
@ -50,6 +61,7 @@ export async function projectProduct(db: Db, projectId: number): Promise<Project
const recent = await db.select({ status: releases.status, createdAt: releases.createdAt }).from(releases).where(and(eq(releases.projectId, projectId), eq(releases.env, "staging"))).orderBy(desc(releases.id)).limit(5);
const deploying = recent.some((r) => r.status === "deploying" && Date.now() - r.createdAt.getTime() < DEPLOYING_MS);
const lastFinished = recent.find((r) => r.status !== "deploying" && r.status !== "removed");
const broken = !!lastFinished && (lastFinished.status === "failed" || lastFinished.status === "rolled_back");
const open = await openProductLinkTask(db, projectId);
const [project] = open ? await db.select({ key: projects.key }).from(projects).where(eq(projects.id, projectId)) : [];
const [shot] = await db
@ -59,13 +71,24 @@ export async function projectProduct(db: Db, projectId: number): Promise<Project
.orderBy(desc(releases.id))
.limit(1);
const fix = open && project ? { key: formatTaskKey(project.key, open.number), working: open.status !== "backlog" } : null;
let stalled = false;
if (!live && !check && !deploying) {
// PEP-274: the wait started with the earliest of: the system story, the first update, the first accepted story.
const [first] = await db.select({ at: releases.createdAt }).from(releases).where(and(eq(releases.projectId, projectId), eq(releases.env, "staging"))).orderBy(asc(releases.id)).limit(1);
const [firstDone] = await db.select({ at: sql<number>`min(${tasks.updatedAt})` }).from(tasks).where(and(eq(tasks.projectId, projectId), eq(tasks.status, "done"), isNull(tasks.archivedAt)));
const doneAt = firstDone?.at == null ? null : Number(firstDone.at);
const starts = [open?.at, first?.at.getTime(), doneAt].filter((x): x is number => typeof x === "number" && Number.isFinite(x));
const waitFrom = starts.length ? Math.min(...starts) : null;
stalled = broken || (waitFrom != null && Date.now() - waitFrom > LINK_WAIT_MS);
}
return {
live,
check,
doneStories: done.length,
fix,
broken: !!lastFinished && (lastFinished.status === "failed" || lastFinished.status === "rolled_back"),
broken,
preparing: !live && !check && (deploying || !!fix),
stalled,
versionDone: !!(await getVersion(db, projectId))?.doneAt,
proposed: await proposedCount(db, projectId),
shot: shot ? { releaseId: shot.id, n: Math.max(0, shot.screenshots.findIndex((s) => s.path === "/")) } : null,

View File

@ -1,7 +1,7 @@
// PEP-77: progress of every project on the Home page — stories per board column and what is
// in work right now (agent, tasks.md progress).
import { m as tr } from "@peppa/shared/i18n";
import { productUrls } from "./product.ts";
import { productLinkStalled, productUrls } from "./product.ts";
import { openProductLinkTask } from "./product-link.ts";
import { projects, tasks, users, type Db } from "@peppa/db";
import { formatTaskKey } from "@peppa/shared";
@ -42,6 +42,8 @@ export interface ProjectProgress {
product: { url: string; live: boolean } | null;
/** PEP-145: no link yet — the key of the system story that makes the product open by a link. */
productFix: string | null;
/** PEP-274: the link story is older than an hour — «Ссылка пока не открывается», not «Готовим». */
productStalled: boolean;
/** PEP-182: «Делается · В очереди» of the project. */
work: WorkLine;
/** PEP-174: the project is on pause. */
@ -76,9 +78,10 @@ export async function progressOverview(db: Db, userId: number): Promise<Progress
const lineOf = await workLineIndex(db, ids);
out.work = lineOf(mineIds);
for (const { p, ownerLogin } of ps) {
const row: ProjectProgress = { key: p.key, name: p.name, ownerLogin: mine.has(p.id) ? null : (ownerLogin ?? tr("без владельца")), backlog: 0, inProgress: 0, review: 0, done: 0, total: 0, working: [], reviewKeys: [], product: products.get(p.id) ?? null, productFix: null, work: lineOf([p.id]), paused: paused.has(p.id) };
const row: ProjectProgress = { key: p.key, name: p.name, ownerLogin: mine.has(p.id) ? null : (ownerLogin ?? tr("без владельца")), backlog: 0, inProgress: 0, review: 0, done: 0, total: 0, working: [], reviewKeys: [], product: products.get(p.id) ?? null, productFix: null, productStalled: false, work: lineOf([p.id]), paused: paused.has(p.id) };
const fix = row.product ? null : await openProductLinkTask(db, p.id);
if (fix) row.productFix = formatTaskKey(p.key, fix.number);
if (fix) row.productStalled = productLinkStalled(fix);
const own = ts.filter((t) => t.projectId === p.id);
const agentsOf = own.some((t) => column(t.status) === "inProgress") ? await taskAgentNames(db, p.id) : new Map<number, string>();
for (const t of own) {

View File

@ -458,4 +458,13 @@ export const project: Dict = {
"Да, удалить": "Yes, delete",
"Удалённые проекты": "Deleted projects",
"Каждый хранится {days} дней со дня удаления — до этого его можно вернуть, потом он исчезнет насовсем.": "Each is kept {days} days from deletion — until then it can be brought back, then it is gone for good.",
// PEP-274
"Чат {key}": "Chat {key}",
"Доступ для приложения": "Access for an app",
"Ссылка на продукт пока не открывается": "The link to your product does not open yet",
"Агент уже чинит это:": "An agent is already fixing it:",
"Ссылка появится здесь сама, делать ничего не нужно.": "The link will show up here by itself — nothing to do.",
"Запустить продукт пока не получилось. Если ссылка нужна срочно —": "The product could not be started yet. If you need the link urgently,",
"напишите аналитику в чате": "write to the analyst in the chat",
"Ссылка пока не открывается": "The link does not open yet",
};

View File

@ -402,4 +402,13 @@ export const project: Dict = {
"Да, удалить": "Иә, жою",
"Удалённые проекты": "Жойылған жобалар",
"Каждый хранится {days} дней со дня удаления — до этого его можно вернуть, потом он исчезнет насовсем.": "Әрқайсысы жойылған күннен бастап {days} күн сақталады — оған дейін қайтаруға болады, содан кейін біржола жойылады.",
// PEP-274
"Чат {key}": "{key} чаты",
"Доступ для приложения": "Қолданбаға рұқсат",
"Ссылка на продукт пока не открывается": "Өнімге сілтеме әзірге ашылмайды",
"Агент уже чинит это:": "Агент мұны түзетіп жатыр:",
"Ссылка появится здесь сама, делать ничего не нужно.": "Сілтеме осында өзі пайда болады, ештеңе істеудің қажеті жоқ.",
"Запустить продукт пока не получилось. Если ссылка нужна срочно —": "Өнімді әзірге іске қосу мүмкін болмады. Сілтеме шұғыл керек болса,",
"напишите аналитику в чате": "чатта аналитикке жазыңыз",
"Ссылка пока не открывается": "Сілтеме әзірге ашылмайды",
};

View File

@ -0,0 +1,54 @@
// PEP-274 (F-12, F-13): small things the test report found — every browser tab has its own
// title; the chat field on a phone keeps its hint whole and its buttons big enough to tap.
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";
import { fileURLToPath } from "node:url";
const web = fileURLToPath(new URL("../../../apps/web/", import.meta.url));
const pages = (dir: string): string[] =>
readdirSync(dir).flatMap((name) => {
const full = join(dir, name);
if (statSync(full).isDirectory()) return name === "node_modules" ? [] : pages(full);
return name === "page.tsx" ? [full] : [];
});
describe("PEP-274: свой заголовок у каждой вкладки браузера", () => {
test("Страница без заголовка не проходит проверку: у каждой page.tsx есть generateMetadata или metadata", () => {
const all = pages(join(web, "app"));
assert.ok(all.length > 30, "pages found");
const missing = all.filter((f) => !/export (async function generateMetadata|const (metadata|generateMetadata)\b)/.test(readFileSync(f, "utf8"))).map((f) => relative(web, f));
assert.deepEqual(missing, [], `страницы без заголовка вкладки: ${missing.join(", ")}`);
});
test("Задача во вкладке и вкладка проекта: ключ и название / вкладка, затем FORGE", () => {
const title = readFileSync(join(web, "lib/title.ts"), "utf8");
assert.match(title, /join\(" · "\)/);
assert.match(title, /— \$\{productName\(t\.locale\)\}/);
assert.match(readFileSync(join(web, "app/(app)/t/[key]/page.tsx"), "utf8"), /taskTitle\(/);
assert.match(readFileSync(join(web, "app/(app)/p/[key]/page.tsx"), "utf8"), /projectTitle\(t, \(await params\)\.key, t\.text\(tab\.label\)\)/);
});
});
describe("PEP-274: поле ввода чата на телефоне", () => {
const page = readFileSync(join(web, "app/(app)/chats/[chat]/page.tsx"), "utf8");
test("Подсказка видна целиком: на узком экране поле на всю ширину и не ниже двух строк", () => {
assert.match(page, /data-chat-text/);
assert.match(page, /basis-full[^"]*\[field-sizing:content\][^"]*md:basis-0/);
assert.match(page, /min-h-\[4\.25rem\][^"]*md:min-h-9/);
});
test("Кнопки удобно нажимать: «Файл», «Голосом», «Отправить» — 44 px (h-11) на телефоне", () => {
assert.match(page, /<AttachField [^>]*touch/);
assert.match(page, /<Dictate [^>]*touch/);
assert.match(page, /className="[^"]*size-11[^"]*md:h-9[^"]*" data-chat-send/);
assert.match(readFileSync(join(web, "components/AttachField.tsx"), "utf8"), /touch && "h-11 min-w-11/);
assert.match(readFileSync(join(web, "components/DictateButton.tsx"), "utf8"), /touch && "h-11 min-w-11/);
});
test("Поле выросло — кнопка жалобы держится над его верхним краем", () => {
const fb = readFileSync(join(web, "components/FeedbackButton.tsx"), "utf8");
assert.match(fb, /querySelector\("\[data-chat-composer\]"\)/);
assert.match(fb, /style=\{lift != null \? \{ bottom: lift \}/);
assert.match(fb, /h-11 min-w-11/);
});
});

View File

@ -1,7 +1,8 @@
// PEP-111: «Ваш продукт» — where the project's result lives and how releases are said to a PM.
import assert from "node:assert/strict";
import { after, describe, test } from "node:test";
import { releases } from "@peppa/db";
import { releases, tasks } from "@peppa/db";
import { eq } from "drizzle-orm";
import { core, db, teardown } from "./helpers.ts";
after(teardown);
@ -17,7 +18,7 @@ describe("PEP-111: the project's product", () => {
test("nothing deployed: no versions, only the count of accepted stories", async () => {
const p = await proj();
const t = await core.createTask(db, { projectId: p.id, title: "Первая" });
assert.deepEqual(await core.projectProduct(db, p.id), { live: null, check: null, doneStories: 0, fix: null, broken: false, preparing: false, shot: null, versionDone: false, proposed: 0 });
assert.deepEqual(await core.projectProduct(db, p.id), { live: null, check: null, doneStories: 0, fix: null, broken: false, preparing: false, stalled: false, shot: null, versionDone: false, proposed: 0 });
await core.updateTask(db, t, { status: "done" });
assert.equal((await core.projectProduct(db, p.id)).doneStories, 1);
assert.equal((await core.productUrls(db, [p.id])).size, 0);
@ -66,4 +67,41 @@ describe("PEP-111: the project's product", () => {
const o = await core.progressOverview(db, owner.id);
assert.deepEqual(o.mine.find((x) => x.key === "MPRH")?.product, { url: "https://prod.mock.test", live: true });
});
// PEP-274 (F-11): «Готовим ссылку» is honest only for a while.
test("Ссылка не появляется: упавшая выкладка и ожидание дольше часа — stalled, идущая выкладка — ещё готовим", async () => {
const p = await proj();
const t = await core.createTask(db, { projectId: p.id, title: "Сделано" });
await core.updateTask(db, t, { status: "done" });
let v = await core.projectProduct(db, p.id);
assert.equal(v.stalled, false, "только что приняли — ещё ждём");
await rel(p.id, "staging", "aaa0001", "failed");
v = await core.projectProduct(db, p.id);
assert.equal(v.stalled, true, "выкладка упала — ошибка, а не «готовим»");
await db.insert(releases).values({ projectId: p.id, env: "staging", sha: "aaa0002", status: "deploying", host: null, tasks: [] });
v = await core.projectProduct(db, p.id);
assert.equal(v.stalled, false, "идёт новая выкладка — снова готовим");
assert.equal(v.preparing, true);
});
test("Ссылку ждут больше часа — stalled; на Главной плашка «не открывается»", async () => {
const owner = await core.registerEgovUser(db, { iin: "880808400022", name: "ЖДУЩИЙ ТЕСТОВЫЙ" });
const p = await core.createProject(db, { slug: "mock-prod-wait", key: "MPRW", name: "Ждём", giteaOwner: "x", workspacePath: "/tmp/mock-prod-wait", ownerId: owner.id });
const done = await core.createTask(db, { projectId: p.id, title: "Готово давно" });
await core.updateTask(db, done, { status: "done" });
const fix = await core.createTask(db, { projectId: p.id, title: core.PRODUCT_LINK_TITLE });
await core.setProductLinkState(db, p.id, { taskId: fix.task.id, at: Date.now() - 10 * 60_000 });
let v = await core.projectProduct(db, p.id);
assert.equal(v.stalled, false, "ждём 10 минут — ещё готовим");
assert.equal((await core.progressOverview(db, owner.id)).mine.find((x) => x.key === "MPRW")?.productStalled, false);
const twoHours = Date.now() - 2 * 3600_000;
await db.update(tasks).set({ updatedAt: new Date(twoHours) }).where(eq(tasks.id, done.task.id));
v = await core.projectProduct(db, p.id);
assert.equal(v.stalled, true, "первую задачу приняли два часа назад — ссылки так и нет");
await core.setProductLinkState(db, p.id, { taskId: fix.task.id, at: twoHours });
const row = (await core.progressOverview(db, owner.id)).mine.find((x) => x.key === "MPRW");
assert.equal(row?.productStalled, true);
});
});