channelReply.test.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. import { createGroupResultDelivery } from "#src/bots/groupResultDelivery.js";
  2. import { describe, expect, it, vi } from "vitest";
  3. import { replyToBotChannel } from "../src/bots/channelReply.js";
  4. import type { BotsStateFile, BotsConfigFile, BotGroupDelivery } from "@zcode/shared";
  5. const mention = {
  6. type: "channelMention" as const,
  7. refId: "m1",
  8. name: "Ryan Bot",
  9. channel: "feishu" as const,
  10. targetId: "ou_target",
  11. idType: "open_id" as const,
  12. entityType: "unknown" as const,
  13. };
  14. function fixture() {
  15. const source = {
  16. authorizationId: "auth",
  17. botId: "bot",
  18. appId: "app",
  19. provider: "feishu",
  20. chatId: "oc_group",
  21. senderId: "member",
  22. senderName: "Member",
  23. messageId: "om_input",
  24. contentParts: [mention],
  25. };
  26. const state = {
  27. version: 3,
  28. bots: {
  29. group: {
  30. botId: "bot",
  31. workspacePath: "/work",
  32. activeTaskId: "task",
  33. group: {
  34. enabled: true,
  35. ownerId: "owner",
  36. chatId: "oc_group",
  37. authorizationId: "auth",
  38. inputs: { input: { taskId: "task", admission: "accepted", source } },
  39. deliveries: {},
  40. },
  41. },
  42. },
  43. } as unknown as BotsStateFile;
  44. const config = {
  45. bots: [
  46. { id: "bot", enabled: true, provider: "feishu", providerUserId: "owner", feishuAppId: "app" },
  47. ],
  48. } as BotsConfigFile;
  49. const deliver = vi.fn(async (_bot, _chat, _thread, result: BotGroupDelivery) => {
  50. state.bots.group!.group!.deliveries![result.id] ??= {
  51. ...result,
  52. status: "sent",
  53. providerMessageId: "om_sent",
  54. };
  55. });
  56. const deps = { readState: async () => state, readConfig: async () => config, deliver };
  57. const request = {
  58. taskId: "task",
  59. inputId: "input",
  60. toolCallId: "call",
  61. authorizationId: "auth",
  62. workspacePath: "/work",
  63. parts: [
  64. { type: "mention" as const, refId: "m1" },
  65. { type: "text" as const, text: " 请确认" },
  66. ],
  67. };
  68. return { state, config, deps, request };
  69. }
  70. describe("authorized native channel reply", () => {
  71. it.each([false, true])(
  72. "waits for active delivery/retry (%s), but never resends a recovered unknown",
  73. async (retrying) => {
  74. const f = fixture();
  75. const started = Promise.withResolvers<void>();
  76. const release = Promise.withResolvers<void>();
  77. const joined = Promise.withResolvers<void>();
  78. const records = f.state.bots.group!.group!.deliveries!;
  79. let attempts = 0;
  80. const send = vi.fn(async () => {
  81. if (retrying && attempts++ === 0)
  82. throw Object.assign(new Error("rate limited"), {
  83. deliveryRejected: true,
  84. retryAfterMs: 250,
  85. });
  86. started.resolve();
  87. await release.promise;
  88. return { providerMessageId: "om_sent" };
  89. });
  90. const owner = createGroupResultDelivery({
  91. read: async (id) => records[id],
  92. write: async (result) => {
  93. records[result.id] = result;
  94. },
  95. authorized: async () => true,
  96. send,
  97. delay: async () => {
  98. started.resolve();
  99. await release.promise;
  100. },
  101. });
  102. let calls = 0;
  103. const deps = {
  104. ...f.deps,
  105. deliver: async (
  106. _bot: unknown,
  107. _chat: string,
  108. _thread: string | undefined,
  109. result: BotGroupDelivery,
  110. ) => {
  111. const pending = owner(result);
  112. if (++calls === 2) joined.resolve();
  113. await pending;
  114. },
  115. };
  116. const first = replyToBotChannel(f.request, deps);
  117. await started.promise;
  118. const second = replyToBotChannel(f.request, deps);
  119. try {
  120. expect(
  121. await Promise.race([second.then(() => "settled"), joined.promise.then(() => "waiting")]),
  122. ).toBe("waiting");
  123. } finally {
  124. release.resolve();
  125. }
  126. expect(await first).toMatchObject({ status: "sent" });
  127. expect(await second).toEqual(await first);
  128. expect(send).toHaveBeenCalledTimes(retrying ? 2 : 1);
  129. const record = Object.values(records)[0]!;
  130. records[record.id] = { ...record, status: "unknown", providerMessageId: undefined };
  131. const restarted = createGroupResultDelivery({
  132. read: async (id) => records[id],
  133. write: async (result) => {
  134. records[result.id] = result;
  135. },
  136. authorized: async () => true,
  137. send,
  138. });
  139. expect(
  140. await replyToBotChannel(f.request, {
  141. ...deps,
  142. deliver: async (_bot, _chat, _thread, result) => restarted(result),
  143. }),
  144. ).toMatchObject({ status: "unknown" });
  145. expect(send).toHaveBeenCalledTimes(retrying ? 2 : 1);
  146. },
  147. );
  148. it("resolves a unique typed name and replays the receipt without a new lookup", async () => {
  149. const f = fixture();
  150. const listMembers = vi.fn(async () => ({ ou_alice: "Alice" }));
  151. const deps = { ...f.deps, listMembers };
  152. const request = { ...f.request, parts: [{ type: "mentionName" as const, name: " Alice " }] };
  153. const first = await replyToBotChannel(request, deps);
  154. expect(first.status).toBe("sent");
  155. expect(f.deps.deliver.mock.calls[0]?.[3].contentParts).toEqual([
  156. expect.objectContaining({ type: "channelMention", targetId: "ou_alice", name: "Alice" }),
  157. ]);
  158. listMembers.mockRejectedValue(new Error("unavailable"));
  159. expect(await replyToBotChannel(request, deps)).toEqual(first);
  160. expect(listMembers).toHaveBeenCalledTimes(1);
  161. expect(f.deps.deliver).toHaveBeenCalledTimes(1);
  162. await expect(
  163. replyToBotChannel({ ...request, parts: [{ type: "text", text: "changed" }] }, deps),
  164. ).rejects.toThrow("idempotency");
  165. });
  166. it("returns ambiguous candidates without delivery and accepts only a valid selected candidate", async () => {
  167. const f = fixture();
  168. const deps = { ...f.deps, listMembers: async () => ({ ou_a: "Alex", ou_b: "Alex" }) };
  169. const request = { ...f.request, parts: [{ type: "mentionName" as const, name: "Alex" }] };
  170. const result = await replyToBotChannel(request, deps);
  171. expect(result.status).toBe("needs_clarification");
  172. expect(f.deps.deliver).not.toHaveBeenCalled();
  173. if (result.status !== "needs_clarification") throw new Error("Expected clarification");
  174. expect(result.unresolved[0]?.candidates).toHaveLength(2);
  175. const candidateRef = result.unresolved[0]!.candidates[1]!.ref;
  176. expect(candidateRef).not.toContain("ou_b");
  177. // 用户在下一条输入选择候选,标识应跨输入保留,但不能跨授权。
  178. const group = f.state.bots.group!.group!;
  179. group.inputs!.followup = {
  180. ...structuredClone(group.inputs!.input!),
  181. source: { ...group.inputs!.input!.source, messageId: "om_choice", contentParts: [] },
  182. };
  183. const selected = await replyToBotChannel(
  184. {
  185. ...request,
  186. inputId: "followup",
  187. toolCallId: "selected",
  188. parts: [{ type: "mentionName", name: "Alex", candidateRef }],
  189. },
  190. deps,
  191. );
  192. expect(selected.status).toBe("sent");
  193. expect(f.deps.deliver.mock.calls[0]?.[3].contentParts?.[0]).toMatchObject({ targetId: "ou_b" });
  194. expect(
  195. (
  196. await replyToBotChannel(
  197. { ...request, parts: [{ type: "mentionName", name: "Alex", candidateRef: "invented" }] },
  198. deps,
  199. )
  200. ).status,
  201. ).toBe("needs_clarification");
  202. expect(f.deps.deliver).toHaveBeenCalledTimes(1);
  203. });
  204. it("resolves a known bot name from trusted task mentions", async () => {
  205. const f = fixture();
  206. await replyToBotChannel(
  207. { ...f.request, parts: [{ type: "mentionName", name: "Ryan Bot" }] },
  208. {
  209. ...f.deps,
  210. listMembers: async () => ({}),
  211. },
  212. );
  213. expect(f.deps.deliver.mock.calls[0]?.[3].contentParts?.[0]).toMatchObject({
  214. targetId: "ou_target",
  215. });
  216. });
  217. it("resolves names from an earlier task without authorizing its mention refs", async () => {
  218. const f = fixture();
  219. const group = f.state.bots.group!.group!;
  220. group.inputs!.old = {
  221. ...structuredClone(group.inputs!.input!),
  222. taskId: "previous-task",
  223. progress: { status: "stopped" },
  224. };
  225. group.inputs!.input!.source.contentParts = [{ type: "text", text: "Find ryan" }];
  226. expect(
  227. await replyToBotChannel(
  228. { ...f.request, parts: [{ type: "mentionName", name: "ryan" }] },
  229. { ...f.deps, listMembers: async () => ({}) },
  230. ),
  231. ).toMatchObject({ status: "sent" });
  232. expect(f.deps.deliver.mock.calls[0]?.[3].contentParts?.[0]).toMatchObject({
  233. targetId: "ou_target",
  234. name: "Ryan Bot",
  235. });
  236. await expect(
  237. replyToBotChannel({ ...f.request, toolCallId: "old-ref" }, f.deps),
  238. ).rejects.toThrow();
  239. });
  240. it.each(["authorizationId", "chatId", "appId", "botId", "provider"] as const)(
  241. "excludes historical names from a different %s",
  242. async (field) => {
  243. const f = fixture();
  244. const group = f.state.bots.group!.group!;
  245. group.inputs!.old = { ...structuredClone(group.inputs!.input!), taskId: "previous-task" };
  246. Object.assign(group.inputs!.old.source, { [field]: "different" });
  247. group.inputs!.input!.source.contentParts = [{ type: "text", text: "Find ryan" }];
  248. const result = await replyToBotChannel(
  249. { ...f.request, parts: [{ type: "mentionName", name: "ryan" }] },
  250. { ...f.deps, listMembers: async () => ({}) },
  251. );
  252. expect(result).toMatchObject({
  253. status: "needs_clarification",
  254. unresolved: [{ reason: "not_found", candidates: [] }],
  255. });
  256. expect(f.deps.deliver).not.toHaveBeenCalled();
  257. },
  258. );
  259. it("treats a directory user and trusted bot with the same name as ambiguous", async () => {
  260. const f = fixture();
  261. const result = await replyToBotChannel(
  262. { ...f.request, parts: [{ type: "mentionName", name: "ryan bot" }] },
  263. { ...f.deps, listMembers: async () => ({ ou_person: "Ryan Bot" }) },
  264. );
  265. expect(result.status).toBe("needs_clarification");
  266. if (result.status !== "needs_clarification") throw new Error("Expected ambiguity");
  267. expect(result.unresolved[0]?.candidates).toHaveLength(2);
  268. expect(f.deps.deliver).not.toHaveBeenCalled();
  269. });
  270. it("does not partially deliver mixed resolved and missing recipients", async () => {
  271. const f = fixture();
  272. expect(
  273. (
  274. await replyToBotChannel(
  275. {
  276. ...f.request,
  277. parts: [
  278. { type: "mention", refId: "m1" },
  279. { type: "mentionName", name: "Unknown" },
  280. ],
  281. },
  282. { ...f.deps, listMembers: async () => ({}) },
  283. )
  284. ).status,
  285. ).toBe("needs_clarification");
  286. expect(f.deps.deliver).not.toHaveBeenCalled();
  287. });
  288. it("bounds duplicate-name output and rejects a candidate from another credential scope", async () => {
  289. const f = fixture();
  290. const deps = {
  291. ...f.deps,
  292. listMembers: async () =>
  293. Object.fromEntries(Array.from({ length: 12 }, (_, i) => [`ou_member_${i}`, "Alex"])),
  294. };
  295. const request = { ...f.request, parts: [{ type: "mentionName" as const, name: "Alex" }] };
  296. const result = await replyToBotChannel(request, deps);
  297. if (result.status !== "needs_clarification") throw new Error("Expected ambiguity");
  298. expect(result.unresolved[0]?.candidates).toHaveLength(10);
  299. expect(result.unresolved[0]?.truncated).toBe(true);
  300. f.config.bots[0]!.credentialRef = "new-credential";
  301. const selected = await replyToBotChannel(
  302. {
  303. ...request,
  304. parts: [
  305. {
  306. type: "mentionName",
  307. name: "Alex",
  308. candidateRef: result.unresolved[0]!.candidates[0]!.ref,
  309. },
  310. ],
  311. },
  312. deps,
  313. );
  314. expect(selected).toMatchObject({
  315. status: "needs_clarification",
  316. unresolved: [expect.objectContaining({ reason: "selection_expired" })],
  317. });
  318. expect(f.deps.deliver).not.toHaveBeenCalled();
  319. });
  320. it("rejects binding changes during lookup even when the directory returns a unique match", async () => {
  321. const f = fixture();
  322. await expect(
  323. replyToBotChannel(
  324. { ...f.request, parts: [{ type: "mentionName", name: "Alice" }] },
  325. {
  326. ...f.deps,
  327. listMembers: async () => {
  328. f.config.bots[0]!.credentialRef = "changed";
  329. return { ou_alice: "Alice" };
  330. },
  331. },
  332. ),
  333. ).rejects.toThrow("authorization changed");
  334. expect(f.deps.deliver).not.toHaveBeenCalled();
  335. });
  336. it.each(["missing", "denied", "revoked"])("never sends for %s name lookup", async (kind) => {
  337. const f = fixture();
  338. const request = { ...f.request, parts: [{ type: "mentionName" as const, name: "Alice" }] };
  339. const deps = {
  340. ...f.deps,
  341. listMembers: async () => {
  342. if (kind === "denied") throw new Error("permission denied");
  343. if (kind === "revoked") f.state.bots.group!.group!.enabled = false;
  344. return kind === "missing" ? {} : { ou_alice: "Alice" };
  345. },
  346. };
  347. if (kind === "revoked") await expect(replyToBotChannel(request, deps)).rejects.toThrow();
  348. else expect((await replyToBotChannel(request, deps)).status).toBe("needs_clarification");
  349. expect(f.deps.deliver).not.toHaveBeenCalled();
  350. });
  351. it("uses trusted targets and returns the saved provider receipt", async () => {
  352. const { deps, request } = fixture();
  353. const result = await replyToBotChannel(request, deps);
  354. expect(result).toMatchObject({ status: "sent", providerMessageId: "om_sent" });
  355. expect(deps.deliver.mock.calls[0]?.[3]).toMatchObject({
  356. replyToMessageId: "om_input",
  357. contentParts: [mention, { type: "text", text: " 请确认" }],
  358. });
  359. expect(await replyToBotChannel(request, deps)).toEqual(result);
  360. await expect(
  361. replyToBotChannel({ ...request, parts: [{ type: "text", text: "different" }] }, deps),
  362. ).rejects.toThrow("idempotency");
  363. });
  364. it.each([undefined, "thread-1"])(
  365. "resolves desktop follow-up from task binding in %s",
  366. async (threadId) => {
  367. const { deps, request, state } = fixture();
  368. const group = state.bots.group!.group!;
  369. group.threadId = threadId;
  370. group.inputs!.input!.source.threadId = threadId;
  371. const { authorizationId: _authorizationId, ...followup } = request;
  372. const result = await replyToBotChannel({ ...followup, inputId: "desktop-input" }, deps);
  373. expect(result.status).toBe("sent");
  374. expect(deps.deliver.mock.calls[0]?.[2]).toBe(threadId);
  375. expect(deps.deliver.mock.calls[0]?.[3].contentParts?.[0]).toEqual(mention);
  376. },
  377. );
  378. it("reuses earlier native references while replying to the current input", async () => {
  379. const { deps, request, state } = fixture();
  380. const group = state.bots.group!.group!;
  381. group.inputs!.followup = {
  382. ...structuredClone(group.inputs!.input!),
  383. source: { ...group.inputs!.input!.source, messageId: "om_followup", contentParts: [] },
  384. };
  385. await replyToBotChannel({ ...request, inputId: "followup" }, deps);
  386. expect(deps.deliver.mock.calls[0]?.[3]).toMatchObject({
  387. replyToMessageId: "om_followup",
  388. contentParts: [mention, { type: "text", text: " 请确认" }],
  389. });
  390. });
  391. it("does not borrow targets from a different task even with a valid binding", async () => {
  392. const { deps, request, state } = fixture();
  393. const group = state.bots.group!.group!;
  394. group.inputs!.old = { ...structuredClone(group.inputs!.input!), taskId: "other-task" };
  395. group.inputs!.input!.source.contentParts = [];
  396. await expect(replyToBotChannel(request, deps)).rejects.toThrow("Unknown channel mention");
  397. expect(deps.deliver).not.toHaveBeenCalled();
  398. });
  399. it.each(["task", "thread", "oldAuthorization", "ambiguous", "identity"])(
  400. "rejects mismatched binding %s",
  401. async (kind) => {
  402. const { deps, request, state } = fixture();
  403. const group = state.bots.group!.group!;
  404. if (kind === "task") group.inputs!.input!.taskId = "other-task";
  405. if (kind === "thread") group.inputs!.input!.source.threadId = "other-thread";
  406. if (kind === "oldAuthorization") group.inputs!.input!.source.authorizationId = "old";
  407. if (kind === "ambiguous") state.bots.duplicate = structuredClone(state.bots.group!);
  408. if (kind === "identity") state.bots.group!.workspaceIdentity = "remote:other";
  409. await expect(
  410. replyToBotChannel({ ...request, inputId: "desktop-input" }, deps),
  411. ).rejects.toThrow();
  412. expect(deps.deliver).not.toHaveBeenCalled();
  413. },
  414. );
  415. it.each(["workspace", "app", "authorization", "unknownRef", "disabled", "stopped"])(
  416. "rejects %s without sending",
  417. async (kind) => {
  418. const { deps, request, state, config } = fixture();
  419. if (kind === "workspace") request.workspacePath = "/other";
  420. if (kind === "app") config.bots[0]!.feishuAppId = "other";
  421. if (kind === "authorization") request.authorizationId = "other";
  422. if (kind === "unknownRef") request.parts = [{ type: "mention", refId: "invented" }];
  423. if (kind === "stopped")
  424. state.bots.group!.group!.inputs!.input!.progress = { status: "stopped" };
  425. if (kind === "disabled") state.bots.group!.group!.enabled = false;
  426. await expect(replyToBotChannel(request, deps)).rejects.toThrow();
  427. expect(deps.deliver).not.toHaveBeenCalled();
  428. },
  429. );
  430. });