Skip to content

Commit 942e501

Browse files
committed
test(tui): prove command surfaces through PTY
1 parent b6a445c commit 942e501

5 files changed

Lines changed: 180 additions & 29 deletions
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
title: TUI command surfaces PTY contracts
2+
scenario:
3+
id: tui-command-surfaces-pty
4+
surface: tui
5+
category: tui.input-and-commands
6+
coverage:
7+
primary: [tui.slash-commands, tui.pickers, tui.settings]
8+
risk: low
9+
objective: Prove slash commands, model and session pickers, and settings updates through the real runTui PTY loop.
10+
successCriteria:
11+
- Slash command help and an executed backend command are visible in authenticated final terminal frames.
12+
- Model and session picker choices are visible, selected through literal PTY input, and applied to subsequent backend calls.
13+
- The settings overlay visibly updates tool output and thinking values, including the history refresh triggered by showing thinking.
14+
codeRefs:
15+
- src/tui/tui-pty-command-surfaces-test-support.ts
16+
- src/tui/tui-pty-harness-assertion-test-support.ts
17+
- src/tui/tui-pty-harness.e2e.test.ts
18+
execution:
19+
kind: script
20+
path: test/e2e/qa-lab/tui/tui-pty-evidence-producer.ts
21+
summary: Runs independently matched real-PTY command surface assertions and authenticates their fresh Vitest results.
22+
timeoutMs: 180000
23+
args: [--artifact-base, "${outputDir}", --scenario-id, "${scenarioId}"]
24+
config:
25+
tuiPtyCases:
26+
- {
27+
coverageId: tui.slash-commands,
28+
testFile: src/tui/tui-pty-harness.e2e.test.ts,
29+
testNamePattern: "^TUI PTY harness lists and executes slash commands through authenticated real PTY frames$",
30+
}
31+
- {
32+
coverageId: tui.pickers,
33+
testFile: src/tui/tui-pty-harness.e2e.test.ts,
34+
testNamePattern: "^TUI PTY harness selects model and session pickers through authenticated real PTY frames$",
35+
}
36+
- {
37+
coverageId: tui.settings,
38+
testFile: src/tui/tui-pty-harness.e2e.test.ts,
39+
testNamePattern: "^TUI PTY harness updates settings through an authenticated real PTY overlay$",
40+
}
Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
import { expect } from "vitest";
2+
import {
3+
type StartTuiPtyFixture,
4+
waitForSynchronizedFrameRows,
5+
} from "./tui-pty-harness-assertion-test-support.js";
6+
import { objectFieldEquals, readFixtureLog } from "./tui-pty-harness-fixture-test-support.js";
7+
8+
const slashHelpMarkers =
9+
"Slash commands:,/help,/verbose <on|off|full>,/reasoning <on|off|stream>,/goal,/goal start <objective>,/btw <side question>,/queue,/stop,/exit".split(
10+
",",
11+
);
12+
const countHistoryLoads = async (logPath: string) =>
13+
(await readFixtureLog(logPath)).filter((entry) => entry.method === "loadHistory").length;
14+
const rowsInclude = (rows: string[], ...texts: string[]) =>
15+
rows.some((row) => texts.every((text) => row.includes(text)));
16+
17+
export async function exerciseTuiCommandSurface(
18+
startFixture: StartTuiPtyFixture,
19+
surface: "slash-commands" | "pickers" | "settings",
20+
startupTimeoutMs: number,
21+
) {
22+
const fixture = await startFixture({
23+
env: {
24+
OPENCLAW_TUI_PTY_COLS: "100",
25+
OPENCLAW_TUI_PTY_ROWS: "24",
26+
...(surface === "pickers" ? { OPENCLAW_TUI_PTY_PICKER_FIXTURE: "1" } : {}),
27+
},
28+
});
29+
try {
30+
const waitForRows = (predicate: Parameters<typeof waitForSynchronizedFrameRows>[1]) =>
31+
waitForSynchronizedFrameRows(fixture.run, predicate, startupTimeoutMs);
32+
await fixture.run.waitForOutput("local ready", startupTimeoutMs);
33+
if (surface === "slash-commands") {
34+
await fixture.run.write("/help\r", { delay: false });
35+
for (const text of slashHelpMarkers) {
36+
await fixture.run.waitForOutput(text, startupTimeoutMs);
37+
}
38+
await waitForRows((rows) =>
39+
["/settings", "/exit"].every((text) => rows.some((row) => row.trim() === text)),
40+
);
41+
await fixture.run.write("/gateway-status\r", { delay: false });
42+
await fixture.waitForLogEntry((entry) => entry.method === "getGatewayStatus");
43+
await waitForRows((rows) => rows.some((row) => row.trim() === "fixture gateway ok"));
44+
return;
45+
}
46+
if (surface === "pickers") {
47+
await fixture.run.write("/models\r", { delay: false });
48+
await fixture.waitForLogEntry((entry) => entry.method === "listModels");
49+
await waitForRows((rows) => rows.some((row) => row.includes("Fixture 2")));
50+
await fixture.run.write("\x1b[B\r", { delay: false });
51+
await fixture.waitForLogEntry(
52+
(entry) =>
53+
entry.method === "patchSession" &&
54+
objectFieldEquals(entry, "model", "fixture-provider/fixture-model-2"),
55+
);
56+
await fixture.run.write("/sessions\r", { delay: false });
57+
await fixture.waitForLogEntry(
58+
(entry) => entry.method === "listSessions" && objectFieldEquals(entry, "purpose", "picker"),
59+
);
60+
await waitForRows((rows) => rows.some((row) => row.includes("Picker target")));
61+
await fixture.run.write("\x1b[B\r", { delay: false });
62+
await fixture.waitForLogEntry(
63+
(entry) =>
64+
entry.method === "loadHistory" &&
65+
objectFieldEquals(entry, "sessionKey", "agent:main:picker-target"),
66+
);
67+
await fixture.run.write("picker selection proof\r", { delay: false });
68+
const sent = await fixture.waitForLogEntry(
69+
(entry) =>
70+
entry.method === "sendChat" &&
71+
objectFieldEquals(entry, "message", "picker selection proof"),
72+
);
73+
expect(sent.payload).toMatchObject({ sessionKey: "agent:main:picker-target" });
74+
await waitForRows((rows) => rowsInclude(rows, "PTY_RESPONSE: picker selection proof"));
75+
return;
76+
}
77+
const initialHistoryLoads = await countHistoryLoads(fixture.logPath);
78+
await fixture.run.write("/settings\r", { delay: false });
79+
await waitForRows(
80+
(rows) =>
81+
rowsInclude(rows, "Tool output", "collapsed") && rowsInclude(rows, "Show thinking", "off"),
82+
);
83+
await fixture.run.write("\r", { delay: false });
84+
await waitForRows((rows) => rowsInclude(rows, "Tool output", "expanded"));
85+
expect(await countHistoryLoads(fixture.logPath)).toBe(initialHistoryLoads);
86+
await fixture.run.write("\x1b[B\r", { delay: false });
87+
await waitForRows((rows) => rowsInclude(rows, "Show thinking", "on"));
88+
await expect
89+
.poll(() => countHistoryLoads(fixture.logPath), { timeout: startupTimeoutMs })
90+
.toBe(initialHistoryLoads + 1);
91+
} finally {
92+
await fixture.cleanup();
93+
}
94+
}

‎src/tui/tui-pty-harness-assertion-test-support.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ describe("hasSynchronizedFrameRow", () => {
3737
expect(hasExpected(frame("T08A safe T08B"))).toBe(false);
3838
expect(parse(frame("界X\r\x1b[2G?"))[0]).toEqual([" ?X"]);
3939
expect(parse(frame("界X\r\x1b[2G\x1b[K"))[0]).toEqual([""]);
40+
expect(parse(`${EXPECTED}${frame("")}`)).toEqual([[""]]);
4041
expect(parse(frame("\u2067RTL\u2069"))[0]).toEqual(["RTL"]);
4142
expect(parse(frame(`${"x".repeat(32)}\x1b[3Jy`), { cols: 32, rows: 2 })[0]).toEqual([
4243
"x".repeat(32),

‎src/tui/tui-pty-harness-assertion-test-support.ts‎

Lines changed: 36 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import {
1313
} from "./tui-pty-test-support.js";
1414

1515
export type FixtureLogEntry = { method: string; payload?: unknown };
16+
type FixtureLogPredicate = (entry: FixtureLogEntry) => boolean;
1617

1718
export const COMPACT_TERMINAL_SIZES = [
1819
[64, 18],
@@ -38,7 +39,7 @@ export async function readFixtureLog(logPath: string): Promise<FixtureLogEntry[]
3839

3940
export async function waitForFixtureLogEntry(
4041
logPath: string,
41-
predicate: (entry: FixtureLogEntry) => boolean,
42+
predicate: FixtureLogPredicate,
4243
timeoutMs: number,
4344
readPtyOutput?: () => string,
4445
) {
@@ -67,8 +68,14 @@ export function objectFieldEquals(entry: FixtureLogEntry, field: string, value:
6768
return Object.hasOwn(payload, field) && payload[field] === value;
6869
}
6970

70-
type StartTuiPtyFixture = Parameters<typeof exerciseFragmentedUnicodePrompt>[0];
71-
type StartedTuiPtyFixture = Awaited<ReturnType<StartTuiPtyFixture>>;
71+
type StartedTuiPtyFixture = {
72+
run: PtyRun;
73+
logPath: string;
74+
waitForLogEntry: (predicate: FixtureLogPredicate, timeoutMs?: number) => Promise<FixtureLogEntry>;
75+
cleanup: () => Promise<void>;
76+
};
77+
type TuiPtyFixtureOptions = { env?: NodeJS.ProcessEnv };
78+
export type StartTuiPtyFixture = (opts?: TuiPtyFixtureOptions) => Promise<StartedTuiPtyFixture>;
7279
type TerminalAttackPayload = {
7380
text: string;
7481
markers: string[];
@@ -261,33 +268,45 @@ function parseTerminalState(
261268
: undefined;
262269
}
263270

271+
function authenticatedRowText(cells: PtyTestScreen["cells"][number]) {
272+
return cells
273+
.slice(0, cells.findLastIndex((cell) => cell.authenticated) + 1)
274+
.map((cell) => (cell.text === "" || cell.authenticated ? cell.text : STALE_CELL_SENTINEL))
275+
.join("")
276+
.trimEnd();
277+
}
278+
264279
export function synchronizedFrameRows(raw: string, dimensions: PtyTerminalDimensions): string[][] {
265280
const screen = parseTerminalState(raw, dimensions);
266281
if (!screen) {
267282
return [];
268283
}
269-
const rows = screen.cells.map((row) =>
270-
row
271-
.map((cell) => cell.text)
272-
.join("")
273-
.trimEnd(),
274-
);
284+
const rows = screen.cells.map(authenticatedRowText);
275285
while (rows.length > 1 && rows.at(-1) === "") {
276286
rows.pop();
277287
}
278288
return [rows];
279289
}
280290

281-
function screenHasRow(screen: PtyTestScreen, predicate: (row: string) => boolean) {
282-
return screen.cells.some((cells) => {
283-
const authoredRow = cells
284-
.map((cell) => (cell.text === "" || cell.authenticated ? cell.text : STALE_CELL_SENTINEL))
285-
.join("")
286-
.trimEnd();
287-
return predicate(authoredRow);
291+
export async function waitForSynchronizedFrameRows(
292+
run: PtyRun,
293+
predicate: (rows: string[]) => boolean,
294+
timeoutMs: number,
295+
) {
296+
return await waitFor({
297+
timeoutMs,
298+
read: () => {
299+
const rows = synchronizedFrameRows(run.output(), run).at(0);
300+
return rows && predicate(rows) ? rows : null;
301+
},
302+
onTimeout: () => new Error(`expected completed synchronized frame\n${run.output()}`),
288303
});
289304
}
290305

306+
function screenHasRow(screen: PtyTestScreen, predicate: (row: string) => boolean) {
307+
return screen.cells.some((cells) => predicate(authenticatedRowText(cells)));
308+
}
309+
291310
function latestFrameHasRow(
292311
raw: string,
293312
dimensions: PtyTerminalDimensions,
@@ -693,11 +712,7 @@ export async function exerciseTerminalOutputSafety(
693712

694713
/** Proves fixture-local fragmentation preserves a Unicode prompt through the real TUI loop. */
695714
export async function exerciseFragmentedUnicodePrompt(
696-
startFixture: (opts: { env?: NodeJS.ProcessEnv }) => Promise<{
697-
run: PtyRun;
698-
waitForLogEntry: (predicate: (entry: FixtureLogEntry) => boolean) => Promise<FixtureLogEntry>;
699-
cleanup: () => Promise<void>;
700-
}>,
715+
startFixture: StartTuiPtyFixture,
701716
startupTimeoutMs: number,
702717
) {
703718
const fixture = await startFixture({

‎src/tui/tui-pty-harness.e2e.test.ts‎

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { mkdtemp, rm } from "node:fs/promises";
33
import { tmpdir } from "node:os";
44
import path from "node:path";
55
import { afterAll, beforeAll, describe, expect, it } from "vitest";
6+
import { exerciseTuiCommandSurface } from "./tui-pty-command-surfaces-test-support.js";
67
import {
78
approveWorkspaceSkill,
89
COMPACT_TERMINAL_SIZES,
@@ -901,14 +902,14 @@ describe.sequential("TUI PTY harness", () => {
901902
STARTUP_TEST_TIMEOUT_MS,
902903
);
903904

904-
it(
905-
"renders slash command help",
906-
async () => {
907-
await fixture.run.write("/help\r", { delay: false });
908-
// prettier-ignore
909-
for (const text of ["Slash commands:", "/help", "/verbose <on|off|full>", "/reasoning <on|off|stream>", "/goal", "/goal start <objective>", "/btw <side question>", "/queue", "/stop", "/exit"]) { await fixture.run.waitForOutput(text); }
910-
},
911-
TEST_TIMEOUT_MS,
905+
it.each([
906+
["lists and executes slash commands through authenticated real PTY frames", "slash-commands"],
907+
["selects model and session pickers through authenticated real PTY frames", "pickers"],
908+
["updates settings through an authenticated real PTY overlay", "settings"],
909+
] as const)(
910+
"%s",
911+
(_name, surface) => exerciseTuiCommandSurface(startTuiFixture, surface, STARTUP_TIMEOUT_MS),
912+
STARTUP_TEST_TIMEOUT_MS,
912913
);
913914

914915
it(

0 commit comments

Comments
 (0)