diff --git a/apps/web/app/(app)/sessions/page.tsx b/apps/web/app/(app)/sessions/page.tsx new file mode 100644 index 00000000..64f5f175 --- /dev/null +++ b/apps/web/app/(app)/sessions/page.tsx @@ -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 ( + + + {t("Живые сессии агентов ваших проектов: выберите слева — справа сразу её терминал.")} + {gone && ( +

+ {t("Сессия #{id} уже завершена — открыта другая.", { id: gone })} +

+ )} + {!selected ? ( + + + + {t("Живых сессий нет.")} + {t("Агент запускается, когда стори переносят в «В работе» на доске проекта, или кнопкой «Новый терминал» в «Работе агентов».")} + + + ) : ( +
+ + +
+ )} +
+ ); +} + +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 ( +
  • + + + + {s.taskKey ?? s.projectKey} + {s.taskTitle ?? s.name ?? t("без стори")} + + + {t(st.label)} + · {PROVIDER_NAMES[s.provider]} + + + {s.agentName ? `${s.agentName} · ` : ""}#{s.id} · {ago(s.lastActivityAt, t)} + + +
  • + ); +} + +async function SessionPane({ s }: { s: SessionView }) { + const t = await getT(); + return ( +
    +
    + + {s.taskKey ? {s.taskKey} : {s.projectKey}} + {s.taskTitle ?? s.name ?? t("без стори")} + {s.agentName && } + + {PROVIDER_NAMES[s.provider]} · #{s.id} + +
    + +
    + +
    +
    + ); +} diff --git a/apps/web/app/(app)/t/[key]/page.tsx b/apps/web/app/(app)/t/[key]/page.tsx index 1bd887ec..69488d3e 100644 --- a/apps/web/app/(app)/t/[key]/page.tsx +++ b/apps/web/app/(app)/t/[key]/page.tsx @@ -337,8 +337,8 @@ export default async function StoryPage({ params, searchParams }: { params: Prom {live ? ( - // PEP-9 terminal + PEP-33 step feed of the newest unfinished runner. - + // PEP-33 step feed of the newest unfinished runner; its terminal — in «Сессии» (PEP-257). + ) : (
    diff --git a/apps/web/components/RunnerConsole.tsx b/apps/web/components/RunnerConsole.tsx index 0dbfda21..d80c22f1 100644 --- a/apps/web/components/RunnerConsole.tsx +++ b/apps/web/components/RunnerConsole.tsx @@ -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("Сессия завершена — терминала больше нет.")} ) : ( - + // PEP-257: one place for terminals — «Сессии», opened on this session. + + + {t("Открыть в «Сессиях»")} + )} diff --git a/apps/web/components/RunnerTerminal.tsx b/apps/web/components/RunnerTerminal.tsx index e1cecd32..60881111 100644 --- a/apps/web/components/RunnerTerminal.tsx +++ b/apps/web/components/RunnerTerminal.tsx @@ -1,9 +1,15 @@ "use client"; // Live runner terminal (PEP-9): xterm.js fed by the tab's live channel (`terminal:`, PEP-225), // input over the same channel; without a WebSocket — SSE of /api/runners//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 = { 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(null); const scroller = useRef(null); const term = useRef(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(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 ( -
    +
    @@ -200,10 +281,14 @@ export function RunnerTerminal({ sessionId, live }: { sessionId: number; live: b {input ? t("Ввод включён") : t("Ввод")} )} - + - {(status === "ended" || status === "error") && ( @@ -215,8 +300,12 @@ export function RunnerTerminal({ sessionId, live }: { sessionId: number; live: b {full ? : }
    -
    -
    +
    + {/* 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. */} +
    +
    +
    {input && live && (
    diff --git a/apps/web/components/Sidebar.tsx b/apps/web/components/Sidebar.tsx index 20b56178..78d5d340 100644 --- a/apps/web/components/Sidebar.tsx +++ b/apps/web/components/Sidebar.tsx @@ -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 }, diff --git a/apps/web/components/cards.tsx b/apps/web/components/cards.tsx index 8b7b68fe..1a9e9b36 100644 --- a/apps/web/components/cards.tsx +++ b/apps/web/components/cards.tsx @@ -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 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 }) { +/** + * `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 (
    @@ -236,15 +238,14 @@ export async function SessionCard({ s, back, showTitle = false, terminal = false - {!terminal && !["done", "failed"].includes(s.status) && ( + {!["done", "failed"].includes(s.status) && ( )} - {steps && } - {terminal && } + {steps && }
    ); }