PEP-257: раздел «Сессии», терминал без растяжения и по ширине

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
peppa-bot 2026-11-24 12:31:08 +00:00
parent 58abeef326
commit 65041d2dc4
6 changed files with 240 additions and 24 deletions

View File

@ -0,0 +1,121 @@
// glossary-ignore-file: раздел «Сессии» — терминалы агентов, только в виде «Инженер» (PEP-257)
// «Сессии» (PEP-257): one place for the terminals of all live agent sessions of the user's
// projects. Left — the list, right — the terminal of the chosen one, open right away: the first
// of the list without `?id`, the given one with it (a story links here with its session).
import Link from "next/link";
import { SquareTerminal } from "lucide-react";
import { FINISHED_SESSION_STATUSES, listUserSessions, PROVIDER_NAMES, type SessionView } from "@peppa/core";
import { AgentBadge } from "@/components/AgentBadge";
import { AttachCommand } from "@/components/cards";
import { ago, Empty, Key, PageHeader, StatusBadge } from "@/components/common";
import { LiveRefresh } from "@/components/LiveRefresh";
import { RunnerTerminal } from "@/components/RunnerTerminal";
import { Workspace } from "@/components/Workspace";
import { requireUser } from "@/lib/auth";
import { db } from "@/lib/db";
import { inbox } from "@/lib/queries";
import { SESSION_STATUS, TONE_BG, TONE_TEXT } from "@/lib/status";
import { cn } from "@/lib/utils";
import { getT } from "@/lib/i18n";
export default async function Sessions({ searchParams }: { searchParams: Promise<{ id?: string }> }) {
const user = await requireUser();
const t = await getT();
const { id } = await searchParams;
const [all, open] = await Promise.all([listUserSessions(db, user.id), inbox(user.id)]);
const asking = new Set(open.map((q) => q.sessionId).filter(Boolean));
const needsPm = (s: SessionView) => s.status === "waiting_input" || asking.has(s.id);
// Live ones only: who needs a person first, then the newest.
const live = all.filter((s) => !FINISHED_SESSION_STATUSES.includes(s.status)).sort((a, b) => Number(needsPm(b)) - Number(needsPm(a)) || b.id - a.id);
const wanted = id ? Number(id) : null;
const selected = (wanted && live.find((s) => s.id === wanted)) || live[0];
// The link pointed at a session that has ended (or is not the user's): say so, show the first.
const gone = wanted && selected?.id !== wanted ? wanted : null;
return (
<Workspace aside={null} wide>
<LiveRefresh scope="runners" />
<PageHeader title={t("Сессии")}>{t("Живые сессии агентов ваших проектов: выберите слева — справа сразу её терминал.")}</PageHeader>
{gone && (
<p className="mb-3 rounded-md border border-warn/40 bg-warn/10 px-3 py-2 text-sm" data-session-gone={gone}>
{t("Сессия #{id} уже завершена — открыта другая.", { id: gone })}
</p>
)}
{!selected ? (
<Empty>
<span className="flex flex-col items-center gap-2">
<SquareTerminal className="size-6" />
<span>{t("Живых сессий нет.")}</span>
<span>{t("Агент запускается, когда стори переносят в «В работе» на доске проекта, или кнопкой «Новый терминал» в «Работе агентов».")}</span>
</span>
</Empty>
) : (
<div className="grid gap-4 lg:grid-cols-[minmax(240px,300px)_minmax(0,1fr)]" data-sessions>
<nav aria-label={t("Список сессий")} className="min-w-0">
<ul className="m-0 flex list-none flex-col gap-1 rounded-lg border bg-card/50 p-1.5 lg:max-h-[calc(100dvh-10rem)] lg:overflow-y-auto">
{live.map((s) => (
<SessionRow key={s.id} s={s} selected={s.id === selected.id} needsPm={needsPm(s)} />
))}
</ul>
</nav>
<SessionPane key={selected.id} s={selected} />
</div>
)}
</Workspace>
);
}
async function SessionRow({ s, selected, needsPm }: { s: SessionView; selected: boolean; needsPm: boolean }) {
const t = await getT();
const st = SESSION_STATUS[s.status] ?? { label: s.status, tone: "muted" as const };
return (
<li>
<Link
href={`/sessions?id=${s.id}`}
scroll={false}
data-hotkey-item
data-session-row={s.id}
aria-current={selected ? "true" : undefined}
className={cn(
"grid grid-cols-[auto_minmax(0,1fr)] items-center gap-x-2.5 gap-y-0.5 rounded-md border border-transparent px-2.5 py-2 text-sm text-foreground transition-colors hover:bg-accent hover:no-underline",
needsPm && "bg-primary/[0.07] shadow-[inset_2px_0_0_var(--primary)]",
selected && "border-border bg-accent",
)}
>
<span className={cn("row-span-3 size-2 self-start mt-1.5 rounded-full", TONE_BG[st.tone], (s.status === "running" || s.status === "starting") && "animate-pulse")} />
<span className="flex min-w-0 items-baseline gap-2">
<span className="shrink-0 font-mono text-xs text-primary">{s.taskKey ?? s.projectKey}</span>
<span className="truncate">{s.taskTitle ?? s.name ?? t("без стори")}</span>
</span>
<span className="flex min-w-0 flex-wrap items-center gap-x-1.5 font-mono text-[11px]">
<span className={TONE_TEXT[st.tone]}>{t(st.label)}</span>
<span className="text-muted-foreground">· {PROVIDER_NAMES[s.provider]}</span>
</span>
<span className="truncate font-mono text-[11px] text-muted-foreground">
{s.agentName ? `${s.agentName} · ` : ""}#{s.id} · {ago(s.lastActivityAt, t)}
</span>
</Link>
</li>
);
}
async function SessionPane({ s }: { s: SessionView }) {
const t = await getT();
return (
<section aria-label={t("Терминал")} className="flex min-w-0 flex-col gap-2.5 lg:sticky lg:top-4 lg:h-[calc(100dvh-10rem)]" data-session-pane={s.id}>
<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>}
<span className="min-w-0 flex-[1_1_12em] truncate font-medium">{s.taskTitle ?? s.name ?? t("без стори")}</span>
{s.agentName && <AgentBadge name={s.agentName} />}
<span className="font-mono text-xs text-muted-foreground">
{PROVIDER_NAMES[s.provider]} · <Link href={`/runners?id=${s.id}`} className="text-muted-foreground hover:text-foreground">#{s.id}</Link>
</span>
</header>
<AttachCommand name={s.tmuxName} />
<div className="h-[70dvh] min-h-0 lg:h-auto lg:flex-1">
<RunnerTerminal sessionId={s.id} live fill />
</div>
</section>
);
}

View File

@ -337,8 +337,8 @@ export default async function StoryPage({ params, searchParams }: { params: Prom
<TaskRunnerSettings taskKey={ref.key} own={runnerOwn} inherited={runnerProject} back={back} />
<TaskAgentModel taskKey={ref.key} own={agentOwn} inherited={agentProject} escalation={escalation} back={back} />
{live ? (
// PEP-9 terminal + PEP-33 step feed of the newest unfinished runner.
<SessionCard s={live} back={back} terminal steps={steps} plainSteps={!engineer} />
// PEP-33 step feed of the newest unfinished runner; its terminal — in «Сессии» (PEP-257).
<SessionCard s={live} back={back} live steps={steps} plainSteps={!engineer} />
) : (
<form action={startTaskSession} className="flex flex-wrap gap-2">
<Hidden fields={{ taskKey: ref.key, back }} />

View File

@ -10,7 +10,6 @@ import { AgentSteps } from "@/components/AgentSteps";
import { AttachCommand, QuestionCard, SessionActions } from "@/components/cards";
import { ago, Key, StatusBadge } from "@/components/common";
import { LocalTime, ScrollIntoViewOnNarrow } from "@/components/LocalTime";
import { RunnerTerminal } from "@/components/RunnerTerminal";
import { SessionUsageLine } from "@/components/Accounting";
import type { InboxItem } from "@/lib/queries";
import { SESSION_STATUS, TONE_BG, TONE_TEXT } from "@/lib/status";
@ -192,7 +191,11 @@ export async function RunnerDetails({ s, questions, events, steps, stories, back
{t("Сессия завершена — терминала больше нет.")}
</div>
) : (
<RunnerTerminal key={s.id} sessionId={s.id} live />
// PEP-257: one place for terminals — «Сессии», opened on this session.
<Link href={`/sessions?id=${s.id}`} data-open-session={s.id} className="inline-flex items-center gap-2 self-start rounded-md border bg-card px-3 py-1.5 text-sm text-foreground hover:bg-accent hover:no-underline">
<SquareTerminal className="size-4" />
{t("Открыть в «Сессиях»")}
</Link>
)}
</PanelSection>

View File

@ -1,9 +1,15 @@
"use client";
// Live runner terminal (PEP-9): xterm.js fed by the tab's live channel (`terminal:<id>`, PEP-225),
// input over the same channel; without a WebSocket — SSE of /api/runners/<id>/terminal and POST.
// PEP-257: the font is given to xterm resolved (a CSS variable is not understood when xterm
// measures its cell — the cell came out wider than the glyphs and got letter-spacing), the cell
// is re-measured when web fonts arrive. By default the whole grid is scaled to the panel width so
// all columns of the pane are visible («по ширине»): a CSS scale of the grid xterm drew, because
// font sizes alone do not fit — browsers round small glyph advances to whole pixels. +/- switch
// to a fixed font size, unscaled, with scrolling.
import "@xterm/xterm/css/xterm.css";
import type { Terminal } from "@xterm/xterm";
import { Keyboard, Maximize2, Minimize2, Minus, Plus, RotateCw } from "lucide-react";
import { ArrowLeftRight, Keyboard, Maximize2, Minimize2, Minus, Plus, RotateCw } from "lucide-react";
import { useCallback, useEffect, useRef, useState } from "react";
import { cn } from "@/lib/utils";
import { liveClient, useLiveMode } from "@/lib/live";
@ -19,8 +25,13 @@ const STATUS_TEXT: Record<Status, string> = {
error: m("нет доступа к терминалу"),
};
const FONT_KEY = "peppa_term_font";
const FIT_KEY = "peppa_term_fit";
const FONT_MIN = 7;
const FONT_MAX = 20;
/** «По ширине» does not blow a narrow pane up beyond this. */
const FIT_MAX_SCALE = 1.5;
/** Horizontal padding of the terminal frame (p-1.5 on both sides + border). */
const FRAME_PAD = 14;
/** Keys a phone keyboard lacks. */
const QUICK_KEYS: Array<[string, string]> = [
["Esc", "\x1b"],
@ -31,6 +42,23 @@ const QUICK_KEYS: Array<[string, string]> = [
["Ctrl-C", "\x03"],
];
function readFit(): boolean {
try {
return localStorage.getItem(FIT_KEY) !== "0";
} catch {
return true;
}
}
/**
* The page's monospace font as real family names: `var(--font-geist-mono)` resolved here,
* because xterm measures its cell with this string outside CSS (PEP-257).
*/
function monoFont(): string {
const v = getComputedStyle(document.documentElement).getPropertyValue("--font-geist-mono").trim();
return [v, "ui-monospace", "Menlo", '"DejaVu Sans Mono"', "monospace"].filter(Boolean).join(", ");
}
function readFont(): number {
try {
const n = Number(localStorage.getItem(FONT_KEY));
@ -40,7 +68,8 @@ function readFont(): number {
}
}
export function RunnerTerminal({ sessionId, live }: { sessionId: number; live: boolean }) {
/** `fill`: the terminal takes the height of its parent (the «Сессии» page), not 60vh. */
export function RunnerTerminal({ sessionId, live, fill = false }: { sessionId: number; live: boolean; fill?: boolean }) {
const host = useRef<HTMLDivElement>(null);
const scroller = useRef<HTMLDivElement>(null);
const term = useRef<Terminal | null>(null);
@ -51,6 +80,11 @@ export function RunnerTerminal({ sessionId, live }: { sessionId: number; live: b
const [input, setInput] = useState(false);
const [full, setFull] = useState(false);
const [font, setFont] = useState(12);
const [fit, setFit] = useState(true);
/** The panel's width and the size of the grid xterm drew (unscaled): what «по ширине» fits. */
const [width, setWidth] = useState(0);
const [grid, setGrid] = useState({ w: 0, h: 0 });
const family = useRef("monospace");
const [error, setError] = useState<string | null>(null);
const [attempt, setAttempt] = useState(0);
const t = useT();
@ -95,13 +129,20 @@ export function RunnerTerminal({ sessionId, live }: { sessionId: number; live: b
let disposed = false;
let cleanup = () => {};
setFont(readFont());
void import("@xterm/xterm").then(({ Terminal }) => {
setFit(readFit());
const font = monoFont();
family.current = font;
// Open only when the web font is there: xterm measures the cell once, at open.
const fonts = document.fonts;
const ready = fonts ? Promise.race([fonts.load(`12px ${font}`, "W Ж").then(() => fonts.ready), new Promise((r) => setTimeout(r, 2000))]) : Promise.resolve();
void Promise.all([import("@xterm/xterm"), ready]).then(([{ Terminal }]) => {
if (disposed || !host.current) return;
const t = new Terminal({
cols: 120,
rows: 30,
fontSize: readFont(),
fontFamily: "var(--font-geist-mono), ui-monospace, Menlo, monospace",
fontFamily: font,
letterSpacing: 0,
scrollback: 5000,
disableStdin: true,
cursorBlink: false,
@ -120,8 +161,16 @@ export function RunnerTerminal({ sessionId, live }: { sessionId: number; live: b
};
const el = host.current;
el.addEventListener("paste", onPaste, true);
// A font (or a Cyrillic subset of it) loaded later: make xterm measure the cell again.
let flip = false;
const remeasure = () => {
flip = !flip;
t.options.fontFamily = flip ? `${font} ` : font;
};
fonts?.addEventListener("loadingdone", remeasure);
term.current = t;
cleanup = () => {
fonts?.removeEventListener("loadingdone", remeasure);
el.removeEventListener("paste", onPaste, true);
onData.dispose();
t.dispose();
@ -170,14 +219,46 @@ export function RunnerTerminal({ sessionId, live }: { sessionId: number; live: b
if (inputRef.current) t.focus();
}, [input, live, attempt]);
// The panel's width and the grid's size (layout size: a transform does not change it).
useEffect(() => {
const el = scroller.current;
const g = host.current;
if (!el || !g || typeof ResizeObserver === "undefined") return;
const ro = new ResizeObserver(() => {
setWidth(el.clientWidth);
setGrid({ w: g.offsetWidth, h: g.offsetHeight });
});
ro.observe(el);
ro.observe(g);
return () => ro.disconnect();
}, []);
const scale = fit && grid.w && width ? Math.min(FIT_MAX_SCALE, (width - FRAME_PAD) / grid.w) : 1;
/** The font size the user sees. */
const size = Math.round(font * scale * 10) / 10;
useEffect(() => {
const t = term.current;
if (!t || t.options.fontSize === font) return;
t.options.fontSize = font;
// Keep the bottom of the pane (where the agent works and the tmux status line is) in view.
requestAnimationFrame(() => scroller.current && (scroller.current.scrollTop = scroller.current.scrollHeight));
}, [font, attempt]);
useEffect(() => {
if (term.current) term.current.options.fontSize = font;
try {
localStorage.setItem(FONT_KEY, String(font));
localStorage.setItem(FIT_KEY, fit ? "1" : "0");
} catch {
// private mode: the size just is not remembered
}
}, [font]);
}, [font, fit]);
/** +/-: from «по ширине» go on from the size shown now. */
const zoom = (d: number) => {
setFit(false);
setFont(Math.max(FONT_MIN, Math.min(FONT_MAX, Math.round(fit ? size : font) + d)));
};
useEffect(() => {
if (!full) return;
@ -188,7 +269,7 @@ export function RunnerTerminal({ sessionId, live }: { sessionId: number; live: b
const btn = "inline-flex items-center gap-1 rounded-md border bg-card px-2 py-1 text-xs text-muted-foreground hover:bg-accent hover:text-foreground disabled:opacity-50";
return (
<div className={cn("flex flex-col gap-2", full && "fixed inset-0 z-50 bg-background p-3")} data-terminal-status={status}>
<div className={cn("flex min-w-0 flex-col gap-2", fill && "h-full min-h-0", full && "fixed inset-0 z-50 bg-background p-3")} data-terminal-status={status} data-terminal-font={size}>
<div className="flex flex-wrap items-center gap-1.5">
<span className={cn("mr-auto flex items-center gap-1.5 font-mono text-[11px]", status === "live" ? "text-ok" : status === "error" ? "text-destructive" : "text-muted-foreground")}>
<span className={cn("size-1.5 rounded-full bg-current", status === "live" && "animate-pulse")} />
@ -200,10 +281,14 @@ export function RunnerTerminal({ sessionId, live }: { sessionId: number; live: b
{input ? t("Ввод включён") : t("Ввод")}
</button>
)}
<button type="button" className={btn} onClick={() => setFont((f) => Math.max(FONT_MIN, f - 1))} aria-label={t("Мельче")} title={t("Мельче")}>
<button type="button" className={cn(btn, fit && "border-primary/60 bg-primary/10 text-foreground")} onClick={() => setFit((v) => !v)} aria-pressed={fit} title={t("Все колонки по ширине окна")} data-terminal-fit>
<ArrowLeftRight className="size-3.5" />
{t("По ширине")}
</button>
<button type="button" className={btn} onClick={() => zoom(-1)} aria-label={t("Мельче")} title={t("Мельче")} data-terminal-zoom="-">
<Minus className="size-3.5" />
</button>
<button type="button" className={btn} onClick={() => setFont((f) => Math.min(FONT_MAX, f + 1))} aria-label={t("Крупнее")} title={t("Крупнее")}>
<button type="button" className={btn} onClick={() => zoom(1)} aria-label={t("Крупнее")} title={t("Крупнее")} data-terminal-zoom="+">
<Plus className="size-3.5" />
</button>
{(status === "ended" || status === "error") && (
@ -215,8 +300,12 @@ export function RunnerTerminal({ sessionId, live }: { sessionId: number; live: b
{full ? <Minimize2 className="size-3.5" /> : <Maximize2 className="size-3.5" />}
</button>
</div>
<div ref={scroller} className={cn("overflow-auto rounded-lg border bg-[#0b0b0d] p-1.5", full ? "min-h-0 flex-1" : "max-h-[60vh]", input && live && "border-primary/60")}>
<div ref={host} className="w-max" />
<div ref={scroller} data-terminal-scroller className={cn("overflow-auto rounded-lg border bg-[#0b0b0d] p-1.5", full || fill ? "min-h-0 flex-1" : "max-h-[60vh]", input && live && "border-primary/60")}>
{/* xterm's helper textarea and scrollbar keep offsets of the previous font size for a
moment and stuck out below the terminal (a blank strip to scroll into) — clip them. */}
<div style={scale !== 1 ? { width: grid.w * scale, height: grid.h * scale } : undefined} className="overflow-hidden">
<div ref={host} className="w-max origin-top-left overflow-hidden" style={scale !== 1 ? { transform: `scale(${scale})` } : undefined} />
</div>
</div>
{input && live && (
<div className="flex flex-wrap gap-1.5">

View File

@ -4,7 +4,7 @@ import Link from "next/link";
import { usePathname } from "next/navigation";
import { useEffect, useState } from "react";
import { useLive } from "@/lib/live";
import { Activity, Bot, PlugZap, Contact, FolderKanban, Gauge, GitBranch, Megaphone, House, KeyRound, MessagesSquare, ScrollText, LifeBuoy, LogOut, MessageCircleWarning, Search, Server, Settings, ShieldCheck, Sparkles, Users, type LucideIcon } from "lucide-react";
import { Activity, Bot, PlugZap, Contact, FolderKanban, Gauge, GitBranch, Megaphone, House, KeyRound, MessagesSquare, ScrollText, LifeBuoy, LogOut, MessageCircleWarning, Search, Server, Settings, ShieldCheck, Sparkles, SquareTerminal, Users, type LucideIcon } from "lucide-react";
import { Brand } from "@/components/Brand";
import { ThemeToggle } from "@/components/ThemeToggle";
import { LanguageSwitcher } from "@/components/I18n";
@ -31,6 +31,8 @@ const ITEMS: Item[] = [
{ href: "/", label: m("Главная"), icon: House, match: (p) => p === "/", count: "questions" },
{ href: "/chats", label: m("Чаты"), icon: MessagesSquare, match: (p) => p.startsWith("/chats"), count: "chats" },
{ href: "/projects", label: m("Проекты"), icon: FolderKanban, match: (p) => p.startsWith("/projects") || p.startsWith("/p/") || p.startsWith("/t/") },
// glossary-ignore: PEP-257, терминалы агентов — пункт только в виде «Инженер»
{ href: "/sessions", label: m("Сессии"), icon: SquareTerminal, match: (p) => p.startsWith("/sessions"), desktopOnly: true, engineer: true },
{ href: "/runners", label: m("Работа агентов"), icon: Bot, match: (p) => p.startsWith("/runners"), count: "waitingRunners", engineer: true },
{ href: "/connections", label: m("Подключения"), icon: PlugZap, match: (p) => p.startsWith("/connections"), desktopOnly: true },
{ href: "/team", label: m("Команда"), icon: Contact, match: (p) => p.startsWith("/team"), desktopOnly: true },

View File

@ -16,7 +16,6 @@ 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 { cleanText } from "@/lib/chat-text";
@ -215,8 +214,11 @@ 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 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 }) {
/**
* `steps` (PEP-33): the step feed of the agent, `live` — it follows the running agent.
* PEP-257: the terminal is not embedded here — it opens in «Сессии» on this session.
*/
export async function SessionCard({ s, back, showTitle = false, live = false, steps, plainSteps = false }: { s: SessionView; back: string; showTitle?: boolean; live?: boolean; steps?: StepView[]; /** PEP-154: «Продакт» — steps in words. */ plainSteps?: boolean }) {
const t = await getT();
return (
<article className="flex flex-col gap-2.5 rounded-lg border bg-card p-3.5">
@ -236,15 +238,14 @@ export async function SessionCard({ s, back, showTitle = false, terminal = false
<SessionUsageLine usage={s.usage} provider={s.provider} />
<AttachCommand name={s.tmuxName} />
<SessionActions s={s} back={back} />
{!terminal && !["done", "failed"].includes(s.status) && (
{!["done", "failed"].includes(s.status) && (
<Button asChild size="sm" variant="outline" className="self-start">
<Link href={`/runners?id=${s.id}`}>
<SquareTerminal /> {t("Открыть терминал")}
<Link href={`/sessions?id=${s.id}`} data-open-session={s.id}>
<SquareTerminal /> {t("Открыть в «Сессиях»")}
</Link>
</Button>
)}
{steps && <AgentSteps key={`steps-${s.id}`} sessionId={s.id} initial={steps} live={terminal} hooks={s.provider === "claude"} plain={plainSteps} />}
{terminal && <RunnerTerminal key={s.id} sessionId={s.id} live />}
{steps && <AgentSteps key={`steps-${s.id}`} sessionId={s.id} initial={steps} live={live} hooks={s.provider === "claude"} plain={plainSteps} />}
</article>
);
}