Skip to content

Commit 5a65c96

Browse files
authored
test(tui): route PTY gateway scenarios through explicit models (#118802)
1 parent 592dbf7 commit 5a65c96

1 file changed

Lines changed: 35 additions & 41 deletions

File tree

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

Lines changed: 35 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ import { sleep, startPty, waitFor, type PtyRun } from "./tui-pty-test-support.js
2525
type MockModelServer = {
2626
baseUrl: string;
2727
requests: (modelId?: string) => MockModelRequest[];
28+
rejectedRequests: () => MockModelRequest[];
2829
releaseFirstResponse: (modelId: string) => void;
2930
stop: () => Promise<void>;
3031
};
@@ -45,18 +46,15 @@ type MockModelRequest = {
4546
type GatewayScenario = MockModelBehavior & {
4647
agentId: string;
4748
modelId: string;
48-
routeMarker: string;
4949
toolsProfile: "minimal" | "coding";
5050
};
5151

5252
const SHARED_GATEWAY_AGENT_ID = "tui-pty-gateway";
53-
const SHARED_GATEWAY_MODEL_ID = "tui-pty-gateway";
5453

5554
const GATEWAY_SCENARIOS = {
5655
validation: {
5756
agentId: "tui-pty-validation",
5857
modelId: "tui-pty-validation",
59-
routeMarker: "trigger malformed edit calls",
6058
toolsProfile: "coding",
6159
replyText: "FIRST_RUN_ACTIVE",
6260
holdFirstResponse: false,
@@ -66,7 +64,6 @@ const GATEWAY_SCENARIOS = {
6664
crossClient: {
6765
agentId: SHARED_GATEWAY_AGENT_ID,
6866
modelId: "tui-pty-cross-client",
69-
routeMarker: "seed cross-client session",
7067
toolsProfile: "minimal",
7168
replyText: "FIRST_RUN_ACTIVE",
7269
holdFirstResponse: false,
@@ -75,7 +72,6 @@ const GATEWAY_SCENARIOS = {
7572
followup: {
7673
agentId: SHARED_GATEWAY_AGENT_ID,
7774
modelId: "tui-pty-followup",
78-
routeMarker: "slow first turn",
7975
toolsProfile: "minimal",
8076
replyText: "FIRST_RUN_ACTIVE",
8177
holdFirstResponse: true,
@@ -84,7 +80,6 @@ const GATEWAY_SCENARIOS = {
8480
emptyReply: {
8581
agentId: SHARED_GATEWAY_AGENT_ID,
8682
modelId: "tui-pty-empty-reply",
87-
routeMarker: "non-deliverable first turn",
8883
toolsProfile: "minimal",
8984
replyText: "[[reply_to_current]]",
9085
holdFirstResponse: false,
@@ -93,7 +88,6 @@ const GATEWAY_SCENARIOS = {
9388
cancel: {
9489
agentId: SHARED_GATEWAY_AGENT_ID,
9590
modelId: "tui-pty-cancel",
96-
routeMarker: "slow turn to abort",
9791
toolsProfile: "minimal",
9892
replyText: "FIRST_RUN_ACTIVE",
9993
holdFirstResponse: true,
@@ -102,7 +96,6 @@ const GATEWAY_SCENARIOS = {
10296
collect: {
10397
agentId: SHARED_GATEWAY_AGENT_ID,
10498
modelId: "tui-pty-collect",
105-
routeMarker: "slow collect parent",
10699
toolsProfile: "minimal",
107100
replyText: "FIRST_RUN_ACTIVE",
108101
holdFirstResponse: true,
@@ -111,7 +104,6 @@ const GATEWAY_SCENARIOS = {
111104
reconnect: {
112105
agentId: SHARED_GATEWAY_AGENT_ID,
113106
modelId: "tui-pty-reconnect",
114-
routeMarker: "send preserved draft after restart",
115107
toolsProfile: "minimal",
116108
replyText: "RECONNECTED_RUN_COMPLETE",
117109
},
@@ -289,12 +281,9 @@ async function readJsonRequest(req: IncomingMessage): Promise<Record<string, unk
289281

290282
async function startRoutedMockModelServer(
291283
behaviors: Readonly<Record<string, MockModelBehavior>>,
292-
opts: {
293-
advertisedModelIds?: string[];
294-
resolveBehaviorId?: (body: Record<string, unknown>, modelId: string) => string;
295-
} = {},
296284
): Promise<MockModelServer> {
297285
const requests: MockModelRequest[] = [];
286+
const rejectedRequests: MockModelRequest[] = [];
298287
const requestsByModel = new Map<string, MockModelRequest[]>();
299288
const firstResponseGates = new Map(
300289
Object.entries(behaviors)
@@ -310,7 +299,7 @@ async function startRoutedMockModelServer(
310299
}
311300
if (req.method === "GET" && url.pathname === "/v1/models") {
312301
writeJson(res, 200, {
313-
data: (opts.advertisedModelIds ?? Object.keys(behaviors)).map((id) => ({
302+
data: Object.keys(behaviors).map((id) => ({
314303
id,
315304
object: "model",
316305
})),
@@ -321,18 +310,18 @@ async function startRoutedMockModelServer(
321310
const body = await readJsonRequest(req);
322311
if (url.pathname === "/v1/responses" || url.pathname === "/responses") {
323312
const modelId = typeof body.model === "string" ? body.model : "";
324-
const behaviorId = opts.resolveBehaviorId?.(body, modelId) ?? modelId;
325-
const behavior = behaviors[behaviorId];
313+
const request = { method: req.method, path: url.pathname, body };
314+
const behavior = behaviors[modelId];
326315
if (!behavior) {
327-
writeJson(res, 400, { error: `unknown mock behavior: ${behaviorId || "missing"}` });
316+
rejectedRequests.push(request);
317+
writeJson(res, 400, { error: `unknown mock model: ${modelId || "missing"}` });
328318
return;
329319
}
330-
const modelRequests = requestsByModel.get(behaviorId) ?? [];
331-
if (!requestsByModel.has(behaviorId)) {
332-
requestsByModel.set(behaviorId, modelRequests);
320+
const modelRequests = requestsByModel.get(modelId) ?? [];
321+
if (!requestsByModel.has(modelId)) {
322+
requestsByModel.set(modelId, modelRequests);
333323
}
334324
const requestIndex = modelRequests.length;
335-
const request = { method: req.method, path: url.pathname, body };
336325
requests.push(request);
337326
modelRequests.push(request);
338327
if (behavior.invalidEditLoop) {
@@ -344,7 +333,7 @@ async function startRoutedMockModelServer(
344333
requestIndex === 0
345334
? behavior.replyText
346335
: (behavior.followupReplyText ?? behavior.replyText),
347-
requestIndex === 0 ? firstResponseGates.get(behaviorId)?.promise : undefined,
336+
requestIndex === 0 ? firstResponseGates.get(modelId)?.promise : undefined,
348337
);
349338
return;
350339
}
@@ -366,6 +355,7 @@ async function startRoutedMockModelServer(
366355
return {
367356
baseUrl: `http://127.0.0.1:${address.port}`,
368357
requests: (modelId) => (modelId ? (requestsByModel.get(modelId) ?? []) : requests),
358+
rejectedRequests: () => rejectedRequests,
369359
releaseFirstResponse: (modelId) => {
370360
firstResponseGates.get(modelId)?.resolve();
371361
},
@@ -614,7 +604,8 @@ function buildGatewayModeConfig(params: { tempDir: string; providerBaseUrl: stri
614604
...new Map(scenarios.map((scenario) => [scenario.agentId, scenario])).values(),
615605
];
616606
const defaultScenario = GATEWAY_SCENARIOS.validation;
617-
const defaultModelRef = `tui-pty-mock/${SHARED_GATEWAY_MODEL_ID}`;
607+
const defaultModelRef = `tui-pty-mock/${defaultScenario.modelId}`;
608+
const modelRefs = scenarios.map((scenario) => `tui-pty-mock/${scenario.modelId}`);
618609
const base = buildLocalModeConfig({
619610
workspaceDir: path.join(params.tempDir, defaultScenario.agentId),
620611
providerBaseUrl: params.providerBaseUrl,
@@ -625,7 +616,9 @@ function buildGatewayModeConfig(params: { tempDir: string; providerBaseUrl: stri
625616
defaults: {
626617
workspace: path.join(params.tempDir, defaultScenario.agentId),
627618
model: { primary: defaultModelRef },
628-
models: { [defaultModelRef]: { agentRuntime: { id: "openclaw" } } },
619+
models: Object.fromEntries(
620+
modelRefs.map((modelRef) => [modelRef, { agentRuntime: { id: "openclaw" } }]),
621+
),
629622
skills: [],
630623
skipBootstrap: true,
631624
},
@@ -636,7 +629,7 @@ function buildGatewayModeConfig(params: { tempDir: string; providerBaseUrl: stri
636629
...(index === 0 ? { default: true } : {}),
637630
workspace: path.join(params.tempDir, scenario.agentId),
638631
skills: [],
639-
model: { primary: defaultModelRef },
632+
model: { primary: `tui-pty-mock/${scenario.modelId}` },
640633
tools: { profile: scenario.toolsProfile },
641634
},
642635
]),
@@ -645,7 +638,10 @@ function buildGatewayModeConfig(params: { tempDir: string; providerBaseUrl: stri
645638
models: {
646639
mode: "replace",
647640
providers: {
648-
"tui-pty-mock": buildMockModelProvider(params.providerBaseUrl, [SHARED_GATEWAY_MODEL_ID]),
641+
"tui-pty-mock": buildMockModelProvider(
642+
params.providerBaseUrl,
643+
scenarios.map((scenario) => scenario.modelId),
644+
),
649645
},
650646
},
651647
messages: {
@@ -656,14 +652,6 @@ function buildGatewayModeConfig(params: { tempDir: string; providerBaseUrl: stri
656652
} satisfies OpenClawConfig;
657653
}
658654

659-
function resolveGatewayBehaviorId(body: Record<string, unknown>): string {
660-
const serialized = JSON.stringify(body);
661-
const match = Object.values(GATEWAY_SCENARIOS).find((scenario) =>
662-
serialized.includes(scenario.routeMarker),
663-
);
664-
return match?.modelId ?? "";
665-
}
666-
667655
async function startSharedGatewayFixture(): Promise<SharedGatewayFixture> {
668656
const tempDir = await mkdtemp(path.join(tmpdir(), "openclaw-tui-pty-gateway-"));
669657
let mockModel: MockModelServer | undefined;
@@ -689,10 +677,6 @@ async function startSharedGatewayFixture(): Promise<SharedGatewayFixture> {
689677
},
690678
]),
691679
),
692-
{
693-
advertisedModelIds: [SHARED_GATEWAY_MODEL_ID],
694-
resolveBehaviorId: (body) => resolveGatewayBehaviorId(body),
695-
},
696680
);
697681
gateway = await createOpenClawTestInstance({
698682
name: "tui-pty-shared-gateway",
@@ -817,13 +801,14 @@ async function startGatewayModeTui(
817801
const shared = await requireSharedGatewayFixture();
818802
const scenario = GATEWAY_SCENARIOS[scenarioId];
819803
const requestOffset = shared.mockModel.requests(scenario.modelId).length;
804+
const rejectedRequestOffset = shared.mockModel.rejectedRequests().length;
820805
const sessionKey = `agent:${scenario.agentId}:tui-pty-${++gatewaySessionSequence}`;
821806
const sessionKeys = new Set([sessionKey]);
822807
await shared.controlClient.createSession({ key: sessionKey, agentId: scenario.agentId });
823808
await shared.controlClient.patchSession({
824809
key: sessionKey,
825810
agentId: scenario.agentId,
826-
model: `tui-pty-mock/${SHARED_GATEWAY_MODEL_ID}`,
811+
model: `tui-pty-mock/${scenario.modelId}`,
827812
});
828813
const run = shared.run;
829814
const outputOffset = run.visibleOutput().length;
@@ -843,6 +828,7 @@ async function startGatewayModeTui(
843828
gateway: shared.gateway,
844829
mockModel: {
845830
requests: () => shared.mockModel.requests(scenario.modelId).slice(requestOffset),
831+
rejectedRequests: () => shared.mockModel.rejectedRequests().slice(rejectedRequestOffset),
846832
releaseFirstResponse: () => shared.mockModel.releaseFirstResponse(scenario.modelId),
847833
},
848834
agentId: scenario.agentId,
@@ -1002,7 +988,11 @@ describe("TUI PTY real backends", () => {
1002988
timeoutMs: LOCAL_OUTPUT_TIMEOUT_MS,
1003989
read: () => (fixture.mockModel.requests().length >= 2 ? true : null),
1004990
onTimeout: () =>
1005-
new Error(`model did not repeat the malformed edit call\n${fixture.run.output()}`),
991+
new Error(
992+
`model did not repeat the malformed edit call\n` +
993+
`rejected model requests=${JSON.stringify(fixture.mockModel.rejectedRequests())}\n` +
994+
fixture.run.output(),
995+
),
1006996
});
1007997
if (eventProbe) {
1008998
await waitFor({
@@ -1355,7 +1345,11 @@ describe("TUI PTY real backends", () => {
13551345
timeoutMs: LOCAL_OUTPUT_TIMEOUT_MS,
13561346
read: () => (fixture.mockModel.requests().length === 1 ? true : null),
13571347
onTimeout: () =>
1358-
new Error(`first prompt did not reach the model\n${fixture.run.output()}`),
1348+
new Error(
1349+
`first prompt did not reach the model\n` +
1350+
`rejected model requests=${JSON.stringify(fixture.mockModel.rejectedRequests())}\n` +
1351+
fixture.run.output(),
1352+
),
13591353
});
13601354
const alphaSend = queueClient.sendChat({
13611355
sessionKey: fixture.sessionKey,

0 commit comments

Comments
 (0)