"use client"; import { useWords } from "@/components/Words"; import Link from "next/link"; import { useRouter } from "next/navigation"; import { useEffect, useState, useTransition } from "react"; import { ChevronDown, ChevronRight, ChevronsDown, ChevronsUp, Lock } from "lucide-react"; import { moveTaskCard, proposalAction } from "@/app/(app)/actions"; import { reorderTaskInline } from "@/app/(app)/board-actions"; import { Button } from "@/components/ui/button"; import { Badge } from "@/components/ui/badge"; import { AgentBadge } from "@/components/AgentBadge"; import { cn } from "@/lib/utils"; import { useT } from "@/components/I18n"; import { m } from "@peppa/shared/i18n"; export type Column = "backlog" | "in_progress" | "review" | "done"; export interface Card { key: string; /** PEP-197: the task id (the buttons of «Предложено» send ids). */ id?: number; title: string; status: string; column: Column; /** Epic label (PEP-66), if the story has an open epic. */ epic?: string | null; /** tasks.md progress of a story in work (PEP-33). */ progress?: CardProgress | null; /** PEP-42: "ждёт PEP-3" while a predecessor isn't in review/done. */ blocked?: string | null; /** PEP-75: the persona working on the story right now. */ agent?: string | null; /** PEP-84 / PEP-198: the analyst still holds the story ("уточняется" / "ждёт ваших ответов"). */ refining?: string | null; /** PEP-127: accepted over a conflict — the agent updates the changes, the story closes by itself. */ accepted?: string | null; /** PEP-150: a delay on the platform's side — nothing is needed from the owner. */ delayed?: string | null; /** PEP-182: place in the queue for a free agent (in work, no agent yet). */ queued?: number | null; /** PEP-197: a story of an agent the owner has not decided on — shown in «Предложено», not in the backlog. */ proposed?: boolean; /** PEP-197: «Поломка» / «Важно» / «Мелочь» on stories of the acceptance agent. */ severity?: "breakage" | "important" | "minor" | null; /** PEP-197: made by an agent, not by a person. */ agentMade?: boolean; } export interface CardProgress { done: number; total: number; current: string | null; } /** «7/12» bar and the item the agent is on (PEP-33). */ export function ProgressLine({ p, className }: { p: CardProgress; className?: string }) { const t = useT(); const w = useWords(); const pct = p.total ? Math.round((p.done / p.total) * 100) : 0; return (
{p.done}/{p.total}
{p.current && {p.current}}
); } const DONE_COLLAPSED = "peppa.board.doneCollapsed"; const COLUMNS: Array<{ id: Column; title: string; hint: string; dot: string }> = [ { id: "backlog", title: m("Бэклог"), hint: "", dot: "bg-muted-foreground" }, { id: "in_progress", title: m("В работе"), hint: m("сюда — запустить агента"), dot: "bg-info" }, { id: "review", title: m("Ревью"), hint: "", dot: "bg-ok" }, { id: "done", title: m("Готово"), hint: "", dot: "bg-ok" }, ]; const STATUS: Record = { proposing: { label: m("план"), tone: "primary" }, awaiting_approval: { label: m("ждёт PM"), tone: "primary" }, blocked: { label: m("блок"), tone: "danger" }, in_progress: { label: m("агент"), tone: "info" }, }; const NEXT: Partial> = { backlog: { to: "in_progress", label: m("В работу →") }, review: { to: "done", label: m("Принять ✓") }, }; /** * Story board: drag a card to another column (or use its button) to move it — the server * starts/stops agents; drag it onto a card of its own column to change the order (= priority * for the dispatcher, PEP-34). «Готово» can be collapsed (remembered in the browser). */ export function Board({ cards, back }: { cards: Card[]; back: string }) { const w = useWords(); const router = useRouter(); const t = useT(); const [pending, start] = useTransition(); const [over, setOver] = useState(null); const [error, setError] = useState(null); const [doneCollapsed, setDoneCollapsed] = useState(false); useEffect(() => { try { setDoneCollapsed(localStorage.getItem(DONE_COLLAPSED) === "1"); } catch {} }, []); const toggleDone = () => { setDoneCollapsed((v) => { try { localStorage.setItem(DONE_COLLAPSED, v ? "0" : "1"); } catch {} return !v; }); }; const move = (key: string, to: Column) => { const f = new FormData(); f.set("taskKey", key); f.set("to", to); f.set("back", back); start(() => moveTaskCard(f)); }; const reorder = (key: string, to: "top" | "bottom" | "before" | "after", other?: string) => start(async () => { setError(await reorderTaskInline(key, to, other)); router.refresh(); }); return (
x.proposed)} back={back} /> {error && (

{t.text(error)}

)}
{COLUMNS.map((c) => { const list = cards.filter((x) => x.column === c.id && !x.proposed); const collapsed = c.id === "done" && doneCollapsed; return (
{ e.preventDefault(); setOver(c.id); }} onDragLeave={() => setOver(null)} onDrop={(e) => { e.preventDefault(); setOver(null); const key = e.dataTransfer.getData("text/plain"); const card = cards.find((x) => x.key === key); if (!card) return; if (card.column !== c.id) move(key, c.id); else if (list.at(-1)?.key !== key) reorder(key, "bottom"); // empty space of its own column: to the end }} >

{t(c.title)} {list.length} {c.id === "done" && ( )}

{!collapsed && c.hint &&

{t(c.hint)}

} {!collapsed && list.map((card, i) => (
e.dataTransfer.setData("text/plain", card.key)} onDrop={(e) => { const key = e.dataTransfer.getData("text/plain"); const dragged = cards.find((x) => x.key === key); if (!dragged || dragged.column !== c.id) return; // another column: the section moves it e.preventDefault(); e.stopPropagation(); setOver(null); if (key === card.key) return; const r = e.currentTarget.getBoundingClientRect(); reorder(key, e.clientY < r.top + r.height / 2 ? "before" : "after", card.key); }} className="group flex cursor-grab flex-col gap-2 rounded-md border bg-card p-2.5 text-sm shadow-xs transition-colors hover:border-primary/40 active:cursor-grabbing" >
{card.key} {card.title} {list.length > 1 && ( {i > 0 && ( )} {i < list.length - 1 && ( )} )}
{card.refining && ( {t.text(card.refining)} )} {card.accepted && ( {card.accepted} )} {card.delayed && ( {card.delayed} )} {card.queued != null && ( {t("В очереди: {n}-я, начнётся, когда освободится агент", { n: card.queued })} )} {card.severity === "breakage" && !card.proposed && ( {t("Поломка")} )} {card.agent && } {card.progress && } {(STATUS[card.status] || NEXT[c.id] || card.epic || card.blocked) && (
{card.blocked && ( {t.text(card.blocked)} )} {card.epic && ( {t("эпик")} {card.epic} )} {STATUS[card.status] && {t(STATUS[card.status]!.label)}} {NEXT[c.id] && ( )}
)}
))}
); })}

{w.engineer ? t("Порядок в колонке — приоритет: перетащите карточку выше или ниже; диспетчер берёт стори из бэклога сверху.") : t("Порядок в колонке — приоритет: перетащите карточку выше или ниже; агенты берут задачи из бэклога сверху.")}

); } const SEVERITY: Record = { breakage: { label: m("Поломка"), variant: "danger" }, important: { label: m("Важно"), variant: "warn" }, minor: { label: m("Мелочь"), variant: "muted" }, }; /** * PEP-197: «Предложено» — what the factory suggests on its own. Folded, with a counter; the * dispatcher takes nothing from here. «Делать» sends a story to the backlog, «Не надо» archives * it and the acceptance agent will not suggest it again. Buttons are at least 44 px for a thumb. */ function Proposed({ cards, back }: { cards: Card[]; back: string }) { const t = useT(); if (!cards.length) return null; const ids = cards.map((c) => c.id).join(","); const important = cards.filter((c) => c.severity !== "minor"); return (
{t("Предложено")} {cards.length}

{t("Это придумала сама фабрика. Пока вы не нажмёте «Делать», агенты за эти задачи не возьмутся.")}

{cards.map((card) => (
{card.key} {card.title} {card.severity && SEVERITY[card.severity] && ( {t(SEVERITY[card.severity]!.label)} )}
))}
{cards.length > 1 && ( // PEP-209: several small fixes of one page become one story — fewer stories to accept.
{t("Отметьте мелкие правки одной страницы — фабрика сделает их одной задачей:")} {cards.map((card) => ( ))}
)}
{important.length > 0 && ( )}
); } function ProposalButtons() { const t = useT(); return ( <> ); }