Skip to content

Commit d90c4fd

Browse files
committed
test(qa): cover image generation task lifecycle
1 parent 7f9994d commit d90c4fd

3 files changed

Lines changed: 364 additions & 0 deletions

File tree

‎extensions/qa-lab/api.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ export {
4949
readQaAgentIdentityMarkdown,
5050
} from "./src/qa-agent-bootstrap.js";
5151
export { seedQaAgentWorkspace } from "./src/qa-agent-workspace.js";
52+
export { createQaChannelTransport } from "./src/qa-channel-transport.js";
5253
export {
5354
buildQaGatewayConfig,
5455
DEFAULT_QA_CONTROL_UI_ALLOWED_ORIGINS,
@@ -57,6 +58,11 @@ export {
5758
QA_BASE_RUNTIME_PLUGIN_IDS,
5859
type QaThinkingLevel,
5960
} from "./src/qa-gateway-config.js";
61+
export {
62+
TINY_PNG_BASE64,
63+
type MockOpenAiRequestSnapshot,
64+
} from "./src/providers/mock-openai/mock-openai-contracts.js";
65+
export { startQaMockOpenAiServer } from "./src/providers/mock-openai/server.js";
6066
export { renderQaMarkdownReport, type QaReportCheck, type QaReportScenario } from "./src/report.js";
6167
export {
6268
type QaScenarioDefinition,
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
title: Image generation task lifecycle
2+
3+
scenario:
4+
id: image-generation-lifecycle
5+
surface: image-generation
6+
coverage:
7+
primary:
8+
- media.generated-image-task-lifecycle
9+
objective: Verify one real QA-channel image request owns a stable asynchronous task across running, completion, cleanup, and recent-success duplicate guards.
10+
successCriteria:
11+
- The first image_generate request creates one running image-generation task with a stable task ID.
12+
- An exact duplicate while the task is running returns that task ID and does not make a second provider call.
13+
- The task completes through the generated-media wake path and delivers exactly one PNG outcome to QA-channel.
14+
- After completion cleanup, an exact duplicate resolves to the same recently succeeded task without another provider call.
15+
docsRefs:
16+
- docs/tools/image-generation.md
17+
- docs/channels/qa-channel.md
18+
codeRefs:
19+
- src/agents/tools/image-generate-tool.ts
20+
- src/agents/tools/media-generate-background-shared.ts
21+
- src/agents/image-generation-task-status.ts
22+
- test/e2e/qa-lab/media/image-generation-lifecycle.e2e.test.ts
23+
execution:
24+
kind: vitest
25+
path: test/e2e/qa-lab/media/image-generation-lifecycle.e2e.test.ts
26+
summary: Hold one deterministic image provider call while QA-channel verifies running and recently completed duplicate guards around one task and one delivery.
Lines changed: 332 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,332 @@
1+
import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
2+
import type { AddressInfo } from "node:net";
3+
import path from "node:path";
4+
import type { OpenClawConfig } from "openclaw/plugin-sdk/config-contracts";
5+
import { afterEach, describe, expect, it, vi } from "vitest";
6+
import {
7+
createQaBusState,
8+
createQaChannelTransport,
9+
startQaBusServer,
10+
startQaGatewayChild,
11+
startQaMockOpenAiServer,
12+
TINY_PNG_BASE64,
13+
type MockOpenAiRequestSnapshot,
14+
} from "../../../../extensions/qa-lab/api.js";
15+
16+
const REPO_ROOT = path.resolve(import.meta.dirname, "../../../..");
17+
const MODEL_REF = "mock-openai/gpt-5.6-luna";
18+
const IMAGE_MODEL_REF = "openai/gpt-image-1";
19+
const REQUEST_TEXT =
20+
"Image generation check IMAGE_TASK_LIFECYCLE: generate the QA lighthouse image.";
21+
const CONVERSATION = { id: "image-generation-lifecycle", kind: "direct" as const };
22+
23+
type GatewayTask = {
24+
id: string;
25+
kind?: string;
26+
sourceId?: string;
27+
status: string;
28+
progressSummary?: string;
29+
endedAt?: string | number;
30+
};
31+
32+
async function readRequestBody(request: IncomingMessage) {
33+
const chunks: Buffer[] = [];
34+
for await (const chunk of request) {
35+
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
36+
}
37+
return Buffer.concat(chunks).toString("utf8");
38+
}
39+
40+
function writeJson(response: ServerResponse, status: number, body: unknown) {
41+
response.writeHead(status, { "content-type": "application/json" });
42+
response.end(JSON.stringify(body));
43+
}
44+
45+
async function startControlledImageProvider() {
46+
const requests: Record<string, unknown>[] = [];
47+
const pendingResponses = new Set<ServerResponse>();
48+
let released = false;
49+
50+
const complete = (response: ServerResponse) => {
51+
pendingResponses.delete(response);
52+
writeJson(response, 200, {
53+
data: [
54+
{
55+
b64_json: TINY_PNG_BASE64,
56+
revised_prompt: "A QA lighthouse with a tiny protocol droid silhouette.",
57+
},
58+
],
59+
});
60+
};
61+
const server = createServer(async (request, response) => {
62+
if (request.method !== "POST" || request.url !== "/v1/images/generations") {
63+
writeJson(response, 404, { error: "not found" });
64+
return;
65+
}
66+
try {
67+
const body = JSON.parse(await readRequestBody(request)) as Record<string, unknown>;
68+
requests.push(body);
69+
if (released) {
70+
complete(response);
71+
return;
72+
}
73+
pendingResponses.add(response);
74+
} catch (error) {
75+
writeJson(response, 400, {
76+
error: error instanceof Error ? error.message : String(error),
77+
});
78+
}
79+
});
80+
await new Promise<void>((resolve, reject) => {
81+
server.once("error", reject);
82+
server.listen(0, "127.0.0.1", resolve);
83+
});
84+
const address = server.address() as AddressInfo;
85+
const release = () => {
86+
released = true;
87+
for (const response of [...pendingResponses]) {
88+
complete(response);
89+
}
90+
};
91+
92+
return {
93+
baseUrl: `http://127.0.0.1:${address.port}`,
94+
requests,
95+
release,
96+
async stop() {
97+
release();
98+
await new Promise<void>((resolve, reject) => {
99+
server.close((error) => (error ? reject(error) : resolve()));
100+
});
101+
},
102+
};
103+
}
104+
105+
function configureImageProvider(
106+
config: OpenClawConfig,
107+
imageProviderBaseUrl: string,
108+
): OpenClawConfig {
109+
const openAiProvider = config.models?.providers?.openai;
110+
if (!openAiProvider) {
111+
throw new Error("openai image provider is missing from QA gateway config");
112+
}
113+
return {
114+
...config,
115+
agents: {
116+
...config.agents,
117+
defaults: {
118+
...config.agents?.defaults,
119+
mediaModels: {
120+
...config.agents?.defaults?.mediaModels,
121+
image: { primary: IMAGE_MODEL_REF },
122+
},
123+
},
124+
},
125+
models: {
126+
...config.models,
127+
providers: {
128+
...config.models?.providers,
129+
openai: {
130+
...openAiProvider,
131+
baseUrl: `${imageProviderBaseUrl}/v1`,
132+
request: {
133+
...openAiProvider.request,
134+
allowPrivateNetwork: true,
135+
},
136+
},
137+
},
138+
},
139+
};
140+
}
141+
142+
async function readMockRequests(baseUrl: string): Promise<MockOpenAiRequestSnapshot[]> {
143+
const response = await fetch(`${baseUrl}/debug/requests`);
144+
if (!response.ok) {
145+
throw new Error(`mock request log failed with HTTP ${response.status}`);
146+
}
147+
return (await response.json()) as MockOpenAiRequestSnapshot[];
148+
}
149+
150+
async function waitForToolOutput(baseUrl: string, needle: string) {
151+
let matched: MockOpenAiRequestSnapshot | undefined;
152+
await vi.waitFor(
153+
async () => {
154+
matched = (await readMockRequests(baseUrl)).find(
155+
(request) =>
156+
request.allInputText.includes("IMAGE_TASK_LIFECYCLE") &&
157+
request.toolOutput.includes(needle),
158+
);
159+
expect(matched).toBeDefined();
160+
},
161+
{ interval: 50, timeout: 30_000 },
162+
);
163+
return matched as MockOpenAiRequestSnapshot;
164+
}
165+
166+
async function readImageTasks(
167+
gateway: Awaited<ReturnType<typeof startQaGatewayChild>>,
168+
): Promise<GatewayTask[]> {
169+
const payload = (await gateway.call("tasks.list", { limit: 100 })) as {
170+
tasks?: GatewayTask[];
171+
};
172+
return (payload.tasks ?? []).filter(
173+
(task) => task.kind === "image_generation" && task.sourceId === "image_generate:openai",
174+
);
175+
}
176+
177+
describe("image generation task lifecycle through QA-channel", () => {
178+
const cleanups: Array<() => Promise<void>> = [];
179+
180+
afterEach(async () => {
181+
const errors: unknown[] = [];
182+
for (const cleanup of cleanups.splice(0).toReversed()) {
183+
try {
184+
await cleanup();
185+
} catch (error) {
186+
errors.push(error);
187+
}
188+
}
189+
if (errors.length === 1) {
190+
throw errors[0];
191+
}
192+
if (errors.length > 1) {
193+
throw new AggregateError(errors, "image generation lifecycle cleanup failed");
194+
}
195+
});
196+
197+
it("deduplicates running and recently completed requests around one completion", async () => {
198+
const state = createQaBusState();
199+
const transport = createQaChannelTransport(state);
200+
const bus = await startQaBusServer({ state });
201+
cleanups.push(() => bus.stop());
202+
203+
const mock = await startQaMockOpenAiServer();
204+
cleanups.push(() => mock.stop());
205+
206+
const imageProvider = await startControlledImageProvider();
207+
cleanups.push(() => imageProvider.stop());
208+
209+
const gateway = await startQaGatewayChild({
210+
repoRoot: REPO_ROOT,
211+
useRepoCli: true,
212+
providerBaseUrl: `${mock.baseUrl}/v1`,
213+
providerMode: "mock-openai",
214+
primaryModel: MODEL_REF,
215+
alternateModel: MODEL_REF,
216+
transport,
217+
transportBaseUrl: bus.baseUrl,
218+
controlUiEnabled: false,
219+
mutateConfig: (config) => configureImageProvider(config, imageProvider.baseUrl),
220+
});
221+
cleanups.push(() => gateway.stop());
222+
await transport.waitReady({ gateway });
223+
224+
const sendExactRequest = () =>
225+
transport.sendInbound({
226+
accountId: "default",
227+
conversation: CONVERSATION,
228+
senderId: CONVERSATION.id,
229+
text: REQUEST_TEXT,
230+
});
231+
232+
await sendExactRequest();
233+
await vi.waitFor(() => expect(imageProvider.requests).toHaveLength(1), {
234+
interval: 50,
235+
timeout: 30_000,
236+
});
237+
238+
let runningTasks: GatewayTask[] = [];
239+
await vi.waitFor(
240+
async () => {
241+
runningTasks = await readImageTasks(gateway);
242+
expect(runningTasks).toHaveLength(1);
243+
expect(runningTasks[0]).toMatchObject({
244+
id: expect.any(String),
245+
status: "running",
246+
progressSummary: "Generating image",
247+
});
248+
},
249+
{ interval: 50, timeout: 30_000 },
250+
);
251+
const taskId = runningTasks[0]?.id;
252+
expect(taskId).toEqual(expect.any(String));
253+
254+
await sendExactRequest();
255+
const runningDuplicate = await waitForToolOutput(mock.baseUrl, "is already running");
256+
expect(runningDuplicate.toolOutput).toContain(taskId);
257+
expect(imageProvider.requests).toHaveLength(1);
258+
expect(await readImageTasks(gateway)).toEqual([
259+
expect.objectContaining({ id: taskId, status: "running" }),
260+
]);
261+
262+
imageProvider.release();
263+
await vi.waitFor(
264+
() => {
265+
const completions = state
266+
.getSnapshot()
267+
.messages.filter(
268+
(message) =>
269+
message.direction === "outbound" &&
270+
message.conversation.id === CONVERSATION.id &&
271+
message.attachments !== undefined &&
272+
message.attachments.some(
273+
(attachment) =>
274+
attachment.kind === "image" &&
275+
attachment.mimeType === "image/png" &&
276+
attachment.contentBase64 === TINY_PNG_BASE64,
277+
),
278+
);
279+
expect(completions).toHaveLength(1);
280+
},
281+
{ interval: 50, timeout: 90_000 },
282+
);
283+
284+
let completedTasks: GatewayTask[] = [];
285+
await vi.waitFor(
286+
async () => {
287+
completedTasks = await readImageTasks(gateway);
288+
expect(completedTasks).toEqual([
289+
expect.objectContaining({
290+
id: taskId,
291+
status: "completed",
292+
progressSummary: "Generated 1 image",
293+
endedAt: expect.anything(),
294+
}),
295+
]);
296+
},
297+
{ interval: 50, timeout: 30_000 },
298+
);
299+
300+
await sendExactRequest();
301+
const completedDuplicate = await waitForToolOutput(mock.baseUrl, "recently succeeded");
302+
expect(completedDuplicate.toolOutput).toContain(taskId);
303+
304+
const plannedCalls = (await readMockRequests(mock.baseUrl)).filter(
305+
(request) =>
306+
request.allInputText.includes("IMAGE_TASK_LIFECYCLE") &&
307+
request.plannedToolName === "image_generate",
308+
);
309+
expect(plannedCalls).toHaveLength(3);
310+
expect(plannedCalls.map((request) => request.plannedToolArgs)).toEqual([
311+
plannedCalls[0]?.plannedToolArgs,
312+
plannedCalls[0]?.plannedToolArgs,
313+
plannedCalls[0]?.plannedToolArgs,
314+
]);
315+
expect(imageProvider.requests).toHaveLength(1);
316+
expect(await readImageTasks(gateway)).toEqual([
317+
expect.objectContaining({ id: taskId, status: "completed" }),
318+
]);
319+
320+
await new Promise((resolve) => setTimeout(resolve, 500));
321+
const completionOutcomes = state
322+
.getSnapshot()
323+
.messages.filter(
324+
(message) =>
325+
message.direction === "outbound" &&
326+
message.conversation.id === CONVERSATION.id &&
327+
message.attachments !== undefined &&
328+
message.attachments.some((attachment) => attachment.kind === "image"),
329+
);
330+
expect(completionOutcomes).toHaveLength(1);
331+
}, 180_000);
332+
});

0 commit comments

Comments
 (0)