Skip to content

Commit 317320a

Browse files
authored
test(gateway): add HTTP API QA coverage (#118809)
1 parent 02885d6 commit 317320a

2 files changed

Lines changed: 310 additions & 0 deletions

File tree

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
title: Gateway HTTP APIs
2+
3+
scenario:
4+
id: gateway-http-apis
5+
surface: runtime
6+
coverage:
7+
primary:
8+
- gateway.openai-compatible-apis
9+
- gateway.tool-invocation-api
10+
- gateway.hook-ingress
11+
objective: Verify the Gateway's public HTTP boundaries over real TCP with deterministic agent, embedding, tool, and hook outcomes.
12+
successCriteria:
13+
- The models, chat completions, responses, and embeddings routes return deterministic OpenAI-compatible results, including agent dispatch and a real local embedding provider fixture.
14+
- The tool invocation route executes the real agents_list tool and rejects a malformed request.
15+
- Hook ingress rejects a missing token without side effects and records an authenticated wake as a real system event.
16+
docsRefs:
17+
- docs/gateway/openai-http-api.md
18+
- docs/gateway/openresponses-http-api.md
19+
- docs/gateway/tools-invoke-http-api.md
20+
- docs/automation/webhook.md
21+
codeRefs:
22+
- src/gateway/models-http.ts
23+
- src/gateway/openai-http.ts
24+
- src/gateway/openresponses-http.ts
25+
- src/gateway/embeddings-http.ts
26+
- src/gateway/tools-invoke-http.ts
27+
- src/gateway/server/hooks.ts
28+
- test/e2e/qa-lab/runtime/gateway-http-apis.e2e.test.ts
29+
execution:
30+
kind: vitest
31+
path: test/e2e/qa-lab/runtime/gateway-http-apis.e2e.test.ts
32+
summary: Starts the full Gateway and proves its OpenAI-compatible, tool invocation, and hook ingress HTTP APIs over real TCP.
Lines changed: 278 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,278 @@
1+
// QA Lab product proof for the Gateway's public HTTP API boundaries.
2+
import fs from "node:fs/promises";
3+
import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
4+
import type { AddressInfo } from "node:net";
5+
import path from "node:path";
6+
import { describe, expect, it } from "vitest";
7+
import { createConfigIO, resetConfigRuntimeState } from "../../../../src/config/config.js";
8+
import { resolveMainSessionKeyFromConfig } from "../../../../src/config/sessions.js";
9+
import {
10+
agentCommand,
11+
getFreePort,
12+
installGatewayTestHooks,
13+
startGatewayServer,
14+
testState,
15+
} from "../../../../src/gateway/test-helpers.js";
16+
import { peekSystemEventEntries } from "../../../../src/infra/system-events.js";
17+
18+
installGatewayTestHooks();
19+
20+
const GATEWAY_TOKEN = "qa-gateway-token";
21+
const HOOK_TOKEN = "qa-hook-token";
22+
const JSON_HEADERS = {
23+
authorization: `Bearer ${GATEWAY_TOKEN}`,
24+
"content-type": "application/json",
25+
};
26+
27+
type JsonRecord = Record<string, unknown>;
28+
29+
async function readJsonBody(req: IncomingMessage): Promise<JsonRecord> {
30+
const chunks: Buffer[] = [];
31+
for await (const chunk of req) {
32+
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
33+
}
34+
return JSON.parse(Buffer.concat(chunks).toString("utf8")) as JsonRecord;
35+
}
36+
37+
async function startEmbeddingFixture() {
38+
const requests: JsonRecord[] = [];
39+
const server = createServer((req: IncomingMessage, res: ServerResponse) => {
40+
void (async () => {
41+
const body = await readJsonBody(req);
42+
requests.push({ method: req.method, url: req.url, body });
43+
const input = Array.isArray(body.input) ? body.input : [body.input];
44+
res.writeHead(200, { "content-type": "application/json" });
45+
res.end(
46+
JSON.stringify({
47+
object: "list",
48+
data: input.map((_text, index) => ({
49+
object: "embedding",
50+
embedding: [index + 0.25, index + 0.5],
51+
index,
52+
})),
53+
model: body.model,
54+
}),
55+
);
56+
})().catch((error: unknown) => {
57+
res.writeHead(500, { "content-type": "application/json" });
58+
res.end(JSON.stringify({ error: error instanceof Error ? error.message : String(error) }));
59+
});
60+
});
61+
62+
await new Promise<void>((resolve, reject) => {
63+
server.once("error", reject);
64+
server.listen(0, "127.0.0.1", () => {
65+
server.off("error", reject);
66+
resolve();
67+
});
68+
});
69+
70+
const address = server.address() as AddressInfo;
71+
return {
72+
baseUrl: `http://127.0.0.1:${address.port}/v1`,
73+
requests,
74+
close: () =>
75+
new Promise<void>((resolve, reject) => {
76+
server.close((error) => (error ? reject(error) : resolve()));
77+
}),
78+
};
79+
}
80+
81+
async function fetchJson(port: number, pathname: string, init?: RequestInit) {
82+
const response = await fetch(`http://127.0.0.1:${port}${pathname}`, init);
83+
return { response, body: (await response.json()) as JsonRecord };
84+
}
85+
86+
describe("Gateway HTTP API product proof", () => {
87+
it("serves OpenAI-compatible, tool invocation, and hook ingress APIs over TCP", async () => {
88+
const embeddingFixture = await startEmbeddingFixture();
89+
let gateway: Awaited<ReturnType<typeof startGatewayServer>> | undefined;
90+
91+
try {
92+
const configPath = createConfigIO().configPath;
93+
await fs.mkdir(path.dirname(configPath), { recursive: true });
94+
await fs.writeFile(
95+
configPath,
96+
`${JSON.stringify(
97+
{
98+
memory: {
99+
search: {
100+
provider: "openai-compatible",
101+
model: "qa-embedding",
102+
documentInputType: "document",
103+
remote: { baseUrl: embeddingFixture.baseUrl },
104+
},
105+
},
106+
},
107+
null,
108+
2,
109+
)}\n`,
110+
"utf8",
111+
);
112+
resetConfigRuntimeState();
113+
114+
testState.agentsConfig = {
115+
entries: {
116+
main: { default: true, tools: { allow: ["agents_list"] } },
117+
beta: {},
118+
},
119+
};
120+
testState.hooksConfig = { enabled: true, token: HOOK_TOKEN };
121+
agentCommand
122+
.mockResolvedValueOnce({ payloads: [{ text: "qa chat response" }] } as never)
123+
.mockResolvedValueOnce({ payloads: [{ text: "qa responses response" }] } as never);
124+
125+
const port = await getFreePort();
126+
gateway = await startGatewayServer(port, {
127+
host: "127.0.0.1",
128+
auth: { mode: "token", token: GATEWAY_TOKEN },
129+
controlUiEnabled: false,
130+
openAiChatCompletionsEnabled: true,
131+
openResponsesEnabled: true,
132+
});
133+
134+
const models = await fetchJson(port, "/v1/models", { headers: JSON_HEADERS });
135+
expect(models.response.status).toBe(200);
136+
expect(models.body.object).toBe("list");
137+
expect((models.body.data as Array<{ id?: string }>).map((model) => model.id)).toEqual(
138+
expect.arrayContaining(["openclaw/main", "openclaw/beta"]),
139+
);
140+
141+
const chat = await fetchJson(port, "/v1/chat/completions", {
142+
method: "POST",
143+
headers: JSON_HEADERS,
144+
body: JSON.stringify({
145+
model: "openclaw/main",
146+
stream: false,
147+
messages: [{ role: "user", content: "qa chat request" }],
148+
}),
149+
});
150+
expect(chat.response.status).toBe(200);
151+
expect(
152+
(
153+
chat.body.choices as Array<{
154+
message?: { content?: string };
155+
}>
156+
)[0]?.message?.content,
157+
).toBe("qa chat response");
158+
159+
const responses = await fetchJson(port, "/v1/responses", {
160+
method: "POST",
161+
headers: JSON_HEADERS,
162+
body: JSON.stringify({
163+
model: "openclaw/main",
164+
stream: false,
165+
input: "qa responses request",
166+
}),
167+
});
168+
expect(responses.response.status).toBe(200);
169+
expect(responses.body.status).toBe("completed");
170+
const output = responses.body.output as Array<{
171+
content?: Array<{ type?: string; text?: string }>;
172+
}>;
173+
expect(output[0]?.content?.[0]).toEqual({
174+
type: "output_text",
175+
text: "qa responses response",
176+
});
177+
expect(agentCommand).toHaveBeenCalledTimes(2);
178+
expect(agentCommand.mock.calls.map((call) => call[0])).toEqual([
179+
expect.objectContaining({
180+
message: "qa chat request",
181+
sessionKey: expect.stringMatching(/^agent:main:openai:/),
182+
}),
183+
expect.objectContaining({
184+
message: "qa responses request",
185+
sessionKey: expect.stringMatching(/^agent:main:openresponses:/),
186+
}),
187+
]);
188+
189+
const embeddings = await fetchJson(port, "/v1/embeddings", {
190+
method: "POST",
191+
headers: JSON_HEADERS,
192+
body: JSON.stringify({
193+
model: "openclaw/main",
194+
input: ["alpha", "beta"],
195+
}),
196+
});
197+
expect(embeddings.response.status).toBe(200);
198+
expect(embeddings.body.data).toEqual([
199+
expect.objectContaining({ index: 0, embedding: [0.25, 0.5] }),
200+
expect.objectContaining({ index: 1, embedding: [1.25, 1.5] }),
201+
]);
202+
expect(embeddingFixture.requests).toEqual([
203+
expect.objectContaining({
204+
method: "POST",
205+
url: "/v1/embeddings",
206+
body: expect.objectContaining({
207+
model: "qa-embedding",
208+
input: ["alpha", "beta"],
209+
input_type: "document",
210+
}),
211+
}),
212+
]);
213+
214+
const tool = await fetchJson(port, "/tools/invoke", {
215+
method: "POST",
216+
headers: JSON_HEADERS,
217+
body: JSON.stringify({
218+
tool: "agents_list",
219+
action: "json",
220+
args: {},
221+
sessionKey: "main",
222+
}),
223+
});
224+
expect(tool.response.status).toBe(200);
225+
expect(tool.body.ok).toBe(true);
226+
expect(tool.body.result).toEqual(
227+
expect.objectContaining({
228+
details: expect.objectContaining({
229+
requester: "main",
230+
allowAny: false,
231+
agents: [expect.objectContaining({ id: "main", configured: true })],
232+
}),
233+
}),
234+
);
235+
236+
const malformedTool = await fetchJson(port, "/tools/invoke", {
237+
method: "POST",
238+
headers: JSON_HEADERS,
239+
body: "{}",
240+
});
241+
expect(malformedTool.response.status).toBe(400);
242+
expect(malformedTool.body).toEqual({
243+
ok: false,
244+
error: {
245+
type: "invalid_request",
246+
message: "tools.invoke requires name",
247+
},
248+
});
249+
250+
const mainSessionKey = resolveMainSessionKeyFromConfig();
251+
const unauthenticatedWake = await fetch(`http://127.0.0.1:${port}/hooks/wake`, {
252+
method: "POST",
253+
headers: { "content-type": "application/json" },
254+
body: JSON.stringify({ text: "must not queue", mode: "next-heartbeat" }),
255+
});
256+
expect(unauthenticatedWake.status).toBe(401);
257+
expect(await unauthenticatedWake.text()).toBe("Unauthorized");
258+
expect(peekSystemEventEntries(mainSessionKey)).toHaveLength(0);
259+
260+
const authenticatedWake = await fetchJson(port, "/hooks/wake", {
261+
method: "POST",
262+
headers: {
263+
authorization: `Bearer ${HOOK_TOKEN}`,
264+
"content-type": "application/json",
265+
},
266+
body: JSON.stringify({ text: "Gateway HTTP QA wake", mode: "next-heartbeat" }),
267+
});
268+
expect(authenticatedWake.response.status).toBe(200);
269+
expect(authenticatedWake.body).toEqual({ ok: true, mode: "next-heartbeat" });
270+
expect(peekSystemEventEntries(mainSessionKey).map((event) => event.text)).toEqual([
271+
"Gateway HTTP QA wake",
272+
]);
273+
} finally {
274+
await gateway?.close({ reason: "Gateway HTTP API QA proof complete" });
275+
await embeddingFixture.close();
276+
}
277+
}, 60_000);
278+
});

0 commit comments

Comments
 (0)