Skip to content

Commit 52954a1

Browse files
authored
chore(tui): add Gateway boundary PTY coverage (#119191)
* test(tui): prove gateway boundary flows * test(tui): tighten gateway boundary assertions * test(tui): satisfy gateway boundary lint * test(tui): harden gateway boundary PTY proof * test(tui): strengthen gateway lifecycle proof * test(tui): validate gateway history metadata * test(tui): isolate gateway model proof * test(tui): isolate gateway model replies * test(tui): isolate gateway boundary fixtures * test(tui): settle gateway session adoption
1 parent b5876a1 commit 52954a1

2 files changed

Lines changed: 310 additions & 6 deletions

File tree

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
title: TUI Gateway boundary PTY contracts
2+
scenario:
3+
id: tui-gateway-boundary-pty
4+
surface: tui
5+
category: tui.runtime-modes
6+
coverage:
7+
primary:
8+
- tui.gateway-connection
9+
- tui.gateway-authentication
10+
- tui.history-load-on-attach
11+
- tui.reconnect-visibility
12+
- tui.gateway-command-rpcs
13+
risk: medium
14+
objective: Prove TUI Gateway connection, authentication, attach history, reconnect visibility, and command RPC behavior through a real WebSocket and PTY.
15+
successCriteria:
16+
- A built TUI proves Gateway connection, isolated authentication without token leakage, authoritative attach history, disconnected-draft recovery, and visible authoritative status, model, session creation, and reset RPC outcomes.
17+
codeRefs: [src/tui/tui-pty-local.e2e.test.ts]
18+
execution:
19+
kind: script
20+
path: test/e2e/qa-lab/tui/tui-pty-evidence-producer.ts
21+
timeoutMs: 600000
22+
args: [--artifact-base, "${outputDir}", --scenario-id, "${scenarioId}"]
23+
config:
24+
requireBuiltCli: true
25+
tuiPtyCases:
26+
- coverageId: tui.gateway-connection
27+
testFile: src/tui/tui-pty-local.e2e.test.ts
28+
testNamePattern: ^TUI PTY real backends with shared Gateway fixture launches openclaw tui against a real Gateway through a real PTY$
29+
- coverageId: tui.gateway-authentication
30+
testFile: src/tui/tui-pty-local.e2e.test.ts
31+
testNamePattern: ^TUI PTY real backends with shared Gateway fixture authenticates valid tokens and rejects invalid tokens through a real Gateway PTY$
32+
- coverageId: tui.history-load-on-attach
33+
testFile: src/tui/tui-pty-local.e2e.test.ts
34+
testNamePattern: ^TUI PTY real backends with shared Gateway fixture loads completed Gateway history on a fresh TUI attach before user input$
35+
- coverageId: tui.reconnect-visibility
36+
testFile: src/tui/tui-pty-local.e2e.test.ts
37+
testNamePattern: ^TUI PTY real backends with shared Gateway fixture preserves a disconnected draft across a real Gateway restart$
38+
- coverageId: tui.gateway-command-rpcs
39+
testFile: src/tui/tui-pty-local.e2e.test.ts
40+
testNamePattern: ^TUI PTY real backends with shared Gateway fixture executes Gateway status model new and reset RPCs through a real TUI PTY$

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

Lines changed: 270 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import type { OpenClawConfig } from "../config/types.openclaw.js";
1414
import { connectGatewayClient } from "../gateway/test-helpers.e2e.js";
1515
import { createDeferred } from "../test-utils/deferred.js";
1616
import { GatewayChatClient } from "./gateway-chat.js";
17+
import { synchronizedFrameRows } from "./tui-pty-harness-assertion-test-support.js";
1718
import {
1819
cleanupStartedFixture,
1920
createFreshSession,
@@ -69,6 +70,18 @@ const GATEWAY_SCENARIOS = {
6970
holdFirstResponse: false,
7071
followupReplyText: "FOLLOWUP_RUN_COMPLETE",
7172
},
73+
command: {
74+
agentId: SHARED_GATEWAY_AGENT_ID,
75+
modelId: "tui-pty-command",
76+
toolsProfile: "minimal",
77+
replyText: "FIRST_RUN_ACTIVE",
78+
},
79+
history: {
80+
agentId: SHARED_GATEWAY_AGENT_ID,
81+
modelId: "tui-pty-history",
82+
toolsProfile: "minimal",
83+
replyText: "T02_HISTORY_ASSISTANT",
84+
},
7285
followup: {
7386
agentId: SHARED_GATEWAY_AGENT_ID,
7487
modelId: "tui-pty-followup",
@@ -602,9 +615,9 @@ function buildGatewayModeConfig(params: { tempDir: string; providerBaseUrl: stri
602615
const scenarios: GatewayScenario[] = Object.values(GATEWAY_SCENARIOS);
603616
// One minimal agent keeps provider/runtime initialization warm; unique
604617
// sessions and per-session models retain each scenario's state boundary.
605-
const agentScenarios = [
606-
...new Map(scenarios.map((scenario) => [scenario.agentId, scenario])).values(),
607-
];
618+
const agentScenarios = scenarios.filter(
619+
({ agentId }, index) => scenarios.findIndex((item) => item.agentId === agentId) === index,
620+
);
608621
const defaultScenario = GATEWAY_SCENARIOS.validation;
609622
const defaultModelRef = `tui-pty-mock/${defaultScenario.modelId}`;
610623
const modelRefs = scenarios.map((scenario) => `tui-pty-mock/${scenario.modelId}`);
@@ -813,10 +826,19 @@ async function startGatewayModeTui(
813826
model: `tui-pty-mock/${scenario.modelId}`,
814827
});
815828
const run = shared.run;
816-
const outputOffset = run.visibleOutput().length;
817-
// Session adoption is the per-case isolation boundary for the shared PTY.
829+
const adoptionOffset = run.visibleOutput().length;
818830
await run.write(`/session ${sessionKey}\r`, { delay: false });
819-
await waitForOutputAfter(run, `session ${sessionKey.split(":").at(-1)}`, outputOffset);
831+
const sessionAcknowledgement = `session ${sessionKey.split(":").at(-1)}`;
832+
await waitForOutputAfter(run, sessionAcknowledgement, adoptionOffset);
833+
await waitFor({
834+
timeoutMs: LOCAL_OUTPUT_TIMEOUT_MS,
835+
read: () => {
836+
const screen = synchronizedFrameRows(run.output(), run)[0]?.join("\n") ?? "";
837+
return screen.includes(sessionAcknowledgement) && screen.includes("| idle") ? true : null;
838+
},
839+
onTimeout: () => new Error("adopted Gateway session did not reach an idle final screen"),
840+
});
841+
const outputOffset = run.visibleOutput().length;
820842
const cleanup = createIdempotentCleanup(async () => {
821843
shared.mockModel.releaseFirstResponse(scenario.modelId);
822844
for (const key of sessionKeys) {
@@ -845,6 +867,74 @@ async function startGatewayModeTui(
845867
};
846868
}
847869

870+
async function startIsolatedGatewayPty(params: {
871+
gateway: OpenClawTestInstance;
872+
registerCleanup: CleanupRegistrar;
873+
sessionKey: string;
874+
token?: string;
875+
}) {
876+
const { gateway, registerCleanup, sessionKey, token = gateway.gatewayToken } = params;
877+
const tempDir = await mkdtemp(path.join(tmpdir(), "openclaw-tui-pty-gateway-client-"));
878+
let run: PtyRun;
879+
try {
880+
await writeFile(path.join(tempDir, "openclaw.json"), "{}\n", "utf8");
881+
const cliArgs = ["tui", "--url", gateway.url, "--token", token, "--session", sessionKey];
882+
run = startPty(process.execPath, buildTuiProcessArgs(cliArgs), {
883+
cwd: process.cwd(),
884+
env: {
885+
...gateway.env,
886+
HOME: tempDir,
887+
OPENCLAW_HOME: tempDir,
888+
OPENCLAW_CONFIG_PATH: path.join(tempDir, "openclaw.json"),
889+
OPENCLAW_STATE_DIR: tempDir,
890+
OPENCLAW_AGENT_DIR: undefined,
891+
OPENCLAW_GATEWAY_TOKEN: undefined,
892+
OPENCLAW_GATEWAY_PASSWORD: undefined,
893+
OPENCLAW_THEME: "dark",
894+
NO_COLOR: undefined,
895+
},
896+
exitTimeoutMs: LOCAL_EXIT_TIMEOUT_MS,
897+
outputTimeoutMs: LOCAL_OUTPUT_TIMEOUT_MS,
898+
});
899+
} catch (error) {
900+
await rm(tempDir, { recursive: true, force: true });
901+
throw error;
902+
}
903+
const cleanup = createIdempotentCleanup(async () => {
904+
try {
905+
await run.dispose();
906+
} finally {
907+
await rm(tempDir, { recursive: true, force: true });
908+
}
909+
});
910+
registerCleanup(cleanup);
911+
return { run, cleanup };
912+
}
913+
type GatewayHistory = { messages: unknown[]; sessionInfo?: Record<string, unknown> };
914+
function hasOrderedTurn(messages: unknown[], userMarker: string, assistantMarker: string) {
915+
const matches = (message: unknown, role: "assistant" | "user", marker: string) =>
916+
(message as { role?: unknown } | null)?.role === role &&
917+
JSON.stringify(message).includes(marker);
918+
const userIndex = messages.findIndex((message) => matches(message, "user", userMarker));
919+
return (
920+
userIndex >= 0 &&
921+
messages.slice(userIndex + 1).some((message) => matches(message, "assistant", assistantMarker))
922+
);
923+
}
924+
async function waitForHistoryMessages(
925+
client: GatewayChatClient,
926+
key: string,
927+
accept: (history: GatewayHistory) => boolean,
928+
) {
929+
const deadline = Date.now() + LOCAL_OUTPUT_TIMEOUT_MS;
930+
for (; Date.now() < deadline; await sleep(25)) {
931+
const history = (await client.loadHistory({ sessionKey: key, limit: 100 })) as GatewayHistory;
932+
if (Array.isArray(history.messages) && accept(history)) {
933+
return history;
934+
}
935+
}
936+
throw new Error(`history ${key} did not reach the expected authoritative state`);
937+
}
848938
// Gateway cases share one real server and PTY but keep isolated models and sessions.
849939
// Per-case abort cleanup and serial order prevent active-run or queue state leaks.
850940
describe("TUI PTY real backends", () => {
@@ -1146,6 +1236,180 @@ describe("TUI PTY real backends", () => {
11461236
});
11471237
}
11481238

1239+
registerGatewayTest(
1240+
"authenticates valid tokens and rejects invalid tokens through a real Gateway PTY",
1241+
async ({ onTestFinished }) => {
1242+
const shared = await requireSharedGatewayFixture();
1243+
const agentId = SHARED_GATEWAY_AGENT_ID;
1244+
const sessionKey = `agent:${agentId}:tui-pty-auth`;
1245+
const invalidToken = "T02_INVALID_TOKEN_MUST_NOT_LEAK";
1246+
await shared.controlClient.createSession({ key: sessionKey, agentId });
1247+
const valid = await startIsolatedGatewayPty({
1248+
gateway: shared.gateway,
1249+
registerCleanup: onTestFinished,
1250+
sessionKey,
1251+
});
1252+
const invalid = await startIsolatedGatewayPty({
1253+
gateway: shared.gateway,
1254+
registerCleanup: onTestFinished,
1255+
sessionKey,
1256+
token: invalidToken,
1257+
});
1258+
try {
1259+
await valid.run.waitForOutput("gateway connected", LOCAL_STARTUP_TIMEOUT_MS);
1260+
await invalid.run.waitForOutput("gateway token mismatch", LOCAL_STARTUP_TIMEOUT_MS);
1261+
const output = `${valid.run.output()}\n${invalid.run.output()}\n${shared.gateway.logs()}`;
1262+
for (const token of [shared.gateway.gatewayToken, invalidToken]) {
1263+
expect(output.includes(token), "Gateway token leaked into captured output").toBe(false);
1264+
}
1265+
} finally {
1266+
await Promise.all([valid.cleanup(), invalid.cleanup()]);
1267+
}
1268+
},
1269+
LOCAL_TEST_TIMEOUT_MS,
1270+
);
1271+
registerGatewayTest(
1272+
"loads completed Gateway history on a fresh TUI attach before user input",
1273+
async ({ onTestFinished }) => {
1274+
const shared = await requireSharedGatewayFixture();
1275+
const agentId = SHARED_GATEWAY_AGENT_ID;
1276+
const sessionKey = `agent:${agentId}:tui-pty-history`;
1277+
const userMarker = "T02_HISTORY_USER";
1278+
const assistantMarker = GATEWAY_SCENARIOS.history.replyText;
1279+
const model = `tui-pty-mock/${GATEWAY_SCENARIOS.history.modelId}`;
1280+
await shared.controlClient.createSession({ key: sessionKey, agentId });
1281+
await shared.controlClient.patchSession({ key: sessionKey, agentId, model });
1282+
await shared.controlClient.sendChat({ sessionKey, message: userMarker });
1283+
await waitForHistoryMessages(shared.controlClient, sessionKey, ({ messages }) =>
1284+
hasOrderedTurn(messages, userMarker, assistantMarker),
1285+
);
1286+
const attached = await startIsolatedGatewayPty({
1287+
gateway: shared.gateway,
1288+
registerCleanup: onTestFinished,
1289+
sessionKey,
1290+
});
1291+
try {
1292+
await attached.run.waitForOutput(assistantMarker, LOCAL_STARTUP_TIMEOUT_MS);
1293+
const output = await waitFor({
1294+
timeoutMs: LOCAL_STARTUP_TIMEOUT_MS,
1295+
read: () => {
1296+
const screen =
1297+
synchronizedFrameRows(attached.run.output(), attached.run)[0]?.join("\n") ?? "";
1298+
return screen.includes(userMarker) && screen.includes(assistantMarker) ? screen : null;
1299+
},
1300+
onTimeout: () => new Error("history did not reach a final synchronized TUI screen"),
1301+
});
1302+
expect(output.split(userMarker)).toHaveLength(2);
1303+
expect(output.split(assistantMarker)).toHaveLength(2);
1304+
expect(output.indexOf(userMarker)).toBeLessThan(output.indexOf(assistantMarker));
1305+
} finally {
1306+
await attached.cleanup();
1307+
}
1308+
},
1309+
LOCAL_TEST_TIMEOUT_MS,
1310+
);
1311+
registerGatewayTest(
1312+
"executes Gateway status model new and reset RPCs through a real TUI PTY",
1313+
async ({ onTestFinished }) => {
1314+
const fixture = await startGatewayModeTui("command", onTestFinished);
1315+
const { controlClient } = await requireSharedGatewayFixture();
1316+
try {
1317+
await fixture.run.write("/gateway-status\r", { delay: false });
1318+
await fixture.waitForOutput("Default model: tui-pty-validation (128k ctx)");
1319+
const newOffset = fixture.run.visibleOutput().length;
1320+
await fixture.run.write("/new\r", { delay: false });
1321+
await waitForOutputAfter(fixture.run, "new session: agent:", newOffset);
1322+
const createdOutput = fixture.run.visibleOutput().slice(newOffset);
1323+
const createdKey = createdOutput.match(/new session: (agent:\S+)/)?.[1];
1324+
expect(createdKey).toBeDefined();
1325+
expect(createdKey).not.toBe(fixture.sessionKey);
1326+
fixture.trackSessionKey(createdKey!);
1327+
const created = await waitForHistoryMessages(
1328+
controlClient,
1329+
createdKey!,
1330+
({ sessionInfo }) => Boolean(sessionInfo?.sessionId),
1331+
);
1332+
const commandModel = `tui-pty-mock/${GATEWAY_SCENARIOS.command.modelId}`;
1333+
const commandModelOffset = fixture.run.visibleOutput().length;
1334+
await fixture.run.write(`/model ${commandModel}\r`, { delay: false });
1335+
await waitForOutputAfter(fixture.run, `model set to ${commandModel}`, commandModelOffset);
1336+
await waitForHistoryMessages(
1337+
controlClient,
1338+
createdKey!,
1339+
({ sessionInfo }) =>
1340+
sessionInfo?.sessionId === created.sessionInfo?.sessionId &&
1341+
[sessionInfo?.modelProvider, sessionInfo?.model].join("/") === commandModel,
1342+
);
1343+
const resetMarker = "T02_RESET_HISTORY";
1344+
const seedReply = GATEWAY_SCENARIOS.command.replyText;
1345+
await fixture.run.write(`${resetMarker}\r`, { delay: false });
1346+
await fixture.waitForOutput(seedReply);
1347+
const seeded = await waitForHistoryMessages(
1348+
controlClient,
1349+
createdKey!,
1350+
({ messages, sessionInfo }) =>
1351+
Boolean(
1352+
sessionInfo?.activeLeafEntryId &&
1353+
sessionInfo?.sessionId === created.sessionInfo?.sessionId &&
1354+
typeof sessionInfo?.updatedAt === "number" &&
1355+
[sessionInfo?.modelProvider, sessionInfo?.model].join("/") === commandModel &&
1356+
hasOrderedTurn(messages, resetMarker, seedReply),
1357+
),
1358+
);
1359+
const seededInfo = seeded.sessionInfo!;
1360+
const alternateModel = `tui-pty-mock/${GATEWAY_SCENARIOS.reconnect.modelId}`;
1361+
const modelOffset = fixture.run.visibleOutput().length;
1362+
await fixture.run.write(`/model ${alternateModel}\r`, { delay: false });
1363+
await waitForOutputAfter(fixture.run, `model set to ${alternateModel}`, modelOffset);
1364+
const selected = await waitForHistoryMessages(
1365+
controlClient,
1366+
createdKey!,
1367+
({ sessionInfo }) =>
1368+
sessionInfo?.sessionId === seededInfo.sessionId &&
1369+
typeof sessionInfo?.updatedAt === "number" &&
1370+
(sessionInfo?.updatedAt as number) >= (seededInfo.updatedAt as number) &&
1371+
Boolean(sessionInfo?.activeLeafEntryId) &&
1372+
[sessionInfo?.modelProvider, sessionInfo?.model].join("/") === alternateModel,
1373+
);
1374+
const selectedInfo = selected.sessionInfo!;
1375+
await fixture.run.write("/reset\r", { delay: false });
1376+
await fixture.waitForOutput(`session ${createdKey} reset`);
1377+
const reset = await waitForHistoryMessages(
1378+
controlClient,
1379+
createdKey!,
1380+
({ messages, sessionInfo }) =>
1381+
sessionInfo?.sessionId === selectedInfo.sessionId &&
1382+
typeof sessionInfo?.updatedAt === "number" &&
1383+
(sessionInfo?.updatedAt as number) >= (selectedInfo.updatedAt as number) &&
1384+
Boolean(sessionInfo?.activeLeafEntryId) &&
1385+
sessionInfo?.activeLeafEntryId !== selectedInfo.activeLeafEntryId &&
1386+
[sessionInfo?.modelProvider, sessionInfo?.model].join("/") === alternateModel &&
1387+
hasOrderedTurn(messages, resetMarker, seedReply),
1388+
);
1389+
const postMarker = "T02_POST_RESET";
1390+
const postOffset = fixture.run.visibleOutput().length;
1391+
await fixture.run.write(`${postMarker}\r`, { delay: false });
1392+
await waitForOutputAfter(fixture.run, GATEWAY_SCENARIOS.reconnect.replyText, postOffset);
1393+
await waitForHistoryMessages(controlClient, createdKey!, ({ messages, sessionInfo }) => {
1394+
const serialized = JSON.stringify(messages);
1395+
return (
1396+
Boolean(sessionInfo?.activeLeafEntryId) &&
1397+
sessionInfo?.sessionId === selectedInfo.sessionId &&
1398+
typeof sessionInfo?.updatedAt === "number" &&
1399+
(sessionInfo?.updatedAt as number) >= (reset.sessionInfo?.updatedAt as number) &&
1400+
sessionInfo?.activeLeafEntryId !== reset.sessionInfo?.activeLeafEntryId &&
1401+
[sessionInfo?.modelProvider, sessionInfo?.model].join("/") === alternateModel &&
1402+
hasOrderedTurn(messages, resetMarker, seedReply) &&
1403+
serialized.indexOf(postMarker) > serialized.indexOf(seedReply) &&
1404+
hasOrderedTurn(messages, postMarker, GATEWAY_SCENARIOS.reconnect.replyText)
1405+
);
1406+
});
1407+
} finally {
1408+
await fixture.cleanup();
1409+
}
1410+
},
1411+
LOCAL_TEST_TIMEOUT_MS,
1412+
);
11491413
registerGatewayTest(
11501414
"preserves a disconnected draft across a real Gateway restart",
11511415
async ({ onTestFinished }) => {

0 commit comments

Comments
 (0)