feishu-provider-interactions.test.ts 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. import type { ZCodeStreamEvent } from "@zcode/shared";
  2. import {
  3. createBotsServiceHarness,
  4. createFeishuCallback,
  5. createFeishuConfig,
  6. createRecordingFeishuFetch,
  7. readBotSyntheticFixture,
  8. type RecordedRequest,
  9. } from "#e2e/bots/helpers/bots-service-harness";
  10. describe("Bot provider interaction E2E", () => {
  11. const originalFetch = globalThis.fetch;
  12. const services: Array<ReturnType<typeof createBotsServiceHarness>["service"]> = [];
  13. afterEach(() => {
  14. for (const service of services) service.disposeAll();
  15. services.length = 0;
  16. globalThis.fetch = originalFetch;
  17. });
  18. it("BOT-E2E-AQ-01 keeps multi-select and custom AskUserQuestion answers on one card", async () => {
  19. const fixture = await readBotSyntheticFixture("feishu-ask-user-question.json");
  20. expect(fixture).toMatchObject({ caseId: "BOT-E2E-AQ-01", classification: "synthetic" });
  21. expect(fixture.syntheticReason.length).toBeGreaterThan(20);
  22. const requests: RecordedRequest[] = [];
  23. globalThis.fetch = createRecordingFeishuFetch(requests);
  24. const harness = createBotsServiceHarness({ config: createFeishuConfig() });
  25. services.push(harness.service);
  26. await harness.service.handleProviderCallbackResponse(
  27. "feishu",
  28. createFeishuCallback("feishu-e2e", "E2E_BOT_ASK_USER_QUESTION"),
  29. );
  30. const listener = harness.subscriptions[0]?.listener;
  31. expect(listener).toBeDefined();
  32. await listener?.({
  33. type: "elicitation_request",
  34. taskId: "task-e2e-bot",
  35. traceId: "run-e2e-aq",
  36. requestId: "request-e2e-aq",
  37. message: "请选择技术方案",
  38. options: [{ value: "web", label: "纯前端" }],
  39. questions: [
  40. {
  41. question: "请选择技术方案",
  42. options: [{ value: "web", label: "纯前端" }],
  43. },
  44. {
  45. question: "请选择交付内容",
  46. options: [
  47. { value: "tests", label: "测试" },
  48. { value: "docs", label: "文档" },
  49. ],
  50. multiSelect: true,
  51. },
  52. ],
  53. } as ZCodeStreamEvent);
  54. const token = requests
  55. .map((request) => request.body ?? "")
  56. .join("\n")
  57. .match(/\/elicitation ([a-f0-9]{12}) web/u)?.[1];
  58. expect(token).toMatch(/^[a-f0-9]{12}$/u);
  59. const callback = (command: string, formValue?: Record<string, string>) =>
  60. harness.service.handleProviderCallbackResponse("feishu", {
  61. botId: "feishu-e2e",
  62. zcodeFeishuSynchronousCardAction: true,
  63. event: {
  64. operator: { operator_id: { open_id: "ou_e2e_user" } },
  65. action: {
  66. behaviors: [{ type: "callback", value: { command, zcodeCardText: "Question" } }],
  67. ...(formValue ? { form_value: formValue } : {}),
  68. },
  69. context: { card_update_token: "card-update-token-e2e" },
  70. },
  71. });
  72. const advanced = await callback(`/elicitation ${token} web`);
  73. const nextToken = advanced.replies[0]?.selection?.token;
  74. expect(nextToken).toMatch(/^[a-f0-9]{12}$/u);
  75. await callback(`/elicitation ${nextToken} tests`);
  76. await callback(`/elicitation ${nextToken} __custom__`);
  77. const completed = await callback(`/elicitation ${nextToken} __form__:`, { answer: "发布说明" });
  78. expect(completed.replies[0]?.elicitation).toMatchObject({
  79. requestId: "request-e2e-aq",
  80. status: "completed",
  81. });
  82. expect(harness.respondElicitationCalls).toEqual([
  83. expect.objectContaining({
  84. taskId: "task-e2e-bot",
  85. runId: "run-e2e-aq",
  86. requestId: "request-e2e-aq",
  87. content: expect.objectContaining({
  88. answers: {
  89. 请选择技术方案: "web",
  90. 请选择交付内容: "tests, 发布说明",
  91. },
  92. answer_0: "web",
  93. answer_1: ["tests", "发布说明"],
  94. }),
  95. }),
  96. ]);
  97. const interactionPosts = requests.filter(
  98. (request) =>
  99. request.method === "POST" &&
  100. request.url.includes("/open-apis/im/v1/messages?receive_id_type="),
  101. );
  102. const interactionUpdates = requests.filter(
  103. (request) =>
  104. request.method === "POST" && request.url.includes("/open-apis/interactive/v1/card/update"),
  105. );
  106. expect(interactionPosts).toHaveLength(1);
  107. expect(interactionUpdates).toHaveLength(0);
  108. expect(
  109. requests.filter(
  110. (request) =>
  111. request.method === "PATCH" && request.url.includes("/open-apis/im/v1/messages/"),
  112. ),
  113. ).toHaveLength(0);
  114. expect(requests.some((request) => request.method === "DELETE")).toBe(false);
  115. const nextQuestionJson = JSON.stringify(advanced.replies[0]);
  116. expect(advanced.replies[0]?.elicitation).toMatchObject({
  117. currentQuestionIndex: 1,
  118. answers: { "0": ["web"] },
  119. });
  120. expect(advanced.replies[0]?.selection?.token).toBe(nextToken);
  121. expect(nextQuestionJson).toContain("请选择技术方案");
  122. expect(nextQuestionJson).toContain("请选择交付内容");
  123. expect(nextQuestionJson).toContain("纯前端");
  124. const finalJson = JSON.stringify(completed.replies[0]);
  125. expect(completed.replies[0]?.elicitation?.answers).toEqual({
  126. "0": ["web"],
  127. "1": ["tests", "发布说明"],
  128. });
  129. expect(finalJson).not.toContain('"command"');
  130. });
  131. it("BOT-E2E-IL-01 seals streaming output and retains the completed interaction card", async () => {
  132. const fixture = await readBotSyntheticFixture("feishu-interaction-card-lifecycle.json");
  133. expect(fixture).toMatchObject({ caseId: "BOT-E2E-IL-01", classification: "synthetic" });
  134. const requests: RecordedRequest[] = [];
  135. globalThis.fetch = createRecordingFeishuFetch(requests);
  136. const harness = createBotsServiceHarness({ config: createFeishuConfig() });
  137. services.push(harness.service);
  138. await harness.service.handleProviderCallbackResponse(
  139. "feishu",
  140. createFeishuCallback("feishu-e2e", "E2E_BOT_INTERACTION_CARD_LIFECYCLE"),
  141. );
  142. const listener = harness.subscriptions[0]?.listener;
  143. expect(listener).toBeDefined();
  144. await listener?.({
  145. type: "agent_message_chunk",
  146. taskId: "task-e2e-bot",
  147. traceId: "run-e2e-il-before",
  148. content: "交互前的普通输出",
  149. } as ZCodeStreamEvent);
  150. await listener?.({
  151. type: "elicitation_request",
  152. taskId: "task-e2e-bot",
  153. traceId: "run-e2e-il-plan",
  154. requestId: "request-e2e-il-plan",
  155. message: "Review this implementation plan.",
  156. options: [{ value: "approve", label: "Approve" }],
  157. schema: {
  158. interaction: "plan_approval",
  159. plan: "# 完整计划\n\n执行生命周期调整。",
  160. },
  161. } as ZCodeStreamEvent);
  162. const token = requests
  163. .map((request) => request.body ?? "")
  164. .join("\n")
  165. .match(/\/elicitation ([a-f0-9]{12}) approve/u)?.[1];
  166. expect(token).toMatch(/^[a-f0-9]{12}$/u);
  167. await harness.service.handleProviderCallbackResponse("feishu", {
  168. botId: "feishu-e2e",
  169. event: {
  170. operator: { operator_id: { open_id: "ou_e2e_user" } },
  171. action: {
  172. behaviors: [
  173. {
  174. type: "callback",
  175. value: {
  176. command: `/elicitation ${token} approve`,
  177. zcodeCardText: "Review this implementation plan.",
  178. },
  179. },
  180. ],
  181. },
  182. context: { card_update_token: "card-update-token-e2e-il" },
  183. },
  184. });
  185. await listener?.({
  186. type: "agent_message_chunk",
  187. taskId: "task-e2e-bot",
  188. traceId: "run-e2e-il-after",
  189. content: "交互后的新输出",
  190. } as ZCodeStreamEvent);
  191. const messagePosts = requests.filter(
  192. (request) =>
  193. request.method === "POST" &&
  194. request.url.includes("/open-apis/im/v1/messages?receive_id_type="),
  195. );
  196. expect(messagePosts).toHaveLength(3);
  197. expect(messagePosts[0]?.body).toContain("交互前的普通输出");
  198. expect(messagePosts[1]?.body).toContain("完整计划");
  199. expect(messagePosts[2]?.body).toContain("交互后的新输出");
  200. expect(messagePosts[2]?.body).not.toContain("完整计划");
  201. const messagePatches = requests.filter(
  202. (request) => request.method === "PATCH" && request.url.includes("/open-apis/im/v1/messages/"),
  203. );
  204. expect(
  205. messagePatches.some(
  206. (request) => request.body?.includes("交互前的普通输出") && !request.body.includes("运行中"),
  207. ),
  208. ).toBe(true);
  209. const interactionUpdates = requests.filter(
  210. (request) =>
  211. request.method === "POST" && request.url.includes("/open-apis/interactive/v1/card/update"),
  212. );
  213. expect(
  214. interactionUpdates.some(
  215. (request) =>
  216. request.body?.includes("完整计划") && !request.body.includes('\\"tag\\":\\"button\\"'),
  217. ),
  218. ).toBe(true);
  219. expect(requests.some((request) => request.method === "DELETE")).toBe(false);
  220. });
  221. it("BOT-E2E-PV-01 keeps Feishu and Lark OpenAPI domains isolated", async () => {
  222. const fixture = await readBotSyntheticFixture("feishu-lark-domain-isolation.json");
  223. expect(fixture).toMatchObject({ caseId: "BOT-E2E-PV-01", classification: "synthetic" });
  224. expect(fixture.syntheticReason.length).toBeGreaterThan(20);
  225. const requests: RecordedRequest[] = [];
  226. globalThis.fetch = createRecordingFeishuFetch(requests);
  227. for (const provider of ["feishu", "lark"] as const) {
  228. const harness = createBotsServiceHarness({ config: createFeishuConfig(provider) });
  229. services.push(harness.service);
  230. await harness.service.handleProviderCallbackResponse(
  231. provider,
  232. createFeishuCallback(`${provider}-e2e`, `E2E_BOT_PROVIDER_DOMAIN_${provider}`),
  233. );
  234. }
  235. const urls = requests.map((request) => request.url);
  236. expect(urls.some((url) => url.startsWith("https://open.feishu.cn/open-apis/"))).toBe(true);
  237. expect(urls.some((url) => url.startsWith("https://open.larksuite.com/open-apis/"))).toBe(true);
  238. expect(
  239. requests
  240. .filter((request) => request.url.includes("open.larksuite.com"))
  241. .every((request) => !request.url.includes("open.feishu.cn")),
  242. ).toBe(true);
  243. });
  244. });