Skip to content

Commit b47fb95

Browse files
fix(qqbot): add cause-specific setup guidance (#119780)
* fix(qqbot): add cause-specific setup guidance * fix(qqbot): recognize expired-token business errors * fix(qqbot): retry structured token failures --------- Co-authored-by: Patrick Erichsen <[email protected]>
1 parent 2e0fe80 commit b47fb95

13 files changed

Lines changed: 524 additions & 26 deletions

File tree

‎extensions/qqbot/src/engine/api/api-client.test.ts‎

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,102 @@ describe("ApiClient", () => {
9797
});
9898
});
9999

100+
it("adds network and whitelist guidance to DNS failures without suggesting credentials", async () => {
101+
fetchWithSsrFGuardMock.mockRejectedValueOnce(
102+
new Error("getaddrinfo ENOTFOUND api.sgroup.qq.com"),
103+
);
104+
105+
const client = new ApiClient({ baseUrl: "https://qqbot.test" });
106+
let error: unknown;
107+
try {
108+
await client.request("token-1", "GET", "/v2/users/@me");
109+
} catch (caught) {
110+
error = caught;
111+
}
112+
113+
const message = error instanceof Error ? error.message : String(error);
114+
expect(message).toContain("Network error [/v2/users/@me]");
115+
expect(message).toContain("network connectivity and DNS");
116+
expect(message).toContain("server IP whitelist");
117+
expect(message).not.toContain("appId");
118+
expect(message).not.toContain("clientSecret");
119+
});
120+
121+
it("adds credential guidance to structured HTTP 401 errors", async () => {
122+
const release = vi.fn(async () => {});
123+
fetchWithSsrFGuardMock.mockResolvedValueOnce({
124+
response: new Response('{"code":11241,"message":"invalid credentials"}', {
125+
status: 401,
126+
headers: { "content-type": "application/json" },
127+
}),
128+
release,
129+
});
130+
131+
const client = new ApiClient({ baseUrl: "https://qqbot.test" });
132+
let error: unknown;
133+
try {
134+
await client.request("token-1", "POST", "/v2/messages", { content: "hi" });
135+
} catch (caught) {
136+
error = caught;
137+
}
138+
139+
const message = error instanceof Error ? error.message : String(error);
140+
expect(message).toContain("API Error [/v2/messages]: invalid credentials");
141+
expect(message).toContain("QQBot account appId and clientSecret");
142+
expect(message).toContain("https://q.qq.com/");
143+
expect(release).toHaveBeenCalledTimes(1);
144+
});
145+
146+
it("adds credential guidance when QQ reports an expired token as HTTP 500", async () => {
147+
const release = vi.fn(async () => {});
148+
fetchWithSsrFGuardMock.mockResolvedValueOnce({
149+
response: new Response('{"code":11244,"message":"token not exist or expire"}', {
150+
status: 500,
151+
headers: { "content-type": "application/json" },
152+
}),
153+
release,
154+
});
155+
156+
const client = new ApiClient({ baseUrl: "https://qqbot.test" });
157+
let error: unknown;
158+
try {
159+
await client.request("token-1", "GET", "/gateway");
160+
} catch (caught) {
161+
error = caught;
162+
}
163+
164+
expect(error).toBeInstanceOf(ApiError);
165+
expect(error).toMatchObject({ httpStatus: 500, bizCode: 11244 });
166+
expect((error as Error).message).toContain("QQBot account appId and clientSecret");
167+
expect(release).toHaveBeenCalledTimes(1);
168+
});
169+
170+
it("keeps non-auth structured API guidance generic", async () => {
171+
const release = vi.fn(async () => {});
172+
fetchWithSsrFGuardMock.mockResolvedValueOnce({
173+
response: new Response('{"code":40034025,"message":"invalid event id"}', {
174+
status: 400,
175+
headers: { "content-type": "application/json" },
176+
}),
177+
release,
178+
});
179+
180+
const client = new ApiClient({ baseUrl: "https://qqbot.test" });
181+
let error: unknown;
182+
try {
183+
await client.request("token-1", "POST", "/v2/messages", { content: "hi" });
184+
} catch (caught) {
185+
error = caught;
186+
}
187+
188+
const message = error instanceof Error ? error.message : String(error);
189+
expect(message).toContain("API Error [/v2/messages]: invalid event id");
190+
expect(message).toContain("QQBot API troubleshooting");
191+
expect(message).not.toContain("appId");
192+
expect(message).not.toContain("clientSecret");
193+
expect(release).toHaveBeenCalledTimes(1);
194+
});
195+
100196
it("bounds successful response bodies without using response.text()", async () => {
101197
const release = vi.fn(async () => {});
102198
const streamed = createStreamingResponse({

‎extensions/qqbot/src/engine/api/api-client.ts‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import {
1616
} from "openclaw/plugin-sdk/provider-http";
1717
import { fetchWithSsrFGuard, type SsrFPolicy } from "openclaw/plugin-sdk/ssrf-runtime";
1818
import { truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
19+
import { qqbotApiGuidance, qqbotNetworkGuidance } from "../config/setup-guidance.js";
1920
import { ApiError, type ApiClientConfig, type EngineLogger } from "../types.js";
2021

2122
const DEFAULT_BASE_URL = "https://api.sgroup.qq.com";
@@ -149,7 +150,11 @@ export class ApiClient {
149150
throw new ApiError(`Request timeout [${path}]: exceeded ${timeout}ms`, 0, path);
150151
}
151152
this.logger?.error?.(`[qqbot:api] <<< Network error: ${formatErrorMessage(err)}`);
152-
throw new ApiError(`Network error [${path}]: ${formatErrorMessage(err)}`, 0, path);
153+
throw new ApiError(
154+
`Network error [${path}]: ${formatErrorMessage(err)}. ${qqbotNetworkGuidance()}`,
155+
0,
156+
path,
157+
);
153158
}
154159

155160
const res = guarded.response;
@@ -206,7 +211,7 @@ export class ApiClient {
206211
};
207212
const bizCode = error.code ?? error.err_code;
208213
throw new ApiError(
209-
`API Error [${path}]: ${error.message ?? rawBody}`,
214+
`API Error [${path}]: ${error.message ?? rawBody}. ${qqbotApiGuidance(res.status, bizCode)}`,
210215
res.status,
211216
path,
212217
bizCode,
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
const QQBOT_TOKEN_EXPIRED_OR_MISSING_CODE = 11244;
2+
3+
/** Match QQ's HTTP and business-code signals for an invalid access token. */
4+
export function isQQBotTokenAuthenticationFailure(httpStatus: number, bizCode?: number): boolean {
5+
return httpStatus === 401 || bizCode === QQBOT_TOKEN_EXPIRED_OR_MISSING_CODE;
6+
}

‎extensions/qqbot/src/engine/api/token.test.ts‎

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,28 @@ describe("QQBot token manager", () => {
8989
expect(release).toHaveBeenCalledTimes(1);
9090
});
9191

92+
it("adds account-neutral credential guidance when the token endpoint omits access_token", async () => {
93+
const release = mockGuardedTokenResponse('{"code":4001,"message":"invalid app secret"}', {
94+
status: 200,
95+
headers: { "content-type": "application/json" },
96+
});
97+
98+
let error: unknown;
99+
try {
100+
await new TokenManager().getAccessToken("app-id", "secret");
101+
} catch (caught) {
102+
error = caught;
103+
}
104+
105+
const message = error instanceof Error ? error.message : String(error);
106+
expect(message).toContain("Failed to get QQBot access_token");
107+
expect(message).toContain("QQBot account appId and clientSecret");
108+
expect(message).toContain("https://q.qq.com/");
109+
expect(message).toContain('{"code":4001,"message":"invalid app secret"}');
110+
expect(message).not.toContain("QQBOT_APP_ID");
111+
expect(release).toHaveBeenCalledTimes(1);
112+
});
113+
92114
it("bounds access token responses without using response.text()", async () => {
93115
const logger = { debug: vi.fn(), info: vi.fn(), error: vi.fn() };
94116
const tracked = cancelTrackedResponse(`${"qqbot token unavailable ".repeat(1024)}tail`, {
@@ -230,7 +252,10 @@ describe("QQBot token manager", () => {
230252
}
231253
const timeoutError = firstOutcome.reason as Error;
232254
expect(timeoutError).toBe(secondOutcome.reason);
233-
expect(timeoutError.message).toBe("Network error getting access_token: request timed out");
255+
expect(timeoutError.message).toContain("Network error getting access_token: request timed out");
256+
expect(timeoutError.message).toContain("Check network connectivity and DNS");
257+
expect(timeoutError.message).toContain("server IP whitelist");
258+
expect(timeoutError.message).not.toContain("appId");
234259
expect(timeoutError.cause).toMatchObject({
235260
name: "TimeoutError",
236261
message: "request timed out",

‎extensions/qqbot/src/engine/api/token.ts‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import {
1616
import { readResponseTextLimited } from "openclaw/plugin-sdk/provider-http";
1717
import { sleepWithAbort } from "openclaw/plugin-sdk/runtime-env";
1818
import { fetchWithSsrFGuard, type SsrFPolicy } from "openclaw/plugin-sdk/ssrf-runtime";
19+
import { qqbotNetworkGuidance, qqbotTokenFailureMessage } from "../config/setup-guidance.js";
1920
import type { EngineLogger } from "../types.js";
2021

2122
const TOKEN_URL = "https://bots.qq.com/app/getAppAccessToken";
@@ -267,9 +268,10 @@ export class TokenManager {
267268
release = guarded.release;
268269
} catch (err) {
269270
this.logger?.error?.(`[qqbot:token:${appId}] Network error: ${formatErrorMessage(err)}`);
270-
throw new Error(`Network error getting access_token: ${formatErrorMessage(err)}`, {
271-
cause: err,
272-
});
271+
throw new Error(
272+
`Network error getting access_token: ${formatErrorMessage(err)}. ${qqbotNetworkGuidance()}`,
273+
{ cause: err },
274+
);
273275
}
274276

275277
try {
@@ -297,7 +299,7 @@ export class TokenManager {
297299
}
298300

299301
if (!data.access_token) {
300-
throw new Error(`Failed to get access_token: ${JSON.stringify(data)}`);
302+
throw new Error(qqbotTokenFailureMessage(JSON.stringify(data)));
301303
}
302304

303305
const nowMs = asDateTimestampMs(Date.now());
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import { describe, expect, it } from "vitest";
2+
import {
3+
qqbotApiGuidance,
4+
qqbotNetworkGuidance,
5+
qqbotNotConfiguredMessage,
6+
} from "./setup-guidance.js";
7+
8+
describe("QQBot setup guidance", () => {
9+
it("offers default-account config and environment variables", () => {
10+
const message = qqbotNotConfiguredMessage("default");
11+
12+
expect(message).toContain("channels.qqbot.appId");
13+
expect(message).toContain("QQBOT_APP_ID and QQBOT_CLIENT_SECRET");
14+
expect(message).toContain("https://docs.openclaw.ai/channels/qqbot");
15+
});
16+
17+
it("directs named accounts to account-scoped config without default-only environment variables", () => {
18+
const message = qqbotNotConfiguredMessage("operations");
19+
20+
expect(message).toContain("channels.qqbot.accounts.operations.appId");
21+
expect(message).toContain("clientSecret (or clientSecretFile)");
22+
expect(message).not.toContain("QQBOT_APP_ID");
23+
expect(message).not.toContain("QQBOT_CLIENT_SECRET");
24+
});
25+
26+
it("keeps authentication guidance account-neutral", () => {
27+
const message = qqbotApiGuidance(401);
28+
29+
expect(message).toContain("QQBot account appId");
30+
expect(message).toContain("https://q.qq.com/");
31+
expect(message).not.toContain("QQBOT_APP_ID");
32+
expect(message).not.toContain("QQBOT_CLIENT_SECRET");
33+
});
34+
35+
it("keeps network guidance cause-specific", () => {
36+
const message = qqbotNetworkGuidance();
37+
38+
expect(message).toContain("network connectivity and DNS");
39+
expect(message).toContain("server IP whitelist");
40+
expect(message).not.toContain("appId");
41+
expect(message).not.toContain("clientSecret");
42+
});
43+
44+
it("uses credential guidance for HTTP and QQ business-code auth failures", () => {
45+
expect(qqbotApiGuidance(401)).toContain("appId and clientSecret");
46+
expect(qqbotApiGuidance(500, 11244)).toContain("appId and clientSecret");
47+
expect(qqbotApiGuidance(403)).not.toContain("appId");
48+
expect(qqbotApiGuidance(500, 40034025)).not.toContain("appId");
49+
expect(qqbotApiGuidance(429)).not.toContain("appId");
50+
});
51+
});
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import { isQQBotTokenAuthenticationFailure } from "../api/auth-errors.js";
2+
import { DEFAULT_ACCOUNT_ID } from "./resolve.js";
3+
4+
const QQBOT_DOCS_URL = "https://docs.openclaw.ai/channels/qqbot";
5+
const QQBOT_OPEN_PLATFORM_URL = "https://q.qq.com/";
6+
7+
function qqbotAuthGuidance(): string {
8+
return `Check the QQBot account appId and clientSecret (or clientSecretFile) in OpenClaw and verify the credentials in QQ Open Platform at ${QQBOT_OPEN_PLATFORM_URL}. See ${QQBOT_DOCS_URL}`;
9+
}
10+
11+
export function qqbotNetworkGuidance(): string {
12+
return `Check network connectivity and DNS, and verify the server IP whitelist in QQ Open Platform at ${QQBOT_OPEN_PLATFORM_URL}. See ${QQBOT_DOCS_URL}`;
13+
}
14+
15+
export function qqbotApiGuidance(httpStatus: number, bizCode?: number): string {
16+
return isQQBotTokenAuthenticationFailure(httpStatus, bizCode)
17+
? qqbotAuthGuidance()
18+
: `See ${QQBOT_DOCS_URL} for QQBot API troubleshooting`;
19+
}
20+
21+
export function qqbotNotConfiguredMessage(accountId: string): string {
22+
const guidance =
23+
accountId === DEFAULT_ACCOUNT_ID
24+
? `Set channels.qqbot.appId and clientSecret (or clientSecretFile), or set QQBOT_APP_ID and QQBOT_CLIENT_SECRET. See ${QQBOT_DOCS_URL}`
25+
: `Set channels.qqbot.accounts.${accountId}.appId and clientSecret (or clientSecretFile). See ${QQBOT_DOCS_URL}`;
26+
return `QQBot not configured (missing appId or clientSecret). ${guidance}`;
27+
}
28+
29+
export function qqbotTokenFailureMessage(detail: string): string {
30+
return `Failed to get QQBot access_token. ${qqbotAuthGuidance()}. Open platform response: ${detail}`;
31+
}

0 commit comments

Comments
 (0)