237 lines
12 KiB
TypeScript
237 lines
12 KiB
TypeScript
// 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 type { Project, Question, SessionView, StepView } from "@peppa/core";
|
||
import { SubscriptionName } from "@/components/SubscriptionName";
|
||
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, StatusBadge } from "@/components/common";
|
||
import { AgentSteps } from "@/components/AgentSteps";
|
||
import { RunnerTerminal } from "@/components/RunnerTerminal";
|
||
import { SessionUsageLine } from "@/components/Accounting";
|
||
import { cn } from "@/lib/utils";
|
||
|
||
const KIND = {
|
||
approval: { label: "Одобрение плана", icon: FileCheck, border: "border-l-primary" },
|
||
question: { label: "Вопрос", icon: CircleHelp, border: "border-l-info" },
|
||
permission: { label: "Разрешение", icon: ShieldQuestion, border: "border-l-warn" },
|
||
attention: { label: "Сообщение от фабрики", icon: BellRing, border: "border-l-ok" },
|
||
} as const;
|
||
|
||
/** Hidden inputs of a server-action form. */
|
||
export function Hidden({ fields }: { fields: Record<string, string | number | null | undefined> }) {
|
||
return (
|
||
<>
|
||
{Object.entries(fields).map(([k, v]) => (v == null ? null : <input key={k} type="hidden" name={k} value={v} />))}
|
||
</>
|
||
);
|
||
}
|
||
|
||
export function QuestionCard({ q, taskKey, taskStatus, back, compact = false }: { q: Question; taskKey?: string | null; taskStatus?: string | null; back: string; compact?: boolean }) {
|
||
const review = q.kind === "attention" && taskStatus === "review";
|
||
const answered = !!q.answeredAt;
|
||
const k = KIND[q.kind];
|
||
const Icon = review ? CircleCheck : k.icon;
|
||
return (
|
||
<article id={`q-${q.id}`} className={cn("flex flex-col gap-2.5 rounded-lg border border-l-2 bg-card p-4", answered ? "border-l-border opacity-70" : k.border)}>
|
||
<header className="flex flex-wrap items-center gap-x-2 gap-y-1 text-sm">
|
||
<Icon className="size-4 text-muted-foreground" />
|
||
<span className="font-medium">{review ? "Готово к ревью" : k.label}</span>
|
||
{taskKey && <Key href={`/t/${taskKey}`}>{taskKey}</Key>}
|
||
<span className="ml-auto font-mono text-xs text-muted-foreground">
|
||
#{q.id} · {ago(q.createdAt)}
|
||
</span>
|
||
</header>
|
||
<p className={cn("m-0 overflow-auto text-sm whitespace-pre-wrap", compact ? "max-h-40" : "max-h-72")}>{q.text}</p>
|
||
{answered ? (
|
||
<p className="m-0 flex items-center gap-1.5 text-sm text-muted-foreground">
|
||
{q.answeredVia === "system" ? <Hourglass className="size-3.5" /> : <CircleCheck className="size-3.5 text-ok" />}
|
||
{q.answeredVia === "system" ? q.answer : `Ответ (${q.answeredVia}): ${q.answer}`}
|
||
</p>
|
||
) : (
|
||
<form action={answerQuestion} className="flex flex-col gap-2">
|
||
<Hidden fields={{ questionId: q.id, back }} />
|
||
<div className="flex flex-wrap gap-2">
|
||
{q.kind === "approval" && <Button name="choice" value="ок" variant="default" size="sm">Одобрить</Button>}
|
||
{q.kind === "permission" && (
|
||
<>
|
||
<Button name="choice" value="allow" variant="default" size="sm">Разрешить</Button>
|
||
<Button name="choice" value="always" size="sm">Всегда</Button>
|
||
<Button name="choice" value="deny" variant="destructive" size="sm">Запретить</Button>
|
||
</>
|
||
)}
|
||
{review && <Button name="choice" value="__accept" variant="default" size="sm">Принять</Button>}
|
||
{q.kind === "attention" && !review && <Button name="choice" value="Продолжай." variant="default" size="sm">Продолжай</Button>}
|
||
{(q.options ?? []).map((o) => (
|
||
<Button key={o} name="choice" value={o} size="sm">{o}</Button>
|
||
))}
|
||
</div>
|
||
{q.kind !== "permission" && (
|
||
<div className="flex gap-2">
|
||
<Input name="answer" data-hotkey-answer placeholder={q.kind === "approval" || review ? "Замечание — вернёт на доработку" : "Свой ответ"} aria-label="Ответ" className="h-8" />
|
||
<Button size="sm">Ответить</Button>
|
||
</div>
|
||
)}
|
||
</form>
|
||
)}
|
||
</article>
|
||
);
|
||
}
|
||
|
||
/** Message / stop / resume controls of one runner. */
|
||
export function SessionActions({ s, back }: { s: SessionView; back: string }) {
|
||
const alive = !["done", "failed"].includes(s.status);
|
||
return (
|
||
<div className="flex flex-wrap gap-2">
|
||
{alive && (
|
||
<form action={messageSession} className="flex min-w-0 flex-[1_1_16rem] gap-2">
|
||
<Hidden fields={{ sessionId: s.id, back }} />
|
||
<Input name="text" placeholder="Написать агенту" aria-label="Написать агенту" className="h-8" />
|
||
<Button size="sm" aria-label="Отправить" title="Отправить">
|
||
<Send />
|
||
<span className="max-sm:hidden">Отправить</span>
|
||
</Button>
|
||
</form>
|
||
)}
|
||
{alive && (
|
||
<form action={stopTaskSession}>
|
||
<Hidden fields={{ sessionId: s.id, back }} />
|
||
<Button variant="destructive" size="sm">
|
||
<Square />
|
||
Остановить
|
||
</Button>
|
||
</form>
|
||
)}
|
||
{(!alive || ["rate_limited", "stalled"].includes(s.status)) && (
|
||
<form action={resumeTaskSession}>
|
||
<Hidden fields={{ sessionId: s.id, back }} />
|
||
<Button size="sm">
|
||
{alive ? <RotateCcw /> : <Play />}
|
||
Resume
|
||
</Button>
|
||
</form>
|
||
)}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
export function AttachCommand({ name }: { name: string }) {
|
||
return <code className="block overflow-x-auto rounded-md bg-muted px-2.5 py-1.5 font-mono text-xs whitespace-nowrap text-muted-foreground">tmux attach -t {name}</code>;
|
||
}
|
||
|
||
/** `steps` (PEP-33): the live step feed of the agent, shown with the terminal. */
|
||
export function SessionCard({ s, back, showTitle = false, terminal = false, steps }: { s: SessionView; back: string; showTitle?: boolean; terminal?: boolean; steps?: StepView[] }) {
|
||
return (
|
||
<article className="flex flex-col gap-2.5 rounded-lg border bg-card p-3.5">
|
||
<header className="flex flex-wrap items-center gap-x-2 gap-y-1 text-sm">
|
||
<StatusBadge status={s.status} kind="session" />
|
||
{s.taskKey ? <Key href={`/t/${s.taskKey}`}>{s.taskKey}</Key> : <Key href={`/p/${s.projectKey}`}>{s.projectKey}</Key>}
|
||
{s.agentName && <AgentBadge name={s.agentName} />}
|
||
{showTitle && (s.taskTitle ?? s.name) && <span className="min-w-0 flex-[1_1_12em] truncate">{s.taskTitle ?? s.name}</span>}
|
||
<span className="ml-auto font-mono text-xs text-muted-foreground">
|
||
<Link href={`/runners?id=${s.id}`} className="text-muted-foreground hover:text-foreground">#{s.id}</Link> · {s.provider}
|
||
<SubscriptionName s={s} prefix=" · " />
|
||
{s.host && <> · {s.host.name}</>}
|
||
{s.container && <> · в контейнере</>}
|
||
{s.subscriptionSwitches > 0 && <> · переключений {s.subscriptionSwitches}</>} · пок. {s.generation} · {ago(s.lastActivityAt)}
|
||
</span>
|
||
</header>
|
||
<SessionUsageLine usage={s.usage} provider={s.provider} />
|
||
<AttachCommand name={s.tmuxName} />
|
||
<SessionActions s={s} back={back} />
|
||
{!terminal && !["done", "failed"].includes(s.status) && (
|
||
<Button asChild size="sm" variant="outline" className="self-start">
|
||
<Link href={`/runners?id=${s.id}`}>
|
||
<SquareTerminal /> Открыть терминал
|
||
</Link>
|
||
</Button>
|
||
)}
|
||
{steps && <AgentSteps key={`steps-${s.id}`} sessionId={s.id} initial={steps} live={terminal} hooks={s.provider === "claude"} />}
|
||
{terminal && <RunnerTerminal key={s.id} sessionId={s.id} live />}
|
||
</article>
|
||
);
|
||
}
|
||
|
||
/**
|
||
* 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 «Подробнее».
|
||
*/
|
||
export function AgentAtWork({ s, back }: { s: SessionView; back: string }) {
|
||
const alive = !["done", "failed"].includes(s.status);
|
||
const verb = s.status === "running" || s.status === "starting" ? "работает над" : s.status === "waiting_input" ? "спрашивает по" : "вёл";
|
||
return (
|
||
<article className="flex flex-col gap-2.5 rounded-lg border bg-card p-3.5" data-agent-at-work={s.id}>
|
||
<header className="flex flex-wrap items-center gap-x-2.5 gap-y-1.5">
|
||
<AgentBadge name={s.agentName ?? "без клички"} large />
|
||
<StatusBadge status={s.status} kind="session" />
|
||
<span className="ml-auto text-xs text-muted-foreground">{ago(s.lastActivityAt)}</span>
|
||
</header>
|
||
<p className="m-0 flex flex-wrap items-center gap-x-2 gap-y-0.5 text-sm">
|
||
{s.taskKey ? (
|
||
<>
|
||
<span className="text-muted-foreground">{verb}</span>
|
||
<Key href={`/t/${s.taskKey}`}>{s.taskKey}</Key>
|
||
<span className="min-w-0 flex-[1_1_12em] truncate">{s.taskTitle}</span>
|
||
</>
|
||
) : (
|
||
<>
|
||
<span className="text-muted-foreground">свободный терминал в проекте</span>
|
||
<Key href={`/p/${s.projectKey}`}>{s.projectKey}</Key>
|
||
{s.name && <span className="min-w-0 truncate">{s.name}</span>}
|
||
</>
|
||
)}
|
||
</p>
|
||
<SessionActions s={s} back={back} />
|
||
<Disclosure summary="Подробнее" className="border-0 bg-transparent [&>summary]:px-0 [&>summary]:py-0 [&>summary]:text-xs [&>summary]:font-normal [&>summary]:text-muted-foreground">
|
||
<div className="flex flex-col gap-2 pt-2">
|
||
<span className="font-mono text-xs text-muted-foreground">
|
||
запуск #{s.id} · {s.provider}
|
||
<SubscriptionName s={s} prefix=" · " />
|
||
{s.host && <> · {s.host.name}</>}
|
||
{s.container && <> · в контейнере</>}
|
||
{s.subscriptionSwitches > 0 && <> · переключений {s.subscriptionSwitches}</>} · пок. {s.generation}
|
||
</span>
|
||
<SessionUsageLine usage={s.usage} provider={s.provider} />
|
||
<AttachCommand name={s.tmuxName} />
|
||
{alive && (
|
||
<Button asChild size="sm" variant="outline" className="self-start">
|
||
<Link href={`/runners?id=${s.id}`}>
|
||
<SquareTerminal /> Открыть терминал
|
||
</Link>
|
||
</Button>
|
||
)}
|
||
</div>
|
||
</Disclosure>
|
||
</article>
|
||
);
|
||
}
|
||
|
||
export function ProjectList({ projects, userId }: { projects: Array<Project & { ownerLogin?: string | null }>; userId: number }) {
|
||
if (!projects.length)
|
||
return (
|
||
<Empty>
|
||
Проектов пока нет. <Link href="/projects/new" className="text-primary">Создать первый</Link>
|
||
</Empty>
|
||
);
|
||
return (
|
||
<ul className="m-0 grid list-none gap-2 p-0 sm:grid-cols-2">
|
||
{projects.map((p) => (
|
||
<li key={p.id}>
|
||
<Link href={`/p/${p.key}`} className="flex h-full flex-col gap-1 rounded-lg border bg-card px-4 py-3 text-foreground transition-colors hover:border-primary/50 hover:no-underline">
|
||
<span className="flex items-center gap-2">
|
||
<span className="rounded bg-muted px-1.5 font-mono text-xs text-primary">{p.key}</span>
|
||
<span className="min-w-0 truncate font-medium">{p.name}</span>
|
||
{p.ownerId !== userId && <span className="ml-auto rounded-full border px-2 text-[11px] text-muted-foreground">{p.ownerLogin !== undefined ? (p.ownerLogin ?? "без владельца") : "общий"}</span>}
|
||
</span>
|
||
<span className="truncate font-mono text-xs text-muted-foreground">
|
||
{p.giteaOwner}/{p.giteaRepo}
|
||
</span>
|
||
</Link>
|
||
</li>
|
||
))}
|
||
</ul>
|
||
);
|
||
}
|