PEP-145: the «Ваш продукт» card with one big button and an honest status, «Показывать всем» setting, links for accepted stories, translations, tests
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
parent
117dc6ea9c
commit
81f62c9a69
@ -47,6 +47,8 @@ import {
|
||||
setTaskAgentSettings,
|
||||
cleanBudget,
|
||||
logEvent,
|
||||
setPublishMode,
|
||||
type PublishMode,
|
||||
setProjectBudget,
|
||||
setTaskBudget,
|
||||
type Budget,
|
||||
@ -63,7 +65,7 @@ import {
|
||||
import { fixFeedback, linkFeedback, rejectFeedback } from "@peppa/core";
|
||||
import { bugsinkFromEnv } from "@peppa/bugsink";
|
||||
import { loadEnv } from "@peppa/shared";
|
||||
import { acceptStory, fixStory, budgetChanged, resolveTaskById, deployProd, bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, grantRepoAccess, moveTask, provisionProjectOnce, projectNamespace, setProjectVisibility, shareProject, unshareProject, type BoardColumn, resumeSession, sendToSession, startSession, stopSession, type Provider, startFreeRunner, renameRunner, promoteRunner, queueTaskOnRunner, managesProject, saveAgentsMd, cancelOwnLogin, finishOwnClaudeLogin, connectOwnSubscription, removeOwnSubscription, type OwnSubscriptionKind, chooseSharedSubscription } from "@peppa/runner";
|
||||
import { acceptStory, autoPublish, fixStory, budgetChanged, resolveTaskById, deployProd, bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, grantRepoAccess, moveTask, provisionProjectOnce, projectNamespace, setProjectVisibility, shareProject, unshareProject, type BoardColumn, resumeSession, sendToSession, startSession, stopSession, type Provider, startFreeRunner, renameRunner, promoteRunner, queueTaskOnRunner, managesProject, saveAgentsMd, cancelOwnLogin, finishOwnClaudeLogin, connectOwnSubscription, removeOwnSubscription, type OwnSubscriptionKind, chooseSharedSubscription } from "@peppa/runner";
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { redirect } from "next/navigation";
|
||||
import { asWebActor, requireUser, words } from "@/lib/auth";
|
||||
@ -354,6 +356,18 @@ export async function deployProdAction(f: FormData) {
|
||||
});
|
||||
}
|
||||
|
||||
/** PEP-145: «Показывать всем: сам / по кнопке» (owner or member). */
|
||||
export async function setPublishModeAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||||
const mode = await setPublishMode(db, p.id, str(f, "mode") as PublishMode);
|
||||
await logEvent(db, { projectId: p.id, type: "publish_mode_set", payload: { mode, login: user.login } });
|
||||
// «Сам» chosen with an accepted version waiting: it goes to everyone right away.
|
||||
if (mode === "auto") await autoPublish(db, p).catch(() => false);
|
||||
});
|
||||
}
|
||||
|
||||
export async function moveTaskCard(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
|
||||
@ -101,6 +101,7 @@ async function ProductHelp() {
|
||||
))}
|
||||
</div>
|
||||
<p className="mt-4 mb-0">{t.question}</p>
|
||||
<p className="mt-4 mb-0">{t.product}</p>
|
||||
<p className="mt-4 mb-0">
|
||||
{t.problem}{" "}
|
||||
<Link href="/feedback" className="text-primary">{tr("Ваши обращения")}</Link>
|
||||
|
||||
@ -1,9 +1,10 @@
|
||||
import { Fragment } from "react";
|
||||
import { ProductCard } from "@/components/ProductCard";
|
||||
import { PublishPanel } from "@/components/PublishPanel";
|
||||
import { notFound } from "next/navigation";
|
||||
import { ExternalLink, Plus, Rocket, SquareTerminal } from "lucide-react";
|
||||
import { columnOf, currentReleases, describeRepo, isPlatform, listReleases, bugsinkWebhookBase, openPulls, platformReleaseCandidate, platformReleaseOffers, ownPendingLogins, readAgentsMd, repoOverview, type Release, sharedRequest } from "@peppa/runner";
|
||||
import { poolSubscriptions, PRODUCT_PROJECT_TABS, userProjectIds, projectProduct, discussionUnread, ensureProjectChat, listHosts, DEFAULT_RUNNER_SETTINGS, DEFAULT_AGENT_SETTINGS, getProjectAgentSettings, getSystemAgentSettings, getProjectRunnerSettings, getSystemRunnerSettings, blockedLabel, blockersMap, epicProgress, progressLabel, taskProgress, getProjectBudget, listJournal, listProjectSecrets, projectMetrics, type ActorChannel, type ActorKind, getAutonomy, getIncidentSettings, getReviewSettings, isSuperadmin, listEpics, listErrorSources, listIncidents, listMembers, listPools, listSpecs, taskAgentNames, getIntakeSettings, intakePendingTasks, projectAgentWarning, memoryStats, readMemory, projectPool, sharedPool, ownPool, poolOverview, repoAudience, repoVisibilityLabel } from "@peppa/core";
|
||||
import { getPublishMode, poolSubscriptions, PRODUCT_PROJECT_TABS, userProjectIds, projectProduct, discussionUnread, ensureProjectChat, listHosts, DEFAULT_RUNNER_SETTINGS, DEFAULT_AGENT_SETTINGS, getProjectAgentSettings, getSystemAgentSettings, getProjectRunnerSettings, getSystemRunnerSettings, blockedLabel, blockersMap, epicProgress, progressLabel, taskProgress, getProjectBudget, listJournal, listProjectSecrets, projectMetrics, type ActorChannel, type ActorKind, getAutonomy, getIncidentSettings, getReviewSettings, isSuperadmin, listEpics, listErrorSources, listIncidents, listMembers, listPools, listSpecs, taskAgentNames, getIntakeSettings, intakePendingTasks, projectAgentWarning, memoryStats, readMemory, projectPool, sharedPool, ownPool, poolOverview, repoAudience, repoVisibilityLabel } from "@peppa/core";
|
||||
import { productNeeds, lastProductReview } from "@peppa/core";
|
||||
import { LiveRefresh } from "@/components/LiveRefresh";
|
||||
import { PanelSection } from "@/components/ActivityAside";
|
||||
@ -165,6 +166,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
||||
const specs = tab === "specs" ? listSpecs(p) : [];
|
||||
const agentsMd = tab === "agents" ? await readAgentsMd(db, p) : null;
|
||||
const product = await projectProduct(db, p.id);
|
||||
const publish = await getPublishMode(db, p.id);
|
||||
const [productNeedList, productReview] = await Promise.all([productNeeds(db, p.id), lastProductReview(db, p.id)]);
|
||||
// The chat belongs to the project's people; a superadmin looking at someone else's project has none.
|
||||
const canChat = (await userProjectIds(db, user.id)).includes(p.id);
|
||||
@ -222,6 +224,10 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
||||
<AutonomyPanel projectId={p.id} settings={autonomy} back={back} engineer={engineer} />
|
||||
</PanelSection>
|
||||
|
||||
<PanelSection title={t("Показывать всем")}>
|
||||
<PublishPanel projectId={p.id} mode={publish} back={back} />
|
||||
</PanelSection>
|
||||
|
||||
{engineer && (
|
||||
<PanelSection title={t("Раннеры")}>
|
||||
<RunnerSettingsPanel projectId={p.id} own={runnerOwn} inherited={{ ...DEFAULT_RUNNER_SETTINGS, ...runnerSystem }} back={back} hosts={runnerHosts} />
|
||||
@ -529,7 +535,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
||||
</p>
|
||||
)}
|
||||
|
||||
{tab === "board" && <ProductCard product={product} projectKey={p.key} chat={canChat} engineer={engineer} projectId={p.id} needs={productNeedList} review={productReview} back={back} />}
|
||||
{tab === "board" && <ProductCard product={product} projectKey={p.key} chat={canChat} engineer={engineer} projectId={p.id} needs={productNeedList} review={productReview} back={back} publish={publish} />}
|
||||
<nav aria-label={t("Разделы проекта")} className="-mt-2 mb-4 flex gap-1 overflow-x-auto border-b">
|
||||
{visibleTabs.map((x) => (
|
||||
<Fragment key={x.id}>
|
||||
|
||||
@ -41,6 +41,7 @@ import {
|
||||
intakePending,
|
||||
taskCiSummary,
|
||||
type GateResult,
|
||||
productUrls,
|
||||
} from "@peppa/core";
|
||||
import { checkRuns } from "@peppa/db";
|
||||
import { desc, eq } from "drizzle-orm";
|
||||
@ -441,7 +442,7 @@ export default async function StoryPage({ params, searchParams }: { params: Prom
|
||||
body
|
||||
) : (
|
||||
<>
|
||||
<StoryProduct view={productView} taskKey={ref.key} taskStatus={task.status} preview={preview} questions={productQuestions} back={back} />
|
||||
<StoryProduct view={productView} taskKey={ref.key} taskStatus={task.status} preview={preview} questions={productQuestions} back={back} productUrl={task.status === "done" ? ((await productUrls(db, [ref.project.id])).get(ref.project.id)?.url ?? null) : null} />
|
||||
<Link
|
||||
href={detailsOpen ? `/t/${ref.key}` : `/t/${ref.key}?more=1`}
|
||||
scroll={false}
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
import Link from "next/link";
|
||||
import { ExternalLink, KeyRound, Rocket, X } from "lucide-react";
|
||||
import type { ProductNeedView, ProductReview, ProjectProduct } from "@peppa/core";
|
||||
import { ExternalLink, Hourglass, KeyRound, Rocket, Wrench, X } from "lucide-react";
|
||||
import type { ProductNeedView, ProductReview, ProjectProduct, PublishMode } from "@peppa/core";
|
||||
import { Hidden } from "@/components/cards";
|
||||
import { ago } from "@/components/common";
|
||||
import { Button } from "@/components/ui/button";
|
||||
@ -13,7 +13,8 @@ const host = (url: string) => url.replace(/^https?:\/\//, "");
|
||||
|
||||
/**
|
||||
* PEP-111: «Ваш продукт» on the project page — where the result is and what to do next, for a
|
||||
* product manager who asks «где это работает?». Nothing is shown before the first accepted story.
|
||||
* product manager who asks «где это работает?». PEP-145: one big «Открыть продукт»; without a
|
||||
* link — the honest status («Готовим ссылку», the system story), never «попросите аналитика».
|
||||
*/
|
||||
export async function ProductCard({
|
||||
product,
|
||||
@ -24,6 +25,7 @@ export async function ProductCard({
|
||||
needs = [],
|
||||
review = null,
|
||||
back,
|
||||
publish = "button",
|
||||
}: {
|
||||
product: ProjectProduct;
|
||||
projectKey: string;
|
||||
@ -36,6 +38,8 @@ export async function ProductCard({
|
||||
/** PEP-112: the product agent's last acceptance. */
|
||||
review?: ProductReview | null;
|
||||
back?: string;
|
||||
/** PEP-145: «Показывать всем: сам» — no button, Peppa shows the version to everyone itself. */
|
||||
publish?: PublishMode;
|
||||
}) {
|
||||
const t = await getT();
|
||||
// «Показать всем»: the same action as the button in «Релизы», without sending a product manager there.
|
||||
@ -52,7 +56,9 @@ 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) return null;
|
||||
if (!live && !check && doneStories === 0 && !open.length && !product.preparing) return null;
|
||||
// PEP-145: one big button — the working product, else the version to check.
|
||||
const link = live ?? check;
|
||||
const deployed = !!(live || check);
|
||||
const mayEdit = chat && projectId != null && !!back;
|
||||
const next = chat && (
|
||||
@ -61,45 +67,57 @@ 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" : "border-ok/40 bg-ok/5"}`}>
|
||||
{live ? (
|
||||
<div className="flex flex-wrap items-center gap-x-4 gap-y-2">
|
||||
<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"}`}>
|
||||
{link ? (
|
||||
<div className="flex flex-wrap items-center gap-x-4 gap-y-3">
|
||||
<div className="flex min-w-0 flex-1 flex-col gap-0.5">
|
||||
<span className="text-[15px] font-semibold">{t("Ваш продукт работает")}</span>
|
||||
<span className="text-[15px] font-semibold">{live ? t("Ваш продукт работает") : t("Ваш продукт готов — пока его видите только вы")}</span>
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{t("Открыт для всех по адресу")} <span className="font-mono text-foreground">{host(live.url)}</span> · {t("обновлён {when}", { when: ago(live.at, t) })}
|
||||
{live.stories.length > 0 && <> · {t("вошли {tasks} {keys}", { tasks: task("pl"), keys: live.stories.slice(0, 6).join(", ") })}</>}
|
||||
{live ? t("Открыт для всех по адресу") : t("Адрес:")} <span className="font-mono text-foreground">{host(link.url)}</span> · {t("обновлён {when}", { when: ago(link.at, t) })}
|
||||
{link.stories.length > 0 && <> · {t("вошли {tasks} {keys}", { tasks: task("pl"), keys: link.stories.slice(0, 6).join(", ") })}</>}
|
||||
</span>
|
||||
{!live && (
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{publish === "auto" ? t("Когда задачи этой версии будут приняты, Peppa FACTORY сама покажет её всем.") : <>{t("Посмотрите — и, если всё хорошо,")} {showAll}</>}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<Button asChild variant="default">
|
||||
<a href={live.url} target="_blank" rel="noreferrer">
|
||||
{product.shot && (
|
||||
<a href={link.url} target="_blank" rel="noreferrer" className="hidden overflow-hidden rounded border sm:block" aria-hidden tabIndex={-1}>
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img src={`/api/releases/${product.shot.releaseId}/shots/${product.shot.n}`} alt="" loading="lazy" className="block h-20 w-32 object-cover object-top" />
|
||||
</a>
|
||||
)}
|
||||
<Button asChild variant="default" size="lg">
|
||||
<a href={link.url} target="_blank" rel="noreferrer">
|
||||
<ExternalLink /> {t("Открыть продукт")}
|
||||
</a>
|
||||
</Button>
|
||||
</div>
|
||||
) : check ? (
|
||||
<div className="flex flex-wrap items-center gap-x-4 gap-y-2">
|
||||
<div className="flex min-w-0 flex-1 flex-col gap-0.5">
|
||||
<span className="text-[15px] font-semibold">{t("Версия для проверки готова")}</span>
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{t("Пока её видите только вы:")} <span className="font-mono text-foreground">{host(check.url)}</span> · {t("обновлена {when}.", { when: ago(check.at, t) })} {t("Посмотрите — и, если всё хорошо,")} {showAll}
|
||||
</span>
|
||||
</div>
|
||||
<Button asChild variant="default">
|
||||
<a href={check.url} target="_blank" rel="noreferrer">
|
||||
<ExternalLink /> {t("Посмотреть")}
|
||||
</a>
|
||||
</Button>
|
||||
</div>
|
||||
) : doneStories === 0 ? null : (
|
||||
<div className="flex flex-col gap-0.5">
|
||||
<span className="text-[15px] font-semibold">{t("Готово {tasks}: {n}", { tasks: task("genPl"), n: doneStories })}</span>
|
||||
) : 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">
|
||||
<Hourglass className="size-4 text-info" /> {t("Готовим ссылку на продукт")}
|
||||
</span>
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{engineer
|
||||
? t("Этот проект пока не открывается по ссылке как сайт. Что получилось — на странице каждой готовой {task}, вкладка «Результат», и во вкладке «Код». Хотите открывать продукт по ссылке — попросите аналитика в чате: «сделай, чтобы продукт открывался по ссылке».", { task: task("gen") })
|
||||
: t("Этот проект пока не открывается по ссылке как сайт. Что получилось — на странице каждой готовой {task}, вкладка «Результат». Хотите открывать продукт по ссылке — попросите аналитика в чате: «сделай, чтобы продукт открывался по ссылке».", { task: task("gen") })}
|
||||
{product.fix ? (
|
||||
<>
|
||||
{product.fix.working ? t("Агент уже этим занят:") : t("Это первая в очереди — агент возьмёт её сам:")} <Link href={`/t/${product.fix.key}`}>{t("{task} {key}", { task: task("nom"), key: product.fix.key })}</Link>. {t("Ссылка появится здесь, делать ничего не нужно.")}
|
||||
</>
|
||||
) : product.preparing ? (
|
||||
t("Продукт запускается — ссылка появится здесь через несколько минут.")
|
||||
) : (
|
||||
t("Ссылка появится здесь сама — делать ничего не нужно. Что уже получилось — на странице каждой готовой {task}.", { task: task("gen") })
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
) : null}
|
||||
{link && product.broken && (
|
||||
<p className="m-0 flex flex-wrap items-center gap-2 text-sm" role="status">
|
||||
<Wrench className="size-4 text-warn" />
|
||||
{t("Последнее обновление не запустилось — по ссылке открывается прежняя версия. Чиним.")}
|
||||
{product.fix && <Link href={`/t/${product.fix.key}`}>{t("{task} {key}", { task: task("nom"), key: product.fix.key })}</Link>}
|
||||
</p>
|
||||
)}
|
||||
{live && check && (
|
||||
<p className="m-0 flex flex-wrap items-center gap-2 text-sm">
|
||||
@ -108,7 +126,7 @@ export async function ProductCard({
|
||||
<a href={check.url} target="_blank" rel="noreferrer">
|
||||
{host(check.url)}
|
||||
</a>
|
||||
{check.stories.length > 0 && <span className="text-muted-foreground">({check.stories.slice(0, 6).join(", ")})</span>} — {showAll}
|
||||
{check.stories.length > 0 && <span className="text-muted-foreground">({check.stories.slice(0, 6).join(", ")})</span>} — {publish === "auto" ? t("Peppa FACTORY покажет её всем сама, когда задачи будут приняты.") : showAll}
|
||||
</p>
|
||||
)}
|
||||
{open.length > 0 && (
|
||||
|
||||
@ -49,11 +49,15 @@ function ProjectRow({ p, t, w }: { p: ProjectProgress; t: Translator; w: Words }
|
||||
<Key href={`/p/${p.key}`}>{p.key}</Key>
|
||||
<Link href={`/p/${p.key}`} className="min-w-0 truncate font-medium text-foreground hover:no-underline">{p.name}</Link>
|
||||
{p.ownerLogin && <span className="rounded-full border px-2 text-[11px] text-muted-foreground">{p.ownerLogin}</span>}
|
||||
{p.product && (
|
||||
<a href={p.product.url} target="_blank" rel="noreferrer" className="rounded-full border border-ok/50 bg-ok/10 px-2 text-[11px] font-medium text-foreground hover:no-underline" title={p.product.live ? t("Рабочая версия, открыта для всех") : t("Версия для проверки")}>
|
||||
{p.product.live ? t("Открыть продукт") : t("Версия для проверки")} ↗
|
||||
{p.product ? (
|
||||
<a href={p.product.url} target="_blank" rel="noreferrer" className="rounded-full border border-ok/60 bg-ok/15 px-3 py-0.5 text-xs font-semibold text-foreground hover:bg-ok/25 hover:no-underline" title={p.product.live ? t("Рабочая версия, открыта для всех") : t("Версия для проверки — пока её видите только вы")}>
|
||||
{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>
|
||||
) : null}
|
||||
<span className="ml-auto text-xs text-muted-foreground">
|
||||
{p.total ? (
|
||||
<>
|
||||
|
||||
26
apps/web/components/PublishPanel.tsx
Normal file
26
apps/web/components/PublishPanel.tsx
Normal file
@ -0,0 +1,26 @@
|
||||
// PEP-145: «Показывать всем: сам / по кнопке» in «⋯ Настройки проекта» — whether an accepted
|
||||
// version reaches everyone by itself or waits for the «Показать всем» button.
|
||||
import { PUBLISH_MODE_HINT, PUBLISH_MODE_RU, PUBLISH_MODES, type PublishMode } from "@peppa/core";
|
||||
import { setPublishModeAction } from "@/app/(app)/actions";
|
||||
import { Hidden } from "@/components/cards";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { getT } from "@/lib/i18n";
|
||||
|
||||
export async function PublishPanel({ projectId, mode, back }: { projectId: number; mode: PublishMode; back: string }) {
|
||||
const t = await getT();
|
||||
return (
|
||||
<div className="flex flex-col gap-3">
|
||||
<div className="flex flex-wrap gap-2" role="group" aria-label={t("Показывать всем")}>
|
||||
{PUBLISH_MODES.map((m) => (
|
||||
<form key={m} action={setPublishModeAction}>
|
||||
<Hidden fields={{ projectId, mode: m, back }} />
|
||||
<Button size="sm" variant={mode === m ? "default" : "outline"} aria-pressed={mode === m} title={t.text(PUBLISH_MODE_HINT[m])}>
|
||||
{t.text(PUBLISH_MODE_RU[m])}
|
||||
</Button>
|
||||
</form>
|
||||
))}
|
||||
</div>
|
||||
<p className="m-0 text-xs text-muted-foreground">{t.text(PUBLISH_MODE_HINT[mode])}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@ -10,7 +10,7 @@ import { getT } from "@/lib/i18n";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { acceptStoryAction, fixStoryAction } from "@/app/(app)/actions";
|
||||
|
||||
export async function StoryProduct({ view, taskKey, taskStatus, preview, questions, back }: { view: StoryProductView; taskKey: string; taskStatus: string; preview: ReviewPreview; questions: Question[]; back: string }) {
|
||||
export async function StoryProduct({ view, taskKey, taskStatus, preview, questions, back, productUrl = null }: { view: StoryProductView; taskKey: string; taskStatus: string; preview: ReviewPreview; questions: Question[]; back: string; /** PEP-145: the project's product — where an accepted story is seen. */ productUrl?: string | null }) {
|
||||
const t = await getT();
|
||||
const pct = view.step ? Math.round(((view.step.n - 1) / view.step.m) * 100) : 0;
|
||||
return (
|
||||
@ -32,6 +32,17 @@ export async function StoryProduct({ view, taskKey, taskStatus, preview, questio
|
||||
)}
|
||||
</div>
|
||||
|
||||
{!preview.previewUrl && productUrl && taskStatus === "done" && (
|
||||
<div className="flex flex-col gap-2">
|
||||
<Button asChild variant="outline" className="self-start">
|
||||
<a href={productUrl} target="_blank" rel="noreferrer">
|
||||
<Eye />
|
||||
{t("Посмотреть результат")}
|
||||
</a>
|
||||
</Button>
|
||||
<p className="m-0 text-xs text-muted-foreground">{t("Откроется продукт проекта — в нём уже есть эта задача.")}</p>
|
||||
</div>
|
||||
)}
|
||||
{preview.previewUrl && (
|
||||
<div className="flex flex-col gap-2">
|
||||
<Button asChild variant={view.canAccept ? "default" : "outline"} className="self-start">
|
||||
|
||||
@ -16,6 +16,8 @@ export interface ProductHelpText {
|
||||
question: string;
|
||||
/** PEP-143: what to do when Peppa itself misbehaves. */
|
||||
problem: string;
|
||||
/** PEP-145: where the product is. */
|
||||
product: string;
|
||||
more: string;
|
||||
moreLink: string;
|
||||
}
|
||||
@ -59,6 +61,7 @@ export const PRODUCT_HELP: Record<HelpLang, ProductHelpText> = {
|
||||
],
|
||||
question: "Агент задал вопрос? Он появится на Главной и в Telegram. Ответьте кнопкой или своими словами — агент продолжит работу.",
|
||||
problem: "Что-то не работает в самой Peppa FACTORY? Нажмите «Сообщить о проблеме» внизу любой страницы: напишите, что случилось, и приложите скриншот. В Telegram то же самое — отправьте боту /problem. Что стало с обращением, видно в разделе «Обращения».",
|
||||
product: "Где посмотреть продукт? На странице проекта и на Главной есть кнопка «Открыть продукт». Ссылка появляется сама, в первый же день проекта; если её пока нет, на её месте написано, что происходит, — делать ничего не нужно.",
|
||||
more: "Хотите видеть всё, что делают агенты, и полный справочник? Включите вид «Инженер».",
|
||||
moreLink: "Открыть Настройки",
|
||||
},
|
||||
@ -97,6 +100,7 @@ export const PRODUCT_HELP: Record<HelpLang, ProductHelpText> = {
|
||||
],
|
||||
question: "Агент сұрақ қойды ма? Ол Басты бетте және Telegram-да пайда болады. Батырмамен немесе өз сөзіңізбен жауап беріңіз — агент жұмысын жалғастырады.",
|
||||
problem: "Peppa FACTORY-дің өзінде бірдеңе жұмыс істемей тұр ма? Кез келген беттің төменгі жағындағы «Мәселе туралы хабарлау» батырмасын басыңыз: не болғанын жазып, скриншот тіркеңіз. Telegram-да да солай — ботқа /problem жіберіңіз. Өтінішіңіздің не болғаны «Өтініштер» бөлімінде көрінеді.",
|
||||
product: "Өнімді қайдан көруге болады? Жоба бетінде және Басты бетте «Өнімді ашу» батырмасы бар. Сілтеме жобаның бірінші күнінде-ақ өзі пайда болады; әзірге жоқ болса, оның орнында не болып жатқаны жазылған — ештеңе істеудің қажеті жоқ.",
|
||||
more: "Агенттердің барлық іс-әрекетін және толық анықтамалықты көргіңіз келе ме? «Инженер» көрінісін қосыңыз.",
|
||||
moreLink: "Баптауларды ашу",
|
||||
},
|
||||
@ -135,6 +139,7 @@ export const PRODUCT_HELP: Record<HelpLang, ProductHelpText> = {
|
||||
],
|
||||
question: "Did an agent ask a question? It appears on Home and in Telegram. Answer with a button or in your own words — the agent carries on.",
|
||||
problem: "Is something not working in Peppa FACTORY itself? Press “Report a problem” at the bottom of any page: write what happened and attach a screenshot. In Telegram it is the same — send /problem to the bot. What became of your report is shown in “Reports”.",
|
||||
product: "Where is the product? The project page and Home have an «Open product» button. The link appears by itself on the project's first day; if it is not there yet, the same place says what is happening — you don't need to do anything.",
|
||||
more: "Want to see everything the agents do and the full reference? Turn on the “Engineer” view.",
|
||||
moreLink: "Open Settings",
|
||||
},
|
||||
|
||||
@ -71,7 +71,7 @@ export async function projectProduct(db: Db, projectId: number): Promise<Project
|
||||
*/
|
||||
export async function productLookLine(db: Db, projectId: number): Promise<string> {
|
||||
const product = (await productUrls(db, [projectId])).get(projectId);
|
||||
return product ? `\n${tr("Посмотреть: {url} — продукт обновится через несколько минут", { url: product.url })}` : "";
|
||||
return product ? `\n${tr("Продукт обновится через несколько минут: {url}", { url: product.url })}` : "";
|
||||
}
|
||||
|
||||
/** Product links of several projects at once (the Home page): projectId → URL of the best version. */
|
||||
|
||||
@ -392,4 +392,32 @@ export const project: Dict = {
|
||||
"Стори без эпика": "Stories without an epic",
|
||||
"Переименовать эпик, изменить описание или убрать в архив — «⋯ Настройки проекта → Эпики». Эпик стори меняется кнопкой «Изменить» на её странице.":
|
||||
"Rename an epic, change its description or archive it in «⋯ Project settings → Epics». A story's epic is changed with the «Edit» button on its page.",
|
||||
// PEP-145: the product always opens by a link
|
||||
"Показывать всем": "Show to everyone",
|
||||
"Ваш продукт готов — пока его видите только вы": "Your product is ready — only you can see it for now",
|
||||
"Адрес:": "Address:",
|
||||
"Когда задачи этой версии будут приняты, Peppa FACTORY сама покажет её всем.": "Once the tasks of this version are accepted, Peppa FACTORY will show it to everyone by itself.",
|
||||
"Готовим ссылку на продукт": "Preparing the link to your product",
|
||||
"Агент уже этим занят:": "An agent is already on it:",
|
||||
"Это первая в очереди — агент возьмёт её сам:": "It is first in line — an agent will take it by itself:",
|
||||
"Ссылка появится здесь, делать ничего не нужно.": "The link will appear here; you don't need to do anything.",
|
||||
"Продукт запускается — ссылка появится здесь через несколько минут.": "The product is starting — the link will appear here in a few minutes.",
|
||||
"Ссылка появится здесь сама — делать ничего не нужно. Что уже получилось — на странице каждой готовой {task}.": "The link will appear here by itself — you don't need to do anything. What is already done is on the page of each finished {task}.",
|
||||
"Последнее обновление не запустилось — по ссылке открывается прежняя версия. Чиним.": "The latest update did not start — the link opens the previous version. We are fixing it.",
|
||||
"Peppa FACTORY покажет её всем сама, когда задачи будут приняты.": "Peppa FACTORY will show it to everyone by itself once the tasks are accepted.",
|
||||
"Версия для проверки — пока её видите только вы": "A version to check — only you can see it for now",
|
||||
"Посмотреть результат": "See the result",
|
||||
"Откроется продукт проекта — в нём уже есть эта задача.": "The project's product will open — this task is already in it.",
|
||||
"Сам": "Automatically",
|
||||
"По кнопке": "By the button",
|
||||
"Когда все задачи новой версии приняты, Peppa FACTORY сама показывает её всем пользователям.": "When all tasks of a new version are accepted, Peppa FACTORY shows it to all users by itself.",
|
||||
"Новую версию сначала видите только вы; всем она открывается по кнопке «Показать всем».": "Only you see a new version at first; it opens to everyone with the «Show to everyone» button.",
|
||||
"Показывать сразу": "Show right away",
|
||||
"Оставить по кнопке": "Keep the button",
|
||||
"Показывать всем: выберите «Сам» или «По кнопке».": "Show to everyone: choose «Automatically» or «By the button».",
|
||||
"Продукт обновится через несколько минут: {url}": "The product will update in a few minutes: {url}",
|
||||
"(неактуально: Peppa FACTORY сама показывает эту версию всем)": "(no longer relevant: Peppa FACTORY is showing this version to everyone by itself)",
|
||||
"💡 {project}: показывать новые версии продукта всем пользователям сразу?": "💡 {project}: show new versions of the product to all users right away?",
|
||||
"Сейчас новую версию сначала видите только вы, а всем она открывается по кнопке «Показать всем». Можно иначе: как только задачи приняты, Peppa FACTORY сама обновляет продукт для всех.": "Right now only you see a new version at first, and it opens to everyone with the «Show to everyone» button. It can work differently: as soon as the tasks are accepted, Peppa FACTORY updates the product for everyone by itself.",
|
||||
"Изменить выбор можно в настройках проекта.": "You can change this in the project settings.",
|
||||
};
|
||||
|
||||
@ -337,4 +337,32 @@ export const project: Dict = {
|
||||
"На доске": "Тақтада",
|
||||
"Стори без эпика": "Эпиксіз сторилер",
|
||||
"Переименовать эпик, изменить описание или убрать в архив — «⋯ Настройки проекта → Эпики». Эпик стори меняется кнопкой «Изменить» на её странице.": "Эпиктің атын, сипаттамасын өзгерту немесе архивке жіберу — «⋯ Жоба баптаулары → Эпиктер». Сторидің эпигі оның бетіндегі «Өзгерту» батырмасымен өзгертіледі.",
|
||||
// PEP-145: the product always opens by a link
|
||||
"Показывать всем": "Барлығына көрсету",
|
||||
"Ваш продукт готов — пока его видите только вы": "Өніміңіз дайын — әзірге оны тек сіз көресіз",
|
||||
"Адрес:": "Мекенжайы:",
|
||||
"Когда задачи этой версии будут приняты, Peppa FACTORY сама покажет её всем.": "Осы нұсқаның тапсырмалары қабылданғанда, Peppa FACTORY оны барлығына өзі көрсетеді.",
|
||||
"Готовим ссылку на продукт": "Өнімге сілтеме дайындалып жатыр",
|
||||
"Агент уже этим занят:": "Агент осымен айналысып жатыр:",
|
||||
"Это первая в очереди — агент возьмёт её сам:": "Ол кезекте бірінші — агент оны өзі алады:",
|
||||
"Ссылка появится здесь, делать ничего не нужно.": "Сілтеме осы жерде пайда болады, ештеңе істеудің қажеті жоқ.",
|
||||
"Продукт запускается — ссылка появится здесь через несколько минут.": "Өнім іске қосылып жатыр — сілтеме осы жерде бірнеше минуттан кейін пайда болады.",
|
||||
"Ссылка появится здесь сама — делать ничего не нужно. Что уже получилось — на странице каждой готовой {task}.": "Сілтеме осы жерде өзі пайда болады — ештеңе істеудің қажеті жоқ. Дайын нәтиже — әр дайын {task} бетінде.",
|
||||
"Последнее обновление не запустилось — по ссылке открывается прежняя версия. Чиним.": "Соңғы жаңарту іске қосылмады — сілтеме бойынша алдыңғы нұсқа ашылады. Жөндеп жатырмыз.",
|
||||
"Peppa FACTORY покажет её всем сама, когда задачи будут приняты.": "Тапсырмалар қабылданғанда, Peppa FACTORY оны барлығына өзі көрсетеді.",
|
||||
"Версия для проверки — пока её видите только вы": "Тексеруге арналған нұсқа — әзірге оны тек сіз көресіз",
|
||||
"Посмотреть результат": "Нәтижені қарау",
|
||||
"Откроется продукт проекта — в нём уже есть эта задача.": "Жобаның өнімі ашылады — бұл тапсырма онда бар.",
|
||||
"Сам": "Өзі",
|
||||
"По кнопке": "Батырмамен",
|
||||
"Когда все задачи новой версии приняты, Peppa FACTORY сама показывает её всем пользователям.": "Жаңа нұсқаның барлық тапсырмалары қабылданғанда, Peppa FACTORY оны барлық пайдаланушыларға өзі көрсетеді.",
|
||||
"Новую версию сначала видите только вы; всем она открывается по кнопке «Показать всем».": "Жаңа нұсқаны алдымен тек сіз көресіз; барлығына ол «Барлығына көрсету» батырмасымен ашылады.",
|
||||
"Показывать сразу": "Бірден көрсету",
|
||||
"Оставить по кнопке": "Батырмамен қалдыру",
|
||||
"Показывать всем: выберите «Сам» или «По кнопке».": "Барлығына көрсету: «Өзі» немесе «Батырмамен» дегенді таңдаңыз.",
|
||||
"Продукт обновится через несколько минут: {url}": "Өнім бірнеше минутта жаңарады: {url}",
|
||||
"(неактуально: Peppa FACTORY сама показывает эту версию всем)": "(өзекті емес: Peppa FACTORY бұл нұсқаны барлығына өзі көрсетіп жатыр)",
|
||||
"💡 {project}: показывать новые версии продукта всем пользователям сразу?": "💡 {project}: өнімнің жаңа нұсқаларын барлық пайдаланушыларға бірден көрсету керек пе?",
|
||||
"Сейчас новую версию сначала видите только вы, а всем она открывается по кнопке «Показать всем». Можно иначе: как только задачи приняты, Peppa FACTORY сама обновляет продукт для всех.": "Қазір жаңа нұсқаны алдымен тек сіз көресіз, ал барлығына ол «Барлығына көрсету» батырмасымен ашылады. Басқаша да болады: тапсырмалар қабылданған бойда Peppa FACTORY өнімді барлығы үшін өзі жаңартады.",
|
||||
"Изменить выбор можно в настройках проекта.": "Таңдауды жоба баптауларында өзгертуге болады.",
|
||||
};
|
||||
|
||||
@ -28,6 +28,9 @@ Object.assign(process.env, {
|
||||
// Unreachable on purpose: rules come from the cache/local template fallback.
|
||||
GITEA_URL: "http://127.0.0.1:9",
|
||||
GITEA_TOKEN: "",
|
||||
// PEP-145: the watchdog files «Продукт должен открываться по ссылке» for any project with
|
||||
// accepted stories and no deploy — every suite's projects. product-link.test.ts turns it on.
|
||||
PEPPA_PRODUCT_LINK: "off",
|
||||
});
|
||||
mkdirSync(process.env.PEPPA_HOME!, { recursive: true });
|
||||
|
||||
|
||||
@ -4,7 +4,7 @@ import { readFileSync } from "node:fs";
|
||||
import { describe, test } from "node:test";
|
||||
import { HELP_LANGS, PRODUCT_HELP, type ProductHelpText } from "@peppa/core";
|
||||
|
||||
const strings = (t: ProductHelpText) => [t.title, t.lead, t.question, t.more, t.moreLink, ...t.sections.flatMap((s) => [s.title, ...s.steps, s.note])];
|
||||
const strings = (t: ProductHelpText) => [t.title, t.lead, t.question, t.product, t.more, t.moreLink, ...t.sections.flatMap((s) => [s.title, ...s.steps, s.note])];
|
||||
|
||||
/** «Нельзя» column of docs/glossary.md. */
|
||||
function forbidden(): string[] {
|
||||
|
||||
241
packages/testkit/test/product-link.test.ts
Normal file
241
packages/testkit/test/product-link.test.ts
Normal file
@ -0,0 +1,241 @@
|
||||
// PEP-145, spec product-link: the product of a project always opens by a link — the system
|
||||
// story when there is no link, «Показывать всем: сам / по кнопке», the card's honest status and
|
||||
// the link in the message about an accepted story. Provisioning scenarios — web.test.ts.
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtempSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { after, before, describe, test } from "node:test";
|
||||
import { questions, releases } from "@peppa/db";
|
||||
import { and, eq, isNull } from "drizzle-orm";
|
||||
import { core, db, runner, teardown } from "./helpers.ts";
|
||||
import { MockGitea } from "../src/mock-gitea.ts";
|
||||
|
||||
process.env.PEPPA_SECRET = "mock-secret-for-tests";
|
||||
delete process.env.PEPPA_PRODUCT_LINK;
|
||||
const gitea = new MockGitea(join(mkdtempSync(join(tmpdir(), "peppa-plink-")), "gitea"));
|
||||
const BOT = { id: 81, login: "peppa-bot", token: "mock-token-bot" };
|
||||
|
||||
before(async () => {
|
||||
await gitea.start();
|
||||
process.env.GITEA_URL = gitea.url;
|
||||
process.env.GITEA_TOKEN = BOT.token;
|
||||
gitea.addUser(BOT);
|
||||
});
|
||||
after(async () => {
|
||||
await gitea.stop();
|
||||
await teardown();
|
||||
});
|
||||
|
||||
let n = 0;
|
||||
async function proj() {
|
||||
n++;
|
||||
const slug = `mock-shop-${n}`;
|
||||
const p = await core.createProject(db, { slug, key: `SH${String.fromCharCode(64 + n)}`, name: `Магазин ${n}`, giteaOwner: BOT.login, giteaRepo: slug, workspacePath: `/tmp/${slug}` });
|
||||
gitea.addRepo(BOT.login, slug, { files: { "README.md": "# shop\n" } });
|
||||
return p;
|
||||
}
|
||||
const story = async (projectId: number, title: string, status?: "done" | "review") => {
|
||||
const ref = await core.createTask(db, { projectId, title });
|
||||
if (status) await core.updateTask(db, ref, { status });
|
||||
return ref;
|
||||
};
|
||||
const rel = (projectId: number, env: "preview" | "staging" | "prod", sha: string, status: "healthy" | "failed" | "rolled_back" | "deploying" = "healthy", extra: Partial<typeof releases.$inferInsert> = {}) =>
|
||||
db.insert(releases).values({ projectId, env, sha, status, host: `shop-${env}.mock.test`, ...extra }).returning().then((r) => r[0]!);
|
||||
const linkTasks = async (projectId: number) => (await core.listTasks(db, { projectId })).filter((t) => t.title === core.PRODUCT_LINK_TITLE);
|
||||
const openQuestions = (projectId: number) => db.select().from(questions).where(and(eq(questions.projectId, projectId), isNull(questions.answeredAt)));
|
||||
const HOUR = 3_600_000;
|
||||
|
||||
describe("PEP-145: системная задача при отсутствии ссылки", () => {
|
||||
test("Принятые задачи без выкладки", async () => {
|
||||
const p = await proj();
|
||||
await story(p.id, "Каталог", "done");
|
||||
await story(p.id, "Корзина", "done");
|
||||
const waiting = await story(p.id, "Оплата");
|
||||
await runner.productLinkTick(db);
|
||||
const backlog = await core.listTasks(db, { projectId: p.id, statuses: ["backlog"] });
|
||||
assert.equal(backlog[0]!.title, "Продукт должен открываться по ссылке", "first in the backlog");
|
||||
assert.match(backlog[0]!.description ?? "", /принято задач: 2/);
|
||||
assert.equal((await runner.readyBacklog(db, p.id))[0]!.id, backlog[0]!.id, "the dispatcher takes it before the rest");
|
||||
assert.ok(backlog.some((t) => t.id === waiting.task.id));
|
||||
});
|
||||
|
||||
test("Упавшая выкладка", async () => {
|
||||
const p = await proj();
|
||||
await rel(p.id, "staging", "aaa1111", "failed", { reason: "сборка образа не удалась", logTail: "step 3/7: npm ERR! missing script: build" });
|
||||
await runner.productLinkTick(db);
|
||||
const [t] = await linkTasks(p.id);
|
||||
assert.ok(t, "filed without any accepted story: the deploy itself failed");
|
||||
assert.match(t.description ?? "", /сборка образа не удалась/);
|
||||
assert.match(t.description ?? "", /missing script: build/, "the log of the failure is in the story");
|
||||
});
|
||||
|
||||
test("Вторая задача не заводится", async () => {
|
||||
const p = await proj();
|
||||
await story(p.id, "Каталог", "done");
|
||||
await runner.productLinkTick(db);
|
||||
await runner.productLinkTick(db);
|
||||
await runner.productLinkTick(db, { now: new Date(Date.now() + 30 * HOUR) });
|
||||
assert.equal((await linkTasks(p.id)).length, 1, "one open story, however much time passes");
|
||||
});
|
||||
|
||||
test("Не чаще раза в сутки", async () => {
|
||||
const p = await proj();
|
||||
await story(p.id, "Каталог", "done");
|
||||
await runner.productLinkTick(db);
|
||||
const [t] = await linkTasks(p.id);
|
||||
await core.updateTask(db, await core.resolveTask(db, `${p.key}-${t!.number}`), { status: "done" });
|
||||
await rel(p.id, "staging", "bbb2222", "rolled_back", { reason: "проверка /healthz не прошла за 120 с" });
|
||||
await runner.productLinkTick(db, { now: new Date(Date.now() + 2 * HOUR) });
|
||||
assert.equal((await linkTasks(p.id)).length, 1, "2 hours after the first: nothing new");
|
||||
await runner.productLinkTick(db, { now: new Date(Date.now() + 25 * HOUR) });
|
||||
assert.equal((await linkTasks(p.id)).length, 2, "a day later the product still has no healthy update");
|
||||
});
|
||||
|
||||
test("Здоровая версия или идущее обновление: задача не нужна", async () => {
|
||||
const healthy = await proj();
|
||||
await story(healthy.id, "Каталог", "done");
|
||||
await rel(healthy.id, "staging", "ccc3333");
|
||||
const starting = await proj();
|
||||
await story(starting.id, "Каталог", "done");
|
||||
await rel(starting.id, "staging", "ddd4444", "deploying");
|
||||
const empty = await proj();
|
||||
await story(empty.id, "Каталог");
|
||||
await runner.productLinkTick(db);
|
||||
for (const p of [healthy, starting, empty]) assert.equal((await linkTasks(p.id)).length, 0, p.key);
|
||||
});
|
||||
});
|
||||
|
||||
/** The commit a version of the project runs: the head of its repository in mock-gitea. */
|
||||
const head = (p: { giteaOwner: string; giteaRepo: string }) => gitea.sha(p.giteaOwner, p.giteaRepo, "main");
|
||||
|
||||
describe("PEP-145: показ всем без нажатий", () => {
|
||||
const stagingHealthy = (p: Awaited<ReturnType<typeof proj>>, sha: string, commits: string[]) =>
|
||||
runner.recordRelease(db, p, { env: "staging", sha, status: "healthy", host: "shop-staging.mock.test", commits });
|
||||
|
||||
test("Режим «сам»", async () => {
|
||||
const p = await proj();
|
||||
await core.setPublishMode(db, p.id, "auto");
|
||||
const t = await story(p.id, "Каталог", "done");
|
||||
await stagingHealthy(p, head(p), [`Merge task/${t.key} into main`]);
|
||||
const [prod] = await db.select().from(releases).where(and(eq(releases.projectId, p.id), eq(releases.env, "prod")));
|
||||
assert.equal(prod?.status, "deploying");
|
||||
assert.equal(prod?.sha, head(p), "the same commit goes to everyone");
|
||||
assert.equal(prod?.deployedBy, "Peppa FACTORY");
|
||||
const tag = gitea.repo(p.giteaOwner, p.giteaRepo).tags.at(-1)!;
|
||||
assert.match(tag.name, /^deploy-prod-/);
|
||||
assert.ok(!(await openQuestions(p.id)).some((q) => /Показать её всем/.test(q.text)), "no question about it");
|
||||
});
|
||||
|
||||
test("Режим «по кнопке»", async () => {
|
||||
const p = await proj();
|
||||
await core.setPublishMode(db, p.id, "button");
|
||||
const t = await story(p.id, "Каталог", "done");
|
||||
await stagingHealthy(p, head(p), [`Merge task/${t.key} into main`]);
|
||||
await runner.productLinkTick(db);
|
||||
assert.equal((await db.select().from(releases).where(and(eq(releases.projectId, p.id), eq(releases.env, "prod")))).length, 0);
|
||||
const [q] = await openQuestions(p.id);
|
||||
assert.deepEqual(q?.options, [runner.PROD_OPTION]);
|
||||
assert.equal(runner.PROD_OPTION, "🚀 Показать всем");
|
||||
});
|
||||
|
||||
test("Не все задачи приняты", async () => {
|
||||
const p = await proj();
|
||||
await core.setPublishMode(db, p.id, "auto");
|
||||
const t = await story(p.id, "Оплата", "review");
|
||||
await stagingHealthy(p, head(p), [`Merge task/${t.key} into main`]);
|
||||
await runner.productLinkTick(db);
|
||||
const prods = () => db.select().from(releases).where(and(eq(releases.projectId, p.id), eq(releases.env, "prod")));
|
||||
assert.equal((await prods()).length, 0, "the story is still in review");
|
||||
await core.updateTask(db, t, { status: "done" });
|
||||
await runner.productLinkTick(db);
|
||||
assert.equal((await prods())[0]?.sha, head(p), "accepted later: the watchdog carries it through");
|
||||
await runner.productLinkTick(db);
|
||||
assert.equal((await prods()).length, 1, "once per version");
|
||||
});
|
||||
|
||||
test("Существующему проекту — предложение один раз", async () => {
|
||||
const p = await proj();
|
||||
await rel(p.id, "staging", head(p));
|
||||
await runner.productLinkTick(db);
|
||||
await runner.productLinkTick(db);
|
||||
const offers = (await openQuestions(p.id)).filter((q) => (q.options ?? []).includes(core.PUBLISH_AUTO_OPTION));
|
||||
assert.equal(offers.length, 1);
|
||||
assert.deepEqual(offers[0]!.options, ["Показывать сразу", "Оставить по кнопке"]);
|
||||
assert.equal(await core.getPublishMode(db, p.id), "button", "nothing changes until the owner chooses");
|
||||
await runner.answerAndDeliver(db, offers[0]!.id, "Показывать сразу", "web");
|
||||
assert.equal(await core.getPublishChoice(db, p.id), "auto");
|
||||
const [prod] = await db.select().from(releases).where(and(eq(releases.projectId, p.id), eq(releases.env, "prod")));
|
||||
assert.equal(prod?.sha, head(p), "the waiting version goes to everyone right away");
|
||||
});
|
||||
|
||||
test("Проект без версии для проверки предложения не получает", async () => {
|
||||
const p = await proj();
|
||||
await runner.productLinkTick(db);
|
||||
assert.equal((await openQuestions(p.id)).length, 0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("PEP-145: карточка «Ваш продукт» с честным статусом", () => {
|
||||
test("Ссылка есть", async () => {
|
||||
const p = await proj();
|
||||
await rel(p.id, "staging", "5555555eeee", "healthy", { tasks: [`${p.key}-1`] });
|
||||
await rel(p.id, "preview", "5555555eeee", "healthy", { prNumber: 1, screenshots: [{ path: "/about", file: "r1-0.png" }, { path: "/", file: "r1-1.png" }] });
|
||||
const v = await core.projectProduct(db, p.id);
|
||||
assert.equal((v.live ?? v.check)?.url, "https://shop-staging.mock.test");
|
||||
assert.equal(v.preparing, false);
|
||||
assert.equal(v.broken, false);
|
||||
assert.equal(v.shot?.n, 1, "the screenshot of the first page");
|
||||
});
|
||||
|
||||
test("Ссылки нет", async () => {
|
||||
const p = await proj();
|
||||
await story(p.id, "Каталог", "done");
|
||||
await runner.productLinkTick(db);
|
||||
const v = await core.projectProduct(db, p.id);
|
||||
assert.equal(v.live ?? v.check, null);
|
||||
assert.equal(v.preparing, true);
|
||||
assert.deepEqual(v.fix, { key: `${p.key}-2`, working: false });
|
||||
const row = (await core.progressOverview(db, -1)).mine.concat((await core.progressOverview(db, -1)).others).find((r) => r.key === p.key);
|
||||
assert.ok(!row || row.productFix === `${p.key}-2`);
|
||||
});
|
||||
|
||||
test("Выкладка упала, прошлая версия работает", async () => {
|
||||
const p = await proj();
|
||||
await rel(p.id, "staging", "6666666ffff");
|
||||
await rel(p.id, "staging", "7777777aaaa", "rolled_back", { reason: "проверка /healthz не прошла за 120 с" });
|
||||
await runner.productLinkTick(db);
|
||||
const v = await core.projectProduct(db, p.id);
|
||||
assert.equal(v.check?.url, "https://shop-staging.mock.test", "the earlier version still opens");
|
||||
assert.equal(v.broken, true);
|
||||
assert.equal(v.fix?.key, `${p.key}-1`, "and the fix is on its way");
|
||||
});
|
||||
|
||||
test("Новый проект: выкладка заглушки идёт — «Готовим ссылку»", async () => {
|
||||
const p = await proj();
|
||||
await rel(p.id, "staging", "8888888bbbb", "deploying");
|
||||
const v = await core.projectProduct(db, p.id);
|
||||
assert.equal(v.preparing, true);
|
||||
assert.equal(v.fix, null);
|
||||
});
|
||||
});
|
||||
|
||||
describe("PEP-145: ссылка на продукт у принятой задачи", () => {
|
||||
test("Сообщение о принятой задаче", async () => {
|
||||
const p = await proj();
|
||||
await rel(p.id, "prod", "9999999cccc", "healthy", { host: "shop-prod.mock.test" });
|
||||
assert.match(await core.productLookLine(db, p.id), /https:\/\/shop-prod\.mock\.test/);
|
||||
});
|
||||
|
||||
test("Ссылки нет", async () => {
|
||||
const p = await proj();
|
||||
assert.equal(await core.productLookLine(db, p.id), "");
|
||||
});
|
||||
});
|
||||
|
||||
describe("PEP-145: тексты", () => {
|
||||
test("описание системной задачи — без слов из «Нельзя» в части для владельца", () => {
|
||||
const text = core.productLinkDescription({ doneStories: 3 }).split("## Для агента")[0]!;
|
||||
for (const word of ["деплой", "выкат", "релиз", "staging", "прод ", "репозитор"]) assert.ok(!text.toLowerCase().includes(word), word);
|
||||
});
|
||||
});
|
||||
@ -17,7 +17,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 });
|
||||
assert.deepEqual(await core.projectProduct(db, p.id), { live: null, check: null, doneStories: 0, fix: null, broken: false, preparing: false, shot: null });
|
||||
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);
|
||||
|
||||
@ -102,6 +102,21 @@ describe("project provisioning", () => {
|
||||
assert.match(execFileSync("git", ["-C", p.workspacePath, "config", "--get-all", "credential.helper"], { encoding: "utf8" }), /git-credential-peppa/);
|
||||
});
|
||||
|
||||
// PEP-145, spec product-link: «Новый проект получает заглушку и первую выкладку».
|
||||
test("new repo: the product placeholder, deploy settings and the tag of the first deploy", async () => {
|
||||
const p = await core.getProject(db, "MDEMO");
|
||||
const files = gitea.files(ALICE.login, "mock-demo");
|
||||
for (const f of ["Dockerfile", "product/server.mjs", "product/index.html", "deploy/compose.yml"]) assert.ok(files.includes(f), `${f} pushed`);
|
||||
assert.match(gitea.show(ALICE.login, "mock-demo", "product/index.html"), /Продукт создаётся/);
|
||||
const cfg = JSON.parse(gitea.show(ALICE.login, "mock-demo", ".peppa/project.json"));
|
||||
assert.deepEqual(cfg.deploy, { compose: "deploy/compose.yml", service: "web", port: 3000, health: "/healthz" });
|
||||
const tags = gitea.repo(ALICE.login, "mock-demo").tags;
|
||||
assert.equal(tags.length, 1);
|
||||
assert.match(tags[0]!.name, /^deploy-staging-\d+$/);
|
||||
assert.equal(tags[0]!.target, execFileSync("git", ["-C", p.workspacePath, "rev-parse", "HEAD"], { encoding: "utf8" }).trim(), "the head of the default branch");
|
||||
assert.equal(await core.getPublishChoice(db, p.id), "auto", "a new project shows accepted versions to everyone by itself");
|
||||
});
|
||||
|
||||
test("PEP-142: the same form sent twice leads to the project just created, not to «slug is taken»", async () => {
|
||||
const again = await runner.justCreatedProject(db, { slug: "Mock-Demo", key: "mdemo", ownerId: alice.id });
|
||||
assert.equal(again?.key, "MDEMO", "the owner's second click finds the project made a moment ago");
|
||||
@ -147,6 +162,10 @@ describe("project provisioning", () => {
|
||||
for (const f of ["src/app.ts", ".peppa/project.json", ".mcp.json", "openspec/config.yaml"]) assert.ok(files.includes(f), f);
|
||||
assert.ok(files.some((f) => f.startsWith(".agents/skills/openspec-")), "openspec init ran");
|
||||
assert.ok(readFileSync(join(p.workspacePath, "src/app.ts"), "utf8"));
|
||||
// PEP-145, spec product-link: «Существующий репозиторий не получает заглушку».
|
||||
assert.ok(!files.includes("Dockerfile") && !files.some((f) => f.startsWith("product/")), "no placeholder in a repository with its own code");
|
||||
assert.equal(JSON.parse(gitea.show(ALICE.login, "mock-legacy", ".peppa/project.json")).deploy, undefined);
|
||||
assert.deepEqual(gitea.repo(ALICE.login, "mock-legacy").tags, []);
|
||||
});
|
||||
|
||||
test("existing repo without admin rights is refused", async () => {
|
||||
|
||||
Loading…
Reference in New Issue
Block a user