bot-large-attachment.test.ts 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. import assert from "node:assert/strict";
  2. import { readFile, rm } from "node:fs/promises";
  3. import type { IZCodeTaskService } from "@zcode/services";
  4. import {
  5. createBotsServiceHarness,
  6. createFeishuConfig,
  7. createRecordingFeishuFetch,
  8. readBotSyntheticFixture,
  9. type RecordedRequest,
  10. } from "#e2e/bots/helpers/bots-service-harness";
  11. type Prompt = Parameters<IZCodeTaskService["sendPrompt"]>[0];
  12. type GroupInput = Parameters<NonNullable<IZCodeTaskService["submitBotGroupInput"]>>[0];
  13. describe("BOT-E2E-AT-01 large Bot attachments", () => {
  14. for (const provider of ["feishu", "lark"] as const) {
  15. for (const chatType of ["p2p", "group"] as const) {
  16. for (const scenario of [
  17. { type: "file", mib: 6 },
  18. { type: "post", mib: 3 },
  19. { type: "post", mib: 6 },
  20. ] as const) {
  21. it(`${provider}/${chatType}/${scenario.type}: caches and submits a ${scenario.mib} MiB file, still rejects download failure`, async () => {
  22. const fixture = await readBotSyntheticFixture("large-attachment.json");
  23. assert.equal(fixture.classification, "synthetic");
  24. const bytes = Buffer.alloc(scenario.mib * 1024 * 1024, "x");
  25. bytes.write(fixture.promptMarker!);
  26. const filename = `${fixture.promptMarker}.txt`;
  27. const requests: RecordedRequest[] = [];
  28. const downloads: string[] = [];
  29. const originalFetch = globalThis.fetch;
  30. const recordingFetch = createRecordingFeishuFetch(requests);
  31. let downloadStatus = 503;
  32. globalThis.fetch = async (input, init) => {
  33. const url = String(input);
  34. if (url.includes("/resources/file_large")) {
  35. downloads.push(url);
  36. return new Response(bytes, { status: downloadStatus });
  37. }
  38. if (url.endsWith("/bot/v3/info"))
  39. return Response.json({ code: 0, bot: { open_id: "ou_current_bot" } });
  40. if (url.includes("/im/v1/chats/"))
  41. return Response.json({ code: 0, data: { name: "E2E Group", chat_mode: "group" } });
  42. return recordingFetch(input, init);
  43. };
  44. const botId = `${provider}-${chatType}-large-attachment`;
  45. const h = createBotsServiceHarness({ config: createFeishuConfig(provider, botId) });
  46. const prompts: Prompt[] = [];
  47. const groupInputs: GroupInput[] = [];
  48. h.zcodeTaskService.sendPrompt = async (params: Prompt) => {
  49. prompts.push(params);
  50. };
  51. h.zcodeTaskService.submitBotGroupInput = async (params: GroupInput) => {
  52. groupInputs.push(params);
  53. return {
  54. commandId: params.commandId,
  55. status: "accepted",
  56. revisionAtDecision: 1,
  57. result: { type: "inputAccepted", inputId: params.commandId, delivery: "startNow" },
  58. };
  59. };
  60. const callback = (messageId: string, messageType: "text" | "file" | "post") => ({
  61. botId,
  62. event: {
  63. sender: { sender_type: "user", sender_id: { open_id: "ou_e2e_user" } },
  64. message: {
  65. chat_type: chatType,
  66. chat_id: "oc_large_attachment",
  67. message_id: messageId,
  68. message_type: messageType,
  69. content: JSON.stringify(
  70. messageType === "file"
  71. ? { file_key: "file_large", file_name: filename }
  72. : messageType === "post"
  73. ? {
  74. title: "",
  75. content: [[{ tag: "text", text: fixture.promptMarker }]],
  76. files: [
  77. { file_key: "file_large", file_name: filename, size: bytes.length },
  78. ],
  79. }
  80. : { text: "@_user_1 /enable" },
  81. ),
  82. mentions: [{ key: "@_user_1", id: { open_id: "ou_current_bot" }, name: "E2E Bot" }],
  83. },
  84. },
  85. });
  86. let cachedPath: string | undefined;
  87. try {
  88. if (chatType === "group") {
  89. await h.service.handleProviderCallbackResponse(
  90. provider,
  91. callback("om_enable", "text"),
  92. );
  93. }
  94. const failureStart = requests.length;
  95. await h.service.handleProviderCallbackResponse(
  96. provider,
  97. callback("om_unavailable", scenario.type),
  98. );
  99. assert.equal(downloads.length, 1);
  100. assert.equal(prompts.length + groupInputs.length, 0);
  101. assert.match(
  102. JSON.stringify(requests.slice(failureStart)),
  103. /无法下载附件|download failed/u,
  104. );
  105. requests.length = 0;
  106. downloadStatus = 200;
  107. await h.service.handleProviderCallbackResponse(
  108. provider,
  109. callback("om_large", scenario.type),
  110. );
  111. assert.equal(prompts.length + groupInputs.length, 1, JSON.stringify(requests));
  112. if (scenario.type === "post") {
  113. assert.ok((prompts[0] ?? groupInputs[0])?.content.includes(fixture.promptMarker!));
  114. }
  115. assert.equal(downloads.length, 2);
  116. assert.equal(
  117. new URL(downloads[0]!).hostname,
  118. provider === "feishu" ? "open.feishu.cn" : "open.larksuite.com",
  119. );
  120. if (chatType === "group") {
  121. const attachment = groupInputs[0]?.attachments?.[0];
  122. assert.ok(attachment);
  123. assert.equal(attachment.kind, "file");
  124. assert.equal(attachment.filename, filename);
  125. assert.equal(attachment.sizeBytes, bytes.length);
  126. assert.ok(attachment.dataBase64);
  127. assert.deepEqual(Buffer.from(attachment.dataBase64, "base64"), bytes);
  128. cachedPath = attachment.localPath;
  129. } else {
  130. assert.equal(groupInputs.length, 0);
  131. cachedPath = prompts[0]?.content.match(/已保存到:([^\n]+)/u)?.[1];
  132. assert.ok(prompts[0]?.content.includes(filename));
  133. }
  134. assert.ok(cachedPath);
  135. assert.deepEqual(await readFile(cachedPath), bytes);
  136. assert.equal(JSON.stringify(requests).includes("附件处理失败"), false);
  137. } finally {
  138. await h.service.disposeAllAndWait();
  139. globalThis.fetch = originalFetch;
  140. if (cachedPath) await rm(cachedPath, { force: true });
  141. }
  142. });
  143. }
  144. }
  145. }
  146. });