PEP-257: раздел «Сессии», терминал без растяжения, нижняя панель tmux #243
@ -10,8 +10,8 @@
|
||||
|
||||
## Грабли
|
||||
- `resumeSession` у сессии без `conversationId` пишет событие `started`, не `resumed`.
|
||||
- `next dev` правит apps/web/AGENTS.md (он в git — `git checkout`, не `rm`) и next-env.d.ts — не коммитить. Открывать `http://localhost:<порт>`, не 127.0.0.1 (allowedDevOrigins — без гидрации кнопки молчат).
|
||||
- Headless Chrome: playwright-core + `chrome-headless-shell`, cookie из curl-jar в `ctx.addCookies`; обрыв канала — `globalThis.__peppaLive.ws.close()`.
|
||||
- `next dev` правит apps/web/AGENTS.md (`git checkout`, не `rm`) и next-env.d.ts — не коммитить; открывать `localhost`, не 127.0.0.1. В песочнице dev перезагружает страницы по кругу — экраны смотри на `next build` + `node server.ts -p`.
|
||||
- Headless Chrome: playwright-core + `chrome-headless-shell` (песочница: `npx playwright-core install chromium-headless-shell`; библиотеки — .deb bookworm из Packages.gz → `dpkg-deb -x` + LD_LIBRARY_PATH, шрифты fonts-dejavu-core + FONTCONFIG_PATH); вход — `peppa web login-link`; обрыв канала — `globalThis.__peppaLive.ws.close()`.
|
||||
- CLI из теста с моком в том же процессе — только async execFile. Тест не импортирует apps/web статически — `import(new URL(…).href)`.
|
||||
- Шаблонная строка с t()/m() внутри (`` `<b>${t("…")}</b>` ``) i18n-check считает непереведённой — собирай конкатенацией. В apps/bot `m` импортирован как `tr`.
|
||||
- localizeText выбирает вариант по числу НЕпереведённых русских букв, не по кириллице: казахский тоже кириллица.
|
||||
|
||||
@ -17,7 +17,7 @@
|
||||
- `packages/testkit` — `mock-claude` / `mock-codex` / `mock-opencode`, `mock-telegram` (мок Bot API) (моки CLI агентов по сценариям: хуки, notify, MCP, лимиты, зависания, падения) и e2e-набор CJM
|
||||
- `packages/cli` — CLI `peppa` (project/goal/task/q), пока нет веба
|
||||
- `packages/runner` — запуск claude в tmux (`peppa-<task>-s<id>`), вачдог, `peppa-hook`
|
||||
- Терминал в вебе (PEP-9): `runner/terminal.ts` — `TerminalFeed` опрашивает pane (`capture-pane -e` + `display-message`, 250 мс, один цикл на раннер для всех зрителей, `globalThis`), шлёт изменившиеся строки и ушедшие в историю; `terminalInput` (`send-keys -H` / `paste-buffer -p`; только владелец/участник, живая сессия, ≤1 КБ нажатий / 64 КБ вставки, 40 запросов за 5 с, сброс `auto_nudges`, событие `terminal_input` раз в минуту). Веб: `GET/POST /api/runners/<id>/terminal` (SSE + JSON, пинг 15 с для Cloudflare), `components/RunnerTerminal.tsx` (xterm.js); pane браузер не ресайзит
|
||||
- Терминал в вебе (PEP-9): `runner/terminal.ts` — `TerminalFeed` опрашивает pane (`capture-pane -e` + `display-message`, 250 мс, один цикл на раннер для всех зрителей, `globalThis`), шлёт изменившиеся строки и ушедшие в историю; `terminalInput` (`send-keys -H` / `paste-buffer -p`; только владелец/участник, живая сессия, ≤1 КБ нажатий / 64 КБ вставки, 40 запросов за 5 с, сброс `auto_nudges`, событие `terminal_input` раз в минуту). Веб: `GET/POST /api/runners/<id>/terminal` (SSE + JSON, пинг 15 с для Cloudflare), `components/RunnerTerminal.tsx` (xterm.js); pane браузер не ресайзит. **Раздел «Сессии» (PEP-257)**: `/sessions` (меню «Инженер») — слева живые сессии, справа терминал выбранной (`?id=`, без него первая); стори и «Работа агентов» терминал не встраивают — ссылка `/sessions?id=<id>`. xterm получает вычисленный шрифт (не `var(--font-geist-mono)`: при замере ячейки он не раскрывается → `letter-spacing`), «По ширине» = CSS `scale` сетки. Строка статуса tmux: `paneInfo` берёт `#{T:status-format[i]}`, `runner/tmux-status.ts` переводит `#[…]` в SGR, `TerminalFeed` добавляет её к экрану (кадр = pane + строки статуса)
|
||||
- Шаги агента (PEP-33): хуки `PostToolUse`/`PostToolUseFailure` с `async: true` → `peppa-hook tool-use` → `recordStep` (core/steps.ts: событие `step` `{tool, kind, text, ok}`, последние 200 на сессию, `last_activity_at` без `notify()`); шаги исключены из журнала стори, `get_task` и «Событий» раннера; лента — `components/AgentSteps.tsx` (у живой сессии на странице стори и в панели раннера, новые шаги — событием `step` из `/api/live?scope=steps:<id>`); прогресс tasks.md («7/12» и текущий пункт) — на карточках доски «В работе» и в шапке стори. Codex/OpenCode шагов не шлют
|
||||
- **Раннеры (PEP-10/27/53)**: настройки `core/runners.ts` с наследованием `platform.runner` → `project.runner:<id>` → `task.runner:<taskId>` (строки `settings`): `mode` story (по умолчанию, один раннер на стори) / queue, `context` fresh / continue, `workspace` shared / worktree, `maxRunners`. История и очередь — таблица `runner_tasks`, имя — `sessions.name`. `moveTask` → `startTaskOnRunner` (runner/runners.ts); переход к следующей стори и переезд очереди упавшего раннера — `runnerTick` в вачдоге; queue: «Готово» освобождает раннер (`releaseRunner`), fresh = `relaunchFresh` (тот же tmux, новое поколение без resume). Worktree — runner/worktree.ts (`$PEPPA_HOME/worktrees/<slug>/s<id>`, `sessions.workspace_path`, ветка `task/<key>`, уборка когда чисто и всё запушено). Свободный раннер — `startFreeRunner` (без стори; хук не пингует), `promoteRunner` («Оформить стори»), `renameRunner`; CLI `peppa runner new|rename|promote|queue|show|settings`
|
||||
- **Раннер-сервис (PEP-21)**: процессы агентов запускает только вачдог (`peppa watchdog` = раннер-сервис, `serveRunnerCommands` в runner/runner-service.ts). Веб (`instrumentation.ts`) и бот (`apps/bot/src/index.ts`) — клиенты (`setRunnerClient`, флаг в `globalThis`): функции жизненного цикла (`startSession`, `startFreeRunner`, `startTaskOnRunner`, `resumeSession`, `stopSession`, `sendToSession`, `moveTask`, `archiveTask`, `acceptTask`, `acceptStory`, `answerAndDeliver`, `queueTaskOnRunner`, `promoteRunner`) первой строкой уходят в `runnerCall` (runner/runner-client.ts): строка в `runner_commands` (payload — id, автор PEP-48 → `runAsActor` в сервисе) + пинок в `$PEPPA_HOME/runner.sock`, ожидание результата; изменяющие tmux-операции (`newSession`/`killSession`/`sendText`/`sendKeys`/`sendHex`) из прочих путей — командой `tmux` (payload стирается после выполнения). Ключ `task:<id>`/`session:<id>` — одна стори по очереди. Нет сокета → сразу ошибка «Агенты сейчас не запускаются: служба запуска не работает…» (PEP-137; админу — `peppa status` и launchd-агент `quest.telecom.peppa.watchdog`), не взял за 15 с (`PEPPA_RUNNER_PICKUP_SEC`) → `expired` и ошибка, поздно не выполняется; рестарт сервиса → `running` → `failed`. Тесты по умолчанию «на месте» (флаг ставят только бинари); `runAsRunnerService` — контекст сервиса в одном процессе с клиентом. `PEPPA_RUNNER_MODE=inline` — аварийный откат. CLI `session start|send|resume|stop`, `runner new|promote|queue`, `q answer` — через сервис, если он жив; `peppa runner commands`, `peppa status`
|
||||
|
||||
121
apps/web/app/(app)/sessions/page.tsx
Normal 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: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>
|
||||
);
|
||||
}
|
||||
@ -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 }} />
|
||||
|
||||
@ -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,12 @@ 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" />
|
||||
{/* glossary-ignore: «Работа агентов» и «Сессии» — только в виде «Инженер» */}
|
||||
{t("Открыть в «Сессиях»")}
|
||||
</Link>
|
||||
)}
|
||||
</PanelSection>
|
||||
|
||||
|
||||
@ -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,21 @@ 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;
|
||||
// i18n-ignore: sample glyphs (Latin and Cyrillic) for the font loader, not a text
|
||||
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 +162,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 +220,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 +270,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 +282,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 +301,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="w-max 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">
|
||||
|
||||
@ -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 },
|
||||
|
||||
@ -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,16 @@ 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) && (
|
||||
{/* «Сессии» are a section of «Инженер»: a product view gets no terminal link (PEP-123). */}
|
||||
{!["done", "failed"].includes(s.status) && (await uiMode()) === "engineer" && (
|
||||
<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}>
|
||||
{/* glossary-ignore: кнопка только в виде «Инженер» */}
|
||||
<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>
|
||||
);
|
||||
}
|
||||
|
||||
@ -40,5 +40,5 @@
|
||||
"apps/web/components/RunnerTerminal.tsx": {"tmux": 1, "сессия": 2, "терминал": 2},
|
||||
"apps/web/components/Runners.tsx": {"tmux": 1, "ветка": 1, "контекст": 1, "пул": 2, "раннер": 12, "стори": 15, "терминал": 2, "токен": 1},
|
||||
"apps/web/components/Sidebar.tsx": {"команда": 2},
|
||||
"apps/web/components/cards.tsx": {"tmux": 1, "терминал": 3}
|
||||
"apps/web/components/cards.tsx": {"tmux": 1, "терминал": 2}
|
||||
}
|
||||
|
||||
@ -0,0 +1,61 @@
|
||||
## Context
|
||||
|
||||
Терминал (PEP-9/225) — xterm.js 6 (DOM-рендерер), кадры строит `TerminalFeed` из
|
||||
`capture-pane -e`. Pane агента создаётся шириной 220 колонок и высотой 50 строк.
|
||||
|
||||
## Диагностика (воспроизведено на стенде, браузер headless Chromium)
|
||||
|
||||
1. **Широкие промежутки.** У `.xterm-rows` вычисленный `letter-spacing: 3px`, ширина экрана
|
||||
2200 px на 220 колонок (10 px ячейка при шрифте 12 px). xterm замеряет ячейку по строке
|
||||
`fontFamily`, переданной в опциях: `var(--font-geist-mono), …`. В замере (canvas/offscreen)
|
||||
CSS-переменные не раскрываются — замер идёт шрифтом по умолчанию, ячейка шире настоящего
|
||||
глифа, и DOM-рендерер добивает разницу `letter-spacing`. Плюс замер был до загрузки
|
||||
веб-шрифта. Решение: передавать xterm уже вычисленное значение переменной
|
||||
(`getComputedStyle(...).getPropertyValue("--font-geist-mono")`), открывать терминал после
|
||||
`document.fonts.load(...)` и после `loadingdone` переустанавливать `fontFamily` (xterm
|
||||
перемеряет ячейку).
|
||||
2. **Обрезка справа.** Pane 220 колонок, панель 300–1100 px: при 12 px шрифте видна часть
|
||||
строки, а прокрутка в узкой панели незаметна. Решение: режим «по ширине» по умолчанию —
|
||||
сетка, которую нарисовал xterm, масштабируется CSS `transform: scale(k)`, k = ширина области /
|
||||
ширина сетки (≤ 1.5; `ResizeObserver` на области и на сетке — смена размера окна, pane, полный
|
||||
экран). Подбор размера шрифта не подошёл: на стенде браузер округляет ширину глифа мелкого
|
||||
шрифта до целых пикселей (6 px → ячейка 4 px, 5 px → 3 px), сетка 220 колонок получалась либо
|
||||
шире области, либо заметно уже. +/- включают ручной размер шрифта без масштаба и с
|
||||
горизонтальной прокруткой, «По ширине» возвращает подгонку. Размер pane браузер не меняет
|
||||
(как и раньше: от него зависит вывод агента).
|
||||
3. **Нет панели tmux.** `capture-pane` отдаёт только содержимое pane, строку статуса tmux
|
||||
рисует клиенту при `attach`, поэтому в веб она не попадала никогда (настройки `status`
|
||||
у сессий не трогаются, `status on`). Решение: тем же вызовом `tmux` (команды через `;`),
|
||||
что и размер/курсор, получаем `#{status}`, `#{status-position}`, `#{window_width}`,
|
||||
`#{E:status-style}` и `#{T:status-format[i]}` — tmux сам раскрывает свою конфигурацию
|
||||
(имя сессии, окна, флаги, время, правая часть). Результат содержит стили `#[…]`;
|
||||
`tmux-status.ts` переводит их в SGR (цвета по имени, `colourN`, `#rrggbb`, атрибуты,
|
||||
`default`/`push-default`/`pop-default`, `align=left|centre|right`, маркеры списка окон
|
||||
скрыты) и раскладывает строку на ширину окна. Строки статуса — часть «виртуального»
|
||||
экрана кадра: снизу (или сверху при `status-position top`), курсор сдвигается, диффы и
|
||||
прокрутка работают как раньше. Это не имитация: текст и цвета — вывод самого tmux.
|
||||
|
||||
## Decisions
|
||||
|
||||
- Раздел называется «Сессии», только в виде «Инженер» (словарь запрещает «сессия»,
|
||||
«терминал» в виде «Продакт»; там терминала не было и нет). Адрес `/sessions`.
|
||||
- Список — живые сессии (`FINISHED_SESSION_STATUSES` исключены) из `listUserSessions`:
|
||||
сначала ждущие человека, потом новые. `?id` завершённой или чужой сессии → выбирается
|
||||
первая и показывается строка «Сессия #N уже завершена».
|
||||
- Терминал на странице сессии занимает всю высоту окна справа (`fill`), без iframe.
|
||||
- В «Работе агентов» терминал тоже заменён ссылкой — одна точка доступа к терминалам.
|
||||
- Несколько строк статуса (`status 2..5`) поддерживаются; ширина — `window_width`
|
||||
(у отсоединённой сессии клиента нет).
|
||||
- Ширина символов строки статуса — упрощённая wcwidth (широкие CJK/эмодзи = 2, комбинирующие = 0).
|
||||
|
||||
- Полный экран (`fixed inset-0`) не должен лежать внутри `position: sticky` — тот создаёт свой
|
||||
контекст наложения, и левое меню перекрывало терминал; правая колонка «Сессий» без sticky.
|
||||
- Ссылка «Открыть в «Сессиях»» на странице стори — только в виде «Инженер» (в «Продакте» слов
|
||||
«сессия»/«терминал» нет, как и раньше терминала).
|
||||
|
||||
## Risks
|
||||
- Выделение мышью в режиме «по ширине»: xterm считает координаты без учёта `transform`, выделение
|
||||
может съезжать; для точного копирования — +/- (без масштаба). Ввод с клавиатуры не затронут.
|
||||
|
||||
- Лишние поля в одном вызове `display-message` на тик — без нового процесса tmux.
|
||||
- Шрифт «по ширине» на узком телефоне мелкий (минимум 5 px) — для чтения есть +/- и полный экран.
|
||||
|
After Width: | Height: | Size: 167 KiB |
|
After Width: | Height: | Size: 31 KiB |
|
After Width: | Height: | Size: 428 KiB |
|
After Width: | Height: | Size: 396 KiB |
|
After Width: | Height: | Size: 353 KiB |
|
After Width: | Height: | Size: 130 KiB |
|
After Width: | Height: | Size: 428 KiB |
|
After Width: | Height: | Size: 319 KiB |
|
After Width: | Height: | Size: 590 KiB |
|
After Width: | Height: | Size: 451 KiB |
@ -0,0 +1,48 @@
|
||||
# PEP-257: визуальная проверка терминала и раздела «Сессии»
|
||||
|
||||
Стенд: production-сборка веба (`next build` + `node server.ts`), отдельная база с `mock-ui-seed`,
|
||||
настоящий tmux 3.3a (`PEPPA_TMUX_SOCKET=stand`), в pane — вывод с русскими и английскими
|
||||
строками, цветным diff, строками длиннее окна и статусной строкой Claude Code; pane 220×50, как
|
||||
у агентов. Браузер — headless Chromium (playwright-core), окно 1440×900, `deviceScaleFactor: 2`
|
||||
(как Retina). Сценарий — `scenario.mjs` (результат каждого шага — JSON ниже).
|
||||
|
||||
## До исправления
|
||||
|
||||
- `0-before-panel.png`, `0-before-terminal.png` — «Работа агентов», терминал в панели:
|
||||
`letter-spacing: 3px` у строк xterm, сетка 2200 px на 220 колонок при шрифте 12 px, видна
|
||||
только левая часть строк, нижней панели tmux нет (кадр 50 строк = только pane).
|
||||
|
||||
## После
|
||||
|
||||
| Шаг | Снимок | Итог |
|
||||
|---|---|---|
|
||||
| 1. Вход в «Сессии» без `id` | `1-first.png` | выбрана первая (#2, ждёт ответа — выше), терминал сразу «в эфире» |
|
||||
| 2. Клик по другой живой сессии | `2-switch.png` | `/sessions?id=1`, справа её терминал, сессии не создаются и не останавливаются |
|
||||
| 3–4. Обратно, перезагрузка страницы | — | та же сессия, кадр заново, всё на месте |
|
||||
| 5. Окно 1100×800 | `5-narrow.png` | все 220 колонок в ширину, панель tmux видна |
|
||||
| 6. Окно 1920×1080 | `6-wide.png` | то же, шрифт крупнее |
|
||||
| 7–8. Кнопки + / − | `7-plus.png` | ручной размер без масштаба, горизонтальная прокрутка, текст не теряется |
|
||||
| 9. «По ширине» | — | снова все колонки в окне |
|
||||
| 10–11. Полный экран и выход (Esc) | `10-full.png` | как в нативном терминале; панель tmux внизу |
|
||||
| 12. Страница стори PAY-1 | `12-story.png` | терминала нет (`.xterm` = 0), кнопка «Открыть в «Сессиях»» |
|
||||
| 13. Переход со стори | — | `/sessions?id=2`, выбрана именно сессия стори |
|
||||
| 14. Завершённая `?id=7` | — | «Сессия #7 уже завершена — открыта другая.» |
|
||||
| 15. «Работа агентов» | — | терминала нет, ссылка на `/sessions?id=2` |
|
||||
| Пустое состояние | `14-empty.png` | «Живых сессий нет.» + как запустить |
|
||||
|
||||
На каждом шаге с терминалом: `iframe` = 0, `letter-spacing: normal`, 51 строка (50 pane + 1
|
||||
статус tmux), последняя строка видна в области терминала, русская и английская длинные строки
|
||||
видны целиком (до «КОНЕЦ» / «END»), ошибок страницы нет. Ввод: «Ввод» + печать `privet-123`
|
||||
дошли в pane (`tmux capture-pane`).
|
||||
|
||||
## Панель tmux
|
||||
|
||||
Нижней панели не было, потому что `capture-pane` отдаёт только содержимое pane, а панель tmux
|
||||
рисует клиенту при `attach`; у сессий она включена (`status on`). Теперь строку берём у самого
|
||||
tmux: `#{T:status-format[0]}` (тот же текст, что увидит `tmux attach`: `[peppa-pay` — tmux сам
|
||||
режет `status-left` до `status-left-length` 10, окно `0:bash*`, справа заголовок pane и время),
|
||||
стили `#[…]` переведены в цвета. Тест `terminal.test.ts` сверяет строку с конфигурацией tmux и
|
||||
`status off`.
|
||||
|
||||
Ограничение окружения: значки `⏵⏵` в строке Claude Code на Linux-стенде без шрифта с этими
|
||||
символами показаны квадратами; на Mac шрифт есть.
|
||||
@ -0,0 +1,63 @@
|
||||
import { chromium } from "/tmp/tools/node_modules/playwright-core/index.mjs";
|
||||
const [login] = process.argv.slice(2);
|
||||
const B = "http://localhost:18300";
|
||||
const b = await chromium.launch({ executablePath: process.env.CHROME });
|
||||
const ctx = await b.newContext({ viewport: { width: 1440, height: 900 }, deviceScaleFactor: 2 });
|
||||
const p = await ctx.newPage();
|
||||
const errors = [];
|
||||
p.on("pageerror", (e) => errors.push(e.message));
|
||||
await p.goto(login, { waitUntil: "networkidle" }).catch(() => {});
|
||||
await p.waitForTimeout(1500);
|
||||
const O = "/tmp/shots/check";
|
||||
const state = (label) => p.evaluate((label) => {
|
||||
const sc = document.querySelector("[data-terminal-scroller]");
|
||||
const rows = [...document.querySelectorAll(".xterm-rows > div")];
|
||||
const last = rows.at(-1);
|
||||
const scR = sc?.getBoundingClientRect();
|
||||
const lastR = last?.getBoundingClientRect();
|
||||
return {
|
||||
label, url: location.pathname + location.search,
|
||||
pane: document.querySelector("[data-session-pane]")?.getAttribute("data-session-pane"),
|
||||
current: document.querySelector("[aria-current=true][data-session-row]")?.getAttribute("data-session-row"),
|
||||
status: document.querySelector("[data-terminal-status]")?.getAttribute("data-terminal-status"),
|
||||
font: document.querySelector("[data-terminal-font]")?.getAttribute("data-terminal-font"),
|
||||
iframes: document.querySelectorAll("iframe").length,
|
||||
letter: rows[0] && getComputedStyle(rows[0].parentElement).letterSpacing,
|
||||
rows: rows.length,
|
||||
statusBar: last?.textContent.trim().slice(0, 60),
|
||||
statusBarVisible: !!(scR && lastR && lastR.bottom <= scR.bottom + 1 && lastR.top >= scR.top - 1),
|
||||
gridFits: !!(sc && sc.scrollWidth <= sc.clientWidth + 1),
|
||||
russianLine: rows.some((r) => r.textContent.includes("Это длинная строка ответа агента") && r.textContent.includes("КОНЕЦ")),
|
||||
englishLine: rows.some((r) => r.textContent.includes("This is a long English line") && r.textContent.includes("END")),
|
||||
};
|
||||
}, label);
|
||||
const log = async (label, shot) => { await p.waitForTimeout(1200); const s = await state(label); console.log(JSON.stringify(s)); if (shot) await p.screenshot({ path: `${O}-${shot}.png` }); return s; };
|
||||
|
||||
await p.goto(B + "/sessions", { waitUntil: "networkidle" }); await p.waitForTimeout(3000);
|
||||
await log("1 вход: первая сессия выбрана сама", "1-first");
|
||||
await p.click("[data-session-row='1']"); await p.waitForURL(/id=1/);
|
||||
await log("2 переключение на другую живую сессию", "2-switch");
|
||||
await p.click("[data-session-row='2']"); await p.waitForURL(/id=2/);
|
||||
await log("3 обратно на первую", null);
|
||||
await p.reload({ waitUntil: "networkidle" }); await p.waitForTimeout(2500);
|
||||
await log("4 повторное открытие (перезагрузка)", "4-reload");
|
||||
await p.setViewportSize({ width: 1100, height: 800 }); await log("5 окно 1100×800", "5-narrow");
|
||||
await p.setViewportSize({ width: 1920, height: 1080 }); await log("6 окно 1920×1080", "6-wide");
|
||||
await p.setViewportSize({ width: 1440, height: 900 });
|
||||
await p.click("[data-terminal-zoom='+']"); await log("7 кнопка + (ручной размер, прокрутка)", "7-plus");
|
||||
await p.click("[data-terminal-zoom='-']"); await p.click("[data-terminal-zoom='-']"); await log("8 кнопка −", null);
|
||||
await p.click("[data-terminal-fit]"); await log("9 снова «По ширине»", null);
|
||||
await p.click("button[aria-label='Во весь экран']"); await log("10 полный экран", "10-full");
|
||||
await p.keyboard.press("Escape"); await log("11 выход из полного экрана", null);
|
||||
await p.goto(B + "/t/PAY-1", { waitUntil: "networkidle" }); await p.waitForTimeout(1500);
|
||||
const story = await p.evaluate(() => ({ xterm: document.querySelectorAll(".xterm").length, link: document.querySelector("[data-open-session]")?.getAttribute("href") }));
|
||||
console.log(JSON.stringify({ label: "12 страница стори", ...story }));
|
||||
await p.screenshot({ path: `${O}-12-story.png` });
|
||||
await p.click("[data-open-session]"); await p.waitForURL(/sessions\?id=/); await p.waitForTimeout(2500);
|
||||
await log("13 переход со стори", "13-from-story");
|
||||
await p.goto(B + "/sessions?id=7", { waitUntil: "networkidle" }); await p.waitForTimeout(1500);
|
||||
console.log(JSON.stringify({ label: "14 завершённая #7", gone: await p.evaluate(() => document.querySelector("[data-session-gone]")?.textContent) }));
|
||||
await p.goto(B + "/runners?id=2", { waitUntil: "networkidle" }); await p.waitForTimeout(1500);
|
||||
console.log(JSON.stringify({ label: "15 работа агентов", xterm: await p.evaluate(() => document.querySelectorAll(".xterm").length), link: await p.evaluate(() => document.querySelector("[data-open-session]")?.getAttribute("href")) }));
|
||||
console.log("page errors:", errors);
|
||||
await b.close();
|
||||
@ -0,0 +1,37 @@
|
||||
## Why
|
||||
|
||||
Терминал агента встроен прямо в страницу стори и в панель «Работы агентов», и там он
|
||||
отображается плохо: символы расставлены слишком широко, длинные строки уходят за правую
|
||||
границу, нижней панели tmux нет. Владелец хочет один раздел, где открыты все живые сессии
|
||||
агентов, и переход туда со стори вместо встроенного окна (PEP-257).
|
||||
|
||||
## What Changes
|
||||
|
||||
- Новый раздел «Сессии» (`/sessions`, пункт левого меню в виде «Инженер»): слева список
|
||||
живых сессий пользователя (стори, CLI, состояние, агент), справа сразу открытый терминал
|
||||
выбранной. Без `id` выбирается первая, `?id=N` — конкретная; пустое состояние, если живых
|
||||
сессий нет. Переключение не создаёт и не останавливает сессии.
|
||||
- Страница стори и панель раннера в «Работе агентов» больше не встраивают терминал: вместо
|
||||
него кнопка «Открыть в «Сессиях»» → `/sessions?id=<сессия>`.
|
||||
- Исправлено отображение терминала: шрифт для xterm берётся вычисленным (CSS-переменная
|
||||
`--font-geist-mono` не понималась при замере ячейки → лишний `letter-spacing`), замер
|
||||
повторяется после загрузки шрифтов; по умолчанию размер шрифта подгоняется под ширину
|
||||
pane («по ширине»), +/- переключают на ручной размер с горизонтальной прокруткой.
|
||||
- Нижняя панель tmux: поток терминала добавляет к экрану pane строки статуса, которые tmux
|
||||
сам вычисляет из своей конфигурации (`status-format`, `status-style`, позиция и число строк),
|
||||
переведённые из стилей tmux в цвета терминала. `status off` — панели нет.
|
||||
|
||||
## Capabilities
|
||||
|
||||
### New Capabilities
|
||||
|
||||
### Modified Capabilities
|
||||
- `runner-terminal`: раздел «Сессии», переход со стори, строка статуса tmux, размер шрифта по ширине.
|
||||
|
||||
## Impact
|
||||
|
||||
- `packages/runner/src/tmux.ts` (`paneInfo` + строки статуса), новый `packages/runner/src/tmux-status.ts`,
|
||||
`packages/runner/src/terminal.ts` (виртуальный экран pane + статус).
|
||||
- Веб: `app/(app)/sessions/page.tsx`, `components/Sidebar.tsx`, `components/RunnerTerminal.tsx`,
|
||||
`components/RunnerConsole.tsx`, `components/cards.tsx`, `t/[key]/page.tsx`, переводы en/kk.
|
||||
- Тесты: `terminal.test.ts` (строка статуса в кадре), `tmux-status.test.ts`.
|
||||
@ -0,0 +1,75 @@
|
||||
## MODIFIED Requirements
|
||||
|
||||
### Requirement: Живой терминал раннера
|
||||
Веб SHALL показывать терминал раннера (pane его tmux-сессии) в реальном времени в разделе
|
||||
«Сессии» (`/sessions`): xterm.js в странице, без iframe. Первый кадр содержит историю pane и
|
||||
текущий экран вместе со строками статуса tmux; дальше приходят изменения; при обрыве клиент
|
||||
переподключается и получает полный кадр. Размер pane браузер не меняет. Ячейка терминала
|
||||
замеряется по настоящему шрифту страницы (без лишних межсимвольных интервалов); по умолчанию
|
||||
сетка масштабируется так, чтобы все колонки pane помещались по ширине, кнопки +/-
|
||||
переключают на ручной размер шрифта с горизонтальной прокруткой.
|
||||
|
||||
#### Scenario: Открыть терминал
|
||||
- **GIVEN** раннер PAY-3 #12 работает, PM — владелец проекта PAY
|
||||
- **WHEN** PM открывает `/sessions?id=12`
|
||||
- **THEN** справа виден экран агента и история pane, новые строки появляются без перезагрузки
|
||||
|
||||
#### Scenario: Несколько зрителей
|
||||
- **GIVEN** раннер #12 открыт у владельца и участника проекта
|
||||
- **WHEN** агент печатает строку
|
||||
- **THEN** строку видят оба, а tmux опрашивается одним циклом на раннер
|
||||
|
||||
#### Scenario: Чужой раннер
|
||||
- **GIVEN** пользователь не владелец и не участник проекта PAY
|
||||
- **WHEN** он запрашивает поток терминала раннера #12
|
||||
- **THEN** ответ 404, вывод не отдаётся
|
||||
|
||||
#### Scenario: Длинные строки по ширине
|
||||
- **GIVEN** pane раннера шириной 220 колонок, в нём строка длиной 200 символов
|
||||
- **WHEN** PM открывает терминал в области шириной 1100 px
|
||||
- **THEN** строка видна целиком, `letter-spacing` строк терминала равен 0
|
||||
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Раздел «Сессии»
|
||||
Веб SHALL иметь раздел «Сессии» (пункт левого меню в виде «Инженер»): слева — живые сессии
|
||||
агентов проектов пользователя (стори или имя, CLI, состояние, агент), справа — открытый
|
||||
терминал выбранной. Без параметра выбирается первая сессия списка, с `?id=N` — сессия N.
|
||||
Выбор другой сессии открывает её существующий терминал, не создаёт и не останавливает
|
||||
сессии. Страница стори и панель раннера не встраивают терминал, а ведут в «Сессии» на свою
|
||||
сессию.
|
||||
|
||||
#### Scenario: Первая сессия открыта сразу
|
||||
- **GIVEN** у PM живые сессии #2 (ждёт ответа) и #5 (работает)
|
||||
- **WHEN** PM открывает «Сессии»
|
||||
- **THEN** выбрана #2 и справа уже идёт её терминал
|
||||
|
||||
#### Scenario: Переход со стори
|
||||
- **GIVEN** у стори PAY-1 живая сессия #2
|
||||
- **WHEN** PM на странице PAY-1 жмёт «Открыть в «Сессиях»»
|
||||
- **THEN** открывается `/sessions?id=2` с выбранной сессией #2, на странице стори терминала нет
|
||||
|
||||
#### Scenario: Живых сессий нет
|
||||
- **GIVEN** у пользователя нет живых сессий
|
||||
- **WHEN** он открывает «Сессии»
|
||||
- **THEN** видно «Живых сессий нет» и подсказка, как их запустить
|
||||
|
||||
#### Scenario: Сессия уже завершена
|
||||
- **GIVEN** сессия #7 завершена
|
||||
- **WHEN** PM открывает `/sessions?id=7`
|
||||
- **THEN** выбрана первая живая сессия и видна строка «Сессия #7 уже завершена»
|
||||
|
||||
### Requirement: Строка статуса tmux в терминале
|
||||
Поток терминала SHALL добавлять к экрану pane строки статуса tmux, которые tmux вычисляет из
|
||||
своей конфигурации (`status-format`, `status-style`, `status-position`, число строк `status`),
|
||||
с цветами и раскладкой по ширине окна. При `status off` строк статуса нет.
|
||||
|
||||
#### Scenario: Панель внизу
|
||||
- **GIVEN** сессия `peppa-pay-1-s2` с `status on` и `status-position bottom`
|
||||
- **WHEN** приходит первый кадр
|
||||
- **THEN** число строк кадра на 1 больше высоты pane, последняя строка содержит `[peppa-pay-1-s2]` и номер окна
|
||||
|
||||
#### Scenario: Панель выключена
|
||||
- **GIVEN** у сессии `status off`
|
||||
- **WHEN** приходит кадр
|
||||
- **THEN** число строк кадра равно высоте pane
|
||||
@ -0,0 +1,21 @@
|
||||
## 1. Строка статуса tmux
|
||||
|
||||
- [x] 1.1 `tmux-status.ts`: разбор стилей tmux и раскладка строки статуса в SGR, юнит-тест
|
||||
- [x] 1.2 `paneInfo` получает статус тем же вызовом tmux; `TerminalFeed` добавляет строки статуса к экрану
|
||||
- [x] 1.3 Тест `terminal.test.ts`: панель в кадре, `status off` — без неё
|
||||
|
||||
## 2. Отображение терминала
|
||||
|
||||
- [x] 2.1 `RunnerTerminal`: вычисленный шрифт, замер после загрузки шрифтов
|
||||
- [x] 2.2 Режим «по ширине» по умолчанию, +/- — ручной размер с прокруткой, `fill` для страницы сессий
|
||||
|
||||
## 3. Раздел «Сессии»
|
||||
|
||||
- [x] 3.1 Страница `/sessions` (список живых сессий + терминал выбранной, пустое состояние, завершённая `id`)
|
||||
- [x] 3.2 Пункт меню, переводы en/kk, словарь
|
||||
- [x] 3.3 Стори и «Работа агентов»: вместо терминала кнопка «Открыть в «Сессиях»»
|
||||
|
||||
## 4. Проверка
|
||||
|
||||
- [x] 4.1 Визуальная проверка в браузере до/после: загрузка, повторное открытие, размер окна, +/-, полный экран, переключение двух сессий, переход со стори, без iframe; скриншоты
|
||||
- [ ] 4.2 Тесты, lint, typecheck; память, archive, PR
|
||||
@ -6,15 +6,18 @@
|
||||
## Requirements
|
||||
|
||||
### Requirement: Живой терминал раннера
|
||||
Веб SHALL показывать терминал раннера (pane его tmux-сессии) в реальном времени в панели
|
||||
раннера и на странице стори у активной сессии: xterm.js в странице, без iframe. Первый кадр
|
||||
содержит историю pane и текущий экран; дальше приходят изменения; при обрыве клиент
|
||||
переподключается и получает полный кадр. Размер pane браузер не меняет.
|
||||
Веб SHALL показывать терминал раннера (pane его tmux-сессии) в реальном времени в разделе
|
||||
«Сессии» (`/sessions`): xterm.js в странице, без iframe. Первый кадр содержит историю pane и
|
||||
текущий экран вместе со строками статуса tmux; дальше приходят изменения; при обрыве клиент
|
||||
переподключается и получает полный кадр. Размер pane браузер не меняет. Ячейка терминала
|
||||
замеряется по настоящему шрифту страницы (без лишних межсимвольных интервалов); по умолчанию
|
||||
сетка масштабируется так, чтобы все колонки pane помещались по ширине, кнопки +/-
|
||||
переключают на ручной размер шрифта с горизонтальной прокруткой.
|
||||
|
||||
#### Scenario: Открыть терминал
|
||||
- **GIVEN** раннер PAY-3 #12 работает, PM — владелец проекта PAY
|
||||
- **WHEN** PM открывает раннер #12 в «Раннерах»
|
||||
- **THEN** в панели виден экран агента и история pane, новые строки появляются без перезагрузки
|
||||
- **WHEN** PM открывает `/sessions?id=12`
|
||||
- **THEN** справа виден экран агента и история pane, новые строки появляются без перезагрузки
|
||||
|
||||
#### Scenario: Несколько зрителей
|
||||
- **GIVEN** раннер #12 открыт у владельца и участника проекта
|
||||
@ -26,6 +29,11 @@
|
||||
- **WHEN** он запрашивает поток терминала раннера #12
|
||||
- **THEN** ответ 404, вывод не отдаётся
|
||||
|
||||
#### Scenario: Длинные строки по ширине
|
||||
- **GIVEN** pane раннера шириной 220 колонок, в нём строка длиной 200 символов
|
||||
- **WHEN** PM открывает терминал в области шириной 1100 px
|
||||
- **THEN** строка видна целиком, `letter-spacing` строк терминала равен 0
|
||||
|
||||
### Requirement: Ввод в терминал раннера
|
||||
Владелец и участники проекта SHALL уметь включить режим ввода и печатать в терминал раннера:
|
||||
нажатия уходят в pane как есть, вставка — одной bracketed-вставкой. Ввод принимается только в
|
||||
@ -65,3 +73,46 @@
|
||||
- **GIVEN** сессия завершена
|
||||
- **WHEN** приходит `{t:"in", …, id:2}`
|
||||
- **THEN** приходит `{t:"ack", id:2, error:"…"}`, в pane ничего не уходит
|
||||
|
||||
### Requirement: Раздел «Сессии»
|
||||
Веб SHALL иметь раздел «Сессии» (пункт левого меню в виде «Инженер»): слева — живые сессии
|
||||
агентов проектов пользователя (стори или имя, CLI, состояние, агент), справа — открытый
|
||||
терминал выбранной. Без параметра выбирается первая сессия списка, с `?id=N` — сессия N.
|
||||
Выбор другой сессии открывает её существующий терминал, не создаёт и не останавливает
|
||||
сессии. Страница стори и панель раннера не встраивают терминал, а ведут в «Сессии» на свою
|
||||
сессию.
|
||||
|
||||
#### Scenario: Первая сессия открыта сразу
|
||||
- **GIVEN** у PM живые сессии #2 (ждёт ответа) и #5 (работает)
|
||||
- **WHEN** PM открывает «Сессии»
|
||||
- **THEN** выбрана #2 и справа уже идёт её терминал
|
||||
|
||||
#### Scenario: Переход со стори
|
||||
- **GIVEN** у стори PAY-1 живая сессия #2
|
||||
- **WHEN** PM на странице PAY-1 жмёт «Открыть в «Сессиях»»
|
||||
- **THEN** открывается `/sessions?id=2` с выбранной сессией #2, на странице стори терминала нет
|
||||
|
||||
#### Scenario: Живых сессий нет
|
||||
- **GIVEN** у пользователя нет живых сессий
|
||||
- **WHEN** он открывает «Сессии»
|
||||
- **THEN** видно «Живых сессий нет» и подсказка, как их запустить
|
||||
|
||||
#### Scenario: Сессия уже завершена
|
||||
- **GIVEN** сессия #7 завершена
|
||||
- **WHEN** PM открывает `/sessions?id=7`
|
||||
- **THEN** выбрана первая живая сессия и видна строка «Сессия #7 уже завершена»
|
||||
|
||||
### Requirement: Строка статуса tmux в терминале
|
||||
Поток терминала SHALL добавлять к экрану pane строки статуса tmux, которые tmux вычисляет из
|
||||
своей конфигурации (`status-format`, `status-style`, `status-position`, число строк `status`),
|
||||
с цветами и раскладкой по ширине окна. При `status off` строк статуса нет.
|
||||
|
||||
#### Scenario: Панель внизу
|
||||
- **GIVEN** сессия `peppa-pay-1-s2` с `status on` и `status-position bottom`
|
||||
- **WHEN** приходит первый кадр
|
||||
- **THEN** число строк кадра на 1 больше высоты pane, последняя строка содержит `[peppa-pay-1-s2]` и номер окна
|
||||
|
||||
#### Scenario: Панель выключена
|
||||
- **GIVEN** у сессии `status off`
|
||||
- **WHEN** приходит кадр
|
||||
- **THEN** число строк кадра равно высоте pane
|
||||
|
||||
@ -8,6 +8,10 @@ import type { Db } from "@peppa/db";
|
||||
import * as tmux from "./tmux.ts";
|
||||
|
||||
export const TERMINAL_POLL_MS = 250;
|
||||
/** PEP-257: how often the tmux status line is re-read (its clock changes once a minute). */
|
||||
const STATUS_EVERY_MS = 1000;
|
||||
const STATUS_RETRY_MS = 30_000;
|
||||
const STATUS_FIRST_WAIT_MS = 500;
|
||||
/** Lines of pane scrollback sent in the first frame. */
|
||||
export const TERMINAL_HISTORY_LINES = 1000;
|
||||
export const TERMINAL_MAX_KEYS_BYTES = 1024;
|
||||
@ -141,14 +145,50 @@ export class TerminalFeed {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* PEP-257: the tmux status lines, refreshed in the background once per STATUS_EVERY_MS — the
|
||||
* pane's picture never waits for them (the first poll gives them a short head start). A failed
|
||||
* or slow query leaves the picture without them and is retried after STATUS_RETRY_MS.
|
||||
*/
|
||||
private bar: tmux.StatusLines = { top: false, lines: [] };
|
||||
private barAt = -Infinity;
|
||||
private barCols = 0;
|
||||
private barJob: Promise<void> | null = null;
|
||||
private barWarned = false;
|
||||
|
||||
private statusBar(cols: number): Promise<tmux.StatusLines> | tmux.StatusLines {
|
||||
const now = Date.now();
|
||||
if (!this.barJob && (now - this.barAt >= STATUS_EVERY_MS || cols !== this.barCols)) {
|
||||
this.barAt = now;
|
||||
this.barCols = cols;
|
||||
this.barJob = tmux.statusLines(this.pane, cols).then(
|
||||
(b) => void (this.bar = b),
|
||||
(e: unknown) => {
|
||||
// Once per feed: the reason is in the service log, the picture just goes on without the bar.
|
||||
if (!this.barWarned) console.warn(`terminal ${this.name}: tmux status line unavailable: ${(e as Error).message}`);
|
||||
this.barWarned = true;
|
||||
this.bar = { top: false, lines: [] };
|
||||
this.barAt = now + STATUS_RETRY_MS - STATUS_EVERY_MS;
|
||||
},
|
||||
).finally(() => (this.barJob = null));
|
||||
if (this.polls === 1) return Promise.race([this.barJob, new Promise((r) => setTimeout(r, STATUS_FIRST_WAIT_MS))]).then(() => this.bar);
|
||||
}
|
||||
return this.bar;
|
||||
}
|
||||
|
||||
private async tick() {
|
||||
if (!this.listeners.size) return;
|
||||
this.polls++;
|
||||
let info: tmux.PaneInfo;
|
||||
let screen: string[];
|
||||
try {
|
||||
info = await tmux.paneInfo(this.pane);
|
||||
screen = fit(this.lines(await tmux.capturePaneAnsi(this.pane, 0, info.rows - 1)), info.rows);
|
||||
const pane = await tmux.paneInfo(this.pane);
|
||||
const body = fit(this.lines(await tmux.capturePaneAnsi(this.pane, 0, pane.rows - 1)), pane.rows);
|
||||
// PEP-257: the status lines are part of the picture, like in a terminal attached to tmux.
|
||||
const bar = await this.statusBar(pane.cols);
|
||||
const status = bar.lines.map((l) => this.mask(l));
|
||||
screen = bar.top ? [...status, ...body] : [...body, ...status];
|
||||
info = { ...pane, rows: pane.rows + status.length, cursorY: pane.cursorY + (bar.top ? status.length : 0) };
|
||||
} catch (e) {
|
||||
if (await tmux.hasSession(this.pane)) throw e;
|
||||
const all = [...this.listeners];
|
||||
|
||||
199
packages/runner/src/tmux-status.ts
Normal file
@ -0,0 +1,199 @@
|
||||
// tmux status line for the web terminal (PEP-257): capture-pane has only the pane, the status
|
||||
// line is drawn by tmux for an attached client. tmux expands its own `status-format` for us
|
||||
// (`#{T:status-format[i]}`); what is left are `#[…]` style directives, turned here into SGR and
|
||||
// laid out on the window width the way tmux does: left, centre and right parts.
|
||||
|
||||
interface Style {
|
||||
fg: string | null;
|
||||
bg: string | null;
|
||||
attrs: Set<string>;
|
||||
}
|
||||
|
||||
const COLOURS = ["black", "red", "green", "yellow", "blue", "magenta", "cyan", "white"];
|
||||
const ATTRS: Record<string, string> = {
|
||||
bright: "1",
|
||||
bold: "1",
|
||||
dim: "2",
|
||||
italics: "3",
|
||||
underscore: "4",
|
||||
"double-underscore": "4",
|
||||
"curly-underscore": "4",
|
||||
"dotted-underscore": "4",
|
||||
"dashed-underscore": "4",
|
||||
blink: "5",
|
||||
reverse: "7",
|
||||
hidden: "8",
|
||||
strikethrough: "9",
|
||||
overline: "53",
|
||||
};
|
||||
|
||||
const clone = (s: Style): Style => ({ fg: s.fg, bg: s.bg, attrs: new Set(s.attrs) });
|
||||
const EMPTY: Style = { fg: null, bg: null, attrs: new Set() };
|
||||
|
||||
/** SGR parameters of a tmux colour for fg (`base` 30) or bg (40); null — the terminal default. */
|
||||
export function colourSgr(c: string, bg: boolean): string | null {
|
||||
const v = c.toLowerCase();
|
||||
const base = bg ? 40 : 30;
|
||||
if (v === "default" || v === "terminal" || v === "") return null;
|
||||
const i = COLOURS.indexOf(v);
|
||||
if (i >= 0) return String(base + i);
|
||||
if (v.startsWith("bright")) {
|
||||
const j = COLOURS.indexOf(v.slice(6));
|
||||
if (j >= 0) return String(base + 60 + j);
|
||||
}
|
||||
const n = /^colou?r(\d{1,3})$/.exec(v);
|
||||
if (n && Number(n[1]) < 256) return `${base + 8};5;${Number(n[1])}`;
|
||||
const hex = /^#([0-9a-f]{6})$/.exec(v);
|
||||
if (hex) {
|
||||
const x = parseInt(hex[1]!, 16);
|
||||
return `${base + 8};2;${(x >> 16) & 255};${(x >> 8) & 255};${x & 255}`;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Applies one tmux style list (`fg=red,bold` / `bg=green fg=black`) to `s`; returns layout tokens. */
|
||||
function applyStyle(spec: string, s: Style, defaults: Style[]): Array<[string, string]> {
|
||||
const layout: Array<[string, string]> = [];
|
||||
for (const raw of spec.split(/[\s,]+/)) {
|
||||
const tok = raw.trim();
|
||||
if (!tok) continue;
|
||||
const eq = tok.indexOf("=");
|
||||
const key = (eq < 0 ? tok : tok.slice(0, eq)).toLowerCase();
|
||||
const val = eq < 0 ? "" : tok.slice(eq + 1);
|
||||
// In a status line `fg=default` is the status style's colour, not the terminal's.
|
||||
if (key === "fg") s.fg = val === "default" ? (defaults.at(-1) ?? EMPTY).fg : val;
|
||||
else if (key === "bg") s.bg = val === "default" ? (defaults.at(-1) ?? EMPTY).bg : val;
|
||||
else if (key === "default") {
|
||||
const d = defaults.at(-1) ?? EMPTY;
|
||||
s.fg = d.fg;
|
||||
s.bg = d.bg;
|
||||
s.attrs = new Set(d.attrs);
|
||||
} else if (key === "none" || key === "noattr") s.attrs.clear();
|
||||
else if (key === "push-default") defaults.push(clone(s));
|
||||
else if (key === "pop-default") {
|
||||
if (defaults.length > 1) defaults.pop();
|
||||
} else if (key in ATTRS) s.attrs.add(key);
|
||||
else if (key.startsWith("no") && key.slice(2) in ATTRS) s.attrs.delete(key.slice(2));
|
||||
else if (key === "align" || key === "list" || key === "nolist") layout.push([key, val]);
|
||||
// range=, norange, fill=, us=, ignore, acs… do not change what is drawn.
|
||||
}
|
||||
return layout;
|
||||
}
|
||||
|
||||
/** Parses a style list (status-style) into a style. */
|
||||
export function parseStyle(spec: string): Style {
|
||||
const s = clone(EMPTY);
|
||||
applyStyle(spec, s, [clone(EMPTY)]);
|
||||
return s;
|
||||
}
|
||||
|
||||
const sgr = (s: Style) => {
|
||||
const p = ["0"];
|
||||
for (const a of s.attrs) p.push(ATTRS[a]!);
|
||||
const fg = s.fg && colourSgr(s.fg, false);
|
||||
const bg = s.bg && colourSgr(s.bg, true);
|
||||
if (fg) p.push(fg);
|
||||
if (bg) p.push(bg);
|
||||
return `\x1b[${p.join(";")}m`;
|
||||
};
|
||||
|
||||
/** Terminal cells a code point takes: wide CJK and emoji 2, combining marks 0. */
|
||||
export function charWidth(cp: number): number {
|
||||
if (cp === 0x200d || (cp >= 0x300 && cp <= 0x36f) || (cp >= 0xfe00 && cp <= 0xfe0f) || (cp >= 0x20d0 && cp <= 0x20ff)) return 0;
|
||||
if (
|
||||
(cp >= 0x1100 && cp <= 0x115f) ||
|
||||
(cp >= 0x2e80 && cp <= 0xa4cf && cp !== 0x303f) ||
|
||||
(cp >= 0xac00 && cp <= 0xd7a3) ||
|
||||
(cp >= 0xf900 && cp <= 0xfaff) ||
|
||||
(cp >= 0xfe30 && cp <= 0xfe4f) ||
|
||||
(cp >= 0xff00 && cp <= 0xff60) ||
|
||||
(cp >= 0xffe0 && cp <= 0xffe6) ||
|
||||
(cp >= 0x1f300 && cp <= 0x1f64f) ||
|
||||
(cp >= 0x1f900 && cp <= 0x1f9ff) ||
|
||||
(cp >= 0x20000 && cp <= 0x3fffd)
|
||||
)
|
||||
return 2;
|
||||
return 1;
|
||||
}
|
||||
|
||||
interface Cell {
|
||||
ch: string;
|
||||
w: number;
|
||||
style: Style;
|
||||
}
|
||||
|
||||
type Align = "left" | "centre" | "right";
|
||||
|
||||
/**
|
||||
* One status line of `width` cells as SGR text: `format` is tmux's own expansion of
|
||||
* `status-format[i]`, `base` — `status-style` (what `default` means).
|
||||
*/
|
||||
export function renderStatusLine(format: string, width: number, base: string): string {
|
||||
const baseStyle = parseStyle(base);
|
||||
const defaults = [clone(baseStyle)];
|
||||
const style = clone(baseStyle);
|
||||
const parts: Record<Align, Cell[]> = { left: [], centre: [], right: [] };
|
||||
let align: Align = "left";
|
||||
let hidden = false; // list markers: drawn by tmux only when the window list is cut
|
||||
let i = 0;
|
||||
while (i < format.length) {
|
||||
if (format.startsWith("#[", i)) {
|
||||
const end = format.indexOf("]", i + 2);
|
||||
if (end < 0) break;
|
||||
for (const [k, v] of applyStyle(format.slice(i + 2, end), style, defaults)) {
|
||||
if (k === "align") align = v === "right" ? "right" : v === "centre" || v === "absolute-centre" ? "centre" : "left";
|
||||
else if (k === "list") hidden = v === "left-marker" || v === "right-marker";
|
||||
else if (k === "nolist") hidden = false;
|
||||
}
|
||||
i = end + 1;
|
||||
continue;
|
||||
}
|
||||
if (format.startsWith("##", i)) i++;
|
||||
const cp = format.codePointAt(i)!;
|
||||
const ch = String.fromCodePoint(cp);
|
||||
i += ch.length;
|
||||
if (hidden || cp < 0x20) continue;
|
||||
parts[align].push({ ch, w: charWidth(cp), style: clone(style) });
|
||||
}
|
||||
const span = (cells: Cell[]) => cells.reduce((n, c) => n + c.w, 0);
|
||||
const fit = (cells: Cell[], room: number, fromEnd = false) => {
|
||||
const out: Cell[] = [];
|
||||
let used = 0;
|
||||
const list = fromEnd ? [...cells].reverse() : cells;
|
||||
for (const c of list) {
|
||||
if (used + c.w > room) break;
|
||||
used += c.w;
|
||||
out.push(c);
|
||||
}
|
||||
return fromEnd ? out.reverse() : out;
|
||||
};
|
||||
const row: Array<Cell | null> = Array(width).fill(null);
|
||||
const place = (cells: Cell[], at: number) => {
|
||||
let x = at;
|
||||
for (const c of cells) {
|
||||
if (x + c.w > width) break;
|
||||
row[x] = c;
|
||||
for (let k = 1; k < c.w; k++) row[x + k] = { ch: "", w: 0, style: c.style };
|
||||
x += c.w;
|
||||
}
|
||||
};
|
||||
const left = fit(parts.left, width);
|
||||
const lw = span(left);
|
||||
const right = fit(parts.right, width - lw, true);
|
||||
const rw = span(right);
|
||||
const centre = fit(parts.centre, width - lw - rw);
|
||||
const cw = span(centre);
|
||||
place(left, 0);
|
||||
place(right, width - rw);
|
||||
place(centre, Math.max(lw, Math.min(width - rw - cw, Math.floor((width - cw) / 2))));
|
||||
let out = "";
|
||||
let last = "";
|
||||
for (const c of row) {
|
||||
const code = sgr(c?.style ?? baseStyle);
|
||||
if (code !== last) out += code;
|
||||
last = code;
|
||||
if (c === null) out += " ";
|
||||
else out += c.ch;
|
||||
}
|
||||
return out + "\x1b[0m";
|
||||
}
|
||||
@ -1,6 +1,7 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { HostUnreachable, runOn, type HostTarget } from "./exec.ts";
|
||||
import { isRunnerClient, runnerCall, runnerClientDb } from "./runner-client.ts";
|
||||
import { renderStatusLine } from "./tmux-status.ts";
|
||||
|
||||
const TMUX = () => process.env.PEPPA_TMUX_BIN ?? "tmux";
|
||||
// Separate tmux server (tmux -L) — tests use their own so they never touch real sessions.
|
||||
@ -197,6 +198,38 @@ export async function paneInfo(p: Pane): Promise<PaneInfo> {
|
||||
return { cols: cols!, rows: rows!, cursorX: x!, cursorY: y!, cursorVisible: flag === 1, historySize: hist! };
|
||||
}
|
||||
|
||||
/** Status lines tmux can have (`status` on | 2..5). */
|
||||
const STATUS_MAX = 5;
|
||||
|
||||
/** PEP-257: tmux status lines of a session — rendered to SGR on `cols` cells, and where they go. */
|
||||
export interface StatusLines {
|
||||
top: boolean;
|
||||
lines: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* PEP-257: the status lines as an attached client sees them — tmux expands its own
|
||||
* `status-format[i]` (`#{T:…}`), the `#[…]` styles become SGR on `cols` cells; `status off` —
|
||||
* none. Separate, time-limited calls: the picture of the pane never waits for them.
|
||||
*/
|
||||
export async function statusLines(p: Pane, cols: number, timeoutMs = 2000): Promise<StatusLines> {
|
||||
const t = `=${paneName(p)}:`;
|
||||
const show = (f: string) => runTmux(p, ["display-message", "-p", "-t", t, f], timeoutMs).then((o) => o.replace(/\n$/, ""));
|
||||
const [status, position] = (await show("#{status} #{status-position}")).trim().split(" ");
|
||||
const n = status === "on" ? 1 : !status || status === "off" ? 0 : Math.min(Number(status) || 0, STATUS_MAX);
|
||||
if (!n) return { top: false, lines: [] };
|
||||
const style = await show("#{E:status-style}");
|
||||
const lines: string[] = [];
|
||||
for (let i = 0; i < n; i++) lines.push(renderStatusLine(await show(`#{T:status-format[${i}]}`), cols, style));
|
||||
return { top: position === "top", lines };
|
||||
}
|
||||
|
||||
async function runTmux(p: Pane, args: string[], timeoutMs: number): Promise<string> {
|
||||
const host = paneHost(p);
|
||||
const { stdout } = await runOn(host, [host ? "tmux" : TMUX(), ...SOCKET(), ...args], { timeoutMs });
|
||||
return stdout;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pane lines with colours (escape sequences), physical rows (no joining of wrapped lines).
|
||||
* `start`/`end` are tmux line numbers: 0 = top of the screen, negative = scrollback.
|
||||
|
||||
@ -18,6 +18,7 @@ import { feedback } from "./feedback.ts";
|
||||
import { intent } from "./intent.ts";
|
||||
import { attachments } from "./attachments.ts";
|
||||
import { capacity } from "./capacity.ts";
|
||||
import { sessions } from "./sessions.ts";
|
||||
import { untrusted } from "./untrusted.ts";
|
||||
import { mcpGuide } from "./mcp-guide.ts";
|
||||
import { subscriptionRequest } from "./subscription-request.ts";
|
||||
@ -34,4 +35,4 @@ import { errors } from "./errors.ts";
|
||||
import { features } from "./features.ts";
|
||||
import { launchSmoke } from "./launch-smoke.ts";
|
||||
|
||||
export const en: Dict = { ...errors, ...common, ...story, ...project, ...admin, ...settings, ...help, ...runner, ...bot, ...merge, ...merge_a, ...merge_b, ...merge_c, ...merge_d, ...feedback, ...attachments, ...capacity, ...untrusted, ...mcpGuide, ...subscriptionRequest, ...domainGuard, ...observe, ...intent, ...proposals, ...analyst, ...chatsUx, ...accountMerge, ...acceptScreen, ...accessHub, ...secretMoves, ...features, ...launchSmoke };
|
||||
export const en: Dict = { ...errors, ...common, ...story, ...project, ...admin, ...settings, ...help, ...runner, ...bot, ...merge, ...merge_a, ...merge_b, ...merge_c, ...merge_d, ...feedback, ...attachments, ...capacity, ...sessions, ...untrusted, ...mcpGuide, ...subscriptionRequest, ...domainGuard, ...observe, ...intent, ...proposals, ...analyst, ...chatsUx, ...accountMerge, ...acceptScreen, ...accessHub, ...secretMoves, ...features, ...launchSmoke };
|
||||
|
||||
11
packages/shared/src/i18n/en/sessions.ts
Normal file
@ -0,0 +1,11 @@
|
||||
// PEP-257: «Сессии» — the terminals of all live agent sessions in one place.
|
||||
export const sessions: Record<string, string> = {
|
||||
"Живые сессии агентов ваших проектов: выберите слева — справа сразу её терминал.": "Live agent sessions of your projects: pick one on the left — its terminal opens on the right.",
|
||||
"Сессия #{id} уже завершена — открыта другая.": "Session #{id} has already ended — another one is open.",
|
||||
"Живых сессий нет.": "No live sessions.",
|
||||
"Агент запускается, когда стори переносят в «В работе» на доске проекта, или кнопкой «Новый терминал» в «Работе агентов».": "An agent starts when a story is moved to «In progress» on the project board, or with «New terminal» in «Agents at work».",
|
||||
"Список сессий": "Sessions",
|
||||
"Открыть в «Сессиях»": "Open in «Sessions»",
|
||||
"Все колонки по ширине окна": "All columns across the window width",
|
||||
"По ширине": "Fit width",
|
||||
};
|
||||
@ -18,6 +18,7 @@ import { feedback } from "./feedback.ts";
|
||||
import { intent } from "./intent.ts";
|
||||
import { attachments } from "./attachments.ts";
|
||||
import { capacity } from "./capacity.ts";
|
||||
import { sessions } from "./sessions.ts";
|
||||
import { untrusted } from "./untrusted.ts";
|
||||
import { mcpGuide } from "./mcp-guide.ts";
|
||||
import { subscriptionRequest } from "./subscription-request.ts";
|
||||
@ -34,4 +35,4 @@ import { errors } from "./errors.ts";
|
||||
import { features } from "./features.ts";
|
||||
import { launchSmoke } from "./launch-smoke.ts";
|
||||
|
||||
export const kk: Dict = { ...errors, ...admin, ...bot, ...common, ...help, ...mergeA, ...mergeB, ...mergeC, ...mergeD, ...merge, ...project, ...runner, ...settings, ...story, ...feedback, ...attachments, ...capacity, ...untrusted, ...mcpGuide, ...subscriptionRequest, ...domainGuard, ...observe, ...intent, ...proposals, ...analyst, ...chatsUx, ...accountMerge, ...acceptScreen, ...accessHub, ...secretMoves, ...features, ...launchSmoke };
|
||||
export const kk: Dict = { ...errors, ...admin, ...bot, ...common, ...help, ...mergeA, ...mergeB, ...mergeC, ...mergeD, ...merge, ...project, ...runner, ...settings, ...story, ...feedback, ...attachments, ...capacity, ...sessions, ...untrusted, ...mcpGuide, ...subscriptionRequest, ...domainGuard, ...observe, ...intent, ...proposals, ...analyst, ...chatsUx, ...accountMerge, ...acceptScreen, ...accessHub, ...secretMoves, ...features, ...launchSmoke };
|
||||
|
||||
11
packages/shared/src/i18n/kk/sessions.ts
Normal file
@ -0,0 +1,11 @@
|
||||
// PEP-257: «Сессии» — the terminals of all live agent sessions in one place.
|
||||
export const sessions: Record<string, string> = {
|
||||
"Живые сессии агентов ваших проектов: выберите слева — справа сразу её терминал.": "Жобаларыңыздағы агенттердің белсенді сессиялары: сол жақтан таңдаңыз — оң жақта бірден оның терминалы ашылады.",
|
||||
"Сессия #{id} уже завершена — открыта другая.": "#{id} сессиясы аяқталған — басқасы ашылды.",
|
||||
"Живых сессий нет.": "Белсенді сессиялар жоқ.",
|
||||
"Агент запускается, когда стори переносят в «В работе» на доске проекта, или кнопкой «Новый терминал» в «Работе агентов».": "Агент жоба тақтасында стори «Жұмыста» бағанына ауыстырылғанда немесе «Агенттер жұмысы» бөліміндегі «Жаңа терминал» батырмасымен іске қосылады.",
|
||||
"Список сессий": "Сессиялар тізімі",
|
||||
"Открыть в «Сессиях»": "«Сессиялар» бөлімінде ашу",
|
||||
"Все колонки по ширине окна": "Барлық бағандар терезе енімен",
|
||||
"По ширине": "Ені бойынша",
|
||||
};
|
||||
@ -2,6 +2,7 @@
|
||||
// access/liveness/size/rate checks, the SSE stream.
|
||||
import assert from "node:assert/strict";
|
||||
import { after, describe, test } from "node:test";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import xterm from "@xterm/headless";
|
||||
import { core, db, project, runner, teardown, waitFor } from "./helpers.ts";
|
||||
|
||||
@ -54,6 +55,9 @@ function viewer() {
|
||||
}
|
||||
|
||||
const plain = async (name: string) => (await tmux.capturePane(name)).split("\n").slice(0, -1).map((l) => l.trimEnd());
|
||||
const tmuxSet = (name: string, opt: string, value: string) => execFileSync("tmux", ["-L", process.env.PEPPA_TMUX_SOCKET!, "set-option", "-t", name, opt, value]);
|
||||
/** PEP-257: the viewer's screen = the pane + tmux's status line at the bottom. */
|
||||
const paneRows = async (v: ReturnType<typeof viewer>) => (await v.screen()).slice(0, -1).map((l) => l.trimEnd());
|
||||
|
||||
describe("terminal feed", () => {
|
||||
test("normalizeAnsiLines carries colours over to the next line", () => {
|
||||
@ -76,7 +80,7 @@ describe("terminal feed", () => {
|
||||
await tmux.sendText(name, "hello", true);
|
||||
await waitFor("echo in the viewer", async () => (await v.screen()).includes("got:hello"));
|
||||
assert.ok(v.events.some((e) => e.type === "out"), "changes come as out events, not new frames");
|
||||
assert.deepEqual((await v.screen()).map((l) => l.trimEnd()), await plain(name), "viewer screen == tmux screen");
|
||||
assert.deepEqual(await paneRows(v), await plain(name), "viewer screen == tmux screen");
|
||||
} finally {
|
||||
off();
|
||||
}
|
||||
@ -94,7 +98,7 @@ describe("terminal feed", () => {
|
||||
const all = (await v.lines()).map((l) => l.trimEnd());
|
||||
const numbered = all.filter((l) => /^line-\d+$/.test(l)).map((l) => Number(l.slice(5)));
|
||||
assert.deepEqual(numbered, Array.from({ length: 80 }, (_, i) => i), "all 80 lines, once each, in order");
|
||||
assert.deepEqual((await v.screen()).map((l) => l.trimEnd()), await plain(name));
|
||||
assert.deepEqual(await paneRows(v), await plain(name));
|
||||
|
||||
// A newcomer gets the history in its first frame.
|
||||
const late = viewer();
|
||||
@ -127,6 +131,31 @@ describe("terminal feed", () => {
|
||||
assert.equal(runner.terminalFeed(name), undefined, "the loop stops without viewers");
|
||||
});
|
||||
|
||||
test("Строка статуса tmux: внизу кадра, по конфигурации tmux; status off — без неё", async () => {
|
||||
const { name } = await liveRunner();
|
||||
const v = viewer();
|
||||
const off = runner.watchTerminal(name, v.fn);
|
||||
try {
|
||||
await waitFor("first frame", async () => v.events.find((e) => e.type === "frame"));
|
||||
const frame = v.events.find((e) => e.type === "frame") as Extract<Ev, { type: "frame" }>;
|
||||
const info = await tmux.paneInfo(name);
|
||||
assert.equal(frame.rows, info.rows + 1, "one status line under the pane");
|
||||
const last = (await v.screen()).at(-1)!;
|
||||
// status-left «[#S] » is cut to status-left-length (10) by tmux itself, as in a native client.
|
||||
assert.ok(last.startsWith(`[${name}`.slice(0, 10)), `session name on the left: ${last}`);
|
||||
assert.match(last, /0:\S+\*/, "the active window with its flag");
|
||||
assert.match(frame.data, /\x1b\[0;30;42m/, "status-style bg=green,fg=black");
|
||||
// The status line follows tmux's configuration, including turning it off.
|
||||
tmuxSet(name, "status-right", "#[fg=red]RIGHT");
|
||||
await waitFor("right part", async () => (await v.screen()).at(-1)!.trimEnd().endsWith("RIGHT"));
|
||||
tmuxSet(name, "status", "off");
|
||||
await waitFor("no status", async () => v.events.some((e) => e.type === "frame" && e.rows === info.rows));
|
||||
assert.deepEqual((await v.screen()).map((l) => l.trimEnd()), await plain(name));
|
||||
} finally {
|
||||
off();
|
||||
}
|
||||
});
|
||||
|
||||
test("tmux-сессия пропала → end", async () => {
|
||||
const { name } = await liveRunner();
|
||||
const v = viewer();
|
||||
|
||||
46
packages/testkit/test/tmux-status.test.ts
Normal file
@ -0,0 +1,46 @@
|
||||
// PEP-257: tmux's own status-format expansion → one SGR line on the pane width.
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { charWidth, colourSgr, renderStatusLine } from "../../runner/src/tmux-status.ts";
|
||||
|
||||
const strip = (s: string) => s.replace(/\x1b\[[0-9;]*m/g, "");
|
||||
// What tmux 3.3 prints for #{T:status-format[0]} of a session «demo» with defaults.
|
||||
const DEFAULT =
|
||||
'#[align=left range=left default]#[push-default][demo] #[pop-default]#[norange default]#[list=on align=left]#[list=left-marker]<#[list=right-marker]>#[list=on]#[range=window|0 list=focus default]#[push-default]0:bash*#[pop-default]#[norange list=on default]#[nolist align=right range=right default]#[push-default]"host" 12:09 24-Nov-26#[pop-default]#[norange default]';
|
||||
|
||||
test("Строка статуса: левая часть, окна, правая часть у правого края, ширина — колонки pane", () => {
|
||||
const line = renderStatusLine(DEFAULT, 60, "bg=green,fg=black");
|
||||
const text = strip(line);
|
||||
assert.equal(text.length, 60);
|
||||
assert.ok(text.startsWith("[demo] 0:bash*"), text);
|
||||
assert.ok(text.endsWith('"host" 12:09 24-Nov-26'), text);
|
||||
assert.ok(!text.includes("<") && !text.includes(">"), "list markers are drawn only when the list is cut");
|
||||
assert.ok(line.startsWith("\x1b[0;30;42m"), "status-style: black on green");
|
||||
});
|
||||
|
||||
test("Стили: цвета по имени, colourN, #rrggbb, атрибуты, default и push-default", () => {
|
||||
assert.equal(colourSgr("red", false), "31");
|
||||
assert.equal(colourSgr("brightblue", true), "104");
|
||||
assert.equal(colourSgr("colour33", false), "38;5;33");
|
||||
assert.equal(colourSgr("#ff8000", true), "48;2;255;128;0");
|
||||
assert.equal(colourSgr("default", false), null);
|
||||
const line = renderStatusLine("#[fg=red,bold]A#[default]B#[fg=#00ff00]#[push-default]C#[fg=red]#[default]D#[pop-default]#[default]E", 10, "bg=blue");
|
||||
assert.match(line, /\x1b\[0;1;31;44mA/);
|
||||
assert.match(line, /\x1b\[0;44mB/);
|
||||
assert.match(line, /\x1b\[0;38;2;0;255;0;44mCD/, "default after push-default is the pushed style");
|
||||
assert.match(line, /\x1b\[0;44mE/, "pop-default restores status-style");
|
||||
});
|
||||
|
||||
test("Узкая строка: правая часть не налезает на левую; по центру — между ними", () => {
|
||||
const text = strip(renderStatusLine("LEFT-PART#[align=right]RIGHT-PART-LONG", 15, ""));
|
||||
assert.equal(text, "LEFT-PARTT-LONG");
|
||||
assert.ok(text.startsWith("LEFT-PART"));
|
||||
assert.ok(text.endsWith("LONG"));
|
||||
assert.equal(strip(renderStatusLine("#[align=centre]MID", 9, "")), " MID ");
|
||||
assert.equal(charWidth("中".codePointAt(0)!), 2);
|
||||
assert.equal(strip(renderStatusLine("中x", 4, "")), "中x ");
|
||||
});
|
||||
|
||||
test("Пустой формат — строка из фона status-style", () => {
|
||||
assert.equal(strip(renderStatusLine("", 5, "bg=green")), " ");
|
||||
});
|
||||