peppa/packages/testkit/test/terminal.test.ts
2026-11-25 12:58:02 +00:00

278 lines
14 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

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

// PEP-9: live runner terminal in the web — pane feed (real tmux → headless xterm), input with
// 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";
process.env.PEPPA_SECRET = "mock-secret-for-tests";
after(teardown);
const { tmux } = runner;
type Ev = import("@peppa/runner").TerminalEvent;
// A pane that prints a coloured line, then echoes lines; "scroll" prints 80 numbered lines.
const PANE_SCRIPT = `printf '\\033[31mred\\033[0m start\\n'; while read l; do if [ "$l" = scroll ]; then i=0; while [ $i -lt 80 ]; do echo "line-$i"; i=$((i+1)); done; else echo "got:$l"; fi; done`;
let seq = 0;
async function liveRunner(opts: { status?: "running" | "done"; ownerId?: number | null } = {}) {
const p = await project({ turns: [] });
const proj = await core.getProject(db, p.key);
if (opts.ownerId !== undefined) await core.setProjectOwner(db, proj.id, opts.ownerId);
const task = await p.task();
const s = await core.createSession(db, { projectId: proj.id, taskId: task.id });
const name = `peppa-term-${process.pid}-${seq++}`;
await core.updateSession(db, s.id, { tmuxName: name, status: opts.status ?? "running" });
await tmux.newSession({ name, cwd: p.dir, command: `sh -c '${PANE_SCRIPT.replace(/'/g, "'\\''")}'`, env: {}, width: 100 });
await tmux.sendKeys(name, ""); // make sure the server is up before the first capture
return { p, proj, session: await core.getSession(db, s.id), name };
}
/** A headless xterm that applies feed events exactly like the browser component. */
function viewer() {
const t = new xterm.Terminal({ cols: 80, rows: 24, scrollback: 5000, allowProposedApi: true });
const events: Ev[] = [];
let pending = Promise.resolve();
const write = (d: string) => (pending = pending.then(() => new Promise<void>((r) => t.write(d, r))));
const fn = (e: Ev) => {
events.push(e);
if (e.type === "frame") {
pending = pending.then(() => {
t.reset();
t.resize(e.cols, e.rows);
});
write(e.data);
} else if (e.type === "out") write(e.data);
};
const lines = async () => {
await pending;
const b = t.buffer.active;
return Array.from({ length: b.length }, (_, i) => b.getLine(i)!.translateToString(true));
};
const screen = async () => (await lines()).slice(-t.rows);
return { t, events, fn, lines, screen };
}
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", () => {
const out = runner.normalizeAnsiLines("\x1b[31mred\nstill red\x1b[0m\nplain\n");
assert.deepEqual(out, ["\x1b[31mred", "\x1b[31mstill red\x1b[0m", "plain"]);
assert.deepEqual(runner.normalizeAnsiLines("\x1b[1m\x1b[0;32mx\ny\n"), ["\x1b[1m\x1b[0;32mx", "\x1b[32my"]);
});
test("Открыть терминал: первый кадр — экран pane с цветами, потом изменения", 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" }>;
assert.equal(frame.cols, 100);
assert.match(frame.data, /\x1b\[31mred/, "colours survive");
assert.equal((await v.screen())[0], "red start");
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 paneRows(v), await plain(name), "viewer screen == tmux screen");
} finally {
off();
}
});
test("История: строки, ушедшие за экран, попадают в прокрутку xterm по порядку", async () => {
const { name } = await liveRunner();
const v = viewer();
const off = runner.watchTerminal(name, v.fn);
try {
await waitFor("first frame", async () => v.events.length > 0);
await tmux.sendText(name, "scroll", true);
await waitFor("last line", async () => (await v.screen()).includes("line-79"));
await new Promise((r) => setTimeout(r, 600));
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 paneRows(v), await plain(name));
// A newcomer gets the history in its first frame.
const late = viewer();
const off2 = runner.watchTerminal(name, late.fn);
await waitFor("late frame", async () => late.events.length > 0);
const lateNumbered = (await late.lines()).filter((l) => /^line-\d+$/.test(l.trimEnd()));
assert.equal(lateNumbered.length, 80);
off2();
} finally {
off();
}
});
test("Несколько зрителей: один цикл опроса на раннер", async () => {
const { name } = await liveRunner();
const a = viewer();
const b = viewer();
const offA = runner.watchTerminal(name, a.fn);
const offB = runner.watchTerminal(name, b.fn);
const feed = runner.terminalFeed(name)!;
assert.equal(feed.size, 2);
await waitFor("both framed", async () => a.events.length > 0 && b.events.length > 0);
await tmux.sendText(name, "both", true);
await waitFor("both see it", async () => (await a.screen()).includes("got:both") && (await b.screen()).includes("got:both"));
const polls = feed.polls;
await new Promise((r) => setTimeout(r, 1000));
assert.ok(feed.polls - polls <= 6, `one loop for two viewers (${feed.polls - polls} polls/s)`);
offA();
offB();
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();
runner.watchTerminal(name, v.fn);
await waitFor("frame", async () => v.events.length > 0);
await tmux.killSession(name);
await waitFor("end", async () => v.events.some((e) => e.type === "end"));
assert.equal(runner.terminalFeed(name), undefined);
});
});
async function user(login: string) {
return core.upsertUserFromGitea(db, { id: 5000 + seq++, login }, { access_token: "x" });
}
async function status(p: Promise<unknown>): Promise<number | "ok"> {
try {
await p;
return "ok";
} catch (e) {
if (e instanceof runner.TerminalError) return e.status;
throw e;
}
}
describe("terminal input", () => {
test("Ответить агенту с клавиатуры: байты в pane, сброс автопродолжений, журнал", async () => {
const owner = await user("term-owner");
const { session, name } = await liveRunner({ ownerId: owner.id });
await core.updateSession(db, session.id, { autoNudges: 2 });
await runner.terminalInput(db, owner, session.id, { keys: "да\r" });
await waitFor("got:да", async () => (await plain(name)).includes("got:да"));
assert.equal((await core.getSession(db, session.id)).autoNudges, 0);
// Arrow keys and Ctrl-codes go through as raw bytes too.
await runner.terminalInput(db, owner, session.id, { keys: "ab\x7fc\r" });
await waitFor("backspace applied", async () => (await plain(name)).includes("got:ac"));
const evs = (await db.$client.prepare("select type, payload from events where session_id = ?").all(session.id)) as Array<{ type: string; payload: string }>;
const logged = evs.filter((e) => e.type === "terminal_input");
assert.equal(logged.length, 1, "one journal entry per minute");
assert.equal(JSON.parse(logged[0]!.payload).login, "term-owner");
});
test("Вставка многострочного текста — одной вставкой", async () => {
const owner = await user("term-paster");
const { session, name } = await liveRunner({ ownerId: owner.id });
await runner.terminalInput(db, owner, session.id, { paste: "one\ntwo\n" });
await waitFor("both lines", async () => {
const s = await plain(name);
return s.includes("got:one") && s.includes("got:two");
});
});
test("Участник может, посторонний — 404", async () => {
const owner = await user("term-o2");
const member = await user("term-member");
const stranger = await user("term-stranger");
const { proj, session, name } = await liveRunner({ ownerId: owner.id });
await core.addMember(db, proj, "term-member", owner.id);
assert.equal(await status(runner.terminalInput(db, member, session.id, { keys: "m\r" })), "ok");
await waitFor("member input", async () => (await plain(name)).includes("got:m"));
assert.equal(await status(runner.terminalInput(db, stranger, session.id, { keys: "x\r" })), 404);
assert.equal(await status(runner.terminalInput(db, stranger, 999999, { keys: "x" })), 404, "missing session looks the same");
assert.equal(await status(runner.terminalSse(db, stranger, session.id, new AbortController().signal)), 404);
});
test("Завершённая сессия и пропавший tmux — 409", async () => {
const owner = await user("term-o3");
const done = await liveRunner({ ownerId: owner.id, status: "done" });
assert.equal(await status(runner.terminalInput(db, owner, done.session.id, { keys: "x\r" })), 409);
assert.ok(!(await plain(done.name)).includes("got:x"));
const gone = await liveRunner({ ownerId: owner.id });
await tmux.killSession(gone.name);
assert.equal(await status(runner.terminalInput(db, owner, gone.session.id, { keys: "x" })), 409);
});
test("Слишком много или слишком часто — 413 / 429", async () => {
const owner = await user("term-o4");
const { session } = await liveRunner({ ownerId: owner.id });
assert.equal(await status(runner.terminalInput(db, owner, session.id, { keys: "x".repeat(runner.TERMINAL_MAX_KEYS_BYTES + 1) })), 413);
assert.equal(await status(runner.terminalInput(db, owner, session.id, { paste: "x".repeat(runner.TERMINAL_MAX_PASTE_BYTES + 1) })), 413);
assert.equal(await status(runner.terminalInput(db, owner, session.id, {})), 400);
const now = Date.now() + 10 * 60_000; // a window of its own
for (let i = 0; i < runner.TERMINAL_RATE_MAX; i++) await runner.terminalInput(db, owner, session.id, { keys: "a" }, now + i);
assert.equal(await status(runner.terminalInput(db, owner, session.id, { keys: "a" }, now + 100)), 429);
assert.equal(await status(runner.terminalInput(db, owner, session.id, { keys: "\r" }, now + runner.TERMINAL_RATE_WINDOW_MS + 100)), "ok", "the window slides");
});
});
describe("terminal SSE", () => {
test("поток: retry, кадр, пинг; отключение освобождает зрителя", async () => {
const owner = await user("term-sse");
const { session, name } = await liveRunner({ ownerId: owner.id });
const ac = new AbortController();
const res = await runner.terminalSse(db, owner, session.id, ac.signal, { pingMs: 200 });
assert.equal(res.headers.get("content-type"), "text/event-stream; charset=utf-8");
assert.match(res.headers.get("cache-control")!, /no-transform/);
const reader = res.body!.getReader();
const dec = new TextDecoder();
let text = "";
await waitFor("frame and ping", async () => {
const { value } = await reader.read();
text += dec.decode(value);
return text.includes("event: frame") && text.includes(": ping");
});
assert.ok(text.startsWith("retry: 3000\n\n"));
const frame = JSON.parse(text.split("event: frame\ndata: ")[1]!.split("\n")[0]!);
assert.equal(frame.cols, 100);
assert.match(frame.data, /red/);
ac.abort();
await waitFor("stream closed on abort", async () => (await reader.read()).done, 3000);
assert.equal(runner.terminalFeed(name), undefined, "the poll loop stopped");
// The viewer slot was released: 8 more streams fit, the 9th does not.
const acs = Array.from({ length: runner.TERMINAL_MAX_VIEWERS_PER_USER }, () => new AbortController());
for (const a of acs) await runner.terminalSse(db, owner, session.id, a.signal);
assert.equal(await status(runner.terminalSse(db, owner, session.id, new AbortController().signal)), 429);
for (const a of acs) a.abort();
});
});