Spaces:
Sleeping
Sleeping
File size: 10,959 Bytes
fb4d8fe | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 | import "./test-helpers.js";
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("../agents/pi-embedded.js", () => ({
abortEmbeddedPiRun: vi.fn().mockReturnValue(false),
isEmbeddedPiRunActive: vi.fn().mockReturnValue(false),
isEmbeddedPiRunStreaming: vi.fn().mockReturnValue(false),
runEmbeddedPiAgent: vi.fn(),
queueEmbeddedPiMessage: vi.fn().mockReturnValue(false),
resolveEmbeddedSessionLane: (key: string) => `session:${key.trim() || "main"}`,
}));
import type { OpenClawConfig } from "../config/config.js";
import { runEmbeddedPiAgent } from "../agents/pi-embedded.js";
import { getReplyFromConfig } from "../auto-reply/reply.js";
import { resetInboundDedupe } from "../auto-reply/reply/inbound-dedupe.js";
import { monitorWebChannel } from "./auto-reply.js";
import { resetLoadConfigMock, setLoadConfigMock } from "./test-helpers.js";
let previousHome: string | undefined;
let tempHome: string | undefined;
const rmDirWithRetries = async (dir: string): Promise<void> => {
// Some tests can leave async session-store writes in-flight; recursive deletion can race and throw ENOTEMPTY.
for (let attempt = 0; attempt < 10; attempt += 1) {
try {
await fs.rm(dir, { recursive: true, force: true });
return;
} catch (err) {
const code =
err && typeof err === "object" && "code" in err
? String((err as { code?: unknown }).code)
: null;
if (code === "ENOTEMPTY" || code === "EBUSY" || code === "EPERM") {
await new Promise((resolve) => setTimeout(resolve, 25));
continue;
}
throw err;
}
}
await fs.rm(dir, { recursive: true, force: true });
};
beforeEach(async () => {
resetInboundDedupe();
previousHome = process.env.HOME;
tempHome = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-web-home-"));
process.env.HOME = tempHome;
});
afterEach(async () => {
process.env.HOME = previousHome;
if (tempHome) {
await rmDirWithRetries(tempHome);
tempHome = undefined;
}
});
const makeSessionStore = async (
entries: Record<string, unknown> = {},
): Promise<{ storePath: string; cleanup: () => Promise<void> }> => {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-session-"));
const storePath = path.join(dir, "sessions.json");
await fs.writeFile(storePath, JSON.stringify(entries));
const cleanup = async () => {
// Session store writes can be in-flight when the test finishes (e.g. updateLastRoute
// after a message flush). `fs.rm({ recursive })` can race and throw ENOTEMPTY.
for (let attempt = 0; attempt < 10; attempt += 1) {
try {
await fs.rm(dir, { recursive: true, force: true });
return;
} catch (err) {
const code =
err && typeof err === "object" && "code" in err
? String((err as { code?: unknown }).code)
: null;
if (code === "ENOTEMPTY" || code === "EBUSY" || code === "EPERM") {
await new Promise((resolve) => setTimeout(resolve, 25));
continue;
}
throw err;
}
}
await fs.rm(dir, { recursive: true, force: true });
};
return {
storePath,
cleanup,
};
};
describe("partial reply gating", () => {
it("does not send partial replies for WhatsApp provider", async () => {
const reply = vi.fn().mockResolvedValue(undefined);
const sendComposing = vi.fn().mockResolvedValue(undefined);
const sendMedia = vi.fn().mockResolvedValue(undefined);
const replyResolver = vi.fn().mockResolvedValue({ text: "final reply" });
const mockConfig: OpenClawConfig = {
channels: { whatsapp: { allowFrom: ["*"] } },
};
setLoadConfigMock(mockConfig);
await monitorWebChannel(
false,
async ({ onMessage }) => {
await onMessage({
id: "m1",
from: "+1000",
conversationId: "+1000",
to: "+2000",
body: "hello",
timestamp: Date.now(),
chatType: "direct",
chatId: "direct:+1000",
sendComposing,
reply,
sendMedia,
});
return { close: vi.fn().mockResolvedValue(undefined) };
},
false,
replyResolver,
);
resetLoadConfigMock();
expect(replyResolver).toHaveBeenCalledTimes(1);
const resolverOptions = replyResolver.mock.calls[0]?.[1] ?? {};
expect("onPartialReply" in resolverOptions).toBe(false);
expect(reply).toHaveBeenCalledTimes(1);
expect(reply).toHaveBeenCalledWith("final reply");
});
it("falls back from empty senderJid to senderE164 for SenderId", async () => {
const reply = vi.fn().mockResolvedValue(undefined);
const sendComposing = vi.fn().mockResolvedValue(undefined);
const sendMedia = vi.fn().mockResolvedValue(undefined);
const replyResolver = vi.fn().mockResolvedValue({ text: "final reply" });
const mockConfig: OpenClawConfig = {
channels: {
whatsapp: {
allowFrom: ["*"],
},
},
};
setLoadConfigMock(mockConfig);
await monitorWebChannel(
false,
async ({ onMessage }) => {
await onMessage({
id: "m1",
from: "+1000",
conversationId: "+1000",
to: "+2000",
body: "hello",
timestamp: Date.now(),
chatType: "direct",
chatId: "direct:+1000",
senderJid: "",
senderE164: "+1000",
sendComposing,
reply,
sendMedia,
});
return { close: vi.fn().mockResolvedValue(undefined) };
},
false,
replyResolver,
);
resetLoadConfigMock();
expect(replyResolver).toHaveBeenCalledTimes(1);
const ctx = replyResolver.mock.calls[0]?.[0] ?? {};
expect(ctx.SenderE164).toBe("+1000");
expect(ctx.SenderId).toBe("+1000");
});
it("updates last-route for direct chats without senderE164", async () => {
const now = Date.now();
const mainSessionKey = "agent:main:main";
const store = await makeSessionStore({
[mainSessionKey]: { sessionId: "sid", updatedAt: now - 1 },
});
const replyResolver = vi.fn().mockResolvedValue(undefined);
const mockConfig: OpenClawConfig = {
channels: { whatsapp: { allowFrom: ["*"] } },
session: { store: store.storePath },
};
setLoadConfigMock(mockConfig);
await monitorWebChannel(
false,
async ({ onMessage }) => {
await onMessage({
id: "m1",
from: "+1000",
conversationId: "+1000",
to: "+2000",
body: "hello",
timestamp: now,
chatType: "direct",
chatId: "direct:+1000",
sendComposing: vi.fn().mockResolvedValue(undefined),
reply: vi.fn().mockResolvedValue(undefined),
sendMedia: vi.fn().mockResolvedValue(undefined),
});
return { close: vi.fn().mockResolvedValue(undefined) };
},
false,
replyResolver,
);
let stored: Record<string, { lastChannel?: string; lastTo?: string }> | null = null;
for (let attempt = 0; attempt < 50; attempt += 1) {
stored = JSON.parse(await fs.readFile(store.storePath, "utf8")) as Record<
string,
{ lastChannel?: string; lastTo?: string }
>;
if (stored[mainSessionKey]?.lastChannel && stored[mainSessionKey]?.lastTo) {
break;
}
await new Promise((resolve) => setTimeout(resolve, 5));
}
if (!stored) {
throw new Error("store not loaded");
}
expect(stored[mainSessionKey]?.lastChannel).toBe("whatsapp");
expect(stored[mainSessionKey]?.lastTo).toBe("+1000");
resetLoadConfigMock();
await store.cleanup();
});
it("updates last-route for group chats with account id", async () => {
const now = Date.now();
const groupSessionKey = "agent:main:whatsapp:group:123@g.us";
const store = await makeSessionStore({
[groupSessionKey]: { sessionId: "sid", updatedAt: now - 1 },
});
const replyResolver = vi.fn().mockResolvedValue(undefined);
const mockConfig: OpenClawConfig = {
channels: { whatsapp: { allowFrom: ["*"] } },
session: { store: store.storePath },
};
setLoadConfigMock(mockConfig);
await monitorWebChannel(
false,
async ({ onMessage }) => {
await onMessage({
id: "g1",
from: "123@g.us",
conversationId: "123@g.us",
to: "+2000",
body: "hello",
timestamp: now,
chatType: "group",
chatId: "123@g.us",
accountId: "work",
senderE164: "+1000",
senderName: "Alice",
selfE164: "+2000",
sendComposing: vi.fn().mockResolvedValue(undefined),
reply: vi.fn().mockResolvedValue(undefined),
sendMedia: vi.fn().mockResolvedValue(undefined),
});
return { close: vi.fn().mockResolvedValue(undefined) };
},
false,
replyResolver,
);
let stored: Record<
string,
{ lastChannel?: string; lastTo?: string; lastAccountId?: string }
> | null = null;
for (let attempt = 0; attempt < 50; attempt += 1) {
stored = JSON.parse(await fs.readFile(store.storePath, "utf8")) as Record<
string,
{ lastChannel?: string; lastTo?: string; lastAccountId?: string }
>;
if (
stored[groupSessionKey]?.lastChannel &&
stored[groupSessionKey]?.lastTo &&
stored[groupSessionKey]?.lastAccountId
) {
break;
}
await new Promise((resolve) => setTimeout(resolve, 5));
}
if (!stored) {
throw new Error("store not loaded");
}
expect(stored[groupSessionKey]?.lastChannel).toBe("whatsapp");
expect(stored[groupSessionKey]?.lastTo).toBe("123@g.us");
expect(stored[groupSessionKey]?.lastAccountId).toBe("work");
resetLoadConfigMock();
await store.cleanup();
});
it("defaults to self-only when no config is present", async () => {
vi.mocked(runEmbeddedPiAgent).mockResolvedValue({
payloads: [{ text: "ok" }],
meta: {
durationMs: 1,
agentMeta: { sessionId: "s", provider: "p", model: "m" },
},
});
// Not self: should be blocked
const blocked = await getReplyFromConfig(
{
Body: "hi",
From: "whatsapp:+999",
To: "whatsapp:+123",
},
undefined,
{},
);
expect(blocked).toBeUndefined();
expect(runEmbeddedPiAgent).not.toHaveBeenCalled();
// Self: should be allowed
const allowed = await getReplyFromConfig(
{
Body: "hi",
From: "whatsapp:+123",
To: "whatsapp:+123",
},
undefined,
{},
);
expect(allowed).toMatchObject({ text: "ok", audioAsVoice: false });
expect(runEmbeddedPiAgent).toHaveBeenCalledOnce();
});
});
|