Skip to content

Commit 1520b83

Browse files
authored
test(qa): prove gateway chat RPCs (#118988)
1 parent 0dc9970 commit 1520b83

2 files changed

Lines changed: 261 additions & 0 deletions

File tree

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
title: Gateway chat RPC lifecycle
2+
3+
scenario:
4+
id: gateway-rpc-chat
5+
surface: gateway
6+
category: gateway.gateway-rpc-apis-and-events
7+
coverage:
8+
primary:
9+
- gateway.chat-apis
10+
objective: Verify the Gateway chat RPC lifecycle through a real WebSocket while only the downstream model provider is mocked.
11+
successCriteria:
12+
- "chat.send accepts a user turn and returns its run identifier."
13+
- "agent.wait observes the same run reaching terminal success."
14+
- "chat.history returns the persisted user turn and downstream assistant reply."
15+
docsRefs:
16+
- docs/gateway/protocol.md
17+
- docs/concepts/qa-e2e-automation.md
18+
codeRefs:
19+
- src/gateway/server-methods/chat.ts
20+
- src/gateway/server-methods/agent.ts
21+
- test/e2e/qa-lab/runtime/gateway-rpc-chat.e2e.test.ts
22+
execution:
23+
kind: vitest
24+
path: test/e2e/qa-lab/runtime/gateway-rpc-chat.e2e.test.ts
25+
summary: Run chat.send, agent.wait, and chat.history across a real Gateway WebSocket with deterministic downstream model output.
Lines changed: 236 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,236 @@
1+
import { randomUUID } from "node:crypto";
2+
import { setTimeout as sleep } from "node:timers/promises";
3+
import { afterEach, describe, expect, it, vi } from "vitest";
4+
import { startQaLiveLaneGateway } from "../../../../extensions/qa-lab/runtime-api.js";
5+
6+
type GatewayChatMessage = {
7+
role?: unknown;
8+
content?: unknown;
9+
text?: unknown;
10+
};
11+
12+
type GatewayChatHistory = {
13+
messages?: GatewayChatMessage[];
14+
};
15+
16+
type GatewayChatRun = {
17+
runId?: unknown;
18+
status?: unknown;
19+
};
20+
21+
type GatewayHandle = Awaited<ReturnType<typeof startQaLiveLaneGateway>>["gateway"];
22+
23+
const HISTORY_RETRY_TIMEOUT_MS = 10_000;
24+
const HISTORY_RETRY_DEFAULT_MS = 250;
25+
const HISTORY_RETRY_MIN_MS = 100;
26+
const HISTORY_RETRY_MAX_MS = 5_000;
27+
28+
let harness: Awaited<ReturnType<typeof startQaLiveLaneGateway>> | undefined;
29+
30+
afterEach(async () => {
31+
await harness?.stop().catch(() => undefined);
32+
harness = undefined;
33+
});
34+
35+
function messageContains(message: GatewayChatMessage, expected: string): boolean {
36+
return JSON.stringify(message).includes(expected);
37+
}
38+
39+
function historyContainsExpectedTurns(
40+
history: GatewayChatHistory,
41+
expectedUser: string,
42+
expectedAssistant: string,
43+
): boolean {
44+
const messages = history.messages ?? [];
45+
return (
46+
messages.some((message) => message.role === "user" && messageContains(message, expectedUser)) &&
47+
messages.some(
48+
(message) => message.role === "assistant" && messageContains(message, expectedAssistant),
49+
)
50+
);
51+
}
52+
53+
// Transcript projection rebuilds can briefly reject chat.history. Retry only
54+
// that structured protocol response; every other failure remains immediate.
55+
function resolveRetryableHistoryDelayMs(error: unknown): number | null {
56+
let current = error;
57+
for (let depth = 0; depth < 4; depth += 1) {
58+
if (typeof current !== "object" || current === null || Array.isArray(current)) {
59+
break;
60+
}
61+
const shaped = current as {
62+
cause?: unknown;
63+
code?: unknown;
64+
details?: unknown;
65+
gatewayCode?: unknown;
66+
retryable?: unknown;
67+
retryAfterMs?: unknown;
68+
};
69+
const code = shaped.gatewayCode ?? shaped.code;
70+
if (code === "UNAVAILABLE" && shaped.retryable === true) {
71+
const detailMethod =
72+
typeof shaped.details === "object" && shaped.details !== null
73+
? (shaped.details as { method?: unknown }).method
74+
: undefined;
75+
if (typeof detailMethod !== "string" || detailMethod === "chat.history") {
76+
const rawDelayMs =
77+
typeof shaped.retryAfterMs === "number" && Number.isFinite(shaped.retryAfterMs)
78+
? shaped.retryAfterMs
79+
: HISTORY_RETRY_DEFAULT_MS;
80+
return Math.min(
81+
Math.max(Math.floor(rawDelayMs), HISTORY_RETRY_MIN_MS),
82+
HISTORY_RETRY_MAX_MS,
83+
);
84+
}
85+
}
86+
current = shaped.cause;
87+
}
88+
return null;
89+
}
90+
91+
async function waitForChatHistory(params: {
92+
gateway: GatewayHandle;
93+
sessionKey: string;
94+
expectedUser: string;
95+
expectedAssistant: string;
96+
timeoutMs?: number;
97+
intervalMs?: number;
98+
}): Promise<GatewayChatHistory> {
99+
const timeoutMs = params.timeoutMs ?? HISTORY_RETRY_TIMEOUT_MS;
100+
const intervalMs = params.intervalMs ?? HISTORY_RETRY_DEFAULT_MS;
101+
const startedAt = Date.now();
102+
let lastRetryableHistoryError: unknown;
103+
while (Date.now() - startedAt < timeoutMs) {
104+
let delayMs = intervalMs;
105+
try {
106+
const history = (await params.gateway.call(
107+
"chat.history",
108+
{ sessionKey: params.sessionKey, limit: 20 },
109+
{ timeoutMs: 10_000 },
110+
)) as GatewayChatHistory;
111+
lastRetryableHistoryError = undefined;
112+
if (historyContainsExpectedTurns(history, params.expectedUser, params.expectedAssistant)) {
113+
return history;
114+
}
115+
} catch (error) {
116+
const retryDelayMs = resolveRetryableHistoryDelayMs(error);
117+
if (retryDelayMs === null) {
118+
throw error;
119+
}
120+
lastRetryableHistoryError = error;
121+
delayMs = retryDelayMs;
122+
}
123+
const remainingMs = timeoutMs - (Date.now() - startedAt);
124+
if (remainingMs <= 0) {
125+
break;
126+
}
127+
await sleep(Math.min(delayMs, remainingMs));
128+
}
129+
const message = `timed out waiting for complete chat.history after ${timeoutMs}ms`;
130+
throw lastRetryableHistoryError === undefined
131+
? new Error(message)
132+
: new Error(message, { cause: lastRetryableHistoryError });
133+
}
134+
135+
describe("Gateway chat RPCs", () => {
136+
it("waits past a successful incomplete chat.history response", async () => {
137+
vi.useFakeTimers();
138+
try {
139+
const call = vi
140+
.fn()
141+
.mockResolvedValueOnce({
142+
messages: [
143+
{ role: "user", content: "expected user" },
144+
{ role: "assistant", content: "still working" },
145+
],
146+
})
147+
.mockResolvedValueOnce({
148+
messages: [
149+
{ role: "user", content: "expected user" },
150+
{ role: "assistant", content: "expected assistant" },
151+
],
152+
});
153+
const pending = waitForChatHistory({
154+
gateway: { call } as unknown as GatewayHandle,
155+
sessionKey: "session-history-projection",
156+
expectedUser: "expected user",
157+
expectedAssistant: "expected assistant",
158+
timeoutMs: 1_000,
159+
intervalMs: 100,
160+
});
161+
162+
await vi.advanceTimersByTimeAsync(100);
163+
164+
await expect(pending).resolves.toMatchObject({
165+
messages: [{ role: "user" }, { role: "assistant" }],
166+
});
167+
expect(call).toHaveBeenCalledTimes(2);
168+
} finally {
169+
vi.useRealTimers();
170+
}
171+
});
172+
173+
it(
174+
"runs chat.send through agent.wait and persists both sides in chat.history",
175+
{ timeout: 120_000 },
176+
async () => {
177+
harness = await startQaLiveLaneGateway({
178+
repoRoot: process.cwd(),
179+
providerMode: "mock-openai",
180+
primaryModel: "mock-openai/gpt-5.6-luna",
181+
alternateModel: "mock-openai/gpt-5.6-luna-alt",
182+
transport: {
183+
requiredPluginIds: [],
184+
createGatewayConfig: () => ({}),
185+
},
186+
transportBaseUrl: "http://127.0.0.1",
187+
controlUiEnabled: false,
188+
});
189+
const { gateway } = harness;
190+
191+
const expectedReply = "GATEWAY_RPC_CHAT_OK";
192+
const prompt = `Gateway chat RPC QA. Reply exactly \`${expectedReply}\`.`;
193+
const sessionKey = `agent:qa:gateway-rpc-chat-${randomUUID()}`;
194+
const started = (await gateway.call(
195+
"chat.send",
196+
{
197+
sessionKey,
198+
message: prompt,
199+
deliver: false,
200+
idempotencyKey: randomUUID(),
201+
},
202+
{ timeoutMs: 30_000 },
203+
)) as GatewayChatRun;
204+
205+
expect(started.status).toBe("started");
206+
expect(typeof started.runId).toBe("string");
207+
208+
const terminal = (await gateway.call(
209+
"agent.wait",
210+
{
211+
runId: started.runId,
212+
timeoutMs: 30_000,
213+
},
214+
{ timeoutMs: 35_000 },
215+
)) as GatewayChatRun;
216+
expect(terminal.status).toBe("ok");
217+
218+
const history = await waitForChatHistory({
219+
gateway,
220+
sessionKey,
221+
expectedUser: prompt,
222+
expectedAssistant: expectedReply,
223+
});
224+
const messages = history.messages ?? [];
225+
226+
expect(
227+
messages.some((message) => message.role === "user" && messageContains(message, prompt)),
228+
).toBe(true);
229+
expect(
230+
messages.some(
231+
(message) => message.role === "assistant" && messageContains(message, expectedReply),
232+
),
233+
).toBe(true);
234+
},
235+
);
236+
});

0 commit comments

Comments
 (0)