Skip to content

Commit 1aff6da

Browse files
authored
refactor(test): use shared timeout helper (#105918)
1 parent 7a8e45f commit 1aff6da

5 files changed

Lines changed: 60 additions & 119 deletions

File tree

‎packages/sdk/src/index.e2e.test.ts‎

Lines changed: 8 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { afterEach, describe, expect, it } from "vitest";
55
import { WebSocketServer, type RawData, type WebSocket } from "ws";
66
import { installGatewayTestHooks, startServer } from "../../../src/gateway/test-helpers.js";
77
import { emitAgentEvent, registerAgentRunContext } from "../../../src/infra/agent-events.js";
8+
import { withTimeout } from "../../../src/utils/with-timeout.js";
89
import { GatewayClientTransport, OpenClaw } from "./index.js";
910

1011
type JsonObject = Record<string, unknown>;
@@ -55,22 +56,6 @@ async function reservePort(): Promise<number> {
5556
return port;
5657
}
5758

58-
async function withTimeout<T>(promise: Promise<T>, timeoutMs: number, message: string): Promise<T> {
59-
let timer: NodeJS.Timeout | undefined;
60-
try {
61-
return await Promise.race([
62-
promise,
63-
new Promise<never>((_resolve, reject) => {
64-
timer = setTimeout(() => reject(new Error(message)), timeoutMs);
65-
}),
66-
]);
67-
} finally {
68-
if (timer) {
69-
clearTimeout(timer);
70-
}
71-
}
72-
}
73-
7459
async function createFakeGateway(port = 0): Promise<FakeGateway> {
7560
const server = new WebSocketServer({ host: "127.0.0.1", port });
7661
servers.push(server);
@@ -410,7 +395,7 @@ describe("OpenClaw SDK websocket e2e", () => {
410395
})();
411396

412397
const [seen, result] = await Promise.all([
413-
withTimeout(seenPromise, 2_000, "timed out waiting for SDK run events"),
398+
withTimeout(seenPromise, 2_000, { message: "timed out waiting for SDK run events" }),
414399
run.wait({ timeoutMs: 2_000 }),
415400
]);
416401

@@ -635,11 +620,9 @@ describe("OpenClaw SDK real Gateway e2e", () => {
635620
data: { phase: "end", endedAt: 222 },
636621
});
637622

638-
const { seen, sessionKeys } = await withTimeout(
639-
eventsPromise,
640-
2_000,
641-
"timed out waiting for real Gateway SDK events",
642-
);
623+
const { seen, sessionKeys } = await withTimeout(eventsPromise, 2_000, {
624+
message: "timed out waiting for real Gateway SDK events",
625+
});
643626
expect(seen).toEqual(["run.started", "assistant.delta", "run.completed"]);
644627
expect(sessionKeys).toEqual([
645628
"agent:main:dashboard:sdk-real-gateway",
@@ -721,11 +704,9 @@ liveGatewayDescribe("OpenClaw SDK live Gateway e2e", () => {
721704
})();
722705

723706
const result = await run.wait({ timeoutMs: 180_000 });
724-
const events = await withTimeout(
725-
eventsPromise,
726-
5_000,
727-
"timed out waiting for live SDK run events",
728-
);
707+
const events = await withTimeout(eventsPromise, 5_000, {
708+
message: "timed out waiting for live SDK run events",
709+
});
729710

730711
expect(result.status).toBe("completed");
731712
expect(events.terminal).toBe("run.completed");

‎src/agents/bash-tools.exec-gateway-approval.e2e.test.ts‎

Lines changed: 4 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import {
1818
} from "../gateway/test-helpers.e2e.js";
1919
import { captureEnv, setTestEnvValue } from "../test-utils/env.js";
2020
import { GATEWAY_CLIENT_MODES, GATEWAY_CLIENT_NAMES } from "../utils/message-channel.js";
21+
import { withTimeout } from "../utils/with-timeout.js";
2122
import type { ExecApprovalFollowupOutcome } from "./bash-tools.exec-types.js";
2223
import { createExecTool } from "./bash-tools.exec.js";
2324

@@ -40,21 +41,6 @@ const EXEC_APPROVAL_E2E_TIMEOUT_MS = 180_000;
4041

4142
type Cleanup = () => Promise<void> | void;
4243

43-
async function withTimeout<T>(promise: Promise<T>, timeoutMs: number, label: string): Promise<T> {
44-
let timeout: NodeJS.Timeout | undefined;
45-
const timeoutPromise = new Promise<never>((_, reject) => {
46-
timeout = setTimeout(() => reject(new Error(`timed out waiting for ${label}`)), timeoutMs);
47-
timeout.unref();
48-
});
49-
try {
50-
return await Promise.race([promise, timeoutPromise]);
51-
} finally {
52-
if (timeout) {
53-
clearTimeout(timeout);
54-
}
55-
}
56-
}
57-
5844
describe("gateway-hosted exec approvals", () => {
5945
const cleanup: Cleanup[] = [];
6046

@@ -177,7 +163,9 @@ describe("gateway-hosted exec approvals", () => {
177163
{ timeoutMs: 10_000 },
178164
);
179165

180-
const outcome = await withTimeout(outcomePromise, 15_000, "approved exec outcome");
166+
const outcome = await withTimeout(outcomePromise, 15_000, {
167+
message: "timed out waiting for approved exec outcome",
168+
});
181169
expect(outcome.status).toBe("completed");
182170
expect(outcome.exitCode).toBe(0);
183171
expect(outcome.aggregated).toBe("smoke");

‎src/cron/service.read-ops-nonblocking.test.ts‎

Lines changed: 25 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import fs from "node:fs/promises";
33
import os from "node:os";
44
import path from "node:path";
55
import { describe, expect, it, vi } from "vitest";
6+
import { withTimeout } from "../utils/with-timeout.js";
67
import { CronService } from "./service.js";
78
import { writeCronStoreSnapshot } from "./service.test-harness.js";
89

@@ -19,22 +20,6 @@ type IsolatedRunResult = {
1920
error?: string;
2021
};
2122

22-
async function withTimeout<T>(promise: Promise<T>, timeoutMs: number, label: string): Promise<T> {
23-
let timeout: NodeJS.Timeout | undefined;
24-
try {
25-
return await Promise.race([
26-
promise,
27-
new Promise<T>((_resolve, reject) => {
28-
timeout = setTimeout(() => reject(new Error(`${label} timed out`)), timeoutMs);
29-
}),
30-
]);
31-
} finally {
32-
if (timeout) {
33-
clearTimeout(timeout);
34-
}
35-
}
36-
}
37-
3823
async function makeStorePath() {
3924
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-cron-"));
4025
return {
@@ -211,12 +196,19 @@ describe("CronService read ops while job is running", () => {
211196
await isolatedRun.runStarted;
212197

213198
await expect(
214-
withTimeout(cron.list({ includeDisabled: true }), 300, "cron.list during cron.run"),
199+
withTimeout(cron.list({ includeDisabled: true }), 300, {
200+
message: "cron.list during cron.run timed out",
201+
}),
215202
).resolves.toHaveLength(1);
216-
expectCronStatus(await withTimeout(cron.status(), 300, "cron.status during cron.run"), {
217-
storePath: store.storePath,
218-
jobs: 1,
219-
});
203+
expectCronStatus(
204+
await withTimeout(cron.status(), 300, {
205+
message: "cron.status during cron.run timed out",
206+
}),
207+
{
208+
storePath: store.storePath,
209+
jobs: 1,
210+
},
211+
);
220212

221213
isolatedRun.completeRun({ status: "ok", summary: "manual done" });
222214
await expect(runPromise).resolves.toEqual({ ok: true, ran: true });
@@ -273,12 +265,19 @@ describe("CronService read ops while job is running", () => {
273265
expect(isolatedRun.runIsolatedAgentJob).not.toHaveBeenCalled();
274266

275267
await expect(
276-
withTimeout(cron.list({ includeDisabled: true }), 300, "cron.list during startup"),
268+
withTimeout(cron.list({ includeDisabled: true }), 300, {
269+
message: "cron.list during startup timed out",
270+
}),
277271
).resolves.toHaveLength(1);
278-
expectCronStatus(await withTimeout(cron.status(), 300, "cron.status during startup"), {
279-
storePath: store.storePath,
280-
jobs: 1,
281-
});
272+
expectCronStatus(
273+
await withTimeout(cron.status(), 300, {
274+
message: "cron.status during startup timed out",
275+
}),
276+
{
277+
storePath: store.storePath,
278+
jobs: 1,
279+
},
280+
);
282281

283282
const jobs = await cron.list({ includeDisabled: true });
284283
expect(jobs[0]?.state.lastStatus).toBeUndefined();

‎src/daemon/launchd.integration.e2e.test.ts‎

Lines changed: 12 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import os from "node:os";
66
import path from "node:path";
77
import { PassThrough } from "node:stream";
88
import { afterAll, beforeAll, describe, expect, it } from "vitest";
9+
import { withTimeout } from "../utils/with-timeout.js";
910
import {
1011
installLaunchAgent,
1112
readLaunchAgentRuntime,
@@ -43,26 +44,6 @@ function resolveGuiDomain(): string {
4344
return `gui/${process.getuid?.() ?? 501}`;
4445
}
4546

46-
async function withTimeout<T>(params: {
47-
run: () => Promise<T>;
48-
timeoutMs: number;
49-
message: string;
50-
}): Promise<T> {
51-
let timer: NodeJS.Timeout | undefined;
52-
try {
53-
return await Promise.race([
54-
params.run(),
55-
new Promise<T>((_, reject) => {
56-
timer = setTimeout(() => reject(new Error(params.message)), params.timeoutMs);
57-
}),
58-
]);
59-
} finally {
60-
if (timer) {
61-
clearTimeout(timer);
62-
}
63-
}
64-
}
65-
6647
async function waitForRunningRuntime(params: {
6748
env: GatewayServiceEnv;
6849
pidNot?: number;
@@ -125,18 +106,18 @@ function launchEnvOrThrow(env: GatewayServiceEnv | undefined): GatewayServiceEnv
125106
}
126107

127108
async function initializeLaunchdRuntime(launchEnv: GatewayServiceEnv, stdout: PassThrough) {
128-
await withTimeout({
129-
run: async () => {
109+
await withTimeout(
110+
(async () => {
130111
await installLaunchAgent({
131112
env: launchEnv,
132113
stdout,
133114
programArguments: [process.execPath, "-e", "setInterval(() => {}, 1000);"],
134115
});
135116
await waitForRunningRuntime({ env: launchEnv });
136-
},
137-
timeoutMs: STARTUP_TIMEOUT_MS,
138-
message: "Timed out initializing launchd integration runtime",
139-
});
117+
})(),
118+
STARTUP_TIMEOUT_MS,
119+
{ message: "Timed out initializing launchd integration runtime" },
120+
);
140121
}
141122

142123
async function writeLaunchAgentProbeScript(params: {
@@ -265,11 +246,11 @@ describeLaunchdIntegration("launchd integration", () => {
265246
await fs.access(resolveLaunchAgentPlistPath(launchEnv));
266247
await fs.writeFile(eventsPath, "", "utf8");
267248

268-
const repair = await withTimeout({
269-
run: async () => repairLaunchAgentBootstrap({ env: launchEnv }),
270-
timeoutMs: STARTUP_TIMEOUT_MS,
271-
message: "Timed out repairing launchd integration runtime",
272-
});
249+
const repair = await withTimeout(
250+
repairLaunchAgentBootstrap({ env: launchEnv }),
251+
STARTUP_TIMEOUT_MS,
252+
{ message: "Timed out repairing launchd integration runtime" },
253+
);
273254
expect(repair).toEqual({ ok: true, status: "repaired" });
274255
await waitForRunningRuntime({ env: launchEnv });
275256

‎src/gateway/server.plugin-node-capability-auth.test.ts‎

Lines changed: 11 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,11 @@ import { connect, type Socket } from "node:net";
55
import type { Duplex } from "node:stream";
66
import { describe, expect, test } from "vitest";
77
import { WebSocket, WebSocketServer } from "ws";
8+
import { withTimeout } from "../utils/with-timeout.js";
89
import { createAuthRateLimiter } from "./auth-rate-limit.js";
910
import type { ResolvedGatewayAuth } from "./auth.js";
1011
import { PLUGIN_NODE_CAPABILITY_PATH_PREFIX } from "./plugin-node-capability.js";
12+
import { MAX_PREAUTH_PAYLOAD_BYTES } from "./server-constants.js";
1113
import { attachGatewayUpgradeHandler, createGatewayHttpServer } from "./server-http.js";
1214
import { createPreauthConnectionBudget } from "./server/preauth-connection-budget.js";
1315
import type { GatewayWsClient } from "./server/ws-types.js";
@@ -53,22 +55,6 @@ async function fetchCanvas(input: string, init?: RequestInit): Promise<Response>
5355
throw new Error("unreachable");
5456
}
5557

56-
async function withTimeout<T>(promise: Promise<T>, timeoutMs: number, label: string): Promise<T> {
57-
let timer: ReturnType<typeof setTimeout> | undefined;
58-
try {
59-
return await Promise.race([
60-
promise,
61-
new Promise<never>((_, reject) => {
62-
timer = setTimeout(() => reject(new Error(`${label} timed out`)), timeoutMs);
63-
}),
64-
]);
65-
} finally {
66-
if (timer) {
67-
clearTimeout(timer);
68-
}
69-
}
70-
}
71-
7258
async function listen(
7359
server: ReturnType<typeof createGatewayHttpServer>,
7460
host = "127.0.0.1",
@@ -101,7 +87,7 @@ async function listen(
10187
server.close((err) => (err ? reject(err) : resolve()));
10288
}),
10389
SERVER_CLOSE_TIMEOUT_MS,
104-
"gateway test server close",
90+
{ message: "gateway test server close timed out" },
10591
);
10692
},
10793
};
@@ -316,7 +302,10 @@ async function withCanvasGatewayHarness(params: {
316302
}) => Promise<void>;
317303
}) {
318304
const clients = new Set<GatewayWsClient>();
319-
const canvasWss = new WebSocketServer({ noServer: true });
305+
const canvasWss = new WebSocketServer({
306+
noServer: true,
307+
maxPayload: MAX_PREAUTH_PAYLOAD_BYTES,
308+
});
320309
const canvasHandler: CanvasHostHandler = {
321310
rootDir: "test",
322311
basePath: "/canvas",
@@ -358,7 +347,10 @@ async function withCanvasGatewayHarness(params: {
358347
rateLimiter: params.rateLimiter,
359348
});
360349

361-
const wss = new WebSocketServer({ noServer: true });
350+
const wss = new WebSocketServer({
351+
noServer: true,
352+
maxPayload: MAX_PREAUTH_PAYLOAD_BYTES,
353+
});
362354
attachGatewayUpgradeHandler({
363355
httpServer,
364356
wss,

0 commit comments

Comments
 (0)