botsService.deletedTask.test.ts 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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: "ssh://host/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. repo: repo as never,
  70. zcodeTaskService: taskService,
  71. broadcastService,
  72. modelSelectionService,
  73. credentialService: f.createCredentialService({ "secret-1": "secret" }),
  74. settingService: f.createSettingService({
  75. locale,
  76. lastWorkspaceSession: [{ kind: remote ? "remote" : "local", ...workspace }],
  77. }),
  78. runStartupBackgroundTasks: false,
  79. warmCandidateCachesOnStartup: false,
  80. });
  81. services.push(service);
  82. return {
  83. service,
  84. repo,
  85. taskService,
  86. broadcastService,
  87. modelSelectionService,
  88. requests,
  89. fetch,
  90. workspace,
  91. };
  92. }
  93. const inbound = { botId: actor.botId, text: "E2E_BOT_DELETED_TASK 原消息", actor };
  94. describe("Bot deleted active task recovery", () => {
  95. it("replacement reuses the current Selection View and freezes the complete V4 first-send selection", async () => {
  96. const h = setup();
  97. const selection = {
  98. providerId: "account:bigmodel-team-coding-plan",
  99. modelId: "GLM-5.3",
  100. options: { reasoningLevel: "high" },
  101. };
  102. h.modelSelectionService.getView.mockResolvedValue({
  103. revision: 2,
  104. providers: [],
  105. preferredSelection: selection,
  106. });
  107. await h.service.handleInboundMessage(inbound);
  108. expect(h.taskService.createTask).toHaveBeenCalledWith(
  109. expect.objectContaining({ v4Create: true, modelSelection: selection }),
  110. );
  111. expect(h.taskService.sendPrompt).toHaveBeenCalledWith(
  112. expect.objectContaining({ modelSelection: selection, content: inbound.text }),
  113. );
  114. expect(h.taskService.getTaskModelSelection).not.toHaveBeenCalled();
  115. expect((await h.repo.readState()).bots[actor.botId]?.draftOptions).toBeUndefined();
  116. });
  117. it("replacement without an available Selection View stays draft without a success notice or default bypass", async () => {
  118. const h = setup();
  119. h.modelSelectionService.getView.mockResolvedValue({
  120. revision: 2,
  121. providers: [],
  122. preferredSelection: undefined,
  123. });
  124. await expect(h.service.handleInboundMessage(inbound)).rejects.toThrow("Submission");
  125. expect(h.taskService.createTask).not.toHaveBeenCalled();
  126. expect(h.taskService.sendPrompt).not.toHaveBeenCalled();
  127. expect(h.requests).toHaveLength(0);
  128. expect((await h.repo.readState()).bots[actor.botId]).toMatchObject({
  129. mode: "draft",
  130. activeTaskId: null,
  131. });
  132. });
  133. it.each([true, false])(
  134. "replaces a deleted task once, preserving workspace scope (remote=%s)",
  135. async (remote) => {
  136. const h = setup("zh-CN", remote);
  137. await h.service.handleInboundMessage(inbound);
  138. expect(h.taskService.listDeletedTaskIds).toHaveBeenCalledWith(h.workspace);
  139. expect(h.taskService.resumeTask).not.toHaveBeenCalled();
  140. expect(h.taskService.createTask).toHaveBeenCalledExactlyOnceWith(
  141. expect.objectContaining(h.workspace),
  142. );
  143. expect(h.taskService.sendPrompt).toHaveBeenCalledExactlyOnceWith(
  144. expect.objectContaining({ taskId: "task-1", content: inbound.text }),
  145. );
  146. expect((await h.repo.readState()).bots[actor.botId]).toMatchObject({
  147. activeTaskId: "task-1",
  148. mode: "task",
  149. ...h.workspace,
  150. });
  151. expect(
  152. (await h.repo.readState()).bots[actor.botId]?.pendingPermissionOptions,
  153. ).toBeUndefined();
  154. expect((await h.repo.readState()).bots[actor.botId]?.pendingElicitation).toBeUndefined();
  155. expect(h.taskService.respondElicitation).not.toHaveBeenCalled();
  156. expect(h.requests).toHaveLength(1);
  157. expect(h.requests[0]).toContain("原任务已删除");
  158. expect(h.requests[0]).toContain("不会继承原任务的对话上下文");
  159. expect(h.broadcastService.send).toHaveBeenCalledWith(
  160. expect.objectContaining({
  161. channel: "bots:task",
  162. payload: expect.objectContaining({ event: "created", taskId: "task-1", ...h.workspace }),
  163. }),
  164. );
  165. // 后续消息可能因当前运行而被拒绝,但不得重复创建任务或重复发送切换通知。
  166. await h.service.handleInboundMessage({ ...inbound, text: "第二条消息" });
  167. expect(h.taskService.createTask).toHaveBeenCalledTimes(1);
  168. expect(h.requests).toHaveLength(1);
  169. },
  170. );
  171. it("does not infer deletion from a missing filtered task list (including archived/pinned tasks)", async () => {
  172. const h = setup();
  173. vi.mocked(h.taskService.listDeletedTaskIds).mockResolvedValue([]);
  174. delete (await h.repo.readState()).bots[actor.botId]!.pendingElicitation;
  175. await h.service.handleInboundMessage(inbound);
  176. expect(h.taskService.createTask).not.toHaveBeenCalled();
  177. expect(h.taskService.resumeTask).toHaveBeenCalledWith(
  178. expect.objectContaining({ taskId: "deleted-task" }),
  179. );
  180. expect(h.requests).toHaveLength(0);
  181. });
  182. it("does not replace or dispatch when the authoritative deletion read fails", async () => {
  183. const h = setup();
  184. vi.mocked(h.taskService.listDeletedTaskIds).mockRejectedValue(new Error("index unavailable"));
  185. await expect(h.service.handleInboundMessage(inbound)).rejects.toThrow("index unavailable");
  186. expect(h.taskService.createTask).not.toHaveBeenCalled();
  187. expect(h.taskService.sendPrompt).not.toHaveBeenCalled();
  188. expect((await h.repo.readState()).bots[actor.botId]?.activeTaskId).toBe("deleted-task");
  189. });
  190. it("keeps draft state without a success notice if replacement creation fails", async () => {
  191. const h = setup();
  192. vi.mocked(h.taskService.createTask).mockRejectedValue(new Error("create failed"));
  193. await expect(h.service.handleInboundMessage(inbound)).rejects.toThrow("create failed");
  194. expect((await h.repo.readState()).bots[actor.botId]?.activeTaskId).toBeNull();
  195. expect(h.requests).toHaveLength(0);
  196. expect(h.taskService.sendPrompt).not.toHaveBeenCalled();
  197. });
  198. it("sends an English transition notice before dispatching the prompt", async () => {
  199. const h = setup("en-US");
  200. let noticesAtDispatch = 0;
  201. vi.mocked(h.taskService.sendPrompt).mockImplementation(async () => {
  202. noticesAtDispatch = h.requests.length;
  203. });
  204. await h.service.handleInboundMessage(inbound);
  205. expect(h.taskService.sendPrompt).toHaveBeenCalledTimes(1);
  206. expect(noticesAtDispatch).toBe(1);
  207. expect(h.requests[0]).toContain("previous task was deleted");
  208. expect(h.requests[0]).toContain("conversation history");
  209. });
  210. it("does not replay the prompt when the transition notice cannot be delivered", async () => {
  211. const h = setup();
  212. h.fetch.mockResolvedValue(new Response("unavailable", { status: 400 }));
  213. const callback = {
  214. botId: actor.botId,
  215. userId: actor.providerUserId,
  216. text: inbound.text,
  217. messageId: "redelivered-message",
  218. webhookSecret: "secret",
  219. };
  220. await expect(
  221. h.service.handleProviderCallbackResponse("webhook", callback),
  222. ).resolves.toMatchObject({ ok: true });
  223. await expect(
  224. h.service.handleProviderCallbackResponse("webhook", callback),
  225. ).resolves.toMatchObject({ ok: true });
  226. expect(h.fetch).toHaveBeenCalledTimes(1);
  227. expect(h.taskService.createTask).toHaveBeenCalledTimes(1);
  228. expect(h.taskService.sendPrompt).toHaveBeenCalledTimes(1);
  229. expect((await h.repo.readState()).bots[actor.botId]?.activeTaskId).toBe("task-1");
  230. });
  231. });