PEP-142: «Создать проект» is disabled while the project is being created; the same form sent twice opens the project instead of «slug is taken»

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Асель 2026-11-16 10:11:21 +05:00
parent f0660d0c95
commit 0412716cb5
6 changed files with 27 additions and 3 deletions

View File

@ -62,7 +62,7 @@ import {
} 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, provisionProject, 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, fixStory, budgetChanged, resolveTaskById, deployProd, bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, grantRepoAccess, moveTask, justCreatedProject, provisionProject, 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";
@ -331,6 +331,9 @@ export async function messageSession(f: FormData) {
export async function createProjectAction(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
// PEP-142: a second click on «Создать проект» while the first request was still working.
const again = await justCreatedProject(db, { slug: str(f, "slug"), key: str(f, "key"), ownerId: user.id });
if (again) return `/p/${again.key}?created=1`;
const p = await provisionProject(db, {
...(await projectNamespace(db, user, str(f, "owner"))), // PEP-68: local user → peppa-bot
slug: str(f, "slug").toLowerCase(),

View File

@ -2,9 +2,9 @@ import { giteaForUser, isLocalUser, type GiteaOrg } from "@peppa/core";
import { loadEnv } from "@peppa/shared";
import { Flash, PageHeader } from "@/components/common";
import { Hidden } from "@/components/cards";
import { Button } from "@/components/ui/button";
import { Label, NativeSelect } from "@/components/ui/input";
import { ProjectBasics } from "@/components/ProjectBasics";
import { PendingButton } from "@/components/PendingButton";
import { Workspace } from "@/components/Workspace";
import { requireUser, words } from "@/lib/auth";
import { db } from "@/lib/db";
@ -76,7 +76,7 @@ export default async function NewProject({ searchParams }: { searchParams: Promi
)}
</ProjectBasics>
<p className="m-0 text-sm text-muted-foreground">{t("Peppa FACTORY подготовит всё для агентов — это займёт до 15 секунд.")}</p>
<Button variant="default" className="self-start">{t("Создать проект")}</Button>
<PendingButton pendingText={t("Создаём проект…")} className="self-start">{t("Создать проект")}</PendingButton>
</form>
</div>
</Workspace>

View File

@ -45,6 +45,17 @@ export async function projectNamespace(db: Db, user: User, owner?: string | null
return { gitea: await giteaForUser(db, user), owner: ns, ownerIsUser: ns === user.login };
}
/**
* PEP-142: the same person sent the same «new project» form twice (a second click while the first
* request was still creating the project). The project made a moment ago is the answer to the
* second request — not «slug is taken».
*/
export async function justCreatedProject(db: Db, o: { slug: string; key: string; ownerId: number }, withinMs = 2 * 60_000): Promise<Project | null> {
const [p] = await db.select().from(projects).where(eq(projects.slug, o.slug.toLowerCase()));
if (!p || p.ownerId !== o.ownerId || p.key !== o.key.toUpperCase()) return null;
return Date.now() - p.createdAt.getTime() <= withinMs ? p : null;
}
export async function provisionProject(db: Db, o: ProvisionOptions): Promise<Project> {
const env = loadEnv();
const log = o.log ?? (() => {});

View File

@ -58,6 +58,7 @@ export const project: Dict = {
"Проект — один продукт: сайт, бот, сервис. Нужны только название и короткий код, например SHOP.":
"A project is one product: a website, a bot, a service. All you need is a name and a short code, e.g. SHOP.",
"Создать проект": "Create project",
"Создаём проект…": "Creating the project…",
"Подключите подписку агента": "Connect an agent subscription",
"Claude, Codex или OpenCode — на ней работают агенты; подключите её к проекту.": "Claude, Codex or OpenCode — agents run on it; connect it to the project.",
"Открыть подписки": "Open subscriptions",

View File

@ -45,6 +45,7 @@ export const project: Dict = {
"Создайте проект": "Жоба жасаңыз",
"Проект — один продукт: сайт, бот, сервис. Нужны только название и короткий код, например SHOP.": "Жоба — бір өнім: сайт, бот, сервис. Тек атауы мен қысқа коды керек, мысалы SHOP.",
"Создать проект": "Жоба жасау",
"Создаём проект…": "Жоба жасалып жатыр…",
"Подключите подписку агента": "Агент жазылымын қосыңыз",
"Claude, Codex или OpenCode — на ней работают агенты; подключите её к проекту.": "Claude, Codex немесе OpenCode — агенттер соның негізінде жұмыс істейді; оны жобаға қосыңыз.",
"Открыть подписки": "Жазылымдарды ашу",

View File

@ -102,6 +102,14 @@ describe("project provisioning", () => {
assert.match(execFileSync("git", ["-C", p.workspacePath, "config", "--get-all", "credential.helper"], { encoding: "utf8" }), /git-credential-peppa/);
});
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");
assert.equal(await runner.justCreatedProject(db, { slug: "mock-demo", key: "MDEMO", ownerId: bob.id }), null, "another person still gets «taken»");
assert.equal(await runner.justCreatedProject(db, { slug: "mock-demo", key: "MOTHER", ownerId: alice.id }), null, "a different key is a different project");
assert.equal(await runner.justCreatedProject(db, { slug: "mock-demo", key: "MDEMO", ownerId: alice.id }, -1), null, "an old project is not «just created»");
});
test("project in an org the user can create repos in", async () => {
const p = await provision({ slug: "mock-team-app", key: "MTEAM", owner: "mock-team", ownerIsUser: false });
assert.equal(p.giteaOwner, "mock-team");