Skip to content

Commit 3bdaa1c

Browse files
committed
fix(discord): configure gateway ready timeouts
1 parent 60538f3 commit 3bdaa1c

12 files changed

Lines changed: 223 additions & 35 deletions

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@ Docs: https://docs.openclaw.ai
5353
- Discord/DMs: keep no-guild inbound messages on direct-message routing when Discord channel lookup is temporarily unavailable, preventing degraded DMs from forking into channel sessions. Fixes #59817. Thanks @DooPeePey.
5454
- Discord: retry outbound API calls on HTTP 5xx, request-timeout, and transient transport failures instead of only Discord rate limits, reducing dropped cron and agent replies during short Discord or network outages. Fixes #52396. Thanks @sunshineo.
5555
- Discord: include Components v2 Text Display content from referenced replies and forwarded snapshots, so component-only messages still appear in reply context. Fixes #56228. Thanks @HollandDrive.
56+
- Discord: add configurable gateway READY timeouts for startup and runtime reconnects, so staggered multi-account setups can avoid false restart loops. Fixes #72273. Thanks @sergionsantos.
5657
- Gateway/config: log config health-state write failures instead of silently hiding config observe-recovery write errors. Thanks @sallyom.
5758
- Diagnostics: reset stuck-session timers on reply, tool, status, block, and ACP progress events, and back off repeated `session.stuck` diagnostics while a session remains unchanged. Supersedes #72010. Thanks @rubencu.
5859

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
8bbb620e445cba64aa8a451cfc1a7142ac24e8c80088d74a2fc813ee9e221680 config-baseline.json
2-
d145a87759d16d5f58873db337a25cb134ab25e776cd454812dca99bb9cb12a7 config-baseline.core.json
3-
c401cd3450f1737bc92418cfea301d20b54b7fbef9e6049834acc01af338e538 config-baseline.channel.json
4-
7731a0b93cb335b56fac4c807447ba659fea51ea7a6cd844dc0ef5616669ee75 config-baseline.plugin.json
1+
1d9157a39ad18841d666af90c58e0539d6427cbd2ad0c1ce29047a5a2131ba7e config-baseline.json
2+
80e6e8dce647aef2d1310de55a81d27de52cca47fc24bd7ad81b80f43a72b84c config-baseline.core.json
3+
1cec599c3d27c258b9df3446baa547cb164e502afa9b30c052bba8737183f551 config-baseline.channel.json
4+
8346667910d2b3a3884efce8f96591adebc4f7ea99ce18337b80e4d70bf8e4d2 config-baseline.plugin.json

‎docs/channels/discord.md‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1255,6 +1255,22 @@ openclaw logs --follow
12551255

12561256
</Accordion>
12571257

1258+
<Accordion title="Gateway READY timeout restarts">
1259+
OpenClaw waits for Discord's gateway `READY` event during startup and after runtime reconnects. Multi-account setups with startup staggering can need a longer startup READY window than the default.
1260+
1261+
READY timeout knobs:
1262+
1263+
- startup single-account: `channels.discord.gatewayReadyTimeoutMs`
1264+
- startup multi-account: `channels.discord.accounts.<accountId>.gatewayReadyTimeoutMs`
1265+
- startup env fallback when config is unset: `OPENCLAW_DISCORD_READY_TIMEOUT_MS`
1266+
- startup default: `15000` (15 seconds), max: `120000`
1267+
- runtime single-account: `channels.discord.gatewayRuntimeReadyTimeoutMs`
1268+
- runtime multi-account: `channels.discord.accounts.<accountId>.gatewayRuntimeReadyTimeoutMs`
1269+
- runtime env fallback when config is unset: `OPENCLAW_DISCORD_RUNTIME_READY_TIMEOUT_MS`
1270+
- runtime default: `30000` (30 seconds), max: `120000`
1271+
1272+
</Accordion>
1273+
12581274
<Accordion title="Permissions audit mismatches">
12591275
`channels status --probe` permission checks only work for numeric channel IDs.
12601276

@@ -1301,7 +1317,7 @@ Primary reference: [Configuration reference - Discord](/gateway/config-channels#
13011317
- policy: `groupPolicy`, `dm.*`, `guilds.*`, `guilds.*.channels.*`
13021318
- command: `commands.native`, `commands.useAccessGroups`, `configWrites`, `slashCommand.*`
13031319
- event queue: `eventQueue.listenerTimeout` (listener budget), `eventQueue.maxQueueSize`, `eventQueue.maxConcurrency`
1304-
- gateway metadata: `gatewayInfoTimeoutMs`
1320+
- gateway: `gatewayInfoTimeoutMs`, `gatewayReadyTimeoutMs`, `gatewayRuntimeReadyTimeoutMs`
13051321
- reply/history: `replyToMode`, `historyLimit`, `dmHistoryLimit`, `dms.*.historyLimit`
13061322
- delivery: `textChunkLimit`, `chunkMode`, `maxLinesPerMessage`
13071323
- streaming: `streaming` (legacy alias: `streamMode`), `streaming.preview.toolProgress`, `draftChunk`, `blockStreaming`, `blockStreamingCoalesce`

‎extensions/discord/src/channel.test.ts‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,33 @@ describe("discordPlugin outbound", () => {
168168
expect(resolveReplyToMode({ cfg, accountId: "default" })).toBe("all");
169169
});
170170

171+
it("inherits Discord gateway READY timeout settings per account", () => {
172+
const cfg = {
173+
channels: {
174+
discord: {
175+
token: "discord-token",
176+
gatewayReadyTimeoutMs: 90_000,
177+
gatewayRuntimeReadyTimeoutMs: 120_000,
178+
accounts: {
179+
work: {
180+
token: "discord-token-work",
181+
gatewayReadyTimeoutMs: 60_000,
182+
},
183+
},
184+
},
185+
},
186+
} as OpenClawConfig;
187+
188+
expect(resolveAccount(cfg).config).toMatchObject({
189+
gatewayReadyTimeoutMs: 90_000,
190+
gatewayRuntimeReadyTimeoutMs: 120_000,
191+
});
192+
expect(resolveAccount(cfg, "work").config).toMatchObject({
193+
gatewayReadyTimeoutMs: 60_000,
194+
gatewayRuntimeReadyTimeoutMs: 120_000,
195+
});
196+
});
197+
171198
it("forwards full media send context to sendMessageDiscord", async () => {
172199
const sendMessageDiscord = vi.fn(async () => ({ messageId: "m1" }));
173200
const mediaReadFile = vi.fn(async () => Buffer.from("media"));

‎extensions/discord/src/config-ui-hints.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,14 @@ export const discordChannelConfigUiHints = {
141141
label: "Discord Gateway Metadata Timeout (ms)",
142142
help: "Timeout for Discord /gateway/bot metadata lookup before falling back to the default gateway URL. Default is 30000; OPENCLAW_DISCORD_GATEWAY_INFO_TIMEOUT_MS can override when config is unset.",
143143
},
144+
gatewayReadyTimeoutMs: {
145+
label: "Discord Gateway READY Timeout (ms)",
146+
help: "Startup wait for the Discord gateway READY event before restarting the socket. Default is 15000; OPENCLAW_DISCORD_READY_TIMEOUT_MS can override when config is unset.",
147+
},
148+
gatewayRuntimeReadyTimeoutMs: {
149+
label: "Discord Gateway Runtime READY Timeout (ms)",
150+
help: "Runtime reconnect wait for the Discord gateway READY event before force-stopping the lifecycle. Default is 30000; OPENCLAW_DISCORD_RUNTIME_READY_TIMEOUT_MS can override when config is unset.",
151+
},
144152
"voice.enabled": {
145153
label: "Discord Voice Enabled",
146154
help: "Enable Discord voice channel conversations. Text-only Discord configs leave voice off by default; set true to enable /vc commands and the Guild Voice States intent.",

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

Lines changed: 47 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -59,9 +59,15 @@ vi.mock("./gateway-registry.js", () => ({
5959

6060
describe("runDiscordGatewayLifecycle", () => {
6161
let runDiscordGatewayLifecycle: typeof import("./provider.lifecycle.js").runDiscordGatewayLifecycle;
62+
let resolveDiscordGatewayReadyTimeoutMs: typeof import("./provider.lifecycle.js").resolveDiscordGatewayReadyTimeoutMs;
63+
let resolveDiscordGatewayRuntimeReadyTimeoutMs: typeof import("./provider.lifecycle.js").resolveDiscordGatewayRuntimeReadyTimeoutMs;
6264

6365
beforeAll(async () => {
64-
({ runDiscordGatewayLifecycle } = await import("./provider.lifecycle.js"));
66+
({
67+
runDiscordGatewayLifecycle,
68+
resolveDiscordGatewayReadyTimeoutMs,
69+
resolveDiscordGatewayRuntimeReadyTimeoutMs,
70+
} = await import("./provider.lifecycle.js"));
6571
});
6672

6773
beforeEach(() => {
@@ -143,24 +149,25 @@ describe("runDiscordGatewayLifecycle", () => {
143149
error: runtimeError,
144150
exit: vi.fn(),
145151
};
152+
const lifecycleParams: LifecycleParams = {
153+
accountId: "default",
154+
gateway: gateway ? (gateway as unknown as MutableDiscordGateway) : undefined,
155+
runtime,
156+
isDisallowedIntentsError: params?.isDisallowedIntentsError ?? (() => false),
157+
voiceManager: null,
158+
voiceManagerRef: { current: null },
159+
threadBindings: { stop: threadStop },
160+
gatewaySupervisor,
161+
statusSink,
162+
abortSignal: undefined,
163+
};
146164
return {
147165
threadStop,
148166
runtimeLog,
149167
runtimeError,
150168
gatewaySupervisor,
151169
statusSink,
152-
lifecycleParams: {
153-
accountId: "default",
154-
gateway: gateway ? (gateway as unknown as MutableDiscordGateway) : undefined,
155-
runtime,
156-
isDisallowedIntentsError: params?.isDisallowedIntentsError ?? (() => false),
157-
voiceManager: null,
158-
voiceManagerRef: { current: null },
159-
threadBindings: { stop: threadStop },
160-
gatewaySupervisor,
161-
statusSink,
162-
abortSignal: undefined as AbortSignal | undefined,
163-
} satisfies LifecycleParams,
170+
lifecycleParams,
164171
};
165172
}
166173

@@ -176,6 +183,26 @@ describe("runDiscordGatewayLifecycle", () => {
176183
expect(params.gatewaySupervisor.detachLifecycle).toHaveBeenCalledTimes(1);
177184
}
178185

186+
it("resolves gateway READY timeouts from config, env, then defaults", () => {
187+
expect(resolveDiscordGatewayReadyTimeoutMs({ configuredTimeoutMs: 45_000 })).toBe(45_000);
188+
expect(
189+
resolveDiscordGatewayReadyTimeoutMs({
190+
env: { OPENCLAW_DISCORD_READY_TIMEOUT_MS: "90000" },
191+
}),
192+
).toBe(90_000);
193+
expect(resolveDiscordGatewayReadyTimeoutMs({ env: {} })).toBe(15_000);
194+
195+
expect(resolveDiscordGatewayRuntimeReadyTimeoutMs({ configuredTimeoutMs: 60_000 })).toBe(
196+
60_000,
197+
);
198+
expect(
199+
resolveDiscordGatewayRuntimeReadyTimeoutMs({
200+
env: { OPENCLAW_DISCORD_RUNTIME_READY_TIMEOUT_MS: "120000" },
201+
}),
202+
).toBe(120_000);
203+
expect(resolveDiscordGatewayRuntimeReadyTimeoutMs({ env: {} })).toBe(30_000);
204+
});
205+
179206
it("cleans up thread bindings when gateway wait fails before READY", async () => {
180207
waitForDiscordGatewayStopMock.mockRejectedValueOnce(new Error("startup failed"));
181208
const { lifecycleParams, threadStop, gatewaySupervisor } = createLifecycleHarness();
@@ -228,14 +255,15 @@ describe("runDiscordGatewayLifecycle", () => {
228255
gateway: null,
229256
},
230257
);
258+
lifecycleParams.gatewayReadyTimeoutMs = 5_000;
231259

232260
const lifecyclePromise = runDiscordGatewayLifecycle(lifecycleParams);
233261
lifecyclePromise.catch(() => {});
234262
await vi.advanceTimersByTimeAsync(0);
235-
await vi.advanceTimersByTimeAsync(15_500);
263+
await vi.advanceTimersByTimeAsync(5_500);
236264

237265
await expect(lifecyclePromise).rejects.toThrow(
238-
"discord gateway did not reach READY within 15000ms",
266+
"discord gateway did not reach READY within 5000ms",
239267
);
240268
expect(statusSink).not.toHaveBeenCalledWith(
241269
expect.objectContaining({
@@ -606,15 +634,16 @@ describe("runDiscordGatewayLifecycle", () => {
606634
);
607635

608636
const { lifecycleParams, runtimeError, statusSink } = createLifecycleHarness({ gateway });
637+
lifecycleParams.gatewayRuntimeReadyTimeoutMs = 5_000;
609638
const lifecyclePromise = runDiscordGatewayLifecycle(lifecycleParams);
610639
lifecyclePromise.catch(() => {});
611640

612-
await vi.advanceTimersByTimeAsync(30_500);
641+
await vi.advanceTimersByTimeAsync(5_500);
613642
await expect(lifecyclePromise).rejects.toThrow(
614-
"discord gateway opened but did not reach READY within 30000ms",
643+
"discord gateway opened but did not reach READY within 5000ms",
615644
);
616645
expect(runtimeError).toHaveBeenCalledWith(
617-
expect.stringContaining("did not reach READY within 30000ms"),
646+
expect.stringContaining("did not reach READY within 5000ms"),
618647
);
619648
expect(statusSink).toHaveBeenCalledWith(
620649
expect.objectContaining({

‎extensions/discord/src/monitor/provider.lifecycle.ts‎

Lines changed: 56 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -19,15 +19,49 @@ import {
1919
} from "./gateway-supervisor.js";
2020
import type { DiscordMonitorStatusSink } from "./status.js";
2121

22-
const DISCORD_GATEWAY_READY_TIMEOUT_MS = 15_000;
23-
const DISCORD_GATEWAY_RUNTIME_READY_TIMEOUT_MS = 30_000;
22+
const DEFAULT_DISCORD_GATEWAY_READY_TIMEOUT_MS = 15_000;
23+
const DEFAULT_DISCORD_GATEWAY_RUNTIME_READY_TIMEOUT_MS = 30_000;
24+
const MAX_DISCORD_GATEWAY_READY_TIMEOUT_MS = 120_000;
25+
const DISCORD_GATEWAY_READY_TIMEOUT_ENV = "OPENCLAW_DISCORD_READY_TIMEOUT_MS";
26+
const DISCORD_GATEWAY_RUNTIME_READY_TIMEOUT_ENV = "OPENCLAW_DISCORD_RUNTIME_READY_TIMEOUT_MS";
2427
const DISCORD_GATEWAY_READY_POLL_MS = 250;
2528
const DISCORD_GATEWAY_STARTUP_DISCONNECT_DRAIN_TIMEOUT_MS = 5_000;
2629
const DISCORD_GATEWAY_STARTUP_TERMINATE_CLOSE_TIMEOUT_MS = 1_000;
2730
const DISCORD_GATEWAY_TRANSPORT_ACTIVITY_STATUS_MIN_INTERVAL_MS = 30_000;
2831

2932
type GatewayReadyWaitResult = "ready" | "stopped" | "timeout";
3033

34+
function normalizeGatewayReadyTimeoutMs(value: unknown): number | undefined {
35+
const numeric =
36+
typeof value === "number" ? value : typeof value === "string" ? Number(value) : Number.NaN;
37+
if (!Number.isFinite(numeric) || numeric <= 0) {
38+
return undefined;
39+
}
40+
return Math.min(Math.floor(numeric), MAX_DISCORD_GATEWAY_READY_TIMEOUT_MS);
41+
}
42+
43+
export function resolveDiscordGatewayReadyTimeoutMs(params?: {
44+
configuredTimeoutMs?: number;
45+
env?: NodeJS.ProcessEnv;
46+
}): number {
47+
return (
48+
normalizeGatewayReadyTimeoutMs(params?.configuredTimeoutMs) ??
49+
normalizeGatewayReadyTimeoutMs(params?.env?.[DISCORD_GATEWAY_READY_TIMEOUT_ENV]) ??
50+
DEFAULT_DISCORD_GATEWAY_READY_TIMEOUT_MS
51+
);
52+
}
53+
54+
export function resolveDiscordGatewayRuntimeReadyTimeoutMs(params?: {
55+
configuredTimeoutMs?: number;
56+
env?: NodeJS.ProcessEnv;
57+
}): number {
58+
return (
59+
normalizeGatewayReadyTimeoutMs(params?.configuredTimeoutMs) ??
60+
normalizeGatewayReadyTimeoutMs(params?.env?.[DISCORD_GATEWAY_RUNTIME_READY_TIMEOUT_ENV]) ??
61+
DEFAULT_DISCORD_GATEWAY_RUNTIME_READY_TIMEOUT_MS
62+
);
63+
}
64+
3165
async function restartGatewayAfterReadyTimeout(params: {
3266
gateway?: Pick<MutableDiscordGateway, "connect" | "disconnect" | "ws">;
3367
abortSignal?: AbortSignal;
@@ -158,6 +192,7 @@ function createGatewayStatusObserver(params: {
158192
runtime: RuntimeEnv;
159193
pushStatus: (patch: Parameters<DiscordMonitorStatusSink>[0]) => void;
160194
isLifecycleStopping: () => boolean;
195+
runtimeReadyTimeoutMs: number;
161196
}) {
162197
let forceStopHandler: ((err: unknown) => void) | undefined;
163198
let queuedForceStopError: unknown;
@@ -214,7 +249,7 @@ function createGatewayStatusObserver(params: {
214249
}
215250
const at = Date.now();
216251
const error = new Error(
217-
`discord gateway opened but did not reach READY within ${DISCORD_GATEWAY_RUNTIME_READY_TIMEOUT_MS}ms`,
252+
`discord gateway opened but did not reach READY within ${params.runtimeReadyTimeoutMs}ms`,
218253
);
219254
params.pushStatus({
220255
connected: false,
@@ -227,7 +262,7 @@ function createGatewayStatusObserver(params: {
227262
});
228263
params.runtime.error?.(danger(error.message));
229264
triggerForceStop(error);
230-
}, DISCORD_GATEWAY_RUNTIME_READY_TIMEOUT_MS);
265+
}, params.runtimeReadyTimeoutMs);
231266
readyTimeoutId.unref?.();
232267
}
233268
};
@@ -292,9 +327,10 @@ async function waitForGatewayReady(params: {
292327
pushStatus?: (patch: Parameters<DiscordMonitorStatusSink>[0]) => void;
293328
runtime: RuntimeEnv;
294329
beforeRestart?: () => Promise<void> | void;
330+
readyTimeoutMs: number;
295331
}): Promise<void> {
296332
const waitUntilReady = async (): Promise<GatewayReadyWaitResult> => {
297-
const deadlineAt = Date.now() + DISCORD_GATEWAY_READY_TIMEOUT_MS;
333+
const deadlineAt = Date.now() + params.readyTimeoutMs;
298334
while (!params.abortSignal?.aborted) {
299335
if ((await params.beforePoll?.()) === "stop") {
300336
return "stopped";
@@ -324,16 +360,12 @@ async function waitForGatewayReady(params: {
324360
return;
325361
}
326362
if (!params.gateway) {
327-
throw new Error(
328-
`discord gateway did not reach READY within ${DISCORD_GATEWAY_READY_TIMEOUT_MS}ms`,
329-
);
363+
throw new Error(`discord gateway did not reach READY within ${params.readyTimeoutMs}ms`);
330364
}
331365

332366
const restartAt = Date.now();
333367
params.runtime.error?.(
334-
danger(
335-
`discord: gateway was not ready after ${DISCORD_GATEWAY_READY_TIMEOUT_MS}ms; restarting gateway`,
336-
),
368+
danger(`discord: gateway was not ready after ${params.readyTimeoutMs}ms; restarting gateway`),
337369
);
338370
params.pushStatus?.({
339371
connected: false,
@@ -356,7 +388,7 @@ async function waitForGatewayReady(params: {
356388

357389
if ((await waitUntilReady()) === "timeout") {
358390
throw new Error(
359-
`discord gateway did not reach READY within ${DISCORD_GATEWAY_READY_TIMEOUT_MS}ms after restart`,
391+
`discord gateway did not reach READY within ${params.readyTimeoutMs}ms after restart`,
360392
);
361393
}
362394
}
@@ -372,6 +404,8 @@ export async function runDiscordGatewayLifecycle(params: {
372404
threadBindings: { stop: () => void };
373405
gatewaySupervisor: DiscordGatewaySupervisor;
374406
statusSink?: DiscordMonitorStatusSink;
407+
gatewayReadyTimeoutMs?: number;
408+
gatewayRuntimeReadyTimeoutMs?: number;
375409
}) {
376410
const gateway = params.gateway;
377411
if (gateway) {
@@ -387,12 +421,21 @@ export async function runDiscordGatewayLifecycle(params: {
387421
const pushStatus = (patch: Parameters<DiscordMonitorStatusSink>[0]) => {
388422
params.statusSink?.(patch);
389423
};
424+
const gatewayReadyTimeoutMs = resolveDiscordGatewayReadyTimeoutMs({
425+
configuredTimeoutMs: params.gatewayReadyTimeoutMs,
426+
env: process.env,
427+
});
428+
const gatewayRuntimeReadyTimeoutMs = resolveDiscordGatewayRuntimeReadyTimeoutMs({
429+
configuredTimeoutMs: params.gatewayRuntimeReadyTimeoutMs,
430+
env: process.env,
431+
});
390432
const statusObserver = createGatewayStatusObserver({
391433
gateway,
392434
abortSignal: params.abortSignal,
393435
runtime: params.runtime,
394436
pushStatus,
395437
isLifecycleStopping: () => lifecycleStopping,
438+
runtimeReadyTimeoutMs: gatewayRuntimeReadyTimeoutMs,
396439
});
397440
gatewayEmitter?.on("debug", statusObserver.onGatewayDebug);
398441
let lastTransportActivityStatusAt: number | undefined;
@@ -460,6 +503,7 @@ export async function runDiscordGatewayLifecycle(params: {
460503
pushStatus,
461504
runtime: params.runtime,
462505
beforeRestart: statusObserver.clearReadyWatch,
506+
readyTimeoutMs: gatewayReadyTimeoutMs,
463507
});
464508

465509
if (drainPendingGatewayErrors() === "stop") {

0 commit comments

Comments
 (0)