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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. import { DatabaseSync } from "node:sqlite";
  2. import { join } from "node:path";
  3. import { readFile } from "node:fs/promises";
  4. import { createBotWorkerIntegration } from "#e2e/helpers/bot-worker-integration";
  5. import { installBotPlatformFixture } from "#e2e/helpers/bot-platform-fixture";
  6. import { startConversationModelProviderReplayServer } from "#e2e/helpers/model-provider-replay";
  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 ordered message content"))
  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. expect(mentions).not.toContain("ReplyToChannel");
  180. expect(mentions).not.toContain('"refId"');
  181. const positioned = strings
  182. .filter((value) => value.includes("Trusted ordered message content"))
  183. .join("\n");
  184. expect(positioned).toContain(
  185. '"isCurrentBot":true},{"type":"text","text":" E2E_BOT_TOPIC_NEXT\\n"}',
  186. );
  187. expect(positioned).toContain(
  188. '"isCurrentBot":false},{"type":"text","text":" handle outline"}',
  189. );
  190. expect(positioned).not.toContain('"targetId"');
  191. expect(nextSource.topicContext?.messages.some((message) => message.id === "om_other")).toBe(
  192. true,
  193. );
  194. expect(group.backgroundHistory).toBeUndefined();
  195. expect(
  196. Object.values(group.deliveries!).some((d) => d.text.includes("E2E_TOPIC_OLD_FINAL")),
  197. ).toBe(false);
  198. expect(platform.requests.some((r) => r.body?.includes("Waiting to run"))).toBe(false);
  199. payload.event.sender.sender_id.open_id = "ou_other_bot";
  200. payload.event.message.mentions = [];
  201. payload.event.message.message_type = "text";
  202. for (let i = 2; i <= 5; i++) {
  203. const id = `om_bot_turn_${i}`;
  204. const text = i === 5 ? "E2E_BOT_TOPIC_SLOW" : "E2E_BOT_TOPIC_NEXT";
  205. platform.add(id, text);
  206. payload.event.message.content = JSON.stringify({ text });
  207. payload.event.message.message_id = id;
  208. await host.bot.service.handleProviderCallback("feishu", payload);
  209. }
  210. const fifthInputId = Object.entries(host.bot.readState().bots[key]!.group!.inputs!).find(
  211. ([, entry]) => entry.source.messageId === "om_bot_turn_5",
  212. )![0];
  213. await browser.waitUntil(
  214. async () =>
  215. (await host.task.readBotTopicExecution!({ workspacePath: host.workspacePath, taskId }))
  216. ?.sourceCommandId === fifthInputId,
  217. { timeout: 30000 },
  218. );
  219. order.length = 0;
  220. payload.event.message.content = JSON.stringify({ text: "E2E_BOT_TOPIC_NEXT" });
  221. payload.event.message.message_id = "om_bot_turn_6";
  222. platform.add("om_bot_turn_6", "E2E_BOT_TOPIC_NEXT");
  223. await host.bot.service.handleProviderCallback("feishu", payload);
  224. expect(order).toEqual([]);
  225. expect(
  226. Object.values(host.bot.readState().bots[key]!.group!.inputs!).some(
  227. (entry) => entry.source.messageId === "om_bot_turn_6",
  228. ),
  229. ).toBe(false);
  230. await send("om_human_resume", "E2E_BOT_TOPIC_NEXT");
  231. payload.event.message.message_id = "om_bot_resumed";
  232. platform.add("om_bot_resumed", "E2E_BOT_TOPIC_NEXT");
  233. await host.bot.service.handleProviderCallback("feishu", payload);
  234. expect(
  235. Object.values(host.bot.readState().bots[key]!.group!.inputs!).some(
  236. (entry) => entry.source.messageId === "om_bot_resumed" && entry.admission === "accepted",
  237. ),
  238. ).toBe(true);
  239. await send("om_batch_running", "E2E_BOT_TOPIC_SLOW");
  240. await browser.waitUntil(
  241. async () =>
  242. !!(await host.task.readBotTopicExecution!({ workspacePath: host.workspacePath, taskId }))
  243. ?.executionId,
  244. { timeout: 30000 },
  245. );
  246. const entered = Promise.withResolvers<void>();
  247. const releaseBatch = Promise.withResolvers<void>();
  248. Object.assign(host.bot.zcodeTaskService, {
  249. stopBotTopicExecution: async (...args: Parameters<typeof stop>) => {
  250. entered.resolve();
  251. await releaseBatch.promise;
  252. await stop(...args);
  253. },
  254. });
  255. const batchMessage = (id: string, text: string, commandText: string) => {
  256. platform.add(id, text);
  257. return host.bot.service.handleInboundMessage({
  258. botId: actor.botId,
  259. actor: {
  260. ...actor,
  261. threadId: "omt_worker",
  262. rootMessageId: "om_root",
  263. providerMessageId: id,
  264. },
  265. text,
  266. commandText,
  267. mentionedBot: true,
  268. });
  269. };
  270. const requirement = batchMessage(
  271. "om_batch_request",
  272. "@Bot E2E_BOT_TOPIC_NEXT",
  273. "E2E_BOT_TOPIC_NEXT",
  274. );
  275. await entered.promise;
  276. const wakeup = batchMessage("om_batch_wakeup", "@Bot", "");
  277. try {
  278. await browser.waitUntil(
  279. async () =>
  280. (await host.bot.service.getBotStates()).find(
  281. (state) => state.group?.threadId === "omt_worker",
  282. )?.group?.preparation?.length === 2,
  283. { timeout: 10000 },
  284. );
  285. } finally {
  286. releaseBatch.resolve();
  287. }
  288. await Promise.all([requirement, wakeup]);
  289. const acceptedBatch = Object.values(host.bot.readState().bots[key]!.group!.inputs!).find(
  290. (entry) => entry.source.messageId === "om_batch_wakeup",
  291. );
  292. expect(acceptedBatch?.admission).toBe("accepted");
  293. expect(acceptedBatch?.source.messages?.map((message) => message.text)).toEqual([
  294. "@Bot E2E_BOT_TOPIC_NEXT",
  295. "@Bot",
  296. ]);
  297. } finally {
  298. await cleanup?.dispose();
  299. platform.restore();
  300. await replay.stop();
  301. }
  302. });
  303. it("downloads admitted historical resources through the actual ReadTopicResource tool", async function () {
  304. this.timeout(180000);
  305. const replay = await startConversationModelProviderReplayServer(
  306. "conversation-session-bot-topic-worker",
  307. );
  308. const platform = installBotPlatformFixture();
  309. let cleanup: Awaited<ReturnType<typeof createBotWorkerIntegration>> | undefined;
  310. try {
  311. const host = (cleanup = await createBotWorkerIntegration(replay.baseUrl));
  312. platform.add("om_root", "Topic root");
  313. platform.add("om_archive", "file", "file");
  314. platform.add("om_request", "E2E_BOT_TOPIC_RESOURCE");
  315. await host.bot.service.handleInboundMessage({ botId: actor.botId, actor, text: "/enable" });
  316. const input: BotInboundMessage = {
  317. botId: actor.botId,
  318. text: "E2E_BOT_TOPIC_RESOURCE",
  319. actor: {
  320. ...actor,
  321. threadId: "omt_worker",
  322. rootMessageId: "om_root",
  323. providerMessageId: "om_request",
  324. },
  325. };
  326. await host.bot.service.handleInboundMessage(input);
  327. await browser.waitUntil(
  328. async () =>
  329. Object.values(host.bot.readState().bots[key]?.group?.deliveries ?? {}).some(
  330. (d) => d.text.includes("E2E_RESOURCE_DONE") && d.status === "sent",
  331. ),
  332. { timeout: 60000 },
  333. );
  334. expect(host.reverseResources).toHaveLength(1);
  335. const taskId = host.bot.readState().bots[key]!.activeTaskId!;
  336. // Node SQLite 只提供同步查询;只读隔离 CLI 持久工具结果并立即关闭。
  337. const database = new DatabaseSync(join(host.home, ".zcode/cli/db/db.sqlite"), {
  338. readOnly: true,
  339. });
  340. let resource: { fileName: string; path: string; bytes: number };
  341. try {
  342. const records = database
  343. .prepare("select data from part where session_id = ?")
  344. .all(taskId) as Array<{ data: string }>;
  345. const tool = records
  346. .map((row) => JSON.parse(row.data))
  347. .find((part) => part.type === "tool" && part.tool === "ReadTopicResource");
  348. expect(tool?.state.status).toBe("completed");
  349. // 会话工具设计 0.8:资源下载从 ReadSessionContext(topic, attachment) 拆成专用工具,结果只含路径与元数据。
  350. resource =
  351. typeof tool.state.output === "string" ? JSON.parse(tool.state.output) : tool.state.output;
  352. expect(resource).toMatchObject({ status: "success", messageId: "om_archive", index: 0 });
  353. } finally {
  354. database.close();
  355. }
  356. expect(resource.fileName).toBe("archive.txt");
  357. expect(resource.bytes).toBe(Buffer.byteLength("E2E_ARCHIVE_FILE_CONTENT"));
  358. expect(resource.path.startsWith(host.home)).toBe(true);
  359. expect(await readFile(resource.path, "utf8")).toBe("E2E_ARCHIVE_FILE_CONTENT");
  360. const downloads = platform.requests.filter((r) => r.url.includes("/resources/"));
  361. expect(downloads).toHaveLength(1);
  362. expect(downloads[0]!.url).toContain("/om_archive/resources/file_e2e");
  363. const request = host.reverseResources[0] as Parameters<
  364. NonNullable<typeof host.bot.service.readTopicResource>
  365. >[0];
  366. await expect(
  367. host.bot.service.readTopicResource!({ ...request, taskId: "other-task" }),
  368. ).rejects.toThrow();
  369. expect(platform.requests.filter((r) => r.url.includes("/resources/"))).toHaveLength(1);
  370. } finally {
  371. await cleanup?.dispose();
  372. platform.restore();
  373. await replay.stop();
  374. }
  375. });
  376. });