File size: 7,329 Bytes
fc93158 | 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 | import fs from "node:fs/promises";
import path from "node:path";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { loadModelCatalog } from "../agents/model-catalog.js";
import type { OpenClawConfig } from "../config/config.js";
import { withTempHome as withTempHomeHarness } from "../config/home-env.test-harness.js";
import { getReplyFromConfig } from "./reply.js";
type RunEmbeddedPiAgent = typeof import("../agents/pi-embedded.js").runEmbeddedPiAgent;
type RunEmbeddedPiAgentParams = Parameters<RunEmbeddedPiAgent>[0];
type RunEmbeddedPiAgentReply = Awaited<ReturnType<RunEmbeddedPiAgent>>;
const piEmbeddedMock = vi.hoisted(() => ({
abortEmbeddedPiRun: vi.fn().mockReturnValue(false),
runEmbeddedPiAgent: vi.fn<RunEmbeddedPiAgent>(),
queueEmbeddedPiMessage: vi.fn().mockReturnValue(false),
resolveEmbeddedSessionLane: (key: string) => `session:${key.trim() || "main"}`,
isEmbeddedPiRunActive: vi.fn().mockReturnValue(false),
isEmbeddedPiRunStreaming: vi.fn().mockReturnValue(false),
}));
vi.mock("/src/agents/pi-embedded.js", () => piEmbeddedMock);
vi.mock("../agents/pi-embedded.js", () => piEmbeddedMock);
vi.mock("../agents/model-catalog.js", () => ({
loadModelCatalog: vi.fn(),
}));
type GetReplyOptions = NonNullable<Parameters<typeof getReplyFromConfig>[1]>;
function createEmbeddedReply(text: string): RunEmbeddedPiAgentReply {
return {
payloads: [{ text }],
meta: {
durationMs: 5,
agentMeta: { sessionId: "s", provider: "p", model: "m" },
},
};
}
function createTelegramMessage(messageSid: string) {
return {
Body: "ping",
From: "+1004",
To: "+2000",
MessageSid: messageSid,
Provider: "telegram",
} as const;
}
function createReplyConfig(home: string, streamMode?: "block"): OpenClawConfig {
return {
agents: {
defaults: {
model: { primary: "anthropic/claude-opus-4-5" },
workspace: path.join(home, "openclaw"),
},
},
channels: { telegram: { allowFrom: ["*"], streamMode } },
session: { store: path.join(home, "sessions.json") },
};
}
async function runTelegramReply(params: {
home: string;
messageSid: string;
onBlockReply?: GetReplyOptions["onBlockReply"];
onReplyStart?: GetReplyOptions["onReplyStart"];
disableBlockStreaming?: boolean;
streamMode?: "block";
}) {
return getReplyFromConfig(
createTelegramMessage(params.messageSid),
{
onReplyStart: params.onReplyStart,
onBlockReply: params.onBlockReply,
disableBlockStreaming: params.disableBlockStreaming,
},
createReplyConfig(params.home, params.streamMode),
);
}
async function withTempHome<T>(fn: (home: string) => Promise<T>): Promise<T> {
return withTempHomeHarness("openclaw-stream-", async (home) => {
await fs.mkdir(path.join(home, ".openclaw", "agents", "main", "sessions"), { recursive: true });
return fn(home);
});
}
describe("block streaming", () => {
beforeEach(() => {
vi.stubEnv("OPENCLAW_TEST_FAST", "1");
piEmbeddedMock.abortEmbeddedPiRun.mockClear().mockReturnValue(false);
piEmbeddedMock.queueEmbeddedPiMessage.mockClear().mockReturnValue(false);
piEmbeddedMock.isEmbeddedPiRunActive.mockClear().mockReturnValue(false);
piEmbeddedMock.isEmbeddedPiRunStreaming.mockClear().mockReturnValue(false);
piEmbeddedMock.runEmbeddedPiAgent.mockClear();
vi.mocked(loadModelCatalog).mockResolvedValue([
{ id: "claude-opus-4-5", name: "Opus 4.5", provider: "anthropic" },
{ id: "gpt-4.1-mini", name: "GPT-4.1 Mini", provider: "openai" },
]);
});
it("handles ordering, timeout fallback, and telegram streamMode block", async () => {
await withTempHome(async (home) => {
let releaseTyping: (() => void) | undefined;
const typingGate = new Promise<void>((resolve) => {
releaseTyping = resolve;
});
let resolveOnReplyStart: (() => void) | undefined;
const onReplyStartCalled = new Promise<void>((resolve) => {
resolveOnReplyStart = resolve;
});
const onReplyStart = vi.fn(() => {
resolveOnReplyStart?.();
return typingGate;
});
const seen: string[] = [];
const onBlockReply = vi.fn(async (payload) => {
seen.push(payload.text ?? "");
});
const impl = async (params: RunEmbeddedPiAgentParams) => {
void params.onBlockReply?.({ text: "first" });
void params.onBlockReply?.({ text: "second" });
return {
payloads: [{ text: "first" }, { text: "second" }],
meta: createEmbeddedReply("first").meta,
};
};
piEmbeddedMock.runEmbeddedPiAgent.mockImplementation(impl);
const replyPromise = runTelegramReply({
home,
messageSid: "msg-123",
onReplyStart,
onBlockReply,
disableBlockStreaming: false,
});
await onReplyStartCalled;
releaseTyping?.();
const res = await replyPromise;
expect(res).toBeUndefined();
expect(seen).toEqual(["first\n\nsecond"]);
const onBlockReplyStreamMode = vi.fn().mockResolvedValue(undefined);
piEmbeddedMock.runEmbeddedPiAgent.mockImplementation(async () =>
createEmbeddedReply("final"),
);
const resStreamMode = await runTelegramReply({
home,
messageSid: "msg-127",
onBlockReply: onBlockReplyStreamMode,
streamMode: "block",
});
const streamPayload = Array.isArray(resStreamMode) ? resStreamMode[0] : resStreamMode;
expect(streamPayload?.text).toBe("final");
expect(onBlockReplyStreamMode).not.toHaveBeenCalled();
});
});
it("trims leading whitespace in block-streamed replies", async () => {
await withTempHome(async (home) => {
const seen: string[] = [];
const onBlockReply = vi.fn(async (payload) => {
seen.push(payload.text ?? "");
});
piEmbeddedMock.runEmbeddedPiAgent.mockImplementation(
async (params: RunEmbeddedPiAgentParams) => {
void params.onBlockReply?.({ text: "\n\n Hello from stream" });
return createEmbeddedReply("\n\n Hello from stream");
},
);
const res = await runTelegramReply({
home,
messageSid: "msg-128",
onBlockReply,
disableBlockStreaming: false,
});
expect(res).toBeUndefined();
expect(onBlockReply).toHaveBeenCalledTimes(1);
expect(seen).toEqual(["Hello from stream"]);
});
});
it("still parses media directives for direct block payloads", async () => {
await withTempHome(async (home) => {
const onBlockReply = vi.fn();
piEmbeddedMock.runEmbeddedPiAgent.mockImplementation(
async (params: RunEmbeddedPiAgentParams) => {
void params.onBlockReply?.({ text: "Result\nMEDIA: ./image.png" });
return createEmbeddedReply("Result\nMEDIA: ./image.png");
},
);
const res = await runTelegramReply({
home,
messageSid: "msg-129",
onBlockReply,
disableBlockStreaming: false,
});
expect(res).toBeUndefined();
expect(onBlockReply).toHaveBeenCalledTimes(1);
expect(onBlockReply.mock.calls[0][0]).toMatchObject({
text: "Result",
mediaUrls: [path.join(home, "openclaw", "image.png")],
});
});
});
});
|