conversation-session-bot-topic-worker.test.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. import { DatabaseSync } from "node:sqlite";
  2. import { join } from "node:path";
  3. import { readFile } from "node:fs/promises";
  4. import { createBotWorkerIntegration } from "../helpers/bot-worker-integration.js";
  5. import { installBotPlatformFixture } from "../helpers/bot-platform-fixture.js";
  6. import { startConversationModelProviderReplayServer } from "../helpers/model-provider-replay.js";
  7. import type { BotInboundMessage } from "@zcode/shared";
  8. const actor = {
  9. botId: "bot-worker",
  10. provider: "feishu" as const,
  11. chatType: "group" as const,
  12. chatId: "oc_worker",
  13. providerUserId: "ou_e2e_user",
  14. };
  15. const key = JSON.stringify([actor.botId, actor.chatId, "omt_worker"]);
  16. describe("BOT-E2E-TP-04/05 real topic worker", () => {
  17. it("automatically stops a running topic before admitting the next message", async function () {
  18. this.timeout(180000);
  19. const replay = await startConversationModelProviderReplayServer(
  20. "conversation-session-bot-topic-worker",
  21. );
  22. const platform = installBotPlatformFixture();
  23. let cleanup: Awaited<ReturnType<typeof createBotWorkerIntegration>> | undefined;
  24. try {
  25. const host = (cleanup = await createBotWorkerIntegration(replay.baseUrl));
  26. const order: string[] = [];
  27. const stop = host.task.stopBotTopicExecution!;
  28. const submit = host.task.submitBotGroupInput!;
  29. Object.assign(host.bot.zcodeTaskService, {
  30. stopBotTopicExecution: async (...args: Parameters<typeof stop>) => {
  31. order.push("stop");
  32. await stop(...args);
  33. order.push("stopped");
  34. },
  35. submitBotGroupInput: async (...args: Parameters<typeof submit>) => {
  36. order.push("submit");
  37. return submit(...args);
  38. },
  39. });
  40. const send = async (id: string, text: string) => {
  41. platform.add(id, text);
  42. return host.bot.service.handleInboundMessage({
  43. botId: actor.botId,
  44. actor: {
  45. ...actor,
  46. threadId: "omt_worker",
  47. rootMessageId: "om_root",
  48. providerMessageId: id,
  49. },
  50. text,
  51. });
  52. };
  53. await host.bot.service.handleInboundMessage({ botId: actor.botId, actor, text: "/enable" });
  54. const replies = await send("om_root", "E2E_BOT_TOPIC_SLOW");
  55. if (!host.bot.readState().bots[key])
  56. throw new Error(`Topic was not admitted: ${JSON.stringify(replies)}`);
  57. let taskId = "";
  58. await browser.waitUntil(
  59. async () => {
  60. taskId = host.bot.readState().bots[key]?.activeTaskId ?? "";
  61. return (
  62. !!taskId &&
  63. !!(
  64. await host.task.readBotTopicExecution!({ workspacePath: host.workspacePath, taskId })
  65. )?.executionId
  66. );
  67. },
  68. { timeout: 60000 },
  69. );
  70. await browser.waitUntil(
  71. async () => host.observedTextEvents.some((text) => text.includes("E2E_TOPIC_RUNNING")),
  72. { timeout: 30000 },
  73. );
  74. order.length = 0;
  75. // 原生 @ 指向别人时,运行中的真实 CLI 不能被停止,也不能接收对方任务。
  76. platform.add("om_other", "@Other Bot handle the outline");
  77. await host.bot.service.handleProviderCallback("feishu", {
  78. botId: actor.botId,
  79. zcodeBotOpenId: "ou_current_bot",
  80. event: {
  81. sender: { sender_type: "user", sender_id: { open_id: "ou_e2e_user" } },
  82. message: {
  83. chat_type: "group",
  84. chat_id: actor.chatId,
  85. thread_id: "omt_worker",
  86. root_id: "om_root",
  87. message_id: "om_other",
  88. message_type: "text",
  89. content: JSON.stringify({ text: "@_other handle the outline" }),
  90. mentions: [{ key: "@_other", id: { open_id: "ou_other_bot" }, name: "Other Bot" }],
  91. },
  92. },
  93. });
  94. expect(order).toEqual([]);
  95. expect(
  96. Object.values(host.bot.readState().bots[key]!.group!.inputs!).map(
  97. (i) => i.source.messageId,
  98. ),
  99. ).toEqual(["om_root"]);
  100. expect(host.bot.readState().bots[key]!.group!.backgroundHistory?.checkpoint).toBe("om_root");
  101. platform.add("om_next", "E2E_BOT_TOPIC_NEXT");
  102. const payload = {
  103. botId: actor.botId,
  104. zcodeBotOpenId: "ou_current_bot",
  105. event: {
  106. sender: { sender_type: "bot", sender_id: { open_id: "ou_other_bot" } },
  107. message: {
  108. chat_type: "group",
  109. chat_id: actor.chatId,
  110. thread_id: "omt_worker",
  111. root_id: "om_root",
  112. message_id: "om_next",
  113. message_type: "interactive",
  114. content: JSON.stringify({
  115. schema: "2.0",
  116. body: {
  117. elements: [
  118. {
  119. tag: "markdown",
  120. content:
  121. "<at id=ou_self_sender_scope></at> E2E_BOT_TOPIC_NEXT\n<at id=ou_other_sender_scope></at> handle outline",
  122. },
  123. ],
  124. },
  125. }),
  126. mentions: [
  127. { key: "@_self", id: { open_id: "ou_current_bot" }, name: "Assistant" },
  128. { key: "@_other", id: { open_id: "ou_recipient" }, name: "Assistant" },
  129. ],
  130. },
  131. },
  132. };
  133. await host.bot.service.handleProviderCallback("feishu", payload);
  134. await host.bot.service.handleProviderCallback("feishu", payload);
  135. payload.event.sender.sender_id.open_id = "ou_current_bot";
  136. payload.event.message.message_id = "om_self_echo";
  137. expect(await host.bot.service.handleProviderCallback("feishu", payload)).toEqual([]);
  138. await browser.waitUntil(
  139. async () =>
  140. Object.values(host.bot.readState().bots[key]?.group?.deliveries ?? {}).some(
  141. (d) => d.status === "sent" && d.text.includes("E2E_TOPIC_NEXT_DONE"),
  142. ),
  143. { timeout: 60000 },
  144. );
  145. expect(order).toEqual(["stop", "stopped", "submit"]);
  146. expect(
  147. Object.values(host.bot.readState().bots[key]!.group!.inputs!).at(-1)?.source.senderId,
  148. ).toBe("ou_other_bot");
  149. const group = host.bot.readState().bots[key]!.group!;
  150. expect(Object.values(group.inputs!).map((i) => i.source.messageId)).toEqual([
  151. "om_root",
  152. "om_next",
  153. ]);
  154. expect(Object.values(group.inputs!).every((i) => i.admission === "accepted")).toBe(true);
  155. const nextSource = Object.values(group.inputs!).at(-1)!.source;
  156. expect(nextSource.messages?.[0]?.text).toBe(
  157. "@Assistant E2E_BOT_TOPIC_NEXT\n@Assistant handle outline",
  158. );
  159. expect(
  160. nextSource.messages?.[0]?.contentParts
  161. ?.filter((part) => part.type === "channelMention")
  162. .map((part) => part.targetId),
  163. ).toEqual(["ou_current_bot", "ou_recipient"]);
  164. expect(nextSource.botIdentity?.openId).toBe("ou_current_bot");
  165. const captured = JSON.parse(await readFile(replay.artifactPath, "utf8"));
  166. const strings: string[] = [];
  167. const collect = (value: unknown): void => {
  168. if (typeof value === "string") strings.push(value);
  169. else if (Array.isArray(value)) value.forEach(collect);
  170. else if (value && typeof value === "object") Object.values(value).forEach(collect);
  171. };
  172. collect(captured);
  173. const mentions = strings
  174. .filter((value) => value.includes("Trusted native mention references"))
  175. .join("\n");
  176. expect(mentions).toContain('"name":"Assistant","channel":"feishu","isCurrentBot":true');
  177. expect(mentions).toContain('"name":"Assistant","channel":"feishu","isCurrentBot":false');
  178. expect(mentions).not.toContain("ou_recipient");
  179. const positioned = strings
  180. .filter((value) => value.includes("Trusted ordered message content"))
  181. .join("\n");
  182. expect(positioned).toContain(
  183. '"isCurrentBot":true},{"type":"text","text":" E2E_BOT_TOPIC_NEXT\\n"}',
  184. );
  185. expect(positioned).toContain(
  186. '"isCurrentBot":false},{"type":"text","text":" handle outline"}',
  187. );
  188. expect(positioned).not.toContain('"targetId"');
  189. expect(nextSource.topicContext?.messages.some((message) => message.id === "om_other")).toBe(
  190. true,
  191. );
  192. expect(group.backgroundHistory).toBeUndefined();
  193. expect(
  194. Object.values(group.deliveries!).some((d) => d.text.includes("E2E_TOPIC_OLD_FINAL")),
  195. ).toBe(false);
  196. expect(platform.requests.some((r) => r.body?.includes("Waiting to run"))).toBe(false);
  197. payload.event.sender.sender_id.open_id = "ou_other_bot";
  198. payload.event.message.mentions = [];
  199. payload.event.message.message_type = "text";
  200. for (let i = 2; i <= 5; i++) {
  201. const id = `om_bot_turn_${i}`;
  202. const text = i === 5 ? "E2E_BOT_TOPIC_SLOW" : "E2E_BOT_TOPIC_NEXT";
  203. platform.add(id, text);
  204. payload.event.message.content = JSON.stringify({ text });
  205. payload.event.message.message_id = id;
  206. await host.bot.service.handleProviderCallback("feishu", payload);
  207. }
  208. const fifthInputId = Object.entries(host.bot.readState().bots[key]!.group!.inputs!).find(
  209. ([, entry]) => entry.source.messageId === "om_bot_turn_5",
  210. )![0];
  211. await browser.waitUntil(
  212. async () =>
  213. (await host.task.readBotTopicExecution!({ workspacePath: host.workspacePath, taskId }))
  214. ?.sourceCommandId === fifthInputId,
  215. { timeout: 30000 },
  216. );
  217. order.length = 0;
  218. payload.event.message.content = JSON.stringify({ text: "E2E_BOT_TOPIC_NEXT" });
  219. payload.event.message.message_id = "om_bot_turn_6";
  220. platform.add("om_bot_turn_6", "E2E_BOT_TOPIC_NEXT");
  221. await host.bot.service.handleProviderCallback("feishu", payload);
  222. expect(order).toEqual([]);
  223. expect(
  224. Object.values(host.bot.readState().bots[key]!.group!.inputs!).some(
  225. (entry) => entry.source.messageId === "om_bot_turn_6",
  226. ),
  227. ).toBe(false);
  228. await send("om_human_resume", "E2E_BOT_TOPIC_NEXT");
  229. payload.event.message.message_id = "om_bot_resumed";
  230. platform.add("om_bot_resumed", "E2E_BOT_TOPIC_NEXT");
  231. await host.bot.service.handleProviderCallback("feishu", payload);
  232. expect(
  233. Object.values(host.bot.readState().bots[key]!.group!.inputs!).some(
  234. (entry) => entry.source.messageId === "om_bot_resumed" && entry.admission === "accepted",
  235. ),
  236. ).toBe(true);
  237. await send("om_batch_running", "E2E_BOT_TOPIC_SLOW");
  238. await browser.waitUntil(
  239. async () =>
  240. !!(await host.task.readBotTopicExecution!({ workspacePath: host.workspacePath, taskId }))
  241. ?.executionId,
  242. { timeout: 30000 },
  243. );
  244. const entered = Promise.withResolvers<void>();
  245. const releaseBatch = Promise.withResolvers<void>();
  246. Object.assign(host.bot.zcodeTaskService, {
  247. stopBotTopicExecution: async (...args: Parameters<typeof stop>) => {
  248. entered.resolve();
  249. await releaseBatch.promise;
  250. await stop(...args);
  251. },
  252. });
  253. const batchMessage = (id: string, text: string, commandText: string) => {
  254. platform.add(id, text);
  255. return host.bot.service.handleInboundMessage({
  256. botId: actor.botId,
  257. actor: {
  258. ...actor,
  259. threadId: "omt_worker",
  260. rootMessageId: "om_root",
  261. providerMessageId: id,
  262. },
  263. text,
  264. commandText,
  265. mentionedBot: true,
  266. });
  267. };
  268. const requirement = batchMessage(
  269. "om_batch_request",
  270. "@Bot E2E_BOT_TOPIC_NEXT",
  271. "E2E_BOT_TOPIC_NEXT",
  272. );
  273. await entered.promise;
  274. const wakeup = batchMessage("om_batch_wakeup", "@Bot", "");
  275. try {
  276. await browser.waitUntil(
  277. async () =>
  278. (await host.bot.service.getBotStates()).find(
  279. (state) => state.group?.threadId === "omt_worker",
  280. )?.group?.preparation?.length === 2,
  281. { timeout: 10000 },
  282. );
  283. } finally {
  284. releaseBatch.resolve();
  285. }
  286. await Promise.all([requirement, wakeup]);
  287. const acceptedBatch = Object.values(host.bot.readState().bots[key]!.group!.inputs!).find(
  288. (entry) => entry.source.messageId === "om_batch_wakeup",
  289. );
  290. expect(acceptedBatch?.admission).toBe("accepted");
  291. expect(acceptedBatch?.source.messages?.map((message) => message.text)).toEqual([
  292. "@Bot E2E_BOT_TOPIC_NEXT",
  293. "@Bot",
  294. ]);
  295. } finally {
  296. await cleanup?.dispose();
  297. platform.restore();
  298. await replay.stop();
  299. }
  300. });
  301. it("downloads admitted historical resources through the actual ReadSessionContext tool", async function () {
  302. this.timeout(180000);
  303. const replay = await startConversationModelProviderReplayServer(
  304. "conversation-session-bot-topic-worker",
  305. );
  306. const platform = installBotPlatformFixture();
  307. let cleanup: Awaited<ReturnType<typeof createBotWorkerIntegration>> | undefined;
  308. try {
  309. const host = (cleanup = await createBotWorkerIntegration(replay.baseUrl));
  310. platform.add("om_root", "Topic root");
  311. platform.add("om_archive", "file", "file");
  312. platform.add("om_request", "E2E_BOT_TOPIC_RESOURCE");
  313. await host.bot.service.handleInboundMessage({ botId: actor.botId, actor, text: "/enable" });
  314. const input: BotInboundMessage = {
  315. botId: actor.botId,
  316. text: "E2E_BOT_TOPIC_RESOURCE",
  317. actor: {
  318. ...actor,
  319. threadId: "omt_worker",
  320. rootMessageId: "om_root",
  321. providerMessageId: "om_request",
  322. },
  323. };
  324. await host.bot.service.handleInboundMessage(input);
  325. await browser.waitUntil(
  326. async () =>
  327. Object.values(host.bot.readState().bots[key]?.group?.deliveries ?? {}).some(
  328. (d) => d.text.includes("E2E_RESOURCE_DONE") && d.status === "sent",
  329. ),
  330. { timeout: 60000 },
  331. );
  332. expect(host.reverseResources).toHaveLength(1);
  333. const taskId = host.bot.readState().bots[key]!.activeTaskId!;
  334. // Node SQLite 只提供同步查询;只读隔离 CLI 持久工具结果并立即关闭。
  335. const database = new DatabaseSync(join(host.home, ".zcode/cli/db/db.sqlite"), {
  336. readOnly: true,
  337. });
  338. let resource: { fileName: string; path: string; bytes: number };
  339. try {
  340. const records = database
  341. .prepare("select data from part where session_id = ?")
  342. .all(taskId) as Array<{ data: string }>;
  343. const tool = records
  344. .map((row) => JSON.parse(row.data))
  345. .find((part) => part.type === "tool" && part.tool === "ReadSessionContext");
  346. expect(tool?.state.status).toBe("completed");
  347. expect(tool.state.output).toContain(
  348. `ReadSessionContext returned local context for ${taskId}.`,
  349. );
  350. resource = JSON.parse(tool.state.output.split("\n").slice(1).join("\n"));
  351. } finally {
  352. database.close();
  353. }
  354. expect(resource.fileName).toBe("archive.txt");
  355. expect(resource.bytes).toBe(Buffer.byteLength("E2E_ARCHIVE_FILE_CONTENT"));
  356. expect(resource.path.startsWith(host.home)).toBe(true);
  357. expect(await readFile(resource.path, "utf8")).toBe("E2E_ARCHIVE_FILE_CONTENT");
  358. const downloads = platform.requests.filter((r) => r.url.includes("/resources/"));
  359. expect(downloads).toHaveLength(1);
  360. expect(downloads[0]!.url).toContain("/om_archive/resources/file_e2e");
  361. const request = host.reverseResources[0] as Parameters<
  362. NonNullable<typeof host.bot.service.readTopicResource>
  363. >[0];
  364. await expect(
  365. host.bot.service.readTopicResource!({ ...request, taskId: "other-task" }),
  366. ).rejects.toThrow();
  367. expect(platform.requests.filter((r) => r.url.includes("/resources/"))).toHaveLength(1);
  368. } finally {
  369. await cleanup?.dispose();
  370. platform.restore();
  371. await replay.stop();
  372. }
  373. });
  374. });