bot-private-redelivery.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. import assert from "node:assert/strict";
  2. import type { IZCodeTaskService } from "@zcode/services";
  3. import type { BotProvider, ZCodeStreamEvent } from "@zcode/shared";
  4. import {
  5. createBotModelSelectionView,
  6. createBotsServiceHarness,
  7. createFeishuConfig,
  8. createRecordingFeishuFetch,
  9. readBotSyntheticFixture,
  10. type RecordedRequest,
  11. } from "#e2e/bots/helpers/bots-service-harness";
  12. type Prompt = Parameters<IZCodeTaskService["sendPrompt"]>[0];
  13. type Harness = ReturnType<typeof createBotsServiceHarness>;
  14. type InboundAttachments = Parameters<Harness["service"]["handleInboundMessage"]>[0]["attachments"];
  15. const TASK_ID = "task-e2e-bot";
  16. // Telegram/微信的 Typing 每 4 秒续发一次;观察窗口超过一个周期才能证明已经停止。
  17. const TYPING_OBSERVE_MS = 5_000;
  18. const PNG_BASE64 =
  19. "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+a9xkAAAAASUVORK5CYII=";
  20. function sleep(ms: number): Promise<void> {
  21. return new Promise((resolve) => setTimeout(resolve, ms));
  22. }
  23. /** 按渠道识别 Typing 请求:Telegram sendChatAction、微信 sendtyping、飞书 Typing reaction。 */
  24. function typingRequests(requests: RecordedRequest[]): RecordedRequest[] {
  25. return requests.filter((request) => /sendChatAction|\/sendtyping|\/reactions/u.test(request.url));
  26. }
  27. function feishuReactionDeletes(requests: RecordedRequest[]): number {
  28. return requests.filter((r) => r.url.includes("/reactions") && r.method === "DELETE").length;
  29. }
  30. function setupProvider(provider: BotProvider) {
  31. const requests: RecordedRequest[] = [];
  32. const feishuFetch = createRecordingFeishuFetch(requests);
  33. globalThis.fetch = async (input, init) => {
  34. if (provider === "feishu") {
  35. // 共享替身先匹配 /im/v1/messages,reaction POST 拿不到 reaction_id,删除会被跳过;
  36. // 真实飞书返回 reaction_id,这里按真实响应补上,才能观察 Typing reaction 的删除。
  37. if (String(input).includes("/reactions") && init?.method === "POST") {
  38. requests.push({ url: String(input), method: "POST" });
  39. return Response.json({ code: 0, data: { reaction_id: "e2e-typing-reaction" } });
  40. }
  41. return feishuFetch(input, init);
  42. }
  43. requests.push({ url: String(input), method: init?.method ?? "GET" });
  44. // 微信 sendtyping 需要先拿到 typing_ticket。
  45. return new Response(JSON.stringify({ ok: true, ret: 0, typing_ticket: "e2e-ticket" }));
  46. };
  47. const config = createFeishuConfig();
  48. const bot = {
  49. ...config.bots[0]!,
  50. provider,
  51. replyMode: provider === "feishu" ? ("streaming_card" as const) : ("assistant_changes" as const),
  52. };
  53. config.bots = [bot];
  54. // 续聊路径要求会话有可用的有效选择;与 BOT-E2E-BASIS-01 相同的绑定方式。
  55. const view = createBotModelSelectionView();
  56. const selection = view.preferredSelection!;
  57. const broadcastEvents: string[] = [];
  58. const h = createBotsServiceHarness({
  59. config,
  60. modelSelectionService: {
  61. getView: async () => ({ ...view, effectiveSelection: selection }),
  62. },
  63. broadcastService: {
  64. send: async (message) => {
  65. const event = (message as { payload?: { event?: unknown } }).payload?.event;
  66. if (typeof event === "string") broadcastEvents.push(event);
  67. },
  68. },
  69. });
  70. h.zcodeTaskService.getTaskModelSelection = async () => selection;
  71. // 任务服务替身按 CLI 命令账本回复:同一个 commandId 第二次提交返回 duplicate,不开新一轮。
  72. const admitted = new Set<string>();
  73. h.zcodeTaskService.sendPrompt = async (params: Prompt) => {
  74. h.sendPromptCalls.push(params);
  75. const duplicate = admitted.has(params.traceId);
  76. admitted.add(params.traceId);
  77. return {
  78. commandId: params.traceId,
  79. status: duplicate ? "duplicate" : "accepted",
  80. revisionAtDecision: 1,
  81. };
  82. };
  83. let taskStatus = "running";
  84. h.zcodeTaskService.getTaskSnapshot = async () => ({ meta: { status: taskStatus } });
  85. const replies: unknown[] = [];
  86. const send = async (
  87. providerMessageId: string,
  88. text: string,
  89. attachments?: InboundAttachments,
  90. ) => {
  91. replies.push(
  92. await h.service.handleInboundMessage({
  93. botId: bot.id,
  94. actor: {
  95. botId: bot.id,
  96. provider,
  97. providerUserId: bot.providerUserId!,
  98. chatType: "private",
  99. providerContextToken: "e2e-context",
  100. providerMessageId,
  101. },
  102. text,
  103. ...(attachments ? { attachments } : {}),
  104. }),
  105. );
  106. };
  107. const waitForPrompts = (count: number) =>
  108. browser.waitUntil(async () => h.sendPromptCalls.length >= count, {
  109. timeout: 10_000,
  110. timeoutMsg: `${provider} 私聊输入没有提交第 ${count} 次,回复:${JSON.stringify(replies)}`,
  111. });
  112. const traceIdAt = (index: number) => (h.sendPromptCalls[index] as Prompt).traceId;
  113. // Bot 自己发起的一轮未结束时,私聊新消息会被“任务运行中”拒绝;线上重投发生在该轮结束之后。
  114. const completeTurn = async (traceId: string) => {
  115. const emit = h.subscriptions[0]!.listener;
  116. const base = { taskId: TASK_ID, traceId, inputId: traceId };
  117. await emit({
  118. ...base,
  119. type: "task_run_started",
  120. startedAt: Date.now(),
  121. inputOrigin: "desktop",
  122. } as ZCodeStreamEvent);
  123. await emit({ ...base, type: "task_complete", stopReason: "end_turn" } as ZCodeStreamEvent);
  124. };
  125. return {
  126. h,
  127. requests,
  128. broadcastEvents,
  129. send,
  130. waitForPrompts,
  131. traceIdAt,
  132. completeTurn,
  133. setTaskStatus: (status: string) => {
  134. taskStatus = status;
  135. },
  136. };
  137. }
  138. describe("BOT-E2E-RD-01 private redelivery keeps one command id", () => {
  139. const originalFetch = globalThis.fetch;
  140. let harness: Harness | undefined;
  141. afterEach(async () => {
  142. await harness?.service.disposeAllAndWait();
  143. harness = undefined;
  144. globalThis.fetch = originalFetch;
  145. });
  146. for (const provider of ["feishu", "telegram", "weixin"] satisfies BotProvider[]) {
  147. it(`${provider}: an idle duplicate reuses the command id and settles typing and running state`, async () => {
  148. const fixture = await readBotSyntheticFixture("private-redelivery.json");
  149. assert.equal(fixture.caseId, "BOT-E2E-RD-01");
  150. const s = setupProvider(provider);
  151. harness = s.h;
  152. await s.send("e2e-message-a", `${fixture.promptMarker} A`);
  153. await s.waitForPrompts(1);
  154. await s.completeTurn(s.traceIdAt(0));
  155. s.setTaskStatus("completed");
  156. const deletesBefore = feishuReactionDeletes(s.requests);
  157. const eventsBefore = s.broadcastEvents.length;
  158. // 直接进入业务处理,等同于内存去重过期后、或游标未提交时的重投。
  159. await s.send("e2e-message-a", `${fixture.promptMarker} A`);
  160. await s.waitForPrompts(2);
  161. assert.equal(s.traceIdAt(1), s.traceIdAt(0), "同一条消息重投必须复用同一个 commandId");
  162. // duplicate 不开新一轮、没有终态事件;Bot 必须按 CLI 快照(空闲)自行收口。
  163. await browser.waitUntil(
  164. async () => s.broadcastEvents.slice(eventsBefore).includes("completed"),
  165. { timeout: 5_000, timeoutMsg: `${provider} duplicate 后没有向桌面广播 completed` },
  166. );
  167. if (provider === "feishu") {
  168. assert.ok(
  169. feishuReactionDeletes(s.requests) > deletesBefore,
  170. "飞书 duplicate 后必须删除 Typing reaction",
  171. );
  172. } else {
  173. const settled = typingRequests(s.requests).length;
  174. await sleep(TYPING_OBSERVE_MS);
  175. assert.equal(
  176. typingRequests(s.requests).length,
  177. settled,
  178. `${provider} duplicate 收口后仍在续发 Typing`,
  179. );
  180. }
  181. // 运行标记已清:下一条新消息不会被“任务运行中”拒绝,并使用新的 commandId。
  182. await s.send("e2e-message-b", `${fixture.promptMarker} B`);
  183. await s.waitForPrompts(3);
  184. assert.notEqual(s.traceIdAt(2), s.traceIdAt(0), "新消息必须使用新的 commandId");
  185. });
  186. it(`${provider}: a duplicate while the task still runs keeps typing until that run ends`, async () => {
  187. const fixture = await readBotSyntheticFixture("private-redelivery.json");
  188. const s = setupProvider(provider);
  189. harness = s.h;
  190. await s.send("e2e-message-a", `${fixture.promptMarker} A`);
  191. await s.waitForPrompts(1);
  192. await s.completeTurn(s.traceIdAt(0));
  193. // Bot 自己的一轮已结束,但会话里还有别的轮次在执行(例如桌面排队的输入)。
  194. s.setTaskStatus("running");
  195. const deletesBefore = feishuReactionDeletes(s.requests);
  196. const eventsBefore = s.broadcastEvents.length;
  197. await s.send("e2e-message-a", `${fixture.promptMarker} A`);
  198. await s.waitForPrompts(2);
  199. const typingAtDuplicate = typingRequests(s.requests).length;
  200. await sleep(TYPING_OBSERVE_MS);
  201. assert.ok(
  202. !s.broadcastEvents.slice(eventsBefore).includes("completed"),
  203. "任务仍在运行时不能广播 completed",
  204. );
  205. if (provider === "feishu") {
  206. assert.equal(feishuReactionDeletes(s.requests), deletesBefore, "不能误删运行中的 reaction");
  207. } else {
  208. assert.ok(
  209. typingRequests(s.requests).length > typingAtDuplicate,
  210. `${provider} 任务仍在运行时 Typing 被误停`,
  211. );
  212. }
  213. // 正在执行的那一轮结束后,按原有终态路径清理。
  214. await s.completeTurn("e2e-other-running-turn");
  215. if (provider === "feishu") {
  216. assert.ok(feishuReactionDeletes(s.requests) > deletesBefore, "终态后必须删除 reaction");
  217. } else {
  218. const settled = typingRequests(s.requests).length;
  219. await sleep(TYPING_OBSERVE_MS);
  220. assert.equal(
  221. typingRequests(s.requests).length,
  222. settled,
  223. `${provider} 终态后仍在续发 Typing`,
  224. );
  225. }
  226. });
  227. }
  228. it("attachment inputs keep a random command id on the legacy send path", async () => {
  229. const fixture = await readBotSyntheticFixture("private-redelivery.json");
  230. const s = setupProvider("feishu");
  231. harness = s.h;
  232. const attachments: InboundAttachments = [
  233. {
  234. id: "e2e-redelivery-attachment",
  235. kind: "image",
  236. filename: "redelivery.png",
  237. mimeType: "image/png",
  238. dataBase64: PNG_BASE64,
  239. },
  240. ];
  241. await s.send("e2e-message-attachment", `${fixture.promptMarker} file`, attachments);
  242. await s.waitForPrompts(1);
  243. await s.completeTurn(s.traceIdAt(0));
  244. s.setTaskStatus("completed");
  245. await s.send("e2e-message-attachment", `${fixture.promptMarker} file`, attachments);
  246. await s.waitForPrompts(2);
  247. // 旧 session/send 不按 inputId 去重;固定 ID 没有保护,还会让两轮共用一个 inputId。
  248. assert.ok((s.h.sendPromptCalls[0] as Prompt).attachments?.length, "首次提交必须带附件");
  249. assert.notEqual(s.traceIdAt(1), s.traceIdAt(0), "附件输入必须保留随机 commandId");
  250. });
  251. });