peppa/apps/web/app/(app)/t/[key]/page.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

177 lines
9.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.

import Link from "next/link";
import { notFound } from "next/navigation";
import { CircleCheck, CircleX, GitPullRequest, Hourglass, Play } from "lucide-react";
import { FINISHED_SESSION_STATUSES, getEpic, isSuperadmin, listPools, listSubscriptions, projectPool, PROVIDER_NAMES, taskCiSummary } from "@peppa/core";
import { AutoRefresh } from "@/components/AutoRefresh";
import { PanelSection } from "@/components/ActivityAside";
import { Hidden, QuestionCard, SessionCard } from "@/components/cards";
import { ago, Disclosure, Empty, Flash, PageHeader, Section, StatusBadge } from "@/components/common";
import { Button } from "@/components/ui/button";
import { Input, NativeSelect } from "@/components/ui/input";
import { Workspace } from "@/components/Workspace";
import { requireUser } from "@/lib/auth";
import { db } from "@/lib/db";
import { openspecArtifacts, taskActivity, taskForUser } from "@/lib/queries";
import { startTaskSession } from "../../actions";
const CI_ICON = { success: <CircleCheck className="size-4 text-ok" />, failure: <CircleX className="size-4 text-destructive" />, pending: <Hourglass className="size-4 text-warn" /> };
export default async function StoryPage({ params, searchParams }: { params: Promise<{ key: string }>; searchParams: Promise<{ error?: string }> }) {
const user = await requireUser();
const { key } = await params;
const { error } = await searchParams;
const ref = await taskForUser(user.id, decodeURIComponent(key)).catch(() => null);
if (!ref) notFound();
const { task, project } = ref;
const { questions, sessions, events } = await taskActivity(task.id);
const liveId = sessions.find((s) => !FINISHED_SESSION_STATUSES.includes(s.status))?.id;
const artifacts = openspecArtifacts(project, task.openspecChange);
const ci = await taskCiSummary(db, ref);
const epic = task.goalId ? await getEpic(db, project.id, task.goalId).catch(() => null) : null;
const back = `/t/${ref.key}`;
// PEP-67: superadmins choose the subscriptions a runner may take; others run on the project's pool.
const superadmin = await isSuperadmin(db, user);
const pool = await projectPool(db, project.id);
const [pools, subs] = superadmin ? await Promise.all([listPools(db), listSubscriptions(db)]) : [[], []];
const aside = (
<div className="flex flex-col gap-6">
<PanelSection title="Проверки">
<div className="flex flex-wrap items-center gap-2 text-sm">
{CI_ICON[ci.state as keyof typeof CI_ICON]}
{ci.runUrl ? <a href={ci.runUrl} className="text-primary">{ci.label}</a> : ci.label}
{ci.sha && <span className="font-mono text-xs text-muted-foreground">{ci.sha.slice(0, 7)}</span>}
</div>
{task.ciAttempts > 0 && <p className="m-0 text-xs text-muted-foreground">красных подряд: {task.ciAttempts}</p>}
{ci.failed.map((f) => (
<Disclosure
key={f.check}
summary={
<span className="flex items-center gap-1.5">
<CircleX className="size-3.5 text-destructive" />
<span className="font-mono">{f.check}</span>
{f.runUrl && <a href={f.runUrl} className="text-xs text-primary">лог</a>}
</span>
}
>
{f.logTail && <pre className="m-0 max-h-80 overflow-auto font-mono text-[11px] whitespace-pre-wrap">{f.logTail.split("\n").slice(-60).join("\n")}</pre>}
</Disclosure>
))}
</PanelSection>
<PanelSection title="События">
{events.length === 0 ? (
<p className="m-0 text-sm text-muted-foreground">Событий нет.</p>
) : (
<ol className="m-0 flex list-none flex-col gap-1.5 border-l p-0 pl-3">
{events.map((e) => (
<li key={e.id} className="text-xs [overflow-wrap:anywhere]">
<span className="font-mono text-muted-foreground">{ago(e.createdAt)}</span> <span className="font-mono text-primary">{e.type}</span>{" "}
{e.type === "progress" ? (e.payload as { text: string }).text : e.type === "task_updated" ? JSON.stringify((e.payload as { to: unknown }).to) : ""}
</li>
))}
</ol>
)}
</PanelSection>
</div>
);
return (
<Workspace aside={aside}>
<AutoRefresh />
<Flash error={error} />
<PageHeader
crumbs={
<>
<Link href={`/p/${project.key}`} className="text-muted-foreground hover:text-foreground">{project.name}</Link>
{epic && (
<>
<span className="text-muted-foreground">/</span>
<Link href={`/p/${project.key}?epic=${epic.id}`} title="Эпик" className="text-muted-foreground hover:text-foreground">
эпик «{epic.title}»
</Link>
</>
)}
</>
}
title={
<>
<span className="font-mono text-primary">{ref.key}</span> {task.title} <StatusBadge status={task.status} />
</>
}
actions={
task.prUrl && (
<Button asChild size="sm">
<a href={task.prUrl}>
<GitPullRequest />
PR
</a>
</Button>
)
}
/>
<div className="rounded-lg border bg-card p-4 text-sm whitespace-pre-wrap">{task.description || <span className="text-muted-foreground">Без описания</span>}</div>
<Section title="Сессии">
<form action={startTaskSession} className="flex flex-wrap gap-2">
<Hidden fields={{ taskKey: ref.key, back }} />
<NativeSelect name="provider" defaultValue="" aria-label="Агент" className="w-auto">
<option value="">{pool || superadmin ? "Любой агент" : "Claude Code"}</option>
<option value="claude">Claude Code</option>
<option value="codex">Codex</option>
<option value="opencode">OpenCode</option>
</NativeSelect>
{superadmin && (
<NativeSelect name="choice" defaultValue="" aria-label="Подписки" className="w-auto">
<option value="">{pool ? `Пул проекта: ${pool.name}` : "Без пула (вход машины)"}</option>
{pools.filter((p) => p.id !== pool?.id).map((p) => (
<option key={p.id} value={`pool:${p.id}`}>Пул: {p.name}</option>
))}
{subs.length > 0 && <option value="pick">Отмеченные подписки ↓</option>}
</NativeSelect>
)}
<Input name="prompt" placeholder="Доп. инструкция (необязательно)" aria-label="Доп. инструкция" className="flex-[1_1_14rem]" />
<Button variant="default">
<Play />
Запустить агента
</Button>
{superadmin && subs.length > 0 && (
<details className="basis-full text-sm">
<summary className="cursor-pointer text-muted-foreground">Отметить подписки (для «Отмеченные подписки»)</summary>
<div className="mt-2 flex flex-col gap-1">
{subs.map((s) => (
<label key={s.id} className="flex items-center gap-2">
<input type="checkbox" name="subscription" value={s.id} className="size-4 accent-primary" />
<span className="text-muted-foreground">{PROVIDER_NAMES[s.provider]}</span> {s.name}
<span className="text-xs text-muted-foreground">· {s.status === "active" ? "активна" : s.status === "limited" ? "лимит" : s.status === "pending" ? "ожидает входа" : "ошибка входа"} · сессий {s.activeSessions}</span>
</label>
))}
</div>
</details>
)}
</form>
{!superadmin && pool && <p className="m-0 text-xs text-muted-foreground">Агент запустится на свободной подписке пула «{pool.name}».</p>}
{sessions.map((s) => (
// PEP-9: the live terminal of the newest unfinished runner.
<SessionCard key={s.id} s={s} back={back} terminal={s.id === liveId} />
))}
</Section>
<Section title="Вопросы">
{questions.length === 0 ? <Empty>Вопросов не было.</Empty> : questions.map((q) => <QuestionCard key={q.id} q={q} taskStatus={task.status} back={back} />)}
</Section>
<Section title={<>OpenSpec {task.openspecChange && <span className="ml-1 font-mono text-xs font-normal text-muted-foreground">{task.openspecChange}</span>}</>}>
{artifacts?.length ? (
artifacts.map((a) => (
<Disclosure key={a.name} open={a.name === "proposal.md"} summary={<span className="font-mono">{a.name}</span>}>
<pre className="m-0 max-h-[32em] overflow-auto font-mono text-xs leading-relaxed whitespace-pre-wrap">{a.text}</pre>
</Disclosure>
))
) : (
<Empty>Change ещё не создан.</Empty>
)}
</Section>
</Workspace>
);
}