peppa/apps/web/components/cards.tsx
Асель 09d2750d75 PEP-9: live runner terminal in the web — xterm.js over SSE, input via POST
- runner/terminal.ts: TerminalFeed polls the pane (capture-pane -e, one loop per runner
  shared by viewers), sends changed lines, scrolled-off lines and the cursor; terminalInput
  (send-keys -H / paste-buffer -p) with access, liveness, size and rate checks, resets
  auto_nudges, logs terminal_input; terminalSse with 15 s pings for Cloudflare
- web: GET/POST /api/runners/[id]/terminal, RunnerTerminal (xterm.js) in the runner panel
  and on the story page; help
- testkit: terminal.test.ts — real tmux into a headless xterm, history, input, access, limits, SSE
- OpenSpec change archived; new spec runner-terminal

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 04:45:32 +05:00

164 lines
8.1 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 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 } from "lucide-react";
import type { Project, Question, SessionView } from "@peppa/core";
import { answerQuestion, messageSession, resumeTaskSession, stopTaskSession } from "@/app/(app)/actions";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { ago, Empty, Key, StatusBadge } from "@/components/common";
import { RunnerTerminal } from "@/components/RunnerTerminal";
import { cn } from "@/lib/utils";
const KIND = {
approval: { label: "Одобрение proposal", 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" 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>;
}
export function SessionCard({ s, back, showTitle = false, terminal = false }: { s: SessionView; back: string; showTitle?: boolean; terminal?: boolean }) {
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>}
{showTitle && s.taskTitle && <span className="min-w-0 flex-[1_1_12em] truncate">{s.taskTitle}</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} · пок. {s.generation} · {ago(s.lastActivityAt)}
</span>
</header>
<AttachCommand name={s.tmuxName} />
<SessionActions s={s} back={back} />
{terminal && <RunnerTerminal key={s.id} sessionId={s.id} live />}
</article>
);
}
export function ProjectList({ projects, userId }: { projects: Project[]; 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">общий</span>}
</span>
<span className="truncate font-mono text-xs text-muted-foreground">
{p.giteaOwner}/{p.giteaRepo}
</span>
</Link>
</li>
))}
</ul>
);
}