Skip to content

Commit 65848d0

Browse files
fix(discord): restore runtime timeout compatibility exports (#91686)
Co-authored-by: openclaw-clownfish[bot] <280122609+openclaw-clownfish[bot]@users.noreply.github.com>
1 parent 9ef67ea commit 65848d0

5 files changed

Lines changed: 167 additions & 2 deletions

File tree

‎extensions/discord/runtime-api.monitor.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,5 +47,9 @@ export {
4747
DISCORD_ATTACHMENT_TOTAL_TIMEOUT_MS,
4848
DISCORD_DEFAULT_INBOUND_WORKER_TIMEOUT_MS,
4949
DISCORD_DEFAULT_LISTENER_TIMEOUT_MS,
50+
isAbortError,
5051
mergeAbortSignals,
52+
normalizeDiscordInboundWorkerTimeoutMs,
53+
normalizeDiscordListenerTimeoutMs,
54+
runDiscordTaskWithTimeout,
5155
} from "./src/monitor/timeouts.js";

‎extensions/discord/runtime-api.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,10 +46,13 @@ export {
4646
createDiscordNativeCommand,
4747
getGateway,
4848
getPresence,
49+
isAbortError,
4950
isDiscordGroupAllowedByPolicy,
5051
mergeAbortSignals,
5152
monitorDiscordProvider,
5253
normalizeDiscordAllowList,
54+
normalizeDiscordInboundWorkerTimeoutMs,
55+
normalizeDiscordListenerTimeoutMs,
5356
normalizeDiscordSlug,
5457
presenceCacheSize,
5558
registerDiscordListener,
@@ -62,6 +65,7 @@ export {
6265
resolveDiscordReplyTarget,
6366
resolveDiscordShouldRequireMention,
6467
resolveGroupDmAllow,
68+
runDiscordTaskWithTimeout,
6569
sanitizeDiscordThreadName,
6670
setPresence,
6771
shouldEmitDiscordReactionNotification,

‎extensions/discord/src/monitor/timeouts.test.ts‎

Lines changed: 73 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,86 @@
11
// Discord tests cover timeouts plugin behavior.
22
import { MAX_TIMER_TIMEOUT_MS } from "openclaw/plugin-sdk/number-runtime";
33
import { afterEach, describe, expect, it, vi } from "vitest";
4-
import { raceWithTimeout, withAbortTimeout } from "./timeouts.js";
4+
import {
5+
isAbortError as runtimeApiIsAbortError,
6+
normalizeDiscordInboundWorkerTimeoutMs as runtimeApiNormalizeDiscordInboundWorkerTimeoutMs,
7+
normalizeDiscordListenerTimeoutMs as runtimeApiNormalizeDiscordListenerTimeoutMs,
8+
runDiscordTaskWithTimeout as runtimeApiRunDiscordTaskWithTimeout,
9+
} from "../../runtime-api.js";
10+
import {
11+
DISCORD_DEFAULT_INBOUND_WORKER_TIMEOUT_MS,
12+
DISCORD_DEFAULT_LISTENER_TIMEOUT_MS,
13+
isAbortError,
14+
normalizeDiscordInboundWorkerTimeoutMs,
15+
normalizeDiscordListenerTimeoutMs,
16+
raceWithTimeout,
17+
runDiscordTaskWithTimeout,
18+
withAbortTimeout,
19+
} from "./timeouts.js";
520

621
afterEach(() => {
722
vi.useRealTimers();
823
vi.restoreAllMocks();
924
});
1025

1126
describe("discord monitor timeouts", () => {
27+
it("keeps deprecated timeout helpers on the runtime api compatibility surface", () => {
28+
expect(runtimeApiIsAbortError).toBe(isAbortError);
29+
expect(runtimeApiNormalizeDiscordInboundWorkerTimeoutMs).toBe(
30+
normalizeDiscordInboundWorkerTimeoutMs,
31+
);
32+
expect(runtimeApiNormalizeDiscordListenerTimeoutMs).toBe(normalizeDiscordListenerTimeoutMs);
33+
expect(runtimeApiRunDiscordTaskWithTimeout).toBe(runDiscordTaskWithTimeout);
34+
});
35+
36+
it("preserves legacy timeout normalization semantics", () => {
37+
expect(normalizeDiscordListenerTimeoutMs(undefined)).toBe(DISCORD_DEFAULT_LISTENER_TIMEOUT_MS);
38+
expect(normalizeDiscordListenerTimeoutMs(0)).toBe(DISCORD_DEFAULT_LISTENER_TIMEOUT_MS);
39+
expect(normalizeDiscordListenerTimeoutMs(250)).toBe(1_000);
40+
expect(normalizeDiscordListenerTimeoutMs(Number.MAX_SAFE_INTEGER)).toBe(MAX_TIMER_TIMEOUT_MS);
41+
42+
expect(normalizeDiscordInboundWorkerTimeoutMs(undefined)).toBe(
43+
DISCORD_DEFAULT_INBOUND_WORKER_TIMEOUT_MS,
44+
);
45+
expect(normalizeDiscordInboundWorkerTimeoutMs(0)).toBeUndefined();
46+
expect(normalizeDiscordInboundWorkerTimeoutMs(-1)).toBe(
47+
DISCORD_DEFAULT_INBOUND_WORKER_TIMEOUT_MS,
48+
);
49+
expect(normalizeDiscordInboundWorkerTimeoutMs(Number.MAX_SAFE_INTEGER)).toBe(
50+
MAX_TIMER_TIMEOUT_MS,
51+
);
52+
});
53+
54+
it("identifies abort errors for deprecated timeout compatibility callers", () => {
55+
expect(isAbortError(Object.assign(new Error("aborted"), { name: "AbortError" }))).toBe(true);
56+
expect(isAbortError(new Error("other"))).toBe(false);
57+
});
58+
59+
it("caps runDiscordTaskWithTimeout timers before arming the watchdog", async () => {
60+
vi.useFakeTimers();
61+
const timeoutSpy = vi.spyOn(globalThis, "setTimeout");
62+
const onTimeout = vi.fn();
63+
let receivedSignal: AbortSignal | undefined;
64+
65+
const task = runDiscordTaskWithTimeout({
66+
timeoutMs: Number.MAX_SAFE_INTEGER,
67+
onTimeout,
68+
run: async (signal) => {
69+
receivedSignal = signal;
70+
await new Promise<void>((resolve) => {
71+
signal?.addEventListener("abort", () => resolve(), { once: true });
72+
});
73+
},
74+
});
75+
76+
await vi.advanceTimersByTimeAsync(MAX_TIMER_TIMEOUT_MS);
77+
78+
await expect(task).resolves.toBe(true);
79+
expect(receivedSignal?.aborted).toBe(true);
80+
expect(onTimeout).toHaveBeenCalledWith(MAX_TIMER_TIMEOUT_MS);
81+
expect(timeoutSpy).toHaveBeenCalledWith(expect.any(Function), MAX_TIMER_TIMEOUT_MS);
82+
});
83+
1284
it("caps raceWithTimeout timers before arming the watchdog", async () => {
1385
const timeoutSpy = vi
1486
.spyOn(globalThis, "setTimeout")

‎extensions/discord/src/monitor/timeouts.ts‎

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,35 @@ export const DISCORD_DEFAULT_INBOUND_WORKER_TIMEOUT_MS = 30 * 60_000;
99
export const DISCORD_ATTACHMENT_IDLE_TIMEOUT_MS = 60_000;
1010
export const DISCORD_ATTACHMENT_TOTAL_TIMEOUT_MS = 120_000;
1111

12+
/** @deprecated Discord listener timeouts are compatibility-only. */
13+
export function normalizeDiscordListenerTimeoutMs(raw: number | undefined): number {
14+
if (!Number.isFinite(raw) || (raw ?? 0) <= 0) {
15+
return DISCORD_DEFAULT_LISTENER_TIMEOUT_MS;
16+
}
17+
return resolveTimerTimeoutMs(raw, DISCORD_DEFAULT_LISTENER_TIMEOUT_MS, 1_000);
18+
}
19+
20+
/** @deprecated Discord no longer applies channel-owned inbound run timeouts. */
21+
export function normalizeDiscordInboundWorkerTimeoutMs(
22+
raw: number | undefined,
23+
): number | undefined {
24+
if (raw === 0) {
25+
return undefined;
26+
}
27+
if (typeof raw !== "number" || !Number.isFinite(raw) || raw < 0) {
28+
return DISCORD_DEFAULT_INBOUND_WORKER_TIMEOUT_MS;
29+
}
30+
return resolveTimerTimeoutMs(raw, DISCORD_DEFAULT_INBOUND_WORKER_TIMEOUT_MS, 1);
31+
}
32+
33+
/** @deprecated Compatibility helper for old Discord timeout integrations. */
34+
export function isAbortError(error: unknown): boolean {
35+
if (typeof error !== "object" || error === null) {
36+
return false;
37+
}
38+
return "name" in error && String((error as { name?: unknown }).name) === "AbortError";
39+
}
40+
1241
export function mergeAbortSignals(
1342
signals: Array<AbortSignal | undefined>,
1443
): AbortSignal | undefined {
@@ -41,6 +70,62 @@ export function mergeAbortSignals(
4170
return fallbackController.signal;
4271
}
4372

73+
/** @deprecated Discord no longer uses this for channel-owned message run timeouts. */
74+
export async function runDiscordTaskWithTimeout(params: {
75+
run: (abortSignal: AbortSignal | undefined) => Promise<void>;
76+
timeoutMs?: number;
77+
abortSignals?: Array<AbortSignal | undefined>;
78+
onTimeout: (timeoutMs: number) => void | Promise<void>;
79+
onAbortAfterTimeout?: () => void;
80+
onErrorAfterTimeout?: (error: unknown) => void;
81+
}): Promise<boolean> {
82+
const timeoutMs =
83+
params.timeoutMs === undefined ? undefined : resolveTimerTimeoutMs(params.timeoutMs, 0, 0);
84+
const timeoutAbortController = timeoutMs ? new AbortController() : undefined;
85+
const mergedAbortSignal = mergeAbortSignals([
86+
...(params.abortSignals ?? []),
87+
timeoutAbortController?.signal,
88+
]);
89+
let timedOut = false;
90+
let timeoutHandle: ReturnType<typeof setTimeout> | null = null;
91+
const runPromise = params.run(mergedAbortSignal).catch((error: unknown) => {
92+
if (!timedOut) {
93+
throw error;
94+
}
95+
if (timeoutAbortController?.signal.aborted && isAbortError(error)) {
96+
params.onAbortAfterTimeout?.();
97+
return;
98+
}
99+
params.onErrorAfterTimeout?.(error);
100+
});
101+
102+
try {
103+
if (!timeoutMs) {
104+
await runPromise;
105+
return false;
106+
}
107+
const timeoutPromise = new Promise<"timeout">((resolve) => {
108+
timeoutHandle = setTimeout(() => resolve("timeout"), timeoutMs);
109+
timeoutHandle.unref?.();
110+
});
111+
const result = await Promise.race([
112+
runPromise.then(() => "completed" as const),
113+
timeoutPromise,
114+
]);
115+
if (result === "timeout") {
116+
timedOut = true;
117+
timeoutAbortController?.abort();
118+
await params.onTimeout(timeoutMs);
119+
return true;
120+
}
121+
return false;
122+
} finally {
123+
if (timeoutHandle) {
124+
clearTimeout(timeoutHandle);
125+
}
126+
}
127+
}
128+
44129
export async function raceWithTimeout<T, U>(params: {
45130
promise: Promise<T>;
46131
timeoutMs: number;

‎src/plugins/contracts/plugin-sdk-runtime-api-guardrails.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ const RUNTIME_API_EXPORT_GUARDS: Record<string, readonly string[]> = {
4646
[bundledPluginFile({ rootDir: ROOT_DIR, pluginId: "discord", relativePath: "runtime-api.ts" })]: [
4747
'export { discordMessageActions, handleDiscordAction, isDiscordModerationAction, readDiscordChannelCreateParams, readDiscordChannelEditParams, readDiscordChannelMoveParams, readDiscordModerationCommand, readDiscordParentIdParam, requiredGuildPermissionForModerationAction, type DiscordModerationAction, type DiscordModerationCommand } from "./runtime-api.actions.js";',
4848
'export { auditDiscordChannelPermissions, collectDiscordAuditChannelIds, fetchDiscordApplicationId, fetchDiscordApplicationSummary, listDiscordDirectoryGroupsLive, listDiscordDirectoryPeersLive, parseApplicationIdFromToken, probeDiscord, resolveDiscordChannelAllowlist, resolveDiscordPrivilegedIntentsFromFlags, resolveDiscordUserAllowlist, setDiscordRuntime, type DiscordApplicationSummary, type DiscordChannelResolution, type DiscordPrivilegedIntentsSummary, type DiscordPrivilegedIntentStatus, type DiscordProbe, type DiscordUserResolution } from "./runtime-api.lookup.js";',
49-
'export { DISCORD_ATTACHMENT_IDLE_TIMEOUT_MS, DISCORD_ATTACHMENT_TOTAL_TIMEOUT_MS, DISCORD_DEFAULT_INBOUND_WORKER_TIMEOUT_MS, DISCORD_DEFAULT_LISTENER_TIMEOUT_MS, allowListMatches, buildDiscordMediaPayload, clearGateways, clearPresences, createDiscordGatewayPlugin, createDiscordMessageHandler, createDiscordNativeCommand, getGateway, getPresence, isDiscordGroupAllowedByPolicy, mergeAbortSignals, monitorDiscordProvider, normalizeDiscordAllowList, normalizeDiscordSlug, presenceCacheSize, registerDiscordListener, registerGateway, resolveDiscordChannelConfig, resolveDiscordChannelConfigWithFallback, resolveDiscordCommandAuthorized, resolveDiscordGatewayIntents, resolveDiscordGuildEntry, resolveDiscordReplyTarget, resolveDiscordShouldRequireMention, resolveGroupDmAllow, sanitizeDiscordThreadName, setPresence, shouldEmitDiscordReactionNotification, unregisterGateway, waitForDiscordGatewayPluginRegistration, type DiscordAllowList, type DiscordChannelConfigResolved, type DiscordGuildEntryResolved, type DiscordMessageEvent, type DiscordMessageHandler, type MonitorDiscordOpts } from "./runtime-api.monitor.js";',
49+
'export { DISCORD_ATTACHMENT_IDLE_TIMEOUT_MS, DISCORD_ATTACHMENT_TOTAL_TIMEOUT_MS, DISCORD_DEFAULT_INBOUND_WORKER_TIMEOUT_MS, DISCORD_DEFAULT_LISTENER_TIMEOUT_MS, allowListMatches, buildDiscordMediaPayload, clearGateways, clearPresences, createDiscordGatewayPlugin, createDiscordMessageHandler, createDiscordNativeCommand, getGateway, getPresence, isAbortError, isDiscordGroupAllowedByPolicy, mergeAbortSignals, monitorDiscordProvider, normalizeDiscordAllowList, normalizeDiscordInboundWorkerTimeoutMs, normalizeDiscordListenerTimeoutMs, normalizeDiscordSlug, presenceCacheSize, registerDiscordListener, registerGateway, resolveDiscordChannelConfig, resolveDiscordChannelConfigWithFallback, resolveDiscordCommandAuthorized, resolveDiscordGatewayIntents, resolveDiscordGuildEntry, resolveDiscordReplyTarget, resolveDiscordShouldRequireMention, resolveGroupDmAllow, runDiscordTaskWithTimeout, sanitizeDiscordThreadName, setPresence, shouldEmitDiscordReactionNotification, unregisterGateway, waitForDiscordGatewayPluginRegistration, type DiscordAllowList, type DiscordChannelConfigResolved, type DiscordGuildEntryResolved, type DiscordMessageEvent, type DiscordMessageHandler, type MonitorDiscordOpts } from "./runtime-api.monitor.js";',
5050
'export { DiscordSendError, addRoleDiscord, banMemberDiscord, createChannelDiscord, createScheduledEventDiscord, createThreadDiscord, deleteChannelDiscord, deleteMessageDiscord, editChannelDiscord, editDiscordComponentMessage, editMessageDiscord, fetchChannelInfoDiscord, fetchChannelPermissionsDiscord, fetchMemberGuildPermissionsDiscord, fetchMemberInfoDiscord, fetchMessageDiscord, fetchReactionsDiscord, fetchRoleInfoDiscord, fetchVoiceStatusDiscord, hasAllGuildPermissionsDiscord, hasAnyGuildPermissionDiscord, kickMemberDiscord, listGuildChannelsDiscord, listGuildEmojisDiscord, listPinsDiscord, listScheduledEventsDiscord, listThreadsDiscord, moveChannelDiscord, pinMessageDiscord, reactMessageDiscord, readMessagesDiscord, registerBuiltDiscordComponentMessage, removeChannelPermissionDiscord, removeOwnReactionsDiscord, removeReactionDiscord, removeRoleDiscord, resolveDiscordOutboundSessionRoute, resolveEventCoverImage, searchMessagesDiscord, sendDiscordComponentMessage, sendMessageDiscord, sendPollDiscord, sendStickerDiscord, sendTypingDiscord, sendVoiceMessageDiscord, sendWebhookMessageDiscord, setChannelPermissionDiscord, timeoutMemberDiscord, unpinMessageDiscord, uploadEmojiDiscord, uploadStickerDiscord, type DiscordChannelCreate, type DiscordChannelEdit, type DiscordChannelMove, type DiscordChannelPermissionSet, type DiscordEmojiUpload, type DiscordMessageEdit, type DiscordMessageQuery, type DiscordModerationTarget, type DiscordPermissionsSummary, type DiscordReactionRuntimeContext, type DiscordReactionSummary, type DiscordReactionUser, type DiscordReactOpts, type DiscordRoleChange, type DiscordRuntimeAccountContext, type DiscordSearchQuery, type DiscordSendResult, type DiscordStickerUpload, type DiscordThreadCreate, type DiscordThreadList, type DiscordTimeoutTarget, type ResolveDiscordOutboundSessionRouteParams } from "./runtime-api.send.js";',
5151
'export { testing as __testing, testing, autoBindSpawnedDiscordSubagent, createNoopThreadBindingManager, createThreadBindingManager, formatThreadBindingDurationLabel, getThreadBindingManager, isRecentlyUnboundThreadWebhookMessage, listThreadBindingsBySessionKey, listThreadBindingsForAccount, reconcileAcpThreadBindingsOnStartup, resolveDiscordThreadBindingIdleTimeoutMs, resolveDiscordThreadBindingMaxAgeMs, resolveThreadBindingIdleTimeoutMs, resolveThreadBindingInactivityExpiresAt, resolveThreadBindingIntroText, resolveThreadBindingMaxAgeExpiresAt, resolveThreadBindingMaxAgeMs, resolveThreadBindingPersona, resolveThreadBindingPersonaFromRecord, resolveThreadBindingsEnabled, resolveThreadBindingThreadName, setThreadBindingIdleTimeoutBySessionKey, setThreadBindingMaxAgeBySessionKey, unbindThreadBindingsBySessionKey, type AcpThreadBindingReconciliationResult, type ThreadBindingManager, type ThreadBindingRecord, type ThreadBindingTargetKind } from "./runtime-api.threads.js";',
5252
],

0 commit comments

Comments
 (0)