// Domain cards shared by pages: agent questions, runners, project list. import Link from "next/link"; import { BellRing, CircleCheck, CircleHelp, FileCheck, Hourglass, Play, RotateCcw, Send, ShieldQuestion, Square, SquareTerminal } from "lucide-react"; import { pausedProjectIds, messageDetails, questionDetails, questionIsFreeText, questionState, questionText, questionType, splitForDisplay, trashDaysLeft, type Project, type Question, type SessionView, type StepView } from "@peppa/core"; import { db } from "@/lib/db"; import { MessagesSquare } from "lucide-react"; import type { AnalystLink } from "@peppa/core"; import { SubscriptionName } from "@/components/SubscriptionName"; import { PausedBadge } from "@/components/ProjectPause"; import { answerQuestion, messageSession, resumeTaskSession, stopTaskSession } from "@/app/(app)/actions"; import { Button } from "@/components/ui/button"; import { AgentBadge } from "@/components/AgentBadge"; import { Input } from "@/components/ui/input"; import { ago, Disclosure, Empty, Key, linkify, StatusBadge } from "@/components/common"; import { AgentSteps } from "@/components/AgentSteps"; import { Dictate } from "@/components/Dictate"; import { RunnerTerminal } from "@/components/RunnerTerminal"; import { SessionUsageLine } from "@/components/Accounting"; import { cn } from "@/lib/utils"; import { getT } from "@/lib/i18n"; import { subscriptionNamesVisible, uiMode } from "@/lib/auth"; import { asIs, m } from "@peppa/shared/i18n"; const KIND = { approval: { label: m("Одобрение плана"), icon: FileCheck, border: "border-l-primary" }, question: { label: m("Вопрос"), icon: CircleHelp, border: "border-l-info" }, permission: { label: m("Разрешение"), icon: ShieldQuestion, border: "border-l-warn" }, attention: { label: m("Сообщение от фабрики"), icon: BellRing, border: "border-l-ok" }, } as const; /** Hidden inputs of a server-action form. */ export function Hidden({ fields }: { fields: Record }) { return ( <> {Object.entries(fields).map(([k, v]) => (v == null ? null : ))} ); } export async function QuestionCard({ q, taskKey, taskStatus, back, compact = false, plain = false }: { q: Question; taskKey?: string | null; taskStatus?: string | null; back: string; compact?: boolean; /** PEP-120: for a product manager — no question number, a terminal command only under «Подробнее». */ plain?: boolean }) { const t = await getT(); const review = q.kind === "attention" && taskStatus === "review"; const answered = !!q.answeredAt; const notice = questionType(q, taskStatus) === null && q.taskId == null && q.sessionId == null; // PEP-149: a factory message with answers to choose from is a question for the person. const k = KIND[q.kind === "attention" && !review && q.options?.length ? "question" : q.kind]; const Icon = review ? CircleCheck : k.icon; // PEP-151: the same state came again — one message with the time it was last refreshed. const state = await questionState(db, q.id).catch(() => null); const updatedAt = state?.updatedAt ? new Date(state.updatedAt) : null; // PEP-152: the main text — at most five lines; the rest and the technical details open under «Подробнее». const details = (await messageDetails(db, [q.id]).catch(() => null))?.get(q.id) ?? null; // A permission request keeps its command whole: that is what the person allows. const shown = q.kind === "permission" ? { main: t.text(questionText(q)), more: details } : splitForDisplay(t.text(questionText(q)), details ? t.text(details) : null); // PEP-154: what the filter removed (command output, paths) — for «Инженер» and a superadmin only. const original = (await uiMode()) === "engineer" || (await subscriptionNamesVisible()) ? await questionDetails(db, q.id).catch(() => null) : null; return (
{review ? t("Готово к ревью") : t(k.label)} {taskKey && {taskKey}} {!plain && <>#{q.id} · }{updatedAt ? t("обновлено {ago}", { ago: ago(updatedAt, t) }) : ago(q.createdAt, t)}
{plain && q.kind === "permission" ? ( <>

{t("Агенту нужно ваше разрешение, чтобы продолжить работу.")}

{t("Подробнее")}

{t.text(questionText(q))}

{!!state?.repeats &&

{t("Повторов: {n} · первое сообщение {ago}", { n: state.repeats, ago: ago(q.createdAt, t) })}

}
) : (

{linkify(shown.main)}

)} {(shown.more || !!state?.repeats) && !(plain && q.kind === "permission") && (
{t("Подробнее")} {shown.more &&

{shown.more}

} {!!state?.repeats &&

{t("Повторов: {n} · первое сообщение {ago}", { n: state.repeats, ago: ago(q.createdAt, t) })}

}
)} {original && (
{t("Подробнее: исходный текст")}
{original}
)} {/* PEP-149: a notice about the product as a whole (released, backlog is empty) asks nothing — no answer form. */} {answered ? (

{q.answeredVia === "system" ? : } {q.answeredVia === "system" ? t.text(q.answer) : t("Ответ ({via}): {answer}", { via: q.answeredVia, answer: q.answer })}

) : notice ? null : (
{/* i18n-ignore: choice values are answers to the agent */} {q.kind === "approval" && } {q.kind === "permission" && ( <> )} {review && } {/* PEP-149: no «continue» button — a message either has answers to choose from or needs none. */} {(q.options ?? []).map((o) => ( ))}
{q.defaultOption &&

{t("Если не ответите, агент продолжит по варианту «{option}».", { option: t.text(q.defaultOption) })}

} {q.kind !== "permission" && (
)} )}
); } /** Message / stop / resume controls of one runner. */ export async function SessionActions({ s, back }: { s: SessionView; back: string }) { const t = await getT(); const alive = !["done", "failed"].includes(s.status); return (
{alive && (
)} {alive && (
)} {(!alive || ["rate_limited", "stalled"].includes(s.status)) && (
)}
); } export function AttachCommand({ name }: { name: string }) { return tmux attach -t {name}; } /** `steps` (PEP-33): the live step feed of the agent, shown with the terminal. */ export async function SessionCard({ s, back, showTitle = false, terminal = false, steps, plainSteps = false }: { s: SessionView; back: string; showTitle?: boolean; terminal?: boolean; steps?: StepView[]; /** PEP-154: «Продакт» — steps in words. */ plainSteps?: boolean }) { const t = await getT(); return (
{s.taskKey ? {s.taskKey} : {s.projectKey}} {s.agentName && } {showTitle && (s.taskTitle ?? s.name) && {s.taskTitle ?? s.name}} #{s.id} · {s.provider} {s.host && <> · {s.host.name}} {s.container && <> · {t("в контейнере")}} {s.subscriptionSwitches > 0 && <> · {t("переключений {n}", { n: s.subscriptionSwitches })}} · {t("пок. {n}", { n: s.generation })} · {ago(s.lastActivityAt, t)}
{!terminal && !["done", "failed"].includes(s.status) && ( )} {steps && } {terminal && }
); } /** * PEP-89: an agent at work, for a product manager — who, on what, in what state. The run's * number, subscription, terminal command and spend sit under «Подробнее» — in «Инженер» only * (PEP-123: «Продакт» sees no terminal commands, subscriptions or spend). */ export async function AgentAtWork({ s, back, engineer = false }: { s: SessionView; back: string; engineer?: boolean }) { const alive = !["done", "failed"].includes(s.status); const t = await getT(); const verb = s.status === "running" || s.status === "starting" ? t("работает над") : s.status === "waiting_input" ? t("спрашивает по") : t("вёл"); return (
{ago(s.lastActivityAt, t)}

{s.taskKey ? ( <> {verb} {s.taskKey} {s.taskTitle} ) : ( <> {engineer ? t("свободный терминал в проекте") : t("помогает в проекте")} {s.projectKey} {s.name && {s.name}} )}

{engineer && (
{t("запуск #{id}", { id: s.id })} · {s.provider} {s.host && <> · {s.host.name}} {s.container && <> · {t("в контейнере")}} {s.subscriptionSwitches > 0 && <> · {t("переключений {n}", { n: s.subscriptionSwitches })}} · {t("пок. {n}", { n: s.generation })} {alive && ( )}
)}
); } /** `engineer` (PEP-123): the address of the code is shown in «Инженер» only. */ export async function ProjectList({ projects, userId, engineer = false, analyst }: { projects: Array; userId: number; engineer?: boolean; /** PEP-161: projectId → the chat with the analyst; no entry — no link. */ analyst?: Map }) { const t = await getT(); if (!projects.length) return ( {t("Проектов пока нет.")}{" "} ); // PEP-174: projects on pause carry a mark. const paused = await pausedProjectIds(db); return (
    {projects.map((p) => { const chat = analyst?.get(p.id); return (
  • {/* The project link is stretched over the whole card; the analyst link lies on top of it — no nested links. */}
    {p.key} {p.name} {paused.has(p.id) && } {p.deletedAt && {t("удалён, ещё {days} дн.", { days: trashDaysLeft(p) })}} {!p.deletedAt && p.ownerId !== userId && {p.ownerLogin !== undefined ? (p.ownerLogin ?? t("без владельца")) : t("общий")}} {engineer && ( {p.giteaOwner}/{p.giteaRepo} )} {chat && ( {t("Написать аналитику")} {chat.unread > 0 && {t("{n} нов.", { n: chat.unread })}} )}
  • ); })}
); }