chore: We have a sleep at home. The sleep at home:

This commit is contained in:
cpojer
2026-02-02 21:34:47 +09:00
parent dfef943f0a
commit 6b0d6e2540
18 changed files with 69 additions and 49 deletions

View File

@@ -1,4 +1,5 @@
import { afterEach, expect, test } from "vitest"; import { afterEach, expect, test } from "vitest";
import { sleep } from "../utils.ts";
import { import {
getFinishedSession, getFinishedSession,
getSession, getSession,
@@ -7,8 +8,6 @@ import {
import { createExecTool } from "./bash-tools.exec"; import { createExecTool } from "./bash-tools.exec";
import { killProcessTree } from "./shell-utils"; import { killProcessTree } from "./shell-utils";
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
afterEach(() => { afterEach(() => {
resetProcessRegistryForTests(); resetProcessRegistryForTests();
}); });

View File

@@ -1,10 +1,9 @@
import { afterEach, expect, test } from "vitest"; import { afterEach, expect, test } from "vitest";
import { sleep } from "../utils";
import { resetProcessRegistryForTests } from "./bash-process-registry"; import { resetProcessRegistryForTests } from "./bash-process-registry";
import { createExecTool } from "./bash-tools.exec"; import { createExecTool } from "./bash-tools.exec";
import { createProcessTool } from "./bash-tools.process"; import { createProcessTool } from "./bash-tools.process";
const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
afterEach(() => { afterEach(() => {
resetProcessRegistryForTests(); resetProcessRegistryForTests();
}); });
@@ -31,7 +30,7 @@ test("process send-keys encodes Enter for pty sessions", async () => {
const deadline = Date.now() + (process.platform === "win32" ? 4000 : 2000); const deadline = Date.now() + (process.platform === "win32" ? 4000 : 2000);
while (Date.now() < deadline) { while (Date.now() < deadline) {
await wait(50); await sleep(50);
const poll = await processTool.execute("toolcall", { action: "poll", sessionId }); const poll = await processTool.execute("toolcall", { action: "poll", sessionId });
const details = poll.details as { status?: string; aggregated?: string }; const details = poll.details as { status?: string; aggregated?: string };
if (details.status !== "running") { if (details.status !== "running") {
@@ -65,7 +64,7 @@ test("process submit sends Enter for pty sessions", async () => {
const deadline = Date.now() + (process.platform === "win32" ? 4000 : 2000); const deadline = Date.now() + (process.platform === "win32" ? 4000 : 2000);
while (Date.now() < deadline) { while (Date.now() < deadline) {
await wait(50); await sleep(50);
const poll = await processTool.execute("toolcall", { action: "poll", sessionId }); const poll = await processTool.execute("toolcall", { action: "poll", sessionId });
const details = poll.details as { status?: string; aggregated?: string }; const details = poll.details as { status?: string; aggregated?: string };
if (details.status !== "running") { if (details.status !== "running") {

View File

@@ -2,6 +2,7 @@ import fs from "node:fs";
import path from "node:path"; import path from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest"; import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { peekSystemEvents, resetSystemEventsForTest } from "../infra/system-events.js"; import { peekSystemEvents, resetSystemEventsForTest } from "../infra/system-events.js";
import { sleep } from "../utils.js";
import { getFinishedSession, resetProcessRegistryForTests } from "./bash-process-registry.js"; import { getFinishedSession, resetProcessRegistryForTests } from "./bash-process-registry.js";
import { createExecTool, createProcessTool, execTool, processTool } from "./bash-tools.js"; import { createExecTool, createProcessTool, execTool, processTool } from "./bash-tools.js";
import { buildDockerExecArgs } from "./bash-tools.shared.js"; import { buildDockerExecArgs } from "./bash-tools.shared.js";
@@ -45,8 +46,6 @@ const normalizeText = (value?: string) =>
.join("\n") .join("\n")
.trim(); .trim();
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
async function waitForCompletion(sessionId: string) { async function waitForCompletion(sessionId: string) {
let status = "running"; let status = "running";
const deadline = Date.now() + (process.platform === "win32" ? 8000 : 2000); const deadline = Date.now() + (process.platform === "win32" ? 8000 : 2000);

View File

@@ -1,4 +1,5 @@
import { beforeEach, describe, expect, it, vi } from "vitest"; import { beforeEach, describe, expect, it, vi } from "vitest";
import { sleep } from "../utils.js";
import { runClaudeCliAgent } from "./claude-cli-runner.js"; import { runClaudeCliAgent } from "./claude-cli-runner.js";
const runCommandWithTimeoutMock = vi.fn(); const runCommandWithTimeoutMock = vi.fn();
@@ -22,7 +23,7 @@ async function waitForCalls(mockFn: { mock: { calls: unknown[][] } }, count: num
if (mockFn.mock.calls.length >= count) { if (mockFn.mock.calls.length >= count) {
return; return;
} }
await new Promise((resolve) => setTimeout(resolve, 0)); await sleep(0);
} }
throw new Error(`Expected ${count} calls, got ${mockFn.mock.calls.length}`); throw new Error(`Expected ${count} calls, got ${mockFn.mock.calls.length}`);
} }

View File

@@ -21,6 +21,7 @@ vi.mock("../config/config.js", async (importOriginal) => {
}); });
import "./test-helpers/fast-core-tools.js"; import "./test-helpers/fast-core-tools.js";
import { sleep } from "../utils.js";
import { createOpenClawTools } from "./openclaw-tools.js"; import { createOpenClawTools } from "./openclaw-tools.js";
const waitForCalls = async (getCount: () => number, count: number, timeoutMs = 2000) => { const waitForCalls = async (getCount: () => number, count: number, timeoutMs = 2000) => {
@@ -29,7 +30,7 @@ const waitForCalls = async (getCount: () => number, count: number, timeoutMs = 2
if (Date.now() - start > timeoutMs) { if (Date.now() - start > timeoutMs) {
throw new Error(`timed out waiting for ${count} calls`); throw new Error(`timed out waiting for ${count} calls`);
} }
await new Promise((resolve) => setTimeout(resolve, 0)); await sleep(0);
} }
}; };
@@ -185,7 +186,10 @@ describe("sessions tools", () => {
const sessionId = "sess-group"; const sessionId = "sess-group";
const targetKey = "agent:main:discord:channel:1457165743010611293"; const targetKey = "agent:main:discord:channel:1457165743010611293";
callGatewayMock.mockImplementation(async (opts: unknown) => { callGatewayMock.mockImplementation(async (opts: unknown) => {
const request = opts as { method?: string; params?: Record<string, unknown> }; const request = opts as {
method?: string;
params?: Record<string, unknown>;
};
if (request.method === "sessions.resolve") { if (request.method === "sessions.resolve") {
return { return {
key: targetKey, key: targetKey,
@@ -388,7 +392,10 @@ describe("sessions tools", () => {
const sessionId = "sess-send"; const sessionId = "sess-send";
const targetKey = "agent:main:discord:channel:123"; const targetKey = "agent:main:discord:channel:123";
callGatewayMock.mockImplementation(async (opts: unknown) => { callGatewayMock.mockImplementation(async (opts: unknown) => {
const request = opts as { method?: string; params?: Record<string, unknown> }; const request = opts as {
method?: string;
params?: Record<string, unknown>;
};
if (request.method === "sessions.resolve") { if (request.method === "sessions.resolve") {
return { key: targetKey }; return { key: targetKey };
} }
@@ -514,8 +521,8 @@ describe("sessions tools", () => {
status: "ok", status: "ok",
reply: "initial", reply: "initial",
}); });
await new Promise((resolve) => setTimeout(resolve, 0)); await sleep(0);
await new Promise((resolve) => setTimeout(resolve, 0)); await sleep(0);
const agentCalls = calls.filter((call) => call.method === "agent"); const agentCalls = calls.filter((call) => call.method === "agent");
expect(agentCalls).toHaveLength(4); expect(agentCalls).toHaveLength(4);

View File

@@ -22,6 +22,7 @@ vi.mock("../config/config.js", async (importOriginal) => {
}); });
import "./test-helpers/fast-core-tools.js"; import "./test-helpers/fast-core-tools.js";
import { sleep } from "../utils.js";
import { createOpenClawTools } from "./openclaw-tools.js"; import { createOpenClawTools } from "./openclaw-tools.js";
import { resetSubagentRegistryForTests } from "./subagent-registry.js"; import { resetSubagentRegistryForTests } from "./subagent-registry.js";
@@ -107,9 +108,9 @@ describe("openclaw-tools: subagents", () => {
runId: "run-1", runId: "run-1",
}); });
await new Promise((resolve) => setTimeout(resolve, 0)); await sleep(0);
await new Promise((resolve) => setTimeout(resolve, 0)); await sleep(0);
await new Promise((resolve) => setTimeout(resolve, 0)); await sleep(0);
const childWait = waitCalls.find((call) => call.runId === childRunId); const childWait = waitCalls.find((call) => call.runId === childRunId);
expect(childWait?.timeoutMs).toBe(1000); expect(childWait?.timeoutMs).toBe(1000);

View File

@@ -23,6 +23,7 @@ vi.mock("../config/config.js", async (importOriginal) => {
import { emitAgentEvent } from "../infra/agent-events.js"; import { emitAgentEvent } from "../infra/agent-events.js";
import "./test-helpers/fast-core-tools.js"; import "./test-helpers/fast-core-tools.js";
import { sleep } from "../utils.js";
import { createOpenClawTools } from "./openclaw-tools.js"; import { createOpenClawTools } from "./openclaw-tools.js";
import { resetSubagentRegistryForTests } from "./subagent-registry.js"; import { resetSubagentRegistryForTests } from "./subagent-registry.js";
@@ -165,7 +166,12 @@ describe("openclaw-tools: subagents", () => {
if (request.method === "agent.wait") { if (request.method === "agent.wait") {
const params = request.params as { runId?: string; timeoutMs?: number } | undefined; const params = request.params as { runId?: string; timeoutMs?: number } | undefined;
waitCalls.push(params ?? {}); waitCalls.push(params ?? {});
return { runId: params?.runId ?? "run-1", status: "ok", startedAt: 1000, endedAt: 2000 }; return {
runId: params?.runId ?? "run-1",
status: "ok",
startedAt: 1000,
endedAt: 2000,
};
} }
if (request.method === "sessions.delete") { if (request.method === "sessions.delete") {
const params = request.params as { key?: string } | undefined; const params = request.params as { key?: string } | undefined;
@@ -206,9 +212,9 @@ describe("openclaw-tools: subagents", () => {
}, },
}); });
await new Promise((resolve) => setTimeout(resolve, 0)); await sleep(0);
await new Promise((resolve) => setTimeout(resolve, 0)); await sleep(0);
await new Promise((resolve) => setTimeout(resolve, 0)); await sleep(0);
const childWait = waitCalls.find((call) => call.runId === childRunId); const childWait = waitCalls.find((call) => call.runId === childRunId);
expect(childWait?.timeoutMs).toBe(1000); expect(childWait?.timeoutMs).toBe(1000);
@@ -272,7 +278,12 @@ describe("openclaw-tools: subagents", () => {
} }
if (request.method === "agent.wait") { if (request.method === "agent.wait") {
const params = request.params as { runId?: string; timeoutMs?: number } | undefined; const params = request.params as { runId?: string; timeoutMs?: number } | undefined;
return { runId: params?.runId ?? "run-1", status: "ok", startedAt: 1000, endedAt: 2000 }; return {
runId: params?.runId ?? "run-1",
status: "ok",
startedAt: 1000,
endedAt: 2000,
};
} }
if (request.method === "sessions.delete" || request.method === "sessions.patch") { if (request.method === "sessions.delete" || request.method === "sessions.patch") {
return { ok: true }; return { ok: true };
@@ -312,9 +323,9 @@ describe("openclaw-tools: subagents", () => {
}, },
}); });
await new Promise((resolve) => setTimeout(resolve, 0)); await sleep(0);
await new Promise((resolve) => setTimeout(resolve, 0)); await sleep(0);
await new Promise((resolve) => setTimeout(resolve, 0)); await sleep(0);
const agentCalls = calls.filter((call) => call.method === "agent"); const agentCalls = calls.filter((call) => call.method === "agent");
expect(agentCalls).toHaveLength(2); expect(agentCalls).toHaveLength(2);

View File

@@ -1,4 +1,5 @@
import { beforeEach, describe, expect, it, vi } from "vitest"; import { beforeEach, describe, expect, it, vi } from "vitest";
import { sleep } from "../utils.ts";
const callGatewayMock = vi.fn(); const callGatewayMock = vi.fn();
vi.mock("../gateway/call.js", () => ({ vi.mock("../gateway/call.js", () => ({
@@ -82,7 +83,12 @@ describe("openclaw-tools: subagents", () => {
if (request.method === "agent.wait") { if (request.method === "agent.wait") {
const params = request.params as { runId?: string; timeoutMs?: number } | undefined; const params = request.params as { runId?: string; timeoutMs?: number } | undefined;
waitCalls.push(params ?? {}); waitCalls.push(params ?? {});
return { runId: params?.runId ?? "run-1", status: "ok", startedAt: 1000, endedAt: 2000 }; return {
runId: params?.runId ?? "run-1",
status: "ok",
startedAt: 1000,
endedAt: 2000,
};
} }
if (request.method === "sessions.patch") { if (request.method === "sessions.patch") {
const params = request.params as { key?: string; label?: string } | undefined; const params = request.params as { key?: string; label?: string } | undefined;
@@ -126,9 +132,9 @@ describe("openclaw-tools: subagents", () => {
}, },
}); });
await new Promise((resolve) => setTimeout(resolve, 0)); await sleep(0);
await new Promise((resolve) => setTimeout(resolve, 0)); await sleep(0);
await new Promise((resolve) => setTimeout(resolve, 0)); await sleep(0);
const childWait = waitCalls.find((call) => call.runId === childRunId); const childWait = waitCalls.find((call) => call.runId === childRunId);
expect(childWait?.timeoutMs).toBe(1000); expect(childWait?.timeoutMs).toBe(1000);

View File

@@ -2,6 +2,7 @@ import type { HumanDelayConfig } from "../../config/types.js";
import type { GetReplyOptions, ReplyPayload } from "../types.js"; import type { GetReplyOptions, ReplyPayload } from "../types.js";
import type { ResponsePrefixContext } from "./response-prefix-template.js"; import type { ResponsePrefixContext } from "./response-prefix-template.js";
import type { TypingController } from "./typing.js"; import type { TypingController } from "./typing.js";
import { sleep } from "../../utils.js";
import { normalizeReplyPayload, type NormalizeReplySkipReason } from "./normalize-reply.js"; import { normalizeReplyPayload, type NormalizeReplySkipReason } from "./normalize-reply.js";
export type ReplyDispatchKind = "tool" | "block" | "final"; export type ReplyDispatchKind = "tool" | "block" | "final";
@@ -37,9 +38,6 @@ function getHumanDelay(config: HumanDelayConfig | undefined): number {
return Math.floor(Math.random() * (max - min + 1)) + min; return Math.floor(Math.random() * (max - min + 1)) + min;
} }
/** Sleep for a given number of milliseconds. */
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
export type ReplyDispatcherOptions = { export type ReplyDispatcherOptions = {
deliver: ReplyDispatchDeliverer; deliver: ReplyDispatchDeliverer;
responsePrefix?: string; responsePrefix?: string;

View File

@@ -1,4 +1,5 @@
import { describe, expect, it, vi } from "vitest"; import { describe, expect, it, vi } from "vitest";
import { sleep } from "../utils.ts";
import { import {
removeAckReactionAfterReply, removeAckReactionAfterReply,
shouldAckReaction, shouldAckReaction,
@@ -237,7 +238,7 @@ describe("removeAckReactionAfterReply", () => {
remove, remove,
onError, onError,
}); });
await new Promise((resolve) => setTimeout(resolve, 0)); await sleep(0);
expect(remove).toHaveBeenCalledTimes(1); expect(remove).toHaveBeenCalledTimes(1);
expect(onError).not.toHaveBeenCalled(); expect(onError).not.toHaveBeenCalled();
}); });
@@ -250,7 +251,7 @@ describe("removeAckReactionAfterReply", () => {
ackReactionValue: "👀", ackReactionValue: "👀",
remove, remove,
}); });
await new Promise((resolve) => setTimeout(resolve, 0)); await sleep(0);
expect(remove).not.toHaveBeenCalled(); expect(remove).not.toHaveBeenCalled();
}); });
@@ -262,7 +263,7 @@ describe("removeAckReactionAfterReply", () => {
ackReactionValue: "👀", ackReactionValue: "👀",
remove, remove,
}); });
await new Promise((resolve) => setTimeout(resolve, 0)); await sleep(0);
expect(remove).not.toHaveBeenCalled(); expect(remove).not.toHaveBeenCalled();
}); });
}); });

View File

@@ -1,5 +1,6 @@
import { execFileSync } from "node:child_process"; import { execFileSync } from "node:child_process";
import { resolveLsofCommandSync } from "../infra/ports-lsof.js"; import { resolveLsofCommandSync } from "../infra/ports-lsof.js";
import { sleep } from "../utils.js";
export type PortProcess = { pid: number; command?: string }; export type PortProcess = { pid: number; command?: string };
@@ -9,10 +10,6 @@ export type ForceFreePortResult = {
escalatedToSigkill: boolean; escalatedToSigkill: boolean;
}; };
function sleep(ms: number) {
return new Promise<void>((resolve) => setTimeout(resolve, ms));
}
export function parseLsofOutput(output: string): PortProcess[] { export function parseLsofOutput(output: string): PortProcess[] {
const lines = output.split(/\r?\n/).filter(Boolean); const lines = output.split(/\r?\n/).filter(Boolean);
const results: PortProcess[] = []; const results: PortProcess[] = [];

View File

@@ -2,6 +2,7 @@ import fs from "node:fs/promises";
import os from "node:os"; import os from "node:os";
import path from "node:path"; import path from "node:path";
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
import { sleep } from "../utils.js";
import { import {
buildGroupDisplayName, buildGroupDisplayName,
deriveSessionKey, deriveSessionKey,
@@ -428,7 +429,6 @@ describe("sessions", () => {
"utf-8", "utf-8",
); );
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
await Promise.all([ await Promise.all([
updateSessionStoreEntry({ updateSessionStoreEntry({
storePath, storePath,

View File

@@ -1,5 +1,6 @@
import type { Guild } from "@buape/carbon"; import type { Guild } from "@buape/carbon";
import { describe, expect, it, vi } from "vitest"; import { describe, expect, it, vi } from "vitest";
import { sleep } from "../utils.js";
import { import {
allowListMatches, allowListMatches,
buildDiscordMediaPayload, buildDiscordMediaPayload,
@@ -88,7 +89,7 @@ describe("DiscordMessageListener", () => {
{} as unknown as import("./monitor/listeners.js").DiscordMessageEvent, {} as unknown as import("./monitor/listeners.js").DiscordMessageEvent,
{} as unknown as import("@buape/carbon").Client, {} as unknown as import("@buape/carbon").Client,
); );
await new Promise((resolve) => setTimeout(resolve, 0)); await sleep(0);
expect(logger.error).toHaveBeenCalledWith(expect.stringContaining("discord handler failed")); expect(logger.error).toHaveBeenCalledWith(expect.stringContaining("discord handler failed"));
}); });

View File

@@ -16,6 +16,7 @@ vi.mock("../infra/update-runner.js", () => ({
})), })),
})); }));
import { sleep } from "../utils.js";
import { import {
connectOk, connectOk,
installGatewayTestHooks, installGatewayTestHooks,
@@ -43,8 +44,6 @@ afterAll(async () => {
await server.close(); await server.close();
}); });
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
const connectNodeClient = async (params: { const connectNodeClient = async (params: {
port: number; port: number;
commands: string[]; commands: string[];

View File

@@ -1,3 +1,5 @@
import { sleep } from "../utils.js";
export type RetryConfig = { export type RetryConfig = {
attempts?: number; attempts?: number;
minDelayMs?: number; minDelayMs?: number;
@@ -27,8 +29,6 @@ const DEFAULT_RETRY_CONFIG = {
jitter: 0, jitter: 0,
}; };
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
const asFiniteNumber = (value: unknown): number | undefined => const asFiniteNumber = (value: unknown): number | undefined =>
typeof value === "number" && Number.isFinite(value) ? value : undefined; typeof value === "number" && Number.isFinite(value) ? value : undefined;

View File

@@ -54,7 +54,8 @@ function resolveRequestUrl(input: RequestInfo | URL): string {
if ("url" in input && typeof input.url === "string") { if ("url" in input && typeof input.url === "string") {
return input.url; return input.url;
} }
return String(input);
throw new Error(`Unable to resolve request URL from input: ${JSON.stringify(input, null, 2)}`);
} }
function createSlackMediaFetch(token: string): FetchLike { function createSlackMediaFetch(token: string): FetchLike {

View File

@@ -15,6 +15,7 @@ vi.mock("../agents/pi-embedded.js", () => ({
import { resetInboundDedupe } from "../auto-reply/reply/inbound-dedupe.js"; import { resetInboundDedupe } from "../auto-reply/reply/inbound-dedupe.js";
import { resetLogger, setLoggerOverride } from "../logging.js"; import { resetLogger, setLoggerOverride } from "../logging.js";
import { sleep } from "../utils.js";
import { monitorWebChannel } from "./auto-reply.js"; import { monitorWebChannel } from "./auto-reply.js";
import { resetBaileysMocks, resetLoadConfigMock, setLoadConfigMock } from "./test-helpers.js"; import { resetBaileysMocks, resetLoadConfigMock, setLoadConfigMock } from "./test-helpers.js";
@@ -33,7 +34,7 @@ const rmDirWithRetries = async (dir: string): Promise<void> => {
? String((err as { code?: unknown }).code) ? String((err as { code?: unknown }).code)
: null; : null;
if (code === "ENOTEMPTY" || code === "EBUSY" || code === "EPERM") { if (code === "ENOTEMPTY" || code === "EBUSY" || code === "EPERM") {
await new Promise((resolve) => setTimeout(resolve, 25)); await sleep(25);
continue; continue;
} }
throw err; throw err;

View File

@@ -4,6 +4,7 @@ import type { WebInboundMsg } from "./types.js";
import { chunkMarkdownTextWithMode, type ChunkMode } from "../../auto-reply/chunk.js"; import { chunkMarkdownTextWithMode, type ChunkMode } from "../../auto-reply/chunk.js";
import { logVerbose, shouldLogVerbose } from "../../globals.js"; import { logVerbose, shouldLogVerbose } from "../../globals.js";
import { convertMarkdownTables } from "../../markdown/tables.js"; import { convertMarkdownTables } from "../../markdown/tables.js";
import { sleep } from "../../utils.js";
import { loadWebMedia } from "../media.js"; import { loadWebMedia } from "../media.js";
import { newConnectionId } from "../reconnect.js"; import { newConnectionId } from "../reconnect.js";
import { formatError } from "../session.js"; import { formatError } from "../session.js";
@@ -36,8 +37,6 @@ export async function deliverWebReply(params: {
? [replyResult.mediaUrl] ? [replyResult.mediaUrl]
: []; : [];
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
const sendWithRetry = async (fn: () => Promise<unknown>, label: string, maxAttempts = 3) => { const sendWithRetry = async (fn: () => Promise<unknown>, label: string, maxAttempts = 3) => {
let lastErr: unknown; let lastErr: unknown;
for (let attempt = 1; attempt <= maxAttempts; attempt++) { for (let attempt = 1; attempt <= maxAttempts; attempt++) {