feishu-channel-mention.test.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  1. import { channelContentText, type BotActor, type ChannelContentPart } from "@zcode/shared";
  2. import {
  3. createBotsServiceHarness,
  4. createFeishuConfig,
  5. createRecordingFeishuFetch,
  6. readBotSyntheticFixture,
  7. type RecordedRequest,
  8. } from "#e2e/bots/helpers/bots-service-harness";
  9. describe("BOT-E2E-MN-01 native channel mentions", () => {
  10. for (const provider of ["feishu", "lark"] as const) {
  11. for (const topic of [false, true]) {
  12. it(`${provider}: preserves targets and delivers once (topic=${topic})`, async () => {
  13. const fixture = await readBotSyntheticFixture("feishu-channel-mention.json");
  14. expect(fixture.classification).toBe("synthetic");
  15. const requests: RecordedRequest[] = [];
  16. const originalFetch = globalThis.fetch;
  17. const record = createRecordingFeishuFetch(requests);
  18. let sendBarrier: { started: () => void; released: Promise<void> } | undefined;
  19. let parentReads = 0;
  20. globalThis.fetch = async (input, init) => {
  21. const url = String(input);
  22. if (sendBarrier && url.includes("/om_input/reply")) {
  23. sendBarrier.started();
  24. await sendBarrier.released;
  25. }
  26. if (url.includes("/im/v1/messages/om_options"))
  27. return Response.json({
  28. code: 0,
  29. data: {
  30. items: [
  31. {
  32. message_id: "om_options",
  33. chat_id: "oc_group",
  34. ...(topic ? { thread_id: "omt_native" } : {}),
  35. msg_type: "interactive",
  36. sender: { id: "ou_other_bot", sender_type: "app" },
  37. body: {
  38. content: JSON.stringify({
  39. elements: [
  40. { tag: "markdown", content: "Select workspace" },
  41. {
  42. tag: "button",
  43. text: { content: "Select" },
  44. value: { command: "/workspace" },
  45. },
  46. ],
  47. }),
  48. },
  49. },
  50. ],
  51. },
  52. });
  53. if (url.includes("/im/v1/messages/om_bot_parent")) {
  54. parentReads++;
  55. return Response.json({
  56. code: 0,
  57. data: {
  58. items: [
  59. {
  60. message_id: "om_bot_parent",
  61. chat_id: "oc_group",
  62. msg_type: "text",
  63. body: { content: JSON.stringify({ text: "Parent bot context" }) },
  64. },
  65. ],
  66. },
  67. });
  68. }
  69. if (url.endsWith("/bot/v3/info"))
  70. return Response.json({ code: 0, bot: { open_id: "ou_bot" } });
  71. if (url.includes("/members?"))
  72. return Response.json({
  73. code: 0,
  74. data: {
  75. items: [
  76. { member_id: "ou_directory", name: "Directory User" },
  77. { member_id: "ou_alex_a", name: "Alex" },
  78. { member_id: "ou_alex_b", name: "Alex" },
  79. ],
  80. has_more: false,
  81. },
  82. });
  83. if (url.includes("/im/v1/chats/"))
  84. return Response.json({
  85. code: 0,
  86. data: { name: "Synthetic group", chat_mode: "group" },
  87. });
  88. if (url.includes("/im/v1/messages?"))
  89. return Response.json({
  90. code: 0,
  91. data: {
  92. items: [
  93. {
  94. message_id: "om_input",
  95. chat_id: "oc_group",
  96. thread_id: "omt_native",
  97. msg_type: "text",
  98. body: {
  99. content: JSON.stringify({ text: "E2E_CHANNEL_MENTION 帮我 @Ryan Bot" }),
  100. },
  101. sender: { id: "ou_e2e_user", sender_type: "user" },
  102. create_time: "2",
  103. },
  104. ],
  105. has_more: false,
  106. },
  107. });
  108. if (url.endsWith("/im/v1/messages/om_root"))
  109. return Response.json({
  110. code: 0,
  111. data: {
  112. items: [
  113. {
  114. message_id: "om_root",
  115. chat_id: "oc_group",
  116. thread_id: "omt_native",
  117. msg_type: "text",
  118. body: { content: JSON.stringify({ text: "Root" }) },
  119. sender: { id: "ou_e2e_user", sender_type: "user" },
  120. create_time: "1",
  121. },
  122. ],
  123. },
  124. });
  125. return record(input, init);
  126. };
  127. const botId = `${provider}-native-${topic}`;
  128. const h = createBotsServiceHarness({ config: createFeishuConfig(provider, botId) });
  129. h.zcodeTaskService.readBotTopicExecution = async () => undefined;
  130. h.zcodeTaskService.invalidateBotTopicInputs = async () => undefined;
  131. h.zcodeTaskService.submitBotGroupInput = async (params: { commandId: string }) => ({
  132. commandId: params.commandId,
  133. status: "accepted",
  134. revisionAtDecision: 1,
  135. result: { type: "inputAccepted", inputId: params.commandId, delivery: "startNow" },
  136. });
  137. const actor: BotActor = {
  138. botId,
  139. provider,
  140. chatType: "group",
  141. chatId: "oc_group",
  142. providerUserId: "ou_e2e_user",
  143. };
  144. try {
  145. await h.service.handleInboundMessage({ botId, actor, text: "/enable" });
  146. const commandReply = await h.service.handleProviderCallback(provider, {
  147. botId,
  148. zcodeBotOpenId: "ou_bot",
  149. event: {
  150. sender: { sender_type: "user", sender_id: { open_id: actor.providerUserId } },
  151. message: {
  152. chat_type: "group",
  153. chat_id: actor.chatId,
  154. message_id: "om_workspace",
  155. message_type: "text",
  156. content: JSON.stringify({ text: "@_self /workspace" }),
  157. mentions: [{ key: "@_self", id: { open_id: "ou_bot" }, name: "Current Bot" }],
  158. },
  159. },
  160. });
  161. expect(commandReply[0]?.selection?.action).toBe("workspace.set");
  162. const parts: ChannelContentPart[] = [
  163. { type: "text", text: `${fixture.promptMarker} 帮我 ` },
  164. {
  165. type: "channelMention",
  166. refId: "om_input:m1",
  167. channel: provider,
  168. targetId: "ou_target",
  169. idType: "open_id",
  170. entityType: "unknown",
  171. name: "Ryan Bot",
  172. },
  173. ];
  174. await h.service.handleInboundMessage({
  175. botId,
  176. actor: {
  177. ...actor,
  178. providerMessageId: "om_input",
  179. ...(topic ? { threadId: "omt_native", rootMessageId: "om_root" } : {}),
  180. },
  181. text: `${fixture.promptMarker} 帮我 @Ryan Bot`,
  182. contentParts: parts,
  183. });
  184. const state = Object.values(h.readState().bots).find(
  185. (context) =>
  186. context.group?.threadId === (topic ? "omt_native" : undefined) &&
  187. context.group?.inputs &&
  188. Object.keys(context.group.inputs).length,
  189. )!;
  190. const [inputId, input] = Object.entries(state.group!.inputs!)[0]!;
  191. expect(
  192. await h.service.handleProviderCallback(provider, {
  193. botId,
  194. zcodeBotOpenId: "ou_bot",
  195. event: {
  196. sender: { sender_type: "bot", sender_id: { open_id: "ou_other_bot" } },
  197. message: {
  198. message_id: "om_plain_card",
  199. chat_id: actor.chatId,
  200. chat_type: "group",
  201. message_type: "interactive",
  202. ...(topic ? { thread_id: "omt_native", root_id: "om_root" } : {}),
  203. mentions: [{ key: "@_self", id: { open_id: "ou_bot" }, name: "Current Bot" }],
  204. content: JSON.stringify({
  205. schema: "2.0",
  206. body: {
  207. elements: [
  208. {
  209. tag: "markdown",
  210. content: "<at id=ou_sender_scope></at> What date is today?",
  211. },
  212. ],
  213. },
  214. }),
  215. },
  216. },
  217. }),
  218. ).toEqual([]);
  219. const afterPlain = Object.values(h.readState().bots).find(
  220. (context) => context.activeTaskId === state.activeTaskId,
  221. )!;
  222. const plainSource = Object.values(afterPlain.group!.inputs!).at(-1)?.source;
  223. expect(
  224. plainSource?.messages?.[0]?.text ?? channelContentText(plainSource?.contentParts ?? []),
  225. ).toBe("@Current Bot What date is today?");
  226. const beforeInputs = Object.keys(afterPlain.group!.inputs!);
  227. const beforeGuard = structuredClone(afterPlain.group!.autoReplyGuard);
  228. expect(
  229. await h.service.handleProviderCallback(provider, {
  230. botId,
  231. zcodeBotOpenId: "ou_bot",
  232. event: {
  233. sender: { sender_type: "bot", sender_id: { open_id: "ou_other_bot" } },
  234. message: {
  235. chat_id: actor.chatId,
  236. chat_type: "group",
  237. message_id: "om_options",
  238. message_type: "interactive",
  239. ...(topic ? { thread_id: "omt_native", root_id: "om_root" } : {}),
  240. mentions: [{ key: "@_self", id: { open_id: "ou_bot" }, name: "Current Bot" }],
  241. content: JSON.stringify({
  242. body: {
  243. elements: [
  244. { tag: "markdown", content: "@_self Select workspace" },
  245. {
  246. tag: "button",
  247. value: { command: "/workspace" },
  248. text: { content: "Workspace" },
  249. },
  250. ],
  251. },
  252. }),
  253. },
  254. },
  255. }),
  256. ).toEqual([]);
  257. expect(
  258. await h.service.handleProviderCallback(provider, {
  259. botId,
  260. zcodeBotOpenId: "ou_bot",
  261. event: {
  262. sender: { sender_type: "bot", sender_id: { open_id: "ou_other_bot" } },
  263. message: {
  264. chat_id: actor.chatId,
  265. chat_type: "group",
  266. message_id: "om_confirmation",
  267. parent_id: "om_options",
  268. message_type: "text",
  269. ...(topic ? { thread_id: "omt_native", root_id: "om_root" } : {}),
  270. mentions: [{ key: "@_self", id: { open_id: "ou_bot" }, name: "Current Bot" }],
  271. content: JSON.stringify({ text: "@_self Permission response submitted." }),
  272. },
  273. },
  274. }),
  275. ).toEqual([]);
  276. expect(
  277. Object.values(h.readState().bots).find(
  278. (context) => context.activeTaskId === state.activeTaskId,
  279. )?.group?.autoReplyGuard,
  280. ).toEqual(beforeGuard);
  281. expect(
  282. Object.keys(
  283. Object.values(h.readState().bots).find(
  284. (context) => context.activeTaskId === state.activeTaskId,
  285. )?.group?.inputs ?? {},
  286. ),
  287. ).toEqual(beforeInputs);
  288. expect(input.source.contentParts).toEqual(parts);
  289. requests.length = 0;
  290. const request = {
  291. taskId: state.activeTaskId!,
  292. inputId,
  293. authorizationId: input.source.authorizationId!,
  294. toolCallId: "native-call",
  295. workspacePath: state.workspacePath!,
  296. workspaceIdentity: state.workspaceIdentity,
  297. parts: [
  298. { type: "mention" as const, refId: "om_input:m1" },
  299. { type: "text" as const, text: " 请确认" },
  300. ],
  301. };
  302. const started = Promise.withResolvers<void>();
  303. const release = Promise.withResolvers<void>();
  304. sendBarrier = { started: started.resolve, released: release.promise };
  305. const initial = h.service.replyToChannel!(request);
  306. await started.promise;
  307. let replaySettled = false;
  308. const replay = h.service.replyToChannel!(request).then((result) => {
  309. replaySettled = true;
  310. return result;
  311. });
  312. try {
  313. // 内存依赖已完成的微任务先排空;平台响应由显式 Promise 屏障控制,不靠延时制造竞态。
  314. await new Promise<void>((resolve) => setImmediate(resolve));
  315. expect(replaySettled).toBe(false);
  316. } finally {
  317. release.resolve();
  318. }
  319. const first = await initial;
  320. expect(await replay).toEqual(first);
  321. sendBarrier = undefined;
  322. expect(first.status).toBe("sent");
  323. expect(await h.service.replyToChannel!(request)).toEqual(first);
  324. await expect(
  325. h.service.replyToChannel!({
  326. ...request,
  327. toolCallId: "unknown-call",
  328. parts: [{ type: "mention", refId: "invented" }],
  329. }),
  330. ).rejects.toThrow();
  331. // 同一任务客户端续聊不携带单条消息来源,也不能改变绑定目标。
  332. const { authorizationId: _authorization, ...followup } = request;
  333. expect(
  334. await h.service.replyToChannel!({
  335. ...followup,
  336. inputId: "desktop-followup",
  337. toolCallId: "followup-call",
  338. }),
  339. ).toMatchObject({ status: "sent" });
  340. await expect(
  341. h.service.replyToChannel!({
  342. ...followup,
  343. taskId: "unbound-task",
  344. toolCallId: "wrong-task",
  345. }),
  346. ).rejects.toThrow();
  347. const named = {
  348. ...followup,
  349. toolCallId: "named",
  350. parts: [
  351. { type: "mentionName" as const, name: "Directory" },
  352. { type: "mentionName" as const, name: "Ryan Bot" },
  353. ],
  354. };
  355. expect((await h.service.replyToChannel!(named)).status).toBe("sent");
  356. expect((await h.service.replyToChannel!(named)).status).toBe("sent");
  357. // 新任务只收到纯文字名字,仍能复用同群历史原生身份;旧 ref 不能恢复发送授权。
  358. const previousRequestCount = requests.length;
  359. const restartedState = h.readState();
  360. const restartedContext = Object.values(restartedState.bots).find(
  361. (context) =>
  362. context.group?.threadId === (topic ? "omt_native" : undefined) &&
  363. context.group?.inputs?.[inputId],
  364. )!;
  365. restartedContext.activeTaskId = "task-after-switch";
  366. restartedContext.group!.inputs!["new-input"] = {
  367. ...structuredClone(restartedContext.group!.inputs![inputId]!),
  368. taskId: "task-after-switch",
  369. progress: undefined,
  370. source: {
  371. ...structuredClone(input.source),
  372. messageId: "om_new",
  373. messages: undefined,
  374. contentParts: [{ type: "text", text: "Find ryan" }],
  375. },
  376. };
  377. const restarted = createBotsServiceHarness({
  378. config: createFeishuConfig(provider, botId),
  379. state: restartedState,
  380. });
  381. try {
  382. const newRequest = {
  383. ...followup,
  384. taskId: "task-after-switch",
  385. inputId: "new-input",
  386. toolCallId: "historical-name",
  387. };
  388. expect(
  389. await restarted.service.replyToChannel!({
  390. ...newRequest,
  391. parts: [{ type: "mentionName", name: "ryan" }],
  392. }),
  393. ).toMatchObject({ status: "sent" });
  394. await expect(
  395. restarted.service.replyToChannel!({ ...newRequest, toolCallId: "historical-ref" }),
  396. ).rejects.toThrow();
  397. } finally {
  398. await restarted.service.disposeAllAndWait();
  399. requests.splice(previousRequestCount);
  400. }
  401. const clarification = await h.service.replyToChannel!({
  402. ...named,
  403. toolCallId: "ambiguous",
  404. parts: [{ type: "mentionName", name: "Alex" }],
  405. });
  406. if (clarification.status !== "needs_clarification")
  407. throw new Error("Expected candidates without sending");
  408. expect(clarification.unresolved[0]?.candidates).toHaveLength(2);
  409. expect(
  410. await h.service.replyToChannel!({
  411. ...named,
  412. toolCallId: "missing",
  413. parts: [
  414. { type: "mentionName", name: "Missing Bot" },
  415. { type: "mentionName", name: "Missing User" },
  416. { type: "mentionName", name: "Directory" },
  417. ],
  418. }),
  419. ).toMatchObject({
  420. status: "needs_clarification",
  421. unresolved: [
  422. { name: "Missing Bot", reason: "not_found" },
  423. { name: "Missing User", reason: "not_found" },
  424. ],
  425. });
  426. expect(
  427. (
  428. await h.service.replyToChannel!({
  429. ...named,
  430. toolCallId: "selected",
  431. parts: [
  432. {
  433. type: "mentionName",
  434. name: "Alex",
  435. candidateRef: clarification.unresolved[0]!.candidates[1]!.ref,
  436. },
  437. ],
  438. })
  439. ).status,
  440. ).toBe("sent");
  441. const posts = requests.filter(
  442. (r) => r.method === "POST" && r.url.includes("/im/v1/messages"),
  443. );
  444. expect(posts).toHaveLength(4);
  445. expect(posts[2]!.body).toContain("<at id=ou_directory>");
  446. expect(posts[2]!.body).toContain("<at id=ou_target>");
  447. expect(posts[3]!.body).toContain("<at id=ou_alex_b>");
  448. expect(posts[0]!.url).toContain("/om_input/reply");
  449. const body = JSON.parse(posts[0]!.body!);
  450. expect(Boolean(body.reply_in_thread)).toBe(topic);
  451. expect(JSON.parse(body.content).body.elements).toEqual([
  452. { tag: "markdown", content: "<at id=ou_target></at> 请确认" },
  453. ]);
  454. if (!topic) {
  455. // 使用真实接收事件的 bot 类型;机器人命令正文也只能作为普通输入。
  456. const payload = {
  457. botId,
  458. zcodeProvider: provider,
  459. zcodeBotOpenId: "ou_bot",
  460. event: {
  461. sender: { sender_type: "bot", sender_id: { open_id: "ou_other_bot" } },
  462. message: {
  463. chat_type: "group",
  464. chat_id: "oc_group",
  465. message_id: "om_bot_main",
  466. parent_id: "om_bot_parent",
  467. message_type: "text",
  468. content: JSON.stringify({ text: "@_bot /stop" }),
  469. mentions: [{ key: "@_bot", id: { open_id: "ou_bot" }, name: "Bot" }],
  470. },
  471. },
  472. };
  473. await h.service.handleProviderCallback(provider, payload);
  474. expect(parentReads).toBeGreaterThan(0);
  475. await h.service.handleProviderCallback(provider, payload);
  476. const groupState = (await h.service.getBotStates()).find(
  477. (state) => state.group?.chatId === "oc_group" && !state.group.threadId,
  478. );
  479. const inputs = Object.values(groupState!.group!.inputs!);
  480. expect(inputs.filter((input) => input.source.messageId === "om_bot_main")).toHaveLength(
  481. 1,
  482. );
  483. expect(
  484. inputs.find((input) => input.source.messageId === "om_bot_main")?.source,
  485. ).toMatchObject({
  486. senderId: "ou_other_bot",
  487. });
  488. for (let i = 1; i <= 5; i++) {
  489. payload.event.message.message_id = `om_bot_limit_${i}`;
  490. await h.service.handleProviderCallback(provider, payload);
  491. }
  492. const readInputs = async () =>
  493. Object.values(
  494. (await h.service.getBotStates()).find(
  495. (current) => current.group?.chatId === "oc_group" && !current.group.threadId,
  496. )!.group!.inputs!,
  497. );
  498. expect(
  499. (await readInputs()).filter((entry) => entry.source.senderId === "ou_other_bot"),
  500. ).toHaveLength(5);
  501. expect(
  502. (await readInputs()).some((entry) => entry.source.messageId === "om_bot_limit_5"),
  503. ).toBe(false);
  504. await h.service.handleInboundMessage({
  505. botId,
  506. actor: { ...actor, providerMessageId: "om_human_resume" },
  507. text: "continue",
  508. });
  509. payload.event.message.message_id = "om_bot_resumed";
  510. await h.service.handleProviderCallback(provider, payload);
  511. expect(
  512. (await readInputs()).some((entry) => entry.source.messageId === "om_bot_resumed"),
  513. ).toBe(true);
  514. }
  515. // 停止仍更新执行状态,但群主聊天和话题都不能再发送停止通知或状态卡。
  516. const stopActor = {
  517. ...actor,
  518. providerMessageId: "om_stop",
  519. ...(topic ? { threadId: "omt_native", rootMessageId: "om_root" } : {}),
  520. };
  521. requests.length = 0;
  522. expect(
  523. await h.service.handleInboundMessage({ botId, actor: stopActor, text: "/stop" }),
  524. ).toEqual([]);
  525. for (const { listener } of h.subscriptions) {
  526. await listener({
  527. type: "task_complete",
  528. taskId: state.activeTaskId!,
  529. inputId,
  530. stopReason: "cancelled",
  531. } as Parameters<typeof listener>[0]);
  532. }
  533. expect(
  534. requests.filter(
  535. (request) =>
  536. request.method === "POST" && /\/messages(?:\?|$|\/[^/]+\/reply)/u.test(request.url),
  537. ),
  538. ).toEqual([]);
  539. } finally {
  540. await h.service.disposeAllAndWait();
  541. globalThis.fetch = originalFetch;
  542. }
  543. });
  544. }
  545. }
  546. });