Skip to content

Commit 958c34e

Browse files
authored
feat(qa-lab): Add proxy capture stack and QA Lab inspector (#64895)
* Add proxy capture core and CLI * Expand transport capture coverage * Add QA Lab capture backend * Refine QA Lab capture UI * Fix proxy capture review feedback * Fix proxy run cleanup and TTS capture * Fix proxy capture transport follow-ups * Fix debug proxy CONNECT target parsing * Harden QA Lab asset path containment
1 parent f04e045 commit 958c34e

48 files changed

Lines changed: 8566 additions & 119 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎extensions/discord/src/monitor/gateway-plugin.ts‎

Lines changed: 79 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,15 @@
11
import * as carbonGateway from "@buape/carbon/gateway";
2+
import { randomUUID } from "node:crypto";
23
import type { APIGatewayBotInfo } from "discord-api-types/v10";
34
import * as httpsProxyAgent from "https-proxy-agent";
45
import type { DiscordAccountConfig } from "openclaw/plugin-sdk/config-runtime";
56
import { formatErrorMessage } from "openclaw/plugin-sdk/error-runtime";
7+
import {
8+
captureHttpExchange,
9+
captureWsEvent,
10+
resolveEffectiveDebugProxyUrl,
11+
resolveDebugProxySettings,
12+
} from "openclaw/plugin-sdk/proxy-capture";
613
import { danger } from "openclaw/plugin-sdk/runtime-env";
714
import type { RuntimeEnv } from "openclaw/plugin-sdk/runtime-env";
815
import { normalizeLowercaseStringOrEmpty } from "openclaw/plugin-sdk/text-runtime";
@@ -275,11 +282,50 @@ function createGatewayPlugin(params: {
275282
if (!url) {
276283
throw new Error("Gateway URL is required");
277284
}
285+
const wsFlowId = randomUUID();
278286
// Avoid Node's undici-backed global WebSocket here. We have seen late
279287
// close-path crashes during Discord gateway teardown; the ws transport is
280288
// already our proxy path and behaves predictably for lifecycle cleanup.
281289
const WebSocketCtor = params.testing?.webSocketCtor ?? ws.default;
282290
const socket = new WebSocketCtor(url, params.wsAgent ? { agent: params.wsAgent } : undefined);
291+
captureWsEvent({
292+
url,
293+
direction: "local",
294+
kind: "ws-open",
295+
flowId: wsFlowId,
296+
meta: { subsystem: "discord-gateway" },
297+
});
298+
socket.on?.("message", (data: unknown) => {
299+
captureWsEvent({
300+
url,
301+
direction: "inbound",
302+
kind: "ws-frame",
303+
flowId: wsFlowId,
304+
payload: Buffer.isBuffer(data) ? data : Buffer.from(String(data)),
305+
meta: { subsystem: "discord-gateway" },
306+
});
307+
});
308+
socket.on?.("close", (code: number, reason: Buffer) => {
309+
captureWsEvent({
310+
url,
311+
direction: "local",
312+
kind: "ws-close",
313+
flowId: wsFlowId,
314+
closeCode: code,
315+
payload: reason,
316+
meta: { subsystem: "discord-gateway" },
317+
});
318+
});
319+
socket.on?.("error", (error: Error) => {
320+
captureWsEvent({
321+
url,
322+
direction: "local",
323+
kind: "error",
324+
flowId: wsFlowId,
325+
errorText: error.message,
326+
meta: { subsystem: "discord-gateway" },
327+
});
328+
});
283329
if ("binaryType" in socket) {
284330
try {
285331
socket.binaryType = "arraybuffer";
@@ -309,7 +355,8 @@ export function createDiscordGatewayPlugin(params: {
309355
};
310356
}): carbonGateway.GatewayPlugin {
311357
const intents = resolveDiscordGatewayIntents(params.discordConfig?.intents);
312-
const proxy = params.discordConfig?.proxy?.trim();
358+
const proxy = resolveEffectiveDebugProxyUrl(params.discordConfig?.proxy);
359+
const debugProxySettings = resolveDebugProxySettings();
313360
const options = {
314361
reconnect: { maxAttempts: 50 },
315362
intents,
@@ -319,7 +366,21 @@ export function createDiscordGatewayPlugin(params: {
319366
if (!proxy) {
320367
return createGatewayPlugin({
321368
options,
322-
fetchImpl: (input, init) => fetch(input, init as RequestInit),
369+
fetchImpl: async (input, init) => {
370+
const response = await fetch(input, init as RequestInit);
371+
if (!debugProxySettings.enabled) {
372+
captureHttpExchange({
373+
url: input,
374+
method: (init?.method as string | undefined) ?? "GET",
375+
requestHeaders: init?.headers as Headers | Record<string, string> | undefined,
376+
requestBody: (init as RequestInit & { body?: BodyInit | null })?.body ?? null,
377+
response,
378+
flowId: randomUUID(),
379+
meta: { subsystem: "discord-gateway-metadata" },
380+
});
381+
}
382+
return response;
383+
},
323384
runtime: params.runtime,
324385
testing: params.__testing
325386
? {
@@ -342,7 +403,22 @@ export function createDiscordGatewayPlugin(params: {
342403

343404
return createGatewayPlugin({
344405
options,
345-
fetchImpl: (input, init) => (params.__testing?.undiciFetch ?? undici.fetch)(input, init),
406+
fetchImpl: async (input, init) => {
407+
const response = (await (params.__testing?.undiciFetch ?? undici.fetch)(
408+
input,
409+
init,
410+
)) as unknown as Response;
411+
captureHttpExchange({
412+
url: input,
413+
method: (init?.method as string | undefined) ?? "GET",
414+
requestHeaders: init?.headers as Headers | Record<string, string> | undefined,
415+
requestBody: (init as RequestInit & { body?: BodyInit | null })?.body ?? null,
416+
response,
417+
flowId: randomUUID(),
418+
meta: { subsystem: "discord-gateway-metadata" },
419+
});
420+
return response;
421+
},
346422
fetchInit: { dispatcher: fetchAgent },
347423
wsAgent,
348424
runtime: params.runtime,

‎extensions/discord/src/monitor/provider.proxy.test.ts‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,14 @@ import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
33
const {
44
GatewayIntents,
55
baseRegisterClientSpy,
6+
captureHttpExchangeSpy,
7+
captureWsEventSpy,
68
GatewayPlugin,
79
globalFetchMock,
810
HttpsProxyAgent,
911
getLastAgent,
1012
restProxyAgentSpy,
13+
resolveDebugProxySettingsMock,
1114
undiciFetchMock,
1215
undiciProxyAgentSpy,
1316
resetLastAgent,
@@ -21,6 +24,9 @@ const {
2124
const globalFetchMock = vi.fn();
2225
const baseRegisterClientSpy = vi.fn();
2326
const webSocketSpy = vi.fn();
27+
const captureHttpExchangeSpy = vi.fn();
28+
const captureWsEventSpy = vi.fn();
29+
const resolveDebugProxySettingsMock = vi.fn(() => ({ enabled: false }));
2430

2531
const GatewayIntents = {
2632
Guilds: 1 << 0,
@@ -66,6 +72,9 @@ const {
6672
HttpsProxyAgent,
6773
getLastAgent: () => HttpsProxyAgent.lastCreated,
6874
restProxyAgentSpy,
75+
captureHttpExchangeSpy,
76+
captureWsEventSpy,
77+
resolveDebugProxySettingsMock,
6978
undiciFetchMock,
7079
undiciProxyAgentSpy,
7180
resetLastAgent: () => {
@@ -106,6 +115,14 @@ vi.mock("ws", () => ({
106115
},
107116
}));
108117

118+
vi.mock("openclaw/plugin-sdk/proxy-capture", () => ({
119+
captureHttpExchange: captureHttpExchangeSpy,
120+
captureWsEvent: captureWsEventSpy,
121+
resolveEffectiveDebugProxyUrl: (configuredProxyUrl?: string) =>
122+
configuredProxyUrl?.trim() || process.env.OPENCLAW_DEBUG_PROXY_URL,
123+
resolveDebugProxySettings: resolveDebugProxySettingsMock,
124+
}));
125+
109126
describe("createDiscordGatewayPlugin", () => {
110127
let createDiscordGatewayPlugin: typeof import("./gateway-plugin.js").createDiscordGatewayPlugin;
111128

@@ -213,6 +230,9 @@ describe("createDiscordGatewayPlugin", () => {
213230
undiciProxyAgentSpy.mockClear();
214231
wsProxyAgentSpy.mockClear();
215232
webSocketSpy.mockClear();
233+
captureHttpExchangeSpy.mockClear();
234+
captureWsEventSpy.mockClear();
235+
resolveDebugProxySettingsMock.mockReset().mockReturnValue({ enabled: false });
216236
resetLastAgent();
217237
});
218238

@@ -249,6 +269,25 @@ describe("createDiscordGatewayPlugin", () => {
249269
expect(wsProxyAgentSpy).not.toHaveBeenCalled();
250270
});
251271

272+
it("allocates a fresh websocket flow id for each gateway socket", () => {
273+
const runtime = createRuntime();
274+
const plugin = createDiscordGatewayPlugin({
275+
discordConfig: {},
276+
runtime,
277+
});
278+
279+
const createWebSocket = (plugin as unknown as { createWebSocket: (url: string) => unknown })
280+
.createWebSocket;
281+
createWebSocket("wss://gateway.discord.gg/?attempt=1");
282+
createWebSocket("wss://gateway.discord.gg/?attempt=2");
283+
284+
const openCalls = captureWsEventSpy.mock.calls.filter(
285+
([event]) => event?.kind === "ws-open",
286+
);
287+
expect(openCalls).toHaveLength(2);
288+
expect(openCalls[0]?.[0]?.flowId).not.toBe(openCalls[1]?.[0]?.flowId);
289+
});
290+
252291
it("maps plain-text Discord 503 responses to fetch failed", async () => {
253292
await expectGatewayRegisterFallback({
254293
ok: false,
@@ -324,6 +363,19 @@ describe("createDiscordGatewayPlugin", () => {
324363
expect(baseRegisterClientSpy).toHaveBeenCalledTimes(1);
325364
});
326365

366+
it("does not double-capture gateway metadata fetches when global fetch patching is enabled", async () => {
367+
resolveDebugProxySettingsMock.mockReturnValue({ enabled: true });
368+
const runtime = createRuntime();
369+
const plugin = createDiscordGatewayPlugin({
370+
discordConfig: {},
371+
runtime,
372+
});
373+
374+
await registerGatewayClientWithMetadata({ plugin, fetchMock: globalFetchMock });
375+
376+
expect(captureHttpExchangeSpy).not.toHaveBeenCalled();
377+
});
378+
327379
it("accepts IPv6 loopback proxy URLs for gateway metadata and websocket setup", async () => {
328380
const runtime = createRuntime();
329381
const plugin = createDiscordGatewayPlugin({

‎extensions/discord/src/monitor/provider.rest-proxy.test.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ describe("resolveDiscordRestFetch", () => {
3030
});
3131

3232
beforeEach(() => {
33+
vi.unstubAllEnvs();
3334
undiciFetchMock.mockReset();
3435
proxyAgentSpy.mockReset();
3536
});
@@ -100,4 +101,21 @@ describe("resolveDiscordRestFetch", () => {
100101
expect(proxyAgentSpy).toHaveBeenCalledWith("http://[::1]:8080");
101102
expect(runtime.error).not.toHaveBeenCalled();
102103
});
104+
105+
it("uses debug proxy env when no discord proxy URL is configured", async () => {
106+
vi.stubEnv("OPENCLAW_DEBUG_PROXY_ENABLED", "1");
107+
vi.stubEnv("OPENCLAW_DEBUG_PROXY_URL", "http://127.0.0.1:7777");
108+
const runtime = {
109+
log: vi.fn(),
110+
error: vi.fn(),
111+
exit: vi.fn(),
112+
} as const;
113+
undiciFetchMock.mockResolvedValue(new Response("ok", { status: 200 }));
114+
115+
const fetcher = resolveDiscordRestFetch(undefined, runtime);
116+
await fetcher("https://discord.com/api/v10/oauth2/applications/@me");
117+
118+
expect(proxyAgentSpy).toHaveBeenCalledWith("http://127.0.0.1:7777");
119+
expect(runtime.log).toHaveBeenCalledWith("discord: rest proxy enabled");
120+
});
103121
});

‎extensions/discord/src/monitor/rest-fetch.ts‎

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,34 @@
11
import { wrapFetchWithAbortSignal } from "openclaw/plugin-sdk/fetch-runtime";
2+
import { captureHttpExchange, resolveEffectiveDebugProxyUrl } from "openclaw/plugin-sdk/proxy-capture";
23
import type { RuntimeEnv } from "openclaw/plugin-sdk/runtime-env";
4+
import { randomUUID } from "node:crypto";
35
import { ProxyAgent, fetch as undiciFetch } from "undici";
46
import { withValidatedDiscordProxy } from "../proxy-fetch.js";
57

68
export function resolveDiscordRestFetch(
79
proxyUrl: string | undefined,
810
runtime: RuntimeEnv,
911
): typeof fetch {
10-
const fetcher = withValidatedDiscordProxy(proxyUrl, runtime, (proxy) => {
12+
const effectiveProxyUrl = resolveEffectiveDebugProxyUrl(proxyUrl);
13+
const fetcher = withValidatedDiscordProxy(effectiveProxyUrl, runtime, (proxy) => {
1114
const agent = new ProxyAgent(proxy);
1215
return wrapFetchWithAbortSignal(
1316
((input: RequestInfo | URL, init?: RequestInit) =>
14-
undiciFetch(input as string | URL, {
17+
(undiciFetch(input as string | URL, {
1518
...(init as Record<string, unknown>),
1619
dispatcher: agent,
17-
}) as unknown as Promise<Response>) as typeof fetch,
20+
}) as unknown as Promise<Response>).then((response) => {
21+
captureHttpExchange({
22+
url: input instanceof URL ? input.toString() : String(input),
23+
method: init?.method ?? "GET",
24+
requestHeaders: init?.headers as Headers | Record<string, string> | undefined,
25+
requestBody: (init as RequestInit & { body?: BodyInit | null })?.body ?? null,
26+
response,
27+
flowId: randomUUID(),
28+
meta: { subsystem: "discord-rest" },
29+
});
30+
return response;
31+
})) as typeof fetch,
1832
);
1933
});
2034
if (!fetcher) {

0 commit comments

Comments
 (0)