botsService.deletedTask.test.ts 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. import { afterEach, describe, expect, it, vi } from "vitest";
  2. import type { BotsStateFile } from "@zcode/shared";
  3. import * as f from "./botsService.fixtures.js";
  4. const actor = {
  5. provider: "webhook" as const,
  6. botId: "webhook-1",
  7. providerUserId: "user-1",
  8. chatType: "private" as const,
  9. };
  10. const services: ReturnType<typeof f.createBotsService>[] = [];
  11. afterEach(() => {
  12. for (const service of services.splice(0)) service.disposeAll();
  13. });
  14. function setup(locale: "zh-CN" | "en-US" = "zh-CN", remote = true) {
  15. const workspace = {
  16. workspacePath: "/tmp/workspace",
  17. ...(remote ? { workspaceIdentity: "remote:server:test-owner:/tmp/workspace" } : {}),
  18. };
  19. const state: BotsStateFile = {
  20. version: 3,
  21. bots: {
  22. "webhook-1": {
  23. botId: "webhook-1",
  24. ...workspace,
  25. workspaceId: workspace.workspaceIdentity ?? workspace.workspacePath,
  26. mode: "task",
  27. activeTaskId: "deleted-task",
  28. updatedAt: Date.now(),
  29. pendingPermissionOptions: [],
  30. pendingElicitation: {
  31. taskId: "deleted-task",
  32. requestId: "old-question",
  33. runId: "old-run",
  34. currentQuestionIndex: 0,
  35. questions: [
  36. { question: "旧问题", header: "旧问题", options: [{ value: "yes", label: "是" }] },
  37. ],
  38. answers: {},
  39. },
  40. },
  41. },
  42. };
  43. const repo = f.createMemoryRepo(
  44. {
  45. ...f.baseConfig,
  46. bots: [
  47. {
  48. ...f.baseConfig.bots[0]!,
  49. providerUserId: "user-1",
  50. webhookUrl: "https://bot.test/reply",
  51. },
  52. ],
  53. },
  54. state,
  55. );
  56. const taskService = f.createLegacyTaskService();
  57. vi.mocked(taskService.listDeletedTaskIds).mockResolvedValue(["deleted-task"]);
  58. const broadcastService = f.createBroadcastService();
  59. const modelSelectionService = f.createModelSelectionService([
  60. { id: "glm", name: "GLM", models: ["default"] },
  61. ]);
  62. const requests: string[] = [];
  63. const fetch = vi.fn(async (_url: unknown, init?: RequestInit) => {
  64. requests.push(String(init?.body));
  65. return new Response("{}", { status: 200 });
  66. });
  67. vi.stubGlobal("fetch", fetch);
  68. const service = f.createBotsService({
  69. ...f.createBotProjectServices([workspace]),
  70. repo: repo as never,
  71. zcodeTaskService: taskService,
  72. broadcastService,
  73. modelSelectionService,
  74. credentialService: f.createCredentialService({ "secret-1": "secret" }),
  75. settingService: f.createSettingService({
  76. locale,
  77. lastWorkspaceSession: [{ kind: remote ? "remote" : "local", ...workspace }],
  78. }),
  79. runStartupBackgroundTasks: false,
  80. warmCandidateCachesOnStartup: false,
  81. });
  82. services.push(service);
  83. return {
  84. service,
  85. repo,
  86. taskService,
  87. broadcastService,
  88. modelSelectionService,
  89. requests,
  90. fetch,
  91. workspace,
  92. };
  93. }
  94. const inbound = { botId: actor.botId, text: "E2E_BOT_DELETED_TASK 原消息", actor };
  95. describe("Bot deleted active task recovery", () => {
  96. it("replacement reuses the current Selection View and freezes the complete V4 first-send selection", async () => {
  97. const h = setup();
  98. const selection = {
  99. providerId: "account:bigmodel-team-coding-plan",
  100. modelId: "GLM-5.3",
  101. options: { reasoningLevel: "high" },
  102. };
  103. h.modelSelectionService.getView.mockResolvedValue({
  104. revision: 2,
  105. providers: [],
  106. preferredSelection: selection,
  107. });
  108. await h.service.handleInboundMessage(inbound);
  109. expect(h.taskService.createTask).toHaveBeenCalledWith(
  110. expect.objectContaining({ v4Create: true, modelSelection: selection }),
  111. );
  112. expect(h.taskService.sendPrompt).toHaveBeenCalledWith(
  113. expect.objectContaining({ modelSelection: selection, content: inbound.text }),
  114. );
  115. expect(h.taskService.getTaskModelSelection).not.toHaveBeenCalled();
  116. expect((await h.repo.readState()).bots[actor.botId]?.draftOptions).toBeUndefined();
  117. });
  118. it("replacement without an available Selection View stays draft without a success notice or default bypass", async () => {
  119. const h = setup();
  120. h.modelSelectionService.getView.mockResolvedValue({
  121. revision: 2,
  122. providers: [],
  123. preferredSelection: undefined,
  124. });
  125. await expect(h.service.handleInboundMessage(inbound)).rejects.toThrow("Submission");
  126. expect(h.taskService.createTask).not.toHaveBeenCalled();
  127. expect(h.taskService.sendPrompt).not.toHaveBeenCalled();
  128. expect(h.requests).toHaveLength(0);
  129. expect((await h.repo.readState()).bots[actor.botId]).toMatchObject({
  130. mode: "draft",
  131. activeTaskId: null,
  132. });
  133. });
  134. it.each([true, false])(
  135. "replaces a deleted task once, preserving workspace scope (remote=%s)",
  136. async (remote) => {
  137. const h = setup("zh-CN", remote);
  138. await h.service.handleInboundMessage(inbound);
  139. expect(h.taskService.listDeletedTaskIds).toHaveBeenCalledWith(h.workspace);
  140. expect(h.taskService.resumeTask).not.toHaveBeenCalled();
  141. expect(h.taskService.createTask).toHaveBeenCalledExactlyOnceWith(
  142. expect.objectContaining(h.workspace),
  143. );
  144. expect(h.taskService.sendPrompt).toHaveBeenCalledExactlyOnceWith(
  145. expect.objectContaining({ taskId: "task-1", content: inbound.text }),
  146. );
  147. expect((await h.repo.readState()).bots[actor.botId]).toMatchObject({
  148. activeTaskId: "task-1",
  149. mode: "task",
  150. ...h.workspace,
  151. });
  152. expect(
  153. (await h.repo.readState()).bots[actor.botId]?.pendingPermissionOptions,
  154. ).toBeUndefined();
  155. expect((await h.repo.readState()).bots[actor.botId]?.pendingElicitation).toBeUndefined();
  156. expect(h.taskService.respondElicitation).not.toHaveBeenCalled();
  157. expect(h.requests).toHaveLength(1);
  158. expect(h.requests[0]).toContain("原任务已删除");
  159. expect(h.requests[0]).toContain("不会继承原任务的对话上下文");
  160. expect(h.broadcastService.send).toHaveBeenCalledWith(
  161. expect.objectContaining({
  162. channel: "bots:task",
  163. payload: expect.objectContaining({ event: "created", taskId: "task-1", ...h.workspace }),
  164. }),
  165. );
  166. // 后续消息可能因当前运行而被拒绝,但不得重复创建任务或重复发送切换通知。
  167. await h.service.handleInboundMessage({ ...inbound, text: "第二条消息" });
  168. expect(h.taskService.createTask).toHaveBeenCalledTimes(1);
  169. expect(h.requests).toHaveLength(1);
  170. },
  171. );
  172. it("does not infer deletion from a missing filtered task list (including archived/pinned tasks)", async () => {
  173. const h = setup();
  174. vi.mocked(h.taskService.listDeletedTaskIds).mockResolvedValue([]);
  175. delete (await h.repo.readState()).bots[actor.botId]!.pendingElicitation;
  176. await h.service.handleInboundMessage(inbound);
  177. expect(h.taskService.createTask).not.toHaveBeenCalled();
  178. expect(h.taskService.resumeTask).toHaveBeenCalledWith(
  179. expect.objectContaining({ taskId: "deleted-task" }),
  180. );
  181. expect(h.requests).toHaveLength(0);
  182. });
  183. it("does not replace or dispatch when the authoritative deletion read fails", async () => {
  184. const h = setup();
  185. vi.mocked(h.taskService.listDeletedTaskIds).mockRejectedValue(new Error("index unavailable"));
  186. await expect(h.service.handleInboundMessage(inbound)).rejects.toThrow("index unavailable");
  187. expect(h.taskService.createTask).not.toHaveBeenCalled();
  188. expect(h.taskService.sendPrompt).not.toHaveBeenCalled();
  189. expect((await h.repo.readState()).bots[actor.botId]?.activeTaskId).toBe("deleted-task");
  190. });
  191. it("keeps draft state without a success notice if replacement creation fails", async () => {
  192. const h = setup();
  193. vi.mocked(h.taskService.createTask).mockRejectedValue(new Error("create failed"));
  194. await expect(h.service.handleInboundMessage(inbound)).rejects.toThrow("create failed");
  195. expect((await h.repo.readState()).bots[actor.botId]?.activeTaskId).toBeNull();
  196. expect(h.requests).toHaveLength(0);
  197. expect(h.taskService.sendPrompt).not.toHaveBeenCalled();
  198. });
  199. it("sends an English transition notice before dispatching the prompt", async () => {
  200. const h = setup("en-US");
  201. let noticesAtDispatch = 0;
  202. vi.mocked(h.taskService.sendPrompt).mockImplementation(async () => {
  203. noticesAtDispatch = h.requests.length;
  204. });
  205. await h.service.handleInboundMessage(inbound);
  206. expect(h.taskService.sendPrompt).toHaveBeenCalledTimes(1);
  207. expect(noticesAtDispatch).toBe(1);
  208. expect(h.requests[0]).toContain("previous task was deleted");
  209. expect(h.requests[0]).toContain("conversation history");
  210. });
  211. it("does not replay the prompt when the transition notice cannot be delivered", async () => {
  212. const h = setup();
  213. h.fetch.mockResolvedValue(new Response("unavailable", { status: 400 }));
  214. const callback = {
  215. botId: actor.botId,
  216. userId: actor.providerUserId,
  217. text: inbound.text,
  218. messageId: "redelivered-message",
  219. webhookSecret: "secret",
  220. };
  221. await expect(
  222. h.service.handleProviderCallbackResponse("webhook", callback),
  223. ).resolves.toMatchObject({ ok: true });
  224. await expect(
  225. h.service.handleProviderCallbackResponse("webhook", callback),
  226. ).resolves.toMatchObject({ ok: true });
  227. expect(h.fetch).toHaveBeenCalledTimes(1);
  228. expect(h.taskService.createTask).toHaveBeenCalledTimes(1);
  229. expect(h.taskService.sendPrompt).toHaveBeenCalledTimes(1);
  230. expect((await h.repo.readState()).bots[actor.botId]?.activeTaskId).toBe("task-1");
  231. });
  232. });